Compare commits

...
11 Commits
Author SHA1 Message Date
FredApps 1bdf4273f8 cadcraft-cli: --version and -V on every subcommand (RFC-0018 rule 1.1) (#3577) 2026-11-30 05:11:27 +01:00
FredAppsandFredApps c1af8dcf83 i18n: load the shared Construction Geometry label (#3414)
* Load Construction Geometry from the shared Chinese catalog

* Format the shared Chinese catalog validation

---------

Co-authored-by: FredApps <FredApps@users.noreply.github.com>
2026-11-30 05:10:56 +01:00
mattlafyandClaude Opus 5.5 4568970e50 Offset: OFFSETGAPTYPE extends, fillets or chamfers polyline corner gaps (#1506)
* feat(offset): OFFSETGAPTYPE extends, fillets or chamfers polyline corner gaps

OFFSETGAPTYPE is a system variable (0, 1 or 2, default 0) kept in the
drawing header. Offsetting a polyline fills the gap at the outside of a
corner between two line segments: 0 extends both copies to meet, 1 inserts
an arc of radius equal to the offset distance centred on the original
vertex, 2 inserts a chamfer line at the offset distance from the vertex.
Inside corners and joints with an arc keep the extended join. OFFSET's
settings echo shows the current value.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* OFFSETGAPTYPE fills only corners the source polyline has; geometry parity headline and history match

* test(offset): OFFSETGAPTYPE fillets and chamfers open outside corners turning either way

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(offset): interactive OFFSET previews and makes the OFFSETGAPTYPE fill

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Remove a leftover merge file

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* OFFSETGAPTYPE: leave docs/geometry-parity.md to the maintainers

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 03:44:41 +01:00
aldozarandClaude Opus 5.5 7f212ef9c7 Dimension text below the line (\X) and leader text at DIMSCALE (#1055, #1056) (#1084)
* Dimension text below the line (\X) and leader text at DIMSCALE (#1055, #1056)

- #1055: in dimension text, `\X` starts the text below the dimension
  line (DXF Reference). CADCraft drew only the part before it, and its
  *D block held only that part. The part after `\X` is now drawn below
  the line, on the other side of it at the same distance (text centred
  on the line moves above it), on screen, in plots and in the *D block
  as a second MTEXT; text width for the fit is the wider part's.
- #1056: LEADER's annotation was DIMTXT high whatever DIMSCALE said
  (0.25 instead of 6.25 beside dimensions at DIMSCALE 25). It is now
  DIMTXT × DIMSCALE (the style's, else the drawing's; 1 for annotative
  styles), in the style's text style, as AutoCAD's LEADER makes it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Dimension `\X`: measure from the dimension line, not DIMTMOVE 1's leader

The part after `\X` is placed from the dimension line's longest segment, and DIMTMOVE 1's leader
(added by #2015) is drawn as a dimension line too: with the text moved far away, the leader won
and the part below went next to the text. The leader's ends are now kept (`text_leader`) and its
segments skipped. Text moved off its place also leaves the part below at the usual clearance
under the line, instead of as far below as the text is above.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* LEADER text of an annotative dimension style: DIMSCALE, and annotative

With an annotative dimension style the leader's text left DIMSCALE out and was not annotative,
so at an annotation scale it stayed small beside the dimensions. It now takes DIMTXT × DIMSCALE
as a dimension of the style does, and is annotative at the current annotation scale.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* LEADER text of an annotative style: the annotation scale replaces DIMSCALE

An annotative dimension takes the annotation scale in DIMSCALE's place (anno_scaled sets its
scale override), so its text is DIMTXT × the annotation scale. The annotative leader text took
DIMTXT × DIMSCALE and then the annotation scale again: twice the dimension text with DIMSCALE 2.
It is now DIMTXT high and annotative; a non-annotative style still takes DIMTXT × DIMSCALE.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* DIMTMOVE 1 leader is kept as the text leader again

The merge of main moved the leader into dim/linear.rs without the text_leader record, so the
text below the line was placed over the leader.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Keep `\X` text below a suppressed or extension-line dimension line

With DIMSD1 and DIMSD2 both on, no dimension line segment is drawn, so
the part after `\X` was dropped. The linear dimension now records its
whole dimension line (`dim_axis`) and the `\X` layout falls back to it.

With DIMJUST 3 or 4 the text runs along an extension line, so its normal
is across the dimension line's: the text no longer moves onto the
dimension line at the arrow, and the part below stacks under it in the
text's own frame.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 03:44:21 +01:00
aldozarandClaude Opus 5.5 9907d9272b FILLET/CHAMFER with polylines: picked side, two polylines, middle segments, closed polylines, arc segments (#1223)
* FILLET/CHAMFER with polylines keep the picked side and join two polylines

A line crossing an open polyline's end segment cut the polyline on the
wrong side when the pick was past the crossing: the polyline always kept
the part towards its other end. Each object now keeps the side it was
picked on and drops what lies past the corner, as AutoCAD does.

Two open polylines picked at their end segments were refused. They now
join into one polyline through the corner (the first one picked keeps
its handle and direction), as AutoCAD does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* FILLET/CHAMFER: a line or polyline joins any straight segment of an open polyline

AutoCAD accepts a middle segment too: an open polyline's end segment
crossing another's middle segment joins them, each keeping its picked
side and dropping what lies past the crossing. Closed polylines and arc
segments are still refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* FILLET with polylines: a closed polyline opens to join a line; an arc segment is cut where a line crosses it

Checked against AutoCAD with the same shapes:

- A closed polyline filleted with a line opens at its first vertex: the
  picked side of the picked segment joins the line, either side, and the
  result is an open polyline. CADCraft refused closed polylines.
- An arc segment crossed by a line (radius 0) is cut where they cross,
  keeping its picked side, with the bulge of what is left of it. A line
  that misses the arc, or a radius, stays refused, as in AutoCAD.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* FILLET: a pick just before a polyline arc's start keeps the start side

Where the pick lies along an arc segment was clamped to the arc's end, so a pick a little before
its start (within the pick box) kept the end side. It now counts at the nearer end.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 03:43:37 +01:00
aldozarandClaude Opus 5.5 98e5c2b08f Drawing locks and WHOHAS: say when a drawing is open elsewhere (part of #540) (#1018)
* Drawing locks and WHOHAS: say when a drawing is open elsewhere (part of #540)

While a drawing opened from a DWG/DXF/DWT file is open, the app keeps
`.<file name>.cadcraft-lock` beside it (user, computer, app instance,
when opened), touched every minute; a lock not touched for five minutes
is stale. Opening a drawing someone else has open says who and since
when, on the command line and in the status bar, and opens it anyway:
the lock only informs. A lock is released when its drawing closes or is
saved under another name and when the app exits, only ever by the
instance that holds it; a stale one is taken over, and an app that finds
its lock taken over notes it instead of touching it. WHOHAS reports the
holder of the current drawing or of a file. The locks run with the
autosave tick; the format is CADCraft's own, not AutoCAD's .dwl.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Drawing lock: claim a free lock atomically

Two apps opening a drawing with no lock at the same moment could both write it and both think
they held it, so neither told its user until a later heartbeat. A missing lock is now created
atomically (a hard link of the staged file, or create_new without hard links), and a stale one
is replaced only if no other app has taken it meanwhile, then read back. The app that loses is
told at once who has the drawing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WHOHAS: a `path` that isn't text is an error

A `path` of another type (`{"path": 7}`) was taken as left out, so WHOHAS answered for the
current drawing. Left out or null still means the current drawing; anything but a string is now
refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Drawing locks: name the imports of the native module

The workspace now denies clippy's wildcard_imports, which `use super::*`
in drawlock's native module trips after the merge of main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Autosave: wake up for the drawing-lock heartbeat, not only for autosaves

Autosaver::tick kept the drawing locks but returned only the next autosave,
None with every drawing saved or SAVETIME 0, and the UI only schedules a
repaint on Some. An idle app then never touched its locks: after STALE_SECS
another app took the drawing over without a word. Locks::next_beat gives
the shortest wait until a held lock (or someone else's) is due again, and
tick returns the sooner of that and the next autosave.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WHOHAS: an error on the web, not "nobody has it open"

The web has no lock files, so the lookup isn't done there; reporting no
holder presented that as a negative result.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fix the wasm build after the merge

The merge dropped the native-only cfg from main's autosave lock field, and
two drawlock items used only by native code warned on wasm.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 03:41:02 +01:00
midasdfandmidasdf 758dc4e805 Plot: JIS B4/B5/B6 and Japanese paper sizes (はがき・封筒・四六判) (#1810)
* Plot: JIS B4/B5/B6 and Japanese paper sizes

Japanese drafting uses the JIS B series: B4 257×364 mm, B5 182×257 mm and
B6 128×182 mm. The paper table only had the ISO sizes, so a JIS B5 drawing
plotted about 7 mm short in each direction. B4/B5/B6 are now the JIS sizes (the
names Japanese Excel and drawings use) and the ISO ones stay reachable as
`B4 (ISO)`/`B5 (ISO)`; a drawing that stored the ISO sheet keeps its stored
size, and a caller that means ISO B5 says so.

Adds the Japanese papers the table lacked: Japanese Postcard (はがき,
100×148 mm), Japanese Double Postcard (往復はがき, 148×200 mm), Japanese
Envelope #3 (長形3号, 120×235 mm), Japanese Envelope Kaku #2 (角形2号,
240×332 mm) and 四六判 (127×188 mm). A6 was already an ISO sheet.

Paper names resolve case-insensitively and ignore spaces, hyphens, underscores
and parentheses (`B5 (JIS)`, `b5-jis`, `b5jis`), with the Japanese spellings as
aliases too (`はがき`, `往復はがき`, `長形3号`, `角形2号`, `四六判`). The
built-in plotters and the Page Setup/Plot paper combo pick the new sizes up
from PAPER_SIZES, and the PDF plot's MediaBox and the plot preview use them.

Tests: the render paper test pins every new size and alias, the ISO sizes keep
their values and the unknown-name fallback is unchanged; a new io test pins the
PDF MediaBox for each new paper (JIS B5 515.91×728.50 pt, はがき 283.46×419.53 pt,
ISO B4/B5 and the rest), and the plot-preview test checks that `B5` resolves to
JIS B5 and `B5 (ISO)` to ISO B5.

Docs: docs/plotters.md standard sizes and the `pagesetup`/PDFBOOK parameter
notes, and ROADMAP.md progress log + revision history, dated 2026-10-21.

* Plot: B4/B5/B6 stay ISO; JIS sizes by explicit name

Review follow-up: making the bare names mean JIS changed the ISO sizes for
every user. `B4`/`B5` are the ISO sizes again, an ISO B6 row (125×176 mm)
completes the bare series, and the JIS sheets (JIS P 0138, 257×364,
182×257 and 128×182 mm) are reachable only as `B4 (JIS)`/`JIS B4`,
`B5 (JIS)`/`JIS B5` and `B6 (JIS)`/`JIS B6`.

Drop the ambiguous bare `Postcard` and `Double Postcard` aliases; the name
and はがき/往復はがき say which postcard is meant. Drop the ROADMAP.md edit
(ROADMAP.md stays at origin/main's content).

The render and io paper tests, the plot-preview test and docs/plotters.md
follow the new mapping; the Japanese stationery sizes and their はがき/
往復はがき/長形3号/角形2号/四六判 spellings are unchanged.

Still safe for stored papers: a page setup keeps the canonical paper name
with its width/height, DXF groups 44/45 round-trip those sizes, and the ISO
canonical names (and the JIS rows by name) did not change.

* Plot: full-width paper names resolve like their ASCII forms

A Japanese keyboard or IME gives B5 (JIS); fold U+FF01..U+FF5E to ASCII (and the
ideographic space to a space) before the existing normalisation, with a test.

---------

Co-authored-by: midasdf <midasdf@tutamail.com>
2026-11-30 03:40:20 +01:00
Dylan M. Taylor cb12bc7984 ci(nightly): enable automated 00:30 UTC schedule and Stage 2 signer dispatch (#3616) 2026-11-29 16:16:22 -05:00
Dylan M. Taylor c1669adaed ci(sonarcloud): give each main commit its own concurrency group (#3655) 2026-11-29 15:54:17 -05:00
Dylan M. Taylor b7079ece62 test(nightly): preserve saved state and refuse invalid profile startup (#3653) 2026-11-29 15:22:26 -05:00
Dylan M. Taylor 5a06e105d6 feat(nightly): adopt craft-nightly for direct-launch self-isolation (#3644)
* feat(nightly): wire craft-nightly for direct-launch self-isolation

* fix(nightly): bump craft-nightly for single-instance sockets and add Windows regression test
2026-11-29 14:40:43 -05:00
52 changed files with 2118 additions and 962 deletions
+3 -1
View File
@@ -83,7 +83,9 @@
}
},
"max_artifact_bytes": 2147483648,
"automatic_signer_actors": [],
"automatic_signer_actors": [
"github-actions[bot]"
],
"platforms": {
"windows-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
+72
View File
@@ -0,0 +1,72 @@
name: Dispatch release-ref nightly
# Transport only, never authorization. No checkout, payload parsing or release environment.
on:
workflow_run:
workflows: [CADCraft unsigned nightly]
types: [completed]
branches: [main]
permissions: {}
jobs:
dispatch:
# Actual context guards: official repository and completed workflow_run only.
if: >-
github.repository == 'storytold/cadcraft' &&
github.event_name == 'workflow_run'
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
actions: write
steps:
- name: Dispatch only the exact completed producer run and attempt
shell: python
env:
GH_TOKEN: ${{ github.token }}
run: |
import json
import os
import urllib.request
def require(value, message):
if not value:
raise RuntimeError(message)
# These filters reduce noise; the protected signer-branch validator repeats admission
# against authenticated API metadata and required attestation/quality evidence.
require(os.environ.get('GITHUB_REPOSITORY') == 'storytold/cadcraft', 'wrong repository')
require(os.environ.get('GITHUB_EVENT_NAME') == 'workflow_run', 'wrong event')
with open(os.environ['GITHUB_EVENT_PATH'], encoding='utf-8') as stream:
event = json.load(stream)
require(event.get('action') == 'completed', 'producer is not complete')
require(event.get('repository', {}).get('full_name') == 'storytold/cadcraft', 'wrong event repository')
producer = event.get('workflow_run', {})
require(producer.get('head_repository', {}).get('full_name') == 'storytold/cadcraft', 'foreign producer')
require(producer.get('path') == '.github/workflows/nightly.yml', 'wrong producer path')
require(producer.get('head_branch') == 'main', 'wrong producer branch')
require(producer.get('status') == 'completed' and producer.get('conclusion') == 'success', 'producer did not succeed')
# First scheduled attempt only; reviewed manual/re-run authority belongs to release policy.
require(producer.get('event') == 'schedule', 'not an automatic scheduled producer')
run_id, attempt = producer.get('id'), producer.get('run_attempt')
require(type(run_id) is int and run_id > 0, 'invalid producer run id')
require(type(attempt) is int and attempt == 1, 'invalid automatic producer attempt')
body = json.dumps({'ref': 'refs/heads/nightly-signer', 'inputs': {
'producer_run_id': str(run_id), 'producer_run_attempt': str(attempt)
}}).encode('utf-8')
request = urllib.request.Request(
'https://api.github.com/repos/storytold/cadcraft/actions/workflows/nightly-sign.yml/dispatches',
data=body, method='POST', headers={
'Authorization': 'Bearer ' + os.environ['GH_TOKEN'],
'Accept': 'application/vnd.github+json',
'Content-Type': 'application/json',
'X-GitHub-Api-Version': '2022-11-28',
'User-Agent': 'cadcraft-nightly-dispatch'
})
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
raise RuntimeError('dispatch redirects are forbidden')
# One bounded request, no retry: duplicate transport is not publication authority.
with urllib.request.build_opener(NoRedirect()).open(request, timeout=20) as response:
require(response.status == 204, 'dispatch was not accepted')
print('Dispatched producer run/attempt to the release-ref validator; not a signing result.')
+4 -2
View File
@@ -1,8 +1,10 @@
name: CADCraft unsigned nightly
# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet.
# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it).
# Automated nightly builds at 00:30 UTC (paired with nightly-dispatch.yml for automatic
# Stage 2 signer dispatch) plus supervised manual runs by the reviewed manual actors.
on:
schedule:
- cron: '30 0 * * *'
workflow_dispatch:
permissions:
+1 -1
View File
@@ -10,7 +10,7 @@ permissions:
contents: read
concurrency:
group: sonarcloud-${{ github.ref }}
group: ${{ github.ref == 'refs/heads/main' && format('sonarcloud-main-{0}', github.sha) || format('sonarcloud-{0}', github.ref) }}
# A push to main is the run that publishes coverage; superseded runs there would never finish.
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
+1
View File
@@ -25,6 +25,7 @@ Generated-in-code assets are original and have no file to list:
| Asset | Author | Source | Licence | Notes |
|---|---|---|---|---|
| `crates/ui-egui/src/i18n/zh_shared.tsv` | @V1dalTheAbidal | [craft-i18n #444](https://github.com/storytold/craft-i18n/pull/444), [pinned Simplified Chinese CADCraft catalog](https://github.com/storytold/craft-i18n/blob/9fa32aecf2759cd61bb216a958df68da619798f3/locales/zh-hans/cadcraft.tsv#L201) | MIT OR Apache-2.0 | Exact generated one-row projection for offline builds; AI-assisted, not native-speaker reviewed. |
| `licenses/jpeg-encoder-0.6.1/` | jpeg-encoder contributors and Independent JPEG Group | [jpeg-encoder 0.6.1](https://crates.io/crates/jpeg-encoder/0.6.1) | (MIT OR Apache-2.0) AND IJG | Dependency license and SIMD notices; source hashes in SOURCE.json. |
| `epaint_default_fonts::EGUI_ICONS`, `epaint_default_fonts::EMOJI_ICON` (dependency font inputs) | John Slegers | [egui 173cc737](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [emoji-icon-font](https://github.com/jslegers/emoji-icon-font) | MIT (Copyright (c) 2014 John Slegers; full upstream text in `NOTICE`) | egui-icons.ttf is the five-glyph subset; emoji-icon-font.ttf is the full monochrome fallback. Registered by the production default font definitions; dependency assets unmodified here, no font file copied into this repository. |
| `krilla 0.8.2 / icc/sGrey-v2-magic.icc` (dependency-embedded) | Clinton Ingram | [craft-libs 9f89fe8 vendor/krilla/icc/sGrey-v2-magic.icc](https://github.com/storytold/craft-libs/blob/9f89fe8f6d72ab4db4cc06f186381a6a254463ab/vendor/krilla/icc/sGrey-v2-magic.icc) (Krilla 0.8.2 upstream 3ffdf0588cf98050aad6edba51ca70162e1fb5b5) | CC0-1.0 | Embedded by the pinned PDF writer (`craft-pdf` 0.1.0, Krilla 0.8.2); unmodified dependency asset, no file copied into this repository. SHA-256 `4110169287e5f1b5149ca9f1da1814d32943905bba8030e849d1a3b729a19481`. |
Generated
+10
View File
@@ -736,6 +736,7 @@ dependencies = [
"cadcraft-ui-egui",
"chrono",
"clap",
"craft-nightly",
"craft-quit",
"craft-update",
"eframe",
@@ -1591,6 +1592,15 @@ dependencies = [
"encoding_rs",
]
[[package]]
name = "craft-nightly"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=8945bdb09b36245a1d442438ce8876377ef430d0#8945bdb09b36245a1d442438ce8876377ef430d0"
dependencies = [
"uds_windows",
"winsafe",
]
[[package]]
name = "craft-pdf"
version = "0.1.0"
+1
View File
@@ -19,6 +19,7 @@ craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "8945bdb09b36245a1d442438ce8876377ef430d0" }
cadcraft-color = { path = "crates/color" }
cadcraft-doc = { path = "crates/doc" }
cadcraft-constraints = { path = "crates/constraints" }
+1 -1
View File
@@ -66,7 +66,7 @@ fn convert_long_about() -> &'static str {
/// cadcraft-cli: headless CADCraft
#[derive(Parser)]
#[command(name = "cadcraft-cli", version = cadcraft_engine::build_version(), arg_required_else_help = true)]
#[command(name = "cadcraft-cli", version = cadcraft_engine::build_version(), propagate_version = true, arg_required_else_help = true)]
pub(crate) struct Cli {
#[command(subcommand)]
pub(crate) command: Command,
+15 -2
View File
@@ -188,12 +188,25 @@ fn subcommand_help_requests() {
),
case("help after an extra argument", &["info", "{b}", "extra", "-h"], 0, Line("Print a drawing's summary as JSON"), Empty),
case("--help after -- is a file name", &["run", "--", "--help"], 1, Empty, Starts("error: invalid parameters for `open`: --help:")),
case("run --version", &["run", "--version"], 2, Empty, Line("error: unexpected argument '--version' found")),
case("info --version", &["info", "--version"], 2, Empty, Line("error: unexpected argument '--version' found")),
],
);
}
/// RFC-0018 rule 1.1: `--version` and `-V` work on every subcommand, print one line on stdout and
/// return without running it (`mcp` would otherwise wait for a client).
#[test]
fn every_subcommand_prints_the_version() {
for sub in ["info", "convert", "run", "commands", "mcp", "perf", "sample", "roundtrip"] {
for flag in ["--version", "-V"] {
let top = invoke(&[flag]);
let release = top.stdout.strip_prefix("cadcraft-cli ").unwrap_or_else(|| panic!("{:?}", top.stdout));
let got = invoke(&[sub, flag]);
assert_eq!((got.code, got.stderr.as_str()), (0, ""), "{sub} {flag}");
assert_eq!(got.stdout, format!("cadcraft-cli-{sub} {release}"), "{sub} {flag}");
}
}
}
#[test]
fn unknown_flags_on_every_subcommand() {
run_cases(
+1
View File
@@ -24,6 +24,7 @@ serde_json = { workspace = true }
serde = { workspace = true }
log = { workspace = true }
clap = { workspace = true }
craft-nightly = { workspace = true }
thiserror = { workspace = true }
chrono = { workspace = true }
# Reads eframe's app.ron to tell whether a window state was saved (main.rs `saved_window`).
+4 -29
View File
@@ -1,23 +1,11 @@
//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build.
use crate::launch_profile::Profile;
use std::ffi::OsString;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BuildFlavor {
Stable,
NightlyV1,
}
pub use craft_nightly::BuildFlavor;
pub const COMPILED: BuildFlavor = if cfg!(cadcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> {
match (flavor, profile.is_nightly()) {
(BuildFlavor::NightlyV1, false) => Err("Open CADCraft Nightly from ArtCraft Launcher".into()),
(BuildFlavor::Stable, true) => Err("This is a stable CADCraft build; nightly-v1 requires the nightly build".into()),
_ => Ok(()),
}
}
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
desktop_session && flavor == BuildFlavor::NightlyV1
}
@@ -35,7 +23,8 @@ pub fn version(flavor: BuildFlavor, stable: &str) -> String {
#[cfg(test)]
mod tests {
use super::*;
use super::{BuildFlavor, needs_native_error, version, version_query};
#[test]
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
@@ -44,20 +33,6 @@ mod tests {
assert!(!needs_native_error(BuildFlavor::Stable, false));
}
#[test]
fn nightly_build_without_a_profile_is_refused_before_startup() {
let started = std::cell::Cell::new(false);
let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true));
assert!(result.unwrap_err().contains("ArtCraft Launcher"));
assert!(!started.get());
}
#[test]
fn stable_and_nightly_flavors_accept_only_their_own_profile() {
let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root"));
assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok());
assert!(require_profile(BuildFlavor::Stable, &nightly).is_err());
assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok());
}
#[test]
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
assert_eq!(version(BuildFlavor::Stable, "0.23.1"), "0.23.1");
+64 -174
View File
@@ -1,211 +1,101 @@
//! Launcher-owned nightly-v1 bootstrap. Selected before logging, updates, fonts or saved state.
//! Stable launches retain their original arguments and directory policy. No environment mutation.
//! Nightly-v1 bootstrap powered by `craft-nightly`: selected before logging, updates, fonts, or
//! saved state. Direct nightly launches self-isolate into `craft_nightly::canonical_profile_root`,
//! while explicit `--launch-profile nightly-v1 --profile-root <dir>` invocations keep their
//! launcher-supplied root. Stable launches retain their original arguments and directory policy.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
use std::sync::OnceLock;
pub const VERSION: &str = "nightly-v1";
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Profile {
Stable,
NightlyV1(PathBuf),
}
impl Profile {
pub fn is_nightly(&self) -> bool {
matches!(self, Self::NightlyV1(_))
}
pub fn root(&self) -> Option<&Path> {
match self {
Self::Stable => None,
Self::NightlyV1(root) => Some(root),
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct Launch {
pub profile: Profile,
pub args: Vec<OsString>,
}
static PROFILE: OnceLock<Profile> = OnceLock::new();
use craft_nightly::{BuildFlavor, Launch, Profile, ProfileError, StartupOptions};
pub fn current() -> &'static Profile {
PROFILE.get().unwrap_or(&Profile::Stable)
craft_nightly::current().unwrap_or(&Profile::Stable)
}
pub fn install(profile: Profile) -> Result<(), String> {
PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into())
}
/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is
/// a file, even when it looks like a profile flag. No filesystem or startup hook runs here.
pub fn parse(args: Vec<OsString>) -> Result<Launch, String> {
let mut selector = None;
let mut root = None;
let mut other = Vec::new();
let mut files = Vec::new();
let mut iter = args.iter();
let mut delimiter = false;
while let Some(arg) = iter.next() {
if arg == "--" {
delimiter = true;
files.extend(iter.cloned());
break;
}
if arg == "--launch-profile" || arg == "--profile-root" {
let slot = if arg == "--launch-profile" { &mut selector } else { &mut root };
if slot.is_some() {
return Err("the profile selector and root must each occur exactly once".into());
}
let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?;
if value.to_string_lossy().starts_with("--") {
return Err("the profile selector/root needs a value".into());
}
*slot = Some(value.clone());
} else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") {
return Err("the nightly protocol requires separate literal selector/root argument tokens".into());
} else {
other.push(arg.clone());
}
}
match (selector, root) {
(None, None) => Ok(Launch { profile: Profile::Stable, args }),
(Some(version), Some(root)) if version == VERSION => {
if !delimiter || !other.is_empty() {
return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into());
}
let root = PathBuf::from(root);
if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) {
return Err("the nightly profile root must be absolute and contain no parent traversal".into());
}
Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() })
}
(Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()),
_ => Err("--launch-profile and --profile-root must be supplied together".into()),
}
}
/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`),
/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never
/// validated or touched, and `-- --version` stays a file name.
pub fn version_query(args: &[OsString]) -> bool {
let Some((last, pair)) = args.split_last() else { return false };
if last != "--version" && last != "-V" {
return false;
}
let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect();
matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1)
}
/// Validation finishes before the caller's first startup effect. Stable never calls the nightly
/// root validator, so its old portable/config resolution stays unchanged.
pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result<PathBuf, String>) -> Result<Launch, String> {
if let Profile::NightlyV1(root) = &launch.profile {
launch.profile = Profile::NightlyV1(validate(root)?);
}
Ok(launch)
}
/// Resolve the selected private root before the caller's first startup effect.
pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option<OsString>, exe: Option<&Path>) -> Result<PathBuf, String> {
crate::profile_root::validate(root, env, exe, crate::portable::probe)
pub fn prepare(flavor: BuildFlavor, args: impl IntoIterator<Item = OsString>) -> Result<Launch, ProfileError> {
craft_nightly::prepare_launch(flavor, &crate::profile_root::spec(), args, &StartupOptions::new())
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::Cell;
use std::ffi::OsString;
use std::path::PathBuf;
use craft_nightly::{BuildFlavor, NIGHTLY_V1_CONTRACT, Profile, ProfileError, StartupOptions, canonical_profile_root, parse_startup};
use crate::profile_root::{APP_ID, spec};
fn args(values: &[&str]) -> Vec<OsString> {
values.iter().map(OsString::from).collect()
}
fn absolute() -> &'static str {
if cfg!(windows) { r"C:\NightlyData\profiles\cadcraft" } else { "/nightly-data/profiles/cadcraft" }
}
fn nightly() -> Vec<OsString> {
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
#[test]
fn direct_nightly_launch_self_isolates_into_canonical_root_and_preserves_user_args() {
let expected_root = canonical_profile_root(APP_ID).unwrap();
let launch = parse_startup(BuildFlavor::NightlyV1, &spec(), args(&["--sample", "plan.dxf"]), &StartupOptions::new()).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(expected_root));
assert!(launch.profile.is_nightly());
assert_eq!(launch.passthrough_args, args(&["--sample", "plan.dxf"]));
assert!(!launch.is_version_query());
}
#[test]
fn stable_arguments_and_directory_policy_are_unchanged() {
for argv in [args(&[]), args(&["--new-window", "a.dxf"]), args(&["--", "--launch-profile", "file.dxf"])] {
let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap();
assert_eq!(launch, Launch { profile: Profile::Stable, args: argv });
}
}
#[test]
fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() {
let mut argv = nightly();
argv.extend(args(&["--profile-root", "drawing with spaces.dxf"]));
let launch = parse(argv).unwrap();
fn explicit_launcher_flags_override_canonical_root_and_forward_passthrough_args() {
let argv = args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--", "drawing with spaces.dxf"]);
let launch = parse_startup(BuildFlavor::NightlyV1, &spec(), argv, &StartupOptions::new()).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
assert_eq!(launch.args, args(&["--", "--profile-root", "drawing with spaces.dxf"]));
assert_eq!(launch.passthrough_args, args(&["drawing with spaces.dxf"]));
assert!(!launch.is_version_query());
}
#[test]
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
fn stable_arguments_are_unchanged_and_nightly_flags_are_refused() {
for argv in [args(&[]), args(&["--new-window", "a.dxf"]), args(&["--", "--launch-profile", "file.dxf"])] {
let launch = parse_startup(BuildFlavor::Stable, &spec(), argv.clone(), &StartupOptions::new()).unwrap();
assert_eq!(launch.profile, Profile::Stable);
assert_eq!(launch.passthrough_args, argv);
}
let nightly = args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"]);
assert!(matches!(parse_startup(BuildFlavor::Stable, &spec(), nightly, &StartupOptions::new()), Err(ProfileError::NightlyFlagsInStableBuild)));
}
#[test]
fn malformed_nightly_flags_are_refused() {
let s = spec();
for argv in [
args(&["--launch-profile", VERSION]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT]),
args(&["--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-window", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute()]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", "", "--"]),
args(&["--new-window", "--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute()]),
] {
assert!(parse(argv).is_err());
assert!(parse_startup(BuildFlavor::NightlyV1, &s, argv, &StartupOptions::new()).is_err());
}
}
#[test]
fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() {
let pair = &["--launch-profile", VERSION, "--profile-root", absolute()];
let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION];
fn launcher_and_direct_version_queries_are_recognized() {
let s = spec();
for flag in ["--version", "-V"] {
for form in [pair, reversed] {
let mut argv = args(form);
argv.push(flag.into());
assert!(version_query(&argv), "{argv:?}");
}
}
for argv in [
args(&["--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-window", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]),
args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]),
args(&["--launch-profile", VERSION, "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]),
] {
assert!(!version_query(&argv), "{argv:?}");
}
// Outside the query the strict protocol still refuses the version flag.
assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err());
}
let direct = parse_startup(BuildFlavor::NightlyV1, &s, args(&[flag]), &StartupOptions::new()).unwrap();
assert!(direct.is_version_query(), "direct {flag}");
#[test]
fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() {
let reached = Cell::new(false);
let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true));
assert!(result.is_err());
assert!(!reached.get());
}
let launcher = parse_startup(
BuildFlavor::NightlyV1,
&s,
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), flag]),
&StartupOptions::new(),
)
.unwrap();
assert!(launcher.is_version_query(), "launcher {flag}");
}
#[test]
fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() {
let checked = PathBuf::from(absolute()).join("checked");
let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap();
assert_eq!(launch.profile.root(), Some(checked.as_path()));
assert!(launch.profile.is_nightly());
let file_named_version = parse_startup(BuildFlavor::NightlyV1, &s, args(&["--", "--version"]), &StartupOptions::new()).unwrap();
assert!(!file_named_version.is_version_query());
}
}
+17 -22
View File
@@ -428,35 +428,30 @@ fn report_launch_profile_error(error: &str) {
/// should return success without opening a window.
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
let argv: Vec<_> = std::env::args_os().skip(1).collect();
// Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
// --version`: answered before root validation, process identity, logging, IPC or any window.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv))
{
// Plain `--version` or `-V`: answered before resolving a home directory, root validation,
// process identity, logging, IPC or any window.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && build_flavor::version_query(&argv) {
use std::io::Write as _;
let _ = writeln!(std::io::stdout(), "{}", nightly_version_line());
return None;
}
let early = launch_profile::parse(argv)
.and_then(|launch| {
build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?;
initialize_nightly_process_identity().map_err(|error| error.to_string())?;
Ok(launch)
})
.and_then(|launch| {
launch_profile::prepare(launch, |root| {
launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref())
})
})
.unwrap_or_else(|error| {
report_launch_profile_error(&error);
std::process::exit(2)
});
let identity = if early.profile.is_nightly() { LaunchIdentity::NightlyV1 } else { LaunchIdentity::Stable };
if let Err(error) = launch_profile::install(early.profile).and_then(|()| os_window::select_identity(identity)) {
let launch = launch_profile::prepare(build_flavor::COMPILED, argv).unwrap_or_else(|error| {
report_launch_profile_error(&error.to_string());
std::process::exit(2)
});
// Launcher's `--launch-profile nightly-v1 --profile-root <dir> --version` (or `-V`):
// `craft_nightly::prepare_launch` leaves the filesystem untouched and installs no profile.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && launch.is_version_query() {
use std::io::Write as _;
let _ = writeln!(std::io::stdout(), "{}", nightly_version_line());
return None;
}
let identity = if launch.profile.is_nightly() { LaunchIdentity::NightlyV1 } else { LaunchIdentity::Stable };
if let Err(error) = initialize_nightly_process_identity().map_err(|e| e.to_string()).and_then(|()| os_window::select_identity(identity)) {
report_launch_profile_error(&error);
std::process::exit(2);
}
Some(early.args)
Some(launch.passthrough_args)
}
/// Parse CLI options (`--control`, `--sample`, files, `--version`), install logging and I/O hooks, build the services and app, and run eframe.
+167 -628
View File
@@ -1,679 +1,218 @@
//! App-owned nightly profile fences; no stable fallback, migration or process environment changes.
//! CADCraft's `craft-nightly` isolation specification: stable paths, environment fence,
//! portable-mode markers, folder-only entries, and platform-specific forbidden roots.
use std::ffi::OsString;
use std::path::PathBuf;
use crate::portable::{PORTABLE_DATA_DIR, portable_marker};
use std::path::{Component, Path, PathBuf};
use craft_nightly::AppProfileSpec;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Platform {
Windows,
Linux,
Mac,
use crate::portable::PORTABLE_MARKER;
pub const APP_ID: &str = "cadcraft";
/// The app id eframe derives stable's storage folder from (`main.rs` `persistence_path`).
const STABLE_PACKAGE_ID: &str = "ai.storyteller.cadcraft";
/// The app id of the nightly bundle (`packaging/linux/flatpak-bundle.sh`).
const NIGHTLY_PACKAGE_ID: &str = "ai.storyteller.cadcraft.nightly";
const STABLE_DIR_NAMES: &[&str] = &["CADCraft", "cadcraft"];
const FORBIDDEN_ENV_VARS: &[&str] = &["CADCRAFT_CONFIG_DIR"];
const PORTABLE_MARKERS: &[&str] = &[PORTABLE_MARKER];
const FOLDER_ONLY_ENTRIES: &[&str] = &["autosave", "logs", "support", "single-instance", "plotters", "crash-reports"];
/// Builds CADCraft's `craft-nightly` isolation specification from the current process environment.
pub fn spec() -> AppProfileSpec {
spec_with_env(|key| std::env::var_os(key))
}
impl Platform {
fn current() -> Result<Self, String> {
match std::env::consts::OS {
"windows" => Ok(Self::Windows),
"linux" => Ok(Self::Linux),
"macos" => Ok(Self::Mac),
// CADCraft also builds for the BSDs (packaging/freebsd): nightly-v1 is Windows, macOS and
// Linux only, as the shared nightlies publish.
_ => Err("nightly-v1 is not defined for this operating system".into()),
}
}
fn ignores_case(self) -> bool {
self != Self::Linux
fn spec_with_env(env: impl Fn(&str) -> Option<OsString>) -> AppProfileSpec {
AppProfileSpec {
app_id: APP_ID,
display_name: "CADCraft",
stable_dir_names: STABLE_DIR_NAMES,
stable_package_id: STABLE_PACKAGE_ID,
nightly_package_id: NIGHTLY_PACKAGE_ID,
profile_root_env: None,
forbidden_env_vars: FORBIDDEN_ENV_VARS,
portable_markers: PORTABLE_MARKERS,
folder_only_entries: FOLDER_ONLY_ENTRIES,
extra_forbidden_roots: extra_forbidden_roots(&env),
}
}
fn absolute(path: PathBuf, label: &str) -> Result<PathBuf, String> {
if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
return Err(format!("{label} must be absolute and contain no parent traversal"));
}
Ok(path)
}
fn required_base(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Result<PathBuf, String> {
let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?;
absolute(PathBuf::from(value), key)
}
fn xdg_base(env: &impl Fn(&str) -> Option<OsString>, key: &str, fallback: &str) -> Result<PathBuf, String> {
match env(key).filter(|v| !v.is_empty()) {
Some(value) => absolute(PathBuf::from(value), key),
None => Ok(required_base(env, "HOME")?.join(fallback)),
}
}
/// Resolve existing ancestors before creating anything. A dangling link or inaccessible ancestor
/// is not a missing directory that may be replaced or followed later.
fn canonical_future(path: &Path) -> Result<PathBuf, String> {
let mut parent = path;
let mut missing = Vec::new();
loop {
match std::fs::symlink_metadata(parent) {
Ok(_) => break,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string());
parent = parent.parent().ok_or("the profile root has no existing ancestor")?;
fn extra_forbidden_roots(env: &impl Fn(&str) -> Option<OsString>) -> Vec<PathBuf> {
let mut roots = Vec::new();
#[cfg(target_os = "windows")]
{
// The MSI's per-machine install folder (`cadcraft.wxs`).
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
if let Some(base) = non_empty_abs(env, key) {
roots.push(base.join("ArtCraft").join("CADCraft"));
}
Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")),
}
}
let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?;
for part in missing.into_iter().rev() {
resolved.push(part);
}
Ok(resolved)
}
fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool {
// A component that is not valid UTF-8 keeps its exact bytes: a lossy comparison would fold two
// different names into the same replacement character and call them one folder.
let parts = |p: &Path| {
p.components()
.map(|c| {
let value = c.as_os_str();
match (platform.ignores_case(), value.to_str()) {
(true, Some(text)) => OsString::from(text.to_lowercase()),
_ => value.to_os_string(),
}
})
.collect::<Vec<_>>()
};
let (a, b) = (parts(a), parts(b));
a.starts_with(&b) || b.starts_with(&a)
}
fn installation_boundary(platform: Platform, exe: &Path) -> Result<PathBuf, String> {
let parent = exe.parent().ok_or("cannot establish the installation boundary")?;
if platform == Platform::Mac {
// A profile in Resources is still inside the versioned install, not beside MacOS.
if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) {
return Ok(bundle.to_path_buf());
#[cfg(all(unix, not(target_os = "macos")))]
{
roots.extend(["/usr/bin/cadcraft", "/usr/local/bin/cadcraft", "/opt/cadcraft"].map(PathBuf::from));
// The stable Flatpak keeps its data in its own per-app folder.
if let Some(home) = non_empty_abs(env, "HOME") {
roots.push(home.join(".var/app/ai.storyteller.cadcraft"));
}
}
Ok(parent.to_path_buf())
}
/// Every stable CADCraft data root of this platform, plus the install folders and the running
/// install ([`installation_boundary`]).
fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>, exe: &Path) -> Result<Vec<PathBuf>, String> {
let mut roots = match platform {
Platform::Windows => {
let mut roots = ["APPDATA", "LOCALAPPDATA"]
.into_iter()
.map(|key| required_base(env, key).map(|p| p.join("CADCraft")))
.collect::<Result<Vec<_>, _>>()?;
// Stable's eframe storage folder (`eframe::storage_dir`: `app.ron` under
// `%APPDATA%\ai.storyteller.cadcraft\data`), outside the roaming `CADCraft` folder.
roots.push(required_base(env, "APPDATA")?.join(EFRAME_APP_ID));
// The MSI's per-machine folder (cadcraft.wxs). A custom install folder is not known
// here; the executable's own folder is fenced below.
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
if let Some(base) = env(key).filter(|v| !v.is_empty()) {
roots.push(absolute(PathBuf::from(base), key)?.join("ArtCraft").join("CADCraft"));
}
}
roots
}
Platform::Linux => {
let mut roots =
[("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")]
.into_iter()
.map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("cadcraft")))
.collect::<Result<Vec<_>, _>>()?;
roots.extend(["/usr/bin/cadcraft", "/usr/local/bin/cadcraft", "/opt/cadcraft"].map(PathBuf::from));
// The stable Flatpak keeps its data in its own per-app folder.
roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.cadcraft"));
// Stable's eframe storage folder (`eframe::storage_dir`: window state, Options profile,
// UI and autosave prefs in `app.ron`), which is not the XDG settings folder above.
roots.push(xdg_base(env, "XDG_DATA_HOME", ".local/share")?.join(EFRAME_APP_ID));
roots
}
Platform::Mac => {
let home = required_base(env, "HOME")?;
#[cfg(target_os = "macos")]
{
if let Some(home) = non_empty_abs(env, "HOME") {
let library = home.join("Library");
vec![
library.join("Application Support/CADCraft"),
library.join("Caches/CADCraft"),
library.join("Caches/ai.storyteller.cadcraft"),
// Stable's eframe storage folder (`eframe::storage_dir`: `app.ron` in Application
// Support), beside the settings folder env.rs uses.
library.join("Application Support").join(EFRAME_APP_ID),
library.join("Preferences/CADCraft"),
library.join("Preferences/ai.storyteller.cadcraft.plist"),
library.join("Saved Application State/ai.storyteller.cadcraft.savedState"),
home.join("Applications/CADCraft.app"),
PathBuf::from("/Applications/CADCraft.app"),
]
roots.push(library.join("Preferences/ai.storyteller.cadcraft.plist"));
roots.push(library.join("Saved Application State/ai.storyteller.cadcraft.savedState"));
roots.push(home.join("Applications/CADCraft.app"));
}
};
roots.push(installation_boundary(platform, exe)?);
roots.into_iter().map(|p| canonical_future(&p)).collect()
roots.push(PathBuf::from("/Applications/CADCraft.app"));
}
roots
}
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Result<PathBuf, String> {
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
let child = canonical_future(&chosen.join(name))?;
if child == chosen || !child.starts_with(&chosen) {
return Err(format!("the nightly {label} must stay inside its selected profile"));
}
// A regular file in a folder's place is not a folder: the readers and sweepers that follow would
// fail halfway, so refuse it while the profile is still being validated.
match std::fs::symlink_metadata(&child) {
Ok(metadata) if !metadata.file_type().is_dir() => {
return Err(format!("the nightly {label} must be a directory, not a file or an alias"));
}
Ok(_) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(format!("cannot inspect the nightly {label}: {error}")),
}
Ok(child)
fn non_empty_abs(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Option<PathBuf> {
let value = env(key).filter(|v| !v.is_empty())?;
let path = PathBuf::from(value);
path.is_absolute().then_some(path)
}
/// Every existing entry directly in the profile (logs, settings and so on) must resolve inside it,
/// so a link there cannot point Nightly's writes at another app's data.
fn entries_stay_inside(root: &Path) -> Result<(), String> {
let entries = match std::fs::read_dir(root) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")),
};
for entry in entries {
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
let path = entry.path();
let metadata = std::fs::symlink_metadata(&path).map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
// Settings and session state are ordinary files, not directories. Keep the existing
// directory-boundary check for folders (including the known folder-only entries).
let folder_only = PROFILE_FOLDERS.iter().any(|name| entry.file_name().eq_ignore_ascii_case(name));
if metadata.is_file() && !folder_only {
private_regular_file(&path, &metadata)?;
} else {
private_subdirectory(root, entry.file_name(), "profile entry")?;
}
}
Ok(())
}
/// Persisted files must have their own ordinary file identity, not an alias to other data.
fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt as _;
if metadata.nlink() != 1 {
return Err("the nightly profile file must not be shared".into());
}
}
#[cfg(windows)]
{
use winsafe::{HFILE, co};
let (file, _) = HFILE::CreateFile(
path.to_str().ok_or("the nightly profile file path is not textual")?,
co::GENERIC::default(),
Some(co::FILE_SHARE::READ | co::FILE_SHARE::WRITE | co::FILE_SHARE::DELETE),
None,
co::DISPOSITION::OPEN_EXISTING,
co::FILE_ATTRIBUTE::NORMAL,
Some(co::FILE_FLAG::OPEN_REPARSE_POINT),
None,
None,
)
.map_err(|e| e.to_string())?;
let info = file.GetFileInformationByHandle().map_err(|e| e.to_string())?;
if info.dwFileAttributes.has(co::FILE_ATTRIBUTE::REPARSE_POINT | co::FILE_ATTRIBUTE::DIRECTORY) {
return Err("the nightly profile file must not be an alias or directory".into());
}
if info.nNumberOfLinks != 1 {
return Err("the nightly profile file must not be shared".into());
}
}
let _ = (path, metadata);
Ok(())
}
/// Recognise the shared portable data namespace in both the supplied and resolved path.
/// This is not an inventory of arbitrary custom Stable overrides or a Launcher ownership proof.
fn is_portable_layout(path: &Path, platform: Platform) -> bool {
// A folder under a portable copy belongs to that copy too. Above the chosen folder itself, a
// marker only counts beside a CADCraft executable, so an unrelated portable.txt higher up
// (in a user folder or at a drive root) does not refuse the profile.
path.ancestors().enumerate().any(|(depth, ancestor)| {
portable_marker(ancestor).is_some() && (depth == 0 || ["cadcraft.exe", "cadcraft"].iter().any(|exe| ancestor.join(exe).is_file()))
}) || path.components().any(|component| match component {
Component::Normal(name) if platform.ignores_case() => name.to_string_lossy().eq_ignore_ascii_case(PORTABLE_DATA_DIR),
Component::Normal(name) => name == PORTABLE_DATA_DIR,
_ => false,
})
}
/// The writable hook is the app's existing exclusive probe (`portable::probe`). Keeping it injected
/// lets filesystem boundary tests exercise the real policy without starting the app or changing
/// global state.
pub fn validate(
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
validate_for(Platform::current()?, root, env, exe, writable)
}
fn validate_for(
platform: Platform,
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
absolute(root.to_path_buf(), "the nightly profile root")?;
let chosen = canonical_future(root)?;
// The deb/rpm CLI wrapper exports CADCRAFT_CONFIG_DIR at the folder this launch already owns (the
// GUI wrappers name the profile through `--profile-root` instead), so that value is inert:
// `env::apply_profile` sets the settings folder from the profile, not from the variable. Any
// other value would redirect Nightly's settings folder, so it is refused.
if let Some(configured) = env("CADCRAFT_CONFIG_DIR").filter(|v| !v.is_empty()) {
let configured = canonical_future(&absolute(PathBuf::from(configured), "CADCRAFT_CONFIG_DIR")?)?;
if !configured.starts_with(&chosen) {
return Err("nightly-v1 cannot be combined with CADCRAFT_CONFIG_DIR outside its own profile".into());
}
}
if platform != Platform::Windows
&& let Some(id) = env("FLATPAK_ID").filter(|v| !v.is_empty())
{
// A Flatpak's data folder and runtime socket namespace belong to its app id. The nightly
// bundle has an id of its own ([`NIGHTLY_FLATPAK_ID`], named by
// `packaging/linux/flatpak-bundle.sh`), so its profile is already the sandbox's own; any
// other instance is the stable app's (or another app's), whose socket this profile must
// not inherit.
if id.to_string_lossy() != NIGHTLY_FLATPAK_ID {
return Err("nightly-v1 cannot inherit another Flatpak app's instance; launch through the native Launcher".into());
}
}
if is_portable_layout(root, platform) || is_portable_layout(&chosen, platform) {
return Err("the nightly root must not use a portable CADCraft installation or its CADCraftData settings folder".into());
}
let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?;
let forbidden = forbidden_roots(platform, &env, &exe)?;
if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) {
return Err("the nightly root must not overlap stable data or an installation".into());
}
entries_stay_inside(&chosen)?;
// Drawing Recovery reads, adopts, overwrites and sweeps entries. Never let its alias leave this
// private profile, including toward a stable portable directory not in our known roots.
private_subdirectory(&chosen, AUTOSAVE, "recovery folder")?;
let mut create = std::fs::DirBuilder::new();
create.recursive(true);
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt as _;
create.mode(0o700);
}
create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?;
let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?;
if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) {
return Err("the nightly profile changed while it was being validated".into());
}
private_subdirectory(&confirmed, AUTOSAVE, "recovery folder")?;
entries_stay_inside(&confirmed)?;
writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?;
Ok(confirmed)
}
/// The app id of the nightly Flatpak bundle (`packaging/linux/flatpak-bundle.sh`): the one Flatpak
/// instance whose sandbox is this channel's own. The window identity ([`crate::os_window`]) and the
/// bundle id differ on purpose, as they do for stable.
pub const NIGHTLY_FLATPAK_ID: &str = "ai.storyteller.cadcraft.nightly";
/// The app id eframe derives stable's storage folder from ([`crate::main`]'s `persistence_path`).
/// A profile that sits there would overwrite stable's `app.ron`, so its folder is fenced too.
const EFRAME_APP_ID: &str = "ai.storyteller.cadcraft";
/// The subfolder autosave and Drawing Recovery write ([`crate::main`], `<settings>/autosave`).
pub const AUTOSAVE: &str = "autosave";
const PROFILE_FOLDERS: [&str; 6] = [AUTOSAVE, "logs", "support", "single-instance", "plotters", "crash-reports"];
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
use std::ffi::OsString;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
struct Fixture {
root: PathBuf,
env: BTreeMap<String, OsString>,
exe: PathBuf,
}
use craft_nightly::{ProfileError, validate_and_prepare_root};
impl Fixture {
fn new() -> Self {
use super::{
APP_ID, FOLDER_ONLY_ENTRIES, FORBIDDEN_ENV_VARS, NIGHTLY_PACKAGE_ID, PORTABLE_MARKERS, STABLE_DIR_NAMES, STABLE_PACKAGE_ID, spec,
spec_with_env,
};
struct TempDir(PathBuf);
impl TempDir {
fn new(label: &str) -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
let root = loop {
let candidate =
std::env::temp_dir().join(format!("cadcraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
let candidate = std::env::temp_dir().join(format!(
"cadcraft-profile-spec-{}-{}-{label}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
match std::fs::create_dir(&candidate) {
Ok(()) => break std::fs::canonicalize(candidate).unwrap(),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("cannot create owned fixture: {error}"),
Err(error) => panic!("cannot create temp dir: {error}"),
}
};
let home = root.join("home");
let exe = root.join("install/cadcraft");
std::fs::create_dir_all(&home).unwrap();
std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
std::fs::write(&exe, b"fixture executable, never run").unwrap();
let env = [("HOME", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))]
.into_iter()
.map(|(key, value)| (key.into(), value.into_os_string()))
.collect();
Self { root, env, exe }
}
fn get(&self, key: &str) -> Option<OsString> {
self.env.get(key).cloned()
}
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
validate_for(
platform,
root,
|key| self.get(key),
Some(&self.exe),
|dir| {
let probe = dir.join("exclusive-test-probe");
let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
drop(file);
std::fs::remove_file(probe)
},
)
}
fn home(&self) -> PathBuf {
PathBuf::from(self.get("HOME").unwrap())
Self(root)
}
}
impl Drop for Fixture {
impl Drop for TempDir {
fn drop(&mut self) {
// Only the directory successfully created by this fixture is owned for removal.
std::fs::remove_dir_all(&self.root).unwrap();
let _ = std::fs::remove_dir_all(&self.0);
}
}
#[test]
fn portable_settings_from_another_install_are_refused_before_any_probe() {
let fixture = Fixture::new();
let stable_install = fixture.root.join("stable portable install");
let stable_data = stable_install.join(PORTABLE_DATA_DIR);
std::fs::create_dir_all(&stable_data).unwrap();
std::fs::write(stable_install.join("portable.txt"), b"owned portable fixture").unwrap();
std::fs::write(stable_data.join("settings.json"), b"stable settings must not change").unwrap();
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
for candidate in [&stable_data, &stable_data.join("nested nightly")] {
let probed = std::cell::Cell::new(false);
let result = validate_for(
platform,
candidate,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
probed.set(true);
Ok(())
},
);
assert!(result.is_err(), "a different portable install is not a private Nightly profile");
assert!(!probed.get(), "reject portable data before a writable probe");
assert!(!stable_data.join("nested nightly").exists());
assert_eq!(std::fs::read(stable_data.join("settings.json")).unwrap(), b"stable settings must not change");
assert_eq!(std::fs::read_dir(&stable_data).unwrap().count(), 1);
}
}
let private = fixture.root.join("CADCraftData-backup-name/nightly");
assert!(fixture.check(Platform::Linux, &private).is_ok(), "a merely similar name is not a portable settings component");
}
fn spec_preserves_cadcraft_isolation_constants_and_extra_forbidden_roots() {
let mut env = BTreeMap::<String, OsString>::new();
#[cfg(target_os = "windows")]
env.insert("ProgramFiles".into(), OsString::from(r"C:\Program Files"));
#[cfg(not(target_os = "windows"))]
env.insert("HOME".into(), OsString::from("/home/tester"));
#[cfg(unix)]
#[test]
fn recovery_aliases_cannot_redirect_to_stable_missing_or_profile_root_data() {
let fixture = Fixture::new();
let stable = fixture.home().join(".local/state/cadcraft/autosave");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-autosave"), b"stable recovery bytes").unwrap();
for (index, target) in [stable.clone(), fixture.root.join("missing recovery target")].into_iter().enumerate() {
let private = fixture.root.join(format!("nightly-{index}"));
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&target, private.join(AUTOSAVE)).unwrap();
let probed = std::cell::Cell::new(false);
let result = validate_for(
Platform::Linux,
&private,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
probed.set(true);
Ok(())
},
let s = spec_with_env(|key| env.get(key).cloned());
assert_eq!(s.app_id, APP_ID);
assert_eq!(s.display_name, "CADCraft");
assert_eq!(s.stable_dir_names, STABLE_DIR_NAMES);
assert_eq!(s.stable_package_id, STABLE_PACKAGE_ID);
assert_eq!(s.nightly_package_id, NIGHTLY_PACKAGE_ID);
assert_eq!(s.profile_root_env, None);
assert_eq!(s.forbidden_env_vars, FORBIDDEN_ENV_VARS);
assert_eq!(s.portable_markers, PORTABLE_MARKERS);
assert_eq!(s.folder_only_entries, FOLDER_ONLY_ENTRIES);
#[cfg(target_os = "windows")]
assert!(s.extra_forbidden_roots.contains(&PathBuf::from(r"C:\Program Files\ArtCraft\CADCraft")));
#[cfg(all(unix, not(target_os = "macos")))]
{
assert!(s.extra_forbidden_roots.contains(&PathBuf::from("/usr/bin/cadcraft")));
assert!(s.extra_forbidden_roots.contains(&PathBuf::from("/usr/local/bin/cadcraft")));
assert!(s.extra_forbidden_roots.contains(&PathBuf::from("/opt/cadcraft")));
assert!(s.extra_forbidden_roots.contains(&PathBuf::from("/home/tester/.var/app/ai.storyteller.cadcraft")));
}
#[cfg(target_os = "macos")]
{
assert!(s.extra_forbidden_roots.contains(&PathBuf::from("/home/tester/Library/Preferences/ai.storyteller.cadcraft.plist")));
assert!(
s.extra_forbidden_roots.contains(&PathBuf::from("/home/tester/Library/Saved Application State/ai.storyteller.cadcraft.savedState"))
);
assert!(result.is_err(), "autosave must not escape the private profile or follow a dangling alias");
assert!(!probed.get());
assert!(s.extra_forbidden_roots.contains(&PathBuf::from("/home/tester/Applications/CADCraft.app")));
assert!(s.extra_forbidden_roots.contains(&PathBuf::from("/Applications/CADCraft.app")));
}
let private = fixture.root.join("nightly-self");
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&private, private.join(AUTOSAVE)).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_err(), "autosave cannot treat all profile settings as recovery entries");
assert_eq!(std::fs::read(stable.join("stable-autosave")).unwrap(), b"stable recovery bytes");
assert_eq!(std::fs::read_dir(stable).unwrap().count(), 1);
}
#[test]
fn nightly_profile_reopens_with_saved_state_and_enforces_folder_only_entries() {
let temp = TempDir::new("reopen");
let private = temp.0.join("nightly-profile");
let s = spec();
let canonical = validate_and_prepare_root(&private, &s).unwrap();
assert_eq!(canonical, private);
for name in ["app.ron", "nightly-session.lock", "nightly-session.json"] {
std::fs::write(private.join(name), b"saved profile data").unwrap();
}
for name in FOLDER_ONLY_ENTRIES {
std::fs::create_dir(private.join(name)).unwrap();
}
assert_eq!(validate_and_prepare_root(&private, &s).unwrap(), private);
for name in ["app.ron", "nightly-session.lock", "nightly-session.json"] {
assert_eq!(std::fs::read(private.join(name)).unwrap(), b"saved profile data", "{name} changed when reopening");
}
for name in FOLDER_ONLY_ENTRIES {
let path = private.join(name);
std::fs::remove_dir(&path).unwrap();
std::fs::write(&path, b"not a directory").unwrap();
assert!(matches!(validate_and_prepare_root(&private, &s), Err(ProfileError::ExpectedDirectoryEntry(_))), "{name} must stay a directory");
std::fs::remove_file(&path).unwrap();
std::fs::create_dir(&path).unwrap();
}
}
#[test]
fn a_non_directory_profile_stops_startup_without_installing_a_profile() {
let temp = TempDir::new("invalid-root");
let root = temp.0.join("ordinary-file");
std::fs::write(&root, b"existing file").unwrap();
let argv = craft_nightly::launch_arguments(&root, &[]);
assert!(craft_nightly::current().is_none());
let result = crate::launch_profile::prepare(craft_nightly::BuildFlavor::NightlyV1, argv);
assert!(matches!(result, Err(ProfileError::NotADirectory(_))));
assert!(craft_nightly::current().is_none());
assert_eq!(std::fs::read(root).unwrap(), b"existing file");
}
#[cfg(unix)]
#[test]
fn recovery_alias_to_a_private_subfolder_keeps_the_profile_usable() {
let fixture = Fixture::new();
let private = fixture.root.join("nightly-private");
let recovery = private.join("private-recovery");
std::fs::create_dir_all(&recovery).unwrap();
std::os::unix::fs::symlink(&recovery, private.join(AUTOSAVE)).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_ok());
assert_eq!(std::fs::canonicalize(private.join(AUTOSAVE)).unwrap(), recovery);
}
#[test]
fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() {
let fixture = Fixture::new();
let root = fixture.home().join("nightly/profiles/cadcraft");
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
assert!(overlaps(&root, &root.join(AUTOSAVE), platform));
assert!(overlaps(&root.join(AUTOSAVE), &root, platform));
assert!(!overlaps(&root, &root.with_file_name("cadcraft-other"), platform));
}
}
#[test]
fn linux_fences_app_xdg_subtrees_but_allows_launcher_sibling() {
let mut fixture = Fixture::new();
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
fixture.env.insert(key.into(), fixture.root.join(key).into_os_string());
}
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
let stable = PathBuf::from(fixture.get(key).unwrap()).join("cadcraft");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap();
for candidate in [stable.clone(), stable.join("nightly"), stable.parent().unwrap().to_path_buf()] {
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
}
assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes");
}
let data = PathBuf::from(fixture.get("XDG_DATA_HOME").unwrap());
// Stable's eframe storage folder holds `app.ron`, so a profile may not sit at or inside it.
let storage = data.join(EFRAME_APP_ID);
std::fs::create_dir_all(&storage).unwrap();
std::fs::write(storage.join("app.ron"), b"stable window state").unwrap();
for candidate in [storage.clone(), storage.join("nightly")] {
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"), "{}", candidate.display());
}
assert_eq!(std::fs::read(storage.join("app.ron")).unwrap(), b"stable window state");
let nightly = data.join("ArtCraftLauncher/nightly/profiles/cadcraft");
assert_eq!(fixture.check(Platform::Linux, &nightly).unwrap(), nightly);
assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0);
}
#[test]
fn nightly_profile_reopens_after_saving_settings_and_session_state() {
let fixture = Fixture::new();
for platform in [Platform::Mac, Platform::Linux, Platform::Windows] {
let private = fixture.root.join(format!("nightly-reopen-{platform:?}"));
assert_eq!(fixture.check(platform, &private).unwrap(), private);
for name in ["app.ron", "nightly-session.lock", "nightly-session.json"] {
std::fs::write(private.join(name), b"saved profile data").unwrap();
}
for name in PROFILE_FOLDERS {
std::fs::create_dir(private.join(name)).unwrap();
}
assert_eq!(fixture.check(platform, &private).unwrap(), private);
assert_eq!(std::fs::read(private.join("app.ron")).unwrap(), b"saved profile data");
for name in [AUTOSAVE, "logs", "support", "single-instance", "plotters", "crash-reports"] {
let path = private.join(name);
std::fs::remove_dir(&path).unwrap();
std::fs::write(&path, b"not a directory").unwrap();
assert!(fixture.check(platform, &private).is_err(), "{name} must stay a directory");
std::fs::remove_file(&path).unwrap();
std::fs::create_dir(&path).unwrap();
}
}
}
#[test]
fn mac_fences_only_app_library_subtrees_and_the_entire_bundle() {
let mut fixture = Fixture::new();
fixture.exe = fixture.root.join("install/CADCraft Nightly.app/Contents/MacOS/CADCraft");
std::fs::create_dir_all(fixture.exe.parent().unwrap()).unwrap();
std::fs::write(&fixture.exe, b"fixture executable, never run").unwrap();
let library = fixture.home().join("Library");
for suffix in [
"Application Support/CADCraft",
"Application Support/ai.storyteller.cadcraft",
"Caches/CADCraft",
"Caches/ai.storyteller.cadcraft",
"Preferences/CADCraft",
"Saved Application State/ai.storyteller.cadcraft.savedState",
] {
let stable = library.join(suffix);
assert!(fixture.check(Platform::Mac, &stable.join("nightly")).unwrap_err().contains("overlap"));
assert!(!stable.exists());
}
let inside_resources = fixture.exe.parent().unwrap().parent().unwrap().join("Resources/profile");
assert!(fixture.check(Platform::Mac, &inside_resources).unwrap_err().contains("overlap"));
assert!(!inside_resources.exists());
let valid = library.join("Application Support/ArtCraftLauncher/nightly/profiles/cadcraft");
assert_eq!(fixture.check(Platform::Mac, &valid).unwrap(), valid);
// The bundle path and the Library fences fold case on macOS.
let cased = library.join("application support/cadcraft/nightly");
assert!(fixture.check(Platform::Mac, &cased).is_err());
}
#[test]
fn windows_fences_roaming_local_and_both_install_folders() {
let mut fixture = Fixture::new();
fixture.env.insert("ProgramFiles".into(), fixture.root.join("program files").into_os_string());
for stable in [
fixture.root.join("roaming/CADCraft"),
fixture.root.join("roaming/ai.storyteller.cadcraft"),
fixture.root.join("local/CADCraft"),
fixture.root.join("program files/ArtCraft/CADCraft"),
] {
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap();
for candidate in [stable.clone(), stable.join("nightly")] {
assert!(fixture.check(Platform::Windows, &candidate).unwrap_err().contains("overlap"), "{}", candidate.display());
}
// Windows folder names ignore case.
assert!(fixture.check(Platform::Windows, &stable.with_file_name("cadcraft")).is_err());
assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes");
}
let valid = fixture.root.join("local/ArtCraftLauncher/nightly/profiles/cadcraft");
assert_eq!(fixture.check(Platform::Windows, &valid).unwrap(), valid);
}
#[test]
fn config_dir_and_flatpak_are_refused() {
let mut fixture = Fixture::new();
fixture.env.insert("CADCRAFT_CONFIG_DIR".into(), fixture.root.join("custom").into_os_string());
let private = fixture.root.join("nightly-config");
assert!(fixture.check(Platform::Linux, &private).unwrap_err().contains("CADCRAFT_CONFIG_DIR"));
assert!(!private.exists());
fixture.env.remove("CADCRAFT_CONFIG_DIR");
for inherited in ["ai.storyteller.cadcraft", "org.freedesktop.other"] {
fixture.env.insert("FLATPAK_ID".into(), inherited.into());
assert!(fixture.check(Platform::Linux, &private).unwrap_err().contains("Flatpak"), "{inherited}");
assert!(!private.exists());
}
}
/// The nightly bundle runs under an app id of its own, so its sandbox data folder is this
/// channel's data root; that one instance is accepted, and its profile stays inside it.
#[test]
fn the_nightly_flatpaks_own_instance_accepts_its_own_profile() {
let mut fixture = Fixture::new();
fixture.env.insert("FLATPAK_ID".into(), NIGHTLY_FLATPAK_ID.into());
let private = fixture.home().join(".var/app/ai.storyteller.cadcraft.nightly/data/cadcraft-nightly");
assert_eq!(fixture.check(Platform::Linux, &private).unwrap(), private);
// Stable's Flatpak folder is still fenced even inside the nightly instance.
let stable = fixture.home().join(".var/app/ai.storyteller.cadcraft");
assert!(fixture.check(Platform::Linux, &stable).unwrap_err().contains("overlap"));
}
/// A Linux Launcher wrapper exports `CADCRAFT_CONFIG_DIR` at the profile it launches; that is
/// the folder this launch already owns, so it must not refuse the profile. Anything else is
/// still a redirect.
#[test]
fn a_wrapper_naming_the_profile_in_config_dir_is_accepted() {
let mut fixture = Fixture::new();
let private = fixture.root.join("nightly-wrapper");
fixture.env.insert("CADCRAFT_CONFIG_DIR".into(), private.clone().into_os_string());
assert_eq!(fixture.check(Platform::Linux, &private).unwrap(), private);
let inside = private.join("nested");
fixture.env.insert("CADCRAFT_CONFIG_DIR".into(), inside.clone().into_os_string());
assert!(fixture.check(Platform::Linux, &inside).is_ok(), "a folder inside the profile is the profile's own");
fixture.env.insert("CADCRAFT_CONFIG_DIR".into(), fixture.root.join("elsewhere").into_os_string());
assert!(fixture.check(Platform::Linux, &private).unwrap_err().contains("CADCRAFT_CONFIG_DIR"));
}
#[test]
fn a_profile_that_cannot_be_written_is_refused_without_a_stable_fallback() {
let fixture = Fixture::new();
let private = fixture.root.join("nightly-unwritable");
let result = validate_for(Platform::Linux, &private, |key| fixture.get(key), Some(&fixture.exe), |_| Err(std::io::Error::other("read-only")));
assert!(result.unwrap_err().contains("not writable"));
assert!(private.exists(), "the profile was created before the probe, and nothing was written into stable");
assert!(!fixture.home().join(".config/cadcraft").exists());
}
#[cfg(unix)]
#[test]
fn a_dangling_entry_inside_the_profile_is_refused_before_writes() {
let fixture = Fixture::new();
let outside = fixture.root.join("outside");
fn symlinks_inside_profile_root_are_refused() {
let temp = TempDir::new("symlink");
let outside = temp.0.join("outside");
let private = temp.0.join("nightly-profile");
std::fs::create_dir_all(&outside).unwrap();
let private = fixture.root.join("nightly-dangling");
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(outside.join("missing"), private.join("logs")).unwrap();
let probed = std::cell::Cell::new(false);
let result = validate_for(
Platform::Linux,
&private,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
probed.set(true);
Ok(())
},
);
assert!(result.is_err());
assert!(!probed.get());
assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0);
std::fs::create_dir_all(&private).unwrap();
std::os::unix::fs::symlink(outside.join("target"), private.join("autosave")).unwrap();
let err = validate_and_prepare_root(&private, &spec()).unwrap_err();
assert!(matches!(err, ProfileError::SymlinkEntry(_)), "unexpected error: {err}");
}
}
+58
View File
@@ -428,4 +428,62 @@ mod tests {
received.sort();
assert_eq!(received, handed);
}
/// A Nightly profile on Windows keeps its single-instance AF_UNIX socket under
/// `<profile>\single-instance\*.sock`. Both a live socket (while a first Nightly copy is
/// running and a second document launch prepares to hand off) and a leftover/stale socket
/// (after the first copy exits, or from an earlier Nightly build) must pass profile
/// validation, and the next launch must reclaim the stale socket and accept subsequent
/// document handoffs.
#[cfg(windows)]
#[test]
fn nightly_profile_allows_live_and_stale_single_instance_socket_for_handoff_and_reopen() {
use std::ffi::OsString;
use craft_nightly::{BuildFlavor, Profile, StartupOptions, launch_arguments, parse_startup, validate_and_prepare_root};
let profile = std::env::temp_dir().join(format!("cc-ni-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&profile);
std::fs::create_dir_all(&profile).unwrap();
let _cleanup = Cleanup(profile.clone());
let spec = crate::profile_root::spec();
let prepare_profile = |doc: &str| {
let argv = launch_arguments(&profile, &[OsString::from(doc)]);
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::new()).unwrap();
let Profile::NightlyV1(root) = launch.profile else {
panic!("expected NightlyV1 profile");
};
validate_and_prepare_root(&root, &spec).unwrap();
launch.passthrough_args
};
let sock_path = socket_path(Some(&profile)).unwrap();
std::fs::create_dir_all(sock_path.parent().unwrap()).unwrap();
if !can_bind(&sock_path) {
return;
}
// 1. Live socket in `<profile>\single-instance\*.sock`: second-document launch must not
// be refused by profile validation before handoff.
let listener = uds_windows::UnixListener::bind(&sock_path).unwrap();
assert_eq!(prepare_profile("second.dwg"), [OsString::from("second.dwg")]);
// 2. First instance exits leaving a leftover/stale socket behind: reopening must pass
// profile validation and reclaim the socket as the new primary instance.
drop(listener);
assert!(sock_path.exists(), "stale socket remains after exit");
assert_eq!(prepare_profile("reopen.dwg"), [OsString::from("reopen.dwg")]);
let Claim::Primary(server) = claim(&[], false, Some(&profile)) else {
panic!("failed to reclaim stale single-instance socket in nightly profile");
};
// 3. While the reclaimed primary instance is running (socket + election lock both live in
// `<profile>\single-instance`), launching a second document passes profile validation
// and hands off to the running instance.
let second_doc = profile.join("second.dwg").to_string_lossy().into_owned();
assert_eq!(prepare_profile(&second_doc), [OsString::from(&second_doc)]);
assert!(matches!(claim(std::slice::from_ref(&second_doc), true, Some(&profile)), Claim::HandedOff));
assert_eq!(server.take_paths(), [PathBuf::from(&second_doc)]);
}
}
+1
View File
@@ -0,0 +1 @@
9fa32aecf2759cd61bb216a958df68da619798f3
+25 -2
View File
@@ -166,6 +166,9 @@ pub struct Autosaver {
start: std::time::Instant,
#[cfg(not(target_arch = "wasm32"))]
last_beat: Option<f64>,
/// Who-has-it-open locks of the drawings open from files ([`crate::drawlock`]).
#[cfg(not(target_arch = "wasm32"))]
drawing_locks: crate::drawlock::Locks,
/// This app's lock files: one per folder, because SAVEFILEPATH can change while files remain
/// in the old folder. Each with the file it holds open for the system lock, or `None` where
/// locks don't work and only the file's age counts.
@@ -187,6 +190,8 @@ impl Autosaver {
#[cfg(not(target_arch = "wasm32"))]
last_beat: None,
#[cfg(not(target_arch = "wasm32"))]
drawing_locks: crate::drawlock::Locks::default(),
#[cfg(not(target_arch = "wasm32"))]
locks: Vec::new(),
}
}
@@ -456,7 +461,8 @@ mod native {
impl Autosaver {
/// Autosave what is due (writing in the background) and delete files no longer needed.
/// Returns how long until the next autosave is due, so the host can wake up for it.
/// Returns how long until the next autosave or drawing-lock heartbeat is due, so the host
/// can wake up for it.
pub fn tick(&mut self, s: &Session) -> Option<Duration> {
let now = self.start.elapsed().as_secs_f64();
self.reap();
@@ -465,7 +471,23 @@ mod native {
let jobs = self.plan(s, now, minutes, &dir);
self.perform(jobs);
self.heartbeat(&dir, now);
self.next_due(now, minutes).map(Duration::from_secs_f64)
self.drawing_locks.sync(s, &self.instance);
// The drawing locks need their heartbeat even with nothing to autosave (SAVETIME 0,
// every drawing saved): left untouched they go stale and another app takes them over.
let due = self.next_due(now, minutes).map(Duration::from_secs_f64);
due.into_iter().chain(self.drawing_locks.next_beat()).min()
}
/// Keep the drawing locks with `locks` instead of the default ones (e.g. a shorter
/// heartbeat, see [`crate::drawlock::Locks::with_heartbeat`]).
pub fn with_locks(mut self, locks: crate::drawlock::Locks) -> Self {
self.drawing_locks = locks;
self
}
/// What the drawing locks have to tell the user (someone else has a drawing open).
pub fn take_lock_notes(&mut self) -> Vec<String> {
self.drawing_locks.take_notes()
}
/// Autosave every drawing with changes not yet autosaved right away, without waiting for
@@ -641,6 +663,7 @@ mod native {
let _ = h.join();
}
self.busy.clear();
self.drawing_locks.release_all(&self.instance);
for path in self.files() {
discard(&path);
}
+20 -2
View File
@@ -247,14 +247,25 @@ struct Sizes {
text: f64,
above: bool,
text_style: String,
/// An annotative style: the annotation scale takes DIMSCALE's place, as for an annotative
/// dimension, so the sizes are unscaled and the text is annotative.
annotative: bool,
}
fn sizes(s: &Session) -> Sizes {
// The current style with the drawing's DIM* overrides (what SETVAR DIMTXT… sets).
let st = s.doc().ok().and_then(|d| d.dim_style(&style(s)).map(|st| st.with_overrides(&d.dim_overrides()))).unwrap_or_default();
let k = if st.scale > 0.0 { st.scale } else { 1.0 };
let dimscale = s.doc().map_or(1.0, |d| d.header.f64("DIMSCALE", 1.0));
let k = if st.annotative { 1.0 } else { st.effective_scale(dimscale) };
let text_style = if st.text_style.is_empty() { "Standard".to_string() } else { st.text_style.clone() };
Sizes { arrow: st.arrow_size * k, gap: st.text_gap.abs() * k, text: st.text_height * k, above: st.text_above != 0, text_style }
Sizes {
arrow: st.arrow_size * k,
gap: st.text_gap.abs() * k,
text: st.text_height * k,
above: st.text_above != 0,
text_style,
annotative: st.annotative,
}
}
/// LEADER's JSON form: a straight leader with an arrow through `pts`, and `text` (lines split at
@@ -348,5 +359,12 @@ pub(super) fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: boo
}
Annotation::None => None,
};
if let (true, Some(t)) = (z.annotative, annotation)
&& matches!(s.doc()?.entity(t).map(|e| &e.kind), Some(EntityKind::MText(_)))
{
let d = s.doc_mut()?;
let cur = d.current_anno_scale();
d.modify_entity(t, |e| cadcraft_doc::set_annotative(e, true, &cur))?;
}
Ok(std::iter::once(leader).chain(annotation).collect())
}
+14 -2
View File
@@ -57,7 +57,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("pdfbook", "Sheet Books to PDF...", run_pdfbook)
.menu(&["File", "Sheet Books to PDF..."])
.alias(&["printpdf", "pdfb"])
.params("{path?: \"DIR/NAME^NAME2.pdf\" (default: the drawing's file; a `^` splits the name into one book name per row of frames; else returns base64 `data` per book), names?: [book names], frameHeight?: mm (default 297), unit?: mm per drawing unit (default 1)} → {books: [{name, pages, bytes, path? | data}], skipped}: closed polylines of the frame height in model space are sheet frames; each row (same lower edge, bottom to top) is one PDF, its frames left to right one page each on the paper (ISO A-series, either orientation) they match")
.params("{path?: \"DIR/NAME^NAME2.pdf\" (default: the drawing's file; a `^` splits the name into one book name per row of frames; else returns base64 `data` per book), names?: [book names], frameHeight?: mm (default 297), unit?: mm per drawing unit (default 1)} → {books: [{name, pages, bytes, path? | data}], skipped}: closed polylines of the frame height in model space are sheet frames; each row (same lower edge, bottom to top) is one PDF, its frames left to right one page each on the paper (any standard size — ISO, JIS, ANSI — either orientation) they match")
.noundo(),
CommandSpec::new("attach", "Attach", |s, p| match str_param(p, "path").map(extension) {
Some(e) if super::image::is_image_ext(&e) => super::image::run_imageattach(s, p),
@@ -573,7 +573,8 @@ struct Frame {
landscape: bool,
}
/// The ISO/ANSI paper a frame of `w` x `h` mm fits (either orientation), and whether it is landscape.
/// The standard paper (ISO, JIS or ANSI) a frame of `w` x `h` mm fits (either orientation), and whether
/// it is landscape.
fn paper_for(w: f64, h: f64) -> Option<(&'static str, bool)> {
cadcraft_render::PAPER_SIZES.iter().find_map(|p| {
let (pw, ph) = (p.width_mm, p.height_mm);
@@ -878,6 +879,17 @@ mod tests {
let r = s.execute("preview", &json!({ "layout": "layout1", "paper": "A4", "landscape": true, "width": 600 })).unwrap();
assert_eq!((r["layout"].as_str(), r["width"].as_u64(), r["height"].as_u64()), (Some("Layout1"), Some(600), Some(424)));
assert_eq!(r["paper"], "ISO A4 (210.00 x 297.00 MM)");
// The bare B5 is the ISO size it always was; the JIS sheet needs its explicit name, and the
// Japanese postcards resolve by their names and their Japanese spelling.
let r = s.execute("preview", &json!({ "layout": "layout1", "paper": "B5", "landscape": false, "width": 400 })).unwrap();
assert_eq!(r["paper"], "ISO B5 (176.00 x 250.00 MM)");
assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(400), Some(568)));
let r = s.execute("preview", &json!({ "layout": "layout1", "paper": "B5 (JIS)", "landscape": false, "width": 400 })).unwrap();
assert_eq!(r["paper"], "JIS B5 (182.00 x 257.00 MM)");
assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(400), Some(565)));
let r = s.execute("preview", &json!({ "layout": "layout1", "paper": "はがき", "landscape": false, "width": 200 })).unwrap();
assert_eq!(r["paper"], "Japanese Postcard (100.00 x 148.00 MM)");
assert_eq!(r["height"], 296);
assert!(s.execute("preview", &json!({ "layout": "Nope" })).is_err());
assert!(s.execute("preview", &json!({ "paper": "Nope" })).is_err());
for p in [json!({ "scale": -1, "fit": false }), json!({ "scale": 1e-300, "fit": false }), json!({ "width": -5 }), json!({ "width": 1e30 })] {
+34
View File
@@ -326,6 +326,10 @@ pub fn specs() -> Vec<CommandSpec> {
.params("{path} | {data: base64, name} → {index, entities?, warnings: what reading left out}")
.enabled(always)
.noundo(),
CommandSpec::new("whohas", "Who Has", run_whohas)
.params("{path?: a drawing file (default: the current drawing's)} → {path, holder: {user, host, instance, opened} | null}")
.enabled(always)
.noundo(),
CommandSpec::new("close", "Close", run_close).menu(&["File", "Close"]).key("Cmd+W").params("{index?}").noundo(),
CommandSpec::new("closeall", "Close All", run_closeall).menu(&["File", "Close All"]).enabled(always).noundo(),
CommandSpec::new("qsave", "Save", run_qsave_reporting).menu(&["File", "Save"]).key("Cmd+S").alias(&["save"]).params("{path?}").noundo(),
@@ -552,6 +556,36 @@ fn run_open(s: &mut Session, p: &Value) -> Result<Value> {
Ok(opened(s, i, false))
}
/// WHOHAS: who has a drawing open, from its lock file ([`crate::drawlock`]): the current
/// drawing's, or the file `path`.
fn run_whohas(s: &mut Session, p: &Value) -> Result<Value> {
// Left out (or null): the current drawing's file; anything but text is an error, not the
// current drawing asked about by mistake.
let path = match p.get("path") {
None | Some(Value::Null) => s.state()?.path.clone().ok_or_else(|| bad("whohas", "the drawing has no file yet; pass `path`"))?,
Some(Value::String(path)) => path.clone(),
Some(_) => return Err(bad("whohas", "`path` must be a file path")),
};
// The web has no lock files to look at: an error, not "nobody has it open".
#[cfg(target_arch = "wasm32")]
{
let _ = path;
Err(bad("whohas", "drawing locks are not available on the web"))
}
#[cfg(not(target_arch = "wasm32"))]
{
// Under the automation roots, the lock beside a file outside them is not looked at.
crate::file_access::check_read(&path).map_err(|e| bad("whohas", e))?;
let holder = crate::drawlock::holder(std::path::Path::new(&path));
let msg = match &holder {
Some(h) => format!("{} is open by {}.", file_name(&path), h.describe()),
None => format!("Nobody has {} open (no current lock).", file_name(&path)),
};
s.echo(msg);
Ok(json!({ "path": path, "holder": holder }))
}
}
/// `close [index]`: cancel the running command, remove the drawing (default: active), keep the active index valid, and bump the document epoch; an unknown index is an error.
fn run_close(s: &mut Session, p: &Value) -> Result<Value> {
let i = p.get("index").and_then(Value::as_u64).map(|i| i as usize).unwrap_or(s.active);
+1 -1
View File
@@ -82,7 +82,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("pagesetup", "Page Setup Manager...", run_pagesetup)
.menu(&["File", "Page Setup Manager..."])
.params(
"{layout?: current, device?: plotter name (PLOTTERMANAGER) | \"None\", paper?: the device's paper | \"A4\"|\"A3\"|\"Letter\"|\"ANSI B\"|…, width?, height? (mm), landscape?, paperUnits?: \"mm\"|\"inches\" (one paper-space unit on the layout), margins?: [l,b,r,t] mm, lineweights?, plotArea?, scale?, scaleToFit?, center?, plotStyleTable?: \"monochrome.ctb\"|\"grayscale.ctb\"|\"default.ctb\"|\"None\"|…, displayPlotStyles?: bool, plotTransparency?: bool}",
"{layout?: current, device?: plotter name (PLOTTERMANAGER) | \"None\", paper?: the device's paper | \"A4\"|\"A3\"|\"Letter\"|\"ANSI B\"|\"B4 (JIS)\"|\"Japanese Postcard\"|…, width?, height? (mm), landscape?, paperUnits?: \"mm\"|\"inches\" (one paper-space unit on the layout), margins?: [l,b,r,t] mm, lineweights?, plotArea?, scale?, scaleToFit?, center?, plotStyleTable?: \"monochrome.ctb\"|\"grayscale.ctb\"|\"default.ctb\"|\"None\"|…, displayPlotStyles?: bool, plotTransparency?: bool}",
),
CommandSpec::new("plot", "Print...", |s, p| run_plot(s, &super::plotters::plot_options(s, p, "plot")?, "plot"))
.menu(&["File", "Print..."])
+76 -21
View File
@@ -19,7 +19,8 @@ fn offsettable(k: &EntityKind) -> bool {
}
/// Offset an entity by `dist` towards `side`. Returns the new geometry.
pub(crate) fn offset_kind(k: &EntityKind, dist: f64, side: Vec2) -> Option<EntityKind> {
/// `gap` is OFFSETGAPTYPE, used by polylines only.
pub(crate) fn offset_kind(k: &EntityKind, dist: f64, side: Vec2, gap: i64) -> Option<EntityKind> {
match k {
EntityKind::Line(l) => {
let ln = Line::new(l.a.xy(), l.b.xy());
@@ -64,7 +65,7 @@ pub(crate) fn offset_kind(k: &EntityKind, dist: f64, side: Vec2) -> Option<Entit
let t = nearest.tangent(0.5);
let left = t.cross(side - c) > 0.0;
let d = if left { dist } else { -dist };
offset_polyline(&pl, d).map(|vs| {
offset_polyline(&pl, d, gap).map(|vs| {
let mut k = lwpoly(vs, p.closed);
if let EntityKind::LwPolyline(n) = &mut k {
n.const_width = p.const_width;
@@ -135,35 +136,50 @@ pub(super) fn offset_points(pts: &[Vec2], d: f64, closed: bool) -> Vec<Vec2> {
out
}
/// Offset a polyline: offset each segment, then join neighbours at their intersections.
pub(crate) fn offset_polyline(pl: &Polyline, d: f64) -> Option<Vec<PolyVertex>> {
let segs: Vec<Segment> = pl.segments().iter().filter_map(|s| s.offset(d)).collect();
if segs.is_empty() {
/// Offset a polyline: offset each segment, then join neighbours at their intersections. `gap`
/// (OFFSETGAPTYPE) fills the gap at the outside of a corner between two lines: 0 extends both
/// copies to meet, 1 inserts an arc of radius `d` centred on the corner, 2 inserts a chamfer line.
pub(crate) fn offset_polyline(pl: &Polyline, d: f64, gap: i64) -> Option<Vec<PolyVertex>> {
let pairs: Vec<(Segment, Segment)> = pl.segments().iter().filter_map(|s| s.offset(d).map(|o| (*s, o))).collect();
if pairs.is_empty() {
return None;
}
let segs: Vec<Segment> = pairs.iter().map(|(_, o)| *o).collect();
let n = segs.len();
// Where each offset segment starts after joining it to the previous one.
let mut starts: Vec<Vec2> = Vec::with_capacity(n);
// At each joint: where the previous copy ends, an optional fill vertex (its start and bulge),
// and where this copy starts.
let mut joints: Vec<(Vec2, Option<PolyVertex>, Vec2)> = Vec::with_capacity(n);
for i in 0..n {
let s = segs.get(i)?;
starts.push(if i == 0 && !pl.closed {
s.start()
joints.push(if i == 0 && !pl.closed {
(s.start(), None, s.start())
} else {
let prev = segs.get((i + n - 1) % n)?;
join_point(prev, s).unwrap_or(s.start())
let corner = pairs.get(i)?.0.start();
// Only two segments that meet in the source have a corner to fill (a collapsed arc
// between them leaves none).
let adjacent = pairs.get((i + n - 1) % n)?.0.end().near(corner, 1e-9);
match gap_fill(prev, s, corner, d.abs(), if adjacent { gap } else { 0 }) {
Some((a, fill, b)) => (a, Some(fill), b),
None => {
let j = join_point(prev, s).unwrap_or(s.start());
(j, None, j)
}
}
});
}
let mut verts: Vec<PolyVertex> = Vec::new();
for i in 0..n {
let s = segs.get(i)?;
let start = *starts.get(i)?;
let end = if i + 1 < n {
*starts.get(i + 1)?
let start = joints.get(i)?.2;
let next = if i + 1 < n {
joints.get(i + 1)
} else if pl.closed {
*starts.first()?
joints.first()
} else {
s.end()
None
};
let end = next.map_or(s.end(), |j| j.0);
let bulge = match s {
Segment::Line(_) => 0.0,
Segment::Arc { arc, ccw } => {
@@ -179,6 +195,9 @@ pub(crate) fn offset_polyline(pl: &Polyline, d: f64) -> Option<Vec<PolyVertex>>
}
};
verts.push(PolyVertex { p: start, bulge, start_width: 0.0, end_width: 0.0 });
if let Some(fill) = next.and_then(|j| j.1) {
verts.push(fill);
}
}
if !pl.closed {
verts.push(PolyVertex::new(segs.last()?.end()));
@@ -186,6 +205,40 @@ pub(crate) fn offset_polyline(pl: &Polyline, d: f64) -> Option<Vec<PolyVertex>>
Some(verts)
}
/// The OFFSETGAPTYPE fill between the offset copies `a` and `b` of two lines meeting at `corner`,
/// when the copies leave a gap (the outside of the turn): where `a` ends, the fill vertex, and
/// where `b` starts. `None` keeps the extended join.
fn gap_fill(a: &Segment, b: &Segment, corner: Vec2, d: f64, gap: i64) -> Option<(Vec2, PolyVertex, Vec2)> {
let (Segment::Line(la), Segment::Line(lb)) = (a, b) else { return None };
if gap == 0 || la.a.near(la.b, 1e-12) || lb.a.near(lb.b, 1e-12) || a.end().near(b.start(), 1e-9) {
return None;
}
let (ta, tb) = (la.dir(), lb.dir());
let j = join_point(a, b)?;
if (j - la.b).dot(ta) <= 1e-9 {
return None;
}
let (ra, rb) = (la.b - corner, lb.a - corner);
match gap {
1 => {
let sweep = ra.cross(rb).atan2(ra.dot(rb));
Some((la.b, PolyVertex::with_bulge(la.b, cadcraft_geom::arc_to_bulge(sweep)), lb.a))
}
2 => {
// The chamfer is the line at distance `d` from the corner, square to the bisector.
let m = (ra + rb).normalized();
let (ka, kb) = (ta.dot(m), tb.dot(m));
if ka.abs() < 1e-9 || kb.abs() < 1e-9 {
return None;
}
let pa = la.b + ta * ((d - ra.dot(m)) / ka);
let pb = lb.a + tb * ((d - rb.dot(m)) / kb);
Some((pa, PolyVertex::new(pa), pb))
}
_ => None,
}
}
fn join_point(a: &Segment, b: &Segment) -> Option<Vec2> {
if a.end().near(b.start(), 1e-9) {
return Some(b.start());
@@ -202,7 +255,8 @@ pub(super) fn run_offset(s: &mut Session, p: &Value) -> Result<Value> {
}
let side = point_req("offset", p, "side")?;
let e = s.doc()?.entity(h).map(|e| (**e).clone()).ok_or_else(|| bad("offset", "no such object"))?;
let k = offset_kind(&e.kind, dist.abs(), side).ok_or_else(|| bad("offset", "cannot offset that object"))?;
let gap = s.doc()?.header.i64("OFFSETGAPTYPE", 0);
let k = offset_kind(&e.kind, dist.abs(), side, gap).ok_or_else(|| bad("offset", "cannot offset that object"))?;
let current_layer = match str_param(p, "layer").map(str::to_ascii_lowercase).as_deref() {
None | Some("source") => false,
Some("current") => true,
@@ -321,9 +375,10 @@ impl Interactive for OffsetM {
}
let (erase, current) = offset_options(s);
s.echo(format!(
"Current settings: Erase source={} Layer={} OFFSETGAPTYPE=0",
"Current settings: Erase source={} Layer={} OFFSETGAPTYPE={}",
if erase { "Yes" } else { "No" },
if current { "Current" } else { "Source" }
if current { "Current" } else { "Source" },
s.doc().map(|d| d.header.i64("OFFSETGAPTYPE", 0)).unwrap_or(0)
));
Ok(Step::Continue)
}
@@ -491,7 +546,7 @@ impl Interactive for OffsetM {
.fold(f64::INFINITY, f64::min)
}
};
match offset_kind(&e.kind, dist, p) {
match offset_kind(&e.kind, dist, p, s.doc()?.header.i64("OFFSETGAPTYPE", 0)) {
Some(k) => {
let before = s.state()?.doc.clone();
let (erase, current) = offset_options(s);
@@ -521,6 +576,6 @@ impl Interactive for OffsetM {
Some(x) => x,
None => crate::select::entity_distance(d, e, c, 1e-3),
};
offset_kind(&e.kind, dist, c).into_iter().collect()
offset_kind(&e.kind, dist, c, d.header.i64("OFFSETGAPTYPE", 0)).into_iter().collect()
}
}
+186 -47
View File
@@ -1,9 +1,11 @@
//! FILLET and CHAMFER with polyline segments (#466): two straight segments of one polyline
//! (adjacent, or with one segment between them, which the corner replaces), or a straight end
//! segment of an open polyline with a line, which joins the polyline.
//! (adjacent, or with one segment between them, which the corner replaces), or a segment of a
//! polyline with a line or with another polyline's segment, which joins the polyline. A closed
//! polyline opens at its first vertex, as in AutoCAD; an arc segment joins at radius 0 where the
//! other object crosses it.
use cadcraft_doc::{EntityKind, Handle, LwPolyline};
use cadcraft_geom::{Line, PolyVertex, Polyline, Segment, Vec2, arc_to_bulge, bulge_to_arc, line_line_infinite};
use cadcraft_geom::{Circle, Line, PolyVertex, Polyline, Segment, Vec2, arc_to_bulge, bulge_to_arc, line_circle, line_line_infinite};
use super::{curves, other, push_entity, set_kind};
use crate::cmd::helpers::{arc, line};
@@ -138,61 +140,205 @@ fn same_polyline(
Ok(Some(h))
}
/// An open polyline's straight end segment with a line: the corner is cut and the line joins
/// the polyline.
/// One side of a corner between two objects: the vertices kept, ordered so the corner comes
/// after the last, which is the kept end of the picked straight segment.
struct Run {
vs: Vec<PolyVertex>,
/// Whether the polyline was turned round to put the corner at its end.
reversed: bool,
}
impl Run {
fn inner(&self) -> Vec2 {
self.vs.last().map(|v| v.p).unwrap_or_default()
}
}
/// The run of a line kept on the picked side of the corner `x`.
fn line_run(ln: Line, pick: Vec2, x: Vec2) -> Run {
let keep = if (ln.a - x).dot(pick - x) >= (ln.b - x).dot(pick - x) { ln.a } else { ln.b };
Run { vs: vec![PolyVertex::new(keep)], reversed: false }
}
/// A closed polyline as an open one that starts and ends at its first vertex (the closing
/// segment becomes the last): joined to another object, AutoCAD opens it there. An open one as
/// it is.
fn opened(pl: &LwPolyline) -> LwPolyline {
let mut o = pl.clone();
if pl.closed
&& let Some(first) = pl.vertices.first()
{
o.vertices.push(PolyVertex { bulge: 0.0, ..*first });
o.closed = false;
}
o
}
/// The picked segment of an open polyline.
fn picked_seg(pl: &LwPolyline, pick: Vec2) -> Result<(usize, Segment)> {
let segs = Polyline { vertices: pl.vertices.clone(), closed: false }.segments();
let k = picked_segment(&segs, pick).ok_or_else(|| other("Select a polyline segment."))?;
segs.get(k).map(|sg| (k, *sg)).ok_or_else(|| other("Select a polyline segment."))
}
/// The picked straight segment of an open polyline, as a line.
fn picked_line(pl: &LwPolyline, pick: Vec2) -> Result<(usize, Line)> {
match picked_seg(pl, pick)? {
(k, Segment::Line(l)) => Ok((k, l)),
_ => Err(other("Fillet and chamfer work on straight polyline segments.")),
}
}
/// The run of a polyline kept on the picked side of the corner `x` on its segment `k`: what lies
/// beyond the corner on the other side goes, as in AutoCAD (an object crossing a segment keeps
/// the picked part of it and drops the rest of the polyline past the crossing).
fn pline_run(pl: &LwPolyline, k: usize, seg: Line, pick: Vec2, x: Vec2) -> Run {
let toward_start = (seg.a - x).dot(pick - x) >= (seg.b - x).dot(pick - x);
if toward_start {
Run { vs: pl.vertices.get(..=k).map(<[PolyVertex]>::to_vec).unwrap_or_default(), reversed: false }
} else {
let tail = pl.vertices.get(k + 1..).unwrap_or_default();
Run { vs: curves::reverse_vertices(tail, false), reversed: true }
}
}
/// A straight segment of an open polyline with a line or another open polyline's: the corner
/// is cut and the other object joins the polyline (`hp`), which keeps its handle and direction.
#[allow(clippy::too_many_arguments)]
fn polyline_and_line(
fn polyline_and_other(
s: &mut Session,
(hp, pl, pp): (Handle, &LwPolyline, Vec2),
(hl, ln, lp): (Handle, Line, Vec2),
(ho, ko, po): (Handle, &EntityKind, Vec2),
polyline_first: bool,
r: f64,
chamfer: Option<ChamferDistances>,
trim: bool,
) -> Result<Option<Handle>> {
let segs = Polyline { vertices: pl.vertices.clone(), closed: pl.closed }.segments();
let k = picked_segment(&segs, pp).ok_or_else(|| other("Select a polyline segment."))?;
let last = segs.len().checked_sub(1).ok_or_else(|| other("Select a polyline segment."))?;
if pl.closed || (k != 0 && k != last) {
return Err(other("A line fillets or chamfers with an end segment of an open polyline."));
}
let at_end = match segs.get(k) {
// A single segment: the end nearer the corner is cut.
Some(sg) if k == 0 && k == last => {
line_line_infinite(sg.start(), sg.end(), ln.a, ln.b).is_none_or(|(x, _, _)| x.dist(sg.end()) <= x.dist(sg.start()))
let pl = &opened(pl);
let other_opened = match ko {
EntityKind::LwPolyline(op) => Some(opened(op)),
_ => None,
};
let other_seg = match (ko, &other_opened) {
(EntityKind::Line(l), _) => (None, Line::new(l.a.xy(), l.b.xy())),
(EntityKind::LwPolyline(_), Some(op)) => {
let (ok, os) = picked_line(op, po)?;
(Some((op, ok)), os)
}
_ => k == last,
_ => return Err(other("A polyline fillets or chamfers with a line, or with another segment of itself.")),
};
// Work at the polyline's end; turn it round if the first segment was picked.
let mut vs = if at_end { pl.vertices.clone() } else { curves::reverse_vertices(&pl.vertices, false) };
let n = vs.len();
let (Some(inner), Some(end)) = (vs.get(n.wrapping_sub(2)).copied(), vs.get(n.wrapping_sub(1)).copied()) else {
return Err(other("Select a polyline segment."));
let (other_pl, oseg) = other_seg;
let (k, seg) = match picked_seg(pl, pp)? {
(k, Segment::Line(l)) => (k, l),
(k, Segment::Arc { .. }) => {
if r > 1e-12 || chamfer.is_some() {
return Err(other("A polyline's arc segment fillets with radius 0 only."));
}
if !trim {
return Ok(None);
}
return arc_segment_and_other(s, (hp, pl, k, pp), (ho, other_pl, oseg, po));
}
};
let x = line_line_infinite(seg.a, seg.b, oseg.a, oseg.b).map(|r| r.0).ok_or_else(|| other("Lines are parallel."))?;
let mine = pline_run(pl, k, seg, pp, x);
let theirs = match other_pl {
Some((op, ok)) => pline_run(op, ok, oseg, po, x),
None => line_run(oseg, po, x),
};
if inner.bulge.abs() > 1e-12 {
return Err(other("Fillet and chamfer work on straight polyline segments."));
}
let x = line_line_infinite(inner.p, end.p, ln.a, ln.b).map(|r| r.0).ok_or_else(|| other("Lines are parallel."))?;
let keep_line = if (ln.a - x).dot(lp - x) >= (ln.b - x).dot(lp - x) { ln.a } else { ln.b };
let side = |keep: Vec2| ((keep - x).normalized(), keep.dist(x));
let c = if polyline_first {
corner(x, side(inner.p), side(keep_line), r, chamfer)?
corner(x, side(mine.inner()), side(theirs.inner()), r, chamfer)?
} else {
let c = corner(x, side(keep_line), side(inner.p), r, chamfer)?;
let c = corner(x, side(theirs.inner()), side(mine.inner()), r, chamfer)?;
Corner { t1: c.t2, t2: c.t1, bulge: -c.bulge }
};
if !trim {
return add_loose(s, hp, &c);
}
vs.truncate(n - 1);
push_point(&mut vs, PolyVertex { p: c.t1, bulge: c.bulge, ..end });
push_point(&mut vs, PolyVertex { p: c.t2, bulge: 0.0, ..end });
push_point(&mut vs, PolyVertex { p: keep_line, bulge: 0.0, ..end });
if !at_end {
let tmpl = pl.vertices.get(k + 1).copied().unwrap_or_default();
let mut vs = mine.vs;
if let Some(l) = vs.last_mut() {
l.bulge = 0.0;
}
push_point(&mut vs, PolyVertex { p: c.t1, bulge: c.bulge, ..tmpl });
push_point(&mut vs, PolyVertex { p: c.t2, bulge: 0.0, ..tmpl });
// The other object's run, from its kept end at the corner out to its far end.
let back = curves::reverse_vertices(&theirs.vs, false);
for v in back {
push_point(&mut vs, if other_pl.is_some() { v } else { PolyVertex { p: v.p, bulge: 0.0, ..tmpl } });
}
if mine.reversed {
vs = curves::reverse_vertices(&vs, false);
}
set_kind(s, hp, EntityKind::LwPolyline(LwPolyline { vertices: vs, ..pl.clone() }))?;
s.doc_mut()?.remove_entity(hl);
s.doc_mut()?.remove_entity(ho);
Ok(Some(hp))
}
/// A polyline's arc segment `k` with a line, or another polyline's straight segment, that
/// crosses it (FILLET with radius 0): the arc is cut where they cross, nearest the picks, and
/// keeps its picked side; the other object's picked side joins the polyline there. Neither is
/// extended: a line that misses the arc is refused, as in AutoCAD.
fn arc_segment_and_other(
s: &mut Session,
(hp, pl, k, pp): (Handle, &LwPolyline, usize, Vec2),
(ho, other_pl, oseg, po): (Handle, Option<(&LwPolyline, usize)>, Line, Vec2),
) -> Result<Option<Handle>> {
let vs = &pl.vertices;
let (Some(start), Some(end)) = (vs.get(k).copied(), vs.get(k + 1).copied()) else { return Err(other("Select a polyline segment.")) };
let (ar, ccw) = bulge_to_arc(start.p, end.p, start.bulge).ok_or_else(|| other("Select a polyline segment."))?;
let total = (4.0 * start.bulge.atan()).abs();
let a0 = ar.center.angle_to(start.p);
// How far along the arc, from its start in its own direction, a point lies (radians).
let along = |q: Vec2| {
let d = ar.center.angle_to(q) - a0;
let d = if ccw { d } else { -d };
d.rem_euclid(std::f64::consts::TAU)
};
let eps = 1e-9 * (1.0 + total);
let x = line_circle(&oseg, &Circle::new(ar.center, ar.radius))
.into_iter()
.map(|h| h.0)
.filter(|q| q.is_finite() && along(*q) > eps && along(*q) < total - eps)
.min_by(|a, b| (a.dist(pp) + a.dist(po)).total_cmp(&(b.dist(pp) + b.dist(po))))
.ok_or_else(|| other("The line does not cross the polyline's arc segment."))?;
let tx = along(x);
let sub = |sweep: f64| arc_to_bulge(start.bulge.signum() * sweep);
let theirs = match other_pl {
Some((op, ok)) => pline_run(op, ok, oseg, po, x),
None => line_run(oseg, po, x),
};
let tmpl = end;
let plain = |v: PolyVertex| if other_pl.is_some() { v } else { PolyVertex { p: v.p, bulge: 0.0, ..tmpl } };
let mut out: Vec<PolyVertex> = Vec::new();
// Where the pick lies along the arc: one a little outside its sweep (within the pick box)
// counts at the nearer end, not always at the far one.
let picked = {
let a = along(pp);
if a > total && std::f64::consts::TAU - a < a - total { 0.0 } else { a.min(total) }
};
if picked <= tx {
// Keep the start of the arc: the polyline up to the crossing, then the other object.
out.extend(vs.get(..k).unwrap_or_default().iter().copied());
out.push(PolyVertex { bulge: sub(tx), ..start });
push_point(&mut out, PolyVertex { p: x, bulge: 0.0, ..tmpl });
for v in curves::reverse_vertices(&theirs.vs, false) {
push_point(&mut out, plain(v));
}
} else {
// Keep the end of the arc: the other object, then the polyline from the crossing on.
for v in &theirs.vs {
push_point(&mut out, plain(*v));
}
if let Some(l) = out.last_mut() {
l.bulge = 0.0;
}
push_point(&mut out, PolyVertex { p: x, bulge: sub(total - tx), ..tmpl });
out.extend(vs.get(k + 1..).unwrap_or_default().iter().copied());
}
set_kind(s, hp, EntityKind::LwPolyline(LwPolyline { vertices: out, ..pl.clone() }))?;
s.doc_mut()?.remove_entity(ho);
Ok(Some(hp))
}
@@ -217,20 +363,13 @@ pub(crate) fn fillet_pline(
if curves::is_locked(s, h1) || curves::is_locked(s, h2) {
return Err(other("The object is on a locked layer."));
}
let as_line = |k: &EntityKind| match k {
EntityKind::Line(l) => Some(Line::new(l.a.xy(), l.b.xy())),
_ => None,
};
let made = match (&e1.kind, &e2.kind) {
(EntityKind::LwPolyline(pl), _) if h1 == h2 => same_polyline(s, h1, pl, (p1, p2), r, chamfer, trim)?,
(EntityKind::LwPolyline(pl), k) if as_line(k).is_some() => {
let ln = as_line(k).ok_or_else(|| other("Select a line."))?;
polyline_and_line(s, (h1, pl, p1), (h2, ln, p2), true, r, chamfer, trim)?
}
(k, EntityKind::LwPolyline(pl)) if as_line(k).is_some() => {
let ln = as_line(k).ok_or_else(|| other("Select a line."))?;
polyline_and_line(s, (h2, pl, p2), (h1, ln, p1), false, r, chamfer, trim)?
// The first polyline picked keeps the result.
(EntityKind::LwPolyline(pl), k) if matches!(k, EntityKind::Line(_) | EntityKind::LwPolyline(_)) => {
polyline_and_other(s, (h1, pl, p1), (h2, k, p2), true, r, chamfer, trim)?
}
(k @ EntityKind::Line(_), EntityKind::LwPolyline(pl)) => polyline_and_other(s, (h2, pl, p2), (h1, k, p1), false, r, chamfer, trim)?,
(EntityKind::LwPolyline(_), _) | (_, EntityKind::LwPolyline(_)) => {
return Err(other("A polyline fillets or chamfers with a line, or with another segment of itself."));
}
+129
View File
@@ -823,6 +823,135 @@ fn offset_polyline_arc_bulge_follows_joined_endpoints() {
assert!((arc.radius - 4.0).abs() < 1e-6, "radius {}", arc.radius);
}
/// Offset the polyline `pl` by 1 towards `side` with OFFSETGAPTYPE = `gap`.
fn offset_with_gap(pts: Value, closed: bool, side: [f64; 2], gap: i64) -> cadcraft_doc::LwPolyline {
let mut s = Session::new();
s.execute("setvar", &json!({"name": "OFFSETGAPTYPE", "value": gap})).unwrap();
let pl = pline(&mut s, pts, closed);
s.execute("offset", &json!({"handle": pl, "distance": 1, "side": side})).unwrap();
poly(&last(&s))
}
fn area(p: &cadcraft_doc::LwPolyline) -> f64 {
Polyline { vertices: p.vertices.clone(), closed: p.closed }.area()
}
fn square() -> Value {
json!([[0, 0], [10, 0], [10, 10], [0, 10]])
}
#[test]
fn offset_gap_type_extends_fillets_or_chamfers_outside_corners() {
let p = offset_with_gap(square(), true, [12.0, 5.0], 0);
assert_eq!(p.vertices.len(), 4);
assert!(p.vertices.iter().all(|v| v.bulge == 0.0));
assert!((area(&p) - 144.0).abs() < 1e-9, "area {}", area(&p));
let p = offset_with_gap(square(), true, [12.0, 5.0], 1);
assert_eq!(p.vertices.len(), 8);
let q = (std::f64::consts::PI / 8.0).tan();
assert_eq!(p.vertices.iter().filter(|v| (v.bulge - q).abs() < 1e-9).count(), 4, "{:?}", p.vertices);
assert_eq!(p.vertices.iter().filter(|v| v.bulge == 0.0).count(), 4);
assert!((area(&p) - (140.0 + std::f64::consts::PI)).abs() < 1e-9, "area {}", area(&p));
for v in p.vertices.iter().filter(|v| v.bulge != 0.0) {
let (arc, ccw) = cadcraft_geom::bulge_to_arc(v.p, p.vertices[(p.vertices.iter().position(|w| w == v).unwrap() + 1) % 8].p, v.bulge).unwrap();
assert!(ccw && (arc.radius - 1.0).abs() < 1e-9, "{arc:?}");
assert!([(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)].iter().any(|&(x, y)| near(arc.center, x, y)), "{arc:?}");
}
let p = offset_with_gap(square(), true, [12.0, 5.0], 2);
assert_eq!(p.vertices.len(), 8);
assert!(p.vertices.iter().all(|v| v.bulge == 0.0));
let k = std::f64::consts::SQRT_2 - 1.0;
assert!(p.vertices.iter().any(|v| near(v.p, 10.0 + k, -1.0)) && p.vertices.iter().any(|v| near(v.p, 11.0, -k)), "{:?}", p.vertices);
// Every chamfer lies at distance 1 from its corner.
let corners = [Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(10.0, 10.0), Vec2::new(0.0, 10.0)];
for i in 0..8 {
let (a, b) = (p.vertices[i].p, p.vertices[(i + 1) % 8].p);
if a.dist(b) < 2.0 {
let c = corners.iter().min_by(|x, y| x.dist(a).total_cmp(&y.dist(a))).unwrap();
assert!((cadcraft_geom::Line::new(a, b).dist(*c) - 1.0).abs() < 1e-9, "chamfer {a:?}-{b:?}");
}
}
assert!((area(&p) - (144.0 - 2.0 * (1.0 - k) * (1.0 - k))).abs() < 1e-9, "area {}", area(&p));
}
#[test]
fn offset_gap_type_handles_open_outside_corners_in_both_orientations() {
let k = std::f64::consts::SQRT_2 - 1.0;
// A left turn offset to the right and a right turn offset to the left: the corner at (10, 0)
// is outside in both, with the copies at y = -1 / x = 11 and y = 1 / x = 11.
for (pts, side, sy) in [(json!([[0, 0], [10, 0], [10, 10]]), [5.0, -2.0], -1.0), (json!([[0, 0], [10, 0], [10, -10]]), [5.0, 2.0], 1.0)] {
let p = offset_with_gap(pts.clone(), false, side, 1);
assert_eq!(p.vertices.len(), 4, "{:?}", p.vertices);
assert!(near(p.vertices[1].p, 10.0, sy) && near(p.vertices[2].p, 11.0, 0.0), "{:?}", p.vertices);
let (arc, ccw) = cadcraft_geom::bulge_to_arc(p.vertices[1].p, p.vertices[2].p, p.vertices[1].bulge).unwrap();
assert_eq!(ccw, sy < 0.0, "{arc:?}");
assert!(near(arc.center, 10.0, 0.0) && (arc.radius - 1.0).abs() < 1e-9, "{arc:?}");
let p = offset_with_gap(pts, false, side, 2);
assert_eq!(p.vertices.len(), 4, "{:?}", p.vertices);
assert!(p.vertices.iter().all(|v| v.bulge == 0.0));
let (a, b) = (p.vertices[1].p, p.vertices[2].p);
assert!(near(a, 10.0 + k, sy) && near(b, 11.0, sy * k), "{:?}", p.vertices);
assert!((cadcraft_geom::Line::new(a, b).dist(Vec2::new(10.0, 0.0)) - 1.0).abs() < 1e-9, "chamfer {a:?}-{b:?}");
}
}
#[test]
fn offset_gap_type_leaves_inside_corners_and_arc_joints_alone() {
let inward: Vec<_> = (0..3).map(|g| offset_with_gap(square(), true, [5.0, 2.0], g).vertices).collect();
assert_eq!(inward[0].len(), 4);
assert!(inward.iter().all(|v| *v == inward[0]));
// An L's inside corner.
let l = json!([[0, 0], [10, 0], [10, 10]]);
let inside: Vec<_> = (0..3).map(|g| offset_with_gap(l.clone(), false, [8.0, 2.0], g).vertices).collect();
assert!(near(inside[0][1].p, 9.0, 1.0), "{:?}", inside[0]);
assert!(inside.iter().all(|v| *v == inside[0]));
// A line into an arc keeps its join.
let la = json!([[0, -5], {"p": [10, 0], "bulge": 1}, [10, 10]]);
let arcs: Vec<_> = (0..3).map(|g| offset_with_gap(la.clone(), false, [12.0, 5.0], g).vertices).collect();
assert!(arcs.iter().all(|v| *v == arcs[0]));
let outward: Vec<_> = (0..3).map(|g| offset_with_gap(la.clone(), false, [9.0, 5.0], g).vertices).collect();
assert!(outward.iter().all(|v| *v == outward[0]));
}
#[test]
fn offset_gap_type_leaves_lines_around_a_collapsed_arc_joined() {
// Offset 1 towards the centre of the radius-0.5 arc collapses it; the lines either side of
// it never met, so no gap type fills a corner between them.
let pts = json!([[-2, 0], {"p": [0, 0], "bulge": 1}, [0, -1], [1, -4]]);
let joined: Vec<_> = (0..3).map(|g| offset_with_gap(pts.clone(), false, [-0.3, -0.5], g).vertices).collect();
assert!(joined[0].iter().all(|v| v.bulge == 0.0), "arc collapsed: {:?}", joined[0]);
assert!(joined.iter().all(|v| *v == joined[0]), "{joined:?}");
}
#[test]
fn offset_echoes_the_gap_type() {
let mut s = Session::new();
s.execute("setvar", &json!({"name": "OFFSETGAPTYPE", "value": 1})).unwrap();
s.cmdline("offset").unwrap();
assert!(s.log.iter().any(|l| l.contains("OFFSETGAPTYPE=1")), "{:?}", s.log);
}
#[test]
fn interactive_offset_previews_and_makes_the_gap_type_fill() {
for (gap, bulged) in [(1, 4), (2, 0)] {
let mut s = Session::new();
s.execute("setvar", &json!({"name": "OFFSETGAPTYPE", "value": gap})).unwrap();
pline(&mut s, square(), true);
s.cmdline("offset 1").unwrap();
s.input(crate::Input::Point(Vec2::new(10.0, 5.0))).unwrap();
let shown: Vec<_> = s.preview(Vec2::new(12.0, 5.0)).into_iter().map(|e| poly(&e.kind)).collect();
assert_eq!(shown.len(), 1, "gap {gap}");
s.input(crate::Input::Point(Vec2::new(12.0, 5.0))).unwrap();
let made = poly(&last(&s));
assert_eq!(made.vertices.len(), 8, "gap {gap}: {:?}", made.vertices);
assert_eq!(made.vertices.iter().filter(|v| v.bulge != 0.0).count(), bulged, "gap {gap}: {:?}", made.vertices);
assert_eq!(shown.first().map(|p| &p.vertices), Some(&made.vertices), "gap {gap}: preview matches the copy");
}
}
#[test]
fn offset_elliptical_arc_follows_picked_side() {
let max_x = |side: Value| {
+340
View File
@@ -0,0 +1,340 @@
//! Drawing locks: who has a drawing open (WHOHAS), for drawings shared on a network folder (#540).
//!
//! While a drawing opened from a file is open, the app keeps a small lock file beside it,
//! `.<file name>.cadcraft-lock`, holding who opened it (user, computer, app instance, when).
//! The file's modification time is its heartbeat: the app touches it every [`HEARTBEAT_SECS`],
//! and a lock not touched for [`STALE_SECS`] belongs to an app that is no longer running (a crash
//! leaves it behind, and it is then ignored and taken over).
//!
//! A lock only informs: opening a drawing someone else has open says so on the command line and
//! in the status bar, and the drawing opens anyway (their lock stays theirs). Only lock files of
//! this app instance are ever deleted. The format is CADCraft's own (JSON), not AutoCAD's `.dwl`.
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
/// How often a held lock is touched, in seconds.
pub const HEARTBEAT_SECS: u64 = 60;
/// A lock not touched for this long is stale, in seconds.
pub const STALE_SECS: u64 = 5 * 60;
/// Largest lock file read (bytes): anything bigger isn't ours.
#[cfg(not(target_arch = "wasm32"))]
const MAX_LOCK_BYTES: u64 = 4096;
/// Who holds a lock.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Holder {
pub user: String,
pub host: String,
/// The app instance (see [`crate::autosave::Autosaver::instance`]).
pub instance: String,
/// When the drawing was opened, in seconds since 1970.
pub opened: u64,
}
/// The lock file of the drawing at `drawing`.
pub fn lock_path(drawing: &Path) -> PathBuf {
let name = drawing.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
drawing.with_file_name(format!(".{name}.cadcraft-lock"))
}
/// Whether drawings at `path` get a lock: drawing files only (not exports).
#[cfg(not(target_arch = "wasm32"))]
fn lockable(path: &str) -> bool {
let ext = Path::new(path).extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
matches!(ext.as_str(), "dwg" | "dxf" | "dwt")
}
/// `secs` since 1970 as `YYYY-MM-DD HH:MM` (UTC).
pub fn utc(secs: u64) -> String {
let days = (secs / 86_400) as i64;
let (h, m) = ((secs % 86_400) / 3600, (secs % 3600) / 60);
// Civil date from days since 1970 (Howard Hinnant's algorithm).
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let mo = if mp < 10 { mp + 3 } else { mp - 9 };
let y = yoe + era * 400 + i64::from(mo <= 2);
format!("{y:04}-{mo:02}-{d:02} {h:02}:{m:02} UTC")
}
impl Holder {
/// "user on host since …".
pub fn describe(&self) -> String {
let who = if self.user.is_empty() { "someone" } else { self.user.as_str() };
let host = if self.host.is_empty() { String::new() } else { format!(" on {}", self.host) };
format!("{who}{host}, since {}", utc(self.opened))
}
}
#[cfg(not(target_arch = "wasm32"))]
pub use native::*;
#[cfg(not(target_arch = "wasm32"))]
mod native {
use std::collections::{HashMap, HashSet};
use std::time::{Duration, Instant, SystemTime};
use super::{HEARTBEAT_SECS, Holder, MAX_LOCK_BYTES, Path, PathBuf, STALE_SECS, lock_path, lockable};
use crate::Session;
/// This user's name, from the environment.
fn user() -> String {
["USER", "USERNAME", "LOGNAME"].iter().find_map(|k| std::env::var(k).ok().filter(|v| !v.trim().is_empty())).unwrap_or_default()
}
/// This computer's name (looked up once).
fn host() -> String {
static HOST: std::sync::OnceLock<String> = std::sync::OnceLock::new();
HOST.get_or_init(|| {
if let Some(h) = ["COMPUTERNAME", "HOSTNAME"].iter().find_map(|k| std::env::var(k).ok().filter(|v| !v.trim().is_empty())) {
return h;
}
std::process::Command::new("hostname")
.stdin(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.output()
.ok()
.map(|o| String::from_utf8_lossy(&o.stdout).trim().chars().take(255).collect())
.unwrap_or_default()
})
.clone()
}
fn now_secs() -> u64 {
SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
}
/// The holder of the lock on `drawing` while its lock is fresh (touched within
/// [`STALE_SECS`]); `None` when there is no lock, it is stale or it isn't one of ours.
pub fn holder(drawing: &Path) -> Option<Holder> {
let lock = lock_path(drawing);
let meta = std::fs::metadata(&lock).ok()?;
if !meta.is_file() || meta.len() > MAX_LOCK_BYTES {
return None;
}
// A time in the future (clock changes, another computer's clock) counts as fresh.
let age = meta.modified().ok().map(|m| SystemTime::now().duration_since(m).unwrap_or_default())?;
if age >= Duration::from_secs(STALE_SECS) {
return None;
}
serde_json::from_slice(&std::fs::read(&lock).ok()?).ok()
}
/// This instance's lock contents for `drawing`, staged next to its lock file.
fn stage(drawing: &Path, h: &Holder) -> std::io::Result<PathBuf> {
let lock = lock_path(drawing);
let tmp = lock.with_file_name(format!(
"{}.{}.tmp",
lock.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(),
std::process::id()
));
std::fs::write(&tmp, serde_json::to_vec(h).unwrap_or_default())?;
Ok(tmp)
}
/// Write this instance's lock on `drawing` (staged, then renamed over any stale one).
fn write(drawing: &Path, h: &Holder) -> std::io::Result<()> {
let tmp = stage(drawing, h)?;
std::fs::rename(&tmp, lock_path(drawing)).inspect_err(|_| {
let _ = std::fs::remove_file(&tmp);
})
}
/// Take the lock on `drawing` when there is none or it is stale: whether it is now this
/// instance's. With no lock file it is created atomically (two apps opening the drawing at
/// once can't both get it); a stale one is replaced and read back, so of two apps taking it
/// over at once only the last one keeps it.
fn claim(drawing: &Path, h: &Holder) -> std::io::Result<bool> {
let lock = lock_path(drawing);
if lock.exists() {
// Taken meanwhile by another app (its lock is fresh again): leave it.
if holder(drawing).is_some_and(|o| o.instance != h.instance) {
return Ok(false);
}
write(drawing, h)?;
} else {
let tmp = stage(drawing, h)?;
// A hard link appears with the whole lock written, or fails when the lock exists.
let linked = std::fs::hard_link(&tmp, &lock);
let _ = std::fs::remove_file(&tmp);
match linked {
Ok(()) => return Ok(true),
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => return Ok(false),
// No hard links on this file system: create it only if it isn't there.
Err(_) => {
use std::io::Write;
match std::fs::OpenOptions::new().write(true).create_new(true).open(&lock) {
Ok(mut f) => f.write_all(&serde_json::to_vec(h).unwrap_or_default())?,
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => return Ok(false),
Err(e) => return Err(e),
}
}
}
}
let back = std::fs::read(&lock).ok().and_then(|b| serde_json::from_slice::<Holder>(&b).ok());
Ok(back.is_some_and(|b| b.instance == h.instance))
}
/// Touch a held lock (its modification time is the heartbeat).
fn touch(drawing: &Path) -> std::io::Result<()> {
std::fs::OpenOptions::new().write(true).open(lock_path(drawing))?.set_modified(SystemTime::now())
}
/// Delete the lock on `drawing` if it is still `instance`'s.
fn release(drawing: &Path, instance: &str) {
let lock = lock_path(drawing);
let ours = std::fs::read(&lock).ok().and_then(|b| serde_json::from_slice::<Holder>(&b).ok()).is_some_and(|h| h.instance == instance);
if ours {
let _ = std::fs::remove_file(lock);
}
}
/// The note that `h` also has the drawing at `path` (named `p`) open.
fn also_open(path: &Path, p: &str, h: &Holder) -> String {
let name = path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| p.to_string());
format!("{name} is also open by {}. Saving it here can overwrite their changes (or theirs yours).", h.describe())
}
/// This instance's lock contents.
fn me(instance: &str) -> Holder {
Holder { user: user(), host: host(), instance: instance.to_string(), opened: now_secs() }
}
/// The drawing locks of one running app.
pub struct Locks {
/// How often held locks are touched and others' locks looked at again.
beat: Duration,
/// Drawings this app holds the lock of, with when it was last touched.
held: HashMap<String, Instant>,
/// Drawings open here that someone else holds, with when that was last checked.
others: HashMap<String, Instant>,
/// What to tell the user (someone else has a drawing open), taken by [`Locks::take_notes`].
notes: Vec<String>,
}
impl Default for Locks {
fn default() -> Self {
Locks::with_heartbeat(Duration::from_secs(HEARTBEAT_SECS))
}
}
impl Locks {
/// Locks touched (and others' looked at again) every `beat` instead of [`HEARTBEAT_SECS`].
pub fn with_heartbeat(beat: Duration) -> Self {
Locks { beat, held: HashMap::new(), others: HashMap::new(), notes: Vec::new() }
}
/// Bring the locks in line with the drawings open in `s`: take the lock of a drawing just
/// opened from a file (or note who else has it open), touch held locks every
/// [`HEARTBEAT_SECS`], take over a lock its holder let go stale, and release the locks of
/// drawings no longer open here (closed, or saved under another name).
pub fn sync(&mut self, s: &Session, instance: &str) {
let open: HashSet<String> = s.docs.iter().filter_map(|d| d.path.clone()).filter(|p| lockable(p)).collect();
let gone: Vec<String> = self.held.keys().filter(|p| !open.contains(*p)).cloned().collect();
for p in gone {
release(Path::new(&p), instance);
self.held.remove(&p);
}
self.others.retain(|p, _| open.contains(p));
let beat = self.beat;
for p in open {
let path = Path::new(&p);
if let Some(at) = self.held.get(&p) {
if at.elapsed() < beat {
continue;
}
// Still ours? Another app may have taken it over (this one was asleep past
// STALE_SECS): then it is theirs, and noted below.
if holder(path).is_none_or(|h| h.instance == instance) {
// A lock removed meanwhile (by hand, a sync tool) is written again.
if touch(path).is_err() {
let _ = write(path, &me(instance));
}
self.held.insert(p, Instant::now());
continue;
}
self.held.remove(&p);
}
if let Some(at) = self.others.get(&p)
&& at.elapsed() < beat
{
continue;
}
match holder(path) {
Some(h) if h.instance != instance => {
if !self.others.contains_key(&p) {
self.notes.push(also_open(path, &p, &h));
}
self.others.insert(p, Instant::now());
}
_ => match claim(path, &me(instance)) {
// Another app took it first: tell the user as for a lock found.
Ok(false) => {
if let Some(h) = holder(path).filter(|h| h.instance != instance) {
self.notes.push(also_open(path, &p, &h));
}
self.others.insert(p, Instant::now());
}
// No lock, a stale one or our own: now ours (a folder we can't write
// to just gets no lock).
_ => {
self.others.remove(&p);
self.held.insert(p, Instant::now());
}
},
}
}
}
/// How long until [`Locks::sync`] next has a lock to touch or look at again (the
/// shortest wait over held locks and others'), so an idle host still wakes up for it;
/// `None` when no drawing open here has a lock.
pub fn next_beat(&self) -> Option<Duration> {
self.held.values().chain(self.others.values()).map(|at| self.beat.saturating_sub(at.elapsed())).min()
}
/// The notes [`Locks::sync`] made since the last call.
pub fn take_notes(&mut self) -> Vec<String> {
std::mem::take(&mut self.notes)
}
/// The app is closing: release every lock it holds.
pub fn release_all(&mut self, instance: &str) {
for (p, _) in self.held.drain() {
release(Path::new(&p), instance);
}
self.others.clear();
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Of two apps claiming a drawing that has no lock, only the first gets it: the second
/// finds it taken and leaves it. A stale lock is taken over.
#[test]
fn only_one_app_claims_a_free_lock() {
let dir = std::env::temp_dir().join(format!("cadcraft-claim-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("Plan.dxf");
std::fs::write(&file, b"").unwrap();
assert!(claim(&file, &me("1-a")).unwrap());
assert!(!claim(&file, &me("2-b")).unwrap(), "a fresh lock stays the first app's");
assert_eq!(holder(&file).map(|h| h.instance), Some("1-a".to_string()));
assert!(claim(&file, &me("1-a")).unwrap(), "its own lock is still its own");
let stale = SystemTime::now() - Duration::from_secs(STALE_SECS + 60);
std::fs::OpenOptions::new().write(true).open(lock_path(&file)).unwrap().set_modified(stale).unwrap();
assert!(claim(&file, &me("2-b")).unwrap(), "a stale lock is taken over");
assert_eq!(holder(&file).map(|h| h.instance), Some("2-b".to_string()));
let _ = std::fs::remove_dir_all(&dir);
}
}
}
@@ -57,6 +57,7 @@ pub const FILES: &[&str] = &[
"stylesmanager",
"tableexport",
"wblock",
"whohas",
"xattach",
"xbind",
"xopen",
+1
View File
@@ -19,6 +19,7 @@ pub mod blockedit;
pub mod capped_read;
pub mod cmd;
pub mod doc_path;
pub mod drawlock;
pub mod file_access;
mod finite;
pub mod grip_dims;
+2
View File
@@ -66,6 +66,8 @@ const HEADER: &[(&str, Kind, Def)] = &[
// Negative: Through (OFFSET picks a point).
("OFFSETDIST", Kind::AnyReal, Def::Real(-1.0)),
("OFFSETERASE", Kind::Choice(&[0, 1]), Def::Int(0)),
// 0: extend offset lines to meet at corners; 1: fill the gap with an arc; 2: with a chamfer.
("OFFSETGAPTYPE", Kind::Choice(&[0, 1, 2]), Def::Int(0)),
("OFFSETLAYER", Kind::Choice(&[0, 1]), Def::Int(0)),
// The width a new polyline starts at; PLINE's Width and Halfwidth answers set it.
("PLINEWID", Kind::Real { min: 0.0, strict: false }, Def::Real(0.0)),
+107
View File
@@ -0,0 +1,107 @@
//! Drawing locks (#540): an app with a drawing open keeps a lock beside it; another app opening
//! the same drawing is told who has it, without taking the lock; the lock goes when the drawing
//! closes, and a stale one is taken over.
use std::time::{Duration, SystemTime};
use cadcraft_engine::Session;
use cadcraft_engine::autosave::{self, Autosaver};
use cadcraft_engine::cmd::file::{IoHooks, set_io};
use cadcraft_engine::drawlock::{Locks, holder, lock_path};
use serde_json::json;
fn session_with(path: &str) -> Session {
set_io(IoHooks {
read: |b, n| cadcraft_io::read(b, n).map_err(|e| e.to_string()),
write: |d, n| cadcraft_io::write(d, n).map_err(|e| e.to_string()),
plot: None,
});
let mut s = Session::new();
s.execute("open", &json!({ "path": path })).unwrap();
s
}
#[test]
fn a_second_app_is_told_who_has_the_drawing_and_the_lock_follows_the_first() {
let dir = std::env::temp_dir().join(format!("cadcraft-lock-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("Shared Plan.dxf");
std::fs::write(&file, cadcraft_io::write(&cadcraft_engine::doc::Drawing::new_metric(), "x.dxf").unwrap()).unwrap();
let path = file.to_string_lossy().to_string();
let now = Duration::ZERO;
let mut a = session_with(&path);
let mut la = Locks::with_heartbeat(now);
la.sync(&a, "1-a");
assert!(lock_path(&file).file_name().unwrap().to_string_lossy().starts_with(".Shared Plan.dxf"));
assert_eq!(holder(&file).map(|h| h.instance), Some("1-a".to_string()));
assert!(la.take_notes().is_empty());
// A second app opening it is told, and the lock stays the first app's.
let b = session_with(&path);
let mut lb = Locks::with_heartbeat(now);
lb.sync(&b, "2-b");
let notes = lb.take_notes();
assert_eq!(notes.len(), 1, "{notes:?}");
assert!(notes[0].starts_with("Shared Plan.dxf is also open by ") && notes[0].contains("UTC"), "{}", notes[0]);
lb.sync(&b, "2-b");
assert!(lb.take_notes().is_empty(), "said once");
assert_eq!(holder(&file).map(|h| h.instance), Some("1-a".to_string()));
// WHOHAS names the holder.
let mut b = b;
// A `path` that isn't a file path is refused, not taken as the current drawing.
assert!(b.execute("whohas", &json!({ "path": 7 })).is_err());
let r = b.execute("whohas", &json!({})).unwrap();
assert_eq!(r["holder"]["instance"], "1-a");
// Releasing what isn't ours leaves it alone.
lb.release_all("2-b");
assert_eq!(holder(&file).map(|h| h.instance), Some("1-a".to_string()));
// The first app closes the drawing: its lock goes, and the second takes it.
a.execute("close", &json!({})).unwrap();
la.sync(&a, "1-a");
assert!(holder(&file).is_none());
lb.sync(&b, "2-b");
assert_eq!(holder(&file).map(|h| h.instance), Some("2-b".to_string()));
// A lock left by a crashed app (not touched for a while) is taken over without a note.
let stale = SystemTime::now() - Duration::from_secs(cadcraft_engine::drawlock::STALE_SECS + 60);
std::fs::OpenOptions::new().write(true).open(lock_path(&file)).unwrap().set_modified(stale).unwrap();
assert!(holder(&file).is_none(), "stale");
let c = session_with(&path);
let mut lc = Locks::with_heartbeat(now);
lc.sync(&c, "3-c");
assert!(lc.take_notes().is_empty());
assert_eq!(holder(&file).map(|h| h.instance), Some("3-c".to_string()));
// The app whose lock was taken over notices on its next heartbeat and doesn't touch it.
lb.sync(&b, "2-b");
assert_eq!(lb.take_notes().len(), 1, "told who has it now");
assert_eq!(holder(&file).map(|h| h.instance), Some("3-c".to_string()));
lc.release_all("3-c");
assert!(!lock_path(&file).exists());
let _ = std::fs::remove_dir_all(&dir);
}
/// An idle app with every drawing saved (and SAVETIME 0) still wakes up for the lock heartbeat:
/// otherwise its lock goes stale and another app takes the drawing over without a word.
#[test]
fn an_idle_app_wakes_up_for_the_lock_heartbeat() {
let dir = std::env::temp_dir().join(format!("cadcraft-lock-idle-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("Saved Plan.dxf");
std::fs::write(&file, cadcraft_io::write(&cadcraft_engine::doc::Drawing::new_metric(), "x.dxf").unwrap()).unwrap();
let s = session_with(&file.to_string_lossy());
assert!(!s.docs.iter().any(|d| d.is_dirty()), "nothing to autosave");
autosave::set_savetime(0);
let beat = Duration::from_secs(2);
let mut a = Autosaver::new("1-idle").with_locks(Locks::with_heartbeat(beat));
let wait = a.tick(&s);
assert_eq!(holder(&file).map(|h| h.instance), Some("1-idle".to_string()));
assert!(wait.is_some_and(|d| d <= beat), "{wait:?}");
a.shutdown();
assert!(!lock_path(&file).exists());
let _ = std::fs::remove_dir_all(&dir);
}
@@ -0,0 +1,33 @@
//! #1056: a leader's annotation is drawn at the dimension text size, DIMTXT × DIMSCALE, like the
//! dimensions beside it.
use cadcraft_engine::Session;
use cadcraft_engine::doc::EntityKind;
use serde_json::json;
#[test]
fn leader_text_takes_dimscale() {
let mut s = Session::new();
s.execute("dimstyle", &json!({"name": "S25", "current": true, "DIMSCALE": 25, "DIMTXT": 0.25, "DIMASZ": 0.2})).unwrap();
s.execute("leader", &json!({"points": [[0, 0], [20, 20], [30, 20]], "text": "NOTE"})).unwrap();
let h = s.doc().unwrap().model.iter().find_map(|e| if let EntityKind::MText(m) = &e.kind { Some(m.height) } else { None }).unwrap();
assert!((h - 6.25).abs() < 1e-9, "{h}");
}
/// An annotative dimension style: the annotation scale takes DIMSCALE's place, as for an
/// annotative dimension, so the text is DIMTXT high and annotative, scaled with the dimension.
#[test]
fn leader_text_of_an_annotative_style_is_annotative() {
let mut s = Session::new();
s.execute("dimstyle", &json!({"name": "A", "current": true, "DIMSCALE": 2, "DIMTXT": 0.25, "annotative": true})).unwrap();
s.execute("leader", &json!({"points": [[0, 0], [20, 20], [30, 20]], "text": "NOTE"})).unwrap();
let d = s.doc().unwrap();
let e = d.model.iter().find(|e| matches!(e.kind, EntityKind::MText(_))).unwrap();
let EntityKind::MText(m) = &e.kind else { unreachable!() };
assert!((m.height - 0.25).abs() < 1e-9, "{}", m.height);
assert!(cadcraft_engine::doc::is_annotative(e), "annotative like the style");
// Drawn at an annotation scale of 1:50, it is as high as the dimension text: DIMTXT × 50.
let scaled = cadcraft_engine::doc::anno_scaled(e, 50.0);
let EntityKind::MText(m) = &scaled.kind else { unreachable!() };
assert!((m.height - 12.5).abs() < 1e-9, "{}", m.height);
}
+1
View File
@@ -98,6 +98,7 @@ mod layoff_repeat;
mod layout_prompts;
mod leader_command;
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod leader_text_scale;
mod lisp_corpus;
mod lisp_findfile;
mod lisp_undo_in_routine;
+139 -1
View File
@@ -567,6 +567,144 @@ fn fillet_and_chamfer_a_line_into_a_polyline() {
assert_eq!(count(&s), 1);
}
#[test]
fn a_line_crossing_a_polyline_end_segment_keeps_the_picked_side() {
// An L whose end segment a line crosses. Picked right of the crossing, the polyline keeps that
// part and drops the rest past the crossing, the line's picked part joining it (as AutoCAD).
let mut s = Session::new();
let p = pline(&mut s, &[[0.0, 1.0], [0.0, 0.0], [4.0, 0.0]], false);
let l = h(&s.execute("line", &json!({ "points": [[2, -1], [2, 1.5]] })).unwrap());
s.execute("fillet", &json!({ "h1": l, "p1": [2, 1], "h2": p, "p2": [3, 0], "radius": 0 })).unwrap();
assert_eq!(verts(&s, &p), vec![(2.0, 1.5, 0.0), (2.0, 0.0, 0.0), (4.0, 0.0, 0.0)]);
assert_eq!(count(&s), 1);
// Picked left of it, the L stays and the line's lower part joins.
let mut s = Session::new();
let p = pline(&mut s, &[[0.0, 1.0], [0.0, 0.0], [4.0, 0.0]], false);
let _ = h(&s.execute("line", &json!({ "points": [[2, -1], [2, 1.5]] })).unwrap());
s.script("FILLET R 0 1,0 2,-0.5\n").unwrap();
assert_eq!(verts(&s, &p), vec![(0.0, 1.0, 0.0), (0.0, 0.0, 0.0), (2.0, 0.0, 0.0), (2.0, -1.0, 0.0)]);
}
#[test]
fn fillet_joins_two_polylines_at_their_end_segments() {
// A wall line short of the corner and an open outline ending under it: one polyline, as AutoCAD.
let mut s = Session::new();
let a = pline(&mut s, &[[0.0, 8.55], [0.0, 1.25]], false);
let b = pline(&mut s, &[[0.15, 0.15], [1.0, 0.15], [1.0, 0.0], [0.0, 0.0]], false);
s.execute("fillet", &json!({ "h1": a, "p1": [0, 5], "h2": b, "p2": [0.5, 0], "radius": 0 })).unwrap();
assert_eq!(verts(&s, &a), vec![(0.0, 8.55, 0.0), (0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 0.15, 0.0), (0.15, 0.15, 0.0)]);
assert_eq!(count(&s), 1);
// The other picked first keeps its direction; a radius rounds the corner.
let mut s = Session::new();
let a = pline(&mut s, &[[0.0, 8.0], [0.0, 2.0]], false);
let b = pline(&mut s, &[[5.0, 5.0], [5.0, 0.0], [1.0, 0.0]], false);
s.execute("fillet", &json!({ "h1": b, "p1": [3, 0], "h2": a, "p2": [0, 5], "radius": 1 })).unwrap();
assert_eq!(verts(&s, &b), vec![(5.0, 5.0, 0.0), (5.0, 0.0, 0.0), (1.0, 0.0, -quarter()), (0.0, 1.0, 0.0), (0.0, 8.0, 0.0)]);
assert_eq!(count(&s), 1);
}
#[test]
fn fillet_joins_a_polyline_end_segment_crossing_another_polylines_middle_segment() {
// As AutoCAD: each keeps its picked side of the crossing, the rest past it goes (here the
// stub below the crossing, and the middle segment's left part with the leg after it).
let mut s = Session::new();
let a = pline(&mut s, &[[0.0, -0.4], [0.0, 0.15], [1.4, 0.15], [1.4, 1.9], [1.2, 1.9]], false);
let b = pline(&mut s, &[[3.4, -0.5], [3.4, 0.0], [-0.7, 0.0], [-0.7, -3.0]], false);
s.execute("fillet", &json!({ "h1": a, "p1": [0, 0.1], "h2": b, "p2": [2, 0], "radius": 0 })).unwrap();
assert_eq!(
verts(&s, &a),
vec![(3.4, -0.5, 0.0), (3.4, 0.0, 0.0), (0.0, 0.0, 0.0), (0.0, 0.15, 0.0), (1.4, 0.15, 0.0), (1.4, 1.9, 0.0), (1.2, 1.9, 0.0)]
);
assert_eq!(count(&s), 1);
}
/// A closed polyline filleted with a line opens at its first vertex, as AutoCAD does: the picked
/// side of the picked segment joins the line, either side, and the result is open. AutoCAD's
/// results for these shapes (a 4 x 3 RECTANG with a line short of it, crossing it, and level
/// with its right side).
#[test]
fn a_closed_polyline_opens_at_its_first_vertex_to_join_a_line() {
let rect = |s: &mut Session, x: f64| pline(s, &[[x, 0.0], [x + 4.0, 0.0], [x + 4.0, 3.0], [x, 3.0]], true);
let line = |s: &mut Session, a: [f64; 2], b: [f64; 2]| h(&s.execute("line", &json!({ "points": [a, b] })).unwrap());
let open = |s: &Session, p: &str| match kind(s, p) {
EntityKind::LwPolyline(pl) => !pl.closed,
_ => false,
};
// A line short of the top side, the top's left part picked.
let mut s = Session::new();
let p = rect(&mut s, 0.0);
let l = line(&mut s, [2.0, 4.5], [2.0, 3.6]);
s.execute("fillet", &json!({ "h1": l, "p1": [2, 4.2], "h2": p, "p2": [1, 3], "radius": 0 })).unwrap();
assert_eq!(verts(&s, &p), vec![(2.0, 4.5, 0.0), (2.0, 3.0, 0.0), (0.0, 3.0, 0.0), (0.0, 0.0, 0.0)]);
assert!(open(&s, &p));
assert_eq!(count(&s), 1);
// Its right part: the other way round the rectangle.
let mut s = Session::new();
let p = rect(&mut s, 0.0);
let l = line(&mut s, [2.0, 4.5], [2.0, 3.6]);
s.execute("fillet", &json!({ "h1": l, "p1": [2, 4.2], "h2": p, "p2": [3, 3], "radius": 0 })).unwrap();
assert_eq!(verts(&s, &p), vec![(0.0, 0.0, 0.0), (4.0, 0.0, 0.0), (4.0, 3.0, 0.0), (2.0, 3.0, 0.0), (2.0, 4.5, 0.0)]);
// A line crossing the top side, its inner part picked.
let mut s = Session::new();
let p = rect(&mut s, 9.0);
let l = line(&mut s, [11.0, 1.8], [11.0, 4.5]);
s.execute("fillet", &json!({ "h1": l, "p1": [11, 2.2], "h2": p, "p2": [10, 3], "radius": 0 })).unwrap();
assert_eq!(verts(&s, &p), vec![(11.0, 1.8, 0.0), (11.0, 3.0, 0.0), (9.0, 3.0, 0.0), (9.0, 0.0, 0.0)]);
// A line level with the right side, below it or above it.
for (pick, want) in [
([22.0, 1.0], vec![(18.0, 0.0, 0.0), (22.0, 0.0, 0.0), (22.0, 2.5, 0.0), (23.5, 2.5, 0.0)]),
([22.0, 2.8], vec![(23.5, 2.5, 0.0), (22.0, 2.5, 0.0), (22.0, 3.0, 0.0), (18.0, 3.0, 0.0), (18.0, 0.0, 0.0)]),
] {
let mut s = Session::new();
let p = rect(&mut s, 18.0);
let l = line(&mut s, [23.5, 2.5], [22.6, 2.5]);
s.execute("fillet", &json!({ "h1": l, "p1": [23.2, 2.5], "h2": p, "p2": pick, "radius": 0 })).unwrap();
assert_eq!(verts(&s, &p), want, "{pick:?}");
}
}
/// An arc segment crossed by a line is cut where they cross (radius 0), keeping its picked side,
/// with the bulge of what is left of it: AutoCAD's result for this shape. A line that misses
/// the arc, or a radius, is refused, as AutoCAD refuses them.
#[test]
fn an_arc_segment_crossed_by_a_line_is_cut_there() {
let shape = |s: &mut Session| {
let p =
h(&s.execute("pline", &json!({ "vertices": [[45, 0], { "p": [47, 0], "bulge": -0.4 }, [49, 0], [49, -1.5]], "closed": false })).unwrap());
let l = h(&s.execute("line", &json!({ "points": [[48, -0.5], [48, 2.2]] })).unwrap());
(p, l)
};
let half = ((-4.0 * 0.4f64.atan() / 2.0 / 4.0).tan() * 1e9).round() / 1e9;
let mut s = Session::new();
let (p, l) = shape(&mut s);
s.execute("fillet", &json!({ "h1": l, "p1": [48, 1.5], "h2": p, "p2": [48.8, 0.25], "radius": 0 })).unwrap();
assert_eq!(verts(&s, &p), vec![(48.0, 2.2, 0.0), (48.0, 0.4, half), (49.0, 0.0, 0.0), (49.0, -1.5, 0.0)]);
assert_eq!(count(&s), 1);
// The other side of the arc.
let mut s = Session::new();
let (p, l) = shape(&mut s);
s.execute("fillet", &json!({ "h1": l, "p1": [48, 1.5], "h2": p, "p2": [47.2, 0.25], "radius": 0 })).unwrap();
assert_eq!(verts(&s, &p), vec![(45.0, 0.0, 0.0), (47.0, 0.0, half), (48.0, 0.4, 0.0), (48.0, 2.2, 0.0)]);
// A pick a little before the arc's start (within the pick box) keeps the start side.
let mut s = Session::new();
let p = h(&s.execute("pline", &json!({ "vertices": [{ "p": [47, 0], "bulge": -0.4 }, [49, 0], [49, -1.5]], "closed": false })).unwrap());
let l = h(&s.execute("line", &json!({ "points": [[48, -0.5], [48, 2.2]] })).unwrap());
// On the arc's circle (centre 48,-1.05, radius 1.45), 2.4° before its start.
let a = (1.05f64).atan2(-1.0) + 2.4f64.to_radians();
let pick = [48.0 + 1.45 * a.cos(), -1.05 + 1.45 * a.sin()];
s.execute("fillet", &json!({ "h1": l, "p1": [48, 1.5], "h2": p, "p2": pick, "radius": 0 })).unwrap();
assert_eq!(verts(&s, &p), vec![(47.0, 0.0, half), (48.0, 0.4, 0.0), (48.0, 2.2, 0.0)]);
// An end arc the line doesn't reach, at radius 0 or not: refused, nothing changed.
for r in [0.0, 0.3] {
let mut s = Session::new();
let p = h(&s.execute("pline", &json!({ "vertices": [[27, 0], { "p": [29, 0], "bulge": 0.3 }, [30.2, 1.2]], "closed": false })).unwrap());
let l = h(&s.execute("line", &json!({ "points": [[31.2, -0.5], [31.2, 3]] })).unwrap());
let before = verts(&s, &p);
assert!(s.execute("fillet", &json!({ "h1": p, "p1": [29.8, 0.6], "h2": l, "p2": [31.2, 2.5], "radius": r })).is_err());
assert_eq!(verts(&s, &p), before);
}
}
#[test]
fn polyline_fillets_at_the_command_line_and_with_no_trim() {
let mut s = Session::new();
@@ -592,7 +730,7 @@ fn polyline_fillet_refusals_leave_it_alone() {
let c = h(&s.execute("circle", &json!({ "center": [30, 0], "radius": 1 })).unwrap());
let l = h(&s.execute("line", &json!({ "points": [[20, -5], [20, 5]] })).unwrap());
for q in [
// Segments too far apart, the same segment, a circle, a middle segment with a line, too big.
// Segments too far apart, the same segment, a circle, a segment parallel to a line, too big.
json!({ "h1": p, "p1": [5, 0], "h2": p, "p2": [0, 15], "radius": 1 }),
json!({ "h1": p, "p1": [5, 0], "h2": p, "p2": [6, 0], "radius": 1 }),
json!({ "h1": p, "p1": [5, 0], "h2": c, "p2": [31, 0], "radius": 1 }),
@@ -19,6 +19,7 @@ fn defaults_are_the_ones_the_commands_use() {
for (name, v) in [
("POLYSIDES", json!(4)),
("OFFSETDIST", json!(-1.0)),
("OFFSETGAPTYPE", json!(0)),
("TRIMMODE", json!(1)),
("PROJMODE", json!(1)),
("EDGEMODE", json!(0)),
@@ -77,6 +78,7 @@ fn bad_values_and_unknown_names_are_refused() {
("POLYSIDES", json!(2)),
("POLYSIDES", json!(5000)),
("TRIMMODE", json!(3)),
("OFFSETGAPTYPE", json!(3)),
("LWDEFAULT", json!(26)),
("LAYLOCKFADECTL", json!(91)),
("LAYLOCKFADECTL", json!(-91)),
+7 -4
View File
@@ -129,18 +129,21 @@ pub(super) fn dim_block_entities(d: &Drawing, dm: &Dimension, layer: &str) -> Ve
for (i, l) in g.lines.iter().enumerate().filter(|(i, _)| g.text_marks.contains(i)) {
out.extend(line_entities(i, l));
}
if !g.value.is_empty() {
// 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,
common: text_c.clone(),
kind: EntityKind::MText(MText {
insert: g.text_pos.to3(0.0),
insert: at.to3(0.0),
height: g.text_height,
width: 0.0,
attach: 5,
rotation: g.text_angle,
style: style.text_style.clone(),
contents: g.mtext_contents(),
contents: cadcraft_render::DimGeometry::mtext_code(&contents),
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
+2 -1
View File
@@ -61,7 +61,8 @@ const MAX_TEXT: usize = 1000;
pub struct PdfOptions {
/// Plot style table name, replacing the page setup's (`"None"` plots without one).
pub plot_style_table: Option<String>,
/// Paper name from [`cadcraft_render::PAPER_SIZES`] (`"A4"`, `"Letter"`, `"ANSI B"`…).
/// Paper name from [`cadcraft_render::PAPER_SIZES`] (`"A4"`, `"Letter"`, `"ANSI B"`, `"B4 (JIS)"`,
/// `"Japanese Postcard"`…).
pub paper: Option<String>,
/// Custom paper size in millimetres (portrait width, height).
pub paper_mm: Option<(f64, f64)>,
+41
View File
@@ -1024,6 +1024,47 @@ fn pdf_model_fitted_to_sheet() {
assert!(write(&d, "x.pdf").unwrap().starts_with(b"%PDF"));
}
/// Paper sizes reach the PDF page: the bare B4/B5/B6 are the ISO sizes, the JIS ones are reachable
/// by their explicit names, and the Japanese postcards/envelopes/四六判 plot at theirs.
#[test]
fn pdf_plot_jis_and_japanese_paper_sizes() {
let d = sample();
for (name, w, h) in [
("B4", 708.66, 1000.63),
("B4 (ISO)", 708.66, 1000.63),
("B5", 498.90, 708.66),
("B5-iso", 498.90, 708.66),
("B6", 354.33, 498.90),
("B6 (ISO)", 354.33, 498.90),
("B4 (JIS)", 728.50, 1031.81),
("JIS B4", 728.50, 1031.81),
("B5 (JIS)", 515.91, 728.50),
("b5-jis", 515.91, 728.50),
("B6 (JIS)", 362.83, 515.91),
("Japanese Postcard", 283.46, 419.53),
("はがき", 283.46, 419.53),
("Japanese Double Postcard", 419.53, 566.93),
("往復はがき", 419.53, 566.93),
("Japanese Envelope #3", 340.16, 666.14),
("長形3号", 340.16, 666.14),
("Japanese Envelope Kaku #2", 680.31, 941.10),
("角形2号", 680.31, 941.10),
("四六判", 360.00, 532.91),
] {
let bytes = plot(&d, &Space::Model, &serde_json::json!({"paper": name, "landscape": false})).unwrap();
check_pdf(&bytes);
let (got_w, got_h) = media_box(&bytes);
assert!((got_w - w).abs() < 0.01 && (got_h - h).abs() < 0.01, "{name}: {got_w} x {got_h}, wanted {w} x {h}");
}
// The ambiguous bare postcard aliases are gone.
assert!(plot(&d, &Space::Model, &serde_json::json!({"paper": "Postcard"})).is_err());
assert!(plot(&d, &Space::Model, &serde_json::json!({"paper": "Double Postcard"})).is_err());
// Existing ISO values and the unknown-name error are unchanged.
let (w, h) = media_box(&plot(&d, &Space::Model, &serde_json::json!({"paper": "A3", "landscape": false})).unwrap());
assert!((w - 841.89).abs() < 0.01 && (h - 1190.55).abs() < 0.01, "A3: {w} x {h}");
assert!(plot(&d, &Space::Model, &serde_json::json!({"paper": "Z9"})).is_err());
}
#[test]
fn pdf_layout_one_to_one_with_viewport() {
let mut d = sample();
+48
View File
@@ -0,0 +1,48 @@
//! #1055: a dimension's `*D` block (what AutoCAD and other readers draw) holds the text after
//! `\X` as a second MTEXT below the dimension line.
use cadcraft_doc::{Common, DimKind, Dimension, Drawing, EntityKind, Space};
use cadcraft_geom::Vec3;
#[test]
fn the_text_below_the_dimension_line_is_a_second_mtext() {
let mut d = Drawing::new_metric();
let dm = Dimension {
kind: DimKind::Linear { rotation: 0.0 },
defpt: Vec3::new(50.0, 20.0, 0.0),
text_mid: Vec3::ZERO,
p13: Vec3::ZERO,
p14: Vec3::new(100.0, 0.0, 0.0),
p15: Vec3::ZERO,
p16: Vec3::ZERO,
text: "30 MIN.\\X50 MAX.".into(),
style: "ISO-25".into(),
measurement: 0.0,
text_rotation: 0.0,
user_text_pos: false,
block: None,
insertion_point: Vec3::ZERO,
overrides: Default::default(),
assoc: Vec::new(),
marks: Default::default(),
};
d.add(&Space::Model, Common::default(), EntityKind::Dimension(dm)).unwrap();
let dxf = cadcraft_io::write_dxf(&d);
let lines: Vec<&str> = dxf.lines().map(str::trim).collect();
let pairs: Vec<(&str, &str)> = lines.chunks(2).filter_map(|c| Some((*c.first()?, *c.get(1)?))).collect();
let blocks = pairs.iter().position(|(c, v)| *c == "2" && *v == "BLOCKS").unwrap();
let start = blocks + pairs[blocks..].iter().position(|(c, v)| *c == "2" && v.starts_with("*D")).unwrap();
let end = start + pairs[start..].iter().position(|(c, v)| *c == "0" && *v == "ENDBLK").unwrap();
let (mut texts, mut kind, mut y) = (Vec::new(), "", 0.0);
for (c, v) in &pairs[start..end] {
match *c {
"0" => kind = v,
"20" if kind == "MTEXT" => y = v.parse().unwrap(),
"1" if kind == "MTEXT" => texts.push((v.to_string(), y)),
_ => {}
}
}
assert_eq!(texts.len(), 2, "{texts:?}");
assert_eq!((texts[0].0.as_str(), texts[1].0.as_str()), ("30 MIN.", "50 MAX."));
assert!(texts[0].1 > 20.0 && texts[1].1 < 20.0, "above and below the line at y = 20: {texts:?}");
}
+1
View File
@@ -16,6 +16,7 @@ mod dash_controls;
mod dim_block_resave_roundtrip;
mod dim_block_text;
mod dim_marks_roundtrip;
mod dim_text_below;
mod dim_text_frame;
mod dimstyle_vars_roundtrip;
mod dimtfill_roundtrip;
+111 -2
View File
@@ -61,9 +61,18 @@ pub struct DimGeometry {
pub value: String,
/// The text as MTEXT contents (stacked fractions and tolerances).
pub mtext: String,
/// The part of the text after `\X`, drawn below the dimension line (DXF Reference: `\X`
/// starts the text below it), as plain text, and where its centre is (#1055).
pub below: Option<(String, Vec2)>,
/// Indices into `lines` of the second extension line (DIMLTEX2); the other extension
/// lines take DIMLTEX1.
pub ext2_lines: Vec<usize>,
/// DIMTMOVE 1's leader to text moved off the dimension line (its two ends), which is drawn as
/// a dimension line but isn't the one the text measures.
pub text_leader: Option<(Vec2, Vec2)>,
/// A linear dimension's whole dimension line (its two feet), drawn or not: with DIMSD1 and
/// DIMSD2 both on nothing of it is drawn, yet the text above and below `\X` still sits by it.
pub dim_axis: Option<(Vec2, Vec2)>,
}
impl DimGeometry {
@@ -72,8 +81,12 @@ impl DimGeometry {
/// so other programs plot nothing for it, while every font draws `%%c` (#1645). A `%`
/// that would run into a code is written `%%%`.
pub fn mtext_contents(&self) -> String {
let mut out = String::with_capacity(self.value.len() + 2);
let mut chars = self.value.chars().peekable();
Self::mtext_code(&self.value)
}
/// [`Self::mtext_contents`] for any piece of a dimension's text (the part below the line too).
pub fn mtext_code(text: &str) -> String {
let mut out = String::with_capacity(text.len() + 2);
let mut chars = text.chars().peekable();
while let Some(c) = chars.next() {
match c {
'⌀' => out.push_str("%%c"),
@@ -266,7 +279,19 @@ impl<'a> DimConfig<'a> {
}
}
/// Text with `\X`: as wide as its wider part, as high as the part above the line (the part
/// below goes on the other side of it).
fn measure(&self, text: &str) -> (f64, f64) {
match split_below(text) {
(above, Some(below)) => {
let ((wa, ha), (wb, _)) = (self.measure_one(above), self.measure_one(below));
(wa.max(wb), ha)
}
(above, None) => self.measure_one(above),
}
}
fn measure_one(&self, text: &str) -> (f64, f64) {
if text.is_empty() {
return (0.0, 0.0);
}
@@ -355,6 +380,70 @@ pub fn dimension_geometry_with(d: &Dimension, st: &DimStyle, dimscale: f64, font
g.text_mark(ends);
}
}
// `\X`: the text before it goes above the dimension line, the text after it below.
if let (above, Some(below)) = split_below(&g.mtext) {
let (above, below) = (above.to_string(), below.to_string());
let n = Vec2::from_angle(text_angle).perp();
let ((_, ha), (_, hb)) = (config.measure_one(&above), config.measure_one(&below));
// The dimension line under the text: the line through its longest piece (arrowheads and
// ticks are short; the line may be broken round centred text), not DIMTMOVE 1's leader.
let leader = g.text_leader;
let on_leader = |a: Vec2, b: Vec2| {
leader.is_some_and(|(l0, l1)| {
let eps = 1e-9 * (1.0 + l0.dist(l1));
let near = |q: Vec2| on_line(q, l0, l1).dist(q) <= eps;
near(a) && near(b)
})
};
// The marks drawn with the text (DIMINSPECT's frame, the arc length symbol) aren't it either.
let foot = g
.lines
.iter()
.zip(&g.line_roles)
.enumerate()
.filter(|(i, (_, r))| **r == LineRole::Dim && !g.text_marks.contains(i))
.flat_map(|(_, (l, _))| l.windows(2))
.filter_map(|w| match w {
[a, b] if !on_leader(*a, *b) => Some((*a, *b)),
_ => None,
})
.max_by(|x, y| x.0.dist(x.1).total_cmp(&y.0.dist(y.1)))
// With both halves suppressed (DIMSD1, DIMSD2) the line isn't drawn but is still there.
.or(g.dim_axis);
if let Some((a, b)) = foot {
let f = on_line(text_mid, a, b);
// DIMJUST 3 and 4 turn the text along an extension line, beside it: it doesn't sit
// on the dimension line, so it stays where it is and the part below goes under it,
// in its own frame.
let across = (b - a).normalized().perp().dot(n).abs() < 0.5;
let below_mid = if across && st.text_just >= 3 && !d.user_text_pos {
text_mid - n * (ha / 2.0 + gap + hb / 2.0)
} else {
let off = (text_mid - f).dot(n);
// Text centred on the line moves above it; text already off it stays where it is.
let side = if off < 0.0 { -1.0 } else { 1.0 };
if off.abs() < ha / 2.0 + gap * 0.5 && !d.user_text_pos {
text_mid = f + n * (side * (gap + ha / 2.0));
}
// As far from the line as the text above is when it sits at its place (whatever
// clearance placed it, #2004), on the other side; text moved away (DIMTEDIT,
// DIMTMOVE) leaves the part below at the usual clearance under the line. A taller
// or shorter part below moves by half the difference.
let above_off = (text_mid - f).dot(n).abs();
let clearance = if above_off <= gap + ha { above_off } else { gap + ha / 2.0 };
f - n * (side * (clearance + (hb - ha) / 2.0))
};
let l = cadcraft_fonts::layout_mtext_with(&below, &params(below_mid, text_angle));
for p in l.pieces {
let base = g.text_glyphs.len();
g.text_runs.extend(p.shaped.text.into_iter().map(|t| cadcraft_fonts::TextGlyph { outline: t.outline + base, ..t }));
g.text.extend(p.shaped.strokes);
g.text_glyphs.extend(p.shaped.glyphs);
}
g.below = Some((decode_value(&cadcraft_fonts::plain_mtext(&below)), below_mid));
}
g.mtext = above;
}
// DIMTFILL: a background behind the text, the text box plus DIMGAP on every side.
if st.text_fill != 0 && !g.mtext.is_empty() {
let (w, h) = measure(&g.mtext);
@@ -395,6 +484,26 @@ pub fn dimension_geometry_with(d: &Dimension, st: &DimStyle, dimscale: f64, font
mod linear;
mod variants;
/// The foot of `p` on the line through `a` and `b`.
fn on_line(p: Vec2, a: Vec2, b: Vec2) -> Vec2 {
let ab = b - a;
let len2 = ab.dot(ab);
if len2 <= 0.0 || !len2.is_finite() {
return a;
}
a + ab * ((p - a).dot(ab) / len2)
}
/// Dimension text split at `\X` (text below the dimension line): the part above and, when there
/// is one, the part below.
fn split_below(text: &str) -> (&str, Option<&str>) {
match text.split_once("\\X") {
Some((above, below)) => (above, Some(below)),
None => (text, None),
}
}
/// `%%` codes in the plain value become their characters (`%%c` → ⌀, `%%p` → ±, `%%d` → °).
fn decode_value(s: &str) -> String {
cadcraft_fonts::decode_controls(s).into_iter().map(|(c, _, _)| c).collect()
+4 -1
View File
@@ -212,6 +212,7 @@ fn draw_linear_lines(config: &DimConfig<'_>, g: &mut DimGeometry, state: &Linear
let dle = if state.tick_like { st.dim_line_extend * config.scale } else { 0.0 };
let lo = if st.suppress_dim1 { state.measurement / 2.0 } else { f64::NEG_INFINITY };
let hi = if st.suppress_dim2 { state.measurement / 2.0 } else { f64::INFINITY };
g.dim_axis = Some((state.f1, state.f2));
let seg = |geometry: &mut DimGeometry, a: Vec2, b: Vec2| {
let (ta, tb) = ((a - state.f1).dot(u), (b - state.f1).dot(u));
let (t0, t1) = (ta.min(tb).max(lo), ta.max(tb).min(hi));
@@ -266,7 +267,9 @@ fn draw_linear_lines(config: &DimConfig<'_>, g: &mut DimGeometry, state: &Linear
let offset = (state.text_mid - base).dot(n).abs();
if offset > state.text_height / 2.0 + config.gap + 1e-9 {
let side = if (base - state.text_mid).dot(state.text_axis) >= 0.0 { state.text_axis } else { -state.text_axis };
g.dim(vec![base, state.text_mid + side * (state.text_width / 2.0 + config.gap)]);
let end = state.text_mid + side * (state.text_width / 2.0 + config.gap);
g.text_leader = Some((base, end));
g.dim(vec![base, end]);
}
}
if let Some(jog) = d.marks.jog_line {
+92
View File
@@ -50,6 +50,98 @@ fn vertical_measures_dy() {
assert!((g.measurement - 3.0).abs() < 1e-12, "{}", g.measurement);
}
/// #1055: `\X` in the text puts what follows below the dimension line, on the other side of
/// it from the rest, at the same distance; the measured value is the part above.
#[test]
fn text_after_backslash_x_goes_below_the_line() {
for (d, on) in [
(lin((0.0, 0.0), (10.0, 0.0), (5.0, 3.0), 0.0), Vec2::new(5.0, 3.0)),
(lin((0.0, 0.0), (0.0, 10.0), (4.0, 5.0), std::f64::consts::FRAC_PI_2), Vec2::new(4.0, 5.0)),
] {
let mut d = d;
d.text = "30 MIN.\\X50 MAX.".into();
for tad in [0, 1] {
let st = st_with(|s| s.text_above = tad);
let g = dimension_geometry(&d, &st, 1.0);
assert_eq!(g.value, "30 MIN.", "tad {tad}");
let (below, at) = g.below.clone().expect("a part below the line");
assert_eq!(below, "50 MAX.");
let n = Vec2::from_angle(g.text_angle).perp();
let (above_side, below_side) = ((g.text_pos - on).dot(n), (at - on).dot(n));
assert!(above_side > 0.0 && below_side < 0.0, "opposite sides of the line (tad {tad}): {above_side} {below_side}");
assert!((above_side + below_side).abs() < 1e-9, "same distance: {above_side} {below_side}");
}
}
// Text moved far off the line with DIMTMOVE 1's leader: the part below still goes just under
// the dimension line, not along the leader nor as far below as the text is above.
let mut moved = lin((0.0, 0.0), (10.0, 0.0), (5.0, 3.0), 0.0);
moved.text = "30 MIN.\\X50 MAX.".into();
moved.user_text_pos = true;
moved.text_mid = Vec3::new(5.0, 30.0, 0.0);
let g = dimension_geometry(&moved, &st_with(|s| s.text_move = 1), 1.0);
assert!(g.text_leader.is_some(), "a leader to the moved text");
let (_, at) = g.below.clone().expect("a part below the line");
assert!(at.y < 3.0 && at.y > 2.5 && (at.x - 5.0).abs() < 1e-6, "{at:?}");
// Without `\X` nothing goes below.
assert!(dimension_geometry(&lin((0.0, 0.0), (10.0, 0.0), (5.0, 3.0), 0.0), &DimStyle::default(), 1.0).below.is_none());
}
/// `\X` with both halves of the dimension line suppressed (DIMSD1, DIMSD2): nothing of the line
/// is drawn, but both parts of the text still sit by it, one on each side, apart.
#[test]
fn text_after_backslash_x_survives_a_suppressed_dimension_line() {
let mut d = lin((0.0, 0.0), (10.0, 5.0), (-3.0 / 5f64.sqrt(), 6.0 / 5f64.sqrt()), 0.0);
d.kind = DimKind::Aligned;
d.text = "30 MIN.\\X50 MAX.".into();
let on = Vec2::new(-3.0 / 5f64.sqrt(), 6.0 / 5f64.sqrt());
let ln = Vec2::new(10.0, 5.0).normalized().perp();
for tad in [0, 1] {
let st = st_with(|s| {
s.suppress_dim1 = true;
s.suppress_dim2 = true;
s.text_inside_horizontal = false;
s.text_above = tad;
});
let g = dimension_geometry(&d, &st, 1.0);
assert_eq!(g.lines_of(LineRole::Dim).count(), 0, "no dimension line drawn (tad {tad})");
assert_eq!(g.value, "30 MIN.");
let (below, at) = g.below.clone().expect("a part below the line");
assert_eq!(below, "50 MAX.");
let (above_side, below_side) = ((g.text_pos - on).dot(ln), (at - on).dot(ln));
assert!(above_side * below_side < 0.0, "opposite sides of the line (tad {tad}): {above_side} {below_side}");
assert!((above_side - below_side).abs() >= g.text_height - 1e-9, "apart (tad {tad}): {above_side} {below_side}");
assert!((at - on).dot(ln.perp()).abs() - (g.text_pos - on).dot(ln.perp()).abs() < 1e-9, "under the text (tad {tad})");
}
}
/// `\X` with DIMJUST 3 and 4: the text runs along an extension line, beside it, and stays
/// there; the part below goes under it in its own frame, not onto the dimension line.
#[test]
fn text_after_backslash_x_stays_by_the_extension_line() {
let mut d = lin((0.0, 0.0), (10.0, 0.0), (5.0, 3.0), 0.0);
d.text = "30 MIN.\\X50 MAX.".into();
for just in [3, 4] {
for tad in [1, 2] {
let st = st_with(|s| {
s.text_just = just;
s.text_above = tad;
});
let g = dimension_geometry(&d, &st, 1.0);
assert!((g.text_angle - std::f64::consts::FRAC_PI_2).abs() < 1e-9, "along the extension line");
let beside = if just == 3 { g.text_pos.x < 0.0 } else { g.text_pos.x > 10.0 };
assert!(
beside && g.text_pos.y > 3.0 + g.text_height,
"beside the extension line, off the dimension line (just {just}, tad {tad}): {:?}",
g.text_pos
);
let (_, at) = g.below.clone().expect("a part below the text");
let (x, n) = (Vec2::from_angle(g.text_angle), Vec2::from_angle(g.text_angle).perp());
assert!((at - g.text_pos).dot(x).abs() < 1e-9, "stacked (just {just}, tad {tad}): {at:?}");
assert!((g.text_pos - at).dot(n) >= g.text_height - 1e-9, "under it, apart (just {just}, tad {tad}): {at:?} {:?}", g.text_pos);
}
}
}
#[test]
fn override_text() {
let mut d = lin((0.0, 0.0), (10.0, 0.0), (0.0, 5.0), 0.0);
+122 -5
View File
@@ -31,7 +31,11 @@ const fn inch(name: &'static str, aliases: &'static [&'static str], w: f64, h: f
PaperSize { name, aliases, width_mm: w * 25.4, height_mm: h * 25.4, imperial: true }
}
/// Common ISO (A0–A6, B0–B5) and ANSI/ARCH sheet sizes (ISO 216, ANSI/ASME Y14.1).
/// Common ISO (A0–A6, B0–B6), JIS (B4–B6), Japanese stationery and ANSI/ARCH sheet sizes
/// (ISO 216, JIS P 0138, ANSI/ASME Y14.1).
///
/// The bare names `B4`/`B5`/`B6` are the ISO sizes (250×353, 176×250 and 125×176 mm); the JIS
/// sheets (257×364, 182×257 and 128×182 mm) need explicit names (`JIS B4`, `B4 (JIS)`…).
pub const PAPER_SIZES: &[PaperSize] = &[
iso("ISO A0 (841.00 x 1189.00 MM)", &["A0", "ISO A0"], 841.0, 1189.0),
iso("ISO A1 (594.00 x 841.00 MM)", &["A1", "ISO A1"], 594.0, 841.0),
@@ -44,8 +48,22 @@ pub const PAPER_SIZES: &[PaperSize] = &[
iso("ISO B1 (707.00 x 1000.00 MM)", &["B1", "ISO B1"], 707.0, 1000.0),
iso("ISO B2 (500.00 x 707.00 MM)", &["B2", "ISO B2"], 500.0, 707.0),
iso("ISO B3 (353.00 x 500.00 MM)", &["B3", "ISO B3"], 353.0, 500.0),
iso("ISO B4 (250.00 x 353.00 MM)", &["B4", "ISO B4"], 250.0, 353.0),
iso("ISO B5 (176.00 x 250.00 MM)", &["B5", "ISO B5"], 176.0, 250.0),
iso("ISO B4 (250.00 x 353.00 MM)", &["B4", "ISO B4", "B4 (ISO)"], 250.0, 353.0),
iso("ISO B5 (176.00 x 250.00 MM)", &["B5", "ISO B5", "B5 (ISO)"], 176.0, 250.0),
iso("ISO B6 (125.00 x 176.00 MM)", &["B6", "ISO B6", "B6 (ISO)"], 125.0, 176.0),
// JIS B4–B6 (JIS P 0138): the sheets Japanese drafting and Excel call B4/B5/B6, a few
// millimetres larger than the ISO ones. Explicit names only, so the bare names stay ISO.
iso("JIS B4 (257.00 x 364.00 MM)", &["B4 (JIS)", "JIS B4"], 257.0, 364.0),
iso("JIS B5 (182.00 x 257.00 MM)", &["B5 (JIS)", "JIS B5"], 182.0, 257.0),
iso("JIS B6 (128.00 x 182.00 MM)", &["B6 (JIS)", "JIS B6"], 128.0, 182.0),
// Japanese stationery: postcards, the long (chou) and square (kaku) envelopes and 四六判, the
// 127×188 mm book/paper trade size. No bare `Postcard`: postcard sizes differ by country, so
// the name (and はがき) say which one is meant.
iso("Japanese Postcard (100.00 x 148.00 MM)", &["Japanese Postcard", "はがき"], 100.0, 148.0),
iso("Japanese Double Postcard (148.00 x 200.00 MM)", &["Japanese Double Postcard", "往復はがき"], 148.0, 200.0),
iso("Japanese Envelope #3 (120.00 x 235.00 MM)", &["Japanese Envelope #3", "Envelope #3", "長形3号"], 120.0, 235.0),
iso("Japanese Envelope Kaku #2 (240.00 x 332.00 MM)", &["Japanese Envelope Kaku #2", "Kaku #2", "角形2号"], 240.0, 332.0),
iso("Japanese Shirokuban (127.00 x 188.00 MM)", &["Shirokuban", "Yotsuro", "四六判"], 127.0, 188.0),
inch("ANSI A (8.50 x 11.00 Inches)", &["ANSI A", "Letter", "A-size"], 8.5, 11.0),
inch("Legal (8.50 x 14.00 Inches)", &["Legal"], 8.5, 14.0),
inch("ANSI B (11.00 x 17.00 Inches)", &["ANSI B", "Tabloid", "Ledger", "B-size"], 11.0, 17.0),
@@ -68,9 +86,22 @@ impl PaperSize {
}
}
/// Look up a paper size by canonical name or alias (case- and space-insensitive).
/// Look up a paper size by canonical name or alias (case-insensitive; spaces, underscores, hyphens
/// and parentheses are ignored, so `B5 (JIS)`, `b5-jis` and `b5jis` are one name).
pub fn paper_size(name: &str) -> Option<&'static PaperSize> {
let norm = |s: &str| s.chars().filter(|c| !c.is_whitespace() && *c != '_' && *c != '-').collect::<String>().to_ascii_lowercase();
// Full-width forms are what a Japanese keyboard or IME produces (`B5 (JIS)`), so fold them
// to ASCII before the rest of the normalisation: U+FF01..U+FF5E are ASCII + 0xFEE0.
let norm = |s: &str| {
s.chars()
.map(|c| match c {
'\u{FF01}'..='\u{FF5E}' => char::from_u32(c as u32 - 0xFEE0).unwrap_or(c),
'\u{3000}' => ' ',
_ => c,
})
.filter(|c| !c.is_whitespace() && !matches!(c, '_' | '-' | '(' | ')'))
.collect::<String>()
.to_ascii_lowercase()
};
let n = norm(name);
if n.is_empty() {
return None;
@@ -200,6 +231,73 @@ pub fn sheet(d: &Drawing, layout: &str) -> Option<Sheet> {
mod tests {
use super::*;
#[test]
fn jis_and_japanese_paper_sizes() {
// The bare names B4/B5/B6 are the ISO sizes, as they were before the JIS sheets arrived.
for (name, w, h) in [
("B4", 250.0, 353.0),
("b4", 250.0, 353.0),
("ISO B4", 250.0, 353.0),
("B4 (ISO)", 250.0, 353.0),
("B5", 176.0, 250.0),
("b5-iso", 176.0, 250.0),
("B6", 125.0, 176.0),
("B6 (ISO)", 125.0, 176.0),
] {
let p = paper_size(name).unwrap_or_else(|| panic!("{name}"));
assert_eq!((p.width_mm, p.height_mm), (w, h), "{name}");
assert!(!p.imperial, "{name} is a metric sheet");
}
assert_eq!(paper_size("B4").map(|p| p.name), Some("ISO B4 (250.00 x 353.00 MM)"));
assert_eq!(paper_size("B6").map(|p| p.name), Some("ISO B6 (125.00 x 176.00 MM)"));
// The JIS sizes (JIS P 0138) are reachable by their explicit names only.
for (name, w, h) in [
("B4 (JIS)", 257.0, 364.0),
("b4-jis", 257.0, 364.0),
("JIS B4", 257.0, 364.0),
("B5 (JIS)", 182.0, 257.0),
("b5 (jis)", 182.0, 257.0),
("JIS B5", 182.0, 257.0),
("B6 (JIS)", 128.0, 182.0),
("b6jis", 128.0, 182.0),
("JIS B6", 128.0, 182.0),
] {
let p = paper_size(name).unwrap_or_else(|| panic!("{name}"));
assert_eq!((p.width_mm, p.height_mm), (w, h), "{name}");
assert!(!p.imperial, "{name} is a metric sheet");
}
assert_eq!(paper_size("JIS B5").map(|p| p.name), Some("JIS B5 (182.00 x 257.00 MM)"));
// A page setup stores the canonical name; the ISO and JIS names both keep resolving, so a
// drawing keeps the sheet it stored.
for name in ["ISO B4 (250.00 x 353.00 MM)", "JIS B4 (257.00 x 364.00 MM)"] {
assert_eq!(paper_size(name).map(|p| p.name), Some(name), "{name}");
}
// Japanese postcards, envelopes and 四六判.
for (name, w, h) in [
("Japanese Postcard", 100.0, 148.0),
("はがき", 100.0, 148.0),
("Japanese Double Postcard", 148.0, 200.0),
("往復はがき", 148.0, 200.0),
("Japanese Envelope #3", 120.0, 235.0),
("長形3号", 120.0, 235.0),
("Japanese Envelope Kaku #2", 240.0, 332.0),
("kaku #2", 240.0, 332.0),
("角形2号", 240.0, 332.0),
("Shirokuban", 127.0, 188.0),
("四六判", 127.0, 188.0),
] {
let p = paper_size(name).unwrap_or_else(|| panic!("{name}"));
assert_eq!((p.width_mm, p.height_mm), (w, h), "{name}");
}
// The bare postcard aliases are ambiguous and gone.
assert!(paper_size("Postcard").is_none());
assert!(paper_size("Double Postcard").is_none());
// A6 was already an ISO sheet.
assert_eq!(paper_size("A6").map(|p| (p.width_mm, p.height_mm)), Some((105.0, 148.0)));
// Unknown names still fail.
assert!(paper_size("Z9").is_none());
}
#[test]
fn metric_length_unit_reads_the_length_unit() {
// Metric units, whatever MEASUREMENT says.
@@ -346,3 +444,22 @@ pub fn saved_plot(page: &PageSetup) -> SavedPlot {
let scale = Some(page.scale).filter(|s| !page.scale_to_fit && s.is_finite() && *s > 0.0 && (*s - 1.0).abs() > 1e-9);
SavedPlot { window, fit, scale, center: page.center }
}
#[cfg(test)]
mod wide_name_tests {
use super::*;
/// A name typed on a Japanese keyboard arrives in full-width forms (`B5 (JIS)`); it must
/// resolve to the same sheet as `B5 (JIS)`.
#[test]
fn full_width_names_resolve_like_their_ascii_forms() {
for (wide, ascii) in [("B5 (JIS)", "B5 (JIS)"), ("A4", "A4"), ("B4", "B4")] {
let w = paper_size(wide).unwrap_or_else(|| panic!("{wide}"));
let a = paper_size(ascii).unwrap_or_else(|| panic!("{ascii}"));
assert_eq!(w.name, a.name, "{wide} vs {ascii}");
}
// The Japanese spellings still work, and the ideographic space is a separator.
assert_eq!(paper_size("はがき").map(|p| p.name), paper_size("Japanese Postcard").map(|p| p.name));
assert_eq!(paper_size(" B5 ").map(|p| p.name), Some(paper_size("B5").unwrap().name));
}
}
+51 -1
View File
@@ -1,4 +1,4 @@
//! Bake the contributor credits into the binary as static Rust tables. Nothing is read at run time.
//! Bake the contributor credits and validate the shared Chinese overlay at build time.
//!
//! - contributors/contributors.json: commit stats per GitHub username, with a mark for whose people.toml
//! entry is verified.
@@ -11,7 +11,11 @@ use std::fmt::Write as _;
use serde_json::Value;
const SHARED_ZH: &str = "src/i18n/zh_shared.tsv";
const SHARED_ZH_KEY: &str = "Construction Geometry";
fn main() {
verify_shared_zh();
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../contributors");
let json = read(&dir.join("contributors.json"), "the About window shows no contributors", |t| {
serde_json::from_str::<Value>(t).map_err(|e| e.to_string())
@@ -25,6 +29,52 @@ fn main() {
}
}
// Local/offline builds use the checked-in projection. Hosted and release builds with
// craft-i18n.rev also check it against their canonical craft-i18n checkout.
fn verify_shared_zh() {
println!("cargo::rerun-if-env-changed=CRAFT_I18N_DIR");
println!("cargo::rerun-if-env-changed=CRAFT_I18N_REQUIRED");
println!("cargo::rerun-if-changed={SHARED_ZH}");
let result = projected_row(include_str!("src/i18n/zh_shared.tsv")).and_then(verify_checkout);
if let Err(e) = result {
println!("cargo::error=shared Simplified Chinese catalog: {e}");
}
}
fn projected_row(projection: &str) -> Result<&str, String> {
let mut rows = projection.lines().filter(|line| !line.is_empty() && !line.starts_with('#'));
let Some(row) = rows.next() else {
return Err(format!("missing projected key {SHARED_ZH_KEY:?}"));
};
let valid = row
.strip_prefix('\t')
.and_then(|rest| rest.split_once('\t'))
.is_some_and(|(key, value)| key == SHARED_ZH_KEY && !value.trim().is_empty() && !value.contains(['\t', '\\', '\r']));
if rows.next().is_some() || !valid {
return Err(format!("expected exactly one ordinary literal row for {SHARED_ZH_KEY:?}"));
}
Ok(row)
}
fn verify_checkout(projected: &str) -> Result<(), String> {
let required = std::env::var("CRAFT_I18N_REQUIRED").is_ok_and(|v| v.trim() == "1");
let Some(dir) = std::env::var_os("CRAFT_I18N_DIR").filter(|dir| !dir.is_empty()) else {
return if required { Err("CRAFT_I18N_REQUIRED=1 but CRAFT_I18N_DIR is unset".to_string()) } else { Ok(()) };
};
let dir = std::path::PathBuf::from(dir);
if !dir.is_absolute() {
return Err("CRAFT_I18N_DIR must be an absolute path".to_string());
}
let catalog = dir.join("locales/zh-hans/cadcraft.tsv");
println!("cargo::rerun-if-changed={}", catalog.display());
let source = std::fs::read_to_string(&catalog).map_err(|e| format!("reading {}: {e}", catalog.display()))?;
let mut rows = source.lines().filter(|row| row.strip_prefix('\t').is_some_and(|rest| rest.split('\t').next() == Some(SHARED_ZH_KEY)));
if rows.next() != Some(projected) || rows.next().is_some() {
return Err(format!("projected key {SHARED_ZH_KEY:?} is missing, duplicated or differs from the checked-out source"));
}
Ok(())
}
fn read<T>(path: &std::path::Path, fallback: &str, parse: impl Fn(&str) -> Result<T, String>) -> Option<T> {
println!("cargo::rerun-if-changed={}", path.display());
let r = std::fs::read_to_string(path).map_err(|e| e.to_string()).and_then(|t| parse(&t));
+8 -1
View File
@@ -96,12 +96,19 @@ impl CadApp {
}
}
/// Every frame: autosave what is due, and wake up when the next one is.
/// Every frame: autosave what is due and keep the drawing locks, and wake up when the next
/// autosave or lock heartbeat is.
pub fn autosave_tick(&mut self, _ctx: &egui::Context) {
#[cfg(not(target_arch = "wasm32"))]
if let Some(wait) = self.autosave.as_mut().and_then(|s| s.tick(&self.session)) {
_ctx.request_repaint_after(wait);
}
// A drawing someone else has open (its lock, `cadcraft_engine::drawlock`): say so.
#[cfg(not(target_arch = "wasm32"))]
for note in self.autosave.as_mut().map(|s| s.take_lock_notes()).unwrap_or_default() {
self.session.echo(note.clone());
self.set_status(note);
}
#[cfg(not(target_arch = "wasm32"))]
{
// A write that fails while the app is idle must still reach the notice.
+17 -1
View File
@@ -352,8 +352,24 @@ fn parse(source: &str) -> (Catalog<'_>, Vec<String>) {
(entries, errors)
}
fn merge_ordinary_zh<'a>(catalog: &mut Catalog<'a>, supplemental: &'a str) {
for ((context, key), value) in parse(supplemental).0 {
if context.is_empty() {
catalog.entry((context, key)).or_insert(value);
}
}
}
fn catalog(language: &str) -> Option<&'static Catalog<'static>> {
LANGUAGES.iter().find(|l| l.code == language && !l.source.is_empty()).map(|l| l.catalog.get_or_init(|| parse(l.source).0))
LANGUAGES.iter().find(|l| l.code == language && !l.source.is_empty()).map(|l| {
l.catalog.get_or_init(|| {
let mut entries = parse(l.source).0;
if l.code == "zh" {
merge_ordinary_zh(&mut entries, include_str!("i18n/zh_shared.tsv"));
}
entries
})
})
}
pub fn tr<'a>(language: &str, source: &'a str) -> &'a str {
+1
View File
@@ -1256,6 +1256,7 @@
Search for pattern Buscar patrón
Not a number or distance: {text} No es un número ni una distancia: {text}
Query Texts Consultar textos
Who Has Quién lo tiene abierto
Analyze Shapes Analizar formas
Check for Updates… Buscar actualizaciones…
CADCraft is up to date. CADCraft está actualizado.
1 # CADCraft Spanish interface catalog — original translations.
1256
1257
1258
1259
1260
1261
1262
+29
View File
@@ -40,6 +40,35 @@ fn catalog_is_valid_and_preserves_placeholders_and_ellipses() {
assert_eq!(tr("unknown", "Open"), "Open");
}
#[test]
fn chinese_supplement_fills_only_missing_ordinary_labels() {
let (mut entries, _) = parse("\tExisting label\tlocal\nmenu\tExisting label\tlocal menu\n");
merge_ordinary_zh(&mut entries, "\tExisting label\tshared\n\tMissing label\tshared\nmenu\tIgnored label\tshared menu\n");
assert_eq!(entries.get(&("", "Existing label")).copied(), Some("local"));
assert_eq!(entries.get(&("menu", "Existing label")).copied(), Some("local menu"));
assert_eq!(entries.get(&("", "Missing label")).copied(), Some("shared"));
assert!(!entries.contains_key(&("menu", "Ignored label")));
}
#[test]
fn installed_chinese_supplement_serves_ordinary_and_menu_lookups() {
const KEY: &str = "Construction Geometry";
let (projection, errors) = parse(include_str!("zh_shared.tsv"));
assert!(errors.is_empty(), "{errors:?}");
assert_eq!(projection.len(), 1);
let translated = projection[&("", KEY)];
assert_ne!(translated, KEY);
assert_eq!(tr("zh", KEY), translated);
assert_eq!(tr_menu("zh", KEY), translated);
with_language("zh", || {
assert_eq!(t(KEY), translated);
assert_eq!(menu(KEY), translated);
assert_eq!(t("Construction Line"), "构造线");
assert_eq!(t("a future untranslated label"), "a future untranslated label");
});
assert_eq!(tr("en", KEY), KEY);
}
/// A prompt with options is translated without its own "or": the command line adds the
/// translated " or [" before the options ("Select polyline or [Multiple]").
#[test]
+1
View File
@@ -1359,6 +1359,7 @@
Justify За шириною
Text color Колір тексту
Click the ruler to add a tab stop, right-click to remove one Натисніть на лінійку, щоб додати табуляцію; права кнопка видаляє її
Who Has Хто відкрив креслення
3 Point 3 точки
New UCS Нова СКК
Origin Початок координат
1 # CADCraft Ukrainian interface catalog — original translations by @dmatviichuk.
1359
1360
1361
1362
1363
1364
1365
+1
View File
@@ -985,6 +985,7 @@
Window 窗口
Wipeout 区域覆盖
Workspace Switching 工作空间切换
Who Has 谁打开了图纸
Write Block 写块
Write Block Pick 写块选取
Xline 构造线
1 # CADCraft Simplified Chinese interface catalog — original translations.
985
986
987
988
989
990
991
+3
View File
@@ -0,0 +1,3 @@
# Generated from locales/zh-hans/cadcraft.tsv at the root craft-i18n.rev.
# Keep only the ordinary Construction Geometry row, byte-for-byte. Do not translate here.
Construction Geometry 构造几何
1 # Generated from locales/zh-hans/cadcraft.tsv at the root craft-i18n.rev.
2 # Keep only the ordinary Construction Geometry row, byte-for-byte. Do not translate here.
3 Construction Geometry 构造几何
+14 -3
View File
@@ -16,12 +16,23 @@ The built-in devices come first:
They offer the standard sizes:
- ISO 216 A0–A6 and B0–B5
- ISO 216 A0–A6 and B0–B6
- JIS B4–B6 (JIS P 0138) by explicit name: `B4 (JIS)`/`JIS B4`, `B5 (JIS)`/`JIS B5` and
`B6 (JIS)`/`JIS B6` (257×364, 182×257 and 128×182 mm). The bare `B4`/`B5`/`B6` stay the ISO
sizes (250×353, 176×250 and 125×176 mm)
- Japanese stationery: Japanese Postcard (はがき, 100×148 mm), Japanese Double Postcard (往復はがき,
148×200 mm), Japanese Envelope #3 (長形3号, 120×235 mm), Japanese Envelope Kaku #2 (角形2号,
240×332 mm) and 四六判 (127×188 mm)
- ANSI A–E and Legal
- ARCH A–E and E1
ISO sheets have 5 mm margins. Inch sheets have quarter-inch (6.35 mm) margins. A page setup
with the device `None` plots to PDF on the page setup's paper, as before.
Metric sheets (ISO and JIS) have 5 mm margins, inch sheets have quarter-inch (6.35 mm) margins.
A page setup with the device `None` plots to PDF on the page setup's paper, as before. Paper names
resolve case-insensitively and ignore spaces, hyphens and parentheses (`B5 (JIS)`, `b5-jis`,
`はがき`).
`B4`/`B5` keep meaning the ISO sizes, so a drawing or caller that used them doesn't change; a plot
that means JIS B4/B5 says `B4 (JIS)`/`B5 (JIS)`. A drawing keeps the sheet size it stored.
User devices are files in our own format, kept in the `plotters` folder of the CADCraft
settings directory:
+34 -7
View File
@@ -185,7 +185,9 @@ class TrustedSourcePreparation(unittest.TestCase):
producer_platforms(source.replace(" " + current + "\n", ""))
def test_continuation_lines_of_any_scalar_form_reach_the_guard_checks(self):
for name, workflow in (("nightly.yml", "nightly.yml"), ("nightly-sign.yml", "nightly-sign.yml")):
for name, workflow in (("nightly.yml", "nightly.yml"),
("nightly-sign.yml", "nightly-sign.yml"),
("nightly-dispatch.yml", "nightly-dispatch.yml")):
source = (ROOT / ".github/workflows" / workflow).read_text()
expected = NightlyEnabledCallers.GUARDS[name]
guard = re.search(r"(?m)^ if: >-\n(?: [^\n]*\n)+", source)[0]
@@ -195,15 +197,38 @@ class TrustedSourcePreparation(unittest.TestCase):
(indicator, expression), = job_conditions(jobs)
self.assertFalse(indicator == ">-" and " ".join(expression.split()) == expected)
def test_no_nightly_schedule_is_registered(self):
for name, event in (("nightly.yml", "workflow_dispatch"),
("nightly-sign.yml", "workflow_dispatch")):
def test_nightly_workflow_triggers_and_schedule_match_review(self):
expected_triggers = (
("nightly.yml", [" schedule:", " workflow_dispatch:"]),
("nightly-sign.yml", [" workflow_dispatch:"]),
("nightly-dispatch.yml", [" workflow_run:"]),
)
for name, expected in expected_triggers:
source = (ROOT / ".github/workflows" / name).read_text()
events = source.split("\non:\n", 1)[1].split("\npermissions:", 1)[0]
triggers = [line for line in events.splitlines() if line.startswith(" ")
and not line.startswith(" ") and line.strip() and not line.lstrip().startswith("#")]
with self.subTest(workflow=name):
self.assertEqual(triggers, [f" {event}:"], "schedule/activation needs explicit review")
self.assertEqual(triggers, expected, "schedule/activation needs explicit review")
producer = (ROOT / ".github/workflows/nightly.yml").read_text()
self.assertEqual(re.findall(r"(?m)^ - cron: '([^']+)'$", producer), ["30 0 * * *"],
"nightly schedule must stay pinned to 00:30 UTC")
def test_nightly_dispatch_is_transport_only_for_scheduled_producer(self):
producer = (ROOT / ".github/workflows/nightly.yml").read_text()
producer_name = re.findall(r"(?m)^name: (.+)$", producer)[0]
dispatch = (ROOT / ".github/workflows/nightly-dispatch.yml").read_text()
self.assertIn(f"workflows: [{producer_name}]", dispatch)
self.assertIn("types: [completed]", dispatch)
self.assertIn("branches: [main]", dispatch)
self.assertIn("\npermissions: {}\n", dispatch)
self.assertNotIn("false &&", dispatch)
self.assertNotRegex(dispatch, r"(?im)^\s*(?:-\s*)?uses:")
self.assertNotRegex(dispatch, r"(?im)^\s*environment:|\bsecrets\b")
self.assertIn("storytold/cadcraft/actions/workflows/nightly-sign.yml/dispatches", dispatch)
self.assertIn("'ref': 'refs/heads/" + SIGNER_BRANCH + "'", dispatch)
self.assertIn("producer.get('event') == 'schedule'", dispatch)
self.assertIn("type(attempt) is int and attempt == 1", dispatch)
def test_signer_serialization_contract_is_enforced(self):
assert_nightly_serialization((ROOT / ".github/workflows/nightly-sign.yml").read_text())
@@ -224,7 +249,7 @@ class TrustedSourcePreparation(unittest.TestCase):
assert_nightly_serialization(source.replace(old, new))
def test_no_cache_actions_or_cache_setup_options_in_app_trusted_closure(self):
for name in ("nightly.yml", "nightly-sign.yml"):
for name in ("nightly.yml", "nightly-sign.yml", "nightly-dispatch.yml"):
source = (ROOT / ".github/workflows" / name).read_text()
executable = "\n".join(line for line in source.splitlines()
if not line.lstrip().startswith("#"))
@@ -322,6 +347,7 @@ class NightlyEnabledCallers(unittest.TestCase):
"github.event_name == 'workflow_dispatch')",
"nightly-sign.yml": "github.repository == 'storytold/cadcraft' && github.event_name == 'workflow_dispatch' && "
"github.ref == 'refs/heads/" + SIGNER_BRANCH + "' && github.ref_type == 'branch'",
"nightly-dispatch.yml": "github.repository == 'storytold/cadcraft' && github.event_name == 'workflow_run'",
}
def test_enabled_jobs_keep_exact_context_guards(self):
@@ -338,7 +364,8 @@ class NightlyEnabledCallers(unittest.TestCase):
source = (ROOT / ".github/workflows/nightly.yml").read_text()
policy = json.loads(INSTALLED_POLICY.read_text())
self.assertEqual(reviewed_manual_actors(source, policy), RELEASE_MANAGERS)
self.assertEqual(policy["automatic_signer_actors"], [], "no automatic signer without a schedule")
self.assertEqual(policy["automatic_signer_actors"], ["github-actions[bot]"],
"only github-actions[bot] may trigger automatic scheduled signing")
def test_an_actor_outside_the_release_managers_is_refused(self):
source = (ROOT / ".github/workflows/nightly.yml").read_text()