Compare commits

...
Author SHA1 Message Date
Dimitrios Vidalis 6681531546 refactor(render,io): move the dimension block generator from the DXF writer to render (#2421) (#3777)
`dim_block_entities` makes the contents of a dimension's anonymous `*D`
block from the dimension's drawn geometry. It lived in the DXF writer
(`crates/io/src/dxf_write/blocks.rs`) and only the writer could call it.
It moves to `crates/render/src/dim_block.rs`, beside the geometry it reads,
and is exported as `cadcraft_render::dim_block_entities`. The writer calls
it there.

The body is unchanged: the three `cadcraft_render::` paths in it lose their
prefix and `pub(super)` becomes `pub`. No behaviour changes.
2026-12-03 15:36:36 +01:00
97fed2970c Annotative objects keep a position per scale; ANNORESET synchronizes them (stacked on #1370) (#1373)
* DXF: a block record keeps its annotative flag and uniform scaling

A BLOCK_RECORD's AcadAnnotative xdata (references to the block are
annotative) was dropped on reading, AcadAnnotative being among the
applications CADCraft writes itself, and never written: a saved drawing's
annotative blocks came back plain, and AutoCAD then scaled their references
by units instead of the annotation scale (a metre block showed Unit factor
1000 and Scale 0.005). Group 281 (scale uniformly) was dropped too. Both are
now read into the block (`Block::annotative`, `Block::scale_uniformly`) and
written back.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* DXF: a block reference keeps its annotation scale contexts, following the reference

A reference to an annotative block holds its scale at each annotation scale in
its extension dictionary (AcDbContextDataManager, ACDB_ANNOTATIONSCALES).
CADCraft dropped it with the other annotation contexts it means to write from
its model, but it models none for references: with the block's annotative
flag kept, AutoCAD then scaled the reference once more by the current
annotation scale (5 became 25). A reference's contexts are now kept, and
refreshed on writing: each moves, turns and scales by what the reference did
since the file was read (its default context was the reference then), so a
reference left alone keeps them as read. The scales they name are found by
name (SCALE group 300), as the scale list is written again from the model.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Block literals in tests take scale_uniformly; a test helper's lifetime is elided

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* DXF: a block reference's attributes keep their annotation scale contexts

The attributes of an annotative reference hold their own contexts (insertion
and alignment points and rotation at each annotation scale, under the ATTRIB's
extension dictionary), dropped like the reference's were. CADCraft writes
attributes with new handles, so their extension dictionaries are now kept by
attribute, as its reference's handle and tag, and put back on the attribute
written with that reference and tag. On writing each context keeps its own
place in the block at its scale, moves by what the attribute did in the block
since (its default context then, the attribute now), and is placed by the
reference's context for that scale as it is now: a reference left alone keeps
them as read; one moved, turned or scaled carries them exactly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* DWG: block reference annotation contexts keep their rotation, insertion and scales

AutoCAD's DXF has a block reference context's rotation (50, degrees),
insertion point and scales straight after its scale (340). acadrust 0.6.4
reads them after an AcDbBlkRefObjectContextData marker, with the rotation in
radians, and without the marker read zeros: a drawing saved as DWG had every
annotative reference at scale 0 at its other annotation scales, where
AutoCAD then drew nothing. The DWG bridge now gives acadrust the contexts its
way (marker, radians) and turns its DXF back into AutoCAD's (no marker,
degrees).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* DXF: kept reference contexts follow the drawing's and the reference's scales

A kept block reference or attribute context whose SCALE is no longer in the
drawing's list is not written (its dictionary entry goes with it), so no
context points at a null scale. A reference CADCraft's model keeps annotative
has a context for exactly the scales it supports: contexts of scales it
dropped go, and one per new scale is made from the default context, scaled
by the ratio of the scales about the reference's insertion point. One
context stays the default.

Attributes are identified by reference, tag and their place among the
reference's attributes with that tag, so two attributes with one tag keep
their own extension dictionaries and contexts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* DXF: new reference contexts come from one whose scale is still written

When the default context's scale had been deleted from the drawing's list,
a reference CADCraft keeps annotative got no new contexts for its added
scales; the template is now its default context, else its first, among
those whose SCALE is written.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* DXF: kept reference contexts follow the reference as read; one default rule

A kept context is brought up to date by what its block reference did since
the file was read. That baseline was the default context, which needn't be
where the reference was (an unchanged save then moved every context); the
reference and its attributes as read are now kept (`Foreign::placements`)
and used, the default context only for data without them.

A context's own offset from the reference now scales and mirrors with it
(back into the reference's frame then, scaled, turned to its frame now), not
only turns.

The default context is the one whose first 290 group is 1 everywhere (an
attribute context has a later 290 of its own).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* DXF: new reference contexts take handles above every handle in use

Upstream now believes handles above 2^48 (AutoCAD writes them), so new
annotation contexts can no longer take stand-in handles from 2^48 up: they
start above the written handles, $HANDSEED, the kept objects and their targets.

Test: a drawing whose reference sits at 2^48 + 1 gains a scale and every
written handle stays unique (red with the old 2^48 base).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* DXF: an attribute as read is found by its tag and place, and keeps its rotation

A kept attribute placement was looked up by its index among the reference's
attributes now, which differs once they are reordered or replaced (ATTSYNC).
It is now found by tag and place among that tag, like the attribute's contexts.
The rotation change is measured from the attribute as read too, not from its
default context, so an unchanged save no longer turns every context when the
ATTRIB (at the current scale) and the default context differ.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* DXF: the kept-context code in read and finish moves into helpers

main now denies cognitive_complexity over 30 and too_many_arguments over 7.
This PR's additions took read to 32 and finish to 31, and retained_objects
to 8 arguments: the block-reference and attribute bookkeeping now lives in
insert_handles, of_insert, keep_attrib_dictionaries, keep_placements,
written_attribs and refreshed_contexts, and retained_objects takes the root
and its entries as one pair.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* DXF/DWG: annotative text, MText and dimensions keep their annotation scales on save

AutoCAD keeps an annotative object's size at each annotation scale it
supports in scale contexts (extension dictionary AcDbContextDataManager,
ACDB_ANNOTATIONSCALES, one *OBJECTCONTEXTDATA_CLASS per scale), with the
object's own groups at its default scale. CADCraft dropped AutoCAD's contexts
on read, so those objects opened as plain text at the default scale's size
and lost their scales on save; its own annotative objects went out with only
CADCraft's private record, so AutoCAD showed them at one size at every scale.

Text, MText and dimensions in model space and layouts are now written at
their default scale (the current one when supported) with AcadAnnotative
xdata and a context per scale: text insertion and alignment points, MText
width and columns, a dimension's text position and a *D block with its
geometry at that scale (sharing the DIMASSOC's extension dictionary when
there is one). Scales missing from the list are added. Reading takes the
scales from the contexts and the sizes back to paper size. Files before the
2007 format keep CADCraft's record as before. The DWG bridge gives acadrust
text contexts its way (marker, radians) and dimension contexts' blocks as
BLOCK_RECORD handles, and turns them back.

Checked in AutoCAD: it opens the output, keeps both contexts of each
object, and draws the dimension at 0.18 / 9.0 text height at 1:1 / 1:50.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* DXF test: a justified text's start point is recomputed on save (since #1062)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* DXF: only annotative dimensions get a *D block per scale

Annotative text and MText went through the dimension block planning too and
left one empty anonymous *D block per scale in every saved file. The hostile
contexts test now saves, opens the file again and checks the scales and that
every context names a written SCALE.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* DXF/DWG: annotative multileaders keep their annotation scales on save

An annotative multileader's scale context (ACDB_MLEADEROBJECTCONTEXTDATA_CLASS)
holds the multileader's whole CONTEXT_DATA body at that scale: overall scale
(40), text height, arrowhead size, landing gap, content position and the
leaders. CADCraft dropped AutoCAD's on read and wrote none, so annotative
multileaders came back plain at the default scale's size, and AutoCAD showed
CADCraft's at one size at every scale.

Multileaders now go through the annotation scale contexts like text, MText
and dimensions: written at the default scale with AcadAnnotative xdata and a
context per scale (the entity writer's CONTEXT_DATA at that scale, with its
overall scale and landing gap set), read back at paper size. The DWG bridge
gives acadrust the CONTEXT_DATA{ group it reads the context after, and takes
acadrust's braces and marker out again.

Checked in AutoCAD: its own annotative multileader reads back at 1:2 and
1:10 at paper size, and the saved file reopens with text 0.18 / 0.9 as
before; one made in CADCraft opens with text 2.5 / 25 at 1:1 / 1:10, the text
moved with the scale.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* DXF: the current annotation scale is AutoCAD's CANNOSCALE variable

AutoCAD keeps the current annotation scale in the named object dictionary's
AcDbVariableDictionary, as a DICTIONARYVAR CANNOSCALE naming the scale.
CADCraft read only its own record, so AutoCAD's drawings opened at 1:1
whatever their scale (annotative objects then showed at their first scale),
and the variable was written back as read, so AutoCAD reopened a drawing at
its old scale after CADCraft changed it.

The variable is read when the scale is in the list (after CADCraft's record:
AutoCAD keeps that record as it was, so the variable is the newer one), and
the kept variable is written with the drawing's current scale. Annotative
objects are written at that scale.

Checked in CADCraft and AutoCAD: an AutoCAD drawing at 1:2 opens at 1:2;
switched to 1:10 and saved as DXF and DWG, AutoCAD opens both at 1:10.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* DXF test: an annotative multileader has no *D block

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* DXF: AutoCAD's CANNOSCALE names the scale the contexts are written at

A CANNOSCALE naming none of the drawing's scales wrote that name to the
variable dictionary while the default contexts were written at 1:1; the
variable now names the resolved scale too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* DWG: a multileader context's body closes (301 }) before the next record

As acadrust writes it; its reader stops at the next record either way.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Annotative objects keep a position per scale; ANNORESET synchronizes them

An annotative object that supports several scales can now sit somewhere
else at one of them, as in AutoCAD: its position grip moves it at the
current annotation scale only, MOVE/ROTATE/SCALE/MIRROR/paste/CHSPACE move
every scale, and ANNORESET puts every scale back where the current one is
(it was a no-op). The offset is kept per scale name (Common::anno_moves)
and applied where an object is drawn at a scale (anno_placed), so drawing,
extents, explode and grips all see it. Grips now show where the object is
drawn at the current scale; a shape grip's edit is taken back to paper size.

What moves per kind: text, MText and block references as a whole; a
multileader's landing and content (arrowheads stay); a dimension's text.

DXF/DWG: each scale context is written at the object's position at that
scale, and a context placing the object elsewhere reads back as its offset.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* DXF: an annotative multileader has annotation scale enabled (293)

The MULTILEADER entity's 293 after its CONTEXT_DATA block is the DXF
reference's "Enable Annotation Scale". CADCraft wrote 0, so AutoCAD kept
the multileader's per-scale contexts (and showed each scale's position)
but its ANNORESET passed the multileader over. With 293 = 1, as AutoCAD
writes for its own annotative multileaders, ANNORESET at either scale
moves the other context to the current scale's position.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Annotative grips and ANNORESET in a viewport use the viewport's scale

In MSPACE the renderer draws model space at the active viewport's scale,
while grips, grip stretches, the hot-grip preview, grip dimensions and
ANNORESET looked up the object at CANNOSCALE: with the two different, grips
sat on another scale's representation and a position grip moved the wrong
scale. They now take the viewport's scale (`DocState::anno_view`,
`Drawing::anno_draw_in`); CANNOSCALE still applies in model space and on
paper outside a viewport.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Annotative scales: import Vec2 after upstream's explicit-import cleanup

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Docs: leave the parity docs to the maintainers (AGENTS.md: PRs don't edit them)

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* Docs: leave the parity docs to the maintainers (AGENTS.md: PRs don't edit them)

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* Docs: leave the parity docs to the maintainers (AGENTS.md: PRs don't edit them)

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* Annotative text contexts test: Dimension gains insertion_point on main

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* io: dxf_anno uses craft_dxf, as main's DXF crate now is

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* io: dxf_anno uses craft_dxf, as main's DXF crate now is

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* io: dxf_anno uses craft_dxf, as main's DXF crate now is

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Tests: the DWG annotation scale round trip waits for craft-libs#2005

Without the bridge's annotation context conversion, a text context read back
from a DWG has its fields from the wrong groups (at the origin), which per-scale
positions read as a move. Ignored until the pinned craft-dwg has the conversion.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fmt: dxf_anno's craft_dxf import in order

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fmt: dxf_anno's craft_dxf import in order

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fmt: dxf_anno's craft_dxf import in order

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* io: dxf_anno reads main's borrowed DXF sections (SectionRef)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Annotative positions: main's text editor box and extents take the placed object (AnnoDraw::Scaled carries its offset)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* DXF writer: annotation scale planning in two helpers (main's tags_kept_for passed the complexity limit)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Select: a blank MText frame is where its annotation scale places it (main's AnnoDraw use, with the offset)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* DXF: a block reference moved in elevation takes its contexts along, at their own heights

block_contexts compared the reference with the one read in X and Y only, so a
reference moved only in Z kept its contexts at their old heights; and any
other change set every context's group 30 to the reference's Z, losing a
context's own height. Z is part of the change check now, and each context
keeps its offset from the reference as read, scaled with the reference's Z
scale as X and Y follow theirs.

FredApps on #1244.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Tests: the annotative block context tests join the io test binary (AGENTS.md rule 30)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Tests: the annotative text context tests join the io test binary (AGENTS.md rule 30)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Tests: the annotative position tests join the engine's test binary (AGENTS.md rule 30)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* DWG: block reference contexts and the block's annotative flag stay DXF-only until the bridge converts them

The DWG bridge doesn't carry annotation scale contexts into a DWG yet
(storytold/craft-libs#2005): the DWG reader read them back as zeros, a
reference at scale 0 at its other scales. A save through the bridge now
leaves the kept block reference and attribute contexts out, as before they
were kept, and the block's AcadAnnotative flag too (without its references'
contexts AutoCAD would scale them by the annotation scale once more). DXF
keeps both.

The DWG round-trip test that waited for craft-libs#2005 (ignored,
a_reference_s_contexts_survive_dwg) is replaced by one that runs: a DWG save
leaves the contexts out and the reference reads back at its own scale. The
round trip of the contexts through DWG follows once the bridge converts
them.

FredApps on #1362 (rule 31).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* DWG: annotative text, MText and dimensions keep their scales in CADCraft's record until the bridge converts contexts

A save through the DWG bridge writes no annotation scale contexts now: the
bridge doesn't convert them yet (storytold/craft-libs#2005), so CADCraft's own
record carries the scales, as for an older format. DXF from 2007 on writes the
contexts as before.

The DWG test that waited for craft-libs#2005 (ignored) now runs: the scales,
paper height and rotation come back through DWG from the record, and the DWG
holds no contexts. The contexts' own round trip through DWG follows with the
bridge.

FredApps on #1362 (rule 31).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Tests: the multileader's DWG round trip runs, through CADCraft's record

The multileader DWG test that waited for craft-libs#2005 (ignored) now runs:
its scales and paper text height come back through DWG from CADCraft's own
record, and the DWG holds no multileader contexts. The contexts' round trip
through DWG follows with the bridge.

FredApps on #1362 (rule 31).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* DWG: per-scale positions travel in CADCraft's record; main's annotation_scales round trip runs again

A DWG save writes no annotation scale contexts while the bridge can't convert
them (storytold/craft-libs#2005), so an object moved at one scale alone would
lose that move through DWG. CADCraft's annotative record now carries each
object's moves next to its scales (only for scales it keeps, finite, at most
MAX_SCALES), as it does for formats before 2007.

The roundtrip/dwg annotation_scales test this PR had marked ignored (main's
own test) runs again, unchanged, and passes; the multileader moved-at-one-scale
DWG test runs too, through the record.

FredApps on #1362 (rule 31).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* DXF writer: the DWG bridge's context choice in contexts_for (finish passed the complexity limit)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Keep annotative I/O fixture at normal text orientation

---------

Co-authored-by: Cody Vogt <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: FredApps <[email protected]>
Co-authored-by: FredApps <[email protected]>
2026-12-03 15:30:30 +01:00
44fa197bcc Linux: native Wayland by default, with in-app window buttons on GNOME (#1853)
* Linux: native Wayland by default; CADCRAFT_X11=1 for XWayland

On a Wayland desktop CADCraft forced winit's X11 backend (XWayland)
whenever DISPLAY was set. The deb and rpm only recommend the X11
libraries, and without libxkbcommon-x11 winit panicked at startup:
"Library libxkbcommon-x11.so could not be loaded".

Run natively on Wayland instead: sharp at fractional scales, with
working input methods. File drops from the file manager work there too,
through storytold/winit's W15 patch. CADCRAFT_X11=1 opts into XWayland
as a fallback, and only when the X11 libraries load; otherwise it logs
what is missing and stays on Wayland. It is read with the other
variables in env.rs and replaces CADCRAFT_WAYLAND.
The deb and rpm recommend libxkbcommon-x11 (and rpm libX11-xcb) too.

Ported from WordCraft (storytold/wordcraft#3359).

* GNOME Wayland: draw the window buttons and resize edges in the app

GNOME's compositor offers no zxdg_decoration_manager_v1, so with native
Wayland it draws no frame for CADCraft. Where the protocol is missing,
the window opens without winit's frame and the app draws a title row as
GNOME's header bar: the drawing's name centred, and minimize, maximize
and close in the order GNOME's button-layout names (read once through
the XDG Desktop Portal). Thin zones along the window's edges resize it.
KDE, Sway, Hyprland, COSMIC and X11 keep the desktop's frame.

Options > Display > Use system title bar (OPTIONS key systemTitleBar)
brings back winit's frame at once. It is kept in workspace.json, which
is now read before the window opens. CADCRAFT_TITLEBAR=app or =system
overrides the detection. The new strings are translated in all 15
catalogs.

Ported from WordCraft (storytold/wordcraft#3361).

* Linux: decide the window frame from the backend winit runs on

On an X11-only session winit picks X11 without CADCRAFT_X11, so x11
stayed false and CADCRAFT_TITLEBAR=app drew the app's window buttons on
X11, whose window manager draws the frame. runs_on_x11 follows winit's
own choice (WAYLAND_DISPLAY or WAYLAND_SOCKET set and not empty).

* Linux: leave WAYLAND_SOCKET to winit; empty DISPLAY; TITLEBAR=app wins

Three CodeRabbit findings on #1853:

- The decorations probe connected with Connection::connect_to_env, which,
  given WAYLAND_SOCKET, takes that descriptor, removes the variable and
  closes it when the probe's connection drops, so winit had no Wayland
  connection left. The probe now connects only to WAYLAND_DISPLAY's
  socket (display_socket, found as wayland-client finds it); with only
  WAYLAND_SOCKET it doesn't probe and the desktop keeps the frame.
- An empty DISPLAY counted as an X display, so CADCRAFT_X11=1 forced X11
  with nothing to connect to. DISPLAY is now read as winit reads the
  Wayland variables: set and not empty.
- CADCRAFT_TITLEBAR=app chose the app's buttons, but a saved Use system
  title bar still kept winit's frame, at startup and in
  CadApp::draws_window_frame. Both now decide with app_draws_frame, which
  the override wins (CadApp::frame_forced), and Options doesn't offer the
  setting while it's overridden.

Tests: display_socket and forces_app (decorations), an empty DISPLAY
(main), and titlebar_app_overrides_the_saved_system_title_bar.

* i18n: window button and title bar rows for bs, ka, pl and vi

These catalogs arrived on main after this branch added "Minimize",
"Maximize", "Use system title bar" and its tooltip to the others, so
every catalog now has all four rows.

* Drop the parity-doc edits; the rows go in the PR description

AGENTS.md: PRs don't edit ROADMAP.md or docs/ui-parity.md.

---------

Co-authored-by: bmh129 <[email protected]>
Co-authored-by: FredApps <[email protected]>
2026-12-03 15:07:20 +01:00
63 changed files with 1295 additions and 164 deletions
Generated
+2
View File
@@ -781,6 +781,8 @@ dependencies = [
"winit",
"winresource",
"winsafe",
"x11-dl",
"xkbcommon-dl",
"zbus",
]
+14
View File
@@ -396,6 +396,20 @@ RISC-V (riscv64) packages are `cadcraft-<ver>-linux-riscv64.deb`,
`cadcraft-<ver>-linux-riscv64.rpm`, and `cadcraft-<ver>-linux-riscv64.tar.gz`. They are
cross-compiled and need glibc 2.39 or newer (Ubuntu 24.04+, Debian 13+).
**Wayland:** on a Wayland desktop the app uses the native Wayland backend, which is sharp at
fractional scales, works with input methods and accepts files dropped from the file manager. If
the native backend misbehaves on your desktop, run the app through XWayland instead with
`CADCRAFT_X11=1` (this needs the X11 libraries: libX11, libX11-xcb, libXcursor, libXi and
libxkbcommon-x11):
```sh
CADCRAFT_X11=1 cadcraft
```
GNOME on Wayland draws no window frames, so there CADCraft's title bar carries the window
buttons, in GNOME's order. **Options ▸ Display ▸ Use system title bar** shows a basic frame
instead. `CADCRAFT_TITLEBAR=app` or `CADCRAFT_TITLEBAR=system` overrides the detection.
### FreeBSD
| Build | File |
+6
View File
@@ -40,6 +40,12 @@ winresource = "0.1"
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
winit = { version = "0.30", default-features = false, features = ["x11"] }
# Checks that the X11 libraries are installed before choosing XWayland (see main.rs). Already in
# the build through winit, at this version.
x11-dl = "2.21"
# Checks for libxkbcommon-x11 too, which winit's X11 backend needs for the keyboard and panics
# without. Already in the build through winit, at this version and with this feature.
xkbcommon-dl = { version = "0.4.2", features = ["x11"] }
# View ▸ Theme ▸ System: the desktop's light/dark choice from the XDG desktop portal
# (desktop_theme.rs). Already in Cargo.lock through accesskit; pinned to that version so nothing
# is built twice.
+8 -8
View File
@@ -12,7 +12,7 @@ const CONFIG_DIR: &str = "CADCRAFT_CONFIG_DIR";
const LOCALE: &str = "CADCRAFT_LOCALE";
const VSYNC: &str = "CADCRAFT_VSYNC";
const STENCIL: &str = "CADCRAFT_STENCIL";
const WAYLAND: &str = "CADCRAFT_WAYLAND";
const X11: &str = "CADCRAFT_X11";
const NO_NATIVE_MENU: &str = "CADCRAFT_NO_NATIVE_MENU";
const SYSTEM_CURSOR: &str = "CADCRAFT_SYSTEM_CURSOR";
const FONTALT: &str = "CADCRAFT_FONTALT";
@@ -27,7 +27,7 @@ pub(crate) const VARS: &[(&str, &str)] = &[
STENCIL,
"0 opens the window without a stencil buffer, 1 keeps it on every attempt; unset, a start that can't draw with it drops it (clipped layout viewports then draw unclipped)",
),
(WAYLAND, "1 keeps the native Wayland backend instead of XWayland; 0 or unset is off"),
(X11, "1 runs through XWayland instead of the native Wayland backend, as a fallback, when the X11 libraries load; 0 or unset is off"),
(NO_NATIVE_MENU, "macOS: 1 keeps the menus inside the window; 0 or unset is off"),
(SYSTEM_CURSOR, "1 uses the system cursor instead of the drawn crosshair; 0 or unset is off"),
(FONTALT, "the font that replaces a missing one"),
@@ -54,9 +54,9 @@ pub(crate) struct Env {
/// `renderer`). Some old drivers (Mesa on Intel HD 4000, old Intel drivers on Windows) accept a
/// stencil pass and then present a black window.
pub(crate) stencil: Switch,
/// Keep the native Wayland backend instead of XWayland.
/// Run through XWayland instead of the native Wayland backend.
#[cfg_attr(not(all(unix, not(target_os = "macos"))), allow(dead_code))]
pub(crate) wayland: Switch,
pub(crate) x11: Switch,
/// macOS: keep the menus inside the window.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
pub(crate) no_native_menu: Switch,
@@ -121,7 +121,7 @@ impl Env {
locale: text(LOCALE),
vsync: switch(VSYNC),
stencil: switch(STENCIL),
wayland: switch(WAYLAND),
x11: switch(X11),
no_native_menu: switch(NO_NATIVE_MENU),
system_cursor: switch(SYSTEM_CURSOR),
font_alt: text(FONTALT),
@@ -223,7 +223,7 @@ mod tests {
(LOCALE, "cs-CZ"),
(VSYNC, " On "),
(STENCIL, "No"),
(WAYLAND, "0"),
(X11, "0"),
(NO_NATIVE_MENU, "yes"),
(SYSTEM_CURSOR, "maybe"),
(FONTALT, "Noto Sans"),
@@ -238,7 +238,7 @@ mod tests {
locale: Some("cs-CZ".into()),
vsync: Switch::On,
stencil: Switch::Off,
wayland: Switch::Off,
x11: Switch::Off,
no_native_menu: Switch::On,
system_cursor: Switch::Default,
font_alt: Some("Noto Sans".into()),
@@ -249,7 +249,7 @@ mod tests {
let read = Env::from_vars(env(&blank));
assert_eq!(read.config_dir, None, "an empty variable means no directory, not the working directory");
assert_eq!((read.locale, read.font_alt, read.font_fallback), (None, None, None));
assert_eq!([read.vsync, read.stencil, read.wayland, read.no_native_menu, read.system_cursor], [Switch::Default; 5]);
assert_eq!([read.vsync, read.stencil, read.x11, read.no_native_menu, read.system_cursor], [Switch::Default; 5]);
}
#[test]
+81 -7
View File
@@ -498,6 +498,38 @@ fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
Some(launch.passthrough_args)
}
/// Whether the libraries winit's X11 backend opens at startup are installed (libX11, libXcursor,
/// libX11-xcb and libXi; libX11-xcb brings in libxcb; and libxkbcommon-x11, for the keyboard).
/// The deb and rpm only recommend them, and a forced X11 backend without them fails to start
/// (winit panics when libxkbcommon-x11 is missing).
#[cfg(all(unix, not(target_os = "macos")))]
fn x11_libraries_load() -> bool {
use x11_dl::{xcursor::Xcursor, xinput2::XInput2, xlib::Xlib, xlib_xcb::Xlib_xcb};
let missing = [Xlib::open().err(), Xcursor::open().err(), Xlib_xcb::open().err(), XInput2::open().err()];
let mut missing: Vec<String> = missing.into_iter().flatten().map(|e| e.to_string()).collect();
if xkbcommon_dl::x11::xkbcommon_x11_option().is_none() {
missing.push("libxkbcommon-x11.so.0 could not be loaded".into());
}
if !missing.is_empty() {
log::warn!("CADCRAFT_X11: X11 libraries missing, using the native Wayland backend: {}", missing.join("; "));
}
missing.is_empty()
}
/// Whether to force winit's X11 backend (XWayland on a Wayland desktop): an X display is there,
/// `CADCRAFT_X11` is on, and the X11 libraries load. The libraries are probed last, only when X11
/// would otherwise be chosen.
#[cfg(all(unix, not(target_os = "macos")))]
fn use_x11(display: bool, setting: Switch, x11_libraries_load: impl FnOnce() -> bool) -> bool {
display && setting == Switch::On && x11_libraries_load()
}
/// Whether a display variable names something: set and not empty, as winit reads them.
#[cfg(all(unix, not(target_os = "macos")))]
fn set(v: Option<&std::ffi::OsStr>) -> bool {
v.is_some_and(|v| !v.is_empty())
}
/// Parse CLI options (`--control`, `--sample`, files, `--version`), install logging and I/O hooks, build the services and app, and run eframe.
fn main() -> eframe::Result {
// A copy of this program started to read or write a DWG file does only that. It is started
@@ -589,9 +621,21 @@ fn main() -> eframe::Result {
cadcraft_engine::fonts::ttf::set_fallback_fonts(list);
}
let surface = cadcraft_ui_egui::gpu::surface_config(vars.vsync, cfg!(all(unix, not(target_os = "macos"))));
// XWayland when it's there (see below), unless CADCRAFT_WAYLAND=1 keeps the native Wayland backend.
let forced_x11 = cfg!(all(unix, not(target_os = "macos"))) && std::env::var_os("DISPLAY").is_some() && vars.wayland != Switch::On;
let frame = cadcraft_ui_egui::framework::frame_decision(forced_x11);
// winit runs natively on a Wayland desktop: sharp at fractional scales, with working input
// methods, and file drops from the file manager through storytold/winit's W15 patch.
// CADCRAFT_X11=1 runs through XWayland instead, as a fallback where the native backend
// misbehaves; 0, off or unset leaves it off. The X11 libraries are only recommended by the
// packages, so without them the setting is ignored rather than failing.
#[cfg(all(unix, not(target_os = "macos")))]
let forced_x11 = use_x11(set(std::env::var_os("DISPLAY").as_deref()), vars.x11, x11_libraries_load);
#[cfg(not(all(unix, not(target_os = "macos"))))]
let forced_x11 = false;
// Read before the window opens: Use system title bar decides the window's frame.
let (workspace, restored, workspace_error) = workspace::Workspace::load(vars.config_dir.as_deref());
// Where the desktop leaves the window frame to the app (GNOME on Wayland), the framework's title
// bar carries the window buttons, unless Options ▸ Display ▸ Use system title bar is on.
let title_bar = cadcraft_ui_egui::title_bar::decide(forced_x11, restored.as_ref().is_some_and(|ui| ui.system_title_bar));
let frame = cadcraft_ui_egui::framework::frame_decision(forced_x11).or_else(|| title_bar.as_ref().map(|t| t.decision().clone()));
let persistence_path = vars
.portable_storage_file
.clone()
@@ -620,9 +664,6 @@ fn main() -> eframe::Result {
d
});
}
// winit has no file drag-and-drop on Wayland (only on X11), so dropping files from the file
// manager showed a "no" cursor. Run through XWayland when it's there; CADCRAFT_WAYLAND=1
// keeps the native Wayland backend.
#[cfg(all(unix, not(target_os = "macos")))]
if forced_x11 {
options.event_loop_builder = Some(Box::new(|b| {
@@ -666,7 +707,6 @@ fn main() -> eframe::Result {
{
app.services.start_pick = Some(start_pick(cc.egui_ctx.clone()));
}
let (workspace, restored, workspace_error) = workspace::Workspace::load(vars.config_dir.as_deref());
if let Some(ui) = restored {
app.ui = ui;
}
@@ -716,6 +756,9 @@ fn main() -> eframe::Result {
app.session.set_lisp_support_dir(Some(support));
}
app.integrated_titlebar = cadcraft_ui_egui::framework::draws_title_row(frame.as_ref());
if let Some(title_bar) = title_bar {
app.set_title_bar(title_bar);
}
if surface.present_mode == eframe::wgpu::PresentMode::AutoNoVsync {
app.frame_cap = Some(cadcraft_ui_egui::gpu::FrameCap::new(240));
}
@@ -781,6 +824,37 @@ mod tests {
use super::{filters_for_save, follow_desktop, nightly_version_line, saved_window, version_string, window_options, without_tiny_window};
use crate::renderer::STENCIL_BITS;
/// A Wayland desktop without the X11 libraries (libxkbcommon-x11 removed, or a package
/// installed without its recommendations) crashed at startup: X11 was forced through XWayland
/// and winit panicked loading them. Native Wayland is now the default, `CADCRAFT_X11=1` asks
/// for X11 only when the libraries load, and probing them never panics, whichever of them
/// this machine has.
#[test]
#[cfg(all(unix, not(target_os = "macos")))]
fn x11_only_when_asked_for_and_the_libraries_load() {
use super::{use_x11, x11_libraries_load};
use cadcraft_ui_egui::switch::Switch;
let unprobed = || -> bool { panic!("the libraries are probed only when X11 would be chosen") };
assert!(!use_x11(true, Switch::Default, unprobed), "native Wayland by default");
assert!(!use_x11(true, Switch::Off, unprobed), "CADCRAFT_X11=0 leaves it off");
assert!(!use_x11(false, Switch::On, unprobed), "no X display");
assert!(use_x11(true, Switch::On, || true));
assert!(!use_x11(true, Switch::On, || false), "missing X11 libraries: native Wayland, no crash");
let loaded = x11_libraries_load();
assert_eq!(use_x11(true, Switch::On, || loaded), loaded);
}
/// An empty `DISPLAY` names no X server, so `CADCRAFT_X11=1` can't force X11 with it.
#[test]
#[cfg(all(unix, not(target_os = "macos")))]
fn an_empty_display_is_no_display() {
use super::set;
use std::ffi::OsStr;
assert!(set(Some(OsStr::new(":0"))));
assert!(!set(Some(OsStr::new(""))));
assert!(!set(None));
}
#[test]
fn save_dialog_offers_dwg_with_the_drawing_format_first() {
let first = |name: &str| filters_for_save(name)[0].1;
+4
View File
@@ -50,6 +50,7 @@ fn snapshot(ui: &UiState) -> Result<Value, String> {
"propertiesAll": ui.properties_all,
"inWindowMenu": ui.in_window_menu,
"historyLines": ui.history_lines,
"systemTitleBar": ui.system_title_bar,
}))
}
@@ -219,6 +220,7 @@ mod tests {
ui.toolset_tab = "Modeling".into();
ui.collapsed_groups = vec!["Solid".into()];
ui.history_lines = 5;
ui.system_title_bar = true;
ui.dialog = Some("layers".into());
ui.start_tab = true;
first.save_if_changed(&ui, Instant::now()).unwrap();
@@ -226,6 +228,7 @@ mod tests {
let value: Value = serde_json::from_slice(&bytes).unwrap();
assert!(value["workspace"].get("dialog").is_none());
assert!(value["workspace"].get("startTab").is_none());
assert_eq!(value["workspace"]["systemTitleBar"], true, "read before the window opens");
let (_, restored, error) = Workspace::at(Some(path.clone()));
assert!(error.is_none());
let restored = restored.unwrap();
@@ -340,6 +343,7 @@ mod tests {
assert_eq!(restored.toolset_tab, "Modeling");
assert_eq!(restored.collapsed_groups, ["Draw"]);
assert_eq!(restored.history_lines, 7);
assert!(!restored.system_title_bar, "older files keep the app's window buttons");
assert_eq!(serde_json::to_value(restored.docking).unwrap(), serde_json::to_value(UiState::default().docking).unwrap());
}
fs::remove_dir_all(directory).unwrap();
+131 -6
View File
@@ -7,9 +7,15 @@
//! it draws at paper size × that view's annotation scale, and only in views whose scale it
//! supports unless `ANNOALLVISIBLE` is 1. Model space is seen at `CANNOSCALE`, a layout viewport
//! at its viewport scale, and paper space itself at 1:1.
//!
//! An object supporting several scales can sit somewhere else at one of them ([`AnnoMove`]): its
//! grips move it at the current scale only, and ANNORESET puts every scale back where the current
//! one is. What moves is the object's position ([`shift_position`]).
use serde::{Deserialize, Serialize};
use cadcraft_geom::{Mat3, Vec2};
use crate::{Common, Drawing, Entity, EntityKind};
/// A named annotation scale: `paper_units` on paper show `drawing_units` of the drawing.
@@ -87,6 +93,13 @@ pub fn imperial_scales() -> Vec<AnnoScale> {
v
}
/// How far an annotative object sits from its shared position at the scale named `scale`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AnnoMove {
pub scale: String,
pub by: Vec2,
}
/// Kinds that can be annotative.
pub fn can_be_annotative(k: &EntityKind) -> bool {
matches!(
@@ -105,6 +118,7 @@ pub fn is_annotative(e: &Entity) -> bool {
pub fn set_annotative(e: &mut Entity, on: bool, current: &AnnoScale) {
if !on {
e.common.anno_scales.clear();
e.common.anno_moves.clear();
} else if can_be_annotative(&e.kind) && e.common.anno_scales.is_empty() {
e.common.anno_scales.push(current.clone());
}
@@ -115,8 +129,9 @@ pub fn set_annotative(e: &mut Entity, on: bool, current: &AnnoScale) {
pub enum AnnoDraw {
/// Not annotative: as stored.
Plain,
/// Annotative, at this factor (drawing units per paper unit).
Scaled(f64),
/// Annotative, at `factor` (drawing units per paper unit), its position moved `by` at that
/// scale.
Scaled { factor: f64, by: Vec2 },
/// Annotative and not supporting the view's scale, with `ANNOALLVISIBLE` 0.
Hidden,
}
@@ -130,6 +145,76 @@ impl Common {
pub fn supports_scale(&self, name: &str) -> bool {
self.anno_scales.iter().any(|s| s.name.eq_ignore_ascii_case(name))
}
/// How far the object sits from its shared position at the scale named `name`.
pub fn moved_at(&self, name: &str) -> Vec2 {
self.anno_moves.iter().find(|m| m.scale.eq_ignore_ascii_case(name)).map(|m| m.by).filter(|v| v.is_finite()).unwrap_or(Vec2::ZERO)
}
/// How far the object sits from its shared position at its scale with the ratio `factor`.
pub fn moved_at_factor(&self, factor: f64) -> Vec2 {
self.anno_scales.iter().find(|s| s.has_factor(factor)).map_or(Vec2::ZERO, |s| self.moved_at(&s.name))
}
/// Move the object `by` at the scale named `name` only (an offset that comes to nothing is
/// dropped).
pub fn move_at(&mut self, name: &str, by: Vec2) {
if !by.is_finite() {
return;
}
let to = self.moved_at(name) + by;
self.anno_moves.retain(|m| !m.scale.eq_ignore_ascii_case(name));
if to.len() > 1e-12 * (1.0 + by.len()) && self.anno_moves.len() < MAX_SCALES {
self.anno_moves.push(AnnoMove { scale: name.to_string(), by: to });
}
}
/// Turn the offsets with `m`'s linear part (MOVE leaves them, ROTATE turns them, SCALE sizes
/// them, MIRROR mirrors them), as the shared position goes through `m`.
pub fn transform_moves(&mut self, m: &Mat3) {
for mv in &mut self.anno_moves {
let v = m.apply_vec(mv.by);
mv.by = if v.is_finite() { v } else { Vec2::ZERO };
}
}
}
/// Move the position of `k` by `by`: a text's, MText's or block reference's whole object, a
/// multileader's landing and content (its arrowheads stay), a dimension's text. Other kinds stay.
pub fn shift_position(k: &mut EntityKind, by: Vec2) {
if !by.is_finite() || by == Vec2::ZERO {
return;
}
let add = |p: &mut cadcraft_geom::Vec3| {
p.x += by.x;
p.y += by.y;
};
match k {
EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::Insert(_) => k.transform(&Mat3::translate(by)),
EntityKind::MLeader(m) => {
add(&mut m.landing);
if let Some(t) = &mut m.text {
add(&mut t.insert);
}
if let Some(b) = &mut m.block {
add(&mut b.insert);
}
}
EntityKind::Dimension(d) => {
add(&mut d.text_mid);
d.user_text_pos = true;
d.block = None;
}
_ => {}
}
}
/// Whether grip `index` of `k` is its position grip: moving it moves what [`shift_position`]
/// moves.
pub fn is_position_grip(k: &EntityKind, index: usize) -> bool {
match k {
EntityKind::Text(_) | EntityKind::MText(_) => true,
EntityKind::Insert(_) => index == 0,
EntityKind::Dimension(_) => index == 3,
EntityKind::MLeader(m) => index == m.leaders.iter().map(Vec::len).sum::<usize>(),
_ => false,
}
}
/// How `e` draws in a view whose annotation scale is `view` (drawing units per paper unit). An
@@ -139,14 +224,23 @@ pub fn anno_draw(e: &Entity, view: f64, all_visible: bool) -> AnnoDraw {
return AnnoDraw::Plain;
}
if e.common.supports_factor(view) {
return AnnoDraw::Scaled(if view.is_finite() && view > 0.0 { view } else { 1.0 });
let factor = if view.is_finite() && view > 0.0 { view } else { 1.0 };
return AnnoDraw::Scaled { factor, by: e.common.moved_at_factor(view) };
}
match e.common.anno_scales.first() {
Some(s) if all_visible => AnnoDraw::Scaled(s.factor()),
Some(s) if all_visible => AnnoDraw::Scaled { factor: s.factor(), by: e.common.moved_at(&s.name) },
_ => AnnoDraw::Hidden,
}
}
/// `e` as it draws at annotation scale `f` with its position moved `by` there: [`anno_scaled`],
/// then [`shift_position`].
pub fn anno_placed(e: &Entity, f: f64, by: Vec2) -> Entity {
let mut out = anno_scaled(e, f);
shift_position(&mut out.kind, by);
out
}
/// `e` as it draws at annotation scale `f`: its paper sizes (text height and width, dimension
/// overall scale, multileader arrow, landing and content, hatch pattern scale, block scale and
/// attributes) multiplied by `f`. A dimension is drawn from its definition at that scale, not
@@ -225,13 +319,44 @@ impl Drawing {
/// (paper space shows every annotative object), elsewhere (model space, or an object not in
/// the drawing yet) as [`anno_draw`] at the current annotation scale.
pub fn anno_draw(&self, e: &Entity) -> AnnoDraw {
self.anno_draw_in(e, None)
}
/// How top-level object `e` draws where it is edited: through an active viewport whose
/// annotation scale is `view` (drawing units per paper unit, the viewport's scale, as the
/// renderer draws model space there), else as [`Drawing::anno_draw`].
pub fn anno_draw_in(&self, e: &Entity, view: Option<f64>) -> AnnoDraw {
if !is_annotative(e) {
return AnnoDraw::Plain;
}
if !self.model.contains(e.handle) && self.layouts.iter().any(|l| l.entities.contains(e.handle)) {
return AnnoDraw::Scaled(1.0);
return AnnoDraw::Scaled { factor: 1.0, by: e.common.moved_at_factor(1.0) };
}
let view = view.filter(|f| f.is_finite() && *f > 0.0).unwrap_or_else(|| self.current_anno_scale().factor());
anno_draw(e, view, self.anno_all_visible())
}
/// The scale `e` shows at outside a viewport (see [`Drawing::anno_draw`]): its name and
/// factor, `None` when `e` isn't annotative or doesn't show.
pub fn anno_shown_scale(&self, e: &Entity) -> Option<AnnoScale> {
self.anno_shown_scale_in(e, None)
}
/// The scale `e` shows at in view `view` (see [`Drawing::anno_draw_in`]).
pub fn anno_shown_scale_in(&self, e: &Entity, view: Option<f64>) -> Option<AnnoScale> {
match self.anno_draw_in(e, view) {
AnnoDraw::Scaled { factor, .. } => e.common.anno_scales.iter().find(|s| s.has_factor(factor)).cloned(),
_ => None,
}
}
/// `e` as it draws outside a viewport: an annotative object at its scale and position there,
/// anything else (and a hidden annotative object) as stored.
pub fn anno_shown(&self, e: &Entity) -> EntityKind {
self.anno_shown_in(e, None)
}
/// `e` as it draws in view `view` (see [`Drawing::anno_draw_in`]).
pub fn anno_shown_in(&self, e: &Entity, view: Option<f64>) -> EntityKind {
match self.anno_draw_in(e, view) {
AnnoDraw::Scaled { factor, by } => anno_placed(e, factor, by).kind,
_ => e.kind.clone(),
}
anno_draw(e, self.current_anno_scale().factor(), self.anno_all_visible())
}
/// Whether new objects of this kind are annotative: text and MText with an annotative text
/// style, dimensions with an annotative dimension style, multileaders with an annotative
+5
View File
@@ -98,6 +98,10 @@ pub struct Common {
/// The annotation scales an annotative object supports (empty: not annotative).
#[serde(skip_serializing_if = "Vec::is_empty")]
pub anno_scales: Vec<crate::AnnoScale>,
/// Where an annotative object sits apart from its shared position at some of its scales
/// (moved with its grips at that scale; ANNORESET clears them).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub anno_moves: Vec<crate::AnnoMove>,
/// Other applications' extended data (xdata) as read from the drawing file: whole
/// applications, each from its `1001` group on. It is part of the object, so a copy of the
/// object (COPY, MIRROR, ARRAY, paste) carries it, as in AutoCAD.
@@ -119,6 +123,7 @@ impl Default for Common {
extrusion: Vec3::Z,
plot_style: "ByLayer".into(),
anno_scales: Vec::new(),
anno_moves: Vec::new(),
xdata: Vec::new(),
}
}
+3 -1
View File
@@ -645,7 +645,9 @@ fn bounds_of<'a>(
match d.anno_draw(e) {
crate::AnnoDraw::Plain => {}
crate::AnnoDraw::Hidden => return Bounds2::EMPTY,
crate::AnnoDraw::Scaled(f) => return bounds_in(d, &crate::anno_scaled(e, f), 0, blocks, in_drawing, off_counts, frozen),
crate::AnnoDraw::Scaled { factor, by } => {
return bounds_in(d, &crate::anno_placed(e, factor, by), 0, blocks, in_drawing, off_counts, frozen);
}
}
}
bounds_in(d, e, depth, blocks, in_drawing, off_counts, frozen)
+23 -2
View File
@@ -3,6 +3,7 @@
//! objects show (ANNOALLVISIBLE) and the current annotation scale (CANNOSCALE with
//! ANNOAUTOSCALE).
use cadcraft_doc::geom::Vec2;
use cadcraft_doc::{AnnoScale, Drawing, EntityKind, Handle, MAX_SCALES, is_annotative};
use serde_json::{Value, json};
@@ -136,6 +137,7 @@ fn remove_scale(d: &mut Drawing, h: Handle, name: &str) -> Removed {
return;
}
e.common.anno_scales.retain(|s| !s.name.eq_ignore_ascii_case(name));
e.common.anno_moves.retain(|m| !m.scale.eq_ignore_ascii_case(name));
r = Removed::Yes;
});
r
@@ -216,8 +218,27 @@ fn with_handles(s: &Session, p: &Value, mut extra: Value) -> Value {
fn run_annoreset(s: &mut Session, p: &Value) -> Result<Value> {
let (hs, _) = annotative_targets(s, p, "annoreset")?;
// One position serves every scale of an object, so they are always in step.
Ok(json!({ "objects": hs.len(), "message": format!("{} annotative object(s) synchronized", hs.len()) }))
// Every scale goes where the object shows now (in the active viewport, at its scale): that
// offset becomes the shared position.
let view = s.anno_view();
let d = s.doc_mut()?;
let mut moved = 0;
for h in &hs {
let Some(e) = d.entity(*h) else { continue };
if e.common.anno_moves.is_empty() || d.layer(&e.common.layer).is_some_and(|l| l.locked) {
continue;
}
let by = match d.anno_draw_in(e, view) {
cadcraft_doc::AnnoDraw::Scaled { by, .. } => by,
_ => Vec2::ZERO,
};
d.modify_entity(*h, |e| {
cadcraft_doc::shift_position(&mut e.kind, by);
e.common.anno_moves.clear();
})?;
moved += 1;
}
Ok(json!({ "objects": hs.len(), "reset": moved, "message": format!("{} annotative object(s) synchronized", hs.len()) }))
}
fn run_annoupdate(s: &mut Session, p: &Value) -> Result<Value> {
+1
View File
@@ -86,6 +86,7 @@ pub(crate) fn paste(s: &mut Session, m: &Mat3) -> Result<Vec<Handle>> {
let old_h = e.handle;
let mut e = adopt(d, e, &renames);
e.kind.transform(m);
e.common.transform_moves(m);
d.ensure_layer(&e.common.layer);
out.push(e.handle);
copies.push((old_h, e.handle));
+43 -26
View File
@@ -1,13 +1,13 @@
//! `grip.*` commands: the undoable, scriptable form of grip editing (see `crate::grips`).
use cadcraft_doc::{Entity, EntityKind, Handle};
use cadcraft_doc::{Drawing, Entity, EntityKind, Handle};
use cadcraft_geom::{Mat3, Vec2, Vec3};
use serde_json::{Value, json};
use super::curves;
use super::{CommandSpec, bad, bool_or, point_param, point_req, str_param, targets};
use crate::grips::{GripAction, GripMode, grip_action, mode_matrix, stretch_grip};
use crate::grips::{GripAction, GripMode, grip_action, mode_matrix, shown_grips, stretch_shown};
use crate::{EngineError, Result, Session};
pub fn specs() -> Vec<CommandSpec> {
@@ -46,25 +46,28 @@ fn stretch(s: &mut Session, cmd: &str, p: &Value) -> Result<Value> {
return Err(EngineError::Other("The object is on a locked layer.".into()));
}
let e = curves::entity(s, h)?;
let k = stretch_grip(&e.kind, i, to).ok_or_else(|| bad(cmd, "no such grip, or the result would be degenerate"))?;
let mut edits = vec![(h, k)];
let view = s.anno_view();
let doc = s.doc()?;
let ne = stretch_shown(doc, &e, i, to, view).ok_or_else(|| bad(cmd, "no such grip, or the result would be degenerate"))?;
let mut edits = vec![(h, ne)];
// The other `handles` with a grip on the same point stretch with it (connected objects stay
// connected); locked ones and edits that would be degenerate are left alone.
let from = e.kind.grips().get(i).copied().unwrap_or(to);
let from = shown_grips(doc, &e, view).get(i).copied().unwrap_or(to);
let tol = 1e-9 * (1.0 + from.len());
for o in targets(s, p)? {
if o == h || edits.iter().any(|(x, _)| *x == o) || curves::is_locked(s, o) {
continue;
}
let Ok(oe) = curves::entity(s, o) else { continue };
if let Some(j) = oe.kind.grips().iter().position(|g| g.near(from, tol))
&& let Some(k) = stretch_grip(&oe.kind, j, to)
if let Some(j) = shown_grips(doc, &oe, view).iter().position(|g| g.near(from, tol))
&& let Some(ne) = stretch_shown(doc, &oe, j, to, view)
{
edits.push((o, k));
edits.push((o, ne));
}
}
let d = s.doc_mut()?;
for (o, k) in &mut edits {
for (o, ne) in &mut edits {
let (k, moves) = (&mut ne.kind, &ne.common.anno_moves);
// A dimension's text moved by its grip: with DIMTMOVE 0 the dimension line follows.
if let cadcraft_doc::EntityKind::Dimension(dm) = k
&& let Some(cadcraft_doc::EntityKind::Dimension(old)) = d.entity(*o).map(|e| &e.kind)
@@ -73,14 +76,17 @@ fn stretch(s: &mut Session, cmd: &str, p: &Value) -> Result<Value> {
let st = d.dim_style(&dm.style).cloned().unwrap_or_default().with_overrides(&dm.overrides);
st.follow_text(dm, d.header.f64("DIMSCALE", 1.0));
}
d.modify_entity(*o, |e| e.kind = k.clone())?;
d.modify_entity(*o, |e| {
e.kind = k.clone();
e.common.anno_moves = moves.clone();
})?;
}
Ok(json!({ "handle": h.hex(), "handles": edits.iter().map(|(o, _)| o.hex()).collect::<Vec<_>>() }))
}
/// Z coordinate of grip `index` on `kind` (matching `EntityKind::grips()` order), when the
/// entity stores a 3D position for that grip.
pub(super) fn grip_z(kind: &EntityKind, index: usize) -> Option<f64> {
fn grip_z(kind: &EntityKind, index: usize) -> Option<f64> {
let text_z = |t: &cadcraft_doc::Text| match (t.halign, t.valign) {
(cadcraft_doc::HAlign::Left, cadcraft_doc::VAlign::Baseline) | (cadcraft_doc::HAlign::Aligned | cadcraft_doc::HAlign::Fit, _) => t.insert.z,
_ => t.align_pt.unwrap_or(t.insert).z,
@@ -151,10 +157,17 @@ fn base_point(s: &Session, cmd: &str, p: &Value, hs: &[Handle]) -> Result<Vec2>
.or_else(|| hs.first().copied())
.ok_or_else(|| bad(cmd, "`base` or `baseHandle` + `index` is required"))?;
let i = index_param(cmd, p)?;
let g = curves::entity(s, h)?.kind.grips();
let g = shown_grips(s.doc()?, &curves::entity(s, h)?, s.anno_view());
g.get(i).copied().ok_or_else(|| bad(cmd, "no such grip"))
}
/// The displayed grip's planar point and its Z, when the entity has one.
pub(super) fn shown_grip_location(d: &Drawing, e: &Entity, index: usize, view: Option<f64>) -> Option<(Vec2, Option<f64>)> {
let kind = d.anno_shown_in(e, view);
let point = kind.grips().get(index).copied()?;
Some((point, grip_z(&kind, index)))
}
/// 3D base point for SCALE: explicit `base` (with optional Z or ELEVATION), or the selected grip's
/// full 3D position so the grip stays stationary in all three coordinates.
fn base_point_3d(s: &Session, cmd: &str, p: &Value, hs: &[Handle]) -> Result<Vec3> {
@@ -169,8 +182,8 @@ fn base_point_3d(s: &Session, cmd: &str, p: &Value, hs: &[Handle]) -> Result<Vec
.ok_or_else(|| bad(cmd, "`base` or `baseHandle` + `index` is required"))?;
let i = index_param(cmd, p)?;
let e = curves::entity(s, h)?;
let g = e.kind.grips().get(i).copied().ok_or_else(|| bad(cmd, "no such grip"))?;
Ok(match grip_z(&e.kind, i) {
let (g, z) = shown_grip_location(s.doc()?, &e, i, s.anno_view()).ok_or_else(|| bad(cmd, "no such grip"))?;
Ok(match z {
Some(z) => Vec3::new(g.x, g.y, z),
None => super::modify::at_elevation(s, g),
})
@@ -201,7 +214,7 @@ fn run_grip_stretch(s: &mut Session, p: &Value) -> Result<Value> {
None => {
let base = match point_param(p, "base") {
Some(b) => b,
None => curves::entity(s, h0)?.kind.grips().get(i0).copied().ok_or_else(|| bad(cmd, "no such grip"))?,
None => shown_grips(s.doc()?, &curves::entity(s, h0)?, s.anno_view()).get(i0).copied().ok_or_else(|| bad(cmd, "no such grip"))?,
};
point_req(cmd, p, "to")? - base
}
@@ -245,8 +258,9 @@ const MAX_GRIPS: usize = 1000;
/// The objects as they'd be after moving the grips `hot` by `delta`, with the grips of `others`
/// that sit on a hot grip's point (connected objects stay connected). Locked objects and edits
/// that would be degenerate are left out; several hot grips of one object move together.
pub(super) fn stretched(s: &Session, hot: &[(Handle, usize)], others: &[Handle], delta: Vec2) -> Vec<(Handle, EntityKind)> {
pub(super) fn stretched(s: &Session, hot: &[(Handle, usize)], others: &[Handle], delta: Vec2) -> Vec<(Handle, Entity)> {
let Ok(d) = s.doc() else { return Vec::new() };
let view = s.anno_view();
// Every grip to move, per object, with its target point.
let mut moves: Vec<(Handle, Vec<(usize, Vec2)>)> = Vec::new();
let mut add = |h: Handle, i: usize, to: Vec2| match moves.iter_mut().find(|(x, _)| *x == h) {
@@ -258,14 +272,14 @@ pub(super) fn stretched(s: &Session, hot: &[(Handle, usize)], others: &[Handle],
None => moves.push((h, vec![(i, to)])),
};
for &(h, i) in hot.iter().take(MAX_GRIPS) {
let Some(from) = d.entity(h).and_then(|e| e.kind.grips().get(i).copied()) else { continue };
let Some(from) = d.entity(h).and_then(|e| shown_grips(d, e, view).get(i).copied()) else { continue };
add(h, i, from + delta);
let tol = 1e-9 * (1.0 + from.len());
for &o in others.iter().take(MAX_GRIPS) {
if o == h {
continue;
}
if let Some(j) = d.entity(o).and_then(|e| e.kind.grips().iter().position(|g| g.near(from, tol))) {
if let Some(j) = d.entity(o).and_then(|e| shown_grips(d, e, view).iter().position(|g| g.near(from, tol))) {
add(o, j, from + delta);
}
}
@@ -276,16 +290,16 @@ pub(super) fn stretched(s: &Session, hot: &[(Handle, usize)], others: &[Handle],
continue;
}
let Some(e) = d.entity(h) else { continue };
let mut k = e.kind.clone();
let mut ne = (**e).clone();
let mut changed = false;
for (i, to) in mv {
if let Some(nk) = stretch_grip(&k, i, to) {
k = nk;
if let Some(n) = stretch_shown(d, &ne, i, to, view) {
ne = n;
changed = true;
}
}
if changed {
out.push((h, k));
out.push((h, ne));
}
}
out
@@ -297,16 +311,19 @@ pub(super) fn stretch_grips(s: &mut Session, hot: &[(Handle, usize)], others: &[
let edits = stretched(s, hot, others, delta);
let d = s.doc_mut()?;
let mut out = Vec::new();
for (h, k) in edits {
for (h, ne) in edits {
if copy {
let (Some(sp), Some(e)) = (d.space_of(h), d.entity(h).map(|e| (**e).clone())) else { continue };
let Some(sp) = d.space_of(h) else { continue };
let nh = d.new_handle();
if let Some(st) = d.space_mut(&sp) {
st.push(Entity { handle: nh, kind: k, ..e });
st.push(Entity { handle: nh, ..ne });
out.push(nh);
}
} else {
d.modify_entity(h, |e| e.kind = k)?;
d.modify_entity(h, |e| {
e.kind = ne.kind;
e.common.anno_moves = ne.common.anno_moves;
})?;
out.push(h);
}
}
+10 -4
View File
@@ -104,14 +104,16 @@ impl GripEdit {
if self.hot.contains(&(h, i)) || self.hot.len() >= MAX_HOT {
return Ok(());
}
let p = s.grips_of(h)?.get(i).copied().ok_or_else(|| other("no such grip"))?;
let d = s.doc()?;
let e = d.entity(h).ok_or_else(|| other("no such object"))?;
let (p, z) = super::gripcmds::shown_grip_location(d, e, i, s.anno_view()).ok_or_else(|| other("no such grip"))?;
// After the lookup: a missing object or grip stays the error it was.
if !shown(s, h) {
return Ok(());
}
if self.hot.is_empty() {
self.base = p;
self.base_z = s.doc().ok().and_then(|d| d.entity(h)).and_then(|e| super::gripcmds::grip_z(&e.kind, i));
self.base_z = z;
self.targets.push(h);
self.targets.extend(s.selection().into_iter().filter(|x| *x != h && shown(s, *x)));
} else if !self.targets.contains(&h) {
@@ -131,7 +133,7 @@ impl GripEdit {
continue;
}
let Some(e) = st.doc.entity(h).filter(|e| st.shows(e)) else { continue };
let gs = e.kind.grips();
let gs = crate::grips::shown_grips(&st.doc, e, s.anno_view());
// The nearest grip of this object within the tolerance.
let best = gs
.iter()
@@ -491,7 +493,11 @@ impl Interactive for GripEdit {
};
let Ok(d) = s.doc() else { return Vec::new() };
let mut out: Vec<EntityKind> = if self.mode == GripMode::Stretch {
super::gripcmds::stretched(s, &self.hot, &self.targets, c - base).into_iter().take(500).map(|(_, k)| k).collect()
super::gripcmds::stretched(s, &self.hot, &self.targets, c - base)
.into_iter()
.take(500)
.map(|(_, e)| d.anno_shown_in(&e, s.anno_view()))
.collect()
} else {
match self.matrix(c) {
Some(m) => self
+2 -1
View File
@@ -190,10 +190,11 @@ pub(crate) fn explode_kind(d: &cadcraft_doc::Drawing, e: &Entity) -> Option<Vec<
// An annotative object explodes into plain objects as it draws at the current annotation scale.
if cadcraft_doc::is_annotative(e) {
let mut se = match d.anno_draw(e) {
cadcraft_doc::AnnoDraw::Scaled(f) => cadcraft_doc::anno_scaled(e, f),
cadcraft_doc::AnnoDraw::Scaled { factor, by } => cadcraft_doc::anno_placed(e, factor, by),
_ => e.clone(),
};
se.common.anno_scales.clear();
se.common.anno_moves.clear();
return explode_kind(d, &se);
}
match &e.kind {
+5 -1
View File
@@ -7,7 +7,10 @@ use super::{Entity, Handle, Mat3, Result, Session, Value, Vec2, bad, bool_or, er
pub(crate) fn transform_entities(s: &mut Session, hs: &[Handle], m: &Mat3, copy: bool) -> Result<Vec<Handle>> {
refuse_ole_frames(s, hs, m, copy)?;
edit_entities(s, hs, copy, |e| e.kind.transform(m))
edit_entities(s, hs, copy, |e| {
e.kind.transform(m);
e.common.transform_moves(m);
})
}
/// MIRROR's default hatch policy retains the fill direction while reflecting its boundary.
@@ -40,6 +43,7 @@ pub(crate) fn scale_entities(s: &mut Session, hs: &[Handle], base: Vec3, f: f64,
refuse_ole_frames(s, hs, &m, copy)?;
edit_entities(s, hs, copy, |e| {
e.kind.transform(&m);
e.common.transform_moves(&m);
e.kind.scale_heights(base.z, f);
e.common.thickness *= f;
})
+1
View File
@@ -202,6 +202,7 @@ fn chspace(s: &mut Session, hs: &[Handle], to: Option<&str>, vp: Option<Handle>)
}
let mut e = e;
e.kind.transform(&m);
e.common.transform_moves(&m);
d.remove_entity(*h);
if let Some(st) = d.space_mut(&target) {
st.push(e);
+2 -2
View File
@@ -70,8 +70,8 @@ pub(crate) fn editor_for(s: &Session, h: Handle) -> Option<crate::TextEditor> {
// Annotative text and dimensions are drawn scaled to the current annotation scale: the box
// follows what is drawn. Multiline text keeps its stored height (it is written back from it).
let scaled = match d.anno_draw(e) {
cadcraft_doc::AnnoDraw::Scaled(f) if matches!(e.kind, EntityKind::Text(_) | EntityKind::AttDef(_) | EntityKind::Dimension(_)) => {
Some(cadcraft_doc::anno_scaled(e, f))
cadcraft_doc::AnnoDraw::Scaled { factor, by } if matches!(e.kind, EntityKind::Text(_) | EntityKind::AttDef(_) | EntityKind::Dimension(_)) => {
Some(cadcraft_doc::anno_placed(e, factor, by))
}
_ => None,
};
+6
View File
@@ -171,6 +171,12 @@ impl DocState {
_ => None,
}
}
/// The annotation scale model space is edited at in the active MSPACE viewport: the
/// viewport's scale (drawing units per paper unit, as the renderer draws it there); `None`
/// outside one (the current annotation scale applies).
pub fn anno_view(&self) -> Option<f64> {
self.active_viewport().map(|(_, v)| v.view_height / v.height).filter(|f| f.is_finite() && *f > 0.0)
}
/// The layers frozen in the active MSPACE viewport (VPLAYER, "VP Freeze"): that viewport does
/// not draw their objects, so picks, selections and grips made through it leave them out.
/// Empty in paper space and on the Model tab.
+3 -2
View File
@@ -185,8 +185,9 @@ pub fn grip_dims(s: &Session) -> Vec<GripDim> {
return Vec::new();
}
let Some((h, i)) = s.current_prompt().and_then(|p| p.grip) else { return Vec::new() };
let Some(e) = s.doc().ok().and_then(|d| d.entity(h)) else { return Vec::new() };
let all = dims_of(&e.kind, i);
let Ok(d) = s.doc() else { return Vec::new() };
let Some(e) = d.entity(h) else { return Vec::new() };
let all = dims_of(&d.anno_shown_in(e, s.anno_view()), i);
let st = &s.settings;
match st.dyndivis {
0 => all.into_iter().take(1).collect(),
+51 -2
View File
@@ -4,7 +4,7 @@
//! The UI calls [`Session::grip_edit`]; every edit runs through a `grip.*` command so it is
//! undoable and reachable from scripts, the control channel and MCP.
use cadcraft_doc::{DimKind, EntityKind, Handle, LwPolyline};
use cadcraft_doc::{DimKind, Drawing, Entity, EntityKind, Handle, LwPolyline};
use cadcraft_geom::{Arc, EPS, Mat3, Polyline, Vec2, Vec3, norm_angle};
use serde::{Deserialize, Serialize};
use serde_json::json;
@@ -564,10 +564,59 @@ impl Session {
/// Grip points of an object (the indices `grip_edit` takes).
pub fn grips_of(&self, handle: Handle) -> Result<Vec<Vec2>> {
self.doc()?.entity(handle).map(|e| e.kind.grips()).ok_or_else(|| EngineError::Other("no such object".into()))
let d = self.doc()?;
d.entity(handle).map(|e| shown_grips(d, e, self.anno_view())).ok_or_else(|| EngineError::Other("no such object".into()))
}
}
/// The grip points of `e` as it shows (the indices `grip_edit` takes): an annotative object's at
/// the annotation scale it shows at and its position there. `view`: the active viewport's scale
/// in MSPACE ([`crate::DocState::anno_view`]), else the current annotation scale applies.
pub fn shown_grips(d: &Drawing, e: &Entity, view: Option<f64>) -> Vec<Vec2> {
d.anno_shown_in(e, view).grips()
}
/// `e` with grip `index` of [`shown_grips`] moved to `to`, or `None` when that grip can't move
/// there. An annotative object's position grip moves it at the scale it shows at only when it
/// supports several scales; its other grips change its shape at every scale (the edit is taken
/// back to paper size).
pub fn stretch_shown(d: &Drawing, e: &Entity, index: usize, to: Vec2, view: Option<f64>) -> Option<Entity> {
let with = |kind: EntityKind| Some(Entity { kind, ..e.clone() });
let (Some(scale), cadcraft_doc::AnnoDraw::Scaled { factor, by }) = (d.anno_shown_scale_in(e, view), d.anno_draw_in(e, view)) else {
return with(stretch_grip(&e.kind, index, to)?);
};
let shown = cadcraft_doc::anno_placed(e, factor, by).kind;
let from = *shown.grips().get(index)?;
let delta = to - from;
if !delta.is_finite() {
return None;
}
if cadcraft_doc::is_position_grip(&e.kind, index) {
if e.common.anno_scales.len() > 1 {
let mut out = e.clone();
out.common.move_at(&scale.name, delta);
return Some(out);
}
let stored = *e.kind.grips().get(index)?;
return with(stretch_grip(&e.kind, index, stored + delta)?);
}
// A shape grip: stretch the object as it shows, then take it back to paper size.
let mut k = stretch_grip(&shown, index, to)?;
cadcraft_doc::shift_position(&mut k, -by);
let k = match (k, &e.kind) {
(EntityKind::Dimension(mut dm), EntityKind::Dimension(old)) => {
// A dimension's geometry isn't scaled: only its style scale was.
dm.overrides = old.overrides.clone();
if by != Vec2::ZERO {
dm.user_text_pos = old.user_text_pos;
}
EntityKind::Dimension(dm)
}
(k, _) => cadcraft_doc::anno_scaled(&Entity { kind: k, ..e.clone() }, 1.0 / factor).kind,
};
with(k)
}
/// Polyline helper kept public for the UI: segment midpoints are grips too.
pub fn polyline_grip_count(p: &LwPolyline) -> usize {
p.vertices.len() + Polyline { vertices: p.vertices.clone(), closed: p.closed }.segments().len().min(p.vertices.len())
+5
View File
@@ -416,6 +416,11 @@ impl Session {
Ok(h)
}
/// The annotation scale of the active MSPACE viewport ([`DocState::anno_view`]).
pub fn anno_view(&self) -> Option<f64> {
self.state().ok().and_then(DocState::anno_view)
}
/// World units per pixel at the current view.
pub fn pixel_size(&self) -> f64 {
let v = self.state().map(DocState::view).unwrap_or_default();
+7 -6
View File
@@ -360,15 +360,16 @@ fn blank_mtext_frame(d: &Drawing, e: &Entity) -> Option<(Vec2, f64, [f64; 4])> {
if !is_blank_mtext(text) {
return None;
}
let f = match d.anno_draw(e) {
cadcraft_doc::AnnoDraw::Plain => 1.0,
cadcraft_doc::AnnoDraw::Scaled(f) if f.is_finite() && f > 0.0 => f,
cadcraft_doc::AnnoDraw::Scaled(_) => 1.0,
// As it is drawn: at the current scale, where that scale places it.
let (f, by) = match d.anno_draw(e) {
cadcraft_doc::AnnoDraw::Plain => (1.0, Vec2::ZERO),
cadcraft_doc::AnnoDraw::Scaled { factor, by } if factor.is_finite() && factor > 0.0 => (factor, by),
cadcraft_doc::AnnoDraw::Scaled { .. } => (1.0, Vec2::ZERO),
cadcraft_doc::AnnoDraw::Hidden => return None,
};
let scaled;
let e = if f != 1.0 {
scaled = cadcraft_doc::anno_scaled(e, f);
let e = if f != 1.0 || by != Vec2::ZERO {
scaled = cadcraft_doc::anno_placed(e, f, by);
&scaled
} else {
e
+1 -1
View File
@@ -81,7 +81,7 @@ fn unsupported_scale_hides_unless_annoallvisible() {
let (mut s, h) = with_text();
setvar(&mut s, "CANNOSCALE", json!("1:20"));
// ANNOALLVISIBLE 1 (the default): shown, at the object's own scale.
assert_eq!(s.doc().unwrap().anno_draw(&entity(&s, h)), AnnoDraw::Scaled(1.0));
assert_eq!(s.doc().unwrap().anno_draw(&entity(&s, h)), AnnoDraw::Scaled { factor: 1.0, by: cadcraft_engine::geom::Vec2::ZERO });
assert!(drawn_height(s.doc().unwrap(), h).is_some());
s.execute("annovisible.current", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().header.i64("ANNOALLVISIBLE", 1), 0);
@@ -0,0 +1,221 @@
//! An annotative object can sit somewhere else at one of its scales: its grips move it at the
//! current annotation scale only (when it supports several), MOVE and ROTATE move every scale,
//! and ANNORESET puts every scale back where the current one is.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{AnnoDraw, Entity, EntityKind, Handle};
use cadcraft_engine::geom::Vec2;
use serde_json::{Value, json};
fn setvar(s: &mut Session, name: &str, value: Value) {
s.execute("setvar", &json!({ "name": name, "value": value })).unwrap();
}
fn handle(r: &Value) -> Handle {
r["handle"].as_str().or_else(|| r["handles"][0].as_str()).and_then(Handle::parse_hex).unwrap()
}
fn entity(s: &Session, h: Handle) -> Entity {
(**s.doc().unwrap().entity(h).unwrap()).clone()
}
/// Annotative text at the origin supporting 1:1 and 1:50, with 1:50 current.
fn two_scales() -> (Session, Handle) {
let mut s = Session::new();
s.execute("style", &json!({ "name": "Notes", "annotative": true, "current": true })).unwrap();
let h = handle(&s.execute("text", &json!({ "at": [0, 0], "text": "NOTE", "height": 0.25 })).unwrap());
setvar(&mut s, "CANNOSCALE", json!("1:50"));
s.execute("objectscale", &json!({ "handles": [h.hex()], "add": "1:50" })).unwrap();
(s, h)
}
/// Where `h` shows at annotation scale `name`.
fn shown_at(s: &mut Session, h: Handle, name: &str) -> Vec2 {
setvar(s, "CANNOSCALE", json!(name));
let d = s.doc().unwrap();
match d.anno_shown(d.entity(h).unwrap()) {
EntityKind::Text(t) => t.insert.xy(),
EntityKind::MText(t) => t.insert.xy(),
EntityKind::MLeader(m) => m.landing.xy(),
EntityKind::Dimension(dm) => dm.text_mid.xy(),
k => panic!("{k:?}"),
}
}
fn near(a: Vec2, b: Vec2) -> bool {
a.dist(b) < 1e-9
}
#[test]
fn a_grip_moves_text_at_the_current_scale_only() {
let (mut s, h) = two_scales();
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
// The grips show where the object is.
assert!(near(s.grips_of(h).unwrap()[0], Vec2::new(5.0, 5.0)));
assert!(near(shown_at(&mut s, h, "1:50"), Vec2::new(5.0, 5.0)));
assert!(near(shown_at(&mut s, h, "1:1"), Vec2::ZERO));
}
#[test]
fn grip_scale_keeps_the_displayed_annotation_pivot_and_its_elevation() {
let (mut s, h) = two_scales();
let (z, other_z) = (7.0, 2.0);
s.doc_mut().unwrap().header.set_f64("ELEVATION", other_z);
s.doc_mut()
.unwrap()
.modify_entity(h, |e| {
let EntityKind::Text(t) = &mut e.kind else { panic!("expected text") };
t.insert.z = z;
})
.unwrap();
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
let pivot = s.grips_of(h).unwrap()[0];
assert!(near(pivot, Vec2::new(5.0, 5.0)));
let EntityKind::Text(before) = entity(&s, h).kind else { panic!("expected text") };
s.execute("grip.scale", &json!({ "handles": [h.hex()], "baseHandle": h.hex(), "index": 0, "factor": 2.0 })).unwrap();
let EntityKind::Text(after) = entity(&s, h).kind else { panic!("expected text") };
assert!(near(s.grips_of(h).unwrap()[0], pivot), "the displayed grip is stationary");
assert!((after.insert.z - z).abs() < 1e-9, "the selected grip's Z is stationary, not ELEVATION");
assert!((after.height - 2.0 * before.height).abs() < 1e-9, "the scale operation actually took effect");
}
#[test]
fn undo_takes_a_move_at_one_scale_back() {
let (mut s, h) = two_scales();
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
assert_eq!(entity(&s, h).common.anno_moves.len(), 1);
s.execute("undo", &json!({})).unwrap();
assert!(entity(&s, h).common.anno_moves.is_empty());
}
#[test]
fn move_and_rotate_carry_every_scale() {
let (mut s, h) = two_scales();
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
s.execute("move", &json!({ "handles": [h.hex()], "delta": [1, 0] })).unwrap();
assert!(near(shown_at(&mut s, h, "1:50"), Vec2::new(6.0, 5.0)));
assert!(near(shown_at(&mut s, h, "1:1"), Vec2::new(1.0, 0.0)));
s.execute("rotate", &json!({ "handles": [h.hex()], "base": [0, 0], "angle": 90 })).unwrap();
assert!(near(shown_at(&mut s, h, "1:50"), Vec2::new(-5.0, 6.0)));
assert!(near(shown_at(&mut s, h, "1:1"), Vec2::new(0.0, 1.0)));
}
#[test]
fn annoreset_puts_every_scale_at_the_current_one() {
let (mut s, h) = two_scales();
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
setvar(&mut s, "CANNOSCALE", json!("1:50"));
let r = s.execute("annoreset", &json!({ "handles": [h.hex()] })).unwrap();
assert_eq!(r["reset"], 1, "{r}");
assert!(entity(&s, h).common.anno_moves.is_empty());
assert!(near(shown_at(&mut s, h, "1:1"), Vec2::new(5.0, 5.0)));
assert!(near(shown_at(&mut s, h, "1:50"), Vec2::new(5.0, 5.0)));
}
#[test]
fn removing_a_scale_drops_its_position() {
let (mut s, h) = two_scales();
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
s.execute("objectscale", &json!({ "handles": [h.hex()], "delete": "1:50" })).unwrap();
assert!(entity(&s, h).common.anno_moves.is_empty());
}
#[test]
fn an_object_with_one_scale_moves_everywhere() {
let mut s = Session::new();
s.execute("style", &json!({ "name": "Notes", "annotative": true, "current": true })).unwrap();
setvar(&mut s, "CANNOSCALE", json!("1:50"));
let h = handle(&s.execute("text", &json!({ "at": [0, 0], "text": "NOTE", "height": 0.25 })).unwrap());
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
let e = entity(&s, h);
assert!(e.common.anno_moves.is_empty());
let EntityKind::Text(t) = &e.kind else { panic!() };
assert!(near(t.insert.xy(), Vec2::new(5.0, 5.0)));
}
#[test]
fn a_multileader_moves_its_content_and_keeps_its_arrowhead() {
let mut s = Session::new();
s.execute("mleaderstyle", &json!({ "name": "Anno", "annotative": true })).unwrap();
let h = handle(&s.execute("mleader", &json!({ "points": [[0, 0], [5, 5]], "text": "A" })).unwrap());
setvar(&mut s, "CANNOSCALE", json!("1:50"));
s.execute("objectscale", &json!({ "handles": [h.hex()], "add": "1:50" })).unwrap();
let EntityKind::MLeader(m) = entity(&s, h).kind else { panic!() };
let landing = m.leaders.iter().map(Vec::len).sum::<usize>();
let to = m.landing.xy() + Vec2::new(2.0, 1.0);
s.execute("grip.move", &json!({ "handle": h.hex(), "index": landing, "to": [to.x, to.y] })).unwrap();
assert!(near(shown_at(&mut s, h, "1:50"), to));
assert!(near(shown_at(&mut s, h, "1:1"), m.landing.xy()));
setvar(&mut s, "CANNOSCALE", json!("1:50"));
let d = s.doc().unwrap();
let EntityKind::MLeader(shown) = d.anno_shown(d.entity(h).unwrap()) else { panic!() };
assert!(near(shown.leaders[0][0].xy(), Vec2::ZERO), "the arrowhead stays");
}
#[test]
fn a_dimension_moves_its_text_at_one_scale() {
let mut s = Session::new();
s.execute("dimstyle", &json!({ "name": "Anno", "annotative": true, "current": true })).unwrap();
let h = handle(&s.execute("dimaligned", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 2] })).unwrap());
setvar(&mut s, "CANNOSCALE", json!("1:2"));
s.execute("objectscale", &json!({ "handles": [h.hex()], "add": "1:2" })).unwrap();
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 3, "to": [20, 20] })).unwrap();
assert!(near(shown_at(&mut s, h, "1:2"), Vec2::new(20.0, 20.0)));
let e = entity(&s, h);
let EntityKind::Dimension(dm) = &e.kind else { panic!() };
assert!(!near(dm.text_mid.xy(), Vec2::new(20.0, 20.0)), "the shared text position stays");
assert_eq!(e.common.anno_moves.len(), 1);
}
#[test]
fn shown_draws_through_the_offset() {
let (mut s, h) = two_scales();
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
setvar(&mut s, "CANNOSCALE", json!("1:50"));
let d = s.doc().unwrap();
assert!(matches!(d.anno_draw(d.entity(h).unwrap()), AnnoDraw::Scaled { by, .. } if near(by, Vec2::new(5.0, 5.0))));
let b = cadcraft_engine::doc::entity_bounds(d, d.entity(h).unwrap(), 0);
assert!(b.min.x > 4.0 && b.min.y > 4.0, "{b:?}");
}
#[test]
fn hostile_offsets_never_panic() {
let (mut s, h) = two_scales();
for to in [json!([1e308, -1e308]), json!([f64::MAX, 0]), json!(["x", 1])] {
let _ = s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": to }));
}
s.doc_mut().unwrap().modify_entity(h, |e| e.common.move_at("1:50", Vec2::new(f64::NAN, 1.0))).unwrap();
let _ = s.execute("annoreset", &json!({ "handles": [h.hex()] }));
let _ = s.execute("rotate", &json!({ "handles": [h.hex()], "base": [0, 0], "angle": 1e300 }));
let d = s.doc().unwrap();
let _ = cadcraft_engine::render::build(d, &cadcraft_engine::doc::Space::Model, &Default::default());
let _ = bounds(d, h);
}
fn bounds(d: &cadcraft_engine::doc::Drawing, h: Handle) -> cadcraft_engine::geom::Bounds2 {
cadcraft_engine::doc::entity_bounds(d, d.entity(h).unwrap(), 0)
}
#[test]
fn in_a_viewport_grips_and_annoreset_use_the_viewport_s_scale() {
// The text moved at 1:50; CANNOSCALE is 1:1 while a 1:50 viewport is active (MSPACE): the
// grips show where the viewport draws it, a grip moves it at 1:50, ANNORESET takes 1:50's place.
let (mut s, h) = two_scales();
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
setvar(&mut s, "CANNOSCALE", json!("1:1"));
s.execute("layout.set", &json!({ "name": "Layout1" })).unwrap();
let vp = s.execute("mview", &json!({ "p1": [0, 0], "p2": [200, 100] })).unwrap();
let vh = vp["viewports"][0].as_str().and_then(Handle::parse_hex).unwrap();
s.execute("viewport.set", &json!({ "handle": vh.hex(), "scale": "1:50", "center": [0, 0] })).unwrap();
s.execute("mspace", &json!({ "handle": vh.hex() })).unwrap();
assert!((s.anno_view().unwrap() - 50.0).abs() < 1e-9);
assert!(near(s.grips_of(h).unwrap()[0], Vec2::new(5.0, 5.0)), "{:?}", s.grips_of(h));
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [7, 7] })).unwrap();
assert!(near(s.grips_of(h).unwrap()[0], Vec2::new(7.0, 7.0)));
s.execute("annoreset", &json!({ "handles": [h.hex()] })).unwrap();
s.execute("pspace", &json!({})).unwrap();
s.execute("layout.set", &json!({ "name": "Model" })).unwrap();
// 1:1 was never moved by the grips, and now sits where 1:50 is.
assert!(near(shown_at(&mut s, h, "1:1"), Vec2::new(7.0, 7.0)));
assert!(near(shown_at(&mut s, h, "1:50"), Vec2::new(7.0, 7.0)));
}
+1
View File
@@ -6,6 +6,7 @@ mod angle_prompts;
mod angle_settings;
mod annotate_options;
mod annotative;
mod annotative_positions;
mod arc_ctrl_direction;
mod array_commands;
mod array_counts;
+85 -3
View File
@@ -11,8 +11,9 @@
//! CADCraft keeps an annotative object at paper size with the list of scales it supports
//! ([`cadcraft_doc::Common::anno_scales`]). It writes the object at its default scale with a
//! context per scale ([`plan`], [`objects`]), and reads the scales and paper size back from the
//! contexts ([`resolve`]). An object's position at each scale is the one the scale gives it:
//! AutoCAD lets a context move an object at one scale only, which CADCraft doesn't model.
//! contexts ([`resolve`]). A context can place the object somewhere else at its scale (moved with
//! grips at that scale in AutoCAD or CADCraft): that is the object's offset at the scale
//! ([`cadcraft_doc::AnnoMove`]), written into and read back from the context's position.
//!
//! Objects inside block definitions are left alone, and files older than AutoCAD 2007's format
//! (before annotation scaling) don't get contexts.
@@ -67,8 +68,16 @@ fn by_alignment(t: &Text) -> bool {
/// `e` at annotation scale `f`, as its groups are written there: sizes scaled (see
/// [`cadcraft_doc::anno_scaled`]) and justified text's start point moved with its size about its
/// alignment point. A dimension's definition gets that scale (DIMSCALE).
/// alignment point. A dimension's definition gets that scale (DIMSCALE). The object's offset at
/// that scale moves it there.
pub(crate) fn at_scale(e: &Entity, f: f64) -> Entity {
let mut out = shared_at_scale(e, f);
cadcraft_doc::shift_position(&mut out.kind, e.common.moved_at_factor(f));
out
}
/// [`at_scale`] at the object's shared position (without its offset there).
fn shared_at_scale(e: &Entity, f: f64) -> Entity {
let mut out = cadcraft_doc::anno_scaled(e, f);
if let (EntityKind::Text(t), EntityKind::Text(paper)) = (&mut out.kind, &e.kind)
&& by_alignment(paper)
@@ -79,6 +88,47 @@ pub(crate) fn at_scale(e: &Entity, f: f64) -> Entity {
out
}
/// The point that places `e` (as written at some scale): a text's start or alignment point, an
/// MText's insertion point, a dimension's text position, a multileader's landing.
fn anchor(d: &Drawing, e: &Entity) -> Option<cadcraft_geom::Vec2> {
let p = match &e.kind {
EntityKind::Text(t) if by_alignment(t) => t.align_pt?.xy(),
EntityKind::Text(t) => t.insert.xy(),
EntityKind::MText(t) => t.insert.xy(),
EntityKind::Dimension(dm) if dm.user_text_pos => dm.text_mid.xy(),
EntityKind::Dimension(dm) => cadcraft_render::dimension_in(d, dm).text_pos,
EntityKind::MLeader(m) => m.landing.xy(),
_ => return None,
};
p.is_finite().then_some(p)
}
/// The same point as a context of `e` holds it (`g`: the context's groups after its SCALE
/// handle).
fn context_anchor(e: &Entity, g: &[Tag]) -> Option<cadcraft_geom::Vec2> {
let xy = |code: i32| -> Option<cadcraft_geom::Vec2> {
let i = g.iter().position(|t| t.code == code)?;
let y = g.get(i + 1).filter(|t| t.code == code + 10)?;
let v = cadcraft_geom::Vec2::new(g.get(i)?.f64(), y.f64());
v.is_finite().then_some(v)
};
match &e.kind {
EntityKind::Text(t) if by_alignment(t) => xy(11),
EntityKind::Text(_) => xy(10),
EntityKind::MText(_) => xy(11),
// Only a text the user placed (294 = 0) holds its own position.
EntityKind::Dimension(_) => g.iter().find(|t| t.code == 294).is_some_and(|t| t.i64() == 0).then(|| xy(10)).flatten(),
EntityKind::MLeader(_) => {
let mut tags = vec![Tag::s(100, "AcDbMLeader"), Tag::s(300, "CONTEXT_DATA{")];
tags.extend(g.iter().cloned());
tags.push(Tag::s(301, "}"));
let p = crate::dxf_mleader::read(&tags).landing.xy();
p.is_finite().then_some(p)
}
_ => None,
}
}
/// One context: its handle, the SCALE object's handle and the scale.
pub(crate) struct Context {
handle: String,
@@ -347,6 +397,16 @@ pub(crate) fn mleader_at(tags: &mut [Tag], f: f64) {
}
}
/// A multileader's groups (as [`crate::dxf_mleader::entity_tags`] writes them) marked annotative:
/// the entity's "enable annotation scale" (its 293, after the `CONTEXT_DATA{` block) is on.
/// Without it AutoCAD keeps the contexts but its ANNORESET passes the multileader over.
pub(crate) fn mleader_annotative(tags: &mut [Tag]) {
let Some(close) = tags.iter().position(|t| t.code == 301) else { return };
if let Some(t) = tags.iter_mut().skip(close + 1).find(|t| t.code == 293) {
*t = Tag::i(293, 1);
}
}
// ---------------------------------------------------------------------------------------------
// Reading
@@ -422,6 +482,7 @@ pub(crate) fn resolve(secs: &[SectionRef<'_>], d: &mut Drawing) {
.and_then(|s| objs.get(&s));
let Some((_, dict)) = dict else { continue };
let mut list: Vec<(AnnoScale, bool)> = Vec::new();
let mut placed: Vec<(String, f64, cadcraft_geom::Vec2)> = Vec::new();
for c in all_entries(dict) {
let Some((_, t)) = objs.get(&c).filter(|(k, _)| k.ends_with("OBJECTCONTEXTDATA_CLASS")) else { continue };
let g = own(t);
@@ -431,6 +492,10 @@ pub(crate) fn resolve(secs: &[SectionRef<'_>], d: &mut Drawing) {
&& !list.iter().any(|(x, _)| x.name.eq_ignore_ascii_case(&s.name))
{
list.push((s.clone(), default));
let after = g.iter().position(|t| t.code == 340).map_or(&[][..], |i| g.get(i + 1..).unwrap_or(&[]));
if let Some(at) = context_anchor(e, after) {
placed.push((s.name.clone(), s.factor(), at));
}
}
}
if list.is_empty() {
@@ -443,6 +508,23 @@ pub(crate) fn resolve(secs: &[SectionRef<'_>], d: &mut Drawing) {
e.common.anno_scales = list;
to_paper(e, f);
});
// A context placing the object elsewhere than its scale would: its offset there.
let Some(e) = d.entity(h).map(|e| (**e).clone()) else { continue };
let moves: Vec<(String, cadcraft_geom::Vec2)> = placed
.iter()
.filter_map(|(name, f, at)| {
let by = *at - anchor(d, &shared_at_scale(&e, *f))?;
let tol = 1e-6 * (1.0 + at.len());
(by.is_finite() && by.len() > tol).then(|| (name.clone(), by))
})
.collect();
if !moves.is_empty() {
let _ = d.modify_entity(h, |e| {
for (name, by) in &moves {
e.common.move_at(name, *by);
}
});
}
}
}
+15 -1
View File
@@ -1024,6 +1024,11 @@ pub(crate) struct AnnoPayload {
struct AnnoObject {
handle: String,
scales: Vec<cadcraft_doc::AnnoScale>,
/// Where the object sits at a scale when it was moved there alone (see `Common::anno_moves`):
/// a format without annotation scale contexts (or a DWG, whose bridge doesn't convert them
/// yet) keeps them here.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
moves: Vec<cadcraft_doc::AnnoMove>,
}
/// Most annotative objects read from one file.
@@ -1041,7 +1046,7 @@ pub(crate) fn anno_chunks(d: &cadcraft_doc::Drawing, contexts: bool) -> Option<V
.iter()
.chain(d.layouts.iter().flat_map(|l| l.entities.iter()))
.filter(|e| cadcraft_doc::is_annotative(e) && !(contexts && crate::dxf_anno::has_contexts(e)))
.map(|e| AnnoObject { handle: e.handle.hex(), scales: e.common.anno_scales.clone() })
.map(|e| AnnoObject { handle: e.handle.hex(), scales: e.common.anno_scales.clone(), moves: e.common.anno_moves.clone() })
.collect();
if cannoscale == "1:1" && annoallvisible == 1 && blocks.is_empty() && objects.is_empty() {
return None;
@@ -1102,9 +1107,18 @@ pub(crate) fn apply_anno(d: &mut cadcraft_doc::Drawing, p: AnnoPayload) {
scales.push(s);
}
}
// Each move once, for a scale the object keeps, by a finite offset.
let mut moves: Vec<cadcraft_doc::AnnoMove> = Vec::new();
for m in o.moves.into_iter().take(cadcraft_doc::MAX_SCALES) {
let known = scales.iter().any(|s| s.name.eq_ignore_ascii_case(&m.scale));
if known && m.by.is_finite() && !moves.iter().any(|x| x.scale.eq_ignore_ascii_case(&m.scale)) {
moves.push(m);
}
}
store.modify(h, |e| {
if cadcraft_doc::can_be_annotative(&e.kind) {
e.common.anno_scales = scales;
e.common.anno_moves = moves;
}
});
}
+1 -78
View File
@@ -1,6 +1,4 @@
use super::{
Block, Color, Common, Dimension, Drawing, Entity, EntityKind, EntityStore, Handle, HashMap, Line, MText, Solid, Table, Vec2, Vec3, dxf_ext,
};
use super::{Block, Color, Common, Drawing, Entity, EntityKind, EntityStore, Handle, HashMap, Line, MText, Solid, Table, Vec2, Vec3, dxf_ext};
/// What happens to the dimension blocks read from a file (#495): a dimension that still names
/// its block is written with that block, under its name, and `*D` blocks nothing else
@@ -79,81 +77,6 @@ pub(super) fn reuse_handles(ents: &mut [Entity], old: &Block, taken: &mut std::c
}
}
/// Anonymous dimension blocks (`*D1`…) with the rendered geometry, as consumers expect.
pub(super) fn dim_block_entities(d: &Drawing, dm: &Dimension, layer: &str) -> Vec<Entity> {
// The dimension as drawn: its overrides, DIMSCALE (0 = the drawing's) and text font.
let style = d.dim_style(&dm.style).cloned().unwrap_or_default().with_overrides(&dm.overrides);
let g = cadcraft_render::dimension_in(d, dm);
let mut out = Vec::new();
// Each part in its style colour (DIMCLRD, DIMCLRE, DIMCLRT), ByBlock when the style says so,
// as AutoCAD writes them: readers that draw the block drew every part ByBlock, i.e. in the
// dimension's own colour (#1052).
let in_color = |color: Color| Common { layer: layer.into(), color, ..Common::default() };
let (dim_c, ext_c, text_c) = (in_color(style.dim_line_color), in_color(style.ext_line_color), in_color(style.text_color));
let line_entities = |i: usize, l: &[Vec2]| -> Vec<Entity> {
let c = match g.line_roles.get(i) {
Some(cadcraft_render::LineRole::Ext) => &ext_c,
_ => &dim_c,
};
l.windows(2)
.filter_map(|seg| match seg {
[a, b] => Some(Entity { handle: Handle(0), common: c.clone(), kind: EntityKind::Line(Line { a: a.to3(0.0), b: b.to3(0.0) }) }),
_ => None,
})
.collect()
};
// The text's marks (arc length symbol, DIMINSPECT frame) go after the text background.
for (i, l) in g.lines.iter().enumerate().filter(|(i, _)| !g.text_marks.contains(i)) {
out.extend(line_entities(i, l));
}
for t in &g.fills {
if let [a, b, cc] = t.as_slice() {
out.push(Entity {
handle: Handle(0),
common: dim_c.clone(),
kind: EntityKind::Solid(Solid { corners: [a.to3(0.0), b.to3(0.0), cc.to3(0.0), cc.to3(0.0)] }),
});
}
}
// DIMTFILL 2: the text background in DIMTFILLCLR, under the text and its marks (SOLID
// corners go 1, 2, 4, 3).
if style.text_fill == 2
&& let [p0, p1, p2, p3] = g.text_fill.as_slice()
{
out.push(Entity {
handle: Handle(0),
common: in_color(style.text_fill_color),
kind: EntityKind::Solid(Solid { corners: [p0.to3(0.0), p1.to3(0.0), p3.to3(0.0), p2.to3(0.0)] }),
});
}
for (i, l) in g.lines.iter().enumerate().filter(|(i, _)| g.text_marks.contains(i)) {
out.extend(line_entities(i, l));
}
// The text, and the part after `\X` below the dimension line as a second MTEXT, as AutoCAD
// writes it (#1055).
let texts = std::iter::once((g.value.clone(), g.text_pos)).chain(g.below.clone());
for (contents, at) in texts.filter(|(t, _)| !t.is_empty()) {
out.push(Entity {
handle: Handle(0),
common: text_c.clone(),
kind: EntityKind::MText(MText {
insert: at.to3(0.0),
height: g.text_height,
width: 0.0,
attach: 5,
rotation: g.text_angle,
style: style.text_style.clone(),
contents: cadcraft_render::DimGeometry::mtext_code(&contents),
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
background: None,
}),
});
}
out
}
/// Rows and columns written for a table (bounded like the renderer).
pub(super) fn table_size(t: &Table) -> (usize, usize) {
(t.row_heights.len().min(10_000), t.col_widths.len().min(10_000))
+1
View File
@@ -678,6 +678,7 @@ fn write_annotations_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, pap
let mut tags = cx.mleader_tags(d, m);
if let Some(o) = cx.anno.objs.get(&e.handle) {
crate::dxf_anno::mleader_at(&mut tags, crate::dxf_anno::default_factor(o));
crate::dxf_anno::mleader_annotative(&mut tags);
}
w.t.extend(tags);
cx.anno_xdata(w, e);
+2 -1
View File
@@ -1,5 +1,5 @@
use super::assoc::std_assoc_refs;
use super::blocks::{arrow_block_entities, dim_block_entities, dim_block_plan, reuse_handles, table_block_entities};
use super::blocks::{arrow_block_entities, dim_block_plan, reuse_handles, table_block_entities};
use super::common::annotative_xdata;
use super::ctx::{AssocObj, Ctx};
use super::entity::{entity, hatch_reactors};
@@ -11,6 +11,7 @@ use super::{
Space, TableStyle, Tag, Ucs, Vec2, Vec3, Version, W, dxf_ext,
};
use super::{entity_handles, structural_start};
use cadcraft_render::dim_block_entities;
struct TableWritePlan<'a> {
d: &'a Drawing,
@@ -798,3 +798,121 @@ fn the_current_scale_is_autocad_s_and_saving_keeps_it_current() {
let var = recs.iter().find(|(k, _)| k == "DICTIONARYVAR").unwrap();
assert_eq!(get(&var.1, 1), Some("1:1"));
}
#[test]
fn a_context_placing_the_object_elsewhere_reads_as_its_offset_there() {
// The text sits 5 further right at 1:10 than its 1:2 position would put it.
let src = FIXTURE.replacen("10 -40\n20 0\n11 30", "10 -35\n20 0\n11 35", 1);
assert_ne!(src, FIXTURE);
let d = cadcraft_io::read_dxf(dxf(&src).as_bytes()).unwrap();
let e = d.entity(Handle::parse_hex("30").unwrap()).unwrap();
assert_eq!(e.common.anno_moves.len(), 1, "{:?}", e.common.anno_moves);
assert_eq!(e.common.anno_moves[0].scale, "1:10");
assert!(e.common.anno_moves[0].by.dist(cadcraft_geom::Vec2::new(5.0, 0.0)) < 1e-9);
// An unmoved fixture has none.
assert!(read().model.iter().all(|e| e.common.anno_moves.is_empty()));
// Written back, the 1:10 context keeps its own position.
let text = save(&d);
let starts: Vec<f64> = contexts_of(&text, "30").iter().map(|c| num(&c.tags, 11)).collect();
assert_eq!(starts, [30.0, 35.0]);
}
#[test]
fn offsets_made_in_cadcraft_survive_a_save() {
let mut d = made();
let hs: Vec<Handle> = d.model.iter().map(|e| e.handle).collect();
for h in &hs {
d.modify_entity(*h, |e| e.common.move_at("1:1", cadcraft_geom::Vec2::new(3.0, 4.0))).unwrap();
}
let back = cadcraft_io::read_dxf(save(&d).as_bytes()).unwrap();
for h in &hs {
let (a, b) = (d.entity(*h).unwrap(), back.entity(*h).unwrap());
for f in [1.0, 50.0] {
let shown = |d: &Drawing, e: &cadcraft_doc::Entity| match cadcraft_doc::anno_draw(e, f, true) {
cadcraft_doc::AnnoDraw::Scaled { factor, by } => match cadcraft_doc::anno_placed(e, factor, by).kind {
EntityKind::Text(t) => t.insert.xy(),
EntityKind::Dimension(dm) if dm.user_text_pos => dm.text_mid.xy(),
EntityKind::Dimension(dm) => cadcraft_render::dimension_in(d, &dm).text_pos,
k => panic!("{k:?}"),
},
m => panic!("{m:?}"),
};
let (p, q) = (shown(&d, a), shown(&back, b));
assert!(p.dist(q) < 1e-6, "{h:?} at {f}: {p:?} vs {q:?}");
}
}
}
/// The landing and text of multileader `e` as it shows at annotation scale `f`.
fn mleader_shown(e: &cadcraft_doc::Entity, f: f64) -> (cadcraft_geom::Vec2, cadcraft_geom::Vec2) {
let cadcraft_doc::AnnoDraw::Scaled { factor, by } = cadcraft_doc::anno_draw(e, f, true) else { panic!("hidden") };
let EntityKind::MLeader(m) = cadcraft_doc::anno_placed(e, factor, by).kind else { panic!("multileader") };
(m.landing.xy(), m.text.unwrap().insert.xy())
}
#[test]
fn a_multileader_moved_at_one_scale_keeps_it_through_dxf() {
let (mut d, h) = with_mleader();
d.modify_entity(h, |e| e.common.move_at("1:1", cadcraft_geom::Vec2::new(2.0, -1.0))).unwrap();
let dxf_back = cadcraft_io::read_dxf(save(&d).as_bytes()).unwrap();
let a = d.entity(h).unwrap();
{
let back = &dxf_back;
let b = back.model.iter().find(|e| matches!(e.kind, EntityKind::MLeader(_))).unwrap();
for f in [1.0, 10.0] {
let ((la, ta), (lb, tb)) = (mleader_shown(a, f), mleader_shown(b, f));
assert!(la.dist(lb) < 1e-6 && ta.dist(tb) < 1e-6, "at {f}: {la:?} {ta:?} vs {lb:?} {tb:?}");
}
}
}
/// A multileader moved at one scale alone is there again after a DWG round trip, carried by
/// CADCraft's own record (the DWG bridge doesn't convert contexts yet, storytold/craft-libs#2005).
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_multileader_moved_at_one_scale_keeps_it_through_dwg() {
cadcraft_io::dwg_worker::allow_in_process();
let (mut d, h) = with_mleader();
d.modify_entity(h, |e| e.common.move_at("1:1", cadcraft_geom::Vec2::new(2.0, -1.0))).unwrap();
let dwg = cadcraft_io::write(&d, "x.dwg").unwrap();
let dwg_back = cadcraft_io::read(&dwg, "x.dwg").unwrap();
let a = d.entity(h).unwrap();
{
let back = &dwg_back;
let b = back.model.iter().find(|e| matches!(e.kind, EntityKind::MLeader(_))).unwrap();
for f in [1.0, 10.0] {
let ((la, ta), (lb, tb)) = (mleader_shown(a, f), mleader_shown(b, f));
assert!(la.dist(lb) < 1e-6 && ta.dist(tb) < 1e-6, "at {f}: {la:?} {ta:?} vs {lb:?} {tb:?}");
}
}
}
/// The MULTILEADER entity's own 293 ("enable annotation scale", after its `CONTEXT_DATA{` block).
fn mleader_enable_annotation_scale(text: &str) -> Option<String> {
let recs = records(text);
let (_, t) = recs.iter().find(|(k, _)| k == "MULTILEADER")?;
let close = t.iter().position(|(c, _)| *c == 301)?;
t.iter().skip(close + 1).find(|(c, _)| *c == 293).map(|(_, v)| v.trim().to_string())
}
#[test]
fn an_annotative_multileader_has_annotation_scale_enabled() {
// AutoCAD's ANNORESET passes over a multileader whose 293 is off, even with its contexts.
let (d, h) = with_mleader();
assert_eq!(mleader_enable_annotation_scale(&save(&d)).as_deref(), Some("1"));
let mut plain = d.clone();
plain.modify_entity(h, |e| e.common.anno_scales.clear()).unwrap();
assert_eq!(mleader_enable_annotation_scale(&save(&plain)).as_deref(), Some("0"));
}
#[test]
fn hostile_context_positions_do_not_panic() {
for bad in ["10 1e309\n20 nan\n11 inf", "10 x\n20 0\n11 -1e308", "10 -40\n20 0\n11 1e308"] {
let src = FIXTURE.replacen("10 -40\n20 0\n11 30", bad, 1);
let Ok(d) = cadcraft_io::read_dxf(dxf(&src).as_bytes()) else { continue };
for e in d.model.iter() {
assert!(e.common.anno_moves.iter().all(|m| m.by.is_finite()), "{:?}", e.common.anno_moves);
}
let _ = save(&d);
}
}
+16 -2
View File
@@ -204,8 +204,21 @@ fn entity(expected: &Entity, actual: &Entity, context: &str) {
fn common(expected: &Common, actual: &Common, context: &str) {
// No `..`: adding a field requires deciding its preservation contract here.
let Common { layer, color, linetype, lineweight, ltscale, transparency, visible, thickness, extrusion, plot_style, anno_scales, xdata } =
expected;
let Common {
layer,
color,
linetype,
lineweight,
ltscale,
transparency,
visible,
thickness,
extrusion,
plot_style,
anno_scales,
anno_moves,
xdata,
} = expected;
equal(layer, &actual.layer, context, "layer");
equal(color, &actual.color, context, "color");
equal(linetype, &actual.linetype, context, "linetype");
@@ -217,6 +230,7 @@ fn common(expected: &Common, actual: &Common, context: &str) {
equal(extrusion, &actual.extrusion, context, "extrusion");
equal(plot_style, &actual.plot_style, context, "plot_style");
equal(anno_scales, &actual.anno_scales, context, "anno_scales");
equal(anno_moves, &actual.anno_moves, context, "anno_moves");
equal(xdata, &actual.xdata, context, "xdata");
}
+83
View File
@@ -0,0 +1,83 @@
//! The contents of a dimension's anonymous `*D` block: the dimension's graphics as plain objects.
use cadcraft_doc::{Common, Dimension, Line, MText, Solid};
use super::{Color, DimGeometry, Drawing, Entity, EntityKind, Handle, LineRole, Vec2, dimension_in};
/// Anonymous dimension blocks (`*D1`…) with the rendered geometry, as consumers expect.
///
/// The entities of the block of dimension `dm` on layer `layer`, with handle 0. The DXF/DWG
/// writer makes the blocks of a saved file with it.
pub fn dim_block_entities(d: &Drawing, dm: &Dimension, layer: &str) -> Vec<Entity> {
// The dimension as drawn: its overrides, DIMSCALE (0 = the drawing's) and text font.
let style = d.dim_style(&dm.style).cloned().unwrap_or_default().with_overrides(&dm.overrides);
let g = dimension_in(d, dm);
let mut out = Vec::new();
// Each part in its style colour (DIMCLRD, DIMCLRE, DIMCLRT), ByBlock when the style says so,
// as AutoCAD writes them: readers that draw the block drew every part ByBlock, i.e. in the
// dimension's own colour (#1052).
let in_color = |color: Color| Common { layer: layer.into(), color, ..Common::default() };
let (dim_c, ext_c, text_c) = (in_color(style.dim_line_color), in_color(style.ext_line_color), in_color(style.text_color));
let line_entities = |i: usize, l: &[Vec2]| -> Vec<Entity> {
let c = match g.line_roles.get(i) {
Some(LineRole::Ext) => &ext_c,
_ => &dim_c,
};
l.windows(2)
.filter_map(|seg| match seg {
[a, b] => Some(Entity { handle: Handle(0), common: c.clone(), kind: EntityKind::Line(Line { a: a.to3(0.0), b: b.to3(0.0) }) }),
_ => None,
})
.collect()
};
// The text's marks (arc length symbol, DIMINSPECT frame) go after the text background.
for (i, l) in g.lines.iter().enumerate().filter(|(i, _)| !g.text_marks.contains(i)) {
out.extend(line_entities(i, l));
}
for t in &g.fills {
if let [a, b, cc] = t.as_slice() {
out.push(Entity {
handle: Handle(0),
common: dim_c.clone(),
kind: EntityKind::Solid(Solid { corners: [a.to3(0.0), b.to3(0.0), cc.to3(0.0), cc.to3(0.0)] }),
});
}
}
// DIMTFILL 2: the text background in DIMTFILLCLR, under the text and its marks (SOLID
// corners go 1, 2, 4, 3).
if style.text_fill == 2
&& let [p0, p1, p2, p3] = g.text_fill.as_slice()
{
out.push(Entity {
handle: Handle(0),
common: in_color(style.text_fill_color),
kind: EntityKind::Solid(Solid { corners: [p0.to3(0.0), p1.to3(0.0), p3.to3(0.0), p2.to3(0.0)] }),
});
}
for (i, l) in g.lines.iter().enumerate().filter(|(i, _)| g.text_marks.contains(i)) {
out.extend(line_entities(i, l));
}
// The text, and the part after `\X` below the dimension line as a second MTEXT, as AutoCAD
// writes it (#1055).
let texts = std::iter::once((g.value.clone(), g.text_pos)).chain(g.below.clone());
for (contents, at) in texts.filter(|(t, _)| !t.is_empty()) {
out.push(Entity {
handle: Handle(0),
common: text_c.clone(),
kind: EntityKind::MText(MText {
insert: at.to3(0.0),
height: g.text_height,
width: 0.0,
attach: 5,
rotation: g.text_angle,
style: style.text_style.clone(),
contents: DimGeometry::mtext_code(&contents),
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
background: None,
}),
});
}
out
}
+2 -2
View File
@@ -82,8 +82,8 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
};
match mode {
cadcraft_doc::AnnoDraw::Hidden => return,
cadcraft_doc::AnnoDraw::Scaled(f) => {
let mut scaled = cadcraft_doc::anno_scaled(e, f);
cadcraft_doc::AnnoDraw::Scaled { factor, by } => {
let mut scaled = cadcraft_doc::anno_placed(e, factor, by);
scaled.common.anno_scales.clear();
return entity_parts(b, ctx, &scaled);
}
+2
View File
@@ -590,6 +590,7 @@ pub use table::{
};
mod blocks;
mod dim_block;
mod dim_draw;
mod display;
mod draw;
@@ -598,6 +599,7 @@ mod props;
mod text_entity;
mod viewports;
pub use dim_block::dim_block_entities;
pub use dim_draw::{dim_text, dimension_in};
pub use display::{DImage, DPrim, DisplayList, Kind, MAX_TRANSPARENCY, NO_LAYER, PlotText, VIEWPORT_CONTENT, alpha};
pub use pipeline::{Options, build, build_entities, build_entities_in_viewport, build_plot};
+2 -2
View File
@@ -62,7 +62,7 @@ pub(super) fn draw_selection_grips(app: &mut CadApp, painter: &egui::Painter, xf
if let Some(e) = st.doc.entity(*h)
&& st.shows(e)
{
let grips = e.kind.grips();
let grips = cadcraft_engine::grips::shown_grips(&st.doc, e, st.anno_view());
let count = grips.len();
for (gi, g) in grips.into_iter().enumerate() {
let sp = xf.to_screen(g);
@@ -182,7 +182,7 @@ pub(super) fn grip_at(app: &CadApp, xf: &Xf, hover: Option<Pos2>) -> Option<(Han
if !st.shows(e) || st.doc.layer(&e.common.layer).is_some_and(|l| l.locked) {
continue;
}
let grips = e.kind.grips();
let grips = cadcraft_engine::grips::shown_grips(&st.doc, e, st.anno_view());
let count = grips.len();
for (i, g) in grips.into_iter().enumerate() {
let sp = xf.to_screen(g);
+15 -4
View File
@@ -44,13 +44,25 @@ const TOOLBAR: &[&[(Icon, &str, &str, Option<&str>)]] = &[
/// Height of the macOS integrated title row (#161): the standard 28 pt title-bar band AppKit centres the traffic
/// lights in.
const MAC_TITLE_BAR: f32 = 28.0;
/// Height of the framework's title bar where it carries the window buttons (GNOME on Wayland, [`crate::title_bar`]):
/// the framework theme's `size.bar.title`.
const INTEGRATED_TITLE_BAR: f32 = 38.0;
/// The width of the toolbar's More button.
const MORE_WIDTH: f32 = 30.0;
/// Title row (with the integrated macOS title bar) and the Tool Bar.
/// Title row (with the integrated macOS title bar, or the framework's title bar with the window buttons where the
/// desktop leaves the frame to the app) and the Tool Bar.
pub fn title_and_toolbar(app: &mut CadApp, ui: &mut egui::Ui) {
let t = Tokens::get();
let title_h = if app.integrated_titlebar { MAC_TITLE_BAR } else { 0.0 };
let mac = ui.ctx().os().is_mac();
// In full screen the framework's bar shows no window buttons, so the row goes too; the macOS row is unchanged.
let fullscreen = ui.ctx().input(|i| i.viewport().fullscreen.unwrap_or(false));
let title_h = match (app.integrated_titlebar, mac) {
(false, _) => 0.0,
(true, true) => MAC_TITLE_BAR,
(true, false) if fullscreen => 0.0,
(true, false) => INTEGRATED_TITLE_BAR,
};
let tb_h = if app.ui.show_toolbar { 34.0 } else { 0.0 };
egui::Panel::top("cc_title_toolbar").exact_size(title_h + tb_h).frame(egui::Frame::NONE.fill(t.chrome)).show(ui, |ui| {
let r = ui.max_rect();
@@ -70,10 +82,9 @@ pub fn title_and_toolbar(app: &mut CadApp, ui: &mut egui::Ui) {
}
if tb_h > 0.0 {
let row = Rect::from_min_size(pos2(r.left(), r.top() + title_h), vec2(r.width(), tb_h));
let mut x = r.left() + if app.integrated_titlebar { 120.0 } else { 12.0 };
let mut x = r.left() + if app.integrated_titlebar && mac { 120.0 } else { 12.0 };
let size = 26.0;
let mut clicked = None;
let mac = ui.ctx().os().is_mac();
let widths: Vec<_> = TOOLBAR.iter().map(|group| group.len() as f32 * (size + 6.0) - 6.0).collect();
let available = (row.right() - 12.0 - x).max(0.0);
let items: Vec<_> = widths.iter().enumerate().map(|(i, w)| FitItem::new(*w, i as u16, FitKeep::Free)).collect();
+2
View File
@@ -1504,6 +1504,8 @@ menu View عرض
This library has no drawings or blocks. لا تحتوي هذه المكتبة على رسومات أو كتل.
Only the first {n} are shown. يتم عرض أول {n} فقط.
The drawing changed. Close the window and open it again. تغيّر الرسم. أغلق النافذة وافتحها مرة أخرى.
Use system title bar استخدام شريط عنوان النظام
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. يعرض شريط عنوان بسيطاً لأزرار النافذة فوق شريط CADCraft نفسه. لا يرسم GNOME أشرطة العناوين للتطبيقات، لذا لا يتبع هذا الشريط سمته.
# ArtCraft feature naming
Additional Tools أدوات إضافية
Can't render this file because it contains an unexpected character in line 1336 and column 24.
+2
View File
@@ -1486,6 +1486,8 @@ menu Modify Izmijeni
Ctrl+Enter to apply Ctrl+Enter to apply
Edit Text Edit Text
The drawing changed. Close the window and open it again. Crtež se promijenio. Zatvorite prozor i otvorite ga ponovo.
Use system title bar Koristi sistemsku naslovnu traku
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Prikaži osnovnu naslovnu traku za dugmad prozora iznad CADCraftove vlastite. GNOME ne crta naslovne trake za aplikacije, pa ova ne prati njegovu temu.
# ArtCraft feature naming
Additional Tools Dodatni alati
Can't render this file because it contains an unexpected character in line 1444 and column 24.
+2
View File
@@ -1471,6 +1471,8 @@ menu Modify Modifikace
This drawing has no blocks. Tento výkres neobsahuje žádné bloky.
This library has no drawings or blocks. Tato knihovna neobsahuje žádné výkresy ani bloky.
Only the first {n} are shown. Zobrazuje se pouze prvních {n}.
Use system title bar Použít systémové záhlaví okna
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Zobrazí nad záhlavím CADCraftu jednoduché záhlaví s tlačítky okna. GNOME aplikacím záhlaví nekreslí, takže toto nesleduje jeho motiv.
# ArtCraft feature naming
Additional Tools Další nástroje
Can't render this file because it contains an unexpected character in line 1407 and column 24.
+2
View File
@@ -1085,6 +1085,8 @@
Ctrl+Enter to apply Ctrl+Enter to apply
Edit Text Edit Text
The drawing changed. Close the window and open it again. Die Zeichnung hat sich geändert. Schließen Sie das Fenster und öffnen Sie es erneut.
Use system title bar System-Titelleiste verwenden
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Eine einfache Titelleiste für die Fensterknöpfe über der von CADCraft anzeigen. GNOME zeichnet für Apps keine Titelleisten, daher folgt diese nicht seinem Design.
# ArtCraft feature naming
Additional Tools Zusätzliche Werkzeuge
1 # CADCraft German interface catalog — original translations by the CADCraft contributors.
1085
1086
1087
1088
1089
1090 # ArtCraft feature naming
1091
1092
+2
View File
@@ -1423,6 +1423,8 @@ menu View Προβολή
Ctrl+Enter to apply Ctrl+Enter to apply
Edit Text Edit Text
The drawing changed. Close the window and open it again. Το σχέδιο άλλαξε. Κλείστε το παράθυρο και ανοίξτε το ξανά.
Use system title bar Χρήση της γραμμής τίτλου του συστήματος
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Εμφανίζει μια απλή γραμμή τίτλου με τα κουμπιά του παραθύρου πάνω από τη γραμμή του CADCraft. Το GNOME δεν σχεδιάζει γραμμές τίτλου για τις εφαρμογές, οπότε αυτή δεν ακολουθεί το θέμα του.
# ArtCraft feature naming
Additional Tools Πρόσθετα εργαλεία
Can't render this file because it contains an unexpected character in line 234 and column 24.
+2
View File
@@ -1303,6 +1303,8 @@
Ctrl+Enter to apply Ctrl+Enter to apply
Edit Text Edit Text
The drawing changed. Close the window and open it again. El dibujo cambió. Cierre la ventana y ábrala de nuevo.
Use system title bar Usar la barra de título del sistema
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Muestra una barra de título básica con los botones de la ventana encima de la de CADCraft. GNOME no dibuja barras de título para las aplicaciones, así que esta no sigue su tema.
# ArtCraft feature naming
Additional Tools Herramientas adicionales
1 # CADCraft Spanish interface catalog — original translations.
1303
1304
1305
1306
1307
1308 # ArtCraft feature naming
1309
1310
+2
View File
@@ -1065,6 +1065,8 @@
Press the keys Appuyez sur les touches
Back to CADCraft's shortcut Revenir au raccourci de CADCraft
A shortcut you give wins over CADCraft's own. Changes apply at once and are kept for next time. Un raccourci que vous définissez l'emporte sur celui de CADCraft. Les modifications s'appliquent tout de suite et sont conservées.
Use system title bar Utiliser la barre de titre du système
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Affiche une barre de titre simple avec les boutons de la fenêtre au-dessus de celle de CADCraft. GNOME ne dessine pas de barre de titre pour les applications, celle-ci ne suit donc pas son thème.
# ArtCraft feature naming
Additional Tools Outils supplémentaires
1 # CADCraft French interface catalog — original translations by @pechnikov2026-star; terminology review by @YannFR81.
1065
1066
1067
1068
1069
1070 # ArtCraft feature naming
1071
1072
+2
View File
@@ -1388,6 +1388,8 @@ menu View Nézet
Ctrl+Enter to apply Ctrl+Enter to apply
Edit Text Edit Text
The drawing changed. Close the window and open it again. A rajz megváltozott. Zárja be az ablakot, és nyissa meg újra.
Use system title bar A rendszer címsorának használata
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Egyszerű címsort jelenít meg az ablak gombjaival a CADCraft saját címsora fölött. A GNOME nem rajzol címsort az alkalmazásoknak, ezért ez nem követi a témáját.
# ArtCraft feature naming
Additional Tools További eszközök
Can't render this file because it contains an unexpected character in line 16 and column 72.
+2
View File
@@ -1434,6 +1434,8 @@ menu Modify Edita
ENTER INVIO
Shortcut Menu: always enabled Menu di scelta rapida: sempre attivo
Shortcut Menu: enabled when command options are present Menu di scelta rapida: attivo se il comando ha opzioni
Use system title bar Usa la barra del titolo di sistema
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Mostra una semplice barra del titolo con i pulsanti della finestra sopra quella di CADCraft. GNOME non disegna barre del titolo per le app, quindi questa non segue il suo tema.
Check for updates when CADCraft starts Controlla gli aggiornamenti all'avvio di CADCraft
Turned off, CADCraft never offers an update on its own; Help ▸ Check for Updates… still looks. Se disattivato, CADCraft non propone mai un aggiornamento da solo; Aiuto ▸ Verifica aggiornamenti… continua a controllare.
1 # CADCraft Italian interface catalog — original translations by Emanuele Bottelli (AI-assisted, Claude).
1434
1435
1436
1437
1438
1439
1440
1441 # ArtCraft feature naming
+2
View File
@@ -1519,6 +1519,8 @@ menu View ხედი
This drawing has no blocks. ამ ნახაზში ბლოკები არ არის.
This library has no drawings or blocks. ამ ბიბლიოთეკაში ნახაზები ან ბლოკები არ არის.
Only the first {n} are shown. ნაჩვენებია მხოლოდ პირველი {n}.
Use system title bar სისტემის სათაურის ზოლის გამოყენება
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. ფანჯრის ღილაკებისთვის მარტივი სათაურის ზოლის ჩვენება CADCraft-ის საკუთარი ზოლის ზემოთ. GNOME აპებისთვის სათაურის ზოლებს არ ხატავს, ამიტომ ეს ზოლი მის თემას არ მიჰყვება.
# ArtCraft feature naming
Additional Tools დამატებითი ხელსაწყოები
Can't render this file because it contains an unexpected character in line 10 and column 14.
+2
View File
@@ -1287,6 +1287,8 @@ menu Modify 수정
Ctrl+Enter to apply Ctrl+Enter to apply
Edit Text Edit Text
The drawing changed. Close the window and open it again. 도면이 변경되었습니다. 창을 닫고 다시 여십시오.
Use system title bar 시스템 제목 표시줄 사용
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. CADCraft의 제목 표시줄 위에 창 단추가 있는 기본 제목 표시줄을 표시합니다. GNOME은 앱의 제목 표시줄을 그리지 않으므로 이 표시줄은 테마를 따르지 않습니다.
# ArtCraft feature naming
Additional Tools 추가 도구
1 # CADCraft Korean interface catalog — original Korean translations.
1287
1288
1289
1290
1291
1292 # ArtCraft feature naming
1293
1294
+2
View File
@@ -2170,6 +2170,8 @@ menu Dimension Wymiarowanie
The current file doesn't look whole, so {name} stays as it is and the current file will be replaced. Bieżący plik wygląda na niekompletny, więc {name} pozostanie bez zmian, a bieżący plik zostanie zastąpiony.
The current file is kept as {name} until the next save. Bieżący plik zostanie zachowany jako {name} do następnego zapisu.
The drawing changed. Close the window and open it again. Rysunek został zmieniony. Zamknij okno i otwórz je ponownie.
Use system title bar Użyj systemowego paska tytułu
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Pokaż prosty pasek tytułu z przyciskami okna nad własnym paskiem CADCraft. GNOME nie rysuje pasków tytułu dla aplikacji, więc ten nie korzysta z jego motywu.
This format can't keep these objects yet: {objects}. Ten format nie potrafi jeszcze zachować tych obiektów: {objects}.
Turn on time-sensitive right-click Włącz obsługę prawego przycisku zależną od czasu
Turned off, a right-click while a command runs does what Right-Click Customization sets for Command mode. Po wyłączeniu tej opcji prawy przycisk podczas polecenia działa zgodnie z ustawieniami trybu polecenia w oknie Dostosowanie prawego przycisku myszy.
Can't render this file because it contains an unexpected character in line 832 and column 20.
+2
View File
@@ -1493,6 +1493,8 @@ menu View Exibir
Ctrl+Enter to apply Ctrl+Enter to apply
Edit Text Edit Text
The drawing changed. Close the window and open it again. O desenho mudou. Feche a janela e abra-a novamente.
Use system title bar Usar a barra de título do sistema
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Mostra uma barra de título simples com os botões da janela acima da do CADCraft. O GNOME não desenha barras de título para os aplicativos, então esta não segue o tema dele.
# ArtCraft feature naming
Additional Tools Ferramentas adicionais
Can't render this file because it contains an unexpected character in line 1441 and column 24.
+2
View File
@@ -1060,6 +1060,8 @@
Ctrl+Enter to apply Ctrl+Enter to apply
Edit Text Edit Text
The drawing changed. Close the window and open it again. Чертёж изменился. Закройте окно и откройте его снова.
Use system title bar Использовать системный заголовок окна
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Показывает простой заголовок окна с кнопками над заголовком CADCraft. GNOME не рисует заголовки для приложений, поэтому этот не следует его теме.
# ArtCraft feature naming
Additional Tools Дополнительные инструменты
1 # CADCraft Russian interface catalog — original translations by @pechnikov2026-star.
1060
1061
1062
1063
1064
1065 # ArtCraft feature naming
1066
1067
+2
View File
@@ -1511,6 +1511,8 @@ menu Modify Ändra
Ctrl+Enter to apply Ctrl+Enter to apply
Edit Text Edit Text
The drawing changed. Close the window and open it again. Ritningen har ändrats. Stäng fönstret och öppna det igen.
Use system title bar Använd systemets namnlist
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Visar en enkel namnlist med fönsterknapparna ovanför CADCrafts egen. GNOME ritar inga namnlister åt appar, så den här följer inte dess tema.
DView DView
Keyboard Shortcuts... Kortkommandon...
Multiple Insert Infoga flera
Can't render this file because it contains an unexpected character in line 1500 and column 24.
+2
View File
@@ -1391,6 +1391,8 @@ menu View Görünüm
Ctrl+Enter to apply Ctrl+Enter to apply
Edit Text Edit Text
The drawing changed. Close the window and open it again. Çizim değişti. Pencereyi kapatıp yeniden açın.
Use system title bar Sistem başlık çubuğunu kullan
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. CADCraft'ın başlık çubuğunun üstünde pencere düğmelerini içeren basit bir başlık çubuğu gösterir. GNOME uygulamalar için başlık çubuğu çizmediğinden bu çubuk onun temasına uymaz.
# ArtCraft feature naming
Additional Tools Ek Araçlar
Can't render this file because it contains an unexpected character in line 11 and column 13.
+2
View File
@@ -1468,6 +1468,8 @@
ENTER Клавіша Enter
Shortcut Menu: always enabled Контекстне меню: завжди
Shortcut Menu: enabled when command options are present Контекстне меню: коли команда має параметри
Use system title bar Використовувати системний заголовок вікна
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Показує простий заголовок вікна з кнопками над заголовком CADCraft. GNOME не малює заголовки для застосунків, тому цей не відповідає його темі.
Check for updates when CADCraft starts Перевіряти оновлення під час запуску CADCraft
Turned off, CADCraft never offers an update on its own; Help ▸ Check for Updates… still looks. Якщо вимкнено, CADCraft ніколи сам не пропонує оновлення; Довідка ▸ Перевірити оновлення… усе одно перевіряє.
Can't render this file because it contains an unexpected character in line 1404 and column 24.
+2
View File
@@ -1492,6 +1492,8 @@ menu Modify Hiệu chỉnh
Ctrl+Enter to apply Ctrl+Enter để áp dụng
Edit Text Sửa chữ
The drawing changed. Close the window and open it again. Bản vẽ đã thay đổi. Đóng cửa sổ và mở lại.
Use system title bar Dùng thanh tiêu đề của hệ thống
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Hiện một thanh tiêu đề đơn giản cho các nút cửa sổ phía trên thanh của CADCraft. GNOME không vẽ thanh tiêu đề cho ứng dụng, nên thanh này không theo chủ đề của nó.
# Phase 1 of craft-i18n#401: the strings the translation_gaps report listed as missing for vi.
# Dimension Style Manager (DIMSTYLE)
<style overrides> <ghi đè kiểu>
Can't render this file because it contains an unexpected character in line 1445 and column 24.
+2
View File
@@ -1530,6 +1530,8 @@ menu View 视图
Ctrl+Enter to apply Ctrl+Enter 应用
Edit Text 编辑文字
The drawing changed. Close the window and open it again. 图纸已切换。请关闭窗口后重新打开。
Use system title bar 使用系统标题栏
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. 在 CADCraft 自己的标题栏上方显示带窗口按钮的基本标题栏。GNOME 不为应用绘制标题栏,因此此标题栏不跟随其主题。
# ArtCraft feature naming
Additional Tools 其他工具
Can't render this file because it contains an unexpected character in line 1486 and column 24.
+13
View File
@@ -74,11 +74,13 @@ pub mod quick;
pub mod save_loss;
pub mod shortcut_menus;
pub mod theme;
pub mod title_bar;
#[cfg(not(target_arch = "wasm32"))]
pub mod updates_ui;
pub mod viewcube;
pub mod vpscale;
pub mod wblock;
mod window_edges;
pub mod exchange;
mod file_provider_app;
@@ -150,6 +152,10 @@ pub struct UiState {
pub last_lisp_dir: Option<String>,
/// The folder the Command Aliases dialog last imported a `.pgp` file from.
pub last_pgp_dir: Option<String>,
/// Options ▸ Display ▸ Use system title bar: where the desktop leaves the window frame to the app (GNOME on
/// Wayland), keep the desktop's frame instead of the framework's title bar ([`title_bar`]). Kept in the desktop
/// workspace file, which is read before the window opens.
pub system_title_bar: bool,
}
/// A DXF/DWG file version (2000 … 2018).
@@ -230,6 +236,7 @@ impl Default for UiState {
hatch_patterns: Default::default(),
last_lisp_dir: None,
last_pgp_dir: None,
system_title_bar: false,
}
}
}
@@ -323,6 +330,8 @@ pub struct CadApp {
/// Drawings being read on worker threads ([`opening`]).
pub opening: opening::Opening,
pub integrated_titlebar: bool,
/// Both frames of Use system title bar, where it applies ([`title_bar::TitleBar`]).
title_bar: Option<title_bar::TitleBar>,
control_rx: Option<Receiver<ControlRequest>>,
/// Fresh surface and identity snapshot (see [`capture`]).
pub(crate) capture_geometry: Option<capture::CaptureGeometry>,
@@ -439,6 +448,7 @@ impl CadApp {
status: None,
opening: opening::Opening::default(),
integrated_titlebar: false,
title_bar: None,
control_rx: None,
capture_geometry: None,
capture_epoch: 0,
@@ -1293,6 +1303,7 @@ impl CadApp {
self.sync_bars();
control::begin_frame(ui.ctx());
let t = theme::Tokens::get();
self.follow_title_bar(ui.ctx());
chrome::title_and_toolbar(self, ui);
if self.ui.in_window_menu {
menus::menu_bar(self, ui);
@@ -1326,6 +1337,8 @@ impl CadApp {
autosave::gpu_notice(self, ui.ctx());
autosave::failure_notice(self, ui.ctx());
self.run_framework_dialogs(ui);
// Last, so the edges' resize cursors win over the drawing area's.
window_edges::show(ui.ctx());
self.frame_ms = now_ms() - t0;
}
+7
View File
@@ -21,6 +21,7 @@
//! | `rightClickDefault`, `rightClickEdit` | with the time-sensitive right-click off, a right-click with no command running and nothing (`Default`) or something (`Edit`) selected: `"menu"` (the shortcut menu, default) or `"repeat"` (the last command) |
//! | `rightClickCommand` | a right-click while a command runs, with the time-sensitive right-click off: `"menu"` (default), `"enter"`, or `"menuWithOptions"` (the menu when the prompt has options, else Enter) |
//! | `systemCursor` | keep the system cursor visible over the drawing area |
//! | `systemTitleBar` | where the desktop leaves the window frame to the app (GNOME on Wayland), keep the desktop's frame instead of the framework's title bar with the window buttons |
//! | `historyLines` | command-line history lines, 0–12 |
//! | `modelBackground`, `paperBackground` | `"#rrggbb"`, or `null` for the default |
//! | `selectionColor` | the colour selected objects are highlighted in: `"#rrggbb"`, or `null` for the theme's |
@@ -230,6 +231,7 @@ struct UiChanges {
language: Option<crate::i18n::Preference>,
save_format: Option<crate::SaveFormat>,
system_cursor: Option<bool>,
system_title_bar: Option<bool>,
history_lines: Option<usize>,
model_background: Option<Option<Color32>>,
paper_background: Option<Option<Color32>>,
@@ -268,6 +270,7 @@ fn parse_ui(key: &str, v: &Value, c: &mut UiChanges) -> Result<bool, String> {
}
"saveFormat" => c.save_format = Some(crate::SaveFormat::parse(text()?).ok_or("saveFormat must be dxf or dwg")?),
"systemCursor" => c.system_cursor = Some(v.as_bool().ok_or("systemCursor must be true or false")?),
"systemTitleBar" => c.system_title_bar = Some(v.as_bool().ok_or("systemTitleBar must be true or false")?),
"historyLines" => {
let n = v.as_u64().filter(|n| *n <= crate::cmdline::MAX_LINES as u64).ok_or("historyLines must be a whole number from 0 to 12")?;
c.history_lines = Some(n as usize);
@@ -330,6 +333,7 @@ fn ui_json(app: &CadApp) -> Map<String, Value> {
m.insert("interfaceLanguage".into(), json!(app.ui.interface_language.code()));
m.insert("saveFormat".into(), json!(app.ui.save_format.as_str()));
m.insert("systemCursor".into(), json!(app.ui.system_cursor));
m.insert("systemTitleBar".into(), json!(app.ui.system_title_bar));
m.insert("historyLines".into(), json!(app.ui.history_lines));
m.insert("modelBackground".into(), color_json(o.model_background));
m.insert("paperBackground".into(), color_json(o.paper_background));
@@ -389,6 +393,9 @@ fn run_json(app: &mut CadApp, params: &Value) -> Result<Value, String> {
if let Some(b) = ui.system_cursor {
app.ui.system_cursor = b;
}
if let Some(b) = ui.system_title_bar {
app.ui.system_title_bar = b;
}
if let Some(n) = ui.history_lines {
app.ui.history_lines = n;
}
+15
View File
@@ -212,6 +212,21 @@ fn display(app: &CadApp, ui: &mut egui::Ui, changes: &mut Map<String, Value>) {
changes.insert("systemCursor".into(), json!(system_cursor));
}
hint(ui, crate::tl!("Screen magnifiers, screen readers and recorders follow the system cursor."));
// Only where the framework's title bar carries the window buttons (GNOME on Wayland); elsewhere
// the desktop draws the frame. `CADCRAFT_TITLEBAR` overrides the setting, so it isn't offered then.
if app.system_title_bar_applies() {
ui.add_space(6.0);
let mut system = app.ui.system_title_bar;
if ui.checkbox(&mut system, crate::tl!("Use system title bar")).changed() {
changes.insert("systemTitleBar".into(), json!(system));
}
hint(
ui,
crate::tl!(
"Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme."
),
);
}
}
/// Files tab: save format and default version, new-drawing units, autosave interval and autosave file location; edits accumulate in `changes`.
+1 -1
View File
@@ -1,4 +1,4 @@
//! Boolean environment switches (`CADCRAFT_VSYNC`, `CADCRAFT_WAYLAND`, ...): one parser, so every
//! Boolean environment switches (`CADCRAFT_VSYNC`, `CADCRAFT_X11`, ...): one parser, so every
//! variable accepts the same spellings.
/// `1/on/true/yes` or `0/off/false/no`, case- and space-insensitive. Blank or unset is `Default`;
+122
View File
@@ -0,0 +1,122 @@
//! Options ▸ Display ▸ Use system title bar: where the desktop leaves the window frame to the app (GNOME on
//! Wayland), the framework's title bar carries the window buttons, in the order of GNOME's `button-layout`; the
//! setting gives the window the desktop's frame instead, at once. craft-window decides the frame
//! (`policy::decide_for`), as on macOS ([`crate::framework::frame_decision`]).
use craft_host::target::Backend;
use craft_ui::runtime::windows::WindowHost;
use craft_window::policy::{self, Decision, TitleBarPref};
use crate::CadApp;
/// The window's frame for each value of Use system title bar, both decided at start-up from the desktop as it was
/// then, so the app's buttons come back in the desktop's `button-layout` order.
#[derive(Clone, Debug, PartialEq)]
pub struct TitleBar {
/// The frame with the setting off: the app's buttons.
app: Decision,
/// The frame with the setting on: the desktop's.
system: Decision,
/// The setting the window's frame follows now.
applied: bool,
}
impl TitleBar {
/// The frames for both values of the setting, or `None` to leave the frame to the desktop, as before. Only where
/// the desktop draws no frame (a Wayland compositor without server-side decorations: GNOME) or
/// `CADCRAFT_TITLEBAR` asks: the policy would also draw the app's buttons on desktops that frame their windows
/// (Windows, KDE), which is a decision for the whole suite rather than this setting.
#[must_use]
pub fn new(app: Decision, system: Decision, system_title_bar: bool) -> Option<Self> {
let leaves_frame_to_app = app.desktop.ssd == Some(false);
(leaves_frame_to_app || app.overridden.is_some()).then_some(Self { app, system, applied: system_title_bar })
}
/// The frame the window opens with.
#[must_use]
pub fn decision(&self) -> &Decision {
if self.applied { &self.system } else { &self.app }
}
/// `Some(true)` when `CADCRAFT_TITLEBAR` forced the app's buttons, `Some(false)` the desktop's frame; the setting
/// then changes nothing.
fn forced(&self) -> Option<bool> {
self.app.overridden
}
}
/// [`TitleBar::new`] for this desktop; `forced_x11` when the app opens its window through XWayland.
#[must_use]
pub fn decide(forced_x11: bool, system_title_bar: bool) -> Option<TitleBar> {
let backend = if forced_x11 { Backend::X11 } else { Backend::from_env() };
let decide = |pref| policy::decide_for(craft_window::Prefix::new("CADCRAFT"), backend, pref);
TitleBar::new(decide(TitleBarPref::Integrated), decide(TitleBarPref::System), system_title_bar)
}
impl CadApp {
/// The window opened with `title_bar`'s frame ([`decide`]): Use system title bar now changes it, and the title
/// row follows it.
pub fn set_title_bar(&mut self, title_bar: TitleBar) {
self.integrated_titlebar = crate::framework::draws_title_row(Some(title_bar.decision()));
self.title_bar = Some(title_bar);
}
/// Whether Use system title bar changes anything here: the framework decides the frame and `CADCRAFT_TITLEBAR`
/// doesn't.
pub(crate) fn system_title_bar_applies(&self) -> bool {
self.title_bar.as_ref().is_some_and(|t| t.forced().is_none())
}
/// Follow Use system title bar at once, before the title row is drawn: the window gets the setting's frame, and
/// the title row shows or goes with the window buttons.
pub(crate) fn follow_title_bar(&mut self, ctx: &egui::Context) {
let system = self.ui.system_title_bar;
let Some(t) = self.title_bar.as_mut().filter(|t| t.forced().is_none() && t.applied != system) else { return };
t.applied = system;
let decision = t.decision().clone();
self.integrated_titlebar = crate::framework::draws_title_row(Some(&decision));
WindowHost::of(ctx).set_root_frame(decision);
}
}
#[cfg(test)]
mod tests {
use super::TitleBar;
use craft_host::target::Backend;
use craft_window::policy::{self, TitleBarPref};
/// Both frames as GNOME on Wayland gives them: no server-side decorations and no override.
fn gnome() -> (policy::Decision, policy::Decision) {
let decide = |pref| {
let mut d = policy::decide_for(craft_window::Prefix::new("CADCRAFT_TEST_UNSET"), Backend::Wayland, pref);
d.desktop.ssd = Some(false);
d.overridden = None;
d
};
(decide(TitleBarPref::Integrated), decide(TitleBarPref::System))
}
#[test]
fn only_where_the_desktop_leaves_the_frame_to_the_app() {
let (app, system) = gnome();
assert!(TitleBar::new(app.clone(), system.clone(), false).is_some(), "GNOME on Wayland");
let mut framed = app.clone();
framed.desktop.ssd = Some(true);
assert!(TitleBar::new(framed.clone(), system.clone(), false).is_none(), "KDE and Sway draw their own frames");
framed.overridden = Some(true);
assert!(TitleBar::new(framed, system, false).is_some(), "CADCRAFT_TITLEBAR=app asks anyway");
}
#[test]
fn the_setting_picks_the_frame_and_the_override_beats_it() {
let (app, system) = gnome();
let t = TitleBar::new(app.clone(), system.clone(), false).unwrap();
assert_eq!(t.decision(), &app);
assert_eq!(t.forced(), None);
let t = TitleBar::new(app.clone(), system.clone(), true).unwrap();
assert_eq!(t.decision(), &system, "Use system title bar on: the desktop's frame");
let mut forced = app;
forced.overridden = Some(true);
assert_eq!(TitleBar::new(forced, system, true).unwrap().forced(), Some(true));
}
}
+116
View File
@@ -0,0 +1,116 @@
//! Resize edges for the framework's integrated frame ([`crate::title_bar`]: GNOME on Wayland, where the desktop draws
//! no frame). The framework gives the window buttons and the move band, but only a window built from its own shell
//! gets its resize grips; CADCraft hosts its own egui UI, so thin zones along the window's edges start the desktop's
//! resize here. The resize goes through the framework (`WindowAction::StartResize`), which gives the button release
//! back after the desktop's grab.
use craft_ui::runtime::windows::{ResizeEdge, WindowAction, WindowHost};
use craft_window::policy::Frame;
use egui::{Color32, CursorIcon, Pos2, Rect, Sense, Stroke, Vec2, ViewportId};
/// How far into the window an edge resizes it.
const EDGE: f32 = 5.0;
/// How far along an edge a corner reaches, so corners are easy to hit.
const CORNER: f32 = 16.0;
/// The resize zones of a window filling `rect`: edges `edge` deep, and each corner an L of two strips reaching
/// `corner` along both edges (a square would reach into the content).
fn zones(rect: Rect, edge: f32, corner: f32) -> Vec<(ResizeEdge, Rect)> {
let (l, r, t, b) = (rect.left(), rect.right(), rect.top(), rect.bottom());
// Never inverted, however small the window.
let zone = |x0: f32, x1: f32, y0: f32, y1: f32| Rect::from_min_max(Pos2::new(x0, y0), Pos2::new(x1.max(x0), y1.max(y0)));
vec![
(ResizeEdge::TopLeft, zone(l, l + corner, t, t + edge)),
(ResizeEdge::TopLeft, zone(l, l + edge, t + edge, t + corner)),
(ResizeEdge::TopRight, zone(r - corner, r, t, t + edge)),
(ResizeEdge::TopRight, zone(r - edge, r, t + edge, t + corner)),
(ResizeEdge::BottomLeft, zone(l, l + corner, b - edge, b)),
(ResizeEdge::BottomLeft, zone(l, l + edge, b - corner, b - edge)),
(ResizeEdge::BottomRight, zone(r - corner, r, b - edge, b)),
(ResizeEdge::BottomRight, zone(r - edge, r, b - corner, b - edge)),
(ResizeEdge::Top, zone(l + corner, r - corner, t, t + edge)),
(ResizeEdge::Bottom, zone(l + corner, r - corner, b - edge, b)),
(ResizeEdge::Left, zone(l, l + edge, t + corner, b - corner)),
(ResizeEdge::Right, zone(r - edge, r, t + corner, b - corner)),
]
}
fn cursor(edge: ResizeEdge) -> CursorIcon {
match edge {
ResizeEdge::Top => CursorIcon::ResizeNorth,
ResizeEdge::Bottom => CursorIcon::ResizeSouth,
ResizeEdge::Right => CursorIcon::ResizeEast,
ResizeEdge::Left => CursorIcon::ResizeWest,
ResizeEdge::TopRight => CursorIcon::ResizeNorthEast,
ResizeEdge::BottomRight => CursorIcon::ResizeSouthEast,
ResizeEdge::TopLeft => CursorIcon::ResizeNorthWest,
ResizeEdge::BottomLeft => CursorIcon::ResizeSouthWest,
_ => CursorIcon::Default,
}
}
/// Resize zones along the root window's edges and a hairline border, while the framework's integrated frame is the
/// window's and the window is neither maximized nor full screen. The zones sit above everything else (in the
/// foreground order), so a press there resizes instead of reaching the panel or canvas under it.
pub(crate) fn show(ctx: &egui::Context) {
let host = WindowHost::of(ctx);
if !matches!(host.frame(), Frame::Integrated(_)) {
return;
}
let (maximized, fullscreen) = ctx.input(|i| (i.viewport().maximized.unwrap_or(false), i.viewport().fullscreen.unwrap_or(false)));
if maximized || fullscreen {
return;
}
let screen = ctx.content_rect();
let dark = crate::theme::active() == egui::Theme::Dark;
egui::Area::new(egui::Id::unique("cadcraft_window_edges")).order(egui::Order::Foreground).fixed_pos(screen.min).interactable(true).show(
ctx,
|ui| {
ui.set_min_size(Vec2::ZERO);
for (n, (edge, rect)) in zones(screen, EDGE, CORNER).into_iter().enumerate() {
if rect.width() <= 0.0 || rect.height() <= 0.0 {
continue;
}
let response = ui.interact(rect, ui.scope_id().with(("edge", n)), Sense::drag()).on_hover_cursor(cursor(edge));
// Sensing only drags, a drag starts on the press itself.
if response.drag_started() {
host.act(ViewportId::ROOT, WindowAction::StartResize(edge));
}
}
// Without the desktop's frame or shadow, a hairline keeps the window apart from what's behind it.
ui.painter().rect_stroke(screen, 0.0, Stroke::new(1.0, Color32::from_black_alpha(if dark { 160 } else { 60 })), egui::StrokeKind::Inside);
},
);
}
#[cfg(test)]
mod tests {
use super::{ResizeEdge, zones};
use egui::{Pos2, Rect};
#[test]
fn resize_zones_line_the_edges_without_overlapping() {
let window = Rect::from_min_size(Pos2::ZERO, egui::vec2(800.0, 600.0));
let zones = zones(window, 5.0, 16.0);
let at = |x: f32, y: f32| zones.iter().filter(|(_, r)| r.contains(Pos2::new(x, y))).map(|(e, _)| *e).collect::<Vec<_>>();
assert_eq!(at(1.0, 1.0), [ResizeEdge::TopLeft]);
assert_eq!(at(2.0, 12.0), [ResizeEdge::TopLeft]);
assert_eq!(at(400.0, 2.0), [ResizeEdge::Top]);
assert_eq!(at(799.0, 300.0), [ResizeEdge::Right]);
assert_eq!(at(400.0, 599.0), [ResizeEdge::Bottom]);
assert_eq!(at(1.0, 300.0), [ResizeEdge::Left]);
assert_eq!(at(799.0, 599.0), [ResizeEdge::BottomRight]);
assert!(at(400.0, 300.0).is_empty(), "the middle of the window is left alone");
assert!(at(12.0, 12.0).is_empty(), "corners stay along the edges");
// Strips meet without overlapping.
for y in [0.5, 4.5, 5.5, 15.5, 16.5, 595.5] {
for x in [0.5, 4.5, 5.5, 15.5, 16.5, 795.5, 799.5] {
assert!(at(x, y).len() <= 1, "({x}, {y}): {:?}", at(x, y));
}
}
// A window smaller than its corners gets empty (not inverted) edge zones.
for (_, r) in super::zones(Rect::from_min_size(Pos2::ZERO, egui::vec2(20.0, 20.0)), 5.0, 16.0) {
assert!(r.width() >= 0.0 && r.height() >= 0.0);
}
}
}
+5 -1
View File
@@ -24,7 +24,8 @@ description: |-
# The binaries link only glibc and libgcc_s directly. Windowing (X11/Wayland, xkbcommon) and the
# GPU (Vulkan, EGL/GL) are loaded at runtime, so they are dependencies/recommendations here
# rather than ELF NEEDED entries.
# rather than ELF NEEDED entries. On a Wayland desktop the app runs natively and needs X11 only
# with CADCRAFT_X11=1 (see main.rs), so the X11 libraries are recommendations.
overrides:
deb:
depends:
@@ -36,6 +37,7 @@ overrides:
- libwayland-client0
- libx11-6
- libx11-xcb1
- libxkbcommon-x11-0
- libxcursor1
- libxi6
- libxrandr2
@@ -48,6 +50,8 @@ overrides:
recommends:
- libwayland-client
- libX11
- libX11-xcb
- libxkbcommon-x11
- libXcursor
- libXi
- libXrandr