Compare commits

..
8 Commits
181 changed files with 1825 additions and 8428 deletions
+5 -5
View File
@@ -2,13 +2,13 @@
"schema": "craft-nightly-release-policy/v3",
"repository": "storytold/cadcraft",
"repository_id": 1408289866,
"producer_workflow_id": 429719786,
"producer_workflow_id": null,
"producer_workflow_path": ".github/workflows/nightly.yml",
"producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"producer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea",
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
"signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"release_branch": "nightly-signer",
"signer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
"release_branch": "release",
"manual_actors": [
"bflatastic",
"dylanmtaylor",
+7 -10
View File
@@ -1,8 +1,7 @@
name: CADCraft release-ref nightly signer
# Enabled for supervised manual dispatch on the dedicated nightly-signer branch, which only ever
# fast-forwards to reviewed main commits (never the stable release branch).
# A reusable callee does not change context; this must be a real top-level signer-branch dispatch.
# Enabled for supervised manual dispatch on release. Main/release contents must match.
# A reusable callee does not change context; this must be a real top-level release dispatch.
on:
workflow_dispatch:
inputs:
@@ -23,23 +22,21 @@ concurrency:
jobs:
release:
# Actual context guards: official repository, manual dispatch, real nightly-signer branch.
# Actual context guards: official repository, manual dispatch, real release branch.
if: >-
github.repository == 'storytold/cadcraft' &&
github.event_name == 'workflow_dispatch' &&
github.ref == 'refs/heads/nightly-signer' && github.ref_type == 'branch'
github.ref == 'refs/heads/release' && github.ref_type == 'branch'
permissions:
contents: write
actions: read
checks: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@605d58766e8f536564da8fc81d3676ac86816dea
with:
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
app-name: cadcraft
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
producer_run_id: ${{ inputs.producer_run_id }}
producer_run_attempt: ${{ inputs.producer_run_attempt }}
# No secrets: inherit or raw platform values in this caller. Only the isolated native
# callee job may bind the release environment and export its keys; that environment must
# admit nightly-signer alongside release before the first dispatch.
# callee job may bind the existing release environment and export keys in its signing step.
+4 -4
View File
@@ -22,13 +22,13 @@ jobs:
actions: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea
with:
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
app-name: cadcraft
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
# One producer run builds every listed platform for one all-or-nothing release. The pin is the
# craft-common-actions main commit that merged the exact-analysis admission (#371, after #370,
# #369 and #364).
# craft-common-actions main commit that merged #339 (bounded lineage compares), on top of the
# Linux/macOS signer (#342).
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
Generated
+84 -1270
View File
File diff suppressed because it is too large Load Diff
+32 -36
View File
@@ -14,11 +14,11 @@ repository = "https://github.com/storytold/cadcraft"
# internal
cadcraft-geom = { path = "crates/geom" }
# DXF tags: the shared reader and writer (moved from crates/dxf; craft-libs#791).
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "219c1d0b14177af6f291395d6587f61a5e09043a" }
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
cadcraft-color = { path = "crates/color" }
cadcraft-doc = { path = "crates/doc" }
cadcraft-constraints = { path = "crates/constraints" }
@@ -28,19 +28,19 @@ cadcraft-io = { path = "crates/io" }
cadcraft-engine = { path = "crates/engine" }
cadcraft-ui-egui = { path = "crates/ui-egui" }
cadcraft-mcp = { path = "crates/mcp" }
craft-mcp = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-mcp = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
# SVG/SVGZ import and export geometry (craft-libs#778).
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
# Which paths stored in a drawing (xrefs, data links) may be opened.
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
# PDF writing (krilla) for plots, and reading them back in tests. The root patches below pin
# craft-pdf's patched backends to the same revision (Cargo ignores dependency-local patches).
craft-pdf = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false }
craft-pdf = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", default-features = false }
# TrueType embedding-permission classification for plotted fonts (craft-libs#778).
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", default-features = false }
# Delimited text (CSV/TSV) parsing (shared Craft library).
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
clap = { version = "4", features = ["derive", "env"] }
clap_complete = "4.6.11"
clap_mangen = { version = "0.3.3", features = ["env"] }
@@ -74,12 +74,8 @@ encoding_rs = "0.8.35"
quick-xml = "0.42"
# ui
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-behavior = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-host = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-keymap = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-theme = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["serde"] }
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] }
egui = { version = "0.37", default-features = false, features = ["default_fonts", "monochrome_emoji_fonts"] }
# Resizable table columns (About ▸ Contributors / Models); no image loaders.
egui_extras = { version = "0.37", default-features = false }
@@ -89,7 +85,7 @@ egui-wgpu = "0.37"
# Monotonic time on native and web (performance.now on wasm).
web-time = "1.1"
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] }
rfd = "0.17"
arboard = { version = "3.6", default-features = false }
@@ -121,23 +117,23 @@ debug = 0
# PDF backends for craft-pdf: pinned to the same reviewed craft-libs revision as craft-pdf itself
# (Cargo ignores dependency-local patches).
[patch.crates-io]
krilla = { version = "=0.8.2", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
krilla = { version = "=0.8.2", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
# Keep the complete egui family and native event bridge on reviewed fork commits.
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
+2 -2
View File
@@ -21,8 +21,8 @@ cadcraft-io = { workspace = true }
cadcraft-fonts = { workspace = true }
# The host messages (storytold/craft-libs): one contract and one bridge for the web builds.
# The page command API (storytold/craft-libs#413): window.cadcraft over the control channel.
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "0.1.0" }
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "0.1.0" }
egui = { workspace = true }
log = { workspace = true }
serde_json = { workspace = true }
+2 -4
View File
@@ -54,12 +54,11 @@ mod web {
if let Some(bridge) = &self.2 {
bridge.report_dirty(&self.0);
}
self.0.close_path(ctx);
}
/// Forward raw input to the web `CadApp` and hand the frame's root values to the UI runtime.
/// Forward raw input to the web `CadApp` and capture Tab at the command line.
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
self.0.raw_input_hook(ctx, raw);
self.0.before_input(ctx);
cadcraft_ui_egui::cmdline::capture_tab(ctx, raw);
}
/// Preferences and validated panel placement survive reloads; egui memory is not kept.
fn save(&mut self, storage: &mut dyn eframe::Storage) {
@@ -167,7 +166,6 @@ mod web {
canvas,
options,
Box::new(move |cc| {
cadcraft_ui_egui::framework::install_headless(&cc.egui_ctx);
// Embedded, the host sends the drawing: start on the Start tab, not Drawing1.
let session = if app_bridge.is_some() { Session::empty() } else { Session::new() };
let control = crate::api::install(cc.egui_ctx.clone());
+1 -1
View File
@@ -94,7 +94,7 @@ mod tests {
let mut ui = UiState::default();
let before = serde_json::to_value(&ui).unwrap();
let mut invalid = ui.clone();
invalid.docking = cadcraft_ui_egui::docking::Workspace::default();
invalid.docking.layout.root = None;
assert!(save(&invalid).is_err());
let mut record: Value = serde_json::from_str(&save(&ui).unwrap()).unwrap();
record["docking"] = serde_json::to_value(&invalid.docking).unwrap();
+7 -3
View File
@@ -41,18 +41,22 @@ winit = { version = "0.30", default-features = false, features = ["x11"] }
zbus = { version = "=5.19.0", default-features = false, features = ["async-io", "blocking-api"] }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
# Floating panels open in their own OS windows on the desktop; the web build keeps them in the page.
craft-ui = { workspace = true, features = ["native-windows"] }
craft-update = { workspace = true }
rfd = { workspace = true }
sys-locale = "0.3"
[target.'cfg(target_os = "macos")'.dependencies]
# `title_bar::sync_movable`: AppKit's title-band drag leaves the window still under the row's
# controls and under floating panels.
craft-window = { workspace = true }
muda = { version = "0.21", default-features = false }
# Quit CADCraft as a close request of the main window, so the unsaved-changes question runs (#2157).
craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
# View ▸ Accessibility ▸ Animation Effects ▸ Use System Setting: the system's Reduce motion
# (system_animations.rs). Already in Cargo.lock through muda.
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSWorkspace", "NSAccessibility"] }
# The same winit eframe uses (the storytold fork, patched in the workspace).
# The same winit eframe uses (the storytold fork, patched in the workspace): its opt-in that turns
# AppKit's terminate (Cmd+Q, Dock Quit) into a close request, so unsaved changes are asked about.
# `rwh_06`: the window handle a file dialog shown as a sheet attaches to (src/sheet.rs).
winit = { version = "0.30", default-features = false, features = ["rwh_06"] }
# Waits for the answer of a file dialog shown as a sheet (src/sheet.rs). MIT OR Apache-2.0, already
+37 -25
View File
@@ -61,6 +61,9 @@ struct App {
/// `CADCRAFT_NO_NATIVE_MENU`: the menus stay inside the window.
#[cfg(target_os = "macos")]
menus_in_window: bool,
/// The `movable` flag last set on the main window.
#[cfg(target_os = "macos")]
movable: Option<bool>,
/// Drawings and quit requests from Finder, the Dock and `open -a` (see `apple_events`).
#[cfg(target_os = "macos")]
apple_events: fmv_macos_events::Inbox,
@@ -138,18 +141,17 @@ impl eframe::App for App {
if std::mem::take(&mut self.cad.quit_requested) {
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
}
self.cad.close_path(ctx);
}
/// Apply the desktop-theme fallback, forward raw input to `CadApp`, and hand the frame's root values to the UI
/// runtime.
/// Apply the desktop-theme fallback, forward raw input to `CadApp`, and capture Tab at the command line.
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
follow_desktop(raw, self.desktop_theme.current());
self.cad.raw_input_hook(ctx, raw);
self.cad.before_input(ctx);
cadcraft_ui_egui::cmdline::capture_tab(ctx, raw);
}
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
cadcraft_ui_egui::framework::before_ui(ui.ctx(), &*frame);
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
self.cad.guarded_ui(ui);
#[cfg(target_os = "macos")]
craft_window::title_bar::sync_movable(ui.ctx(), &mut self.movable);
}
/// A normal exit: the workspace is saved, and this run's autosave files are not needed (a
/// crash leaves them for recovery).
@@ -300,15 +302,17 @@ const MIN_INNER_SIZE: [f32; 2] = [900.0, 560.0];
/// The main window: its size, title bar, placement and rendering needs. `restoring`: a window state
/// saved by the last session is restored instead of opening centred. `stencil`: the stencil bits of
/// its render pass ([`stencil_bits`]).
fn window_options(restoring: bool, stencil: u8, frame: Option<&cadcraft_ui_egui::framework::Decision>) -> eframe::NativeOptions {
let viewport = egui::ViewportBuilder::default()
.with_title(os_window::name_for(os_window::identity()))
.with_inner_size([1600.0, 1000.0])
.with_min_inner_size(MIN_INNER_SIZE)
.with_drag_and_drop(true)
.with_app_id(os_window::app_id());
fn window_options(restoring: bool, stencil: u8) -> eframe::NativeOptions {
eframe::NativeOptions {
viewport: cadcraft_ui_egui::framework::apply_frame(viewport, frame),
viewport: egui::ViewportBuilder::default()
.with_title(os_window::name_for(os_window::identity()))
.with_inner_size([1600.0, 1000.0])
.with_min_inner_size(MIN_INNER_SIZE)
.with_drag_and_drop(true)
.with_fullsize_content_view(true)
.with_titlebar_shown(false)
.with_title_shown(false)
.with_app_id(os_window::app_id()),
// The size, position and maximized state are kept between sessions (#2595); eframe keeps a
// restored window on the monitors that are connected now.
persist_window: true,
@@ -540,9 +544,6 @@ fn main() -> eframe::Result {
if stencil == 0 {
log::warn!("CADCRAFT_STENCIL is off: the window has no stencil buffer; clipped layout viewports draw unclipped");
}
// XWayland when it's there (see below), unless CADCRAFT_WAYLAND=1 keeps the native Wayland backend.
let forced_x11 = cfg!(all(unix, not(target_os = "macos"))) && std::env::var_os("DISPLAY").is_some() && vars.wayland != Switch::On;
let frame = cadcraft_ui_egui::framework::frame_decision(forced_x11);
let persistence_path = vars
.portable_storage_file
.clone()
@@ -552,7 +553,7 @@ fn main() -> eframe::Result {
// swapchains hold two frames back under vsync (`CADCRAFT_VSYNC=1` restores vsync).
wgpu_options: eframe::egui_wgpu::WgpuConfiguration::default().with_surface_config(surface),
persistence_path: persistence_path.clone(),
..window_options(restores_window(persistence_path.as_deref()), stencil, frame.as_ref())
..window_options(restores_window(persistence_path.as_deref()), stencil)
};
if let Some(icon) = app_icon() {
options.viewport = options.viewport.with_icon(icon);
@@ -575,12 +576,22 @@ fn main() -> eframe::Result {
// manager showed a "no" cursor. Run through XWayland when it's there; CADCRAFT_WAYLAND=1
// keeps the native Wayland backend.
#[cfg(all(unix, not(target_os = "macos")))]
if forced_x11 {
if std::env::var_os("DISPLAY").is_some() && vars.wayland != Switch::On {
options.event_loop_builder = Some(Box::new(|b| {
use winit::platform::x11::EventLoopBuilderExtX11;
b.with_x11();
}));
}
// macOS: Quit CADCraft (Cmd+Q), the Dock's Quit and logout end the app through AppKit's
// terminate, which would skip the unsaved-changes prompt (#2157). winit turns each into a
// close request for the window instead, so it asks first, as the close button does.
#[cfg(target_os = "macos")]
{
options.event_loop_builder = Some(Box::new(|b| {
use winit::platform::macos::EventLoopBuilderExtMacOS;
b.with_close_requested_on_terminate(true);
}));
}
// Registered before the event loop starts, so it catches the Finder event that launched us as
// well as later ones. Lives until the event loop returns; the app creator only borrows it.
#[cfg(target_os = "macos")]
@@ -593,7 +604,6 @@ fn main() -> eframe::Result {
os_window::name_for(os_window::identity()),
options,
Box::new(move |cc| {
cadcraft_ui_egui::framework::install(&cc.egui_ctx, forced_x11, frame.clone())?;
let mut app = CadApp::new(Session::empty(), services());
// The exit hook runs in `on_exit`: macOS ends the process inside AppKit's terminate after
// it, so nothing after `run_native` can be relied on there.
@@ -656,7 +666,7 @@ fn main() -> eframe::Result {
}
app.session.set_lisp_support_dir(Some(support));
}
app.integrated_titlebar = cadcraft_ui_egui::framework::draws_title_row(frame.as_ref());
app.integrated_titlebar = cfg!(target_os = "macos");
if surface.present_mode == eframe::wgpu::PresentMode::AutoNoVsync {
app.frame_cap = Some(cadcraft_ui_egui::gpu::FrameCap::new(240));
}
@@ -707,6 +717,8 @@ fn main() -> eframe::Result {
#[cfg(target_os = "macos")]
menus_in_window: vars.no_native_menu == Switch::On,
#[cfg(target_os = "macos")]
movable: None,
#[cfg(target_os = "macos")]
apple_events,
}))
}),
@@ -744,7 +756,7 @@ mod tests {
/// #1129: the first launch opens centred, not cascaded from the top-left corner.
#[test]
fn the_first_launch_opens_centred() {
let o = window_options(false, STENCIL_BITS, None);
let o = window_options(false, STENCIL_BITS);
assert!(o.centered, "centred on launch");
assert!(o.persist_window, "the window state is saved for the next launch");
}
@@ -752,7 +764,7 @@ mod tests {
/// #2595: a saved window state (size, position, maximized) is restored, not centred over.
#[test]
fn a_saved_window_reopens_where_it_was() {
let o = window_options(true, STENCIL_BITS, None);
let o = window_options(true, STENCIL_BITS);
assert!(!o.centered, "centring would move a restored window");
assert!(o.persist_window);
}
@@ -777,8 +789,8 @@ mod tests {
#[test]
fn the_window_carries_the_chosen_stencil_bits() {
for bits in [0, STENCIL_BITS] {
assert_eq!(window_options(false, bits, None).stencil_buffer, bits);
assert_eq!(window_options(true, bits, None).stencil_buffer, bits);
assert_eq!(window_options(false, bits).stencil_buffer, bits);
assert_eq!(window_options(true, bits).stencil_buffer, bits);
}
let format = |bits| eframe::egui_wgpu::depth_format_from_bits(0, bits);
assert_eq!(format(0), None, "no stencil: the canvas builds no clip pipelines");
+2 -10
View File
@@ -15,9 +15,6 @@ pub struct NativeMenu {
items: HashMap<String, (String, String, MenuItem)>,
submenus: Vec<(String, Submenu)>,
predefined: Vec<(&'static str, PredefinedMenuItem)>,
/// Quit CADCraft: a close request of the main window, so unsaved drawings are asked about first.
/// muda's predefined Quit ends the process through `terminate:` without asking.
quit: MenuItem,
language: &'static str,
/// Monotonic time of the last enablement refresh. `NEG_INFINITY` makes the first poll refresh
/// immediately: `now_ms` starts near zero, so the old `0.0` sentinel suppressed the first
@@ -61,6 +58,7 @@ impl NativeMenu {
("Hide CADCraft", PredefinedMenuItem::hide(Some(i18n::tr(language, "Hide CADCraft")))),
("Hide Others", PredefinedMenuItem::hide_others(Some(i18n::tr(language, "Hide Others")))),
("Show All", PredefinedMenuItem::show_all(Some(i18n::tr(language, "Show All")))),
("Quit CADCraft", PredefinedMenuItem::quit(Some(i18n::tr(language, "Quit CADCraft")))),
];
// The Mac place for preferences: CADCraft ▸ Settings… (⌘,) opens the Options dialog.
let settings = MenuItem::with_id("cc-settings", i18n::tr(language, "Settings..."), true, accel("Cmd+Comma"));
@@ -71,8 +69,6 @@ impl NativeMenu {
let _ = app_menu.append(&PredefinedMenuItem::separator());
}
}
let quit = MenuItem::with_id(craft_quit::QUIT_MENU_ID, i18n::tr(language, "Quit CADCraft"), true, accel("Cmd+Q"));
let _ = app_menu.append(&quit);
items.insert("cc-about".into(), ("ui.dialog.about".into(), "About CADCraft".into(), about));
items.insert("cc-discord".into(), ("ui.discord".into(), "Join the ArtCraft Discord…".into(), discord));
items.insert("cc-settings".into(), ("options".into(), "Settings...".into(), settings));
@@ -89,7 +85,6 @@ impl NativeMenu {
items,
submenus,
predefined,
quit,
language,
last_refresh: f64::NEG_INFINITY,
recent: app.ui.recent_files.clone(),
@@ -119,9 +114,7 @@ impl NativeMenu {
/// Drain queued menu events into commands (Discord opens externally), rebuild Open Recent, retranslate on a language change and refresh enablement when 300 ms have elapsed.
pub fn poll(&mut self, app: &mut CadApp, ctx: &egui::Context) {
while let Ok(ev) = self.events.try_recv() {
if craft_quit::on_menu_event(ctx, ev.id.as_ref()) {
ctx.request_repaint();
} else if let Some((cmd, _, _)) = self.items.get(ev.id.as_ref()) {
if let Some((cmd, _, _)) = self.items.get(ev.id.as_ref()) {
if cmd == "ui.discord" {
ctx.open_url(egui::OpenUrl::new_tab("https://discord.gg/artcraft"));
} else {
@@ -140,7 +133,6 @@ impl NativeMenu {
for (label, item) in &self.predefined {
item.set_text(i18n::tr(language, label));
}
self.quit.set_text(i18n::tr(language, "Quit CADCraft"));
for (label, submenu) in &self.submenus {
submenu.set_text(i18n::tr_menu(language, label));
}
+5 -5
View File
@@ -252,7 +252,7 @@ mod tests {
app.run("ui.dock", json!({"operation":"move", "panel":"layers", "target":"properties", "zone":"left"})).unwrap();
app.run("ui.dock", json!({"operation":"float", "panel":"properties", "rect":[120,90,340,410]})).unwrap();
ui.docking = app.ui.docking;
ui.docking.set_visible(Panel::ToolSets, false, None, false, permissions).unwrap();
ui.docking.set_visible(Panel::ToolSets, false, None, permissions).unwrap();
ui.show_toolsets = false;
store.save_if_changed(&ui, Instant::now()).unwrap();
let saved: Value = serde_json::from_slice(&fs::read(&path).unwrap()).unwrap();
@@ -263,9 +263,9 @@ mod tests {
assert_eq!(serde_json::to_value(&reloaded.docking).unwrap(), serde_json::to_value(&ui.docking).unwrap());
assert!(!reloaded.show_toolsets);
reveal_panel(&mut reloaded.docking, Panel::ToolSets).unwrap();
let tools = reloaded.docking.layout().location(&Panel::ToolSets).unwrap();
let tools = reloaded.docking.layout.location(&Panel::ToolSets).unwrap();
assert_eq!(serde_json::to_value(&tools.group).unwrap()["column"]["side"], json!("Start"), "{tools:?}");
assert_eq!(reloaded.docking.layout().floating[0].rect, egui::Rect::from_min_size(egui::pos2(120.0, 90.0), egui::vec2(340.0, 410.0)));
assert_eq!(reloaded.docking.layout.floating[0].rect, [120.0, 90.0, 340.0, 410.0]);
fs::remove_dir_all(directory).unwrap();
}
@@ -293,8 +293,8 @@ mod tests {
assert_eq!(ui.toolset_tab, "Modeling");
assert_eq!(ui.history_lines, 4);
assert!(!ui.show_toolsets && ui.show_palettes && !ui.show_toolbar);
assert_eq!(ui.docking.layout(), default_workspace().layout());
assert!(ui.docking.hidden().is_empty(), "{:?}", ui.docking.hidden());
assert_eq!(ui.docking.layout, default_workspace().layout);
assert!(ui.docking.hidden.is_empty(), "{:?}", ui.docking.hidden);
fs::remove_dir_all(directory).unwrap();
}
+3
View File
@@ -2,4 +2,7 @@ allow-unwrap-in-tests = true
allow-expect-in-tests = true
allow-panic-in-tests = true
allow-indexing-slicing-in-tests = true
disallowed-types = [
{ path = "egui::ComboBox", reason = "use craft_ui::ComboBox: egui's combo box menu can't grow back while open (egui#5225)" },
]
cognitive-complexity-threshold = 30
+1 -1
View File
@@ -47,7 +47,7 @@ mod proxy;
mod text;
mod wipeout;
pub use block::{Attrib, AttribModes, AttribProps, Insert, MultilineAttrib, TagKey, mtext_literal};
pub use block::{Attrib, AttribModes, AttribProps, Insert, MultilineAttrib, mtext_literal};
pub use common::{Common, Handle, Lineweight, RawTag, Transparency};
pub use curves::{Arc, Circle, Ellipse, Face3d, Line, LwPolyline, Point, PolyfaceMesh, Polyline3d, RayLine, Solid};
pub use dim::{AssocSnap, DimAssoc, DimBreak, DimKind, DimMarks, Dimension, Inspection, JoggedRadius, Leader, MLeader};
-67
View File
@@ -1,6 +1,3 @@
use std::cmp::Ordering;
use std::collections::BTreeMap;
use super::common::{Common, Lineweight};
use super::text::{MText, Text};
use super::{Color, Deserialize, EntityKind, Mat3, Serialize, Vec2, Vec3};
@@ -145,43 +142,6 @@ impl AttribProps {
}
}
/// An attribute tag as attributes are matched to their definitions and to each other: ASCII
/// letters in either case are the same tag, other characters must be equal. As an ordered map key
/// it finds the match in a logarithmic number of comparisons, where comparing each attribute with
/// each definition costs their product on a block with many of both (#1923). It orders, rather
/// than hashes, so the cost doesn't depend on hash keys a crafted file could predict (the web
/// build's `RandomState`), as in the layer and block name index.
#[derive(Clone, Copy, Debug)]
pub struct TagKey<'a>(pub &'a str);
impl TagKey<'_> {
/// The tag's bytes with ASCII letters in lower case: equal for the tags `eq_ignore_ascii_case`
/// finds equal.
fn folded(&self) -> impl Iterator<Item = u8> + '_ {
self.0.bytes().map(|b| b.to_ascii_lowercase())
}
}
impl PartialEq for TagKey<'_> {
fn eq(&self, other: &Self) -> bool {
self.0.eq_ignore_ascii_case(other.0)
}
}
impl Eq for TagKey<'_> {}
impl Ord for TagKey<'_> {
fn cmp(&self, other: &Self) -> Ordering {
self.folded().cmp(other.folded())
}
}
impl PartialOrd for TagKey<'_> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Insert {
@@ -244,31 +204,4 @@ impl Insert {
.then_before(Mat3::scale(self.scale.x, self.scale.y))
.then_before(Mat3::translate(-base))
}
/// The reference's attributes by tag: of several with one tag (in any ASCII case), the first.
/// Built once, it tells whether the reference carries a definition's tag, and its value, in
/// one lookup instead of a pass over the attributes per definition (#1923).
pub fn attribs_by_tag(&self) -> BTreeMap<TagKey<'_>, &Attrib> {
let mut by_tag = BTreeMap::new();
for a in &self.attribs {
by_tag.entry(TagKey(a.tag.as_str())).or_insert(a);
}
by_tag
}
}
impl crate::Block {
/// The block's attribute definitions by tag: of several with one tag (in any ASCII case), the
/// first in the block's order, the one an attribute of that tag takes its properties from.
/// Built once for all of a reference's attributes, it matches each in one lookup instead of a
/// pass over the block per attribute (#1923).
pub fn attdefs_by_tag(&self) -> BTreeMap<TagKey<'_>, &crate::Entity> {
let mut by_tag = BTreeMap::new();
for e in self.entities.iter() {
if let EntityKind::AttDef(a) = &e.kind {
by_tag.entry(TagKey(a.tag.as_str())).or_insert(e.as_ref());
}
}
by_tag
}
}
+17 -20
View File
@@ -1,10 +1,10 @@
//! Approximate entity bounds (used for extents, zoom and selection pre-filtering).
use std::collections::{BTreeMap, HashMap};
use std::collections::HashMap;
use cadcraft_geom::{Arc, Bounds2, EPS, Polyline, Vec2, bulge_to_arc};
use crate::{Drawing, Entity, EntityKind, LwPolyline, Prim, TagKey};
use crate::{Drawing, Entity, EntityKind, LwPolyline, Prim};
/// Nested block references deeper than this are ignored (cyclic or hostile files).
pub const MAX_BLOCK_DEPTH: usize = 16;
@@ -283,33 +283,33 @@ fn layer_counts(d: &Drawing, layer: &str, off_counts: bool) -> bool {
}
/// The layer an insert's attribute draws on, as the renderer takes it: its own, else its
/// definition's, from the block's definitions by tag `defs` (layer "0" being the insert's).
fn attrib_layer<'a>(defs: Option<&BTreeMap<TagKey<'a>, &'a Entity>>, a: &'a crate::Attrib) -> &'a str {
a.props.layer.as_deref().unwrap_or_else(|| defs.and_then(|defs| defs.get(&TagKey(&a.tag))).map_or("0", |be| be.common.layer.as_str()))
/// definition's (layer "0" being the insert's).
fn attrib_layer<'a>(d: &'a Drawing, ins: &crate::Insert, a: &'a crate::Attrib) -> &'a str {
a.props.layer.as_deref().unwrap_or_else(|| {
d.block(&ins.block)
.and_then(|blk| blk.entities.iter().find(|be| matches!(&be.kind, EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(&a.tag))))
.map_or("0", |be| be.common.layer.as_str())
})
}
/// The bounds of a block's contents, in block coordinates: its geometry, which every reference to
/// the block shows, and the value of each constant attribute definition ATTMODE shows, by tag, which
/// only a block reference draws (a dimension's block does not), and only when the reference
/// carries no attribute of that tag. They are kept apart so that the one cache serves every
/// reference, whichever asks first. Also the block's attribute definitions by tag, for the layer
/// of an attribute that has none of its own.
/// reference, whichever asks first.
struct Contents<'a> {
geometry: Bounds2,
constants: Vec<(&'a str, Bounds2)>,
defs: BTreeMap<TagKey<'a>, &'a Entity>,
}
impl Contents<'_> {
/// What reference `ins` shows of the block: its geometry and the constant values `ins` has
/// no attribute for (that attribute is drawn instead, and counted with the attributes).
fn in_reference(&self, ins: &crate::Insert) -> Bounds2 {
if self.constants.is_empty() {
return self.geometry;
}
// The reference's tags are gathered once, not scanned again for each constant (#1923).
let carried = ins.attribs_by_tag();
self.constants.iter().filter(|(tag, _)| !carried.contains_key(&TagKey(tag))).fold(self.geometry, |b, (_, c)| b.union(c))
self.constants
.iter()
.filter(|(tag, _)| !ins.attribs.iter().any(|r| r.tag.eq_ignore_ascii_case(tag)))
.fold(self.geometry, |b, (_, c)| b.union(c))
}
}
@@ -323,7 +323,7 @@ fn contents<'a, 'm>(
) -> Option<&'m Contents<'a>> {
let key = (blk.name.as_str(), depth);
if !blocks.contains_key(&key) {
let mut c = Contents { geometry: Bounds2::EMPTY, constants: Vec::new(), defs: blk.attdefs_by_tag() };
let mut c = Contents { geometry: Bounds2::EMPTY, constants: Vec::new() };
// ATTMODE, as the renderer applies it to a constant value: 0 shows none, 1 the visible
// ones, 2 all of them.
let attmode = d.header.i64("ATTMODE", 1);
@@ -487,12 +487,9 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<
// one draws nothing, so it contributes nothing: ZOOM Extents must not fly off to its
// insertion point. Attributes below still count.
let mut b = Bounds2::EMPTY;
let mut defs = None;
if let Some(blk) = d.block(&ins.block) {
let m = ins.transform(blk.base.xy());
let c = contents(d, blk, depth, blocks, off_counts);
defs = c.map(|c| &c.defs);
let inner = c.map_or(Bounds2::EMPTY, |c| c.in_reference(ins));
let inner = contents(d, blk, depth, blocks, off_counts).map_or(Bounds2::EMPTY, |c| c.in_reference(ins));
b = if inner.is_empty() { Bounds2::EMPTY } else { Bounds2::from_points(inner.corners().map(|c| m.apply(c))) };
// XCLIP: the reference app takes the boundary's box, also where it reaches past the
// block or misses it (an inverted clip can show anything, so it keeps the block's).
@@ -514,7 +511,7 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<
}
}
for a in &ins.attribs {
if !a.invisible && layer_counts(d, attrib_layer(defs, a), off_counts) {
if !a.invisible && layer_counts(d, attrib_layer(d, ins, a), off_counts) {
b = b.union(&match a.multiline_text() {
Some(m) => mtext_box(&m),
None => text_box(&a.text, a.text.value.chars().count()),
+7 -15
View File
@@ -14,7 +14,6 @@ mod format;
mod gdt;
mod header;
pub mod library;
mod names;
mod plotstyle;
mod plotter;
mod raster;
@@ -37,7 +36,6 @@ pub use extents::{
pub use format::Format;
pub use gdt::*;
pub use header::{HVal, Header};
pub use names::{Named, NamedList, NamedMap};
pub use plotstyle::*;
pub use plotter::*;
pub use raster::{Raster, Rasters};
@@ -103,8 +101,7 @@ pub struct Drawing {
pub header: Header,
/// File data CADCraft does not model, written back on save.
pub foreign: std::sync::Arc<foreign::Foreign>,
/// Layers in table order; [`Drawing::layer`] looks them up by name.
pub layers: NamedList<Layer>,
pub layers: Vec<Layer>,
pub linetypes: Vec<Linetype>,
pub text_styles: Vec<TextStyle>,
pub dim_styles: Vec<DimStyle>,
@@ -112,8 +109,7 @@ pub struct Drawing {
pub table_styles: Vec<TableStyle>,
/// Multiline styles (MLSTYLE); STANDARD is always there.
pub mline_styles: Vec<MLineStyle>,
/// Block definitions by name; [`Drawing::block`] looks them up.
pub blocks: NamedMap<std::sync::Arc<Block>>,
pub blocks: BTreeMap<String, std::sync::Arc<Block>>,
pub model: EntityStore,
/// Model layout's page setup, or the default extents-to-fit setup for a new drawing.
pub model_page: Option<PageSetup>,
@@ -199,7 +195,7 @@ impl Drawing {
Drawing {
header: Header::default(),
foreign: std::sync::Arc::default(),
layers: vec![Layer::default(), Layer { name: "Defpoints".into(), plot: false, ..Layer::default() }].into(),
layers: vec![Layer::default(), Layer { name: "Defpoints".into(), plot: false, ..Layer::default() }],
linetypes: vec![
Linetype { name: "ByBlock".into(), description: String::new(), pattern: Vec::new() },
Linetype { name: "ByLayer".into(), description: String::new(), pattern: Vec::new() },
@@ -210,7 +206,7 @@ impl Drawing {
mleader_styles: vec![MLeaderStyle::default()],
table_styles: vec![TableStyle::default()],
mline_styles: vec![MLineStyle::default()],
blocks: NamedMap::default(),
blocks: BTreeMap::new(),
model: EntityStore::new(),
model_page: None,
layouts: vec![Layout::new("Layout1", 1), Layout::new("Layout2", 2)],
@@ -317,14 +313,11 @@ impl Drawing {
}
}
/// The first layer named `name`, without case.
pub fn layer(&self, name: &str) -> Option<&Layer> {
self.layers.by_name(name)
self.layers.iter().find(|l| l.name.eq_ignore_ascii_case(name))
}
/// The first layer named `name`, without case, to change.
pub fn layer_mut(&mut self, name: &str) -> Option<&mut Layer> {
let i = self.layers.position_by_name(name)?;
self.layers.get_mut(i)
self.layers.iter_mut().find(|l| l.name.eq_ignore_ascii_case(name))
}
pub fn linetype(&self, name: &str) -> Option<&Linetype> {
self.linetypes.iter().find(|l| l.name.eq_ignore_ascii_case(name))
@@ -401,9 +394,8 @@ impl Drawing {
}
}
}
/// The block named exactly `name`, else the first by name order named `name` without case.
pub fn block(&self, name: &str) -> Option<&std::sync::Arc<Block>> {
self.blocks.by_name(name)
self.blocks.get(name).or_else(|| self.blocks.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v))
}
pub fn layout(&self, name: &str) -> Option<&Layout> {
self.layouts.iter().find(|l| l.name.eq_ignore_ascii_case(name))
-503
View File
@@ -1,503 +0,0 @@
//! The layer and block tables, whose names are looked up without case through an index instead of a
//! scan once a table is large and looked up often.
//!
//! [`Drawing::layer`](crate::Drawing::layer) and [`Drawing::block`](crate::Drawing::block) run for
//! every entity while a drawing is read, measured and drawn. Scanning the table on each made a file
//! of N layers, or of N blocks and N references to blocks it does not have, cost N² name
//! comparisons: tens of seconds to open at a few tens of thousands (#1924, F-04).
//!
//! Each table keeps an index from a name with its ASCII letters lower-cased to the table's first
//! entry of that name, so a lookup returns what a scan in table order returns. The index is ordered
//! by those bytes, not hashed: a lookup costs a logarithmic number of name comparisons whatever
//! the names are, also where a file could predict a hash's keys (the web build's `RandomState`).
//! Every change to a table goes through `DerefMut`, which drops the index, so it can never be
//! stale. The index is built only once a table has been scanned [`SCANS_BEFORE_INDEX`] times since
//! it last changed: a table changed between every few hundred lookups costs at most about 2.5 times
//! what scanning it always did, and one looked up many times in between is indexed once.
use std::collections::{BTreeMap, btree_map};
use std::ops::{Deref, DerefMut};
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Arc, OnceLock};
/// Tables with fewer entries than this are always scanned: a search of the index costs about what a
/// scan of 100 names does (measured), so a smaller table gains nothing from one.
const MIN_INDEXED: usize = 128;
/// Lookups that scan a table after it changed before its index is built. A build costs about 100
/// to 350 scans (measured on tables of 100 to 40 000 names), so a table changed after every few
/// hundred lookups costs at most about 2.5 times what scanning it always did.
const SCANS_BEFORE_INDEX: u32 = 256;
/// From a name with its ASCII letters lower-cased to the first entry, in table order, of that name.
struct Index<V>(BTreeMap<Box<[u8]>, V>);
impl<V> Index<V> {
fn build<'a>(entries: impl Iterator<Item = (&'a str, V)>) -> Self {
let mut map = BTreeMap::new();
for (name, v) in entries {
map.entry(name.to_ascii_lowercase().into_bytes().into_boxed_slice()).or_insert(v);
}
Index(map)
}
/// The first entry named `name`, without case.
fn get(&self, name: &str) -> Option<&V> {
with_folded(name, |folded| self.0.get(folded))
}
}
/// `f` of the bytes of `name` with its ASCII letters lower-cased, which are equal for the names
/// `eq_ignore_ascii_case` finds equal. A short name is folded on the stack.
fn with_folded<R>(name: &str, f: impl FnOnce(&[u8]) -> R) -> R {
let mut buf = [0u8; 64];
match buf.get_mut(..name.len()) {
Some(short) => {
short.copy_from_slice(name.as_bytes());
short.make_ascii_lowercase();
f(short)
}
None => f(name.to_ascii_lowercase().as_bytes()),
}
}
/// A table's index: built on demand, shared by copies of the unchanged table (an undo snapshot),
/// dropped when the table changes.
struct Lazy<V> {
index: OnceLock<Arc<Index<V>>>,
/// Lookups that scanned the table since it last changed.
scans: AtomicU32,
}
impl<V> Lazy<V> {
/// The index of a table of `len` entries, built with `build` once the table has been scanned
/// often enough since it changed; `None` while it is to be scanned.
fn get(&self, len: usize, build: impl FnOnce() -> Index<V>) -> Option<&Index<V>> {
if let Some(ix) = self.index.get() {
return Some(ix);
}
if len < MIN_INDEXED || self.scans.fetch_add(1, Ordering::Relaxed) < SCANS_BEFORE_INDEX {
return None;
}
Some(self.index.get_or_init(|| Arc::new(build())))
}
/// Forget the index: the table may change.
fn clear(&mut self) {
self.index = OnceLock::new();
*self.scans.get_mut() = 0;
}
}
impl<V> Default for Lazy<V> {
fn default() -> Self {
Lazy { index: OnceLock::new(), scans: AtomicU32::new(0) }
}
}
impl<V> Clone for Lazy<V> {
fn clone(&self) -> Self {
Lazy { index: self.index.clone(), scans: AtomicU32::new(0) }
}
}
/// An entry of a [`NamedList`]: what it is looked up by.
pub trait Named {
fn name(&self) -> &str;
}
impl Named for crate::Layer {
fn name(&self) -> &str {
&self.name
}
}
/// A list of named entries in their own order (the drawing's layers). It reads and changes as a
/// `Vec`; [`NamedList::by_name`] finds the first entry of a name without case.
pub struct NamedList<T> {
list: Vec<T>,
index: Lazy<usize>,
}
impl<T: Named> NamedList<T> {
/// The position of the first entry named `name`, without case.
pub fn position_by_name(&self, name: &str) -> Option<usize> {
match self.index.get(self.list.len(), || Index::build(self.list.iter().enumerate().map(|(i, t)| (t.name(), i)))) {
Some(ix) => ix.get(name).copied(),
None => self.list.iter().position(|t| t.name().eq_ignore_ascii_case(name)),
}
}
/// The first entry named `name`, without case.
pub fn by_name(&self, name: &str) -> Option<&T> {
self.position_by_name(name).and_then(|i| self.list.get(i))
}
}
impl<T> Deref for NamedList<T> {
type Target = Vec<T>;
fn deref(&self) -> &Vec<T> {
&self.list
}
}
impl<T> DerefMut for NamedList<T> {
fn deref_mut(&mut self) -> &mut Vec<T> {
self.index.clear();
&mut self.list
}
}
impl<T> Default for NamedList<T> {
fn default() -> Self {
Vec::new().into()
}
}
impl<T: Clone> Clone for NamedList<T> {
fn clone(&self) -> Self {
NamedList { list: self.list.clone(), index: self.index.clone() }
}
}
impl<T: std::fmt::Debug> std::fmt::Debug for NamedList<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.list.fmt(f)
}
}
impl<T: PartialEq> PartialEq for NamedList<T> {
fn eq(&self, other: &Self) -> bool {
self.list == other.list
}
}
impl<T> From<Vec<T>> for NamedList<T> {
fn from(list: Vec<T>) -> Self {
NamedList { list, index: Lazy::default() }
}
}
impl<T> From<NamedList<T>> for Vec<T> {
fn from(l: NamedList<T>) -> Self {
l.list
}
}
impl<T: serde::Serialize> serde::Serialize for NamedList<T> {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
self.list.serialize(s)
}
}
impl<T> FromIterator<T> for NamedList<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
Vec::from_iter(iter).into()
}
}
impl<T> IntoIterator for NamedList<T> {
type Item = T;
type IntoIter = std::vec::IntoIter<T>;
fn into_iter(self) -> Self::IntoIter {
self.list.into_iter()
}
}
impl<'a, T> IntoIterator for &'a NamedList<T> {
type Item = &'a T;
type IntoIter = std::slice::Iter<'a, T>;
fn into_iter(self) -> Self::IntoIter {
self.list.iter()
}
}
impl<'a, T> IntoIterator for &'a mut NamedList<T> {
type Item = &'a mut T;
type IntoIter = std::slice::IterMut<'a, T>;
fn into_iter(self) -> Self::IntoIter {
self.deref_mut().iter_mut()
}
}
/// Entries by name, in name order (the drawing's block definitions). It reads and changes as a
/// `BTreeMap`; [`NamedMap::by_name`] finds an entry by its exact name, else the first in name
/// order whose name matches without case.
pub struct NamedMap<V> {
map: BTreeMap<String, V>,
index: Lazy<Box<str>>,
}
impl<V> NamedMap<V> {
/// The entry named exactly `name`, else the first in name order named `name` without case.
pub fn by_name(&self, name: &str) -> Option<&V> {
if let Some(v) = self.map.get(name) {
return Some(v);
}
match self.index.get(self.map.len(), || Index::build(self.map.keys().map(|k| (k.as_str(), Box::from(k.as_str()))))) {
Some(ix) => ix.get(name).and_then(|k| self.map.get(&**k)),
None => self.map.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v),
}
}
}
impl<V> Deref for NamedMap<V> {
type Target = BTreeMap<String, V>;
fn deref(&self) -> &BTreeMap<String, V> {
&self.map
}
}
impl<V> DerefMut for NamedMap<V> {
fn deref_mut(&mut self) -> &mut BTreeMap<String, V> {
self.index.clear();
&mut self.map
}
}
impl<V> Default for NamedMap<V> {
fn default() -> Self {
BTreeMap::new().into()
}
}
impl<V: Clone> Clone for NamedMap<V> {
fn clone(&self) -> Self {
NamedMap { map: self.map.clone(), index: self.index.clone() }
}
}
impl<V: std::fmt::Debug> std::fmt::Debug for NamedMap<V> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.map.fmt(f)
}
}
impl<V: PartialEq> PartialEq for NamedMap<V> {
fn eq(&self, other: &Self) -> bool {
self.map == other.map
}
}
impl<V> From<BTreeMap<String, V>> for NamedMap<V> {
fn from(map: BTreeMap<String, V>) -> Self {
NamedMap { map, index: Lazy::default() }
}
}
impl<V> FromIterator<(String, V)> for NamedMap<V> {
fn from_iter<I: IntoIterator<Item = (String, V)>>(iter: I) -> Self {
BTreeMap::from_iter(iter).into()
}
}
impl<V> IntoIterator for NamedMap<V> {
type Item = (String, V);
type IntoIter = btree_map::IntoIter<String, V>;
fn into_iter(self) -> Self::IntoIter {
self.map.into_iter()
}
}
impl<'a, V> IntoIterator for &'a NamedMap<V> {
type Item = (&'a String, &'a V);
type IntoIter = btree_map::Iter<'a, String, V>;
fn into_iter(self) -> Self::IntoIter {
self.map.iter()
}
}
impl<'a, V> IntoIterator for &'a mut NamedMap<V> {
type Item = (&'a String, &'a mut V);
type IntoIter = btree_map::IterMut<'a, String, V>;
fn into_iter(self) -> Self::IntoIter {
self.deref_mut().iter_mut()
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use super::MIN_INDEXED;
use crate::{Block, Drawing, Layer};
/// Names to look up: each given name as it is, upper-cased, lower-cased and with a character
/// added (a miss).
fn probes<'a>(names: impl Iterator<Item = &'a str>) -> Vec<String> {
names.flat_map(|n| [n.to_string(), n.to_ascii_uppercase(), n.to_ascii_lowercase(), format!("{n}?")]).collect()
}
fn layers_indexed(d: &Drawing) -> bool {
d.layers.index.index.get().is_some()
}
fn blocks_indexed(d: &Drawing) -> bool {
d.blocks.index.index.get().is_some()
}
/// `layer_mut` finds the first layer of a name and drops the index, as the table may change
/// through it. Then every layer lookup finds what a scan in table order finds (the first of a
/// name without case), and a large table looked up this often is left indexed.
fn check_layers(d: &mut Drawing, extra: &[&str]) {
let p = extra.first().copied().unwrap_or("L1");
let want = d.layers.iter().position(|l| l.name.eq_ignore_ascii_case(p)).and_then(|i| d.layers.get(i)).map(std::ptr::from_ref);
assert_eq!(d.layer_mut(p).map(|l| std::ptr::from_ref(&*l)), want, "{p}");
assert!(want.is_none() || !layers_indexed(d));
let names: Vec<String> = d.layers.iter().map(|l| l.name.clone()).collect();
for p in probes(names.iter().map(String::as_str).chain(extra.iter().copied())) {
let want = d.layers.iter().position(|l| l.name.eq_ignore_ascii_case(&p));
assert_eq!(d.layers.position_by_name(&p), want, "{p}");
let at = want.and_then(|i| d.layers.get(i)).map(std::ptr::from_ref);
assert_eq!(d.layer(&p).map(std::ptr::from_ref), at, "{p}");
}
assert_eq!(layers_indexed(d), d.layers.len() >= MIN_INDEXED);
}
/// Every block lookup finds what `Drawing::block` always found: the block of that exact name,
/// else the first in name order of that name without case. Only names that miss an exact name
/// count towards building the index, so the names are looked up twice.
fn check_blocks(d: &Drawing, extra: &[&str]) {
let names: Vec<String> = d.blocks.keys().cloned().collect();
for p in probes(names.iter().chain(&names).map(String::as_str).chain(extra.iter().copied())) {
let want = d.blocks.get(&p).or_else(|| d.blocks.iter().find(|(k, _)| k.eq_ignore_ascii_case(&p)).map(|(_, v)| v));
assert_eq!(d.block(&p).map(std::ptr::from_ref), want.map(std::ptr::from_ref), "{p}");
}
assert_eq!(blocks_indexed(d), d.blocks.len() >= MIN_INDEXED);
}
/// The index answers by itself, with no scan to fall back on: every name finds the first entry
/// of its name without case, also names that differ only after a long shared prefix, names
/// that fill the stack buffer or are longer, and names with non-ASCII letters (which keep their
/// case). Names are compared, not hashed, so no two names can share a slot.
#[test]
fn the_index_alone_finds_the_first_entry_of_every_name() {
let long = "x".repeat(100);
let names: Vec<String> = vec![
"Door".into(),
"DOOR".into(),
"door2".into(),
format!("{long}A"),
format!("{long}a"),
format!("{long}B"),
format!("{}b", "P".repeat(63)),
format!("{}B", "p".repeat(63)),
"Ärea".into(),
"ärea".into(),
"ÄREA".into(),
String::new(),
];
let ix = super::Index::build(names.iter().enumerate().map(|(i, n)| (n.as_str(), i)));
for p in names.iter().flat_map(|n| [n.clone(), n.to_ascii_uppercase(), n.to_ascii_lowercase(), format!("{n}?")]) {
let want = names.iter().position(|n| n.eq_ignore_ascii_case(&p));
assert_eq!(ix.get(&p).copied(), want, "{p:?}");
}
assert_eq!(ix.get(&format!("{long}a")), Some(&3));
assert_eq!(ix.get("ärea"), Some(&9));
}
#[test]
fn layer_lookups_find_the_first_of_a_name_through_every_change() {
let mut d = Drawing::new_imperial();
d.layers = (0..200).map(|i| Layer::new(&format!("L{i}"))).chain([Layer::new("l5"), Layer::new("Doors")]).collect();
check_layers(&mut d, &["l5", "missing"]);
// Renamed through layer_mut (RENAME).
d.layer_mut("l7").unwrap().name = "Seven".into();
assert!(!layers_indexed(&d));
assert!(d.layer("L7").is_none());
check_layers(&mut d, &["SEVEN", "L7"]);
// Added (LAYER New, or a file's later record of a name it already has).
d.layers.push(Layer::new("SEVEN"));
assert!(!layers_indexed(&d));
check_layers(&mut d, &["seven"]);
// Removed (PURGE, LAYDEL): the later `l5` becomes the first of that name.
d.layers.retain(|l| l.name != "L5");
assert!(!layers_indexed(&d));
assert_eq!(d.layer("L5").map(|l| l.name.as_str()), Some("l5"));
check_layers(&mut d, &["L5"]);
// Inserted before an earlier layer of the same name.
d.layers.insert(0, Layer::new("l9"));
assert!(!layers_indexed(&d));
assert_eq!(d.layer("L9").map(|l| l.name.as_str()), Some("l9"));
check_layers(&mut d, &["L9"]);
// Changed by position, and by a loop over all of them.
d.layers[3].name = "Third".into();
assert!(!layers_indexed(&d));
check_layers(&mut d, &["third"]);
for l in &mut d.layers {
l.name.make_ascii_uppercase();
}
assert!(!layers_indexed(&d));
check_layers(&mut d, &["doors"]);
// Undo: a snapshot keeps the table it was taken with, and its index.
let names = |d: &Drawing| d.layers.iter().map(|l| l.name.clone()).collect::<Vec<_>>();
assert!(layers_indexed(&d));
let (snap, before) = (d.clone(), names(&d));
d.layers.clear();
d.layers.push(Layer::new("Only"));
check_layers(&mut d, &["only", "L1"]);
d = snap;
assert!(layers_indexed(&d));
assert_eq!(names(&d), before);
check_layers(&mut d, &["THIRD"]);
// The whole table replaced (LAYERP, LAYUNISO).
d.layers = vec![Layer::new("0"), Layer::new("A"), Layer::new("a")].into();
check_layers(&mut d, &["a"]);
}
#[test]
fn block_lookups_find_an_exact_name_else_the_first_without_case_through_every_change() {
let block = |name: &str| Arc::new(Block::new(name));
let mut d = Drawing::new_imperial();
for name in (0..150).map(|i| format!("B{i}")).chain(["Door", "DOOR", "door"].map(String::from)) {
d.blocks.insert(name.clone(), block(&name));
}
check_blocks(&d, &["dOOR", "missing"]);
// An exact name wins; otherwise the first in name order ("DOOR" < "Door" < "door").
assert_eq!(d.block("door").map(|b| b.name.as_str()), Some("door"));
assert_eq!(d.block("dOOR").map(|b| b.name.as_str()), Some("DOOR"));
// Removed (PURGE, a definition replaced under another name).
d.blocks.remove("DOOR");
assert!(!blocks_indexed(&d));
assert_eq!(d.block("dOOR").map(|b| b.name.as_str()), Some("Door"));
check_blocks(&d, &["dOOR"]);
// Added before the first of that name.
d.blocks.insert("DoOr".into(), block("DoOr"));
assert!(!blocks_indexed(&d));
assert_eq!(d.block("dOOR").map(|b| b.name.as_str()), Some("DoOr"));
check_blocks(&d, &["dOOR"]);
// Renamed (RENAME takes the definition out and puts it back under the new name).
let b1 = d.blocks.remove("B1").unwrap();
d.blocks.insert("Renamed".into(), b1);
assert!(d.block("b1").is_none() && d.block("RENAMED").is_some());
check_blocks(&d, &["b1", "RENAMED"]);
// Redefined in place, and changed through get_mut: the names stay.
d.blocks.insert("Door".into(), block("Door"));
assert!(!blocks_indexed(&d));
check_blocks(&d, &["DOOR"]);
Arc::make_mut(d.blocks.get_mut("B2").unwrap()).description = "changed".into();
assert!(!blocks_indexed(&d));
check_blocks(&d, &["b2"]);
// Many removed at once.
d.blocks.retain(|k, _| !k.starts_with("B9"));
assert!(!blocks_indexed(&d));
check_blocks(&d, &["b9", "b90"]);
// A loop over all of them.
for (_, b) in &mut d.blocks {
Arc::make_mut(b).description = "looped".into();
}
assert!(!blocks_indexed(&d));
check_blocks(&d, &["b3"]);
// Undo: a snapshot keeps the table it was taken with, and its index.
let snap = d.clone();
d.blocks.clear();
d.blocks.insert("Only".into(), block("Only"));
check_blocks(&d, &["only", "door"]);
d = snap;
assert!(blocks_indexed(&d));
check_blocks(&d, &["DOOR", "only"]);
}
}
+2 -2
View File
@@ -1018,8 +1018,8 @@ impl LayerState {
pub const ALL: u32 = 2047;
/// A state of every property of `layers`, with `current` the layer restoring makes current.
pub fn new(name: impl Into<String>, layers: impl Into<Vec<Layer>>, current: impl Into<String>) -> Self {
LayerState { name: name.into(), layers: layers.into(), current: current.into(), ..LayerState::default() }
pub fn new(name: impl Into<String>, layers: Vec<Layer>, current: impl Into<String>) -> Self {
LayerState { name: name.into(), layers, current: current.into(), ..LayerState::default() }
}
}
-98
View File
@@ -890,101 +890,3 @@ fn constant_values_count_in_extents_as_attmode_shows_them() {
assert!(top(1, true) < 40.0);
assert!(top(2, true) > 40.0, "ATTMODE 2 shows an invisible one");
}
#[test]
fn an_attribute_lies_on_the_layer_of_the_first_definition_of_its_tag() {
// Two definitions of one tag, in different case, on a frozen layer and on layer 0: an
// attribute without a layer of its own (in a third case) lies on the first one's.
let top = |defs: [(&str, &str); 2]| {
let mut d = Drawing::new_imperial();
let mut frozen = Layer::new("AFRZ");
frozen.frozen = true;
d.layers.push(frozen);
let mut blk = Block::new("B");
blk.entities.push(on_layer("0", line((0.0, 0.0), (1.0, 1.0)), 1));
for (h, (layer, tag)) in (2..).zip(defs) {
blk.entities.push(on_layer(layer, EntityKind::AttDef(plain_attrib(tag)), h));
}
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
let EntityKind::Insert(mut ins) = plain_insert("B") else { panic!("an insert") };
let mut a = plain_attrib("Tag");
a.text.insert = Vec3::new(0.0, 500.0, 0.0);
ins.attribs.push(a);
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
extents_pair(&d).1.y
};
assert!(top([("AFRZ", "TAG"), ("0", "tag")]) < 100.0, "on the first definition's frozen layer");
assert!(top([("0", "tag"), ("AFRZ", "TAG")]) > 400.0, "on the first definition's layer 0");
}
#[test]
fn constant_definitions_of_one_tag_all_count_unless_the_reference_carries_the_tag() {
// Two constant definitions of one tag, in different case: a reference draws both values,
// unless it carries an attribute of that tag (in a third case), which stands for both.
let max = |attribs: Vec<Attrib>| {
let mut d = Drawing::new_imperial();
let mut blk = Block::new("B");
blk.entities.push(Entity::new(Handle(1), line((0.0, 0.0), (1.0, 1.0))));
for (h, tag, at) in [(2, "C", Vec3::new(0.0, 5000.0, 0.0)), (3, "c", Vec3::new(7000.0, 0.0, 0.0))] {
let mut a = plain_attrib(tag);
a.text.insert = at;
a.constant = true;
blk.entities.push(Entity::new(Handle(h), EntityKind::AttDef(a)));
}
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
let EntityKind::Insert(mut ins) = plain_insert("B") else { panic!("an insert") };
ins.attribs = attribs;
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
extents_pair(&d).1
};
for shown in [max(vec![]), max(vec![plain_attrib("D")])] {
assert!(shown.x > 6000.0 && shown.y > 4000.0, "both values count: {shown:?}");
}
let carried = max(vec![plain_attrib("D"), plain_attrib("Cc"), plain_attrib("C")]);
assert!(carried.x < 100.0 && carried.y < 100.0, "neither value counts: {carried:?}");
}
#[test]
fn many_attributes_and_definitions_are_matched_without_comparing_every_pair() {
// #1923: one reference with N attributes (none with a layer of its own) of a block with N
// constant definitions, the tags N long ones alike up to their last characters, no attribute's
// a definition's. Comparing each attribute with each definition, for its layer and for which
// constant values the reference carries, cost N x N comparisons of whole tags (many seconds
// here); one lookup per attribute or definition costs milliseconds.
const N: usize = 4000;
let tag = |kind: char, i: usize| format!("{}{kind}{i:05}", "T".repeat(1000));
let mut d = Drawing::new_imperial();
let mut blk = Block::new("B");
blk.entities.push(Entity::new(Handle(1), line((0.0, 0.0), (1.0, 1.0))));
for (h, i) in (2..).zip(0..N) {
let mut a = plain_attrib(&tag('D', i));
a.constant = true;
blk.entities.push(Entity::new(Handle(h), EntityKind::AttDef(a)));
}
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
let EntityKind::Insert(mut ins) = plain_insert("B") else { panic!("an insert") };
ins.attribs = (0..N).map(|i| plain_attrib(&tag('A', i))).collect();
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
let t = std::time::Instant::now();
assert!(!d.extents(&Space::Model).is_empty());
assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed());
}
/// Looking a layer or a block up by name does not scan the table: a file of N layers, or of N
/// blocks and N references to blocks it does not have, opened in N² name comparisons (#1924).
#[test]
fn layer_and_block_lookups_by_name_cost_about_the_same_for_any_table_size() {
const N: usize = 60_000;
let mut d = Drawing::new_imperial();
d.layers = (0..N).map(|i| Layer::new(&format!("L{i}"))).collect();
for i in 0..N {
let name = format!("B{i}");
d.blocks.insert(name.clone(), std::sync::Arc::new(Block::new(&name)));
}
let started = std::time::Instant::now();
for i in 0..N {
assert!(d.layer(&format!("l{i}")).is_some() && d.layer(&format!("M{i}")).is_none());
assert!(d.block(&format!("b{i}")).is_some() && d.block(&format!("Z{i}")).is_none());
}
assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed());
}
+1 -7
View File
@@ -1,5 +1,5 @@
//! Dimensions and leaders: DIMLINEAR, DIMALIGNED, DIMRADIUS, DIMDIAMETER, DIMANGULAR, DIMARC,
//! DIMORDINATE, DIMCONTINUE, DIMBASELINE, QDIM, DIM (smart), MLEADER, LEADER, QLEADER, DIMOVERRIDE,
//! DIMORDINATE, DIMCONTINUE, DIMBASELINE, QDIM, DIM (smart), MLEADER, LEADER, DIMOVERRIDE,
//! DIMREASSOCIATE / DIMDISASSOCIATE, DIMTEDIT, DIMSPACE; DIMEDIT, DIMJOGGED, DIMJOGLINE,
//! DIMBREAK and DIMINSPECT in `annotate_dimedit.rs`.
@@ -19,7 +19,6 @@ mod edit;
mod leader;
mod linear;
mod mleader;
mod qleader;
mod radial;
use angular::{AngularM, ArcLenM, run_angular, run_arclen};
@@ -28,7 +27,6 @@ use common::{DimText, add_dim, assoc_enabled, circle_of, dim, pick_at};
use edit::{DimSpaceM, OverrideM, dims_of, run_dimspace, run_dimtedit, run_disassociate, run_override, run_reassociate, run_tedit, run_update};
use linear::{ChainM, LinearM, MAX_CHAIN, OrdinateM, run_aligned, run_baseline, run_continue, run_linear, run_ordinate};
use mleader::{MLeaderM, run_leader, run_mleader};
use qleader::{QLeaderM, run_qleader};
use radial::{RadialM, run_diameter, run_radius};
pub fn specs() -> Vec<CommandSpec> {
@@ -95,10 +93,6 @@ pub fn specs() -> Vec<CommandSpec> {
.alias(&["lead"])
.params("{points: [[x,y]...], text?}")
.interactive(|_| Ok(Box::new(leader::LeaderM::default()))),
CommandSpec::new("qleader", "Quick Leader", run_qleader)
.alias(&["le"])
.params("{points: [[x,y], [x,y], [x,y]?] (2 or 3), width?: text width (default 0), text?: lines split at \\n}")
.interactive(|_| Ok(Box::new(QLeaderM::default()))),
CommandSpec::new("dimstyle.update", "Update", run_update)
.menu(&["Dimension", "Update"])
.params("{handles?}")
+3 -25
View File
@@ -42,13 +42,8 @@ pub(super) struct LeaderM {
}
/// What follows the leader.
pub(super) enum Annotation {
enum Annotation {
Text(Vec<String>),
/// QLEADER's text: its lines and its width.
Quick {
lines: Vec<String>,
width: f64,
},
/// A copy of a text or multiline text: its contents, height, width and style.
Copy(MText),
None,
@@ -268,13 +263,13 @@ pub(super) fn json_leader(s: &mut Session, pts: &[Vec2], text: Option<&str>) ->
}
/// Draw the leader through `pts` and its annotation, as AutoCAD 2024 places them; their handles.
pub(super) fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: bool, ann: Annotation) -> Result<Vec<Handle>> {
fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: bool, ann: Annotation) -> Result<Vec<Handle>> {
let (Some(&end), Some(&before)) = (pts.last(), pts.len().checked_sub(2).and_then(|i| pts.get(i))) else { return Ok(Vec::new()) };
let z = sizes(s);
// The side the leader runs to: right unless its last segment runs left.
let dir = if end.x < before.x { -1.0 } else { 1.0 };
let mut vertices = pts.to_vec();
if let Annotation::Text(_) | Annotation::Quick { .. } | Annotation::Copy(_) = ann {
if let Annotation::Text(_) | Annotation::Copy(_) = ann {
let d = end - before;
// A copied text is centred on its line, and with DIMTAD on that line is above the leader:
// the leader ends half the text height lower.
@@ -315,23 +310,6 @@ pub(super) fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: boo
columns: None,
}))?)
}
Annotation::Quick { lines, width } => {
// The middle of the first line level with the end on the right, of the last line on
// the left, whatever DIMTAD.
let (attach, lift) = if dir > 0.0 { (1, z.text / 2.0) } else { (9, -z.text / 2.0) };
Some(s.add_entity(EntityKind::MText(MText {
insert: v3(end + Vec2::new(dir * z.gap, lift)),
height: z.text,
width,
attach,
rotation: 0.0,
style: z.text_style,
contents: lines.join("\\P"),
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
}))?)
}
Annotation::Copy(m) => {
let lift = if z.above { z.gap } else { 0.0 };
let attach = if dir > 0.0 { 4 } else { 6 };
-121
View File
@@ -1,121 +0,0 @@
//! QLEADER at the command line, as AutoCAD 2024 runs it with its default settings (accoreconsole,
//! synthetic drawings): up to three points, a text width, then lines of text.
//!
//! The leader is LEADER's, with an arrow and a hook line DIMASZ long when its last segment is more
//! than 15° off horizontal and text follows. The multiline text sits DIMGAP past the leader's end,
//! as wide as the width given: with the middle of its first line level with the end when the
//! leader runs right, and of its last line when it runs left, whatever DIMTAD. Enter at the first
//! line of text leaves the leader without text. The Settings dialog isn't available yet.
use serde_json::{Value, json};
use super::leader::{Annotation, add_leader};
use super::{Accept, Input, Interactive, Prompt, Result, Session, Step, Vec2, bad, points_param, str_param};
use crate::cmd::size_param;
/// QLEADER's default number of leader points.
const MAX_POINTS: usize = 3;
#[derive(Clone, Copy, Default, PartialEq)]
enum Ask {
#[default]
Points,
Width,
FirstLine,
NextLine,
}
#[derive(Default)]
pub(super) struct QLeaderM {
ask: Ask,
pts: Vec<Vec2>,
width: f64,
lines: Vec<String>,
}
impl Interactive for QLeaderM {
fn name(&self) -> &'static str {
"QLEADER"
}
fn prompt(&self, _s: &Session) -> Prompt {
let last = self.pts.last().copied();
match self.ask {
Ask::Points if self.pts.is_empty() => Prompt::new("Specify first leader point,", Accept::POINT).kw(&["Settings"]).default("Settings"),
Ask::Points => Prompt::new("Specify next point", Accept::POINT).base_opt(last),
// The width isn't remembered: AutoCAD 2024 offers 0 again after a width of 20.
Ask::Width => Prompt::new("Specify text width", Accept::POINT_OR_NUMBER).distance().default("0").base_opt(last),
Ask::FirstLine => Prompt::new("Enter first line of annotation text", Accept::TEXT).default("Mtext"),
Ask::NextLine => Prompt::new("Enter next line of annotation text", Accept::TEXT),
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
match self.ask {
Ask::Points => match i {
Input::Point(p) => {
self.pts.push(p);
if self.pts.len() == MAX_POINTS {
self.ask = Ask::Width;
}
}
Input::Enter | Input::Keyword(_) if self.pts.is_empty() => s.echo("The QLEADER Settings dialog is not available yet."),
// Enter after one point: no leader.
Input::Enter if self.pts.len() < 2 => return Ok(Step::Done),
Input::Enter => self.ask = Ask::Width,
_ => {}
},
Ask::Width => {
// A point gives the width as its distance from the leader's end; a negative
// width is none.
let width = match i {
Input::Point(p) => self.pts.last().map(|e| e.dist(p)),
Input::Text(t) => crate::units::parse_distance(&t),
Input::Enter => Some(0.0),
_ => return Ok(Step::Continue),
};
let finite = width.filter(|w| w.is_finite());
self.width = finite.ok_or_else(|| crate::EngineError::Other("Requires numeric distance or two points.".into()))?.max(0.0);
self.ask = Ask::FirstLine;
}
// Only typed text and Enter: a click in the drawing is no line of text, as at TEXT's.
Ask::FirstLine | Ask::NextLine => match i {
Input::Text(t) if !t.is_empty() => {
self.lines.push(t);
self.ask = Ask::NextLine;
}
Input::Text(_) | Input::Enter => {
let lines = std::mem::take(&mut self.lines);
let ann = if lines.is_empty() { Annotation::None } else { Annotation::Quick { lines, width: self.width } };
add_leader(s, &std::mem::take(&mut self.pts), false, true, ann)?;
return Ok(Step::Done);
}
_ => {}
},
}
Ok(Step::Continue)
}
}
/// QLEADER's JSON form: a leader through 2 or 3 `points`, with `text` (one line per line of it) as wide
/// as `width`, placed as the command line places them. The handles of the leader and its text.
pub(super) fn run_qleader(s: &mut Session, p: &Value) -> Result<Value> {
if p.get("points").is_none_or(Value::is_null) {
return Err(bad("qleader", "`points` is required"));
}
let pts = points_param(p, "points").ok_or_else(|| bad("qleader", "`points` must be a list of [x, y] points"))?;
if !(2..=MAX_POINTS).contains(&pts.len()) {
return Err(bad("qleader", "`points` takes 2 or 3 points"));
}
let width = size_param("qleader", p, "width", true)?.unwrap_or(0.0);
if p.get("text").is_some_and(|t| !t.is_null() && !t.is_string()) {
return Err(bad("qleader", "`text` must be a string"));
}
// Empty lines at the end are dropped, as the command line ends at one: a left-running leader
// would otherwise sit level with a blank last line. Text with nothing left is no text.
let mut lines: Vec<String> = str_param(p, "text").map(|t| t.lines().map(str::to_string).collect()).unwrap_or_default();
while lines.last().is_some_and(String::is_empty) {
lines.pop();
}
let ann = if lines.is_empty() { Annotation::None } else { Annotation::Quick { lines, width } };
let hs = add_leader(s, &pts, false, true, ann)?;
Ok(json!({ "handles": hs.iter().map(|h| h.hex()).collect::<Vec<_>>() }))
}
+7 -4
View File
@@ -3,7 +3,7 @@
use std::sync::Arc;
use cadcraft_doc::{Attrib, Block, Entity, EntityKind, Handle, Insert, TagKey};
use cadcraft_doc::{Attrib, Block, Entity, EntityKind, Handle, Insert};
use serde_json::{Value, json};
use crate::cmd::curves::KW;
@@ -102,14 +102,17 @@ impl Interactive for AttdispM {
/// Properties set on single attributes (layer, colour, …) go back to the definitions', as in AutoCAD.
pub(super) fn synced(blk: &Block, defs: &[&Attrib], ins: &Insert) -> Vec<Attrib> {
let m = ins.transform(blk.base.xy());
// The reference's attributes by tag, gathered once for all the definitions (#1923).
let carried = ins.attribs_by_tag();
defs.iter()
.map(|ad| {
let mut k = EntityKind::Text(ad.text.clone());
k.transform(&m);
let mut t = if let EntityKind::Text(t) = k { t } else { ad.text.clone() };
t.value = carried.get(&TagKey(&ad.tag)).map_or_else(|| ad.text.value.clone(), |a| a.text.value.clone());
t.value = ins
.attribs
.iter()
.find(|a| a.tag.eq_ignore_ascii_case(&ad.tag))
.map(|a| a.text.value.clone())
.unwrap_or_else(|| ad.text.value.clone());
Attrib {
tag: ad.tag.clone(),
text: t,
+8 -8
View File
@@ -2,7 +2,7 @@
//! become text with the values they show instead of the block's attribute definitions.
use cadcraft_color::Color;
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, TagKey};
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, Insert};
use serde_json::{Value, json};
use crate::cmd::machines::SelectRun;
@@ -28,22 +28,22 @@ fn run_burst(s: &mut Session, p: &Value) -> Result<Value> {
fn burst_pieces(d: &Drawing, e: &Entity) -> Option<Vec<Entity>> {
let EntityKind::Insert(ins) = &e.kind else { return None };
let mut out: Vec<Entity> = explode_kind(d, e)?.into_iter().filter(|p| !matches!(p.kind, EntityKind::AttDef(_))).collect();
// The block's definitions by tag, gathered once for all the attributes (#1923).
let defs = d.block(&ins.block).map(|b| b.attdefs_by_tag()).unwrap_or_default();
for a in ins.attribs.iter().filter(|a| !a.invisible) {
let kind = match a.multiline_text() {
Some(m) => EntityKind::MText(m),
None => EntityKind::Text(a.text.clone()),
};
out.push(Entity { handle: Handle(0), common: attrib_common(e, defs.get(&TagKey(&a.tag)).copied(), &a.props), kind });
out.push(Entity { handle: Handle(0), common: attrib_common(d, e, ins, &a.tag, &a.props), kind });
}
Some(out)
}
/// The properties an attribute is drawn with: its own, else those of its definition `def`; layer
/// 0 is the reference's layer and ByBlock colour the reference's colour, as EXPLODE gives the
/// block's objects.
fn attrib_common(e: &Entity, def: Option<&Entity>, props: &cadcraft_doc::AttribProps) -> Common {
/// The properties an attribute is drawn with: its own, else its definition's; layer 0 is the
/// reference's layer and ByBlock colour the reference's colour, as EXPLODE gives the block's
/// objects.
fn attrib_common(d: &Drawing, e: &Entity, ins: &Insert, tag: &str, props: &cadcraft_doc::AttribProps) -> Common {
let def =
d.block(&ins.block).and_then(|b| b.entities.iter().find(|be| matches!(&be.kind, EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(tag))));
// An attribute without a definition follows the reference.
let base = def.map(|de| de.common.clone()).unwrap_or_else(|| Common { color: Color::ByBlock, ..Common::default() });
let mut c = props.over(&base);
+5 -52
View File
@@ -5,7 +5,7 @@
use cadcraft_doc::color::Color;
use cadcraft_doc::dynblock::{self, GripPart, GripShape};
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, Lineweight, TagKey, Transparency};
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, Lineweight, Transparency};
use cadcraft_geom::Vec2;
use serde_json::{Value, json};
@@ -111,10 +111,11 @@ fn drawn(d: &Drawing, h: Handle) -> Vec<Entity> {
.collect();
// An attribute draws with its definition's properties, except those set on it.
let by_block = Common { layer: "0".into(), color: Color::ByBlock, linetype: "ByBlock".into(), lineweight: Lineweight::ByBlock, ..r.clone() };
// The block's definitions by tag, gathered once for all the attributes (#1923).
let defs = b.attdefs_by_tag();
out.extend(ins.attribs.iter().filter(|a| !a.invisible).map(|a| {
let def = defs.get(&TagKey(&a.tag)).map(|e| &e.common);
let def = b.entities.iter().find_map(|e| match &e.kind {
EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(&a.tag) => Some(&e.common),
_ => None,
});
let common = under(&a.props.over(def.unwrap_or(&by_block)), r);
let kind = match a.multiline_text() {
Some(m) => EntityKind::MText(m),
@@ -247,51 +248,3 @@ impl Session {
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn many_attributes_are_previewed_without_comparing_every_pair_with_the_definitions() {
// #1923: a reference with N attributes of a block with N definitions, the tags N long ones
// alike up to their last characters, no attribute's a definition's. Looking for each
// attribute's definition by comparing it with every one cost N x N comparisons of whole
// tags for each preview (many seconds here); the definitions gathered by tag once cost
// milliseconds.
const N: usize = 4000;
let tag = |kind: char, i: usize| format!("{}{kind}{i:05}", "T".repeat(1000));
let attrib = |tag: String| cadcraft_doc::Attrib {
tag,
text: cadcraft_doc::Text {
insert: cadcraft_geom::Vec3::ZERO,
align_pt: None,
height: 1.0,
value: "v".into(),
rotation: 0.0,
width_factor: 1.0,
oblique: 0.0,
style: "Standard".into(),
halign: Default::default(),
valign: Default::default(),
},
invisible: false,
constant: false,
prompt: String::new(),
props: Default::default(),
multiline: None,
modes: Default::default(),
};
let mut d = Drawing::new_metric();
let mut blk = cadcraft_doc::Block::new("B");
for (h, i) in (1..).zip(0..N) {
blk.entities.push(Entity::new(Handle(h), EntityKind::AttDef(attrib(tag('D', i)))));
}
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
let ins = cadcraft_doc::Insert { block: "B".into(), attribs: (0..N).map(|i| attrib(tag('A', i))).collect(), ..Default::default() };
let h = d.add(&cadcraft_doc::Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
let t = std::time::Instant::now();
assert_eq!(drawn(&d, h).len(), N);
assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed());
}
}
+1 -1
View File
@@ -265,7 +265,7 @@ fn defs_for(src: &Drawing, ents: &[Entity]) -> Drawing {
}
let mut d = Drawing::new_imperial();
d.header = src.header.clone();
d.layers = pick(&src.layers, &used.layers, |l| &l.name).into();
d.layers = pick(&src.layers, &used.layers, |l| &l.name);
d.linetypes = pick(&src.linetypes, &used.linetypes, |l| &l.name);
d.text_styles = pick(&src.text_styles, &used.text_styles, |t| &t.name);
d.dim_styles = pick(&src.dim_styles, &used.dim_styles, |t| &t.name);
+6 -4
View File
@@ -253,14 +253,16 @@ 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 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),
let f = match p.get("factor").and_then(Value::as_f64).filter(|a| a.is_finite()) {
Some(f) if f > 1e-12 => f,
Some(_) => return Err(bad("grip.scale", "factor must be positive")),
None => {
mode_matrix(GripMode::Scale, base, point_req("grip.scale", p, "to")?).ok_or_else(|| bad("grip.scale", "scale factor would be zero"))?
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")) }
}
};
apply(s, &hs, &m, bool_or(p, "copy", false))
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<_>>() }))
}
fn run_grip_mirror(s: &mut Session, p: &Value) -> Result<Value> {
+48 -19
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::transform_entities;
use super::modify::{at_elevation, scale_entities, 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,14 +220,7 @@ 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.")),
};
fn finish_edit(&mut self, before: Arc<Drawing>, changed: bool) -> Result<Step> {
if !changed {
return Err(other("The objects can't be edited that way (locked, or the result would be degenerate)."));
}
@@ -240,6 +233,27 @@ 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() {
@@ -286,12 +300,20 @@ impl GripEdit {
Ok(Step::Continue)
}
Input::Point(p) => {
let m = self.matrix(p);
self.edit(s, p, m)
if self.mode == GripMode::Scale {
self.edit_scale(s, self.base.dist(p))
} else {
let m = self.matrix(p);
self.edit(s, p, m)
}
}
Input::Deferred(d) => {
let m = self.matrix(d.at);
self.edit(s, d.at, m)
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)
}
}
Input::Text(t) => match self.mode {
GripMode::Rotate => {
@@ -300,7 +322,7 @@ impl GripEdit {
}
GripMode::Scale => {
let f = positive(number(&t))?;
self.edit(s, self.base, Some(Mat3::scale_about(self.base, f)))
self.edit_scale(s, f)
}
_ => Err(other("Requires a point or an option keyword.")),
},
@@ -327,14 +349,21 @@ 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(_), 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::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(r), Input::Text(t)) => {
let v = value(&t)?;
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));
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);
}
(_, Input::Enter) => self.ask = Ask::Mode,
_ => {}
+2 -2
View File
@@ -297,7 +297,7 @@ fn run_layerp(s: &mut Session, _p: &Value) -> Result<Value> {
let d = s.doc_mut()?;
let snap = d.header.str("CADCRAFT_LAYERP", "");
let layers: Vec<Layer> = serde_json::from_str(&snap).map_err(|_| bad("layerp", "No previous layer state."))?;
d.layers = layers.into();
d.layers = layers;
Ok(json!({"message": "Restored previous layer states."}))
}
@@ -375,7 +375,7 @@ fn run_layuniso(s: &mut Session, _p: &Value) -> Result<Value> {
let d = s.doc_mut()?;
let snap = d.header.str("CADCRAFT_LAYISO", "");
let layers: Vec<Layer> = serde_json::from_str(&snap).map_err(|_| bad("layuniso", "No isolated layers."))?;
d.layers = layers.into();
d.layers = layers;
ok()
}
+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::{holds_ole_frame, ole_refusal, refuse_ole_frames, transform_entities};
pub(crate) use transform::{at_elevation, holds_ole_frame, ole_refusal, refuse_ole_frames, scale_entities, 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,
+50 -376
View File
@@ -129,406 +129,80 @@ pub(crate) fn join(s: &mut Session, hs: &[Handle]) -> Result<Option<Handle>> {
if hs.iter().any(|h| crate::cmd::curves::is_locked(s, *h)) {
return Err(EngineError::Other("An object is on a locked layer.".into()));
}
let hs = joinable_picks(s.doc()?, hs);
let hs = &hs[..];
if let Some(h) = join_on_source(s, hs)? {
return Ok(Some(h));
}
let d = s.doc()?;
// Each object JOIN can take, as the pieces it is made of: a line or an arc is one piece, an
// open polyline its segments in order, each keeping its vertices, bulge and widths exactly.
// Each also with whether it faces down: an arc or a polyline whose normal points down Z
// (measured with 0,0,-1; a tilted one is taken the same way). A line faces up whatever its
// normal (AutoCAD 2024 joins one with normal 0,0,-1 to a polyline facing up, and no line to a
// polyline facing down; measured).
let mut units: Vec<(bool, Vec<Piece>)> = Vec::new();
let down = |e: &Entity| !matches!(e.kind, EntityKind::Line(_)) && e.common.extrusion.z < 0.0;
let mut segs: Vec<Segment> = Vec::new();
// Source entity of each segment in `segs`, so only entities that end up in the chain are removed.
let mut owners: Vec<Handle> = Vec::new();
let mut common = None;
for h in hs {
let Some(e) = d.entity(*h) else { continue };
let piece =
|ends: (Vec2, Vec2), heights: (f64, f64), bulge: f64, widths: Option<(f64, f64)>| Piece { owner: *h, ends, heights, bulge, widths };
let unit: Vec<Piece> = match &e.kind {
// A line of no length joins as AutoCAD 2024 joins it, a repeated vertex.
EntityKind::Line(l) => vec![piece((l.a.xy(), l.b.xy()), (l.a.z, l.b.z), 0.0, None)],
EntityKind::Arc(a) => {
let arc = Arc::new(a.center.xy(), a.radius, a.start, a.end);
vec![piece((arc.start_point(), arc.end_point()), (a.center.z, a.center.z), cadcraft_geom::arc_to_bulge(arc.sweep()), None)]
}
// Repeated vertices included: AutoCAD 2024 keeps them.
EntityKind::LwPolyline(p) if !p.closed => {
// The elevation is along the polyline's normal: down Z for a mirrored one.
let z = if down(e) { -p.elevation } else { p.elevation };
p.vertices
.windows(2)
.map(|w| {
let widths = if p.const_width > 0.0 { (p.const_width, p.const_width) } else { (w[0].start_width, w[0].end_width) };
piece((w[0].p, w[1].p), (z, z), w[0].bulge, Some(widths))
})
.collect()
}
_ => Vec::new(),
};
if !unit.is_empty() {
units.push((down(e), unit));
common.get_or_insert_with(|| e.common.clone());
match &e.kind {
EntityKind::Line(l) => segs.push(Segment::Line(Line::new(l.a.xy(), l.b.xy()))),
EntityKind::Arc(a) => segs.push(Segment::Arc { arc: Arc::new(a.center.xy(), a.radius, a.start, a.end), ccw: true }),
EntityKind::LwPolyline(p) if !p.closed => segs.extend(Polyline { vertices: p.vertices.clone(), closed: false }.segments()),
_ => {}
}
owners.resize(segs.len(), *h);
}
if units.iter().map(|u| u.1.len()).sum::<usize>() < 2 {
if segs.len() < 2 {
return Err(EngineError::Other("Select at least two objects to join.".into()));
}
// An object facing the other way from a polyline source stays out (AutoCAD 2024, measured: one
// facing up takes no arc facing down, and one facing down no arc or polyline facing up). Onto a
// line or an arc it wasn't measured (the core console's JOIN takes only collinear lines or arcs
// on one circle onto those), so objects facing either way still join there.
let polyline_source = units.first().filter(|u| u.1.first().is_some_and(|p| p.widths.is_some())).map(|u| u.0);
let units: Vec<Vec<Piece>> = units.into_iter().filter(|u| polyline_source.is_none_or(|down| u.0 == down)).map(|u| u.1).collect();
// A new polyline takes the source's properties.
let first = units.first().and_then(|u| u.first()).map(|p| p.owner);
let common = first.and_then(|h| d.entity(h)).map(|e| e.common.clone());
// Chain greedily from the first segment.
let mut chain = vec![segs.remove(0)];
let mut used = vec![owners.remove(0)];
let tol = 1e-6;
let links = chain_units(units, tol);
// One object alone joins nothing, even a polyline whose ends meet: AutoCAD 2024 leaves it open
// ("0 segments added to polyline").
let closed = links.first().zip(links.last()).is_some_and(|(a, b)| meet(a.start(), b.end(), tol));
let one_object = links.first().is_some_and(|f| links.iter().all(|l| l.owner == f.owner));
if links.len() < 2 || one_object {
loop {
let start = chain.first().map(Segment::start).unwrap_or_default();
let end = chain.last().map(Segment::end).unwrap_or_default();
let Some(i) =
segs.iter().position(|s| s.start().near(end, tol) || s.end().near(end, tol) || s.start().near(start, tol) || s.end().near(start, tol))
else {
break;
};
let s0 = segs.remove(i);
used.push(owners.remove(i));
if s0.start().near(end, tol) {
chain.push(s0);
} else if s0.end().near(end, tol) {
chain.push(s0.reversed());
} else if s0.end().near(start, tol) {
chain.insert(0, s0);
} else {
chain.insert(0, s0.reversed());
}
}
if chain.len() < 2 {
return Err(EngineError::Other("Objects are not connected.".into()));
}
let used = |h: &Handle| links.iter().any(|l| l.owner == *h);
// A polyline's own segments keep their widths.
let mut vs: Vec<PolyVertex> = links
let closed = chain.first().zip(chain.last()).is_some_and(|(a, b)| a.start().near(b.end(), tol));
let mut vs: Vec<PolyVertex> = chain
.iter()
.map(|l| {
let (start_width, end_width) = l.widths.unwrap_or_default();
PolyVertex { p: l.ends.0, bulge: l.bulge, start_width, end_width }
.map(|s| PolyVertex {
p: s.start(),
bulge: match s {
Segment::Line(_) => 0.0,
Segment::Arc { arc, ccw } => cadcraft_geom::arc_to_bulge(if *ccw { arc.sweep() } else { -arc.sweep() }),
},
..Default::default()
})
.collect();
if !closed && let Some(l) = links.last() {
vs.push(PolyVertex::new(l.ends.1));
if !closed && let Some(l) = chain.last() {
vs.push(PolyVertex::new(l.end()));
}
// A new polyline goes in the source's space, whichever space is current.
let space = first.and_then(|h| d.space_of(h)).unwrap_or_else(|| s.space());
let space = s.space();
let doc = s.doc_mut()?;
// A polyline source takes the other pieces and keeps its handle (AutoCAD 2024: "1 segments
// added to polyline").
if let Some(src) = first
&& let Some(EntityKind::LwPolyline(sp)) = doc.entity(src).map(|e| &e.kind)
&& let Some(onto) = onto_polyline(sp, src, &links, closed)
{
for h in hs.iter().filter(|h| **h != src && used(h)) {
doc.remove_entity(*h);
}
doc.modify_entity(src, |e| e.kind = EntityKind::LwPolyline(onto))?;
s.set_selection(Vec::new());
return Ok(Some(src));
}
for h in hs.iter().filter(|h| used(h)) {
for h in hs.iter().filter(|h| used.contains(*h)) {
doc.remove_entity(*h);
}
// A new polyline stays at the source's height, as a polyline source keeps its elevation. The
// elevation runs along its normal: negated for one facing down. Not measured: the core
// console's JOIN makes no new polyline.
let height = links.iter().find(|l| Some(l.owner) == first).map_or(0.0, |l| l.heights.0);
let common = common.unwrap_or_default();
let elevation = if common.extrusion.z < 0.0 { -height } else { height };
let mut kind = lwpoly(vs, closed);
if let EntityKind::LwPolyline(p) = &mut kind {
p.elevation = elevation;
}
let nh = doc.new_handle();
if let Some(st) = doc.space_mut(&space) {
st.push(Entity { handle: nh, common, kind });
st.push(Entity { handle: nh, common: common.unwrap_or_default(), kind: lwpoly(vs, closed) });
}
s.set_selection(Vec::new());
Ok(Some(nh))
}
/// The picks JOIN can take, each once, in the order picked: lines, arcs and open polylines. The
/// first of them is the source (AutoCAD 2024 passes over a circle picked first and leaves it).
fn joinable_picks(d: &cadcraft_doc::Drawing, hs: &[Handle]) -> Vec<Handle> {
let mut seen = std::collections::HashSet::new();
let joinable = |h: &Handle| {
d.entity(*h).is_some_and(|e| match &e.kind {
EntityKind::Line(_) => true,
EntityKind::Arc(a) => a.radius > cadcraft_geom::EPS,
EntityKind::LwPolyline(p) => !p.closed,
_ => false,
})
};
hs.iter().copied().filter(|h| joinable(h) && seen.insert(*h)).collect()
}
/// Whether JOIN would make the picked arcs a circle. AutoCAD 2024 asks first ("Combined arc
/// segments form a circle. Convert to circle? [Yes/No] <Yes>:"), and No leaves every arc as it
/// is (measured).
pub(crate) fn join_makes_circle(s: &Session, hs: &[Handle]) -> bool {
let Ok(d) = s.doc() else { return false };
// Elliptical arcs and splines join another way, and a locked object stops the join.
let other_way = |h: &Handle| d.entity(*h).is_some_and(|e| matches!(e.kind, EntityKind::Ellipse(_) | EntityKind::Spline(_)));
if hs.iter().any(|h| other_way(h) || crate::cmd::curves::is_locked(s, *h)) {
return false;
}
let picks = joinable_picks(d, hs);
let arcs: Vec<&cadcraft_doc::Arc> = picks
.iter()
.filter_map(|h| match d.entity(*h).map(|e| &e.kind) {
Some(EntityKind::Arc(a)) => Some(a),
_ => None,
})
.collect();
let tol = 1e-6;
match &arcs[..] {
[g, rest @ ..] if !rest.is_empty() && arcs.len() == picks.len() => arc_reach(g, rest, tol).is_some_and(|far| far > cadcraft_geom::TAU - tol),
_ => false,
}
}
/// How far round the source arc `g`'s circle, counterclockwise from its start, it and the
/// `others` reach; `None` when one of them isn't on that circle (less than `tol` off its centre
/// and radius). An arc that starts even a hair before the source's start reaches on round past
/// it: AutoCAD 2024 makes a circle of 7°-100° and an arc stored from 7° less 5e-16 rad, and
/// leaves 7°-100° with one from exactly 7° or 5e-7 rad after it.
fn arc_reach(g: &cadcraft_doc::Arc, others: &[&cadcraft_doc::Arc], tol: f64) -> Option<f64> {
let same_circle =
|o: &cadcraft_doc::Arc| o.center.xy().dist(g.center.xy()) < tol && (o.radius - g.radius).abs() < tol && (o.center.z - g.center.z).abs() < tol;
let reach = |o: &cadcraft_doc::Arc| norm_angle(o.start - g.start) + cadcraft_geom::ccw_sweep(o.start, o.end);
others.iter().all(|o| same_circle(o)).then(|| others.iter().map(|o| reach(o)).fold(reach(g), f64::max))
}
/// The chain JOIN builds from the first object: each next object with an end on one of the
/// chain's ends joins whole, turned round where needed, as AutoCAD 2024 joins them, until a join
/// closes the chain; one that the chain meets only at an inner vertex of a polyline stays out.
/// Ends are compared at the objects' own end points, not ones worked out again from arcs, and at
/// their heights.
fn chain_units(mut units: Vec<Vec<Piece>>, tol: f64) -> Vec<Piece> {
let ends = |u: &[Piece]| u.first().zip(u.last()).map(|(a, b)| (a.start(), b.end()));
let near = |p, q| meet(p, q, tol);
if units.is_empty() {
return Vec::new();
}
// A source that already ends where it starts still takes more, unless it has no length at all
// (AutoCAD 2024, measured with a polyline that ends where it starts and with a line of no
// length).
let mut chain: std::collections::VecDeque<Piece> = units.remove(0).into();
if chain.iter().all(|p| p.ends.0.near(p.ends.1, tol)) {
return chain.into();
}
while let (Some(start), Some(end)) = (chain.front().map(Piece::start), chain.back().map(Piece::end)) {
let meets = |u: &Vec<Piece>| ends(u).is_some_and(|(a, b)| near(a, end) || near(b, end) || near(a, start) || near(b, start));
let Some(i) = units.iter().position(meets) else { break };
let unit = units.remove(i);
let Some((a, b)) = ends(&unit) else { break };
// Where an object that meets the chain at more than one place goes, as AutoCAD 2024 puts
// it (measured): a polyline by its first vertex if it can, and before the chain rather
// than after it; a line or an arc turned round if it can, its end on the chain's end
// before its start on the chain's start.
let polyline = unit.first().is_some_and(|p| p.widths.is_some());
let (before, turned) = if polyline {
if near(a, start) {
(true, true)
} else if near(a, end) {
(false, false)
} else {
(near(b, start), !near(b, start))
}
} else if near(b, end) {
(false, true)
} else if near(a, start) {
(true, true)
} else {
(!near(a, end), false)
};
match (before, turned) {
(false, false) => chain.extend(unit),
(false, true) => chain.extend(unit.into_iter().rev().map(Piece::flipped)),
(true, false) => unit.into_iter().rev().for_each(|p| chain.push_front(p)),
(true, true) => unit.into_iter().for_each(|p| chain.push_front(p.flipped())),
}
// A chain that a join closes takes nothing more.
if chain.front().zip(chain.back()).is_some_and(|(f, l)| near(f.start(), l.end())) {
break;
}
}
chain.into()
}
/// A segment in the chain JOIN builds: the object it came from, its end points as the object has
/// them (turned round when it runs backwards in the chain) and their world heights (a line's own
/// Z, an arc's centre Z, a polyline's elevation, negated for one facing down), its bulge and, for a
/// polyline's own segment, its widths.
#[derive(Clone, Copy)]
struct Piece {
owner: Handle,
ends: (Vec2, Vec2),
heights: (f64, f64),
bulge: f64,
widths: Option<(f64, f64)>,
}
impl Piece {
fn flipped(self) -> Self {
Piece {
ends: (self.ends.1, self.ends.0),
heights: (self.heights.1, self.heights.0),
bulge: -self.bulge,
widths: self.widths.map(|(a, b)| (b, a)),
..self
}
}
fn start(&self) -> (Vec2, f64) {
(self.ends.0, self.heights.0)
}
fn end(&self) -> (Vec2, f64) {
(self.ends.1, self.heights.1)
}
}
/// Whether two ends meet: in plan and at the same height. AutoCAD 2024 leaves an end that meets
/// another only in plan apart (measured: a line or a polyline at 0 and a line at 5, or a polyline
/// at 5 and a line at 0, end to end in plan, stay as they are).
fn meet(p: (Vec2, f64), q: (Vec2, f64), tol: f64) -> bool {
p.0.near(q.0, tol) && (p.1 - q.1).abs() < tol
}
/// The open polyline `sp` (handle `src`) with the chain's other pieces added before and after
/// it, as AutoCAD 2024 JOIN makes it (measured with `entget`): its own vertices stay exactly as
/// they are, and so do its elevation, linetype generation and, when only lines and arcs join,
/// its constant width; another polyline's segments keep their bulges and widths; a line or arc
/// takes the widths of the source's vertex at the end it joins (first or last); and when another
/// polyline joins, the end vertex's widths are cleared.
///
/// `None` when the source's segments aren't one run of the chain (they always are: the chain
/// starts from the source and takes its segments in order).
fn onto_polyline(sp: &cadcraft_doc::LwPolyline, src: Handle, links: &[Piece], closed: bool) -> Option<cadcraft_doc::LwPolyline> {
let run: Vec<usize> = (0..links.len()).filter(|i| links[*i].owner == src).collect();
let (&first, &last) = (run.first()?, run.last()?);
if sp.closed || run.len() != last - first + 1 {
return None;
}
let other_polyline = links.iter().any(|l| l.owner != src && l.widths.is_some());
let mut own = sp.vertices.clone();
if other_polyline && sp.const_width > 0.0 {
// The constant width goes, so spell it out on the source's own segments.
for v in &mut own {
(v.start_width, v.end_width) = (sp.const_width, sp.const_width);
}
}
let widths = |v: &PolyVertex| (v.start_width, v.end_width);
let (head, tail) = (widths(own.first()?), widths(own.last()?));
let vertex = |i: usize, fill: (f64, f64)| {
let (start_width, end_width) = links[i].widths.unwrap_or(fill);
PolyVertex { p: links[i].ends.0, bulge: links[i].bulge, start_width, end_width }
};
let mut vs: Vec<PolyVertex> = (0..first).map(|i| vertex(i, head)).collect();
vs.extend(own);
if last + 1 < links.len() {
// The source's end vertex starts the first piece after it.
let v = vertex(last + 1, tail);
if let Some(end) = vs.last_mut() {
(end.bulge, end.start_width, end.end_width) = (v.bulge, v.start_width, v.end_width);
}
vs.extend((last + 2..links.len()).map(|i| vertex(i, tail)));
vs.push(PolyVertex { p: links.last()?.ends.1, start_width: tail.0, end_width: tail.1, ..Default::default() });
}
if other_polyline && let Some(end) = vs.last_mut() {
(end.start_width, end.end_width) = (0.0, 0.0);
}
if closed {
// The last vertex is the first one again.
vs.pop();
}
Some(cadcraft_doc::LwPolyline { vertices: vs, closed, const_width: if other_polyline { 0.0 } else { sp.const_width }, ..sp.clone() })
}
/// JOIN onto the first object (the source) as AutoCAD 2024 does when the others all lie on its
/// line or its circle: gaps and overlaps are bridged and the source keeps its handle.
///
/// - Lines on the source's line make one line, from the source's start end to the farthest
/// point the way it runs (and back past its start if one reaches behind it).
/// - Arcs on the source's circle join counterclockwise from the source's start to the farthest
/// end; arcs that reach all the way round make a circle, a new object in their place.
///
/// `None` when the objects aren't all of one of those kinds.
fn join_on_source(s: &mut Session, hs: &[Handle]) -> Result<Option<Handle>> {
let d = s.doc()?;
let ents: Vec<std::sync::Arc<Entity>> = hs.iter().filter_map(|h| d.entity(*h).cloned()).collect();
let [src, rest @ ..] = &ents[..] else { return Ok(None) };
if rest.is_empty() || ents.len() != hs.len() {
return Ok(None);
}
// AutoCAD 2024 takes lines less than 1e-6 off the source's line, and arcs less than 1e-6
// off its centre and radius, at any size of coordinates (measured at 0, 1000 and 2.4e6), and
// makes a circle of arcs that come round to less than 1e-6 radians from the source's start.
let tol = 1e-6;
let kind = match &src.kind {
EntityKind::Line(l) => {
let (a, b) = (l.a.xy(), l.b.xy());
let len = a.dist(b);
let lines: Vec<&cadcraft_doc::Line> = rest
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Line(o) => Some(o),
_ => None,
})
.collect();
let level = |z: f64| (z - l.a.z).abs() < tol;
if lines.len() != rest.len() || len <= 0.0 || !level(l.b.z) || !lines.iter().all(|o| level(o.a.z) && level(o.b.z)) {
return Ok(None);
}
let u = (b - a) * (1.0 / len);
let on_line = |p: Vec2| (p - a).cross(u).abs() < tol;
if !lines.iter().all(|o| on_line(o.a.xy()) && on_line(o.b.xy())) {
return Ok(None);
}
let ts = lines.iter().flat_map(|o| [o.a.xy(), o.b.xy()]).map(|p| (p - a).dot(u)).chain([0.0, len]);
let (t0, t1) = ts.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), t| (lo.min(t), hi.max(t)));
let at = |t: f64| (a + u * t).to3(l.a.z);
EntityKind::Line(cadcraft_doc::Line { a: at(t0), b: if t1 == len { l.b } else { at(t1) } })
}
EntityKind::Arc(g) => {
let arcs: Vec<&cadcraft_doc::Arc> = rest
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Arc(o) => Some(o),
_ => None,
})
.collect();
let Some(far) = arc_reach(g, &arcs, tol).filter(|_| arcs.len() == rest.len()) else { return Ok(None) };
if far > cadcraft_geom::TAU - tol {
let circle = Entity {
handle: Handle(0),
common: src.common.clone(),
kind: EntityKind::Circle(cadcraft_doc::Circle { center: g.center, radius: g.radius }),
};
// In the source's space, whichever space is current.
let space = d.space_of(src.handle).unwrap_or_else(|| s.space());
let doc = s.doc_mut()?;
for h in hs {
doc.remove_entity(*h);
}
let nh = doc.new_handle();
if let Some(st) = doc.space_mut(&space) {
st.push(Entity { handle: nh, ..circle });
}
s.set_selection(Vec::new());
return Ok(Some(nh));
}
let end = if far > cadcraft_geom::ccw_sweep(g.start, g.end) { norm_angle(g.start + far) } else { g.end };
EntityKind::Arc(cadcraft_doc::Arc { end, ..g.clone() })
}
_ => return Ok(None),
};
let src_h = src.handle;
let doc = s.doc_mut()?;
for h in hs.iter().filter(|h| **h != src_h) {
doc.remove_entity(*h);
}
doc.modify_entity(src_h, |e| e.kind = kind)?;
s.set_selection(Vec::new());
Ok(Some(src_h))
}
pub(super) fn run_join(s: &mut Session, p: &Value) -> Result<Value> {
let hs = targets(s, p)?;
if p.get("close").and_then(Value::as_bool) == Some(true) {
+80 -72
View File
@@ -1,4 +1,4 @@
use super::break_join::{join, join_makes_circle};
use super::break_join::join;
use super::explode::explode;
use super::transform::{at_elevation, erase, scale_entities, transform_entities};
use super::{
@@ -27,12 +27,11 @@ pub(super) struct SelectThen {
objs: Vec<Handle>,
pts: Vec<Vec2>,
reference: bool,
/// 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`.
/// ROTATE Reference: the reference angle (radians), once known.
ref_angle: Option<f64>,
/// ROTATE Reference: the new angle is given by two points (the `Points` option).
/// ROTATE/SCALE Reference: the new angle/length is given by two points (the `Points` option).
ref_points: bool,
/// SCALE Reference: first point of a reference length given by two points.
/// ROTATE/SCALE Reference: first point of a reference or `Points` pair given by two points.
ref_from: Option<Vec2>,
/// SCALE Reference: the reference length, once known.
ref_len: Option<f64>,
@@ -40,8 +39,6 @@ pub(super) struct SelectThen {
ask_erase: bool,
/// JOIN of a single arc or elliptical arc: the prompt asks for arcs to join to it, or cLose.
join_source: Option<Handle>,
/// JOIN of arcs that make a circle: asking whether to.
ask_circle: bool,
}
impl SelectThen {
@@ -59,7 +56,6 @@ impl SelectThen {
copy_mode: false,
ask_erase: false,
join_source: None,
ask_circle: false,
}
}
fn apply(&mut self, s: &mut Session) -> Result<Step> {
@@ -87,17 +83,8 @@ impl SelectThen {
}
}
/// JOIN the selected objects and report what they became. Arcs that make a circle ask first,
/// as AutoCAD 2024 does.
/// JOIN the selected objects and report what they became.
fn join_now(&mut self, s: &mut Session) -> Result<Step> {
if join_makes_circle(s, &self.objs) {
self.ask_circle = true;
return Ok(Step::Continue);
}
self.join_apply(s)
}
fn join_apply(&mut self, s: &mut Session) -> Result<Step> {
match join(s, &self.objs) {
Ok(h) => {
// Objects outside the joined chain are kept, so count only the ones JOIN consumed
@@ -107,9 +94,6 @@ impl SelectThen {
let what = match h.and_then(|h| d.entity(h)).map(|e| &e.kind) {
Some(EntityKind::Spline(_)) => "spline",
Some(EntityKind::Ellipse(_)) => "ellipse",
Some(EntityKind::Line(_)) => "line",
Some(EntityKind::Arc(_)) => "arc",
Some(EntityKind::Circle(_)) => "circle",
_ => "polyline",
};
s.echo(format!("{n} objects joined into 1 {what}"))
@@ -142,30 +126,47 @@ impl SelectThen {
}
}
/// 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.
/// 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.
fn scale_reference(&mut self, s: &mut Session, i: Input) -> Result<Step> {
let Some(base) = self.pts.first().copied() else { return Ok(Step::Done) };
match (self.ref_len, self.ref_from, i) {
(None, None, Input::Point(p)) => {
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)) => {
self.ref_from = Some(p);
Ok(Step::Continue)
}
(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))?;
(true, Some(a), Input::Point(p)) => {
let n = require_length(Some(a.dist(p)))?;
self.scale_by(s, base, n / r)
}
(_, _, Input::Enter) => Ok(Step::Done),
@@ -173,6 +174,26 @@ 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.
@@ -323,9 +344,6 @@ impl Interactive for SelectThen {
if self.ask_erase {
return Prompt::new("Erase source objects?", Accept::TEXT).kw(&["Yes", "No"]).default("No");
}
if self.ask_circle {
return Prompt::new("Combined arc segments form a circle. Convert to circle?", crate::cmd::curves::KW).kw(&["Yes", "No"]).default("Yes");
}
if let Some(src) = self.join_source {
let ellipse = s.doc().is_ok_and(|d| matches!(d.entity(src).map(|e| &e.kind), Some(EntityKind::Ellipse(_))));
let msg = if ellipse { "Select elliptical arcs to join to source" } else { "Select arcs to join to source" };
@@ -334,11 +352,7 @@ impl Interactive for SelectThen {
let k = self.pts.len();
let base = self.pts.first().copied();
if self.op == Op::Scale && self.reference {
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"),
};
return self.scale_reference_prompt();
}
if self.op == Op::Rotate && self.reference {
return self.rotate_reference_prompt();
@@ -379,14 +393,6 @@ impl Interactive for SelectThen {
}
}
}
// No leaves every arc as it is (AutoCAD 2024, measured).
if self.ask_circle {
return match &i {
Input::Keyword(k) if k == "No" => Ok(Step::Done),
Input::Keyword(_) | Input::Enter => self.join_apply(s),
_ => Err(EngineError::Other("Invalid option keyword.".into())),
};
}
if let Some(src) = self.join_source {
return self.join_source_input(s, src, i);
}
@@ -494,16 +500,15 @@ impl Interactive for SelectThen {
return Vec::new();
}
let Some(base) = self.pts.first().copied() else { return Vec::new() };
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(),
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),
None => return self.ref_from.map(|a| vec![line(a, c)]).unwrap_or_default(),
},
Op::Mirror if !self.ask_erase => Mat3::mirror(base, c),
Op::Mirror if !self.ask_erase => (Mat3::mirror(base, c), base),
_ => return Vec::new(),
};
let Ok(d) = s.doc() else { return Vec::new() };
@@ -522,7 +527,7 @@ impl Interactive for SelectThen {
k
})
.collect();
out.push(line(base, c));
out.push(line(rubber_from, c));
out
}
/// Separate shared GPU transforms from objects that need an individual MIRROR preview.
@@ -531,15 +536,18 @@ impl Interactive for SelectThen {
return None;
}
let base = self.pts.first().copied()?;
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),
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),
_ => return None,
};
let mut extra = vec![line(base, c)];
let mut extra = vec![line(rubber_from, c)];
if self.op != Op::Mirror {
return Some(crate::prompt::Drag { handles: self.objs.clone(), matrix, extra, clipboard: false });
}
+1 -43
View File
@@ -4,8 +4,7 @@
use cadcraft_doc::{Common, Entity, EntityKind, Handle, LwPolyline, MAX_BLOCK_DEPTH, Space};
use cadcraft_geom::{
Arc, Ellipse, Line, Mat3, PolyVertex, Polyline, Segment, Spline, TAU, Vec2, Vec3, ccw_sweep, intersect_ext, line_circle, line_line_infinite,
norm_angle,
Arc, Ellipse, Line, Mat3, PolyVertex, Polyline, Segment, Spline, TAU, Vec2, ccw_sweep, intersect_ext, line_circle, line_line_infinite, norm_angle,
};
use serde_json::{Value, json};
@@ -123,47 +122,6 @@ pub(crate) fn as_lwpoly(k: &EntityKind) -> Option<LwPolyline> {
}
}
/// The polyline PEDIT turns a line or an arc into, and the normal it faces, as AutoCAD 2024 makes
/// them (measured): facing the way the arc faces, and up for a line whatever its normal; at the
/// line's height, or at the arc's centre height measured along its normal (a mirrored arc whose
/// centre is at world Z -5 gives elevation 5, one at Z 5 elevation -5); the thickness stays the
/// object's. A sloped line still comes out at elevation 0: AutoCAD makes a polyline in the line's
/// vertical plane, which a CADCraft polyline can't be. An arc in a tilted plane (normal neither up
/// nor down Z), which CADCraft keeps only approximately, keeps its normal and goes by the sign of
/// its Z as above; AutoCAD's result for one isn't measured. A polyline is returned as it is.
pub(crate) fn polyline_of(e: &Entity) -> Option<(LwPolyline, Vec3)> {
let mut pl = as_lwpoly(&e.kind)?;
let normal = e.common.extrusion;
match &e.kind {
EntityKind::Line(l) => {
if (l.a.z - l.b.z).abs() < 1e-9 {
pl.elevation = l.a.z;
}
Some((pl, Vec3::Z))
}
// The arc's centre is in world coordinates; a polyline's elevation runs along its normal.
// A mirrored arc runs clockwise in plan, and so does its polyline (AutoCAD 2024 starts it
// at the arc's start in the arc's own coordinates).
EntityKind::Arc(a) => {
pl.elevation = if normal.z < 0.0 { -a.center.z } else { a.center.z };
if normal.z < 0.0 {
pl.vertices = curves::reverse_vertices(&pl.vertices, false);
}
Some((pl, normal))
}
_ => Some((pl, normal)),
}
}
/// Puts the polyline `pl`, facing `normal`, in place of the object `h`.
fn set_polyline(s: &mut Session, h: Handle, pl: LwPolyline, normal: Vec3) -> Result<()> {
s.doc_mut()?.modify_entity(h, |e| {
e.kind = EntityKind::LwPolyline(pl);
e.common.extrusion = normal;
})?;
Ok(())
}
mod pedit_multi;
mod pedit_vertex;
+29 -99
View File
@@ -1,7 +1,7 @@
use super::{
Accept, Chain, Entity, EntityKind, Handle, Input, Interactive, LwPolyline, MAX_GEN, PolyVertex, Prompt, Result, SelOutcome, SelectPhase, Session,
Spline, Step, Value, Vec2, Vec3, as_lwpoly, bad, bool_or, curves, f64_or, f64_req, json, line, number, other, pedit_vertex, point_req,
polyline_of, set_kind, set_polyline, str_param, targets,
Accept, Chain, EntityKind, Handle, Input, Interactive, LwPolyline, MAX_GEN, PolyVertex, Prompt, Result, SelOutcome, SelectPhase, Session, Spline,
Step, Value, Vec2, as_lwpoly, bad, bool_or, curves, f64_or, f64_req, json, line, number, other, pedit_vertex, point_req, set_kind, str_param,
targets,
};
/// Fit curve: a tangent-continuous pair of arcs (biarc) per segment through every vertex,
@@ -106,21 +106,7 @@ pub(crate) fn spline_vertices(vs: &[PolyVertex], closed: bool, segs: usize) -> V
}
/// Join connected lines/arcs/open polylines onto the ends of polyline `h` (kept in place).
///
/// As AutoCAD 2024 joins (measured), none facing the other way: an arc or a polyline whose normal
/// points down Z where the polyline's points up, or the other way round; a line counts as facing
/// up. Multiple's Join (`same_height` false) takes them at any height (lines at Z 5 and Z 0 join).
///
/// PEDIT's own Join takes only objects in one plane with the polyline: the plane the polyline and
/// every line picked share, when they share one, else the polyline's own. So a sloped line joins
/// only when the polyline and all the lines picked lie in one plane (a vertical one for a sloped
/// line continuing a straight polyline in plan), and then no arc or polyline joins, as those lie
/// flat; otherwise only objects at the polyline's height join (a line, arc or polyline at Z 0
/// stays off one at Z 5). Ends meet within `fuzz` in plan and within 1e-6 in height, which `fuzz`
/// doesn't widen. After a sloped line the chain's end is at the line's far end, so the next object
/// meets it there; AutoCAD's polyline then lies in the lines' plane, CADCraft's keeps the source's
/// elevation and runs through the objects' points seen from above.
pub(crate) fn pedit_join(s: &mut Session, h: Handle, others: &[Handle], fuzz: f64, same_height: bool) -> Result<usize> {
pub(crate) fn pedit_join(s: &mut Session, h: Handle, others: &[Handle], fuzz: f64) -> Result<usize> {
let e = curves::entity(s, h)?;
let mut base = as_lwpoly(&e.kind).ok_or_else(|| other("Select a polyline."))?;
if base.closed {
@@ -128,88 +114,46 @@ pub(crate) fn pedit_join(s: &mut Session, h: Handle, others: &[Handle], fuzz: f6
}
let mut chain = Chain::of(&EntityKind::LwPolyline(base.clone())).unwrap_or_default();
let tol = fuzz.max(1e-6);
// Which way an object faces, and its two ends' world heights.
let down = |e: &Entity| !matches!(e.kind, EntityKind::Line(_)) && e.common.extrusion.z < 0.0;
let heights = |e: &Entity| match &e.kind {
EntityKind::Line(l) => (l.a.z, l.b.z),
// An arc's centre is in world coordinates.
EntityKind::Arc(a) => (a.center.z, a.center.z),
// A polyline's elevation runs along its normal.
EntityKind::LwPolyline(p) => {
let z = if down(e) { -p.elevation } else { p.elevation };
(z, z)
}
_ => (0.0, 0.0),
};
// Two ends meet: in plan within the fuzz distance, and for PEDIT's own Join at the same height.
let at = |p: Vec2, ph: f64, q: Vec2, qh: f64| p.near(q, tol) && (!same_height || (ph - qh).abs() < 1e-6);
let picked: Vec<(Handle, Entity)> = others.iter().filter(|o| **o != h).filter_map(|o| Some((*o, curves::entity(s, *o).ok()?))).collect();
// The plane PEDIT's own Join works in (AutoCAD 2024, measured): the polyline's points, with a
// point off the chord of an arc segment, which lies flat, and the ends of every line picked.
let z0 = heights(&e).0;
let mut pts: Vec<Vec3> = base.vertices.iter().map(|v| Vec3::new(v.p.x, v.p.y, z0)).collect();
if let Some(w) = base.vertices.windows(2).find(|w| w[0].bulge.abs() > 1e-12) {
let (a, b) = (w[0].p, w[1].p);
let off = (a + b) * 0.5 + Vec2::new(a.y - b.y, b.x - a.x);
pts.push(Vec3::new(off.x, off.y, z0));
}
let lines: Vec<(Vec3, Vec3)> =
picked.iter().filter_map(|(_, oe)| if let EntityKind::Line(l) = &oe.kind { Some((l.a, l.b)) } else { None }).collect();
pts.extend(lines.iter().flat_map(|(a, b)| [*a, *b]));
let shared = coplanar(&pts);
// That plane is the polyline's own, flat, when every line is at its height.
let level = lines.iter().all(|(a, b)| (a.z - z0).abs() < 1e-6 && (b.z - z0).abs() < 1e-6);
let mut pool: Vec<(Handle, Chain, (f64, f64))> = Vec::new();
for (o, oe) in &picked {
if down(oe) != down(&e) {
let mut pool: Vec<(Handle, Chain)> = Vec::new();
for o in others {
if *o == h {
continue;
}
let line = matches!(oe.kind, EntityKind::Line(_));
let (ah, bh) = heights(oe);
// A sloped line lies in no flat plane, and an arc or a polyline in no other.
let off_plane = if shared && !level { !line } else { (ah - bh).abs() >= 1e-6 };
if same_height && off_plane {
continue;
}
let ok = line || matches!(&oe.kind, EntityKind::Arc(_)) || matches!(&oe.kind, EntityKind::LwPolyline(p) if !p.closed);
let Ok(oe) = curves::entity(s, *o) else { continue };
let ok = matches!(&oe.kind, EntityKind::Line(_) | EntityKind::Arc(_)) || matches!(&oe.kind, EntityKind::LwPolyline(p) if !p.closed);
if ok && let Some(c) = Chain::of(&oe.kind) {
pool.push((*o, c, (ah, bh)));
pool.push((*o, c));
}
}
let (mut st_h, mut en_h) = heights(&e);
let mut joined = Vec::new();
while let (Some(st), Some(en)) = (chain.start(), chain.end()) {
let meets = |c: &Chain, (ah, bh): (f64, f64)| {
c.start().zip(c.end()).is_some_and(|(a, b)| at(a, ah, en, en_h) || at(b, bh, en, en_h) || at(a, ah, st, st_h) || at(b, bh, st, st_h))
};
let Some(i) = pool.iter().position(|(_, c, z)| meets(c, *z)) else {
let Some(i) = pool
.iter()
.position(|(_, c)| c.start().zip(c.end()).is_some_and(|(a, b)| a.near(en, tol) || b.near(en, tol) || a.near(st, tol) || b.near(st, tol)))
else {
break;
};
let (oh, c, (ah, bh)) = pool.remove(i);
let (oh, c) = pool.remove(i);
let (Some(a), Some(b)) = (c.start(), c.end()) else { continue };
if at(a, ah, en, en_h) {
if a.near(en, tol) {
chain.segs.extend(c.segs);
en_h = bh;
} else if at(b, bh, en, en_h) {
} else if b.near(en, tol) {
chain.segs.extend(c.reversed().segs);
en_h = ah;
} else if at(b, bh, st, st_h) {
} else if b.near(st, tol) {
let mut v = c.segs;
v.extend(chain.segs);
chain.segs = v;
st_h = ah;
} else {
let mut v = c.reversed().segs;
v.extend(chain.segs);
chain.segs = v;
st_h = bh;
}
joined.push(oh);
}
if joined.is_empty() {
return Ok(0);
}
chain.closed = chain.start().zip(chain.end()).is_some_and(|(a, b)| at(a, st_h, b, en_h)) && chain.segs.len() > 1;
chain.closed = chain.start().zip(chain.end()).is_some_and(|(a, b)| a.near(b, tol)) && chain.segs.len() > 1;
base.vertices = chain.vertices();
base.closed = chain.closed;
let d = s.doc_mut()?;
@@ -220,29 +164,14 @@ pub(crate) fn pedit_join(s: &mut Session, h: Handle, others: &[Handle], fuzz: f6
Ok(joined.len())
}
/// Whether the points `pts` lie in one plane, to within 1e-6 (points in a line always do).
fn coplanar(pts: &[Vec3]) -> bool {
let Some(&p0) = pts.first() else { return true };
let far = |a: &&Vec3, b: &&Vec3| (**a - p0).len().total_cmp(&(**b - p0).len());
let Some(&p1) = pts.iter().max_by(far) else { return true };
let d = p1 - p0;
// The normal from the point farthest off the line p0 p1, for the least rounding.
let Some(n) = pts.iter().map(|p| d.cross(*p - p0)).max_by(|a, b| a.len().total_cmp(&b.len())) else { return true };
if n.len() <= 1e-6 * d.len() {
return true;
}
let n = n.normalized();
pts.iter().all(|p| n.dot(*p - p0).abs() < 1e-6)
}
pub(super) fn pedit_apply(s: &mut Session, h: Handle, opt: &str, p: &Value) -> Result<Value> {
let e = curves::entity(s, h)?;
if curves::is_locked(s, h) {
return Err(other("The object is on a locked layer."));
}
let (mut pl, normal) = match &e.kind {
EntityKind::LwPolyline(pl) => (pl.clone(), e.common.extrusion),
EntityKind::Line(_) | EntityKind::Arc(_) if bool_or(p, "convert", true) => polyline_of(&e).ok_or_else(|| other("Cannot convert."))?,
let mut pl = match &e.kind {
EntityKind::LwPolyline(pl) => pl.clone(),
EntityKind::Line(_) | EntityKind::Arc(_) if bool_or(p, "convert", true) => as_lwpoly(&e.kind).ok_or_else(|| other("Cannot convert."))?,
_ => return Err(other("Object selected is not a polyline.")),
};
match opt {
@@ -268,14 +197,14 @@ pub(super) fn pedit_apply(s: &mut Session, h: Handle, opt: &str, p: &Value) -> R
"reverse" | "r" => pl.vertices = curves::reverse_vertices(&pl.vertices, pl.closed),
"ltypegen" | "l" => pl.plinegen = bool_or(p, "on", !pl.plinegen),
"join" | "j" => {
set_polyline(s, h, pl, normal)?;
set_kind(s, h, EntityKind::LwPolyline(pl))?;
let others: Vec<Handle> = p
.get("handles2")
.or_else(|| p.get("join"))
.and_then(Value::as_array)
.map(|a| a.iter().filter_map(curves::handle_value).collect())
.unwrap_or_default();
let n = pedit_join(s, h, &others, f64_or(p, "fuzz", 0.0), true)?;
let n = pedit_join(s, h, &others, f64_or(p, "fuzz", 0.0))?;
return Ok(json!({ "handle": h.hex(), "joined": n }));
}
"vertex" | "e" => {
@@ -325,7 +254,7 @@ pub(super) fn pedit_apply(s: &mut Session, h: Handle, opt: &str, p: &Value) -> R
}
_ => return Err(bad("pedit", "unknown option")),
}
set_polyline(s, h, pl, normal)?;
set_kind(s, h, EntityKind::LwPolyline(pl))?;
Ok(json!({ "handle": h.hex() }))
}
@@ -539,9 +468,10 @@ impl Interactive for PeditM {
return Ok(Step::Done);
}
let h = self.h.ok_or_else(|| other("No object."))?;
let (pl, normal) = polyline_of(&curves::entity(s, h)?).ok_or_else(|| other("Cannot convert."))?;
let k = curves::entity(s, h)?.kind;
let pl = as_lwpoly(&k).ok_or_else(|| other("Cannot convert."))?;
self.original = Some(pl.vertices.clone());
set_polyline(s, h, pl, normal)?;
set_kind(s, h, EntityKind::LwPolyline(pl))?;
self.phase = PPhase::Main;
Ok(Step::Continue)
}
@@ -614,7 +544,7 @@ impl Interactive for PeditM {
SelOutcome::Done(hs) => {
let h = self.h.ok_or_else(|| other("No polyline."))?;
self.snapshot(s);
let n = pedit_join(s, h, &hs, 0.0, true)?;
let n = pedit_join(s, h, &hs, 0.0)?;
s.echo(format!("{n} segments added to polyline"));
s.set_selection(vec![h]);
self.phase = PPhase::Main;
+7 -7
View File
@@ -8,7 +8,7 @@ use serde_json::json;
use super::super::curves;
use super::super::machines::{SelOutcome, SelectPhase, number};
use super::pedit::{PPhase, PeditM, clear_widths, pedit_apply, pedit_join, yes_no};
use super::{other, polyline_of, set_kind, set_polyline};
use super::{as_lwpoly, other, set_kind};
use crate::{Accept, Input, Prompt, Result, Session, Step};
/// Most option steps Undo can take back.
@@ -78,13 +78,13 @@ impl PeditM {
let no = !yes_no(&i)?;
let mut kept = Vec::new();
for h in std::mem::take(&mut self.multi) {
let e = curves::entity(s, h)?;
match e.kind {
let kind = curves::entity(s, h)?.kind;
match kind {
EntityKind::LwPolyline(_) => kept.push(h),
_ if no => {}
_ => {
if let Some((pl, normal)) = polyline_of(&e) {
set_polyline(s, h, pl, normal)?;
k => {
if let Some(pl) = as_lwpoly(&k) {
set_kind(s, h, EntityKind::LwPolyline(pl))?;
kept.push(h);
}
}
@@ -219,7 +219,7 @@ impl PeditM {
let open = matches!(curves::entity(s, h)?.kind, EntityKind::LwPolyline(p) if !p.closed);
if open {
// A polyline that took on segments no longer goes back past the Join on Decurve.
if pedit_join(s, h, &rest, fuzz, false)? > 0 {
if pedit_join(s, h, &rest, fuzz)? > 0 {
self.morig.remove(&h);
}
rest.retain(|o| s.doc().is_ok_and(|d| d.entity(*o).is_some()));
+4 -85
View File
@@ -85,31 +85,18 @@ pub fn profile(s: &Session) -> Value {
Value::Object(m)
}
/// The profile variables the drawing keeps in its header rather than in the session's settings.
const DRAWING_VARS: &[&str] = &["SNAPUNIT", "GRIDUNIT"];
/// Set the profile variables named in `values` (an object; other keys are refused). All or
/// nothing: one bad name or value leaves every setting, and the drawing, as they were.
/// nothing: one bad name or value leaves every setting as it was.
pub fn apply(s: &mut Session, values: &Value) -> Result<()> {
let Some(obj) = values.as_object() else { return Err(bad("options", "expected an object of profile variables")) };
let before = s.settings.clone();
// When one of the values is a drawing variable, the drawing as it is: put back whole on a
// refusal, it is the same drawing again, so not marked as changed either.
let touches_drawing = obj.keys().any(|k| DRAWING_VARS.iter().any(|v| v.eq_ignore_ascii_case(k.trim())));
let drawing = if touches_drawing { s.state().ok().map(|st| st.doc.clone()) } else { None };
let put_back = |s: &mut Session| {
s.settings = before.clone();
if let (Some(doc), Ok(st)) = (&drawing, s.state_mut()) {
st.doc = doc.clone();
}
};
for (name, v) in obj {
if !is_profile_var(name) {
put_back(s);
s.settings = before;
return Err(bad("options", format!("{name} is not a profile setting")));
}
if let Err(e) = crate::sysvars::set(s, name, v) {
put_back(s);
s.settings = before;
return Err(bad("options", format!("invalid value for {}: {e}", name.to_ascii_uppercase())));
}
}
@@ -130,8 +117,7 @@ pub fn restore(s: &mut Session, saved: &Value) {
}
}
/// Put every profile variable back to its default, except [`DRAWING_VARS`]: a reset doesn't change
/// the drawing.
/// Put every profile variable back to its default.
pub fn reset(s: &mut Session) {
let d = Settings::default();
let st = &mut s.settings;
@@ -159,21 +145,6 @@ pub fn reset(s: &mut Session) {
st.pickadd = d.pickadd;
st.pickdrag = d.pickdrag;
st.maxarray = d.maxarray;
st.dynprompt = d.dynprompt;
st.dyndigrip = d.dyndigrip;
st.dyndivis = d.dyndivis;
st.selectioneffect = d.selectioneffect;
st.selectionpreview = d.selectionpreview;
st.previeweffect = d.previeweffect;
st.previewfilter = d.previewfilter;
st.grips = d.grips;
st.gripobjlimit = d.gripobjlimit;
st.selectionarea = d.selectionarea;
st.windowareacolor = d.windowareacolor;
st.crossingareacolor = d.crossingareacolor;
st.selectionareaopacity = d.selectionareaopacity;
st.pickstyle = d.pickstyle;
st.measureinit = d.measureinit;
}
fn run_options(s: &mut Session, p: &Value) -> Result<Value> {
@@ -220,56 +191,4 @@ mod tests {
restore(&mut b, &saved);
assert_eq!(profile(&b), saved);
}
#[test]
fn a_refused_change_leaves_the_drawings_snap_and_grid_too() {
let mut s = Session::new();
let before = profile(&s);
let refused = [
json!({ "SNAPUNIT": [2, 3], "GRIDUNIT": [4, 5], "WINDOWAREACOLOR": 0 }),
json!({ "GRIDUNIT": [4, 5], "LUNITS": 2 }),
json!({ "WINDOWAREACOLOR": 0 }),
];
for bad_one in refused {
assert!(apply(&mut s, &bad_one).is_err(), "{bad_one}");
assert_eq!(profile(&s), before, "{bad_one}");
// The same drawing, so there is nothing new to save.
assert!(!s.state().unwrap().is_dirty(), "{bad_one}");
}
assert!(s.execute("options", &json!({ "reset": true, "SNAPUNIT": [2, 3], "WINDOWAREACOLOR": 0 })).is_err());
assert_eq!(profile(&s), before);
// The header entries come back exactly: a zero grid spacing (which reads as the snap
// spacing), and a snap spacing the drawing doesn't have. The refused value comes last, so
// both are written first (the keys are taken in name order).
let header = |s: &Session, n: &str| s.doc().unwrap().header.get(n).cloned();
s.doc_mut().unwrap().header.set("GRIDUNIT", cadcraft_doc::HVal::Point(cadcraft_geom::Vec3::new(0.0, 0.0, 0.0)));
s.doc_mut().unwrap().header.vars.remove("SNAPUNIT");
let (grid, snap) = (header(&s, "GRIDUNIT"), header(&s, "SNAPUNIT"));
assert!(apply(&mut s, &json!({ "GRIDUNIT": [4, 5], "SNAPUNIT": [2, 3], "WINDOWAREACOLOR": 0 })).is_err());
assert_eq!((header(&s, "GRIDUNIT"), header(&s, "SNAPUNIT")), (grid, snap));
}
#[test]
fn reset_puts_every_profile_var_back_except_the_drawings() {
let defaults = profile(&Session::new());
let mut s = Session::new();
for name in PROFILE_VARS.iter().filter(|n| !DRAWING_VARS.contains(n)) {
// A value the variable takes that isn't its default: 0 and 1 swapped, or a number one
// more or less, or an angle.
let was = &defaults[*name];
let n = was.as_f64().unwrap_or(0.0);
let tries = [json!(if n == 0.0 { 1 } else { 0 }), json!(n + 1.0), json!(n - 1.0), json!("15")];
let changed = tries.iter().any(|v| apply(&mut s, &json!({ *name: v })).is_ok() && profile(&s)[*name] != *was);
assert!(changed, "no other value found for {name} (default {was})");
}
assert!(PROFILE_VARS.iter().filter(|n| !DRAWING_VARS.contains(n)).all(|n| profile(&s)[*n] != defaults[*n]));
apply(&mut s, &json!({ "SNAPUNIT": [2, 3], "GRIDUNIT": [4, 5] })).unwrap();
reset(&mut s);
let after = profile(&s);
for name in PROFILE_VARS.iter().filter(|n| !DRAWING_VARS.contains(n)) {
assert_eq!(after[*name], defaults[*name], "{name}");
}
// The snap and grid spacing are the drawing's, and stay.
assert_eq!((after["SNAPUNIT"].clone(), after["GRIDUNIT"].clone()), (json!([2.0, 3.0]), json!([4.0, 5.0])));
}
}
@@ -202,7 +202,6 @@ pub const NO_FILES: &[&str] = &[
"dim",
"mleader",
"leader",
"qleader",
"dimstyle.update",
"dimoverride",
"dimreassociate",
+1 -1
View File
@@ -161,7 +161,7 @@ impl SpatialIndex {
let infinite = chunks.iter().flat_map(|(off, c)| c.infinite.iter().map(move |i| off + i)).collect();
SpatialIndex {
store: store.clone(),
blocks: (*d.blocks).clone(),
blocks: d.blocks.clone(),
dim_styles: d.dim_styles.clone(),
dimscale: d.header.f64("DIMSCALE", 1.0),
anno: anno_key(d),
+91
View File
@@ -532,6 +532,97 @@ 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();
@@ -1,98 +0,0 @@
//! Attributes are matched to their block's definitions, and definitions to a reference's
//! attributes, by tag in one lookup each: BURST and ATTSYNC on a reference with many of both.
use std::sync::Arc;
use cadcraft_doc::{Attrib, EntityKind, Handle};
use cadcraft_engine::Session;
use serde_json::json;
/// Block B with definition T and a reference to it carrying T = "v"; with `n` > 0 the block gets
/// `n` more definitions and the reference's attribute is replaced by `n`, the tags `n` long ones
/// alike up to their last characters, no attribute's a definition's.
fn reference(n: usize) -> (Session, Handle) {
let mut s = Session::new();
s.execute("attdef", &json!({"tag": "T", "default": "d", "at": [0, 1], "height": 1.0})).unwrap();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
let hs: Vec<String> = s.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect();
s.execute("block", &json!({"name": "B", "base": [0, 0], "keep": "delete", "handles": hs})).unwrap();
let r = s.execute("insert", &json!({"name": "B", "at": [0, 0], "attribs": {"T": "v"}})).unwrap();
let h = Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
if n > 0 {
let tag = |kind: char, i: usize| format!("{}{kind}{i:05}", "T".repeat(1000));
let d = s.doc_mut().unwrap();
let handles: Vec<Handle> = (0..n).map(|_| d.new_handle()).collect();
let blk = Arc::make_mut(d.blocks.get_mut("B").unwrap());
let def = blk.entities.iter().find(|e| matches!(e.kind, EntityKind::AttDef(_))).unwrap().as_ref().clone();
for (i, h) in handles.into_iter().enumerate() {
let mut e = def.clone();
e.handle = h;
if let EntityKind::AttDef(a) = &mut e.kind {
a.tag = tag('D', i);
}
blk.entities.push(e);
}
d.modify_entity(h, |e| {
if let EntityKind::Insert(ins) = &mut e.kind {
let one = ins.attribs[0].clone();
ins.attribs = (0..n).map(|i| Attrib { tag: tag('A', i), ..one.clone() }).collect();
}
})
.unwrap();
}
(s, h)
}
fn attribs(s: &Session, h: Handle) -> Vec<Attrib> {
let EntityKind::Insert(i) = &s.doc().unwrap().entity(h).unwrap().kind else { panic!("not an insert") };
i.attribs.clone()
}
/// #1923: comparing each attribute with each definition (BURST: for its properties; ATTSYNC: for
/// the value each definition keeps) cost N x N comparisons of whole tags (many seconds here); one
/// lookup each costs milliseconds.
const N: usize = 4000;
#[test]
fn burst_matches_many_attributes_without_comparing_every_pair() {
let (mut s, h) = reference(N);
let t = std::time::Instant::now();
s.execute("burst", &json!({"handles": [h.hex()]})).unwrap();
assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed());
assert_eq!(s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Text(_))).count(), N);
}
#[test]
fn attsync_matches_many_definitions_without_comparing_every_pair() {
let (mut s, h) = reference(N);
let t = std::time::Instant::now();
s.execute("attsync", &json!({"name": "B"})).unwrap();
assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed());
// An attribute for each definition (T and the N others), with its default value: the
// reference carried none of their tags.
let a = attribs(&s, h);
assert_eq!(a.len(), N + 1);
assert!(a.iter().all(|a| a.text.value == "d"));
}
#[test]
fn attsync_keeps_the_value_of_the_first_attribute_of_a_tag() {
// A reference carrying two attributes of one tag (in different case, as a file can hold
// them) keeps the first one's value for the definition of that tag.
let (mut s, h) = reference(0);
s.doc_mut()
.unwrap()
.modify_entity(h, |e| {
if let EntityKind::Insert(ins) = &mut e.kind {
let mut second = ins.attribs[0].clone();
second.tag = "t".into();
second.text.value = "second".into();
ins.attribs[0].text.value = "first".into();
ins.attribs.push(second);
}
})
.unwrap();
s.execute("attsync", &json!({"name": "B"})).unwrap();
let a = attribs(&s, h);
assert_eq!(a.iter().map(|a| (a.tag.as_str(), a.text.value.as_str())).collect::<Vec<_>>(), [("T", "first")]);
}
File diff suppressed because it is too large Load Diff
-4
View File
@@ -12,7 +12,6 @@ mod attdisp_attsync;
mod attedit_prompts;
mod attrib_modes;
mod attrib_props;
mod attribute_tag_matching;
mod attribute_tools;
mod attribute_value_baseline;
mod block_description;
@@ -85,7 +84,6 @@ mod insert_enter;
mod insert_prompts;
mod isometric;
mod join_close;
mod join_on_source;
mod json_param_validation;
mod kept_dimension_snaps;
mod layer_cmdline;
@@ -124,7 +122,6 @@ mod oops_command;
mod options_profile;
mod overkill;
mod parallel_display_list;
mod pedit_heights;
mod pedit_multiple;
mod pedit_splinedit;
mod pick_text;
@@ -146,7 +143,6 @@ mod purge_mlinestyles;
mod purge_prompts;
mod qdim;
mod qdim_modes;
mod qleader;
mod query_entities;
mod quickcalc;
mod recent_commands;
-365
View File
@@ -1,365 +0,0 @@
//! PEDIT on lines, arcs and polylines away from Z 0, as AutoCAD 2024 runs it (accoreconsole,
//! `entget` of the polyline made, on self-built drawings). A mirrored object here is one whose
//! normal is 0,0,-1, kept in world coordinates as the DXF reader keeps it.
use cadcraft_doc::{Entity, EntityKind, Handle, LwPolyline};
use cadcraft_engine::Session;
use cadcraft_geom::Vec3;
use serde_json::{Value, json};
fn handle(v: &Value) -> Handle {
Handle::parse_hex(v["handle"].as_str().or_else(|| v["handles"][0].as_str()).unwrap()).unwrap()
}
fn entity(s: &Session, h: Handle) -> Entity {
(**s.doc().unwrap().entity(h).unwrap()).clone()
}
fn edit(s: &mut Session, h: Handle, f: impl FnOnce(&mut Entity)) {
s.doc_mut().unwrap().modify_entity(h, f).unwrap();
}
/// A line from `a` to `b`.
fn line(s: &mut Session, a: [f64; 3], b: [f64; 3]) -> Handle {
let h = handle(&s.execute("line", &json!({ "points": [[a[0], a[1]], [b[0], b[1]]] })).unwrap());
edit(s, h, |e| {
if let EntityKind::Line(l) = &mut e.kind {
(l.a.z, l.b.z) = (a[2], b[2]);
}
});
h
}
/// An arc round `c` (world) from `a1` to `a2` degrees, counterclockwise in plan.
fn arc(s: &mut Session, c: [f64; 3], r: f64, a1: f64, a2: f64) -> Handle {
let h = handle(&s.execute("arc", &json!({ "center": [c[0], c[1]], "radius": r, "start": a1, "end": a2 })).unwrap());
edit(s, h, |e| {
if let EntityKind::Arc(a) = &mut e.kind {
a.center.z = c[2];
}
});
h
}
/// An open polyline through `points` at `elevation`.
fn pline(s: &mut Session, points: Value, elevation: f64) -> Handle {
let h = handle(&s.execute("pline", &json!({ "points": points })).unwrap());
edit(s, h, |e| {
if let EntityKind::LwPolyline(p) = &mut e.kind {
p.elevation = elevation;
}
});
h
}
fn face_down(s: &mut Session, h: Handle) {
edit(s, h, |e| e.common.extrusion = Vec3::new(0.0, 0.0, -1.0));
}
fn polyline(e: &Entity) -> LwPolyline {
let EntityKind::LwPolyline(p) = &e.kind else { panic!("not a polyline: {e:?}") };
p.clone()
}
/// PEDIT's JSON form with nothing to change, which only turns a line or an arc into a polyline.
fn convert(s: &mut Session, h: Handle) -> Entity {
s.execute("pedit", &json!({ "handle": h.hex(), "option": "ltypegen", "on": false })).unwrap();
entity(s, h)
}
#[test]
fn a_line_or_an_arc_becomes_a_polyline_at_its_height() {
// AutoCAD 2024: a line at Z 5 and an arc whose centre is at Z 5 give elevation 5 facing up;
// a thickness of 2 stays, a line's and an arc's; a line facing down still gives a polyline
// facing up.
let mut s = Session::new();
let l = line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
edit(&mut s, l, |e| e.common.thickness = 2.0);
let e = convert(&mut s, l);
assert_eq!((polyline(&e).elevation, e.common.extrusion, e.common.thickness), (5.0, Vec3::Z, 2.0));
let a = arc(&mut s, [10.0, 5.0, 5.0], 5.0, 270.0, 0.0);
edit(&mut s, a, |e| e.common.thickness = 2.0);
let e = convert(&mut s, a);
let p = polyline(&e);
assert_eq!((p.elevation, e.common.extrusion, e.common.thickness), (5.0, Vec3::Z, 2.0));
assert!((p.vertices[0].bulge - std::f64::consts::FRAC_PI_8.tan()).abs() < 1e-9, "{p:?}");
// Below Z 0 too (AutoCAD 2024: 38 = -5 for the arc's centre at Z -5).
let a = arc(&mut s, [10.0, 5.0, -5.0], 5.0, 270.0, 0.0);
let e = convert(&mut s, a);
assert_eq!((polyline(&e).elevation, e.common.extrusion), (-5.0, Vec3::Z));
let l = line(&mut s, [0.0, 20.0, 5.0], [10.0, 20.0, 5.0]);
face_down(&mut s, l);
let e = convert(&mut s, l);
assert_eq!((polyline(&e).elevation, e.common.extrusion), (5.0, Vec3::Z));
// A mirrored arc keeps its normal (AutoCAD 2024: 210 0,0,-1, elevation 5 for the arc at world
// Z -5) and runs as it does in its own coordinates: from world (15,5) to (10,0), bulge
// -0.414214 in plan (0.414214 in its own coordinates).
let a = arc(&mut s, [10.0, 5.0, -5.0], 5.0, 270.0, 0.0);
face_down(&mut s, a);
let e = convert(&mut s, a);
let p = polyline(&e);
assert_eq!((p.elevation, e.common.extrusion), (5.0, Vec3::new(0.0, 0.0, -1.0)));
let v: Vec<(f64, f64)> = p.vertices.iter().map(|v| (v.p.x, v.p.y)).collect();
assert!((v[0].0 - 15.0).abs() < 1e-9 && (v[0].1 - 5.0).abs() < 1e-9 && (v[1].0 - 10.0).abs() < 1e-9 && v[1].1.abs() < 1e-9, "{v:?}");
assert!((p.vertices[0].bulge + std::f64::consts::FRAC_PI_8.tan()).abs() < 1e-9, "{p:?}");
// The elevation runs along the normal the other way too: a mirrored arc at world Z 5 gives -5,
// and one 2 thick at world Z -5 keeps the thickness (AutoCAD 2024: 38 = -5; 38 = 5, 39 = 2).
let a = arc(&mut s, [10.0, 5.0, 5.0], 5.0, 270.0, 0.0);
face_down(&mut s, a);
let e = convert(&mut s, a);
assert_eq!((polyline(&e).elevation, e.common.extrusion), (-5.0, Vec3::new(0.0, 0.0, -1.0)));
let a = arc(&mut s, [10.0, 5.0, -5.0], 5.0, 270.0, 0.0);
face_down(&mut s, a);
edit(&mut s, a, |e| e.common.thickness = 2.0);
let e = convert(&mut s, a);
assert_eq!((polyline(&e).elevation, e.common.extrusion, e.common.thickness), (5.0, Vec3::new(0.0, 0.0, -1.0), 2.0));
// A sloped line still comes out at elevation 0, facing up: AutoCAD 2024 makes a polyline in the
// line's vertical plane (normal 0,1,0), which a CADCraft polyline can't be.
let l = line(&mut s, [0.0, 40.0, 0.0], [10.0, 40.0, 5.0]);
let e = convert(&mut s, l);
assert_eq!((polyline(&e).elevation, e.common.extrusion), (0.0, Vec3::Z));
// A refused option leaves a line as it was, its normal included.
let l = line(&mut s, [0.0, 60.0, 5.0], [10.0, 60.0, 5.0]);
face_down(&mut s, l);
let before = entity(&s, l);
let r = s.execute("pedit", &json!({ "handle": l.hex(), "option": "vertex", "index": 0, "action": "break" }));
assert!(r.is_err(), "{r:?}");
assert_eq!(entity(&s, l), before);
}
/// PEDIT Join from the first object onto the second; whether the second was taken.
fn joins(s: &mut Session, first: Handle, second: Handle) -> bool {
let r = s.execute("pedit", &json!({ "handle": first.hex(), "option": "join", "join": [second.hex()] })).unwrap();
let taken = r["joined"] == json!(1);
assert_eq!(taken, s.doc().unwrap().entity(second).is_none(), "{r}");
taken
}
#[test]
fn join_takes_only_objects_at_the_polylines_height_facing_its_way() {
// AutoCAD 2024, from a line at Z 5 ending at (10,0): "1 segments added to polyline" or "0".
let next: [(&str, bool, fn(&mut Session) -> Handle); 6] = [
("a line at Z 5", true, |s| line(s, [10.0, 0.0, 5.0], [10.0, 5.0, 5.0])),
("a line at Z 0", false, |s| line(s, [10.0, 0.0, 0.0], [10.0, 5.0, 0.0])),
("an arc at Z 5", true, |s| arc(s, [10.0, 5.0, 5.0], 5.0, 270.0, 0.0)),
("an arc at Z 0", false, |s| arc(s, [10.0, 5.0, 0.0], 5.0, 270.0, 0.0)),
("a mirrored line at Z 5", true, |s| {
let h = line(s, [10.0, 0.0, 5.0], [10.0, 5.0, 5.0]);
face_down(s, h);
h
}),
("a mirrored arc at Z 5", false, |s| {
let h = arc(s, [10.0, 5.0, 5.0], 5.0, 270.0, 0.0);
face_down(s, h);
h
}),
];
for (what, want, make) in next {
let mut s = Session::new();
let base = line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
let other = make(&mut s);
assert_eq!(joins(&mut s, base, other), want, "{what}");
let p = polyline(&entity(&s, base));
assert_eq!((p.elevation, p.vertices.len()), (5.0, if want { 3 } else { 2 }), "{what}");
if want && what.contains("arc") {
// AutoCAD 2024: bulge 0.414214 on the arc's segment.
assert!((p.vertices[1].bulge - std::f64::consts::FRAC_PI_8.tan()).abs() < 1e-9, "{what}: {p:?}");
}
}
// From a mirrored polyline at elevation 5 (world Z -5, from (0,0) to (10,0)): no line at its
// world height, but a mirrored arc there and another mirrored polyline at elevation 5; and a
// polyline at elevation 5 takes no polyline at 0.
let mirrored: [(&str, bool, fn(&mut Session) -> Handle); 3] = [
("a line at Z -5", false, |s| line(s, [10.0, 0.0, -5.0], [10.0, 5.0, -5.0])),
("a mirrored arc at Z -5", true, |s| {
let h = arc(s, [10.0, 5.0, -5.0], 5.0, 270.0, 0.0);
face_down(s, h);
h
}),
("a mirrored polyline at elevation 5", true, |s| {
let h = pline(s, json!([[10, 0], [10, 5]]), 5.0);
face_down(s, h);
h
}),
];
for (what, want, make) in mirrored {
let mut s = Session::new();
let base = pline(&mut s, json!([[0, 0], [10, 0]]), 5.0);
face_down(&mut s, base);
let other = make(&mut s);
assert_eq!(joins(&mut s, base, other), want, "{what}");
// AutoCAD 2024: the polyline keeps elevation 5 and normal 0,0,-1; the arc's segment has
// bulge -0.414214 in the polyline's own coordinates, 0.414214 seen from above.
let e = entity(&s, base);
let p = polyline(&e);
assert_eq!((p.elevation, e.common.extrusion, p.vertices.len()), (5.0, Vec3::new(0.0, 0.0, -1.0), if want { 3 } else { 2 }), "{what}");
if want && what.contains("arc") {
assert!((p.vertices[1].bulge - std::f64::consts::FRAC_PI_8.tan()).abs() < 1e-9, "{what}: {p:?}");
}
}
let mut s = Session::new();
let base = pline(&mut s, json!([[0, 0], [10, 0]]), 5.0);
let other = pline(&mut s, json!([[10, 0], [10, 5]]), 0.0);
assert!(!joins(&mut s, base, other), "a polyline at elevation 0");
}
#[test]
fn multiple_join_takes_objects_at_any_height_but_not_facing_the_other_way() {
// AutoCAD 2024: PEDIT Multiple, a line at Z 5 and one at Z 0 meeting it in plan, convert and
// Join with no fuzz: "1 segments added to polyline", one polyline at elevation 5.
let mut s = Session::new();
line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
line(&mut s, [10.0, 0.0, 0.0], [10.0, 5.0, 0.0]);
s.cmdline("pedit m 5,0 10,2.5").unwrap();
s.cmdline("").unwrap();
s.cmdline("y j 0").unwrap();
s.cmdline("").unwrap();
let objects: Vec<Entity> = s.doc().unwrap().model.iter().map(|e| (**e).clone()).collect();
assert_eq!(objects.len(), 1, "{objects:?}");
let p = polyline(&objects[0]);
assert_eq!((p.elevation, p.vertices.len()), (5.0, 3));
// A line at Z 0 to (10,0) and a mirrored arc from there to (15,5), picked in either order:
// both become polylines, the arc's facing down, and Join takes neither ("0 segments added").
for arc_first in [false, true] {
let mut s = Session::new();
line(&mut s, [0.0, 0.0, 0.0], [10.0, 0.0, 0.0]);
let a = arc(&mut s, [10.0, 5.0, 0.0], 5.0, 270.0, 0.0);
face_down(&mut s, a);
// The arc picked on it, at 315 degrees.
s.cmdline(if arc_first { "pedit m 13.5355339,1.4644661 5,0" } else { "pedit m 5,0 13.5355339,1.4644661" }).unwrap();
s.cmdline("").unwrap();
s.cmdline("y j 0").unwrap();
s.cmdline("").unwrap();
let objects: Vec<Entity> = s.doc().unwrap().model.iter().map(|e| (**e).clone()).collect();
assert_eq!(objects.len(), 2, "arc first {arc_first}: {objects:?}");
assert!(objects.iter().all(|e| matches!(e.kind, EntityKind::LwPolyline(_))), "{objects:?}");
// AutoCAD 2024: the arc's polyline at elevation 0 with normal 0,0,-1, the line's facing up.
let (arcs, lines): (Vec<&Entity>, Vec<&Entity>) = objects.iter().partition(|e| e.common.extrusion.z < 0.0);
assert_eq!((arcs.len(), lines.len()), (1, 1), "{objects:?}");
let p = polyline(arcs[0]);
assert!(p.elevation == 0.0 && p.vertices[0].bulge != 0.0 && lines[0].common.extrusion == Vec3::Z, "{objects:?}");
}
}
#[test]
fn join_continues_from_a_sloped_lines_far_end_height() {
// AutoCAD 2024: from a line at Z 5, a sloped line down to Z 0 and a line on at Z 0 both join
// ("2 segments added"), at the polyline's end and at its start alike, the sloped line drawn
// either way. AutoCAD makes that polyline in the lines' vertical plane; a CADCraft polyline
// stays at the source's elevation.
for (base, sloped, next) in [
([[0.0, 0.0, 5.0], [10.0, 0.0, 5.0]], [[10.0, 0.0, 5.0], [20.0, 0.0, 0.0]], [[20.0, 0.0, 0.0], [30.0, 0.0, 0.0]]),
([[0.0, 0.0, 5.0], [10.0, 0.0, 5.0]], [[20.0, 0.0, 0.0], [10.0, 0.0, 5.0]], [[20.0, 0.0, 0.0], [30.0, 0.0, 0.0]]),
([[10.0, 0.0, 5.0], [20.0, 0.0, 5.0]], [[0.0, 0.0, 0.0], [10.0, 0.0, 5.0]], [[-10.0, 0.0, 0.0], [0.0, 0.0, 0.0]]),
([[10.0, 0.0, 5.0], [20.0, 0.0, 5.0]], [[10.0, 0.0, 5.0], [0.0, 0.0, 0.0]], [[-10.0, 0.0, 0.0], [0.0, 0.0, 0.0]]),
] {
let mut s = Session::new();
let h = line(&mut s, base[0], base[1]);
let a = line(&mut s, sloped[0], sloped[1]);
let b = line(&mut s, next[0], next[1]);
let r = s.execute("pedit", &json!({ "handle": h.hex(), "option": "join", "join": [a.hex(), b.hex()] })).unwrap();
assert_eq!(r["joined"], json!(2), "{base:?}: {r}");
assert_eq!(polyline(&entity(&s, h)).vertices.len(), 4);
}
}
#[test]
fn a_chain_closes_only_at_one_height() {
// AutoCAD 2024: three sides of a triangle at Z 5 join into a closed polyline; with its last
// side at Z 0, that side stays a line and the polyline stays open ("1 segments added").
for (last_z, joined, closed) in [(5.0, 2, true), (0.0, 1, false)] {
let mut s = Session::new();
let h = line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
let a = line(&mut s, [10.0, 0.0, 5.0], [10.0, 10.0, 5.0]);
let b = line(&mut s, [10.0, 10.0, last_z], [0.0, 0.0, last_z]);
let r = s.execute("pedit", &json!({ "handle": h.hex(), "option": "join", "join": [a.hex(), b.hex()] })).unwrap();
assert_eq!(r["joined"], json!(joined), "last side at {last_z}: {r}");
assert_eq!(polyline(&entity(&s, h)).closed, closed, "last side at {last_z}");
}
// A line at Z 5 and a sloped line back over it to Z 0: the ends meet in plan at Z 5 and at Z 0,
// and the polyline stays open (AutoCAD 2024: "1 segments added", 70 = 0).
let mut s = Session::new();
let h = line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
let back = line(&mut s, [10.0, 0.0, 5.0], [0.0, 0.0, 0.0]);
assert!(joins(&mut s, h, back));
let p = polyline(&entity(&s, h));
assert_eq!((p.vertices.len(), p.closed), (3, false));
}
#[test]
fn join_takes_a_sloped_line_only_in_one_plane_with_the_polyline_and_every_line_picked() {
// AutoCAD 2024 joins only objects in one plane with the polyline: the plane the polyline and
// every line picked share, when they share one, else the polyline's own, flat, where no sloped
// line lies. From a line at Z 5, (0,0) to (10,0):
let cases: [(&str, &[[[f64; 3]; 2]], usize); 4] = [
// a sloped line at right angles in plan, a tilted plane: "1 segments added";
("at an angle", &[[[10.0, 0.0, 5.0], [10.0, 10.0, 0.0]]], 1),
// a triangle at Z 5 whose last side slopes from (10,10,5) to (0,0,0): that side stays a line;
("a triangle's sloped side", &[[[10.0, 0.0, 5.0], [10.0, 10.0, 5.0]], [[10.0, 10.0, 5.0], [0.0, 0.0, 0.0]]], 1),
// a corner at Z 5, then a sloped line on in plan: the sloped line stays a line;
("after a corner", &[[[10.0, 0.0, 5.0], [10.0, 10.0, 5.0]], [[10.0, 10.0, 5.0], [10.0, 20.0, 0.0]]], 1),
// a sloped line on in plan, then a line at Z 0 from its foot turning off their vertical
// plane: the three share no plane, and neither joins ("0 segments added").
("then a turn", &[[[10.0, 0.0, 5.0], [20.0, 0.0, 0.0]], [[20.0, 0.0, 0.0], [20.0, 10.0, 0.0]]], 0),
];
for (what, lines, joined) in cases {
let mut s = Session::new();
let h = line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
let picked: Vec<String> = lines.iter().map(|[a, b]| line(&mut s, *a, *b).hex()).collect();
let r = s.execute("pedit", &json!({ "handle": h.hex(), "option": "join", "join": picked })).unwrap();
assert_eq!(r["joined"], json!(joined), "{what}: {r}");
let left = s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count();
assert_eq!(left, lines.len() - joined, "{what}");
}
// A sloped line on in plan, then an arc at Z 0 from its foot: the line joins, the arc, which
// lies flat, doesn't ("1 segments added").
let mut s = Session::new();
let h = line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
let l = line(&mut s, [10.0, 0.0, 5.0], [20.0, 0.0, 0.0]);
let a = arc(&mut s, [20.0, 5.0, 0.0], 5.0, 270.0, 0.0);
let r = s.execute("pedit", &json!({ "handle": h.hex(), "option": "join", "join": [l.hex(), a.hex()] })).unwrap();
assert_eq!(r["joined"], json!(1), "{r}");
assert!(s.doc().unwrap().entity(l).is_none() && s.doc().unwrap().entity(a).is_some());
}
#[test]
fn join_meets_within_the_fuzz_in_plan_and_1e_6_in_height() {
// The JSON form's fuzz bridges a gap in plan only: a line 0.3 off the end joins with fuzz 0.5
// at the polyline's height, to within 1e-6, and not 0.001 above it.
for (z, want) in [(5.0, true), (5.0 + 1e-9, true), (5.001, false)] {
let mut s = Session::new();
let h = line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
let o = line(&mut s, [10.3, 0.0, z], [10.3, 5.0, z]);
let r = s.execute("pedit", &json!({ "handle": h.hex(), "option": "join", "join": [o.hex()], "fuzz": 0.5 })).unwrap();
assert_eq!(r["joined"] == json!(1), want, "Z {z}: {r}");
}
// Multiple's Join takes the line 0.001 above too, as it takes one at any height.
let mut s = Session::new();
line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
line(&mut s, [10.3, 0.0, 5.001], [10.3, 5.0, 5.001]);
s.cmdline("pedit m 5,0 10.3,2.5").unwrap();
s.cmdline("").unwrap();
s.cmdline("y j 0.5").unwrap();
s.cmdline("").unwrap();
assert_eq!(s.doc().unwrap().model.iter().count(), 1);
}
#[test]
fn the_command_line_converts_and_joins_the_same_way() {
// PEDIT typed: a mirrored line at Z 5 becomes a polyline at elevation 5 facing up, and Join
// leaves a line at Z 0 off it ("0 segments added to polyline").
let mut s = Session::new();
let h = line(&mut s, [0.0, 0.0, 5.0], [10.0, 0.0, 5.0]);
face_down(&mut s, h);
let other = line(&mut s, [10.0, 0.0, 0.0], [10.0, 5.0, 0.0]);
s.cmdline("pedit 5,0 y").unwrap();
let e = entity(&s, h);
assert_eq!((polyline(&e).elevation, e.common.extrusion), (5.0, Vec3::Z));
let n = s.log.len();
s.cmdline("j 10,2.5").unwrap();
s.cmdline("").unwrap();
assert!(s.log[n..].iter().any(|l| l.contains("0 segments added to polyline")), "{:?}", &s.log[n..]);
assert!(s.doc().unwrap().entity(other).is_some());
s.cmdline("").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
}
-253
View File
@@ -1,253 +0,0 @@
//! QLEADER at the command line as AutoCAD 2024 runs it with its default settings (accoreconsole,
//! `(command "_.QLEADER" ...)` on a metric drawing, then `entget` of the LEADER and the MTEXT):
//! up to three points, a text width, lines of text; the text sits DIMGAP past the leader's end
//! with the middle of its first line level with it on the right, of its last line on the left.
use cadcraft_engine::doc::EntityKind;
use cadcraft_engine::geom::Vec2;
use cadcraft_engine::{Input, Session};
use serde_json::json;
/// What QLEADER drew: the leader's vertices, and the text's insertion point, height, width,
/// attachment and contents (rounded to 1e-9).
type Drawn = (Vec<(f64, f64)>, Option<((f64, f64), f64, f64, u8, String)>);
fn drawn(s: &Session) -> Drawn {
let r = |v: f64| (v * 1e9).round() / 1e9;
let d = s.doc().unwrap();
let leader = d
.model
.iter()
.find_map(|e| if let EntityKind::Leader(l) = &e.kind { Some(l.vertices.iter().map(|p| (r(p.x), r(p.y))).collect()) } else { None });
let text = d.model.iter().find_map(|e| match &e.kind {
EntityKind::MText(m) => Some(((r(m.insert.x), r(m.insert.y)), r(m.height), r(m.width), m.attach, m.contents.clone())),
_ => None,
});
(leader.unwrap_or_default(), text)
}
/// A drawing with the measured scripts' dimension settings: DIMTAD 1, DIMGAP 0.625, DIMASZ 2.5,
/// DIMSCALE 1 and DIMTXT 2.5.
fn session() -> Session {
let mut s = Session::new();
for (name, v) in [("DIMTAD", 1.0), ("DIMGAP", 0.625), ("DIMASZ", 2.5), ("DIMSCALE", 1.0), ("DIMTXT", 2.5)] {
s.execute("setvar", &json!({ "name": name, "value": v })).unwrap();
}
s
}
/// Types QLEADER then each of `inputs`, and checks it ended.
fn qleader(s: &mut Session, inputs: &[&str]) {
s.cmdline("QLEADER").unwrap();
for t in inputs {
s.cmdline(t).unwrap();
}
assert!(s.running.is_none(), "{inputs:?}: {}", s.prompt_text());
}
#[test]
fn qleader_places_the_text_as_autocad_does() {
// (inputs, AutoCAD's leader vertices, text insertion point, width, attachment, contents)
type Case<'a> = (&'a [&'a str], &'a [(f64, f64)], (f64, f64), f64, u8, &'a str);
let cases: [Case; 8] = [
// Three points, the last segment level: no hook line.
(&["0,0", "20,15", "40,15", "0", "ABC", ""], &[(0.0, 0.0), (20.0, 15.0), (40.0, 15.0)], (40.625, 16.25), 0.0, 1, "ABC"),
// Two points: a hook line DIMASZ (2.5) long into the end.
(&["0,0", "20,15", "", "0", "ABC", ""], &[(0.0, 0.0), (17.5, 15.0), (20.0, 15.0)], (20.625, 16.25), 0.0, 1, "ABC"),
(
&["0,0", "20,15", "35,30", "20", "AB", "CD", ""],
&[(0.0, 0.0), (20.0, 15.0), (32.5, 30.0), (35.0, 30.0)],
(35.625, 31.25),
20.0,
1,
"AB\\PCD",
),
// Running left: the middle of the last line level with the end.
(&["0,0", "-20,15", "-40,15", "0", "AB", "CD", ""], &[(0.0, 0.0), (-20.0, 15.0), (-40.0, 15.0)], (-40.625, 13.75), 0.0, 9, "AB\\PCD"),
(&["0,0", "-20,15", "-40,15", "0", "A", "B", "C", ""], &[(0.0, 0.0), (-20.0, 15.0), (-40.0, 15.0)], (-40.625, 13.75), 0.0, 9, "A\\PB\\PC"),
// A short leader running left: the hook line comes from past the start.
(&["0.5,0.25", "0.48,0.265", "", "0", "ABC", ""], &[(0.5, 0.25), (2.98, 0.265), (0.48, 0.265)], (-0.145, -0.985), 0.0, 9, "ABC"),
// Straight up: it counts as running right.
(&["0,0", "0,20", "", "0", "ABC", ""], &[(0.0, 0.0), (-2.5, 20.0), (0.0, 20.0)], (0.625, 21.25), 0.0, 1, "ABC"),
// Survey coordinates, running left.
(
&["612345.678,2398765.432", "612325.678,2398780.432", "612305.678,2398780.432", "0", "ABC", ""],
&[(612345.678, 2398765.432), (612325.678, 2398780.432), (612305.678, 2398780.432)],
(612305.053, 2398779.182),
0.0,
9,
"ABC",
),
];
for (inputs, leader, at, width, attach, text) in cases {
let mut s = session();
qleader(&mut s, inputs);
assert_eq!(drawn(&s), (leader.to_vec(), Some((at, 2.5, width, attach, text.to_string()))), "{inputs:?}");
}
}
#[test]
fn qleader_scales_with_dimscale_and_ignores_dimtad() {
// DIMGAP 2 and DIMSCALE 2: text 5 high, 4 past the end; the hook line 5 long.
let mut s = session();
s.execute("setvar", &json!({ "name": "DIMGAP", "value": 2.0 })).unwrap();
s.execute("setvar", &json!({ "name": "DIMSCALE", "value": 2.0 })).unwrap();
qleader(&mut s, &["0,0", "20,15", "35,30", "0", "ABC", ""]);
let want = vec![(0.0, 0.0), (20.0, 15.0), (30.0, 30.0), (35.0, 30.0)];
assert_eq!(drawn(&s), (want, Some(((39.0, 32.5), 5.0, 0.0, 1, "ABC".to_string()))));
// DIMTAD 0 or 1, the same place.
for tad in [0, 1] {
let mut s = session();
s.execute("setvar", &json!({ "name": "DIMTAD", "value": tad })).unwrap();
qleader(&mut s, &["0,0", "20,15", "40,15", "0", "ABC", ""]);
assert_eq!(drawn(&s).1, Some(((40.625, 16.25), 2.5, 0.0, 1, "ABC".to_string())), "DIMTAD {tad}");
}
}
#[test]
fn qleader_prompts_and_its_width() {
let mut s = session();
let mut asked = Vec::new();
s.cmdline("QLEADER").unwrap();
for t in ["0,0", "20,15", "40,15", "50,15", "ABC", ""] {
asked.push(s.current_prompt().unwrap().display());
s.cmdline(t).unwrap();
}
assert_eq!(
asked,
[
"Specify first leader point, or [Settings] <Settings>:",
"Specify next point:",
"Specify next point:",
"Specify text width <0>:",
"Enter first line of annotation text <Mtext>:",
"Enter next line of annotation text:",
]
);
// A point gives the width as its distance from the end, so Dynamic Input shows a distance.
assert_eq!(drawn(&s).1.map(|t| t.2), Some(10.0));
let mut s = session();
s.cmdline("QLEADER").unwrap();
for t in ["0,0", "20,15", "40,15"] {
s.cmdline(t).unwrap();
}
assert!(s.current_prompt().unwrap().distance);
// Text that isn't a distance is refused and asked again; Enter is no width.
let _ = s.cmdline("abc");
assert!(s.log.iter().any(|l| l.contains("Requires numeric distance or two points.")), "{:?}", s.log);
assert_eq!(s.current_prompt().unwrap().display(), "Specify text width <0>:");
for t in ["", "ABC", ""] {
s.cmdline(t).unwrap();
}
assert!(s.running.is_none());
assert_eq!(drawn(&s).1.map(|t| t.2), Some(0.0));
// A point so far off that its distance overflows is refused like bad text.
let mut s = session();
s.cmdline("QLEADER").unwrap();
for p in [Vec2::new(0.0, 0.0), Vec2::new(1e308, 0.0)] {
s.input(Input::Point(p)).unwrap();
}
s.cmdline("").unwrap();
let _ = s.input(Input::Point(Vec2::new(-1e308, 0.0)));
assert!(s.log.iter().any(|l| l.contains("Requires numeric distance or two points.")), "{:?}", s.log);
assert_eq!(s.current_prompt().unwrap().display(), "Specify text width <0>:");
// A negative width is none. A width isn't remembered: AutoCAD 2024 offers 0 again after 20.
for width in ["-5", "20"] {
let mut s = session();
qleader(&mut s, &["0,0", "20,15", "40,15", width, "ABC", ""]);
assert_eq!(drawn(&s).1.map(|t| t.2), Some(width.parse::<f64>().unwrap().max(0.0)));
s.cmdline("QLEADER").unwrap();
for t in ["0,0", "20,15", "40,15"] {
s.cmdline(t).unwrap();
}
assert_eq!(s.current_prompt().unwrap().display(), "Specify text width <0>:", "{width}");
}
}
#[test]
fn a_click_at_the_text_prompts_is_no_line_of_text() {
let mut s = session();
s.cmdline("QLEADER").unwrap();
for t in ["0,0", "20,15", "40,15", "0"] {
s.cmdline(t).unwrap();
}
s.input(Input::Point(Vec2::new(5.0, 5.0))).unwrap();
assert_eq!(s.current_prompt().unwrap().display(), "Enter first line of annotation text <Mtext>:");
s.cmdline("AB").unwrap();
s.input(Input::Point(Vec2::new(5.0, 5.0))).unwrap();
assert_eq!(s.current_prompt().unwrap().display(), "Enter next line of annotation text:");
s.cmdline("CD").unwrap();
s.cmdline("").unwrap();
assert!(s.running.is_none());
assert_eq!(drawn(&s).1.map(|t| t.4), Some("AB\\PCD".to_string()));
}
#[test]
fn qleader_without_text_or_points() {
// Enter at the first line: the leader alone.
let mut s = session();
qleader(&mut s, &["0,0", "20,15", "40,15", "0", ""]);
assert_eq!(drawn(&s), (vec![(0.0, 0.0), (20.0, 15.0), (40.0, 15.0)], None));
// Sloped, without text: no hook line either (AutoCAD 2024: two vertices).
let mut s = session();
qleader(&mut s, &["0,0", "20,15", "", "0", ""]);
assert_eq!(drawn(&s), (vec![(0.0, 0.0), (20.0, 15.0)], None));
// Enter after one point: nothing.
let mut s = session();
qleader(&mut s, &["0,0", ""]);
assert_eq!(s.doc().unwrap().model.iter().count(), 0);
// Settings, typed or by Enter: no dialog yet, the first point is asked again.
for settings in ["S", ""] {
let mut s = session();
s.cmdline("QLEADER").unwrap();
s.cmdline(settings).unwrap();
assert!(s.log.iter().any(|l| l == "The QLEADER Settings dialog is not available yet."), "{settings:?}: {:?}", s.log);
assert_eq!(s.current_prompt().unwrap().display(), "Specify first leader point, or [Settings] <Settings>:", "{settings:?}");
}
// LE starts it too.
let mut s = session();
s.cmdline("LE").unwrap();
assert_eq!(s.current_prompt().unwrap().display(), "Specify first leader point, or [Settings] <Settings>:");
}
#[test]
fn qleader_by_json() {
let mut s = session();
let r = s.execute("qleader", &json!({ "points": [[0, 0], [20, 15], [35, 30]], "width": 20, "text": "AB\r\nCD" })).unwrap();
assert_eq!(r["handles"].as_array().map(Vec::len), Some(2));
let want = vec![(0.0, 0.0), (20.0, 15.0), (32.5, 30.0), (35.0, 30.0)];
assert_eq!(drawn(&s), (want, Some(((35.625, 31.25), 2.5, 20.0, 1, "AB\\PCD".to_string()))));
// Text with nothing on its lines is no text: the leader alone, without a hook line.
for text in ["", "\n", "\r\n\r\n"] {
let mut s = session();
let r = s.execute("qleader", &json!({ "points": [[0, 0], [20, 15]], "width": 0, "text": text })).unwrap();
assert_eq!(r["handles"].as_array().map(Vec::len), Some(1), "{text:?}");
assert_eq!(drawn(&s), (vec![(0.0, 0.0), (20.0, 15.0)], None), "{text:?}");
}
// Empty lines at the end are dropped: running left, the text sits as the command line puts it.
let mut s = session();
s.execute("qleader", &json!({ "points": [[0, 0], [-20, 15], [-40, 15]], "text": "AB\n\n" })).unwrap();
assert_eq!(drawn(&s).1, Some(((-40.625, 13.75), 2.5, 0.0, 9, "AB".to_string())));
// 2 or 3 points, a width of 0 or more, text as a string.
for bad in [
json!({ "points": [[0, 0]] }),
json!({ "points": [[0, 0], [1, 1], [2, 1], [3, 1]] }),
json!({ "points": [[0, 0], [1, 1]], "width": -1 }),
json!({ "points": [[0, 0], [1, 1]], "width": "x" }),
json!({ "points": [[0, 0], [1, 1]], "text": 5 }),
json!({ "points": [[0, 0], [1, 1]], "text": ["AB", "CD"] }),
] {
let before = s.doc().unwrap().model.iter().count();
assert!(s.execute("qleader", &bad).is_err(), "{bad}");
assert_eq!(s.doc().unwrap().model.iter().count(), before, "{bad}");
}
// A point that can't be read is named as such, not as missing points.
for (bad, says) in [
(json!({}), "`points` is required"),
(json!({ "points": null }), "`points` is required"),
(json!({ "points": [[0, 0], ["x", 1]] }), "`points` must be a list of [x, y] points"),
] {
let e = s.execute("qleader", &bad).unwrap_err().to_string();
assert!(e.contains(says), "{bad}: {e}");
}
}
+12 -4
View File
@@ -617,12 +617,20 @@ pub(crate) fn entity_tags(d: &Drawing, m: &MLeader, r: &Refs) -> Vec<Tag> {
p(&mut t, 10, b.scale);
f(&mut t, 43, b.rotation);
i(&mut t, 176, 1);
// Attribute values by their ATTDEF in the block, the definitions gathered by tag once.
let defs = d.block(&b.block).map(|blk| blk.attdefs_by_tag()).unwrap_or_default();
// Attribute values by their ATTDEF in the block.
let defs: Vec<(Handle, &str)> = d
.block(&b.block)
.map(|blk| {
blk.entities
.iter()
.filter_map(|e| if let EntityKind::AttDef(ad) = &e.kind { Some((e.handle, ad.tag.as_str())) } else { None })
.collect()
})
.unwrap_or_default();
let mut n = 0i64;
for a in &b.attribs {
let Some(def) = defs.get(&cadcraft_doc::TagKey(&a.tag)) else { continue };
s(&mut t, 330, &def.handle.hex());
let Some((h, _)) = defs.iter().find(|(_, tag)| tag.eq_ignore_ascii_case(&a.tag)) else { continue };
s(&mut t, 330, &h.hex());
i(&mut t, 177, n);
f(&mut t, 44, 0.0);
s(&mut t, 302, &a.text.value);
-10
View File
@@ -74,8 +74,6 @@ struct Rx {
block: Option<String>,
/// The points HATCH boundary curves may still be sampled into.
curves: hatch::CurvePoints,
/// LTYPE records read with only their first `MAX_LINETYPE_ELEMENTS` dash elements.
linetypes_cut: usize,
/// IMAGE entity handle, as read (a repeated one reassigned) → its IMAGEDEF handle (upper case).
image_defs: HashMap<Handle, String>,
}
@@ -294,14 +292,6 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize)
}
crate::dxf_raw::read(&secs, &mut d);
crate::dxf_clip::read(&mut d);
if rx.linetypes_cut > 0 {
let (n, max) = (rx.linetypes_cut, craft_dxf::lin_pat::MAX_LINETYPE_ELEMENTS);
d.read_notes.push(if n == 1 {
format!("DXF: 1 linetype has more than {max} dash elements; only its first {max} were read.")
} else {
format!("DXF: {n} linetypes have more than {max} dash elements; only the first {max} of each were read.")
});
}
if rx.curves.cut > 0 {
// Echoed on open, returned by OPEN and listed by the CLI, so a coarse boundary is never silent.
let n = rx.curves.cut;
+3 -13
View File
@@ -5,7 +5,6 @@ use super::{
VportConfig, VportTile, record_slices,
};
use cadcraft_fonts::windows::windows_font;
use craft_dxf::lin_pat::MAX_LINETYPE_ELEMENTS;
pub(super) fn header(tags: &[Tag], d: &mut Drawing) {
let mut i = 0;
@@ -167,8 +166,7 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) {
continue;
}
linetype_names.insert(name.to_ascii_lowercase());
let (pattern, cut) = ltype_pattern(tg, &ltype_styles);
rx.linetypes_cut = rx.linetypes_cut.saturating_add(usize::from(cut));
let pattern = ltype_pattern(tg, &ltype_styles);
d.linetypes.push(Linetype { name, description: t.s(3).unwrap_or_default(), pattern });
}
"STYLE" => {
@@ -404,18 +402,10 @@ fn vport_record(d: &mut Drawing, t: &T, first_active: bool) {
/// LTYPE): each `49` length starts an element; `74` type flags (1 absolute rotation, 2 text,
/// 4 shape), `75` shape number, `340` STYLE, `46` scale, `50` rotation (radians), `44`/`45`
/// offset and `9` text follow it.
///
/// At most [`MAX_LINETYPE_ELEMENTS`] elements are read, the cap a `.lin` file has: the rest of
/// the pattern, with the text and shapes of its elements, is dropped and `true` comes back so
/// the reader can say so. The renderer copies and walks the whole pattern for every object
/// drawn with it, so an uncapped pattern made each redraw and export cost grow with its length.
fn ltype_pattern(tags: &[Tag], styles: &HashMap<String, String>) -> (Vec<DashElement>, bool) {
fn ltype_pattern(tags: &[Tag], styles: &HashMap<String, String>) -> Vec<DashElement> {
let mut out: Vec<DashElement> = Vec::new();
for t in tags.iter().take_while(|t| t.code < 1000) {
if t.code == 49 {
if out.len() >= MAX_LINETYPE_ELEMENTS {
return (out, true);
}
out.push(DashElement::dash(t.f64()));
continue;
}
@@ -442,5 +432,5 @@ fn ltype_pattern(tags: &[Tag], styles: &HashMap<String, String>) -> (Vec<DashEle
_ => {}
}
}
(out, false)
out
}
+1 -1
View File
@@ -8,7 +8,7 @@ use std::collections::{HashMap, HashSet};
use cadcraft_color::Color;
use cadcraft_doc::{
AssocSnap, Attrib, Block, Common, DimAssoc, DimKind, DimStyle, Dimension, Drawing, Entity, EntityKind, EntityStore, Gradient, Group, HAlign,
HVal, Handle, Hatch, Layout, Leader, Line, Lineweight, LwPolyline, MLeader, MLeaderStyle, MText, PageSetup, Point, Solid, Space, Table,
HVal, Handle, Hatch, Insert, Layout, Leader, Line, Lineweight, LwPolyline, MLeader, MLeaderStyle, MText, PageSetup, Point, Solid, Space, Table,
TableStyle, Text, Transparency, Ucs, VAlign, VportConfig, VportTile,
};
use cadcraft_geom::{Bounds2, Vec2, Vec3};
+9 -7
View File
@@ -1,7 +1,7 @@
use super::ctx::{AssocObj, Ctx};
use super::{
Attrib, Color, Common, DimKind, DimStyle, Dimension, Drawing, Entity, HAlign, HashMap, Lineweight, Text, Transparency, VAlign, Vec3, Version, W,
dxf_ext,
Attrib, Color, Common, DimKind, DimStyle, Dimension, Drawing, Entity, EntityKind, HAlign, HashMap, Insert, Lineweight, Text, Transparency,
VAlign, Vec3, Version, W, dxf_ext,
};
/// `AcadAnnotative` xdata marking an annotative style.
@@ -145,11 +145,13 @@ pub(super) fn layer_and_props(w: &mut W, c: &Common, base: Option<&Common>) {
}
}
/// The properties attribute `a` of block reference `e` is drawn with: its own, else its
/// definition's, from the block's definitions by tag `defs`; an attribute defined on layer 0 is on
/// the reference's layer. Also the definition's properties.
pub(super) fn attrib_common(e: &Entity, defs: &std::collections::BTreeMap<cadcraft_doc::TagKey<'_>, &Entity>, a: &Attrib) -> (Common, Common) {
let def = defs.get(&cadcraft_doc::TagKey(&a.tag));
/// The properties attribute `a` of block reference `e` (of `ins`) is drawn with: its own, else its
/// definition's; an attribute defined on layer 0 is on the reference's layer. Also the
/// definition's properties.
pub(super) fn attrib_common(d: &Drawing, e: &Entity, ins: &Insert, a: &Attrib) -> (Common, Common) {
let def = d
.block(&ins.block)
.and_then(|b| b.entities.iter().find(|be| matches!(&be.kind, EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(&a.tag))));
let base = def.map(|de| de.common.clone()).unwrap_or_default();
let mut c = a.props.over(&base);
if c.layer == "0" {
+1 -3
View File
@@ -372,15 +372,13 @@ fn write_insert_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: b
w.f(45, i.row_spacing);
}
if !i.attribs.is_empty() {
// The block's definitions by tag, gathered once for all the attributes (#1923).
let defs = d.block(&i.block).map(|b| b.attdefs_by_tag()).unwrap_or_default();
for (index, a) in i.attribs.iter().enumerate() {
let ah = w.h();
w.s(0, "ATTRIB");
w.s(5, ah);
w.s(330, e.handle.hex());
w.s(100, "AcDbEntity");
let (c, base) = attrib_common(e, &defs, a);
let (c, base) = attrib_common(d, e, i, a);
layer_and_props(w, &c, Some(&base));
// Hidden with its definition (a dynamic block's visibility state hides it).
if !base.visible {
-47
View File
@@ -109,53 +109,6 @@ fn attributes_without_properties_stay_without() {
assert!(a.iter().all(|a| a.props.is_empty()), "{a:?}");
}
#[test]
fn many_attributes_are_written_without_comparing_every_pair_with_the_definitions() {
// #1923: a reference with N attributes, and a multileader's block content with N, of a block
// with N definitions, the tags N long ones alike up to their last characters, no attribute's
// a definition's. Looking for each attribute's definition by comparing it with every one (for
// the ATTRIB's properties, the multileader's attribute values) cost N x N comparisons of whole
// tags (many seconds here); the definitions gathered by tag once cost milliseconds.
const N: usize = 8000;
let tag = |kind: char, i: usize| format!("{}{kind}{i:05}", "T".repeat(150));
let mut d = Drawing::new_metric();
let mut blk = Block::new("TAGS");
for (h, i) in (0x100..).zip(0..N) {
blk.entities.push(Entity::new(Handle(h), EntityKind::AttDef(attrib(&tag('D', i), 0.0, AttribProps::default()))));
}
d.blocks.insert(blk.name.clone(), Arc::new(blk));
let ins = Insert {
block: "TAGS".into(),
insert: Vec3::ZERO,
scale: Vec3::new(1.0, 1.0, 1.0),
rotation: 0.0,
attribs: (0..N).map(|i| attrib(&tag('A', i), 0.0, AttribProps::default())).collect(),
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
};
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins.clone())).expect("add");
let m = MLeader {
leaders: vec![vec![Vec3::ZERO]],
landing: Vec3::new(10.0, 0.0, 0.0),
dogleg: 1.0,
text: None,
style: "Standard".into(),
arrow_size: 1.0,
spline: false,
block: Some(ins),
};
d.add(&Space::Model, Common::default(), EntityKind::MLeader(m)).expect("add");
// A version with native multileaders: R2000 writes one as a leader and a block reference.
let opts = cadcraft_io::SaveOptions { version: Some(cadcraft_io::Version::R2007), binary: false };
let t = std::time::Instant::now();
let dxf = String::from_utf8(cadcraft_io::write_with(&d, "x.dxf", &opts).expect("write")).expect("text");
assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed());
assert!(dxf.contains("MULTILEADER") && dxf.contains("ATTRIB"));
}
#[test]
fn hostile_attrib_groups_do_not_panic() {
let dxf = "0\nSECTION\n2\nENTITIES\n0\nINSERT\n5\n20\n8\n0\n66\n1\n2\nNOPE\n10\n0\n20\n0\n30\n0\n\
-92
View File
@@ -1,92 +0,0 @@
//! An LTYPE record keeps at most `MAX_LINETYPE_ELEMENTS` dash elements on DXF read, the cap a
//! `.lin` file has (#1923, F-05): the rest of its pattern is dropped, opening the file says so,
//! and saving writes the elements kept.
use cadcraft_doc::library::files::MAX_LINETYPE_ELEMENTS as MAX;
use cadcraft_io::{read_dxf, write_dxf};
/// Element `i`: a dash `(i + 1) / 100` long for even `i`, a gap that long for odd `i`.
fn length(i: usize) -> f64 {
let l = (i + 1) as f64 / 100.0;
if i.is_multiple_of(2) { l } else { -l }
}
/// An LTYPE record `name` of `elements` elements, the last one carrying the text `last_text`.
fn ltype(name: &str, elements: usize, last_text: &str) -> String {
let mut s = format!("0\nLTYPE\n2\n{name}\n70\n0\n3\n{name} dashes\n72\n65\n73\n{elements}\n40\n1\n");
for i in 0..elements {
s.push_str(&format!("49\n{}\n", length(i)));
if i + 1 == elements {
s.push_str(&format!("74\n2\n75\n0\n46\n0.1\n50\n0\n44\n0\n45\n0\n9\n{last_text}\n"));
} else {
s.push_str("74\n0\n");
}
}
s
}
/// A DXF of these LTYPE records and one LINE drawn with the first.
fn dxf(ltypes: &[String], line_type: &str) -> String {
let mut s = String::from("0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nLTYPE\n70\n1\n");
for l in ltypes {
s.push_str(l);
}
s.push_str(&format!("0\nENDTAB\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n0\nLINE\n8\n0\n6\n{line_type}\n10\n0\n20\n0\n30\n0\n11\n10\n21\n0\n31\n0\n"));
s.push_str("0\nENDSEC\n0\nEOF\n");
s
}
/// The value of group `code` in the LTYPE record named `name` of a written DXF.
fn ltype_group<'a>(text: &'a str, name: &str, code: &str) -> Option<&'a str> {
let lines: Vec<&str> = text.lines().map(str::trim).collect();
let pairs: Vec<(&str, &str)> = lines.chunks(2).filter_map(|p| Some((*p.first()?, *p.get(1)?))).collect();
// A record runs from its `0` group to the next one.
let starts: Vec<usize> = (0..pairs.len()).filter(|&i| pairs[i].0 == "0").chain([pairs.len()]).collect();
starts
.windows(2)
.map(|w| &pairs[w[0]..w[1]])
.find(|r| r[0] == ("0", "LTYPE") && r.contains(&("2", name)))?
.iter()
.find(|p| p.0 == code)
.map(|p| p.1)
}
#[test]
fn an_ltype_past_the_element_cap_keeps_its_first_elements_and_says_so() {
let d = read_dxf(dxf(&[ltype("LONG", MAX + 1, "DROPPED")], "LONG").as_bytes()).expect("read");
let lt = d.linetype("LONG").expect("the linetype is kept");
let lengths: Vec<f64> = lt.pattern.iter().map(|e| e.length).collect();
assert_eq!(lengths, (0..MAX).map(length).collect::<Vec<_>>());
// The text of the dropped element is not moved onto the last element kept.
assert!(lt.pattern.iter().all(|e| e.text.is_none() && e.shape.is_none()), "{:?}", lt.pattern.last());
assert!(matches!(d.read_notes.as_slice(), [note] if note.contains("1 linetype") && note.contains(&MAX.to_string())), "{:?}", d.read_notes);
assert!(d.model.iter().any(|e| e.common.linetype == "LONG"), "the line keeps its linetype");
// Saved, the record holds and counts the elements kept; reopened, it reads whole, without a note.
let text = write_dxf(&d);
assert_eq!(ltype_group(&text, "LONG", "73"), Some(MAX.to_string().as_str()));
let back = read_dxf(text.as_bytes()).expect("reopen");
assert_eq!(back.linetype("LONG"), Some(lt));
assert!(back.read_notes.is_empty(), "{:?}", back.read_notes);
}
#[test]
fn an_ltype_at_the_element_cap_reads_whole() {
let d = read_dxf(dxf(&[ltype("FULL", MAX, "KEPT")], "FULL").as_bytes()).expect("read");
let lt = d.linetype("FULL").expect("FULL");
let lengths: Vec<f64> = lt.pattern.iter().map(|e| e.length).collect();
assert_eq!(lengths, (0..MAX).map(length).collect::<Vec<_>>());
assert_eq!(lt.pattern.last().and_then(|e| e.text.as_deref()), Some("KEPT"));
assert!(d.read_notes.is_empty(), "{:?}", d.read_notes);
}
/// One note counts every linetype cut; a repeated name is not read again (the first definition
/// wins), so it is not counted.
#[test]
fn one_note_counts_the_linetypes_cut() {
let records = [ltype("A", MAX + 1, "x"), ltype("B", MAX + 40, "y"), ltype("SHORT", 3, "z"), ltype("a", MAX + 1, "again")];
let d = read_dxf(dxf(&records, "A").as_bytes()).expect("read");
assert!(matches!(d.read_notes.as_slice(), [note] if note.contains("2 linetypes")), "{:?}", d.read_notes);
for (name, n) in [("A", MAX), ("B", MAX), ("SHORT", 3)] {
assert_eq!(d.linetype(name).map(|l| l.pattern.len()), Some(n), "{name}");
}
}
-1
View File
@@ -51,7 +51,6 @@ mod layout_plot_window;
mod leader_vertex_elevation;
#[cfg(not(target_arch = "wasm32"))]
mod low_handseed;
mod ltype_element_cap;
mod minsert_marker;
mod mleader_content;
mod mleader_roundtrip;
+4 -22
View File
@@ -1,7 +1,3 @@
use std::collections::BTreeMap;
use cadcraft_doc::TagKey;
use super::draw::entity;
use super::props::{resolve, resolve_common, transparency};
use super::text_entity::{mtext, place_text_entity};
@@ -70,9 +66,6 @@ pub(crate) fn insert(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc:
if let Some(blk) = ctx.d.block(&ins.block) {
// ATTMODE (ATTDISP) for the block's constant attributes, as for its other attributes.
let attmode = ctx.d.header.i64("ATTMODE", 1);
// The reference's attributes by tag, gathered at the first constant definition that asks
// and kept for the others and every copy.
let mut carried = None;
let cols = ins.cols.clamp(1, 10_000);
let rows = ins.rows.clamp(1, 10_000);
'copies: for r in 0..rows {
@@ -98,7 +91,7 @@ pub(crate) fn insert(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc:
// Attribute definitions inside blocks are not drawn (the reference's attributes
// are), except a constant one: its value draws with the block's geometry.
if let EntityKind::AttDef(a) = &be.kind {
if let Some(text) = constant_attribute(be, a, ins, attmode, &mut carried) {
if let Some(text) = constant_attribute(be, a, ins, attmode) {
entity(target, &sub, &text);
}
continue;
@@ -130,20 +123,9 @@ pub(crate) fn insert(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc:
/// its value, with the definition's properties. A constant value isn't copied into the reference's
/// attributes, so it is drawn from the definition. `None` for a variable definition (its attribute
/// is drawn instead), one ATTMODE hides (0 hides all, 1 the invisible ones), and one the reference
/// carries an attribute for (that attribute is drawn, not both). `carried`: the reference's
/// attributes by tag, gathered here on first use so that each definition costs one lookup (#1923).
fn constant_attribute<'i>(
be: &Entity,
a: &cadcraft_doc::Attrib,
ins: &'i cadcraft_doc::Insert,
attmode: i64,
carried: &mut Option<BTreeMap<TagKey<'i>, &'i cadcraft_doc::Attrib>>,
) -> Option<Entity> {
if !a.constant
|| attmode == 0
|| (a.invisible && attmode != 2)
|| carried.get_or_insert_with(|| ins.attribs_by_tag()).contains_key(&TagKey(&a.tag))
{
/// carries an attribute for (that attribute is drawn, not both).
fn constant_attribute(be: &Entity, a: &cadcraft_doc::Attrib, ins: &cadcraft_doc::Insert, attmode: i64) -> Option<Entity> {
if !a.constant || attmode == 0 || (a.invisible && attmode != 2) || ins.attribs.iter().any(|r| r.tag.eq_ignore_ascii_case(&a.tag)) {
return None;
}
let kind = match a.multiline_text() {
+20 -29
View File
@@ -1,7 +1,6 @@
use super::blocks::{insert, proxy, sub_ctx};
use super::dim_draw::{MAX_FILL_SOLIDS, MAX_FILL_TEXTS, block_text_box, dim_text_fill, dimension, dimension_in, solid_covers, starts_text_marks};
use super::display::{Kind, NO_LAYER, VIEWPORT_CONTENT};
use super::linetype::Layout;
use super::props::{resolve, transparency};
use super::text_entity::{mtext, place_text_entity};
use super::{
@@ -90,11 +89,11 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
};
let tol = b.opts.tolerance / ctx.xf.scale_factor().max(1e-12);
let lw = if b.opts.lineweights { lw } else { 0.0 };
// Stroke a run with the entity's linetype, laid out as `how` says.
let stroke_as = |b: &mut Builder, pts: &[Vec2], how: Layout| match lt.as_ref().filter(|_| b.opts.linetypes) {
// Stroke a polyline with the entity's linetype.
let stroke = |b: &mut Builder, pts: &[Vec2]| match lt.as_ref().filter(|_| b.opts.linetypes) {
Some(lt) => {
let min = b.opts.min_dash / ctx.xf.scale_factor().max(1e-12);
for dash in linetype::apply_as(pts, lt, ltscale, min, how) {
for dash in linetype::apply(pts, lt, ltscale, min) {
if dash.len() == 1 {
if let Some(p) = dash.first() {
b.point(ctx, rgb, *p);
@@ -105,31 +104,13 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
}
// Text and shapes embedded in the linetype (shapes when their SHX file is found).
if b.opts.text {
for sh in linetype_text::texts(ctx.d, pts, lt, ltscale, min, how) {
for sh in linetype_text::texts(ctx.d, pts, lt, ltscale, min) {
b.shaped(ctx, rgb, lw, &sh);
}
}
}
None => b.polyline(ctx, rgb, lw, pts),
};
let stroke = |b: &mut Builder, pts: &[Vec2]| stroke_as(b, pts, Layout::Open);
// A polyline's centre line: with PLINEGEN the pattern runs along the whole of it (stretched
// around a closed one from its second vertex, as AutoCAD lays it); otherwise it restarts at
// every vertex.
let centre_line = |b: &mut Builder, p: &cadcraft_doc::LwPolyline| {
let pl = Polyline { vertices: p.vertices.clone(), closed: p.closed };
if p.plinegen && p.closed {
stroke_as(b, &pl.tessellate(tol), Layout::Closed { anchor: wide::second_vertex_at(p, tol) });
} else if !b.opts.linetypes || p.plinegen || lt.is_none() {
stroke(b, &pl.tessellate(tol));
} else {
for s in pl.segments() {
let mut pts = Vec::new();
s.tessellate(tol, &mut pts);
stroke(b, &pts);
}
}
};
match &e.kind {
EntityKind::Text(t) => {
if !b.opts.text {
@@ -199,11 +180,22 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
}
}
} else {
// Fill off: the centre line, dashed as a polyline without width is.
centre_line(b, p);
let pl = Polyline { vertices: p.vertices.clone(), closed: p.closed };
stroke(b, &pl.tessellate(tol));
}
}
EntityKind::LwPolyline(p) => {
let pl = Polyline { vertices: p.vertices.clone(), closed: p.closed };
if !b.opts.linetypes || p.plinegen || lt.is_none() {
stroke(b, &pl.tessellate(tol));
} else {
for s in pl.segments() {
let mut pts = Vec::new();
s.tessellate(tol, &mut pts);
stroke(b, &pts);
}
}
}
EntityKind::LwPolyline(p) => centre_line(b, p),
EntityKind::Solid(s) | EntityKind::Trace(s) => {
let c = &s.corners;
let q = [c[0].xy(), c[1].xy(), c[3].xy(), c[2].xy()];
@@ -257,16 +249,15 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
s.tessellate(tol, &mut pts);
stroke(b, &pts);
}
// Closed runs from angle 0 (or the ellipse's start parameter).
Prim::Circle(c) => {
let mut pts = Vec::new();
c.tessellate(tol, &mut pts);
stroke_as(b, &pts, Layout::Closed { anchor: 0.0 });
stroke(b, &pts);
}
Prim::Ellipse(el) => {
let mut pts = Vec::new();
el.tessellate(tol, &mut pts);
stroke_as(b, &pts, if el.is_full() { Layout::Closed { anchor: 0.0 } } else { Layout::Open });
stroke(b, &pts);
}
Prim::Spline(s) => stroke(b, &s.tessellate(tol)),
Prim::Point(p) => b.point(ctx, rgb, p),
+101 -392
View File
@@ -1,255 +1,117 @@
//! Apply a dash pattern along a run (a polyline), laid out as AutoCAD lays it out.
//!
//! Measured on AutoCAD 2024 plots (DWG To PDF at a fixed scale, every stroke read back), with the
//! pattern [2, -1] unless said otherwise:
//! - An open run (a line, an arc, a spline, an open polyline with PLINEGEN, each segment of one
//! without) shorter than one period is drawn continuous. Otherwise the pattern is centred:
//! with n = floor(L / period) and p0 = (n·period + first − L) / 2, the elements sit where they
//! would if the pattern started at −p0, except that the first dash starts at the run's start
//! and the last ends at its end. A line 7 long gets [0, 1.5] [2.5, 4.5] [5.5, 7]; 6 gets
//! [0, 1] [2, 4] [5, 6]; 5.99 gets [0, 2.495] [3.495, 5.99]; 2.99 is continuous. A pattern
//! opening with a dot puts dots at both ends ([0, −1] on 5.3: 0, 1.15, 2.15, 3.15, 4.15, 5.3).
//! - A closed run (a circle, a whole ellipse, a closed polyline with PLINEGEN) is stretched to
//! n = round(L / period) periods, one starting at its anchor: a circle of radius 2 is dashed
//! 0°–60°, 90°–150°…; a 5 × 5 square polyline gets 7 periods.
//! - A pattern opening with a gap (e0 < 0), with r = L − n·period and x = (r + e0) / 2: for
//! x < 0 the elements run from −p0; otherwise a piece [0, x] is drawn (a dot when x is 0),
//! then the elements from the period's second on, n − 1 whole periods, and a last piece 2x
//! long.
//! Apply a dash pattern along a polyline.
use cadcraft_doc::Linetype;
use cadcraft_geom::Vec2;
/// How a run lays its pattern out (see the module notes).
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Layout {
/// Centred on an open run.
Open,
/// Stretched around a closed run, a period starting `anchor` along it.
Closed { anchor: f64 },
}
/// Most periods a run is dashed over in a display build (`min_pattern` above 0, a view zoomed out
/// a lot); a longer run is drawn continuous. A plot or export has no zoom (`min_pattern` is 0), so
/// it keeps the pattern, bounded by [`MAX_ELEMENTS`] (#1069).
const MAX_PERIODS: f64 = 50_000.0;
/// Most pattern elements a run is laid out over (a long pattern repeated many times); beyond
/// that it is drawn continuous too.
const MAX_ELEMENTS: f64 = 2_000_000.0;
/// The drawn stretches of a run `len` long, as (start, end) along it (a dot: start == end), in
/// order; `None` when it is drawn continuous (shorter than one period, or repeating too often).
/// `pattern` is scaled; `min_pattern` is the caller's (see [`MAX_PERIODS`]).
fn layout(len: f64, pattern: &[f64], how: Layout, min_pattern: f64) -> Option<Vec<(f64, f64)>> {
let period: f64 = pattern.iter().map(|d| d.abs()).sum();
if !(len.is_finite() && period > 1e-12) || len < period || (min_pattern > 0.0 && len / period > MAX_PERIODS) {
return None;
}
if (len / period + 2.0) * pattern.len() as f64 > MAX_ELEMENTS {
return None;
}
let mut drawn = Vec::new();
let mut at = 0.0;
for &d in pattern {
if d >= 0.0 {
drawn.push((at, d));
}
at += d.abs();
}
if drawn.is_empty() {
return Some(Vec::new());
}
let first = pattern.first().copied().unwrap_or(0.0);
let out = match how {
Layout::Closed { anchor } => {
let n = (len / period).round().max(1.0);
let f = len / (n * period);
let a = if anchor.is_finite() { anchor.rem_euclid(period * f) } else { 0.0 };
let mut out = Vec::new();
for k in -1..=(n as i64) {
for &(o, e) in &drawn {
let s0 = a + k as f64 * period * f + o * f;
let s1 = s0 + e * f;
if e == 0.0 {
if (0.0..len).contains(&s0) {
out.push((s0, s0));
}
} else if s1.min(len) > s0.max(0.0) {
out.push((s0.max(0.0), s1.min(len)));
}
}
}
out
}
Layout::Open if first < 0.0 => gap_first(len, pattern, period),
Layout::Open => {
// A length at a multiple of the period: 6.0 / 3 is 2, not 1.
let n = (len / period + 1e-9).floor();
let p0 = (n * period + first - len) / 2.0;
let count = n as usize * drawn.len() + 1;
let mut out = Vec::with_capacity(count);
for i in 0..count {
let Some(&(o, e)) = drawn.get(i % drawn.len()) else { continue };
let mut s0 = (i / drawn.len()) as f64 * period + o - p0;
let mut s1 = s0 + e;
if i == 0 {
s0 = 0.0;
if first == 0.0 {
s1 = 0.0;
}
}
if i + 1 == count {
s1 = len;
if first == 0.0 {
s0 = len;
}
}
out.push((s0, s1));
}
out
}
};
Some(out)
}
/// [`layout`] of an open run for a pattern opening with a gap.
fn gap_first(len: f64, pattern: &[f64], period: f64) -> Vec<(f64, f64)> {
let first = pattern.first().copied().unwrap_or(0.0);
let n = (len / period + 1e-9).floor();
let x = (len - n * period + first) / 2.0;
let mut out = Vec::new();
if x < 0.0 {
let p0 = (n * period + first - len) / 2.0;
let mut u = 0.0;
for _ in 0..(n as usize + 2) {
for &e in pattern {
let (a, b) = (u, u + e.abs());
u = b;
if e < 0.0 {
continue;
}
let b = b.min(p0 + len);
if b > a.max(p0) || (e == 0.0 && (p0..=p0 + len).contains(&a)) {
out.push((a.max(p0) - p0, b - p0));
}
}
}
} else {
out.push((0.0, x));
let mut pos = x;
let whole = pattern.iter().cycle().take(pattern.len() * (n as usize).saturating_sub(1));
for &e in pattern.iter().skip(1).chain(whole) {
if e >= 0.0 {
out.push((pos, pos + e));
}
pos += e.abs();
}
if x > 0.0 {
out.push((pos, (pos + 2.0 * x).min(len)));
}
}
out.sort_by(|a, b| a.0.total_cmp(&b.0));
out
}
/// Length of a polyline.
fn length(pts: &[Vec2]) -> f64 {
pts.windows(2).map(|w| w.first().zip(w.get(1)).map(|(a, b)| a.dist(*b)).unwrap_or(0.0)).sum()
}
/// The pattern scaled, or `None` when a run is drawn continuous at any length: no pattern, or one
/// shorter than `min_pattern` (sub-pixel).
fn scaled(lt: &Linetype, scale: f64, min_pattern: f64) -> Option<Vec<f64>> {
/// Split `pts` into dashes. Dots come back as single-point runs. When the scaled pattern is
/// shorter than `min_pattern` (sub-pixel), the polyline is returned whole.
pub fn apply(pts: &[Vec2], lt: &Linetype, scale: f64, min_pattern: f64) -> Vec<Vec<Vec2>> {
let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 };
let total = lt.pattern_length() * scale;
(total > 1e-12 && total >= min_pattern).then(|| lt.pattern.iter().map(|d| d.length * scale).collect())
}
/// The pieces of `pts` over `ranges` (in order along it), a dot as a single point.
fn cut(pts: &[Vec2], ranges: &[(f64, f64)]) -> Vec<Vec<Vec2>> {
let mut cum = Vec::with_capacity(pts.len());
let mut acc = 0.0;
cum.push(0.0);
for w in pts.windows(2) {
acc += w.first().zip(w.get(1)).map(|(a, b)| a.dist(*b)).unwrap_or(0.0);
cum.push(acc);
if pts.len() < 2 || total <= 1e-12 || total < min_pattern {
return vec![pts.to_vec()];
}
let last = pts.len().saturating_sub(1).max(1);
// The point `s` along, and the index of the first vertex past it.
let at = |s: f64| -> (Vec2, usize) {
let j = cum.partition_point(|&c| c <= s).clamp(1, last);
let (Some(&a), Some(&b), Some(&ca), Some(&cb)) = (pts.get(j - 1), pts.get(j), cum.get(j - 1), cum.get(j)) else {
return (pts.first().copied().unwrap_or(Vec2::ZERO), j);
};
let t = if cb > ca { ((s - ca) / (cb - ca)).clamp(0.0, 1.0) } else { 0.0 };
(a + (b - a) * t, j)
};
let mut out = Vec::with_capacity(ranges.len());
for &(s0, s1) in ranges {
let (p, j) = at(s0);
if s1 <= s0 {
out.push(vec![p]);
// Guard against huge dash counts (zoomed out a lot): fall back to continuous.
let len: f64 = pts.windows(2).map(|w| w.first().zip(w.get(1)).map(|(a, b)| a.dist(*b)).unwrap_or(0.0)).sum();
if len / total > 50_000.0 {
return vec![pts.to_vec()];
}
let pattern: Vec<f64> = lt.pattern.iter().map(|d| d.length * scale).collect();
// AutoCAD centres the pattern so lines start and end with a dash: start at half the first dash.
let mut out: Vec<Vec<Vec2>> = Vec::new();
let mut cur: Vec<Vec2> = Vec::new();
let mut idx = 0usize;
let first = pattern.first().copied().unwrap_or(0.0);
let mut remaining = if first > 0.0 { first } else { first.abs() };
let mut on = first >= 0.0;
if on && first == 0.0 {
if let Some(p) = pts.first() {
out.push(vec![*p]);
}
idx = 1 % pattern.len();
let n = pattern.get(idx).copied().unwrap_or(0.0);
remaining = n.abs();
on = n > 0.0;
}
if on && let Some(p) = pts.first() {
cur.push(*p);
}
let mut guard = 0usize;
for w in pts.windows(2) {
let (Some(&a), Some(&b)) = (w.first(), w.get(1)) else { continue };
let seg = a.dist(b);
if seg <= 1e-15 {
continue;
}
let mut piece = vec![p];
let mut k = j;
while let (Some(&c), Some(&q)) = (cum.get(k), pts.get(k)) {
if c >= s1 {
break;
let dir = (b - a) / seg;
let mut pos = 0.0;
while seg - pos > remaining {
guard += 1;
if guard > 2_000_000 {
return vec![pts.to_vec()];
}
pos += remaining;
let p = a + dir * pos;
if on {
cur.push(p);
out.push(std::mem::take(&mut cur));
}
idx = (idx + 1) % pattern.len();
let n = pattern.get(idx).copied().unwrap_or(0.0);
if n == 0.0 {
out.push(vec![p]);
idx = (idx + 1) % pattern.len();
let n2 = pattern.get(idx).copied().unwrap_or(0.0);
remaining = n2.abs();
on = n2 > 0.0;
} else {
remaining = n.abs();
on = n > 0.0;
}
if on {
cur.push(p);
}
piece.push(q);
k += 1;
}
piece.push(at(s1).0);
out.push(piece);
remaining -= seg - pos;
if on {
cur.push(b);
}
}
if cur.len() >= 2 {
out.push(cur);
}
out
}
/// Split `pts`, an open run, into dashes. Dots come back as single-point runs. A run shorter than
/// one period, or with a scaled pattern shorter than `min_pattern` (sub-pixel), comes back whole.
pub fn apply(pts: &[Vec2], lt: &Linetype, scale: f64, min_pattern: f64) -> Vec<Vec<Vec2>> {
apply_as(pts, lt, scale, min_pattern, Layout::Open)
}
/// [`apply`] with the run laid out as `how` says.
pub fn apply_as(pts: &[Vec2], lt: &Linetype, scale: f64, min_pattern: f64, how: Layout) -> Vec<Vec<Vec2>> {
let laid = if pts.len() >= 2 { scaled(lt, scale, min_pattern).and_then(|p| layout(length(pts), &p, how, min_pattern)) } else { None };
match laid {
Some(r) => cut(pts, &r),
None => vec![pts.to_vec()],
/// The dashes of the pattern along a run of length `len`, as (start, end) distances; a dot has
/// start == end. Laid out like [`apply`]. `None` when the run is drawn continuous: the scaled
/// pattern is shorter than `min_pattern` or would repeat too often.
pub fn ranges(len: f64, lt: &Linetype, scale: f64, min_pattern: f64) -> Option<Vec<(f64, f64)>> {
let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 };
let total = lt.pattern_length() * scale;
if !(len.is_finite() && len > 0.0) || total <= 1e-12 || total < min_pattern || len / total > 50_000.0 {
return None;
}
}
/// The dashes of the pattern along a run of length `len` laid out as `how` says, as (start, end)
/// distances; a dot has start == end. Laid out like [`apply_as`]. `None` when the run is drawn
/// continuous: shorter than one period, a scaled pattern shorter than `min_pattern`, or too many
/// repeats (see [`MAX_PERIODS`]).
pub fn ranges(len: f64, lt: &Linetype, scale: f64, min_pattern: f64, how: Layout) -> Option<Vec<(f64, f64)>> {
if len > 0.0 { scaled(lt, scale, min_pattern).and_then(|p| layout(len, &p, how, min_pattern)) } else { None }
}
/// Where the pattern starts on a run `len` long laid out as `how`, and how much it is stretched:
/// period `k` starts at `start + k · period · stretch`. `None` when the run is drawn continuous.
pub fn phase(len: f64, lt: &Linetype, scale: f64, min_pattern: f64, how: Layout) -> Option<(f64, f64)> {
let pattern = scaled(lt, scale, min_pattern)?;
let period: f64 = pattern.iter().map(|d| d.abs()).sum();
layout(len, &pattern, how, min_pattern)?;
let first = pattern.first().copied().unwrap_or(0.0);
Some(match how {
Layout::Open => {
let n = (len / period + 1e-9).floor();
let x = (len - n * period + first) / 2.0;
// A gap-first pattern with room for a piece of dash at the start ([`gap_first`]) has
// its second element at `x`, a gap after its period starts.
(if first < 0.0 && x >= 0.0 { x + first } else { x - first }, 1.0)
let mut out = Vec::new();
let mut pos = 0.0;
// Gap-only patterns draw nothing, matching `apply`, without walking every repeat.
if !lt.pattern.iter().any(|d| d.length >= 0.0) {
return Some(Vec::new());
}
// Bound the pattern elements visited, independent of emitted ranges, so a pattern that emits
// little still cannot cycle hundreds of millions of times.
let mut visits: u64 = 0;
for d in lt.pattern.iter().map(|d| d.length * scale).cycle() {
visits += 1;
if pos >= len || out.len() > 2_000_000 || visits > 4_000_000 {
break;
}
Layout::Closed { anchor } => {
let f = len / ((len / period).round().max(1.0) * period);
(if anchor.is_finite() { anchor.rem_euclid(period * f) } else { 0.0 }, f)
if d >= 0.0 {
out.push((pos, (pos + d).min(len)));
}
})
pos += d.abs();
}
Some(out)
}
#[cfg(test)]
@@ -260,7 +122,7 @@ mod tests {
#[test]
fn an_all_gap_pattern_draws_nothing_without_spinning() {
let lt = Linetype::simple("GAPS", "", &[-0.001, -0.002]);
assert_eq!(ranges(1.0, &lt, 1.0, 0.0, Layout::Open), Some(Vec::new()));
assert_eq!(ranges(1.0, &lt, 1.0, 0.0), Some(Vec::new()));
assert!(apply(&[Vec2::ZERO, Vec2::new(1.0, 0.0)], &lt, 1.0, 0.0).is_empty());
}
@@ -268,11 +130,10 @@ mod tests {
fn dashes_split_line() {
let lt = Linetype::simple("DASHED", "", &[0.5, -0.25]);
let d = apply(&[Vec2::ZERO, Vec2::new(3.0, 0.0)], &lt, 1.0, 0.0);
// 3.0 / 0.75 = 4 periods, centred: a half dash at each end and four whole ones between.
assert_eq!(d.len(), 5);
assert!((d[0][1].x - 0.25).abs() < 1e-9);
assert!((d[1][0].x - 0.5).abs() < 1e-9);
assert!((d[4][0].x - 2.75).abs() < 1e-9 && (d[4][1].x - 3.0).abs() < 1e-9);
// 3.0 / 0.75 = 4 patterns → 4 dashes.
assert_eq!(d.len(), 4);
assert!((d[0][1].x - 0.5).abs() < 1e-9);
assert!((d[1][0].x - 0.75).abs() < 1e-9);
}
#[test]
@@ -296,156 +157,4 @@ mod tests {
let d = apply(&[Vec2::ZERO, Vec2::new(0.3, 0.0), Vec2::new(0.3, 1.0)], &lt, 1.0, 0.0);
assert_eq!(d[0].len(), 3); // the first dash turns the corner
}
/// The drawn stretches of a run, a continuous one as one stretch, with stretches that touch
/// joined (a plot draws them as one stroke).
fn drawn(len: f64, pattern: &[f64], how: Layout) -> Vec<(f64, f64)> {
let mut out: Vec<(f64, f64)> = Vec::new();
for (a, b) in layout(len, pattern, how, 0.0).unwrap_or_else(|| vec![(0.0, len)]) {
match out.last_mut() {
Some(last) if (last.1 - a).abs() < 1e-9 && b > a && last.1 > last.0 => last.1 = b,
_ => out.push((a, b)),
}
}
out
}
fn near(got: &[(f64, f64)], want: &[(f64, f64)], tol: f64) -> bool {
got.len() == want.len() && got.iter().zip(want).all(|(g, w)| (g.0 - w.0).abs() <= tol && (g.1 - w.1).abs() <= tol)
}
/// AutoCAD 2024 plots (DWG To PDF at 10:1, every stroke read back to 0.01): open runs.
#[test]
fn open_runs_are_laid_out_as_autocad_plots_them() {
let dut = [2.0, -1.0];
for (len, want) in [
(7.0, vec![(0.0, 1.5), (2.5, 4.5), (5.5, 7.0)]),
(6.0, vec![(0.0, 1.0), (2.0, 4.0), (5.0, 6.0)]),
(5.99, vec![(0.0, 2.495), (3.495, 5.99)]),
(2.99, vec![(0.0, 2.99)]),
] {
assert!(near(&drawn(len, &dut, Layout::Open), &want, 1e-9), "{len}: {:?}", drawn(len, &dut, Layout::Open));
}
// A pattern opening with a dot: dots at both ends.
let dots = drawn(5.3, &[0.0, -1.0], Layout::Open);
assert!(near(&dots, &[(0.0, 0.0), (1.15, 1.15), (2.15, 2.15), (3.15, 3.15), (4.15, 4.15), (5.3, 5.3)], 1e-9), "{dots:?}");
// Patterns opening with a gap.
let (h1, h2, h3, h4) = ([-1.0, 2.0], [-0.5, 2.0, -0.5], [-1.0, 2.0, -2.0, 1.0], [-2.0, 1.0]);
let table: [(&[f64], f64, &[(f64, f64)]); 33] = [
(&h1, 3.0, &[(1.5, 3.0)]),
(&h1, 3.5, &[(1.75, 3.5)]),
(&h1, 4.0, &[(0.0, 0.0), (0.0, 2.0)]),
(&h1, 4.5, &[(0.0, 2.75)]),
(&h1, 5.0, &[(0.0, 3.5)]),
(&h1, 5.5, &[(0.0, 4.25)]),
(&h1, 6.0, &[(1.5, 3.5), (4.5, 6.0)]),
(&h1, 6.5, &[(1.75, 3.75), (4.75, 6.5)]),
(&h1, 7.0, &[(0.0, 0.0), (0.0, 2.0), (3.0, 5.0)]),
(&h1, 7.5, &[(0.0, 2.25), (3.25, 5.75)]),
(&h1, 8.0, &[(0.0, 2.5), (3.5, 6.5)]),
(&h1, 9.0, &[(1.5, 3.5), (4.5, 6.5), (7.5, 9.0)]),
(&h1, 10.0, &[(0.0, 0.0), (0.0, 2.0), (3.0, 5.0), (6.0, 8.0)]),
(&h1, 11.0, &[(0.0, 2.5), (3.5, 5.5), (6.5, 9.5)]),
(&h1, 12.5, &[(1.75, 3.75), (4.75, 6.75), (7.75, 9.75), (10.75, 12.5)]),
(&h1, 1.0, &[(0.0, 1.0)]),
(&h1, 2.0, &[(0.0, 2.0)]),
(&h1, 2.5, &[(0.0, 2.5)]),
(&h1, 2.9, &[(0.0, 2.9)]),
(&h2, 4.0, &[(0.0, 2.25), (2.75, 3.25)]),
(&h2, 5.0, &[(0.0, 2.75), (3.25, 4.75)]),
(&h2, 6.0, &[(0.75, 2.75), (3.75, 5.75)]),
(&h2, 7.0, &[(0.0, 2.25), (3.25, 5.25), (5.75, 6.25)]),
(&h2, 8.0, &[(0.0, 2.75), (3.75, 5.75), (6.25, 7.75)]),
(&h3, 10.0, &[(0.0, 3.5), (5.5, 9.5)]),
(&h3, 13.0, &[(0.0, 0.0), (0.0, 2.0), (4.0, 5.0), (6.0, 8.0), (10.0, 11.0)]),
(&h3, 15.5, &[(0.0, 3.25), (5.25, 6.25), (7.25, 9.25), (11.25, 14.75)]),
(&h4, 7.0, &[(3.5, 4.5), (6.5, 7.0)]),
(&h4, 8.0, &[(0.0, 0.0), (0.0, 1.0), (3.0, 4.0)]),
(&h4, 10.0, &[(3.5, 4.5), (6.5, 7.5), (9.5, 10.0)]),
(&h4, 2.0, &[(0.0, 2.0)]),
(&h2, 2.9, &[(0.0, 2.9)]),
(&h3, 5.9, &[(0.0, 5.9)]),
];
for (pattern, len, want) in table {
let got = drawn(len, pattern, Layout::Open);
assert!(near(&got, want, 0.006), "{pattern:?} on {len}: {got:?}");
}
}
/// Text in a linetype follows [`phase`]: it must say where the periods of a gap-first pattern
/// start on each side of the room left for a piece of dash at the start.
#[test]
fn phase_follows_the_dashes_of_a_gap_first_pattern() {
let lt = Linetype::simple("GF", "", &[-1.0, 2.0]);
for len in [6.5, 7.0, 7.5, 8.9, 12.5] {
let (start, f) = phase(len, &lt, 1.0, 0.0, Layout::Open).unwrap();
assert_eq!(f, 1.0);
// Every whole dash starts a gap (1) after a period (3) starts.
let whole: Vec<f64> =
ranges(len, &lt, 1.0, 0.0, Layout::Open).unwrap().into_iter().filter(|(a, b)| (b - a - 2.0).abs() < 1e-9).map(|(a, _)| a).collect();
assert!(!whole.is_empty(), "{len}");
for a in whole {
let k = (a - 1.0 - start) / 3.0;
assert!((k - k.round()).abs() < 1e-9, "{len}: a dash at {a}, periods from {start}");
}
}
}
/// Closed runs on the same plots: stretched to round(L / period) periods from their anchor.
#[test]
fn closed_runs_are_stretched_as_autocad_plots_them() {
let dut = [2.0, -1.0];
// A circle of radius 2 from angle 0: 0°–60°, 90°–150°, 180°–240°, 270°–330°.
let r = 2.0;
let got = drawn(std::f64::consts::TAU * r, &dut, Layout::Closed { anchor: 0.0 });
let want: Vec<(f64, f64)> =
[(0.0, 60.0), (90.0, 150.0), (180.0, 240.0), (270.0, 330.0)].map(|(a, b): (f64, f64)| (a.to_radians() * r, b.to_radians() * r)).into();
assert!(near(&got, &want, 1e-9), "{got:?}");
// Rectangles (PLINEGEN, closed), anchored at the second vertex: 4 × 4 has 5 periods of 3.2
// from s = 0.8, 5 × 5 has 7 (round, not floor) from 2.143, 2 × 3 from 2.0, 3 × 3 from 0.
for (w, h, periods, start) in [(4.0, 4.0, 5.0, 0.8), (5.0, 5.0, 7.0, 2.0 + 1.0 / 7.0), (2.0, 3.0, 3.0, 2.0), (3.0, 3.0, 4.0, 0.0)] {
let len = 2.0 * (w + h);
let got = drawn(len, &dut, Layout::Closed { anchor: w });
let dash = 2.0 * len / (3.0 * periods);
assert!(got.iter().any(|r| (r.0 - start).abs() < 1e-9 && (r.1 - r.0 - dash).abs() < 1e-9), "{w}×{h}: {got:?}");
}
}
/// A pattern too long for the run draws it continuous.
#[test]
fn a_run_shorter_than_one_period_is_continuous() {
let lt = Linetype::simple("DASHED", "", &[2.0, -1.0]);
assert_eq!(apply(&[Vec2::ZERO, Vec2::new(2.99, 0.0)], &lt, 1.0, 0.0).len(), 1);
assert_eq!(ranges(2.99, &lt, 1.0, 0.0, Layout::Open), None);
}
/// A long pattern repeated many times is drawn continuous rather than laid out element by
/// element: 100 elements over 40,000 periods is past the cap, 400 periods is not.
#[test]
fn a_long_pattern_repeated_too_often_is_continuous() {
let pattern: Vec<f64> = (0..100).map(|i| if i % 2 == 0 { 0.001 } else { -0.001 }).collect();
let lt = Linetype::simple("MANY", "", &pattern);
for how in [Layout::Open, Layout::Closed { anchor: 0.0 }] {
assert_eq!(ranges(4000.0, &lt, 1.0, 0.0, how), None, "{how:?}");
assert!(ranges(40.0, &lt, 1.0, 0.0, how).is_some_and(|r| r.len() > 10_000), "{how:?}");
}
}
/// A plot or export keeps the dashes of a run more than 50,000 periods long; a display build,
/// with a level of detail, draws it continuous (#1069).
#[test]
fn a_plot_keeps_the_dashes_of_a_run_of_many_periods() {
let lt = Linetype::simple("DASHED", "", &[0.5, -0.25]);
let len = 50_001.0 * 0.75;
// Centred, the first and last dashes are halves: one more dash than periods.
for (how, dashes) in [(Layout::Open, 50_002), (Layout::Closed { anchor: 0.0 }, 50_001)] {
assert_eq!(ranges(len, &lt, 1.0, 0.0, how).map(|r| r.len()), Some(dashes), "{how:?}");
assert_eq!(ranges(len, &lt, 1.0, 1e-9, how), None, "{how:?}");
// Where linetype texts are placed from.
assert!(phase(len, &lt, 1.0, 0.0, how).is_some(), "{how:?}");
assert_eq!(phase(len, &lt, 1.0, 1e-9, how), None, "{how:?}");
}
let pts = [Vec2::ZERO, Vec2::new(len, 0.0)];
assert_eq!(apply(&pts, &lt, 1.0, 0.0).len(), 50_002);
assert_eq!(apply(&pts, &lt, 1.0, 1e-9).len(), 1);
}
}
+22 -32
View File
@@ -4,8 +4,7 @@
//! A dash element may carry a text (DXF `74` bit 2, `9` string) or a shape (`74` bit 4, `75`
//! shape number). As in a `.lin` definition, where the bracketed text or shape follows the dash
//! or gap that carries it, it is placed where that element ends, at every repeat of the pattern
//! (laid out on the run as [`crate::linetype::apply_as`] lays out its dashes, so none on a run
//! drawn continuous):
//! (laid out from the start of the run like [`crate::linetype::apply`]):
//! - height: the element's scale (`46`), times the text style's fixed height when it has one,
//! times the linetype scale;
//! - origin: the anchor shifted by the X/Y offsets (`44`/`45`, times the linetype scale) along
@@ -23,8 +22,6 @@ use cadcraft_doc::{Drawing, Linetype};
use cadcraft_fonts::{Shaped, TextParams};
use cadcraft_geom::Vec2;
use crate::linetype::Layout;
/// Upper bound on the texts and shapes drawn along one run (hostile scales; `apply` caps the
/// dashes).
const MAX_TEXTS: usize = 10_000;
@@ -50,8 +47,8 @@ struct Element {
/// The texts and shapes of `lt` along the polyline `pts`, in the coordinates of `pts`. Empty
/// when the linetype has none or its scaled pattern is drawn continuous (shorter than
/// `min_pattern`, or, in a display build, repeating too often: see [`crate::linetype::phase`]).
pub fn texts(d: &Drawing, pts: &[Vec2], lt: &Linetype, scale: f64, min_pattern: f64, how: Layout) -> Vec<Shaped> {
/// `min_pattern`, or repeating too often).
pub fn texts(d: &Drawing, pts: &[Vec2], lt: &Linetype, scale: f64, min_pattern: f64) -> Vec<Shaped> {
let mut out = Vec::new();
if pts.len() < 2 || !lt.pattern.iter().any(|e| e.text.as_deref().is_some_and(|t| !t.trim().is_empty()) || e.shape.is_some()) {
return out;
@@ -59,25 +56,20 @@ pub fn texts(d: &Drawing, pts: &[Vec2], lt: &Linetype, scale: f64, min_pattern:
let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 };
let total = lt.pattern_length() * scale;
let len: f64 = pts.windows(2).map(|w| w.first().zip(w.get(1)).map(|(a, b)| a.dist(*b)).unwrap_or(0.0)).sum();
if !(total.is_finite() && total > 1e-12 && len.is_finite()) || total < min_pattern {
if !(total.is_finite() && total > 1e-12 && len.is_finite()) || total < min_pattern || len / total > 50_000.0 {
return out;
}
let elements = elements(d, lt, scale);
let Some((start, stretch)) = crate::linetype::phase(len, lt, scale, min_pattern, how) else { return out };
if elements.is_empty() {
return out;
}
let mut walk = Walk { pts, i: 0, start: 0.0 };
let mut points_left = MAX_TEXT_POINTS;
// From the period before the run's start (a centred or anchored pattern starts before it).
let mut base = start - total * stretch;
let mut base = 0.0;
let mut points = 0usize;
'repeats: while base <= len {
for el in &elements {
let s = base + el.at * stretch;
if s < 0.0 {
continue;
}
let s = base + el.at;
points = points.saturating_add(point_count(&el.local));
if s > len + 1e-9 || out.len() >= MAX_TEXTS || points > MAX_POINTS {
break 'repeats;
@@ -91,7 +83,7 @@ pub fn texts(d: &Drawing, pts: &[Vec2], lt: &Linetype, scale: f64, min_pattern:
sh.map(|q| origin + q.rotate(rot));
out.push(sh);
}
base += total * stretch;
base += total;
}
out
}
@@ -227,20 +219,20 @@ mod tests {
#[test]
fn one_text_per_repeat_at_the_end_of_its_element() {
let d = Drawing::new_imperial();
let t = texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &gas(), 1.0, 0.0, Layout::Open);
// Pattern 0.95 long, centred on the 2.0 run (p0 = 0.2): anchors at 0.7 − 0.2 and 1.65 − 0.2.
let t = texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &gas(), 1.0, 0.0);
// Pattern 0.95 long: anchors at 0.7 and 1.65.
assert_eq!(t.len(), 2);
let x = starts(&t);
assert!(x[0] >= 0.49 && x[0] < 0.55, "{x:?}");
assert!(x[1] >= 1.44 && x[1] < 1.50, "{x:?}");
assert!(x[0] >= 0.69 && x[0] < 0.75, "{x:?}");
assert!(x[1] >= 1.64 && x[1] < 1.70, "{x:?}");
}
#[test]
fn no_text_when_drawn_continuous() {
let d = Drawing::new_imperial();
assert!(texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &gas(), 1.0, 5.0, Layout::Open).is_empty());
assert!(texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &gas(), 1.0, 5.0).is_empty());
let plain = Linetype::simple("DASHED", "", &[0.5, -0.25]);
assert!(texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &plain, 1.0, 0.0, Layout::Open).is_empty());
assert!(texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &plain, 1.0, 0.0).is_empty());
}
/// A long label repeated along a long run stops at the point allowance, well before MAX_TEXTS.
@@ -250,7 +242,7 @@ mod tests {
let mut lt = gas();
lt.pattern[1].text = Some("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM".into());
// 0.95 per repeat over 9,000: about 9,500 repeats, under the 50,000 the run is drawn for.
let t = texts(&d, &[Vec2::ZERO, Vec2::new(9_000.0, 0.0)], &lt, 1.0, 0.0, Layout::Open);
let t = texts(&d, &[Vec2::ZERO, Vec2::new(9_000.0, 0.0)], &lt, 1.0, 0.0);
let points: usize =
t.iter().map(|s| s.strokes.iter().map(Vec::len).sum::<usize>() + s.glyphs.iter().flatten().map(Vec::len).sum::<usize>()).sum();
assert!(!t.is_empty() && t.len() < MAX_TEXTS, "{}", t.len());
@@ -280,28 +272,26 @@ mod tests {
register_shapes();
let d = Drawing::new_imperial();
// An unnamed shape-file style reads as its file name (DXF); scale 0.1 per vector unit.
let t = texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &fence("cadcraft-render-lt.shx"), 1.0, 0.0, Layout::Open);
// Laid out as the text above: the 0.95 pattern centred on the 2.0 run, anchors at 0.7 − 0.2
// and 1.65 − 0.2.
let t = texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &fence("cadcraft-render-lt.shx"), 1.0, 0.0);
assert_eq!(t.len(), 2);
let x = starts(&t);
assert!((x[0] - 0.5).abs() < 1e-9 && (x[1] - 1.45).abs() < 1e-9, "{x:?}");
assert!((x[0] - 0.7).abs() < 1e-9 && (x[1] - 1.65).abs() < 1e-9, "{x:?}");
let ys = t[0].strokes.iter().flatten().fold((f64::MAX, f64::MIN), |(a, b), p| (a.min(p.y), b.max(p.y)));
assert!((ys.0).abs() < 1e-9 && (ys.1 - 0.2).abs() < 1e-9, "{ys:?}");
// Along a vertical line the shape turns with it; absolute rotation keeps it level.
let t = texts(&d, &[Vec2::ZERO, Vec2::new(0.0, 2.0)], &fence("cadcraft-render-lt.shx"), 2.0, 0.0, Layout::Open);
let t = texts(&d, &[Vec2::ZERO, Vec2::new(0.0, 2.0)], &fence("cadcraft-render-lt.shx"), 2.0, 0.0);
assert_eq!(t.len(), 1);
let xs = t[0].strokes.iter().flatten().fold((f64::MAX, f64::MIN), |(a, b), p| (a.min(p.x), b.max(p.x)));
assert!((xs.0 + 0.4).abs() < 1e-9 && xs.1.abs() < 1e-9, "{xs:?}");
// A named style whose font is the shape file.
let mut d = Drawing::new_imperial();
d.text_styles.push(cadcraft_doc::TextStyle { name: "SHAPES".into(), font: "cadcraft-render-lt.shx".into(), ..Default::default() });
assert_eq!(texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &fence("SHAPES"), 1.0, 0.0, Layout::Open).len(), 2);
assert_eq!(texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &fence("SHAPES"), 1.0, 0.0).len(), 2);
// A shape file that isn't found, or a shape it lacks, draws nothing.
assert!(texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &fence("cadcraft-no-such-file.shx"), 1.0, 0.0, Layout::Open).is_empty());
assert!(texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &fence("cadcraft-no-such-file.shx"), 1.0, 0.0).is_empty());
let mut lt = fence("cadcraft-render-lt.shx");
lt.pattern[1].shape = Some(131);
assert!(texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &lt, 1.0, 0.0, Layout::Open).is_empty());
assert!(texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &lt, 1.0, 0.0).is_empty());
}
#[test]
@@ -314,7 +304,7 @@ mod tests {
let mut lt = fence("cadcraft-render-big.shx");
lt.pattern[1].shape = Some(131);
// 3,000 repeats would hold about 3 million points.
let t = texts(&d, &[Vec2::ZERO, Vec2::new(2850.0, 0.0)], &lt, 1.0, 0.0, Layout::Open);
let t = texts(&d, &[Vec2::ZERO, Vec2::new(2850.0, 0.0)], &lt, 1.0, 0.0);
let points: usize = t.iter().map(point_count).sum();
assert!(!t.is_empty() && t.len() < 3000 && points <= MAX_POINTS, "{} shapes, {points} points", t.len());
}
@@ -355,7 +345,7 @@ mod tests {
}
let pts = [Vec2::ZERO, Vec2::ZERO, Vec2::new(1e6, 0.0), Vec2::new(1e6, 0.0)];
for scale in [f64::NAN, 0.0, -1.0, 1e-9, 1e300] {
let t = texts(&d, &pts, &lt, scale, 0.0, Layout::Open);
let t = texts(&d, &pts, &lt, scale, 0.0);
assert!(t.len() <= MAX_TEXTS);
}
}
-26
View File
@@ -940,32 +940,6 @@ fn a_constant_attribute_definition_draws_its_value_with_the_reference() {
assert_eq!(drawn_above_line(constant(false), vec![own], 1, at).len(), pts.len());
}
#[test]
fn many_constant_definitions_are_matched_to_the_attributes_without_comparing_every_pair() {
// #1923: a reference with N attributes of a block with N constant definitions, the tags N long
// ones alike up to their last characters, no attribute's a definition's. Asking for each
// definition whether the reference carries its tag by comparing it with every attribute cost
// N x N comparisons of whole tags for each copy drawn (many seconds here); gathering the
// reference's tags once costs milliseconds. The values are empty and the attributes invisible,
// so drawing them costs nothing.
const N: usize = 4000;
let tag = |kind: char, i: usize| format!("{}{kind}{i:05}", "T".repeat(1000));
let mut d = Drawing::new_imperial();
let mut blk = cadcraft_doc::Block::new("K");
for (h, i) in (1..).zip(0..N) {
let mut a = cadcraft_doc::Attrib { constant: true, ..attrib(&tag('D', i)) };
a.text.value.clear();
blk.entities.push(block_entity(h, Common::default(), EntityKind::AttDef(a)));
}
d.blocks.insert("K".into(), std::sync::Arc::new(blk));
let EntityKind::Insert(mut ins) = insert_of("K") else { panic!("an insert") };
ins.attribs = (0..N).map(|i| cadcraft_doc::Attrib { invisible: true, ..attrib(&tag('A', i)) }).collect();
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
let t = std::time::Instant::now();
build(&d, &Space::Model, &Options::default());
assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed());
}
#[test]
fn constant_attribute_definitions_follow_attmode() {
let at = Vec3::ZERO;
+4 -16
View File
@@ -3,7 +3,7 @@
use cadcraft_doc::{Linetype, LwPolyline};
use cadcraft_geom::{MAX_TESSELLATED_POINTS, Polyline, Vec2};
use crate::linetype::{self, Layout};
use crate::linetype;
/// A point on the centre line: position, unit direction, half width and distance along the run.
#[derive(Clone, Copy, Debug)]
@@ -67,26 +67,14 @@ fn edges(x: &Sample) -> (Vec2, Vec2) {
(x.p + nrm, x.p - nrm)
}
/// How far along a closed PLINEGEN polyline, drawn from its first vertex, its second vertex lies
/// (an arc by its chords at `tol`): where the pattern stretched around it is anchored, as AutoCAD
/// lays it. 0 when the first two vertices coincide (`Polyline::segments` leaves that segment out).
pub(crate) fn second_vertex_at(p: &LwPolyline, tol: f64) -> f64 {
let first = Polyline { vertices: p.vertices.iter().take(2).copied().collect(), closed: false };
first.tessellate(tol).windows(2).map(|w| if let [a, b] = w { a.dist(*b) } else { 0.0 }).sum()
}
/// Triangles for the dashes of a wide polyline drawn with `lt` at `scale`, a line across the band
/// for each dot, and the centre line of each dash. With PLINEGEN the pattern runs along the whole
/// polyline (stretched around a closed one from its second vertex, as a thin one is); otherwise
/// it restarts at every vertex. A pattern shorter than `min_pattern` fills the whole band.
/// polyline; otherwise it restarts at every vertex. A pattern shorter than `min_pattern` fills
/// the whole band.
pub fn dashed(p: &LwPolyline, tol: f64, lt: &Linetype, scale: f64, min_pattern: f64) -> (Vec<Vec2>, Vec<Vec<Vec2>>, Vec<Vec<Vec2>>) {
let mut budget = MAX_TESSELLATED_POINTS;
let mut runs = segments(p, tol, &mut budget);
let mut how = Layout::Open;
if p.plinegen && runs.len() > 1 {
if p.closed {
how = Layout::Closed { anchor: second_vertex_at(p, tol) };
}
let mut whole: Vec<Sample> = Vec::new();
for run in runs {
let base = whole.last().map(|x| x.s).unwrap_or(0.0);
@@ -99,7 +87,7 @@ pub fn dashed(p: &LwPolyline, tol: f64, lt: &Linetype, scale: f64, min_pattern:
let mut centres = Vec::new();
for run in &runs {
let len = run.last().map(|x| x.s).unwrap_or(0.0);
let dashes = linetype::ranges(len, lt, scale, min_pattern, how).unwrap_or_else(|| vec![(0.0, len)]);
let dashes = linetype::ranges(len, lt, scale, min_pattern).unwrap_or_else(|| vec![(0.0, len)]);
for (a, b) in dashes {
if b - a <= 1e-12 {
if let Some(x) = at(run, a) {
+1 -5
View File
@@ -35,16 +35,12 @@ fn drawing(ltscale: f64, own: &str) -> Drawing {
d
}
/// The lengths of the dashes drawn for the reference, all but the first and the last (the
/// pattern is centred on the line, so those two may be cut).
/// The lengths of the dashes drawn for the reference, all but the last one (which may be cut).
fn dashes(d: &Drawing) -> Vec<f64> {
let l = build(d, &Space::Model, &Options::default());
let mut out: Vec<f64> =
l.prims.iter().filter(|p| p.kind == Kind::Polyline).map(|p| l.points(p).windows(2).map(|w| w[0].dist(w[1])).sum()).collect();
out.pop();
if !out.is_empty() {
out.remove(0);
}
out
}
+5 -7
View File
@@ -33,11 +33,10 @@ fn fenceline_draws_a_circle_in_every_gap() {
let (a, b) = (Vec2::ZERO, Vec2::new(9.5, 0.0));
let d = drawing(fence, a, b);
let marks = off_line(&d, &Options::default(), a, b);
// Pattern 0.25 on, 0.1 off, "o", 0.1 off, 0.5 on = 0.95: ten repeats along 9.5, the pattern
// centred on it (p0 = (9.5 + 0.25 − 9.5) / 2 = 0.125, so it starts 0.125 before the line).
// Pattern 0.25 on, 0.1 off, "o", 0.1 off, 0.5 on = 0.95: ten repeats along 9.5.
assert_eq!(marks.len(), 10, "{marks:?}");
for (i, m) in marks.iter().enumerate() {
let gap = i as f64 * 0.95 + 0.25 - 0.125;
let gap = i as f64 * 0.95 + 0.25;
assert!(m.min.x > gap && m.max.x < gap + 0.2, "mark {i} at {m:?} outside its gap");
// Centred on the line.
assert!((m.min.y + m.max.y).abs() < 0.01 && m.max.y > 0.02, "{m:?}");
@@ -73,10 +72,9 @@ fn text_follows_the_line_or_keeps_an_absolute_rotation() {
let marks = off_line(&drawing(gas(absolute), a, b), &Options::default(), a, b);
assert!(!marks.is_empty(), "absolute {absolute}: no text");
let all = Bounds2::from_points(marks.iter().flat_map(|m| [m.min, m.max]));
// The pattern centred on the line (p0 = (0.95 + 0.5 − 1) / 2 = 0.225): anchor 0.7 − 0.225
// up the line, shifted 0.1 back along it and 0.05 to its right: the text starts at
// (0.05, 0.375).
assert!((all.min.y - 0.375).abs() < 0.01, "absolute {absolute}: {all:?}");
// Anchor 0.7 up the line, shifted 0.1 back along it and 0.05 to its right: the text
// starts at (0.05, 0.6).
assert!((all.min.y - 0.6).abs() < 0.01, "absolute {absolute}: {all:?}");
if absolute {
assert!(all.width() > all.height(), "{all:?}");
assert!((all.min.x - 0.05).abs() < 0.01, "{all:?}");
+5 -7
View File
@@ -44,10 +44,9 @@ fn dash_lengths(d: &Drawing) -> Vec<f64> {
#[test]
fn psltscale_on_keeps_paper_dash_length() {
let dashes = dash_lengths(&drawing(1));
// 1000 model units = 10 paper units; 0.75-unit pattern on paper → about 13 dashes of 0.5
// (centred on the line: the first and last may be shorter).
// 1000 model units = 10 paper units; 0.75-unit pattern on paper → about 13 dashes of 0.5.
assert!((12..=15).contains(&dashes.len()), "{} dashes", dashes.len());
assert!(dashes.iter().skip(1).take(dashes.len() - 2).all(|l| (l - 0.5).abs() < 1e-6), "{dashes:?}");
assert!(dashes.iter().take(dashes.len() - 1).all(|l| (l - 0.5).abs() < 1e-6), "{dashes:?}");
}
#[test]
@@ -55,14 +54,13 @@ fn psltscale_off_scales_dashes_with_the_viewport() {
let dashes = dash_lengths(&drawing(0));
// Model-space dash length 0.5, shrunk 100x by the viewport.
assert!(dashes.len() > 1000, "{} dashes", dashes.len());
assert!(dashes.iter().skip(1).take(dashes.len() - 2).all(|l| (l - 0.005).abs() < 1e-6));
assert!(dashes.iter().take(dashes.len() - 1).all(|l| (l - 0.005).abs() < 1e-6));
}
#[test]
fn model_space_ignores_psltscale() {
let d = drawing(1);
let l = build(&d, &Space::Model, &Options::default());
// The second dash (the first is cut where the centred pattern meets the line's start).
let second = l.prims.iter().filter(|p| p.kind == Kind::Polyline).nth(1).map(|p| l.points(p).to_vec()).unwrap();
assert!((second[0].dist(second[1]) - 0.5).abs() < 1e-9);
let first = l.prims.iter().find(|p| p.kind == Kind::Polyline).map(|p| l.points(p).to_vec()).unwrap();
assert!((first[0].dist(first[1]) - 0.5).abs() < 1e-9);
}
+3 -87
View File
@@ -40,96 +40,12 @@ fn wide_polyline_dashes_are_filled_bands() {
assert!(dashed.iter().all(|q| (q.y.abs() - 0.1).abs() < 1e-9), "dashes keep the full width");
}
#[test]
fn a_band_more_than_50000_periods_long_keeps_its_dashes_without_a_level_of_detail() {
// 50,001 DASHED periods: two thirds of the band is dashes (0.5 of each 0.75, the end ones
// halves), as a plot or export draws it; a display build, with a level of detail, draws it
// whole (#1069).
let len = 50_001.0 * 0.75;
let d = drawing(&[0.0, len], "DASHED", false);
let dashed = area(&tris(&d));
assert!((dashed - 0.2 * len * 2.0 / 3.0).abs() < 1e-4, "{dashed}");
let l = build(&d, &Space::Model, &Options { min_dash: 1e-6, ..Default::default() });
let whole = area(&l.prims.iter().filter(|p| p.kind == Kind::Tris).flat_map(|p| l.points(p).to_vec()).collect::<Vec<_>>());
assert!((whole - 0.2 * len).abs() < 1e-4, "{whole}");
}
#[test]
fn a_closed_plinegen_band_is_stretched_around_as_a_thin_one_is() {
// A closed 10.5 square is 42 around: 56 DASHED periods laid from its second vertex, 10.5 along
// (a whole number of periods), so the first side has dashes at 0-0.5, 0.75-1.25…; laid as an
// open run they would be centred, at 0-0.25, 0.5-1.0….
let mut d = Drawing::new_imperial();
d.linetypes.extend(library::standard_linetypes().into_iter().filter(|l| l.name == "DASHED"));
let p = LwPolyline {
vertices: [(0.0, 0.0), (10.5, 0.0), (10.5, 10.5), (0.0, 10.5)].map(|(x, y)| PolyVertex::new(Vec2::new(x, y))).to_vec(),
closed: true,
const_width: 0.2,
elevation: 0.0,
plinegen: true,
};
d.add(&Space::Model, Common { linetype: "DASHED".into(), ..Default::default() }, EntityKind::LwPolyline(p)).unwrap();
let t = tris(&d);
let on_first_side = |x: f64| t.iter().any(|q| (q.x - x).abs() < 1e-9 && q.y.abs() <= 0.1 + 1e-9);
assert!(on_first_side(0.75) && on_first_side(1.25) && !on_first_side(1.0), "{t:?}");
// With fill off only the centre line is drawn, laid out the same way.
d.header.set_i64("FILLMODE", 0);
let l = build(&d, &Space::Model, &Options::default());
let starts: Vec<Vec2> = l.prims.iter().filter(|p| p.kind == Kind::Polyline).filter_map(|p| l.points(p).first().copied()).collect();
let starts_at = |x: f64| starts.iter().any(|q| (q.x - x).abs() < 1e-9 && q.y.abs() < 1e-9);
assert!(starts_at(0.75) && !starts_at(0.5), "{starts:?}");
}
#[test]
fn a_closed_plinegen_run_is_anchored_at_its_second_vertex_after_an_arc() {
// The first segment is an arc (bulge 0.5): the pattern is measured along the run as drawn, so
// a dash starts right at the second vertex, without width and with fill off alike.
for width in [0.0, 0.2] {
let mut d = Drawing::new_imperial();
d.linetypes.extend(library::standard_linetypes().into_iter().filter(|l| l.name == "DASHED"));
d.header.set_i64("FILLMODE", 0);
let mut vertices: Vec<PolyVertex> =
[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)].map(|(x, y)| PolyVertex::new(Vec2::new(x, y))).to_vec();
if let Some(v) = vertices.first_mut() {
v.bulge = 0.5;
}
let p = LwPolyline { vertices, closed: true, const_width: width, elevation: 0.0, plinegen: true };
d.add(&Space::Model, Common { linetype: "DASHED".into(), ..Default::default() }, EntityKind::LwPolyline(p)).unwrap();
let l = build(&d, &Space::Model, &Options::default());
let starts: Vec<Vec2> = l.prims.iter().filter(|p| p.kind == Kind::Polyline).filter_map(|p| l.points(p).first().copied()).collect();
assert!(starts.iter().any(|q| q.dist(Vec2::new(10.0, 0.0)) < 1e-9), "{width}: {starts:?}");
}
}
#[test]
fn a_closed_plinegen_run_whose_first_two_vertices_coincide_is_anchored_at_them() {
// The zero-length first segment is left out of the drawn run, but the second vertex is still
// where the run starts: the 40-unit square is stretched to 53 DASHED periods from there, so
// dashes start at 0 and 40/53 (not 10 + k * 40/53, from the next vertex). Without width, with
// fill off, and with fill on (the band's centre line) alike.
for (width, fill) in [(0.0, 0), (0.2, 0), (0.2, 1)] {
let mut d = Drawing::new_imperial();
d.linetypes.extend(library::standard_linetypes().into_iter().filter(|l| l.name == "DASHED"));
d.header.set_i64("FILLMODE", fill);
let vertices: Vec<PolyVertex> =
[(0.0, 0.0), (0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)].map(|(x, y)| PolyVertex::new(Vec2::new(x, y))).to_vec();
let p = LwPolyline { vertices, closed: true, const_width: width, elevation: 0.0, plinegen: true };
d.add(&Space::Model, Common { linetype: "DASHED".into(), ..Default::default() }, EntityKind::LwPolyline(p)).unwrap();
let l = build(&d, &Space::Model, &Options { min_dash: 1e-6, ..Default::default() });
let starts: Vec<Vec2> = l.prims.iter().filter(|p| p.kind == Kind::Polyline).filter_map(|p| l.points(p).first().copied()).collect();
for x in [0.0, 40.0 / 53.0] {
assert!(starts.iter().any(|q| q.dist(Vec2::new(x, 0.0)) < 1e-9), "{width} {fill} {x}: {starts:?}");
}
}
}
#[test]
fn plinegen_runs_the_pattern_along_the_whole_polyline() {
// Two 0.6 segments: per segment each is shorter than the 0.75 pattern, so drawn continuous;
// along the whole 1.2 the centred pattern gives 0.475 + 0.475.
// Two 0.6 segments: per segment each gets one 0.5 dash; along the whole 1.2 the pattern
// gives 0.5 + 0.45.
let per_segment = area(&tris(&drawing(&[0.0, 0.6, 1.2], "DASHED", false)));
let whole = area(&tris(&drawing(&[0.0, 0.6, 1.2], "DASHED", true)));
assert!((per_segment - 0.24).abs() < 1e-9, "{per_segment}");
assert!((per_segment - 0.2).abs() < 1e-9, "{per_segment}");
assert!((whole - 0.19).abs() < 1e-9, "{whole}");
}
+2 -4
View File
@@ -11,10 +11,6 @@ workspace = true
[dependencies]
craft-ui = { workspace = true }
craft-behavior = { workspace = true }
craft-host = { workspace = true }
craft-keymap = { workspace = true, features = ["egui"] }
craft-theme = { workspace = true }
cadcraft-geom = { workspace = true }
cadcraft-color = { workspace = true }
cadcraft-doc = { workspace = true }
@@ -39,6 +35,8 @@ web-time = { workspace = true }
craft-update = { workspace = true }
[dev-dependencies]
# Tests build the dock area as the desktop app does (headless contexts keep floats in-window).
craft-ui = { workspace = true, features = ["native-windows"] }
# The workspace `egui` dependency enables `default_fonts` and `monochrome_emoji_fonts` in
# production too; the tests exercise the same installed chain as the app.
egui_kittest = { workspace = true, features = ["wgpu", "snapshot"] }
-2
View File
@@ -28,7 +28,6 @@ fn ready(kind: ArrayLiveKind) -> (CadApp, Handle) {
fn frames(app: &mut CadApp) -> egui::Context {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
app.logic(&ctx);
let input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 1000.0))), ..Default::default() };
for _ in 0..10 {
@@ -152,7 +151,6 @@ fn apply_live_applies_a_changed_value() {
fn dialog_returns_immediately_without_state() {
let mut app = CadApp::new(Session::new(), Services::default());
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut open = true;
dialog(&mut app, &ctx, &mut open);
assert!(open, "no state: the window is left untouched");
+1 -1
View File
@@ -124,7 +124,7 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) {
ui.label(RichText::new(crate::tl!("Values typed at the command line work too")).small().color(t.text_dim));
});
});
if crate::framework::escape_pressed(ctx) {
if ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
done = Done::Cancel;
}
if fresh {
+1 -1
View File
@@ -227,7 +227,7 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) {
later = true;
}
});
if crate::framework::escape_pressed(ui.ctx()) {
if ui.input(|i| i.key_pressed(egui::Key::Escape)) {
later = true;
}
});
+1 -1
View File
@@ -857,7 +857,7 @@ pub fn section(app: &mut CadApp, ui: &mut egui::Ui) {
let w = (ui.available_width() - 150.0).max(80.0);
ui.add(egui::TextEdit::singleline(&mut st.filter).hint_text(crate::tl!("Filter")).desired_width(w));
let view_label = ui.label(crate::tl!("View"));
egui::ComboBox::from_id_salt("blocks-view")
craft_ui::ComboBox::from_id_salt("blocks-view")
.selected_text(st.view.label())
.show_ui(ui, |ui| {
for v in View::ALL {
+2 -39
View File
@@ -207,10 +207,6 @@ pub struct CanvasState {
hover_cycle: Option<(Pos2, Vec<Handle>, usize)>,
/// What the cycling list and the Shift+Space highlight were made for (see [`CycleKey`]).
cycle_key: Option<CycleKey>,
/// The drawing (its uid) shown in the last pass; `None` while the Start page is.
pub(crate) shown: Option<u64>,
/// A drawing opened or became active and has yet to ask for the keyboard focus ([`focus_opened`]).
wants_focus: bool,
}
/// The command, prompt, drawing (and its revision) and view that the objects under the cursor
@@ -728,7 +724,7 @@ fn update_hover(app: &mut CadApp, ui: &egui::Ui, inside: bool, hover_pos: Option
app.canvas.hover_at = None;
}
// The open selection cycling list highlights the object of the row under the pointer.
if app.canvas.cycle.is_some() && crate::framework::escape_pressed(ui.ctx()) {
if app.canvas.cycle.is_some() && ui.input(|i| i.key_pressed(egui::Key::Escape)) {
app.canvas.cycle = None;
}
if let Some(c) = &app.canvas.cycle {
@@ -845,38 +841,6 @@ pub(crate) fn right_click_cancels_placing(app: &CadApp) -> bool {
&& app.session.current_prompt().is_some_and(|p| p.message == "Specify insertion point")
}
/// A press in the drawing gives it the keyboard focus, so Tab reaches the command line. Real presses only: with the
/// drawing focused, egui makes Enter and Space clicks of it.
fn focus_on_press(resp: &egui::Response) {
if resp.is_pointer_button_down_on() && resp.ctx.input(|i| i.pointer.any_pressed()) {
resp.request_focus();
}
}
/// A drawing that opens or becomes active asks for the keyboard focus, because typing goes to its command line. So does
/// the drawing while nothing is focused and its command line has work for Tab. It waits for a modal dialog, menu or
/// popup to close, and leaves the focus with a text field and with a widget of another window. Called after [`show`], so
/// a key that opened the drawing is not read again by the command line.
pub(crate) fn focus_opened(app: &mut CadApp, ctx: &egui::Context) {
let doc = app.session.docs.get(app.session.active).map(|doc| doc.uid);
if app.canvas.shown != doc {
app.canvas.shown = doc;
app.canvas.wants_focus = true;
}
let focused = ctx.memory(|memory| memory.focused());
// Escape in a palette's field leaves the focus nowhere.
let tab_work = focused.is_none() && crate::cmdline::tab_has_work(app);
if !(app.canvas.wants_focus || tab_work) || crate::framework::overlay_open(app, ctx) {
return;
}
app.canvas.wants_focus = false;
let drawing = crate::framework::drawing_id();
let layer = |id| ctx.read_response(id).map(|widget| widget.layer_id);
if !ctx.text_edit_focused() && focused.is_none_or(|id| layer(id) == layer(drawing)) {
ctx.memory_mut(|memory| memory.request_focus(drawing));
}
}
/// Draw the drawing area and handle its input (zoom and pan, picking, the crosshair) for this
/// frame.
///
@@ -892,8 +856,7 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) {
// draws the others.
let tiles = tile_rects(app, full);
let rect = tiles.iter().find(|(_, tile)| tile.active).map_or(full, |(r, _)| *r);
let resp = ui.interact(full, crate::framework::drawing_id(), Sense::click_and_drag());
focus_on_press(&resp);
let resp = ui.interact(full, ui.scope_id().with("canvas"), Sense::click_and_drag());
let painter = ui.painter_at(rect);
app.canvas.rect = Some(rect);
app.session.viewport_px = (f64::from(rect.width()).max(1.0), f64::from(rect.height()).max(1.0));
+2 -2
View File
@@ -42,8 +42,8 @@ pub(super) fn grip_menu(app: &mut CadApp, resp: &egui::Response) {
let Some(g) = app.canvas.grip_menu else { return };
let options = grip_options(app, g);
let mut chosen: Option<Option<cadcraft_engine::grips::GripAction>> = None;
let open = crate::context_menu::popup(resp)
.show(|ui| {
let open = resp
.context_menu(|ui| {
let vertex = options.contains(&cadcraft_engine::grips::GripAction::RemoveVertex);
if ui.button(crate::i18n::t(if vertex { "Stretch Vertex" } else { "Stretch" })).clicked() {
chosen = Some(None);
-1
View File
@@ -83,7 +83,6 @@ mod hatch_pick_tests {
let hx = app.session.execute("hatch", &json!({ "points": [[5, 5]], "pattern": "SOLID" })).unwrap()["handle"].as_str().unwrap().to_string();
let _ = app.session.zoom_extents();
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let screen = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 1000.0)));
let frame = |app: &mut CadApp, events: Vec<egui::Event>, time: f64| {
app.logic(&ctx);
-6
View File
@@ -184,7 +184,6 @@ fn wheel_zoom_reads_every_notch_of_the_frame() {
#[test]
fn a_wheel_notch_zooms_whole_in_its_own_frame() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let o = ctx.options(|o| o.input_options);
let input = egui::RawInput { events: vec![wheel(egui::MouseWheelUnit::Line, 1.0, egui::Modifiers::NONE)], ..Default::default() };
let mut seen = (0.0, 0.0);
@@ -232,7 +231,6 @@ fn dynamic_input_distance_follows_the_drawing_units() {
let mut app = CadApp::new(cadcraft_engine::Session::new(), crate::Services::default());
app.session.execute("units", &serde_json::json!({"lunits": 4, "luprec": 4})).unwrap();
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
painted_text(&mut app, &ctx, pos2(700.0, 450.0));
app.session.cmdline("line").unwrap();
app.session.input(Input::Point(Vec2::ZERO)).unwrap();
@@ -277,7 +275,6 @@ fn cursor_shows_pickbox_only_at_command_object_selection_prompts() {
let at = pos2(400.0, 300.0);
let paint = |app: &CadApp| {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
let painter = ui.painter_at(rect);
let picking = app.session.picking_objects() && app.session.pending_window.is_none();
@@ -462,7 +459,6 @@ fn the_cycling_badge_follows_the_frozen_layers_under_a_resting_pointer() {
app.session.execute("setvar", &serde_json::json!({ "name": "SELECTIONCYCLING", "value": 1 })).unwrap();
app.session.execute("mspace", &serde_json::json!({ "handle": b })).unwrap();
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
/// Whether the badge shows after a frame with the pointer resting on the two lines.
fn badge(app: &mut CadApp, ctx: &egui::Context) -> bool {
let (at, on_lines) = (Some(Pos2::new(200.0, 150.0)), Some(Vec2::new(50.0, 0.0)));
@@ -487,7 +483,6 @@ fn trim_highlights_the_piece_a_click_removes_once_per_cursor_position() {
}
app.session.zoom_extents().unwrap();
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
painted_text(&mut app, &ctx, pos2(700.0, 450.0));
app.session.cmdline("trim").unwrap();
let at = app.canvas.xf.unwrap().to_screen(Vec2::new(5.0, 0.0));
@@ -514,7 +509,6 @@ fn a_fence_point_taken_back_with_undo_updates_the_highlight_at_once() {
}
app.session.zoom_extents().unwrap();
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
painted_text(&mut app, &ctx, pos2(700.0, 450.0));
for answer in ["trim", "f", "5,-4", "5,1.5"] {
app.session.cmdline(answer).unwrap();
+21 -16
View File
@@ -1,15 +1,15 @@
//! Bounded, one-shot window screenshots for `ui.screenshot`.
//!
//! The request record owns the output path, reply, deadline, document/focus identity and the
//! geometry it was admitted against. The runtime's `ScreenshotSlot`, made when the capture is issued
//! (`WindowHost::screenshot`), owns the strong `egui::Context`; its screenshot callback holds only a
//! weak reference and never writes a file.
//! geometry it was admitted against. The shared `craft_ui::capture::CaptureSlot` owns the strong
//! `egui::Context`; its screenshot callback holds only a weak reference and never writes a file.
//! Files are encoded and written only from the logic drain, after the deadline and every identity
//! check have passed.
use std::sync::mpsc::Sender;
use craft_ui::runtime::windows::{ScreenshotSlot, WindowHost};
use craft_ui::capture::CaptureSlot;
use egui::ViewportCommand;
use serde_json::{Value, json};
use web_time::{Duration, Instant};
@@ -174,8 +174,8 @@ struct Shot {
geometry: SurfaceGeometry,
expected: [usize; 2],
reserved: usize,
/// The runtime's screenshot slot, from the moment the capture is issued.
slot: Option<ScreenshotSlot>,
slot: Option<CaptureSlot>,
callback: Option<egui::ScreenshotCallback>,
}
/// All admitted screenshots. `requests` includes queued, issued and completed-but-undrained
@@ -234,10 +234,9 @@ fn active_document(app: &CadApp) -> Option<u64> {
app.session.docs.get(app.session.active).map(|doc| doc.uid)
}
/// The widget egui currently reports as keyboard-focused, if any. The drawing's focus shows nothing, so it counts as
/// none: a command that opens a drawing moves the focus to it in a later frame.
/// The widget egui currently reports as keyboard-focused, if any.
fn current_focus(ctx: &egui::Context) -> Option<egui::Id> {
ctx.memory(|memory| memory.focused()).filter(|id| *id != crate::framework::drawing_id())
ctx.memory(|memory| memory.focused())
}
/// Snapshot the active drawing UID, the monotonic document epoch and the focused widget together.
@@ -345,6 +344,7 @@ pub(crate) fn admit(app: &mut CadApp, ctx: &egui::Context, path: Option<String>,
format!("screenshot budget exceeded: {total} bytes reserved by outstanding requests, over the {MAX_TOTAL_BYTES}-byte limit"),
);
}
let (slot, callback) = CaptureSlot::new(ctx, ctx.viewport_id(), MAX_IMAGE_BYTES);
let now = Instant::now();
app.shots.requests.push(Shot {
token,
@@ -360,7 +360,8 @@ pub(crate) fn admit(app: &mut CadApp, ctx: &egui::Context, path: Option<String>,
geometry: geometry.surface,
expected,
reserved,
slot: None,
slot: Some(slot),
callback: Some(callback),
});
ctx.request_repaint();
}
@@ -389,10 +390,10 @@ fn identity_change(app: &CadApp, ctx: &egui::Context, shot: &Shot) -> Option<&'s
/// Issue settled requests from the first non-discarded UI pass.
///
/// A pass is skipped only when `craft_ui::runtime::frame::will_rerun` says it will run again, and
/// the final pass of a multi-pass frame reports false; a hidden `run_logic` tick never reaches `issue` at all.
/// egui discards a pass only when `will_discard()` says so, and the final pass of a multi-pass
/// frame reports false; a hidden `run_logic` tick never reaches `issue` at all.
pub(crate) fn issue(app: &mut CadApp, ctx: &egui::Context) {
if craft_ui::runtime::frame::will_rerun(ctx) {
if ctx.will_discard() {
return;
}
// The draw may have moved the focus or switched drawings: observe that before judging.
@@ -446,7 +447,11 @@ pub(crate) fn issue(app: &mut CadApp, ctx: &egui::Context) {
continue;
}
let shot = &mut app.shots.requests[i];
shot.slot = Some(WindowHost::of(ctx).screenshot(ctx.viewport_id(), MAX_IMAGE_BYTES));
let Some(callback) = shot.callback.take() else {
failures.push((i, "screenshot failed: the capture callback was already consumed".into()));
continue;
};
ctx.send_viewport_cmd_to(ctx.viewport_id(), ViewportCommand::Screenshot(callback));
shot.issued = true;
shot.identity = current.identity;
shot.geometry = current.surface;
@@ -504,7 +509,7 @@ pub(crate) fn drain(app: &mut CadApp, ctx: &egui::Context) {
reject(shot.reply, shot.token, "screenshot failed: the window geometry changed while the capture was queued");
continue;
}
let Some(result) = app.shots.requests[i].slot.as_ref().and_then(ScreenshotSlot::take) else {
let Some(result) = app.shots.requests[i].slot.as_ref().and_then(CaptureSlot::take) else {
i += 1;
continue;
};
@@ -555,7 +560,7 @@ pub(crate) fn cancel_all(app: &mut CadApp) {
pub(crate) fn request_hidden_paint(app: &CadApp, ctx: &egui::Context) {
if app.shots.has_unissued() {
#[cfg(not(target_arch = "wasm32"))]
ctx.send_viewport_cmd(egui::ViewportCommand::RequestPaintWhileHidden);
ctx.send_viewport_cmd(ViewportCommand::RequestPaintWhileHidden);
ctx.request_repaint();
}
}
+11 -39
View File
@@ -50,13 +50,10 @@ fn ui_frame(app: &mut CadApp, ctx: &egui::Context) -> egui::FullOutput {
ui_frame_sized(app, ctx, 800.0, 600.0)
}
/// Run one real frame at the requested size, as the desktop app does (the raw input hooks, then `logic` + `ui`), and
/// drop texture deltas, yielding the frame's output. The framework's hook gives the runtime the Options interface
/// scale, which it applies as egui's zoom.
/// Run one real `logic` + `ui` pass at the requested size and drop texture deltas, yielding the frame's output.
fn ui_frame_sized(app: &mut CadApp, ctx: &egui::Context, width: f32, height: f32) -> egui::FullOutput {
let mut raw = raw(width, height);
app.raw_input_hook(ctx, &mut raw);
app.before_input(ctx);
let raw = raw(width, height);
note_raw_geometry(app, ctx, &raw);
let mut out = ctx.run_ui(raw, |ui| {
app.logic(ui.ctx());
app.ui(ui);
@@ -103,22 +100,12 @@ fn complete(callbacks: Vec<egui::ScreenshotCallback>, size: [usize; 2]) {
#[test]
fn admission_counts_completed_but_undrained_and_never_evicts() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = app();
// One geometry for every admission: a geometry seeded again between them is an identity change that rejects the
// queued requests at the next drain.
set_geometry(&mut app, &ctx, egui::vec2(800.0, 600.0));
let _receivers: Vec<_> = (0..MAX_REQUESTS)
.map(|_| {
let (tx, rx) = channel();
admit(&mut app, &ctx, None, tx);
rx
})
.collect();
let _receivers: Vec<_> = (0..MAX_REQUESTS).map(|_| admit_one(&mut app, &ctx)).collect();
assert_eq!(app.shots.len(), MAX_REQUESTS);
// Complete the issued slots without draining them: each still owns its reservation and request.
let (_, callbacks) = issue_after_settling(&mut app, &ctx);
complete(callbacks, [800, 600]);
// Complete the first slot without draining it: it still owns its reservation and request.
let image = Arc::new(ColorImage::filled([800, 600], Color32::RED));
app.shots.requests[0].callback.take().expect("a callback").complete(image);
let (tx, rx) = channel();
admit(&mut app, &ctx, None, tx);
assert_eq!(app.shots.len(), MAX_REQUESTS, "the fifth request is rejected, not admitted");
@@ -132,12 +119,13 @@ fn admission_counts_completed_but_undrained_and_never_evicts() {
#[test]
fn deadline_is_checked_before_writing_a_completed_image() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = app();
let (rx, _) = admit_one(&mut app, &ctx);
let (_, callbacks) = issue_after_settling(&mut app, &ctx);
app.shots.requests[0].issued = true;
app.shots.requests[0].surface_epoch = app.capture_epoch;
app.shots.requests[0].deadline = Instant::now() - Duration::from_millis(1);
complete(callbacks, [800, 600]);
let image = Arc::new(ColorImage::filled([800, 600], Color32::RED));
app.shots.requests[0].callback.take().expect("a callback").complete(image);
drain(&mut app, &ctx);
let reply = rx.recv().expect("a timeout reply");
assert_eq!(reply["ok"], false);
@@ -149,7 +137,6 @@ fn deadline_is_checked_before_writing_a_completed_image() {
#[test]
fn document_change_cancels_before_issuing() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = app();
let (rx, _) = admit_one(&mut app, &ctx);
app.session.new_drawing(false);
@@ -163,7 +150,6 @@ fn document_change_cancels_before_issuing() {
#[test]
fn focus_change_cancels_an_unissued_capture() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let focus_a = egui::Id::unique("focus-a");
let focus_b = egui::Id::unique("focus-b");
ctx.memory_mut(|memory| memory.request_focus(focus_a));
@@ -184,7 +170,6 @@ fn focus_change_cancels_an_unissued_capture() {
fn issued_callbacks_reply_once_with_matching_tokens_and_distinct_pathless_files() {
let _shots = crate::control::lock_pathless_shots();
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = app();
set_geometry(&mut app, &ctx, egui::vec2(800.0, 600.0));
let (tx1, rx1) = channel();
@@ -214,7 +199,6 @@ fn issued_callbacks_reply_once_with_matching_tokens_and_distinct_pathless_files(
#[test]
fn document_switch_after_issue_rejects_the_completed_callback_without_writing() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = app();
let (rx, token) = admit_one(&mut app, &ctx);
let (_, callbacks) = issue_after_settling(&mut app, &ctx);
@@ -233,7 +217,6 @@ fn document_switch_after_issue_rejects_the_completed_callback_without_writing()
#[test]
fn completed_callback_after_timeout_writes_nothing() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = app();
let (rx, _) = admit_one(&mut app, &ctx);
let (_, callbacks) = issue_after_settling(&mut app, &ctx);
@@ -250,7 +233,6 @@ fn completed_callback_after_timeout_writes_nothing() {
#[test]
fn callback_completed_before_cancel_all_is_inert() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = app();
let (rx, token) = admit_one(&mut app, &ctx);
let (_, callbacks) = issue_after_settling(&mut app, &ctx);
@@ -267,7 +249,6 @@ fn callback_completed_before_cancel_all_is_inert() {
#[test]
fn per_image_and_aggregate_budgets_reject_before_issue() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = app();
// 5000×5000×4 bytes = 100 MB, over the 64 MiB per-image bound.
set_geometry(&mut app, &ctx, egui::vec2(5000.0, 5000.0));
@@ -301,7 +282,6 @@ fn admit_one_at(app: &mut CadApp, ctx: &egui::Context, size: egui::Vec2) -> (Rec
#[test]
fn every_observed_geometry_change_bumps_the_generation() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = app();
note_raw_geometry(&mut app, &ctx, &raw(800.0, 600.0));
let first = app.capture_epoch;
@@ -319,7 +299,6 @@ fn every_observed_geometry_change_bumps_the_generation() {
#[test]
fn an_invalid_pass_invalidates_the_retained_surface() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = app();
note_raw_geometry(&mut app, &ctx, &raw(800.0, 600.0));
assert!(app.capture_geometry.is_some(), "the raw snapshot was retained");
@@ -345,7 +324,6 @@ fn an_invalid_pass_invalidates_the_retained_surface() {
#[test]
fn raw_geometry_uses_screen_rect_when_inner_rect_is_absent() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = app();
let mut raw = egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(640.0, 480.0))),
@@ -366,7 +344,6 @@ fn raw_geometry_uses_screen_rect_when_inner_rect_is_absent() {
fn a_discarded_pass_does_not_issue_and_the_settled_pass_does_once() {
let _shots = crate::control::lock_pathless_shots();
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = app();
let (rx, _) = admit_one(&mut app, &ctx);
for shot in &mut app.shots.requests {
@@ -399,7 +376,6 @@ fn a_discarded_pass_does_not_issue_and_the_settled_pass_does_once() {
fn issuance_uses_the_settled_interface_scale_not_the_admission_estimate() {
let _shots = crate::control::lock_pathless_shots();
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = app();
app.options.interface_scale = 2.0;
let raw = raw(800.0, 600.0);
@@ -420,7 +396,6 @@ fn issuance_uses_the_settled_interface_scale_not_the_admission_estimate() {
#[test]
fn a_document_switch_that_returns_still_rejects_the_queued_capture() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = app();
app.session.new_drawing(false);
let (rx, _) = admit_one(&mut app, &ctx);
@@ -442,7 +417,6 @@ fn a_document_switch_that_returns_still_rejects_the_queued_capture() {
#[test]
fn a_drawing_created_and_closed_between_observations_still_bumps_the_identity_epoch() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = app();
set_geometry(&mut app, &ctx, egui::vec2(800.0, 600.0));
let before_epoch = app.capture_identity_epoch;
@@ -459,7 +433,6 @@ fn a_drawing_created_and_closed_between_observations_still_bumps_the_identity_ep
#[test]
fn a_settled_window_does_not_keep_changing_the_surface_epoch() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = app();
ui_frame(&mut app, &ctx).drop_without_applying_deltas();
let epoch = app.capture_epoch;
@@ -477,7 +450,6 @@ fn a_settled_window_does_not_keep_changing_the_surface_epoch() {
fn a_resize_while_settling_is_absorbed_at_issue() {
let _shots = crate::control::lock_pathless_shots();
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = app();
let (rx, _) = admit_one(&mut app, &ctx);
for shot in &mut app.shots.requests {
+41 -19
View File
@@ -1,6 +1,5 @@
//! Window chrome: title and tool bar, file tabs, status bar and the Start page.
use craft_behavior::fit::{FitItem, FitKeep};
use egui::{Rect, Sense, Stroke, pos2, vec2};
use serde_json::json;
@@ -41,11 +40,26 @@ const TOOLBAR: &[&[(Icon, &str, &str, Option<&str>)]] = &[
&[(Icon::Help, "ui.dialog.about", "Help", None)],
];
/// Height of the macOS integrated title row (#161): the standard 28 pt title-bar band AppKit centres the traffic
/// lights in.
/// Height of the macOS integrated title row (#161). AppKit draws the traffic lights itself,
/// centred in the standard 28 pt title-bar band at the top of the window; moving them would take
/// AppKit calls (`unsafe`, which the workspace forbids). So the title row is that band, and what
/// it holds is centred on the same line as the lights.
const MAC_TITLE_BAR: f32 = 28.0;
/// The width of the toolbar's More button.
const MORE_WIDTH: f32 = 30.0;
/// The traffic lights as AppKit lays them out: button diameter, centre-to-centre pitch and the
/// first button's left edge (8–10 pt depending on the macOS version; the larger value keeps the
/// gap after them from shrinking).
const MAC_LIGHT: f32 = 12.0;
const MAC_LIGHT_PITCH: f32 = 20.0;
const MAC_LIGHTS_LEFT: f32 = 10.0;
/// Where title-row content may start to the right of the traffic lights: the end of the three
/// lights plus the same gap the lights keep from the top of the window.
const MAC_CONTENT_LEFT: f32 = MAC_LIGHTS_LEFT + 2.0 * MAC_LIGHT_PITCH + MAC_LIGHT + (MAC_TITLE_BAR - MAC_LIGHT) / 2.0;
/// Left edge of the window title in a title row starting at `left`, `width` wide: centred, but
/// never under the traffic lights (a long drawing name in a narrow window slides right instead).
fn title_left(left: f32, width: f32, text_w: f32) -> f32 {
(left + (width - text_w) / 2.0).max(left + MAC_CONTENT_LEFT)
}
/// Title row (with the integrated macOS title bar) and the Tool Bar.
pub fn title_and_toolbar(app: &mut CadApp, ui: &mut egui::Ui) {
@@ -55,18 +69,17 @@ pub fn title_and_toolbar(app: &mut CadApp, ui: &mut egui::Ui) {
egui::Panel::top("cc_title_toolbar").exact_size(title_h + tb_h).frame(egui::Frame::NONE.fill(t.chrome)).show(ui, |ui| {
let r = ui.max_rect();
if title_h > 0.0 {
// The window's title bar: its free area moves the window and follows the system's double-click setting.
// The empty row moves the window; it goes first so later widgets take their own clicks.
craft_window::title_bar::empty_area(ui, Rect::from_min_size(r.min, vec2(r.width(), title_h)));
let title = match app.session.state() {
Ok(st) if !app.ui.start_tab => format!("CADCraft {}{}", st.title, if st.title.contains('.') { "" } else { ".dwg" }),
_ => format!("CADCraft {}", crate::tl!("Start")),
};
let row = Rect::from_min_size(r.min, vec2(r.width(), title_h));
ui.scope_builder(egui::UiBuilder::new().max_rect(row), |ui| {
let bar = craft_ui::shell::TitleBar::new().show_titled(ui, craft_ui::shell::Title::new(title), |_, _| {}, |_, _| {});
if bar.close_requested {
ui.ctx().send_viewport_cmd(egui::ViewportCommand::Close);
}
});
// Centred on the traffic lights' centre line (the row's middle): with the system font
// the capitals' middle is the text box's middle, so no optical nudge.
let galley = ui.painter().layout_no_wrap(title, egui::FontId::proportional(13.0), t.text_dim);
let x = title_left(r.left(), r.width(), galley.size().x);
ui.painter().galley(pos2(x, r.top() + (title_h - galley.size().y) / 2.0), galley, t.text_dim);
}
if tb_h > 0.0 {
let row = Rect::from_min_size(pos2(r.left(), r.top() + title_h), vec2(r.width(), tb_h));
@@ -76,9 +89,7 @@ pub fn title_and_toolbar(app: &mut CadApp, ui: &mut egui::Ui) {
let mac = ui.ctx().os().is_mac();
let widths: Vec<_> = TOOLBAR.iter().map(|group| group.len() as f32 * (size + 6.0) - 6.0).collect();
let available = (row.right() - 12.0 - x).max(0.0);
let items: Vec<_> = widths.iter().enumerate().map(|(i, w)| FitItem::new(*w, i as u16, FitKeep::Free)).collect();
let fit = craft_behavior::fit::fit_items(&items, available, 24.0, 24.0, MORE_WIDTH);
if !fit.overflow.is_empty() && available < MORE_WIDTH {
let Some(fit) = craft_ui::layout::fit_toolbar(&widths, available, 24.0, 30.0) else {
// Very small windows still expose the complete command row by scrolling.
ui.scope_builder(egui::UiBuilder::new().max_rect(row.shrink2(vec2(4.0, 0.0))), |ui| {
egui::ScrollArea::horizontal().id_salt("toolbar_small").show(ui, |ui| {
@@ -98,8 +109,8 @@ pub fn title_and_toolbar(app: &mut CadApp, ui: &mut egui::Ui) {
app.start(command);
}
return;
}
for index in &fit.shown {
};
for (index, _) in &fit.shown {
let Some(group) = TOOLBAR.get(*index) else { continue };
for (icon, cmd, label, shortcut) in group.iter() {
let br = Rect::from_min_size(pos2(x, row.center().y - size / 2.0), vec2(size, size));
@@ -121,7 +132,7 @@ pub fn title_and_toolbar(app: &mut CadApp, ui: &mut egui::Ui) {
x += 18.0;
}
if !fit.overflow.is_empty() {
let br = Rect::from_min_size(pos2(x, row.center().y - size / 2.0), vec2(MORE_WIDTH, size));
let br = Rect::from_min_size(pos2(x, row.center().y - size / 2.0), vec2(fit.overflow_width, size));
let response = ui.interact(br, ui.scope_id().with("toolbar_more"), Sense::click());
if response.hovered() {
ui.painter().rect_filled(br, 3.0, t.control_hover.gamma_multiply(0.6));
@@ -609,6 +620,17 @@ pub fn start_page(app: &mut CadApp, ui: &mut egui::Ui) {
mod tests {
use super::*;
#[test]
fn mac_title_row_centres_and_clears_the_traffic_lights() {
// The lights are centred in the row, and content keeps the same gap after them.
let margin = (MAC_TITLE_BAR - MAC_LIGHT) / 2.0;
let lights_end = MAC_LIGHTS_LEFT + 2.0 * MAC_LIGHT_PITCH + MAC_LIGHT;
assert_eq!(MAC_CONTENT_LEFT - lights_end, margin);
// A short title is centred; one too wide for that starts after the lights.
assert_eq!(title_left(100.0, 1000.0, 200.0), 500.0);
assert_eq!(title_left(100.0, 900.0, 800.0), 100.0 + MAC_CONTENT_LEFT);
}
#[test]
fn layout_tabs_that_do_not_fit_keep_the_current_one() {
let w = [50.0; 6];
+8 -11
View File
@@ -50,18 +50,15 @@ pub enum ShortcutAction {
/// The actions the Cut/Copy/Paste events of this frame ask for. Pasted DXF text that isn't our
/// own last copy (another CADCraft's) becomes the clipboard first; non-DXF tab-separated table text
/// starts `pastetable`.
///
/// `fired` holds the events a floating panel's window ran as framework commands ([`CadApp::queue_fired_edits`]); they
/// come before this window's own.
pub fn shortcut_actions(app: &mut CadApp, ctx: &egui::Context, fired: Vec<egui::Event>) -> Vec<ShortcutAction> {
// Each event with its Shift: the fired chords have none, whatever is held by the time this window reads them.
let events: Vec<(egui::Event, bool)> = ctx.input(|i| {
let own = i.events.iter().filter(|e| matches!(e, egui::Event::Copy | egui::Event::Cut | egui::Event::Paste(_)));
fired.into_iter().map(|e| (e, false)).chain(own.map(|e| (e.clone(), i.modifiers.shift))).collect()
pub fn shortcut_actions(app: &mut CadApp, ctx: &egui::Context) -> Vec<ShortcutAction> {
let (events, shift) = ctx.input(|i| {
let ev: Vec<egui::Event> =
i.events.iter().filter(|e| matches!(e, egui::Event::Copy | egui::Event::Cut | egui::Event::Paste(_))).cloned().collect();
(ev, i.modifiers.shift)
});
let paste_cmd = || if shift { "pasteblock" } else { "pasteclip" };
let mut out = Vec::new();
for (e, shift) in events {
let paste_cmd = || if shift { "pasteblock" } else { "pasteclip" };
for e in events {
match e {
egui::Event::Copy => out.push(ShortcutAction::Command(if shift { "copybase" } else { "copyclip" })),
egui::Event::Cut => out.push(ShortcutAction::Command("cutclip")),
@@ -265,7 +262,7 @@ pub fn pump(app: &mut CadApp, ctx: &egui::Context) {
}
if let Some(p) = app.paste.request.take() {
// A focused text field would take the `Paste` itself.
if crate::framework::widget_has_keyboard(ctx) {
if ctx.egui_wants_keyboard_input() {
run_now(app, p);
} else {
ctx.send_viewport_cmd(egui::ViewportCommand::RequestPaste);
+4 -10
View File
@@ -256,7 +256,7 @@ pub fn prompt(app: &mut CadApp, ctx: &egui::Context) {
choice = Some(Choice::Discard);
}
});
if crate::framework::escape_pressed(ui.ctx()) {
if ui.input(|i| i.key_pressed(egui::Key::Escape)) {
choice = Some(Choice::Cancel);
}
});
@@ -448,10 +448,7 @@ mod tests {
use egui::{ViewportCommand, ViewportEvent, ViewportId, ViewportInfo};
let mut input = egui::RawInput::default();
input.viewports.insert(ViewportId::ROOT, ViewportInfo { events: vec![ViewportEvent::Close], ..Default::default() });
let mut out = ctx.run_ui(input, |ui| {
app.logic(ui.ctx());
app.close_path(ui.ctx());
});
let mut out = ctx.run_ui(input, |ui| app.logic(ui.ctx()));
out.textures_delta.clear();
out.viewport_output.get(&ViewportId::ROOT).is_some_and(|v| v.commands.contains(&ViewportCommand::CancelClose))
}
@@ -460,10 +457,8 @@ mod tests {
#[test]
fn window_close_with_unsaved_changes_is_held() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = app_with(&["A"]);
// Only the app's decision: a close that goes ahead ends in the platform's quit, which macOS answers by cancelling it.
assert!(!app.request_quit(), "a saved drawing closes without asking");
assert!(!close_frame(&mut app, &ctx), "a saved drawing closes without asking");
dirty(&mut app, 0);
assert!(close_frame(&mut app, &ctx), "unsaved changes must cancel the close");
assert_eq!(app.close_prompt(), Some("A"));
@@ -473,12 +468,11 @@ mod tests {
#[test]
fn programmatic_quit_skips_the_prompt() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = app_with(&["A"]);
dirty(&mut app, 0);
let (req, _rx) = crate::control::ControlRequest::new("app.quit", json!({}));
let _ = crate::control::handle(&mut app, &ctx, &req);
assert!(!app.request_quit());
assert!(!close_frame(&mut app, &ctx));
assert!(app.closing.is_none());
}
+28 -31
View File
@@ -64,19 +64,33 @@ pub fn dyn_frame(app: &CadApp) -> Option<crate::dyninput::Frame> {
Some(crate::dyninput::Frame { base: p.base, cartesian: st.dynpi_cartesian, absolute: st.dynpi_absolute, ucs })
}
/// Whether Tab on the command line has something to act on: a running command or LISP prompt, typed
/// text, the Dynamic Input or grip value boxes, or a snap marker under the cursor.
pub(crate) fn tab_has_work(app: &CadApp) -> bool {
app.session.prompting() || !app.cmd.buffer.is_empty() || dyn_frame(app).is_some() || app.canvas.snap.is_some()
/// Take Tab away from egui before it moves keyboard focus to the next widget (which would leave
/// the command line deaf to typing). While no widget has focus, a pressed Tab becomes a `"\t"`
/// text event, which keeps its place among the other keystrokes; [`keyboard`] handles it.
pub fn capture_tab(ctx: &egui::Context, raw: &mut egui::RawInput) {
if ctx.egui_wants_keyboard_input() {
return;
}
raw.events.retain_mut(|e| {
let tab = match e {
egui::Event::Key { key: Key::Tab, pressed, .. } => Some(*pressed),
_ => None,
};
match tab {
Some(true) => {
*e = egui::Event::Text("\t".into());
true
}
Some(false) => false,
None => true,
}
});
}
/// Tab on the command line: cycle the object snaps under the cursor, type the Dynamic Input
/// separator (`,` or `<`) after a value, cycle between the two Dynamic Input boxes, or complete a
/// command name.
fn tab(app: &mut CadApp) {
if !tab_has_work(app) {
return;
}
// Grip dimensional input: Tab locks the typed value and moves to the next field.
if crate::grip_dyn::tab(app) {
return;
@@ -353,18 +367,14 @@ fn enable_ime(app: &mut CadApp, ctx: &egui::Context) {
});
}
/// Handle keyboard input destined for the command line (with nothing or the drawing focused).
/// Handle keyboard input destined for the command line (when no text field has focus).
pub fn keyboard(app: &mut CadApp, ctx: &egui::Context) {
if crate::framework::widget_has_keyboard(ctx) {
if ctx.egui_wants_keyboard_input() {
app.cmd.preedit.clear();
app.cmd.ime_on = false;
return;
}
let mut events = ctx.input(|i| i.events.clone());
// With nothing focused, Escape is the window's cancel, which the runtime keeps out of egui's events.
if crate::framework::window_cancel_pending(ctx) {
events.push(egui::Event::Key { key: Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE });
}
let events = ctx.input(|i| i.events.clone());
let selection = app.session.selection();
app.cmd.watch_selection(&selection);
let mac = ctx.os() == egui::os::OperatingSystem::Mac;
@@ -412,7 +422,9 @@ pub fn keyboard(app: &mut CadApp, ctx: &egui::Context) {
}
match ev {
egui::Event::Text(t) => {
if t == " " && !text_prompt {
if t == "\t" {
tab(app);
} else if t == " " && !text_prompt {
submit(app);
} else {
app.cmd.preedit.clear();
@@ -905,7 +917,6 @@ mod tests {
assert_eq!(app.session.current_prompt().map(|p| p.message.clone()).as_deref(), Some("Enter text"));
assert!(app.session.text_editor().is_none(), "no in-place editor at this prompt");
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let out = frame(&mut app, &ctx, Vec::new());
// The IME is enabled for the command line while it is collecting text.
assert!(out.platform_output.ime.is_some());
@@ -940,7 +951,6 @@ mod tests {
app.session.echo(format!("line {i}"));
}
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
frame(&mut app, &ctx, Vec::new());
frame(&mut app, &ctx, Vec::new());
let canvas = app.canvas.rect.unwrap_or(Rect::NOTHING);
@@ -1186,13 +1196,8 @@ mod dyn_tab_tests {
out.textures_delta.clear();
}
/// The key events of typing `text`, a tab character as a press of Tab.
fn typed(text: &str) -> Vec<egui::Event> {
let event = |c: char| match c {
'\t' => egui::Event::Key { key: Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE },
c => egui::Event::Text(c.to_string()),
};
text.chars().map(event).collect()
text.chars().map(|c| egui::Event::Text(c.to_string())).collect()
}
#[test]
@@ -1201,13 +1206,11 @@ mod dyn_tab_tests {
let mut app = CadApp::new(cadcraft_engine::Session::new(), crate::Services::default());
app.session.settings.dynmode = true;
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
run_frame(&mut app, &ctx, Vec::new());
let center = app.canvas.rect.map_or(egui::pos2(700.0, 450.0), |r| r.center());
run_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(center)]);
app.cmdline("line");
app.cmdline("0,0");
run_frame(&mut app, &ctx, Vec::new());
run_frame(&mut app, &ctx, typed("40\t90\t"));
assert!(app.cmd.first_active(), "{:?}", app.cmd.buffer);
let escape = egui::Key::Escape;
@@ -1234,13 +1237,11 @@ mod dyn_tab_tests {
let mut app = CadApp::new(cadcraft_engine::Session::new(), crate::Services::default());
app.session.settings.dynmode = true;
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
run_frame(&mut app, &ctx, Vec::new());
let center = app.canvas.rect.map_or(egui::pos2(700.0, 450.0), |r| r.center());
run_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(center)]);
app.cmdline("line");
app.cmdline("0,0");
run_frame(&mut app, &ctx, Vec::new());
run_frame(&mut app, &ctx, typed("40\t90\t"));
assert!(app.cmd.first_active(), "{:?}", app.cmd.buffer);
app.session.settings.dynmode = false;
@@ -1268,12 +1269,10 @@ mod dyn_tab_tests {
let mut app = CadApp::new(cadcraft_engine::Session::new(), crate::Services::default());
app.session.settings.dynmode = true;
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
run_frame(&mut app, &ctx, Vec::new());
let center = app.canvas.rect.map_or(egui::pos2(700.0, 450.0), |r| r.center());
app.cmdline("line");
app.cmdline("0,0");
run_frame(&mut app, &ctx, Vec::new());
run_frame(&mut app, &ctx, typed("40\t90\t"));
let back = egui::Key::Backspace;
let m = egui::Modifiers::NONE;
@@ -1335,12 +1334,10 @@ mod dyn_tab_tests {
let mut app = CadApp::new(cadcraft_engine::Session::new(), crate::Services::default());
app.session.settings.dynmode = true;
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
run_frame(&mut app, &ctx, Vec::new());
let center = app.canvas.rect.map_or(egui::pos2(700.0, 450.0), |r| r.center());
app.cmdline("line");
app.cmdline("0,0");
run_frame(&mut app, &ctx, Vec::new());
run_frame(&mut app, &ctx, typed("40<90\t"));
assert!(app.cmd.second_locked());
let at = center + egui::vec2(37.0, -23.0);
+1 -8
View File
@@ -388,13 +388,6 @@ pub fn groups_ui(ui: &mut egui::Ui, groups: &[Vec<Entry>], clicked: &mut Option<
}
}
/// A right-click menu of the drawing. Only real clicks open and close it: with the drawing focused, egui makes Enter and
/// Space clicks of it, and those go to the command line.
pub(crate) fn popup(drawing: &egui::Response) -> egui::Popup<'static> {
let open = if drawing.secondary_clicked() { Some(true) } else { drawing.clicked_by(egui::PointerButton::Primary).then_some(false) };
egui::Popup::context_menu(drawing).open_memory(open.map(egui::SetOpenCommand::Bool))
}
/// Attach the menu to the canvas response: it opens on a right-click, as the object snap menu
/// when that click held Shift or Ctrl (`CanvasState::snap_menu`).
pub fn show(app: &mut CadApp, resp: &egui::Response) {
@@ -418,7 +411,7 @@ pub fn show(app: &mut CadApp, resp: &egui::Response) {
}
return;
}
popup(resp).show(|ui| {
resp.context_menu(|ui| {
let groups = if snap { snap_entries(app) } else { entries(app) };
groups_ui(ui, &groups, &mut clicked);
});
+1 -1
View File
@@ -177,7 +177,7 @@ fn focus_json(ctx: &egui::Context) -> Value {
"id": focused.map(|id| format!("{:016x}", id.value())),
"label": widget.map(|widget| &widget.label),
"role": widget.map(|widget| widget.role),
"keyboardInput": crate::framework::widget_has_keyboard(ctx),
"keyboardInput": ctx.egui_wants_keyboard_input(),
})
}
+1 -1
View File
@@ -223,7 +223,7 @@ pub fn contributors_ui(ui: &mut egui::Ui) {
}
ui.separator();
ui.label(crate::tl!("Sort"));
egui::ComboBox::from_id_salt("credits_sort").selected_text(crate::i18n::t(v.key.label().0)).show_ui(ui, |ui| {
craft_ui::ComboBox::from_id_salt("credits_sort").selected_text(crate::i18n::t(v.key.label().0)).show_ui(ui, |ui| {
for k in SortKey::ALL {
if ui.selectable_label(v.key == k, crate::i18n::t(k.label().0)).clicked() {
v.key = k;
+3 -3
View File
@@ -100,7 +100,7 @@ fn dsettings(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
let mut deg = current;
ui.horizontal(|ui| {
let label = ui.label(crate::tl!("Increment angle"));
let combo = egui::ComboBox::from_id_salt("polarang").selected_text(format!("{deg}")).show_ui(ui, |ui| {
let combo = craft_ui::ComboBox::from_id_salt("polarang").selected_text(format!("{deg}")).show_ui(ui, |ui| {
for a in [90.0, 45.0, 30.0, 22.5, 18.0, 15.0, 10.0, 5.0] {
ui.selectable_value(&mut deg, a, format!("{a}"));
}
@@ -246,7 +246,7 @@ const INSERTION_UNITS: [&str; 25] = [
/// A combo box over `(value, label)` options.
fn pick(ui: &mut egui::Ui, salt: &str, value: &mut i64, options: &[(i64, String)]) {
let current = options.iter().find(|o| o.0 == *value).map(|o| o.1.clone()).unwrap_or_default();
egui::ComboBox::from_id_salt(salt).selected_text(current).width(180.0).show_ui(ui, |ui| {
craft_ui::ComboBox::from_id_salt(salt).selected_text(current).width(180.0).show_ui(ui, |ui| {
for (k, label) in options {
ui.selectable_value(value, *k, label);
}
@@ -415,7 +415,7 @@ fn commands(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
/// Interface Language combo; selecting a language runs `ui.language` with its code.
fn language(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
egui::Window::new(crate::tl!("Interface Language")).id(egui::Id::unique("interface_language")).open(open).resizable(false).show(ctx, |ui| {
egui::ComboBox::from_id_salt("interface_language_choice").selected_text(app.ui.interface_language.name()).show_ui(ui, |ui| {
craft_ui::ComboBox::from_id_salt("interface_language_choice").selected_text(app.ui.interface_language.name()).show_ui(ui, |ui| {
for preference in crate::i18n::Preference::for_picker() {
if ui.selectable_label(app.ui.interface_language == preference, preference.name()).clicked() {
let _ = app.run("ui.language", serde_json::json!({"lang": preference.code()}));
+228 -442
View File
@@ -1,21 +1,11 @@
//! Application panel identities and persistence around craft-ui's `DockArea`. Document contents remain owned by
//! their existing view implementations.
//!
//! `UiState::docking` is the saved workspace and the source of truth. The dock shows an `Arc` of it
//! ([`LiveDock`]), kept while the saved workspace is unchanged; every change the dock reports goes through the
//! same checks as a `ui.dock` command.
//! Application panel identities and persistence around the shared docking renderer.
//! Document contents remain owned by their existing view implementations.
use std::sync::Arc;
use craft_behavior::DockSide;
use craft_behavior::dock::{Action, Column, DockEdge, DockError, DockPlacement, Group, Layout, Location, Node, Permissions, SplitSize, Target};
use craft_behavior::flow::Axis;
use craft_ui::contract::{Bind, BodyCx, MemoKey, MemoProps, PlainData, SizeLimits, Tracked};
use craft_ui::docking::{DockConfig, DockHeights, DockPanels, DockSides, GroupAt, PanelSpec, PanelSpecs};
use craft_ui::patterns::dock::DockArea;
use craft_ui::primitives::{Glyph, IconSpec};
use craft_ui::style::UiTokens;
use egui::{Rect, pos2, vec2};
use craft_ui::docking::{
Action, Column, DockArea, DockCommand, DockContent, DockHeights, DockOperation, DockStyle, FloatSpace, Group, Layout, Location, Node,
PanelLimits, Permissions, Placement, Side, Sides, Target, UiDock, Zone,
};
use craft_ui::layout::{SplitAxis, SplitSize};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
@@ -34,8 +24,6 @@ pub enum Panel {
impl Panel {
pub const ALL: &[Self] = &[Self::Canvas, Self::ToolSets, Self::Layers, Self::Properties, Self::ExternalRefs];
/// Every panel, the ones opened on request included.
const EVERY: [Self; 7] = [Self::Canvas, Self::ToolSets, Self::QuickCalc, Self::Layers, Self::Properties, Self::ExternalRefs, Self::Blocks];
pub fn id(self) -> &'static str {
match self {
Self::Canvas => "canvas",
@@ -77,15 +65,19 @@ impl Panel {
/// The drawing view never moves, floats, closes or takes tabs; palettes dock beside it.
pub fn permissions(panel: &Panel) -> Permissions {
if *panel == Panel::Canvas { Permissions::PROTECTED.accepts_splits(true) } else { Permissions::default() }
if *panel == Panel::Canvas { Permissions { accepts_splits: true, ..Permissions::PROTECTED } } else { Permissions::default() }
}
fn tabs(panel: Panel) -> Node<Panel> {
Node::tabs(vec![panel], 0)
Node::Tabs { panels: vec![panel], active: 0 }
}
fn split(axis: SplitAxis, size: SplitSize, first: Node<Panel>, second: Node<Panel>) -> Node<Panel> {
Node::Split { axis, size, first: Box::new(first), second: Box::new(second) }
}
/// The saved panel arrangement: craft-ui's workspace over CADCraft's panels.
pub type Workspace = craft_behavior::dock::Workspace<Panel>;
pub type Workspace = craft_ui::docking::Workspace<Panel>;
/// The panel layout's shape version, saved beside it. Layouts saved without it, or with an
/// older one, are the split frames from before the dock columns and give way to the default.
@@ -98,47 +90,47 @@ pub const PALETTES_WIDTH: f32 = 300.0;
/// Layers' body height above Properties in a dock column.
const LAYERS_HEIGHT: f32 = 280.0;
fn dock(side: DockEdge, width: f32, groups: &[Panel]) -> Node<Panel> {
fn dock(side: Side, width: f32, groups: &[Panel]) -> Node<Panel> {
let groups = groups.iter().map(|panel| Group::new(vec![*panel], 0)).collect();
Node::dock(side, vec![Column::new(groups).with_width(width)])
Node::Dock { side, columns: vec![Column::new(groups, width)] }
}
/// Tool Sets in the left dock, the drawing, and Layers above Properties in the right dock.
pub fn default_workspace() -> Workspace {
Workspace::new(Layout::new(
Some(Node::split(
Axis::X,
Workspace::new(Layout {
root: Some(split(
SplitAxis::Horizontal,
SplitSize::FixedFirst(TOOL_SETS_WIDTH),
dock(DockEdge::Start, TOOL_SETS_WIDTH, &[Panel::ToolSets]),
Node::split(
Axis::X,
dock(Side::Start, TOOL_SETS_WIDTH, &[Panel::ToolSets]),
split(
SplitAxis::Horizontal,
SplitSize::FixedSecond(PALETTES_WIDTH),
tabs(Panel::Canvas),
dock(DockEdge::End, PALETTES_WIDTH, &[Panel::Layers, Panel::Properties]),
dock(Side::End, PALETTES_WIDTH, &[Panel::Layers, Panel::Properties]),
),
)),
Vec::new(),
))
floating: Vec::new(),
})
}
/// The dock a panel belongs in: Tool Sets on the left, the palettes on the right.
fn home_side(panel: Panel) -> (DockEdge, f32) {
if panel == Panel::ToolSets { (DockEdge::Start, TOOL_SETS_WIDTH) } else { (DockEdge::End, PALETTES_WIDTH) }
fn home_side(panel: Panel) -> (Side, f32) {
if panel == Panel::ToolSets { (Side::Start, TOOL_SETS_WIDTH) } else { (Side::End, PALETTES_WIDTH) }
}
/// The panels of every dock group on `side`: columns from the window edge inwards, groups from
/// top to bottom.
fn dock_groups(layout: &Layout<Panel>, side: DockEdge) -> Vec<Vec<Vec<Panel>>> {
fn dock_groups(layout: &Layout<Panel>, side: Side) -> Vec<Vec<Vec<Panel>>> {
let mut nodes: Vec<&Node<Panel>> = layout.root.iter().collect();
let mut seen = 0usize;
while let Some(node) = nodes.pop() {
seen = seen.saturating_add(1);
if seen > 4 * craft_behavior::dock::MAX_PANELS {
if seen > 4 * craft_ui::docking::MAX_PANELS {
break;
}
match node {
Node::Split { first, second, .. } => nodes.extend([&**first, &**second]),
Node::Dock { side: s, columns, .. } if *s == side => {
Node::Dock { side: s, columns } if *s == side => {
return columns.iter().map(|column| column.groups.iter().map(|group| group.panels.clone()).collect()).collect();
}
_ => {}
@@ -148,7 +140,7 @@ fn dock_groups(layout: &Layout<Panel>, side: DockEdge) -> Vec<Vec<Vec<Panel>>> {
}
fn docked(layout: &Layout<Panel>, panel: Panel) -> bool {
[DockEdge::Start, DockEdge::End].into_iter().any(|side| dock_groups(layout, side).iter().flatten().flatten().any(|p| *p == panel))
[Side::Start, Side::End].into_iter().any(|side| dock_groups(layout, side).iter().flatten().flatten().any(|p| *p == panel))
}
/// The docked neighbour a panel with no recorded place opens beside, as a new group above
@@ -180,24 +172,23 @@ fn home_anchor(layout: &Layout<Panel>, panel: Panel) -> Option<(Panel, bool)> {
/// docked neighbour, else a new dock on its side at its default width.
fn home(layout: &Layout<Panel>, panel: Panel) -> Vec<Action<Panel>> {
if let Some((anchor, below)) = home_anchor(layout, panel) {
return vec![Action::open_at(panel, anchor, DockPlacement::group(below, None))];
return vec![Action::OpenAt { panel, anchor, placement: Placement::Group { below, height: None } }];
}
let (side, width) = home_side(panel);
vec![Action::open(panel, None), Action::move_panel(panel, Target::new_dock(side)), Action::resize_column(panel, width)]
vec![Action::Open { panel, anchor: None }, Action::MovePanel { panel, to: Target::NewDock { side } }, Action::ResizeColumn { panel, width }]
}
/// craft-ui's checks plus the drawing view's: a saved or hand-edited file cannot hide, float,
/// group, collapse or dock it, or restore a palette over it.
pub fn validate(workspace: &Workspace) -> Result<(), String> {
workspace.validate().map_err(|error| error.to_string())?;
let layout = workspace.layout();
if !layout.contains(&Panel::Canvas) {
if !workspace.layout.contains(&Panel::Canvas) {
return Err("The panel layout must contain its document view".into());
}
if layout.floating.iter().any(|window| window.contains(&Panel::Canvas)) {
if workspace.layout.floating.iter().any(|window| window.contains(&Panel::Canvas)) {
return Err("The document view cannot float".into());
}
let mut nodes: Vec<_> = layout.root.iter().collect();
let mut nodes: Vec<_> = workspace.layout.root.iter().collect();
while let Some(node) = nodes.pop() {
match node {
Node::Split { first, second, .. } => {
@@ -207,7 +198,7 @@ pub fn validate(workspace: &Workspace) -> Result<(), String> {
Node::Tabs { panels, .. } if panels.contains(&Panel::Canvas) && panels.len() != 1 => {
return Err("The document view cannot share a tab group".into());
}
Node::Stack { entries, .. } if entries.iter().any(|entry| entry.panel == Panel::Canvas) => {
Node::Stack { entries } if entries.iter().any(|entry| entry.panel == Panel::Canvas) => {
return Err("The document view cannot be collapsed".into());
}
Node::Dock { columns, .. } if columns.iter().flat_map(|column| &column.groups).any(|group| group.panels.contains(&Panel::Canvas)) => {
@@ -217,9 +208,9 @@ pub fn validate(workspace: &Workspace) -> Result<(), String> {
}
}
let over_canvas = |location: &Location<Panel>| {
location.anchor == Some(Panel::Canvas) && matches!(location.placement, DockPlacement::Tab { .. } | DockPlacement::Split(DockSide::Center))
location.anchor == Some(Panel::Canvas) && matches!(location.placement, Placement::Tab { .. } | Placement::Split(Zone::Center))
};
if workspace.hidden().iter().any(|(_, location)| over_canvas(location)) {
if workspace.hidden.iter().any(|(_, location)| over_canvas(location)) {
return Err("A hidden panel cannot restore over the document view".into());
}
Ok(())
@@ -230,12 +221,11 @@ pub fn validate(workspace: &Workspace) -> Result<(), String> {
/// its docked neighbour's group.
pub fn reveal_panel(workspace: &mut Workspace, panel: Panel) -> Result<(), String> {
let mut next = workspace.clone();
if next.layout().contains(&panel) || next.hidden().iter().any(|(id, _)| *id == panel) {
let fallback = home_anchor(next.layout(), panel).map(|(anchor, _)| anchor);
next.set_visible(panel, true, fallback, false, permissions).map_err(|error| error.to_string())?;
if next.layout.contains(&panel) || next.hidden.iter().any(|(id, _)| *id == panel) {
let fallback = home_anchor(&next.layout, panel).map(|(anchor, _)| anchor);
next.set_visible(panel, true, fallback, permissions).map_err(|error| error.to_string())?;
} else {
let actions: Vec<_> = home(next.layout(), panel).into_iter().chain([Action::activate(panel)]).collect();
next.apply_all(actions, false, permissions).map_err(|error| error.to_string())?;
next.apply_all(home(&next.layout, panel).into_iter().chain([Action::Activate { panel }]), permissions).map_err(|error| error.to_string())?;
}
validate(&next)?;
*workspace = next;
@@ -247,19 +237,18 @@ pub fn reveal_panel(workspace: &mut Workspace, panel: Panel) -> Result<(), Strin
/// entries are open. Otherwise it goes through [`reveal_panel`], which regroups it with hidden
/// panels it was beside, and selects it.
fn set_visible(workspace: &mut Workspace, panel: Panel, visible: bool) -> Result<(), String> {
if workspace.layout().contains(&panel) == visible {
if workspace.layout.contains(&panel) == visible {
return Ok(());
}
if !visible {
return workspace.set_visible(panel, false, None, false, permissions).map_err(|error| error.to_string());
return workspace.set_visible(panel, false, None, permissions).map_err(|error| error.to_string());
}
let location = workspace.hidden().iter().find(|(id, _)| *id == panel).map(|(_, location)| location.clone());
let mut next = workspace.clone();
let location = next.hidden.iter().find(|(id, _)| *id == panel).map(|(_, location)| location.clone());
// A direct restore against a hidden anchor would open a window of its own.
let direct = location.filter(|location| location.anchor.is_none_or(|anchor| workspace.layout().contains(&anchor)));
let mut layout = workspace.layout().clone();
if direct.is_some_and(|location| layout.restore(panel, &location).is_ok()) {
let hidden = workspace.hidden().iter().filter(|(id, _)| *id != panel).cloned().collect();
let next = Workspace::from_parts(layout, hidden, workspace.floated().to_vec());
let direct = location.filter(|location| location.anchor.is_none_or(|anchor| next.layout.contains(&anchor)));
if direct.is_some_and(|location| next.layout.restore(panel, &location).is_ok()) {
next.hidden.retain(|(id, _)| *id != panel);
validate(&next)?;
*workspace = next;
return Ok(());
@@ -267,168 +256,36 @@ fn set_visible(workspace: &mut Workspace, panel: Panel, visible: bool) -> Result
reveal_panel(workspace, panel)
}
/// `ui.dock` params: `{action}`, a layout action, or `{operation, …}` ([`DockOperation`]).
/// `ui.dock` params: `{action}` or `{operation, …}` in craft-ui's shared grammar.
fn apply_command(workspace: &mut Workspace, params: &Value) -> Result<(), String> {
validate(workspace)?;
let action = if let Some(action) = params.get("action") {
serde_json::from_value(action.clone()).map_err(|error| error.to_string())?
let operation = if let Some(action) = params.get("action") {
UiDock::Action { action: serde_json::from_value(action.clone()).map_err(|error| error.to_string())? }
} else {
let operation: DockOperation = serde_json::from_value(params.clone()).map_err(|error| error.to_string())?;
if let DockOperation::Open { panel } | DockOperation::Activate { panel } = &operation
&& !workspace.layout().contains(panel)
{
let mut next = workspace.clone();
reveal_panel(&mut next, *panel)?;
validate(&next)?;
*workspace = next;
return Ok(());
}
operation.action(workspace.layout()).map_err(|error| error.to_string())?
UiDock::Operation(serde_json::from_value(params.clone()).map_err(|error| error.to_string())?)
};
apply_action(workspace, action)
}
/// Apply one layout action to a copy of `workspace` and keep it only when it passes [`validate`].
fn apply_action(workspace: &mut Workspace, action: Action<Panel>) -> Result<(), String> {
let mut next = workspace.clone();
next.apply(action, false, permissions).map_err(|error| error.to_string())?;
match operation {
UiDock::Operation(DockOperation::Open { panel } | DockOperation::Activate { panel }) if !next.layout.contains(&panel) => {
reveal_panel(&mut next, panel)?;
}
operation => {
// Every ui.dock operation carries its own rect, so the float space is never consulted.
let space = FloatSpace::new(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 800.0)));
DockCommand::UiDock(operation).apply(&mut next, false, &space, permissions).map_err(|error| error.to_string())?;
}
}
validate(&next)?;
*workspace = next;
Ok(())
}
/// A drop zone by name, as `ui.dock` writes it. PascalCase names also parse.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
enum ZoneName {
Tab,
#[serde(alias = "Center")]
Center,
#[serde(alias = "Left")]
Left,
#[serde(alias = "Right")]
Right,
#[serde(alias = "Top")]
Top,
#[serde(alias = "Bottom")]
Bottom,
Above,
Below,
}
/// A present field, `null` included: `Some(None)` for `null`, `None` when absent.
fn present<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(deserializer: D) -> Result<Option<T>, D::Error> {
T::deserialize(deserializer).map(Some)
}
/// A required field that may be `null`.
fn required<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(deserializer: D) -> Result<T, D::Error> {
T::deserialize(deserializer)
}
/// A `ui.dock` operation, tagged by `operation`. `move` takes `target` (the anchor), `zone`
/// (default `center`) and `before`, which only applies to a center move. Rects are `[x, y, width, height]`.
#[derive(Clone, Debug, PartialEq, Deserialize)]
#[serde(tag = "operation", rename_all = "camelCase")]
enum DockOperation {
/// Show a panel at its last location and select it.
Open {
panel: Panel,
},
Close {
panel: Panel,
},
Activate {
panel: Panel,
},
Float {
panel: Panel,
rect: [f32; 4],
},
MoveFloating {
panel: Panel,
rect: [f32; 4],
},
Move {
panel: Panel,
target: Panel,
#[serde(default)]
zone: Option<ZoneName>,
#[serde(default, deserialize_with = "present")]
before: Option<Option<Panel>>,
},
SetStackOpen {
panel: Panel,
open: bool,
},
/// `height` is required; `null` clears it.
ResizeStack {
panel: Panel,
#[serde(deserialize_with = "required")]
height: Option<f32>,
},
ResizeSplit {
path: Vec<bool>,
size: SplitSize,
},
}
/// `[x, y, width, height]` as a rect.
fn rect_of([x, y, width, height]: [f32; 4]) -> Rect {
Rect::from_min_size(pos2(x, y), vec2(width, height))
}
/// Where a `move` puts the panel relative to `anchor`: `zone` (default `center`) and `before`,
/// with side zones mapped onto the anchor's container by [`DockPlacement::for_zone`].
fn placement(
layout: &Layout<Panel>,
anchor: &Panel,
zone: Option<ZoneName>,
before: Option<Option<Panel>>,
) -> Result<DockPlacement<Panel>, DockError> {
let side = |side| DockPlacement::for_zone(layout, anchor, side);
Ok(match (zone.unwrap_or(ZoneName::Center), before) {
(ZoneName::Tab | ZoneName::Center, Some(before)) => DockPlacement::tab(before),
(ZoneName::Tab, None) => DockPlacement::tab(None),
(ZoneName::Center, None) => DockPlacement::Split(DockSide::Center),
(_, Some(_)) => return Err(DockError::InvalidPlacement),
(ZoneName::Left, None) => side(DockSide::Start)?,
(ZoneName::Right, None) => side(DockSide::End)?,
(ZoneName::Top, None) => side(DockSide::Top)?,
(ZoneName::Bottom, None) => side(DockSide::Bottom)?,
(ZoneName::Above, None) => DockPlacement::group(false, None),
(ZoneName::Below, None) => DockPlacement::group(true, None),
})
}
impl DockOperation {
/// The layout action this operation makes on `layout`. A panel that is not shown is
/// [`DockError::MissingPanel`] for Open and Activate, which show it first ([`apply_command`]).
fn action(&self, layout: &Layout<Panel>) -> Result<Action<Panel>, DockError> {
Ok(match self {
Self::Open { panel } | Self::Activate { panel } => {
if !layout.contains(panel) {
return Err(DockError::MissingPanel);
}
Action::activate(*panel)
}
Self::Close { panel } => Action::close(*panel),
Self::Float { panel, rect } => Action::float(*panel, rect_of(*rect)),
Self::MoveFloating { panel, rect } => Action::move_floating(*panel, rect_of(*rect)),
Self::Move { panel, target, zone, before } => Action::move_beside(*panel, *target, placement(layout, target, *zone, *before)?),
Self::SetStackOpen { panel, open } => Action::set_stack_open(*panel, *open),
Self::ResizeStack { panel, height } => Action::resize_stack(*panel, *height),
Self::ResizeSplit { path, size } => Action::resize_split(path.clone(), *size),
})
}
}
fn sync(workspace: &mut Workspace, app: &crate::CadApp) -> Result<(), String> {
set_visible(workspace, Panel::ToolSets, app.ui.show_toolsets)?;
if !app.ui.show_palettes {
set_visible(workspace, Panel::Layers, false)?;
set_visible(workspace, Panel::Properties, false)?;
} else if !workspace.layout().contains(&Panel::Layers) && !workspace.layout().contains(&Panel::Properties) {
} else if !workspace.layout.contains(&Panel::Layers) && !workspace.layout.contains(&Panel::Properties) {
// Reopen the palette that closed last before the one recorded beside it.
set_visible(workspace, Panel::Properties, true)?;
set_visible(workspace, Panel::Layers, true)?;
@@ -437,20 +294,20 @@ fn sync(workspace: &mut Workspace, app: &crate::CadApp) -> Result<(), String> {
}
fn publish_visibility(app: &mut crate::CadApp, workspace: &Workspace) {
app.ui.show_toolsets = workspace.layout().contains(&Panel::ToolSets);
app.ui.show_palettes = workspace.layout().contains(&Panel::Layers) || workspace.layout().contains(&Panel::Properties);
app.ui.show_toolsets = workspace.layout.contains(&Panel::ToolSets);
app.ui.show_palettes = workspace.layout.contains(&Panel::Layers) || workspace.layout.contains(&Panel::Properties);
}
pub fn command(app: &mut crate::CadApp, reset: bool, params: &Value) -> Result<Value, String> {
let mut workspace = app.ui.docking.clone();
if reset {
workspace.replace(default_workspace());
workspace = default_workspace();
} else {
sync(&mut workspace, app)?;
apply_command(&mut workspace, params)?;
// An opened panel's floating window comes to the front, in its own OS window too.
if matches!(params.get("operation").and_then(Value::as_str), Some("open" | "activate")) {
app.dock.raise = params.get("panel").and_then(|panel| serde_json::from_value(panel.clone()).ok());
app.raise_panel = params.get("panel").and_then(|panel| serde_json::from_value(panel.clone()).ok());
}
}
publish_visibility(app, &workspace);
@@ -458,199 +315,104 @@ pub fn command(app: &mut crate::CadApp, reset: bool, params: &Value) -> Result<V
Ok(json!({"docking": app.ui.docking}))
}
/// Apply a change the dock reported, with the app's visibility switches synced first.
fn apply_reported(app: &mut crate::CadApp, action: Action<Panel>) -> Result<(), String> {
let mut workspace = app.ui.docking.clone();
sync(&mut workspace, app)?;
validate(&workspace)?;
apply_action(&mut workspace, action)?;
publish_visibility(app, &workspace);
app.ui.docking = workspace;
Ok(())
}
/// The workspace the dock shows, the panels' specs and the panel to raise.
#[derive(Default)]
pub struct LiveDock {
shown: Option<Arc<Workspace>>,
specs: Tracked<DockSpecs>,
/// A panel opened from a menu or command, whose floating window comes to the front on the next frame.
raise: Option<Panel>,
}
impl LiveDock {
/// The `Arc` the dock shows for `workspace`: the last one while its arrangement is the same, so an idle pass keeps
/// the workspace's revision and the dock reads no spec.
fn shown(&mut self, workspace: &Workspace) -> Arc<Workspace> {
if let Some(shown) = self.shown.as_ref().filter(|shown| ***shown == *workspace) {
return Arc::clone(shown);
}
let shown = Arc::new(workspace.clone());
self.shown = Some(Arc::clone(&shown));
shown
}
}
/// What the dock reads of the panels: their names in the interface language.
#[derive(Clone, Debug, Default, PartialEq, PlainData)]
struct DockSpecs {
/// The tab names, in [`Panel::EVERY`] order.
labels: Vec<String>,
}
impl PanelSpecs<Panel> for DockSpecs {
fn spec(&self, panel: &Panel) -> PanelSpec {
let label = Panel::EVERY.iter().position(|p| p == panel).and_then(|index| self.labels.get(index)).cloned().unwrap_or_default();
// Every panel is CADCraft's own egui code: the dock runs it with the window's style.
let mut spec = PanelSpec::new(label).limits(panel_limits(panel)).host_body();
if let Some(glyph) = PanelGlyph::of(*panel) {
spec = spec.icon(IconSpec::glyph(glyph));
}
match panel {
Panel::Canvas => spec.canvas(),
// Layers keeps its list's height above Properties, which takes the rest of the column.
Panel::Layers => spec.heights(DockHeights::new(LAYERS_HEIGHT)),
_ => spec,
}
}
fn permissions(&self, panel: &Panel) -> Permissions {
permissions(panel)
}
}
/// Reads the panel names in the interface language, moving the specs' revision only when one changed.
fn refresh_specs(app: &mut crate::CadApp) {
let labels: Vec<String> = Panel::EVERY.iter().map(|panel| crate::i18n::t(panel.label()).to_string()).collect();
if app.dock.specs.labels != labels {
app.dock.specs.labels = labels;
}
}
/// A palette's icon in a column collapsed to icons and in its flyout cell, painted by CADCraft's own icon painter.
#[derive(Debug, PartialEq)]
struct PanelGlyph(crate::icons::Icon);
impl PanelGlyph {
fn of(panel: Panel) -> Option<&'static PanelGlyph> {
use crate::icons::Icon;
static TOOL_SETS: PanelGlyph = PanelGlyph(Icon::Switcher);
static QUICK_CALC: PanelGlyph = PanelGlyph(Icon::Table);
static LAYERS: PanelGlyph = PanelGlyph(Icon::Layers);
static PROPERTIES: PanelGlyph = PanelGlyph(Icon::Properties);
static EXTERNAL_REFS: PanelGlyph = PanelGlyph(Icon::Attach);
static BLOCKS: PanelGlyph = PanelGlyph(Icon::Blocks);
match panel {
Panel::Canvas => None,
Panel::ToolSets => Some(&TOOL_SETS),
Panel::QuickCalc => Some(&QUICK_CALC),
Panel::Layers => Some(&LAYERS),
Panel::Properties => Some(&PROPERTIES),
Panel::ExternalRefs => Some(&EXTERNAL_REFS),
Panel::Blocks => Some(&BLOCKS),
}
}
}
impl MemoProps for PanelGlyph {
fn key(&self, key: &mut MemoKey) {
key.feed_hash(&self.0);
}
}
impl Glyph for PanelGlyph {
/// CADCraft's icons keep their own colours (blue for created geometry, orange for picked points), so the dock's
/// ink is not applied.
fn paint(&self, painter: &egui::Painter, _tokens: &UiTokens, rect: Rect, _color: egui::Color32, _mirrored: bool) {
crate::icons::paint(painter, rect, self.0, false);
}
}
/// Validate and repair the stored workspace, sync it with the app, and draw the dock: restore or fall back from the
/// persisted layout (a failed restore falls back to the default layout with a status message), draw every panel body
/// and the drawing, forward the keys typed in floating panels' own windows, and apply the pass's layout actions.
/// Bodies may dispatch commands, so the canonical workspace is published before drawing while the shown `Arc` stays
/// unchanged.
/// Validate and repair the stored workspace, sync it with the app, and render the dock panels; a failed restore falls back to the default layout with a status message.
/// Draw the docked workspace: restore or fall back from the persisted layout, render every
/// panel body plus the header close buttons, and apply the resulting actions through
/// [`command`]. Bodies may dispatch commands, so the canonical workspace is published before
/// rendering while the layout snapshot stays immutable.
pub fn show(app: &mut crate::CadApp, ui: &mut egui::Ui) {
let t = crate::theme::Tokens::get();
let mut workspace = app.ui.docking.clone();
if let Err(error) = validate(&workspace).and_then(|()| sync(&mut workspace, app)) {
app.set_status(format!("Panel layout could not be restored: {error}"));
workspace = default_workspace();
let _ = sync(&mut workspace, app);
}
// Bodies can dispatch commands (including the drawing's typed command line).
// Keep the canonical workspace accessible while rendering an immutable snapshot.
app.ui.docking = workspace.clone();
refresh_specs(app);
let shown = app.dock.shown(&workspace);
// The specs leave the app while its panels borrow it, and come back with their revision.
let specs = std::mem::take(&mut app.dock.specs);
let raise = app.dock.raise.take();
// AutoCAD's palettes dock only in the left and right dock columns: a window edge without a dock makes one, and
// neither the drawing nor the top and bottom edges take a drop. Floating title bars only move windows. Each
// closable tab has its close button.
let config =
DockConfig::default().side_edge_zones(false).new_dock_zones(true).drop_edges(DockSides::NONE).title_bar_docks(false).tab_close_buttons(true);
let (output, focused_windows) = {
let mut panels = Panels { app: &mut *app, focused_windows: Vec::new() };
let mut area = DockArea::new("Panels", Bind::given(shown), &specs, &mut panels, config);
if let Some(panel) = raise {
area = area.raise(panel);
}
let output = area.show(ui);
(output, panels.focused_windows)
let mut style = DockStyle::from_ui(ui);
style.min_pane = 96.0;
style.background = t.panel;
style.tab_background = t.chrome;
style.active_background = t.tab_active;
style.text = t.text;
style.inactive_text = t.text_dim;
style.border = egui::Stroke::new(1.0, t.border);
style.accent = t.accent;
style.font = crate::theme::body();
// AutoCAD's palettes dock only in the left and right dock columns: a window edge without a
// dock makes one, and neither the drawing nor the top and bottom edges take a drop.
// Floating title bars only move windows.
style.side_edge_zones = false;
style.new_dock_zones = true;
style.drop_edges = Sides::NONE;
style.title_bar_docks = false;
let mut area = DockArea::new(egui::Id::unique("cadcraft-docking")).input_blocked(native_input_blocked(app, ui.ctx()));
if let Some(panel) = app.raise_panel.take() {
area = area.raise_panel(panel);
}
let (mut output, header_close) = {
let mut panels = Panels { app, close: None };
let output = area.show_content(ui, &workspace.layout, &style, &mut panels);
(output, panels.close)
};
app.dock.specs = specs;
// Keys typed in a floating panel's own OS window run the main window's shortcuts and command line; while one of that
// window's widgets has the keyboard, only the keyboard zoom reads them. Files dropped on one open like files dropped
// on the main window.
let ctx = ui.ctx().clone();
for (_, viewport) in &output.windows {
if *viewport == egui::ViewportId::ROOT {
// Accordion title bars are rendered by the shared surface without a header callback, so
// place the same close button over their title bar, left of the stock collapse control.
let mut close = header_close;
for panel in stack_panels(&workspace.layout) {
if !permissions(&panel).closable {
continue;
}
if focused_windows.contains(viewport) {
app.zoom_keys(&ctx, *viewport);
let Some(title) = ui.ctx().read_response(egui::Id::unique("cadcraft-docking").with(("tab", panel))) else { continue };
if !title.rect.is_positive() {
continue;
}
let (events, modifiers) =
ctx.input_for(*viewport, |input| (input.events.iter().filter(|e| forwarded(e)).cloned().collect::<Vec<_>>(), input.modifiers));
// A Copy, Cut or Paste chord is the runtime's command: it reaches the app through the next frame's `FrameOutput`.
if modifiers.command {
ctx.request_repaint_of(egui::ViewportId::ROOT);
let rect = egui::Rect::from_center_size(
egui::pos2(title.rect.right() - 18.0 - CLOSE_BUTTON * 0.5 - 4.0, title.rect.center().y),
egui::vec2(CLOSE_BUTTON, CLOSE_BUTTON),
);
if close_button(ui, panel, rect) {
close = Some(panel);
}
let modifiers = (!events.is_empty()).then_some(modifiers);
app.forward_native_input(&ctx, events, modifiers);
}
if let Some(panel) = close {
output.actions.push(Action::Close { panel });
}
// Keys typed in a floating panel's own OS window run the main window's shortcuts and
// command line; files dropped on one open like files dropped on the main window.
app.forward_native_input(ui.ctx(), std::mem::take(&mut output.forwarded_events), output.forwarded_modifiers);
#[cfg(not(target_arch = "wasm32"))]
for dropped in &output.window_files {
for path in dropped.files.iter().filter_map(|file| file.path.as_ref()) {
app.open_path(path);
for files in std::mem::take(&mut output.window_files) {
for file in files.dropped {
let path = file.path();
if !path.as_os_str().is_empty() {
app.open_path(path);
}
}
}
// Existing panel switches and commands still own their visibility switches.
// Existing panel close buttons and commands still own their visibility switches.
let rendered = workspace;
let mut workspace = app.ui.docking.clone();
let _ = sync(&mut workspace, app);
let stale = workspace != rendered;
if stale {
craft_ui::runtime::drag::cancel(ui.ctx(), craft_behavior::CancelReason::HostChanged);
craft_ui::docking::cancel_drag::<Panel>(ui.ctx(), egui::Id::unique("cadcraft-docking"));
}
publish_visibility(app, &workspace);
app.ui.docking = workspace;
if stale {
return;
}
for action in output.actions.into_iter().chain(output.requested) {
if let Err(error) = apply_reported(app, action) {
for action in output.actions {
if let Err(error) =
serde_json::to_value(action).map_err(|error| error.to_string()).and_then(|action| command(app, false, &json!({"action": action})))
{
app.set_status(format!("Panel move was not applied: {error}"));
}
}
}
/// The events a floating panel's own window hands to the main window: keys, text and the clipboard.
fn forwarded(event: &egui::Event) -> bool {
matches!(event, egui::Event::Key { .. } | egui::Event::Text(_) | egui::Event::Copy | egui::Event::Cut | egui::Event::Paste(_))
}
/// Whether the floating panels' own OS windows ignore input: while a modal dialog is up, since
/// egui's `Modal` blocks only the main window. egui's modal layer is last frame's; the app's
/// state covers the frame a modal opens in.
@@ -658,20 +420,65 @@ pub fn native_input_blocked(app: &crate::CadApp, ctx: &egui::Context) -> bool {
app.shows_modal() || ctx.memory(|memory| memory.top_modal_layer()).is_some()
}
/// The dock's panels over the app in one pass.
struct Panels<'a> {
app: &'a mut crate::CadApp,
/// The floating panels' own OS windows in which one of CADCraft's widgets had the keyboard after its body ran.
focused_windows: Vec<egui::ViewportId>,
/// The panels' contents, names, size limits and icons for the dock area.
pub struct Panels<'a> {
pub app: &'a mut crate::CadApp,
/// The panel whose header close button was clicked this frame.
pub close: Option<Panel>,
}
impl DockPanels<Panel> for Panels<'_> {
/// Render `panel`'s existing view; Layers, Properties and External References scroll independently.
fn body(&mut self, panel: &Panel, ui: &mut egui::Ui, _: &mut BodyCx<'_>) {
/// Size of a panel header's close button, in points.
const CLOSE_BUTTON: f32 = 16.0;
/// The accessible name of a header's close button. One translated template carries both the
/// verb and the panel name, so a catalog translates the whole name instead of leaving an
/// English verb in front of a translated panel label.
fn close_label(panel: Panel) -> String {
crate::tf!("Close {panel}", panel = crate::i18n::t(panel.label()))
}
/// A visible close button for a panel header. It runs the same action as the tab context
/// menu's "Close panel"; the accessible name includes the panel so the headers stay distinct.
fn close_button(ui: &mut egui::Ui, panel: Panel, rect: egui::Rect) -> bool {
let t = crate::theme::Tokens::get();
let response = ui.interact(rect, egui::Id::unique("cadcraft-docking").with(("close", panel.id())), egui::Sense::click());
let label = close_label(panel);
crate::icons::describe_control(ui, &response, &label, None, false);
if response.hovered() {
ui.painter().rect_filled(rect.expand(2.0), 2.0, t.control_hover.gamma_multiply(0.6));
}
crate::icons::paint(ui.painter(), rect, crate::icons::Icon::Close, false);
response.on_hover_text(crate::tl!("Close panel")).clicked()
}
/// Panels whose title bar is an accordion entry rather than a tab group header.
fn stack_panels(layout: &Layout<Panel>) -> Vec<Panel> {
let mut panels = Vec::new();
let mut nodes: Vec<&Node<Panel>> = layout.root.iter().collect();
while let Some(node) = nodes.pop() {
match node {
Node::Split { first, second, .. } => {
nodes.push(first);
nodes.push(second);
}
Node::Stack { entries } => panels.extend(entries.iter().map(|entry| entry.panel)),
// Tab groups draw their own header; nothing else stacks an accordion entry.
_ => {}
}
}
panels
}
impl DockContent<Panel> for Panels<'_> {
/// Render `panel`'s existing view; Layers, Properties and External References scroll
/// independently, and the drawing canvas paints its own background before the view.
fn body(&mut self, ui: &mut egui::Ui, panel: &Panel) {
let app = &mut *self.app;
match panel {
// The drawing is its group's `group_view`.
Panel::Canvas => {}
Panel::Canvas => {
ui.painter().rect_filled(ui.max_rect(), 0.0, crate::theme::Tokens::get().canvas);
crate::canvas::show(app, ui);
}
Panel::ToolSets => crate::palettes::toolsets(app, ui),
Panel::QuickCalc => crate::palettes::quickcalc::show(app, ui),
Panel::Layers => {
@@ -695,72 +502,51 @@ impl DockPanels<Panel> for Panels<'_> {
.show(ui, |ui| crate::blocks_palette::section(app, ui));
}
}
let viewport = ui.ctx().viewport_id();
if viewport != egui::ViewportId::ROOT {
self.focused_windows.retain(|window| *window != viewport);
if ui.memory(|memory| memory.focused().is_some()) {
self.focused_windows.push(viewport);
}
}
}
/// The drawing: it paints its own background, and is the window's document canvas.
fn group_view(&mut self, panels: &[Panel], _: usize, ui: &mut egui::Ui, at: GroupAt, _: &mut BodyCx<'_>) -> Option<f32> {
let GroupAt::Show(rect) = at else { return None };
if !panels.contains(&Panel::Canvas) {
return None;
fn logical_label(&self, panel: &Panel) -> String {
crate::i18n::t(panel.label()).into()
}
fn permissions(&self, panel: &Panel) -> Permissions {
permissions(panel)
}
fn limits(&self, panel: &Panel) -> PanelLimits {
panel_limits(panel)
}
fn dock_heights(&self, panel: &Panel) -> Option<DockHeights> {
// Layers keeps its list's height above Properties, which takes the rest of the column.
(*panel == Panel::Layers).then(|| DockHeights::new(LAYERS_HEIGHT))
}
fn paint_icon(&mut self, painter: &egui::Painter, rect: egui::Rect, panel: &Panel, _color: egui::Color32) -> bool {
let Some(icon) = panel.icon() else { return false };
crate::icons::paint(painter, rect, icon, false);
true
}
/// Reserve header space for the close button only when `active` may be closed, so the
/// drawing view's title gets no empty gap.
fn group_header_width(&self, _panels: &[Panel], active: &Panel, _floating: bool, _strip_width: f32) -> f32 {
if permissions(active).closable { CLOSE_BUTTON + 8.0 } else { 0.0 }
}
/// Draw the close button at the right edge of a tab-group header and remember the panel
/// to close once the docking surface has returned, so layout changes stay outside rendering.
fn group_header(&mut self, ui: &mut egui::Ui, _panels: &[Panel], active: &Panel, _floating: bool) {
let header = ui.max_rect();
let rect = egui::Rect::from_center_size(
egui::pos2(header.right() - CLOSE_BUTTON * 0.5 - 4.0, header.center().y),
egui::vec2(CLOSE_BUTTON, CLOSE_BUTTON),
);
if close_button(ui, *active, rect) {
self.close = Some(*active);
}
// Declared before the widgets drawn over it, for its place in Tab order, and again after this pass's input has
// changed what Tab has to do.
crate::framework::host_canvas(ui.ctx(), crate::cmdline::tab_has_work(self.app));
ui.painter().rect_filled(rect, 0.0, crate::theme::Tokens::get().canvas);
crate::canvas::show(self.app, ui);
crate::canvas::focus_opened(self.app, ui.ctx());
crate::framework::host_canvas(ui.ctx(), crate::cmdline::tab_has_work(self.app));
Some(rect.height())
}
}
/// The panels' body limits: a minimum size and a maximum width.
fn panel_limits(panel: &Panel) -> SizeLimits {
fn panel_limits(panel: &Panel) -> PanelLimits {
let (min, max_width) = match panel {
Panel::Canvas => (vec2(300.0, 180.0), SizeLimits::BOUND),
Panel::QuickCalc => (vec2(240.0, 160.0), 600.0),
Panel::ToolSets => (vec2(220.0, 150.0), 480.0),
Panel::Layers | Panel::Properties | Panel::ExternalRefs => (vec2(220.0, 100.0), 720.0),
Panel::Blocks => (vec2(240.0, 260.0), 720.0),
Panel::Canvas => (egui::vec2(300.0, 180.0), 1_000_000.0),
Panel::QuickCalc => (egui::vec2(240.0, 160.0), 600.0),
Panel::ToolSets => (egui::vec2(220.0, 150.0), 480.0),
Panel::Layers | Panel::Properties | Panel::ExternalRefs => (egui::vec2(220.0, 100.0), 720.0),
Panel::Blocks => (egui::vec2(240.0, 260.0), 720.0),
};
SizeLimits::new(min, vec2(max_width, SizeLimits::BOUND))
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
#[test]
fn an_opened_panel_is_raised_for_one_frame() {
let mut app = crate::CadApp::new(cadcraft_engine::Session::default(), crate::Services::default());
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
command(&mut app, false, &json!({"operation": "open", "panel": Panel::Properties.id()})).unwrap();
assert_eq!(app.dock.raise, Some(Panel::Properties));
let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(1600.0, 1000.0))), ..Default::default() };
let mut output = ctx.run_ui(input, |ui| app.ui(ui));
output.textures_delta.clear();
assert_eq!(app.dock.raise, None);
}
#[test]
fn a_reset_replaces_the_workspace() {
let mut app = crate::CadApp::new(cadcraft_engine::Session::default(), crate::Services::default());
let start = app.ui.docking.generation();
command(&mut app, false, &json!({"operation": "open", "panel": Panel::Blocks.id()})).unwrap();
assert_eq!(app.ui.docking.generation(), start);
command(&mut app, true, &Value::Null).unwrap();
assert_ne!(app.ui.docking.generation(), start);
assert_eq!(app.ui.docking, default_workspace());
}
PanelLimits { min, max: egui::vec2(max_width, 1_000_000.0) }
}
+1 -1
View File
@@ -210,7 +210,7 @@ pub(crate) fn menu(app: &mut CadApp, ctx: &egui::Context, xf: &Xf) {
if let Err(e) = app.run("blocks.reference.set", json!({ "handle": h.hex(), "name": g.property, "value": value })) {
app.session.echo(e);
}
} else if clicked_elsewhere || crate::framework::escape_pressed(ctx) {
} else if clicked_elsewhere || ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
app.canvas.dyn_menu = None;
}
}
-1
View File
@@ -572,7 +572,6 @@ mod tests {
fn down_arrow_lists_the_options_and_enter_or_a_click_picks_one() {
let mut app = crate::CadApp::new(cadcraft_engine::Session::new(), crate::Services::default());
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
run_frame(&mut app, &ctx, Vec::new());
let center = app.canvas.rect.map_or(egui::pos2(700.0, 450.0), |r| r.center());
let hover = vec![egui::Event::PointerMoved(center)];
+2 -2
View File
@@ -126,7 +126,7 @@ pub fn pdf_dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
});
},
);
if crate::framework::escape_pressed(ctx) {
if ctx.input(|input| input.key_pressed(egui::Key::Escape)) {
cancel = true;
}
if import {
@@ -242,7 +242,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
close = ui.button("Close").clicked();
});
});
if crate::framework::escape_pressed(ctx) {
if ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
close = true;
}
if close || print {
-254
View File
@@ -1,254 +0,0 @@
//! The craft-ui runtime, hosted from CADCraft's own eframe `App` (craft-libs docs/craft-framework.md, section 2.2).
//! The desktop app calls [`install`] once, [`CadApp::before_input`] in `raw_input_hook` after CADCraft's own hook,
//! [`CadApp::close_path`] last in `logic`, and [`before_ui`] first in `ui`; the browser build and tests install with
//! [`install_headless`]. The framework dialogs run on [`CadApp::framework_dialogs`] after CADCraft's own UI.
//!
//! The runtime takes Escape, Tab and the clipboard events for the whole window unless one of CADCraft's own egui
//! widgets has the keyboard. The window's Escape is read with [`escape_pressed`]; the drawing is declared to the
//! runtime with [`host_canvas`], which keeps Enter, the arrows, the edit chords and the clipboard events in egui's
//! input for the command line and CADCraft's shortcuts while nothing has the focus.
use std::sync::{Arc, OnceLock};
use craft_host::target::ShellInfo;
use craft_host::{AppInfo, Host};
use craft_keymap::Overrides;
use craft_ui::fonts::{I18nScripts, SystemFonts, UiFonts};
use craft_ui::runtime::commands::{CommandInput, CommandSet as _, EditCommands, FirePhase, FireSource, Fired, NavCommand};
use craft_ui::runtime::env::{RootEnv, Scale};
use craft_ui::runtime::focus::{EditSet, KeepKeys, KeyUse};
use craft_ui::runtime::frame::{FrameInput, FrameOutput};
use craft_ui::runtime::keys::{Intent, with_window_intents};
use craft_ui::runtime::overlay::{self, OpenFilter};
use craft_ui::shell::embed::{self, CloseDecision};
use craft_window::system::WindowSystem;
use egui::ViewportId;
use crate::CadApp;
use crate::options::INTERFACE_SCALES;
/// Each pass of the root window, first in `App::ui`: hands the runtime the native window it answers the hit test of
/// (Windows) and fits the window to its monitor once.
#[cfg(not(target_arch = "wasm32"))]
pub use craft_ui::shell::embed::before_ui;
/// The override variable's prefix: `CADCRAFT_TITLEBAR`.
#[cfg(not(target_arch = "wasm32"))]
const PREFIX: craft_window::Prefix = craft_window::Prefix::new("CADCRAFT");
/// The scripts of the interface languages, for the font stack.
static SCRIPTS: I18nScripts = I18nScripts;
/// The runtime's first font stack: egui's bundled faces and no installed system fonts. CADCraft's own definitions
/// ([`crate::theme::install_fonts`]) replace it in the first pass, before anything is drawn.
fn ui_fonts() -> UiFonts<'static> {
UiFonts::new(&SCRIPTS).system_fonts(SystemFonts::Off)
}
fn install_with(ctx: &egui::Context, shell: ShellInfo, windows: Arc<dyn WindowSystem>, frame: Option<Decision>) -> Result<(), String> {
let mut spec = craft_ui::InstallSpec::new(shell, windows).app_id(crate::os_window::app_id());
if let Some(frame) = frame {
spec = spec.frame(frame);
}
embed::install(ctx, spec, &ui_fonts()).map(drop).map_err(|error| format!("the UI runtime could not be installed: {error}"))
}
/// Who draws the main window's frame, decided once before the window opens: on macOS the traffic lights sit over
/// CADCraft's title row (a full-size content view with a hidden title), elsewhere the system draws the frame.
/// `CADCRAFT_TITLEBAR=system` keeps the macOS title bar. `None` where the system decides alone.
#[cfg(not(target_arch = "wasm32"))]
pub fn frame_decision(forced_x11: bool) -> Option<Decision> {
use craft_host::target::Backend;
let backend = if forced_x11 { Backend::X11 } else { Backend::from_env() };
cfg!(target_os = "macos").then(|| craft_window::policy::decide_for(PREFIX, backend, craft_window::policy::TitleBarPref::Integrated))
}
/// Installs the runtime on the desktop window's context, once, before the first pass. `forced_x11` when the app
/// opens its window through XWayland; `frame` is [`frame_decision`]'s.
#[cfg(not(target_arch = "wasm32"))]
pub fn install(ctx: &egui::Context, forced_x11: bool, frame: Option<Decision>) -> Result<(), String> {
use craft_host::target::Backend;
let backend = if forced_x11 { Backend::X11 } else { Backend::from_env() };
install_with(ctx, ShellInfo::default().backend(backend), Arc::new(craft_window::system::SystemWindows), frame)
}
/// Installs the runtime on a context with no native window of its own: the browser build's canvas and test windows.
pub fn install_headless(ctx: &egui::Context) {
if let Err(error) = install_with(ctx, ShellInfo::default(), Arc::new(craft_window::system::NoWindows), None) {
log::warn!("{error}");
}
}
/// Who CADCraft is to the framework's dock and dialogs (the update dialogs show its name and icon).
pub(crate) fn host() -> Arc<Host> {
Arc::new(
Host::builder(AppInfo { id: "cadcraft", name: "CADCraft", version: env!("CARGO_PKG_VERSION") })
.icon_png(include_bytes!("../../../assets/app-icon/hicolor/128x128/apps/ai.storyteller.cadcraft.png"))
.build(),
)
}
/// Every function key is CADCraft's to assign (Tools ▸ Shortcuts records any of them), so the runtime's F6 and
/// Shift+F6 pane moves are unbound. Overrides are keyed by command id, which the command set gives.
fn command_overrides() -> Arc<Overrides> {
static OVERRIDES: OnceLock<Arc<Overrides>> = OnceLock::new();
OVERRIDES
.get_or_init(|| {
let mut overrides = Overrides::new();
for id in [NavCommand::NextPane.id(), NavCommand::PreviousPane.id()] {
overrides.insert(id, Vec::new());
}
Arc::new(overrides)
})
.clone()
}
impl CadApp {
/// The framework's part of `App::raw_input_hook`, once per frame before the first pass: takes what the runtime
/// gathered since the last frame and gives the coming passes the root values (theme mode, interface scale).
pub fn before_input(&mut self, ctx: &egui::Context) {
embed::before_input(ctx, |output| self.frame_input(ctx, output));
}
/// Takes the Copy, Cut and Paste chords the runtime ran as its own `edit.*` commands, because nothing in a
/// floating panel's window had them (the runtime keeps those clipboard events out of the window's input, so
/// [`CadApp::forward_native_input`] never sees them). The shortcuts read them as the clipboard events they stand
/// for, with the paste's text. Undo, Redo, Select All and Delete are not read here: their keys are still forwarded.
/// A chord with Shift (COPYBASE, PASTEBLOCK) is no `edit.*` command and arrives as a key press.
pub fn queue_fired_edits(&mut self, ctx: &egui::Context, fired: &[Fired]) {
let before = self.fired_edits.len();
for fired in fired.iter().filter(|fired| fired.source == FireSource::Key && fired.phase == FirePhase::Press && !fired.mods.shift) {
match fired.command.id.as_str() {
id if id == EditCommands::Copy.id() => self.fired_edits.push(egui::Event::Copy),
id if id == EditCommands::Cut.id() => self.fired_edits.push(egui::Event::Cut),
// A paste with no text (an empty or image clipboard) sends no event in the main window either.
id if id == EditCommands::Paste.id() => {
if let Some(text) = fired.pasted.as_ref().and_then(|content| content.text.as_deref()) {
self.fired_edits.push(egui::Event::Paste(text.to_string()));
}
}
_ => {}
}
}
if self.fired_edits.len() > before {
ctx.request_repaint_of(ViewportId::ROOT);
}
}
/// The root values of this frame. CADCraft registers no commands with the runtime and lets it toggle no chrome, so
/// it acts only on the clipboard commands the output carries. The interface scale is the Options value: the runtime
/// is the one writer of egui's zoom factor. While one of CADCraft's own modals shows (Save Changes, the lossy-save
/// warning, Drawing Recovery, an egui modal), the runtime blocks the panels floated into windows of their own.
fn frame_input(&mut self, ctx: &egui::Context, output: FrameOutput) -> FrameInput {
self.queue_fired_edits(ctx, &output.fired);
let mode = match self.ui.theme.resolve(ctx.system_theme()) {
egui::Theme::Light => craft_theme::Mode::Light,
egui::Theme::Dark => craft_theme::Mode::Dark,
};
let root = RootEnv::new().mode(mode).scale(Scale::new(self.options.interface_scale));
let app_modal = crate::docking::native_input_blocked(self, ctx).then_some(ViewportId::ROOT);
FrameInput::new(root).commands(CommandInput::new().overrides(command_overrides())).host(Arc::clone(&self.framework_host)).app_modal(app_modal)
}
/// The keyboard zoom: Ctrl+=, Ctrl++ and Ctrl+- (Cmd on macOS) step the Options dialog's interface scale by a tenth
/// within its limits, and Ctrl+0 sets it back to the system's own size, also while a text field has the keyboard.
/// It takes the keys out of `viewport`'s input, so it runs after the shortcuts, where the user may have given one of
/// these keys to a command. A shortcut being recorded gets them, and in the browser they zoom the page.
pub(crate) fn zoom_keys(&mut self, ctx: &egui::Context, viewport: ViewportId) {
use egui::gui_zoom::kb_shortcuts::{ZOOM_IN, ZOOM_IN_SECONDARY, ZOOM_OUT, ZOOM_RESET};
if cfg!(target_arch = "wasm32") || crate::keys::recording(ctx) {
return;
}
let (smallest, largest) = (*INTERFACE_SCALES.start(), *INTERFACE_SCALES.end());
let step = |scale: f32, by: f32| ((scale + by).clamp(smallest, largest) * 10.0).round() / 10.0;
let shown = self.options.interface_scale;
let scale = ctx.input_mut_for(viewport, |input| {
if input.consume_shortcut(&ZOOM_RESET) {
return 1.0;
}
let mut scale = shown;
if input.consume_shortcut(&ZOOM_IN) || input.consume_shortcut(&ZOOM_IN_SECONDARY) {
scale = step(scale, 0.1);
}
if input.consume_shortcut(&ZOOM_OUT) {
scale = step(scale, -0.1);
}
scale
});
if scale != shown {
self.options.interface_scale = scale;
// The next frame's root values carry it.
ctx.request_repaint_of(ViewportId::ROOT);
}
}
/// The framework's part of `App::logic`, after CADCraft's own: the root window's close path. Unsaved drawings hold
/// the window open while Save Changes asks about each ([`CadApp::request_quit`]); otherwise it closes.
pub fn close_path(&mut self, ctx: &egui::Context) {
embed::logic(ctx, || if self.request_quit() { CloseDecision::Hold } else { CloseDecision::Close });
}
/// The framework dialogs open on [`CadApp::framework_dialogs`], once per pass after CADCraft's own UI.
pub(crate) fn run_framework_dialogs(&mut self, ui: &mut egui::Ui) {
self.framework_dialogs.run(ui);
}
}
/// The drawing's widget, the window's document canvas.
pub(crate) fn drawing_id() -> egui::Id {
egui::Id::unique("cadcraft-drawing")
}
/// Declares the drawing, drawn in this pass, as the window's document canvas. With nothing focused it is the window's
/// key target: Enter, the arrows, Delete, the edit chords and the clipboard events stay in egui's input for the command
/// line and CADCraft's shortcuts. Tab and Shift+Tab stop at the drawing; with `keeps_tab` the focused drawing keeps
/// them in egui's input, else they move on from it.
pub(crate) fn host_canvas(ctx: &egui::Context, keeps_tab: bool) {
const KEYS: KeyUse = KeyUse::CANVAS.with_edits(EditSet::ALL);
let keys = if keeps_tab { KEYS.with_keep(KeepKeys::Tab) } else { KEYS };
craft_ui::runtime::focus::host_canvas(ctx, drawing_id(), keys);
}
/// Whether a modal dialog, CADCraft's, egui's or the framework's, or an egui menu or popup is up. A framework menu holds
/// the focus in its own layer.
pub(crate) fn overlay_open(app: &CadApp, ctx: &egui::Context) -> bool {
crate::docking::native_input_blocked(app, ctx) || egui::Popup::is_any_open(ctx) || overlay::any_open(ctx, OpenFilter::Modal)
}
/// Whether a widget other than the drawing has the keyboard. The command line and CADCraft's shortcuts have it
/// otherwise: with nothing focused, and while the drawing is the focused Tab stop.
pub(crate) fn widget_has_keyboard(ctx: &egui::Context) -> bool {
ctx.egui_wants_keyboard_input() && !ctx.memory(|memory| memory.has_focus(drawing_id()))
}
/// Whether Escape was pressed in this pass: from egui while one of CADCraft's own widgets or popups has the keyboard,
/// otherwise the window's cancel, which the runtime routes to no component. Leaves it for later readers.
pub(crate) fn escape_pressed(ctx: &egui::Context) -> bool {
ctx.input(|i| i.key_pressed(egui::Key::Escape)) || window_cancel_pending(ctx)
}
/// Whether the window's cancel (an Escape while nothing has framework focus) is there and untaken.
pub(crate) fn window_cancel_pending(ctx: &egui::Context) -> bool {
let mut pending = false;
with_window_intents(ctx, false, |intents| {
pending = intents.untaken(&Intent::Cancel);
false
});
pending
}
/// The window frame the app decides, for the main window's builder and the runtime.
pub use craft_window::policy::Decision;
/// `builder` with the decided `frame` applied: the macOS inset frame's full-size content view and hidden title.
pub fn apply_frame(builder: egui::ViewportBuilder, frame: Option<&Decision>) -> egui::ViewportBuilder {
match frame {
Some(decision) => craft_window::policy::apply(builder, &decision.frame),
None => builder,
}
}
/// Whether CADCraft draws the title row: the frame is not the system's.
pub fn draws_title_row(frame: Option<&Decision>) -> bool {
frame.is_some_and(|decision| !matches!(decision.frame, craft_window::policy::Frame::Native))
}
+2 -4
View File
@@ -269,7 +269,6 @@ mod tests {
let r = app.session.execute("line", &serde_json::json!({"points": [[0, 0], [10, 0]]})).unwrap();
let h = Handle::parse_hex(r["handles"][0].as_str().unwrap()).unwrap();
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
run_frame(&mut app, &ctx, Vec::new());
let at = app.canvas.rect.map_or(pos2(700.0, 450.0), |r| r.center() + vec2(40.0, -30.0));
run_frame(&mut app, &ctx, vec![Event::PointerMoved(at)]);
@@ -279,7 +278,8 @@ mod tests {
// `20` Tab: the length locks and the next field is active; the grip sits on the circle.
run_frame(&mut app, &ctx, vec![Event::Text("20".into())]);
run_frame(&mut app, &ctx, key(egui::Key::Tab));
// (Tab reaches the command line as text: `cmdline::capture_tab`.)
run_frame(&mut app, &ctx, vec![Event::Text("\t".into())]);
assert_eq!(app.canvas.grip_dyn.locked, [(0, "20".to_owned())]);
assert_eq!(app.canvas.grip_dyn.active, 1);
assert!(app.cmd.buffer.is_empty());
@@ -312,7 +312,6 @@ mod tests {
// The UCS icon paints "X" and "Y" too: off (UCSICON, which the drawing keeps).
app.run("ucsicon", serde_json::json!({"on": false})).unwrap();
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
crate::canvas::tests::painted_text(&mut app, &ctx, pos2(700.0, 450.0));
let at = app.canvas.xf.unwrap().to_screen(Vec2::ZERO) + vec2(130.0, -70.0);
let labels = |text: &str| text.lines().filter(|l| matches!(*l, "X" | "Y" | "<")).map(str::to_owned).collect::<Vec<_>>();
@@ -350,7 +349,6 @@ mod tests {
let r = app.session.execute("line", &serde_json::json!({"points": [[0, 0], [10, 0]]})).unwrap();
let h = Handle::parse_hex(r["handles"][0].as_str().unwrap()).unwrap();
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
crate::canvas::tests::painted_text(&mut app, &ctx, pos2(700.0, 450.0));
let at = app.canvas.xf.unwrap().to_screen(Vec2::ZERO) + vec2(130.0, -70.0);
app.session.start_grip_edit(&[(h, 2)]).unwrap();
+2 -2
View File
@@ -498,7 +498,7 @@ fn fill_ui(ui: &mut egui::Ui, f: &mut Fill, action: &mut Action) {
}
ui.end_row();
ui.label(crate::tl!("Shape"));
egui::ComboBox::from_id_salt("hatch_shape").selected_text(shape_label(&f.shape)).show_ui(ui, |ui| {
craft_ui::ComboBox::from_id_salt("hatch_shape").selected_text(shape_label(&f.shape)).show_ui(ui, |ui| {
for name in SHAPES {
ui.selectable_value(&mut f.shape, name.to_string(), shape_label(name));
}
@@ -545,7 +545,7 @@ fn fill_ui(ui: &mut egui::Ui, f: &mut Fill, action: &mut Action) {
f.origin = None;
}
ui.add_enabled_ui(f.origin.is_none(), |ui| {
egui::ComboBox::from_id_salt("hatch_origin_mode").selected_text(origin_label(&f.origin_mode)).show_ui(ui, |ui| {
craft_ui::ComboBox::from_id_salt("hatch_origin_mode").selected_text(origin_label(&f.origin_mode)).show_ui(ui, |ui| {
for m in ORIGIN_MODES {
ui.selectable_value(&mut f.origin_mode, m.to_string(), origin_label(m));
}
-1
View File
@@ -233,7 +233,6 @@ fn picks_merge_into_the_state() {
fn frames(app: &mut CadApp) -> egui::Context {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
app.logic(&ctx);
let input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 1000.0))), ..Default::default() };
// Enough frames for a window that grows each frame to show it.
-7
View File
@@ -398,7 +398,6 @@ fn the_wcs_pill_draws_its_arrow_instead_of_a_glyph_a_font_may_lack() {
// #1541: "WCS ⌄" showed a box where the UI font had no "⌄"; the chevron is now drawn as
// lines, so no catalog and no language paints the glyph.
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let mut app = CadApp::new(Session::new(), Services::default());
for language in &LANGUAGES {
assert!(!language.source.contains('\u{2304}'), "{}.tsv still has the \u{2304} glyph", language.code);
@@ -452,7 +451,6 @@ fn render(app: &mut CadApp, ctx: &egui::Context) -> String {
#[test]
fn the_command_line_says_or_before_keywords_as_the_prompt_does() {
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
for lang in ["en", "de"] {
let mut app = CadApp::new(Session::new(), Services::default());
app.run("ui.language", json!({ "lang": lang })).unwrap();
@@ -481,7 +479,6 @@ fn live_switch_translates_the_shell_without_mutating_drawing_or_automation() {
app.ui.in_window_menu = true;
app.session.state_mut().unwrap().title = "Open".into();
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
app.logic(&ctx);
assert!(render(&mut app, &ctx).contains("Properties"));
let commands = crate::control::all_commands(&app);
@@ -544,7 +541,6 @@ fn dialogs_render_in_every_language_and_keep_their_source_ids() {
app.ui.interface_language = Preference::parse(language.code).unwrap();
app.ui.dialog = Some(dialog.into());
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
app.logic(&ctx);
let text = render(&mut app, &ctx);
assert!(text.contains(tr(app.language(), heading)), "{}: {dialog}: {text}", language.code);
@@ -565,7 +561,6 @@ fn interface_fonts_cover_every_letter_in_each_catalog() {
continue;
}
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
if extra_font {
crate::theme::install_fonts(&ctx, language.code);
}
@@ -636,7 +631,6 @@ fn korean_ui_fonts_cover_the_language_picker_in_both_families() {
// The picker shows 한국어 in an English interface only when the CJK fonts loaded in every
// language cover Hangul; the Korean interface itself always does, with a fallback font.
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let english = crate::theme::cjk_covers_hangul();
assert_eq!(with_language("en", || Preference::Korean.name()), if english { "한국어" } else { "Korean" });
assert_eq!(with_language("ko", || Preference::Korean.name()), "한국어");
@@ -681,7 +675,6 @@ fn production_font_chain_covers_latin_and_shortcut_symbols() {
// `default_fonts` and `monochrome_emoji_fonts` in production, so web and native builds
// always start with bounded Latin and monochrome icon faces instead of an empty family.
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
crate::theme::install_fonts(&ctx, "en");
let mut output = ctx.run_ui(Default::default(), |_| {});
output.textures_delta.clear();
-1
View File
@@ -592,7 +592,6 @@
Query Entities 查询实体
Quick 快速
Quick Dimension 快速标注
Quick Leader 快速引线
Quick Properties 快速特性
Quick Select 快速选择
Quick Select Properties 快速选择特性
1 # CADCraft Simplified Chinese interface catalog — original translations.
592
593
594
595
596
597
+15 -22
View File
@@ -3,6 +3,7 @@
//! Icons are line drawings on a 24×24 design grid: light strokes for existing geometry, blue for
//! the geometry a command creates and orange dots for picked points.
use craft_ui::buttons::{ButtonVisuals, IconButton, IconButtonStyle};
use egui::{Color32, Painter, Pos2, Rect, Stroke, pos2};
use crate::theme::Tokens;
@@ -1145,31 +1146,23 @@ pub fn button(ui: &mut egui::Ui, icon: Icon, size: f32, tooltip: &str, selected:
button_bare(ui, icon, size, tooltip, selected).on_hover_text(crate::i18n::t(tooltip))
}
/// [`button`] without its hover text, for callers that show a richer tooltip of their own. CADCraft paints the
/// button in its own colours: transparent, the hover tint, the active-tab fill while selected, and an accent ring
/// inside it while it has keyboard focus.
/// [`button`] without its hover text, for callers that show a richer tooltip of their own.
pub fn button_bare(ui: &mut egui::Ui, icon: Icon, size: f32, tooltip: &str, selected: bool) -> egui::Response {
const RADIUS: egui::CornerRadius = egui::CornerRadius::same(3);
let t = Tokens::get();
let label = crate::i18n::t(tooltip);
let (rect, resp) = ui.allocate_exact_size(egui::vec2(size, size), egui::Sense::click());
resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, ui.is_enabled(), selected, label));
let fill = if selected {
t.tab_active
} else if resp.hovered() {
t.control_hover.gamma_multiply(0.6)
} else {
Color32::TRANSPARENT
let visuals = |fill| ButtonVisuals { fill, stroke: Stroke::NONE, icon: t.icon };
let style = IconButtonStyle {
normal: visuals(Color32::TRANSPARENT),
hovered: visuals(t.control_hover.gamma_multiply(0.6)),
pressed: None,
selected: visuals(t.tab_active),
corner_radius: egui::CornerRadius::same(3),
focus_stroke: Stroke::new(1.0, t.accent),
};
if fill != Color32::TRANSPARENT {
ui.painter().rect_filled(rect, RADIUS, fill);
}
// A single tint would erase the blue geometry and orange picked points: the original painter keeps its own
// colours and its explicit dimming.
paint(ui.painter(), rect.shrink(size * 0.08), icon, !ui.is_enabled());
if resp.has_focus() && size > 4.0 {
ui.painter().rect_stroke(rect.shrink(2.0), RADIUS, Stroke::new(1.0, t.accent), egui::StrokeKind::Inside);
}
let resp = IconButton::new(crate::i18n::t(tooltip), egui::vec2(size, size), &style).selected(selected).show(ui, |ui, rect, _| {
// A single tint would erase the blue geometry and orange picked points. Keep the
// original painter and its explicit dimming on the same parent-enabled UI.
paint(ui.painter(), rect.shrink(size * 0.08), icon, !ui.is_enabled());
});
crate::control::record_widget(ui, &resp, tooltip, "button", Some(selected));
resp
}
-2
View File
@@ -341,8 +341,6 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
_ => None,
})
});
// An Escape with nothing focused is the window's cancel, which the runtime keeps out of egui's events.
let pressed = pressed.or_else(|| crate::framework::window_cancel_pending(ctx).then_some((Key::Escape, egui::Modifiers::NONE)));
if let Some((k, m)) = pressed {
if k != Key::Escape {
note = Some(match assign(&mut app.ui.shortcuts, &id, &format(m, k)) {
+2 -2
View File
@@ -234,7 +234,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
let linetypes: Vec<cadcraft_doc::Linetype> = d.linetypes.clone();
let library: Vec<String> = cadcraft_doc::library::standard_linetypes().into_iter().map(|l| l.name).filter(|n| d.linetype(n).is_none()).collect();
let states: Vec<String> = d.layer_states.iter().map(|s| s.name.clone()).collect();
let mut layers: Vec<Layer> = d.layers.to_vec();
let mut layers: Vec<Layer> = d.layers.clone();
layers.sort_by_key(|l| natural_lower(&l.name));
if st.sort_desc {
layers.reverse();
@@ -283,7 +283,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
// Layer states.
ui.label(crate::tl!("Layer State"));
let label = st.state_sel.clone().unwrap_or_else(|| crate::tl!("Unsaved Layer State").into());
egui::ComboBox::from_id_salt("lpm_states").selected_text(label).width(170.0).show_ui(ui, |ui| {
craft_ui::ComboBox::from_id_salt("lpm_states").selected_text(label).width(170.0).show_ui(ui, |ui| {
for s in &states {
if ui.selectable_label(st.state_sel.as_deref() == Some(s), s).clicked() {
st.state_sel = Some(s.clone());
+22 -28
View File
@@ -35,7 +35,6 @@ pub mod dialogs;
pub mod docking;
mod drawing_fonts;
pub mod fault;
pub mod framework;
// The Find and Replace window behind the FIND command.
pub mod arraydlg;
pub mod finddlg;
@@ -330,17 +329,11 @@ pub struct CadApp {
/// modifiers held there, for the main window's next input ([`Self::forward_native_input`]).
forwarded: Vec<egui::Event>,
forwarded_modifiers: Option<egui::Modifiers>,
/// The Copy, Cut and Paste a floating panel's window fired as framework commands, as the clipboard events the
/// shortcuts read ([`Self::queue_fired_edits`]).
fired_edits: Vec<egui::Event>,
/// The main window's own modifiers, put back the frame after forwarded keys went in.
restore_modifiers: Option<egui::Modifiers>,
/// The panel arrangement the dock shows and the panels' specs ([`docking::LiveDock`]).
pub(crate) dock: docking::LiveDock,
/// Who CADCraft is to the framework's dock and dialogs ([`framework`]).
framework_host: std::sync::Arc<craft_host::Host>,
/// The framework dialogs CADCraft keeps open (the update dialogs), run after its own UI.
pub framework_dialogs: craft_ui::dialog::DialogHost,
/// A panel opened from a menu or command, whose floating window comes to the front on the
/// next frame (craft-ui's `DockArea::raise_panel`).
pub raise_panel: Option<docking::Panel>,
/// One synthetic batch has been put into `RawInput` and is waiting for a real `App::ui` call.
synthetic_injected: bool,
/// Counts settled UI passes (one per painted frame; never hidden logic-only ticks or
@@ -359,6 +352,8 @@ pub struct CadApp {
shown_follows_system: bool,
/// Whether egui was last told to animate (`None` until the first frame).
shown_animations: Option<bool>,
/// The interface scale last handed to egui (`None` until the first frame).
shown_interface_scale: Option<f32>,
pub frame_ms: f64,
pub quit_requested: bool,
/// The app may close although drawings have unsaved changes (they were dealt with, or the
@@ -427,11 +422,8 @@ impl CadApp {
paste: clipboard::Paste::default(),
forwarded: Vec::new(),
forwarded_modifiers: None,
fired_edits: Vec::new(),
restore_modifiers: None,
dock: docking::LiveDock::default(),
framework_host: framework::host(),
framework_dialogs: craft_ui::dialog::DialogHost::default(),
raise_panel: None,
synthetic_injected: false,
ui_frames: 0,
#[cfg(not(target_arch = "wasm32"))]
@@ -441,6 +433,7 @@ impl CadApp {
shown_theme: None,
shown_follows_system: false,
shown_animations: None,
shown_interface_scale: None,
frame_ms: 0.0,
quit_requested: false,
quit_confirmed: false,
@@ -1022,6 +1015,11 @@ impl CadApp {
if self.restore_modifiers.is_some() {
ctx.request_repaint();
}
// Closing the window with unsaved changes asks first. `run_logic` refreshes viewport
// close/focus state, so this must also work while hidden.
if ctx.input(|i| i.viewport().close_requested()) && self.request_quit() {
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
}
// A long AutoLISP routine runs one bounded slice per frame, including hidden web/native
// ticks; it must not depend on a paint or `RequestPaintWhileHidden`.
self.session.lisp_tick();
@@ -1131,9 +1129,9 @@ impl CadApp {
// The batch reached an actual Ui callback; a discarded pass still consumed it.
self.synthetic_injected = false;
}
// `will_rerun` is false on the settled (final) pass of a frame, whether the frame is
// single-pass or the second pass after a layout discard; a pass that will run again is skipped.
if !craft_ui::runtime::frame::will_rerun(&ctx) {
// `will_discard()` is false on the settled (final) pass of a frame, whether the frame is
// single-pass or the second pass after a layout discard; a discarded pass is skipped.
if !ctx.will_discard() {
self.ui_frames = self.ui_frames.saturating_add(1);
capture::issue(self, &ctx);
}
@@ -1175,6 +1173,13 @@ impl CadApp {
if !animate {
animation::unsmooth_scroll(ctx);
}
// Applied only when the saved scale changes, so egui's own keyboard zoom keeps working
// within a session (and is never saved).
let scale = self.options.interface_scale;
if self.shown_interface_scale != Some(scale) {
ctx.set_zoom_factor(scale);
self.shown_interface_scale = Some(scale);
}
// Wait for the frame cap on a painted pass, where a wait cannot delay a hidden tick.
#[cfg(not(target_arch = "wasm32"))]
if let Some(cap) = &mut self.frame_cap {
@@ -1187,7 +1192,6 @@ impl CadApp {
/// Input-derived work, once per layout frame.
fn ui_input(&mut self, ctx: &egui::Context) {
menus::shortcuts(self, ctx);
self.zoom_keys(ctx, egui::ViewportId::ROOT);
#[cfg(not(target_arch = "wasm32"))]
{
let dropped = ctx.input_mut(|input| std::mem::take(&mut input.raw.dropped_files));
@@ -1227,7 +1231,6 @@ impl CadApp {
if has_doc {
docking::show(self, ui);
} else {
self.canvas.shown = None;
chrome::start_page(self, ui);
}
});
@@ -1241,7 +1244,6 @@ impl CadApp {
autosave::show(self, ui.ctx());
autosave::gpu_notice(self, ui.ctx());
autosave::failure_notice(self, ui.ctx());
self.run_framework_dialogs(ui);
self.frame_ms = now_ms() - t0;
}
@@ -1361,7 +1363,6 @@ mod tests {
start(&mut single);
start(&mut twice);
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
frame(&mut single, &ctx, None);
two_pass_frame(&mut twice, &ctx);
let counter = |app: &CadApp| match app.session.lisp_var("CC-TWO") {
@@ -1385,7 +1386,6 @@ mod tests {
let (request, reply) = ControlRequest::new("engine.execute", json!({ "command": "line", "params": { "points": [[0.0, 0.0], [10.0, 0.0]] } }));
tx.send(request).expect("the request is queued");
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
two_pass_frame(&mut app, &ctx);
let entities = app.session.doc().map(cadcraft_doc::Drawing::entity_count).unwrap_or_default();
assert_eq!(entities, 1, "one command ran once, in the first pass");
@@ -1398,7 +1398,6 @@ mod tests {
fn hidden_logic_does_not_run_frame_only_work() {
let mut a = app();
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
// A logic-only call (what eframe runs for a hidden window) reports pass index zero too.
a.logic(&ctx);
assert_eq!(a.ui_frames, 0, "no real Ui callback ran");
@@ -1415,7 +1414,6 @@ mod tests {
let mut a = CadApp::new(Session::new(), Services::default());
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let started = a
.session
.lisp_eval("(setq cc-hidden 0) (while (< cc-hidden 400000) (setq cc-hidden (1+ cc-hidden)))", false, false, Vec::new())
@@ -1439,7 +1437,6 @@ mod tests {
fn one_synthetic_batch_waits_for_a_real_ui_pass() {
let mut a = app();
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
a.synthetic.push(egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE });
let mut first = egui::RawInput::default();
a.raw_input_hook(&ctx, &mut first);
@@ -1475,7 +1472,6 @@ mod tests {
assert_eq!(b.ui.theme, ThemePref::Light, "bad prefs are ignored");
// A fixed choice ignores the OS; the tokens and egui follow the choice.
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
frame(&mut b, &ctx, Some(egui::Theme::Dark));
assert_eq!(Tokens::get(), Tokens::LIGHT);
assert_eq!(ctx.theme(), egui::Theme::Light);
@@ -1493,7 +1489,6 @@ mod tests {
let mut a = app();
a.start("ui.theme.system");
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
frame(&mut a, &ctx, Some(egui::Theme::Light));
assert_eq!(Tokens::get(), Tokens::LIGHT);
assert_eq!(ctx.theme(), egui::Theme::Light);
@@ -1512,7 +1507,6 @@ mod tests {
let mut a = app();
a.start("ui.theme.system");
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
frame(&mut a, &ctx, Some(egui::Theme::Light));
// A concrete Light would pin the native window appearance and hide later OS changes.
assert_eq!(ctx.options(|o| o.theme_preference), egui::ThemePreference::System);
+1 -1
View File
@@ -143,7 +143,7 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) {
});
});
let outside = ctx.input(|i| i.pointer.primary_pressed() && i.pointer.interact_pos().is_some_and(|p| !area.response.rect.contains(p)));
if crate::framework::escape_pressed(ctx) {
if ctx.input(|i| i.key_pressed(Key::Escape)) {
done = Done::Cancel;
} else if armed && outside {
done = Done::Ok;
+7 -7
View File
@@ -139,7 +139,7 @@ fn linetype(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Action {
let mut pick_lin = false;
egui::Window::new("Linetype Manager").open(open).default_size(vec2(520.0, 360.0)).resizable(true).show(ctx, |ui| {
ui.horizontal(|ui| {
egui::ComboBox::from_id_salt("ltmgr_load").selected_text("Load...").width(110.0).show_ui(ui, |ui| {
craft_ui::ComboBox::from_id_salt("ltmgr_load").selected_text("Load...").width(110.0).show_ui(ui, |ui| {
if library.is_empty() {
ui.label("Every library linetype is loaded.");
} else if ui.selectable_label(false, "All").clicked() {
@@ -519,7 +519,7 @@ fn style_manager(ctx: &egui::Context, open: &mut bool, title: &str, cmd: &'stati
Field::Choice(key, label, v, choices) => {
ui.label(*label);
let mut picked = None;
egui::ComboBox::from_id_salt((cmd, *key)).selected_text(v.as_str()).show_ui(ui, |ui| {
craft_ui::ComboBox::from_id_salt((cmd, *key)).selected_text(v.as_str()).show_ui(ui, |ui| {
for c in choices.iter() {
if ui.selectable_label(c == v, c).clicked() && c != v {
picked = Some(c.clone());
@@ -682,7 +682,7 @@ fn page_rows(
) -> Option<(&'static str, Value)> {
let mut change = None;
ui.label("Printer/plotter");
egui::ComboBox::from_id_salt(salt.with("device")).selected_text(device_label(page)).width(190.0).show_ui(ui, |ui| {
craft_ui::ComboBox::from_id_salt(salt.with("device")).selected_text(device_label(page)).width(190.0).show_ui(ui, |ui| {
if ui.selectable_label(device_label(page) == "None", "None").on_hover_text("PDF on the paper chosen below").clicked()
&& device_label(page) != "None"
{
@@ -701,7 +701,7 @@ fn page_rows(
// The device's papers, else the standard sizes.
let device = choices.devices.iter().find(|dv| dv.name.eq_ignore_ascii_case(&page.device));
ui.label("Paper size");
egui::ComboBox::from_id_salt(salt.with("paper")).selected_text(page.paper.as_str()).width(190.0).show_ui(ui, |ui| match device {
craft_ui::ComboBox::from_id_salt(salt.with("paper")).selected_text(page.paper.as_str()).width(190.0).show_ui(ui, |ui| match device {
Some(dev) => {
for p in &dev.papers {
if ui.selectable_label(p.name == page.paper, &p.name).clicked() && p.name != page.paper {
@@ -747,7 +747,7 @@ fn page_rows(
}
ui.label("Plot area");
ui.add_enabled_ui(rows.areas.len() > 1, |ui| {
egui::ComboBox::from_id_salt(salt.with("area")).selected_text(area_label(&page.plot_area)).show_ui(ui, |ui| {
craft_ui::ComboBox::from_id_salt(salt.with("area")).selected_text(area_label(&page.plot_area)).show_ui(ui, |ui| {
for a in rows.areas {
if ui.selectable_label(page.plot_area == *a, area_label(a)).clicked() && page.plot_area != *a {
change = Some(("plotArea", json!(a)));
@@ -823,7 +823,7 @@ fn page_rows(
}
ui.end_row();
ui.label("Plot style table");
egui::ComboBox::from_id_salt(salt.with("styles")).selected_text(style_label(page)).width(190.0).show_ui(ui, |ui| {
craft_ui::ComboBox::from_id_salt(salt.with("styles")).selected_text(style_label(page)).width(190.0).show_ui(ui, |ui| {
if ui.selectable_label(style_label(page) == "None", "None").clicked() && style_label(page) != "None" {
change = Some(("plotStyleTable", json!("None")));
}
@@ -1041,7 +1041,7 @@ fn plot(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Action {
egui::Window::new("Plot").open(open).collapsible(false).resizable(false).pivot(egui::Align2::CENTER_CENTER).default_pos(center).show(ctx, |ui| {
egui::Grid::new("plot_target").num_columns(2).spacing(vec2(10.0, 6.0)).show(ui, |ui| {
ui.label("Layout");
egui::ComboBox::from_id_salt("plot_layout").selected_text(st.target.as_str()).width(190.0).show_ui(ui, |ui| {
craft_ui::ComboBox::from_id_salt("plot_layout").selected_text(st.target.as_str()).width(190.0).show_ui(ui, |ui| {
for n in &targets {
if ui.selectable_label(*n == st.target, n).clicked() && *n != st.target {
st.page = plot_page(d, n);
+2 -2
View File
@@ -103,7 +103,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Option<
}
ui.horizontal(|ui| {
ui.label("Block:");
egui::ComboBox::from_id_salt("battman_blocks").selected_text(block.as_str()).width(180.0).show_ui(ui, |ui| {
craft_ui::ComboBox::from_id_salt("battman_blocks").selected_text(block.as_str()).width(180.0).show_ui(ui, |ui| {
for b in &blocks {
if ui.selectable_label(*b == block, b).clicked() {
block = b.clone();
@@ -189,7 +189,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Option<
}
ui.end_row();
ui.label("Layer");
egui::ComboBox::from_id_salt("battman_layer").selected_text(r.layer.as_str()).show_ui(ui, |ui| {
craft_ui::ComboBox::from_id_salt("battman_layer").selected_text(r.layer.as_str()).show_ui(ui, |ui| {
for l in &layers {
if ui.selectable_label(*l == r.layer, l).clicked() && *l != r.layer {
action = act(edit("layer", json!(l)), apply);

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