Compare commits

..
72 changed files with 1277 additions and 3904 deletions
-72
View File
@@ -1,72 +0,0 @@
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.')
+2 -4
View File
@@ -1,10 +1,8 @@
name: CADCraft unsigned nightly
# 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.
# 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).
on:
schedule:
- cron: '30 0 * * *'
workflow_dispatch:
permissions:
+1 -1
View File
@@ -10,7 +10,7 @@ permissions:
contents: read
concurrency:
group: ${{ github.ref == 'refs/heads/main' && format('sonarcloud-main-{0}', github.sha) || format('sonarcloud-{0}', github.ref) }}
group: sonarcloud-${{ 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,7 +25,6 @@ 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,7 +736,6 @@ dependencies = [
"cadcraft-ui-egui",
"chrono",
"clap",
"craft-nightly",
"craft-quit",
"craft-update",
"eframe",
@@ -1592,15 +1591,6 @@ 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,7 +19,6 @@ 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(), propagate_version = true, arg_required_else_help = true)]
#[command(name = "cadcraft-cli", version = cadcraft_engine::build_version(), arg_required_else_help = true)]
pub(crate) struct Cli {
#[command(subcommand)]
pub(crate) command: Command,
+2 -15
View File
@@ -188,25 +188,12 @@ 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,7 +24,6 @@ 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`).
+29 -4
View File
@@ -1,11 +1,23 @@
//! 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;
pub use craft_nightly::BuildFlavor;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BuildFlavor {
Stable,
NightlyV1,
}
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
}
@@ -23,8 +35,7 @@ pub fn version(flavor: BuildFlavor, stable: &str) -> String {
#[cfg(test)]
mod tests {
use super::{BuildFlavor, needs_native_error, version, version_query};
use super::*;
#[test]
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
@@ -33,6 +44,20 @@ 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");
+174 -64
View File
@@ -1,101 +1,211 @@
//! 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.
//! 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.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
use std::sync::OnceLock;
use craft_nightly::{BuildFlavor, Launch, Profile, ProfileError, StartupOptions};
pub const VERSION: &str = "nightly-v1";
pub fn current() -> &'static Profile {
craft_nightly::current().unwrap_or(&Profile::Stable)
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Profile {
Stable,
NightlyV1(PathBuf),
}
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())
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();
pub fn current() -> &'static Profile {
PROFILE.get().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)
}
#[cfg(test)]
mod tests {
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};
use super::*;
use std::cell::Cell;
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" }
}
#[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());
fn nightly() -> Vec<OsString> {
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
}
#[test]
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.passthrough_args, args(&["drawing with spaces.dxf"]));
assert!(!launch.is_version_query());
}
#[test]
fn stable_arguments_are_unchanged_and_nightly_flags_are_refused() {
fn stable_arguments_and_directory_policy_are_unchanged() {
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 launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap();
assert_eq!(launch, Launch { profile: Profile::Stable, 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();
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();
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
assert_eq!(launch.args, args(&["--", "--profile-root", "drawing with spaces.dxf"]));
}
#[test]
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
for argv in [
args(&["--launch-profile", NIGHTLY_V1_CONTRACT]),
args(&["--launch-profile", VERSION]),
args(&["--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--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()]),
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()]),
] {
assert!(parse_startup(BuildFlavor::NightlyV1, &s, argv, &StartupOptions::new()).is_err());
assert!(parse(argv).is_err());
}
}
#[test]
fn launcher_and_direct_version_queries_are_recognized() {
let s = spec();
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];
for flag in ["--version", "-V"] {
let direct = parse_startup(BuildFlavor::NightlyV1, &s, args(&[flag]), &StartupOptions::new()).unwrap();
assert!(direct.is_version_query(), "direct {flag}");
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}");
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 file_named_version = parse_startup(BuildFlavor::NightlyV1, &s, args(&["--", "--version"]), &StartupOptions::new()).unwrap();
assert!(!file_named_version.is_version_query());
#[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());
}
#[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());
}
}
+22 -17
View File
@@ -428,30 +428,35 @@ 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 `-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) {
// 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))
{
use std::io::Write as _;
let _ = writeln!(std::io::stdout(), "{}", nightly_version_line());
return None;
}
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)) {
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)) {
report_launch_profile_error(&error);
std::process::exit(2);
}
Some(launch.passthrough_args)
Some(early.args)
}
/// Parse CLI options (`--control`, `--sample`, files, `--version`), install logging and I/O hooks, build the services and app, and run eframe.
+633 -172
View File
@@ -1,218 +1,679 @@
//! CADCraft's `craft-nightly` isolation specification: stable paths, environment fence,
//! portable-mode markers, folder-only entries, and platform-specific forbidden roots.
//! App-owned nightly profile fences; no stable fallback, migration or process environment changes.
use std::ffi::OsString;
use std::path::PathBuf;
use craft_nightly::AppProfileSpec;
use crate::portable::{PORTABLE_DATA_DIR, portable_marker};
use std::path::{Component, Path, PathBuf};
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))
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Platform {
Windows,
Linux,
Mac,
}
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),
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 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"));
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")?;
}
Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")),
}
}
#[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"));
}
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);
}
#[cfg(target_os = "macos")]
{
if let Some(home) = non_empty_abs(env, "HOME") {
let library = home.join("Library");
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(PathBuf::from("/Applications/CADCraft.app"));
}
roots
Ok(resolved)
}
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)
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());
}
}
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")?;
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(installation_boundary(platform, exe)?);
roots.into_iter().map(|p| canonical_future(&p)).collect()
}
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)
}
/// 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};
use craft_nightly::{ProfileError, validate_and_prepare_root};
struct Fixture {
root: PathBuf,
env: BTreeMap<String, OsString>,
exe: PathBuf,
}
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 {
impl Fixture {
fn new() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
let root = loop {
let candidate = std::env::temp_dir().join(format!(
"cadcraft-profile-spec-{}-{}-{label}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
let candidate =
std::env::temp_dir().join(format!("cadcraft-profile-policy-{}-{}", 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 temp dir: {error}"),
Err(error) => panic!("cannot create owned fixture: {error}"),
}
};
Self(root)
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())
}
}
impl Drop for TempDir {
impl Drop for Fixture {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
// Only the directory successfully created by this fixture is owned for removal.
std::fs::remove_dir_all(&self.root).unwrap();
}
}
#[test]
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"));
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")));
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);
}
}
#[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!(s.extra_forbidden_roots.contains(&PathBuf::from("/home/tester/Applications/CADCraft.app")));
assert!(s.extra_forbidden_roots.contains(&PathBuf::from("/Applications/CADCraft.app")));
}
}
#[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");
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");
}
#[cfg(unix)]
#[test]
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();
std::fs::create_dir_all(&private).unwrap();
std::os::unix::fs::symlink(outside.join("target"), private.join("autosave")).unwrap();
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(())
},
);
assert!(result.is_err(), "autosave must not escape the private profile or follow a dangling alias");
assert!(!probed.get());
}
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);
}
let err = validate_and_prepare_root(&private, &spec()).unwrap_err();
assert!(matches!(err, ProfileError::SymlinkEntry(_)), "unexpected error: {err}");
#[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");
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);
}
}
-58
View File
@@ -428,62 +428,4 @@ 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
@@ -1 +0,0 @@
9fa32aecf2759cd61bb216a958df68da619798f3
+2 -25
View File
@@ -166,9 +166,6 @@ 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.
@@ -190,8 +187,6 @@ 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(),
}
}
@@ -461,8 +456,7 @@ 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 or drawing-lock heartbeat is due, so the host
/// can wake up for it.
/// Returns how long until the next autosave 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();
@@ -471,23 +465,7 @@ mod native {
let jobs = self.plan(s, now, minutes, &dir);
self.perform(jobs);
self.heartbeat(&dir, now);
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()
self.next_due(now, minutes).map(Duration::from_secs_f64)
}
/// Autosave every drawing with changes not yet autosaved right away, without waiting for
@@ -663,7 +641,6 @@ mod native {
let _ = h.join();
}
self.busy.clear();
self.drawing_locks.release_all(&self.instance);
for path in self.files() {
discard(&path);
}
+2 -20
View File
@@ -247,25 +247,14 @@ 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 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 k = if st.scale > 0.0 { st.scale } else { 1.0 };
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,
annotative: st.annotative,
}
Sizes { arrow: st.arrow_size * k, gap: st.text_gap.abs() * k, text: st.text_height * k, above: st.text_above != 0, text_style }
}
/// LEADER's JSON form: a straight leader with an arrow through `pts`, and `text` (lines split at
@@ -359,12 +348,5 @@ 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())
}
-22
View File
@@ -343,11 +343,6 @@ fn eq_variants(o: &TanObj) -> Vec<Eq3> {
/// Circle tangent to three objects, nearest the pick points (Newton on all sign combinations).
pub fn ttt(objs: [(TanObj, Vec2); 3]) -> Option<Circle> {
ttt_where(objs, |_| true)
}
/// [`ttt`] among the circles `ok` accepts.
pub fn ttt_where(objs: [(TanObj, Vec2); 3], ok: impl Fn(&Circle) -> bool) -> Option<Circle> {
let [(o1, p1), (o2, p2), (o3, p3)] = objs;
let mut starts: Vec<[f64; 3]> = Vec::new();
let cen = (p1 + p2 + p3) / 3.0;
@@ -355,20 +350,6 @@ pub fn ttt_where(objs: [(TanObj, Vec2); 3], ok: impl Fn(&Circle) -> bool) -> Opt
starts.push([cen.x, cen.y, rad.max(1e-3)]);
if let Some(c) = Circle::from_3_points(p1, p2, p3) {
starts.push([c.center.x, c.center.y, c.radius]);
} else {
// The picks lie in one line. When the circles picked are centred on it too, every Newton
// step from a start on that line stays on it: start off it as well, on both sides, from
// the circle through the two picks farthest apart and a point beside them.
let (a, b) = [(p1, p2), (p1, p3), (p2, p3)].into_iter().max_by(|x, y| x.0.dist(x.1).total_cmp(&y.0.dist(y.1))).unwrap_or((p1, p3));
let span = a.dist(b);
let n = (b - a).normalized().perp();
if span.is_finite() && span > 0.0 && n.is_finite() {
for side in [1.0, -1.0] {
if let Some(c) = Circle::from_3_points(a, b, (a + b) / 2.0 + n * (span * side)) {
starts.push([c.center.x, c.center.y, c.radius]);
}
}
}
}
let mut best: Option<(f64, Circle)> = None;
let scale = rad.max(p1.dist(p2)).max(1e-6);
@@ -398,9 +379,6 @@ pub fn ttt_where(objs: [(TanObj, Vec2); 3], ok: impl Fn(&Circle) -> bool) -> Opt
continue;
}
let c = Circle::new(Vec2::new(x[0], x[1]), x[2]);
if !ok(&c) {
continue;
}
let sc = score(&c, &objs);
if best.is_none_or(|(b, _)| sc < b - 1e-12) {
best = Some((sc, c));
+5 -74
View File
@@ -2,7 +2,6 @@ use super::{
Accept, Arc, Circle, EntityKind, Input, Interactive, Prompt, Result, Session, Step, Value, Vec2, added, arc, bad, circle, f64_req, line, number,
point_param, size_param,
};
use crate::snap;
pub(super) fn run_circle(s: &mut Session, p: &Value) -> Result<Value> {
let c = if let Some(center) = point_param(p, "center") {
@@ -52,8 +51,6 @@ pub(super) fn run_arc(s: &mut Session, p: &Value) -> Result<Value> {
pub(super) struct CircleM {
mode: u8, // 0 center-radius, 1 = 3P, 2 = 2P, 3 = TTR
pts: Vec<Vec2>,
/// 3P: the circle or arc each point was picked on with a tangent snap, by point.
tans: Vec<Option<snap::SnapCurve>>,
diameter: bool,
/// The `Ttr` option hands over to the tangent-circle machine.
delegate: Option<Box<dyn Interactive>>,
@@ -72,22 +69,18 @@ impl Interactive for CircleM {
match (self.mode, n) {
(0, 0) => Prompt::new("Specify center point for circle", Accept::POINT).kw(&["3P", "2P", "Ttr (tan tan radius)"]),
(0, _) if self.diameter => {
Prompt::new("Specify diameter of circle", Accept::POINT_OR_NUMBER).base_opt(self.pts.first().copied()).distance().deferred()
Prompt::new("Specify diameter of circle", Accept::POINT_OR_NUMBER).base_opt(self.pts.first().copied()).distance()
}
(0, _) => {
let p = Prompt::new("Specify radius of circle", Accept::POINT_OR_NUMBER)
.kw(&["Diameter"])
.base_opt(self.pts.first().copied())
.distance()
.deferred();
let p =
Prompt::new("Specify radius of circle", Accept::POINT_OR_NUMBER).kw(&["Diameter"]).base_opt(self.pts.first().copied()).distance();
if last_r > 0.0 { p.default(format!("{last_r:.4}")) } else { p }
}
(1, k) => Prompt::new(
["Specify first point on circle", "Specify second point on circle", "Specify third point on circle"].get(k).copied().unwrap_or(""),
Accept::POINT,
)
.base_opt(self.pts.last().copied())
.deferred(),
.base_opt(self.pts.last().copied()),
(2, k) => Prompt::new(
if k == 0 { "Specify first end point of circle's diameter" } else { "Specify second end point of circle's diameter" },
Accept::POINT,
@@ -127,14 +120,7 @@ impl Interactive for CircleM {
let r = if self.diameter { c.dist(*e) / 2.0 } else { c.dist(*e) };
Some(Circle::new(*c, r))
}
1 if self.pts.len() == 3 => match self.three_points() {
Some(c) => Some(c),
None => {
self.pts.pop();
self.tans.truncate(self.pts.len());
return Err(crate::EngineError::Other("Circle does not exist.".into()));
}
},
1 if self.pts.len() == 3 => Circle::from_3_points(self.pts[0], self.pts[1], self.pts[2]),
2 if self.pts.len() == 2 => Some(Circle::from_2_points(self.pts[0], self.pts[1])),
_ => None,
};
@@ -144,29 +130,6 @@ impl Interactive for CircleM {
}
Ok(Step::Continue)
}
// 3P: a point picked with a tangent snap makes the circle tangent to that curve (#1512).
Input::Deferred(d) if self.mode == 1 => {
let tan = (d.mode == snap::mode::TAN && !matches!(d.curve, snap::SnapCurve::Line { .. })).then_some(d.curve);
self.tans.resize(self.pts.len(), None);
self.tans.push(tan);
self.input(s, Input::Point(d.at))
}
// A tangent picked for the radius: the circle around the center that touches the
// curve, on the side it was picked (#1512).
Input::Deferred(d) if self.mode == 0 && self.pts.len() == 1 => {
let Some(&c) = self.pts.first() else { return Ok(Step::Continue) };
// Around the picked curve's own center the circle would lie on it, not touch it.
let concentric =
matches!(d.curve, snap::SnapCurve::Circle { center, .. } | snap::SnapCurve::Arc { center, .. } if center.near(c, 1e-9));
let touch = d.curve.perpendiculars(c, d.at).into_iter().filter(|_| !concentric).min_by(|a, b| a.dist(d.at).total_cmp(&b.dist(d.at)));
match touch.map(|t| c.dist(t)).filter(|r| *r > 1e-12 && r.is_finite()) {
Some(r) => {
finish_circle(s, Circle::new(c, r))?;
Ok(Step::Done)
}
None => Err(crate::EngineError::Other("No circle around the center is tangent there.".into())),
}
}
Input::Text(t) if self.mode == 0 && self.pts.len() == 1 => {
let v = number(&t).ok_or_else(|| crate::EngineError::Other("Requires numeric distance or second point.".into()))?;
let r = if self.diameter { v / 2.0 } else { v };
@@ -211,38 +174,6 @@ impl Interactive for CircleM {
}
}
impl CircleM {
/// The 3P circle: through the three points, or tangent to the curves picked with TAN.
fn three_points(&self) -> Option<Circle> {
let [a, b, c] = <[Vec2; 3]>::try_from(self.pts.as_slice()).ok()?;
if self.tans.iter().all(Option::is_none) {
return Circle::from_3_points(a, b, c);
}
let tan = |i: usize| self.tans.get(i).copied().flatten();
// A plain point is a circle of radius zero to pass through; an arc is solved as its circle.
let target = |i: usize, p: Vec2| {
let circle = match tan(i) {
Some(snap::SnapCurve::Circle { center, radius } | snap::SnapCurve::Arc { center, radius, .. }) => Circle::new(center, radius),
_ => Circle::new(p, 0.0),
};
crate::cmd::curves::TanObj::Circle(circle)
};
let pts = [a, b, c];
// The circle must touch an arc within its sweep, not elsewhere on the arc's circle, and
// not be the picked circle itself (which lies on it rather than touching it).
let touches = |found: &Circle| {
pts.iter().enumerate().all(|(i, p)| {
tan(i).is_none_or(|t| {
let same = matches!(target(i, *p), crate::cmd::curves::TanObj::Circle(o)
if o.center.dist(found.center) + (o.radius - found.radius).abs() <= 1e-9 * o.radius);
!same && t.contains(target(i, *p).touch(found))
})
})
};
crate::cmd::curves::ttt_where([(target(0, a), a), (target(1, b), b), (target(2, c), c)], touches)
}
}
fn finish_circle(s: &mut Session, c: Circle) -> Result<()> {
s.add_entity(circle(c.center, c.radius))?;
s.doc_mut()?.header.set_f64("CIRCLERAD", c.radius);
+2 -14
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 (any standard size — ISO, JIS, ANSI — 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 (ISO A-series, 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,8 +573,7 @@ struct Frame {
landscape: bool,
}
/// The standard paper (ISO, JIS or ANSI) a frame of `w` x `h` mm fits (either orientation), and whether
/// it is landscape.
/// The ISO/ANSI paper 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);
@@ -879,17 +878,6 @@ 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,10 +326,6 @@ 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(),
@@ -556,36 +552,6 @@ 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);
+4 -6
View File
@@ -253,16 +253,14 @@ fn run_grip_rotate(s: &mut Session, p: &Value) -> Result<Value> {
fn run_grip_scale(s: &mut Session, p: &Value) -> Result<Value> {
let hs = targets(s, p)?;
let base = base_point(s, "grip.scale", p, &hs)?;
let f = match p.get("factor").and_then(Value::as_f64).filter(|a| a.is_finite()) {
Some(f) if f > 1e-12 => f,
let m = match p.get("factor").and_then(Value::as_f64).filter(|a| a.is_finite()) {
Some(f) if f > 0.0 => Mat3::scale_about(base, f),
Some(_) => return Err(bad("grip.scale", "factor must be positive")),
None => {
let f = base.dist(point_req("grip.scale", p, "to")?);
if f.is_finite() && f > 1e-12 { f } else { return Err(bad("grip.scale", "scale factor would be zero")) }
mode_matrix(GripMode::Scale, base, point_req("grip.scale", p, "to")?).ok_or_else(|| bad("grip.scale", "scale factor would be zero"))?
}
};
let r = super::modify::scale_entities(s, &hs, super::modify::at_elevation(s, base), f, bool_or(p, "copy", false))?;
Ok(json!({ "handles": r.iter().map(|h| h.hex()).collect::<Vec<_>>() }))
apply(s, &hs, &m, bool_or(p, "copy", false))
}
fn run_grip_mirror(s: &mut Session, p: &Value) -> Result<Value> {
+19 -48
View File
@@ -14,7 +14,7 @@ use cadcraft_geom::{Mat3, Vec2};
use super::gripcmds::stretch_grips;
use super::helpers::line;
use super::machines::number;
use super::modify::{at_elevation, scale_entities, transform_entities};
use super::modify::transform_entities;
use crate::grips::{GripAction, GripMode, grip_action, grip_actions, mode_matrix};
use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Running, Session, Step};
@@ -220,7 +220,14 @@ impl GripEdit {
}
}
fn finish_edit(&mut self, before: Arc<Drawing>, changed: bool) -> Result<Step> {
/// Edit with the dragged point `to` (STRETCH) or the transform `m` (the other modes).
fn edit(&mut self, s: &mut Session, to: Vec2, m: Option<Mat3>) -> Result<Step> {
let before = s.state()?.doc.clone();
let changed = match (self.mode, m) {
(GripMode::Stretch, _) => !stretch_grips(s, &self.hot, &self.targets, to - self.base, self.copy)?.is_empty(),
(_, Some(m)) => !transform_entities(s, &self.targets, &m, self.copy)?.is_empty(),
(_, None) => return Err(other("Invalid point.")),
};
if !changed {
return Err(other("The objects can't be edited that way (locked, or the result would be degenerate)."));
}
@@ -233,27 +240,6 @@ impl GripEdit {
}
}
/// Edit with the dragged point `to` (STRETCH) or the transform `m` (the other modes).
fn edit(&mut self, s: &mut Session, to: Vec2, m: Option<Mat3>) -> Result<Step> {
let before = s.state()?.doc.clone();
let changed = match (self.mode, m) {
(GripMode::Stretch, _) => !stretch_grips(s, &self.hot, &self.targets, to - self.base, self.copy)?.is_empty(),
(_, Some(m)) => !transform_entities(s, &self.targets, &m, self.copy)?.is_empty(),
(_, None) => return Err(other("Invalid point.")),
};
self.finish_edit(before, changed)
}
/// Scale `targets` uniformly about `base` in 3D, scaling text heights, elevations and thickness.
fn edit_scale(&mut self, s: &mut Session, f: f64) -> Result<Step> {
if !f.is_finite() || f <= 1e-12 {
return Err(other("Invalid point."));
}
let before = s.state()?.doc.clone();
let changed = !scale_entities(s, &self.targets, at_elevation(s, self.base), f, self.copy)?.is_empty();
self.finish_edit(before, changed)
}
fn mode_input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
match i {
Input::Keyword(k) => match k.as_str() {
@@ -300,20 +286,12 @@ impl GripEdit {
Ok(Step::Continue)
}
Input::Point(p) => {
if self.mode == GripMode::Scale {
self.edit_scale(s, self.base.dist(p))
} else {
let m = self.matrix(p);
self.edit(s, p, m)
}
let m = self.matrix(p);
self.edit(s, p, m)
}
Input::Deferred(d) => {
if self.mode == GripMode::Scale {
self.edit_scale(s, self.base.dist(d.at))
} else {
let m = self.matrix(d.at);
self.edit(s, d.at, m)
}
let m = self.matrix(d.at);
self.edit(s, d.at, m)
}
Input::Text(t) => match self.mode {
GripMode::Rotate => {
@@ -322,7 +300,7 @@ impl GripEdit {
}
GripMode::Scale => {
let f = positive(number(&t))?;
self.edit_scale(s, f)
self.edit(s, self.base, Some(Mat3::scale_about(self.base, f)))
}
_ => Err(other("Requires a point or an option keyword.")),
},
@@ -349,21 +327,14 @@ impl GripEdit {
(Ask::RefFirst, Input::Text(t)) => self.ask = Ask::RefNew(value(&t)?),
(Ask::RefFirst, Input::Enter) => self.ask = Ask::RefNew(if rotate { 0.0 } else { 1.0 }),
(Ask::RefSecond(a), Input::Point(p)) => self.ask = Ask::RefNew(between(a, p)?),
(Ask::RefNew(r), Input::Point(p)) => {
if rotate {
let m = self.matrix(p).ok_or_else(|| other("Requires a positive length."))?;
return self.edit(s, p, Some(m));
}
let f = positive(Some(self.base.dist(p) / r))?;
return self.edit_scale(s, f);
(Ask::RefNew(_), Input::Point(p)) => {
let m = self.matrix(p).ok_or_else(|| other("Requires a positive length."))?;
return self.edit(s, p, Some(m));
}
(Ask::RefNew(r), Input::Text(t)) => {
let v = value(&t)?;
if rotate {
return self.edit(s, self.base, Some(Mat3::rotate_about(self.base, v - r)));
}
let f = positive(Some(v / r))?;
return self.edit_scale(s, f);
let m = if rotate { Mat3::rotate_about(self.base, v - r) } else { Mat3::scale_about(self.base, positive(Some(v / r))?) };
return self.edit(s, self.base, Some(m));
}
(_, Input::Enter) => self.ask = Ask::Mode,
_ => {}
+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\"|\"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}",
"{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}",
),
CommandSpec::new("plot", "Print...", |s, p| run_plot(s, &super::plotters::plot_options(s, p, "plot")?, "plot"))
.menu(&["File", "Print..."])
-58
View File
@@ -602,61 +602,3 @@ fn plot_path_extension_picks_the_format_like_export() {
assert!(!dir.join("w.png").exists(), "nothing written when `output` and the path disagree");
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn osnap_in_mspace_skips_vplayer_frozen_layers() {
let mut s = Session::new();
s.execute("layer.new", &json!({"name": "Hidden"})).unwrap();
s.execute("line", &json!({"points": [[60, -25], [70, -25]]})).unwrap();
let line_h = s.doc().unwrap().model.iter().last().unwrap().handle;
s.execute("properties.set", &json!({"handles": [line_h], "layer": "Hidden"})).unwrap();
s.execute("layout.set", &json!({"name": "Layout1"})).unwrap();
s.execute("mview", &json!({"p1": [20, 20], "p2": [220, 120]})).unwrap();
let vp_h = viewports(&s, "Layout1").last().unwrap().0;
s.execute("vplayer", &json!({"handles": [vp_h], "freeze": ["Hidden"]})).unwrap();
s.execute("mspace", &json!({"handle": vp_h})).unwrap();
let ap = s.pixel_size() * s.settings.aperture.max(1.0);
let d = ap * 0.5;
let model_before = s.doc().unwrap().model.len();
for (ovr, pt, name) in [
("end", format!("{},-25", 60.0 + d), "Endpoint"),
("mid", format!("{},-25", 65.0 + d), "Midpoint"),
("nea", format!("63,{}", -25.0 + d), "Nearest"),
] {
s.cmdline("line").unwrap();
s.cmdline(ovr).unwrap();
s.cmdline(&pt).unwrap();
assert_eq!(
s.log.last().map(String::as_str),
Some(format!("No {name} found for specified point.").as_str()),
"{ovr} should not snap to a line on a VPLAYER-frozen layer; log: {:?}",
s.log
);
s.cmdline("").unwrap();
}
assert_eq!(s.doc().unwrap().model.len(), model_before, "no new line should be created");
// Running osnaps through snap_cursor must also ignore the VPLAYER-frozen layer.
s.settings.osmode = crate::snap::mode::END | crate::snap::mode::MID | crate::snap::mode::NEA;
let cs = s.snap_cursor(
cadcraft_geom::Vec2::new(60.0 + d, -25.0),
&crate::snap::tracking::CursorQuery { base: None, deferred: false, corner: false, aperture: ap, tol: ap, now: 0.0, shift: false },
);
assert!(cs.snap.is_none(), "running osnap should not snap to a VPLAYER-frozen line: {:?}", cs.snap);
// A block reference on layer "0" containing an entity on "Hidden" must also not snap.
s.execute("block", &json!({"name": "B", "base": [60, -25], "handles": [line_h]})).unwrap();
let model_with_block = s.doc().unwrap().model.len();
s.cmdline("line").unwrap();
s.cmdline("end").unwrap();
s.cmdline(&format!("{},-25", 60.0 + d)).unwrap();
assert_eq!(
s.log.last().map(String::as_str),
Some("No Endpoint found for specified point."),
"end should not snap to a block entity on a VPLAYER-frozen layer; log: {:?}",
s.log
);
s.cmdline("").unwrap();
assert_eq!(s.doc().unwrap().model.len(), model_with_block);
}
+1 -1
View File
@@ -36,7 +36,7 @@ use oops::run_oops;
pub(crate) use oops::{Erased, erase_kept};
use select_then::{DisplaceM, Op, SelectThen};
use stretch::{StretchM, run_stretch};
pub(crate) use transform::{at_elevation, holds_ole_frame, ole_refusal, refuse_ole_frames, scale_entities, transform_entities};
pub(crate) use transform::{holds_ole_frame, ole_refusal, refuse_ole_frames, transform_entities};
use transform::{mirror_entities, mirror_kind, run_copy, run_erase, run_mirror, run_move, run_rotate, run_scale};
pub(crate) use trim::{
CUT_ONCE, Edges, Overlay, edge_segments, edge_segments_over, extend, extend_kind, extended, json_pick_error, trim, trim_kind, trimmed,
+21 -76
View File
@@ -19,8 +19,7 @@ fn offsettable(k: &EntityKind) -> bool {
}
/// Offset an entity by `dist` towards `side`. Returns the new geometry.
/// `gap` is OFFSETGAPTYPE, used by polylines only.
pub(crate) fn offset_kind(k: &EntityKind, dist: f64, side: Vec2, gap: i64) -> Option<EntityKind> {
pub(crate) fn offset_kind(k: &EntityKind, dist: f64, side: Vec2) -> Option<EntityKind> {
match k {
EntityKind::Line(l) => {
let ln = Line::new(l.a.xy(), l.b.xy());
@@ -65,7 +64,7 @@ pub(crate) fn offset_kind(k: &EntityKind, dist: f64, side: Vec2, gap: i64) -> Op
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, gap).map(|vs| {
offset_polyline(&pl, d).map(|vs| {
let mut k = lwpoly(vs, p.closed);
if let EntityKind::LwPolyline(n) = &mut k {
n.const_width = p.const_width;
@@ -136,50 +135,35 @@ 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. `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() {
/// 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() {
return None;
}
let segs: Vec<Segment> = pairs.iter().map(|(_, o)| *o).collect();
let n = segs.len();
// 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);
// Where each offset segment starts after joining it to the previous one.
let mut starts: Vec<Vec2> = Vec::with_capacity(n);
for i in 0..n {
let s = segs.get(i)?;
joints.push(if i == 0 && !pl.closed {
(s.start(), None, s.start())
starts.push(if i == 0 && !pl.closed {
s.start()
} else {
let prev = segs.get((i + n - 1) % n)?;
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)
}
}
join_point(prev, s).unwrap_or(s.start())
});
}
let mut verts: Vec<PolyVertex> = Vec::new();
for i in 0..n {
let s = segs.get(i)?;
let start = joints.get(i)?.2;
let next = if i + 1 < n {
joints.get(i + 1)
let start = *starts.get(i)?;
let end = if i + 1 < n {
*starts.get(i + 1)?
} else if pl.closed {
joints.first()
*starts.first()?
} else {
None
s.end()
};
let end = next.map_or(s.end(), |j| j.0);
let bulge = match s {
Segment::Line(_) => 0.0,
Segment::Arc { arc, ccw } => {
@@ -195,9 +179,6 @@ pub(crate) fn offset_polyline(pl: &Polyline, d: f64, gap: i64) -> Option<Vec<Pol
}
};
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()));
@@ -205,40 +186,6 @@ pub(crate) fn offset_polyline(pl: &Polyline, d: f64, gap: i64) -> Option<Vec<Pol
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());
@@ -255,8 +202,7 @@ 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 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 k = offset_kind(&e.kind, dist.abs(), side).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,
@@ -375,10 +321,9 @@ impl Interactive for OffsetM {
}
let (erase, current) = offset_options(s);
s.echo(format!(
"Current settings: Erase source={} Layer={} OFFSETGAPTYPE={}",
"Current settings: Erase source={} Layer={} OFFSETGAPTYPE=0",
if erase { "Yes" } else { "No" },
if current { "Current" } else { "Source" },
s.doc().map(|d| d.header.i64("OFFSETGAPTYPE", 0)).unwrap_or(0)
if current { "Current" } else { "Source" }
));
Ok(Step::Continue)
}
@@ -546,7 +491,7 @@ impl Interactive for OffsetM {
.fold(f64::INFINITY, f64::min)
}
};
match offset_kind(&e.kind, dist, p, s.doc()?.header.i64("OFFSETGAPTYPE", 0)) {
match offset_kind(&e.kind, dist, p) {
Some(k) => {
let before = s.state()?.doc.clone();
let (erase, current) = offset_options(s);
@@ -576,6 +521,6 @@ impl Interactive for OffsetM {
Some(x) => x,
None => crate::select::entity_distance(d, e, c, 1e-3),
};
offset_kind(&e.kind, dist, c, d.header.i64("OFFSETGAPTYPE", 0)).into_iter().collect()
offset_kind(&e.kind, dist, c).into_iter().collect()
}
}
+44 -78
View File
@@ -39,11 +39,12 @@ pub(super) struct SelectThen {
objs: Vec<Handle>,
pts: Vec<Vec2>,
reference: bool,
/// ROTATE Reference: the reference angle (radians), once known.
/// ROTATE Reference: the reference angle (radians), once known. Its first point, and the
/// first of the two new-angle points, are kept in `ref_from`.
ref_angle: Option<f64>,
/// ROTATE/SCALE Reference: the new angle/length is given by two points (the `Points` option).
/// ROTATE Reference: the new angle is given by two points (the `Points` option).
ref_points: bool,
/// ROTATE/SCALE Reference: first point of a reference or `Points` pair given by two points.
/// SCALE Reference: first point of a reference length given by two points.
ref_from: Option<Vec2>,
/// SCALE Reference: the reference length, once known.
ref_len: Option<f64>,
@@ -264,47 +265,30 @@ impl SelectThen {
}
}
/// SCALE Reference: reference length (typed, or two points), then new length (typed, a point
/// measured from the base point, or two points after `Points`). The scale factor is new length /
/// reference length.
/// SCALE Reference: reference length (typed, or two points), then new length (typed, or a
/// point measured from the base point). The scale factor is new length / reference length.
fn scale_reference(&mut self, s: &mut Session, i: Input) -> Result<Step> {
let Some(base) = self.pts.first().copied() else { return Ok(Step::Done) };
if matches!(&i, Input::Keyword(k) if k == "Copy") {
self.copy_mode = true;
s.echo("Scaling a copy of the selected objects.");
return Ok(Step::Continue);
}
let Some(r) = self.ref_len else {
match (self.ref_from, i) {
(None, Input::Point(p)) => self.ref_from = Some(p),
(None, Input::Text(t)) => self.ref_len = Some(require_length(number(&t))?),
(None, Input::Enter) => self.ref_len = Some(1.0),
(Some(a), Input::Point(p)) => {
self.ref_len = Some(require_length(Some(a.dist(p)))?);
self.ref_from = None;
}
(_, Input::Enter) => return Ok(Step::Done),
_ => {}
}
return Ok(Step::Continue);
};
match (self.ref_points, self.ref_from, i) {
(false, _, Input::Keyword(k)) if k == "Points" => {
self.ref_points = true;
self.ref_from = None;
Ok(Step::Continue)
}
(false, _, Input::Point(p)) => self.scale_by(s, base, base.dist(p) / r),
(false, _, Input::Text(t)) => {
let n = require_length(number(&t))?;
self.scale_by(s, base, n / r)
}
(true, None, Input::Point(p)) => {
match (self.ref_len, self.ref_from, i) {
(None, None, Input::Point(p)) => {
self.ref_from = Some(p);
Ok(Step::Continue)
}
(true, Some(a), Input::Point(p)) => {
let n = require_length(Some(a.dist(p)))?;
(None, None, Input::Text(t)) => {
self.ref_len = Some(require_length(number(&t))?);
Ok(Step::Continue)
}
(None, None, Input::Enter) => {
self.ref_len = Some(1.0);
Ok(Step::Continue)
}
(None, Some(a), Input::Point(p)) => {
self.ref_len = Some(require_length(Some(a.dist(p)))?);
Ok(Step::Continue)
}
(Some(r), _, Input::Point(p)) => self.scale_by(s, base, base.dist(p) / r),
(Some(r), _, Input::Text(t)) => {
let n = require_length(number(&t))?;
self.scale_by(s, base, n / r)
}
(_, _, Input::Enter) => Ok(Step::Done),
@@ -312,26 +296,6 @@ impl SelectThen {
}
}
/// The prompt while SCALE Reference collects its lengths.
fn scale_reference_prompt(&self) -> Prompt {
let base = self.pts.first().copied();
match (self.ref_len, self.ref_points, self.ref_from) {
(None, _, None) => Prompt::new("Specify reference length", Accept::POINT_OR_NUMBER).kw(&["Copy"]).default("1"),
(None, _, Some(p)) | (Some(_), true, Some(p)) => Prompt::new("Specify second point", Accept::POINT).base(p),
(Some(_), false, _) => Prompt::new("Specify new length", Accept::POINT_OR_NUMBER).kw(&["Points", "Copy"]).base_opt(base).distance(),
(Some(_), true, None) => Prompt::new("Specify first point", Accept::POINT),
}
}
/// Live factor and rubber-band anchor while SCALE Reference previews with the cursor at `c`.
fn scale_reference_factor(&self, base: Vec2, c: Vec2) -> Option<(f64, Vec2)> {
match (self.ref_len, self.ref_points, self.ref_from) {
(Some(r), false, _) => positive_length(Some(base.dist(c) / r)).map(|f| (f, base)),
(Some(r), true, Some(a)) => positive_length(Some(a.dist(c) / r)).map(|f| (f, a)),
_ => None,
}
}
/// ROTATE Reference: reference angle (typed, or two points), then the new angle (typed, a
/// point measured from the base point, or two points after `Points`). The objects turn by the
/// new angle minus the reference angle.
@@ -493,7 +457,11 @@ impl Interactive for SelectThen {
let k = self.pts.len();
let base = self.pts.first().copied();
if self.op == Op::Scale && self.reference {
return self.scale_reference_prompt();
return match (self.ref_len, self.ref_from) {
(Some(_), _) => Prompt::new("Specify new length", Accept::POINT_OR_NUMBER).base_opt(base),
(None, Some(p)) => Prompt::new("Specify second point", Accept::POINT).base(p),
(None, None) => Prompt::new("Specify reference length", Accept::POINT_OR_NUMBER).default("1"),
};
}
if self.op == Op::Rotate && self.reference {
return self.rotate_reference_prompt();
@@ -637,15 +605,16 @@ impl Interactive for SelectThen {
return Vec::new();
}
let Some(base) = self.pts.first().copied() else { return Vec::new() };
let (m, rubber_from) = match self.op {
Op::Move | Op::Copy => (Mat3::translate(c - base), base),
Op::Rotate => (Mat3::rotate_about(base, base.angle_to(c)), base),
Op::Scale if !self.reference => (Mat3::scale_about(base, base.dist(c).max(1e-9)), base),
Op::Scale => match self.scale_reference_factor(base, c) {
Some((f, from)) => (Mat3::scale_about(base, f), from),
let m = match self.op {
Op::Move | Op::Copy => Mat3::translate(c - base),
Op::Rotate => Mat3::rotate_about(base, base.angle_to(c)),
Op::Scale if !self.reference => Mat3::scale_about(base, base.dist(c).max(1e-9)),
Op::Scale => match self.ref_len.and_then(|r| positive_length(Some(base.dist(c) / r))) {
Some(f) => Mat3::scale_about(base, f),
None if self.ref_len.is_some() => return Vec::new(),
None => return self.ref_from.map(|a| vec![line(a, c)]).unwrap_or_default(),
},
Op::Mirror if !self.ask_erase => (Mat3::mirror(base, c), base),
Op::Mirror if !self.ask_erase => Mat3::mirror(base, c),
_ => return Vec::new(),
};
let Ok(d) = s.doc() else { return Vec::new() };
@@ -664,7 +633,7 @@ impl Interactive for SelectThen {
k
})
.collect();
out.push(line(rubber_from, c));
out.push(line(base, c));
out
}
/// Separate shared GPU transforms from objects that need an individual MIRROR preview.
@@ -673,18 +642,15 @@ impl Interactive for SelectThen {
return None;
}
let base = self.pts.first().copied()?;
let (matrix, rubber_from) = match self.op {
Op::Move | Op::Copy => (Mat3::translate(c - base), base),
Op::Rotate => (Mat3::rotate_about(base, base.angle_to(c)), base),
Op::Scale if !self.reference => (Mat3::scale_about(base, base.dist(c).max(1e-9)), base),
Op::Scale => {
let (f, from) = self.scale_reference_factor(base, c)?;
(Mat3::scale_about(base, f), from)
}
Op::Mirror if !self.ask_erase => (Mat3::mirror(base, c), base),
let matrix = match self.op {
Op::Move | Op::Copy => Mat3::translate(c - base),
Op::Rotate => Mat3::rotate_about(base, base.angle_to(c)),
Op::Scale if !self.reference => Mat3::scale_about(base, base.dist(c).max(1e-9)),
Op::Scale => Mat3::scale_about(base, self.ref_len.and_then(|r| positive_length(Some(base.dist(c) / r)))?),
Op::Mirror if !self.ask_erase => Mat3::mirror(base, c),
_ => return None,
};
let mut extra = vec![line(rubber_from, c)];
let mut extra = vec![line(base, c)];
if self.op != Op::Mirror {
return Some(crate::prompt::Drag { handles: self.objs.clone(), matrix, extra, clipboard: false });
}
+47 -186
View File
@@ -1,11 +1,9 @@
//! 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 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.
//! (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.
use cadcraft_doc::{EntityKind, Handle, LwPolyline};
use cadcraft_geom::{Circle, Line, PolyVertex, Polyline, Segment, Vec2, arc_to_bulge, bulge_to_arc, line_circle, line_line_infinite};
use cadcraft_geom::{Line, PolyVertex, Polyline, Segment, Vec2, arc_to_bulge, bulge_to_arc, line_line_infinite};
use super::{curves, other, push_entity, set_kind};
use crate::cmd::helpers::{arc, line};
@@ -140,205 +138,61 @@ fn same_polyline(
Ok(Some(h))
}
/// 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.
/// An open polyline's straight end segment with a line: the corner is cut and the line joins
/// the polyline.
#[allow(clippy::too_many_arguments)]
fn polyline_and_other(
fn polyline_and_line(
s: &mut Session,
(hp, pl, pp): (Handle, &LwPolyline, Vec2),
(ho, ko, po): (Handle, &EntityKind, Vec2),
(hl, ln, lp): (Handle, Line, Vec2),
polyline_first: bool,
r: f64,
chamfer: Option<ChamferDistances>,
trim: bool,
) -> Result<Option<Handle>> {
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)
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()))
}
_ => return Err(other("A polyline fillets or chamfers with a line, or with another segment of itself.")),
_ => k == last,
};
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),
// 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."));
};
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(mine.inner()), side(theirs.inner()), r, chamfer)?
corner(x, side(inner.p), side(keep_line), r, chamfer)?
} else {
let c = corner(x, side(theirs.inner()), side(mine.inner()), r, chamfer)?;
let c = corner(x, side(keep_line), side(inner.p), r, chamfer)?;
Corner { t1: c.t2, t2: c.t1, bulge: -c.bulge }
};
if !trim {
return add_loose(s, hp, &c);
}
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.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 {
vs = curves::reverse_vertices(&vs, false);
}
set_kind(s, hp, EntityKind::LwPolyline(LwPolyline { vertices: vs, ..pl.clone() }))?;
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);
s.doc_mut()?.remove_entity(hl);
Ok(Some(hp))
}
@@ -363,13 +217,20 @@ 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)?,
// 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)?
(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)?
}
(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,135 +823,6 @@ 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
@@ -1,340 +0,0 @@
//! 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,7 +57,6 @@ pub const FILES: &[&str] = &[
"stylesmanager",
"tableexport",
"wblock",
"whohas",
"xattach",
"xbind",
"xopen",
-1
View File
@@ -19,7 +19,6 @@ 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;
+7 -32
View File
@@ -126,36 +126,14 @@ pub fn snap_name(m: u32) -> &'static str {
mode::ALL.iter().find(|(b, _)| *b == m).map_or("None", |(_, n)| *n)
}
/// The candidate snaps near `cursor` for Tab cycling: the snap [`crate::snap::osnap`] picks
/// first, then every other snap of the modes in `osmode` under the aperture (each endpoint of
/// each object, each intersection …; [`crate::snap::osnap_all`]), best first, without repeats.
/// The candidate snaps near `cursor` for Tab cycling: every object snap within the aperture, the
/// one [`crate::snap::osnap`] picks first and the rest in its order (specific snaps nearest
/// first, then deferred snaps, then Nearest), without repeats.
pub fn snap_candidates(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Vec<SnapHit> {
snap_candidates_with_frozen(d, space, cursor, aperture, osmode, base, deferred, &[])
}
/// [`snap_candidates`] skipping entities (and block leaves) on `frozen` layers in `space`.
#[allow(clippy::too_many_arguments)]
pub fn snap_candidates_with_frozen(
d: &Drawing,
space: &Space,
cursor: Vec2,
aperture: f64,
osmode: u32,
base: Option<Vec2>,
deferred: bool,
frozen: &[String],
) -> Vec<SnapHit> {
// A base that is not a number would give meaningless perpendiculars and tangents.
if osmode & !mode::HATCH == 0 || osmode & mode::OFF != 0 || base.is_some_and(|b| !b.is_finite()) {
if osmode & !mode::HATCH == 0 || osmode & mode::OFF != 0 {
return Vec::new();
}
let mut out: Vec<SnapHit> = crate::snap::osnap_with_frozen(d, space, cursor, aperture, osmode, base, deferred, frozen).into_iter().collect();
for h in crate::snap::osnap_all_with_frozen(d, space, cursor, aperture, osmode, base, deferred, frozen) {
if !out.iter().any(|o| o.same(&h, aperture)) {
out.push(h);
}
}
out
crate::snap::osnap_all(d, space, cursor, aperture, osmode, base, deferred)
}
/// Strip the international (`_`) and transparent (`'`) prefixes a modifier may be typed with.
@@ -365,15 +343,12 @@ impl Session {
Frame::Snap { mode } => {
// Snap the point with this mode alone, within the aperture.
let prompt = self.current_prompt();
let (doc, space, frozen) = {
let st = self.state()?;
(st.doc.clone(), st.edit_space(), st.viewport_frozen().to_vec())
};
let space = self.space();
let aperture = self.pixel_size() * self.settings.aperture.max(1.0);
let hatch = if self.settings.osnaphatch { mode::HATCH } else { 0 };
let base = prompt.as_ref().and_then(|q| q.base);
let deferred = prompt.as_ref().is_some_and(|q| q.deferred);
let hit = crate::snap::osnap_with_frozen(&doc, &space, p, aperture, mode | hatch, base, deferred, &frozen);
let hit = crate::snap::osnap(self.doc()?, &space, p, aperture, mode | hatch, base, deferred);
match hit {
Some(h) if self.point_mods.is_empty() => return self.input_snapped(h),
Some(h) => p = h.point,
+2 -3
View File
@@ -76,9 +76,8 @@ pub struct Prompt {
/// Rubber-band origin (for direct distance entry, ortho and polar).
pub base: Option<Vec2>,
/// The command resolves deferred tangent/perpendicular snaps ([`Input::Deferred`]) at this
/// prompt (a point with no base yet, e.g. the first point of a line; with a base, only
/// tangents, e.g. a circle's radius). Elsewhere a deferred pick arrives as the plain point it
/// was picked at.
/// prompt (a point with no base yet, e.g. the first point of a line). Elsewhere a deferred
/// pick arrives as the plain point it was picked at.
pub deferred: bool,
/// The base is a rectangle's first corner (ZOOM Window, PLOTWINDOW, RECTANG, ARRAYRECT's unit
/// cell, MTEXT): ortho does not bend the opposite corner, so the rectangle keeps its area.
+210 -553
View File
@@ -65,24 +65,6 @@ pub struct SnapHit {
}
impl SnapHit {
fn plain(mode: u32, point: Vec2) -> SnapHit {
SnapHit { point, mode, name: name_of(mode), viewport: None, deferred: None }
}
/// The same snap as `o`, for a Tab list without repeats: the same mode at the same point
/// (within a millionth of `aperture`), deferred or not alike (and if deferred, on the same
/// curve), and from the same source (this space, or one viewport). Overlapping viewports can
/// show different model points at one paper point; each stays a candidate, since DIST
/// measures in the model units of the viewport picked.
pub(crate) fn same(&self, o: &SnapHit, aperture: f64) -> bool {
self.mode == o.mode
// Deferred snaps on different curves at one provisional point stay apart: the line
// drawn from each depends on its curve.
&& self.deferred.map(|d| d.curve) == o.deferred.map(|d| d.curve)
&& self.viewport.map(|v| v.viewport) == o.viewport.map(|v| v.viewport)
&& self.point.near(o.point, aperture * 1e-6)
}
/// The command input a pick at this snap gives: a deferred snap or a plain point.
pub fn input(&self) -> crate::Input {
match self.deferred {
@@ -90,6 +72,33 @@ impl SnapHit {
None => crate::Input::Point(self.point),
}
}
fn plain(mode: u32, point: Vec2) -> SnapHit {
SnapHit { point, mode, name: name_of(mode), viewport: None, deferred: None }
}
/// Where this hit sorts among the candidates near a cursor: specific snaps by distance
/// (Endpoint and Intersection favoured a little), then deferred snaps, then Nearest.
fn rank(&self, cursor: Vec2, aperture: f64) -> (u8, f64) {
let class = if self.deferred.is_some() {
1
} else if self.mode == mode::NEA {
2
} else {
0
};
(class, snap_score(self.mode, self.point, cursor, aperture))
}
/// The same snap as `o`: mode and point, from the same source (paper space, or one
/// viewport). Overlapping viewports can show different model points at one paper point;
/// each stays a candidate, since DIST measures in the model units of the viewport picked.
fn same(&self, o: &SnapHit) -> bool {
self.mode == o.mode
&& self.deferred.is_some() == o.deferred.is_some()
&& self.viewport.map(|v| v.viewport) == o.viewport.map(|v| v.viewport)
&& self.point.near(o.point, 1e-9 * (1.0 + self.point.len()))
}
}
/// The curve a deferred snap refers to.
@@ -128,16 +137,12 @@ impl SnapCurve {
}
/// Points on the curve whose perpendicular passes through `p`; `picked` is where the curve
/// was picked, kept when `p` is the center of a circle or arc (every radius is perpendicular).
pub(crate) fn perpendiculars(&self, p: Vec2, picked: Vec2) -> Vec<Vec2> {
fn perpendiculars(&self, p: Vec2, picked: Vec2) -> Vec<Vec2> {
match self {
SnapCurve::Circle { center, radius } | SnapCurve::Arc { center, radius, .. } => {
let u = (p - *center).normalized();
if u == Vec2::ZERO {
// On an arc, the point within its sweep.
vec![match *self {
SnapCurve::Arc { center, radius, start, end } => cadcraft_geom::Arc::new(center, radius, start, end).closest(picked),
_ => Circle::new(*center, *radius).closest(picked),
}]
vec![Circle::new(*center, *radius).closest(picked)]
} else {
[*center + u * *radius, *center - u * *radius].into_iter().filter(|q| self.contains(*q)).collect()
}
@@ -224,34 +229,23 @@ fn prim_segments(p: &Prim) -> Vec<Segment> {
/// Tangent and perpendicular snaps need the base point (the other end of the line). With no
/// base and `deferred` set (the prompt says it can resolve them, `Prompt.deferred`),
/// they snap as *deferred*: the hit carries the curve and is resolved once the other end is
/// known. With a base and `deferred` set, tangents to circles and circular arcs are deferred too
/// (CIRCLE's radius: the circle around the base that touches the curve, #1512); an elliptical arc
/// or a spline keeps its ordinary tangent from the base. Deferred hits only win
/// where no other snap does (they are as unspecific as Nearest).
/// known. Deferred hits only win where no other snap does (they are as unspecific as Nearest).
pub fn osnap(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Option<SnapHit> {
osnap_with_frozen(d, space, cursor, aperture, osmode, base, deferred, &[])
}
/// [`osnap`] skipping entities (and block leaves) on `frozen` layers in `space`.
#[allow(clippy::too_many_arguments)]
pub fn osnap_with_frozen(
d: &Drawing,
space: &Space,
cursor: Vec2,
aperture: f64,
osmode: u32,
base: Option<Vec2>,
deferred: bool,
frozen: &[String],
) -> Option<SnapHit> {
if osmode == 0 || osmode & mode::OFF != 0 {
return None;
}
let ix = crate::spatial::index(d, space);
osnap_with_neighborhood(d, space, &ix, cursor, aperture, osmode, base, deferred, frozen).0
osnap_with(d, space, &ix, cursor, aperture, osmode, base, deferred)
}
/// Every object snap within `aperture` of `cursor`, the one [`osnap`] picks first and the rest
/// in the order Tab cycles them: specific snaps nearest first, then deferred snaps, then Nearest.
/// Snaps seen through layout viewports are included.
pub fn osnap_all(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Vec<SnapHit> {
let ix = crate::spatial::index(d, space);
osnap_all_with_neighborhood(d, space, &ix, cursor, aperture, osmode, base, deferred).0
}
#[cfg(test)]
#[allow(clippy::too_many_arguments)]
pub(crate) fn osnap_with(
d: &Drawing,
@@ -263,7 +257,7 @@ pub(crate) fn osnap_with(
base: Option<Vec2>,
deferred: bool,
) -> Option<SnapHit> {
osnap_with_neighborhood(d, space, ix, cursor, aperture, osmode, base, deferred, &[]).0
osnap_with_neighborhood(d, space, ix, cursor, aperture, osmode, base, deferred).0
}
/// Find the best object snap and retain the local-space primitives gathered for that query.
@@ -277,21 +271,40 @@ pub(crate) fn osnap_with_neighborhood(
osmode: u32,
base: Option<Vec2>,
deferred: bool,
frozen: &[String],
) -> (Option<SnapHit>, Option<Vec<Prim>>) {
let (all, prims) = osnap_all_with_neighborhood(d, space, ix, cursor, aperture, osmode, base, deferred);
(all.into_iter().next(), prims)
}
/// Every object snap near the cursor ([`osnap_all`]) and the local-space primitives gathered.
#[allow(clippy::too_many_arguments)]
fn osnap_all_with_neighborhood(
d: &Drawing,
space: &Space,
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
cursor: Vec2,
aperture: f64,
osmode: u32,
base: Option<Vec2>,
deferred: bool,
) -> (Vec<SnapHit>, Option<Vec<Prim>>) {
if osmode == 0 || osmode & mode::OFF != 0 || !cursor.is_finite() || !(aperture.is_finite() && aperture > 0.0) {
return (None, None);
return (Vec::new(), None);
}
let (mut best, near_prims) = match osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, frozen, None) {
Some((hit, prims)) => (hit, Some(prims)),
None => (None, None),
let (mut all, near_prims) = match osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, &[], None) {
Some((hits, prims)) => (hits, Some(prims)),
None => (Vec::new(), None),
};
let views = viewport::near(d, space, cursor, aperture);
if views.is_empty() {
return (best.map(|(h, _)| h), near_prims);
return (all, near_prims);
}
let model = Space::Model;
let model_ix = crate::spatial::index(d, &model);
// What a click picks across spaces stays as it was: each space's best snap, and a viewport's
// replaces the best so far only when it scores closer. A paper-space Nearest can therefore
// beat an Endpoint seen through a viewport, which `ranked` alone would put first.
let mut pick = all.first().copied();
for view in views {
let model_cursor = view.to_model(cursor);
let model_aperture = aperture / view.scale;
@@ -299,49 +312,66 @@ pub(crate) fn osnap_with_neighborhood(
if !model_cursor.is_finite() || !(model_aperture.is_finite() && model_aperture > 0.0) || model_base.is_some_and(|p| !p.is_finite()) {
continue;
}
let Some((cands, prims)) = collect_in(d, &model, &model_ix, model_cursor, model_aperture, osmode, &view.viewport.frozen_layers) else {
continue;
};
let clip = Some(view.model_clip);
// The rank was found in model units: paper units are model units times the scale.
let project = |(h, r): (SnapHit, Rank)| Some((view.hit(h)?, Rank { score: r.score * view.scale, ..r }));
let first = finish(cands.clone(), &prims, model_cursor, model_aperture, osmode, model_base, deferred, clip);
// The model clip is the box round the viewport as the model sees it, larger than the
// viewport when it is twisted: a snap inside it can still fall off the viewport. Then the
// best of the others that is on it, as Tab ranks them.
let hit = first.and_then(|f| {
project(f)
.or_else(|| finish_all(cands, &prims, model_cursor, model_aperture, osmode, model_base, deferred, clip).into_iter().find_map(project))
});
if let Some((hit, rank)) = hit
&& best.as_ref().is_none_or(|(_, b)| rank.beats(b))
let hits = osnap_in(
d,
&model,
&model_ix,
model_cursor,
model_aperture,
osmode,
model_base,
deferred,
&view.viewport.frozen_layers,
Some(view.model_clip),
);
if let Some(hit) = hits.first().and_then(|h| view.hit(*h))
&& pick.as_ref().is_none_or(|b| snap_score(hit.mode, hit.point, cursor, aperture) < snap_score(b.mode, b.point, cursor, aperture))
{
best = Some((hit, rank));
pick = Some(hit);
}
all.extend(hits.into_iter().filter_map(|h| view.hit(h)));
}
let mut out = ranked(all, cursor, aperture);
if let Some(pick) = pick {
out.retain(|h| !h.same(&pick));
out.insert(0, pick);
}
(out, near_prims)
}
/// `hits` best first ([`SnapHit::rank`]), without repeats.
fn ranked(mut hits: Vec<SnapHit>, cursor: Vec2, aperture: f64) -> Vec<SnapHit> {
hits.sort_by(|a, b| {
let (ca, sa) = a.rank(cursor, aperture);
let (cb, sb) = b.rank(cursor, aperture);
ca.cmp(&cb).then(sa.total_cmp(&sb))
});
let mut out: Vec<SnapHit> = Vec::with_capacity(hits.len());
for h in hits {
if !out.iter().any(|o| o.same(&h)) {
out.push(h);
}
}
(best.map(|(h, _)| h), near_prims)
out
}
/// How a hit ranks against the hits of another space (paper space, another viewport) and, for
/// Tab, against the other candidates: first the order [`finish`] tries them in (snap points, then
/// a perpendicular or tangent on the object under the cursor or a center found from its curve,
/// then deferred snaps, then Nearest), then its score within that tier, in the units of the cursor.
#[derive(Clone, Copy, Debug)]
struct Rank {
tier: u8,
score: f64,
}
impl Rank {
fn cmp(&self, other: &Rank) -> std::cmp::Ordering {
self.tier.cmp(&other.tier).then(self.score.total_cmp(&other.score))
}
fn beats(&self, other: &Rank) -> bool {
self.cmp(other).is_lt()
}
#[allow(clippy::too_many_arguments)]
fn osnap_in(
d: &Drawing,
space: &Space,
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
cursor: Vec2,
aperture: f64,
osmode: u32,
base: Option<Vec2>,
deferred: bool,
frozen: &[String],
clip: Option<Bounds2>,
) -> Vec<SnapHit> {
osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, frozen, clip).map(|(hits, _)| hits).unwrap_or_default()
}
/// The snaps near the cursor in one space, best first, and the primitives gathered there.
#[allow(clippy::too_many_arguments)]
fn osnap_in_with_prims(
d: &Drawing,
@@ -354,92 +384,7 @@ fn osnap_in_with_prims(
deferred: bool,
frozen: &[String],
clip: Option<Bounds2>,
) -> Option<(Option<(SnapHit, Rank)>, Vec<Prim>)> {
let (cands, near_prims) = collect_in(d, space, ix, cursor, aperture, osmode, frozen)?;
let hit = finish(cands, &near_prims, cursor, aperture, osmode, base, deferred, clip);
Some((hit, near_prims))
}
/// Every snap of `osmode` under the aperture round `cursor`, best first: Tab cycles through
/// these. Each mode's points of every object nearby, the intersections, perpendicular and
/// tangent points from `base`, the centers found from their curves, the deferred snaps and the
/// nearest point of each object, ranked as [`osnap`] ranks them, without repeats and at most
/// [`MAX_CYCLE`]; in viewports too, as [`osnap`] snaps.
pub fn osnap_all(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Vec<SnapHit> {
osnap_all_with_frozen(d, space, cursor, aperture, osmode, base, deferred, &[])
}
/// [`osnap_all`] skipping entities (and block leaves) on `frozen` layers in `space`.
#[allow(clippy::too_many_arguments)]
pub fn osnap_all_with_frozen(
d: &Drawing,
space: &Space,
cursor: Vec2,
aperture: f64,
osmode: u32,
base: Option<Vec2>,
deferred: bool,
frozen: &[String],
) -> Vec<SnapHit> {
if osmode == 0
|| osmode & mode::OFF != 0
|| !cursor.is_finite()
|| !(aperture.is_finite() && aperture > 0.0)
|| base.is_some_and(|b| !b.is_finite())
{
return Vec::new();
}
let ix = crate::spatial::index(d, space);
let mut out: Vec<(SnapHit, Rank)> = Vec::new();
if let Some((cands, prims)) = collect_in(d, space, &ix, cursor, aperture, osmode, frozen) {
out = finish_all(cands, &prims, cursor, aperture, osmode, base, deferred, None);
}
let model = Space::Model;
let views = viewport::near(d, space, cursor, aperture);
if !views.is_empty() {
let model_ix = crate::spatial::index(d, &model);
for view in views {
let (mc, ma, mb) = (view.to_model(cursor), aperture / view.scale, base.map(|p| view.to_model(p)));
if !mc.is_finite() || !(ma.is_finite() && ma > 0.0) || mb.is_some_and(|p| !p.is_finite()) {
continue;
}
let Some((cands, prims)) = collect_in(d, &model, &model_ix, mc, ma, osmode, &view.viewport.frozen_layers) else { continue };
// The rank was found in model units: paper units are model units times the scale.
out.extend(
finish_all(cands, &prims, mc, ma, osmode, mb, deferred, Some(view.model_clip))
.into_iter()
.filter_map(|(h, r)| Some((view.hit(h)?, Rank { score: r.score * view.scale, ..r }))),
);
}
}
out.sort_by(|a, b| a.1.cmp(&b.1));
let mut unique: Vec<SnapHit> = Vec::with_capacity(out.len().min(MAX_CYCLE));
for (h, _) in out {
if unique.len() >= MAX_CYCLE {
break;
}
if !unique.iter().any(|u| u.same(&h, aperture)) {
unique.push(h);
}
}
unique
}
/// Most snaps [`osnap_all`] offers.
const MAX_CYCLE: usize = 256;
/// The candidate snap points near `cursor` (each with its mode) and the primitives near it:
/// [`gather_in`]'s, plus the intersections between those primitives.
#[allow(clippy::too_many_arguments)]
fn collect_in(
d: &Drawing,
space: &Space,
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
cursor: Vec2,
aperture: f64,
osmode: u32,
frozen: &[String],
) -> Option<(Vec<(u32, Vec2)>, Vec<Prim>)> {
) -> Option<(Vec<SnapHit>, Vec<Prim>)> {
let (mut cands, near_prims) = gather_in(d, space, ix, cursor, aperture, osmode, frozen, None)?;
// Intersections between nearby primitives; Apparent Intersection also where their extensions
// meet (lines extended, arcs as full circles: in 2D, the "apparent" crossing of objects
@@ -477,7 +422,8 @@ fn collect_in(
}
}
}
Some((cands, near_prims))
let hits = finish(cands, &near_prims, cursor, aperture, osmode, base, deferred, clip);
Some((hits, near_prims))
}
fn finite_intersection_probe(cursor: Vec2, aperture: f64) -> Option<Bounds2> {
@@ -519,6 +465,19 @@ pub(crate) fn extendable(p: &Prim) -> bool {
matches!(p, Prim::Seg(_) | Prim::Circle(_) | Prim::Infinite { .. })
}
/// The snap candidates of `osmode` and the primitives within `aperture` of `cursor`; `None`
/// when the drawing can't be searched.
pub(crate) fn gather(
d: &Drawing,
space: &Space,
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
cursor: Vec2,
aperture: f64,
osmode: u32,
) -> Option<(Vec<(u32, Vec2)>, Vec<Prim>)> {
gather_in(d, space, ix, cursor, aperture, osmode, &[], None)
}
/// The point nearest `cursor` within `aperture` on the visible objects of `space` other than
/// `skip` (and on the objects inside block references), with the object's direction there (a unit
/// vector; a circle's or arc's runs counterclockwise): what an alignment grip aligns a dynamic
@@ -569,10 +528,8 @@ pub(crate) fn nearest_with_direction(
best.map(|(_, at, dir)| (at, dir))
}
/// The snap candidates of `osmode` and the primitives within `aperture` of `cursor`; `None`
/// when the drawing can't be searched.
#[allow(clippy::too_many_arguments)]
pub(crate) fn gather_in(
fn gather_in(
d: &Drawing,
space: &Space,
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
@@ -646,19 +603,8 @@ pub(crate) fn gather_in(
Some((cands, near_prims))
}
/// Picks the best of the gathered candidates, adding the base-dependent and deferred snaps, with
/// its [`Rank`].
///
/// In order of preference (the rank's tier):
/// 0. the snap point within `aperture` of the cursor that scores best (see [`snap_score`]),
/// perpendicular and tangent points from the base point included;
/// 1. with a base point, a perpendicular or tangent on an object that passes within `aperture`,
/// wherever its point lies (see [`from_base_on_objects`]), or the center of a circle, arc or
/// ellipse under the cursor (see [`curve_centers`]): the object nearest the cursor;
/// 2. a deferred perpendicular or tangent (no base point yet);
/// 3. Nearest.
///
/// [`finish_all`] keeps every candidate in this order, for Tab.
/// Ranks the gathered candidates within the aperture ([`ranked`]), adding the base-dependent
/// snaps, the deferred snaps and Nearest.
#[allow(clippy::too_many_arguments)]
fn finish(
mut cands: Vec<(u32, Vec2)>,
@@ -669,192 +615,71 @@ fn finish(
base: Option<Vec2>,
deferred: bool,
clip: Option<Bounds2>,
) -> Option<(SnapHit, Rank)> {
let from_base = base_snaps(near_prims, osmode, base, cursor, deferred);
cands.extend(from_base.iter().map(|f| (f.mode, f.point)));
) -> Vec<SnapHit> {
// Perpendicular / tangent from the base point.
if let Some(bp) = base {
for p in near_prims {
if osmode & mode::PER != 0 {
match p {
Prim::Seg(Segment::Line(l)) => cands.push((mode::PER, l.project(bp))),
// Both antipodes, filtered to the arc's sweep: a perpendicular in the gap is
// not offered, and the far side is still found.
Prim::Seg(Segment::Arc { arc, .. }) => {
let curve = SnapCurve::Arc { center: arc.center, radius: arc.radius, start: arc.start, end: arc.end };
cands.extend(curve.perpendiculars(bp, bp).into_iter().map(|q| (mode::PER, q)));
}
Prim::Circle(c) => cands.push((mode::PER, c.closest(bp))),
Prim::Infinite { base: b0, dir, .. } => cands.push((mode::PER, *b0 + *dir * (bp - *b0).dot(*dir))),
Prim::Ellipse(e) => cands.extend(curves::ellipse_perpendiculars(e, bp).into_iter().map(|q| (mode::PER, q))),
Prim::Spline(s) => cands.extend(curves::spline_perpendiculars(s, bp).into_iter().map(|q| (mode::PER, q))),
_ => {}
}
}
if osmode & mode::TAN != 0 {
let pts = match p {
// Only the tangent points that lie on the arc itself (not its circle).
Prim::Seg(Segment::Arc { arc, .. }) => Circle::new(arc.center, arc.radius)
.tangent_points(bp)
.into_iter()
.filter(|t| arc.contains_angle(arc.center.angle_to(*t)))
.collect(),
Prim::Circle(c) => c.tangent_points(bp),
Prim::Ellipse(e) => curves::ellipse_tangents(e, bp),
Prim::Spline(s) => curves::spline_tangents(s, bp),
_ => Vec::new(),
};
cands.extend(pts.into_iter().map(|t| (mode::TAN, t)));
}
}
}
let visible = |p: Vec2| p.is_finite() && clip.is_none_or(|c| c.contains(p));
// Prefer more specific modes when nearly equidistant.
let best = cands
.iter()
.filter(|(_, p)| visible(*p) && p.dist(cursor) <= aperture)
.map(|(m, p)| (snap_score(*m, *p, cursor, aperture), *m, *p))
.min_by(|a, b| a.0.total_cmp(&b.0));
if let Some((score, m, p)) = best {
return Some((SnapHit::plain(m, p), Rank { tier: 0, score }));
}
// A perpendicular or tangent on the object under the cursor, or the center found from its
// curve, only when no snap point is in the aperture: the Midpoint or Quadrant under the cursor
// wins over the center of the same curve, as in AutoCAD. Of the two, the object nearer the
// cursor; on a tie (the same curve), the perpendicular or tangent.
let on_object = from_base_on_objects(&from_base, near_prims, cursor, aperture, visible)
.into_iter()
.min_by(|a, b| a.1.score.total_cmp(&b.1.score).then(a.2.total_cmp(&b.2)))
.map(|(h, r, _)| (h, r));
let center = curve_centers(near_prims, cursor, aperture, osmode)
.into_iter()
.filter(|(_, c)| visible(*c))
.min_by(|a, b| a.0.total_cmp(&b.0))
.map(|(score, c)| (SnapHit::plain(mode::CEN, c), Rank { tier: 1, score }));
match (on_object, center) {
(Some(o), Some(c)) => return Some(if c.1.beats(&o.1) { c } else { o }),
(Some(h), None) | (None, Some(h)) => return Some(h),
(None, None) => {}
}
// With a base, perpendiculars are resolved from it above; only tangents are left to defer.
let deferrable = if base.is_some() { osmode & mode::TAN } else { osmode };
if deferred && let Some(h) = deferred_hit(near_prims, cursor, aperture, deferrable, clip) {
let score = h.point.dist(cursor);
return Some((h, Rank { tier: 2, score }));
let mut hits: Vec<SnapHit> =
cands.into_iter().filter(|(_, p)| visible(*p) && p.dist(cursor) <= aperture).map(|(m, p)| SnapHit::plain(m, p)).collect();
if base.is_none() && deferred {
hits.extend(deferred_hits(near_prims, cursor, aperture, osmode, clip));
}
if osmode & mode::NEA != 0 {
// The closest point of all nearby objects, whatever their drawing order.
let nb = near_prims.iter().filter_map(|p| nearest_point(p, cursor, aperture, &visible)).min_by(|a, b| a.0.total_cmp(&b.0));
if let Some((score, p)) = nb {
return Some((SnapHit::plain(mode::NEA, p), Rank { tier: 3, score }));
let mut nb: Option<(f64, Vec2)> = None;
let mut consider = |c: Vec2| {
let dd = c.dist(cursor);
if visible(c) && dd <= aperture && nb.is_none_or(|(bd, _)| dd < bd) {
nb = Some((dd, c));
}
};
for p in near_prims {
for s in prim_segments(p) {
consider(fix_circle(&s).closest(cursor));
}
if let Prim::Circle(c) = p {
consider(c.closest(cursor));
}
}
if let Some((_, p)) = nb {
hits.push(SnapHit { point: p, mode: mode::NEA, name: "Nearest", viewport: None, deferred: None });
}
}
None
}
/// [`finish`], keeping every candidate with its [`Rank`], in the order [`finish`] prefers them:
/// the snap points best first, then the perpendiculars and tangents on the objects under the
/// cursor and the centers found from their curves, then the deferred snaps, then the nearest point
/// of each object nearby.
#[allow(clippy::too_many_arguments)]
fn finish_all(
mut cands: Vec<(u32, Vec2)>,
near_prims: &[Prim],
cursor: Vec2,
aperture: f64,
osmode: u32,
base: Option<Vec2>,
deferred: bool,
clip: Option<Bounds2>,
) -> Vec<(SnapHit, Rank)> {
let from_base = base_snaps(near_prims, osmode, base, cursor, deferred);
cands.extend(from_base.iter().map(|f| (f.mode, f.point)));
let visible = |p: Vec2| p.is_finite() && clip.is_none_or(|c| c.contains(p));
let mut out: Vec<(SnapHit, Rank)> = cands
.iter()
.filter(|(_, p)| visible(*p) && p.dist(cursor) <= aperture)
.map(|(m, p)| (SnapHit::plain(*m, *p), Rank { tier: 0, score: snap_score(*m, *p, cursor, aperture) }))
.collect();
// Of several points on one object (a circle's two tangents), the one nearer the cursor first,
// as `finish` picks it; the sort below is stable.
let mut on_object = from_base_on_objects(&from_base, near_prims, cursor, aperture, visible);
on_object.sort_by(|a, b| a.1.score.total_cmp(&b.1.score).then(a.2.total_cmp(&b.2)));
out.extend(on_object.into_iter().map(|(h, r, _)| (h, r)));
out.extend(
curve_centers(near_prims, cursor, aperture, osmode)
.into_iter()
.filter(|(_, c)| visible(*c))
.map(|(score, c)| (SnapHit::plain(mode::CEN, c), Rank { tier: 1, score })),
);
let deferrable = if base.is_some() { osmode & mode::TAN } else { osmode };
if deferred {
let hits = deferred_hits(near_prims, cursor, aperture, deferrable, clip);
out.extend(hits.into_iter().map(|h| (h, Rank { tier: 2, score: h.point.dist(cursor) })));
}
if osmode & mode::NEA != 0 {
let near = near_prims.iter().filter_map(|p| nearest_point(p, cursor, aperture, &visible));
out.extend(near.map(|(score, p)| (SnapHit::plain(mode::NEA, p), Rank { tier: 3, score })));
}
out.sort_by(|a, b| a.1.cmp(&b.1));
out
}
/// The point of `p` closest to `cursor` among its visible points within `aperture`, with its
/// distance: each segment's closest point is checked before the closest is chosen, so a curve
/// whose closest point is clipped away (outside a viewport) still offers the visible one.
fn nearest_point(p: &Prim, cursor: Vec2, aperture: f64, visible: &impl Fn(Vec2) -> bool) -> Option<(f64, Vec2)> {
let mut nb: Option<(f64, Vec2)> = None;
let mut consider = |c: Vec2| {
let dd = c.dist(cursor);
if visible(c) && dd <= aperture && nb.is_none_or(|(bd, _)| dd < bd) {
nb = Some((dd, c));
}
};
for s in prim_segments(p) {
consider(fix_circle(&s).closest(cursor));
}
if let Prim::Circle(c) = p {
consider(c.closest(cursor));
}
nb
}
/// The perpendicular and tangent points from the base point `base` (none without one), each
/// with the index in `near_prims` of the object it lies on. At a `deferred` prompt the tangents to
/// circles and arcs are left out: the prompt resolves them itself (CIRCLE's radius, #1512).
fn base_snaps(near_prims: &[Prim], osmode: u32, base: Option<Vec2>, cursor: Vec2, deferred: bool) -> Vec<FromBase> {
let mut from_base: Vec<FromBase> = Vec::new();
let Some(bp) = base else { return from_base };
for (prim, p) in near_prims.iter().enumerate() {
let mut found = |mode: u32, points: Vec<Vec2>| from_base.extend(points.into_iter().map(|point| FromBase { mode, point, prim }));
if osmode & mode::PER != 0 {
let pts = match p {
Prim::Seg(Segment::Line(l)) => vec![l.project(bp)],
// Both antipodes, filtered to the arc's sweep: a perpendicular in the gap is
// not offered, and the far side is still found. From the centre, the point of
// the arc under the cursor.
Prim::Seg(Segment::Arc { arc, .. }) => {
SnapCurve::Arc { center: arc.center, radius: arc.radius, start: arc.start, end: arc.end }.perpendiculars(bp, cursor)
}
// Both antipodes too, so a pick on the far side of the circle snaps there
// rather than across it. From the centre every point is perpendicular: the
// one under the cursor.
Prim::Circle(c) => SnapCurve::Circle { center: c.center, radius: c.radius }.perpendiculars(bp, cursor),
Prim::Infinite { base: b0, dir, .. } => vec![*b0 + *dir * (bp - *b0).dot(*dir)],
Prim::Ellipse(e) => curves::ellipse_perpendiculars(e, bp),
Prim::Spline(s) => curves::spline_perpendiculars(s, bp),
_ => Vec::new(),
};
found(mode::PER, pts);
}
if osmode & mode::TAN != 0 {
let pts = match p {
// A deferred prompt resolves tangents to circles and arcs itself.
Prim::Seg(Segment::Arc { .. }) | Prim::Circle(_) if deferred => Vec::new(),
// Only the tangent points that lie on the arc itself (not its circle).
Prim::Seg(Segment::Arc { arc, .. }) => Circle::new(arc.center, arc.radius)
.tangent_points(bp)
.into_iter()
.filter(|t| arc.contains_angle(arc.center.angle_to(*t)))
.collect(),
Prim::Circle(c) => c.tangent_points(bp),
Prim::Ellipse(e) => curves::ellipse_tangents(e, bp),
Prim::Spline(s) => curves::spline_tangents(s, bp),
_ => Vec::new(),
};
found(mode::TAN, pts);
}
}
from_base
}
/// Center, as in AutoCAD: with the cursor over a circle, an arc (also a polyline's) or an
/// ellipse, the running Center snap finds its center however far away it is. Each center comes
/// with how far the curve is from `cursor` (its score); [`finish`] tries them only when no snap
/// point is in the aperture. Empty unless Center is among `osmode`.
fn curve_centers(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32) -> Vec<(f64, Vec2)> {
let mut out = Vec::new();
if osmode & mode::CEN == 0 {
return out;
}
// The work limit counts the curves only, so straight segments before them can't hide them.
let curves = prims.iter().filter_map(|p| match p {
Prim::Circle(c) => Some((c.center, c.closest(cursor))),
Prim::Seg(s @ Segment::Arc { arc, .. }) => Some((arc.center, fix_circle(s).closest(cursor))),
Prim::Ellipse(e) => Some((e.center, e.closest(cursor))),
_ => None,
});
for (center, on) in curves.take(2000) {
let d = on.dist(cursor);
if center.is_finite() && d.is_finite() && d <= aperture {
out.push((d, center));
}
}
out
ranked(hits, cursor, aperture)
}
/// Prefer more specific modes when nearly equidistant.
@@ -862,61 +687,6 @@ fn snap_score(mode: u32, point: Vec2, cursor: Vec2, aperture: f64) -> f64 {
point.dist(cursor) - if mode == mode::INT || mode == mode::END { aperture * 0.15 } else { 0.0 }
}
/// A perpendicular ([`mode::PER`]) or tangent ([`mode::TAN`]) point found from the base point,
/// with the index in `near_prims` of the object it lies on.
struct FromBase {
mode: u32,
point: Vec2,
prim: usize,
}
/// The perpendiculars and tangents from the base point on the objects that pass within
/// `aperture` of the cursor, wherever the foot or tangent point lies (#2800), each with its
/// [`Rank`] (tier 1, scored by the cursor's distance to the object) and its distance to the cursor.
///
/// These snaps name an object, not a spot on it: you can't know in advance where the foot of a
/// perpendicular will be, so, as in AutoCAD, hovering anywhere over the object finds it and the
/// point jumps there. [`finish`] asks for this only when no snap point lies within the aperture,
/// so an endpoint, midpoint or intersection under the cursor still wins.
///
/// [`finish`] takes the object nearest the cursor; of several points on it (an arc's two
/// antipodes, a circle's two tangents), the one nearest the cursor.
fn from_base_on_objects(
found: &[FromBase],
near_prims: &[Prim],
cursor: Vec2,
aperture: f64,
visible: impl Fn(Vec2) -> bool,
) -> Vec<(SnapHit, Rank, f64)> {
let mut out = Vec::new();
if found.is_empty() {
return out;
}
// `near_prims` holds every object whose box comes near the cursor, so the true distance is
// checked here. It is measured once per object, and only for objects with a point to offer:
// an ellipse or a spline is measured on its tessellation.
let mut reach: Vec<Option<f64>> = vec![None; near_prims.len()];
for f in found.iter().filter(|f| visible(f.point)) {
let Some(slot) = reach.get_mut(f.prim) else { continue };
let to_object = *slot.get_or_insert_with(|| near_prims.get(f.prim).map_or(f64::INFINITY, |p| distance_to_prim(p, cursor)));
// A NaN distance (from a degenerate object) never qualifies.
if to_object.is_nan() || to_object > aperture {
continue;
}
out.push((SnapHit::plain(f.mode, f.point), Rank { tier: 1, score: to_object }, f.point.dist(cursor)));
}
out
}
/// The distance from `cursor` to the nearest point of `p`, measured as Nearest measures it.
fn distance_to_prim(p: &Prim, cursor: Vec2) -> f64 {
// A ray runs one way from its start (an xline both ways, as its segment does).
if let Prim::Infinite { base, dir, ray: true } = p {
return (*base + *dir * (cursor - *base).dot(*dir).max(0.0)).dist(cursor);
}
prim_segments(p).iter().map(|s| fix_circle(s).closest(cursor).dist(cursor)).fold(f64::INFINITY, f64::min)
}
/// Upper bound on the block-reference objects one snap query looks at (hostile files).
const MAX_BLOCK_LEAVES: usize = 20_000;
@@ -1232,15 +1002,11 @@ fn xform_prim(p: &Prim, m: &Mat3) -> Prim {
}
}
/// Every deferred tangent and perpendicular within `aperture` of `cursor`, for Tab: one per curve
/// and mode, in drawing order (the caller ranks them), so Tab can go from the tangent to the
/// perpendicular on the same circle, and to the deferred snap of each curve nearby. A click takes
/// the nearest one ([`deferred_hit`]).
/// Every deferred tangent and perpendicular within `aperture` of `cursor`: one per curve and
/// mode, in drawing order (the caller ranks them), so Tab can cycle from the tangent to the
/// perpendicular on the same circle.
fn deferred_hits(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32, clip: Option<Bounds2>) -> Vec<SnapHit> {
let mut hits = Vec::new();
if osmode & (mode::TAN | mode::PER) == 0 {
return hits;
}
for p in prims {
let curve = match p {
Prim::Circle(c) => SnapCurve::Circle { center: c.center, radius: c.radius },
@@ -1273,45 +1039,6 @@ fn deferred_hits(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32, clip:
hits
}
/// The nearest deferred tangent/perpendicular within `aperture` of `cursor`.
fn deferred_hit(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32, clip: Option<Bounds2>) -> Option<SnapHit> {
let mut best: Option<(f64, SnapHit)> = None;
for p in prims {
let curve = match p {
Prim::Circle(c) => SnapCurve::Circle { center: c.center, radius: c.radius },
Prim::Seg(Segment::Arc { arc, .. }) => SnapCurve::Arc { center: arc.center, radius: arc.radius, start: arc.start, end: arc.end },
Prim::Seg(Segment::Line(l)) => SnapCurve::Line { a: l.a, b: l.b },
Prim::Infinite { base, dir, .. } => SnapCurve::Line { a: *base, b: *base + *dir },
_ => continue,
};
let (m, name, at) = match curve {
SnapCurve::Circle { center, radius } if osmode & mode::TAN != 0 => {
(mode::TAN, "Deferred Tangent", Circle::new(center, radius).closest(cursor))
}
SnapCurve::Circle { center, radius } if osmode & mode::PER != 0 => {
(mode::PER, "Deferred Perpendicular", Circle::new(center, radius).closest(cursor))
}
SnapCurve::Arc { center, radius, start, end } if osmode & mode::TAN != 0 => {
(mode::TAN, "Deferred Tangent", cadcraft_geom::Arc::new(center, radius, start, end).closest(cursor))
}
SnapCurve::Arc { center, radius, start, end } if osmode & mode::PER != 0 => {
(mode::PER, "Deferred Perpendicular", cadcraft_geom::Arc::new(center, radius, start, end).closest(cursor))
}
SnapCurve::Line { a, b } if osmode & mode::PER != 0 => {
// Pick on the drawn extent: a segment's own span, an xline/ray anywhere.
let l = cadcraft_geom::Line::new(a, b);
(mode::PER, "Deferred Perpendicular", if matches!(p, Prim::Seg(_)) { l.closest(cursor) } else { l.project(cursor) })
}
_ => continue,
};
let dd = at.dist(cursor);
if at.is_finite() && clip.is_none_or(|c| c.contains(at)) && dd <= aperture && best.is_none_or(|(bd, _)| dd < bd) {
best = Some((dd, SnapHit { point: at, mode: m, name, viewport: None, deferred: Some(Deferred { mode: m, curve, at }) }));
}
}
best.map(|(_, h)| h)
}
/// Solve a line whose ends may be deferred tangent/perpendicular snaps: returns its two
/// endpoints (in the order given), or `None` when there is no such line (a point inside the
/// circle it should be tangent to, concentric circles, non-parallel lines both perpendicular to
@@ -1717,22 +1444,21 @@ mod tests {
assert_eq!(h.name, "Intersection");
}
/// Tab cycling sees every snap within the aperture: snap points nearest first (Intersection
/// favoured), then Nearest on each object, and no snap twice; the first is what `osnap` picks.
/// On a circle with no base point, its quadrant, then the deferred tangent and the deferred
/// perpendicular at the same spot.
/// Tab cycling sees every snap within the aperture: specific snaps nearest first (Intersection
/// favoured), then deferred snaps, then Nearest, and no snap twice; the first is what `osnap`
/// picks.
#[test]
fn osnap_all_ranks_every_candidate() {
let d = drawing();
let (cursor, modes) = (Vec2::new(5.2, 0.2), mode::END | mode::MID | mode::INT | mode::NEA);
let all = osnap_all(&d, &Space::Model, cursor, 0.5, modes, None, false);
// Both lines' midpoints are the intersection point: one Midpoint. Each line has its Nearest.
assert_eq!(all.iter().map(|h| h.mode).collect::<Vec<_>>(), [mode::INT, mode::MID, mode::NEA, mode::NEA], "{all:?}");
assert_eq!(all.first().map(|h| h.point), osnap(&d, &Space::Model, cursor, 0.5, modes, None, false).map(|h| h.point));
let modes = mode::END | mode::MID | mode::INT | mode::NEA;
let all = osnap_all(&d, &Space::Model, Vec2::new(5.2, 0.2), 0.5, modes, None, false);
assert_eq!(all.iter().map(|h| h.mode).collect::<Vec<_>>(), [mode::INT, mode::MID, mode::NEA], "{all:?}");
assert_eq!(all[0].point, osnap(&d, &Space::Model, Vec2::new(5.2, 0.2), 0.5, modes, None, false).unwrap().point);
// On the circle: its quadrant, then the deferred tangent and perpendicular at the same spot.
let all = osnap_all(&d, &Space::Model, Vec2::new(22.1, 0.1), 0.5, mode::QUA | mode::TAN | mode::PER, None, true);
let kinds: Vec<(u32, bool)> = all.iter().map(|h| (h.mode, h.deferred.is_some())).collect();
assert_eq!(kinds, [(mode::QUA, false), (mode::TAN, true), (mode::PER, true)], "{all:?}");
assert!(osnap_all(&d, &Space::Model, Vec2::new(50.0, 50.0), 0.5, mode::QUA | mode::TAN | mode::PER, None, true).is_empty());
assert!(osnap_all(&d, &Space::Model, Vec2::new(50.0, 50.0), 0.5, modes, None, false).is_empty());
}
#[test]
@@ -1751,70 +1477,6 @@ mod tests {
assert!(h.point.near(Vec2::new(3.0, 0.0), 1e-9));
}
/// #2800: hovering anywhere over the line finds the perpendicular, though its foot (2,0) is
/// six units from the cursor; it used to snap only within the aperture of the foot.
#[test]
fn perpendicular_from_base_anywhere_on_the_line() {
let d = drawing();
let h = osnap(&d, &Space::Model, Vec2::new(8.0, 0.1), 0.5, mode::PER, Some(Vec2::new(2.0, 4.0)), false).unwrap();
assert!(h.point.near(Vec2::new(2.0, 0.0), 1e-9), "{h:?}");
assert_eq!(h.mode, mode::PER);
}
/// #2800: the tangent point is found from anywhere on the circle; of its two tangent points
/// from the base, the one nearer the cursor.
#[test]
fn tangent_from_base_anywhere_on_the_circle() {
let d = drawing();
// From (30,0), 10 from the centre (20,0) of the radius-2 circle: the tangent points are
// at cos = 2/10 from the line to the base, (20.4, ±1.9596).
let upper = Vec2::new(20.4, 2.0 * (1.0f64 - 0.04).sqrt());
let on_circle = Vec2::new(20.0 - 2.0 * std::f64::consts::FRAC_1_SQRT_2, 2.0 * std::f64::consts::FRAC_1_SQRT_2);
let h = osnap(&d, &Space::Model, on_circle, 0.5, mode::TAN, Some(Vec2::new(30.0, 0.0)), false).unwrap();
assert!(h.point.near(upper, 1e-9), "{h:?}");
let mirrored = Vec2::new(on_circle.x, -on_circle.y);
let h = osnap(&d, &Space::Model, mirrored, 0.5, mode::TAN, Some(Vec2::new(30.0, 0.0)), false).unwrap();
assert!(h.point.near(Vec2::new(upper.x, -upper.y), 1e-9), "{h:?}");
}
/// A circle offers both perpendicular points from the base, so a pick on its far side snaps
/// there, not to the near side across the circle (CodeRabbit on #2825).
#[test]
fn perpendicular_from_base_on_a_circle_takes_the_side_under_the_cursor() {
let d = drawing();
// The circle at (20,0), radius 2, seen from (30,0): perpendicular at (22,0) and (18,0).
let base = Some(Vec2::new(30.0, 0.0));
let far = osnap(&d, &Space::Model, Vec2::new(18.1, 0.1), 0.5, mode::PER, base, false).unwrap();
assert!(far.point.near(Vec2::new(18.0, 0.0), 1e-9), "{far:?}");
// Away from both points, at (19, √3) on the circle: 2 from (18,0) and √12 from (22,0).
let top = osnap(&d, &Space::Model, Vec2::new(19.0, 3.0f64.sqrt()), 0.5, mode::PER, base, false).unwrap();
assert!(top.point.near(Vec2::new(18.0, 0.0), 1e-9), "{top:?}");
let near = osnap(&d, &Space::Model, Vec2::new(21.9, 0.1), 0.5, mode::PER, base, false).unwrap();
assert!(near.point.near(Vec2::new(22.0, 0.0), 1e-9), "{near:?}");
}
/// With several objects under the aperture, the one nearest the cursor gives the
/// perpendicular, even when another object's foot is nearer.
#[test]
fn perpendicular_from_base_takes_the_object_nearest_the_cursor() {
let d = drawing();
// 0.4 above the horizontal line and 0.2 right of the vertical one: the vertical line wins,
// with its foot (5,4) farther from the cursor than the horizontal line's (2,0).
let h = osnap(&d, &Space::Model, Vec2::new(5.2, 0.4), 0.5, mode::PER, Some(Vec2::new(2.0, 4.0)), false).unwrap();
assert!(h.point.near(Vec2::new(5.0, 4.0), 1e-9), "{h:?}");
}
/// A snap point under the cursor still beats a perpendicular whose foot is away from it, and
/// an object outside the aperture gives none, though its box is near.
#[test]
fn perpendicular_from_base_yields_to_points_under_the_cursor() {
let d = drawing();
let base = Some(Vec2::new(2.0, 4.0));
let h = osnap(&d, &Space::Model, Vec2::new(9.9, 0.05), 0.5, mode::END | mode::PER, base, false).unwrap();
assert_eq!((h.point, h.mode), (Vec2::new(10.0, 0.0), mode::END));
assert!(osnap(&d, &Space::Model, Vec2::new(8.0, 0.7), 0.5, mode::PER, base, false).is_none());
}
#[test]
fn ortho_and_polar() {
assert_eq!(ortho(Vec2::ZERO, Vec2::new(5.0, 1.0)), Vec2::new(5.0, 0.0));
@@ -1857,14 +1519,9 @@ mod tests {
let df = h.deferred.unwrap();
assert_eq!(df.curve, SnapCurve::Circle { center: Vec2::new(20.0, 0.0), radius: 2.0 });
assert_eq!(h.input(), crate::Input::Deferred(df));
// With a base it is an ordinary tangent, unless the prompt resolves it (CIRCLE's radius).
let t = osnap(&d, &Space::Model, Vec2::new(19.9, 1.9), 1.0, mode::TAN, Some(Vec2::new(10.0, 0.0)), false).unwrap();
// With a base it is an ordinary tangent.
let t = osnap(&d, &Space::Model, Vec2::new(19.9, 1.9), 1.0, mode::TAN, Some(Vec2::new(10.0, 0.0)), true).unwrap();
assert!(t.deferred.is_none() && t.name == "Tangent");
let t = osnap(&d, &Space::Model, at, 0.5, mode::TAN, Some(Vec2::new(10.0, 0.0)), true).unwrap();
assert_eq!(t.name, "Deferred Tangent");
// A perpendicular from the base is still resolved from it.
let p = osnap(&d, &Space::Model, Vec2::new(2.0, 0.2), 0.5, mode::PER, Some(Vec2::new(2.0, 5.0)), true).unwrap();
assert!(p.deferred.is_none() && p.point.near(Vec2::new(2.0, 0.0), 1e-9));
// A specific snap still wins over a deferred one.
let q = osnap(&d, &Space::Model, at, 0.5, mode::TAN | mode::QUA, None, true).unwrap();
assert_eq!(q.mode, mode::QUA);
+8 -47
View File
@@ -482,38 +482,13 @@ impl Tracker {
cfg: &TrackConfig,
base: Option<Vec2>,
) -> Option<Track> {
self.track_with_frozen(d, space, cursor, aperture, tol, cfg, base, &[])
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn track_with_frozen(
&mut self,
d: &Drawing,
space: &Space,
cursor: Vec2,
aperture: f64,
tol: f64,
cfg: &TrackConfig,
base: Option<Vec2>,
frozen: &[String],
) -> Option<Track> {
let t = self.find(d, space, cursor, aperture, tol, cfg, base, frozen);
let t = self.find(d, space, cursor, aperture, tol, cfg, base);
self.last = t.clone();
t
}
#[allow(clippy::too_many_arguments)]
fn find(
&self,
d: &Drawing,
space: &Space,
cursor: Vec2,
aperture: f64,
tol: f64,
cfg: &TrackConfig,
base: Option<Vec2>,
frozen: &[String],
) -> Option<Track> {
fn find(&self, d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, tol: f64, cfg: &TrackConfig, base: Option<Vec2>) -> Option<Track> {
if !(cursor.is_finite() && aperture.is_finite() && tol.is_finite() && aperture > 0.0 && tol > 0.0) {
return None;
}
@@ -563,7 +538,7 @@ impl Tracker {
// 2. A path crossing an object.
if cfg.running(mode::INT | mode::APP) {
let ix = crate::spatial::index(d, space);
let prims = super::gather_in(d, space, &ix, cursor, aperture, mode::NEA, frozen, None).map(|(_, p)| p).unwrap_or_default();
let prims = super::gather(d, space, &ix, cursor, aperture, mode::NEA).map(|(_, p)| p).unwrap_or_default();
for prim in prims.iter().take(200) {
let extend = cfg.running(mode::APP) && super::extendable(prim);
for seg in super::prim_segments(prim) {
@@ -613,26 +588,12 @@ pub fn candidate(
aperture: f64,
cfg: &TrackConfig,
base: Option<Vec2>,
) -> Option<Acquired> {
candidate_with_frozen(d, space, cursor, hit, aperture, cfg, base, &[])
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn candidate_with_frozen(
d: &Drawing,
space: &Space,
cursor: Vec2,
hit: Option<&SnapHit>,
aperture: f64,
cfg: &TrackConfig,
base: Option<Vec2>,
frozen: &[String],
) -> Option<Acquired> {
if !can_acquire(cursor, aperture, cfg) {
return None;
}
let ix = crate::spatial::index(d, space);
let prims = super::gather_in(d, space, &ix, cursor, aperture, mode::NEA, frozen, None).map(|(_, p)| p).unwrap_or_default();
let prims = super::gather(d, space, &ix, cursor, aperture, mode::NEA).map(|(_, p)| p).unwrap_or_default();
candidate_from_prims(cursor, hit, aperture, cfg, base, &prims)
}
@@ -828,7 +789,7 @@ impl crate::Session {
s.orthomode ^= q.shift;
let angbase = self.angle_settings().angbase;
let Ok(st) = self.state() else { return CursorSnap { point: raw, ..Default::default() } };
let (doc, space, frozen) = (st.doc.clone(), st.edit_space(), st.viewport_frozen().to_vec());
let (doc, space) = (st.doc.clone(), st.edit_space());
if !raw.is_finite() {
return CursorSnap { point: raw, ..Default::default() };
}
@@ -837,10 +798,10 @@ impl crate::Session {
let cfg = TrackConfig::relative_to(&s, angbase, last);
let osmode = s.osmode | if s.osnaphatch { mode::HATCH } else { 0 };
let ix = crate::spatial::index(&doc, &space);
let (hit, near_prims) = super::osnap_with_neighborhood(&doc, &space, &ix, raw, q.aperture, osmode, q.base, q.deferred, &frozen);
let (hit, near_prims) = super::osnap_with_neighborhood(&doc, &space, &ix, raw, q.aperture, osmode, q.base, q.deferred);
let cand = match (osmode & mode::HATCH, near_prims.as_deref()) {
(0, Some(prims)) => candidate_with_prims(raw, hit.as_ref(), q.aperture, &cfg, q.base, prims),
_ => candidate_with_frozen(&doc, &space, raw, hit.as_ref(), q.aperture, &cfg, q.base, &frozen),
_ => candidate(&doc, &space, raw, hit.as_ref(), q.aperture, &cfg, q.base),
};
let wait = self.tracking.hover(cand, q.now, cfg.shift_acquire, q.shift);
if let Some(h) = hit {
@@ -855,7 +816,7 @@ impl crate::Session {
let (origin, angle) = super::grid_frame_in(&doc, &space);
p = super::grid_snap(p, doc.header.snap_unit(), origin, angle);
}
if let Some(mut t) = self.tracking.track_with_frozen(&doc, &space, p, q.aperture, q.tol, &cfg, q.base, &frozen) {
if let Some(mut t) = self.tracking.track(&doc, &space, p, q.aperture, q.tol, &cfg, q.base) {
// PolarSnap (SNAPTYPE 1): steps of POLARDIST, or of the snap X spacing when it is 0.
let step = if s.polardist > 0.0 { s.polardist } else { s.snapunit.x };
if s.snapmode
-2
View File
@@ -66,8 +66,6 @@ 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)),
-91
View File
@@ -532,97 +532,6 @@ fn scale_reference_typed_and_picked() {
assert!(end(&s).near(Vec2::new(50.0, 0.0), 1e-9));
}
#[test]
fn scale_reference_points_and_copy() {
fn line_ends(s: &Session) -> Vec<Vec2> {
s.doc()
.unwrap()
.model
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Line(l) => Some(l.b.xy()),
_ => None,
})
.collect()
}
let mut s = Session::new();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
// Reference 10 via two points, then Points option with two points of length 30 -> (30, 0).
for t in ["scale", "all", "", "0,0", "r", "0,0", "10,0"] {
s.cmdline(t).unwrap();
}
let p = s.current_prompt().unwrap();
assert_eq!(p.message, "Specify new length");
assert!(p.keywords.contains(&"Points".to_string()));
assert!(p.keywords.contains(&"Copy".to_string()));
s.cmdline("p").unwrap();
assert_eq!(s.current_prompt().unwrap().message, "Specify first point");
s.cmdline("5,5").unwrap();
assert_eq!(s.current_prompt().unwrap().message, "Specify second point");
s.cmdline("5,35").unwrap();
assert!(s.running.is_none());
assert!(line_ends(&s)[0].near(Vec2::new(30.0, 0.0), 1e-9));
// Coinciding Points are rejected without leaving the second-point prompt; a valid point completes.
for t in ["scale", "all", "", "0,0", "r", "30", "p", "5,5", "5,5"] {
s.cmdline(t).unwrap();
}
assert!(s.running.is_some());
assert_eq!(s.current_prompt().unwrap().message, "Specify second point");
s.cmdline("5,25").unwrap();
assert!(s.running.is_none());
assert!(line_ends(&s)[0].near(Vec2::new(20.0, 0.0), 1e-9));
// Copy entered inside Reference mode before reference length keeps the original and adds a scaled copy.
for t in ["scale", "all", "", "0,0", "r", "c", "20", "40"] {
s.cmdline(t).unwrap();
}
assert!(s.running.is_none());
let ends = line_ends(&s);
assert_eq!(ends.len(), 2);
assert!(ends.iter().any(|p| p.near(Vec2::new(20.0, 0.0), 1e-9)));
assert!(ends.iter().any(|p| p.near(Vec2::new(40.0, 0.0), 1e-9)));
// Copy entered at "Specify new length" combined with Points scales a copy.
for t in ["scale", "l", "", "0,0", "r", "40", "c", "p", "0,0", "10,0"] {
s.cmdline(t).unwrap();
}
assert!(s.running.is_none());
let ends = line_ends(&s);
assert_eq!(ends.len(), 3);
assert!(ends.iter().any(|p| p.near(Vec2::new(10.0, 0.0), 1e-9)));
}
#[test]
fn hot_grip_scale_scales_heights_and_thickness() {
let mut s = Session::new();
let r = s.execute("text", &json!({"at": [10, 0], "height": 2.0, "text": "H"})).unwrap();
let h = cadcraft_doc::Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
s.doc_mut()
.unwrap()
.modify_entity(h, |e| {
e.common.thickness = 3.0;
if let EntityKind::Text(t) = &mut e.kind {
t.insert.z = 5.0;
}
})
.unwrap();
s.set_selection(vec![h]);
s.start_grip_edit(&[(h, 0)]).unwrap();
// STRETCH -> MOVE -> ROTATE -> SCALE
for _ in 0..3 {
s.input(Input::Enter).unwrap();
}
assert!(s.current_prompt().unwrap().message.contains("** SCALE **"));
s.cmdline("2").unwrap();
assert!(s.running.is_none());
let e = s.doc().unwrap().entity(h).unwrap();
assert_eq!(e.common.thickness, 6.0);
let EntityKind::Text(t) = &e.kind else { panic!("expected text") };
assert_eq!(t.height, 4.0);
assert_eq!(t.insert.z, 10.0);
}
#[test]
fn layers_and_properties() {
let mut s = Session::new();
-107
View File
@@ -1,107 +0,0 @@
//! 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);
}
@@ -1,33 +0,0 @@
//! #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);
}
-4
View File
@@ -98,7 +98,6 @@ 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;
@@ -126,7 +125,6 @@ mod offset_ellipse_side;
mod offset_move;
mod oops_command;
mod options_profile;
mod osnap_opened_drawings;
mod overkill;
mod parallel_display_list;
mod pedit_heights;
@@ -174,12 +172,10 @@ mod setvar_coverage;
mod shapes;
mod snap_annotations;
mod snap_blocks;
mod snap_center_on_curve;
mod snap_curves;
mod snap_intersections_aperture;
mod snap_nearest;
mod snap_overrides;
mod snap_tab_cycling;
mod snap_tracking;
mod snaps_more;
mod solid_command;
@@ -1,8 +1,7 @@
//! DIST snaps to the model geometry displayed in paper-space viewports (#516).
use cadcraft_engine::doc::{Block, Circle, Common, Drawing, Ellipse, Entity, EntityKind, Handle, Insert, Line, Space, Viewport};
use cadcraft_engine::doc::{Block, Circle, Common, Drawing, Entity, EntityKind, Handle, Insert, Line, Space, Viewport};
use cadcraft_engine::geom::{Vec2, Vec3};
use cadcraft_engine::pointmod::snap_candidates;
use cadcraft_engine::snap::{SnapCurve, SnapHit, mode, osnap, osnap_all};
use cadcraft_engine::{Input, Session};
use serde_json::json;
@@ -279,22 +278,22 @@ fn clipped_endpoints_do_not_hide_a_visible_candidate() {
assert!(osnap(&d, &paper, Vec2::new(110.11, 51.0), 0.2, mode::END, None, false).is_none());
}
/// Across spaces a click takes the viewport's Endpoint over a paper-space Nearest that scores
/// closer, as within one space a snap point beats Nearest. Tab starts at the click's snap and
/// still reaches the paper-space Nearest.
/// Across spaces a click keeps the snap it had before Tab cycling: a viewport's best snap
/// replaces paper space's only when it scores closer. Tab still reaches the other one.
#[test]
fn a_viewport_endpoint_beats_a_closer_paper_space_nearest() {
fn a_closer_paper_space_nearest_keeps_the_click_over_a_viewport_endpoint() {
let (mut d, paper) = drawing();
// A paper-space line 0.3 left of the model endpoint (0, 0), which the viewport shows at (95, 50).
d.add(&paper, Common::default(), EntityKind::Line(Line { a: Vec3::new(94.7, 48.0, 0.0), b: Vec3::new(94.7, 52.0, 0.0) })).unwrap();
let (cursor, modes) = (Vec2::new(94.8, 50.0), mode::END | mode::NEA);
let hit = osnap(&d, &paper, cursor, 0.5, modes, None, false).unwrap();
assert!(hit.mode == mode::END && hit.viewport.is_some() && hit.point.near(Vec2::new(95.0, 50.0), 1e-9), "{hit:?}");
let all = snap_candidates(&d, &paper, cursor, 0.5, modes, None, false);
assert_eq!((hit.mode, hit.viewport), (mode::NEA, None), "{hit:?}");
assert!(hit.point.near(Vec2::new(94.7, 50.0), 1e-9), "{hit:?}");
let all = osnap_all(&d, &paper, cursor, 0.5, modes, None, false);
assert_eq!(all.first(), Some(&hit), "Tab starts at the click's snap");
assert!(
all.iter().any(|h| h.mode == mode::NEA && h.viewport.is_none() && h.point.near(Vec2::new(94.7, 50.0), 1e-9)),
"Tab reaches the paper-space Nearest: {all:?}"
all.iter().any(|h| h.mode == mode::END && h.viewport.is_some() && h.point.near(Vec2::new(95.0, 50.0), 1e-9)),
"Tab reaches the viewport's endpoint: {all:?}"
);
}
@@ -430,50 +429,3 @@ fn malformed_and_paper_space_viewports_are_not_snap_sources() {
assert!(osnap(&d, &paper, Vec2::new(95.1, 50.1), 0.5, mode::END, None, false).is_none());
}
}
/// Nearest on a curve that leaves the viewport: the curve's closest point to the cursor is outside
/// the viewport, another point of it within the aperture is inside, and Nearest snaps there.
#[test]
fn nearest_takes_the_visible_part_of_a_curve_crossing_the_viewport_edge() {
let (mut d, paper) = drawing();
// The viewport shows model y up to 20. A tall ellipse peaks at (15, 20.1), just outside.
let ellipse = Ellipse { center: Vec3::new(15.0, 0.0, 0.0), major: Vec3::new(0.0, 20.1, 0.0), ratio: 0.1, start: 0.0, end: std::f64::consts::TAU };
d.add(&Space::Model, Common::default(), EntityKind::Ellipse(ellipse)).unwrap();
// The viewport's border is on a layer that is off, so it offers no Nearest of its own.
d.layers.push(cadcraft_engine::doc::Layer { name: "Border".into(), on: false, ..Default::default() });
let vp = viewport(&d, &paper);
d.modify_entity(vp, |e| e.common.layer = "Border".into()).unwrap();
// Model (15, 19.99): 0.11 from the peak, about 0.2 from where the ellipse comes back inside.
let cursor = Vec2::new(102.5, 59.995);
let hit = osnap(&d, &paper, cursor, 0.5, mode::NEA, None, false).expect("a visible nearest point");
let model = hit.viewport.expect("seen through the viewport").point;
assert!(model.y <= 20.0 + 1e-9 && model.dist(Vec2::new(15.0, 19.99)) <= 1.0, "{hit:?}");
}
#[test]
fn a_twisted_viewport_offers_the_visible_perpendicular_when_a_nearer_one_is_off_the_sheet() {
// A viewport twisted 45°, 20 square at 0,0 on the sheet, scale 1. Through it, a line along
// y = 0 under the cursor and one along x = 9.3 (sheet coordinates). From the base 12,3 the
// foot on the first, 12,0, is inside the turned model box but off the viewport; the foot on
// the second, 9.3,3, is on it.
let mut d = Drawing::new_imperial();
let paper = Space::Paper("Layout1".into());
let vp = Viewport {
center: Vec3::ZERO,
width: 20.0,
height: 20.0,
view_center: Vec2::ZERO,
view_height: 20.0,
id: 2,
twist: std::f64::consts::FRAC_PI_4,
..Viewport::default()
};
for (a, b) in [(Vec2::new(-9.0, 0.0), Vec2::new(30.0, 0.0)), (Vec2::new(9.3, -9.0), Vec2::new(9.3, 9.0))] {
let (a, b) = (vp.paper_to_model(a), vp.paper_to_model(b));
d.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: a.to3(0.0), b: b.to3(0.0) })).unwrap();
}
d.add(&paper, Common::default(), EntityKind::Viewport(vp)).unwrap();
let hit = osnap(&d, &paper, Vec2::new(9.0, 0.0), 0.5, mode::PER, Some(Vec2::new(12.0, 3.0)), false).expect("the visible foot");
assert_eq!(hit.mode, mode::PER);
assert!(hit.point.near(Vec2::new(9.3, 3.0), 1e-9), "{hit:?}");
}
+1 -139
View File
@@ -567,144 +567,6 @@ 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();
@@ -730,7 +592,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 segment parallel to a line, too big.
// Segments too far apart, the same segment, a circle, a middle segment with 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 }),
@@ -1,116 +0,0 @@
//! Running object snaps in a fresh drawing and in drawings opened from DXF and DWG files, with
//! AutoCAD's default modes (OSMODE 4133: Endpoint, Center, Intersection, Extension).
//!
//! Moving onto a circle, an arc or a polyline arc finds its Center. OSMODE is a profile setting,
//! as in AutoCAD (saved in the registry there, not the drawing): a file's `$OSMODE` header
//! variable, 0 included, never changes the running snaps.
use cadcraft_engine::Session;
use cadcraft_engine::doc::Drawing;
use cadcraft_engine::geom::Vec2;
use cadcraft_engine::snap::{mode, tracking::CursorQuery};
use serde_json::json;
/// AutoCAD's default running snaps.
const DEFAULT: u32 = 4133;
fn polar(c: Vec2, r: f64, deg: f64) -> Vec2 {
let a = deg.to_radians();
c + Vec2::new(r * a.cos(), r * a.sin())
}
/// A line crossed by another, a circle, an arc and a polyline with a straight and an arc segment.
fn draw(s: &mut Session) {
s.execute("line", &json!({ "points": [[0, 0], [20, 0]] })).unwrap();
s.execute("line", &json!({ "points": [[5, -5], [5, 5]] })).unwrap();
s.execute("circle", &json!({ "center": [50, 0], "radius": 5 })).unwrap();
s.execute("arc", &json!({ "center": [80, 0], "radius": 5, "start": 0, "end": 180 })).unwrap();
// 100,0 to 110,0 straight, then a half circle (bulge 1) to 130,0 round 120,0, below the axis.
s.execute("pline", &json!({ "vertices": [[100, 0], {"p": [110, 0], "bulge": 1.0}, [130, 0]] })).unwrap();
}
fn drawing() -> Drawing {
let mut s = Session::new();
draw(&mut s);
s.doc().unwrap().clone()
}
/// Where a click at `cursor` lands while LINE asks for its first point (the drawing area's path).
fn snap(s: &mut Session, cursor: Vec2) -> Option<(Vec2, u32)> {
if s.running.is_none() {
s.start("line").unwrap();
}
let q = CursorQuery { base: None, deferred: true, corner: false, aperture: 1.0, tol: 0.5, now: 0.0, shift: false };
let r = s.snap_cursor(cursor, &q);
r.snap.map(|h| (r.point, h.mode))
}
fn assert_snaps(s: &mut Session, what: &str) {
assert_eq!(s.settings.osmode, DEFAULT, "{what}: the running snaps are the profile's");
let cases = [
("the line's end", Vec2::new(20.2, 0.1), Vec2::new(20.0, 0.0), &[mode::END][..]),
("the lines' crossing", Vec2::new(5.2, 0.15), Vec2::new(5.0, 0.0), &[mode::INT][..]),
("the circle", polar(Vec2::new(50.0, 0.0), 5.3, 45.0), Vec2::new(50.0, 0.0), &[mode::CEN][..]),
("the arc", polar(Vec2::new(80.0, 0.0), 5.2, 90.0), Vec2::new(80.0, 0.0), &[mode::CEN][..]),
("the arc's end", Vec2::new(85.2, 0.1), Vec2::new(85.0, 0.0), &[mode::END][..]),
("the polyline's vertex", Vec2::new(110.2, 0.1), Vec2::new(110.0, 0.0), &[mode::END][..]),
("the polyline's arc", polar(Vec2::new(120.0, 0.0), 10.2, 270.0), Vec2::new(120.0, 0.0), &[mode::CEN][..]),
];
for (name, cursor, want, modes) in cases {
let (p, m) = snap(s, cursor).unwrap_or_else(|| panic!("{what}: no snap on {name}"));
assert!(modes.contains(&m), "{what}, {name}: mode {m}");
assert!(p.near(want, 1e-6), "{what}, {name}: {p:?}");
}
// Away from everything: nothing.
assert_eq!(snap(s, Vec2::new(35.0, 20.0)), None, "{what}");
// F3 off: nothing; on again: back.
s.execute("osnap", &json!({})).unwrap();
assert_eq!(snap(s, Vec2::new(20.2, 0.1)), None, "{what}: F3 off");
s.execute("osnap", &json!({})).unwrap();
assert_eq!(snap(s, Vec2::new(20.2, 0.1)).map(|h| h.1), Some(mode::END), "{what}: F3 on");
}
#[test]
fn default_snaps_work_in_a_fresh_drawing() {
let mut s = Session::new();
draw(&mut s);
assert_snaps(&mut s, "fresh drawing");
}
/// `text` with `$OSMODE` set to `value` at the top of its header.
fn with_osmode(text: &str, value: u32) -> String {
let at = text.find("HEADER").expect("a header section") + "HEADER".len();
let eol = if text.contains("\r\n") { "\r\n" } else { "\n" };
let (head, tail) = text.split_at(at);
format!("{head}{eol} 9{eol}$OSMODE{eol} 70{eol}{value}{tail}")
}
#[test]
fn a_dxf_with_osmode_0_keeps_the_running_snaps() {
let clean = String::from_utf8(cadcraft_io::write(&drawing(), "snaps.dxf").unwrap()).unwrap();
let text = with_osmode(&clean, 0);
let d = cadcraft_io::read(text.as_bytes(), "snaps.dxf").unwrap();
let mut s = Session::new();
// OSMODE is the profile's: the user's own choice survives opening the file.
s.execute("setvar", &json!({ "name": "OSMODE", "value": DEFAULT })).unwrap();
s.open_drawing(d, "snaps.dxf", None);
assert_snaps(&mut s, "DXF with $OSMODE 0");
// Nor does a file change a profile without Center.
let mut s = Session::new();
s.execute("setvar", &json!({ "name": "OSMODE", "value": mode::END })).unwrap();
let text = with_osmode(&clean, DEFAULT);
assert_eq!(text.matches("$OSMODE").count(), 1, "one $OSMODE in the file");
s.open_drawing(cadcraft_io::read(text.as_bytes(), "x.dxf").unwrap(), "x.dxf", None);
assert_eq!(s.settings.osmode, mode::END);
}
#[test]
fn default_snaps_work_in_a_drawing_opened_from_dwg() {
// The drawing is the test's own, so it is converted in this process.
cadcraft_io::dwg_worker::allow_in_process();
let bytes = cadcraft_io::write(&drawing(), "snaps.dwg").unwrap();
let d = cadcraft_io::read(&bytes, "snaps.dwg").unwrap();
let mut s = Session::new();
s.open_drawing(d, "snaps.dwg", None);
assert_snaps(&mut s, "DWG");
}
@@ -19,7 +19,6 @@ 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)),
@@ -78,7 +77,6 @@ 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)),
@@ -1,202 +0,0 @@
//! Center snaps from the curve, as in AutoCAD: with the cursor over a circle, an arc, an
//! ellipse or a polyline arc (also inside a block reference) the running Center snap finds its
//! center, however far away it is. Before, the center was only found with the cursor on the
//! center itself, so moving onto a circle with the default running snaps (END, CEN, INT, EXT)
//! showed nothing.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{Common, EntityKind, Insert, Space};
use cadcraft_engine::geom::{Vec2, Vec3};
use cadcraft_engine::pointmod::snap_candidates;
use cadcraft_engine::snap::{self, mode};
use serde_json::json;
/// AutoCAD's default running snaps (OSMODE 4133).
const DEFAULT: u32 = 4133;
fn snap_at(s: &Session, cursor: Vec2, aperture: f64, osmode: u32) -> Option<(Vec2, u32)> {
snap::osnap(s.doc().unwrap(), &Space::Model, cursor, aperture, osmode, None, false).map(|h| (h.point, h.mode))
}
fn polar(c: Vec2, r: f64, deg: f64) -> Vec2 {
let a = deg.to_radians();
c + Vec2::new(r * a.cos(), r * a.sin())
}
#[test]
fn cursor_on_a_circle_snaps_to_its_center() {
let mut s = Session::new();
s.execute("circle", &json!({ "center": [100, 50], "radius": 20 })).unwrap();
let c = Vec2::new(100.0, 50.0);
for deg in [10.0, 45.0, 130.0, 250.0, 300.0] {
// A hair off the circle, well inside the aperture; the center is 20 units away.
let cursor = polar(c, 20.3, deg);
let (p, m) = snap_at(&s, cursor, 1.0, DEFAULT).unwrap_or_else(|| panic!("no snap on the circle at {deg}°"));
assert_eq!(m, mode::CEN, "at {deg}°");
assert!(p.near(c, 1e-9), "at {deg}°: {p:?}");
}
// Away from the circle (outside the aperture) there is nothing.
assert_eq!(snap_at(&s, polar(c, 23.0, 45.0), 1.0, DEFAULT), None);
// Center off: no center.
assert_eq!(snap_at(&s, polar(c, 20.3, 45.0), 1.0, mode::END), None);
// On the center itself, as before.
assert_eq!(snap_at(&s, c + Vec2::new(0.2, 0.1), 1.0, DEFAULT).map(|h| h.1), Some(mode::CEN));
}
#[test]
fn arcs_ellipses_and_polyline_arcs_snap_to_their_centers() {
let mut s = Session::new();
s.execute("arc", &json!({ "center": [0, 0], "radius": 10, "start": 0, "end": 90 })).unwrap();
s.execute("ellipse", &json!({ "center": [50, 0], "major": [8, 0], "ratio": 0.5 })).unwrap();
// A polyline with a half-circle bulge from (100,0) to (120,0): center (110,0), radius 10.
s.execute("pline", &json!({ "vertices": [{"p": [100, 0], "bulge": 1.0}, [120, 0]] })).unwrap();
let arc = snap_at(&s, polar(Vec2::ZERO, 10.2, 45.0), 1.0, DEFAULT).unwrap();
assert_eq!(arc.1, mode::CEN);
assert!(arc.0.near(Vec2::ZERO, 1e-9));
// The arc runs 0°-90°: on its circle at 200° (not on the arc) there is no center.
assert_eq!(snap_at(&s, polar(Vec2::ZERO, 10.2, 200.0), 1.0, DEFAULT), None);
let el = snap_at(&s, Vec2::new(50.0, 4.2), 1.0, DEFAULT).unwrap();
assert_eq!(el.1, mode::CEN);
assert!(el.0.near(Vec2::new(50.0, 0.0), 1e-9));
let pl = snap_at(&s, polar(Vec2::new(110.0, 0.0), 10.2, 270.0), 1.0, DEFAULT).unwrap();
assert_eq!(pl.1, mode::CEN, "the bulge's arc");
assert!(pl.0.near(Vec2::new(110.0, 0.0), 1e-9), "{:?}", pl.0);
}
#[test]
fn a_nearer_endpoint_or_intersection_still_wins() {
let mut s = Session::new();
s.execute("circle", &json!({ "center": [0, 0], "radius": 10 })).unwrap();
s.execute("line", &json!({ "points": [[10, 0], [30, 0]] })).unwrap();
// At the line's end on the circle: Endpoint/Intersection, not the far center.
let (p, m) = snap_at(&s, Vec2::new(10.2, 0.1), 1.0, DEFAULT).unwrap();
assert!(m == mode::END || m == mode::INT, "{m}");
assert!(p.near(Vec2::new(10.0, 0.0), 1e-9));
}
#[test]
fn circles_inside_block_references_snap_to_their_centers() {
let mut s = Session::new();
let c = s.execute("circle", &json!({ "center": [5, 0], "radius": 2 })).unwrap()["handle"].as_str().unwrap().to_string();
s.execute("block", &json!({ "name": "H", "base": [0, 0], "handles": [c], "keep": "delete" })).unwrap();
let kind = EntityKind::Insert(Insert {
block: "H".into(),
insert: Vec3::new(100.0, 100.0, 0.0),
scale: Vec3::new(3.0, 3.0, 1.0),
rotation: 0.0,
attribs: Vec::new(),
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
});
s.doc_mut().unwrap().add(&Space::Model, Common::default(), kind).unwrap();
// The circle lands at (115,100) with radius 6.
let (p, m) = snap_at(&s, polar(Vec2::new(115.0, 100.0), 6.2, 60.0), 1.0, DEFAULT).unwrap();
assert_eq!(m, mode::CEN);
assert!(p.near(Vec2::new(115.0, 100.0), 1e-9), "{p:?}");
}
#[test]
fn tab_cycling_offers_the_center_from_the_curve() {
let mut s = Session::new();
s.execute("circle", &json!({ "center": [0, 0], "radius": 10 })).unwrap();
let all = snap_candidates(s.doc().unwrap(), &Space::Model, polar(Vec2::ZERO, 10.2, 30.0), 1.0, DEFAULT, None, false);
assert_eq!(all.iter().filter(|h| h.mode == mode::CEN && h.point.near(Vec2::ZERO, 1e-9)).count(), 1, "{all:?}");
}
#[test]
fn the_cursor_query_snaps_to_the_center_from_the_curve() {
// The path the drawing area uses (Session::snap_cursor): the point a click would take.
let mut s = Session::new();
s.execute("circle", &json!({ "center": [0, 0], "radius": 50 })).unwrap();
s.start("line").unwrap();
let q = snap::tracking::CursorQuery { base: None, deferred: true, corner: false, aperture: 1.0, tol: 0.5, now: 0.0, shift: false };
let r = s.snap_cursor(polar(Vec2::ZERO, 50.4, 33.0), &q);
assert_eq!(r.snap.map(|h| h.mode), Some(mode::CEN));
assert!(r.point.near(Vec2::ZERO, 1e-9), "{:?}", r.point);
}
/// The arc of the review of #2347 (and #1114's test): center (100,50), radius 80, 30°-150°.
fn review_arc() -> Session {
let mut s = Session::new();
s.execute("arc", &json!({ "center": [100, 50], "radius": 80, "start": 30, "end": 150 })).unwrap();
s
}
#[test]
fn a_midpoint_under_the_cursor_beats_the_center_from_the_curve() {
let s = review_arc();
// On the arc's midpoint (100,130) with Center and Midpoint running: Midpoint, as in AutoCAD.
for cursor in [Vec2::new(100.05, 130.0), Vec2::new(100.2, 130.1)] {
assert_eq!(snap_at(&s, cursor, 0.5, mode::CEN | mode::MID), Some((Vec2::new(100.0, 130.0), mode::MID)), "at {cursor:?}");
assert_eq!(snap_at(&s, cursor, 0.5, mode::MID), Some((Vec2::new(100.0, 130.0), mode::MID)), "at {cursor:?}");
}
// Elsewhere on the arc, with no snap point in the aperture, the center from the curve.
let (p, m) = snap_at(&s, polar(Vec2::new(100.0, 50.0), 80.1, 70.0), 0.5, mode::CEN | mode::MID).unwrap();
assert_eq!(m, mode::CEN);
assert!(p.near(Vec2::new(100.0, 50.0), 1e-9), "{p:?}");
}
#[test]
fn a_quadrant_under_the_cursor_beats_the_center_from_the_curve() {
let mut s = Session::new();
s.execute("circle", &json!({ "center": [20, 0], "radius": 2 })).unwrap();
let cursor = Vec2::new(20.1, 2.0);
assert_eq!(snap_at(&s, cursor, 0.5, mode::CEN | mode::QUA), Some((Vec2::new(20.0, 2.0), mode::QUA)));
assert_eq!(snap_at(&s, cursor, 0.5, mode::QUA), Some((Vec2::new(20.0, 2.0), mode::QUA)));
// Away from the quadrants the center from the curve.
let (p, m) = snap_at(&s, polar(Vec2::new(20.0, 0.0), 2.1, 45.0), 0.5, mode::CEN | mode::QUA).unwrap();
assert_eq!(m, mode::CEN);
assert!(p.near(Vec2::new(20.0, 0.0), 1e-9), "{p:?}");
}
#[test]
fn many_straight_segments_do_not_hide_a_circle_from_center() {
// A polyline of 2,500 straight segments zigzagging over the cursor, then a circle: the
// work limit counts circles and arcs only, so the circle's center is still found.
let mut s = Session::new();
let vertices: Vec<[f64; 2]> = (0..=2500).map(|i| [i as f64 * 0.04, if i % 2 == 0 { 0.0 } else { 100.0 }]).collect();
s.execute("pline", &json!({ "vertices": vertices })).unwrap();
s.execute("circle", &json!({ "center": [50, 50], "radius": 20 })).unwrap();
let (p, m) = snap_at(&s, polar(Vec2::new(50.0, 50.0), 20.2, 100.0), 0.5, mode::CEN).unwrap();
assert_eq!(m, mode::CEN);
assert!(p.near(Vec2::new(50.0, 50.0), 1e-9), "{p:?}");
}
#[test]
fn a_viewport_center_keeps_its_curve_distance_against_paper_space() {
use cadcraft_engine::doc::{Circle, Drawing, Viewport};
let mut d = Drawing::new_imperial();
let paper = Space::Paper("Layout1".into());
// Model circle (10,0) r16 seen through a viewport at half scale: paper center (100,50), radius 8.
d.add(&Space::Model, Common::default(), EntityKind::Circle(Circle { center: Vec3::new(10.0, 0.0, 0.0), radius: 16.0 })).unwrap();
let vp = Viewport {
center: Vec3::new(100.0, 50.0, 0.0),
width: 20.0,
height: 20.0,
view_center: Vec2::new(10.0, 0.0),
view_height: 40.0,
id: 2,
locked: false,
frozen_layers: Vec::new(),
layer_colors: Vec::new(),
clip: None,
on: true,
twist: 0.0,
};
d.add(&paper, Common::default(), EntityKind::Viewport(vp)).unwrap();
// A small paper-space circle whose curve passes 0.3 from the cursor and whose center is
// nearer the cursor (3.3) than the model circle's (8).
d.add(&paper, Common::default(), EntityKind::Circle(Circle { center: Vec3::new(108.0, 53.3, 0.0), radius: 3.0 })).unwrap();
// The cursor is on the model circle (0.1 off in paper units): its center wins.
let h = snap::osnap(&d, &paper, Vec2::new(108.1, 50.0), 0.5, mode::CEN, None, false).unwrap();
assert_eq!(h.mode, mode::CEN);
assert!(h.point.near(Vec2::new(100.0, 50.0), 1e-9), "{h:?}");
assert!(h.viewport.is_some());
// On the paper circle, away from the model one: its center.
let h = snap::osnap(&d, &paper, Vec2::new(108.0, 56.35), 0.5, mode::CEN, None, false).unwrap();
assert!(h.point.near(Vec2::new(108.0, 53.3), 1e-9), "{h:?}");
assert!(h.viewport.is_none());
}
-28
View File
@@ -70,9 +70,6 @@ fn elliptical_arc_perpendicular_and_tangent_from_a_base_point() {
let (q, m) = along_quarter(&s, mode::TAN, Some(base)).expect("a tangent point on the arc");
assert_eq!(m, mode::TAN);
assert!(on_quarter(q) && Vec2::new(q.x / 16.0, q.y / 4.0).dot(q - base).abs() < 1e-9, "{q:?}");
// The same tangent at a prompt that resolves deferred snaps (CIRCLE's 3P points, #1512).
let h = snap::osnap(s.doc().unwrap(), &Space::Model, q, 0.3, mode::TAN, Some(base), true).expect("tangent at a deferred prompt");
assert!(h.mode == mode::TAN && h.deferred.is_none() && h.point.near(q, 1e-9), "{h:?}");
// Perpendicular from (10,10): the line from the base runs along the normal.
let base = Vec2::new(10.0, 10.0);
let (q, m) = along_quarter(&s, mode::PER, Some(base)).expect("a perpendicular foot on the arc");
@@ -122,28 +119,3 @@ fn spline_midpoint_perpendicular_and_tangent() {
let d = (sp.eval(i + 1e-6) - sp.eval(i - 1e-6)).normalized();
assert!(d.cross((q - base).normalized()).abs() < 1e-3, "the line from the base runs along the curve at {q:?}");
}
#[test]
fn perpendicular_from_an_arcs_center_stays_on_the_arc() {
// From the center of an arc every point is perpendicular: the one under the cursor, never a
// point of its circle outside the sweep.
let mut s = Session::new();
s.execute("arc", &serde_json::json!({"center": [0, 0], "radius": 10, "start": 90, "end": 180})).unwrap();
let hit = snap::osnap(s.doc().unwrap(), &Space::Model, Vec2::new(-6.0, 8.0), 0.3, mode::PER, Some(Vec2::ZERO), false);
let (p, m) = hit.map(|h| (h.point, h.mode)).expect("a perpendicular on the arc");
assert_eq!(m, mode::PER);
assert!(p.near(Vec2::new(-6.0, 8.0), 1e-9), "{p:?}");
}
#[test]
fn perpendicular_to_a_ray_needs_the_cursor_on_the_ray() {
// A ray along +X from the origin: behind its start the cursor is over nothing.
let mut s = Session::new();
s.execute("ray", &serde_json::json!({"base": [0, 0], "through": [10, 0]})).unwrap();
let d = s.doc().unwrap();
let base = Some(Vec2::new(5.0, 3.0));
assert_eq!(snap::osnap(d, &Space::Model, Vec2::new(-2.0, 0.0), 0.5, mode::PER, base, false), None);
// Over the ray, the foot is found.
let hit = snap::osnap(d, &Space::Model, Vec2::new(2.0, 0.0), 0.5, mode::PER, base, false).expect("the foot on the ray");
assert!(hit.point.near(Vec2::new(5.0, 0.0), 1e-9), "{hit:?}");
}
-122
View File
@@ -21,17 +21,6 @@ fn last_line(s: &Session) -> (Vec2, Vec2) {
s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Line(l) = &e.kind { Some((l.a.xy(), l.b.xy())) } else { None }).last().unwrap()
}
/// The last circle drawn as (center, radius).
fn last_circle(s: &Session) -> (Vec2, f64) {
s.doc()
.unwrap()
.model
.iter()
.filter_map(|e| if let EntityKind::Circle(c) = &e.kind { Some((c.center.xy(), c.radius)) } else { None })
.last()
.unwrap()
}
fn near(p: Vec2, x: f64, y: f64) -> bool {
p.near(Vec2::new(x, y), 1e-9)
}
@@ -91,23 +80,6 @@ fn nothing_to_snap_to_rejects_the_point() {
assert!(near(s.last_point, 10.0, 10.0));
}
/// #2800: a typed PER or TAN finds its point from a pick anywhere on the object, as in AutoCAD.
/// The pick used to have to land within the aperture (0.125 here) of the foot or tangent point,
/// which you can't know in advance; elsewhere it said "No Perpendicular found".
#[test]
fn typed_per_and_tan_snap_from_anywhere_on_the_object() {
let mut s = drawing();
// From (5,5), PER picked at (3,0) on the line 0,0–10,0: two units from the foot (5,0).
s.script("LINE 5,5 PER 3,0\n\n").unwrap();
let (a, b) = last_line(&s);
assert!(near(a, 5.0, 5.0) && near(b, 5.0, 0.0), "{a:?} {b:?}");
// From (30,20), TAN picked at the top of the circle (centre 20,20, radius 3): the tangent
// points are at cos = 3/10 from the line to the base, and the upper one is nearer the pick.
s.script("LINE 30,20 TAN 20,23\n\n").unwrap();
let (a, b) = last_line(&s);
assert!(near(a, 30.0, 20.0) && near(b, 20.9, 20.0 + 3.0 * 0.91f64.sqrt()), "{a:?} {b:?}");
}
#[test]
fn from_nests_with_a_snap_override() {
let mut s = drawing();
@@ -144,97 +116,3 @@ fn a_command_keyword_wins_over_a_snap_word() {
s.cmdline("arc _cen").unwrap();
assert!(s.prompt_text().ends_with("Center of:"), "{}", s.prompt_text());
}
#[test]
fn tan_for_a_circle_radius_touches_the_picked_circle() {
// #1512: the circle around the center that touches the circle at 20,20 radius 3, on the side
// it was picked: the near side (radius 7), the far side (13), and through Diameter.
for (script, center, r) in [
("CIRCLE 30,20 TAN 23.02,20.03\n", (30.0, 20.0), 7.0),
("CIRCLE 30,20 TAN 16.98,19.97\n", (30.0, 20.0), 13.0),
("CIRCLE 20,10 D TAN 20.03,17.02\n", (20.0, 10.0), 7.0),
] {
let mut s = drawing();
s.script(script).unwrap();
assert!(s.running.is_none(), "{script}: {}", s.prompt_text());
let (c, got) = last_circle(&s);
assert!(near(c, center.0, center.1) && (got - r).abs() < 1e-9, "{script}: {c:?} r={got}");
}
}
#[test]
fn tan_for_a_3p_circle_touches_the_picked_circles() {
// #1512: through two points and tangent to the circle at 20,20 radius 3, the tangent pick
// first or last.
for script in ["CIRCLE 3P 26,20 26,26 TAN 23.02,20.03\n", "CIRCLE 3P TAN 23.02,20.03 26,20 26,26\n"] {
let mut s = drawing();
s.script(script).unwrap();
assert!(s.running.is_none(), "{script}: {}", s.prompt_text());
let (c, r) = last_circle(&s);
assert!((c.dist(Vec2::new(26.0, 20.0)) - r).abs() < 1e-9 && (c.dist(Vec2::new(26.0, 26.0)) - r).abs() < 1e-9, "{script}");
assert!((c.dist(Vec2::new(20.0, 20.0)) - (3.0 + r)).abs() < 1e-9, "{script}: {c:?} r={r}");
}
// Tan, Tan, Tan: the circle between three circles of radius 1, picked on their inner sides.
let mut s = Session::new();
s.script("CIRCLE 0,0 1\nCIRCLE 6,0 1\nCIRCLE 3,5 1\nCIRCLE 3P TAN 0.98,0.2 TAN 5.02,0.2 TAN 3.01,3.98\n").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
let (c, r) = last_circle(&s);
for k in [(0.0, 0.0), (6.0, 0.0), (3.0, 5.0)] {
assert!((c.dist(Vec2::new(k.0, k.1)) - (1.0 + r)).abs() < 1e-9, "{c:?} r={r}");
}
}
#[test]
fn tan_for_a_3p_circle_touches_an_arc_within_its_sweep() {
// #1512: through 26,20 and 26,26, the circles tangent to the circle at 20,20 radius 3 touch it
// on the right or the far left, both off an arc swept from 90° to 100°: no circle.
let mut s = Session::new();
s.execute("arc", &serde_json::json!({"center": [20, 20], "radius": 3, "start": 90, "end": 100})).unwrap();
s.script("CIRCLE 3P 26,20 26,26 TAN 19.74,22.99\n").unwrap();
assert!(s.prompt_text().contains("third point"), "{}", s.prompt_text());
assert!(!s.doc().unwrap().model.iter().any(|e| matches!(e.kind, EntityKind::Circle(_))));
}
#[test]
fn tan_for_a_3p_circle_takes_the_solution_that_touches_the_arc() {
// #1512: through 26,20 and 26,26, the circles tangent to the circle at 20,20 radius 3 touch it
// at about 29.6° and -103.3°. Picked at 20° on an arc swept from 200° to 25°, the 29.6°
// circle is nearer the pick but off the arc: the -103.3° one (radius 6.0826) is drawn.
let mut s = Session::new();
s.execute("arc", &serde_json::json!({"center": [20, 20], "radius": 3, "start": 200, "end": 25})).unwrap();
s.script("CIRCLE 3P 26,20 26,26 TAN 22.82,21.03\n").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
let (c, r) = last_circle(&s);
assert!((c.dist(Vec2::new(20.0, 20.0)) - (r - 3.0)).abs() < 1e-9 && (r - 6.082575694955838).abs() < 1e-9, "{c:?} r={r}");
}
#[test]
fn tan_for_a_circle_radius_refuses_the_picked_circles_own_center() {
// #1512: a circle around 20,20 would lie on the circle there, not touch it.
let mut s = drawing();
s.script("CIRCLE 20,20 TAN 23.02,20.03\n").unwrap();
assert!(s.prompt_text().contains("radius of circle"), "{}", s.prompt_text());
assert!(s.log.iter().any(|l| l.contains("No circle around the center is tangent there.")), "{:?}", s.log);
assert_eq!(s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Circle(_))).count(), 1);
}
#[test]
fn tan_for_a_3p_circle_refuses_the_picked_circle_itself() {
// #1512: tangent twice to the circle and through a point on it is only the circle itself.
let mut s = drawing();
s.script("CIRCLE 3P TAN 23.02,20.03 TAN 16.98,20.03 20,23\n").unwrap();
assert!(s.prompt_text().contains("third point"), "{}", s.prompt_text());
assert!(s.log.iter().any(|l| l.contains("Circle does not exist.")), "{:?}", s.log);
assert_eq!(s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Circle(_))).count(), 1);
}
#[test]
fn tan_for_a_3p_circle_through_points_in_line_with_the_picked_circles_center() {
// Through 3,0 and 5,0 and tangent to the unit circle at the origin: the two points and that
// circle's center lie on one line, the circle that touches it does not (center 4,±√48, radius 7).
let mut s = Session::new();
s.script("CIRCLE 0,0 1\nCIRCLE 3P 3,0 5,0 TAN 1,0\n").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
let (c, r) = last_circle(&s);
assert!(near(Vec2::new(c.x, c.y.abs()), 4.0, 48f64.sqrt()) && (r - 7.0).abs() < 1e-9, "{c:?} r={r}");
}
-102
View File
@@ -1,102 +0,0 @@
//! Tab cycling through object snaps: a crowd of candidates is capped, hostile cursors and
//! apertures give no candidates, and the list never repeats a snap.
use cadcraft_engine::Session;
use cadcraft_engine::doc::Space;
use cadcraft_engine::geom::Vec2;
use cadcraft_engine::pointmod::snap_candidates;
use cadcraft_engine::snap::mode;
use serde_json::json;
#[test]
fn a_crowd_of_snaps_is_capped_and_never_repeats() {
let mut s = Session::new();
// 600 short lines fanning out from points packed round the origin: 1,200 endpoints.
for i in 0..600 {
let a = f64::from(i) * 0.01;
let p = [1e-3 * a.cos(), 1e-3 * a.sin()];
s.execute("line", &json!({ "points": [p, [a.cos(), a.sin()]] })).unwrap();
}
let d = s.doc().unwrap();
let cands = snap_candidates(d, &Space::Model, Vec2::ZERO, 0.5, mode::END | mode::INT | mode::NEA, None, false);
assert!(!cands.is_empty());
assert!(cands.len() <= 257, "{} candidates", cands.len());
for (i, a) in cands.iter().enumerate() {
assert!(a.point.is_finite());
assert!(!cands.iter().skip(i + 1).any(|b| b.mode == a.mode && b.point == a.point), "{a:?} repeats");
}
}
#[test]
fn hostile_cursor_and_aperture_give_no_candidates() {
let mut s = Session::new();
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
let d = s.doc().unwrap();
let space = Space::Model;
let all = mode::END | mode::MID | mode::INT | mode::NEA | mode::PER;
for (c, ap) in [
(Vec2::new(f64::NAN, 0.0), 0.5),
(Vec2::new(0.0, f64::INFINITY), 0.5),
(Vec2::ZERO, f64::NAN),
(Vec2::ZERO, 0.0),
(Vec2::ZERO, -1.0),
(Vec2::ZERO, f64::INFINITY),
] {
assert!(snap_candidates(d, &space, c, ap, all, None, false).is_empty(), "{c:?} {ap}");
assert!(snap_candidates(d, &space, c, ap, all, Some(Vec2::new(f64::NAN, 1.0)), true).is_empty(), "{c:?} {ap}");
}
// A huge but finite aperture still answers, from the objects there are.
let far = snap_candidates(d, &space, Vec2::ZERO, 1e300, mode::END, None, false);
assert!(far.iter().all(|h| h.point.is_finite()));
// Object snaps off (or only the OFF bit) offer nothing.
assert!(snap_candidates(d, &space, Vec2::ZERO, 0.5, 0, None, false).is_empty());
assert!(snap_candidates(d, &space, Vec2::ZERO, 0.5, mode::END | mode::OFF, None, false).is_empty());
}
#[test]
fn every_endpoint_under_the_aperture_is_offered_not_one_per_mode() {
let mut s = Session::new();
// Three line ends close together, all within the aperture of the cursor between them.
for (a, b) in [([0.0, 0.0], [10.0, 0.0]), ([0.06, 0.05], [0.06, 10.0]), ([0.03, -0.06], [-10.0, -10.0])] {
s.execute("line", &json!({ "points": [a, b] })).unwrap();
}
let d = s.doc().unwrap();
let cands = snap_candidates(d, &Space::Model, Vec2::new(0.03, 0.0), 0.125, mode::END, None, false);
let ends: Vec<Vec2> = cands.iter().filter(|h| h.mode == mode::END).map(|h| h.point).collect();
assert_eq!(ends.len(), 3, "{cands:?}");
for want in [Vec2::new(0.0, 0.0), Vec2::new(0.06, 0.05), Vec2::new(0.03, -0.06)] {
assert!(ends.iter().any(|p| p.near(want, 1e-12)), "{want:?} in {ends:?}");
}
// The first is the snap a click would take.
let first = snap_candidates(d, &Space::Model, Vec2::new(0.03, 0.0), 0.125, mode::END, None, false).first().map(|h| h.point);
assert_eq!(first, cadcraft_engine::snap::osnap(d, &Space::Model, Vec2::new(0.03, 0.0), 0.125, mode::END, None, false).map(|h| h.point));
}
/// A base point that is not a number gives no candidates, though the cursor is on an endpoint: the
/// perpendicular and tangent points from it would be meaningless, as a viewport already treats it.
#[test]
fn a_non_finite_base_gives_no_candidates() {
let mut s = Session::new();
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
let d = s.doc().unwrap();
let all = mode::END | mode::PER | mode::TAN | mode::NEA;
for base in [Vec2::new(f64::NAN, 1.0), Vec2::new(1.0, f64::INFINITY), Vec2::new(f64::NEG_INFINITY, f64::NAN)] {
assert!(snap_candidates(d, &Space::Model, Vec2::new(10.01, 0.0), 0.5, all, Some(base), false).is_empty(), "{base:?}");
assert!(cadcraft_engine::snap::osnap_all(d, &Space::Model, Vec2::new(10.01, 0.0), 0.5, all, Some(base), true).is_empty(), "{base:?}");
}
// A finite base still offers them.
assert!(!snap_candidates(d, &Space::Model, Vec2::new(10.01, 0.0), 0.5, all, Some(Vec2::new(5.0, 5.0)), false).is_empty());
}
#[test]
fn deferred_snaps_of_two_curves_at_one_point_are_both_offered() {
// Two circles touching at the origin: each offers its own deferred tangent there, and the
// line drawn from it depends on which circle it is.
let mut s = Session::new();
s.script("CIRCLE 0,1 1\nCIRCLE 0,-2 2\n").unwrap();
let d = s.doc().unwrap();
let all = cadcraft_engine::snap::osnap_all(d, &Space::Model, Vec2::new(0.0, 0.1), 0.5, mode::TAN, None, true);
let curves: Vec<_> = all.iter().filter_map(|h| h.deferred.map(|f| f.curve)).collect();
assert_eq!(curves.len(), 2, "{all:?}");
assert_ne!(curves.first(), curves.get(1), "{all:?}");
}
+4 -7
View File
@@ -129,21 +129,18 @@ 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));
}
// 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()) {
if !g.value.is_empty() {
out.push(Entity {
handle: Handle(0),
common: text_c.clone(),
common: text_c,
kind: EntityKind::MText(MText {
insert: at.to3(0.0),
insert: g.text_pos.to3(0.0),
height: g.text_height,
width: 0.0,
attach: 5,
rotation: g.text_angle,
style: style.text_style.clone(),
contents: cadcraft_render::DimGeometry::mtext_code(&contents),
contents: g.mtext_contents(),
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
+1 -2
View File
@@ -61,8 +61,7 @@ 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"`, `"B4 (JIS)"`,
/// `"Japanese Postcard"`…).
/// Paper name from [`cadcraft_render::PAPER_SIZES`] (`"A4"`, `"Letter"`, `"ANSI B"`…).
pub paper: Option<String>,
/// Custom paper size in millimetres (portrait width, height).
pub paper_mm: Option<(f64, f64)>,
-41
View File
@@ -1024,47 +1024,6 @@ 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
@@ -1,48 +0,0 @@
//! #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,7 +16,6 @@ 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;
+2 -111
View File
@@ -61,18 +61,9 @@ 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 {
@@ -81,12 +72,8 @@ 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 {
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();
let mut out = String::with_capacity(self.value.len() + 2);
let mut chars = self.value.chars().peekable();
while let Some(c) = chars.next() {
match c {
'⌀' => out.push_str("%%c"),
@@ -279,19 +266,7 @@ 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);
}
@@ -380,70 +355,6 @@ 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);
@@ -484,26 +395,6 @@ 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()
+1 -4
View File
@@ -212,7 +212,6 @@ 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));
@@ -267,9 +266,7 @@ 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 };
let end = state.text_mid + side * (state.text_width / 2.0 + config.gap);
g.text_leader = Some((base, end));
g.dim(vec![base, end]);
g.dim(vec![base, state.text_mid + side * (state.text_width / 2.0 + config.gap)]);
}
}
if let Some(jog) = d.marks.jog_line {
-92
View File
@@ -50,98 +50,6 @@ 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);
+5 -122
View File
@@ -31,11 +31,7 @@ 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–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)`…).
/// Common ISO (A0–A6, B0–B5) and ANSI/ARCH sheet sizes (ISO 216, ANSI/ASME Y14.1).
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),
@@ -48,22 +44,8 @@ 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", "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),
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),
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),
@@ -86,22 +68,9 @@ impl PaperSize {
}
}
/// 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).
/// Look up a paper size by canonical name or alias (case- and space-insensitive).
pub fn paper_size(name: &str) -> Option<&'static PaperSize> {
// 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 norm = |s: &str| s.chars().filter(|c| !c.is_whitespace() && *c != '_' && *c != '-').collect::<String>().to_ascii_lowercase();
let n = norm(name);
if n.is_empty() {
return None;
@@ -231,73 +200,6 @@ 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.
@@ -444,22 +346,3 @@ 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));
}
}
+1 -51
View File
@@ -1,4 +1,4 @@
//! Bake the contributor credits and validate the shared Chinese overlay at build time.
//! Bake the contributor credits into the binary as static Rust tables. Nothing is read at run time.
//!
//! - contributors/contributors.json: commit stats per GitHub username, with a mark for whose people.toml
//! entry is verified.
@@ -11,11 +11,7 @@ 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())
@@ -29,52 +25,6 @@ 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));
+1 -8
View File
@@ -96,19 +96,12 @@ impl CadApp {
}
}
/// Every frame: autosave what is due and keep the drawing locks, and wake up when the next
/// autosave or lock heartbeat is.
/// Every frame: autosave what is due, and wake up when the next one 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.
+2 -4
View File
@@ -200,14 +200,12 @@ pub(super) fn override_cursor(app: &mut CadApp, raw: Vec2, xf: &Xf) {
let s = &app.session.settings;
let osmode = over.unwrap_or(s.osmode) | if s.osnaphatch { snap::mode::HATCH } else { 0 };
let Ok(st) = app.session.state() else { return };
let space = st.edit_space();
let frozen = st.viewport_frozen();
let hit = match cycle {
Some(i) => {
let cands = cadcraft_engine::pointmod::snap_candidates_with_frozen(&st.doc, &space, raw, ap, osmode, base, deferred, frozen);
let cands = cadcraft_engine::pointmod::snap_candidates(&st.doc, &st.edit_space(), raw, ap, osmode, base, deferred);
cands.get(i % cands.len().max(1)).copied()
}
None => snap::osnap_with_frozen(&st.doc, &space, raw, ap, osmode, base, deferred, frozen),
None => snap::osnap(&st.doc, &st.edit_space(), raw, ap, osmode, base, deferred),
};
let p = match (hit, app.canvas.snap) {
(Some(h), _) => {
+1 -17
View File
@@ -352,24 +352,8 @@ 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(|| {
let mut entries = parse(l.source).0;
if l.code == "zh" {
merge_ordinary_zh(&mut entries, include_str!("i18n/zh_shared.tsv"));
}
entries
})
})
LANGUAGES.iter().find(|l| l.code == language && !l.source.is_empty()).map(|l| l.catalog.get_or_init(|| parse(l.source).0))
}
pub fn tr<'a>(language: &str, source: &'a str) -> &'a str {
-1
View File
@@ -1256,7 +1256,6 @@
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
-29
View File
@@ -40,35 +40,6 @@ 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,7 +1359,6 @@
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
-1
View File
@@ -985,7 +985,6 @@
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
-3
View File
@@ -1,3 +0,0 @@
# 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 构造几何
-1
View File
@@ -47,7 +47,6 @@ mod shared_controls;
mod shortcut_menus;
mod shortcuts_checked;
mod slow_clicks;
mod snap_tab_cycling;
mod space_at_options;
mod status_bar_toggles;
mod style_dialogs;
-136
View File
@@ -1,136 +0,0 @@
//! Tab at a point prompt steps through every object snap under the aperture (each endpoint of
//! each object nearby), not just the closest snap of each running mode, and comes back round.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{Common, Drawing, EntityKind, Line, Space};
use cadcraft_engine::snap::mode;
use cadcraft_geom::Vec2;
use cadcraft_ui_egui::{CadApp, Services};
use egui::{Event, Modifiers, PointerButton, Pos2, vec2};
use egui_kittest::Harness;
use serde_json::json;
#[test]
fn tab_cycles_through_every_endpoint_under_the_aperture() {
let mut s = Session::new();
// Three line ends close together (within the aperture of the cursor between them).
for (a, b) in [([0.0, 0.0], [10.0, 0.0]), ([0.06, 0.05], [0.06, 10.0]), ([0.03, -0.06], [-10.0, -10.0])] {
s.execute("line", &json!({ "points": [a, b] })).unwrap();
}
s.execute("setvar", &json!({ "name": "OSMODE", "value": 1 })).unwrap();
s.execute("view.set", &json!({ "center": [0, 0], "height": 20 })).unwrap();
let mut app = CadApp::new(s, Services::default());
app.canvas.zoom_pending = false;
let mut h = Harness::builder().with_context_setup(cadcraft_ui_egui::framework::install_headless).with_size(vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut CadApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(3);
h.state_mut().session.start("line").unwrap();
h.run_steps(2);
let xf = h.state().canvas.xf.unwrap();
let at = xf.to_screen(Vec2::new(0.03, 0.0));
h.event(Event::PointerMoved(at));
h.run_steps(2);
let mut seen: Vec<Vec2> = Vec::new();
for i in 0..4 {
let p = h.state().canvas.snap.map(|s| s.point).unwrap();
if i < 3 {
assert!(!seen.iter().any(|q| q.near(p, 1e-9)), "Tab {i} repeats {p:?} ({seen:?})");
} else {
assert!(seen.first().is_some_and(|q| q.near(p, 1e-9)), "the fourth Tab comes back round");
}
seen.push(p);
h.key_press(egui::Key::Tab);
h.run_steps(2);
}
for want in [Vec2::new(0.0, 0.0), Vec2::new(0.06, 0.05), Vec2::new(0.03, -0.06)] {
assert!(seen.iter().any(|q| q.near(want, 1e-9)), "{want:?} in {seen:?}");
}
}
/// Three endpoints near 10,0: 10,0 (the nearest to the cursor), 10.03,0 and 9.95,0. Endpoint is
/// the only running snap, so every candidate is an endpoint.
fn three_ends() -> Harness<'static, CadApp> {
let mut d = Drawing::new_imperial();
for (a, b) in [((0.0, 0.0), (10.0, 0.0)), ((10.03, 0.0), (20.0, 0.0)), ((9.95, 0.0), (9.95, -5.0))] {
let line = Line { a: Vec2::new(a.0, a.1).to3(0.0), b: Vec2::new(b.0, b.1).to3(0.0) };
d.add(&Space::Model, Common::default(), EntityKind::Line(line)).unwrap();
}
let mut session = Session::empty();
session.open_drawing(d, "Tab snap cycling", None);
session.execute("view.set", &json!({"center":[10,0],"height":8})).unwrap();
session.settings.osmode = mode::END;
session.settings.snapmode = false;
session.settings.orthomode = false;
let mut app = CadApp::new(session, Services::default());
app.canvas.zoom_pending = false;
let mut h = Harness::builder().with_context_setup(cadcraft_ui_egui::framework::install_headless).with_size(vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut CadApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(5);
h.state_mut().start("line");
h.run_steps(2);
assert_eq!(h.state().session.running.as_ref().unwrap().id, "line");
let ap = h.state().session.settings.aperture / h.state().canvas.xf.unwrap().scale;
assert!(ap > 0.07, "all three endpoints lie in the aperture ({ap})");
h
}
const CURSOR: Vec2 = Vec2::new(10.01, 0.0);
fn hover(h: &mut Harness<'_, CadApp>, p: Vec2) -> Pos2 {
let pos = h.state().canvas.xf.unwrap().to_screen(p);
h.event(Event::PointerMoved(pos));
h.run_steps(3);
pos
}
/// Tab, as the command line receives it (`cmdline::capture_tab`).
fn tab(h: &mut Harness<'_, CadApp>) {
h.key_press(egui::Key::Tab);
h.run_steps(3);
}
fn snapped(h: &Harness<'_, CadApp>) -> Vec2 {
let hit = h.state().canvas.snap.expect("a snap marker");
assert_eq!(hit.mode, mode::END);
hit.point
}
fn assert_at(got: Vec2, x: f64) {
assert!(got.near(Vec2::new(x, 0.0), 1e-9), "{got:?}, expected {x},0");
}
#[test]
fn moving_the_cursor_away_starts_the_cycle_over() {
let mut h = three_ends();
hover(&mut h, CURSOR);
tab(&mut h);
assert_at(snapped(&h), 10.03);
hover(&mut h, Vec2::new(10.0, 2.0));
assert!(h.state().canvas.snap.is_none());
hover(&mut h, CURSOR);
assert_at(snapped(&h), 10.0);
}
#[test]
fn a_click_places_the_candidate_tab_chose() {
let mut h = three_ends();
let pos = hover(&mut h, CURSOR);
tab(&mut h);
assert_at(snapped(&h), 10.03);
for pressed in [true, false] {
h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
h.run_steps(2);
}
let base = h.state().session.current_prompt().and_then(|p| p.base).expect("LINE asks for the next point");
assert_at(base, 10.03);
}
+3 -14
View File
@@ -16,23 +16,12 @@ The built-in devices come first:
They offer the standard sizes:
- 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)
- ISO 216 A0–A6 and B0–B5
- ANSI A–E and Legal
- ARCH A–E and E1
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.
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.
User devices are files in our own format, kept in the `plotters` folder of the CADCraft
settings directory:
+7 -34
View File
@@ -185,9 +185,7 @@ 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"),
("nightly-dispatch.yml", "nightly-dispatch.yml")):
for name, workflow in (("nightly.yml", "nightly.yml"), ("nightly-sign.yml", "nightly-sign.yml")):
source = (ROOT / ".github/workflows" / workflow).read_text()
expected = NightlyEnabledCallers.GUARDS[name]
guard = re.search(r"(?m)^ if: >-\n(?: [^\n]*\n)+", source)[0]
@@ -197,38 +195,15 @@ class TrustedSourcePreparation(unittest.TestCase):
(indicator, expression), = job_conditions(jobs)
self.assertFalse(indicator == ">-" and " ".join(expression.split()) == expected)
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:
def test_no_nightly_schedule_is_registered(self):
for name, event in (("nightly.yml", "workflow_dispatch"),
("nightly-sign.yml", "workflow_dispatch")):
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, 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)
self.assertEqual(triggers, [f" {event}:"], "schedule/activation needs explicit review")
def test_signer_serialization_contract_is_enforced(self):
assert_nightly_serialization((ROOT / ".github/workflows/nightly-sign.yml").read_text())
@@ -249,7 +224,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", "nightly-dispatch.yml"):
for name in ("nightly.yml", "nightly-sign.yml"):
source = (ROOT / ".github/workflows" / name).read_text()
executable = "\n".join(line for line in source.splitlines()
if not line.lstrip().startswith("#"))
@@ -347,7 +322,6 @@ 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):
@@ -364,8 +338,7 @@ 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"], ["github-actions[bot]"],
"only github-actions[bot] may trigger automatic scheduled signing")
self.assertEqual(policy["automatic_signer_actors"], [], "no automatic signer without a schedule")
def test_an_actor_outside_the_release_managers_is_refused(self):
source = (ROOT / ".github/workflows/nightly.yml").read_text()