Compare commits

..
Author SHA1 Message Date
FredApps 7afe6b3b78 Merge origin/main into stack/s11: snaps keep main's Z sources through this branch's ranking
main's snap Z (#1511) records what each candidate lies on; collect_in, finish and finish_all
now carry those sources, so the hit chosen (or each Tab candidate) takes its object's Z:
gathered and intersection points from the gather, perpendiculars and tangents from the base
from their object, centers, deferred snaps and Nearest from their curve.
2026-12-03 05:15:35 +01:00
FredApps 17e0c81967 Center snap test: the viewport takes main's new fields (UCS, extra data) from their defaults 2026-12-03 05:01:04 +01:00
FredApps 01d5fae93f Merge pull request #2791 from salehnemari-max/ar-cadcraft-complete
ar: complete the Arabic catalog
2026-12-03 04:57:50 +01:00
FredApps c974978fce Merge pull request #3742 from Elvis33LE/ci/event-driven-cache-prune
ci: add event-driven cache-prune workflow
2026-12-03 04:56:07 +01:00
FredApps adca169651 Snap test from main: count every Endpoint through osnap_all_with_frozen, this branch's form of osnap_in 2026-12-03 10:50:34 +07:00
FredApps 77973774d0 Merge pull request #2405 from Dievartis/feature/command-suggestions-navigation
Add Shift+Arrow keyboard navigation for command suggestions
2026-12-03 04:49:09 +01:00
FredApps 27b3e8727d Merge pull request #1511 from aldozar/feat/snap-z
Object snaps give points their Z; LINE and POINT keep it (OSNAPZ)
2026-12-03 04:47:17 +01:00
FredApps 456926ff70 Merge pull request #1233 from midasmatterhorn/fix/properties-set-hatch-data-loss
engine: keep a hatch's custom .pat definition when properties.set changes it
2026-12-03 04:46:42 +01:00
FredApps 6295b6093f Merge pull request #1097 from codyvogt/fix/dynblock-visibility-grip-position
Dynamic blocks: a visibility or lookup grip carried by an action goes with it
2026-12-03 04:45:53 +01:00
FredApps 15b2085dfe Merge pull request #3171 from Torentje/feat/i18n-18-languages-parity
feat(i18n): register Dutch (nl) and European Portuguese (pt-PT) interface languages
2026-12-03 04:45:08 +01:00
FredApps f894be9117 Merge pull request #768 from SBaksa/ui-font-scripts
Interface fonts for the scripts of the names shown, on top of install_fonts (follow-up to #732)
2026-12-03 04:44:31 +01:00
FredApps 7843840bf0 Merge pull request #3741 from V1dalTheAbidal/pr/typed-window-rubber-band
Typed W, C and BOX draw their selection rectangle after the first corner (#3667)
2026-12-03 04:43:56 +01:00
FredApps d049a1cf7f Merge remote-tracking branch 'origin/main' into s11
# Conflicts:
#	crates/engine/src/cmd/layout/tests.rs
2026-12-03 10:43:41 +07:00
midasmatterhorn adac927d7d Merge main into fix/properties-set-hatch-data-loss 2026-12-03 04:35:48 +03:00
Elvis33LE d0747f768a ci: ensure trailing newline in cache-prune workflow 2026-12-02 21:48:42 +01:00
FredApps 9d2d4085d3 docs: include acadrust's MPL-2.0 text and the ACadSharp notice (#3759) (#3760) 2026-12-02 19:35:43 +01:00
DievartisandFredApps 8e329e42b9 Hatch dialog: create custom patterns and capture a repeating tile from a drawing (#3631)
* Hatch dialog: author custom PAT families and capture a repeating tile

* Handle Escape through CADCraft's window cancel intent in the hatch dialog

* Keep custom hatches in the pattern gallery and fix repeating tile capture

* Exercise keyboard input in the hatch gallery filter

* Use the active drawing’s hatch geometry and finish tile picks only after two corners

Resolve embedded pattern lines for the gallery, HATCH, HATCHEDIT and Properties. Retry an empty compact swatch at full-period scale. Add coverage for two reopened drawings with the same pattern name, incomplete picks and aligned sparse marks.

The earlier shallow-slope fix skips empty scanlines before clipping. Its regression counts 10,000 full-length marks in a 100 by 100 tile area.

* Expose hatch tile capture as a headless engine command and reuse it in the dialog

* Respect drawing visibility and localize hatch capture errors in the dialog

* Use the public UI state constructor in workspace tests and route hatch capture through CadApp::run

* Classify in-memory hatch tile capture as requiring no files

* Check the saved hatch by handle independently of entity iteration order

* Reserve the native user-defined hatch name across custom pattern entry points

* Add the Chinese command label for Capture hatch tile

chinese_menus_and_commands_are_fully_translated requires every command
label in the Simplified Chinese catalog. The Ubuntu gate failed with this
one key still in English.

---------

Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-12-02 16:18:48 +01:00
Elvis33LE ccdbb4207a ci(cache-prune): pin action SHA and allowlist same-repo main push 2026-12-02 14:22:08 +01:00
FredApps 46ebd11c11 fix(ci): give each plotter test its own device name (#3758)
The in-memory plotter store is shared by the whole test process. On
FreeBSD the tests run as threads of one process (cargo test), so the
three tests that each create a "Banner Printer" collide and the later
one fails with "plotter `Banner Printer` already exists". Each test now
creates a device with its own name.
2026-12-02 11:54:15 +01:00
FredApps e064c97a3d io: take the test-only acadrust from the storytold/acadrust fork (#3761)
* io: take the test-only acadrust from the storytold/acadrust fork at storytold/v0.6.6

* io: say the test-only acadrust matches craft-dwg's crates.io 0.6.6 until the craft-libs repin
2026-12-02 10:49:50 +01:00
Dievartis 931c2c799d Merge upstream main and integrate command suggestion navigation 2026-12-02 06:23:58 +01:00
V1dalTheAbidal f8578a4020 A typed W, C or BOX draws its rectangle to the snapped second corner (#3667)
At "Specify opposite corner" the running object snaps hold the cursor, and
a click gives the held point as the second corner. The rectangle was drawn
to the pointer itself, so it could differ from the selected area by the
snap distance, and a BOX could be drawn as a window while the click made a
crossing. A typed rectangle is now drawn to the cursor as the click uses
it. The implied window keeps the pointer, the point its click selects with.
2026-12-02 03:41:44 +02:00
Elvis33LE 7364032102 ci: add event-driven cache-prune workflow 2026-12-01 20:01:00 +01:00
The old Dutch Guy 2d52623dd6 feat(i18n): register Dutch (nl) and European Portuguese (pt-PT) interface languages 2026-12-01 19:09:04 +01:00
Saleh Hassan AlnemariandClaude Opus 5.5 76a1ece890 Merge main into ar-cadcraft-complete
The Arabic catalog conflicted at the end of ar.tsv, where both sides
added rows. Kept this branch's Arabic rows for Find and Replace, Edit
Text and Ctrl+Enter (main had them as English placeholders), and the 27
block-library rows main added. No key appears twice; the ui-egui i18n
tests pass, including the Stretch/Trim/Point test from #2898.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LMLkQogmJDoeteHcBk22Rj
2026-12-01 18:11:51 +03:00
Aldo ZarateandClaude Opus 5.5 04dc8bc2b0 Merge upstream/main into feat/snap-z
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 09:07:42 -06:00
V1dalTheAbidal e9fa62f141 Typed W, C and BOX draw their selection rectangle after the first corner (#3667)
The drawing area drew a selection rectangle only for the implied window a
click on empty space opens, so a W, C or BOX typed at "Select objects"
showed nothing between its two corners. The rectangle is now drawn from
the typed mode's first corner to the cursor with the same code: W as a
window, C as a crossing, BOX as a window to the right and a crossing to
the left, with the same area fill settings.
2026-12-01 16:38:47 +02:00
Codex f760e79be9 Run the layer-name font regression through normal frame hooks 2026-12-01 08:10:53 -05:00
Tanish Manku 7aaee29277 Tab snap tests: send Tab as the key press the command line reads now 2026-11-30 13:24:05 -07:00
Tanish Manku 334bcc3dc0 Tab snap tests: install the headless framework hook the app's frame now needs 2026-11-30 13:01:37 -07:00
Tanish Manku 3944964adf Merge main: gather_in takes main's skip handle and stays visible to tracking 2026-11-30 12:32:45 -07:00
Codex 1b40e9ca4e Merge main and isolate the name-font cache regression test 2026-11-30 00:08:17 -05:00
FredApps 566e137483 test(engine): preserve LINE elevations on close and undo 2026-11-30 03:49:17 +01:00
Cody Vogt 81ca3d0cc5 Merge remote-tracking branch 'upstream/main' into fix/dynblock-visibility-grip-position 2026-11-29 08:21:27 -06:00
Aldo ZarateandClaude Opus 5.5 71671af789 Merge upstream/main into feat/snap-z
Conflicts: typed Z ported onto main's UCS point parsing (parse_point3_in, parse_typed_point3; LISP points too), snap sources kept through main's ranked snap list, the new skip/dimension/proxy block paths and M2P/filter changes; both changelog rows kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 18:31:46 -06:00
Cody VogtandClaude Opus 5.5 2d9b9d1512 Dynamic blocks: a visibility or lookup grip carried by an action goes with it
A visibility or lookup parameter in a stretch, move, rotate, flip, scale or
polar stretch action's selection is carried along like the others, and
AutoCAD records where it went in the reference's value record (its state or
value, and its position). The record's position is now read
(`Value::Text::at`), carried by the actions with the state kept, written
back, and the grip is drawn there instead of where the dynamic block has it;
a state change leaves it where it is. A moved base point takes it back with
the other parameters.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 17:45:08 -06:00
Tanish Manku f8769d9650 Snap: rustfmt 2026-11-23 12:33:39 -07:00
Tanish Manku 0b2cfae274 Snap: Perpendicular to a ray needs the cursor on the ray
The 'cursor is over this object' distance measured a ray as a line both
ways, so a cursor behind the ray's start snapped to the foot on it. Measure
to the ray's own half; an xline stays two-sided.
2026-11-23 12:33:14 -07:00
Tanish Manku c647cb4eb9 Snap: a perpendicular from an arc's centre stays on the arc
From the centre every point of an arc is perpendicular. The snap passed the
base as the pick, so it fell back to a point of the arc's circle (10,0 for a
90-180 degree arc) outside the sweep. Take the point of the arc nearest the
cursor.
2026-11-23 12:31:37 -07:00
Tanish Manku 0314c8bf2a Snap: a twisted viewport offers its next snap when the best is off it
In a twisted viewport the model clip is the box round the turned viewport.
A perpendicular foot inside that box but off the viewport could win, and
view.hit then rejected it, so the click got no snap from the viewport while
Tab still offered a valid one. When the winner falls off the viewport, take
the best of the ranked others that is on it; the extra ranking runs only then.
2026-11-23 12:29:20 -07:00
Tanish Manku 71f4879f9c Tab: keep deferred snaps of different curves at one point
Two circles touching at the cursor each offer a deferred tangent at the same
provisional point. SnapHit::same took them for one snap and dropped the
second, so Tab could not pick the other circle. Compare the deferred curve.
2026-11-23 12:27:03 -07:00
Tanish Manku 472d3661ce CIRCLE 3P TAN: solve picks in line with the picked circle's centre
CIRCLE 3P 3,0 5,0 TAN on a unit circle at the origin found no circle: the
picks were collinear, so the only Newton start lay on y = 0 with every target
centre, and each step stayed on that line until the matrix went singular.
With collinear picks, also start from circles on both sides of their line.
2026-11-23 12:25:05 -07:00
Tanish Manku ca90388ff3 OSMODE test: build each DXF variant from the clean export
The second check added $OSMODE = 4133 to text that already had $OSMODE = 0,
so the file carried both. Build it from the clean export and assert one.
2026-11-23 12:23:04 -07:00
Tanish Manku ded4122de0 Merge main
#1673 (Tab cycles every candidate) is already carried by this stack: its
deferred_hits and tests were ported, and Tab's list comes from finish_all
ranked by Rank. Keep the stack's snap.rs, pointmod.rs and
measure_distance_snapping.rs; restore the first half of #1673's
osnap_all_ranks_every_candidate (snap points, then Nearest on each object).
2026-11-23 12:19:18 -07:00
Tanish Manku fe3b20a37a Merge main 2026-11-20 18:28:48 -07:00
Tanish Manku 9746b6999a Snap: rustfmt 2026-11-20 17:58:24 -07:00
Marco Arnulfo 0ca0af9026 Tab snap tests from #1408: moving away restarts the cycle, a click takes Tab's choice
Carried from #1408's crates/ui-egui/tests/tab_snap_cycling.rs onto the #2350
Tab list: moving_the_cursor_away_starts_the_cycle_over and
a_click_places_the_candidate_tab_chose, with their three-endpoint fixture.
2026-11-20 17:57:59 -07:00
Tanish Manku 6971715295 Tab: a base point that is not a number gives no candidates
With a finite cursor and aperture, a NaN or infinite base passed the Tab
list's guards and it still offered snaps, though the perpendicular and tangent
points from such a base mean nothing (a viewport already skips it).
osnap_all and snap_candidates now return none for it.
2026-11-20 17:51:37 -07:00
Tanish Manku 5bfba91aa8 Tab: every deferred tangent and perpendicular under the aperture
The Tab list took the one deferred snap a click would, so with a circle under
the cursor and no base point the deferred perpendicular could not be reached
after the deferred tangent, nor a second curve's deferred snap. The list now
has one deferred snap per curve and mode (ported from #1673), ranked after
the snap points; the click still takes the nearest. Makes
osnap_all_ranks_every_candidate (from #1673) pass.
2026-11-20 17:47:22 -07:00
Tanish Manku 080c96aa06 Tab: snaps seen through different viewports stay apart in the list
The Tab list dropped a snap as a repeat when another had the same mode and
paper point, so where two viewports overlap only one of their model points
could be picked, and DIST measures in the model units of the viewport picked.
A repeat now also has to come from the same viewport (and be deferred or not
alike), in osnap_all and in snap_candidates. Makes
overlapping_viewports_each_offer_their_model_point (from #1673) pass.
2026-11-20 17:45:11 -07:00
Oliver Hagmann a2f732118f Snap tests from #1673: Tab keeps each viewport's snap and every deferred snap
Carried from #1673 onto the #2350 Tab list: overlapping viewports each offer
their model point, the deferred tangent and perpendicular on one circle are
both offered, and a click across spaces. That last test is inverted from
#1673: with #2347's ranking a viewport Endpoint beats a paper-space Nearest
that scores closer, as a snap point beats Nearest within one space; Tab
starts at the click's snap and still reaches the Nearest.
2026-11-20 17:43:12 -07:00
Tanish Manku c2af11dfa7 Nearest: a curve crossing a viewport edge offers its visible point
The Nearest from #2350 took each object's closest point first and only then
dropped it when the viewport clipped it, so an ellipse or spline whose closest
point lay just outside the viewport offered nothing, though another of its
points was in the aperture and in view. Each segment's point is now checked
before the closest is chosen, as before #2350, in one helper the click snap
and the Tab list share.
2026-11-20 17:39:55 -07:00
Tanish Manku b1dcb46e08 Snap test: convert the test's own DWG in process, as main's DWG reader now asks 2026-11-20 17:37:04 -07:00
Tanish Manku c00bc59949 Snap tests: fill in the Insert clip and Viewport twist fields that main added after #2347 2026-11-20 17:28:59 -07:00
Tanish Manku 1b577e9eed Merge #3164: Snap: object snaps skip layers frozen in the active layout viewport
# Conflicts:
#	crates/engine/src/doc_state.rs
#	crates/engine/src/pointmod.rs
2026-11-20 17:27:48 -07:00
Tanish Manku 29bf02b6ce Merge #2103: CIRCLE: tangent snaps for the radius and for 3P points
# Conflicts:
#	crates/engine/src/snap.rs
2026-11-20 17:27:21 -07:00
Tanish Manku 1998da2643 Merge #2350: Tab cycles through every object snap under the aperture, not one per mode
# Conflicts:
#	crates/engine/src/snap.rs
#	crates/ui-egui/tests/it/main.rs
#	docs/gaps.md
#	docs/ui-parity.md
2026-11-20 17:26:58 -07:00
Tanish Manku 28ed9c58a7 Merge #2347: Object snap: Center found by moving onto a circle, arc, ellipse or polyline arc
# Conflicts:
#	crates/engine/src/snap.rs
#	docs/ui-parity.md
2026-11-20 17:23:44 -07:00
Tanish Manku a3560a1442 Merge #2825: PER and TAN snap from anywhere on the object 2026-11-20 17:23:11 -07:00
jayzed80 c40ff9603e Snap: skip VPLAYER-frozen layers in MSPACE (#3158) 2026-11-14 14:54:49 +00:00
midasmatterhorn 1cae514a0d engine: keep a hatch's line families when the pattern registry lost them 2026-11-14 17:04:17 +03:00
Saleh AlnemariandClaude Opus 5.5 2604fa0326 Merge main into ar-cadcraft-complete; apply review suggestions
Resolves the ar.tsv conflict with main: keeps the translated Find and
Replace rows and adds main's three new rows, translating "Ctrl+Enter to
apply" and "Edit Text".

Applies thegr8dooma's review suggestions:
- Clear Recent Files / Open Recent now name the list, not the files.
- DXF rows: masculine verb with "تنسيق DXF" to agree with "قبله".
- Mils, Limits, Save Anyway, the save-changes question, "doesn't look
  whole", "authoring elements", and the US Survey units (مسحي, so they
  no longer use the word for Area).
- "Save changes to block" uses the same question form for consistency.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NQSx2Pokw4gVqdEQCAzh8r
2026-11-12 02:19:15 +00:00
ZachAR3 595ccf2b06 Merge remote-tracking branch 'origin/main' into circle-tan-radius
# Conflicts:
#	crates/engine/src/cmd/draw.rs
#	docs/ui-parity.md
2026-11-09 17:07:40 +01:00
SBaksa e05636a26a UI fonts: look for an unfound script's font again when the font folders change, not every 30 s (review) 2026-11-07 08:41:38 +11:00
SBaksa 452cac8f0c UI fonts: retry unfound fonts after a delay, repaint when the loader ends (review) 2026-11-07 07:44:56 +11:00
SBaksa 7623ee2e91 Merge remote-tracking branch 'origin/main' into ui-font-scripts 2026-11-07 02:21:08 +11:00
SBaksa f036f6ce07 WIP row 80: font review fixes (uncompiled) 2026-11-07 02:21:04 +11:00
SBaksa d06393f33a Merge remote-tracking branch 'origin/main' into ui-font-scripts 2026-11-07 00:01:44 +11:00
austin62jakeandClaude Opus 5.5 8acdceeb61 fix(snap): a circle offers both perpendicular points from the base (CodeRabbit on #2825)
PER on a circle offered only the point nearest the base point, so with the
new object fallback a pick on the circle's far side jumped across it. Like
an arc, a circle now offers both antipodes, and the one nearer the cursor
wins. From the circle's centre, where every point is perpendicular, the
point under the cursor is taken.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 08:05:36 -06:00
austin62jakeandClaude Opus 5.5 4ce72c668a fix(snap): PER and TAN snap from anywhere on the object (#2800)
With a base point, a perpendicular or tangent snap was kept only when its
foot or tangent point lay within the aperture, so hovering elsewhere on the
line or circle found nothing, and a typed `per` said "No Perpendicular found
for specified point". As in AutoCAD, these snaps name an object, not a spot
on it: from anywhere over the object, the point jumps to the foot or the
tangent point.

They now also qualify when their object passes within the aperture, as a
fallback after every snap point within the aperture, so an endpoint,
midpoint or intersection under the cursor still wins. Of several objects,
the one nearest the cursor gives the snap; of several points on one (an
arc's antipodes, a circle's two tangents), the one nearest the cursor.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 07:39:52 -06:00
Saleh Hassan AlnemariandClaude Opus 5.5 27fb887f38 ar: complete the Arabic catalog (93 missing rows, Find and Replace dialog)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NQSx2MfhTCZcmeLrffc2ko
2026-11-04 20:45:46 +03:00
Aldo ZarateandClaude Opus 5.5 906395b4d2 Merge upstream/main into feat/snap-z
cmd.rs keeps main's new image module and this branch's crate-visible inquiry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 18:23:43 -06:00
SBaksa 4a3243e70a Merge remote-tracking branch 'origin/main' into ui-font-scripts 2026-11-03 19:59:07 +11:00
SBaksa a41ab8e249 Merge remote-tracking branch 'origin/main' into ui-font-scripts
# Conflicts:
#	docs/parity-checklist.md
2026-11-03 19:57:52 +11:00
Aldo ZarateandClaude Opus 5.5 b10856b14e Merge upstream/main into feat/snap-z
Session keeps LASTPOINT's Z and main's AREA, PERIMETER and DISTANCE; LASTPOINT
still reports its Z.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 15:48:05 -06:00
midasmatterhorn 687e30afa2 engine: keep a hatch's custom .pat definition when properties.set changes it 2026-11-01 05:34:05 +03:00
Aldo ZarateandClaude Opus 5.5 629d56689f Snaps inside block references and on ellipses take their Z
A snap on an object inside a block reference took the reference's
insertion Z. Each snap now remembers the object in the block it came
from and how the references on the way place it (insertion Z, Z scale,
block base), and takes that object's Z there. A reference in a tilted
plane keeps its own Z. Ellipses give their centre's Z.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 18:52:09 -06:00
SBaksa a6665d4040 Merge remote-tracking branch 'origin/main' into ui-font-scripts 2026-11-01 10:25:32 +11:00
SBaksa d93c513d2a Parity checklist: regenerate after interface fonts merge 2026-11-01 09:13:41 +11:00
SBaksa 170ebd3ee4 Merge main into interface script fonts
Keep per-script name fallbacks and cached language fonts alongside the new Vietnamese interface support. Check that its primary face retains diacritic coverage when installing name scripts.
2026-11-01 09:01:55 +11:00
SBaksa d61ad720d7 Parity checklist: regenerated after merging main 2026-10-30 13:52:38 +11:00
SBaksa df3b0a865c Merge remote-tracking branch 'origin/main' into ui-font-scripts
# Conflicts:
#	docs/parity-checklist.md
2026-10-30 13:49:27 +11:00
Aldo Zarate eb719cd766 Merge remote-tracking branch 'upstream/main' into feat/snap-z
# Conflicts:
#	docs/ui-parity.md
2026-10-29 19:26:00 -06:00
Aldo ZarateandClaude Opus 5.5 3523324084 Name the commands that read a typed Z in ui-parity
LINE and POINT read a typed Z as well as 3DPOLY now, and a point picked
with an object snap carries the Z of the object it snapped to.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 10:51:01 -06:00
Aldo ZarateandClaude Opus 5.5 fc99200d73 Take a snapped point's Z from the object it snapped to
The Z of a snapped point came from a fresh pick at the snapped XY, so a
snap whose point lies off the object missed it: CEN of a circle at
z = 5, picked near its center, gave ELEVATION instead of 5. With two
objects under an intersection, the pick returned whichever was on top.

A snap hit now records the entity its candidate came from, and the
point takes that entity's Z at the snapped point. An intersection takes
the first of its two objects (in drawing order). Where a snap has no
source, the pick at the point is still used.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 10:51:01 -06:00
Aldo ZarateandClaude Opus 5.5 bbfcd27d6c Keep the next point's Z after a deferred LINE start
A LINE started with a deferred tangent or perpendicular drew its first
segment flat: typing `10,10,5` after `tan` on a circle ended the line at
z = 0, while the same point typed after a plain start kept z = 5. The
deferred start still lies on the curve at z = 0, but the point that
resolves it now keeps its typed or snapped Z, and the next segment
starts from there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 10:48:36 -06:00
Aldo Zarate a3243c96be Merge remote-tracking branch 'upstream/main' into feat/snap-z 2026-10-29 10:47:17 -06:00
Francesco BVandClaude Opus 5.5 55ec024e31 Object snap: the center from the curve ranks behind snap points
A center found from its curve was scored by the cursor's distance to the
curve, so it beat the Midpoint or Quadrant of the same curve under the
cursor (those lie on the curve), and they could only be picked with Tab.
Now finish() tries the curve centers only when no snap point is in the
aperture, as in AutoCAD: Endpoint, Midpoint, Quadrant and Intersection
under the cursor win, the center shows elsewhere on the curve.

Hits from layout viewports are compared with paper-space ones by the same
rank (tier, then the score scaled into paper units), so a center keeps
its curve distance there instead of being rescored by the distance to the
center point. The 2,000-item work limit counts circles, arcs and ellipses
only, so straight segments gathered before them can't hide them.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-29 08:52:22 +01:00
Dievartis d23c4726de Fix autocomplete suggestion execution and add keyboard tests 2026-10-29 08:45:01 +01:00
Dievartis f60b174711 Fix command suggestion navigation review findings 2026-10-29 07:55:39 +01:00
Dievartis 4e58f46423 Fix keyboard navigation for command suggestions 2026-10-28 15:01:17 +01:00
Dievartis 5daebac3b5 Add Shift+Arrow navigation for command suggestions 2026-10-28 14:05:05 +01:00
SBaksa ea87dafb99 Parity checklist: regenerated after merging main 2026-10-28 19:29:23 +11:00
SBaksa 53b8a64871 Interface fonts: rescan names after an in-place edit, keep one language's fonts, read the CJK font for Hangul only when a name needs it
doc_mut now bumps the drawing's revision: a drawing nothing else holds is edited in place, so the
name-script cache (keyed by the drawing pointer) missed the edit. The language-font cache keeps the
last language only, so trying several interface languages doesn't hold a copy of the large font
files for each. cjk_covers_hangul reads the whole CJK collection the first time; it is now asked
only when a name needs Hangul.
2026-10-28 18:18:05 +11:00
Francesco BVandClaude Opus 5.5 64cb95d8ec Tab cycles through every object snap under the aperture, not one per mode (gaps U4)
Tab at a point prompt offered only the closest snap of each running mode,
so of several line ends under the aperture only one was reachable. The
candidate gathering is split out of osnap_in_with_prims (collect_in) and
the new snap::osnap_all keeps every candidate: each mode's points of every
object nearby, the intersections, perpendicular and tangent points from
the base, the deferred snap and the nearest point of each object, in
layout viewports too, ranked with the click snap's score (Nearest and
deferred last), without repeats and capped at 256. finish and finish_all
share base_snaps and nearest_points. pointmod::snap_candidates puts the
click snap first, then osnap_all's list.

Tests: every endpoint under the aperture is offered; 1,200 endpoints and
their crossings give at most 257 finite, unrepeated candidates; NaN or
infinite cursors, base points and apertures, zero or negative apertures,
OSMODE 0 and the F3 bit give none; with the real pointer Tab visits three
line ends and comes back round.

gaps: U4 removed. ui-parity: Tab row.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-27 19:52:55 +01:00
Francesco BVandClaude Opus 5.5 4a0063f5f6 Object snap: Center found by moving onto a circle, arc, ellipse or polyline arc
With the default running snaps (OSMODE 4133: END, CEN, INT, EXT) moving the
cursor onto a circle, an arc or the middle of a polyline arc found nothing:
Center only snapped with the cursor on the center itself. As in AutoCAD,
the cursor on a circle, arc, ellipse or polyline arc (also inside block
references) now finds its center (snap::curve_centers), scored by how near
the curve is so a nearer endpoint or intersection still wins; Tab cycling
offers it too.

Regression tests open DXF (with $OSMODE 0, which never changes the
profile's running snaps) and DWG files and snap on lines, intersections,
circles, arcs and polylines.

ui-parity: Center row.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-27 19:52:26 +01:00
SBaksa cf9a63c92f Merge remote-tracking branch 'origin/main' into ui-font-scripts-local 2026-10-27 17:53:58 +11:00
SBaksa d8c2c4cb4c Merge remote-tracking branch 'fork/ui-font-scripts' into ui-font-scripts-local
# Conflicts:
#	crates/ui-egui/src/lib.rs
#	crates/ui-egui/src/theme.rs
2026-10-27 17:53:57 +11:00
SBaksa 939fec385c Interface fonts: read a face's bytes through egui 0.37's shared font data 2026-10-27 16:54:23 +11:00
Claude 36c14239cc Interface fonts: read the primary face's bytes through egui's shared font data 2026-10-27 01:51:12 +00:00
Aldo Zarate 7eaf0c3104 Merge remote-tracking branch 'upstream/main' into feat/snap-z
# Conflicts:
#	crates/engine/src/cmd/draw.rs
#	crates/engine/src/cmd/draw2.rs
#	crates/engine/src/lib.rs
2026-10-26 19:40:52 -06:00
Claude 77bc4dba9e Merge remote-tracking branch 'upstream/main' into ui-font-scripts
# Conflicts:
#	crates/ui-egui/src/lib.rs
#	crates/ui-egui/src/theme.rs
2026-10-27 01:09:19 +00:00
SBaksa f2c849273c Merge remote-tracking branch 'origin/main' into ui-font-scripts-local
# Conflicts:
#	crates/ui-egui/src/lib.rs
#	crates/ui-egui/src/theme.rs
2026-10-27 11:32:45 +11:00
ZachAR3 f4f0702d08 CIRCLE: a tangent circle never lies on the picked circle (#1512)
A radius picked with TAN around the picked circle's own center, or a 3P
circle tangent twice to one circle through a point on it, would only
reproduce that circle; both now report that no such circle exists.
2026-10-25 03:08:29 +01:00
ZachAR3 98401d6de2 CIRCLE: a 3P circle takes the tangent solution that touches the arc (#1512)
The arc check ran on the solver's best circle only, so when that one
touched the arc's circle off the sweep, a valid circle that touches the
arc was reported as nonexistent. The Tan, Tan, Tan solver now takes a
filter (ttt_where), and 3P skips off-arc candidates before choosing.
2026-10-25 02:47:57 +01:00
ZachAR3 97fbaf7da4 CIRCLE: keep ellipse and spline tangents, and touch an arc within its sweep (#1512)
At CIRCLE's deferred prompts only tangents to circles and arcs are
deferred; ellipses and splines keep the ordinary tangent from the base,
as before. A 3P circle solved for an arc's circle must touch the arc
itself: a circle that touches the arc's circle off the sweep is
refused with "Circle does not exist."
2026-10-25 02:14:02 +01:00
ZachAR3 90a239b410 CIRCLE: tangent snaps for the radius and for 3P points (fixes #1512)
At CIRCLE's radius and diameter prompts a TAN pick on a circle or arc
used the tangent point as seen from the center, which gives the wrong
radius, and the 3P points took a tangent as a plain point. These prompts
now take the tangent as deferred and CIRCLE resolves it:

- Radius or diameter: the circle around the center that touches the
  curve, on the side it was picked.
- 3P: the circle through the plain points that touches every curve
  picked with TAN, solved by the Tan, Tan, Tan solver (a plain point is
  a circle of radius zero). Three tangent picks give Tan, Tan, Tan.
  Points with no such circle report "Circle does not exist." and ask
  for the last point again.

A perpendicular from the base is still resolved from it, so PER keeps
giving a circle tangent to a line. Only prompts that ask for deferred
snaps change: LINE's have no base.
2026-10-25 00:22:55 +02:00
Aldo ZarateandClaude Opus 5.5 26fe7656af A point from a LISP expression keeps its Z at point prompts
A LISP expression answering a point prompt passed only X and Y on, so `(list 1 2 7)` at LINE
gave a point at z = 0. It now keeps the third number as the point's Z, as a typed `x,y,z` does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 07:20:43 -06:00
Aldo ZarateandClaude Opus 5.5 0056d148fe Merge upstream/main into feat/snap-z
Keeps main's MEASUREINIT with the 3D LASTPOINT, and both changelog rows; the snap Z test moves
into tests/it (one test binary per crate, #1989).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 00:06:13 -06:00
SBaksa ca87d3acd1 Interface fonts: reuse the language's fonts when a name's script changes
install_fonts_for keeps the fonts read for each interface language
(cached_language_fonts; a clone shares their Arcs), so installing again
for a name's script, or when its face arrives, no longer reads the UI and
CJK font files on the UI thread again.
2026-10-21 03:42:02 +11:00
SBaksa cc50a8c3c5 Interface fonts for the scripts of the names shown, on top of install_fonts
Rebuilt on main's theme::install_fonts (#861, #513), which loads CJK faces
for every interface language and Korean or Arabic for those interfaces.
Names the interface shows (drawing titles and their layers, layouts and
blocks) can still need a script the language's fonts don't cover: a
Korean layer name in an English interface, a Thai, Devanagari, Arabic or
Hebrew drawing name.

install_fonts_for(ctx, language, names) adds a face for each such script,
found the way drawing text finds one (ttf::fallback_for). Faces are looked
for off the UI thread and kept for the process; fonts_generation() changes
when they're ready and the app installs again. The app scans the names
again only when a drawing changes, opens or closes. install_fonts keeps
its behaviour (no names).
2026-10-20 17:18:45 +11:00
SBaksa 1811abc66b Merge remote-tracking branch 'origin/main' into ui-font-scripts-local
# Conflicts:
#	contributors/people.toml
#	crates/ui-egui/src/lib.rs
#	crates/ui-egui/src/theme.rs
2026-10-20 15:57:15 +11:00
Aldo ZarateandClaude Opus 5.5 5b26e817d8 A one-off snap under M2P gives its point the snapped Z
A snap typed for an M2P point (M2P, NOD, then the point) snapped the X and Y but kept the earlier
Z, so the midpoint lay at the wrong level. It now takes the Z of what it snapped to, as a snapped
pick does (OSNAPZ-aware). The Z a point modifier gives is also dropped once the point is used,
so the next plain point starts at z = 0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 17:43:03 -06:00
Aldo ZarateandClaude Opus 5.5 15b99d94ba M2P is midway in Z too
The midpoint between two snapped points kept the second point's Z. The M2P frame now keeps the
first point's Z and gives the midpoint the average of both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 17:25:44 -06:00
Aldo ZarateandClaude Opus 5.5 50a7e7a3da Merge upstream/main into feat/snap-z
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 16:29:58 -06:00
Aldo ZarateandClaude Opus 5.5 324e3f4e97 Merge upstream/main into feat/snap-z
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 01:04:12 -06:00
Aldo ZarateandClaude Opus 5.5 d28ba1ce33 Object snaps give points their Z; LINE and POINT keep it (OSNAPZ)
Points reach commands in 2D, so a line drawn between a survey point and
a contour lay at z = 0 whatever their levels. An object snap now gives
the point the Z of what it snapped to (the object a pick finds there, as
ID reads it), through Session::point_z, as AutoCAD does with OSNAPZ 0;
OSNAPZ 1 uses the current elevation. A point picked through a layout
viewport, or without a snap, stays at z = 0.

LINE and POINT build their points with point_z, so they keep a typed Z
as well as a snapped one (3DPOLY already did).

Stacked on #1431 (Session::point_z) and #1509 (z_at).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 08:15:24 -06:00
Aldo Zarate f6124ce296 Merge branch 'feat/inquiry-z' into feat/snap-z 2026-10-17 08:08:39 -06:00
Aldo ZarateandClaude Opus 5.5 f197952a9c ID, DIST and LIST report Z
ID always printed Z = 0, DIST's Delta Z and angle from the XY plane were
0, and LIST printed Z = 0 for lines, circles, arcs and polyline vertices,
though the drawing kept every Z: a topographic drawing's levels could not
be read in CADCraft.

Points reach these commands in 2D, so the Z is that of what is drawn at
the point, as AutoCAD reports a snapped point's: the object a pick finds
there (a point, a 3D line or 3D polyline interpolated, a polyline's
elevation, down Z for a mirrored one, a circle, arc, text, block or the
plane of a 3D face), else the current elevation (ELEVATION). A Z given
with a JSON point wins. DIST gives the 3D distance, Delta Z and the angle
from the XY plane; LIST the Z of lines, circles, arcs and text, a line's
3D length and deltas, and a polyline's elevation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 07:54:52 -06:00
Gert Pellin fbee9d6f5e Docs: typed points keep their Z, and so do 3DPOLY's typed vertices (#1409, #1410) 2026-10-16 10:36:57 +02:00
Gert Pellin 246f13b5a7 Command line: a typed point keeps its Z, and 3DPOLY draws with it (#1409, #1410)
parse_point_with parsed the third number of x,y,z and dropped it, so no
typed Z reached a command, and the interactive 3DPOLY lifted every
point to z = 0.

parse_point3_with keeps Z (absolute x,y,z; relative @dx,dy,dz adds to
the last point's Z, @dx,dy keeps it, as in AutoCAD); parse_point_with
keeps its Vec2 signature for its callers. The session gives commands
the Z of the point being entered (Session::point_z, 0 for a pick) and
remembers LASTPOINT's Z. Poly3dM stores Vec3, so typed vertices keep
their Z and a vertex straight above the last one is no longer dropped
as a repeat.
2026-10-16 10:29:58 +02:00
SBaksa 17b5b06a78 Interface fonts for every script a shown name needs, loaded off the UI thread
Builds on #732. The interface loaded one CJK font, read on the UI thread
whenever a drawing name needed it and read again each time a drawing
needing it opened after none did; Korean names and names elsewhere (layers,
layouts, blocks) still showed boxes.

install_fonts now takes the scripts interface text needs (Chinese/Japanese,
Hangul, Thai, Devanagari, Arabic, Hebrew), from the interface language and
the names of drawings, layers, layouts and blocks; the names are scanned
again only when a drawing changes, opens or closes. Chinese prefers
cjk_font() as before; other scripts, and Chinese without it, take the
installed font drawing text would use (ttf::fallback_for). Faces are found
off the UI thread and kept for the process, so a script shown again never
re-reads a file, and egui shares the cached font data instead of a copy per
install. Scripts the UI font already has load nothing.
2026-10-12 22:50:58 +11:00
NetterSilver 876f6ccef9 Add my contributor entry 2026-10-12 10:45:22 +02:00
NetterSilver 9ae49fe1df Load the CJK font while an open drawing's name needs it (#658)
The CJK interface font was only loaded for the Chinese interface, so a
drawing named in Chinese, Japanese or Korean showed boxes in its tab and
title with any other interface language. The font is now also loaded
while an open drawing's title has CJK characters, and dropped again when
none does.
2026-10-12 10:37:59 +02:00
76 changed files with 5675 additions and 485 deletions
+34
View File
@@ -0,0 +1,34 @@
name: Cache prune
# Keeps one rolling gate entry on main, so the repository stays within its 10 GB Actions cache
# budget, where GitHub evicts entries a run still needs. Each main CI attempt's `cache warm` leg
# saves a new rolling entry; this deletes the entry it replaced once the attempt ends. It runs once
# after every attempt, re-runs of failed jobs and canceled runs included (craft-common-actions
# actions/cache-prune).
on:
workflow_run:
workflows: [CI]
types: [completed]
branches: [main]
permissions:
contents: read
jobs:
cache-prune:
name: cache prune
# A fork's pull request from a branch named main also matches `branches`.
if: github.event.workflow_run.event == 'push' && github.event.workflow_run.head_branch == 'main' && github.event.workflow_run.head_repository.full_name == github.repository
timeout-minutes: 10
runs-on: ubuntu-24.04
permissions:
actions: write
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
# A failed pass warns; the next run's prune deletes what it missed.
- name: Prune replaced cache entries
uses: storytold/craft-common-actions/actions/cache-prune@b2726eb1defb6eccdfad920cc6988e1e3ec1c3c9 # main
continue-on-error: true
+3 -1
View File
@@ -31,6 +31,8 @@ Generated-in-code assets are original and have no file to list:
|---|---|---|---|---|
| `crates/ui-egui/src/i18n/zh_shared.tsv` | @V1dalTheAbidal | [craft-i18n #444](https://github.com/storytold/craft-i18n/pull/444), [pinned Simplified Chinese CADCraft catalog](https://github.com/storytold/craft-i18n/blob/9fa32aecf2759cd61bb216a958df68da619798f3/locales/zh-hans/cadcraft.tsv#L201) | MIT OR Apache-2.0 | Exact generated one-row projection for offline builds; AI-assisted, not native-speaker reviewed. |
| `licenses/jpeg-encoder-0.6.1/` | jpeg-encoder contributors and Independent JPEG Group | [jpeg-encoder 0.6.1](https://crates.io/crates/jpeg-encoder/0.6.1) | (MIT OR Apache-2.0) AND IJG | Dependency license and SIMD notices; source hashes in SOURCE.json. |
| `licenses/dwg/acadrust-MPL-2.0.txt` | acadrust contributors | [acadrust 0.6.6](https://crates.io/crates/acadrust/0.6.6), [hakanaktt/acadrust](https://github.com/hakanaktt/acadrust), copied from [craft-libs 8fa4db64 licenses/dwg](https://github.com/storytold/craft-libs/tree/8fa4db64a9bb943520259ea95331a303ba788f21/licenses/dwg) | MPL-2.0 | DWG read/write dependency, used unmodified through craft-dwg. Full licence text is also in NOTICE. |
| `licenses/dwg/acadrust-THIRD_PARTY_NOTICES.md` | Albert Domenech (ACadSharp) and acadrust contributors | [ACadSharp](https://github.com/DomCR/ACadSharp), via [acadrust 0.6.6 third-party notices](https://github.com/hakanaktt/acadrust/blob/v0.6.6/THIRD_PARTY_NOTICES.md), copied from [craft-libs 8fa4db64 licenses/dwg](https://github.com/storytold/craft-libs/tree/8fa4db64a9bb943520259ea95331a303ba788f21/licenses/dwg) | MIT (ACadSharp, via acadrust) | Upstream notice for MIT code ported into acadrust's DWG reader and writer. Full text is also in NOTICE. |
| `epaint_default_fonts::EGUI_ICONS`, `epaint_default_fonts::EMOJI_ICON` (dependency font inputs) | John Slegers | [egui 173cc737](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [emoji-icon-font](https://github.com/jslegers/emoji-icon-font) | MIT (Copyright (c) 2014 John Slegers; full upstream text in `NOTICE`) | egui-icons.ttf is the five-glyph subset; emoji-icon-font.ttf is the full monochrome fallback. Registered by the production default font definitions; dependency assets unmodified here, no font file copied into this repository. |
| `krilla 0.8.2 / icc/sGrey-v2-magic.icc` (dependency-embedded) | Clinton Ingram | [craft-libs 9f89fe8 vendor/krilla/icc/sGrey-v2-magic.icc](https://github.com/storytold/craft-libs/blob/9f89fe8f6d72ab4db4cc06f186381a6a254463ab/vendor/krilla/icc/sGrey-v2-magic.icc) (Krilla 0.8.2 upstream 3ffdf0588cf98050aad6edba51ca70162e1fb5b5) | CC0-1.0 | Embedded by the pinned PDF writer (`craft-pdf` 0.1.0, Krilla 0.8.2); unmodified dependency asset, no file copied into this repository. SHA-256 `4110169287e5f1b5149ca9f1da1814d32943905bba8030e849d1a3b729a19481`. |
| `krilla 0.8.2 / icc/sGrey-v4.icc` (dependency-embedded) | Clinton Ingram | [craft-libs 9f89fe8 vendor/krilla/icc/sGrey-v4.icc](https://github.com/storytold/craft-libs/blob/9f89fe8f6d72ab4db4cc06f186381a6a254463ab/vendor/krilla/icc/sGrey-v4.icc) (Krilla 0.8.2 upstream 3ffdf0588cf98050aad6edba51ca70162e1fb5b5) | CC0-1.0 | Embedded by the pinned PDF writer (`craft-pdf` 0.1.0, Krilla 0.8.2); unmodified dependency asset, no file copied into this repository. SHA-256 `00c0f94e09127520a17dc0e1d9264b5702081d96dbdb1549ee88e3631ce42a9d`. |
@@ -88,7 +90,7 @@ Generated-in-code assets are original and have no file to list:
| `crates/ui-egui/src/i18n/sv.tsv` | Erik Holmbom (@holmbom) with Claude Code (AI-assisted) | Original Swedish translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; terminology and the running app reviewed by a native speaker |
| `crates/ui-egui/src/i18n/it.tsv` | Emanuele Bottelli (AI-assisted); terminology corrections: Andrea Brandi (@starise) with OpenAI Codex (AI-assisted) | Original Italian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; targeted Chamfer terminology review by a native speaker |
| `crates/ui-egui/src/i18n/ko.tsv` | @huk082 (AI-assisted) | Original Korean translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; no font assets added |
| `crates/ui-egui/src/i18n/ar.tsv` | @hasan-sdaif | Original Arabic translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
| `crates/ui-egui/src/i18n/ar.tsv` | @hasan-sdaif; missing rows and the Find and Replace dialog: Saleh Hassan Alnemari (@salehnemari-max) with Claude Code (AI-assisted) | Original Arabic translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; the added rows reviewed line by line by the translator, a native speaker |
| `crates/ui-egui/src/i18n/hu.tsv` | @Skaywalker | Original Hungarian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
| `crates/ui-egui/src/i18n/tr.tsv` | @ogzhnklvz (AI-assisted); 870 later rows: @HolyZephyros (AI-assisted) | Original Turkish translations of CADCraft English strings (original catalog by @ogzhnklvz; 870 later rows written from CADCraft's English strings in #3291) | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; the running app for the original catalog was reviewed by a native speaker; the 870 rows added in #3291 have not yet been reviewed by a native speaker |
| `crates/ui-egui/src/i18n/el.tsv` | @Camthalion77 with ChatGPT (AI-assisted); 46 later rows: @V1dalTheAbidal with Claude Code (AI-assisted) | Original Greek translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; the 46 later rows were read by their contributor, a native Greek speaker; independent native proofreading of the whole file pending |
Generated
+25 -2
View File
@@ -26,6 +26,29 @@ dependencies = [
"web-time",
]
[[package]]
name = "acadrust"
version = "0.6.6"
source = "git+https://github.com/storytold/acadrust.git?rev=5d5c482b3fcb3dc77e8281474461760f32959436#5d5c482b3fcb3dc77e8281474461760f32959436"
dependencies = [
"anyhow",
"bitflags 2.13.2",
"byteorder",
"encoding_rs",
"flate2",
"foldhash 0.2.0",
"indexmap",
"itoa",
"memmap2",
"nom 7.1.3",
"oem_cp",
"once_cell",
"rayon",
"ryu",
"thiserror 2.0.21",
"web-time",
]
[[package]]
name = "accesskit"
version = "0.25.2"
@@ -855,7 +878,7 @@ dependencies = [
name = "cadcraft-io"
version = "0.21.0"
dependencies = [
"acadrust",
"acadrust 0.6.6 (git+https://github.com/storytold/acadrust.git?rev=5d5c482b3fcb3dc77e8281474461760f32959436)",
"cadcraft-color",
"cadcraft-doc",
"cadcraft-fonts",
@@ -1434,7 +1457,7 @@ name = "craft-dwg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
dependencies = [
"acadrust",
"acadrust 0.6.6 (registry+https://github.com/rust-lang/crates.io-index)",
"log",
]
+428 -2
View File
@@ -10,9 +10,435 @@ docs/brand/LICENSE-brand.txt.
Third-party material
Software dependencies are listed in Cargo.lock. One is under a weak-copyleft licence: the acadrust
crate (DWG reading and writing, https://github.com/hakanaktt/acadrust) is licensed under the
crate (DWG reading and writing, https://github.com/hakanaktt/acadrust) 0.6.6 is licensed under the
Mozilla Public License 2.0 and is used unmodified as a separate library via craft-dwg. Its source
is available from crates.io and the repository above.
is available from crates.io and the repository above. The licence text and upstream third-party
notices are retained in licenses/dwg/, copied verbatim from craft-libs at
8fa4db64a9bb943520259ea95331a303ba788f21, the revision this repository pins.
acadrust's DWG reader and writer include code ported and adapted from ACadSharp
(https://github.com/DomCR/ACadSharp), Copyright (c) 2021 Albert Domenech, under the MIT License.
The Mozilla Public License 2.0 text and the upstream third-party notices follow.
The following text is reproduced verbatim from licenses/dwg/acadrust-MPL-2.0.txt:
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under the name "LEGAL", and included in all Covered Software
distributed in Source Code Form. Except to the extent prohibited by
statute or regulation, such description must be sufficiently detailed
for a recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at https://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.
The following text is reproduced verbatim from licenses/dwg/acadrust-THIRD_PARTY_NOTICES.md:
# Third-Party Notices
## ACadSharp
The DWG reader and writer include code ported and adapted from ACadSharp. The repository
history's initial DWG support commit identifies the source classes explicitly, including
`DwgStreamReaderBase`, `DwgLZ77AC21Decompressor`, `DwgFileHeaderWriterAC18`, and
`DwgObjectWriter`. Their current Rust implementations are in `src/io/dwg`.
Copyright (c) 2021 Albert Domenech
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
## DWG Format References
DWG field layouts and version behavior are based on the Open Design Alliance (ODA) DWG
specification and reverse engineering, including comparison with drawings produced by CAD
applications. LibreDWG is used as a secondary cross-check for selected field names and
layouts. The Reed-Solomon tests cite numeric reference values from LibreDWG's
`src/reedsolomon.c` to validate the Rust implementation; those values are test data, not
translated routines. The repository history and source review found no LibreDWG routines
ported into the implementation. The source comments identify the specific cross-checks.
CADCraft's icons, drafting font, hatch patterns and linetypes are drawn or defined in code.
+1 -1
View File
@@ -124,7 +124,7 @@ numbers):
| Layouts & plotting | Paper-space layouts, viewports (scale, lock, per-viewport layer freeze), MSPACE/PSPACE through viewports, page setups, PLOT and EXPORTPDF |
| Parametric | Geometric and dimensional constraints, AUTOCONSTRAIN, PARAMETERS with expressions, conflict detection; constraints re-solve after every edit |
| Grips | Hot grips with Space to cycle Stretch, Move, Rotate, Scale and Mirror |
| Interface languages | English, Ukrainian (Українська), Brazilian Portuguese (Português (Brasil)), German (Deutsch), Spanish (Español), Czech (Čeština), Russian (Русский), French (Français), Simplified Chinese (简体中文, with an installed CJK font), Italian (Italiano), Korean (한국어, with an installed Hangul font), Swedish (Svenska), Arabic (العربية, with an installed Arabic font), Hungarian (Magyar), Turkish (Türkçe), Greek (Ελληνικά), Bosnian (Bosanski), Georgian (ქართული) and Tamil (தமிழ், with an installed Tamil font), live switching and a remembered Auto/system-language choice; [details](docs/localization.md) |
| Interface languages | English, Ukrainian (Українська), Brazilian Portuguese (Português (Brasil)), German (Deutsch), Spanish (Español), Czech (Čeština), Russian (Русский), French (Français), Simplified Chinese (简体中文, with an installed CJK font), Italian (Italiano), Korean (한국어, with an installed Hangul font), Swedish (Svenska), Arabic (العربية, with an installed Arabic font), Hungarian (Magyar), Turkish (Türkçe), Greek (Ελληνικά), Bosnian (Bosanski), Georgian (ქართული), Tamil (தமிழ், with an installed Tamil font), Dutch (Nederlands) and European Portuguese (Português (Portugal)) (catalogs in `storytold/craft-i18n`; fall back to English until embedded), live switching and a remembered Auto/system-language choice; [details](docs/localization.md) |
| Automation | MCP server, JSON control channel, `cadcraft-cli` (info, convert, run, commands, mcp) |
## Quick start
+17 -14
View File
@@ -213,16 +213,14 @@ mod tests {
let path = directory.join("workspace.json");
let (mut first, restored, error) = Workspace::at(Some(path.clone()));
assert!(restored.is_none() && error.is_none());
let ui = UiState {
show_palettes: false,
show_command_line: false,
toolset_tab: "Modeling".into(),
collapsed_groups: vec!["Solid".into()],
history_lines: 5,
dialog: Some("layers".into()),
start_tab: true,
..Default::default()
};
let mut ui = UiState::default();
ui.show_palettes = false;
ui.show_command_line = false;
ui.toolset_tab = "Modeling".into();
ui.collapsed_groups = vec!["Solid".into()];
ui.history_lines = 5;
ui.dialog = Some("layers".into());
ui.start_tab = true;
first.save_if_changed(&ui, Instant::now()).unwrap();
let bytes = fs::read(&path).unwrap();
let value: Value = serde_json::from_slice(&bytes).unwrap();
@@ -313,7 +311,9 @@ mod tests {
let (mut store, ui, error) = Workspace::at(Some(path.clone()));
assert!(ui.is_none());
assert!(error.as_deref().is_some_and(|error| error.contains("left unchanged")));
store.save_if_changed(&UiState { show_palettes: false, ..Default::default() }, Instant::now()).unwrap();
let mut ui = UiState::default();
ui.show_palettes = false;
store.save_if_changed(&ui, Instant::now()).unwrap();
assert_eq!(fs::read(&path).unwrap(), bytes);
}
fs::remove_dir_all(directory).unwrap();
@@ -351,7 +351,8 @@ mod tests {
let path = directory.join("workspace.json");
let (mut store, _, _) = Workspace::at(Some(path.clone()));
let start = Instant::now();
let mut ui = UiState { history_lines: 1, ..Default::default() };
let mut ui = UiState::default();
ui.history_lines = 1;
assert_eq!(store.save_if_changed(&ui, start).unwrap(), None);
// A drag: a new state every frame, none of them written until the interval ends.
for (frame, lines) in (2..=5).enumerate() {
@@ -375,7 +376,8 @@ mod tests {
let directory = temp_dir();
let path = directory.join("workspace.json");
let (mut store, _, _) = Workspace::at(Some(path.clone()));
let mut ui = UiState { show_palettes: false, ..Default::default() };
let mut ui = UiState::default();
ui.show_palettes = false;
store.save_if_changed(&ui, Instant::now()).unwrap();
let good = fs::read(&path).unwrap();
ui.collapsed_groups = vec!["x".repeat(257)];
@@ -391,7 +393,8 @@ mod tests {
let (mut store, _, _) = Workspace::at(Some(path.clone()));
// Simulate a destination becoming unavailable after startup.
fs::create_dir(&path).unwrap();
let ui = UiState { show_palettes: false, ..Default::default() };
let mut ui = UiState::default();
ui.show_palettes = false;
let first_error = store.save_if_changed(&ui, Instant::now()).unwrap_err();
fs::remove_dir(&path).unwrap();
assert_eq!(store.save_if_changed(&ui, Instant::now()).unwrap_err(), first_error);
+85 -21
View File
@@ -104,6 +104,48 @@ enum Val {
Flip(Vec3, Vec3, bool),
/// A flip grip's state: its value record's last group 70.
State(bool),
/// Where a visibility or lookup parameter is, when an action carries it, with its state or
/// value (unchanged; its record holds both).
At(Vec3, String),
}
/// What an action carries of parameter `node`: the value this change has given it so far, else
/// its current one; of a visibility or lookup parameter, its position (its state or value stays).
/// None for a parameter whose state this change sets (it stays where it is).
fn carried(m: &DynamicBlock, values: &BTreeMap<i32, Value>, new: &BTreeMap<i32, Val>, node: i32) -> Option<Val> {
match new.get(&node) {
Some(Val::Text(_)) => None,
Some(v) => Some(v.clone()),
None => match current(m, values, node)? {
Val::Text(t) => located(m, values, node).map(|p| Val::At(p, t)),
v => Some(v),
},
}
}
/// Parameter value `v` with each of its points moved by `f` (a visibility or lookup parameter's
/// carried position too); `None` for a value without points (a state or a value alone).
fn moved(v: Val, f: impl Fn(Vec3) -> Vec3) -> Option<Val> {
Some(match v {
Val::Point(q) => Val::Point(f(q)),
Val::At(q, t) => Val::At(f(q), t),
Val::Points(b, e) => Val::Points(f(b), f(e)),
Val::Flip(b, e, s) => Val::Flip(f(b), f(e), s),
Val::Text(_) | Val::State(_) => return None,
})
}
/// Where a visibility or lookup parameter is on a reference: as its record has it, else as the
/// dynamic block has it.
fn located(m: &DynamicBlock, values: &BTreeMap<i32, Value>, node: i32) -> Option<Vec3> {
let home = m.parameters.iter().find(|p| p.node == node).and_then(|p| match &p.kind {
ParameterKind::Visibility { at, .. } | ParameterKind::Lookup { at, .. } => Some(*at),
_ => None,
})?;
Some(match values.get(&node) {
Some(Value::Text { at: Some(q), .. }) => *q,
_ => home,
})
}
/// A rotation parameter's angle (radians, 0 to 2π): its end's direction from its base, from the
@@ -173,7 +215,7 @@ fn current(m: &DynamicBlock, values: &BTreeMap<i32, Value>, node: i32) -> Option
let p = m.parameters.iter().find(|p| p.node == node)?;
let given = values.get(&node);
Some(match (&p.kind, given) {
(_, Some(Value::Text { value })) => Val::Text(value.clone()),
(_, Some(Value::Text { value, .. })) => Val::Text(value.clone()),
(_, Some(Value::Point { at })) => Val::Point(*at),
(_, Some(Value::Points { base, end })) => Val::Points(*base, *end),
(_, Some(Value::Flip { base, end, flipped })) => Val::Flip(*base, *end, *flipped),
@@ -954,7 +996,7 @@ impl ActionRun<'_> {
/// The value of parameter `node` so far: carried along by an action already, else the
/// reference's.
fn value_of(&self, node: i32) -> Option<Val> {
self.new.get(&node).cloned().or_else(|| current(self.m, self.values, node))
carried(self.m, self.values, &self.new, node)
}
/// Action `a`, when one of its connections follows a parameter the change sets.
@@ -1022,13 +1064,9 @@ impl ActionRun<'_> {
}
let back = |q: Vec3| q - rebase.to3(0.0);
for p in self.m.parameters.iter().filter(|p| !matches!(p.kind, ParameterKind::BasePoint { .. })) {
let moved = match self.value_of(p.node) {
Some(Val::Point(q)) => Val::Point(back(q)),
Some(Val::Points(b, e)) => Val::Points(back(b), back(e)),
Some(Val::Flip(b, e, f)) => Val::Flip(back(b), back(e), f),
_ => continue,
};
self.new.insert(p.node, moved);
// A visibility or lookup grip goes back too (its carried position).
let Some(now) = self.value_of(p.node).and_then(|v| moved(v, back)) else { continue };
self.new.insert(p.node, now);
}
rebase
}
@@ -1047,14 +1085,8 @@ impl ActionRun<'_> {
continue;
}
let Some(cur) = self.value_of(node) else { continue };
let p = |q: Vec3| t.apply(q.xy()).to3(q.z);
let moved = match cur {
Val::Point(q) => Val::Point(p(q)),
Val::Points(b, e) => Val::Points(p(b), p(e)),
Val::Flip(b, e, f) => Val::Flip(p(b), p(e), f),
other => other,
};
self.new.insert(node, moved);
let now = moved(cur.clone(), |q| t.apply(q.xy()).to3(q.z)).unwrap_or(cur);
self.new.insert(node, now);
} else if let Some(c) = self.copy_of(h) {
self.moves.entry(c).or_default().push(Op::Transform(t));
}
@@ -1082,7 +1114,8 @@ impl ActionRun<'_> {
}
let Some(cur) = self.value_of(node) else { continue };
let home = current(self.m, &BTreeMap::new(), node);
self.new.insert(node, turned_and_shifted(cur, home, frame, (turn, v)));
let at = located(self.m, &BTreeMap::new(), node);
self.new.insert(node, turned_and_shifted(cur, (home, at), frame, (turn, v)));
continue;
}
let Some(c) = self.copy_of(h) else { continue };
@@ -1148,7 +1181,8 @@ impl ActionRun<'_> {
}
let Some(cur) = self.value_of(node) else { continue };
let home = current(self.m, &BTreeMap::new(), node);
self.new.insert(node, shifted(cur, home, frame, v));
let at = located(self.m, &BTreeMap::new(), node);
self.new.insert(node, shifted(cur, (home, at), frame, v));
continue;
}
let Some(c) = self.copy_of(h) else { continue };
@@ -1204,7 +1238,7 @@ fn earlier_copies(src: &Block, src_tag: &HashMap<Handle, i64>, arrays: &HashMap<
/// A parameter value `cur` turned by `turn`, and carried by `v` where its points are in `frame`
/// (judged where the dynamic block has them, `home`), after a polar stretch.
fn turned_and_shifted(cur: Val, home: Option<Val>, frame: &[Vec2], (turn, v): (Mat3, Vec2)) -> Val {
fn turned_and_shifted(cur: Val, (home, located): (Option<Val>, Option<Vec3>), frame: &[Vec2], (turn, v): (Mat3, Vec2)) -> Val {
let carry = |p: Vec3, at: Vec3| {
let q = turn.apply(p.xy()).to3(p.z);
if in_frame(frame, at.xy()) { q + v.to3(0.0) } else { q }
@@ -1212,6 +1246,8 @@ fn turned_and_shifted(cur: Val, home: Option<Val>, frame: &[Vec2], (turn, v): (M
match (cur, home) {
(Val::Point(p), Some(Val::Point(h))) => Val::Point(carry(p, h)),
(Val::Point(p), _) => Val::Point(carry(p, p)),
// A carried visibility or lookup grip: in the frame where the dynamic block has it.
(Val::At(p, t), _) => Val::At(carry(p, located.unwrap_or(p)), t),
(Val::Points(b, e), Some(Val::Points(hb, he))) => Val::Points(carry(b, hb), carry(e, he)),
(Val::Points(b, e), _) => Val::Points(carry(b, b), carry(e, e)),
(Val::Flip(b, e, f), Some(Val::Flip(hb, he, _))) => Val::Flip(carry(b, hb), carry(e, he), f),
@@ -1222,11 +1258,12 @@ fn turned_and_shifted(cur: Val, home: Option<Val>, frame: &[Vec2], (turn, v): (M
/// Parameter value `cur` carried by `v`: the points in `frame` (empty: all of them), judged where
/// the dynamic block has them (`home`), move.
fn shifted(cur: Val, home: Option<Val>, frame: &[Vec2], v: Vec2) -> Val {
fn shifted(cur: Val, (home, located): (Option<Val>, Option<Vec3>), frame: &[Vec2], v: Vec2) -> Val {
let shift = |p: Vec3, at: Option<Vec3>| if frame.is_empty() || in_frame(frame, at.unwrap_or(p).xy()) { p + v.to3(0.0) } else { p };
match (cur, home) {
(Val::Point(p), Some(Val::Point(h))) => Val::Point(shift(p, Some(h))),
(Val::Point(p), _) => Val::Point(shift(p, None)),
(Val::At(p, t), _) => Val::At(shift(p, located), t),
(Val::Points(b, e), Some(Val::Points(hb, he))) => Val::Points(shift(b, Some(hb)), shift(e, Some(he))),
(Val::Points(b, e), _) => Val::Points(shift(b, None), shift(e, None)),
(Val::Flip(b, e, f), Some(Val::Flip(hb, he, _))) => Val::Flip(shift(b, Some(hb)), shift(e, Some(he)), f),
@@ -2030,6 +2067,10 @@ fn write_value(tags: &mut Vec<RawTag>, v: &Val) {
return;
}
Val::Point(p) => vec![*p],
Val::At(p, t) => {
write_value(tags, &Val::Text(t.clone()));
vec![*p]
}
Val::Points(b, e) | Val::Flip(b, e, _) => vec![*b, *e],
Val::State(f) => {
set_state(tags, *f);
@@ -2244,6 +2285,29 @@ mod tests {
assert_eq!(total, 23);
}
#[test]
fn a_carried_visibility_grip_moves_with_the_points() {
let up = |q: Vec3| q + Vec3::new(0.0, 1.0, 0.0);
let at = Val::At(Vec3::new(2.0, 0.0, 0.0), "Open".into());
assert_eq!(moved(at, up), Some(Val::At(Vec3::new(2.0, 1.0, 0.0), "Open".into())));
assert_eq!(moved(Val::Text("Open".into()), up), None);
assert_eq!(moved(Val::State(true), up), None);
}
#[test]
fn a_polar_stretch_carries_a_visibility_grip() {
let turn = Mat3::rotate_about(Vec2::ZERO, std::f64::consts::FRAC_PI_2);
let frame = [Vec2::new(1.0, -1.0), Vec2::new(3.0, 1.0)];
let at = |x: f64, y: f64| Val::At(Vec3::new(x, y, 0.0), "Open".into());
let near = |v: Val, x: f64, y: f64| matches!(v, Val::At(p, _) if (p.x - x).abs() < 1e-9 && (p.y - y).abs() < 1e-9);
// In the frame where the dynamic block has it: turned, then moved.
let v = turned_and_shifted(at(2.0, 0.0), (None, Some(Vec3::new(2.0, 0.0, 0.0))), &frame, (turn, Vec2::new(0.0, 1.0)));
assert!(near(v, 0.0, 3.0));
// Outside it: only turned.
let v = turned_and_shifted(at(5.0, 0.0), (None, Some(Vec3::new(5.0, 0.0, 0.0))), &frame, (turn, Vec2::new(0.0, 1.0)));
assert!(near(v, 0.0, 5.0));
}
fn tagged(h: u64, tag_value: Option<&str>) -> Entity {
let mut e = Entity::new(Handle(h), EntityKind::Line(crate::Line { a: Vec3::ZERO, b: Vec3::ZERO }));
if let Some(v) = tag_value {
+6 -2
View File
@@ -172,7 +172,7 @@ pub fn grips(d: &Drawing, insert: Handle) -> Vec<DynGrip> {
for p in &m.parameters {
if let ParameterKind::Visibility { states, .. } = &p.kind {
let current = match r.values.get(&p.node) {
Some(Value::Text { value }) => states.iter().find(|s| s.name.eq_ignore_ascii_case(value)),
Some(Value::Text { value, .. }) => states.iter().find(|s| s.name.eq_ignore_ascii_case(value)),
_ => states.first(),
};
if let Some(s) = current {
@@ -340,7 +340,11 @@ pub fn grips(d: &Drawing, insert: Handle) -> Vec<DynGrip> {
ParameterKind::Visibility { at, label, .. } | ParameterKind::Lookup { at, label, .. } => {
let Some(list) = choices.get(&label.to_ascii_uppercase()).filter(|c| !c.is_empty()) else { continue };
if shown(p.node, grip(0)) {
let at = world(*at);
// Where the reference's record has it (an action may have carried it).
let at = match r.values.get(&p.node) {
Some(Value::Text { at: Some(q), .. }) => world(*q),
_ => world(*at),
};
out.push(DynGrip {
node: p.node,
part: GripPart::At,
+12 -6
View File
@@ -23,8 +23,13 @@ const MAX_VALUES: usize = 10_000;
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum Value {
/// A visibility state's name or a lookup value.
Text { value: String },
/// A visibility state's name or a lookup value, and where the parameter is when the record
/// says (an action may have carried it from where the dynamic block has it).
Text {
value: String,
#[serde(skip_serializing_if = "Option::is_none")]
at: Option<Vec3>,
},
/// A point parameter's position.
Point { at: Vec3 },
/// A two-point parameter's points.
@@ -93,17 +98,18 @@ fn entries(objects: &HashMap<Handle, &ForeignObject>, dict: Handle) -> Vec<(Stri
out
}
/// A value XRECORD: its text (group 1) when it has one, else its points (10/20/30); a flip
/// A value XRECORD: its text (group 1) when it has one, with the parameter's position (a
/// visibility or lookup grip's, 10/20/30) when it has that too; else its points; a flip
/// parameter's also has its state, a group 70 after its points (the header's `70 25`, `70 104`
/// come before them).
fn value(o: &ForeignObject) -> Option<Value> {
if let Some(t) = o.tags.iter().find(|t| t.code == 1) {
return Some(Value::Text { value: t.value.clone() });
}
let num = |code: i32, i: usize| {
o.tags.iter().filter(|t| t.code == code).nth(i).and_then(|t| t.value.trim().parse::<f64>().ok()).filter(|v| v.is_finite())
};
let point = |i: usize| Some(Vec3::new(num(10, i)?, num(20, i)?, num(30, i).unwrap_or(0.0)));
if let Some(t) = o.tags.iter().find(|t| t.code == 1) {
return Some(Value::Text { value: t.value.clone(), at: point(0) });
}
let first_point = o.tags.iter().position(|t| t.code == 10).unwrap_or(o.tags.len());
let state = o.tags.get(first_point..).unwrap_or_default().iter().rev().find(|t| t.code == 70).map(|t| t.value.trim() == "1");
match (point(0), point(1)) {
+5
View File
@@ -261,6 +261,11 @@ pub fn is_user_pattern(name: &str) -> bool {
name.eq_ignore_ascii_case(USER_PATTERN)
}
/// Names owned by the standard library or the native user-defined hatch form.
pub fn is_reserved_pattern_name(name: &str) -> bool {
is_user_pattern(name) || pattern(name).is_some()
}
/// Hatch pattern scales must be greater than this limit. For a user-defined hatch, the scale is its line spacing.
pub const MIN_HATCH_PATTERN_SCALE: f64 = 1e-9;
+1 -1
View File
@@ -21,7 +21,7 @@ mod griphot;
pub(crate) mod groups;
pub(crate) mod hatch;
mod image;
mod inquiry;
pub(crate) mod inquiry;
pub mod interface;
mod layer;
mod layout;
+22
View File
@@ -343,6 +343,11 @@ fn eq_variants(o: &TanObj) -> Vec<Eq3> {
/// Circle tangent to three objects, nearest the pick points (Newton on all sign combinations).
pub fn ttt(objs: [(TanObj, Vec2); 3]) -> Option<Circle> {
ttt_where(objs, |_| true)
}
/// [`ttt`] among the circles `ok` accepts.
pub fn ttt_where(objs: [(TanObj, Vec2); 3], ok: impl Fn(&Circle) -> bool) -> Option<Circle> {
let [(o1, p1), (o2, p2), (o3, p3)] = objs;
let mut starts: Vec<[f64; 3]> = Vec::new();
let cen = (p1 + p2 + p3) / 3.0;
@@ -350,6 +355,20 @@ pub fn ttt(objs: [(TanObj, Vec2); 3]) -> Option<Circle> {
starts.push([cen.x, cen.y, rad.max(1e-3)]);
if let Some(c) = Circle::from_3_points(p1, p2, p3) {
starts.push([c.center.x, c.center.y, c.radius]);
} else {
// The picks lie in one line. When the circles picked are centred on it too, every Newton
// step from a start on that line stays on it: start off it as well, on both sides, from
// the circle through the two picks farthest apart and a point beside them.
let (a, b) = [(p1, p2), (p1, p3), (p2, p3)].into_iter().max_by(|x, y| x.0.dist(x.1).total_cmp(&y.0.dist(y.1))).unwrap_or((p1, p3));
let span = a.dist(b);
let n = (b - a).normalized().perp();
if span.is_finite() && span > 0.0 && n.is_finite() {
for side in [1.0, -1.0] {
if let Some(c) = Circle::from_3_points(a, b, (a + b) / 2.0 + n * (span * side)) {
starts.push([c.center.x, c.center.y, c.radius]);
}
}
}
}
let mut best: Option<(f64, Circle)> = None;
let scale = rad.max(p1.dist(p2)).max(1e-6);
@@ -379,6 +398,9 @@ pub fn ttt(objs: [(TanObj, Vec2); 3]) -> Option<Circle> {
continue;
}
let c = Circle::new(Vec2::new(x[0], x[1]), x[2]);
if !ok(&c) {
continue;
}
let sc = score(&c, &objs);
if best.is_none_or(|(b, _)| sc < b - 1e-12) {
best = Some((sc, c));
+74 -5
View File
@@ -2,6 +2,7 @@ use super::{
Accept, Arc, Circle, EntityKind, Input, Interactive, Prompt, Result, Session, Step, Value, Vec2, added, arc, bad, circle, f64_req, line, number,
point_param, size_param,
};
use crate::snap;
pub(super) fn run_circle(s: &mut Session, p: &Value) -> Result<Value> {
let c = if let Some(center) = point_param(p, "center") {
@@ -51,6 +52,8 @@ pub(super) fn run_arc(s: &mut Session, p: &Value) -> Result<Value> {
pub(super) struct CircleM {
mode: u8, // 0 center-radius, 1 = 3P, 2 = 2P, 3 = TTR
pts: Vec<Vec2>,
/// 3P: the circle or arc each point was picked on with a tangent snap, by point.
tans: Vec<Option<snap::SnapCurve>>,
diameter: bool,
/// The `Ttr` option hands over to the tangent-circle machine.
delegate: Option<Box<dyn Interactive>>,
@@ -69,18 +72,22 @@ impl Interactive for CircleM {
match (self.mode, n) {
(0, 0) => Prompt::new("Specify center point for circle", Accept::POINT).kw(&["3P", "2P", "Ttr (tan tan radius)"]),
(0, _) if self.diameter => {
Prompt::new("Specify diameter of circle", Accept::POINT_OR_NUMBER).base_opt(self.pts.first().copied()).distance()
Prompt::new("Specify diameter of circle", Accept::POINT_OR_NUMBER).base_opt(self.pts.first().copied()).distance().deferred()
}
(0, _) => {
let p =
Prompt::new("Specify radius of circle", Accept::POINT_OR_NUMBER).kw(&["Diameter"]).base_opt(self.pts.first().copied()).distance();
let p = Prompt::new("Specify radius of circle", Accept::POINT_OR_NUMBER)
.kw(&["Diameter"])
.base_opt(self.pts.first().copied())
.distance()
.deferred();
if last_r > 0.0 { p.default(format!("{last_r:.4}")) } else { p }
}
(1, k) => Prompt::new(
["Specify first point on circle", "Specify second point on circle", "Specify third point on circle"].get(k).copied().unwrap_or(""),
Accept::POINT,
)
.base_opt(self.pts.last().copied()),
.base_opt(self.pts.last().copied())
.deferred(),
(2, k) => Prompt::new(
if k == 0 { "Specify first end point of circle's diameter" } else { "Specify second end point of circle's diameter" },
Accept::POINT,
@@ -120,7 +127,14 @@ impl Interactive for CircleM {
let r = if self.diameter { c.dist(*e) / 2.0 } else { c.dist(*e) };
Some(Circle::new(*c, r))
}
1 if self.pts.len() == 3 => Circle::from_3_points(self.pts[0], self.pts[1], self.pts[2]),
1 if self.pts.len() == 3 => match self.three_points() {
Some(c) => Some(c),
None => {
self.pts.pop();
self.tans.truncate(self.pts.len());
return Err(crate::EngineError::Other("Circle does not exist.".into()));
}
},
2 if self.pts.len() == 2 => Some(Circle::from_2_points(self.pts[0], self.pts[1])),
_ => None,
};
@@ -130,6 +144,29 @@ impl Interactive for CircleM {
}
Ok(Step::Continue)
}
// 3P: a point picked with a tangent snap makes the circle tangent to that curve (#1512).
Input::Deferred(d) if self.mode == 1 => {
let tan = (d.mode == snap::mode::TAN && !matches!(d.curve, snap::SnapCurve::Line { .. })).then_some(d.curve);
self.tans.resize(self.pts.len(), None);
self.tans.push(tan);
self.input(s, Input::Point(d.at))
}
// A tangent picked for the radius: the circle around the center that touches the
// curve, on the side it was picked (#1512).
Input::Deferred(d) if self.mode == 0 && self.pts.len() == 1 => {
let Some(&c) = self.pts.first() else { return Ok(Step::Continue) };
// Around the picked curve's own center the circle would lie on it, not touch it.
let concentric =
matches!(d.curve, snap::SnapCurve::Circle { center, .. } | snap::SnapCurve::Arc { center, .. } if center.near(c, 1e-9));
let touch = d.curve.perpendiculars(c, d.at).into_iter().filter(|_| !concentric).min_by(|a, b| a.dist(d.at).total_cmp(&b.dist(d.at)));
match touch.map(|t| c.dist(t)).filter(|r| *r > 1e-12 && r.is_finite()) {
Some(r) => {
finish_circle(s, Circle::new(c, r))?;
Ok(Step::Done)
}
None => Err(crate::EngineError::Other("No circle around the center is tangent there.".into())),
}
}
Input::Text(t) if self.mode == 0 && self.pts.len() == 1 => {
let v = number(&t).ok_or_else(|| crate::EngineError::Other("Requires numeric distance or second point.".into()))?;
let r = if self.diameter { v / 2.0 } else { v };
@@ -174,6 +211,38 @@ impl Interactive for CircleM {
}
}
impl CircleM {
/// The 3P circle: through the three points, or tangent to the curves picked with TAN.
fn three_points(&self) -> Option<Circle> {
let [a, b, c] = <[Vec2; 3]>::try_from(self.pts.as_slice()).ok()?;
if self.tans.iter().all(Option::is_none) {
return Circle::from_3_points(a, b, c);
}
let tan = |i: usize| self.tans.get(i).copied().flatten();
// A plain point is a circle of radius zero to pass through; an arc is solved as its circle.
let target = |i: usize, p: Vec2| {
let circle = match tan(i) {
Some(snap::SnapCurve::Circle { center, radius } | snap::SnapCurve::Arc { center, radius, .. }) => Circle::new(center, radius),
_ => Circle::new(p, 0.0),
};
crate::cmd::curves::TanObj::Circle(circle)
};
let pts = [a, b, c];
// The circle must touch an arc within its sweep, not elsewhere on the arc's circle, and
// not be the picked circle itself (which lies on it rather than touching it).
let touches = |found: &Circle| {
pts.iter().enumerate().all(|(i, p)| {
tan(i).is_none_or(|t| {
let same = matches!(target(i, *p), crate::cmd::curves::TanObj::Circle(o)
if o.center.dist(found.center) + (o.radius - found.radius).abs() <= 1e-9 * o.radius);
!same && t.contains(target(i, *p).touch(found))
})
})
};
crate::cmd::curves::ttt_where([(target(0, a), a), (target(1, b), b), (target(2, c), c)], touches)
}
}
fn finish_circle(s: &mut Session, c: Circle) -> Result<()> {
s.add_entity(circle(c.center, c.radius))?;
s.doc_mut()?.header.set_f64("CIRCLERAD", c.radius);
+22 -6
View File
@@ -70,9 +70,16 @@ pub(super) fn run_pline(s: &mut Session, p: &Value) -> Result<Value> {
// ---------------- interactive ----------------
/// A LINE between two 3D points.
fn line3(a: cadcraft_geom::Vec3, b: cadcraft_geom::Vec3) -> EntityKind {
EntityKind::Line(cadcraft_doc::Line { a, b })
}
#[derive(Default)]
pub(super) struct LineM {
pts: Vec<Vec2>,
/// The Z of each of `pts` ([`Session::point_z`]: typed, or from an object snap).
zs: Vec<f64>,
handles: Vec<cadcraft_doc::Handle>,
/// A first point picked as a deferred tangent/perpendicular, resolved by the next point.
first: Option<snap::Deferred>,
@@ -85,8 +92,11 @@ impl LineM {
let what = if first.mode == snap::mode::TAN { "tangent" } else { "perpendicular" };
return Err(crate::EngineError::Other(format!("No {what} line through that point; pick another point.")));
};
self.handles.push(s.add_entity(line(a, b))?);
// The deferred start lies on the curve at z = 0; the other end keeps its own Z.
let z = s.point_z();
self.handles.push(s.add_entity(line3(a.to3(0.0), b.to3(z)))?);
self.pts = vec![a, b];
self.zs = vec![0.0, z];
self.first = None;
s.last_point = b;
Ok(Step::Continue)
@@ -119,6 +129,7 @@ impl Interactive for LineM {
let e = t + Vec2::new(ang.cos(), ang.sin()) * dist;
self.handles.push(s.add_entity(line(t, e))?);
self.pts = vec![t, e];
self.zs = vec![0.0, 0.0];
s.last_point = e;
self.first = None;
return Ok(Step::Continue);
@@ -143,13 +154,15 @@ impl Interactive for LineM {
None => Ok(Step::Continue),
},
Input::Point(p) => {
if let Some(last) = self.pts.last().copied() {
if last.near(p, 1e-12) {
let z = s.point_z();
if let (Some(last), Some(lz)) = (self.pts.last().copied(), self.zs.last().copied()) {
if last.near(p, 1e-12) && (lz - z).abs() < 1e-12 {
return Ok(Step::Continue);
}
self.handles.push(s.add_entity(line(last, p))?);
self.handles.push(s.add_entity(line3(last.to3(lz), p.to3(z)))?);
}
self.pts.push(p);
self.zs.push(z);
Ok(Step::Continue)
}
Input::Keyword(k) if k == "Undo" => {
@@ -160,11 +173,14 @@ impl Interactive for LineM {
s.doc_mut()?.remove_entity(h);
}
self.pts.pop();
self.zs.pop();
Ok(Step::Continue)
}
Input::Keyword(k) if k == "Close" => {
if let (Some(a), Some(b)) = (self.pts.last().copied(), self.pts.first().copied()) {
s.add_entity(line(a, b))?;
if let (Some(a), Some(b), Some(za), Some(zb)) =
(self.pts.last().copied(), self.pts.first().copied(), self.zs.last().copied(), self.zs.first().copied())
{
s.add_entity(line3(a.to3(za), b.to3(zb)))?;
}
Ok(Step::Done)
}
+1 -1
View File
@@ -66,7 +66,7 @@ impl Interactive for PointM {
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
match i {
Input::Point(p) => {
s.add_entity(EntityKind::Point(Point { p: v3(p), angle: 0.0 }))?;
s.add_entity(EntityKind::Point(Point { p: p.to3(s.point_z()), angle: 0.0 }))?;
Ok(if self.multiple { Step::Continue } else { Step::Done })
}
Input::Enter => Ok(Step::Done),
+9 -7
View File
@@ -1,6 +1,6 @@
use super::{
Accept, EntityKind, Handle, Helix, HelixConstrain, Input, Interactive, MAX_GEN, Polyline3d, Prompt, Result, Session, Spline, Step, Value, Vec2,
Vec3, added, bad, bool_or, circle, curves, f64_or, f64_req, line, number, other, point_req, points_param, v3,
Vec3, added, bad, bool_or, circle, curves, f64_or, f64_req, line, number, other, point_req, points_param,
};
// =====================================================================================
@@ -26,13 +26,14 @@ pub(super) fn run_3dpoly(s: &mut Session, p: &Value) -> Result<Value> {
#[derive(Default)]
pub(super) struct Poly3dM {
pts: Vec<Vec2>,
/// The vertices: a typed point keeps its Z ([`Session::point_z`]), a picked one is at z = 0.
pts: Vec<Vec3>,
handle: Option<Handle>,
}
impl Poly3dM {
fn sync(&mut self, s: &mut Session, closed: bool) -> Result<()> {
let k = EntityKind::Polyline3d(Polyline3d { points: self.pts.iter().map(|p| v3(*p)).collect(), closed });
let k = EntityKind::Polyline3d(Polyline3d { points: self.pts.clone(), closed });
match (self.handle, self.pts.len() >= 2) {
(Some(h), true) => s.doc_mut()?.modify_entity(h, |e| e.kind = k)?,
(None, true) => self.handle = Some(s.add_entity(k)?),
@@ -53,14 +54,15 @@ impl Interactive for Poly3dM {
fn prompt(&self, _s: &Session) -> Prompt {
match self.pts.len() {
0 => Prompt::new("Specify start point of polyline", Accept::POINT),
1 | 2 => Prompt::new("Specify endpoint of line", Accept::POINT).kw(&["Undo"]).base_opt(self.pts.last().copied()),
_ => Prompt::new("Specify endpoint of line", Accept::POINT).kw(&["Close", "Undo"]).base_opt(self.pts.last().copied()),
1 | 2 => Prompt::new("Specify endpoint of line", Accept::POINT).kw(&["Undo"]).base_opt(self.pts.last().map(|p| p.xy())),
_ => Prompt::new("Specify endpoint of line", Accept::POINT).kw(&["Close", "Undo"]).base_opt(self.pts.last().map(|p| p.xy())),
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
match i {
Input::Point(p) => {
if self.pts.last().is_none_or(|l| !l.near(p, 1e-12)) && self.pts.len() < MAX_GEN {
let p = p.to3(s.point_z());
if self.pts.last().is_none_or(|l| (*l - p).len() > 1e-12) && self.pts.len() < MAX_GEN {
self.pts.push(p);
self.sync(s, false)?;
}
@@ -80,7 +82,7 @@ impl Interactive for Poly3dM {
}
}
fn preview(&self, _s: &Session, c: Vec2) -> Vec<EntityKind> {
self.pts.last().map(|l| vec![line(*l, c)]).unwrap_or_default()
self.pts.last().map(|l| vec![line(l.xy(), c)]).unwrap_or_default()
}
}
+35 -1
View File
@@ -1,5 +1,5 @@
use cadcraft_doc::EntityKind;
use cadcraft_geom::{Arc, Vec2};
use cadcraft_geom::{Arc, Vec2, Vec3};
use serde_json::json;
use crate::{Input, Session};
@@ -1466,6 +1466,40 @@ fn poly3d_json_and_command_line() {
assert_eq!(s.state().unwrap().undo.len(), 2);
}
#[test]
fn poly3d_typed_points_keep_their_z() {
// A typed third number reaches the polyline (#1409, #1410): absolute `x,y,z`, relative
// `@dx,dy,dz`, and `@dx,dy`, which keeps the last point's Z, as in AutoCAD.
let mut s = Session::new();
s.cmdline("3dpoly 0,0,0 10,0,5 @0,10,-2 @5,0 #1,2,3").unwrap();
// A picked point lies on the XY plane.
s.input(Input::Point(Vec2::new(20.0, 20.0))).unwrap();
s.input(Input::Enter).unwrap();
assert!(s.running.is_none());
let EntityKind::Polyline3d(p) = last(&s) else { panic!("{:?}", last(&s)) };
let got: Vec<[f64; 3]> = p.points.iter().map(|v| [v.x, v.y, v.z]).collect();
assert_eq!(got, vec![[0.0, 0.0, 0.0], [10.0, 0.0, 5.0], [10.0, 10.0, 3.0], [15.0, 10.0, 3.0], [1.0, 2.0, 3.0], [20.0, 20.0, 0.0]]);
// LASTPOINT carries the Z of a typed point.
s.cmdline("3dpoly 0,0,0 4,5,6").unwrap();
assert_eq!(crate::sysvars::get(&s, "LASTPOINT"), Some(json!([4.0, 5.0, 6.0])));
s.input(Input::Enter).unwrap();
}
#[test]
fn poly3d_flat_and_vertical_segments() {
// Two numbers still give z = 0.
let mut s = Session::new();
s.cmdline("3dpoly 0,0 1,0 1,1 ").unwrap();
assert!(matches!(last(&s), EntityKind::Polyline3d(p) if p.points.len() == 3 && p.points.iter().all(|v| v.z == 0.0)));
// A point straight above the last one is a new vertex, not a repeat.
s.cmdline("3dpoly 0,0,0 0,0,5 ").unwrap();
assert!(matches!(last(&s), EntityKind::Polyline3d(p) if p.points.len() == 2 && p.points[1].z == 5.0));
// Undo drops the Z with its point.
s.cmdline("3dpoly 0,0,1 1,0,2 u 0,1,3 ").unwrap();
let EntityKind::Polyline3d(p) = last(&s) else { panic!("{:?}", last(&s)) };
assert_eq!(p.points, vec![Vec3::new(0.0, 0.0, 1.0), Vec3::new(0.0, 1.0, 3.0)]);
}
#[test]
fn mline_json_and_command_line() {
// Element offsets from the vertex path, sorted.
+26 -10
View File
@@ -1,10 +1,11 @@
//! HATCH, GRADIENT, BOUNDARY, REGION: boundaries from pick points or selected closed objects.
//! HATCHGENERATEBOUNDARY: polylines around existing hatches.
mod capture;
mod patfile;
pub(super) use edit::{set_pattern, takes_pattern};
pub(super) use patfile::run_patterns;
pub use patfile::{PatternChoice, pattern_choices};
pub use patfile::{PatternChoice, pattern_choices, pattern_choices_in, register_drawing_patterns};
pub(super) use patfile::{drawing_lines, run_patterns};
use cadcraft_color::Color;
use cadcraft_doc::library::{MIN_HATCH_PATTERN_SCALE, is_supported_hatch_pattern_scale};
@@ -56,6 +57,10 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("hatchgenerateboundary", "Generate Boundary", edit::run_hatchgenerateboundary)
.params("{handles?} (a closed polyline around each boundary loop of the hatches, which stay as they are) → handles")
.interactive(|_| Ok(Box::new(SelectRun::new("hatchgenerateboundary", "HATCHGENERATEBOUNDARY")))),
CommandSpec::new("hatch.capture", "Capture hatch tile", capture::run)
.params("{first:[x,y], second:[x,y], name?:string} → {pattern, patternText}; capture line segments inside the tile in the active space")
.enabled(has_doc)
.noundo(),
CommandSpec::new("hatchpick", "Hatch Pick", pick::run_hatchpick)
.params("{points?: [[x,y]] (internal points), handles?: [hex] (closed objects)} (typed: Points, Objects, oRigin or Hatch, then the picks): the Hatch and Gradient dialog's picks, kept in the session; changes nothing")
.enabled(has_doc)
@@ -340,6 +345,7 @@ pub(crate) fn gradient_name(t: &str) -> Option<&'static str> {
#[derive(Clone)]
struct HatchSettings {
lines: Vec<cadcraft_doc::library::PatternLine>,
pattern: String,
scale: f64,
/// HPSPACE for user-defined patterns. The entity stores it as its scale.
@@ -372,8 +378,10 @@ impl HatchSettings {
angle: f64_or(p, "angle", 0.0).to_radians(),
centered: bool_or(p, "centered", true),
});
let lines = s.doc().ok().and_then(|d| drawing_lines(d, &pattern)).unwrap_or_else(|| patfile::lines_for(&pattern));
let scale = f64_or(p, "scale", hdr.1).max(1e-9);
HatchSettings {
lines,
pattern,
scale,
user_spacing: scale,
@@ -417,12 +425,12 @@ impl HatchSettings {
background: None,
// A user-defined hatch's families come from its angle, spacing and double flag, not
// from a pattern definition; any other hatch takes the loaded pattern's, if any.
pattern_lines: if user_defined { cadcraft_doc::library::user_defined_lines(self.double) } else { patfile::lines_for(&self.pattern) },
pattern_lines: if user_defined { cadcraft_doc::library::user_defined_lines(self.double) } else { self.lines.clone() },
})
}
}
fn make(s: &mut Session, p: &Value, gradient: bool) -> Result<Value> {
fn make(s: &mut Session, p: &Value, gradient: bool, loaded: &[String]) -> Result<Value> {
// A zero or negative pattern scale would be clamped to a near-zero spacing.
size_param(if gradient { "gradient" } else { "hatch" }, p, "scale", false)?;
let cmd = if gradient { "gradient" } else { "hatch" };
@@ -435,7 +443,10 @@ fn make(s: &mut Session, p: &Value, gradient: bool) -> Result<Value> {
if gradient && str_param(p, "name").is_some_and(|t| gradient_name(t).is_none()) {
return Err(bad(cmd, format!("unknown gradient `name`; use one of {}", GRADIENT_NAMES.join(", "))));
}
let st = HatchSettings::from(s, p, gradient);
let mut st = HatchSettings::from(s, p, gradient);
if loaded.iter().any(|n| n.eq_ignore_ascii_case(&st.pattern)) {
st.lines = patfile::lines_for(&st.pattern);
}
// Loops by picked point or selected object: one hatch each when separate.
let mut groups: Vec<Vec<HatchLoop>> = Vec::new();
// Internal points and boundary objects can come together (the dialog's Pick points and
@@ -534,18 +545,19 @@ fn add_hatches(s: &mut Session, st: &HatchSettings, groups: Vec<Vec<HatchLoop>>)
}
fn run_hatch(s: &mut Session, p: &Value) -> Result<Value> {
patfile::load_param(p)?;
let loaded = patfile::load_param(p)?;
// Like the prompt: a name without a definition would be drawn as ANSI31.
if let Some(up) = str_param(p, "pattern").map(str::to_ascii_uppercase)
&& cadcraft_doc::library::pattern(&up).is_none()
&& patfile::user_pattern(&up).is_none()
&& drawing_lines(s.doc()?, &up).is_none()
{
return Err(bad("hatch", format!("unknown pattern {up}: not built in; load it with patternFile or patternText (a .pat file)")));
}
make(s, p, false)
make(s, p, false, &loaded)
}
fn run_gradient(s: &mut Session, p: &Value) -> Result<Value> {
make(s, p, true)
make(s, p, true, &[])
}
fn boundary_at(s: &mut Session, q: Vec2) -> Result<Vec<Handle>> {
@@ -706,13 +718,17 @@ impl HatchM {
self.settings.double = s.last_used.hatch_double;
return Ok(true);
}
let up = match patfile::typed_file(s, t) {
let file = patfile::typed_file(s, t);
let explicit = file.is_some();
let up = match file {
// Nothing loaded from it: the pattern is asked again.
Some(n) if n.is_empty() => return Ok(false),
Some(n) => n,
None => t.to_ascii_uppercase(),
};
if pattern_exists(&up) {
let local = if explicit { None } else { drawing_lines(s.doc()?, &up) };
if local.is_some() || pattern_exists(&up) {
self.settings.lines = local.unwrap_or_else(|| patfile::lines_for(&up));
self.settings.pattern = up.clone();
// A named pattern, SOLID included, is not the user-defined one.
self.settings.double = false;
+205
View File
@@ -0,0 +1,205 @@
//! Capture a rectangular tile from the active drawing space as reusable PAT text.
use cadcraft_doc::{Drawing, EntityKind, Space, library::PatternLine};
use cadcraft_geom::Vec2;
use serde_json::{Value, json};
use crate::cmd::{bad, point_param};
use crate::{Result, Session};
const COMMAND: &str = "hatch.capture";
pub(super) fn run(s: &mut Session, p: &Value) -> Result<Value> {
let corner = |key| point_param(p, key).filter(|q| q.is_finite()).ok_or_else(|| bad(COMMAND, format!("give a finite {key} point [x,y]")));
let a = corner("first")?;
let b = corner("second")?;
let name = match p.get("name") {
None => "CAPTURED_TILE",
Some(v) => v.as_str().ok_or_else(|| bad(COMMAND, "name must be a string"))?,
}
.trim()
.to_ascii_uppercase();
if name.is_empty()
|| name.len() > 31
|| !name.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_')
|| cadcraft_doc::library::is_reserved_pattern_name(&name)
{
return Err(bad(COMMAND, "use a custom pattern name of 1 to 31 letters, digits or underscores"));
}
let lines = capture_lines(s.doc()?, &s.space(), a, b).map_err(|e| bad(COMMAND, e))?;
let mut text = format!("*{name}, Custom pattern\n");
for line in lines {
text.push_str(&format!("{},{},{},{},{}", line.angle, line.origin.0, line.origin.1, line.delta.0, line.delta.1));
for dash in line.dashes {
text.push_str(&format!(",{dash}"));
}
text.push('\n');
}
Ok(json!({"pattern": name, "patternText": text}))
}
/// A PAT family repeats along an integer combination of the two tile edges.
/// The perpendicular neighbour is a second combination with determinant one.
fn captured_family(start: Vec2, end: Vec2, u: Vec2, v: Vec2, m: i32, n: i32) -> PatternLine {
let along = u * f64::from(m) + v * f64::from(n);
let period = along.len();
let dir = along / period;
// Extended Euclid: a*m + b*n = 1, so the neighbour is -b*u + a*v.
let (mut r, mut t) = (m, n);
let (mut a, mut b, mut c, mut d) = (1, 0, 0, 1);
while t != 0 {
let k = r / t;
(r, t) = (t, r % t);
(a, c) = (c, a - k * c);
(b, d) = (d, b - k * d);
}
let neighbour = (v * f64::from(a) - u * f64::from(b)) / f64::from(r);
let len = start.dist(end);
PatternLine {
origin: (start.x, start.y),
angle: dir.y.atan2(dir.x).to_degrees(),
delta: (neighbour.dot(dir), u.cross(v) / period),
dashes: if len >= period { Vec::new() } else { vec![len, len - period] },
}
}
fn capture_lines(d: &Drawing, space: &Space, a: Vec2, b: Vec2) -> std::result::Result<Vec<PatternLine>, &'static str> {
let low = Vec2::new(a.x.min(b.x), a.y.min(b.y));
let w = (a.x - b.x).abs();
let h = (a.y - b.y).abs();
if !w.is_finite() || !h.is_finite() || w < 1e-9 || h < 1e-9 {
return Err("Pick two opposite corners for the tile");
}
let entities = || d.space(space).into_iter().flat_map(|store| store.iter()).filter(|entity| d.is_visible(entity));
let (mut origin, mut u, mut v) = (low, Vec2::new(w, 0.), Vec2::new(0., h));
let mut guides = Vec::new();
for entity in entities() {
let EntityKind::LwPolyline(p) = &entity.kind else { continue };
if !p.closed || p.vertices.len() != 4 || p.vertices.iter().any(|q| q.bulge != 0.) {
continue;
}
let mut corners = [None; 4];
let mut order = [0usize; 4];
for (index, vertex) in p.vertices.iter().enumerate() {
let q = vertex.p;
let right = q.x > low.x + w / 2.;
let top = q.y > low.y + h / 2.;
let target = low + Vec2::new(if right { w } else { 0. }, if top { h } else { 0. });
if (q.x - target.x).abs() <= w * 0.002 && (q.y - target.y).abs() <= h * 0.002 {
order[index] = usize::from(right) + 2 * usize::from(top);
corners[order[index]] = Some(q);
}
}
if let [Some(bl), Some(br), Some(tl), Some(tr)] = corners
&& order.iter().zip(order.iter().cycle().skip(1)).all(|(a, b)| (a ^ b).count_ones() == 1)
&& (bl + (br - bl) + (tl - bl)).dist(tr) < w.min(h) * 1e-8
{
(origin, u, v) = (bl, br - bl, tl - bl);
guides.push(entity.handle);
}
}
let area = u.cross(v);
let coords = |p: Vec2| Vec2::new(p.cross(v) / area, u.cross(p) / area);
let world = |p: Vec2| u * p.x + v * p.y;
let mut families = Vec::new();
let mut add = |a: Vec2, b: Vec2, grid: bool| -> std::result::Result<(), &'static str> {
let (mut start, mut end) = (a - origin, b - origin);
let (s, e) = (coords(start), coords(end));
let inside = |q: Vec2| (-1e-8..=1.00000001).contains(&q.x) && (-1e-8..=1.00000001).contains(&q.y);
if !inside(s) || !inside(e) || start == end {
return Ok(());
}
let delta = e - s;
// Simple LINE geometry retains its original coordinates and short dash period.
let simple = if delta.x.abs() < 1e-14 {
Some((0, delta.y.signum() as i32))
} else {
(1..=128).find_map(|m| {
let m = m * delta.x.signum() as i32;
let n = f64::from(m) * delta.y / delta.x;
(n.abs() <= 128. && (n - n.round()).abs() < 1e-10).then_some((m, n.round() as i32))
})
};
let (mut m, mut n) = if let Some(dir) = simple.filter(|_| !grid) {
dir
} else {
// Shared vertices round identically, including on neighbouring tiles.
let snap = |p: Vec2| Vec2::new((p.x * 2048.).round(), (p.y * 2048.).round());
let (s, e) = (snap(s), snap(e));
if s == e {
return Err("A segment is too small for the tile capture precision.");
}
start = world(s / 2048.);
end = world(e / 2048.);
((e.x - s.x) as i32, (e.y - s.y) as i32)
};
if m < 0 || (m == 0 && n < 0) {
std::mem::swap(&mut start, &mut end);
(m, n) = (-m, -n);
}
let (mut gcd, mut k) = (m.abs(), n.abs());
while k != 0 {
(gcd, k) = (k, gcd % k);
}
if gcd != 0 {
families.push(captured_family(start, end, u, v, m / gcd, n / gcd));
}
Ok(())
};
for entity in entities() {
match &entity.kind {
EntityKind::Line(l) => add(l.a.xy(), l.b.xy(), false)?,
EntityKind::LwPolyline(p) if !guides.contains(&entity.handle) => {
for (i, vertex) in p.vertices.iter().enumerate() {
let next = p.vertices.get(i + 1).or_else(|| if p.closed { p.vertices.first() } else { None });
if let Some(next) = next
&& vertex.bulge == 0.
{
add(vertex.p, next.p, true)?;
}
}
}
_ => {}
}
}
if families.is_empty() {
return Err("No complete line segments in the selected tile.");
}
Ok(families)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn capture_l_from_drawing_without_a_dialog() {
let mut s = Session::new();
s.execute("rectang", &json!({"p1":[30,40], "p2":[40,50]})).unwrap();
for (a, b) in [([32, 42], [35, 42]), ([32, 42], [32, 46]), ([50, 60], [57, 60])] {
s.execute("line", &json!({"points":[a,b]})).unwrap();
}
// An almost coincident hidden guide would shift the origin if it were used.
let guide = s.execute("rectang", &json!({"p1":[30.01,40.01],"p2":[40.01,50.01]})).unwrap();
s.execute("hideobjects", &json!({"handles":[guide["handle"]]})).unwrap();
s.execute("layer.new", &json!({"name":"Hidden detail","current":true})).unwrap();
s.execute("line", &json!({"points":[[33,43],[36,43]]})).unwrap();
let detail = s.doc().unwrap().model.iter().last().unwrap().handle.hex();
s.execute("layer.current", &json!({"name":"0"})).unwrap();
s.execute("layoff", &json!({"handles":[detail]})).unwrap();
let result = s.execute(COMMAND, &json!({"first":[40,50],"second":[30,40],"name":"HEADLESS_L"})).unwrap();
let dest = s.execute("rectang", &json!({"p1":[0,0],"p2":[30,20]})).unwrap();
let mut apply = result;
apply["handles"] = json!([dest["handle"]]);
s.execute("hatch", &apply).unwrap();
let drawing = s.doc().unwrap();
let hatch = drawing.model.iter().find_map(|e| if let EntityKind::Hatch(h) = &e.kind { Some(h) } else { None }).unwrap();
assert_eq!(hatch.pattern, "HEADLESS_L");
assert_eq!(hatch.pattern_lines.len(), 2, "frame and exterior segment excluded");
for (angle, ink) in [(0., 3.), (90., 4.)] {
let line = hatch.pattern_lines.iter().find(|l| (l.angle - angle).abs() < 1e-8).unwrap();
assert_eq!(line.origin, (2., 2.));
assert_eq!(line.dashes, vec![ink, ink - 10.]);
assert!((line.delta.1 - 10.).abs() < 1e-8);
}
}
}
+16 -6
View File
@@ -195,9 +195,9 @@ fn separate(s: &mut Session, handle: Handle) -> Result<Vec<Handle>> {
}
/// Pattern, scale and angle (degrees) from the parameters.
fn properties(h: &mut Hatch, p: &Value) {
fn properties(h: &mut Hatch, p: &Value, local: Option<&[cadcraft_doc::library::PatternLine]>) {
if let Some(v) = str_param(p, "pattern") {
set_pattern(h, v);
set_pattern(h, v, local);
}
if let Some(x) = p.get("scale").and_then(Value::as_f64).filter(|x| x.is_finite() && *x > 0.0) {
h.scale = x;
@@ -222,11 +222,12 @@ pub(crate) fn takes_pattern(h: &Hatch, name: &str) -> bool {
/// Give `h` the pattern called `name` (HATCHEDIT's and Properties' pattern edit); false, and
/// nothing changes, for a blank name or one the hatch can't take ([`takes_pattern`]).
pub(crate) fn set_pattern(h: &mut Hatch, name: &str) -> bool {
pub(crate) fn set_pattern(h: &mut Hatch, name: &str, local: Option<&[cadcraft_doc::library::PatternLine]>) -> bool {
let name = name.trim();
if name.is_empty() || !takes_pattern(h, name) {
if name.is_empty() || (local.is_none() && !takes_pattern(h, name)) {
return false;
}
let keep_lines = h.pattern.eq_ignore_ascii_case(name) && !h.pattern_lines.is_empty();
h.pattern = name.to_ascii_uppercase();
h.solid = h.pattern == "SOLID";
// A named pattern, SOLID included, replaces the gradient fill; the renderer draws the
@@ -237,6 +238,10 @@ pub(crate) fn set_pattern(h: &mut Hatch, name: &str) -> bool {
// any other name is the hatch's own and keeps its definition.
if cadcraft_doc::library::pattern(&h.pattern).is_some() {
h.pattern_lines.clear();
} else if keep_lines {
return true;
} else if let Some(lines) = local {
h.pattern_lines = lines.to_vec();
} else if let Some(user) = super::patfile::user_pattern(&h.pattern) {
h.pattern_lines = user.lines;
}
@@ -479,7 +484,9 @@ pub(super) fn run_hatchedit(s: &mut Session, p: &Value) -> Result<Value> {
}
// Like the prompt: a pattern must be one CADCraft defines, SOLID, or the hatches' own (a
// pattern read from a file keeps its definition).
let local = str_param(p, "pattern").and_then(|n| super::drawing_lines(s.doc().ok()?, n.trim()));
if let Some(up) = str_param(p, "pattern").map(|v| v.trim().to_ascii_uppercase()).filter(|v| !v.is_empty())
&& local.is_none()
&& !defined_pattern(&up)
{
let d = s.doc()?;
@@ -507,7 +514,7 @@ pub(super) fn run_hatchedit(s: &mut Session, p: &Value) -> Result<Value> {
notes.push(format!("Hatch {}: {missing} new boundary loop(s) could not be linked; it is now non-associative.", handle.hex()));
}
}
properties(&mut h, p);
properties(&mut h, p, local.as_deref());
if let Some(g) = &grad {
g.apply(&mut h);
}
@@ -720,7 +727,10 @@ impl Interactive for HatchEditM {
(Ask::Pattern, _) => {
if let Some(t) = text.filter(|t| !t.is_empty()) {
let up = t.to_ascii_uppercase();
if cadcraft_doc::library::pattern(&up).is_none() && super::patfile::user_pattern(&up).is_none() {
if cadcraft_doc::library::pattern(&up).is_none()
&& super::patfile::user_pattern(&up).is_none()
&& super::drawing_lines(s.doc()?, &up).is_none()
{
s.echo(format!("Unknown pattern {up}."));
return Ok(Step::Continue);
}
+54 -5
View File
@@ -9,7 +9,7 @@
use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError};
use cadcraft_doc::library::files::{UserPattern, parse_pat};
use cadcraft_doc::library::{PatternLine, pattern, standard_patterns};
use cadcraft_doc::library::{PatternLine, is_reserved_pattern_name, standard_patterns};
use serde_json::{Value, json};
use super::super::helpers::support_text;
@@ -38,7 +38,7 @@ pub(crate) fn user_pattern_name(name: &str) -> Option<String> {
/// The line families a new hatch of pattern `name` carries: a user pattern's, else none (the
/// library's patterns are drawn and saved from the library).
pub(crate) fn lines_for(name: &str) -> Vec<PatternLine> {
if pattern(name).is_some() {
if is_reserved_pattern_name(name) {
return Vec::new();
}
user_pattern(name).map(|p| p.lines).unwrap_or_default()
@@ -70,6 +70,54 @@ pub fn pattern_choices() -> Vec<PatternChoice> {
v
}
fn embedded(d: &cadcraft_doc::Drawing) -> impl Iterator<Item = &cadcraft_doc::Hatch> {
let stores = std::iter::once(&d.model)
.chain(d.layouts.iter().map(|l| &l.entities))
.chain(d.blocks.values().filter(|b| b.xref_path.is_none()).map(|b| &b.entities));
stores.flat_map(|s| s.iter()).filter_map(|e| match &e.kind {
cadcraft_doc::EntityKind::Hatch(h) if !h.pattern_lines.is_empty() => Some(h),
_ => None,
})
}
pub(crate) fn drawing_lines(d: &cadcraft_doc::Drawing, name: &str) -> Option<Vec<PatternLine>> {
if is_reserved_pattern_name(name) {
return None;
}
embedded(d).find(|h| h.pattern.eq_ignore_ascii_case(name)).map(|h| h.pattern_lines.clone())
}
/// An embedded definition takes precedence over the session library in its own drawing.
pub fn pattern_choices_in(d: &cadcraft_doc::Drawing) -> Vec<PatternChoice> {
let mut choices = pattern_choices();
let mut seen = std::collections::HashSet::new();
for h in embedded(d) {
if !seen.insert(h.pattern.to_ascii_uppercase()) || is_reserved_pattern_name(&h.pattern) {
continue;
}
if let Some(c) = choices.iter_mut().find(|c| c.name.eq_ignore_ascii_case(&h.pattern)) {
c.lines.clone_from(&h.pattern_lines);
} else {
choices.push(PatternChoice { name: h.pattern.clone(), description: String::new(), lines: h.pattern_lines.clone() });
}
}
choices
}
/// Make embedded custom definitions available when opening the hatch manager in an older drawing.
pub fn register_drawing_patterns(d: &cadcraft_doc::Drawing) {
let mut user = store();
let mut known: std::collections::HashSet<_> = user.iter().map(|p| p.name.to_ascii_uppercase()).collect();
for h in embedded(d) {
if user.len() >= MAX_USER_PATTERNS {
break;
}
if !h.pattern_lines.is_empty() && known.insert(h.pattern.to_ascii_uppercase()) && !is_reserved_pattern_name(&h.pattern) {
user.push(UserPattern { name: h.pattern.clone(), description: String::new(), lines: h.pattern_lines.clone() });
}
}
}
/// Add the patterns of a `.pat` file's text (a pattern loaded before under the same name is
/// replaced). Returns the names added and the file's problems.
pub(crate) fn load(text: &str) -> (Vec<String>, Vec<String>) {
@@ -78,7 +126,7 @@ pub(crate) fn load(text: &str) -> (Vec<String>, Vec<String>) {
let mut added = Vec::new();
let mut user = store();
for p in parsed.items {
if pattern(&p.name).is_some() {
if is_reserved_pattern_name(&p.name) {
warnings.push(format!("{} is a built-in pattern; the built-in definition is kept", p.name));
continue;
}
@@ -97,14 +145,15 @@ pub(crate) fn load(text: &str) -> (Vec<String>, Vec<String>) {
}
/// Load the pattern file a HATCH call names (`patternFile` path or `patternText` contents).
pub(super) fn load_param(p: &Value) -> Result<()> {
pub(super) fn load_param(p: &Value) -> Result<Vec<String>> {
if let Some((text, source)) = support_text("hatch", p, "patternFile", "patternText")? {
let (added, warnings) = load(&text);
if added.is_empty() {
return Err(bad("hatch", format!("no hatch pattern could be read from {source}: {}", warnings.join("; "))));
}
return Ok(added);
}
Ok(())
Ok(Vec::new())
}
/// A `.pat` file typed at HATCH's pattern prompt: load it and return the pattern to use (the
+21 -2
View File
@@ -14,7 +14,7 @@ use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
pub(crate) const MAX_PICKS: usize = 1000;
/// The first prompt's keywords: what to pick.
const MODES: [&str; 4] = ["Points", "Objects", "oRigin", "Hatch"];
const MODES: [&str; 5] = ["Points", "Objects", "oRigin", "Hatch", "TileRect"];
/// What HATCHPICK picks.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
@@ -22,6 +22,8 @@ pub enum PickMode {
/// Internal points, each inside a closed boundary.
#[default]
Points,
/// Two opposite corners of a rectangular custom-pattern tile.
TileRect,
/// Closed boundary objects.
Objects,
/// One point: the pattern origin.
@@ -44,6 +46,7 @@ pub struct HatchPicks {
fn mode_named(t: &str) -> Option<PickMode> {
Some(match t.trim().to_ascii_lowercase().as_str() {
"points" | "p" => PickMode::Points,
"tilerect" | "tile" => PickMode::TileRect,
"objects" | "o" => PickMode::Objects,
"origin" | "r" => PickMode::Origin,
"hatch" | "h" => PickMode::Hatch,
@@ -134,6 +137,10 @@ impl Interactive for HatchPickM {
match self.mode {
None => Prompt::new("Enter what to pick", Accept::TEXT).kw(&MODES),
Some(PickMode::Points) => Prompt::new("Pick internal point", Accept::POINT).kw(&["Undo"]),
Some(PickMode::TileRect) => {
Prompt::new(if self.picks.is_empty() { "Pick first corner of tile" } else { "Pick opposite corner of tile" }, Accept::POINT)
.kw(&["Undo"])
}
Some(PickMode::Objects) => Prompt::new("Select objects", Accept::SELECT).kw(&["Undo"]),
Some(PickMode::Origin) => Prompt::new("Specify the pattern origin", Accept::POINT),
Some(PickMode::Hatch) => Prompt::new("Select hatch object", Accept::SELECT),
@@ -150,12 +157,13 @@ impl Interactive for HatchPickM {
};
match (mode, i) {
(_, Input::Cancel) => Ok(Step::Cancel),
(PickMode::Points | PickMode::Objects, Input::Keyword(k)) if k == "Undo" => {
(PickMode::Points | PickMode::TileRect | PickMode::Objects, Input::Keyword(k)) if k == "Undo" => {
if self.picks.pop().is_none() {
s.echo("Nothing to undo.");
}
Ok(Step::Continue)
}
(PickMode::TileRect, Input::Enter) => Ok(Step::Continue),
(PickMode::Points | PickMode::Objects, Input::Enter) => {
self.keep(s, mode);
Ok(Step::Done)
@@ -174,6 +182,17 @@ impl Interactive for HatchPickM {
}
Ok(Step::Continue)
}
(PickMode::TileRect, Input::Point(q)) => {
if self.count() < 2 {
self.picks.push(Pick::Point(q, Vec::new()));
}
if self.count() >= 2 {
self.keep(s, mode);
Ok(Step::Done)
} else {
Ok(Step::Continue)
}
}
(PickMode::Objects, Input::Pick(hs)) => {
let room = MAX_PICKS.saturating_sub(self.count());
let closed: Vec<Handle> = {
+2 -1
View File
@@ -281,7 +281,7 @@ pub(crate) fn z_at(s: &Session, p: Vec2) -> f64 {
}
/// The Z of `e` at the point of it nearest `p` (seen from above), when it has one there.
fn entity_z(e: &Entity, p: Vec2) -> Option<f64> {
pub(crate) fn entity_z(e: &Entity, p: Vec2) -> Option<f64> {
let on_segment = |a: Vec3, b: Vec3| {
let d = b.xy() - a.xy();
let l2 = d.dot(d);
@@ -308,6 +308,7 @@ fn entity_z(e: &Entity, p: Vec2) -> Option<f64> {
// Read in world coordinates already.
EntityKind::Circle(c) => Some(c.center.z),
EntityKind::Arc(a) => Some(a.center.z),
EntityKind::Ellipse(el) => Some(el.center.z),
EntityKind::Text(t) | EntityKind::AttDef(cadcraft_doc::Attrib { text: t, .. }) => Some(t.insert.z),
EntityKind::MText(t) => Some(t.insert.z),
EntityKind::Insert(i) => Some(i.insert.z),
+58
View File
@@ -603,6 +603,64 @@ fn plot_path_extension_picks_the_format_like_export() {
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn osnap_in_mspace_skips_vplayer_frozen_layers() {
let mut s = Session::new();
s.execute("layer.new", &json!({"name": "Hidden"})).unwrap();
s.execute("line", &json!({"points": [[60, -25], [70, -25]]})).unwrap();
let line_h = s.doc().unwrap().model.iter().last().unwrap().handle;
s.execute("properties.set", &json!({"handles": [line_h], "layer": "Hidden"})).unwrap();
s.execute("layout.set", &json!({"name": "Layout1"})).unwrap();
s.execute("mview", &json!({"p1": [20, 20], "p2": [220, 120]})).unwrap();
let vp_h = viewports(&s, "Layout1").last().unwrap().0;
s.execute("vplayer", &json!({"handles": [vp_h], "freeze": ["Hidden"]})).unwrap();
s.execute("mspace", &json!({"handle": vp_h})).unwrap();
let ap = s.pixel_size() * s.settings.aperture.max(1.0);
let d = ap * 0.5;
let model_before = s.doc().unwrap().model.len();
for (ovr, pt, name) in [
("end", format!("{},-25", 60.0 + d), "Endpoint"),
("mid", format!("{},-25", 65.0 + d), "Midpoint"),
("nea", format!("63,{}", -25.0 + d), "Nearest"),
] {
s.cmdline("line").unwrap();
s.cmdline(ovr).unwrap();
s.cmdline(&pt).unwrap();
assert_eq!(
s.log.last().map(String::as_str),
Some(format!("No {name} found for specified point.").as_str()),
"{ovr} should not snap to a line on a VPLAYER-frozen layer; log: {:?}",
s.log
);
s.cmdline("").unwrap();
}
assert_eq!(s.doc().unwrap().model.len(), model_before, "no new line should be created");
// Running osnaps through snap_cursor must also ignore the VPLAYER-frozen layer.
s.settings.osmode = crate::snap::mode::END | crate::snap::mode::MID | crate::snap::mode::NEA;
let cs = s.snap_cursor(
cadcraft_geom::Vec2::new(60.0 + d, -25.0),
&crate::snap::tracking::CursorQuery { base: None, deferred: false, corner: false, aperture: ap, tol: ap, now: 0.0, shift: false },
);
assert!(cs.snap.is_none(), "running osnap should not snap to a VPLAYER-frozen line: {:?}", cs.snap);
// A block reference on layer "0" containing an entity on "Hidden" must also not snap.
s.execute("block", &json!({"name": "B", "base": [60, -25], "handles": [line_h]})).unwrap();
let model_with_block = s.doc().unwrap().model.len();
s.cmdline("line").unwrap();
s.cmdline("end").unwrap();
s.cmdline(&format!("{},-25", 60.0 + d)).unwrap();
assert_eq!(
s.log.last().map(String::as_str),
Some("No Endpoint found for specified point."),
"end should not snap to a block entity on a VPLAYER-frozen layer; log: {:?}",
s.log
);
s.cmdline("").unwrap();
assert_eq!(s.doc().unwrap().model.len(), model_with_block);
}
#[test]
fn layout_set_frames_extents_away_from_origin() {
let mut s = Session::new();
+43 -2
View File
@@ -204,6 +204,7 @@ fn set_override(dm: &mut cadcraft_doc::Dimension, field: &'static str, v: Value)
/// A `properties.set` call, checked before any object changes: the values every object takes,
/// and what the edits need to know beforehand.
struct Call<'a> {
hatch_lines: Option<Vec<cadcraft_doc::library::PatternLine>>,
p: &'a Value,
color: Option<Color>,
transparency: Option<Transparency>,
@@ -351,8 +352,10 @@ pub(super) fn run_set(s: &mut Session, p: &Value) -> Result<Value> {
}
}
}
let hatch_lines = str_param(p, "pattern").and_then(|n| crate::cmd::hatch::drawing_lines(d, n.trim()));
// A pattern must be one each hatch can take, as HATCHEDIT refuses others.
if let Some(v) = str_param(p, "pattern").filter(|v| !v.trim().is_empty())
&& hatch_lines.is_none()
&& hs.iter().any(|h| matches!(d.entity(*h).map(|e| &e.kind), Some(EntityKind::Hatch(x)) if !crate::cmd::hatch::takes_pattern(x, v)))
{
return Err(bad("properties.set", format!("unknown pattern {}", v.trim().to_ascii_uppercase())));
@@ -363,7 +366,7 @@ pub(super) fn run_set(s: &mut Session, p: &Value) -> Result<Value> {
}
let prep = Prepared::new(d, p, &hs);
let anno_scale = d.current_anno_scale();
let c = Call { p, color, transparency, thickness, lineweight, linetype, dim_style, text_style, dim_vars, prep, anno_scale };
let c = Call { hatch_lines, p, color, transparency, thickness, lineweight, linetype, dim_style, text_style, dim_vars, prep, anno_scale };
// A failed call changes nothing (a command's error doesn't undo what it did), so the drawing
// is taken for writing, and the layer made, only after every check.
let d = s.doc_mut()?;
@@ -805,7 +808,7 @@ fn dimension_posts(dm: &mut Dimension, c: &Call<'_>, used: &mut Used<'_>) {
fn hatch(ha: &mut Hatch, c: &Call<'_>, used: &mut Used<'_>) {
// HATCHEDIT's pattern edit (a blank name changes nothing, so it's ignored).
if let Some(v) = str_param(c.p, "pattern")
&& crate::cmd::hatch::set_pattern(ha, v)
&& crate::cmd::hatch::set_pattern(ha, v, c.hatch_lines.as_deref())
{
used.insert("pattern");
}
@@ -818,3 +821,41 @@ fn hatch(ha: &mut Hatch, c: &Call<'_>, used: &mut Used<'_>) {
used.insert("angle");
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The hatch of a drawing, by handle.
fn hatch_of(s: &Session, h: Handle) -> Hatch {
match &s.doc().unwrap().entity(h).unwrap().kind {
EntityKind::Hatch(ha) => ha.clone(),
other => panic!("{h:?} is a {}", other.type_name()),
}
}
#[test]
fn setting_the_same_pattern_keeps_the_lines_the_hatch_carries() {
// The loaded patterns are session-wide: HATCH.PATTERNS can clear them, and a drawing
// reopened without its .pat file leaves the hatch's own families as the only copy.
// Setting the name the hatch already carries must keep them (#1232).
let mut s = Session::new();
let kind = EntityKind::Hatch(
serde_json::from_value(json!({
"pattern": "MYGRID",
"solid": false,
"loops": [],
"patternLines": [{"angle": 0.0, "origin": [0.0, 0.0], "delta": [0.0, 0.5], "dashes": []}],
}))
.unwrap(),
);
let h = s.add_entity(kind).unwrap();
s.execute("properties.set", &json!({ "handles": [h.hex()], "pattern": "mygrid" })).unwrap();
let ha = hatch_of(&s, h);
assert_eq!(ha.pattern, "MYGRID");
assert_eq!(ha.pattern_lines.len(), 1, "the definition the hatch carries was dropped");
// A library pattern is drawn from the library: it has no lines of its own.
s.execute("properties.set", &json!({ "handles": [h.hex()], "pattern": "ANSI31" })).unwrap();
assert!(hatch_of(&s, h).pattern_lines.is_empty());
}
}
@@ -241,6 +241,7 @@ pub const NO_FILES: &[&str] = &[
"gradient",
"boundary",
"region",
"hatch.capture",
"hatchedit",
"hatchgenerateboundary",
"hatchpick",
+15 -4
View File
@@ -46,7 +46,7 @@ pub mod units;
use std::sync::Arc;
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, Space};
use cadcraft_geom::{Bounds2, Vec2};
use cadcraft_geom::{Bounds2, Vec2, Vec3};
use serde::{Deserialize, Serialize};
use serde_json::Value;
@@ -57,7 +57,7 @@ pub use cadcraft_geom as geom;
pub use cadcraft_render as render;
pub use cmd::blocks::WblockPicks;
pub use cmd::blocks::attedit::{AttributeRow, attributes};
pub use cmd::hatch::{HatchPicks, PatternChoice, PickMode, pattern_choices};
pub use cmd::hatch::{HatchPicks, PatternChoice, PickMode, pattern_choices, pattern_choices_in, register_drawing_patterns};
pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command};
pub use prompt::{Accept, AttribAsk, AttribEntry, DisplayOnly, Drag, EditorKind, Input, Interactive, Picker, Prompt, Step, TextEditor};
@@ -138,6 +138,12 @@ pub struct Session {
pub(crate) last_paste_table: Option<(String, Option<f64>)>,
/// LASTPOINT.
pub last_point: Vec2,
/// LASTPOINT's Z, as `(last_point, z)`: it holds only while `last_point` is still that point
/// (whatever sets `last_point` without a Z puts it back on z = 0). See [`Session::last_point3`].
last_point_z: (Vec2, f64),
/// The Z of the point being entered: the third number of a typed point
/// ([`prompt::parse_point3_with`]), 0 for a picked one. See [`Session::point_z`].
point_z: f64,
/// AREA and PERIMETER: the last area AREA or MEASUREGEOM measured (in their Add and Subtract
/// modes the running total) and that area's perimeter. Not saved, as in AutoCAD.
pub area: f64,
@@ -241,6 +247,8 @@ impl Session {
last_command: None,
last_paste_table: None,
last_point: Vec2::ZERO,
last_point_z: (Vec2::ZERO, 0.0),
point_z: 0.0,
area: 0.0,
perimeter: 0.0,
distance: 0.0,
@@ -284,9 +292,12 @@ impl Session {
pub fn doc(&self) -> Result<&Drawing> {
Ok(&self.state()?.doc)
}
/// Copy-on-write access to the drawing.
/// Copy-on-write access to the drawing. The revision changes too: a drawing nothing else holds
/// is edited in place, so a cache keyed by the drawing's pointer alone would miss the edit.
pub fn doc_mut(&mut self) -> Result<&mut Drawing> {
Ok(Arc::make_mut(&mut self.state_mut()?.doc))
let st = self.state_mut()?;
st.revision += 1;
Ok(Arc::make_mut(&mut st.doc))
}
/// Settings for the active drawing, without caching drawing variables in the profile.
pub fn drafting_settings(&self) -> Settings {
+59 -17
View File
@@ -75,8 +75,8 @@ impl Axes {
pub enum Frame {
/// `FROM`: the base point once given, then the offset point.
From { base: Option<Vec2> },
/// `M2P`/`MTP`: the first point once given, then the second.
Mid { first: Option<Vec2> },
/// `M2P`/`MTP`: the first point once given (with its Z), then the second.
Mid { first: Option<Vec2>, z: f64 },
/// A point filter: the point to take `keep` from once given, then the rest.
Filter { keep: Axes, first: Option<Vec2> },
/// `<a`: the next point lies on the line through `base` in direction `dir` (a unit vector).
@@ -126,14 +126,36 @@ pub fn snap_name(m: u32) -> &'static str {
mode::ALL.iter().find(|(b, _)| *b == m).map_or("None", |(_, n)| *n)
}
/// The candidate snaps near `cursor` for Tab cycling: every object snap within the aperture, the
/// one [`crate::snap::osnap`] picks first and the rest in its order (specific snaps nearest
/// first, then deferred snaps, then Nearest), without repeats.
/// The candidate snaps near `cursor` for Tab cycling: the snap [`crate::snap::osnap`] picks
/// first, then every other snap of the modes in `osmode` under the aperture (each endpoint of
/// each object, each intersection …; [`crate::snap::osnap_all`]), best first, without repeats.
pub fn snap_candidates(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Vec<SnapHit> {
if osmode & !mode::HATCH == 0 || osmode & mode::OFF != 0 {
snap_candidates_with_frozen(d, space, cursor, aperture, osmode, base, deferred, &[])
}
/// [`snap_candidates`] skipping entities (and block leaves) on `frozen` layers in `space`.
#[allow(clippy::too_many_arguments)]
pub fn snap_candidates_with_frozen(
d: &Drawing,
space: &Space,
cursor: Vec2,
aperture: f64,
osmode: u32,
base: Option<Vec2>,
deferred: bool,
frozen: &[String],
) -> Vec<SnapHit> {
// A base that is not a number would give meaningless perpendiculars and tangents.
if osmode & !mode::HATCH == 0 || osmode & mode::OFF != 0 || base.is_some_and(|b| !b.is_finite()) {
return Vec::new();
}
crate::snap::osnap_all(d, space, cursor, aperture, osmode, base, deferred)
let mut out: Vec<SnapHit> = crate::snap::osnap_with_frozen(d, space, cursor, aperture, osmode, base, deferred, frozen).into_iter().collect();
for h in crate::snap::osnap_all_with_frozen(d, space, cursor, aperture, osmode, base, deferred, frozen) {
if !out.iter().any(|o| o.same(&h, aperture)) {
out.push(h);
}
}
out
}
/// Strip the international (`_`) and transparent (`'`) prefixes a modifier may be typed with.
@@ -153,8 +175,8 @@ impl Session {
self.point_mods.iter().fold(cmd, |p, f| match *f {
Frame::From { base: None } => Prompt::new("Base point", point),
Frame::From { base: Some(b) } => Prompt::new("<Offset>", point).base(b),
Frame::Mid { first: None } => Prompt::new("First point of mid", point),
Frame::Mid { first: Some(f) } => Prompt::new("Second point of mid", point).base(f),
Frame::Mid { first: None, .. } => Prompt::new("First point of mid", point),
Frame::Mid { first: Some(f), .. } => Prompt::new("Second point of mid", point).base(f),
Frame::Filter { keep, first: None } => Prompt::new(format!("{} of", keep.name()), point).base_opt(p.base),
Frame::Filter { keep, first: Some(_) } => Prompt::new(format!("(need {})", keep.need()), point).base_opt(p.base),
Frame::TempTrack => Prompt::new("Specify temporary OTRACK point", point),
@@ -200,7 +222,7 @@ impl Session {
let b = b.to_ascii_lowercase();
match b.as_str() {
"from" | "fro" => Some(Frame::From { base: None }),
"m2p" | "mtp" => Some(Frame::Mid { first: None }),
"m2p" | "mtp" => Some(Frame::Mid { first: None, z: 0.0 }),
"tt" => Some(Frame::TempTrack),
// TK, or TRACKING from three letters (TRA, TRACK).
"tk" => Some(Frame::Track { last: None }),
@@ -300,7 +322,16 @@ impl Session {
/// A point given while modifiers are pending: complete the top frame, and when it has its
/// point, hand that to the frame (or command) below.
pub(crate) fn modifier_point(&mut self, mut p: Vec2) -> Result<()> {
pub(crate) fn modifier_point(&mut self, p: Vec2) -> Result<()> {
// The frames below may give the point another Z (a snap's, a midpoint's); the next
// point starts from the Z it comes with.
let z = self.point_z;
let result = self.modifier_point_frames(p);
self.point_z = z;
result
}
fn modifier_point_frames(&mut self, mut p: Vec2) -> Result<()> {
if !p.is_finite() {
self.echo("Invalid point.");
return Ok(());
@@ -313,8 +344,8 @@ impl Session {
self.last_point = p;
return Ok(());
}
Frame::Mid { first: None } => {
self.point_mods.push(Frame::Mid { first: Some(p) });
Frame::Mid { first: None, .. } => {
self.point_mods.push(Frame::Mid { first: Some(p), z: self.point_z });
self.last_point = p;
return Ok(());
}
@@ -336,22 +367,33 @@ impl Session {
}
// The offset point is already measured from the base (`@` reads the last point).
Frame::From { base: Some(_) } => {}
Frame::Mid { first: Some(f) } => p = (f + p) * 0.5,
Frame::Mid { first: Some(f), z } => {
p = (f + p) * 0.5;
// Midway in Z too: between two snapped levels, or typed `x,y,z` points.
self.point_z = (z + self.point_z) * 0.5;
}
Frame::Filter { keep, first: Some(f) } => p = keep.combine_in(&self.input_ucs(), f, p),
Frame::Angle { base, dir } => p = base + dir * (p - base).dot(dir),
Frame::Snap { mode: 0 } => {}
Frame::Snap { mode } => {
// Snap the point with this mode alone, within the aperture.
let prompt = self.current_prompt();
let space = self.space();
let (doc, space, frozen) = {
let st = self.state()?;
(st.doc.clone(), st.edit_space(), st.viewport_frozen().to_vec())
};
let aperture = self.pixel_size() * self.settings.aperture.max(1.0);
let hatch = if self.settings.osnaphatch { mode::HATCH } else { 0 };
let base = prompt.as_ref().and_then(|q| q.base);
let deferred = prompt.as_ref().is_some_and(|q| q.deferred);
let hit = crate::snap::osnap(self.doc()?, &space, p, aperture, mode | hatch, base, deferred);
let hit = crate::snap::osnap_with_frozen(&doc, &space, p, aperture, mode | hatch, base, deferred, &frozen);
match hit {
Some(h) if self.point_mods.is_empty() => return self.input_snapped(h),
Some(h) => p = h.point,
Some(h) => {
// The Z of what it snapped to, as for a snapped pick (OSNAPZ-aware).
self.point_z = if h.viewport.is_none() { self.snap_z(&h) } else { 0.0 };
p = h.point;
}
None => {
self.echo(format!("No {} found for specified point.", snap_name(mode)));
return Ok(());
+67 -10
View File
@@ -1,7 +1,7 @@
//! Interactive commands: prompts, inputs and the command-line coordinate grammar.
use cadcraft_doc::{EntityKind, Handle};
use cadcraft_geom::{Mat3, Vec2};
use cadcraft_geom::{Mat3, Vec2, Vec3};
use serde::Serialize;
use crate::{Result, Session};
@@ -76,8 +76,9 @@ pub struct Prompt {
/// Rubber-band origin (for direct distance entry, ortho and polar).
pub base: Option<Vec2>,
/// The command resolves deferred tangent/perpendicular snaps ([`Input::Deferred`]) at this
/// prompt (a point with no base yet, e.g. the first point of a line). Elsewhere a deferred
/// pick arrives as the plain point it was picked at.
/// prompt (a point with no base yet, e.g. the first point of a line; with a base, only
/// tangents, e.g. a circle's radius). Elsewhere a deferred pick arrives as the plain point it
/// was picked at.
pub deferred: bool,
/// The base is a rectangle's first corner (ZOOM Window, PLOTWINDOW, RECTANG, ARRAYRECT's unit
/// cell, MTEXT): ortho does not bend the opposite corner, so the rectangle keeps its area.
@@ -511,16 +512,33 @@ pub fn parse_point(text: &str, last: Vec2) -> Option<Vec2> {
}
/// `parse_point` with polar angles read per `angles` (AUNITS, ANGBASE, ANGDIR); `d<<a` and
/// `d<<<a` measure from +X counterclockwise (in degrees and in AUNITS).
/// `d<<<a` measure from +X counterclockwise (in degrees and in AUNITS). A third number is
/// accepted and dropped; [`parse_point3_with`] keeps it.
pub fn parse_point_with(text: &str, last: Vec2, angles: &crate::units::AngleSettings) -> Option<Vec2> {
parse_point_in(text, last, angles, &crate::ucs::UcsFrame::WORLD)
}
/// [`parse_point_with`] keeping Z: `x,y,z` and `#x,y,z` give that Z, `x,y` and `d<a` lie at
/// z = 0, and the relative forms add to `last`'s Z (`@dx,dy,dz`; `@dx,dy` and `@d<a` keep it,
/// as in AutoCAD).
pub fn parse_point3_with(text: &str, last: Vec3, angles: &crate::units::AngleSettings) -> Option<Vec3> {
parse_point3_in(text, last, angles, &crate::ucs::UcsFrame::WORLD)
}
/// `parse_point_with` in a UCS: coordinates are UCS coordinates (`x,y` from its origin along its
/// axes, `@dx,dy` along its axes), and polar angles are measured as `angles` says (which carries
/// the UCS rotation, [`crate::units::AngleSettings::ucs`]). A `*` prefix reads the point in
/// world coordinates instead. `last` and the result are world points.
/// world coordinates instead. `last` and the result are world points. A third number is
/// accepted and dropped; [`parse_point3_in`] keeps it.
pub fn parse_point_in(text: &str, last: Vec2, angles: &crate::units::AngleSettings, ucs: &crate::ucs::UcsFrame) -> Option<Vec2> {
parse_point3_in(text, last.to3(0.0), angles, ucs).map(Vec3::xy)
}
/// [`parse_point_in`] keeping Z, as [`parse_point3_with`] does: `x,y,z` is a UCS point (its Z
/// measured along the UCS Z axis, from its origin), `x,y` and `d<a` lie at world z = 0, and the
/// relative forms add their Z to `last`'s (`@dx,dy` and `@d<a` keep it). `last` and the result
/// are world points.
pub fn parse_point3_in(text: &str, last: Vec3, angles: &crate::units::AngleSettings, ucs: &crate::ucs::UcsFrame) -> Option<Vec3> {
let t = text.trim();
if t.is_empty() {
return None;
@@ -554,7 +572,7 @@ pub fn parse_point_in(text: &str, last: Vec2, angles: &crate::units::AngleSettin
// `d<<a` / `d<<<a`: the override prefixes keep their `<<` / `<<<`.
let ang = if a.starts_with('<') { angles.direction(&format!("<{a}"))? } else { angles.direction(a)? };
let v = Vec2::from_angle(ang) * dist;
if rel { last + v } else { frame.origin.xy() + v }
if rel { (last.xy() + v).to3(last.z) } else { (frame.origin.xy() + v).to3(0.0) }
} else {
let parts: Vec<&str> = body.split(',').collect();
if parts.len() < 2 || parts.len() > 3 {
@@ -562,11 +580,18 @@ pub fn parse_point_in(text: &str, last: Vec2, angles: &crate::units::AngleSettin
}
let x = crate::units::parse_distance(parts.first()?)?;
let y = crate::units::parse_distance(parts.get(1)?)?;
if let Some(z) = parts.get(2) {
crate::units::parse_distance(z)?;
}
let z = match parts.get(2) {
Some(z) => Some(crate::units::parse_distance(z)?),
None => None,
};
let v = Vec2::new(x, y);
if rel { last + frame.vec_to_wcs(v) } else { frame.to_wcs(v) }
// The UCS Z axis in world coordinates (straight up for the planar UCSs points are read in).
let dz = frame.z().z;
if rel {
(last.xy() + frame.vec_to_wcs(v)).to3(last.z + z.unwrap_or(0.0) * dz)
} else {
frame.to_wcs(v).to3(z.map_or(0.0, |z| frame.origin.z + z * dz))
}
};
p.is_finite().then_some(p)
}
@@ -617,6 +642,38 @@ mod tests {
assert_eq!(latin.match_keyword("Θ").as_deref(), Some("Undo"), "a Greek-layout shortcut still works");
}
#[test]
fn points_with_z() {
let last = Vec3::new(10.0, 10.0, 1.0);
let p3 = |t: &str| parse_point3_with(t, last, &crate::units::AngleSettings::default());
assert_eq!(p3("1,2"), Some(Vec3::new(1.0, 2.0, 0.0)));
assert_eq!(p3("1,2,3"), Some(Vec3::new(1.0, 2.0, 3.0)));
assert_eq!(p3("#10,20,30"), Some(Vec3::new(10.0, 20.0, 30.0)));
assert_eq!(p3("*1,2,3"), Some(Vec3::new(1.0, 2.0, 3.0)));
// Relative input adds to the last point's Z; without a third number Z stays.
assert_eq!(p3("@0,0,5"), Some(Vec3::new(10.0, 10.0, 6.0)));
assert_eq!(p3("@1,2"), Some(Vec3::new(11.0, 12.0, 1.0)));
assert_eq!(p3("@"), Some(last));
assert!(p3("@5<90").is_some_and(|p| (p - Vec3::new(10.0, 15.0, 1.0)).len() < 1e-9));
assert!(p3("5<0").is_some_and(|p| (p - Vec3::new(5.0, 0.0, 0.0)).len() < 1e-9));
// Hostile forms: rejected, no panic.
for t in ["1,2,3,4", "1,2,", "1,2,z", "1,2,inf", "1,2,NaN", ",,", "@,,1"] {
assert_eq!(p3(t), None, "{t}");
}
let far = Vec3::new(0.0, 0.0, f64::MAX);
assert_eq!(parse_point3_with("@0,0,1e308", far, &crate::units::AngleSettings::default()), None);
// The 2D form is unchanged.
assert_eq!(parse_point("3,4,5", Vec2::new(10.0, 10.0)), Some(Vec2::new(3.0, 4.0)));
// In a UCS: a typed Z is measured from its origin; `x,y` lies at z = 0; `@` adds to `last`.
let ucs = crate::ucs::UcsFrame::new(Vec3::new(5.0, 0.0, 2.0), Vec3::new(0.0, 1.0, 0.0), Vec3::new(-1.0, 0.0, 0.0)).unwrap();
let angles = crate::units::AngleSettings::default();
let u3 = |t: &str| parse_point3_in(t, Vec3::new(0.0, 0.0, 4.0), &angles, &ucs);
assert!(u3("1,0,3").is_some_and(|p| (p - Vec3::new(5.0, 1.0, 5.0)).len() < 1e-9));
assert!(u3("1,0").is_some_and(|p| (p - Vec3::new(5.0, 1.0, 0.0)).len() < 1e-9));
assert!(u3("@1,0,1").is_some_and(|p| (p - Vec3::new(0.0, 1.0, 5.0)).len() < 1e-9));
assert!(u3("*1,0,3").is_some_and(|p| (p - Vec3::new(1.0, 0.0, 3.0)).len() < 1e-9));
}
#[test]
fn keywords() {
let p = Prompt::new("Specify next point", Accept::POINT).kw(&["Undo", "Close"]);
+2 -2
View File
@@ -3,8 +3,8 @@ use super::error::{EngineError, Result};
use super::running::{PendingWindow, Running};
use super::view::View;
use super::{
Arc, Bounds2, Drag, Drawing, Entity, Handle, Input, Origin, Prompt, Session, Space, Step, Value, Vec2, assoc, cmd, find_command, guard, lisp,
pointmod, prompt, select, snap, sysvars, units,
Arc, Bounds2, Drag, Drawing, Entity, Handle, Input, Origin, Prompt, Session, Space, Step, Value, Vec2, Vec3, assoc, cmd, find_command, guard,
lisp, pointmod, prompt, select, snap, sysvars, units,
};
mod cmdline;
+16 -5
View File
@@ -1,4 +1,4 @@
use super::{EngineError, Input, Result, Session, Value, Vec2, cmd, lisp, prompt, snap, units};
use super::{EngineError, Input, Result, Session, Value, Vec2, Vec3, cmd, lisp, prompt, snap, units};
impl Session {
/// Process one line typed at the command line (Enter pressed). Spaces separate inputs as in a
@@ -128,8 +128,16 @@ impl Session {
lisp::value::Value::Real(r) => self.typed_token(&format!("{r}"), false),
lisp::value::Value::Str(s) => self.typed_token(&s, false),
other => match other.as_point() {
// A point from LISP is in the current UCS, as typed coordinates are.
Some(p) => self.input(Input::Point(self.input_ucs().to_wcs(Vec2::new(p[0], p[1])))),
// A point from LISP is in the current UCS, as typed coordinates are, and a 3D
// point keeps its Z, as a typed `x,y,z` does.
Some(p) => {
let ucs = self.input_ucs();
let xy = ucs.to_wcs(Vec2::new(p[0], p[1]));
self.point_z = p.get(2).copied().filter(|z| z.is_finite()).map_or(0.0, |z| ucs.to_wcs3(Vec3::new(p[0], p[1], z)).z);
let r = self.input(Input::Point(xy));
self.point_z = 0.0;
r
}
None => {
self.echo(format!("Invalid input: {}", lisp::value::to_text(&other, true)));
Ok(())
@@ -169,9 +177,12 @@ impl Session {
}
if prompt.accept.point {
self.note_tilted_ucs();
if let Some(p) = self.parse_typed_point(tt, self.last_point) {
if let Some(p) = self.parse_typed_point3(tt, self.last_point3()) {
self.last_polar = prompt::parse_polar_text(tt, &self.angle_settings());
return self.input(Input::Point(p));
self.point_z = p.z;
let r = self.input(Input::Point(p.xy()));
self.point_z = 0.0;
return r;
}
// Direct distance entry along the tracking path the cursor is on, from the point it
// comes from (an acquired or temporary tracking point needs no base point).
+42 -1
View File
@@ -2,7 +2,7 @@ use crate::DisplayOnly;
use super::{
Arc, Bounds2, Drag, Drawing, EngineError, Entity, Handle, Input, Origin, PendingWindow, Prompt, Result, Running, Session, Snapshot, Step, Value,
Vec2, assoc, cmd, find_command, guard, pointmod, select, snap, sysvars,
Vec2, Vec3, assoc, cmd, find_command, guard, pointmod, select, snap, sysvars,
};
impl Session {
@@ -219,11 +219,51 @@ impl Session {
pub fn input_snapped(&mut self, hit: snap::SnapHit) -> Result<()> {
let source = hit.viewport.filter(|_| self.point_mods.iter().all(|f| matches!(f, pointmod::Frame::Snap { mode } if *mode != 0)));
let previous = std::mem::replace(&mut self.picked_viewport, source);
// An object snap gives the Z of what it snapped to, as in AutoCAD: a survey point's
// level, a contour's elevation (OSNAPZ 1 uses the current elevation instead). A point
// picked through a layout viewport stays at z = 0.
self.point_z = if hit.viewport.is_none() && hit.mode != 0 { self.snap_z(&hit) } else { 0.0 };
let result = self.input(hit.input());
self.point_z = 0.0;
self.picked_viewport = previous;
result
}
/// The Z an object snap gives a point: the Z of the object it snapped to at that point (of
/// the object found there, [`cmd::inquiry::z_at`], when the snap doesn't say), or ELEVATION
/// with OSNAPZ on.
pub(crate) fn snap_z(&self, hit: &snap::SnapHit) -> f64 {
let elevation = self.doc().map(|d| d.header.f64("ELEVATION", 0.0)).unwrap_or(0.0);
let on_source = || {
let d = self.doc().ok()?;
let src = hit.source?;
let z = match src.leaf {
// An object inside a block reference: its Z where the snap lies, placed by the reference.
Some(l) => {
let e = d.blocks.values().find_map(|b| b.entities.get(l.handle))?;
cmd::inquiry::entity_z(e, l.to_block.apply(hit.point)).map(|z| l.z0 + l.zs * z)
}
None => cmd::inquiry::entity_z(d.entity(src.handle)?, hit.point),
};
z.filter(|z| z.is_finite())
};
let z = if self.settings.osnapz { elevation } else { on_source().unwrap_or_else(|| cmd::inquiry::z_at(self, hit.point)) };
if z.is_finite() { z } else { 0.0 }
}
/// LASTPOINT with its Z (z = 0 unless the last point was typed with one, or relative to one).
pub fn last_point3(&self) -> Vec3 {
let (p, z) = self.last_point_z;
self.last_point.to3(if p == self.last_point { z } else { 0.0 })
}
/// The Z of the point a command is being given ([`Input::Point`] carries only X and Y): the
/// third number of a typed `x,y,z` or `@dx,dy,dz` (relative forms add to LASTPOINT's Z), 0
/// for a picked point. Commands that build 3D geometry (3DPOLY) read it with the point.
pub fn point_z(&self) -> f64 {
self.point_z
}
/// Give an input to the running command. With no command running, `Enter` repeats the last
/// command (as in AutoCAD) and points do nothing. A LISP routine waiting in a `get…`
/// function takes the input instead; one paused in `command` carries on after it.
@@ -429,6 +469,7 @@ impl Session {
Some(i) => {
if let Input::Point(p) = &i {
self.last_point = *p;
self.last_point_z = (*p, self.point_z);
if let Some(b) = base.filter(|b| b.is_finite() && p.is_finite() && b.dist(*p) > 1e-12) {
self.last_segment = Some((b, *p));
}
+4
View File
@@ -16,6 +16,9 @@ pub struct Settings {
pub snapunit: Vec2,
/// OSNAPHATCH: object snaps find hatch objects (off by default, as in AutoCAD).
pub osnaphatch: bool,
/// OSNAPZ: an object snap gives the point the current elevation (on) instead of the Z of the
/// object it snapped to (off, the default, as in AutoCAD).
pub osnapz: bool,
/// GRIDUNIT in a drafting settings snapshot; zero components follow SNAPUNIT.
pub gridunit: Vec2,
/// Major grid line every N minor lines (GRIDMAJOR).
@@ -159,6 +162,7 @@ impl Default for Settings {
snapmode: false,
snapunit: Vec2::new(0.5, 0.5),
osnaphatch: false,
osnapz: false,
gridunit: Vec2::new(0.5, 0.5),
gridmajor: 5,
zoomfactor: 60,
+713 -230
View File
File diff suppressed because it is too large Load Diff
+47 -8
View File
@@ -482,13 +482,38 @@ impl Tracker {
cfg: &TrackConfig,
base: Option<Vec2>,
) -> Option<Track> {
let t = self.find(d, space, cursor, aperture, tol, cfg, base);
self.track_with_frozen(d, space, cursor, aperture, tol, cfg, base, &[])
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn track_with_frozen(
&mut self,
d: &Drawing,
space: &Space,
cursor: Vec2,
aperture: f64,
tol: f64,
cfg: &TrackConfig,
base: Option<Vec2>,
frozen: &[String],
) -> Option<Track> {
let t = self.find(d, space, cursor, aperture, tol, cfg, base, frozen);
self.last = t.clone();
t
}
#[allow(clippy::too_many_arguments)]
fn find(&self, d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, tol: f64, cfg: &TrackConfig, base: Option<Vec2>) -> Option<Track> {
fn find(
&self,
d: &Drawing,
space: &Space,
cursor: Vec2,
aperture: f64,
tol: f64,
cfg: &TrackConfig,
base: Option<Vec2>,
frozen: &[String],
) -> Option<Track> {
if !(cursor.is_finite() && aperture.is_finite() && tol.is_finite() && aperture > 0.0 && tol > 0.0) {
return None;
}
@@ -538,7 +563,7 @@ impl Tracker {
// 2. A path crossing an object.
if cfg.running(mode::INT | mode::APP) {
let ix = crate::spatial::index(d, space);
let prims = super::gather(d, space, &ix, cursor, aperture, mode::NEA).map(|(_, p)| p).unwrap_or_default();
let prims = super::gather_in(d, space, &ix, cursor, aperture, mode::NEA, frozen, None).map(|(_, p, _)| p).unwrap_or_default();
for prim in prims.iter().take(200) {
let extend = cfg.running(mode::APP) && super::extendable(prim);
for seg in super::prim_segments(prim) {
@@ -588,12 +613,26 @@ pub fn candidate(
aperture: f64,
cfg: &TrackConfig,
base: Option<Vec2>,
) -> Option<Acquired> {
candidate_with_frozen(d, space, cursor, hit, aperture, cfg, base, &[])
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn candidate_with_frozen(
d: &Drawing,
space: &Space,
cursor: Vec2,
hit: Option<&SnapHit>,
aperture: f64,
cfg: &TrackConfig,
base: Option<Vec2>,
frozen: &[String],
) -> Option<Acquired> {
if !can_acquire(cursor, aperture, cfg) {
return None;
}
let ix = crate::spatial::index(d, space);
let prims = super::gather(d, space, &ix, cursor, aperture, mode::NEA).map(|(_, p)| p).unwrap_or_default();
let prims = super::gather_in(d, space, &ix, cursor, aperture, mode::NEA, frozen, None).map(|(_, p, _)| p).unwrap_or_default();
candidate_from_prims(cursor, hit, aperture, cfg, base, &prims)
}
@@ -789,7 +828,7 @@ impl crate::Session {
s.orthomode ^= q.shift;
let angbase = self.angle_settings().angbase;
let Ok(st) = self.state() else { return CursorSnap { point: raw, ..Default::default() } };
let (doc, space) = (st.doc.clone(), st.edit_space());
let (doc, space, frozen) = (st.doc.clone(), st.edit_space(), st.viewport_frozen().to_vec());
if !raw.is_finite() {
return CursorSnap { point: raw, ..Default::default() };
}
@@ -798,10 +837,10 @@ impl crate::Session {
let cfg = TrackConfig::relative_to(&s, angbase, last);
let osmode = s.osmode | if s.osnaphatch { mode::HATCH } else { 0 };
let ix = crate::spatial::index(&doc, &space);
let (hit, near_prims) = super::osnap_with_neighborhood(&doc, &space, &ix, raw, q.aperture, osmode, q.base, q.deferred);
let (hit, near_prims) = super::osnap_with_neighborhood(&doc, &space, &ix, raw, q.aperture, osmode, q.base, q.deferred, &frozen);
let cand = match (osmode & mode::HATCH, near_prims.as_deref()) {
(0, Some(prims)) => candidate_with_prims(raw, hit.as_ref(), q.aperture, &cfg, q.base, prims),
_ => candidate(&doc, &space, raw, hit.as_ref(), q.aperture, &cfg, q.base),
_ => candidate_with_frozen(&doc, &space, raw, hit.as_ref(), q.aperture, &cfg, q.base, &frozen),
};
let wait = self.tracking.hover(cand, q.now, cfg.shift_acquire, q.shift);
if let Some(h) = hit {
@@ -816,7 +855,7 @@ impl crate::Session {
let (origin, angle) = super::grid_frame_in(&doc, &space);
p = super::grid_snap(p, doc.header.snap_unit(), origin, angle);
}
if let Some(mut t) = self.tracking.track(&doc, &space, p, q.aperture, q.tol, &cfg, q.base) {
if let Some(mut t) = self.tracking.track_with_frozen(&doc, &space, p, q.aperture, q.tol, &cfg, q.base, &frozen) {
// PolarSnap (SNAPTYPE 1): steps of POLARDIST, or of the snap X spacing when it is 0.
let step = if s.polardist > 0.0 { s.polardist } else { s.snapunit.x };
if s.snapmode
+7 -1
View File
@@ -12,6 +12,7 @@ const SESSION_VARS: &[&str] = &[
"ATTREQ",
"OSMODE",
"OSNAPHATCH",
"OSNAPZ",
"HPSPACE",
"HPDOUBLE",
"ANNOAUTOSCALE",
@@ -88,6 +89,7 @@ pub fn get(s: &Session, name: &str) -> Option<Value> {
let v = match n.as_str() {
"OSMODE" => json!(st.osmode),
"OSNAPHATCH" => json!(i32::from(st.osnaphatch)),
"OSNAPZ" => json!(i32::from(st.osnapz)),
"HPSPACE" => json!(s.last_used.hatch_spacing),
"HPDOUBLE" => json!(i32::from(s.last_used.hatch_double)),
// AutoCAD's values: positive on, negative off (4 = every annotative object).
@@ -156,7 +158,10 @@ pub fn get(s: &Session, name: &str) -> Option<Value> {
"MAXARRAY" => json!(st.maxarray),
"ZOOMFACTOR" => json!(st.zoomfactor),
"MEASUREINIT" => json!(i32::from(st.measureinit)),
"LASTPOINT" => json!([s.last_point.x, s.last_point.y, 0.0]),
"LASTPOINT" => {
let p = s.last_point3();
json!([p.x, p.y, p.z])
}
"AREA" => json!(s.area),
"PERIMETER" => json!(s.perimeter),
"DISTANCE" => json!(s.distance),
@@ -333,6 +338,7 @@ pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> {
// The `color` command's input: ByLayer, ByBlock, a name, an index or a true colour.
"CECOLOR" => crate::cmd::set_current_color_value(s, v).ok_or_else(bad)?,
"OSNAPHATCH" => st.osnaphatch = as_bool(v).ok_or_else(bad)?,
"OSNAPZ" => st.osnapz = as_bool(v).ok_or_else(bad)?,
"HPSPACE" => {
s.last_used.hatch_spacing = as_f64(v).filter(|f| is_supported_hatch_pattern_scale(*f)).ok_or_else(|| EngineError::BadParams {
cmd: "setvar".into(),
+5
View File
@@ -244,6 +244,11 @@ impl Session {
crate::prompt::parse_point_in(text, last, &self.angle_settings(), &self.input_ucs())
}
/// [`Session::parse_typed_point`] keeping Z ([`crate::prompt::parse_point3_in`]).
pub fn parse_typed_point3(&self, text: &str, last: Vec3) -> Option<Vec3> {
crate::prompt::parse_point3_in(text, last, &self.angle_settings(), &self.input_ucs())
}
/// A world point in the coordinates shown to the user (the current UCS).
pub fn ucs_point(&self, p: Vec2) -> Vec2 {
self.input_ucs().to_ucs(p)
+4
View File
@@ -131,6 +131,7 @@ mod offset_ellipse_side;
mod offset_move;
mod oops_command;
mod options_profile;
mod osnap_opened_drawings;
mod overkill;
mod parallel_display_list;
mod pedit_heights;
@@ -180,11 +181,14 @@ mod setvar_coverage;
mod shapes;
mod snap_annotations;
mod snap_blocks;
mod snap_center_on_curve;
mod snap_curves;
mod snap_intersections_aperture;
mod snap_nearest;
mod snap_overrides;
mod snap_tab_cycling;
mod snap_tracking;
mod snap_z;
mod snaps_more;
mod solid_command;
mod space_is_enter;
@@ -1,7 +1,8 @@
//! DIST snaps to the model geometry displayed in paper-space viewports (#516).
use cadcraft_engine::doc::{Block, Circle, Common, Drawing, Entity, EntityKind, Handle, Insert, Line, Space, Viewport};
use cadcraft_engine::doc::{Block, Circle, Common, Drawing, Ellipse, Entity, EntityKind, Handle, Insert, Line, Space, Viewport};
use cadcraft_engine::geom::{Vec2, Vec3};
use cadcraft_engine::pointmod::snap_candidates;
use cadcraft_engine::snap::{SnapCurve, SnapHit, mode, osnap, osnap_all};
use cadcraft_engine::{Input, Session};
use serde_json::json;
@@ -281,22 +282,22 @@ fn clipped_endpoints_do_not_hide_a_visible_candidate() {
assert!(osnap(&d, &paper, Vec2::new(110.11, 51.0), 0.2, mode::END, None, false).is_none());
}
/// Across spaces a click keeps the snap it had before Tab cycling: a viewport's best snap
/// replaces paper space's only when it scores closer. Tab still reaches the other one.
/// Across spaces a click takes the viewport's Endpoint over a paper-space Nearest that scores
/// closer, as within one space a snap point beats Nearest. Tab starts at the click's snap and
/// still reaches the paper-space Nearest.
#[test]
fn a_closer_paper_space_nearest_keeps_the_click_over_a_viewport_endpoint() {
fn a_viewport_endpoint_beats_a_closer_paper_space_nearest() {
let (mut d, paper) = drawing();
// A paper-space line 0.3 left of the model endpoint (0, 0), which the viewport shows at (95, 50).
d.add(&paper, Common::default(), EntityKind::Line(Line { a: Vec3::new(94.7, 48.0, 0.0), b: Vec3::new(94.7, 52.0, 0.0) })).unwrap();
let (cursor, modes) = (Vec2::new(94.8, 50.0), mode::END | mode::NEA);
let hit = osnap(&d, &paper, cursor, 0.5, modes, None, false).unwrap();
assert_eq!((hit.mode, hit.viewport), (mode::NEA, None), "{hit:?}");
assert!(hit.point.near(Vec2::new(94.7, 50.0), 1e-9), "{hit:?}");
let all = osnap_all(&d, &paper, cursor, 0.5, modes, None, false);
assert!(hit.mode == mode::END && hit.viewport.is_some() && hit.point.near(Vec2::new(95.0, 50.0), 1e-9), "{hit:?}");
let all = snap_candidates(&d, &paper, cursor, 0.5, modes, None, false);
assert_eq!(all.first(), Some(&hit), "Tab starts at the click's snap");
assert!(
all.iter().any(|h| h.mode == mode::END && h.viewport.is_some() && h.point.near(Vec2::new(95.0, 50.0), 1e-9)),
"Tab reaches the viewport's endpoint: {all:?}"
all.iter().any(|h| h.mode == mode::NEA && h.viewport.is_none() && h.point.near(Vec2::new(94.7, 50.0), 1e-9)),
"Tab reaches the paper-space Nearest: {all:?}"
);
}
@@ -432,3 +433,50 @@ fn malformed_and_paper_space_viewports_are_not_snap_sources() {
assert!(osnap(&d, &paper, Vec2::new(95.1, 50.1), 0.5, mode::END, None, false).is_none());
}
}
/// Nearest on a curve that leaves the viewport: the curve's closest point to the cursor is outside
/// the viewport, another point of it within the aperture is inside, and Nearest snaps there.
#[test]
fn nearest_takes_the_visible_part_of_a_curve_crossing_the_viewport_edge() {
let (mut d, paper) = drawing();
// The viewport shows model y up to 20. A tall ellipse peaks at (15, 20.1), just outside.
let ellipse = Ellipse { center: Vec3::new(15.0, 0.0, 0.0), major: Vec3::new(0.0, 20.1, 0.0), ratio: 0.1, start: 0.0, end: std::f64::consts::TAU };
d.add(&Space::Model, Common::default(), EntityKind::Ellipse(ellipse)).unwrap();
// The viewport's border is on a layer that is off, so it offers no Nearest of its own.
d.layers.push(cadcraft_engine::doc::Layer { name: "Border".into(), on: false, ..Default::default() });
let vp = viewport(&d, &paper);
d.modify_entity(vp, |e| e.common.layer = "Border".into()).unwrap();
// Model (15, 19.99): 0.11 from the peak, about 0.2 from where the ellipse comes back inside.
let cursor = Vec2::new(102.5, 59.995);
let hit = osnap(&d, &paper, cursor, 0.5, mode::NEA, None, false).expect("a visible nearest point");
let model = hit.viewport.expect("seen through the viewport").point;
assert!(model.y <= 20.0 + 1e-9 && model.dist(Vec2::new(15.0, 19.99)) <= 1.0, "{hit:?}");
}
#[test]
fn a_twisted_viewport_offers_the_visible_perpendicular_when_a_nearer_one_is_off_the_sheet() {
// A viewport twisted 45°, 20 square at 0,0 on the sheet, scale 1. Through it, a line along
// y = 0 under the cursor and one along x = 9.3 (sheet coordinates). From the base 12,3 the
// foot on the first, 12,0, is inside the turned model box but off the viewport; the foot on
// the second, 9.3,3, is on it.
let mut d = Drawing::new_imperial();
let paper = Space::Paper("Layout1".into());
let vp = Viewport {
center: Vec3::ZERO,
width: 20.0,
height: 20.0,
view_center: Vec2::ZERO,
view_height: 20.0,
id: 2,
twist: std::f64::consts::FRAC_PI_4,
..Viewport::default()
};
for (a, b) in [(Vec2::new(-9.0, 0.0), Vec2::new(30.0, 0.0)), (Vec2::new(9.3, -9.0), Vec2::new(9.3, 9.0))] {
let (a, b) = (vp.paper_to_model(a), vp.paper_to_model(b));
d.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: a.to3(0.0), b: b.to3(0.0) })).unwrap();
}
d.add(&paper, Common::default(), EntityKind::Viewport(vp)).unwrap();
let hit = osnap(&d, &paper, Vec2::new(9.0, 0.0), 0.5, mode::PER, Some(Vec2::new(12.0, 3.0)), false).expect("the visible foot");
assert_eq!(hit.mode, mode::PER);
assert!(hit.point.near(Vec2::new(9.3, 3.0), 1e-9), "{hit:?}");
}
@@ -0,0 +1,116 @@
//! Running object snaps in a fresh drawing and in drawings opened from DXF and DWG files, with
//! AutoCAD's default modes (OSMODE 4133: Endpoint, Center, Intersection, Extension).
//!
//! Moving onto a circle, an arc or a polyline arc finds its Center. OSMODE is a profile setting,
//! as in AutoCAD (saved in the registry there, not the drawing): a file's `$OSMODE` header
//! variable, 0 included, never changes the running snaps.
use cadcraft_engine::Session;
use cadcraft_engine::doc::Drawing;
use cadcraft_engine::geom::Vec2;
use cadcraft_engine::snap::{mode, tracking::CursorQuery};
use serde_json::json;
/// AutoCAD's default running snaps.
const DEFAULT: u32 = 4133;
fn polar(c: Vec2, r: f64, deg: f64) -> Vec2 {
let a = deg.to_radians();
c + Vec2::new(r * a.cos(), r * a.sin())
}
/// A line crossed by another, a circle, an arc and a polyline with a straight and an arc segment.
fn draw(s: &mut Session) {
s.execute("line", &json!({ "points": [[0, 0], [20, 0]] })).unwrap();
s.execute("line", &json!({ "points": [[5, -5], [5, 5]] })).unwrap();
s.execute("circle", &json!({ "center": [50, 0], "radius": 5 })).unwrap();
s.execute("arc", &json!({ "center": [80, 0], "radius": 5, "start": 0, "end": 180 })).unwrap();
// 100,0 to 110,0 straight, then a half circle (bulge 1) to 130,0 round 120,0, below the axis.
s.execute("pline", &json!({ "vertices": [[100, 0], {"p": [110, 0], "bulge": 1.0}, [130, 0]] })).unwrap();
}
fn drawing() -> Drawing {
let mut s = Session::new();
draw(&mut s);
s.doc().unwrap().clone()
}
/// Where a click at `cursor` lands while LINE asks for its first point (the drawing area's path).
fn snap(s: &mut Session, cursor: Vec2) -> Option<(Vec2, u32)> {
if s.running.is_none() {
s.start("line").unwrap();
}
let q = CursorQuery { base: None, deferred: true, corner: false, aperture: 1.0, tol: 0.5, now: 0.0, shift: false };
let r = s.snap_cursor(cursor, &q);
r.snap.map(|h| (r.point, h.mode))
}
fn assert_snaps(s: &mut Session, what: &str) {
assert_eq!(s.settings.osmode, DEFAULT, "{what}: the running snaps are the profile's");
let cases = [
("the line's end", Vec2::new(20.2, 0.1), Vec2::new(20.0, 0.0), &[mode::END][..]),
("the lines' crossing", Vec2::new(5.2, 0.15), Vec2::new(5.0, 0.0), &[mode::INT][..]),
("the circle", polar(Vec2::new(50.0, 0.0), 5.3, 45.0), Vec2::new(50.0, 0.0), &[mode::CEN][..]),
("the arc", polar(Vec2::new(80.0, 0.0), 5.2, 90.0), Vec2::new(80.0, 0.0), &[mode::CEN][..]),
("the arc's end", Vec2::new(85.2, 0.1), Vec2::new(85.0, 0.0), &[mode::END][..]),
("the polyline's vertex", Vec2::new(110.2, 0.1), Vec2::new(110.0, 0.0), &[mode::END][..]),
("the polyline's arc", polar(Vec2::new(120.0, 0.0), 10.2, 270.0), Vec2::new(120.0, 0.0), &[mode::CEN][..]),
];
for (name, cursor, want, modes) in cases {
let (p, m) = snap(s, cursor).unwrap_or_else(|| panic!("{what}: no snap on {name}"));
assert!(modes.contains(&m), "{what}, {name}: mode {m}");
assert!(p.near(want, 1e-6), "{what}, {name}: {p:?}");
}
// Away from everything: nothing.
assert_eq!(snap(s, Vec2::new(35.0, 20.0)), None, "{what}");
// F3 off: nothing; on again: back.
s.execute("osnap", &json!({})).unwrap();
assert_eq!(snap(s, Vec2::new(20.2, 0.1)), None, "{what}: F3 off");
s.execute("osnap", &json!({})).unwrap();
assert_eq!(snap(s, Vec2::new(20.2, 0.1)).map(|h| h.1), Some(mode::END), "{what}: F3 on");
}
#[test]
fn default_snaps_work_in_a_fresh_drawing() {
let mut s = Session::new();
draw(&mut s);
assert_snaps(&mut s, "fresh drawing");
}
/// `text` with `$OSMODE` set to `value` at the top of its header.
fn with_osmode(text: &str, value: u32) -> String {
let at = text.find("HEADER").expect("a header section") + "HEADER".len();
let eol = if text.contains("\r\n") { "\r\n" } else { "\n" };
let (head, tail) = text.split_at(at);
format!("{head}{eol} 9{eol}$OSMODE{eol} 70{eol}{value}{tail}")
}
#[test]
fn a_dxf_with_osmode_0_keeps_the_running_snaps() {
let clean = String::from_utf8(cadcraft_io::write(&drawing(), "snaps.dxf").unwrap()).unwrap();
let text = with_osmode(&clean, 0);
let d = cadcraft_io::read(text.as_bytes(), "snaps.dxf").unwrap();
let mut s = Session::new();
// OSMODE is the profile's: the user's own choice survives opening the file.
s.execute("setvar", &json!({ "name": "OSMODE", "value": DEFAULT })).unwrap();
s.open_drawing(d, "snaps.dxf", None);
assert_snaps(&mut s, "DXF with $OSMODE 0");
// Nor does a file change a profile without Center.
let mut s = Session::new();
s.execute("setvar", &json!({ "name": "OSMODE", "value": mode::END })).unwrap();
let text = with_osmode(&clean, DEFAULT);
assert_eq!(text.matches("$OSMODE").count(), 1, "one $OSMODE in the file");
s.open_drawing(cadcraft_io::read(text.as_bytes(), "x.dxf").unwrap(), "x.dxf", None);
assert_eq!(s.settings.osmode, mode::END);
}
#[test]
fn default_snaps_work_in_a_drawing_opened_from_dwg() {
// The drawing is the test's own, so it is converted in this process.
cadcraft_io::dwg_worker::allow_in_process();
let bytes = cadcraft_io::write(&drawing(), "snaps.dwg").unwrap();
let d = cadcraft_io::read(&bytes, "snaps.dwg").unwrap();
let mut s = Session::new();
s.open_drawing(d, "snaps.dwg", None);
assert_snaps(&mut s, "DWG");
}
@@ -0,0 +1,203 @@
//! Center snaps from the curve, as in AutoCAD: with the cursor over a circle, an arc, an
//! ellipse or a polyline arc (also inside a block reference) the running Center snap finds its
//! center, however far away it is. Before, the center was only found with the cursor on the
//! center itself, so moving onto a circle with the default running snaps (END, CEN, INT, EXT)
//! showed nothing.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{Common, EntityKind, Insert, Space};
use cadcraft_engine::geom::{Vec2, Vec3};
use cadcraft_engine::pointmod::snap_candidates;
use cadcraft_engine::snap::{self, mode};
use serde_json::json;
/// AutoCAD's default running snaps (OSMODE 4133).
const DEFAULT: u32 = 4133;
fn snap_at(s: &Session, cursor: Vec2, aperture: f64, osmode: u32) -> Option<(Vec2, u32)> {
snap::osnap(s.doc().unwrap(), &Space::Model, cursor, aperture, osmode, None, false).map(|h| (h.point, h.mode))
}
fn polar(c: Vec2, r: f64, deg: f64) -> Vec2 {
let a = deg.to_radians();
c + Vec2::new(r * a.cos(), r * a.sin())
}
#[test]
fn cursor_on_a_circle_snaps_to_its_center() {
let mut s = Session::new();
s.execute("circle", &json!({ "center": [100, 50], "radius": 20 })).unwrap();
let c = Vec2::new(100.0, 50.0);
for deg in [10.0, 45.0, 130.0, 250.0, 300.0] {
// A hair off the circle, well inside the aperture; the center is 20 units away.
let cursor = polar(c, 20.3, deg);
let (p, m) = snap_at(&s, cursor, 1.0, DEFAULT).unwrap_or_else(|| panic!("no snap on the circle at {deg}°"));
assert_eq!(m, mode::CEN, "at {deg}°");
assert!(p.near(c, 1e-9), "at {deg}°: {p:?}");
}
// Away from the circle (outside the aperture) there is nothing.
assert_eq!(snap_at(&s, polar(c, 23.0, 45.0), 1.0, DEFAULT), None);
// Center off: no center.
assert_eq!(snap_at(&s, polar(c, 20.3, 45.0), 1.0, mode::END), None);
// On the center itself, as before.
assert_eq!(snap_at(&s, c + Vec2::new(0.2, 0.1), 1.0, DEFAULT).map(|h| h.1), Some(mode::CEN));
}
#[test]
fn arcs_ellipses_and_polyline_arcs_snap_to_their_centers() {
let mut s = Session::new();
s.execute("arc", &json!({ "center": [0, 0], "radius": 10, "start": 0, "end": 90 })).unwrap();
s.execute("ellipse", &json!({ "center": [50, 0], "major": [8, 0], "ratio": 0.5 })).unwrap();
// A polyline with a half-circle bulge from (100,0) to (120,0): center (110,0), radius 10.
s.execute("pline", &json!({ "vertices": [{"p": [100, 0], "bulge": 1.0}, [120, 0]] })).unwrap();
let arc = snap_at(&s, polar(Vec2::ZERO, 10.2, 45.0), 1.0, DEFAULT).unwrap();
assert_eq!(arc.1, mode::CEN);
assert!(arc.0.near(Vec2::ZERO, 1e-9));
// The arc runs 0°-90°: on its circle at 200° (not on the arc) there is no center.
assert_eq!(snap_at(&s, polar(Vec2::ZERO, 10.2, 200.0), 1.0, DEFAULT), None);
let el = snap_at(&s, Vec2::new(50.0, 4.2), 1.0, DEFAULT).unwrap();
assert_eq!(el.1, mode::CEN);
assert!(el.0.near(Vec2::new(50.0, 0.0), 1e-9));
let pl = snap_at(&s, polar(Vec2::new(110.0, 0.0), 10.2, 270.0), 1.0, DEFAULT).unwrap();
assert_eq!(pl.1, mode::CEN, "the bulge's arc");
assert!(pl.0.near(Vec2::new(110.0, 0.0), 1e-9), "{:?}", pl.0);
}
#[test]
fn a_nearer_endpoint_or_intersection_still_wins() {
let mut s = Session::new();
s.execute("circle", &json!({ "center": [0, 0], "radius": 10 })).unwrap();
s.execute("line", &json!({ "points": [[10, 0], [30, 0]] })).unwrap();
// At the line's end on the circle: Endpoint/Intersection, not the far center.
let (p, m) = snap_at(&s, Vec2::new(10.2, 0.1), 1.0, DEFAULT).unwrap();
assert!(m == mode::END || m == mode::INT, "{m}");
assert!(p.near(Vec2::new(10.0, 0.0), 1e-9));
}
#[test]
fn circles_inside_block_references_snap_to_their_centers() {
let mut s = Session::new();
let c = s.execute("circle", &json!({ "center": [5, 0], "radius": 2 })).unwrap()["handle"].as_str().unwrap().to_string();
s.execute("block", &json!({ "name": "H", "base": [0, 0], "handles": [c], "keep": "delete" })).unwrap();
let kind = EntityKind::Insert(Insert {
block: "H".into(),
insert: Vec3::new(100.0, 100.0, 0.0),
scale: Vec3::new(3.0, 3.0, 1.0),
rotation: 0.0,
attribs: Vec::new(),
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
});
s.doc_mut().unwrap().add(&Space::Model, Common::default(), kind).unwrap();
// The circle lands at (115,100) with radius 6.
let (p, m) = snap_at(&s, polar(Vec2::new(115.0, 100.0), 6.2, 60.0), 1.0, DEFAULT).unwrap();
assert_eq!(m, mode::CEN);
assert!(p.near(Vec2::new(115.0, 100.0), 1e-9), "{p:?}");
}
#[test]
fn tab_cycling_offers_the_center_from_the_curve() {
let mut s = Session::new();
s.execute("circle", &json!({ "center": [0, 0], "radius": 10 })).unwrap();
let all = snap_candidates(s.doc().unwrap(), &Space::Model, polar(Vec2::ZERO, 10.2, 30.0), 1.0, DEFAULT, None, false);
assert_eq!(all.iter().filter(|h| h.mode == mode::CEN && h.point.near(Vec2::ZERO, 1e-9)).count(), 1, "{all:?}");
}
#[test]
fn the_cursor_query_snaps_to_the_center_from_the_curve() {
// The path the drawing area uses (Session::snap_cursor): the point a click would take.
let mut s = Session::new();
s.execute("circle", &json!({ "center": [0, 0], "radius": 50 })).unwrap();
s.start("line").unwrap();
let q = snap::tracking::CursorQuery { base: None, deferred: true, corner: false, aperture: 1.0, tol: 0.5, now: 0.0, shift: false };
let r = s.snap_cursor(polar(Vec2::ZERO, 50.4, 33.0), &q);
assert_eq!(r.snap.map(|h| h.mode), Some(mode::CEN));
assert!(r.point.near(Vec2::ZERO, 1e-9), "{:?}", r.point);
}
/// The arc of the review of #2347 (and #1114's test): center (100,50), radius 80, 30°-150°.
fn review_arc() -> Session {
let mut s = Session::new();
s.execute("arc", &json!({ "center": [100, 50], "radius": 80, "start": 30, "end": 150 })).unwrap();
s
}
#[test]
fn a_midpoint_under_the_cursor_beats_the_center_from_the_curve() {
let s = review_arc();
// On the arc's midpoint (100,130) with Center and Midpoint running: Midpoint, as in AutoCAD.
for cursor in [Vec2::new(100.05, 130.0), Vec2::new(100.2, 130.1)] {
assert_eq!(snap_at(&s, cursor, 0.5, mode::CEN | mode::MID), Some((Vec2::new(100.0, 130.0), mode::MID)), "at {cursor:?}");
assert_eq!(snap_at(&s, cursor, 0.5, mode::MID), Some((Vec2::new(100.0, 130.0), mode::MID)), "at {cursor:?}");
}
// Elsewhere on the arc, with no snap point in the aperture, the center from the curve.
let (p, m) = snap_at(&s, polar(Vec2::new(100.0, 50.0), 80.1, 70.0), 0.5, mode::CEN | mode::MID).unwrap();
assert_eq!(m, mode::CEN);
assert!(p.near(Vec2::new(100.0, 50.0), 1e-9), "{p:?}");
}
#[test]
fn a_quadrant_under_the_cursor_beats_the_center_from_the_curve() {
let mut s = Session::new();
s.execute("circle", &json!({ "center": [20, 0], "radius": 2 })).unwrap();
let cursor = Vec2::new(20.1, 2.0);
assert_eq!(snap_at(&s, cursor, 0.5, mode::CEN | mode::QUA), Some((Vec2::new(20.0, 2.0), mode::QUA)));
assert_eq!(snap_at(&s, cursor, 0.5, mode::QUA), Some((Vec2::new(20.0, 2.0), mode::QUA)));
// Away from the quadrants the center from the curve.
let (p, m) = snap_at(&s, polar(Vec2::new(20.0, 0.0), 2.1, 45.0), 0.5, mode::CEN | mode::QUA).unwrap();
assert_eq!(m, mode::CEN);
assert!(p.near(Vec2::new(20.0, 0.0), 1e-9), "{p:?}");
}
#[test]
fn many_straight_segments_do_not_hide_a_circle_from_center() {
// A polyline of 2,500 straight segments zigzagging over the cursor, then a circle: the
// work limit counts circles and arcs only, so the circle's center is still found.
let mut s = Session::new();
let vertices: Vec<[f64; 2]> = (0..=2500).map(|i| [i as f64 * 0.04, if i % 2 == 0 { 0.0 } else { 100.0 }]).collect();
s.execute("pline", &json!({ "vertices": vertices })).unwrap();
s.execute("circle", &json!({ "center": [50, 50], "radius": 20 })).unwrap();
let (p, m) = snap_at(&s, polar(Vec2::new(50.0, 50.0), 20.2, 100.0), 0.5, mode::CEN).unwrap();
assert_eq!(m, mode::CEN);
assert!(p.near(Vec2::new(50.0, 50.0), 1e-9), "{p:?}");
}
#[test]
fn a_viewport_center_keeps_its_curve_distance_against_paper_space() {
use cadcraft_engine::doc::{Circle, Drawing, Viewport};
let mut d = Drawing::new_imperial();
let paper = Space::Paper("Layout1".into());
// Model circle (10,0) r16 seen through a viewport at half scale: paper center (100,50), radius 8.
d.add(&Space::Model, Common::default(), EntityKind::Circle(Circle { center: Vec3::new(10.0, 0.0, 0.0), radius: 16.0 })).unwrap();
let vp = Viewport {
center: Vec3::new(100.0, 50.0, 0.0),
width: 20.0,
height: 20.0,
view_center: Vec2::new(10.0, 0.0),
view_height: 40.0,
id: 2,
locked: false,
frozen_layers: Vec::new(),
layer_colors: Vec::new(),
clip: None,
on: true,
twist: 0.0,
..Default::default()
};
d.add(&paper, Common::default(), EntityKind::Viewport(vp)).unwrap();
// A small paper-space circle whose curve passes 0.3 from the cursor and whose center is
// nearer the cursor (3.3) than the model circle's (8).
d.add(&paper, Common::default(), EntityKind::Circle(Circle { center: Vec3::new(108.0, 53.3, 0.0), radius: 3.0 })).unwrap();
// The cursor is on the model circle (0.1 off in paper units): its center wins.
let h = snap::osnap(&d, &paper, Vec2::new(108.1, 50.0), 0.5, mode::CEN, None, false).unwrap();
assert_eq!(h.mode, mode::CEN);
assert!(h.point.near(Vec2::new(100.0, 50.0), 1e-9), "{h:?}");
assert!(h.viewport.is_some());
// On the paper circle, away from the model one: its center.
let h = snap::osnap(&d, &paper, Vec2::new(108.0, 56.35), 0.5, mode::CEN, None, false).unwrap();
assert!(h.point.near(Vec2::new(108.0, 53.3), 1e-9), "{h:?}");
assert!(h.viewport.is_none());
}
+28
View File
@@ -70,6 +70,9 @@ fn elliptical_arc_perpendicular_and_tangent_from_a_base_point() {
let (q, m) = along_quarter(&s, mode::TAN, Some(base)).expect("a tangent point on the arc");
assert_eq!(m, mode::TAN);
assert!(on_quarter(q) && Vec2::new(q.x / 16.0, q.y / 4.0).dot(q - base).abs() < 1e-9, "{q:?}");
// The same tangent at a prompt that resolves deferred snaps (CIRCLE's 3P points, #1512).
let h = snap::osnap(s.doc().unwrap(), &Space::Model, q, 0.3, mode::TAN, Some(base), true).expect("tangent at a deferred prompt");
assert!(h.mode == mode::TAN && h.deferred.is_none() && h.point.near(q, 1e-9), "{h:?}");
// Perpendicular from (10,10): the line from the base runs along the normal.
let base = Vec2::new(10.0, 10.0);
let (q, m) = along_quarter(&s, mode::PER, Some(base)).expect("a perpendicular foot on the arc");
@@ -119,3 +122,28 @@ fn spline_midpoint_perpendicular_and_tangent() {
let d = (sp.eval(i + 1e-6) - sp.eval(i - 1e-6)).normalized();
assert!(d.cross((q - base).normalized()).abs() < 1e-3, "the line from the base runs along the curve at {q:?}");
}
#[test]
fn perpendicular_from_an_arcs_center_stays_on_the_arc() {
// From the center of an arc every point is perpendicular: the one under the cursor, never a
// point of its circle outside the sweep.
let mut s = Session::new();
s.execute("arc", &serde_json::json!({"center": [0, 0], "radius": 10, "start": 90, "end": 180})).unwrap();
let hit = snap::osnap(s.doc().unwrap(), &Space::Model, Vec2::new(-6.0, 8.0), 0.3, mode::PER, Some(Vec2::ZERO), false);
let (p, m) = hit.map(|h| (h.point, h.mode)).expect("a perpendicular on the arc");
assert_eq!(m, mode::PER);
assert!(p.near(Vec2::new(-6.0, 8.0), 1e-9), "{p:?}");
}
#[test]
fn perpendicular_to_a_ray_needs_the_cursor_on_the_ray() {
// A ray along +X from the origin: behind its start the cursor is over nothing.
let mut s = Session::new();
s.execute("ray", &serde_json::json!({"base": [0, 0], "through": [10, 0]})).unwrap();
let d = s.doc().unwrap();
let base = Some(Vec2::new(5.0, 3.0));
assert_eq!(snap::osnap(d, &Space::Model, Vec2::new(-2.0, 0.0), 0.5, mode::PER, base, false), None);
// Over the ray, the foot is found.
let hit = snap::osnap(d, &Space::Model, Vec2::new(2.0, 0.0), 0.5, mode::PER, base, false).expect("the foot on the ray");
assert!(hit.point.near(Vec2::new(5.0, 0.0), 1e-9), "{hit:?}");
}
+122
View File
@@ -21,6 +21,17 @@ fn last_line(s: &Session) -> (Vec2, Vec2) {
s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Line(l) = &e.kind { Some((l.a.xy(), l.b.xy())) } else { None }).last().unwrap()
}
/// The last circle drawn as (center, radius).
fn last_circle(s: &Session) -> (Vec2, f64) {
s.doc()
.unwrap()
.model
.iter()
.filter_map(|e| if let EntityKind::Circle(c) = &e.kind { Some((c.center.xy(), c.radius)) } else { None })
.last()
.unwrap()
}
fn near(p: Vec2, x: f64, y: f64) -> bool {
p.near(Vec2::new(x, y), 1e-9)
}
@@ -80,6 +91,23 @@ fn nothing_to_snap_to_rejects_the_point() {
assert!(near(s.last_point, 10.0, 10.0));
}
/// #2800: a typed PER or TAN finds its point from a pick anywhere on the object, as in AutoCAD.
/// The pick used to have to land within the aperture (0.125 here) of the foot or tangent point,
/// which you can't know in advance; elsewhere it said "No Perpendicular found".
#[test]
fn typed_per_and_tan_snap_from_anywhere_on_the_object() {
let mut s = drawing();
// From (5,5), PER picked at (3,0) on the line 0,0–10,0: two units from the foot (5,0).
s.script("LINE 5,5 PER 3,0\n\n").unwrap();
let (a, b) = last_line(&s);
assert!(near(a, 5.0, 5.0) && near(b, 5.0, 0.0), "{a:?} {b:?}");
// From (30,20), TAN picked at the top of the circle (centre 20,20, radius 3): the tangent
// points are at cos = 3/10 from the line to the base, and the upper one is nearer the pick.
s.script("LINE 30,20 TAN 20,23\n\n").unwrap();
let (a, b) = last_line(&s);
assert!(near(a, 30.0, 20.0) && near(b, 20.9, 20.0 + 3.0 * 0.91f64.sqrt()), "{a:?} {b:?}");
}
#[test]
fn from_nests_with_a_snap_override() {
let mut s = drawing();
@@ -116,3 +144,97 @@ fn a_command_keyword_wins_over_a_snap_word() {
s.cmdline("arc _cen").unwrap();
assert!(s.prompt_text().ends_with("Center of:"), "{}", s.prompt_text());
}
#[test]
fn tan_for_a_circle_radius_touches_the_picked_circle() {
// #1512: the circle around the center that touches the circle at 20,20 radius 3, on the side
// it was picked: the near side (radius 7), the far side (13), and through Diameter.
for (script, center, r) in [
("CIRCLE 30,20 TAN 23.02,20.03\n", (30.0, 20.0), 7.0),
("CIRCLE 30,20 TAN 16.98,19.97\n", (30.0, 20.0), 13.0),
("CIRCLE 20,10 D TAN 20.03,17.02\n", (20.0, 10.0), 7.0),
] {
let mut s = drawing();
s.script(script).unwrap();
assert!(s.running.is_none(), "{script}: {}", s.prompt_text());
let (c, got) = last_circle(&s);
assert!(near(c, center.0, center.1) && (got - r).abs() < 1e-9, "{script}: {c:?} r={got}");
}
}
#[test]
fn tan_for_a_3p_circle_touches_the_picked_circles() {
// #1512: through two points and tangent to the circle at 20,20 radius 3, the tangent pick
// first or last.
for script in ["CIRCLE 3P 26,20 26,26 TAN 23.02,20.03\n", "CIRCLE 3P TAN 23.02,20.03 26,20 26,26\n"] {
let mut s = drawing();
s.script(script).unwrap();
assert!(s.running.is_none(), "{script}: {}", s.prompt_text());
let (c, r) = last_circle(&s);
assert!((c.dist(Vec2::new(26.0, 20.0)) - r).abs() < 1e-9 && (c.dist(Vec2::new(26.0, 26.0)) - r).abs() < 1e-9, "{script}");
assert!((c.dist(Vec2::new(20.0, 20.0)) - (3.0 + r)).abs() < 1e-9, "{script}: {c:?} r={r}");
}
// Tan, Tan, Tan: the circle between three circles of radius 1, picked on their inner sides.
let mut s = Session::new();
s.script("CIRCLE 0,0 1\nCIRCLE 6,0 1\nCIRCLE 3,5 1\nCIRCLE 3P TAN 0.98,0.2 TAN 5.02,0.2 TAN 3.01,3.98\n").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
let (c, r) = last_circle(&s);
for k in [(0.0, 0.0), (6.0, 0.0), (3.0, 5.0)] {
assert!((c.dist(Vec2::new(k.0, k.1)) - (1.0 + r)).abs() < 1e-9, "{c:?} r={r}");
}
}
#[test]
fn tan_for_a_3p_circle_touches_an_arc_within_its_sweep() {
// #1512: through 26,20 and 26,26, the circles tangent to the circle at 20,20 radius 3 touch it
// on the right or the far left, both off an arc swept from 90° to 100°: no circle.
let mut s = Session::new();
s.execute("arc", &serde_json::json!({"center": [20, 20], "radius": 3, "start": 90, "end": 100})).unwrap();
s.script("CIRCLE 3P 26,20 26,26 TAN 19.74,22.99\n").unwrap();
assert!(s.prompt_text().contains("third point"), "{}", s.prompt_text());
assert!(!s.doc().unwrap().model.iter().any(|e| matches!(e.kind, EntityKind::Circle(_))));
}
#[test]
fn tan_for_a_3p_circle_takes_the_solution_that_touches_the_arc() {
// #1512: through 26,20 and 26,26, the circles tangent to the circle at 20,20 radius 3 touch it
// at about 29.6° and -103.3°. Picked at 20° on an arc swept from 200° to 25°, the 29.6°
// circle is nearer the pick but off the arc: the -103.3° one (radius 6.0826) is drawn.
let mut s = Session::new();
s.execute("arc", &serde_json::json!({"center": [20, 20], "radius": 3, "start": 200, "end": 25})).unwrap();
s.script("CIRCLE 3P 26,20 26,26 TAN 22.82,21.03\n").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
let (c, r) = last_circle(&s);
assert!((c.dist(Vec2::new(20.0, 20.0)) - (r - 3.0)).abs() < 1e-9 && (r - 6.082575694955838).abs() < 1e-9, "{c:?} r={r}");
}
#[test]
fn tan_for_a_circle_radius_refuses_the_picked_circles_own_center() {
// #1512: a circle around 20,20 would lie on the circle there, not touch it.
let mut s = drawing();
s.script("CIRCLE 20,20 TAN 23.02,20.03\n").unwrap();
assert!(s.prompt_text().contains("radius of circle"), "{}", s.prompt_text());
assert!(s.log.iter().any(|l| l.contains("No circle around the center is tangent there.")), "{:?}", s.log);
assert_eq!(s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Circle(_))).count(), 1);
}
#[test]
fn tan_for_a_3p_circle_refuses_the_picked_circle_itself() {
// #1512: tangent twice to the circle and through a point on it is only the circle itself.
let mut s = drawing();
s.script("CIRCLE 3P TAN 23.02,20.03 TAN 16.98,20.03 20,23\n").unwrap();
assert!(s.prompt_text().contains("third point"), "{}", s.prompt_text());
assert!(s.log.iter().any(|l| l.contains("Circle does not exist.")), "{:?}", s.log);
assert_eq!(s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Circle(_))).count(), 1);
}
#[test]
fn tan_for_a_3p_circle_through_points_in_line_with_the_picked_circles_center() {
// Through 3,0 and 5,0 and tangent to the unit circle at the origin: the two points and that
// circle's center lie on one line, the circle that touches it does not (center 4,±√48, radius 7).
let mut s = Session::new();
s.script("CIRCLE 0,0 1\nCIRCLE 3P 3,0 5,0 TAN 1,0\n").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
let (c, r) = last_circle(&s);
assert!(near(Vec2::new(c.x, c.y.abs()), 4.0, 48f64.sqrt()) && (r - 7.0).abs() < 1e-9, "{c:?} r={r}");
}
+102
View File
@@ -0,0 +1,102 @@
//! Tab cycling through object snaps: a crowd of candidates is capped, hostile cursors and
//! apertures give no candidates, and the list never repeats a snap.
use cadcraft_engine::Session;
use cadcraft_engine::doc::Space;
use cadcraft_engine::geom::Vec2;
use cadcraft_engine::pointmod::snap_candidates;
use cadcraft_engine::snap::mode;
use serde_json::json;
#[test]
fn a_crowd_of_snaps_is_capped_and_never_repeats() {
let mut s = Session::new();
// 600 short lines fanning out from points packed round the origin: 1,200 endpoints.
for i in 0..600 {
let a = f64::from(i) * 0.01;
let p = [1e-3 * a.cos(), 1e-3 * a.sin()];
s.execute("line", &json!({ "points": [p, [a.cos(), a.sin()]] })).unwrap();
}
let d = s.doc().unwrap();
let cands = snap_candidates(d, &Space::Model, Vec2::ZERO, 0.5, mode::END | mode::INT | mode::NEA, None, false);
assert!(!cands.is_empty());
assert!(cands.len() <= 257, "{} candidates", cands.len());
for (i, a) in cands.iter().enumerate() {
assert!(a.point.is_finite());
assert!(!cands.iter().skip(i + 1).any(|b| b.mode == a.mode && b.point == a.point), "{a:?} repeats");
}
}
#[test]
fn hostile_cursor_and_aperture_give_no_candidates() {
let mut s = Session::new();
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
let d = s.doc().unwrap();
let space = Space::Model;
let all = mode::END | mode::MID | mode::INT | mode::NEA | mode::PER;
for (c, ap) in [
(Vec2::new(f64::NAN, 0.0), 0.5),
(Vec2::new(0.0, f64::INFINITY), 0.5),
(Vec2::ZERO, f64::NAN),
(Vec2::ZERO, 0.0),
(Vec2::ZERO, -1.0),
(Vec2::ZERO, f64::INFINITY),
] {
assert!(snap_candidates(d, &space, c, ap, all, None, false).is_empty(), "{c:?} {ap}");
assert!(snap_candidates(d, &space, c, ap, all, Some(Vec2::new(f64::NAN, 1.0)), true).is_empty(), "{c:?} {ap}");
}
// A huge but finite aperture still answers, from the objects there are.
let far = snap_candidates(d, &space, Vec2::ZERO, 1e300, mode::END, None, false);
assert!(far.iter().all(|h| h.point.is_finite()));
// Object snaps off (or only the OFF bit) offer nothing.
assert!(snap_candidates(d, &space, Vec2::ZERO, 0.5, 0, None, false).is_empty());
assert!(snap_candidates(d, &space, Vec2::ZERO, 0.5, mode::END | mode::OFF, None, false).is_empty());
}
#[test]
fn every_endpoint_under_the_aperture_is_offered_not_one_per_mode() {
let mut s = Session::new();
// Three line ends close together, all within the aperture of the cursor between them.
for (a, b) in [([0.0, 0.0], [10.0, 0.0]), ([0.06, 0.05], [0.06, 10.0]), ([0.03, -0.06], [-10.0, -10.0])] {
s.execute("line", &json!({ "points": [a, b] })).unwrap();
}
let d = s.doc().unwrap();
let cands = snap_candidates(d, &Space::Model, Vec2::new(0.03, 0.0), 0.125, mode::END, None, false);
let ends: Vec<Vec2> = cands.iter().filter(|h| h.mode == mode::END).map(|h| h.point).collect();
assert_eq!(ends.len(), 3, "{cands:?}");
for want in [Vec2::new(0.0, 0.0), Vec2::new(0.06, 0.05), Vec2::new(0.03, -0.06)] {
assert!(ends.iter().any(|p| p.near(want, 1e-12)), "{want:?} in {ends:?}");
}
// The first is the snap a click would take.
let first = snap_candidates(d, &Space::Model, Vec2::new(0.03, 0.0), 0.125, mode::END, None, false).first().map(|h| h.point);
assert_eq!(first, cadcraft_engine::snap::osnap(d, &Space::Model, Vec2::new(0.03, 0.0), 0.125, mode::END, None, false).map(|h| h.point));
}
/// A base point that is not a number gives no candidates, though the cursor is on an endpoint: the
/// perpendicular and tangent points from it would be meaningless, as a viewport already treats it.
#[test]
fn a_non_finite_base_gives_no_candidates() {
let mut s = Session::new();
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
let d = s.doc().unwrap();
let all = mode::END | mode::PER | mode::TAN | mode::NEA;
for base in [Vec2::new(f64::NAN, 1.0), Vec2::new(1.0, f64::INFINITY), Vec2::new(f64::NEG_INFINITY, f64::NAN)] {
assert!(snap_candidates(d, &Space::Model, Vec2::new(10.01, 0.0), 0.5, all, Some(base), false).is_empty(), "{base:?}");
assert!(cadcraft_engine::snap::osnap_all(d, &Space::Model, Vec2::new(10.01, 0.0), 0.5, all, Some(base), true).is_empty(), "{base:?}");
}
// A finite base still offers them.
assert!(!snap_candidates(d, &Space::Model, Vec2::new(10.01, 0.0), 0.5, all, Some(Vec2::new(5.0, 5.0)), false).is_empty());
}
#[test]
fn deferred_snaps_of_two_curves_at_one_point_are_both_offered() {
// Two circles touching at the origin: each offers its own deferred tangent there, and the
// line drawn from it depends on which circle it is.
let mut s = Session::new();
s.script("CIRCLE 0,1 1\nCIRCLE 0,-2 2\n").unwrap();
let d = s.doc().unwrap();
let all = cadcraft_engine::snap::osnap_all(d, &Space::Model, Vec2::new(0.0, 0.1), 0.5, mode::TAN, None, true);
let curves: Vec<_> = all.iter().filter_map(|h| h.deferred.map(|f| f.curve)).collect();
assert_eq!(curves.len(), 2, "{all:?}");
assert_ne!(curves.first(), curves.get(1), "{all:?}");
}
+268
View File
@@ -0,0 +1,268 @@
//! An object snap gives the point the Z of what it snapped to, as in AutoCAD (OSNAPZ 0): a line
//! drawn between a survey point and a contour runs from the point's level to the contour's
//! elevation instead of lying at z = 0. OSNAPZ 1 uses the current elevation; an unsnapped pick
//! stays at z = 0. LINE and POINT keep the Z of typed points too.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{EntityKind, LwPolyline, Point, Space};
use cadcraft_engine::geom::{PolyVertex, Vec2, Vec3};
use cadcraft_engine::snap::{self, mode};
fn survey(s: &mut Session) {
s.add_entity(EntityKind::Point(Point { p: Vec3::new(0.0, 0.0, 1880.0), angle: 0.0 })).unwrap();
s.add_entity(EntityKind::LwPolyline(LwPolyline {
vertices: vec![PolyVertex::new(Vec2::new(10.0, 0.0)), PolyVertex::new(Vec2::new(10.0, 10.0))],
closed: false,
const_width: 0.0,
elevation: 1881.0,
plinegen: false,
}))
.unwrap();
s.cmdline("zoom e").ok();
}
/// Click at `at` with the object snaps in `osmode`, as the canvas does.
fn click(s: &mut Session, at: Vec2, osmode: u32) {
let ap = s.pixel_size() * 20.0;
let hit = snap::osnap(s.doc().unwrap(), &Space::Model, at, ap, osmode, None, false).expect("a snap");
s.input_snapped(hit).unwrap();
}
fn lines(s: &Session) -> Vec<(Vec3, Vec3)> {
s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Line(l) = &e.kind { Some((l.a, l.b)) } else { None }).collect()
}
#[test]
fn a_line_snapped_to_a_survey_point_and_a_contour_keeps_their_levels() {
let mut s = Session::new();
survey(&mut s);
s.cmdline("line").unwrap();
click(&mut s, Vec2::new(0.01, 0.0), mode::NOD);
click(&mut s, Vec2::new(10.0, 0.01), mode::END);
s.input(cadcraft_engine::Input::Enter).unwrap();
assert_eq!(lines(&s), vec![(Vec3::new(0.0, 0.0, 1880.0), Vec3::new(10.0, 0.0, 1881.0))]);
}
#[test]
fn osnapz_on_uses_the_current_elevation_and_a_plain_pick_stays_flat() {
let mut s = Session::new();
survey(&mut s);
s.execute("setvar", &serde_json::json!({ "name": "OSNAPZ", "value": 1 })).unwrap();
s.doc_mut().unwrap().header.set_f64("ELEVATION", 5.0);
s.cmdline("line").unwrap();
click(&mut s, Vec2::new(0.01, 0.0), mode::NOD);
s.input(cadcraft_engine::Input::Point(Vec2::new(20.0, 20.0))).unwrap();
s.input(cadcraft_engine::Input::Enter).unwrap();
assert_eq!(lines(&s), vec![(Vec3::new(0.0, 0.0, 5.0), Vec3::new(20.0, 20.0, 0.0))]);
assert_eq!(s.execute("getvar", &serde_json::json!({ "name": "OSNAPZ" })).unwrap()["value"], 1);
}
#[test]
fn point_takes_a_snapped_z_and_line_a_typed_one() {
let mut s = Session::new();
survey(&mut s);
s.cmdline("point").unwrap();
click(&mut s, Vec2::new(10.0, 10.01), mode::END);
let pts: Vec<Vec3> = s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Point(p) = &e.kind { Some(p.p) } else { None }).collect();
assert!(pts.contains(&Vec3::new(10.0, 10.0, 1881.0)), "{pts:?}");
s.cmdline("line").unwrap();
s.cmdline("100,100,3").unwrap();
s.cmdline("@10,0,2").unwrap();
s.cmdline("").unwrap();
assert!(lines(&s).contains(&(Vec3::new(100.0, 100.0, 3.0), Vec3::new(110.0, 100.0, 5.0))), "{:?}", lines(&s));
}
/// M2P between two snapped points is midway in Z too: halfway between a survey point's level
/// and a contour's elevation.
#[test]
fn m2p_between_two_snapped_points_is_midway_in_z() {
let mut s = Session::new();
survey(&mut s);
s.cmdline("point").unwrap();
s.cmdline("m2p").unwrap();
click(&mut s, Vec2::new(0.01, 0.0), mode::NOD);
click(&mut s, Vec2::new(10.0, 0.01), mode::END);
let pts: Vec<Vec3> = s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Point(p) = &e.kind { Some(p.p) } else { None }).collect();
assert!(pts.contains(&Vec3::new(5.0, 0.0, 1880.5)), "{pts:?}");
}
/// A one-off snap typed for an M2P point gives that point the Z of what it snapped to, and
/// the next plain point is back at z = 0.
#[test]
fn m2p_with_a_typed_snap_for_each_point_takes_their_levels() {
let mut s = Session::new();
survey(&mut s);
s.cmdline("point").unwrap();
s.cmdline("m2p").unwrap();
s.cmdline("nod").unwrap();
s.input(cadcraft_engine::Input::Point(Vec2::new(0.01, 0.0))).unwrap();
s.cmdline("end").unwrap();
s.input(cadcraft_engine::Input::Point(Vec2::new(10.0, 0.01))).unwrap();
s.cmdline("point").unwrap();
s.input(cadcraft_engine::Input::Point(Vec2::new(50.0, 50.0))).unwrap();
let pts: Vec<Vec3> = s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Point(p) = &e.kind { Some(p.p) } else { None }).collect();
assert!(pts.contains(&Vec3::new(5.0, 0.0, 1880.5)), "{pts:?}");
assert!(pts.contains(&Vec3::new(50.0, 50.0, 0.0)), "{pts:?}");
}
/// A point a LISP expression gives at a point prompt keeps its Z, as a typed `x,y,z` does.
#[test]
fn a_lisp_point_keeps_its_z() {
let mut s = Session::new();
s.cmdline("line").unwrap();
s.cmdline("(list 1 2 7)").unwrap();
s.cmdline("(list 5 2)").unwrap();
s.cmdline("").unwrap();
assert!(lines(&s).contains(&(Vec3::new(1.0, 2.0, 7.0), Vec3::new(5.0, 2.0, 0.0))), "{:?}", lines(&s));
}
/// A LINE started with a deferred tangent keeps the Z typed for its next point, and the
/// segment after it starts there.
#[test]
fn a_deferred_tangent_start_keeps_the_next_points_z() {
let mut s = Session::new();
s.cmdline("circle 0,0 2").unwrap();
s.cmdline("zoom e").ok();
s.cmdline("line").unwrap();
s.cmdline("tan").unwrap();
s.input(cadcraft_engine::Input::Point(Vec2::new(-1.4, 1.4))).unwrap();
s.cmdline("10,10,5").unwrap();
s.cmdline("20,10,1").unwrap();
s.cmdline("").unwrap();
let ls = lines(&s);
assert_eq!(ls.len(), 2, "{ls:?}");
assert_eq!(ls[0].0.z, 0.0, "{ls:?}");
assert_eq!(ls[0].1, Vec3::new(10.0, 10.0, 5.0), "{ls:?}");
assert_eq!(ls[1], (Vec3::new(10.0, 10.0, 5.0), Vec3::new(20.0, 10.0, 1.0)), "{ls:?}");
}
fn points(s: &Session) -> Vec<Vec3> {
s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Point(p) = &e.kind { Some(p.p) } else { None }).collect()
}
/// A center snap takes the circle's Z, though no object passes under the cursor there.
#[test]
fn a_center_snap_takes_the_circles_z() {
let mut s = Session::new();
s.add_entity(EntityKind::Circle(cadcraft_engine::doc::Circle { center: Vec3::new(0.0, 0.0, 5.0), radius: 10.0 })).unwrap();
s.cmdline("zoom e").ok();
s.cmdline("point").unwrap();
click(&mut s, Vec2::new(0.01, 0.01), mode::CEN);
assert_eq!(points(&s), vec![Vec3::new(0.0, 0.0, 5.0)]);
}
/// An intersection of two objects at different levels takes the Z of the first one drawn,
/// whichever is on top.
#[test]
fn an_intersection_takes_the_z_of_the_first_object() {
let mut s = Session::new();
s.add_entity(EntityKind::Line(cadcraft_engine::doc::Line { a: Vec3::new(-5.0, 0.0, 0.0), b: Vec3::new(5.0, 0.0, 0.0) })).unwrap();
s.add_entity(EntityKind::Line(cadcraft_engine::doc::Line { a: Vec3::new(0.0, -5.0, 3.0), b: Vec3::new(0.0, 5.0, 3.0) })).unwrap();
s.cmdline("zoom e").ok();
s.cmdline("point").unwrap();
click(&mut s, Vec2::new(0.01, 0.01), mode::INT);
assert_eq!(points(&s), vec![Vec3::new(0.0, 0.0, 0.0)]);
}
/// A reference to `block` at `at`, scaled by `z_scale` in Z only.
fn reference(block: &str, at: Vec3, z_scale: f64) -> EntityKind {
EntityKind::Insert(cadcraft_engine::doc::Insert {
block: block.into(),
insert: at,
scale: Vec3::new(1.0, 1.0, z_scale),
rotation: 0.0,
attribs: Vec::new(),
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
})
}
/// Block B: a line rising from (0,0,0) to (10,0,10) and a point at (5,5,5). Block C: B placed
/// 3 units up.
fn blocks(s: &mut Session) {
let d = s.doc_mut().unwrap();
let mut b = cadcraft_engine::doc::Block::new("B");
let line = cadcraft_engine::doc::Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(10.0, 0.0, 10.0) };
b.entities.push(cadcraft_engine::doc::Entity::new(d.new_handle(), EntityKind::Line(line)));
b.entities.push(cadcraft_engine::doc::Entity::new(d.new_handle(), EntityKind::Point(Point { p: Vec3::new(5.0, 5.0, 5.0), angle: 0.0 })));
d.blocks.insert("B".into(), std::sync::Arc::new(b));
let mut c = cadcraft_engine::doc::Block::new("C");
c.entities.push(cadcraft_engine::doc::Entity::new(d.new_handle(), reference("B", Vec3::new(0.0, 0.0, 3.0), 1.0)));
d.blocks.insert("C".into(), std::sync::Arc::new(c));
}
/// A snap on an object inside a block reference takes that object's Z, placed by the
/// reference (its insertion Z and Z scale), through nested references too.
#[test]
fn a_snap_inside_a_block_takes_the_z_of_the_object_there() {
let mut s = Session::new();
blocks(&mut s);
s.add_entity(reference("B", Vec3::new(100.0, 0.0, 2.0), 2.0)).unwrap();
s.add_entity(reference("C", Vec3::new(300.0, 0.0, 1.0), 1.0)).unwrap();
s.cmdline("zoom e").ok();
s.cmdline("point").unwrap();
click(&mut s, Vec2::new(110.01, 0.01), mode::END);
s.cmdline("point").unwrap();
click(&mut s, Vec2::new(105.01, 5.01), mode::NOD);
s.cmdline("point").unwrap();
click(&mut s, Vec2::new(310.01, 0.01), mode::END);
assert_eq!(points(&s), vec![Vec3::new(110.0, 0.0, 22.0), Vec3::new(105.0, 5.0, 12.0), Vec3::new(310.0, 0.0, 14.0)]);
}
/// Center and quadrant snaps on an ellipse take its Z.
#[test]
fn ellipse_snaps_take_the_ellipses_z() {
let mut s = Session::new();
let e = cadcraft_engine::doc::Ellipse {
center: Vec3::new(300.0, 0.0, 3.0),
major: Vec3::new(10.0, 0.0, 0.0),
ratio: 0.5,
start: 0.0,
end: std::f64::consts::TAU,
};
s.add_entity(EntityKind::Ellipse(e)).unwrap();
s.cmdline("zoom e").ok();
s.cmdline("point").unwrap();
click(&mut s, Vec2::new(300.01, 0.01), mode::CEN);
s.cmdline("point").unwrap();
click(&mut s, Vec2::new(310.01, 0.01), mode::QUA);
assert_eq!(points(&s), vec![Vec3::new(300.0, 0.0, 3.0), Vec3::new(310.0, 0.0, 3.0)]);
}
#[test]
fn closing_a_line_preserves_its_first_and_last_z() {
let mut s = Session::new();
survey(&mut s);
s.cmdline("line").unwrap();
click(&mut s, Vec2::new(0.01, 0.0), mode::NOD);
click(&mut s, Vec2::new(10.0, 0.01), mode::END);
s.cmdline("20,10,1885").unwrap();
s.cmdline("close").unwrap();
let a = Vec3::new(0.0, 0.0, 1880.0);
let b = Vec3::new(10.0, 0.0, 1881.0);
let c = Vec3::new(20.0, 10.0, 1885.0);
assert_eq!(lines(&s), vec![(a, b), (b, c), (c, a)]);
}
#[test]
fn undoing_a_line_segment_restores_the_previous_points_z() {
let mut s = Session::new();
survey(&mut s);
s.cmdline("line").unwrap();
click(&mut s, Vec2::new(0.01, 0.0), mode::NOD);
click(&mut s, Vec2::new(10.0, 0.01), mode::END);
s.cmdline("20,10,1885").unwrap();
s.cmdline("undo").unwrap();
let a = Vec3::new(0.0, 0.0, 1880.0);
let b = Vec3::new(10.0, 0.0, 1881.0);
assert_eq!(lines(&s), vec![(a, b)]);
s.cmdline("20,20,1889").unwrap();
s.input(cadcraft_engine::Input::Enter).unwrap();
assert_eq!(lines(&s), vec![(a, b), (b, Vec3::new(20.0, 20.0, 1889.0))]);
}
+18
View File
@@ -210,3 +210,21 @@ fn hostile_support_files_never_panic() {
}
assert!(hatches(&s).is_empty());
}
#[test]
fn properties_set_pattern_keeps_a_user_patterns_definition() {
let mut s = Session::new();
s.execute("rectang", &json!({ "p1": [0, 0], "p2": [10, 10] })).unwrap();
s.execute("hatch", &json!({ "points": [[5, 5]], "pattern": "MYGRID", "patternText": PAT })).unwrap();
let hx = s.doc().unwrap().model.iter().find(|e| matches!(e.kind, EntityKind::Hatch(_))).unwrap().handle.hex();
// Setting the same name again keeps the definition the hatch carries.
s.execute("properties.set", &json!({ "handles": [hx], "pattern": "MYGRID" })).unwrap();
assert_eq!(hatches(&s).pop().unwrap().pattern_lines.len(), 2);
// Another loaded .pat pattern brings its own lines.
s.execute("properties.set", &json!({ "handles": [hx], "pattern": "MYSTEPS" })).unwrap();
let h = hatches(&s).pop().unwrap();
assert_eq!((h.pattern.as_str(), h.pattern_lines.first().map(|l| l.dashes.clone())), ("MYSTEPS", Some(vec![0.25, -0.25])));
// A library pattern is drawn from the library, with no lines of its own.
s.execute("properties.set", &json!({ "handles": [hx], "pattern": "ANSI31" })).unwrap();
assert!(hatches(&s).pop().unwrap().pattern_lines.is_empty());
}
+4
View File
@@ -67,6 +67,10 @@ impl Face {
FontRef::from_index(&bytes, index).ok()?;
Some(Face { bytes, index })
}
/// The font file's bytes and this face's index in it (a collection holds several faces).
pub fn data(&self) -> (&Arc<Vec<u8>>, u32) {
(&self.bytes, self.index)
}
pub(crate) fn font(&self) -> Option<FontRef<'_>> {
FontRef::from_index(&self.bytes, self.index).ok()
}
+4 -1
View File
@@ -35,5 +35,8 @@ craft-pdf = { workspace = true, features = ["read"] }
# Inspect DWG output only where craft-dwg builds its native bridge. An unconditional
# dev-dependency also builds acadrust during --all-targets, breaking FreeBSD aarch64 (#2526).
# The storytold/acadrust fork at tag `storytold/v0.6.6` (upstream v0.6.6), the source craft-dwg moves
# to in storytold/craft-libs#4762; until craft-libs is repinned, craft-dwg still takes the identical
# crates.io 0.6.6.
[target.'cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))'.dev-dependencies]
acadrust = "0.6.6"
acadrust = { git = "https://github.com/storytold/acadrust.git", rev = "5d5c482b3fcb3dc77e8281474461760f32959436" }
@@ -0,0 +1,78 @@
//! A visibility parameter in a stretch's selection is carried along with the stretch: its grip
//! goes with it, its record keeps the new position (with its state) through a save, and a state
//! change leaves it where it is.
//!
//! The fixture is the synthetic DOOR block of `dynblock_read`, with Visibility1 (at (18, 40))
//! given a grip and put in the Width stretch's selection, whose frame is widened to hold it.
use cadcraft_doc::dynblock::{GripShape, grips, reference, set_property};
use cadcraft_doc::geom::{Vec2, Vec3};
use cadcraft_doc::{Drawing, EntityKind, Handle};
use cadcraft_io::{read_dxf, write_dxf};
fn dxf(src: &str) -> String {
src.lines()
.map(str::trim)
.filter(|l| !l.is_empty())
.map(|l| {
let (code, value) = l.split_once(' ').unwrap_or((l, ""));
format!("{code}\n{value}\n")
})
.collect()
}
/// DOOR as described above, and a reference to it at (100, 0).
fn door() -> (Drawing, Handle) {
let src = include_str!("../data/dynblock_door.txt")
.replace("\r\n", "\n")
.replace("1030 0\n93 0\n170 0\n171 0\n100 AcDbBlockVisibilityParameter", "1030 0\n93 10\n170 0\n171 0\n100 AcDbBlockVisibilityParameter")
.replace("71 1\n330 30\n1010 40", "71 2\n330 30\n330 62\n1010 40")
.replace("1011 34\n1021 -2\n1011 38\n1021 2\n", "1011 10\n1021 -2\n1011 38\n1021 50\n");
let mut d = read_dxf(dxf(&src).as_bytes()).unwrap();
let ins = cadcraft_doc::Insert {
block: "Door".into(),
insert: Vec3::new(100.0, 0.0, 0.0),
scale: Vec3::new(1.0, 1.0, 1.0),
rotation: 0.0,
attribs: Vec::new(),
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
};
let r = d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), EntityKind::Insert(ins)).unwrap();
(d, r)
}
/// Where the reference's visibility grip is.
fn visibility_grip(d: &Drawing, r: Handle) -> Vec2 {
grips(d, r).into_iter().find(|g| g.shape == GripShape::List && g.property == "Visibility1").map(|g| g.at).unwrap()
}
fn near(a: Vec2, b: (f64, f64)) -> bool {
(a.x - b.0).abs() < 1e-9 && (a.y - b.1).abs() < 1e-9
}
#[test]
fn a_stretch_carries_the_visibility_grip() {
let (mut d, r) = door();
assert!(near(visibility_grip(&d, r), (118.0, 40.0)), "{:?}", grips(&d, r));
// Width 36 → 30: the stretch moves its selection 6 to the left, Visibility1 with it.
set_property(&mut d, r, "Width", "30").unwrap();
assert!(near(visibility_grip(&d, r), (112.0, 40.0)), "{:?}", visibility_grip(&d, r));
let state = |d: &Drawing| reference(d, r).and_then(|x| x.values.get(&1).cloned());
assert_eq!(
serde_json::to_value(state(&d)).unwrap(),
serde_json::json!({ "type": "text", "value": "Open", "at": { "x": 12.0, "y": 40.0, "z": 0.0 } })
);
// Saved and read back where it went.
let again = read_dxf(write_dxf(&d).as_bytes()).unwrap();
assert!(near(visibility_grip(&again, r), (112.0, 40.0)));
// Another state: the grip stays where the stretch put it.
set_property(&mut d, r, "Visibility1", "Closed").unwrap();
assert!(near(visibility_grip(&d, r), (112.0, 40.0)));
}
+1
View File
@@ -35,6 +35,7 @@ mod dynblock_params;
mod dynblock_read;
mod dynblock_rotate_flip;
mod dynblock_scale_polar;
mod dynblock_visibility_position;
mod entity_props_roundtrip;
mod exhausted_handseed;
mod followups_626;
+46 -9
View File
@@ -553,15 +553,29 @@ const MAX_SWATCH_WORK: u64 = 2_000_000;
/// A preview of a pattern for a pattern picker: the runs of its line families `lines` inside the
/// `side` × `side` square with a corner at the origin, at a scale that shows a few repeats of the
/// pattern (each family's line spacing or dash repeat, whichever is longer). Empty for a pattern
/// pattern. For sparse, staggered tile edges the area per mark sets the preview scale. Empty for a pattern
/// with no lines (SOLID).
pub fn pattern_swatch(lines: &[PatternLine], side: f64) -> Vec<Vec<Vec2>> {
let repeat =
lines.iter().map(|l| l.delta.1.abs().max(l.dashes.iter().map(|d| d.abs()).sum::<f64>())).filter(|r| r.is_finite()).fold(0.0, f64::max);
let estimate = |sparse: bool| {
lines
.iter()
.map(|l| {
let spacing = l.delta.1.abs();
let period = l.dashes.iter().map(|d| d.abs()).sum::<f64>();
if sparse && l.delta.0 != 0. && matches!(l.dashes.as_slice(), [ink, gap] if *ink > 0. && -*gap > 32. * spacing) {
(period * spacing).sqrt()
} else {
spacing.max(period)
}
})
.filter(|r| r.is_finite())
.fold(0.0, f64::max)
};
let repeat = estimate(true);
if !side.is_finite() || side <= 0.0 || repeat < 1e-9 {
return Vec::new();
}
let h = Hatch {
let mut h = Hatch {
pattern: String::new(),
solid: false,
loops: Vec::new(),
@@ -578,7 +592,16 @@ pub fn pattern_swatch(lines: &[PatternLine], side: f64) -> Vec<Vec<Vec2>> {
let square = vec![Vec2::new(0.0, 0.0), Vec2::new(side, 0.0), Vec2::new(side, side), Vec2::new(0.0, side)];
// The generator stops at the swatch's own limits, so a compact pattern is never made in full
// (about a million runs) to keep a few thousand.
let mut runs = pattern_lines_within(&Drawing::default(), &h, &[square], 0.0, None, None, MAX_SWATCH_RUNS, MAX_SWATCH_WORK);
let loops = [square];
let render = |h: &Hatch| pattern_lines_within(&Drawing::default(), h, &loops, 0.0, None, None, MAX_SWATCH_RUNS, MAX_SWATCH_WORK);
let mut runs = render(&h);
if runs.is_empty() {
let full = estimate(false);
if full > repeat {
h.scale = side / (SWATCH_REPEATS * full);
runs = render(&h);
}
}
runs.truncate(MAX_SWATCH_RUNS);
runs.shrink_to_fit();
runs
@@ -644,14 +667,18 @@ impl Family<'_> {
let k0 = (lo.y / self.spacing).floor() as i64;
let k1 = (hi.y / self.spacing).ceil() as i64;
let max_lines = if view.is_some() { MAX_VIEW_FAMILY_LINES } else { MAX_FAMILY_LINES };
if k1.saturating_sub(k0) > max_lines {
return;
}
let many_rows = k1.saturating_sub(k0) > max_lines;
let pat_len: f64 = self.dashes.iter().map(|d| d.abs()).sum();
// Level of detail: a whole repeat under two pixels reads as a continuous line (when the
// family draws anything at all).
let draws = self.dashes.iter().any(|d| *d >= 0.0);
let solid_line = self.dashes.is_empty() || pat_len < 1e-12 || (px > 0.0 && pat_len < 2.0 * px && draws);
// Captured tile edges can have many tightly spaced rows, each with a long empty gap.
// Reject empty rows by dash phase before walking or sorting any boundary edges.
let sparse = matches!(self.dashes, [ink, gap] if *ink >= 0. && -*gap > hi.x - lo.x) && !solid_line;
if many_rows && (!sparse || k1.abs_diff(k0) >= *work) {
return;
}
// Each scanline visits every boundary edge and sorts the intersections. Charge both the
// traversal and an n*ceil(log2(n)) upper bound for sorting, scaled to one unit per eight
// operations, whether or not any dash is made.
@@ -662,10 +689,20 @@ impl Family<'_> {
if out.len() >= self.max_runs || crossings_charge > *work || is_set(cancel) {
return;
}
let offset = shift_per_line * k as f64;
if many_rows {
*work -= 1;
let phase = (lo.x - offset).rem_euclid(pat_len);
if phase > self.dashes[0] && pat_len - phase > hi.x - lo.x {
continue;
}
if crossings_charge > *work {
return;
}
}
*work -= crossings_charge;
let y = k as f64 * self.spacing;
let xs = crossings(&local, y);
let offset = shift_per_line * k as f64;
for span in xs.chunks(2) {
let [x0, x1] = span else { continue };
let (x0, x1) = match span_cut {
+4 -4
View File
@@ -84,7 +84,7 @@ enum Tab {
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum View {
pub(crate) enum View {
ExtraLarge,
Large,
#[default]
@@ -95,10 +95,10 @@ enum View {
}
impl View {
const ALL: [View; 6] = [View::ExtraLarge, View::Large, View::Medium, View::Small, View::Details, View::List];
pub(crate) const ALL: [View; 6] = [View::ExtraLarge, View::Large, View::Medium, View::Small, View::Details, View::List];
/// The name shown on the view's button.
fn label(self) -> &'static str {
pub(crate) fn label(self) -> &'static str {
match self {
View::ExtraLarge => crate::tl!("Extra Large Icons"),
View::Large => crate::tl!("Large Icons"),
@@ -110,7 +110,7 @@ impl View {
}
/// The side of a gallery tile, for the icon views.
fn tile(self) -> Option<f32> {
pub(crate) fn tile(self) -> Option<f32> {
match self {
View::ExtraLarge => Some(150.0),
View::Large => Some(104.0),
+29 -4
View File
@@ -1207,6 +1207,27 @@ fn press_at(app: &mut CadApp, xf: &Xf, ctx: &egui::Context, pos: Pos2, mods: egu
!had_window && app.session.pending_window.is_some()
}
/// The selection rectangle to draw from its first corner to the cursor at `c`: that corner, and
/// whether it is a crossing area. An implied window (a click on empty space) crosses when the
/// cursor went leftwards on screen. A `W` or `C` typed at "Select objects" is a window or a
/// crossing whichever way the cursor goes, and `BOX` crosses when the cursor is left of the first
/// corner, as [`cadcraft_engine::select::SelectMode::select_in`] selects. `None` while no
/// rectangle has its first corner.
fn selection_band(session: &cadcraft_engine::Session, c: Vec2) -> Option<(Vec2, bool)> {
use cadcraft_engine::select::SelectKind;
if let Some(pw) = session.pending_window {
return Some((pw.corner, session.window_is_crossing(pw.corner, c)));
}
let mode = session.select_mode.as_ref()?;
let corner = mode.pts.first().copied()?;
match mode.kind {
SelectKind::Window => Some((corner, false)),
SelectKind::Crossing => Some((corner, true)),
SelectKind::Box => Some((corner, c.x < corner.x)),
SelectKind::Fence | SelectKind::WPolygon | SelectKind::CPolygon | SelectKind::Group => None,
}
}
fn paint_canvas(frame: CanvasPaint<'_>) {
let CanvasPaint {
app,
@@ -1344,11 +1365,15 @@ fn paint_canvas(frame: CanvasPaint<'_>) {
draw_list(painter, &xf, &list, bg, false);
}
}
// Pending selection window.
if let (Some(pw), Some(c)) = (app.session.pending_window, raw_world) {
// Pending selection window: an implied one, or a typed W, C or BOX after its first corner.
// Each is drawn to the point its closing click selects with: an implied window to the pointer
// itself, a typed one to the cursor as snaps and the other drawing aids hold it.
let band_to = if app.session.pending_window.is_some() { raw_world } else { app.canvas.cursor };
if let Some(c) = band_to
&& let Some((corner, crossing)) = selection_band(&app.session, c)
{
// The world box it selects (turned in a twisted view).
let corners = [pw.corner, Vec2::new(c.x, pw.corner.y), c, Vec2::new(pw.corner.x, c.y)].map(|q| xf.to_screen(q));
let crossing = app.session.window_is_crossing(pw.corner, c);
let corners = [corner, Vec2::new(c.x, corner.y), c, Vec2::new(corner.x, c.y)].map(|q| xf.to_screen(q));
if let Some(fill) = selection_area_fill(&app.session.settings, crossing) {
painter.add(Shape::convex_polygon(corners.to_vec(), fill, Stroke::NONE));
}
+4 -2
View File
@@ -200,12 +200,14 @@ pub(super) fn override_cursor(app: &mut CadApp, raw: Vec2, xf: &Xf) {
let s = &app.session.settings;
let osmode = over.unwrap_or(s.osmode) | if s.osnaphatch { snap::mode::HATCH } else { 0 };
let Ok(st) = app.session.state() else { return };
let space = st.edit_space();
let frozen = st.viewport_frozen();
let hit = match cycle {
Some(i) => {
let cands = cadcraft_engine::pointmod::snap_candidates(&st.doc, &st.edit_space(), raw, ap, osmode, base, deferred);
let cands = cadcraft_engine::pointmod::snap_candidates_with_frozen(&st.doc, &space, raw, ap, osmode, base, deferred, frozen);
cands.get(i % cands.len().max(1)).copied()
}
None => snap::osnap(&st.doc, &st.edit_space(), raw, ap, osmode, base, deferred),
None => snap::osnap_with_frozen(&st.doc, &space, raw, ap, osmode, base, deferred, frozen),
};
let p = match (hit, app.canvas.snap) {
(Some(h), _) => {
+97 -7
View File
@@ -18,6 +18,8 @@ pub struct CmdLine {
typed_since_selection: bool,
pub history: Vec<String>,
pub history_pos: Option<usize>,
/// Explicit keyboard choice and the command prefix it belongs to.
suggestion: Option<(String, usize)>,
/// What was typed at command prompts (not command names), oldest first: the in-command
/// shortcut menu's Recent Input.
pub recent_input: Vec<String>,
@@ -102,7 +104,7 @@ fn tab(app: &mut CadApp) {
}
app.cmd.first_active = Some(app.cmd.buffer.clone());
}
} else if let Some(s) = suggestions_in(&app.session, &app.cmd.buffer).first() {
} else if let Some(s) = suggestions_in(&app.session, &app.cmd.buffer).get(app.cmd.suggestion_index().unwrap_or(0)) {
app.cmd.buffer = s.id.clone();
}
}
@@ -189,6 +191,10 @@ fn suggestions(prefix: &str, is_own_command: &dyn Fn(&str) -> bool) -> Vec<Sugge
}
impl CmdLine {
fn suggestion_index(&self) -> Option<usize> {
self.suggestion.as_ref().filter(|(prefix, _)| prefix == &self.buffer).map(|(_, index)| *index)
}
/// Track the selection: a new selection starts with nothing typed since.
pub fn watch_selection(&mut self, sel: &[cadcraft_doc::Handle]) {
if self.seen_selection != sel {
@@ -247,6 +253,7 @@ impl CmdLine {
/// again later does not lock anything without Tab.
pub fn clear_entry(&mut self) {
self.buffer.clear();
self.suggestion = None;
self.first_active = None;
self.locked_second = None;
}
@@ -452,6 +459,14 @@ pub fn keyboard(app: &mut CadApp, ctx: &egui::Context) {
app.cmd.backspace();
}
}
Key::ArrowUp | Key::ArrowDown if modifiers == egui::Modifiers::SHIFT && !app.session.prompting() => {
let count = suggestions_in(&app.session, &app.cmd.buffer).len();
if count > 0 {
let index = app.cmd.suggestion_index().unwrap_or(0);
let step = if key == Key::ArrowDown { 1 } else { count - 1 };
app.cmd.suggestion = Some((app.cmd.buffer.clone(), (index + step) % count));
}
}
Key::ArrowUp if !modifiers.any() && !app.cmd.history.is_empty() => {
let n = app.cmd.history.len();
let pos = app.cmd.history_pos.map(|p| p.saturating_sub(1)).unwrap_or(n - 1);
@@ -482,6 +497,9 @@ pub fn keyboard(app: &mut CadApp, ctx: &egui::Context) {
},
_ => {}
}
if app.cmd.suggestion_index().is_none() {
app.cmd.suggestion = None;
}
app.cmd.note_typing();
}
app.cmd.forget_stale_first(dyn_frame(app).is_some());
@@ -512,7 +530,21 @@ pub fn submit(app: &mut CadApp) {
app.cmd.buffer = text;
}
}
let text = std::mem::take(&mut app.cmd.buffer);
let selected = app.cmd.suggestion_index();
app.cmd.suggestion = None;
let mut text = std::mem::take(&mut app.cmd.buffer);
// Keep the normal alias and unknown-command fallback until the user explicitly chooses a row.
let mut completion = None;
if !app.session.prompting()
&& !text.trim().is_empty()
&& let Some(choice) = suggestions_in(&app.session, text.trim()).into_iter().nth(selected.unwrap_or(0))
{
if selected.is_some() {
text = choice.id;
} else {
completion = Some(choice.id.to_ascii_lowercase());
}
}
app.cmd.locked_second = None;
app.cmd.first_active = None;
app.cmd.history_pos = None;
@@ -533,9 +565,7 @@ pub fn submit(app: &mut CadApp) {
if !app.session.prompting() && app.open_typed(&text) {
return;
}
// A partly typed command name runs the highlighted (first) AutoComplete suggestion.
let completion = if app.session.prompting() { None } else { suggestions_in(&app.session, text.trim()).into_iter().next() };
app.cmdline_or(&text, completion.map(|s| s.id.to_ascii_lowercase()).as_deref());
app.cmdline_or(&text, completion.as_deref());
}
fn visible_lines(app: &CadApp, canvas: Rect, bar: Rect) -> usize {
@@ -690,7 +720,9 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui, canvas: Rect) {
for (i, s) in sug.iter().enumerate() {
let r = Rect::from_min_size(pos2(lr.left(), lr.top() + rh * i as f32), vec2(lr.width(), rh));
let resp = ui.interact(r, ui.scope_id().with(("sug", i)), Sense::click());
if resp.hovered() || i == 0 {
let selected = i == app.cmd.suggestion_index().unwrap_or(0);
resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, resp.enabled(), selected, &s.display));
if resp.hovered() || selected {
p.rect_filled(r.shrink(1.0), 2.0, if resp.hovered() { t.cmd_keyword_hover } else { t.list_row });
}
p.text(Pos2::new(r.left() + 8.0, r.center().y), egui::Align2::LEFT_CENTER, &s.display, crate::theme::body(), t.text);
@@ -833,7 +865,7 @@ mod tests {
assert_eq!(app.ui.history_lines, 12);
}
fn frame(app: &mut CadApp, ctx: &egui::Context, events: Vec<Event>) -> egui::FullOutput {
pub(super) fn frame(app: &mut CadApp, ctx: &egui::Context, events: Vec<Event>) -> egui::FullOutput {
let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1400.0, 900.0))), events, ..Default::default() };
let mut out = ctx.run_ui(raw, |ui| {
app.logic(ui.ctx());
@@ -1031,6 +1063,7 @@ mod delete_key_tests {
#[cfg(test)]
mod autocomplete_tests {
use super::tests::frame;
use super::*;
#[test]
@@ -1077,6 +1110,63 @@ mod autocomplete_tests {
assert_eq!(app.cmd.buffer, "RECTANG");
}
fn key(key: Key, modifiers: egui::Modifiers) -> egui::Event {
egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }
}
fn keyboard_context(app: &mut CadApp) -> egui::Context {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
frame(app, &ctx, Vec::new());
ctx
}
#[test]
fn arrows_browse_history_and_shift_arrows_cycle_before_tab() {
use egui::Modifiers as M;
let mut app = app();
let ctx = keyboard_context(&mut app);
app.cmd.history = vec!["line".into(), "rec".into()];
frame(&mut app, &ctx, vec![key(Key::ArrowUp, M::NONE), key(Key::ArrowUp, M::NONE)]);
assert_eq!(app.cmd.buffer, "line");
frame(&mut app, &ctx, vec![key(Key::ArrowDown, M::NONE)]);
assert_eq!(app.cmd.buffer, "rec");
let count = suggestions_in(&app.session, "rec").len();
frame(&mut app, &ctx, vec![key(Key::ArrowUp, M::SHIFT)]);
assert_eq!(app.cmd.suggestion_index(), Some(count - 1));
frame(&mut app, &ctx, vec![key(Key::ArrowDown, M::SHIFT), key(Key::ArrowDown, M::SHIFT), key(Key::Tab, M::NONE)]);
assert_eq!(app.cmd.buffer, "RECOVER");
assert_eq!(app.cmd.history_pos, Some(1));
}
#[test]
fn enter_and_space_start_the_chosen_command_even_for_an_exact_alias() {
use egui::Modifiers as M;
for accept in [vec![key(Key::Enter, M::NONE)], vec![key(Key::Space, M::NONE), egui::Event::Text(" ".into())]] {
let mut app = app();
let ctx = keyboard_context(&mut app);
app.cmd.buffer = "c".into();
let choices = suggestions_in(&app.session, "c");
let index = choices.iter().position(|s| s.id == "COPY").unwrap();
assert!(index > 0);
frame(&mut app, &ctx, vec![key(Key::ArrowDown, M::SHIFT); index]);
frame(&mut app, &ctx, accept);
assert_eq!(app.session.running.as_ref().map(|r| r.id.as_str()), Some("copy"));
assert_eq!(app.cmd.history.last().map(String::as_str), Some("COPY"));
}
}
#[test]
fn editing_the_prefix_discards_the_selection() {
use egui::Modifiers as M;
let mut app = app();
let ctx = keyboard_context(&mut app);
app.cmd.buffer = "rec".into();
frame(&mut app, &ctx, vec![key(Key::ArrowDown, M::SHIFT), egui::Event::Text("t".into()), key(Key::Backspace, M::NONE)]);
assert_eq!(app.cmd.buffer, "rec");
assert_eq!(app.cmd.suggestion_index(), None);
}
fn app() -> CadApp {
let mut app = CadApp::new(cadcraft_engine::Session::empty(), crate::Services::default());
app.start("ui.sample");
+220 -12
View File
@@ -46,7 +46,10 @@ pub struct Fill {
/// The dialog while open (and while a pick it started runs).
#[derive(Clone, Debug, PartialEq)]
pub struct HatchDlgState {
choices: Vec<cadcraft_engine::PatternChoice>,
pub fill: Fill,
custom: Option<CustomPattern>,
saved_source: Option<String>,
/// The fill as the dialog opened: edit mode sends only what changed.
pub opened: Fill,
/// The hatches being edited; empty in create mode.
@@ -61,6 +64,8 @@ pub struct HatchDlgState {
pub remove_loops: Vec<usize>,
/// A HATCHPICK the dialog started that hasn't ended yet.
pub picking: Option<PickMode>,
/// The next point pick defines a repeating tile for the custom pattern.
capture_tile: bool,
/// The last command error, shown in the dialog.
pub error: Option<String>,
/// The drawing the dialog belongs to (`DocState::uid`).
@@ -70,9 +75,79 @@ pub struct HatchDlgState {
pub space: Space,
}
#[derive(Clone, Debug, PartialEq)]
struct CustomPattern {
name: String,
families: Vec<PatternFamily>,
}
#[derive(Clone, Debug, PartialEq)]
struct PatternFamily {
origin: (f64, f64),
shift: f64,
angle: f64,
spacing: f64,
dashes: String,
}
impl Default for PatternFamily {
fn default() -> Self {
Self { origin: (0., 0.), shift: 0., angle: 45.0, spacing: 5.0, dashes: String::new() }
}
}
fn available_name(base: &str) -> String {
let choices = cadcraft_engine::pattern_choices();
let used = |name: &str| choices.iter().any(|p| p.name.eq_ignore_ascii_case(name));
let mut name = base.to_owned();
let mut suffix = 2;
while used(&name) {
name = format!("{base}_{suffix}");
suffix += 1;
}
name
}
impl Default for CustomPattern {
fn default() -> Self {
Self { name: available_name("MY_PATTERN"), families: vec![PatternFamily::default()] }
}
}
impl CustomPattern {
fn encode(&self) -> Option<(String, String)> {
let name = self.name.trim().to_ascii_uppercase();
if name.is_empty() || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') || cadcraft_doc::library::is_reserved_pattern_name(&name)
{
return None;
}
let mut text = format!("*{name}, Custom pattern\n");
for family in &self.families {
if !family.angle.is_finite() || !family.spacing.is_finite() || family.spacing <= 0.0 {
return None;
}
text.push_str(&format!("{},{},{},{},{}", family.angle, family.origin.0, family.origin.1, family.shift, family.spacing));
if !family.dashes.trim().is_empty() {
let dashes: Vec<_> =
family.dashes.split_whitespace().map(|value| value.parse::<f64>().ok().filter(|v| v.is_finite())).collect::<Option<_>>()?;
if dashes.iter().all(|d| *d == 0.0) {
return None;
}
for dash in dashes {
text.push_str(&format!(",{dash}"));
}
}
text.push('\n');
}
let parsed = cadcraft_doc::library::files::parse_pat(&text);
(parsed.items.len() == 1 && parsed.warnings.is_empty()).then_some((name, text))
}
}
/// Create mode, from the drawing's HATCH settings (HPNAME, HPSCALE, HPANG, HPASSOC, HPSEPARATE,
/// HPORIGINMODE, HPISLANDDETECTION); values a file got wrong fall back to the defaults.
pub fn create_state(d: &Drawing, uid: u64, gradient: bool) -> HatchDlgState {
cadcraft_engine::register_drawing_patterns(d);
let h = &d.header;
let scale = Some(h.f64("HPSCALE", 1.0)).filter(|v| v.is_finite() && *v > 0.0).unwrap_or(1.0);
let angle = Some(h.f64("HPANG", 0.0).to_degrees()).filter(|v| v.is_finite()).unwrap_or(0.0);
@@ -96,8 +171,11 @@ pub fn create_state(d: &Drawing, uid: u64, gradient: bool) -> HatchDlgState {
style: u8::try_from(h.i64("HPISLANDDETECTION", 0).clamp(0, 2)).unwrap_or(0),
};
HatchDlgState {
choices: cadcraft_engine::pattern_choices_in(d),
opened: fill.clone(),
fill,
custom: None,
saved_source: None,
edit: Vec::new(),
separate: h.i64("HPSEPARATE", 0) != 0,
points: Vec::new(),
@@ -105,6 +183,7 @@ pub fn create_state(d: &Drawing, uid: u64, gradient: bool) -> HatchDlgState {
loop_outer: Vec::new(),
remove_loops: Vec::new(),
picking: None,
capture_tile: false,
error: None,
uid,
space: Space::Model,
@@ -189,7 +268,17 @@ pub fn ok_call(st: &HatchDlgState) -> Option<(&'static str, Value)> {
p.insert("color2".into(), json!(f.color2.name()));
p.insert("centered".into(), json!(f.centered));
} else {
p.insert("pattern".into(), json!(f.pattern));
let pattern = if let Some(custom) = &st.custom {
let (name, text) = custom.encode()?;
p.insert("patternText".into(), json!(text));
name
} else {
if let Some(text) = &st.saved_source {
p.insert("patternText".into(), json!(text));
}
f.pattern.clone()
};
p.insert("pattern".into(), json!(pattern));
p.insert("scale".into(), json!(f.scale));
}
p.insert("angle".into(), json!(f.angle));
@@ -260,7 +349,7 @@ pub fn ok_call(st: &HatchDlgState) -> Option<(&'static str, Value)> {
/// Take a HATCHPICK's picks into the dialog (Hatch picks are taken by `resume`).
pub fn merge_picks(st: &mut HatchDlgState, picks: HatchPicks) {
match picks.mode {
PickMode::Points | PickMode::Objects => {
PickMode::Points | PickMode::TileRect | PickMode::Objects => {
st.points.extend(picks.points.iter().map(|q| [q.x, q.y]));
for h in picks.handles {
if !st.handles.contains(&h) {
@@ -324,6 +413,7 @@ pub fn start_pick(app: &mut CadApp, mode: PickMode) {
app.start("hatchpick");
let kw = match mode {
PickMode::Points => "Points",
PickMode::TileRect => "TileRect",
PickMode::Objects => "Objects",
PickMode::Origin => "oRigin",
PickMode::Hatch => "Hatch",
@@ -335,6 +425,27 @@ pub fn start_pick(app: &mut CadApp, mode: PickMode) {
}
}
/// Convert the engine's PAT result into editable fields in the dialog.
fn capture_draft(app: &mut CadApp, a: cadcraft_geom::Vec2, b: cadcraft_geom::Vec2) -> Result<CustomPattern, String> {
let params = json!({"first":[a.x,a.y], "second":[b.x,b.y], "name":available_name("CAPTURED_TILE")});
let result = app.run("hatch.capture", params)?;
let text = result["patternText"].as_str().ok_or_else(|| crate::tl!("Missing captured PAT definition").to_owned())?;
let parsed = cadcraft_doc::library::files::parse_pat(text);
let pattern = parsed.items.into_iter().next().ok_or_else(|| crate::tl!("Invalid captured PAT definition").to_owned())?;
let families = pattern
.lines
.into_iter()
.map(|line| PatternFamily {
origin: line.origin,
shift: line.delta.0,
angle: line.angle,
spacing: line.delta.1,
dashes: line.dashes.iter().map(ToString::to_string).collect::<Vec<_>>().join(" "),
})
.collect();
Ok(CustomPattern { name: pattern.name, families })
}
/// Every frame: once a HATCHPICK the dialog started has ended, take its picks and bring the
/// dialog back (unchanged when the pick was cancelled). A different drawing by then drops the
/// dialog and its picks; a Hatch pick that found none closes it.
@@ -356,7 +467,17 @@ pub fn resume(app: &mut CadApp) {
next.space = st.space.clone();
st = next;
} else if let Some(p) = picks {
merge_picks(&mut st, p);
if st.capture_tile && mode == PickMode::TileRect {
st.capture_tile = false;
if let [a, b] = p.points.as_slice() {
match capture_draft(app, *a, *b) {
Ok(pattern) => st.custom = Some(pattern),
Err(message) => st.error = Some(message),
}
}
} else {
merge_picks(&mut st, p);
}
}
app.hatch_dlg = Some(st);
app.ui.dialog = Some("hatch".into());
@@ -370,8 +491,12 @@ pub fn ok(app: &mut CadApp) -> bool {
app.hatch_dlg = None;
return true;
};
let authored = p["pattern"].as_str().zip(p["patternText"].as_str()).map(|(n, t)| (n.to_owned(), t.to_owned()));
match app.run(cmd, p) {
Ok(_) => {
if let Some((name, text)) = authored {
app.ui.hatch_patterns.insert(name, text);
}
app.hatch_dlg = None;
true
}
@@ -384,7 +509,31 @@ pub fn ok(app: &mut CadApp) -> bool {
}
}
/// Register a finished draft even when the user has not picked a surface to fill.
fn save_pattern(app: &mut CadApp) {
let Some((name, text)) = app.hatch_dlg.as_ref().and_then(|s| s.custom.as_ref()).and_then(CustomPattern::encode) else { return };
let result = app.run("hatch.patterns", json!({"text": text}));
let Some(st) = app.hatch_dlg.as_mut() else { return };
match result {
Ok(value) if value["added"].as_array().is_some_and(|a| a.iter().any(|n| n.as_str() == Some(&name))) => {
st.saved_source = Some(text.clone());
app.ui.hatch_patterns.insert(name.clone(), text);
st.fill.pattern = name;
if let Ok(d) = app.session.doc() {
st.choices = cadcraft_engine::pattern_choices_in(d);
}
st.custom = None;
st.error = None;
}
Ok(value) => {
st.error = Some(value["warnings"].as_array().into_iter().flatten().filter_map(Value::as_str).collect::<Vec<_>>().join("\n"));
}
Err(error) => st.error = Some(error),
}
}
enum Action {
SavePattern,
None,
Ok,
Cancel,
@@ -429,12 +578,16 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
return;
};
let title = if st.edit.is_empty() { crate::tl!("Hatch and Gradient") } else { crate::tl!("Hatch Edit") };
let mut action = Action::None;
// Esc cancels, as the Cancel button does.
let mut action = if crate::framework::escape_pressed(ctx) { Action::Cancel } else { Action::None };
egui::Window::new(title).id(egui::Id::unique("hatch_dialog")).open(open).collapsible(false).resizable(false).show(ctx, |ui| {
ui.horizontal_top(|ui| {
ui.vertical(|ui| {
ui.set_width(340.0);
fill_ui(ui, &mut st.fill, &mut action);
fill_ui(ui, &mut st.fill, &st.choices, &mut st.saved_source, &mut action);
if st.edit.is_empty() && !st.fill.gradient {
custom_pattern_ui(ui, &mut st.custom, &mut st.capture_tile, &mut action);
}
});
// Space, not a vertical separator: a separator takes the height available, and the
// window grew by it every frame until the buttons left the screen.
@@ -449,7 +602,8 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
}
ui.separator();
ui.horizontal(|ui| {
let ready = !st.edit.is_empty() || !(st.points.is_empty() && st.handles.is_empty());
let valid = st.fill.gradient || st.custom.as_ref().is_none_or(|draft| draft.encode().is_some());
let ready = valid && (!st.edit.is_empty() || !(st.points.is_empty() && st.handles.is_empty()));
if ui.add_enabled(ready, egui::Button::new(crate::tl!("OK"))).clicked() {
action = Action::Ok;
}
@@ -469,6 +623,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
app.hatch_dlg = None;
*open = false;
}
Action::SavePattern => save_pattern(app),
Action::Pick(mode) => start_pick(app, mode),
Action::None => {
if !*open {
@@ -478,8 +633,62 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
}
}
fn custom_pattern_ui(ui: &mut egui::Ui, custom: &mut Option<CustomPattern>, capture_tile: &mut bool, action: &mut Action) {
let mut enabled = custom.is_some();
if ui.checkbox(&mut enabled, crate::tl!("Create a custom hatch pattern")).changed() {
*custom = enabled.then(CustomPattern::default);
}
let Some(draft) = custom else { return };
if ui
.button(crate::tl!("Capture square tile from drawing"))
.on_hover_text(crate::tl!("Pick two opposite corners to define the repeating tile"))
.clicked()
{
// The two corners become the horizontal and vertical repeat steps.
// The normal boundary picker remains available separately.
*capture_tile = true;
*action = Action::Pick(PickMode::TileRect);
}
let name = ui.label(crate::tl!("Pattern name"));
ui.add(egui::TextEdit::singleline(&mut draft.name).char_limit(31)).labelled_by(name.id);
ui.label(crate::tl!("Use spaces between dashes: positive draws, negative skips, zero marks a dot."));
let mut remove = None;
egui::ScrollArea::vertical().id_salt("custom-hatch-families").max_height(125.0).show(ui, |ui| {
for (index, family) in draft.families.iter_mut().enumerate() {
ui.push_id(index, |ui| {
ui.horizontal(|ui| {
let angle = ui.label(crate::tl!("Angle"));
ui.add(egui::DragValue::new(&mut family.angle).suffix("°")).labelled_by(angle.id);
let spacing = ui.label(crate::tl!("Spacing"));
ui.add(egui::DragValue::new(&mut family.spacing).range(0.0001..=1e6).clamp_existing_to_range(false)).labelled_by(spacing.id);
let dashes = ui.label(crate::tl!("Dashes"));
ui.add(egui::TextEdit::singleline(&mut family.dashes).char_limit(120).desired_width(70.0)).labelled_by(dashes.id);
if ui.small_button("×").on_hover_text(crate::tl!("Remove")).clicked() {
remove = Some(index);
}
})
});
}
});
if let Some(index) = remove
&& draft.families.len() > 1
{
draft.families.remove(index);
}
if ui.add_enabled(draft.families.len() < 16, egui::Button::new(crate::tl!("Add line family"))).clicked() {
draft.families.push(PatternFamily::default());
}
let valid = draft.encode().is_some();
if ui.add_enabled(valid, egui::Button::new(crate::tl!("Save pattern"))).clicked() {
*action = Action::SavePattern;
}
if !valid {
ui.colored_label(Tokens::get().warn, crate::tl!("Check the pattern name, spacing and dash values."));
}
}
/// Pattern/gradient fill selector and its controls; an origin pick is reported through `action`.
fn fill_ui(ui: &mut egui::Ui, f: &mut Fill, action: &mut Action) {
fn fill_ui(ui: &mut egui::Ui, f: &mut Fill, choices: &[cadcraft_engine::PatternChoice], saved_source: &mut Option<String>, action: &mut Action) {
ui.horizontal(|ui| {
ui.selectable_value(&mut f.gradient, false, crate::tl!("Pattern"));
ui.selectable_value(&mut f.gradient, true, crate::tl!("Gradient"));
@@ -515,11 +724,10 @@ fn fill_ui(ui: &mut egui::Ui, f: &mut Fill, action: &mut Action) {
ui.end_row();
});
} else {
egui::ScrollArea::vertical().id_salt("hatch_swatches").max_height(220.0).show(ui, |ui| {
if let Some(name) = crate::palettes::patterns::grid(ui, &f.pattern, "") {
f.pattern = name;
}
});
if let Some(name) = crate::palettes::patterns::manager(ui, &f.pattern, choices) {
*saved_source = None;
f.pattern = name;
}
egui::Grid::new("hatch_pattern").num_columns(2).spacing(vec2(12.0, 6.0)).show(ui, |ui| {
ui.label(crate::tl!("Angle"));
ui.add(egui::DragValue::new(&mut f.angle).speed(1.0).range(-360.0..=360.0).clamp_existing_to_range(false).suffix("°"));
+377
View File
@@ -19,6 +19,13 @@ fn app_with_rect() -> (CadApp, Handle) {
(CadApp::new(s, Services::default()), r)
}
#[test]
fn capture_errors_use_the_dialog_translation_keys() {
let mut app = CadApp::new(Session::new(), Services::default());
assert_eq!(capture_draft(&mut app, Vec2::ZERO, Vec2::ZERO).unwrap_err(), crate::tl!("Pick two opposite corners for the tile"));
assert_eq!(capture_draft(&mut app, Vec2::ZERO, Vec2::new(10., 10.)).unwrap_err(), crate::tl!("No complete line segments in the selected tile."));
}
#[test]
fn pick_points_hides_the_dialog_and_brings_it_back_with_the_points() {
let (mut app, _) = app_with_rect();
@@ -471,3 +478,373 @@ fn edit_mode_leaves_out_a_selected_hatch_the_viewport_does_not_draw() {
assert_eq!(app.hatch_dlg.as_ref().map(|d| d.edit.clone()), Some(Vec::new()), "a hatch the viewport does not draw must not be edited");
assert!(app.session.running.is_some(), "HATCHPICK must be asking for a hatch");
}
#[test]
fn captured_tile_keeps_l_segments_and_excludes_outside_line() {
use cadcraft_doc::{Common, Line};
use cadcraft_engine::geom::Vec3;
let mut app = CadApp::new(Session::new(), Services::default());
for (a, b) in [([32., 42.], [32., 46.]), ([35., 42.], [32., 42.]), ([50., 60.], [57., 60.])] {
app.session
.doc_mut()
.unwrap()
.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: Vec3::new(a[0], a[1], 0.), b: Vec3::new(b[0], b[1], 0.) }))
.unwrap();
}
open_create(&mut app, false);
app.hatch_dlg.as_mut().unwrap().capture_tile = true;
start_pick(&mut app, PickMode::TileRect);
for point in [Vec2::new(40., 50.), Vec2::new(30., 40.)] {
app.session.input(cadcraft_engine::Input::Point(point)).unwrap();
}
resume(&mut app);
let (_, text) = app.hatch_dlg.as_ref().unwrap().custom.as_ref().unwrap().encode().unwrap();
assert!(text.contains(",3,-7"), "horizontal L segment must repeat every 10 units: {text}");
assert!(text.contains(",4,-6"), "vertical L segment must repeat every 10 units: {text}");
assert!(!text.contains(",7,-3"), "outside segment must be excluded");
let rect = app.session.execute("rectang", &json!({"p1":[0,0],"p2":[30,20]})).unwrap();
app.hatch_dlg.as_mut().unwrap().handles.push(Handle::parse_hex(rect["handle"].as_str().unwrap()).unwrap());
assert!(ok(&mut app));
let d = app.session.doc().unwrap();
let reopened = cadcraft_io::read_dxf(cadcraft_io::write_dxf(d).as_bytes()).unwrap();
for drawing in [d, &reopened] {
let handle = drawing.model.iter().find(|e| matches!(e.kind, EntityKind::Hatch(_))).unwrap().handle;
let list = cadcraft_render::build(drawing, &Space::Model, &Default::default());
let segments: Vec<_> = list
.prims
.iter()
.filter(|p| p.handle == handle && p.kind == cadcraft_render::Kind::Polyline)
.map(|p| &list.verts[p.start as usize..(p.start + p.len) as usize])
.collect();
assert_eq!(segments.len(), 12, "two segments in each of six tiles: {segments:?}");
for x in [2., 12., 22.] {
for y in [2., 12.] {
let corner = Vec2::new(x, y);
for tip in [corner + Vec2::new(3., 0.), corner + Vec2::new(0., 4.)] {
assert!(
segments.iter().any(|s| s.len() == 2
&& ((s[0].dist(corner) < 1e-7 && s[1].dist(tip) < 1e-7) || (s[1].dist(corner) < 1e-7 && s[0].dist(tip) < 1e-7))),
"missing {corner:?} to {tip:?}: {segments:?}"
);
}
}
}
}
}
#[test]
fn tile_corners_do_not_require_closed_boundaries() {
let mut app = CadApp::new(Session::new(), Services::default());
open_create(&mut app, false);
start_pick(&mut app, PickMode::TileRect);
app.session.input(cadcraft_engine::Input::Enter).unwrap();
assert!(app.session.prompt_text().contains("first corner"));
app.session.input(cadcraft_engine::Input::Point(Vec2::new(20.0, 30.0))).unwrap();
app.session.input(cadcraft_engine::Input::Enter).unwrap();
assert!(app.session.prompt_text().contains("opposite corner"));
app.session.cmdline("Undo").unwrap();
assert!(app.session.prompt_text().contains("first corner"));
app.session.input(cadcraft_engine::Input::Point(Vec2::new(20.0, 30.0))).unwrap();
app.session.input(cadcraft_engine::Input::Point(Vec2::new(40.0, 50.0))).unwrap();
assert!(app.session.running.is_none());
assert_eq!(app.session.hatch_picks.as_ref().unwrap().points.len(), 2);
}
#[test]
fn a_custom_hatch_created_in_the_dialog_stores_its_line_families() {
let (mut app, boundary) = app_with_rect();
open_create(&mut app, false);
let state = app.hatch_dlg.as_mut().unwrap();
state.handles.push(boundary);
state.custom = Some(CustomPattern {
name: "DIEVART_TEST_HATCH".into(),
families: vec![PatternFamily::default(), PatternFamily { angle: 90.0, spacing: 3.0, dashes: "2 -1".into(), ..Default::default() }],
});
assert!(ok(&mut app));
let drawing = app.session.doc().unwrap();
let hatch = drawing.model.iter().find_map(|e| if let EntityKind::Hatch(hatch) = &e.kind { Some(hatch) } else { None }).unwrap();
assert_eq!(hatch.pattern, "DIEVART_TEST_HATCH");
assert_eq!(hatch.pattern_lines.len(), 2);
let expected = hatch.pattern_lines.clone();
let prefs = app.prefs_json();
let mut restarted = CadApp::new(Session::new(), Services::default());
// Replace the in-memory definition so success requires reading the saved families.
restarted.session.execute("hatch.patterns", &json!({"text":"*DIEVART_TEST_HATCH, temporary\n0,0,0,0,7\n"})).unwrap();
restarted.load_prefs(&prefs);
let restored = cadcraft_engine::pattern_choices().into_iter().find(|p| p.name == hatch.pattern).unwrap();
assert_eq!(restored.lines, expected);
assert_ne!(available_name(&hatch.pattern), hatch.pattern);
assert_eq!(restarted.ui.hatch_patterns, app.ui.hatch_patterns);
// An older DXF has an embedded definition, even on a machine without the author's preferences.
let dxf = cadcraft_io::write_dxf(drawing).replace("DIEVART_TEST_HATCH", "OLDER_EMBEDDED_TEST");
let reopened = cadcraft_io::read_dxf(dxf.as_bytes()).unwrap();
create_state(&reopened, 99, false);
let embedded = cadcraft_engine::pattern_choices().into_iter().find(|p| p.name == "OLDER_EMBEDDED_TEST").unwrap();
assert_eq!(embedded.lines.len(), expected.len());
}
#[test]
fn escape_closes_the_dialog_as_cancel_does() {
let (mut app, _) = app_with_rect();
open_create(&mut app, false);
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut open = true;
let esc = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
let mut out = ctx.run_ui(egui::RawInput { events: vec![esc], ..Default::default() }, |ui| dialog(&mut app, ui.ctx(), &mut open));
out.textures_delta.clear();
assert!(!open && app.hatch_dlg.is_none());
}
#[test]
fn stone_tile_excludes_skewed_frame_and_repeats_open_and_closed_polylines() {
use cadcraft_doc::{Common, LwPolyline};
use cadcraft_geom::PolyVertex;
let mut app = CadApp::new(Session::new(), Services::default());
let u = Vec2::new(700., 0.35);
let v = Vec2::new(0., 700.);
let stone = [Vec2::new(111.23, 161.71), Vec2::new(132.01, 158.33), Vec2::new(120.57, 147.83)];
let joint = [Vec2::new(0., 611.31), Vec2::new(21.49, 621.15), Vec2::new(66.21, 615.19)];
for (points, closed) in [(&[Vec2::ZERO, u, u + v, v][..], true), (&stone[..], true), (&joint[..], false)] {
let poly =
LwPolyline { vertices: points.iter().copied().map(PolyVertex::new).collect(), closed, const_width: 0., elevation: 0., plinegen: false };
app.session.doc_mut().unwrap().add(&Space::Model, Common::default(), EntityKind::LwPolyline(poly)).unwrap();
}
let custom = capture_draft(&mut app, u + v, Vec2::ZERO).unwrap();
assert_eq!(custom.families.len(), 5);
open_create(&mut app, false);
let rect = app.session.execute("rectang", &json!({"p1":[0,0],"p2":[1400,700]})).unwrap();
let state = app.hatch_dlg.as_mut().unwrap();
state.custom = Some(custom);
state.handles.push(Handle::parse_hex(rect["handle"].as_str().unwrap()).unwrap());
assert!(ok(&mut app));
let drawing = cadcraft_io::read_dxf(cadcraft_io::write_dxf(app.session.doc().unwrap()).as_bytes()).unwrap();
let handle = drawing.model.iter().find(|e| matches!(e.kind, EntityKind::Hatch(_))).unwrap().handle;
let list = cadcraft_render::build(&drawing, &Space::Model, &Default::default());
let runs: Vec<_> = list
.prims
.iter()
.filter(|p| p.handle == handle && p.kind == cadcraft_render::Kind::Polyline)
.map(|p| &list.verts[p.start as usize..(p.start + p.len) as usize])
.collect();
for offset in [Vec2::ZERO, u] {
for (a, b) in [(stone[0], stone[1]), (stone[1], stone[2]), (stone[2], stone[0]), (joint[0], joint[1]), (joint[1], joint[2])] {
let (a, b) = (a + offset, b + offset);
assert!(
runs.iter().any(|s| s.len() == 2 && ((s[0].dist(a) < 0.25 && s[1].dist(b) < 0.25) || (s[1].dist(a) < 0.25 && s[0].dist(b) < 0.25))),
"missing {a:?} to {b:?}"
);
}
}
}
#[test]
fn crossed_four_corner_polyline_is_part_of_the_motif() {
use cadcraft_doc::{Common, LwPolyline};
use cadcraft_geom::PolyVertex;
let mut app = CadApp::new(Session::new(), Services::default());
let corners = [Vec2::ZERO, Vec2::new(10., 10.), Vec2::new(0., 10.), Vec2::new(10., 0.)];
let poly =
LwPolyline { vertices: corners.into_iter().map(PolyVertex::new).collect(), closed: true, const_width: 0., elevation: 0., plinegen: false };
app.session.doc_mut().unwrap().add(&Space::Model, Common::default(), EntityKind::LwPolyline(poly)).unwrap();
let custom = capture_draft(&mut app, Vec2::ZERO, corners[1]).unwrap();
assert_eq!(custom.families.len(), 4);
}
#[test]
fn shallow_captured_edge_repeats_over_a_hundred_by_a_hundred_tiles() {
let mut app = CadApp::new(Session::new(), Services::default());
let tile = 10.;
let a = Vec2::new(0., 2.);
let b = a + Vec2::new(2047., 1.) * (tile / 2048.);
app.session.execute("line", &json!({"points":[[a.x,a.y],[b.x,b.y]]})).unwrap();
let capture = app.session.execute("hatch.capture", &json!({"first":[0,0],"second":[tile,tile],"name":"SHALLOW_CAPTURE_TEST"})).unwrap();
let text = &capture["patternText"];
let r = app.session.execute("rectang", &json!({"p1":[0,0],"p2":[1000,1000]})).unwrap();
app.session.execute("hatch", &json!({"handles":[r["handle"]],"pattern":"SHALLOW_CAPTURE_TEST","patternText":text})).unwrap();
let d = app.session.doc().unwrap();
let h = d.model.iter().find(|e| matches!(e.kind, EntityKind::Hatch(_))).unwrap().handle;
let list = cadcraft_render::build(d, &Space::Model, &Default::default());
let runs = list.prims.iter().filter(|p| p.handle == h && p.kind == cadcraft_render::Kind::Polyline);
let full = runs
.filter(|p| {
let seg = &list.verts[p.start as usize..(p.start + p.len) as usize];
seg.len() == 2 && (seg[0].dist(seg[1]) - a.dist(b)).abs() < 1e-6
})
.count();
assert_eq!(full, 10000);
}
#[test]
fn save_pattern_without_applying_it_then_use_it_in_a_new_drawing() {
let mut app = CadApp::new(Session::new(), Services::default());
open_create(&mut app, false);
app.hatch_dlg.as_mut().unwrap().custom = Some(CustomPattern { name: "UNAPPLIED_TILE_TEST".into(), families: vec![PatternFamily::default()] });
save_pattern(&mut app);
let st = app.hatch_dlg.as_ref().unwrap();
assert_eq!(st.fill.pattern, "UNAPPLIED_TILE_TEST");
assert!(st.custom.is_none() && st.error.is_none() && app.session.doc().unwrap().model.iter().next().is_none());
let (mut reopened, boundary) = app_with_rect();
reopened.load_prefs(&app.prefs_json());
open_create(&mut reopened, false);
let st = reopened.hatch_dlg.as_mut().unwrap();
st.fill.pattern = cadcraft_engine::pattern_choices().into_iter().find(|p| p.name == "UNAPPLIED_TILE_TEST").unwrap().name;
st.handles.push(boundary);
assert!(ok(&mut reopened));
assert!(
reopened
.session
.doc()
.unwrap()
.model
.iter()
.any(|e| matches!(&e.kind, EntityKind::Hatch(h) if h.pattern=="UNAPPLIED_TILE_TEST" && h.pattern_lines.len()==1))
);
}
#[test]
fn gallery_filters_by_description_and_selects_the_pattern_in_list_view() {
use egui_kittest::{Harness, kittest::Queryable};
let mut session = Session::new();
session.execute("hatch.patterns", &json!({"text":"*GALLERY_TEST, Quarry sample\n0,0,0,0,1\n"})).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(360., 420.)).build_ui_state(
|ui, selected: &mut String| {
if let Some(name) = crate::palettes::patterns::manager(ui, selected, &cadcraft_engine::pattern_choices()) {
*selected = name;
}
},
String::new(),
);
h.get_by_label("Filter").click();
h.run_steps(3);
h.get_by_role(egui::accesskit::Role::TextInput).click();
h.run_steps(2);
h.get_by_role(egui::accesskit::Role::TextInput).type_text("quarry");
h.run_steps(3);
assert!(h.query_by_label("ANSI31").is_none());
h.get_by_role(egui::accesskit::Role::ComboBox).click();
h.run_steps(3);
h.get_by_label("List").click();
h.run_steps(3);
h.get_by_label("GALLERY_TEST").click();
h.run_steps(3);
assert_eq!(h.state(), "GALLERY_TEST");
}
#[test]
fn same_name_in_two_drawings_uses_the_active_drawings_geometry() {
let name = "SHARED_DXF_NAME_TEST";
let make = |spacing| {
let (mut app, boundary) = app_with_rect();
app.run("hatch", json!({"handles":[boundary.hex()],"pattern":name,"patternText":format!("*{name}, local\n0,0,0,0,{spacing}\n")})).unwrap();
let reopened = cadcraft_io::read_dxf(cadcraft_io::write_dxf(app.session.doc().unwrap()).as_bytes()).unwrap();
app.session.open_drawing(reopened, "Reopened", None);
(app, boundary, spacing)
};
let first = make(3);
let second = make(7);
for (mut app, boundary, spacing) in [first, second] {
open_create(&mut app, false);
let st = app.hatch_dlg.as_mut().unwrap();
let choice = st.choices.iter().find(|c| c.name == name).unwrap();
assert_eq!(choice.lines[0].delta.1, f64::from(spacing));
st.fill.pattern = name.into();
st.handles.push(boundary);
assert!(ok(&mut app));
let drawing = app.session.doc().unwrap();
let hatches: Vec<_> = drawing
.model
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Hatch(h) => Some(h),
_ => None,
})
.collect();
assert_eq!(hatches.len(), 2);
assert!(hatches.iter().all(|h| h.pattern_lines[0].delta.1 == f64::from(spacing)));
}
}
#[test]
fn aligned_sparse_marks_still_get_a_visible_swatch() {
let family = cadcraft_doc::library::PatternLine { angle: 0., origin: (70., 0.), delta: (100., 1.), dashes: vec![1., -99.] };
assert!(!cadcraft_render::pattern_swatch(&[family], 1.).is_empty());
}
#[test]
fn capture_refuses_a_polyline_with_a_segment_lost_to_rounding() {
use cadcraft_doc::{Common, LwPolyline};
use cadcraft_geom::PolyVertex;
let mut app = CadApp::new(Session::new(), Services::default());
let vertices = [Vec2::new(1., 1.), Vec2::new(1.001, 1.), Vec2::new(8., 6.)].into_iter().map(PolyVertex::new).collect();
let poly = LwPolyline { vertices, closed: false, const_width: 0., elevation: 0., plinegen: false };
app.session.doc_mut().unwrap().add(&Space::Model, Common::default(), EntityKind::LwPolyline(poly)).unwrap();
assert_eq!(
capture_draft(&mut app, Vec2::ZERO, Vec2::new(10., 10.)).unwrap_err(),
crate::tl!("A segment is too small for the tile capture precision.")
);
}
#[test]
fn applying_a_just_saved_pattern_uses_its_new_spacing() {
let (mut app, boundary) = app_with_rect();
let name = "SAVED_OVER_EMBEDDED_TEST";
let old = app.run("hatch", json!({"handles":[boundary.hex()], "pattern":name, "patternText":format!("*{name}, old\n0,0,0,0,3\n")})).unwrap();
let old = Handle::parse_hex(old["handle"].as_str().unwrap()).unwrap();
open_create(&mut app, false);
let st = app.hatch_dlg.as_mut().unwrap();
st.handles.push(boundary);
st.custom = Some(CustomPattern { name: name.into(), families: vec![PatternFamily { spacing: 7., ..Default::default() }] });
save_pattern(&mut app);
assert!(app.hatch_dlg.as_ref().unwrap().custom.is_none());
assert!(ok(&mut app));
let drawing = app.session.doc().unwrap();
let hatches: Vec<_> = drawing
.model
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Hatch(h) if h.pattern == name => Some((e.handle, h.pattern_lines[0].delta.1)),
_ => None,
})
.collect();
assert_eq!(hatches.len(), 2);
assert!(hatches.contains(&(old, 3.)));
assert!(hatches.iter().any(|(handle, spacing)| *handle != old && *spacing == 7.));
}
#[test]
fn reserved_user_hatch_cannot_be_shadowed_by_a_custom_pattern() {
use cadcraft_doc::library::is_user_pattern;
let (mut app, boundary) = app_with_rect();
let reserved = "_uSeR";
let ordinary = "RESERVED_NAME_CONTROL";
let draft = CustomPattern { name: reserved.into(), families: vec![PatternFamily::default()] };
assert!(draft.encode().is_none());
assert!(app.run("hatch.capture", json!({"first":[0,0], "second":[10,10], "name":reserved})).is_err());
let source = format!("*{reserved}, collision\n0,0,0,0,13\n*{ordinary}, named\n30,0,0,0,7\n");
let registered = app.run("hatch.patterns", json!({"text":source})).unwrap();
assert_eq!(registered["added"], json!([ordinary]));
assert!(!registered["warnings"].as_array().unwrap().is_empty());
app.session.cmdline("(command \"_.hatch\" \"_u\" 45 100 \"_y\" \"_l\" \"\")").unwrap();
app.run("hatch", json!({"handles":[boundary.hex()], "pattern":ordinary})).unwrap();
let drawing = app.session.doc().unwrap();
let hatch = |name: &str| {
drawing
.model
.iter()
.find_map(|e| match &e.kind {
EntityKind::Hatch(h) if h.pattern.eq_ignore_ascii_case(name) => Some(h),
_ => None,
})
.unwrap()
};
let native = hatch(reserved);
assert_eq!(native.pattern_lines, cadcraft_doc::library::user_defined_lines(true));
assert_eq!(native.scale, 100.);
assert_eq!(hatch(ordinary).pattern_lines[0].delta.1, 7.);
cadcraft_engine::register_drawing_patterns(drawing);
assert!(!cadcraft_engine::pattern_choices_in(drawing).iter().any(|p| is_user_pattern(&p.name)));
assert!(!cadcraft_engine::pattern_choices().iter().any(|p| is_user_pattern(&p.name)));
}
+74 -7
View File
@@ -55,9 +55,13 @@ pub enum Preference {
Vietnamese,
#[serde(rename = "ta")]
Tamil,
#[serde(rename = "nl")]
Dutch,
#[serde(rename = "pt-PT")]
Portuguese,
}
impl Preference {
pub const ALL: [Self; 22] = [
pub const ALL: [Self; 24] = [
Self::Auto,
Self::English,
Self::Greek,
@@ -80,6 +84,8 @@ impl Preference {
Self::Bosnian,
Self::Vietnamese,
Self::Tamil,
Self::Dutch,
Self::Portuguese,
];
/// Every preference in the order the Interface Language dialog lists them: Auto, then English
@@ -132,6 +138,8 @@ impl Preference {
Self::Bosnian => "bs",
Self::Vietnamese => "vi",
Self::Tamil => "ta",
Self::Dutch => "nl",
Self::Portuguese => "pt-PT",
}
}
@@ -188,6 +196,8 @@ impl Preference {
"Tamil"
}
}
Self::Dutch => "Nederlands",
Self::Portuguese => "Português (Portugal)",
}
}
@@ -223,7 +233,9 @@ impl Preference {
Self::Bosnian => "bs",
Self::Vietnamese => "vi",
Self::Tamil => "ta",
Self::Auto => locales.iter().find_map(|s| locale_language(s)).unwrap_or("en"),
Self::Dutch => "nl",
Self::Portuguese => "pt-PT",
Self::Auto => locales.iter().find_map(|s| resolve_locale(s, language_is_available)).unwrap_or("en"),
}
}
}
@@ -239,7 +251,7 @@ pub struct Language {
catalog: OnceLock<Catalog<'static>>,
}
pub static LANGUAGES: [Language; 21] = [
pub static LANGUAGES: [Language; 23] = [
Language { code: "en", name: "English", source: "", plural: plural_en, plural_forms: 2, catalog: OnceLock::new() },
Language { code: "pl", name: "Polski", source: include_str!("i18n/pl.tsv"), plural: plural_pl, plural_forms: 3, catalog: OnceLock::new() },
// Greek: one for exactly 1; other for zero and all other integer counts.
@@ -304,13 +316,68 @@ pub static LANGUAGES: [Language; 21] = [
Language {
code: "ta", name: "தமிழ்", source: include_str!("i18n/ta.tsv"), plural: plural_en, plural_forms: 2, catalog: OnceLock::new()
},
// Dutch integer plurals follow the English rule: one (1), other.
// Catalog lives in storytold/craft-i18n (`locales/nl/cadcraft.tsv`); falls back to English until cutover.
Language { code: "nl", name: "Nederlands", source: "", plural: plural_en, plural_forms: 2, catalog: OnceLock::new() },
// European Portuguese integer plurals (CLDR `pt-PT`): one (1), other.
// Catalog lives in storytold/craft-i18n (`locales/pt-pt/cadcraft.tsv`); falls back to English until cutover.
Language { code: "pt-PT", name: "Português (Portugal)", source: "", plural: plural_en, plural_forms: 2, catalog: OnceLock::new() },
];
/// BCP 47 and POSIX locale tags, including `uk-UA`, `uk_UA.UTF-8` and `pt_BR.UTF-8`.
/// A catalog is chosen by the tag's primary language, so any `pt-*` tag selects `pt-BR`.
/// BCP 47 and POSIX locale tags, including `uk-UA`, `uk_UA.UTF-8`, `pt_BR.UTF-8`, `pt-PT`
/// and `pt-Latn-PT`. An exact `<language>-<region>` catalog (e.g. `pt-PT`) wins over the
/// primary-language fallback (`pt-BR`). Region matching is restricted to the language portion
/// before any BCP 47 extension or private-use singleton (`x`, `u`, `t`, …) per RFC 5646 §2.1.
pub fn locale_language(tag: &str) -> Option<&'static str> {
let primary = tag.trim().split(['-', '_', '.', '@']).next()?;
LANGUAGES.iter().find(|l| l.code.split('-').next().is_some_and(|p| p.eq_ignore_ascii_case(primary))).map(|l| l.code)
resolve_locale(tag, |_| true)
}
/// Whether `Auto` may select `language`: English itself, or a registered language whose catalog
/// is loaded in this build. Locales registered ahead of `craft-i18n` cutover (`source: ""`) stay
/// selectable explicitly while `Auto` keeps existing translated fallbacks (e.g. `nl-NL, de-DE` →
/// `de`, `pt-PT` → `pt-BR`).
fn language_is_available(language: &Language) -> bool {
language.code == "en" || !language.source.is_empty()
}
fn resolve_locale(tag: &str, eligible: impl Fn(&Language) -> bool) -> Option<&'static str> {
let base = tag.trim().split(['.', '@']).next()?;
let mut parts = base.split(['-', '_']);
let primary = parts.next()?;
if let Some(reg) = bcp47_region(parts)
&& let Some(exact) = LANGUAGES
.iter()
.filter(|l| eligible(l))
.find(|l| l.code.split_once('-').is_some_and(|(p, r)| p.eq_ignore_ascii_case(primary) && r.eq_ignore_ascii_case(reg)))
{
return Some(exact.code);
}
LANGUAGES.iter().filter(|l| eligible(l)).find(|l| l.code.split('-').next().is_some_and(|p| p.eq_ignore_ascii_case(primary))).map(|l| l.code)
}
/// Extract the BCP 47 region subtag (2 ASCII letters or 3 ASCII digits) from subtags following the
/// primary language, skipping optional extlang (3 ASCII letters, up to 3) and script (4 ASCII
/// letters) subtags, and stopping before variants or extension/private-use singletons (`len == 1`).
fn bcp47_region<'a>(subtags: impl Iterator<Item = &'a str>) -> Option<&'a str> {
let mut extlangs = 0usize;
let mut saw_script = false;
for subtag in subtags {
if subtag.len() == 1 {
return None;
}
if !saw_script && extlangs < 3 && subtag.len() == 3 && subtag.bytes().all(|b| b.is_ascii_alphabetic()) {
extlangs += 1;
continue;
}
if !saw_script && subtag.len() == 4 && subtag.bytes().all(|b| b.is_ascii_alphabetic()) {
saw_script = true;
continue;
}
let is_region = (subtag.len() == 2 && subtag.bytes().all(|b| b.is_ascii_alphabetic()))
|| (subtag.len() == 3 && subtag.bytes().all(|b| b.is_ascii_digit()));
return is_region.then_some(subtag);
}
None
}
thread_local! {
+108 -15
View File
@@ -1333,7 +1333,7 @@ menu View عرض
Save Layout as Template حفظ التخطيط كقالب
Save Reference Edits حفظ تعديلات المرجع
Save alias حفظ الاختصار
Save changes to block "{name}"? حفظ التغييرات على الكتلة "{name}"؟
Save changes to block "{name}"? هل تريد حفظ التغييرات على الكتلة "{name}"؟
Select boundaries to remove حدد الحدود المراد إزالتها
Select using two clicks only التحديد بنقرتين فقط
Selection Area Effect تأثير منطقة التحديد
@@ -1369,6 +1369,113 @@ menu View عرض
overrides built-in يتجاوز المدمج
{alias} is already defined; select it and use Edit. {alias} معرَّف مسبقاً؛ حدده واستخدم «تحرير».
{command} is an unknown command. {command} أمر غير معروف.
Find All بحث عن الكل
Find what: البحث عن:
Match case مطابقة حالة الأحرف
Replace استبدال
Replace All استبدال الكل
Replace with: استبدال بـ:
Replacement text النص البديل
Results النتائج
Searches the current space. يبحث في الفراغ الحالي.
Text to find النص المراد البحث عنه
Whole words كلمات كاملة
Nothing found لم يُعثر على شيء
Angstroms أنغستروم
Apply to Layout تطبيق على التخطيط
Architectural معماري
Arrow size حجم السهم
Astronomical Units وحدات فلكية
Backup copies are off, so the current file will be replaced. النسخ الاحتياطية متوقفة، لذا سيُستبدل الملف الحالي.
CADCraft CADCraft
Center the plot توسيط الطباعة
Centimeters سنتيمترات
Change تغيير
Clear Recent Files مسح قائمة الملفات الأخيرة
Custom مخصص
DView عرض ديناميكي
DXF 2010 and earlier keep them. Use Save As to keep them in the drawing. يحتفظ بها تنسيق DXF 2010 وما قبله. استخدم «حفظ باسم» لإبقائها في الرسم.
DXF keeps them. Use Save As to keep them in the drawing. يحتفظ بها تنسيق DXF. استخدم «حفظ باسم» لإبقائها في الرسم.
Decameters ديكامترات
Decimal عشري
Decimal Degrees درجات عشرية
Decimeters ديسيمترات
Deg/Min/Sec درجة/دقيقة/ثانية
Dim scale overall مقياس التأشير الكلي
Don't Save عدم الحفظ
Drawing Units وحدات الرسم
E ق
Engineering هندسي
Enter block names to extract أدخل أسماء الكتل المراد استخراجها
Enter geometric characteristic أدخل الخاصية الهندسية
Enter name of LISP file to load أدخل اسم ملف LISP المراد تحميله
Feet أقدام
First corner الزاوية الأولى
Fit to paper ملاءمة للورقة
Fractional كسري
Gigameters غيغامترات
Grads غراد
Hectometers هكتومترات
Inches بوصات
Insertion scale مقياس الإدراج
Kilometers كيلومترات
Landscape أفقي
Layouts التخطيطات
Light Years سنوات ضوئية
Limits حدود الرسم
Meters أمتار
Microinches ميكروبوصات
Microns ميكرونات
Miles أميال
Millimeters مليمترات
Mils مِل (جزء من ألف من البوصة)
Multiple Insert إدراج متعدد
N ش
Nanometers نانومترات
Open Recent فتح من الملفات الأخيرة
Opposite corner الزاوية المقابلة
Orientation الاتجاه
Paper size حجم الورقة
Parsecs فراسخ فلكية
Plot area منطقة الطباعة
Plot object lineweights طباعة سماكات خطوط الكائنات
Plot offset إزاحة الطباعة
Plot transparency طباعة الشفافية
Portrait عمودي
Precision الدقة
Printer/plotter الطابعة/الراسمة
Radians راديان
Raster Image Reference... مرجع صورة نقطية...
Raster Images الصور النقطية
S ج
Sample output مثال على المُخرَج
Save Anyway حفظ على أي حال
Save cancelled: {path} was not changed. أُلغي الحفظ: لم يتغير {path}.
Save changes to {name}? هل تريد حفظ التغييرات في {name}؟
Saving {name} will remove content حفظ {name} سيُزيل بعض المحتوى
Scientific علمي
Surveyor's Units وحدات المساحين
The current file doesn't look whole, so {name} stays as it is and the current file will be replaced. يبدو الملف الحالي غير سليم، لذا يبقى {name} كما هو وسيُستبدل الملف الحالي.
The current file is kept as {name} until the next save. يُحتفظ بالملف الحالي باسم {name} حتى الحفظ التالي.
This drawing هذا الرسم
This format can't keep these objects yet: {objects}. لا يستطيع هذا التنسيق الاحتفاظ بهذه الكائنات بعد: {objects}.
US Survey Feet أقدام مسحية أمريكية
US Survey Inch بوصة مسحية أمريكية
US Survey Mile ميل مسحي أمريكي
US Survey Yard ياردة مسحية أمريكية
Unitless بلا وحدات
Units الوحدات
Units to scale inserted content وحدات تحجيم المحتوى المُدرَج
W غ
Window < نافذة <
X offset (mm) إزاحة X (مم)
Y offset (mm) إزاحة Y (مم)
Yards ياردات
Your changes will be lost if you don't save them. ستضيع تغييراتك إن لم تحفظها.
contains authoring elements. Open in Block Editor? يحتوي على عناصر تحرير. هل تريد فتحه في محرر الكتل؟
{count} more types أنواع أخرى: {count}
Ctrl+Enter to apply Ctrl+Enter للتطبيق
Edit Text تحرير النص
Add a drawing file as a block library إضافة ملف رسم كمكتبة كتل
Add a folder of drawings or a drawing file to use its blocks. أضف مجلدًا يحتوي على رسومات أو ملف رسم لاستخدام كتله.
Block Libraries مكتبات الكتل
@@ -1396,20 +1503,6 @@ menu View عرض
This drawing has no blocks. لا يحتوي هذا الرسم على كتل.
This library has no drawings or blocks. لا تحتوي هذه المكتبة على رسومات أو كتل.
Only the first {n} are shown. يتم عرض أول {n} فقط.
Find All Find All
Find what: Find what:
Match case Match case
Replace Replace
Replace All Replace All
Replace with: Replace with:
Replacement text Replacement text
Results Results
Searches the current space. Searches the current space.
Text to find Text to find
Whole words Whole words
Nothing found Nothing found
Ctrl+Enter to apply Ctrl+Enter to apply
Edit Text Edit Text
The drawing changed. Close the window and open it again. تغيّر الرسم. أغلق النافذة وافتحها مرة أخرى.
# ArtCraft feature naming
Can't render this file because it contains an unexpected character in line 1336 and column 24.
+56 -6
View File
@@ -281,9 +281,43 @@ fn assert_primary_locale_aliases() {
}
fn assert_portuguese_and_spanish_aliases() {
for tag in ["pt", "pt-BR", "pt_BR.UTF-8", "PT-br", "pt-PT"] {
// Plain `pt` and tags with no region (including private-use/extension subtags like `pt-x-pt`)
// keep the existing `pt-BR` fallback per RFC 5646 §2.1.
for tag in [
"pt",
"pt-BR",
"pt_BR.UTF-8",
"PT-br",
"pt-x-pt",
"pt-Latn-x-pt",
"pt-u-ca-pt",
"pt-t-pt",
"pt-BR-x-pt",
"pt-ao1990-pt",
"pt-419",
"pt--PT",
"pt@PT",
"pt-1996-PT",
"pt-é-PT",
"pt-Latn-abc-PT",
] {
assert_eq!(locale_language(tag), Some("pt-BR"), "{tag}");
}
for tag in ["pt-PT", "pt_PT.UTF-8", "PT-pt", "pt-Latn-PT", "pt-abc-PT", "pt-PT-x-br", "pt-PT-u-ca-gregory"] {
assert_eq!(locale_language(tag), Some("pt-PT"), "{tag}");
}
assert_eq!(Preference::Auto.resolve(&["pt-x-pt".into()]), "pt-BR");
// Before `pt-PT`'s catalog is embedded, Auto keeps the existing `pt-BR` translated fallback.
assert_eq!(Preference::Auto.resolve(&["pt-PT".into()]), "pt-BR");
assert_eq!(Preference::Auto.resolve(&["pt-Latn-PT".into()]), "pt-BR");
assert_eq!(Preference::Auto.resolve(&["pt-PT".into(), "de-DE".into()]), "pt-BR");
// Before `nl`'s catalog is embedded, a Dutch-first locale list falls through to the next translated choice.
assert_eq!(Preference::Auto.resolve(&["nl-NL".into(), "de-DE".into()]), "de");
assert_eq!(Preference::Auto.resolve(&["nl-BE".into(), "fr-FR".into()]), "fr");
assert_eq!(Preference::Auto.resolve(&["nl-NL".into()]), "en");
// Registered languages whose catalogs live in storytold/craft-i18n fall back cleanly to English.
assert_eq!(tr("nl", "Open"), "Open");
assert_eq!(tr("pt-PT", "Open"), "Open");
for tag in ["es", "es-ES", "es_MX.UTF-8", "ES-ar"] {
assert_eq!(locale_language(tag), Some("es"), "{tag}");
@@ -303,6 +337,7 @@ fn assert_additional_locale_aliases() {
("el", &["el", "el-GR", "el_GR.UTF-8", "EL-cy"]),
("ka", &["ka", "ka-GE", "ka_GE.UTF-8", "KA-ge", " ka-GE "]),
("ta", &["ta", "ta-IN", "ta_IN.UTF-8", "TA-in", " ta-LK ", "ta-SG", "ta_MY.UTF-8"]),
("nl", &["nl", "nl-NL", "nl_NL.UTF-8", "NL-nl", " nl-BE ", "nl_BE.UTF-8"]),
("zh", &["zh", "zh-CN"]),
] {
for tag in tags {
@@ -313,7 +348,7 @@ fn assert_additional_locale_aliases() {
fn assert_unrecognized_locale_tags() {
// Look-alike codes, three-letter codes and endonyms pick nothing: `se` is Northern Sami.
let look_alikes = ["ua", "ukulele", "nl-NL", "", "garbage", "💙", "ptolemy", "cz", "csharp", "csomething", "italic"];
let look_alikes = ["ua", "ukulele", "fi-FI", "", "garbage", "💙", "ptolemy", "cz", "csharp", "csomething", "italic"];
let others = ["kr", "korean", "kotlin", "se", "swe", "svenska", "hun", "magyar", "tur", "türkçe", "elvish", "kat", "geo", "kab", "kartuli"];
let tamil = ["tam", "tamil", "தமிழ்"];
for tag in look_alikes.into_iter().chain(others).chain(tamil) {
@@ -322,11 +357,11 @@ fn assert_unrecognized_locale_tags() {
}
fn assert_auto_locale_precedence() {
assert_eq!(Preference::Auto.resolve(&["nl-NL".into(), "pt-BR".into()]), "pt-BR");
assert_eq!(Preference::Auto.resolve(&["fi-FI".into(), "pt-BR".into()]), "pt-BR");
assert_eq!(Preference::Auto.resolve(&["pl-PL".into(), "pt-BR".into()]), "pl");
assert_eq!(Preference::Auto.resolve(&["fr-FR".into(), "pt-BR".into()]), "fr");
assert_eq!(Preference::Auto.resolve(&["es-ES".into(), "pt-BR".into()]), "es");
let locales = vec!["nl-NL".into(), "uk-UA".into(), "en-US".into()];
let locales = vec!["fi-FI".into(), "uk-UA".into(), "en-US".into()];
assert_eq!(Preference::Auto.resolve(&locales), "uk");
assert_eq!(Preference::English.resolve(&locales), "en");
assert_eq!(Preference::Auto.resolve(&["en-US".into(), "uk-UA".into()]), "en");
@@ -348,8 +383,8 @@ fn assert_preference_resolution(preference: Preference) {
assert_eq!(Preference::parse(preference.code()), Some(preference));
// A chosen language wins over the system's; Auto takes the first system language there is.
assert_eq!(preference.resolve(&["uk-UA".into()]), preference.code());
if preference != Preference::English {
assert_eq!(Preference::Auto.resolve(&["nl-NL".into(), preference.code().into(), "en-US".into()]), preference.code());
if preference != Preference::English && LANGUAGES.iter().any(|l| l.code == preference.code() && !l.source.is_empty()) {
assert_eq!(Preference::Auto.resolve(&["fi-FI".into(), preference.code().into(), "en-US".into()]), preference.code());
}
}
@@ -822,3 +857,18 @@ fn arabic_tells_stretch_trim_and_point_from_their_neighbours() {
assert!(tr("ar", prompt).contains(verb), "{prompt}");
}
}
#[test]
fn dutch_and_european_portuguese_registration_and_plurals() {
assert_eq!(Preference::parse("nl"), Some(Preference::Dutch));
assert_eq!(Preference::parse("pt-PT"), Some(Preference::Portuguese));
assert_eq!(Preference::Dutch.native_name(), "Nederlands");
assert_eq!(Preference::Portuguese.native_name(), "Português (Portugal)");
// Verify LANGUAGES plural wiring: nl and pt-PT treat 0 as plural (1), while pt-BR treats 0 as singular (0).
let nl = LANGUAGES.iter().find(|l| l.code == "nl").expect("nl registered");
let pt_pt = LANGUAGES.iter().find(|l| l.code == "pt-PT").expect("pt-PT registered");
let pt_br = LANGUAGES.iter().find(|l| l.code == "pt-BR").expect("pt-BR registered");
assert_eq!(((nl.plural)(0), (nl.plural)(1), (nl.plural)(2)), (1, 0, 1));
assert_eq!(((pt_pt.plural)(0), (pt_pt.plural)(1), (pt_pt.plural)(2)), (1, 0, 1));
assert_eq!(((pt_br.plural)(0), (pt_br.plural)(1), (pt_br.plural)(2)), (0, 0, 1));
}
+1
View File
@@ -1448,6 +1448,7 @@
B B
Backup copy 备份副本
Block to create or edit 要创建或编辑的块
Capture hatch tile 捕获图案填充单元
Choose the command the alias starts. 选择别名要启动的命令。
Click the ruler to add a tab stop, right-click to remove one 单击标尺可添加制表位,右键单击可将其删除
Command 命令
1 # CADCraft Simplified Chinese interface catalog — original translations.
1448
1449
1450
1451
1452
1453
1454
+136 -5
View File
@@ -145,6 +145,7 @@ pub struct UiState {
pub save_version: String,
/// Drawings opened from a path, newest first (File ▸ Open Recent and the Start page).
pub recent_files: Vec<String>,
pub(crate) hatch_patterns: std::collections::BTreeMap<String, String>,
/// The folder the last APPLOAD file came from: the next pick starts there.
pub last_lisp_dir: Option<String>,
/// The folder the Command Aliases dialog last imported a `.pgp` file from.
@@ -226,6 +227,7 @@ impl Default for UiState {
save_format: SaveFormat::default(),
save_version: SaveVersion::default().year().to_string(),
recent_files: Vec::new(),
hatch_patterns: Default::default(),
last_lisp_dir: None,
last_pgp_dir: None,
}
@@ -356,6 +358,11 @@ pub struct CadApp {
pub frame_cap: Option<gpu::FrameCap>,
/// Language whose interface fonts are installed (`None` until the first frame).
fonts_language: Option<&'static str>,
/// The scripts of the names shown the fonts were installed for, and the name-font loads they
/// include (`None` until the first frame): a Korean layer name, a Thai drawing name.
fonts_names: Option<(theme::Scripts, u64)>,
/// The names last scanned for their scripts (a fingerprint), and those scripts.
font_names: Option<(u64, theme::Scripts)>,
/// Language last given to egui (and so to the AccessKit root; `None` until the first frame).
shown_language: Option<&'static str>,
/// The theme last installed into egui (`None` until the first frame).
@@ -445,6 +452,8 @@ impl CadApp {
#[cfg(not(target_arch = "wasm32"))]
frame_cap: None,
fonts_language: None,
fonts_names: None,
font_names: None,
shown_language: None,
shown_theme: None,
shown_follows_system: false,
@@ -634,7 +643,17 @@ impl CadApp {
// The bars as the interface shows them now (a `ui.set` may have just changed one), and any
// MENUBAR or TOOLBAR request applied at once.
self.sync_bars();
let r = self.session.execute(id, &params).map_err(|e| e.to_string());
let r = self.session.execute(id, &params).map_err(|error| match &error {
cadcraft_engine::EngineError::BadParams { cmd, msg } if cmd == "hatch.capture" => match msg.as_str() {
"Pick two opposite corners for the tile" => crate::tl!("Pick two opposite corners for the tile").to_owned(),
"A segment is too small for the tile capture precision." => {
crate::tl!("A segment is too small for the tile capture precision.").to_owned()
}
"No complete line segments in the selected tile." => crate::tl!("No complete line segments in the selected tile.").to_owned(),
_ => error.to_string(),
},
_ => error.to_string(),
});
self.sync_bars();
if let Ok(v) = &r
&& let Some(m) = v.get("message").and_then(Value::as_str)
@@ -758,6 +777,9 @@ impl CadApp {
if self.spacemouse.settings != spacemouse::Settings::default() {
prefs["spacemouse"] = json!(self.spacemouse.settings);
}
if !self.ui.hatch_patterns.is_empty() {
prefs["hatchPatterns"] = json!(self.ui.hatch_patterns);
}
if !self.ui.recent_files.is_empty() {
prefs["recentFiles"] = json!(self.ui.recent_files);
}
@@ -776,6 +798,19 @@ impl CadApp {
/// Restore preferences saved by [`Self::prefs_json`]; unknown or malformed values are ignored.
pub fn load_prefs(&mut self, json: &str) {
let Ok(v) = serde_json::from_str::<Value>(json) else { return };
if let Some(patterns) = v["hatchPatterns"].as_object() {
for (name, text) in patterns {
if let Some(text) = text.as_str()
&& self
.session
.execute("hatch.patterns", &json!({"text":text}))
.ok()
.is_some_and(|v| v["added"].as_array().is_some_and(|a| a.iter().any(|n| n.as_str() == Some(name))))
{
self.ui.hatch_patterns.insert(name.clone(), text.to_owned());
}
}
}
if let Some(calculator) = v.get("quickcalc") {
self.quickcalc.load_prefs(calculator);
}
@@ -1006,6 +1041,32 @@ impl CadApp {
recent.truncate(RECENT_FILES);
}
/// The scripts of the names the interface shows (drawing titles and their layers, layouts and
/// blocks) that need a font beyond the interface language's. The names are scanned again only
/// when a drawing changes (a new revision, or a new drawing), opens or closes.
fn name_scripts(&mut self) -> theme::Scripts {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
for d in &self.session.docs {
(d.uid, d.revision, std::sync::Arc::as_ptr(&d.doc) as usize, &d.title).hash(&mut h);
}
let key = h.finish();
if let Some((k, s)) = self.font_names
&& k == key
{
return s;
}
let mut s = theme::Scripts::NONE;
for d in &self.session.docs {
s |= theme::Scripts::of(&d.title);
for name in d.doc.layers.iter().map(|l| &l.name).chain(d.doc.layouts.iter().map(|l| &l.name)).chain(d.doc.blocks.keys()) {
s |= theme::Scripts::of(name);
}
}
self.font_names = Some((key, s));
s
}
/// Consume asynchronous work on every logic callback, including hidden `run_logic` ticks.
///
/// Consume-based queues and screenshot settlement run on **every** call, whichever pass
@@ -1157,10 +1218,14 @@ impl CadApp {
let ctx = ui.ctx().clone();
let ctx = &ctx;
let language = self.language();
if self.fonts_language != Some(language) {
drawing_fonts::install(ctx);
theme::install_fonts(ctx, language);
let names = (self.name_scripts(), theme::fonts_generation());
if self.fonts_language != Some(language) || self.fonts_names != Some(names) {
if self.fonts_language != Some(language) {
drawing_fonts::install(ctx);
}
theme::install_fonts_for(ctx, language, names.0);
self.fonts_language = Some(language);
self.fonts_names = Some(names);
}
// The AccessKit root carries the language the interface is actually shown in; egui copies
// it onto the root node at the end of the pass.
@@ -1335,7 +1400,9 @@ mod tests {
/// One real UI frame, with the OS reporting `system` as its appearance.
fn frame(app: &mut CadApp, ctx: &egui::Context, system: Option<egui::Theme>) {
let raw = egui::RawInput { system_theme: system, ..Default::default() };
let mut raw = egui::RawInput { system_theme: system, ..Default::default() };
app.raw_input_hook(ctx, &mut raw);
app.before_input(ctx);
let mut out = ctx.run_ui(raw, |ui| {
app.logic(ui.ctx());
app.ui(ui);
@@ -1343,6 +1410,70 @@ mod tests {
out.textures_delta.clear();
}
/// Frames until the interface fonts have every glyph of `text` (faces for names load off the
/// UI thread), at most about five seconds.
fn fonts_show(a: &mut CadApp, ctx: &egui::Context, text: &str) -> bool {
for _ in 0..500 {
frame(a, ctx, None);
if ctx.fonts_mut(|f| f.has_glyphs(&theme::body(), text)) {
return true;
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
false
}
/// A Latin-named drawing in an English interface with a Korean layer name: the scan finds
/// Hangul and a font that shows it is installed (when one is installed on this machine);
/// renaming it away drops the need. Names are scanned again only when the drawings change.
#[test]
fn a_layer_name_brings_the_font_its_script_needs() {
let mut a = app();
a.session.new_drawing(false);
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
frame(&mut a, &ctx, None);
assert_eq!(a.fonts_names.map(|f| f.0), Some(theme::Scripts::NONE), "English interface, Latin names");
let rename = |a: &mut CadApp, name: &str| {
if let Some(d) = a.session.docs.first_mut() {
let mut doc = (*d.doc).clone();
if let Some(l) = doc.layers.first_mut() {
l.name = name.into();
}
d.doc = std::sync::Arc::new(doc);
}
};
rename(&mut a, "도면 레이어");
frame(&mut a, &ctx, None);
assert_eq!(a.fonts_names.map(|f| f.0), Some(theme::Scripts::HANGUL), "the Layers palette needs Hangul");
if cadcraft_fonts::ttf::fallback_for('한').is_some() {
assert!(fonts_show(&mut a, &ctx, "도면"), "the layer name shows its characters, not boxes");
}
let scanned = a.font_names;
frame(&mut a, &ctx, None);
assert_eq!(a.font_names, scanned, "no change, no new scan");
// Installing again for a name's script (and when its face arrives) reuses the language's
// fonts read before: the UI and CJK font files aren't read on the UI thread again.
let reads = theme::LANGUAGE_FONT_READS.with(std::cell::Cell::get);
rename(&mut a, "แผนผัง");
frame(&mut a, &ctx, None);
frame(&mut a, &ctx, None);
assert_eq!(theme::LANGUAGE_FONT_READS.with(std::cell::Cell::get), reads, "the language's fonts are reused");
rename(&mut a, "도면 레이어");
frame(&mut a, &ctx, None);
rename(&mut a, "Walls");
frame(&mut a, &ctx, None);
assert_eq!(a.fonts_names.map(|f| f.0), Some(theme::Scripts::NONE));
// An edit in place through `doc_mut` keeps the drawing's pointer; the scan still sees it.
let before = a.session.state().map(|st| std::sync::Arc::as_ptr(&st.doc)).unwrap();
if let Some(l) = a.session.doc_mut().unwrap().layers.first_mut() {
l.name = "도면 레이어".into();
}
assert_eq!(a.session.state().map(|st| std::sync::Arc::as_ptr(&st.doc)).unwrap(), before, "edited in place");
frame(&mut a, &ctx, None);
assert_eq!(a.fonts_names.map(|f| f.0), Some(theme::Scripts::HANGUL), "the in-place rename is scanned");
}
/// One real UI frame whose first pass asks egui for a second layout pass, as a popup or a
/// changed layout does.
fn two_pass_frame(app: &mut CadApp, ctx: &egui::Context) {
+1 -1
View File
@@ -10,7 +10,7 @@
//! |---|---|
//! | `theme` | `"system"`, `"light"` or `"dark"` |
//! | `animations` | `"system"`, `"on"` or `"off"`: dialog and menu fades and smoothed scrolling |
//! | `interfaceLanguage` | `"auto"`, `"en"`, `"uk"`, `"pt-BR"`, `"de"`, `"es"`, `"cs"`, `"ru"`, `"fr"`, `"zh"`, `"it"`, `"ko"`, `"sv"`, `"ar"`, `"hu"`, `"tr"`, `"bs"`, `"vi"`, `"el"`, `"ka"` or `"ta"` |
//! | `interfaceLanguage` | `"auto"`, `"en"`, `"uk"`, `"pt-BR"`, `"de"`, `"es"`, `"cs"`, `"ru"`, `"fr"`, `"zh"`, `"it"`, `"ko"`, `"sv"`, `"ar"`, `"hu"`, `"tr"`, `"bs"`, `"vi"`, `"el"`, `"ka"`, `"ta"`, `"nl"` or `"pt-PT"` |
//! | `saveFormat` | `"dxf"` or `"dwg"`: the format Save As suggests for new drawings |
//! | `saveVersion` | `"2000"` … `"2018"`: the version drawings with no file yet are saved in |
//! | `SAVETIME` | minutes between automatic saves, 0–600 (0: off) |
+2 -2
View File
@@ -1349,7 +1349,7 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) {
EntityKind::Hatch(hh) => {
prop_row(ui, "Pattern", |ui| {
ui.menu_button(hh.pattern.clone(), |ui| {
if let Some(name) = patterns::menu(ui, &hh.pattern) {
if let Some(name) = patterns::menu(ui, &hh.pattern, d) {
set = Some(json!({ "handles": ids, "pattern": name }));
ui.close();
}
@@ -1599,7 +1599,7 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) {
let pattern = shared("hatch.pattern", &|k| if let EntityKind::Hatch(h) = k { Some(h.pattern.clone()) } else { None });
prop_row(ui, "Pattern", |ui| {
ui.menu_button(pattern.clone(), |ui| {
if let Some(name) = patterns::menu(ui, &pattern) {
if let Some(name) = patterns::menu(ui, &pattern, d) {
set = Some(json!({ "handles": ids, "pattern": name }));
ui.close();
}
+62 -18
View File
@@ -6,7 +6,7 @@ use std::cell::RefCell;
use std::sync::Arc;
use cadcraft_engine::geom::Vec2;
use cadcraft_engine::{Input, PatternChoice, Picker, pattern_choices};
use cadcraft_engine::{Input, PatternChoice, Picker, pattern_choices_in};
use egui::{Align2, Rect, Sense, Stroke, pos2, vec2};
use crate::CadApp;
@@ -29,8 +29,8 @@ struct Swatch {
solid: bool,
}
/// The patterns' names and line family counts, and their swatches.
type Swatches = (Vec<(String, usize)>, Arc<Vec<Swatch>>);
/// The complete definitions used to build the cached swatches.
type Swatches = (Vec<PatternChoice>, Arc<Vec<Swatch>>);
thread_local! {
static SWATCHES: RefCell<Swatches> = RefCell::new((Vec::new(), Arc::new(Vec::new())));
@@ -38,27 +38,26 @@ thread_local! {
/// The swatches of the patterns offered now, made again only when the list changes (a `.pat`
/// file loaded more patterns).
fn swatches() -> Arc<Vec<Swatch>> {
let choices = pattern_choices();
let key: Vec<(String, usize)> = choices.iter().map(|c| (c.name.clone(), c.lines.len())).collect();
fn swatches(choices: &[PatternChoice]) -> Arc<Vec<Swatch>> {
SWATCHES.with(|cell| {
let mut cache = cell.borrow_mut();
if cache.0 != key {
*cache = (key, Arc::new(choices.into_iter().map(swatch).collect()));
if cache.0 != choices {
let previews = choices.iter().map(swatch).collect();
*cache = (choices.to_vec(), Arc::new(previews));
}
cache.1.clone()
})
}
fn swatch(c: PatternChoice) -> Swatch {
fn swatch(c: &PatternChoice) -> Swatch {
let solid = c.lines.is_empty();
Swatch { runs: cadcraft_engine::render::pattern_swatch(&c.lines, 1.0), name: c.name, description: c.description, solid }
Swatch { runs: cadcraft_engine::render::pattern_swatch(&c.lines, 1.0), name: c.name.clone(), description: c.description.clone(), solid }
}
/// Draw one swatch in `r` (the square and the name under it).
fn paint(p: &egui::Painter, r: Rect, s: &Swatch, selected: bool, hovered: bool) {
let t = Tokens::get();
let square = Rect::from_min_size(r.min, vec2(CELL, CELL));
let square = Rect::from_min_size(r.min, vec2(r.width(), r.width()));
p.rect_filled(square, 3.0, t.field);
let inner = square.shrink(3.0);
if s.solid {
@@ -91,18 +90,61 @@ fn paint(p: &egui::Painter, r: Rect, s: &Swatch, selected: bool, hovered: bool)
/// The swatches whose name or description holds `filter`, `current` marked; returns the
/// pattern clicked.
pub fn grid(ui: &mut egui::Ui, current: &str, filter: &str) -> Option<String> {
pub fn grid(ui: &mut egui::Ui, current: &str, filter: &str, choices: &[PatternChoice]) -> Option<String> {
gallery(ui, current, filter, Some(CELL), false, choices)
}
pub(crate) fn manager(ui: &mut egui::Ui, current: &str, choices: &[PatternChoice]) -> Option<String> {
use crate::blocks_palette::View;
let id = ui.make_persistent_id("hatch-gallery-settings");
let (mut view, mut filtering, mut filter): (View, bool, String) = ui.data_mut(|data| data.get_temp(id)).unwrap_or_default();
ui.horizontal(|ui| {
let label = ui.label(crate::tl!("View"));
egui::ComboBox::from_id_salt("hatch-view")
.selected_text(view.label())
.show_ui(ui, |ui| {
for v in View::ALL {
ui.selectable_value(&mut view, v, v.label());
}
})
.response
.labelled_by(label.id);
ui.toggle_value(&mut filtering, crate::tl!("Filter"));
});
if filtering {
ui.add(egui::TextEdit::singleline(&mut filter).hint_text(crate::tl!("Search for pattern")));
}
let chosen = egui::ScrollArea::vertical()
.id_salt("hatch_swatches")
.max_height(220.0)
.show(ui, |ui| gallery(ui, current, if filtering { &filter } else { "" }, view.tile(), view == View::Details, choices))
.inner;
ui.data_mut(|data| data.insert_temp(id, (view, filtering, filter)));
chosen
}
fn gallery(ui: &mut egui::Ui, current: &str, filter: &str, side: Option<f32>, details: bool, choices: &[PatternChoice]) -> Option<String> {
let filter = filter.trim().to_lowercase();
let mut chosen = None;
let row_width = ui.available_width();
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing = vec2(GAP, GAP);
let shown = swatches();
let shown = swatches(choices);
for s in
shown.iter().filter(|s| filter.is_empty() || s.name.to_lowercase().contains(&filter) || s.description.to_lowercase().contains(&filter))
{
let (r, resp) = ui.allocate_exact_size(vec2(CELL, CELL + LABEL_H), Sense::click());
let Some(side) = side else {
let label = if details { format!("{} {}", s.name, s.description) } else { s.name.clone() };
if ui.add_sized([row_width, LABEL_H + GAP], egui::Button::selectable(s.name.eq_ignore_ascii_case(current), label)).clicked() {
chosen = Some(s.name.clone());
}
continue;
};
let (r, resp) = ui.allocate_exact_size(vec2(side, side + LABEL_H), Sense::click());
let selected = s.name.eq_ignore_ascii_case(current);
resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, resp.enabled(), selected, &s.name));
if ui.is_rect_visible(r) {
paint(ui.painter(), r, s, s.name.eq_ignore_ascii_case(current), resp.hovered());
paint(ui.painter(), r, s, selected, resp.hovered() || resp.has_focus());
}
let tip = if s.description.is_empty() { s.name.clone() } else { format!("{}\n{}", s.name, s.description) };
if resp.on_hover_text(tip).clicked() {
@@ -115,9 +157,9 @@ pub fn grid(ui: &mut egui::Ui, current: &str, filter: &str) -> Option<String> {
/// The Properties palette's pattern menu: the swatch grid, scrolling; returns the pattern
/// clicked.
pub fn menu(ui: &mut egui::Ui, current: &str) -> Option<String> {
pub fn menu(ui: &mut egui::Ui, current: &str, d: &cadcraft_doc::Drawing) -> Option<String> {
ui.set_width(MENU_COLUMNS * (CELL + GAP));
egui::ScrollArea::vertical().max_height(360.0).show(ui, |ui| grid(ui, current, "")).inner
egui::ScrollArea::vertical().max_height(360.0).show(ui, |ui| grid(ui, current, "", &pattern_choices_in(d))).inner
}
/// The picker window while the prompt offers one (HATCH's boundary and pattern prompts,
@@ -139,7 +181,9 @@ pub fn prompt_picker(app: &mut CadApp, ctx: &egui::Context) {
.on_hover_text(crate::tl!("Search for pattern"));
ui.add_space(4.0);
egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
chosen = grid(ui, &current, &filter);
if let Ok(d) = app.session.doc() {
chosen = grid(ui, &current, &filter, &pattern_choices_in(d));
}
});
});
ctx.data_mut(|d| d.insert_temp(filter_id, filter));
+436 -1
View File
@@ -321,7 +321,13 @@ pub fn mono() -> FontId {
/// interface adds a Hangul font only when the CJK font found doesn't cover Hangul
/// ([`korean_font`]).
pub fn install_fonts(ctx: &egui::Context, language: &str) {
crate::mtext_editor::install_diameter_glyph(ctx);
install_fonts_for(ctx, language, Scripts::NONE);
}
/// The fonts [`install_fonts`] installs for `language`.
fn language_fonts(language: &str) -> egui::FontDefinitions {
#[cfg(test)]
LANGUAGE_FONT_READS.with(|n| n.set(n.get() + 1));
let mut fonts = egui::FontDefinitions::default();
let mut added: Vec<(String, std::sync::Arc<egui::FontData>)> = Vec::new();
#[cfg(not(target_arch = "wasm32"))]
@@ -406,9 +412,322 @@ pub fn install_fonts(ctx: &egui::Context, language: &str) {
{
f.push("Hack".into());
}
fonts
}
/// Scripts names the interface shows (drawings, layers, layouts, blocks) may need a font for
/// beyond the ones [`install_fonts`] loads for every language (a set). CJK isn't one: every
/// interface loads CJK faces already (#513).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Scripts(u8);
impl Scripts {
pub const NONE: Scripts = Scripts(0);
pub const HANGUL: Scripts = Scripts(1);
pub const THAI: Scripts = Scripts(1 << 1);
pub const DEVANAGARI: Scripts = Scripts(1 << 2);
pub const ARABIC: Scripts = Scripts(1 << 3);
pub const HEBREW: Scripts = Scripts(1 << 4);
/// Each script with a character a font must have to show it.
#[cfg(not(target_arch = "wasm32"))]
const SAMPLES: [(Scripts, char); 5] =
[(Scripts::HANGUL, '한'), (Scripts::THAI, 'ก'), (Scripts::DEVANAGARI, 'क'), (Scripts::ARABIC, 'ع'), (Scripts::HEBREW, 'א')];
/// The script of `c`, if it is one of these.
pub fn of_char(c: char) -> Scripts {
match u32::from(c) {
0x0590..=0x05FF | 0xFB1D..=0xFB4F => Scripts::HEBREW,
// The Arabic blocks only: not the intervening Syriac, Thaana, NKo, Samaritan or Mandaic blocks, and
// not U+FEFF (the byte order mark, which can lead any name).
0x0600..=0x06FF | 0x0750..=0x077F | 0x08A0..=0x08FF | 0xFB50..=0xFDFF | 0xFE70..=0xFEFE => Scripts::ARABIC,
0x0900..=0x097F | 0xA8E0..=0xA8FF => Scripts::DEVANAGARI,
0x0E00..=0x0E7F => Scripts::THAI,
0x1100..=0x11FF | 0x3130..=0x318F | 0xA960..=0xA97F | 0xAC00..=0xD7FF => Scripts::HANGUL,
_ => Scripts::NONE,
}
}
/// The scripts of `text`'s characters.
pub fn of(text: &str) -> Scripts {
text.chars().fold(Scripts::NONE, |s, c| s | Scripts::of_char(c))
}
pub fn contains(self, other: Scripts) -> bool {
self.0 & other.0 == other.0
}
pub fn is_empty(self) -> bool {
self.0 == 0
}
#[cfg(not(target_arch = "wasm32"))]
fn without(self, other: Scripts) -> Scripts {
Scripts(self.0 & !other.0)
}
}
impl std::ops::BitOr for Scripts {
type Output = Scripts;
fn bitor(self, rhs: Scripts) -> Scripts {
Scripts(self.0 | rhs.0)
}
}
impl std::ops::BitOrAssign for Scripts {
fn bitor_assign(&mut self, rhs: Scripts) {
self.0 |= rhs.0;
}
}
/// Faces read for names' scripts. They stay for the process, so showing a script again never
/// re-reads a file, and egui shares these `Arc`s on every install instead of copying the bytes.
#[cfg(not(target_arch = "wasm32"))]
#[derive(Default)]
struct NameFonts {
faces: Vec<std::sync::Arc<egui::FontData>>,
/// The interface font `resolved` was worked out against: whether the UI font has a script
/// depends on it, so a new one (another interface language) starts the answers over.
primary: Option<std::sync::Arc<egui::FontData>>,
/// Scripts looked for, with the face that shows them (`None`: the UI font has them).
resolved: Vec<(Scripts, Option<usize>)>,
/// Scripts no installed font showed, with the font table's [`cadcraft_fonts::ttf::generation`]
/// when that was found out. They are looked for again once the table changes (the user changed
/// the font folders), not on a timer.
unfound: Vec<(Scripts, u64)>,
/// Scripts being looked for off the UI thread.
loading: Scripts,
}
#[cfg(not(target_arch = "wasm32"))]
fn same_primary(a: &Option<std::sync::Arc<egui::FontData>>, b: &Option<std::sync::Arc<egui::FontData>>) -> bool {
match (a, b) {
(Some(a), Some(b)) => std::sync::Arc::ptr_eq(a, b),
(None, None) => true,
_ => false,
}
}
#[cfg(not(target_arch = "wasm32"))]
impl NameFonts {
/// Forget the misses found out against an older font table, so they are searched again.
fn drop_stale_unfound(&mut self, generation: u64) {
self.unfound.retain(|(_, g)| *g == generation);
}
/// Forget what was worked out against another interface font.
fn use_primary(&mut self, primary: &Option<std::sync::Arc<egui::FontData>>) {
if !same_primary(&self.primary, primary) {
self.primary = primary.clone();
self.resolved.clear();
self.unfound.clear();
self.faces.clear();
}
}
/// Return cached faces and reserve pending lookups before the cache is unlocked.
fn plan_lookup(
&mut self,
needed: Scripts,
primary: &Option<std::sync::Arc<egui::FontData>>,
generation: u64,
) -> (Vec<(String, std::sync::Arc<egui::FontData>)>, Scripts) {
self.use_primary(primary);
self.drop_stale_unfound(generation);
let (mut shown, mut missing) = (Vec::new(), Scripts::NONE);
for (s, _) in Scripts::SAMPLES {
if !needed.contains(s) {
continue;
}
match self.resolved.iter().find(|(k, _)| *k == s) {
Some((_, Some(i))) if !shown.contains(i) => shown.push(*i),
Some(_) => {}
None if self.unfound.iter().any(|(k, _)| *k == s) => {}
None => missing |= s,
}
}
let out = shown.into_iter().filter_map(|i| Some((format!("names-fallback-{i}"), self.faces.get(i)?.clone()))).collect();
let missing = missing.without(self.loading);
self.loading |= missing;
(out, missing)
}
}
/// Clears a search's scripts from `loading` when it ends, also when the loader panics, so they are
/// looked for again instead of staying "loading" for good.
#[cfg(not(target_arch = "wasm32"))]
struct LoadingGuard(Scripts, Option<egui::Context>);
#[cfg(not(target_arch = "wasm32"))]
impl Drop for LoadingGuard {
fn drop(&mut self) {
let mut c = name_fonts();
c.loading = c.loading.without(self.0);
drop(c);
NAME_FONTS_LOADED.fetch_add(1, std::sync::atomic::Ordering::Release);
if let Some(ctx) = &self.1 {
ctx.request_repaint();
}
}
}
#[cfg(not(target_arch = "wasm32"))]
fn name_fonts() -> std::sync::MutexGuard<'static, NameFonts> {
static CACHE: std::sync::OnceLock<std::sync::Mutex<NameFonts>> = std::sync::OnceLock::new();
CACHE.get_or_init(Default::default).lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
/// Bumped each time faces for names finish loading off the UI thread, so the caller installs the
/// fonts again to show them.
static NAME_FONTS_LOADED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
/// Changes when faces for names' scripts finished loading since they were asked for.
pub fn fonts_generation() -> u64 {
// The font table's change count is part of it: a changed table makes the caller look again
// for scripts no font showed.
NAME_FONTS_LOADED.load(std::sync::atomic::Ordering::Acquire).wrapping_add(cadcraft_fonts::ttf::generation())
}
/// [`install_fonts`], then a face for each of `names`' scripts the interface language's fonts
/// don't cover (a Korean layer name in an English interface; a Thai, Devanagari, Arabic or Hebrew
/// drawing name), found the way drawing text finds one ([`cadcraft_fonts::ttf::fallback_for`]).
/// Faces not read yet are looked for off the UI thread; [`fonts_generation`] changes when they
/// are ready, and installing again shows them.
pub fn install_fonts_for(ctx: &egui::Context, language: &str, names: Scripts) {
crate::mtext_editor::install_diameter_glyph(ctx);
#[cfg_attr(target_arch = "wasm32", allow(unused_mut))]
let mut fonts = cached_language_fonts(language);
#[cfg(not(target_arch = "wasm32"))]
{
let primary = fonts.font_data.get("system-ui").cloned();
for (name, data) in name_faces(ctx, language, names, primary) {
fonts.font_data.insert(name.clone(), data);
for family in [FontFamily::Proportional, FontFamily::Monospace] {
if let Some(f) = fonts.families.get_mut(&family) {
f.push(name.clone());
}
}
}
}
#[cfg(target_arch = "wasm32")]
let _ = names;
craft_ui::fonts::load(ctx, fonts);
}
/// [`language_fonts`] for `language`, read once: installing again for another name's script or
/// when faces finish loading reuses them (a clone shares their `Arc`s) instead of reading the UI
/// and CJK font files on the UI thread again. Only the last language is kept, so trying several
/// interface languages doesn't keep a copy of the large font files for each. Fonts are installed
/// on the UI thread, so the entry is that thread's.
fn cached_language_fonts(language: &str) -> egui::FontDefinitions {
thread_local! {
static READ: std::cell::RefCell<Option<(String, egui::FontDefinitions)>> = const { std::cell::RefCell::new(None) };
}
READ.with_borrow_mut(|read| match read {
Some((l, fonts)) if l == language => fonts.clone(),
_ => {
let fonts = language_fonts(language);
*read = Some((language.to_string(), fonts.clone()));
fonts
}
})
}
#[cfg(test)]
thread_local! {
/// How many times [`language_fonts`] read the fonts on this thread (a test checks that a
/// name's script reuses them).
pub(crate) static LANGUAGE_FONT_READS: Cell<usize> = const { Cell::new(0) };
}
/// The faces for `names` already read, as (font name, data); scripts not looked for yet start
/// loading off the UI thread.
#[cfg(not(target_arch = "wasm32"))]
fn name_faces(
ctx: &egui::Context,
language: &str,
names: Scripts,
primary: Option<std::sync::Arc<egui::FontData>>,
) -> Vec<(String, std::sync::Arc<egui::FontData>)> {
let mut needed = names;
// The Korean interface's own fonts have Hangul. Whether the CJK fonts of the other interfaces
// do reads the whole collection, so the loader thread finds that out.
if language == "ko" {
needed = needed.without(Scripts::HANGUL);
}
if language == "ar" {
needed = needed.without(Scripts::ARABIC);
}
let mut c = name_fonts();
let (out, missing) = c.plan_lookup(needed, &primary, cadcraft_fonts::ttf::generation());
drop(c);
if !missing.is_empty() {
let worker_ctx = ctx.clone();
let spawned = std::thread::Builder::new().name("ui-fonts".into()).spawn(move || {
let _loading = LoadingGuard(missing, Some(worker_ctx));
load_name_faces(missing, primary);
});
if let Err(e) = spawned {
log::warn!("interface fonts for other scripts not loaded: {e}");
let mut c = name_fonts();
c.loading = c.loading.without(missing);
drop(c);
NAME_FONTS_LOADED.fetch_add(1, std::sync::atomic::Ordering::Release);
ctx.request_repaint_after(std::time::Duration::from_secs(1));
}
}
out
}
/// Look for faces for `missing` (off the UI thread) and record them in the cache. `primary` is the
/// interface font the search is for; if the interface changed meanwhile the answers are dropped.
#[cfg(not(target_arch = "wasm32"))]
fn load_name_faces(missing: Scripts, primary: Option<std::sync::Arc<egui::FontData>>) {
use cadcraft_fonts::ttf::{Face, fallback_for};
let generation = cadcraft_fonts::ttf::generation();
let face_of_primary = primary.as_deref().and_then(|d| Face::new(std::sync::Arc::new(d.bytes().to_vec()), d.index));
// For each script: `Ok(None)` the UI font has it, `Ok(Some)` a face that does, `Err` none does.
let mut found: Vec<(Scripts, Result<Option<Face>, ()>)> = Vec::new();
for (s, sample) in Scripts::SAMPLES {
if !missing.contains(s) {
continue;
}
let face = if face_of_primary.as_ref().is_some_and(|p| p.has_glyph(sample)) || (s == Scripts::HANGUL && cjk_covers_hangul()) {
Ok(None)
} else if let Some(f) = found.iter().filter_map(|(_, f)| f.as_ref().ok()?.as_ref()).find(|f| f.has_glyph(sample)) {
Ok(Some(f.clone()))
} else {
fallback_for(sample).map(Some).ok_or(())
};
found.push((s, face));
}
let mut c = name_fonts();
if !same_primary(&c.primary, &primary) {
return;
}
let mut ids: Vec<(Face, usize)> = Vec::new();
for (s, face) in found {
match face {
Err(()) => c.unfound.push((s, generation)),
Ok(None) => c.resolved.push((s, None)),
Ok(Some(f)) => {
let i = match ids.iter().find(|(g, _)| *g == f) {
Some((_, i)) => *i,
None => {
// The bytes are shared with the font table, not copied (a CJK collection is
// tens of megabytes).
let (bytes, index) = f.data();
c.faces.push(std::sync::Arc::new(egui::FontData::from_blob(bytes.clone(), index)));
let i = c.faces.len() - 1;
ids.push((f, i));
i
}
};
c.resolved.push((s, Some(i)));
}
}
}
}
/// The system interface fonts [`install_fonts`] looks for, in order; it loads the first installed
/// one ahead of egui's bundled faces.
#[cfg(not(target_arch = "wasm32"))]
@@ -935,6 +1254,8 @@ pub fn apply(ctx: &egui::Context, theme: Theme, follow_system: bool) {
#[cfg(test)]
mod tests {
use super::Scripts;
/// An empty font file found first doesn't hide a readable one after it: the CJK, Arabic and
/// Japanese fonts are kept only when [`super::read_capped`] can take them.
#[cfg(not(target_arch = "wasm32"))]
@@ -966,6 +1287,22 @@ mod tests {
assert_eq!(super::ui_font_choice(installed(), true, |_| false), None);
}
/// Per-script installation keeps the Vietnamese primary face and cached language choice.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn vietnamese_primary_survives_installing_name_scripts() {
let Some(_) = super::vietnamese_font() else { return };
let ctx = egui::Context::default();
super::install_fonts_for(&ctx, "vi", super::Scripts::THAI);
let fonts = super::cached_language_fonts("vi");
let data = fonts.font_data.get("system-ui").expect("Vietnamese primary");
let face = cadcraft_fonts::ttf::Face::new(std::sync::Arc::new(data.font.as_ref().as_ref().to_vec()), data.index).expect("valid face");
assert!(super::covers_vietnamese(&face));
assert_eq!(fonts.families[&egui::FontFamily::Proportional].first().map(String::as_str), Some("system-ui"));
// A second installation must still choose the same language's primary face.
super::install_fonts_for(&ctx, "vi", super::Scripts::NONE);
assert!(std::sync::Arc::ptr_eq(data, &super::cached_language_fonts("vi").font_data["system-ui"]));
}
use cadcraft_fonts::CraftFont;
/// A face shaped like `build.rs` writes them, with no font file (as in `cadcraft-fonts`).
@@ -977,6 +1314,104 @@ mod tests {
faces.iter().map(|f| f.family).collect()
}
/// Names' scripts: each script the interface may need a face for, once per name, and none
/// for Latin or CJK text (every interface loads CJK faces already).
#[test]
fn scripts_of_names() {
assert_eq!(Scripts::of("Floor plan 2"), Scripts::NONE);
assert_eq!(Scripts::of("图纸A図面"), Scripts::NONE, "CJK is loaded for every language");
assert_eq!(Scripts::of("도면"), Scripts::HANGUL);
assert_eq!(Scripts::of("แผนผัง"), Scripts::THAI);
assert_eq!(Scripts::of("नक्शा"), Scripts::DEVANAGARI);
assert_eq!(Scripts::of("مخطط"), Scripts::ARABIC);
assert_eq!(Scripts::of("תוכנית"), Scripts::HEBREW);
let mixed = Scripts::of("Plan 도면 תוכנית");
assert!(mixed.contains(Scripts::HANGUL) && mixed.contains(Scripts::HEBREW) && !mixed.contains(Scripts::THAI));
assert!(Scripts::of("").is_empty());
}
/// A byte order mark can lead any name; it is not Arabic (review on #768).
#[test]
fn a_bom_in_a_layer_name_is_not_arabic() {
assert_eq!(Scripts::of("\u{FEFF}Layer1"), Scripts::NONE);
assert_eq!(Scripts::of("\u{FEFF}\u{0639}"), Scripts::ARABIC);
assert_eq!(Scripts::of_char('\u{FE70}'), Scripts::ARABIC);
assert_eq!(Scripts::of_char('\u{FEFE}'), Scripts::ARABIC);
}
/// Syriac, Thaana and NKo sit between the Arabic blocks; they need their own fonts (review on
/// #768).
#[test]
fn syriac_is_not_arabic() {
for c in ['\u{0710}', '\u{0780}', '\u{07C0}', '\u{0840}', '\u{0860}'] {
assert_eq!(Scripts::of_char(c), Scripts::NONE, "{c:?}");
}
for c in ['\u{0600}', '\u{06FF}', '\u{0750}', '\u{077F}', '\u{08A0}', '\u{08FF}', '\u{FB50}', '\u{FDFF}'] {
assert_eq!(Scripts::of_char(c), Scripts::ARABIC, "{c:?}");
}
}
/// Whether the interface font has a script depends on which font it is: answers worked out for
/// one are dropped when another takes over, not reused (review on #768).
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn name_font_cache_is_cleared_when_the_primary_face_changes() {
let a = Some(std::sync::Arc::new(egui::FontData::from_static(b"a")));
let b = Some(std::sync::Arc::new(egui::FontData::from_static(b"b")));
let mut c = super::NameFonts::default();
c.use_primary(&a);
c.resolved.push((Scripts::THAI, None));
c.unfound.push((Scripts::HEBREW, 0));
c.use_primary(&a);
assert_eq!(c.resolved.len(), 1, "the same primary keeps its answers");
c.use_primary(&b);
assert!(c.resolved.is_empty() && c.unfound.is_empty() && c.faces.is_empty(), "another primary starts over");
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn an_unfound_font_is_retried_after_the_font_table_changes() {
let mut c = super::NameFonts::default();
c.unfound.push((Scripts::THAI, 7));
c.unfound.push((Scripts::HEBREW, 6));
c.drop_stale_unfound(7);
assert_eq!(c.unfound, vec![(Scripts::THAI, 7)], "a miss from the current table stays, an older one is searched again");
}
/// No timer and no rescan: a miss is not searched again while the font table is as it was.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn an_unfound_font_is_not_retried_while_the_font_table_is_unchanged() {
let primary = Some(std::sync::Arc::new(egui::FontData::from_static(b"unfound-test-primary")));
let mut cache = super::NameFonts::default();
cache.use_primary(&primary);
cache.unfound.push((Scripts::THAI, 7));
for _ in 0..2 {
let (faces, to_load) = cache.plan_lookup(Scripts::THAI, &primary, 7);
assert!(faces.is_empty());
assert!(to_load.is_empty(), "no search was started");
}
let (_, to_load) = cache.plan_lookup(Scripts::THAI, &primary, 8);
assert_eq!(to_load, Scripts::THAI, "a new font table starts a search");
}
/// A loader that panics must not leave its scripts "loading" for good (review on #768).
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_dropped_font_loader_clears_loading() {
// An unused mask bit cannot collide with another test's real font request.
let pending = Scripts(1 << 7);
super::name_fonts().loading |= pending;
let r = std::panic::catch_unwind(|| {
let _loading = super::LoadingGuard(pending, None);
panic!("the loader died");
});
assert!(r.is_err());
assert!(!super::name_fonts().loading.contains(pending));
}
#[test]
fn korean_font_rejects_invalid_or_glyphless_files() {
for bytes in [vec![], vec![0xff; 32], vec![0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] {
+2
View File
@@ -50,6 +50,7 @@ mod shared_controls;
mod shortcut_menus;
mod shortcuts_checked;
mod slow_clicks;
mod snap_tab_cycling;
mod space_at_options;
mod status_bar_toggles;
mod style_dialogs;
@@ -59,6 +60,7 @@ mod text_edit_in_place;
mod toolsets_gear;
mod toolsets_parametric;
mod typed_open;
mod typed_window_rubber_band;
mod viewport_double_click_selection;
mod workspace_focus;
mod zoomed_far_in;
+136
View File
@@ -0,0 +1,136 @@
//! Tab at a point prompt steps through every object snap under the aperture (each endpoint of
//! each object nearby), not just the closest snap of each running mode, and comes back round.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{Common, Drawing, EntityKind, Line, Space};
use cadcraft_engine::snap::mode;
use cadcraft_geom::Vec2;
use cadcraft_ui_egui::{CadApp, Services};
use egui::{Event, Modifiers, PointerButton, Pos2, vec2};
use egui_kittest::Harness;
use serde_json::json;
#[test]
fn tab_cycles_through_every_endpoint_under_the_aperture() {
let mut s = Session::new();
// Three line ends close together (within the aperture of the cursor between them).
for (a, b) in [([0.0, 0.0], [10.0, 0.0]), ([0.06, 0.05], [0.06, 10.0]), ([0.03, -0.06], [-10.0, -10.0])] {
s.execute("line", &json!({ "points": [a, b] })).unwrap();
}
s.execute("setvar", &json!({ "name": "OSMODE", "value": 1 })).unwrap();
s.execute("view.set", &json!({ "center": [0, 0], "height": 20 })).unwrap();
let mut app = CadApp::new(s, Services::default());
app.canvas.zoom_pending = false;
let mut h = Harness::builder().with_context_setup(cadcraft_ui_egui::framework::install_headless).with_size(vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut CadApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(3);
h.state_mut().session.start("line").unwrap();
h.run_steps(2);
let xf = h.state().canvas.xf.unwrap();
let at = xf.to_screen(Vec2::new(0.03, 0.0));
h.event(Event::PointerMoved(at));
h.run_steps(2);
let mut seen: Vec<Vec2> = Vec::new();
for i in 0..4 {
let p = h.state().canvas.snap.map(|s| s.point).unwrap();
if i < 3 {
assert!(!seen.iter().any(|q| q.near(p, 1e-9)), "Tab {i} repeats {p:?} ({seen:?})");
} else {
assert!(seen.first().is_some_and(|q| q.near(p, 1e-9)), "the fourth Tab comes back round");
}
seen.push(p);
h.key_press(egui::Key::Tab);
h.run_steps(2);
}
for want in [Vec2::new(0.0, 0.0), Vec2::new(0.06, 0.05), Vec2::new(0.03, -0.06)] {
assert!(seen.iter().any(|q| q.near(want, 1e-9)), "{want:?} in {seen:?}");
}
}
/// Three endpoints near 10,0: 10,0 (the nearest to the cursor), 10.03,0 and 9.95,0. Endpoint is
/// the only running snap, so every candidate is an endpoint.
fn three_ends() -> Harness<'static, CadApp> {
let mut d = Drawing::new_imperial();
for (a, b) in [((0.0, 0.0), (10.0, 0.0)), ((10.03, 0.0), (20.0, 0.0)), ((9.95, 0.0), (9.95, -5.0))] {
let line = Line { a: Vec2::new(a.0, a.1).to3(0.0), b: Vec2::new(b.0, b.1).to3(0.0) };
d.add(&Space::Model, Common::default(), EntityKind::Line(line)).unwrap();
}
let mut session = Session::empty();
session.open_drawing(d, "Tab snap cycling", None);
session.execute("view.set", &json!({"center":[10,0],"height":8})).unwrap();
session.settings.osmode = mode::END;
session.settings.snapmode = false;
session.settings.orthomode = false;
let mut app = CadApp::new(session, Services::default());
app.canvas.zoom_pending = false;
let mut h = Harness::builder().with_context_setup(cadcraft_ui_egui::framework::install_headless).with_size(vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut CadApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(5);
h.state_mut().start("line");
h.run_steps(2);
assert_eq!(h.state().session.running.as_ref().unwrap().id, "line");
let ap = h.state().session.settings.aperture / h.state().canvas.xf.unwrap().scale;
assert!(ap > 0.07, "all three endpoints lie in the aperture ({ap})");
h
}
const CURSOR: Vec2 = Vec2::new(10.01, 0.0);
fn hover(h: &mut Harness<'_, CadApp>, p: Vec2) -> Pos2 {
let pos = h.state().canvas.xf.unwrap().to_screen(p);
h.event(Event::PointerMoved(pos));
h.run_steps(3);
pos
}
/// Tab, as the command line receives it (`cmdline::capture_tab`).
fn tab(h: &mut Harness<'_, CadApp>) {
h.key_press(egui::Key::Tab);
h.run_steps(3);
}
fn snapped(h: &Harness<'_, CadApp>) -> Vec2 {
let hit = h.state().canvas.snap.expect("a snap marker");
assert_eq!(hit.mode, mode::END);
hit.point
}
fn assert_at(got: Vec2, x: f64) {
assert!(got.near(Vec2::new(x, 0.0), 1e-9), "{got:?}, expected {x},0");
}
#[test]
fn moving_the_cursor_away_starts_the_cycle_over() {
let mut h = three_ends();
hover(&mut h, CURSOR);
tab(&mut h);
assert_at(snapped(&h), 10.03);
hover(&mut h, Vec2::new(10.0, 2.0));
assert!(h.state().canvas.snap.is_none());
hover(&mut h, CURSOR);
assert_at(snapped(&h), 10.0);
}
#[test]
fn a_click_places_the_candidate_tab_chose() {
let mut h = three_ends();
let pos = hover(&mut h, CURSOR);
tab(&mut h);
assert_at(snapped(&h), 10.03);
for pressed in [true, false] {
h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
h.run_steps(2);
}
let base = h.state().session.current_prompt().and_then(|p| p.base).expect("LINE asks for the next point");
assert_at(base, 10.03);
}
@@ -0,0 +1,270 @@
//! A `W`, `C` or `BOX` typed at "Select objects" draws its rectangle from the first corner to the
//! cursor, in the look of the implied window a click on empty space opens (#3667).
use cadcraft_engine::Session;
use cadcraft_engine::doc::{Drawing, Handle, Space};
use cadcraft_engine::geom::Vec2;
use cadcraft_ui_egui::{CadApp, Services};
use egui::{Color32, Event, Modifiers, PointerButton, Pos2, Rect, Shape, vec2};
use egui_kittest::Harness;
use serde_json::json;
/// The first corner of every rectangle in these tests.
const FIRST: Vec2 = Vec2::new(70.0, 20.0);
/// A cursor position up and to the right of [`FIRST`]: the rectangle holds the vertical line.
const RIGHT: Vec2 = Vec2::new(90.0, 80.0);
/// A cursor position up and to the left of [`FIRST`]: the rectangle holds the horizontal line.
const LEFT: Vec2 = Vec2::new(10.0, 80.0);
/// The upper end of the vertical line: where the Endpoint object snap holds the cursor.
const END: Vec2 = Vec2::new(80.0, 70.0);
/// What is painted of a selection rectangle between two screen corners.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
struct Band {
/// The colour of the area fill over the whole rectangle.
fill: Option<Color32>,
/// A continuous outline around the rectangle (the window look).
solid: bool,
/// Short dashes along the rectangle's edges (the crossing look).
dashed: bool,
}
/// A harness at 60 frames a second with MOVE at "Select objects" and two lines to select: a
/// horizontal one from (20, 50) to (40, 50) and a vertical one at x = 80. Returns the lines'
/// handles with it, in that order.
fn harness() -> (Harness<'static, CadApp>, Vec<Handle>) {
harness_with(0, None)
}
/// [`harness`] with the running object snaps `osmode` and, after the two lines, one more from
/// `extra[0]` to `extra[1]`, whose handle comes third.
fn harness_with(osmode: u32, extra: Option<[Vec2; 2]>) -> (Harness<'static, CadApp>, Vec<Handle>) {
let mut session = Session::empty();
session.open_drawing(Drawing::new_imperial(), "Typed window", None);
session.execute("view.set", &json!({"center":[50,50],"height":100})).unwrap();
session.settings.osmode = osmode;
session.execute("line", &json!({"points": [[20, 50], [40, 50]]})).unwrap();
session.execute("line", &json!({"points": [[80, 30], [80, 70]]})).unwrap();
if let Some([a, b]) = extra {
session.execute("line", &json!({"points": [[a.x, a.y], [b.x, b.y]]})).unwrap();
}
let mut app = CadApp::new(session, Services::default());
app.canvas.zoom_pending = false;
let mut h = Harness::builder()
.with_context_setup(cadcraft_ui_egui::framework::install_headless)
.with_size(vec2(1600.0, 1000.0))
.with_step_dt(1.0 / 60.0)
.build_ui_state(
|ui, app: &mut CadApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(5);
let ids = h.state().session.state().unwrap().doc.space(&Space::Model).unwrap().iter().map(|e| e.handle).collect();
h.state_mut().start("move");
h.run_steps(2);
(h, ids)
}
/// Where the drawing point `p` is on screen.
fn screen(h: &Harness<'_, CadApp>, p: Vec2) -> Pos2 {
h.state().canvas.xf.unwrap().to_screen(p)
}
/// Move the pointer to the drawing point `p` and draw the frames that show it there.
fn hover(h: &mut Harness<'_, CadApp>, p: Vec2) {
let pos = screen(h, p);
h.event(Event::PointerMoved(pos));
h.run_steps(2);
}
/// Click at the drawing point `p` with the pointer at rest, then wait out the double-click
/// interval.
fn click(h: &mut Harness<'_, CadApp>, p: Vec2) {
let pos = screen(h, p);
h.event(Event::PointerMoved(pos));
for pressed in [true, false] {
h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
h.run_steps(1);
}
h.run_steps(30);
}
/// Type `text` on the command line and press Enter.
fn typed(h: &mut Harness<'_, CadApp>, text: &str) {
assert_eq!(h.state_mut().cmdline(text), None, "`{text}` is accepted");
h.run_steps(2);
}
/// Whether `p` lies on an edge of the screen rectangle between the corners `a` and `b`.
fn on_edge(p: Pos2, a: Pos2, b: Pos2) -> bool {
let near = |u: f32, v: f32| (u - v).abs() < 0.5;
Rect::from_two_pos(a, b).expand(0.5).contains(p) && (near(p.x, a.x) || near(p.x, b.x) || near(p.y, a.y) || near(p.y, b.y))
}
/// Whether `p` is a corner of the screen rectangle between the corners `a` and `b`.
fn is_corner(p: Pos2, a: Pos2, b: Pos2) -> bool {
let near = |u: f32, v: f32| (u - v).abs() < 0.5;
(near(p.x, a.x) || near(p.x, b.x)) && (near(p.y, a.y) || near(p.y, b.y))
}
/// Add what `shape` paints of the rectangle between `a` and `b` to `band`, counting its dashes
/// (segments no longer than a dash, so the crosshair's arms are not taken for one) in `dashes`.
fn collect(shape: &Shape, a: Pos2, b: Pos2, band: &mut Band, dashes: &mut usize) {
match shape {
Shape::Path(path) if path.points.len() >= 4 && path.points.iter().all(|p| is_corner(*p, a, b)) => {
if path.closed && path.fill != Color32::TRANSPARENT {
band.fill = Some(path.fill);
}
if !path.closed && path.points.len() == 5 {
band.solid = true;
}
}
Shape::LineSegment { points: [p, q], .. } if on_edge(*p, a, b) && on_edge(*q, a, b) && p.distance(*q) <= 6.0 => *dashes += 1,
Shape::Vec(shapes) => shapes.iter().for_each(|s| collect(s, a, b, band, dashes)),
_ => {}
}
}
/// What the last frame painted of a selection rectangle from the drawing point `first` to the
/// drawing point `cursor`.
fn band(h: &Harness<'_, CadApp>, first: Vec2, cursor: Vec2) -> Band {
let (a, b) = (screen(h, first), screen(h, cursor));
let (mut band, mut dashes) = (Band::default(), 0);
for clipped in &h.output().shapes {
collect(&clipped.shape, a, b, &mut band, &mut dashes);
}
band.dashed = dashes > 8;
band
}
/// The look of the implied window MOVE's "Select objects" opens at [`FIRST`]: with the cursor at
/// [`RIGHT`] (a window) and at [`LEFT`] (a crossing). The window is cancelled again.
fn implied_looks(h: &mut Harness<'_, CadApp>) -> (Band, Band) {
click(h, FIRST);
assert!(h.state().session.pending_window.is_some(), "a click on empty space opens a window");
hover(h, RIGHT);
let window = band(h, FIRST, RIGHT);
hover(h, LEFT);
let crossing = band(h, FIRST, LEFT);
h.state_mut().session.pending_window = None;
h.run_steps(2);
assert_eq!(band(h, FIRST, LEFT), Band::default(), "nothing is left of the cancelled window");
assert!(window.fill.is_some() && window.solid && !window.dashed, "{window:?}");
assert!(crossing.fill.is_some() && !crossing.solid && crossing.dashed, "{crossing:?}");
assert_ne!(window.fill, crossing.fill);
(window, crossing)
}
/// Typed `W`: no rectangle before the first corner; after it the rectangle follows the cursor in
/// the window look, to the left as well as to the right, and the second corner selects.
#[test]
fn a_typed_window_draws_its_rectangle_after_the_first_corner() {
let (mut h, ids) = harness();
let (window, _) = implied_looks(&mut h);
typed(&mut h, "W");
assert_eq!(h.state().session.current_prompt().unwrap().message, "Specify first corner");
hover(&mut h, RIGHT);
assert_eq!(band(&h, FIRST, RIGHT), Band::default(), "no rectangle before the first corner");
click(&mut h, FIRST);
hover(&mut h, RIGHT);
assert_eq!(band(&h, FIRST, RIGHT), window, "the rectangle follows the cursor as a window");
hover(&mut h, LEFT);
assert_eq!(band(&h, FIRST, LEFT), window, "W is a window to the left too");
click(&mut h, RIGHT);
assert_eq!(h.state().session.selection(), vec![ids[1]], "the window took the vertical line");
hover(&mut h, LEFT);
assert_eq!(band(&h, FIRST, LEFT), Band::default(), "no rectangle once the window is closed");
}
/// Typed `C`: the rectangle follows the cursor in the crossing look, to the right as well.
#[test]
fn a_typed_crossing_draws_its_rectangle_in_the_crossing_look() {
let (mut h, ids) = harness();
let (_, crossing) = implied_looks(&mut h);
typed(&mut h, "C");
hover(&mut h, RIGHT);
assert_eq!(band(&h, FIRST, RIGHT), Band::default(), "no rectangle before the first corner");
click(&mut h, FIRST);
hover(&mut h, LEFT);
assert_eq!(band(&h, FIRST, LEFT), crossing);
hover(&mut h, RIGHT);
assert_eq!(band(&h, FIRST, RIGHT), crossing, "C is a crossing to the right too");
click(&mut h, RIGHT);
assert_eq!(h.state().session.selection(), vec![ids[1]], "the crossing took the vertical line");
}
/// Typed `BOX`: a window while the cursor is right of the first corner, a crossing left of it.
#[test]
fn a_typed_box_draws_a_window_to_the_right_and_a_crossing_to_the_left() {
let (mut h, ids) = harness();
let (window, crossing) = implied_looks(&mut h);
typed(&mut h, "BOX");
click(&mut h, FIRST);
hover(&mut h, RIGHT);
assert_eq!(band(&h, FIRST, RIGHT), window);
hover(&mut h, LEFT);
assert_eq!(band(&h, FIRST, LEFT), crossing);
click(&mut h, LEFT);
assert_eq!(h.state().session.selection(), vec![ids[0]], "the box took the horizontal line");
}
/// With the area fill off (SELECTIONAREA 0) the typed window keeps its outline and has no fill,
/// as the implied window does.
#[test]
fn a_typed_window_follows_the_selection_area_setting() {
let (mut h, _) = harness();
h.state_mut().session.settings.selectionarea = false;
typed(&mut h, "W");
click(&mut h, FIRST);
hover(&mut h, RIGHT);
assert_eq!(band(&h, FIRST, RIGHT), Band { fill: None, solid: true, dashed: false });
}
/// Hover at `raw`, a point near [`END`], and check that the Endpoint snap holds the cursor on
/// [`END`] while the pointer itself is somewhere else on screen.
fn hover_snapped(h: &mut Harness<'_, CadApp>, raw: Vec2) {
hover(h, raw);
assert!(h.state().canvas.snap.is_some(), "the Endpoint snap is active at the corner prompt");
let cursor = h.state().canvas.cursor.unwrap();
assert!(cursor.dist(END) < 1e-9, "the cursor is held on the line's end: {cursor:?}");
assert!(screen(h, raw).distance(screen(h, END)) > 1.0, "the pointer is off the snapped point");
}
/// Typed `W` with a running object snap: the rectangle is drawn to the snapped point, the corner a
/// click gives, not to the pointer. A line between the two is inside the drawn rectangle and the
/// click selects it.
#[test]
fn a_typed_window_draws_its_rectangle_to_the_snapped_corner() {
let between = [Vec2::new(79.75, 40.0), Vec2::new(79.75, 60.0)];
let (mut h, ids) = harness_with(cadcraft_engine::snap::mode::END, Some(between));
let (window, _) = implied_looks(&mut h);
typed(&mut h, "W");
click(&mut h, FIRST);
assert_eq!(h.state().session.current_prompt().unwrap().message, "Specify opposite corner");
let raw = Vec2::new(79.5, 70.4);
hover_snapped(&mut h, raw);
assert_eq!(band(&h, FIRST, END), window, "the rectangle reaches the snapped point");
assert_eq!(band(&h, FIRST, raw), Band::default(), "no rectangle to the pointer itself");
click(&mut h, raw);
assert!(h.state().session.selection().contains(&ids[2]), "the click selects what the rectangle held");
}
/// Typed `BOX` with a running object snap that takes the cursor across the first corner: the
/// pointer is right of the corner and the snapped point left of it, so the rectangle is drawn as
/// the crossing the click makes.
#[test]
fn a_typed_box_takes_its_direction_from_the_snapped_corner() {
let between = [Vec2::new(80.1, 40.0), Vec2::new(80.1, 60.0)];
let (mut h, ids) = harness_with(cadcraft_engine::snap::mode::END, Some(between));
let (_, crossing) = implied_looks(&mut h);
typed(&mut h, "BOX");
let first = Vec2::new(80.25, 20.0);
click(&mut h, first);
hover_snapped(&mut h, Vec2::new(80.5, 70.4));
assert_eq!(band(&h, first, END), crossing, "left of the first corner after the snap: a crossing");
click(&mut h, Vec2::new(80.5, 70.4));
assert!(h.state().session.selection().contains(&ids[2]), "the crossing took the line it held");
}
+1 -1
View File
@@ -229,7 +229,7 @@ Select a language with `engine.execute` and the UI command `ui.language`:
{"id":1,"method":"engine.execute","params":{"command":"ui.language","params":{"lang":"uk"}}}
```
Supported values are `auto`, `en`, `uk`, `pt-BR`, `de`, `es`, `cs`, `ru`, `fr`, `zh`, `it`, `ko`, `sv`, `ar`, `hu`, `tr`, `bs`, `el`, `ka` and `ta`.
Supported values are `auto`, `en`, `uk`, `pt-BR`, `de`, `es`, `cs`, `ru`, `fr`, `zh`, `it`, `ko`, `sv`, `ar`, `hu`, `tr`, `bs`, `el`, `ka`, `ta`, `nl` and `pt-PT`.
Chinese needs an installed CJK font, Arabic an installed Arabic font, Tamil an installed Tamil font
or the `Taml` face from craft-fonts; Korean needs a font covering the Korean interface from the
optional craft-fonts input or the operating system; Georgian needs the `Geor` face from craft-fonts (an installed font
+1 -1
View File
@@ -54,7 +54,7 @@ constraints 10%.
| Spline: closed/periodic | periodic | "closed" appends the first point and refits; **not periodic** (`modify2.rs:647`) |
| Spline editing: knot insertion, split, refine, rebuild, convert to polyline | SPLINEDIT, grips | knot insertion and splitting (`curves.rs:539-622`); refine/rebuild partial |
| Helix | yes | **no** |
| 3D polyline | yes | stored and drawn; no 3D operations |
| 3D polyline | yes | stored and drawn; typed vertices keep their Z (#1410); no 3D operations |
| Regions, 3D solids, surfaces, meshes (ACIS/B-rep, NURBS surfaces, subdivision) | yes | **no** (M11) |
## Intersections (≈ 40%)
+4 -4
View File
@@ -1,17 +1,17 @@
# Interface languages
Choose **Edit → Interface Language** and select **Auto (system language)**, **English**,
**Українська**, **Português (Brasil)**, **Deutsch**, **Español**, **Čeština** (Czech), **Русский**, **Français**, **简体中文**, **Italiano**, **한국어** (Korean), **Svenska** (Swedish), **العربية** (Arabic), **Magyar** (Hungarian), **Türkçe** (Turkish), **Ελληνικά** (Greek), **Bosanski** (Bosnian), **ქართული** (Georgian), **Tiếng Việt** (Vietnamese), or **தமிழ்** (Tamil).
**Українська**, **Português (Brasil)**, **Deutsch**, **Español**, **Čeština** (Czech), **Русский**, **Français**, **简体中文**, **Italiano**, **한국어** (Korean), **Svenska** (Swedish), **العربية** (Arabic), **Magyar** (Hungarian), **Türkçe** (Turkish), **Ελληνικά** (Greek), **Bosanski** (Bosnian), **ქართული** (Georgian), **Tiếng Việt** (Vietnamese), **தமிழ்** (Tamil), **Nederlands** (Dutch), or **Português (Portugal)** (European Portuguese).
The interface updates without restarting, including the native macOS menus.
The choice is saved with the other interface preferences (`cadcraft.prefs`, beside the theme):
eframe storage on the desktop, browser local storage on the web. Installations without a saved
choice use Auto.
Auto uses the first supported language in the operating system's preferred locales, or the
browser's `navigator.languages` on the web. BCP 47 and POSIX tags select their primary language:
browser's `navigator.languages` on the web. BCP 47 and POSIX tags match an exact `<language>-<region>` catalog first (e.g. `pt-PT`) and otherwise select their primary language:
`uk-UA` → `uk`, `de_AT.UTF-8` → `de`, `es-MX` → `es`, `pt_BR.UTF-8` → `pt-BR`,
`cs-CZ` and `cs_CZ.UTF-8` → `cs`, `it-IT` and `it_CH.UTF-8` → `it`, `ko-KR` and `ko_KR.UTF-8` → `ko`,
`sv-SE`, `sv-FI` and `sv_SE.UTF-8` → `sv`, `hu-HU` and `hu_HU.UTF-8` → `hu`, `tr-TR` and `tr_TR.UTF-8` → `tr`, `ka-GE` and `ka_GE.UTF-8` → `ka`, `ta-IN`, `ta-LK` and `ta_IN.UTF-8` → `ta`. Unsupported languages fall back to English.
`sv-SE`, `sv-FI` and `sv_SE.UTF-8` → `sv`, `hu-HU` and `hu_HU.UTF-8` → `hu`, `tr-TR` and `tr_TR.UTF-8` → `tr`, `ka-GE` and `ka_GE.UTF-8` → `ka`, `ta-IN`, `ta-LK` and `ta_IN.UTF-8` → `ta`, `nl-NL`, `nl-BE` and `nl_NL.UTF-8` → `nl`, `pt-PT`, `pt_PT.UTF-8` and `pt-Latn-PT` → `pt-PT` (extension/private-use tags like `pt-x-pt` fall back to `pt-BR`). Until CADCraft embeds the `nl` and `pt-PT` catalogs from `storytold/craft-i18n`, `Auto` skips empty catalogs so existing translated fallbacks stay intact (`nl-NL, de-DE` → `de`; `pt-PT` → `pt-BR`), while explicitly selecting `nl` or `pt-PT` saves the preference and displays English.
Set `CADCRAFT_LOCALE=cs-CZ` to override the desktop's locale for a launch.
An explicit saved language choice takes precedence over that override.
@@ -22,7 +22,7 @@ Automation can select the language through the existing control channel:
```
The `ui.set` method also accepts `{"interfaceLanguage":"cs"}`. Supported values are `auto`,
`en`, `uk`, `pt-BR`, `de`, `es`, `cs`, `ru`, `fr`, `zh`, `it`, `ko`, `sv`, `ar`, `hu`, `tr`, `bs`, `el`, `ka`, `vi`, and `ta`; invalid values are rejected without changing the current
`en`, `uk`, `pt-BR`, `de`, `es`, `cs`, `ru`, `fr`, `zh`, `it`, `ko`, `sv`, `ar`, `hu`, `tr`, `bs`, `el`, `ka`, `vi`, `ta`, `nl`, and `pt-PT`; invalid values are rejected without changing the current
selection. Resetting palettes keeps the language choice.
## Translation coverage
+2 -1
View File
@@ -44,7 +44,7 @@ percentages below are from 2026-10-11 and were not re-measured. Remaining: **≈
| Input | AutoCAD | CADCraft | Evidence |
|---|---|---|---|
| `x,y[,z]`, `@dx,dy`, `@d<a`, `d<a`, `#x,y`, bare `@` | yes | yes; `#` equals absolute because there is no UCS; Z parsed then discarded | `prompt.rs:147-180` |
| `x,y[,z]`, `@dx,dy[,dz]`, `@d<a`, `d<a`, `#x,y[,z]`, bare `@` | yes | yes; `#` equals absolute because there is no UCS; a typed Z reaches the command (`Session::point_z`; relative forms add to LASTPOINT's Z); LINE, POINT and 3DPOLY read it, and a point picked with an object snap carries the Z of the object it snapped to | `prompt.rs` (`parse_point3_in`) |
| `*x,y` (WCS override) | yes | yes (`*x,y`, `*@dx,dy`, `@*dx,dy`); the same as the plain forms because there is no UCS | `prompt.rs` |
| Direct distance entry | yes, honours ortho, polar and tracking paths | yes, ortho; polar only through the UI's snapped cursor | `lib.rs:782-793` |
| Angle forms: `45d30'`, radians, grads, surveyor `N45dE` | yes | yes | `units.rs:141-197` |
@@ -211,6 +211,7 @@ dimensions are edited).
| 2026-10-27 | minor | WIPEOUT grips treat implicit and explicit closure alike; moving the first vertex carries the closing marker, and moving endpoints together keeps both corners editable. Open/closed polyline flags and coincident polyline vertices remain independent (#2256) |
| 2026-10-26 | minor | Browser host stores bounded, validated panel layout separately from drawing state; malformed or unsupported records retain defaults. Native workspace storage is unchanged. |
| 2026-10-24 | minor | Re-audit against main 41d9b5e95: evidence text for TK and typed snap overrides, PolarSnap, Dynamic Input, hot-grip options, dynamic block grips, SCRIPT, ZOOM Realtime/Dynamic, named views and VPORTS; headline no longer lists selection cycling as missing; the 48% and the area percentages are not re-measured |
| 2026-10-16 | trivial | A typed point keeps its Z (`x,y,z`, `@dx,dy,dz`; LASTPOINT carries it), and the interactive 3DPOLY draws with it (#1409, #1410) |
| 2026-10-22 | minor | Polyline segment midpoint grips use rectangles, distinct from square vertex grips, with matching hover and pick bounds (#1950) |
| 2026-10-13 | minor | Filled-region highlight boundaries are traversed in deterministic coordinate order, fixing dash-phase jumps on CPU hover/selection redraws and GPU highlight rebuilds; CPU dash-position, pixel and GPU mesh regressions |
| 2026-10-14 | minor | Selection cycling (#1143): the list and badge of SELECTIONCYCLING, Shift+Space through overlapping objects (#1145) |
+374
View File
@@ -0,0 +1,374 @@
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under the name "LEGAL", and included in all Covered Software
distributed in Source Code Form. Except to the extent prohibited by
statute or regulation, such description must be sufficiently detailed
for a recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at https://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.
@@ -0,0 +1,40 @@
# Third-Party Notices
## ACadSharp
The DWG reader and writer include code ported and adapted from ACadSharp. The repository
history's initial DWG support commit identifies the source classes explicitly, including
`DwgStreamReaderBase`, `DwgLZ77AC21Decompressor`, `DwgFileHeaderWriterAC18`, and
`DwgObjectWriter`. Their current Rust implementations are in `src/io/dwg`.
Copyright (c) 2021 Albert Domenech
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
## DWG Format References
DWG field layouts and version behavior are based on the Open Design Alliance (ODA) DWG
specification and reverse engineering, including comparison with drawings produced by CAD
applications. LibreDWG is used as a secondary cross-check for selected field names and
layouts. The Reed-Solomon tests cite numeric reference values from LibreDWG's
`src/reedsolomon.c` to validate the Rust implementation; those values are test data, not
translated routines. The repository history and source review found no LibreDWG routines
ported into the implementation. The source comments identify the specific cross-checks.
+4 -1
View File
@@ -23,5 +23,8 @@ fn dwg_test_dependency_matches_the_shared_bridge_targets() {
tests["target"], "cfg(not(any(target_arch = \"wasm32\", all(target_os = \"freebsd\", target_arch = \"aarch64\"))))",
"--all-targets must not add acadrust where the shared DWG bridge excludes it"
);
assert_eq!(tests["req"], "^0.6.6", "tests inspect output from the decoder version used by craft-dwg");
assert_eq!(
tests["source"], "git+https://github.com/storytold/acadrust.git?rev=5d5c482b3fcb3dc77e8281474461760f32959436",
"tests inspect output from the decoder craft-dwg uses: the storytold/acadrust fork at storytold/v0.6.6"
);
}