mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-04 21:12:57 -05:00
Merge main into fix/popout-stable-measure
This commit is contained in:
commit
829f85298e
220 files changed
+16981
-901
No files matched your search
Generated
+103
@@ -2,6 +2,30 @@
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "acadrust"
|
||||
version = "0.6.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8923c99ea1f151cb7fc17ce2fc14f8b1e330fa22611e535602d985c0cc3c89a2"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"bitflags 2.13.2",
|
||||
"byteorder",
|
||||
"encoding_rs",
|
||||
"flate2",
|
||||
"foldhash 0.2.0",
|
||||
"indexmap",
|
||||
"itoa",
|
||||
"memmap2",
|
||||
"nom 7.1.3",
|
||||
"oem_cp",
|
||||
"once_cell",
|
||||
"rayon",
|
||||
"ryu",
|
||||
"thiserror 2.0.21",
|
||||
"web-time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "accesskit"
|
||||
version = "0.25.2"
|
||||
@@ -1238,6 +1262,7 @@ dependencies = [
|
||||
"craft-browse",
|
||||
"craft-cms",
|
||||
"craft-color-ui",
|
||||
"craft-control",
|
||||
"craft-dialogs",
|
||||
"craft-draw",
|
||||
"craft-font-catalog",
|
||||
@@ -1280,6 +1305,16 @@ dependencies = [
|
||||
"ruzstd",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-ai-agents"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-ai-integrations?rev=d94a3593adcff504eaaad9e5aee4c84fd2f07a72#d94a3593adcff504eaaad9e5aee4c84fd2f07a72"
|
||||
dependencies = [
|
||||
"dirs",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-appkit"
|
||||
version = "0.1.0"
|
||||
@@ -1417,8 +1452,13 @@ name = "craft-control"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"craft-ai-agents",
|
||||
"craft-atomic",
|
||||
"craft-control-protocol",
|
||||
"craft-flags",
|
||||
"craft-platform",
|
||||
"dirs",
|
||||
"log",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
@@ -1510,6 +1550,15 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-dwg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"acadrust",
|
||||
"log",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-dxf"
|
||||
version = "0.1.0"
|
||||
@@ -1537,6 +1586,16 @@ name = "craft-eps"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
|
||||
[[package]]
|
||||
name = "craft-flags"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"dirs",
|
||||
"toml_edit",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-font-catalog"
|
||||
version = "0.1.0"
|
||||
@@ -1983,6 +2042,15 @@ dependencies = [
|
||||
"web-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-raster3d"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-review"
|
||||
version = "0.1.0"
|
||||
@@ -5865,6 +5933,15 @@ dependencies = [
|
||||
"objc2-foundation 0.2.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "oem_cp"
|
||||
version = "2.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8c7959d3349f484aec36462f98226983578bf7d33f9b034c32967489c7000e1f"
|
||||
dependencies = [
|
||||
"phf 0.11.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.21.4"
|
||||
@@ -6037,6 +6114,15 @@ dependencies = [
|
||||
"indexmap",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "phf"
|
||||
version = "0.11.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078"
|
||||
dependencies = [
|
||||
"phf_shared 0.11.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "phf"
|
||||
version = "0.13.1"
|
||||
@@ -6104,6 +6190,15 @@ dependencies = [
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "phf_shared"
|
||||
version = "0.11.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5"
|
||||
dependencies = [
|
||||
"siphasher",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "phf_shared"
|
||||
version = "0.13.1"
|
||||
@@ -8619,6 +8714,7 @@ dependencies = [
|
||||
name = "vectorcraft-cad"
|
||||
version = "0.25.1"
|
||||
dependencies = [
|
||||
"craft-dwg",
|
||||
"craft-dxf",
|
||||
"craft-image-codecs",
|
||||
"craft-plotter",
|
||||
@@ -8632,12 +8728,15 @@ dependencies = [
|
||||
"vectorcraft-geom 0.25.1",
|
||||
"vectorcraft-pathops 0.25.1",
|
||||
"vectorcraft-text",
|
||||
"web-time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-cli"
|
||||
version = "0.25.1"
|
||||
dependencies = [
|
||||
"craft",
|
||||
"craft-dwg",
|
||||
"log",
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-text",
|
||||
@@ -8700,6 +8799,7 @@ name = "vectorcraft-effects"
|
||||
version = "0.25.1"
|
||||
dependencies = [
|
||||
"craft-image-codecs",
|
||||
"craft-raster3d",
|
||||
"craft-svg",
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
@@ -8727,6 +8827,7 @@ dependencies = [
|
||||
"craft-codepage",
|
||||
"craft-doc",
|
||||
"craft-docpath",
|
||||
"craft-dwg",
|
||||
"craft-font-catalog",
|
||||
"craft-font-store",
|
||||
"craft-image-codecs",
|
||||
@@ -9005,6 +9106,7 @@ dependencies = [
|
||||
name = "vectorcraft-render"
|
||||
version = "0.25.1"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"craft-gif",
|
||||
"craft-image-codecs",
|
||||
"craft-psd",
|
||||
@@ -9173,6 +9275,7 @@ dependencies = [
|
||||
"bytemuck",
|
||||
"chrono",
|
||||
"craft",
|
||||
"craft-dwg",
|
||||
"craft-image-codecs",
|
||||
"egui",
|
||||
"egui_extras",
|
||||
|
||||
@@ -34,6 +34,8 @@ craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea3
|
||||
# DXF tags, reader and writer (craft-libs#778, #926, #927).
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
# DWG to DXF bytes, in a child process on desktop builds (acadrust 0.6.6, MPL-2.0, unmodified).
|
||||
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
# WMF, EMF and EMF+ reader (craft-libs#778).
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
@@ -47,6 +49,8 @@ craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea3
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
# The metallic-roughness BRDF and environment light the 3D effects' Roughness and Metallic shade with.
|
||||
craft-pbr = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
# The CPU rasterizer that draws a 3D effect's Render Settings › Rendered image: depth-buffered triangles, shadow maps.
|
||||
craft-raster3d = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
# The framework facade (`craft::ui`, `craft::settings`, `craft::platform`, ...). No default features: each crate names
|
||||
# the members it imports.
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" }
|
||||
|
||||
@@ -35,6 +35,12 @@ based in part on the work of the Independent JPEG Group.
|
||||
WebAssembly plug-ins run in the wasmi interpreter (MIT OR Apache-2.0); its wasmparser dependency is
|
||||
under the Apache License 2.0 with the LLVM exception.
|
||||
|
||||
DWG drawings are read by the acadrust crate 0.6.6 (https://crates.io/crates/acadrust/0.6.6), through
|
||||
craft-dwg from https://github.com/storytold/craft-libs. acadrust is used unmodified under the Mozilla
|
||||
Public License 2.0; its source is available at that address. Its license text and its third-party
|
||||
notices (code adapted from ACadSharp, Copyright (c) 2021 Albert Domenech, MIT License) are in
|
||||
licenses/acadrust-0.6.6/.
|
||||
|
||||
The .cdr reader (crates/cdr) reads the record layouts that the Kaitai Struct specification
|
||||
coreldraw_cdr.ksy (https://github.com/kaitai-io/coreldraw_cdr.ksy, MIT License) and its fork by Zach
|
||||
Wolfe (https://github.com/filestar/coreldraw_cdr.ksy, branch new_stuff, MIT License) describe. No part
|
||||
|
||||
@@ -316,6 +316,8 @@ RISC-V (riscv64) packages are `vectorcraft-<ver>-linux-riscv64.deb`,
|
||||
|
||||
### FreeBSD
|
||||
|
||||
Prebuilt FreeBSD release archives target FreeBSD 15.1 or newer; FreeBSD 14.x is not supported by these builds.
|
||||
|
||||
| Build | File |
|
||||
|---|---|
|
||||
| x86_64 | `vectorcraft-<ver>-freebsd-x86_64.tar.gz` |
|
||||
|
||||
@@ -271,6 +271,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-26 | minor | Show Missing Links in View and the Links panel marks missing linked images and placed documents on the canvas; the link watcher scans them in the background, so turning it on never waits on a file; transient overlays stay out of artwork, export and undo history; command API controls and lists markers (#5547). Scores and estimates unchanged. |
|
||||
| 2026-11-20 | minor | Color conversion indexes global swatch bases and linked-paint lookups (#8804); scores, estimates and measured budgets unchanged. |
|
||||
| 2026-11-22 | minor | Upcoming: the G11 item names what is left, the unit preference reverting to points (#864; SVG export units are fixed) and a Transform effect in a fill's or stroke's own effects (#885), instead of Shape Builder regions and Asset Export borders, which are fixed (#937, #983 / #1037); its estimate follows docs/roadmap.md and docs/gaps.md, 8–15 → 6–13 h, #8314. The Essentials readiness row's Shape Builder item names what its 4–8 h still covers (checking #937's fix on the reporter's file, still unconfirmed). Headline numbers unchanged. |
|
||||
| 2026-11-15 | minor | Graphic Styles: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); G5 estimate unchanged (3–13 h). |
|
||||
|
||||
@@ -25,6 +25,8 @@ vectorcraft-render = { workspace = true }
|
||||
vectorcraft-text = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
log = { workspace = true }
|
||||
# The agent settings and the desktop app to start for plain `mcp` (the shared `src/agent_settings.rs`).
|
||||
craft = { workspace = true, features = ["automation-agents"] }
|
||||
|
||||
# `perf` on Windows (src/perf.rs) reads how busy the processors are (GetSystemTimes) and this
|
||||
# process's working set (GetProcessMemoryInfo) through winsafe's safe wrappers over Win32 (MIT),
|
||||
@@ -47,11 +49,14 @@ objc2-core-text = { version = "0.3", default-features = false, features = ["std"
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
vectorcraft-testkit = { workspace = true }
|
||||
# DWG files for the `info` test, written from DXF by craft-dwg.
|
||||
craft-dwg = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
# The files of other crates that this crate compiles or its tests read, for CI's test selection.
|
||||
[package.metadata.craft]
|
||||
reads = [
|
||||
"apps/vectorcraft/src/agent_settings.rs",
|
||||
"apps/vectorcraft/src/mac_fonts.rs",
|
||||
"apps/vectorcraft/src/prefs_dir.rs",
|
||||
"apps/vectorcraft/src/profile.rs",
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//!
|
||||
//! ```text
|
||||
//! vectorcraft-cli --safe-mode SUBCOMMAND ...
|
||||
//! vectorcraft-cli mcp [--connect 127.0.0.1:7979 | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]...
|
||||
//! vectorcraft-cli mcp [--headless] [--when-closed launch|headless|error] [--automation-read-root DIR]... [--automation-write-root DIR]...
|
||||
//! vectorcraft-cli run [--in FILE] [--cmd id [--params '{json}'] | --commands FILE|-]... [--export out.svg]... [--scale 2] [--ppi 300] [--width 1920] [--height 1080] [--background transparent]
|
||||
//! vectorcraft-cli commands
|
||||
//! vectorcraft-cli convert IN OUT [--scale 2] [--ppi 300] [--width 1920] [--height 1080] [--background transparent] [--artboard 0 | --range 1-3,5] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--legacy-name-encoding ENC] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
|
||||
@@ -39,6 +39,10 @@ macro_rules! out {
|
||||
}};
|
||||
}
|
||||
|
||||
/// The desktop app's agent settings (Preferences › AI Integrations), shared: plain `mcp` reads the
|
||||
/// closed-app choice and the agent folders the app saved.
|
||||
#[path = "../../vectorcraft/src/agent_settings.rs"]
|
||||
mod agent_settings;
|
||||
/// The desktop app's CoreText font lister, shared: exports and MCP find the same fonts.
|
||||
#[cfg(target_os = "macos")]
|
||||
#[path = "../../vectorcraft/src/mac_fonts.rs"]
|
||||
@@ -56,9 +60,11 @@ mod system_fonts;
|
||||
#[path = "../../vectorcraft/src/windows_cores.rs"]
|
||||
mod windows_cores;
|
||||
|
||||
use craft::automation::agents::WhenAppClosed;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_engine::file_access::{self, AutomationRoots};
|
||||
use vectorcraft_mcp::{Backend, DEFAULT_ADDR, Headless, Remote, Server};
|
||||
use vectorcraft_mcp::agents::{LiveBackend, LiveConfig};
|
||||
use vectorcraft_mcp::{Backend, Headless, Remote, Server};
|
||||
|
||||
/// stdout went away. A reader that stopped early (a closed pipe) ends the program quietly, as
|
||||
/// ripgrep does; any other write error is reported.
|
||||
@@ -79,9 +85,18 @@ USAGE:
|
||||
Safe Mode is on. Plug-ins stay installed. `--safe-mode mcp` serves a headless session and
|
||||
does not take --connect.
|
||||
|
||||
vectorcraft-cli mcp [--connect ADDR | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]... [--allow-plugin-grants]
|
||||
Run the MCP server on stdio. Default: connect to a running app at 127.0.0.1:7979
|
||||
(vectorcraft --control 7979), falling back to a headless in-process session.
|
||||
vectorcraft-cli mcp [--headless] [--when-closed launch|headless|error] [--automation-read-root DIR]... [--automation-write-root DIR]... [--allow-plugin-grants]
|
||||
Run the MCP server on stdio. Every tool call goes to the open VectorCraft window while AI
|
||||
agents may use it (ArtCraft Launcher › Settings › AI agents), found through the connection
|
||||
file the window publishes in the settings folder: no port or token to configure, and an app
|
||||
opened after the session started is found too. Otherwise the call runs in a session without
|
||||
a window. While agents may use VectorCraft but it is closed, the choice in Preferences › AI
|
||||
Integrations applies (open VectorCraft, a session without a window in the agent folders, or
|
||||
an error); --when-closed overrides it. Files of the open window's agent requests stay in the
|
||||
agent folders set there (Documents/ArtCraft/Agents/VectorCraft when none is set); the
|
||||
agent_folders tool names them. --headless always runs without a window.
|
||||
--connect ADDR (deprecated, removed in a later release) drives an app started with
|
||||
vectorcraft --control PORT and its VECTORCRAFT_CONTROL_TOKEN.
|
||||
--automation-read-root / --automation-write-root confine the files the agent's commands read
|
||||
(open, place, relink, library loads…) and write (save, export, package, library saves…) to
|
||||
DIR, links followed; each may be given more than once, a path inside any of its folders being
|
||||
@@ -209,6 +224,12 @@ fn help() -> Result<(), String> {
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
// A copy of this program started with `--dwg-worker` alone converts one DWG drawing and exits.
|
||||
if let Some(code) = vectorcraft_engine::dwg::serve_if_asked() {
|
||||
std::process::exit(code);
|
||||
}
|
||||
// DWG drawings open through that copy, so a damaged file can't end this process.
|
||||
vectorcraft_engine::dwg::use_own_worker();
|
||||
// Before the first render: the cores the process may run on.
|
||||
#[cfg(windows)]
|
||||
windows_cores::install();
|
||||
@@ -280,6 +301,20 @@ fn with_stores(mut h: Headless) -> Headless {
|
||||
h
|
||||
}
|
||||
|
||||
/// Plain `mcp`'s window lookup: the agent settings in `dir`, the closed-app choice (`--when-closed`
|
||||
/// overrides the saved one), the desktop app beside this CLI to start, and headless sessions with
|
||||
/// the user's stores, or confined to the agent folders without them.
|
||||
fn live_config(dir: std::path::PathBuf, when_closed: Option<WhenAppClosed>) -> LiveConfig {
|
||||
let mut cfg = LiveConfig::new(dir, agent_settings::read_settings);
|
||||
cfg.when_closed = when_closed;
|
||||
cfg.launch = std::env::current_exe().ok().and_then(|cli| craft::automation::agents::launcher(&cli, vectorcraft_mcp::agents::APP_EXE));
|
||||
cfg.headless = Box::new(|roots| match roots {
|
||||
Some(roots) => Headless::with_document().with_automation_roots(Some(roots)),
|
||||
None => with_stores(Headless::with_document()),
|
||||
});
|
||||
cfg
|
||||
}
|
||||
|
||||
/// Makes `h`'s `plugin.install` accept `grant` and `allowHeavy` when `allow` (`--allow-plugin-grants`).
|
||||
fn accepting_grants(mut h: Headless, allow: bool) -> Headless {
|
||||
if allow {
|
||||
@@ -288,26 +323,34 @@ fn accepting_grants(mut h: Headless, allow: bool) -> Headless {
|
||||
h
|
||||
}
|
||||
|
||||
/// `mcp`. With `--safe-mode` (`safe_mode`) it serves a headless session: a running app loads its own
|
||||
/// plug-ins, so `--connect` is refused and the default does not connect.
|
||||
/// The stderr line `mcp --connect` prints: the flag works for one more release.
|
||||
const CONNECT_DEPRECATED: &str = "vectorcraft-cli: --connect is deprecated and will be removed in a later release; plain `vectorcraft-cli mcp` finds the open VectorCraft window while AI agents are on in ArtCraft Launcher › Settings › AI agents";
|
||||
|
||||
/// `mcp`: the open VectorCraft window while the person lets agents use it (the ArtCraft Launcher's
|
||||
/// switch), found through its connection file on every tool call, otherwise a headless session
|
||||
/// (`vectorcraft_mcp::agents`). `--headless`, the automation roots, `--allow-plugin-grants` and
|
||||
/// `--safe-mode` (`safe_mode`: a running app loads its own plug-ins) always run headless.
|
||||
/// `--connect ADDR` drives an app started with `vectorcraft --control PORT` (deprecated).
|
||||
fn mcp(args: &[String], safe_mode: bool) -> Result<(), String> {
|
||||
if help_requested(args, &["--connect", "--automation-read-root", "--automation-write-root"]) {
|
||||
if help_requested(args, &["--connect", "--when-closed", "--automation-read-root", "--automation-write-root"]) {
|
||||
return help();
|
||||
}
|
||||
let mut connect: Option<String> = None;
|
||||
let mut headless = false;
|
||||
let mut when_closed: Option<String> = None;
|
||||
let mut allow_grants = false;
|
||||
let (mut read_roots, mut write_roots): (Vec<String>, Vec<String>) = (vec![], vec![]);
|
||||
let mut it = args.iter();
|
||||
while let Some(a) = it.next() {
|
||||
// The roots also come as `--flag=DIR`, as the other Craft apps take them.
|
||||
let (flag, inline) = match a.split_once('=') {
|
||||
Some((f, v)) if f.starts_with("--automation-") => (f, Some(v.to_string())),
|
||||
Some((f, v)) if f.starts_with("--automation-") || f == "--when-closed" => (f, Some(v.to_string())),
|
||||
_ => (a.as_str(), None),
|
||||
};
|
||||
match flag {
|
||||
"--connect" => connect = Some(it.next().cloned().ok_or("--connect needs an address")?),
|
||||
"--headless" => headless = true,
|
||||
"--when-closed" => when_closed = Some(inline.or_else(|| it.next().cloned()).ok_or("--when-closed needs launch, headless or error")?),
|
||||
"--allow-plugin-grants" => allow_grants = true,
|
||||
"--automation-read-root" | "--automation-write-root" => {
|
||||
let dir = inline.or_else(|| it.next().cloned()).ok_or_else(|| format!("{flag} needs a folder"))?;
|
||||
@@ -328,6 +371,16 @@ fn mcp(args: &[String], safe_mode: bool) -> Result<(), String> {
|
||||
if safe_mode && connect.is_some() {
|
||||
return Err("--safe-mode runs a headless session without plug-ins; a running app loads its own: start it with `vectorcraft --safe-mode --control <port>`".into());
|
||||
}
|
||||
let when_closed = match when_closed.as_deref() {
|
||||
None => None,
|
||||
Some(choice) => {
|
||||
let parsed = WhenAppClosed::parse(choice).ok_or_else(|| format!("--when-closed must be launch, headless or error, not `{choice}`"))?;
|
||||
if connect.is_some() || headless || safe_mode || allow_grants || !(read_roots.is_empty() && write_roots.is_empty()) {
|
||||
return Err("--when-closed is for the open window of plain `mcp`; --connect, --headless, --safe-mode, --allow-plugin-grants and the automation roots never use it".into());
|
||||
}
|
||||
Some(parsed)
|
||||
}
|
||||
};
|
||||
let read: Vec<&Path> = read_roots.iter().map(Path::new).collect();
|
||||
let write: Vec<&Path> = write_roots.iter().map(Path::new).collect();
|
||||
let roots = AutomationRoots::new(&read, &write)?;
|
||||
@@ -343,13 +396,18 @@ fn mcp(args: &[String], safe_mode: bool) -> Result<(), String> {
|
||||
} else if headless || safe_mode || allow_grants {
|
||||
Box::new(accepting_grants(with_stores(Headless::with_document()), allow_grants))
|
||||
} else if let Some(addr) = connect {
|
||||
eprintln!("{CONNECT_DEPRECATED}");
|
||||
// Explicit address: fail loudly if the app isn't there.
|
||||
let token = vectorcraft_mcp::control_token()?;
|
||||
Box::new(Remote::connect(&addr, &token).map_err(|e| format!("cannot connect to {addr}: {e}"))?)
|
||||
} else {
|
||||
// No token or no app listening: the headless session answers instead.
|
||||
match vectorcraft_mcp::control_token().ok().and_then(|token| Remote::connect(DEFAULT_ADDR, &token).ok()) {
|
||||
Some(r) => Box::new(r),
|
||||
match prefs_dir::prefs_dir() {
|
||||
Some(dir) => Box::new(LiveBackend::new(live_config(dir, when_closed))),
|
||||
// No settings folder (no home folder): no window can be found either, so `--when-closed error`
|
||||
// refuses rather than answering from a session the agent didn't ask for.
|
||||
None if when_closed == Some(WhenAppClosed::Error) => {
|
||||
return Err("VectorCraft's settings folder can't be found (no home folder), so its window can't be either: open VectorCraft, or run `mcp` without `--when-closed error`".into());
|
||||
}
|
||||
None => Box::new(with_stores(Headless::with_document())),
|
||||
}
|
||||
};
|
||||
@@ -616,6 +674,8 @@ fn thumbnail(args: &[String]) -> Result<(), String> {
|
||||
}
|
||||
}
|
||||
let [input, output] = <[&str; 2]>::try_from(files).map_err(|_| "thumbnail needs IN and OUT")?;
|
||||
// A DWG worker ends by then too, so the exit below leaves no conversion running.
|
||||
vectorcraft_engine::dwg::use_own_worker_for(THUMBNAIL_TIME);
|
||||
// The process ends when the time is up, wherever the work is: OUT is written whole or not at all.
|
||||
std::thread::spawn(|| {
|
||||
std::thread::sleep(THUMBNAIL_TIME);
|
||||
|
||||
@@ -836,3 +836,20 @@ fn runs_without_preferences_remember_nothing() {
|
||||
let r = run_in(&config, &[("pdf.preset.list", json!({}))]);
|
||||
assert!(r[0]["presets"].as_array().unwrap().iter().all(|p| p["builtIn"] == true));
|
||||
}
|
||||
|
||||
/// Plain `mcp` takes `--when-closed` for the open window only, and `--connect` still works for one
|
||||
/// release but says it is deprecated before it connects.
|
||||
#[test]
|
||||
fn mcp_when_closed_and_the_deprecated_connect() {
|
||||
let fails = |args: &[&str], why: &str| {
|
||||
let out = Command::new(crate::bin()).args(args).env("VECTORCRAFT_NO_PREFS", "1").stdin(Stdio::null()).output().unwrap();
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(!out.status.success() && err.contains(why), "{args:?}: {err}");
|
||||
err.into_owned()
|
||||
};
|
||||
fails(&["mcp", "--when-closed", "later"], "--when-closed must be launch, headless or error");
|
||||
fails(&["mcp", "--when-closed", "launch", "--headless"], "--when-closed is for the open window");
|
||||
fails(&["mcp", "--when-closed=error", "--connect", "127.0.0.1:1"], "--when-closed is for the open window");
|
||||
let err = fails(&["mcp", "--connect", "127.0.0.1:1"], "--connect is deprecated");
|
||||
assert!(err.contains("cannot connect") || err.contains("no control token"), "{err}");
|
||||
}
|
||||
@@ -378,3 +378,70 @@ fn convert_and_run_write_ait_templates() {
|
||||
assert!(!one.status.success());
|
||||
assert!(String::from_utf8_lossy(&one.stderr).contains("every artboard"), "{}", String::from_utf8_lossy(&one.stderr));
|
||||
}
|
||||
|
||||
/// A DWG drawing opens through a worker copy of the program, so a damaged one ends in an error from
|
||||
/// `info`, never in a crash. craft-dwg reads and writes DWG everywhere but wasm32 and FreeBSD on
|
||||
/// aarch64.
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
#[test]
|
||||
fn info_reads_a_dwg_and_a_damaged_one_is_an_error_not_a_crash() {
|
||||
let dxf = tmp("plan.dxf");
|
||||
make(&dxf, 120, 80);
|
||||
craft_dwg::allow_in_process();
|
||||
let dwg = craft_dwg::dxf_to_dwg_as(&std::fs::read(&dxf).unwrap(), "AC1018").unwrap();
|
||||
let good = tmp("plan.dwg");
|
||||
std::fs::write(&good, &dwg).unwrap();
|
||||
// The DWG comes in as the DXF it was written from.
|
||||
let (v, from) = (info(&good), info(&dxf));
|
||||
assert!(v["kinds"]["Path"].as_u64().is_some_and(|n| n > 0), "{v}");
|
||||
assert_eq!((&v["kinds"], &v["artboards"][0]["rect"]), (&from["kinds"], &from["artboards"][0]["rect"]), "{v}\n{from}");
|
||||
|
||||
let n = dwg.len();
|
||||
let mut damaged = vec![dwg[..n / 3].to_vec(), dwg[..2 * n / 3].to_vec(), dwg[..16].to_vec()];
|
||||
let mut overwritten = dwg.clone();
|
||||
overwritten[n / 2..(n / 2 + 64).min(n)].fill(0xFF);
|
||||
damaged.push(overwritten);
|
||||
let mut flipped = dwg.clone();
|
||||
flipped.iter_mut().skip(32).step_by(97).for_each(|b| *b ^= 0xA5);
|
||||
damaged.push(flipped);
|
||||
for (i, bytes) in damaged.iter().enumerate() {
|
||||
let path = tmp(&format!("damaged-{i}.dwg"));
|
||||
std::fs::write(&path, bytes).unwrap();
|
||||
let out = Command::new(crate::bin()).args(["info", &path]).output().unwrap();
|
||||
// A process ended by a signal has no exit code.
|
||||
assert!(out.status.code().is_some(), "damaged file {i}: {:?}", out.status);
|
||||
// The file cut to a third and the one cut to its header can't be read; the reader may
|
||||
// recover the others.
|
||||
if i == 0 || i == 2 {
|
||||
assert!(!out.status.success(), "damaged file {i} is refused: {}", String::from_utf8_lossy(&out.stdout));
|
||||
}
|
||||
if !out.status.success() {
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("DWG"), "damaged file {i}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A DWG worker started with a deadline (as `thumbnail` starts one) exits with code 1 once the
|
||||
/// deadline passes, even while it still waits for its drawing, and at once when it has already
|
||||
/// passed, so `thumbnail`'s exit leaves no conversion running.
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
#[test]
|
||||
fn a_dwg_worker_with_a_time_limit_exits_when_the_time_is_up() {
|
||||
let now = std::time::SystemTime::now();
|
||||
for until in [now + std::time::Duration::from_secs(1), now - std::time::Duration::from_secs(1)] {
|
||||
let millis = until.duration_since(std::time::UNIX_EPOCH).unwrap().as_millis().to_string();
|
||||
let mut worker = Command::new(crate::bin())
|
||||
.args(["--dwg-worker", "--dwg-worker-until", &millis])
|
||||
.stdin(std::process::Stdio::piped())
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
// Its input stays open, so the worker never gets the whole request.
|
||||
let input = worker.stdin.take();
|
||||
let out = worker.wait_with_output().unwrap();
|
||||
drop(input);
|
||||
assert_eq!(out.status.code(), Some(1), "{:?}", out.status);
|
||||
// It stops without answering, so no partial drawing reaches the caller.
|
||||
assert!(out.stdout.is_empty(), "{} bytes written", out.stdout.len());
|
||||
}
|
||||
}
|
||||
@@ -143,7 +143,8 @@ async fn run(host: Host, canvas: web_sys::HtmlCanvasElement, moving: Option<Movi
|
||||
let pen = host.pointers.borrow().pen();
|
||||
let spec = InstallSpec::new(ShellInfo::current(), Arc::new(SystemWindows)).pen(pen);
|
||||
// The interface faces the page serves are fetched by the stack as text needs them.
|
||||
let fonts = vectorcraft_ui_egui::ui_fonts().fetcher(Arc::new(crate::fonts::BrowserFetcher));
|
||||
let language = taken.borrow().as_ref().map_or_else(i18n::system_lang, VectorcraftApp::ui_language);
|
||||
let fonts = vectorcraft_ui_egui::configure_ui_fonts(ctx, language, Some(Arc::new(crate::fonts::BrowserFetcher)));
|
||||
embed::install(ctx, spec, &fonts).map_err(|e| e.to_string())?;
|
||||
egui_extras::install_image_loaders(ctx);
|
||||
let files = {
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
//! The agent settings of Preferences › AI Integrations, in `agents.json` in the settings folder
|
||||
//! (`prefs_dir.rs`). The desktop app writes them when they change (`prefs.agents`); `vectorcraft-cli`
|
||||
//! (which shares this file) reads them on every tool call of plain `mcp`, for the closed-app choice
|
||||
//! and the agent folders.
|
||||
|
||||
use std::io::Read as _;
|
||||
use std::path::Path;
|
||||
|
||||
use craft::automation::agents::AgentSettings;
|
||||
use serde_json::Value;
|
||||
|
||||
/// The file in the settings folder: `{"controlPort", "readRoot", "writeRoot", "whenAppClosed",
|
||||
/// "allowAgentControl"}`, the framework's `AgentSettings`.
|
||||
pub const SETTINGS_FILE: &str = "agents.json";
|
||||
|
||||
/// The largest settings file read; the settings are a few short strings.
|
||||
const MAX_SETTINGS_FILE: u64 = 64 * 1024;
|
||||
|
||||
/// The agent settings saved in `dir`; the defaults when nothing is saved or the file can't be read,
|
||||
/// so neither the app nor the CLI fails over them. One bad value resets only itself.
|
||||
pub fn read_settings(dir: &Path) -> AgentSettings {
|
||||
let Ok(file) = std::fs::File::open(dir.join(SETTINGS_FILE)) else { return AgentSettings::default() };
|
||||
let mut text = String::new();
|
||||
if file.take(MAX_SETTINGS_FILE + 1).read_to_string(&mut text).is_err() || text.len() as u64 > MAX_SETTINGS_FILE {
|
||||
return AgentSettings::default();
|
||||
}
|
||||
let Ok(Value::Object(saved)) = serde_json::from_str::<Value>(&text) else { return AgentSettings::default() };
|
||||
let mut settings = AgentSettings::default();
|
||||
for (key, value) in saved {
|
||||
let Ok(Value::Object(mut one)) = serde_json::to_value(&settings) else { continue };
|
||||
if one.contains_key(&key) {
|
||||
one.insert(key, value);
|
||||
if let Ok(next) = serde_json::from_value(Value::Object(one)) {
|
||||
settings = next;
|
||||
}
|
||||
}
|
||||
}
|
||||
settings
|
||||
}
|
||||
|
||||
/// Saves `settings` in `dir` (created when missing), replacing the file in one step, so a
|
||||
/// `vectorcraft-cli mcp` reading it at the same time sees the old or the new settings, never half.
|
||||
// The desktop writes the settings; `vectorcraft-cli` includes this file and only reads them.
|
||||
#[allow(dead_code)]
|
||||
pub fn write_settings(dir: &Path, settings: &AgentSettings) -> std::io::Result<()> {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let text = serde_json::to_vec_pretty(settings).map_err(std::io::Error::other)?;
|
||||
let partial = dir.join(format!("{SETTINGS_FILE}.{}.tmp", std::process::id()));
|
||||
std::fs::write(&partial, text)?;
|
||||
std::fs::rename(&partial, dir.join(SETTINGS_FILE)).inspect_err(|_| {
|
||||
let _ = std::fs::remove_file(&partial);
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use craft::automation::agents::WhenAppClosed;
|
||||
|
||||
// Settings saved by the app read back in the CLI, and a damaged file or value never fails it.
|
||||
#[test]
|
||||
fn saved_settings_read_back_and_bad_values_reset_alone() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
assert_eq!(read_settings(dir.path()), AgentSettings::default());
|
||||
let mut settings = AgentSettings::default();
|
||||
settings.read_root = "/in".into();
|
||||
settings.when_app_closed = WhenAppClosed::Headless;
|
||||
write_settings(dir.path(), &settings).unwrap();
|
||||
assert_eq!(read_settings(dir.path()), settings);
|
||||
std::fs::write(dir.path().join(SETTINGS_FILE), "not json").unwrap();
|
||||
assert_eq!(read_settings(dir.path()), AgentSettings::default());
|
||||
std::fs::write(dir.path().join(SETTINGS_FILE), r#"{"whenAppClosed": "error", "readRoot": 5, "unknown": true}"#).unwrap();
|
||||
let read = read_settings(dir.path());
|
||||
assert_eq!(read.when_app_closed, WhenAppClosed::Error);
|
||||
assert_eq!(read.read_root, "");
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@
|
||||
//! how the window's frames reach the display (`presentation`).
|
||||
#![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")]
|
||||
|
||||
mod agent_settings;
|
||||
mod automation_args;
|
||||
#[cfg(test)]
|
||||
mod build_channel;
|
||||
@@ -516,6 +517,30 @@ fn launch_arguments(nightly: bool, arguments: &[std::ffi::OsString]) -> Vec<Stri
|
||||
if nightly { arguments.iter().map(|a| a.to_string_lossy().into_owned()).collect() } else { std::env::args().skip(1).collect() }
|
||||
}
|
||||
|
||||
/// Agents in the open window (`vectorcraft_ui_egui::agents`): while the ArtCraft Launcher's switch
|
||||
/// names VectorCraft, the window serves agents on loopback and publishes the connection in its
|
||||
/// settings folder, where `vectorcraft-cli mcp` finds it. A connection file a crashed run left is
|
||||
/// removed first. With `--control` (`control_port`, served by `launched`) that channel serves the
|
||||
/// whole run and the link stays off. A nightly and a run without preferences have no link.
|
||||
fn agents_link(ctx: &egui::Context, control_port: Option<u16>, launched: Option<&Listening>) -> Option<vectorcraft_ui_egui::agents::Agents> {
|
||||
use craft::automation::agents::{AgentSwitch, remove_stale_connection};
|
||||
use vectorcraft_ui_egui::agents::{Agents, LAUNCHER_APP_ID, SaveFn};
|
||||
let dir = prefs_dir::prefs_dir()?;
|
||||
remove_stale_connection(&dir);
|
||||
let switch = AgentSwitch::watch(LAUNCHER_APP_ID, {
|
||||
let ctx = ctx.clone();
|
||||
move || ctx.request_repaint()
|
||||
});
|
||||
let save_dir = dir.clone();
|
||||
let save: SaveFn = Box::new(move |settings| {
|
||||
agent_settings::write_settings(&save_dir, settings).map_err(|e| format!("couldn't save the agent settings in {}: {e}", save_dir.display()))
|
||||
});
|
||||
let version = format!("VectorCraft {}", env!("VECTORCRAFT_BUILT_VERSION"));
|
||||
let agents = Agents::new(Some(dir.clone()), version, switch, agent_settings::read_settings(&dir), save);
|
||||
// The port it listens on (the one the system picked for `--control 0`), none when it couldn't.
|
||||
Some(if control_port.is_some() { agents.launched_with_control(launched.map(|l| l.addr.port())) } else { agents })
|
||||
}
|
||||
|
||||
/// The control channel's port, and the token's notice with the token itself.
|
||||
type ControlChannel = (Option<u16>, Option<(String, String)>);
|
||||
|
||||
@@ -573,10 +598,17 @@ fn finish_pending_update(nightly: bool) {
|
||||
}
|
||||
|
||||
fn main() -> std::process::ExitCode {
|
||||
// A copy of this program started with `--dwg-worker` alone converts one DWG drawing and exits,
|
||||
// before the launch profile, the logger or any window.
|
||||
if let Some(code) = vectorcraft_engine::dwg::serve_if_asked() {
|
||||
std::process::exit(code);
|
||||
}
|
||||
// The launch profile first: a nightly build self-isolates or uses the Launcher's profile here,
|
||||
// before the update helper, the logger, fonts or any saved state, and `--version` is answered
|
||||
// here too.
|
||||
let Some(arguments) = prepare_launch() else { return std::process::ExitCode::SUCCESS };
|
||||
// DWG drawings open through that copy, so a damaged file can't end this process.
|
||||
vectorcraft_engine::dwg::use_own_worker();
|
||||
let nightly = launch_profile::current().is_nightly();
|
||||
#[cfg(windows)]
|
||||
finish_pending_update(nightly);
|
||||
@@ -857,8 +889,6 @@ fn main() -> std::process::ExitCode {
|
||||
Some(pen) => spec.pen(pen),
|
||||
None => spec,
|
||||
};
|
||||
embed::install(ctx, spec, &vectorcraft_ui_egui::ui_fonts()).map_err(|e| e.to_string())?;
|
||||
egui_extras::install_image_loaders(ctx);
|
||||
let folders = settings.lock().get().ui.last_folders.clone();
|
||||
let wake = {
|
||||
let ctx = ctx.clone();
|
||||
@@ -875,7 +905,6 @@ fn main() -> std::process::ExitCode {
|
||||
.settings(Arc::new(settings.clone()))
|
||||
.files(files.clone())
|
||||
.build();
|
||||
host.clone().install(ctx);
|
||||
let mut session = Session::new();
|
||||
// The profiles loaded before come back before the preferences name any of them.
|
||||
prefs_dir::attach_profile_store(&mut session);
|
||||
@@ -900,12 +929,16 @@ fn main() -> std::process::ExitCode {
|
||||
prefs_dir::attach_proof_setups(&mut session);
|
||||
prefs_dir::attach_script_data(&mut session);
|
||||
let mut app = VectorcraftApp::new(session, services(winit_window.clone()));
|
||||
load_prefs(&mut app, &settings);
|
||||
let fonts = vectorcraft_ui_egui::configure_ui_fonts(ctx, app.ui_language(), None);
|
||||
embed::install(ctx, spec, &fonts).map_err(|e| e.to_string())?;
|
||||
egui_extras::install_image_loaders(ctx);
|
||||
host.clone().install(ctx);
|
||||
app.host = Arc::new(host);
|
||||
app.adopt_context(&cc.egui_ctx);
|
||||
// A nightly is updated by the Launcher: it never checks for a stable release, which
|
||||
// would install this program's own updater over the nightly build.
|
||||
app.set_startup_update_check(!nightly);
|
||||
load_prefs(&mut app, &settings);
|
||||
safe_mode::after_start(&mut app, stopped);
|
||||
// Loads started later (a preference change, the end of Safe Mode) are waited for,
|
||||
// after the launch's own.
|
||||
@@ -1048,6 +1081,12 @@ fn main() -> std::process::ExitCode {
|
||||
}
|
||||
}
|
||||
}
|
||||
if !nightly
|
||||
&& prefs_enabled()
|
||||
&& let Some(agents) = agents_link(&cc.egui_ctx, control_port, control_server.as_ref())
|
||||
{
|
||||
app = app.with_agents(agents);
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
open_documents::set_ui(&cc.egui_ctx);
|
||||
|
||||
@@ -180,7 +180,8 @@ mod system {
|
||||
let sockets = local_sockets();
|
||||
// A local PPD describes a local queue. With a remote scheduler the job goes to that server's queue,
|
||||
// so its sizes come from the server.
|
||||
if scheduler_is_local(named.as_deref(), &sockets, real_path) {
|
||||
let port = vectorcraft_ui_egui::print::ipp_port(std::env::var("IPP_PORT").ok().as_deref());
|
||||
if named_scheduler_is_local(named.as_deref(), port, |s| std::path::Path::new(s).exists(), &sockets, real_path) {
|
||||
const PPD_CAP: u64 = 16 << 20;
|
||||
let mut bytes = Vec::new();
|
||||
let read = std::fs::File::open(format!("/etc/cups/ppd/{printer}.ppd")).and_then(|f| f.take(PPD_CAP).read_to_end(&mut bytes));
|
||||
@@ -199,7 +200,6 @@ mod system {
|
||||
return papers;
|
||||
}
|
||||
// A queue whose server has no PPD either: its IPP `media-supported` attribute, from the scheduler CUPS uses.
|
||||
let port = vectorcraft_ui_egui::print::ipp_port(std::env::var("IPP_PORT").ok().as_deref());
|
||||
let server = ipp_server(named, |s| std::path::Path::new(s).exists(), real_path);
|
||||
let Some(uri) = vectorcraft_ui_egui::print::ipp_queue_uri(server.as_deref(), port, printer) else { return papers };
|
||||
use std::io::Write as _;
|
||||
@@ -286,10 +286,19 @@ mod system {
|
||||
}
|
||||
}
|
||||
/// The scheduler CUPS clients use: `CUPS_SERVER`, else the `ServerName` of `~/.cups/client.conf` or
|
||||
/// `/etc/cups/client.conf`; `None` for the local default. macOS does not read `ServerName`
|
||||
/// `/etc/cups/client.conf`; `None` when none is named, where CUPS uses its domain socket when one exists and
|
||||
/// `localhost` on `IPP_PORT` otherwise ([`named_scheduler_is_local`] resolves that case). macOS does not read `ServerName`
|
||||
/// (https://openprinting.github.io/cups/doc/man-client.conf.html), so there only `CUPS_SERVER` counts.
|
||||
/// A server named without a port gets the one `IPP_PORT` sets, so `localhost` with `IPP_PORT=8631` is a second
|
||||
/// scheduler rather than the local one.
|
||||
#[cfg(not(windows))]
|
||||
fn cups_server() -> Option<String> {
|
||||
let port = vectorcraft_ui_egui::print::ipp_port(std::env::var("IPP_PORT").ok().as_deref());
|
||||
named_cups_server().map(|server| vectorcraft_ui_egui::print::server_with_ipp_port(&server, port))
|
||||
}
|
||||
/// The scheduler `cups_server` names, as written.
|
||||
#[cfg(not(windows))]
|
||||
fn named_cups_server() -> Option<String> {
|
||||
if let Some(server) = std::env::var("CUPS_SERVER").ok().filter(|s| !s.trim().is_empty()) {
|
||||
return Some(server.trim().to_string());
|
||||
}
|
||||
@@ -304,8 +313,26 @@ mod system {
|
||||
client_conf_server_name(&text)
|
||||
})
|
||||
}
|
||||
/// Whether the scheduler CUPS uses runs on this machine, given the server `cups_server` names, the `IPP_PORT`
|
||||
/// port, whether a path exists, the local scheduler's domain `sockets` and a socket path's real path. With no
|
||||
/// server named, CUPS uses its domain socket when one exists, which is local, and otherwise `localhost` on the
|
||||
/// `IPP_PORT` port, which is local only on port 631.
|
||||
#[cfg(not(windows))]
|
||||
pub(super) fn named_scheduler_is_local(
|
||||
named: Option<&str>,
|
||||
port: Option<u16>,
|
||||
exists: impl Fn(&str) -> bool,
|
||||
sockets: &[String],
|
||||
resolve: impl Fn(&str) -> Option<String>,
|
||||
) -> bool {
|
||||
match named {
|
||||
Some(server) => scheduler_is_local(Some(server), sockets, resolve),
|
||||
None if CUPS_SOCKETS.iter().any(|s| exists(s)) => true,
|
||||
None => scheduler_is_local(Some(&vectorcraft_ui_egui::print::server_with_ipp_port("localhost", port)), sockets, resolve),
|
||||
}
|
||||
}
|
||||
/// Whether a scheduler named by `cups_server` runs on this machine: none named, one of the local scheduler's domain
|
||||
/// `sockets`, or `localhost`, `127.0.0.1` or `::1` with no port or port 631, each with an optional `/version=` suffix.
|
||||
/// `sockets`, or `localhost`, `127.0.0.1` or `[::1]` with no port or port 631, each with an optional `/version=` suffix.
|
||||
/// A loopback name on another port, or another socket path, is a second scheduler, whose queues the local PPD folder
|
||||
/// does not describe. `resolve` gives a socket path's real path, so a link to one of `sockets` counts as that socket.
|
||||
#[cfg(not(windows))]
|
||||
@@ -320,6 +347,10 @@ mod system {
|
||||
rest.split_once(']').map_or((rest, None), |(host, after)| (host, after.strip_prefix(':')))
|
||||
} else if server.matches(':').count() == 1 {
|
||||
server.split_once(':').map_or((server, None), |(host, port)| (host, Some(port)))
|
||||
} else if let Some((host, port)) = server.rsplit_once(':').filter(|(_, port)| port.starts_with(|c: char| c.is_ascii_digit())) {
|
||||
// CUPS (`cupsSetServer`) reads the digits after the last `:` of an unbracketed name as its port, so `::1` is
|
||||
// host `:` on port 1.
|
||||
(host, Some(port))
|
||||
} else {
|
||||
(server, None)
|
||||
};
|
||||
@@ -646,7 +677,21 @@ mod turn_tests {
|
||||
|
||||
#[cfg(all(test, not(windows)))]
|
||||
mod client_conf_tests {
|
||||
use super::system::{client_conf_server_name, cupsd_listen_sockets, ipp_server, scheduler_is_local};
|
||||
use super::system::{client_conf_server_name, cupsd_listen_sockets, ipp_server, named_scheduler_is_local, scheduler_is_local};
|
||||
|
||||
#[test]
|
||||
fn with_no_server_named_the_implicit_scheduler_decides_locality() {
|
||||
let none = |_: &str| false;
|
||||
let socket = |s: &str| s == "/run/cups/cups.sock";
|
||||
let real = |_: &str| None;
|
||||
let own = cupsd_listen_sockets("");
|
||||
assert!(!named_scheduler_is_local(None, Some(8631), none, &own, real), "localhost:8631 is a second scheduler");
|
||||
assert!(named_scheduler_is_local(None, Some(631), none, &own, real));
|
||||
assert!(named_scheduler_is_local(None, None, none, &own, real));
|
||||
assert!(named_scheduler_is_local(None, Some(8631), socket, &own, real), "CUPS's socket is the local scheduler");
|
||||
assert!(!named_scheduler_is_local(Some("print.example.com"), None, socket, &own, real));
|
||||
assert!(named_scheduler_is_local(Some("localhost:631"), Some(8631), none, &own, real));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_ipp_lookup_asks_a_socket_scheduler_only_when_it_is_cups_own() {
|
||||
@@ -700,7 +745,6 @@ mod client_conf_tests {
|
||||
Some("LocalHost:631"),
|
||||
Some("localhost:631"),
|
||||
Some("127.0.0.1:631"),
|
||||
Some("::1"),
|
||||
Some("[::1]:631"),
|
||||
Some("[::1]"),
|
||||
Some("localhost/version=1.1"),
|
||||
@@ -714,6 +758,7 @@ mod client_conf_tests {
|
||||
"192.0.2.7",
|
||||
"[2001:db8::1]:631",
|
||||
"2001:db8::1",
|
||||
"::1",
|
||||
"localhost.example.com",
|
||||
"print.example.com:631/version=1.1",
|
||||
"localhost:8631",
|
||||
@@ -727,6 +772,23 @@ mod client_conf_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_loopback_server_on_another_ipp_port_is_not_local() {
|
||||
use vectorcraft_ui_egui::print::server_with_ipp_port;
|
||||
let own = cupsd_listen_sockets("");
|
||||
let real = |_: &str| None;
|
||||
for named in ["localhost", "127.0.0.1", "[::1]", "localhost/version=1.1"] {
|
||||
assert!(!scheduler_is_local(Some(&server_with_ipp_port(named, Some(8631))), &own, real), "{named}");
|
||||
assert!(scheduler_is_local(Some(&server_with_ipp_port(named, Some(631))), &own, real), "{named}");
|
||||
}
|
||||
// CUPS reads an unbracketed `::1` as host `:` on port 1, so it is not the local scheduler on any `IPP_PORT`.
|
||||
for port in [None, Some(631), Some(8631)] {
|
||||
assert!(!scheduler_is_local(Some(&server_with_ipp_port("::1", port)), &own, real), "::1 with {port:?}");
|
||||
}
|
||||
assert!(scheduler_is_local(Some(&server_with_ipp_port("localhost:631", Some(8631))), &own, real), "a port in the server name wins");
|
||||
assert!(scheduler_is_local(Some(&server_with_ipp_port("/run/cups/cups.sock", Some(8631))), &own, real));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn server_name_drops_a_trailing_comment_and_keeps_an_escaped_hash() {
|
||||
assert_eq!(client_conf_server_name("ServerName print.example.com\n").as_deref(), Some("print.example.com"));
|
||||
|
||||
@@ -3,13 +3,14 @@ name = "vectorcraft-cad"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
description = "VectorCraft CAD interchange: DXF export through craft-dxf and an HP-GL/2 plot file reader and writer"
|
||||
description = "VectorCraft CAD interchange: DXF export through craft-dxf, DXF and DWG import, and an HP-GL/2 plot file reader and writer"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-dxf = { workspace = true }
|
||||
craft-dwg = { workspace = true }
|
||||
craft-plotter = { workspace = true }
|
||||
vectorcraft-geom = { workspace = true }
|
||||
vectorcraft-color = { workspace = true }
|
||||
@@ -21,6 +22,7 @@ vectorcraft-text = { workspace = true }
|
||||
kurbo = { workspace = true }
|
||||
image = { workspace = true }
|
||||
craft-image-codecs = { workspace = true }
|
||||
web-time = "1"
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
//! DWG drawings, read as DXF: `craft_dwg` converts the bytes and the DXF reader reads the result.
|
||||
//!
|
||||
//! The conversion runs in a child process once the program has called [`use_own_worker`] (and
|
||||
//! [`serve_if_asked`] first thing in `main`), so a damaged file that makes the DWG reader abort
|
||||
//! ends that process, not VectorCraft. Without a worker the conversion is refused, unless
|
||||
//! [`allow_in_process`] was called (tests). Web builds answer that DWG can't be read there.
|
||||
|
||||
use std::hash::BuildHasher;
|
||||
use std::sync::{Arc, LazyLock, Mutex, PoisonError, Weak};
|
||||
use std::time::Duration;
|
||||
|
||||
use web_time::Instant;
|
||||
|
||||
pub use craft_dwg::{WORKER_ARG, allow_in_process, use_own_worker};
|
||||
|
||||
/// The worker argument after [`WORKER_ARG`] that gives its deadline in milliseconds since the UNIX epoch
|
||||
/// ([`use_own_worker_for`]).
|
||||
const WORKER_UNTIL_ARG: &str = "--dwg-worker-until";
|
||||
|
||||
/// Serve one conversion and return the exit code if this process was started as a worker. A
|
||||
/// worker started by [`use_own_worker_for`] exits with code 1 once its time is up, wherever the
|
||||
/// conversion is.
|
||||
pub fn serve_if_asked() -> Option<i32> {
|
||||
let mut args = std::env::args_os().skip(1);
|
||||
if args.next()? != WORKER_ARG {
|
||||
return None;
|
||||
}
|
||||
if args.next().is_some_and(|a| a == WORKER_UNTIL_ARG)
|
||||
&& let Some(millis) = args.next().and_then(|s| s.to_str()?.parse::<u64>().ok())
|
||||
&& let Some(until) = std::time::UNIX_EPOCH.checked_add(std::time::Duration::from_millis(millis))
|
||||
{
|
||||
if until <= std::time::SystemTime::now() {
|
||||
return Some(1);
|
||||
}
|
||||
std::thread::spawn(move || {
|
||||
std::thread::sleep(until.duration_since(std::time::SystemTime::now()).unwrap_or_default());
|
||||
std::process::exit(1);
|
||||
});
|
||||
}
|
||||
craft_dwg::serve_if_asked()
|
||||
}
|
||||
|
||||
/// [`use_own_worker`], each worker exiting once `limit` from this call is up (a deadline passed to it
|
||||
/// in milliseconds since the UNIX epoch), however late it starts, so a program that ends after
|
||||
/// `limit` leaves no conversion running. If this program's path can't be found, or the deadline
|
||||
/// can't be written, the worker setting does not change. Web builds have no worker.
|
||||
pub fn use_own_worker_for(limit: std::time::Duration) {
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
if let Ok(program) = std::env::current_exe()
|
||||
&& let Some(until) = std::time::SystemTime::now().checked_add(limit).and_then(|until| until.duration_since(std::time::UNIX_EPOCH).ok())
|
||||
&& let Ok(millis) = u64::try_from(until.as_millis())
|
||||
{
|
||||
craft_dwg::worker::use_worker(program, vec![WORKER_ARG.into(), WORKER_UNTIL_ARG.into(), millis.to_string().into()]);
|
||||
}
|
||||
#[cfg(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64")))]
|
||||
let _ = limit;
|
||||
}
|
||||
|
||||
/// The largest DXF rendition kept for the next read of the same drawing (128 MiB).
|
||||
const MAX_KEPT: usize = 128 << 20;
|
||||
|
||||
/// Is `bytes` a DWG drawing (an `AC10nn` version code first)?
|
||||
pub fn is_dwg(bytes: &[u8]) -> bool {
|
||||
craft_dwg::is_dwg(bytes)
|
||||
}
|
||||
|
||||
/// A DWG drawing as DXF bytes, and what the conversion left out.
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub(crate) struct Converted {
|
||||
pub dxf: Vec<u8>,
|
||||
pub notes: Vec<String>,
|
||||
}
|
||||
|
||||
type Outcome = Result<Arc<Converted>, String>;
|
||||
|
||||
/// The outcome of the last drawing converted, by a hash of its bytes and its length, and the
|
||||
/// conversions a [`Held`] keeps. Open reads a drawing's layouts, draws a preview of each in its
|
||||
/// dialog and then opens it, and each of those reads the same file; a file the conversion refused
|
||||
/// (or whose worker stopped) is refused again without another conversion for [`FAILURE_KEPT`],
|
||||
/// after which the next read converts it again.
|
||||
#[derive(Default)]
|
||||
struct Kept {
|
||||
hasher: std::collections::hash_map::RandomState,
|
||||
/// The last outcome, by key, and when it was kept.
|
||||
last: Option<((u64, usize), Outcome, Instant)>,
|
||||
/// The conversions handed out by [`hold`], while a [`Held`] for each exists.
|
||||
held: Vec<((u64, usize), Weak<Converted>)>,
|
||||
}
|
||||
|
||||
impl Kept {
|
||||
fn key(&self, bytes: &[u8]) -> (u64, usize) {
|
||||
(self.hasher.hash_one(bytes), bytes.len())
|
||||
}
|
||||
|
||||
fn get(&self, key: (u64, usize), now: Instant) -> Option<Outcome> {
|
||||
let fresh = |outcome: &Outcome, at: &Instant| outcome.is_ok() || now.saturating_duration_since(*at) < FAILURE_KEPT;
|
||||
if let Some((_, outcome, _)) = self.last.as_ref().filter(|(k, outcome, at)| *k == key && fresh(outcome, at)) {
|
||||
return Some(outcome.clone());
|
||||
}
|
||||
self.held.iter().filter(|(k, _)| *k == key).find_map(|(_, c)| c.upgrade()).map(Ok)
|
||||
}
|
||||
|
||||
fn hold(&mut self, key: (u64, usize), converted: &Arc<Converted>) {
|
||||
self.held.retain(|(_, c)| c.strong_count() > 0);
|
||||
self.held.push((key, Arc::downgrade(converted)));
|
||||
}
|
||||
|
||||
fn keep(&mut self, key: (u64, usize), outcome: &Outcome, now: Instant) {
|
||||
if outcome.as_ref().is_ok_and(|c| c.dxf.len() > MAX_KEPT) {
|
||||
self.last = None;
|
||||
} else {
|
||||
self.last = Some((key, outcome.clone(), now));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How long a failed conversion is returned again for the same bytes. A worker can fail for a
|
||||
/// passing cause (memory, its deadline, a failed start), so a later read converts the drawing again.
|
||||
const FAILURE_KEPT: Duration = Duration::from_secs(10);
|
||||
|
||||
/// The conversion of `bytes` that `kept` holds, else `convert`'s, which `kept` then holds. The
|
||||
/// lock is not held while `convert` runs, so another drawing can be converted at the same time.
|
||||
fn through(kept: &Mutex<Kept>, bytes: &[u8], convert: impl FnOnce(&[u8]) -> Result<Converted, String>) -> Outcome {
|
||||
through_at(kept, bytes, &Instant::now, convert)
|
||||
}
|
||||
|
||||
/// [`through`] with the time read from `now`; an outcome is kept from when `convert` returned.
|
||||
fn through_at(kept: &Mutex<Kept>, bytes: &[u8], now: &dyn Fn() -> Instant, convert: impl FnOnce(&[u8]) -> Result<Converted, String>) -> Outcome {
|
||||
let key = {
|
||||
let kept = kept.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let key = kept.key(bytes);
|
||||
if let Some(outcome) = kept.get(key, now()) {
|
||||
return outcome;
|
||||
}
|
||||
key
|
||||
};
|
||||
let outcome = convert(bytes).map(Arc::new);
|
||||
kept.lock().unwrap_or_else(PoisonError::into_inner).keep(key, &outcome, now());
|
||||
outcome
|
||||
}
|
||||
|
||||
/// [`through`], and the conversion stays where `kept` finds it while the [`Held`] lasts.
|
||||
fn hold_in(kept: &Mutex<Kept>, bytes: &[u8], convert: impl FnOnce(&[u8]) -> Result<Converted, String>) -> Result<Held, String> {
|
||||
let converted = through(kept, bytes, convert)?;
|
||||
let mut kept = kept.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let key = kept.key(bytes);
|
||||
kept.hold(key, &converted);
|
||||
Ok(Held { _converted: converted })
|
||||
}
|
||||
|
||||
static KEPT: LazyLock<Mutex<Kept>> = LazyLock::new(Mutex::default);
|
||||
|
||||
/// `bytes` (a DWG drawing) as DXF, within craft-dwg's default limits (512 MiB of DWG, 1 GiB of DXF).
|
||||
pub(crate) fn to_dxf(bytes: &[u8]) -> Outcome {
|
||||
through(&KEPT, bytes, convert)
|
||||
}
|
||||
|
||||
/// A DWG drawing's conversion, kept for every read of the same bytes ([`crate::info`],
|
||||
/// [`crate::import`]) while this value exists, whatever other drawings are converted meanwhile and
|
||||
/// however large its DXF is.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Held {
|
||||
_converted: Arc<Converted>,
|
||||
}
|
||||
|
||||
/// Convert `bytes` (a DWG drawing), or take the conversion already kept, and keep it while the
|
||||
/// returned [`Held`] exists → the conversion's error when it fails.
|
||||
pub fn hold(bytes: &[u8]) -> Result<Held, String> {
|
||||
hold_in(&KEPT, bytes, convert)
|
||||
}
|
||||
|
||||
fn convert(bytes: &[u8]) -> Result<Converted, String> {
|
||||
let (dxf, notes) = craft_dwg::decode(bytes, craft_dwg::Limits::DEFAULT).map_err(|e| worded(&e))?;
|
||||
Ok(Converted { dxf, notes: notes.iter().map(|n| worded(n)).collect() })
|
||||
}
|
||||
|
||||
/// craft-dwg's message or note in VectorCraft's words: VectorCraft opens a DWG and never saves one.
|
||||
fn worded(message: &str) -> String {
|
||||
message
|
||||
.replace("accepted by this bridge", "VectorCraft opens")
|
||||
.replace("types this bridge can't preserve", "types VectorCraft can't read")
|
||||
.replace("; saving over the original file would lose them", "")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn counting<'a>(calls: &'a std::cell::Cell<usize>, dxf: &'a [u8]) -> impl FnOnce(&[u8]) -> Result<Converted, String> + 'a {
|
||||
move |_| {
|
||||
calls.set(calls.get() + 1);
|
||||
Ok(Converted { dxf: dxf.to_vec(), notes: vec![] })
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_drawing_is_converted_once_and_another_drawing_again() {
|
||||
let kept = Mutex::new(Kept::default());
|
||||
let calls = std::cell::Cell::new(0);
|
||||
let a = through(&kept, b"AC1015 one", counting(&calls, b"0\nEOF\n")).unwrap();
|
||||
let again = through(&kept, b"AC1015 one", counting(&calls, b"other")).unwrap();
|
||||
assert_eq!(calls.get(), 1);
|
||||
assert_eq!(again.dxf, a.dxf);
|
||||
through(&kept, b"AC1015 two", counting(&calls, b"0\nEOF\n")).unwrap();
|
||||
assert_eq!(calls.get(), 2);
|
||||
// The first drawing is no longer held.
|
||||
through(&kept, b"AC1015 one", counting(&calls, b"0\nEOF\n")).unwrap();
|
||||
assert_eq!(calls.get(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refused_file_is_refused_again_without_converting_and_an_oversized_rendition_is_not_kept() {
|
||||
let kept = Mutex::new(Kept::default());
|
||||
let calls = std::cell::Cell::new(0);
|
||||
let start = Instant::now();
|
||||
let at_start = move || start;
|
||||
assert_eq!(through_at(&kept, b"AC1015 bad", &at_start, |_| Err("DWG: no".to_string())).unwrap_err(), "DWG: no");
|
||||
let again = through_at(&kept, b"AC1015 bad", &at_start, counting(&calls, b"0\nEOF\n"));
|
||||
assert_eq!((again.unwrap_err().as_str(), calls.get()), ("DWG: no", 0));
|
||||
let big = vec![b' '; MAX_KEPT + 1];
|
||||
through(&kept, b"AC1015 big", counting(&calls, &big)).unwrap();
|
||||
through(&kept, b"AC1015 big", counting(&calls, &big)).unwrap();
|
||||
assert_eq!(calls.get(), 2, "a rendition over MAX_KEPT is converted again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_conversion_is_tried_again_once_its_time_is_up() {
|
||||
let kept = Mutex::new(Kept::default());
|
||||
let calls = std::cell::Cell::new(0);
|
||||
let clock = std::cell::Cell::new(Instant::now());
|
||||
let now = || clock.get();
|
||||
// The worker fails after running for longer than FAILURE_KEPT: the failure is kept from then.
|
||||
let slow_failure = |_: &[u8]| {
|
||||
clock.set(clock.get() + FAILURE_KEPT * 2);
|
||||
Err("DWG: stopped".to_string())
|
||||
};
|
||||
assert!(through_at(&kept, b"AC1015 bad", &now, slow_failure).is_err());
|
||||
clock.set(clock.get() + FAILURE_KEPT / 2);
|
||||
let within = through_at(&kept, b"AC1015 bad", &now, counting(&calls, b"0\nEOF\n"));
|
||||
assert_eq!((within.unwrap_err().as_str(), calls.get()), ("DWG: stopped", 0));
|
||||
clock.set(clock.get() + FAILURE_KEPT / 2);
|
||||
let later = through_at(&kept, b"AC1015 bad", &now, counting(&calls, b"0\nEOF\n"));
|
||||
assert_eq!((later.unwrap().dxf.as_slice(), calls.get()), (b"0\nEOF\n".as_slice(), 1));
|
||||
// A conversion that worked is kept whatever the time.
|
||||
clock.set(clock.get() + FAILURE_KEPT * 100);
|
||||
through_at(&kept, b"AC1015 bad", &now, counting(&calls, b"other")).unwrap();
|
||||
assert_eq!(calls.get(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_held_drawing_is_not_converted_again_until_its_hold_is_dropped() {
|
||||
let kept = Mutex::new(Kept::default());
|
||||
let calls = std::cell::Cell::new(0);
|
||||
let big = vec![b' '; MAX_KEPT + 1];
|
||||
let one = hold_in(&kept, b"AC1015 one", counting(&calls, b"0\nEOF\n")).unwrap();
|
||||
let large = hold_in(&kept, b"AC1015 big", counting(&calls, &big)).unwrap();
|
||||
through(&kept, b"AC1015 two", counting(&calls, b"0\nEOF\n")).unwrap();
|
||||
assert_eq!(calls.get(), 3);
|
||||
// Another drawing converted since, and a rendition over MAX_KEPT, are still found.
|
||||
through(&kept, b"AC1015 one", counting(&calls, b"other")).unwrap();
|
||||
assert_eq!(through(&kept, b"AC1015 big", counting(&calls, b"other")).unwrap().dxf.len(), big.len());
|
||||
assert_eq!(calls.get(), 3);
|
||||
drop((one, large));
|
||||
through(&kept, b"AC1015 one", counting(&calls, b"0\nEOF\n")).unwrap();
|
||||
through(&kept, b"AC1015 big", counting(&calls, &big)).unwrap();
|
||||
assert_eq!(calls.get(), 5, "a dropped hold no longer keeps its conversion");
|
||||
let refused = hold_in(&kept, b"AC1015 bad", |_| Err("DWG: no".to_string()));
|
||||
assert_eq!(refused.unwrap_err(), "DWG: no");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn messages_name_what_vectorcraft_does() {
|
||||
let m = worded("DWG: the file is 9.9 MB, larger than the 1.0 MB accepted by this bridge");
|
||||
assert_eq!(m, "DWG: the file is 9.9 MB, larger than the 1.0 MB VectorCraft opens");
|
||||
let n = worded("DWG: 2 objects of types this bridge can't preserve were left out (X × 2); saving over the original file would lose them");
|
||||
assert_eq!(n, "DWG: 2 objects of types VectorCraft can't read were left out (X × 2)");
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
//! DXF import: a DXF drawing (ASCII or binary) of any version as a document.
|
||||
//! DXF import: a DXF drawing (ASCII or binary) of any version as a document. A DWG drawing comes
|
||||
//! in the same way, converted to DXF first ([`crate::dwg`]).
|
||||
//!
|
||||
//! The drawing's model space (or a paper layout) comes in at a ratio (1 unit of the art = N
|
||||
//! drawing units; by default the drawing's own unit at 1:1) or fitted to an artboard, centred
|
||||
@@ -102,11 +103,24 @@ pub fn is_dxf(bytes: &[u8]) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// The tags of a DXF file and where it is damaged (DWG files are refused).
|
||||
fn tags(bytes: &[u8]) -> Result<(Vec<craft_dxf::Tag>, Option<String>), String> {
|
||||
if bytes.starts_with(b"AC10") || bytes.starts_with(b"AC1.") {
|
||||
return Err("this is a DWG drawing, which can't be read: save it from the CAD app as a DXF and open that".into());
|
||||
/// The tags of a DXF file, or of a DWG file converted to DXF ([`crate::dwg`]), and what the read
|
||||
/// left out: where the file is damaged, and what the DWG conversion couldn't read.
|
||||
fn tags(bytes: &[u8]) -> Result<(Vec<craft_dxf::Tag>, Vec<String>), String> {
|
||||
if crate::dwg::is_dwg(bytes) {
|
||||
let converted = crate::dwg::to_dxf(bytes)?;
|
||||
let (tags, mut notes) = dxf_tags(&converted.dxf)?;
|
||||
notes.extend(converted.notes.iter().cloned());
|
||||
return Ok((tags, notes));
|
||||
}
|
||||
// R1.x and R2.x drawings (MC0.0, AC1.2 to AC2.10), and an AC10 header with no version number.
|
||||
if [&b"AC10"[..], b"AC1.", b"AC2.", b"MC0."].iter().any(|magic| bytes.starts_with(magic)) {
|
||||
return Err("this DWG drawing's version can't be read: save it from the CAD app as a DXF and open that".into());
|
||||
}
|
||||
dxf_tags(bytes)
|
||||
}
|
||||
|
||||
/// The tags of a DXF file and where it is damaged.
|
||||
fn dxf_tags(bytes: &[u8]) -> Result<(Vec<craft_dxf::Tag>, Vec<String>), String> {
|
||||
let (tags, damaged) = craft_dxf::parse_recovering(bytes).map_err(|e| match e {
|
||||
craft_dxf::DxfError::TooLarge { .. } => "the drawing is too large to open".to_string(),
|
||||
_ if bytes.starts_with(reader::BINARY_SENTINEL) => "this binary DXF file is damaged or cut short".to_string(),
|
||||
@@ -115,7 +129,7 @@ fn tags(bytes: &[u8]) -> Result<(Vec<craft_dxf::Tag>, Option<String>), String> {
|
||||
if tags.is_empty() {
|
||||
return Err("not a DXF drawing".into());
|
||||
}
|
||||
Ok((tags, damaged.map(|line| format!("the file is damaged at line {line}: what follows is left out"))))
|
||||
Ok((tags, damaged.map(|line| format!("the file is damaged at line {line}: what follows is left out")).into_iter().collect()))
|
||||
}
|
||||
|
||||
/// The unit of `$INSUNITS` code `code` and the scale that shows the drawing 1:1 in it.
|
||||
@@ -182,7 +196,7 @@ pub fn info(bytes: &[u8]) -> Result<DxfInfo, String> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Import a DXF drawing with `o`.
|
||||
/// Import a DXF or DWG drawing with `o`.
|
||||
pub fn import(bytes: &[u8], o: &ImportOptions) -> Result<Imported, String> {
|
||||
let (w, h) = o.fit_to;
|
||||
if !(w > 0.0 && h > 0.0 && w.max(h) <= build::MAX_EXTENT) {
|
||||
@@ -193,7 +207,7 @@ pub fn import(bytes: &[u8], o: &ImportOptions) -> Result<Imported, String> {
|
||||
{
|
||||
return Err(format!("scale must be a number from {} to {}, not {s}", SCALE_RANGE.start(), SCALE_RANGE.end()));
|
||||
}
|
||||
let (tags, damaged) = tags(bytes)?;
|
||||
let (tags, notes) = tags(bytes)?;
|
||||
let d = reader::Drawing::read(craft_dxf::model::Document::read(&tags));
|
||||
if d.sections == 0 {
|
||||
return Err("not a DXF drawing".into());
|
||||
@@ -214,10 +228,12 @@ pub fn import(bytes: &[u8], o: &ImportOptions) -> Result<Imported, String> {
|
||||
};
|
||||
let (mut document, mut warnings) = build::Build::new(&d, o).run(layout, natural, ratio)?;
|
||||
document.units = if o.fit { unit } else { o.unit.unwrap_or(unit) };
|
||||
warnings.extend(damaged);
|
||||
warnings.extend(notes);
|
||||
document.limit_depth_noting(&mut warnings);
|
||||
Ok(Imported { document, warnings })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
#[cfg(test)]
|
||||
mod tests_dwg;
|
||||
@@ -0,0 +1,85 @@
|
||||
//! DWG import: drawings written as DXF, converted to DWG by craft-dwg's writer, come in as the DXF
|
||||
//! does; damaged files are errors. craft-dwg reads and writes DWG everywhere but wasm32 and FreeBSD
|
||||
//! on aarch64.
|
||||
#![cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, Unit};
|
||||
use vectorcraft_geom::{Rect, shapes};
|
||||
|
||||
use super::*;
|
||||
use crate::{DxfOptions, DxfVersion};
|
||||
|
||||
/// A drawing in millimetres on a layer named `Walls`: a red rectangle and a blue ellipse.
|
||||
fn dxf() -> Vec<u8> {
|
||||
let mut d = Document::new(200.0, 100.0);
|
||||
let layer = d.add_layer(Some("Walls"));
|
||||
let stroke = |c| Appearance::basic(Paint::None, Paint::solid(c), 1.0);
|
||||
let rect = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 110.0, 60.0)), stroke(Color::rgb(1.0, 0.0, 0.0)));
|
||||
let oval = Node::path(d.alloc_id(), shapes::ellipse(Rect::new(120.0, 20.0, 180.0, 80.0)), stroke(Color::rgb(0.0, 0.0, 1.0)));
|
||||
for n in [rect, oval] {
|
||||
d.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
}
|
||||
let o = DxfOptions { version: DxfVersion::R2000, region: d.artboards[0].rect, unit: Unit::Millimeters, ..DxfOptions::default() };
|
||||
crate::export(&d, &o).unwrap().bytes
|
||||
}
|
||||
|
||||
fn dwg() -> Vec<u8> {
|
||||
crate::dwg::allow_in_process();
|
||||
craft_dwg::dxf_to_dwg_as(&dxf(), "AC1018").unwrap()
|
||||
}
|
||||
|
||||
/// A layer's name, and each of its objects' bounds (to 0.01 pt) and stroke color.
|
||||
type LayerArt = (Option<String>, Vec<([i64; 4], Option<[u8; 4]>)>);
|
||||
|
||||
/// Each layer holding art.
|
||||
fn art(doc: &Document) -> Vec<LayerArt> {
|
||||
let r = |v: f64| (v * 100.0).round() as i64;
|
||||
doc.layers
|
||||
.iter()
|
||||
.filter_map(|layer| {
|
||||
let objects: Vec<_> = layer
|
||||
.children()?
|
||||
.iter()
|
||||
.map(|n| {
|
||||
let b = n.geometric_bounds().unwrap();
|
||||
let stroke = match n.appearance.stroke().map(|s| &s.paint) {
|
||||
Some(Paint::Solid { color, .. }) => Some(color.to_rgba8(1.0)),
|
||||
_ => None,
|
||||
};
|
||||
([r(b.x0), r(b.y0), r(b.x1), r(b.y1)], stroke)
|
||||
})
|
||||
.collect();
|
||||
(!objects.is_empty()).then(|| (layer.name.clone(), objects))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dwg_drawing_comes_in_as_its_dxf_does() {
|
||||
let (dxf, dwg) = (dxf(), dwg());
|
||||
assert!(crate::is_dwg(&dwg) && !crate::is_dwg(&dxf));
|
||||
let o = ImportOptions { unit: Some(Unit::Millimeters), scale: Some(1.0), ..ImportOptions::default() };
|
||||
let want = art(&import(&dxf, &o).unwrap().document);
|
||||
assert_eq!(want.len(), 1, "{want:?}");
|
||||
assert_eq!(want[0].0.as_deref(), Some("Walls"));
|
||||
assert_eq!(want[0].1.len(), 2, "{want:?}");
|
||||
assert_eq!(art(&import(&dwg, &o).unwrap().document), want);
|
||||
let i = info(&dwg).unwrap();
|
||||
assert_eq!((i.units.as_str(), i.unit, i.layouts.first().map(String::as_str)), ("Millimeters", Unit::Millimeters, Some("Model")));
|
||||
assert!(i.layers.iter().any(|l| l == "Walls"), "{i:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_damaged_dwg_is_an_error_that_names_dwg() {
|
||||
let mut cut = dwg();
|
||||
cut.truncate(cut.len() / 3);
|
||||
let e = import(&cut, &ImportOptions::default()).unwrap_err();
|
||||
assert!(e.contains("DWG"), "{e}");
|
||||
assert!(info(&cut).is_err());
|
||||
// An R1.x or R2.x drawing is refused without reading it.
|
||||
for old in [&b"AC1.50\x00\x00\x00\x00"[..], b"AC2.10\x00\x00\x00\x00", b"MC0.0\x00\x00\x00\x00"] {
|
||||
let e = import(old, &ImportOptions::default()).unwrap_err();
|
||||
assert!(e.contains("version can't be read") && e.contains("DXF"), "{e}");
|
||||
}
|
||||
}
|
||||
@@ -14,16 +14,19 @@
|
||||
//! clipping) is approximated or left out, and each such loss comes back as a warning.
|
||||
//!
|
||||
//! [`import()`] reads a DXF drawing (ASCII or binary, any version) into a document: see [`import`].
|
||||
//! It reads a DWG drawing too, converted to DXF by [`dwg`].
|
||||
//! [`hpgl::import`] reads an HP-GL plotter file, and [`hpgl::export`] writes one: see [`hpgl`].
|
||||
//!
|
||||
//! - `aci`: the 256-colour index palette and the nearest index of a colour.
|
||||
//! - The ASCII file around those entities is written by `craft_dxf::drawing`.
|
||||
//! - `scene`: the document walk that turns objects into entities.
|
||||
//! - `import`: the reader, entities to art, blocks to symbols.
|
||||
//! - `dwg`: DWG drawings converted to DXF by craft-dwg, in a child process on desktop builds.
|
||||
//! - `hpgl`: the HP-GL reader, the pen's moves to paths, and the writer, paths to pen moves.
|
||||
#![doc(test(attr(deny(unsafe_code))))]
|
||||
|
||||
mod aci;
|
||||
pub mod dwg;
|
||||
#[cfg(test)]
|
||||
mod expansion_test;
|
||||
pub mod hpgl;
|
||||
@@ -34,6 +37,7 @@ use vectorcraft_doc::{Document, Unit};
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
pub use aci::{aci_rgb, nearest_aci};
|
||||
pub use dwg::is_dwg;
|
||||
pub use import::{DxfInfo, ImportOptions, Imported, import, info, is_dxf};
|
||||
|
||||
/// How deep symbols, blocks and brush art may nest in one another (deeper art is left out).
|
||||
|
||||
@@ -36,14 +36,14 @@ pub fn convert_radii_relative(live: &mut LiveShape, relative: bool) {
|
||||
let was_relative = live.radii_relative();
|
||||
let base = match live {
|
||||
LiveShape::Rectangle { w, h, .. } => shapes::rectangle(Rect::new(0.0, 0.0, *w, *h)),
|
||||
LiveShape::Polygon { .. } => live.polygon_outline(),
|
||||
LiveShape::Polygon { .. } | LiveShape::Star { .. } => live.polygon_outline(),
|
||||
LiveShape::Path { base, .. } => base.clone(),
|
||||
LiveShape::Ellipse { .. } | LiveShape::Line { .. } => return,
|
||||
};
|
||||
let corners = path_corners(&base);
|
||||
let radii: &mut [f64] = match live {
|
||||
LiveShape::Rectangle { radii, .. } => radii,
|
||||
LiveShape::Polygon { radii, .. } => radii,
|
||||
LiveShape::Polygon { radii, .. } | LiveShape::Star { radii, .. } => radii,
|
||||
LiveShape::Path { radii, .. } => radii,
|
||||
LiveShape::Ellipse { .. } | LiveShape::Line { .. } => return,
|
||||
};
|
||||
@@ -62,6 +62,7 @@ pub fn convert_radii_relative(live: &mut LiveShape, relative: bool) {
|
||||
match live {
|
||||
LiveShape::Rectangle { radii_relative: rel, .. }
|
||||
| LiveShape::Polygon { radii_relative: rel, .. }
|
||||
| LiveShape::Star { radii_relative: rel, .. }
|
||||
| LiveShape::Path { radii_relative: rel, .. } => {
|
||||
*rel = relative;
|
||||
}
|
||||
@@ -99,7 +100,7 @@ impl<'a> LiveCorners<'a> {
|
||||
let LiveShape::Rectangle { w, h, radii, kinds, radii_relative, xf } = l.folded() else { return None };
|
||||
(Cow::Owned(shapes::rectangle(Rect::new(0.0, 0.0, w, h))), xf, radii.to_vec(), kinds.to_vec(), radii_relative)
|
||||
}
|
||||
Some(l @ LiveShape::Polygon { radii, kinds, radii_relative, .. }) => {
|
||||
Some(l @ (LiveShape::Polygon { radii, kinds, radii_relative, .. } | LiveShape::Star { radii, kinds, radii_relative, .. })) => {
|
||||
(Cow::Owned(l.polygon_outline()), Affine::IDENTITY, radii.clone(), kinds.clone(), *radii_relative)
|
||||
}
|
||||
Some(LiveShape::Path { base, radii, kinds, radii_relative }) => {
|
||||
@@ -258,6 +259,14 @@ pub fn set_corners(path: &mut PathData, live: &mut Option<Box<LiveShape>>, corne
|
||||
edit(&outline, relative, radii, kinds, corners, radius, kind);
|
||||
trim_vec_radii(radii, kinds);
|
||||
}
|
||||
LiveShape::Star { r1, r2, points, xf, radii, kinds, .. } => {
|
||||
let outline = shapes::star(Point::ZERO, *r1, *r2, *points, 0.0).transformed(*xf);
|
||||
let n = 2 * *points as usize;
|
||||
radii.resize(n, 0.0);
|
||||
kinds.resize(n, CornerKind::Round);
|
||||
edit(&outline, relative, radii, kinds, corners, radius, kind);
|
||||
trim_vec_radii(radii, kinds);
|
||||
}
|
||||
LiveShape::Path { base, radii, kinds, .. } => {
|
||||
let n = base.anchor_count();
|
||||
radii.resize(n, 0.0);
|
||||
@@ -277,6 +286,57 @@ pub fn set_corners(path: &mut PathData, live: &mut Option<Box<LiveShape>>, corne
|
||||
}
|
||||
}
|
||||
|
||||
/// Edit the anchors of the uncut outline that `anchors` (of the path as drawn) come from, while the
|
||||
/// path keeps its Live Corners: `edit` gets the outline in document space and those of its anchors,
|
||||
/// and the path is cut again with the same radii and kinds. A live rectangle or polygon becomes a
|
||||
/// [`LiveShape::Path`] with that outline. [`LiveCorners::sources`] before and after the edit map
|
||||
/// the anchors as drawn to the corners they come from.
|
||||
/// Returns `None`, leaving the path unchanged, when the path has no live shape or
|
||||
/// no cut corner, or is a rectangle sheared or scaled unevenly.
|
||||
pub fn edit_corner_anchors(
|
||||
path: &mut PathData,
|
||||
live: &mut Option<Box<LiveShape>>,
|
||||
anchors: &BTreeSet<AnchorRef>,
|
||||
edit: impl FnOnce(&mut PathData, &BTreeSet<AnchorRef>),
|
||||
) -> Option<()> {
|
||||
live.as_ref()?;
|
||||
if let Some(LiveShape::Rectangle { xf, .. }) = live.as_deref() {
|
||||
let [a, b, c, d, _, _] = xf.as_coeffs();
|
||||
let scale = (a * a + b * b).max(c * c + d * d).max(1e-12);
|
||||
if ((a * a + b * b) - (c * c + d * d)).abs() > 1e-9 * scale || (a * c + b * d).abs() > 1e-9 * scale {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let (mut base, moved, radii, kinds, relative) = {
|
||||
let lc = LiveCorners::new(path, live.as_deref())?;
|
||||
if !lc.drawn.iter().any(|r| *r > 0.0) {
|
||||
return None;
|
||||
}
|
||||
let moved: BTreeSet<usize> = anchors.iter().filter_map(|(si, ai)| lc.sources.get(*si)?.get(*ai).copied()).collect();
|
||||
if moved.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut radii = lc.radii.clone();
|
||||
radii.resize(lc.base.anchor_count(), 0.0);
|
||||
(lc.base.transformed(lc.xf), moved, radii, lc.kinds.clone(), lc.relative)
|
||||
};
|
||||
let mut on_base = BTreeSet::new();
|
||||
let mut k = 0;
|
||||
for (si, sp) in base.subpaths.iter().enumerate() {
|
||||
for ai in 0..sp.anchors.len() {
|
||||
if moved.contains(&k) {
|
||||
on_base.insert((si, ai));
|
||||
}
|
||||
k += 1;
|
||||
}
|
||||
}
|
||||
edit(&mut base, &on_base);
|
||||
let l = LiveShape::Path { base, radii, kinds, radii_relative: relative };
|
||||
*path = l.to_path();
|
||||
*live = Some(Box::new(l));
|
||||
Some(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -239,6 +239,52 @@ impl Document {
|
||||
round_json_paths(brushes, &round);
|
||||
}
|
||||
}
|
||||
|
||||
/// Make every live star a plain path of the outline it draws, for a save that versions before
|
||||
/// live stars read: in the art of the layers, symbols, graph designs, pattern swatches and the
|
||||
/// pattern definition that pattern editing's Cancel puts back (opacity-mask art included), and
|
||||
/// in the brush definitions.
|
||||
pub fn live_stars_to_paths(&mut self) {
|
||||
let is_star = |n: &Node| matches!(n.live_shape(), Some(LiveShape::Star { .. }));
|
||||
let mut plain = |n: &mut Node| {
|
||||
if let NodeKind::Path { live, .. } = &mut n.kind
|
||||
&& matches!(live.as_deref(), Some(LiveShape::Star { .. }))
|
||||
{
|
||||
*live = None;
|
||||
}
|
||||
};
|
||||
let roots = self
|
||||
.layers
|
||||
.iter_mut()
|
||||
.chain(self.symbols.iter_mut().map(|s| &mut s.art))
|
||||
.chain(self.graph_designs.iter_mut().map(|g| &mut g.art))
|
||||
.chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut()))
|
||||
.chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut()));
|
||||
for root in roots {
|
||||
edit_branches_where(root, &is_star, &mut plain);
|
||||
}
|
||||
if let Some(brushes) = self.unknown.get_mut("brushes") {
|
||||
json_stars_to_paths(brushes);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Take `live` off every serialized path object (`type: "path"`) in `v` whose live shape is a
|
||||
/// star.
|
||||
fn json_stars_to_paths(v: &mut serde_json::Value) {
|
||||
use serde_json::Value;
|
||||
match v {
|
||||
Value::Object(o) => {
|
||||
if o.get("type").and_then(Value::as_str) == Some("path")
|
||||
&& o.get("live").and_then(|l| l.get("shape")).and_then(Value::as_str) == Some("star")
|
||||
{
|
||||
o.remove("live");
|
||||
}
|
||||
o.values_mut().for_each(json_stars_to_paths);
|
||||
}
|
||||
Value::Array(a) => a.iter_mut().for_each(json_stars_to_paths),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Change with `f` the nodes of `n`'s tree (opacity-mask art included) for which `wants` holds,
|
||||
|
||||
@@ -103,7 +103,7 @@ pub use appearance::{
|
||||
};
|
||||
pub use assets::ExportAsset;
|
||||
pub use compound_shape::ShapeMode;
|
||||
pub use corners::LiveCorners;
|
||||
pub use corners::{LiveCorners, edit_corner_anchors};
|
||||
pub use depth::{MAX_DEPTH, MAX_SYMBOL_NODES};
|
||||
pub use graph::{
|
||||
ColumnDesign, ColumnType, DEFAULT_FILLED_LINE_WIDTH, FILLED_LINE_OUTLINE_WIDTH, Fractions, GraphDesign, GraphKind, GraphSpec, LabelRows,
|
||||
|
||||
@@ -46,11 +46,32 @@ pub enum LiveShape {
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
radii_relative: bool,
|
||||
},
|
||||
/// A star drawn with the Star tool or `shape.star`: its point count and radii stay editable.
|
||||
Star {
|
||||
/// Outer radius: centre to each tip.
|
||||
r1: f64,
|
||||
/// Inner radius: centre to each point between two tips.
|
||||
r2: f64,
|
||||
/// 2–1000, as [`LiveShape::set_points`] gives it; a file's count is clamped when read.
|
||||
#[serde(deserialize_with = "de_points")]
|
||||
points: u32,
|
||||
/// Maps the star (centred on the origin, first tip straight up) into the document.
|
||||
xf: Affine,
|
||||
/// Corner radii in document units, by vertex from the first tip clockwise, tips and inner
|
||||
/// points alternating (none: sharp).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
radii: Vec<f64>,
|
||||
/// Corner kinds, in the same order (none: round).
|
||||
#[serde(default, skip_serializing_if = "all_round")]
|
||||
kinds: Vec<CornerKind>,
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
radii_relative: bool,
|
||||
},
|
||||
Line {
|
||||
a: Point,
|
||||
b: Point,
|
||||
},
|
||||
/// Any other path whose corners Live Corners cut (a star, a pen path): it keeps its uncut
|
||||
/// Any other path whose corners Live Corners cut (a pen path, a star saved as a path): it keeps its uncut
|
||||
/// outline so the corners stay editable. Without a cut corner it is a plain path again.
|
||||
Path {
|
||||
/// The path with its corners uncut, in the document.
|
||||
@@ -74,9 +95,10 @@ fn is_false(b: &bool) -> bool {
|
||||
impl LiveShape {
|
||||
pub fn radii_relative(&self) -> bool {
|
||||
match self {
|
||||
LiveShape::Rectangle { radii_relative, .. } | LiveShape::Polygon { radii_relative, .. } | LiveShape::Path { radii_relative, .. } => {
|
||||
*radii_relative
|
||||
}
|
||||
LiveShape::Rectangle { radii_relative, .. }
|
||||
| LiveShape::Polygon { radii_relative, .. }
|
||||
| LiveShape::Star { radii_relative, .. }
|
||||
| LiveShape::Path { radii_relative, .. } => *radii_relative,
|
||||
LiveShape::Ellipse { .. } | LiveShape::Line { .. } => false,
|
||||
}
|
||||
}
|
||||
@@ -86,6 +108,7 @@ impl LiveShape {
|
||||
LiveShape::Rectangle { .. } => "Rectangle",
|
||||
LiveShape::Ellipse { .. } => "Ellipse",
|
||||
LiveShape::Polygon { .. } => "Polygon",
|
||||
LiveShape::Star { .. } => "Star",
|
||||
LiveShape::Line { .. } => "Line",
|
||||
LiveShape::Path { .. } => "Path",
|
||||
}
|
||||
@@ -100,7 +123,7 @@ impl LiveShape {
|
||||
shapes::rectangle_with_corners(Rect::new(0.0, 0.0, *w, *h), radii, *kinds).transformed(*xf)
|
||||
}
|
||||
LiveShape::Ellipse { w, h, pie, xf } => shapes::ellipse_pie(Rect::new(0.0, 0.0, *w, *h), pie.0, pie.1).transformed(*xf),
|
||||
LiveShape::Polygon { radii, kinds, radii_relative, .. } => {
|
||||
LiveShape::Polygon { radii, kinds, radii_relative, .. } | LiveShape::Star { radii, kinds, radii_relative, .. } => {
|
||||
let outline = self.polygon_outline();
|
||||
let radii = crate::corners::resolve_stored_radii(&outline, radii, *radii_relative);
|
||||
cut_corners(&outline, &radii, kinds).0
|
||||
@@ -112,10 +135,12 @@ impl LiveShape {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// A polygon's outline with its corners uncut, in the document (empty for other shapes).
|
||||
/// A polygon's or star's outline with its corners uncut, in the document (empty for other
|
||||
/// shapes).
|
||||
pub fn polygon_outline(&self) -> PathData {
|
||||
match self {
|
||||
LiveShape::Polygon { radius, sides, xf, .. } => shapes::polygon(Point::ZERO, *radius, *sides, 0.0).transformed(*xf),
|
||||
LiveShape::Star { r1, r2, points, xf, .. } => shapes::star(Point::ZERO, *r1, *r2, *points, 0.0).transformed(*xf),
|
||||
_ => PathData::default(),
|
||||
}
|
||||
}
|
||||
@@ -123,16 +148,38 @@ impl LiveShape {
|
||||
/// the corners past the old last one are sharp.
|
||||
pub fn set_sides(&mut self, n: u64) {
|
||||
let LiveShape::Polygon { sides, radii, kinds, .. } = self else { return };
|
||||
let old = *sides as usize;
|
||||
*sides = n.clamp(3, 1000) as u32;
|
||||
fn spread<T: Copy + PartialEq + Default>(v: &mut Vec<T>, n: usize) {
|
||||
match v.first().copied() {
|
||||
Some(x) if v.iter().all(|y| *y == x) => *v = vec![x; n],
|
||||
Some(_) => v.resize(n, T::default()),
|
||||
None => {}
|
||||
}
|
||||
spread(radii, old, *sides as usize);
|
||||
spread(kinds, old, *sides as usize);
|
||||
}
|
||||
/// A star's point count. None for other shapes.
|
||||
pub fn star_points(&self) -> Option<u32> {
|
||||
let LiveShape::Star { points, .. } = self else { return None };
|
||||
Some(*points)
|
||||
}
|
||||
/// Give a star `n` points (2–1000). Its corners keep the radius and kind they shared; else the
|
||||
/// corners past the old last one are sharp.
|
||||
pub fn set_points(&mut self, n: u64) {
|
||||
let LiveShape::Star { points, radii, kinds, .. } = self else { return };
|
||||
let old = 2 * *points as usize;
|
||||
*points = n.clamp(2, 1000) as u32;
|
||||
spread(radii, old, 2 * *points as usize);
|
||||
spread(kinds, old, 2 * *points as usize);
|
||||
}
|
||||
/// A star's ratio: its inner radius over its outer radius (0 when the outer radius is 0). None
|
||||
/// for other shapes.
|
||||
pub fn star_ratio(&self) -> Option<f64> {
|
||||
let LiveShape::Star { r1, r2, .. } = self else { return None };
|
||||
Some(if *r1 > 0.0 { *r2 / *r1 } else { 0.0 })
|
||||
}
|
||||
/// Give a star the ratio `ratio` (0 to 1, see [`LiveShape::star_ratio`]), keeping its outer
|
||||
/// radius. Nothing changes for other shapes or a ratio outside 0 to 1.
|
||||
pub fn set_star_ratio(&mut self, ratio: f64) {
|
||||
let LiveShape::Star { r1, r2, .. } = self else { return };
|
||||
if ratio.is_finite() && (0.0..=1.0).contains(&ratio) {
|
||||
*r2 = *r1 * ratio;
|
||||
}
|
||||
spread(radii, *sides as usize);
|
||||
spread(kinds, *sides as usize);
|
||||
}
|
||||
/// A polygon's radius in the document, centre to vertex: its own radius by the mean scale of
|
||||
/// `xf` (exact while its sides are equal). None for other shapes.
|
||||
@@ -151,7 +198,9 @@ impl LiveShape {
|
||||
/// ellipse drawn level reads 0°, as does a polygon drawn with its first vertex straight up. None for
|
||||
/// other shapes.
|
||||
pub fn shape_angle(&self) -> Option<f64> {
|
||||
let (LiveShape::Rectangle { .. } | LiveShape::Ellipse { .. } | LiveShape::Polygon { .. }) = self else { return None };
|
||||
let (LiveShape::Rectangle { .. } | LiveShape::Ellipse { .. } | LiveShape::Polygon { .. } | LiveShape::Star { .. }) = self else {
|
||||
return None;
|
||||
};
|
||||
// No −0° or 360° from rounding: a shape drawn level reads 0°.
|
||||
let a = (-self.angle_deg()).rem_euclid(360.0);
|
||||
Some(if a > 360.0 - 1e-9 { 0.0 } else { a + 0.0 })
|
||||
@@ -168,7 +217,7 @@ impl LiveShape {
|
||||
let angle = angle.rem_euclid(360.0);
|
||||
let (xf, local) = match self {
|
||||
LiveShape::Rectangle { w, h, xf, .. } | LiveShape::Ellipse { w, h, xf, .. } => (xf, Point::new(*w / 2.0, *h / 2.0)),
|
||||
LiveShape::Polygon { xf, .. } => (xf, Point::ZERO),
|
||||
LiveShape::Polygon { xf, .. } | LiveShape::Star { xf, .. } => (xf, Point::ZERO),
|
||||
LiveShape::Line { .. } | LiveShape::Path { .. } => return,
|
||||
};
|
||||
let center = *xf * local;
|
||||
@@ -274,7 +323,7 @@ impl LiveShape {
|
||||
*xf = a * *xf;
|
||||
false
|
||||
}
|
||||
LiveShape::Polygon { xf, radii, radii_relative, .. } => {
|
||||
LiveShape::Polygon { xf, radii, radii_relative, .. } | LiveShape::Star { xf, radii, radii_relative, .. } => {
|
||||
*xf = a * *xf;
|
||||
scale_radii(radii, a, *radii_relative)
|
||||
}
|
||||
@@ -326,7 +375,7 @@ impl LiveShape {
|
||||
let relative = self.radii_relative();
|
||||
let radii: &mut [f64] = match self {
|
||||
LiveShape::Rectangle { radii, .. } => radii,
|
||||
LiveShape::Polygon { radii, .. } | LiveShape::Path { radii, .. } => radii,
|
||||
LiveShape::Polygon { radii, .. } | LiveShape::Star { radii, .. } | LiveShape::Path { radii, .. } => radii,
|
||||
LiveShape::Ellipse { .. } | LiveShape::Line { .. } => return false,
|
||||
};
|
||||
if relative || !radii.iter().any(|r| *r > 0.0) || k <= 1e-12 {
|
||||
@@ -338,7 +387,7 @@ impl LiveShape {
|
||||
/// Rotation angle of the live shape in degrees, clockwise on the page (y points down).
|
||||
pub fn angle_deg(&self) -> f64 {
|
||||
match self {
|
||||
LiveShape::Rectangle { xf, .. } | LiveShape::Ellipse { xf, .. } | LiveShape::Polygon { xf, .. } => {
|
||||
LiveShape::Rectangle { xf, .. } | LiveShape::Ellipse { xf, .. } | LiveShape::Polygon { xf, .. } | LiveShape::Star { xf, .. } => {
|
||||
let c = xf.as_coeffs();
|
||||
c[1].atan2(c[0]).to_degrees()
|
||||
}
|
||||
@@ -358,6 +407,28 @@ fn de_sides<'de, D: serde::Deserializer<'de>>(d: D) -> Result<u32, D::Error> {
|
||||
u32::deserialize(d).map(|n| n.clamp(3, 1000))
|
||||
}
|
||||
|
||||
/// A star's point count read from a file, clamped as the commands clamp it (see [`de_sides`]).
|
||||
fn de_points<'de, D: serde::Deserializer<'de>>(d: D) -> Result<u32, D::Error> {
|
||||
u32::deserialize(d).map(|n| n.clamp(2, 1000))
|
||||
}
|
||||
|
||||
/// Give a corner list for `old` corners `n` entries: one value all `old` corners shared fills it;
|
||||
/// otherwise entries past its end are the default (sharp, round) and entries past `n` go. A list
|
||||
/// shorter than `old` holds the default for its missing corners, so it is shared only when that
|
||||
/// default is; entries of a longer list past `old` name no corner and go first. An empty list
|
||||
/// stays empty.
|
||||
fn spread<T: Copy + PartialEq + Default>(v: &mut Vec<T>, old: usize, n: usize) {
|
||||
v.truncate(old);
|
||||
if !v.is_empty() && v.len() < old {
|
||||
v.resize(old, T::default());
|
||||
}
|
||||
match v.first().copied() {
|
||||
Some(x) if v.iter().all(|y| *y == x) => *v = vec![x; n],
|
||||
Some(_) => v.resize(n, T::default()),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `a` only moves (no rotation, scale, shear or reflection).
|
||||
pub(super) fn moves_only(a: Affine) -> bool {
|
||||
let [a0, a1, a2, a3, _, _] = a.as_coeffs();
|
||||
|
||||
@@ -158,6 +158,77 @@ fn a_polygon_from_a_file_has_3_to_1000_sides() {
|
||||
assert_eq!(huge.polygon_outline().anchor_count(), 1000);
|
||||
}
|
||||
|
||||
/// A live star saves and reads back as it was, and one read from a file has 2 to 1000 points.
|
||||
#[test]
|
||||
fn a_star_round_trips_and_its_file_count_is_clamped() {
|
||||
let star = LiveShape::Star {
|
||||
r1: 40.0,
|
||||
r2: 20.0,
|
||||
points: 7,
|
||||
xf: Affine::translate((10.0, 20.0)),
|
||||
radii: vec![2.0; 14],
|
||||
kinds: vec![],
|
||||
radii_relative: false,
|
||||
};
|
||||
let text = serde_json::to_string(&star).unwrap();
|
||||
assert_eq!(serde_json::from_str::<LiveShape>(&text).unwrap(), star);
|
||||
assert_eq!(star.label(), "Star");
|
||||
let read = |points: u64| {
|
||||
let json = serde_json::json!({"shape": "star", "r1": 10.0, "r2": 5.0, "points": points, "xf": [1, 0, 0, 1, 0, 0]});
|
||||
serde_json::from_value::<LiveShape>(json).unwrap().star_points().unwrap()
|
||||
};
|
||||
assert_eq!([0, 2, 5, 1000, 4_000_000_000].map(read), [2, 2, 5, 1000, 1000]);
|
||||
// Points and ratio change; the outer radius stays.
|
||||
let mut s = star.clone();
|
||||
s.set_points(9);
|
||||
s.set_star_ratio(0.25);
|
||||
assert!(matches!(&s, LiveShape::Star { r1, r2, points: 9, radii, .. } if *r1 == 40.0 && *r2 == 10.0 && *radii == vec![2.0; 18]));
|
||||
assert_eq!(s.polygon_outline().anchor_count(), 18);
|
||||
}
|
||||
|
||||
/// A corner list shorter than the corners holds sharp corners past its end, so a new point or
|
||||
/// side count does not give those corners the first corner's radius.
|
||||
#[test]
|
||||
fn a_short_corner_list_keeps_its_missing_corners_sharp() {
|
||||
let mut star = LiveShape::Star { r1: 40.0, r2: 20.0, points: 5, xf: Affine::IDENTITY, radii: vec![2.0], kinds: vec![], radii_relative: false };
|
||||
star.set_points(6);
|
||||
let mut want = vec![0.0; 12];
|
||||
want[0] = 2.0;
|
||||
assert!(matches!(&star, LiveShape::Star { radii, .. } if *radii == want), "{star:?}");
|
||||
let mut polygon = LiveShape::Polygon { radius: 40.0, sides: 5, xf: Affine::IDENTITY, radii: vec![2.0], kinds: vec![], radii_relative: false };
|
||||
polygon.set_sides(6);
|
||||
let mut want = vec![0.0; 6];
|
||||
want[0] = 2.0;
|
||||
assert!(matches!(&polygon, LiveShape::Polygon { radii, .. } if *radii == want), "{polygon:?}");
|
||||
}
|
||||
|
||||
/// A corner list longer than the corners drops its entries past the old last corner, so the
|
||||
/// corners a new point count adds are sharp and keep the default kind.
|
||||
#[test]
|
||||
fn a_long_corner_list_drops_its_entries_past_the_corners() {
|
||||
let mut radii = vec![0.0; 12];
|
||||
radii[0] = 2.0;
|
||||
radii[10] = 7.0;
|
||||
radii[11] = 7.0;
|
||||
let mut kinds = vec![CornerKind::Round; 12];
|
||||
kinds[0] = CornerKind::Chamfer;
|
||||
kinds[10] = CornerKind::Chamfer;
|
||||
kinds[11] = CornerKind::Chamfer;
|
||||
let mut star = LiveShape::Star { r1: 40.0, r2: 20.0, points: 5, xf: Affine::IDENTITY, radii, kinds, radii_relative: false };
|
||||
star.set_points(6);
|
||||
let mut want_radii = vec![0.0; 12];
|
||||
want_radii[0] = 2.0;
|
||||
let mut want_kinds = vec![CornerKind::Round; 12];
|
||||
want_kinds[0] = CornerKind::Chamfer;
|
||||
assert!(matches!(&star, LiveShape::Star { radii, .. } if *radii == want_radii), "{star:?}");
|
||||
assert!(matches!(&star, LiveShape::Star { kinds, .. } if *kinds == want_kinds), "{star:?}");
|
||||
// A complete list that all corners share still fills the new corners.
|
||||
let mut star =
|
||||
LiveShape::Star { r1: 40.0, r2: 20.0, points: 5, xf: Affine::IDENTITY, radii: vec![3.0; 10], kinds: vec![], radii_relative: false };
|
||||
star.set_points(6);
|
||||
assert!(matches!(&star, LiveShape::Star { radii, .. } if *radii == vec![3.0; 12]), "{star:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_polygon_reports_and_takes_its_radius_angle_and_equal_sides() {
|
||||
let close = |a: f64, b: f64| (a - b).abs() < 1e-9;
|
||||
|
||||
@@ -24,6 +24,11 @@ craft-svg = { workspace = true, features = ["tree-render"] }
|
||||
# The number lists of filter attributes, read as usvg reads them (MIT OR Apache-2.0; already used by usvg).
|
||||
svgtypes = "0.16"
|
||||
serde_json = { workspace = true }
|
||||
# Render Settings › Rendered: the 3D effects' solids drawn as an image with depth and shadow maps.
|
||||
craft-raster3d = { workspace = true }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
craft-raster3d = { workspace = true, features = ["parallel"] }
|
||||
|
||||
[dev-dependencies]
|
||||
vectorcraft-color = { workspace = true }
|
||||
|
||||
@@ -354,7 +354,7 @@ fn bake_object(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
if let Some(m) = crate::addons::halftone::halftone_art(d, n) {
|
||||
return Some(bake_pieces(d, m));
|
||||
}
|
||||
if let Some(m) = crate::revolve_art_in(Some(d), n).or_else(|| crate::solid_art_in(Some(d), n)) {
|
||||
if let Some(m) = crate::revolve_art_drawn_in(Some(d), n).or_else(|| crate::solid_art_drawn_in(Some(d), n)) {
|
||||
let m = evaluate_container(Some(d), &m).unwrap_or(m);
|
||||
return Some(bake_pieces(d, m));
|
||||
}
|
||||
@@ -871,7 +871,7 @@ pub type StrokeArt<'a> = &'a mut dyn FnMut(&mut Document, &PathData, FillRule, &
|
||||
/// without transparency or effects of its own takes `n`'s place itself. Hidden fills, strokes and
|
||||
/// effects are dropped. `None` for other kinds of objects.
|
||||
pub fn expand_leaf(d: &mut Document, n: &Node, stroke_art: StrokeArt) -> Option<Node> {
|
||||
if let Some(m) = crate::revolve::expand_revolve_art_in(Some(d), n).or_else(|| crate::solid_art_in(Some(d), n)) {
|
||||
if let Some(m) = crate::revolve::expand_revolve_art_in(Some(d), n).or_else(|| crate::solid_art_drawn_in(Some(d), n)) {
|
||||
let m = evaluate_container(Some(d), &m).unwrap_or(m);
|
||||
return Some(bake_pieces(d, m));
|
||||
}
|
||||
@@ -963,7 +963,7 @@ pub fn bake_type_appearance(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
|
||||
/// [`bake_appearance`], or with `outline_strokes` false [`bake_type_appearance`].
|
||||
fn bake_appearance_as(doc: Option<&Document>, n: &Node, outline_strokes: bool) -> Option<Node> {
|
||||
if let Some(m) = crate::revolve_art_in(doc, n).or_else(|| crate::solid_art_in(doc, n)) {
|
||||
if let Some(m) = crate::revolve_art_drawn_in(doc, n).or_else(|| crate::solid_art_drawn_in(doc, n)) {
|
||||
return Some(m);
|
||||
}
|
||||
if !matches!(n.kind, NodeKind::Path { clipping: false, guide: false, .. } | NodeKind::Compound { .. }) {
|
||||
|
||||
@@ -241,28 +241,28 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
REVOLVE,
|
||||
"Revolve…",
|
||||
&["Effect", "3D and Materials"],
|
||||
"{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true: solid, closing circular ends of open profiles and a partial sweep's cut sides; false: hollow), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), material: object ({roughness: 1, metallic: 0}; the 3D and Materials panel's Materials › Properties: roughness: 0..1 (1; lower values give a smaller, brighter highlight), metallic: 0..1 (0; higher values tint the reflected light with the paint and darken the diffuse light); a key left out keeps its default, and any other key or value is an error; the default draws as before), render: object ({mode: shaded}; mode: shaded|wireframe, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.",
|
||||
"{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; in the shaded faces the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it; with render mode rendered, every light with an intensity above 0 casts shadows in the image), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true: solid, closing circular ends of open profiles and a partial sweep's cut sides; false: hollow), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), material: object ({roughness: 1, metallic: 0}; the 3D and Materials panel's Materials › Properties: roughness: 0..1 (1; lower values give a smaller, brighter highlight), metallic: 0..1 (0; higher values tint the reflected light with the paint and darken the diffuse light); a key left out keeps its default, and any other key or value is an error; the default draws as before), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own; rendered draws the solid as one image with a depth buffer, lit by every light; with shadow on, every light with an intensity above 0 casts shadows on the solid and on the shadow plane in the image, and with it off none does; it draws the shaded faces when the image can't be made or a later geometry effect reshapes paths but leaves images unchanged; quality: low|medium|high (medium; 1, 2 x 2 or 3 x 3 samples a pixel, VectorCraft's own), resolution: null or ppi 1..2400 (null: Document Raster Effects Settings), background: transparent|white (transparent); any other key or value is an error)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.",
|
||||
json!({"angle":360.0,"offset":0.0,"edge":"left","rotationX":0.0,"rotationY":0.0,"rotationZ":0.0,"perspectiveAngle":0.0,"segments":64,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"cap":true,"expandVisibleOnly":true,"graphics":[],"material":{"roughness":1.0,"metallic":0.0},"render":{"mode":"shaded"}}),
|
||||
),
|
||||
g(
|
||||
EXTRUDE,
|
||||
"Extrude & Bevel…",
|
||||
&["Effect", "3D and Materials"],
|
||||
"{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none; or custom, a bevel of the user's own drawn by bevelProfile), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), bevelName: string (a custom bevel's name), bevelProfile: [[x, y], …] (a custom bevel's 2 to 64 points, shares 0..1 of the width and height from [0, 0] at the cap's edge to [1, 1] at the side wall, joined by straight lines; effect.apply and effect.setParams also take bevel {custom: name}, a bevel of the bevels file (threeD.bevels.list), and store it as bevel custom with its bevelName and bevelProfile), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps and the side, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back|side (front; the back reads left to right as seen from behind; side is the walls and bevels), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on the side from the middle of the side unrolled flat, along the outline, clockwise from its top), y: pt (0; on the side from the front toward the back), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the face and clipped to it: on a cap of a solid object only, and on the side of a solid or hollow object wrapped around it and drawn only where its outside faces the viewer), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).",
|
||||
"{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none; or custom, a bevel of the user's own drawn by bevelProfile), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), bevelName: string (a custom bevel's name), bevelProfile: [[x, y], …] (a custom bevel's 2 to 64 points, shares 0..1 of the width and height from [0, 0] at the cap's edge to [1, 1] at the side wall, joined by straight lines; effect.apply and effect.setParams also take bevel {custom: name}, a bevel of the bevels file (threeD.bevels.list), and store it as bevel custom with its bevelName and bevelProfile), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; in the shaded faces the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it; with render mode rendered, every light with an intensity above 0 casts shadows in the image), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps and the side, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back|side (front; the back reads left to right as seen from behind; side is the walls and bevels), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on the side from the middle of the side unrolled flat, along the outline, clockwise from its top), y: pt (0; on the side from the front toward the back), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the face and clipped to it: on a cap of a solid object only, and on the side of a solid or hollow object wrapped around it and drawn only where its outside faces the viewer), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, quality, resolution and background, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).",
|
||||
json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"material":{"roughness":1.0,"metallic":0.0},"render":{"mode":"shaded"}}),
|
||||
),
|
||||
g(
|
||||
INFLATE,
|
||||
"Inflate…",
|
||||
&["Effect", "3D and Materials"],
|
||||
"{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the puffed front and back, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind and takes graphics with bothSides and cap on), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the art's plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); carried straight out from the art's plane onto the puffed face, twist and taper turning and shrinking the back's with it, shaded with the surface and drawn only where its outside faces the viewer), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Painted with the top fill (else the top stroke).",
|
||||
"{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; in the shaded faces the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it; with render mode rendered, every light with an intensity above 0 casts shadows in the image), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the puffed front and back, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind and takes graphics with bothSides and cap on), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the art's plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); carried straight out from the art's plane onto the puffed face, twist and taper turning and shrinking the back's with it, shaded with the surface and drawn only where its outside faces the viewer), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, quality, resolution and background, as Revolve's)}. Painted with the top fill (else the top stroke).",
|
||||
json!({"depth":0.0,"twist":0.0,"taper":100.0,"cap":true,"volume":50.0,"bothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"material":{"roughness":1.0,"metallic":0.0},"render":{"mode":"shaded"}}),
|
||||
),
|
||||
g(
|
||||
ROTATE,
|
||||
"Rotate…",
|
||||
&["Effect", "3D and Materials"],
|
||||
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.",
|
||||
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; in the shaded faces the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it; with render mode rendered, every light with an intensity above 0 casts shadows in the image), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, quality, resolution and background, as Revolve's)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.",
|
||||
json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"material":{"roughness":1.0,"metallic":0.0},"render":{"mode":"shaded"}}),
|
||||
),
|
||||
g(
|
||||
|
||||
@@ -96,16 +96,19 @@ pub use reshape::{
|
||||
has_transform_options, image_paint, instance_as_art, needs_outline, outer_effects, outline_art, outline_text, paint_type_piece, reshape,
|
||||
};
|
||||
pub use revolve::{
|
||||
CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in,
|
||||
CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_drawn_in, revolve_art_in, revolve_options, validate_revolve,
|
||||
validate_revolve_in,
|
||||
};
|
||||
pub use solids::rendered::{rendered_warning, three_d_bounds_art_in};
|
||||
pub use solids::{
|
||||
BEVEL_NAME, BEVEL_PROFILE, CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MATERIAL, MAX_GRAPHICS, MappedGraphic,
|
||||
MeshGraphics, RENDER, RENDER_MODES, ROTATE, ROTATE_SURFACES, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES,
|
||||
classic_extrude_options, classic_shading, extrude_options, graphic_bounds, graphic_frame, graphic_symbols, has_solid, inflate_options,
|
||||
is_classic_three_d, is_three_d, mapped_graphics, mesh_graphics_art, missing_symbol, names_graphic_symbol, rename_graphic_symbol,
|
||||
rename_graphic_symbol_in, renders_wireframe, solid_art, solid_art_in, takes_graphics, three_d_meshes, three_d_meshes_in, three_d_meshes_of,
|
||||
three_d_meshes_of_in, three_d_params_as, three_d_wireframe_in, validate_solid, validate_solid_in, validate_three_d, validate_three_d_at,
|
||||
validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options, with_graphic,
|
||||
MeshGraphics, RENDER, RENDER_BACKGROUNDS, RENDER_MODES, RENDER_QUALITIES, ROTATE, ROTATE_SURFACES, ROTATION_PRESETS, RenderSettings,
|
||||
SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, classic_shading, extrude_options, graphic_bounds, graphic_frame,
|
||||
graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d, mapped_graphics, mesh_graphics_art, missing_symbol,
|
||||
names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, render_settings, rendered, renders_image, renders_wireframe, solid_art,
|
||||
solid_art_drawn_in, solid_art_in, takes_graphics, three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as,
|
||||
three_d_wireframe_in, validate_solid, validate_solid_in, validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in,
|
||||
validate_three_d_params, view_options, with_graphic,
|
||||
};
|
||||
pub use solids::{
|
||||
GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, exports_three_d, graphic_fitting_scale,
|
||||
|
||||
@@ -172,8 +172,9 @@ fn highlight_fills(highlight: vectorcraft_three_d::Highlight) -> Vec<AppearanceI
|
||||
}
|
||||
|
||||
/// The path that screens `highlight` over a face of outline `path` closed by a seam `seam` wide:
|
||||
/// the highlight's fills ([`highlight_fills`]) on the face and its seam ([`seamed_fill`], else the
|
||||
/// outline alone). `None` without a highlight or when it holds no light.
|
||||
/// the highlight's fills ([`highlight_fills`]) on the face and its seam ([`seamed_fill`], or for a
|
||||
/// curved face [`curved_seamed_fill`]; else the outline alone). Each fill covers the face and its
|
||||
/// seam once. `None` without a highlight or when it holds no light.
|
||||
pub(crate) fn highlight_over(
|
||||
id: vectorcraft_doc::NodeId,
|
||||
path: &vectorcraft_geom::PathData,
|
||||
@@ -184,10 +185,126 @@ pub(crate) fn highlight_over(
|
||||
if items.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let shape = seamed_fill(path, seam).unwrap_or_else(|| path.clone());
|
||||
let shape = seamed_fill(path, seam).or_else(|| curved_seamed_fill(path, seam)).unwrap_or_else(|| path.clone());
|
||||
Some(vectorcraft_doc::Node::path(id, shape, vectorcraft_doc::Appearance { items, ..Default::default() }))
|
||||
}
|
||||
|
||||
/// How far, in points, a curved face's flattened outline may stray from its curves when
|
||||
/// [`curved_seamed_fill`] tests it.
|
||||
const HIGHLIGHT_FLATNESS: f64 = 0.05;
|
||||
|
||||
/// Curved face `path` and its round seam `seam` wide as one path to fill: the [`footprint`] of the
|
||||
/// curves themselves, as the face's clip is. `None` unless `path` has curves and its outline,
|
||||
/// flattened to within [`HIGHLIGHT_FLATNESS`], is a polygon [`seamed_fill`] takes: one closed
|
||||
/// contour of up to [`SEAMED_FILL_EDGES`] edges that does not fold over itself. Flattening stops
|
||||
/// once the outline passes that many edges.
|
||||
fn curved_seamed_fill(path: &vectorcraft_geom::PathData, seam: f64) -> Option<vectorcraft_geom::PathData> {
|
||||
use kurbo::{ParamCurve, ParamCurveExtrema, PathEl, PathSeg, Shape};
|
||||
let bez = path.to_bezpath();
|
||||
let elements = bez.elements();
|
||||
if elements.len() > SEAMED_FILL_EDGES + 2 || !elements.iter().any(|el| matches!(el, PathEl::QuadTo(..) | PathEl::CurveTo(..))) {
|
||||
return None;
|
||||
}
|
||||
let segments: Vec<PathSeg> = bez.segments().collect();
|
||||
for (i, a) in segments.iter().enumerate() {
|
||||
let b = &segments[(i + 1) % segments.len()];
|
||||
if matches!((a, b), (PathSeg::Line(_), PathSeg::Line(_))) {
|
||||
continue;
|
||||
}
|
||||
let controls = |s: &PathSeg| match s {
|
||||
PathSeg::Line(s) => vec![s.p0, s.p1],
|
||||
PathSeg::Quad(s) => vec![s.p0, s.p1, s.p2],
|
||||
PathSeg::Cubic(s) => vec![s.p0, s.p1, s.p2, s.p3],
|
||||
};
|
||||
let seam = a.end();
|
||||
let directions: Vec<_> = controls(a)
|
||||
.into_iter()
|
||||
.map(|p| p - seam)
|
||||
.chain(controls(b).into_iter().map(|p| seam - p))
|
||||
.filter(|v| v.hypot() > 0.0)
|
||||
.map(|v| v / v.hypot())
|
||||
.collect();
|
||||
let separated = directions.iter().any(|a| {
|
||||
directions.iter().any(|b| {
|
||||
let axis = *a + *b;
|
||||
directions.iter().all(|v| axis.dot(*v) > 1e-12)
|
||||
})
|
||||
});
|
||||
if !separated {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let mut flat = vectorcraft_geom::BezPath::new();
|
||||
let mut overflow = false;
|
||||
let mut last = kurbo::Point::ZERO;
|
||||
for el in elements {
|
||||
if overflow {
|
||||
break;
|
||||
}
|
||||
let from = last;
|
||||
let controls = match el {
|
||||
PathEl::QuadTo(a, b) => Some([from, *a, *b, *b]),
|
||||
PathEl::CurveTo(a, b, c) => Some([from, *a, *b, *c]),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(controls) = controls {
|
||||
let length: f64 = controls.windows(2).map(|pair| pair[0].distance(pair[1])).sum();
|
||||
if !length.is_finite()
|
||||
|| length > HIGHLIGHT_FLATNESS * vectorcraft_geom::MAX_FLATTEN_PER_CURVE.powi(2)
|
||||
|| controls.iter().any(|p| !(p.x.abs() <= vectorcraft_geom::MAX_FLATTEN_LENGTH && p.y.abs() <= vectorcraft_geom::MAX_FLATTEN_LENGTH))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
}
|
||||
last = match el {
|
||||
PathEl::MoveTo(p) | PathEl::LineTo(p) | PathEl::QuadTo(_, p) | PathEl::CurveTo(_, _, p) => *p,
|
||||
PathEl::ClosePath => last,
|
||||
};
|
||||
let curve = match el {
|
||||
PathEl::QuadTo(a, b) => Some(PathSeg::Quad(kurbo::QuadBez::new(from, *a, *b))),
|
||||
PathEl::CurveTo(a, b, c) => Some(PathSeg::Cubic(kurbo::CubicBez::new(from, *a, *b, *c))),
|
||||
_ => None,
|
||||
};
|
||||
// Each curve piece is monotonic in both coordinates before flattening.
|
||||
let pieces = curve.map_or_else(
|
||||
|| vec![(from, *el)],
|
||||
|curve| {
|
||||
curve
|
||||
.extrema_ranges()
|
||||
.into_iter()
|
||||
.map(|range| {
|
||||
let piece = curve.subsegment(range);
|
||||
(piece.start(), piece.as_path_el())
|
||||
})
|
||||
.collect()
|
||||
},
|
||||
);
|
||||
for (from, el) in pieces {
|
||||
if overflow {
|
||||
break;
|
||||
}
|
||||
let start = [PathEl::MoveTo(from)].into_iter().filter(|_| !matches!(el, PathEl::MoveTo(_)));
|
||||
let mut skip = usize::from(!matches!(el, PathEl::MoveTo(_)));
|
||||
vectorcraft_geom::flatten(start.chain([el]), HIGHLIGHT_FLATNESS, |e| {
|
||||
if skip > 0 {
|
||||
skip -= 1;
|
||||
} else if flat.elements().len() > SEAMED_FILL_EDGES + 2 {
|
||||
overflow = true;
|
||||
} else {
|
||||
flat.push(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
if overflow {
|
||||
return None;
|
||||
}
|
||||
// Each flattened edge may be HIGHLIGHT_FLATNESS away from its curve.
|
||||
seamed_fill_with_clearance(&vectorcraft_geom::PathData::from_bezpath(&flat), seam, 2.0 * HIGHLIGHT_FLATNESS)?;
|
||||
let fill = footprint(&bez, seam);
|
||||
(fill.bounding_box().is_finite() && fill.area().abs() >= bez.area().abs()).then(|| vectorcraft_geom::PathData::from_bezpath(&fill))
|
||||
}
|
||||
|
||||
/// `face`, the art of a face of outline `path` closed by a seam `seam` wide, with `highlight`
|
||||
/// screened over it: a group of the face and the highlight's path on the face and its seam
|
||||
/// ([`highlight_over`]). An opacity mask on the face moves to the group, so it covers the
|
||||
@@ -255,7 +372,13 @@ const SEAMED_FILL_EDGES: usize = 256;
|
||||
/// a seam that is not a positive finite width, or a footprint with no finite bounds or less area
|
||||
/// than the facet.
|
||||
pub(crate) fn seamed_fill(path: &vectorcraft_geom::PathData, seam: f64) -> Option<vectorcraft_geom::PathData> {
|
||||
use kurbo::{PathEl, Point, Shape};
|
||||
seamed_fill_with_clearance(path, seam, 0.0)
|
||||
}
|
||||
|
||||
/// [`seamed_fill`], also `None` when two edges that are not neighbors come within `clearance` of
|
||||
/// each other.
|
||||
fn seamed_fill_with_clearance(path: &vectorcraft_geom::PathData, seam: f64, clearance: f64) -> Option<vectorcraft_geom::PathData> {
|
||||
use kurbo::{Line, ParamCurveNearest, PathEl, Point, Shape};
|
||||
if !(seam.is_finite() && seam > 0.0) {
|
||||
return None;
|
||||
}
|
||||
@@ -294,6 +417,19 @@ pub(crate) fn seamed_fill(path: &vectorcraft_geom::PathData, seam: f64) -> Optio
|
||||
if touch(a, b, c, d) {
|
||||
return None;
|
||||
}
|
||||
if clearance > 0.0 {
|
||||
let ab = Line::new(a, b);
|
||||
let cd = Line::new(c, d);
|
||||
let distance_sq = ab
|
||||
.nearest(c, 1e-6)
|
||||
.distance_sq
|
||||
.min(ab.nearest(d, 1e-6).distance_sq)
|
||||
.min(cd.nearest(a, 1e-6).distance_sq)
|
||||
.min(cd.nearest(b, 1e-6).distance_sq);
|
||||
if distance_sq <= clearance * clearance {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let fill = footprint(&bez, seam);
|
||||
@@ -690,6 +826,98 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A material's highlight over a curved face reaches its seam too, as the face's clip does,
|
||||
/// wound one way so a nonzero fill screens it once. A curved face that folds over itself keeps
|
||||
/// its outline alone.
|
||||
#[test]
|
||||
fn a_highlight_over_a_curved_face_covers_its_seam() {
|
||||
use kurbo::Shape;
|
||||
let circle = vectorcraft_geom::shapes::ellipse(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
let highlight = vectorcraft_three_d::Highlight { flat: [0.5; 3], ramp: None };
|
||||
for path in [circle.clone(), vectorcraft_geom::PathData::from_bezpath(&circle.to_bezpath().reverse_subpaths())] {
|
||||
let Some(over) = highlight_over(vectorcraft_doc::NodeId(1), &path, 1.0, Some(highlight)) else { panic!("a highlight") };
|
||||
let Some(shape) = over.path_data() else { panic!("a path") };
|
||||
let bez = shape.to_bezpath();
|
||||
assert_ne!(bez.winding(Point::new(5.0, 10.4)), 0, "the seam past the bottom edge");
|
||||
assert_ne!(bez.winding(Point::new(5.0, 5.0)), 0, "the face");
|
||||
assert_eq!(bez.winding(Point::new(5.0, 11.0)), 0, "past the seam");
|
||||
assert!(bez.elements().iter().filter(|el| matches!(el, kurbo::PathEl::MoveTo(_))).count() >= 2);
|
||||
}
|
||||
// A curved face that folds over itself keeps its outline alone, as its own nonzero fill.
|
||||
let mut folded = vectorcraft_geom::BezPath::new();
|
||||
folded.move_to((0.0, 0.0));
|
||||
folded.quad_to((5.0, -1.0), (10.0, 10.0));
|
||||
folded.line_to((10.0, 0.0));
|
||||
folded.quad_to((5.0, 1.0), (0.0, 10.0));
|
||||
folded.close_path();
|
||||
let folded = vectorcraft_geom::PathData::from_bezpath(&folded);
|
||||
let Some(over) = highlight_over(vectorcraft_doc::NodeId(1), &folded, 1.0, Some(highlight)) else { panic!("a highlight") };
|
||||
assert_eq!(over.path_data(), Some(&folded));
|
||||
}
|
||||
|
||||
/// A curved face whose fold is smaller than the flattening tolerance, so that its flattened
|
||||
/// outline does not cross itself, still keeps its outline alone, wound either way.
|
||||
#[test]
|
||||
fn a_highlight_over_a_fold_smaller_than_flatness_keeps_its_outline() {
|
||||
let mut folded = vectorcraft_geom::BezPath::new();
|
||||
folded.move_to((0.0, 0.0));
|
||||
folded.line_to((10.0, 0.0));
|
||||
folded.line_to((10.0, 10.0));
|
||||
folded.line_to((0.0, 10.0));
|
||||
folded.line_to((0.0, 0.01));
|
||||
folded.quad_to((5.0, -0.03), (9.0, 0.01));
|
||||
folded.close_path();
|
||||
let highlight = vectorcraft_three_d::Highlight { flat: [0.5; 3], ramp: None };
|
||||
for bez in [folded.clone(), folded.reverse_subpaths()] {
|
||||
let mut flat = vectorcraft_geom::BezPath::new();
|
||||
vectorcraft_geom::flatten(bez.iter(), HIGHLIGHT_FLATNESS, |el| flat.push(el));
|
||||
assert!(seamed_fill(&vectorcraft_geom::PathData::from_bezpath(&flat), 1.0).is_some(), "flattening hides the fold");
|
||||
let path = vectorcraft_geom::PathData::from_bezpath(&bez);
|
||||
let Some(over) = highlight_over(vectorcraft_doc::NodeId(1), &path, 1.0, Some(highlight)) else { panic!("a highlight") };
|
||||
assert_eq!(over.path_data(), Some(&path));
|
||||
}
|
||||
}
|
||||
|
||||
/// A face with a collinear cubic that reverses direction keeps its highlight outline.
|
||||
#[test]
|
||||
fn a_highlight_over_a_retraced_cubic_keeps_its_outline() {
|
||||
let mut folded = vectorcraft_geom::BezPath::new();
|
||||
folded.move_to((0.0, 0.0));
|
||||
folded.curve_to((-8.0, 0.0), (-4.0, 0.0), (12.0, 0.0));
|
||||
folded.line_to((12.0, 10.0));
|
||||
folded.line_to((0.0, 10.0));
|
||||
folded.close_path();
|
||||
let highlight = vectorcraft_three_d::Highlight { flat: [0.5; 3], ramp: None };
|
||||
for bez in [folded.clone(), folded.reverse_subpaths()] {
|
||||
let mut flat = vectorcraft_geom::BezPath::new();
|
||||
vectorcraft_geom::flatten(bez.iter(), HIGHLIGHT_FLATNESS, |el| flat.push(el));
|
||||
assert!(seamed_fill(&vectorcraft_geom::PathData::from_bezpath(&flat), 1.0).is_some(), "flattening hides the reversal");
|
||||
let path = vectorcraft_geom::PathData::from_bezpath(&bez);
|
||||
let Some(over) = highlight_over(vectorcraft_doc::NodeId(1), &path, 1.0, Some(highlight)) else { panic!("a highlight") };
|
||||
assert_eq!(over.path_data(), Some(&path));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_curved_edge_crossing_its_neighbor_keeps_the_highlight_outline() {
|
||||
let mut folded = vectorcraft_geom::BezPath::new();
|
||||
folded.move_to((0.0, 0.0));
|
||||
folded.line_to((1000.0, 1000.0));
|
||||
folded.quad_to((500.0, 499.999), (0.0, 0.2));
|
||||
folded.line_to((-1000.0, 1000.0));
|
||||
folded.line_to((-1000.0, -1000.0));
|
||||
folded.close_path();
|
||||
let highlight = vectorcraft_three_d::Highlight { flat: [0.5; 3], ramp: None };
|
||||
for bez in [folded.clone(), folded.reverse_subpaths()] {
|
||||
let mut flat = vectorcraft_geom::BezPath::new();
|
||||
vectorcraft_geom::flatten(bez.iter(), HIGHLIGHT_FLATNESS, |el| flat.push(el));
|
||||
assert!(seamed_fill_with_clearance(&vectorcraft_geom::PathData::from_bezpath(&flat), 1.0, 2.0 * HIGHLIGHT_FLATNESS).is_some());
|
||||
let path = vectorcraft_geom::PathData::from_bezpath(&bez);
|
||||
let over = highlight_over(vectorcraft_doc::NodeId(1), &path, 1.0, Some(highlight)).unwrap();
|
||||
assert_eq!(over.path_data(), Some(&path));
|
||||
}
|
||||
}
|
||||
|
||||
/// A simple polygon facet and its 0.75 pt round seam are one nonzero-filled path: it covers the
|
||||
/// facet and the 0.375 pt the seam reaches past each edge and corner, and nothing more, wound
|
||||
/// either way and in a concave notch. A facet whose footprint would gain or lose area under a
|
||||
|
||||
@@ -10,7 +10,7 @@ use vectorcraft_three_d::{Edge, PlanarFace, Revolve, SolidFaces};
|
||||
|
||||
use crate::solids::wireframe::{WireFace, wireframe_params};
|
||||
use crate::solids::{
|
||||
Profile, Scope, is_container, members, object_profile, past_effect, profile, reshape_members, resolve_for, solid_paints, union_bounds,
|
||||
Build, Profile, Scope, is_container, members, object_profile, past_effect, profile, reshape_members, resolve_for, solid_paints, union_bounds,
|
||||
};
|
||||
use crate::util::{flag, num, text};
|
||||
use crate::{GeomContext, apply_geometry_with, is_geometry, merged_params};
|
||||
@@ -845,7 +845,7 @@ pub fn revolve_art(n: &Node) -> Option<Node> {
|
||||
/// or in a group, revolve the art they show ([`resolve_for`]). `None` too when that art can't be
|
||||
/// resolved.
|
||||
pub fn revolve_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
art(doc, n, false)
|
||||
art_reporting(doc, n, false, Build::Vector, &mut None)
|
||||
}
|
||||
|
||||
/// [`expand_revolve_art_in`] without a document.
|
||||
@@ -854,10 +854,11 @@ pub(crate) fn expand_revolve_art(n: &Node) -> Option<Node> {
|
||||
expand_revolve_art_in(None, n)
|
||||
}
|
||||
|
||||
/// Revolve's own Expand Appearance path, with the symbols of `doc` ([`revolve_art_in`]). The shared
|
||||
/// command and UI remain unchanged.
|
||||
/// Revolve's own Expand Appearance path, with the symbols of `doc` ([`revolve_art_in`]): in
|
||||
/// Render Settings › Rendered, the rendered image where it can be made. The shared command and UI
|
||||
/// remain unchanged.
|
||||
pub(crate) fn expand_revolve_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
art(doc, n, true)
|
||||
art_reporting(doc, n, true, Build::Draw, &mut None)
|
||||
}
|
||||
|
||||
/// The surfaces [`revolve_art`] draws, as meshes ([`crate::three_d_meshes`]): with the effect on
|
||||
@@ -918,8 +919,9 @@ fn surface_meshes(
|
||||
graphics: bool,
|
||||
) -> Result<Vec<crate::SolidMesh>, String> {
|
||||
let material = crate::solids::material::of(&fx.id, &merged_params(&fx.id, &fx.params));
|
||||
let projection = Some(vectorcraft_three_d::revolve_mesh_projection(b, options));
|
||||
surface_meshes_of(path, rule, b, fx, options, (paint, opacity, member), graphics)
|
||||
.map(|meshes| meshes.into_iter().map(|m| crate::SolidMesh { material, ..m }).collect())
|
||||
.map(|meshes| meshes.into_iter().map(|m| crate::SolidMesh { material, projection, ..m }).collect())
|
||||
}
|
||||
|
||||
/// [`surface_meshes`] in the default material.
|
||||
@@ -1083,13 +1085,23 @@ fn group_meshes(n: &Node, total: &mut usize, limit: usize) -> Result<Vec<crate::
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
/// The art [`revolve_art_in`] builds, as it is drawn and exported: in Render Settings › Rendered,
|
||||
/// the image of the lit surface where it can be made, in place of the shaded faces that
|
||||
/// [`revolve_art_in`] keeps for bounds, hit testing and snapping.
|
||||
pub fn revolve_art_drawn_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
art_reporting(doc, n, false, Build::Draw, &mut None)
|
||||
}
|
||||
|
||||
/// [`revolve_art_in`], or with `expand` Revolve's Expand Appearance art, built for `build`, with
|
||||
/// the reason a rendered image can't be made kept in `warning`.
|
||||
pub(crate) fn art_reporting(doc: Option<&Document>, n: &Node, expand: bool, build: Build, warning: &mut Option<String>) -> Option<Node> {
|
||||
let check_only = build == Build::Check;
|
||||
if !has_revolve(n) {
|
||||
return None;
|
||||
}
|
||||
let n = &*resolve_for(doc, n, "Revolve", false).ok()?;
|
||||
if is_container(n) {
|
||||
return group_art(doc, n, expand);
|
||||
return group_art(doc, n, expand, check_only, warning);
|
||||
}
|
||||
let (path, rule) = profile(n)?;
|
||||
let ctx = GeomContext::of(n);
|
||||
@@ -1103,7 +1115,43 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
let paints = solid_paints(n);
|
||||
let item = surface_item(&paints)?;
|
||||
let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
|
||||
if crate::solids::renders_wireframe(fx) {
|
||||
let p = merged_params(&fx.id, &fx.params);
|
||||
// Rendered, the surface's image, with the shadows of every light on the surface and on the
|
||||
// shadow plane; the shaded faces when it can't be made, and for vector measurements.
|
||||
let image = crate::render_settings(&fx.id, &p).filter(|_| build != Build::Vector).and_then(|settings| {
|
||||
let result = if crate::solids::rendered::reshapes_paths_only(&n.appearance.effects[index + 1..]) {
|
||||
Err(crate::solids::rendered::PATHS_ONLY.into())
|
||||
} else if crate::mapped_graphics(&p).is_empty() && crate::solids::rendered::takes([item], false) {
|
||||
let b = path.bounds()?;
|
||||
let (paint, opacity, _) = paint_of(item);
|
||||
let options = rule_options(fx, rule);
|
||||
surface_meshes(&path, rule, b, fx, options, (&paint, opacity, 1.0), true).and_then(|meshes| {
|
||||
let lighting = crate::solids::rendered::lighting(&fx.id, &p);
|
||||
let lighting = match crate::solids::rendered::plane_settings(&p, &lighting).filter(|_| crate::solids::shadow::casts(opacity)) {
|
||||
Some(shadow) => {
|
||||
let mut caster = vectorcraft_three_d::ShadowCaster::new();
|
||||
let faces = cast_surface(&mut caster, &path, b, options, None)?;
|
||||
crate::solids::rendered::with_receiver(lighting, &caster, shadow, &[faces])
|
||||
}
|
||||
None => lighting,
|
||||
};
|
||||
if build == Build::Bounds {
|
||||
crate::solids::rendered::bounds_art(doc, n.id, &lighting, &meshes, settings)
|
||||
} else {
|
||||
crate::solids::rendered::art(doc, n.id, &lighting, &meshes, settings, check_only)
|
||||
}
|
||||
})
|
||||
} else {
|
||||
Err(crate::solids::rendered::OPAQUE_ONLY.into())
|
||||
};
|
||||
crate::solids::rendered::reported(result, warning)
|
||||
});
|
||||
if check_only {
|
||||
return None;
|
||||
}
|
||||
if let Some(image) = image {
|
||||
children.push(image);
|
||||
} else if crate::solids::renders_wireframe(fx) {
|
||||
// In wireframe mode the edges of the faces, with no shadow.
|
||||
children.push(wire_art(n.id, [(&path, rule)], path.bounds()?, fx, fx_options(fx))?);
|
||||
} else {
|
||||
@@ -1132,6 +1180,12 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
for (original, item) in originals.into_iter().zip(&items) {
|
||||
if let Some(index) = item.effects().iter().position(|e| e.visible && is_revolve(&e.id)) {
|
||||
let fx = item.effects().get(index)?;
|
||||
if crate::renders_image(fx) {
|
||||
warning.get_or_insert_with(|| crate::solids::rendered::OBJECTS_ONLY.into());
|
||||
}
|
||||
if check_only {
|
||||
continue;
|
||||
}
|
||||
let p = geometry(&path, item.effects().get(..index)?, &ctx.item(original));
|
||||
let expand = expand && !item.effects().iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
|
||||
if crate::solids::renders_wireframe(fx) {
|
||||
@@ -1284,9 +1338,15 @@ pub(crate) fn overlaps(a: Rect, b: Rect) -> bool {
|
||||
/// [`art`] of group or layer `n`: every member swept about one axis on the bounds of all of them,
|
||||
/// each in its own paint. Every member's faces are drawn in one back-to-front order. `None` when
|
||||
/// the effect is only on the group's own fills or strokes or when its members can't be revolved.
|
||||
fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
fn group_art(doc: Option<&Document>, n: &Node, expand: bool, check_only: bool, warning: &mut Option<String>) -> Option<Node> {
|
||||
let index = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id))?;
|
||||
let fx = n.appearance.effects.get(index)?;
|
||||
if crate::renders_image(fx) {
|
||||
warning.get_or_insert_with(|| crate::solids::rendered::OBJECTS_ONLY.into());
|
||||
}
|
||||
if check_only {
|
||||
return None;
|
||||
}
|
||||
let mut shapes = members(n, "").ok()?;
|
||||
reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes);
|
||||
let b = union_bounds(&shapes)?;
|
||||
|
||||
+120
-19
@@ -41,7 +41,12 @@ pub use vectorcraft_three_d::SurfaceKind;
|
||||
pub(crate) mod shadow;
|
||||
|
||||
pub(crate) mod wireframe;
|
||||
pub use wireframe::{RENDER, RENDER_MODES, renders_wireframe, three_d_wireframe_in};
|
||||
pub use wireframe::{
|
||||
RENDER, RENDER_BACKGROUNDS, RENDER_MODES, RENDER_QUALITIES, RenderSettings, render_settings, renders_image, renders_wireframe,
|
||||
three_d_wireframe_in,
|
||||
};
|
||||
|
||||
pub mod rendered;
|
||||
|
||||
pub(crate) mod material;
|
||||
pub use material::MATERIAL;
|
||||
@@ -1003,6 +1008,11 @@ fn region(path: &PathData, rule: FillRule, item: &AppearanceItem) -> (PathData,
|
||||
/// fill rule, its shape's scopes and the index of its shape.
|
||||
type Part<'a> = (&'a AppearanceItem, f32, PathData, FillRule, &'a [Scope], usize);
|
||||
|
||||
fn solid_items(shape: &Profile) -> impl Iterator<Item = &AppearanceItem> {
|
||||
let top_fill = shape.items.iter().rposition(|i| matches!(i, AppearanceItem::Fill(_)));
|
||||
shape.items.iter().enumerate().filter(move |(k, i)| Some(*k) == top_fill || matches!(i, AppearanceItem::Stroke(_))).map(|(_, i)| i)
|
||||
}
|
||||
|
||||
/// The parts Extrude & Bevel and Inflate build solids from: each shape's top fill and its strokes,
|
||||
/// a group's members from the back up, each with its shape's opacity, the region it paints and its
|
||||
/// shape's scopes. The solids share the bounds of all their parts (`fallback` when none has any):
|
||||
@@ -1012,8 +1022,7 @@ fn solid_parts(shapes: &[Profile], fallback: Rect) -> (Vec<Part<'_>>, Rect) {
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(member, s)| {
|
||||
let top_fill = s.items.iter().rposition(|i| matches!(i, AppearanceItem::Fill(_)));
|
||||
s.items.iter().enumerate().filter(move |(k, i)| Some(*k) == top_fill || matches!(i, AppearanceItem::Stroke(_))).map(move |(_, i)| {
|
||||
solid_items(s).map(move |i| {
|
||||
let (area, rule) = region(&s.path, s.rule, i);
|
||||
(i, s.opacity, area, rule, s.scopes.as_slice(), member)
|
||||
})
|
||||
@@ -2053,12 +2062,57 @@ type ShadowAndSurfaces = (Vec<Arc<Node>>, Vec<Arc<Node>>);
|
||||
/// ([`masked`]). The art comes in two parts: the effect's shadow ([`cast_shadow`], none with it
|
||||
/// off), cast from the faces the solids drawn kept ([`cast_built`]), to be drawn behind every
|
||||
/// surface of the object, and the surfaces.
|
||||
fn art_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<ShadowAndSurfaces> {
|
||||
fn art_for(
|
||||
doc: Option<&Document>,
|
||||
n: &Node,
|
||||
effects: &[Effect],
|
||||
shapes: &[Profile],
|
||||
build: Build,
|
||||
warning: &mut Option<String>,
|
||||
) -> Option<ShadowAndSurfaces> {
|
||||
let (fx, later) = effects.split_first()?;
|
||||
if build == Build::Check && !crate::renders_image(fx) {
|
||||
return Some((vec![], vec![]));
|
||||
}
|
||||
// In wireframe mode the effect draws the edges of the faces it builds, with no shadow.
|
||||
if wireframe::renders_wireframe(fx) {
|
||||
return Some((vec![], wireframe::wire_surfaces(n.id, fx, shapes)?));
|
||||
}
|
||||
let p = crate::merged_params(&fx.id, &fx.params);
|
||||
// Rendered, the solids' image, with the shadows of every light on the solids and on the shadow
|
||||
// plane; the shaded faces when it can't be made, and for vector measurements.
|
||||
if build != Build::Vector
|
||||
&& let Some(settings) = wireframe::render_settings(&fx.id, &p)
|
||||
{
|
||||
let image = if rendered::reshapes_paths_only(later) {
|
||||
Err(rendered::PATHS_ONLY.into())
|
||||
} else if mapped_graphics(&p).is_empty() && rendered::takes(shapes.iter().flat_map(solid_items), has_masks(shapes)) {
|
||||
meshes_for(fx, shapes, &mut 0, MAX_MESH_TRIANGLES).and_then(|meshes| {
|
||||
let lighting = rendered::lighting(&fx.id, &p);
|
||||
let lighting = match cast_shadow_with(&fx.id, &p, shapes, rendered::plane_settings(&p, &lighting))? {
|
||||
Some((caster, shadow, cast)) => {
|
||||
let faces: Vec<std::ops::Range<usize>> = cast.iter().map(|c| c.2.clone()).collect();
|
||||
rendered::with_receiver(lighting, &caster, shadow, &faces)
|
||||
}
|
||||
None => lighting,
|
||||
};
|
||||
if build == Build::Bounds {
|
||||
rendered::bounds_art(doc, n.id, &lighting, &meshes, settings)
|
||||
} else {
|
||||
rendered::art(doc, n.id, &lighting, &meshes, settings, build == Build::Check)
|
||||
}
|
||||
})
|
||||
} else {
|
||||
Err(rendered::OPAQUE_ONLY.into())
|
||||
};
|
||||
let image = rendered::reported(image, warning);
|
||||
if build == Build::Check {
|
||||
return Some((vec![], vec![]));
|
||||
}
|
||||
if let Some(image) = image {
|
||||
return Some((vec![], vec![image]));
|
||||
}
|
||||
}
|
||||
let cast = casts_shadow(&fx.id, &p);
|
||||
let (art, built) = surfaces_for(doc, n, fx, shapes, cast)?;
|
||||
// A shadow past the limits draws the source path, as a solid past them does; commands report
|
||||
@@ -2091,10 +2145,20 @@ pub(crate) fn shadow_for(id: NodeId, fx: &Effect, shapes: &[Profile]) -> Result<
|
||||
/// When a member's opacity mask or blending mode applies to its solids ([`masked`]), it applies to
|
||||
/// the part of the shadow they cast too ([`shadow::scoped_art`]).
|
||||
fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result<Option<Cast<'a>>, String> {
|
||||
cast_shadow_with(id, p, shapes, shadow::options(p))
|
||||
}
|
||||
|
||||
/// [`cast_shadow`] with the shadow settings `settings` in place of those of `p`.
|
||||
fn cast_shadow_with<'a>(
|
||||
id: &str,
|
||||
p: &Value,
|
||||
shapes: &'a [Profile],
|
||||
settings: Option<vectorcraft_three_d::Shadow>,
|
||||
) -> Result<Option<Cast<'a>>, String> {
|
||||
if id == CLASSIC_EXTRUDE || id == CLASSIC_ROTATE {
|
||||
return Ok(None);
|
||||
}
|
||||
let (Some(settings), Some(b)) = (shadow::options(p), union_bounds(shapes)) else { return Ok(None) };
|
||||
let (Some(settings), Some(b)) = (settings, union_bounds(shapes)) else { return Ok(None) };
|
||||
let view = view_options(p);
|
||||
let mut caster = vectorcraft_three_d::ShadowCaster::new();
|
||||
// The faces each solid of visible art added, with its member's scopes and its ink (opacity
|
||||
@@ -2823,21 +2887,48 @@ pub fn solid_art(n: &Node) -> Option<Node> {
|
||||
/// or in a group, build from the art they show ([`resolve`]). `None` too when that art can't be
|
||||
/// resolved.
|
||||
pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
solid_art_reporting(doc, n, Build::Vector, &mut None)
|
||||
}
|
||||
|
||||
/// The art [`solid_art_in`] builds, as it is drawn and exported: in Render Settings › Rendered, the
|
||||
/// image of the lit solids where it can be made ([`rendered`]), in place of the shaded faces that
|
||||
/// [`solid_art_in`] keeps for bounds, hit testing and snapping.
|
||||
pub fn solid_art_drawn_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
solid_art_reporting(doc, n, Build::Draw, &mut None)
|
||||
}
|
||||
|
||||
/// What a 3D effect's art is built for.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Build {
|
||||
/// The vector art: the shaded faces and the vector shadow, in every mode but wireframe. No
|
||||
/// rendered image is made.
|
||||
Vector,
|
||||
/// Painted measurement art, with rendered images represented by their rectangles and no pixels.
|
||||
Bounds,
|
||||
/// Only whether the rendered image can be made, with the reason in the warning when it can't:
|
||||
/// no art and no pixels.
|
||||
Check,
|
||||
/// The art drawn and exported: the rendered image where it can be made.
|
||||
Draw,
|
||||
}
|
||||
|
||||
pub(crate) fn solid_art_reporting(doc: Option<&Document>, n: &Node, build: Build, warning: &mut Option<String>) -> Option<Node> {
|
||||
if !has_solid(n) {
|
||||
return None;
|
||||
}
|
||||
let n = &*resolve(doc, n, "").ok()?;
|
||||
if is_container(n) {
|
||||
return group_solid_art(doc, n);
|
||||
return group_solid_art(doc, n, build, warning);
|
||||
}
|
||||
let (path, rule) = profile(n)?;
|
||||
let ctx = GeomContext::of(n);
|
||||
let (sources, paints) = solid_paint_sources(n);
|
||||
let mut children = vec![];
|
||||
let remaining: Vec<Effect>;
|
||||
if let Some((index, fx)) = solid(&n.appearance.effects) {
|
||||
if let Some((index, _)) = solid(&n.appearance.effects) {
|
||||
let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx);
|
||||
let (shadow, surfaces) = art_for(doc, n, fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }])?;
|
||||
let (shadow, surfaces) =
|
||||
art_for(doc, n, &n.appearance.effects[index..], &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }], build, warning)?;
|
||||
children.extend(shadow.into_iter().chain(surfaces));
|
||||
// Later geometry effects act on the projected art as a whole.
|
||||
remaining = past_effect(&n.appearance.effects, index);
|
||||
@@ -2851,9 +2942,16 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
// Every item's shadow goes behind every item's art.
|
||||
let mut shadows = vec![];
|
||||
for (source, item) in sources.into_iter().zip(&paints) {
|
||||
if let Some((index, fx)) = solid(item.effects()) {
|
||||
if let Some((index, _)) = solid(item.effects()) {
|
||||
let p = geometry(&path, item.effects().get(..index)?, &ctx.item(source.unwrap_or(item)));
|
||||
let (shadow, surfaces) = art_for(doc, n, fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }])?;
|
||||
let (shadow, surfaces) = art_for(
|
||||
doc,
|
||||
n,
|
||||
&item.effects()[index..],
|
||||
&[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }],
|
||||
build,
|
||||
warning,
|
||||
)?;
|
||||
let later: Vec<Effect> = item.effects().iter().skip(index + 1).filter(|e| !is_three_d(&e.id)).cloned().collect();
|
||||
let with_later = |mut art: Arc<Node>| {
|
||||
Arc::make_mut(&mut art).appearance.effects = later.clone();
|
||||
@@ -2882,11 +2980,11 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
/// geometry effects before it reshape the members, those after it bend the result as a whole; the
|
||||
/// group's own fills and strokes are not drawn. `None` when the effect is only on one of the
|
||||
/// group's own fills or strokes, or when its members can't become solids.
|
||||
fn group_solid_art(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
let (index, fx) = solid(&n.appearance.effects)?;
|
||||
fn group_solid_art(doc: Option<&Document>, n: &Node, build: Build, warning: &mut Option<String>) -> Option<Node> {
|
||||
let (index, _) = solid(&n.appearance.effects)?;
|
||||
let mut shapes = members(n, "").ok()?;
|
||||
reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes);
|
||||
let (shadow, surfaces) = art_for(doc, n, fx, &shapes)?;
|
||||
let (shadow, surfaces) = art_for(doc, n, &n.appearance.effects[index..], &shapes, build, warning)?;
|
||||
let children = shadow.into_iter().chain(surfaces).collect();
|
||||
let remaining = past_effect(&n.appearance.effects, index);
|
||||
let mut art = n.clone();
|
||||
@@ -3195,12 +3293,15 @@ pub struct SolidMesh {
|
||||
/// The surface's Roughness and Metallic ([`MATERIAL`]); [`vectorcraft_three_d::Material::DEFAULT`]
|
||||
/// for the 3D (Classic) effects.
|
||||
pub material: vectorcraft_three_d::Material,
|
||||
/// The projection that takes the mesh's points to where the effect draws them on the page;
|
||||
/// `None` when it is not known.
|
||||
pub projection: Option<vectorcraft_three_d::MeshProjection>,
|
||||
}
|
||||
|
||||
impl SolidMesh {
|
||||
/// A mesh painted `color`, with no graphics, in the default material.
|
||||
/// A mesh painted `color`, with no graphics, in the default material, with no projection.
|
||||
pub fn plain(mesh: Mesh, color: [f32; 4]) -> Self {
|
||||
Self { mesh, color, graphics: None, material: vectorcraft_three_d::Material::DEFAULT }
|
||||
Self { mesh, color, graphics: None, material: vectorcraft_three_d::Material::DEFAULT, projection: None }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3305,17 +3406,17 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize)
|
||||
let material = material::of(&fx.id, &p);
|
||||
let mut out = vec![];
|
||||
// A solid's parts with and without graphics count together against the limit.
|
||||
let mut keep = |out: &mut Vec<SolidMesh>, mesh: Mesh, (paint, opacity): (&Paint, f32), bounds: Rect| {
|
||||
let mut keep = |out: &mut Vec<SolidMesh>, (mesh, projection): (Mesh, _), (paint, opacity): (&Paint, f32), bounds: Rect| {
|
||||
split_graphics(&fx.id, &p, bounds, mesh, (mesh_color(paint, opacity), opacity))
|
||||
.into_iter()
|
||||
.try_for_each(|part| keep_mesh(out, total, SolidMesh { material, ..part }, limit))
|
||||
.try_for_each(|part| keep_mesh(out, total, SolidMesh { material, projection, ..part }, limit))
|
||||
};
|
||||
if is_plane(&fx.id) {
|
||||
for s in shapes {
|
||||
for item in &s.items {
|
||||
let (paint, opacity, _) = paint_of(item, s.opacity);
|
||||
let (area, rule) = region(&s.path, s.rule, item);
|
||||
keep(&mut out, vectorcraft_three_d::plane_mesh(&area, rule, b, view)?, (&paint, opacity), b)?;
|
||||
keep(&mut out, vectorcraft_three_d::plane_meshed(&area, rule, b, view)?, (&paint, opacity), b)?;
|
||||
}
|
||||
}
|
||||
return Ok(out);
|
||||
@@ -3352,7 +3453,7 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize)
|
||||
match solid.mesh() {
|
||||
Ok(mesh) => {
|
||||
let (paint, opacity, _) = paint_of(item, *member);
|
||||
keep(&mut out, mesh, (&paint, opacity), bounds)?;
|
||||
keep(&mut out, (mesh, solid.projection()), (&paint, opacity), bounds)?;
|
||||
}
|
||||
Err(_) if matches!(item, AppearanceItem::Stroke(_)) => {}
|
||||
Err(e) => return Err(e),
|
||||
|
||||
@@ -0,0 +1,779 @@
|
||||
//! Render Settings › Rendered: the solids of a 3D effect drawn as one image, with a depth buffer,
|
||||
//! the metallic-roughness shading of every light and the shadows each light casts on the solids,
|
||||
//! instead of the shaded vector faces. The image lies on the page where the vector faces lie: each
|
||||
//! mesh point goes through the projection the effect draws its faces with
|
||||
//! ([`vectorcraft_three_d::MeshProjection`]).
|
||||
use std::io::Cursor;
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft_raster3d::{Limits, Scene, Vertex, srgb_to_linear, try_encode, try_render_cpu, try_shadow_maps};
|
||||
use vectorcraft_doc::{ImageBlob, ImageObject, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
use vectorcraft_three_d::{Light, MeshProjection};
|
||||
|
||||
use super::SolidMesh;
|
||||
use super::wireframe::RenderSettings;
|
||||
|
||||
/// The message a rendered image that can't be made is reported with; the effect then draws its
|
||||
/// shaded faces.
|
||||
pub const TOO_LARGE: &str = "The 3D render is too large; showing the shaded faces instead";
|
||||
|
||||
/// The message for a solid painted with something other than an opaque solid color in Normal
|
||||
/// blending, or with graphics; the effect then draws its shaded faces.
|
||||
pub const OPAQUE_ONLY: &str = "The 3D render shows opaque solid colors only; showing the shaded faces instead";
|
||||
|
||||
/// The message for a later geometry effect that reshapes paths but leaves images unchanged.
|
||||
pub const PATHS_ONLY: &str = "A later effect reshapes the 3D object's paths; showing the shaded faces instead";
|
||||
|
||||
/// Do any visible effects reshape paths without also reshaping images in `reshape_leaves`?
|
||||
pub(crate) fn reshapes_paths_only(effects: &[vectorcraft_doc::Effect]) -> bool {
|
||||
effects.iter().any(|e| {
|
||||
e.visible
|
||||
&& (crate::is_geometry(&e.id) || crate::is_pathfinder(&e.id))
|
||||
&& e.id != "distort.transform"
|
||||
&& e.id.strip_prefix("warp.").and_then(crate::warp::WarpStyle::from_id).is_none()
|
||||
})
|
||||
}
|
||||
|
||||
/// The message for Revolve on a group or on a fill or stroke, which draws its shaded faces.
|
||||
pub const OBJECTS_ONLY: &str = "Revolve renders on a single object only; showing the shaded faces instead";
|
||||
|
||||
/// Why a visible 3D effect in rendered mode on `n` draws shaded faces instead of an image.
|
||||
/// Messages are English, to be translated when displayed. `None` when no rendered effect falls back.
|
||||
pub fn rendered_warning(doc: &vectorcraft_doc::Document, n: &Node) -> Option<String> {
|
||||
let rendered = |fx: &vectorcraft_doc::Effect| fx.visible && crate::renders_image(fx);
|
||||
if !n.appearance.effects.iter().any(rendered) && !n.appearance.items.iter().any(|i| i.effects().iter().any(rendered)) {
|
||||
return None;
|
||||
}
|
||||
let mut warning = None;
|
||||
if crate::has_revolve(n) {
|
||||
let _ = crate::revolve::art_reporting(Some(doc), n, false, super::Build::Check, &mut warning);
|
||||
} else {
|
||||
let _ = super::solid_art_reporting(Some(doc), n, super::Build::Check, &mut warning);
|
||||
}
|
||||
warning
|
||||
}
|
||||
|
||||
/// The art of `n`'s 3D effect for painted bounds, with rendered images represented by their page
|
||||
/// rectangles without pixels. Shaded fallback art and later effects keep their normal bounds.
|
||||
/// This art is for measurement only; selection and snapping use the vector art instead.
|
||||
pub fn three_d_bounds_art_in(doc: Option<&vectorcraft_doc::Document>, n: &Node) -> Option<Node> {
|
||||
crate::revolve::art_reporting(doc, n, false, super::Build::Bounds, &mut None)
|
||||
.or_else(|| super::solid_art_reporting(doc, n, super::Build::Bounds, &mut None))
|
||||
}
|
||||
|
||||
/// The image rectangle for painted measurements, with the same eligibility and scene limits as
|
||||
/// the rendered image, without rasterizing or adding an image to the cache.
|
||||
pub(crate) fn bounds_art(
|
||||
doc: Option<&vectorcraft_doc::Document>,
|
||||
id: NodeId,
|
||||
lighting: &Lighting,
|
||||
meshes: &[SolidMesh],
|
||||
settings: RenderSettings,
|
||||
) -> Result<Option<Arc<Node>>, String> {
|
||||
art(doc, id, lighting, meshes, settings, true)?;
|
||||
let m = measure(meshes, lighting, settings, doc.map_or(72.0, |d| d.raster_ppi()), false, &Limits::default())?;
|
||||
let object = ImageObject {
|
||||
key: String::new(),
|
||||
width: m.cols,
|
||||
height: m.rows,
|
||||
xf: Affine::new([m.rect.width() / f64::from(m.cols), 0.0, 0.0, m.rect.height() / f64::from(m.rows), m.rect.x0, m.rect.y0]),
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
Ok(Some(Arc::new(Node::new(id, NodeKind::Image(Box::new(object))))))
|
||||
}
|
||||
|
||||
/// The rendered image of `result`, or `None` after a successful check. An error keeps its message
|
||||
/// in `warning` when no earlier reason is there; the caller then draws its shaded faces.
|
||||
pub(crate) fn reported(result: Result<Option<Arc<Node>>, String>, warning: &mut Option<String>) -> Option<Arc<Node>> {
|
||||
match result {
|
||||
Ok(image) => image,
|
||||
Err(message) => {
|
||||
warning.get_or_insert(message);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The lights a rendered image is shaded with, as the effect's shaded faces are.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Lighting {
|
||||
/// The directional lights ([`vectorcraft_three_d::Revolve::active_lights`]).
|
||||
pub lights: Vec<Light>,
|
||||
/// Each light's shadow diffusion in points, in the same order as `lights`.
|
||||
pub diffusion: Vec<f64>,
|
||||
/// The ambient light, 0 to 2.
|
||||
pub ambient: f64,
|
||||
/// Shading on: off, the solids show their paint unlit, as the shaded faces do.
|
||||
pub shade: bool,
|
||||
/// Shadows on: each light that lights the art casts shadows on the solids and on
|
||||
/// [`Lighting::receiver`]. Off, no light casts one.
|
||||
pub shadows: bool,
|
||||
/// The part of the shadow plane the shadows fall on, as four corners in mesh space (y up), in
|
||||
/// order round it ([`receiver`]); `None` without one.
|
||||
pub receiver: Option<[[f64; 3]; 4]>,
|
||||
}
|
||||
|
||||
impl Lighting {
|
||||
/// Does light `l` cast shadows in the image: Shading and Shadows are on and it lights the art?
|
||||
fn casts(&self, l: &Light) -> bool {
|
||||
self.shade && self.shadows && l.intensity > 0.0
|
||||
}
|
||||
}
|
||||
|
||||
/// The opacity of the black the shadow plane shows where a shadow falls, as the effect's vector
|
||||
/// shadow paints it.
|
||||
const PLANE_SHADOW: f32 = 0.5;
|
||||
|
||||
/// How far the shadow plane reaches past the shadows on it, as a share of the solids' largest size,
|
||||
/// so a soft edge is not cut. VectorCraft's own value.
|
||||
const PLANE_MARGIN: f64 = 0.05;
|
||||
|
||||
/// `lighting` with the part of the shadow plane the shadows of the faces in `faces` of `caster`
|
||||
/// fall on, with settings `shadow`, for every light that casts one ([`Lighting::casts`]).
|
||||
pub(crate) fn with_receiver(
|
||||
mut lighting: Lighting,
|
||||
caster: &vectorcraft_three_d::ShadowCaster,
|
||||
shadow: vectorcraft_three_d::Shadow,
|
||||
faces: &[std::ops::Range<usize>],
|
||||
) -> Lighting {
|
||||
let toward: Vec<[f64; 3]> = lighting.lights.iter().filter(|l| lighting.casts(l)).map(|l| l.direction()).collect();
|
||||
lighting.diffusion = lighting
|
||||
.lights
|
||||
.iter()
|
||||
.map(|l| caster.shadow_blur(vectorcraft_three_d::Shadow { softness: l.softness, ..shadow }, faces).unwrap_or(0.0))
|
||||
.collect();
|
||||
let softness = lighting.lights.iter().filter(|l| lighting.casts(l)).map(|l| l.softness).fold(0.0, f64::max);
|
||||
let shadow = vectorcraft_three_d::Shadow { softness, ..shadow };
|
||||
lighting.receiver = caster.receiver(shadow, faces, &toward, PLANE_MARGIN).map(|q| q.map(|[x, y, z]| [x, -y, z]));
|
||||
lighting
|
||||
}
|
||||
|
||||
/// A rendered image: `cols` × `rows` straight-alpha sRGB RGBA8 pixels covering `rect` on the page,
|
||||
/// made with `samples` × `samples` samples a pixel.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Rendered {
|
||||
pub rect: Rect,
|
||||
pub cols: u32,
|
||||
pub rows: u32,
|
||||
pub samples: u32,
|
||||
pub pixels: Vec<u8>,
|
||||
}
|
||||
|
||||
/// The margin, as a share of the depth range, the solids' nearest and farthest points keep from the
|
||||
/// ends of the depth buffer.
|
||||
const DEPTH_MARGIN: f64 = 0.01;
|
||||
|
||||
/// The largest share of the eye's distance a point may lie in front of the projection origin: at it
|
||||
/// the vector faces stop growing ([`vectorcraft_three_d::MeshProjection::project`]).
|
||||
const NEAREST: f64 = 0.999;
|
||||
|
||||
/// The image of `meshes` lit by `lighting`, with `settings`, at the document's raster effects
|
||||
/// resolution `doc_ppi` when the settings take it, within `limits`. An error ([`TOO_LARGE`]) when a
|
||||
/// mesh has no projection or a different one, when a point lies at or behind the eye, when the
|
||||
/// image has more pixels than `limits` allow even at one sample a pixel, or when the rasterizer
|
||||
/// refuses the scene. `draft` takes one sample a pixel and draft shadow maps, as Low quality does.
|
||||
pub fn render(
|
||||
meshes: &[SolidMesh],
|
||||
lighting: &Lighting,
|
||||
settings: RenderSettings,
|
||||
doc_ppi: f64,
|
||||
draft: bool,
|
||||
limits: &Limits,
|
||||
) -> Result<Rendered, String> {
|
||||
let too_large = || TOO_LARGE.to_string();
|
||||
let Measured { projection, rect, z, clip, cols, rows, samples: k, low } = measure(meshes, lighting, settings, doc_ppi, draft, limits)?;
|
||||
let scale = f64::from(cols * k) / rect.width();
|
||||
let mut scene = scene(meshes, lighting, projection, z, clip, (cols * k, rows * k), scale).ok_or_else(too_large)?;
|
||||
scene.ssaa = k;
|
||||
#[cfg(test)]
|
||||
RASTERIZATIONS.with(|n| n.set(n.get() + 1));
|
||||
if scene.lights.iter().any(|l| l.shadow >= 0) {
|
||||
try_shadow_maps(&mut scene, low, limits).map_err(|_| too_large())?;
|
||||
}
|
||||
let (mut image, _) = try_render_cpu(&scene, limits).map_err(|_| too_large())?;
|
||||
try_encode(&mut image).map_err(|_| too_large())?;
|
||||
let pixels = image
|
||||
.data
|
||||
.iter()
|
||||
.flat_map(|p| {
|
||||
let p = if settings.white { [p[0] + 1.0 - p[3], p[1] + 1.0 - p[3], p[2] + 1.0 - p[3], 1.0] } else { *p };
|
||||
let a = p[3].clamp(0.0, 1.0);
|
||||
let straight = |c: f32| if a > 0.0 { (c / a).clamp(0.0, 1.0) } else { 0.0 };
|
||||
[straight(p[0]), straight(p[1]), straight(p[2]), a].map(|c| (c * 255.0).round() as u8)
|
||||
})
|
||||
.collect();
|
||||
Ok(Rendered { rect, cols, rows, samples: k, pixels })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many rendered images enter the rasterizing path on this thread.
|
||||
static RASTERIZATIONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The projection, clip matrix and raster dimensions within the image's sample budget.
|
||||
struct Measured {
|
||||
projection: MeshProjection,
|
||||
rect: Rect,
|
||||
z: [f64; 2],
|
||||
clip: [[f32; 4]; 4],
|
||||
cols: u32,
|
||||
rows: u32,
|
||||
samples: u32,
|
||||
low: bool,
|
||||
}
|
||||
|
||||
/// Measure the image of `meshes` and the shadow plane `lighting` places, and choose its samples,
|
||||
/// without building a scene or producing pixels.
|
||||
fn measure(
|
||||
meshes: &[SolidMesh],
|
||||
lighting: &Lighting,
|
||||
settings: RenderSettings,
|
||||
doc_ppi: f64,
|
||||
draft: bool,
|
||||
limits: &Limits,
|
||||
) -> Result<Measured, String> {
|
||||
let too_large = || TOO_LARGE.to_string();
|
||||
let projection = meshes.first().and_then(|m| m.projection).ok_or_else(too_large)?;
|
||||
if meshes.iter().any(|m| m.projection != Some(projection)) {
|
||||
return Err(too_large());
|
||||
}
|
||||
let (bounds, z) = extent(meshes, receiver(lighting), projection).ok_or_else(too_large)?;
|
||||
let cell = 72.0 / settings.resolution.unwrap_or(doc_ppi).clamp(1.0, 2400.0);
|
||||
let (cols, rows) = ((bounds.width() / cell).ceil().max(1.0), (bounds.height() / cell).ceil().max(1.0));
|
||||
let pixels = cols * rows;
|
||||
if pixels.is_nan() || pixels > limits.max_pixels as f64 {
|
||||
return Err(too_large());
|
||||
}
|
||||
let (cols, rows) = (cols as u32, rows as u32);
|
||||
let rect = Rect::new(bounds.x0, bounds.y0, bounds.x0 + f64::from(cols) * cell, bounds.y0 + f64::from(rows) * cell);
|
||||
let low = draft || settings.quality == 0;
|
||||
let mut k = if low { 1 } else { settings.samples() };
|
||||
while k > 1 && pixels * f64::from(k * k) > limits.max_pixels as f64 {
|
||||
k -= 1;
|
||||
}
|
||||
let clip = clip(projection, rect, z).ok_or_else(too_large)?;
|
||||
Ok(Measured { projection, rect, z, clip, cols, rows, samples: k, low })
|
||||
}
|
||||
|
||||
/// Check scene limits without allocating raster or shadow depth buffers. The counts follow
|
||||
/// craft-raster3d at 2680a3b3fe464c7afa3d260b33a828fa94e12f6d: lib.rs:178-223,
|
||||
/// scene.rs:242-278,325-328, raster.rs:245-281,307-385,740-747 and
|
||||
/// shadow.rs:109-135,262-276,316-356,413-449,500-515,533-538,576-657.
|
||||
/// Measured solids and the shadow plane lie inside the clip volume, the solids use opaque, visible
|
||||
/// materials, the plane's two triangles hold no texture and the lights are directional, so each
|
||||
/// source triangle contributes one bounding box, without clipping or an alpha-discard search. Raster and shadow work have separate budgets, as in the renderer.
|
||||
fn check(meshes: &[SolidMesh], lighting: &Lighting, settings: RenderSettings, ppi: f64, limits: &Limits) -> Result<(), String> {
|
||||
let m = measure(meshes, lighting, settings, ppi, false, limits)?;
|
||||
let size = (m.cols * m.samples, m.rows * m.samples);
|
||||
let s = scene(meshes, lighting, m.projection, m.z, m.clip, size, f64::from(size.0) / m.rect.width()).ok_or(TOO_LARGE)?;
|
||||
limits.check(s.width, s.height).map_err(|_| TOO_LARGE)?;
|
||||
if s.indices.len() as u64 / 3 > limits.max_triangles || s.vertices.len() as u64 > limits.max_vertices || s.lights.len() > limits.max_lights {
|
||||
return Err(TOO_LARGE.into());
|
||||
}
|
||||
let transform =
|
||||
|matrix: &[[f32; 4]], p: [f32; 3], row: usize| matrix[row][0] * p[0] + matrix[row][1] * p[1] + matrix[row][2] * p[2] + matrix[row][3];
|
||||
let mut work = 0u64;
|
||||
for tri in s.indices.as_chunks::<3>().0 {
|
||||
let mut points = [[0.0; 2]; 3];
|
||||
for (point, &i) in points.iter_mut().zip(tri) {
|
||||
let p = s.vertices[i as usize].pos;
|
||||
let c = [0, 1, 2, 3].map(|r| transform(&s.clip, p, r));
|
||||
// Refuse transforms whose rounding escapes the measured clip volume.
|
||||
if !c.iter().all(|v| v.is_finite()) || c[3] <= 0.0 || c[2] < 0.0 || c[2] > c[3] {
|
||||
return Err(TOO_LARGE.into());
|
||||
}
|
||||
let iw = 1.0 / c[3];
|
||||
*point = [(f64::from(c[0] * iw) + 1.0) * 0.5 * f64::from(s.width), (1.0 - f64::from(c[1] * iw)) * 0.5 * f64::from(s.height)];
|
||||
}
|
||||
let area = (0..3).map(|i| points[i][0] * points[(i + 1) % 3][1] - points[(i + 1) % 3][0] * points[i][1]).sum::<f64>();
|
||||
if !area.is_finite() {
|
||||
return Err(TOO_LARGE.into());
|
||||
}
|
||||
if area != 0.0 {
|
||||
let pixels = bounding_work(points, [s.width, s.height]);
|
||||
if pixels > 0 {
|
||||
work = work.saturating_add(pixels + 1);
|
||||
}
|
||||
}
|
||||
if work > limits.max_work {
|
||||
return Err(TOO_LARGE.into());
|
||||
}
|
||||
}
|
||||
// Shadow maps are made only for the lights that cast shadows, from the triangles that cast them.
|
||||
let casters: Vec<&[u32; 3]> = s
|
||||
.indices
|
||||
.as_chunks::<3>()
|
||||
.0
|
||||
.iter()
|
||||
.filter(|t| s.materials.get(s.vertices[t[0] as usize].material as usize).is_some_and(|m| m.casts_shadows))
|
||||
.collect();
|
||||
if casters.is_empty() || s.lights.iter().all(|l| l.shadow < 0) {
|
||||
return Ok(());
|
||||
}
|
||||
let (mut lo, mut hi) = ([f64::INFINITY; 3], [f64::NEG_INFINITY; 3]);
|
||||
for v in &s.vertices {
|
||||
for k in 0..3 {
|
||||
lo[k] = lo[k].min(f64::from(v.pos[k]));
|
||||
hi[k] = hi[k].max(f64::from(v.pos[k]));
|
||||
}
|
||||
}
|
||||
let center = [0, 1, 2].map(|k| (lo[k] + hi[k]) * 0.5);
|
||||
let radius = ((hi[0] - lo[0]).powi(2) + (hi[1] - lo[1]).powi(2) + (hi[2] - lo[2]).powi(2)).sqrt() * 0.5 + 1.0;
|
||||
let kinds: Vec<u32> = s.lights.iter().map(|l| u32::from(l.shadow >= 0)).chain(std::iter::once(0)).collect();
|
||||
let sizes = craft_raster3d::shadow_sizes(s.width, s.height, m.low, &kinds);
|
||||
let maps = sizes.iter().flatten().count() as u64;
|
||||
if maps.saturating_mul(casters.len() as u64) > limits.max_work {
|
||||
return Err(TOO_LARGE.into());
|
||||
}
|
||||
let mut work = 0u64;
|
||||
for (light, size) in s.lights.iter().zip(sizes) {
|
||||
let (Some(size), true) = (size, light.shadow >= 0) else { continue };
|
||||
let dir = light.dir.map(f64::from);
|
||||
let eye = [0, 1, 2].map(|k| center[k] - dir[k] * radius * 2.0);
|
||||
let dot = |a: [f64; 3], b: [f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
|
||||
let unit = |v: [f64; 3]| v.map(|x| x / dot(v, v).sqrt());
|
||||
let forward = unit(dir);
|
||||
let hint = if dir[1].abs() < 0.9 { [0.0, 1.0, 0.0] } else { [0.0, 0.0, 1.0] };
|
||||
let down = unit([0, 1, 2].map(|k| hint[k] - forward[k] * dot(hint, forward)));
|
||||
let right = unit([
|
||||
down[1] * forward[2] - down[2] * forward[1],
|
||||
down[2] * forward[0] - down[0] * forward[2],
|
||||
down[0] * forward[1] - down[1] * forward[0],
|
||||
]);
|
||||
let view = [right, down].map(|row| [row[0] as f32, row[1] as f32, row[2] as f32, (-dot(row, eye)) as f32]);
|
||||
let focal = (f64::from(size) * 0.5 / radius) as f32;
|
||||
for tri in &casters {
|
||||
let points = [0, 1, 2].map(|k| {
|
||||
let p = s.vertices[tri[k] as usize].pos;
|
||||
[0, 1].map(|r| f64::from(transform(&view, p, r) * focal + size as f32 * 0.5))
|
||||
});
|
||||
let [a, b, c] = points;
|
||||
let area = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
|
||||
if !area.is_finite() {
|
||||
return Err(TOO_LARGE.into());
|
||||
}
|
||||
let texels = if area.abs() < 1e-12 { 0 } else { bounding_work(points, [size; 2]) };
|
||||
work = work.saturating_add(texels + 1);
|
||||
if work > limits.max_work {
|
||||
return Err(TOO_LARGE.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The pixels inside a triangle's bounding box, clamped to the raster.
|
||||
fn bounding_work(points: [[f64; 2]; 3], size: [u32; 2]) -> u64 {
|
||||
[0, 1]
|
||||
.map(|k| {
|
||||
let lo = points.iter().map(|p| p[k]).fold(f64::INFINITY, f64::min).floor().clamp(0.0, f64::from(size[k])) as u64;
|
||||
let hi = points.iter().map(|p| p[k]).fold(f64::NEG_INFINITY, f64::max).ceil().clamp(0.0, f64::from(size[k])) as u64;
|
||||
hi.saturating_sub(lo)
|
||||
})
|
||||
.into_iter()
|
||||
.product()
|
||||
}
|
||||
|
||||
/// The corners of the shadow plane of `lighting`, in mesh space; none without one.
|
||||
fn receiver(lighting: &Lighting) -> &[[f64; 3]] {
|
||||
lighting.receiver.as_ref().map_or(&[], |q| q.as_slice())
|
||||
}
|
||||
|
||||
/// The page bounds the points of `meshes` and the shadow plane's corners `plane` project to, and
|
||||
/// the range of their depths. `None` with no mesh point, a point that isn't finite, or one at or
|
||||
/// behind the eye.
|
||||
fn extent(meshes: &[SolidMesh], plane: &[[f64; 3]], projection: MeshProjection) -> Option<(Rect, [f64; 2])> {
|
||||
let mut bounds: Option<Rect> = None;
|
||||
let mut z = [f64::INFINITY, f64::NEG_INFINITY];
|
||||
meshes.iter().flat_map(|m| &m.mesh.positions).next()?;
|
||||
for p in meshes.iter().flat_map(|m| &m.mesh.positions).chain(plane) {
|
||||
if !p.iter().all(|v| v.is_finite()) || projection.eye.is_some_and(|e| p[2] >= e * NEAREST) {
|
||||
return None;
|
||||
}
|
||||
let at = projection.project(*p);
|
||||
let r = Rect::from_points(at, at);
|
||||
bounds = Some(bounds.map_or(r, |b| b.union(r)));
|
||||
z = [z[0].min(p[2]), z[1].max(p[2])];
|
||||
}
|
||||
bounds.filter(|b| b.width().is_finite() && b.height().is_finite()).map(|b| (b, z))
|
||||
}
|
||||
|
||||
/// The row-major clip matrix that takes a point of the solids' world space (mesh space with y down,
|
||||
/// about the projection origin) to the image `rect` as [`MeshProjection::project`] places it, with
|
||||
/// depths `z` kept inside the depth buffer and nearer points deeper in it. `None` when no depth
|
||||
/// mapping keeps them in order.
|
||||
fn clip(projection: MeshProjection, rect: Rect, z: [f64; 2]) -> Option<[[f32; 4]; 4]> {
|
||||
let (rw, rh) = (rect.width(), rect.height());
|
||||
let a = 2.0 * (projection.origin.x - rect.x0) / rw - 1.0;
|
||||
let b = 1.0 - 2.0 * (projection.origin.y - rect.y0) / rh;
|
||||
// w = 1 − z / eye without perspective's eye: 1.
|
||||
let inv_eye = projection.eye.map_or(0.0, |e| 1.0 / e);
|
||||
let (z0, z1) = if z[1] > z[0] { (z[0], z[1]) } else { (z[0] - 0.5, z[0] + 0.5) };
|
||||
let w = |z: f64| 1.0 - z * inv_eye;
|
||||
// ndc depth (dz · z + d0) / w: the farthest at DEPTH_MARGIN, the nearest at 1 − DEPTH_MARGIN.
|
||||
// With w positive over [z0, z1] the ndc depth is a linear-fractional function of z, so it rises
|
||||
// monotonically between those two ends even when dz itself is negative (a near eye).
|
||||
let (w0, w1) = (w(z0), w(z1));
|
||||
if !(w0 > 0.0 && w1 > 0.0) {
|
||||
return None;
|
||||
}
|
||||
let (lo, hi) = (DEPTH_MARGIN * w0, (1.0 - DEPTH_MARGIN) * w1);
|
||||
let dz = (hi - lo) / (z1 - z0);
|
||||
let d0 = lo - dz * z0;
|
||||
if !(dz.is_finite() && d0.is_finite() && hi / w1 > lo / w0) {
|
||||
return None;
|
||||
}
|
||||
let m = [[2.0 / rw, 0.0, -a * inv_eye, a], [0.0, -2.0 / rh, -b * inv_eye, b], [0.0, 0.0, dz, d0], [0.0, 0.0, -inv_eye, 1.0]];
|
||||
let m = m.map(|row| row.map(|v| v as f32));
|
||||
m.iter().flatten().all(|v| v.is_finite()).then_some(m)
|
||||
}
|
||||
|
||||
/// The scene of `meshes` for an image `size` raster pixels with clip matrix `clip`: every triangle in world
|
||||
/// space (mesh space with y down, as the page is), opaque ones first, then
|
||||
/// those of see-through solids from back to front; one material for each mesh; one parallel light,
|
||||
/// casting shadows, for each of `lighting`'s lights. `scale` is raster pixels per point, including
|
||||
/// the samples per image pixel.
|
||||
fn scene(
|
||||
meshes: &[SolidMesh],
|
||||
lighting: &Lighting,
|
||||
projection: MeshProjection,
|
||||
z: [f64; 2],
|
||||
clip: [[f32; 4]; 4],
|
||||
size: (u32, u32),
|
||||
scale: f64,
|
||||
) -> Option<Scene> {
|
||||
let eye = projection.eye.unwrap_or(z[1] + 1.0);
|
||||
let mut vertices = vec![];
|
||||
let mut opaque: Vec<[u32; 3]> = vec![];
|
||||
let mut clear: Vec<([u32; 3], f64)> = vec![];
|
||||
let mut materials = vec![];
|
||||
for (index, m) in meshes.iter().enumerate() {
|
||||
let [r, g, b, alpha] = m.color.map(|c| if c.is_finite() { c.clamp(0.0, 1.0) } else { 0.0 });
|
||||
materials.push(craft_raster3d::Material {
|
||||
base: [srgb_to_linear(r), srgb_to_linear(g), srgb_to_linear(b), 1.0],
|
||||
metallic: m.material.metallic() as f32,
|
||||
roughness: m.material.roughness() as f32,
|
||||
opacity: alpha,
|
||||
double_sided: true,
|
||||
unlit: !lighting.shade,
|
||||
casts_shadows: true,
|
||||
..Default::default()
|
||||
});
|
||||
let base = vertices.len() as u32;
|
||||
let mesh = &m.mesh;
|
||||
for (i, p) in mesh.positions.iter().enumerate() {
|
||||
let n = mesh.normals.get(i).copied().unwrap_or([0.0, 0.0, 1.0]);
|
||||
vertices.push(Vertex {
|
||||
pos: [p[0] as f32, -p[1] as f32, p[2] as f32],
|
||||
normal: [n[0] as f32, -n[1] as f32, n[2] as f32],
|
||||
uv: mesh.uvs.get(i).map_or([0.0; 2], |uv| [uv[0] as f32, uv[1] as f32]),
|
||||
tangent: [1.0, 0.0, 0.0, 1.0],
|
||||
material: index as u32,
|
||||
});
|
||||
}
|
||||
for t in &mesh.triangles {
|
||||
if t.iter().any(|&i| i as usize >= mesh.positions.len()) {
|
||||
return None;
|
||||
}
|
||||
let tri = t.map(|i| base + i);
|
||||
if alpha >= 1.0 {
|
||||
opaque.push(tri);
|
||||
} else {
|
||||
let depth = t.iter().map(|&i| mesh.positions[i as usize][2]).sum::<f64>() / 3.0;
|
||||
clear.push((tri, depth));
|
||||
}
|
||||
}
|
||||
}
|
||||
clear.sort_by(|a, b| a.1.total_cmp(&b.1));
|
||||
// The shadow plane: drawn only where a shadow falls on it, black at the vector shadow's
|
||||
// opacity, behind every surface, so first in the see-through range.
|
||||
let mut plane = vec![];
|
||||
if let Some(q) = lighting.receiver.filter(|_| lighting.shade && lighting.shadows) {
|
||||
let edge = |a: [f64; 3], b: [f64; 3]| [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
|
||||
let (e1, e2) = (edge(q[0], q[1]), edge(q[0], q[3]));
|
||||
let n = [e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0]];
|
||||
let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt();
|
||||
if len.is_finite() && len > 0.0 {
|
||||
let material = materials.len() as u32;
|
||||
materials.push(craft_raster3d::Material {
|
||||
base: [0.0, 0.0, 0.0, 1.0],
|
||||
opacity: PLANE_SHADOW,
|
||||
double_sided: true,
|
||||
shadows_only: true,
|
||||
receives_shadows: true,
|
||||
casts_shadows: false,
|
||||
..Default::default()
|
||||
});
|
||||
let base = vertices.len() as u32;
|
||||
for p in q {
|
||||
vertices.push(Vertex {
|
||||
pos: [p[0] as f32, -p[1] as f32, p[2] as f32],
|
||||
normal: [(n[0] / len) as f32, (-n[1] / len) as f32, (n[2] / len) as f32],
|
||||
uv: [0.0; 2],
|
||||
tangent: [1.0, 0.0, 0.0, 1.0],
|
||||
material,
|
||||
});
|
||||
}
|
||||
plane = vec![[base, base + 1, base + 2], [base, base + 2, base + 3]];
|
||||
}
|
||||
}
|
||||
// Later meshes paint over earlier ones in the shaded faces. Submit their opaque triangles
|
||||
// first so the strict depth test keeps that paint when surfaces share a depth.
|
||||
let opaque_count = (opaque.len() * 3) as u32;
|
||||
let indices = opaque.into_iter().rev().flatten().chain(plane.into_iter().flatten()).chain(clear.into_iter().flat_map(|(t, _)| t)).collect();
|
||||
let lights = lighting
|
||||
.lights
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|_| lighting.shade)
|
||||
.map(|(i, l)| {
|
||||
// The direction the light travels: away from it.
|
||||
let [x, y, z] = l.direction().map(|v| -v);
|
||||
let len = (x * x + y * y + z * z).sqrt();
|
||||
craft_raster3d::Light {
|
||||
kind: 0,
|
||||
pos: [0.0; 3],
|
||||
dir: [(x / len) as f32, (y / len) as f32, (z / len) as f32],
|
||||
color: l.color.map(|c| srgb_to_linear((c * l.intensity).clamp(0.0, 1.0) as f32)),
|
||||
cos_inner: 1.0,
|
||||
cos_outer: 1.0,
|
||||
falloff: 0,
|
||||
radius: 0.0,
|
||||
falloff_distance: 0.0,
|
||||
// With Shadows off no light casts one, on the solids or on a plane.
|
||||
shadow: if lighting.casts(l) { 0 } else { -1 },
|
||||
shadow_darkness: 1.0,
|
||||
shadow_diffusion: lighting.diffusion.get(i).map_or(l.softness, |blur| blur * scale) as f32,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
// Ambient light up to 100% goes through the sRGB curve; above it, the linear value scales with
|
||||
// the intensity, as the shaded faces' ambient term does.
|
||||
let ambient = lighting.ambient.clamp(0.0, 2.0) as f32;
|
||||
let ambient = srgb_to_linear(ambient.min(1.0)) * ambient.max(1.0);
|
||||
Some(Scene {
|
||||
width: size.0,
|
||||
height: size.1,
|
||||
ssaa: 1,
|
||||
clip,
|
||||
// Camera depth: the distance in front of the eye, on the z axis.
|
||||
view: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, -1.0, eye as f32], [0.0, 0.0, 0.0, 1.0]],
|
||||
eye: [0.0, 0.0, eye as f32],
|
||||
cam_fwd: [0.0, 0.0, -1.0],
|
||||
ortho: projection.eye.is_none(),
|
||||
vertices,
|
||||
indices,
|
||||
opaque_count,
|
||||
// Read only by the renderers with auxiliary outputs, which this one does not use.
|
||||
part_ids: vec![],
|
||||
materials,
|
||||
textures: vec![],
|
||||
texels: vec![],
|
||||
lights,
|
||||
shadows: vec![],
|
||||
shadow_texels: vec![],
|
||||
env: None,
|
||||
ambient: [ambient; 3],
|
||||
linear_io: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// `image` as an image object of `id`'s art, holding its pixels as a PNG; `None` when it can't be
|
||||
/// encoded.
|
||||
pub fn image_node(id: NodeId, image: &Rendered) -> Option<Arc<Node>> {
|
||||
Some(Arc::new(Node::new(id, NodeKind::Image(Box::new(image_object(image)?)))))
|
||||
}
|
||||
|
||||
/// `image` as an image object holding its pixels as a PNG; `None` when it can't be encoded.
|
||||
fn image_object(image: &Rendered) -> Option<ImageObject> {
|
||||
let raw = image::RgbaImage::from_raw(image.cols, image.rows, image.pixels.clone())?;
|
||||
let mut png = vec![];
|
||||
raw.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?;
|
||||
let blob = ImageBlob::png(png);
|
||||
let cell = image.rect.width() / f64::from(image.cols);
|
||||
Some(ImageObject {
|
||||
key: blob.content_key(),
|
||||
width: image.cols,
|
||||
height: image.rows,
|
||||
xf: Affine::new([cell, 0.0, 0.0, image.rect.height() / f64::from(image.rows), image.rect.x0, image.rect.y0]),
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: Some(Arc::new(blob)),
|
||||
})
|
||||
}
|
||||
|
||||
/// The image a 3D effect with `settings` draws for object `id` from `meshes`, lit by `lighting`, with
|
||||
/// the raster effects resolution of `doc` (72 ppi without one). An error when it can't be made: the
|
||||
/// effect then draws its shaded faces. With `check_only`, validate the colors and scene limits
|
||||
/// without producing pixels, returning `Ok(None)` when it fits.
|
||||
pub(crate) fn art(
|
||||
doc: Option<&vectorcraft_doc::Document>,
|
||||
id: NodeId,
|
||||
lighting: &Lighting,
|
||||
meshes: &[SolidMesh],
|
||||
settings: RenderSettings,
|
||||
check_only: bool,
|
||||
) -> Result<Option<Arc<Node>>, String> {
|
||||
// Mapped graphics and see-through solids keep their shaded faces, which draw the graphics and
|
||||
// apply a solid's opacity once to the whole surface.
|
||||
if meshes.iter().any(|m| m.graphics.is_some() || m.color[3].is_nan() || m.color[3] < 1.0) {
|
||||
return Err(OPAQUE_ONLY.into());
|
||||
}
|
||||
let ppi = doc.map_or(72.0, |d| d.raster_ppi());
|
||||
if check_only {
|
||||
check(meshes, lighting, settings, ppi, &Limits::default())?;
|
||||
return Ok(None);
|
||||
}
|
||||
let key = image_key(meshes, lighting, settings, ppi);
|
||||
let made = match cached(key) {
|
||||
Some(made) => made,
|
||||
None => {
|
||||
let made = render(meshes, lighting, settings, ppi, false, &Limits::default())
|
||||
.and_then(|image| image_object(&image).ok_or_else(|| TOO_LARGE.to_string()));
|
||||
keep(key, &made);
|
||||
made
|
||||
}
|
||||
};
|
||||
made.map(|object| Some(Arc::new(Node::new(id, NodeKind::Image(Box::new(object))))))
|
||||
}
|
||||
|
||||
/// Most rendered images [`art`] keeps for reuse, and most PNG bytes they hold together. VectorCraft's
|
||||
/// own values.
|
||||
const KEPT_IMAGES: usize = 32;
|
||||
const KEPT_BYTES: usize = 64 << 20;
|
||||
|
||||
/// What [`art`] made, newest last, under the key of what it was made from ([`image_key`]).
|
||||
type Kept = Vec<(u128, Result<ImageObject, String>)>;
|
||||
|
||||
#[cfg(not(test))]
|
||||
static KEPT: std::sync::Mutex<Kept> = std::sync::Mutex::new(Vec::new());
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Each test thread keeps its own images, so a test's count of rasterizations doesn't depend on
|
||||
/// what other tests drew.
|
||||
static KEPT: std::cell::RefCell<Kept> = const { std::cell::RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
/// Run `f` on the kept images; `None` when they can't be reached.
|
||||
fn with_kept<T>(f: impl FnOnce(&mut Kept) -> T) -> Option<T> {
|
||||
#[cfg(not(test))]
|
||||
{
|
||||
KEPT.lock().ok().map(|mut kept| f(&mut kept))
|
||||
}
|
||||
#[cfg(test)]
|
||||
{
|
||||
KEPT.with(|kept| kept.try_borrow_mut().ok().map(|mut kept| f(&mut kept)))
|
||||
}
|
||||
}
|
||||
|
||||
/// The image kept under `key`, moved to the newest place.
|
||||
fn cached(key: u128) -> Option<Result<ImageObject, String>> {
|
||||
with_kept(|kept| {
|
||||
let at = kept.iter().position(|(k, _)| *k == key)?;
|
||||
let entry = kept.remove(at);
|
||||
let made = entry.1.clone();
|
||||
kept.push(entry);
|
||||
Some(made)
|
||||
})
|
||||
.flatten()
|
||||
}
|
||||
|
||||
/// Keep `made` under `key`, letting the oldest go past [`KEPT_IMAGES`] or [`KEPT_BYTES`].
|
||||
fn keep(key: u128, made: &Result<ImageObject, String>) {
|
||||
let bytes = |m: &Result<ImageObject, String>| m.as_ref().ok().and_then(|o| o.pixels.as_ref()).map_or(0, |b| b.bytes.len());
|
||||
if bytes(made) > KEPT_BYTES {
|
||||
return;
|
||||
}
|
||||
with_kept(|kept| {
|
||||
kept.retain(|(k, _)| *k != key);
|
||||
kept.push((key, made.clone()));
|
||||
while kept.len() > KEPT_IMAGES || kept.iter().map(|(_, m)| bytes(m)).sum::<usize>() > KEPT_BYTES {
|
||||
drop(kept.remove(0));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// A 128-bit hash of everything a rendered image is made from: every mesh's points, normals,
|
||||
/// texture coordinates, triangles, color, material and projection, the lights, ambient light,
|
||||
/// shading, shadows and shadow plane, the render settings and the resolution. Moving, turning or
|
||||
/// reshaping the object, or changing any setting, changes it; panning and redrawing do not.
|
||||
fn image_key(meshes: &[SolidMesh], lighting: &Lighting, settings: RenderSettings, ppi: f64) -> u128 {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let half = |seed: u8| {
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
seed.hash(&mut h);
|
||||
let mut f = |v: f64| v.to_bits().hash(&mut h);
|
||||
for m in meshes {
|
||||
let mesh = &m.mesh;
|
||||
mesh.positions.iter().chain(&mesh.normals).flatten().for_each(|v| f(*v));
|
||||
mesh.uvs.iter().flatten().for_each(|v| f(*v));
|
||||
m.color.iter().for_each(|c| f(f64::from(*c)));
|
||||
f(m.material.roughness());
|
||||
f(m.material.metallic());
|
||||
if let Some(p) = m.projection {
|
||||
[p.origin.x, p.origin.y, p.eye.unwrap_or(f64::NAN)].into_iter().for_each(&mut f);
|
||||
}
|
||||
f(mesh.positions.len() as f64);
|
||||
f(mesh.triangles.len() as f64);
|
||||
}
|
||||
for l in &lighting.lights {
|
||||
[l.rotation, l.height, l.intensity, l.softness, f64::from(u8::from(l.behind))].into_iter().chain(l.color).for_each(&mut f);
|
||||
}
|
||||
lighting.receiver.iter().flatten().flatten().for_each(|v| f(*v));
|
||||
lighting.diffusion.iter().for_each(|v| f(*v));
|
||||
f(lighting.diffusion.len() as f64);
|
||||
[lighting.ambient, f64::from(u8::from(lighting.shade)), f64::from(u8::from(lighting.shadows)), lighting.lights.len() as f64]
|
||||
.into_iter()
|
||||
.for_each(&mut f);
|
||||
[settings.quality as f64, settings.resolution.unwrap_or(f64::NAN), f64::from(u8::from(settings.white)), ppi].into_iter().for_each(&mut f);
|
||||
for m in meshes {
|
||||
m.mesh.triangles.hash(&mut h);
|
||||
}
|
||||
h.finish()
|
||||
};
|
||||
(u128::from(half(1)) << 64) | u128::from(half(2))
|
||||
}
|
||||
|
||||
/// Can the solids of `items` be drawn as a rendered image: is each painted with a solid color (or
|
||||
/// nothing) in Normal blending, with no member's opacity mask or blending mode applying to them
|
||||
/// (`masked`)? Otherwise the effect draws its shaded faces, which keep gradients, patterns, mapped
|
||||
/// graphics, masks and blending.
|
||||
pub(crate) fn takes<'a>(items: impl IntoIterator<Item = &'a vectorcraft_doc::AppearanceItem>, masked: bool) -> bool {
|
||||
use vectorcraft_doc::AppearanceItem;
|
||||
use vectorcraft_doc::color::Paint;
|
||||
!masked
|
||||
&& items.into_iter().all(|i| match i {
|
||||
AppearanceItem::Fill(f) => matches!(f.paint, Paint::Solid { .. } | Paint::None) && f.blend == Default::default(),
|
||||
AppearanceItem::Stroke(s) => matches!(s.paint, Paint::Solid { .. } | Paint::None) && s.blend == Default::default(),
|
||||
})
|
||||
}
|
||||
|
||||
/// The lights a 3D effect with parameters `p` shades its faces with: Revolve's ([`crate::revolve_options`])
|
||||
/// for Revolve, the other effects' ([`super::view_options`]) otherwise.
|
||||
pub(crate) fn lighting(id: &str, p: &serde_json::Value) -> Lighting {
|
||||
let (lights, ambient, shade) = if id == crate::REVOLVE {
|
||||
let o = crate::revolve_options(p);
|
||||
(o.active_lights(), o.ambient, o.shade)
|
||||
} else {
|
||||
let v = super::view_options(p);
|
||||
(v.active_lights(), v.ambient, v.shade)
|
||||
};
|
||||
let lit = lights.iter().any(|l| l.intensity > 0.0);
|
||||
let shadows = super::shadow::rendered_options(p, lit).is_some();
|
||||
Lighting { lights, diffusion: vec![], ambient, shade, shadows, receiver: None }
|
||||
}
|
||||
|
||||
/// The shadow settings a rendered image of a 3D effect with parameters `p` and lights `lighting`
|
||||
/// draws its shadow plane with; `None` with Shadows off or no light lighting the art.
|
||||
pub(crate) fn plane_settings(p: &serde_json::Value, lighting: &Lighting) -> Option<vectorcraft_three_d::Shadow> {
|
||||
super::shadow::rendered_options(p, lighting.lights.iter().any(|l| l.intensity > 0.0))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "rendered/tests.rs"]
|
||||
mod tests;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -25,12 +25,24 @@ pub(crate) fn options(p: &Value) -> Option<Shadow> {
|
||||
let first = crate::lighting::lights(p).and_then(|l| l.iter().next().copied());
|
||||
let intensity = first.map_or_else(|| num(p, "lightIntensity", 80.0), |l| l.intensity);
|
||||
let lit = flag(p, "shade", true) && intensity > 0.0;
|
||||
(lit && flag(p, "shadow", false)).then(|| Shadow {
|
||||
(lit && flag(p, "shadow", false)).then(|| settings(p, first))
|
||||
}
|
||||
|
||||
/// The shadow a rendered image of `p` draws, in which every light casts one: as [`options`], but on
|
||||
/// when any light lights the art (`lit`), not only the first.
|
||||
pub(crate) fn rendered_options(p: &Value, lit: bool) -> Option<Shadow> {
|
||||
let first = crate::lighting::lights(p).and_then(|l| l.iter().next().copied());
|
||||
(lit && flag(p, "shade", true) && flag(p, "shadow", false)).then(|| settings(p, first))
|
||||
}
|
||||
|
||||
/// The plane settings of `p`, with the softness of light `first` (the single light's without one).
|
||||
fn settings(p: &Value, first: Option<vectorcraft_three_d::Light>) -> Shadow {
|
||||
Shadow {
|
||||
position: ShadowPosition::parse(text(p, "shadowPosition", "behind")).unwrap_or_default(),
|
||||
distance: num(p, "shadowDistance", 0.0) / 100.0,
|
||||
bounds: num(p, "shadowBounds", 100.0) / 100.0,
|
||||
softness: first.map_or_else(|| num(p, "lightSoftness", 0.0) / 100.0, |l| l.softness),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Check the shadow settings in `p`: an error for a value out of its range or of the wrong kind.
|
||||
|
||||
@@ -398,5 +398,7 @@ fn meshes_carry_the_material() {
|
||||
let mut n = square_node();
|
||||
let Some(fx) = crate::new_effect(EXTRUDE, &json!({})) else { panic!("extrude") };
|
||||
n.appearance.effects.push(fx);
|
||||
assert!(three_d_meshes(&n).unwrap_or_default().iter().all(|m| m.material.is_default()));
|
||||
let meshes = three_d_meshes(&n).unwrap_or_else(|e| panic!("extrude: {e}"));
|
||||
assert!(!meshes.is_empty(), "extrude");
|
||||
assert!(meshes.iter().all(|m| m.material.is_default()));
|
||||
}
|
||||
@@ -356,7 +356,7 @@ fn the_shadow_cast_from_the_solids_drawn_is_the_shadow_of_solids_built_for_it()
|
||||
let (path, rule) = profile(&n).unwrap();
|
||||
vec![Profile { path, rule, items: solid_paint_sources(&n).1, opacity: 1.0, scopes: vec![] }]
|
||||
};
|
||||
let (drawn, _) = art_for(None, &n, fx, &shapes).unwrap();
|
||||
let (drawn, _) = art_for(None, &n, std::slice::from_ref(fx), &shapes, Build::Vector, &mut None).unwrap();
|
||||
let p = crate::merged_params(&fx.id, &fx.params);
|
||||
let (caster, settings, cast) = cast_shadow(&fx.id, &p, &shapes).unwrap().unwrap();
|
||||
let alone = shadow::scoped_art(n.id, &caster, settings, cast, has_masks(&shapes));
|
||||
|
||||
@@ -21,12 +21,84 @@ use crate::{GeomContext, is_geometry};
|
||||
pub(crate) const MAX_WIRE_EDGES: usize = 1_000_000;
|
||||
|
||||
/// The parameter that holds a 3D effect's render settings: an object whose `mode` is one of
|
||||
/// [`RENDER_MODES`].
|
||||
/// [`RENDER_MODES`], with the rendered image's `quality` ([`RENDER_QUALITIES`]), `resolution` and
|
||||
/// `background` ([`RENDER_BACKGROUNDS`]).
|
||||
pub const RENDER: &str = "render";
|
||||
|
||||
/// The render modes of a 3D effect: `shaded` draws the lit faces, `wireframe` the edges of every
|
||||
/// face ([`renders_wireframe`]).
|
||||
pub const RENDER_MODES: [&str; 2] = ["shaded", "wireframe"];
|
||||
/// face ([`renders_wireframe`]), and `rendered` an image of the lit solid with the shadows of its
|
||||
/// lights ([`render_settings`]).
|
||||
pub const RENDER_MODES: [&str; 3] = ["shaded", "wireframe", "rendered"];
|
||||
|
||||
/// The qualities of the rendered image, from fastest to finest: 1, 2 × 2 and 3 × 3 samples a pixel
|
||||
/// ([`RenderSettings::samples`]). VectorCraft's own values.
|
||||
pub const RENDER_QUALITIES: [&str; 3] = ["low", "medium", "high"];
|
||||
|
||||
/// What the rendered image shows where no surface is: nothing, or white.
|
||||
pub const RENDER_BACKGROUNDS: [&str; 2] = ["transparent", "white"];
|
||||
|
||||
/// The index in [`RENDER_QUALITIES`] of the quality a `render` without one takes (VectorCraft's own
|
||||
/// default).
|
||||
const DEFAULT_QUALITY: usize = 1;
|
||||
|
||||
/// The settings of a 3D effect's rendered image ([`render_settings`]).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct RenderSettings {
|
||||
/// The quality, as an index into [`RENDER_QUALITIES`] (0 low, 1 medium, 2 high).
|
||||
pub quality: usize,
|
||||
/// Pixels per inch, 1 to 2400; `None` takes Document Raster Effects Settings › Resolution.
|
||||
pub resolution: Option<f64>,
|
||||
/// A white background, which makes the image opaque; otherwise it is transparent where no
|
||||
/// surface or shadow is.
|
||||
pub white: bool,
|
||||
}
|
||||
|
||||
impl RenderSettings {
|
||||
/// The samples a pixel takes along each side at this quality: 1, 2 or 3.
|
||||
pub fn samples(&self) -> u32 {
|
||||
self.quality.min(2) as u32 + 1
|
||||
}
|
||||
}
|
||||
|
||||
/// The settings of the image 3D effect `id` with parameters `p` draws, when its `render` passes
|
||||
/// [`validate_render`] and sets `mode` to `rendered`; `None` otherwise, when the effect draws its
|
||||
/// shaded faces or its wireframe (a loaded file whose `render` breaks the rules draws shaded).
|
||||
pub fn render_settings(id: &str, p: &Value) -> Option<RenderSettings> {
|
||||
let render = p.get(RENDER).filter(|_| TAKES_RENDER.contains(&id))?;
|
||||
if check_render(render).is_err() || render.get("mode").and_then(Value::as_str) != Some("rendered") {
|
||||
return None;
|
||||
}
|
||||
let quality = render.get("quality").and_then(Value::as_str).and_then(|q| RENDER_QUALITIES.iter().position(|k| *k == q));
|
||||
Some(RenderSettings {
|
||||
quality: quality.unwrap_or(DEFAULT_QUALITY),
|
||||
resolution: render.get("resolution").and_then(Value::as_f64),
|
||||
white: render.get("background").and_then(Value::as_str) == Some("white"),
|
||||
})
|
||||
}
|
||||
|
||||
/// Does effect `fx` draw as a rendered image ([`render_settings`])?
|
||||
pub fn renders_image(fx: &Effect) -> bool {
|
||||
render_settings(&fx.id, &fx.params).is_some()
|
||||
}
|
||||
|
||||
/// The message a `render` that breaks the rules of [`validate_render`] is refused with.
|
||||
const RENDER_RULES: &str = "`render` must be an object holding only mode (shaded, wireframe or rendered), quality (low, medium or high), \
|
||||
resolution (null or a number from 1 to 2400) and background (transparent or white)";
|
||||
|
||||
/// Check one `render` value against [`RENDER_RULES`].
|
||||
fn check_render(render: &Value) -> Result<(), String> {
|
||||
let one_of = |v: &Value, list: &[&str]| v.as_str().is_some_and(|s| list.contains(&s));
|
||||
let valid = render.as_object().is_some_and(|fields| {
|
||||
fields.iter().all(|(key, value)| match key.as_str() {
|
||||
"mode" => one_of(value, &RENDER_MODES),
|
||||
"quality" => one_of(value, &RENDER_QUALITIES),
|
||||
"background" => one_of(value, &RENDER_BACKGROUNDS),
|
||||
"resolution" => value.is_null() || value.as_f64().is_some_and(|r| (1.0..=2400.0).contains(&r)),
|
||||
_ => false,
|
||||
})
|
||||
});
|
||||
if valid { Ok(()) } else { Err(RENDER_RULES.into()) }
|
||||
}
|
||||
|
||||
/// The 3D effects that take [`RENDER`]: the 3D and Materials panel's Extrude & Bevel, Revolve,
|
||||
/// Inflate and Rotate. The 3D (Classic) effects have their own Wireframe surface.
|
||||
@@ -50,17 +122,14 @@ pub(crate) fn wireframe_params(id: &str, p: &Value) -> bool {
|
||||
}
|
||||
|
||||
/// Check the render settings in 3D effect `id`'s parameters `p`: `render`, when given to one of the
|
||||
/// effects in [`TAKES_RENDER`], is an object that holds only `mode`, one of [`RENDER_MODES`] (a
|
||||
/// missing `mode` is `shaded`). The 3D (Classic) effects refuse it as a parameter they do not take.
|
||||
/// effects in [`TAKES_RENDER`], is an object that holds only `mode` (one of [`RENDER_MODES`]),
|
||||
/// `quality` (one of [`RENDER_QUALITIES`]), `resolution` (`null`, or a number from 1 to 2400 pixels
|
||||
/// per inch) and `background` (one of [`RENDER_BACKGROUNDS`]). A key left out takes its default:
|
||||
/// `shaded`, `medium`, the document's raster effects resolution and `transparent`. The 3D (Classic)
|
||||
/// effects refuse it as a parameter they do not take.
|
||||
pub(crate) fn validate_render(id: &str, p: &Value) -> Result<(), String> {
|
||||
let Some(render) = p.get(RENDER).filter(|_| TAKES_RENDER.contains(&id)) else { return Ok(()) };
|
||||
let valid = render
|
||||
.as_object()
|
||||
.is_some_and(|fields| fields.iter().all(|(key, value)| key == "mode" && value.as_str().is_some_and(|m| RENDER_MODES.contains(&m))));
|
||||
if !valid {
|
||||
return Err("`render` must be an object holding only `mode`, set to shaded or wireframe".into());
|
||||
}
|
||||
Ok(())
|
||||
check_render(render)
|
||||
}
|
||||
|
||||
/// The art a 3D effect in wireframe mode draws for object `id` in place of its shaded faces: a group
|
||||
|
||||
@@ -418,12 +418,23 @@ fn expanding_a_revolve_in_wireframe_mode_gives_the_edges() {
|
||||
assert!(art.iter().all(|(_, filled, stroke)| !filled && stroke.as_ref().is_some_and(|s| s.width == WIRE_WEIGHT)));
|
||||
}
|
||||
|
||||
/// `render` is checked before an edit: an object holding only `mode`, `shaded` or `wireframe`, and
|
||||
/// only on the panel's four effects.
|
||||
/// `render` is checked before an edit: an object holding only `mode` (shaded, wireframe or
|
||||
/// rendered), `quality` (low, medium or high), `resolution` (null or 1 to 2400) and `background`
|
||||
/// (transparent or white), and only on the panel's four effects.
|
||||
#[test]
|
||||
fn render_settings_are_validated() {
|
||||
for id in WIRE {
|
||||
for good in [json!({}), json!({"render": {}}), json!({"render": {"mode": "shaded"}}), json!({"render": {"mode": "wireframe"}})] {
|
||||
for good in [
|
||||
json!({}),
|
||||
json!({"render": {}}),
|
||||
json!({"render": {"mode": "shaded"}}),
|
||||
json!({"render": {"mode": "wireframe"}}),
|
||||
json!({"render": {"mode": "rendered"}}),
|
||||
json!({"render": {"mode": "rendered", "quality": "high", "resolution": 300, "background": "white"}}),
|
||||
json!({"render": {"mode": "rendered", "quality": "low", "resolution": null, "background": "transparent"}}),
|
||||
json!({"render": {"resolution": 1}}),
|
||||
json!({"render": {"resolution": 2400}}),
|
||||
] {
|
||||
assert_eq!(crate::validate_three_d_params(id, &good), Ok(()), "{id} {good}");
|
||||
}
|
||||
for bad in [
|
||||
@@ -431,10 +442,20 @@ fn render_settings_are_validated() {
|
||||
json!({"render": null}),
|
||||
json!({"render": {"mode": "raytrace"}}),
|
||||
json!({"render": {"mode": true}}),
|
||||
json!({"render": {"mode": "wireframe", "quality": "high"}}),
|
||||
json!({"render": {"mode": "rendered", "quality": "ultra"}}),
|
||||
json!({"render": {"mode": "rendered", "resolution": 0.5}}),
|
||||
json!({"render": {"mode": "rendered", "resolution": 2401}}),
|
||||
json!({"render": {"mode": "rendered", "resolution": "300"}}),
|
||||
json!({"render": {"mode": "rendered", "background": "black"}}),
|
||||
json!({"render": {"mode": "rendered", "samples": 4}}),
|
||||
] {
|
||||
let e = crate::validate_three_d_params(id, &bad).unwrap_err();
|
||||
assert_eq!(e, "`render` must be an object holding only `mode`, set to shaded or wireframe", "{id} {bad}");
|
||||
assert_eq!(
|
||||
e,
|
||||
"`render` must be an object holding only mode (shaded, wireframe or rendered), quality (low, medium or high), resolution (null \
|
||||
or a number from 1 to 2400) and background (transparent or white)",
|
||||
"{id} {bad}"
|
||||
);
|
||||
}
|
||||
// The command check on the object refuses it too.
|
||||
let n = solid_square(id, json!({}));
|
||||
|
||||
@@ -114,6 +114,8 @@ apple-native-keyring-store = { version = "1.0.2", features = ["keychain"] }
|
||||
zbus-secret-service-keyring-store = { version = "1.0.1", features = ["crypto-rust"] }
|
||||
|
||||
[dev-dependencies]
|
||||
# DWG files for the `.dwg` open and place tests, written from DXF by craft-dwg.
|
||||
craft-dwg = { workspace = true }
|
||||
# JPEG XL files for the `.jxl` open and place tests.
|
||||
zune-jpegxl = { workspace = true }
|
||||
zune-core = { workspace = true }
|
||||
|
||||
@@ -298,7 +298,7 @@ fn star(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pie,
|
||||
arc_mode,
|
||||
};
|
||||
insert_custom(s, "Star", None, cs)
|
||||
insert_custom(s, "Star", cs.to_live_shape(), cs)
|
||||
}
|
||||
|
||||
fn spiral(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -144,6 +144,68 @@ fn shape_of(s: &Session, id: NodeId) -> CustomShape {
|
||||
CustomShape::read(s.doc().unwrap().doc.node(id).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn configuring_a_live_star_keeps_its_live_shape() {
|
||||
let mut s = new_session();
|
||||
for cmd in ["shape.star", "addon.shapes.star"] {
|
||||
let id = id_of(&mut s, cmd, json!({"cx": 50.0, "cy": 50.0, "radius1": 40.0, "radius2": 20.0, "points": 5}));
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
assert!(matches!(&n.kind, NodeKind::Path { live: Some(live), .. } if matches!(live.as_ref(), LiveShape::Star { points: 5, .. })));
|
||||
assert!(matches!(CustomShape::read(n), Some(CustomShape::Polygon { sides: 5, spoke_ratio: Some(_), .. })));
|
||||
|
||||
s.execute("addon.shapes.configure", &json!({"ids": [id.0], "sides": 7})).unwrap();
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
let NodeKind::Path { path, live: Some(live), .. } = &n.kind else { panic!("expected live star") };
|
||||
assert!(matches!(live.as_ref(), LiveShape::Star { points: 7, .. }));
|
||||
assert_eq!(path, &live.to_path());
|
||||
|
||||
s.execute("addon.shapes.configure", &json!({"ids": [id.0], "spokeRatio": 0.4})).unwrap();
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
let NodeKind::Path { path, live: Some(live), .. } = &n.kind else { panic!("expected live star") };
|
||||
assert!(matches!(live.as_ref(), LiveShape::Star { points: 7, .. }));
|
||||
assert!((live.star_ratio().unwrap() - 0.4).abs() < 1e-9);
|
||||
assert_eq!(path, &live.to_path());
|
||||
}
|
||||
}
|
||||
|
||||
/// A live star with a ratio below 0.01, which `object.setLiveShape` accepts, keeps its inner
|
||||
/// radius and stays live when it is configured without a ratio.
|
||||
#[test]
|
||||
fn configuring_a_live_star_keeps_a_small_ratio() {
|
||||
let mut s = new_session();
|
||||
let id = id_of(&mut s, "shape.star", json!({"cx": 50.0, "cy": 50.0, "radius1": 60.0, "radius2": 30.0, "points": 5}));
|
||||
s.execute("object.setLiveShape", &json!({"id": id.0, "ratio": 0.0001})).unwrap();
|
||||
s.execute("addon.shapes.configure", &json!({"ids": [id.0], "sides": 6})).unwrap();
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
let NodeKind::Path { path, live: Some(live), .. } = &n.kind else { panic!("expected live star") };
|
||||
assert!(matches!(live.as_ref(), LiveShape::Star { r1, r2, points: 6, .. } if *r1 == 60.0 && (r2 - 0.006).abs() < 1e-9), "{live:?}");
|
||||
assert_eq!(path, &live.to_path());
|
||||
}
|
||||
|
||||
/// Angles configured on a whole shape stay live and are kept for a later arc mode.
|
||||
#[test]
|
||||
fn angles_configured_on_a_whole_shape_are_kept_for_a_later_arc_mode() {
|
||||
let mut s = new_session();
|
||||
let shapes = [
|
||||
("shape.star", json!({"cx": 50.0, "cy": 50.0, "radius1": 40.0, "radius2": 20.0, "points": 5})),
|
||||
("shape.polygon", json!({"cx": 50.0, "cy": 50.0, "radius": 40.0, "sides": 5})),
|
||||
("shape.rectangle", json!({"x": 0.0, "y": 0.0, "width": 100.0, "height": 50.0})),
|
||||
("shape.ellipse", json!({"x": 0.0, "y": 0.0, "width": 80.0, "height": 60.0})),
|
||||
];
|
||||
for (cmd, p) in shapes {
|
||||
let id = id_of(&mut s, cmd, p);
|
||||
s.execute("addon.shapes.configure", &json!({"ids": [id.0], "startAngle": 0.0, "endAngle": 90.0})).unwrap();
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
assert!(matches!(&n.kind, NodeKind::Path { live: Some(_), .. }), "{cmd} stays live");
|
||||
s.execute("addon.shapes.configure", &json!({"ids": [id.0], "arcMode": "pie"})).unwrap();
|
||||
let pie = match CustomShape::read(s.doc().unwrap().doc.node(id).unwrap()) {
|
||||
Some(CustomShape::Rectangle { pie, .. } | CustomShape::Ellipse { pie, .. } | CustomShape::Polygon { pie, .. }) => pie,
|
||||
other => panic!("{cmd}: {other:?}"),
|
||||
};
|
||||
assert_eq!(pie, (0.0, 90.0), "{cmd}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `cmd` with `p`, which must fail with `msg` and leave the document and its history as they
|
||||
/// were.
|
||||
fn refused(s: &mut Session, cmd: &str, p: serde_json::Value, msg: &str) {
|
||||
|
||||
@@ -903,7 +903,7 @@ pub struct SymbolOptions {
|
||||
|
||||
impl SymbolOptions {
|
||||
/// The options `d` keeps for symbol `name`.
|
||||
fn of(d: &Document, name: &str) -> Self {
|
||||
pub(in crate::cmd) fn of(d: &Document, name: &str) -> Self {
|
||||
Self {
|
||||
size: stored_natural_size(d, name),
|
||||
registration: d.symbol_registration(name),
|
||||
@@ -914,7 +914,7 @@ impl SymbolOptions {
|
||||
}
|
||||
|
||||
/// Make them the options of `d`'s symbol `name`.
|
||||
fn give(&self, d: &mut Document, name: &str) {
|
||||
pub(in crate::cmd) fn give(&self, d: &mut Document, name: &str) {
|
||||
set_natural_size(d, name, self.size);
|
||||
d.set_symbol_registration(name, self.registration);
|
||||
d.set_symbol_export_type(name, self.export_type);
|
||||
|
||||
@@ -10,9 +10,12 @@
|
||||
//! custom character sets:
|
||||
//! <https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=348>.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::text::{COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, CUSTOM_CHARS_MAX, CUSTOM_SETS_MAX};
|
||||
use vectorcraft_doc::{CharClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet};
|
||||
use vectorcraft_doc::{CharClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet, Document, Node, NodeKind};
|
||||
use vectorcraft_text::FontDb;
|
||||
|
||||
use super::fileio::{read_file_head, write_file};
|
||||
@@ -77,6 +80,166 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
]
|
||||
}
|
||||
|
||||
/// Every stored family name, including regeneration settings and retained style defaults.
|
||||
/// Planning reads a private clone so gathering names never changes the destination.
|
||||
fn family_names(d: &Document) -> Result<BTreeSet<String>> {
|
||||
let mut view = d.clone();
|
||||
let mut names = BTreeSet::new();
|
||||
let mut note = |family: &mut String| {
|
||||
names.insert(family.to_lowercase());
|
||||
};
|
||||
super::textstyles::each_text_mut(&mut view, &mut |text| {
|
||||
for run in &mut text.runs {
|
||||
note(&mut run.style.font_family);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
for style in view.char_styles.iter_mut().chain(view.para_styles.iter_mut()) {
|
||||
if let Some(Value::String(family)) = style.attrs.get_mut("font_family") {
|
||||
note(family);
|
||||
}
|
||||
}
|
||||
let mut graphs = Vec::new();
|
||||
view.visit_stored(|node, _| {
|
||||
if node.extras().graph.is_some() {
|
||||
graphs.push(node.id);
|
||||
}
|
||||
});
|
||||
for id in graphs {
|
||||
if let Some(node) = view.stored_node_mut(id) {
|
||||
graph_families(node, &mut note);
|
||||
}
|
||||
}
|
||||
fn brush_graphs(node: &mut Node, note: &mut impl FnMut(&mut String)) {
|
||||
graph_families(node, note);
|
||||
if let Some(mask) = node.extras_if_any().and_then(|extras| extras.mask.as_mut()) {
|
||||
brush_graphs(Arc::make_mut(&mut mask.art), note);
|
||||
}
|
||||
for child in node.children_mut().into_iter().flatten() {
|
||||
brush_graphs(Arc::make_mut(child), note);
|
||||
}
|
||||
}
|
||||
for art in vectorcraft_brush::library(&view).iter_mut().flat_map(|brush| brush.art_mut()) {
|
||||
brush_graphs(art, &mut note);
|
||||
}
|
||||
Ok(names)
|
||||
}
|
||||
|
||||
fn graph_families(node: &mut Node, visit: &mut impl FnMut(&mut String)) {
|
||||
if let Some(graph) = node.extras_if_any().and_then(|extras| extras.graph.as_deref_mut()) {
|
||||
let labels = &mut graph.label_styles;
|
||||
for style in [&mut labels.values, &mut labels.categories, &mut labels.legend].into_iter().flatten() {
|
||||
visit(&mut style.font_family);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Family fields held directly by one node; the adoption walker owns tree/resource traversal.
|
||||
pub(super) fn node_families(node: &mut Node, visit: &mut impl FnMut(&mut String)) {
|
||||
if let NodeKind::Text(text) = &mut node.kind {
|
||||
for run in &mut text.runs {
|
||||
visit(&mut run.style.font_family);
|
||||
}
|
||||
}
|
||||
graph_families(node, visit);
|
||||
}
|
||||
|
||||
/// A fully checked incoming-only rename map and the destination's prospective definitions.
|
||||
pub(super) struct CompositeImport {
|
||||
names: BTreeMap<String, String>,
|
||||
pub(super) combined: Vec<CompositeFont>,
|
||||
}
|
||||
|
||||
impl CompositeImport {
|
||||
pub(super) fn rename(&self, family: &mut String) -> bool {
|
||||
if let Some(name) = self.names.get(&family.to_lowercase()) {
|
||||
let changed = family.as_str() != name.as_str();
|
||||
*family = name.clone();
|
||||
changed
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn composite_alias(base: &str, reserved: &BTreeSet<String>, cmd: &str) -> Result<String> {
|
||||
let db = FontDb::global();
|
||||
let mut number = 2_u64;
|
||||
loop {
|
||||
let suffix = format!(" {number}");
|
||||
let stem: String = base.chars().take(COMPOSITE_NAME_MAX.saturating_sub(suffix.chars().count())).collect();
|
||||
let name = format!("{}{suffix}", stem.trim_end());
|
||||
if CompositeFont::clean_name(&name).as_deref() == Some(name.as_str())
|
||||
&& !reserved.contains(&name.to_lowercase())
|
||||
&& !db.has_installed_family(&name)
|
||||
{
|
||||
return Ok(name);
|
||||
}
|
||||
number = number.checked_add(1).ok_or_else(|| bad(cmd, "no free name for a placed composite font"))?;
|
||||
}
|
||||
}
|
||||
|
||||
/// Plan used incoming definitions before changing either document or the font database.
|
||||
/// Keep existing meanings even for an uninstalled family that destination art still names.
|
||||
pub(super) fn plan_import(source: Vec<CompositeFont>, source_families: BTreeSet<String>, target: &Document, cmd: &str) -> Result<CompositeImport> {
|
||||
if source.len() > COMPOSITE_FONTS_MAX || target.composite_fonts.len() > COMPOSITE_FONTS_MAX {
|
||||
return Err(bad(cmd, format!("a document keeps at most {COMPOSITE_FONTS_MAX} composite fonts")));
|
||||
}
|
||||
let mut source_names = BTreeSet::new();
|
||||
for font in &source {
|
||||
font.check().map_err(|why| bad(cmd, why))?;
|
||||
if !source_names.insert(font.name.to_lowercase()) {
|
||||
return Err(bad(cmd, format!("two incoming composite fonts are named `{}`", font.name)));
|
||||
}
|
||||
}
|
||||
let target_families = family_names(target)?;
|
||||
let mut target_taken = target_families.clone();
|
||||
for font in target.composite_fonts.iter() {
|
||||
target_taken.insert(font.name.to_lowercase());
|
||||
target_taken.extend(font.part_fonts().map(str::to_lowercase));
|
||||
}
|
||||
let mut reserved = source_families;
|
||||
reserved.extend(target_families);
|
||||
for font in source.iter().chain(target.composite_fonts.iter()) {
|
||||
reserved.insert(font.name.to_lowercase());
|
||||
reserved.extend(font.part_fonts().map(str::to_lowercase));
|
||||
}
|
||||
let db = FontDb::global();
|
||||
let mut names = BTreeMap::new();
|
||||
let mut combined = target.composite_fonts.to_vec();
|
||||
for font in source {
|
||||
let equivalent = |other: &&CompositeFont| other.parts == font.parts && other.custom == font.custom;
|
||||
let mut reused = CompositeFont::named(&target.composite_fonts, &font.name).filter(equivalent);
|
||||
let needs_alias = reused.is_none() && (target_taken.contains(&font.name.to_lowercase()) || db.has_installed_family(&font.name));
|
||||
if needs_alias {
|
||||
// A repeated import reuses its already-installed equal alias.
|
||||
reused = target.composite_fonts.iter().find(equivalent);
|
||||
}
|
||||
let name = match reused {
|
||||
Some(other) => other.name.clone(),
|
||||
None if needs_alias => composite_alias(&font.name, &reserved, cmd)?,
|
||||
None => font.name.clone(),
|
||||
};
|
||||
reserved.insert(name.to_lowercase());
|
||||
names.insert(font.name.to_lowercase(), name.clone());
|
||||
if reused.is_none() {
|
||||
combined.push(CompositeFont { name, ..font });
|
||||
}
|
||||
}
|
||||
// A source document may currently lend fonts to the database. Validate the prospective
|
||||
// document, not composite names temporarily registered by a different document.
|
||||
if combined.len() > COMPOSITE_FONTS_MAX {
|
||||
return Err(bad(cmd, format!("a document keeps at most {COMPOSITE_FONTS_MAX} composite fonts")));
|
||||
}
|
||||
if let Some(font) = combined.iter().find(|font| db.has_installed_family(&font.name)) {
|
||||
return Err(bad(cmd, format!("`{}` is the name of an installed font", font.name)));
|
||||
}
|
||||
if CompositeFont::usable(&combined).is_some() {
|
||||
return Err(bad(cmd, "the composite fonts in the placed art and document cannot stand together"));
|
||||
}
|
||||
Ok(CompositeImport { names, combined })
|
||||
}
|
||||
|
||||
/// Register the active document's composite fonts in the font database, and remove the ones the
|
||||
/// other open documents (or an earlier active document) defined. Run after each command and when
|
||||
/// another document takes the front, so an undo, a revert, an opened or closed file or a document
|
||||
|
||||
@@ -65,7 +65,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Star",
|
||||
[],
|
||||
None,
|
||||
"{cx, cy, radius1, radius2, onLayer?: layer id|null (draw normally on this layer), points=5, rotation?: deg clockwise (0: a point straight up)} → {id}",
|
||||
"{cx, cy, radius1, radius2, onLayer?: layer id|null (draw normally on this layer), points=5, rotation?: deg clockwise (0: a point straight up)} → {id}: a live star whose points and ratio object.setLiveShape changes",
|
||||
has_doc,
|
||||
star
|
||||
),
|
||||
@@ -655,14 +655,11 @@ fn star(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let r2 = f64_or(p, "radius2", r1 / 2.0).abs();
|
||||
let n = count_or(p, "points", 5, "shape.star")?.clamp(2, 1000) as u32;
|
||||
let rot = f64_or(p, "rotation", 0.0);
|
||||
let turn = vectorcraft_geom::rotate_deg(rot);
|
||||
// A quarter or whole turn (a Constrain Angle of 90°, say) turns the upright star exactly.
|
||||
let path = if rot != 0.0 && turn.as_coeffs()[..4].iter().all(|c| c.fract() == 0.0) {
|
||||
shapes::star(Point::ZERO, r1, r2, n, 0.0).transformed(Affine::translate(c.to_vec2()) * turn)
|
||||
} else {
|
||||
shapes::star(c, r1, r2, n, rot)
|
||||
};
|
||||
add_art_turned(s, "Star", path_kind(path, None), constrained_turn(s, rot))
|
||||
let xf = Affine::translate(c.to_vec2()) * vectorcraft_geom::rotate_deg(rot);
|
||||
// The star stays live: its point count and ratio can change later (`object.setLiveShape`).
|
||||
let live = LiveShape::Star { r1, r2, points: n, xf, radii: vec![], kinds: vec![], radii_relative: false };
|
||||
add_art_turned(s, "Star", path_kind(live.to_path(), Some(live)), constrained_turn(s, rot))
|
||||
}
|
||||
|
||||
fn line(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -289,6 +289,15 @@ fn refresh_deferred(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"refreshed": counts.refreshed, "stillDeferred": counts.still_deferred, "failed": counts.failed}))
|
||||
}
|
||||
|
||||
/// Report the first rendered 3D effect that keeps its shaded faces after an edit.
|
||||
fn with_render_warning(s: &Session, ids: &[NodeId], mut out: Value) -> Result<Value> {
|
||||
let d = &s.doc()?.doc;
|
||||
if let Some(message) = ids.iter().filter_map(|id| d.node(*id)).find_map(|n| effects::rendered_warning(d, n)) {
|
||||
out["warning"] = json!(message);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn ids_json(ids: &[NodeId]) -> Value {
|
||||
json!(ids.iter().map(|i| i.0).collect::<Vec<_>>())
|
||||
}
|
||||
@@ -569,7 +578,7 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let landed = first.and_then(|n| at.effects_item(&n.appearance, C).ok().flatten());
|
||||
let index = first.and_then(|n| n.appearance.effects_at(landed)).map_or(0, |fx| fx.len().saturating_sub(1));
|
||||
Ok(json!({ "ids": ids_json(&ids), "index": index, "item": landed }))
|
||||
with_render_warning(s, &ids, json!({ "ids": ids_json(&ids), "index": index, "item": landed }))
|
||||
}
|
||||
|
||||
/// The selected objects a Pathfinder effect should group before it applies: it combines the
|
||||
@@ -891,7 +900,7 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids: Vec<&str> =
|
||||
targets.iter().filter_map(|&(id, at, index)| d.node(id)?.appearance.effects_at(at)?.get(index).map(|e| e.id.as_str())).collect();
|
||||
if !ids.is_empty() && ids.iter().all(|id| *id == to) {
|
||||
return Ok(json!({ "ids": [] }));
|
||||
return with_render_warning(s, &targets.iter().map(|t| t.0).collect::<Vec<_>>(), json!({ "ids": [] }));
|
||||
}
|
||||
}
|
||||
// Pathfinder effects given the values they already evaluate with, and nothing else to change,
|
||||
@@ -900,7 +909,7 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let d = &s.doc()?.doc;
|
||||
let fx: Vec<&Effect> = targets.iter().filter_map(|&(id, at, index)| d.node(id)?.appearance.effects_at(at)?.get(index)).collect();
|
||||
if !fx.is_empty() && fx.iter().all(|e| pathfinder_edit_changes_nothing(e, ¶ms)) {
|
||||
return Ok(json!({ "ids": [] }));
|
||||
return with_render_warning(s, &targets.iter().map(|t| t.0).collect::<Vec<_>>(), json!({ "ids": [] }));
|
||||
}
|
||||
}
|
||||
// An SVG filter is named by its id: another filter renames the effect.
|
||||
@@ -947,7 +956,7 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let d = &s.doc()?.doc;
|
||||
let fx: Vec<&Effect> = targets.iter().filter_map(|&(id, at, index)| d.node(id)?.appearance.effects_at(at)?.get(index)).collect();
|
||||
if !fx.is_empty() && fx.iter().all(|e| three_d_edit_changes_nothing(e, ¶ms)) {
|
||||
return Ok(json!({ "ids": [] }));
|
||||
return with_render_warning(s, &targets.iter().map(|t| t.0).collect::<Vec<_>>(), json!({ "ids": [] }));
|
||||
}
|
||||
}
|
||||
// The effect edited, when every target has one at `index` and all are the same: a dialog's
|
||||
@@ -982,7 +991,7 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
true
|
||||
})
|
||||
})?;
|
||||
Ok(json!({ "ids": ids_json(&ids) }))
|
||||
with_render_warning(s, &ids, json!({ "ids": ids_json(&ids) }))
|
||||
}
|
||||
|
||||
/// Does effect `id` take a `bevel` (Extrude & Bevel, Extrude & Bevel (Classic)), which may be a
|
||||
|
||||
@@ -74,7 +74,7 @@ use serde_json::{Value, json};
|
||||
|
||||
pub(crate) use action_batch::action_step;
|
||||
pub use action_batch::batch_overwrites_one_file;
|
||||
pub use dxf::{UNSUPPORTED, Unsupported, unsupported};
|
||||
pub use dxf::{UNSUPPORTED, Unsupported, unsupported, write_hint};
|
||||
pub use encode::{
|
||||
ARTBOARD_PARAMS, ArtboardPick, Encoded, Note, NoteKind, encode, encode_all, encode_with_notes, encode_with_warnings, export_art_bounds,
|
||||
note_texts,
|
||||
@@ -246,6 +246,8 @@ mod tests_svgimport;
|
||||
#[cfg(test)]
|
||||
mod tests_eps;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests_dwgimport;
|
||||
#[cfg(test)]
|
||||
mod tests_dxfimport;
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -126,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"File Formats",
|
||||
[],
|
||||
None,
|
||||
"{} → {formats: [{id, label, extensions, mime, read, write, raster, options: {name: {type, default, description}}, plugin?: the id of the exporter plug-in (write only) or importer plug-in (read only) that adds the format (its id is plugin.<plug-in id>; see plugin.list), place?: true (an importer's format whose files file.place also reads, see file.place's importer)}], readable: [id…], writable: [id…], openExtensions: [ext…] (the importers' extensions that no built-in format reads included), unsupported: [{id, label, extensions, hint}] (formats asked for that can be neither opened nor written, such as DWG and PageMaker, with what to use instead)}",
|
||||
"{} → {formats: [{id, label, extensions, mime, read, write, raster, options: {name: {type, default, description}}, plugin?: the id of the exporter plug-in (write only) or importer plug-in (read only) that adds the format (its id is plugin.<plug-in id>; see plugin.list), place?: true (an importer's format whose files file.place also reads, see file.place's importer)}], readable: [id…], writable: [id…], openExtensions: [ext…] (the importers' extensions that no built-in format reads included), unsupported: [{id, label, extensions, hint}] (formats asked for that can be neither opened nor written, such as PageMaker, with what to use instead)}",
|
||||
always,
|
||||
formats
|
||||
),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! DXF export for every DXF path (`document.export {format: dxf}`, `document.exportDxf`, Export As
|
||||
//! → DXF Options): the options parsed from the params, one drawing per artboard with Use
|
||||
//! Artboards, and the formats that can't be written (DWG, PageMaker) with what to use instead.
|
||||
//! Artboards, and the formats that can't be written (DWG, which opens, and PageMaker) with what to
|
||||
//! use instead.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -99,20 +100,12 @@ pub struct Unsupported {
|
||||
}
|
||||
|
||||
/// Formats people ask for that VectorCraft doesn't read or write. Append-only.
|
||||
pub const UNSUPPORTED: &[Unsupported] = &[
|
||||
Unsupported {
|
||||
id: "dwg",
|
||||
label: "DWG",
|
||||
extensions: &["dwg"],
|
||||
hint: "DWG is not available (no openly licensed writer exists): export DXF instead, which CAD apps open",
|
||||
},
|
||||
Unsupported {
|
||||
id: "pmd",
|
||||
label: "PageMaker",
|
||||
extensions: &["pmd"],
|
||||
hint: "PageMaker (.pmd) is not supported: open the layout in PageMaker and export PDF or EPS, or place a PDF export here",
|
||||
},
|
||||
];
|
||||
pub const UNSUPPORTED: &[Unsupported] = &[Unsupported {
|
||||
id: "pmd",
|
||||
label: "PageMaker",
|
||||
extensions: &["pmd"],
|
||||
hint: "PageMaker (.pmd) is not supported: open the layout in PageMaker and export PDF or EPS, or place a PDF export here",
|
||||
}];
|
||||
|
||||
/// The unsupported format an id or extension (any case, leading dot allowed) names.
|
||||
pub fn unsupported(id_or_ext: &str) -> Option<&'static Unsupported> {
|
||||
@@ -120,6 +113,16 @@ pub fn unsupported(id_or_ext: &str) -> Option<&'static Unsupported> {
|
||||
UNSUPPORTED.iter().find(|u| u.id == k || u.extensions.contains(&k.as_str()))
|
||||
}
|
||||
|
||||
/// Formats VectorCraft opens but doesn't write, with what to export instead.
|
||||
const READ_ONLY_HINTS: &[(&str, &str)] = &[("dwg", "DWG files open but can't be written: export DXF instead, which CAD apps open")];
|
||||
|
||||
/// What to write instead of the format an id or extension (any case, leading dot allowed) names,
|
||||
/// when that format can't be written: an unsupported format's hint, or a read-only one's (DWG).
|
||||
pub fn write_hint(id_or_ext: &str) -> Option<&'static str> {
|
||||
let k = id_or_ext.trim_start_matches('.').to_ascii_lowercase();
|
||||
unsupported(&k).map(|u| u.hint).or_else(|| READ_ONLY_HINTS.iter().find(|(id, _)| *id == k).map(|(_, hint)| *hint))
|
||||
}
|
||||
|
||||
impl Unsupported {
|
||||
pub fn to_json(&self) -> Value {
|
||||
json!({ "id": self.id, "label": self.label, "extensions": self.extensions, "hint": self.hint })
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Opening and placing DXF drawings: the `dxf` options `document.open` and `file.place` read
|
||||
//! Opening and placing DXF and DWG drawings: the `dxf` options `document.open` and `file.place` read
|
||||
//! (layout, scale or fit, lineweights, centring, merged layers) and `document.dxfInfo` (layouts,
|
||||
//! layers, units) for the DXF Import Options dialog.
|
||||
|
||||
@@ -16,7 +16,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"DXF Info",
|
||||
[],
|
||||
None,
|
||||
"{path} or {name?, dataBase64} what a DXF drawing holds → {version (2018, R12…), units (its drawing unit: Millimeters, Inches, Unitless…), layouts: [\"Model\", paper layouts…], layers: [name…], unit, scale (the default ratio: 1 unit = scale drawing units, the drawing at 1:1)}; a DWG answers an error saying to save it as DXF",
|
||||
"{path} or {name?, dataBase64} what a DXF or DWG drawing holds → {version (2018, R12…; a DWG's is that of the DXF it converts to), units (its drawing unit: Millimeters, Inches, Unitless…), layouts: [\"Model\", paper layouts…], layers: [name…], unit, scale (the default ratio: 1 unit = scale drawing units, the drawing at 1:1)}",
|
||||
always,
|
||||
dxf_info
|
||||
)]
|
||||
@@ -70,7 +70,7 @@ pub(super) fn options(cmd: &str, p: Option<&Value>) -> Result<ImportOptions> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Import a DXF drawing → the document and import notes.
|
||||
/// Import a DXF or DWG drawing → the document and import notes.
|
||||
pub(super) fn import(bytes: &[u8], o: &ImportOptions) -> Result<(Document, Vec<String>)> {
|
||||
let r = vectorcraft_cad::import(bytes, o).map_err(err)?;
|
||||
Ok((r.document, r.warnings))
|
||||
|
||||
@@ -561,6 +561,9 @@ pub const FORMATS: &[Format] = &[
|
||||
// Layered raster `.pcraft` documents, read by `pcraftread` as one image: the full-size
|
||||
// composite, the layers combined, or the preview with a note. Exports don't write them.
|
||||
reader("pcraft", "PCRAFT", &["pcraft"], "application/x-pcraft", true),
|
||||
// DWG drawings, converted to DXF by craft-dwg (`vectorcraft_cad::dwg`) and read by the DXF
|
||||
// reader with the DXF import options. Exports don't write them.
|
||||
reader("dwg", "DWG", &["dwg"], "image/vnd.dwg", false),
|
||||
];
|
||||
|
||||
/// Every extension `document.open` reads (the "All readable files" filter of open dialogs).
|
||||
@@ -622,6 +625,7 @@ pub const OPEN_EXTS: &[&str] = &[
|
||||
"cdt",
|
||||
"cmx",
|
||||
"pcraft",
|
||||
"dwg",
|
||||
];
|
||||
|
||||
/// Extensions in [`OPEN_EXTS`] the packaging declares no type for: Photoshop documents belong to
|
||||
@@ -629,11 +633,11 @@ pub const OPEN_EXTS: &[&str] = &[
|
||||
/// `.epsf`, `.ps`, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF, JPEG XL, `.cdr` or `.cmx` type, nor one for the `.pns`, `.dib` and `.rle` names of
|
||||
/// PNG and BMP files (File › Open and Place still read them all). On Linux the desktop entry's EPS
|
||||
/// type (shared-mime-info's) also covers `.epsf`, so file managers offer VectorCraft for it.
|
||||
/// The packaging declares no type for HP-GL plot files, PICT pictures or layered raster `.pcraft`
|
||||
/// documents either.
|
||||
/// The packaging declares no type for HP-GL plot files, PICT pictures, layered raster `.pcraft`
|
||||
/// documents or DWG drawings either.
|
||||
pub const UNASSOCIATED_EXTS: &[&str] = &[
|
||||
"psd", "pdd", "psb", "epsf", "ps", "pns", "dib", "rle", "tga", "vda", "icb", "vst", "pcx", "pxr", "jpf", "jpx", "jp2", "j2k", "j2c", "jpc",
|
||||
"heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", "pcraft",
|
||||
"heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", "pcraft", "dwg",
|
||||
];
|
||||
|
||||
/// The extension that picks each writable format when exporting (the format's first; PNG-8 shares
|
||||
@@ -724,6 +728,7 @@ pub const PLACE_EXTS: &[&str] = &[
|
||||
"cdt",
|
||||
"cmx",
|
||||
"pcraft",
|
||||
"dwg",
|
||||
"txt",
|
||||
"rtf",
|
||||
"docx",
|
||||
@@ -1087,6 +1092,8 @@ pub fn writable_format(format_param: Option<&str>, path: Option<&str>) -> std::r
|
||||
Ok(f)
|
||||
} else if TEMPLATE_FORMATS.contains(&f.id) {
|
||||
Err(format!("{} files are written by file.saveAsTemplate", f.label))
|
||||
} else if let Some(hint) = super::dxf::write_hint(f.id) {
|
||||
Err(hint.to_string())
|
||||
} else {
|
||||
Err(format!("{} files can be opened but not written (see document.formats)", f.label))
|
||||
}
|
||||
|
||||
@@ -47,12 +47,12 @@ impl Loaded {
|
||||
/// PDF, an EPS or `.ai` without ruler units, a raster image, a metafile, an Affinity file or
|
||||
/// what an importer plug-in reads, as the reference app opens such files (#5820). A native
|
||||
/// document (also one that an SVG, PDF, `.ai` or EPS file carries, `restored`), an SVG (the
|
||||
/// units of its root's size, pixels when it gives none), a DXF drawing (the unit it was read
|
||||
/// in) and a `.ai` or EPS with ruler units keep theirs. Only the units the document shows
|
||||
/// units of its root's size, pixels when it gives none), a DXF or DWG drawing (the unit it was
|
||||
/// read in) and a `.ai` or EPS with ruler units keep theirs. Only the units the document shows
|
||||
/// change, not its art.
|
||||
pub(crate) fn with_unit_prefs(mut self, prefs: &Prefs) -> Self {
|
||||
let records_units =
|
||||
self.restored || self.doc.units_from_file || matches!(self.format.id, "vectorcraft" | "template" | "svg" | "svgz" | "dxf");
|
||||
self.restored || self.doc.units_from_file || matches!(self.format.id, "vectorcraft" | "template" | "svg" | "svgz" | "dxf" | "dwg");
|
||||
if !records_units {
|
||||
self.doc.units = crate::units::pref_unit(&prefs.units_general);
|
||||
}
|
||||
@@ -125,6 +125,9 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> {
|
||||
if vectorcraft_cad::is_dxf(bytes) {
|
||||
return format("dxf");
|
||||
}
|
||||
if vectorcraft_cad::is_dwg(bytes) {
|
||||
return format("dwg");
|
||||
}
|
||||
if let Some(kind) = vectorcraft_metafile::sniff(bytes) {
|
||||
return format(kind.id());
|
||||
}
|
||||
@@ -560,7 +563,8 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
}
|
||||
read
|
||||
}
|
||||
"dxf" => {
|
||||
// A DWG drawing is read as the DXF craft-dwg converts it to.
|
||||
"dxf" | "dwg" => {
|
||||
let (doc, warnings) = super::dxfimport::import(bytes, &opts.dxf)?;
|
||||
(doc, warnings, false)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
//! DWG through the commands: `document.open`, `document.dxfInfo` and File → Place read a DWG
|
||||
//! drawing as the DXF it converts to, with the DXF options; DWG is in the format table as read
|
||||
//! only, and exporting one says to write DXF. craft-dwg reads and writes DWG everywhere but wasm32
|
||||
//! and FreeBSD on aarch64.
|
||||
#![cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Node, NodeKind};
|
||||
|
||||
use super::tests_dxfimport::plan;
|
||||
use super::*;
|
||||
|
||||
fn b64(bytes: &[u8]) -> String {
|
||||
vectorcraft_format::base64_encode(bytes)
|
||||
}
|
||||
|
||||
/// The DXF test drawing as a DWG 2004 file, written by craft-dwg.
|
||||
fn plan_dwg() -> Vec<u8> {
|
||||
vectorcraft_cad::dwg::allow_in_process();
|
||||
craft_dwg::dxf_to_dwg_as(&plan(), "AC1018").unwrap()
|
||||
}
|
||||
|
||||
fn open(s: &mut Session, name: &str, bytes: &[u8], extra: Value) -> crate::Result<Value> {
|
||||
let mut p = json!({"name": name, "dataBase64": b64(bytes)});
|
||||
if let (Some(p), Value::Object(e)) = (p.as_object_mut(), extra) {
|
||||
p.extend(e);
|
||||
}
|
||||
s.execute("document.open", &p)
|
||||
}
|
||||
|
||||
fn layer_names(s: &Session) -> Vec<String> {
|
||||
s.doc().unwrap().doc.layers.iter().filter_map(|l| l.name.clone()).collect()
|
||||
}
|
||||
|
||||
fn leaves(s: &Session) -> Vec<Node> {
|
||||
let mut out = vec![];
|
||||
s.doc().unwrap().doc.walk(|n| {
|
||||
if n.children().is_none() {
|
||||
out.push(n.clone());
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_open_reads_a_dwg_drawing_as_its_dxf() {
|
||||
let mut s = Session::new();
|
||||
open(&mut s, "plan.dxf", &plan(), json!({})).unwrap();
|
||||
let (want_layers, want_board, want_leaves) = (layer_names(&s), s.doc().unwrap().doc.artboards[0].rect, leaves(&s).len());
|
||||
let r = open(&mut s, "plan.dwg", &plan_dwg(), json!({})).unwrap();
|
||||
assert_eq!((r["format"].as_str(), r["title"].as_str()), (Some("dwg"), Some("plan.dwg")));
|
||||
assert_eq!(layer_names(&s), want_layers);
|
||||
let st = s.doc().unwrap();
|
||||
let board = st.doc.artboards[0].rect;
|
||||
assert!((board.width() - want_board.width()).abs() < 1e-6 && (board.height() - want_board.height()).abs() < 1e-6, "{board:?}");
|
||||
assert_eq!(st.doc.units, vectorcraft_doc::Unit::Millimeters);
|
||||
assert_eq!(leaves(&s).len(), want_leaves);
|
||||
assert_eq!(leaves(&s).iter().filter(|n| matches!(n.kind, NodeKind::SymbolInstance { .. })).count(), 2, "the block's two inserts");
|
||||
// The DXF options apply.
|
||||
open(&mut s, "plan.dwg", &plan_dwg(), json!({"dxf": {"fit": true, "mergeLayers": true}})).unwrap();
|
||||
assert_eq!(layer_names(&s), ["Layer 1"]);
|
||||
assert!(open(&mut s, "plan.dwg", &plan_dwg(), json!({"dxf": {"layout": "Sheet 9"}})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dwg_opened_is_never_written_back_as_dwg() {
|
||||
let dir = std::env::temp_dir().join(format!("vc-dwg-save-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("plan.dwg");
|
||||
let dwg = plan_dwg();
|
||||
std::fs::write(&path, &dwg).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.execute("document.open", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
let e = s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap_err().to_string();
|
||||
assert!(e.contains("not DWG"), "{e}");
|
||||
let e = s.execute("document.export", &json!({"format": "dwg"})).unwrap_err().to_string();
|
||||
assert!(e.contains("export DXF instead"), "{e}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), dwg, "the drawing is unchanged");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dxf_info_and_place_read_a_dwg() {
|
||||
let mut s = Session::new();
|
||||
let dxf = s.execute("document.dxfInfo", &json!({"dataBase64": b64(&plan())})).unwrap();
|
||||
let dwg = s.execute("document.dxfInfo", &json!({"dataBase64": b64(&plan_dwg())})).unwrap();
|
||||
for k in ["units", "layouts", "unit", "scale"] {
|
||||
assert_eq!(dwg[k], dxf[k], "{k}");
|
||||
}
|
||||
let layers: Vec<&str> = dwg["layers"].as_array().unwrap().iter().filter_map(Value::as_str).collect();
|
||||
assert!(layers.contains(&"Walls") && layers.contains(&"Notes"), "{layers:?}");
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let r = s.execute("file.place", &json!({"name": "plan.dwg", "dataBase64": b64(&plan_dwg()), "dxf": {"fit": true}})).unwrap();
|
||||
assert_eq!(r["format"], "dwg");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step");
|
||||
let id = vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap());
|
||||
let b = s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap();
|
||||
assert!((b.width() - 600.0).abs() < 1.0 && (b.center().y - 200.0).abs() < 0.5, "fitted to the artboard: {b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dwg_is_read_only_and_detected_by_content() {
|
||||
let f = format("dwg").unwrap();
|
||||
assert!(f.read && !f.write);
|
||||
assert!(OPEN_EXTS.contains(&"dwg") && PLACE_EXTS.contains(&"dwg") && UNASSOCIATED_EXTS.contains(&"dwg"));
|
||||
assert_eq!(detect("drawing.bin", &plan_dwg()).map(|f| f.id), Some("dwg"), "the content tells");
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("document.formats", &json!({})).unwrap();
|
||||
assert!(r["readable"].as_array().unwrap().contains(&json!("dwg")));
|
||||
assert!(!r["writable"].as_array().unwrap().contains(&json!("dwg")));
|
||||
assert!(r["unsupported"].as_array().unwrap().iter().all(|u| u["id"] != "dwg"));
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
//! DXF export through the commands: options, artboards, selection, images, and the formats that
|
||||
//! can't be written (DWG, PageMaker).
|
||||
//! can't be written (DWG, which opens, and PageMaker).
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -293,7 +293,7 @@ fn formats_list_dxf_and_what_can_not_be_written() {
|
||||
}
|
||||
assert!(r["writable"].as_array().unwrap().contains(&json!("dxf")));
|
||||
let unsupported: Vec<&str> = r["unsupported"].as_array().unwrap().iter().map(|u| u["id"].as_str().unwrap()).collect();
|
||||
assert_eq!(unsupported, ["dwg", "pmd"]);
|
||||
assert_eq!(unsupported, ["pmd"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -301,7 +301,7 @@ fn dwg_and_pagemaker_say_what_to_use_instead() {
|
||||
let mut s = two_boards();
|
||||
for p in [json!({"format": "dwg"}), json!({"path": "/tmp/plan.DWG"})] {
|
||||
let e = s.execute("document.export", &p).unwrap_err().to_string();
|
||||
assert!(e.contains("DWG is not available") && e.contains("DXF"), "{p}: {e}");
|
||||
assert!(e.contains("DWG files open but can't be written") && e.contains("export DXF instead"), "{p}: {e}");
|
||||
}
|
||||
// PICT opens; it isn't written.
|
||||
let e = s.execute("document.export", &json!({"format": "pict"})).unwrap_err().to_string();
|
||||
@@ -315,7 +315,8 @@ fn dwg_and_pagemaker_say_what_to_use_instead() {
|
||||
.execute("document.open", &json!({"name": "site.dwg", "dataBase64": vectorcraft_format::base64_encode(b"AC1032\0\0")}))
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(e.contains("DWG is not available"), "{e}");
|
||||
// A DWG that can't be converted says so (DWG drawings open: see tests_dwgimport).
|
||||
assert!(e.contains("DWG"), "{e}");
|
||||
let e = s
|
||||
.execute("document.open", &json!({"name": "brochure.PMD", "dataBase64": vectorcraft_format::base64_encode(b"PageMaker")}))
|
||||
.unwrap_err()
|
||||
|
||||
@@ -14,7 +14,7 @@ fn b64(bytes: &[u8]) -> String {
|
||||
|
||||
/// A millimetre drawing: a 200 × 100 rectangle on layer Walls, a circle on layer Notes, a block
|
||||
/// "Mark" (a short line) inserted twice, and a paper layout holding a line.
|
||||
fn plan() -> Vec<u8> {
|
||||
pub(super) fn plan() -> Vec<u8> {
|
||||
let pairs: &[(i32, &str)] = &[
|
||||
(0, "SECTION"),
|
||||
(2, "HEADER"),
|
||||
|
||||
@@ -40,6 +40,12 @@ use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_do
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(query "view.showMissingLinks", "Show Missing Links", ["View"], None,
|
||||
"{on?: bool (default: toggle)} show non-printing red outlines and badges on missing linked images and placed documents in the active document; transient view state, no undo step; reads no files (the desktop app scans in the background, links.marked inspects now) → {on}",
|
||||
has_doc, show_missing_links),
|
||||
cmd!(query "links.marked", "Marked Missing Links", [], None,
|
||||
"{} inspect missing links now; only visible image objects and placed documents are marked, and none when the toggle is off → {on, images: [{id, bounds: [x0, y0, x1, y1]}]}",
|
||||
has_doc, marked),
|
||||
cmd!(
|
||||
query "links.check",
|
||||
"Check Links",
|
||||
@@ -518,6 +524,8 @@ fn refused(link: &LinkInfo, doc_path: Option<&str>) -> Option<craft_docpath::Ref
|
||||
/// the content shown. Its bytes are read only when its size or modification time changed. An image
|
||||
/// placed from a DCS file is modified when one of its plate files of their own changed.
|
||||
fn probe(g: &Group, base: LinkBase) -> (Status, Option<Found>) {
|
||||
#[cfg(test)]
|
||||
probe_gate::hold(&g.link.path);
|
||||
let Some(mut f) = locate(&g.link, base) else { return (Status::Missing, None) };
|
||||
let l = &g.link;
|
||||
if !g.plate_files.is_empty() && super::place::dcs::plate_files_changed(&g.plate_files, &f.path) {
|
||||
@@ -536,6 +544,24 @@ fn probe(g: &Group, base: LinkBase) -> (Status, Option<Found>) {
|
||||
(if same { Status::Ok } else { Status::Modified }, Some(f))
|
||||
}
|
||||
|
||||
/// Whether [`probe`] would find group `g`'s file missing, without reading or hashing its content.
|
||||
/// A changed file is opened to check it can be read, and nothing more: the canvas markers ask only
|
||||
/// this, and with Update Links set to Manually a changed file keeps differing from its stored link,
|
||||
/// so a full probe would read the whole file again on every look while the markers are on.
|
||||
fn missing(g: &Group, base: LinkBase) -> bool {
|
||||
#[cfg(test)]
|
||||
probe_gate::hold(&g.link.path);
|
||||
let Some(f) = locate(&g.link, base) else { return true };
|
||||
let l = &g.link;
|
||||
if !g.plate_files.is_empty() && super::place::dcs::plate_files_changed(&g.plate_files, &f.path) {
|
||||
return false;
|
||||
}
|
||||
if l.size == Some(f.size) && l.modified.is_some() && l.modified == f.modified {
|
||||
return false;
|
||||
}
|
||||
fileio::read_file_head(&f.path, 0).is_err()
|
||||
}
|
||||
|
||||
/// Is image `key` of `d` showing its preview (its file not read)?
|
||||
fn previewing(d: &Document, key: &str) -> bool {
|
||||
d.images.get(key).is_none_or(ImageBlob::is_proxy)
|
||||
@@ -2159,6 +2185,7 @@ fn update_where(s: &mut Session, ids: Option<Vec<NodeId>>, path: Option<&str>) -
|
||||
editing_brush_art(d, |d| reads.into_iter().try_for_each(|(g, read)| install_read(d, &g.ids, read, None, Some(&g))))
|
||||
})?;
|
||||
}
|
||||
clear_markers(s, &updated)?;
|
||||
let mut out = json!({ "updated": updated, "missing": missing });
|
||||
if !warnings.is_empty() {
|
||||
out["warnings"] = json!(warnings);
|
||||
@@ -2451,6 +2478,7 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
not_found.sort();
|
||||
not_found.dedup();
|
||||
clear_markers(s, &relinked)?;
|
||||
let mut out = json!({ "relinked": relinked, "notFound": not_found });
|
||||
if !warnings.is_empty() {
|
||||
out["warnings"] = json!(warnings);
|
||||
@@ -2630,6 +2658,56 @@ pub(crate) fn statuses(st: &crate::DocState) -> BTreeMap<NodeId, (Status, Option
|
||||
out
|
||||
}
|
||||
|
||||
/// Missing placed objects, using the same file resolution as the Links panel. Hidden ones are
|
||||
/// included: [`crate::DocState::marked_missing_links`] leaves out what is hidden when it is drawn, so
|
||||
/// artwork shown later is marked without another scan. Also used on the link watch worker, away
|
||||
/// from the UI thread.
|
||||
pub(crate) fn missing_markers(doc: &Document, base: LinkBase) -> Vec<NodeId> {
|
||||
groups(doc, None).iter().filter(|g| !g.ids.is_empty() && missing(g, base)).flat_map(|g| g.ids.iter().copied()).collect()
|
||||
}
|
||||
|
||||
fn show_missing_links(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let st = s.doc_mut()?;
|
||||
let on = super::switch_or(p, "on", !st.show_missing_links, "view.showMissingLinks")?;
|
||||
// Never probes files here: a changed linked file is read in full to tell whether it still
|
||||
// matches, which would hold up the caller (the desktop UI thread) on a large or slow file.
|
||||
// Turning the overlay on leaves its markers unscanned; the link watch worker scans them
|
||||
// at once ([`Session::missing_link_scan_due`]) and the canvas repaints from its result.
|
||||
// `links.marked` stays the explicit, synchronous inspection. The web build has no worker
|
||||
// and no files to read: its app marks them in place ([`Session::mark_missing_links_in_place`]).
|
||||
if !on || !st.show_missing_links {
|
||||
st.missing_link_markers = None;
|
||||
}
|
||||
st.show_missing_links = on;
|
||||
Ok(json!({"on": on}))
|
||||
}
|
||||
|
||||
fn marked(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let st = s.doc_mut()?;
|
||||
let ids = if st.show_missing_links { missing_markers(&st.doc, LinkBase::of(st)) } else { vec![] };
|
||||
let images: Vec<Value> = ids
|
||||
.iter()
|
||||
.filter(|id| st.doc.is_visible(**id))
|
||||
.filter_map(|id| {
|
||||
let b = st.doc.node(*id)?.geometric_bounds()?;
|
||||
Some(json!({"id": id.0, "bounds": [b.x0, b.y0, b.x1, b.y1]}))
|
||||
})
|
||||
.collect();
|
||||
st.missing_link_markers = Some((st.doc.clone(), ids));
|
||||
Ok(json!({"on": st.show_missing_links, "images": images}))
|
||||
}
|
||||
|
||||
/// Successful repair clears its decoration even when the file's metadata is unchanged.
|
||||
fn clear_markers(s: &mut Session, repaired: &[u64]) -> Result<()> {
|
||||
if !repaired.is_empty()
|
||||
&& let Some((_, ids)) = &mut s.doc_mut()?.missing_link_markers
|
||||
{
|
||||
let repaired: std::collections::HashSet<_> = repaired.iter().copied().collect();
|
||||
ids.retain(|id| !repaired.contains(&id.0));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The format of the file image `im` of `d` shows: its link's extension, else its pixels' type.
|
||||
fn format_label(d: &Document, im: &ImageObject) -> &'static str {
|
||||
if im.link.is_some() && d.images.get(&im.key).is_some_and(ImageBlob::is_separated) {
|
||||
@@ -3319,6 +3397,64 @@ fn placement_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "ids": ids_json(&ids), "placement": placement_json(shown) }))
|
||||
}
|
||||
|
||||
/// Test seam: hold the probe of one linked path until the test releases it, so a test can
|
||||
/// tell whether a command returned before the probe finished, and on which thread it ran.
|
||||
#[cfg(test)]
|
||||
pub(crate) mod probe_gate {
|
||||
use std::sync::{Arc, Condvar, Mutex, PoisonError};
|
||||
use std::time::Duration;
|
||||
|
||||
/// A gated path: (open, entered on thread named, finished), and the condition signalling
|
||||
/// each change.
|
||||
#[derive(Default)]
|
||||
pub struct Gate {
|
||||
state: Mutex<(bool, Option<String>, bool)>,
|
||||
changed: Condvar,
|
||||
}
|
||||
|
||||
static GATES: Mutex<Vec<(String, Arc<Gate>)>> = Mutex::new(Vec::new());
|
||||
|
||||
impl Gate {
|
||||
/// Gate probes of the link stored as `path` until [`Gate::open`].
|
||||
pub fn close(path: &str) -> Arc<Gate> {
|
||||
let g = Arc::new(Gate::default());
|
||||
GATES.lock().unwrap_or_else(PoisonError::into_inner).push((path.to_string(), g.clone()));
|
||||
g
|
||||
}
|
||||
pub fn open(&self) {
|
||||
self.state.lock().unwrap_or_else(PoisonError::into_inner).0 = true;
|
||||
self.changed.notify_all();
|
||||
}
|
||||
/// The name of the thread that entered the probe, waiting up to `limit` for one.
|
||||
pub fn entered(&self, limit: Duration) -> Option<String> {
|
||||
let s = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let (s, _) = self.changed.wait_timeout_while(s, limit, |s| s.1.is_none()).unwrap_or_else(PoisonError::into_inner);
|
||||
s.1.clone()
|
||||
}
|
||||
pub fn finished(&self) -> bool {
|
||||
self.state.lock().unwrap_or_else(PoisonError::into_inner).2
|
||||
}
|
||||
}
|
||||
|
||||
/// Called at the start of every probe: blocks while `path` is gated and closed (at most
|
||||
/// ten seconds, so a regression fails the test instead of hanging it).
|
||||
pub(super) fn hold(path: &str) {
|
||||
let gate = GATES.lock().unwrap_or_else(PoisonError::into_inner).iter().find(|(p, _)| p == path).map(|(_, g)| g.clone());
|
||||
let Some(g) = gate else { return };
|
||||
let mut s = g.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
s.1 = Some(std::thread::current().name().unwrap_or("").to_string());
|
||||
g.changed.notify_all();
|
||||
let (mut s, _) = g.changed.wait_timeout_while(s, Duration::from_secs(10), |s| !s.0).unwrap_or_else(PoisonError::into_inner);
|
||||
s.2 = true;
|
||||
g.changed.notify_all();
|
||||
}
|
||||
|
||||
/// Stop gating `path`.
|
||||
pub fn remove(path: &str) {
|
||||
GATES.lock().unwrap_or_else(PoisonError::into_inner).retain(|(p, _)| p != path);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -16,7 +16,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Transform",
|
||||
[],
|
||||
None,
|
||||
"{matrix: [a,b,c,d,e,f], copy?: bool, ids?, strokes?: bool, corners?: bool, typeAreas?: bool, anchors?: bool, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), releaseOutside?: bool, interpolate?: bool (with anchors and a matrix that only moves them: the handles of each segment with one moved end are re-mapped, as path.moveAnchors's; default: prefs interpolateControlPoints), drawBehind?: bool (with copy: in Draw Behind, view.drawMode, each copy goes directly below its original instead of above it, as the Selection and Direct Selection tools' Alt-drags send; default false)} apply an affine to the selection (or ids); anchors (without ids or copy): paths with anchors selected with Direct Selection have only those anchors and their handles transformed, as the Transform tools and object.move/rotate/scale/reflect/shear do (default: the whole objects); strokes/corners: Scale Strokes & Effects / Scale Corners (default: the preferences); typeAreas: area type among them (not type inside a group) reshapes its frame by the matrix and its text reflows at its size, as a bounding-box handle drag does (default: the type transforms too); releaseOutside (without copy or anchors): a Shaper Group's original shape that ends wholly outside the bounds the group's original shapes had before takes shaper.releaseSource in the same undo step, named Remove from Shaper Group, as the Selection tool's moves in Construction mode do",
|
||||
"{matrix: [a,b,c,d,e,f], copy?: bool, ids?, strokes?: bool, corners?: bool, typeAreas?: bool, anchors?: bool, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), releaseOutside?: bool, interpolate?: bool (with anchors and a matrix that only moves them: the handles of each segment with one moved end are re-mapped, as path.moveAnchors's; default: prefs interpolateControlPoints), drawBehind?: bool (with copy: in Draw Behind, view.drawMode, each copy goes directly below its original instead of above it, as the Selection and Direct Selection tools' Alt-drags send; default false)} apply an affine to the selection (or ids); anchors (without ids or copy): paths with anchors selected with Direct Selection have only those anchors and their handles transformed, as the Transform tools and object.move/rotate/scale/reflect/shear do (default: the whole objects), and a matrix that only moves them moves the uncut corners of a path with rounded Live Corners, which is cut again at its radii; strokes/corners: Scale Strokes & Effects / Scale Corners (default: the preferences); typeAreas: area type among them (not type inside a group) reshapes its frame by the matrix and its text reflows at its size, as a bounding-box handle drag does (default: the type transforms too); releaseOutside (without copy or anchors): a Shaper Group's original shape that ends wholly outside the bounds the group's original shapes had before takes shaper.releaseSource in the same undo step, named Remove from Shaper Group, as the Selection tool's moves in Construction mode do",
|
||||
has_doc,
|
||||
transform
|
||||
),
|
||||
@@ -25,7 +25,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move…",
|
||||
["Object", "Transform"],
|
||||
Some("Cmd+Shift+M"),
|
||||
"{ids?: [id…] (selected first; default: the selection), dx, dy, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), interpolate?: bool (as path.moveAnchors's; default: prefs interpolateControlPoints)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
|
||||
"{ids?: [id…] (selected first; default: the selection), dx, dy, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), interpolate?: bool (as path.moveAnchors's; default: prefs interpolateControlPoints)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box. On a path with rounded Live Corners, the uncut corner of each selected anchor moves by (dx, dy) and is cut again at its radius.",
|
||||
has_selection_or_guides,
|
||||
move_cmd
|
||||
),
|
||||
@@ -314,7 +314,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Live Shape Properties",
|
||||
[],
|
||||
None,
|
||||
"{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding: store radii as fractions of each corner's maximum so they scale with the shape; it applies to a whole live rectangle, live polygon or path with Live Corners; a plain path, an ellipse and a line are left as they are, with no undo step), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it), strokes?, patterns?: bool (Scale Strokes & Effects and Transform Patterns, as object.scale takes them; default: the preferences)} (a new angle, polygon radius or side length, makeSidesEqual, lineLength or lineAngle moves, scales or turns the object as a transform does, so a linked opacity mask, placed gradients and (with `patterns`) pattern tiles go with the shape, and with `strokes` its strokes and effects scale, while corner radii in the mask keep their size; a line takes the turn and even scale that take its old ends to its new ones; the bounding box keeps its angle; rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)",
|
||||
"{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding: store radii as fractions of each corner's maximum so they scale with the shape; it applies to a whole live rectangle, live polygon or path with Live Corners; a plain path, an ellipse and a line are left as they are, with no undo step), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), points?: n (a live star's point count, a whole number from 2 to 1000; its corners keep the radius they shared; a new point count drops its selected anchors and segments; not with radius or kind), ratio?: above 0 and up to 1 (a live star's inner radius over its outer radius; the outer radius stays; a change to the corners a rounded star cuts drops its selected anchors and segments, and is an error with radius or kind), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it), strokes?, patterns?: bool (Scale Strokes & Effects and Transform Patterns, as object.scale takes them; default: the preferences)} (a new angle, polygon radius or side length, makeSidesEqual, lineLength or lineAngle moves, scales or turns the object as a transform does, so a linked opacity mask, placed gradients and (with `patterns`) pattern tiles go with the shape, and with `strokes` its strokes and effects scale, while corner radii in the mask keep their size; a line takes the turn and even scale that take its old ends to its new ones; the bounding box keeps its angle; rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)",
|
||||
has_selection,
|
||||
set_live_shape
|
||||
),
|
||||
|
||||
@@ -103,7 +103,7 @@ fn corners_param(p: &Value) -> Result<Option<BTreeSet<usize>>> {
|
||||
/// Whether `relativeRadii` applies to a path with live shape `live`: a live rectangle, a live
|
||||
/// polygon or a path with Live Corners. A plain path, an ellipse and a line stay as they are.
|
||||
fn takes_rounding(live: Option<&LiveShape>) -> bool {
|
||||
matches!(live, Some(LiveShape::Rectangle { .. } | LiveShape::Polygon { .. } | LiveShape::Path { .. }))
|
||||
matches!(live, Some(LiveShape::Rectangle { .. } | LiveShape::Polygon { .. } | LiveShape::Star { .. } | LiveShape::Path { .. }))
|
||||
}
|
||||
|
||||
/// Live line `l` with Line Length `len` (its first end stays) and then Line Angle `angle` (about
|
||||
@@ -130,6 +130,16 @@ fn line_edit(l: &LiveShape, len: Option<f64>, angle: Option<f64>) -> Option<Live
|
||||
(changed && new != *l).then_some(new)
|
||||
}
|
||||
|
||||
/// Whether a star's anchors are laid out differently after an edit: a new point count, or a ratio
|
||||
/// that changes which corners a rounded star cuts (each drawn anchor's source corner).
|
||||
fn star_relaid(old: &LiveShape, new: &LiveShape) -> bool {
|
||||
fn layout(l: &LiveShape) -> Option<Vec<Vec<usize>>> {
|
||||
let path = l.to_path();
|
||||
LiveCorners::new(&path, Some(l)).map(|c| c.sources().to_vec())
|
||||
}
|
||||
old.star_points().is_some() && (old.star_points() != new.star_points() || layout(old) != layout(new))
|
||||
}
|
||||
|
||||
/// The transform that takes live shape `old` to `new` where they differ only in place, angle and
|
||||
/// size (a new Rectangle, Ellipse or Polygon Angle, Polygon Radius, Side Length, Make Sides Equal,
|
||||
/// Line Length or Line Angle): what moves, turns and scales the rest of the object (a linked
|
||||
@@ -175,7 +185,7 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
&["constrainPie", "invertPie", "makeSidesEqual", "rectanglesOnly", "relativeRadii", "strokes", "patterns"],
|
||||
"object.setLiveShape",
|
||||
)?;
|
||||
check_numbers(p, &["radius", "sides"], "object.setLiveShape")?;
|
||||
check_numbers(p, &["radius", "sides", "points", "ratio"], "object.setLiveShape")?;
|
||||
// `items`: objects each with its own `corners`; else `ids` (or the selection) sharing them.
|
||||
let items = match p.get("items").filter(|v| !v.is_null()) {
|
||||
None => None,
|
||||
@@ -240,6 +250,16 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} else {
|
||||
number("sides", |n| n.fract() == 0.0 && (3.0..=1000.0).contains(&n), "a whole number from 3 to 1000")?.map(|n| n as u64)
|
||||
};
|
||||
// A star's Star Properties: its point count (a whole number from 2 to 1000, as `shape.star`
|
||||
// takes it) and its ratio (inner radius over outer radius, above 0 and up to 1). Both are
|
||||
// checked on replay too: no recording predates them.
|
||||
let points = number("points", |n| n.fract() == 0.0 && (2.0..=1000.0).contains(&n), "a whole number from 2 to 1000")?.map(|n| n as u64);
|
||||
let ratio = number("ratio", |r| r > 0.0 && r <= 1.0, "a ratio above 0 and up to 1")?;
|
||||
// A new point count lays a star's corners out again, so the corners a radius or kind would set
|
||||
// can't be told from the anchors selected before it.
|
||||
if points.is_some() && (radius.is_some() || kind.is_some()) {
|
||||
return Err(bad("object.setLiveShape", "`points` can't be set with `radius` or `kind`: set the corners in a call of their own"));
|
||||
}
|
||||
// An ellipse's pie (Ellipse Properties: Pie Start and End Angle, degrees; Invert Pie swaps them).
|
||||
let (pie_start, pie_end) = (angle("pieStart")?, angle("pieEnd")?);
|
||||
let invert = p.get("invertPie").and_then(Value::as_bool) == Some(true);
|
||||
@@ -292,6 +312,11 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} else {
|
||||
ids
|
||||
};
|
||||
// A ratio is the inner radius over the outer one: a star whose outer radius is 0 has none to set.
|
||||
if ratio.is_some() && ids.iter().any(|id| matches!(st.doc.node(*id).and_then(|n| n.live_shape()), Some(LiveShape::Star { r1, .. }) if *r1 <= 0.0))
|
||||
{
|
||||
return Err(bad("object.setLiveShape", "a star whose outer radius is 0 has no ratio to set"));
|
||||
}
|
||||
// The lines that Line Length or Line Angle changes, as they become. A line that would reach
|
||||
// past the document's coordinate limit is an error before anything changes.
|
||||
let mut lines = std::collections::BTreeMap::new();
|
||||
@@ -321,6 +346,12 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
{
|
||||
return false;
|
||||
}
|
||||
Some(l @ LiveShape::Star { points: now, .. })
|
||||
if !(points.is_none_or(|n| n.clamp(2, 1000) == u64::from(*now))
|
||||
&& ratio.is_none_or(|r| l.star_ratio().is_some_and(|k| (k - r).abs() < 1e-12))) =>
|
||||
{
|
||||
return false;
|
||||
}
|
||||
Some(l @ LiveShape::Ellipse { pie, .. }) if pie_of(*pie) != *pie || ellipse_angle.is_some_and(|a| !at_angle(l.shape_angle(), a)) => {
|
||||
return false;
|
||||
}
|
||||
@@ -386,6 +417,17 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
edited = true;
|
||||
}
|
||||
if let l @ LiveShape::Star { .. } = &mut new
|
||||
&& (points.is_some() || ratio.is_some())
|
||||
{
|
||||
if let Some(n) = points {
|
||||
l.set_points(n);
|
||||
}
|
||||
if let Some(r) = ratio {
|
||||
l.set_star_ratio(r);
|
||||
}
|
||||
edited = true;
|
||||
}
|
||||
if let Some(a) = rectangle_angle
|
||||
&& let l @ LiveShape::Rectangle { .. } = &mut new
|
||||
{
|
||||
@@ -411,6 +453,14 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
reshaped.insert(*id, ((**old).clone(), new));
|
||||
}
|
||||
}
|
||||
// A ratio that changes which corners a rounded star cuts lays its anchors out again, as a new
|
||||
// point count does, so the corners a radius or kind would set can't be told apart.
|
||||
if ratio.is_some() && (radius.is_some() || kind.is_some()) && reshaped.values().any(|(old, new)| star_relaid(old, new)) {
|
||||
return Err(bad(
|
||||
"object.setLiveShape",
|
||||
"this `ratio` changes the star's anchors, so it can't be set with `radius` or `kind`: set the corners in a call of their own",
|
||||
));
|
||||
}
|
||||
// A shape that moves, turns or scales takes the rest of the object along as a transform does:
|
||||
// Scale Strokes & Effects and Transform Patterns come from `strokes` and `patterns` or the
|
||||
// preferences, and are noted in the journal so a replay does the same. Corner radii in the rest
|
||||
@@ -439,6 +489,13 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
*live = Some(Box::new(new.clone()));
|
||||
*path = new.to_path();
|
||||
}
|
||||
// A new point count, or a ratio that changes which corners the rounded star cuts, lays its
|
||||
// anchors out again: anchors and segments selected on the old layout would name others,
|
||||
// or none.
|
||||
if star_relaid(old, new) {
|
||||
sel.anchors.remove(id);
|
||||
sel.segments.remove(id);
|
||||
}
|
||||
}
|
||||
for id in &ids {
|
||||
let Some(NodeKind::Path { path, live, .. }) = d.node_mut(*id).map(|n| &mut n.kind) else { continue };
|
||||
|
||||
+163
-17
@@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Anchors",
|
||||
[],
|
||||
None,
|
||||
"{dx, dy (a move by 0 changes nothing and records no undo step), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), interpolate?: bool (Interpolate Control Points: the handles of each segment with one moved end are re-mapped by the turn, scale and move that take its old ends to its new ends; default: prefs interpolateControlPoints)} move direct-selected anchors (whole paths if fully selected); refused while an object of a symbol instance's art is selected",
|
||||
"{dx, dy (a move by 0, or one that the pixel-grid snap of pixel-aligned paths takes back, changes nothing and records no undo step), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), interpolate?: bool (Interpolate Control Points: the handles of each segment with one moved end are re-mapped by the turn, scale and move that take its old ends to its new ends; default: prefs interpolateControlPoints)} move direct-selected anchors (whole paths if fully selected); with rounded Live Corners, each selected anchor's uncut corner moves by (dx, dy) and is recut at its radius, so a grabbed arc end can move off a snap target; refused while an object of a symbol instance's art is selected",
|
||||
has_selection,
|
||||
move_anchors
|
||||
),
|
||||
@@ -68,7 +68,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Anchor Point",
|
||||
[],
|
||||
None,
|
||||
"{id, subpath?, anchor, x, y} move one anchor to (x, y), its handles with it",
|
||||
"{id, subpath?, anchor, x, y} move one anchor to (x, y), its handles with it; with rounded Live Corners, the uncut corner moves by the delta from the drawn anchor to (x, y) and is recut at its radius, so the drawn anchor can finish away from (x, y)",
|
||||
has_doc,
|
||||
move_anchor
|
||||
),
|
||||
@@ -176,6 +176,118 @@ pub(super) fn path_mut(d: &mut vectorcraft_doc::Document, id: NodeId) -> Result<
|
||||
}
|
||||
}
|
||||
|
||||
/// Transform `anchors` of path `id` by `xf` when the path has cut Live Corners: the anchors of its
|
||||
/// uncut outline move (with `interpolate` and a move, as [`move_interpolating_handles`] moves
|
||||
/// them) and the corners are cut again with the same radii, so they stay live
|
||||
/// ([`vectorcraft_doc::edit_corner_anchors`]). Returns `None`, changing nothing, for a path
|
||||
/// without cut corners.
|
||||
fn transform_live_corner_anchors(
|
||||
d: &mut vectorcraft_doc::Document,
|
||||
id: NodeId,
|
||||
anchors: &BTreeSet<AnchorRef>,
|
||||
xf: vectorcraft_geom::Affine,
|
||||
interpolate: bool,
|
||||
) -> Option<()> {
|
||||
let NodeKind::Path { path, live, .. } = &mut d.node_mut(id)?.kind else { return None };
|
||||
let c = xf.as_coeffs();
|
||||
vectorcraft_doc::edit_corner_anchors(path, live, anchors, |base, set| {
|
||||
if interpolate && c[..4] == [1.0, 0.0, 0.0, 1.0] {
|
||||
move_interpolating_handles(base, set, Vec2::new(c[4], c[5]));
|
||||
} else {
|
||||
for &(si, ai) in set {
|
||||
if let Some(a) = base.anchor_mut(si, ai) {
|
||||
*a = a.transform(xf);
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// For each anchor of path `id` as drawn (per subpath), the anchor of its uncut outline it comes
|
||||
/// from ([`vectorcraft_doc::LiveCorners::sources`]), or `None` when `id` is not a path.
|
||||
fn corner_sources(d: &Document, id: NodeId) -> Option<Vec<Vec<usize>>> {
|
||||
let NodeKind::Path { path, live, .. } = &d.node(id)?.kind else { return None };
|
||||
Some(vectorcraft_doc::LiveCorners::new(path, live.as_deref())?.sources().to_vec())
|
||||
}
|
||||
|
||||
/// After the anchors of path `id` as drawn changed from `before` to `after` (each listing the
|
||||
/// corners they come from, as [`corner_sources`] gives them), point the selected anchors and the
|
||||
/// key anchor of `sel` on that path at the anchors of the same corners, and drop the path's
|
||||
/// selected segments. An unchanged layout leaves `sel` as it is.
|
||||
fn remap_corner_anchors(sel: &mut Selection, id: NodeId, before: &[Vec<usize>], after: &[Vec<usize>]) {
|
||||
if before == after {
|
||||
return;
|
||||
}
|
||||
let source = |(si, ai): AnchorRef| before.get(si).and_then(|v| v.get(ai)).copied();
|
||||
let drawn =
|
||||
|k: usize| after.iter().enumerate().flat_map(move |(si, v)| v.iter().enumerate().filter(move |(_, s)| **s == k).map(move |(ai, _)| (si, ai)));
|
||||
if let Some(set) = sel.anchors.get_mut(&id) {
|
||||
let corners: BTreeSet<usize> = set.iter().filter_map(|r| source(*r)).collect();
|
||||
*set = corners.into_iter().flat_map(drawn).collect();
|
||||
}
|
||||
if let Some((key, r)) = sel.key_anchor
|
||||
&& key == id
|
||||
{
|
||||
sel.key_anchor = source(r).and_then(|k| drawn(k).next()).map(|r| (id, r));
|
||||
}
|
||||
sel.segments.remove(&id);
|
||||
}
|
||||
|
||||
/// Snap pixel-aligned path `id`, or the pixel-aligned compound path that holds it, to the pixel
|
||||
/// grid again, with `sel` following its anchors when the snap cuts its Live Corners again with a
|
||||
/// different layout ([`remap_corner_anchors`]).
|
||||
fn snap_keeping_selection(d: &mut Document, id: NodeId, sel: &mut Selection, before: Option<&[Vec<usize>]>) {
|
||||
let top = compound_or_self(d, id);
|
||||
if let Some(n) = d.node_mut(top) {
|
||||
super::object::snap_if_aligned(n);
|
||||
}
|
||||
if let (Some(before), Some(after)) = (before, corner_sources(d, id)) {
|
||||
remap_corner_anchors(sel, id, before, &after);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `apply` on a copy of the active document, followed by the pixel-grid snap that
|
||||
/// [`Session::edit`] makes, leaves the document as it was (a nudge that the snap of a
|
||||
/// pixel-aligned path takes back). Without a pixel-aligned path among `ids` (or a compound path
|
||||
/// holding one) the answer is `false` without trying. An anchor edit turns a live rectangle or
|
||||
/// polygon into a live path with the same outline, radii and kinds; that conversion alone counts
|
||||
/// as no change, while any change to the uncut outline or the corner settings still counts.
|
||||
fn snap_undoes(s: &Session, ids: impl IntoIterator<Item = NodeId>, apply: impl FnOnce(&mut Document, &mut Selection) -> Result<()>) -> Result<bool> {
|
||||
let st = s.doc()?;
|
||||
let ids: Vec<NodeId> = ids.into_iter().collect();
|
||||
if !ids.iter().any(|&id| st.doc.node(compound_or_self(&st.doc, id)).is_some_and(|n| n.extras().pixel_aligned)) {
|
||||
return Ok(false);
|
||||
}
|
||||
let mut doc = (*st.doc).clone();
|
||||
let mut sel = st.selection.clone();
|
||||
apply(&mut doc, &mut sel)?;
|
||||
super::refresh_pixel_aligned(&st.doc, &mut doc);
|
||||
for &id in &ids {
|
||||
let (Some(NodeKind::Path { path, live, .. }), Some(anchors)) = (st.doc.node(id).map(|n| &n.kind), st.selection.anchors.get(&id)) else {
|
||||
continue;
|
||||
};
|
||||
// A live path keeps its variant through an anchor edit, so only a rectangle or polygon
|
||||
// needs the comparison below.
|
||||
if !matches!(live.as_deref(), Some(vectorcraft_doc::LiveShape::Rectangle { .. } | vectorcraft_doc::LiveShape::Polygon { .. })) {
|
||||
continue;
|
||||
}
|
||||
// The path and live shape the same anchors, left where they are, would turn this path
|
||||
// into. The drawn path is cut from the live shape, and a recut can differ from the stored
|
||||
// path by rounding, so the live shapes are compared and both fields are restored.
|
||||
let (mut converted_path, mut converted) = (path.clone(), live.clone());
|
||||
if vectorcraft_doc::edit_corner_anchors(&mut converted_path, &mut converted, anchors, |_, _| {}).is_none() {
|
||||
continue;
|
||||
}
|
||||
if let Some(NodeKind::Path { path: after_path, live: after, .. }) = doc.node_mut(id).map(|n| &mut n.kind)
|
||||
&& *after == converted
|
||||
{
|
||||
after.clone_from(live);
|
||||
after_path.clone_from(path);
|
||||
}
|
||||
}
|
||||
Ok(doc == *st.doc)
|
||||
}
|
||||
|
||||
fn append_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = object_param(p, "id", "path.appendAnchor")?.ok_or_else(|| bad("path.appendAnchor", "missing id"))?;
|
||||
let a = anchor_from_json(p, "path.appendAnchor")?;
|
||||
@@ -278,6 +390,13 @@ fn move_selected(s: &mut Session, p: &Value, bend: bool) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let mut sel = st.selection.clone();
|
||||
let (held, bends) = if bend { held_segments(&st.doc, &mut sel, d) } else { (false, vec![]) };
|
||||
// A path with a curved segment that bends or holds its anchors is edited anchor by anchor, so
|
||||
// the segment indices found above stay valid.
|
||||
let plain: BTreeSet<NodeId> = bends
|
||||
.iter()
|
||||
.map(|b| b.0)
|
||||
.chain(sel.anchors.iter().filter(|(id, set)| st.selection.anchors.get(id) != Some(*set)).map(|(id, _)| *id))
|
||||
.collect();
|
||||
// Segments that hold their anchors and don't bend, with nothing else to move, change nothing.
|
||||
if held && bends.is_empty() && sel.whole().is_empty() && sel.guides.is_empty() && sel.anchors.values().all(BTreeSet::is_empty) {
|
||||
return ok();
|
||||
@@ -286,15 +405,21 @@ fn move_selected(s: &mut Session, p: &Value, bend: bool) -> Result<Value> {
|
||||
// `patterns` (default: General › Transform Pattern Tiles) is on.
|
||||
let sc = Scaling { patterns: super::object::transform_patterns(s, p, &sel.whole())?, ..Scaling::default() };
|
||||
let interpolate = interpolates_handles(s, p, C)?;
|
||||
s.edit(if bends.is_empty() { "Move" } else { "Reshape" }, |doc, _| {
|
||||
transform_selected(doc, &sel, vectorcraft_geom::Affine::translate(d), sc, interpolate)?;
|
||||
let apply = |doc: &mut Document, live: &mut Selection| -> Result<()> {
|
||||
transform_selected(doc, &sel, live, &plain, vectorcraft_geom::Affine::translate(d), sc, interpolate)?;
|
||||
for &(id, si, seg) in &bends {
|
||||
if let Some(sp) = path_mut(doc, id)?.subpaths.get_mut(si) {
|
||||
sp.nudge_segment(seg, d);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
};
|
||||
// Anchors and objects selected whole that the pixel-grid snap puts back where they were change
|
||||
// nothing, and record no undo step.
|
||||
if sel.guides.is_empty() && snap_undoes(s, sel.anchors.keys().copied().chain(sel.whole()), apply)? {
|
||||
return ok();
|
||||
}
|
||||
s.edit(if bends.is_empty() { "Move" } else { "Reshape" }, apply)?;
|
||||
// Transform Again repeats a move that moved something; a drag records it when it commits. A
|
||||
// move that held segments' anchors is not one move of the selection.
|
||||
let st = s.doc_mut()?;
|
||||
@@ -350,7 +475,7 @@ pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_ge
|
||||
let c = xf.as_coeffs();
|
||||
let is_translation = (c[0] - 1.0).abs() < 1e-9 && c[1].abs() < 1e-9 && c[2].abs() < 1e-9 && (c[3] - 1.0).abs() < 1e-9;
|
||||
s.edit(label, |doc, live| {
|
||||
transform_selected(doc, &sel, xf, sc, interpolate)?;
|
||||
transform_selected(doc, &sel, live, &BTreeSet::new(), xf, sc, interpolate)?;
|
||||
Ok(if is_translation { vec![] } else { doc.transform_ruler_guides(live, xf) })
|
||||
})
|
||||
}
|
||||
@@ -359,14 +484,32 @@ pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_ge
|
||||
/// objects selected whole (those with no entry in `sel`'s `anchors`). An object inside
|
||||
/// another selected object, such as a path in a selected group, moves once, with that object.
|
||||
/// When `xf` is a move and `interpolate` is on, the handles of each segment with one moved end
|
||||
/// are re-mapped ([`move_interpolating_handles`]).
|
||||
fn transform_selected(doc: &mut Document, sel: &Selection, xf: vectorcraft_geom::Affine, sc: Scaling, interpolate: bool) -> Result<()> {
|
||||
/// are re-mapped ([`move_interpolating_handles`]). A path with rounded Live Corners keeps them
|
||||
/// ([`transform_live_corner_anchors`]), and `live_sel` follows its anchors when the recut changes
|
||||
/// them, except for the paths in `plain`, which are edited anchor by anchor.
|
||||
fn transform_selected(
|
||||
doc: &mut Document,
|
||||
sel: &Selection,
|
||||
live_sel: &mut Selection,
|
||||
plain: &BTreeSet<NodeId>,
|
||||
xf: vectorcraft_geom::Affine,
|
||||
sc: Scaling,
|
||||
interpolate: bool,
|
||||
) -> Result<()> {
|
||||
let ids = super::edit::outermost(doc, sel.objects.clone());
|
||||
let c = xf.as_coeffs();
|
||||
let is_translation = (c[0] - 1.0).abs() < 1e-9 && c[1].abs() < 1e-9 && c[2].abs() < 1e-9 && (c[3] - 1.0).abs() < 1e-9;
|
||||
let delta = vectorcraft_geom::Vec2::new(c[4], c[5]);
|
||||
for id in &ids {
|
||||
match sel.anchors.get(id) {
|
||||
Some(set)
|
||||
if c[..4] == [1.0, 0.0, 0.0, 1.0]
|
||||
&& !plain.contains(id)
|
||||
&& let Some(before) = corner_sources(doc, *id)
|
||||
&& transform_live_corner_anchors(doc, *id, set, xf, interpolate).is_some() =>
|
||||
{
|
||||
snap_keeping_selection(doc, *id, live_sel, Some(&before));
|
||||
}
|
||||
Some(set) => {
|
||||
let path = path_mut(doc, *id)?;
|
||||
// Only an exact move takes the interpolating path: a near-identity scale or
|
||||
@@ -798,16 +941,19 @@ fn move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
{
|
||||
return ok();
|
||||
}
|
||||
s.edit("Move", |d, _| {
|
||||
let path = path_mut(d, id)?;
|
||||
let a = path.anchor_mut(si, ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
|
||||
*a = a.transform(vectorcraft_geom::Affine::translate(pos - a.p));
|
||||
// A pixel-aligned path, or the pixel-aligned compound path that holds it, snaps to the
|
||||
// pixel grid again.
|
||||
let top = compound_or_self(d, id);
|
||||
if let Some(n) = d.node_mut(top) {
|
||||
super::object::snap_if_aligned(n);
|
||||
s.edit("Move", |d, sel| {
|
||||
let old = d.node(id).and_then(|n| n.path_data()).and_then(|p| p.subpaths.get(si)).and_then(|sp| sp.anchors.get(ai)).map(|a| a.p);
|
||||
let before = corner_sources(d, id);
|
||||
let moved = BTreeSet::from([(si, ai)]);
|
||||
let kept = old.and_then(|p0| transform_live_corner_anchors(d, id, &moved, vectorcraft_geom::Affine::translate(pos - p0), false));
|
||||
if kept.is_none() {
|
||||
let path = path_mut(d, id)?;
|
||||
let a = path.anchor_mut(si, ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
|
||||
*a = a.transform(vectorcraft_geom::Affine::translate(pos - a.p));
|
||||
}
|
||||
// A pixel-aligned path, or the pixel-aligned compound path that holds it, snaps to the
|
||||
// pixel grid again, and the selection follows a path whose corners were cut again.
|
||||
snap_keeping_selection(d, id, sel, kept.and(before.as_deref()));
|
||||
Ok(())
|
||||
})?;
|
||||
ok()
|
||||
|
||||
@@ -357,9 +357,9 @@ fn load_into(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool, slices_o
|
||||
let (natural, warnings) = (s.frame, s.warnings.clone());
|
||||
return Ok(Loaded { name, format, art: Art::Document(s, link.clone(), !crop), natural, warnings, link: Some(link), board: None });
|
||||
}
|
||||
let anchored = format.id == "dxf" && (opts.dxf.fit || !opts.dxf.center);
|
||||
let anchored = matches!(format.id, "dxf" | "dwg") && (opts.dxf.fit || !opts.dxf.center);
|
||||
let (mut doc, warnings) = {
|
||||
// Of the open options, only a DXF drawing's apply (the colour mode stays the file's).
|
||||
// Of the open options, only a DXF or DWG drawing's apply (the colour mode stays the file's).
|
||||
let o = fileio::LoadOptions { dxf: opts.dxf, ..Default::default() };
|
||||
let mut l = fileio::load_with(src.name, &src.bytes, &o)?;
|
||||
// An Affinity file whose native document couldn't be read is only its preview: it
|
||||
@@ -380,7 +380,7 @@ fn load_into(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool, slices_o
|
||||
let board = doc.artboards.first().map(|a| a.rect).filter(|_| anchored);
|
||||
let layers = std::mem::take(&mut doc.layers);
|
||||
let symbols = doc.symbol_boxes();
|
||||
let (nodes, clip) = if matches!(format.id, "svg" | "svgz" | "dxf" | "hpgl") {
|
||||
let (nodes, clip) = if matches!(format.id, "svg" | "svgz" | "dxf" | "dwg" | "hpgl") {
|
||||
// An SVG with `crop: "crop"` asked for is framed and clipped by its viewBox (its artboard),
|
||||
// as a PDF by its page: art drawn on a shared canvas keeps its place and scale (#788). By
|
||||
// default, as Illustrator places one, it is its art's bounds.
|
||||
@@ -578,7 +578,7 @@ fn art_of<'a>(nodes: impl Iterator<Item = &'a Arc<Node>>) -> Vec<Node> {
|
||||
}
|
||||
|
||||
/// The art as one object of `d` (its resources added), at its natural size and position.
|
||||
fn build(d: &mut Document, l: Loaded, link: Option<LinkInfo>) -> Node {
|
||||
fn build(d: &mut Document, l: Loaded, link: Option<LinkInfo>) -> Result<Node> {
|
||||
let mut node = match l.art {
|
||||
Art::Image(img, clip) => {
|
||||
let (sx, sy) = pt_per_px(img.ppi);
|
||||
@@ -613,7 +613,7 @@ fn build(d: &mut Document, l: Loaded, link: Option<LinkInfo>) -> Node {
|
||||
Art::Text(t) => Node::new(d.alloc_id(), NodeKind::Text(Box::new(text::area_text(t, l.natural, &d.setup)))),
|
||||
Art::Document(s, link, bounding) => document::node(d, &s, link, bounding),
|
||||
Art::Vector { src, mut nodes, clip } => {
|
||||
adopt::adopt(d, &src, &mut nodes);
|
||||
adopt::adopt(d, &src, &mut nodes, PLACE)?;
|
||||
let mut children: Vec<Arc<Node>> = nodes.iter().map(|n| Arc::new(d.reid(n))).collect();
|
||||
if let Some(r) = clip {
|
||||
children.insert(0, Arc::new(clip_path(d.alloc_id(), r)));
|
||||
@@ -622,7 +622,7 @@ fn build(d: &mut Document, l: Loaded, link: Option<LinkInfo>) -> Node {
|
||||
}
|
||||
};
|
||||
node.name = Some(l.name);
|
||||
node
|
||||
Ok(node)
|
||||
}
|
||||
|
||||
/// `node` moved and scaled by `m` as a whole: strokes, effects and pattern tiles go along.
|
||||
@@ -817,22 +817,86 @@ impl Session {
|
||||
if self.doc()?.uid != read.job.doc {
|
||||
return Err(bad(PLACE, NOT_ACTIVE));
|
||||
}
|
||||
let params = read.job.params.clone();
|
||||
if let Some(old) = read.job.old {
|
||||
let st = self.doc()?;
|
||||
// Deleted, changed, or another object with its id: an undo that removes the object frees
|
||||
// its id for the next object made.
|
||||
if st.doc.node(old) != read.job.replaced.as_ref() {
|
||||
// Keep the asynchronous target check against the drawing currently on show.
|
||||
if self.doc()?.doc.node(old) != read.job.replaced.as_ref() {
|
||||
return Err(bad(PLACE, "replace: the object to replace was changed or deleted"));
|
||||
}
|
||||
}
|
||||
let params = read.job.params.clone();
|
||||
// Provisional reselection and placement are one outside command. Deferring their
|
||||
// notifications must not make an asynchronous handoff part of an unrelated tool drag.
|
||||
if self.depth == 0 && !self.previewing && !self.in_tool_actions {
|
||||
self.command_with_settled_warnings(|s| s.outside_interaction(PLACE, ¶ms, |s| s.place_read_handoff(read, ¶ms)))
|
||||
} else {
|
||||
self.place_read_handoff(read, ¶ms)
|
||||
}
|
||||
}
|
||||
|
||||
fn place_read_handoff(&mut self, read: PlaceRead, params: &Value) -> Result<Value> {
|
||||
let mut rollback = None;
|
||||
let mut reselect = None;
|
||||
if let Some(old) = read.job.old {
|
||||
let st = self.doc()?;
|
||||
if st.selection.objects != [old] || st.selection.symbol_part.is_some() {
|
||||
self.execute("select.set", &json!({ "ids": [old.0] }))?;
|
||||
// Adoption may now fail. Its provisional selection must not escape that error.
|
||||
rollback = Some((
|
||||
self.active,
|
||||
st.clone(),
|
||||
self.paint.clone(),
|
||||
self.fill_active,
|
||||
self.pending_paint.clone(),
|
||||
self.active_appearance_item.clone(),
|
||||
self.batch_paint_docs.clone(),
|
||||
self.journal.len(),
|
||||
self.journal.held(),
|
||||
));
|
||||
self.journal.hold(Some(self.journal.first_kept()));
|
||||
reselect = Some(old);
|
||||
}
|
||||
}
|
||||
self.place_hand_off = Some(read);
|
||||
let r = self.execute(PLACE, ¶ms);
|
||||
let outer_tool_actions = self.in_tool_actions;
|
||||
if reselect.is_some() {
|
||||
self.in_tool_actions = true;
|
||||
}
|
||||
let result = (|| {
|
||||
if let Some(old) = reselect {
|
||||
self.execute("select.set", &json!({ "ids": [old.0] }))?;
|
||||
}
|
||||
self.place_hand_off = Some(read);
|
||||
self.execute(PLACE, params)
|
||||
})();
|
||||
self.place_hand_off = None;
|
||||
r
|
||||
if let Some((active, before, paint, fill_active, pending, appearance, paint_docs, journal, held)) = rollback {
|
||||
if result.is_err() {
|
||||
if let Some(st) = self.docs.iter_mut().find(|st| st.uid == before.uid) {
|
||||
let revision = st.revision.max(before.revision);
|
||||
*st = before;
|
||||
st.revision = revision + 1;
|
||||
}
|
||||
self.active = active;
|
||||
self.paint = paint;
|
||||
self.fill_active = fill_active;
|
||||
self.pending_paint = pending;
|
||||
self.active_appearance_item = appearance;
|
||||
self.batch_paint_docs = paint_docs;
|
||||
self.journal.truncate(journal);
|
||||
for group in self.docs.iter_mut().filter_map(|st| st.undo_group.as_mut()) {
|
||||
group.journal.retain(|&(n, _)| n < journal);
|
||||
group.steps.retain(|&(n, _)| n < journal);
|
||||
}
|
||||
self.clear_deferred_overlay_cache();
|
||||
self.decoded_images.empty();
|
||||
self.sync_front_profiles();
|
||||
super::compositefonts::sync(self);
|
||||
}
|
||||
self.journal.hold(held);
|
||||
}
|
||||
if reselect.is_some() {
|
||||
self.in_tool_actions = outer_tool_actions;
|
||||
self.after_command(result.is_ok().then_some(PLACE));
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
@@ -998,7 +1062,7 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
|
||||
n => warnings.push(format!("{n} slices would lie outside the canvas and were left out")),
|
||||
}
|
||||
let (id, size, slice_ids) = s.edit("Place", |d, sel| {
|
||||
let mut node = transformed(build(d, loaded, link), m);
|
||||
let mut node = transformed(build(d, loaded, link)?, m);
|
||||
if let Some((old_image, (_, q, _))) = distorted {
|
||||
node = with_corners(node, q).ok_or_else(|| super::xform::distorted_image_error(PLACE, old_image))?;
|
||||
}
|
||||
@@ -1266,7 +1330,7 @@ fn thumbnail_png(l: Loaded, px: f64) -> Result<String> {
|
||||
let natural = l.natural;
|
||||
let mut d = Document::new(natural.width().max(1.0), natural.height().max(1.0));
|
||||
let layer = d.layers.first().map(|l| l.id);
|
||||
let node = build(&mut d, l, None);
|
||||
let node = build(&mut d, l, None)?;
|
||||
d.insert(layer, 0, node)?;
|
||||
let k = px.clamp(1.0, MAX_THUMBNAIL) / natural.width().max(natural.height()).max(1e-9);
|
||||
let png = vectorcraft_render::Renderer::new().render_region(&d, natural, k, false).to_png().map_err(EngineError::Other)?;
|
||||
|
||||
@@ -5,13 +5,16 @@
|
||||
//! defines differently keeps its colour, unlinked. Text styles are left as they are: the art carries
|
||||
//! its own formatting.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_brush::{Brush, BrushKind};
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::{AppearanceItem, Document, Node, NodeKind, PatternDef, Symbol};
|
||||
|
||||
use super::super::Result;
|
||||
use super::super::clipboard::SymbolOptions;
|
||||
use super::super::compositefonts::{CompositeImport, node_families, plan_import};
|
||||
use super::unique_name;
|
||||
|
||||
/// Visit `n` and every descendant (children and opacity-mask art) mutably.
|
||||
@@ -52,9 +55,56 @@ fn paint_refs(p: &mut Paint, f: &mut impl FnMut(Ref)) {
|
||||
});
|
||||
}
|
||||
|
||||
/// Visit only the records the shared reader accepted, in their original order. Consuming
|
||||
/// each accepted record once also leaves ignored duplicate surfaces and capped records alone.
|
||||
fn accepted_graphic_refs<T: PartialEq>(
|
||||
list: &mut serde_json::Value,
|
||||
accepted: Vec<T>,
|
||||
parse: impl Fn(&serde_json::Value) -> Option<T>,
|
||||
f: &mut impl FnMut(Ref),
|
||||
) {
|
||||
let Some(list) = list.as_array_mut() else { return };
|
||||
let mut accepted = accepted.into_iter().peekable();
|
||||
for value in list {
|
||||
let Some(next) = accepted.peek() else { break };
|
||||
if parse(value).as_ref() != Some(next) {
|
||||
continue;
|
||||
}
|
||||
let _ = accepted.next();
|
||||
if let Some(serde_json::Value::String(symbol)) = value.get_mut("symbol") {
|
||||
f(Ref::Symbol(symbol));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Symbol references in accepted Graphics and Map Art records, including fill/stroke effects.
|
||||
/// Each stored name is visited once, so a rename cannot feed a second rename in the same map.
|
||||
fn appearance_graphic_refs(appearance: &mut vectorcraft_doc::Appearance, f: &mut impl FnMut(Ref)) {
|
||||
use vectorcraft_render::effects as fx;
|
||||
|
||||
if fx::appearance_graphic_symbols(appearance).is_empty() {
|
||||
return;
|
||||
}
|
||||
let (effects, items) = (&mut appearance.effects, &mut appearance.items);
|
||||
for effect in effects.iter_mut().chain(items.iter_mut().flat_map(|item| item.effects_mut())) {
|
||||
if fx::takes_graphics(&effect.id) {
|
||||
let accepted = fx::mapped_graphics(&effect.params);
|
||||
if let Some(list) = effect.params.get_mut(fx::GRAPHICS) {
|
||||
accepted_graphic_refs(list, accepted, |value| fx::MappedGraphic::from_value(value).ok(), f);
|
||||
}
|
||||
} else if fx::takes_map_art(&effect.id) {
|
||||
let accepted = fx::surface_maps(&effect.params);
|
||||
if let Some(list) = effect.params.get_mut(fx::MAP_ART) {
|
||||
accepted_graphic_refs(list, accepted, |value| fx::SurfaceMap::from_value(value).ok(), f);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every resource reference in `n` and its descendants.
|
||||
fn refs(n: &mut Node, f: &mut impl FnMut(Ref)) {
|
||||
each_mut(n, &mut |n| {
|
||||
appearance_graphic_refs(&mut n.appearance, f);
|
||||
for it in &mut n.appearance.items {
|
||||
match it {
|
||||
AppearanceItem::Fill(fl) => paint_refs(&mut fl.paint, f),
|
||||
@@ -71,6 +121,9 @@ fn refs(n: &mut Node, f: &mut impl FnMut(Ref)) {
|
||||
for r in &mut t.runs {
|
||||
paint_refs(&mut r.style.fill, f);
|
||||
paint_refs(&mut r.style.stroke, f);
|
||||
if let Some(inline) = &mut r.inline {
|
||||
f(Ref::Symbol(&mut inline.symbol));
|
||||
}
|
||||
}
|
||||
if let Some(fonts) = &mut t.file_fonts {
|
||||
fonts.map_keys(|key| f(Ref::Image(key)));
|
||||
@@ -81,6 +134,14 @@ fn refs(n: &mut Node, f: &mut impl FnMut(Ref)) {
|
||||
NodeKind::SymbolInstance { symbol, .. } => f(Ref::Symbol(symbol)),
|
||||
_ => {}
|
||||
}
|
||||
if let Some(extras) = n.extras_if_any() {
|
||||
extras
|
||||
.symbol_overrides
|
||||
.iter_mut()
|
||||
.flat_map(|override_| [&mut override_.fill, &mut override_.stroke])
|
||||
.flatten()
|
||||
.for_each(|paint| paint_refs(paint, f));
|
||||
}
|
||||
// A color-masked image's masked pixels come along, and the key they were made from
|
||||
// follows the image's.
|
||||
if let Some(cm) = n.extras_if_any().and_then(|e| e.color_mask.as_deref_mut()) {
|
||||
@@ -162,7 +223,16 @@ fn canon(dst: &Document, n: &Node) -> Node {
|
||||
own.images.insert(k.clone(), blob.clone());
|
||||
}
|
||||
}
|
||||
own.reid(n)
|
||||
let mut canonical = own.reid(n);
|
||||
// Derived layout caches do not define the stored art's resource identity.
|
||||
each_mut(&mut canonical, &mut |node| {
|
||||
if let NodeKind::Text(text) = &mut node.kind {
|
||||
text.cached_bounds = None;
|
||||
text.cached_baselines.clear();
|
||||
text.cached_ink = None;
|
||||
}
|
||||
});
|
||||
canonical
|
||||
}
|
||||
|
||||
/// Do symbols `a` and `b` draw the same, whatever ids their art has ([`canon`])?
|
||||
@@ -220,12 +290,273 @@ fn brush_art(b: &mut Brush) -> Vec<&mut Node> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Bring the resources `nodes` (art from `src`) use into `dst`, renaming on conflict, and point
|
||||
/// `nodes` at the names they got.
|
||||
pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
|
||||
/// Apply the final resource-name plan to one incoming reference.
|
||||
fn rename_ref(r: Ref<'_>, maps: [&Renames; 5]) {
|
||||
let (map, key) = match r {
|
||||
Ref::Image(key) => (maps[0], key),
|
||||
Ref::Symbol(key) => (maps[1], key),
|
||||
Ref::Pattern(key) => (maps[2], key),
|
||||
Ref::Brush(key) => (maps[3], key),
|
||||
Ref::Swatch(link) => {
|
||||
if let Some((new, _)) = link.as_deref().and_then(|key| maps[4].get(key)) {
|
||||
*link = new.clone();
|
||||
}
|
||||
return;
|
||||
}
|
||||
};
|
||||
if let Some((Some(new), _)) = map.get(key.as_str()) {
|
||||
*key = new.clone();
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd)]
|
||||
enum ResourceKind {
|
||||
Symbol,
|
||||
Pattern,
|
||||
Brush,
|
||||
}
|
||||
|
||||
type ResourceKey = (ResourceKind, String);
|
||||
|
||||
/// A source definition's dependencies whose planned names have not been finalized yet.
|
||||
fn pending_dependencies(key: &ResourceKey, src: &Document, brushes: &[Brush], pending: &BTreeSet<ResourceKey>) -> BTreeSet<ResourceKey> {
|
||||
let mut dependencies = BTreeSet::new();
|
||||
let mut note = |r: Ref<'_>| {
|
||||
let key = match r {
|
||||
Ref::Symbol(name) => (ResourceKind::Symbol, name.clone()),
|
||||
Ref::Pattern(name) => (ResourceKind::Pattern, name.clone()),
|
||||
Ref::Brush(name) => (ResourceKind::Brush, name.clone()),
|
||||
Ref::Image(_) | Ref::Swatch(_) => return,
|
||||
};
|
||||
if pending.contains(&key) {
|
||||
dependencies.insert(key);
|
||||
}
|
||||
};
|
||||
match key.0 {
|
||||
ResourceKind::Symbol => {
|
||||
if let Some(symbol) = src.symbols.iter().find(|symbol| symbol.name == key.1) {
|
||||
refs(&mut (*symbol.art).clone(), &mut note);
|
||||
}
|
||||
}
|
||||
ResourceKind::Pattern => {
|
||||
if let Some(pattern) = src.pattern(&key.1) {
|
||||
for art in &pattern.art {
|
||||
refs(&mut (**art).clone(), &mut note);
|
||||
}
|
||||
}
|
||||
}
|
||||
ResourceKind::Brush => {
|
||||
if let Some(mut brush) = brushes.iter().find(|brush| brush.name == key.1).cloned() {
|
||||
for art in brush_art(&mut brush) {
|
||||
refs(art, &mut note);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
dependencies
|
||||
}
|
||||
|
||||
/// Prefer the original name, then only canonical numbered variants from `unique_name`.
|
||||
/// A free original name keeps its planned copy; another incoming name is never stolen.
|
||||
fn matching_name<T>(base: &str, definitions: &[T], used: &[String], name: impl Fn(&T) -> &str, same: impl Fn(&T) -> bool) -> Option<String> {
|
||||
let original = definitions.iter().find(|definition| name(definition) == base)?;
|
||||
if same(original) {
|
||||
return Some(base.to_string());
|
||||
}
|
||||
let prefix = format!("{base} ");
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut aliases: Vec<_> = definitions
|
||||
.iter()
|
||||
.filter_map(|definition| {
|
||||
let candidate = name(definition);
|
||||
// Match the first definition, as the document name lookups do.
|
||||
if !seen.insert(candidate.to_string()) {
|
||||
return None;
|
||||
}
|
||||
let suffix = candidate.strip_prefix(&prefix)?;
|
||||
if suffix.starts_with('0') || !suffix.bytes().all(|byte| byte.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
let number = suffix.parse::<u64>().ok()?;
|
||||
(number >= 2 && !used.iter().any(|used| used == candidate)).then_some((number, definition))
|
||||
})
|
||||
.collect();
|
||||
aliases.sort_unstable_by_key(|(number, _)| *number);
|
||||
aliases.into_iter().find_map(|(_, definition)| same(definition).then(|| name(definition).to_string()))
|
||||
}
|
||||
|
||||
/// Compare final incoming content, not the original references or destination's resource name.
|
||||
fn reusable_name(
|
||||
key: &ResourceKey,
|
||||
dst: &Document,
|
||||
src: &Document,
|
||||
src_brushes: &[Brush],
|
||||
dst_brushes: &[Brush],
|
||||
used: &Used,
|
||||
maps: [&Renames; 5],
|
||||
) -> Option<String> {
|
||||
match key.0 {
|
||||
ResourceKind::Symbol => {
|
||||
let source = src.symbols.iter().find(|symbol| symbol.name == key.1)?;
|
||||
let mut incoming = source.clone();
|
||||
refs(Arc::make_mut(&mut incoming.art), &mut |r| rename_ref(r, maps));
|
||||
matching_name(
|
||||
&key.1,
|
||||
&dst.symbols,
|
||||
&used.symbols,
|
||||
|symbol| &symbol.name,
|
||||
|candidate| {
|
||||
let mut normalized = candidate.clone();
|
||||
normalized.name = incoming.name.clone();
|
||||
same_symbol(dst, &normalized, &incoming) && SymbolOptions::of(dst, &candidate.name) == SymbolOptions::of(src, &source.name)
|
||||
},
|
||||
)
|
||||
}
|
||||
ResourceKind::Pattern => {
|
||||
let mut incoming = src.pattern(&key.1)?.clone();
|
||||
for art in &mut incoming.art {
|
||||
refs(Arc::make_mut(art), &mut |r| rename_ref(r, maps));
|
||||
}
|
||||
matching_name(
|
||||
&key.1,
|
||||
&dst.patterns,
|
||||
&used.patterns,
|
||||
|pattern| &pattern.name,
|
||||
|candidate| {
|
||||
let mut normalized = candidate.clone();
|
||||
normalized.name = incoming.name.clone();
|
||||
same_pattern(dst, &normalized, &incoming)
|
||||
},
|
||||
)
|
||||
}
|
||||
ResourceKind::Brush => {
|
||||
let mut incoming = src_brushes.iter().find(|brush| brush.name == key.1)?.clone();
|
||||
for art in brush_art(&mut incoming) {
|
||||
refs(art, &mut |r| rename_ref(r, maps));
|
||||
*art = canon(dst, art);
|
||||
}
|
||||
matching_name(
|
||||
&key.1,
|
||||
dst_brushes,
|
||||
&used.brushes,
|
||||
|brush| &brush.name,
|
||||
|candidate| {
|
||||
let mut normalized = candidate.clone();
|
||||
normalized.name = incoming.name.clone();
|
||||
for art in brush_art(&mut normalized) {
|
||||
*art = canon(dst, art);
|
||||
}
|
||||
normalized == incoming
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Finalize each copied definition only after its copied dependencies. Each key/edge is
|
||||
/// processed once; a cycle (and its unresolved parents) conservatively keeps the planned copies.
|
||||
fn reuse_remapped_resources(
|
||||
dst: &Document,
|
||||
src: &Document,
|
||||
src_brushes: &[Brush],
|
||||
dst_brushes: &[Brush],
|
||||
used: &Used,
|
||||
fixed: [&Renames; 2],
|
||||
changing: [&mut Renames; 3],
|
||||
) {
|
||||
let [symbols, patterns, brushes] = changing;
|
||||
let mut pending = BTreeSet::new();
|
||||
for (kind, map) in [(ResourceKind::Symbol, &*symbols), (ResourceKind::Pattern, &*patterns), (ResourceKind::Brush, &*brushes)] {
|
||||
pending.extend(map.iter().filter(|(_, (_, copy))| *copy).map(|(name, _)| (kind, name.clone())));
|
||||
}
|
||||
let mut waiting = BTreeMap::new();
|
||||
let mut parents: BTreeMap<ResourceKey, Vec<ResourceKey>> = BTreeMap::new();
|
||||
let mut ready = BTreeSet::new();
|
||||
for key in &pending {
|
||||
let dependencies = pending_dependencies(key, src, src_brushes, &pending);
|
||||
if dependencies.is_empty() {
|
||||
ready.insert(key.clone());
|
||||
}
|
||||
waiting.insert(key.clone(), dependencies.len());
|
||||
for dependency in dependencies {
|
||||
parents.entry(dependency).or_default().push(key.clone());
|
||||
}
|
||||
}
|
||||
while let Some(key) = ready.pop_first() {
|
||||
let maps = [fixed[0], &*symbols, &*patterns, &*brushes, fixed[1]];
|
||||
if let Some(name) = reusable_name(&key, dst, src, src_brushes, dst_brushes, used, maps) {
|
||||
let map = match key.0 {
|
||||
ResourceKind::Symbol => &mut *symbols,
|
||||
ResourceKind::Pattern => &mut *patterns,
|
||||
ResourceKind::Brush => &mut *brushes,
|
||||
};
|
||||
map.insert(key.1.clone(), (Some(name), false));
|
||||
}
|
||||
for parent in parents.remove(&key).into_iter().flatten() {
|
||||
if let Some(count) = waiting.get_mut(&parent) {
|
||||
*count -= 1;
|
||||
if *count == 0 {
|
||||
ready.insert(parent);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Remap only incoming users before resource equality decides whether to share or copy.
|
||||
/// Report actual family renaming for the final copied-resource reuse phase.
|
||||
fn remap_composite_families(src: &Document, nodes: &mut [Node], used: &Used, brushes: &mut [Brush], plan: &CompositeImport) -> (Document, bool) {
|
||||
let mut staged = src.clone();
|
||||
let mut aliased = false;
|
||||
for node in nodes.iter_mut() {
|
||||
each_mut(node, &mut |node| {
|
||||
node_families(node, &mut |family| {
|
||||
aliased |= plan.rename(family);
|
||||
});
|
||||
});
|
||||
}
|
||||
for symbol in staged.symbols.iter_mut().filter(|symbol| used.symbols.contains(&symbol.name)) {
|
||||
each_mut(Arc::make_mut(&mut symbol.art), &mut |node| {
|
||||
node_families(node, &mut |family| {
|
||||
aliased |= plan.rename(family);
|
||||
});
|
||||
});
|
||||
}
|
||||
for pattern in staged.patterns.iter_mut().filter(|pattern| used.patterns.contains(&pattern.name)) {
|
||||
for art in &mut pattern.art {
|
||||
each_mut(Arc::make_mut(art), &mut |node| {
|
||||
node_families(node, &mut |family| {
|
||||
aliased |= plan.rename(family);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
for brush in brushes.iter_mut().filter(|brush| used.brushes.contains(&brush.name)) {
|
||||
for art in brush_art(brush) {
|
||||
each_mut(art, &mut |node| {
|
||||
node_families(node, &mut |family| {
|
||||
aliased |= plan.rename(family);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
(staged, aliased)
|
||||
}
|
||||
|
||||
/// Discover the incoming resource frontier and its composite-font users before planning
|
||||
/// names or changing either document. Resource order and the no-composite fast path stay shared.
|
||||
fn collect_resources(src: &Document, nodes: &mut [Node]) -> (Used, Vec<Brush>, BTreeSet<String>) {
|
||||
let mut used = Used::default();
|
||||
let composites = !src.composite_fonts.is_empty();
|
||||
let mut families = BTreeSet::new();
|
||||
let mut note_family = |name: &mut String| {
|
||||
families.insert(name.to_lowercase());
|
||||
};
|
||||
for n in nodes.iter_mut() {
|
||||
refs(n, &mut |r| used.note(r));
|
||||
if composites {
|
||||
each_mut(n, &mut |node| node_families(node, &mut note_family));
|
||||
}
|
||||
}
|
||||
let src_brushes = vectorcraft_brush::library(src);
|
||||
// Symbol, pattern and brush art and tint swatches can use more resources (the lists grow while
|
||||
@@ -254,8 +585,29 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
|
||||
}
|
||||
for mut a in art {
|
||||
refs(&mut a, &mut |r| used.note(r));
|
||||
if composites {
|
||||
each_mut(&mut a, &mut |node| node_families(node, &mut note_family));
|
||||
}
|
||||
}
|
||||
}
|
||||
(used, src_brushes, families)
|
||||
}
|
||||
|
||||
/// Bring the resources `nodes` (art from `src`) use into `dst`, renaming on conflict, and point
|
||||
/// `nodes` at the names they got.
|
||||
pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node], cmd: &str) -> Result<()> {
|
||||
let (used, mut src_brushes, families) = collect_resources(src, nodes);
|
||||
let fonts = src.composite_fonts.iter().filter(|font| families.contains(&font.name.to_lowercase())).cloned().collect::<Vec<_>>();
|
||||
// All representability/validation errors precede incoming or destination mutation.
|
||||
let plan = if fonts.is_empty() { None } else { Some(plan_import(fonts, families, dst, cmd)?) };
|
||||
let staged;
|
||||
let mut aliased = false;
|
||||
let src = if let Some(plan) = &plan {
|
||||
(staged, aliased) = remap_composite_families(src, nodes, &used, &mut src_brushes, plan);
|
||||
&staged
|
||||
} else {
|
||||
src
|
||||
};
|
||||
|
||||
let images = names(&used.images, |k| src.images.get(k), |k| dst.images.get(k), |a, b| a == b, |c| dst.images.contains_key(c));
|
||||
// Symbol and pattern art copied in takes ids of `dst`, so their art is compared by what it
|
||||
@@ -264,7 +616,7 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
|
||||
&used.symbols,
|
||||
|n| src.symbols.iter().find(|s| s.name == n),
|
||||
|n| dst.symbols.iter().find(|s| s.name == n),
|
||||
|a, b| same_symbol(dst, a, b),
|
||||
|a, b| same_symbol(dst, a, b) && SymbolOptions::of(dst, &a.name) == SymbolOptions::of(src, &b.name),
|
||||
|c| dst.symbols.iter().any(|s| s.name == c),
|
||||
);
|
||||
let mut patterns = names(&used.patterns, |n| src.pattern(n), |n| dst.pattern(n), |a, b| same_pattern(dst, a, b), |c| dst.pattern(c).is_some());
|
||||
@@ -330,23 +682,14 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
|
||||
unshare(&mut brushes, &bru, &used.brushes, |c| dst_brushes.iter().any(|b| b.name == c));
|
||||
}
|
||||
|
||||
let mut rename = |r: Ref| {
|
||||
let (map, k) = match r {
|
||||
Ref::Image(k) => (&images, k),
|
||||
Ref::Symbol(k) => (&symbols, k),
|
||||
Ref::Pattern(k) => (&patterns, k),
|
||||
Ref::Brush(k) => (&brushes, k),
|
||||
Ref::Swatch(link) => {
|
||||
if let Some((new, _)) = link.as_deref().and_then(|k| swatches.get(k)) {
|
||||
*link = new.clone();
|
||||
}
|
||||
return;
|
||||
}
|
||||
};
|
||||
if let Some((Some(new), _)) = map.get(k.as_str()) {
|
||||
*k = new.clone();
|
||||
}
|
||||
};
|
||||
if aliased || symbols.values().any(|(_, copy)| *copy) {
|
||||
reuse_remapped_resources(dst, src, &src_brushes, &dst_brushes, &used, [&images, &swatches], [&mut symbols, &mut patterns, &mut brushes]);
|
||||
}
|
||||
|
||||
if let Some(plan) = plan {
|
||||
dst.composite_fonts = plan.combined.into();
|
||||
}
|
||||
let mut rename = |r: Ref| rename_ref(r, [&images, &symbols, &patterns, &brushes, &swatches]);
|
||||
for n in nodes.iter_mut() {
|
||||
refs(n, &mut rename);
|
||||
}
|
||||
@@ -375,6 +718,7 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
|
||||
// The art takes ids of `dst`: those of `src` may name objects of `dst` already.
|
||||
def.art = Arc::new(dst.reid(&def.art));
|
||||
dst.symbols.push(def);
|
||||
SymbolOptions::of(src, old).give(dst, new);
|
||||
}
|
||||
}
|
||||
for (old, new) in copies(&patterns) {
|
||||
@@ -406,4 +750,5 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
|
||||
dst.swatches.push(w);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -178,6 +178,10 @@ fn opened_document_art(
|
||||
super::super::links::resolve(&mut l.doc, super::super::links::LinkBase::file(path), false, false);
|
||||
}
|
||||
l.doc.drop_edit_modes();
|
||||
// Measure and crop in this source's composite fonts, not those of the front document.
|
||||
// The existing thread-local loan restores its caller's context on every return or unwind.
|
||||
let source_fonts = l.doc.composite_fonts.clone();
|
||||
let _source_fonts = vectorcraft_text::FontDb::global().lend_document_composite_fonts(&source_fonts);
|
||||
// The native file does not store type's layout bounds. Measure them before cropping or
|
||||
// copying the art, so the placed group keeps the positions of aligned point type.
|
||||
for warning in crate::Session::refresh_text_bounds(&mut l.doc) {
|
||||
@@ -544,7 +548,7 @@ pub(crate) fn expand(d: &mut Document, id: NodeId, cmd: &str) -> Result<()> {
|
||||
let a = document_art(p.link.name(), &bytes, Some(&p.link.path), p.page(), p.bounding, p.page_box, cmd)?;
|
||||
let m = p.art_xf(a.frame).ok_or_else(|| bad(cmd, format!("object {} has no size", id.0)))?;
|
||||
let mut nodes = a.nodes;
|
||||
super::adopt::adopt(d, &a.doc, &mut nodes);
|
||||
super::adopt::adopt(d, &a.doc, &mut nodes, cmd)?;
|
||||
let mut children: Vec<Arc<Node>> = nodes.iter().map(|n| Arc::new(d.reid(n))).collect();
|
||||
if let Some(r) = a.clip {
|
||||
children.insert(0, Arc::new(super::clip_path(d.alloc_id(), r)));
|
||||
|
||||
@@ -750,6 +750,7 @@ pub const SWITCHING_LABELS: &[&str] = &[
|
||||
"Lock Guides",
|
||||
"Hide Slices",
|
||||
"Show Print Tiling",
|
||||
"Show Missing Links",
|
||||
"Lock Grid",
|
||||
"Edit Envelope",
|
||||
"Edit Contents",
|
||||
|
||||
@@ -174,6 +174,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[
|
||||
choice(&[("touching", "Touching"), ("enclosed", "Fully Enclosed"), ("directional", "Drag Direction")])
|
||||
),
|
||||
p!("objectSelectionByPathOnly", "Selection & Anchor Display", "Selection", "Object Selection by Path Only", bool),
|
||||
p!("selectInsideUnfilledShapes", "Selection & Anchor Display", "Selection", "Select Inside Unfilled Shapes", bool),
|
||||
p!("snapToPointTolerance", "Selection & Anchor Display", "Selection", "Snap to Point", num(1.0, 8.0, "px")),
|
||||
p!("ctrlClickSelectsBehind", "Selection & Anchor Display", "Selection", "Command Click to Select Objects Behind", bool),
|
||||
p!("zoomToSelection", "Selection & Anchor Display", "Selection", "Zoom to Selection", bool),
|
||||
|
||||
@@ -132,6 +132,10 @@ pub struct DocState {
|
||||
pub spelling_ignored: std::collections::BTreeSet<String>,
|
||||
/// View → Show Transparency Grid, per document (saved view state, not undoable).
|
||||
pub transparency_grid: bool,
|
||||
/// View → Show Missing Links: transient canvas decoration, never document artwork.
|
||||
pub show_missing_links: bool,
|
||||
/// Last worker scan, tied to the exact document snapshot it inspected.
|
||||
pub missing_link_markers: Option<(Arc<Document>, Vec<NodeId>)>,
|
||||
/// The format Save writes ([`cmd::fileio::SAVE_FORMATS`]): the one the document was opened
|
||||
/// from or last saved as.
|
||||
pub format: &'static str,
|
||||
@@ -491,6 +495,30 @@ impl SameContent {
|
||||
}
|
||||
|
||||
impl DocState {
|
||||
/// Cached missing links still present and visible in the current art. Geometry-only edits
|
||||
/// keep their markers moving with the objects; relinking or embedding drops them immediately.
|
||||
pub fn marked_missing_links(&self) -> Vec<NodeId> {
|
||||
if !self.show_missing_links {
|
||||
return vec![];
|
||||
}
|
||||
let Some((before, ids)) = &self.missing_link_markers else { return vec![] };
|
||||
fn link(n: &vectorcraft_doc::Node) -> Option<&vectorcraft_doc::LinkInfo> {
|
||||
match &n.kind {
|
||||
NodeKind::Image(im) => im.link.as_ref(),
|
||||
NodeKind::PlacedDocument(p) => Some(&p.link),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
ids.iter()
|
||||
.copied()
|
||||
.filter(|id| {
|
||||
let old = before.node(*id).and_then(link);
|
||||
let now = self.doc.node(*id).and_then(link);
|
||||
now.is_some() && now == old && self.doc.is_visible(*id)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn new(mut doc: Document, path: Option<String>) -> Self {
|
||||
let active_layer = doc.default_layer();
|
||||
// Saved view state lives here while the document is open (saves write it back).
|
||||
@@ -532,6 +560,8 @@ impl DocState {
|
||||
mask_view: None,
|
||||
spelling_ignored: Default::default(),
|
||||
transparency_grid,
|
||||
show_missing_links: false,
|
||||
missing_link_markers: None,
|
||||
format: "vectorcraft",
|
||||
save_options: Default::default(),
|
||||
save_artboards: vec![],
|
||||
|
||||
@@ -93,7 +93,7 @@ impl AutomationRoots {
|
||||
|
||||
/// Roots that grant no access of either kind: inside [`confine`] with them, every path a
|
||||
/// command reads or writes is refused.
|
||||
pub(crate) fn none() -> Arc<Self> {
|
||||
pub fn none() -> Arc<Self> {
|
||||
Arc::new(Self { read: Vec::new(), write: Vec::new() })
|
||||
}
|
||||
|
||||
@@ -124,6 +124,11 @@ impl AutomationRoots {
|
||||
if roots.iter().any(|r| inside(real, &r.resolved)) { Ok(()) } else { Err(refused(roots, &real.display().to_string(), access)) }
|
||||
}
|
||||
|
||||
/// The folders of the kind `access`, as people read them.
|
||||
pub fn folders(&self, access: Access) -> impl Iterator<Item = &Path> {
|
||||
self.of(access).iter().map(|r| r.shown.as_path())
|
||||
}
|
||||
|
||||
/// The roots of the kind `access`.
|
||||
fn of(&self, access: Access) -> &[Root] {
|
||||
match access {
|
||||
|
||||
@@ -46,6 +46,9 @@ pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command};
|
||||
pub use cmd::{EyedropperOptions, PathfinderOptions};
|
||||
pub use journal::Journal;
|
||||
pub use tooling::{UiRequest, ViewInfo};
|
||||
/// DWG drawings are converted in a child process: a program calls `dwg::serve_if_asked` first in
|
||||
/// `main` and `dwg::use_own_worker` at startup.
|
||||
pub use vectorcraft_cad::dwg;
|
||||
pub use vectorcraft_doc as doc;
|
||||
pub use vectorcraft_doc::cancel;
|
||||
pub use vectorcraft_pathops::{SIMPLIFY_LEVEL, SMOOTH_AUTO_LEVEL, simplify_level_tolerance};
|
||||
|
||||
@@ -27,9 +27,24 @@ use crate::{Result, Session};
|
||||
/// A file's size and modification time (nanoseconds since 1970).
|
||||
pub type Stamp = (u64, u128);
|
||||
|
||||
/// Stamps of a document's linked files taken on a worker thread: (document uid, [(file,
|
||||
/// object ids, stamp)]), the condition the worker signals when it ends, and whether it has.
|
||||
pub type LinkScan = Arc<(Mutex<Option<(u64, Vec<(String, Vec<u64>, Option<Stamp>)>)>>, Condvar, AtomicBool)>;
|
||||
/// A document's linked-file scan, the condition the worker signals when it ends, and whether
|
||||
/// it has. Includes missing-link marker ids when their view toggle is enabled.
|
||||
pub type LinkScan = Arc<(Mutex<Option<LinkScanResult>>, Condvar, AtomicBool)>;
|
||||
|
||||
/// A worker's stamps and optional missing-link overlay scan of the same document snapshot.
|
||||
pub struct LinkScanResult {
|
||||
uid: u64,
|
||||
stamps: Vec<(String, Vec<u64>, Option<Stamp>)>,
|
||||
markers: Option<(Arc<vectorcraft_doc::Document>, Vec<vectorcraft_doc::NodeId>)>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl LinkScanResult {
|
||||
/// A look's stamps of document `uid`'s linked files, with no missing-link scan.
|
||||
pub(crate) fn stamps(uid: u64, stamps: Vec<(String, Vec<u64>, Option<Stamp>)>) -> Self {
|
||||
Self { uid, stamps, markers: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// Held by a look's worker: marks the look as ended and wakes [`Session::wait_link_scan`] when
|
||||
/// dropped, whether the worker returned or unwound.
|
||||
@@ -83,6 +98,29 @@ pub(crate) fn update_changed(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Whether the active document shows missing links but has no marker scan yet (the overlay
|
||||
/// was just turned on, or its first scan saw art that has since changed): the desktop app
|
||||
/// then starts a look at once instead of waiting for the next periodic one.
|
||||
pub fn missing_link_scan_due(&self) -> bool {
|
||||
self.link_scan.is_none() && self.active().is_some_and(|st| st.show_missing_links && st.missing_link_markers.is_none())
|
||||
}
|
||||
|
||||
/// Find the active document's missing links again, here and now, when it shows them and its art
|
||||
/// changed since they were last found (or they never were); returns whether it did. This reads
|
||||
/// linked files on the calling thread, so only the web app calls it: it has no files to read,
|
||||
/// so every linked file is missing there, and no link watch worker to scan in the background.
|
||||
/// Artwork restored or placed while the overlay is on is then marked too. The desktop app
|
||||
/// scans on the worker instead ([`Session::start_link_scan`]).
|
||||
pub fn mark_missing_links_in_place(&mut self) -> bool {
|
||||
let Some(st) = self.active_mut() else { return false };
|
||||
if !st.show_missing_links || st.missing_link_markers.as_ref().is_some_and(|(seen, _)| Arc::ptr_eq(seen, &st.doc)) {
|
||||
return false;
|
||||
}
|
||||
let ids = crate::cmd::links::missing_markers(&st.doc, crate::cmd::links::LinkBase::of(st));
|
||||
st.missing_link_markers = Some((st.doc.clone(), ids));
|
||||
true
|
||||
}
|
||||
|
||||
/// Start stamping the active document's linked files on a worker thread, unless a look is
|
||||
/// still running, a script is running (or the build has no files to look at: the web app).
|
||||
pub fn start_link_scan(&mut self) {
|
||||
@@ -94,7 +132,14 @@ impl Session {
|
||||
// A confined caller's roots, else what the caller that opened the document may read (the
|
||||
// desktop frame is unconfined).
|
||||
let opened_by = st.opened_by.clone();
|
||||
let marker_doc = st.show_missing_links.then(|| st.doc.clone());
|
||||
let links_from = st.links_from.clone();
|
||||
if files.is_empty() {
|
||||
// Nothing linked, so nothing missing: an empty scan, which also ends
|
||||
// [`Session::missing_link_scan_due`] without starting a worker.
|
||||
if let Some(st) = self.docs.iter_mut().find(|st| st.uid == uid) {
|
||||
st.missing_link_markers = st.show_missing_links.then(|| (st.doc.clone(), vec![]));
|
||||
}
|
||||
return;
|
||||
}
|
||||
let slot: LinkScan = Arc::default();
|
||||
@@ -103,12 +148,18 @@ impl Session {
|
||||
let spawned = std::thread::Builder::new().name("link-watch".into()).spawn(move || {
|
||||
// Marks the look as ended when the worker returns or unwinds.
|
||||
let _ended = Ended(out.clone());
|
||||
let stamps = scope.run(|| {
|
||||
let (stamps, markers) = scope.run(|| {
|
||||
crate::file_access::confine(crate::file_access::current().or(opened_by).as_ref(), || {
|
||||
files.into_iter().map(|(p, ids)| (p.clone(), ids, stamp(&p, doc_path.as_deref()))).collect()
|
||||
let stamps = files.into_iter().map(|(p, ids)| (p.clone(), ids, stamp(&p, doc_path.as_deref()))).collect();
|
||||
let markers = marker_doc.map(|doc| {
|
||||
let base = crate::cmd::links::LinkBase::of_files(doc_path.as_deref(), links_from.as_deref());
|
||||
let ids = crate::cmd::links::missing_markers(&doc, base);
|
||||
(doc, ids)
|
||||
});
|
||||
(stamps, markers)
|
||||
})
|
||||
});
|
||||
*out.0.lock().unwrap_or_else(PoisonError::into_inner) = Some((uid, stamps));
|
||||
*out.0.lock().unwrap_or_else(PoisonError::into_inner) = Some(LinkScanResult { uid, stamps, markers });
|
||||
});
|
||||
if spawned.is_ok() {
|
||||
self.link_scan = Some(slot);
|
||||
@@ -123,8 +174,15 @@ impl Session {
|
||||
return None;
|
||||
}
|
||||
self.link_scan.take_if(|scan| ended_without_stamps(scan, |ended| ended.load(Ordering::SeqCst)));
|
||||
let (uid, stamps) = self.link_scan.as_ref()?.0.lock().unwrap_or_else(PoisonError::into_inner).take()?;
|
||||
let LinkScanResult { uid, stamps, markers } = self.link_scan.as_ref()?.0.lock().unwrap_or_else(PoisonError::into_inner).take()?;
|
||||
self.link_scan = None;
|
||||
if let Some(st) = self.docs.iter_mut().find(|st| st.uid == uid)
|
||||
&& st.show_missing_links
|
||||
&& let Some((doc, ids)) = markers
|
||||
&& Arc::ptr_eq(&st.doc, &doc)
|
||||
{
|
||||
st.missing_link_markers = Some((doc, ids));
|
||||
}
|
||||
Some(self.apply_link_stamps(uid, stamps, false))
|
||||
}
|
||||
|
||||
|
||||
@@ -134,6 +134,9 @@ pub struct Prefs {
|
||||
/// Selection-tool marquee: touching (default), enclosed, or screen drag direction.
|
||||
pub marquee_selection: String,
|
||||
pub object_selection_by_path_only: bool,
|
||||
/// Off (the default), a selection tool click inside a closed path with no fill starts a
|
||||
/// marquee; on, it selects the path when no other object is hit there (#9175).
|
||||
pub select_inside_unfilled_shapes: bool,
|
||||
pub snap_to_point_tolerance: f64,
|
||||
pub ctrl_click_selects_behind: bool,
|
||||
pub zoom_to_selection: bool,
|
||||
@@ -593,6 +596,7 @@ impl Default for Prefs {
|
||||
selection_tolerance: 3.0,
|
||||
marquee_selection: "touching".into(),
|
||||
object_selection_by_path_only: false,
|
||||
select_inside_unfilled_shapes: false,
|
||||
snap_to_point_tolerance: 2.0,
|
||||
ctrl_click_selects_behind: true,
|
||||
zoom_to_selection: true,
|
||||
|
||||
@@ -853,9 +853,24 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
let locks = d.locked_artboards();
|
||||
let on_locked: Vec<u64> = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect();
|
||||
// A clipping path whose group or layer keeps other art would leave the next object clipping it.
|
||||
let going: std::collections::HashSet<NodeId> = ids.iter().copied().collect();
|
||||
// Deleting every path of a compound path would leave it empty, so a compound path that
|
||||
// clips counts as deleted too.
|
||||
let mut going: std::collections::HashSet<NodeId> = ids.iter().copied().collect();
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut emptied: Vec<NodeId> = Vec::new();
|
||||
for p in ids.iter().filter_map(|i| d.parent_of(*i)) {
|
||||
if going.contains(&p) || !seen.insert(p) {
|
||||
continue;
|
||||
}
|
||||
let all_go = |n: &crate::doc::Node| n.children().is_some_and(|k| k.iter().all(|k| going.contains(&k.id)));
|
||||
if d.node(p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }) && all_go(n)) {
|
||||
emptied.push(p);
|
||||
}
|
||||
}
|
||||
going.extend(emptied.iter().copied());
|
||||
let masks: Vec<u64> = ids
|
||||
.iter()
|
||||
.chain(&emptied)
|
||||
.filter(|i| {
|
||||
d.parent_of(**i).and_then(|p| d.node(p)).is_some_and(|p| {
|
||||
let kids = p.children().map_or(&[][..], Vec::as_slice);
|
||||
|
||||
@@ -394,6 +394,19 @@ fn paint_owner<'a>(d: &'a crate::Document, id: NodeId, n: &'a crate::doc::Node)
|
||||
d.parent_of(id).and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. }) || p.is_compound_shape()).unwrap_or(n)
|
||||
}
|
||||
|
||||
/// A script's new path goes on the active layer while it is shown and unlocked, or the topmost
|
||||
/// shown, unlocked layer otherwise. While an opacity mask, pattern or symbol is being edited,
|
||||
/// the path goes on the layer recorded by that edit mode. `create::on_layer` validates the layer.
|
||||
fn new_path_layer(st: &crate::DocState) -> Option<NodeId> {
|
||||
let d = &st.doc;
|
||||
if let Some(layer) =
|
||||
d.mask_edit.map(|e| e.layer).or_else(|| d.pattern_edit.as_ref().map(|e| e.layer)).or_else(|| d.symbol_edit.as_ref().map(|e| e.layer))
|
||||
{
|
||||
return Some(layer);
|
||||
}
|
||||
st.current_layer().filter(|l| d.is_editable(*l)).or_else(|| d.default_layer())
|
||||
}
|
||||
|
||||
/// Runs a path creation command with its layer placement recorded.
|
||||
fn drawing_normally(h: &super::Host, parent: Option<NodeId>, id: &str, params: &Value) -> std::result::Result<(Data, Value), HostError> {
|
||||
let mut params = params.clone();
|
||||
@@ -679,7 +692,7 @@ fn made_id(r: &(Data, Value)) -> std::result::Result<NodeId, HostError> {
|
||||
fn make(h: &super::Host, doc: Doc, id: &str, params: &Value, reversed: bool) -> Answer {
|
||||
let made = keeping_paint(h, || {
|
||||
on_doc(h, doc.uid, true, |h| {
|
||||
let parent = with_doc(h, doc, |_, st| st.current_layer().or_else(|| st.doc.default_layer()));
|
||||
let parent = with_doc(h, doc, |_, st| new_path_layer(st));
|
||||
let id = made_id(&drawing_normally(h, parent, id, params)?)?;
|
||||
if reversed {
|
||||
command(h, "path.reverse", &json!({"ids": [id.0]}))?;
|
||||
@@ -845,7 +858,7 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let ap = h.session.borrow().new_art();
|
||||
ap.fill_paint().is_none() && ap.stroke_paint().is_none()
|
||||
};
|
||||
let parent = with_doc(h, doc, |_, st| st.current_layer().or_else(|| st.doc.default_layer()));
|
||||
let parent = with_doc(h, doc, |_, st| new_path_layer(st));
|
||||
let id = made_id(&drawing_normally(h, parent, "path.create", &json!({"d": ""}))?)?;
|
||||
if unpainted {
|
||||
command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0], "objectOnly": true}))?;
|
||||
|
||||
@@ -661,6 +661,7 @@ impl Session {
|
||||
self.pending_paint = None;
|
||||
// The previous preview's Assign Profile is undone with it.
|
||||
self.sync_front_profiles();
|
||||
cmd::compositefonts::sync(self);
|
||||
let rw = cmd::distortcmds::perspective_rewrite(self, cmd, params).or_else(|| cmd::bounds_rewrite(self, cmd, params));
|
||||
let (cmd, params) = rw.as_ref().map_or((cmd, params), |(c, p)| (c.as_str(), p));
|
||||
// A selected object's converted appearance must not replace the current paints while
|
||||
@@ -877,6 +878,7 @@ impl Session {
|
||||
deselect_hidden(&menu, &st.doc, &mut st.selection);
|
||||
// A canceled preview's Assign Profile is undone with it.
|
||||
self.sync_front_profiles();
|
||||
cmd::compositefonts::sync(self);
|
||||
// With New Art Has Basic Appearance off, new art takes the appearance of the selection as
|
||||
// the document has it again, not as a preview left it. An interaction that changed only the
|
||||
// defaults (`defaultsOnly: true`) leaves the defaults it began with.
|
||||
|
||||
@@ -25,6 +25,12 @@ fn with_settled_warnings(mut r: Value, settled: &[String]) -> Value {
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Run a command callback and keep warnings from every preview it settles or restores.
|
||||
pub(crate) fn command_with_settled_warnings(&mut self, f: impl FnOnce(&mut Self) -> Result<Value>) -> Result<Value> {
|
||||
let (r, settled) = self.collect_settled_warnings(f);
|
||||
r.map(|v| with_settled_warnings(v, &settled))
|
||||
}
|
||||
|
||||
/// `spec`'s `enabled` with `ids` selected instead of the selection, which is then put back.
|
||||
fn enabled_with_selection(&mut self, spec: &CommandSpec, ids: Vec<NodeId>) -> std::result::Result<(), String> {
|
||||
let Some(d) = self.active_mut() else { return (spec.enabled)(self) };
|
||||
@@ -121,10 +127,9 @@ impl Session {
|
||||
// A preview that a top-level command applied first (a drag with Real-time Drawing off, kept
|
||||
// before Undo) reports its warning in the command's result.
|
||||
let r = if self.depth == 0 {
|
||||
let (r, settled) = self.collect_settled_warnings(|s| {
|
||||
self.command_with_settled_warnings(|s| {
|
||||
if outside { s.outside_interaction(id, params, |s| s.execute_spec(spec, id, params)) } else { s.execute_spec(spec, id, params) }
|
||||
});
|
||||
r.map(|v| with_settled_warnings(v, &settled))
|
||||
})
|
||||
} else {
|
||||
self.execute_spec(spec, id, params)
|
||||
};
|
||||
@@ -253,6 +258,10 @@ impl Session {
|
||||
// after an undone or redone Assign Profile, a failed or panicked command's documents put
|
||||
// back, and a batch step, before the next step converts through them.
|
||||
self.sync_front_profiles();
|
||||
if self.depth != 0 {
|
||||
// The next batch step can measure/outline definitions this step adopted.
|
||||
cmd::compositefonts::sync(self);
|
||||
}
|
||||
if r.is_err() && self.depth == 0 {
|
||||
self.batch_paint_docs.clear();
|
||||
// A failed or panicked command's documents are put back: type is drawn in their
|
||||
|
||||
@@ -118,6 +118,7 @@ mod livecorners;
|
||||
mod maskview;
|
||||
pub(super) mod menucmds;
|
||||
mod mesh_picks;
|
||||
mod missing_links;
|
||||
mod moved;
|
||||
mod nativefile;
|
||||
mod newart;
|
||||
|
||||
@@ -173,12 +173,12 @@ fn export_writes_the_sheet_and_rasterized_art() {
|
||||
// Without a path: the CSS as data, the pictures as base64.
|
||||
let r = run(&mut s, "css.export", json!({"scope": "all", "rasterize": true}));
|
||||
let data = r["data"].as_str().unwrap();
|
||||
assert!(data.contains(".rectangle {") && data.contains(".path {\n") && data.contains("background-image: url(path.png);"), "{data}");
|
||||
assert!(data.contains(".rectangle {") && data.contains(".star {\n") && data.contains("background-image: url(star.png);"), "{data}");
|
||||
assert!(data.ends_with("}\n"));
|
||||
assert_eq!(r["rules"], json!(2));
|
||||
let images = r["images"].as_array().unwrap();
|
||||
assert_eq!(images.len(), 1, "only the star is rasterized");
|
||||
assert_eq!(images[0]["name"], json!("path.png"));
|
||||
assert_eq!(images[0]["name"], json!("star.png"));
|
||||
let png = vectorcraft_format::base64_decode(images[0]["dataBase64"].as_str().unwrap()).unwrap();
|
||||
assert!(png.starts_with(b"\x89PNG"));
|
||||
// The selection alone (the star, selected last).
|
||||
@@ -263,9 +263,9 @@ fn export_to_a_path_puts_the_pictures_next_to_the_sheet() {
|
||||
let path = dir.join("site.css");
|
||||
let r = run(&mut s, "css.export", json!({"path": path.to_string_lossy(), "rasterize": true}));
|
||||
let written = std::fs::read_to_string(&path).unwrap();
|
||||
assert!(written.contains("url(path.png)"), "{written}");
|
||||
assert!(written.contains("url(star.png)"), "{written}");
|
||||
assert_eq!(r["bytes"], json!(written.len()));
|
||||
let png = dir.join("path.png");
|
||||
let png = dir.join("star.png");
|
||||
assert_eq!(r["images"], json!([png.to_string_lossy()]));
|
||||
assert!(std::fs::read(&png).unwrap().starts_with(b"\x89PNG"));
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::Node;
|
||||
use vectorcraft_render::encode::{RasterExportOptions, RasterFormat};
|
||||
|
||||
use crate::*;
|
||||
|
||||
@@ -181,3 +182,240 @@ fn warps_keep_the_map_their_version_names() {
|
||||
}
|
||||
assert_eq!(node(&s, id).appearance.effects.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rendered_warning_is_in_effect_command_results() {
|
||||
let (mut s, _) = session_with_rect();
|
||||
run(
|
||||
&mut s,
|
||||
"paint.setFill",
|
||||
json!({"gradient": {"kind": "linear", "stops": [
|
||||
{"offset": 0, "color": "#000000"}, {"offset": 1, "color": "#ffffff"}
|
||||
]}}),
|
||||
);
|
||||
let warning = vectorcraft_render::effects::rendered::OPAQUE_ONLY;
|
||||
let applied = run(&mut s, "effect.apply", json!({"effect": "threeD.extrude", "item": null, "params": {"render": {"mode": "rendered"}}}));
|
||||
assert_eq!(applied["warning"], warning);
|
||||
let shaded = run(&mut s, "effect.setParams", json!({"index": 0, "item": null, "params": {"render": {"mode": "shaded"}}}));
|
||||
assert!(shaded.get("warning").is_none());
|
||||
let params = json!({"index": 0, "item": null, "params": {"render": {"mode": "rendered"}}});
|
||||
assert_eq!(run(&mut s, "effect.setParams", params.clone())["warning"], warning);
|
||||
assert_eq!(run(&mut s, "effect.setParams", params)["warning"], warning, "unchanged settings still report the fallback");
|
||||
run(&mut s, "paint.setFill", json!({"color": "#338ad6"}));
|
||||
let plain = run(&mut s, "effect.setParams", json!({"index": 0, "item": null, "params": {"render": {"mode": "rendered", "quality": "low"}}}));
|
||||
assert!(plain.get("warning").is_none());
|
||||
}
|
||||
|
||||
/// The color space of each color image (not a soft mask) in PDF `bytes`, in order.
|
||||
fn image_spaces(bytes: &[u8]) -> Vec<String> {
|
||||
let text = String::from_utf8_lossy(bytes);
|
||||
let mut out = vec![];
|
||||
for (at, _) in text.match_indices("/Subtype/Image") {
|
||||
let start = text[..at].rfind(" obj").unwrap_or(0);
|
||||
let end = text[at..].find("stream").map_or(text.len(), |e| at + e);
|
||||
let dict = &text[start..end];
|
||||
let Some(cs) = dict.find("/ColorSpace") else { continue };
|
||||
let name = dict[cs + "/ColorSpace".len()..].trim_start_matches(['[', ' ', '/']);
|
||||
let space: String = name.chars().take_while(|c| c.is_ascii_alphanumeric()).collect();
|
||||
if space != "DeviceGray" {
|
||||
out.push(space);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// In a CMYK document, PDF export writes a rendered 3D object as it writes a raster effect: one
|
||||
/// image in the color space a drop shadow's image takes, kept in RGB by default and converted to
|
||||
/// CMYK by Press Quality.
|
||||
#[test]
|
||||
fn a_rendered_3d_object_in_a_cmyk_pdf_is_written_as_raster_effects_are() {
|
||||
let spaces = |effect: &str, params: Value, preset: Option<&str>| {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 300, "height": 300, "colorMode": "cmyk"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap();
|
||||
run(&mut s, "paint.setStroke", json!({"none": true}));
|
||||
run(&mut s, "paint.setFill", json!({"color": "#338ad6"}));
|
||||
run(&mut s, "effect.apply", json!({"effect": effect, "item": null, "params": params}));
|
||||
let v = s.execute("document.exportPdf", &preset.map_or(json!({}), |name| json!({"preset": name}))).unwrap();
|
||||
image_spaces(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap())
|
||||
};
|
||||
let rendered = json!({"render": {"mode": "rendered", "quality": "low"}});
|
||||
let shadow = json!({"x": 6.0, "y": 6.0, "blur": 3.0, "opacity": 75.0});
|
||||
for preset in [None, Some("Press Quality")] {
|
||||
let three_d = spaces("threeD.extrude", rendered.clone(), preset);
|
||||
let dropped = spaces("stylize.dropShadow", shadow.clone(), preset);
|
||||
assert_eq!(three_d.len(), 1, "{preset:?}: one image of the rendered object: {three_d:?}");
|
||||
assert_eq!(dropped.len(), 1, "{preset:?}: {dropped:?}");
|
||||
assert_eq!(three_d, dropped, "{preset:?}: the rendered image takes the drop shadow's color space");
|
||||
}
|
||||
assert_eq!(spaces("threeD.extrude", rendered, Some("Press Quality")), vec!["DeviceCMYK".to_string()]);
|
||||
}
|
||||
|
||||
/// A selected 100 pt square filled blue with no stroke, rendered by Extrude at Low quality, and
|
||||
/// `after` (effect, params) applied after it.
|
||||
fn rendered_square(after: &[(&str, Value)]) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap();
|
||||
run(&mut s, "paint.setStroke", json!({"none": true}));
|
||||
run(&mut s, "paint.setFill", json!({"color": "#338ad6"}));
|
||||
run(&mut s, "effect.apply", json!({"effect": "threeD.extrude", "item": null, "params": {"render": {"mode": "rendered", "quality": "low"}}}));
|
||||
for (effect, params) in after {
|
||||
run(&mut s, "effect.apply", json!({"effect": effect, "item": null, "params": params}));
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// The `/Width` of each color image (not a soft mask) in PDF `bytes`.
|
||||
fn image_widths(bytes: &[u8]) -> Vec<u32> {
|
||||
let text = String::from_utf8_lossy(bytes);
|
||||
let mut out = vec![];
|
||||
for (at, _) in text.match_indices("/Subtype/Image") {
|
||||
let start = text[..at].rfind(" obj").unwrap_or(0);
|
||||
let end = text[at..].find("stream").map_or(text.len(), |e| at + e);
|
||||
let dict = &text[start..end];
|
||||
if dict.contains("/DeviceGray") {
|
||||
continue;
|
||||
}
|
||||
if let Some(w) = dict.find("/Width") {
|
||||
out.push(dict[w + "/Width".len()..].trim_start().chars().take_while(char::is_ascii_digit).collect::<String>().parse().unwrap());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// PDF and SVG export write one image for a rendered 3D object, and Expand Appearance leaves one
|
||||
/// embedded image of the same size in pixels that covers the object.
|
||||
#[test]
|
||||
fn export_and_expand_write_one_image_of_a_rendered_3d_object() {
|
||||
let mut s = rendered_square(&[]);
|
||||
let pdf = s.execute("document.exportPdf", &json!({})).unwrap();
|
||||
let widths = image_widths(&vectorcraft_format::base64_decode(pdf["dataBase64"].as_str().unwrap()).unwrap());
|
||||
assert_eq!(widths.len(), 1, "{widths:?}");
|
||||
let svg = s.execute("document.export", &json!({"format": "svg"})).unwrap();
|
||||
let svg = String::from_utf8(vectorcraft_format::base64_decode(svg["dataBase64"].as_str().unwrap()).unwrap()).unwrap();
|
||||
assert_eq!(svg.matches("<image").count(), 1, "{svg}");
|
||||
run(&mut s, "effect.expandAppearance", json!({}));
|
||||
let mut found = vec![];
|
||||
for l in &s.doc().unwrap().doc.layers {
|
||||
l.walk(&mut |n| {
|
||||
if let vectorcraft_doc::NodeKind::Image(im) = &n.kind {
|
||||
found.push((**im).clone());
|
||||
}
|
||||
});
|
||||
}
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
let im = &found[0];
|
||||
assert!(s.doc().unwrap().doc.images.contains_key(&im.key), "the image is embedded");
|
||||
assert_eq!(im.width, widths[0], "the PDF's image and the expanded image have the same pixels");
|
||||
let c = im.xf.as_coeffs();
|
||||
let (x0, x1) = (c[4], c[4] + f64::from(im.width) * c[0]);
|
||||
assert!(x0 <= 100.0 + 1e-6 && x1 >= 200.0 - 1e-6, "the image spans {x0} to {x1}");
|
||||
}
|
||||
|
||||
/// PNG export draws a rendered 3D object as the canvas draws it at export quality. The rendered image takes as many
|
||||
/// pixels as the shaded faces' bounds times the resolution over 72, rounded up to whole pixels as a
|
||||
/// raster effect's image is (`effect_region` in `crates/engine/src/cmd/rasterfx.rs`), at the
|
||||
/// effect's own resolution and at the document's raster effects resolution.
|
||||
#[test]
|
||||
fn png_export_matches_the_canvas_and_the_image_takes_the_raster_effect_size() {
|
||||
for (doc_ppi, resolution) in [(72.0, Some(150.0)), (150.0, None), (300.0, Some(37.0))] {
|
||||
let what = format!("document {doc_ppi} ppi, effect {resolution:?}");
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 300, "height": 300, "rasterEffectsPpi": doc_ppi})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap();
|
||||
run(&mut s, "paint.setStroke", json!({"none": true}));
|
||||
run(&mut s, "paint.setFill", json!({"color": "#338ad6"}));
|
||||
let render = json!({"mode": "rendered", "quality": "low", "resolution": resolution});
|
||||
run(&mut s, "effect.apply", json!({"effect": "threeD.extrude", "item": null, "params": {"render": render}}));
|
||||
let png = s.execute("document.export", &json!({"format": "png", "background": "transparent"})).unwrap();
|
||||
let png = image::load_from_memory(&vectorcraft_format::base64_decode(png["dataBase64"].as_str().unwrap()).unwrap()).unwrap().to_rgba8();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
// The canvas drawn at export quality (precise, supersampled and with templates left out) and
|
||||
// at the resolution PNG export takes by default, the document's raster resolution.
|
||||
let quality = RasterExportOptions::default().render_options(RasterFormat::Png);
|
||||
let canvas = vectorcraft_render::Renderer::new().render_region_with(doc, doc.artboards[0].rect, doc_ppi / 72.0, &quality);
|
||||
assert_eq!((png.width(), png.height()), (canvas.width, canvas.height), "{what}");
|
||||
let changed = png.as_raw().chunks(4).zip(canvas.to_straight().chunks(4)).filter(|(a, b)| a != b).count();
|
||||
assert_eq!(changed, 0, "{what}: pixels of the PNG export that differ from the canvas");
|
||||
let drawn = |s: &Session| {
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let mut object = None;
|
||||
for layer in &doc.layers {
|
||||
layer.walk(&mut |n| {
|
||||
if n.appearance.effects.iter().any(|e| e.id == "threeD.extrude") {
|
||||
object = Some(n.clone());
|
||||
}
|
||||
});
|
||||
}
|
||||
vectorcraft_render::effects::solid_art_drawn_in(Some(doc), &object.unwrap()).unwrap()
|
||||
};
|
||||
let mut images = vec![];
|
||||
drawn(&s).walk(&mut |n| {
|
||||
if let vectorcraft_doc::NodeKind::Image(im) = &n.kind {
|
||||
images.push((**im).clone());
|
||||
}
|
||||
});
|
||||
assert_eq!(images.len(), 1, "{what}");
|
||||
run(&mut s, "effect.setParams", json!({"index": 0, "item": null, "params": {"render": {"mode": "shaded"}}}));
|
||||
let mut faces: Option<vectorcraft_geom::Rect> = None;
|
||||
drawn(&s).walk(&mut |n| {
|
||||
if let Some(b) = n.path_data().and_then(vectorcraft_geom::PathData::bounds) {
|
||||
faces = Some(faces.map_or(b, |f| f.union(b)));
|
||||
}
|
||||
});
|
||||
let faces = faces.unwrap();
|
||||
let scale = resolution.unwrap_or(doc_ppi) / 72.0;
|
||||
let expected = ((faces.width() * scale).ceil().max(1.0) as u32, (faces.height() * scale).ceil().max(1.0) as u32);
|
||||
assert_eq!((images[0].width, images[0].height), expected, "{what}: the image's pixels for faces {faces:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The page bounds, in whole points, of the pixels the canvas covers in session `s`.
|
||||
fn covered(s: &Session) -> (Vec<u8>, [u32; 4]) {
|
||||
let img =
|
||||
vectorcraft_render::Renderer::new().render_region(&s.doc().unwrap().doc, vectorcraft_geom::Rect::new(0.0, 0.0, 300.0, 300.0), 1.0, false);
|
||||
let mut b = [u32::MAX, u32::MAX, 0, 0];
|
||||
for (i, p) in img.pixels.chunks(4).enumerate() {
|
||||
if p[3] > 8 {
|
||||
let (x, y) = (i as u32 % img.width, i as u32 / img.width);
|
||||
b = [b[0].min(x), b[1].min(y), b[2].max(x), b[3].max(y)];
|
||||
}
|
||||
}
|
||||
(img.pixels, b)
|
||||
}
|
||||
|
||||
/// Gaussian Blur spreads a rendered 3D image past its edges and Transform moves it. Roughen
|
||||
/// draws the shaded faces instead and reports why.
|
||||
#[test]
|
||||
fn effects_after_a_rendered_3d_effect_keep_the_image_or_reshape_the_faces() {
|
||||
let (_, at) = covered(&rendered_square(&[]));
|
||||
let (_, blurred) = covered(&rendered_square(&[("blur.gaussian", json!({"radius": 5.0}))]));
|
||||
assert!(blurred[0] + 2 <= at[0] && blurred[2] >= at[2] + 2, "blurred {blurred:?} against {at:?}");
|
||||
let (_, moved) = covered(&rendered_square(&[("distort.transform", json!({"moveH": 50.0}))]));
|
||||
assert_eq!([moved[0], moved[2]], [at[0] + 50, at[2] + 50], "moved {moved:?} against {at:?}");
|
||||
let rough = rendered_square(&[("distort.roughen", json!({"size": 5.0}))]);
|
||||
let doc = &rough.doc().unwrap().doc;
|
||||
let mut object = None;
|
||||
for layer in &doc.layers {
|
||||
layer.walk(&mut |n| {
|
||||
if n.appearance.effects.iter().any(|e| e.id == "threeD.extrude") {
|
||||
object = Some(n.clone());
|
||||
}
|
||||
});
|
||||
}
|
||||
let object = object.unwrap();
|
||||
let art = vectorcraft_render::effects::solid_art_drawn_in(Some(doc), &object).unwrap();
|
||||
let mut has_image = false;
|
||||
let mut has_faces = false;
|
||||
art.walk(&mut |n| {
|
||||
has_image |= matches!(n.kind, vectorcraft_doc::NodeKind::Image(_));
|
||||
has_faces |= n.path_data().is_some();
|
||||
});
|
||||
assert!(!has_image);
|
||||
assert!(has_faces);
|
||||
assert_eq!(
|
||||
vectorcraft_render::effects::rendered_warning(doc, &object).as_deref(),
|
||||
Some("A later effect reshapes the 3D object's paths; showing the shaded faces instead")
|
||||
);
|
||||
}
|
||||
@@ -152,7 +152,7 @@ fn a_look_that_stores_its_stamps_between_the_polls_reads_keeps_them() {
|
||||
// The worker takes its turn after the slot is read and before the flag is, if the slot is free.
|
||||
let ended = link_watch::ended_without_stamps(&scan, |flag| {
|
||||
if let Ok(mut slot) = scan.0.try_lock() {
|
||||
*slot = Some((uid, stamps.clone()));
|
||||
*slot = Some(link_watch::LinkScanResult::stamps(uid, stamps.clone()));
|
||||
flag.store(true, Ordering::SeqCst);
|
||||
}
|
||||
flag.load(Ordering::SeqCst)
|
||||
@@ -163,7 +163,7 @@ fn a_look_that_stores_its_stamps_between_the_polls_reads_keeps_them() {
|
||||
let scan = scan.clone();
|
||||
move || {
|
||||
let _ended = link_watch::Ended(scan.clone());
|
||||
*scan.0.lock().unwrap() = Some((uid, stamps));
|
||||
*scan.0.lock().unwrap() = Some(link_watch::LinkScanResult::stamps(uid, stamps));
|
||||
}
|
||||
});
|
||||
worker.join().unwrap();
|
||||
|
||||
@@ -334,7 +334,7 @@ fn corners_of_a_non_square_rectangle_are_alike_circles() {
|
||||
assert_spans(&s, id, [8.0; 4]);
|
||||
}
|
||||
|
||||
/// A selected five-pointed star at (200, 200) of radii 60 and 30: a plain path.
|
||||
/// A selected five-pointed live star at (200, 200) of radii 60 and 30.
|
||||
fn star(s: &mut Session) -> NodeId {
|
||||
NodeId(s.execute("shape.star", &json!({"cx": 200, "cy": 200, "radius1": 60, "radius2": 30})).unwrap()["id"].as_u64().unwrap())
|
||||
}
|
||||
@@ -357,8 +357,8 @@ fn radii<const N: usize>(s: &Session, id: NodeId) -> [f64; N] {
|
||||
std::array::from_fn(|k| c.radius(k))
|
||||
}
|
||||
|
||||
/// #511: a star (a plain path) rounds all ten corners as one step, keeps them editable (a new
|
||||
/// radius cuts the outline again rather than the cut path), and is the plain star again at 0.
|
||||
/// #511: a live star rounds all ten corners as one step, keeps them editable (a new radius cuts
|
||||
/// the outline again rather than the cut path), and is the sharp star again at 0.
|
||||
#[test]
|
||||
fn a_star_rounds_its_corners_and_keeps_them_live() {
|
||||
let (mut s, _) = session();
|
||||
@@ -370,17 +370,102 @@ fn a_star_rounds_its_corners_and_keeps_them_live() {
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
let (path, live) = node_path(&s, id);
|
||||
assert_eq!(path.anchor_count(), 20);
|
||||
assert!(matches!(&live, Some(LiveShape::Path { base, .. }) if *base == sharp), "{live:?}");
|
||||
assert!(matches!(&live, Some(l @ LiveShape::Star { points: 5, .. }) if l.polygon_outline() == sharp), "{live:?}");
|
||||
assert_eq!(style(&s, id), (Some(4.0), Some(CornerKind::Round), 10));
|
||||
assert_eq!(s.doc().unwrap().doc.node(id).unwrap().kind_label(), "Path");
|
||||
assert_eq!(s.doc().unwrap().doc.node(id).unwrap().kind_label(), "Star");
|
||||
run(&mut s, json!({"radius": 6, "kind": "chamfer"}));
|
||||
assert_eq!((node_path(&s, id).0.anchor_count(), style(&s, id)), (20, (Some(6.0), Some(CornerKind::Chamfer), 10)));
|
||||
run(&mut s, json!({"radius": 0, "kind": "round"}));
|
||||
assert_eq!(node_path(&s, id), (sharp, None));
|
||||
let (path, live) = node_path(&s, id);
|
||||
assert_eq!(path, sharp);
|
||||
assert!(matches!(&live, Some(LiveShape::Star { radii, kinds, .. }) if radii.is_empty() && kinds.is_empty()), "{live:?}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(style(&s, id).0, Some(6.0));
|
||||
}
|
||||
|
||||
/// #4339: a live star takes a new point count and ratio from `object.setLiveShape` in one undo
|
||||
/// step each, keeps the corner radius its corners shared, and records nothing when the values
|
||||
/// are the ones it has. A count or ratio out of range is an error that changes nothing.
|
||||
#[test]
|
||||
fn a_live_star_takes_a_new_point_count_and_ratio() {
|
||||
let (mut s, _) = session();
|
||||
let id = star(&mut s);
|
||||
assert_eq!(node_path(&s, id).0.anchor_count(), 10);
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
run(&mut s, json!({"points": 8}));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
let (path, live) = node_path(&s, id);
|
||||
assert_eq!(path.anchor_count(), 16);
|
||||
assert_eq!(live.as_ref().and_then(LiveShape::star_points), Some(8));
|
||||
// The same count again: no undo step.
|
||||
run(&mut s, json!({"points": 8}));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
run(&mut s, json!({"ratio": 0.25}));
|
||||
let (_, live) = node_path(&s, id);
|
||||
assert!(matches!(live, Some(LiveShape::Star { r1, r2, .. }) if r1 == 60.0 && (r2 - 15.0).abs() < 1e-9));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 2);
|
||||
// The shared corner radius spreads to the new corners.
|
||||
run(&mut s, json!({"radius": 3}));
|
||||
run(&mut s, json!({"points": 6}));
|
||||
assert_eq!(style(&s, id), (Some(3.0), Some(CornerKind::Round), 12));
|
||||
for bad in [
|
||||
json!({"points": 1}),
|
||||
json!({"points": 1001}),
|
||||
json!({"points": 5.5}),
|
||||
json!({"ratio": 1.5}),
|
||||
json!({"ratio": -0.1}),
|
||||
json!({"ratio": 0}),
|
||||
json!({"points": 7, "radius": 2}),
|
||||
] {
|
||||
let before = node_path(&s, id);
|
||||
assert!(s.execute("object.setLiveShape", &bad).is_err(), "{bad}");
|
||||
assert_eq!(node_path(&s, id), before, "{bad}");
|
||||
}
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let (path, live) = node_path(&s, id);
|
||||
assert_eq!(path.anchor_count(), 10);
|
||||
assert_eq!(live.as_ref().and_then(LiveShape::star_points), Some(5));
|
||||
// Anchors selected on the old layout are dropped with a new point count.
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 8]], "mode": "set"})).unwrap();
|
||||
run(&mut s, json!({"id": id.0, "points": 3}));
|
||||
assert_eq!(selected_anchors(&s, id), None);
|
||||
// A star whose outer radius is 0 has no ratio to set.
|
||||
let flat = NodeId(s.execute("shape.star", &json!({"cx": 50, "cy": 50, "radius1": 0, "radius2": 10})).unwrap()["id"].as_u64().unwrap());
|
||||
let before = node_path(&s, flat);
|
||||
assert!(s.execute("object.setLiveShape", &json!({"id": flat.0, "ratio": 0.5})).is_err());
|
||||
assert_eq!(node_path(&s, flat), before);
|
||||
}
|
||||
|
||||
/// A ratio that changes how many anchors a rounded star draws can't come with a radius: the
|
||||
/// corners selected before it would no longer name the same corners. A ratio alone still drops
|
||||
/// the stale anchor selection.
|
||||
#[test]
|
||||
fn a_ratio_that_relays_a_rounded_star_is_not_set_with_a_radius() {
|
||||
let (mut s, _) = session();
|
||||
// At this ratio the inner points lie on the lines between the outer ones.
|
||||
let flat = 36f64.to_radians().cos();
|
||||
let id = star(&mut s);
|
||||
run(&mut s, json!({"id": id.0, "radius": 4}));
|
||||
let rounded = node_path(&s, id).0.anchor_count();
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap();
|
||||
let before = (node_path(&s, id), selected_anchors(&s, id));
|
||||
let err = s.execute("object.setLiveShape", &json!({"id": id.0, "ratio": flat, "radius": 6})).unwrap_err();
|
||||
assert!(err.to_string().contains("`ratio`"), "{err}");
|
||||
assert_eq!((node_path(&s, id), selected_anchors(&s, id)), before);
|
||||
// The same ratio alone lays the anchors out again and drops the selection.
|
||||
run(&mut s, json!({"id": id.0, "ratio": flat}));
|
||||
assert_ne!(node_path(&s, id).0.anchor_count(), rounded);
|
||||
assert_eq!(selected_anchors(&s, id), None);
|
||||
// A ratio that keeps the anchors still goes with a radius.
|
||||
let other = star(&mut s);
|
||||
run(&mut s, json!({"id": other.0, "radius": 4}));
|
||||
run(&mut s, json!({"id": other.0, "ratio": 0.4, "radius": 5}));
|
||||
assert_eq!(style(&s, other).0, Some(5.0));
|
||||
}
|
||||
|
||||
/// Each corner stops at its own limit: its cut reaches halfway along its shorter side, so a
|
||||
/// star's neighbouring corners meet without overlapping.
|
||||
#[test]
|
||||
@@ -389,7 +474,8 @@ fn star_corners_stop_at_their_own_limit() {
|
||||
let id = star(&mut s);
|
||||
run(&mut s, json!({"radius": 1000}));
|
||||
let (path, live) = node_path(&s, id);
|
||||
let Some(LiveShape::Path { base, .. }) = live else { panic!("live corners") };
|
||||
let Some(l @ LiveShape::Star { .. }) = live else { panic!("live corners") };
|
||||
let base = l.polygon_outline();
|
||||
// Every cut ends at the middle of a side: each side's two cuts meet there.
|
||||
let sp = &base.subpaths[0];
|
||||
for (i, a) in sp.anchors.iter().enumerate() {
|
||||
@@ -1241,3 +1327,258 @@ fn a_double_click_on_a_corner_widget_with_the_selection_tool_asks_for_the_transf
|
||||
let asked = double_click(&mut s, "directSelection");
|
||||
assert!(matches!(asked.as_slice(), [UiRequest::Dialog(k, _)] if k == vectorcraft_tools::corners::DIALOG), "{asked:?}");
|
||||
}
|
||||
|
||||
/// Live radii of every corner of path `id`, or `None` when it has no Live Corners left.
|
||||
fn live_radii(s: &Session, id: NodeId) -> Option<Vec<f64>> {
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
let lc = LiveCorners::of(n)?;
|
||||
let all = lc.all();
|
||||
Some(all.iter().map(|k| lc.drawn_radius(*k)).collect())
|
||||
}
|
||||
|
||||
/// #10545: moving an anchor of a rounded rectangle moves its corner and keeps every corner live
|
||||
/// at its radius, in one undo step.
|
||||
#[test]
|
||||
fn moving_an_anchor_keeps_the_corners_live() {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 0, "y": 25})).unwrap();
|
||||
assert_eq!(live_radii(&s, id), Some(vec![10.0; 4]));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
assert_eq!(n.path_data().unwrap().anchor_count(), 8);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(corners(&s, id), ([10.0; 4], [CornerKind::Round; 4], 8));
|
||||
}
|
||||
|
||||
/// #10545: dragging direct-selected anchors of a rounded rectangle keeps its corners live, and
|
||||
/// the corner they belong to moves by the drag.
|
||||
#[test]
|
||||
fn dragging_selected_anchors_keeps_the_corners_live() {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let before = s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap();
|
||||
// The two ends of the top-left corner's arc.
|
||||
let arc: Vec<[usize; 2]> = {
|
||||
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
|
||||
lc.anchors_of(&BTreeSet::from([0])).into_iter().map(|(si, ai)| [si, ai]).collect()
|
||||
};
|
||||
assert_eq!(arc.len(), 2);
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": arc, "mode": "set"})).unwrap();
|
||||
s.execute("path.moveAnchors", &json!({"dx": -20, "dy": 0})).unwrap();
|
||||
assert_eq!(live_radii(&s, id), Some(vec![10.0; 4]));
|
||||
let after = s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap();
|
||||
assert!(after.x0 < before.x0 - 10.0 && (after.x1 - before.x1).abs() < 1e-6, "{before:?} -> {after:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_an_anchor_of_a_distorted_rectangle_edits_the_drawn_path() {
|
||||
for xf in [Affine::scale_non_uniform(2.0, 1.0), Affine::new([1.0, 0.0, 0.5, 1.0, 10.0, 10.0])] {
|
||||
for command in ["path.moveAnchor", "path.moveAnchors"] {
|
||||
let (mut s, id) = session();
|
||||
let live = LiveShape::Rectangle { w: 50.0, h: 60.0, radii: [10.0; 4], kinds: Default::default(), radii_relative: false, xf };
|
||||
let mut expected = live.to_path();
|
||||
{
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let NodeKind::Path { path, live: slot, .. } = &mut d.node_mut(id).unwrap().kind else { panic!("not a path") };
|
||||
*path = expected.clone();
|
||||
*slot = Some(Box::new(live));
|
||||
}
|
||||
let delta = vectorcraft_geom::Vec2::new(-20.0, 5.0);
|
||||
let a = expected.anchor_mut(0, 0).unwrap();
|
||||
*a = a.transform(Affine::translate(delta));
|
||||
let target = a.p;
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0]], "mode": "set"})).unwrap();
|
||||
let params = if command == "path.moveAnchor" {
|
||||
json!({"id": id.0, "anchor": 0, "x": target.x, "y": target.y})
|
||||
} else {
|
||||
json!({"dx": delta.x, "dy": delta.y, "interpolate": false})
|
||||
};
|
||||
s.execute(command, ¶ms).unwrap();
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
assert!(n.live_shape().is_none(), "{command}: {xf:?}");
|
||||
assert_eq!(n.path_data().unwrap(), &expected, "{command}: {xf:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_recut_remaps_the_whole_anchor_selection() {
|
||||
for command in ["path.moveAnchor", "path.moveAnchors"] {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let (selected, moved, target, sources) = {
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
let lc = LiveCorners::of(n).unwrap();
|
||||
let selected: BTreeSet<_> = [0, 2].into_iter().map(|k| *lc.anchors_of(&BTreeSet::from([k])).first().unwrap()).collect();
|
||||
let moved = *lc.anchors_of(&BTreeSet::from([0])).first().unwrap();
|
||||
let target = n.path_data().unwrap().subpaths[moved.0].anchors[moved.1].p + vectorcraft_geom::Vec2::new(50.0, 30.0);
|
||||
(selected, moved, target, lc.sources().to_vec())
|
||||
};
|
||||
s.doc_mut().unwrap().selection.anchors.insert(id, selected);
|
||||
s.doc_mut().unwrap().selection.segments.insert(id, BTreeSet::from([(0, 0)]));
|
||||
let before = s.doc().unwrap().selection.clone();
|
||||
let params = if command == "path.moveAnchor" {
|
||||
json!({"id": id.0, "subpath": moved.0, "anchor": moved.1, "x": target.x, "y": target.y})
|
||||
} else {
|
||||
json!({"dx": 50, "dy": 30, "interpolate": false})
|
||||
};
|
||||
s.execute(command, ¶ms).unwrap();
|
||||
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
|
||||
assert_ne!(lc.sources(), sources, "{command}: the corner becomes straight");
|
||||
assert_eq!(selected_anchors(&s, id), Some(lc.anchors_of(&BTreeSet::from([0, 2]))), "{command}");
|
||||
assert!(!s.doc().unwrap().selection.segments.contains_key(&id), "{command}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().selection, before, "{command}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_recut_clears_segments_even_when_selected_anchor_indices_stay_the_same() {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let (selected, moved, target, sources) = {
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
let lc = LiveCorners::of(n).unwrap();
|
||||
let selected = lc.anchors_of(&BTreeSet::from([1]));
|
||||
let moved = *lc.anchors_of(&BTreeSet::from([2])).first().unwrap();
|
||||
let target = n.path_data().unwrap().subpaths[moved.0].anchors[moved.1].p + vectorcraft_geom::Vec2::new(-50.0, -30.0);
|
||||
(selected, moved, target, lc.sources().to_vec())
|
||||
};
|
||||
s.doc_mut().unwrap().selection.anchors.insert(id, selected.clone());
|
||||
s.doc_mut().unwrap().selection.segments.insert(id, BTreeSet::from([(0, 1)]));
|
||||
s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": moved.1, "x": target.x, "y": target.y})).unwrap();
|
||||
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
|
||||
assert_ne!(lc.sources(), sources);
|
||||
assert_eq!(lc.anchors_of(&BTreeSet::from([1])), selected);
|
||||
assert_eq!(selected_anchors(&s, id), Some(selected));
|
||||
assert!(!s.doc().unwrap().selection.segments.contains_key(&id));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unchanged_corner_layout_keeps_the_selection() {
|
||||
for command in ["path.moveAnchor", "path.moveAnchors"] {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
s.doc_mut().unwrap().selection.anchors.insert(id, anchors(&[0, 1, 2]));
|
||||
s.doc_mut().unwrap().selection.segments.insert(id, BTreeSet::from([(0, 1)]));
|
||||
let before = s.doc().unwrap().selection.clone();
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
let sources = LiveCorners::of(n).unwrap().sources().to_vec();
|
||||
let target = n.path_data().unwrap().subpaths[0].anchors[4].p + vectorcraft_geom::Vec2::new(-20.0, 0.0);
|
||||
let params = if command == "path.moveAnchor" {
|
||||
json!({"id": id.0, "anchor": 4, "x": target.x, "y": target.y})
|
||||
} else {
|
||||
json!({"dx": -20, "dy": 0, "interpolate": false})
|
||||
};
|
||||
s.execute(command, ¶ms).unwrap();
|
||||
assert_eq!(LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap().sources(), sources);
|
||||
assert_eq!(s.doc().unwrap().selection, before, "{command}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_recut_keeps_the_key_anchor_on_its_corner() {
|
||||
for command in ["path.moveAnchor", "path.moveAnchors"] {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let (selected, moved, key, target, sources) = {
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
let lc = LiveCorners::of(n).unwrap();
|
||||
// The top right corner moves to the middle of the rectangle.
|
||||
let moved = *lc.anchors_of(&BTreeSet::from([1])).first().unwrap();
|
||||
let key = *lc.anchors_of(&BTreeSet::from([3])).first().unwrap();
|
||||
let target = n.path_data().unwrap().subpaths[moved.0].anchors[moved.1].p + vectorcraft_geom::Vec2::new(-50.0, 30.0);
|
||||
(BTreeSet::from([moved, key]), moved, key, target, lc.sources().to_vec())
|
||||
};
|
||||
let sel = &mut s.doc_mut().unwrap().selection;
|
||||
sel.anchors.insert(id, selected);
|
||||
sel.key_anchor = Some((id, key));
|
||||
let params = if command == "path.moveAnchor" {
|
||||
json!({"id": id.0, "subpath": moved.0, "anchor": moved.1, "x": target.x, "y": target.y})
|
||||
} else {
|
||||
json!({"dx": -50, "dy": 30, "interpolate": false})
|
||||
};
|
||||
s.execute(command, ¶ms).unwrap();
|
||||
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
|
||||
assert_ne!(lc.sources(), sources, "{command}: the corner becomes straight");
|
||||
let now = s.doc().unwrap().selection.key_anchor;
|
||||
assert_eq!(now, lc.anchors_of(&BTreeSet::from([3])).first().map(|r| (id, *r)), "{command}");
|
||||
assert_ne!(now, Some((id, key)), "{command}: the key anchor's index changed with the recut");
|
||||
}
|
||||
}
|
||||
|
||||
/// A nudge of a pixel-aligned rounded rectangle's edge that the pixel-grid snap takes back
|
||||
/// changes nothing and records no undo step.
|
||||
#[test]
|
||||
fn a_nudge_the_pixel_grid_takes_back_records_no_undo_step() {
|
||||
let (mut s, id) = session();
|
||||
s.execute("object.setPixelAligned", &json!({"ids": [id.0]})).unwrap();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let left: Vec<[usize; 2]> = {
|
||||
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
|
||||
lc.anchors_of(&BTreeSet::from([0, 3])).into_iter().map(|(si, ai)| [si, ai]).collect()
|
||||
};
|
||||
assert_eq!(left.len(), 4);
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": left, "mode": "set"})).unwrap();
|
||||
// A first move by a whole point makes the rectangle a live path; the snap keeps that move.
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("path.moveAnchors", &json!({"dx": 1, "dy": 0})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("path.moveAnchors", &json!({"dx": 0.2, "dy": 0})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc, doc);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
}
|
||||
|
||||
/// The same nudge on a rounded rectangle that no anchor edit has touched yet records no undo
|
||||
/// step and leaves it a live rectangle.
|
||||
#[test]
|
||||
fn a_nudge_the_pixel_grid_takes_back_keeps_a_live_rectangle() {
|
||||
for x in [10, 50, 137] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let id = NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 100, "height": 60})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.setPixelAligned", &json!({"ids": [id.0]})).unwrap();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let left: Vec<[usize; 2]> = {
|
||||
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
|
||||
lc.anchors_of(&BTreeSet::from([0, 3])).into_iter().map(|(si, ai)| [si, ai]).collect()
|
||||
};
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": left, "mode": "set"})).unwrap();
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("path.moveAnchors", &json!({"dx": 0.2, "dy": 0})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "x = {x}");
|
||||
assert!(matches!(s.doc().unwrap().doc.node(id).unwrap().live_shape(), Some(LiveShape::Rectangle { .. })), "x = {x}");
|
||||
assert_eq!(s.doc().unwrap().doc, doc, "x = {x}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The same nudge with a second pixel-aligned rectangle selected whole, which the snap also takes
|
||||
/// back, records no undo step and leaves the rounded rectangle a live rectangle.
|
||||
#[test]
|
||||
fn a_nudge_the_pixel_grid_takes_back_with_an_object_selected_whole_records_no_undo_step() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let id = NodeId(s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 100, "height": 60})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.setPixelAligned", &json!({"ids": [id.0]})).unwrap();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let whole = NodeId(s.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 50, "height": 40})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.setPixelAligned", &json!({"ids": [whole.0]})).unwrap();
|
||||
let left: Vec<[usize; 2]> = {
|
||||
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
|
||||
lc.anchors_of(&BTreeSet::from([0, 3])).into_iter().map(|(si, ai)| [si, ai]).collect()
|
||||
};
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": left, "mode": "set"})).unwrap();
|
||||
s.execute("select.add", &json!({"ids": [whole.0]})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().selection.whole(), vec![whole]);
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("path.moveAnchors", &json!({"dx": 0.2, "dy": 0})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
assert!(matches!(s.doc().unwrap().doc.node(id).unwrap().live_shape(), Some(LiveShape::Rectangle { .. })));
|
||||
assert_eq!(s.doc().unwrap().doc, doc);
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
//! Canvas marker state and command API, independent of artwork and link update preferences.
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
use crate::tests_links::{Folder, RED, place, png, session, write};
|
||||
use crate::*;
|
||||
|
||||
fn marked(s: &mut Session) -> Vec<u64> {
|
||||
s.execute("links.marked", &json!({})).unwrap()["images"].as_array().unwrap().iter().map(|r| r["id"].as_u64().unwrap()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_link_toggle_is_transient_per_document_and_validated() {
|
||||
let mut s = session();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
assert!(marked(&mut s).is_empty());
|
||||
assert_eq!(s.execute("view.showMissingLinks", &json!({"on": true})).unwrap(), json!({"on": true}));
|
||||
for p in [json!({"on": "false"}), json!({"on": 1}), json!({"on": []})] {
|
||||
assert!(s.execute("view.showMissingLinks", &p).is_err());
|
||||
assert!(s.doc().unwrap().show_missing_links);
|
||||
}
|
||||
assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
assert!(!s.doc().unwrap().is_dirty());
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
assert!(!s.doc().unwrap().show_missing_links);
|
||||
s.execute("document.activate", &json!({"index": 0})).unwrap();
|
||||
assert!(s.doc().unwrap().show_missing_links);
|
||||
assert_eq!(s.execute("view.showMissingLinks", &json!({})).unwrap(), json!({"on": false}));
|
||||
assert!(s.doc().unwrap().missing_link_markers.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_link_markers_follow_files_relink_update_and_embed() {
|
||||
let dir = Folder::new("marker-lifecycle");
|
||||
let path = dir.file("art.png");
|
||||
let replacement = dir.file("replacement.png");
|
||||
let bytes = png(40, 40, RED);
|
||||
write(&path, &bytes);
|
||||
write(&replacement, &bytes);
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &path);
|
||||
s.execute("view.showMissingLinks", &json!({"on": true})).unwrap();
|
||||
assert!(marked(&mut s).is_empty());
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
assert_eq!(marked(&mut s), vec![id.0]);
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let selection = s.doc().unwrap().selection.clone();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let saved = vectorcraft_format::save_file(&doc);
|
||||
let pixels = vectorcraft_render::Renderer::new().render_region(&doc, vectorcraft_geom::Rect::new(0.0, 0.0, 400.0, 300.0), 1.0, true).pixels;
|
||||
s.execute("view.showMissingLinks", &json!({"on": false})).unwrap();
|
||||
assert!(marked(&mut s).is_empty());
|
||||
s.execute("view.showMissingLinks", &json!({"on": true})).unwrap();
|
||||
assert_eq!(marked(&mut s), vec![id.0]);
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!(st.selection, selection);
|
||||
assert_eq!(st.history.undo.len(), undo);
|
||||
assert_eq!(vectorcraft_format::save_file(&st.doc), saved);
|
||||
assert_eq!(
|
||||
vectorcraft_render::Renderer::new().render_region(&st.doc, vectorcraft_geom::Rect::new(0.0, 0.0, 400.0, 300.0), 1.0, true).pixels,
|
||||
pixels
|
||||
);
|
||||
s.execute("links.relink", &json!({"ids": [id.0], "path": replacement})).unwrap();
|
||||
assert!(s.doc().unwrap().marked_missing_links().is_empty());
|
||||
assert!(marked(&mut s).is_empty());
|
||||
std::fs::remove_file(&replacement).unwrap();
|
||||
assert_eq!(marked(&mut s), vec![id.0]);
|
||||
write(&replacement, &bytes);
|
||||
s.execute("links.update", &json!({"ids": [id.0]})).unwrap();
|
||||
assert!(s.doc().unwrap().marked_missing_links().is_empty());
|
||||
assert!(marked(&mut s).is_empty());
|
||||
s.execute("links.embed", &json!({"ids": [id.0]})).unwrap();
|
||||
std::fs::remove_file(&replacement).unwrap();
|
||||
assert!(marked(&mut s).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_link_worker_refreshes_without_the_panel_and_ignores_old_art() {
|
||||
for mode in ["automatically", "askWhenModified", "manually"] {
|
||||
let dir = Folder::new(&format!("marker-watch-{mode}"));
|
||||
let path = dir.file("art.png");
|
||||
let bytes = png(20, 20, RED);
|
||||
write(&path, &bytes);
|
||||
let mut s = session();
|
||||
s.prefs.update_links = mode.into();
|
||||
let id = place(&mut s, &path);
|
||||
s.execute("view.showMissingLinks", &json!({"on": true})).unwrap();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
s.start_link_scan();
|
||||
s.wait_link_scan();
|
||||
s.poll_link_scan().unwrap().unwrap();
|
||||
assert_eq!(s.doc().unwrap().missing_link_markers.as_ref().unwrap().1, vec![id]);
|
||||
write(&path, &bytes);
|
||||
s.start_link_scan();
|
||||
s.wait_link_scan();
|
||||
s.poll_link_scan().unwrap().unwrap();
|
||||
assert!(s.doc().unwrap().missing_link_markers.as_ref().unwrap().1.is_empty());
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
s.start_link_scan();
|
||||
s.wait_link_scan();
|
||||
let seen = s.doc().unwrap().missing_link_markers.as_ref().unwrap().0.clone();
|
||||
s.execute("shape.rectangle", &json!({"x": 1, "y": 1, "width": 3, "height": 4})).unwrap();
|
||||
s.poll_link_scan().unwrap().unwrap();
|
||||
assert!(std::sync::Arc::ptr_eq(&seen, &s.doc().unwrap().missing_link_markers.as_ref().unwrap().0));
|
||||
assert!(s.doc().unwrap().marked_missing_links().is_empty());
|
||||
s.start_link_scan();
|
||||
s.wait_link_scan();
|
||||
// Switching the toggle off while a look is pending must not resurrect its markers.
|
||||
s.execute("view.showMissingLinks", &json!({"on": false})).unwrap();
|
||||
s.poll_link_scan().unwrap().unwrap();
|
||||
assert!(s.doc().unwrap().missing_link_markers.is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turning_missing_links_on_returns_before_the_file_probe_and_scans_on_the_link_watcher() {
|
||||
use crate::cmd::links::probe_gate::{self, Gate};
|
||||
use std::time::Duration;
|
||||
let dir = Folder::new("marker-toggle-nonblocking");
|
||||
let path = dir.file("art.png");
|
||||
write(&path, &png(20, 20, RED));
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &path);
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
let stored = crate::tests_links::image(&s, id).link.unwrap().path;
|
||||
let gate = Gate::close(&stored);
|
||||
// The toggle returns while the probe of the (slow) linked file is held closed.
|
||||
assert_eq!(s.execute("view.showMissingLinks", &json!({"on": true})).unwrap(), json!({"on": true}));
|
||||
assert!(!gate.finished(), "the toggle waited for the file probe");
|
||||
assert_eq!(gate.entered(Duration::ZERO), None, "the toggle probed the file on the calling thread");
|
||||
assert!(s.doc().unwrap().missing_link_markers.is_none());
|
||||
assert!(s.doc().unwrap().marked_missing_links().is_empty());
|
||||
// The desktop app starts the watcher's look at once, and the probe runs there.
|
||||
assert!(s.missing_link_scan_due());
|
||||
s.start_link_scan();
|
||||
assert!(!s.missing_link_scan_due());
|
||||
assert_eq!(gate.entered(Duration::from_secs(10)).as_deref(), Some("link-watch"));
|
||||
assert!(s.poll_link_scan().is_none(), "the look ended before its probe was released");
|
||||
gate.open();
|
||||
s.wait_link_scan();
|
||||
s.poll_link_scan().unwrap().unwrap();
|
||||
probe_gate::remove(&stored);
|
||||
assert_eq!(s.doc().unwrap().marked_missing_links(), vec![id]);
|
||||
assert!(!s.missing_link_scan_due());
|
||||
// Turning it on again while on keeps the markers; off clears them.
|
||||
s.execute("view.showMissingLinks", &json!({"on": true})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().marked_missing_links(), vec![id]);
|
||||
s.execute("view.showMissingLinks", &json!({"on": false})).unwrap();
|
||||
assert!(!s.missing_link_scan_due());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_link_scan_for_a_document_without_links_ends_without_a_worker() {
|
||||
let mut s = session();
|
||||
s.execute("view.showMissingLinks", &json!({"on": true})).unwrap();
|
||||
assert!(s.missing_link_scan_due());
|
||||
s.start_link_scan();
|
||||
assert!(s.link_scan.is_none());
|
||||
assert!(!s.missing_link_scan_due());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_link_hidden_when_the_overlay_turns_on_is_marked_once_shown() {
|
||||
let dir = Folder::new("marker-hidden-then-shown");
|
||||
let path = dir.file("art.png");
|
||||
write(&path, &png(20, 20, RED));
|
||||
// Found by the desktop's link watch worker, and in place as the web app does.
|
||||
for in_place in [false, true] {
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &path);
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
s.execute("object.hide", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("view.showMissingLinks", &json!({"on": true})).unwrap();
|
||||
let mark = |s: &mut Session| {
|
||||
if in_place {
|
||||
s.mark_missing_links_in_place();
|
||||
} else {
|
||||
s.start_link_scan();
|
||||
s.wait_link_scan();
|
||||
s.poll_link_scan().unwrap().unwrap();
|
||||
}
|
||||
};
|
||||
mark(&mut s);
|
||||
assert!(s.doc().unwrap().marked_missing_links().is_empty(), "hidden art is not marked");
|
||||
s.execute("object.showAll", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().marked_missing_links(), vec![id], "shown art is marked without another scan");
|
||||
if in_place {
|
||||
// Artwork restored while the overlay is on is marked again.
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(id).is_none());
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.mark_missing_links_in_place());
|
||||
assert_eq!(s.doc().unwrap().marked_missing_links(), vec![id]);
|
||||
assert!(!s.mark_missing_links_in_place(), "unchanged art is not looked at again");
|
||||
}
|
||||
write(&path, &png(20, 20, RED));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_link_markers_include_placed_documents_and_exclude_hidden_art() {
|
||||
let dir = Folder::new("marker-placed");
|
||||
let path = dir.file("placed.vectorcraft");
|
||||
write(&path, &vectorcraft_format::save_file(&vectorcraft_doc::Document::new(40.0, 20.0)));
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &path);
|
||||
assert!(matches!(s.doc().unwrap().doc.node(id).unwrap().kind, vectorcraft_doc::NodeKind::PlacedDocument(_)));
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
s.execute("view.showMissingLinks", &json!({"on": true})).unwrap();
|
||||
assert_eq!(marked(&mut s), vec![id.0]);
|
||||
s.execute("object.move", &json!({"ids": [id.0], "dx": 15, "dy": 10})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().marked_missing_links(), vec![id]);
|
||||
s.execute("object.hide", &json!({"ids": [id.0]})).unwrap();
|
||||
assert!(s.doc().unwrap().marked_missing_links().is_empty());
|
||||
assert!(marked(&mut s).is_empty());
|
||||
}
|
||||
@@ -2713,6 +2713,32 @@ fn removing_all_the_paths_of_a_compound_path_keeps_the_compound_path() {
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
}
|
||||
|
||||
/// `removeAll()` on the `pathItems` of a compound path that clips a group keeping other art
|
||||
/// would leave an empty clipping path, so it throws and deletes nothing, as deleting the clipping
|
||||
/// path itself does. Removing some of its paths still works.
|
||||
#[test]
|
||||
fn removing_all_the_paths_of_a_clipping_compound_path_is_refused() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("object.compoundPath.make", &json!({})).unwrap();
|
||||
let compound = s.active().unwrap().doc.parent_of(a).unwrap();
|
||||
let other = rect(&mut s, 200.0, 20.0, 30.0, 40.0);
|
||||
s.execute("select.set", &json!({"ids": [compound.0, other.0]})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
run(&mut s, "var g = app.activeDocument.groupItems[0]; g.compoundPathItems[0].zOrder(ZOrderMethod.BRINGTOFRONT); g.clipped = true;").unwrap();
|
||||
let d = &s.active().unwrap().doc;
|
||||
assert_eq!(d.parent_of(compound).and_then(|g| d.node(g)).and_then(|g| g.children()).map(|k| k[0].id), Some(compound));
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
let steps = undo_steps(&s);
|
||||
let e = failure(&mut s, "app.activeDocument.compoundPathItems[0].pathItems.removeAll();");
|
||||
assert!(e.contains("cannot delete a clipping path"), "{e}");
|
||||
assert!(e.contains(&compound.0.to_string()), "{e}");
|
||||
assert_eq!(s.active().unwrap().doc, before);
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
run(&mut s, "app.activeDocument.compoundPathItems[0].pathItems[0].remove();").unwrap();
|
||||
assert_eq!(s.active().unwrap().doc.node(compound).and_then(|n| n.children()).map(Vec::len), Some(1));
|
||||
}
|
||||
|
||||
/// `move` leaves art on a locked artboard where it is, and a move that leaves an object where it
|
||||
/// is runs no command, also in a layer whose ruler guides are above its art.
|
||||
#[test]
|
||||
|
||||
@@ -680,6 +680,68 @@ fn document_path_creators_use_the_active_layer_during_isolation() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A locked or hidden active layer does not take a script's new path: the path goes on the
|
||||
/// topmost shown, unlocked layer, where the app's own creation commands put new art.
|
||||
#[test]
|
||||
fn document_path_creators_skip_a_locked_or_hidden_active_layer() {
|
||||
for (prop, value) in [("locked", true), ("visible", false)] {
|
||||
for create in ["add()", "rectangle(100, 10, 20, 30)", "roundedRectangle(100, 10, 20, 30)", "ellipse()", "polygon()", "star()"] {
|
||||
let (mut s, _, _) = doc();
|
||||
let editable = s.active().unwrap().active_layer.unwrap();
|
||||
let top = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(s.active().unwrap().active_layer, Some(top));
|
||||
s.execute("layer.setProps", &json!({"id": top.0, prop: value})).unwrap();
|
||||
let before = node(&s, editable).children().unwrap().len();
|
||||
log(&mut s, &format!("app.activeDocument.pathItems.{create};"));
|
||||
let st = s.active().unwrap();
|
||||
assert!(st.doc.node(top).unwrap().children().unwrap().is_empty(), "{prop} {create}");
|
||||
let children = st.doc.node(editable).unwrap().children().unwrap();
|
||||
assert_eq!(children.len(), before + 1, "{prop} {create}");
|
||||
let made = children.last().unwrap();
|
||||
assert!(matches!(made.kind, NodeKind::Path { .. }), "{prop} {create}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// While an opacity mask is being edited, a locked mask layer refuses a script's new path instead
|
||||
/// of the path going on an ordinary layer outside the mask.
|
||||
#[test]
|
||||
fn document_path_creators_refuse_a_locked_mask_editing_layer() {
|
||||
let (mut s, a, _) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
|
||||
let layer = s.active().unwrap().doc.mask_edit.unwrap().layer;
|
||||
assert_eq!(s.active().unwrap().active_layer, Some(layer));
|
||||
s.execute("layer.setProps", &json!({"id": layer.0, "locked": true})).unwrap();
|
||||
let before = art(&s);
|
||||
let e = failure(&mut s, "app.activeDocument.pathItems.add();");
|
||||
assert!(e.contains("onLayer must name an editable layer"), "{e}");
|
||||
assert_eq!(art(&s), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_path_creators_use_the_mask_editing_layer_after_the_active_layer_changes() {
|
||||
let (mut s, a, _) = doc();
|
||||
let ordinary = s.active().unwrap().active_layer.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
|
||||
let layer = s.active().unwrap().doc.mask_edit.unwrap().layer;
|
||||
s.execute("layer.setCurrent", &json!({"id": ordinary.0})).unwrap();
|
||||
s.execute("layer.setProps", &json!({"id": ordinary.0, "locked": true})).unwrap();
|
||||
assert_eq!(s.active().unwrap().active_layer, Some(ordinary));
|
||||
let before = node(&s, layer).children().unwrap().len();
|
||||
let ordinary_before = node(&s, ordinary).children().unwrap().len();
|
||||
log(&mut s, "app.activeDocument.pathItems.add();");
|
||||
let st = s.active().unwrap();
|
||||
assert_eq!(st.doc.mask_edit.unwrap().layer, layer);
|
||||
let children = st.doc.node(layer).unwrap().children().unwrap();
|
||||
assert_eq!(children.len(), before + 1);
|
||||
assert!(matches!(children.last().unwrap().kind, NodeKind::Path { .. }));
|
||||
// The mask's art is stored on its object, which stays on the ordinary layer; that layer gains
|
||||
// no path of its own.
|
||||
assert_eq!(node(&s, ordinary).children().unwrap().len(), ordinary_before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paint_writes_refuse_generated_graph_design_paths() {
|
||||
for (kind, command) in [("column", "graph.column"), ("line", "graph.marker")] {
|
||||
|
||||
@@ -62,8 +62,12 @@ fn a_click_outside_an_outside_stroke_selects_it() {
|
||||
s.execute("stroke.set", &json!({"ids": [r.0], "align": "center"})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert!(click(&mut s, 84.0, 200.0).is_empty(), "a centred stroke doesn't reach");
|
||||
// With it off, a click inside the unfilled square selects it (#9175).
|
||||
// With it off, a click inside the unfilled square selects nothing by default, and selects the
|
||||
// square with Select Inside Unfilled Shapes on (#9175).
|
||||
s.execute("prefs.set", &json!({"key": "objectSelectionByPathOnly", "value": false})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert!(click(&mut s, 116.0, 200.0).is_empty(), "off by default");
|
||||
s.execute("prefs.set", &json!({"key": "selectInsideUnfilledShapes", "value": true})).unwrap();
|
||||
assert_eq!(click(&mut s, 116.0, 200.0), [r]);
|
||||
}
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@ pub(crate) struct HoverKey {
|
||||
last_tools: (Option<&'static str>, Option<&'static str>),
|
||||
ctrl_click_selects_behind: bool,
|
||||
object_selection_by_path_only: bool,
|
||||
select_inside_unfilled_shapes: bool,
|
||||
type_selection_by_path_only: bool,
|
||||
selection_tolerance: f64,
|
||||
anchor_size: u32,
|
||||
@@ -364,6 +365,7 @@ impl Session {
|
||||
last_tools: (self.last_selection_tool, self.last_part_selection_tool),
|
||||
ctrl_click_selects_behind: p.ctrl_click_selects_behind,
|
||||
object_selection_by_path_only: p.object_selection_by_path_only,
|
||||
select_inside_unfilled_shapes: p.select_inside_unfilled_shapes,
|
||||
type_selection_by_path_only: p.type_selection_by_path_only,
|
||||
selection_tolerance: p.selection_tolerance,
|
||||
anchor_size: p.anchor_size,
|
||||
@@ -409,11 +411,14 @@ impl Session {
|
||||
/// The selection tool a press at `p` with `mods` borrows ([`Self::lent_tool`]): none when
|
||||
/// the Selection tool keeps a Cmd press on a selected object to select the object behind it
|
||||
/// (Selection & Anchor Display › Command Click to Select Objects Behind), which an earlier Cmd
|
||||
/// press armed ([`Self::behind_armed`]).
|
||||
/// press armed ([`Self::behind_armed`]); none either when the active tool keeps the press
|
||||
/// ([`vectorcraft_tools::Tool::keeps_cmd_press`]), as Direct Selection keeps one on a shown
|
||||
/// direction handle to mirror the opposite handle.
|
||||
fn lent_tool_at(&mut self, p: Point, mods: &Mods, view: ViewInfo) -> Option<&'static str> {
|
||||
let id = self.lent_tool(self.tool.id(), mods)?;
|
||||
let behind = self.tool.id() == "selection" && self.with_tool_cx(view, |_, cx| vectorcraft_tools::select::selects_behind_at(cx, p));
|
||||
(!behind).then_some(id)
|
||||
let kept = !behind && self.with_tool_cx(view, |t, cx| t.keeps_cmd_press(cx, p, *mods));
|
||||
(!behind && !kept).then_some(id)
|
||||
}
|
||||
|
||||
/// Is the press `ev` lent a selection tool ([`Self::lend_selection_tool`])? The frontend asks
|
||||
@@ -649,6 +654,7 @@ impl Session {
|
||||
},
|
||||
anchor_size: self.prefs.anchor_size,
|
||||
path_only: self.prefs.object_selection_by_path_only,
|
||||
unfilled_interiors: self.prefs.select_inside_unfilled_shapes,
|
||||
type_path_only: self.prefs.type_selection_by_path_only,
|
||||
double_click_isolate: self.prefs.double_click_to_isolate,
|
||||
double_click_adds_anchor: self.prefs.double_click_adds_anchor_points,
|
||||
|
||||
@@ -332,6 +332,70 @@ fn direct_handle_cmd_before_press_still_lends_selection_and_returns_direct() {
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), before.undo);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_handle_cmd_held_before_pressing_a_handle_mirrors_instead_of_moving_the_path() {
|
||||
let mut s = session();
|
||||
let id = curve(&mut s, Point::new(50.0, 100.0));
|
||||
let before = node(&s, id);
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let end = Point::new(180.0, 100.0);
|
||||
pointer(&mut s, PointerKind::Down, end, cmd());
|
||||
assert_eq!(s.tool_id(), "directSelection", "a Cmd press on a shown handle is not lent to the Selection tool");
|
||||
let q = Point::new(180.0, 160.0);
|
||||
pointer(&mut s, PointerKind::Drag, q, cmd());
|
||||
assert_mirrored(anchor(&s, id), q, AnchorKind::Smooth);
|
||||
assert_other_geometry(&s, id, &before);
|
||||
pointer(&mut s, PointerKind::Up, q, cmd());
|
||||
assert_mirrored(anchor(&s, id), q, AnchorKind::Smooth);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
assert_eq!(s.tool_id(), "directSelection");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_handle_cmd_shift_held_before_pressing_a_handle_constrains_and_mirrors() {
|
||||
let mut s = session();
|
||||
let id = curve(&mut s, Point::new(50.0, 100.0));
|
||||
let before = node(&s, id);
|
||||
let p = anchor(&s, id).p;
|
||||
let shifted = Mods { shift: true, ..cmd() };
|
||||
pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), shifted);
|
||||
assert_eq!(s.tool_id(), "directSelection");
|
||||
let raw = Point::new(180.0, 150.0);
|
||||
pointer(&mut s, PointerKind::Drag, raw, shifted);
|
||||
assert_mirrored(anchor(&s, id), constrained(p, raw), AnchorKind::Smooth);
|
||||
assert_other_geometry(&s, id, &before);
|
||||
pointer(&mut s, PointerKind::Up, raw, shifted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_handle_cmd_press_on_a_handle_under_a_bounding_box_handle_still_lends_selection() {
|
||||
let mut s = session();
|
||||
let id = curve(&mut s, Point::new(50.0, 100.0));
|
||||
// A second object widens the selection's bounding box so its top-middle handle lands on the
|
||||
// curve's outgoing handle end at (180, 100).
|
||||
let rect = run(&mut s, "path.create", json!({"anchors": [{"x": 330, "y": 150}, {"x": 340, "y": 150}, {"x": 340, "y": 200}], "closed": true}));
|
||||
run(&mut s, "select.set", json!({"ids": [id.0, rect["id"]]}));
|
||||
let boxed = ViewInfo { show_bbox: true, ..view() };
|
||||
let end = Point::new(180.0, 100.0);
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, end.x, end.y).with_mods(cmd()), boxed).unwrap();
|
||||
assert_eq!(s.tool_id(), "selection", "the bounding box handle keeps the press for the lent Selection tool");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, end.x, end.y).with_mods(cmd()), boxed).unwrap();
|
||||
assert_eq!(s.tool_id(), "directSelection");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_handle_cmd_alt_before_pressing_a_handle_still_lends_group_selection() {
|
||||
let mut s = session();
|
||||
let id = curve(&mut s, Point::new(50.0, 100.0));
|
||||
let a = anchor(&s, id);
|
||||
let both = Mods { alt: true, ..cmd() };
|
||||
pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), both);
|
||||
assert_eq!(s.tool_id(), "groupSelection", "Cmd+Alt keeps its Group Selection loan on a handle");
|
||||
pointer(&mut s, PointerKind::Up, Point::new(180.0, 100.0), both);
|
||||
assert_eq!(s.tool_id(), "directSelection");
|
||||
assert_eq!(anchor(&s, id), a);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_handle_cmd_that_lends_direct_selection_from_the_pen_does_not_mirror() {
|
||||
let mut s = session();
|
||||
@@ -490,6 +554,22 @@ fn direct_handle_pinned_blend_spine_cmd_shift_preserves_keys_and_mapping() {
|
||||
assert_content(&s, &after);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_handle_cmd_held_before_pressing_a_blend_spine_handle_mirrors() {
|
||||
let mut s = session();
|
||||
let id = blend(&mut s);
|
||||
let (a, keys, _) = blend_state(&s, id);
|
||||
pointer(&mut s, PointerKind::Down, a.h_out, cmd());
|
||||
assert_eq!(s.tool_id(), "directSelection", "a Cmd press on a spine handle is not lent to the Selection tool");
|
||||
let q = Point::new(180.0, 160.0);
|
||||
pointer(&mut s, PointerKind::Drag, q, cmd());
|
||||
pointer(&mut s, PointerKind::Up, q, cmd());
|
||||
let (after, after_keys, _) = blend_state(&s, id);
|
||||
near(after.p, a.p);
|
||||
assert_mirrored(after, q, AnchorKind::Smooth);
|
||||
assert_eq!(after_keys, keys, "the key objects did not move");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_handle_incoming_drag_mirrors_outgoing_and_release_restores_ordinary_length() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -119,6 +119,78 @@ fn picked_handles_stay_picked_after_they_are_dragged() {
|
||||
near(anchor(&s, id, 2).h_in, Point::new(310.0, 170.0));
|
||||
}
|
||||
|
||||
/// With two handles picked, Cmd/Ctrl held before the press on one of them drags that handle alone
|
||||
/// and mirrors its opposite handle; the other picked handle stays where it is.
|
||||
#[test]
|
||||
fn a_cmd_drag_of_one_of_two_picked_handles_mirrors_its_opposite_handle() {
|
||||
let (mut s, id) = session();
|
||||
click(&mut s, Point::new(180.0, 100.0), Mods::default());
|
||||
click(&mut s, Point::new(300.0, 140.0), shift());
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
drag(&mut s, Point::new(180.0, 100.0), Point::new(180.0, 160.0), cmd);
|
||||
assert_eq!(s.tool_id(), "directSelection");
|
||||
let a = anchor(&s, id, 1);
|
||||
near(a.h_out, Point::new(180.0, 160.0));
|
||||
near(a.h_in, Point::new(20.0, 40.0));
|
||||
assert_eq!(a.kind, AnchorKind::Smooth);
|
||||
near(anchor(&s, id, 2).h_in, Point::new(300.0, 140.0));
|
||||
}
|
||||
|
||||
/// Both handles stay picked after a Cmd/Ctrl drag of one of them: a drag of the other without
|
||||
/// Cmd/Ctrl then moves both.
|
||||
#[test]
|
||||
fn picked_handles_stay_picked_after_a_cmd_drag_of_one_of_them() {
|
||||
let (mut s, id) = session();
|
||||
click(&mut s, Point::new(180.0, 100.0), Mods::default());
|
||||
click(&mut s, Point::new(300.0, 140.0), shift());
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
drag(&mut s, Point::new(180.0, 100.0), Point::new(180.0, 160.0), cmd);
|
||||
drag(&mut s, Point::new(300.0, 140.0), Point::new(310.0, 140.0), Mods::default());
|
||||
near(anchor(&s, id, 1).h_out, Point::new(190.0, 160.0));
|
||||
near(anchor(&s, id, 2).h_in, Point::new(310.0, 140.0));
|
||||
}
|
||||
|
||||
/// Both handles stay picked after a Cmd/Ctrl+Shift drag of one of them, and after Escape during
|
||||
/// one.
|
||||
#[test]
|
||||
fn picked_handles_stay_picked_after_a_cmd_shift_drag_of_one_of_them() {
|
||||
for escape in [false, true] {
|
||||
let (mut s, id) = session();
|
||||
click(&mut s, Point::new(180.0, 100.0), Mods::default());
|
||||
click(&mut s, Point::new(300.0, 140.0), shift());
|
||||
let cmd_shift = Mods { cmd: true, shift: true, ..Mods::default() };
|
||||
pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), cmd_shift);
|
||||
pointer(&mut s, PointerKind::Drag, Point::new(220.0, 100.0), cmd_shift);
|
||||
if escape {
|
||||
s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap();
|
||||
}
|
||||
pointer(&mut s, PointerKind::Up, Point::new(220.0, 100.0), cmd_shift);
|
||||
let x = if escape { 180.0 } else { 220.0 };
|
||||
near(anchor(&s, id, 1).h_out, Point::new(x, 100.0));
|
||||
drag(&mut s, Point::new(300.0, 140.0), Point::new(310.0, 140.0), Mods::default());
|
||||
near(anchor(&s, id, 1).h_out, Point::new(x + 10.0, 100.0));
|
||||
near(anchor(&s, id, 2).h_in, Point::new(310.0, 140.0));
|
||||
}
|
||||
}
|
||||
|
||||
/// Escape during a Cmd/Ctrl drag of one of two picked handles puts the handle back and leaves both
|
||||
/// picked.
|
||||
#[test]
|
||||
fn escape_during_a_cmd_drag_of_a_picked_handle_keeps_both_picked() {
|
||||
let (mut s, id) = session();
|
||||
click(&mut s, Point::new(180.0, 100.0), Mods::default());
|
||||
click(&mut s, Point::new(300.0, 140.0), shift());
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), cmd);
|
||||
pointer(&mut s, PointerKind::Drag, Point::new(180.0, 160.0), cmd);
|
||||
s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap();
|
||||
pointer(&mut s, PointerKind::Up, Point::new(180.0, 160.0), cmd);
|
||||
near(anchor(&s, id, 1).h_out, Point::new(180.0, 100.0));
|
||||
drag(&mut s, Point::new(300.0, 140.0), Point::new(310.0, 140.0), Mods::default());
|
||||
near(anchor(&s, id, 1).h_out, Point::new(190.0, 100.0));
|
||||
near(anchor(&s, id, 2).h_in, Point::new(310.0, 140.0));
|
||||
}
|
||||
|
||||
/// A Shift-click on a picked handle takes it away, and Escape lets every picked handle go: a drag
|
||||
/// then moves only the handle pressed.
|
||||
#[test]
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -8,7 +8,7 @@ use vectorcraft_doc::{
|
||||
Appearance, AppearanceItem, Artboard, Dash, Document, FillLayer, ImageBlob, ImageObject, Knockout, LayerColor, LineCap, LineJoin, Node, NodeKind,
|
||||
OpacityMask, StrokeLayer, Symbol,
|
||||
};
|
||||
use vectorcraft_geom::{Affine, FillRule, PathData, Rect, shapes};
|
||||
use vectorcraft_geom::{Affine, FillRule, PathData, Rect, Shape, shapes};
|
||||
|
||||
use super::*;
|
||||
|
||||
@@ -1020,6 +1020,167 @@ fn hidden_layers_open_hidden() {
|
||||
assert!(text.contains("%AI5_NumLayers: 3\n%AI5_OpenViewLayers: 776\n"), "{text}");
|
||||
}
|
||||
|
||||
fn dash_painted_nodes(nodes: &[Arc<Node>], out: &mut Vec<Node>) {
|
||||
for n in nodes {
|
||||
match &n.kind {
|
||||
NodeKind::Path { .. } | NodeKind::Compound { .. } => out.push((**n).clone()),
|
||||
_ => {
|
||||
if let Some(children) = n.children() {
|
||||
dash_painted_nodes(children, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Original synthetic rectangle, independent of the artwork in #10476.
|
||||
fn dash_compat_document(pattern: Vec<f64>) -> Document {
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let mut stroke = StrokeLayer::new(solid(Color::BLACK), 4.0);
|
||||
stroke.dash = Some(Dash { pattern, offset: 2.5, align_corners: false });
|
||||
stroke.overprint = true;
|
||||
let ap = Appearance {
|
||||
items: vec![AppearanceItem::Fill(FillLayer::new(solid(Color::rgb(0.0, 1.0, 0.0)))), AppearanceItem::Stroke(stroke)],
|
||||
..Appearance::default()
|
||||
};
|
||||
let n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 180.0, 80.0)), ap);
|
||||
doc.insert(Some(doc.layers[0].id), usize::MAX, n).unwrap();
|
||||
doc
|
||||
}
|
||||
|
||||
fn ai_dash_outputs(doc: &Document) -> Vec<(String, Vec<String>, Document)> {
|
||||
let out = export_ai_editing(doc, &opts()).unwrap();
|
||||
let legacy = crate::export_legacy_ai(doc, &crate::LegacyAiOptions::default()).unwrap();
|
||||
let legacy_back = crate::import(&legacy.bytes).unwrap().document;
|
||||
vec![
|
||||
(String::from_utf8(out.program).unwrap().replace("\r\n", "\n"), out.warnings, read_back(doc)),
|
||||
(String::from_utf8(legacy.bytes).unwrap().replace("\r\n", "\n"), legacy.warnings, legacy_back),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ai_dash_lists_reduce_repetitions_and_keep_small_patterns_editable() {
|
||||
for (pattern, emitted) in [
|
||||
(vec![33.5673; 5], "[33.5673] 2.5 d"),
|
||||
(vec![33.5673; 10], "[33.5673] 2.5 d"),
|
||||
(vec![3.0, 2.0, 1.0, 3.0, 2.0, 1.0, 3.0, 2.0, 1.0], "[3 2 1] 2.5 d"),
|
||||
(vec![0.25], "[0.25] 2.5 d"),
|
||||
(vec![0.25, 0.5], "[0.25 0.5] 2.5 d"),
|
||||
(vec![3.0, 2.0, 1.0], "[3 2 1] 2.5 d"),
|
||||
(vec![3.0, 2.0, 1.0, 2.0, 3.0, 4.0], "[3 2 1 2 3 4] 2.5 d"),
|
||||
] {
|
||||
let doc = dash_compat_document(pattern.clone());
|
||||
for (text, warnings, back) in ai_dash_outputs(&doc) {
|
||||
assert!(text.contains(emitted), "{pattern:?}: missing {emitted}: {text}");
|
||||
assert!(warnings.is_empty(), "{pattern:?}: {warnings:?}");
|
||||
let mut art = vec![];
|
||||
dash_painted_nodes(&back.layers, &mut art);
|
||||
assert_eq!(art.len(), 1);
|
||||
let st = art[0].appearance.stroke().unwrap();
|
||||
assert_eq!(st.width, 4.0);
|
||||
assert!(st.overprint);
|
||||
assert_eq!(st.dash.as_ref().unwrap().offset, 2.5);
|
||||
let got = &st.dash.as_ref().unwrap().pattern;
|
||||
for i in 0..pattern.len() * got.len() * 2 {
|
||||
assert_eq!(pattern[i % pattern.len()], got[i % got.len()]);
|
||||
}
|
||||
assert!(art[0].appearance.fill().is_some());
|
||||
}
|
||||
assert_eq!(doc.layers[0].children().unwrap()[0].appearance.stroke().unwrap().dash.as_ref().unwrap().pattern, pattern);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ai_dash_lists_that_exceed_six_effective_lengths_are_outlined_with_a_warning() {
|
||||
for pattern in [vec![3.0, 2.0, 1.0, 2.0, 3.0], vec![3.0, 2.0, 1.0, 2.0, 3.0, 4.0, 5.0], vec![3.0, 2.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0]] {
|
||||
let doc = dash_compat_document(pattern);
|
||||
let original = &doc.layers[0].children().unwrap()[0];
|
||||
let path = original.path_data().unwrap();
|
||||
let expected = vectorcraft_effects::stroke::outline_region(path, FillRule::NonZero, original.appearance.stroke().unwrap()).to_bezpath();
|
||||
for (text, warnings, back) in ai_dash_outputs(&doc) {
|
||||
assert!(warnings.iter().any(|w| w.contains("filled outlines")), "{warnings:?}");
|
||||
assert!(
|
||||
!text.lines().filter(|l| l.ends_with(" d")).any(|l| {
|
||||
let array = l.rsplit_once('[').unwrap().1.split(']').next().unwrap();
|
||||
let n = array.split_whitespace().count();
|
||||
n > 6 || (n % 2 == 1 && n * 2 > 6)
|
||||
}),
|
||||
"{text}"
|
||||
);
|
||||
let mut art = vec![];
|
||||
dash_painted_nodes(&back.layers, &mut art);
|
||||
assert!(art.iter().all(|n| n.appearance.stroke().is_none()), "{art:?}");
|
||||
assert_eq!(art.len(), 2, "fill and outlined stroke keep their paint order");
|
||||
assert_eq!(art[0].appearance.fill().unwrap().paint, solid(Color::rgb(0.0, 1.0, 0.0)));
|
||||
let fill = art[1].appearance.fill().unwrap();
|
||||
assert_eq!(fill.paint, solid(Color::BLACK));
|
||||
assert!(fill.overprint);
|
||||
let got = art[1].stroke_path().unwrap();
|
||||
for y in 5..85 {
|
||||
for x in 5..185 {
|
||||
let p = vectorcraft_geom::Point::new(f64::from(x) + 0.123, f64::from(y) + 0.123);
|
||||
assert_eq!(got.winding(p) != 0, expected.winding(p) != 0, "at {p:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ai_dash_lists_in_linked_styles_also_respect_the_reader_limit() {
|
||||
for (pattern, live) in [(vec![3.0, 2.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0], false), (vec![33.5673; 5], true)] {
|
||||
let mut doc = dash_compat_document(pattern);
|
||||
let n = Arc::make_mut(&mut Arc::make_mut(&mut doc.layers[0]).children_mut().unwrap()[0]);
|
||||
n.appearance.stroke_mut().unwrap().overprint = false;
|
||||
n.extras_mut().graphic_style = Some(7);
|
||||
let mut style = vectorcraft_doc::GraphicStyle::new("Dashed", (*n.appearance).clone());
|
||||
style.id = 7;
|
||||
doc.graphic_styles.push(style);
|
||||
let out = export_ai_editing(&doc, &opts()).unwrap();
|
||||
let text = String::from_utf8(out.program).unwrap();
|
||||
assert!(!text.contains("[3 2 1 2 3 4 5 6]"), "a style dictionary must not keep an incompatible dash list");
|
||||
if live {
|
||||
assert!(out.warnings.is_empty(), "{:?}", out.warnings);
|
||||
assert!(text.contains("1 (Dashed) XW"), "an equivalent dash representation keeps the style link");
|
||||
assert!(text.contains("[33.5673] 2.5 d"));
|
||||
} else {
|
||||
assert!(out.warnings.iter().any(|w| w.contains("filled outlines")), "{:?}", out.warnings);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ai_dash_lists_in_legacy_text_reduce_or_outline_without_becoming_solid() {
|
||||
use vectorcraft_doc::{CharStyle, TextObject};
|
||||
use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, height_font};
|
||||
// Existing licensed test face, with original single-letter artwork.
|
||||
vectorcraft_text::FontDb::global().add_font(height_font(true).unwrap());
|
||||
for (pattern, live) in [(vec![33.5673; 5], true), (vec![3.0, 2.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0], false)] {
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let st = CharStyle {
|
||||
font_family: HEIGHT_FAMILY.into(),
|
||||
size: 48.0,
|
||||
fill: solid(Color::rgb(0.0, 1.0, 0.0)),
|
||||
stroke: solid(Color::BLACK),
|
||||
stroke_width: 2.0,
|
||||
stroke_dash: Some(Dash { pattern, offset: 2.5, align_corners: false }),
|
||||
..CharStyle::default()
|
||||
};
|
||||
let t = TextObject::point(vectorcraft_geom::Point::new(20.0, 60.0), "T", st);
|
||||
let n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t)));
|
||||
doc.insert(Some(doc.layers[0].id), usize::MAX, n).unwrap();
|
||||
let out = crate::export_legacy_ai(&doc, &crate::LegacyAiOptions::default()).unwrap();
|
||||
let text = String::from_utf8(out.bytes).unwrap().replace("\r\n", "\n");
|
||||
assert_eq!(text.contains("0 To\n"), live, "irreducible type strokes must take the outline fallback");
|
||||
if live {
|
||||
assert!(text.contains("[33.5673] 2.5 d"));
|
||||
} else {
|
||||
assert!(out.warnings.iter().any(|w| w.contains("filled outlines")), "{:?}", out.warnings);
|
||||
assert!(text.matches("\nf\n").count() >= 2, "the glyph's fill and dashed stroke are both painted");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A 200 × 100 document of a gradient fill, a compound path, an image and a symbol instance, and
|
||||
/// what the data holds as plain paths: type.
|
||||
fn unsupported() -> Document {
|
||||
|
||||
@@ -71,7 +71,7 @@ pub(super) const LIVE: &str =
|
||||
"repeats, placed documents, intertwines and distorted images are written as their art in the editing data for other apps";
|
||||
pub(super) const DEEP_DISTORTED: &str = "images changed by Perspective Distort or Free Distort nested 8 deep in opacity masks, symbols, live objects and pattern tiles are written as the nearest parallelogram in the editing data for other apps";
|
||||
pub(super) const GRAPHS: &str = "graphs are written as their art, without their data or settings, in the editing data for other apps";
|
||||
pub(super) const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, dots, dashes fitted to corners, gradients, patterns, arrowheads) are written as filled outlines, and brushed strokes as their brush's art, in the editing data for other apps";
|
||||
pub(super) const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, complex dash patterns, dots, dashes fitted to corners, gradients, patterns, arrowheads) are written as filled outlines, and brushed strokes as their brush's art, in the editing data for other apps";
|
||||
pub(super) const ITEM_TRANSPARENCY: &str =
|
||||
"the opacity and blending modes of single fills and strokes are left out of the editing data for other apps";
|
||||
pub(super) const LAYER_MASKS: &str = "opacity masks on layers are left out of the editing data for other apps";
|
||||
|
||||
@@ -364,7 +364,7 @@ fn plain_key(k: &Node) -> bool {
|
||||
&& i.effects().is_empty()
|
||||
&& i.opacity() >= 1.0
|
||||
&& i.blend() == BlendMode::Normal
|
||||
&& !matches!(i, AppearanceItem::Stroke(s) if !vectorcraft_effects::stroke::is_plain(s) || !dash_read_back(s))
|
||||
&& !matches!(i, AppearanceItem::Stroke(s) if !crate::ai_ops::plain_stroke(s) || !dash_read_back(s))
|
||||
});
|
||||
plain &= kind && fills <= 1 && strokes <= 1 && order && quiet && n.appearance.effects.is_empty() && n.extras().mask.is_none();
|
||||
});
|
||||
|
||||
@@ -258,7 +258,7 @@ fn plain_within(art: &Node, masks: u32) -> bool {
|
||||
&& i.opacity() >= 1.0
|
||||
&& i.blend() == BlendMode::Normal
|
||||
&& matches!(i.paint(), Paint::Solid { .. } | Paint::None)
|
||||
&& !matches!(i, AppearanceItem::Stroke(s) if !vectorcraft_effects::stroke::is_plain(s))
|
||||
&& !matches!(i, AppearanceItem::Stroke(s) if !crate::ai_ops::plain_stroke(s))
|
||||
});
|
||||
// A group's own fills and strokes aren't written.
|
||||
let group_paint = matches!(n.kind, NodeKind::Group { .. }) && items.iter().any(|i| !i.paint().is_none());
|
||||
@@ -519,7 +519,7 @@ impl Writer<'_> {
|
||||
let name = st.brush.as_deref()?;
|
||||
self.brush_set();
|
||||
let (plugin, kind) = self.live_brush(name).map(|b| (b.plugin, b.brush.kind.clone()))?;
|
||||
if !matches!(st.paint, Paint::Solid { .. }) || st.overprint {
|
||||
if !matches!(st.paint, Paint::Solid { .. }) || st.overprint || !ai_ops::dash_fits(st) {
|
||||
return None;
|
||||
}
|
||||
let ops = self.color_ops(&st.paint, true);
|
||||
|
||||
@@ -8,7 +8,6 @@ use vectorcraft_color::gradient::GradientGeom;
|
||||
use vectorcraft_color::swatch::REGISTRATION;
|
||||
use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint};
|
||||
use vectorcraft_doc::{AppearanceItem, FillLayer, PatternDef, StrokeLayer, TileType};
|
||||
use vectorcraft_effects::stroke;
|
||||
use vectorcraft_geom::{Affine, BezPath, Rect, Shape, Vec2};
|
||||
|
||||
use super::{MAX_NEST, Writer, Xy};
|
||||
@@ -367,7 +366,7 @@ impl Writer<'_> {
|
||||
/// Does a plain line of `s`'s paint draw it ([`Self::direct`], and the line style operators can
|
||||
/// write it)?
|
||||
pub(super) fn direct_stroke(&self, s: &StrokeLayer) -> bool {
|
||||
self.direct(&s.paint) && stroke::is_plain(s)
|
||||
self.direct(&s.paint) && crate::ai_ops::plain_stroke(s)
|
||||
}
|
||||
|
||||
/// `n`'s paint `items` as one path object paints: no paint, a fill, a plain line, or both, the
|
||||
|
||||
@@ -404,7 +404,7 @@ impl Writer<'_> {
|
||||
if st.brush.is_some() {
|
||||
return self.brush_filter(s, st, visible);
|
||||
}
|
||||
if !matches!(st.paint, Paint::Solid { .. }) || st.overprint {
|
||||
if !matches!(st.paint, Paint::Solid { .. }) || st.overprint || !ai_ops::dash_fits(st) {
|
||||
return None;
|
||||
}
|
||||
let ops = self.color_ops(&st.paint, true);
|
||||
@@ -1077,6 +1077,16 @@ pub(in crate::ai_editing) fn same_appearance(a: &Appearance, b: &Appearance) ->
|
||||
let below = ap.items.iter().take(ci).filter(|i| !i.paint().is_none()).count();
|
||||
ap.items.retain(|i| !i.paint().is_none());
|
||||
ap.contents_index = (below > 0).then_some(below);
|
||||
// The writer shortens repeated dash lists without changing their painted period.
|
||||
// Compare those representations equally so a linked style can stay live.
|
||||
for i in &mut ap.items {
|
||||
if let AppearanceItem::Stroke(st) = i
|
||||
&& let Some(d) = st.dash.as_mut().filter(|d| d.is_dashed())
|
||||
&& let Some(pattern) = ai_ops::dash_pattern(&d.pattern)
|
||||
{
|
||||
d.pattern = pattern.to_vec();
|
||||
}
|
||||
}
|
||||
for e in ap.effects.iter_mut().chain(ap.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut())) {
|
||||
e.params = normalized_params(e);
|
||||
}
|
||||
|
||||
@@ -53,7 +53,9 @@ pub(in crate::ai_editing) const SYMBOL_COUNT: &str = "symbols past 4,096 are lef
|
||||
pub(super) fn redrawn(n: &Node) -> bool {
|
||||
let rounded = |l: &vectorcraft_doc::LiveShape| match l {
|
||||
vectorcraft_doc::LiveShape::Rectangle { radii, .. } => radii.iter().any(|r| *r > 0.0),
|
||||
vectorcraft_doc::LiveShape::Polygon { radii, .. } | vectorcraft_doc::LiveShape::Path { radii, .. } => radii.iter().any(|r| *r > 0.0),
|
||||
vectorcraft_doc::LiveShape::Polygon { radii, .. }
|
||||
| vectorcraft_doc::LiveShape::Star { radii, .. }
|
||||
| vectorcraft_doc::LiveShape::Path { radii, .. } => radii.iter().any(|r| *r > 0.0),
|
||||
vectorcraft_doc::LiveShape::Ellipse { .. } | vectorcraft_doc::LiveShape::Line { .. } => false,
|
||||
};
|
||||
match &n.kind {
|
||||
|
||||
@@ -425,8 +425,8 @@ fn plain_wrap_art(n: &Node, styled: &HashMap<NodeId, Arc<Node>>) -> bool {
|
||||
let painted = || match super::visible_items(n).as_slice() {
|
||||
[] => true,
|
||||
[AppearanceItem::Fill(f)] => solid(&f.paint),
|
||||
[AppearanceItem::Stroke(s)] => solid(&s.paint) && vectorcraft_effects::stroke::is_plain(s),
|
||||
[AppearanceItem::Fill(f), AppearanceItem::Stroke(s)] => solid(&f.paint) && solid(&s.paint) && vectorcraft_effects::stroke::is_plain(s),
|
||||
[AppearanceItem::Stroke(s)] => solid(&s.paint) && crate::ai_ops::plain_stroke(s),
|
||||
[AppearanceItem::Fill(f), AppearanceItem::Stroke(s)] => solid(&f.paint) && solid(&s.paint) && crate::ai_ops::plain_stroke(s),
|
||||
_ => false,
|
||||
};
|
||||
let whole = |p: &PathData| p.subpaths.iter().all(|sp| sp.anchors.len() >= 2);
|
||||
|
||||
@@ -179,7 +179,28 @@ pub(crate) fn window_samples(samples: &[u8], w: u32, channels: usize, [x0, y0, x
|
||||
out
|
||||
}
|
||||
|
||||
/// The stroke's width, cap, join, miter limit and dashes: `w J j M d`.
|
||||
/// The shortest equivalent dash list the AI reader can hold. Odd lists repeat twice before
|
||||
/// dash/gap parity repeats. Keep at most six effective lengths: longer lists can make the
|
||||
/// reader reject the entire file (#10476). Compare exactly, so no dash or gap changes length.
|
||||
pub(crate) fn dash_pattern(pattern: &[f64]) -> Option<&[f64]> {
|
||||
(1..=pattern.len().min(6))
|
||||
.filter(|n| n % 2 == 0 || *n <= 3)
|
||||
.find(|n| pattern.len().is_multiple_of(*n) && pattern.iter().enumerate().all(|(i, v)| *v == pattern[i % n]))
|
||||
.map(|n| &pattern[..n])
|
||||
}
|
||||
|
||||
/// Invalid or empty dashes already draw solid; valid dashes need an exact short representation.
|
||||
pub(crate) fn dash_fits(st: &StrokeLayer) -> bool {
|
||||
st.dash.as_ref().filter(|d| d.is_dashed()).is_none_or(|d| dash_pattern(&d.pattern).is_some())
|
||||
}
|
||||
|
||||
/// A plain AI stroke, including the reader's dash-list limit. Other strokes use filled outlines.
|
||||
pub(crate) fn plain_stroke(st: &StrokeLayer) -> bool {
|
||||
vectorcraft_effects::stroke::is_plain(st) && dash_fits(st)
|
||||
}
|
||||
|
||||
/// The stroke's width, cap, join, miter limit and dashes: `w J j M d`. Callers check
|
||||
/// [`dash_fits`] first; irreducible longer patterns belong in their outline fallback.
|
||||
pub(crate) fn line_style(s: &mut String, st: &StrokeLayer) {
|
||||
let cap = match st.cap {
|
||||
LineCap::Butt => ps::LineCap::Butt,
|
||||
@@ -191,6 +212,6 @@ pub(crate) fn line_style(s: &mut String, st: &StrokeLayer) {
|
||||
LineJoin::Round => ps::LineJoin::Round,
|
||||
LineJoin::Bevel => ps::LineJoin::Bevel,
|
||||
};
|
||||
let dash = st.dash.as_ref().filter(|d| d.is_dashed()).map(|d| (d.pattern.as_slice(), d.offset));
|
||||
let dash = st.dash.as_ref().filter(|d| d.is_dashed()).and_then(|d| dash_pattern(&d.pattern).map(|p| (p, d.offset)));
|
||||
ps::push_line_style(s, st.width, cap, join, st.miter_limit, dash);
|
||||
}
|
||||
@@ -125,8 +125,7 @@ const HUE_STOPS: &str = "gradients mixed around the hue wheel are written in pro
|
||||
const PERCEPTUAL_STOPS: &str = "Perceptual gradients are written in process colors, with the colors between their stops as stops of their own (at most 256; legacy .ai gradients mix their stops' colors directly)";
|
||||
/// Wedges a conic gradient is written as: one a degree.
|
||||
const CONIC_WEDGES: usize = 360;
|
||||
const STROKES: &str =
|
||||
"strokes a plain line can't draw (inside or outside the path, variable width, gradients, brushes, arrowheads) are written as filled outlines";
|
||||
const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, complex dash patterns, gradients, brushes, arrowheads) are written as filled outlines";
|
||||
const IMAGE_ALPHA: &str = "transparent image pixels are written over white";
|
||||
const LIVE: &str = "symbols, blends, envelopes, meshes, repeats, placed documents, intertwines and distorted images are written as their art";
|
||||
const DEEP_DISTORTED: &str =
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::writer::Writer;
|
||||
use super::{
|
||||
Affine, AreaOptions, BezPath, CharPosition, CharStyle, CompositeFont, Document, Gradient, GradientKind, Paint, ParaStyle, PathAlign, PathEffect,
|
||||
StrokeLayer, TextKind, TextObject, Write, latin, ps, stroke,
|
||||
StrokeLayer, TextKind, TextObject, Write, latin, ps,
|
||||
};
|
||||
|
||||
/// A gradient definition: `%AI5_BeginGradient: (name)`, `(name) type stops Bd`, `[`, the stops
|
||||
@@ -111,6 +111,9 @@ pub(super) fn holds_as_text(t: &TextObject) -> bool {
|
||||
r.inline.is_none()
|
||||
&& solid(&r.style.fill)
|
||||
&& solid(&r.style.stroke)
|
||||
// Long dash lists can reject the entire AI file. Keep their glyph paint by
|
||||
// taking the existing type-outline path instead of writing a solid stroke.
|
||||
&& (!r.style.has_stroke() || crate::ai_ops::dash_fits(&r.style.stroke_layer()))
|
||||
&& (if r.style.all_caps { r.text.to_uppercase() } else { r.text.clone() }).chars().all(|c| latin::encode(c).is_some())
|
||||
})
|
||||
}
|
||||
@@ -221,5 +224,5 @@ pub(super) fn direct_fill(p: &Paint) -> bool {
|
||||
|
||||
/// Can stroke `s` be written as the stroke of a path object (a plain line of a colour)?
|
||||
pub(super) fn direct_stroke(s: &StrokeLayer) -> bool {
|
||||
matches!(s.paint, Paint::Solid { .. }) && stroke::is_plain(s)
|
||||
matches!(s.paint, Paint::Solid { .. }) && crate::ai_ops::plain_stroke(s)
|
||||
}
|
||||
@@ -275,6 +275,10 @@ fn body(doc: &Document, o: &SaveOptions) -> Result<Body, FormatError> {
|
||||
d.halftone_radii_to_points();
|
||||
d.store_legacy_twist_angles();
|
||||
}
|
||||
// Older apps don't know live stars: they get the outline a star draws as a plain path.
|
||||
if version < VERSION {
|
||||
d.live_stars_to_paths();
|
||||
}
|
||||
let v1 = if version == 1 {
|
||||
let mut v = serde_json::to_value(&d).map_err(encode_err)?;
|
||||
legacy::anchors_to_v1(&mut v);
|
||||
|
||||
@@ -19,6 +19,20 @@ fn json_of(bytes: &[u8]) -> Value {
|
||||
serde_json::from_slice(bytes).unwrap()
|
||||
}
|
||||
|
||||
/// `v` (a document's JSON) with every live star's `live` taken off its path.
|
||||
fn without_live_stars(v: &mut Value) {
|
||||
match v {
|
||||
Value::Object(o) => {
|
||||
if o.get("live").and_then(|l| l.get("shape")).and_then(Value::as_str) == Some("star") {
|
||||
o.remove("live");
|
||||
}
|
||||
o.values_mut().for_each(without_live_stars);
|
||||
}
|
||||
Value::Array(a) => a.iter_mut().for_each(without_live_stars),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn gzip(bytes: &[u8]) -> Vec<u8> {
|
||||
let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
|
||||
gz.write_all(bytes).unwrap();
|
||||
@@ -274,7 +288,9 @@ fn version_1_files_load() {
|
||||
fn saves_down_to_older_versions() {
|
||||
let mut d = rich_doc();
|
||||
d.color_profiles = ColorProfiles { rgb: None, cmyk: Some("Coated".into()) };
|
||||
let current = doc_json(&load(&save(&d, false)).unwrap());
|
||||
let mut current = doc_json(&load(&save(&d, false)).unwrap());
|
||||
// Older versions get live stars as plain paths.
|
||||
without_live_stars(&mut current);
|
||||
for version in [1, 2] {
|
||||
let bytes = save_with(&d, &opts(version, false)).unwrap();
|
||||
let v = json_of(&bytes);
|
||||
@@ -299,6 +315,47 @@ fn saves_down_to_older_versions() {
|
||||
assert!(matches!(save_with(&d, &opts(2, true)), Err(FormatError::CompressedTooOld(2))));
|
||||
}
|
||||
|
||||
/// Versions before [`VERSION`] don't know live stars: a save for them writes the star's outline as
|
||||
/// a plain path, which those versions read; the current version keeps the star live.
|
||||
#[test]
|
||||
fn older_versions_get_a_live_star_as_its_path() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let star = vectorcraft_doc::LiveShape::Star {
|
||||
r1: 40.0,
|
||||
r2: 20.0,
|
||||
points: 5,
|
||||
xf: Affine::translate((50.0, 50.0)),
|
||||
radii: vec![],
|
||||
kinds: vec![],
|
||||
radii_relative: false,
|
||||
};
|
||||
let id = d.alloc_id();
|
||||
let mut node = Node::path(id, star.to_path(), Default::default());
|
||||
if let NodeKind::Path { live, .. } = &mut node.kind {
|
||||
*live = Some(Box::new(star.clone()));
|
||||
}
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), usize::MAX, node).unwrap();
|
||||
for version in 1..VERSION {
|
||||
let bytes = save_with(&d, &opts(version, false)).unwrap();
|
||||
let text = String::from_utf8(bytes.clone()).unwrap();
|
||||
assert!(!text.contains("\"star\""), "v{version} writes no live star");
|
||||
let back = load(&bytes).unwrap();
|
||||
let mut anchors = None;
|
||||
back.walk(|n| {
|
||||
if let NodeKind::Path { path, live, .. } = &n.kind {
|
||||
assert!(live.is_none(), "v{version}");
|
||||
anchors = Some(path.anchor_count());
|
||||
}
|
||||
});
|
||||
assert_eq!(anchors, Some(10), "v{version} keeps the star's outline");
|
||||
}
|
||||
let back = load(&save(&d, false)).unwrap();
|
||||
let mut live = None;
|
||||
back.walk(|n| live = live.clone().or(n.live_shape().cloned()));
|
||||
assert_eq!(live, Some(star));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preview_is_embedded_and_read_back() {
|
||||
let d = Document::new(10.0, 10.0);
|
||||
|
||||
@@ -11,6 +11,20 @@ use vectorcraft_testkit::fixtures;
|
||||
use vectorcraft_testkit::invariants::{check_document, check_native_roundtrip, check_native_roundtrip_exact, doc_json, json_approx_eq};
|
||||
use vectorcraft_testkit::strategies::arb_ops;
|
||||
|
||||
/// `v` (a document's JSON) with every live star's `live` taken off its path.
|
||||
fn without_live_stars(v: &mut Value) {
|
||||
match v {
|
||||
Value::Object(o) => {
|
||||
if o.get("live").and_then(|l| l.get("shape")).and_then(Value::as_str) == Some("star") {
|
||||
o.remove("live");
|
||||
}
|
||||
o.values_mut().for_each(without_live_stars);
|
||||
}
|
||||
Value::Array(a) => a.iter_mut().for_each(without_live_stars),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn rich_doc() -> Document {
|
||||
(*fixtures::rich_session().doc().unwrap().doc).clone()
|
||||
}
|
||||
@@ -117,9 +131,13 @@ proptest! {
|
||||
}
|
||||
let d = s.doc().unwrap().doc.clone();
|
||||
let want = doc_json(&load(&save(&d, false)).unwrap());
|
||||
// Older versions get live stars as plain paths.
|
||||
let mut older = want.clone();
|
||||
without_live_stars(&mut older);
|
||||
for o in [SaveOptions { compress: true, ..SaveOptions::default() }, SaveOptions { version: 2, ..SaveOptions::default() }, SaveOptions { version: 1, pretty: true, ..SaveOptions::default() }] {
|
||||
let back = load(&save_with(&d, &o).unwrap()).unwrap();
|
||||
prop_assert!(json_approx_eq(&doc_json(&back), &want, 1e-12), "{:?} differs", o);
|
||||
let want = if o.version < vectorcraft_format::VERSION { &older } else { &want };
|
||||
prop_assert!(json_approx_eq(&doc_json(&back), want, 1e-12), "{:?} differs", o);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -455,9 +455,9 @@ pub fn polygon_configured(center: Point, radius: f64, sides: u32, rotation_deg:
|
||||
contour_with_rounding(&pts, rounded)
|
||||
}
|
||||
|
||||
/// Star with `points` tips (≥ 2), outer radius `r1`, inner radius `r2`, first tip up.
|
||||
/// Star with `points` tips (2–1000), outer radius `r1`, inner radius `r2`, first tip up.
|
||||
pub fn star(center: Point, r1: f64, r2: f64, points: u32, rotation_deg: f64) -> PathData {
|
||||
let n = points.max(2) * 2;
|
||||
let n = points.clamp(2, 1000) * 2;
|
||||
let rot = rotation_deg.to_radians();
|
||||
let pts: Vec<Point> = (0..n)
|
||||
.map(|i| {
|
||||
@@ -1485,6 +1485,12 @@ mod tests {
|
||||
assert!((d[0] - 10.0).abs() < 1e-9 && (d[1] - 5.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn star_keeps_to_a_thousand_points() {
|
||||
assert_eq!(star(Point::ZERO, 10.0, 5.0, 5000, 0.0).anchor_count(), 2000);
|
||||
assert_eq!(star(Point::ZERO, 10.0, 5.0, 1, 0.0).anchor_count(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn straight_star_five_points() {
|
||||
let r2 = straight_star_inner_radius(100.0, 5);
|
||||
|
||||
@@ -22,7 +22,9 @@ vectorcraft-format = { workspace = true }
|
||||
vectorcraft-tools = { workspace = true }
|
||||
vectorcraft-geom = { workspace = true }
|
||||
vectorcraft-doc = { workspace = true }
|
||||
craft = { workspace = true, features = ["automation"] }
|
||||
# `automation-agents` and `control-agents`: plain `mcp` finds the open window through the ArtCraft
|
||||
# Launcher's switch and the connection file, with the shared live client and the agent folders.
|
||||
craft = { workspace = true, features = ["automation", "automation-agents", "control-agents"] }
|
||||
serde_json = { workspace = true }
|
||||
log = { workspace = true }
|
||||
|
||||
|
||||
Loaded 100 of 220 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user