Compare commits

...
Author SHA1 Message Date
FredApps ba344a894b Merge pull request #2790 from 2ez4gcx/fix/join-other-height
JOIN: ends meet at the same height; objects facing the other way stay out
2026-11-26 06:13:20 +01:00
FredApps c9260d1b59 Merge pull request #2740 from 2ez4gcx/feat/qleader
QLEADER at the command line, as AutoCAD 2024 runs it
2026-11-26 06:06:19 +01:00
FredApps d2587c694e Merge pull request #2487 from 2ez4gcx/fix/linetype-dash-layout
Linetypes: lay dashes out as AutoCAD does
2026-11-26 06:05:59 +01:00
FredApps a06b236f0c Merge branch 'main' into fix/join-other-height 2026-11-26 05:34:33 +01:00
FredApps 4a4b1e2339 Merge pull request #2906 from 2ez4gcx/fix/pedit-heights
PEDIT: polylines at their objects' height; Join only at the same height
2026-11-26 05:32:57 +01:00
FredApps b5481e3bbf Merge pull request #2725 from 2ez4gcx/feat/join-autocad
JOIN onto the source object as AutoCAD 2024 does: lines, arcs, and a polyline that keeps its handle
2026-11-26 05:32:42 +01:00
FredApps 7244d2bc96 Note QLEADER in the Leaders, tables, fields parity row
The command-line form lands in #2740 / #3532; the Settings dialog is still open.
Percentages and hours are not re-measured.
2026-11-26 05:30:16 +01:00
FredApps d8aa2c60dc Merge main into feat/qleader 2026-11-26 05:30:16 +01:00
FredApps b38215b7cf Merge main into fix/linetype-dash-layout 2026-11-26 05:30:04 +01:00
FredApps d955a3ccfc Clamp gap-first open-run dashes to the start of the run
In the x < 0 branch, a dash that starts slightly before p0 could push a
negative range. Keep the start at p0 (and the existing end cap at p0 + len).
2026-11-26 05:30:04 +01:00
aiongg b55abde2a8 Merge pull request #3449 from aiongg/minimal-port-next
CadCraft: move to craft-libs next (minimal port)
2026-11-25 23:16:50 -05:00
aiongg a3640199b6 Quit CADCraft asks about unsaved drawings again
muda's predefined Quit ends the process through terminate: without asking. The menu item
is craft-quit's Quit, a close request of the main window, so the close path asks first
as the close button does (#2157).
2026-11-26 03:48:00 +00:00
FredApps 91966ccc9d Classify qleader under NO_FILES for automation roots 2026-11-26 10:15:15 +07:00
FredApps 414e544282 Merge pull request #2760 from 2ez4gcx/fix/options-reset-profile
OPTIONS: reset restores every profile variable; a refused change leaves the drawing's snap and grid
2026-11-26 03:58:53 +01:00
FredApps b255d58275 Merge pull request #3491 from 2ez4gcx/fix/attrib-tag-matching
fix(doc,render,io,engine): match attributes to their definitions by tag in one lookup (part of #1923)
2026-11-26 03:54:12 +01:00
FredApps 1fb86ec415 Merge remote-tracking branch 'origin/main' into ic40-2740 2026-11-26 09:50:41 +07:00
FredApps bc5749ec18 fix(doc): order attribute tags instead of hashing them, so crafted tags can't collide on the web build
The web build's RandomState keys come from addresses, not entropy, so a
file could pick tags whose hashes collide and bring back the A x K cost
this change removes. Key the by-tag maps by the tag's ASCII-folded bytes
in a BTreeMap, as the layer and block name index (#3484) does. Matching
is unchanged: TagKey's order is consistent with eq_ignore_ascii_case.

Part of #1923.
2026-11-26 09:42:42 +07:00
FredApps 4cc0e1f19a Merge main into fix/attrib-tag-matching 2026-11-26 09:34:25 +07:00
aiongg f99ae6956c A copy fired in a floating panel keeps the modifiers it was pressed with 2026-11-25 20:11:31 +00:00
aiongg b844248903 Floating windows carry the running channel's app id 2026-11-25 20:09:16 +00:00
aiongg 1cff8cd681 Repin craft-libs to storytold next 8fa4db64a9 and egui to b9770908e 2026-11-25 19:15:09 +00:00
aiongg 09944da2a4 Repin craft-libs to the hidden-window and modal-focus fixes (next + float-fixes) 2026-11-25 18:45:26 +00:00
aiongg 433e51abc4 Reset Panel Layout cancels a panel drag in progress again
As before the move to the craft-ui dock, a tab held while the layout
resets is not dropped into the reset layout. The reset replaces the
workspace, so its generation changes.
2026-11-25 18:29:18 +00:00
aiongg 53d1790348 Close tests: a close that goes ahead is checked without quitting
The tests assert CADCraft's own close decision for a saved drawing and
for a programmatic quit, as they did before the platform's quit joined
the close path, so they pass on macOS, where that quit cancels the window
close. Unsaved drawings still run the whole close frame.
2026-11-25 18:24:58 +00:00
aiongg f4c3018003 An opened panel's floating window comes to the front again
As before the move to the craft-ui dock, opening or activating a panel
with a command raises the floating window that holds it, once. Docked
panels only become the front tab.
2026-11-25 18:24:58 +00:00
aiongg 239f8a32f0 Repin craft-libs to the fix for windows that stay hidden (next + float-menu) 2026-11-25 18:19:04 +00:00
aiongg 9d214d6e88 Drawing focus comment: a click on a palette leaves the drawing focused 2026-11-25 15:50:21 +00:00
aiongg d26d9ca01f Repin craft-libs to storytold next aa401985d 2026-11-25 15:50:21 +00:00
aiongg c9286726ab Copy, Cut and Paste pressed in a floating panel reach the app 2026-11-25 15:15:06 +00:00
aiongg 138f447988 Ctrl+=, Ctrl++, Ctrl+- and Ctrl+0 change the interface scale
The keys (Cmd on macOS) step the Options interface scale by a tenth, within its limits, and Ctrl+0 sets it back to 100 %. They work while a text field or the command line has the keyboard, and a key the user gave to a command runs the command. In the browser they zoom the page.
2026-11-25 14:35:42 +00:00
aiongg e425c71c44 Enter and Space leave the drawing's right-click menus open 2026-11-25 14:20:12 +00:00
aiongg c3f691264a Repin craft-libs to storytold next d1bdf8e5da 2026-11-25 13:44:10 +00:00
aiongg aac7ae1cf2 A running command keeps Tab after a click on the palette or the status bar 2026-11-25 13:24:08 +00:00
aiongg 849e6fd5c4 The drawing takes the keyboard focus and keeps Tab while the command line has work for it
A press in the drawing, and a drawing that opens or becomes active, give the drawing the focus; a text field, a dialog
or a menu keeps it. The focused drawing keeps Tab (KeepKeys::Tab) only while a command runs, text is typed, value boxes
are live or a snap marker is under the cursor. A bare Tab with nothing focused is the framework's: capture_tab is gone.
2026-11-25 13:06:11 +00:00
aiongg 9e5889b782 Tab reaches the palettes from the document tabs
The drawing's host canvas is declared with the id of the drawing's own widget, so egui keeps the focus Tab gives it.
While the drawing is the focused Tab stop, the command line and the shortcuts take the keyboard as with nothing focused.
2026-11-25 12:38:02 +00:00
2ez4gcxandClaude Opus 5.5 a34ebd0bd0 Match attributes to their definitions by tag in one lookup (part of #1923)
One block reference with A attributes of a block with K attribute
definitions cost A x K tag comparisons wherever they are matched: the
extents (constant values a reference carries, the layer of an attribute
without its own), the renderer's constant values (per MINSERT copy), the
DXF writer (ATTRIB properties, MULTILEADER block-content values), BURST,
ATTSYNC/BLOCKREPLACE and the dynamic-grip preview. Crafted 16k x 16k and
32k x 32k files took 2-28 s to open, draw or save in a dev build.

TagKey compares and hashes a tag without ASCII case, as
eq_ignore_ascii_case does; Block::attdefs_by_tag and
Insert::attribs_by_tag keep the first definition or attribute of a tag,
as the scans' find/any did. Each site builds the map once and looks each
tag up once. Outputs of the crafted files are byte-identical.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 15:26:03 +07:00
aiongg c089fdff1a Paste tests that run only the shortcut table don't install the runtime (no drawing keeps the clipboard events in egui) 2026-11-25 07:19:23 +00:00
aiongg ad1446c302 Allow egui::ComboBox: craft-libs next has no craft_ui::ComboBox 2026-11-25 06:47:06 +00:00
aiongg 7eb9401f08 cargo fmt 2026-11-25 06:40:11 +00:00
aiongg 69a040acc6 Merge main into the minimal port
Conflicts: Cargo.toml (kept the next/egui pins for every craft-libs entry, including main's new craft-csv and hayro-interpret/cmap/postscript patches), apps/cadcraft/src/main.rs (port's framework frame decision and apply_frame with main's os_window identity, persistence path and exit hook), crates/ui-egui/src/updates_ui.rs (next's argument-free check calls with main's check_updates_at_start gate). Main's new tests and dialogs switched to install_headless and escape_pressed.
2026-11-25 06:38:00 +00:00
aiongg 2282d11b37 Repin egui to storytold b15ffe9bfc (what craft-libs next pins) 2026-11-25 06:32:55 +00:00
aiongg d659315743 Repin craft-libs to storytold next 16001e7210 and egui to storytold b15ffe9bfc 2026-11-25 06:31:24 +00:00
aiongg 9ea307ede8 Capture tests: frames run the app's raw input hooks; one geometry for the admission test
The capture rig ran note_raw_geometry alone, so the framework never got
the Options interface scale (FrameInput's Scale, given in before_input)
and egui's zoom stayed 1: the settled-scale test saw 800×600. It now runs
raw_input_hook and before_input, as the desktop app does.

The admission test reseeded the geometry for each request, an identity
change that the next drain rejects queued requests for; it now admits
all four against one geometry, so all four issue and stay undrained.
2026-11-24 19:28:13 +00:00
aiongg c125e9ebb8 Repin craft-libs to 9fd8b0cdaa; frame-only work and captures skip passes that will run again 2026-11-24 19:08:26 +00:00
aiongg ddee4e5bec Tests on next: clipboard rig without the runtime, wheel rig with the frame input, QuickCalc field under its panel, traversal from a focused control, left-edge drop case 2026-11-24 17:40:53 +00:00
aiongg 092ab07e66 Repin craft-libs to next-host-input 3ad64a26ea 2026-11-24 17:06:04 +00:00
aiongg 5195d9e5c8 Screenshots need no egui import on the web; iconic-column test reads the icons right of the drawing 2026-11-24 16:57:16 +00:00
aiongg 4f4a3e94b6 Tests: install the runtime in harnesses that run the app's UI; dock tests on next's model
Harnesses and bare contexts that run CadApp::ui install the runtime headless; rigs that
run the raw hook also run before_input. Dock tests use the workspace accessors, next's
action constructors and the tabs' accessible names; tests of the old renderer's hit rects,
divider ids and drag bar are removed.
2026-11-24 16:47:31 +00:00
aiongg 68de3797cc Host the craft-ui runtime from CADCraft's eframe App on craft-libs next
The runtime is installed in the desktop and web shells, before_input runs in the raw hook,
the close path decides in embed::logic, and the interface scale is the runtime's RootEnv
scale. The dock is next's DockArea over the saved workspace with CADCraft's panel bodies
and the drawing as its canvas group; ui.dock keeps its JSON vocabulary. Update dialogs run
on a DialogHost, the macOS title row is shell::TitleBar, screenshots use the runtime's
screenshot slot, and Escape with nothing focused is read as the window's cancel.
2026-11-24 16:47:31 +00:00
aiongg b6ee77e3ac Cargo.lock for the next pins (rustix 1.1.6) 2026-11-24 16:35:24 +00:00
aiongg 180ff4471d minimal-port rewrite: 99 edits (dock rename 43, combo 40, dock 10, split rename 3, deps 2, split 1) 2026-11-24 16:27:10 +00:00
aiongg 8fe5682b63 minimal-port repin: 35 edits (revs 30, features 5) 2026-11-24 16:26:54 +00:00
2ez4gcxandClaude Opus 5.5 ee13c648df Merge main into fix/linetype-dash-layout
Conflict in crates/render/src/wide.rs dashed(): keep main's point budget
for segments() (#3306) and the branch's closed PLINEGEN anchor.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 17:34:35 +07:00
2ez4gcxandClaude Opus 5.5 12b7742384 JOIN: set the new polyline's elevation without with_z
#2548 rewrites BREAK and deletes with_z; with both PRs in, this branch's
call to it no longer compiled (E0425), whichever landed first. Set the
elevation on the polyline lwpoly() makes instead: the same value, and
nothing of this branch depends on with_z any more.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 08:59:04 +07:00
2ez4gcxandClaude Opus 5.5 74c183415b Merge main into fix/linetype-dash-layout
Brings the branch up to main ca87680f. The one conflict is in
crates/render/src/linetype_text.rs, texts(): main's #2744 adds a point
allowance for the labels of a run, and this branch starts the run a period
before its start. Both are kept: the allowance is charged for each label
placed, and elements before the run's start are skipped before any charge.
Main's new test placed_labels_stop_at_the_point_allowance now passes the
Layout argument this branch added to texts().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 11:54:27 +07:00
2ez4gcxandClaude Opus 5.5 45300ee3a2 Merge main into fix/pedit-heights
Brings the branch up to main 6d744887, which has #2954's fix for
mtext::tests::strips_formatting, so the gate runs on a main that passes.
No conflicts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 12:52:16 +07:00
2ez4gcxandClaude Opus 5.5 96e62b4632 PEDIT Join: only objects in one plane with the polyline, as AutoCAD 2024
AutoCAD 2024 joins only objects that lie in one plane with the polyline:
the plane the polyline and every line picked share, if they share one,
else the polyline's own. Measured: a triangle at Z 5 whose last side slopes
to Z 0 leaves that side out; a sloped line followed by a line turning off
their vertical plane joins neither; a sloped line followed by an arc joins
the line only. Before, a sloped line joined wherever its end met the chain
at the same height.

Also, after review: tests for the sloped line drawn either way, a chain
meeting its start at another height, arcs below Z 0 and mirrored above it,
thickness, the joined polyline's normal and bulges, fuzz in plan only, and
an exact pick on the arc; doc comments for the plane rule, the height
tolerance and tilted arcs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 04:04:46 +07:00
2ez4gcxandClaude Opus 5.5 e20f5ed590 PEDIT: polylines at their objects' height; Join only at the same height
PEDIT turned a line or an arc into a polyline at elevation 0, so a line at
Z 5 dropped to Z 0, and its Join took any object meeting the polyline in
plan. As AutoCAD 2024 does (measured):

- Convert puts the polyline at the line's height or the arc's centre
  height and keeps the thickness; a line's polyline faces up whatever the
  line's normal, a mirrored arc's keeps its normal and runs as the arc
  does in its own coordinates.
- PEDIT's Join takes an object only where the ends meet at the same
  height, and none facing the other way (an arc or polyline whose normal
  points down Z where the polyline's points up, or the other way round;
  a line counts as facing up). After a sloped line, the chain continues
  from its far end's height.
- Multiple's Join leaves out objects facing the other way too, but takes
  them at any height.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 21:19:21 +07:00
2ez4gcxandClaude Opus 5.5 6133dc60bb JOIN: a new polyline stays at the source's height
JOIN made the new polyline from a line or arc source at elevation 0, so
lines at Z 5 moved down to Z 0. It now takes the source's height, as a
polyline source keeps its elevation with a sloped line joined to it
(AutoCAD 2024, measured), negated when the polyline inherits a normal
pointing down Z. The new polyline itself wasn't measured: the core
console's JOIN never makes one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 09:02:04 +07:00
2ez4gcxandClaude Opus 5.5 19dcf74419 JOIN: ends meet at the same height; objects facing the other way stay out
JOIN compared chain ends in plan only, so an end meeting another only in
plan at another height was joined and collapsed onto the source's
elevation. Each piece now carries its ends' world heights (a line's own
Z, an arc's centre Z, a polyline's elevation, negated when its normal
points down Z), turned round with the piece, and ends must meet at the
same height too.

Onto a polyline source, an object facing the other way stays out: an arc
or a polyline faces its normal, a line always counts as facing up.
AutoCAD 2024 (accoreconsole, measured) joins a line with normal 0,0,-1
to a polyline facing up, no line to a polyline facing down, and an arc
or polyline only when it faces the polyline's way. A line or arc source
keeps the old behaviour: the core console can't measure it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 23:18:18 +07:00
2ez4gcxandClaude Opus 5.5 81f8032255 OPTIONS: a refused change puts the same drawing back
Writing the header entries back went through doc_mut, whose copy on
write gave a clean drawing a new Arc, so a refused OPTIONS call marked
it changed. apply now keeps the drawing's Arc when SNAPUNIT or GRIDUNIT
is among the values and puts that same Arc back on a refusal; a call
that names neither never touches the drawing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 13:43:33 +07:00
2ez4gcxandClaude Opus 5.5 ab71b353d5 OPTIONS: reset puts every profile variable back; a refused change leaves the drawing's snap and grid
options::reset missed 15 profile variables (the Dynamic Input, selection
preview and area, grip, PICKSTYLE and MEASUREINIT settings), so a reset
left them as they were. It now restores all of them; SNAPUNIT and
GRIDUNIT, which the drawing keeps in its header, are still left alone.

apply is all or nothing, but a refused value left SNAPUNIT and GRIDUNIT
written to the drawing's header. Their raw header entries are now put
back as they were, or removed when the drawing didn't have them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 11:54:04 +07:00
2ez4gcxandClaude Opus 5.5 02dfd37d14 Merge main into fix/linetype-dash-layout
main added SHX shapes to complex linetypes in linetype_text.rs; this
branch lays linetype elements out with Layout and phase. Both are kept:
shapes go where texts and dashes go (centred on an open run), and
main's point budget counts only the elements placed. main's shape test
now expects the centred positions, as the text test does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 09:35:44 +07:00
2ez4gcxandClaude Opus 5.5 43207db68e QLEADER: refuse a width that overflows; name an unreadable JSON point
A width given by a point far enough away to overflow is refused with the
message typed text gets, and the width is asked again. In the JSON form, a
point that can't be read says so instead of saying `points` is missing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 05:02:43 +07:00
2ez4gcxandClaude Opus 5.5 3c9b4be339 JOIN: whole objects by their ends, the circle question, the source's space
Measured in AutoCAD 2024's core console:
- Objects join whole, by their end points; a polyline is never split, and
  one met only at an inner vertex stays as it is. The source is the first
  pick JOIN can take (a circle picked first is passed over).
- Where an object meeting the chain at more than one place goes: a
  polyline by its first vertex if it can, before the chain rather than
  after; a line or an arc turned round if it can. A source that already
  ends where it starts still takes more; a join that closes the chain
  stops it; a source of no length takes nothing; a lone polyline whose
  ends meet stays open.
- Arcs that come round make a circle with no tolerance at the source's
  start, and the command line asks "Combined arc segments form a circle.
  Convert to circle? [Yes/No] <Yes>:" first; No leaves the arcs. The JSON
  form takes the default.
- A new polyline keeps another polyline's widths, and what JOIN makes
  goes in the source's space.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 04:36:45 +07:00
2ez4gcxandClaude Opus 5.5 762b64268b QLEADER at the command line, as AutoCAD 2024 runs it with its default settings
Up to three leader points, a text width (not remembered; a point gives its
distance from the leader's end), then lines of multiline text. The text
sits DIMGAP past the end: with the middle of its first line level with it
when the leader runs right (attachment 1), of its last line when it runs
left (attachment 9), whatever DIMTAD. A hook line DIMASZ long is added when
the last segment slopes and text follows. Enter at the first line leaves
the leader alone. Measured in AutoCAD 2024's core console. Alias LE, and a
JSON form.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 03:32:55 +07:00
2ez4gcxandClaude Opus 5.5 6c81995e03 fix(engine): JOIN onto the source object as AutoCAD 2024 does
Lines on the source's line make it one longer line and arcs on its circle
join counterclockwise from its start, both keeping the source's handle;
arcs that come round to within 1e-6 rad of its start make a circle on the
source's layer. An open polyline source keeps its handle, its own vertices,
elevation, PLINEGEN and (with only lines and arcs) constant width; other
polylines keep their bulges and widths, lines and arcs take the widths of
the source's vertex at that end. The tolerance is AutoCAD's measured 1e-6,
absolute at any coordinate size. The message names a line, arc or circle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 23:23:26 +07:00
2ez4gcxandClaude Opus 5.5 897f53c7b3 Merge main into fix/linetype-dash-layout
After #2603, dashes are laid out only with Options::linetypes on: the
runs stroked with a layout (open, or closed from an anchor) and the
polyline centre line keep that check, so hit tests still draw lines
whole.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 07:40:25 +07:00
2ez4gcxandClaude Opus 5.5 b91fa88224 Linetypes: a plot or export keeps the dashes of a run over 50,000 periods
The 50,000-period guard is for a display zoomed out a lot, so it now applies only where there
is a level of detail (min_pattern above 0). A plot or export has none and keeps the pattern on a
run of any length, bounded by the two-million-element work limit; linetype text follows, through
phase. This is the plot exemption of #1277 (#1069) in the new layout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 08:41:26 +07:00
2ez4gcxandClaude Opus 5.5 3e8f468fe3 Linetypes: anchor a closed PLINEGEN run at its second vertex when it coincides with the first
The anchor was the length of the first drawn segment, so when the first two
vertices coincide (Polyline::segments leaves that pair out) the pattern was
anchored at the third vertex. It is now the chord length from the first
vertex to the second (wide::second_vertex_at), 0 for that pair, and the
thin run and the wide band share it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 22:57:33 +07:00
2ez4gcxandClaude Opus 5.5 e6f2ea0405 Linetypes: keep the cap on pattern elements laid out
The rewritten layout capped runs at 50,000 periods but dropped the
earlier limit of 2,000,000 pattern elements, so a long pattern repeated
that often could produce millions of ranges. A run past either limit is
drawn continuous again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 19:21:33 +07:00
2ez4gcxandClaude Opus 5.5 dc07a1032d Linetypes: anchor a closed run at its second vertex as it is drawn
The anchor of a closed PLINEGEN polyline is now the length of its first
segment tessellated at the drawing tolerance, as the run is measured,
not the arc length. With an arc first, a dash now starts right at the
second vertex, matching the filled band, which already measured it so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 18:46:54 +07:00
2ez4gcxandClaude Opus 5.5 6c2d37983e Linetypes: a wide polyline's centre line is dashed as a thin one
With fill off, a polyline with width draws its centre line. It now goes
through the same layout as a polyline without width: stretched around a
closed PLINEGEN one from its second vertex, along the whole of an open
PLINEGEN one, and restarted at each vertex otherwise.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 18:15:45 +07:00
2ez4gcxandClaude Opus 5.5 6d3f63752b Linetypes: one ranges function that takes the layout
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 15:28:29 +07:00
2ez4gcxandClaude Opus 5.5 3944717ca2 Merge main into fix/linetype-dash-layout
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 14:54:02 +07:00
2ez4gcxandClaude Opus 5.5 c319cd7ae4 Linetypes: closed wide bands and gap-first phase follow the dashes
A closed PLINEGEN polyline with width now lays its pattern out like a
thin one: stretched around the run from the second vertex
(linetype::ranges_as with Layout::Closed), not centred as an open run.

phase() now gives where the periods of a gap-first pattern start when
the run leaves room for a piece of dash at its start: a gap before the
second element at x, as gap_first lays them, so text in the linetype
sits with its dashes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 14:54:01 +07:00
2ez4gcxandClaude Opus 5.5 a303ff433c Linetypes: lay dashes out as AutoCAD does
Patterns were laid out from the start of every run with the first dash
whole. AutoCAD 2024 plots, read back stroke by stroke, show otherwise:
an open run is drawn continuous when shorter than one period, and
otherwise the pattern is centred (n = floor(L / period),
p0 = (n·period + first − L) / 2), the first dash starting at the run's
start and the last ending at its end; a pattern opening with a dot puts
dots at both ends, and one opening with a gap has a rule of its own. A
closed run (a circle, a whole ellipse, a closed PLINEGEN polyline) is
stretched to round(L / period) periods from its anchor (angle 0, or the
second vertex).

linetype::layout makes the drawn stretches for both; apply, apply_as
and ranges use it, the draw code picks the closed layout for circles,
whole ellipses and closed PLINEGEN polylines, and text in complex
linetypes follows the same phase. The measured lines, dots, circle,
rectangles and 33 gap-first cases are pinned in the linetype tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 13:11:38 +07:00
159 changed files with 7203 additions and 1498 deletions
Generated
+1272 -86
View File
File diff suppressed because it is too large Load Diff
+36 -32
View File
@@ -14,11 +14,11 @@ repository = "https://github.com/storytold/cadcraft"
# internal
cadcraft-geom = { path = "crates/geom" }
# DXF tags: the shared reader and writer (moved from crates/dxf; craft-libs#791).
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "219c1d0b14177af6f291395d6587f61a5e09043a" }
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
cadcraft-color = { path = "crates/color" }
cadcraft-doc = { path = "crates/doc" }
cadcraft-constraints = { path = "crates/constraints" }
@@ -28,19 +28,19 @@ cadcraft-io = { path = "crates/io" }
cadcraft-engine = { path = "crates/engine" }
cadcraft-ui-egui = { path = "crates/ui-egui" }
cadcraft-mcp = { path = "crates/mcp" }
craft-mcp = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-mcp = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# SVG/SVGZ import and export geometry (craft-libs#778).
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# Which paths stored in a drawing (xrefs, data links) may be opened.
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# PDF writing (krilla) for plots, and reading them back in tests. The root patches below pin
# craft-pdf's patched backends to the same revision (Cargo ignores dependency-local patches).
craft-pdf = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", default-features = false }
craft-pdf = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false }
# TrueType embedding-permission classification for plotted fonts (craft-libs#778).
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", default-features = false }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false }
# Delimited text (CSV/TSV) parsing (shared Craft library).
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
clap = { version = "4", features = ["derive", "env"] }
clap_complete = "4.6.11"
clap_mangen = { version = "0.3.3", features = ["env"] }
@@ -74,8 +74,12 @@ encoding_rs = "0.8.35"
quick-xml = "0.42"
# ui
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["serde"] }
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] }
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-behavior = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-host = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-keymap = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-theme = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
egui = { version = "0.37", default-features = false, features = ["default_fonts", "monochrome_emoji_fonts"] }
# Resizable table columns (About ▸ Contributors / Models); no image loaders.
egui_extras = { version = "0.37", default-features = false }
@@ -85,7 +89,7 @@ egui-wgpu = "0.37"
# Monotonic time on native and web (performance.now on wasm).
web-time = "1.1"
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
rfd = "0.17"
arboard = { version = "3.6", default-features = false }
@@ -117,23 +121,23 @@ debug = 0
# PDF backends for craft-pdf: pinned to the same reviewed craft-libs revision as craft-pdf itself
# (Cargo ignores dependency-local patches).
[patch.crates-io]
krilla = { version = "=0.8.2", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
krilla = { version = "=0.8.2", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# Keep the complete egui family and native event bridge on reviewed fork commits.
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
+2 -2
View File
@@ -21,8 +21,8 @@ cadcraft-io = { workspace = true }
cadcraft-fonts = { workspace = true }
# The host messages (storytold/craft-libs): one contract and one bridge for the web builds.
# The page command API (storytold/craft-libs#413): window.cadcraft over the control channel.
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "0.1.0" }
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "0.1.0" }
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
egui = { workspace = true }
log = { workspace = true }
serde_json = { workspace = true }
+4 -2
View File
@@ -54,11 +54,12 @@ mod web {
if let Some(bridge) = &self.2 {
bridge.report_dirty(&self.0);
}
self.0.close_path(ctx);
}
/// Forward raw input to the web `CadApp` and capture Tab at the command line.
/// Forward raw input to the web `CadApp` and hand the frame's root values to the UI runtime.
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
self.0.raw_input_hook(ctx, raw);
cadcraft_ui_egui::cmdline::capture_tab(ctx, raw);
self.0.before_input(ctx);
}
/// Preferences and validated panel placement survive reloads; egui memory is not kept.
fn save(&mut self, storage: &mut dyn eframe::Storage) {
@@ -166,6 +167,7 @@ mod web {
canvas,
options,
Box::new(move |cc| {
cadcraft_ui_egui::framework::install_headless(&cc.egui_ctx);
// Embedded, the host sends the drawing: start on the Start tab, not Drawing1.
let session = if app_bridge.is_some() { Session::empty() } else { Session::new() };
let control = crate::api::install(cc.egui_ctx.clone());
+1 -1
View File
@@ -94,7 +94,7 @@ mod tests {
let mut ui = UiState::default();
let before = serde_json::to_value(&ui).unwrap();
let mut invalid = ui.clone();
invalid.docking.layout.root = None;
invalid.docking = cadcraft_ui_egui::docking::Workspace::default();
assert!(save(&invalid).is_err());
let mut record: Value = serde_json::from_str(&save(&ui).unwrap()).unwrap();
record["docking"] = serde_json::to_value(&invalid.docking).unwrap();
+3 -7
View File
@@ -41,22 +41,18 @@ winit = { version = "0.30", default-features = false, features = ["x11"] }
zbus = { version = "=5.19.0", default-features = false, features = ["async-io", "blocking-api"] }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
# Floating panels open in their own OS windows on the desktop; the web build keeps them in the page.
craft-ui = { workspace = true, features = ["native-windows"] }
craft-update = { workspace = true }
rfd = { workspace = true }
sys-locale = "0.3"
[target.'cfg(target_os = "macos")'.dependencies]
# `title_bar::sync_movable`: AppKit's title-band drag leaves the window still under the row's
# controls and under floating panels.
craft-window = { workspace = true }
muda = { version = "0.21", default-features = false }
# Quit CADCraft as a close request of the main window, so the unsaved-changes question runs (#2157).
craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
# View ▸ Accessibility ▸ Animation Effects ▸ Use System Setting: the system's Reduce motion
# (system_animations.rs). Already in Cargo.lock through muda.
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSWorkspace", "NSAccessibility"] }
# The same winit eframe uses (the storytold fork, patched in the workspace): its opt-in that turns
# AppKit's terminate (Cmd+Q, Dock Quit) into a close request, so unsaved changes are asked about.
# The same winit eframe uses (the storytold fork, patched in the workspace).
# `rwh_06`: the window handle a file dialog shown as a sheet attaches to (src/sheet.rs).
winit = { version = "0.30", default-features = false, features = ["rwh_06"] }
# Waits for the answer of a file dialog shown as a sheet (src/sheet.rs). MIT OR Apache-2.0, already
+25 -37
View File
@@ -61,9 +61,6 @@ struct App {
/// `CADCRAFT_NO_NATIVE_MENU`: the menus stay inside the window.
#[cfg(target_os = "macos")]
menus_in_window: bool,
/// The `movable` flag last set on the main window.
#[cfg(target_os = "macos")]
movable: Option<bool>,
/// Drawings and quit requests from Finder, the Dock and `open -a` (see `apple_events`).
#[cfg(target_os = "macos")]
apple_events: fmv_macos_events::Inbox,
@@ -141,17 +138,18 @@ impl eframe::App for App {
if std::mem::take(&mut self.cad.quit_requested) {
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
}
self.cad.close_path(ctx);
}
/// Apply the desktop-theme fallback, forward raw input to `CadApp`, and capture Tab at the command line.
/// Apply the desktop-theme fallback, forward raw input to `CadApp`, and hand the frame's root values to the UI
/// runtime.
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
follow_desktop(raw, self.desktop_theme.current());
self.cad.raw_input_hook(ctx, raw);
cadcraft_ui_egui::cmdline::capture_tab(ctx, raw);
self.cad.before_input(ctx);
}
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
cadcraft_ui_egui::framework::before_ui(ui.ctx(), &*frame);
self.cad.guarded_ui(ui);
#[cfg(target_os = "macos")]
craft_window::title_bar::sync_movable(ui.ctx(), &mut self.movable);
}
/// A normal exit: the workspace is saved, and this run's autosave files are not needed (a
/// crash leaves them for recovery).
@@ -302,17 +300,15 @@ const MIN_INNER_SIZE: [f32; 2] = [900.0, 560.0];
/// The main window: its size, title bar, placement and rendering needs. `restoring`: a window state
/// saved by the last session is restored instead of opening centred. `stencil`: the stencil bits of
/// its render pass ([`stencil_bits`]).
fn window_options(restoring: bool, stencil: u8) -> eframe::NativeOptions {
fn window_options(restoring: bool, stencil: u8, frame: Option<&cadcraft_ui_egui::framework::Decision>) -> eframe::NativeOptions {
let viewport = egui::ViewportBuilder::default()
.with_title(os_window::name_for(os_window::identity()))
.with_inner_size([1600.0, 1000.0])
.with_min_inner_size(MIN_INNER_SIZE)
.with_drag_and_drop(true)
.with_app_id(os_window::app_id());
eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_title(os_window::name_for(os_window::identity()))
.with_inner_size([1600.0, 1000.0])
.with_min_inner_size(MIN_INNER_SIZE)
.with_drag_and_drop(true)
.with_fullsize_content_view(true)
.with_titlebar_shown(false)
.with_title_shown(false)
.with_app_id(os_window::app_id()),
viewport: cadcraft_ui_egui::framework::apply_frame(viewport, frame),
// The size, position and maximized state are kept between sessions (#2595); eframe keeps a
// restored window on the monitors that are connected now.
persist_window: true,
@@ -544,6 +540,9 @@ fn main() -> eframe::Result {
if stencil == 0 {
log::warn!("CADCRAFT_STENCIL is off: the window has no stencil buffer; clipped layout viewports draw unclipped");
}
// XWayland when it's there (see below), unless CADCRAFT_WAYLAND=1 keeps the native Wayland backend.
let forced_x11 = cfg!(all(unix, not(target_os = "macos"))) && std::env::var_os("DISPLAY").is_some() && vars.wayland != Switch::On;
let frame = cadcraft_ui_egui::framework::frame_decision(forced_x11);
let persistence_path = vars
.portable_storage_file
.clone()
@@ -553,7 +552,7 @@ fn main() -> eframe::Result {
// swapchains hold two frames back under vsync (`CADCRAFT_VSYNC=1` restores vsync).
wgpu_options: eframe::egui_wgpu::WgpuConfiguration::default().with_surface_config(surface),
persistence_path: persistence_path.clone(),
..window_options(restores_window(persistence_path.as_deref()), stencil)
..window_options(restores_window(persistence_path.as_deref()), stencil, frame.as_ref())
};
if let Some(icon) = app_icon() {
options.viewport = options.viewport.with_icon(icon);
@@ -576,22 +575,12 @@ fn main() -> eframe::Result {
// manager showed a "no" cursor. Run through XWayland when it's there; CADCRAFT_WAYLAND=1
// keeps the native Wayland backend.
#[cfg(all(unix, not(target_os = "macos")))]
if std::env::var_os("DISPLAY").is_some() && vars.wayland != Switch::On {
if forced_x11 {
options.event_loop_builder = Some(Box::new(|b| {
use winit::platform::x11::EventLoopBuilderExtX11;
b.with_x11();
}));
}
// macOS: Quit CADCraft (Cmd+Q), the Dock's Quit and logout end the app through AppKit's
// terminate, which would skip the unsaved-changes prompt (#2157). winit turns each into a
// close request for the window instead, so it asks first, as the close button does.
#[cfg(target_os = "macos")]
{
options.event_loop_builder = Some(Box::new(|b| {
use winit::platform::macos::EventLoopBuilderExtMacOS;
b.with_close_requested_on_terminate(true);
}));
}
// Registered before the event loop starts, so it catches the Finder event that launched us as
// well as later ones. Lives until the event loop returns; the app creator only borrows it.
#[cfg(target_os = "macos")]
@@ -604,6 +593,7 @@ fn main() -> eframe::Result {
os_window::name_for(os_window::identity()),
options,
Box::new(move |cc| {
cadcraft_ui_egui::framework::install(&cc.egui_ctx, forced_x11, frame.clone())?;
let mut app = CadApp::new(Session::empty(), services());
// The exit hook runs in `on_exit`: macOS ends the process inside AppKit's terminate after
// it, so nothing after `run_native` can be relied on there.
@@ -666,7 +656,7 @@ fn main() -> eframe::Result {
}
app.session.set_lisp_support_dir(Some(support));
}
app.integrated_titlebar = cfg!(target_os = "macos");
app.integrated_titlebar = cadcraft_ui_egui::framework::draws_title_row(frame.as_ref());
if surface.present_mode == eframe::wgpu::PresentMode::AutoNoVsync {
app.frame_cap = Some(cadcraft_ui_egui::gpu::FrameCap::new(240));
}
@@ -717,8 +707,6 @@ fn main() -> eframe::Result {
#[cfg(target_os = "macos")]
menus_in_window: vars.no_native_menu == Switch::On,
#[cfg(target_os = "macos")]
movable: None,
#[cfg(target_os = "macos")]
apple_events,
}))
}),
@@ -756,7 +744,7 @@ mod tests {
/// #1129: the first launch opens centred, not cascaded from the top-left corner.
#[test]
fn the_first_launch_opens_centred() {
let o = window_options(false, STENCIL_BITS);
let o = window_options(false, STENCIL_BITS, None);
assert!(o.centered, "centred on launch");
assert!(o.persist_window, "the window state is saved for the next launch");
}
@@ -764,7 +752,7 @@ mod tests {
/// #2595: a saved window state (size, position, maximized) is restored, not centred over.
#[test]
fn a_saved_window_reopens_where_it_was() {
let o = window_options(true, STENCIL_BITS);
let o = window_options(true, STENCIL_BITS, None);
assert!(!o.centered, "centring would move a restored window");
assert!(o.persist_window);
}
@@ -789,8 +777,8 @@ mod tests {
#[test]
fn the_window_carries_the_chosen_stencil_bits() {
for bits in [0, STENCIL_BITS] {
assert_eq!(window_options(false, bits).stencil_buffer, bits);
assert_eq!(window_options(true, bits).stencil_buffer, bits);
assert_eq!(window_options(false, bits, None).stencil_buffer, bits);
assert_eq!(window_options(true, bits, None).stencil_buffer, bits);
}
let format = |bits| eframe::egui_wgpu::depth_format_from_bits(0, bits);
assert_eq!(format(0), None, "no stencil: the canvas builds no clip pipelines");
+10 -2
View File
@@ -15,6 +15,9 @@ pub struct NativeMenu {
items: HashMap<String, (String, String, MenuItem)>,
submenus: Vec<(String, Submenu)>,
predefined: Vec<(&'static str, PredefinedMenuItem)>,
/// Quit CADCraft: a close request of the main window, so unsaved drawings are asked about first.
/// muda's predefined Quit ends the process through `terminate:` without asking.
quit: MenuItem,
language: &'static str,
/// Monotonic time of the last enablement refresh. `NEG_INFINITY` makes the first poll refresh
/// immediately: `now_ms` starts near zero, so the old `0.0` sentinel suppressed the first
@@ -58,7 +61,6 @@ impl NativeMenu {
("Hide CADCraft", PredefinedMenuItem::hide(Some(i18n::tr(language, "Hide CADCraft")))),
("Hide Others", PredefinedMenuItem::hide_others(Some(i18n::tr(language, "Hide Others")))),
("Show All", PredefinedMenuItem::show_all(Some(i18n::tr(language, "Show All")))),
("Quit CADCraft", PredefinedMenuItem::quit(Some(i18n::tr(language, "Quit CADCraft")))),
];
// The Mac place for preferences: CADCraft ▸ Settings… (⌘,) opens the Options dialog.
let settings = MenuItem::with_id("cc-settings", i18n::tr(language, "Settings..."), true, accel("Cmd+Comma"));
@@ -69,6 +71,8 @@ impl NativeMenu {
let _ = app_menu.append(&PredefinedMenuItem::separator());
}
}
let quit = MenuItem::with_id(craft_quit::QUIT_MENU_ID, i18n::tr(language, "Quit CADCraft"), true, accel("Cmd+Q"));
let _ = app_menu.append(&quit);
items.insert("cc-about".into(), ("ui.dialog.about".into(), "About CADCraft".into(), about));
items.insert("cc-discord".into(), ("ui.discord".into(), "Join the ArtCraft Discord…".into(), discord));
items.insert("cc-settings".into(), ("options".into(), "Settings...".into(), settings));
@@ -85,6 +89,7 @@ impl NativeMenu {
items,
submenus,
predefined,
quit,
language,
last_refresh: f64::NEG_INFINITY,
recent: app.ui.recent_files.clone(),
@@ -114,7 +119,9 @@ impl NativeMenu {
/// Drain queued menu events into commands (Discord opens externally), rebuild Open Recent, retranslate on a language change and refresh enablement when 300 ms have elapsed.
pub fn poll(&mut self, app: &mut CadApp, ctx: &egui::Context) {
while let Ok(ev) = self.events.try_recv() {
if let Some((cmd, _, _)) = self.items.get(ev.id.as_ref()) {
if craft_quit::on_menu_event(ctx, ev.id.as_ref()) {
ctx.request_repaint();
} else if let Some((cmd, _, _)) = self.items.get(ev.id.as_ref()) {
if cmd == "ui.discord" {
ctx.open_url(egui::OpenUrl::new_tab("https://discord.gg/artcraft"));
} else {
@@ -133,6 +140,7 @@ impl NativeMenu {
for (label, item) in &self.predefined {
item.set_text(i18n::tr(language, label));
}
self.quit.set_text(i18n::tr(language, "Quit CADCraft"));
for (label, submenu) in &self.submenus {
submenu.set_text(i18n::tr_menu(language, label));
}
+5 -5
View File
@@ -252,7 +252,7 @@ mod tests {
app.run("ui.dock", json!({"operation":"move", "panel":"layers", "target":"properties", "zone":"left"})).unwrap();
app.run("ui.dock", json!({"operation":"float", "panel":"properties", "rect":[120,90,340,410]})).unwrap();
ui.docking = app.ui.docking;
ui.docking.set_visible(Panel::ToolSets, false, None, permissions).unwrap();
ui.docking.set_visible(Panel::ToolSets, false, None, false, permissions).unwrap();
ui.show_toolsets = false;
store.save_if_changed(&ui, Instant::now()).unwrap();
let saved: Value = serde_json::from_slice(&fs::read(&path).unwrap()).unwrap();
@@ -263,9 +263,9 @@ mod tests {
assert_eq!(serde_json::to_value(&reloaded.docking).unwrap(), serde_json::to_value(&ui.docking).unwrap());
assert!(!reloaded.show_toolsets);
reveal_panel(&mut reloaded.docking, Panel::ToolSets).unwrap();
let tools = reloaded.docking.layout.location(&Panel::ToolSets).unwrap();
let tools = reloaded.docking.layout().location(&Panel::ToolSets).unwrap();
assert_eq!(serde_json::to_value(&tools.group).unwrap()["column"]["side"], json!("Start"), "{tools:?}");
assert_eq!(reloaded.docking.layout.floating[0].rect, [120.0, 90.0, 340.0, 410.0]);
assert_eq!(reloaded.docking.layout().floating[0].rect, egui::Rect::from_min_size(egui::pos2(120.0, 90.0), egui::vec2(340.0, 410.0)));
fs::remove_dir_all(directory).unwrap();
}
@@ -293,8 +293,8 @@ mod tests {
assert_eq!(ui.toolset_tab, "Modeling");
assert_eq!(ui.history_lines, 4);
assert!(!ui.show_toolsets && ui.show_palettes && !ui.show_toolbar);
assert_eq!(ui.docking.layout, default_workspace().layout);
assert!(ui.docking.hidden.is_empty(), "{:?}", ui.docking.hidden);
assert_eq!(ui.docking.layout(), default_workspace().layout());
assert!(ui.docking.hidden().is_empty(), "{:?}", ui.docking.hidden());
fs::remove_dir_all(directory).unwrap();
}
-3
View File
@@ -2,7 +2,4 @@ allow-unwrap-in-tests = true
allow-expect-in-tests = true
allow-panic-in-tests = true
allow-indexing-slicing-in-tests = true
disallowed-types = [
{ path = "egui::ComboBox", reason = "use craft_ui::ComboBox: egui's combo box menu can't grow back while open (egui#5225)" },
]
cognitive-complexity-threshold = 30
+1 -1
View File
@@ -47,7 +47,7 @@ mod proxy;
mod text;
mod wipeout;
pub use block::{Attrib, AttribModes, AttribProps, Insert, MultilineAttrib, mtext_literal};
pub use block::{Attrib, AttribModes, AttribProps, Insert, MultilineAttrib, TagKey, mtext_literal};
pub use common::{Common, Handle, Lineweight, RawTag, Transparency};
pub use curves::{Arc, Circle, Ellipse, Face3d, Line, LwPolyline, Point, PolyfaceMesh, Polyline3d, RayLine, Solid};
pub use dim::{AssocSnap, DimAssoc, DimBreak, DimKind, DimMarks, Dimension, Inspection, JoggedRadius, Leader, MLeader};
+67
View File
@@ -1,3 +1,6 @@
use std::cmp::Ordering;
use std::collections::BTreeMap;
use super::common::{Common, Lineweight};
use super::text::{MText, Text};
use super::{Color, Deserialize, EntityKind, Mat3, Serialize, Vec2, Vec3};
@@ -142,6 +145,43 @@ impl AttribProps {
}
}
/// An attribute tag as attributes are matched to their definitions and to each other: ASCII
/// letters in either case are the same tag, other characters must be equal. As an ordered map key
/// it finds the match in a logarithmic number of comparisons, where comparing each attribute with
/// each definition costs their product on a block with many of both (#1923). It orders, rather
/// than hashes, so the cost doesn't depend on hash keys a crafted file could predict (the web
/// build's `RandomState`), as in the layer and block name index.
#[derive(Clone, Copy, Debug)]
pub struct TagKey<'a>(pub &'a str);
impl TagKey<'_> {
/// The tag's bytes with ASCII letters in lower case: equal for the tags `eq_ignore_ascii_case`
/// finds equal.
fn folded(&self) -> impl Iterator<Item = u8> + '_ {
self.0.bytes().map(|b| b.to_ascii_lowercase())
}
}
impl PartialEq for TagKey<'_> {
fn eq(&self, other: &Self) -> bool {
self.0.eq_ignore_ascii_case(other.0)
}
}
impl Eq for TagKey<'_> {}
impl Ord for TagKey<'_> {
fn cmp(&self, other: &Self) -> Ordering {
self.folded().cmp(other.folded())
}
}
impl PartialOrd for TagKey<'_> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Insert {
@@ -204,4 +244,31 @@ impl Insert {
.then_before(Mat3::scale(self.scale.x, self.scale.y))
.then_before(Mat3::translate(-base))
}
/// The reference's attributes by tag: of several with one tag (in any ASCII case), the first.
/// Built once, it tells whether the reference carries a definition's tag, and its value, in
/// one lookup instead of a pass over the attributes per definition (#1923).
pub fn attribs_by_tag(&self) -> BTreeMap<TagKey<'_>, &Attrib> {
let mut by_tag = BTreeMap::new();
for a in &self.attribs {
by_tag.entry(TagKey(a.tag.as_str())).or_insert(a);
}
by_tag
}
}
impl crate::Block {
/// The block's attribute definitions by tag: of several with one tag (in any ASCII case), the
/// first in the block's order, the one an attribute of that tag takes its properties from.
/// Built once for all of a reference's attributes, it matches each in one lookup instead of a
/// pass over the block per attribute (#1923).
pub fn attdefs_by_tag(&self) -> BTreeMap<TagKey<'_>, &crate::Entity> {
let mut by_tag = BTreeMap::new();
for e in self.entities.iter() {
if let EntityKind::AttDef(a) = &e.kind {
by_tag.entry(TagKey(a.tag.as_str())).or_insert(e.as_ref());
}
}
by_tag
}
}
+20 -17
View File
@@ -1,10 +1,10 @@
//! Approximate entity bounds (used for extents, zoom and selection pre-filtering).
use std::collections::HashMap;
use std::collections::{BTreeMap, HashMap};
use cadcraft_geom::{Arc, Bounds2, EPS, Polyline, Vec2, bulge_to_arc};
use crate::{Drawing, Entity, EntityKind, LwPolyline, Prim};
use crate::{Drawing, Entity, EntityKind, LwPolyline, Prim, TagKey};
/// Nested block references deeper than this are ignored (cyclic or hostile files).
pub const MAX_BLOCK_DEPTH: usize = 16;
@@ -283,33 +283,33 @@ fn layer_counts(d: &Drawing, layer: &str, off_counts: bool) -> bool {
}
/// The layer an insert's attribute draws on, as the renderer takes it: its own, else its
/// definition's (layer "0" being the insert's).
fn attrib_layer<'a>(d: &'a Drawing, ins: &crate::Insert, a: &'a crate::Attrib) -> &'a str {
a.props.layer.as_deref().unwrap_or_else(|| {
d.block(&ins.block)
.and_then(|blk| blk.entities.iter().find(|be| matches!(&be.kind, EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(&a.tag))))
.map_or("0", |be| be.common.layer.as_str())
})
/// definition's, from the block's definitions by tag `defs` (layer "0" being the insert's).
fn attrib_layer<'a>(defs: Option<&BTreeMap<TagKey<'a>, &'a Entity>>, a: &'a crate::Attrib) -> &'a str {
a.props.layer.as_deref().unwrap_or_else(|| defs.and_then(|defs| defs.get(&TagKey(&a.tag))).map_or("0", |be| be.common.layer.as_str()))
}
/// The bounds of a block's contents, in block coordinates: its geometry, which every reference to
/// the block shows, and the value of each constant attribute definition ATTMODE shows, by tag, which
/// only a block reference draws (a dimension's block does not), and only when the reference
/// carries no attribute of that tag. They are kept apart so that the one cache serves every
/// reference, whichever asks first.
/// reference, whichever asks first. Also the block's attribute definitions by tag, for the layer
/// of an attribute that has none of its own.
struct Contents<'a> {
geometry: Bounds2,
constants: Vec<(&'a str, Bounds2)>,
defs: BTreeMap<TagKey<'a>, &'a Entity>,
}
impl Contents<'_> {
/// What reference `ins` shows of the block: its geometry and the constant values `ins` has
/// no attribute for (that attribute is drawn instead, and counted with the attributes).
fn in_reference(&self, ins: &crate::Insert) -> Bounds2 {
self.constants
.iter()
.filter(|(tag, _)| !ins.attribs.iter().any(|r| r.tag.eq_ignore_ascii_case(tag)))
.fold(self.geometry, |b, (_, c)| b.union(c))
if self.constants.is_empty() {
return self.geometry;
}
// The reference's tags are gathered once, not scanned again for each constant (#1923).
let carried = ins.attribs_by_tag();
self.constants.iter().filter(|(tag, _)| !carried.contains_key(&TagKey(tag))).fold(self.geometry, |b, (_, c)| b.union(c))
}
}
@@ -323,7 +323,7 @@ fn contents<'a, 'm>(
) -> Option<&'m Contents<'a>> {
let key = (blk.name.as_str(), depth);
if !blocks.contains_key(&key) {
let mut c = Contents { geometry: Bounds2::EMPTY, constants: Vec::new() };
let mut c = Contents { geometry: Bounds2::EMPTY, constants: Vec::new(), defs: blk.attdefs_by_tag() };
// ATTMODE, as the renderer applies it to a constant value: 0 shows none, 1 the visible
// ones, 2 all of them.
let attmode = d.header.i64("ATTMODE", 1);
@@ -487,9 +487,12 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<
// one draws nothing, so it contributes nothing: ZOOM Extents must not fly off to its
// insertion point. Attributes below still count.
let mut b = Bounds2::EMPTY;
let mut defs = None;
if let Some(blk) = d.block(&ins.block) {
let m = ins.transform(blk.base.xy());
let inner = contents(d, blk, depth, blocks, off_counts).map_or(Bounds2::EMPTY, |c| c.in_reference(ins));
let c = contents(d, blk, depth, blocks, off_counts);
defs = c.map(|c| &c.defs);
let inner = c.map_or(Bounds2::EMPTY, |c| c.in_reference(ins));
b = if inner.is_empty() { Bounds2::EMPTY } else { Bounds2::from_points(inner.corners().map(|c| m.apply(c))) };
// XCLIP: the reference app takes the boundary's box, also where it reaches past the
// block or misses it (an inverted clip can show anything, so it keeps the block's).
@@ -511,7 +514,7 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<
}
}
for a in &ins.attribs {
if !a.invisible && layer_counts(d, attrib_layer(d, ins, a), off_counts) {
if !a.invisible && layer_counts(d, attrib_layer(defs, a), off_counts) {
b = b.union(&match a.multiline_text() {
Some(m) => mtext_box(&m),
None => text_box(&a.text, a.text.value.chars().count()),
+79
View File
@@ -891,6 +891,85 @@ fn constant_values_count_in_extents_as_attmode_shows_them() {
assert!(top(2, true) > 40.0, "ATTMODE 2 shows an invisible one");
}
#[test]
fn an_attribute_lies_on_the_layer_of_the_first_definition_of_its_tag() {
// Two definitions of one tag, in different case, on a frozen layer and on layer 0: an
// attribute without a layer of its own (in a third case) lies on the first one's.
let top = |defs: [(&str, &str); 2]| {
let mut d = Drawing::new_imperial();
let mut frozen = Layer::new("AFRZ");
frozen.frozen = true;
d.layers.push(frozen);
let mut blk = Block::new("B");
blk.entities.push(on_layer("0", line((0.0, 0.0), (1.0, 1.0)), 1));
for (h, (layer, tag)) in (2..).zip(defs) {
blk.entities.push(on_layer(layer, EntityKind::AttDef(plain_attrib(tag)), h));
}
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
let EntityKind::Insert(mut ins) = plain_insert("B") else { panic!("an insert") };
let mut a = plain_attrib("Tag");
a.text.insert = Vec3::new(0.0, 500.0, 0.0);
ins.attribs.push(a);
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
extents_pair(&d).1.y
};
assert!(top([("AFRZ", "TAG"), ("0", "tag")]) < 100.0, "on the first definition's frozen layer");
assert!(top([("0", "tag"), ("AFRZ", "TAG")]) > 400.0, "on the first definition's layer 0");
}
#[test]
fn constant_definitions_of_one_tag_all_count_unless_the_reference_carries_the_tag() {
// Two constant definitions of one tag, in different case: a reference draws both values,
// unless it carries an attribute of that tag (in a third case), which stands for both.
let max = |attribs: Vec<Attrib>| {
let mut d = Drawing::new_imperial();
let mut blk = Block::new("B");
blk.entities.push(Entity::new(Handle(1), line((0.0, 0.0), (1.0, 1.0))));
for (h, tag, at) in [(2, "C", Vec3::new(0.0, 5000.0, 0.0)), (3, "c", Vec3::new(7000.0, 0.0, 0.0))] {
let mut a = plain_attrib(tag);
a.text.insert = at;
a.constant = true;
blk.entities.push(Entity::new(Handle(h), EntityKind::AttDef(a)));
}
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
let EntityKind::Insert(mut ins) = plain_insert("B") else { panic!("an insert") };
ins.attribs = attribs;
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
extents_pair(&d).1
};
for shown in [max(vec![]), max(vec![plain_attrib("D")])] {
assert!(shown.x > 6000.0 && shown.y > 4000.0, "both values count: {shown:?}");
}
let carried = max(vec![plain_attrib("D"), plain_attrib("Cc"), plain_attrib("C")]);
assert!(carried.x < 100.0 && carried.y < 100.0, "neither value counts: {carried:?}");
}
#[test]
fn many_attributes_and_definitions_are_matched_without_comparing_every_pair() {
// #1923: one reference with N attributes (none with a layer of its own) of a block with N
// constant definitions, the tags N long ones alike up to their last characters, no attribute's
// a definition's. Comparing each attribute with each definition, for its layer and for which
// constant values the reference carries, cost N x N comparisons of whole tags (many seconds
// here); one lookup per attribute or definition costs milliseconds.
const N: usize = 4000;
let tag = |kind: char, i: usize| format!("{}{kind}{i:05}", "T".repeat(1000));
let mut d = Drawing::new_imperial();
let mut blk = Block::new("B");
blk.entities.push(Entity::new(Handle(1), line((0.0, 0.0), (1.0, 1.0))));
for (h, i) in (2..).zip(0..N) {
let mut a = plain_attrib(&tag('D', i));
a.constant = true;
blk.entities.push(Entity::new(Handle(h), EntityKind::AttDef(a)));
}
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
let EntityKind::Insert(mut ins) = plain_insert("B") else { panic!("an insert") };
ins.attribs = (0..N).map(|i| plain_attrib(&tag('A', i))).collect();
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
let t = std::time::Instant::now();
assert!(!d.extents(&Space::Model).is_empty());
assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed());
}
/// Looking a layer or a block up by name does not scan the table: a file of N layers, or of N
/// blocks and N references to blocks it does not have, opened in N² name comparisons (#1924).
#[test]
+7 -1
View File
@@ -1,5 +1,5 @@
//! Dimensions and leaders: DIMLINEAR, DIMALIGNED, DIMRADIUS, DIMDIAMETER, DIMANGULAR, DIMARC,
//! DIMORDINATE, DIMCONTINUE, DIMBASELINE, QDIM, DIM (smart), MLEADER, LEADER, DIMOVERRIDE,
//! DIMORDINATE, DIMCONTINUE, DIMBASELINE, QDIM, DIM (smart), MLEADER, LEADER, QLEADER, DIMOVERRIDE,
//! DIMREASSOCIATE / DIMDISASSOCIATE, DIMTEDIT, DIMSPACE; DIMEDIT, DIMJOGGED, DIMJOGLINE,
//! DIMBREAK and DIMINSPECT in `annotate_dimedit.rs`.
@@ -19,6 +19,7 @@ mod edit;
mod leader;
mod linear;
mod mleader;
mod qleader;
mod radial;
use angular::{AngularM, ArcLenM, run_angular, run_arclen};
@@ -27,6 +28,7 @@ use common::{DimText, add_dim, assoc_enabled, circle_of, dim, pick_at};
use edit::{DimSpaceM, OverrideM, dims_of, run_dimspace, run_dimtedit, run_disassociate, run_override, run_reassociate, run_tedit, run_update};
use linear::{ChainM, LinearM, MAX_CHAIN, OrdinateM, run_aligned, run_baseline, run_continue, run_linear, run_ordinate};
use mleader::{MLeaderM, run_leader, run_mleader};
use qleader::{QLeaderM, run_qleader};
use radial::{RadialM, run_diameter, run_radius};
pub fn specs() -> Vec<CommandSpec> {
@@ -93,6 +95,10 @@ pub fn specs() -> Vec<CommandSpec> {
.alias(&["lead"])
.params("{points: [[x,y]...], text?}")
.interactive(|_| Ok(Box::new(leader::LeaderM::default()))),
CommandSpec::new("qleader", "Quick Leader", run_qleader)
.alias(&["le"])
.params("{points: [[x,y], [x,y], [x,y]?] (2 or 3), width?: text width (default 0), text?: lines split at \\n}")
.interactive(|_| Ok(Box::new(QLeaderM::default()))),
CommandSpec::new("dimstyle.update", "Update", run_update)
.menu(&["Dimension", "Update"])
.params("{handles?}")
+25 -3
View File
@@ -42,8 +42,13 @@ pub(super) struct LeaderM {
}
/// What follows the leader.
enum Annotation {
pub(super) enum Annotation {
Text(Vec<String>),
/// QLEADER's text: its lines and its width.
Quick {
lines: Vec<String>,
width: f64,
},
/// A copy of a text or multiline text: its contents, height, width and style.
Copy(MText),
None,
@@ -263,13 +268,13 @@ pub(super) fn json_leader(s: &mut Session, pts: &[Vec2], text: Option<&str>) ->
}
/// Draw the leader through `pts` and its annotation, as AutoCAD 2024 places them; their handles.
fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: bool, ann: Annotation) -> Result<Vec<Handle>> {
pub(super) fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: bool, ann: Annotation) -> Result<Vec<Handle>> {
let (Some(&end), Some(&before)) = (pts.last(), pts.len().checked_sub(2).and_then(|i| pts.get(i))) else { return Ok(Vec::new()) };
let z = sizes(s);
// The side the leader runs to: right unless its last segment runs left.
let dir = if end.x < before.x { -1.0 } else { 1.0 };
let mut vertices = pts.to_vec();
if let Annotation::Text(_) | Annotation::Copy(_) = ann {
if let Annotation::Text(_) | Annotation::Quick { .. } | Annotation::Copy(_) = ann {
let d = end - before;
// A copied text is centred on its line, and with DIMTAD on that line is above the leader:
// the leader ends half the text height lower.
@@ -310,6 +315,23 @@ fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: bool, ann: Ann
columns: None,
}))?)
}
Annotation::Quick { lines, width } => {
// The middle of the first line level with the end on the right, of the last line on
// the left, whatever DIMTAD.
let (attach, lift) = if dir > 0.0 { (1, z.text / 2.0) } else { (9, -z.text / 2.0) };
Some(s.add_entity(EntityKind::MText(MText {
insert: v3(end + Vec2::new(dir * z.gap, lift)),
height: z.text,
width,
attach,
rotation: 0.0,
style: z.text_style,
contents: lines.join("\\P"),
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
}))?)
}
Annotation::Copy(m) => {
let lift = if z.above { z.gap } else { 0.0 };
let attach = if dir > 0.0 { 4 } else { 6 };
+121
View File
@@ -0,0 +1,121 @@
//! QLEADER at the command line, as AutoCAD 2024 runs it with its default settings (accoreconsole,
//! synthetic drawings): up to three points, a text width, then lines of text.
//!
//! The leader is LEADER's, with an arrow and a hook line DIMASZ long when its last segment is more
//! than 15° off horizontal and text follows. The multiline text sits DIMGAP past the leader's end,
//! as wide as the width given: with the middle of its first line level with the end when the
//! leader runs right, and of its last line when it runs left, whatever DIMTAD. Enter at the first
//! line of text leaves the leader without text. The Settings dialog isn't available yet.
use serde_json::{Value, json};
use super::leader::{Annotation, add_leader};
use super::{Accept, Input, Interactive, Prompt, Result, Session, Step, Vec2, bad, points_param, str_param};
use crate::cmd::size_param;
/// QLEADER's default number of leader points.
const MAX_POINTS: usize = 3;
#[derive(Clone, Copy, Default, PartialEq)]
enum Ask {
#[default]
Points,
Width,
FirstLine,
NextLine,
}
#[derive(Default)]
pub(super) struct QLeaderM {
ask: Ask,
pts: Vec<Vec2>,
width: f64,
lines: Vec<String>,
}
impl Interactive for QLeaderM {
fn name(&self) -> &'static str {
"QLEADER"
}
fn prompt(&self, _s: &Session) -> Prompt {
let last = self.pts.last().copied();
match self.ask {
Ask::Points if self.pts.is_empty() => Prompt::new("Specify first leader point,", Accept::POINT).kw(&["Settings"]).default("Settings"),
Ask::Points => Prompt::new("Specify next point", Accept::POINT).base_opt(last),
// The width isn't remembered: AutoCAD 2024 offers 0 again after a width of 20.
Ask::Width => Prompt::new("Specify text width", Accept::POINT_OR_NUMBER).distance().default("0").base_opt(last),
Ask::FirstLine => Prompt::new("Enter first line of annotation text", Accept::TEXT).default("Mtext"),
Ask::NextLine => Prompt::new("Enter next line of annotation text", Accept::TEXT),
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
match self.ask {
Ask::Points => match i {
Input::Point(p) => {
self.pts.push(p);
if self.pts.len() == MAX_POINTS {
self.ask = Ask::Width;
}
}
Input::Enter | Input::Keyword(_) if self.pts.is_empty() => s.echo("The QLEADER Settings dialog is not available yet."),
// Enter after one point: no leader.
Input::Enter if self.pts.len() < 2 => return Ok(Step::Done),
Input::Enter => self.ask = Ask::Width,
_ => {}
},
Ask::Width => {
// A point gives the width as its distance from the leader's end; a negative
// width is none.
let width = match i {
Input::Point(p) => self.pts.last().map(|e| e.dist(p)),
Input::Text(t) => crate::units::parse_distance(&t),
Input::Enter => Some(0.0),
_ => return Ok(Step::Continue),
};
let finite = width.filter(|w| w.is_finite());
self.width = finite.ok_or_else(|| crate::EngineError::Other("Requires numeric distance or two points.".into()))?.max(0.0);
self.ask = Ask::FirstLine;
}
// Only typed text and Enter: a click in the drawing is no line of text, as at TEXT's.
Ask::FirstLine | Ask::NextLine => match i {
Input::Text(t) if !t.is_empty() => {
self.lines.push(t);
self.ask = Ask::NextLine;
}
Input::Text(_) | Input::Enter => {
let lines = std::mem::take(&mut self.lines);
let ann = if lines.is_empty() { Annotation::None } else { Annotation::Quick { lines, width: self.width } };
add_leader(s, &std::mem::take(&mut self.pts), false, true, ann)?;
return Ok(Step::Done);
}
_ => {}
},
}
Ok(Step::Continue)
}
}
/// QLEADER's JSON form: a leader through 2 or 3 `points`, with `text` (one line per line of it) as wide
/// as `width`, placed as the command line places them. The handles of the leader and its text.
pub(super) fn run_qleader(s: &mut Session, p: &Value) -> Result<Value> {
if p.get("points").is_none_or(Value::is_null) {
return Err(bad("qleader", "`points` is required"));
}
let pts = points_param(p, "points").ok_or_else(|| bad("qleader", "`points` must be a list of [x, y] points"))?;
if !(2..=MAX_POINTS).contains(&pts.len()) {
return Err(bad("qleader", "`points` takes 2 or 3 points"));
}
let width = size_param("qleader", p, "width", true)?.unwrap_or(0.0);
if p.get("text").is_some_and(|t| !t.is_null() && !t.is_string()) {
return Err(bad("qleader", "`text` must be a string"));
}
// Empty lines at the end are dropped, as the command line ends at one: a left-running leader
// would otherwise sit level with a blank last line. Text with nothing left is no text.
let mut lines: Vec<String> = str_param(p, "text").map(|t| t.lines().map(str::to_string).collect()).unwrap_or_default();
while lines.last().is_some_and(String::is_empty) {
lines.pop();
}
let ann = if lines.is_empty() { Annotation::None } else { Annotation::Quick { lines, width } };
let hs = add_leader(s, &pts, false, true, ann)?;
Ok(json!({ "handles": hs.iter().map(|h| h.hex()).collect::<Vec<_>>() }))
}
+4 -7
View File
@@ -3,7 +3,7 @@
use std::sync::Arc;
use cadcraft_doc::{Attrib, Block, Entity, EntityKind, Handle, Insert};
use cadcraft_doc::{Attrib, Block, Entity, EntityKind, Handle, Insert, TagKey};
use serde_json::{Value, json};
use crate::cmd::curves::KW;
@@ -102,17 +102,14 @@ impl Interactive for AttdispM {
/// Properties set on single attributes (layer, colour, …) go back to the definitions', as in AutoCAD.
pub(super) fn synced(blk: &Block, defs: &[&Attrib], ins: &Insert) -> Vec<Attrib> {
let m = ins.transform(blk.base.xy());
// The reference's attributes by tag, gathered once for all the definitions (#1923).
let carried = ins.attribs_by_tag();
defs.iter()
.map(|ad| {
let mut k = EntityKind::Text(ad.text.clone());
k.transform(&m);
let mut t = if let EntityKind::Text(t) = k { t } else { ad.text.clone() };
t.value = ins
.attribs
.iter()
.find(|a| a.tag.eq_ignore_ascii_case(&ad.tag))
.map(|a| a.text.value.clone())
.unwrap_or_else(|| ad.text.value.clone());
t.value = carried.get(&TagKey(&ad.tag)).map_or_else(|| ad.text.value.clone(), |a| a.text.value.clone());
Attrib {
tag: ad.tag.clone(),
text: t,
+8 -8
View File
@@ -2,7 +2,7 @@
//! become text with the values they show instead of the block's attribute definitions.
use cadcraft_color::Color;
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, Insert};
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, TagKey};
use serde_json::{Value, json};
use crate::cmd::machines::SelectRun;
@@ -28,22 +28,22 @@ fn run_burst(s: &mut Session, p: &Value) -> Result<Value> {
fn burst_pieces(d: &Drawing, e: &Entity) -> Option<Vec<Entity>> {
let EntityKind::Insert(ins) = &e.kind else { return None };
let mut out: Vec<Entity> = explode_kind(d, e)?.into_iter().filter(|p| !matches!(p.kind, EntityKind::AttDef(_))).collect();
// The block's definitions by tag, gathered once for all the attributes (#1923).
let defs = d.block(&ins.block).map(|b| b.attdefs_by_tag()).unwrap_or_default();
for a in ins.attribs.iter().filter(|a| !a.invisible) {
let kind = match a.multiline_text() {
Some(m) => EntityKind::MText(m),
None => EntityKind::Text(a.text.clone()),
};
out.push(Entity { handle: Handle(0), common: attrib_common(d, e, ins, &a.tag, &a.props), kind });
out.push(Entity { handle: Handle(0), common: attrib_common(e, defs.get(&TagKey(&a.tag)).copied(), &a.props), kind });
}
Some(out)
}
/// The properties an attribute is drawn with: its own, else its definition's; layer 0 is the
/// reference's layer and ByBlock colour the reference's colour, as EXPLODE gives the block's
/// objects.
fn attrib_common(d: &Drawing, e: &Entity, ins: &Insert, tag: &str, props: &cadcraft_doc::AttribProps) -> Common {
let def =
d.block(&ins.block).and_then(|b| b.entities.iter().find(|be| matches!(&be.kind, EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(tag))));
/// The properties an attribute is drawn with: its own, else those of its definition `def`; layer
/// 0 is the reference's layer and ByBlock colour the reference's colour, as EXPLODE gives the
/// block's objects.
fn attrib_common(e: &Entity, def: Option<&Entity>, props: &cadcraft_doc::AttribProps) -> Common {
// An attribute without a definition follows the reference.
let base = def.map(|de| de.common.clone()).unwrap_or_else(|| Common { color: Color::ByBlock, ..Common::default() });
let mut c = props.over(&base);
+52 -5
View File
@@ -5,7 +5,7 @@
use cadcraft_doc::color::Color;
use cadcraft_doc::dynblock::{self, GripPart, GripShape};
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, Lineweight, Transparency};
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, Lineweight, TagKey, Transparency};
use cadcraft_geom::Vec2;
use serde_json::{Value, json};
@@ -111,11 +111,10 @@ fn drawn(d: &Drawing, h: Handle) -> Vec<Entity> {
.collect();
// An attribute draws with its definition's properties, except those set on it.
let by_block = Common { layer: "0".into(), color: Color::ByBlock, linetype: "ByBlock".into(), lineweight: Lineweight::ByBlock, ..r.clone() };
// The block's definitions by tag, gathered once for all the attributes (#1923).
let defs = b.attdefs_by_tag();
out.extend(ins.attribs.iter().filter(|a| !a.invisible).map(|a| {
let def = b.entities.iter().find_map(|e| match &e.kind {
EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(&a.tag) => Some(&e.common),
_ => None,
});
let def = defs.get(&TagKey(&a.tag)).map(|e| &e.common);
let common = under(&a.props.over(def.unwrap_or(&by_block)), r);
let kind = match a.multiline_text() {
Some(m) => EntityKind::MText(m),
@@ -248,3 +247,51 @@ impl Session {
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn many_attributes_are_previewed_without_comparing_every_pair_with_the_definitions() {
// #1923: a reference with N attributes of a block with N definitions, the tags N long ones
// alike up to their last characters, no attribute's a definition's. Looking for each
// attribute's definition by comparing it with every one cost N x N comparisons of whole
// tags for each preview (many seconds here); the definitions gathered by tag once cost
// milliseconds.
const N: usize = 4000;
let tag = |kind: char, i: usize| format!("{}{kind}{i:05}", "T".repeat(1000));
let attrib = |tag: String| cadcraft_doc::Attrib {
tag,
text: cadcraft_doc::Text {
insert: cadcraft_geom::Vec3::ZERO,
align_pt: None,
height: 1.0,
value: "v".into(),
rotation: 0.0,
width_factor: 1.0,
oblique: 0.0,
style: "Standard".into(),
halign: Default::default(),
valign: Default::default(),
},
invisible: false,
constant: false,
prompt: String::new(),
props: Default::default(),
multiline: None,
modes: Default::default(),
};
let mut d = Drawing::new_metric();
let mut blk = cadcraft_doc::Block::new("B");
for (h, i) in (1..).zip(0..N) {
blk.entities.push(Entity::new(Handle(h), EntityKind::AttDef(attrib(tag('D', i)))));
}
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
let ins = cadcraft_doc::Insert { block: "B".into(), attribs: (0..N).map(|i| attrib(tag('A', i))).collect(), ..Default::default() };
let h = d.add(&cadcraft_doc::Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
let t = std::time::Instant::now();
assert_eq!(drawn(&d, h).len(), N);
assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed());
}
}
+376 -50
View File
@@ -129,80 +129,406 @@ pub(crate) fn join(s: &mut Session, hs: &[Handle]) -> Result<Option<Handle>> {
if hs.iter().any(|h| crate::cmd::curves::is_locked(s, *h)) {
return Err(EngineError::Other("An object is on a locked layer.".into()));
}
let hs = joinable_picks(s.doc()?, hs);
let hs = &hs[..];
if let Some(h) = join_on_source(s, hs)? {
return Ok(Some(h));
}
let d = s.doc()?;
let mut segs: Vec<Segment> = Vec::new();
// Source entity of each segment in `segs`, so only entities that end up in the chain are removed.
let mut owners: Vec<Handle> = Vec::new();
let mut common = None;
// Each object JOIN can take, as the pieces it is made of: a line or an arc is one piece, an
// open polyline its segments in order, each keeping its vertices, bulge and widths exactly.
// Each also with whether it faces down: an arc or a polyline whose normal points down Z
// (measured with 0,0,-1; a tilted one is taken the same way). A line faces up whatever its
// normal (AutoCAD 2024 joins one with normal 0,0,-1 to a polyline facing up, and no line to a
// polyline facing down; measured).
let mut units: Vec<(bool, Vec<Piece>)> = Vec::new();
let down = |e: &Entity| !matches!(e.kind, EntityKind::Line(_)) && e.common.extrusion.z < 0.0;
for h in hs {
let Some(e) = d.entity(*h) else { continue };
common.get_or_insert_with(|| e.common.clone());
match &e.kind {
EntityKind::Line(l) => segs.push(Segment::Line(Line::new(l.a.xy(), l.b.xy()))),
EntityKind::Arc(a) => segs.push(Segment::Arc { arc: Arc::new(a.center.xy(), a.radius, a.start, a.end), ccw: true }),
EntityKind::LwPolyline(p) if !p.closed => segs.extend(Polyline { vertices: p.vertices.clone(), closed: false }.segments()),
_ => {}
let piece =
|ends: (Vec2, Vec2), heights: (f64, f64), bulge: f64, widths: Option<(f64, f64)>| Piece { owner: *h, ends, heights, bulge, widths };
let unit: Vec<Piece> = match &e.kind {
// A line of no length joins as AutoCAD 2024 joins it, a repeated vertex.
EntityKind::Line(l) => vec![piece((l.a.xy(), l.b.xy()), (l.a.z, l.b.z), 0.0, None)],
EntityKind::Arc(a) => {
let arc = Arc::new(a.center.xy(), a.radius, a.start, a.end);
vec![piece((arc.start_point(), arc.end_point()), (a.center.z, a.center.z), cadcraft_geom::arc_to_bulge(arc.sweep()), None)]
}
// Repeated vertices included: AutoCAD 2024 keeps them.
EntityKind::LwPolyline(p) if !p.closed => {
// The elevation is along the polyline's normal: down Z for a mirrored one.
let z = if down(e) { -p.elevation } else { p.elevation };
p.vertices
.windows(2)
.map(|w| {
let widths = if p.const_width > 0.0 { (p.const_width, p.const_width) } else { (w[0].start_width, w[0].end_width) };
piece((w[0].p, w[1].p), (z, z), w[0].bulge, Some(widths))
})
.collect()
}
_ => Vec::new(),
};
if !unit.is_empty() {
units.push((down(e), unit));
}
owners.resize(segs.len(), *h);
}
if segs.len() < 2 {
if units.iter().map(|u| u.1.len()).sum::<usize>() < 2 {
return Err(EngineError::Other("Select at least two objects to join.".into()));
}
// Chain greedily from the first segment.
let mut chain = vec![segs.remove(0)];
let mut used = vec![owners.remove(0)];
// An object facing the other way from a polyline source stays out (AutoCAD 2024, measured: one
// facing up takes no arc facing down, and one facing down no arc or polyline facing up). Onto a
// line or an arc it wasn't measured (the core console's JOIN takes only collinear lines or arcs
// on one circle onto those), so objects facing either way still join there.
let polyline_source = units.first().filter(|u| u.1.first().is_some_and(|p| p.widths.is_some())).map(|u| u.0);
let units: Vec<Vec<Piece>> = units.into_iter().filter(|u| polyline_source.is_none_or(|down| u.0 == down)).map(|u| u.1).collect();
// A new polyline takes the source's properties.
let first = units.first().and_then(|u| u.first()).map(|p| p.owner);
let common = first.and_then(|h| d.entity(h)).map(|e| e.common.clone());
let tol = 1e-6;
loop {
let start = chain.first().map(Segment::start).unwrap_or_default();
let end = chain.last().map(Segment::end).unwrap_or_default();
let Some(i) =
segs.iter().position(|s| s.start().near(end, tol) || s.end().near(end, tol) || s.start().near(start, tol) || s.end().near(start, tol))
else {
break;
};
let s0 = segs.remove(i);
used.push(owners.remove(i));
if s0.start().near(end, tol) {
chain.push(s0);
} else if s0.end().near(end, tol) {
chain.push(s0.reversed());
} else if s0.end().near(start, tol) {
chain.insert(0, s0);
} else {
chain.insert(0, s0.reversed());
}
}
if chain.len() < 2 {
let links = chain_units(units, tol);
// One object alone joins nothing, even a polyline whose ends meet: AutoCAD 2024 leaves it open
// ("0 segments added to polyline").
let closed = links.first().zip(links.last()).is_some_and(|(a, b)| meet(a.start(), b.end(), tol));
let one_object = links.first().is_some_and(|f| links.iter().all(|l| l.owner == f.owner));
if links.len() < 2 || one_object {
return Err(EngineError::Other("Objects are not connected.".into()));
}
let closed = chain.first().zip(chain.last()).is_some_and(|(a, b)| a.start().near(b.end(), tol));
let mut vs: Vec<PolyVertex> = chain
let used = |h: &Handle| links.iter().any(|l| l.owner == *h);
// A polyline's own segments keep their widths.
let mut vs: Vec<PolyVertex> = links
.iter()
.map(|s| PolyVertex {
p: s.start(),
bulge: match s {
Segment::Line(_) => 0.0,
Segment::Arc { arc, ccw } => cadcraft_geom::arc_to_bulge(if *ccw { arc.sweep() } else { -arc.sweep() }),
},
..Default::default()
.map(|l| {
let (start_width, end_width) = l.widths.unwrap_or_default();
PolyVertex { p: l.ends.0, bulge: l.bulge, start_width, end_width }
})
.collect();
if !closed && let Some(l) = chain.last() {
vs.push(PolyVertex::new(l.end()));
if !closed && let Some(l) = links.last() {
vs.push(PolyVertex::new(l.ends.1));
}
let space = s.space();
// A new polyline goes in the source's space, whichever space is current.
let space = first.and_then(|h| d.space_of(h)).unwrap_or_else(|| s.space());
let doc = s.doc_mut()?;
for h in hs.iter().filter(|h| used.contains(*h)) {
// A polyline source takes the other pieces and keeps its handle (AutoCAD 2024: "1 segments
// added to polyline").
if let Some(src) = first
&& let Some(EntityKind::LwPolyline(sp)) = doc.entity(src).map(|e| &e.kind)
&& let Some(onto) = onto_polyline(sp, src, &links, closed)
{
for h in hs.iter().filter(|h| **h != src && used(h)) {
doc.remove_entity(*h);
}
doc.modify_entity(src, |e| e.kind = EntityKind::LwPolyline(onto))?;
s.set_selection(Vec::new());
return Ok(Some(src));
}
for h in hs.iter().filter(|h| used(h)) {
doc.remove_entity(*h);
}
// A new polyline stays at the source's height, as a polyline source keeps its elevation. The
// elevation runs along its normal: negated for one facing down. Not measured: the core
// console's JOIN makes no new polyline.
let height = links.iter().find(|l| Some(l.owner) == first).map_or(0.0, |l| l.heights.0);
let common = common.unwrap_or_default();
let elevation = if common.extrusion.z < 0.0 { -height } else { height };
let mut kind = lwpoly(vs, closed);
if let EntityKind::LwPolyline(p) = &mut kind {
p.elevation = elevation;
}
let nh = doc.new_handle();
if let Some(st) = doc.space_mut(&space) {
st.push(Entity { handle: nh, common: common.unwrap_or_default(), kind: lwpoly(vs, closed) });
st.push(Entity { handle: nh, common, kind });
}
s.set_selection(Vec::new());
Ok(Some(nh))
}
/// The picks JOIN can take, each once, in the order picked: lines, arcs and open polylines. The
/// first of them is the source (AutoCAD 2024 passes over a circle picked first and leaves it).
fn joinable_picks(d: &cadcraft_doc::Drawing, hs: &[Handle]) -> Vec<Handle> {
let mut seen = std::collections::HashSet::new();
let joinable = |h: &Handle| {
d.entity(*h).is_some_and(|e| match &e.kind {
EntityKind::Line(_) => true,
EntityKind::Arc(a) => a.radius > cadcraft_geom::EPS,
EntityKind::LwPolyline(p) => !p.closed,
_ => false,
})
};
hs.iter().copied().filter(|h| joinable(h) && seen.insert(*h)).collect()
}
/// Whether JOIN would make the picked arcs a circle. AutoCAD 2024 asks first ("Combined arc
/// segments form a circle. Convert to circle? [Yes/No] <Yes>:"), and No leaves every arc as it
/// is (measured).
pub(crate) fn join_makes_circle(s: &Session, hs: &[Handle]) -> bool {
let Ok(d) = s.doc() else { return false };
// Elliptical arcs and splines join another way, and a locked object stops the join.
let other_way = |h: &Handle| d.entity(*h).is_some_and(|e| matches!(e.kind, EntityKind::Ellipse(_) | EntityKind::Spline(_)));
if hs.iter().any(|h| other_way(h) || crate::cmd::curves::is_locked(s, *h)) {
return false;
}
let picks = joinable_picks(d, hs);
let arcs: Vec<&cadcraft_doc::Arc> = picks
.iter()
.filter_map(|h| match d.entity(*h).map(|e| &e.kind) {
Some(EntityKind::Arc(a)) => Some(a),
_ => None,
})
.collect();
let tol = 1e-6;
match &arcs[..] {
[g, rest @ ..] if !rest.is_empty() && arcs.len() == picks.len() => arc_reach(g, rest, tol).is_some_and(|far| far > cadcraft_geom::TAU - tol),
_ => false,
}
}
/// How far round the source arc `g`'s circle, counterclockwise from its start, it and the
/// `others` reach; `None` when one of them isn't on that circle (less than `tol` off its centre
/// and radius). An arc that starts even a hair before the source's start reaches on round past
/// it: AutoCAD 2024 makes a circle of 7°-100° and an arc stored from 7° less 5e-16 rad, and
/// leaves 7°-100° with one from exactly 7° or 5e-7 rad after it.
fn arc_reach(g: &cadcraft_doc::Arc, others: &[&cadcraft_doc::Arc], tol: f64) -> Option<f64> {
let same_circle =
|o: &cadcraft_doc::Arc| o.center.xy().dist(g.center.xy()) < tol && (o.radius - g.radius).abs() < tol && (o.center.z - g.center.z).abs() < tol;
let reach = |o: &cadcraft_doc::Arc| norm_angle(o.start - g.start) + cadcraft_geom::ccw_sweep(o.start, o.end);
others.iter().all(|o| same_circle(o)).then(|| others.iter().map(|o| reach(o)).fold(reach(g), f64::max))
}
/// The chain JOIN builds from the first object: each next object with an end on one of the
/// chain's ends joins whole, turned round where needed, as AutoCAD 2024 joins them, until a join
/// closes the chain; one that the chain meets only at an inner vertex of a polyline stays out.
/// Ends are compared at the objects' own end points, not ones worked out again from arcs, and at
/// their heights.
fn chain_units(mut units: Vec<Vec<Piece>>, tol: f64) -> Vec<Piece> {
let ends = |u: &[Piece]| u.first().zip(u.last()).map(|(a, b)| (a.start(), b.end()));
let near = |p, q| meet(p, q, tol);
if units.is_empty() {
return Vec::new();
}
// A source that already ends where it starts still takes more, unless it has no length at all
// (AutoCAD 2024, measured with a polyline that ends where it starts and with a line of no
// length).
let mut chain: std::collections::VecDeque<Piece> = units.remove(0).into();
if chain.iter().all(|p| p.ends.0.near(p.ends.1, tol)) {
return chain.into();
}
while let (Some(start), Some(end)) = (chain.front().map(Piece::start), chain.back().map(Piece::end)) {
let meets = |u: &Vec<Piece>| ends(u).is_some_and(|(a, b)| near(a, end) || near(b, end) || near(a, start) || near(b, start));
let Some(i) = units.iter().position(meets) else { break };
let unit = units.remove(i);
let Some((a, b)) = ends(&unit) else { break };
// Where an object that meets the chain at more than one place goes, as AutoCAD 2024 puts
// it (measured): a polyline by its first vertex if it can, and before the chain rather
// than after it; a line or an arc turned round if it can, its end on the chain's end
// before its start on the chain's start.
let polyline = unit.first().is_some_and(|p| p.widths.is_some());
let (before, turned) = if polyline {
if near(a, start) {
(true, true)
} else if near(a, end) {
(false, false)
} else {
(near(b, start), !near(b, start))
}
} else if near(b, end) {
(false, true)
} else if near(a, start) {
(true, true)
} else {
(!near(a, end), false)
};
match (before, turned) {
(false, false) => chain.extend(unit),
(false, true) => chain.extend(unit.into_iter().rev().map(Piece::flipped)),
(true, false) => unit.into_iter().rev().for_each(|p| chain.push_front(p)),
(true, true) => unit.into_iter().for_each(|p| chain.push_front(p.flipped())),
}
// A chain that a join closes takes nothing more.
if chain.front().zip(chain.back()).is_some_and(|(f, l)| near(f.start(), l.end())) {
break;
}
}
chain.into()
}
/// A segment in the chain JOIN builds: the object it came from, its end points as the object has
/// them (turned round when it runs backwards in the chain) and their world heights (a line's own
/// Z, an arc's centre Z, a polyline's elevation, negated for one facing down), its bulge and, for a
/// polyline's own segment, its widths.
#[derive(Clone, Copy)]
struct Piece {
owner: Handle,
ends: (Vec2, Vec2),
heights: (f64, f64),
bulge: f64,
widths: Option<(f64, f64)>,
}
impl Piece {
fn flipped(self) -> Self {
Piece {
ends: (self.ends.1, self.ends.0),
heights: (self.heights.1, self.heights.0),
bulge: -self.bulge,
widths: self.widths.map(|(a, b)| (b, a)),
..self
}
}
fn start(&self) -> (Vec2, f64) {
(self.ends.0, self.heights.0)
}
fn end(&self) -> (Vec2, f64) {
(self.ends.1, self.heights.1)
}
}
/// Whether two ends meet: in plan and at the same height. AutoCAD 2024 leaves an end that meets
/// another only in plan apart (measured: a line or a polyline at 0 and a line at 5, or a polyline
/// at 5 and a line at 0, end to end in plan, stay as they are).
fn meet(p: (Vec2, f64), q: (Vec2, f64), tol: f64) -> bool {
p.0.near(q.0, tol) && (p.1 - q.1).abs() < tol
}
/// The open polyline `sp` (handle `src`) with the chain's other pieces added before and after
/// it, as AutoCAD 2024 JOIN makes it (measured with `entget`): its own vertices stay exactly as
/// they are, and so do its elevation, linetype generation and, when only lines and arcs join,
/// its constant width; another polyline's segments keep their bulges and widths; a line or arc
/// takes the widths of the source's vertex at the end it joins (first or last); and when another
/// polyline joins, the end vertex's widths are cleared.
///
/// `None` when the source's segments aren't one run of the chain (they always are: the chain
/// starts from the source and takes its segments in order).
fn onto_polyline(sp: &cadcraft_doc::LwPolyline, src: Handle, links: &[Piece], closed: bool) -> Option<cadcraft_doc::LwPolyline> {
let run: Vec<usize> = (0..links.len()).filter(|i| links[*i].owner == src).collect();
let (&first, &last) = (run.first()?, run.last()?);
if sp.closed || run.len() != last - first + 1 {
return None;
}
let other_polyline = links.iter().any(|l| l.owner != src && l.widths.is_some());
let mut own = sp.vertices.clone();
if other_polyline && sp.const_width > 0.0 {
// The constant width goes, so spell it out on the source's own segments.
for v in &mut own {
(v.start_width, v.end_width) = (sp.const_width, sp.const_width);
}
}
let widths = |v: &PolyVertex| (v.start_width, v.end_width);
let (head, tail) = (widths(own.first()?), widths(own.last()?));
let vertex = |i: usize, fill: (f64, f64)| {
let (start_width, end_width) = links[i].widths.unwrap_or(fill);
PolyVertex { p: links[i].ends.0, bulge: links[i].bulge, start_width, end_width }
};
let mut vs: Vec<PolyVertex> = (0..first).map(|i| vertex(i, head)).collect();
vs.extend(own);
if last + 1 < links.len() {
// The source's end vertex starts the first piece after it.
let v = vertex(last + 1, tail);
if let Some(end) = vs.last_mut() {
(end.bulge, end.start_width, end.end_width) = (v.bulge, v.start_width, v.end_width);
}
vs.extend((last + 2..links.len()).map(|i| vertex(i, tail)));
vs.push(PolyVertex { p: links.last()?.ends.1, start_width: tail.0, end_width: tail.1, ..Default::default() });
}
if other_polyline && let Some(end) = vs.last_mut() {
(end.start_width, end.end_width) = (0.0, 0.0);
}
if closed {
// The last vertex is the first one again.
vs.pop();
}
Some(cadcraft_doc::LwPolyline { vertices: vs, closed, const_width: if other_polyline { 0.0 } else { sp.const_width }, ..sp.clone() })
}
/// JOIN onto the first object (the source) as AutoCAD 2024 does when the others all lie on its
/// line or its circle: gaps and overlaps are bridged and the source keeps its handle.
///
/// - Lines on the source's line make one line, from the source's start end to the farthest
/// point the way it runs (and back past its start if one reaches behind it).
/// - Arcs on the source's circle join counterclockwise from the source's start to the farthest
/// end; arcs that reach all the way round make a circle, a new object in their place.
///
/// `None` when the objects aren't all of one of those kinds.
fn join_on_source(s: &mut Session, hs: &[Handle]) -> Result<Option<Handle>> {
let d = s.doc()?;
let ents: Vec<std::sync::Arc<Entity>> = hs.iter().filter_map(|h| d.entity(*h).cloned()).collect();
let [src, rest @ ..] = &ents[..] else { return Ok(None) };
if rest.is_empty() || ents.len() != hs.len() {
return Ok(None);
}
// AutoCAD 2024 takes lines less than 1e-6 off the source's line, and arcs less than 1e-6
// off its centre and radius, at any size of coordinates (measured at 0, 1000 and 2.4e6), and
// makes a circle of arcs that come round to less than 1e-6 radians from the source's start.
let tol = 1e-6;
let kind = match &src.kind {
EntityKind::Line(l) => {
let (a, b) = (l.a.xy(), l.b.xy());
let len = a.dist(b);
let lines: Vec<&cadcraft_doc::Line> = rest
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Line(o) => Some(o),
_ => None,
})
.collect();
let level = |z: f64| (z - l.a.z).abs() < tol;
if lines.len() != rest.len() || len <= 0.0 || !level(l.b.z) || !lines.iter().all(|o| level(o.a.z) && level(o.b.z)) {
return Ok(None);
}
let u = (b - a) * (1.0 / len);
let on_line = |p: Vec2| (p - a).cross(u).abs() < tol;
if !lines.iter().all(|o| on_line(o.a.xy()) && on_line(o.b.xy())) {
return Ok(None);
}
let ts = lines.iter().flat_map(|o| [o.a.xy(), o.b.xy()]).map(|p| (p - a).dot(u)).chain([0.0, len]);
let (t0, t1) = ts.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), t| (lo.min(t), hi.max(t)));
let at = |t: f64| (a + u * t).to3(l.a.z);
EntityKind::Line(cadcraft_doc::Line { a: at(t0), b: if t1 == len { l.b } else { at(t1) } })
}
EntityKind::Arc(g) => {
let arcs: Vec<&cadcraft_doc::Arc> = rest
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Arc(o) => Some(o),
_ => None,
})
.collect();
let Some(far) = arc_reach(g, &arcs, tol).filter(|_| arcs.len() == rest.len()) else { return Ok(None) };
if far > cadcraft_geom::TAU - tol {
let circle = Entity {
handle: Handle(0),
common: src.common.clone(),
kind: EntityKind::Circle(cadcraft_doc::Circle { center: g.center, radius: g.radius }),
};
// In the source's space, whichever space is current.
let space = d.space_of(src.handle).unwrap_or_else(|| s.space());
let doc = s.doc_mut()?;
for h in hs {
doc.remove_entity(*h);
}
let nh = doc.new_handle();
if let Some(st) = doc.space_mut(&space) {
st.push(Entity { handle: nh, ..circle });
}
s.set_selection(Vec::new());
return Ok(Some(nh));
}
let end = if far > cadcraft_geom::ccw_sweep(g.start, g.end) { norm_angle(g.start + far) } else { g.end };
EntityKind::Arc(cadcraft_doc::Arc { end, ..g.clone() })
}
_ => return Ok(None),
};
let src_h = src.handle;
let doc = s.doc_mut()?;
for h in hs.iter().filter(|h| **h != src_h) {
doc.remove_entity(*h);
}
doc.modify_entity(src_h, |e| e.kind = kind)?;
s.set_selection(Vec::new());
Ok(Some(src_h))
}
pub(super) fn run_join(s: &mut Session, p: &Value) -> Result<Value> {
let hs = targets(s, p)?;
if p.get("close").and_then(Value::as_bool) == Some(true) {
+28 -2
View File
@@ -1,4 +1,4 @@
use super::break_join::join;
use super::break_join::{join, join_makes_circle};
use super::explode::explode;
use super::transform::{at_elevation, erase, scale_entities, transform_entities};
use super::{
@@ -40,6 +40,8 @@ pub(super) struct SelectThen {
ask_erase: bool,
/// JOIN of a single arc or elliptical arc: the prompt asks for arcs to join to it, or cLose.
join_source: Option<Handle>,
/// JOIN of arcs that make a circle: asking whether to.
ask_circle: bool,
}
impl SelectThen {
@@ -57,6 +59,7 @@ impl SelectThen {
copy_mode: false,
ask_erase: false,
join_source: None,
ask_circle: false,
}
}
fn apply(&mut self, s: &mut Session) -> Result<Step> {
@@ -84,8 +87,17 @@ impl SelectThen {
}
}
/// JOIN the selected objects and report what they became.
/// JOIN the selected objects and report what they became. Arcs that make a circle ask first,
/// as AutoCAD 2024 does.
fn join_now(&mut self, s: &mut Session) -> Result<Step> {
if join_makes_circle(s, &self.objs) {
self.ask_circle = true;
return Ok(Step::Continue);
}
self.join_apply(s)
}
fn join_apply(&mut self, s: &mut Session) -> Result<Step> {
match join(s, &self.objs) {
Ok(h) => {
// Objects outside the joined chain are kept, so count only the ones JOIN consumed
@@ -95,6 +107,9 @@ impl SelectThen {
let what = match h.and_then(|h| d.entity(h)).map(|e| &e.kind) {
Some(EntityKind::Spline(_)) => "spline",
Some(EntityKind::Ellipse(_)) => "ellipse",
Some(EntityKind::Line(_)) => "line",
Some(EntityKind::Arc(_)) => "arc",
Some(EntityKind::Circle(_)) => "circle",
_ => "polyline",
};
s.echo(format!("{n} objects joined into 1 {what}"))
@@ -308,6 +323,9 @@ impl Interactive for SelectThen {
if self.ask_erase {
return Prompt::new("Erase source objects?", Accept::TEXT).kw(&["Yes", "No"]).default("No");
}
if self.ask_circle {
return Prompt::new("Combined arc segments form a circle. Convert to circle?", crate::cmd::curves::KW).kw(&["Yes", "No"]).default("Yes");
}
if let Some(src) = self.join_source {
let ellipse = s.doc().is_ok_and(|d| matches!(d.entity(src).map(|e| &e.kind), Some(EntityKind::Ellipse(_))));
let msg = if ellipse { "Select elliptical arcs to join to source" } else { "Select arcs to join to source" };
@@ -361,6 +379,14 @@ impl Interactive for SelectThen {
}
}
}
// No leaves every arc as it is (AutoCAD 2024, measured).
if self.ask_circle {
return match &i {
Input::Keyword(k) if k == "No" => Ok(Step::Done),
Input::Keyword(_) | Input::Enter => self.join_apply(s),
_ => Err(EngineError::Other("Invalid option keyword.".into())),
};
}
if let Some(src) = self.join_source {
return self.join_source_input(s, src, i);
}
+43 -1
View File
@@ -4,7 +4,8 @@
use cadcraft_doc::{Common, Entity, EntityKind, Handle, LwPolyline, MAX_BLOCK_DEPTH, Space};
use cadcraft_geom::{
Arc, Ellipse, Line, Mat3, PolyVertex, Polyline, Segment, Spline, TAU, Vec2, ccw_sweep, intersect_ext, line_circle, line_line_infinite, norm_angle,
Arc, Ellipse, Line, Mat3, PolyVertex, Polyline, Segment, Spline, TAU, Vec2, Vec3, ccw_sweep, intersect_ext, line_circle, line_line_infinite,
norm_angle,
};
use serde_json::{Value, json};
@@ -122,6 +123,47 @@ pub(crate) fn as_lwpoly(k: &EntityKind) -> Option<LwPolyline> {
}
}
/// The polyline PEDIT turns a line or an arc into, and the normal it faces, as AutoCAD 2024 makes
/// them (measured): facing the way the arc faces, and up for a line whatever its normal; at the
/// line's height, or at the arc's centre height measured along its normal (a mirrored arc whose
/// centre is at world Z -5 gives elevation 5, one at Z 5 elevation -5); the thickness stays the
/// object's. A sloped line still comes out at elevation 0: AutoCAD makes a polyline in the line's
/// vertical plane, which a CADCraft polyline can't be. An arc in a tilted plane (normal neither up
/// nor down Z), which CADCraft keeps only approximately, keeps its normal and goes by the sign of
/// its Z as above; AutoCAD's result for one isn't measured. A polyline is returned as it is.
pub(crate) fn polyline_of(e: &Entity) -> Option<(LwPolyline, Vec3)> {
let mut pl = as_lwpoly(&e.kind)?;
let normal = e.common.extrusion;
match &e.kind {
EntityKind::Line(l) => {
if (l.a.z - l.b.z).abs() < 1e-9 {
pl.elevation = l.a.z;
}
Some((pl, Vec3::Z))
}
// The arc's centre is in world coordinates; a polyline's elevation runs along its normal.
// A mirrored arc runs clockwise in plan, and so does its polyline (AutoCAD 2024 starts it
// at the arc's start in the arc's own coordinates).
EntityKind::Arc(a) => {
pl.elevation = if normal.z < 0.0 { -a.center.z } else { a.center.z };
if normal.z < 0.0 {
pl.vertices = curves::reverse_vertices(&pl.vertices, false);
}
Some((pl, normal))
}
_ => Some((pl, normal)),
}
}
/// Puts the polyline `pl`, facing `normal`, in place of the object `h`.
fn set_polyline(s: &mut Session, h: Handle, pl: LwPolyline, normal: Vec3) -> Result<()> {
s.doc_mut()?.modify_entity(h, |e| {
e.kind = EntityKind::LwPolyline(pl);
e.common.extrusion = normal;
})?;
Ok(())
}
mod pedit_multi;
mod pedit_vertex;
+99 -29
View File
@@ -1,7 +1,7 @@
use super::{
Accept, Chain, EntityKind, Handle, Input, Interactive, LwPolyline, MAX_GEN, PolyVertex, Prompt, Result, SelOutcome, SelectPhase, Session, Spline,
Step, Value, Vec2, as_lwpoly, bad, bool_or, curves, f64_or, f64_req, json, line, number, other, pedit_vertex, point_req, set_kind, str_param,
targets,
Accept, Chain, Entity, EntityKind, Handle, Input, Interactive, LwPolyline, MAX_GEN, PolyVertex, Prompt, Result, SelOutcome, SelectPhase, Session,
Spline, Step, Value, Vec2, Vec3, as_lwpoly, bad, bool_or, curves, f64_or, f64_req, json, line, number, other, pedit_vertex, point_req,
polyline_of, set_kind, set_polyline, str_param, targets,
};
/// Fit curve: a tangent-continuous pair of arcs (biarc) per segment through every vertex,
@@ -106,7 +106,21 @@ pub(crate) fn spline_vertices(vs: &[PolyVertex], closed: bool, segs: usize) -> V
}
/// Join connected lines/arcs/open polylines onto the ends of polyline `h` (kept in place).
pub(crate) fn pedit_join(s: &mut Session, h: Handle, others: &[Handle], fuzz: f64) -> Result<usize> {
///
/// As AutoCAD 2024 joins (measured), none facing the other way: an arc or a polyline whose normal
/// points down Z where the polyline's points up, or the other way round; a line counts as facing
/// up. Multiple's Join (`same_height` false) takes them at any height (lines at Z 5 and Z 0 join).
///
/// PEDIT's own Join takes only objects in one plane with the polyline: the plane the polyline and
/// every line picked share, when they share one, else the polyline's own. So a sloped line joins
/// only when the polyline and all the lines picked lie in one plane (a vertical one for a sloped
/// line continuing a straight polyline in plan), and then no arc or polyline joins, as those lie
/// flat; otherwise only objects at the polyline's height join (a line, arc or polyline at Z 0
/// stays off one at Z 5). Ends meet within `fuzz` in plan and within 1e-6 in height, which `fuzz`
/// doesn't widen. After a sloped line the chain's end is at the line's far end, so the next object
/// meets it there; AutoCAD's polyline then lies in the lines' plane, CADCraft's keeps the source's
/// elevation and runs through the objects' points seen from above.
pub(crate) fn pedit_join(s: &mut Session, h: Handle, others: &[Handle], fuzz: f64, same_height: bool) -> Result<usize> {
let e = curves::entity(s, h)?;
let mut base = as_lwpoly(&e.kind).ok_or_else(|| other("Select a polyline."))?;
if base.closed {
@@ -114,46 +128,88 @@ pub(crate) fn pedit_join(s: &mut Session, h: Handle, others: &[Handle], fuzz: f6
}
let mut chain = Chain::of(&EntityKind::LwPolyline(base.clone())).unwrap_or_default();
let tol = fuzz.max(1e-6);
let mut pool: Vec<(Handle, Chain)> = Vec::new();
for o in others {
if *o == h {
// Which way an object faces, and its two ends' world heights.
let down = |e: &Entity| !matches!(e.kind, EntityKind::Line(_)) && e.common.extrusion.z < 0.0;
let heights = |e: &Entity| match &e.kind {
EntityKind::Line(l) => (l.a.z, l.b.z),
// An arc's centre is in world coordinates.
EntityKind::Arc(a) => (a.center.z, a.center.z),
// A polyline's elevation runs along its normal.
EntityKind::LwPolyline(p) => {
let z = if down(e) { -p.elevation } else { p.elevation };
(z, z)
}
_ => (0.0, 0.0),
};
// Two ends meet: in plan within the fuzz distance, and for PEDIT's own Join at the same height.
let at = |p: Vec2, ph: f64, q: Vec2, qh: f64| p.near(q, tol) && (!same_height || (ph - qh).abs() < 1e-6);
let picked: Vec<(Handle, Entity)> = others.iter().filter(|o| **o != h).filter_map(|o| Some((*o, curves::entity(s, *o).ok()?))).collect();
// The plane PEDIT's own Join works in (AutoCAD 2024, measured): the polyline's points, with a
// point off the chord of an arc segment, which lies flat, and the ends of every line picked.
let z0 = heights(&e).0;
let mut pts: Vec<Vec3> = base.vertices.iter().map(|v| Vec3::new(v.p.x, v.p.y, z0)).collect();
if let Some(w) = base.vertices.windows(2).find(|w| w[0].bulge.abs() > 1e-12) {
let (a, b) = (w[0].p, w[1].p);
let off = (a + b) * 0.5 + Vec2::new(a.y - b.y, b.x - a.x);
pts.push(Vec3::new(off.x, off.y, z0));
}
let lines: Vec<(Vec3, Vec3)> =
picked.iter().filter_map(|(_, oe)| if let EntityKind::Line(l) = &oe.kind { Some((l.a, l.b)) } else { None }).collect();
pts.extend(lines.iter().flat_map(|(a, b)| [*a, *b]));
let shared = coplanar(&pts);
// That plane is the polyline's own, flat, when every line is at its height.
let level = lines.iter().all(|(a, b)| (a.z - z0).abs() < 1e-6 && (b.z - z0).abs() < 1e-6);
let mut pool: Vec<(Handle, Chain, (f64, f64))> = Vec::new();
for (o, oe) in &picked {
if down(oe) != down(&e) {
continue;
}
let Ok(oe) = curves::entity(s, *o) else { continue };
let ok = matches!(&oe.kind, EntityKind::Line(_) | EntityKind::Arc(_)) || matches!(&oe.kind, EntityKind::LwPolyline(p) if !p.closed);
let line = matches!(oe.kind, EntityKind::Line(_));
let (ah, bh) = heights(oe);
// A sloped line lies in no flat plane, and an arc or a polyline in no other.
let off_plane = if shared && !level { !line } else { (ah - bh).abs() >= 1e-6 };
if same_height && off_plane {
continue;
}
let ok = line || matches!(&oe.kind, EntityKind::Arc(_)) || matches!(&oe.kind, EntityKind::LwPolyline(p) if !p.closed);
if ok && let Some(c) = Chain::of(&oe.kind) {
pool.push((*o, c));
pool.push((*o, c, (ah, bh)));
}
}
let (mut st_h, mut en_h) = heights(&e);
let mut joined = Vec::new();
while let (Some(st), Some(en)) = (chain.start(), chain.end()) {
let Some(i) = pool
.iter()
.position(|(_, c)| c.start().zip(c.end()).is_some_and(|(a, b)| a.near(en, tol) || b.near(en, tol) || a.near(st, tol) || b.near(st, tol)))
else {
let meets = |c: &Chain, (ah, bh): (f64, f64)| {
c.start().zip(c.end()).is_some_and(|(a, b)| at(a, ah, en, en_h) || at(b, bh, en, en_h) || at(a, ah, st, st_h) || at(b, bh, st, st_h))
};
let Some(i) = pool.iter().position(|(_, c, z)| meets(c, *z)) else {
break;
};
let (oh, c) = pool.remove(i);
let (oh, c, (ah, bh)) = pool.remove(i);
let (Some(a), Some(b)) = (c.start(), c.end()) else { continue };
if a.near(en, tol) {
if at(a, ah, en, en_h) {
chain.segs.extend(c.segs);
} else if b.near(en, tol) {
en_h = bh;
} else if at(b, bh, en, en_h) {
chain.segs.extend(c.reversed().segs);
} else if b.near(st, tol) {
en_h = ah;
} else if at(b, bh, st, st_h) {
let mut v = c.segs;
v.extend(chain.segs);
chain.segs = v;
st_h = ah;
} else {
let mut v = c.reversed().segs;
v.extend(chain.segs);
chain.segs = v;
st_h = bh;
}
joined.push(oh);
}
if joined.is_empty() {
return Ok(0);
}
chain.closed = chain.start().zip(chain.end()).is_some_and(|(a, b)| a.near(b, tol)) && chain.segs.len() > 1;
chain.closed = chain.start().zip(chain.end()).is_some_and(|(a, b)| at(a, st_h, b, en_h)) && chain.segs.len() > 1;
base.vertices = chain.vertices();
base.closed = chain.closed;
let d = s.doc_mut()?;
@@ -164,14 +220,29 @@ pub(crate) fn pedit_join(s: &mut Session, h: Handle, others: &[Handle], fuzz: f6
Ok(joined.len())
}
/// Whether the points `pts` lie in one plane, to within 1e-6 (points in a line always do).
fn coplanar(pts: &[Vec3]) -> bool {
let Some(&p0) = pts.first() else { return true };
let far = |a: &&Vec3, b: &&Vec3| (**a - p0).len().total_cmp(&(**b - p0).len());
let Some(&p1) = pts.iter().max_by(far) else { return true };
let d = p1 - p0;
// The normal from the point farthest off the line p0 p1, for the least rounding.
let Some(n) = pts.iter().map(|p| d.cross(*p - p0)).max_by(|a, b| a.len().total_cmp(&b.len())) else { return true };
if n.len() <= 1e-6 * d.len() {
return true;
}
let n = n.normalized();
pts.iter().all(|p| n.dot(*p - p0).abs() < 1e-6)
}
pub(super) fn pedit_apply(s: &mut Session, h: Handle, opt: &str, p: &Value) -> Result<Value> {
let e = curves::entity(s, h)?;
if curves::is_locked(s, h) {
return Err(other("The object is on a locked layer."));
}
let mut pl = match &e.kind {
EntityKind::LwPolyline(pl) => pl.clone(),
EntityKind::Line(_) | EntityKind::Arc(_) if bool_or(p, "convert", true) => as_lwpoly(&e.kind).ok_or_else(|| other("Cannot convert."))?,
let (mut pl, normal) = match &e.kind {
EntityKind::LwPolyline(pl) => (pl.clone(), e.common.extrusion),
EntityKind::Line(_) | EntityKind::Arc(_) if bool_or(p, "convert", true) => polyline_of(&e).ok_or_else(|| other("Cannot convert."))?,
_ => return Err(other("Object selected is not a polyline.")),
};
match opt {
@@ -197,14 +268,14 @@ pub(super) fn pedit_apply(s: &mut Session, h: Handle, opt: &str, p: &Value) -> R
"reverse" | "r" => pl.vertices = curves::reverse_vertices(&pl.vertices, pl.closed),
"ltypegen" | "l" => pl.plinegen = bool_or(p, "on", !pl.plinegen),
"join" | "j" => {
set_kind(s, h, EntityKind::LwPolyline(pl))?;
set_polyline(s, h, pl, normal)?;
let others: Vec<Handle> = p
.get("handles2")
.or_else(|| p.get("join"))
.and_then(Value::as_array)
.map(|a| a.iter().filter_map(curves::handle_value).collect())
.unwrap_or_default();
let n = pedit_join(s, h, &others, f64_or(p, "fuzz", 0.0))?;
let n = pedit_join(s, h, &others, f64_or(p, "fuzz", 0.0), true)?;
return Ok(json!({ "handle": h.hex(), "joined": n }));
}
"vertex" | "e" => {
@@ -254,7 +325,7 @@ pub(super) fn pedit_apply(s: &mut Session, h: Handle, opt: &str, p: &Value) -> R
}
_ => return Err(bad("pedit", "unknown option")),
}
set_kind(s, h, EntityKind::LwPolyline(pl))?;
set_polyline(s, h, pl, normal)?;
Ok(json!({ "handle": h.hex() }))
}
@@ -468,10 +539,9 @@ impl Interactive for PeditM {
return Ok(Step::Done);
}
let h = self.h.ok_or_else(|| other("No object."))?;
let k = curves::entity(s, h)?.kind;
let pl = as_lwpoly(&k).ok_or_else(|| other("Cannot convert."))?;
let (pl, normal) = polyline_of(&curves::entity(s, h)?).ok_or_else(|| other("Cannot convert."))?;
self.original = Some(pl.vertices.clone());
set_kind(s, h, EntityKind::LwPolyline(pl))?;
set_polyline(s, h, pl, normal)?;
self.phase = PPhase::Main;
Ok(Step::Continue)
}
@@ -544,7 +614,7 @@ impl Interactive for PeditM {
SelOutcome::Done(hs) => {
let h = self.h.ok_or_else(|| other("No polyline."))?;
self.snapshot(s);
let n = pedit_join(s, h, &hs, 0.0)?;
let n = pedit_join(s, h, &hs, 0.0, true)?;
s.echo(format!("{n} segments added to polyline"));
s.set_selection(vec![h]);
self.phase = PPhase::Main;
+7 -7
View File
@@ -8,7 +8,7 @@ use serde_json::json;
use super::super::curves;
use super::super::machines::{SelOutcome, SelectPhase, number};
use super::pedit::{PPhase, PeditM, clear_widths, pedit_apply, pedit_join, yes_no};
use super::{as_lwpoly, other, set_kind};
use super::{other, polyline_of, set_kind, set_polyline};
use crate::{Accept, Input, Prompt, Result, Session, Step};
/// Most option steps Undo can take back.
@@ -78,13 +78,13 @@ impl PeditM {
let no = !yes_no(&i)?;
let mut kept = Vec::new();
for h in std::mem::take(&mut self.multi) {
let kind = curves::entity(s, h)?.kind;
match kind {
let e = curves::entity(s, h)?;
match e.kind {
EntityKind::LwPolyline(_) => kept.push(h),
_ if no => {}
k => {
if let Some(pl) = as_lwpoly(&k) {
set_kind(s, h, EntityKind::LwPolyline(pl))?;
_ => {
if let Some((pl, normal)) = polyline_of(&e) {
set_polyline(s, h, pl, normal)?;
kept.push(h);
}
}
@@ -219,7 +219,7 @@ impl PeditM {
let open = matches!(curves::entity(s, h)?.kind, EntityKind::LwPolyline(p) if !p.closed);
if open {
// A polyline that took on segments no longer goes back past the Join on Decurve.
if pedit_join(s, h, &rest, fuzz)? > 0 {
if pedit_join(s, h, &rest, fuzz, false)? > 0 {
self.morig.remove(&h);
}
rest.retain(|o| s.doc().is_ok_and(|d| d.entity(*o).is_some()));
+85 -4
View File
@@ -85,18 +85,31 @@ pub fn profile(s: &Session) -> Value {
Value::Object(m)
}
/// The profile variables the drawing keeps in its header rather than in the session's settings.
const DRAWING_VARS: &[&str] = &["SNAPUNIT", "GRIDUNIT"];
/// Set the profile variables named in `values` (an object; other keys are refused). All or
/// nothing: one bad name or value leaves every setting as it was.
/// nothing: one bad name or value leaves every setting, and the drawing, as they were.
pub fn apply(s: &mut Session, values: &Value) -> Result<()> {
let Some(obj) = values.as_object() else { return Err(bad("options", "expected an object of profile variables")) };
let before = s.settings.clone();
// When one of the values is a drawing variable, the drawing as it is: put back whole on a
// refusal, it is the same drawing again, so not marked as changed either.
let touches_drawing = obj.keys().any(|k| DRAWING_VARS.iter().any(|v| v.eq_ignore_ascii_case(k.trim())));
let drawing = if touches_drawing { s.state().ok().map(|st| st.doc.clone()) } else { None };
let put_back = |s: &mut Session| {
s.settings = before.clone();
if let (Some(doc), Ok(st)) = (&drawing, s.state_mut()) {
st.doc = doc.clone();
}
};
for (name, v) in obj {
if !is_profile_var(name) {
s.settings = before;
put_back(s);
return Err(bad("options", format!("{name} is not a profile setting")));
}
if let Err(e) = crate::sysvars::set(s, name, v) {
s.settings = before;
put_back(s);
return Err(bad("options", format!("invalid value for {}: {e}", name.to_ascii_uppercase())));
}
}
@@ -117,7 +130,8 @@ pub fn restore(s: &mut Session, saved: &Value) {
}
}
/// Put every profile variable back to its default.
/// Put every profile variable back to its default, except [`DRAWING_VARS`]: a reset doesn't change
/// the drawing.
pub fn reset(s: &mut Session) {
let d = Settings::default();
let st = &mut s.settings;
@@ -145,6 +159,21 @@ pub fn reset(s: &mut Session) {
st.pickadd = d.pickadd;
st.pickdrag = d.pickdrag;
st.maxarray = d.maxarray;
st.dynprompt = d.dynprompt;
st.dyndigrip = d.dyndigrip;
st.dyndivis = d.dyndivis;
st.selectioneffect = d.selectioneffect;
st.selectionpreview = d.selectionpreview;
st.previeweffect = d.previeweffect;
st.previewfilter = d.previewfilter;
st.grips = d.grips;
st.gripobjlimit = d.gripobjlimit;
st.selectionarea = d.selectionarea;
st.windowareacolor = d.windowareacolor;
st.crossingareacolor = d.crossingareacolor;
st.selectionareaopacity = d.selectionareaopacity;
st.pickstyle = d.pickstyle;
st.measureinit = d.measureinit;
}
fn run_options(s: &mut Session, p: &Value) -> Result<Value> {
@@ -191,4 +220,56 @@ mod tests {
restore(&mut b, &saved);
assert_eq!(profile(&b), saved);
}
#[test]
fn a_refused_change_leaves_the_drawings_snap_and_grid_too() {
let mut s = Session::new();
let before = profile(&s);
let refused = [
json!({ "SNAPUNIT": [2, 3], "GRIDUNIT": [4, 5], "WINDOWAREACOLOR": 0 }),
json!({ "GRIDUNIT": [4, 5], "LUNITS": 2 }),
json!({ "WINDOWAREACOLOR": 0 }),
];
for bad_one in refused {
assert!(apply(&mut s, &bad_one).is_err(), "{bad_one}");
assert_eq!(profile(&s), before, "{bad_one}");
// The same drawing, so there is nothing new to save.
assert!(!s.state().unwrap().is_dirty(), "{bad_one}");
}
assert!(s.execute("options", &json!({ "reset": true, "SNAPUNIT": [2, 3], "WINDOWAREACOLOR": 0 })).is_err());
assert_eq!(profile(&s), before);
// The header entries come back exactly: a zero grid spacing (which reads as the snap
// spacing), and a snap spacing the drawing doesn't have. The refused value comes last, so
// both are written first (the keys are taken in name order).
let header = |s: &Session, n: &str| s.doc().unwrap().header.get(n).cloned();
s.doc_mut().unwrap().header.set("GRIDUNIT", cadcraft_doc::HVal::Point(cadcraft_geom::Vec3::new(0.0, 0.0, 0.0)));
s.doc_mut().unwrap().header.vars.remove("SNAPUNIT");
let (grid, snap) = (header(&s, "GRIDUNIT"), header(&s, "SNAPUNIT"));
assert!(apply(&mut s, &json!({ "GRIDUNIT": [4, 5], "SNAPUNIT": [2, 3], "WINDOWAREACOLOR": 0 })).is_err());
assert_eq!((header(&s, "GRIDUNIT"), header(&s, "SNAPUNIT")), (grid, snap));
}
#[test]
fn reset_puts_every_profile_var_back_except_the_drawings() {
let defaults = profile(&Session::new());
let mut s = Session::new();
for name in PROFILE_VARS.iter().filter(|n| !DRAWING_VARS.contains(n)) {
// A value the variable takes that isn't its default: 0 and 1 swapped, or a number one
// more or less, or an angle.
let was = &defaults[*name];
let n = was.as_f64().unwrap_or(0.0);
let tries = [json!(if n == 0.0 { 1 } else { 0 }), json!(n + 1.0), json!(n - 1.0), json!("15")];
let changed = tries.iter().any(|v| apply(&mut s, &json!({ *name: v })).is_ok() && profile(&s)[*name] != *was);
assert!(changed, "no other value found for {name} (default {was})");
}
assert!(PROFILE_VARS.iter().filter(|n| !DRAWING_VARS.contains(n)).all(|n| profile(&s)[*n] != defaults[*n]));
apply(&mut s, &json!({ "SNAPUNIT": [2, 3], "GRIDUNIT": [4, 5] })).unwrap();
reset(&mut s);
let after = profile(&s);
for name in PROFILE_VARS.iter().filter(|n| !DRAWING_VARS.contains(n)) {
assert_eq!(after[*name], defaults[*name], "{name}");
}
// The snap and grid spacing are the drawing's, and stay.
assert_eq!((after["SNAPUNIT"].clone(), after["GRIDUNIT"].clone()), (json!([2.0, 3.0]), json!([4.0, 5.0])));
}
}
@@ -202,6 +202,7 @@ pub const NO_FILES: &[&str] = &[
"dim",
"mleader",
"leader",
"qleader",
"dimstyle.update",
"dimoverride",
"dimreassociate",
@@ -0,0 +1,98 @@
//! Attributes are matched to their block's definitions, and definitions to a reference's
//! attributes, by tag in one lookup each: BURST and ATTSYNC on a reference with many of both.
use std::sync::Arc;
use cadcraft_doc::{Attrib, EntityKind, Handle};
use cadcraft_engine::Session;
use serde_json::json;
/// Block B with definition T and a reference to it carrying T = "v"; with `n` > 0 the block gets
/// `n` more definitions and the reference's attribute is replaced by `n`, the tags `n` long ones
/// alike up to their last characters, no attribute's a definition's.
fn reference(n: usize) -> (Session, Handle) {
let mut s = Session::new();
s.execute("attdef", &json!({"tag": "T", "default": "d", "at": [0, 1], "height": 1.0})).unwrap();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
let hs: Vec<String> = s.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect();
s.execute("block", &json!({"name": "B", "base": [0, 0], "keep": "delete", "handles": hs})).unwrap();
let r = s.execute("insert", &json!({"name": "B", "at": [0, 0], "attribs": {"T": "v"}})).unwrap();
let h = Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
if n > 0 {
let tag = |kind: char, i: usize| format!("{}{kind}{i:05}", "T".repeat(1000));
let d = s.doc_mut().unwrap();
let handles: Vec<Handle> = (0..n).map(|_| d.new_handle()).collect();
let blk = Arc::make_mut(d.blocks.get_mut("B").unwrap());
let def = blk.entities.iter().find(|e| matches!(e.kind, EntityKind::AttDef(_))).unwrap().as_ref().clone();
for (i, h) in handles.into_iter().enumerate() {
let mut e = def.clone();
e.handle = h;
if let EntityKind::AttDef(a) = &mut e.kind {
a.tag = tag('D', i);
}
blk.entities.push(e);
}
d.modify_entity(h, |e| {
if let EntityKind::Insert(ins) = &mut e.kind {
let one = ins.attribs[0].clone();
ins.attribs = (0..n).map(|i| Attrib { tag: tag('A', i), ..one.clone() }).collect();
}
})
.unwrap();
}
(s, h)
}
fn attribs(s: &Session, h: Handle) -> Vec<Attrib> {
let EntityKind::Insert(i) = &s.doc().unwrap().entity(h).unwrap().kind else { panic!("not an insert") };
i.attribs.clone()
}
/// #1923: comparing each attribute with each definition (BURST: for its properties; ATTSYNC: for
/// the value each definition keeps) cost N x N comparisons of whole tags (many seconds here); one
/// lookup each costs milliseconds.
const N: usize = 4000;
#[test]
fn burst_matches_many_attributes_without_comparing_every_pair() {
let (mut s, h) = reference(N);
let t = std::time::Instant::now();
s.execute("burst", &json!({"handles": [h.hex()]})).unwrap();
assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed());
assert_eq!(s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Text(_))).count(), N);
}
#[test]
fn attsync_matches_many_definitions_without_comparing_every_pair() {
let (mut s, h) = reference(N);
let t = std::time::Instant::now();
s.execute("attsync", &json!({"name": "B"})).unwrap();
assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed());
// An attribute for each definition (T and the N others), with its default value: the
// reference carried none of their tags.
let a = attribs(&s, h);
assert_eq!(a.len(), N + 1);
assert!(a.iter().all(|a| a.text.value == "d"));
}
#[test]
fn attsync_keeps_the_value_of_the_first_attribute_of_a_tag() {
// A reference carrying two attributes of one tag (in different case, as a file can hold
// them) keeps the first one's value for the definition of that tag.
let (mut s, h) = reference(0);
s.doc_mut()
.unwrap()
.modify_entity(h, |e| {
if let EntityKind::Insert(ins) = &mut e.kind {
let mut second = ins.attribs[0].clone();
second.tag = "t".into();
second.text.value = "second".into();
ins.attribs[0].text.value = "first".into();
ins.attribs.push(second);
}
})
.unwrap();
s.execute("attsync", &json!({"name": "B"})).unwrap();
let a = attribs(&s, h);
assert_eq!(a.iter().map(|a| (a.tag.as_str(), a.text.value.as_str())).collect::<Vec<_>>(), [("T", "first")]);
}
File diff suppressed because it is too large Load Diff
+4
View File
@@ -12,6 +12,7 @@ mod attdisp_attsync;
mod attedit_prompts;
mod attrib_modes;
mod attrib_props;
mod attribute_tag_matching;
mod attribute_tools;
mod attribute_value_baseline;
mod block_description;
@@ -84,6 +85,7 @@ mod insert_enter;
mod insert_prompts;
mod isometric;
mod join_close;
mod join_on_source;
mod json_param_validation;
mod kept_dimension_snaps;
mod layer_cmdline;
@@ -122,6 +124,7 @@ mod oops_command;
mod options_profile;
mod overkill;
mod parallel_display_list;
mod pedit_heights;
mod pedit_multiple;
mod pedit_splinedit;
mod pick_text;
@@ -143,6 +146,7 @@ mod purge_mlinestyles;
mod purge_prompts;
mod qdim;
mod qdim_modes;
mod qleader;
mod query_entities;
mod quickcalc;
mod recent_commands;
+365
View File
@@ -0,0 +1,365 @@
//! PEDIT on lines, arcs and polylines away from Z 0, as AutoCAD 2024 runs it (accoreconsole,
//! `entget` of the polyline made, on self-built drawings). A mirrored object here is one whose
//! normal is 0,0,-1, kept in world coordinates as the DXF reader keeps it.
use cadcraft_doc::{Entity, EntityKind, Handle, LwPolyline};
use cadcraft_engine::Session;
use cadcraft_geom::Vec3;
use serde_json::{Value, json};
fn handle(v: &Value) -> Handle {
Handle::parse_hex(v["handle"].as_str().or_else(|| v["handles"][0].as_str()).unwrap()).unwrap()
}
fn entity(s: &Session, h: Handle) -> Entity {
(**s.doc().unwrap().entity(h).unwrap()).clone()
}
fn edit(s: &mut Session, h: Handle, f: impl FnOnce(&mut Entity)) {
s.doc_mut().unwrap().modify_entity(h, f).unwrap();
}
/// A line from `a` to `b`.
fn line(s: &mut Session, a: [f64; 3], b: [f64; 3]) -> Handle {
let h = handle(&s.execute("line", &json!({ "points": [[a[0], a[1]], [b[0], b[1]]] })).unwrap());
edit(s, h, |e| {
if let EntityKind::Line(l) = &mut e.kind {
(l.a.z, l.b.z) = (a[2], b[2]);
}
});
h
}
/// An arc round `c` (world) from `a1` to `a2` degrees, counterclockwise in plan.
fn arc(s: &mut Session, c: [f64; 3], r: f64, a1: f64, a2: f64) -> Handle {
let h = handle(&s.execute("arc", &json!({ "center": [c[0], c[1]], "radius": r, "start": a1, "end": a2 })).unwrap());
edit(s, h, |e| {
if let EntityKind::Arc(a) = &mut e.kind {
a.center.z = c[2];
}
});
h
}
/// An open polyline through `points` at `elevation`.
fn pline(s: &mut Session, points: Value, elevation: f64) -> Handle {
let h = handle(&s.execute("pline", &json!({ "points": points })).unwrap());
edit(s, h, |e| {
if let EntityKind::LwPolyline(p) = &mut e.kind {
p.elevation = elevation;
}
});
h
}
fn face_down(s: &mut Session, h: Handle) {
edit(s, h, |e| e.common.extrusion = Vec3::new(0.0, 0.0, -1.0));
}
fn polyline(e: &Entity) -> LwPolyline {
let EntityKind::LwPolyline(p) = &e.kind else { panic!("not a polyline: {e:?}") };
p.clone()
}
/// PEDIT's JSON form with nothing to change, which only turns a line or an arc into a polyline.
fn convert(s: &mut Session, h: Handle) -> Entity {
s.execute("pedit", &json!({ "handle": h.hex(), "option": "ltypegen", "on": false })).unwrap();
entity(s, h)
}
#[test]
fn a_line_or_an_arc_becomes_a_polyline_at_its_height() {
// AutoCAD 2024: a line at Z 5 and an arc whose centre is at Z 5 give elevation 5 facing up;
// a thickness of 2 stays, a line's and an arc's; a line facing down still gives a polyline
// facing up.
let mut s = Session::new();
let l = line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
edit(&mut s, l, |e| e.common.thickness = 2.0);
let e = convert(&mut s, l);
assert_eq!((polyline(&e).elevation, e.common.extrusion, e.common.thickness), (5.0, Vec3::Z, 2.0));
let a = arc(&mut s, [10.0, 5.0, 5.0], 5.0, 270.0, 0.0);
edit(&mut s, a, |e| e.common.thickness = 2.0);
let e = convert(&mut s, a);
let p = polyline(&e);
assert_eq!((p.elevation, e.common.extrusion, e.common.thickness), (5.0, Vec3::Z, 2.0));
assert!((p.vertices[0].bulge - std::f64::consts::FRAC_PI_8.tan()).abs() < 1e-9, "{p:?}");
// Below Z 0 too (AutoCAD 2024: 38 = -5 for the arc's centre at Z -5).
let a = arc(&mut s, [10.0, 5.0, -5.0], 5.0, 270.0, 0.0);
let e = convert(&mut s, a);
assert_eq!((polyline(&e).elevation, e.common.extrusion), (-5.0, Vec3::Z));
let l = line(&mut s, [0.0, 20.0, 5.0], [10.0, 20.0, 5.0]);
face_down(&mut s, l);
let e = convert(&mut s, l);
assert_eq!((polyline(&e).elevation, e.common.extrusion), (5.0, Vec3::Z));
// A mirrored arc keeps its normal (AutoCAD 2024: 210 0,0,-1, elevation 5 for the arc at world
// Z -5) and runs as it does in its own coordinates: from world (15,5) to (10,0), bulge
// -0.414214 in plan (0.414214 in its own coordinates).
let a = arc(&mut s, [10.0, 5.0, -5.0], 5.0, 270.0, 0.0);
face_down(&mut s, a);
let e = convert(&mut s, a);
let p = polyline(&e);
assert_eq!((p.elevation, e.common.extrusion), (5.0, Vec3::new(0.0, 0.0, -1.0)));
let v: Vec<(f64, f64)> = p.vertices.iter().map(|v| (v.p.x, v.p.y)).collect();
assert!((v[0].0 - 15.0).abs() < 1e-9 && (v[0].1 - 5.0).abs() < 1e-9 && (v[1].0 - 10.0).abs() < 1e-9 && v[1].1.abs() < 1e-9, "{v:?}");
assert!((p.vertices[0].bulge + std::f64::consts::FRAC_PI_8.tan()).abs() < 1e-9, "{p:?}");
// The elevation runs along the normal the other way too: a mirrored arc at world Z 5 gives -5,
// and one 2 thick at world Z -5 keeps the thickness (AutoCAD 2024: 38 = -5; 38 = 5, 39 = 2).
let a = arc(&mut s, [10.0, 5.0, 5.0], 5.0, 270.0, 0.0);
face_down(&mut s, a);
let e = convert(&mut s, a);
assert_eq!((polyline(&e).elevation, e.common.extrusion), (-5.0, Vec3::new(0.0, 0.0, -1.0)));
let a = arc(&mut s, [10.0, 5.0, -5.0], 5.0, 270.0, 0.0);
face_down(&mut s, a);
edit(&mut s, a, |e| e.common.thickness = 2.0);
let e = convert(&mut s, a);
assert_eq!((polyline(&e).elevation, e.common.extrusion, e.common.thickness), (5.0, Vec3::new(0.0, 0.0, -1.0), 2.0));
// A sloped line still comes out at elevation 0, facing up: AutoCAD 2024 makes a polyline in the
// line's vertical plane (normal 0,1,0), which a CADCraft polyline can't be.
let l = line(&mut s, [0.0, 40.0, 0.0], [10.0, 40.0, 5.0]);
let e = convert(&mut s, l);
assert_eq!((polyline(&e).elevation, e.common.extrusion), (0.0, Vec3::Z));
// A refused option leaves a line as it was, its normal included.
let l = line(&mut s, [0.0, 60.0, 5.0], [10.0, 60.0, 5.0]);
face_down(&mut s, l);
let before = entity(&s, l);
let r = s.execute("pedit", &json!({ "handle": l.hex(), "option": "vertex", "index": 0, "action": "break" }));
assert!(r.is_err(), "{r:?}");
assert_eq!(entity(&s, l), before);
}
/// PEDIT Join from the first object onto the second; whether the second was taken.
fn joins(s: &mut Session, first: Handle, second: Handle) -> bool {
let r = s.execute("pedit", &json!({ "handle": first.hex(), "option": "join", "join": [second.hex()] })).unwrap();
let taken = r["joined"] == json!(1);
assert_eq!(taken, s.doc().unwrap().entity(second).is_none(), "{r}");
taken
}
#[test]
fn join_takes_only_objects_at_the_polylines_height_facing_its_way() {
// AutoCAD 2024, from a line at Z 5 ending at (10,0): "1 segments added to polyline" or "0".
let next: [(&str, bool, fn(&mut Session) -> Handle); 6] = [
("a line at Z 5", true, |s| line(s, [10.0, 0.0, 5.0], [10.0, 5.0, 5.0])),
("a line at Z 0", false, |s| line(s, [10.0, 0.0, 0.0], [10.0, 5.0, 0.0])),
("an arc at Z 5", true, |s| arc(s, [10.0, 5.0, 5.0], 5.0, 270.0, 0.0)),
("an arc at Z 0", false, |s| arc(s, [10.0, 5.0, 0.0], 5.0, 270.0, 0.0)),
("a mirrored line at Z 5", true, |s| {
let h = line(s, [10.0, 0.0, 5.0], [10.0, 5.0, 5.0]);
face_down(s, h);
h
}),
("a mirrored arc at Z 5", false, |s| {
let h = arc(s, [10.0, 5.0, 5.0], 5.0, 270.0, 0.0);
face_down(s, h);
h
}),
];
for (what, want, make) in next {
let mut s = Session::new();
let base = line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
let other = make(&mut s);
assert_eq!(joins(&mut s, base, other), want, "{what}");
let p = polyline(&entity(&s, base));
assert_eq!((p.elevation, p.vertices.len()), (5.0, if want { 3 } else { 2 }), "{what}");
if want && what.contains("arc") {
// AutoCAD 2024: bulge 0.414214 on the arc's segment.
assert!((p.vertices[1].bulge - std::f64::consts::FRAC_PI_8.tan()).abs() < 1e-9, "{what}: {p:?}");
}
}
// From a mirrored polyline at elevation 5 (world Z -5, from (0,0) to (10,0)): no line at its
// world height, but a mirrored arc there and another mirrored polyline at elevation 5; and a
// polyline at elevation 5 takes no polyline at 0.
let mirrored: [(&str, bool, fn(&mut Session) -> Handle); 3] = [
("a line at Z -5", false, |s| line(s, [10.0, 0.0, -5.0], [10.0, 5.0, -5.0])),
("a mirrored arc at Z -5", true, |s| {
let h = arc(s, [10.0, 5.0, -5.0], 5.0, 270.0, 0.0);
face_down(s, h);
h
}),
("a mirrored polyline at elevation 5", true, |s| {
let h = pline(s, json!([[10, 0], [10, 5]]), 5.0);
face_down(s, h);
h
}),
];
for (what, want, make) in mirrored {
let mut s = Session::new();
let base = pline(&mut s, json!([[0, 0], [10, 0]]), 5.0);
face_down(&mut s, base);
let other = make(&mut s);
assert_eq!(joins(&mut s, base, other), want, "{what}");
// AutoCAD 2024: the polyline keeps elevation 5 and normal 0,0,-1; the arc's segment has
// bulge -0.414214 in the polyline's own coordinates, 0.414214 seen from above.
let e = entity(&s, base);
let p = polyline(&e);
assert_eq!((p.elevation, e.common.extrusion, p.vertices.len()), (5.0, Vec3::new(0.0, 0.0, -1.0), if want { 3 } else { 2 }), "{what}");
if want && what.contains("arc") {
assert!((p.vertices[1].bulge - std::f64::consts::FRAC_PI_8.tan()).abs() < 1e-9, "{what}: {p:?}");
}
}
let mut s = Session::new();
let base = pline(&mut s, json!([[0, 0], [10, 0]]), 5.0);
let other = pline(&mut s, json!([[10, 0], [10, 5]]), 0.0);
assert!(!joins(&mut s, base, other), "a polyline at elevation 0");
}
#[test]
fn multiple_join_takes_objects_at_any_height_but_not_facing_the_other_way() {
// AutoCAD 2024: PEDIT Multiple, a line at Z 5 and one at Z 0 meeting it in plan, convert and
// Join with no fuzz: "1 segments added to polyline", one polyline at elevation 5.
let mut s = Session::new();
line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
line(&mut s, [10.0, 0.0, 0.0], [10.0, 5.0, 0.0]);
s.cmdline("pedit m 5,0 10,2.5").unwrap();
s.cmdline("").unwrap();
s.cmdline("y j 0").unwrap();
s.cmdline("").unwrap();
let objects: Vec<Entity> = s.doc().unwrap().model.iter().map(|e| (**e).clone()).collect();
assert_eq!(objects.len(), 1, "{objects:?}");
let p = polyline(&objects[0]);
assert_eq!((p.elevation, p.vertices.len()), (5.0, 3));
// A line at Z 0 to (10,0) and a mirrored arc from there to (15,5), picked in either order:
// both become polylines, the arc's facing down, and Join takes neither ("0 segments added").
for arc_first in [false, true] {
let mut s = Session::new();
line(&mut s, [0.0, 0.0, 0.0], [10.0, 0.0, 0.0]);
let a = arc(&mut s, [10.0, 5.0, 0.0], 5.0, 270.0, 0.0);
face_down(&mut s, a);
// The arc picked on it, at 315 degrees.
s.cmdline(if arc_first { "pedit m 13.5355339,1.4644661 5,0" } else { "pedit m 5,0 13.5355339,1.4644661" }).unwrap();
s.cmdline("").unwrap();
s.cmdline("y j 0").unwrap();
s.cmdline("").unwrap();
let objects: Vec<Entity> = s.doc().unwrap().model.iter().map(|e| (**e).clone()).collect();
assert_eq!(objects.len(), 2, "arc first {arc_first}: {objects:?}");
assert!(objects.iter().all(|e| matches!(e.kind, EntityKind::LwPolyline(_))), "{objects:?}");
// AutoCAD 2024: the arc's polyline at elevation 0 with normal 0,0,-1, the line's facing up.
let (arcs, lines): (Vec<&Entity>, Vec<&Entity>) = objects.iter().partition(|e| e.common.extrusion.z < 0.0);
assert_eq!((arcs.len(), lines.len()), (1, 1), "{objects:?}");
let p = polyline(arcs[0]);
assert!(p.elevation == 0.0 && p.vertices[0].bulge != 0.0 && lines[0].common.extrusion == Vec3::Z, "{objects:?}");
}
}
#[test]
fn join_continues_from_a_sloped_lines_far_end_height() {
// AutoCAD 2024: from a line at Z 5, a sloped line down to Z 0 and a line on at Z 0 both join
// ("2 segments added"), at the polyline's end and at its start alike, the sloped line drawn
// either way. AutoCAD makes that polyline in the lines' vertical plane; a CADCraft polyline
// stays at the source's elevation.
for (base, sloped, next) in [
([[0.0, 0.0, 5.0], [10.0, 0.0, 5.0]], [[10.0, 0.0, 5.0], [20.0, 0.0, 0.0]], [[20.0, 0.0, 0.0], [30.0, 0.0, 0.0]]),
([[0.0, 0.0, 5.0], [10.0, 0.0, 5.0]], [[20.0, 0.0, 0.0], [10.0, 0.0, 5.0]], [[20.0, 0.0, 0.0], [30.0, 0.0, 0.0]]),
([[10.0, 0.0, 5.0], [20.0, 0.0, 5.0]], [[0.0, 0.0, 0.0], [10.0, 0.0, 5.0]], [[-10.0, 0.0, 0.0], [0.0, 0.0, 0.0]]),
([[10.0, 0.0, 5.0], [20.0, 0.0, 5.0]], [[10.0, 0.0, 5.0], [0.0, 0.0, 0.0]], [[-10.0, 0.0, 0.0], [0.0, 0.0, 0.0]]),
] {
let mut s = Session::new();
let h = line(&mut s, base[0], base[1]);
let a = line(&mut s, sloped[0], sloped[1]);
let b = line(&mut s, next[0], next[1]);
let r = s.execute("pedit", &json!({ "handle": h.hex(), "option": "join", "join": [a.hex(), b.hex()] })).unwrap();
assert_eq!(r["joined"], json!(2), "{base:?}: {r}");
assert_eq!(polyline(&entity(&s, h)).vertices.len(), 4);
}
}
#[test]
fn a_chain_closes_only_at_one_height() {
// AutoCAD 2024: three sides of a triangle at Z 5 join into a closed polyline; with its last
// side at Z 0, that side stays a line and the polyline stays open ("1 segments added").
for (last_z, joined, closed) in [(5.0, 2, true), (0.0, 1, false)] {
let mut s = Session::new();
let h = line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
let a = line(&mut s, [10.0, 0.0, 5.0], [10.0, 10.0, 5.0]);
let b = line(&mut s, [10.0, 10.0, last_z], [0.0, 0.0, last_z]);
let r = s.execute("pedit", &json!({ "handle": h.hex(), "option": "join", "join": [a.hex(), b.hex()] })).unwrap();
assert_eq!(r["joined"], json!(joined), "last side at {last_z}: {r}");
assert_eq!(polyline(&entity(&s, h)).closed, closed, "last side at {last_z}");
}
// A line at Z 5 and a sloped line back over it to Z 0: the ends meet in plan at Z 5 and at Z 0,
// and the polyline stays open (AutoCAD 2024: "1 segments added", 70 = 0).
let mut s = Session::new();
let h = line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
let back = line(&mut s, [10.0, 0.0, 5.0], [0.0, 0.0, 0.0]);
assert!(joins(&mut s, h, back));
let p = polyline(&entity(&s, h));
assert_eq!((p.vertices.len(), p.closed), (3, false));
}
#[test]
fn join_takes_a_sloped_line_only_in_one_plane_with_the_polyline_and_every_line_picked() {
// AutoCAD 2024 joins only objects in one plane with the polyline: the plane the polyline and
// every line picked share, when they share one, else the polyline's own, flat, where no sloped
// line lies. From a line at Z 5, (0,0) to (10,0):
let cases: [(&str, &[[[f64; 3]; 2]], usize); 4] = [
// a sloped line at right angles in plan, a tilted plane: "1 segments added";
("at an angle", &[[[10.0, 0.0, 5.0], [10.0, 10.0, 0.0]]], 1),
// a triangle at Z 5 whose last side slopes from (10,10,5) to (0,0,0): that side stays a line;
("a triangle's sloped side", &[[[10.0, 0.0, 5.0], [10.0, 10.0, 5.0]], [[10.0, 10.0, 5.0], [0.0, 0.0, 0.0]]], 1),
// a corner at Z 5, then a sloped line on in plan: the sloped line stays a line;
("after a corner", &[[[10.0, 0.0, 5.0], [10.0, 10.0, 5.0]], [[10.0, 10.0, 5.0], [10.0, 20.0, 0.0]]], 1),
// a sloped line on in plan, then a line at Z 0 from its foot turning off their vertical
// plane: the three share no plane, and neither joins ("0 segments added").
("then a turn", &[[[10.0, 0.0, 5.0], [20.0, 0.0, 0.0]], [[20.0, 0.0, 0.0], [20.0, 10.0, 0.0]]], 0),
];
for (what, lines, joined) in cases {
let mut s = Session::new();
let h = line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
let picked: Vec<String> = lines.iter().map(|[a, b]| line(&mut s, *a, *b).hex()).collect();
let r = s.execute("pedit", &json!({ "handle": h.hex(), "option": "join", "join": picked })).unwrap();
assert_eq!(r["joined"], json!(joined), "{what}: {r}");
let left = s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count();
assert_eq!(left, lines.len() - joined, "{what}");
}
// A sloped line on in plan, then an arc at Z 0 from its foot: the line joins, the arc, which
// lies flat, doesn't ("1 segments added").
let mut s = Session::new();
let h = line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
let l = line(&mut s, [10.0, 0.0, 5.0], [20.0, 0.0, 0.0]);
let a = arc(&mut s, [20.0, 5.0, 0.0], 5.0, 270.0, 0.0);
let r = s.execute("pedit", &json!({ "handle": h.hex(), "option": "join", "join": [l.hex(), a.hex()] })).unwrap();
assert_eq!(r["joined"], json!(1), "{r}");
assert!(s.doc().unwrap().entity(l).is_none() && s.doc().unwrap().entity(a).is_some());
}
#[test]
fn join_meets_within_the_fuzz_in_plan_and_1e_6_in_height() {
// The JSON form's fuzz bridges a gap in plan only: a line 0.3 off the end joins with fuzz 0.5
// at the polyline's height, to within 1e-6, and not 0.001 above it.
for (z, want) in [(5.0, true), (5.0 + 1e-9, true), (5.001, false)] {
let mut s = Session::new();
let h = line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
let o = line(&mut s, [10.3, 0.0, z], [10.3, 5.0, z]);
let r = s.execute("pedit", &json!({ "handle": h.hex(), "option": "join", "join": [o.hex()], "fuzz": 0.5 })).unwrap();
assert_eq!(r["joined"] == json!(1), want, "Z {z}: {r}");
}
// Multiple's Join takes the line 0.001 above too, as it takes one at any height.
let mut s = Session::new();
line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
line(&mut s, [10.3, 0.0, 5.001], [10.3, 5.0, 5.001]);
s.cmdline("pedit m 5,0 10.3,2.5").unwrap();
s.cmdline("").unwrap();
s.cmdline("y j 0.5").unwrap();
s.cmdline("").unwrap();
assert_eq!(s.doc().unwrap().model.iter().count(), 1);
}
#[test]
fn the_command_line_converts_and_joins_the_same_way() {
// PEDIT typed: a mirrored line at Z 5 becomes a polyline at elevation 5 facing up, and Join
// leaves a line at Z 0 off it ("0 segments added to polyline").
let mut s = Session::new();
let h = line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
face_down(&mut s, h);
let other = line(&mut s, [10.0, 0.0, 0.0], [10.0, 5.0, 0.0]);
s.cmdline("pedit 5,0 y").unwrap();
let e = entity(&s, h);
assert_eq!((polyline(&e).elevation, e.common.extrusion), (5.0, Vec3::Z));
let n = s.log.len();
s.cmdline("j 10,2.5").unwrap();
s.cmdline("").unwrap();
assert!(s.log[n..].iter().any(|l| l.contains("0 segments added to polyline")), "{:?}", &s.log[n..]);
assert!(s.doc().unwrap().entity(other).is_some());
s.cmdline("").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
}
+253
View File
@@ -0,0 +1,253 @@
//! QLEADER at the command line as AutoCAD 2024 runs it with its default settings (accoreconsole,
//! `(command "_.QLEADER" ...)` on a metric drawing, then `entget` of the LEADER and the MTEXT):
//! up to three points, a text width, lines of text; the text sits DIMGAP past the leader's end
//! with the middle of its first line level with it on the right, of its last line on the left.
use cadcraft_engine::doc::EntityKind;
use cadcraft_engine::geom::Vec2;
use cadcraft_engine::{Input, Session};
use serde_json::json;
/// What QLEADER drew: the leader's vertices, and the text's insertion point, height, width,
/// attachment and contents (rounded to 1e-9).
type Drawn = (Vec<(f64, f64)>, Option<((f64, f64), f64, f64, u8, String)>);
fn drawn(s: &Session) -> Drawn {
let r = |v: f64| (v * 1e9).round() / 1e9;
let d = s.doc().unwrap();
let leader = d
.model
.iter()
.find_map(|e| if let EntityKind::Leader(l) = &e.kind { Some(l.vertices.iter().map(|p| (r(p.x), r(p.y))).collect()) } else { None });
let text = d.model.iter().find_map(|e| match &e.kind {
EntityKind::MText(m) => Some(((r(m.insert.x), r(m.insert.y)), r(m.height), r(m.width), m.attach, m.contents.clone())),
_ => None,
});
(leader.unwrap_or_default(), text)
}
/// A drawing with the measured scripts' dimension settings: DIMTAD 1, DIMGAP 0.625, DIMASZ 2.5,
/// DIMSCALE 1 and DIMTXT 2.5.
fn session() -> Session {
let mut s = Session::new();
for (name, v) in [("DIMTAD", 1.0), ("DIMGAP", 0.625), ("DIMASZ", 2.5), ("DIMSCALE", 1.0), ("DIMTXT", 2.5)] {
s.execute("setvar", &json!({ "name": name, "value": v })).unwrap();
}
s
}
/// Types QLEADER then each of `inputs`, and checks it ended.
fn qleader(s: &mut Session, inputs: &[&str]) {
s.cmdline("QLEADER").unwrap();
for t in inputs {
s.cmdline(t).unwrap();
}
assert!(s.running.is_none(), "{inputs:?}: {}", s.prompt_text());
}
#[test]
fn qleader_places_the_text_as_autocad_does() {
// (inputs, AutoCAD's leader vertices, text insertion point, width, attachment, contents)
type Case<'a> = (&'a [&'a str], &'a [(f64, f64)], (f64, f64), f64, u8, &'a str);
let cases: [Case; 8] = [
// Three points, the last segment level: no hook line.
(&["0,0", "20,15", "40,15", "0", "ABC", ""], &[(0.0, 0.0), (20.0, 15.0), (40.0, 15.0)], (40.625, 16.25), 0.0, 1, "ABC"),
// Two points: a hook line DIMASZ (2.5) long into the end.
(&["0,0", "20,15", "", "0", "ABC", ""], &[(0.0, 0.0), (17.5, 15.0), (20.0, 15.0)], (20.625, 16.25), 0.0, 1, "ABC"),
(
&["0,0", "20,15", "35,30", "20", "AB", "CD", ""],
&[(0.0, 0.0), (20.0, 15.0), (32.5, 30.0), (35.0, 30.0)],
(35.625, 31.25),
20.0,
1,
"AB\\PCD",
),
// Running left: the middle of the last line level with the end.
(&["0,0", "-20,15", "-40,15", "0", "AB", "CD", ""], &[(0.0, 0.0), (-20.0, 15.0), (-40.0, 15.0)], (-40.625, 13.75), 0.0, 9, "AB\\PCD"),
(&["0,0", "-20,15", "-40,15", "0", "A", "B", "C", ""], &[(0.0, 0.0), (-20.0, 15.0), (-40.0, 15.0)], (-40.625, 13.75), 0.0, 9, "A\\PB\\PC"),
// A short leader running left: the hook line comes from past the start.
(&["0.5,0.25", "0.48,0.265", "", "0", "ABC", ""], &[(0.5, 0.25), (2.98, 0.265), (0.48, 0.265)], (-0.145, -0.985), 0.0, 9, "ABC"),
// Straight up: it counts as running right.
(&["0,0", "0,20", "", "0", "ABC", ""], &[(0.0, 0.0), (-2.5, 20.0), (0.0, 20.0)], (0.625, 21.25), 0.0, 1, "ABC"),
// Survey coordinates, running left.
(
&["612345.678,2398765.432", "612325.678,2398780.432", "612305.678,2398780.432", "0", "ABC", ""],
&[(612345.678, 2398765.432), (612325.678, 2398780.432), (612305.678, 2398780.432)],
(612305.053, 2398779.182),
0.0,
9,
"ABC",
),
];
for (inputs, leader, at, width, attach, text) in cases {
let mut s = session();
qleader(&mut s, inputs);
assert_eq!(drawn(&s), (leader.to_vec(), Some((at, 2.5, width, attach, text.to_string()))), "{inputs:?}");
}
}
#[test]
fn qleader_scales_with_dimscale_and_ignores_dimtad() {
// DIMGAP 2 and DIMSCALE 2: text 5 high, 4 past the end; the hook line 5 long.
let mut s = session();
s.execute("setvar", &json!({ "name": "DIMGAP", "value": 2.0 })).unwrap();
s.execute("setvar", &json!({ "name": "DIMSCALE", "value": 2.0 })).unwrap();
qleader(&mut s, &["0,0", "20,15", "35,30", "0", "ABC", ""]);
let want = vec![(0.0, 0.0), (20.0, 15.0), (30.0, 30.0), (35.0, 30.0)];
assert_eq!(drawn(&s), (want, Some(((39.0, 32.5), 5.0, 0.0, 1, "ABC".to_string()))));
// DIMTAD 0 or 1, the same place.
for tad in [0, 1] {
let mut s = session();
s.execute("setvar", &json!({ "name": "DIMTAD", "value": tad })).unwrap();
qleader(&mut s, &["0,0", "20,15", "40,15", "0", "ABC", ""]);
assert_eq!(drawn(&s).1, Some(((40.625, 16.25), 2.5, 0.0, 1, "ABC".to_string())), "DIMTAD {tad}");
}
}
#[test]
fn qleader_prompts_and_its_width() {
let mut s = session();
let mut asked = Vec::new();
s.cmdline("QLEADER").unwrap();
for t in ["0,0", "20,15", "40,15", "50,15", "ABC", ""] {
asked.push(s.current_prompt().unwrap().display());
s.cmdline(t).unwrap();
}
assert_eq!(
asked,
[
"Specify first leader point, or [Settings] <Settings>:",
"Specify next point:",
"Specify next point:",
"Specify text width <0>:",
"Enter first line of annotation text <Mtext>:",
"Enter next line of annotation text:",
]
);
// A point gives the width as its distance from the end, so Dynamic Input shows a distance.
assert_eq!(drawn(&s).1.map(|t| t.2), Some(10.0));
let mut s = session();
s.cmdline("QLEADER").unwrap();
for t in ["0,0", "20,15", "40,15"] {
s.cmdline(t).unwrap();
}
assert!(s.current_prompt().unwrap().distance);
// Text that isn't a distance is refused and asked again; Enter is no width.
let _ = s.cmdline("abc");
assert!(s.log.iter().any(|l| l.contains("Requires numeric distance or two points.")), "{:?}", s.log);
assert_eq!(s.current_prompt().unwrap().display(), "Specify text width <0>:");
for t in ["", "ABC", ""] {
s.cmdline(t).unwrap();
}
assert!(s.running.is_none());
assert_eq!(drawn(&s).1.map(|t| t.2), Some(0.0));
// A point so far off that its distance overflows is refused like bad text.
let mut s = session();
s.cmdline("QLEADER").unwrap();
for p in [Vec2::new(0.0, 0.0), Vec2::new(1e308, 0.0)] {
s.input(Input::Point(p)).unwrap();
}
s.cmdline("").unwrap();
let _ = s.input(Input::Point(Vec2::new(-1e308, 0.0)));
assert!(s.log.iter().any(|l| l.contains("Requires numeric distance or two points.")), "{:?}", s.log);
assert_eq!(s.current_prompt().unwrap().display(), "Specify text width <0>:");
// A negative width is none. A width isn't remembered: AutoCAD 2024 offers 0 again after 20.
for width in ["-5", "20"] {
let mut s = session();
qleader(&mut s, &["0,0", "20,15", "40,15", width, "ABC", ""]);
assert_eq!(drawn(&s).1.map(|t| t.2), Some(width.parse::<f64>().unwrap().max(0.0)));
s.cmdline("QLEADER").unwrap();
for t in ["0,0", "20,15", "40,15"] {
s.cmdline(t).unwrap();
}
assert_eq!(s.current_prompt().unwrap().display(), "Specify text width <0>:", "{width}");
}
}
#[test]
fn a_click_at_the_text_prompts_is_no_line_of_text() {
let mut s = session();
s.cmdline("QLEADER").unwrap();
for t in ["0,0", "20,15", "40,15", "0"] {
s.cmdline(t).unwrap();
}
s.input(Input::Point(Vec2::new(5.0, 5.0))).unwrap();
assert_eq!(s.current_prompt().unwrap().display(), "Enter first line of annotation text <Mtext>:");
s.cmdline("AB").unwrap();
s.input(Input::Point(Vec2::new(5.0, 5.0))).unwrap();
assert_eq!(s.current_prompt().unwrap().display(), "Enter next line of annotation text:");
s.cmdline("CD").unwrap();
s.cmdline("").unwrap();
assert!(s.running.is_none());
assert_eq!(drawn(&s).1.map(|t| t.4), Some("AB\\PCD".to_string()));
}
#[test]
fn qleader_without_text_or_points() {
// Enter at the first line: the leader alone.
let mut s = session();
qleader(&mut s, &["0,0", "20,15", "40,15", "0", ""]);
assert_eq!(drawn(&s), (vec![(0.0, 0.0), (20.0, 15.0), (40.0, 15.0)], None));
// Sloped, without text: no hook line either (AutoCAD 2024: two vertices).
let mut s = session();
qleader(&mut s, &["0,0", "20,15", "", "0", ""]);
assert_eq!(drawn(&s), (vec![(0.0, 0.0), (20.0, 15.0)], None));
// Enter after one point: nothing.
let mut s = session();
qleader(&mut s, &["0,0", ""]);
assert_eq!(s.doc().unwrap().model.iter().count(), 0);
// Settings, typed or by Enter: no dialog yet, the first point is asked again.
for settings in ["S", ""] {
let mut s = session();
s.cmdline("QLEADER").unwrap();
s.cmdline(settings).unwrap();
assert!(s.log.iter().any(|l| l == "The QLEADER Settings dialog is not available yet."), "{settings:?}: {:?}", s.log);
assert_eq!(s.current_prompt().unwrap().display(), "Specify first leader point, or [Settings] <Settings>:", "{settings:?}");
}
// LE starts it too.
let mut s = session();
s.cmdline("LE").unwrap();
assert_eq!(s.current_prompt().unwrap().display(), "Specify first leader point, or [Settings] <Settings>:");
}
#[test]
fn qleader_by_json() {
let mut s = session();
let r = s.execute("qleader", &json!({ "points": [[0, 0], [20, 15], [35, 30]], "width": 20, "text": "AB\r\nCD" })).unwrap();
assert_eq!(r["handles"].as_array().map(Vec::len), Some(2));
let want = vec![(0.0, 0.0), (20.0, 15.0), (32.5, 30.0), (35.0, 30.0)];
assert_eq!(drawn(&s), (want, Some(((35.625, 31.25), 2.5, 20.0, 1, "AB\\PCD".to_string()))));
// Text with nothing on its lines is no text: the leader alone, without a hook line.
for text in ["", "\n", "\r\n\r\n"] {
let mut s = session();
let r = s.execute("qleader", &json!({ "points": [[0, 0], [20, 15]], "width": 0, "text": text })).unwrap();
assert_eq!(r["handles"].as_array().map(Vec::len), Some(1), "{text:?}");
assert_eq!(drawn(&s), (vec![(0.0, 0.0), (20.0, 15.0)], None), "{text:?}");
}
// Empty lines at the end are dropped: running left, the text sits as the command line puts it.
let mut s = session();
s.execute("qleader", &json!({ "points": [[0, 0], [-20, 15], [-40, 15]], "text": "AB\n\n" })).unwrap();
assert_eq!(drawn(&s).1, Some(((-40.625, 13.75), 2.5, 0.0, 9, "AB".to_string())));
// 2 or 3 points, a width of 0 or more, text as a string.
for bad in [
json!({ "points": [[0, 0]] }),
json!({ "points": [[0, 0], [1, 1], [2, 1], [3, 1]] }),
json!({ "points": [[0, 0], [1, 1]], "width": -1 }),
json!({ "points": [[0, 0], [1, 1]], "width": "x" }),
json!({ "points": [[0, 0], [1, 1]], "text": 5 }),
json!({ "points": [[0, 0], [1, 1]], "text": ["AB", "CD"] }),
] {
let before = s.doc().unwrap().model.iter().count();
assert!(s.execute("qleader", &bad).is_err(), "{bad}");
assert_eq!(s.doc().unwrap().model.iter().count(), before, "{bad}");
}
// A point that can't be read is named as such, not as missing points.
for (bad, says) in [
(json!({}), "`points` is required"),
(json!({ "points": null }), "`points` is required"),
(json!({ "points": [[0, 0], ["x", 1]] }), "`points` must be a list of [x, y] points"),
] {
let e = s.execute("qleader", &bad).unwrap_err().to_string();
assert!(e.contains(says), "{bad}: {e}");
}
}
+4 -12
View File
@@ -617,20 +617,12 @@ pub(crate) fn entity_tags(d: &Drawing, m: &MLeader, r: &Refs) -> Vec<Tag> {
p(&mut t, 10, b.scale);
f(&mut t, 43, b.rotation);
i(&mut t, 176, 1);
// Attribute values by their ATTDEF in the block.
let defs: Vec<(Handle, &str)> = d
.block(&b.block)
.map(|blk| {
blk.entities
.iter()
.filter_map(|e| if let EntityKind::AttDef(ad) = &e.kind { Some((e.handle, ad.tag.as_str())) } else { None })
.collect()
})
.unwrap_or_default();
// Attribute values by their ATTDEF in the block, the definitions gathered by tag once.
let defs = d.block(&b.block).map(|blk| blk.attdefs_by_tag()).unwrap_or_default();
let mut n = 0i64;
for a in &b.attribs {
let Some((h, _)) = defs.iter().find(|(_, tag)| tag.eq_ignore_ascii_case(&a.tag)) else { continue };
s(&mut t, 330, &h.hex());
let Some(def) = defs.get(&cadcraft_doc::TagKey(&a.tag)) else { continue };
s(&mut t, 330, &def.handle.hex());
i(&mut t, 177, n);
f(&mut t, 44, 0.0);
s(&mut t, 302, &a.text.value);
+1 -1
View File
@@ -8,7 +8,7 @@ use std::collections::{HashMap, HashSet};
use cadcraft_color::Color;
use cadcraft_doc::{
AssocSnap, Attrib, Block, Common, DimAssoc, DimKind, DimStyle, Dimension, Drawing, Entity, EntityKind, EntityStore, Gradient, Group, HAlign,
HVal, Handle, Hatch, Insert, Layout, Leader, Line, Lineweight, LwPolyline, MLeader, MLeaderStyle, MText, PageSetup, Point, Solid, Space, Table,
HVal, Handle, Hatch, Layout, Leader, Line, Lineweight, LwPolyline, MLeader, MLeaderStyle, MText, PageSetup, Point, Solid, Space, Table,
TableStyle, Text, Transparency, Ucs, VAlign, VportConfig, VportTile,
};
use cadcraft_geom::{Bounds2, Vec2, Vec3};
+7 -9
View File
@@ -1,7 +1,7 @@
use super::ctx::{AssocObj, Ctx};
use super::{
Attrib, Color, Common, DimKind, DimStyle, Dimension, Drawing, Entity, EntityKind, HAlign, HashMap, Insert, Lineweight, Text, Transparency,
VAlign, Vec3, Version, W, dxf_ext,
Attrib, Color, Common, DimKind, DimStyle, Dimension, Drawing, Entity, HAlign, HashMap, Lineweight, Text, Transparency, VAlign, Vec3, Version, W,
dxf_ext,
};
/// `AcadAnnotative` xdata marking an annotative style.
@@ -145,13 +145,11 @@ pub(super) fn layer_and_props(w: &mut W, c: &Common, base: Option<&Common>) {
}
}
/// The properties attribute `a` of block reference `e` (of `ins`) is drawn with: its own, else its
/// definition's; an attribute defined on layer 0 is on the reference's layer. Also the
/// definition's properties.
pub(super) fn attrib_common(d: &Drawing, e: &Entity, ins: &Insert, a: &Attrib) -> (Common, Common) {
let def = d
.block(&ins.block)
.and_then(|b| b.entities.iter().find(|be| matches!(&be.kind, EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(&a.tag))));
/// The properties attribute `a` of block reference `e` is drawn with: its own, else its
/// definition's, from the block's definitions by tag `defs`; an attribute defined on layer 0 is on
/// the reference's layer. Also the definition's properties.
pub(super) fn attrib_common(e: &Entity, defs: &std::collections::BTreeMap<cadcraft_doc::TagKey<'_>, &Entity>, a: &Attrib) -> (Common, Common) {
let def = defs.get(&cadcraft_doc::TagKey(&a.tag));
let base = def.map(|de| de.common.clone()).unwrap_or_default();
let mut c = a.props.over(&base);
if c.layer == "0" {
+3 -1
View File
@@ -372,13 +372,15 @@ fn write_insert_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: b
w.f(45, i.row_spacing);
}
if !i.attribs.is_empty() {
// The block's definitions by tag, gathered once for all the attributes (#1923).
let defs = d.block(&i.block).map(|b| b.attdefs_by_tag()).unwrap_or_default();
for (index, a) in i.attribs.iter().enumerate() {
let ah = w.h();
w.s(0, "ATTRIB");
w.s(5, ah);
w.s(330, e.handle.hex());
w.s(100, "AcDbEntity");
let (c, base) = attrib_common(d, e, i, a);
let (c, base) = attrib_common(e, &defs, a);
layer_and_props(w, &c, Some(&base));
// Hidden with its definition (a dynamic block's visibility state hides it).
if !base.visible {
+47
View File
@@ -109,6 +109,53 @@ fn attributes_without_properties_stay_without() {
assert!(a.iter().all(|a| a.props.is_empty()), "{a:?}");
}
#[test]
fn many_attributes_are_written_without_comparing_every_pair_with_the_definitions() {
// #1923: a reference with N attributes, and a multileader's block content with N, of a block
// with N definitions, the tags N long ones alike up to their last characters, no attribute's
// a definition's. Looking for each attribute's definition by comparing it with every one (for
// the ATTRIB's properties, the multileader's attribute values) cost N x N comparisons of whole
// tags (many seconds here); the definitions gathered by tag once cost milliseconds.
const N: usize = 8000;
let tag = |kind: char, i: usize| format!("{}{kind}{i:05}", "T".repeat(150));
let mut d = Drawing::new_metric();
let mut blk = Block::new("TAGS");
for (h, i) in (0x100..).zip(0..N) {
blk.entities.push(Entity::new(Handle(h), EntityKind::AttDef(attrib(&tag('D', i), 0.0, AttribProps::default()))));
}
d.blocks.insert(blk.name.clone(), Arc::new(blk));
let ins = Insert {
block: "TAGS".into(),
insert: Vec3::ZERO,
scale: Vec3::new(1.0, 1.0, 1.0),
rotation: 0.0,
attribs: (0..N).map(|i| attrib(&tag('A', i), 0.0, AttribProps::default())).collect(),
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
};
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins.clone())).expect("add");
let m = MLeader {
leaders: vec![vec![Vec3::ZERO]],
landing: Vec3::new(10.0, 0.0, 0.0),
dogleg: 1.0,
text: None,
style: "Standard".into(),
arrow_size: 1.0,
spline: false,
block: Some(ins),
};
d.add(&Space::Model, Common::default(), EntityKind::MLeader(m)).expect("add");
// A version with native multileaders: R2000 writes one as a leader and a block reference.
let opts = cadcraft_io::SaveOptions { version: Some(cadcraft_io::Version::R2007), binary: false };
let t = std::time::Instant::now();
let dxf = String::from_utf8(cadcraft_io::write_with(&d, "x.dxf", &opts).expect("write")).expect("text");
assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed());
assert!(dxf.contains("MULTILEADER") && dxf.contains("ATTRIB"));
}
#[test]
fn hostile_attrib_groups_do_not_panic() {
let dxf = "0\nSECTION\n2\nENTITIES\n0\nINSERT\n5\n20\n8\n0\n66\n1\n2\nNOPE\n10\n0\n20\n0\n30\n0\n\
+22 -4
View File
@@ -1,3 +1,7 @@
use std::collections::BTreeMap;
use cadcraft_doc::TagKey;
use super::draw::entity;
use super::props::{resolve, resolve_common, transparency};
use super::text_entity::{mtext, place_text_entity};
@@ -66,6 +70,9 @@ pub(crate) fn insert(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc:
if let Some(blk) = ctx.d.block(&ins.block) {
// ATTMODE (ATTDISP) for the block's constant attributes, as for its other attributes.
let attmode = ctx.d.header.i64("ATTMODE", 1);
// The reference's attributes by tag, gathered at the first constant definition that asks
// and kept for the others and every copy.
let mut carried = None;
let cols = ins.cols.clamp(1, 10_000);
let rows = ins.rows.clamp(1, 10_000);
'copies: for r in 0..rows {
@@ -91,7 +98,7 @@ pub(crate) fn insert(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc:
// Attribute definitions inside blocks are not drawn (the reference's attributes
// are), except a constant one: its value draws with the block's geometry.
if let EntityKind::AttDef(a) = &be.kind {
if let Some(text) = constant_attribute(be, a, ins, attmode) {
if let Some(text) = constant_attribute(be, a, ins, attmode, &mut carried) {
entity(target, &sub, &text);
}
continue;
@@ -123,9 +130,20 @@ pub(crate) fn insert(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc:
/// its value, with the definition's properties. A constant value isn't copied into the reference's
/// attributes, so it is drawn from the definition. `None` for a variable definition (its attribute
/// is drawn instead), one ATTMODE hides (0 hides all, 1 the invisible ones), and one the reference
/// carries an attribute for (that attribute is drawn, not both).
fn constant_attribute(be: &Entity, a: &cadcraft_doc::Attrib, ins: &cadcraft_doc::Insert, attmode: i64) -> Option<Entity> {
if !a.constant || attmode == 0 || (a.invisible && attmode != 2) || ins.attribs.iter().any(|r| r.tag.eq_ignore_ascii_case(&a.tag)) {
/// carries an attribute for (that attribute is drawn, not both). `carried`: the reference's
/// attributes by tag, gathered here on first use so that each definition costs one lookup (#1923).
fn constant_attribute<'i>(
be: &Entity,
a: &cadcraft_doc::Attrib,
ins: &'i cadcraft_doc::Insert,
attmode: i64,
carried: &mut Option<BTreeMap<TagKey<'i>, &'i cadcraft_doc::Attrib>>,
) -> Option<Entity> {
if !a.constant
|| attmode == 0
|| (a.invisible && attmode != 2)
|| carried.get_or_insert_with(|| ins.attribs_by_tag()).contains_key(&TagKey(&a.tag))
{
return None;
}
let kind = match a.multiline_text() {
+29 -20
View File
@@ -1,6 +1,7 @@
use super::blocks::{insert, proxy, sub_ctx};
use super::dim_draw::{MAX_FILL_SOLIDS, MAX_FILL_TEXTS, block_text_box, dim_text_fill, dimension, dimension_in, solid_covers, starts_text_marks};
use super::display::{Kind, NO_LAYER, VIEWPORT_CONTENT};
use super::linetype::Layout;
use super::props::{resolve, transparency};
use super::text_entity::{mtext, place_text_entity};
use super::{
@@ -89,11 +90,11 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
};
let tol = b.opts.tolerance / ctx.xf.scale_factor().max(1e-12);
let lw = if b.opts.lineweights { lw } else { 0.0 };
// Stroke a polyline with the entity's linetype.
let stroke = |b: &mut Builder, pts: &[Vec2]| match lt.as_ref().filter(|_| b.opts.linetypes) {
// Stroke a run with the entity's linetype, laid out as `how` says.
let stroke_as = |b: &mut Builder, pts: &[Vec2], how: Layout| match lt.as_ref().filter(|_| b.opts.linetypes) {
Some(lt) => {
let min = b.opts.min_dash / ctx.xf.scale_factor().max(1e-12);
for dash in linetype::apply(pts, lt, ltscale, min) {
for dash in linetype::apply_as(pts, lt, ltscale, min, how) {
if dash.len() == 1 {
if let Some(p) = dash.first() {
b.point(ctx, rgb, *p);
@@ -104,13 +105,31 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
}
// Text and shapes embedded in the linetype (shapes when their SHX file is found).
if b.opts.text {
for sh in linetype_text::texts(ctx.d, pts, lt, ltscale, min) {
for sh in linetype_text::texts(ctx.d, pts, lt, ltscale, min, how) {
b.shaped(ctx, rgb, lw, &sh);
}
}
}
None => b.polyline(ctx, rgb, lw, pts),
};
let stroke = |b: &mut Builder, pts: &[Vec2]| stroke_as(b, pts, Layout::Open);
// A polyline's centre line: with PLINEGEN the pattern runs along the whole of it (stretched
// around a closed one from its second vertex, as AutoCAD lays it); otherwise it restarts at
// every vertex.
let centre_line = |b: &mut Builder, p: &cadcraft_doc::LwPolyline| {
let pl = Polyline { vertices: p.vertices.clone(), closed: p.closed };
if p.plinegen && p.closed {
stroke_as(b, &pl.tessellate(tol), Layout::Closed { anchor: wide::second_vertex_at(p, tol) });
} else if !b.opts.linetypes || p.plinegen || lt.is_none() {
stroke(b, &pl.tessellate(tol));
} else {
for s in pl.segments() {
let mut pts = Vec::new();
s.tessellate(tol, &mut pts);
stroke(b, &pts);
}
}
};
match &e.kind {
EntityKind::Text(t) => {
if !b.opts.text {
@@ -180,22 +199,11 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
}
}
} else {
let pl = Polyline { vertices: p.vertices.clone(), closed: p.closed };
stroke(b, &pl.tessellate(tol));
}
}
EntityKind::LwPolyline(p) => {
let pl = Polyline { vertices: p.vertices.clone(), closed: p.closed };
if !b.opts.linetypes || p.plinegen || lt.is_none() {
stroke(b, &pl.tessellate(tol));
} else {
for s in pl.segments() {
let mut pts = Vec::new();
s.tessellate(tol, &mut pts);
stroke(b, &pts);
}
// Fill off: the centre line, dashed as a polyline without width is.
centre_line(b, p);
}
}
EntityKind::LwPolyline(p) => centre_line(b, p),
EntityKind::Solid(s) | EntityKind::Trace(s) => {
let c = &s.corners;
let q = [c[0].xy(), c[1].xy(), c[3].xy(), c[2].xy()];
@@ -249,15 +257,16 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
s.tessellate(tol, &mut pts);
stroke(b, &pts);
}
// Closed runs from angle 0 (or the ellipse's start parameter).
Prim::Circle(c) => {
let mut pts = Vec::new();
c.tessellate(tol, &mut pts);
stroke(b, &pts);
stroke_as(b, &pts, Layout::Closed { anchor: 0.0 });
}
Prim::Ellipse(el) => {
let mut pts = Vec::new();
el.tessellate(tol, &mut pts);
stroke(b, &pts);
stroke_as(b, &pts, if el.is_full() { Layout::Closed { anchor: 0.0 } } else { Layout::Open });
}
Prim::Spline(s) => stroke(b, &s.tessellate(tol)),
Prim::Point(p) => b.point(ctx, rgb, p),
+392 -101
View File
@@ -1,117 +1,255 @@
//! Apply a dash pattern along a polyline.
//! Apply a dash pattern along a run (a polyline), laid out as AutoCAD lays it out.
//!
//! Measured on AutoCAD 2024 plots (DWG To PDF at a fixed scale, every stroke read back), with the
//! pattern [2, -1] unless said otherwise:
//! - An open run (a line, an arc, a spline, an open polyline with PLINEGEN, each segment of one
//! without) shorter than one period is drawn continuous. Otherwise the pattern is centred:
//! with n = floor(L / period) and p0 = (n·period + first − L) / 2, the elements sit where they
//! would if the pattern started at −p0, except that the first dash starts at the run's start
//! and the last ends at its end. A line 7 long gets [0, 1.5] [2.5, 4.5] [5.5, 7]; 6 gets
//! [0, 1] [2, 4] [5, 6]; 5.99 gets [0, 2.495] [3.495, 5.99]; 2.99 is continuous. A pattern
//! opening with a dot puts dots at both ends ([0, −1] on 5.3: 0, 1.15, 2.15, 3.15, 4.15, 5.3).
//! - A closed run (a circle, a whole ellipse, a closed polyline with PLINEGEN) is stretched to
//! n = round(L / period) periods, one starting at its anchor: a circle of radius 2 is dashed
//! 0°–60°, 90°–150°…; a 5 × 5 square polyline gets 7 periods.
//! - A pattern opening with a gap (e0 < 0), with r = L − n·period and x = (r + e0) / 2: for
//! x < 0 the elements run from −p0; otherwise a piece [0, x] is drawn (a dot when x is 0),
//! then the elements from the period's second on, n − 1 whole periods, and a last piece 2x
//! long.
use cadcraft_doc::Linetype;
use cadcraft_geom::Vec2;
/// Split `pts` into dashes. Dots come back as single-point runs. When the scaled pattern is
/// shorter than `min_pattern` (sub-pixel), the polyline is returned whole.
pub fn apply(pts: &[Vec2], lt: &Linetype, scale: f64, min_pattern: f64) -> Vec<Vec<Vec2>> {
/// How a run lays its pattern out (see the module notes).
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Layout {
/// Centred on an open run.
Open,
/// Stretched around a closed run, a period starting `anchor` along it.
Closed { anchor: f64 },
}
/// Most periods a run is dashed over in a display build (`min_pattern` above 0, a view zoomed out
/// a lot); a longer run is drawn continuous. A plot or export has no zoom (`min_pattern` is 0), so
/// it keeps the pattern, bounded by [`MAX_ELEMENTS`] (#1069).
const MAX_PERIODS: f64 = 50_000.0;
/// Most pattern elements a run is laid out over (a long pattern repeated many times); beyond
/// that it is drawn continuous too.
const MAX_ELEMENTS: f64 = 2_000_000.0;
/// The drawn stretches of a run `len` long, as (start, end) along it (a dot: start == end), in
/// order; `None` when it is drawn continuous (shorter than one period, or repeating too often).
/// `pattern` is scaled; `min_pattern` is the caller's (see [`MAX_PERIODS`]).
fn layout(len: f64, pattern: &[f64], how: Layout, min_pattern: f64) -> Option<Vec<(f64, f64)>> {
let period: f64 = pattern.iter().map(|d| d.abs()).sum();
if !(len.is_finite() && period > 1e-12) || len < period || (min_pattern > 0.0 && len / period > MAX_PERIODS) {
return None;
}
if (len / period + 2.0) * pattern.len() as f64 > MAX_ELEMENTS {
return None;
}
let mut drawn = Vec::new();
let mut at = 0.0;
for &d in pattern {
if d >= 0.0 {
drawn.push((at, d));
}
at += d.abs();
}
if drawn.is_empty() {
return Some(Vec::new());
}
let first = pattern.first().copied().unwrap_or(0.0);
let out = match how {
Layout::Closed { anchor } => {
let n = (len / period).round().max(1.0);
let f = len / (n * period);
let a = if anchor.is_finite() { anchor.rem_euclid(period * f) } else { 0.0 };
let mut out = Vec::new();
for k in -1..=(n as i64) {
for &(o, e) in &drawn {
let s0 = a + k as f64 * period * f + o * f;
let s1 = s0 + e * f;
if e == 0.0 {
if (0.0..len).contains(&s0) {
out.push((s0, s0));
}
} else if s1.min(len) > s0.max(0.0) {
out.push((s0.max(0.0), s1.min(len)));
}
}
}
out
}
Layout::Open if first < 0.0 => gap_first(len, pattern, period),
Layout::Open => {
// A length at a multiple of the period: 6.0 / 3 is 2, not 1.
let n = (len / period + 1e-9).floor();
let p0 = (n * period + first - len) / 2.0;
let count = n as usize * drawn.len() + 1;
let mut out = Vec::with_capacity(count);
for i in 0..count {
let Some(&(o, e)) = drawn.get(i % drawn.len()) else { continue };
let mut s0 = (i / drawn.len()) as f64 * period + o - p0;
let mut s1 = s0 + e;
if i == 0 {
s0 = 0.0;
if first == 0.0 {
s1 = 0.0;
}
}
if i + 1 == count {
s1 = len;
if first == 0.0 {
s0 = len;
}
}
out.push((s0, s1));
}
out
}
};
Some(out)
}
/// [`layout`] of an open run for a pattern opening with a gap.
fn gap_first(len: f64, pattern: &[f64], period: f64) -> Vec<(f64, f64)> {
let first = pattern.first().copied().unwrap_or(0.0);
let n = (len / period + 1e-9).floor();
let x = (len - n * period + first) / 2.0;
let mut out = Vec::new();
if x < 0.0 {
let p0 = (n * period + first - len) / 2.0;
let mut u = 0.0;
for _ in 0..(n as usize + 2) {
for &e in pattern {
let (a, b) = (u, u + e.abs());
u = b;
if e < 0.0 {
continue;
}
let b = b.min(p0 + len);
if b > a.max(p0) || (e == 0.0 && (p0..=p0 + len).contains(&a)) {
out.push((a.max(p0) - p0, b - p0));
}
}
}
} else {
out.push((0.0, x));
let mut pos = x;
let whole = pattern.iter().cycle().take(pattern.len() * (n as usize).saturating_sub(1));
for &e in pattern.iter().skip(1).chain(whole) {
if e >= 0.0 {
out.push((pos, pos + e));
}
pos += e.abs();
}
if x > 0.0 {
out.push((pos, (pos + 2.0 * x).min(len)));
}
}
out.sort_by(|a, b| a.0.total_cmp(&b.0));
out
}
/// Length of a polyline.
fn length(pts: &[Vec2]) -> f64 {
pts.windows(2).map(|w| w.first().zip(w.get(1)).map(|(a, b)| a.dist(*b)).unwrap_or(0.0)).sum()
}
/// The pattern scaled, or `None` when a run is drawn continuous at any length: no pattern, or one
/// shorter than `min_pattern` (sub-pixel).
fn scaled(lt: &Linetype, scale: f64, min_pattern: f64) -> Option<Vec<f64>> {
let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 };
let total = lt.pattern_length() * scale;
if pts.len() < 2 || total <= 1e-12 || total < min_pattern {
return vec![pts.to_vec()];
}
// Guard against huge dash counts (zoomed out a lot): fall back to continuous.
let len: f64 = pts.windows(2).map(|w| w.first().zip(w.get(1)).map(|(a, b)| a.dist(*b)).unwrap_or(0.0)).sum();
if len / total > 50_000.0 {
return vec![pts.to_vec()];
}
let pattern: Vec<f64> = lt.pattern.iter().map(|d| d.length * scale).collect();
// AutoCAD centres the pattern so lines start and end with a dash: start at half the first dash.
let mut out: Vec<Vec<Vec2>> = Vec::new();
let mut cur: Vec<Vec2> = Vec::new();
let mut idx = 0usize;
let first = pattern.first().copied().unwrap_or(0.0);
let mut remaining = if first > 0.0 { first } else { first.abs() };
let mut on = first >= 0.0;
if on && first == 0.0 {
if let Some(p) = pts.first() {
out.push(vec![*p]);
}
idx = 1 % pattern.len();
let n = pattern.get(idx).copied().unwrap_or(0.0);
remaining = n.abs();
on = n > 0.0;
}
if on && let Some(p) = pts.first() {
cur.push(*p);
}
let mut guard = 0usize;
(total > 1e-12 && total >= min_pattern).then(|| lt.pattern.iter().map(|d| d.length * scale).collect())
}
/// The pieces of `pts` over `ranges` (in order along it), a dot as a single point.
fn cut(pts: &[Vec2], ranges: &[(f64, f64)]) -> Vec<Vec<Vec2>> {
let mut cum = Vec::with_capacity(pts.len());
let mut acc = 0.0;
cum.push(0.0);
for w in pts.windows(2) {
let (Some(&a), Some(&b)) = (w.first(), w.get(1)) else { continue };
let seg = a.dist(b);
if seg <= 1e-15 {
acc += w.first().zip(w.get(1)).map(|(a, b)| a.dist(*b)).unwrap_or(0.0);
cum.push(acc);
}
let last = pts.len().saturating_sub(1).max(1);
// The point `s` along, and the index of the first vertex past it.
let at = |s: f64| -> (Vec2, usize) {
let j = cum.partition_point(|&c| c <= s).clamp(1, last);
let (Some(&a), Some(&b), Some(&ca), Some(&cb)) = (pts.get(j - 1), pts.get(j), cum.get(j - 1), cum.get(j)) else {
return (pts.first().copied().unwrap_or(Vec2::ZERO), j);
};
let t = if cb > ca { ((s - ca) / (cb - ca)).clamp(0.0, 1.0) } else { 0.0 };
(a + (b - a) * t, j)
};
let mut out = Vec::with_capacity(ranges.len());
for &(s0, s1) in ranges {
let (p, j) = at(s0);
if s1 <= s0 {
out.push(vec![p]);
continue;
}
let dir = (b - a) / seg;
let mut pos = 0.0;
while seg - pos > remaining {
guard += 1;
if guard > 2_000_000 {
return vec![pts.to_vec()];
}
pos += remaining;
let p = a + dir * pos;
if on {
cur.push(p);
out.push(std::mem::take(&mut cur));
}
idx = (idx + 1) % pattern.len();
let n = pattern.get(idx).copied().unwrap_or(0.0);
if n == 0.0 {
out.push(vec![p]);
idx = (idx + 1) % pattern.len();
let n2 = pattern.get(idx).copied().unwrap_or(0.0);
remaining = n2.abs();
on = n2 > 0.0;
} else {
remaining = n.abs();
on = n > 0.0;
}
if on {
cur.push(p);
let mut piece = vec![p];
let mut k = j;
while let (Some(&c), Some(&q)) = (cum.get(k), pts.get(k)) {
if c >= s1 {
break;
}
piece.push(q);
k += 1;
}
remaining -= seg - pos;
if on {
cur.push(b);
}
}
if cur.len() >= 2 {
out.push(cur);
piece.push(at(s1).0);
out.push(piece);
}
out
}
/// The dashes of the pattern along a run of length `len`, as (start, end) distances; a dot has
/// start == end. Laid out like [`apply`]. `None` when the run is drawn continuous: the scaled
/// pattern is shorter than `min_pattern` or would repeat too often.
pub fn ranges(len: f64, lt: &Linetype, scale: f64, min_pattern: f64) -> Option<Vec<(f64, f64)>> {
let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 };
let total = lt.pattern_length() * scale;
if !(len.is_finite() && len > 0.0) || total <= 1e-12 || total < min_pattern || len / total > 50_000.0 {
return None;
/// Split `pts`, an open run, into dashes. Dots come back as single-point runs. A run shorter than
/// one period, or with a scaled pattern shorter than `min_pattern` (sub-pixel), comes back whole.
pub fn apply(pts: &[Vec2], lt: &Linetype, scale: f64, min_pattern: f64) -> Vec<Vec<Vec2>> {
apply_as(pts, lt, scale, min_pattern, Layout::Open)
}
/// [`apply`] with the run laid out as `how` says.
pub fn apply_as(pts: &[Vec2], lt: &Linetype, scale: f64, min_pattern: f64, how: Layout) -> Vec<Vec<Vec2>> {
let laid = if pts.len() >= 2 { scaled(lt, scale, min_pattern).and_then(|p| layout(length(pts), &p, how, min_pattern)) } else { None };
match laid {
Some(r) => cut(pts, &r),
None => vec![pts.to_vec()],
}
let mut out = Vec::new();
let mut pos = 0.0;
// Gap-only patterns draw nothing, matching `apply`, without walking every repeat.
if !lt.pattern.iter().any(|d| d.length >= 0.0) {
return Some(Vec::new());
}
// Bound the pattern elements visited, independent of emitted ranges, so a pattern that emits
// little still cannot cycle hundreds of millions of times.
let mut visits: u64 = 0;
for d in lt.pattern.iter().map(|d| d.length * scale).cycle() {
visits += 1;
if pos >= len || out.len() > 2_000_000 || visits > 4_000_000 {
break;
}
/// The dashes of the pattern along a run of length `len` laid out as `how` says, as (start, end)
/// distances; a dot has start == end. Laid out like [`apply_as`]. `None` when the run is drawn
/// continuous: shorter than one period, a scaled pattern shorter than `min_pattern`, or too many
/// repeats (see [`MAX_PERIODS`]).
pub fn ranges(len: f64, lt: &Linetype, scale: f64, min_pattern: f64, how: Layout) -> Option<Vec<(f64, f64)>> {
if len > 0.0 { scaled(lt, scale, min_pattern).and_then(|p| layout(len, &p, how, min_pattern)) } else { None }
}
/// Where the pattern starts on a run `len` long laid out as `how`, and how much it is stretched:
/// period `k` starts at `start + k · period · stretch`. `None` when the run is drawn continuous.
pub fn phase(len: f64, lt: &Linetype, scale: f64, min_pattern: f64, how: Layout) -> Option<(f64, f64)> {
let pattern = scaled(lt, scale, min_pattern)?;
let period: f64 = pattern.iter().map(|d| d.abs()).sum();
layout(len, &pattern, how, min_pattern)?;
let first = pattern.first().copied().unwrap_or(0.0);
Some(match how {
Layout::Open => {
let n = (len / period + 1e-9).floor();
let x = (len - n * period + first) / 2.0;
// A gap-first pattern with room for a piece of dash at the start ([`gap_first`]) has
// its second element at `x`, a gap after its period starts.
(if first < 0.0 && x >= 0.0 { x + first } else { x - first }, 1.0)
}
if d >= 0.0 {
out.push((pos, (pos + d).min(len)));
Layout::Closed { anchor } => {
let f = len / ((len / period).round().max(1.0) * period);
(if anchor.is_finite() { anchor.rem_euclid(period * f) } else { 0.0 }, f)
}
pos += d.abs();
}
Some(out)
})
}
#[cfg(test)]
@@ -122,7 +260,7 @@ mod tests {
#[test]
fn an_all_gap_pattern_draws_nothing_without_spinning() {
let lt = Linetype::simple("GAPS", "", &[-0.001, -0.002]);
assert_eq!(ranges(1.0, &lt, 1.0, 0.0), Some(Vec::new()));
assert_eq!(ranges(1.0, &lt, 1.0, 0.0, Layout::Open), Some(Vec::new()));
assert!(apply(&[Vec2::ZERO, Vec2::new(1.0, 0.0)], &lt, 1.0, 0.0).is_empty());
}
@@ -130,10 +268,11 @@ mod tests {
fn dashes_split_line() {
let lt = Linetype::simple("DASHED", "", &[0.5, -0.25]);
let d = apply(&[Vec2::ZERO, Vec2::new(3.0, 0.0)], &lt, 1.0, 0.0);
// 3.0 / 0.75 = 4 patterns → 4 dashes.
assert_eq!(d.len(), 4);
assert!((d[0][1].x - 0.5).abs() < 1e-9);
assert!((d[1][0].x - 0.75).abs() < 1e-9);
// 3.0 / 0.75 = 4 periods, centred: a half dash at each end and four whole ones between.
assert_eq!(d.len(), 5);
assert!((d[0][1].x - 0.25).abs() < 1e-9);
assert!((d[1][0].x - 0.5).abs() < 1e-9);
assert!((d[4][0].x - 2.75).abs() < 1e-9 && (d[4][1].x - 3.0).abs() < 1e-9);
}
#[test]
@@ -157,4 +296,156 @@ mod tests {
let d = apply(&[Vec2::ZERO, Vec2::new(0.3, 0.0), Vec2::new(0.3, 1.0)], &lt, 1.0, 0.0);
assert_eq!(d[0].len(), 3); // the first dash turns the corner
}
/// The drawn stretches of a run, a continuous one as one stretch, with stretches that touch
/// joined (a plot draws them as one stroke).
fn drawn(len: f64, pattern: &[f64], how: Layout) -> Vec<(f64, f64)> {
let mut out: Vec<(f64, f64)> = Vec::new();
for (a, b) in layout(len, pattern, how, 0.0).unwrap_or_else(|| vec![(0.0, len)]) {
match out.last_mut() {
Some(last) if (last.1 - a).abs() < 1e-9 && b > a && last.1 > last.0 => last.1 = b,
_ => out.push((a, b)),
}
}
out
}
fn near(got: &[(f64, f64)], want: &[(f64, f64)], tol: f64) -> bool {
got.len() == want.len() && got.iter().zip(want).all(|(g, w)| (g.0 - w.0).abs() <= tol && (g.1 - w.1).abs() <= tol)
}
/// AutoCAD 2024 plots (DWG To PDF at 10:1, every stroke read back to 0.01): open runs.
#[test]
fn open_runs_are_laid_out_as_autocad_plots_them() {
let dut = [2.0, -1.0];
for (len, want) in [
(7.0, vec![(0.0, 1.5), (2.5, 4.5), (5.5, 7.0)]),
(6.0, vec![(0.0, 1.0), (2.0, 4.0), (5.0, 6.0)]),
(5.99, vec![(0.0, 2.495), (3.495, 5.99)]),
(2.99, vec![(0.0, 2.99)]),
] {
assert!(near(&drawn(len, &dut, Layout::Open), &want, 1e-9), "{len}: {:?}", drawn(len, &dut, Layout::Open));
}
// A pattern opening with a dot: dots at both ends.
let dots = drawn(5.3, &[0.0, -1.0], Layout::Open);
assert!(near(&dots, &[(0.0, 0.0), (1.15, 1.15), (2.15, 2.15), (3.15, 3.15), (4.15, 4.15), (5.3, 5.3)], 1e-9), "{dots:?}");
// Patterns opening with a gap.
let (h1, h2, h3, h4) = ([-1.0, 2.0], [-0.5, 2.0, -0.5], [-1.0, 2.0, -2.0, 1.0], [-2.0, 1.0]);
let table: [(&[f64], f64, &[(f64, f64)]); 33] = [
(&h1, 3.0, &[(1.5, 3.0)]),
(&h1, 3.5, &[(1.75, 3.5)]),
(&h1, 4.0, &[(0.0, 0.0), (0.0, 2.0)]),
(&h1, 4.5, &[(0.0, 2.75)]),
(&h1, 5.0, &[(0.0, 3.5)]),
(&h1, 5.5, &[(0.0, 4.25)]),
(&h1, 6.0, &[(1.5, 3.5), (4.5, 6.0)]),
(&h1, 6.5, &[(1.75, 3.75), (4.75, 6.5)]),
(&h1, 7.0, &[(0.0, 0.0), (0.0, 2.0), (3.0, 5.0)]),
(&h1, 7.5, &[(0.0, 2.25), (3.25, 5.75)]),
(&h1, 8.0, &[(0.0, 2.5), (3.5, 6.5)]),
(&h1, 9.0, &[(1.5, 3.5), (4.5, 6.5), (7.5, 9.0)]),
(&h1, 10.0, &[(0.0, 0.0), (0.0, 2.0), (3.0, 5.0), (6.0, 8.0)]),
(&h1, 11.0, &[(0.0, 2.5), (3.5, 5.5), (6.5, 9.5)]),
(&h1, 12.5, &[(1.75, 3.75), (4.75, 6.75), (7.75, 9.75), (10.75, 12.5)]),
(&h1, 1.0, &[(0.0, 1.0)]),
(&h1, 2.0, &[(0.0, 2.0)]),
(&h1, 2.5, &[(0.0, 2.5)]),
(&h1, 2.9, &[(0.0, 2.9)]),
(&h2, 4.0, &[(0.0, 2.25), (2.75, 3.25)]),
(&h2, 5.0, &[(0.0, 2.75), (3.25, 4.75)]),
(&h2, 6.0, &[(0.75, 2.75), (3.75, 5.75)]),
(&h2, 7.0, &[(0.0, 2.25), (3.25, 5.25), (5.75, 6.25)]),
(&h2, 8.0, &[(0.0, 2.75), (3.75, 5.75), (6.25, 7.75)]),
(&h3, 10.0, &[(0.0, 3.5), (5.5, 9.5)]),
(&h3, 13.0, &[(0.0, 0.0), (0.0, 2.0), (4.0, 5.0), (6.0, 8.0), (10.0, 11.0)]),
(&h3, 15.5, &[(0.0, 3.25), (5.25, 6.25), (7.25, 9.25), (11.25, 14.75)]),
(&h4, 7.0, &[(3.5, 4.5), (6.5, 7.0)]),
(&h4, 8.0, &[(0.0, 0.0), (0.0, 1.0), (3.0, 4.0)]),
(&h4, 10.0, &[(3.5, 4.5), (6.5, 7.5), (9.5, 10.0)]),
(&h4, 2.0, &[(0.0, 2.0)]),
(&h2, 2.9, &[(0.0, 2.9)]),
(&h3, 5.9, &[(0.0, 5.9)]),
];
for (pattern, len, want) in table {
let got = drawn(len, pattern, Layout::Open);
assert!(near(&got, want, 0.006), "{pattern:?} on {len}: {got:?}");
}
}
/// Text in a linetype follows [`phase`]: it must say where the periods of a gap-first pattern
/// start on each side of the room left for a piece of dash at the start.
#[test]
fn phase_follows_the_dashes_of_a_gap_first_pattern() {
let lt = Linetype::simple("GF", "", &[-1.0, 2.0]);
for len in [6.5, 7.0, 7.5, 8.9, 12.5] {
let (start, f) = phase(len, &lt, 1.0, 0.0, Layout::Open).unwrap();
assert_eq!(f, 1.0);
// Every whole dash starts a gap (1) after a period (3) starts.
let whole: Vec<f64> =
ranges(len, &lt, 1.0, 0.0, Layout::Open).unwrap().into_iter().filter(|(a, b)| (b - a - 2.0).abs() < 1e-9).map(|(a, _)| a).collect();
assert!(!whole.is_empty(), "{len}");
for a in whole {
let k = (a - 1.0 - start) / 3.0;
assert!((k - k.round()).abs() < 1e-9, "{len}: a dash at {a}, periods from {start}");
}
}
}
/// Closed runs on the same plots: stretched to round(L / period) periods from their anchor.
#[test]
fn closed_runs_are_stretched_as_autocad_plots_them() {
let dut = [2.0, -1.0];
// A circle of radius 2 from angle 0: 0°–60°, 90°–150°, 180°–240°, 270°–330°.
let r = 2.0;
let got = drawn(std::f64::consts::TAU * r, &dut, Layout::Closed { anchor: 0.0 });
let want: Vec<(f64, f64)> =
[(0.0, 60.0), (90.0, 150.0), (180.0, 240.0), (270.0, 330.0)].map(|(a, b): (f64, f64)| (a.to_radians() * r, b.to_radians() * r)).into();
assert!(near(&got, &want, 1e-9), "{got:?}");
// Rectangles (PLINEGEN, closed), anchored at the second vertex: 4 × 4 has 5 periods of 3.2
// from s = 0.8, 5 × 5 has 7 (round, not floor) from 2.143, 2 × 3 from 2.0, 3 × 3 from 0.
for (w, h, periods, start) in [(4.0, 4.0, 5.0, 0.8), (5.0, 5.0, 7.0, 2.0 + 1.0 / 7.0), (2.0, 3.0, 3.0, 2.0), (3.0, 3.0, 4.0, 0.0)] {
let len = 2.0 * (w + h);
let got = drawn(len, &dut, Layout::Closed { anchor: w });
let dash = 2.0 * len / (3.0 * periods);
assert!(got.iter().any(|r| (r.0 - start).abs() < 1e-9 && (r.1 - r.0 - dash).abs() < 1e-9), "{w}×{h}: {got:?}");
}
}
/// A pattern too long for the run draws it continuous.
#[test]
fn a_run_shorter_than_one_period_is_continuous() {
let lt = Linetype::simple("DASHED", "", &[2.0, -1.0]);
assert_eq!(apply(&[Vec2::ZERO, Vec2::new(2.99, 0.0)], &lt, 1.0, 0.0).len(), 1);
assert_eq!(ranges(2.99, &lt, 1.0, 0.0, Layout::Open), None);
}
/// A long pattern repeated many times is drawn continuous rather than laid out element by
/// element: 100 elements over 40,000 periods is past the cap, 400 periods is not.
#[test]
fn a_long_pattern_repeated_too_often_is_continuous() {
let pattern: Vec<f64> = (0..100).map(|i| if i % 2 == 0 { 0.001 } else { -0.001 }).collect();
let lt = Linetype::simple("MANY", "", &pattern);
for how in [Layout::Open, Layout::Closed { anchor: 0.0 }] {
assert_eq!(ranges(4000.0, &lt, 1.0, 0.0, how), None, "{how:?}");
assert!(ranges(40.0, &lt, 1.0, 0.0, how).is_some_and(|r| r.len() > 10_000), "{how:?}");
}
}
/// A plot or export keeps the dashes of a run more than 50,000 periods long; a display build,
/// with a level of detail, draws it continuous (#1069).
#[test]
fn a_plot_keeps_the_dashes_of_a_run_of_many_periods() {
let lt = Linetype::simple("DASHED", "", &[0.5, -0.25]);
let len = 50_001.0 * 0.75;
// Centred, the first and last dashes are halves: one more dash than periods.
for (how, dashes) in [(Layout::Open, 50_002), (Layout::Closed { anchor: 0.0 }, 50_001)] {
assert_eq!(ranges(len, &lt, 1.0, 0.0, how).map(|r| r.len()), Some(dashes), "{how:?}");
assert_eq!(ranges(len, &lt, 1.0, 1e-9, how), None, "{how:?}");
// Where linetype texts are placed from.
assert!(phase(len, &lt, 1.0, 0.0, how).is_some(), "{how:?}");
assert_eq!(phase(len, &lt, 1.0, 1e-9, how), None, "{how:?}");
}
let pts = [Vec2::ZERO, Vec2::new(len, 0.0)];
assert_eq!(apply(&pts, &lt, 1.0, 0.0).len(), 50_002);
assert_eq!(apply(&pts, &lt, 1.0, 1e-9).len(), 1);
}
}
+32 -22
View File
@@ -4,7 +4,8 @@
//! A dash element may carry a text (DXF `74` bit 2, `9` string) or a shape (`74` bit 4, `75`
//! shape number). As in a `.lin` definition, where the bracketed text or shape follows the dash
//! or gap that carries it, it is placed where that element ends, at every repeat of the pattern
//! (laid out from the start of the run like [`crate::linetype::apply`]):
//! (laid out on the run as [`crate::linetype::apply_as`] lays out its dashes, so none on a run
//! drawn continuous):
//! - height: the element's scale (`46`), times the text style's fixed height when it has one,
//! times the linetype scale;
//! - origin: the anchor shifted by the X/Y offsets (`44`/`45`, times the linetype scale) along
@@ -22,6 +23,8 @@ use cadcraft_doc::{Drawing, Linetype};
use cadcraft_fonts::{Shaped, TextParams};
use cadcraft_geom::Vec2;
use crate::linetype::Layout;
/// Upper bound on the texts and shapes drawn along one run (hostile scales; `apply` caps the
/// dashes).
const MAX_TEXTS: usize = 10_000;
@@ -47,8 +50,8 @@ struct Element {
/// The texts and shapes of `lt` along the polyline `pts`, in the coordinates of `pts`. Empty
/// when the linetype has none or its scaled pattern is drawn continuous (shorter than
/// `min_pattern`, or repeating too often).
pub fn texts(d: &Drawing, pts: &[Vec2], lt: &Linetype, scale: f64, min_pattern: f64) -> Vec<Shaped> {
/// `min_pattern`, or, in a display build, repeating too often: see [`crate::linetype::phase`]).
pub fn texts(d: &Drawing, pts: &[Vec2], lt: &Linetype, scale: f64, min_pattern: f64, how: Layout) -> Vec<Shaped> {
let mut out = Vec::new();
if pts.len() < 2 || !lt.pattern.iter().any(|e| e.text.as_deref().is_some_and(|t| !t.trim().is_empty()) || e.shape.is_some()) {
return out;
@@ -56,20 +59,25 @@ pub fn texts(d: &Drawing, pts: &[Vec2], lt: &Linetype, scale: f64, min_pattern:
let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 };
let total = lt.pattern_length() * scale;
let len: f64 = pts.windows(2).map(|w| w.first().zip(w.get(1)).map(|(a, b)| a.dist(*b)).unwrap_or(0.0)).sum();
if !(total.is_finite() && total > 1e-12 && len.is_finite()) || total < min_pattern || len / total > 50_000.0 {
if !(total.is_finite() && total > 1e-12 && len.is_finite()) || total < min_pattern {
return out;
}
let elements = elements(d, lt, scale);
let Some((start, stretch)) = crate::linetype::phase(len, lt, scale, min_pattern, how) else { return out };
if elements.is_empty() {
return out;
}
let mut walk = Walk { pts, i: 0, start: 0.0 };
let mut points_left = MAX_TEXT_POINTS;
let mut base = 0.0;
// From the period before the run's start (a centred or anchored pattern starts before it).
let mut base = start - total * stretch;
let mut points = 0usize;
'repeats: while base <= len {
for el in &elements {
let s = base + el.at;
let s = base + el.at * stretch;
if s < 0.0 {
continue;
}
points = points.saturating_add(point_count(&el.local));
if s > len + 1e-9 || out.len() >= MAX_TEXTS || points > MAX_POINTS {
break 'repeats;
@@ -83,7 +91,7 @@ pub fn texts(d: &Drawing, pts: &[Vec2], lt: &Linetype, scale: f64, min_pattern:
sh.map(|q| origin + q.rotate(rot));
out.push(sh);
}
base += total;
base += total * stretch;
}
out
}
@@ -219,20 +227,20 @@ mod tests {
#[test]
fn one_text_per_repeat_at_the_end_of_its_element() {
let d = Drawing::new_imperial();
let t = texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &gas(), 1.0, 0.0);
// Pattern 0.95 long: anchors at 0.7 and 1.65.
let t = texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &gas(), 1.0, 0.0, Layout::Open);
// Pattern 0.95 long, centred on the 2.0 run (p0 = 0.2): anchors at 0.7 − 0.2 and 1.65 − 0.2.
assert_eq!(t.len(), 2);
let x = starts(&t);
assert!(x[0] >= 0.69 && x[0] < 0.75, "{x:?}");
assert!(x[1] >= 1.64 && x[1] < 1.70, "{x:?}");
assert!(x[0] >= 0.49 && x[0] < 0.55, "{x:?}");
assert!(x[1] >= 1.44 && x[1] < 1.50, "{x:?}");
}
#[test]
fn no_text_when_drawn_continuous() {
let d = Drawing::new_imperial();
assert!(texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &gas(), 1.0, 5.0).is_empty());
assert!(texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &gas(), 1.0, 5.0, Layout::Open).is_empty());
let plain = Linetype::simple("DASHED", "", &[0.5, -0.25]);
assert!(texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &plain, 1.0, 0.0).is_empty());
assert!(texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &plain, 1.0, 0.0, Layout::Open).is_empty());
}
/// A long label repeated along a long run stops at the point allowance, well before MAX_TEXTS.
@@ -242,7 +250,7 @@ mod tests {
let mut lt = gas();
lt.pattern[1].text = Some("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM".into());
// 0.95 per repeat over 9,000: about 9,500 repeats, under the 50,000 the run is drawn for.
let t = texts(&d, &[Vec2::ZERO, Vec2::new(9_000.0, 0.0)], &lt, 1.0, 0.0);
let t = texts(&d, &[Vec2::ZERO, Vec2::new(9_000.0, 0.0)], &lt, 1.0, 0.0, Layout::Open);
let points: usize =
t.iter().map(|s| s.strokes.iter().map(Vec::len).sum::<usize>() + s.glyphs.iter().flatten().map(Vec::len).sum::<usize>()).sum();
assert!(!t.is_empty() && t.len() < MAX_TEXTS, "{}", t.len());
@@ -272,26 +280,28 @@ mod tests {
register_shapes();
let d = Drawing::new_imperial();
// An unnamed shape-file style reads as its file name (DXF); scale 0.1 per vector unit.
let t = texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &fence("cadcraft-render-lt.shx"), 1.0, 0.0);
let t = texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &fence("cadcraft-render-lt.shx"), 1.0, 0.0, Layout::Open);
// Laid out as the text above: the 0.95 pattern centred on the 2.0 run, anchors at 0.7 − 0.2
// and 1.65 − 0.2.
assert_eq!(t.len(), 2);
let x = starts(&t);
assert!((x[0] - 0.7).abs() < 1e-9 && (x[1] - 1.65).abs() < 1e-9, "{x:?}");
assert!((x[0] - 0.5).abs() < 1e-9 && (x[1] - 1.45).abs() < 1e-9, "{x:?}");
let ys = t[0].strokes.iter().flatten().fold((f64::MAX, f64::MIN), |(a, b), p| (a.min(p.y), b.max(p.y)));
assert!((ys.0).abs() < 1e-9 && (ys.1 - 0.2).abs() < 1e-9, "{ys:?}");
// Along a vertical line the shape turns with it; absolute rotation keeps it level.
let t = texts(&d, &[Vec2::ZERO, Vec2::new(0.0, 2.0)], &fence("cadcraft-render-lt.shx"), 2.0, 0.0);
let t = texts(&d, &[Vec2::ZERO, Vec2::new(0.0, 2.0)], &fence("cadcraft-render-lt.shx"), 2.0, 0.0, Layout::Open);
assert_eq!(t.len(), 1);
let xs = t[0].strokes.iter().flatten().fold((f64::MAX, f64::MIN), |(a, b), p| (a.min(p.x), b.max(p.x)));
assert!((xs.0 + 0.4).abs() < 1e-9 && xs.1.abs() < 1e-9, "{xs:?}");
// A named style whose font is the shape file.
let mut d = Drawing::new_imperial();
d.text_styles.push(cadcraft_doc::TextStyle { name: "SHAPES".into(), font: "cadcraft-render-lt.shx".into(), ..Default::default() });
assert_eq!(texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &fence("SHAPES"), 1.0, 0.0).len(), 2);
assert_eq!(texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &fence("SHAPES"), 1.0, 0.0, Layout::Open).len(), 2);
// A shape file that isn't found, or a shape it lacks, draws nothing.
assert!(texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &fence("cadcraft-no-such-file.shx"), 1.0, 0.0).is_empty());
assert!(texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &fence("cadcraft-no-such-file.shx"), 1.0, 0.0, Layout::Open).is_empty());
let mut lt = fence("cadcraft-render-lt.shx");
lt.pattern[1].shape = Some(131);
assert!(texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &lt, 1.0, 0.0).is_empty());
assert!(texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &lt, 1.0, 0.0, Layout::Open).is_empty());
}
#[test]
@@ -304,7 +314,7 @@ mod tests {
let mut lt = fence("cadcraft-render-big.shx");
lt.pattern[1].shape = Some(131);
// 3,000 repeats would hold about 3 million points.
let t = texts(&d, &[Vec2::ZERO, Vec2::new(2850.0, 0.0)], &lt, 1.0, 0.0);
let t = texts(&d, &[Vec2::ZERO, Vec2::new(2850.0, 0.0)], &lt, 1.0, 0.0, Layout::Open);
let points: usize = t.iter().map(point_count).sum();
assert!(!t.is_empty() && t.len() < 3000 && points <= MAX_POINTS, "{} shapes, {points} points", t.len());
}
@@ -345,7 +355,7 @@ mod tests {
}
let pts = [Vec2::ZERO, Vec2::ZERO, Vec2::new(1e6, 0.0), Vec2::new(1e6, 0.0)];
for scale in [f64::NAN, 0.0, -1.0, 1e-9, 1e300] {
let t = texts(&d, &pts, &lt, scale, 0.0);
let t = texts(&d, &pts, &lt, scale, 0.0, Layout::Open);
assert!(t.len() <= MAX_TEXTS);
}
}
+26
View File
@@ -940,6 +940,32 @@ fn a_constant_attribute_definition_draws_its_value_with_the_reference() {
assert_eq!(drawn_above_line(constant(false), vec![own], 1, at).len(), pts.len());
}
#[test]
fn many_constant_definitions_are_matched_to_the_attributes_without_comparing_every_pair() {
// #1923: a reference with N attributes of a block with N constant definitions, the tags N long
// ones alike up to their last characters, no attribute's a definition's. Asking for each
// definition whether the reference carries its tag by comparing it with every attribute cost
// N x N comparisons of whole tags for each copy drawn (many seconds here); gathering the
// reference's tags once costs milliseconds. The values are empty and the attributes invisible,
// so drawing them costs nothing.
const N: usize = 4000;
let tag = |kind: char, i: usize| format!("{}{kind}{i:05}", "T".repeat(1000));
let mut d = Drawing::new_imperial();
let mut blk = cadcraft_doc::Block::new("K");
for (h, i) in (1..).zip(0..N) {
let mut a = cadcraft_doc::Attrib { constant: true, ..attrib(&tag('D', i)) };
a.text.value.clear();
blk.entities.push(block_entity(h, Common::default(), EntityKind::AttDef(a)));
}
d.blocks.insert("K".into(), std::sync::Arc::new(blk));
let EntityKind::Insert(mut ins) = insert_of("K") else { panic!("an insert") };
ins.attribs = (0..N).map(|i| cadcraft_doc::Attrib { invisible: true, ..attrib(&tag('A', i)) }).collect();
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
let t = std::time::Instant::now();
build(&d, &Space::Model, &Options::default());
assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed());
}
#[test]
fn constant_attribute_definitions_follow_attmode() {
let at = Vec3::ZERO;
+16 -4
View File
@@ -3,7 +3,7 @@
use cadcraft_doc::{Linetype, LwPolyline};
use cadcraft_geom::{MAX_TESSELLATED_POINTS, Polyline, Vec2};
use crate::linetype;
use crate::linetype::{self, Layout};
/// A point on the centre line: position, unit direction, half width and distance along the run.
#[derive(Clone, Copy, Debug)]
@@ -67,14 +67,26 @@ fn edges(x: &Sample) -> (Vec2, Vec2) {
(x.p + nrm, x.p - nrm)
}
/// How far along a closed PLINEGEN polyline, drawn from its first vertex, its second vertex lies
/// (an arc by its chords at `tol`): where the pattern stretched around it is anchored, as AutoCAD
/// lays it. 0 when the first two vertices coincide (`Polyline::segments` leaves that segment out).
pub(crate) fn second_vertex_at(p: &LwPolyline, tol: f64) -> f64 {
let first = Polyline { vertices: p.vertices.iter().take(2).copied().collect(), closed: false };
first.tessellate(tol).windows(2).map(|w| if let [a, b] = w { a.dist(*b) } else { 0.0 }).sum()
}
/// Triangles for the dashes of a wide polyline drawn with `lt` at `scale`, a line across the band
/// for each dot, and the centre line of each dash. With PLINEGEN the pattern runs along the whole
/// polyline; otherwise it restarts at every vertex. A pattern shorter than `min_pattern` fills
/// the whole band.
/// polyline (stretched around a closed one from its second vertex, as a thin one is); otherwise
/// it restarts at every vertex. A pattern shorter than `min_pattern` fills the whole band.
pub fn dashed(p: &LwPolyline, tol: f64, lt: &Linetype, scale: f64, min_pattern: f64) -> (Vec<Vec2>, Vec<Vec<Vec2>>, Vec<Vec<Vec2>>) {
let mut budget = MAX_TESSELLATED_POINTS;
let mut runs = segments(p, tol, &mut budget);
let mut how = Layout::Open;
if p.plinegen && runs.len() > 1 {
if p.closed {
how = Layout::Closed { anchor: second_vertex_at(p, tol) };
}
let mut whole: Vec<Sample> = Vec::new();
for run in runs {
let base = whole.last().map(|x| x.s).unwrap_or(0.0);
@@ -87,7 +99,7 @@ pub fn dashed(p: &LwPolyline, tol: f64, lt: &Linetype, scale: f64, min_pattern:
let mut centres = Vec::new();
for run in &runs {
let len = run.last().map(|x| x.s).unwrap_or(0.0);
let dashes = linetype::ranges(len, lt, scale, min_pattern).unwrap_or_else(|| vec![(0.0, len)]);
let dashes = linetype::ranges(len, lt, scale, min_pattern, how).unwrap_or_else(|| vec![(0.0, len)]);
for (a, b) in dashes {
if b - a <= 1e-12 {
if let Some(x) = at(run, a) {
+5 -1
View File
@@ -35,12 +35,16 @@ fn drawing(ltscale: f64, own: &str) -> Drawing {
d
}
/// The lengths of the dashes drawn for the reference, all but the last one (which may be cut).
/// The lengths of the dashes drawn for the reference, all but the first and the last (the
/// pattern is centred on the line, so those two may be cut).
fn dashes(d: &Drawing) -> Vec<f64> {
let l = build(d, &Space::Model, &Options::default());
let mut out: Vec<f64> =
l.prims.iter().filter(|p| p.kind == Kind::Polyline).map(|p| l.points(p).windows(2).map(|w| w[0].dist(w[1])).sum()).collect();
out.pop();
if !out.is_empty() {
out.remove(0);
}
out
}
+7 -5
View File
@@ -33,10 +33,11 @@ fn fenceline_draws_a_circle_in_every_gap() {
let (a, b) = (Vec2::ZERO, Vec2::new(9.5, 0.0));
let d = drawing(fence, a, b);
let marks = off_line(&d, &Options::default(), a, b);
// Pattern 0.25 on, 0.1 off, "o", 0.1 off, 0.5 on = 0.95: ten repeats along 9.5.
// Pattern 0.25 on, 0.1 off, "o", 0.1 off, 0.5 on = 0.95: ten repeats along 9.5, the pattern
// centred on it (p0 = (9.5 + 0.25 − 9.5) / 2 = 0.125, so it starts 0.125 before the line).
assert_eq!(marks.len(), 10, "{marks:?}");
for (i, m) in marks.iter().enumerate() {
let gap = i as f64 * 0.95 + 0.25;
let gap = i as f64 * 0.95 + 0.25 - 0.125;
assert!(m.min.x > gap && m.max.x < gap + 0.2, "mark {i} at {m:?} outside its gap");
// Centred on the line.
assert!((m.min.y + m.max.y).abs() < 0.01 && m.max.y > 0.02, "{m:?}");
@@ -72,9 +73,10 @@ fn text_follows_the_line_or_keeps_an_absolute_rotation() {
let marks = off_line(&drawing(gas(absolute), a, b), &Options::default(), a, b);
assert!(!marks.is_empty(), "absolute {absolute}: no text");
let all = Bounds2::from_points(marks.iter().flat_map(|m| [m.min, m.max]));
// Anchor 0.7 up the line, shifted 0.1 back along it and 0.05 to its right: the text
// starts at (0.05, 0.6).
assert!((all.min.y - 0.6).abs() < 0.01, "absolute {absolute}: {all:?}");
// The pattern centred on the line (p0 = (0.95 + 0.5 − 1) / 2 = 0.225): anchor 0.7 − 0.225
// up the line, shifted 0.1 back along it and 0.05 to its right: the text starts at
// (0.05, 0.375).
assert!((all.min.y - 0.375).abs() < 0.01, "absolute {absolute}: {all:?}");
if absolute {
assert!(all.width() > all.height(), "{all:?}");
assert!((all.min.x - 0.05).abs() < 0.01, "{all:?}");
+7 -5
View File
@@ -44,9 +44,10 @@ fn dash_lengths(d: &Drawing) -> Vec<f64> {
#[test]
fn psltscale_on_keeps_paper_dash_length() {
let dashes = dash_lengths(&drawing(1));
// 1000 model units = 10 paper units; 0.75-unit pattern on paper → about 13 dashes of 0.5.
// 1000 model units = 10 paper units; 0.75-unit pattern on paper → about 13 dashes of 0.5
// (centred on the line: the first and last may be shorter).
assert!((12..=15).contains(&dashes.len()), "{} dashes", dashes.len());
assert!(dashes.iter().take(dashes.len() - 1).all(|l| (l - 0.5).abs() < 1e-6), "{dashes:?}");
assert!(dashes.iter().skip(1).take(dashes.len() - 2).all(|l| (l - 0.5).abs() < 1e-6), "{dashes:?}");
}
#[test]
@@ -54,13 +55,14 @@ fn psltscale_off_scales_dashes_with_the_viewport() {
let dashes = dash_lengths(&drawing(0));
// Model-space dash length 0.5, shrunk 100x by the viewport.
assert!(dashes.len() > 1000, "{} dashes", dashes.len());
assert!(dashes.iter().take(dashes.len() - 1).all(|l| (l - 0.005).abs() < 1e-6));
assert!(dashes.iter().skip(1).take(dashes.len() - 2).all(|l| (l - 0.005).abs() < 1e-6));
}
#[test]
fn model_space_ignores_psltscale() {
let d = drawing(1);
let l = build(&d, &Space::Model, &Options::default());
let first = l.prims.iter().find(|p| p.kind == Kind::Polyline).map(|p| l.points(p).to_vec()).unwrap();
assert!((first[0].dist(first[1]) - 0.5).abs() < 1e-9);
// The second dash (the first is cut where the centred pattern meets the line's start).
let second = l.prims.iter().filter(|p| p.kind == Kind::Polyline).nth(1).map(|p| l.points(p).to_vec()).unwrap();
assert!((second[0].dist(second[1]) - 0.5).abs() < 1e-9);
}
+87 -3
View File
@@ -40,12 +40,96 @@ fn wide_polyline_dashes_are_filled_bands() {
assert!(dashed.iter().all(|q| (q.y.abs() - 0.1).abs() < 1e-9), "dashes keep the full width");
}
#[test]
fn a_band_more_than_50000_periods_long_keeps_its_dashes_without_a_level_of_detail() {
// 50,001 DASHED periods: two thirds of the band is dashes (0.5 of each 0.75, the end ones
// halves), as a plot or export draws it; a display build, with a level of detail, draws it
// whole (#1069).
let len = 50_001.0 * 0.75;
let d = drawing(&[0.0, len], "DASHED", false);
let dashed = area(&tris(&d));
assert!((dashed - 0.2 * len * 2.0 / 3.0).abs() < 1e-4, "{dashed}");
let l = build(&d, &Space::Model, &Options { min_dash: 1e-6, ..Default::default() });
let whole = area(&l.prims.iter().filter(|p| p.kind == Kind::Tris).flat_map(|p| l.points(p).to_vec()).collect::<Vec<_>>());
assert!((whole - 0.2 * len).abs() < 1e-4, "{whole}");
}
#[test]
fn a_closed_plinegen_band_is_stretched_around_as_a_thin_one_is() {
// A closed 10.5 square is 42 around: 56 DASHED periods laid from its second vertex, 10.5 along
// (a whole number of periods), so the first side has dashes at 0-0.5, 0.75-1.25…; laid as an
// open run they would be centred, at 0-0.25, 0.5-1.0….
let mut d = Drawing::new_imperial();
d.linetypes.extend(library::standard_linetypes().into_iter().filter(|l| l.name == "DASHED"));
let p = LwPolyline {
vertices: [(0.0, 0.0), (10.5, 0.0), (10.5, 10.5), (0.0, 10.5)].map(|(x, y)| PolyVertex::new(Vec2::new(x, y))).to_vec(),
closed: true,
const_width: 0.2,
elevation: 0.0,
plinegen: true,
};
d.add(&Space::Model, Common { linetype: "DASHED".into(), ..Default::default() }, EntityKind::LwPolyline(p)).unwrap();
let t = tris(&d);
let on_first_side = |x: f64| t.iter().any(|q| (q.x - x).abs() < 1e-9 && q.y.abs() <= 0.1 + 1e-9);
assert!(on_first_side(0.75) && on_first_side(1.25) && !on_first_side(1.0), "{t:?}");
// With fill off only the centre line is drawn, laid out the same way.
d.header.set_i64("FILLMODE", 0);
let l = build(&d, &Space::Model, &Options::default());
let starts: Vec<Vec2> = l.prims.iter().filter(|p| p.kind == Kind::Polyline).filter_map(|p| l.points(p).first().copied()).collect();
let starts_at = |x: f64| starts.iter().any(|q| (q.x - x).abs() < 1e-9 && q.y.abs() < 1e-9);
assert!(starts_at(0.75) && !starts_at(0.5), "{starts:?}");
}
#[test]
fn a_closed_plinegen_run_is_anchored_at_its_second_vertex_after_an_arc() {
// The first segment is an arc (bulge 0.5): the pattern is measured along the run as drawn, so
// a dash starts right at the second vertex, without width and with fill off alike.
for width in [0.0, 0.2] {
let mut d = Drawing::new_imperial();
d.linetypes.extend(library::standard_linetypes().into_iter().filter(|l| l.name == "DASHED"));
d.header.set_i64("FILLMODE", 0);
let mut vertices: Vec<PolyVertex> =
[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)].map(|(x, y)| PolyVertex::new(Vec2::new(x, y))).to_vec();
if let Some(v) = vertices.first_mut() {
v.bulge = 0.5;
}
let p = LwPolyline { vertices, closed: true, const_width: width, elevation: 0.0, plinegen: true };
d.add(&Space::Model, Common { linetype: "DASHED".into(), ..Default::default() }, EntityKind::LwPolyline(p)).unwrap();
let l = build(&d, &Space::Model, &Options::default());
let starts: Vec<Vec2> = l.prims.iter().filter(|p| p.kind == Kind::Polyline).filter_map(|p| l.points(p).first().copied()).collect();
assert!(starts.iter().any(|q| q.dist(Vec2::new(10.0, 0.0)) < 1e-9), "{width}: {starts:?}");
}
}
#[test]
fn a_closed_plinegen_run_whose_first_two_vertices_coincide_is_anchored_at_them() {
// The zero-length first segment is left out of the drawn run, but the second vertex is still
// where the run starts: the 40-unit square is stretched to 53 DASHED periods from there, so
// dashes start at 0 and 40/53 (not 10 + k * 40/53, from the next vertex). Without width, with
// fill off, and with fill on (the band's centre line) alike.
for (width, fill) in [(0.0, 0), (0.2, 0), (0.2, 1)] {
let mut d = Drawing::new_imperial();
d.linetypes.extend(library::standard_linetypes().into_iter().filter(|l| l.name == "DASHED"));
d.header.set_i64("FILLMODE", fill);
let vertices: Vec<PolyVertex> =
[(0.0, 0.0), (0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)].map(|(x, y)| PolyVertex::new(Vec2::new(x, y))).to_vec();
let p = LwPolyline { vertices, closed: true, const_width: width, elevation: 0.0, plinegen: true };
d.add(&Space::Model, Common { linetype: "DASHED".into(), ..Default::default() }, EntityKind::LwPolyline(p)).unwrap();
let l = build(&d, &Space::Model, &Options { min_dash: 1e-6, ..Default::default() });
let starts: Vec<Vec2> = l.prims.iter().filter(|p| p.kind == Kind::Polyline).filter_map(|p| l.points(p).first().copied()).collect();
for x in [0.0, 40.0 / 53.0] {
assert!(starts.iter().any(|q| q.dist(Vec2::new(x, 0.0)) < 1e-9), "{width} {fill} {x}: {starts:?}");
}
}
}
#[test]
fn plinegen_runs_the_pattern_along_the_whole_polyline() {
// Two 0.6 segments: per segment each gets one 0.5 dash; along the whole 1.2 the pattern
// gives 0.5 + 0.45.
// Two 0.6 segments: per segment each is shorter than the 0.75 pattern, so drawn continuous;
// along the whole 1.2 the centred pattern gives 0.475 + 0.475.
let per_segment = area(&tris(&drawing(&[0.0, 0.6, 1.2], "DASHED", false)));
let whole = area(&tris(&drawing(&[0.0, 0.6, 1.2], "DASHED", true)));
assert!((per_segment - 0.2).abs() < 1e-9, "{per_segment}");
assert!((per_segment - 0.24).abs() < 1e-9, "{per_segment}");
assert!((whole - 0.19).abs() < 1e-9, "{whole}");
}
+4 -2
View File
@@ -11,6 +11,10 @@ workspace = true
[dependencies]
craft-ui = { workspace = true }
craft-behavior = { workspace = true }
craft-host = { workspace = true }
craft-keymap = { workspace = true, features = ["egui"] }
craft-theme = { workspace = true }
cadcraft-geom = { workspace = true }
cadcraft-color = { workspace = true }
cadcraft-doc = { workspace = true }
@@ -35,8 +39,6 @@ web-time = { workspace = true }
craft-update = { workspace = true }
[dev-dependencies]
# Tests build the dock area as the desktop app does (headless contexts keep floats in-window).
craft-ui = { workspace = true, features = ["native-windows"] }
# The workspace `egui` dependency enables `default_fonts` and `monochrome_emoji_fonts` in
# production too; the tests exercise the same installed chain as the app.
egui_kittest = { workspace = true, features = ["wgpu", "snapshot"] }
+2
View File
@@ -28,6 +28,7 @@ fn ready(kind: ArrayLiveKind) -> (CadApp, Handle) {
fn frames(app: &mut CadApp) -> egui::Context {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
app.logic(&ctx);
let input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 1000.0))), ..Default::default() };
for _ in 0..10 {
@@ -151,6 +152,7 @@ fn apply_live_applies_a_changed_value() {
fn dialog_returns_immediately_without_state() {
let mut app = CadApp::new(Session::new(), Services::default());
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut open = true;
dialog(&mut app, &ctx, &mut open);
assert!(open, "no state: the window is left untouched");
+1 -1
View File
@@ -124,7 +124,7 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) {
ui.label(RichText::new(crate::tl!("Values typed at the command line work too")).small().color(t.text_dim));
});
});
if ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
if crate::framework::escape_pressed(ctx) {
done = Done::Cancel;
}
if fresh {
+1 -1
View File
@@ -227,7 +227,7 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) {
later = true;
}
});
if ui.input(|i| i.key_pressed(egui::Key::Escape)) {
if crate::framework::escape_pressed(ui.ctx()) {
later = true;
}
});
+1 -1
View File
@@ -857,7 +857,7 @@ pub fn section(app: &mut CadApp, ui: &mut egui::Ui) {
let w = (ui.available_width() - 150.0).max(80.0);
ui.add(egui::TextEdit::singleline(&mut st.filter).hint_text(crate::tl!("Filter")).desired_width(w));
let view_label = ui.label(crate::tl!("View"));
craft_ui::ComboBox::from_id_salt("blocks-view")
egui::ComboBox::from_id_salt("blocks-view")
.selected_text(st.view.label())
.show_ui(ui, |ui| {
for v in View::ALL {
+39 -2
View File
@@ -207,6 +207,10 @@ pub struct CanvasState {
hover_cycle: Option<(Pos2, Vec<Handle>, usize)>,
/// What the cycling list and the Shift+Space highlight were made for (see [`CycleKey`]).
cycle_key: Option<CycleKey>,
/// The drawing (its uid) shown in the last pass; `None` while the Start page is.
pub(crate) shown: Option<u64>,
/// A drawing opened or became active and has yet to ask for the keyboard focus ([`focus_opened`]).
wants_focus: bool,
}
/// The command, prompt, drawing (and its revision) and view that the objects under the cursor
@@ -724,7 +728,7 @@ fn update_hover(app: &mut CadApp, ui: &egui::Ui, inside: bool, hover_pos: Option
app.canvas.hover_at = None;
}
// The open selection cycling list highlights the object of the row under the pointer.
if app.canvas.cycle.is_some() && ui.input(|i| i.key_pressed(egui::Key::Escape)) {
if app.canvas.cycle.is_some() && crate::framework::escape_pressed(ui.ctx()) {
app.canvas.cycle = None;
}
if let Some(c) = &app.canvas.cycle {
@@ -841,6 +845,38 @@ pub(crate) fn right_click_cancels_placing(app: &CadApp) -> bool {
&& app.session.current_prompt().is_some_and(|p| p.message == "Specify insertion point")
}
/// A press in the drawing gives it the keyboard focus, so Tab reaches the command line. Real presses only: with the
/// drawing focused, egui makes Enter and Space clicks of it.
fn focus_on_press(resp: &egui::Response) {
if resp.is_pointer_button_down_on() && resp.ctx.input(|i| i.pointer.any_pressed()) {
resp.request_focus();
}
}
/// A drawing that opens or becomes active asks for the keyboard focus, because typing goes to its command line. So does
/// the drawing while nothing is focused and its command line has work for Tab. It waits for a modal dialog, menu or
/// popup to close, and leaves the focus with a text field and with a widget of another window. Called after [`show`], so
/// a key that opened the drawing is not read again by the command line.
pub(crate) fn focus_opened(app: &mut CadApp, ctx: &egui::Context) {
let doc = app.session.docs.get(app.session.active).map(|doc| doc.uid);
if app.canvas.shown != doc {
app.canvas.shown = doc;
app.canvas.wants_focus = true;
}
let focused = ctx.memory(|memory| memory.focused());
// Escape in a palette's field leaves the focus nowhere.
let tab_work = focused.is_none() && crate::cmdline::tab_has_work(app);
if !(app.canvas.wants_focus || tab_work) || crate::framework::overlay_open(app, ctx) {
return;
}
app.canvas.wants_focus = false;
let drawing = crate::framework::drawing_id();
let layer = |id| ctx.read_response(id).map(|widget| widget.layer_id);
if !ctx.text_edit_focused() && focused.is_none_or(|id| layer(id) == layer(drawing)) {
ctx.memory_mut(|memory| memory.request_focus(drawing));
}
}
/// Draw the drawing area and handle its input (zoom and pan, picking, the crosshair) for this
/// frame.
///
@@ -856,7 +892,8 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) {
// draws the others.
let tiles = tile_rects(app, full);
let rect = tiles.iter().find(|(_, tile)| tile.active).map_or(full, |(r, _)| *r);
let resp = ui.interact(full, ui.scope_id().with("canvas"), Sense::click_and_drag());
let resp = ui.interact(full, crate::framework::drawing_id(), Sense::click_and_drag());
focus_on_press(&resp);
let painter = ui.painter_at(rect);
app.canvas.rect = Some(rect);
app.session.viewport_px = (f64::from(rect.width()).max(1.0), f64::from(rect.height()).max(1.0));
+2 -2
View File
@@ -42,8 +42,8 @@ pub(super) fn grip_menu(app: &mut CadApp, resp: &egui::Response) {
let Some(g) = app.canvas.grip_menu else { return };
let options = grip_options(app, g);
let mut chosen: Option<Option<cadcraft_engine::grips::GripAction>> = None;
let open = resp
.context_menu(|ui| {
let open = crate::context_menu::popup(resp)
.show(|ui| {
let vertex = options.contains(&cadcraft_engine::grips::GripAction::RemoveVertex);
if ui.button(crate::i18n::t(if vertex { "Stretch Vertex" } else { "Stretch" })).clicked() {
chosen = Some(None);
+1
View File
@@ -83,6 +83,7 @@ mod hatch_pick_tests {
let hx = app.session.execute("hatch", &json!({ "points": [[5, 5]], "pattern": "SOLID" })).unwrap()["handle"].as_str().unwrap().to_string();
let _ = app.session.zoom_extents();
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let screen = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 1000.0)));
let frame = |app: &mut CadApp, events: Vec<egui::Event>, time: f64| {
app.logic(&ctx);
+6
View File
@@ -184,6 +184,7 @@ fn wheel_zoom_reads_every_notch_of_the_frame() {
#[test]
fn a_wheel_notch_zooms_whole_in_its_own_frame() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let o = ctx.options(|o| o.input_options);
let input = egui::RawInput { events: vec![wheel(egui::MouseWheelUnit::Line, 1.0, egui::Modifiers::NONE)], ..Default::default() };
let mut seen = (0.0, 0.0);
@@ -231,6 +232,7 @@ fn dynamic_input_distance_follows_the_drawing_units() {
let mut app = CadApp::new(cadcraft_engine::Session::new(), crate::Services::default());
app.session.execute("units", &serde_json::json!({"lunits": 4, "luprec": 4})).unwrap();
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
painted_text(&mut app, &ctx, pos2(700.0, 450.0));
app.session.cmdline("line").unwrap();
app.session.input(Input::Point(Vec2::ZERO)).unwrap();
@@ -275,6 +277,7 @@ fn cursor_shows_pickbox_only_at_command_object_selection_prompts() {
let at = pos2(400.0, 300.0);
let paint = |app: &CadApp| {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
let painter = ui.painter_at(rect);
let picking = app.session.picking_objects() && app.session.pending_window.is_none();
@@ -459,6 +462,7 @@ fn the_cycling_badge_follows_the_frozen_layers_under_a_resting_pointer() {
app.session.execute("setvar", &serde_json::json!({ "name": "SELECTIONCYCLING", "value": 1 })).unwrap();
app.session.execute("mspace", &serde_json::json!({ "handle": b })).unwrap();
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
/// Whether the badge shows after a frame with the pointer resting on the two lines.
fn badge(app: &mut CadApp, ctx: &egui::Context) -> bool {
let (at, on_lines) = (Some(Pos2::new(200.0, 150.0)), Some(Vec2::new(50.0, 0.0)));
@@ -483,6 +487,7 @@ fn trim_highlights_the_piece_a_click_removes_once_per_cursor_position() {
}
app.session.zoom_extents().unwrap();
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
painted_text(&mut app, &ctx, pos2(700.0, 450.0));
app.session.cmdline("trim").unwrap();
let at = app.canvas.xf.unwrap().to_screen(Vec2::new(5.0, 0.0));
@@ -509,6 +514,7 @@ fn a_fence_point_taken_back_with_undo_updates_the_highlight_at_once() {
}
app.session.zoom_extents().unwrap();
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
painted_text(&mut app, &ctx, pos2(700.0, 450.0));
for answer in ["trim", "f", "5,-4", "5,1.5"] {
app.session.cmdline(answer).unwrap();
+16 -21
View File
@@ -1,15 +1,15 @@
//! Bounded, one-shot window screenshots for `ui.screenshot`.
//!
//! The request record owns the output path, reply, deadline, document/focus identity and the
//! geometry it was admitted against. The shared `craft_ui::capture::CaptureSlot` owns the strong
//! `egui::Context`; its screenshot callback holds only a weak reference and never writes a file.
//! geometry it was admitted against. The runtime's `ScreenshotSlot`, made when the capture is issued
//! (`WindowHost::screenshot`), owns the strong `egui::Context`; its screenshot callback holds only a
//! weak reference and never writes a file.
//! Files are encoded and written only from the logic drain, after the deadline and every identity
//! check have passed.
use std::sync::mpsc::Sender;
use craft_ui::capture::CaptureSlot;
use egui::ViewportCommand;
use craft_ui::runtime::windows::{ScreenshotSlot, WindowHost};
use serde_json::{Value, json};
use web_time::{Duration, Instant};
@@ -174,8 +174,8 @@ struct Shot {
geometry: SurfaceGeometry,
expected: [usize; 2],
reserved: usize,
slot: Option<CaptureSlot>,
callback: Option<egui::ScreenshotCallback>,
/// The runtime's screenshot slot, from the moment the capture is issued.
slot: Option<ScreenshotSlot>,
}
/// All admitted screenshots. `requests` includes queued, issued and completed-but-undrained
@@ -234,9 +234,10 @@ fn active_document(app: &CadApp) -> Option<u64> {
app.session.docs.get(app.session.active).map(|doc| doc.uid)
}
/// The widget egui currently reports as keyboard-focused, if any.
/// The widget egui currently reports as keyboard-focused, if any. The drawing's focus shows nothing, so it counts as
/// none: a command that opens a drawing moves the focus to it in a later frame.
fn current_focus(ctx: &egui::Context) -> Option<egui::Id> {
ctx.memory(|memory| memory.focused())
ctx.memory(|memory| memory.focused()).filter(|id| *id != crate::framework::drawing_id())
}
/// Snapshot the active drawing UID, the monotonic document epoch and the focused widget together.
@@ -344,7 +345,6 @@ pub(crate) fn admit(app: &mut CadApp, ctx: &egui::Context, path: Option<String>,
format!("screenshot budget exceeded: {total} bytes reserved by outstanding requests, over the {MAX_TOTAL_BYTES}-byte limit"),
);
}
let (slot, callback) = CaptureSlot::new(ctx, ctx.viewport_id(), MAX_IMAGE_BYTES);
let now = Instant::now();
app.shots.requests.push(Shot {
token,
@@ -360,8 +360,7 @@ pub(crate) fn admit(app: &mut CadApp, ctx: &egui::Context, path: Option<String>,
geometry: geometry.surface,
expected,
reserved,
slot: Some(slot),
callback: Some(callback),
slot: None,
});
ctx.request_repaint();
}
@@ -390,10 +389,10 @@ fn identity_change(app: &CadApp, ctx: &egui::Context, shot: &Shot) -> Option<&'s
/// Issue settled requests from the first non-discarded UI pass.
///
/// egui discards a pass only when `will_discard()` says so, and the final pass of a multi-pass
/// frame reports false; a hidden `run_logic` tick never reaches `issue` at all.
/// A pass is skipped only when `craft_ui::runtime::frame::will_rerun` says it will run again, and
/// the final pass of a multi-pass frame reports false; a hidden `run_logic` tick never reaches `issue` at all.
pub(crate) fn issue(app: &mut CadApp, ctx: &egui::Context) {
if ctx.will_discard() {
if craft_ui::runtime::frame::will_rerun(ctx) {
return;
}
// The draw may have moved the focus or switched drawings: observe that before judging.
@@ -447,11 +446,7 @@ pub(crate) fn issue(app: &mut CadApp, ctx: &egui::Context) {
continue;
}
let shot = &mut app.shots.requests[i];
let Some(callback) = shot.callback.take() else {
failures.push((i, "screenshot failed: the capture callback was already consumed".into()));
continue;
};
ctx.send_viewport_cmd_to(ctx.viewport_id(), ViewportCommand::Screenshot(callback));
shot.slot = Some(WindowHost::of(ctx).screenshot(ctx.viewport_id(), MAX_IMAGE_BYTES));
shot.issued = true;
shot.identity = current.identity;
shot.geometry = current.surface;
@@ -509,7 +504,7 @@ pub(crate) fn drain(app: &mut CadApp, ctx: &egui::Context) {
reject(shot.reply, shot.token, "screenshot failed: the window geometry changed while the capture was queued");
continue;
}
let Some(result) = app.shots.requests[i].slot.as_ref().and_then(CaptureSlot::take) else {
let Some(result) = app.shots.requests[i].slot.as_ref().and_then(ScreenshotSlot::take) else {
i += 1;
continue;
};
@@ -560,7 +555,7 @@ pub(crate) fn cancel_all(app: &mut CadApp) {
pub(crate) fn request_hidden_paint(app: &CadApp, ctx: &egui::Context) {
if app.shots.has_unissued() {
#[cfg(not(target_arch = "wasm32"))]
ctx.send_viewport_cmd(ViewportCommand::RequestPaintWhileHidden);
ctx.send_viewport_cmd(egui::ViewportCommand::RequestPaintWhileHidden);
ctx.request_repaint();
}
}
+39 -11
View File
@@ -50,10 +50,13 @@ fn ui_frame(app: &mut CadApp, ctx: &egui::Context) -> egui::FullOutput {
ui_frame_sized(app, ctx, 800.0, 600.0)
}
/// Run one real `logic` + `ui` pass at the requested size and drop texture deltas, yielding the frame's output.
/// Run one real frame at the requested size, as the desktop app does (the raw input hooks, then `logic` + `ui`), and
/// drop texture deltas, yielding the frame's output. The framework's hook gives the runtime the Options interface
/// scale, which it applies as egui's zoom.
fn ui_frame_sized(app: &mut CadApp, ctx: &egui::Context, width: f32, height: f32) -> egui::FullOutput {
let raw = raw(width, height);
note_raw_geometry(app, ctx, &raw);
let mut raw = raw(width, height);
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);
@@ -100,12 +103,22 @@ fn complete(callbacks: Vec<egui::ScreenshotCallback>, size: [usize; 2]) {
#[test]
fn admission_counts_completed_but_undrained_and_never_evicts() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = app();
let _receivers: Vec<_> = (0..MAX_REQUESTS).map(|_| admit_one(&mut app, &ctx)).collect();
// One geometry for every admission: a geometry seeded again between them is an identity change that rejects the
// queued requests at the next drain.
set_geometry(&mut app, &ctx, egui::vec2(800.0, 600.0));
let _receivers: Vec<_> = (0..MAX_REQUESTS)
.map(|_| {
let (tx, rx) = channel();
admit(&mut app, &ctx, None, tx);
rx
})
.collect();
assert_eq!(app.shots.len(), MAX_REQUESTS);
// Complete the first slot without draining it: it still owns its reservation and request.
let image = Arc::new(ColorImage::filled([800, 600], Color32::RED));
app.shots.requests[0].callback.take().expect("a callback").complete(image);
// Complete the issued slots without draining them: each still owns its reservation and request.
let (_, callbacks) = issue_after_settling(&mut app, &ctx);
complete(callbacks, [800, 600]);
let (tx, rx) = channel();
admit(&mut app, &ctx, None, tx);
assert_eq!(app.shots.len(), MAX_REQUESTS, "the fifth request is rejected, not admitted");
@@ -119,13 +132,12 @@ fn admission_counts_completed_but_undrained_and_never_evicts() {
#[test]
fn deadline_is_checked_before_writing_a_completed_image() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = app();
let (rx, _) = admit_one(&mut app, &ctx);
app.shots.requests[0].issued = true;
app.shots.requests[0].surface_epoch = app.capture_epoch;
let (_, callbacks) = issue_after_settling(&mut app, &ctx);
app.shots.requests[0].deadline = Instant::now() - Duration::from_millis(1);
let image = Arc::new(ColorImage::filled([800, 600], Color32::RED));
app.shots.requests[0].callback.take().expect("a callback").complete(image);
complete(callbacks, [800, 600]);
drain(&mut app, &ctx);
let reply = rx.recv().expect("a timeout reply");
assert_eq!(reply["ok"], false);
@@ -137,6 +149,7 @@ fn deadline_is_checked_before_writing_a_completed_image() {
#[test]
fn document_change_cancels_before_issuing() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = app();
let (rx, _) = admit_one(&mut app, &ctx);
app.session.new_drawing(false);
@@ -150,6 +163,7 @@ fn document_change_cancels_before_issuing() {
#[test]
fn focus_change_cancels_an_unissued_capture() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let focus_a = egui::Id::unique("focus-a");
let focus_b = egui::Id::unique("focus-b");
ctx.memory_mut(|memory| memory.request_focus(focus_a));
@@ -170,6 +184,7 @@ fn focus_change_cancels_an_unissued_capture() {
fn issued_callbacks_reply_once_with_matching_tokens_and_distinct_pathless_files() {
let _shots = crate::control::lock_pathless_shots();
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = app();
set_geometry(&mut app, &ctx, egui::vec2(800.0, 600.0));
let (tx1, rx1) = channel();
@@ -199,6 +214,7 @@ fn issued_callbacks_reply_once_with_matching_tokens_and_distinct_pathless_files(
#[test]
fn document_switch_after_issue_rejects_the_completed_callback_without_writing() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = app();
let (rx, token) = admit_one(&mut app, &ctx);
let (_, callbacks) = issue_after_settling(&mut app, &ctx);
@@ -217,6 +233,7 @@ fn document_switch_after_issue_rejects_the_completed_callback_without_writing()
#[test]
fn completed_callback_after_timeout_writes_nothing() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = app();
let (rx, _) = admit_one(&mut app, &ctx);
let (_, callbacks) = issue_after_settling(&mut app, &ctx);
@@ -233,6 +250,7 @@ fn completed_callback_after_timeout_writes_nothing() {
#[test]
fn callback_completed_before_cancel_all_is_inert() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = app();
let (rx, token) = admit_one(&mut app, &ctx);
let (_, callbacks) = issue_after_settling(&mut app, &ctx);
@@ -249,6 +267,7 @@ fn callback_completed_before_cancel_all_is_inert() {
#[test]
fn per_image_and_aggregate_budgets_reject_before_issue() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = app();
// 5000×5000×4 bytes = 100 MB, over the 64 MiB per-image bound.
set_geometry(&mut app, &ctx, egui::vec2(5000.0, 5000.0));
@@ -282,6 +301,7 @@ fn admit_one_at(app: &mut CadApp, ctx: &egui::Context, size: egui::Vec2) -> (Rec
#[test]
fn every_observed_geometry_change_bumps_the_generation() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = app();
note_raw_geometry(&mut app, &ctx, &raw(800.0, 600.0));
let first = app.capture_epoch;
@@ -299,6 +319,7 @@ fn every_observed_geometry_change_bumps_the_generation() {
#[test]
fn an_invalid_pass_invalidates_the_retained_surface() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = app();
note_raw_geometry(&mut app, &ctx, &raw(800.0, 600.0));
assert!(app.capture_geometry.is_some(), "the raw snapshot was retained");
@@ -324,6 +345,7 @@ fn an_invalid_pass_invalidates_the_retained_surface() {
#[test]
fn raw_geometry_uses_screen_rect_when_inner_rect_is_absent() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = app();
let mut raw = egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(640.0, 480.0))),
@@ -344,6 +366,7 @@ fn raw_geometry_uses_screen_rect_when_inner_rect_is_absent() {
fn a_discarded_pass_does_not_issue_and_the_settled_pass_does_once() {
let _shots = crate::control::lock_pathless_shots();
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = app();
let (rx, _) = admit_one(&mut app, &ctx);
for shot in &mut app.shots.requests {
@@ -376,6 +399,7 @@ fn a_discarded_pass_does_not_issue_and_the_settled_pass_does_once() {
fn issuance_uses_the_settled_interface_scale_not_the_admission_estimate() {
let _shots = crate::control::lock_pathless_shots();
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = app();
app.options.interface_scale = 2.0;
let raw = raw(800.0, 600.0);
@@ -396,6 +420,7 @@ fn issuance_uses_the_settled_interface_scale_not_the_admission_estimate() {
#[test]
fn a_document_switch_that_returns_still_rejects_the_queued_capture() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = app();
app.session.new_drawing(false);
let (rx, _) = admit_one(&mut app, &ctx);
@@ -417,6 +442,7 @@ fn a_document_switch_that_returns_still_rejects_the_queued_capture() {
#[test]
fn a_drawing_created_and_closed_between_observations_still_bumps_the_identity_epoch() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = app();
set_geometry(&mut app, &ctx, egui::vec2(800.0, 600.0));
let before_epoch = app.capture_identity_epoch;
@@ -433,6 +459,7 @@ fn a_drawing_created_and_closed_between_observations_still_bumps_the_identity_ep
#[test]
fn a_settled_window_does_not_keep_changing_the_surface_epoch() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = app();
ui_frame(&mut app, &ctx).drop_without_applying_deltas();
let epoch = app.capture_epoch;
@@ -450,6 +477,7 @@ fn a_settled_window_does_not_keep_changing_the_surface_epoch() {
fn a_resize_while_settling_is_absorbed_at_issue() {
let _shots = crate::control::lock_pathless_shots();
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = app();
let (rx, _) = admit_one(&mut app, &ctx);
for shot in &mut app.shots.requests {
+19 -41
View File
@@ -1,5 +1,6 @@
//! Window chrome: title and tool bar, file tabs, status bar and the Start page.
use craft_behavior::fit::{FitItem, FitKeep};
use egui::{Rect, Sense, Stroke, pos2, vec2};
use serde_json::json;
@@ -40,26 +41,11 @@ const TOOLBAR: &[&[(Icon, &str, &str, Option<&str>)]] = &[
&[(Icon::Help, "ui.dialog.about", "Help", None)],
];
/// Height of the macOS integrated title row (#161). AppKit draws the traffic lights itself,
/// centred in the standard 28 pt title-bar band at the top of the window; moving them would take
/// AppKit calls (`unsafe`, which the workspace forbids). So the title row is that band, and what
/// it holds is centred on the same line as the lights.
/// Height of the macOS integrated title row (#161): the standard 28 pt title-bar band AppKit centres the traffic
/// lights in.
const MAC_TITLE_BAR: f32 = 28.0;
/// The traffic lights as AppKit lays them out: button diameter, centre-to-centre pitch and the
/// first button's left edge (8–10 pt depending on the macOS version; the larger value keeps the
/// gap after them from shrinking).
const MAC_LIGHT: f32 = 12.0;
const MAC_LIGHT_PITCH: f32 = 20.0;
const MAC_LIGHTS_LEFT: f32 = 10.0;
/// Where title-row content may start to the right of the traffic lights: the end of the three
/// lights plus the same gap the lights keep from the top of the window.
const MAC_CONTENT_LEFT: f32 = MAC_LIGHTS_LEFT + 2.0 * MAC_LIGHT_PITCH + MAC_LIGHT + (MAC_TITLE_BAR - MAC_LIGHT) / 2.0;
/// Left edge of the window title in a title row starting at `left`, `width` wide: centred, but
/// never under the traffic lights (a long drawing name in a narrow window slides right instead).
fn title_left(left: f32, width: f32, text_w: f32) -> f32 {
(left + (width - text_w) / 2.0).max(left + MAC_CONTENT_LEFT)
}
/// The width of the toolbar's More button.
const MORE_WIDTH: f32 = 30.0;
/// Title row (with the integrated macOS title bar) and the Tool Bar.
pub fn title_and_toolbar(app: &mut CadApp, ui: &mut egui::Ui) {
@@ -69,17 +55,18 @@ pub fn title_and_toolbar(app: &mut CadApp, ui: &mut egui::Ui) {
egui::Panel::top("cc_title_toolbar").exact_size(title_h + tb_h).frame(egui::Frame::NONE.fill(t.chrome)).show(ui, |ui| {
let r = ui.max_rect();
if title_h > 0.0 {
// The empty row moves the window; it goes first so later widgets take their own clicks.
craft_window::title_bar::empty_area(ui, Rect::from_min_size(r.min, vec2(r.width(), title_h)));
// The window's title bar: its free area moves the window and follows the system's double-click setting.
let title = match app.session.state() {
Ok(st) if !app.ui.start_tab => format!("CADCraft {}{}", st.title, if st.title.contains('.') { "" } else { ".dwg" }),
_ => format!("CADCraft {}", crate::tl!("Start")),
};
// Centred on the traffic lights' centre line (the row's middle): with the system font
// the capitals' middle is the text box's middle, so no optical nudge.
let galley = ui.painter().layout_no_wrap(title, egui::FontId::proportional(13.0), t.text_dim);
let x = title_left(r.left(), r.width(), galley.size().x);
ui.painter().galley(pos2(x, r.top() + (title_h - galley.size().y) / 2.0), galley, t.text_dim);
let row = Rect::from_min_size(r.min, vec2(r.width(), title_h));
ui.scope_builder(egui::UiBuilder::new().max_rect(row), |ui| {
let bar = craft_ui::shell::TitleBar::new().show_titled(ui, craft_ui::shell::Title::new(title), |_, _| {}, |_, _| {});
if bar.close_requested {
ui.ctx().send_viewport_cmd(egui::ViewportCommand::Close);
}
});
}
if tb_h > 0.0 {
let row = Rect::from_min_size(pos2(r.left(), r.top() + title_h), vec2(r.width(), tb_h));
@@ -89,7 +76,9 @@ pub fn title_and_toolbar(app: &mut CadApp, ui: &mut egui::Ui) {
let mac = ui.ctx().os().is_mac();
let widths: Vec<_> = TOOLBAR.iter().map(|group| group.len() as f32 * (size + 6.0) - 6.0).collect();
let available = (row.right() - 12.0 - x).max(0.0);
let Some(fit) = craft_ui::layout::fit_toolbar(&widths, available, 24.0, 30.0) else {
let items: Vec<_> = widths.iter().enumerate().map(|(i, w)| FitItem::new(*w, i as u16, FitKeep::Free)).collect();
let fit = craft_behavior::fit::fit_items(&items, available, 24.0, 24.0, MORE_WIDTH);
if !fit.overflow.is_empty() && available < MORE_WIDTH {
// Very small windows still expose the complete command row by scrolling.
ui.scope_builder(egui::UiBuilder::new().max_rect(row.shrink2(vec2(4.0, 0.0))), |ui| {
egui::ScrollArea::horizontal().id_salt("toolbar_small").show(ui, |ui| {
@@ -109,8 +98,8 @@ pub fn title_and_toolbar(app: &mut CadApp, ui: &mut egui::Ui) {
app.start(command);
}
return;
};
for (index, _) in &fit.shown {
}
for index in &fit.shown {
let Some(group) = TOOLBAR.get(*index) else { continue };
for (icon, cmd, label, shortcut) in group.iter() {
let br = Rect::from_min_size(pos2(x, row.center().y - size / 2.0), vec2(size, size));
@@ -132,7 +121,7 @@ pub fn title_and_toolbar(app: &mut CadApp, ui: &mut egui::Ui) {
x += 18.0;
}
if !fit.overflow.is_empty() {
let br = Rect::from_min_size(pos2(x, row.center().y - size / 2.0), vec2(fit.overflow_width, size));
let br = Rect::from_min_size(pos2(x, row.center().y - size / 2.0), vec2(MORE_WIDTH, size));
let response = ui.interact(br, ui.scope_id().with("toolbar_more"), Sense::click());
if response.hovered() {
ui.painter().rect_filled(br, 3.0, t.control_hover.gamma_multiply(0.6));
@@ -620,17 +609,6 @@ pub fn start_page(app: &mut CadApp, ui: &mut egui::Ui) {
mod tests {
use super::*;
#[test]
fn mac_title_row_centres_and_clears_the_traffic_lights() {
// The lights are centred in the row, and content keeps the same gap after them.
let margin = (MAC_TITLE_BAR - MAC_LIGHT) / 2.0;
let lights_end = MAC_LIGHTS_LEFT + 2.0 * MAC_LIGHT_PITCH + MAC_LIGHT;
assert_eq!(MAC_CONTENT_LEFT - lights_end, margin);
// A short title is centred; one too wide for that starts after the lights.
assert_eq!(title_left(100.0, 1000.0, 200.0), 500.0);
assert_eq!(title_left(100.0, 900.0, 800.0), 100.0 + MAC_CONTENT_LEFT);
}
#[test]
fn layout_tabs_that_do_not_fit_keep_the_current_one() {
let w = [50.0; 6];
+11 -8
View File
@@ -50,15 +50,18 @@ pub enum ShortcutAction {
/// The actions the Cut/Copy/Paste events of this frame ask for. Pasted DXF text that isn't our
/// own last copy (another CADCraft's) becomes the clipboard first; non-DXF tab-separated table text
/// starts `pastetable`.
pub fn shortcut_actions(app: &mut CadApp, ctx: &egui::Context) -> Vec<ShortcutAction> {
let (events, shift) = ctx.input(|i| {
let ev: Vec<egui::Event> =
i.events.iter().filter(|e| matches!(e, egui::Event::Copy | egui::Event::Cut | egui::Event::Paste(_))).cloned().collect();
(ev, i.modifiers.shift)
///
/// `fired` holds the events a floating panel's window ran as framework commands ([`CadApp::queue_fired_edits`]); they
/// come before this window's own.
pub fn shortcut_actions(app: &mut CadApp, ctx: &egui::Context, fired: Vec<egui::Event>) -> Vec<ShortcutAction> {
// Each event with its Shift: the fired chords have none, whatever is held by the time this window reads them.
let events: Vec<(egui::Event, bool)> = ctx.input(|i| {
let own = i.events.iter().filter(|e| matches!(e, egui::Event::Copy | egui::Event::Cut | egui::Event::Paste(_)));
fired.into_iter().map(|e| (e, false)).chain(own.map(|e| (e.clone(), i.modifiers.shift))).collect()
});
let paste_cmd = || if shift { "pasteblock" } else { "pasteclip" };
let mut out = Vec::new();
for e in events {
for (e, shift) in events {
let paste_cmd = || if shift { "pasteblock" } else { "pasteclip" };
match e {
egui::Event::Copy => out.push(ShortcutAction::Command(if shift { "copybase" } else { "copyclip" })),
egui::Event::Cut => out.push(ShortcutAction::Command("cutclip")),
@@ -262,7 +265,7 @@ pub fn pump(app: &mut CadApp, ctx: &egui::Context) {
}
if let Some(p) = app.paste.request.take() {
// A focused text field would take the `Paste` itself.
if ctx.egui_wants_keyboard_input() {
if crate::framework::widget_has_keyboard(ctx) {
run_now(app, p);
} else {
ctx.send_viewport_cmd(egui::ViewportCommand::RequestPaste);
+10 -4
View File
@@ -256,7 +256,7 @@ pub fn prompt(app: &mut CadApp, ctx: &egui::Context) {
choice = Some(Choice::Discard);
}
});
if ui.input(|i| i.key_pressed(egui::Key::Escape)) {
if crate::framework::escape_pressed(ui.ctx()) {
choice = Some(Choice::Cancel);
}
});
@@ -448,7 +448,10 @@ mod tests {
use egui::{ViewportCommand, ViewportEvent, ViewportId, ViewportInfo};
let mut input = egui::RawInput::default();
input.viewports.insert(ViewportId::ROOT, ViewportInfo { events: vec![ViewportEvent::Close], ..Default::default() });
let mut out = ctx.run_ui(input, |ui| app.logic(ui.ctx()));
let mut out = ctx.run_ui(input, |ui| {
app.logic(ui.ctx());
app.close_path(ui.ctx());
});
out.textures_delta.clear();
out.viewport_output.get(&ViewportId::ROOT).is_some_and(|v| v.commands.contains(&ViewportCommand::CancelClose))
}
@@ -457,8 +460,10 @@ mod tests {
#[test]
fn window_close_with_unsaved_changes_is_held() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = app_with(&["A"]);
assert!(!close_frame(&mut app, &ctx), "a saved drawing closes without asking");
// Only the app's decision: a close that goes ahead ends in the platform's quit, which macOS answers by cancelling it.
assert!(!app.request_quit(), "a saved drawing closes without asking");
dirty(&mut app, 0);
assert!(close_frame(&mut app, &ctx), "unsaved changes must cancel the close");
assert_eq!(app.close_prompt(), Some("A"));
@@ -468,11 +473,12 @@ mod tests {
#[test]
fn programmatic_quit_skips_the_prompt() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = app_with(&["A"]);
dirty(&mut app, 0);
let (req, _rx) = crate::control::ControlRequest::new("app.quit", json!({}));
let _ = crate::control::handle(&mut app, &ctx, &req);
assert!(!close_frame(&mut app, &ctx));
assert!(!app.request_quit());
assert!(app.closing.is_none());
}
+31 -28
View File
@@ -64,33 +64,19 @@ pub fn dyn_frame(app: &CadApp) -> Option<crate::dyninput::Frame> {
Some(crate::dyninput::Frame { base: p.base, cartesian: st.dynpi_cartesian, absolute: st.dynpi_absolute, ucs })
}
/// Take Tab away from egui before it moves keyboard focus to the next widget (which would leave
/// the command line deaf to typing). While no widget has focus, a pressed Tab becomes a `"\t"`
/// text event, which keeps its place among the other keystrokes; [`keyboard`] handles it.
pub fn capture_tab(ctx: &egui::Context, raw: &mut egui::RawInput) {
if ctx.egui_wants_keyboard_input() {
return;
}
raw.events.retain_mut(|e| {
let tab = match e {
egui::Event::Key { key: Key::Tab, pressed, .. } => Some(*pressed),
_ => None,
};
match tab {
Some(true) => {
*e = egui::Event::Text("\t".into());
true
}
Some(false) => false,
None => true,
}
});
/// Whether Tab on the command line has something to act on: a running command or LISP prompt, typed
/// text, the Dynamic Input or grip value boxes, or a snap marker under the cursor.
pub(crate) fn tab_has_work(app: &CadApp) -> bool {
app.session.prompting() || !app.cmd.buffer.is_empty() || dyn_frame(app).is_some() || app.canvas.snap.is_some()
}
/// Tab on the command line: cycle the object snaps under the cursor, type the Dynamic Input
/// separator (`,` or `<`) after a value, cycle between the two Dynamic Input boxes, or complete a
/// command name.
fn tab(app: &mut CadApp) {
if !tab_has_work(app) {
return;
}
// Grip dimensional input: Tab locks the typed value and moves to the next field.
if crate::grip_dyn::tab(app) {
return;
@@ -367,14 +353,18 @@ fn enable_ime(app: &mut CadApp, ctx: &egui::Context) {
});
}
/// Handle keyboard input destined for the command line (when no text field has focus).
/// Handle keyboard input destined for the command line (with nothing or the drawing focused).
pub fn keyboard(app: &mut CadApp, ctx: &egui::Context) {
if ctx.egui_wants_keyboard_input() {
if crate::framework::widget_has_keyboard(ctx) {
app.cmd.preedit.clear();
app.cmd.ime_on = false;
return;
}
let events = ctx.input(|i| i.events.clone());
let mut events = ctx.input(|i| i.events.clone());
// With nothing focused, Escape is the window's cancel, which the runtime keeps out of egui's events.
if crate::framework::window_cancel_pending(ctx) {
events.push(egui::Event::Key { key: Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE });
}
let selection = app.session.selection();
app.cmd.watch_selection(&selection);
let mac = ctx.os() == egui::os::OperatingSystem::Mac;
@@ -422,9 +412,7 @@ pub fn keyboard(app: &mut CadApp, ctx: &egui::Context) {
}
match ev {
egui::Event::Text(t) => {
if t == "\t" {
tab(app);
} else if t == " " && !text_prompt {
if t == " " && !text_prompt {
submit(app);
} else {
app.cmd.preedit.clear();
@@ -917,6 +905,7 @@ mod tests {
assert_eq!(app.session.current_prompt().map(|p| p.message.clone()).as_deref(), Some("Enter text"));
assert!(app.session.text_editor().is_none(), "no in-place editor at this prompt");
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let out = frame(&mut app, &ctx, Vec::new());
// The IME is enabled for the command line while it is collecting text.
assert!(out.platform_output.ime.is_some());
@@ -951,6 +940,7 @@ mod tests {
app.session.echo(format!("line {i}"));
}
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
frame(&mut app, &ctx, Vec::new());
frame(&mut app, &ctx, Vec::new());
let canvas = app.canvas.rect.unwrap_or(Rect::NOTHING);
@@ -1196,8 +1186,13 @@ mod dyn_tab_tests {
out.textures_delta.clear();
}
/// The key events of typing `text`, a tab character as a press of Tab.
fn typed(text: &str) -> Vec<egui::Event> {
text.chars().map(|c| egui::Event::Text(c.to_string())).collect()
let event = |c: char| match c {
'\t' => egui::Event::Key { key: Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE },
c => egui::Event::Text(c.to_string()),
};
text.chars().map(event).collect()
}
#[test]
@@ -1206,11 +1201,13 @@ mod dyn_tab_tests {
let mut app = CadApp::new(cadcraft_engine::Session::new(), crate::Services::default());
app.session.settings.dynmode = true;
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
run_frame(&mut app, &ctx, Vec::new());
let center = app.canvas.rect.map_or(egui::pos2(700.0, 450.0), |r| r.center());
run_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(center)]);
app.cmdline("line");
app.cmdline("0,0");
run_frame(&mut app, &ctx, Vec::new());
run_frame(&mut app, &ctx, typed("40\t90\t"));
assert!(app.cmd.first_active(), "{:?}", app.cmd.buffer);
let escape = egui::Key::Escape;
@@ -1237,11 +1234,13 @@ mod dyn_tab_tests {
let mut app = CadApp::new(cadcraft_engine::Session::new(), crate::Services::default());
app.session.settings.dynmode = true;
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
run_frame(&mut app, &ctx, Vec::new());
let center = app.canvas.rect.map_or(egui::pos2(700.0, 450.0), |r| r.center());
run_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(center)]);
app.cmdline("line");
app.cmdline("0,0");
run_frame(&mut app, &ctx, Vec::new());
run_frame(&mut app, &ctx, typed("40\t90\t"));
assert!(app.cmd.first_active(), "{:?}", app.cmd.buffer);
app.session.settings.dynmode = false;
@@ -1269,10 +1268,12 @@ mod dyn_tab_tests {
let mut app = CadApp::new(cadcraft_engine::Session::new(), crate::Services::default());
app.session.settings.dynmode = true;
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
run_frame(&mut app, &ctx, Vec::new());
let center = app.canvas.rect.map_or(egui::pos2(700.0, 450.0), |r| r.center());
app.cmdline("line");
app.cmdline("0,0");
run_frame(&mut app, &ctx, Vec::new());
run_frame(&mut app, &ctx, typed("40\t90\t"));
let back = egui::Key::Backspace;
let m = egui::Modifiers::NONE;
@@ -1334,10 +1335,12 @@ mod dyn_tab_tests {
let mut app = CadApp::new(cadcraft_engine::Session::new(), crate::Services::default());
app.session.settings.dynmode = true;
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
run_frame(&mut app, &ctx, Vec::new());
let center = app.canvas.rect.map_or(egui::pos2(700.0, 450.0), |r| r.center());
app.cmdline("line");
app.cmdline("0,0");
run_frame(&mut app, &ctx, Vec::new());
run_frame(&mut app, &ctx, typed("40<90\t"));
assert!(app.cmd.second_locked());
let at = center + egui::vec2(37.0, -23.0);
+8 -1
View File
@@ -388,6 +388,13 @@ pub fn groups_ui(ui: &mut egui::Ui, groups: &[Vec<Entry>], clicked: &mut Option<
}
}
/// A right-click menu of the drawing. Only real clicks open and close it: with the drawing focused, egui makes Enter and
/// Space clicks of it, and those go to the command line.
pub(crate) fn popup(drawing: &egui::Response) -> egui::Popup<'static> {
let open = if drawing.secondary_clicked() { Some(true) } else { drawing.clicked_by(egui::PointerButton::Primary).then_some(false) };
egui::Popup::context_menu(drawing).open_memory(open.map(egui::SetOpenCommand::Bool))
}
/// Attach the menu to the canvas response: it opens on a right-click, as the object snap menu
/// when that click held Shift or Ctrl (`CanvasState::snap_menu`).
pub fn show(app: &mut CadApp, resp: &egui::Response) {
@@ -411,7 +418,7 @@ pub fn show(app: &mut CadApp, resp: &egui::Response) {
}
return;
}
resp.context_menu(|ui| {
popup(resp).show(|ui| {
let groups = if snap { snap_entries(app) } else { entries(app) };
groups_ui(ui, &groups, &mut clicked);
});
+1 -1
View File
@@ -177,7 +177,7 @@ fn focus_json(ctx: &egui::Context) -> Value {
"id": focused.map(|id| format!("{:016x}", id.value())),
"label": widget.map(|widget| &widget.label),
"role": widget.map(|widget| widget.role),
"keyboardInput": ctx.egui_wants_keyboard_input(),
"keyboardInput": crate::framework::widget_has_keyboard(ctx),
})
}
+1 -1
View File
@@ -223,7 +223,7 @@ pub fn contributors_ui(ui: &mut egui::Ui) {
}
ui.separator();
ui.label(crate::tl!("Sort"));
craft_ui::ComboBox::from_id_salt("credits_sort").selected_text(crate::i18n::t(v.key.label().0)).show_ui(ui, |ui| {
egui::ComboBox::from_id_salt("credits_sort").selected_text(crate::i18n::t(v.key.label().0)).show_ui(ui, |ui| {
for k in SortKey::ALL {
if ui.selectable_label(v.key == k, crate::i18n::t(k.label().0)).clicked() {
v.key = k;
+3 -3
View File
@@ -100,7 +100,7 @@ fn dsettings(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
let mut deg = current;
ui.horizontal(|ui| {
let label = ui.label(crate::tl!("Increment angle"));
let combo = craft_ui::ComboBox::from_id_salt("polarang").selected_text(format!("{deg}")).show_ui(ui, |ui| {
let combo = egui::ComboBox::from_id_salt("polarang").selected_text(format!("{deg}")).show_ui(ui, |ui| {
for a in [90.0, 45.0, 30.0, 22.5, 18.0, 15.0, 10.0, 5.0] {
ui.selectable_value(&mut deg, a, format!("{a}"));
}
@@ -246,7 +246,7 @@ const INSERTION_UNITS: [&str; 25] = [
/// A combo box over `(value, label)` options.
fn pick(ui: &mut egui::Ui, salt: &str, value: &mut i64, options: &[(i64, String)]) {
let current = options.iter().find(|o| o.0 == *value).map(|o| o.1.clone()).unwrap_or_default();
craft_ui::ComboBox::from_id_salt(salt).selected_text(current).width(180.0).show_ui(ui, |ui| {
egui::ComboBox::from_id_salt(salt).selected_text(current).width(180.0).show_ui(ui, |ui| {
for (k, label) in options {
ui.selectable_value(value, *k, label);
}
@@ -415,7 +415,7 @@ fn commands(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
/// Interface Language combo; selecting a language runs `ui.language` with its code.
fn language(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
egui::Window::new(crate::tl!("Interface Language")).id(egui::Id::unique("interface_language")).open(open).resizable(false).show(ctx, |ui| {
craft_ui::ComboBox::from_id_salt("interface_language_choice").selected_text(app.ui.interface_language.name()).show_ui(ui, |ui| {
egui::ComboBox::from_id_salt("interface_language_choice").selected_text(app.ui.interface_language.name()).show_ui(ui, |ui| {
for preference in crate::i18n::Preference::for_picker() {
if ui.selectable_label(app.ui.interface_language == preference, preference.name()).clicked() {
let _ = app.run("ui.language", serde_json::json!({"lang": preference.code()}));
+443 -229
View File
@@ -1,11 +1,21 @@
//! Application panel identities and persistence around the shared docking renderer.
//! Document contents remain owned by their existing view implementations.
//! Application panel identities and persistence around craft-ui's `DockArea`. Document contents remain owned by
//! their existing view implementations.
//!
//! `UiState::docking` is the saved workspace and the source of truth. The dock shows an `Arc` of it
//! ([`LiveDock`]), kept while the saved workspace is unchanged; every change the dock reports goes through the
//! same checks as a `ui.dock` command.
use craft_ui::docking::{
Action, Column, DockArea, DockCommand, DockContent, DockHeights, DockOperation, DockStyle, FloatSpace, Group, Layout, Location, Node,
PanelLimits, Permissions, Placement, Side, Sides, Target, UiDock, Zone,
};
use craft_ui::layout::{SplitAxis, SplitSize};
use std::sync::Arc;
use craft_behavior::DockSide;
use craft_behavior::dock::{Action, Column, DockEdge, DockError, DockPlacement, Group, Layout, Location, Node, Permissions, SplitSize, Target};
use craft_behavior::flow::Axis;
use craft_ui::contract::{Bind, BodyCx, MemoKey, MemoProps, PlainData, SizeLimits, Tracked};
use craft_ui::docking::{DockConfig, DockHeights, DockPanels, DockSides, GroupAt, PanelSpec, PanelSpecs};
use craft_ui::patterns::dock::DockArea;
use craft_ui::primitives::{Glyph, IconSpec};
use craft_ui::style::UiTokens;
use egui::{Rect, pos2, vec2};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
@@ -24,6 +34,8 @@ pub enum Panel {
impl Panel {
pub const ALL: &[Self] = &[Self::Canvas, Self::ToolSets, Self::Layers, Self::Properties, Self::ExternalRefs];
/// Every panel, the ones opened on request included.
const EVERY: [Self; 7] = [Self::Canvas, Self::ToolSets, Self::QuickCalc, Self::Layers, Self::Properties, Self::ExternalRefs, Self::Blocks];
pub fn id(self) -> &'static str {
match self {
Self::Canvas => "canvas",
@@ -65,19 +77,15 @@ impl Panel {
/// The drawing view never moves, floats, closes or takes tabs; palettes dock beside it.
pub fn permissions(panel: &Panel) -> Permissions {
if *panel == Panel::Canvas { Permissions { accepts_splits: true, ..Permissions::PROTECTED } } else { Permissions::default() }
if *panel == Panel::Canvas { Permissions::PROTECTED.accepts_splits(true) } else { Permissions::default() }
}
fn tabs(panel: Panel) -> Node<Panel> {
Node::Tabs { panels: vec![panel], active: 0 }
}
fn split(axis: SplitAxis, size: SplitSize, first: Node<Panel>, second: Node<Panel>) -> Node<Panel> {
Node::Split { axis, size, first: Box::new(first), second: Box::new(second) }
Node::tabs(vec![panel], 0)
}
/// The saved panel arrangement: craft-ui's workspace over CADCraft's panels.
pub type Workspace = craft_ui::docking::Workspace<Panel>;
pub type Workspace = craft_behavior::dock::Workspace<Panel>;
/// The panel layout's shape version, saved beside it. Layouts saved without it, or with an
/// older one, are the split frames from before the dock columns and give way to the default.
@@ -90,47 +98,47 @@ pub const PALETTES_WIDTH: f32 = 300.0;
/// Layers' body height above Properties in a dock column.
const LAYERS_HEIGHT: f32 = 280.0;
fn dock(side: Side, width: f32, groups: &[Panel]) -> Node<Panel> {
fn dock(side: DockEdge, width: f32, groups: &[Panel]) -> Node<Panel> {
let groups = groups.iter().map(|panel| Group::new(vec![*panel], 0)).collect();
Node::Dock { side, columns: vec![Column::new(groups, width)] }
Node::dock(side, vec![Column::new(groups).with_width(width)])
}
/// Tool Sets in the left dock, the drawing, and Layers above Properties in the right dock.
pub fn default_workspace() -> Workspace {
Workspace::new(Layout {
root: Some(split(
SplitAxis::Horizontal,
Workspace::new(Layout::new(
Some(Node::split(
Axis::X,
SplitSize::FixedFirst(TOOL_SETS_WIDTH),
dock(Side::Start, TOOL_SETS_WIDTH, &[Panel::ToolSets]),
split(
SplitAxis::Horizontal,
dock(DockEdge::Start, TOOL_SETS_WIDTH, &[Panel::ToolSets]),
Node::split(
Axis::X,
SplitSize::FixedSecond(PALETTES_WIDTH),
tabs(Panel::Canvas),
dock(Side::End, PALETTES_WIDTH, &[Panel::Layers, Panel::Properties]),
dock(DockEdge::End, PALETTES_WIDTH, &[Panel::Layers, Panel::Properties]),
),
)),
floating: Vec::new(),
})
Vec::new(),
))
}
/// The dock a panel belongs in: Tool Sets on the left, the palettes on the right.
fn home_side(panel: Panel) -> (Side, f32) {
if panel == Panel::ToolSets { (Side::Start, TOOL_SETS_WIDTH) } else { (Side::End, PALETTES_WIDTH) }
fn home_side(panel: Panel) -> (DockEdge, f32) {
if panel == Panel::ToolSets { (DockEdge::Start, TOOL_SETS_WIDTH) } else { (DockEdge::End, PALETTES_WIDTH) }
}
/// The panels of every dock group on `side`: columns from the window edge inwards, groups from
/// top to bottom.
fn dock_groups(layout: &Layout<Panel>, side: Side) -> Vec<Vec<Vec<Panel>>> {
fn dock_groups(layout: &Layout<Panel>, side: DockEdge) -> Vec<Vec<Vec<Panel>>> {
let mut nodes: Vec<&Node<Panel>> = layout.root.iter().collect();
let mut seen = 0usize;
while let Some(node) = nodes.pop() {
seen = seen.saturating_add(1);
if seen > 4 * craft_ui::docking::MAX_PANELS {
if seen > 4 * craft_behavior::dock::MAX_PANELS {
break;
}
match node {
Node::Split { first, second, .. } => nodes.extend([&**first, &**second]),
Node::Dock { side: s, columns } if *s == side => {
Node::Dock { side: s, columns, .. } if *s == side => {
return columns.iter().map(|column| column.groups.iter().map(|group| group.panels.clone()).collect()).collect();
}
_ => {}
@@ -140,7 +148,7 @@ fn dock_groups(layout: &Layout<Panel>, side: Side) -> Vec<Vec<Vec<Panel>>> {
}
fn docked(layout: &Layout<Panel>, panel: Panel) -> bool {
[Side::Start, Side::End].into_iter().any(|side| dock_groups(layout, side).iter().flatten().flatten().any(|p| *p == panel))
[DockEdge::Start, DockEdge::End].into_iter().any(|side| dock_groups(layout, side).iter().flatten().flatten().any(|p| *p == panel))
}
/// The docked neighbour a panel with no recorded place opens beside, as a new group above
@@ -172,23 +180,24 @@ fn home_anchor(layout: &Layout<Panel>, panel: Panel) -> Option<(Panel, bool)> {
/// docked neighbour, else a new dock on its side at its default width.
fn home(layout: &Layout<Panel>, panel: Panel) -> Vec<Action<Panel>> {
if let Some((anchor, below)) = home_anchor(layout, panel) {
return vec![Action::OpenAt { panel, anchor, placement: Placement::Group { below, height: None } }];
return vec![Action::open_at(panel, anchor, DockPlacement::group(below, None))];
}
let (side, width) = home_side(panel);
vec![Action::Open { panel, anchor: None }, Action::MovePanel { panel, to: Target::NewDock { side } }, Action::ResizeColumn { panel, width }]
vec![Action::open(panel, None), Action::move_panel(panel, Target::new_dock(side)), Action::resize_column(panel, width)]
}
/// craft-ui's checks plus the drawing view's: a saved or hand-edited file cannot hide, float,
/// group, collapse or dock it, or restore a palette over it.
pub fn validate(workspace: &Workspace) -> Result<(), String> {
workspace.validate().map_err(|error| error.to_string())?;
if !workspace.layout.contains(&Panel::Canvas) {
let layout = workspace.layout();
if !layout.contains(&Panel::Canvas) {
return Err("The panel layout must contain its document view".into());
}
if workspace.layout.floating.iter().any(|window| window.contains(&Panel::Canvas)) {
if layout.floating.iter().any(|window| window.contains(&Panel::Canvas)) {
return Err("The document view cannot float".into());
}
let mut nodes: Vec<_> = workspace.layout.root.iter().collect();
let mut nodes: Vec<_> = layout.root.iter().collect();
while let Some(node) = nodes.pop() {
match node {
Node::Split { first, second, .. } => {
@@ -198,7 +207,7 @@ pub fn validate(workspace: &Workspace) -> Result<(), String> {
Node::Tabs { panels, .. } if panels.contains(&Panel::Canvas) && panels.len() != 1 => {
return Err("The document view cannot share a tab group".into());
}
Node::Stack { entries } if entries.iter().any(|entry| entry.panel == Panel::Canvas) => {
Node::Stack { entries, .. } if entries.iter().any(|entry| entry.panel == Panel::Canvas) => {
return Err("The document view cannot be collapsed".into());
}
Node::Dock { columns, .. } if columns.iter().flat_map(|column| &column.groups).any(|group| group.panels.contains(&Panel::Canvas)) => {
@@ -208,9 +217,9 @@ pub fn validate(workspace: &Workspace) -> Result<(), String> {
}
}
let over_canvas = |location: &Location<Panel>| {
location.anchor == Some(Panel::Canvas) && matches!(location.placement, Placement::Tab { .. } | Placement::Split(Zone::Center))
location.anchor == Some(Panel::Canvas) && matches!(location.placement, DockPlacement::Tab { .. } | DockPlacement::Split(DockSide::Center))
};
if workspace.hidden.iter().any(|(_, location)| over_canvas(location)) {
if workspace.hidden().iter().any(|(_, location)| over_canvas(location)) {
return Err("A hidden panel cannot restore over the document view".into());
}
Ok(())
@@ -221,11 +230,12 @@ pub fn validate(workspace: &Workspace) -> Result<(), String> {
/// its docked neighbour's group.
pub fn reveal_panel(workspace: &mut Workspace, panel: Panel) -> Result<(), String> {
let mut next = workspace.clone();
if next.layout.contains(&panel) || next.hidden.iter().any(|(id, _)| *id == panel) {
let fallback = home_anchor(&next.layout, panel).map(|(anchor, _)| anchor);
next.set_visible(panel, true, fallback, permissions).map_err(|error| error.to_string())?;
if next.layout().contains(&panel) || next.hidden().iter().any(|(id, _)| *id == panel) {
let fallback = home_anchor(next.layout(), panel).map(|(anchor, _)| anchor);
next.set_visible(panel, true, fallback, false, permissions).map_err(|error| error.to_string())?;
} else {
next.apply_all(home(&next.layout, panel).into_iter().chain([Action::Activate { panel }]), permissions).map_err(|error| error.to_string())?;
let actions: Vec<_> = home(next.layout(), panel).into_iter().chain([Action::activate(panel)]).collect();
next.apply_all(actions, false, permissions).map_err(|error| error.to_string())?;
}
validate(&next)?;
*workspace = next;
@@ -237,18 +247,19 @@ pub fn reveal_panel(workspace: &mut Workspace, panel: Panel) -> Result<(), Strin
/// entries are open. Otherwise it goes through [`reveal_panel`], which regroups it with hidden
/// panels it was beside, and selects it.
fn set_visible(workspace: &mut Workspace, panel: Panel, visible: bool) -> Result<(), String> {
if workspace.layout.contains(&panel) == visible {
if workspace.layout().contains(&panel) == visible {
return Ok(());
}
if !visible {
return workspace.set_visible(panel, false, None, permissions).map_err(|error| error.to_string());
return workspace.set_visible(panel, false, None, false, permissions).map_err(|error| error.to_string());
}
let mut next = workspace.clone();
let location = next.hidden.iter().find(|(id, _)| *id == panel).map(|(_, location)| location.clone());
let location = workspace.hidden().iter().find(|(id, _)| *id == panel).map(|(_, location)| location.clone());
// A direct restore against a hidden anchor would open a window of its own.
let direct = location.filter(|location| location.anchor.is_none_or(|anchor| next.layout.contains(&anchor)));
if direct.is_some_and(|location| next.layout.restore(panel, &location).is_ok()) {
next.hidden.retain(|(id, _)| *id != panel);
let direct = location.filter(|location| location.anchor.is_none_or(|anchor| workspace.layout().contains(&anchor)));
let mut layout = workspace.layout().clone();
if direct.is_some_and(|location| layout.restore(panel, &location).is_ok()) {
let hidden = workspace.hidden().iter().filter(|(id, _)| *id != panel).cloned().collect();
let next = Workspace::from_parts(layout, hidden, workspace.floated().to_vec());
validate(&next)?;
*workspace = next;
return Ok(());
@@ -256,36 +267,168 @@ fn set_visible(workspace: &mut Workspace, panel: Panel, visible: bool) -> Result
reveal_panel(workspace, panel)
}
/// `ui.dock` params: `{action}` or `{operation, …}` in craft-ui's shared grammar.
/// `ui.dock` params: `{action}`, a layout action, or `{operation, …}` ([`DockOperation`]).
fn apply_command(workspace: &mut Workspace, params: &Value) -> Result<(), String> {
validate(workspace)?;
let operation = if let Some(action) = params.get("action") {
UiDock::Action { action: serde_json::from_value(action.clone()).map_err(|error| error.to_string())? }
let action = if let Some(action) = params.get("action") {
serde_json::from_value(action.clone()).map_err(|error| error.to_string())?
} else {
UiDock::Operation(serde_json::from_value(params.clone()).map_err(|error| error.to_string())?)
let operation: DockOperation = serde_json::from_value(params.clone()).map_err(|error| error.to_string())?;
if let DockOperation::Open { panel } | DockOperation::Activate { panel } = &operation
&& !workspace.layout().contains(panel)
{
let mut next = workspace.clone();
reveal_panel(&mut next, *panel)?;
validate(&next)?;
*workspace = next;
return Ok(());
}
operation.action(workspace.layout()).map_err(|error| error.to_string())?
};
apply_action(workspace, action)
}
/// Apply one layout action to a copy of `workspace` and keep it only when it passes [`validate`].
fn apply_action(workspace: &mut Workspace, action: Action<Panel>) -> Result<(), String> {
let mut next = workspace.clone();
match operation {
UiDock::Operation(DockOperation::Open { panel } | DockOperation::Activate { panel }) if !next.layout.contains(&panel) => {
reveal_panel(&mut next, panel)?;
}
operation => {
// Every ui.dock operation carries its own rect, so the float space is never consulted.
let space = FloatSpace::new(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 800.0)));
DockCommand::UiDock(operation).apply(&mut next, false, &space, permissions).map_err(|error| error.to_string())?;
}
}
next.apply(action, false, permissions).map_err(|error| error.to_string())?;
validate(&next)?;
*workspace = next;
Ok(())
}
/// A drop zone by name, as `ui.dock` writes it. PascalCase names also parse.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
enum ZoneName {
Tab,
#[serde(alias = "Center")]
Center,
#[serde(alias = "Left")]
Left,
#[serde(alias = "Right")]
Right,
#[serde(alias = "Top")]
Top,
#[serde(alias = "Bottom")]
Bottom,
Above,
Below,
}
/// A present field, `null` included: `Some(None)` for `null`, `None` when absent.
fn present<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(deserializer: D) -> Result<Option<T>, D::Error> {
T::deserialize(deserializer).map(Some)
}
/// A required field that may be `null`.
fn required<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(deserializer: D) -> Result<T, D::Error> {
T::deserialize(deserializer)
}
/// A `ui.dock` operation, tagged by `operation`. `move` takes `target` (the anchor), `zone`
/// (default `center`) and `before`, which only applies to a center move. Rects are `[x, y, width, height]`.
#[derive(Clone, Debug, PartialEq, Deserialize)]
#[serde(tag = "operation", rename_all = "camelCase")]
enum DockOperation {
/// Show a panel at its last location and select it.
Open {
panel: Panel,
},
Close {
panel: Panel,
},
Activate {
panel: Panel,
},
Float {
panel: Panel,
rect: [f32; 4],
},
MoveFloating {
panel: Panel,
rect: [f32; 4],
},
Move {
panel: Panel,
target: Panel,
#[serde(default)]
zone: Option<ZoneName>,
#[serde(default, deserialize_with = "present")]
before: Option<Option<Panel>>,
},
SetStackOpen {
panel: Panel,
open: bool,
},
/// `height` is required; `null` clears it.
ResizeStack {
panel: Panel,
#[serde(deserialize_with = "required")]
height: Option<f32>,
},
ResizeSplit {
path: Vec<bool>,
size: SplitSize,
},
}
/// `[x, y, width, height]` as a rect.
fn rect_of([x, y, width, height]: [f32; 4]) -> Rect {
Rect::from_min_size(pos2(x, y), vec2(width, height))
}
/// Where a `move` puts the panel relative to `anchor`: `zone` (default `center`) and `before`,
/// with side zones mapped onto the anchor's container by [`DockPlacement::for_zone`].
fn placement(
layout: &Layout<Panel>,
anchor: &Panel,
zone: Option<ZoneName>,
before: Option<Option<Panel>>,
) -> Result<DockPlacement<Panel>, DockError> {
let side = |side| DockPlacement::for_zone(layout, anchor, side);
Ok(match (zone.unwrap_or(ZoneName::Center), before) {
(ZoneName::Tab | ZoneName::Center, Some(before)) => DockPlacement::tab(before),
(ZoneName::Tab, None) => DockPlacement::tab(None),
(ZoneName::Center, None) => DockPlacement::Split(DockSide::Center),
(_, Some(_)) => return Err(DockError::InvalidPlacement),
(ZoneName::Left, None) => side(DockSide::Start)?,
(ZoneName::Right, None) => side(DockSide::End)?,
(ZoneName::Top, None) => side(DockSide::Top)?,
(ZoneName::Bottom, None) => side(DockSide::Bottom)?,
(ZoneName::Above, None) => DockPlacement::group(false, None),
(ZoneName::Below, None) => DockPlacement::group(true, None),
})
}
impl DockOperation {
/// The layout action this operation makes on `layout`. A panel that is not shown is
/// [`DockError::MissingPanel`] for Open and Activate, which show it first ([`apply_command`]).
fn action(&self, layout: &Layout<Panel>) -> Result<Action<Panel>, DockError> {
Ok(match self {
Self::Open { panel } | Self::Activate { panel } => {
if !layout.contains(panel) {
return Err(DockError::MissingPanel);
}
Action::activate(*panel)
}
Self::Close { panel } => Action::close(*panel),
Self::Float { panel, rect } => Action::float(*panel, rect_of(*rect)),
Self::MoveFloating { panel, rect } => Action::move_floating(*panel, rect_of(*rect)),
Self::Move { panel, target, zone, before } => Action::move_beside(*panel, *target, placement(layout, target, *zone, *before)?),
Self::SetStackOpen { panel, open } => Action::set_stack_open(*panel, *open),
Self::ResizeStack { panel, height } => Action::resize_stack(*panel, *height),
Self::ResizeSplit { path, size } => Action::resize_split(path.clone(), *size),
})
}
}
fn sync(workspace: &mut Workspace, app: &crate::CadApp) -> Result<(), String> {
set_visible(workspace, Panel::ToolSets, app.ui.show_toolsets)?;
if !app.ui.show_palettes {
set_visible(workspace, Panel::Layers, false)?;
set_visible(workspace, Panel::Properties, false)?;
} else if !workspace.layout.contains(&Panel::Layers) && !workspace.layout.contains(&Panel::Properties) {
} else if !workspace.layout().contains(&Panel::Layers) && !workspace.layout().contains(&Panel::Properties) {
// Reopen the palette that closed last before the one recorded beside it.
set_visible(workspace, Panel::Properties, true)?;
set_visible(workspace, Panel::Layers, true)?;
@@ -294,20 +437,20 @@ fn sync(workspace: &mut Workspace, app: &crate::CadApp) -> Result<(), String> {
}
fn publish_visibility(app: &mut crate::CadApp, workspace: &Workspace) {
app.ui.show_toolsets = workspace.layout.contains(&Panel::ToolSets);
app.ui.show_palettes = workspace.layout.contains(&Panel::Layers) || workspace.layout.contains(&Panel::Properties);
app.ui.show_toolsets = workspace.layout().contains(&Panel::ToolSets);
app.ui.show_palettes = workspace.layout().contains(&Panel::Layers) || workspace.layout().contains(&Panel::Properties);
}
pub fn command(app: &mut crate::CadApp, reset: bool, params: &Value) -> Result<Value, String> {
let mut workspace = app.ui.docking.clone();
if reset {
workspace = default_workspace();
workspace.replace(default_workspace());
} else {
sync(&mut workspace, app)?;
apply_command(&mut workspace, params)?;
// An opened panel's floating window comes to the front, in its own OS window too.
if matches!(params.get("operation").and_then(Value::as_str), Some("open" | "activate")) {
app.raise_panel = params.get("panel").and_then(|panel| serde_json::from_value(panel.clone()).ok());
app.dock.raise = params.get("panel").and_then(|panel| serde_json::from_value(panel.clone()).ok());
}
}
publish_visibility(app, &workspace);
@@ -315,104 +458,199 @@ pub fn command(app: &mut crate::CadApp, reset: bool, params: &Value) -> Result<V
Ok(json!({"docking": app.ui.docking}))
}
/// Validate and repair the stored workspace, sync it with the app, and render the dock panels; a failed restore falls back to the default layout with a status message.
/// Draw the docked workspace: restore or fall back from the persisted layout, render every
/// panel body plus the header close buttons, and apply the resulting actions through
/// [`command`]. Bodies may dispatch commands, so the canonical workspace is published before
/// rendering while the layout snapshot stays immutable.
/// Apply a change the dock reported, with the app's visibility switches synced first.
fn apply_reported(app: &mut crate::CadApp, action: Action<Panel>) -> Result<(), String> {
let mut workspace = app.ui.docking.clone();
sync(&mut workspace, app)?;
validate(&workspace)?;
apply_action(&mut workspace, action)?;
publish_visibility(app, &workspace);
app.ui.docking = workspace;
Ok(())
}
/// The workspace the dock shows, the panels' specs and the panel to raise.
#[derive(Default)]
pub struct LiveDock {
shown: Option<Arc<Workspace>>,
specs: Tracked<DockSpecs>,
/// A panel opened from a menu or command, whose floating window comes to the front on the next frame.
raise: Option<Panel>,
}
impl LiveDock {
/// The `Arc` the dock shows for `workspace`: the last one while its arrangement is the same, so an idle pass keeps
/// the workspace's revision and the dock reads no spec.
fn shown(&mut self, workspace: &Workspace) -> Arc<Workspace> {
if let Some(shown) = self.shown.as_ref().filter(|shown| ***shown == *workspace) {
return Arc::clone(shown);
}
let shown = Arc::new(workspace.clone());
self.shown = Some(Arc::clone(&shown));
shown
}
}
/// What the dock reads of the panels: their names in the interface language.
#[derive(Clone, Debug, Default, PartialEq, PlainData)]
struct DockSpecs {
/// The tab names, in [`Panel::EVERY`] order.
labels: Vec<String>,
}
impl PanelSpecs<Panel> for DockSpecs {
fn spec(&self, panel: &Panel) -> PanelSpec {
let label = Panel::EVERY.iter().position(|p| p == panel).and_then(|index| self.labels.get(index)).cloned().unwrap_or_default();
// Every panel is CADCraft's own egui code: the dock runs it with the window's style.
let mut spec = PanelSpec::new(label).limits(panel_limits(panel)).host_body();
if let Some(glyph) = PanelGlyph::of(*panel) {
spec = spec.icon(IconSpec::glyph(glyph));
}
match panel {
Panel::Canvas => spec.canvas(),
// Layers keeps its list's height above Properties, which takes the rest of the column.
Panel::Layers => spec.heights(DockHeights::new(LAYERS_HEIGHT)),
_ => spec,
}
}
fn permissions(&self, panel: &Panel) -> Permissions {
permissions(panel)
}
}
/// Reads the panel names in the interface language, moving the specs' revision only when one changed.
fn refresh_specs(app: &mut crate::CadApp) {
let labels: Vec<String> = Panel::EVERY.iter().map(|panel| crate::i18n::t(panel.label()).to_string()).collect();
if app.dock.specs.labels != labels {
app.dock.specs.labels = labels;
}
}
/// A palette's icon in a column collapsed to icons and in its flyout cell, painted by CADCraft's own icon painter.
#[derive(Debug, PartialEq)]
struct PanelGlyph(crate::icons::Icon);
impl PanelGlyph {
fn of(panel: Panel) -> Option<&'static PanelGlyph> {
use crate::icons::Icon;
static TOOL_SETS: PanelGlyph = PanelGlyph(Icon::Switcher);
static QUICK_CALC: PanelGlyph = PanelGlyph(Icon::Table);
static LAYERS: PanelGlyph = PanelGlyph(Icon::Layers);
static PROPERTIES: PanelGlyph = PanelGlyph(Icon::Properties);
static EXTERNAL_REFS: PanelGlyph = PanelGlyph(Icon::Attach);
static BLOCKS: PanelGlyph = PanelGlyph(Icon::Blocks);
match panel {
Panel::Canvas => None,
Panel::ToolSets => Some(&TOOL_SETS),
Panel::QuickCalc => Some(&QUICK_CALC),
Panel::Layers => Some(&LAYERS),
Panel::Properties => Some(&PROPERTIES),
Panel::ExternalRefs => Some(&EXTERNAL_REFS),
Panel::Blocks => Some(&BLOCKS),
}
}
}
impl MemoProps for PanelGlyph {
fn key(&self, key: &mut MemoKey) {
key.feed_hash(&self.0);
}
}
impl Glyph for PanelGlyph {
/// CADCraft's icons keep their own colours (blue for created geometry, orange for picked points), so the dock's
/// ink is not applied.
fn paint(&self, painter: &egui::Painter, _tokens: &UiTokens, rect: Rect, _color: egui::Color32, _mirrored: bool) {
crate::icons::paint(painter, rect, self.0, false);
}
}
/// Validate and repair the stored workspace, sync it with the app, and draw the dock: restore or fall back from the
/// persisted layout (a failed restore falls back to the default layout with a status message), draw every panel body
/// and the drawing, forward the keys typed in floating panels' own windows, and apply the pass's layout actions.
/// Bodies may dispatch commands, so the canonical workspace is published before drawing while the shown `Arc` stays
/// unchanged.
pub fn show(app: &mut crate::CadApp, ui: &mut egui::Ui) {
let t = crate::theme::Tokens::get();
let mut workspace = app.ui.docking.clone();
if let Err(error) = validate(&workspace).and_then(|()| sync(&mut workspace, app)) {
app.set_status(format!("Panel layout could not be restored: {error}"));
workspace = default_workspace();
let _ = sync(&mut workspace, app);
}
// Bodies can dispatch commands (including the drawing's typed command line).
// Keep the canonical workspace accessible while rendering an immutable snapshot.
app.ui.docking = workspace.clone();
let mut style = DockStyle::from_ui(ui);
style.min_pane = 96.0;
style.background = t.panel;
style.tab_background = t.chrome;
style.active_background = t.tab_active;
style.text = t.text;
style.inactive_text = t.text_dim;
style.border = egui::Stroke::new(1.0, t.border);
style.accent = t.accent;
style.font = crate::theme::body();
// AutoCAD's palettes dock only in the left and right dock columns: a window edge without a
// dock makes one, and neither the drawing nor the top and bottom edges take a drop.
// Floating title bars only move windows.
style.side_edge_zones = false;
style.new_dock_zones = true;
style.drop_edges = Sides::NONE;
style.title_bar_docks = false;
let mut area = DockArea::new(egui::Id::unique("cadcraft-docking")).input_blocked(native_input_blocked(app, ui.ctx()));
if let Some(panel) = app.raise_panel.take() {
area = area.raise_panel(panel);
}
let (mut output, header_close) = {
let mut panels = Panels { app, close: None };
let output = area.show_content(ui, &workspace.layout, &style, &mut panels);
(output, panels.close)
refresh_specs(app);
let shown = app.dock.shown(&workspace);
// The specs leave the app while its panels borrow it, and come back with their revision.
let specs = std::mem::take(&mut app.dock.specs);
let raise = app.dock.raise.take();
// AutoCAD's palettes dock only in the left and right dock columns: a window edge without a dock makes one, and
// neither the drawing nor the top and bottom edges take a drop. Floating title bars only move windows. Each
// closable tab has its close button.
let config =
DockConfig::default().side_edge_zones(false).new_dock_zones(true).drop_edges(DockSides::NONE).title_bar_docks(false).tab_close_buttons(true);
let (output, focused_windows) = {
let mut panels = Panels { app: &mut *app, focused_windows: Vec::new() };
let mut area = DockArea::new("Panels", Bind::given(shown), &specs, &mut panels, config);
if let Some(panel) = raise {
area = area.raise(panel);
}
let output = area.show(ui);
(output, panels.focused_windows)
};
// Accordion title bars are rendered by the shared surface without a header callback, so
// place the same close button over their title bar, left of the stock collapse control.
let mut close = header_close;
for panel in stack_panels(&workspace.layout) {
if !permissions(&panel).closable {
app.dock.specs = specs;
// Keys typed in a floating panel's own OS window run the main window's shortcuts and command line; while one of that
// window's widgets has the keyboard, only the keyboard zoom reads them. Files dropped on one open like files dropped
// on the main window.
let ctx = ui.ctx().clone();
for (_, viewport) in &output.windows {
if *viewport == egui::ViewportId::ROOT {
continue;
}
let Some(title) = ui.ctx().read_response(egui::Id::unique("cadcraft-docking").with(("tab", panel))) else { continue };
if !title.rect.is_positive() {
if focused_windows.contains(viewport) {
app.zoom_keys(&ctx, *viewport);
continue;
}
let rect = egui::Rect::from_center_size(
egui::pos2(title.rect.right() - 18.0 - CLOSE_BUTTON * 0.5 - 4.0, title.rect.center().y),
egui::vec2(CLOSE_BUTTON, CLOSE_BUTTON),
);
if close_button(ui, panel, rect) {
close = Some(panel);
let (events, modifiers) =
ctx.input_for(*viewport, |input| (input.events.iter().filter(|e| forwarded(e)).cloned().collect::<Vec<_>>(), input.modifiers));
// A Copy, Cut or Paste chord is the runtime's command: it reaches the app through the next frame's `FrameOutput`.
if modifiers.command {
ctx.request_repaint_of(egui::ViewportId::ROOT);
}
let modifiers = (!events.is_empty()).then_some(modifiers);
app.forward_native_input(&ctx, events, modifiers);
}
if let Some(panel) = close {
output.actions.push(Action::Close { panel });
}
// Keys typed in a floating panel's own OS window run the main window's shortcuts and
// command line; files dropped on one open like files dropped on the main window.
app.forward_native_input(ui.ctx(), std::mem::take(&mut output.forwarded_events), output.forwarded_modifiers);
#[cfg(not(target_arch = "wasm32"))]
for files in std::mem::take(&mut output.window_files) {
for file in files.dropped {
let path = file.path();
if !path.as_os_str().is_empty() {
app.open_path(path);
}
for dropped in &output.window_files {
for path in dropped.files.iter().filter_map(|file| file.path.as_ref()) {
app.open_path(path);
}
}
// Existing panel close buttons and commands still own their visibility switches.
// Existing panel switches and commands still own their visibility switches.
let rendered = workspace;
let mut workspace = app.ui.docking.clone();
let _ = sync(&mut workspace, app);
let stale = workspace != rendered;
if stale {
craft_ui::docking::cancel_drag::<Panel>(ui.ctx(), egui::Id::unique("cadcraft-docking"));
craft_ui::runtime::drag::cancel(ui.ctx(), craft_behavior::CancelReason::HostChanged);
}
publish_visibility(app, &workspace);
app.ui.docking = workspace;
if stale {
return;
}
for action in output.actions {
if let Err(error) =
serde_json::to_value(action).map_err(|error| error.to_string()).and_then(|action| command(app, false, &json!({"action": action})))
{
for action in output.actions.into_iter().chain(output.requested) {
if let Err(error) = apply_reported(app, action) {
app.set_status(format!("Panel move was not applied: {error}"));
}
}
}
/// The events a floating panel's own window hands to the main window: keys, text and the clipboard.
fn forwarded(event: &egui::Event) -> bool {
matches!(event, egui::Event::Key { .. } | egui::Event::Text(_) | egui::Event::Copy | egui::Event::Cut | egui::Event::Paste(_))
}
/// Whether the floating panels' own OS windows ignore input: while a modal dialog is up, since
/// egui's `Modal` blocks only the main window. egui's modal layer is last frame's; the app's
/// state covers the frame a modal opens in.
@@ -420,65 +658,20 @@ pub fn native_input_blocked(app: &crate::CadApp, ctx: &egui::Context) -> bool {
app.shows_modal() || ctx.memory(|memory| memory.top_modal_layer()).is_some()
}
/// The panels' contents, names, size limits and icons for the dock area.
pub struct Panels<'a> {
pub app: &'a mut crate::CadApp,
/// The panel whose header close button was clicked this frame.
pub close: Option<Panel>,
/// The dock's panels over the app in one pass.
struct Panels<'a> {
app: &'a mut crate::CadApp,
/// The floating panels' own OS windows in which one of CADCraft's widgets had the keyboard after its body ran.
focused_windows: Vec<egui::ViewportId>,
}
/// Size of a panel header's close button, in points.
const CLOSE_BUTTON: f32 = 16.0;
/// The accessible name of a header's close button. One translated template carries both the
/// verb and the panel name, so a catalog translates the whole name instead of leaving an
/// English verb in front of a translated panel label.
fn close_label(panel: Panel) -> String {
crate::tf!("Close {panel}", panel = crate::i18n::t(panel.label()))
}
/// A visible close button for a panel header. It runs the same action as the tab context
/// menu's "Close panel"; the accessible name includes the panel so the headers stay distinct.
fn close_button(ui: &mut egui::Ui, panel: Panel, rect: egui::Rect) -> bool {
let t = crate::theme::Tokens::get();
let response = ui.interact(rect, egui::Id::unique("cadcraft-docking").with(("close", panel.id())), egui::Sense::click());
let label = close_label(panel);
crate::icons::describe_control(ui, &response, &label, None, false);
if response.hovered() {
ui.painter().rect_filled(rect.expand(2.0), 2.0, t.control_hover.gamma_multiply(0.6));
}
crate::icons::paint(ui.painter(), rect, crate::icons::Icon::Close, false);
response.on_hover_text(crate::tl!("Close panel")).clicked()
}
/// Panels whose title bar is an accordion entry rather than a tab group header.
fn stack_panels(layout: &Layout<Panel>) -> Vec<Panel> {
let mut panels = Vec::new();
let mut nodes: Vec<&Node<Panel>> = layout.root.iter().collect();
while let Some(node) = nodes.pop() {
match node {
Node::Split { first, second, .. } => {
nodes.push(first);
nodes.push(second);
}
Node::Stack { entries } => panels.extend(entries.iter().map(|entry| entry.panel)),
// Tab groups draw their own header; nothing else stacks an accordion entry.
_ => {}
}
}
panels
}
impl DockContent<Panel> for Panels<'_> {
/// Render `panel`'s existing view; Layers, Properties and External References scroll
/// independently, and the drawing canvas paints its own background before the view.
fn body(&mut self, ui: &mut egui::Ui, panel: &Panel) {
impl DockPanels<Panel> for Panels<'_> {
/// Render `panel`'s existing view; Layers, Properties and External References scroll independently.
fn body(&mut self, panel: &Panel, ui: &mut egui::Ui, _: &mut BodyCx<'_>) {
let app = &mut *self.app;
match panel {
Panel::Canvas => {
ui.painter().rect_filled(ui.max_rect(), 0.0, crate::theme::Tokens::get().canvas);
crate::canvas::show(app, ui);
}
// The drawing is its group's `group_view`.
Panel::Canvas => {}
Panel::ToolSets => crate::palettes::toolsets(app, ui),
Panel::QuickCalc => crate::palettes::quickcalc::show(app, ui),
Panel::Layers => {
@@ -502,51 +695,72 @@ impl DockContent<Panel> for Panels<'_> {
.show(ui, |ui| crate::blocks_palette::section(app, ui));
}
}
}
fn logical_label(&self, panel: &Panel) -> String {
crate::i18n::t(panel.label()).into()
}
fn permissions(&self, panel: &Panel) -> Permissions {
permissions(panel)
}
fn limits(&self, panel: &Panel) -> PanelLimits {
panel_limits(panel)
}
fn dock_heights(&self, panel: &Panel) -> Option<DockHeights> {
// Layers keeps its list's height above Properties, which takes the rest of the column.
(*panel == Panel::Layers).then(|| DockHeights::new(LAYERS_HEIGHT))
}
fn paint_icon(&mut self, painter: &egui::Painter, rect: egui::Rect, panel: &Panel, _color: egui::Color32) -> bool {
let Some(icon) = panel.icon() else { return false };
crate::icons::paint(painter, rect, icon, false);
true
}
/// Reserve header space for the close button only when `active` may be closed, so the
/// drawing view's title gets no empty gap.
fn group_header_width(&self, _panels: &[Panel], active: &Panel, _floating: bool, _strip_width: f32) -> f32 {
if permissions(active).closable { CLOSE_BUTTON + 8.0 } else { 0.0 }
}
/// Draw the close button at the right edge of a tab-group header and remember the panel
/// to close once the docking surface has returned, so layout changes stay outside rendering.
fn group_header(&mut self, ui: &mut egui::Ui, _panels: &[Panel], active: &Panel, _floating: bool) {
let header = ui.max_rect();
let rect = egui::Rect::from_center_size(
egui::pos2(header.right() - CLOSE_BUTTON * 0.5 - 4.0, header.center().y),
egui::vec2(CLOSE_BUTTON, CLOSE_BUTTON),
);
if close_button(ui, *active, rect) {
self.close = Some(*active);
let viewport = ui.ctx().viewport_id();
if viewport != egui::ViewportId::ROOT {
self.focused_windows.retain(|window| *window != viewport);
if ui.memory(|memory| memory.focused().is_some()) {
self.focused_windows.push(viewport);
}
}
}
/// The drawing: it paints its own background, and is the window's document canvas.
fn group_view(&mut self, panels: &[Panel], _: usize, ui: &mut egui::Ui, at: GroupAt, _: &mut BodyCx<'_>) -> Option<f32> {
let GroupAt::Show(rect) = at else { return None };
if !panels.contains(&Panel::Canvas) {
return None;
}
// Declared before the widgets drawn over it, for its place in Tab order, and again after this pass's input has
// changed what Tab has to do.
crate::framework::host_canvas(ui.ctx(), crate::cmdline::tab_has_work(self.app));
ui.painter().rect_filled(rect, 0.0, crate::theme::Tokens::get().canvas);
crate::canvas::show(self.app, ui);
crate::canvas::focus_opened(self.app, ui.ctx());
crate::framework::host_canvas(ui.ctx(), crate::cmdline::tab_has_work(self.app));
Some(rect.height())
}
}
fn panel_limits(panel: &Panel) -> PanelLimits {
/// The panels' body limits: a minimum size and a maximum width.
fn panel_limits(panel: &Panel) -> SizeLimits {
let (min, max_width) = match panel {
Panel::Canvas => (egui::vec2(300.0, 180.0), 1_000_000.0),
Panel::QuickCalc => (egui::vec2(240.0, 160.0), 600.0),
Panel::ToolSets => (egui::vec2(220.0, 150.0), 480.0),
Panel::Layers | Panel::Properties | Panel::ExternalRefs => (egui::vec2(220.0, 100.0), 720.0),
Panel::Blocks => (egui::vec2(240.0, 260.0), 720.0),
Panel::Canvas => (vec2(300.0, 180.0), SizeLimits::BOUND),
Panel::QuickCalc => (vec2(240.0, 160.0), 600.0),
Panel::ToolSets => (vec2(220.0, 150.0), 480.0),
Panel::Layers | Panel::Properties | Panel::ExternalRefs => (vec2(220.0, 100.0), 720.0),
Panel::Blocks => (vec2(240.0, 260.0), 720.0),
};
PanelLimits { min, max: egui::vec2(max_width, 1_000_000.0) }
SizeLimits::new(min, vec2(max_width, SizeLimits::BOUND))
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
#[test]
fn an_opened_panel_is_raised_for_one_frame() {
let mut app = crate::CadApp::new(cadcraft_engine::Session::default(), crate::Services::default());
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
command(&mut app, false, &json!({"operation": "open", "panel": Panel::Properties.id()})).unwrap();
assert_eq!(app.dock.raise, Some(Panel::Properties));
let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(1600.0, 1000.0))), ..Default::default() };
let mut output = ctx.run_ui(input, |ui| app.ui(ui));
output.textures_delta.clear();
assert_eq!(app.dock.raise, None);
}
#[test]
fn a_reset_replaces_the_workspace() {
let mut app = crate::CadApp::new(cadcraft_engine::Session::default(), crate::Services::default());
let start = app.ui.docking.generation();
command(&mut app, false, &json!({"operation": "open", "panel": Panel::Blocks.id()})).unwrap();
assert_eq!(app.ui.docking.generation(), start);
command(&mut app, true, &Value::Null).unwrap();
assert_ne!(app.ui.docking.generation(), start);
assert_eq!(app.ui.docking, default_workspace());
}
}
+1 -1
View File
@@ -210,7 +210,7 @@ pub(crate) fn menu(app: &mut CadApp, ctx: &egui::Context, xf: &Xf) {
if let Err(e) = app.run("blocks.reference.set", json!({ "handle": h.hex(), "name": g.property, "value": value })) {
app.session.echo(e);
}
} else if clicked_elsewhere || ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
} else if clicked_elsewhere || crate::framework::escape_pressed(ctx) {
app.canvas.dyn_menu = None;
}
}
+1
View File
@@ -572,6 +572,7 @@ mod tests {
fn down_arrow_lists_the_options_and_enter_or_a_click_picks_one() {
let mut app = crate::CadApp::new(cadcraft_engine::Session::new(), crate::Services::default());
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
run_frame(&mut app, &ctx, Vec::new());
let center = app.canvas.rect.map_or(egui::pos2(700.0, 450.0), |r| r.center());
let hover = vec![egui::Event::PointerMoved(center)];
+2 -2
View File
@@ -126,7 +126,7 @@ pub fn pdf_dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
});
},
);
if ctx.input(|input| input.key_pressed(egui::Key::Escape)) {
if crate::framework::escape_pressed(ctx) {
cancel = true;
}
if import {
@@ -242,7 +242,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
close = ui.button("Close").clicked();
});
});
if ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
if crate::framework::escape_pressed(ctx) {
close = true;
}
if close || print {
+254
View File
@@ -0,0 +1,254 @@
//! The craft-ui runtime, hosted from CADCraft's own eframe `App` (craft-libs docs/craft-framework.md, section 2.2).
//! The desktop app calls [`install`] once, [`CadApp::before_input`] in `raw_input_hook` after CADCraft's own hook,
//! [`CadApp::close_path`] last in `logic`, and [`before_ui`] first in `ui`; the browser build and tests install with
//! [`install_headless`]. The framework dialogs run on [`CadApp::framework_dialogs`] after CADCraft's own UI.
//!
//! The runtime takes Escape, Tab and the clipboard events for the whole window unless one of CADCraft's own egui
//! widgets has the keyboard. The window's Escape is read with [`escape_pressed`]; the drawing is declared to the
//! runtime with [`host_canvas`], which keeps Enter, the arrows, the edit chords and the clipboard events in egui's
//! input for the command line and CADCraft's shortcuts while nothing has the focus.
use std::sync::{Arc, OnceLock};
use craft_host::target::ShellInfo;
use craft_host::{AppInfo, Host};
use craft_keymap::Overrides;
use craft_ui::fonts::{I18nScripts, SystemFonts, UiFonts};
use craft_ui::runtime::commands::{CommandInput, CommandSet as _, EditCommands, FirePhase, FireSource, Fired, NavCommand};
use craft_ui::runtime::env::{RootEnv, Scale};
use craft_ui::runtime::focus::{EditSet, KeepKeys, KeyUse};
use craft_ui::runtime::frame::{FrameInput, FrameOutput};
use craft_ui::runtime::keys::{Intent, with_window_intents};
use craft_ui::runtime::overlay::{self, OpenFilter};
use craft_ui::shell::embed::{self, CloseDecision};
use craft_window::system::WindowSystem;
use egui::ViewportId;
use crate::CadApp;
use crate::options::INTERFACE_SCALES;
/// Each pass of the root window, first in `App::ui`: hands the runtime the native window it answers the hit test of
/// (Windows) and fits the window to its monitor once.
#[cfg(not(target_arch = "wasm32"))]
pub use craft_ui::shell::embed::before_ui;
/// The override variable's prefix: `CADCRAFT_TITLEBAR`.
#[cfg(not(target_arch = "wasm32"))]
const PREFIX: craft_window::Prefix = craft_window::Prefix::new("CADCRAFT");
/// The scripts of the interface languages, for the font stack.
static SCRIPTS: I18nScripts = I18nScripts;
/// The runtime's first font stack: egui's bundled faces and no installed system fonts. CADCraft's own definitions
/// ([`crate::theme::install_fonts`]) replace it in the first pass, before anything is drawn.
fn ui_fonts() -> UiFonts<'static> {
UiFonts::new(&SCRIPTS).system_fonts(SystemFonts::Off)
}
fn install_with(ctx: &egui::Context, shell: ShellInfo, windows: Arc<dyn WindowSystem>, frame: Option<Decision>) -> Result<(), String> {
let mut spec = craft_ui::InstallSpec::new(shell, windows).app_id(crate::os_window::app_id());
if let Some(frame) = frame {
spec = spec.frame(frame);
}
embed::install(ctx, spec, &ui_fonts()).map(drop).map_err(|error| format!("the UI runtime could not be installed: {error}"))
}
/// Who draws the main window's frame, decided once before the window opens: on macOS the traffic lights sit over
/// CADCraft's title row (a full-size content view with a hidden title), elsewhere the system draws the frame.
/// `CADCRAFT_TITLEBAR=system` keeps the macOS title bar. `None` where the system decides alone.
#[cfg(not(target_arch = "wasm32"))]
pub fn frame_decision(forced_x11: bool) -> Option<Decision> {
use craft_host::target::Backend;
let backend = if forced_x11 { Backend::X11 } else { Backend::from_env() };
cfg!(target_os = "macos").then(|| craft_window::policy::decide_for(PREFIX, backend, craft_window::policy::TitleBarPref::Integrated))
}
/// Installs the runtime on the desktop window's context, once, before the first pass. `forced_x11` when the app
/// opens its window through XWayland; `frame` is [`frame_decision`]'s.
#[cfg(not(target_arch = "wasm32"))]
pub fn install(ctx: &egui::Context, forced_x11: bool, frame: Option<Decision>) -> Result<(), String> {
use craft_host::target::Backend;
let backend = if forced_x11 { Backend::X11 } else { Backend::from_env() };
install_with(ctx, ShellInfo::default().backend(backend), Arc::new(craft_window::system::SystemWindows), frame)
}
/// Installs the runtime on a context with no native window of its own: the browser build's canvas and test windows.
pub fn install_headless(ctx: &egui::Context) {
if let Err(error) = install_with(ctx, ShellInfo::default(), Arc::new(craft_window::system::NoWindows), None) {
log::warn!("{error}");
}
}
/// Who CADCraft is to the framework's dock and dialogs (the update dialogs show its name and icon).
pub(crate) fn host() -> Arc<Host> {
Arc::new(
Host::builder(AppInfo { id: "cadcraft", name: "CADCraft", version: env!("CARGO_PKG_VERSION") })
.icon_png(include_bytes!("../../../assets/app-icon/hicolor/128x128/apps/ai.storyteller.cadcraft.png"))
.build(),
)
}
/// Every function key is CADCraft's to assign (Tools ▸ Shortcuts records any of them), so the runtime's F6 and
/// Shift+F6 pane moves are unbound. Overrides are keyed by command id, which the command set gives.
fn command_overrides() -> Arc<Overrides> {
static OVERRIDES: OnceLock<Arc<Overrides>> = OnceLock::new();
OVERRIDES
.get_or_init(|| {
let mut overrides = Overrides::new();
for id in [NavCommand::NextPane.id(), NavCommand::PreviousPane.id()] {
overrides.insert(id, Vec::new());
}
Arc::new(overrides)
})
.clone()
}
impl CadApp {
/// The framework's part of `App::raw_input_hook`, once per frame before the first pass: takes what the runtime
/// gathered since the last frame and gives the coming passes the root values (theme mode, interface scale).
pub fn before_input(&mut self, ctx: &egui::Context) {
embed::before_input(ctx, |output| self.frame_input(ctx, output));
}
/// Takes the Copy, Cut and Paste chords the runtime ran as its own `edit.*` commands, because nothing in a
/// floating panel's window had them (the runtime keeps those clipboard events out of the window's input, so
/// [`CadApp::forward_native_input`] never sees them). The shortcuts read them as the clipboard events they stand
/// for, with the paste's text. Undo, Redo, Select All and Delete are not read here: their keys are still forwarded.
/// A chord with Shift (COPYBASE, PASTEBLOCK) is no `edit.*` command and arrives as a key press.
pub fn queue_fired_edits(&mut self, ctx: &egui::Context, fired: &[Fired]) {
let before = self.fired_edits.len();
for fired in fired.iter().filter(|fired| fired.source == FireSource::Key && fired.phase == FirePhase::Press && !fired.mods.shift) {
match fired.command.id.as_str() {
id if id == EditCommands::Copy.id() => self.fired_edits.push(egui::Event::Copy),
id if id == EditCommands::Cut.id() => self.fired_edits.push(egui::Event::Cut),
// A paste with no text (an empty or image clipboard) sends no event in the main window either.
id if id == EditCommands::Paste.id() => {
if let Some(text) = fired.pasted.as_ref().and_then(|content| content.text.as_deref()) {
self.fired_edits.push(egui::Event::Paste(text.to_string()));
}
}
_ => {}
}
}
if self.fired_edits.len() > before {
ctx.request_repaint_of(ViewportId::ROOT);
}
}
/// The root values of this frame. CADCraft registers no commands with the runtime and lets it toggle no chrome, so
/// it acts only on the clipboard commands the output carries. The interface scale is the Options value: the runtime
/// is the one writer of egui's zoom factor. While one of CADCraft's own modals shows (Save Changes, the lossy-save
/// warning, Drawing Recovery, an egui modal), the runtime blocks the panels floated into windows of their own.
fn frame_input(&mut self, ctx: &egui::Context, output: FrameOutput) -> FrameInput {
self.queue_fired_edits(ctx, &output.fired);
let mode = match self.ui.theme.resolve(ctx.system_theme()) {
egui::Theme::Light => craft_theme::Mode::Light,
egui::Theme::Dark => craft_theme::Mode::Dark,
};
let root = RootEnv::new().mode(mode).scale(Scale::new(self.options.interface_scale));
let app_modal = crate::docking::native_input_blocked(self, ctx).then_some(ViewportId::ROOT);
FrameInput::new(root).commands(CommandInput::new().overrides(command_overrides())).host(Arc::clone(&self.framework_host)).app_modal(app_modal)
}
/// The keyboard zoom: Ctrl+=, Ctrl++ and Ctrl+- (Cmd on macOS) step the Options dialog's interface scale by a tenth
/// within its limits, and Ctrl+0 sets it back to the system's own size, also while a text field has the keyboard.
/// It takes the keys out of `viewport`'s input, so it runs after the shortcuts, where the user may have given one of
/// these keys to a command. A shortcut being recorded gets them, and in the browser they zoom the page.
pub(crate) fn zoom_keys(&mut self, ctx: &egui::Context, viewport: ViewportId) {
use egui::gui_zoom::kb_shortcuts::{ZOOM_IN, ZOOM_IN_SECONDARY, ZOOM_OUT, ZOOM_RESET};
if cfg!(target_arch = "wasm32") || crate::keys::recording(ctx) {
return;
}
let (smallest, largest) = (*INTERFACE_SCALES.start(), *INTERFACE_SCALES.end());
let step = |scale: f32, by: f32| ((scale + by).clamp(smallest, largest) * 10.0).round() / 10.0;
let shown = self.options.interface_scale;
let scale = ctx.input_mut_for(viewport, |input| {
if input.consume_shortcut(&ZOOM_RESET) {
return 1.0;
}
let mut scale = shown;
if input.consume_shortcut(&ZOOM_IN) || input.consume_shortcut(&ZOOM_IN_SECONDARY) {
scale = step(scale, 0.1);
}
if input.consume_shortcut(&ZOOM_OUT) {
scale = step(scale, -0.1);
}
scale
});
if scale != shown {
self.options.interface_scale = scale;
// The next frame's root values carry it.
ctx.request_repaint_of(ViewportId::ROOT);
}
}
/// The framework's part of `App::logic`, after CADCraft's own: the root window's close path. Unsaved drawings hold
/// the window open while Save Changes asks about each ([`CadApp::request_quit`]); otherwise it closes.
pub fn close_path(&mut self, ctx: &egui::Context) {
embed::logic(ctx, || if self.request_quit() { CloseDecision::Hold } else { CloseDecision::Close });
}
/// The framework dialogs open on [`CadApp::framework_dialogs`], once per pass after CADCraft's own UI.
pub(crate) fn run_framework_dialogs(&mut self, ui: &mut egui::Ui) {
self.framework_dialogs.run(ui);
}
}
/// The drawing's widget, the window's document canvas.
pub(crate) fn drawing_id() -> egui::Id {
egui::Id::unique("cadcraft-drawing")
}
/// Declares the drawing, drawn in this pass, as the window's document canvas. With nothing focused it is the window's
/// key target: Enter, the arrows, Delete, the edit chords and the clipboard events stay in egui's input for the command
/// line and CADCraft's shortcuts. Tab and Shift+Tab stop at the drawing; with `keeps_tab` the focused drawing keeps
/// them in egui's input, else they move on from it.
pub(crate) fn host_canvas(ctx: &egui::Context, keeps_tab: bool) {
const KEYS: KeyUse = KeyUse::CANVAS.with_edits(EditSet::ALL);
let keys = if keeps_tab { KEYS.with_keep(KeepKeys::Tab) } else { KEYS };
craft_ui::runtime::focus::host_canvas(ctx, drawing_id(), keys);
}
/// Whether a modal dialog, CADCraft's, egui's or the framework's, or an egui menu or popup is up. A framework menu holds
/// the focus in its own layer.
pub(crate) fn overlay_open(app: &CadApp, ctx: &egui::Context) -> bool {
crate::docking::native_input_blocked(app, ctx) || egui::Popup::is_any_open(ctx) || overlay::any_open(ctx, OpenFilter::Modal)
}
/// Whether a widget other than the drawing has the keyboard. The command line and CADCraft's shortcuts have it
/// otherwise: with nothing focused, and while the drawing is the focused Tab stop.
pub(crate) fn widget_has_keyboard(ctx: &egui::Context) -> bool {
ctx.egui_wants_keyboard_input() && !ctx.memory(|memory| memory.has_focus(drawing_id()))
}
/// Whether Escape was pressed in this pass: from egui while one of CADCraft's own widgets or popups has the keyboard,
/// otherwise the window's cancel, which the runtime routes to no component. Leaves it for later readers.
pub(crate) fn escape_pressed(ctx: &egui::Context) -> bool {
ctx.input(|i| i.key_pressed(egui::Key::Escape)) || window_cancel_pending(ctx)
}
/// Whether the window's cancel (an Escape while nothing has framework focus) is there and untaken.
pub(crate) fn window_cancel_pending(ctx: &egui::Context) -> bool {
let mut pending = false;
with_window_intents(ctx, false, |intents| {
pending = intents.untaken(&Intent::Cancel);
false
});
pending
}
/// The window frame the app decides, for the main window's builder and the runtime.
pub use craft_window::policy::Decision;
/// `builder` with the decided `frame` applied: the macOS inset frame's full-size content view and hidden title.
pub fn apply_frame(builder: egui::ViewportBuilder, frame: Option<&Decision>) -> egui::ViewportBuilder {
match frame {
Some(decision) => craft_window::policy::apply(builder, &decision.frame),
None => builder,
}
}
/// Whether CADCraft draws the title row: the frame is not the system's.
pub fn draws_title_row(frame: Option<&Decision>) -> bool {
frame.is_some_and(|decision| !matches!(decision.frame, craft_window::policy::Frame::Native))
}
+4 -2
View File
@@ -269,6 +269,7 @@ mod tests {
let r = app.session.execute("line", &serde_json::json!({"points": [[0, 0], [10, 0]]})).unwrap();
let h = Handle::parse_hex(r["handles"][0].as_str().unwrap()).unwrap();
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
run_frame(&mut app, &ctx, Vec::new());
let at = app.canvas.rect.map_or(pos2(700.0, 450.0), |r| r.center() + vec2(40.0, -30.0));
run_frame(&mut app, &ctx, vec![Event::PointerMoved(at)]);
@@ -278,8 +279,7 @@ mod tests {
// `20` Tab: the length locks and the next field is active; the grip sits on the circle.
run_frame(&mut app, &ctx, vec![Event::Text("20".into())]);
// (Tab reaches the command line as text: `cmdline::capture_tab`.)
run_frame(&mut app, &ctx, vec![Event::Text("\t".into())]);
run_frame(&mut app, &ctx, key(egui::Key::Tab));
assert_eq!(app.canvas.grip_dyn.locked, [(0, "20".to_owned())]);
assert_eq!(app.canvas.grip_dyn.active, 1);
assert!(app.cmd.buffer.is_empty());
@@ -312,6 +312,7 @@ mod tests {
// The UCS icon paints "X" and "Y" too: off (UCSICON, which the drawing keeps).
app.run("ucsicon", serde_json::json!({"on": false})).unwrap();
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
crate::canvas::tests::painted_text(&mut app, &ctx, pos2(700.0, 450.0));
let at = app.canvas.xf.unwrap().to_screen(Vec2::ZERO) + vec2(130.0, -70.0);
let labels = |text: &str| text.lines().filter(|l| matches!(*l, "X" | "Y" | "<")).map(str::to_owned).collect::<Vec<_>>();
@@ -349,6 +350,7 @@ mod tests {
let r = app.session.execute("line", &serde_json::json!({"points": [[0, 0], [10, 0]]})).unwrap();
let h = Handle::parse_hex(r["handles"][0].as_str().unwrap()).unwrap();
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
crate::canvas::tests::painted_text(&mut app, &ctx, pos2(700.0, 450.0));
let at = app.canvas.xf.unwrap().to_screen(Vec2::ZERO) + vec2(130.0, -70.0);
app.session.start_grip_edit(&[(h, 2)]).unwrap();
+2 -2
View File
@@ -498,7 +498,7 @@ fn fill_ui(ui: &mut egui::Ui, f: &mut Fill, action: &mut Action) {
}
ui.end_row();
ui.label(crate::tl!("Shape"));
craft_ui::ComboBox::from_id_salt("hatch_shape").selected_text(shape_label(&f.shape)).show_ui(ui, |ui| {
egui::ComboBox::from_id_salt("hatch_shape").selected_text(shape_label(&f.shape)).show_ui(ui, |ui| {
for name in SHAPES {
ui.selectable_value(&mut f.shape, name.to_string(), shape_label(name));
}
@@ -545,7 +545,7 @@ fn fill_ui(ui: &mut egui::Ui, f: &mut Fill, action: &mut Action) {
f.origin = None;
}
ui.add_enabled_ui(f.origin.is_none(), |ui| {
craft_ui::ComboBox::from_id_salt("hatch_origin_mode").selected_text(origin_label(&f.origin_mode)).show_ui(ui, |ui| {
egui::ComboBox::from_id_salt("hatch_origin_mode").selected_text(origin_label(&f.origin_mode)).show_ui(ui, |ui| {
for m in ORIGIN_MODES {
ui.selectable_value(&mut f.origin_mode, m.to_string(), origin_label(m));
}
+1
View File
@@ -233,6 +233,7 @@ fn picks_merge_into_the_state() {
fn frames(app: &mut CadApp) -> egui::Context {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
app.logic(&ctx);
let input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 1000.0))), ..Default::default() };
// Enough frames for a window that grows each frame to show it.
+7
View File
@@ -398,6 +398,7 @@ fn the_wcs_pill_draws_its_arrow_instead_of_a_glyph_a_font_may_lack() {
// #1541: "WCS ⌄" showed a box where the UI font had no "⌄"; the chevron is now drawn as
// lines, so no catalog and no language paints the glyph.
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = CadApp::new(Session::new(), Services::default());
for language in &LANGUAGES {
assert!(!language.source.contains('\u{2304}'), "{}.tsv still has the \u{2304} glyph", language.code);
@@ -451,6 +452,7 @@ fn render(app: &mut CadApp, ctx: &egui::Context) -> String {
#[test]
fn the_command_line_says_or_before_keywords_as_the_prompt_does() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
for lang in ["en", "de"] {
let mut app = CadApp::new(Session::new(), Services::default());
app.run("ui.language", json!({ "lang": lang })).unwrap();
@@ -479,6 +481,7 @@ fn live_switch_translates_the_shell_without_mutating_drawing_or_automation() {
app.ui.in_window_menu = true;
app.session.state_mut().unwrap().title = "Open".into();
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
app.logic(&ctx);
assert!(render(&mut app, &ctx).contains("Properties"));
let commands = crate::control::all_commands(&app);
@@ -541,6 +544,7 @@ fn dialogs_render_in_every_language_and_keep_their_source_ids() {
app.ui.interface_language = Preference::parse(language.code).unwrap();
app.ui.dialog = Some(dialog.into());
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
app.logic(&ctx);
let text = render(&mut app, &ctx);
assert!(text.contains(tr(app.language(), heading)), "{}: {dialog}: {text}", language.code);
@@ -561,6 +565,7 @@ fn interface_fonts_cover_every_letter_in_each_catalog() {
continue;
}
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
if extra_font {
crate::theme::install_fonts(&ctx, language.code);
}
@@ -631,6 +636,7 @@ fn korean_ui_fonts_cover_the_language_picker_in_both_families() {
// The picker shows 한국어 in an English interface only when the CJK fonts loaded in every
// language cover Hangul; the Korean interface itself always does, with a fallback font.
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let english = crate::theme::cjk_covers_hangul();
assert_eq!(with_language("en", || Preference::Korean.name()), if english { "한국어" } else { "Korean" });
assert_eq!(with_language("ko", || Preference::Korean.name()), "한국어");
@@ -675,6 +681,7 @@ fn production_font_chain_covers_latin_and_shortcut_symbols() {
// `default_fonts` and `monochrome_emoji_fonts` in production, so web and native builds
// always start with bounded Latin and monochrome icon faces instead of an empty family.
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
crate::theme::install_fonts(&ctx, "en");
let mut output = ctx.run_ui(Default::default(), |_| {});
output.textures_delta.clear();
+1
View File
@@ -592,6 +592,7 @@
Query Entities 查询实体
Quick 快速
Quick Dimension 快速标注
Quick Leader 快速引线
Quick Properties 快速特性
Quick Select 快速选择
Quick Select Properties 快速选择特性
1 # CADCraft Simplified Chinese interface catalog — original translations.
592
593
594
595
596
597
598
+22 -15
View File
@@ -3,7 +3,6 @@
//! Icons are line drawings on a 24×24 design grid: light strokes for existing geometry, blue for
//! the geometry a command creates and orange dots for picked points.
use craft_ui::buttons::{ButtonVisuals, IconButton, IconButtonStyle};
use egui::{Color32, Painter, Pos2, Rect, Stroke, pos2};
use crate::theme::Tokens;
@@ -1146,23 +1145,31 @@ pub fn button(ui: &mut egui::Ui, icon: Icon, size: f32, tooltip: &str, selected:
button_bare(ui, icon, size, tooltip, selected).on_hover_text(crate::i18n::t(tooltip))
}
/// [`button`] without its hover text, for callers that show a richer tooltip of their own.
/// [`button`] without its hover text, for callers that show a richer tooltip of their own. CADCraft paints the
/// button in its own colours: transparent, the hover tint, the active-tab fill while selected, and an accent ring
/// inside it while it has keyboard focus.
pub fn button_bare(ui: &mut egui::Ui, icon: Icon, size: f32, tooltip: &str, selected: bool) -> egui::Response {
const RADIUS: egui::CornerRadius = egui::CornerRadius::same(3);
let t = Tokens::get();
let visuals = |fill| ButtonVisuals { fill, stroke: Stroke::NONE, icon: t.icon };
let style = IconButtonStyle {
normal: visuals(Color32::TRANSPARENT),
hovered: visuals(t.control_hover.gamma_multiply(0.6)),
pressed: None,
selected: visuals(t.tab_active),
corner_radius: egui::CornerRadius::same(3),
focus_stroke: Stroke::new(1.0, t.accent),
let label = crate::i18n::t(tooltip);
let (rect, resp) = ui.allocate_exact_size(egui::vec2(size, size), egui::Sense::click());
resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, ui.is_enabled(), selected, label));
let fill = if selected {
t.tab_active
} else if resp.hovered() {
t.control_hover.gamma_multiply(0.6)
} else {
Color32::TRANSPARENT
};
let resp = IconButton::new(crate::i18n::t(tooltip), egui::vec2(size, size), &style).selected(selected).show(ui, |ui, rect, _| {
// A single tint would erase the blue geometry and orange picked points. Keep the
// original painter and its explicit dimming on the same parent-enabled UI.
paint(ui.painter(), rect.shrink(size * 0.08), icon, !ui.is_enabled());
});
if fill != Color32::TRANSPARENT {
ui.painter().rect_filled(rect, RADIUS, fill);
}
// A single tint would erase the blue geometry and orange picked points: the original painter keeps its own
// colours and its explicit dimming.
paint(ui.painter(), rect.shrink(size * 0.08), icon, !ui.is_enabled());
if resp.has_focus() && size > 4.0 {
ui.painter().rect_stroke(rect.shrink(2.0), RADIUS, Stroke::new(1.0, t.accent), egui::StrokeKind::Inside);
}
crate::control::record_widget(ui, &resp, tooltip, "button", Some(selected));
resp
}
+2
View File
@@ -341,6 +341,8 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
_ => None,
})
});
// An Escape with nothing focused is the window's cancel, which the runtime keeps out of egui's events.
let pressed = pressed.or_else(|| crate::framework::window_cancel_pending(ctx).then_some((Key::Escape, egui::Modifiers::NONE)));
if let Some((k, m)) = pressed {
if k != Key::Escape {
note = Some(match assign(&mut app.ui.shortcuts, &id, &format(m, k)) {
+1 -1
View File
@@ -283,7 +283,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
// Layer states.
ui.label(crate::tl!("Layer State"));
let label = st.state_sel.clone().unwrap_or_else(|| crate::tl!("Unsaved Layer State").into());
craft_ui::ComboBox::from_id_salt("lpm_states").selected_text(label).width(170.0).show_ui(ui, |ui| {
egui::ComboBox::from_id_salt("lpm_states").selected_text(label).width(170.0).show_ui(ui, |ui| {
for s in &states {
if ui.selectable_label(st.state_sel.as_deref() == Some(s), s).clicked() {
st.state_sel = Some(s.clone());
+28 -22
View File
@@ -35,6 +35,7 @@ pub mod dialogs;
pub mod docking;
mod drawing_fonts;
pub mod fault;
pub mod framework;
// The Find and Replace window behind the FIND command.
pub mod arraydlg;
pub mod finddlg;
@@ -329,11 +330,17 @@ pub struct CadApp {
/// modifiers held there, for the main window's next input ([`Self::forward_native_input`]).
forwarded: Vec<egui::Event>,
forwarded_modifiers: Option<egui::Modifiers>,
/// The Copy, Cut and Paste a floating panel's window fired as framework commands, as the clipboard events the
/// shortcuts read ([`Self::queue_fired_edits`]).
fired_edits: Vec<egui::Event>,
/// The main window's own modifiers, put back the frame after forwarded keys went in.
restore_modifiers: Option<egui::Modifiers>,
/// A panel opened from a menu or command, whose floating window comes to the front on the
/// next frame (craft-ui's `DockArea::raise_panel`).
pub raise_panel: Option<docking::Panel>,
/// The panel arrangement the dock shows and the panels' specs ([`docking::LiveDock`]).
pub(crate) dock: docking::LiveDock,
/// Who CADCraft is to the framework's dock and dialogs ([`framework`]).
framework_host: std::sync::Arc<craft_host::Host>,
/// The framework dialogs CADCraft keeps open (the update dialogs), run after its own UI.
pub framework_dialogs: craft_ui::dialog::DialogHost,
/// One synthetic batch has been put into `RawInput` and is waiting for a real `App::ui` call.
synthetic_injected: bool,
/// Counts settled UI passes (one per painted frame; never hidden logic-only ticks or
@@ -352,8 +359,6 @@ pub struct CadApp {
shown_follows_system: bool,
/// Whether egui was last told to animate (`None` until the first frame).
shown_animations: Option<bool>,
/// The interface scale last handed to egui (`None` until the first frame).
shown_interface_scale: Option<f32>,
pub frame_ms: f64,
pub quit_requested: bool,
/// The app may close although drawings have unsaved changes (they were dealt with, or the
@@ -422,8 +427,11 @@ impl CadApp {
paste: clipboard::Paste::default(),
forwarded: Vec::new(),
forwarded_modifiers: None,
fired_edits: Vec::new(),
restore_modifiers: None,
raise_panel: None,
dock: docking::LiveDock::default(),
framework_host: framework::host(),
framework_dialogs: craft_ui::dialog::DialogHost::default(),
synthetic_injected: false,
ui_frames: 0,
#[cfg(not(target_arch = "wasm32"))]
@@ -433,7 +441,6 @@ impl CadApp {
shown_theme: None,
shown_follows_system: false,
shown_animations: None,
shown_interface_scale: None,
frame_ms: 0.0,
quit_requested: false,
quit_confirmed: false,
@@ -1015,11 +1022,6 @@ impl CadApp {
if self.restore_modifiers.is_some() {
ctx.request_repaint();
}
// Closing the window with unsaved changes asks first. `run_logic` refreshes viewport
// close/focus state, so this must also work while hidden.
if ctx.input(|i| i.viewport().close_requested()) && self.request_quit() {
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
}
// A long AutoLISP routine runs one bounded slice per frame, including hidden web/native
// ticks; it must not depend on a paint or `RequestPaintWhileHidden`.
self.session.lisp_tick();
@@ -1129,9 +1131,9 @@ impl CadApp {
// The batch reached an actual Ui callback; a discarded pass still consumed it.
self.synthetic_injected = false;
}
// `will_discard()` is false on the settled (final) pass of a frame, whether the frame is
// single-pass or the second pass after a layout discard; a discarded pass is skipped.
if !ctx.will_discard() {
// `will_rerun` is false on the settled (final) pass of a frame, whether the frame is
// single-pass or the second pass after a layout discard; a pass that will run again is skipped.
if !craft_ui::runtime::frame::will_rerun(&ctx) {
self.ui_frames = self.ui_frames.saturating_add(1);
capture::issue(self, &ctx);
}
@@ -1173,13 +1175,6 @@ impl CadApp {
if !animate {
animation::unsmooth_scroll(ctx);
}
// Applied only when the saved scale changes, so egui's own keyboard zoom keeps working
// within a session (and is never saved).
let scale = self.options.interface_scale;
if self.shown_interface_scale != Some(scale) {
ctx.set_zoom_factor(scale);
self.shown_interface_scale = Some(scale);
}
// Wait for the frame cap on a painted pass, where a wait cannot delay a hidden tick.
#[cfg(not(target_arch = "wasm32"))]
if let Some(cap) = &mut self.frame_cap {
@@ -1192,6 +1187,7 @@ impl CadApp {
/// Input-derived work, once per layout frame.
fn ui_input(&mut self, ctx: &egui::Context) {
menus::shortcuts(self, ctx);
self.zoom_keys(ctx, egui::ViewportId::ROOT);
#[cfg(not(target_arch = "wasm32"))]
{
let dropped = ctx.input_mut(|input| std::mem::take(&mut input.raw.dropped_files));
@@ -1231,6 +1227,7 @@ impl CadApp {
if has_doc {
docking::show(self, ui);
} else {
self.canvas.shown = None;
chrome::start_page(self, ui);
}
});
@@ -1244,6 +1241,7 @@ impl CadApp {
autosave::show(self, ui.ctx());
autosave::gpu_notice(self, ui.ctx());
autosave::failure_notice(self, ui.ctx());
self.run_framework_dialogs(ui);
self.frame_ms = now_ms() - t0;
}
@@ -1363,6 +1361,7 @@ mod tests {
start(&mut single);
start(&mut twice);
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
frame(&mut single, &ctx, None);
two_pass_frame(&mut twice, &ctx);
let counter = |app: &CadApp| match app.session.lisp_var("CC-TWO") {
@@ -1386,6 +1385,7 @@ mod tests {
let (request, reply) = ControlRequest::new("engine.execute", json!({ "command": "line", "params": { "points": [[0.0, 0.0], [10.0, 0.0]] } }));
tx.send(request).expect("the request is queued");
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
two_pass_frame(&mut app, &ctx);
let entities = app.session.doc().map(cadcraft_doc::Drawing::entity_count).unwrap_or_default();
assert_eq!(entities, 1, "one command ran once, in the first pass");
@@ -1398,6 +1398,7 @@ mod tests {
fn hidden_logic_does_not_run_frame_only_work() {
let mut a = app();
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
// A logic-only call (what eframe runs for a hidden window) reports pass index zero too.
a.logic(&ctx);
assert_eq!(a.ui_frames, 0, "no real Ui callback ran");
@@ -1414,6 +1415,7 @@ mod tests {
let mut a = CadApp::new(Session::new(), Services::default());
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let started = a
.session
.lisp_eval("(setq cc-hidden 0) (while (< cc-hidden 400000) (setq cc-hidden (1+ cc-hidden)))", false, false, Vec::new())
@@ -1437,6 +1439,7 @@ mod tests {
fn one_synthetic_batch_waits_for_a_real_ui_pass() {
let mut a = app();
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
a.synthetic.push(egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE });
let mut first = egui::RawInput::default();
a.raw_input_hook(&ctx, &mut first);
@@ -1472,6 +1475,7 @@ mod tests {
assert_eq!(b.ui.theme, ThemePref::Light, "bad prefs are ignored");
// A fixed choice ignores the OS; the tokens and egui follow the choice.
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
frame(&mut b, &ctx, Some(egui::Theme::Dark));
assert_eq!(Tokens::get(), Tokens::LIGHT);
assert_eq!(ctx.theme(), egui::Theme::Light);
@@ -1489,6 +1493,7 @@ mod tests {
let mut a = app();
a.start("ui.theme.system");
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
frame(&mut a, &ctx, Some(egui::Theme::Light));
assert_eq!(Tokens::get(), Tokens::LIGHT);
assert_eq!(ctx.theme(), egui::Theme::Light);
@@ -1507,6 +1512,7 @@ mod tests {
let mut a = app();
a.start("ui.theme.system");
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
frame(&mut a, &ctx, Some(egui::Theme::Light));
// A concrete Light would pin the native window appearance and hide later OS changes.
assert_eq!(ctx.options(|o| o.theme_preference), egui::ThemePreference::System);
+1 -1
View File
@@ -143,7 +143,7 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) {
});
});
let outside = ctx.input(|i| i.pointer.primary_pressed() && i.pointer.interact_pos().is_some_and(|p| !area.response.rect.contains(p)));
if ctx.input(|i| i.key_pressed(Key::Escape)) {
if crate::framework::escape_pressed(ctx) {
done = Done::Cancel;
} else if armed && outside {
done = Done::Ok;
+7 -7
View File
@@ -139,7 +139,7 @@ fn linetype(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Action {
let mut pick_lin = false;
egui::Window::new("Linetype Manager").open(open).default_size(vec2(520.0, 360.0)).resizable(true).show(ctx, |ui| {
ui.horizontal(|ui| {
craft_ui::ComboBox::from_id_salt("ltmgr_load").selected_text("Load...").width(110.0).show_ui(ui, |ui| {
egui::ComboBox::from_id_salt("ltmgr_load").selected_text("Load...").width(110.0).show_ui(ui, |ui| {
if library.is_empty() {
ui.label("Every library linetype is loaded.");
} else if ui.selectable_label(false, "All").clicked() {
@@ -519,7 +519,7 @@ fn style_manager(ctx: &egui::Context, open: &mut bool, title: &str, cmd: &'stati
Field::Choice(key, label, v, choices) => {
ui.label(*label);
let mut picked = None;
craft_ui::ComboBox::from_id_salt((cmd, *key)).selected_text(v.as_str()).show_ui(ui, |ui| {
egui::ComboBox::from_id_salt((cmd, *key)).selected_text(v.as_str()).show_ui(ui, |ui| {
for c in choices.iter() {
if ui.selectable_label(c == v, c).clicked() && c != v {
picked = Some(c.clone());
@@ -682,7 +682,7 @@ fn page_rows(
) -> Option<(&'static str, Value)> {
let mut change = None;
ui.label("Printer/plotter");
craft_ui::ComboBox::from_id_salt(salt.with("device")).selected_text(device_label(page)).width(190.0).show_ui(ui, |ui| {
egui::ComboBox::from_id_salt(salt.with("device")).selected_text(device_label(page)).width(190.0).show_ui(ui, |ui| {
if ui.selectable_label(device_label(page) == "None", "None").on_hover_text("PDF on the paper chosen below").clicked()
&& device_label(page) != "None"
{
@@ -701,7 +701,7 @@ fn page_rows(
// The device's papers, else the standard sizes.
let device = choices.devices.iter().find(|dv| dv.name.eq_ignore_ascii_case(&page.device));
ui.label("Paper size");
craft_ui::ComboBox::from_id_salt(salt.with("paper")).selected_text(page.paper.as_str()).width(190.0).show_ui(ui, |ui| match device {
egui::ComboBox::from_id_salt(salt.with("paper")).selected_text(page.paper.as_str()).width(190.0).show_ui(ui, |ui| match device {
Some(dev) => {
for p in &dev.papers {
if ui.selectable_label(p.name == page.paper, &p.name).clicked() && p.name != page.paper {
@@ -747,7 +747,7 @@ fn page_rows(
}
ui.label("Plot area");
ui.add_enabled_ui(rows.areas.len() > 1, |ui| {
craft_ui::ComboBox::from_id_salt(salt.with("area")).selected_text(area_label(&page.plot_area)).show_ui(ui, |ui| {
egui::ComboBox::from_id_salt(salt.with("area")).selected_text(area_label(&page.plot_area)).show_ui(ui, |ui| {
for a in rows.areas {
if ui.selectable_label(page.plot_area == *a, area_label(a)).clicked() && page.plot_area != *a {
change = Some(("plotArea", json!(a)));
@@ -823,7 +823,7 @@ fn page_rows(
}
ui.end_row();
ui.label("Plot style table");
craft_ui::ComboBox::from_id_salt(salt.with("styles")).selected_text(style_label(page)).width(190.0).show_ui(ui, |ui| {
egui::ComboBox::from_id_salt(salt.with("styles")).selected_text(style_label(page)).width(190.0).show_ui(ui, |ui| {
if ui.selectable_label(style_label(page) == "None", "None").clicked() && style_label(page) != "None" {
change = Some(("plotStyleTable", json!("None")));
}
@@ -1041,7 +1041,7 @@ fn plot(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Action {
egui::Window::new("Plot").open(open).collapsible(false).resizable(false).pivot(egui::Align2::CENTER_CENTER).default_pos(center).show(ctx, |ui| {
egui::Grid::new("plot_target").num_columns(2).spacing(vec2(10.0, 6.0)).show(ui, |ui| {
ui.label("Layout");
craft_ui::ComboBox::from_id_salt("plot_layout").selected_text(st.target.as_str()).width(190.0).show_ui(ui, |ui| {
egui::ComboBox::from_id_salt("plot_layout").selected_text(st.target.as_str()).width(190.0).show_ui(ui, |ui| {
for n in &targets {
if ui.selectable_label(*n == st.target, n).clicked() && *n != st.target {
st.page = plot_page(d, n);
+2 -2
View File
@@ -103,7 +103,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Option<
}
ui.horizontal(|ui| {
ui.label("Block:");
craft_ui::ComboBox::from_id_salt("battman_blocks").selected_text(block.as_str()).width(180.0).show_ui(ui, |ui| {
egui::ComboBox::from_id_salt("battman_blocks").selected_text(block.as_str()).width(180.0).show_ui(ui, |ui| {
for b in &blocks {
if ui.selectable_label(*b == block, b).clicked() {
block = b.clone();
@@ -189,7 +189,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Option<
}
ui.end_row();
ui.label("Layer");
craft_ui::ComboBox::from_id_salt("battman_layer").selected_text(r.layer.as_str()).show_ui(ui, |ui| {
egui::ComboBox::from_id_salt("battman_layer").selected_text(r.layer.as_str()).show_ui(ui, |ui| {
for l in &layers {
if ui.selectable_label(*l == r.layer, l).clicked() && *l != r.layer {
action = act(edit("layer", json!(l)), apply);
+6 -6
View File
@@ -285,7 +285,7 @@ fn list_page(
}
});
});
let filter = craft_ui::ComboBox::from_id_salt("dimstyle_list_filter")
let filter = egui::ComboBox::from_id_salt("dimstyle_list_filter")
.selected_text(if st.in_use_only { crate::tl!("Styles in use") } else { crate::tl!("All styles") })
.show_ui(ui, |ui| {
ui.selectable_value(&mut st.in_use_only, false, crate::tl!("All styles"));
@@ -434,7 +434,7 @@ fn new_page(ui: &mut egui::Ui, d: &Drawing, st: &mut State) {
ui.add(egui::TextEdit::singleline(&mut st.new_name).desired_width(220.0)).labelled_by(name_label.id);
ui.end_row();
let start_label = ui.label(crate::tl!("Start with"));
let start = craft_ui::ComboBox::from_id_salt("dimstyle_start_with").selected_text(st.start_with.clone()).width(220.0).show_ui(ui, |ui| {
let start = egui::ComboBox::from_id_salt("dimstyle_start_with").selected_text(st.start_with.clone()).width(220.0).show_ui(ui, |ui| {
for s in &d.dim_styles {
ui.selectable_value(&mut st.start_with, s.name.clone(), &s.name);
}
@@ -620,7 +620,7 @@ fn fields(ui: &mut egui::Ui, d: &Drawing, st: &mut State) {
DimPropKind::Color => {
let c = serde_json::from_value::<cadcraft_color::Color>(cur.clone()).unwrap_or(cadcraft_color::Color::ByBlock);
let mut out = None;
craft_ui::ComboBox::from_id_salt(id).selected_text(crate::i18n::t(&c.name())).width(160.0).show_ui(ui, |ui| {
egui::ComboBox::from_id_salt(id).selected_text(crate::i18n::t(&c.name())).width(160.0).show_ui(ui, |ui| {
for (n, aci) in [
("ByBlock", 0),
("ByLayer", 256),
@@ -677,7 +677,7 @@ fn combo(ui: &mut egui::Ui, id: egui::Id, cur: &Value, options: Vec<(Value, Stri
.find(|(v, _)| v == cur)
.map_or_else(|| cur.as_str().map(str::to_string).unwrap_or_else(|| cur.to_string()), |(_, l)| l.clone());
let mut out = None;
craft_ui::ComboBox::from_id_salt(id).selected_text(shown).width(160.0).show_ui(ui, |ui| {
egui::ComboBox::from_id_salt(id).selected_text(shown).width(160.0).show_ui(ui, |ui| {
for (v, label) in options {
if ui.selectable_label(v == *cur, label).clicked() {
out = Some(v);
@@ -698,14 +698,14 @@ fn compare_page(ui: &mut egui::Ui, d: &Drawing, st: &mut State, current: &str, o
}
ui.horizontal(|ui| {
let compare_label = ui.label(crate::tl!("Compare"));
let a = craft_ui::ComboBox::from_id_salt("dimstyle_compare_a").selected_text(st.selected.clone()).show_ui(ui, |ui| {
let a = egui::ComboBox::from_id_salt("dimstyle_compare_a").selected_text(st.selected.clone()).show_ui(ui, |ui| {
for n in &names {
ui.selectable_value(&mut st.selected, n.clone(), n);
}
});
a.response.labelled_by(compare_label.id);
let with_label = ui.label(crate::tl!("With"));
let b = craft_ui::ComboBox::from_id_salt("dimstyle_compare_b").selected_text(st.compare_with.clone()).show_ui(ui, |ui| {
let b = egui::ComboBox::from_id_salt("dimstyle_compare_b").selected_text(st.compare_with.clone()).show_ui(ui, |ui| {
for n in &names {
ui.selectable_value(&mut st.compare_with, n.clone(), n);
}
+30 -7
View File
@@ -849,7 +849,7 @@ pub fn activate(app: &mut CadApp, id: &str) {
run_transparent(app, id);
return;
}
if id == "xref" && app.ui.docking.layout.contains(&crate::docking::Panel::ExternalRefs) {
if id == "xref" && app.ui.docking.layout().contains(&crate::docking::Panel::ExternalRefs) {
if let Err(e) = crate::xrefs::close_palette(app) {
app.set_status(e);
}
@@ -874,14 +874,36 @@ pub fn activate_native(app: &mut CadApp, ctx: &egui::Context, id: &str) {
app.synthetic.extend(events);
ctx.request_repaint();
}
TextCommand::Events(events) => craft_ui::docking::send_keys(ctx, window, events),
TextCommand::Events(events) => {
// The menu took the key from the floating panel's own window: it reaches that window as the key pressed.
let host = craft_ui::runtime::windows::WindowHost::of(ctx);
let platform = craft_keymap::egui::platform(ctx);
for equivalent in events.iter().filter_map(|event| key_equivalent(event, platform)) {
host.key_equivalent(window, equivalent);
}
}
}
}
/// The window whose text field has the keyboard: a floating panel's own OS window, or the main
/// window.
/// The key equivalent the native menu took for `event`: a copy, a cut, or a key press as a tap of its chord.
fn key_equivalent(event: &egui::Event, platform: craft_keymap::Platform) -> Option<craft_ui::runtime::windows::KeyEquivalent> {
use craft_ui::runtime::windows::KeyEquivalent;
match event {
egui::Event::Copy => Some(KeyEquivalent::Copy),
egui::Event::Cut => Some(KeyEquivalent::Cut),
egui::Event::Key { key, pressed: true, modifiers, .. } => {
let key = craft_keymap::Key::from_egui(*key)?;
Some(KeyEquivalent::Tap(craft_keymap::Chord::new(craft_keymap::Mods::from_egui(modifiers, platform), key)))
}
_ => None,
}
}
/// The window whose text field has the keyboard: the window that has the keys (a floating panel's own OS window, or
/// the main window) while a text field there has the focus.
pub fn text_field_window(ctx: &egui::Context) -> Option<egui::ViewportId> {
craft_ui::docking::typing_window(ctx).or_else(|| ctx.text_edit_focused().then_some(egui::ViewportId::ROOT))
let host = craft_ui::runtime::windows::WindowHost::of(ctx);
host.typing().then(|| host.key_window())
}
/// Whether a focused text field takes the menu command `id` ([`activate_native`]): a native
@@ -978,6 +1000,7 @@ pub fn shortcuts(app: &mut CadApp, ctx: &egui::Context) {
if app.ui.dialog.as_deref() != Some(crate::keys::DIALOG) {
crate::keys::stop_recording(ctx);
}
let float_edits = std::mem::take(&mut app.fired_edits);
if crate::keys::recording(ctx) {
return;
}
@@ -992,13 +1015,13 @@ pub fn shortcuts(app: &mut CadApp, ctx: &egui::Context) {
if pairs.iter().any(|(s, id)| *s == quickcalc && id == "ui.toggle.quickcalc") && ctx.input_mut(|i| i.consume_shortcut(&quickcalc)) {
run_transparent(app, "ui.toggle.quickcalc");
}
if ctx.egui_wants_keyboard_input() {
if crate::framework::widget_has_keyboard(ctx) {
return;
}
// Cmd/Ctrl+C, X and V arrive as clipboard events, not key presses.
let mut fire: Vec<String> = Vec::new();
let mut pasted_table = false;
for action in crate::clipboard::shortcut_actions(app, ctx) {
for action in crate::clipboard::shortcut_actions(app, ctx, float_edits) {
match action {
crate::clipboard::ShortcutAction::Command(id) => {
let id = id.to_string();
+9 -3
View File
@@ -159,7 +159,7 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) {
});
});
});
if ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
if crate::framework::escape_pressed(ctx) {
done = Done::Cancel;
} else if ctx.input(|i| i.modifiers.command && i.key_pressed(egui::Key::Enter)) {
done = Done::Ok;
@@ -251,7 +251,7 @@ fn toolbar(ui: &mut egui::Ui, st: &mut State, base_h: f64) {
ui.add_space(4.0);
// Font
let shown = cur.font.clone().unwrap_or_else(|| st.fmt.base_font.clone());
craft_ui::ComboBox::from_id_salt("mtext_font")
egui::ComboBox::from_id_salt("mtext_font")
.width(120.0)
.selected_text(shown.clone())
.show_ui(ui, |ui| {
@@ -592,7 +592,7 @@ fn text_box(ui: &mut egui::Ui, st: &mut State, base_h: f64, px: f32, width: f32,
out.response.response.clone().accessible_name(crate::tl!("Text"));
// On opening, and while the text is empty, the editor takes the focus; a field of the toolbar
// the user clicked keeps it.
let free = ui.memory(|m| m.focused().is_none());
let free = !crate::framework::widget_has_keyboard(ui.ctx());
if !out.response.has_focus() && (!st.focused || (buf.is_empty() && st.fmt.is_empty() && free)) {
out.response.request_focus();
}
@@ -712,6 +712,7 @@ mod tests {
#[test]
fn diameter_button_is_painted_and_named_under_bundled_fonts() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
ctx.set_missing_glyph_policy(egui::MissingGlyphPolicy::Panic);
let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(120.0, 60.0))), ..Default::default() };
let mut out = ctx.run_ui(raw, |ui| {
@@ -758,6 +759,7 @@ mod tests {
#[test]
fn editor_opens_only_for_mtext_text_entry_and_finishes_with_formatted_contents() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = CadApp::new(Session::new(), Services::default());
let frame = |app: &mut CadApp| {
let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1200.0, 800.0))), ..Default::default() };
@@ -793,6 +795,7 @@ mod tests {
#[test]
fn textedit_on_the_next_mtext_does_not_keep_the_first_ones_text() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = CadApp::new(Session::new(), Services::default());
let frame = |app: &mut CadApp| {
let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1200.0, 800.0))), ..Default::default() };
@@ -818,6 +821,7 @@ mod tests {
#[test]
fn textedit_opens_an_existing_mtext_with_its_contents() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = CadApp::new(Session::new(), Services::default());
let frame = |app: &mut CadApp| {
let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1200.0, 800.0))), ..Default::default() };
@@ -853,6 +857,7 @@ mod tests {
#[test]
fn a_relative_height_in_a_multileaders_text_is_kept() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = CadApp::new(Session::new(), Services::default());
let frame = |app: &mut CadApp| {
let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1200.0, 800.0))), ..Default::default() };
@@ -896,6 +901,7 @@ mod tests {
return;
}
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = CadApp::new(Session::new(), Services::default());
app.run("mtext", serde_json::json!({ "at": [0, 20], "text": thai, "height": 2.5, "width": 40 })).unwrap();
app.start("textedit");
+5 -5
View File
@@ -141,7 +141,7 @@ fn display(app: &CadApp, ui: &mut egui::Ui, changes: &mut Map<String, Value>) {
grid(ui, "options_display", |ui| {
let theme_caption = ui.label(crate::tl!("Interface theme"));
let mut theme = app.ui.theme;
let theme_combo = craft_ui::ComboBox::from_id_salt("options_theme").selected_text(theme_label(theme)).show_ui(ui, |ui| {
let theme_combo = egui::ComboBox::from_id_salt("options_theme").selected_text(theme_label(theme)).show_ui(ui, |ui| {
for t in ThemePref::ALL {
ui.selectable_value(&mut theme, t, theme_label(t));
}
@@ -154,7 +154,7 @@ fn display(app: &CadApp, ui: &mut egui::Ui, changes: &mut Map<String, Value>) {
let animations_caption = ui.label(crate::tl!("Animation effects"));
let mut animations = app.ui.animations;
let animations_combo = craft_ui::ComboBox::from_id_salt("options_animations").selected_text(animations_label(animations)).show_ui(ui, |ui| {
let animations_combo = egui::ComboBox::from_id_salt("options_animations").selected_text(animations_label(animations)).show_ui(ui, |ui| {
for a in AnimationPref::ALL {
ui.selectable_value(&mut animations, a, animations_label(a));
}
@@ -168,7 +168,7 @@ fn display(app: &CadApp, ui: &mut egui::Ui, changes: &mut Map<String, Value>) {
let scale_caption = ui.label(crate::tl!("Interface scale"));
let scale = app.options.interface_scale;
let percent = |s: f32| format!("{} %", (s * 100.0).round());
let scale_combo = craft_ui::ComboBox::from_id_salt("options_interface_scale").selected_text(percent(scale)).show_ui(ui, |ui| {
let scale_combo = egui::ComboBox::from_id_salt("options_interface_scale").selected_text(percent(scale)).show_ui(ui, |ui| {
for n in [75u16, 100, 125, 150, 175, 200, 250, 300] {
let s = f32::from(n) / 100.0;
if ui.selectable_label((scale - s).abs() < 1e-4, format!("{n} %")).clicked() && (scale - s).abs() >= 1e-4 {
@@ -254,7 +254,7 @@ fn save_version_row(ui: &mut egui::Ui, app: &CadApp, changes: &mut Map<String, V
let version_caption = ui.label(crate::tl!("Default save version"));
let current = crate::SaveVersion::parse(&app.ui.save_version).unwrap_or_default();
let mut version = current;
let version_combo = craft_ui::ComboBox::from_id_salt("options_save_version").selected_text(version.year()).show_ui(ui, |ui| {
let version_combo = egui::ComboBox::from_id_salt("options_save_version").selected_text(version.year()).show_ui(ui, |ui| {
for v in crate::SaveVersion::ALL {
ui.selectable_value(&mut version, v, v.year());
}
@@ -543,7 +543,7 @@ fn preferences(app: &CadApp, ui: &mut egui::Ui, changes: &mut Map<String, Value>
grid(ui, "options_preferences", |ui| {
let language_caption = ui.label(crate::tl!("Interface language"));
let mut lang = app.ui.interface_language;
let language_combo = craft_ui::ComboBox::from_id_salt("options_language").selected_text(lang.name()).show_ui(ui, |ui| {
let language_combo = egui::ComboBox::from_id_salt("options_language").selected_text(lang.name()).show_ui(ui, |ui| {
for p in crate::i18n::Preference::for_picker() {
ui.selectable_value(&mut lang, p, p.name());
}
+4 -4
View File
@@ -252,7 +252,7 @@ impl State {
/// Hiding the panel leaves its expression, history and variables intact.
pub(crate) fn toggle(app: &mut CadApp) -> Result<Value, String> {
let panel = crate::docking::Panel::QuickCalc;
if app.ui.docking.layout.contains(&panel) {
if app.ui.docking.layout().contains(&panel) {
crate::docking::command(app, false, &json!({ "operation": "close", "panel": panel.id() }))
} else {
open(app)
@@ -263,7 +263,7 @@ pub(crate) fn toggle(app: &mut CadApp) -> Result<Value, String> {
/// returns where it was closed.
pub fn open(app: &mut CadApp) -> Result<Value, String> {
let panel = crate::docking::Panel::QuickCalc;
let first = !app.ui.docking.layout.contains(&panel) && !app.ui.docking.hidden.iter().any(|(p, _)| *p == panel);
let first = !app.ui.docking.layout().contains(&panel) && !app.ui.docking.hidden().iter().any(|(p, _)| *p == panel);
let r = crate::docking::command(app, false, &json!({ "operation": "open", "panel": panel.id() }))?;
if !first {
return Ok(r);
@@ -371,7 +371,7 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) {
egui::Grid::new("qc-units-grid").num_columns(2).spacing(vec2(6.0, 4.0)).show(ui, |ui| {
ui.label(crate::tl!("Type"));
let kind_label = KINDS.get(st.kind).map_or("", |k| k.1);
craft_ui::ComboBox::from_id_salt("qc-kind").selected_text(crate::i18n::t(kind_label)).show_ui(ui, |ui| {
egui::ComboBox::from_id_salt("qc-kind").selected_text(crate::i18n::t(kind_label)).show_ui(ui, |ui| {
for (i, (_, label)) in KINDS.iter().enumerate() {
if ui.selectable_label(st.kind == i, crate::i18n::t(label)).clicked() {
st.kind = i;
@@ -386,7 +386,7 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) {
ui.label(label);
let sel = if which == 0 { &mut st.from } else { &mut st.to };
let shown = list.get(*sel).map(|u| u.1.clone()).unwrap_or_default();
craft_ui::ComboBox::from_id_salt(salt).selected_text(shown).show_ui(ui, |ui| {
egui::ComboBox::from_id_salt(salt).selected_text(shown).show_ui(ui, |ui| {
for (i, (_, sym)) in list.iter().enumerate() {
if ui.selectable_label(*sel == i, sym).clicked() {
*sel = i;
+3 -3
View File
@@ -69,7 +69,7 @@ fn window(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Action {
egui::Window::new(title).id(egui::Id::unique("Plot Style Manager")).open(open).default_size(vec2(760.0, 460.0)).resizable(true).show(ctx, |ui| {
ui.horizontal(|ui| {
ui.label(crate::tl!("Plot style table"));
craft_ui::ComboBox::from_id_salt("pstyle_table").selected_text(sel.as_str()).width(200.0).show_ui(ui, |ui| {
egui::ComboBox::from_id_salt("pstyle_table").selected_text(sel.as_str()).width(200.0).show_ui(ui, |ui| {
for n in &names {
if ui.selectable_label(n.eq_ignore_ascii_case(&sel), n).clicked() {
sel = n.clone();
@@ -160,7 +160,7 @@ fn window(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Action {
action = set(&table.name, style("screening", json!(screen)));
}
let lt = st.linetype.clone().unwrap_or_else(|| crate::tl!("Use object linetype").to_string());
craft_ui::ComboBox::from_id_salt(("pstyle_lt", &st.name)).selected_text(lt).width(140.0).show_ui(ui, |ui| {
egui::ComboBox::from_id_salt(("pstyle_lt", &st.name)).selected_text(lt).width(140.0).show_ui(ui, |ui| {
if ui.selectable_label(st.linetype.is_none(), crate::tl!("Use object linetype")).clicked() {
action = set(&table.name, style("linetype", Value::Null));
}
@@ -174,7 +174,7 @@ fn window(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Action {
.lineweight
.map(|w| format!("{:.2} mm", f64::from(w) / 100.0))
.unwrap_or_else(|| crate::tl!("Use object lineweight").to_string());
craft_ui::ComboBox::from_id_salt(("pstyle_lw", &st.name)).selected_text(lw).width(140.0).show_ui(ui, |ui| {
egui::ComboBox::from_id_salt(("pstyle_lw", &st.name)).selected_text(lw).width(140.0).show_ui(ui, |ui| {
if ui.selectable_label(st.lineweight.is_none(), crate::tl!("Use object lineweight")).clicked() {
action = set(&table.name, style("lineweight", Value::Null));
}
+5 -5
View File
@@ -86,7 +86,7 @@ pub fn qselect_dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
.show(ctx, |ui| {
egui::Grid::new("qs_grid").num_columns(2).spacing(vec2(10.0, 6.0)).show(ui, |ui| {
ui.label(crate::tl!("Apply to:"));
craft_ui::ComboBox::from_id_salt("qs_apply")
egui::ComboBox::from_id_salt("qs_apply")
.width(220.0)
.selected_text(crate::i18n::t(if st.apply_selection { "Current selection" } else { "Entire drawing" }))
.show_ui(ui, |ui| {
@@ -107,7 +107,7 @@ pub fn qselect_dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
.collect()
})
.unwrap_or_default();
craft_ui::ComboBox::from_id_salt("qs_type").width(220.0).selected_text(crate::i18n::t(&st.ty)).show_ui(ui, |ui| {
egui::ComboBox::from_id_salt("qs_type").width(220.0).selected_text(crate::i18n::t(&st.ty)).show_ui(ui, |ui| {
ui.selectable_value(&mut st.ty, "Multiple".to_string(), crate::tl!("Multiple"));
for (n, c) in &types {
ui.selectable_value(&mut st.ty, n.clone(), format!("{} ({c})", crate::i18n::t(n)));
@@ -136,7 +136,7 @@ pub fn qselect_dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
ui.end_row();
ui.label(crate::tl!("Operator:"));
let op_label = OPERATORS.iter().find(|o| o.0 == st.operator).map(|o| o.1).unwrap_or("= Equals");
craft_ui::ComboBox::from_id_salt("qs_op").width(220.0).selected_text(crate::i18n::t(op_label)).show_ui(ui, |ui| {
egui::ComboBox::from_id_salt("qs_op").width(220.0).selected_text(crate::i18n::t(op_label)).show_ui(ui, |ui| {
for (o, l) in OPERATORS {
ui.selectable_value(&mut st.operator, o.to_string(), crate::i18n::t(l));
}
@@ -317,7 +317,7 @@ pub fn quick_properties(app: &mut CadApp, ctx: &egui::Context) {
}
ui.end_row();
ui.label(RichText::new(crate::tl!("Layer")).color(Tokens::get().text_dim));
craft_ui::ComboBox::from_id_salt("qp_layer").width(150.0).selected_text(layer.clone()).show_ui(ui, |ui| {
egui::ComboBox::from_id_salt("qp_layer").width(150.0).selected_text(layer.clone()).show_ui(ui, |ui| {
for l in &layers {
if ui.selectable_label(*l == layer, l).clicked() {
set = Some(("layer".into(), json!(l)));
@@ -326,7 +326,7 @@ pub fn quick_properties(app: &mut CadApp, ctx: &egui::Context) {
});
ui.end_row();
ui.label(RichText::new(crate::tl!("Linetype")).color(Tokens::get().text_dim));
craft_ui::ComboBox::from_id_salt("qp_lt").width(150.0).selected_text(linetype.clone()).show_ui(ui, |ui| {
egui::ComboBox::from_id_salt("qp_lt").width(150.0).selected_text(linetype.clone()).show_ui(ui, |ui| {
for l in std::iter::once("ByLayer".to_string())
.chain(std::iter::once("ByBlock".to_string()))
.chain(linetypes.iter().filter(|l| !["ByLayer", "ByBlock"].contains(&l.as_str())).cloned())
+1 -1
View File
@@ -192,7 +192,7 @@ pub fn prompt(app: &mut CadApp, ctx: &egui::Context) {
choice = Some(Choice::SaveAnyway);
}
});
if ui.input(|i| i.key_pressed(egui::Key::Escape)) {
if crate::framework::escape_pressed(ui.ctx()) {
choice = Some(Choice::Cancel);
}
});
+1 -1
View File
@@ -406,7 +406,7 @@ pub fn install_fonts(ctx: &egui::Context, language: &str) {
{
f.push("Hack".into());
}
ctx.set_fonts(fonts);
craft_ui::fonts::load(ctx, fonts);
}
/// The system interface fonts [`install_fonts`] looks for, in order; it loads the first installed
+41 -21
View File
@@ -1,9 +1,10 @@
//! One background update check at startup, the "Update and Restart" prompt, and Help ▸ Check for
//! Updates… (desktop only; the web build is always the latest). The flow itself is
//! `craft_update::updater::Updater`.
//! `craft_update::updater::Updater`; its dialogs run on [`CadApp::framework_dialogs`].
use craft_ui::dialog::DialogResult;
use craft_update::stack_dialogs::{CheckChoice, UpdateCheckDialog};
use craft_update::updater::{Action, Status, Updater};
use craft_update::{CheckResultDialog, CheckResultResponse};
use crate::CadApp;
@@ -51,17 +52,15 @@ pub fn tick(app: &mut CadApp, ctx: &egui::Context) {
let at_start = checks_at_start(app);
let rt = &mut app.updates_rt;
if std::mem::take(&mut rt.check_requested) {
rt.updater.check_now(ctx);
rt.updater.check_now();
} else if at_start {
rt.updater.check_at_start(ctx);
rt.updater.check_at_start();
}
rt.updater.tick(ctx);
let outcome = match rt.updater.status() {
Status::UpToDate => Some(crate::tl!("CADCraft is up to date.")),
Status::Failed(_) => Some(crate::tl!("Could not check for updates.")),
Status::Idle | Status::Checking | Status::Installing | Status::Ready | Status::Managed | Status::Updated(_) | Status::InstallFailed(_) => {
None
}
_ => None,
};
if let Some(message) = outcome
&& !std::mem::replace(&mut rt.result_echoed, true)
@@ -77,29 +76,50 @@ fn result_window_shows(status: &Status, prompt_open: bool) -> bool {
!prompt_open && !matches!(status, Status::Idle)
}
/// Draw the prompt while there is one and act on its answer.
/// One pass of the update flow, before the dialog host runs ([`CadApp::run_framework_dialogs`]): answers the
/// check result dialog closed in the last pass, drives the startup prompt, and keeps the result dialog open and
/// current while the updater has something to report.
pub fn show(app: &mut CadApp, ctx: &egui::Context) {
// The close for a ready update waits until no drawing holds unsaved changes.
let clean = !app.session.docs.iter().any(|d| d.is_dirty());
let rt = &mut app.updates_rt;
if result_window_shows(rt.updater.status(), rt.updater.prompt_open()) {
match CheckResultDialog::new(&crate::UPDATE_APP, VERSION).show(ctx, rt.updater.status()) {
CheckResultResponse::Close => rt.updater.dismiss_status(),
CheckResultResponse::CheckAgain => {
rt.result_echoed = false;
rt.check_requested = true;
}
// The next `show_if` asks the window to close once nothing is unsaved.
CheckResultResponse::RestartToUpdate => rt.updater.restart_to_update(),
CheckResultResponse::None => {}
// Answered before the dialog is kept open below, so a dismissed result does not open again at once.
match app.framework_dialogs.take::<UpdateCheckDialog>() {
Some(DialogResult::Ok(CheckChoice::CheckNow | CheckChoice::CheckAgain)) => {
app.updates_rt.result_echoed = false;
app.updates_rt.check_requested = true;
}
// The next `run` asks the window to close once nothing is unsaved.
Some(DialogResult::Ok(CheckChoice::RestartToUpdate)) => app.updates_rt.updater.restart_to_update(),
Some(DialogResult::Ok(CheckChoice::Update)) => {
app.updates_rt.updater.request_install(clean);
}
Some(DialogResult::Ok(CheckChoice::Download)) => ctx.open_url(egui::OpenUrl::new_tab(crate::UPDATE_APP.releases_url())),
// Close, Esc and the close box dismiss the outcome it showed.
Some(_) => app.updates_rt.updater.dismiss_status(),
None => {}
}
match app.updates_rt.updater.show_if(ctx, clean) {
match app.updates_rt.updater.run(&mut app.framework_dialogs, clean) {
Action::OpenUrl(url) => ctx.open_url(egui::OpenUrl::new_tab(url)),
// The guarded close path asks about unsaved changes. The install helper starts when the
// app exits and drops the updater.
Action::Close => ctx.send_viewport_cmd(egui::ViewportCommand::Close),
Action::None => {}
_ => {}
}
let rt = &app.updates_rt;
let shows = result_window_shows(rt.updater.status(), rt.updater.prompt_open());
if shows && !app.framework_dialogs.is_open::<UpdateCheckDialog>() {
app.framework_dialogs.open(UpdateCheckDialog::new(VERSION));
}
let updater = &app.updates_rt.updater;
let (status, installing, message) = (updater.status().clone(), updater.is_installing(), updater.status_message());
if let Some(dialog) = app.framework_dialogs.get_mut::<UpdateCheckDialog>() {
dialog.set_status(status);
dialog.set_installing(installing);
dialog.set_message(message);
}
// The prompt taking over dismisses the outcome the dialog showed.
if !shows && app.framework_dialogs.is_open::<UpdateCheckDialog>() {
app.framework_dialogs.cancel::<UpdateCheckDialog>(ctx);
}
}
+1
View File
@@ -323,6 +323,7 @@ mod tests {
app.ui.in_window_menu = true;
app.start("ui.sample");
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
frame(&mut app, &ctx, Vec::new());
frame(&mut app, &ctx, Vec::new());
(app, ctx)
+2 -2
View File
@@ -183,7 +183,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
ui.radio_value(&mut app.wblock.source, Source::Block, crate::tl!("Block"));
ui.add_space(8.0);
ui.add_enabled_ui(app.wblock.source == Source::Block, |ui| {
craft_ui::ComboBox::from_id_salt("wblock_block_name")
egui::ComboBox::from_id_salt("wblock_block_name")
.selected_text(if app.wblock.block_name.is_empty() { crate::tl!("(select)") } else { app.wblock.block_name.as_str() })
.width(220.0)
.show_ui(ui, |ui| {
@@ -277,7 +277,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
});
});
if ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
if crate::framework::escape_pressed(ctx) {
cancel = true;
}
+1 -1
View File
@@ -13,7 +13,7 @@ use serde_json::json;
/// A 1400×900 kittest harness whose frame runs `logic` and then `ui` on the supplied app.
fn harness(app: CadApp) -> Harness<'static, CadApp> {
Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_ui_state(
Harness::builder().with_context_setup(cadcraft_ui_egui::framework::install_headless).with_size(egui::vec2(1400.0, 900.0)).build_ui_state(
|ui, app: &mut CadApp| {
app.logic(ui.ctx());
app.ui(ui);
+1
View File
@@ -49,6 +49,7 @@ fn a_failed_autosave_is_shown_until_a_write_works() {
let mut app = CadApp::new(Session::new(), Services::default());
app.enable_autosave(&dir);
let ctx = egui::Context::default();
cadcraft_ui_egui::framework::install_headless(&ctx);
app.autosave_tick(&ctx);
assert!(app.autosave_notice.is_none(), "nothing failed yet");
+11 -7
View File
@@ -49,6 +49,7 @@ fn bedit_without_a_selected_reference_opens_the_dialog() {
app.bedit.name = "door".into();
let ctx = egui::Context::default();
cadcraft_ui_egui::framework::install_headless(&ctx);
app.logic(&ctx);
painted(&mut app, &ctx);
let text = painted(&mut app, &ctx);
@@ -77,6 +78,7 @@ fn a_new_name_starts_a_new_block_and_a_bad_one_keeps_the_dialog() {
app.bedit.name = " Skylight ".into();
let ctx = egui::Context::default();
cadcraft_ui_egui::framework::install_headless(&ctx);
app.logic(&ctx);
painted(&mut app, &ctx);
assert!(painted(&mut app, &ctx).contains("New block"));
@@ -144,6 +146,7 @@ fn opening_a_drawing_with_authoring_elements_offers_the_block_editor() {
app.finish_opening();
assert_eq!(app.ui.dialog.as_deref(), Some("authoring"));
let ctx = egui::Context::default();
cadcraft_ui_egui::framework::install_headless(&ctx);
app.logic(&ctx);
painted(&mut app, &ctx);
let text = painted(&mut app, &ctx);
@@ -213,13 +216,14 @@ fn in_the_block_editor_the_dialog_switches_blocks_asking_to_save_first() {
app.bedit.name = "door".into();
assert!(!bedit::confirm(&mut app), "asks first");
assert!(app.bedit.ask_save);
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut CadApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
let mut h =
Harness::builder().with_context_setup(cadcraft_ui_egui::framework::install_headless).with_size(egui::vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut CadApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(2);
assert!(h.query_by_label_contains("Save changes to block \"Window\"").is_some());
h.get_by_label("Cancel").click();
+18 -14
View File
@@ -25,13 +25,17 @@ fn drawing() -> CadApp {
}
fn harness(app: CadApp) -> Harness<'static, CadApp> {
let mut h = Harness::builder().with_size(vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|ui, app: &mut CadApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
let mut h = Harness::builder()
.with_context_setup(cadcraft_ui_egui::framework::install_headless)
.with_size(vec2(1400.0, 900.0))
.with_step_dt(1.0 / 60.0)
.build_ui_state(
|ui, app: &mut CadApp| {
app.logic(&ui.ctx().clone());
app.ui(ui);
},
app,
);
h.run_steps(4);
h
}
@@ -40,7 +44,7 @@ fn harness(app: CadApp) -> Harness<'static, CadApp> {
fn blockspalette_opens_the_palette_and_lists_the_blocks() {
let mut app = drawing();
assert!(app.cmdline("BLOCKSPALETTE").is_none());
assert!(app.ui.docking.layout.contains(&Panel::Blocks));
assert!(app.ui.docking.layout().contains(&Panel::Blocks));
app.ui.in_window_menu = false;
let h = harness(app);
h.get_by_label("Door");
@@ -62,7 +66,7 @@ fn json_blockspalette_lists_and_never_opens_the_palette() {
// The palette itself asks for no counts, which would read every object.
let r = app.run("blockspalette", json!({ "references": false })).unwrap();
assert_eq!(r["blocks"][1], json!({ "name": "Door", "description": "Hinged door" }));
assert!(!app.ui.docking.layout.contains(&Panel::Blocks));
assert!(!app.ui.docking.layout().contains(&Panel::Blocks));
}
/// A click on a tile starts INSERT and answers the prompts the options settle.
@@ -249,11 +253,11 @@ fn insert_started_by_the_palette_flow_waits_for_the_point() {
fn the_palette_closes_and_reopens_where_it_was() {
let mut app = drawing();
app.cmdline("BLOCKSPALETTE");
assert!(app.ui.docking.layout.contains(&Panel::Blocks));
assert!(app.ui.docking.layout().contains(&Panel::Blocks));
app.run("ui.dock", json!({ "operation": "close", "panel": "blocks" })).unwrap();
assert!(!app.ui.docking.layout.contains(&Panel::Blocks));
assert!(!app.ui.docking.layout().contains(&Panel::Blocks));
app.cmdline("BLOCKSPALETTE");
assert!(app.ui.docking.layout.contains(&Panel::Blocks));
assert!(app.ui.docking.layout().contains(&Panel::Blocks));
}
/// How many times a library file was parsed.
@@ -376,12 +380,12 @@ fn a_library_is_added_listed_placed_and_removed() {
fn the_toolbar_icon_and_the_window_menu_open_the_palette_not_a_dialog() {
let mut app = drawing();
app.run("ui.dialog.blocks", serde_json::Value::Null).unwrap();
assert!(app.ui.docking.layout.contains(&Panel::Blocks));
assert!(app.ui.docking.layout().contains(&Panel::Blocks));
assert!(app.ui.dialog.is_none(), "the old Blocks window is gone");
// Like the other ui.dialog.* ids, it opens whatever the parameters are.
let mut app = drawing();
app.run("ui.dialog.blocks", json!({})).unwrap();
assert!(app.ui.docking.layout.contains(&Panel::Blocks));
assert!(app.ui.docking.layout().contains(&Panel::Blocks));
}
/// An exploded block leaves no reference, and it repeats all the same.
+8 -1
View File
@@ -17,6 +17,13 @@ struct Canvas {
}
impl Canvas {
/// A context with the UI runtime installed, as the app's window has.
fn context() -> Context {
let ctx = Context::default();
cadcraft_ui_egui::framework::install_headless(&ctx);
ctx
}
fn new(paper: bool) -> Self {
let previous_theme = theme::active();
let mut session = Session::new();
@@ -33,7 +40,7 @@ impl Canvas {
app.ui.show_command_line = false;
app.ui.show_viewcube = false;
app.run("options", json!({"theme": "dark", "systemCursor": false, "PICKBOX": 4, "SELECTIONPREVIEW": 1})).unwrap();
let mut canvas = Self { app, ctx: Context::default(), previous_theme };
let mut canvas = Self { app, ctx: Self::context(), previous_theme };
canvas.paint(pos2(640.0, 400.0));
canvas
}

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