Merge main into fix/hindi-label-senses

This commit is contained in:
dotCooCoo
2026-11-14 02:25:08 -08:00
350 changed files with 44151 additions and 3437 deletions
Generated
+99 -28
View File
@@ -978,11 +978,33 @@ dependencies = [
"ruzstd",
]
[[package]]
name = "craft-codepage"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
[[package]]
name = "craft-docpath"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
[[package]]
name = "craft-dxf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
dependencies = [
"craft-codepage",
"encoding_rs",
"kurbo 0.13.1",
"log",
"thiserror 2.0.21",
]
[[package]]
name = "craft-eps"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
@@ -1057,6 +1079,21 @@ dependencies = [
"unicode-normalization",
]
[[package]]
name = "craft-svg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
dependencies = [
"craft-xml",
"flate2",
"kurbo 0.13.1",
"roxmltree 0.21.2",
"thiserror 2.0.21",
"usvg 0.48.1",
"vectorcraft-geom 0.18.0",
"vectorcraft-pathops 0.18.0",
]
[[package]]
name = "craft-ui"
version = "0.1.0"
@@ -1146,6 +1183,15 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
dependencies = [
"quick-xml 0.41.0",
"thiserror 2.0.21",
]
[[package]]
name = "crc32fast"
version = "1.5.3"
@@ -6340,6 +6386,7 @@ dependencies = [
"pollster 1.0.1",
"raw-window-handle",
"rfd",
"rustix 1.1.6",
"serde_json",
"socket2",
"tempfile",
@@ -6386,13 +6433,14 @@ dependencies = [
"serde_json",
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
]
[[package]]
name = "vectorcraft-cad"
version = "0.24.1"
dependencies = [
"craft-dxf",
"image",
"kurbo 0.13.1",
"serde_json",
@@ -6400,8 +6448,8 @@ dependencies = [
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
"vectorcraft-geom",
"vectorcraft-pathops",
"vectorcraft-geom 0.24.1",
"vectorcraft-pathops 0.24.1",
"vectorcraft-text",
]
@@ -6418,7 +6466,7 @@ dependencies = [
"vectorcraft-doc",
"vectorcraft-engine",
"vectorcraft-format",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"vectorcraft-mcp",
"vectorcraft-render",
"vectorcraft-svg",
@@ -6455,7 +6503,7 @@ dependencies = [
"thiserror 2.0.21",
"tiff",
"vectorcraft-color",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"zune-jpeg 0.5.15",
]
@@ -6470,8 +6518,8 @@ dependencies = [
"svgtypes 0.16.1",
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-geom",
"vectorcraft-pathops",
"vectorcraft-geom 0.24.1",
"vectorcraft-pathops 0.24.1",
"vectorcraft-plugins",
"vectorcraft-text",
"vectorcraft-three-d",
@@ -6515,10 +6563,10 @@ dependencies = [
"vectorcraft-doc",
"vectorcraft-eps",
"vectorcraft-format",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"vectorcraft-js",
"vectorcraft-metafile",
"vectorcraft-pathops",
"vectorcraft-pathops 0.24.1",
"vectorcraft-pdf",
"vectorcraft-plugins",
"vectorcraft-render",
@@ -6537,6 +6585,7 @@ dependencies = [
name = "vectorcraft-eps"
version = "0.24.1"
dependencies = [
"craft-eps",
"craft-pdf",
"encoding_rs",
"fax",
@@ -6552,9 +6601,9 @@ dependencies = [
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"vectorcraft-metafile",
"vectorcraft-pathops",
"vectorcraft-pathops 0.24.1",
"vectorcraft-pdf",
"vectorcraft-render",
"vectorcraft-testkit",
@@ -6573,10 +6622,20 @@ dependencies = [
"serde_json",
"thiserror 2.0.21",
"vectorcraft-doc",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"vectorcraft-testkit",
]
[[package]]
name = "vectorcraft-geom"
version = "0.18.0"
source = "git+https://github.com/storytold/vectorcraft.git?rev=6b3a6b8788ebcb420d69449199cbdf323888d27e#6b3a6b8788ebcb420d69449199cbdf323888d27e"
dependencies = [
"kurbo 0.13.1",
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "vectorcraft-geom"
version = "0.24.1"
@@ -6611,7 +6670,7 @@ dependencies = [
"vectorcraft-doc",
"vectorcraft-engine",
"vectorcraft-format",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"vectorcraft-render",
"vectorcraft-svg",
"vectorcraft-testkit",
@@ -6628,10 +6687,21 @@ dependencies = [
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"vectorcraft-text",
]
[[package]]
name = "vectorcraft-pathops"
version = "0.18.0"
source = "git+https://github.com/storytold/vectorcraft.git?rev=6b3a6b8788ebcb420d69449199cbdf323888d27e#6b3a6b8788ebcb420d69449199cbdf323888d27e"
dependencies = [
"kurbo 0.13.1",
"linesweeper",
"thiserror 2.0.21",
"vectorcraft-geom 0.18.0",
]
[[package]]
name = "vectorcraft-pathops"
version = "0.24.1"
@@ -6640,7 +6710,7 @@ dependencies = [
"linesweeper",
"proptest",
"thiserror 2.0.21",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"vectorcraft-testkit",
]
@@ -6673,7 +6743,7 @@ dependencies = [
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"vectorcraft-testkit",
"vectorcraft-text",
"weezl 0.2.1",
@@ -6692,7 +6762,7 @@ dependencies = [
"thiserror 2.0.21",
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"wasmi",
"wat",
"web-time",
@@ -6717,7 +6787,7 @@ dependencies = [
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"vectorcraft-plugins",
"vectorcraft-testkit",
"vectorcraft-text",
@@ -6741,6 +6811,7 @@ name = "vectorcraft-svg"
version = "0.24.1"
dependencies = [
"craft-docpath",
"craft-svg",
"flate2",
"image",
"kurbo 0.13.1",
@@ -6757,8 +6828,8 @@ dependencies = [
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
"vectorcraft-geom",
"vectorcraft-pathops",
"vectorcraft-geom 0.24.1",
"vectorcraft-pathops 0.24.1",
"vectorcraft-testkit",
"vectorcraft-text",
]
@@ -6776,7 +6847,7 @@ dependencies = [
"vectorcraft-doc",
"vectorcraft-engine",
"vectorcraft-format",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"vectorcraft-render",
"vectorcraft-svg",
]
@@ -6796,7 +6867,7 @@ dependencies = [
"unicode-script",
"unicode-segmentation",
"vectorcraft-doc",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"vello_cpu",
"windows-registry",
"write-fonts",
@@ -6806,8 +6877,8 @@ dependencies = [
name = "vectorcraft-three-d"
version = "0.24.1"
dependencies = [
"vectorcraft-geom",
"vectorcraft-pathops",
"vectorcraft-geom 0.24.1",
"vectorcraft-pathops 0.24.1",
]
[[package]]
@@ -6822,8 +6893,8 @@ dependencies = [
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
"vectorcraft-geom",
"vectorcraft-pathops",
"vectorcraft-geom 0.24.1",
"vectorcraft-pathops 0.24.1",
"vectorcraft-text",
]
@@ -6836,7 +6907,7 @@ dependencies = [
"serde",
"serde_json",
"thiserror 2.0.21",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
]
[[package]]
@@ -6865,7 +6936,7 @@ dependencies = [
"vectorcraft-engine",
"vectorcraft-eps",
"vectorcraft-format",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"vectorcraft-pdf",
"vectorcraft-plugins",
"vectorcraft-render",
+6
View File
@@ -25,6 +25,12 @@ craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", re
# craft-update: app-specific pretend versions apply to startup and manual checks.
# Native Affinity documents (craft-libs#914).
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "228f6d0c50f1fdee4c5124603602993fc79d4c9d" }
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2", features = ["tree"] }
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" }
# DXF tags, reader and writer (craft-libs#778, #926, #927).
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", features = ["egui"] }
# internal
vectorcraft-geom = { path = "crates/geom" }
+6
View File
@@ -18,6 +18,8 @@ gate: all six core workflows (path drawing and editing, paint and style, type, l
production, file exchange) work end to end on macOS with save and reopen, and only the last is partial, without
blocking it ([Alpha gate](docs/roadmap.md#alpha-gate)).
> **Gujarati status (2026-11-14, #6613):** 4,673 catalog rows: the original 4,286 remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial, and the pinned CI/release fonts and web startup list contain no Gujarati face; web selection stays unavailable until a Gujarati interface face is bundled. Scores and estimates unchanged.
## Headline numbers
| | Value | Kind |
@@ -96,6 +98,7 @@ Weights, evidence and the missing items per area: [target-app-parity.md](docs/ta
| Simplified Chinese | `zh-hans` | partial (messages in English) | 85% |
| Spanish | `es` | full | 100% |
| Hindi | `hi` | catalog complete; machine-assisted draft, native review pending | complete under the scanner |
| Gujarati | `gu` | 4,673 contributor-reviewed catalog rows; 11 corrections applied to the 387 additions | menus and dialogs; status/error messages partial |
| Arabic | `ar` | none (no right-to-left interface) | 0% |
| French | `fr` | full | 100% |
| Portuguese (Brazil) | `pt-br` | full | 100% |
@@ -218,6 +221,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap
| Date | Change | Summary |
|---|---|---|
| 2026-11-14 | minor | Gujarati (#6613): contributor proofreading completed for all 387 additions, with 11 wording corrections; 4,673 reviewed catalog rows. Status/error messages remain partial; web selection requires a bundled Gujarati face. Scores and estimates unchanged. |
| 2026-11-10 | minor | Tidy-up, no content change: the unheaded change bullets at the top of the file and a revision row inside the headline-numbers table move to this table under their commit dates. Scores and estimates unchanged. |
| 2026-11-10 | minor | Raster effects: Effect Gallery thumbnails and an in-dialog preview (an original drawing through each filter). Features-table Raster effects 85% → 88%, hours 1–2 → none. Headline numbers unchanged, so the progress log is unchanged. |
| 2026-11-05 | minor | Compound Shapes add-on (beyond Illustrator): a menu for Make, Release and Expand Compound Shape and a setting, off by default, that makes the Pathfinder panel's Shape Mode buttons create compound shapes on a click. Scores and estimates unchanged. |
@@ -226,6 +230,8 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap
| 2026-11-03 | minor | UI: Window → Help Bar toggles the tool-help strip separately from the status bar and saves visibility with workspaces. Scores and estimates unchanged. |
| 2026-11-03 | minor | Docked Tools stays between left-side panels and the canvas; redocking accepts canvas and window edges. Requested layout choice; scores and estimates unchanged. |
| 2026-11-02 | minor | Selection QoL: saved marquee modes, screen drag direction with a 3 px dead zone, and translated mode/E feedback (#5313); VectorCraft addition, scores and estimates unchanged. |
| 2026-11-12 | minor | Gujarati (`gu`): reviewed by a native speaker; zero/one singular plurals (CLDR); Gujarati craft-fonts faces join the UI fonts; strings added on main since branching translated (4,286 rows) |
| 2026-11-11 | minor | Gujarati (`gu`): 4,235-row machine-assisted interface catalog, one/other plurals, desktop Gujarati font fallback; messages not yet translated; native review pending |
| 2026-11-06 | minor | Hindi (`hi`): 7,877-row machine-assisted catalog, zero/one singular plurals, desktop font fallback and optional Devanagari craft-fonts fallback; all 55 translation tests pass; native review and a web font remain; scores and estimates unchanged |
| 2026-11-05 | minor | Progress log row for the Type Tools add-on's Release Type on a Path (#5532); headline numbers unchanged. |
| 2026-11-03 | minor | Progress log row for the Type Tools add-on's Text Tweaker (#4924); headline numbers unchanged. |
+4
View File
@@ -110,6 +110,10 @@ wayland-protocols = { version = "0.32", features = ["client", "unstable"] }
# wayland-protocols' `unstable` set) made on the window's own connection. MIT, already in the build
# through winit and rfd.
wayland-backend = { version = "0.3", features = ["client_system"] }
# The Wayland clipboard's pipes (src/clipboard.rs): `poll` and the nonblocking flag give up a read
# or send when the other app moves no data for a while. Apache-2.0 WITH LLVM-exception OR
# Apache-2.0 OR MIT, already in the build through the workspace.
rustix = { workspace = true, features = ["std", "event", "fs"] }
# The save dialog's file type (src/portal_save.rs, #2679): the desktop portal over D-Bus, on the
# systems where rfd shows the portal's dialog. MIT, already in the build through accesskit. Pinned
+185 -43
View File
@@ -1790,15 +1790,17 @@ mod portable {
/// starts a thread for each paste of a Copy's data by another app ([`MAX_SENDS`] at once). Reads
/// run on another worker and take [`MAX_BYTES`] at most; text waits [`LOAD_WAIT`] at most, SVG and
/// PNG as long as a paste's bitmap from arboard. A read that gets no answer in its wait is kept for
/// a paste to wait for off the UI thread, as arboard's are.
/// a paste to wait for off the UI thread, as arboard's are. A read or send whose pipe moves no data
/// for [`IDLE_WAIT`] fails and closes the pipe, which frees its worker or thread.
#[cfg(target_os = "linux")]
mod wayland {
use std::io::{Read, Write};
use std::os::fd::AsFd as _;
use std::io::{ErrorKind, Read, Write};
use std::os::fd::{AsFd, BorrowedFd};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError, mpsc};
use std::time::{Duration, Instant};
use rustix::event::{PollFd, PollFlags, Timespec};
use vectorcraft_engine::cmd::clipboard::names_a_picture;
use vectorcraft_ui_egui::ClipboardRead;
use wayland_client::backend::ObjectData;
@@ -1827,6 +1829,11 @@ mod wayland {
const MAX_SENDS: usize = 8;
/// The most types of an offer that are kept (untrusted data).
const MAX_TYPES: usize = 256;
/// How long a read or send waits for the other app to move a byte through the pipe before it
/// fails, VectorCraft's own limit; the wait starts again after each byte moved.
const IDLE_WAIT: Duration = LOAD_WAIT;
/// The most bytes a read takes from the pipe at a time.
const CHUNK: usize = 64 << 10;
/// What a read gives: the bytes, or why there are none.
type Got = Result<Vec<u8>, String>;
@@ -1898,37 +1905,117 @@ mod wayland {
Some(first)
}
/// `from` read to its end, `cap` bytes at most: more is an error, as is a failed read.
fn read_capped(from: impl Read, cap: usize) -> Got {
let mut data = vec![];
from.take(cap as u64 + 1).read_to_end(&mut data).map_err(|e| format!("couldn't read the clipboard's data: {e}"))?;
if data.len() > cap {
return Err(format!("the clipboard's data is larger than {} MiB", cap >> 20));
/// The time `idle` from now; None when that is past the clock's range (no limit).
fn idle_until(idle: Duration) -> Option<Instant> {
Instant::now().checked_add(idle)
}
/// Makes `fd` nonblocking, its other flags kept.
fn nonblocking(fd: BorrowedFd<'_>) -> std::io::Result<()> {
let flags = rustix::fs::fcntl_getfl(fd)?;
rustix::fs::fcntl_setfl(fd, flags | rustix::fs::OFlags::NONBLOCK)?;
Ok(())
}
/// Waits until `fd` is ready for `events`, closed or failed (true), or `until` passes (false);
/// None waits without a limit. A wait a signal cuts short goes on until `until`.
fn ready(fd: BorrowedFd<'_>, events: PollFlags, until: Option<Instant>) -> std::io::Result<bool> {
loop {
let left = until.map(|t| t.saturating_duration_since(Instant::now()));
let timeout = left.and_then(|d| Timespec::try_from(d).ok());
let mut fds = [PollFd::new(&fd, events)];
match rustix::event::poll(&mut fds, timeout.as_ref()) {
Ok(n) => return Ok(n > 0),
Err(rustix::io::Errno::INTR) => {}
Err(e) => return Err(e.into()),
}
}
Ok(data)
}
/// `from` read to its end, `cap` bytes at most: more is an error, as is a failed read and a
/// pipe that is left open with no byte coming for `idle`. A read that fails gives none of the
/// bytes it took, and closes `from`.
fn read_capped(mut from: impl Read + AsFd, cap: usize, idle: Duration) -> Got {
let failed = |e: std::io::Error| format!("couldn't read the clipboard's data: {e}");
nonblocking(from.as_fd()).map_err(failed)?;
let (mut data, mut chunk) = (vec![], vec![0u8; CHUNK]);
let mut until = idle_until(idle);
loop {
match from.read(&mut chunk) {
Ok(0) => return Ok(data),
Ok(n) => {
let got = chunk.get(..n).ok_or_else(|| failed(ErrorKind::InvalidData.into()))?;
if data.len() + got.len() > cap {
return Err(format!("the clipboard's data is larger than {} MiB", cap >> 20));
}
data.extend_from_slice(got);
until = idle_until(idle);
}
Err(e) if e.kind() == ErrorKind::Interrupted => {}
Err(e) if e.kind() == ErrorKind::WouldBlock => {
if !ready(from.as_fd(), PollFlags::IN, until).map_err(failed)? {
return Err("the app that copied stopped sending the clipboard's data".to_string());
}
}
Err(e) => return Err(failed(e)),
}
}
}
/// `data` written to `to`: an error when the app that pastes closes its end (the process
/// ignores `SIGPIPE`) or takes no byte for `idle`.
fn send(mut to: impl Write + AsFd, data: &[u8], idle: Duration) -> std::io::Result<()> {
nonblocking(to.as_fd())?;
let (mut sent, mut until) = (0, idle_until(idle));
while let Some(rest) = data.get(sent..).filter(|rest| !rest.is_empty()) {
match to.write(rest) {
Ok(0) => return Err(ErrorKind::WriteZero.into()),
Ok(n) => {
sent += n;
until = idle_until(idle);
}
Err(e) if e.kind() == ErrorKind::Interrupted => {}
Err(e) if e.kind() == ErrorKind::WouldBlock => {
if !ready(to.as_fd(), PollFlags::OUT, until)? {
return Err(ErrorKind::TimedOut.into());
}
}
Err(e) => return Err(e),
}
}
Ok(())
}
/// The threads that send a Copy's data to the apps that paste it, counted.
#[derive(Clone, Default)]
struct Sends(Arc<AtomicUsize>);
#[derive(Clone)]
struct Sends {
running: Arc<AtomicUsize>,
/// How long a send waits for the app that pastes to take a byte.
idle: Duration,
}
impl Default for Sends {
fn default() -> Self {
Self { running: Arc::default(), idle: IDLE_WAIT }
}
}
impl Sends {
/// `data` written to `to` on a thread of its own, which then closes `to`; an app that
/// closes its end early ends the write (the process ignores `SIGPIPE`). While
/// [`MAX_SENDS`] are being written `to` is closed at once with nothing written → false.
fn start(&self, mut to: impl Write + Send + 'static, data: Arc<[u8]>) -> bool {
if self.0.fetch_add(1, Ordering::SeqCst) >= MAX_SENDS {
self.0.fetch_sub(1, Ordering::SeqCst);
/// `data` written to `to` on a thread of its own ([`send`]), which then closes `to`; an app
/// that closes its end early or takes no byte for the send's idle wait ends the write.
/// While [`MAX_SENDS`] are being written `to` is closed at once with nothing written → false.
fn start(&self, to: impl Write + AsFd + Send + 'static, data: Arc<[u8]>) -> bool {
if self.running.fetch_add(1, Ordering::SeqCst) >= MAX_SENDS {
self.running.fetch_sub(1, Ordering::SeqCst);
return false;
}
let count = self.0.clone();
let send = move || {
let _ = to.write_all(&data);
drop(to);
let (count, idle) = (self.running.clone(), self.idle);
let work = move || {
let _ = send(to, &data, idle);
count.fetch_sub(1, Ordering::SeqCst);
};
if std::thread::Builder::new().name("wayland-clipboard-send".into()).spawn(send).is_err() {
self.0.fetch_sub(1, Ordering::SeqCst);
if std::thread::Builder::new().name("wayland-clipboard-send".into()).spawn(work).is_err() {
self.running.fetch_sub(1, Ordering::SeqCst);
return false;
}
true
@@ -1937,7 +2024,7 @@ mod wayland {
/// How many are being written.
#[cfg(test)]
fn running(&self) -> usize {
self.0.load(Ordering::SeqCst)
self.running.load(Ordering::SeqCst)
}
}
@@ -2298,7 +2385,7 @@ mod wayland {
impl Receiver {
/// The clipboard's data of type `wire`, read until the app that copied closes the pipe,
/// [`MAX_BYTES`] at most.
/// [`MAX_BYTES`] at most; an error when that app sends no byte for [`IDLE_WAIT`].
fn receive(&self, wire: String) -> Got {
let offer = lock(&self.objects).selection.clone().ok_or("the clipboard is empty")?;
let (from, to) = std::io::pipe().map_err(|e| format!("couldn't open a pipe for the clipboard's data: {e}"))?;
@@ -2307,7 +2394,7 @@ mod wayland {
// holds the only one, and the read ends when that app closes it.
drop(to);
self.conn.flush().map_err(|e| format!("couldn't reach the compositor: {e}"))?;
read_capped(from, MAX_BYTES)
read_capped(from, MAX_BYTES, IDLE_WAIT)
}
}
@@ -2557,31 +2644,86 @@ mod wayland {
assert_eq!(keyboard_serial(&modifiers(9), None), None);
}
/// A wait no test reaches: the other end of each pipe below either moves data or closes.
const LONG: Duration = Duration::from_secs(600);
/// A pipe holding `data`, its write end closed when `close`.
fn pipe_with(data: &[u8], close: bool) -> (std::io::PipeReader, Option<std::io::PipeWriter>) {
let (from, mut to) = std::io::pipe().unwrap();
to.write_all(data).unwrap();
(from, (!close).then_some(to))
}
#[test]
fn a_read_stops_at_its_limit() {
assert_eq!(MAX_BYTES, 64 * 1024 * 1024);
assert_eq!(read_capped(&b"12345678"[..], 8), Ok(b"12345678".to_vec()));
assert_eq!(read_capped(&b""[..], 8), Ok(vec![]));
assert_eq!(read_capped(&[0u8; 9][..], 8), Err("the clipboard's data is larger than 0 MiB".to_string()));
assert_eq!(read_capped(&vec![0u8; (2 << 20) + 1][..], 2 << 20), Err("the clipboard's data is larger than 2 MiB".to_string()));
/// A pipe that breaks.
struct Broken;
impl Read for Broken {
fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
Err(std::io::ErrorKind::BrokenPipe.into())
}
assert_eq!(IDLE_WAIT, LOAD_WAIT);
assert_eq!(read_capped(pipe_with(b"12345678", true).0, 8, Duration::ZERO), Ok(b"12345678".to_vec()));
assert_eq!(read_capped(pipe_with(b"", true).0, 8, Duration::ZERO), Ok(vec![]));
assert_eq!(read_capped(pipe_with(&[0u8; 9], true).0, 8, Duration::ZERO), Err("the clipboard's data is larger than 0 MiB".to_string()));
// More than a pipe holds, from an app that is still sending.
let (from, to) = std::io::pipe().unwrap();
assert!(Sends::default().start(to, vec![0u8; (2 << 20) + 1].into()));
assert_eq!(read_capped(from, 2 << 20, LONG), Err("the clipboard's data is larger than 2 MiB".to_string()));
// A pipe that can't be read: the write end.
let (_, to) = std::io::pipe().unwrap();
let unreadable = std::fs::File::from(std::os::fd::OwnedFd::from(to));
assert!(read_capped(unreadable, 8, LONG).is_err_and(|e| e.starts_with("couldn't read the clipboard's data")));
}
#[test]
fn a_read_from_an_app_that_stops_sending_fails_and_closes_the_pipe() {
let stopped = Err("the app that copied stopped sending the clipboard's data".to_string());
// Some bytes and then nothing, the pipe left open: none of them are pasted.
let (from, to) = pipe_with(b"part", false);
assert_eq!(read_capped(from, MAX_BYTES, Duration::ZERO), stopped);
// The read end is closed, so that app's next write fails.
let mut to = to.unwrap();
assert_eq!(to.write(b"x").map_err(|e| e.kind()), Err(ErrorKind::BrokenPipe));
// Nothing at all, and data that fills the limit exactly with more never coming.
let (from, _held) = pipe_with(b"", false);
assert_eq!(read_capped(from, MAX_BYTES, Duration::ZERO), stopped);
let (from, _held) = pipe_with(b"12345678", false);
assert_eq!(read_capped(from, 8, Duration::ZERO), stopped);
// The next read gets its data.
assert_eq!(read_capped(pipe_with(b"words", true).0, MAX_BYTES, Duration::ZERO), Ok(b"words".to_vec()));
}
#[test]
fn a_send_to_an_app_that_stops_reading_fails_and_frees_its_thread() {
let data: Arc<[u8]> = vec![3u8; 300_000].into();
// More than a pipe holds, to an app that never reads.
let (_held, to) = std::io::pipe().unwrap();
assert_eq!(send(to, &data, Duration::ZERO).map_err(|e| e.kind()), Err(ErrorKind::TimedOut));
// An app that closes its end before reading.
let (from, to) = std::io::pipe().unwrap();
drop(from);
assert_eq!(send(to, &data, LONG).map_err(|e| e.kind()), Err(ErrorKind::BrokenPipe));
// A send thread to an app that does not read until the send gives up, its end still open.
let sends = Sends { idle: Duration::ZERO, ..Sends::default() };
let (from, to) = std::io::pipe().unwrap();
assert!(sends.start(to, data.clone()));
while sends.running() > 0 {
std::thread::yield_now();
}
assert!(read_capped(Broken, 8).is_err_and(|e| e.starts_with("couldn't read the clipboard's data")));
// What the pipe held when the send gave up, then the end of the data: the send closed it.
let got = read_capped(from, MAX_BYTES, Duration::ZERO).map(|d| d.len());
assert!(got.as_ref().is_ok_and(|&n| n > 0 && n < data.len()), "{got:?}");
// The thread is free for the next paste.
let (from, to) = std::io::pipe().unwrap();
assert!(sends.start(to, b"words"[..].into()));
assert_eq!(read_capped(from, MAX_BYTES, LONG), Ok(b"words".to_vec()));
}
#[test]
fn a_copys_data_is_sent_through_the_pipe_and_closed() {
let sends = Sends::default();
assert_eq!(sends.idle, IDLE_WAIT);
let (from, to) = std::io::pipe().unwrap();
let data: Arc<[u8]> = vec![7u8; 300_000].into();
assert!(sends.start(to, data.clone()));
// More than a pipe holds: the write ends once all of it is read, then the pipe closes.
assert_eq!(read_capped(from, MAX_BYTES).as_deref(), Ok(&data[..]));
assert_eq!(read_capped(from, MAX_BYTES, LONG).as_deref(), Ok(&data[..]));
// An app that closes its end before reading ends the send.
let (from, to) = std::io::pipe().unwrap();
drop(from);
@@ -2593,9 +2735,9 @@ mod wayland {
#[test]
fn pastes_that_read_nothing_hold_a_few_sends_at_most() {
let sends = Sends::default();
let sends = Sends { idle: LONG, ..Sends::default() };
let data: Arc<[u8]> = vec![1u8; 300_000].into();
// Apps that ask for the data and never read it.
// Apps that ask for the data and never read it, within the sends' idle wait.
let stalled: Vec<_> = (0..MAX_SENDS)
.map(|_| {
let (from, to) = std::io::pipe().unwrap();
@@ -2606,7 +2748,7 @@ mod wayland {
// The next paste gets its pipe closed at once, with nothing written.
let (from, to) = std::io::pipe().unwrap();
assert!(!sends.start(to, data.clone()));
assert_eq!(read_capped(from, MAX_BYTES), Ok(vec![]));
assert_eq!(read_capped(from, MAX_BYTES, Duration::ZERO), Ok(vec![]));
// Once those apps close their pipes, the sends end and others are sent again.
drop(stalled);
while sends.running() > 0 {
@@ -2614,7 +2756,7 @@ mod wayland {
}
let (from, to) = std::io::pipe().unwrap();
assert!(sends.start(to, data.clone()));
assert_eq!(read_capped(from, MAX_BYTES).map(|d| d.len()), Ok(data.len()));
assert_eq!(read_capped(from, MAX_BYTES, LONG).map(|d| d.len()), Ok(data.len()));
}
/// What a clipboard holds, by type.
+12 -2
View File
@@ -107,7 +107,7 @@ use titlebar::opted_into_system_title_bar;
#[cfg(windows)]
use titlebar::set_taskbar_icon;
#[cfg(all(test, feature = "wgpu"))]
use titlebar::{app_draws_frame, opted_into_app_title_bar, start_frame, system_title_bar_applies};
use titlebar::{app_draws_frame, caption_layout_from, opted_into_app_title_bar, start_frame, system_title_bar_applies};
use titlebar::{custom_titlebar, native_options, titlebar_from_env};
struct App {
@@ -367,17 +367,20 @@ fn main() -> std::process::ExitCode {
};
#[cfg(feature = "wgpu")]
let crash = left_out.crash.clone();
let custom_titlebar = custom_titlebar(saved.as_ref());
let (custom_titlebar, caption_layout) = custom_titlebar(saved.as_ref());
let options = native_options(custom_titlebar);
// winit picks Wayland whenever `WAYLAND_DISPLAY` is set; Preferences › Performance › Linux
// Display Server › X11 opens the window through XWayland instead, where file drops work (#1151),
// and the other choices do so when a pen is attached, where the pen draws (#2028, #4967).
#[cfg(target_os = "linux")]
let mut forced_to_x11 = false;
#[cfg(target_os = "linux")]
let options = {
let mut options = options;
let pref = saved.as_ref().and_then(|ui| ui.engine_prefs.get("linuxDisplayServer")).and_then(serde_json::Value::as_str);
if xwayland::wanted(pref, |name| std::env::var_os(name), xwayland::pen_attached) {
if xwayland::x11_libraries_found() {
forced_to_x11 = true;
if pref != Some("x11") {
log::info!("pen found: opening the window through XWayland, where the pen works (VECTORCRAFT_NATIVE_WAYLAND=1 keeps Wayland)");
} else {
@@ -393,6 +396,11 @@ fn main() -> std::process::ExitCode {
}
options
};
#[cfg(not(target_os = "linux"))]
let forced_to_x11 = false;
// Preferences › User Interface notes under System Title Bar when the desktop draws the frame
// with it on or off.
let desktop_keeps_frame = titlebar::desktop_keeps_frame(forced_to_x11);
// With Windows Ink, winit reports a pen as a touch and drops its barrel button and which end
// is down; the message hook notes each pointer contact and whether it starts with the barrel
// button held, and writes the pen's end into the pen feed (`windows_stylus`). It also notes the
@@ -593,7 +601,9 @@ fn main() -> std::process::ExitCode {
}
app.titlebar_from_env = titlebar_from_env();
app.custom_titlebar = custom_titlebar;
app.caption_layout = caption_layout;
app.desktop_frame = !custom_titlebar;
app.desktop_keeps_frame = desktop_keeps_frame;
if let Some(port) = control_port {
let rx = control_server::start(port, cc.egui_ctx.clone());
app = app.with_control(rx).with_automation_roots(roots.clone());
+61 -6
View File
@@ -220,8 +220,10 @@ fn the_app_title_bar_preference_gives_the_app_frame_on_desktop_frames() {
}
/// The frame a start uses: the preference turns the desktop frame the probe chose into the app frame
/// with the default window buttons, a probed app frame keeps its own buttons, and the desktop frame
/// stays where the app frame is not drawn. System Title Bar takes precedence over the preference.
/// with the default window buttons, an app frame the desktop left to the app keeps its own buttons,
/// one that `VECTORCRAFT_TITLEBAR=app` forced or the preference kept through XWayland gets the
/// default buttons, and the desktop frame stays
/// where the app frame is not drawn. System Title Bar takes precedence over the preference.
#[test]
fn the_start_frame_applies_the_app_title_bar_preference() {
use craft_window::{Button, Frame, Layout};
@@ -233,9 +235,10 @@ fn the_start_frame_applies_the_app_title_bar_preference() {
((Frame::Desktop, None, true, true), Frame::App(Layout::default())),
((Frame::App(gnome.clone()), None, false, false), Frame::App(gnome.clone())),
((Frame::App(gnome.clone()), None, true, false), Frame::Desktop),
((Frame::App(gnome.clone()), None, true, true), Frame::App(gnome.clone())),
((Frame::App(gnome.clone()), None, true, true), Frame::App(Layout::default())),
((Frame::Desktop, Some(false), false, true), Frame::Desktop),
((Frame::App(gnome.clone()), Some(true), true, false), Frame::App(gnome.clone())),
((Frame::App(gnome.clone()), Some(true), true, false), Frame::App(Layout::default())),
((Frame::App(gnome.clone()), Some(true), false, false), Frame::App(Layout::default())),
];
for ((probed, overridden, forced_to_x11, opted_into_app), expected) in cases {
let label = format!("{probed:?} {overridden:?} {forced_to_x11} {opted_into_app}");
@@ -246,6 +249,30 @@ fn the_start_frame_applies_the_app_title_bar_preference() {
assert!(!super::custom_titlebar_from(&both, true), "System Title Bar takes precedence over the app title bar preference");
}
/// The app bar's caption buttons follow the window-button layout of the app frame on Linux and the
/// BSDs (Close alone at the right, or all three at the left with Close outermost); the desktop frame,
/// macOS and Windows keep all three at the right.
#[test]
fn the_caption_buttons_follow_the_frame_layout() {
use craft_window::{Button, Frame, Layout};
use vectorcraft_ui_egui::titlebar::{Caption, CaptionLayout};
let close_only = Layout::parse("appmenu:close");
let at_left = Layout { left: vec![Button::Close, Button::Minimize, Button::Maximize], right: vec![] };
let split = Layout { left: vec![Button::Close], right: vec![Button::Minimize, Button::Maximize] };
let probed = [
(close_only, CaptionLayout { left: vec![], right: vec![Caption::Close] }),
(at_left, CaptionLayout { left: vec![Caption::Close, Caption::Minimize, Caption::Maximize], right: vec![] }),
(split, CaptionLayout { left: vec![Caption::Close], right: vec![Caption::Minimize, Caption::Maximize] }),
];
for (layout, expected) in probed {
let shown = super::caption_layout_from(&Frame::App(layout.clone()));
let expected = if cfg!(any(target_os = "macos", target_os = "windows")) { CaptionLayout::default() } else { expected };
assert_eq!(shown, expected, "{layout:?}");
}
assert_eq!(super::caption_layout_from(&Frame::Desktop), CaptionLayout::default());
assert_eq!(CaptionLayout::default().right, vec![Caption::Minimize, Caption::Maximize, Caption::Close]);
}
/// `VECTORCRAFT_TITLEBAR` chooses the frame for the run it is set in, with System Title Bar off and
/// on. The saved preference still decides while the variable is unset.
#[test]
@@ -303,7 +330,7 @@ fn the_titlebar_variable_decides_the_frame_before_the_window_opens() {
let off = ui_state_with_prefs(serde_json::json!({"systemTitleBar": false}));
let on = ui_state_with_prefs(serde_json::json!({"systemTitleBar": true}));
for (saved, opted_into_system) in [(None, false), (Some(&off), false), (Some(&on), true)] {
let custom = super::custom_titlebar(saved);
let (custom, _) = super::custom_titlebar(saved);
let expected = match value.as_str() {
_ if not_read => !cfg!(target_os = "macos") && !opted_into_system,
"app" => true,
@@ -312,13 +339,41 @@ fn the_titlebar_variable_decides_the_frame_before_the_window_opens() {
// `craft-window` probe decides, the same with System Title Bar off as with no saved
// preferences.
_ if opted_into_system => false,
_ => super::custom_titlebar(None),
_ => super::custom_titlebar(None).0,
};
assert_eq!(custom, expected, "{value}, preference {opted_into_system}");
assert_eq!(super::native_options(custom).viewport.decorations, Some(!custom), "{value}, preference {opted_into_system}");
}
}
/// Preferences says under System Title Bar that the desktop draws the frame with it on or off
/// exactly where the start frame without VectorCraft Title Bar on Every Desktop is the desktop's
/// with System Title Bar off as well as on and `VECTORCRAFT_TITLEBAR` is unset: Linux and the BSDs
/// only.
#[test]
fn the_desktop_keeps_the_frame_where_system_title_bar_does_not_change_it() {
use crate::titlebar::desktop_keeps_frame_from;
use craft_window::{Frame, Layout};
let linux = cfg!(not(any(target_os = "macos", target_os = "windows")));
for probed in [Frame::Desktop, Frame::App(Layout::default())] {
for forced_to_x11 in [false, true] {
let frame = super::start_frame(probed.clone(), None, forced_to_x11, false);
let either_way = !super::custom_titlebar_from(&frame, false) && !super::custom_titlebar_from(&frame, true);
assert_eq!(desktop_keeps_frame_from(&probed, None, forced_to_x11), linux && either_way, "{probed:?} {forced_to_x11}");
}
}
// KDE, Sway and X11, and GNOME through XWayland, keep the desktop's frame; GNOME on Wayland does not.
assert_eq!(desktop_keeps_frame_from(&Frame::Desktop, None, false), linux);
assert_eq!(desktop_keeps_frame_from(&Frame::App(Layout::default()), None, true), linux);
assert!(!desktop_keeps_frame_from(&Frame::App(Layout::default()), None, false));
// While `VECTORCRAFT_TITLEBAR` chooses the frame, System Title Bar does not apply and there is no note.
for (frame, overridden) in [(Frame::App(Layout::default()), Some(true)), (Frame::Desktop, Some(false))] {
for forced_to_x11 in [false, true] {
assert!(!desktop_keeps_frame_from(&frame, overridden, forced_to_x11), "{overridden:?} {forced_to_x11}");
}
}
}
/// The file extensions the macOS bundle declares: its document types and its own exported type.
fn plist_extensions(plist: &str) -> Vec<&str> {
["<key>CFBundleTypeExtensions</key>", "<key>public.filename-extension</key>"]
+56 -9
View File
@@ -31,7 +31,7 @@ pub(crate) fn adapter_summary(info: &eframe::wgpu::AdapterInfo) -> String {
format!("{} ({:?}, {:?})", info.name.trim(), info.backend, info.device_type)
}
/// Windows and Linux: no OS title bar; the app bar is the title bar (`vectorcraft_ui_egui::titlebar`).
/// Windows: no OS title bar; the app bar is the title bar (`vectorcraft_ui_egui::titlebar`).
/// macOS keeps its traffic lights over the integrated title strip.
///
/// Used on macOS and Windows (where VectorCraft keeps today's frame regardless of the
@@ -68,18 +68,45 @@ pub(crate) fn app_draws_frame(probed_app: bool, overridden: Option<bool>, forced
}
/// The frame this start uses, before the System Title Bar preference is applied
/// ([`custom_titlebar_from`]): [`app_draws_frame`] applied to the frame the probe chose. A probed
/// app frame keeps its window-button layout; an app frame the probe did not choose gets the default
/// layout, since `custom_titlebar_from` reads only which frame it is.
/// ([`custom_titlebar_from`]): [`app_draws_frame`] applied to the frame the probe chose. An app frame
/// the desktop left to the app (no `VECTORCRAFT_TITLEBAR` override, not forced onto XWayland) keeps
/// its window-button layout. An app frame turned on by `VECTORCRAFT_TITLEBAR=app` or by VectorCraft
/// Title Bar on Every Desktop gets the default layout: on those desktops the `button-layout` key that `craft-window` reads can
/// hold its schema default (`appmenu:close`) rather than the desktop's own buttons.
pub(crate) fn start_frame(probed: craft_window::Frame, overridden: Option<bool>, forced_to_x11: bool, opted_into_app: bool) -> craft_window::Frame {
let probed_app = matches!(probed, craft_window::Frame::App(_));
match (app_draws_frame(probed_app, overridden, forced_to_x11, opted_into_app), probed) {
(true, frame @ craft_window::Frame::App(_)) => frame,
(true, craft_window::Frame::Desktop) => craft_window::Frame::App(craft_window::Layout::default()),
(true, frame @ craft_window::Frame::App(_)) if overridden.is_none() && !forced_to_x11 => frame,
(true, _) => craft_window::Frame::App(craft_window::Layout::default()),
(false, _) => craft_window::Frame::Desktop,
}
}
/// Where the app bar puts its caption buttons for `frame`: on Linux and the BSDs, the window-button
/// layout of an app frame, which `craft-window` reads from the desktop (the `button-layout` key of
/// `org.gnome.desktop.wm.preferences`); otherwise all three at the right. Each list is copied in the
/// key's order, first item leftmost, so `close,minimize,maximize:` puts Close at the left edge.
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
pub(crate) fn caption_layout_from(frame: &craft_window::Frame) -> vectorcraft_ui_egui::titlebar::CaptionLayout {
use vectorcraft_ui_egui::titlebar::{Caption, CaptionLayout};
let caption = |b: &craft_window::Button| match b {
craft_window::Button::Minimize => Caption::Minimize,
craft_window::Button::Maximize => Caption::Maximize,
craft_window::Button::Close => Caption::Close,
};
match frame.layout() {
Some(layout) => CaptionLayout { left: layout.left.iter().map(caption).collect(), right: layout.right.iter().map(caption).collect() },
None => CaptionLayout::default(),
}
}
/// macOS and Windows: all three caption buttons at the right, whatever the probe says (see
/// [`custom_titlebar_from`]).
#[cfg(any(target_os = "macos", target_os = "windows"))]
pub(crate) fn caption_layout_from(_frame: &craft_window::Frame) -> vectorcraft_ui_egui::titlebar::CaptionLayout {
vectorcraft_ui_egui::titlebar::CaptionLayout::default()
}
/// The `craft-window` probe's answer for this process (its override variable is
/// `VECTORCRAFT_TITLEBAR`). The probe runs once; on a Wayland session it opens a connection.
fn probed_choice() -> &'static craft_window::Choice {
@@ -131,7 +158,8 @@ pub(crate) fn custom_titlebar_from(_frame: &craft_window::Frame, opted_into_syst
CUSTOM_TITLEBAR && !opted_into_system
}
/// Whether this start draws its own title bar. Probes the shared `craft-window` crate once (its
/// Whether this start draws its own title bar, and where its caption buttons go
/// ([`caption_layout_from`]). Probes the shared `craft-window` crate once (its
/// override variable is `VECTORCRAFT_TITLEBAR`) and combines its decision with the saved System
/// Title Bar preference, which does not apply while the variable is set to `app`, `system` or
/// `desktop`. Call once at startup,
@@ -142,7 +170,7 @@ pub(crate) fn custom_titlebar_from(_frame: &craft_window::Frame, opted_into_syst
/// on X11, whose window manager draws the frame — so when XWayland is being forced, keep the native
/// frame, the same as a real X11 session. A recognized `VECTORCRAFT_TITLEBAR` override still wins,
/// and so does VectorCraft Title Bar on Every Desktop ([`app_draws_frame`]).
pub(crate) fn custom_titlebar(saved: Option<&vectorcraft_ui_egui::UiState>) -> bool {
pub(crate) fn custom_titlebar(saved: Option<&vectorcraft_ui_egui::UiState>) -> (bool, vectorcraft_ui_egui::titlebar::CaptionLayout) {
let choice = probed_choice();
let opted_into_system = system_title_bar_applies(opted_into_system_title_bar(saved), titlebar_from_env());
// macOS and Windows never read VectorCraft Title Bar on Every Desktop (`custom_titlebar_from`
@@ -160,7 +188,26 @@ pub(crate) fn custom_titlebar(saved: Option<&vectorcraft_ui_egui::UiState>) -> b
#[cfg(not(target_os = "linux"))]
let forced_to_x11 = false;
let frame = start_frame(choice.frame().clone(), choice.overridden(), forced_to_x11, opted_into_app);
custom_titlebar_from(&frame, opted_into_system)
(custom_titlebar_from(&frame, opted_into_system), caption_layout_from(&frame))
}
/// Whether the desktop would draw this window's frame with System Title Bar on or off while
/// VectorCraft Title Bar on Every Desktop is off: `VECTORCRAFT_TITLEBAR` is not set to `app`,
/// `system` or `desktop` (`overridden` is `None`), and the probe chose
/// [`craft_window::Frame::Desktop`] or the window opens through XWayland (`forced_to_x11`)
/// ([`app_draws_frame`]). The saved VectorCraft Title Bar on Every Desktop is left out, so the value
/// stays `true` on such a desktop while that preference gives the app the frame. Always `false` on
/// macOS and Windows, where System Title Bar decides the frame by itself.
pub(crate) fn desktop_keeps_frame_from(probed: &craft_window::Frame, overridden: Option<bool>, forced_to_x11: bool) -> bool {
let probed_app = matches!(probed, craft_window::Frame::App(_));
cfg!(not(any(target_os = "macos", target_os = "windows"))) && overridden.is_none() && !app_draws_frame(probed_app, None, forced_to_x11, false)
}
/// [`desktop_keeps_frame_from`] for this start's probe, given whether the launch path opens the
/// window through XWayland.
pub(crate) fn desktop_keeps_frame(forced_to_x11: bool) -> bool {
let choice = probed_choice();
desktop_keeps_frame_from(choice.frame(), choice.overridden(), forced_to_x11)
}
pub(crate) fn native_options(custom_titlebar: bool) -> eframe::NativeOptions {
+5 -1
View File
@@ -78,7 +78,11 @@ fn samples(t: &Track, step: Option<f64>) -> Vec<(Point, Vec2, f64)> {
let pieces = (seg / step).ceil().clamp(1.0, MAX_STEPS) as usize;
for k in 1..pieces {
let u = k as f64 / pieces as f64;
out.push((p.lerp(t.verts[i + 1], u), t.dirs[i], (t.cum[i] + seg * u) / len));
let s = t.cum[i] + seg * u;
// On a chord of a flattened curve the samples follow the smooth frame through the
// vertices.
let (q, tg) = if t.curved.get(i).copied().unwrap_or(false) { t.frame_in(i, u) } else { (p.lerp(t.verts[i + 1], u), t.dirs[i]) };
out.push((q, tg, s / len));
}
}
}
+3 -45
View File
@@ -114,51 +114,9 @@ fn strip_brushes(n: &mut Node) {
}
}
/// Mix every solid paint under `n` towards `color` by `amount` (0..1) — the Symbol Stainer.
pub fn tint_node(n: &mut Node, color: &Color, amount: f32) {
let amount = amount.clamp(0.0, 1.0);
for it in &mut n.appearance.items {
let p = match it {
AppearanceItem::Fill(f) => &mut f.paint,
AppearanceItem::Stroke(s) => &mut s.paint,
};
if let Paint::Solid { color: c, .. } = p {
*p = Paint::solid(c.lerp(color, amount));
}
}
if let vectorcraft_doc::NodeKind::Text(t) = &mut n.kind {
for r in &mut t.runs {
for p in [&mut r.style.fill, &mut r.style.stroke] {
if let Paint::Solid { color: c, .. } = p {
*p = Paint::solid(c.lerp(color, amount));
}
}
}
}
if let Some(ch) = n.children_mut() {
for c in ch.iter_mut() {
tint_node(Arc::make_mut(c), color, amount);
}
}
}
/// The stain instance `inst` puts on its symbol's art: its visible fill colour and that fill's
/// opacity (how far the art mixes towards it). `None` for an unstained instance, including one
/// whose fill has an opacity of 0, so its art keeps its paints and their swatch links.
pub fn stain(inst: &Node) -> Option<(Color, f32)> {
let f = inst.appearance.fill().filter(|f| f.visible && f.opacity > 0.0)?;
Some((f.paint.color()?, f.opacity))
}
/// A symbol's art for instance `inst`: with the instance's own appearance changes to it (a dynamic
/// symbol's, [`vectorcraft_doc::symbol_overrides`]), stained by the instance's fill ([`stain`]).
pub fn instance_art(art: &Node, inst: &Node) -> Node {
let mut a = vectorcraft_doc::symbol_overrides::dynamic_art(art, inst);
if let Some((c, amount)) = stain(inst) {
tint_node(&mut a, &c, amount);
}
a
}
/// The Symbol Stainer's mix, an instance's stain and its stained art, from
/// [`vectorcraft_doc::symbol_overrides`], which the effects that reshape an instance also read.
pub use vectorcraft_doc::symbol_overrides::{instance_art, stain, tint_node};
/// The solid colours of the fills and strokes under `nodes`, most used first (then in the order
/// they first appear): the colours Brush Options offers as Hue Shift's key colour, the first being
+49
View File
@@ -1037,6 +1037,26 @@ fn pressed(points: Vec<(f64, f64)>) -> StrokeLayer {
StrokeLayer { pressure: Some(vectorcraft_doc::PressureProfile { points }), ..stroke(1.0) }
}
/// A nib that follows the pen is sampled between the vertices of the flattened path too. Along a
/// curve those samples sit on the curve, and the outline keeps its distance from it.
#[test]
fn pen_driven_nib_outline_follows_the_curve_between_vertices() {
// The top half of a circle of radius 50; a round nib 20 pt across, the same at any pressure.
let (r, half) = (50.0, 10.0);
let c = Point::new(r, r);
let ring = shapes::ellipse(Rect::new(0.0, 0.0, 2.0 * r, 2.0 * r)).to_bezpath();
let half_circle: BezPath = ring.elements().iter().take(3).copied().collect();
let out = stroke_pieces(&Document::new(1.0, 1.0), &pressure_calli(20.0, 0.0), &half_circle, &pressed(vec![(0.0, 0.5), (1.0, 0.5)]));
let mut pts = vec![];
for n in &out {
all_points(n, &mut pts);
}
// Away from the round caps at the two ends, every outline point is `half` from the curve.
let middle = pts.iter().filter(|p| ((p.y - c.y).atan2(p.x - c.x).abs() - std::f64::consts::FRAC_PI_2).abs() <= 1.2);
let worst = middle.map(|p| ((p.distance(c) - (r + half)).abs()).min((p.distance(c) - (r - half)).abs())).fold(0.0, f64::max);
assert!(worst < 0.05, "an outline point strays {worst:.4} pt from the nib's reach");
}
/// #852: with Size on Pressure the nib goes from size − variation at the lightest pressure to
/// size + variation at the heaviest, along the stroke where the pen pressed.
#[test]
@@ -1686,6 +1706,35 @@ fn an_ordinary_stroke_is_unaffected_by_the_budget() {
assert!(anchors(&out) < 2_000_000);
}
/// A straight-sided art brush on a smooth curve draws smooth edges: they do not turn at the smooth
/// anchors the fit puts along them.
#[test]
fn art_brush_edges_stay_smooth_along_a_curve() {
for &(r, w, h, sw) in &[(100.0, 100.0, 10.0, 1.0), (300.0, 100.0, 10.0, 2.0), (30.0, 100.0, 10.0, 1.0), (2000.0, 100.0, 10.0, 1.0)] {
// The top half of a circle, as one open path of two curves.
let ring = shapes::ellipse(Rect::new(0.0, 0.0, 2.0 * r, 2.0 * r)).to_bezpath();
let half_circle: BezPath = ring.elements().iter().take(3).copied().collect();
let out = stroke_pieces(&Document::new(1.0, 1.0), &art_brush(rect_art(w, h), ArtScale::Stretch), &half_circle, &stroke(sw));
let NodeKind::Path { path, .. } = &out[0].kind else { panic!("an art brush on a path draws a path") };
// The turn at each smooth anchor of the edges: the angle between the incoming and the
// outgoing direction. Real corners (the ends of the art) turn by far more than 60°.
let mut kink = 0.0f64;
for sp in &path.subpaths {
for (k, a) in sp.anchors.iter().enumerate().skip(1).take(sp.anchors.len().saturating_sub(2)) {
let h_in = if a.h_in != a.p { a.h_in } else { sp.anchors[k - 1].p };
let h_out = if a.h_out != a.p { a.h_out } else { sp.anchors[k + 1].p };
let (u, v) = (a.p - h_in, h_out - a.p);
if u.hypot() < 1e-9 || v.hypot() < 1e-9 || u.dot(v) < 0.5 * u.hypot() * v.hypot() {
continue;
}
kink = kink.max(u.cross(v).atan2(u.dot(v)).abs().to_degrees());
}
}
assert!(kink < 0.5, "r={r} art={w}x{h} weight {sw}: an edge turns by {kink:.3}° at a smooth anchor");
}
}
/// Anchors under `n`, and how many of them keep a handle (so the segment is a curve).
fn anchors_and_curved(n: &Node) -> (usize, usize) {
let NodeKind::Path { path, .. } = &n.kind else { return (0, 0) };
+346 -35
View File
@@ -1,8 +1,9 @@
//! Arc-length parameterised polylines ("tracks") that brushes lay art along.
//!
//! A track is one flattened subpath. `frame(s)` gives the point and unit tangent at arc length
//! `s`; tangents are blended across the gentle vertices of flattened curves (so warped art bends
//! smoothly) but stay discontinuous at real corners (so art folds there, like Illustrator).
//! `s`. Along a flattened curve the frame runs on a smooth curve through the vertices, so warped
//! art bends smoothly; along a line of the path it stays on the line. At real corners the tangent
//! stays discontinuous, so art folds there.
use vectorcraft_geom::{BezPath, PathEl, Point, Vec2};
@@ -22,6 +23,11 @@ pub struct Track {
pub tangents: Vec<Vec2>,
/// Is the vertex a corner (turn > [`CORNER_DEG`])? Open ends are never corners.
pub corner: Vec<bool>,
/// Does the segment come from flattening a curve (rather than from a line of the path)?
pub curved: Vec<bool>,
/// How far (radians) a curved segment's end tangents may turn from its direction for `frame`
/// to follow a curve through them; 0 for a line.
turn: Vec<f64>,
}
fn unit(v: Vec2) -> Vec2 {
@@ -35,16 +41,53 @@ fn aligned(a: Vec2, b: Vec2) -> bool {
a.dot(b) > 1.0 - 1e-12
}
/// How far a vertex tangent may turn from a chord of a flattened curve, as a multiple of the
/// flattening tolerance over the chord's length. A circular arc needs 4; the rest is slack for
/// flattening that lands a little inside its tolerance.
const TURN_PER_TOL: f64 = 6.0;
/// `t` turned by the smallest angle that brings it within `limit` radians of each `dir`. When no
/// angle satisfies every limit, `t` turns to the middle of the gap between them.
fn held_within(t: Vec2, limits: [Option<(Vec2, f64)>; 2]) -> Vec2 {
let (mut lo, mut hi) = (f64::NEG_INFINITY, f64::INFINITY);
for (d, limit) in limits.into_iter().flatten() {
let to = t.cross(d).atan2(t.dot(d));
lo = lo.max(to - limit);
hi = hi.min(to + limit);
}
let turn = if lo <= hi { 0f64.max(lo).min(hi) } else { (lo + hi) / 2.0 };
if turn == 0.0 || !turn.is_finite() {
return t;
}
let (sin, cos) = turn.sin_cos();
Vec2::new(t.x * cos - t.y * sin, t.x * sin + t.y * cos)
}
/// Left-hand normal in y-down document space (for a path running +x it points +y).
pub fn normal(t: Vec2) -> Vec2 {
Vec2::new(-t.y, t.x)
}
impl Track {
fn new(mut pts: Vec<Point>, closed: bool) -> Option<Track> {
pts.dedup_by(|a, b| a.distance(*b) < 1e-9);
/// `raw` pairs each vertex with the tolerance the segment ending at it was flattened with
/// when it comes from a curve, and `None` when it is a line of the path.
fn new(raw: Vec<(Point, Option<f64>)>, closed: bool) -> Option<Track> {
let mut pts: Vec<Point> = Vec::with_capacity(raw.len());
// `ends_curve[k]`: the flattening tolerance of the segment ending at vertex `k`, when it
// comes from a curve.
let mut ends_curve: Vec<Option<f64>> = Vec::with_capacity(raw.len());
for (p, c) in raw {
// A duplicate vertex adds no segment, so it is dropped with its tolerance.
if pts.last().is_some_and(|q| q.distance(p) < 1e-9) {
continue;
}
pts.push(p);
ends_curve.push(c);
}
let mut closing_curve = None;
if closed && pts.len() > 2 && pts[0].distance(pts[pts.len() - 1]) < 1e-9 {
pts.pop();
closing_curve = ends_curve.pop().flatten();
}
if pts.len() < 2 {
return None;
@@ -52,8 +95,11 @@ impl Track {
let closed = closed && pts.len() > 2;
if closed {
pts.push(pts[0]);
ends_curve.push(closing_curve);
}
let nseg = pts.len() - 1;
let curve_tol: Vec<Option<f64>> = (0..nseg).map(|i| ends_curve.get(i + 1).copied().flatten()).collect();
let curved: Vec<bool> = curve_tol.iter().map(Option::is_some).collect();
let dirs: Vec<Vec2> = (0..nseg).map(|i| unit(pts[i + 1] - pts[i])).collect();
let mut cum = vec![0.0];
for i in 0..nseg {
@@ -62,34 +108,78 @@ impl Track {
let mut tangents = Vec::with_capacity(nseg + 1);
let mut corner = Vec::with_capacity(nseg + 1);
let cos_limit = CORNER_DEG.to_radians().cos();
let seg = |i: usize| (dirs[i], cum[i + 1] - cum[i], curved[i]);
for i in 0..=nseg {
let incoming = if i > 0 {
Some(dirs[i - 1])
Some(seg(i - 1))
} else if closed {
Some(dirs[nseg - 1])
Some(seg(nseg - 1))
} else {
None
};
let outgoing = if i < nseg {
Some(dirs[i])
Some(seg(i))
} else if closed {
Some(dirs[0])
Some(seg(0))
} else {
None
};
match (incoming, outgoing) {
(Some(a), Some(b)) => {
(Some((a, la, ca)), Some((b, lb, cb))) => {
corner.push(a.dot(b) < cos_limit);
tangents.push(unit(a + b));
tangents.push(match (ca, cb) {
// Between two chords of a flattened curve: each direction weighted by the
// length of the other chord, which is the tangent of the circle through
// the vertex and its two neighbors.
(true, true) => unit(a * lb + b * la),
// Where a line of the path meets a curve, the line's direction.
(false, true) => a,
(true, false) => b,
(false, false) => unit(a + b),
});
}
(a, b) => {
// An end of an open track (both `None` only for a track without segments).
corner.push(false);
tangents.push(a.or(b).unwrap_or(Vec2::new(1.0, 0.0)));
tangents.push(a.or(b).map_or(Vec2::new(1.0, 0.0), |(d, _, _)| d));
}
}
}
Some(Track { verts: pts, cum, closed, dirs, tangents, corner })
// An open track's end on a curve continues the bend of its last chord: the tangent there
// is the neighboring vertex's tangent mirrored about the chord, as on the circle through
// the last three vertices.
if !closed && nseg >= 2 {
for (end, inner, d) in [(0, 1, dirs[0]), (nseg, nseg - 1, dirs[nseg - 1])] {
let (s_end, s_inner) = if end == 0 { (0, 1) } else { (nseg - 1, nseg - 2) };
if !corner[inner] && curved[s_end] && curved[s_inner] {
let t = tangents[inner];
tangents[end] = unit(d * (2.0 * d.dot(t)) - t);
}
}
}
// A curve lies within its flattening tolerance `tol` of each of its chords, so its tangent
// at a vertex turns only a little from a chord: at most about `4 * tol / len` on a
// circular arc. Next to a long chord the estimates above can turn much further (a
// straight curve element beside a tight bend), and `frame` would then bow off the chord.
// Between curved chords, each vertex tangent is held within `TURN_PER_TOL * tol / len` of
// both chords. Where a line meets a curve the tangent stays the line's direction, and a
// curved chord whose end tangents turn further than that from it keeps to the chord.
let turn: Vec<f64> = (0..nseg)
.map(|j| match curve_tol.get(j) {
Some(Some(tol)) => (TURN_PER_TOL * tol / (cum[j + 1] - cum[j]).max(1e-12)).min(1.0).asin(),
_ => 0.0,
})
.collect();
for (i, t) in tangents.iter_mut().enumerate() {
let incoming = if i > 0 { Some(i - 1) } else { closed.then_some(nseg - 1) };
let outgoing = if i < nseg { Some(i) } else { closed.then_some(0) };
let sides = [incoming, outgoing];
if corner[i] || sides.iter().flatten().any(|&j| !curved[j]) {
continue;
}
*t = held_within(*t, sides.map(|j| j.map(|j| (dirs[j], turn[j]))));
}
Some(Track { verts: pts, cum, closed, dirs, tangents, corner, curved, turn })
}
pub fn len(&self) -> f64 {
@@ -135,11 +225,11 @@ impl Track {
let n = self.segments();
let s = if self.closed && l > 0.0 { s.rem_euclid(l) } else { s };
if s <= 0.0 && !self.closed {
let t = self.dirs[0];
let t = self.tangents[0];
return (self.verts[0] + t * s, t);
}
if s >= l && !self.closed {
let t = self.dirs[n - 1];
let t = self.tangents[n];
return (self.verts[n] + t * (s - l), t);
}
// Binary search the segment.
@@ -149,10 +239,44 @@ impl Track {
};
let seg = self.cum[i + 1] - self.cum[i];
let u = if seg > 1e-12 { ((s - self.cum[i]) / seg).clamp(0.0, 1.0) } else { 0.0 };
let p = self.verts[i].lerp(self.verts[i + 1], u);
let t0 = if self.corner[i] { self.dirs[i] } else { self.tangents[i] };
let t1 = if self.corner[i + 1] { self.dirs[i] } else { self.tangents[i + 1] };
(p, unit(t0 + (t1 - t0) * u))
self.frame_in(i, u)
}
/// Segment `i`'s direction and the tangents [`Self::frame`] uses at its two ends: the vertex
/// tangents, or the segment's direction at a corner.
fn end_tangents(&self, i: usize) -> Option<(Vec2, Vec2, Vec2)> {
let (&d, &c0, &c1, &t0, &t1) =
(self.dirs.get(i)?, self.corner.get(i)?, self.corner.get(i + 1)?, self.tangents.get(i)?, self.tangents.get(i + 1)?);
Some((d, if c0 { d } else { t0 }, if c1 { d } else { t1 }))
}
/// Point and unit tangent at the fraction `u` (0 to 1) of segment `i`, as [`Self::frame`]
/// gives them. `i` must be below [`Self::segments`].
pub fn frame_in(&self, i: usize, u: f64) -> (Point, Vec2) {
let (Some(&p0), Some(&p1), Some((d, t0, t1))) = (self.verts.get(i), self.verts.get(i + 1), self.end_tangents(i)) else {
return (self.verts.last().copied().unwrap_or(Point::ZERO), Vec2::new(1.0, 0.0));
};
let seg = self.cum.get(i + 1).zip(self.cum.get(i)).map_or(0.0, |(b, a)| b - a);
if aligned(t0, d) && aligned(t1, d) {
return (p0.lerp(p1, u), d);
}
// The tangents may turn this far from a curved chord, a little beyond it for rounding.
let within = self.turn.get(i).map_or(-1.0, |a| a.sin() + 1e-9);
let bends = |t: Vec2| t.dot(d) <= 0.0 || t.cross(d).abs() > within;
if !self.curved.get(i).copied().unwrap_or(false) || bends(t0) || bends(t1) {
// A line of the path, or a curved chord at a sharper turn than the curve can make
// there: the point stays on it, and the tangent turns across it toward the vertex
// tangents.
return (p0.lerp(p1, u), unit(t0 + (t1 - t0) * u));
}
// On a chord of a flattened curve the frame follows the cubic through both vertices with
// their tangents, at the chord's length per unit of `u`. Its position and tangent then
// meet those of the next segment at each vertex.
let (u2, u3) = (u * u, u * u * u);
let (m0, m1) = (t0 * seg, t1 * seg);
let p = p0 + (p1 - p0) * (3.0 * u2 - 2.0 * u3) + m0 * (u3 - 2.0 * u2 + u) + m1 * (u3 - u2);
let dp = (p1 - p0) * (6.0 * u - 6.0 * u2) + m0 * (3.0 * u2 - 4.0 * u + 1.0) + m1 * (3.0 * u2 - 2.0 * u);
(p, unit(dp))
}
/// The point at arc length `s`, offset `d` along the left normal.
@@ -183,8 +307,8 @@ impl Track {
if self.closed && (lo < -1e-9 || hi > l + 1e-9) {
return false;
}
// Past an open track's ends `frame` extrapolates along the end segment's direction, so
// those segments are part of the span too.
// Past an open track's ends `frame` extrapolates along the end tangent, which is checked
// against the end segment's direction below, so those segments are part of the span too.
let ends = [(!self.closed && lo < 0.0).then_some(0), (!self.closed && hi > l).then(|| n - 1)];
let touched = (0..n).filter(|&i| {
let (a, b) = (self.cum.get(i), self.cum.get(i + 1));
@@ -193,9 +317,7 @@ impl Track {
let mut dir: Option<Vec2> = None;
let mut any = false;
for i in touched.chain(ends.into_iter().flatten()) {
let (Some(&d), Some(&t0), Some(&t1), Some(&c0), Some(&c1)) =
(self.dirs.get(i), self.tangents.get(i), self.tangents.get(i + 1), self.corner.get(i), self.corner.get(i + 1))
else {
let Some((d, t0, t1)) = self.end_tangents(i) else {
return false;
};
if dir.is_some_and(|first: Vec2| !aligned(first, d)) {
@@ -203,11 +325,11 @@ impl Track {
}
dir = Some(d);
any = true;
// `frame` blends the two vertex tangents across the segment unless the vertex is a
// corner, where it uses the segment's own direction. So a neighbour outside the span
// can still bend the tangent inside it, and checking the directions alone would miss
// that: segments d, d, e leave vertex 2's tangent at unit(d + e).
if !(c0 || aligned(t0, d)) || !(c1 || aligned(t1, d)) {
// `frame` blends the two end tangents across a line, and follows a curve through them
// on a curved chord. So a neighbour outside the span can still bend the tangent
// inside it, and checking the directions alone would miss that: segments d, d, e
// leave vertex 2's tangent at unit(d + e).
if !aligned(t0, d) || !aligned(t1, d) {
return false;
}
}
@@ -220,9 +342,10 @@ const MAX_FLATTENED: usize = 4_000_000;
/// Flatten `bp` into tracks (one per subpath) with `tol` accuracy.
pub fn tracks(bp: &BezPath, tol: f64) -> Vec<Track> {
let tol = tol.max(1e-4);
let mut out = vec![];
let mut cur: Vec<Point> = vec![];
let flush = |cur: &mut Vec<Point>, closed: bool, out: &mut Vec<Track>| {
let mut cur: Vec<(Point, Option<f64>)> = vec![];
let flush = |cur: &mut Vec<(Point, Option<f64>)>, closed: bool, out: &mut Vec<Track>| {
if let Some(t) = Track::new(std::mem::take(cur), closed) {
out.push(t);
}
@@ -236,19 +359,40 @@ pub fn tracks(bp: &BezPath, tol: f64) -> Vec<Track> {
return out;
}
let mut els = vec![];
// When the element being flattened is a curve, the tolerance `flatten` uses for it: `flatten`
// pulls each element before it reports that element's lines, and raises the tolerance of a
// long curve as `vectorcraft_geom::flatten` describes.
let in_curve = std::cell::Cell::new(None);
let (last, start) = (std::cell::Cell::new(Point::ZERO), std::cell::Cell::new(Point::ZERO));
let source = bp.iter().inspect(|el| {
let from = last.get();
let (curve, to) = match *el {
PathEl::MoveTo(p) => {
start.set(p);
(None, p)
}
PathEl::LineTo(p) => (None, p),
PathEl::QuadTo(a, p) => (Some(from.distance(a) + a.distance(p)), p),
PathEl::CurveTo(a, b, p) => (Some(from.distance(a) + a.distance(b) + b.distance(p)), p),
PathEl::ClosePath => (None, start.get()),
};
last.set(to);
let per = vectorcraft_geom::MAX_FLATTEN_PER_CURVE * vectorcraft_geom::MAX_FLATTEN_PER_CURVE;
in_curve.set(curve.map(|length| if length.is_finite() { tol.max(length / per) } else { f64::INFINITY }));
});
// Guarded: kurbo works out every subdivision of a curve even when the callback drops them.
vectorcraft_geom::flatten(bp.iter(), tol.max(1e-4), |el| {
vectorcraft_geom::flatten(source, tol, |el| {
if els.len() < MAX_FLATTENED {
els.push(el);
els.push((el, in_curve.get()));
}
});
for el in els {
for (el, from_curve) in els {
match el {
PathEl::MoveTo(p) => {
flush(&mut cur, false, &mut out);
cur.push(p);
cur.push((p, None));
}
PathEl::LineTo(p) => cur.push(p),
PathEl::LineTo(p) => cur.push((p, from_curve)),
PathEl::ClosePath => flush(&mut cur, true, &mut out),
_ => {}
}
@@ -368,6 +512,173 @@ mod tests {
assert_eq!(t.map(110.0, 0.0), Point::new(110.0, 0.0));
}
/// Between two lines that meet at a gentle turn, the frame stays on the lines: only the chords
/// of a flattened curve are smoothed. Where a line meets a curve at a gentle turn, the frame
/// stays on the line with the line's direction, and its tangent does not jump at the join.
#[test]
fn a_polylines_frame_stays_on_its_lines() {
// A line, then a line or a nearly straight curve at a 20° turn, below the corner angle, so
// the vertex is not a corner.
let turn = 20f64.to_radians();
let (c, s) = (100.0 * turn.cos(), 100.0 * turn.sin());
for curve in [false, true] {
let mut bp = BezPath::new();
bp.move_to((0.0, 0.0));
bp.line_to((100.0, 0.0));
if curve {
bp.curve_to((100.0 + c / 3.0, s / 3.0 + 0.5), (100.0 + 2.0 * c / 3.0, 2.0 * s / 3.0 + 0.5), (100.0 + c, s));
} else {
bp.line_to((100.0 + c, s));
}
let t = &tracks(&bp, 0.05)[0];
for at in [10.0, 30.0, 50.0, 70.0, 90.0] {
let (p, tg) = t.frame(at);
assert!(p.y.abs() < 1e-9 && (p.x - at).abs() < 1e-9, "curve {curve}: at {at} the frame left the first line: {p:?}");
if curve {
assert!(tg.y.abs() < 1e-12, "at {at} the line's tangent turned toward the curve: {tg:?}");
}
}
if curve {
// The curve's first chord keeps to the chord rather than bending toward the line.
let (a, b) = (t.cum[1], t.cum[2]);
let (p, q) = (t.verts[1], t.verts[2]);
let mid = t.frame((a + b) / 2.0).0;
assert!((mid - p.midpoint(q)).hypot() < 1e-9, "the first curve chord bows: {mid:?}");
}
let (before, after) = (t.frame(100.0 - 1e-7).1, t.frame(100.0 + 1e-7).1);
assert!(before.dot(after) > 1.0 - 1e-9, "curve {curve}: the tangent jumps at the join: {before:?} {after:?}");
}
}
/// A curve of no length between two lines leaves them lines.
#[test]
fn a_curve_of_no_length_leaves_a_line_a_line() {
let turn = 20f64.to_radians();
let mut bp = BezPath::new();
bp.move_to((0.0, 0.0));
bp.line_to((100.0, 0.0));
bp.curve_to((100.0, 0.0), (100.0, 0.0), (100.0, 0.0));
bp.line_to((100.0 + 100.0 * turn.cos(), 100.0 * turn.sin()));
let t = &tracks(&bp, 0.05)[0];
assert!(t.curved.iter().all(|c| !c), "no segment is a curve: {:?}", t.curved);
for at in [10.0, 50.0, 90.0] {
let (p, _) = t.frame(at);
assert!(p.y.abs() < 1e-9 && (p.x - at).abs() < 1e-9, "at {at} the frame left the first line: {p:?}");
}
}
/// Where a line joins a curve smoothly, the line keeps its direction up to the join.
#[test]
fn a_line_into_a_smooth_curve_keeps_its_direction() {
// A line along y = 0 into a quarter circle of radius 50 that starts along +x.
let r = 50.0;
let mut bp = BezPath::new();
bp.move_to((-100.0, 0.0));
bp.line_to((0.0, 0.0));
bp.curve_to((r * K, 0.0), (r, r - r * K), (r, r));
let t = &tracks(&bp, 0.05)[0];
for s in [10.0, 50.0, 90.0, 99.0] {
let (p, tg) = t.frame(s);
assert!(p.y.abs() < 1e-9 && tg.y.abs() < 1e-9, "at {s} the line's frame turned: {p:?} {tg:?}");
}
}
/// The handle length of a cubic quarter circle.
const K: f64 = 0.552_284_749_8;
/// A curve element whose handles lie on its chord is a line drawn as a curve. Next to a tight
/// bend, at either end of a track, the frame along it stays within the flattening tolerance
/// of the line.
#[test]
fn a_straight_curve_element_beside_a_tight_bend_stays_on_its_line() {
let tol = 0.05;
for bend_first in [false, true] {
// A 200 pt line along y = 0 drawn as a cubic, joined smoothly to a quarter circle of
// radius 5 that turns toward +y.
let mut bp = BezPath::new();
if bend_first {
bp.move_to((-5.0, -5.0));
bp.curve_to((-5.0, -5.0 + 5.0 * K), (-5.0 * K, 0.0), (0.0, 0.0));
bp.curve_to((50.0, 0.0), (150.0, 0.0), (200.0, 0.0));
} else {
bp.move_to((0.0, 0.0));
bp.curve_to((50.0, 0.0), (150.0, 0.0), (200.0, 0.0));
bp.curve_to((200.0 + 5.0 * K, 0.0), (205.0, 5.0 - 5.0 * K), (205.0, 5.0));
}
let t = &tracks(&bp, tol)[0];
// The bend lies outside 0 <= x <= 200, so every frame point in that range is on the
// line's stretch of the track.
let on_line: Vec<(Point, Vec2)> =
(0..=2000).map(|k| t.frame(t.len() * k as f64 / 2000.0)).filter(|(p, _)| (0.0..=200.0).contains(&p.x)).collect();
let worst = on_line.iter().map(|(p, _)| p.y.abs()).fold(0.0, f64::max);
assert!(worst <= 2.0 * tol, "bend first {bend_first}: the frame strays {worst:.4} pt off the line");
// Along the line the tangent turns by no more than the line's flattening allows.
let lean = on_line.iter().map(|(_, tg)| tg.y.abs()).fold(0.0, f64::max);
assert!(lean <= 0.01, "bend first {bend_first}: the tangent turns {lean:.4} off the line");
}
}
/// A curve long enough that flattening raises its tolerance still has its frame follow the
/// curve between the vertices, not the chords.
#[test]
fn a_long_curve_flattened_coarser_is_still_followed() {
// A line along y = 0 into a cubic quarter circle of radius 5,000,000 that starts along +x.
let r = 5.0e6;
let curve = kurbo::CubicBez::new((0.0, 0.0), (r * K, 0.0), (r, r - r * K), (r, r));
let mut bp = BezPath::new();
bp.move_to((-100.0, 0.0));
bp.line_to((0.0, 0.0));
bp.curve_to(curve.p1, curve.p2, curve.p3);
let t = &tracks(&bp, 0.05)[0];
let worst = (1..400)
.map(|k| t.frame(100.0 + (t.len() - 100.0) * k as f64 / 400.0).0)
.map(|p| kurbo::ParamCurveNearest::nearest(&curve, p, 1e-9).distance_sq.sqrt())
.fold(0.0, f64::max);
assert!(worst < 0.05, "the frame strays {worst:.4} pt from the curve");
}
/// A closed curve is smooth across its seam: the frame stays on the circle and at right angles
/// to its radius all the way round, the start included.
#[test]
fn a_closed_curves_frame_is_smooth_across_its_seam() {
let (r, tol) = (50.0, 0.05);
let mut bp = BezPath::new();
bp.move_to((r, 0.0));
bp.curve_to((r, r * K), (r * K, r), (0.0, r));
bp.curve_to((-r * K, r), (-r, r * K), (-r, 0.0));
bp.curve_to((-r, -r * K), (-r * K, -r), (0.0, -r));
bp.curve_to((r * K, -r), (r, -r * K), (r, 0.0));
bp.close_path();
let t = &tracks(&bp, tol)[0];
assert!(t.closed && t.curved.iter().all(|c| *c), "every chord of the circle is a chord of a curve");
for k in -20..=20 {
let (p, tg) = t.frame(k as f64 * 0.37);
let radial = p.to_vec2() / p.to_vec2().hypot();
assert!((p.to_vec2().hypot() - r).abs() <= tol, "at {k} the frame is off the circle: {p:?}");
assert!(tg.dot(radial).abs() < 0.5f64.to_radians().sin(), "at {k} the tangent leans off the circle: {tg:?}");
}
}
/// A closed path whose last side is the implicit line back to the start keeps that line
/// straight.
#[test]
fn an_implicit_closing_line_is_not_a_curve() {
let r = 50.0;
let mut bp = BezPath::new();
bp.move_to((r, 0.0));
bp.curve_to((r, r * K), (r * K, r), (0.0, r));
bp.curve_to((-r * K, r), (-r, r * K), (-r, 0.0));
bp.close_path();
let t = &tracks(&bp, 0.05)[0];
assert!(t.closed);
assert_eq!(t.curved.last(), Some(&false), "the closing line is a line");
let n = t.segments();
for u in [0.1, 0.5, 0.9] {
let (p, _) = t.frame(t.cum[n - 1] + (t.cum[n] - t.cum[n - 1]) * u);
assert!(p.y.abs() < 1e-9, "the frame leaves the closing line: {p:?}");
}
}
#[test]
fn closed_square_has_four_corners() {
let mut bp = BezPath::new();
+1
View File
@@ -9,6 +9,7 @@ description = "VectorCraft CAD interchange: a hand-written ASCII DXF writer (R12
workspace = true
[dependencies]
craft-dxf = { workspace = true }
vectorcraft-geom = { workspace = true }
vectorcraft-color = { workspace = true }
vectorcraft-doc = { workspace = true }
+4 -67
View File
@@ -1,50 +1,11 @@
//! The 256-colour index palette CAD apps share, generated rather than tabulated: indices 1–9 are
//! the standard colours, 10–249 run through 24 hues at five brightnesses each in a full and a
//! half-saturated tone, and 250–255 are greys.
//! The colour index palette is `craft_dxf::model::aci`; here are the indices each colour depth
//! of the writer may use.
use crate::ColorDepth;
/// The nine standard colours (index 7 shows white on a dark background and black on paper).
const STANDARD: [[u8; 3]; 9] =
[[255, 0, 0], [255, 255, 0], [0, 255, 0], [0, 255, 255], [0, 0, 255], [255, 0, 255], [255, 255, 255], [128, 128, 128], [192, 192, 192]];
/// The brightness of the five shades of each hue.
const SHADES: [f64; 5] = [1.0, 0.65, 0.5, 0.3, 0.15];
/// The RGB of colour index `i` (1–255; anything else is index 7's white).
pub fn aci_rgb(i: u8) -> [u8; 3] {
match i {
1..=9 => STANDARD[usize::from(i - 1)],
10..=249 => {
let hue = f64::from(i / 10 - 1) * 15.0;
let k = i % 10;
let v = SHADES[usize::from(k / 2)];
let pastel = k % 2 == 1;
hue_rgb(hue).map(|f| {
let f = if pastel { f + (1.0 - f) / 2.0 } else { f };
(255.0 * v * f).floor() as u8
})
}
250..=255 => {
let g = (51.0 + 204.0 * f64::from(i - 250) / 5.0).floor() as u8;
[g; 3]
}
_ => STANDARD[6],
}
}
/// The fully saturated, full-brightness colour of `hue` degrees as 0–1 channels.
fn hue_rgb(hue: f64) -> [f64; 3] {
let h = hue.rem_euclid(360.0) / 60.0;
let x = 1.0 - (h % 2.0 - 1.0).abs();
match h as u8 {
0 => [1.0, x, 0.0],
1 => [x, 1.0, 0.0],
2 => [0.0, 1.0, x],
3 => [0.0, x, 1.0],
4 => [x, 0.0, 1.0],
_ => [1.0, 0.0, x],
}
craft_dxf::model::aci::rgb(i)
}
/// The indices a colour depth may use (true colour: all of them, for the fallback index).
@@ -59,37 +20,13 @@ fn candidates(depth: ColorDepth) -> Box<dyn Iterator<Item = u8>> {
/// The index of `depth` nearest to `rgb` (squared RGB distance; ties go to the lower index).
/// Index 7 stands for both white and black, as CAD apps draw it in the background's contrast.
pub fn nearest_aci(rgb: [u8; 3], depth: ColorDepth) -> u8 {
let dist = |c: [u8; 3]| rgb.iter().zip(c).map(|(a, b)| (i32::from(*a) - i32::from(b)).pow(2)).sum::<i32>();
candidates(depth).min_by_key(|i| if *i == 7 { dist([255; 3]).min(dist([0; 3])) } else { dist(aci_rgb(*i)) }).unwrap_or(7)
craft_dxf::model::aci::nearest(rgb, candidates(depth))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_palette_matches_its_known_entries() {
let known: [(u8, [u8; 3]); 14] = [
(1, [255, 0, 0]),
(10, [255, 0, 0]),
(11, [255, 127, 127]),
(12, [165, 0, 0]),
(13, [165, 82, 82]),
(17, [76, 38, 38]),
(19, [38, 19, 19]),
(20, [255, 63, 0]),
(21, [255, 159, 127]),
(30, [255, 127, 0]),
(140, [0, 191, 255]),
(250, [51, 51, 51]),
(252, [132, 132, 132]),
(255, [255, 255, 255]),
];
for (i, rgb) in known {
assert_eq!(aci_rgb(i), rgb, "index {i}");
}
}
#[test]
fn nearest_index_by_depth() {
assert_eq!(nearest_aci([255, 0, 0], ColorDepth::Aci8), 1);
+20 -19
View File
@@ -1,4 +1,4 @@
//! DXF import: an ASCII DXF drawing of any version as a document.
//! DXF import: a DXF drawing (ASCII or binary) of any version as a document.
//!
//! 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
@@ -10,7 +10,8 @@
//! lineweights, linetypes and transparency come through layers and blocks as CAD apps resolve
//! them. What can't come in is listed in the warnings.
//!
//! - `reader`: the file's text, group codes, sections, tables, blocks and layouts.
//! - `reader`: what the import uses of the drawing `craft_dxf::model` reads: header, tables,
//! blocks and layouts.
//! - `entity`: entities to items (geometry and properties).
//! - `curve`: bulges, arcs, ellipses and NURBS as Bézier paths.
//! - `text`: text values to plain text.
@@ -31,9 +32,6 @@ use crate::{DxfVersion, INSUNITS, SCALE_RANGE};
/// Letter, the box Fit to Artboard fills unless told otherwise (points).
pub const FIT_TO: (f64, f64) = (612.0, 792.0);
/// Why a binary DXF can't be opened.
pub const BINARY: &str = "this is a binary DXF file, which can't be read: save it from the CAD app as an ASCII DXF and open that";
/// How a drawing comes in.
#[derive(Clone, Debug, PartialEq)]
pub struct ImportOptions {
@@ -104,15 +102,20 @@ pub fn is_dxf(bytes: &[u8]) -> bool {
false
}
/// The pairs of a DXF file and where it is damaged (binary and DWG files are refused).
fn text(bytes: &[u8]) -> Result<std::borrow::Cow<'_, str>, String> {
if bytes.starts_with(reader::BINARY_SENTINEL) {
return Err(BINARY.into());
}
/// 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 an ASCII DXF and open that".into());
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());
}
Ok(reader::decode(bytes))
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(),
_ => "not a DXF drawing".to_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"))))
}
/// The unit of `$INSUNITS` code `code` and the scale that shows the drawing 1:1 in it.
@@ -161,9 +164,8 @@ fn units_name(code: i64) -> &'static str {
/// Read what `bytes` holds: its version, units, layouts and layers.
pub fn info(bytes: &[u8]) -> Result<DxfInfo, String> {
let text = text(bytes)?;
let (pairs, _) = reader::pairs(&text)?;
let d = reader::Drawing::read(&pairs);
let (tags, _) = tags(bytes)?;
let d = reader::Drawing::read(craft_dxf::model::Document::read(&tags));
if d.sections == 0 {
return Err("not a DXF drawing".into());
}
@@ -180,7 +182,7 @@ pub fn info(bytes: &[u8]) -> Result<DxfInfo, String> {
})
}
/// Import an ASCII DXF drawing with `o`.
/// Import a DXF 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) {
@@ -191,9 +193,8 @@ 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 text = text(bytes)?;
let (pairs, damaged) = reader::pairs(&text)?;
let d = reader::Drawing::read(&pairs);
let (tags, damaged) = tags(bytes)?;
let d = reader::Drawing::read(craft_dxf::model::Document::read(&tags));
if d.sections == 0 {
return Err("not a DXF drawing".into());
}
+180 -302
View File
@@ -7,9 +7,10 @@ use kurbo::{BezPath, PathEl};
use vectorcraft_doc::Justify;
use vectorcraft_geom::{Affine, Point, Vec2};
use craft_dxf::model::{self, EntityRecord, Groups, HatchEdge, HatchPath};
use super::curve::{self, Vertex};
use super::reader::{Groups, Pair, Record, groups, number};
use crate::aci::aci_rgb;
use super::reader::{aci_paper, point};
/// How far below the baseline the lowest descender reaches, as a fraction of the cap height.
const DESCENT: f64 = 0.3;
@@ -25,21 +26,6 @@ const MAX_COORD: f64 = 1e12;
/// factor 1, the 1 to 10,000% horizontal scale the Character panel allows.
const SPAN_SCALE: (f64, f64) = (0.01, 100.0);
/// The colour of index `i` on paper: index 7 (white on a CAD screen) is black.
pub(crate) fn aci_paper(i: u64) -> [u8; 3] {
match u8::try_from(i) {
Ok(7) | Err(_) => [0; 3],
Ok(i) => aci_rgb(i),
}
}
/// The true colour (group 420, `0xRRGGBB`) of an entity or layer.
pub(crate) fn true_color(g: &[Pair<'_>]) -> Option<[u8; 3]> {
let v = g.int(420)?;
let [_, r, gr, b] = u32::try_from(v & 0xFF_FFFF).ok()?.to_be_bytes();
Some([r, gr, b])
}
/// An entity's colour.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) enum Col {
@@ -79,30 +65,30 @@ pub(crate) struct Props {
}
impl Props {
fn read(g: &[Pair<'_>]) -> Self {
let color = match (true_color(g), g.int(62)) {
(Some(rgb), _) => Col::Rgb(rgb),
(None, Some(0)) => Col::ByBlock,
(None, None | Some(256..)) => Col::ByLayer,
(None, Some(i)) => Col::Rgb(aci_paper(i.unsigned_abs())),
fn read(c: &model::Common) -> Self {
let color = match c.color {
model::Color::Rgb(rgb) => Col::Rgb(rgb),
model::Color::ByBlock => Col::ByBlock,
model::Color::ByLayer => Col::ByLayer,
model::Color::Index(i) => Col::Rgb(aci_paper(i)),
};
let lineweight = match g.int(370) {
Some(-2) => Lw::ByBlock,
Some(-3) => Lw::Default,
Some(v @ 0..=211) => Lw::Hundredths(v as i32),
let lineweight = match c.lineweight {
model::Lineweight::ByBlock => Lw::ByBlock,
model::Lineweight::Default => Lw::Default,
model::Lineweight::Hundredths(v @ 0..=211) => Lw::Hundredths(i32::from(v)),
_ => Lw::ByLayer,
};
let alpha = match g.int(440) {
Some(v) if v & 0x0200_0000 != 0 => Alpha::Opacity((v & 0xFF) as f32 / 255.0),
Some(v) if v & 0x0100_0000 != 0 => Alpha::ByBlock,
_ => Alpha::ByLayer,
let alpha = match c.transparency {
model::Transparency::Alpha(a) => Alpha::Opacity(f32::from(a) / 255.0),
model::Transparency::ByBlock => Alpha::ByBlock,
model::Transparency::ByLayer => Alpha::ByLayer,
};
Self {
layer: g.name(8).unwrap_or("0").to_string(),
layer: c.layer.clone(),
color,
lineweight,
linetype: g.name(6).unwrap_or("BYLAYER").to_uppercase(),
ltscale: g.num(48).filter(|v| *v > 0.0).unwrap_or(1.0),
linetype: c.linetype.as_deref().unwrap_or("BYLAYER").to_uppercase(),
ltscale: c.ltscale,
alpha,
}
}
@@ -209,90 +195,87 @@ impl Converter {
}
/// The items of `records` (an entity section or a block), in drawing order.
pub fn items(&mut self, records: &[Record<'_>]) -> Vec<Item> {
pub fn items(&mut self, records: &[EntityRecord<'_>]) -> Vec<Item> {
let mut out = Vec::new();
for group in groups(records) {
let Some(head) = group.first() else { continue };
for e in records {
let m = model::Entity::read(e);
// Invisible entities.
if head.g.int(60) == Some(1) {
if !m.common.visible {
continue;
}
match self.geom(head, group) {
match self.geom(e, &m) {
Some(geom) if !in_range(&geom) => self.warn(FAR_AWAY),
Some(geom) => out.push(Item { props: Props::read(head.g), geom }),
None if is_known(head.kind) => {}
None => self.skip(head.kind),
Some(geom) => out.push(Item { props: Props::read(&m.common), geom }),
None if is_known(e.kind) => {}
None => self.skip(e.kind),
}
}
out
}
fn geom(&mut self, head: &Record<'_>, group: &[Record<'_>]) -> Option<Geom> {
let g = head.g;
fn geom(&mut self, e: &EntityRecord<'_>, m: &model::Entity) -> Option<Geom> {
let g = e.groups();
let path = |bp: BezPath| Some(Geom::Path { bp, fill: false, width: 0.0 });
match head.kind {
"LINE" => {
let ocs = ocs(m.common.extrusion);
match &m.kind {
model::EntityKind::Line { start, end } => {
let mut bp = BezPath::new();
bp.move_to(g.point(10));
bp.line_to(g.point(11));
bp.move_to(point(*start));
bp.line_to(point(*end));
path(bp)
}
"CIRCLE" => path(transformed(curve::arc(g.point(10), g.num(40)?, 0.0, std::f64::consts::TAU)?, ocs(g))),
"ARC" => {
let (start, end) = (g.num_or(50, 0.0), g.num_or(51, 360.0));
let sweep = ccw_sweep(start, end);
path(transformed(curve::arc(g.point(10), g.num(40)?, start.to_radians(), sweep.to_radians())?, ocs(g)))
model::EntityKind::Circle { center, radius } => path(transformed(curve::arc(point(*center), *radius, 0.0, std::f64::consts::TAU)?, ocs)),
model::EntityKind::Arc { center, radius, start_angle, end_angle } => {
let sweep = ccw_sweep(*start_angle, *end_angle);
path(transformed(curve::arc(point(*center), *radius, start_angle.to_radians(), sweep.to_radians())?, ocs))
}
"ELLIPSE" => path(ellipse(g)?),
"LWPOLYLINE" => lwpolyline(g),
"POLYLINE" => self.polyline(g, group.get(1..).unwrap_or(&[])),
"SPLINE" => path(spline(g)?),
"SOLID" | "TRACE" => {
let [a, b, c, d] = [g.point(10), g.point(11), g.point(12), g.point_opt(13).unwrap_or(g.point(12))];
model::EntityKind::Ellipse { center, major, ratio, start, end } => {
path(ellipse(m.common.extrusion, *center, *major, *ratio, *start, *end)?)
}
model::EntityKind::LwPolyline(p) => lwpolyline(p, ocs),
model::EntityKind::Polyline(p) => self.polyline(p, ocs),
model::EntityKind::Spline(s) => path(spline(s)?),
model::EntityKind::Solid { corners } | model::EntityKind::Trace { corners } => {
let [a, b, c, d] = corners.map(point);
// The corners zigzag: the outline runs 1, 2, 4, 3.
Some(Geom::Path { bp: transformed(polygon(&[a, b, d, c]), ocs(g)), fill: true, width: 0.0 })
Some(Geom::Path { bp: transformed(polygon(&[a, b, d, c]), ocs), fill: true, width: 0.0 })
}
"3DFACE" => {
let [a, b, c, d] = [g.point(10), g.point(11), g.point(12), g.point_opt(13).unwrap_or(g.point(12))];
path(polygon(&[a, b, c, d]))
}
"HATCH" => self.hatch(g),
"TEXT" | "ATTRIB" => text(g, head.kind == "ATTRIB").map(Geom::Text),
"MTEXT" => mtext(g).map(Geom::Text),
"INSERT" => self.insert(g, group.get(1..).unwrap_or(&[])),
model::EntityKind::Face3d { corners, .. } => path(polygon(&corners.map(point))),
model::EntityKind::Hatch(h) => self.hatch(h, ocs),
model::EntityKind::Text(t) => text(t, &g, false, ocs).map(Geom::Text),
model::EntityKind::MText(t) => mtext(t, e.tags).map(Geom::Text),
model::EntityKind::Insert(ins) => self.insert(ins, &e.followers, ocs),
// A dimension draws the anonymous block of its lines, arrows and text.
"DIMENSION" => Some(Geom::Insert(InsertItem { block: g.name(2)?.to_uppercase(), cells: vec![Affine::IDENTITY], attribs: vec![] })),
model::EntityKind::Dimension(d) => {
Some(Geom::Insert(InsertItem { block: d.block.as_ref()?.to_uppercase(), cells: vec![Affine::IDENTITY], attribs: vec![] }))
}
_ => None,
}
}
fn polyline(&mut self, g: &[Pair<'_>], rest: &[Record<'_>]) -> Option<Geom> {
let flags = g.int_or(70, 0);
if flags & (16 | 64) != 0 {
fn polyline(&mut self, p: &model::Polyline, ocs: Affine) -> Option<Geom> {
if p.is_mesh() || p.is_polyface() {
self.warn(MESHES);
return None;
}
// Spline frame control points and polyface faces aren't on the line.
let verts: Vec<Vertex> = rest
.iter()
.filter(|r| r.kind == "VERTEX" && r.g.int_or(70, 0) & (16 | 128) == 0)
.map(|r| Vertex { p: r.g.point(10), bulge: r.g.num_or(42, 0.0) })
.collect();
let bp = curve::polyline(&verts, flags & 1 != 0)?;
let verts: Vec<Vertex> =
p.vertices.iter().filter(|v| v.flags & (16 | 128) == 0).map(|v| Vertex { p: point(v.location), bulge: v.bulge }).collect();
let bp = curve::polyline(&verts, p.closed())?;
// 3D polylines are in world coordinates; 2D ones in their plane's.
let bp = if flags & 8 != 0 { bp } else { transformed(bp, ocs(g)) };
Some(Geom::Path { bp, fill: false, width: g.num_or(40, 0.0).max(0.0) })
let bp = if p.is_3d() { bp } else { transformed(bp, ocs) };
Some(Geom::Path { bp, fill: false, width: p.start_width.max(0.0) })
}
fn insert(&mut self, g: &[Pair<'_>], rest: &[Record<'_>]) -> Option<Geom> {
let block = g.name(2)?.to_uppercase();
let (sx, sy) = (g.num_or(41, 1.0), g.num_or(42, 1.0));
fn insert(&mut self, ins: &model::Insert, followers: &[model::Record<'_>], ocs: Affine) -> Option<Geom> {
let block = Some(ins.block.trim()).filter(|b| !b.is_empty())?.to_uppercase();
let [sx, sy, _] = ins.scale;
if sx.abs() < 1e-12 || sy.abs() < 1e-12 {
return None;
}
let place = ocs(g) * Affine::translate(g.point(10).to_vec2()) * Affine::rotate(g.num_or(50, 0.0).to_radians());
let (cols, rows) = (g.int_or(70, 1).max(1), g.int_or(71, 1).max(1));
let (cs, rs) = (g.num_or(44, 0.0), g.num_or(45, 0.0));
let place = ocs * Affine::translate(point(ins.insert).to_vec2()) * Affine::rotate(ins.rotation.to_radians());
let (cols, rows) = (ins.columns, ins.rows);
let (cs, rs) = (ins.column_spacing, ins.row_spacing);
let (cols, rows) = if cols.saturating_mul(rows) > MAX_CELLS {
self.warn(BIG_ARRAY);
(cols.min(MAX_CELLS), (MAX_CELLS / cols.min(MAX_CELLS)).max(1).min(rows))
@@ -312,27 +295,41 @@ impl Converter {
.flat_map(|r| (0..cols).map(move |c| (r, c)))
.map(|(r, c)| place * Affine::translate((c as f64 * cs, r as f64 * rs)) * Affine::scale_non_uniform(sx, sy))
.collect();
let attribs = self.items(rest);
let attribs = self.attribs(followers);
Some(Geom::Insert(InsertItem { block, cells, attribs }))
}
fn hatch(&mut self, g: &[Pair<'_>]) -> Option<Geom> {
let start = g.iter().position(|p| p.code == 91)?;
let count = g.get(start).and_then(|p| number(p.value)).filter(|n| *n >= 0.0)? as usize;
let mut c = Cursor { g, i: start + 1 };
/// An insert's attributes as text.
fn attribs(&mut self, followers: &[model::Record<'_>]) -> Vec<Item> {
let mut out = Vec::new();
for r in followers {
let c = model::Common::read(r.tags);
if !c.visible {
continue;
}
let a = model::Attrib::read("ATTRIB", r.tags);
match text(&a.text, &r.groups(), true, ocs(c.extrusion)) {
Some(t) if !in_range(&Geom::Text(t.clone())) => self.warn(FAR_AWAY),
Some(t) => out.push(Item { props: Props::read(&c), geom: Geom::Text(t) }),
None => {}
}
}
out
}
fn hatch(&mut self, h: &model::Hatch, ocs: Affine) -> Option<Geom> {
let mut bp = BezPath::new();
for _ in 0..count {
let Some(path) = boundary(&mut c) else { break };
for l in &h.loops {
let Some(path) = boundary(&l.path) else { break };
bp.extend(path);
}
if bp.elements().is_empty() {
return None;
}
let bp = transformed(bp, ocs(g));
let solid = g.int_or(70, 0) == 1;
if g.int_or(450, 0) == 1 {
let bp = transformed(bp, ocs);
if h.gradient.is_some() {
self.warn(GRADIENT_HATCH);
} else if !solid {
} else if !h.solid {
self.warn(PATTERN_HATCH);
return Some(Geom::Path { bp, fill: false, width: 0.0 });
}
@@ -401,217 +398,104 @@ fn polygon(pts: &[Point]) -> BezPath {
bp
}
/// The extrusion direction (210, 220, 230) of a planar entity, normalised.
fn extrusion(g: &[Pair<'_>]) -> [f64; 3] {
let n = [g.num_or(210, 0.0), g.num_or(220, 0.0), g.num_or(230, 1.0)];
let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt();
if len > 1e-12 && len.is_finite() { n.map(|v| v / len) } else { [0.0, 0.0, 1.0] }
}
fn cross(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
[a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
}
fn unit(v: [f64; 3]) -> [f64; 3] {
let len = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
if len > 1e-12 { v.map(|x| x / len) } else { v }
}
/// A planar entity's coordinate system seen from above: its x and y axes in world space by the
/// arbitrary axis algorithm (identity for drawings in the world's plane; extruded along −z it
/// mirrors x).
fn ocs(g: &[Pair<'_>]) -> Affine {
let n = extrusion(g);
if n[2] > 1.0 - 1e-12 {
fn ocs(extrusion: model::Point) -> Affine {
let [ax, ay, _] = model::ocs_axes(extrusion);
if ax == [1.0, 0.0, 0.0] && ay == [0.0, 1.0, 0.0] {
return Affine::IDENTITY;
}
let ax = unit(if n[0].abs() < 1.0 / 64.0 && n[1].abs() < 1.0 / 64.0 { cross([0.0, 1.0, 0.0], n) } else { cross([0.0, 0.0, 1.0], n) });
let ay = unit(cross(n, ax));
Affine::new([ax[0], ax[1], ay[0], ay[1], 0.0, 0.0])
}
fn ellipse(g: &[Pair<'_>]) -> Option<BezPath> {
let centre = g.point(10);
let major = g.point(11).to_vec2();
let ratio = g.num_or(40, 1.0);
fn ellipse(extrusion: model::Point, centre: model::Point, major: model::Point, ratio: f64, start: f64, end: f64) -> Option<BezPath> {
let centre = point(centre);
let major = point(major).to_vec2();
if ratio <= 0.0 || major.hypot() < 1e-12 {
return None;
}
// The minor axis is the major one turned a quarter about the extrusion direction.
let n = extrusion(g);
let n = model::ocs_axes(extrusion)[2];
let m = cross(n, [major.x, major.y, 0.0]);
let minor = Vec2::new(m[0], m[1]) * ratio;
let (start, end) = (g.num_or(41, 0.0), g.num_or(42, std::f64::consts::TAU));
let sweep = ccw_sweep(start.to_degrees(), end.to_degrees()).to_radians();
curve::ellipse(Affine::new([major.x, major.y, minor.x, minor.y, centre.x, centre.y]), start, sweep)
}
fn lwpolyline(g: &[Pair<'_>]) -> Option<Geom> {
let mut verts: Vec<Vertex> = Vec::new();
let (mut widths, mut uniform) = (None, true);
for p in g {
match p.code {
10 => verts.push(Vertex { p: Point::new(number(p.value)?, 0.0), bulge: 0.0 }),
20 => verts.last_mut()?.p.y = number(p.value)?,
42 => verts.last_mut()?.bulge = number(p.value).unwrap_or(0.0),
40 | 41 => {
let w = number(p.value).unwrap_or(0.0);
uniform &= widths.is_none_or(|x: f64| (x - w).abs() < 1e-12);
widths = Some(w);
}
_ => {}
}
}
let bp = transformed(curve::polyline(&verts, g.int_or(70, 0) & 1 != 0)?, ocs(g));
let width = g.num(43).filter(|w| *w > 0.0).or(widths.filter(|_| uniform)).unwrap_or(0.0).max(0.0);
fn lwpolyline(p: &model::LwPolyline, ocs: Affine) -> Option<Geom> {
let verts: Vec<Vertex> = p.vertices.iter().map(|v| Vertex { p: Point::new(v.x, v.y), bulge: v.bulge }).collect();
let bp = transformed(curve::polyline(&verts, p.closed)?, ocs);
// One width for every vertex is the line's width.
let widths: Vec<f64> = p.vertices.iter().flat_map(|v| [v.start_width, v.end_width]).collect();
let uniform = widths.first().filter(|w| widths.iter().all(|x| (x - *w).abs() < 1e-12)).copied();
let width = Some(p.const_width).filter(|w| *w > 0.0).or(uniform).unwrap_or(0.0).max(0.0);
Some(Geom::Path { bp, fill: false, width })
}
/// The points at `code` (x) and `code + 10` (y), in order.
fn points(g: &[Pair<'_>], code: i32) -> Option<Vec<Point>> {
let mut out: Vec<Point> = Vec::new();
for p in g {
if p.code == code {
out.push(Point::new(number(p.value)?, 0.0));
} else if p.code == code + 10 {
out.last_mut()?.y = number(p.value)?;
}
}
Some(out)
}
fn spline(g: &[Pair<'_>]) -> Option<BezPath> {
let flags = g.int_or(70, 0);
let ctrl = points(g, 10)?;
let degree = usize::try_from(g.int_or(71, 3)).ok()?;
let knots: Vec<f64> = g.iter().filter(|p| p.code == 40).map(|p| number(p.value)).collect::<Option<_>>()?;
let weights: Vec<f64> = g.iter().filter(|p| p.code == 41).filter_map(|p| number(p.value)).collect();
let weights = (flags & 4 != 0 && weights.len() == ctrl.len()).then_some(weights.as_slice());
curve::nurbs(degree, &knots, &ctrl, weights)
fn spline(s: &model::Spline) -> Option<BezPath> {
let ctrl: Vec<Point> = s.control.iter().map(|p| point(*p)).collect();
let degree = usize::try_from(s.degree).ok()?;
let weights = (s.flags & 4 != 0 && s.weights.len() == ctrl.len()).then_some(s.weights.as_slice());
curve::nurbs(degree, &s.knots, &ctrl, weights)
.map(|mut path| {
if flags & 1 != 0 {
if s.flags & 1 != 0 {
path.close_path();
}
path
})
.or_else(|| curve::through(&points(g, 11)?, flags & 1 != 0))
}
/// Reads a hatch's boundary groups in order.
struct Cursor<'g, 'a> {
g: &'g [Pair<'a>],
i: usize,
}
impl Cursor<'_, '_> {
/// The next group's value when it has `code` (consumed).
fn opt(&mut self, code: i32) -> Option<&str> {
let p = self.g.get(self.i).filter(|p| p.code == code)?;
self.i += 1;
Some(p.value)
}
fn num(&mut self, code: i32) -> Option<f64> {
self.opt(code).and_then(number)
}
fn count(&mut self, code: i32) -> Option<usize> {
self.num(code).filter(|n| *n >= 0.0 && *n <= 1e7).map(|n| n as usize)
}
fn point(&mut self, code: i32) -> Option<Point> {
Some(Point::new(self.num(code)?, self.num(code + 10)?))
}
.or_else(|| curve::through(&s.fit.iter().map(|p| point(*p)).collect::<Vec<_>>(), s.flags & 1 != 0))
}
/// One hatch boundary loop, closed.
fn boundary(c: &mut Cursor<'_, '_>) -> Option<BezPath> {
let flags = c.num(92)? as i64;
let mut bp = BezPath::new();
if flags & 2 != 0 {
let bulges = c.num(72).unwrap_or(0.0) != 0.0;
let _closed = c.opt(73);
let n = c.count(93)?;
let mut verts = Vec::with_capacity(n.min(4096));
for _ in 0..n {
let p = c.point(10)?;
let bulge = if bulges { c.num(42).unwrap_or(0.0) } else { 0.0 };
verts.push(Vertex { p, bulge });
fn boundary(path: &HatchPath) -> Option<BezPath> {
let xy = |p: &[f64; 2]| Point::new(p[0], p[1]);
match path {
HatchPath::Polyline { vertices, .. } => {
let verts: Vec<Vertex> = vertices.iter().map(|[x, y, b]| Vertex { p: Point::new(*x, *y), bulge: *b }).collect();
curve::polyline(&verts, true)
}
bp = curve::polyline(&verts, true)?;
} else {
let n = c.count(93)?;
for _ in 0..n {
let edge = edge(c)?;
append(&mut bp, &edge);
}
if bp.elements().is_empty() {
return None;
}
bp.close_path();
}
// The boundary objects it was made from.
if let Some(n) = c.count(97) {
for _ in 0..n {
if c.opt(330).is_none() {
break;
}
}
}
Some(bp)
}
/// One edge of a hatch boundary.
fn edge(c: &mut Cursor<'_, '_>) -> Option<BezPath> {
match c.num(72)? as i64 {
1 => {
HatchPath::Edges(edges) => {
let mut bp = BezPath::new();
bp.move_to(c.point(10)?);
bp.line_to(c.point(11)?);
for e in edges {
let seg = match e {
HatchEdge::Line { start, end } => {
let mut bp = BezPath::new();
bp.move_to(xy(start));
bp.line_to(xy(end));
Some(bp)
}
HatchEdge::Arc { center, radius, start_angle, end_angle, ccw } => {
let sweep = ccw_sweep(*start_angle, *end_angle);
// Clockwise arcs have their angles measured clockwise.
let (start, sweep) = if *ccw { (*start_angle, sweep) } else { (-start_angle, -sweep) };
curve::arc(xy(center), *radius, start.to_radians(), sweep.to_radians())
}
HatchEdge::Ellipse { center, major, ratio, start_angle, end_angle, ccw } => {
let (centre, major) = (xy(center), xy(major).to_vec2());
let minor = Vec2::new(-major.y, major.x) * *ratio * if *ccw { 1.0 } else { -1.0 };
let sweep = ccw_sweep(*start_angle, *end_angle).to_radians();
curve::ellipse(Affine::new([major.x, major.y, minor.x, minor.y, centre.x, centre.y]), start_angle.to_radians(), sweep)
}
HatchEdge::Spline { degree, rational, knots, control, weights, fit, .. } => {
let ctrl: Vec<Point> = control.iter().map(xy).collect();
let degree = usize::try_from(*degree).ok()?;
let weights = (*rational && weights.len() == ctrl.len()).then_some(weights.as_slice());
curve::nurbs(degree, knots, &ctrl, weights).or_else(|| curve::through(&fit.iter().map(xy).collect::<Vec<_>>(), false))
}
};
append(&mut bp, &seg?);
}
if bp.elements().is_empty() {
return None;
}
bp.close_path();
Some(bp)
}
2 => {
let (centre, r, start, end) = (c.point(10)?, c.num(40)?, c.num(50)?, c.num(51)?);
let ccw = c.num(73).unwrap_or(1.0) != 0.0;
let sweep = ccw_sweep(start, end);
// Clockwise arcs have their angles measured clockwise.
let (start, sweep) = if ccw { (start, sweep) } else { (-start, -sweep) };
curve::arc(centre, r, start.to_radians(), sweep.to_radians())
}
3 => {
let (centre, major, ratio, start, end) = (c.point(10)?, c.point(11)?.to_vec2(), c.num(40)?, c.num(50)?, c.num(51)?);
let ccw = c.num(73).unwrap_or(1.0) != 0.0;
let minor = Vec2::new(-major.y, major.x) * ratio * if ccw { 1.0 } else { -1.0 };
let sweep = ccw_sweep(start, end).to_radians();
curve::ellipse(Affine::new([major.x, major.y, minor.x, minor.y, centre.x, centre.y]), start.to_radians(), sweep)
}
4 => {
let degree = c.count(94)?;
let rational = c.num(73).unwrap_or(0.0) != 0.0;
let _periodic = c.opt(74);
let (nk, nc) = (c.count(95)?, c.count(96)?);
let knots: Vec<f64> = (0..nk).map(|_| c.num(40)).collect::<Option<_>>()?;
let mut ctrl = Vec::with_capacity(nc.min(4096));
let mut weights = Vec::with_capacity(nc.min(4096));
for _ in 0..nc {
ctrl.push(c.point(10)?);
weights.push(c.num(42).unwrap_or(1.0));
}
// Fit data (DXF 2010 and later): a count, then that many points. Older files have none,
// and the 97 that may follow is the boundary's count of source objects (then their
// handles), so it is only the fit count when it is 0 or points follow.
let fit_count = match (c.g.get(c.i), c.g.get(c.i + 1)) {
(Some(count), next) if count.code == 97 => number(count.value) == Some(0.0) || next.is_some_and(|p| p.code == 11),
_ => false,
};
let fit: Vec<Point> = match fit_count.then(|| c.count(97)).flatten() {
Some(n) => (0..n).map(|_| c.point(11)).collect::<Option<_>>()?,
None => vec![],
};
// Start and end tangents.
for code in [12, 13] {
c.point(code);
}
curve::nurbs(degree, &knots, &ctrl, rational.then_some(weights.as_slice())).or_else(|| curve::through(&fit, false))
}
_ => None,
}
}
@@ -643,18 +527,21 @@ fn baseline(v: i64, height: f64) -> f64 {
}
}
fn text(g: &[Pair<'_>], attrib: bool) -> Option<TextItem> {
if attrib && g.int_or(70, 0) & 1 != 0 {
/// TEXT, or an ATTRIB's text. The string is read from group 1 as written, so that the caret and
/// percent codes are turned into text once, by `super::text`.
fn text(t: &model::Text, g: &Groups<'_>, attrib: bool, ocs: Affine) -> Option<TextItem> {
if attrib && g.i_or(70, 0) & 1 != 0 {
return None;
}
let s = super::text::plain(g.raw(1)?);
let s = super::text::plain(&g.s(1)?);
if s.trim().is_empty() {
return None;
}
let height = g.num(40).filter(|h| *h > 0.0)?;
let (h, v) = (g.int_or(72, 0), g.int_or(if attrib { 74 } else { 73 }, 0));
let (p1, p2) = (g.point(10), g.point_opt(11));
let mut angle = g.num_or(50, 0.0).to_radians();
let height = Some(t.height).filter(|h| *h > 0.0)?;
// An ATTRIB's 73 is its field length: its vertical alignment is 74.
let (h, v) = (t.halign, if attrib { g.i_or(74, 0) } else { t.valign });
let (p1, p2) = (point(t.insert), t.align.map(point));
let mut angle = t.rotation.to_radians();
let mut span = None;
// Aligned and fit text run from the first point to the second.
let anchor = match (h, p2) {
@@ -674,33 +561,36 @@ fn text(g: &[Pair<'_>], attrib: bool) -> Option<TextItem> {
_ => Justify::Left,
};
let v = if h == 4 { 2 } else { v };
let flags = g.int_or(71, 0);
let flags = t.generation;
let mirror = Affine::scale_non_uniform(if flags & 2 != 0 { -1.0 } else { 1.0 }, if flags & 4 != 0 { -1.0 } else { 1.0 });
let xf = ocs(g) * Affine::translate(anchor.to_vec2()) * Affine::rotate(angle) * mirror * Affine::translate((0.0, baseline(v, height)));
let xf = ocs * Affine::translate(anchor.to_vec2()) * Affine::rotate(angle) * mirror * Affine::translate((0.0, baseline(v, height)));
Some(TextItem {
text: s,
height,
xf,
width: g.num(41).filter(|w| *w > 0.0).unwrap_or(1.0),
width: Some(t.width_factor).filter(|w| *w > 0.0).unwrap_or(1.0),
justify,
style: g.name(7).unwrap_or("STANDARD").to_uppercase(),
style: t.style.to_uppercase(),
family: None,
leading: None,
span,
})
}
fn mtext(g: &[Pair<'_>]) -> Option<TextItem> {
// The text comes in 250-character chunks (3) before the last (1).
let raw: String = g.iter().filter(|p| p.code == 3).map(|p| p.value).chain(g.raw(1)).collect();
/// MTEXT. The contents are read from groups 3 and 1 as written, as for [`text`].
fn mtext(t: &model::MText, tags: &[craft_dxf::Tag]) -> Option<TextItem> {
// The text comes in 250-character chunks (3) before the last (1), up to an embedded object.
let (own, _) = model::text::split_embedded(tags);
let g = Groups(own);
let raw: String = own.iter().filter(|t| t.code == 3).map(craft_dxf::Tag::str).chain(g.s(1)).collect();
let (s, family) = super::text::mtext(&raw);
if s.trim().is_empty() {
return None;
}
let height = g.num(40).filter(|h| *h > 0.0)?;
let leading = height * LINE_SPACING * g.num(44).filter(|f| *f > 0.0).unwrap_or(1.0);
let height = Some(t.height).filter(|h| *h > 0.0)?;
let leading = height * LINE_SPACING * Some(t.line_spacing).filter(|f| *f > 0.0).unwrap_or(1.0);
let lines = s.lines().count().max(1) as f64;
let attach = g.int_or(71, 1).clamp(1, 9) - 1;
let attach = i64::from(t.attach) - 1;
let justify = [Justify::Left, Justify::Center, Justify::Right].get((attach % 3) as usize).copied().unwrap_or_default();
// The first baseline below the attachment point: under the top, around the middle, above
// the bottom of the lines.
@@ -710,18 +600,6 @@ fn mtext(g: &[Pair<'_>]) -> Option<TextItem> {
1 => total / 2.0 - height,
_ => (lines - 1.0) * leading,
};
let direction = g.point_opt(11).map(|p| p.to_vec2()).filter(|d| d.hypot() > 1e-12);
let angle = direction.map_or_else(|| g.num_or(50, 0.0), |d| d.atan2());
let xf = Affine::translate(g.point(10).to_vec2()) * Affine::rotate(angle) * Affine::translate((0.0, first));
Some(TextItem {
text: s,
height,
xf,
width: 1.0,
justify,
style: g.name(7).unwrap_or("STANDARD").to_uppercase(),
family,
leading: Some(leading),
span: None,
})
let xf = Affine::translate(point(t.insert).to_vec2()) * Affine::rotate(t.angle()) * Affine::translate((0.0, first));
Some(TextItem { text: s, height, xf, width: 1.0, justify, style: t.style.to_uppercase(), family, leading: Some(leading), span: None })
}
+68 -331
View File
@@ -1,156 +1,14 @@
//! Reading an ASCII DXF file: its text, the group-code pairs, and what the import uses of its
//! sections (header variables; the layer, linetype, text style and block record tables; the
//! blocks; the entities; the layouts).
//! What the import uses of a drawing, from `craft_dxf::model`: header variables; the layer,
//! linetype and text style tables; the blocks; the entities; the layouts.
use std::borrow::Cow;
use std::collections::HashMap;
use craft_dxf::model::{self, EntityRecord};
use vectorcraft_geom::Point;
/// The most group-code pairs a drawing may hold (about 300 MB of DXF).
const MAX_PAIRS: usize = 20_000_000;
/// The first bytes of a binary DXF file (its format's signature).
pub const BINARY_SENTINEL: &[u8] = b"AutoCAD Binary DXF\r\n\x1a\x00";
/// One group: its code and its value as written.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Pair<'a> {
pub code: i32,
pub value: &'a str,
}
/// Values of a run of pairs by group code.
pub(crate) trait Groups<'a> {
/// The value of the first `code`, as written.
fn raw(&self, code: i32) -> Option<&'a str>;
/// The first `code` as a name (trimmed, never empty).
fn name(&self, code: i32) -> Option<&'a str> {
self.raw(code).map(str::trim).filter(|s| !s.is_empty())
}
/// The first `code` as a finite number.
fn num(&self, code: i32) -> Option<f64> {
self.raw(code).and_then(number)
}
fn num_or(&self, code: i32, default: f64) -> f64 {
self.num(code).unwrap_or(default)
}
/// The first `code` as a whole number.
fn int(&self, code: i32) -> Option<i64> {
self.raw(code).and_then(integer)
}
fn int_or(&self, code: i32, default: i64) -> i64 {
self.int(code).unwrap_or(default)
}
/// The point at `code` (x) and `code + 10` (y); 0 for what is missing.
fn point(&self, code: i32) -> Point {
Point::new(self.num_or(code, 0.0), self.num_or(code + 10, 0.0))
}
/// [`Groups::point`] when its x is given.
fn point_opt(&self, code: i32) -> Option<Point> {
self.num(code).map(|x| Point::new(x, self.num_or(code + 10, 0.0)))
}
}
impl<'a> Groups<'a> for [Pair<'a>] {
fn raw(&self, code: i32) -> Option<&'a str> {
self.iter().find(|p| p.code == code).map(|p| p.value)
}
}
/// A finite number (`1e999`, `NaN` and junk are none).
pub(crate) fn number(s: &str) -> Option<f64> {
s.trim().parse::<f64>().ok().filter(|v| v.is_finite())
}
/// A whole number; some writers put integers as `1.0`.
pub(crate) fn integer(s: &str) -> Option<i64> {
let s = s.trim();
s.parse::<i64>().ok().or_else(|| number(s).filter(|v| v.abs() < 9.0e15 && v.fract() == 0.0).map(|v| v as i64))
}
/// One object: its type (the value of its `0` group) and the groups up to the next object.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Record<'a> {
pub kind: &'a str,
pub g: &'a [Pair<'a>],
}
/// The text of a DXF file: UTF-8 (DXF 2007 and later), else the Windows code page older versions
/// write (a byte order mark is dropped).
pub(crate) fn decode(bytes: &[u8]) -> Cow<'_, str> {
let bytes = bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(bytes);
match std::str::from_utf8(bytes) {
Ok(s) => Cow::Borrowed(s),
Err(_) => Cow::Owned(bytes.iter().map(|b| windows_1252(*b)).collect()),
}
}
/// A byte of the Windows Western code page.
fn windows_1252(b: u8) -> char {
const HIGH: [char; 32] = [
'€', '\u{81}', '‚', 'ƒ', '„', '…', '†', '‡', 'ˆ', '‰', 'Š', '‹', 'Œ', '\u{8D}', 'Ž', '\u{8F}', '\u{90}', '‘', '’', '“', '”', '•', '–', '—',
'˜', '™', 'š', '›', 'œ', '\u{9D}', 'ž', 'Ÿ',
];
match b {
0x80..=0x9F => HIGH.get(usize::from(b - 0x80)).copied().unwrap_or('?'),
_ => char::from(b),
}
}
/// The group-code pairs of `text`, up to `0 EOF`. A line that isn't a group code ends the
/// reading: what came before is kept and the second value says where the file is damaged.
pub(crate) fn pairs(text: &str) -> Result<(Vec<Pair<'_>>, Option<String>), String> {
let mut out = Vec::new();
let mut lines = text.lines().enumerate();
let mut damaged = None;
while let Some((n, code)) = lines.next() {
let c = code.trim();
if c.is_empty() && out.is_empty() {
continue;
}
let Ok(code) = c.parse::<i32>() else {
damaged = Some(format!("the file is damaged at line {}: what follows is left out", n + 1));
break;
};
let value = lines.next().map_or("", |(_, v)| v);
if code == 0 && value.trim() == "EOF" {
break;
}
if out.len() >= MAX_PAIRS {
return Err("the drawing is too large to open".into());
}
out.push(Pair { code, value });
}
if out.is_empty() {
return Err("not a DXF drawing".into());
}
Ok((out, damaged))
}
/// The objects in `pairs`: each from a `0` group up to the next.
fn records<'a>(pairs: &'a [Pair<'a>]) -> Vec<Record<'a>> {
let mut out = Vec::new();
let mut start: Option<usize> = None;
for (i, p) in pairs.iter().enumerate() {
if p.code == 0 {
if let Some(s) = start {
out.extend(record(pairs, s, i));
}
start = Some(i);
}
}
if let Some(s) = start {
out.extend(record(pairs, s, pairs.len()));
}
out
}
fn record<'a>(pairs: &'a [Pair<'a>], start: usize, end: usize) -> Option<Record<'a>> {
let kind = pairs.get(start)?.value.trim();
Some(Record { kind, g: pairs.get(start + 1..end)? })
}
/// The header variables the import reads.
#[derive(Clone, Debug, Default)]
pub(crate) struct Header {
@@ -186,7 +44,7 @@ pub(crate) struct LayerDef {
pub(crate) struct BlockDef<'a> {
pub name: String,
pub base: Point,
pub records: Vec<Record<'a>>,
pub records: Vec<EntityRecord<'a>>,
/// A reference to another drawing (its art isn't in this file).
pub xref: bool,
}
@@ -218,97 +76,51 @@ pub(crate) struct Drawing<'a> {
/// Blocks by upper-case name.
pub blocks: HashMap<String, BlockDef<'a>>,
/// The ENTITIES section.
pub entities: Vec<Record<'a>>,
pub entities: Vec<EntityRecord<'a>>,
/// Model space first, then the paper layouts in tab order.
pub layouts: Vec<LayoutDef>,
/// How many sections the file has (none: not a drawing).
pub sections: usize,
}
impl<'a> Drawing<'a> {
/// Read the sections of `pairs`.
pub fn read(pairs: &'a [Pair<'a>]) -> Self {
let mut d = Drawing { header: Header { ltscale: 1.0, lwdefault: 25, ..Header::default() }, ..Drawing::default() };
let all = records(pairs);
let mut section: Option<&str> = None;
let (mut tables, mut blocks, mut objects) = (vec![], vec![], vec![]);
for r in all {
match (r.kind, section) {
("SECTION", _) => {
d.sections += 1;
section = r.g.name(2);
if section == Some("HEADER") {
d.header = header(r.g);
}
}
("ENDSEC", _) => section = None,
(_, Some("TABLES")) => tables.push(r),
(_, Some("BLOCKS")) => blocks.push(r),
(_, Some("ENTITIES")) => d.entities.push(r),
(_, Some("OBJECTS")) => objects.push(r),
_ => {}
}
}
let mut block_records = HashMap::new();
let mut table = "";
for r in &tables {
match r.kind {
"TABLE" => table = r.g.name(2).unwrap_or(""),
"LAYER" if table == "LAYER" => {
if let Some(l) = layer(r.g) {
d.layer_index.entry(l.name.to_uppercase()).or_insert(d.layers.len());
d.layers.push(l);
}
}
"LTYPE" if table == "LTYPE" => {
if let Some(name) = r.g.name(2) {
let pattern: Vec<f64> = r.g.iter().filter(|p| p.code == 49).filter_map(|p| number(p.value)).collect();
d.linetypes.insert(name.to_uppercase(), pattern);
}
}
"STYLE" if table == "STYLE" => {
if let Some(name) = r.g.name(2) {
d.styles.insert(name.to_uppercase(), font_family(r.g));
}
}
"BLOCK_RECORD" if table == "BLOCK_RECORD" => {
if let (Some(h), Some(name)) = (r.g.name(5), r.g.name(2)) {
block_records.insert(h.to_uppercase(), name.to_uppercase());
}
}
_ => {}
}
}
d.read_blocks(&blocks, &mut block_records);
d.layouts = layouts(&objects, &block_records, &d.entities);
d
}
/// The colour of index `i` on paper: index 7 (white on a CAD screen) is black.
pub(crate) fn aci_paper(i: u8) -> [u8; 3] {
if i == 7 { [0; 3] } else { model::aci::rgb(i) }
}
fn read_blocks(&mut self, records: &[Record<'a>], block_records: &mut HashMap<String, String>) {
let mut current: Option<BlockDef<'a>> = None;
for r in records {
match r.kind {
"BLOCK" => {
let name = r.g.name(2).or_else(|| r.g.name(3)).unwrap_or("").to_string();
// R13+ blocks name their block record: layouts find their block through it.
if let Some(owner) = r.g.name(330) {
block_records.entry(owner.to_uppercase()).or_insert_with(|| name.to_uppercase());
}
let xref = r.g.int_or(70, 0) & 4 != 0;
current = Some(BlockDef { name, base: r.g.point(10), records: vec![], xref });
}
"ENDBLK" => {
if let Some(b) = current.take().filter(|b| !b.name.is_empty()) {
self.blocks.insert(b.name.to_uppercase(), b);
}
}
_ => {
if let Some(b) = &mut current {
b.records.push(*r);
}
}
}
impl<'a> Drawing<'a> {
/// What the import uses of `doc`.
pub fn read(doc: model::Document<'a>) -> Self {
let h = &doc.header;
let header = Header {
acadver: h.acadver().unwrap_or_default(),
insunits: h.insunits(),
measurement: h.measurement(),
ltscale: h.ltscale(),
lwdefault: i32::from(h.lwdefault()),
};
let mut d = Drawing { header, sections: doc.sections, ..Drawing::default() };
for l in doc.layers() {
d.layer_index.entry(l.name.to_uppercase()).or_insert(d.layers.len());
d.layers.push(layer(l));
}
for lt in doc.linetypes() {
d.linetypes.insert(lt.name.to_uppercase(), lt.pattern.iter().map(|e| e.length).collect());
}
for st in doc.text_styles().into_iter().filter(|s| !s.name.is_empty()) {
d.styles.insert(st.name.to_uppercase(), st.family().unwrap_or_default());
}
let block_names = doc.block_names();
d.layouts = layouts(&doc, &block_names);
for b in doc.blocks {
if b.name.is_empty() {
continue;
}
let def = BlockDef { name: b.name.to_string(), base: point(b.base()), xref: b.flags() & 4 != 0, records: b.entities };
d.blocks.insert(b.name.to_uppercase(), def);
}
d.entities = doc.entities;
d
}
/// The layout named `name` (any case; `model` is model space).
@@ -317,7 +129,7 @@ impl<'a> Drawing<'a> {
}
/// The entity records of `layout`.
pub fn layout_records(&self, layout: &LayoutDef) -> Vec<Record<'a>> {
pub fn layout_records(&self, layout: &LayoutDef) -> Vec<EntityRecord<'a>> {
let block = |name: &str| self.blocks.get(name).map(|b| b.records.clone()).unwrap_or_default();
// The active paper layout keeps its art in the ENTITIES section, flagged paper space.
let (block_name, paper) = match &layout.block {
@@ -325,7 +137,7 @@ impl<'a> Drawing<'a> {
Some(b) if b == PAPER_BLOCK => (PAPER_BLOCK, true),
Some(b) => return block(b),
};
let mut out: Vec<Record<'a>> = groups(&self.entities).filter(|g| in_paper_space(g) == paper).flatten().copied().collect();
let mut out: Vec<EntityRecord<'a>> = self.entities.iter().filter(|e| e.paper_space() == paper).cloned().collect();
out.extend(block(block_name));
out
}
@@ -336,111 +148,47 @@ impl<'a> Drawing<'a> {
}
}
/// Is an entity (its first record) in paper space?
fn in_paper_space(group: &[Record<'_>]) -> bool {
group.first().is_some_and(|r| r.g.int(67) == Some(1))
pub(crate) fn point(p: model::Point) -> Point {
Point::new(p[0], p[1])
}
/// The entities of `records`, each with the records that belong to it (a polyline's vertices,
/// an insert's attributes, and the SEQEND closing them).
pub(crate) fn groups<'r, 'a>(records: &'r [Record<'a>]) -> impl Iterator<Item = &'r [Record<'a>]> {
let mut i = 0;
std::iter::from_fn(move || {
let start = i;
let head = records.get(start)?;
i += 1;
if matches!(head.kind, "POLYLINE" | "INSERT") {
while let Some(r) = records.get(i) {
match r.kind {
"VERTEX" | "ATTRIB" => i += 1,
"SEQEND" => {
i += 1;
break;
}
_ => break,
}
}
}
records.get(start..i)
})
}
fn header(g: &[Pair<'_>]) -> Header {
let mut h = Header { ltscale: 1.0, lwdefault: 25, ..Header::default() };
let mut var = "";
for p in g {
if p.code == 9 {
var = p.value.trim();
continue;
}
match (var, p.code) {
("$ACADVER", 1) => h.acadver = p.value.trim().to_string(),
("$INSUNITS", 70) => h.insunits = integer(p.value).unwrap_or(0),
("$MEASUREMENT", 70) => h.measurement = integer(p.value),
("$LTSCALE", 40) => h.ltscale = number(p.value).filter(|v| *v > 0.0).unwrap_or(1.0),
("$LWDEFAULT", 370) => h.lwdefault = integer(p.value).and_then(|v| i32::try_from(v).ok()).filter(|v| *v >= 0).unwrap_or(25),
_ => {}
}
}
h
}
fn layer(g: &[Pair<'_>]) -> Option<LayerDef> {
let name = g.name(2)?.to_string();
let aci = g.int_or(62, 7);
let flags = g.int_or(70, 0);
let rgb = super::entity::true_color(g).unwrap_or_else(|| super::entity::aci_paper(aci.unsigned_abs()));
Some(LayerDef {
fn layer(l: model::Layer) -> LayerDef {
let rgb = match l.color {
model::Color::Rgb(rgb) => rgb,
model::Color::Index(i) => aci_paper(i),
model::Color::ByLayer | model::Color::ByBlock => aci_paper(7),
};
LayerDef {
// CAD apps never plot this layer of dimension points.
plot: g.int_or(290, 1) != 0 && !name.eq_ignore_ascii_case("Defpoints"),
name,
plot: l.plot && !l.name.eq_ignore_ascii_case("Defpoints"),
rgb,
hidden: aci < 0 || flags & 1 != 0,
locked: flags & 4 != 0,
linetype: g.name(6).unwrap_or("CONTINUOUS").to_uppercase(),
lineweight: g.int(370).and_then(|v| i32::try_from(v).ok()).unwrap_or(-3),
})
}
/// A text style's font family: the one 2000-and-later files name, else the font file's name
/// (TrueType); CAD fonts (`.shx`) have none.
fn font_family(g: &[Pair<'_>]) -> String {
if let Some(i) = g.iter().position(|p| p.code == 1001 && p.value.trim() == "ACAD")
&& let Some(f) = g.get(i + 1..).and_then(|rest| rest.name(1000))
{
return f.to_string();
}
let file = g.name(3).unwrap_or("");
let path = std::path::Path::new(file);
let ext = path.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
match ext.as_str() {
"ttf" | "otf" | "ttc" => path.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(),
_ => String::new(),
hidden: !l.on || l.frozen,
locked: l.locked,
linetype: l.linetype.to_uppercase(),
lineweight: i32::try_from(l.lineweight.to_dxf()).unwrap_or(-3),
name: l.name,
}
}
/// Model space, then each paper layout (its LAYOUT object, in tab order); a file without layout
/// objects but with paper-space art has one paper layout.
/// The most bytes of layout and block names the layouts keep together. Each layout keeps its own
/// copy of its block's name, so many layouts naming one long block name multiplied it; real
/// drawings have a few dozen layouts with short names.
const MAX_LAYOUT_NAME_BYTES: usize = 4 << 20;
fn layouts(objects: &[Record<'_>], block_records: &HashMap<String, String>, entities: &[Record<'_>]) -> Vec<LayoutDef> {
/// Model space, then each paper layout (its LAYOUT object, in tab order); a file without layout
/// objects but with paper-space art has one paper layout.
fn layouts(doc: &model::Document<'_>, block_names: &HashMap<u64, &str>) -> Vec<LayoutDef> {
let mut paper: Vec<(i64, LayoutDef)> = vec![];
let mut seen = std::collections::HashSet::new();
let mut name_bytes = 0usize;
for r in objects.iter().filter(|r| r.kind == "LAYOUT") {
// The layout's own groups follow its subclass marker.
let own = r.g.iter().position(|p| p.code == 100 && p.value.trim() == "AcDbLayout").and_then(|i| r.g.get(i + 1..)).unwrap_or(&[]);
let Some(name) = own.name(1) else { continue };
let block = own.name(330).and_then(|h| block_records.get(&h.to_uppercase()));
if name.eq_ignore_ascii_case(MODEL) || block.map(String::as_str) == Some(MODEL_BLOCK) {
for l in doc.layouts() {
let block = l.block_record.and_then(|h| block_names.get(&h)).map(|n| n.to_uppercase());
if l.name.eq_ignore_ascii_case(MODEL) || block.as_deref() == Some(MODEL_BLOCK) {
continue;
}
let Some(block) = block else { continue };
let key = name.to_ascii_lowercase();
let cost = name.len() + block.len();
let key = l.name.to_ascii_lowercase();
let cost = l.name.len() + block.len();
// A layout past the allowance is skipped alone: a later short one is still offered, and a
// skipped one reserves neither its name nor its bytes.
if seen.contains(&key) || name_bytes.saturating_add(cost) > MAX_LAYOUT_NAME_BYTES {
@@ -448,22 +196,11 @@ fn layouts(objects: &[Record<'_>], block_records: &HashMap<String, String>, enti
}
seen.insert(key);
name_bytes += cost;
paper.push((own.int_or(71, i64::MAX), LayoutDef { name: name.to_string(), block: Some(block.clone()) }));
paper.push((l.tab_order, LayoutDef { name: l.name, block: Some(block) }));
}
paper.sort_by_key(|(order, _)| *order);
if paper.is_empty() && groups(entities).any(in_paper_space) {
if paper.is_empty() && doc.entities.iter().any(EntityRecord::paper_space) {
paper.push((1, LayoutDef { name: "Layout1".into(), block: Some(PAPER_BLOCK.into()) }));
}
std::iter::once(LayoutDef { name: MODEL.into(), block: None }).chain(paper.into_iter().map(|(_, l)| l)).collect()
}
#[cfg(test)]
mod tests {
use super::integer;
#[test]
fn integer_rejects_fractional_float_values() {
assert_eq!(integer("1.0"), Some(1));
assert_eq!(integer("1.9"), None);
}
}
+8 -4
View File
@@ -997,7 +997,12 @@ fn binary_dwg_damaged_and_foreign_files() {
binary.extend([0u8; 40]);
assert!(is_dxf(&binary));
let e = import(&binary, &ImportOptions::default()).unwrap_err();
assert!(e.contains("binary DXF") && e.contains("ASCII"), "{e}");
assert!(e.contains("binary DXF") && e.contains("damaged"), "{e}");
// A binary DXF opens as its ASCII form does.
let ascii = entities(LINE);
let tags = craft_dxf::parse(&ascii).unwrap();
let r = open(&craft_dxf::write_binary(&tags, true), &points());
assert_eq!(leaves(&r.document).len(), 1);
let e = import(b"AC1032\x00\x00\x00", &ImportOptions::default()).unwrap_err();
assert!(e.contains("DWG"), "{e}");
for junk in [&b""[..], b"hello", b"<svg/>", b"999\nnote\n"] {
@@ -1166,9 +1171,8 @@ fn many_array_inserts_of_a_missing_block_stay_bounded() {
let one = [(0, "INSERT"), (8, "0"), (2, "NOPE"), (10, "0"), (20, "0"), (70, "100"), (71, "100"), (44, "1"), (45, "1")];
let e: Vec<(i32, &str)> = (0..3000).flat_map(|_| one).collect();
let bytes = entities(&e);
let text = reader::decode(&bytes);
let (pairs, _) = reader::pairs(&text).unwrap();
let d = reader::Drawing::read(&pairs);
let tags = craft_dxf::parse(&bytes).unwrap();
let d = reader::Drawing::read(craft_dxf::model::Document::read(&tags));
let model = d.layout("Model").or(d.layouts.first()).unwrap();
let mut conv = entity::Converter::default();
let items = conv.items(&d.layout_records(model));
+3 -3
View File
@@ -1,5 +1,5 @@
//! CAD interchange: a hand-written ASCII DXF writer (versions R12 to 2018) and reader, and an
//! HP-GL/2 plot file reader and writer.
//! CAD interchange: a hand-written ASCII DXF writer (versions R12 to 2018) and a reader on
//! `craft_dxf::model`, and an HP-GL/2 plot file reader and writer.
//!
//! [`export`] writes the visible art of a document into one DXF drawing: each layer becomes a DXF
//! layer (hidden ones switched off, locked ones locked, non-printing ones not plotted), paths
@@ -11,7 +11,7 @@
//! What DXF can't hold (blending modes, opacity masks, raster effects, gradients, patterns,
//! clipping) is approximated or left out, and each such loss comes back as a warning.
//!
//! [`import()`] reads an ASCII DXF drawing (any version) into a document: see [`import`].
//! [`import()`] reads a DXF drawing (ASCII or binary, any version) into a document: see [`import`].
//! [`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.
+1 -1
View File
@@ -683,7 +683,7 @@ impl<'a> Scene<'a> {
{
// Symbols holding instances of symbols are written in full for each instance,
// empty or not: every instance's art counts against one budget for the export.
let art = vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, n);
let art = vectorcraft_doc::symbol_overrides::instance_art(&sym.art, n);
let count = art.count_with_masks() as u64;
// Counted as `place_symbol_art_unclipped` places it: no clip groups.
let most = doc.symbol_slice_map(symbol, *xf).map_or(count, |m| m.most_placed_unclipped(&art, doc));
+15
View File
@@ -1395,6 +1395,21 @@ fn crop_keeps_an_instance_whose_art_reaches_the_region() {
assert!(!kinds(&export(&d, &o).unwrap()).is_empty());
}
/// An instance stained blue by its fill writes its symbol's red art in blue, as the canvas draws it.
#[test]
fn a_stained_instance_is_written_in_its_stained_color() {
let mut d = doc_with(|d| {
let mut n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf: Affine::translate((30.0, 30.0)) });
n.appearance = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0).into();
vec![n]
});
let art = path(&mut d, shapes::rectangle(Rect::new(0.0, 0.0, 40.0, 40.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0);
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Mark".into(), art: Arc::new(art) });
let out = export(&d, &opts(&d)).unwrap();
let colors: Vec<Option<String>> = entities(&out).iter().map(|e| get(e, 420).map(str::to_string)).collect();
assert!(!colors.is_empty() && colors.iter().all(|c| c.as_deref() == Some("255")), "{colors:?}");
}
#[test]
fn symbols_fanning_out_into_empty_symbols_stop_at_the_symbol_budget() {
// Five levels of 100 instances of the level below, ending in an empty symbol: 10^10 empty
+237 -44
View File
@@ -3,6 +3,7 @@
//! the ruler origin and the objects an edit touches), so a file holding something beyond it could be
//! opened but not edited: one object, artboard or guide out there made every move fail.
use std::collections::BTreeSet;
use std::sync::Arc;
use vectorcraft_geom::{Point, Rect};
@@ -72,27 +73,41 @@ fn clipping(n: &Node) -> Option<bool> {
}
}
/// Does `n`, or any object in it, reach beyond the canvas? A container is looked into object by
/// object: its own bounds leave out a layer's hidden objects and, when it clips, all but its
/// clipping path.
fn reaches_beyond(n: &Node) -> bool {
match clipping(n) {
None => beyond(n),
Some(_) => n.children().is_some_and(|c| c.iter().any(|c| reaches_beyond(c))),
/// The objects of a layer or group that a walk picked, by index in order, each with what was
/// picked inside it (nothing for an object that is not a container).
#[derive(Debug, Default)]
struct Picked(Vec<(usize, Picked)>);
/// What in `n` reaches beyond the canvas, by `far`, or `None` when nothing does. A container is
/// looked into object by object: its own bounds leave out a layer's hidden objects and, when it
/// clips, all but its clipping path. Each object is measured once, and the objects a clipping
/// path beyond the canvas clips are not measured: they go with it (see [`clips_beyond`]).
fn reach(n: &Node, far: &impl Fn(&Node) -> bool) -> Option<Picked> {
let Some(clip) = clipping(n) else { return far(n).then(Picked::default) };
let mut inner = Vec::new();
for (i, c) in n.children().into_iter().flatten().enumerate() {
if let Some(p) = reach(c, far) {
inner.push((i, p));
if clip && i == 0 {
break;
}
}
}
(!inner.is_empty()).then_some(Picked(inner))
}
/// Does `n` clip by a path that reaches beyond the canvas? Then the path and the objects it clips
/// go together, so no other object becomes the clipping path.
fn clips_beyond(n: &Node) -> bool {
clipping(n) == Some(true) && n.children().and_then(|c| c.first()).is_some_and(|c| reaches_beyond(c))
/// Does `n`, whose objects beyond the canvas are `found`, clip by a path that reaches beyond it?
/// Then the path and the objects it clips go together, so no other object becomes the clipping
/// path.
fn clips_beyond(n: &Node, found: &Picked) -> bool {
clipping(n) == Some(true) && found.0.first().is_some_and(|(i, _)| *i == 0)
}
/// Add the ids of `n` and the layers in it, if it is a layer, to `layers`: their layer guides go
/// with them.
fn layers_in(n: &Node, layers: &mut Vec<NodeId>) {
fn layers_in(n: &Node, layers: &mut BTreeSet<NodeId>) {
if matches!(n.kind, NodeKind::Layer { .. }) {
layers.push(n.id);
layers.insert(n.id);
}
if clipping(n).is_some() {
for c in n.children().into_iter().flatten() {
@@ -109,22 +124,22 @@ fn guides_in(n: &Node) -> usize {
}
}
/// Remove the objects in `node` that reach beyond the canvas: a layer or group keeps those of its
/// objects within it, unless its clipping path reaches beyond (see [`clips_beyond`]); anything
/// else goes whole. Only containers holding such an object are copied. Recursion follows the
/// nesting, which [`Document::limit_depth`] bounds. The layers removed are added to `layers`, and
/// the ruler guides they held to `guides`.
fn drop_children_beyond(node: &mut Arc<Node>, dropped: &mut usize, layers: &mut Vec<NodeId>, guides: &mut usize) {
if !node.children().is_some_and(|c| c.iter().any(|c| reaches_beyond(c))) {
return;
}
/// Remove the objects in `node` that reach beyond the canvas, which [`reach`] `found`: a layer or
/// group keeps those of its objects within it, unless its clipping path reaches beyond (see
/// [`clips_beyond`]); anything else goes whole. Only containers holding such an object are
/// copied, and only those are visited again. Recursion follows the nesting, which
/// [`Document::limit_depth`] bounds. The layers removed are added to `layers`, and the ruler
/// guides they held to `guides`.
fn drop_children_beyond(node: &mut Arc<Node>, found: Picked, dropped: &mut usize, layers: &mut BTreeSet<NodeId>, guides: &mut usize) {
let Some(children) = Arc::make_mut(node).children_mut() else { return };
let mut found = found.0.into_iter().peekable();
let mut next = 0;
children.retain_mut(|c| {
if !reaches_beyond(c) {
return true;
}
if clipping(c).is_some() && !clips_beyond(c) {
drop_children_beyond(c, dropped, layers, guides);
let at = next;
next += 1;
let Some((_, inner)) = found.next_if(|(i, _)| *i == at) else { return true };
if clipping(c).is_some() && !clips_beyond(c, &inner) {
drop_children_beyond(c, inner, dropped, layers, guides);
return true;
}
layers_in(c, layers);
@@ -134,21 +149,49 @@ fn drop_children_beyond(node: &mut Arc<Node>, dropped: &mut usize, layers: &mut
});
}
/// Is `id` unset, or not one of `ids`? The check takes time logarithmic in the number of ids.
fn not_in<T: Ord>(id: Option<T>, ids: &BTreeSet<T>) -> bool {
id.is_none_or(|i| !ids.contains(&i))
}
/// Remove the ruler guides of layer `layer` and of its sublayers that `out` picks, adding how many
/// to `dropped`. Only layers holding one are copied.
/// to `dropped`. `out` looks at each object in the layers once. Only layers holding one are
/// copied.
fn drop_guides(layer: &mut Arc<Node>, out: &impl Fn(&Node) -> bool, dropped: &mut usize) {
fn holds(n: &Node, out: &impl Fn(&Node) -> bool) -> bool {
n.is_layer() && n.children().is_some_and(|ch| ch.iter().any(|c| out(c) || holds(c, out)))
/// The objects of `n`, if it is a layer, that `out` picks (with nothing inside), and its
/// sublayers holding one (with what they hold), or `None` when it holds none.
fn holds(n: &Node, out: &impl Fn(&Node) -> bool) -> Option<Picked> {
if !n.is_layer() {
return None;
}
let inner: Vec<(usize, Picked)> = n
.children()
.into_iter()
.flatten()
.enumerate()
.filter_map(|(i, c)| if out(c) { Some((i, Picked::default())) } else { holds(c, out).map(|p| (i, p)) })
.collect();
(!inner.is_empty()).then_some(Picked(inner))
}
if !holds(layer, out) {
return;
fn drop(layer: &mut Arc<Node>, held: Picked, dropped: &mut usize) {
let Some(children) = Arc::make_mut(layer).children_mut() else { return };
let mut held = held.0.into_iter().peekable();
let mut next = 0;
children.retain_mut(|c| {
let at = next;
next += 1;
let Some((_, inner)) = held.next_if(|(i, _)| *i == at) else { return true };
// A sublayer holds something; an object picked itself has nothing inside.
if inner.0.is_empty() {
*dropped += 1;
return false;
}
drop(c, inner, dropped);
true
});
}
let Some(children) = Arc::make_mut(layer).children_mut() else { return };
let before = children.len();
children.retain(|c| !out(c));
*dropped += before - children.len();
for c in children.iter_mut().filter(|c| c.is_layer()) {
drop_guides(c, out, dropped);
if let Some(held) = holds(layer, out) {
drop(layer, held, dropped);
}
}
@@ -162,9 +205,10 @@ impl Document {
/// whose artboards were all removed has none left.
pub fn drop_beyond_canvas(&mut self) -> BeyondCanvas {
let mut gone = BeyondCanvas::default();
let mut layers = vec![];
let mut layers = BTreeSet::new();
for layer in &mut self.layers {
if clips_beyond(layer) {
let Some(found) = reach(layer, &beyond) else { continue };
if clips_beyond(layer, &found) {
let layer = Arc::make_mut(layer);
if let NodeKind::Layer { children, clip, .. } = &mut layer.kind {
for c in children.iter() {
@@ -177,7 +221,7 @@ impl Document {
*clip = false;
}
} else {
drop_children_beyond(layer, &mut gone.objects, &mut layers, &mut gone.guides);
drop_children_beyond(layer, found, &mut gone.objects, &mut layers, &mut gone.guides);
}
}
if gone.objects > 0 {
@@ -192,13 +236,13 @@ impl Document {
self.retire_artboard_id(*id);
}
gone.artboards = removed.len();
let removed: BTreeSet<u32> = removed.into_iter().collect();
// The saved list, when the guides are not nodes yet ([`Document::guides_into_nodes`]).
let guides = self.saved_guides.len();
self.saved_guides
.retain(|g| in_range(g.pos) && g.artboard.is_none_or(|a| !removed.contains(&a)) && g.layer.is_none_or(|l| !layers.contains(&l)));
self.saved_guides.retain(|g| in_range(g.pos) && not_in(g.artboard, &removed) && not_in(g.layer, &layers));
gone.guides += guides - self.saved_guides.len();
let out = |n: &Node| match n.kind {
NodeKind::RulerGuide { pos, artboard, .. } => !in_range(pos) || artboard.is_some_and(|a| removed.contains(&a)),
NodeKind::RulerGuide { pos, artboard, .. } => !in_range(pos) || !not_in(artboard, &removed),
_ => false,
};
for layer in &mut self.layers {
@@ -392,4 +436,153 @@ mod tests {
assert_eq!(d.assets.iter().map(|a| (a.id, a.nodes.clone())).collect::<Vec<_>>(), [(2, vec![NodeId(10)])]);
assert_eq!(d.variables.bindings.keys().copied().collect::<Vec<_>>(), [NodeId(10)]);
}
#[test]
fn guides_of_many_removed_artboards_and_layers_go_and_the_rest_keep_their_order() {
let probe = Document::new(1.0, 1.0);
// Sublayers 40 to 43 clip by a path beyond the canvas, so they go whole; 50 stays.
let far: Vec<Arc<Node>> = (40..44).map(|id| sublayer(&probe, id, vec![rect(id * 10, 1e17), rect(id * 10 + 1, 0.0)], true)).collect();
let near = sublayer(&probe, 50, vec![rect(500, 0.0)], false);
let mut d = doc(far.into_iter().chain([near, rect(10, 0.0)]).collect());
let kept = d.artboards[0].id;
for id in 9..13 {
d.artboards.push(Artboard { id, rect: Rect::new(0.0, 1e17, 100.0, 1e17 + 100.0), ..d.artboards[0].clone() });
}
let top = d.layers[0].id;
let guide = |pos: f64, artboard: Option<u32>, layer: Option<NodeId>| Guide { artboard, layer, ..Guide::new(false, pos) };
d.saved_guides = vec![
guide(1.0, Some(9), None),
guide(2.0, None, None),
guide(3.0, Some(kept), Some(NodeId(41))),
guide(4.0, Some(kept), None),
guide(5.0, Some(12), None),
guide(6.0, None, Some(NodeId(50))),
guide(7.0, None, Some(NodeId(43))),
guide(8.0, Some(10), Some(top)),
guide(9.0, None, Some(top)),
];
d.saved_selections = vec![crate::records::SavedSelection { name: "s".into(), objects: vec![NodeId(42), NodeId(10), NodeId(500)] }].into();
let mut nodes = d.clone();
assert_eq!(nodes.guides_into_nodes(), 9);
let gone = d.drop_beyond_canvas();
assert_eq!(gone, BeyondCanvas { objects: 4, artboards: 4, guides: 5, ruler_origin: false });
assert_eq!(d.artboards.iter().map(|a| a.id).collect::<Vec<_>>(), [kept]);
let left: Vec<f64> = d.saved_guides.iter().map(|g| g.pos).collect();
assert_eq!(left, [2.0, 4.0, 6.0, 9.0], "the guides that stay keep their order");
assert_eq!(d.saved_selections[0].objects, [NodeId(10), NodeId(500)]);
assert_eq!(nodes.drop_beyond_canvas(), gone, "guide nodes go as saved guides do");
let mut left: Vec<f64> = nodes.ruler_guides().iter().map(|g| g.pos).collect();
left.sort_by(f64::total_cmp);
assert_eq!(left, [2.0, 4.0, 6.0, 9.0]);
assert_eq!(nodes.saved_selections, d.saved_selections);
}
thread_local! {
static COMPARISONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// An id that counts how often it is compared.
#[derive(Debug)]
struct Counted(u32);
impl Ord for Counted {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
COMPARISONS.with(|c| c.set(c.get() + 1));
self.0.cmp(&other.0)
}
}
impl PartialOrd for Counted {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for Counted {
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == std::cmp::Ordering::Equal
}
}
impl Eq for Counted {}
#[test]
fn a_guide_is_checked_without_scanning_every_removed_id() {
let per_guide = |removed: u32| {
let ids: BTreeSet<Counted> = (0..removed).map(|i| Counted(i * 2)).collect();
COMPARISONS.with(|c| c.set(0));
// Guides on removed ids, on ids between them, on ids past them and on none.
let guides: Vec<Option<Counted>> = (0..64).map(|i| (i % 4 != 3).then(|| Counted(i * 31 % (removed * 2 + 8)))).collect();
let kept = guides.into_iter().filter(|g| not_in(g.as_ref().map(|c| Counted(c.0)), &ids)).count();
assert!(kept > 0 && kept < 64);
COMPARISONS.with(|c| c.get()) as f64 / 64.0
};
let small = per_guide(16);
let large = per_guide(16_384);
// A sorted lookup grows with the depth of the tree; a scan of 16,384 ids compares thousands per guide.
assert!(large < small * 32.0 && large < 256.0, "{small} comparisons per guide among 16 ids, {large} among 16,384");
}
#[test]
fn each_object_is_measured_once_however_deep_the_nesting() {
// 32 groups, each inside the one before and holding an object within the canvas; the
// innermost also holds one beyond it. Beside them, a group with nothing beyond and a clip
// group whose clipping path reaches beyond.
let mut chain = Arc::new(Node::group(NodeId(100), vec![rect(200, 0.0), rect(201, 1e17)]));
for depth in 1..32 {
chain = Arc::new(Node::group(NodeId(100 + depth), vec![rect(300 + depth, 0.0), chain]));
}
let still = Arc::new(Node::group(NodeId(400), vec![rect(401, 0.0), rect(402, 5.0)]));
let clip = Arc::new(Node::new(NodeId(600), NodeKind::Group { children: vec![rect(601, 1e17), rect(602, 0.0), rect(603, 0.0)], clip: true }));
let mut d = doc(vec![chain, Arc::clone(&still), clip]);
let mut whole = d.clone();
let measured = std::cell::Cell::new(0_usize);
let far = |n: &Node| {
measured.set(measured.get() + 1);
beyond(n)
};
let layer = &mut d.layers[0];
let found = reach(layer, &far).unwrap();
assert_eq!(
measured.get(),
36,
"the 33 objects in the groups, the 2 beside them and the clipping path, each measured once; not what the path clips"
);
assert!(!clips_beyond(layer, &found));
let (mut dropped, mut layers, mut guides) = (0, BTreeSet::new(), 0);
drop_children_beyond(layer, found, &mut dropped, &mut layers, &mut guides);
assert_eq!(measured.get(), 36, "removing measures nothing again");
assert_eq!((dropped, layers.len(), guides), (2, 0, 0));
assert!(d.layers[0].children().is_some_and(|c| Arc::ptr_eq(&c[1], &still)), "a group with nothing beyond is not copied");
assert_eq!(whole.drop_beyond_canvas(), BeyondCanvas { objects: 2, ..Default::default() });
assert_eq!(ids(&whole), ids(&d));
assert!(!ids(&d).contains(&201) && !ids(&d).contains(&600) && ids(&d).contains(&200) && ids(&d).contains(&331));
}
#[test]
fn each_object_is_looked_at_once_when_guides_go_from_nested_layers() {
let guide = |id: u64, pos: f64| Arc::new(Node::new(NodeId(id), NodeKind::RulerGuide { vertical: false, pos, artboard: None }));
let probe = Document::new(1.0, 1.0);
// 32 sublayers, each inside the one before, each holding a guide within the canvas and one
// beyond it. Beside them, a sublayer with nothing to remove.
let mut chain = sublayer(&probe, 100, vec![guide(200, 5.0), guide(201, 1e17)], false);
for depth in 1..32 {
chain = sublayer(&probe, 100 + depth, vec![guide(300 + depth * 2, 5.0), guide(301 + depth * 2, 1e17), chain], false);
}
let still = sublayer(&probe, 500, vec![guide(501, 5.0), rect(502, 0.0)], false);
let mut d = doc(vec![chain, Arc::clone(&still)]);
let looked = std::cell::Cell::new(0_usize);
let out = |n: &Node| {
looked.set(looked.get() + 1);
matches!(n.kind, NodeKind::RulerGuide { pos, .. } if !in_range(pos))
};
let mut dropped = 0;
drop_guides(&mut d.layers[0], &out, &mut dropped);
assert_eq!(dropped, 32);
assert_eq!(looked.get(), 2 + 2 + 31 * 3 + 2, "each object in the layers is looked at once");
assert!(d.layers[0].children().is_some_and(|c| Arc::ptr_eq(&c[1], &still)), "a sublayer with nothing to remove is not copied");
let left = d.ruler_guides();
assert_eq!(left.len(), 33);
assert!(left.iter().all(|g| g.pos == 5.0));
}
}
+446 -86
View File
@@ -183,8 +183,8 @@ impl Document {
self.layers.retain(|l| !l.is_ruler_guide());
gone -= self.layers.len();
for l in &mut self.layers {
if layer_untidy(l) {
gone += tidy_layer(Arc::make_mut(l));
if let Some(found) = untidy(l, &Node::is_ruler_guide) {
gone += tidy_layer(Arc::make_mut(l), found);
}
}
let others = self
@@ -198,8 +198,8 @@ impl Document {
if root.is_ruler_guide() {
*root = Arc::new(Node::group(root.id, vec![]));
gone += 1;
} else if any_guide(root) {
gone += drop_guides_below(Arc::make_mut(root));
} else if let Some(found) = guides_below(root, &Node::is_ruler_guide) {
gone += drop_guides_below(Arc::make_mut(root), found);
}
}
gone
@@ -272,8 +272,8 @@ impl Document {
return;
}
for l in &mut self.layers {
if l.holds_ruler_guides() {
Arc::make_mut(l).strip_ruler_guides();
if let Some(held) = picked_in_layers(l, &Node::is_ruler_guide) {
drop_picked(l, held);
}
}
self.saved_guides.extend(guides);
@@ -347,16 +347,14 @@ impl Document {
/// saved guide whose layer is gone opens. Returns the removed node, without the guides.
pub fn remove_edit_layer(&mut self, id: NodeId) -> Result<Arc<Node>, crate::DocError> {
let mut layer = self.remove(id)?;
if !layer.holds_ruler_guides() {
return Ok(layer);
}
let Some(held) = picked_in_layers(&layer, &Node::is_ruler_guide) else { return Ok(layer) };
let mut guides = vec![];
layer.walk(&mut |c| {
if c.is_ruler_guide() {
guides.push(Arc::new(c.clone()));
}
});
Arc::make_mut(&mut layer).strip_ruler_guides();
drop_picked(&mut layer, held);
let home = self.default_layer().unwrap_or_else(|| self.add_layer(None));
self.children_mut(Some(home))?.extend(guides);
Ok(layer)
@@ -418,21 +416,11 @@ impl Document {
if gone.is_empty() {
return 0;
}
fn drop(layer: &mut Arc<Node>, gone: &HashSet<NodeId>) {
fn holds(n: &Node, gone: &HashSet<NodeId>) -> bool {
n.is_layer() && n.children().is_some_and(|ch| ch.iter().any(|c| gone.contains(&c.id) || holds(c, gone)))
}
if !holds(layer, gone) {
return;
}
let Some(ch) = Arc::make_mut(layer).children_mut() else { return };
ch.retain(|c| !(c.is_ruler_guide() && gone.contains(&c.id)));
for c in ch.iter_mut().filter(|c| c.is_layer()) {
drop(c, gone);
}
}
let pick = |n: &Node| n.is_ruler_guide() && gone.contains(&n.id);
for l in &mut self.layers {
drop(l, &gone);
if let Some(held) = picked_in_layers(l, &pick) {
drop_picked(l, held);
}
}
sel.guides.retain(|id| !gone.contains(id));
if sel.key_guide.is_some_and(|k| gone.contains(&k)) {
@@ -444,29 +432,11 @@ impl Document {
/// Change the line of every ruler guide on artboard `id` with `f` (whether it is vertical, its
/// position).
fn edit_artboard_guides(&mut self, id: u32, f: &mut impl FnMut(bool, &mut f64)) {
fn visit(layer: &mut Arc<Node>, id: u32, f: &mut impl FnMut(bool, &mut f64)) {
fn holds(n: &Node, id: u32) -> bool {
n.is_layer()
&& n.children().is_some_and(|ch| {
ch.iter().any(|c| matches!(c.kind, NodeKind::RulerGuide { artboard: Some(a), .. } if a == id) || holds(c, id))
})
}
if !holds(layer, id) {
return;
}
let Some(ch) = Arc::make_mut(layer).children_mut() else { return };
for c in ch.iter_mut() {
if matches!(c.kind, NodeKind::RulerGuide { artboard: Some(a), .. } if a == id) {
if let NodeKind::RulerGuide { vertical, pos, .. } = &mut Arc::make_mut(c).kind {
f(*vertical, pos);
}
} else if c.is_layer() {
visit(c, id, f);
}
}
}
let pick = |n: &Node| matches!(n.kind, NodeKind::RulerGuide { artboard: Some(a), .. } if a == id);
for l in &mut self.layers {
visit(l, id, f);
if let Some(held) = picked_in_layers(l, &pick) {
edit_picked(l, held, f);
}
}
}
@@ -580,65 +550,172 @@ impl Document {
}
}
/// Does `n`, or anything below it (opacity-mask art included), hold a ruler guide?
fn any_guide(n: &Node) -> bool {
let mut any = false;
crate::swatches::walk_with_masks(n, &mut |m| any |= m.is_ruler_guide());
any
/// What a walk picked in a node: its children by index in order, each with what was picked
/// inside it, and what was picked in its opacity-mask art. Empty for a node picked itself.
#[derive(Debug, Default)]
struct Picked {
children: Vec<(usize, Picked)>,
mask: Option<Box<Picked>>,
}
/// Remove every ruler guide below `n`, in its members and its opacity-mask art (`n` itself
/// stays). Mask art that is a ruler guide becomes an empty group. Returns how many went.
fn drop_guides_below(n: &mut Node) -> usize {
let mut gone = drop_mask_guides(n);
if let Some(ch) = n.children_mut() {
let before = ch.len();
ch.retain(|c| !c.is_ruler_guide());
gone += before - ch.len();
for c in ch.iter_mut().filter(|c| any_guide(c)) {
gone += drop_guides_below(Arc::make_mut(c));
impl Picked {
fn is_empty(&self) -> bool {
self.children.is_empty() && self.mask.is_none()
}
/// `self`, or `None` when nothing was picked.
fn some(self) -> Option<Self> {
(!self.is_empty()).then_some(self)
}
}
/// The children of `n`, if it is a layer, that `pick` picks (with nothing inside), and its
/// sublayers holding one (with what they hold), or `None` when it holds none. `pick` looks at
/// each child of the layers once.
fn picked_in_layers(n: &Node, pick: &impl Fn(&Node) -> bool) -> Option<Picked> {
if !n.is_layer() {
return None;
}
let children = n
.children()
.into_iter()
.flatten()
.enumerate()
.filter_map(|(i, c)| if pick(c) { Some((i, Picked::default())) } else { picked_in_layers(c, pick).map(|p| (i, p)) })
.collect();
Picked { children, mask: None }.some()
}
/// Remove the children of `layer` and of its sublayers that [`picked_in_layers`] picked (`held`).
/// Only the layers holding one are copied, and only those are visited.
fn drop_picked(layer: &mut Arc<Node>, held: Picked) {
let Some(ch) = Arc::make_mut(layer).children_mut() else { return };
let mut held = held.children.into_iter().peekable();
let mut next = 0;
ch.retain_mut(|c| {
let at = next;
next += 1;
let Some((_, inner)) = held.next_if(|(i, _)| *i == at) else { return true };
// A sublayer holds something; a child picked itself has nothing inside.
if inner.is_empty() {
return false;
}
drop_picked(c, inner);
true
});
}
/// Change with `f` (whether it is vertical, its position) the line of each ruler guide of `layer`
/// and of its sublayers that [`picked_in_layers`] picked (`held`), in the order they lie in. Only
/// the layers holding one, and the guides, are copied, and only those layers are visited.
fn edit_picked(layer: &mut Arc<Node>, held: Picked, f: &mut impl FnMut(bool, &mut f64)) {
let Some(ch) = Arc::make_mut(layer).children_mut() else { return };
for (i, inner) in held.children {
let Some(c) = ch.get_mut(i) else { continue };
if !inner.is_empty() {
edit_picked(c, inner, f);
} else if let NodeKind::RulerGuide { vertical, pos, .. } = &mut Arc::make_mut(c).kind {
f(*vertical, pos);
}
}
}
/// `n` picked itself when it is a ruler guide by `is_guide`, else the ruler guides below it
/// ([`guides_below`]).
fn guide_or_below(n: &Node, is_guide: &impl Fn(&Node) -> bool) -> Option<Picked> {
if is_guide(n) { Some(Picked::default()) } else { guides_below(n, is_guide) }
}
/// The ruler guides below `n`, by `is_guide`: those among its members and its opacity-mask art
/// (each with nothing inside), and the members and mask art holding one further down (with what
/// they hold), or `None` when there is none. `is_guide` looks at each node below `n` once, and at
/// nothing inside a ruler guide.
fn guides_below(n: &Node, is_guide: &impl Fn(&Node) -> bool) -> Option<Picked> {
let mask = n.extras().mask.as_deref().and_then(|m| guide_or_below(&m.art, is_guide)).map(Box::new);
let children = n.children().into_iter().flatten().enumerate().filter_map(|(i, c)| guide_or_below(c, is_guide).map(|p| (i, p))).collect();
Picked { children, mask }.some()
}
/// Remove the ruler guides below `n` that [`guides_below`] `found`, in its members and its
/// opacity-mask art (`n` itself stays). Mask art that is a ruler guide becomes an empty group.
/// Only the nodes holding one are copied, and only those are visited. Returns how many went.
fn drop_guides_below(n: &mut Node, found: Picked) -> usize {
let mut gone = drop_mask_guides(n, found.mask);
if let Some(ch) = n.children_mut() {
let mut found = found.children.into_iter().peekable();
let mut next = 0;
ch.retain_mut(|c| {
let at = next;
next += 1;
let Some((_, inner)) = found.next_if(|(i, _)| *i == at) else { return true };
if inner.is_empty() {
gone += 1;
return false;
}
gone += drop_guides_below(Arc::make_mut(c), inner);
true
});
}
gone
}
/// Remove every ruler guide in the opacity-mask art of `n`. Mask art that is a ruler guide
/// becomes an empty group. Returns how many went.
fn drop_mask_guides(n: &mut Node) -> usize {
/// Remove the ruler guides `found` in the opacity-mask art of `n` ([`guides_below`]'s mask
/// part). Mask art that is a ruler guide becomes an empty group. Returns how many went.
fn drop_mask_guides(n: &mut Node, found: Option<Box<Picked>>) -> usize {
let Some(found) = found else { return 0 };
let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()) else { return 0 };
if mask.art.is_ruler_guide() {
if found.is_empty() {
mask.art = Arc::new(Node::group(mask.art.id, vec![]));
1
} else if any_guide(&mask.art) {
drop_guides_below(Arc::make_mut(&mut mask.art))
} else {
0
drop_guides_below(Arc::make_mut(&mut mask.art), *found)
}
}
/// Does layer `l` hold a ruler guide out of place: below art, in an object or in mask art, or so
/// in one of its sublayers?
fn layer_untidy(l: &Node) -> bool {
let Some(ch) = l.children() else { return false };
let start = Node::guide_run_start(ch);
l.extras().mask.as_deref().is_some_and(|m| any_guide(&m.art))
|| ch.iter().take(start).any(|c| c.is_ruler_guide() || if c.is_layer() { layer_untidy(c) } else { any_guide(c) })
/// The ruler guides, by `is_guide`, that layer `l` holds out of place, or `None` when it holds
/// none: those below art (each with nothing inside), those in its mask art and in its objects
/// ([`guides_below`]), and its sublayers holding one out of place (with what they hold).
/// `is_guide` looks at each node once; the guides at the end of a layer are in place and are
/// not looked at.
fn untidy(l: &Node, is_guide: &impl Fn(&Node) -> bool) -> Option<Picked> {
let ch = l.children()?;
let mask = l.extras().mask.as_deref().and_then(|m| guide_or_below(&m.art, is_guide)).map(Box::new);
let children = ch
.iter()
.enumerate()
.take(Node::guide_run_start(ch))
.filter_map(|(i, c)| {
let found = if is_guide(c) {
Some(Picked::default())
} else if c.is_layer() {
untidy(c, is_guide)
} else {
guides_below(c, is_guide)
};
found.map(|p| (i, p))
})
.collect();
Picked { children, mask }.some()
}
/// [`Document::tidy_ruler_guides`] for layer `l`. Returns how many guides were removed.
fn tidy_layer(l: &mut Node) -> usize {
let mut gone = drop_mask_guides(l);
/// [`Document::tidy_ruler_guides`] for layer `l`, whose guides out of place [`untidy`] `found`.
/// Only the nodes holding one are copied, and only those are visited. Returns how many guides
/// were removed.
fn tidy_layer(l: &mut Node, found: Picked) -> usize {
let mut gone = drop_mask_guides(l, found.mask);
let Some(ch) = l.children_mut() else { return gone };
for c in ch.iter_mut() {
if c.is_layer() {
if layer_untidy(c) {
gone += tidy_layer(Arc::make_mut(c));
}
} else if !c.is_ruler_guide() && any_guide(c) {
gone += drop_guides_below(Arc::make_mut(c));
let mut below_art = false;
for (i, inner) in found.children {
let Some(c) = ch.get_mut(i) else { continue };
if inner.is_empty() {
below_art = true;
} else if c.is_layer() {
gone += tidy_layer(Arc::make_mut(c), inner);
} else {
gone += drop_guides_below(Arc::make_mut(c), inner);
}
}
if ch.iter().take(Node::guide_run_start(ch)).any(|c| c.is_ruler_guide()) {
if below_art {
let (guides, art): (Vec<_>, Vec<_>) = std::mem::take(ch).into_iter().partition(|c| c.is_ruler_guide());
*ch = art;
ch.extend(guides);
@@ -698,3 +775,286 @@ impl std::fmt::Debug for GuideCache {
f.write_str("GuideCache")
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Appearance, OpacityMask, Symbol};
use std::cell::Cell;
use vectorcraft_geom::shapes;
/// The sublayers in [`nested`]'s chain: with the top-level layer around them and the objects in
/// the innermost, the deepest a document goes ([`crate::MAX_DEPTH`]).
const CHAIN: u64 = 30;
fn rect(id: u64) -> Arc<Node> {
Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()))
}
fn guide(id: u64, artboard: Option<u32>) -> Arc<Node> {
Arc::new(Node::new(NodeId(id), NodeKind::RulerGuide { vertical: false, pos: id as f64, artboard }))
}
fn group(id: u64, children: Vec<Arc<Node>>) -> Arc<Node> {
Arc::new(Node::group(NodeId(id), children))
}
/// `n` with `art` as its opacity-mask art.
fn masked(n: Arc<Node>, art: Arc<Node>) -> Arc<Node> {
let mut n = (*n).clone();
n.extras_mut().mask = Some(Box::new(OpacityMask { art, clip: true, invert: false, disabled: false, linked: true }));
Arc::new(n)
}
/// A sublayer like a new document's first layer, holding `children`.
fn sublayer(id: u64, children: Vec<Arc<Node>>) -> Arc<Node> {
let mut l = (*Document::new(1.0, 1.0).layers[0]).clone();
l.id = NodeId(id);
if let Some(ch) = l.children_mut() {
*ch = children;
}
Arc::new(l)
}
/// A document whose first layer holds `children`.
fn doc(children: Vec<Arc<Node>>) -> Document {
let mut d = Document::new(100.0, 100.0);
if let Some(ch) = d.layers.first_mut().and_then(|l| Arc::make_mut(l).children_mut()) {
*ch = children;
}
d
}
/// The ids of the nodes in the layers, in tree order.
fn ids(d: &Document) -> Vec<u64> {
fn walk(n: &Node, out: &mut Vec<u64>) {
out.push(n.id.0);
for c in n.children().into_iter().flatten() {
walk(c, out);
}
}
let mut out = vec![];
for l in &d.layers {
walk(l, &mut out);
}
out
}
/// [`CHAIN`] sublayers, each inside the one before and holding an object, a canvas guide and a
/// guide of artboard 7 (the innermost: object 150, guides 200 and 201). Beside the chain, a
/// sublayer with a canvas guide only. Returns the document and that sublayer.
fn nested() -> (Document, Arc<Node>) {
let mut chain = sublayer(100, vec![rect(150), guide(200, None), guide(201, Some(7))]);
for depth in 1..CHAIN {
chain = sublayer(100 + depth, vec![rect(600 + depth), chain, guide(300 + depth * 2, None), guide(301 + depth * 2, Some(7))]);
}
let still = sublayer(500, vec![rect(502), guide(501, None)]);
(doc(vec![chain, Arc::clone(&still)]), still)
}
/// How many children the layers of [`nested`] hold: the first layer's 2, the untouched
/// sublayer's 2, the innermost sublayer's 3 and 4 in each sublayer around it.
const NESTED_CHILDREN: usize = 2 + 2 + 3 + (CHAIN as usize - 1) * 4;
fn on_artboard_7(n: &Node) -> bool {
matches!(n.kind, NodeKind::RulerGuide { artboard: Some(7), .. })
}
#[test]
fn removing_guides_looks_at_each_child_of_nested_layers_once() {
let (mut d, still) = nested();
assert!(!d.clone().limit_depth(), "the chain is as deep as a document goes");
let mut deeper = doc(vec![sublayer(999, d.layers[0].children().cloned().unwrap_or_default())]);
assert!(deeper.limit_depth(), "a document nested deeper is brought within the cap when it is read");
let mut whole = d.clone();
let looked = Cell::new(0_usize);
let pick = |n: &Node| {
looked.set(looked.get() + 1);
on_artboard_7(n)
};
let held = picked_in_layers(&d.layers[0], &pick).unwrap();
assert_eq!(looked.get(), NESTED_CHILDREN, "each child of the layers is looked at once");
drop_picked(&mut d.layers[0], held);
assert_eq!(looked.get(), NESTED_CHILDREN, "removing looks at nothing again");
assert!(d.layers[0].children().is_some_and(|c| Arc::ptr_eq(&c[1], &still)), "a sublayer with nothing to remove is not copied");
// The command's own entry point removes the same guides.
let before = whole.clone();
let mut sel = Selection::default();
sel.set_guides([NodeId(200), NodeId(201), NodeId(501)]);
sel.objects.push(NodeId(150));
sel.key_guide = Some(NodeId(201));
assert_eq!(whole.retain_guides(&mut sel, |g| g.artboard != Some(7)), CHAIN as usize);
assert_eq!(ids(&whole), ids(&d));
assert_eq!(ids(&whole).len(), ids(&before).len() - CHAIN as usize);
assert!(whole.ruler_guides().iter().all(|g| g.artboard.is_none()));
assert_eq!(whole.ruler_guides().len(), CHAIN as usize + 1);
assert_eq!((sel.objects.as_slice(), sel.guides.as_slice(), sel.key_guide), (&[NodeId(150)][..], &[NodeId(200), NodeId(501)][..], None));
assert!(whole.layers[0].children().is_some_and(|c| Arc::ptr_eq(&c[1], &still)));
// The document as it was (an undo step's copy) still holds every guide.
assert_eq!(before.ruler_guides().len(), CHAIN as usize * 2 + 1);
// Saving the guides as a list, and removing a layer but not its guides, take the guides
// out of the nested layers too.
let mut saved = before.clone();
saved.guides_to_saved();
assert_eq!(saved.saved_guides, before.ruler_guides());
assert_eq!(ids(&saved).len(), 1 + CHAIN as usize * 2 + 2);
assert!(saved.layers[0].children().is_some_and(|c| !Arc::ptr_eq(&c[1], &still) && c[1].children().is_some_and(|c| c.len() == 1)));
let mut edited = before.clone();
let chain = edited.remove_edit_layer(NodeId(100 + CHAIN - 1)).unwrap();
assert!(!chain.holds_ruler_guides());
assert_eq!(edited.ruler_guides().len(), before.ruler_guides().len(), "the removed layer's guides stay in the document");
assert_eq!(edited.guides_on(edited.layers[0].id).len(), CHAIN as usize * 2);
// Keeping every guide changes nothing and copies no layer.
let kept = whole.clone();
assert_eq!(whole.retain_guides(&mut sel, |_| true), 0);
assert!(Arc::ptr_eq(&whole.layers[0], &kept.layers[0]));
// Removing every guide leaves the objects.
assert_eq!(whole.retain_guides(&mut sel, |_| false), CHAIN as usize + 1);
assert!(whole.ruler_guides().is_empty() && sel.guides.is_empty());
assert_eq!(ids(&whole).len(), 1 + CHAIN as usize * 2 + 2);
assert_eq!(sel.objects, [NodeId(150)]);
// A document without layers, and one without guides, have nothing to remove.
let mut empty = Document::new(10.0, 10.0);
assert_eq!(empty.retain_guides(&mut sel, |_| false), 0);
empty.layers.clear();
assert_eq!(empty.retain_guides(&mut sel, |_| false), 0);
}
#[test]
fn moving_an_artboards_guides_looks_at_each_child_of_nested_layers_once() {
let (mut d, still) = nested();
let mut whole = d.clone();
let looked = Cell::new(0_usize);
let pick = |n: &Node| {
looked.set(looked.get() + 1);
on_artboard_7(n)
};
let held = picked_in_layers(&d.layers[0], &pick).unwrap();
assert_eq!(looked.get(), NESTED_CHILDREN, "each child of the layers is looked at once");
let mut seen = vec![];
edit_picked(&mut d.layers[0], held, &mut |vertical, pos: &mut f64| {
seen.push((vertical, *pos));
*pos += 9.0;
});
assert_eq!(looked.get(), NESTED_CHILDREN, "changing looks at nothing again");
// A sublayer comes before its layer's own guides, so the innermost guide is changed first.
let order: Vec<(bool, f64)> = [201.0].into_iter().chain((1..CHAIN).map(|depth| (301 + depth * 2) as f64)).map(|pos| (false, pos)).collect();
assert_eq!(seen, order, "each guide of the artboard is changed once, in the order the guides lie in");
assert!(d.layers[0].children().is_some_and(|c| Arc::ptr_eq(&c[1], &still)), "a sublayer with no guide of the artboard is not copied");
// The public moves change the same guides by the same amount.
let before = whole.clone();
whole.move_artboard_guides(7, Vec2::new(5.0, 9.0));
assert_eq!(whole, d);
assert_eq!(ids(&whole), ids(&before));
for g in whole.ruler_guides() {
let id = g.id.map_or(0, |id| id.0) as f64;
assert_eq!(g.pos, if g.artboard == Some(7) { id + 9.0 } else { id }, "guide {id}");
}
assert!(whole.layers[0].children().is_some_and(|c| Arc::ptr_eq(&c[1], &still)));
assert_eq!(before.ruler_guide(NodeId(201)).map(|g| g.pos), Some(201.0), "the document as it was keeps its guides");
whole.map_artboard_guides(7, Affine::scale(2.0));
assert_eq!(whole.ruler_guide(NodeId(201)).map(|g| g.pos), Some(420.0));
assert_eq!(whole.ruler_guide(NodeId(200)).map(|g| g.pos), Some(200.0), "a canvas guide stays");
// An artboard without guides, and a document without layers, change nothing and copy no layer.
let kept = whole.clone();
whole.move_artboard_guides(99, Vec2::new(5.0, 9.0));
assert!(Arc::ptr_eq(&whole.layers[0], &kept.layers[0]));
let mut empty = Document::new(10.0, 10.0);
empty.layers.clear();
empty.move_artboard_guides(7, Vec2::new(5.0, 9.0));
assert!(empty.layers.is_empty());
}
#[test]
fn guides_in_objects_are_found_by_looking_at_each_node_once() {
// Groups, each inside the one before and holding an object and a guide. Beside them, an
// object whose mask art holds a guide, one whose mask art is a guide, and a group with none.
let mut chain = group(100, vec![rect(150), guide(200, None)]);
for depth in 1..CHAIN {
chain = group(100 + depth, vec![rect(600 + depth), chain, guide(300 + depth, None)]);
}
let still = group(700, vec![rect(701)]);
let root = group(
1,
vec![chain, masked(rect(800), group(801, vec![guide(802, None), rect(803)])), masked(rect(810), guide(811, None)), Arc::clone(&still)],
);
let looked = Cell::new(0_usize);
let is_guide = |n: &Node| {
looked.set(looked.get() + 1);
n.is_ruler_guide()
};
// The chain's groups, objects and guides; a masked object, its mask group and the two in
// it; a masked object and its mask guide; the last group and its object.
let nodes = CHAIN as usize * 3 + 4 + 2 + 2;
let found = guides_below(&root, &is_guide).unwrap();
assert_eq!(looked.get(), nodes, "each node below the root is looked at once");
let mut cleared = (*root).clone();
assert_eq!(drop_guides_below(&mut cleared, found), CHAIN as usize + 2);
assert_eq!(looked.get(), nodes, "removing looks at nothing again");
assert!(guides_below(&cleared, &Node::is_ruler_guide).is_none());
let ch = cleared.children().unwrap();
assert!(Arc::ptr_eq(&ch[3], &still), "a group without guides is not copied");
assert_eq!(
ch[1].extras().mask.as_deref().map(|m| m.art.children().map(|c| c.iter().map(|c| c.id.0).collect::<Vec<_>>())),
Some(Some(vec![803]))
);
assert_eq!(ch[2].extras().mask.as_deref().map(|m| (m.art.id, m.art.children().map(Vec::len))), Some((NodeId(811), Some(0))));
// Opening a file removes the same guides from an object on a layer and from a symbol's art.
let mut d = doc(vec![Arc::clone(&root), guide(900, None)]);
d.symbols = vec![Symbol { name: "s".into(), art: Arc::clone(&root), dynamic: false }];
assert_eq!(d.tidy_ruler_guides(), (CHAIN as usize + 2) * 2);
assert_eq!(d.layers[0].children().map(|c| (*c[0]).clone()), Some(cleared.clone()));
assert_eq!(*d.symbols[0].art, cleared);
assert_eq!(d.ruler_guides().iter().map(|g| g.id).collect::<Vec<_>>(), [Some(NodeId(900))]);
}
#[test]
fn guides_out_of_place_are_found_by_looking_at_each_node_once() {
// Sublayers, each inside the one before, with their guides in place; the innermost also
// holds a guide below its art. Beside them, a group holding a guide, a sublayer with its
// guide in place, and a sublayer whose mask art holds a guide.
let mut chain = sublayer(100, vec![guide(200, None), rect(150), guide(201, None)]);
for depth in 1..CHAIN {
chain = sublayer(100 + depth, vec![rect(600 + depth), chain, guide(300 + depth, None)]);
}
let still = sublayer(500, vec![rect(502), guide(501, None)]);
let with_mask = masked(sublayer(510, vec![rect(513)]), group(511, vec![guide(512, None)]));
let mut d = doc(vec![chain, group(700, vec![rect(701), guide(702, None)]), Arc::clone(&still), with_mask, guide(900, None)]);
let mut whole = d.clone();
let looked = Cell::new(0_usize);
let is_guide = |n: &Node| {
looked.set(looked.get() + 1);
n.is_ruler_guide()
};
// Below the guides at the end of each layer: the first layer's 4, the group's 2, the
// untouched sublayer's 1, the masked sublayer's mask group, its guide and the object, 2 in
// the innermost sublayer and 2 in each sublayer around it.
let nodes = 4 + 2 + 1 + 3 + 2 + (CHAIN as usize - 1) * 2;
let found = untidy(&d.layers[0], &is_guide).unwrap();
assert_eq!(looked.get(), nodes, "each node below the guides in place is looked at once");
assert_eq!(tidy_layer(Arc::make_mut(&mut d.layers[0]), found), 2);
assert_eq!(looked.get(), nodes, "tidying looks at nothing again");
assert!(d.layers[0].children().is_some_and(|c| Arc::ptr_eq(&c[2], &still)), "a sublayer with its guides in place is not copied");
assert!(untidy(&d.layers[0], &Node::is_ruler_guide).is_none());
// Opening a file does the same.
let before = whole.clone();
assert_eq!(whole.tidy_ruler_guides(), 2);
assert_eq!(whole, d);
let all = ids(&whole);
assert!(!all.contains(&702) && all.len() == ids(&before).len() - 1);
let innermost = whole.node(NodeId(100)).and_then(|n| n.children()).map(|c| c.iter().map(|c| c.id.0).collect::<Vec<_>>());
assert_eq!(innermost, Some(vec![150, 200, 201]), "a guide below art moves up to the other guides");
assert!(whole.node(NodeId(510)).is_some_and(|n| n.extras().mask.as_deref().is_some_and(|m| m.art.children().is_some_and(Vec::is_empty))));
// A tidy document is left alone, and no layer is copied.
let kept = whole.clone();
assert_eq!(whole.tidy_ruler_guides(), 0);
assert!(Arc::ptr_eq(&whole.layers[0], &kept.layers[0]));
}
}
+8
View File
@@ -363,6 +363,14 @@ pub struct SeriesPaint {
/// Object blend mode of each path directly in the series group, as [`Self::opacity`]. Absent: Normal.
#[serde(skip_serializing_if = "Option::is_none")]
pub blend: Option<vectorcraft_color::BlendMode>,
/// A gradient in [`Self::fill`] is placed relative to the unit box (0, 0)–(1, 1), and each mark takes it on its own
/// geometric bounds. False: the gradient is in document coordinates, and every mark takes it unchanged.
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub fill_unit_box: bool,
/// A gradient in [`Self::stroke`] is placed relative to the unit box, as [`Self::fill_unit_box`], and each mark takes
/// it on its stroke's box (the geometric bounds grown by half the weight).
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub stroke_unit_box: bool,
}
/// The object rows one kind of graph label keeps ([`LabelStyles::values_rows`]): the paint, weight, opacity and blend mode
+61 -20
View File
@@ -763,33 +763,19 @@ impl Node {
children.iter().rposition(|c| !c.is_ruler_guide()).map_or(0, |i| i + 1)
}
/// Remove the ruler guides of this layer and of its sublayers. Other nodes hold none.
/// Remove the ruler guides of this layer and of its sublayers. Other nodes hold none. Only
/// layers that hold one are copied.
pub fn strip_ruler_guides(&mut self) {
if !self.holds_ruler_guides() {
return;
}
if let Some(ch) = self.children_mut() {
ch.retain(|c| !c.is_ruler_guide());
for c in ch.iter_mut().filter(|c| c.holds_ruler_guides()) {
Arc::make_mut(c).strip_ruler_guides();
}
if let Some(held) = held_guides(self, &Self::is_ruler_guide) {
strip_held(self, held);
}
}
/// Call `f` on the position (along the axis it crosses) of each ruler guide of this layer and
/// of its sublayers, with whether the guide is vertical. Only layers that hold one are copied.
pub fn map_ruler_guide_positions(&mut self, f: &mut impl FnMut(bool, &mut f64)) {
if !self.holds_ruler_guides() {
return;
}
if let Some(ch) = self.children_mut() {
for c in ch.iter_mut().filter(|c| c.is_ruler_guide() || c.holds_ruler_guides()) {
let c = Arc::make_mut(c);
match &mut c.kind {
NodeKind::RulerGuide { vertical, pos, .. } => f(*vertical, pos),
_ => c.map_ruler_guide_positions(f),
}
}
if let Some(held) = held_guides(self, &Self::is_ruler_guide) {
map_held(self, held, f);
}
}
@@ -834,6 +820,61 @@ impl Node {
}
}
/// The ruler guides a layer holds: its children that are one, by index in order (each with
/// nothing inside), and its sublayers holding one (with what they hold).
#[derive(Debug, Default)]
pub(super) struct HeldGuides(Vec<(usize, HeldGuides)>);
/// The ruler guides, by `is_guide`, that `n` holds if it is a layer, or `None` when it holds
/// none. `is_guide` looks at each child of `n` and of its sublayers once.
pub(super) fn held_guides(n: &Node, is_guide: &impl Fn(&Node) -> bool) -> Option<HeldGuides> {
if !n.is_layer() {
return None;
}
let held: Vec<_> = n
.children()
.into_iter()
.flatten()
.enumerate()
.filter_map(|(i, c)| if is_guide(c) { Some((i, HeldGuides::default())) } else { held_guides(c, is_guide).map(|h| (i, h)) })
.collect();
(!held.is_empty()).then_some(HeldGuides(held))
}
/// Remove the ruler guides of `layer` and of its sublayers that [`held_guides`] found (`held`).
/// Only the sublayers holding one are copied, and only those are visited.
pub(super) fn strip_held(layer: &mut Node, held: HeldGuides) {
let Some(ch) = layer.children_mut() else { return };
let mut held = held.0.into_iter().peekable();
let mut next = 0;
ch.retain_mut(|c| {
let at = next;
next += 1;
let Some((_, inner)) = held.next_if(|(i, _)| *i == at) else { return true };
// A sublayer holds something; a ruler guide has nothing inside.
if inner.0.is_empty() {
return false;
}
strip_held(Arc::make_mut(c), inner);
true
});
}
/// Call `f` (whether it is vertical, its position) on each ruler guide of `layer` and of its
/// sublayers that [`held_guides`] found (`held`), in the order they lie in. Only the sublayers
/// holding one, and the guides, are copied, and only those sublayers are visited.
pub(super) fn map_held(layer: &mut Node, held: HeldGuides, f: &mut impl FnMut(bool, &mut f64)) {
let Some(ch) = layer.children_mut() else { return };
for (i, inner) in held.0 {
let Some(c) = ch.get_mut(i) else { continue };
if !inner.0.is_empty() {
map_held(Arc::make_mut(c), inner, f);
} else if let NodeKind::RulerGuide { vertical, pos, .. } = &mut Arc::make_mut(c).kind {
f(*vertical, pos);
}
}
}
impl Node {
/// The Appearance panel's row for what this object's own fills and strokes paint around:
/// "Contents" for a group or layer (its members) and for an image (its pixels), "Characters"
+204
View File
@@ -598,3 +598,207 @@ fn compound_stroke_path_is_its_members_in_order() {
assert_eq!(bp.elements(), expected.elements());
assert!(!bp.elements().is_empty());
}
/// The sublayers in [`guide_layers`]'s chain, each inside the one before.
const GUIDE_CHAIN: u64 = 30;
/// How many children the layers of [`guide_layers`] hold: the layer's 6, 1 in the sublayer
/// without a guide, 2 at each of the two places the shared sublayer lies, the innermost
/// sublayer's 2 and 3 in each sublayer around it.
const GUIDE_LAYER_CHILDREN: usize = 6 + 1 + 2 * 2 + 2 + (GUIDE_CHAIN as usize - 1) * 3;
/// How many ruler guides the layers of [`guide_layers`] hold: one in each sublayer of the chain,
/// one at each place the shared sublayer lies and the layer's own.
const GUIDE_LAYER_GUIDES: usize = GUIDE_CHAIN as usize + 2 + 1;
/// A layer holding, in order: [`GUIDE_CHAIN`] sublayers, each inside the one before and holding an
/// object and a ruler guide; a sublayer with an object only; a sublayer with an object and a
/// guide; an object; that last sublayer again; and a guide. Guides differ in direction, artboard
/// and lock. Returns the layer, the sublayer without a guide and the one that lies twice.
fn guide_layers() -> (Node, Arc<Node>, Arc<Node>) {
let rect = |id| Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()));
let guide = |id: u64| {
let kind = NodeKind::RulerGuide { vertical: id.is_multiple_of(2), pos: id as f64, artboard: id.is_multiple_of(3).then_some(7) };
let mut g = Node::new(NodeId(id), kind);
g.locked = id.is_multiple_of(5);
Arc::new(g)
};
let sublayer = |id, children: Vec<Arc<Node>>| {
let mut l = Node::layer(NodeId(id), "Sub", LayerColor::Preset(1));
if let Some(ch) = l.children_mut() {
*ch = children;
}
Arc::new(l)
};
let mut chain = sublayer(100, vec![rect(150), guide(200)]);
for depth in 1..GUIDE_CHAIN {
chain = sublayer(100 + depth, vec![rect(600 + depth), chain, guide(300 + depth)]);
}
let still = sublayer(500, vec![rect(501)]);
let twice = sublayer(510, vec![rect(511), guide(512)]);
let mut layer = Node::layer(NodeId(1), "Layer", LayerColor::Preset(0));
if let Some(ch) = layer.children_mut() {
*ch = vec![chain, Arc::clone(&still), Arc::clone(&twice), rect(2), Arc::clone(&twice), guide(3)];
}
(layer, still, twice)
}
/// Whether `a` and `b` hold the same children, none of them copied.
fn same_children(a: &Node, b: &Node) -> bool {
let (a, b) = (a.children().unwrap(), b.children().unwrap());
a.len() == b.len() && a.iter().zip(b).all(|(a, b)| Arc::ptr_eq(a, b))
}
/// Stripping the ruler guides of a layer looks at each child of the layer and of its sublayers
/// once, however deep the sublayers nest. The art and its order stay, a sublayer without a guide is
/// not copied, and a copy of the layer held elsewhere keeps its guides.
#[test]
fn stripping_ruler_guides_looks_at_each_child_of_nested_layers_once() {
use std::cell::Cell;
let (whole, still, twice) = guide_layers();
let ids = |n: &Node| {
let mut out = vec![];
n.walk(&mut |c| out.push(c.id));
out
};
let mut art = vec![];
whole.walk(&mut |c| {
if !c.is_ruler_guide() {
art.push(c.id);
}
});
assert_eq!(ids(&whole).len(), art.len() + GUIDE_LAYER_GUIDES);
let mut n = whole.clone();
let looked = Cell::new(0_usize);
let pick = |c: &Node| {
looked.set(looked.get() + 1);
c.is_ruler_guide()
};
let held = super::ops::held_guides(&n, &pick).unwrap();
assert_eq!(looked.get(), GUIDE_LAYER_CHILDREN, "each child of the layers is looked at once");
super::ops::strip_held(&mut n, held);
assert_eq!(looked.get(), GUIDE_LAYER_CHILDREN, "removing looks at nothing again");
assert_eq!(ids(&n), art, "the art stays, in its order");
let ch = n.children().unwrap();
assert!(Arc::ptr_eq(&ch[1], &still), "a sublayer without a guide is not copied");
assert!(Arc::ptr_eq(&ch[3], &whole.children().unwrap()[3]), "an object is not copied");
assert!(!Arc::ptr_eq(&ch[2], &twice) && !Arc::ptr_eq(&ch[4], &twice) && !Arc::ptr_eq(&ch[2], &ch[4]));
assert_eq!(
(ch[2].children().map(Vec::len), ch[4].children().map(Vec::len)),
(Some(1), Some(1)),
"a sublayer lying twice is stripped at both places"
);
// The copies held elsewhere (an undo step's, say) keep their guides.
assert_eq!(twice.children().map(Vec::len), Some(2));
assert_eq!(ids(&whole).len(), art.len() + GUIDE_LAYER_GUIDES);
// The method strips the same guides.
let mut same = whole.clone();
same.strip_ruler_guides();
assert_eq!(same, n);
assert!(Arc::ptr_eq(&same.children().unwrap()[1], &still));
// With no guide left there is nothing to remove, and nothing is copied.
let before = n.clone();
n.strip_ruler_guides();
assert!(same_children(&n, &before));
let mut empty = Node::layer(NodeId(900), "Empty", LayerColor::Preset(0));
empty.strip_ruler_guides();
assert_eq!(empty.children().map(Vec::len), Some(0));
// Only a layer holds ruler guides: a group is left as it is, on its own and in a layer.
let mut group = Node::group(NodeId(901), vec![Arc::clone(&twice)]);
assert!(super::ops::held_guides(&group, &Node::is_ruler_guide).is_none());
group.strip_ruler_guides();
assert!(Arc::ptr_eq(&group.children().unwrap()[0], &twice));
let group = Arc::new(group);
let mut around = Node::layer(NodeId(902), "Around", LayerColor::Preset(0));
around.children_mut().unwrap().push(Arc::clone(&group));
around.strip_ruler_guides();
assert!(Arc::ptr_eq(&around.children().unwrap()[0], &group));
}
/// Changing the positions of the ruler guides of a layer looks at each child of the layer and of
/// its sublayers once, however deep the sublayers nest. Each guide is changed once, in the order
/// the guides lie in, and keeps everything else about it; the art is unchanged, a sublayer without
/// a guide is not copied, and a copy of the layer held elsewhere keeps its positions.
#[test]
fn mapping_ruler_guide_positions_looks_at_each_child_of_nested_layers_once() {
use std::cell::Cell;
let (whole, still, twice) = guide_layers();
let mut lines = vec![];
whole.walk(&mut |c| {
if let NodeKind::RulerGuide { vertical, pos, .. } = c.kind {
lines.push((vertical, pos));
}
});
assert_eq!(lines.len(), GUIDE_LAYER_GUIDES);
assert!(lines.iter().any(|l| l.0) && lines.iter().any(|l| !l.0), "guides in both directions");
let mut n = whole.clone();
let looked = Cell::new(0_usize);
let pick = |c: &Node| {
looked.set(looked.get() + 1);
c.is_ruler_guide()
};
let held = super::ops::held_guides(&n, &pick).unwrap();
assert_eq!(looked.get(), GUIDE_LAYER_CHILDREN, "each child of the layers is looked at once");
let mut seen = vec![];
super::ops::map_held(&mut n, held, &mut |vertical, pos| {
seen.push((vertical, *pos));
*pos = *pos * 2.0 + 1.0;
});
assert_eq!(looked.get(), GUIDE_LAYER_CHILDREN, "changing looks at nothing again");
assert_eq!(seen, lines, "each guide once, in the order the guides lie in");
// The same nodes in the same order: a guide differs in its position alone, and the art not
// at all.
let (mut was, mut now) = (vec![], vec![]);
whole.walk(&mut |c| was.push(c));
n.walk(&mut |c| now.push(c));
assert_eq!(was.len(), now.len());
for (a, b) in was.into_iter().zip(now) {
if a.is_layer() {
assert_eq!((b.id, b.is_layer(), b.children().map(Vec::len)), (a.id, true, a.children().map(Vec::len)));
continue;
}
let mut want = a.clone();
if let NodeKind::RulerGuide { pos, .. } = &mut want.kind {
*pos = *pos * 2.0 + 1.0;
}
assert_eq!(b, &want);
}
let ch = n.children().unwrap();
assert!(Arc::ptr_eq(&ch[1], &still), "a sublayer without a guide is not copied");
assert!(Arc::ptr_eq(&ch[3], &whole.children().unwrap()[3]), "an object is not copied");
assert!(!Arc::ptr_eq(&ch[2], &twice) && !Arc::ptr_eq(&ch[4], &twice) && !Arc::ptr_eq(&ch[2], &ch[4]));
// The copy held elsewhere keeps its position.
assert!(matches!(twice.children().unwrap()[1].kind, NodeKind::RulerGuide { pos, .. } if pos == 512.0));
// The method changes the same guides, each once.
let mut same = whole.clone();
let mut calls = 0;
same.map_ruler_guide_positions(&mut |_, pos| {
calls += 1;
*pos = *pos * 2.0 + 1.0;
});
assert_eq!((calls, &same), (GUIDE_LAYER_GUIDES, &n));
assert!(Arc::ptr_eq(&same.children().unwrap()[1], &still));
// A function that leaves the positions as they are is still called on each guide.
let mut kept = whole.clone();
let mut calls = 0;
kept.map_ruler_guide_positions(&mut |_, _| calls += 1);
assert_eq!((calls, &kept), (GUIDE_LAYER_GUIDES, &whole));
// A layer without a guide, an empty layer and a group: nothing to change, nothing copied.
let mut bare = whole.clone();
bare.strip_ruler_guides();
let before = bare.clone();
let mut calls = 0;
bare.map_ruler_guide_positions(&mut |_, _| calls += 1);
assert!(same_children(&bare, &before));
let mut empty = Node::layer(NodeId(900), "Empty", LayerColor::Preset(0));
empty.map_ruler_guide_positions(&mut |_, _| calls += 1);
let mut group = Node::group(NodeId(901), vec![Arc::clone(&twice)]);
group.map_ruler_guide_positions(&mut |_, _| calls += 1);
assert!(Arc::ptr_eq(&group.children().unwrap()[0], &twice));
assert_eq!(calls, 0);
}
+68
View File
@@ -3,6 +3,8 @@
//! square to it: scaling by a side handle stretches it along its own width or height. Path
//! geometry is still baked; Object ▸ Transform ▸ Reset Bounding Box sets the angle back to 0.
use std::sync::Arc;
use vectorcraft_geom::{Affine, Point, Rect, Vec2, normalize_deg, union_opt};
use crate::{Document, Node, NodeId, NodeKind, SymbolBoxes};
@@ -84,7 +86,35 @@ pub fn transformed_angle(angle: f64, a: Affine) -> f64 {
}
}
/// The turn (counter-clockwise degrees) from the boxes of art placed by a symbol instance's
/// transform `xf` to the instance's own box at `angle`: 0 while the box turns with the transform,
/// otherwise the change Reset Bounding Box made to it. Under a mirroring `xf` the instance's box can
/// stand 180° from the one `xf` gives in one step ([`transformed_angle`] keeps the angle nearer the
/// one before at each step); the turn is then 180°, so the art's boxes match the instance's.
pub fn placed_turn(angle: f64, xf: Affine) -> f64 {
let turn = normalize_deg(angle - transformed_angle(0.0, xf));
if turn.is_finite() && turn.abs() > EPS_DEG { turn } else { 0.0 }
}
impl Node {
/// Turns the box of this object, and of every object that turns with it ([`Node::transform`]:
/// its children and the art of a linked opacity mask), by `by` degrees counter-clockwise.
/// Layers have no box.
pub fn turn_boxes(&mut self, by: f64) {
if !self.is_layer() {
let a = normalize_deg(self.bbox_angle + by);
self.bbox_angle = if a.abs() <= EPS_DEG { 0.0 } else { a };
}
for c in self.children_mut().into_iter().flatten() {
Arc::make_mut(c).turn_boxes(by);
}
if let Some(m) = self.extras_if_any().and_then(|e| e.mask.as_mut())
&& m.linked
{
Arc::make_mut(&mut m.art).turn_boxes(by);
}
}
/// Bounds of this object as `a` would place it (geometric, or `visual` with its strokes),
/// without changing it, symbol instances measured by their art from `symbols`
/// ([`Node::geometric_bounds_with`]).
@@ -185,6 +215,44 @@ mod tests {
assert_eq!(transformed_angle(30.0, Affine::scale(0.0)), 30.0);
}
#[test]
fn placed_turn_is_what_reset_bounding_box_took_off_the_instance() {
let xf = Affine::translate((40.0, 10.0)) * rot(20.0) * Affine::scale_non_uniform(2.0, 0.5);
// The box turns with the transform: no turn.
assert_eq!(placed_turn(transformed_angle(0.0, xf), xf), 0.0);
assert_eq!(placed_turn(0.0, Affine::scale(3.0)), 0.0);
// Reset to 0: the placed art turns back by the 20°.
assert!(close(placed_turn(0.0, xf), -20.0));
// Mirrored: turned 170° and then flipped, the instance's box stands 180° from the box the
// whole transform gives in one step, and the art turns the half turn to match it.
let flip = Affine::scale_non_uniform(1.0, -1.0);
let flipped = flip * rot(170.0);
let stepwise = transformed_angle(transformed_angle(0.0, rot(170.0)), flip);
assert!(close(stepwise, -170.0) && close(transformed_angle(0.0, flipped), 10.0));
assert!(close(placed_turn(stepwise, flipped).abs(), 180.0));
assert!(close(normalize_deg(placed_turn(0.0, flipped) + transformed_angle(0.0, flipped)), 0.0));
// Degenerate and non-finite transforms turn nothing.
assert_eq!(placed_turn(0.0, Affine::scale(0.0)), 0.0);
assert_eq!(placed_turn(f64::NAN, xf), 0.0);
}
#[test]
fn turn_boxes_turns_children_and_linked_mask_art_but_not_layers() {
let mut d = Document::new(500.0, 500.0);
let a = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art());
let mut g = Node::group(d.alloc_id(), vec![Arc::new(a.clone())]);
g.bbox_angle = 170.0;
g.extras_mut().mask = Some(Box::new(crate::OpacityMask::new(a.clone(), true)));
let mut layer = (*d.layers[0]).clone();
layer.children_mut().unwrap().push(Arc::new(g));
layer.turn_boxes(20.0);
assert_eq!(layer.bbox_angle, 0.0);
let g = &layer.children().unwrap()[0];
assert!(close(g.bbox_angle, -170.0), "wraps to (-180, 180]");
assert!(close(g.children().unwrap()[0].bbox_angle, 20.0));
assert!(close(g.extras().mask.as_ref().unwrap().art.bbox_angle, 20.0));
}
#[test]
fn oriented_bounds_hug_a_rotated_rectangle() {
let mut d = Document::new(500.0, 500.0);
+7 -1
View File
@@ -614,6 +614,8 @@ impl NineSliceMap {
/// `n`, whose box at the natural size is `b`, drawn in each cell it reaches: a clip group of
/// the cell around a copy placed by the cell's map, all in a group with `n`'s id. `n` placed
/// by `center` when it draws symbol art ([`draws_symbol_art`]), and in [`Self::place_unclipped`].
/// The clip groups and clip paths take the angle of the cell map that places them. The group
/// and each copy keep `n`'s box angle, turned by the map that places them.
///
/// The drop shadows, outer glows and blurs ([`PAINTED_EFFECTS`]) at the end of `n`'s own
/// effects, after its last other visible effect, go on that group with its opacity, blending
@@ -647,11 +649,15 @@ impl NineSliceMap {
area.transform(local);
let mut clip = Node::new(NodeId(0), NodeKind::Path { path: area, rule: FillRule::NonZero, live: None, clipping: true, guide: false });
clip.appearance = Appearance::default().into();
clip.bbox_angle = crate::orient::transformed_angle(0.0, local);
let copy = transformed(n, local * self.natural);
cells.push(Arc::new(Node::new(NodeId(0), NodeKind::Group { children: vec![Arc::new(clip), Arc::new(copy)], clip: true })));
let mut cell = Node::new(NodeId(0), NodeKind::Group { children: vec![Arc::new(clip), Arc::new(copy)], clip: true });
cell.bbox_angle = crate::orient::transformed_angle(0.0, local);
cells.push(Arc::new(cell));
}
}
let mut out = Node::group(n.id, cells);
out.bbox_angle = crate::orient::transformed_angle(n.bbox_angle, center);
out.visible = n.visible;
out.locked = n.locked;
out.name = n.name.clone();
+50 -4
View File
@@ -2,14 +2,15 @@
//! symbol keeps appearance changes of its own to objects in the symbol's art, while the art stays
//! the symbol's. Editing the symbol reshapes every instance and each keeps its changes; Reset drops
//! them. The changes are stored on the instance ([`crate::node::NodeExtras::symbol_overrides`]) and
//! applied wherever an instance is drawn or exported ([`dynamic_art`]).
//! applied wherever an instance is drawn or exported ([`dynamic_art`]), and an instance's fill
//! stains the art after them ([`instance_art`]).
use std::sync::Arc;
use serde::{Deserialize, Serialize};
use vectorcraft_color::{BlendMode, Paint};
use vectorcraft_color::{BlendMode, Color, Paint};
use crate::{Node, NodeKind};
use crate::{AppearanceItem, Node, NodeKind};
/// Deepest object an override may name: groups nested this deep in the symbol's art.
pub const MAX_PATH_DEPTH: usize = 64;
@@ -150,6 +151,52 @@ pub fn dynamic_art(art: &Node, inst: &Node) -> Node {
a
}
/// Mix every solid paint under `n` towards `color` by `amount` (0..1): the Symbol Stainer.
pub fn tint_node(n: &mut Node, color: &Color, amount: f32) {
let amount = amount.clamp(0.0, 1.0);
for it in &mut n.appearance.items {
let p = match it {
AppearanceItem::Fill(f) => &mut f.paint,
AppearanceItem::Stroke(s) => &mut s.paint,
};
if let Paint::Solid { color: c, .. } = p {
*p = Paint::solid(c.lerp(color, amount));
}
}
if let NodeKind::Text(t) = &mut n.kind {
for r in &mut t.runs {
for p in [&mut r.style.fill, &mut r.style.stroke] {
if let Paint::Solid { color: c, .. } = p {
*p = Paint::solid(c.lerp(color, amount));
}
}
}
}
if let Some(ch) = n.children_mut() {
for c in ch.iter_mut() {
tint_node(Arc::make_mut(c), color, amount);
}
}
}
/// The stain instance `inst` puts on its symbol's art: its visible fill color and that fill's
/// opacity (how far the art mixes towards it). `None` for an unstained instance, including one
/// whose fill has an opacity of 0, so its art keeps its paints and their swatch links.
pub fn stain(inst: &Node) -> Option<(Color, f32)> {
let f = inst.appearance.fill().filter(|f| f.visible && f.opacity > 0.0)?;
Some((f.paint.color()?, f.opacity))
}
/// A symbol's art for instance `inst`, as the canvas draws it: with the instance's own appearance
/// changes to it ([`dynamic_art`]), stained by the instance's fill ([`stain`]).
pub fn instance_art(art: &Node, inst: &Node) -> Node {
let mut a = dynamic_art(art, inst);
if let Some((c, amount)) = stain(inst) {
tint_node(&mut a, &c, amount);
}
a
}
/// Keep the overrides that name an object of `art` (a symbol's new art), dropping the rest.
pub fn retain_parts(overrides: &mut Vec<SymbolOverride>, art: &Node) {
overrides.retain(|o| part(art, &o.path).is_some());
@@ -159,7 +206,6 @@ pub fn retain_parts(overrides: &mut Vec<SymbolOverride>, art: &Node) {
mod tests {
use super::*;
use crate::{Appearance, NodeId};
use vectorcraft_color::Color;
use vectorcraft_geom::{Rect, shapes};
fn square(id: u64) -> Arc<Node> {
+3 -2
View File
@@ -523,13 +523,14 @@ fn color_mask_keys<'a>(n: &'a Node, out: &mut Vec<&'a str>) {
/// [`adjust`] for export and Expand Appearance: recoloured embedded images become new images in
/// `d` (named by their content), and a symbol instance stands for its symbol's art: `symbol_art`
/// when given, otherwise the symbol's art with the instance's own appearance changes.
/// when given, otherwise the symbol's art with the instance's own appearance changes, stained by
/// the instance's fill ([`vectorcraft_doc::symbol_overrides::instance_art`]).
pub fn adjust_in_document(d: &mut Document, n: &Node, symbol_art: Option<Node>) -> Option<Node> {
let art;
let src = match &n.kind {
NodeKind::SymbolInstance { symbol, .. } if has_adjustment(n) => {
let symbol = symbol_art
.or_else(|| d.symbols.iter().find(|s| s.name == *symbol).map(|s| vectorcraft_doc::symbol_overrides::dynamic_art(&s.art, n)));
.or_else(|| d.symbols.iter().find(|s| s.name == *symbol).map(|s| vectorcraft_doc::symbol_overrides::instance_art(&s.art, n)));
art = crate::reshape::as_art(Some(d), n, symbol.as_ref())?;
&art
}
+10 -5
View File
@@ -29,7 +29,7 @@ use crate::group::{has_own_paint, paints};
use crate::reshape::{as_art, geometry_effects, glyph_outlines, outline_nested_text, reshape_leaves};
use crate::{
GeomContext, adjust_in_document, apply_geometry_carrying, crop_marks_art, evaluate_container, has_adjustment, has_crop_marks, has_geometry,
has_item_geometry, has_pathfinder, is_pathfinder, merged_params, needs_outline, outline_text, reshape,
has_instance_row_raster, has_item_geometry, has_pathfinder, is_pathfinder, merged_params, needs_outline, outline_text, reshape,
};
fn item_effects(item: &AppearanceItem) -> &[vectorcraft_doc::Effect] {
@@ -58,6 +58,7 @@ pub fn needs_bake(n: &Node) -> bool {
|| has_geometry(&n.appearance.effects)
|| n.projection().is_some()
|| n.appearance.items.iter().any(|i| has_geometry(item_effects(i)))
|| has_instance_row_raster(n)
|| n.children().is_some_and(|ch| ch.iter().any(|c| needs_bake(c)))
}
@@ -142,15 +143,19 @@ fn bake_node(d: &mut Document, n: &Node) -> Option<Node> {
}
// Type, images, symbol instances and live objects: reshaped through their outlines, and so are
// type whose own fills or strokes have geometry effects and images whose own fills or strokes
// paint a shape ([`has_item_geometry`]). Type that Transform effects only move and copy stays
// type, moved to each place.
if needs_outline(n) && (has_geometry(&n.appearance.effects) || n.projection().is_some() || has_item_geometry(n)) {
// paint a shape ([`has_item_geometry`]), and symbol instances whose active fill or stroke has a
// raster effect, which the fills and strokes of their art then carry
// ([`has_instance_row_raster`]). Type that Transform effects only move and copy stays type,
// moved to each place.
if needs_outline(n) && (has_geometry(&n.appearance.effects) || n.projection().is_some() || has_item_geometry(n) || has_instance_row_raster(n)) {
if let Some(m) = moved_type_group(n) {
return Some(bake_pieces(d, m));
}
// A symbol instance's art as the canvas draws it: with its own appearance changes, stained
// by its fill.
let symbol = match &n.kind {
NodeKind::SymbolInstance { symbol, .. } => {
d.symbols.iter().find(|s| s.name == *symbol).map(|s| vectorcraft_doc::symbol_overrides::dynamic_art(&s.art, n))
d.symbols.iter().find(|s| s.name == *symbol).map(|s| vectorcraft_doc::symbol_overrides::instance_art(&s.art, n))
}
_ => None,
};
+40
View File
@@ -59,6 +59,46 @@ fn object_effects_become_geometry_and_raster_effects_stay() {
assert_eq!(m.appearance.effects[0].id, "stylize.dropShadow");
}
/// The fill colors of the paths under the layers of `d`, in paint order.
fn path_fills(d: &Document) -> Vec<Color> {
let mut out = vec![];
d.walk(|n| {
if matches!(n.kind, NodeKind::Path { .. })
&& let Some(c) = n.appearance.fill_paint().color()
{
out.push(c);
}
});
out
}
/// A symbol instance half stained red is baked in its stained colors, as the canvas draws it:
/// moved by a Transform effect, and recolored by a color adjustment (Invert Colors) after the
/// stain.
#[test]
fn a_stained_instance_is_baked_in_its_stained_colors() {
let blue = Color::rgb8(30, 90, 220);
let art = Node::path(NodeId(2), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(Paint::solid(blue), Paint::None, 0.0));
let mut inst = Node::new(NodeId(50), NodeKind::SymbolInstance { symbol: "Mark".into(), xf: vectorcraft_geom::Affine::translate((20.0, 20.0)) });
inst.appearance = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0).into();
inst.appearance.items.retain(|i| i.is_fill());
if let vectorcraft_doc::AppearanceItem::Fill(f) = &mut inst.appearance.items[0] {
f.opacity = 0.5;
}
let stained = vectorcraft_doc::symbol_overrides::instance_art(&art, &inst).appearance.fill_paint().color().unwrap();
assert_ne!(stained.to_hex(), blue.to_hex());
let [r, g, b] = stained.to_rgb();
let inverted = Color::rgb(1.0 - r, 1.0 - g, 1.0 - b);
for (id, params, want) in [("distort.transform", json!({"moveH": 30.0}), stained), (crate::addons::color::INVERT, json!({}), inverted)] {
let mut n = inst.clone();
n.appearance.effects.push(fx(id, params));
let mut d = doc_with(n);
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Mark".into(), art: Arc::new(art.clone()) });
let fills = path_fills(&bake_document(&d).unwrap());
assert_eq!(fills.iter().map(Color::to_hex).collect::<Vec<_>>(), [want.to_hex()], "{id}");
}
}
#[test]
fn a_baked_transform_moves_a_placed_gradient_with_the_path() {
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
+3 -2
View File
@@ -80,8 +80,9 @@ pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks};
pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace};
pub use raster::{RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, without_geometry};
pub use reshape::{
SYMBOL_ART_MAX_NODES, expand_outlined, follows_image_pixels, gives_image_shape, has_gradient_copies, has_item_geometry, has_painted_effects,
has_transform_art, has_transform_copies, has_transform_options, image_paint, needs_outline, outline_art, outline_text, reshape,
SYMBOL_ART_MAX_NODES, expand_outlined, follows_image_pixels, gives_image_shape, has_gradient_copies, has_instance_row_raster, has_item_geometry,
has_painted_effects, has_transform_art, has_transform_copies, has_transform_options, image_paint, needs_outline, outline_art, outline_text,
reshape,
};
pub use revolve::{
CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in,
+10 -3
View File
@@ -23,15 +23,22 @@ pub fn text_outliner() -> Outliner<'static> {
/// Type outlined, or a symbol instance as its symbol's art (from `doc`) placed by the instance,
/// through the symbol's 9-slice guides when it has them ([`Document::place_symbol_art`], `None`
/// past its object limit). As an [`OutlineHook`](crate::OutlineHook), it gives compound shapes and
/// Pathfinder operations the symbol instances among their members.
/// Pathfinder operations the symbol instances among their members. The group around the art takes
/// the instance's box angle, and the art's boxes turn with it, as Break Link turns them.
pub fn outline_object(doc: Option<&Document>, n: &Node) -> Option<Node> {
match &n.kind {
NodeKind::SymbolInstance { symbol, xf } => {
let doc = doc?;
let sym = doc.symbols.iter().find(|s| s.name == *symbol)?;
let art = vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, n);
let art = doc.place_symbol_art(symbol, &art, *xf)?;
Some(Node::group(n.id, vec![Arc::new(art)]))
let mut art = doc.place_symbol_art(symbol, &art, *xf)?;
let turn = vectorcraft_doc::orient::placed_turn(n.bbox_angle, *xf);
if turn != 0.0 {
art.turn_boxes(turn);
}
let mut out = Node::group(n.id, vec![Arc::new(art)]);
out.bbox_angle = n.bbox_angle;
Some(out)
}
_ => outline_text(n),
}
+29 -16
View File
@@ -162,15 +162,26 @@ fn active_stroke(n: &Node) -> Option<&vectorcraft_doc::StrokeLayer> {
n.appearance.stroke().filter(|s| s.visible && s.opacity > 0.0)
}
/// The visible geometry effects in `fx`, in order.
fn geometry_of(fx: &[Effect]) -> Vec<Effect> {
fx.iter().filter(|e| e.visible && is_geometry(&e.id)).cloned().collect()
/// Is `n` a symbol instance whose active fill or stroke has a visible raster effect (a shadow, glow,
/// blur, feather or other painted effect, [`crate::is_raster`])? Its art takes that effect on each
/// fill or stroke in it that paints ([`add_instance_row_effects`]), and draws it there.
pub fn has_instance_row_raster(n: &Node) -> bool {
let raster = |fx: &[Effect]| fx.iter().any(|e| e.visible && crate::is_raster(&e.id));
matches!(n.kind, NodeKind::SymbolInstance { .. })
&& (active_fill(n).is_some_and(|f| raster(&f.effects)) || active_stroke(n).is_some_and(|s| raster(&s.effects)))
}
/// `art`, the art symbol instance `n` places, with the visible geometry effects of `n`'s active
/// fill added after the effects of every fill in it that paints, and those of its active stroke
/// after the effects of every stroke in it that paints ([`active_fill`], [`active_stroke`]). Each
/// fill or stroke keeps its paint, and the others keep their shapes. Live objects in it that are
/// The visible geometry and raster effects in `fx`, in order: those a symbol instance's active fill
/// or stroke passes on to its art.
fn row_effects_of(fx: &[Effect]) -> Vec<Effect> {
fx.iter().filter(|e| e.visible && (is_geometry(&e.id) || crate::is_raster(&e.id))).cloned().collect()
}
/// `art`, the art symbol instance `n` places, with the visible geometry and raster effects of
/// `n`'s active fill added after the effects of every fill in it that paints, and those of its
/// active stroke after the effects of every stroke in it that paints ([`active_fill`],
/// [`active_stroke`]): a Drop Shadow on the instance's fill shadows each filled shape in the art.
/// Each fill or stroke keeps its paint, and the others keep their shapes. Live objects in it that are
/// reached are evaluated first (with the symbols of `doc`), so the effects reshape what they draw.
/// Clip groups' clipping paths, guides and the art of opacity masks keep their shapes. A symbol
/// instance in the art takes the effects on its own active fill or stroke, or on a new fill or
@@ -180,8 +191,8 @@ fn geometry_of(fx: &[Effect]) -> Vec<Effect> {
/// instance in the art takes them.
fn add_instance_row_effects(doc: Option<&Document>, n: &Node, art: &mut Node) {
let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return };
let fill = active_fill(n).map_or(vec![], |f| geometry_of(&f.effects));
let stroke = active_stroke(n).map_or(vec![], |s| geometry_of(&s.effects));
let fill = active_fill(n).map_or(vec![], |f| row_effects_of(&f.effects));
let stroke = active_stroke(n).map_or(vec![], |s| row_effects_of(&s.effects));
if !fill.is_empty() || !stroke.is_empty() {
add_row_effects(doc, symbol, art, &fill, &stroke);
}
@@ -526,8 +537,8 @@ fn with_id(art: &Node, id: NodeId) -> Node {
/// a symbol instance as `symbol_art` (the symbol's art, stained as the caller draws it) placed by
/// the instance's transform (through the symbol's 9-slice guides in `doc`, when it has them), as
/// the art its members draw when the instance has geometry effects of its own
/// ([`crate::group::members_as_drawn`]), its fills and strokes carrying the geometry effects of the
/// instance's active fill and stroke ([`add_instance_row_effects`]).
/// ([`crate::group::members_as_drawn`]), its fills and strokes carrying the geometry and raster
/// effects of the instance's active fill and stroke ([`add_instance_row_effects`]).
/// `None` for other kinds (images, paths, containers), and for an instance whose art placed
/// through the guides could hold more than [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects. A Repeat counts the Repeats in the art of
/// `doc`'s symbols that its instances show toward its instance budget.
@@ -709,12 +720,14 @@ pub(crate) fn outline_nested_text(doc: Option<&Document>, n: &mut Node, clipping
/// reshaped with it, and keep their effects from their first Convert to Shape or Outline Object
/// on. The result is a group with `n`'s id, name, visibility, transparency, opacity mask
/// and remaining (raster) effects; `None` when `n` has no visible geometry effect, no perspective
/// and is not type or an image with a fill or stroke of its own that [`has_item_geometry`] counts,
/// or has no art (a symbol instance without `symbol_art`). A path with [`has_transform_art`] is
/// always reshaped. The fills and strokes in the art whose own Transform effects reach their
/// appearance become objects of their own ([`transform_items`]).
/// and is not type or an image with a fill or stroke of its own that [`has_item_geometry`] counts
/// or a symbol instance whose active fill or stroke has a raster effect
/// ([`has_instance_row_raster`]), or has no art (a symbol instance without `symbol_art`). A path
/// with [`has_transform_art`] is always reshaped. The fills and strokes in the art whose own
/// Transform effects reach their appearance become objects of their own ([`transform_items`]).
pub fn reshape(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option<Node> {
if !has_transform_art(n) && ((geometry_effects(n).is_empty() && n.projection().is_none() && !has_item_geometry(n)) || !needs_outline(n)) {
let own = !geometry_effects(n).is_empty() || n.projection().is_some() || has_item_geometry(n) || has_instance_row_raster(n);
if !has_transform_art(n) && (!own || !needs_outline(n)) {
return None;
}
as_art(doc, n, symbol_art)
+79 -41
View File
@@ -7,7 +7,7 @@ use vectorcraft_doc::color::{BlendMode, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeId, NodeKind, OpacityMask};
use vectorcraft_geom::{BezPath, FillRule, PathData, Point, Rect, Vec2};
use vectorcraft_pathops::BoolOp;
use vectorcraft_three_d::{Bevel, BevelShape, DepthPlane, Extrude, Facet, Inflate, MAX_OBJECT_FACES, Mesh, PlanarFace, View};
use vectorcraft_three_d::{Bevel, BevelShape, DepthPlane, Extrude, Facet, Inflate, MAX_OBJECT_FACES, Mesh, MeshedSolid, PlanarFace, View};
#[cfg(test)]
use vectorcraft_doc::color::Color;
@@ -429,6 +429,12 @@ const MAX_MEMBERS: usize = 4096;
/// normals): past it the object is too complex to export.
const MAX_MESH_TRIANGLES: usize = 2_000_000;
/// The most facets of solid colors under colored lights that one 3D effect draws as faces of their
/// own, to go in one order with other solids' faces. Each such face is about 16 nodes, a composite
/// of a whole surface about 6 per facet, so at this count the faces hold about as many nodes as the
/// composites do at the paint-copy allowance. Past it those solids draw as one composite each.
const MAX_FACE_COMPOSITES: usize = 30_720;
/// The shapes a 3D effect on group or layer `n` builds its solids from: every visible path,
/// compound path and type in it (after [`resolve`] gives it the art of its symbol instances, blends
/// and clipping groups), at any depth of its groups, each through its own geometry
@@ -535,9 +541,12 @@ pub fn validate_three_d_params(id: &str, p: &Value) -> Result<(), String> {
}
/// One surface: each facet a path shaded from `paint`, as a group with the paint's opacity and
/// blend mode (so overlapping facets don't add up their transparency).
fn surface(n: &Node, facets: Vec<Facet>, paint: &Paint, opacity: f32, blend: BlendMode, colored: bool) -> Node {
if colored && paint.color().is_some() && facets.iter().any(|face| face.rgb_gradient.is_some()) {
/// blend mode (so overlapping facets don't add up their transparency). Under colored lights a solid
/// color with smooth facets is one composite of all its facets ([`composites_facets`]) unless
/// `faces`: then each facet is a face of its own, as in a gradient, so the faces can go in one order
/// with the faces of other solids.
fn surface(n: &Node, facets: Vec<Facet>, paint: &Paint, opacity: f32, blend: BlendMode, colored: bool, faces: bool) -> Node {
if !faces && composites_facets(&facets, paint, colored) {
let mut group = crate::lighting::solid_surface(n.id, &facets, paint);
group.opacity = opacity;
group.blend = blend;
@@ -583,6 +592,12 @@ fn surface(n: &Node, facets: Vec<Facet>, paint: &Paint, opacity: f32, blend: Ble
group
}
/// Is a surface of `facets` in `paint` one composite of all its facets when [`surface`] draws it
/// whole: a solid color under colored lights with smooth shading?
fn composites_facets(facets: &[Facet], paint: &Paint, colored: bool) -> bool {
colored && paint.color().is_some() && facets.iter().any(|face| face.rgb_gradient.is_some())
}
/// `item`'s paint, its opacity times `member` (the opacity of the objects it is in) and its blend.
fn paint_of(item: &AppearanceItem, member: f32) -> (Paint, f32, BlendMode) {
match item {
@@ -600,10 +615,10 @@ fn paint_ref(item: &AppearanceItem) -> &Paint {
}
/// Paint copies `surface` makes for `facets`: two per facet (fill and seam stroke), six when colored
/// lights give each facet derived paints (`lighting::solid_surface`).
/// lights give each facet derived paints (`lighting::solid_surface`, or `lighting::facet_art` for
/// each face).
fn facet_copies(facets: &[Facet], paint: &Paint, colored: bool) -> usize {
let derived = colored && paint.color().is_some() && facets.iter().any(|f| f.rgb_gradient.is_some());
facets.len().saturating_mul(if derived { 6 } else { 2 })
facets.len().saturating_mul(if composites_facets(facets, paint, colored) { 6 } else { 2 })
}
/// The area `item` paints on `path`, and the rule that fills it: the path itself for a fill, the
@@ -641,7 +656,7 @@ fn solid_parts(shapes: &[Profile], fallback: Rect) -> (Vec<Part<'_>>, Rect) {
#[cfg(test)]
thread_local! {
/// How many solids [`built_solids`] has built on this thread, for the tests.
/// How many solids [`built_solids`] and [`meshes_for`] have built on this thread, for the tests.
static SOLIDS_BUILT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
@@ -1265,8 +1280,9 @@ type ShadowAndSurfaces = (Vec<Arc<Node>>, Vec<Arc<Node>>);
/// The 3D art of one effect `fx` on `path` (already through the effects before it).
/// Rotate turns every fill and stroke, each in its own paint. Extrude & Bevel and Inflate build a
/// solid from the path for the top visible fill and one from the outline of each visible stroke,
/// each in its own paint. When every one is opaque with normal blending and no colored light makes
/// a surface one composite, their faces are drawn in one back-to-front order (where depths tie, as
/// each in its own paint. When every one is opaque with normal blending, their faces are drawn in
/// one back-to-front order, a solid color under colored lights included up to
/// [`MAX_FACE_COMPOSITES`] facets (where depths tie, as
/// for the caps turned toward the viewer, in the order of the appearance, and with caps, a shape's
/// fill walls before the faces of its covering strokes that overlap them, and its fill's faces and
/// its other strokes' faces, cut where they pass through each other ([`cut_stroke_faces`]), in the
@@ -1521,7 +1537,8 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
filled.push(Filled { at: out.len(), member, caps, opacity, blend, masked: masks_surface(&paint, colored) });
}
}
let art = if classic { classic::surface(n, f, &paint, opacity, blend, &p) } else { surface(n, f, &paint, opacity, blend, colored) };
let art =
if classic { classic::surface(n, f, &paint, opacity, blend, &p) } else { surface(n, f, &paint, opacity, blend, colored, false) };
out.push((s.scopes.as_slice(), Arc::new(art)));
}
}
@@ -1554,22 +1571,31 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
opacity >= 1.0 && blend == BlendMode::Normal
});
let closed = |shape: usize| shapes.get(shape).is_some_and(|s| holds_edge(&fx.id, &s.path));
// A solid whose surface is one composite of all its facets ([`surface`]: a solid color under
// colored lights with smooth shading) has no faces to order.
let composite = |item: &AppearanceItem, f: &[Facet]| colored && paint_ref(item).color().is_some() && f.iter().any(|f| f.rgb_gradient.is_some());
// The faces are drawn in one order (below) unless a composite draws the surfaces whole. Under
// a member's opacity mask or blending, each member's faces go in one order of their own when its
// fills and strokes are opaque, blend normally, carry no opacity mask and are not composites.
let one_order = opaque && !solids.iter().any(|(item, _, _, f, _)| composite(item, f));
// A solid color under colored lights with smooth shading draws as one composite of its facets
// ([`surface`]) unless its facets go in one order with other solids' faces. They do while all
// such facets together number at most MAX_FACE_COMPOSITES.
let composite = |item: &AppearanceItem, f: &[Facet]| composites_facets(f, paint_ref(item), colored);
let colored_faces: usize = solids.iter().filter(|(item, _, _, f, _)| composite(item, f)).map(|(.., f, _)| f.len()).sum();
let split = colored_faces <= MAX_FACE_COMPOSITES;
// The faces are drawn in one order (below) when every solid is opaque and blends normally and
// no composite draws a surface whole. Under a member's opacity mask or blending, each member's
// faces go in one order of their own when its fills and strokes are opaque, blend normally,
// carry no opacity mask and are not composites.
let one_order = opaque && (split || !solids.iter().any(|(item, _, _, f, _)| composite(item, f)));
let shape_order: Vec<bool> = (0..shapes.len())
.map(|shape| {
solids.iter().filter(|s| s.4 == shape).all(|(item, member, _, f, _)| {
let (paint, opacity, blend) = paint_of(item, *member);
opacity >= 1.0 && blend == BlendMode::Normal && !masks_surface(&paint, colored) && !composite(item, f)
opacity >= 1.0 && blend == BlendMode::Normal && !masks_surface(&paint, colored) && (split || !composite(item, f))
})
})
.collect();
let ordered = |shape: usize| if masks { shape_order.get(shape).copied().unwrap_or(false) } else { one_order };
// The solids whose faces share one order with another solid's: every solid in the one order of
// the object, or of its member under a mask. A lone solid draws its facets in their own order,
// so a solid color under colored lights stays one composite there ([`surface`]).
let shared: Vec<bool> =
(0..shapes.len()).map(|shape| ordered(shape) && solids.iter().filter(|s| !masks || s.4 == shape).nth(1).is_some()).collect();
if solids.iter().any(|s| ordered(s.4)) {
// A stroke face that passes through a fill wall or another stroke's face is cut where it
// does. The pieces count against the limits as the faces did: cutting stops before the
@@ -1605,6 +1631,10 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
.collect();
placed_graphics(doc, n.id, (&fx.id, &p), bounds, &filled, masks)
};
// With the pieces of the cuts, solid colors under colored lights past MAX_FACE_COMPOSITES draw
// as one composite each, so their surfaces draw whole (below).
let split =
split && solids.iter().filter(|(item, _, _, f, _)| composite(item, f)).map(|(.., f, _)| f.len()).sum::<usize>() <= MAX_FACE_COMPOSITES;
let members: Vec<usize> = solids.iter().map(|s| s.4).collect();
let surfaces: Vec<BuiltSurface> = solids
.into_iter()
@@ -1613,7 +1643,11 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
let depths: Vec<Placed> = f.iter().map(|f| Placed::of(f, shape, paints)).collect();
let ends = f.iter().map(|f| f.end.filter(|_| !f.away)).collect();
let (paint, opacity, blend) = paint_of(item, member);
let art = if classic { classic::surface(n, f, &paint, opacity, blend, &p) } else { surface(n, f, &paint, opacity, blend, colored) };
let art = if classic {
classic::surface(n, f, &paint, opacity, blend, &p)
} else {
surface(n, f, &paint, opacity, blend, colored, split && shared.get(shape).copied().unwrap_or(false))
};
(depths, art, scopes, ends)
})
.collect();
@@ -1622,8 +1656,8 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
CLASSIC_EXTRUDE => classic_extrude_options(&p).cap,
_ => extrude_options(&p).cap,
};
// One order takes a plain group of faces from each solid, one face for each facet. With
// colored lights a surface can instead be one clipped composite of all its facets. A composite
// One order takes a plain group of faces from each solid, one face for each facet. A lone
// solid's surface can instead be one clipped composite of all its facets ([`surface`]), which
// has no faces to order, so it draws whole.
let plain = |(depths, s, _, _): &BuiltSurface| matches!(&s.kind, NodeKind::Group { children, clip: false } if children.len() == depths.len());
if masks {
@@ -2005,31 +2039,35 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize)
return Ok(out);
}
let (parts, bounds) = solid_parts(shapes, b);
// The solids the art draws, past the limits of the object's solids together as it is
// ([`built_solids`]), each built and its faces counted as the loop reaches it, then dropped.
let drawn = built_solids(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES).map(|r| r.map(|f| f.is_some()));
// Inflate lays out every puff at once (they share one eye); each Inflate and Extrude & Bevel
// solid and its mesh are built as the loop reaches them.
// Inflate lays out every puff at once (they share one eye). Each Inflate and Extrude & Bevel
// solid is built once, as the loop reaches it: its facets decide whether the art draws it, as
// [`built_solids`] does, and its faces before projection make its mesh.
let mut inflated = (fx.id == INFLATE).then(|| {
let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule, _, _)| (area, *rule)).collect();
vectorcraft_three_d::inflate_meshes(&shapes, bounds, inflate_options(&p), view)
vectorcraft_three_d::inflate_meshed(&shapes, bounds, inflate_options(&p), view)
});
let extrude = if fx.id == CLASSIC_EXTRUDE { classic_extrude_options(&p) } else { extrude_options(&p) };
for ((item, member, area, rule, _, _), drawn) in parts.iter().zip(drawn) {
let mut kept = 0usize;
for (item, member, area, rule, _, _) in &parts {
let item: &AppearanceItem = item;
if !drawn? {
// A stroke the art leaves out is left out of the meshes too; Inflate's next puff
// still belongs to the next part.
if let Some(built) = inflated.as_mut() {
built.next();
}
continue;
}
let mesh = match inflated.as_mut() {
Some(built) => built.next().unwrap_or_else(|| Ok(Mesh::default())),
None => vectorcraft_three_d::extrude_mesh(area, *rule, bounds, extrude, view),
#[cfg(test)]
SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
let built = match inflated.as_mut() {
Some(each) => each.next().unwrap_or_else(|| Ok(MeshedSolid::default())),
None => vectorcraft_three_d::extrude_meshed(area, *rule, bounds, extrude, view),
};
match mesh {
// A stroke the art leaves out is left out of the meshes too. The faces of the solids kept
// count together against the object's limit.
let solid = match built {
Ok(solid) => solid,
Err(_) if matches!(item, AppearanceItem::Stroke(_)) => continue,
Err(e) => return Err(e),
};
kept = kept.saturating_add(solid.facets.len());
if kept > MAX_OBJECT_FACES {
return Err(vectorcraft_three_d::TOO_COMPLEX_SOLID.to_string());
}
match solid.mesh() {
Ok(mesh) => {
let (paint, opacity, _) = paint_of(item, *member);
keep(&mut out, mesh, mesh_color(&paint, opacity))?;
+229 -14
View File
@@ -491,8 +491,8 @@ fn a_masked_members_fill_and_stroke_faces_go_in_one_order() {
}
/// Under a light that is not white, Inflate in gradients, whose faces are drawn one by one, draws the
/// fill's and the dashed stroke's faces in one order, as it does under a white light. A solid color,
/// drawn as one composite of each surface's facets, still draws each surface whole.
/// fill's and the dashed stroke's faces in one order, as it does under a white light, and so does
/// Inflate in solid colors.
#[test]
fn a_colored_inflate_in_gradients_draws_its_faces_in_one_order() {
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
@@ -530,9 +530,111 @@ fn a_colored_inflate_in_gradients_draws_its_faces_in_one_order() {
let cut = drawn_parts(&n, INFLATE, &json!({"rotationX": -20, "rotationY": -40, "rotationZ": 0, "depth": 60})).len();
assert_eq!(white.1, cut, "the white light's faces, cut");
assert_eq!(drawn(&n, Some(colored.clone())).0, 1, "one order under the colored light");
// A solid color under the colored light: a composite for each of the fill and the stroke.
// A solid color under the colored light: the fill's and the stroke's faces in one order too.
let solid = stroked(&letter_c());
assert_eq!(drawn(&solid, Some(colored)).0, 2);
assert_eq!(drawn(&solid, Some(colored)).0, 1);
}
/// The bounds of face `f` of 3D art: its path's, or for a clipped colored composite
/// ([`crate::lighting::facet_art`]) its color cover's, which is the face's bounds grown by 1 pt.
fn drawn_face_bounds(f: &Node) -> Rect {
match &f.kind {
NodeKind::Path { .. } => f.path_data().and_then(PathData::bounds).unwrap(),
NodeKind::Group { clip: true, children } => {
let cover = &children[1].children().unwrap()[0];
cover.path_data().and_then(PathData::bounds).unwrap().inflate(-1.0, -1.0)
}
_ => panic!("a face is a path or a clipped composite"),
}
}
/// Under a light that is not white, a solid-color fill and a solid-color stroke, plain, dashed or
/// with a width profile, draw their faces in one order, the faces of both solids in the order of
/// their depths where they overlap, in Inflate and in Extrude & Bevel, with and without perspective
/// and in a member with an opacity mask. Drawing each solid whole, the fill's faces before the
/// stroke's, shows farther faces on top.
#[test]
fn colored_solid_fills_and_strokes_share_face_depth_order() {
use vectorcraft_doc::{Dash, WidthProfile};
type Style<'a> = (&'a str, &'a dyn Fn(&mut StrokeLayer));
let styles: [Style; 3] = [
("plain", &|_| {}),
("dashed", &|s| s.dash = Some(Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false })),
("profiled", &|s| s.profile = Some(WidthProfile::lens())),
];
let views = [
json!({"rotationX": -20, "rotationY": -40, "rotationZ": 0}),
json!({"rotationX": -30, "rotationY": 20, "rotationZ": 5, "perspectiveAngle": 40}),
];
let mut whole_misdrawn = 0;
for id in [INFLATE, EXTRUDE] {
for view in &views {
for (style, set) in &styles {
let mut params = view.clone();
params["depth"] = json!(60);
params["lights"] = json!([{"color": "#ff8080"}, {"color": "#4060ff", "rotation": 120}]);
let mut n = stroked(&letter_c());
if let Some(AppearanceItem::Stroke(s)) = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Stroke(_))) {
set(s);
}
let what = format!("{id} {view} {style}");
let parts = drawn_parts(&n, id, &params);
if id == INFLATE {
assert!(parts.iter().any(|(f, ..)| f.rgb_gradient.is_some()), "{what}: smooth colored facets");
}
let mut with = n.clone();
with.appearance.effects.push(fx(id, params.clone()));
let art = solid_art(&with).unwrap();
let surfaces = art.children().unwrap();
assert_eq!(surfaces.len(), 1, "{what}: one order");
let faces = surfaces[0].children().unwrap();
assert_eq!(faces.len(), parts.len(), "{what}: one face per facet");
for (k, (face, (facet, ..))) in faces.iter().zip(&parts).enumerate() {
let (a, b) = (drawn_face_bounds(face), facet.path().bounds().unwrap());
let close = [a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().all(|d| d.abs() < 1e-6);
assert!(close, "{what}: face {k} drawn out of the order of the depths");
}
let allowed = if id == INFLATE { 5 } else { 0 };
let wrong = misdrawn(&parts);
assert!(wrong.len() <= allowed, "{what}: {} points show a farther face, first {:?}", wrong.len(), wrong.first());
// The same faces drawn as two whole surfaces, the fill's then the stroke's.
let mut whole = parts.clone();
whole.sort_by_key(|(_, part, _)| *part);
whole_misdrawn += misdrawn(&whole).len();
// In a group, under the member's opacity mask, the faces keep the same order.
if id == INFLATE && *style == "plain" {
let cover = Node::path(
NodeId(900),
vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 400.0, 400.0)),
Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0),
);
let mut masked = n.clone();
masked.extras_mut().mask = Some(Box::new(OpacityMask::new(cover, true)));
let mut plain = Node::group(NodeId(2), vec![Arc::new(n.clone())]);
plain.appearance.effects.push(fx(id, params.clone()));
let mut g = Node::group(NodeId(2), vec![Arc::new(masked)]);
g.appearance.effects.push(fx(id, params.clone()));
let bounds = |art: &Node| {
let mut out = vec![];
art.walk(&mut |n| {
if let NodeKind::Group { clip: true, .. } = &n.kind {
out.push(drawn_face_bounds(n));
}
});
out
};
let (plain, scoped) = (solid_art(&plain).unwrap(), solid_art(&g).unwrap());
let mut masks = 0;
scoped.walk(&mut |n| masks += usize::from(n.extras().mask.is_some()));
assert!(masks > 0, "{what}: drawn in the member's mask");
let ordered = bounds(&plain);
assert!(ordered.len() > 100, "{what}: clipped faces");
assert_eq!(bounds(&scoped), ordered, "{what}: the member's faces in one order");
}
}
}
}
assert!(whole_misdrawn > 0, "whole surfaces show farther faces");
}
/// A face of a stroke that leaves gaps passing through the plane of its fill's wall where they
@@ -1322,11 +1424,12 @@ fn legacy_white_inflate_keeps_polygon_faces_and_its_seam_range() {
assert!(faces(&art).iter().all(|face| matches!(face.kind, NodeKind::Path { .. })));
}
/// A solid color under colored lights is one composite of all its facets, with one clip and a fixed
/// number of groups, where its solid's faces draw in no order shared with another solid's: a lone
/// fill, or a fill and a translucent stroke. A fill and an opaque stroke draw each face on its own,
/// in one order.
#[test]
fn colored_solid_inflate_batches_channels_and_clips_once_per_surface() {
let mut n = square_node();
n.appearance.effects.push(fx(INFLATE, json!({"lights":[{"color":"#ff0000"},{"color":"#0000ff"}]})));
let art = solid_art(&n).unwrap();
fn count(n: &Node) -> (usize, usize, usize) {
let (mut groups, mut clips, mut paths) = match &n.kind {
NodeKind::Group { clip, .. } => (1, usize::from(*clip), 0),
@@ -1341,13 +1444,125 @@ fn colored_solid_inflate_batches_channels_and_clips_once_per_surface() {
}
(groups, clips, paths)
}
let (groups, clips, paths) = count(&art);
assert!(paths > 1000, "exercise a tessellated surface");
// The fill's solid and the stroke's, each one composite with its own clip.
let surfaces = art.children().unwrap().len();
assert_eq!(surfaces, 2);
assert_eq!(clips, surfaces);
assert_eq!(groups, 1 + 6 * surfaces, "group count must not grow with triangle count");
let lights = json!({"lights":[{"color":"#ff0000"},{"color":"#0000ff"}]});
let lone = |n: &mut Node| n.appearance.items.retain(|i| matches!(i, AppearanceItem::Fill(_)));
let translucent = |n: &mut Node| {
if let Some(AppearanceItem::Stroke(s)) = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Stroke(_))) {
s.opacity = 0.5;
}
};
for (what, set, surfaces) in [("a lone fill", &lone as &dyn Fn(&mut Node), 1), ("a translucent stroke", &translucent, 2)] {
let mut n = square_node();
set(&mut n);
n.appearance.effects.push(fx(INFLATE, lights.clone()));
let art = solid_art(&n).unwrap();
let (groups, clips, paths) = count(&art);
assert!(paths > 1000, "{what}: exercise a tessellated surface");
// Each solid one composite with its own clip.
assert_eq!(art.children().unwrap().len(), surfaces, "{what}");
assert_eq!(clips, surfaces, "{what}");
assert_eq!(groups, 1 + 6 * surfaces, "{what}: group count must not grow with triangle count");
}
// An opaque fill and stroke: one order of faces, each its own clipped composite or shaded path.
let mut n = square_node();
n.appearance.effects.push(fx(INFLATE, lights));
let art = solid_art(&n).unwrap();
let surfaces = art.children().unwrap();
assert_eq!(surfaces.len(), 1, "one order");
let faces = surfaces[0].children().unwrap();
assert!(faces.len() > 100, "one face per facet");
assert!(faces.iter().all(|f| matches!(&f.kind, NodeKind::Path { .. } | NodeKind::Group { clip: true, .. })));
assert!(faces.iter().any(|f| matches!(&f.kind, NodeKind::Group { clip: true, .. })), "colored ramps");
}
/// Solid colors under colored lights go in one order of faces while their facets together, with the
/// pieces of the cuts, number at most `MAX_FACE_COMPOSITES`. Past it each solid draws whole, as one
/// composite.
#[test]
fn colored_solids_past_the_face_limit_draw_as_composites() {
let lights = json!({"lights":[{"color":"#ff0000"},{"color":"#0000ff","rotation":90}]});
let mut base = square_node();
base.appearance.effects.push(fx(INFLATE, lights.clone()));
let stroke = base.appearance.items.iter().find(|i| matches!(i, AppearanceItem::Stroke(_))).cloned().unwrap();
// The facets each solid draws under these lights. Strokes alike each build the same solid.
let shapes = [Profile { path: profile(&base).unwrap().0, rule: FillRule::NonZero, items: solid_paints(&base), opacity: 1.0, scopes: vec![] }];
let (parts, bounds) = solid_parts(&shapes, union_bounds(&shapes).unwrap());
let counts: Vec<usize> = built_solids(INFLATE, &crate::merged_params(INFLATE, &lights), &parts, bounds, MAX_OBJECT_FACES)
.map(|f| f.unwrap().map_or(0, |f| f.len()))
.collect();
let [fill, each] = counts[..] else { panic!("a fill's solid and a stroke's") };
let fits = (MAX_FACE_COMPOSITES - fill) / each;
assert!(fits >= 4, "{fill} + {fits} × {each}");
// Under the limit; under it before the cuts but past it with their pieces; past it before them.
let mut seen = vec![];
for strokes in [fits / 2, fits, fits + 1] {
let mut n = base.clone();
n.appearance.items.extend(std::iter::repeat_n(stroke.clone(), strokes - 1));
let uncut = fill + strokes * each;
let cut = drawn_parts(&n, INFLATE, &lights).len();
let one_order = cut <= MAX_FACE_COMPOSITES;
seen.push((uncut <= MAX_FACE_COMPOSITES, one_order));
let art = solid_art(&n).unwrap();
let surfaces = art.children().unwrap();
if one_order {
assert_eq!(surfaces.len(), 1, "{uncut} faces, {cut} cut: one order");
} else {
assert_eq!(surfaces.len(), 1 + strokes, "{uncut} faces, {cut} cut: each solid whole");
assert!(surfaces.iter().all(|s| s.children().is_some_and(|c| c.len() < 10)), "each solid one composite");
}
}
assert_eq!(seen, [(true, true), (true, false), (false, false)], "every case");
}
/// A solid-color face drawn on its own under colored lights takes the same colors as in the
/// surface's one composite: the paint, multiplied by the same red, green and blue light ramps, and
/// a seam of the same width.
#[test]
fn a_colored_solid_face_on_its_own_keeps_the_composites_colors() {
let n = square_node();
let p = crate::merged_params(INFLATE, &json!({"lights":[{"color":"#ff0000"},{"color":"#0000ff","rotation":90}]}));
let (path, rule) = profile(&n).unwrap();
let all = facets(INFLATE, &path, rule, path.bounds().unwrap(), &p).unwrap();
let face = all
.iter()
.find(|f| f.rgb_gradient.is_some_and(|g| g.channels[0] != g.channels[1] || g.channels[1] != g.channels[2]))
.expect("a facet with colored ramps")
.clone();
let paint = Paint::solid(RED);
// Each node's own fill paint, and its seam stroke's width, for every node under `n`.
let paints = |n: &Node| {
let mut out = vec![];
n.walk(&mut |n| {
for item in &n.appearance.items {
match item {
AppearanceItem::Fill(f) => out.push((Some(f.paint.clone()), None)),
AppearanceItem::Stroke(s) => out.push((None, Some(s.width))),
}
}
});
out
};
let alone = surface(&n, vec![face.clone()], &paint, 1.0, BlendMode::Normal, true, true);
let batch = surface(&n, vec![face.clone()], &paint, 1.0, BlendMode::Normal, true, false);
let [single] = alone.children().unwrap().as_slice() else { panic!("one face") };
assert!(matches!(&single.kind, NodeKind::Group { clip: true, .. }), "a clipped face");
// The face's paint cover and its three channel ramps.
let fills = |n: &Node| paints(n).into_iter().filter_map(|(f, _)| f).collect::<Vec<_>>();
let one = fills(single);
assert_eq!(one.len(), 4);
assert_eq!(one[0], paint, "the paint");
// The composite: its paint cover, then each channel's black backdrop and the face's ramp.
let all_fills = fills(&batch);
let ramps: Vec<&Paint> = all_fills.iter().filter(|p| **p != Paint::solid(Color::BLACK)).skip(1).collect();
assert_eq!(all_fills.first(), Some(&paint));
assert_eq!(ramps, one.iter().skip(1).collect::<Vec<_>>(), "the same light ramps");
// The single face's clip holds its seam: the clip reaches past the facet by half the seam.
let seam = (face.thickness() / 2.0).clamp(0.05, 0.75);
let widths: Vec<f64> = paints(&batch).into_iter().filter_map(|(_, w)| w).filter(|w| *w > 0.0).collect();
assert!(widths.len() == 3 && widths.iter().all(|w| (w - seam).abs() < 1e-12), "{widths:?}");
let NodeKind::Group { children, .. } = &single.kind else { panic!("a clip group") };
let (clip, facet) = (children[0].path_data().and_then(PathData::bounds).unwrap(), face.path().bounds().unwrap());
assert!((clip.x0 - (facet.x0 - seam / 2.0)).abs() < 0.1 && (clip.x1 - (facet.x1 + seam / 2.0)).abs() < 0.1, "{clip:?} {facet:?}");
}
/// `square_node` moved right by `dx`, with id `id` and fill `fill`.
+148
View File
@@ -208,3 +208,151 @@ fn a_gradient_takes_the_average_of_its_stops() {
let pattern = Paint::Pattern { pattern: "x".into(), xf: vectorcraft_geom::Affine::IDENTITY };
assert!(close(mesh_color(&pattern, 0.5), [0.5, 0.5, 0.5, 0.5]));
}
/// The meshes of Extrude & Bevel or Inflate `fx` on `shapes`, each built apart from the facets that
/// decide which solids are drawn ([`built_solids`], then [`vectorcraft_three_d::extrude_mesh`] or
/// [`vectorcraft_three_d::inflate_meshes`]), for comparing with [`meshes_for`].
fn meshes_built_apart(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize) -> Result<Vec<SolidMesh>, String> {
let p = crate::merged_params(&fx.id, &fx.params);
let view = view_options(&p);
let (parts, bounds) = solid_parts(shapes, union_bounds(shapes).unwrap());
let drawn = built_solids(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES).map(|r| r.map(|f| f.is_some()));
let mut inflated = (fx.id == INFLATE).then(|| {
let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule, _, _)| (area, *rule)).collect();
vectorcraft_three_d::inflate_meshes(&shapes, bounds, inflate_options(&p), view)
});
let extrude = if fx.id == CLASSIC_EXTRUDE { classic_extrude_options(&p) } else { extrude_options(&p) };
let mut out = vec![];
for ((item, opacity, area, rule, _, _), drawn) in parts.iter().zip(drawn) {
let item: &AppearanceItem = item;
if !drawn? {
if let Some(built) = inflated.as_mut() {
built.next();
}
continue;
}
let mesh = match inflated.as_mut() {
Some(built) => built.next().unwrap_or_else(|| Ok(Mesh::default())),
None => vectorcraft_three_d::extrude_mesh(area, *rule, bounds, extrude, view),
};
match mesh {
Ok(mesh) => {
let (paint, opacity, _) = paint_of(item, *opacity);
keep_mesh(&mut out, total, SolidMesh { mesh, color: mesh_color(&paint, opacity) }, limit)?;
}
Err(_) if matches!(item, AppearanceItem::Stroke(_)) => {}
Err(e) => return Err(e),
}
}
Ok(out)
}
/// The bits of every number in `meshes`, for comparing two exports exactly.
type MeshBits = Vec<([u32; 4], Vec<[u64; 3]>, Vec<[u64; 3]>, Vec<[u32; 3]>)>;
fn mesh_bits(meshes: &[SolidMesh]) -> MeshBits {
meshes
.iter()
.map(|m| {
let (positions, normals) = (&m.mesh.positions, &m.mesh.normals);
(
m.color.map(f32::to_bits),
positions.iter().map(|p| p.map(f64::to_bits)).collect(),
normals.iter().map(|n| n.map(f64::to_bits)).collect(),
m.mesh.triangles.clone(),
)
})
.collect()
}
/// A five-pointed star about `(x, 150)` with curved edges, filled red and stroked black.
fn star_node(id: u64, x: f64) -> Node {
let mut b = BezPath::new();
for k in 0..10 {
let (s, c) = (k as f64 * std::f64::consts::PI / 5.0).sin_cos();
let r = if k % 2 == 0 { 60.0 } else { 25.0 };
let p = (x + r * c, 150.0 + r * s);
if k == 0 { b.move_to(p) } else { b.curve_to((p.0 + 4.0, p.1), (p.0, p.1 + 4.0), p) }
}
b.close_path();
Node::path(NodeId(id), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(RED), Paint::solid(Color::BLACK), 6.0))
}
/// The shapes `meshes_for` builds from: one node's, or each of several.
fn shapes_of(nodes: &[&Node]) -> Vec<Profile> {
nodes
.iter()
.map(|n| Profile { path: profile(n).unwrap().0, rule: FillRule::NonZero, items: solid_paints(n), opacity: 1.0, scopes: vec![] })
.collect()
}
/// Building each Extrude & Bevel and Inflate solid once exports the same meshes, to the bit, as
/// building its facets and its mesh apart, within and past the triangle budget.
#[test]
fn one_build_exports_the_meshes_built_apart() {
let mut second_stroke = square_node(3, 400.0);
if let Some(stroke) = second_stroke.appearance.items.get(1).cloned() {
second_stroke.appearance.items.push(stroke);
}
let (star, square, other) = (star_node(1, 100.0), square_node(2, 250.0), star_node(4, 600.0));
let cases = [
(EXTRUDE, json!({})),
(EXTRUDE, json!({ "bevel": "rounded", "bevelWidth": 6.0, "bevelHeight": 5.0, "twist": 60.0, "taper": 70.0 })),
(EXTRUDE, json!({ "bevel": "cove", "bevelInside": true, "bevelBothSides": true, "cap": false, "perspectiveAngle": 50.0 })),
(EXTRUDE, json!({ "depth": 0.0 })),
(CLASSIC_EXTRUDE, json!({ "bevel": "classic", "bevelHeight": 8.0 })),
(INFLATE, json!({})),
(INFLATE, json!({ "depth": 30.0, "bothSides": true, "volume": 80.0 })),
(INFLATE, json!({ "depth": 40.0, "twist": 360.0, "taper": 70.0, "cap": false })),
(INFLATE, json!({ "depth": 0.1, "twist": 0.1, "bothSides": true })),
];
let sets: [Vec<&Node>; 3] = [vec![&star], vec![&second_stroke], vec![&star, &square, &other]];
for (id, params) in cases {
let effect = fx(id, params.clone());
for nodes in &sets {
let shapes = shapes_of(nodes);
let (mut once, mut apart) = (0, 0);
let built = meshes_for(&effect, &shapes, &mut once, MAX_MESH_TRIANGLES).unwrap_or_else(|e| panic!("{id} {params}: {e}"));
let reference = meshes_built_apart(&effect, &shapes, &mut apart, MAX_MESH_TRIANGLES).unwrap();
assert!(!reference.is_empty());
assert_eq!(mesh_bits(&built), mesh_bits(&reference), "{id} {params}");
assert_eq!(once, apart);
// Past the budget, at the same mesh, with the same count.
let limit = once - 1;
let (mut once, mut apart) = (0, 0);
let built = meshes_for(&effect, &shapes, &mut once, limit);
assert!(built.is_err(), "{id} {params}");
assert_eq!(built.err(), meshes_built_apart(&effect, &shapes, &mut apart, limit).err(), "{id} {params}");
assert_eq!(once, apart, "{id} {params}");
}
}
}
/// A stroke whose solid is past the limits is left out of the export and the fill's mesh exports,
/// as when the facets and the mesh are built apart.
#[test]
fn a_stroke_past_the_limits_is_left_out_of_the_export() {
// 40,000 corners: within the 65,536 points of the fill's solid, but not the stroke's outline.
let points: Vec<Point> = (0..40_000)
.map(|k| {
let (s, c) = (k as f64 * std::f64::consts::TAU / 40_000.0).sin_cos();
let r = if k % 2 == 0 { 10_000.0 } else { 9_999.0 };
Point::new(20_000.0 + r * c, 20_000.0 + r * s)
})
.collect();
let path = PathData::single(vectorcraft_geom::SubPath::polyline(&points, true));
let n = Node::path(NodeId(1), path, Appearance::basic(Paint::solid(RED), Paint::solid(Color::BLACK), 2.0));
for id in [EXTRUDE, INFLATE] {
// Without caps: a cap of 40,000 corners takes more work to cut into triangles than an
// export allows.
let effect = fx(id, json!({ "cap": false }));
let shapes = shapes_of(&[&n]);
// The fill's mesh alone has more triangles than an export takes.
let (mut once, mut apart) = (0, 0);
let built = meshes_for(&effect, &shapes, &mut once, usize::MAX).unwrap_or_else(|e| panic!("{id}: {e}"));
assert_eq!(built.len(), 1, "{id}: the fill's mesh alone");
assert!(close(built[0].color, [0.8, 0.2, 0.1, 1.0]), "{id}");
let reference = meshes_built_apart(&effect, &shapes, &mut apart, usize::MAX).unwrap();
assert_eq!(mesh_bits(&built), mesh_bits(&reference), "{id}");
}
}
+21
View File
@@ -1570,6 +1570,27 @@ fn outline_object_is_a_geometry_effect_that_keeps_the_path() {
assert_eq!(apply_geometry(&[fx("path.outlineObject", json!({})), offset.clone()], &square(), b), apply_geometry(&[offset], &square(), b));
}
/// A symbol instance given to Pathfinder and compound shapes as its art: the group takes the
/// instance's box angle and the art turns with it, turned with the instance or reset to 0.
#[test]
fn outline_object_turns_an_instances_art_with_its_box() {
use std::sync::Arc;
use vectorcraft_doc::orient::transformed_angle;
use vectorcraft_doc::{Appearance, Document, NodeId, Symbol};
let mut d = Document::new(500.0, 500.0);
d.symbols.push(Symbol { dynamic: false, name: "s".into(), art: Arc::new(Node::path(NodeId(0), square(), Appearance::default())) });
let xf = Affine::translate((200.0, 100.0)) * Affine::rotate(0.35);
for box_angle in [transformed_angle(0.0, xf), 0.0] {
let mut inst = Node::new(NodeId(3), NodeKind::SymbolInstance { symbol: "s".into(), xf });
inst.bbox_angle = box_angle;
let out = outline_object(Some(&d), &inst).unwrap();
let mut angles = vec![];
out.walk(&mut |c| angles.push(c.bbox_angle));
assert!(angles.len() == 2 && angles.iter().all(|a| close(*a, box_angle, 1e-9)), "{box_angle}: {angles:?}");
}
}
#[test]
fn convert_to_shape_sizes() {
let r = run("convertToShape.rectangle", json!({"extraW": 20, "extraH": 10}), &square()).bounds().unwrap();
+18
View File
@@ -440,6 +440,15 @@ pub(crate) fn f64_req(p: &Value, key: &str, cmd: &str) -> Result<f64> {
Some(v) => v.as_f64().ok_or_else(|| bad(cmd, format!("`{key}` must be a number, not {v}"))),
}
}
/// The whole number of 0 or more that `p` gives for `key`. A missing key or null is "missing integer
/// `{key}`"; any other value, such as `"3"`, `2.5`, `-1` or `true`, is "`{key}` must be a whole
/// number", as [`object_param`] words it.
pub(crate) fn u64_req(p: &Value, key: &str, cmd: &str) -> Result<u64> {
match p.get(key) {
None | Some(Value::Null) => Err(bad(cmd, format!("missing integer `{key}`"))),
Some(v) => v.as_u64().ok_or_else(|| bad(cmd, format!("`{key}` must be a whole number"))),
}
}
/// The number `p` gives for `key`, or `default` when `p` leaves it out or gives null. Any other
/// value, such as `"40"`, is an error: "`{key}` must be a number, not {v}".
pub(crate) fn number_or(p: &Value, key: &str, default: f64, cmd: &str) -> Result<f64> {
@@ -550,6 +559,15 @@ pub(crate) fn given_object_ids(p: &Value, command: &str) -> Result<Option<Vec<No
pub(crate) fn index(v: u64) -> usize {
usize::try_from(v).unwrap_or(usize::MAX)
}
/// The whole number of 0 or more that `p` gives for `key`, read with [`index`], or `None` when `p`
/// leaves it out or gives null. Any other value, such as `"3"`, `2.5`, `-1` or `true`, is an error
/// under `cmd`: "`{key}` must be a whole number".
pub(crate) fn index_opt(p: &Value, key: &str, cmd: &str) -> Result<Option<usize>> {
match p.get(key) {
None | Some(Value::Null) => Ok(None),
Some(v) => v.as_u64().map(|n| Some(index(n))).ok_or_else(|| bad(cmd, format!("`{key}` must be a whole number"))),
}
}
/// Validate all explicit targets before a command changes the document or selection.
pub(crate) fn checked_ids_param(s: &Session, p: &Value, key: &str, command: &str) -> Result<Vec<NodeId>> {
checked_nodes_param(s, p, key, command, false)
+20 -3
View File
@@ -20,7 +20,9 @@ use vectorcraft_doc::{Node, NodeId, OrientedBox};
use vectorcraft_geom::{Affine, Point, Rect};
use vectorcraft_render::effects;
use super::super::appearance::series_children_in_paint_order;
use super::super::edit::selected_roots;
use super::super::graph::capture_series_object_opacity;
use super::super::menucmds::whole_or;
use super::super::object::{choice, object_bounds_transform, scaling, transform_node, transform_patterns};
use super::super::typecmd::refresh_bounds_of;
@@ -90,7 +92,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Randomize Opacity",
["Object", "Plug-ins", "Arrange Tools"],
None,
"{min?: % 0..100 (30), max?: % 0..100 (100; not less than min), seed?: whole number (0; the same seed, objects and range give the same opacities), ids?: [id…] (default: the selection)} give each selected object (the top-level ones) its own opacity, picked at random and evenly from min to max, as one undo step; it is the object's opacity, as the Transparency panel sets it → {count}",
"{min?: % 0..100 (30), max?: % 0..100 (100; not less than min), seed?: whole number (0; the same seed, objects and range give the same opacities), ids?: [id…] (default: the selection)} give each selected object (the top-level ones) its own opacity, picked at random and evenly from min to max, as one undo step; it is the object's opacity, as the Transparency panel sets it. On paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw (docs/mcp.md) → {count}",
has_selection,
randomize_opacity
),
@@ -99,7 +101,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Sort Objects",
["Object", "Plug-ins", "Arrange Tools"],
None,
"{by?: \"width\" | \"height\" | \"area\" (width × height) | \"x\" (left edge) | \"y\" (top edge) | \"opacity\" (%) | \"stacking\" (stacking order, from the back) (\"area\"), apply?: one of the same (\"stacking\"), order?: \"ascending\" (small to large) | \"descending\" (large to small) | \"random\" (\"ascending\"), distribute?: false (true: the values step evenly from the smallest to the largest; false: the objects trade the values they have), seed?: whole number (0; the order \"random\" picks), scaleStrokes?: the Scale Strokes & Effects preference (width, height and area), ids?: [id…] (default: the selection)} sort the selected objects (the top-level ones, at most 20000) by the attribute `by` and give them the values of `apply` in that order, as one undo step: the first in order gets the smallest value. Sizes and places are measured and set as object.setBounds measures them (Use Preview Bounds), a width, height or area about each object's centre (an area in proportion); stacking order always trades places, and only among the objects in the same layer or group. A run that changes nothing makes no step → {count}",
"{by?: \"width\" | \"height\" | \"area\" (width × height) | \"x\" (left edge) | \"y\" (top edge) | \"opacity\" (%) | \"stacking\" (stacking order, from the back) (\"area\"), apply?: one of the same (\"stacking\"), order?: \"ascending\" (small to large) | \"descending\" (large to small) | \"random\" (\"ascending\"), distribute?: false (true: the values step evenly from the smallest to the largest; false: the objects trade the values they have), seed?: whole number (0; the order \"random\" picks), scaleStrokes?: the Scale Strokes & Effects preference (width, height and area), ids?: [id…] (default: the selection)} sort the selected objects (the top-level ones, at most 20000) by the attribute `by` and give them the values of `apply` in that order, as one undo step: the first in order gets the smallest value. Sizes and places are measured and set as object.setBounds measures them (Use Preview Bounds), a width, height or area about each object's centre (an area in proportion); stacking order always trades places, and only among the objects in the same layer or group. With apply \"opacity\", on paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw (docs/mcp.md). A run that changes nothing makes no step → {count}",
has_multi,
sort
),
@@ -396,17 +398,30 @@ fn randomize_opacity(s: &mut Session, p: &Value) -> Result<Value> {
}
let (lo, hi) = ((min / 100.0) as f32, (max / 100.0) as f32);
s.edit("Randomize Opacity", |d, _| {
let mut changed = vec![];
for id in &ids {
let o = rng.range(lo, hi);
if let Some(n) = d.node_mut(*id) {
if let Some(n) = d.node_mut(*id)
&& n.opacity != o
{
n.opacity = o;
changed.push(*id);
}
}
keep_series_opacity(d, &changed);
Ok(())
})?;
Ok(json!({ "count": ids.len() }))
}
/// Store on their graphs the opacity just given to the paths among `changed` (objects whose opacity changed) that are
/// directly in a graph series, with their blend mode, so that every path of the series has them when the graph is drawn
/// again; the frontmost of them in a series sets them.
fn keep_series_opacity(d: &mut vectorcraft_doc::Document, changed: &[NodeId]) {
let marks = series_children_in_paint_order(d, changed);
capture_series_object_opacity(d, &marks);
}
/// An object Sort Objects sorts: its layer or group, its place in it, its box as
/// `object.setBounds` measures it and its opacity (%).
struct Sorted {
@@ -510,6 +525,8 @@ fn sort(s: &mut Session, p: &Value) -> Result<Value> {
n.opacity = (v / 100.0) as f32;
}
}
let changed: Vec<NodeId> = wanted.iter().filter(|(o, v)| (o.opacity - v).abs() >= 1e-6).map(|(o, _)| o.id).collect();
keep_series_opacity(d, &changed);
Ok(())
})?;
return Ok(count);
+2 -2
View File
@@ -43,7 +43,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Apply as Filter",
["Object", "Plug-ins", "Color Effects"],
None,
"{effect: a colour adjustment's effect id (adjust.brightnessContrast, adjust.curves, adjust.hueSaturation, adjust.levels, adjust.shiftToColor, adjust.temperatureTint, addon.color.exposure, addon.color.desaturate, addon.color.duotone or addon.color.invert), params?: {…} (as effect.apply; missing keys take the dialog defaults), fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?: [id…] (default: the selection)} recolour the objects and everything inside them as the live effect would draw them, but in their colours, as edit.colors.invert does (fills, strokes, type, gradient meshes, embedded images and pattern tiles), as one undo step; their effects stay. Duotone links a colour to its one tone's swatch as the live effect does. On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke (docs/mcp.md) → {changed}",
"{effect: a colour adjustment's effect id (adjust.brightnessContrast, adjust.curves, adjust.hueSaturation, adjust.levels, adjust.shiftToColor, adjust.temperatureTint, addon.color.exposure, addon.color.desaturate, addon.color.duotone or addon.color.invert), params?: {…} (as effect.apply; missing keys take the dialog defaults), fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?: [id…] (default: the selection)} recolour the objects and everything inside them as the live effect would draw them, but in their colours, as edit.colors.invert does (fills, strokes, type, gradient meshes, embedded images and pattern tiles), as one undo step (none when nothing changes); their effects stay. Duotone links a colour to its one tone's swatch as the live effect does. On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke (docs/mcp.md) → {changed}",
has_selection,
filter
),
@@ -70,7 +70,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Apply Nearest Swatch",
["Object", "Plug-ins", "Color Effects"],
None,
"{library?: as addon.color.nearestSwatch (default: \"document\"), fill?: true, stroke?: true, ids?: [id…] (default: the selection)} give each solid colour and gradient stop of the selected objects' fills and strokes (their type's and those of the objects inside them; gradient meshes too) the colour of its nearest swatch in the library, as addon.color.nearestSwatch finds it, as one undo step: a global or spot swatch's colour links to it. A library's swatches the colours take are added to the document's first, as swatch.library.add adds them (a spot colour stays spot); images and patterns keep their colours. On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke (docs/mcp.md) → {changed: paints changed, swatches: [the document swatches the colours took], added: [swatches added to the document]}",
"{library?: as addon.color.nearestSwatch (default: \"document\"), fill?: true, stroke?: true, ids?: [id…] (default: the selection)} give each solid colour and gradient stop of the selected objects' fills and strokes (their type's and those of the objects inside them; gradient meshes too) the colour of its nearest swatch in the library, as addon.color.nearestSwatch finds it, as one undo step (none when nothing changes): a global or spot swatch's colour links to it. A library's swatches the colours take are added to the document's first, as swatch.library.add adds them (a spot colour stays spot); images and patterns keep their colours. On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke (docs/mcp.md) → {changed: paints changed, swatches: [the document swatches the colours took], added: [swatches added to the document]}",
has_selection,
nearest::apply
),
@@ -713,6 +713,71 @@ fn corner_commands_refuse_bad_params() {
}
}
#[test]
fn corner_commands_refuse_an_unknown_item_key() {
let mut s = session();
let id = square(&mut s);
let i = id.0;
let set = json!({"items": [{"id": i, "anchor": [0]}], "radius": 5});
let e = s.execute("addon.pathtools.cornerSet", &set).unwrap_err().to_string();
assert!(e.contains("unknown parameter `items[0].anchor`; did you mean `items[0].anchors`?"), "{e}");
let set_late = json!({"items": [{"id": i, "anchors": [0]}, {"id": i, "radius": 3}], "radius": 5});
let e = s.execute("addon.pathtools.cornerSet", &set_late).unwrap_err().to_string();
assert!(e.contains("unknown parameter `items[1].radius`; the command takes: items[1].id, items[1].anchors"), "{e}");
refuses(&mut s, "addon.pathtools.cornerSet", &[set, set_late]);
s.execute("addon.pathtools.cornerSet", &json!({"radius": 10})).unwrap();
let remove = json!({"items": [{"id": i, "anchor": [0]}]});
let e = s.execute("addon.pathtools.cornerRemove", &remove).unwrap_err().to_string();
assert!(e.contains("unknown parameter `items[0].anchor`; did you mean `items[0].anchors`?"), "{e}");
refuses(&mut s, "addon.pathtools.cornerRemove", &[remove]);
assert_eq!(drawn(&s, id, 0), 10.0);
}
#[test]
fn corner_items_take_their_documented_keys() {
let mut s = session();
let id = square(&mut s);
let i = id.0;
let r = s.execute("addon.pathtools.cornerSet", &json!({"items": [{"id": i, "anchors": [0]}], "radius": 5})).unwrap();
assert_eq!((r["corners"].clone(), drawn(&s, id, 0), drawn(&s, id, 1)), (json!(1), 5.0, 0.0));
// A member without `anchors` takes the request's.
s.execute("addon.pathtools.cornerSet", &json!({"items": [{"id": i}], "anchors": [2], "radius": 6})).unwrap();
assert_eq!(drawn(&s, id, 2), 6.0);
let r = s.execute("addon.pathtools.cornerRemove", &json!({"items": [{"id": i, "anchors": [0]}]})).unwrap();
assert_eq!((r["corners"].clone(), drawn(&s, id, 0), drawn(&s, id, 2)), (json!(1), 0.0, 6.0));
// A null `ids` beside `items` counts as not given.
s.execute("addon.pathtools.cornerRemove", &json!({"items": [{"id": i}], "ids": null})).unwrap();
assert_eq!(drawn(&s, id, 2), 0.0);
}
#[test]
fn corner_commands_refuse_items_with_ids() {
let mut s = session();
let id = square(&mut s);
let other = line(&mut s, &[(350.0, 10.0), (390.0, 10.0), (390.0, 50.0)], false);
let both = json!({"items": [{"id": id.0, "anchors": [0]}], "ids": [other.0], "radius": 5});
let e = s.execute("addon.pathtools.cornerSet", &both).unwrap_err().to_string();
assert!(e.contains("give `items` or `ids`, not both"), "{e}");
refuses(&mut s, "addon.pathtools.cornerSet", &[both]);
s.execute("addon.pathtools.cornerSet", &json!({"ids": [id.0], "radius": 5})).unwrap();
let both = json!({"items": [{"id": id.0}], "ids": [id.0]});
let e = s.execute("addon.pathtools.cornerRemove", &both).unwrap_err().to_string();
assert!(e.contains("give `items` or `ids`, not both"), "{e}");
refuses(&mut s, "addon.pathtools.cornerRemove", &[both]);
}
#[test]
fn saved_corner_steps_with_older_item_keys_still_play() {
let mut s = session();
let id = square(&mut s);
let other = line(&mut s, &[(350.0, 10.0), (390.0, 10.0), (390.0, 50.0)], false);
let saved = json!({"items": [{"id": id.0, "anchors": [0], "old": 1}], "ids": [other.0], "radius": 5});
s.replay("addon.pathtools.cornerSet", &saved).unwrap();
assert_eq!((drawn(&s, id, 0), drawn(&s, id, 1)), (5.0, 0.0));
s.replay("addon.pathtools.cornerRemove", &json!({"items": [{"id": id.0, "old": 1}]})).unwrap();
assert_eq!(drawn(&s, id, 0), 0.0);
}
/// A closed five-pointed star about (200, 150): its points at the even indices 0, 2… (the odd
/// numbers counting from 1), its inner corners at the odd ones.
fn star_path(s: &mut Session) -> NodeId {
+179 -79
View File
@@ -9,6 +9,8 @@
#[cfg(test)]
mod tests;
use std::ops::RangeInclusive;
use serde_json::{Value, json};
use vectorcraft_doc::{LiveShape, NodeId, NodeKind};
use vectorcraft_geom::{Affine, FillRule, Point, Rect, shapes};
@@ -16,9 +18,25 @@ use vectorcraft_tools::addons::box3d::CustomShape;
use super::super::create::insert_look;
use super::super::{
CommandSpec, Result, Session, bool_or, check_numbers, check_switches, cmd, f64_or, f64_req, has_doc, has_selection, str_param, targets,
CommandSpec, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, f64_or, f64_req, has_doc, has_selection, number_or, str_param,
targets,
};
/// The sides of a polygon and the points of a star: whole numbers in this range.
const COUNTS: RangeInclusive<f64> = 3.0..=1000.0;
/// `rounded` and `randomized` of a polygon or star.
const ROUNDING: RangeInclusive<f64> = -10.0..=10.0;
/// A star's inner radius as a fraction of its outer radius.
const SPOKE_RATIO: RangeInclusive<f64> = 0.01..=1.0;
/// A spiral's `turns`.
const TURNS: RangeInclusive<f64> = 0.01..=1024.0;
/// A spiral's `divergence`.
const DIVERGENCE: RangeInclusive<f64> = 0.0..=1000.0;
/// A spiral's `innerRadius`, as a fraction of its radius.
const INNER_RADIUS: RangeInclusive<f64> = 0.0..=0.999;
/// The `arcMode` names; `slice` and `open` are also read as `pie` and `arc`.
const ARC_MODES: [&str; 4] = ["whole", "pie", "chord", "arc"];
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
@@ -26,7 +44,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Rectangle",
[],
None,
"{x, y, width, height, radius?: pt, radii?: [tl,tr,br,bl], startAngle?, endAngle?: degrees (the part of the outline kept, clockwise from its first anchor, the top-left corner; each side an equal share of 360; default 0 and 360), arcMode?: whole|pie|chord|arc, rotation?: deg clockwise about the centre (0: upright)} → {id}",
"{x, y, width, height: pt (0 or more), radius?: pt (0 or more), radii?: [tl,tr,br,bl] (each 0 or more), startAngle?, endAngle?: degrees (the part of the outline kept, clockwise from its first anchor, the top-left corner; each side an equal share of 360; default 0 and 360), arcMode?: whole|pie|chord|arc, rotation?: deg clockwise about the centre (0: upright)} → {id}",
has_doc,
rectangle
),
@@ -35,7 +53,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Ellipse",
[],
None,
"{x, y, width, height, startAngle?, endAngle?: degrees (counter-clockwise from 3 o'clock, as object.setLiveShape's pieStart and pieEnd; default 0 and 360), arcMode?: whole|pie|chord|arc, rotation?: deg clockwise about the centre (0: upright)} → {id}",
"{x, y, width, height: pt (0 or more), startAngle?, endAngle?: degrees (counter-clockwise from 3 o'clock, as object.setLiveShape's pieStart and pieEnd; default 0 and 360), arcMode?: whole|pie|chord|arc, rotation?: deg clockwise about the centre (0: upright)} → {id}",
has_doc,
ellipse
),
@@ -44,7 +62,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Polygon",
[],
None,
"{cx, cy, radius, sides=6, rounded=0, randomized=0, startAngle?, endAngle?: degrees (the part of the outline kept, clockwise from its first anchor, the top corner; each side an equal share of 360; default 0 and 360), arcMode?: whole|pie|chord|arc, rotation?: deg clockwise (0: a corner straight up)} → {id}",
"{cx, cy, radius: pt (0 or more), sides=6: a whole number 3 to 1000, rounded=0, randomized=0: -10 to 10, startAngle?, endAngle?: degrees (the part of the outline kept, clockwise from its first anchor, the top corner; each side an equal share of 360; default 0 and 360), arcMode?: whole|pie|chord|arc, rotation?: deg clockwise (0: a corner straight up)} → {id}",
has_doc,
polygon
),
@@ -53,7 +71,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Star",
[],
None,
"{cx, cy, radius1, radius2?, points=5, rounded=0, randomized=0, startAngle?, endAngle?: degrees (the part of the outline kept, clockwise from its first anchor, the top point; each side an equal share of 360; default 0 and 360), arcMode?: whole|pie|chord|arc, rotation?: deg clockwise (0: a point straight up)} → {id}",
"{cx, cy, radius1: pt (0 or more), radius2?: pt (0.01 to 1 times radius1; default half of it), points=5: a whole number 3 to 1000, rounded=0, randomized=0: -10 to 10, startAngle?, endAngle?: degrees (the part of the outline kept, clockwise from its first anchor, the top point; each side an equal share of 360; default 0 and 360), arcMode?: whole|pie|chord|arc, rotation?: deg clockwise (0: a point straight up)} → {id}",
has_doc,
star
),
@@ -62,7 +80,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Spiral",
[],
None,
"{cx, cy, radius, turns=3, divergence=1, innerRadius=0, clockwise=true} → {id}",
"{cx, cy, radius: pt (0 or more), turns=3: 0.01 to 1024, divergence=1: 0 to 1000, innerRadius=0: 0 to 0.999 of radius, clockwise=true} → {id}",
has_doc,
spiral
),
@@ -71,7 +89,7 @@ pub fn specs() -> Vec<CommandSpec> {
"3D Box",
[],
None,
"{x, y, width, height, angleX=30 (degrees about the level axis: positive tips the top away from you), angleY=30 (degrees about the upright axis: positive turns the right side away from you), angleZ=0 (degrees clockwise in the page), parallelX=false, parallelY=true, parallelZ=false} → {id}",
"{x, y, width, height: pt (0 or more), angleX=30 (degrees about the level axis: positive tips the top away from you), angleY=30 (degrees about the upright axis: positive turns the right side away from you), angleZ=0 (degrees clockwise in the page), parallelX=false, parallelY=true, parallelZ=false} → {id}",
has_doc,
box3d
),
@@ -80,33 +98,96 @@ pub fn specs() -> Vec<CommandSpec> {
"Configure Shape",
[],
None,
"{ids?, radius?, radii?: [tl,tr,br,bl], startAngle?, endAngle?: degrees (as addon.shapes.rectangle, ellipse, polygon and star take them: an ellipse's counter-clockwise from 3 o'clock, the others' clockwise along the outline), arcMode?: whole|pie|chord|arc, sides?, isStar?, spokeRatio?, rounded?, randomized?, turns?, divergence?, innerRadius?, angleX?, angleY?: degrees (as addon.shapes.box3d: positive tips the top, or turns the right side, away from you), angleZ?: degrees clockwise in the page, parallelX?, parallelY?, parallelZ?, reset?: bool} → {updated}",
"{ids?, radius?: pt (0 or more; fitted to half each rectangle's shorter side), radii?: [tl,tr,br,bl] (each 0 or more), startAngle?, endAngle?: degrees (as addon.shapes.rectangle, ellipse, polygon and star take them: an ellipse's counter-clockwise from 3 o'clock, the others' clockwise along the outline), arcMode?: whole|pie|chord|arc, sides?: a whole number 3 to 1000, isStar?, spokeRatio?: 0.01 to 1, rounded?, randomized?: -10 to 10, turns?: 0.01 to 1024, divergence?: 0 to 1000, innerRadius?: 0 to 0.999, angleX?, angleY?: degrees (as addon.shapes.box3d: positive tips the top, or turns the right side, away from you), angleZ?: degrees clockwise in the page, parallelX?, parallelY?, parallelZ?, reset?: bool} an omitted or null value keeps each shape's setting → {updated}",
has_selection,
configure
),
]
}
fn parse_arc_params(p: &Value) -> ((f64, f64), shapes::EllipseMode) {
/// The number `p` gives for `key`, or `default` when `p` leaves it out or gives null. A number
/// outside `range` is an error that names `key` and the range.
fn ranged(p: &Value, key: &str, default: f64, range: &RangeInclusive<f64>, cmd: &str) -> Result<f64> {
let x = number_or(p, key, default, cmd)?;
if !range.contains(&x) {
let (min, max) = (range.start(), range.end());
return Err(bad(cmd, format!("`{key}` must be between {min} and {max} (got {x})")));
}
Ok(x)
}
/// The number of sides or points `p` gives for `key`, or `default` when `p` leaves it out or gives
/// null. A fraction or a number outside [`COUNTS`] is an error.
fn count(p: &Value, key: &str, default: u32, cmd: &str) -> Result<u32> {
let x = number_or(p, key, f64::from(default), cmd)?;
if x.fract() != 0.0 || !COUNTS.contains(&x) {
let (min, max) = (COUNTS.start(), COUNTS.end());
return Err(bad(cmd, format!("`{key}` must be a whole number between {min} and {max} (got {x})")));
}
Ok(x as u32)
}
/// The size `p` gives for `key`: a number that is not negative.
fn size(p: &Value, key: &str, cmd: &str) -> Result<f64> {
not_negative(f64_req(p, key, cmd)?, key, cmd)
}
/// The size `p` gives for `key`, or `default` when `p` leaves it out or gives null.
fn size_or(p: &Value, key: &str, default: f64, cmd: &str) -> Result<f64> {
not_negative(number_or(p, key, default, cmd)?, key, cmd)
}
fn not_negative(x: f64, key: &str, cmd: &str) -> Result<f64> {
if x < 0.0 {
return Err(bad(cmd, format!("`{key}` must be a number not below 0")));
}
Ok(x)
}
/// The four corner radii `p` gives as `radii` ([tl, tr, br, bl]), or `None` when `p` leaves it out
/// or gives null. Anything but four numbers that are not negative is an error.
fn radii_param(p: &Value, cmd: &str) -> Result<Option<[f64; 4]>> {
let key = "radii";
match p.get(key) {
None | Some(Value::Null) => Ok(None),
Some(v) => {
let four = v.as_array().filter(|a| a.len() == 4).and_then(|a| {
let mut out = [0.0; 4];
for (slot, item) in out.iter_mut().zip(a) {
*slot = item.as_f64().filter(|r| *r >= 0.0)?;
}
Some(out)
});
four.map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be four numbers not below 0: [tl, tr, br, bl]")))
}
}
}
/// The mode `p` gives as `arcMode`, or `None` when `p` leaves it out or gives null. Any other
/// value than one of [`ARC_MODES`] (or `slice` or `open`) is an error.
fn arc_mode(p: &Value, cmd: &str) -> Result<Option<shapes::EllipseMode>> {
let key = "arcMode";
match p.get(key) {
None | Some(Value::Null) => Ok(None),
Some(v) => v.as_str().and_then(parse_mode).map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be one of {}", ARC_MODES.join(", ")))),
}
}
fn parse_arc_params(p: &Value, cmd: &str) -> Result<((f64, f64), shapes::EllipseMode)> {
let start = f64_or(p, "startAngle", 0.0);
let end = f64_or(p, "endAngle", 360.0);
let mode = match str_param(p, "arcMode") {
Some("pie" | "slice") => shapes::EllipseMode::Slice,
Some("chord") => shapes::EllipseMode::Chord,
Some("arc" | "open") => shapes::EllipseMode::Arc,
_ => shapes::EllipseMode::Whole,
};
let mode = arc_mode(p, cmd)?.unwrap_or(shapes::EllipseMode::Whole);
let span = (end - start).rem_euclid(360.0);
let pie = if mode == shapes::EllipseMode::Whole && (span < 1e-6 || (span - 360.0).abs() < 1e-6) { (0.0, 360.0) } else { (start, end) };
(pie, mode)
Ok((pie, mode))
}
fn rect_of(p: &Value, c: &str) -> Result<Rect> {
let x = f64_req(p, "x", c)?;
let y = f64_req(p, "y", c)?;
let w = f64_req(p, "width", c)?;
let h = f64_req(p, "height", c)?;
Ok(Rect::new(x, y, x + w.abs(), y + h.abs()).abs())
let w = size(p, "width", c)?;
let h = size(p, "height", c)?;
Ok(Rect::new(x, y, x + w, y + h))
}
fn rect_xf(r: Rect, rot: f64) -> Affine {
@@ -141,18 +222,9 @@ fn rectangle(s: &mut Session, p: &Value) -> Result<Value> {
let c = "addon.shapes.rectangle";
check_numbers(p, &["radius", "startAngle", "endAngle", "rotation"], c)?;
let r = rect_of(p, c)?;
let radius = f64_or(p, "radius", 0.0).max(0.0);
let mut radii = [radius; 4];
if let Some(arr) = p.get("radii").and_then(Value::as_array)
&& arr.len() == 4
{
for (i, item) in arr.iter().enumerate() {
if let Some(val) = item.as_f64().filter(|n| n.is_finite()) {
radii[i] = val.max(0.0);
}
}
}
let (pie, arc_mode) = parse_arc_params(p);
let radius = size_or(p, "radius", 0.0, c)?;
let radii = radii_param(p, c)?.unwrap_or([radius; 4]);
let (pie, arc_mode) = parse_arc_params(p, c)?;
let xf = rect_xf(r, f64_or(p, "rotation", 0.0));
let live = LiveShape::Rectangle { w: r.width(), h: r.height(), radii, kinds: Default::default(), radii_relative: false, xf };
let cs = CustomShape::Rectangle { w: r.width(), h: r.height(), radii, kinds: Default::default(), radii_relative: false, xf, pie, arc_mode };
@@ -164,7 +236,7 @@ fn ellipse(s: &mut Session, p: &Value) -> Result<Value> {
let c = "addon.shapes.ellipse";
check_numbers(p, &["startAngle", "endAngle", "rotation"], c)?;
let r = rect_of(p, c)?;
let (pie, arc_mode) = parse_arc_params(p);
let (pie, arc_mode) = parse_arc_params(p, c)?;
let xf = rect_xf(r, f64_or(p, "rotation", 0.0));
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie, xf };
let cs = CustomShape::Ellipse { w: r.width(), h: r.height(), pie, arc_mode, xf };
@@ -174,13 +246,13 @@ fn ellipse(s: &mut Session, p: &Value) -> Result<Value> {
fn polygon(s: &mut Session, p: &Value) -> Result<Value> {
let c = "addon.shapes.polygon";
let center = Point::new(f64_req(p, "cx", c)?, f64_req(p, "cy", c)?);
let r = f64_req(p, "radius", c)?.abs();
let r = size(p, "radius", c)?;
check_numbers(p, &["sides", "rotation", "rounded", "randomized", "startAngle", "endAngle"], c)?;
let sides = (f64_or(p, "sides", 6.0).round() as i64).clamp(3, 1000) as u32;
let sides = count(p, "sides", 6, c)?;
let rot = f64_or(p, "rotation", 0.0);
let rounded = f64_or(p, "rounded", 0.0).clamp(-10.0, 10.0);
let randomized = f64_or(p, "randomized", 0.0).clamp(-10.0, 10.0);
let (pie, arc_mode) = parse_arc_params(p);
let rounded = ranged(p, "rounded", 0.0, &ROUNDING, c)?;
let randomized = ranged(p, "randomized", 0.0, &ROUNDING, c)?;
let (pie, arc_mode) = parse_arc_params(p, c)?;
let xf = Affine::translate(center.to_vec2()) * vectorcraft_geom::rotate_deg(rot);
let live = LiveShape::Polygon { radius: r, sides, xf, radii: vec![], kinds: vec![], radii_relative: false };
let cs = CustomShape::Polygon {
@@ -202,16 +274,17 @@ fn polygon(s: &mut Session, p: &Value) -> Result<Value> {
fn star(s: &mut Session, p: &Value) -> Result<Value> {
let c = "addon.shapes.star";
let center = Point::new(f64_req(p, "cx", c)?, f64_req(p, "cy", c)?);
let r1 = f64_req(p, "radius1", c)?.abs();
let r1 = size(p, "radius1", c)?;
check_numbers(p, &["radius2", "points", "rotation", "rounded", "randomized", "startAngle", "endAngle"], c)?;
let r2 = f64_or(p, "radius2", r1 / 2.0).abs();
let points = (f64_or(p, "points", 5.0).round() as i64).clamp(3, 1000) as u32;
// The inner radius is a fraction of the outer one, in `SPOKE_RATIO`.
let r2 = ranged(p, "radius2", r1 / 2.0, &(r1 * SPOKE_RATIO.start()..=r1 * SPOKE_RATIO.end()), c)?;
let points = count(p, "points", 5, c)?;
let rot = f64_or(p, "rotation", 0.0);
let rounded = f64_or(p, "rounded", 0.0).clamp(-10.0, 10.0);
let randomized = f64_or(p, "randomized", 0.0).clamp(-10.0, 10.0);
let (pie, arc_mode) = parse_arc_params(p);
let rounded = ranged(p, "rounded", 0.0, &ROUNDING, c)?;
let randomized = ranged(p, "randomized", 0.0, &ROUNDING, c)?;
let (pie, arc_mode) = parse_arc_params(p, c)?;
let xf = Affine::translate(center.to_vec2()) * vectorcraft_geom::rotate_deg(rot);
let ratio = if r1 > 1e-9 { (r2 / r1).clamp(0.01, 1.0) } else { 0.5 };
let ratio = if r1 > 1e-9 { (r2 / r1).clamp(*SPOKE_RATIO.start(), *SPOKE_RATIO.end()) } else { 0.5 };
let cs = CustomShape::Polygon {
radius: r1,
sides: points,
@@ -231,12 +304,12 @@ fn star(s: &mut Session, p: &Value) -> Result<Value> {
fn spiral(s: &mut Session, p: &Value) -> Result<Value> {
let c = "addon.shapes.spiral";
let center = Point::new(f64_req(p, "cx", c)?, f64_req(p, "cy", c)?);
let r = f64_req(p, "radius", c)?.abs();
let r = size(p, "radius", c)?;
check_numbers(p, &["turns", "divergence", "innerRadius"], c)?;
check_switches(p, &["clockwise"], c)?;
let turns = f64_or(p, "turns", 3.0).clamp(0.01, 1024.0);
let divergence = f64_or(p, "divergence", 1.0).clamp(0.0, 1000.0);
let inner_radius = f64_or(p, "innerRadius", 0.0).clamp(0.0, 0.999);
let turns = ranged(p, "turns", 3.0, &TURNS, c)?;
let divergence = ranged(p, "divergence", 1.0, &DIVERGENCE, c)?;
let inner_radius = ranged(p, "innerRadius", 0.0, &INNER_RADIUS, c)?;
let clockwise = bool_or(p, "clockwise", true);
let cs = CustomShape::Spiral { center, radius: r, turns, divergence, inner_radius, clockwise };
insert_custom(s, "Spiral", None, cs)
@@ -299,24 +372,54 @@ fn configure(s: &mut Session, p: &Value) -> Result<Value> {
c,
)?;
check_switches(p, &["isStar", "parallelX", "parallelY", "parallelZ", "reset"], c)?;
check_configure(p, c)?;
let ids = targets(s, p)?;
let reset = bool_or(p, "reset", false);
let spiral_hint = p.get("turns").is_some() || p.get("divergence").is_some() || p.get("innerRadius").is_some();
// The shapes the params change, worked out first so that a call that changes nothing records
// no undo step.
let changes: Vec<(NodeId, CustomShape)> = {
let doc = &s.doc()?.doc;
ids.into_iter()
.filter_map(|id| {
let n = doc.node(id)?;
let before = CustomShape::read_for_update(n, spiral_hint)?;
let mut cs = before.clone();
let stored = CustomShape::read(n).is_some();
(apply_shape_params(&mut cs, p, reset) && (cs != before || !stored)).then_some((id, cs))
})
.collect()
};
if changes.is_empty() {
return Ok(json!({ "updated": 0 }));
}
let updated = s.edit("Live Shape", |d, _| {
let mut count = 0usize;
for id in ids {
let Some(n) = d.node_mut(id) else { continue };
let Some(mut cs) = CustomShape::read_for_update(n, spiral_hint) else { continue };
if apply_shape_params(&mut cs, p, reset) {
cs.write_to_node(n);
count += 1;
}
for (id, cs) in &changes {
let Some(n) = d.node_mut(*id) else { continue };
cs.write_to_node(n);
count += 1;
}
Ok(count)
})?;
Ok(json!({ "updated": updated }))
}
/// Error unless every bounded value `p` gives is in its range, before any shape changes.
fn check_configure(p: &Value, c: &str) -> Result<()> {
size_or(p, "radius", 0.0, c)?;
radii_param(p, c)?;
arc_mode(p, c)?;
count(p, "sides", 6, c)?;
ranged(p, "spokeRatio", 0.5, &SPOKE_RATIO, c)?;
ranged(p, "rounded", 0.0, &ROUNDING, c)?;
ranged(p, "randomized", 0.0, &ROUNDING, c)?;
ranged(p, "turns", 3.0, &TURNS, c)?;
ranged(p, "divergence", 1.0, &DIVERGENCE, c)?;
ranged(p, "innerRadius", 0.0, &INNER_RADIUS, c)?;
Ok(())
}
fn num_param(p: &Value, k: &str) -> Option<f64> {
p.get(k).and_then(Value::as_f64).filter(|v| v.is_finite())
}
@@ -331,8 +434,8 @@ fn apply_arc_params(p: &Value, pie: &mut (f64, f64), arc_mode: &mut shapes::Elli
pie.1 = a1.rem_euclid(360.0);
changed = true;
}
if let Some(m) = str_param(p, "arcMode") {
*arc_mode = parse_mode(m);
if let Some(m) = str_param(p, "arcMode").and_then(parse_mode) {
*arc_mode = m;
if *arc_mode == shapes::EllipseMode::Whole {
*pie = (0.0, 360.0);
} else if (pie.1 - pie.0).abs() < 1e-6 || ((pie.1 - pie.0).abs() - 360.0).abs() < 1e-6 {
@@ -351,19 +454,14 @@ fn apply_rect_params(p: &Value, reset: bool, max_r: f64, radii: &mut [f64; 4], p
*arc_mode = shapes::EllipseMode::Whole;
changed = true;
}
// A radius larger than half the rectangle's shorter side is fitted to that size.
if let Some(r) = num_param(p, "radius") {
*radii = [r.clamp(0.0, max_r); 4];
changed = true;
}
if let Some(arr) = p.get("radii").and_then(Value::as_array)
&& arr.len() == 4
{
for (i, v) in arr.iter().enumerate() {
if let Some(r) = v.as_f64().filter(|x| x.is_finite()) {
radii[i] = r.clamp(0.0, max_r);
changed = true;
}
}
if let Ok(Some(four)) = radii_param(p, "addon.shapes.configure") {
*radii = four.map(|r| r.clamp(0.0, max_r));
changed = true;
}
changed | apply_arc_params(p, pie, arc_mode)
}
@@ -378,8 +476,9 @@ fn apply_poly_params(p: &Value, reset: bool, sides: &mut u32, spoke_ratio: &mut
}
changed = true;
}
if let Some(n_sides) = p.get("sides").and_then(Value::as_u64) {
*sides = (n_sides as u32).clamp(3, 1000);
// `check_configure` has refused values outside their ranges.
if let Some(n_sides) = num_param(p, "sides") {
*sides = n_sides as u32;
changed = true;
}
if let Some(star) = p.get("isStar").and_then(Value::as_bool) {
@@ -387,15 +486,15 @@ fn apply_poly_params(p: &Value, reset: bool, sides: &mut u32, spoke_ratio: &mut
changed = true;
}
if let Some(sr) = num_param(p, "spokeRatio") {
*spoke_ratio = Some(sr.clamp(0.01, 1.0));
*spoke_ratio = Some(sr);
changed = true;
}
if let Some(rnd) = num_param(p, "rounded") {
*rounded = rnd.clamp(-10.0, 10.0);
*rounded = rnd;
changed = true;
}
if let Some(rand) = num_param(p, "randomized") {
*randomized = rand.clamp(-10.0, 10.0);
*randomized = rand;
changed = true;
}
changed
@@ -429,15 +528,15 @@ fn apply_shape_params(cs: &mut CustomShape, p: &Value, reset: bool) -> bool {
changed = true;
}
if let Some(t) = num_param(p, "turns") {
*turns = t.clamp(0.01, 1024.0);
*turns = t;
changed = true;
}
if let Some(div) = num_param(p, "divergence") {
*divergence = div.clamp(0.0, 1000.0);
*divergence = div;
changed = true;
}
if let Some(ir) = num_param(p, "innerRadius") {
*inner_radius = ir.clamp(0.0, 0.999);
*inner_radius = ir;
changed = true;
}
changed
@@ -470,11 +569,12 @@ fn apply_shape_params(cs: &mut CustomShape, p: &Value, reset: bool) -> bool {
}
}
fn parse_mode(m: &str) -> shapes::EllipseMode {
fn parse_mode(m: &str) -> Option<shapes::EllipseMode> {
match m {
"pie" | "slice" => shapes::EllipseMode::Slice,
"chord" => shapes::EllipseMode::Chord,
"arc" | "open" => shapes::EllipseMode::Arc,
_ => shapes::EllipseMode::Whole,
"whole" => Some(shapes::EllipseMode::Whole),
"pie" | "slice" => Some(shapes::EllipseMode::Slice),
"chord" => Some(shapes::EllipseMode::Chord),
"arc" | "open" => Some(shapes::EllipseMode::Arc),
_ => None,
}
}
@@ -135,3 +135,169 @@ fn addon_shapes_commands_and_format_roundtrip_preserve_paths() {
assert_eq!(CustomShape::read(a), CustomShape::read(b));
}
}
fn id_of(s: &mut Session, cmd: &str, p: serde_json::Value) -> NodeId {
NodeId(s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd} {p}: {e}"))["id"].as_u64().unwrap())
}
fn shape_of(s: &Session, id: NodeId) -> CustomShape {
CustomShape::read(s.doc().unwrap().doc.node(id).unwrap()).unwrap()
}
/// 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) {
let saved = vectorcraft_format::save(&s.doc().unwrap().doc, false);
let undo = s.doc().unwrap().history.undo.len();
let e = s.execute(cmd, &p).map(|v| v.to_string()).unwrap_err().to_string();
assert!(e.contains(msg), "{cmd} {p}: {e}");
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{cmd} {p}");
assert_eq!(vectorcraft_format::save(&s.doc().unwrap().doc, false), saved, "{cmd} {p}");
}
#[test]
fn polygon_and_star_refuse_counts_that_are_not_whole_numbers_from_3_to_1000() {
let mut s = new_session();
for n in [json!(2.5), json!(2), json!(0), json!(-6), json!(1000.5), json!(5000), json!(4_294_967_299u64)] {
let x = n.as_f64().unwrap();
let p = json!({"cx": 0.0, "cy": 0.0, "radius": 10.0, "sides": n});
refused(&mut s, "addon.shapes.polygon", p, &format!("`sides` must be a whole number between 3 and 1000 (got {x})"));
let p = json!({"cx": 0.0, "cy": 0.0, "radius1": 10.0, "points": n});
refused(&mut s, "addon.shapes.star", p, &format!("`points` must be a whole number between 3 and 1000 (got {x})"));
}
refused(&mut s, "addon.shapes.polygon", json!({"cx": 0.0, "cy": 0.0, "radius": 10.0, "sides": "6"}), "`sides` must be a number");
refused(&mut s, "addon.shapes.star", json!({"cx": 0.0, "cy": 0.0, "radius1": 10.0, "points": [5]}), "`points` must be a number");
// The ends of the range are taken as given, and an omitted or null count is the default.
for (n, want) in [(json!(3), 3), (json!(1000), 1000), (json!(7.0), 7), (json!(null), 6)] {
let id = id_of(&mut s, "addon.shapes.polygon", json!({"cx": 0.0, "cy": 0.0, "radius": 10.0, "sides": n}));
assert!(matches!(shape_of(&s, id), CustomShape::Polygon { sides, spoke_ratio: None, .. } if sides == want), "{n}");
}
let id = id_of(&mut s, "addon.shapes.polygon", json!({"cx": 0.0, "cy": 0.0, "radius": 10.0}));
assert!(matches!(shape_of(&s, id), CustomShape::Polygon { sides: 6, .. }));
for (n, want) in [(json!(3), 3), (json!(1000), 1000), (json!(null), 5)] {
let id = id_of(&mut s, "addon.shapes.star", json!({"cx": 0.0, "cy": 0.0, "radius1": 10.0, "points": n}));
assert!(matches!(shape_of(&s, id), CustomShape::Polygon { sides, spoke_ratio: Some(_), .. } if sides == want), "{n}");
}
}
#[test]
fn shapes_refuse_numbers_outside_their_ranges() {
let mut s = new_session();
let poly = json!({"cx": 0.0, "cy": 0.0, "radius": 10.0});
let star = json!({"cx": 0.0, "cy": 0.0, "radius1": 10.0});
let spiral = json!({"cx": 0.0, "cy": 0.0, "radius": 10.0});
let with = |base: &serde_json::Value, key: &str, v: f64| {
let mut p = base.clone();
p[key] = json!(v);
p
};
for (cmd, base, key, bad, good) in [
("addon.shapes.polygon", &poly, "rounded", [-10.5, 10.5], [-10.0, 10.0]),
("addon.shapes.polygon", &poly, "randomized", [-11.0, 10.01], [-10.0, 10.0]),
("addon.shapes.star", &star, "rounded", [-10.5, 10.5], [-10.0, 10.0]),
("addon.shapes.star", &star, "randomized", [-11.0, 10.01], [-10.0, 10.0]),
("addon.shapes.star", &star, "radius2", [0.05, 11.0], [0.1, 10.0]),
("addon.shapes.spiral", &spiral, "turns", [0.0, 1024.5], [0.01, 1024.0]),
("addon.shapes.spiral", &spiral, "divergence", [-0.1, 1000.5], [0.0, 1000.0]),
("addon.shapes.spiral", &spiral, "innerRadius", [-0.1, 1.0], [0.0, 0.999]),
] {
let (min, max) = (good[0], good[1]);
for x in bad {
refused(&mut s, cmd, with(base, key, x), &format!("`{key}` must be between {min} and {max} (got {x})"));
}
for x in good {
s.execute(cmd, &with(base, key, x)).unwrap_or_else(|e| panic!("{cmd} {key} {x}: {e}"));
}
}
// Sizes are not negative.
for (cmd, p, key) in [
("addon.shapes.polygon", json!({"cx": 0.0, "cy": 0.0, "radius": -10.0}), "radius"),
("addon.shapes.star", json!({"cx": 0.0, "cy": 0.0, "radius1": -10.0}), "radius1"),
("addon.shapes.spiral", json!({"cx": 0.0, "cy": 0.0, "radius": -10.0}), "radius"),
("addon.shapes.rectangle", json!({"x": 0.0, "y": 0.0, "width": -10.0, "height": 10.0}), "width"),
("addon.shapes.rectangle", json!({"x": 0.0, "y": 0.0, "width": 10.0, "height": 10.0, "radius": -1.0}), "radius"),
("addon.shapes.ellipse", json!({"x": 0.0, "y": 0.0, "width": 10.0, "height": -10.0}), "height"),
("addon.shapes.box3d", json!({"x": 0.0, "y": 0.0, "width": -10.0, "height": 10.0}), "width"),
] {
refused(&mut s, cmd, p, &format!("`{key}` must be a number not below 0"));
}
// Corner radii are four numbers that are not negative.
for radii in [json!([1.0, 2.0, 3.0]), json!([1.0, 2.0, 3.0, -4.0]), json!([1.0, 2.0, 3.0, "4"]), json!(4.0)] {
let p = json!({"x": 0.0, "y": 0.0, "width": 100.0, "height": 80.0, "radii": radii});
refused(&mut s, "addon.shapes.rectangle", p, "`radii` must be four numbers not below 0: [tl, tr, br, bl]");
}
// An arc mode is one of the names the commands take.
for mode in [json!("slices"), json!(""), json!(3)] {
let p = json!({"x": 0.0, "y": 0.0, "width": 100.0, "height": 80.0, "arcMode": mode});
refused(&mut s, "addon.shapes.rectangle", p.clone(), "`arcMode` must be one of whole, pie, chord, arc");
refused(&mut s, "addon.shapes.ellipse", p, "`arcMode` must be one of whole, pie, chord, arc");
}
for mode in ["whole", "pie", "slice", "chord", "arc", "open"] {
s.execute("addon.shapes.ellipse", &json!({"x": 0.0, "y": 0.0, "width": 100.0, "height": 80.0, "arcMode": mode})).unwrap();
}
}
#[test]
fn configure_refuses_values_outside_their_ranges_before_changing_any_shape() {
let mut s = new_session();
let rect = id_of(&mut s, "addon.shapes.rectangle", json!({"x": 0.0, "y": 0.0, "width": 100.0, "height": 80.0, "radius": 4.0}));
let poly = id_of(&mut s, "addon.shapes.polygon", json!({"cx": 50.0, "cy": 50.0, "radius": 40.0, "sides": 5}));
let spiral = id_of(&mut s, "addon.shapes.spiral", json!({"cx": 60.0, "cy": 60.0, "radius": 45.0}));
let ids = json!([rect.0, poly.0, spiral.0]);
let cfg = |key: &str, v: serde_json::Value| json!({"ids": ids.clone(), key: v});
let c = "addon.shapes.configure";
for n in [json!(2.5), json!(2), json!(-1), json!(5000), json!(4_294_967_299u64)] {
let x = n.as_f64().unwrap();
refused(&mut s, c, cfg("sides", n), &format!("`sides` must be a whole number between 3 and 1000 (got {x})"));
}
for (key, bad, min, max) in [
("spokeRatio", [0.0, 1.5], 0.01, 1.0),
("rounded", [-10.5, 11.0], -10.0, 10.0),
("randomized", [-11.0, 10.5], -10.0, 10.0),
("turns", [0.0, 2000.0], 0.01, 1024.0),
("divergence", [-1.0, 1000.5], 0.0, 1000.0),
("innerRadius", [-0.5, 1.0], 0.0, 0.999),
] {
for x in bad {
refused(&mut s, c, cfg(key, json!(x)), &format!("`{key}` must be between {min} and {max} (got {x})"));
}
}
refused(&mut s, c, cfg("radius", json!(-1.0)), "`radius` must be a number not below 0");
for radii in [json!([1.0, 2.0]), json!([1.0, 2.0, 3.0, -1.0]), json!("4")] {
refused(&mut s, c, cfg("radii", radii), "`radii` must be four numbers not below 0: [tl, tr, br, bl]");
}
refused(&mut s, c, cfg("arcMode", json!("bogus")), "`arcMode` must be one of whole, pie, chord, arc");
// A valid value next to a refused one changes no shape either.
refused(&mut s, c, json!({"ids": ids.clone(), "sides": 8, "turns": 0.0}), "`turns` must be between 0.01 and 1024 (got 0)");
// In range, the values are taken as given; a radius larger than the rectangle takes is fitted to it.
s.execute(c, &json!({"ids": [poly.0], "sides": 1000, "rounded": -10.0, "randomized": 10.0})).unwrap();
assert!(matches!(shape_of(&s, poly), CustomShape::Polygon { sides: 1000, rounded, randomized, .. } if rounded == -10.0 && randomized == 10.0));
s.execute(c, &json!({"ids": [poly.0], "sides": 3})).unwrap();
assert!(matches!(shape_of(&s, poly), CustomShape::Polygon { sides: 3, .. }));
s.execute(c, &json!({"ids": [spiral.0], "turns": 1024.0, "divergence": 0.0, "innerRadius": 0.999})).unwrap();
assert!(
matches!(shape_of(&s, spiral), CustomShape::Spiral { turns, divergence, inner_radius, .. } if turns == 1024.0 && divergence == 0.0 && inner_radius == 0.999)
);
s.execute(c, &json!({"ids": [rect.0], "radius": 1000.0})).unwrap();
assert!(matches!(shape_of(&s, rect), CustomShape::Rectangle { radii, .. } if radii == [40.0; 4]));
}
#[test]
fn configure_records_no_undo_step_when_nothing_changes() {
let mut s = new_session();
let poly = id_of(&mut s, "addon.shapes.polygon", json!({"cx": 50.0, "cy": 50.0, "radius": 40.0, "sides": 5, "rounded": 0.5}));
let undo = s.doc().unwrap().history.undo.len();
let r = s.execute("addon.shapes.configure", &json!({"ids": [poly.0], "sides": 5, "rounded": 0.5})).unwrap();
assert_eq!(r["updated"], 0);
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
let r = s.execute("addon.shapes.configure", &json!({"ids": [poly.0], "sides": 6})).unwrap();
assert_eq!(r["updated"], 1);
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
assert!(matches!(shape_of(&s, poly), CustomShape::Polygon { sides: 6, .. }));
}
+43 -10
View File
@@ -36,7 +36,7 @@ use super::paint::paint_from;
use super::{AppearanceAttrs, EyedropperAttrs, FillAttrs, StrokeAttrs};
use super::{
CommandSpec, NodeId, Result, Session, bad, check_numbers, check_switches, cmd, has_doc, has_selection, ids_param, index, leaf_targets,
object_param, ok, paint_targets, str_param, switch_or, targets,
object_param, ok, paint_targets, str_param, switch_or, targets, u64_req,
};
use crate::EngineError;
@@ -419,6 +419,27 @@ pub(crate) fn appearance_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>>
if targets_contents(p)? { leaf_targets(s, &roots) } else { Ok(roots) }
}
/// The refusal of an appearance edit whose targets are all the art of graph designs drawn in graph series.
const DESIGN_ART: &str = "the art of a graph design in a graph series is drawn again from the design: edit the design to change it";
/// The [`appearance_targets`] whose rows and effects a command edits: the art of graph designs drawn in graph series
/// ([`super::graph::is_design_art`]) is left out, as the graph draws it again from the design. A command whose targets
/// are all such art is refused.
pub(crate) fn edit_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
let ids = appearance_targets(s, p)?;
without_design_art(&s.doc()?.doc, ids, "appearance")
}
/// `ids` without the art of graph designs drawn in graph series; `cmd` is refused when `ids` held nothing else.
pub(crate) fn without_design_art(d: &Document, mut ids: Vec<NodeId>, cmd: &str) -> Result<Vec<NodeId>> {
let given = ids.len();
ids.retain(|id| !super::graph::is_design_art(d, *id));
if given > 0 && ids.is_empty() {
return Err(bad(cmd, DESIGN_ART));
}
Ok(ids)
}
/// `ids` with each graph series group that has no fill or stroke row of its own replaced by the paths directly inside
/// it ([`super::graph::series_group_marks`]). A series group with rows, as a document saved earlier can hold, stays:
/// the Appearance panel lists those rows and edits them by index.
@@ -453,17 +474,17 @@ pub(crate) fn look_holder<'a>(d: &'a Document, n: &'a Node) -> &'a Node {
look_holders(d, n.id).last().and_then(|id| d.node(*id)).unwrap_or(n)
}
/// Objects whose fill and stroke rows a command edits: the [`appearance_targets`], with a graph series group standing
/// for the paths directly inside it ([`rowless_series_marks`]), so the graph can store the edit.
/// Objects whose fill and stroke rows a command edits: the [`edit_targets`], with a graph series group standing for the
/// paths directly inside it ([`rowless_series_marks`]), so the graph can store the edit.
pub(crate) fn row_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
let ids = appearance_targets(s, p)?;
let ids = edit_targets(s, p)?;
Ok(rowless_series_marks(&s.doc()?.doc, &ids))
}
/// Objects whose whole appearance a command edits: the [`row_targets`], then each graph series group they stand for,
/// which can hold effects and a graphic style link of its own.
pub(crate) fn whole_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
let own = appearance_targets(s, p)?;
let own = edit_targets(s, p)?;
let mut ids = rowless_series_marks(&s.doc()?.doc, &own);
let groups = stood_for(&own, &ids);
ids.extend(groups);
@@ -583,9 +604,9 @@ pub(crate) fn edits_stroke(s: &Session, p: &Value, item: ItemTarget, default: bo
Ok(ids.get(item.anchor(s, &ids)).and_then(|id| d.node(*id)?.appearance.items.get(index)).map_or(default, |it| !it.is_fill()))
}
/// The whole number of 0 or more that `key` holds, read with [`index`].
/// The whole number of 0 or more that `key` holds, read with [`u64_req`] and [`index`].
pub(crate) fn index_param(p: &Value, key: &str, cmd: &str) -> Result<usize> {
p.get(key).and_then(Value::as_u64).map(index).ok_or_else(|| bad(cmd, format!("missing integer `{key}`")))
u64_req(p, key, cmd).map(index)
}
fn set_active_item(s: &mut Session, p: &Value) -> Result<Value> {
@@ -806,12 +827,18 @@ pub(super) fn capture_series_writes(
/// and objects the edit left as they were keep what the graph stores. When the edit changes several marks of one series,
/// the frontmost one sets what the graph stores, whatever order `ids` are in. Returns whether the stored paint changed.
pub(crate) fn capture_series_changes(before: &vectorcraft_doc::Document, d: &mut vectorcraft_doc::Document, ids: &[NodeId]) -> bool {
let marks = series_children_in_paint_order(d, ids);
!marks.is_empty() && capture_series_writes(before, d, &marks, (false, false), (false, false), false, false)
}
/// Each of `ids` directly in a series group, from the back to the front: a later mark's capture replaces an earlier
/// one's, so the frontmost one sets what the graph stores.
pub(crate) fn series_children_in_paint_order(d: &vectorcraft_doc::Document, ids: &[NodeId]) -> Vec<NodeId> {
// Only objects directly in a series group can be marks: other edits skip the search of the document for graphs.
let in_series = |id: &NodeId| d.parent_of(*id).and_then(|p| d.node(p)).is_some_and(|g| g.extras().series_index.is_some());
let mut marks: Vec<NodeId> = ids.iter().copied().filter(in_series).collect();
// A later mark's capture replaces an earlier one's: take them in paint order.
marks.sort_by_cached_key(|id| d.index_path(*id));
!marks.is_empty() && capture_series_writes(before, d, &marks, (false, false), (false, false), false, false)
marks
}
/// Store on the graph the paint that an edit of `ids` (from `before` to `d`) leaves on the topmost visible fill and stroke
@@ -863,6 +890,11 @@ fn transfer(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, "`source` and `target` are the same object"));
}
let copy = switch_or(p, "copy", false, C)?;
// The art of a graph design in a series is read as a source, but neither takes an appearance nor gives one up.
without_design_art(&s.doc()?.doc, vec![target], C)?;
if !copy {
without_design_art(&s.doc()?.doc, vec![source], C)?;
}
// A graph series group stands for the paths directly inside it: as the source, the topmost of them is read and a
// move clears them all; as the target, each of them other than a source takes the appearance.
let sources = look_holders(&s.doc()?.doc, source);
@@ -1239,7 +1271,7 @@ fn move_item(s: &mut Session, p: &Value) -> Result<Value> {
let aligned = aligned(p, C)?;
if p.get("from").and_then(Value::as_str) == Some("contents") {
// A graph series group's own Contents row, not its paths, which have none.
let ids = appearance_targets(s, p)?;
let ids = edit_targets(s, p)?;
if ids.is_empty() {
return Err(bad(C, "select objects or give ids"));
}
@@ -1441,6 +1473,7 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
(Some(clicked), leaf_targets(s, &selected)?)
};
targets.retain(|id| Some(*id) != source);
let mut targets = without_design_art(&s.doc()?.doc, targets, C)?;
let node = match source {
Some(id) => Arc::new(s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?.clone()),
None => s.eyedropper_sample.clone().ok_or_else(|| bad(C, "select the object to copy from"))?,
+2 -2
View File
@@ -53,7 +53,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export Assets",
[],
None,
"{assets?: [asset id…] (default all but the 3D assets, which assets.export3D writes), folder?, zip?, openLocation?, formats?, preset?, settings?, prefix?, subfolders?, antiAlias?} each asset's art alone, cropped to it, in every format row: document.exportForScreens {assets} at the document's export settings (document.exportSettings) under the ones given; with subfolders false every file goes into the folder itself, mobile and density rows too → what document.exportForScreens returns (no folder: the files, or one zip, as dataBase64). Leaves the remembered settings as they are (assets.settings.set changes them)",
"{assets?: [asset id…] (default all but the 3D assets, which assets.export3D writes), folder?, zip?, openLocation?, formats?, preset?, settings?, prefix?, subfolders?, antiAlias?} each asset's art alone, cropped to it, in every format row: document.exportForScreens {assets} at the document's export settings (document.exportSettings) under the ones given; with subfolders false every file goes into the folder itself, mobile and density rows too → what document.exportForScreens returns (no folder: the files, or one zip, as dataBase64; warnings name a key in the rows or settings given that only another format takes, not one in the remembered settings). Leaves the remembered settings as they are (assets.settings.set changes them)",
has_doc,
export
),
@@ -429,7 +429,7 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
}
q.insert("assets".into(), json!(all));
}
export_screens(s, &Value::Object(q)).map_err(|e| of_cmd(C, e))
export_screens(s, &Value::Object(q), p).map_err(|e| of_cmd(C, e))
}
fn settings_set(s: &mut Session, p: &Value) -> Result<Value> {
+1 -1
View File
@@ -226,7 +226,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Break Link to Symbol",
[],
None,
"{ids?|id?} expand selected instances into plain art (with their appearance changes to a dynamic symbol), placed through the symbol's 9-slice guides when it has them, with the instance's opacity mask; a hidden or locked instance's art stays hidden or locked and is not selected → {ids}",
"{ids?|id?} expand selected instances into plain art (with their appearance changes to a dynamic symbol), placed through the symbol's 9-slice guides when it has them, with the instance's opacity mask and its own bounding box (square after Reset Bounding Box); a hidden or locked instance's art stays hidden or locked and is not selected → {ids}",
has_selection,
symbol_break_link
),
+11 -3
View File
@@ -393,8 +393,10 @@ pub(super) fn symbol_place(s: &mut Session, p: &Value) -> Result<Value> {
/// The plain art of instance `inst` in document space (fresh ids), with the instance's own
/// appearance changes to a dynamic symbol's art when `own`, placed through its symbol's 9-slice
/// guides when it has them. The instance's opacity mask goes on the art, or on a group around it
/// when the art has a mask of its own.
/// guides when it has them. The art's bounding boxes turn with the instance's own box, so after
/// Reset Bounding Box they stand as the instance's box does. The instance's opacity mask goes on
/// the art, or on a group around it when the art has a mask of its own; a group added around the
/// art takes the instance's box angle.
fn expanded_instance(d: &mut Document, inst: &Node, own: bool) -> Option<Node> {
let NodeKind::SymbolInstance { symbol, xf } = &inst.kind else { return None };
let sym = d.symbols.iter().find(|s| &s.name == symbol)?;
@@ -402,12 +404,17 @@ fn expanded_instance(d: &mut Document, inst: &Node, own: bool) -> Option<Node> {
if let Some((color, amount)) = brush::stain(inst) {
brush::tint_node(&mut art, &color, amount);
}
let art = d.place_symbol_art(symbol, &art, *xf)?;
let mut art = d.place_symbol_art(symbol, &art, *xf)?;
let turn = vectorcraft_doc::orient::placed_turn(inst.bbox_angle, *xf);
if turn != 0.0 {
art.turn_boxes(turn);
}
let mut art = d.reid(&art);
if inst.opacity < 1.0 || inst.blend != vectorcraft_color::BlendMode::Normal {
if !matches!(art.kind, NodeKind::Group { .. }) {
let id = d.alloc_id();
art = Node::group(id, vec![Arc::new(art)]);
art.bbox_angle = inst.bbox_angle;
}
art.opacity *= inst.opacity;
art.blend = inst.blend;
@@ -416,6 +423,7 @@ fn expanded_instance(d: &mut Document, inst: &Node, own: bool) -> Option<Node> {
if art.extras().mask.is_some() {
let id = d.alloc_id();
art = Node::group(id, vec![Arc::new(art)]);
art.bbox_angle = inst.bbox_angle;
}
art.extras_mut().mask = Some(mask.clone());
}
+5 -5
View File
@@ -72,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Make",
["Object", "Live Paint"],
Some("Cmd+Alt+X"),
"{ids?|id?} build a Live Paint group from the selected paths (paths, compound paths and groups of them; type, images and other objects are refused, nothing changes); each covered face starts with its front-most covering source's fill; with a Live Paint group among them, add the others to it as livePaint.merge does → {id, faces, edges}",
"{ids?|id?} build a Live Paint group from the selected paths (paths, compound paths and groups of them; type, images and other objects are refused, nothing changes); each covered face starts with its front-most covering source's fill; with a Live Paint group among them, add the others to it as livePaint.merge does; a Live Paint group alone has nothing to add, so it is selected and nothing changes (no undo step) → {id, faces, edges}",
has_selection_or_ids,
lp_make
),
@@ -81,7 +81,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Merge",
["Object", "Live Paint"],
None,
"{ids?|id?} add the other selected paths (compound paths, groups of paths and Live Paint groups too; type, images and other objects are refused, nothing changes) to the bottom-most Live Paint group, keeping its id, its paint and its own properties (name, lock, visibility, transparency, appearance, opacity mask, graphic style link) → {id, faces, edges}",
"{ids?|id?} add the other selected paths (compound paths, groups of paths and Live Paint groups too; type, images and other objects are refused, nothing changes) to the bottom-most Live Paint group, keeping its id, its paint and its own properties (name, lock, visibility, transparency, appearance, opacity mask, graphic style link); a Live Paint group alone has nothing to add, so it is selected and nothing changes (no undo step) → {id, faces, edges}",
has_multi_or_ids,
lp_merge
),
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Gap Options",
[],
None,
"{id?, ids?: [id…] (instead of id; default: the selected Live Paint groups), detect?: bool (Gap Detection: paint stops at gaps up to size wide), size?: \"small\" (3 pt) | \"medium\" (6 pt) | \"large\" (12 pt) | pt (custom, over 0 up to 72) (Paint Stops At), color?: #rrggbb or a layer color's name such as \"Red\" (Gap Preview Color; a hex color with an alpha part, #rrggbbaa or #rgba, is an error), closeGaps?: bool (add an unpainted path across each gap up to size wide to the group's paths)} set the Gap Options of Live Paint groups (what is not given stays as it was; a group starts with detect false, small and Red) and make their faces again, keeping their paint → {ids, faces, gaps: [[x0,y0,x1,y1]…] (the gaps up to size wide that no path closes, from a loose end of a path to where it closes to; detect closes them for paint), closed (paths added)}",
"{id?, ids?: [id…] (instead of id; default: the selected Live Paint groups), detect?: bool (Gap Detection: paint stops at gaps up to size wide), size?: \"small\" (3 pt) | \"medium\" (6 pt) | \"large\" (12 pt) | pt (custom, over 0 up to 72) (Paint Stops At), color?: #rrggbb or a layer color's name such as \"Red\" (Gap Preview Color; a hex color with an alpha part, #rrggbbaa or #rgba, is an error), closeGaps?: bool (add an unpainted path across each gap up to size wide to the group's paths)} set the Gap Options of Live Paint groups (what is not given stays as it was; a group starts with detect false, small and Red) and make their faces again, keeping their paint; when every group already has the options and closeGaps finds no gap, nothing changes (no undo step) → {ids, faces, gaps: [[x0,y0,x1,y1]…] (the gaps up to size wide that no path closes, from a loose end of a path to where it closes to; detect closes them for paint), closed (paths added)}",
has_selection_or_ids,
lp_gap_options
),
@@ -117,7 +117,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Live Paint Bucket",
[],
None,
"{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], points?: [[x,y]…] (a drag polyline starting at point; 1 to 4096 finite canvas points; fills every crossed face of the same group), continuation?: [[[x,y]…]…] (further path chunks of 1 to 4096 finite canvas points each; each starts at the preceding chunk's last point; requires points), color?|swatch?|gradient?|none? (default: current fill; a color in #rrggbbaa or #rgba is refused), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces → {group, face}",
"{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], points?: [[x,y]…] (a drag polyline starting at point; 1 to 4096 finite canvas points; fills every crossed face of the same group), continuation?: [[[x,y]…]…] (further path chunks of 1 to 4096 finite canvas points each; each starts at the preceding chunk's last point; requires points), color?|swatch?|gradient?|none? (default: current fill; a color in #rrggbbaa or #rgba is refused), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces; when every face it reaches already has the paint, nothing changes (no undo step, and the recent colors stay as they are) → {group, face}",
has_doc,
lp_fill
),
@@ -126,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Live Paint Bucket (Stroke)",
[],
None,
"{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point → {group, edge}",
"{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point; when it already has the paint and the width, nothing changes (no undo step, and the recent colors stay as they are) → {group, edge}",
has_doc,
lp_stroke_edge
),
+135 -33
View File
@@ -52,8 +52,34 @@ fn make_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result<
Ok((gid, nf, ne))
}
/// Select `ids` alone, without an undo step, when they are not selected that way already.
fn select_only(s: &mut Session, ids: &[NodeId]) -> Result<()> {
let st = s.doc()?;
let mut sel = st.selection.clone();
sel.set(ids.iter().copied());
if sel != st.selection {
s.select(|_, selection| *selection = sel)?;
}
Ok(())
}
/// Make or Merge given one Live Paint group and nothing else has nothing to add to it, so it leaves
/// the document as it is, records no undo step and selects the group: → its reply. `None` for any
/// other `roots`.
fn lone_live_group(s: &mut Session, roots: &[NodeId]) -> Result<Option<Value>> {
let d = &s.doc()?.doc;
let Some(&g) = roots.first().filter(|g| roots.iter().all(|r| r == *g)) else { return Ok(None) };
let Some(n) = d.node(g).filter(|n| is_live_paint(n)) else { return Ok(None) };
let reply = json!({ "id": g.0, "faces": b::faces(n).len(), "edges": b::edges(n).len() });
select_only(s, &[g])?;
Ok(Some(reply))
}
pub(super) fn lp_make(s: &mut Session, p: &Value) -> Result<Value> {
let roots = root_ids(s, p)?;
if let Some(reply) = lone_live_group(s, &roots)? {
return Ok(reply);
}
let (id, faces, edges) = s.edit("Make Live Paint", |d, sel| make_live(d, sel, &roots))?;
Ok(json!({ "id": id.0, "faces": faces, "edges": edges }))
}
@@ -130,6 +156,9 @@ fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result
pub(super) fn lp_merge(s: &mut Session, p: &Value) -> Result<Value> {
let roots = root_ids(s, p)?;
if let Some(reply) = lone_live_group(s, &roots)? {
return Ok(reply);
}
let (id, faces, edges) = s.edit("Merge Live Paint", |d, sel| merge_live(d, sel, &roots))?;
Ok(json!({ "id": id.0, "faces": faces, "edges": edges }))
}
@@ -230,27 +259,58 @@ pub(super) fn lp_gap_options(s: &mut Session, p: &Value) -> Result<Value> {
};
let close = switch_or(p, "closeGaps", false, C)?;
let targets = live_targets(s, p)?;
let with_params = |mut options: GapOptions| {
options.detect = detect.unwrap_or(options.detect);
options.size = size.unwrap_or(options.size);
options.color = color.unwrap_or(options.color);
options
};
// When every group already has these options and Close Gaps With Paths has no gap to close,
// nothing changes: no undo step, and the reply is the same.
let unchanged = {
let d = &s.doc()?.doc;
let (mut faces, mut gaps, mut same) = (0, vec![], true);
for g in &targets {
let old = d.node(*g).ok_or(EngineError::NoNode(*g))?;
let options = old.gap_options();
if with_params(options) != options {
same = false;
break;
}
let open = open_gaps(old, options);
if close && !open.is_empty() {
same = false;
break;
}
faces += b::faces(old).len();
gaps.extend(open);
}
same.then_some((faces, gaps))
};
if let Some((faces, gaps)) = unchanged {
select_only(s, &targets)?;
return Ok(json!({ "ids": ids_json(&targets), "faces": faces, "gaps": gaps_json(&gaps), "closed": 0 }));
}
let (faces, gaps, closed) = s.edit("Gap Options", |d, sel| {
let (mut faces, mut gaps, mut closed) = (0, vec![], 0);
let mut changed = Beside::replacing(d, &targets);
for g in &targets {
let old = d.node(*g).cloned().ok_or(EngineError::NoNode(*g))?;
let mut options = old.gap_options();
options.detect = detect.unwrap_or(options.detect);
options.size = size.unwrap_or(options.size);
options.color = color.unwrap_or(options.color);
let options = with_params(old.gap_options());
let mut sources = source_nodes(&old);
let mut added = 0;
if close {
// Close Gaps With Paths adds an unpainted line across each gap to the group's paths.
for gap in po::find_gaps(&source_shapes(&sources).0, options.size.points()) {
let line = PathData::single(SubPath::polyline(&gap, false));
sources.push(Arc::new(Node::path(d.alloc_id(), line, Appearance::default())));
closed += 1;
added += 1;
}
}
closed += added;
let mut n = old.clone();
// The faces change only with what paint stops at, or with new paths.
if close || options.max_gap() != old.gap_options().max_gap() {
if added > 0 || options.max_gap() != old.gap_options().max_gap() {
let (children, _, _) = build_children(d, sources, options.max_gap())?;
if let Some(ch) = n.children_mut() {
*ch = children;
@@ -305,27 +365,9 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
let paint = paint_from(s, p)?.unwrap_or_else(|| s.paint.fill.clone());
let group = object_param(p, "group", C)?;
let roots = if group.is_none() { root_ids(s, p)? } else { vec![] };
let (g, face) = s.edit("Live Paint Bucket", |d, sel| {
let gid = match group {
Some(g) => {
if !d.node(g).is_some_and(is_live_paint) {
return Err(bad(C, format!("{g} is not a Live Paint group")));
}
g
}
None => {
let live_at = |face: fn(&Node, Point) -> Option<&Arc<Node>>| {
roots.iter().copied().find(|r| d.node(*r).is_some_and(|n| is_live_paint(n) && face(n, pt).is_some()))
};
match (live_at(b::visible_face_at), live_at(face_at)) {
(Some(g), _) => g,
// At a point on a hidden face of a Live Paint group among the objects, the command returns an error
// and does not merge the objects.
(None, Some(_)) => return Err(EngineError::Other("no Live Paint face at that point".into())),
(None, None) => make_live(d, sel, &roots)?.0,
}
}
};
// The faces the click or drag paints in Live Paint group `gid`: the visible face at the point,
// and every visible face the drag crosses; → (the face at the point, the faces).
let targets_in = |d: &Document, gid: NodeId| -> Result<(NodeId, std::collections::BTreeSet<NodeId>)> {
let fid = d
.node(gid)
.and_then(|n| b::visible_face_at(n, pt))
@@ -355,11 +397,58 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
targets.extend(map.hits_along(&chunk, None).regions.iter().filter_map(|i| face_ids.get(*i).copied()));
}
}
for target in targets {
d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance.set_fill(paint.clone());
Ok((fid, targets))
};
// The Live Paint group the fill paints; `None` when the objects are made into one first.
let live = {
let d = &s.doc()?.doc;
match group {
Some(g) => {
if !d.node(g).is_some_and(is_live_paint) {
return Err(bad(C, format!("{g} is not a Live Paint group")));
}
Some(g)
}
None => {
let live_at = |face: fn(&Node, Point) -> Option<&Arc<Node>>| {
roots.iter().copied().find(|r| d.node(*r).is_some_and(|n| is_live_paint(n) && face(n, pt).is_some()))
};
match (live_at(b::visible_face_at), live_at(face_at)) {
(Some(g), _) => Some(g),
// At a point on a hidden face of a Live Paint group among the objects, the command returns an error
// and does not merge the objects.
(None, Some(_)) => return Err(EngineError::Other("no Live Paint face at that point".into())),
(None, None) => None,
}
}
}
Ok((gid, fid))
})?;
};
let (g, face) = match live {
Some(gid) => {
let (fid, targets) = targets_in(&s.doc()?.doc, gid)?;
// Faces that already have the paint stay as they are: when every face has it, nothing
// changes and no undo step is recorded.
let d = &s.doc()?.doc;
let unpainted: Vec<NodeId> = targets.into_iter().filter(|t| d.node(*t).is_none_or(|f| f.appearance.fill_paint() != paint)).collect();
if unpainted.is_empty() {
return Ok(json!({ "group": gid.0, "face": fid.0 }));
}
s.edit("Live Paint Bucket", |d, _| {
for target in unpainted {
d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance.set_fill(paint.clone());
}
Ok((gid, fid))
})?
}
None => s.edit("Live Paint Bucket", |d, sel| {
let gid = make_live(d, sel, &roots)?.0;
let (fid, targets) = targets_in(d, gid)?;
for target in targets {
d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance.set_fill(paint.clone());
}
Ok((gid, fid))
})?,
};
s.remember_paint(&paint);
Ok(json!({ "group": g.0, "face": face.0 }))
}
@@ -375,9 +464,22 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, "width out of range"));
}
let tol = number_or(p, "tolerance", 4.0, C)?.clamp(0.0, 1000.0);
let edge = s.edit("Live Paint Bucket", |d, _| {
let (eid, unchanged) = {
let d = &s.doc()?.doc;
let n = d.node(g).filter(|n| is_live_paint(n)).ok_or_else(|| bad(C, format!("{g} is not a Live Paint group")))?;
let eid = b::visible_edge_near(n, pt, tol).map(|e| e.id).ok_or_else(|| EngineError::Other("no Live Paint edge near that point".into()))?;
let e = b::visible_edge_near(n, pt, tol).ok_or_else(|| EngineError::Other("no Live Paint edge near that point".into()))?;
// An edge that already has the paint and the width (or has no stroke and gets none) stays as
// it is, and no undo step is recorded.
let unchanged = match e.appearance.stroke() {
Some(st) => st.paint == paint && st.width == width,
None => paint.is_none(),
};
(e.id, unchanged)
};
if unchanged {
return Ok(json!({ "group": g.0, "edge": eid.0 }));
}
let edge = s.edit("Live Paint Bucket", |d, _| {
let e = d.node_mut(eid).ok_or(EngineError::NoNode(eid))?;
e.appearance.set_stroke(paint.clone());
if let Some(st) = e.appearance.stroke_mut() {
@@ -127,6 +127,17 @@ fn node_refs(n: &Node, f: Visit) {
if let Some(cm) = Document::color_mask_of(m) {
f(Ref::Name(Res::Image, &cm.key));
}
// A graph keeps paints and style names for its series and labels, which a redraw gives them.
if let Some(g) = m.extras().graph.as_deref() {
vectorcraft_doc::swatches::graph_paints(m).for_each(|p| paint_refs(p, f));
let l = &g.label_styles;
for s in [&l.values, &l.categories, &l.legend].into_iter().flatten().filter_map(|st| st.style_name.as_ref()) {
f(Ref::Name(Res::CharStyle, s));
}
for s in [&l.values_para, &l.categories_para, &l.legend_para].into_iter().flatten().filter_map(|pa| pa.style_name.as_ref()) {
f(Ref::Name(Res::ParaStyle, s));
}
}
match &m.kind {
NodeKind::Text(t) => {
for r in &t.runs {
@@ -671,6 +682,27 @@ impl Relink {
self.name(Res::Image, &mut cm.key);
self.name(Res::Image, &mut cm.from);
}
if let Some(g) = n.extras_if_any().and_then(|e| e.graph.as_deref_mut()) {
for s in &mut g.series_paints {
s.fill.iter_mut().chain(s.stroke.iter_mut()).for_each(|p| self.paint(p));
}
let l = &mut g.label_styles;
for st in [&mut l.values, &mut l.categories, &mut l.legend].into_iter().flatten() {
self.paint(&mut st.fill);
self.paint(&mut st.stroke);
if let Some(s) = &mut st.style_name {
self.name(Res::CharStyle, s);
}
}
for pa in [&mut l.values_para, &mut l.categories_para, &mut l.legend_para].into_iter().flatten() {
if let Some(s) = &mut pa.style_name {
self.name(Res::ParaStyle, s);
}
}
for r in [&mut l.values_rows, &mut l.categories_rows, &mut l.legend_rows].into_iter().flatten() {
r.paint.fill.iter_mut().chain(r.paint.stroke.iter_mut()).for_each(|p| self.paint(p));
}
}
match &mut n.kind {
NodeKind::Text(t) => {
for r in &mut t.runs {
+48 -30
View File
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Invert Colors",
["Edit", "Edit Colors"],
None,
"{fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?} replace each colour by its RGB inverse (keeps the colour model) in fills, strokes, text, gradient meshes (with fills), colorized image fills (their pixels stay unchanged), other embedded images (a recoloured copy) and pattern tiles (a new pattern swatch; the original stays), as one undo step. On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke (docs/mcp.md) → {changed, notChanged: {locked, hidden} (when the selection is everything select.all takes: the locked and hidden objects it left out whose colors would have changed; an object both hidden and locked counts as hidden), warning?: set when notChanged counts any object}",
"{fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?} replace each colour by its RGB inverse (keeps the colour model) in fills, strokes, text, gradient meshes (with fills), colorized image fills (their pixels stay unchanged), other embedded images (a recoloured copy) and pattern tiles (a new pattern swatch; the original stays), as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke (docs/mcp.md) → {changed, notChanged: {locked, hidden} (when the selection is everything select.all takes: the locked and hidden objects it left out whose colors would have changed; an object both hidden and locked counts as hidden), warning?: set when notChanged counts any object}",
has_selection,
|s, p| recolor(s, p, "edit.colors.invert", "Invert Colors", &invert)
),
@@ -104,7 +104,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Blend Front to Back",
["Edit", "Edit Colors"],
None,
"{} ≥3 filled objects (solid fills or gradient meshes, which keep their shading): intermediate fills graded between the frontmost and backmost fill. On a path directly in a graph series, the graph also stores the new fill, as for the other Blend commands (docs/mcp.md) → {changed}",
"{} ≥3 filled objects (solid fills or gradient meshes, which keep their shading): intermediate fills graded between the frontmost and backmost fill. On a path directly in a graph series, the graph also stores the new fill, as for the other Blend commands (docs/mcp.md); no undo step when no fill changes → {changed}",
has_selection,
|s, _| blend(s, BlendOrder::Stack)
),
@@ -113,7 +113,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Blend Horizontally",
["Edit", "Edit Colors"],
None,
"{} ≥3 filled objects or meshes: fills graded between the leftmost and rightmost → {changed}",
"{} ≥3 filled objects or meshes: fills graded between the leftmost and rightmost; no undo step when no fill changes → {changed}",
has_selection,
|s, _| blend(s, BlendOrder::Horizontal)
),
@@ -122,7 +122,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Blend Vertically",
["Edit", "Edit Colors"],
None,
"{} ≥3 filled objects or meshes: fills graded between the topmost and bottommost → {changed}",
"{} ≥3 filled objects or meshes: fills graded between the topmost and bottommost; no undo step when no fill changes → {changed}",
has_selection,
|s, _| blend(s, BlendOrder::Vertical)
),
@@ -457,8 +457,8 @@ pub(crate) fn recolor_links(s: &mut Session, p: &Value, cmd: &str, label: &str,
run_pass(s, p, cmd, label, Recolor::with_links(Scope::of(p, cmd)?, f, links))
}
/// Run `pass` on the `ids` param's objects (default: the selection) as one undo step named `label`;
/// errors name the command `cmd`. The reply's `notChanged` counts the locked and hidden objects the
/// Run `pass` on the `ids` param's objects (default: the selection) as one undo step named `label`,
/// or none when the pass changes nothing; errors name the command `cmd`. The reply's `notChanged` counts the locked and hidden objects the
/// selection left out ([`left_out`]) that the pass would have changed.
fn run_pass(s: &mut Session, p: &Value, cmd: &str, label: &str, pass: Recolor) -> Result<Value> {
let (ids, left) = match ids_param(p, "ids", cmd)? {
@@ -471,20 +471,47 @@ fn run_pass(s: &mut Session, p: &Value, cmd: &str, label: &str, pass: Recolor) -
}
};
let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok();
let (n, not_changed) = s.edit(label, |d, _| {
let (n, not_changed) = edit_if_changed(s, label, |_, d| {
let not_changed = NotChanged::of(pass.again().would_change(d, &left).into_iter().map(|(_, hidden)| hidden));
let n = keeping_series_paint(d, &ids, |d| {
let n = pass.run(d, &ids);
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(cmd, e))?;
Ok(n)
})?;
Ok((n, not_changed))
Ok(((n, not_changed), n > 0))
})?;
let mut out = json!({ "changed": n });
not_changed.report(&mut out);
Ok(out)
}
/// [`Session::edit`] for an Edit Colors pass, which may change nothing: `f` runs on a copy of the
/// document (it gets the document as it is too) and returns its result with whether it changed the
/// copy. Only a changed copy becomes the document, as one undo step named `label`; otherwise the
/// undo and redo steps and the saved state stay as they were.
pub(crate) fn edit_if_changed<T>(s: &mut Session, label: &str, f: impl FnOnce(&Document, &mut Document) -> Result<(T, bool)>) -> Result<T> {
if s.script_running() {
return Err(EngineError::Busy);
}
// A typing session ends here as `s.edit` would end it, before the copy is taken, so that the
// copy holds what was typed.
if !s.previewing && super::typing_in_progress(s) {
super::settle_interaction(s)?;
}
let before = s.doc()?.doc.clone();
let mut doc = (*before).clone();
let (v, changed) = f(&before, &mut doc)?;
// The document is shared with `before` no longer, so `s.edit` does not copy it again.
drop(before);
if changed {
s.edit(label, |d, _| {
*d = doc;
Ok(())
})?;
}
Ok(v)
}
/// Run `recolor` on `d` (it returns how many objects it changed) over `roots`, then store on their graphs what it changed
/// on the graph series marks among `roots` and inside them, so the marks keep their new paint when the graph is drawn
/// again.
@@ -597,11 +624,6 @@ fn pass_targets(s: &Session, p: &Value, cmd: &str) -> Result<Targets> {
fn to_indexed(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "edit.colors.toIndexed";
let indexing = Indexing::of(s, p)?;
// A typing session ends here as `s.edit` would end it, before the copy is taken, so that the
// copy holds what was typed.
if !s.previewing && super::typing_in_progress(s) {
super::settle_interaction(s)?;
}
let remake = |b: &ImageBlob| indexing.convert(b);
let images = Scope { fill: false, stroke: false, images: true, patterns: false };
let pass = Recolor { remake: Some(&remake), ..Recolor::new(images, &same) };
@@ -609,22 +631,18 @@ fn to_indexed(s: &mut Session, p: &Value) -> Result<Value> {
// indexed PNG yet; it is not converted to find out. The empty PNG only gives it a new key.
let would = |b: &ImageBlob| (!b.indexed_png() && b.pixel_size().is_some()).then(|| ImageBlob::png(vec![]));
let (ids, left) = pass_targets(s, p, C)?;
let st = s.doc()?;
let colorized_ok = super::paint::check_colorized(&st.doc).is_ok();
let not_changed = NotChanged::of(
Recolor { remake: Some(&would), ..Recolor::new(images, &same) }.would_change(&st.doc, &left).into_iter().map(|(_, hidden)| hidden),
);
let mut doc = (*st.doc).clone();
let n = pass.run(&mut doc, &ids);
if let Some((w, h)) = indexing.too_large.get() {
return Err(bad(C, format!("an image of {w} × {h} pixels is too large to convert (at most {} pixels)", Indexing::MAX_PIXELS)));
}
if n > 0 {
s.edit("Convert to Indexed Color", |d, _| {
*d = doc;
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))
})?;
}
let (n, not_changed) = edit_if_changed(s, "Convert to Indexed Color", |now, doc| {
let colorized_ok = super::paint::check_colorized(now).is_ok();
let not_changed = NotChanged::of(
Recolor { remake: Some(&would), ..Recolor::new(images, &same) }.would_change(now, &left).into_iter().map(|(_, hidden)| hidden),
);
let n = pass.run(doc, &ids);
if let Some((w, h)) = indexing.too_large.get() {
return Err(bad(C, format!("an image of {w} × {h} pixels is too large to convert (at most {} pixels)", Indexing::MAX_PIXELS)));
}
super::paint::check_colorized_kept(colorized_ok, doc).map_err(|e| bad(C, e))?;
Ok(((n, not_changed), n > 0))
})?;
let mut out = json!({ "changed": n });
not_changed.report(&mut out);
Ok(out)
@@ -923,7 +941,7 @@ fn blend(s: &mut Session, order: BlendOrder) -> Result<Value> {
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(label, e))?;
Ok(changed)
};
let changed = s.edit(label, |d, _| keeping_series_paint(d, &ids, run))?;
let changed = edit_if_changed(s, label, |_, d| keeping_series_paint(d, &ids, run).map(|n| (n, n > 0)))?;
Ok(json!({ "changed": changed }))
}
@@ -536,6 +536,80 @@ fn a_document_replaced_in_the_back_is_measured_when_the_front_one_closes() {
assert_eq!(actual.cached_bounds, Some(expected));
}
/// The type of document `index` with id `id`, wherever its tab is.
fn text_in(s: &Session, index: usize, id: u64) -> vectorcraft_doc::TextObject {
match &s.documents()[index].doc.node(NodeId(id)).unwrap().kind {
NodeKind::Text(t) => (**t).clone(),
_ => panic!("not text"),
}
}
/// A document replaced while in the back has its type measured in its own composite fonts at once,
/// while the front document stays in front with its own definition registered; coming to the front
/// does not measure that type again.
#[test]
fn a_document_replaced_in_the_back_is_measured_before_it_comes_to_the_front() {
let (bytes, id, width) = full_roman_file("CF Pane");
let mut s = session();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Pane")]})).unwrap();
assert!(s.replace_document(0, vectorcraft_format::load(&bytes).unwrap()));
assert_eq!(s.active_index(), Some(1));
let front = vectorcraft_text::FontDb::global().composite_font("CF Pane").unwrap();
assert_eq!(front.parts.get(vectorcraft_doc::CharClass::Roman).size, 50.0);
let measured = text_in(&s, 0, id);
assert!((measured.cached_bounds.unwrap().width() - width).abs() < 1e-6);
let node = s.documents()[0].doc.node(NodeId(id)).unwrap().geometric_bounds().unwrap();
assert!((node.width() - width).abs() < 1e-6);
let doc = std::sync::Arc::as_ptr(&s.documents()[0].doc);
assert!(s.set_active(0));
assert!(std::ptr::eq(doc, std::sync::Arc::as_ptr(&s.documents()[0].doc)));
assert_eq!(text(&s, id).cached_bounds, measured.cached_bounds);
}
/// Type a document replaced in the back sets in a composite font that only the front document
/// defines is measured in that font while the front one is registered, and again, as missing, when
/// the replaced document comes to the front.
#[test]
fn a_document_replaced_in_the_back_measures_a_font_it_lacks_again_in_front() {
let mut s = session();
let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab12", "size": 20, "font": "CF Lacked"})).unwrap()["id"].as_u64().unwrap();
let bytes = vectorcraft_format::save_file(&s.doc().unwrap().doc);
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Lacked")]})).unwrap();
assert!(s.replace_document(0, vectorcraft_format::load(&bytes).unwrap()));
let back = text_in(&s, 0, id);
let expected = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &back).bounds;
assert_eq!(back.cached_bounds, Some(expected));
assert!(s.set_active(0));
assert!(vectorcraft_text::FontDb::global().composite_font("CF Lacked").is_none());
let actual = text(&s, id);
let expected = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &actual).bounds;
assert_eq!(actual.cached_bounds, Some(expected));
}
/// Text holding an inline graphic whose symbol's art is type in a composite font, in a document
/// replaced in the back, is measured with the graphic at the size the document's own definition
/// gives it before it comes to the front.
#[test]
fn a_document_replaced_in_the_back_measures_inline_graphics_in_its_own_definition() {
let mut s = session();
let mut full = font("CF Back Inline");
full["parts"]["roman"]["size"] = json!(100);
s.execute("type.compositeFonts.set", &json!({"fonts": [full]})).unwrap();
let art =
s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab12", "size": 20, "font": "CF Back Inline"})).unwrap()["id"].as_u64().unwrap();
s.execute("symbol.new", &json!({"name": "CF Back Inline Mark", "ids": [art]})).unwrap();
let id = s.execute("text.create", &json!({"x": 10, "y": 150, "text": "x", "size": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("text.insertInline", &json!({"id": id, "at": 0, "symbol": "CF Back Inline Mark"})).unwrap();
let width = text(&s, id).cached_bounds.unwrap().width();
let bytes = vectorcraft_format::save_file(&s.doc().unwrap().doc);
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Back Inline")]})).unwrap();
assert!(s.replace_document(0, vectorcraft_format::load(&bytes).unwrap()));
assert!((text_in(&s, 0, id).cached_bounds.unwrap().width() - width).abs() < 1e-6);
}
/// A failed batch takes back the composite fonts it set, in the font database too.
#[test]
fn a_failed_batch_takes_back_its_composite_fonts() {
+232 -52
View File
@@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Document Info",
["Window", "Document Info"],
None,
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else Linear gradient, Radial gradient or Freeform gradient; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone. brushNames, brushes, spotObjects, patternObjects and gradientObjects leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0 (with selectionOnly too), their characters' paints and colorized images included; objects still counts them as paths, groups and the other kinds",
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freeform, when it is named by its kind, else null; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone. brushNames, brushes, spotObjects, patternObjects and gradientObjects leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0 (with selectionOnly too), their characters' paints and colorized images included; objects still counts them as paths, groups and the other kinds",
has_doc,
info
),
@@ -85,17 +85,65 @@ pub struct Section {
/// What a font's `fsType` lets a copy of it do, read as exports read it ([`Embedding`]): the
/// most permissive usage bit wins, and bitmap-only fonts may not be embedded.
pub fn embedding_label(fs_type: u16) -> &'static str {
if Embedding::from_fs_type(fs_type) == Embedding::Forbidden {
"embedding not allowed"
} else if fs_type & 0x0008 != 0 {
"embedding for editing"
} else if fs_type & 0x0004 != 0 {
"embedding for preview and print"
} else {
"embedding allowed"
match embedding_id(fs_type) {
"forbidden" => "embedding not allowed",
"editing" => "embedding for editing",
"previewPrint" => "embedding for preview and print",
_ => "embedding allowed",
}
}
/// [`embedding_label`] as the `embedding` value of a `fontDetails` entry: `forbidden`, `editing`,
/// `previewPrint` or `allowed`.
pub fn embedding_id(fs_type: u16) -> &'static str {
if Embedding::from_fs_type(fs_type) == Embedding::Forbidden {
"forbidden"
} else if fs_type & 0x0008 != 0 {
"editing"
} else if fs_type & 0x0004 != 0 {
"previewPrint"
} else {
"allowed"
}
}
/// A font as Font Details lists it: its `fontDetails` entry and its row. The row gives the file
/// the font is drawn from (`built in` for a face with no file) and whether its license lets it be
/// embedded; for a style the family lacks, the face shown in its place; for a font that is not
/// installed, the face shown instead, or `missing`. The entry holds the same facts as values
/// (`match`: `exact`, `style`, `missingWithFallback` or `missing`), so the panel can show them in
/// the interface language.
fn font_detail(used: &super::fonts::UsedFont) -> (Value, (String, String)) {
let db = vectorcraft_text::FontDb::global();
let (family, style, version) = used;
let label = super::fonts::font_label(used);
// Found by any of its names (in the version the type names); a style the family lacks shows in
// another.
let resolved = db.resolve(family, style).map(|(f, m)| (db.face_version(family, style, version.as_deref()).unwrap_or(f), m));
let (entry, detail) = match resolved {
Some((f, m)) if m != vectorcraft_text::FontMatch::Missing => {
let file = f.path().and_then(|p| p.file_name()).map(|n| n.to_string_lossy().into_owned());
let found = format!("{}; {}", file.as_deref().unwrap_or("built in"), embedding_label(f.fs_type()));
let substituted = m == vectorcraft_text::FontMatch::Style;
let entry = json!({
"font": label,
"match": if substituted { "style" } else { "exact" },
"family": f.family,
"style": f.style,
"file": file,
"embedding": embedding_id(f.fs_type()),
});
(entry, if substituted { format!("substituted: shown in {} {} ({found})", f.family, f.style) } else { found })
}
Some((f, _)) => (
json!({ "font": label, "match": "missingWithFallback", "family": f.family, "style": f.style, "file": null, "embedding": null }),
format!("missing: shown in {} {}", f.family, f.style),
),
None => (json!({ "font": label, "match": "missing", "family": null, "style": null, "file": null, "embedding": null }), "missing".into()),
};
(entry, (label, detail))
}
/// An image object as Document Info lists it: (name, width, height, linked file).
type ImageRow = (String, u32, u32, Option<String>);
@@ -131,14 +179,15 @@ fn repeat_entry(d: &Document, n: &Node, spec: &RepeatSpec) -> (Value, (String, S
}
/// The Document Info categories of `d` (only `category` when given) from `info` (what
/// `document.info` reports), its fonts, its image objects, the rows of the brushes its art uses, the
/// rows of its Repeat objects and the rows of its objects filled or stroked with a spot color, with a
/// pattern and with a gradient.
/// `document.info` reports), its fonts and their Font Details rows, its image objects, the rows of
/// the brushes its art uses, the rows of its Repeat objects and the rows of its objects filled or
/// stroked with a spot color, with a pattern and with a gradient.
#[allow(clippy::too_many_arguments)]
fn sections(
d: &Document,
info: &Value,
fonts: &BTreeSet<super::fonts::UsedFont>,
font_details: &[(String, String)],
images: &[ImageRow],
brushes: &[(String, String)],
repeats: &[(String, String)],
@@ -192,34 +241,7 @@ fn sections(
"gradients" => gradient_objects.to_vec(),
"symbols" => names("symbols"),
"fonts" => fonts.iter().map(|f| (super::fonts::font_label(f), String::new())).collect(),
"fontDetails" => {
let db = vectorcraft_text::FontDb::global();
fonts
.iter()
.map(|used| {
let (family, style, version) = used;
// Found by any of its names (in the version the type names); a style the
// family lacks shows in another.
let resolved =
db.resolve(family, style).map(|(f, m)| (db.face_version(family, style, version.as_deref()).unwrap_or(f), m));
let detail = match resolved {
Some((f, m)) if m != vectorcraft_text::FontMatch::Missing => {
let file =
f.path().and_then(|p| p.file_name()).map_or_else(|| "built in".into(), |n| n.to_string_lossy().into_owned());
let found = format!("{file}; {}", embedding_label(f.fs_type()));
if m == vectorcraft_text::FontMatch::Style {
format!("substituted: shown in {} {} ({found})", f.family, f.style)
} else {
found
}
}
Some((f, _)) => format!("missing: shown in {} {}", f.family, f.style),
None => "missing".into(),
};
(super::fonts::font_label(used), detail)
})
.collect()
}
"fontDetails" => font_details.to_vec(),
"linkedImages" => {
images.iter().filter_map(|(name, w, h, link)| Some((name.clone(), format!("{w} × {h} px — {}", link.as_ref()?)))).collect()
}
@@ -277,6 +299,39 @@ fn gradient_label(p: &Paint) -> Option<String> {
}
}
/// Where [`gradient_label`]'s name for gradient paint `p` comes from: `swatch:<name>` for a
/// gradient linked to a swatch, else `kind:<kind>` (`linear`, `radial`, `conic`, `diamond` or
/// `freeform`). The two prefixes keep a swatch's name apart from a kind's name it reads like.
fn gradient_source(p: &Paint) -> Option<String> {
match p {
Paint::Gradient(g) => Some(match g.swatch.as_deref().filter(|s| !s.is_empty()) {
Some(swatch) => format!("swatch:{swatch}"),
None => format!("kind:{}", g.gradient.kind.label().to_ascii_lowercase()),
}),
_ => None,
}
}
/// For each of `names` (an object's [`gradient_label`]s), the kind it names when only a kind
/// gives that name: a name one of `sources` (the object's [`gradient_source`]s) gives as a kind's
/// and none gives as a swatch's, else null. A swatch named like a kind keeps its name even where
/// a gradient of that kind is listed under the same name.
fn gradient_kinds(names: &[String], sources: &[String]) -> Vec<Value> {
names
.iter()
.map(|name| {
if sources.iter().any(|s| s.strip_prefix("swatch:") == Some(name.as_str())) {
return Value::Null;
}
sources
.iter()
.filter_map(|s| s.strip_prefix("kind:"))
.find(|k| vectorcraft_color::GradientKind::parse(k).is_some_and(|kind| *name == format!("{} gradient", kind.label())))
.map_or(Value::Null, |k| json!(k))
})
.collect()
}
/// The names of `d`'s spot color swatches: the swatches whose prints go to a plate of their own
/// ([`vectorcraft_doc::inks::inks`]). A name held by several swatches is the first one's, as
/// [`Document::swatch`] finds it, and the Registration swatch prints on every plate, so it is not
@@ -486,9 +541,11 @@ fn node_and_drawn<'a>(d: &'a Document, path: &[usize]) -> Option<(&'a Node, bool
/// The spot colors, the patterns and the gradients (`spots`: [`spot_swatches`]) that object `n`
/// paints, each once: those of its own fills and strokes ([`own_paints`], `members` included), of
/// its drawn characters and, for a grayscale or 1-bit image, of the color it is colorized with.
fn object_paints(d: &Document, spots: &HashSet<&str>, members: &HashSet<*const Node>, n: &Node) -> [Vec<String>; 3] {
/// The fourth list gives where each gradient comes from: a swatch or a kind ([`gradient_source`]).
fn object_paints(d: &Document, spots: &HashSet<&str>, members: &HashSet<*const Node>, n: &Node) -> [Vec<String>; 4] {
let (spot, pattern, gradient) = (|p: &Paint| spot_labels(spots, p), one_label(pattern_label), one_label(gradient_label));
let labels: [&PaintNames<'_>; 3] = [&spot, &pattern, &gradient];
let gradient_from = one_label(gradient_source);
let labels: [&PaintNames<'_>; 4] = [&spot, &pattern, &gradient, &gradient_from];
let painted_runs = painted_runs(d, spots, n);
let mut used = labels.map(|label| own_paints(d, n, members, painted_runs.as_ref(), label));
// The characters' own paints: an inline graphic draws no outline and does not take its run's
@@ -654,8 +711,10 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(k) = k {
*counts.entry(k).or_default() += 1;
}
// The spot colors, the patterns and the gradients this object paints, each once; none when it does not draw.
let [used_spots, used_patterns, used_gradients] = if drawn { object_paints(d, &spot_swatches, &members, n) } else { Default::default() };
// The spot colors, the patterns and the gradients this object paints, each once, and where each gradient comes from;
// none when it does not draw.
let [used_spots, used_patterns, used_gradients, used_sources] =
if drawn { object_paints(d, &spot_swatches, &members, n) } else { Default::default() };
// Objects counts the objects that Spot Color Objects, Pattern Objects and Gradient Objects list.
if !used_spots.is_empty() {
let name = n.display_name();
@@ -675,7 +734,8 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
let name = n.display_name();
gradients.extend(used_gradients.iter().cloned());
gradient_rows.push((name.clone(), used_gradients.join(", ")));
gradient_objects.push(json!({ "id": n.id.0, "name": name, "gradients": used_gradients }));
let kinds = gradient_kinds(&used_gradients, &used_sources);
gradient_objects.push(json!({ "id": n.id.0, "name": name, "gradients": used_gradients, "kinds": kinds }));
*counts.entry("gradients").or_default() += 1;
}
if n.extras().mask.is_some() {
@@ -710,10 +770,21 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
fonts.extend(super::fonts::art_texts_of(d).into_iter().flat_map(|(_, t, _)| t.runs.iter().map(|r| super::fonts::font_of(&r.style))));
}
let font_names: Vec<String> = fonts.iter().map(super::fonts::font_label).collect();
let (font_entries, font_rows): (Vec<Value>, Vec<(String, String)>) = fonts.iter().map(font_detail).unzip();
// The image objects in walk order, as Linked Images and Embedded Images list them: `file` is a
// linked image's row value (its path, or its file name alone when the request may not read it),
// and null for an embedded one.
let image_objects: Vec<Value> = image_rows
.iter()
.map(|(name, w, h, file)| json!({ "name": name, "width": w, "height": h, "linked": file.is_some(), "file": file }))
.collect();
// Each brush the art uses with its type, found by name in the Brushes panel as the renderer finds it (the first of two
// brushes with one name); a brush the panel does not hold draws as a plain stroke and has no type. A row names the type
// as the New Brush dialog does (`Art Brush`), and the panel translates these values when it shows them.
let kinds: HashMap<&str, &vectorcraft_brush::BrushKind> = library.iter().map(|b| (b.name.as_str(), &b.kind)).collect();
let mut kinds: HashMap<&str, &vectorcraft_brush::BrushKind> = HashMap::new();
for b in &library {
kinds.entry(b.name.as_str()).or_insert(&b.kind);
}
let brush_entries: Vec<Value> =
brushes.iter().map(|name| json!({ "name": name, "type": kinds.get(name.as_str()).map(|k| k.type_id()) })).collect();
let brush_rows: Vec<(String, String)> = brushes
@@ -727,7 +798,9 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
"objects": counts,
"pathLength": path_length,
"fonts": font_names,
"fontDetails": font_entries,
"images": images,
"imageObjects": image_objects,
"symbols": symbols,
"spotColors": spot,
"spotColorNames": spot,
@@ -749,7 +822,7 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
});
// The document's name: its file's, else its title.
out["document"]["name"] = json!(st.title());
let sections = sections(d, &out, &fonts, &image_rows, &brush_rows, &repeat_rows, &spot_rows, &pattern_rows, &gradient_rows, category);
let sections = sections(d, &out, &fonts, &font_rows, &image_rows, &brush_rows, &repeat_rows, &spot_rows, &pattern_rows, &gradient_rows, category);
if text {
return Ok(json!({ "text": report_text(&st.title(), selection_only, &sections) }));
}
@@ -763,6 +836,7 @@ fn document_summary(d: &Document) -> Value {
"title": d.title,
"colorMode": match d.color_mode { ColorMode::Rgb => "RGB", ColorMode::Cmyk => "CMYK" },
"units": d.units.label(),
"unitId": d.units.key(),
"artboards": d.artboards.iter().map(|a| json!({ "name": a.name, "width": a.rect.width() / u, "height": a.rect.height() / u })).collect::<Vec<_>>(),
"rasterEffectsPpi": d.raster_effects_ppi,
})
@@ -1289,11 +1363,11 @@ mod tests {
assert_eq!(
i["gradientObjects"],
json!([
{"id": a, "name": "Both", "gradients": ["Ramp", "Linear gradient"]},
{"id": b, "name": "<Rectangle>", "gradients": ["Radial gradient"]},
{"id": f, "name": "<Rectangle>", "gradients": ["Freeform gradient"]},
{"id": t, "name": "Type", "gradients": ["Ramp"]},
{"id": bar, "name": "Bar", "gradients": ["Ramp"]},
{"id": a, "name": "Both", "gradients": ["Ramp", "Linear gradient"], "kinds": [null, "linear"]},
{"id": b, "name": "<Rectangle>", "gradients": ["Radial gradient"], "kinds": ["radial"]},
{"id": f, "name": "<Rectangle>", "gradients": ["Freeform gradient"], "kinds": ["freeform"]},
{"id": t, "name": "Type", "gradients": ["Ramp"], "kinds": [null]},
{"id": bar, "name": "Bar", "gradients": ["Ramp"], "kinds": [null]},
])
);
assert_eq!(i["gradientNames"], json!(["Freeform gradient", "Linear gradient", "Radial gradient", "Ramp"]));
@@ -1800,6 +1874,112 @@ mod tests {
assert_eq!(embedding_label(0x0003), "embedding not allowed");
assert_eq!(embedding_label(0x0006), "embedding for preview and print");
assert_eq!(embedding_label(0x000c), "embedding for editing");
// `fontDetails` names each permission by id.
assert_eq!(
[0, 0x0002, 0x0104, 0x0008, 0x0200, 0x000c].map(embedding_id),
["allowed", "forbidden", "previewPrint", "editing", "forbidden", "editing"]
);
}
/// `fontDetails` gives each Font Details row's facts as values, in the rows' order: how the
/// font was found, the face shown, its file (null for a built-in face) and its embedding
/// permission. The rows and the report stay in English.
#[test]
fn info_exposes_structured_font_details_without_changing_english_rows() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Hi"})).unwrap();
s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Heavy", "font": "Source Sans 3", "style": "Black Wide"})).unwrap();
s.execute("text.create", &json!({"x": 10, "y": 80, "text": "Gone", "font": "Qx Absent Family"})).unwrap();
let i = s.execute("document.info", &json!({"category": "fontDetails"})).unwrap();
let (entries, rows) = (i["fontDetails"].as_array().unwrap(), i["sections"][0]["rows"].as_array().unwrap());
assert_eq!(entries.iter().map(|e| e["font"].clone()).collect::<Vec<_>>(), rows.iter().map(|r| r[0].clone()).collect::<Vec<_>>());
let at = |prefix: &str| entries.iter().position(|e| e["font"].as_str().unwrap().starts_with(prefix)).unwrap();
let regular = at("Source Sans 3 Regular");
assert_eq!(
entries[regular],
json!({"font": "Source Sans 3 Regular", "match": "exact", "family": "Source Sans 3", "style": "Regular", "file": null, "embedding": "allowed"})
);
assert_eq!(rows[regular][1], "built in; embedding allowed");
let (wide, e) = (at("Source Sans 3 Black Wide"), &entries[at("Source Sans 3 Black Wide")]);
assert_eq!((e["match"].as_str(), e["family"].as_str()), (Some("style"), Some("Source Sans 3")), "{e}");
let file = e["file"].as_str().unwrap_or("built in");
let fs_type = [("allowed", 0), ("forbidden", 0x0002), ("previewPrint", 0x0004), ("editing", 0x0008)]
.into_iter()
.find_map(|(id, bits)| (e["embedding"] == id).then_some(bits))
.unwrap();
let found = format!("{file}; {}", embedding_label(fs_type));
assert_eq!(rows[wide][1], format!("substituted: shown in Source Sans 3 {} ({found})", e["style"].as_str().unwrap()));
let (gone, e) = (at("Qx Absent Family"), &entries[at("Qx Absent Family")]);
assert!(e["file"].is_null() && e["embedding"].is_null(), "{e}");
match e["match"].as_str() {
Some("missingWithFallback") => {
assert_eq!(rows[gone][1], format!("missing: shown in {} {}", e["family"].as_str().unwrap(), e["style"].as_str().unwrap()))
}
Some("missing") => assert_eq!((rows[gone][1].as_str(), e["family"].is_null()), (Some("missing"), true)),
m => panic!("{m:?}"),
}
let text = s.execute("document.info", &json!({"category": "fontDetails", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string();
assert!(text.contains("Source Sans 3 Regular: built in; embedding allowed\n"), "{text}");
}
/// `document.unitId` names the document's units as Preferences › Units does, beside the English
/// `units`, and `imageObjects` lists the image objects in the order Embedded Images and Linked
/// Images list them, with the file a linked one shows (null for an embedded one).
#[test]
fn info_exposes_ordered_images_and_unit_id() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
s.edit("Units", |d, _| {
d.units = vectorcraft_doc::Unit::Millimeters;
Ok(())
})
.unwrap();
for x in [0.0, 50.0] {
let r = s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 20, "height": 10})).unwrap()["id"].clone();
s.execute("select.set", &json!({"ids": [r]})).unwrap();
s.execute("object.rasterize", &json!({"ppi": 72})).unwrap();
}
let i = s.execute("document.info", &json!({})).unwrap();
assert_eq!((i["document"]["units"].as_str(), i["document"]["unitId"].as_str()), (Some("Millimeters"), Some("millimeters")));
let section = |id: &str| i["sections"].as_array().unwrap().iter().find(|s| s["id"] == id).unwrap()["rows"].as_array().unwrap().clone();
assert!(section("document").iter().any(|r| *r == json!(["Units", "Millimeters"])));
let embedded = section("embeddedImages");
let objects = i["imageObjects"].as_array().unwrap();
assert_eq!(objects.len(), 2, "{objects:?}");
for (o, r) in objects.iter().zip(&embedded) {
assert_eq!((o["linked"].clone(), o["file"].clone(), o["name"].clone()), (json!(false), Value::Null, r[0].clone()), "{o}");
assert_eq!(r[1], format!("{} × {} px", o["width"], o["height"]));
}
assert!(section("linkedImages").is_empty());
}
/// A `gradientObjects` entry's `kinds` gives the kind of each gradient listed by its kind
/// rather than by a swatch, and null for a swatch's name, even one that reads like a kind and
/// one an object's gradient of that kind shares; a type object's characters count as its own.
#[test]
fn gradient_kinds_tell_kinds_from_swatch_names() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
let ramp = |kind: &str| json!({"kind": kind, "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]});
s.execute("swatch.new", &json!({"name": "Radial gradient", "gradient": ramp("linear")})).unwrap();
let r = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
s.execute("paint.setFill", &json!({"ids": [r], "swatch": "Radial gradient"})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [r], "gradient": ramp("conic")})).unwrap();
let t = s.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi"})).unwrap()["id"].clone();
s.execute("paint.setFill", &json!({"ids": [t], "gradient": ramp("diamond")})).unwrap();
// The swatch's name and a radial gradient's kind name are listed once, as the name.
let both = s.execute("shape.rectangle", &json!({"x": 20, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
s.execute("paint.setFill", &json!({"ids": [both], "swatch": "Radial gradient"})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [both], "gradient": ramp("radial")})).unwrap();
let i = s.execute("document.info", &json!({})).unwrap();
let entry = |id: &Value| i["gradientObjects"].as_array().unwrap().iter().find(|e| e["id"] == *id).unwrap().clone();
assert_eq!(
(entry(&r)["gradients"].clone(), entry(&r)["kinds"].clone()),
(json!(["Radial gradient", "Conic gradient"]), json!([null, "conic"]))
);
assert_eq!((entry(&t)["gradients"].clone(), entry(&t)["kinds"].clone()), (json!(["Diamond gradient"]), json!(["diamond"])));
assert_eq!((entry(&both)["gradients"].clone(), entry(&both)["kinds"].clone()), (json!(["Radial gradient"]), json!([null])));
}
#[test]
+2 -2
View File
@@ -231,9 +231,9 @@ pub(super) fn within_input_bound(q: Point) -> bool {
q.x.is_finite() && q.y.is_finite() && q.x.abs() < MAX_INPUT && q.y.abs() < MAX_INPUT
}
/// The whole number of 0 or more that `key` holds, read with [`index`].
/// The whole number of 0 or more that `key` holds, read with [`u64_req`](crate::cmd::u64_req) and [`index`].
pub(super) fn usize_req(p: &Value, key: &str, cmd: &str) -> Result<usize> {
p.get(key).and_then(Value::as_u64).map(index).ok_or_else(|| bad(cmd, format!("missing integer `{key}`")))
crate::cmd::u64_req(p, key, cmd).map(index)
}
/// The whole number of 0 or more that `key` holds, or `None` when `key` is absent or null. Any other
+17 -4
View File
@@ -11,7 +11,9 @@ use super::{
// ---------- Pencil / Paintbrush ----------
/// Fit a freehand polyline: drop jitter, build a spline through the samples (sharp turns stay
/// corners) and simplify it to `tol`.
/// corners) and simplify it to `tol`. A closed stroke is fitted as the open one is and closed by a
/// straight segment from its end back to its start: fitting round the gap would curve that segment
/// on from both ends, past them and back.
fn fit_freehand(pts: &[Point], tol: f64, closed: bool) -> SubPath {
let min = (tol * 0.3).max(vectorcraft_tools::draw2::MIN_FIT_TOLERANCE * 0.3);
let (Some(&p0), Some(&pn)) = (pts.first(), pts.last()) else { return SubPath::new(vec![], closed) };
@@ -41,15 +43,26 @@ fn fit_freehand(pts: &[Point], tol: f64, closed: bool) -> SubPath {
(kept[i], corner)
})
.collect();
let sp = vectorcraft_tools::draw2::catmull_rom(&marked, closed);
let sp = vectorcraft_tools::draw2::catmull_rom(&marked, false);
if sp.anchors.len() < 3 {
return sp;
// Two anchors closed would run back over the line itself.
return SubPath::new(sp.anchors, closed && n > 2);
}
let fitted = po::simplify_with(
&PathData::single(sp.clone()),
&SimplifyOptions { tolerance: tol, corner_angle_deg: 60.0, straight_lines: false, ..Default::default() },
);
fitted.subpaths.into_iter().next().filter(|s| s.anchors.len() >= 2).unwrap_or(sp)
let mut anchors = fitted.subpaths.into_iter().next().filter(|s| s.anchors.len() >= 2).unwrap_or(sp).anchors;
if closed {
// No handle on either side of the closing segment.
if let Some(l) = anchors.last_mut() {
l.h_out = l.p;
}
if let Some(f) = anchors.first_mut() {
f.h_in = f.p;
}
}
SubPath::new(anchors, closed)
}
/// The path of a freehand stroke: fitted at `tol` ([`fit_freehand`]), or with no `tol` the points
+26 -11
View File
@@ -15,15 +15,27 @@ const SMOOTH_SPREAD: f64 = 1.0 / 3.0;
/// The options the Smooth tool refits with: the path smoothed along its length by a Gaussian of
/// spread `sigma` (none at 0), then refitted within `tol` of that and within twice the distance the
/// smoothing moved it, keeping a corner only where the path turns back on itself.
fn refit_options(tol: f64, sigma: f64) -> SimplifyOptions {
SimplifyOptions { tolerance: tol, corner_angle_deg: 179.0, straight_lines: false, smooth: sigma, smooth_moved_only: true }
/// smoothing moved it, keeping a corner only where the path turns back on itself. `free` says whether
/// the start and the end of the stretch refitted are ends of an open path, whose direction then
/// follows the smoothed path within the reach rather than the first or last segment.
fn refit_options(tol: f64, sigma: f64, free: [bool; 2]) -> SimplifyOptions {
SimplifyOptions {
tolerance: tol,
corner_angle_deg: 179.0,
straight_lines: false,
smooth: sigma,
smooth_moved_only: true,
free_start: free[0],
free_end: free[1],
}
}
/// Smooth and refit the anchors of an open run `a[lo..=hi]` keeping its end points and outer handles.
fn refit_run(anchors: &[Anchor], tol: f64, sigma: f64) -> Vec<Anchor> {
/// `free` says whether its first and last anchors are ends of an open path: the curve leaving or
/// arriving at such an end can turn.
fn refit_run(anchors: &[Anchor], tol: f64, sigma: f64, free: [bool; 2]) -> Vec<Anchor> {
let piece = PathData::single(SubPath::new(anchors.to_vec(), false));
let fitted = po::simplify_with(&piece, &refit_options(tol, sigma));
let fitted = po::simplify_with(&piece, &refit_options(tol, sigma, free));
let Some(mut out) = fitted.subpaths.into_iter().next().map(|s| s.anchors).filter(|a| a.len() >= 2) else { return anchors.to_vec() };
let (f, l) = (anchors[0], anchors[anchors.len() - 1]);
let last = out.len() - 1;
@@ -228,7 +240,7 @@ fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f
if sp.closed {
let Some(k) = marked.iter().position(|m| !m) else {
// Everything is in range: smooth the whole closed path, across its start too.
let f = po::simplify_with(&PathData::single(sp.clone()), &refit_options(tol, sigma));
let f = po::simplify_with(&PathData::single(sp.clone()), &refit_options(tol, sigma, [false; 2]));
return f.subpaths.into_iter().next();
};
// Rotate so an untouched anchor comes first, duplicate it at the end and treat as open.
@@ -239,14 +251,14 @@ fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f
open.anchors.push(open.anchors[0]);
m.push(false);
open.closed = false;
let mut res = smooth_open(&open.anchors, &m, near, tol, sigma);
let mut res = smooth_open(&open.anchors, &m, near, tol, sigma, false);
let l = res.pop()?;
if let Some(r0) = res.first_mut() {
r0.h_in = l.h_in;
}
return Some(SubPath::new(res, true));
}
Some(SubPath::new(smooth_open(&sp.anchors, &marked, near, tol, sigma), false))
Some(SubPath::new(smooth_open(&sp.anchors, &marked, near, tol, sigma, true), false))
}
/// The segment `c`, which ends in the drag's reach (`near`) and starts outside it, split where it
@@ -278,8 +290,10 @@ fn split_at_reach(c: CubicBez, near: &dyn Fn(Point) -> bool) -> Option<(CubicBez
/// `anchors` with each run of `marked` ones smoothed by a Gaussian of spread `sigma` and refitted
/// within `tol`, together with the stretch of the segments leading into the run that is in the
/// drag's reach (`near`): a short drag smooths what is under it, and the rest of a long segment next
/// to it stays as it was (#1512).
fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool, tol: f64, sigma: f64) -> Vec<Anchor> {
/// to it stays as it was (#1512). With `open`, `anchors` are an open path, and the curve at its first
/// or last anchor turns with the smoothing when a run's refit reaches that anchor; a run's other ends,
/// and those of the open run a closed path is cut into, keep their direction.
fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool, tol: f64, sigma: f64, open: bool) -> Vec<Anchor> {
let n = anchors.len();
let mut runs = vec![];
let mut i = 0;
@@ -319,7 +333,8 @@ fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool
head = Some(Anchor { h_out: far.p1, ..*outer });
*outer = Anchor::with_handles(far.p3, far.p2, reach.p1);
}
let new = refit_run(&piece, tol, sigma);
let free = [open && lo == 0 && head.is_none(), open && hi == n - 1 && tail.is_none()];
let new = refit_run(&piece, tol, sigma, free);
out.splice(lo..=hi, head.into_iter().chain(new).chain(tail));
}
out
+17 -12
View File
@@ -11,7 +11,7 @@ use super::clipboard::SwatchChoices;
use super::{
CommandSpec, Result, Session, always, bad, can_clear_history, can_redo, can_undo, check_numbers, checked_ids_param, clock_date, cmd, date_param,
f64_req, finite_numbers, has_clipboard, has_doc, has_selection, has_selection_guides_or_artboard_tool, has_selection_or_guides, index, number_or,
object_param, ok, point_param, str_param, switch_or,
object_param, ok, point_param, str_param, switch_or, u64_req,
};
use crate::{Clipboard, EngineError, SourceLayer, inspect};
@@ -249,7 +249,10 @@ fn file_close(s: &mut Session, p: &Value) -> Result<Value> {
}
fn doc_activate(s: &mut Session, p: &Value) -> Result<Value> {
let i = p.get("index").and_then(Value::as_u64).map(index).ok_or_else(|| bad("document.activate", "missing index"))?;
let i = match p.get("index") {
None | Some(Value::Null) => return Err(bad("document.activate", "missing index")),
Some(v) => v.as_u64().map(index).ok_or_else(|| bad("document.activate", "`index` must be a whole number"))?,
};
if s.set_active(i) { ok() } else { Err(bad("document.activate", "no such document")) }
}
@@ -262,7 +265,10 @@ fn doc_move(s: &mut Session, p: &Value) -> Result<Value> {
if from >= n {
return Err(bad("document.move", "no such document"));
}
let to = p.get("to").and_then(Value::as_u64).map(index).ok_or_else(|| bad("document.move", "missing `to`: a non-negative integer"))?;
let to = match p.get("to") {
None | Some(Value::Null) => return Err(bad("document.move", "missing `to`: a non-negative integer")),
Some(v) => v.as_u64().map(index).ok_or_else(|| bad("document.move", "`to` must be a whole number"))?,
};
let to = to.min(n.saturating_sub(1));
if !s.move_document(from, to) {
return Err(bad("document.move", "no such document"));
@@ -562,12 +568,11 @@ fn switch_units(s: &mut Session, _: &Value) -> Result<Value> {
Ok(json!({ "units": next.label() }))
}
/// The `artboard` param of the ruler origin commands: an artboard index, 0 when not given.
/// The `artboard` param of the ruler origin commands: an artboard index, 0 when left out or null. A
/// value that is not a whole number is "`artboard` must be a whole number"; one past the artboards
/// is "index out of range".
fn artboard_param(s: &Session, p: &Value, c: &str) -> Result<usize> {
let index = match p.get("artboard") {
None => 0,
Some(v) => v.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or_else(|| bad(c, "index out of range"))?,
};
let index = super::index_opt(p, "artboard", c)?.unwrap_or(0);
if index >= s.doc()?.doc.artboards.len() {
return Err(bad(c, "index out of range"));
}
@@ -577,14 +582,15 @@ fn artboard_param(s: &Session, p: &Value, c: &str) -> Result<usize> {
fn ruler_origin(s: &mut Session, p: &Value) -> Result<Value> {
let d = &s.doc()?.doc;
// A document without artboards measures from its global zero point.
let index = if d.artboards.is_empty() && p.get("artboard").is_none() { 0 } else { artboard_param(s, p, "document.rulerOrigin")? };
let index =
if d.artboards.is_empty() && p.get("artboard").is_none_or(Value::is_null) { 0 } else { artboard_param(s, p, "document.rulerOrigin")? };
Ok(json!(s.doc()?.doc.ruler_origin_for(index)))
}
fn set_ruler_origin(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "document.setRulerOrigin";
let origin = Point::new(f64_req(p, "x", C)?, f64_req(p, "y", C)?);
let index = if s.doc()?.doc.rulers == RulerMode::Global && p.get("artboard").is_none() { 0 } else { artboard_param(s, p, C)? };
let index = if s.doc()?.doc.rulers == RulerMode::Global && p.get("artboard").is_none_or(Value::is_null) { 0 } else { artboard_param(s, p, C)? };
change_ruler_origin(s, index, Some(origin), "Ruler Origin")
}
@@ -1190,8 +1196,7 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
/// Document ids scope node ids: two tabs may contain objects with the same node id.
fn drop_selection(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "edit.dropSelection";
let key = "sourceDocument";
let uid = p[key].as_u64().ok_or_else(|| bad(CMD, format!("missing integer `{key}`")))?;
let uid = u64_req(p, "sourceDocument", CMD)?;
let point = |key: &str| finite_numbers::<2>(&p[key]).ok_or_else(|| bad(CMD, format!("{key} must be [x, y] with finite coordinates")));
let grab = point("grab")?;
let at = point("at")?;
+12 -9
View File
@@ -13,7 +13,7 @@ use vectorcraft_doc::{Document, Effect, Node, NodeKind, StrokeLayer};
use vectorcraft_geom::{FillRule, PathData};
use vectorcraft_render::effects;
use super::appearance::{ItemTarget, aligned, appearance_targets, index_param, item_indices, item_target, item_target_at};
use super::appearance::{ItemTarget, aligned, appearance_targets, edit_targets, index_param, item_indices, item_target, item_target_at};
use super::expand::has_seeded;
use super::rasterfx;
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, check_switches, cmd, fileio, has_doc, str_param, switch_or};
@@ -49,7 +49,7 @@ fn effect_specs() -> Vec<CommandSpec> {
"Apply Effect",
[],
None,
"{effect: id (see effect.list, e.g. \"stylize.dropShadow\", \"distort.roughen\", \"warp.arc\", or \"plugin.<id>\" for an installed effect plug-in), params?: {…} (missing keys take the dialog defaults), item?: appearance item index|null (apply to that fill/stroke only; omitted: the Appearance panel's active item, else the whole object), ids?|id?: [..] (layers too), target?: \"object\"|\"contents\" (contents: the objects inside groups and layers)} append a live effect to each selected object's appearance (a group's or layer's apply to its members as one piece: one combined shadow; a Pathfinder effect, which combines a group's contents, groups several loose selected objects first, in the same undo step) → {ids, index, item, grouped?}",
"{effect: id (see effect.list, e.g. \"stylize.dropShadow\", \"distort.roughen\", \"warp.arc\", or \"plugin.<id>\" for an installed effect plug-in), params?: {…} (missing keys take the dialog defaults), item?: appearance item index|null (apply to that fill/stroke only; omitted: the Appearance panel's active item, else the whole object), ids?|id?: [..] (layers too), target?: \"object\"|\"contents\" (contents: the objects inside groups and layers)} append a live effect to each selected object's appearance (a group's or layer's apply to its members as one piece: one combined shadow; a Pathfinder effect, which combines a group's contents, groups several loose selected objects first, in the same undo step); the art of a graph design in a graph series is left out, and objects that are all such art are an error (docs/mcp.md) → {ids, index, item, grouped?}",
has_doc,
apply
),
@@ -298,7 +298,7 @@ fn ids_json(ids: &[NodeId]) -> Value {
/// edits its equal item, or its equal object-level effect, each target matched on its own whatever
/// the other targets have; in a target without them, `item` and `index` stand for themselves.
pub(crate) fn effect_targets(s: &Session, p: &Value, item: ItemTarget, index: usize, cmd: &str) -> Result<Vec<(NodeId, Option<usize>, usize)>> {
let roots = appearance_targets(s, p)?;
let roots = edit_targets(s, p)?;
let d = &s.doc()?.doc;
let per = item.per_target(s, &roots);
let first = roots.first().and_then(|f| d.node(*f));
@@ -453,7 +453,7 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
}
let item = item_target(s, p, C)?;
if effects::is_three_d(id) {
let targets = appearance_targets(s, p)?;
let targets = edit_targets(s, p)?;
for (target, at) in targets.iter().copied().zip(item.per_target(s, &targets)) {
let d = &s.doc()?.doc;
let n = d.node(target).ok_or(EngineError::NoNode(target))?;
@@ -492,8 +492,9 @@ fn loose_for_pathfinder(s: &Session, p: &Value, id: &str) -> Result<Option<Vec<N
if !effects::is_pathfinder(id) || ["ids", "id", "item", "target"].iter().any(|k| p.get(k).is_some()) {
return Ok(None);
}
let roots = super::appearance::subject_roots(s)?;
let d = &s.doc()?.doc;
// The art of a graph design in a series stays where the graph draws it.
let roots = super::appearance::without_design_art(d, super::appearance::subject_roots(s)?, "appearance")?;
let grouped = roots.iter().any(|r| d.node(*r).is_some_and(|n| matches!(n.kind, NodeKind::Group { clip: false, .. } | NodeKind::Layer { .. })));
Ok((roots.len() >= 2 && !grouped).then_some(roots))
}
@@ -606,7 +607,7 @@ fn move_effect(s: &mut Session, p: &Value) -> Result<Value> {
let src = item_target_at(s, p, "fromItem", C)?;
let dst = if p.get("toItem").is_some() { item_target_at(s, p, "toItem", C)? } else { src };
let copy = switch_or(p, "copy", false, C)?;
let roots = appearance_targets(s, p)?;
let roots = edit_targets(s, p)?;
// Where an aligned effect would go in each of several different stacks isn't one place.
if aligned(p, C)? && super::appearance::appearances_differ(&s.doc()?.doc, &roots) {
return Err(bad(C, "effects of objects whose appearances differ can't be moved together"));
@@ -864,8 +865,8 @@ fn load_texture(params: &mut Value, cmd: &str) -> Result<()> {
/// Has `n` an appearance Expand Appearance turns into objects: a path that isn't basic (several
/// fills or strokes, effects, transparency of a fill or stroke, a brush), a group or layer with
/// fills, strokes or effects of its own or such members, other objects with effects, type with
/// fills or strokes of its own, or a symbol instance whose active fill or stroke has a geometry
/// effect ([`effects::has_item_geometry`])?
/// fills or strokes of its own, or a symbol instance whose active fill or stroke has a geometry or
/// raster effect ([`effects::has_item_geometry`], [`effects::has_instance_row_raster`])?
pub(crate) fn expandable(n: &Node) -> bool {
expandable_except(n, &[])
}
@@ -882,7 +883,9 @@ pub(crate) fn expandable_except(n: &Node, skip: &[NodeId]) -> bool {
!n.appearance.items.is_empty() || !n.appearance.effects.is_empty() || children.iter().any(|c| expandable_except(c, skip))
}
NodeKind::Text(_) => !n.appearance.items.is_empty() || !n.appearance.effects.is_empty(),
NodeKind::Image(_) | NodeKind::SymbolInstance { .. } => effects::has_item_geometry(n) || !n.appearance.effects.is_empty(),
NodeKind::Image(_) | NodeKind::SymbolInstance { .. } => {
effects::has_item_geometry(n) || effects::has_instance_row_raster(n) || !n.appearance.effects.is_empty()
}
_ => !n.appearance.effects.is_empty(),
}
}
+2 -2
View File
@@ -7,7 +7,7 @@ use serde_json::{Map, Value, json};
use vectorcraft_doc::{Effect, Node};
use vectorcraft_render::effects;
use super::super::appearance::{appearance_targets, index_param, item_target};
use super::super::appearance::{edit_targets, index_param, item_target};
use super::super::brushsym::{normalize, selection_art, store_symbol};
use super::super::{CommandSpec, EngineError, NodeId, Result, Session, bad, cmd, has_doc, has_selection, str_param};
use super::{effect_targets, ids_json};
@@ -95,7 +95,7 @@ fn map_graphic(s: &mut Session, p: &Value) -> Result<Value> {
effect_targets(s, p, item, index, C)?
} else {
let mut out = vec![];
for id in appearance_targets(s, p)? {
for id in edit_targets(s, p)? {
let (item, index) = d.node(id).and_then(first_three_d).ok_or_else(|| bad(C, format!("object {} needs a 3D effect", id.0)))?;
out.push((id, item, index));
}
+52 -9
View File
@@ -25,7 +25,7 @@ use super::dimension::EndedLink;
use super::edit::selected_roots;
use super::menucmds::{run_raw, squash};
use super::object::as_clipping_path;
use super::pathops::{assemble, node_path, outline_strokes, replace_leaves, styled_copy, with_transparency};
use super::pathops::{assemble, node_path, outlinable, outline_strokes, replace_leaves, styled_copy, with_transparency};
use super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_selection, number_or, switch_or, text_param};
const C: &str = "object.expand";
@@ -47,7 +47,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Expand…",
["Object"],
None,
"{object?: true (symbol instances without effects (their fills' and strokes' included) and not in perspective → their art, as Break Link to Symbol places it (the instances that art holds stay instances), type → outlines, live shapes → paths, effects baked, blends → groups of their steps, repeats → groups of their instances, Intertwine groups → groups of their objects and of the parts drawn over the others (clip groups), envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art, pattern fills → their tiles in a clip group shaped like the object), stroke?: true (strokes → filled outlines, the stroked paths that baking effects leaves included), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients, wedges around the center for conic ones, nested squares for diamond ones) | \"mesh\" (a gradient mesh); both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255; a gradient that repeats or reflects gets the same whole number of them in each run, at least one, so a run starts on an object's edge; one that needs more than 256 runs across the box stays a gradient)} one undo step; a dimension whose art an option changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked → {ids}",
"{object?: true (symbol instances without effects (their fills' and strokes' included) and not in perspective → their art, as Break Link to Symbol places it (the instances that art holds stay instances), type → outlines (its own fills and strokes on paths of its whole outline, which Fill and Stroke expand), live shapes → paths, effects baked, blends → groups of their steps, repeats → groups of their instances, Intertwine groups → groups of their objects and of the parts drawn over the others (clip groups), envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art, pattern fills → their tiles in a clip group shaped like the object), stroke?: true (strokes → filled outlines, the stroked paths that baking effects leaves included), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients, wedges around the center for conic ones, nested squares for diamond ones) | \"mesh\" (a gradient mesh); both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255; a gradient that repeats or reflects gets the same whole number of them in each run, at least one, so a run starts on an object's edge; one that needs more than 256 runs across the box stays a gradient)} one undo step; a dimension whose art an option changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked → {ids}",
has_selection,
expand
),
@@ -56,7 +56,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Expand Options",
[],
None,
"{} what each Expand option would change in the selection → {object, fill, stroke, gradient, appearance, symbolArt?: {fill, stroke, gradient}} (true: something to expand; gradient: a gradient fill that Fill expands (in type, on the outline Object makes of a character), which Expand Gradient To applies to; appearance: appearance attributes Expand Appearance expands first, for which Object › Expand… is dimmed in the menus; symbolArt, when the selection holds symbol instances that Object expands: true when only their art holds it, which Fill and Stroke reach only with Object on)",
"{} what each Expand option would change in the selection → {object, fill, stroke, gradient, appearance, symbolArt?: {fill, stroke, gradient}} (true: something to expand; gradient: a gradient fill that Fill expands (in type, on the outline Object makes of a character, or of the whole type for the type object's own fills), which Expand Gradient To applies to; appearance: appearance attributes Expand Appearance expands first, for which Object › Expand… is dimmed in the menus; symbolArt, when the selection holds symbol instances that Object expands: true when only their art holds it, which Fill and Stroke reach only with Object on)",
has_selection,
|s, _| {
let roots = selected_roots(s)?;
@@ -189,21 +189,37 @@ impl Expandable {
e.placed |= matches!(c.kind, NodeKind::PlacedDocument(_));
e.repeats |= matches!(c.kind, NodeKind::Repeat(_));
e.intertwines |= matches!(c.kind, NodeKind::Intertwine { .. });
// Type's outlines take its characters' stroke and fill, and a path of its whole outline
// takes the type object's own fills and strokes (see `type.createOutlines`).
// Any stroke Outline Stroke outlines, not only the topmost one.
let own_stroke = c.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(st) if outlinable(st)));
let own_pattern = c.appearance.items.iter().any(|i| pattern_fill(d, i).is_some());
let own_gradient = c.appearance.items.iter().any(|i| gradient_fill(i).is_some());
// Type without an outline (empty, or only spaces) gets no path for its own fills and strokes.
let whole = match &c.kind {
NodeKind::Text(t) if own_stroke || own_pattern || own_gradient => text_whole_outline(t),
_ => None,
};
e.stroke |= match &c.kind {
// Type's outlines take its characters' stroke (see `type.createOutlines`).
NodeKind::Text(t) => t.runs.iter().any(|r| r.style.has_stroke()),
_ => shape && !c.appearance.stroke_paint().is_none(),
NodeKind::Text(t) => (own_stroke && whole.is_some()) || t.runs.iter().any(|r| r.style.has_stroke()),
_ => shape && own_stroke,
};
// Once one is found, the next path is not measured.
e.gradient = e.gradient
|| match &c.kind {
NodeKind::Text(t) => text_gradient_expands(d, t),
NodeKind::Text(t) => {
text_gradient_expands(d, t)
|| (own_gradient && whole.as_ref().is_some_and(|(path, tb)| text_object_gradient_expands(d, c, path, *tb)))
}
_ => shape && gradient_expands(d, c),
};
e.fill |= e.gradient;
e.fill |= match &c.kind {
NodeKind::Text(t) => t.runs.iter().any(|r| matches!(&r.style.fill, Paint::Pattern { pattern, .. } if d.pattern(pattern).is_some())),
_ => shape && c.appearance.items.iter().any(|i| pattern_fill(d, i).is_some()),
NodeKind::Text(t) => {
(own_pattern && whole.is_some())
|| t.runs.iter().any(|r| matches!(&r.style.fill, Paint::Pattern { pattern, .. } if d.pattern(pattern).is_some()))
}
_ => shape && own_pattern,
};
});
}
@@ -275,6 +291,33 @@ fn text_gradient_expands(d: &Document, t: &TextObject) -> bool {
|| vectorcraft_text::decorations(&lay, vectorcraft_text::FontDb::global(), t).iter().any(|(run, bar)| expands(*run, bar))
}
/// The path of type `t`'s whole outline in the document (glyphs, ruby glyphs and underline and
/// strikethrough bars), which `type.createOutlines` paints with the type object's own fills and
/// strokes, and the layout's bounds there; `None` when the type has no outline.
fn text_whole_outline(t: &TextObject) -> Option<(PathData, Rect)> {
let db = vectorcraft_text::FontDb::global();
let lay = vectorcraft_text::layout(db, t);
let mut all = BezPath::new();
for g in lay.glyphs.iter().chain(&lay.ruby) {
all.extend(g.outline.iter());
}
for (_, bar) in vectorcraft_text::decorations(&lay, db, t) {
all.extend(bar.iter());
}
let path = PathData::from_bezpath(&all).transformed(t.xf);
(!path.is_empty()).then(|| (path, t.xf.transform_rect_bbox(lay.bounds)))
}
/// Whether type node `n` has a gradient fill of its own (not its characters') that Fill expands
/// once Object has outlined it: [`gradient_expands`] on `path`, the type's whole outline
/// ([`text_whole_outline`]), with its unplaced gradients fixed to `tb`, the layout's bounds in the
/// document. Leaves the document as it is.
fn text_object_gradient_expands(d: &Document, n: &Node, path: &PathData, tb: Rect) -> bool {
let mut appearance = Appearance { items: n.appearance.items.clone(), ..Default::default() };
appearance.pin_gradients(tb);
gradient_expands(d, &Node::path(NodeId(u64::MAX), path.clone(), appearance))
}
/// [`gradient_expands`] for a path that no live-effect plug-in paints ([`expand_piece_fills`]).
fn piece_gradient_expands(d: &Document, l: &Node) -> bool {
if !l.appearance.items.iter().filter_map(gradient_fill).any(|(_, g)| g.gradient.is_spread()) {
+2 -2
View File
@@ -92,7 +92,7 @@ pub use pdfimport::{LoadOptions, page_document};
pub(crate) use save::job_for;
pub(crate) use save::save as save_document;
pub use save::{
SAVE_FORMATS, SaveJob, SaveMode, SavePlan, StreamWrite, TEMPLATE_FORMATS, dialog_folder, documents_dialog_folder, export_folder,
SAVE_FORMATS, SaveJob, SaveMode, SavePlan, StreamWrite, TEMPLATE_FORMATS, dialog_folder, documents_dialog_folder, export_folder, file_reads,
leave_out_unreadable_save_paths, reads_option as save_reads_option, remembered_save_options, save_filters, save_format, save_job, save_plan,
save_with, stamp_save_dates, template_filters, templates_dialog_folder, templates_folder,
};
@@ -123,7 +123,7 @@ mod formats;
#[cfg(not(target_arch = "wasm32"))]
pub(crate) use access::list_dir;
pub use access::{write_file_with, write_save_file, write_save_file_with};
pub use access::{check_linked_scripts, write_file_with, write_save_file, write_save_file_with};
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests_readonly;
+18
View File
@@ -121,6 +121,24 @@ pub(crate) fn naming_in_message(msg: &str, path: &str, name: &str) -> String {
out
}
/// The error for an SVG of a document that links a JavaScript file outside the read roots.
pub(crate) const SCRIPT_OUTSIDE: &str = "a linked JavaScript file is outside the read roots";
/// `cmd` may write `st`'s document in format `format` (a format id): any format but SVG and SVGZ,
/// and those too unless read roots are in force and the document links a JavaScript file outside
/// them (`svg_scripts`, a relative path taken from the document's folder; a URL is not checked),
/// which the file's `<script>` element would name. The error names no file or folder.
pub fn check_linked_scripts(cmd: &str, format: &str, st: &crate::DocState) -> Result<()> {
if !matches!(format, "svg" | "svgz") || crate::file_access::current().is_none() {
return Ok(());
}
let doc_path = st.path.as_deref();
if st.doc.svg_scripts.iter().any(|f| crate::cmd::links::script_hidden(f, doc_path)) {
return Err(bad(cmd, SCRIPT_OUTSIDE));
}
Ok(())
}
/// `path` checked for writing against the automation roots in force.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn may_write(path: &str) -> Result<()> {
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -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 binary DXF or a DWG answers an error saying to save it as ASCII DXF",
"{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",
always,
dxf_info
)]
+18 -15
View File
@@ -12,7 +12,8 @@ use crate::DocState;
use super::super::{Result, Session, bad, check_switches, edit, number_or, switch_or, text_param};
use super::encode::single_artboard;
use super::{
ARTBOARD_PARAMS, Format, default_name, encode_all, encode_with_warnings, merge, with_black_output, writable, write_encoded, write_or_return,
ARTBOARD_PARAMS, Format, check_linked_scripts, default_name, encode_all, encode_with_warnings, merge, with_black_output, writable, write_encoded,
write_or_return,
};
/// The keys the export commands take for every format, beside the path, the format and the
@@ -31,28 +32,28 @@ pub fn unused_option_notes(cmd: &str, f: &Format, p: &Value) -> Vec<String> {
}
let listed = |k: &str| super::FORMATS.iter().filter(|f| f.write).flat_map(|f| f.options).any(|o| o.name == k);
let written = super::save::written_as(cmd, f, p);
let legacy = f.id == "ai" && super::legacy_ai::wanted(cmd, f, p).unwrap_or(false);
let reads = |k: &str| match (f.id, k) {
// A legacy `.ai` file is not a PDF: it reads its own options only.
("ai", _) if legacy => super::legacy_ai::reads(k),
// The other `.ai` files don't read the legacy file's options, and `preserveEditing` is
// on for them whatever is given.
("ai", "preserveEditing") => false,
("ai", _) if super::legacy_ai::LEGACY_ONLY.contains(&k) => false,
// An export writes one file: only a save writes each artboard to a file of its own, and
// a native file's `range` names those files.
("vectorcraft" | "template" | "ai", "separateArtboards") | ("vectorcraft" | "template", "range") => false,
_ => super::save::reads_option(f, k),
};
let legacy = super::save::legacy_file(cmd, f, p);
given
.iter()
.filter(|(k, v)| !v.is_null() && !EXPORT_PARAMS.contains(&k.as_str()) && listed(k) && !reads(k))
.filter(|(k, v)| !v.is_null() && !EXPORT_PARAMS.contains(&k.as_str()) && listed(k) && !export_reads(f, legacy, k))
.map(|(k, _)| super::save::unused_option_note(k, &written))
.collect()
}
/// Does the file an export writes in `f` read option `key`, `legacy` when it is a legacy `.ai`
/// file? As a save's file does ([`super::save::file_reads`]), except that an export writes one
/// file: only a save writes each artboard to a file of its own, and a native file's `range` names
/// those files.
pub(super) fn export_reads(f: &Format, legacy: bool, key: &str) -> bool {
match (f.id, key) {
("vectorcraft" | "template" | "ai", "separateArtboards") | ("vectorcraft" | "template", "range") => false,
_ => super::save::file_reads(f, legacy, key),
}
}
pub(super) fn serialize(s: &mut Session, p: &Value) -> Result<Value> {
let f = writable("document.serialize", Some(text_param(p, "format", "document.serialize")?.unwrap_or("vectorcraft")), None)?;
check_linked_scripts("document.serialize", f.id, s.doc()?)?;
let unused = unused_option_notes("document.serialize", f, p);
let expanded = expand_presets(s, "document.serialize", p)?;
let p = with_black_output(s, &expanded);
@@ -96,6 +97,7 @@ pub(super) fn export(s: &mut Session, p: &Value) -> Result<Value> {
super::check_not_lossy_overwrite(s.doc()?, path, p, "document.export")?;
}
let f = writable("document.export", text_param(p, "format", "document.export")?, path)?;
check_linked_scripts("document.export", f.id, s.doc()?)?;
let unused = unused_option_notes("document.export", f, p);
let expanded = expand_presets(s, "document.export", p)?;
let p = with_black_output(s, &expanded);
@@ -355,6 +357,7 @@ pub(super) fn export_selection(s: &mut Session, p: &Value) -> Result<Value> {
super::check_not_lossy_overwrite(s.doc()?, path, p, C)?;
}
let f = writable(C, text_param(p, "format", C)?, path)?;
check_linked_scripts(C, f.id, s.doc()?)?;
let unused = unused_option_notes(C, f, p);
let expanded = expand_presets(s, C, p)?;
let p = with_black_output(s, &expanded);
+70 -10
View File
@@ -95,14 +95,18 @@ pub struct SavePlan {
/// The `modified` param (as `date_param` reads it): the File Info date a Save or Save As to a file
/// stamps; `None`: the time it is written.
pub modified: Option<Option<i64>>,
/// Warnings about the params themselves: each native option (`compress`, `version`,
/// `preview`, `precision`) given beside the path, and each key of `options`, that the format
/// doesn't read, naming the file the save writes.
/// Warnings about the params themselves: each option a save format takes given beside the
/// path, and each key of `options`, that the file the save writes doesn't read
/// ([`file_reads`]), naming that file.
pub notes: Vec<String>,
/// The file the document was read from and what reading it left out, when the save needs
/// `acknowledgeLoss` to write over it and was not given it: every file the save writes is
/// checked against it before the first is written.
pub lossy_source: Option<(String, Vec<String>)>,
/// The `.ai` options the file doesn't read, with the values the document remembers from its
/// last `.ai` save: not in `options`, they go back into the remembered options once the file
/// is the document's own.
pub kept: Map<String, Value>,
}
impl SavePlan {
@@ -279,7 +283,8 @@ pub fn save_plan(s: &Session, mode: SaveMode, p: &Value) -> Result<SavePlan> {
}
}
// None given: the ones the document was last saved with in this format.
let mut options = if given.is_empty() && format.id == st.format { remembered_save_options(st) } else { given };
let from_memory = given.is_empty() && format.id == st.format;
let mut options = if from_memory { remembered_save_options(st) } else { given };
// Remember the effective choice, including the encoder's default, so another document's
// later save cannot change what this one writes. Invalid non-null values still reach validation.
if matches!(format.id, "vectorcraft" | "template") {
@@ -311,21 +316,54 @@ pub fn save_plan(s: &Session, mode: SaveMode, p: &Value) -> Result<SavePlan> {
let given = str_param(p, "path").is_some_and(|g| !g.is_empty());
super::check_not_lossy_overwrite(st, path, p, cmd).map_err(|e| if given { e } else { super::access::naming_in_error(e, path) })?;
}
let written = written_as(cmd, format, &Value::Object(options.clone()));
let top = NATIVE_OPTIONS.iter().filter(|k| p.get(**k).is_some_and(|v| !v.is_null())).map(|k| k.to_string());
let chosen = Value::Object(options.clone());
let written = written_as(cmd, format, &chosen);
let legacy = legacy_file(cmd, format, &chosen);
// Beside the path, a key some save format takes; in `options`, any key.
let top = p.as_object().into_iter().flatten().filter(|(k, v)| !v.is_null() && save_listed(k)).map(|(k, _)| k.to_string());
let nested = p.get("options").and_then(Value::as_object).into_iter().flatten().filter(|(_, v)| !v.is_null()).map(|(k, _)| k);
let notes = top
.filter(|k| !reads_option(format, k))
.chain(nested.filter(|k| !reads_option(format, k)).map(|k| format!("options.{k}")))
.filter(|k| !file_reads(format, legacy, k))
.chain(nested.filter(|k| !file_reads(format, legacy, k)).map(|k| format!("options.{k}")))
.map(|k| unused_option_note(&k, &written))
.collect();
// When the document's own file is a `.ai`, the `.ai` options this file doesn't read and the
// request doesn't give keep their remembered values ([`SavePlan::kept`]), so that Save Options
// still shows them (it sends only the ones the file reads). They are neither written nor sent
// again.
let mut kept = Map::new();
if format.id == "ai" && format.id == st.format {
let last = remembered_save_options(st);
for o in format.options.iter().filter(|o| !file_reads(format, legacy, o.name)) {
let value = if from_memory {
options.remove(o.name)
} else if options.contains_key(o.name) {
None
} else {
last.get(o.name).cloned()
};
if let Some(v) = value {
kept.insert(o.name.to_string(), v);
}
}
}
let lossy_source = super::lossy_source(st, p);
Ok(SavePlan { mode, path, format, options, name, folder, modified, notes, lossy_source })
Ok(SavePlan { mode, path, format, options, name, folder, modified, notes, lossy_source, kept })
}
/// The native save options, which a save also takes beside the path.
const NATIVE_OPTIONS: [&str; 4] = ["compress", "version", "preview", "precision"];
/// Does some save format (or template format) take option `key`?
fn save_listed(key: &str) -> bool {
NATIVE_OPTIONS.contains(&key)
|| super::FORMATS
.iter()
.filter(|f| SAVE_FORMATS.contains(&f.id) || TEMPLATE_FORMATS.contains(&f.id))
.flat_map(|f| f.options)
.any(|o| o.name == key)
}
/// The first option `p` gives both beside the path and in `options` with different values, as
/// `(key, top-level value, options value)`. For an SVG save (`svg`), an SVG option's value on
/// either side is the one its `svg: {…}` object gives, else the flat one.
@@ -467,6 +505,26 @@ pub fn reads_option(f: &Format, key: &str) -> bool {
f.options.iter().any(|o| o.name == key) || (is_pdf(f) && (super::pdf::OPTIONS.iter().any(|o| o.name == key) || super::pdf::is_setting(key)))
}
/// Does the file a save or an export writes in `f` read option `key`, `legacy` when it is a legacy
/// `.ai` file ([`super::legacy_ai::wanted`])? As [`reads_option`], except for `.ai` and `.ait`
/// files: a legacy file reads its own options only ([`super::legacy_ai::reads`]), and the others
/// don't read the legacy file's options or `preserveEditing`, which is on for them whatever is
/// given.
pub fn file_reads(f: &Format, legacy: bool, key: &str) -> bool {
match (f.id, key) {
("ai", _) if legacy => super::legacy_ai::reads(key),
("ai" | "ait", "preserveEditing") => false,
("ai" | "ait", _) if super::legacy_ai::LEGACY_ONLY.contains(&key) => false,
_ => reads_option(f, key),
}
}
/// Is a save or an export of `cmd` in `f` with options `p` to write a legacy `.ai` file? An
/// unknown version is not one (the save or export refuses it).
pub(super) fn legacy_file(cmd: &str, f: &Format, p: &Value) -> bool {
f.id == "ai" && super::legacy_ai::wanted(cmd, f, p).unwrap_or(false)
}
/// The note a save or an export gives for option `key`, as the request names it, which the file it
/// writes (`written`, see [`written_as`]) doesn't read.
pub(super) fn unused_option_note(key: &str, written: &Format) -> String {
@@ -822,6 +880,7 @@ pub(crate) fn job_for(s: &Session, st: &DocState, plan: SavePlan) -> Result<Save
fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option<i64>) -> Result<SaveJob> {
let cmd = plan.mode.command();
super::check_linked_scripts(cmd, plan.format.id, st)?;
let mut own = doc_to_save(st, plan.format);
// The file the document is saved as (else its own) titles it if New's name is all it has.
let file = plan.path.as_deref().filter(|_| plan.retargets()).or(st.path.as_deref());
@@ -1036,6 +1095,7 @@ impl SaveJob {
st.path = Some(path);
st.format = self.plan.format.id;
st.save_options = self.plan.options;
st.save_options.extend(self.plan.kept);
// A later save rounds only when it gives `precision` too.
st.save_options.remove("precision");
st.save_artboards = self.snapshot.artboards.iter().map(|a| a.id).collect();
@@ -1238,7 +1298,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
"Save Document",
[],
None,
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings say when the format doesn't read compress, version, preview or precision given flat, or a key given in options), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel",
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel",
has_doc,
|s, p| save(s, SaveMode::Save, p)
),
+91 -7
View File
@@ -18,7 +18,7 @@ use vectorcraft_geom::Rect;
use super::super::{EngineError, NodeId, Result, Session, bad, bool_or, str_param};
use super::encode::{add_note, single_artboard};
use super::export::{export_crop, isolated, selected_artwork, without_artboards};
use super::export::{export_crop, export_reads, isolated, selected_artwork, without_artboards};
use super::naming::{self, NameParts};
use super::{
ARTBOARD_PARAMS, ArtboardPick, Format, Note, artboard_file_names_keeping_dots, create_dir, distinct_names_by, encode_with_notes, merge,
@@ -524,6 +524,77 @@ fn rows_of(s: &Session, p: &Value, preset: Option<&str>) -> Result<Vec<Row>> {
Ok(rows)
}
/// A note for each option of a format row (`formats`) or of a format's `settings` in the request
/// `asked` that some format takes but the file the row writes, or every row of that format writes,
/// doesn't read (`{format: png, quality: 80}`), in the wording of a save's note and named as the
/// request names it (`formats[0].quality`, `settings.png.quality`). The rows and settings the
/// export writes with are those of `p` (`asked` with a preset or the remembered settings laid
/// under it). A row's own keys (`scale`, `suffix`…), the keys the export reads for every format
/// (`includeArtboardFill`, `richBlack`, `params`) and an artboard choice (the export picks the
/// artboards) get none, and so does an exporter plug-in's format.
pub(crate) fn unused_option_notes(asked: &Value, p: &Value) -> Vec<String> {
let listed = |k: &str| super::FORMATS.iter().filter(|f| f.write).flat_map(|f| f.options).any(|o| o.name == k);
let own = |k: &str| {
ROW_KEYS.contains(&k) || ARTBOARD_PARAMS.contains(&k) || matches!(k, "useArtboards" | "includeArtboardFill" | "richBlack" | "params")
};
// The keys of `given` that `f`, writing with `options` (the format's settings and the row's
// own), doesn't read.
let unread = |f: &Format, given: &Map<String, Value>, options: &Value| -> Vec<String> {
if vectorcraft_plugins::export::by_format(f.id).is_some() {
return Vec::new();
}
let legacy = super::save::legacy_file(C, f, options);
given.iter().filter(|(k, v)| !v.is_null() && !own(k) && listed(k) && !export_reads(f, legacy, k)).map(|(k, _)| k.clone()).collect()
};
let note = |key: String, f: &Format, options: &Value| super::save::unused_option_note(&key, &super::save::written_as(C, f, options));
let settings = p.get("settings").and_then(Value::as_object);
let of_format = |id: &str| settings.and_then(|s| s.get(id)).and_then(Value::as_object).cloned().unwrap_or_default();
// A row's format and the options it writes with.
let row_of = |row: &Value| -> Option<(&'static Format, Value)> {
let (Some(row), Ok(f)) = (row.as_object(), writable(C, Some(str_param(row, "format").unwrap_or("png")), None)) else { return None };
let mut options = of_format(f.id);
options.extend(row.iter().map(|(k, v)| (k.clone(), v.clone())));
Some((f, Value::Object(options)))
};
let mut out: Vec<String> = Vec::new();
if let Some(Value::Array(rows)) = asked.get("formats") {
for (i, row) in rows.iter().enumerate() {
let (Some((f, options)), Some(given)) = (row_of(row), row.as_object()) else { continue };
out.extend(unread(f, given, &options).into_iter().map(|k| note(format!("formats[{i}].{k}"), f, &options)));
}
}
// The rows written, each with its own keys: a format's settings are read as each of its rows
// writes them (a row may name another `.ai` version), else as they are.
let written: Vec<(&Format, Value, Map<String, Value>)> = match p.get("formats") {
Some(Value::Array(rows)) => {
rows.iter().filter_map(|row| row_of(row).map(|(f, options)| (f, options, row.as_object().cloned().unwrap_or_default()))).collect()
}
_ => Vec::new(),
};
for (id, given) in asked.get("settings").and_then(Value::as_object).into_iter().flatten() {
let (Some(given), Ok(f)) = (given.as_object(), writable(C, Some(id), None)) else { continue };
let mut rows: Vec<(&Value, Option<&Map<String, Value>>)> =
written.iter().filter(|(g, ..)| g.id == f.id).map(|(_, o, row)| (o, Some(row))).collect();
let alone = Value::Object(of_format(f.id));
if rows.is_empty() {
rows.push((&alone, None));
}
let unread_by: Vec<Vec<String>> = rows.iter().map(|(o, _)| unread(f, given, o)).collect();
// A setting a row reads and doesn't give itself is used. One no row uses is noted when a
// row doesn't read it, naming the first such row's file.
for (k, v) in given {
// A row's own key, null too, replaces the setting.
let overridden = |row: Option<&Map<String, Value>>| row.is_some_and(|r| r.contains_key(k));
let used = rows.iter().zip(&unread_by).any(|((_, row), u)| !u.contains(k) && !overridden(*row));
let unread_row = rows.iter().zip(&unread_by).find(|(_, u)| u.contains(k));
if let (false, false, Some(((options, _), _))) = (v.is_null(), used, unread_row) {
out.push(note(format!("settings.{id}.{k}"), f, options));
}
}
}
out
}
/// Check the export settings in `p` (formats, preset, settings…) as an export would read them.
pub(crate) fn check_settings(s: &Session, p: &Value) -> Result<()> {
rows_of(s, p, ScreenParams::of(p)?.preset.as_deref()).map(|_| ())
@@ -646,9 +717,10 @@ impl Output {
pub(super) fn export_for_screens(s: &mut Session, p: &Value) -> Result<Value> {
// A folder the client gave, as against the one its `exportPreset` keeps.
let given = p.get("folder").is_some();
let asked = p;
let p = with_preset(s, p)?;
let hidden = if given { None } else { str_param(&p, "folder").filter(|f| !f.is_empty() && !super::access::shown(f)) };
let mut r = export(s, &p).map_err(|e| match hidden {
let mut r = export(s, &p, asked).map_err(|e| match hidden {
Some(folder) => super::access::naming_in_error(e, folder),
None => e,
})?;
@@ -1022,14 +1094,21 @@ pub(crate) fn with_export_preset(s: &Session, cmd: &str, settings: &mut Map<Stri
/// else the bounds of all art). Items that share a name get `-2`, `-3`… instead of overwriting, and
/// so do different files that would share a name, with or without the `name` pattern. The reply's
/// `warnings` lists every warning the encoders give for the files, each once, what the files lose
/// first ([`super::note_texts`]).
pub(crate) fn export(s: &mut Session, p: &Value) -> Result<Value> {
/// first ([`super::note_texts`]), and a note for each option of the request `asked` (`p` before a
/// preset or the remembered settings were laid under it) that the files the rows write don't read
/// ([`unused_option_notes`]).
pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result<Value> {
check_passwords(p)?;
let unused = unused_option_notes(asked, p);
let o = ScreenParams::of(p)?;
let rows = rows_of(s, p, o.preset.as_deref())?;
o.one_source()?;
// `<filename>`: the document's file, as Save names it, or its title before it is saved.
let st = s.doc()?;
// Before the folder is made or any row is written.
for r in &rows {
super::check_linked_scripts(C, r.format.id, st)?;
}
let naming = Naming::of(&o, st.path.as_deref().unwrap_or(&st.doc.title))?;
let selection = o.selection_mode()?;
let selected = if selection.is_some() { selected_artwork(s)? } else { vec![] };
@@ -1050,7 +1129,7 @@ pub(crate) fn export(s: &mut Session, p: &Value) -> Result<Value> {
// Include Artboard Fill off: the encoders leave the background colors out.
let fill = if o.include_artboard_fill == Some(false) { json!({ "includeArtboardFill": false }) } else { json!({}) };
let rows = rows.into_iter().map(|r| Row { options: merge(with_black_output(s, &r.options), fill.clone()), ..r }).collect();
let export = ScreenExport { cmd: C, o, rows, naming, items, hidden: None };
let export = ScreenExport { cmd: C, o, rows, naming, items, unused, hidden: None };
match &mut s.screens_hand_off {
Some(slot) => {
*slot = Some(export);
@@ -1071,6 +1150,8 @@ pub struct ScreenExport {
rows: Vec<Row>,
naming: Naming,
items: Vec<Item>,
/// The notes on options the files don't read ([`unused_option_notes`]).
unused: Vec<String>,
/// The export folder and the name the request that prepared the export may see it by, when the
/// folder came from the `exportPreset` and is outside that request's read roots: the reply and
/// the errors of [`ScreenExport::write`] name it as [`export_for_screens`] does.
@@ -1135,14 +1216,17 @@ impl ScreenExport {
/// [`ScreenExport::write`].
fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> {
let ScreenExport { o, rows, naming, items, .. } = export;
let ScreenExport { o, rows, naming, items, unused, .. } = export;
let folder = o.folder.as_deref().filter(|f| !f.is_empty());
if let Some(dir) = folder {
create_dir(dir)?;
}
let mut out = Output::default();
// The encoders' notes for every file, each once.
// The notes on the options, then the encoders' notes for every file, each once.
let mut notes: Vec<Note> = Vec::new();
for text in unused {
add_note(&mut notes, Note::setting(text));
}
// Include Bleed: a grown artboard already holds the bleed. Assets, layers and a selection are
// written on a page of their own bounds, which it doesn't grow.
let bleed_on_page = o.include_bleed && o.assets.is_none() && o.layers.is_none() && o.selection.is_none();
+2 -2
View File
@@ -748,8 +748,8 @@ fn a_native_save_streams_the_bytes_the_encoder_makes() {
}
/// An option given beside the path (an SVG option flat or in `svg`) and in `options` with different
/// values is refused before anything is written; `compress`, `version`, `preview` or `precision` beside the path of a format
/// that doesn't read it is named in the warnings.
/// values is refused before anything is written; a native option beside the path of a format that doesn't read it is named
/// in the warnings.
#[test]
fn a_save_refuses_disagreeing_options_and_names_unread_native_ones() {
let d = tmp_dir("save-options");
@@ -163,12 +163,12 @@ fn dxf_info_lists_layouts_layers_and_units() {
}
#[test]
fn binary_dxf_says_to_save_it_as_ascii() {
fn damaged_binary_dxf_says_so() {
let mut s = Session::new();
let mut bytes = vectorcraft_cad::import::BINARY_SENTINEL.to_vec();
bytes.extend([0u8; 64]);
let e = open(&mut s, &bytes, json!({})).unwrap_err().to_string();
assert!(e.contains("binary DXF") && e.contains("ASCII"), "{e}");
assert!(e.contains("binary DXF") && e.contains("damaged"), "{e}");
let e = s.execute("document.dxfInfo", &json!({"dataBase64": b64(&bytes)})).unwrap_err().to_string();
assert!(e.contains("binary DXF"), "{e}");
}
@@ -280,3 +280,102 @@ fn note_texts_give_the_losses_first_each_kind_in_order() {
assert_eq!(note_texts(&[Note::setting("s1"), Note::setting("s2")]), ["s1", "s2"]);
assert!(note_texts(&[]).is_empty());
}
/// A save notes the `.ai` options its file doesn't read as an export does: a PDF-compatible file
/// doesn't read the legacy file's options or `preserveEditing`, and a legacy file reads its own
/// options only. The notes cover the options beside the path and in `options`.
#[test]
fn a_save_notes_the_ai_options_its_file_does_not_read() {
let (mut s, notes) = (with_art(), unused);
let r = s
.execute("file.saveCopy", &json!({"format": "ai", "outlineText": true, "preserveEditing": false, "options": {"hiddenObjects": "omit"}}))
.unwrap();
assert_eq!(
notes(&r),
[
"`outlineText` was not used: PDF-compatible .ai files don't read it",
"`preserveEditing` was not used: PDF-compatible .ai files don't read it",
"`options.hiddenObjects` was not used: PDF-compatible .ai files don't read it"
],
"{r}"
);
let p = json!({"format": "ai", "aiVersion": "7", "compress": true, "marks": {"trim": true}, "options": {"pdfCompatible": false}});
let r = s.execute("file.saveCopy", &p).unwrap();
assert_eq!(
notes(&r),
[
"`compress` was not used: legacy .ai (version 7) files don't read it",
"`marks` was not used: legacy .ai (version 7) files don't read it",
"`options.pdfCompatible` was not used: legacy .ai (version 7) files don't read it"
],
"{r}"
);
// The file's own options get none.
for p in [
json!({"format": "ai", "aiVersion": "7", "outlineText": true, "options": {"hiddenObjects": "omit", "range": "1"}}),
json!({"format": "ai", "compress": true, "marks": {"trim": true}, "options": {"editingData": false}}),
json!({"format": "pdf", "marks": {"trim": true}, "preserveEditing": false}),
] {
let r = s.execute("file.saveCopy", &p).unwrap();
assert!(notes(&r).is_empty(), "{p}: {r}");
}
}
/// A save notes an option beside the path that only another save format takes, as it notes one in
/// `options`.
#[test]
fn a_save_notes_an_option_beside_the_path_that_only_another_save_format_takes() {
let (mut s, notes) = (with_art(), unused);
let r = s.execute("file.saveCopy", &json!({"format": "vectorcraft", "marks": {"trim": true}, "svg": {"minify": true}})).unwrap();
assert_eq!(notes(&r), ["`marks` was not used: VectorCraft files don't read it", "`svg` was not used: VectorCraft files don't read it"], "{r}");
}
/// The `.ai` options a save's file doesn't read keep the values the document's last save in that
/// format gave them, so a save from Save Options, which sends only the options the file reads,
/// leaves the other version's choices as they were.
#[test]
fn a_save_keeps_the_ai_options_its_file_does_not_read_from_the_last_save() {
let mut s = with_art();
let dir = tmp_dir("ai-kept");
let path = dir.join("kept.ai").to_string_lossy().to_string();
let value = |s: &mut Session, key: &str| s.execute("file.formatOptions", &json!({"format": "ai"})).unwrap()["options"][key]["value"].clone();
s.execute("file.saveAs", &json!({"path": path, "format": "ai", "options": {"aiVersion": "7", "outlineText": true}})).unwrap();
s.execute("file.saveAs", &json!({"path": path, "format": "ai", "options": {"aiVersion": "pdf", "editingData": false}})).unwrap();
assert_eq!(value(&mut s, "outlineText"), json!(true));
assert_eq!(value(&mut s, "editingData"), json!(false));
s.execute("file.saveAs", &json!({"path": path, "format": "ai", "options": {"aiVersion": "7", "hiddenObjects": "omit"}})).unwrap();
assert_eq!(value(&mut s, "editingData"), json!(false));
// An option the request gives is the one saved.
s.execute("file.saveAs", &json!({"path": path, "format": "ai", "options": {"aiVersion": "7", "outlineText": false}})).unwrap();
assert_eq!(value(&mut s, "outlineText"), json!(false));
// The kept options are neither written nor sent again: a plain save's options (which a retry
// in another folder sends to Save As) hold only what the legacy file reads.
for p in [json!({}), json!({"options": {"aiVersion": "7"}})] {
let plan = save_plan(&s, SaveMode::Save, &p).unwrap();
assert!(!plan.options.contains_key("editingData") && !plan.options.contains_key("compress"), "{:?}", plan.options);
assert_eq!(plan.kept.get("editingData"), Some(&json!(false)));
assert!(plan.notes.is_empty(), "{:?}", plan.notes);
let retry = json!({"path": path, "format": "ai", "options": plan.options});
let r = s.execute("file.saveAs", &retry).unwrap();
assert!(!r["warnings"].to_string().contains("was not used"), "{r}");
assert_eq!(value(&mut s, "editingData"), json!(false));
}
std::fs::remove_dir_all(&dir).unwrap();
}
/// The first `.ai` save of a document whose own file is another format remembers only the options
/// it was given: nothing from that format's options is kept.
#[test]
fn a_first_ai_save_keeps_only_the_options_it_is_given() {
let mut s = with_art();
let dir = tmp_dir("ai-first");
let native = dir.join("first.vectorcraft").to_string_lossy().to_string();
let path = dir.join("first.ai").to_string_lossy().to_string();
s.execute("file.saveAs", &json!({"path": native, "options": {"compress": false}})).unwrap();
let plan = save_plan(&s, SaveMode::SaveAs, &json!({"path": path, "format": "ai", "options": {"aiVersion": "7"}})).unwrap();
assert!(plan.kept.is_empty(), "{:?}", plan.kept);
s.execute("file.saveAs", &json!({"path": path, "format": "ai", "options": {"aiVersion": "7"}})).unwrap();
let o = s.execute("file.formatOptions", &json!({"format": "ai"})).unwrap();
assert_eq!(o["options"]["compress"]["value"], json!(true), "{o}");
std::fs::remove_dir_all(&dir).unwrap();
}
+23 -1
View File
@@ -304,11 +304,22 @@ fn options_not_applied_yet_and_document_features_warn() {
let frame = s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 50, "height": 40})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setStroke", &json!({"ids": [frame], "swatch": "Dots"})).unwrap();
assert_eq!(warnings(&export(&mut s, json!({}))).len(), 0);
// A knockout group is approximated: its warning comes back from every PDF path.
// A knockout group is written as a PDF knockout group: nothing to report.
s.execute("select.set", &json!({"ids": [frame]})).unwrap();
s.execute("object.group", &json!({})).unwrap();
s.execute("transparency.set", &json!({"knockout": "on"})).unwrap();
let knockout = |w: Vec<String>| w.iter().any(|w| w.contains("knockout groups"));
assert!(!knockout(warnings(&export(&mut s, json!({})))));
// One whose soft masks would draw a brushed stroke is approximated: its warning comes back
// from every PDF path.
let rect =
|s: &mut Session, x: i32| s.execute("shape.rectangle", &json!({"x": x, "y": 45, "width": 40, "height": 30})).unwrap()["id"].as_u64().unwrap();
let (lower, upper) = (rect(&mut s, 20), rect(&mut s, 40));
s.execute("brush.apply", &json!({"ids": [upper], "name": "3 pt. Round"})).unwrap();
s.execute("object.setProps", &json!({"ids": [lower, upper], "opacity": 50, "knockoutShape": true})).unwrap();
s.execute("select.set", &json!({"ids": [lower, upper]})).unwrap();
s.execute("object.group", &json!({})).unwrap();
s.execute("transparency.set", &json!({"knockout": "on"})).unwrap();
assert!(knockout(warnings(&export(&mut s, json!({})))));
assert!(knockout(warnings(&s.execute("document.export", &as_export(&json!({}))).unwrap())));
// Other formats have none.
@@ -432,6 +443,17 @@ fn pdf_settings_summarise_changes_and_warnings() {
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [g]})).unwrap();
assert_eq!(s.execute("document.pdfSettings", &json!({"includeDocument": true})).unwrap()["warnings"], json!([]));
s.execute("transparency.set", &json!({"knockout": "on"})).unwrap();
// A knockout group is written as a PDF knockout group: nothing to report.
assert_eq!(s.execute("document.pdfSettings", &json!({"includeDocument": true})).unwrap()["warnings"], json!([]));
// One whose soft masks would draw a brushed stroke is approximated.
let rect =
|s: &mut Session, x: i32| s.execute("shape.rectangle", &json!({"x": x, "y": 45, "width": 40, "height": 30})).unwrap()["id"].as_u64().unwrap();
let (lower, upper) = (rect(&mut s, 20), rect(&mut s, 40));
s.execute("brush.apply", &json!({"ids": [upper], "name": "3 pt. Round"})).unwrap();
s.execute("object.setProps", &json!({"ids": [lower, upper], "opacity": 50, "knockoutShape": true})).unwrap();
s.execute("select.set", &json!({"ids": [lower, upper]})).unwrap();
s.execute("object.group", &json!({})).unwrap();
s.execute("transparency.set", &json!({"knockout": "on"})).unwrap();
assert_eq!(s.execute("document.pdfSettings", &json!({})).unwrap()["warnings"], json!([]));
let full = s.execute("document.pdfSettings", &json!({"includeDocument": true})).unwrap();
assert!(warnings(&full).iter().any(|w| w.contains("knockout groups")), "{}", full["warnings"]);
@@ -1163,3 +1163,93 @@ fn single_file_pdfs_hold_every_chosen_artboard() {
assert_eq!(names(&r), ["Artboard-1.pdf", "Artboard-2.pdf"]);
assert!(s.execute("document.exportForScreens", &json!({"pdfs": "both", "formats": [{"format": "pdf"}]})).is_err());
}
/// The warnings of reply `r` that name an option the file doesn't read.
fn unused(r: &Value) -> Vec<String> {
r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).filter(|w| w.contains("was not used")).map(str::to_string).collect()
}
/// An option of a format row, or of a format's settings, that only another format reads is
/// accepted, and the reply's warnings name it as the request does, in the words of a save's note.
#[test]
fn a_row_option_only_another_format_reads_gets_a_note() {
let mut s = session(1);
let p = json!({
"formats": [{"format": "png", "quality": 80}, {"format": "jpg", "quality": 80}, {"format": "ai", "aiVersion": "7", "compress": true}],
"settings": {"png": {"quality": 50, "interlaced": true}, "svg": {"interlaced": true}},
});
let r = export(&mut s, p);
assert_eq!(
unused(&r),
[
"`formats[0].quality` was not used: PNG files don't read it",
"`formats[2].compress` was not used: legacy .ai (version 7) files don't read it",
"`settings.png.quality` was not used: PNG files don't read it",
"`settings.svg.interlaced` was not used: SVG files don't read it"
],
"{r}"
);
// A row's own keys, the keys every row takes and the artboard choices get none.
let p = json!({"formats": [
{"format": "png", "scale": "2x", "suffix": "@2x", "folder": "x", "includeArtboardFill": false, "artboard": 0, "useArtboards": true},
{"format": "pdf", "marks": {"trim": true}, "preset": "High Quality Print"},
{"format": "vectorcraft", "compress": true, "range": "1"},
]});
let r = export(&mut s, p);
assert!(unused(&r).is_empty(), "{r}");
// A format's settings are read as each row of that format writes them: a row can name another
// `.ai` version than the settings do.
let r = export(&mut s, json!({"formats": [{"format": "ai", "aiVersion": "7"}], "settings": {"ai": {"marks": {"trim": true}}}}));
assert_eq!(unused(&r), ["`settings.ai.marks` was not used: legacy .ai (version 7) files don't read it"], "{r}");
let r = export(&mut s, json!({"formats": [{"format": "ai", "aiVersion": "pdf"}], "settings": {"ai": {"aiVersion": "7", "compress": true}}}));
assert!(unused(&r).is_empty(), "{r}");
// A setting another row of the format reads gets none; one no row reads names the first row's
// file.
let rows = json!([{"format": "ai", "aiVersion": "7"}, {"format": "ai"}]);
let r = export(&mut s, json!({"formats": rows, "settings": {"ai": {"editingData": false}}}));
assert!(unused(&r).is_empty(), "{r}");
let r = export(&mut s, json!({"formats": rows, "settings": {"ai": {"quality": 80}}}));
assert_eq!(unused(&r), ["`settings.ai.quality` was not used: legacy .ai (version 7) files don't read it"], "{r}");
// A row that gives the key itself doesn't use the setting.
let rows = json!([{"format": "ai", "aiVersion": "7"}, {"format": "ai", "editingData": true}]);
let r = export(&mut s, json!({"formats": rows, "settings": {"ai": {"editingData": false}}}));
assert_eq!(unused(&r), ["`settings.ai.editingData` was not used: legacy .ai (version 7) files don't read it"], "{r}");
let rows = json!([{"format": "ai", "aiVersion": "7"}, {"format": "ai", "editingData": null}]);
let r = export(&mut s, json!({"formats": rows, "settings": {"ai": {"editingData": false}}}));
assert_eq!(unused(&r), ["`settings.ai.editingData` was not used: legacy .ai (version 7) files don't read it"], "{r}");
// An export writes one file per row and item: a native row doesn't read `separateArtboards`.
let r = export(&mut s, json!({"formats": [{"format": "vectorcraft", "separateArtboards": true}]}));
assert_eq!(unused(&r), ["`formats[0].separateArtboards` was not used: VectorCraft files don't read it"], "{r}");
}
/// The Asset Export panel's export notes the options of its request, not those of the settings
/// the document remembers.
#[test]
fn an_asset_export_notes_the_options_it_is_given() {
let mut s = session(1);
s.execute("select.all", &json!({})).unwrap();
s.execute("assets.add", &json!({"multiple": false})).unwrap();
s.execute("assets.settings.set", &json!({"formats": [{"format": "png", "quality": 80}]})).unwrap();
let r = s.execute("assets.export", &json!({})).unwrap();
assert!(unused(&r).is_empty(), "{r}");
let r = s.execute("assets.export", &json!({"formats": [{"format": "svg", "quality": 80}]})).unwrap();
assert_eq!(unused(&r), ["`formats[0].quality` was not used: SVG files don't read it"], "{r}");
// Settings given are read as the remembered rows write them.
s.execute("assets.settings.set", &json!({"formats": [{"format": "ai", "aiVersion": "7"}]})).unwrap();
let r = s.execute("assets.export", &json!({"settings": {"ai": {"editingData": false}}})).unwrap();
assert_eq!(unused(&r), ["`settings.ai.editingData` was not used: legacy .ai (version 7) files don't read it"], "{r}");
s.execute("assets.settings.set", &json!({"formats": [{"format": "png", "quality": 80}]})).unwrap();
// So does the export a client prepares.
let p = json!({"formats": [{"format": "svg", "quality": 80}]});
let r = s.prepare_screen_export("assets.export", &p).unwrap().write(&mut |_: &str, _: &[u8]| Ok(())).unwrap();
assert_eq!(unused(&r), ["`formats[0].quality` was not used: SVG files don't read it"], "{r}");
}
/// A preset's options add no notes: Export for Screens notes the options of its request.
#[test]
fn an_export_preset_adds_no_notes() {
let mut s = session(1);
s.execute("document.exportPresets.save", &json!({"name": "Mixed", "settings": {"formats": [{"format": "png", "quality": 80}]}})).unwrap();
let r = export(&mut s, json!({"exportPreset": "Mixed"}));
assert!(unused(&r).is_empty(), "{r}");
}
+17
View File
@@ -49,6 +49,10 @@
//! member with another order, and any other change to the list (items moved, or several added
//! or removed at once), takes the model's whole list of fills and strokes.
//!
//! A path directly in a graph series that takes an edit from another member (a graph's paths are
//! members only while the graph is isolated) also has what changed stored on its graph, so that
//! every path of the series takes it when the graph is drawn again (docs/mcp.md).
//!
//! Members that are hidden or locked at the time are left as they are. An edit that would take any
//! member past the canvas (beyond [`vectorcraft_doc::MAX_COORD`]) is refused whole, as one that
//! takes the selection there is. Whenever the document is put back (Undo, Redo, a cancelled drag
@@ -786,9 +790,22 @@ pub(crate) fn propagate(before: &Document, d: &mut Document, ge: &GlobalEdit, se
}
super::object::keep_compound_aligned(d, *id, Scaling::default());
}
keep_series_changes(before, d, &edited);
edited
}
/// Store on their graphs what the members `edited`, and the objects in them, took on the paths directly in a graph
/// series, for the graph's next redraw. The edited member is left to the edit's own command.
fn keep_series_changes(before: &Document, d: &mut Document, edited: &[NodeId]) {
let mut taken = vec![];
for id in edited {
if let Some(n) = d.node(*id) {
n.walk(&mut |c: &Node| taken.push(c.id));
}
}
super::appearance::capture_series_changes(before, d, &taken);
}
/// The outlines of the members of the active document's Global Edit that are not selected, hold
/// no selected object and sit inside no selected object, in their layer's colour: the canvas
/// highlights them while Global Edit is on. While it is off, with one supported object selected,
+1 -1
View File
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Gradient Vector",
[],
None,
"{start?: [x,y], end?: [x,y] (document coordinates; both or neither: omitted, the vector stays), aspect?: % (radial, conic and diamond: the extent's height / width across the vector, a negative one mirroring a conic's sweep and an error for the other kinds; default: kept), focal?: [x,y] (document coordinates) | null (radial: the focal point, where the first stop sits, pulled inside the extent ellipse; null centres it; default: it keeps its place in the ellipse; an error on a conic or diamond gradient), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (alias: index; omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\", index?: appearance item index (as item)} set the gradient vector, aspect ratio and focal point (solid paints become the default gradient; type objects set it on their runs, in text space). On a path directly in a graph series, the graph also stores the gradient with its placement when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, with the gradient fitted to each label",
"{start?: [x,y], end?: [x,y] (document coordinates; both or neither: omitted, the vector stays), aspect?: % (radial, conic and diamond: the extent's height / width across the vector, a negative one mirroring a conic's sweep and an error for the other kinds; default: kept), focal?: [x,y] (document coordinates) | null (radial: the focal point, where the first stop sits, pulled inside the extent ellipse; null centres it; default: it keeps its place in the ellipse; an error on a conic or diamond gradient), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (alias: index; omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\", index?: appearance item index (as item)} set the gradient vector, aspect ratio and focal point (solid paints become the default gradient; type objects set it on their runs, in text space). On a path directly in a graph series, the graph also stores the gradient with its placement relative to the path's box when it is on the topmost visible fill or stroke, and every path of the series takes it at the same place on its own box (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, with the gradient fitted to each label",
has_doc,
set_gradient_geom
),
+3 -2
View File
@@ -46,8 +46,9 @@ use generate::generate;
use series::default_series_color;
pub(crate) use series::{
LabelTextChange, capture_label_anti_alias, capture_label_object_opacity, capture_label_paragraphs, capture_label_rows, capture_label_styles,
capture_label_text, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, label_object_opacity_differs,
paint_targets, series_group_marks, series_group_marks_where, series_marks_in, series_object_opacity_differs, shown_paint,
capture_label_text, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, is_design_art,
label_object_opacity_differs, paint_targets, series_group_marks, series_group_marks_where, series_marks_in, series_object_opacity_differs,
shown_paint,
};
#[cfg(test)]
+2 -2
View File
@@ -6,7 +6,7 @@ use super::labels::{
recolour_text, runs, shadow_of,
};
use super::markers::{MARKER_BUDGET, marker_cost, marker_designs};
use super::series::{series_marks, with_series_opacity};
use super::series::{series_marks, with_series_gradients, with_series_opacity};
use super::{
Arc, BezPath, Color, Document, GraphKind, GraphSpec, Justify, Node, NodeKind, Paint, PathData, Point, Rect, TickLength, ValueAxisSide, shapes,
};
@@ -1006,7 +1006,7 @@ impl<'a> Plot<'a> {
}
}
let name = g.series.get(s).cloned().filter(|n| !n.is_empty()).unwrap_or_else(|| format!("Series {}", s + 1));
let grp = self.b.series(&name, s, with_series_opacity(g, s, items));
let grp = self.b.series(&name, s, with_series_opacity(g, s, with_series_gradients(g, s, items)));
self.b.out.push(grp);
}
self.b.out.append(&mut self.on_top);
+156 -17
View File
@@ -2,7 +2,7 @@ use vectorcraft_color::BlendMode;
use super::axis::radar_axis;
use super::labels::{Role, filled_lines_on, label_para, label_style};
use super::{Arc, CharStyle, Color, Document, GraphKind, GraphSpec, HashMap, Node, NodeId, NodeKind, Paint, Result, Session, Value, bad};
use super::{Arc, CharStyle, Color, Document, GraphKind, GraphSpec, HashMap, Node, NodeId, NodeKind, Paint, Rect, Result, Session, Value, bad};
// ---------- generation ----------
@@ -131,7 +131,7 @@ pub(crate) fn paint_targets(doc: &Document, ids: &[NodeId]) -> Vec<NodeId> {
}
let mut out = Vec::new();
for id in ids {
// The series' own marks: the art of a marker design inside it keeps the design's paint (painting it would
// The series' own marks: the art of a graph design inside it keeps the design's paint (painting it would
// last only until the graph is drawn again), so edit the design to change it.
match members.get(id) {
Some(r) if r.group == *id => {
@@ -139,7 +139,7 @@ pub(crate) fn paint_targets(doc: &Document, ids: &[NodeId]) -> Vec<NodeId> {
out.extend(group.children().into_iter().flatten().filter(|m| matches!(m.kind, NodeKind::Path { .. })).map(|m| m.id));
}
}
Some(r) if doc.parent_of(*id) != Some(r.group) => {}
Some(r) if doc.parent_of(*id) != Some(r.group) || doc.node(*id).is_some_and(|n| !matches!(n.kind, NodeKind::Path { .. })) => {}
_ => out.push(*id),
}
}
@@ -157,18 +157,11 @@ pub(crate) fn series_group_marks(doc: &Document, ids: &[NodeId]) -> Vec<NodeId>
/// [`series_group_marks`] for the series groups `stands` accepts; the others pass through.
pub(crate) fn series_group_marks_where(doc: &Document, ids: &[NodeId], stands: impl Fn(&Node) -> bool) -> Vec<NodeId> {
// A series group is a child of a graph with one of the graph's series indexes ([`series_members`]). Each id is
// looked up through its parent, with no pass over the document: the panels call this while they draw.
let is_series_group = |n: &Node| {
let Some(index) = n.extras().series_index.and_then(|i| usize::try_from(i).ok()) else { return false };
let graph = doc.parent_of(n.id).and_then(|parent| doc.node(parent)).and_then(|parent| parent.extras().graph.as_deref());
graph.is_some_and(|spec| index < series_count(spec))
};
let mut seen = std::collections::HashSet::new();
let mut out = Vec::new();
for id in ids {
match doc.node(*id) {
Some(group) if is_series_group(group) && stands(group) => {
Some(group) if is_series_group(doc, group) && stands(group) => {
let marks: Vec<NodeId> =
group.children().into_iter().flatten().filter(|m| matches!(m.kind, NodeKind::Path { .. })).map(|m| m.id).collect();
if marks.is_empty() { out.push(*id) } else { out.extend(marks) }
@@ -180,6 +173,26 @@ pub(crate) fn series_group_marks_where(doc: &Document, ids: &[NodeId], stands: i
out
}
/// Whether `n` is a graph series group: a child of a graph with one of the graph's series indexes ([`series_members`]).
/// It is looked up through its parent, with no pass over the document: the panels call this while they draw.
fn is_series_group(doc: &Document, n: &Node) -> bool {
let Some(index) = n.extras().series_index.and_then(|i| usize::try_from(i).ok()) else { return false };
let graph = doc.parent_of(n.id).and_then(|parent| doc.node(parent)).and_then(|parent| parent.extras().graph.as_deref());
graph.is_some_and(|spec| index < series_count(spec))
}
/// Whether `id` is the art of a graph design drawn in a graph series (Object › Graph › Column or Marker): an object
/// inside a series group other than a path directly in it. The graph draws that art again from the design.
pub(crate) fn is_design_art(doc: &Document, id: NodeId) -> bool {
let Some(chain) = doc.ancestry(id) else { return false };
let Some(at) = chain.iter().position(|a| doc.node(*a).is_some_and(|n| is_series_group(doc, n))) else { return false };
match chain.len() - at {
1 => false,
2 => doc.node(id).is_some_and(|n| !matches!(n.kind, NodeKind::Path { .. })),
_ => true,
}
}
/// The paint of the topmost visible fill (`true`) or stroke (`false`) of `node`, and a stroke's weight (0 without paint).
/// With no such row: no paint.
pub(crate) fn shown_paint(node: &Node, fill: bool) -> (Paint, f64) {
@@ -216,7 +229,8 @@ pub(crate) fn capture_series_top_paints(doc: &mut Document, edited: &[(NodeId, b
continue;
}
let (paint, width) = shown_paint(node, *fill);
captures.push((r.graph, r.index, *fill, paint, (!*fill).then_some(width)));
let width = (!*fill).then_some(width);
captures.push((r.graph, r.index, *fill, paint, width, paint_box(node, width)));
}
store_series_paints(doc, captures)
}
@@ -268,11 +282,129 @@ fn settle_series_paints(doc: &mut Document, before: SeriesPaintsBefore) -> bool
changed
}
/// Store each capture (graph, series index, fill or stroke, paint, stroke weight) in its series. Returns whether a
/// The box a series keeps a gradient relative to: (0, 0)–(1, 1), as graphic styles keep theirs.
const UNIT_BOX: Rect = vectorcraft_doc::GraphicStyle::UNIT_BOX;
/// The gradient `slot` keeps for its fill (`fill`) or stroke as the graph draws it on box `on`: one kept relative to the
/// unit box placed on `on`, also when `on` has no width or no height, and one kept in document coordinates as it is kept.
/// None when the slot keeps no gradient, or keeps one relative to the unit box and there is no box.
fn kept_on(slot: &vectorcraft_doc::SeriesPaint, fill: bool, on: Option<Rect>) -> Option<Paint> {
let (kept, unit) = if fill { (&slot.fill, slot.fill_unit_box) } else { (&slot.stroke, slot.stroke_unit_box) };
let Some(Paint::Gradient(g)) = kept else { return None };
if !unit {
return Some(Paint::Gradient(g.clone()));
}
let on = on?;
let mut g = g.clone();
g.rebase(UNIT_BOX, on);
Some(Paint::Gradient(g))
}
/// Whether `a` and `b` are the same paint, a gradient's vector, focal point and freeform points each within 1e-6 pt (the
/// rounding a move or a placement on another box leaves).
fn same_paint_placed(a: &Paint, b: &Paint) -> bool {
let (Paint::Gradient(a), Paint::Gradient(b)) = (a, b) else { return a == b };
let near = |p: vectorcraft_geom::Point, q: vectorcraft_geom::Point| (p - q).hypot() <= 1e-6;
let mut a = (**a).clone();
match (&mut a.geom, &b.geom) {
(Some(ag), Some(bg)) => {
let focal = match (ag.focal, bg.focal) {
(Some(p), Some(q)) => near(p, q),
(p, q) => p.is_none() && q.is_none(),
};
if !(near(ag.start, bg.start) && near(ag.end, bg.end) && focal) {
return false;
}
(ag.start, ag.end, ag.focal) = (bg.start, bg.end, bg.focal);
}
(None, None) => {}
_ => return false,
}
match (&mut a.freeform, &b.freeform) {
(Some(af), Some(bf)) => {
if af.points.len() != bf.points.len() || !af.points.iter().zip(&bf.points).all(|(p, q)| near(p.at, q.at)) {
return false;
}
for (p, q) in af.points.iter_mut().zip(&bf.points) {
p.at = q.at;
}
}
(None, None) => {}
_ => return false,
}
a == **b
}
/// The box a gradient on `node`'s fill (`width` None) or on its stroke of `width` is placed on: the geometric bounds, grown
/// by half the weight for a stroke. The box can have no width or no height.
fn paint_box(node: &Node, width: Option<f64>) -> Option<Rect> {
let b = node.geometric_bounds()?;
Some(width.map_or(b, |w| vectorcraft_doc::appearance::stroke_paint_bounds(b, w)))
}
/// `paint` as a series keeps it: a gradient placed on `from` (the edited mark's [`paint_box`]) is moved to the same place
/// relative to [`UNIT_BOX`], so each mark takes it on its own box. A box with no width or no height, which a gradient's
/// place cannot be kept relative to, leaves the paint in document coordinates. Returns the paint and whether it was moved.
fn unit_box_paint(paint: Paint, from: Option<Rect>) -> (Paint, bool) {
match (paint, from.filter(|b| b.width() > 1e-9 && b.height() > 1e-9)) {
(Paint::Gradient(mut g), Some(from)) => {
g.rebase(from, UNIT_BOX);
(Paint::Gradient(g), true)
}
(paint, _) => (paint, false),
}
}
/// The paths directly inside series `i`'s group (`items`) with the series' kept gradients, which are kept relative to the
/// unit box, placed on each path's own box: a fill on its geometric bounds, a stroke on its stroke's box. Paints kept in
/// document coordinates (from files saved before the unit box) are left as they are.
pub(super) fn with_series_gradients(g: &GraphSpec, i: usize, mut items: Vec<Arc<Node>>) -> Vec<Arc<Node>> {
let Some(slot) = g.series_paints.get(i) else { return items };
fn kept(p: &Option<Paint>, unit: bool) -> Option<&Paint> {
p.as_ref().filter(|p| unit && matches!(p, Paint::Gradient(_)))
}
let (fill, stroke) = (kept(&slot.fill, slot.fill_unit_box), kept(&slot.stroke, slot.stroke_unit_box));
if fill.is_none() && stroke.is_none() {
return items;
}
// A Filled Lines band takes the kept stroke as its fill when no fill is kept.
let band_fill = if slot.fill.is_none() { stroke } else { None };
let fill_from_store = |p: &Paint| fill == Some(p) || band_fill == Some(p);
let stroke_from_store = |p: &Paint| stroke == Some(p);
for item in &mut items {
if !matches!(item.kind, NodeKind::Path { .. }) {
continue;
}
let Some(b) = item.geometric_bounds() else { continue };
let ap = &item.appearance;
if !ap.fill().is_some_and(|f| fill_from_store(&f.paint)) && !ap.stroke().is_some_and(|st| stroke_from_store(&st.paint)) {
continue;
}
let ap = &mut Arc::make_mut(item).appearance;
if let Some(f) = ap.fill_mut().filter(|f| fill_from_store(&f.paint))
&& let Paint::Gradient(gp) = &mut f.paint
{
gp.rebase(UNIT_BOX, b);
}
if let Some(st) = ap.stroke_mut().filter(|st| stroke_from_store(&st.paint)) {
let to = st.paint_bounds(b);
if let Paint::Gradient(gp) = &mut st.paint {
gp.rebase(UNIT_BOX, to);
}
}
}
items
}
/// A paint taken from a series mark: graph, series index, fill or stroke, paint, stroke weight and the mark's
/// [`paint_box`].
type Capture = (NodeId, usize, bool, Paint, Option<f64>, Option<Rect>);
/// Store each capture in its series; a gradient is kept relative to the unit box ([`unit_box_paint`]). Returns whether a
/// series' captured fill or stroke differs from what the graph stored before the first capture.
fn store_series_paints(doc: &mut Document, captures: Vec<(NodeId, usize, bool, Paint, Option<f64>)>) -> bool {
fn store_series_paints(doc: &mut Document, captures: Vec<Capture>) -> bool {
let mut before = SeriesPaintsBefore::new();
for (graph, index, fill, paint, width) in captures {
for (graph, index, fill, paint, width, from) in captures {
let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue };
before.entry(graph).or_insert_with(|| spec.series_paints.clone());
// `index` is below the graph's series count (`series_members`).
@@ -280,10 +412,17 @@ fn store_series_paints(doc: &mut Document, captures: Vec<(NodeId, usize, bool, P
spec.series_paints.resize(index + 1, vectorcraft_doc::SeriesPaint::default());
}
let Some(slot) = spec.series_paints.get_mut(index) else { continue };
// A mark that shows the kept gradient as it was drawn leaves the kept gradient as it is.
let drawn = kept_on(slot, fill, from).is_some_and(|kept| same_paint_placed(&kept, &paint));
let (paint, unit) = unit_box_paint(paint, from);
if fill {
slot.fill = Some(paint);
if !drawn {
(slot.fill, slot.fill_unit_box) = (Some(paint), unit);
}
} else {
slot.stroke = Some(paint);
if !drawn {
(slot.stroke, slot.stroke_unit_box) = (Some(paint), unit);
}
slot.stroke_width = width;
}
}
+593 -19
View File
@@ -373,8 +373,8 @@ fn removing_a_series_marks_fill_forgets_its_kept_opacity() {
assert_eq!(spec(&s, id).series_paints[0].fill_opacity, None);
}
/// An opacity set on a row added to a graph design's copy inside a series is not kept for the series: the graph draws
/// the design again from the design itself.
/// A row or a row opacity is not given to a graph design's copy inside a series, and the graph keeps no opacity for the
/// series: the graph draws the design again from the design itself.
#[test]
fn an_opacity_on_a_design_copy_in_a_series_is_not_kept() {
let mut s = Session::new();
@@ -384,11 +384,143 @@ fn an_opacity_on_a_design_copy_in_a_series_is_not_kept() {
s.execute("graph.column", &json!({"id": id.0, "design": "Square"})).unwrap();
let copy = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].clone();
assert!(matches!(copy.kind, NodeKind::Group { .. }));
s.execute("appearance.addFill", &json!({"ids": [copy.id.0]})).unwrap();
s.execute("transparency.set", &json!({"ids": [copy.id.0], "item": 0, "opacity": 40})).unwrap();
assert!(s.execute("appearance.addFill", &json!({"ids": [copy.id.0]})).is_err());
assert!(s.execute("transparency.set", &json!({"ids": [copy.id.0], "item": 0, "opacity": 40})).is_err());
assert!(spec(&s, id).series_paints.first().is_none_or(|p| p.fill_opacity.is_none()));
}
/// A column graph whose series 0 draws the design "Square": the graph, series 0's first copy of the design, a path
/// inside that copy, and the first mark of series 1, drawn plain.
fn design_art() -> (Session, NodeId, NodeId, NodeId, NodeId) {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let id = graph(&mut s, "column");
save_design(&mut s, "Square");
s.execute("graph.column", &json!({"id": id.0, "seriesIndexes": [0], "design": "Square"})).unwrap();
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
let copy = series(&n, 0).children().unwrap()[0].clone();
assert!(matches!(copy.kind, NodeKind::Group { .. }));
let mut art = vec![];
copy.walk(&mut |m| {
if matches!(m.kind, NodeKind::Path { .. }) {
art.push(m.id);
}
});
let mark = series(&n, 1).children().unwrap()[0].clone();
assert!(matches!(mark.kind, NodeKind::Path { .. }));
(s, id, copy.id, art[0], mark.id)
}
/// `cmd` with `p` is refused as an edit of graph design art, and the document keeps its undo history.
fn refused_on_design_art(s: &mut Session, cmd: &str, p: serde_json::Value) {
let steps = s.doc().unwrap().history.undo.len();
let e = s.execute(cmd, &p).unwrap_err().to_string();
assert!(e.contains("drawn again from the design"), "{cmd}: {e}");
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{cmd}");
}
/// The commands that give rows, effects or graphic styles refuse the art of a graph design inside a series, given by
/// id (the design's copy or a path inside it) or selected: the graph draws that art again from the design.
#[test]
fn appearance_commands_refuse_a_graph_designs_art_in_a_series() {
let (mut s, _, copy, art, _) = design_art();
let (rect, _) = blue_style(&mut s, "Blue", false);
let graphic = s.execute("shape.rectangle", &json!({"x": 700, "y": 700, "width": 10, "height": 10})).unwrap()["id"].clone();
s.execute("threeD.addGraphic", &json!({"name": "Mark", "ids": [graphic]})).unwrap();
let fill = top_row(&s, art, true);
for ids in [json!([copy.0]), json!([art.0])] {
refused_on_design_art(
&mut s,
"graphicStyle.addFromLibrary",
json!({"library": "painted-sketched", "name": "Wet Ink", "apply": true, "ids": ids}),
);
for cmd in ["appearance.addFill", "appearance.addStroke", "appearance.clear", "appearance.reduceToBasic", "appearance.showAllHidden"] {
refused_on_design_art(&mut s, cmd, json!({"ids": ids}));
}
refused_on_design_art(&mut s, "appearance.moveItem", json!({"ids": ids, "from": "contents", "to": 0}));
refused_on_design_art(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "ids": ids}));
refused_on_design_art(&mut s, "appearance.addEffect", json!({"effect": "stylize.dropShadow", "ids": ids}));
refused_on_design_art(&mut s, "effect.apply", json!({"effect": "threeD.extrude", "item": null, "ids": ids}));
refused_on_design_art(&mut s, "effect.move", json!({"ids": ids, "from": 0, "to": 0}));
refused_on_design_art(&mut s, "effect.remove", json!({"ids": ids, "index": 0}));
refused_on_design_art(&mut s, "threeD.mapGraphic", json!({"ids": ids, "symbol": "Mark"}));
refused_on_design_art(&mut s, "graphicStyle.apply", json!({"name": "Blue", "ids": ids}));
}
for cmd in ["appearance.removeItem", "appearance.duplicateItem"] {
refused_on_design_art(&mut s, cmd, json!({"ids": [art.0], "index": fill}));
}
refused_on_design_art(&mut s, "appearance.setItem", json!({"ids": [art.0], "index": fill, "color": "#00ff00"}));
refused_on_design_art(&mut s, "appearance.moveItem", json!({"ids": [art.0], "from": fill, "to": 0}));
refused_on_design_art(&mut s, "transparency.set", json!({"ids": [art.0], "item": fill, "opacity": 40}));
refused_on_design_art(&mut s, "appearance.copyFrom", json!({"source": rect.0, "ids": [art.0]}));
refused_on_design_art(&mut s, "appearance.transfer", json!({"source": rect.0, "target": art.0, "copy": true}));
refused_on_design_art(&mut s, "appearance.transfer", json!({"source": art.0, "target": rect.0}));
// Selected, and through the contents of the design's copy.
s.execute("select.set", &json!({"ids": [art.0]})).unwrap();
refused_on_design_art(&mut s, "appearance.addFill", json!({}));
refused_on_design_art(&mut s, "graphicStyle.addFromLibrary", json!({"library": "painted-sketched", "name": "Wet Ink", "apply": true}));
refused_on_design_art(&mut s, "appearance.addStroke", json!({"ids": [copy.0], "target": "contents"}));
// A Pathfinder effect does not group the selected paths of the design's copy.
let mut paths = vec![];
s.doc().unwrap().doc.node(copy).unwrap().walk(&mut |m| {
if matches!(m.kind, NodeKind::Path { .. }) {
paths.push(m.id.0);
}
});
assert_eq!(paths.len(), 2);
s.execute("select.set", &json!({"ids": paths})).unwrap();
refused_on_design_art(&mut s, "effect.apply", json!({"effect": "pathfinder.add"}));
// Read as a source, the art gives its look.
s.execute("appearance.transfer", &json!({"source": art.0, "target": rect.0, "copy": true})).unwrap();
}
/// Given the art of a graph design in a series with other objects, the commands edit the other objects only.
#[test]
fn appearance_commands_edit_the_objects_given_with_a_graph_designs_art() {
let (mut s, id, copy, art, mark) = design_art();
let (rect, _) = blue_style(&mut s, "Blue", false);
let rows = |s: &Session, id: NodeId| s.doc().unwrap().doc.node(id).unwrap().appearance.clone();
let (copy_was, art_was, mark_was) = (rows(&s, copy), rows(&s, art), rows(&s, mark));
s.execute("appearance.addFill", &json!({"ids": [copy.0, mark.0]})).unwrap();
assert_eq!((rows(&s, copy), rows(&s, art)), (copy_was.clone(), art_was.clone()));
assert_eq!(rows(&s, mark).items.len(), mark_was.items.len() + 1);
s.execute("edit.undo", &json!({})).unwrap();
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [art.0, mark.0]})).unwrap();
assert_eq!(rows(&s, art), art_was);
assert_eq!(rows(&s, mark).effects.len(), 1);
s.execute("edit.undo", &json!({})).unwrap();
s.execute("appearance.copyFrom", &json!({"source": rect.0, "ids": [art.0, mark.0]})).unwrap();
assert_eq!(rows(&s, art), art_was);
assert_ne!(rows(&s, mark), mark_was);
s.execute("edit.undo", &json!({})).unwrap();
// The graph's contents: series 1's marks take the fill, the design's art does not.
s.execute("appearance.addFill", &json!({"ids": [id.0], "target": "contents"})).unwrap();
assert_eq!((rows(&s, copy), rows(&s, art)), (copy_was, art_was));
assert_eq!(rows(&s, mark).items.len(), mark_was.items.len() + 1);
}
/// The paint commands leave the art of a graph design in a series out, a copy of the design given by id with an item
/// included.
#[test]
fn paint_targets_leave_a_graph_designs_copy_out() {
let (s, _, copy, art, mark) = design_art();
let d = &s.doc().unwrap().doc;
assert_eq!(super::paint_targets(d, &[copy, art, mark]), [mark]);
}
/// The art of a marker design in a series is refused too.
#[test]
fn effect_commands_refuse_a_marker_designs_art() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut s, "Pill");
let id = graph(&mut s, "line");
s.execute("graph.marker", &json!({"id": id.0, "seriesIndexes": [1], "design": "Pill"})).unwrap();
let marker = series(s.doc().unwrap().doc.node(id).unwrap(), 1).children().unwrap()[1].clone();
assert!(matches!(marker.kind, NodeKind::Group { .. }), "the design's art");
refused_on_design_art(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "ids": [marker.id.0]}));
}
/// A series' kept opacity goes on its generated marks only: a column design made of one path keeps its own opacity.
#[test]
fn a_column_design_keeps_its_own_opacity_under_a_series_opacity() {
@@ -572,6 +704,124 @@ fn an_object_opacity_a_series_mark_already_shows_replaces_the_kept_opacity() {
assert!(spec(&s, id).series_paints.iter().all(|p| p.opacity.is_none()));
}
/// Randomize Opacity on marks of one series stores the opacity of the frontmost of them on the graph in the same undo
/// step, and every mark of the series has it when the graph is drawn again.
#[test]
fn a_random_opacity_on_series_marks_survives_regeneration() {
let (mut s, id, _, marks) = column_marks();
s.execute("addon.arrange.randomizeOpacity", &json!({"ids": [marks[1].0, marks[0].0], "min": 30, "max": 60, "seed": 7})).unwrap();
let front = s.doc().unwrap().doc.node(marks[1]).unwrap().opacity;
assert!(front < 1.0);
assert_eq!(spec(&s, id).series_paints[0].opacity, Some(front));
s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4]]})).unwrap();
assert!(transparency_of(&s, id, 0).iter().all(|t| t.0 == front), "{:?}", transparency_of(&s, id, 0));
assert!(transparency_of(&s, id, 1).iter().all(|t| t.0 == 1.0), "{:?}", transparency_of(&s, id, 1));
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert!(spec(&s, id).series_paints.is_empty(), "undo takes back the opacities and what the graph stored");
}
/// Sort Objects giving series marks new opacities stores the opacity of the frontmost of them on the graph, in place of
/// the one another mark left there.
#[test]
fn an_opacity_sort_objects_gives_series_marks_survives_regeneration() {
let (mut s, id, _, marks) = column_marks();
s.execute("object.setProps", &json!({"id": marks[2].0, "opacity": 30})).unwrap();
assert_eq!(spec(&s, id).series_paints[0].opacity, Some(0.3));
// From left to right the three columns get 30%, 65% and 100%: the frontmost, the rightmost, is fully opaque.
let ids = [marks[0].0, marks[1].0, marks[2].0];
s.execute("addon.arrange.sort", &json!({"ids": ids, "by": "x", "apply": "opacity", "distribute": true})).unwrap();
let opacities: Vec<f32> = marks[..3].iter().map(|m| s.doc().unwrap().doc.node(*m).unwrap().opacity).collect();
assert_eq!(opacities, [0.3, 0.65, 1.0]);
assert_eq!(spec(&s, id).series_paints[0].opacity, None);
s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4]]})).unwrap();
assert!(transparency_of(&s, id, 0).iter().all(|t| t.0 == 1.0), "{:?}", transparency_of(&s, id, 0));
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(spec(&s, id).series_paints[0].opacity, Some(0.3), "undo takes back the sort and what the graph stored");
}
/// Sort Objects stores the opacity of the frontmost series mark whose opacity it changes: a mark in front that keeps its
/// opacity leaves the stored value to the marks it changed.
#[test]
fn an_opacity_sort_objects_stores_the_frontmost_mark_it_changes() {
let (mut s, id, _, marks) = column_marks();
s.execute("object.setProps", &json!({"id": marks[0].0, "opacity": 60})).unwrap();
s.execute("object.setProps", &json!({"id": marks[1].0, "opacity": 30})).unwrap();
assert_eq!(spec(&s, id).series_paints[0].opacity, Some(0.3));
// From left to right the columns trade 60%, 30% and 100% for 30%, 60% and 100%: the frontmost keeps its 100%.
let ids = [marks[0].0, marks[1].0, marks[2].0];
s.execute("addon.arrange.sort", &json!({"ids": ids, "by": "x", "apply": "opacity"})).unwrap();
let opacities: Vec<f32> = marks[..3].iter().map(|m| s.doc().unwrap().doc.node(*m).unwrap().opacity).collect();
assert_eq!(opacities, [0.3, 0.6, 1.0]);
assert_eq!(spec(&s, id).series_paints[0].opacity, Some(0.6));
}
/// An object opacity, blend mode, fill, stroke and weight that Global Edit gives a mark of another series from the mark
/// that was edited are stored on the graph for that series in the same undo step, and every mark of the series has them
/// when the graph is drawn again.
#[test]
fn what_global_edit_gives_series_marks_survives_regeneration() {
let (mut s, id, _, _) = column_marks();
// Equal values: the first column of each series has the same shape.
s.execute("graph.setData", &json!({"rows": [[3, 3], [5, 2]]})).unwrap();
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
let (first, other) = (series(&n, 0).children().unwrap()[0].id, series(&n, 1).children().unwrap()[0].id);
s.execute("object.isolate", &json!({"id": id.0})).unwrap();
s.execute("select.set", &json!({"ids": [first.0]})).unwrap();
let r = s.execute("select.globalEdit", &json!({})).unwrap();
assert!(r["ids"].as_array().unwrap().contains(&json!(other.0)), "{r}");
let steps = s.doc().unwrap().history.undo.len();
s.execute("transparency.set", &json!({"ids": [first.0], "opacity": 40, "blend": "multiply"})).unwrap();
s.execute("paint.setFill", &json!({"ids": [first.0], "color": "#e8573f"})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [first.0], "color": "#1f4e9c"})).unwrap();
s.execute("stroke.set", &json!({"ids": [first.0], "weight": 5})).unwrap();
let mark = s.doc().unwrap().doc.node(other).unwrap().clone();
assert_eq!((mark.opacity, mark.blend), (0.4, BlendMode::Multiply), "Global Edit reaches the other series' mark");
let kept = spec(&s, id).series_paints[1].clone();
assert_eq!((kept.opacity, kept.blend), (Some(0.4), Some(BlendMode::Multiply)));
assert_eq!(kept.fill, Some(mark.appearance.fill_paint()));
assert_eq!((kept.stroke, kept.stroke_width), (Some(mark.appearance.stroke_paint()), Some(5.0)));
s.execute("object.exitIsolation", &json!({})).unwrap();
s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4]]})).unwrap();
let normal = BlendMode::Normal;
assert!(transparency_of(&s, id, 1).iter().all(|t| *t == (0.4, BlendMode::Multiply, normal, normal)), "{:?}", transparency_of(&s, id, 1));
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
assert!(series(&n, 1).children().unwrap().iter().all(|m| m.appearance.fill_paint() == mark.appearance.fill_paint()));
while s.doc().unwrap().history.undo.len() > steps {
s.execute("edit.undo", &json!({})).unwrap();
}
assert!(spec(&s, id).series_paints.iter().all(|p| *p == vectorcraft_doc::SeriesPaint::default()), "{:?}", spec(&s, id).series_paints);
}
/// With a whole series group picked and Global Edit on, the other series groups of the same form take the edit of its
/// marks, and the graph stores it for their series too.
#[test]
fn what_global_edit_gives_the_marks_of_another_series_group_survives_regeneration() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
// Series without names draw no legend, so each series group holds only its columns, laid out like the other's.
let csv = ",,\nQ1,3,3\nQ2,5,5";
let made = s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap();
let id = NodeId(made["id"].as_u64().unwrap());
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
let (first, other) = (series(&n, 0).clone(), series(&n, 1).id);
s.execute("object.isolate", &json!({"id": id.0})).unwrap();
s.execute("select.set", &json!({"ids": [first.id.0]})).unwrap();
let r = s.execute("select.globalEdit", &json!({})).unwrap();
assert!(r["ids"].as_array().unwrap().contains(&json!(other.0)), "{r}");
let marks: Vec<u64> = first.children().unwrap().iter().map(|m| m.id.0).collect();
s.execute("paint.setFill", &json!({"ids": marks, "color": "#e8573f"})).unwrap();
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
let given = series(&n, 1).children().unwrap()[0].appearance.fill_paint();
assert_eq!(given, series(&n, 0).children().unwrap()[0].appearance.fill_paint(), "Global Edit reaches the other group");
assert_eq!(spec(&s, id).series_paints[1].fill, Some(given.clone()));
s.execute("object.exitIsolation", &json!({})).unwrap();
s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4]]})).unwrap();
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
assert!(series(&n, 1).children().unwrap().iter().all(|m| m.appearance.fill_paint() == given));
}
/// A blend mode set on the top fill or stroke row of one series mark is kept by the graph and drawn on every mark of
/// the series again; Normal forgets it.
#[test]
@@ -1627,8 +1877,8 @@ fn a_paint_on_a_design_copy_or_the_other_kind_of_row_is_not_kept() {
s.execute("graph.column", &json!({"id": id.0, "design": "Square"})).unwrap();
let copy = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].clone();
assert!(matches!(copy.kind, NodeKind::Group { .. }));
s.execute("appearance.addFill", &json!({"ids": [copy.id.0]})).unwrap();
s.execute("appearance.setItem", &json!({"ids": [copy.id.0], "index": 0, "color": "#0000ff"})).unwrap();
assert!(s.execute("appearance.addFill", &json!({"ids": [copy.id.0]})).is_err());
assert!(s.execute("appearance.setItem", &json!({"ids": [copy.id.0], "index": 0, "color": "#0000ff"})).is_err());
assert!(spec(&s, id).series_paints.first().is_none_or(|p| p.fill.is_none()));
// A path inside the design's copy is a member of the series too, and its paint is not kept either.
let copy = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].clone();
@@ -1639,7 +1889,7 @@ fn a_paint_on_a_design_copy_or_the_other_kind_of_row_is_not_kept() {
}
});
let art = paths[0];
s.execute("appearance.setItem", &json!({"ids": [art.0], "index": top_row(&s, art, true), "color": "#00ff00"})).unwrap();
assert!(s.execute("appearance.setItem", &json!({"ids": [art.0], "index": top_row(&s, art, true), "color": "#00ff00"})).is_err());
assert!(spec(&s, id).series_paints.first().is_none_or(|p| p.fill.is_none()));
let mut s = Session::new();
@@ -2504,10 +2754,39 @@ fn a_gradient_edit_on_a_series_mark_is_kept() {
series_0_is(&mut s, id, (&fill, 0.4, &red, 2.0), &was);
}
/// A gradient placed on a series mark's fill with `paint.setGradientGeom` is stored on the graph as it is placed, and
/// every mark of the series has that fill, placement included, after the graph is drawn again.
/// Where gradient `paint` sits on box `b`: its vector's start and end, then each freeform point, as fractions of the box.
fn gradient_place(paint: &Paint, b: vectorcraft_geom::Rect) -> Vec<f64> {
let Paint::Gradient(g) = paint else { panic!("not a gradient: {paint:?}") };
let points = g.geom.iter().flat_map(|geom| [geom.start, geom.end]).chain(g.freeform.iter().flat_map(|f| f.points.iter().map(|p| p.at)));
points.flat_map(|p| [(p.x - b.x0) / b.width(), (p.y - b.y0) / b.height()]).collect()
}
/// The box a gradient on `mark`'s fill (`stroke` false) or stroke is placed on.
fn paint_box_of(mark: &vectorcraft_doc::Node, stroke: bool) -> vectorcraft_geom::Rect {
let b = mark.geometric_bounds().unwrap();
if stroke { vectorcraft_doc::appearance::stroke_paint_bounds(b, mark.appearance.stroke_width()) } else { b }
}
/// The fill (`stroke` false) or stroke of every path of series 0, the legend swatch included, has a gradient at `place` on
/// its own box, and the gradients are not all at one place in the document. Returns how many paths were checked.
fn series_0_gradients_at(s: &Session, id: NodeId, stroke: bool, place: &[f64]) -> usize {
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
let paths: Vec<_> = series(&n, 0).children().unwrap().iter().filter(|m| matches!(m.kind, NodeKind::Path { .. })).cloned().collect();
let paints: Vec<Paint> = paths.iter().map(|m| if stroke { m.appearance.stroke_paint() } else { m.appearance.fill_paint() }).collect();
for (m, paint) in paths.iter().zip(&paints) {
let at = gradient_place(paint, paint_box_of(m, stroke));
assert_eq!(at.len(), place.len(), "{at:?}");
assert!(at.iter().zip(place).all(|(a, b)| (a - b).abs() < 1e-9), "{at:?} is not {place:?}");
}
assert!(paints.windows(2).any(|w| w[0] != w[1]), "every mark has the gradient at one place: {paints:?}");
paths.len()
}
/// A gradient placed on a series mark's fill with `paint.setGradientGeom` is stored relative to the mark's box, and every
/// mark of the series has it at the same place on its own box after the graph is drawn again, also after a data change
/// moves and resizes the marks and after the graph is moved.
#[test]
fn a_gradient_placed_on_a_series_mark_is_kept_with_its_placement() {
fn a_gradient_placed_on_a_series_mark_takes_the_same_place_on_every_mark() {
let (mut s, id, _, marks) = column_marks();
// `paint.setFill` stores the gradient before it is placed.
s.execute("paint.setFill", &json!({"ids": [marks[0].0], "gradient": {"kind": "linear"}})).unwrap();
@@ -2516,26 +2795,258 @@ fn a_gradient_placed_on_a_series_mark_is_kept_with_its_placement() {
s.execute("paint.setGradientGeom", &json!({"ids": [marks[0].0], "start": [0, 0], "end": [10, 40]})).unwrap();
let placed = fill_of(&s, marks[0]);
assert_ne!(placed, fill, "the command places the gradient");
assert_eq!(spec(&s, id).series_paints[0].fill, Some(placed.clone()));
s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2], [3, 4]]})).unwrap();
assert!(marks_of(&s, id, 0).iter().all(|m| m.0 == placed), "{:?}", marks_of(&s, id, 0));
let mark = s.doc().unwrap().doc.node(marks[0]).unwrap().clone();
let place = gradient_place(&placed, paint_box_of(&mark, false));
let kept = spec(&s, id).series_paints[0].clone();
assert!(kept.fill_unit_box);
assert_eq!(gradient_place(kept.fill.as_ref().unwrap(), vectorcraft_doc::GraphicStyle::UNIT_BOX), place);
s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2], [3, 4], [6, 1]]})).unwrap();
assert!(series_0_gradients_at(&s, id, false, &place) >= 4);
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("object.move", &json!({"dx": 50, "dy": 30})).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "rows": [[2, 2], [5, 4], [1, 1]]})).unwrap();
series_0_gradients_at(&s, id, false, &place);
}
/// A point recolored with `paint.freeform.setPoint` in a freeform gradient on a series mark's fill is stored on the graph.
/// A gradient placed on a series mark's stroke is kept relative to the mark's stroke box, and every mark of the series has
/// it at the same place on its own stroke box after the graph is drawn again.
#[test]
fn a_gradient_placed_on_a_series_marks_stroke_takes_the_same_place_on_every_mark() {
let (mut s, id, _, marks) = column_marks();
s.execute("paint.setStroke", &json!({"ids": [marks[1].0], "gradient": {"kind": "radial"}})).unwrap();
s.execute("stroke.set", &json!({"ids": [marks[1].0], "weight": 4})).unwrap();
s.execute("paint.setGradientGeom", &json!({"ids": [marks[1].0], "stroke": true, "start": [150, 200], "end": [170, 260]})).unwrap();
let mark = s.doc().unwrap().doc.node(marks[1]).unwrap().clone();
let place = gradient_place(&mark.appearance.stroke_paint(), paint_box_of(&mark, true));
assert!(spec(&s, id).series_paints[0].stroke_unit_box);
s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2], [3, 4], [6, 1]]})).unwrap();
series_0_gradients_at(&s, id, true, &place);
}
/// A placed gradient picked up with the Eyedropper from art outside the graph is kept relative to the series mark it is
/// dropped on, and every mark of the series has it at the same place on its own box.
#[test]
fn a_placed_gradient_dropped_on_a_series_mark_takes_the_same_place_on_every_mark() {
let (mut s, id, _, marks) = column_marks();
let r = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap());
s.execute("paint.setFill", &json!({"ids": [r.0], "gradient": {"kind": "linear"}})).unwrap();
s.execute("paint.setGradientGeom", &json!({"ids": [r.0], "start": [610, 600], "end": [630, 620]})).unwrap();
s.execute("appearance.copyFrom", &json!({"source": r.0, "ids": [marks[2].0]})).unwrap();
let mark = s.doc().unwrap().doc.node(marks[2]).unwrap().clone();
let place = gradient_place(&mark.appearance.fill_paint(), paint_box_of(&mark, false));
assert!(spec(&s, id).series_paints[0].fill_unit_box);
s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2], [3, 4], [6, 1]]})).unwrap();
series_0_gradients_at(&s, id, false, &place);
}
/// A graphic style with a placed gradient applied to a series mark is kept relative to that mark's box, and every mark of
/// the series has the gradient at the same place on its own box.
#[test]
fn a_graphic_style_gradient_applied_to_a_series_mark_takes_the_same_place_on_every_mark() {
let (mut s, id, _, marks) = column_marks();
let r = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap());
s.execute("paint.setFill", &json!({"ids": [r.0], "gradient": {"kind": "linear"}})).unwrap();
s.execute("paint.setGradientGeom", &json!({"ids": [r.0], "start": [610, 600], "end": [630, 620]})).unwrap();
s.execute("graphicStyle.new", &json!({"id": r.0, "name": "Placed"})).unwrap();
s.execute("graphicStyle.apply", &json!({"name": "Placed", "ids": [marks[2].0]})).unwrap();
let mark = s.doc().unwrap().doc.node(marks[2]).unwrap().clone();
let place = gradient_place(&mark.appearance.fill_paint(), paint_box_of(&mark, false));
assert!(spec(&s, id).series_paints[0].fill_unit_box);
s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2], [3, 4], [6, 1]]})).unwrap();
series_0_gradients_at(&s, id, false, &place);
}
/// A point recolored with `paint.freeform.setPoint` in a freeform gradient on a series mark's fill is stored on the graph,
/// and every mark of the series has the gradient's points at the same place on its own box after the graph is drawn again.
#[test]
fn a_freeform_gradient_edit_on_a_series_mark_is_kept() {
let (mut s, id, _, marks) = column_marks();
let points = json!([{"at": [20, 20], "color": "#53aadf"}, {"at": [50, 50], "color": "#ff8000"}]);
// `paint.setFill` stores the gradient before its point is recolored.
s.execute("paint.setFill", &json!({"ids": [marks[0].0], "gradient": {"kind": "freeform", "freeform": {"points": points}}})).unwrap();
let fill = fill_of(&s, marks[0]);
assert_eq!(spec(&s, id).series_paints[0].fill, Some(fill.clone()));
s.execute("paint.freeform.setPoint", &json!({"ids": [marks[0].0], "index": 1, "color": "#00ff00"})).unwrap();
let edited = fill_of(&s, marks[0]);
assert_ne!(edited, fill, "the command recolors the point");
assert_eq!(spec(&s, id).series_paints[0].fill, Some(edited.clone()));
let Paint::Gradient(g) = &edited else { panic!("{edited:?}") };
assert_eq!(g.freeform.as_ref().unwrap().points[1].color.to_hex(), "#00ff00");
let mark = s.doc().unwrap().doc.node(marks[0]).unwrap().clone();
let place = gradient_place(&edited, paint_box_of(&mark, false));
let kept = spec(&s, id).series_paints[0].clone();
assert!(kept.fill_unit_box);
assert_eq!(gradient_place(kept.fill.as_ref().unwrap(), vectorcraft_doc::GraphicStyle::UNIT_BOX), place);
s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2], [3, 4]]})).unwrap();
assert!(marks_of(&s, id, 0).iter().all(|m| m.0 == edited), "{:?}", marks_of(&s, id, 0));
series_0_gradients_at(&s, id, false, &place);
}
/// A gradient a graph kept in document coordinates (a file saved before gradients were kept relative to the unit box) is
/// drawn on every mark as it was kept.
#[test]
fn a_gradient_kept_in_document_coordinates_is_drawn_as_kept() {
let (mut s, id, _, marks) = column_marks();
s.execute("paint.setFill", &json!({"ids": [marks[0].0], "gradient": {"kind": "linear"}})).unwrap();
s.execute("paint.setGradientGeom", &json!({"ids": [marks[0].0], "start": [0, 0], "end": [10, 40]})).unwrap();
let placed = fill_of(&s, marks[0]);
s.edit("Kept in document coordinates", |d, _| {
let mut extras = d.node_mut(id).unwrap().extras_mut();
let slot = &mut extras.graph.as_mut().unwrap().series_paints[0];
(slot.fill, slot.fill_unit_box) = (Some(placed.clone()), false);
Ok(())
})
.unwrap();
s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2], [3, 4]]})).unwrap();
assert!(marks_of(&s, id, 0).iter().all(|m| m.0 == placed), "{:?}", marks_of(&s, id, 0));
// The same gradient kept for the fill relative to the unit box leaves the stroke kept in document coordinates as it is.
s.edit("Kept fill and stroke", |d, _| {
let mut extras = d.node_mut(id).unwrap().extras_mut();
let slot = &mut extras.graph.as_mut().unwrap().series_paints[0];
(slot.fill, slot.fill_unit_box) = (Some(placed.clone()), true);
(slot.stroke, slot.stroke_unit_box, slot.stroke_width) = (Some(placed.clone()), false, Some(2.0));
Ok(())
})
.unwrap();
s.execute("graph.setData", &json!({"id": id.0, "rows": [[2, 2], [3, 4]]})).unwrap();
let drawn = marks_of(&s, id, 0);
assert!(drawn.iter().all(|m| m.1 == placed), "{drawn:?}");
series_0_gradients_at(&s, id, false, &gradient_place(&placed, vectorcraft_doc::GraphicStyle::UNIT_BOX));
}
/// A gradient placed on a series path with no height (a flat line's fill) is kept in document coordinates, and every
/// path of the series that takes the kept fill has it at that place in the document.
#[test]
fn a_gradient_placed_on_a_series_path_with_no_height_is_kept_in_document_coordinates() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let id = graph(&mut s, "line");
s.execute("graph.setData", &json!({"id": id.0, "rows": [[3, 2], [3, 4], [3, 6]]})).unwrap();
let flat = |s: &Session| {
let parts = series_parts(s, id, 0);
parts.into_iter().find(|m| m.appearance.fill_paint().is_none() && m.geometric_bounds().is_some_and(|b| b.height() < 1e-9)).unwrap().id
};
let line = flat(&s);
s.execute("paint.setFill", &json!({"ids": [line.0], "gradient": {"kind": "linear"}})).unwrap();
s.execute("paint.setGradientGeom", &json!({"ids": [line.0], "start": [150, 120], "end": [300, 280]})).unwrap();
let placed = fill_of(&s, line);
let kept = spec(&s, id).series_paints[0].clone();
assert!(!kept.fill_unit_box);
assert_eq!(kept.fill, Some(placed.clone()));
s.execute("graph.setData", &json!({"id": id.0, "rows": [[3, 1], [3, 5], [3, 2]]})).unwrap();
let fills: Vec<Paint> = series_parts(&s, id, 0).iter().map(|m| m.appearance.fill_paint()).filter(|p| matches!(p, Paint::Gradient(_))).collect();
assert!(fills.len() >= 2 && fills.iter().all(|p| *p == placed), "{fills:?}");
}
/// Writing a series mark's stroke weight as it is, after the graph drew the mark's stroke from a gradient the series
/// keeps relative to the unit box, leaves the kept gradient, the document and its undo history as they are, on every mark.
#[test]
fn rewriting_a_series_marks_drawn_gradient_stroke_records_no_undo_step() {
let (mut s, id, _, marks) = column_marks();
s.execute("paint.setStroke", &json!({"ids": [marks[1].0], "gradient": {"kind": "radial"}})).unwrap();
s.execute("stroke.set", &json!({"ids": [marks[1].0], "weight": 4})).unwrap();
s.execute("paint.setGradientGeom", &json!({"ids": [marks[1].0], "stroke": true, "start": [150, 200], "end": [170, 260]})).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "rows": [[1.3, 2], [3.7, 4], [6.1, 1]]})).unwrap();
let was = s.doc().unwrap().doc.clone();
let undo = s.doc().unwrap().history.undo.len();
let drawn: Vec<_> = series_parts(&s, id, 0).into_iter().filter(|m| matches!(m.appearance.stroke_paint(), Paint::Gradient(_))).collect();
assert!(drawn.len() >= 4, "{}", drawn.len());
for mark in drawn {
let row = top_row(&s, mark.id, false);
s.execute("appearance.setItem", &json!({"ids": [mark.id.0], "index": row, "weight": mark.appearance.stroke_width()})).unwrap();
assert!(s.doc().unwrap().doc == was, "writing mark {:?} changed the document", mark.id);
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
}
// A mark moved with its gradient shows the kept gradient on its moved box, up to rounding.
let kept = spec(&s, id).series_paints[0].clone();
for (i, mark) in series_parts(&s, id, 0).into_iter().filter(|m| matches!(m.appearance.stroke_paint(), Paint::Gradient(_))).enumerate() {
s.execute("select.set", &json!({"ids": [mark.id.0]})).unwrap();
s.execute("object.move", &json!({"dx": 13.37 + i as f64 * 0.731, "dy": -7.19})).unwrap();
let moved = s.doc().unwrap().doc.node(mark.id).unwrap().geometric_bounds().unwrap();
assert!((moved.x0 - mark.geometric_bounds().unwrap().x0 - 13.37 - i as f64 * 0.731).abs() < 1e-9, "mark {:?} did not move", mark.id);
let undo = s.doc().unwrap().history.undo.len();
let row = top_row(&s, mark.id, false);
s.execute("appearance.setItem", &json!({"ids": [mark.id.0], "index": row, "weight": mark.appearance.stroke_width()})).unwrap();
assert_eq!(spec(&s, id).series_paints[0], kept, "writing moved mark {:?} changed the kept stroke", mark.id);
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
}
}
/// Writing the fill of a series mark with no height (a column for a value of 0) as it is, after the graph drew the mark's
/// fill from a gradient the series keeps relative to the unit box, leaves the kept gradient and its unit-box flag as they
/// are.
#[test]
fn rewriting_a_drawn_gradient_fill_on_a_series_mark_with_no_height_keeps_the_kept_gradient() {
let (mut s, id, _, marks) = column_marks();
s.execute("paint.setFill", &json!({"ids": [marks[0].0], "gradient": {"kind": "linear"}})).unwrap();
s.execute("paint.setGradientGeom", &json!({"ids": [marks[0].0], "start": [0, 0], "end": [10, 40]})).unwrap();
let kept = spec(&s, id).series_paints[0].clone();
assert!(kept.fill_unit_box);
s.execute("graph.setData", &json!({"id": id.0, "rows": [[0, 2], [3, 4], [6, 1]]})).unwrap();
let flat = series_parts(&s, id, 0)
.into_iter()
.find(|m| matches!(m.appearance.fill_paint(), Paint::Gradient(_)) && m.geometric_bounds().is_some_and(|b| b.height() < 1e-9))
.unwrap()
.id;
let changed = s.edit("Write the fill as it is", |d, _| Ok(super::capture_series_top_paints(d, &[(flat, true)]))).unwrap();
assert!(!changed);
assert_eq!(spec(&s, id).series_paints[0], kept);
}
/// Writing a series mark's stroke weight as it is, after the graph drew the mark's stroke from a gradient the series keeps
/// in document coordinates (a file saved before the unit box), leaves the kept gradient and its unit-box flag as they are
/// and records no undo step.
#[test]
fn rewriting_a_series_marks_stroke_drawn_from_a_gradient_kept_in_document_coordinates_keeps_it() {
let (mut s, id, _, marks) = column_marks();
s.execute("paint.setStroke", &json!({"ids": [marks[1].0], "gradient": {"kind": "radial"}})).unwrap();
s.execute("stroke.set", &json!({"ids": [marks[1].0], "weight": 2})).unwrap();
s.execute("paint.setGradientGeom", &json!({"ids": [marks[1].0], "stroke": true, "start": [150, 200], "end": [170, 260]})).unwrap();
let placed = s.doc().unwrap().doc.node(marks[1]).unwrap().appearance.stroke_paint();
s.edit("Kept in document coordinates", |d, _| {
let mut extras = d.node_mut(id).unwrap().extras_mut();
let slot = &mut extras.graph.as_mut().unwrap().series_paints[0];
(slot.stroke, slot.stroke_unit_box, slot.stroke_width) = (Some(placed.clone()), false, Some(2.0));
Ok(())
})
.unwrap();
s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2], [3, 4], [6, 1]]})).unwrap();
let kept = spec(&s, id).series_paints[0].clone();
let undo = s.doc().unwrap().history.undo.len();
let drawn: Vec<_> = series_parts(&s, id, 0).into_iter().filter(|m| m.appearance.stroke_paint() == placed).collect();
assert!(drawn.len() >= 3, "{}", drawn.len());
for mark in drawn {
let row = top_row(&s, mark.id, false);
s.execute("appearance.setItem", &json!({"ids": [mark.id.0], "index": row, "weight": mark.appearance.stroke_width()})).unwrap();
assert_eq!(spec(&s, id).series_paints[0], kept, "writing mark {:?} changed the kept stroke", mark.id);
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
}
}
/// A gradient placed on a line series' stroke is kept relative to the line's stroke box, and with Draw Filled Lines the
/// band, which takes the kept stroke as its fill, has it at the same place on its own box.
#[test]
fn a_gradient_kept_for_a_lines_stroke_takes_the_same_place_on_its_filled_line() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let id = graph(&mut s, "line");
let line = series_parts(&s, id, 0).into_iter().find(|m| m.appearance.fill_paint().is_none()).unwrap().id;
s.execute("paint.setStroke", &json!({"ids": [line.0], "gradient": {"kind": "linear"}})).unwrap();
s.execute("paint.setGradientGeom", &json!({"ids": [line.0], "stroke": true, "start": [150, 120], "end": [300, 280]})).unwrap();
let kept = spec(&s, id).series_paints[0].clone();
assert!(kept.stroke_unit_box && kept.fill.is_none());
let place = gradient_place(kept.stroke.as_ref().unwrap(), vectorcraft_doc::GraphicStyle::UNIT_BOX);
s.execute("graph.setType", &json!({"id": id.0, "filledLines": true})).unwrap();
let band = series_parts(&s, id, 0).into_iter().find(|m| matches!(m.appearance.fill_paint(), Paint::Gradient(_))).unwrap();
let at = gradient_place(&band.appearance.fill_paint(), band.geometric_bounds().unwrap());
assert!(at.iter().zip(&place).all(|(a, b)| (a - b).abs() < 1e-9), "{at:?} is not {place:?}");
}
/// A series' kept unit-box flags are read from and written to a file, and a file without them reads as document
/// coordinates.
#[test]
fn a_series_paints_unit_box_flags_round_trip() {
let kept = vectorcraft_doc::SeriesPaint { fill_unit_box: true, stroke_unit_box: true, ..Default::default() };
let text = serde_json::to_string(&kept).unwrap();
assert_eq!(text, r#"{"fillUnitBox":true,"strokeUnitBox":true}"#);
assert_eq!(serde_json::from_str::<vectorcraft_doc::SeriesPaint>(&text).unwrap(), kept);
let old: vectorcraft_doc::SeriesPaint = serde_json::from_str("{}").unwrap();
assert!(!old.fill_unit_box && !old.stroke_unit_box);
}
/// A series mark's fill recolored with Invert or Complement (the proxy, or one appearance row), an Edit Colors command,
@@ -5932,3 +6443,66 @@ fn graph_commands_refuse_params_of_the_wrong_type() {
s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, null], [2, 3]], "series": null, "transpose": null})).unwrap();
assert_eq!(spec(&s).cells(), vec![vec![Some(1.0), None], vec![Some(2.0), Some(3.0)]]);
}
/// A `.ai` in PostScript form whose graph's records read whole (version 7 specification, appendix A)
/// opens as a graph whose data can be edited: Graph Data redraws it on its plot. Saving it as `.ai`
/// says its data and settings aren't written, in either form.
#[test]
fn a_graph_opened_from_ai_keeps_its_data_for_editing() {
let graph = "%_Gs\n%_100 200 300 100 Gb\n%_5 0 0 14 0 1 0 0 6 44 Gy\n%_10 2 0 0 90 80 0 Gd\n\
%_1 () Ga\n%_0 13 0 0 0 0 0 () GA\n%_2 () Ga\n%_0 14 0 0 0 0 0 () GA\n%_4 () Ga\n%_0 14 0 0 0 0 0 () GA\n\
%_2 2 1 1 Gz\n%_() Gc (East) Gc (Q1) Gc 5 Gc GC\n\
u\nu\n0.6 0 1 0 k\n110 100 m\n110 150 L\n130 150 L\n130 100 L\nf\nU\n%_2 1 0 0 Go\n\
u\n0 0 0 1 K\n100 200 m\n100 100 L\n300 100 L\nS\nU\nU\n%_GS\n";
let text = format!(
"%!PS-Adobe-3.0\n%%Creator: a script\n%%BoundingBox: 0 0 400 400\n%AI5_FileFormat 3\n%AI3_Cropmarks: 0 0 400 400\n%%EndComments\n\
%%BeginProlog\n%%EndProlog\n%%BeginSetup\n%%EndSetup\n%AI5_BeginLayer\n1 1 1 1 0 0 0 79 128 255 Lb\n(Graph) Ln\n0 A\n{graph}LB\n\
%AI5_EndLayer--\n%%PageTrailer\n%%Trailer\n%%EOF\n"
);
let dir = vectorcraft_testkit::temp_dir("graph-ai-open");
let path = dir.join("graph.ai");
std::fs::write(&path, text).unwrap();
let mut s = Session::new();
s.execute("document.open", &json!({"path": path})).unwrap();
let mut found = vec![];
s.doc().unwrap().doc.walk(|n| {
if n.extras().graph.is_some() {
found.push(n.id);
}
});
assert_eq!(found.len(), 1);
let id = found[0];
let before = spec(&s, id);
assert_eq!(
(before.series.as_slice(), before.categories.as_slice(), before.rows.as_slice()),
(&["East".to_string()][..], &["Q1".to_string()][..], &[vec![5.0]][..])
);
// The fill of the series' first mark.
let series_fill = |s: &Session| {
let mut fill = None;
s.doc().unwrap().doc.walk(|n| {
if n.extras().series_index == Some(0) && fill.is_none() {
let first = n.children().and_then(|c| c.first().cloned());
fill = first.and_then(|m| m.appearance.items.iter().find(|i| i.is_fill()).map(|i| i.paint().clone()));
}
});
fill
};
let painted = series_fill(&s);
assert!(painted.is_some());
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "csv": ",East\nQ1,8\nQ2,2"})).unwrap();
let after = spec(&s, id);
assert_eq!(after.rows, [[8.0], [2.0]]);
assert_eq!(after.rect, before.rect, "the graph is redrawn on its plot");
assert_eq!(series_fill(&s), painted, "the series keeps the file's paint");
for (name, version) in [("v7.ai", Some("7")), ("pdf.ai", None)] {
let mut p = json!({"path": dir.join(name), "format": "ai"});
if let Some(v) = version {
p["aiVersion"] = json!(v);
}
let r = s.execute("file.saveAs", &p).unwrap();
let notes = r["warnings"].as_array().cloned().unwrap_or_default();
assert!(notes.iter().any(|w| w.as_str().is_some_and(|w| w.starts_with("graphs are written as their art"))), "{name}: {r}");
}
}
+3 -3
View File
@@ -21,7 +21,7 @@ use vectorcraft_color::{Color, GradientPaint, Paint};
use vectorcraft_doc::{Appearance, Node, NodeId, TextStyleDef};
use super::clipboard::SwatchChoices;
use super::{CommandSpec, EngineError, Result, Session, always, bad, cmd, color_value, has_doc, ids_param, index, ok, point_param, str_param};
use super::{CommandSpec, EngineError, Result, Session, always, bad, cmd, color_value, has_doc, ids_param, index_opt, ok, point_param, str_param};
use crate::Clipboard;
/// The extension of a library file.
@@ -1649,11 +1649,11 @@ fn move_group(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "library.moveGroup";
let id = library_id(s, p, C)?;
let group = group_param(p, C)?;
let to = p.get("to").and_then(Value::as_u64).ok_or_else(|| bad(C, "missing `to` (an index)"))?;
let to = index_opt(p, "to", C)?.ok_or_else(|| bad(C, "missing `to` (an index)"))?;
let (name, at) = s.libraries.change(&id, |lib| {
let i = group_at(lib, group, C)?;
let g = lib.groups.remove(i);
let at = index(to).min(lib.groups.len());
let at = to.min(lib.groups.len());
let name = g.name.clone();
lib.groups.insert(at, g);
Ok((name, at))
+2 -2
View File
@@ -96,7 +96,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
"Invert",
[],
None,
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke (docs/mcp.md) → {changed}",
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke (docs/mcp.md); no undo step when no color changes → {changed}",
has_doc,
|s, p| proxy_recolor(s, p, "paint.invert", "Invert", &super::colorcmds::invert)
),
@@ -105,7 +105,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
"Complement",
[],
None,
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} replace the active proxy's colours by their complements ((highest + lowest) − each component, over RGB or CMY; grey unchanged) keeping each colour's model; honours the Appearance panel's active item and a selected object of a dynamic symbol instance as paint.invert does; with nothing selected, the default → {changed}",
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} replace the active proxy's colours by their complements ((highest + lowest) − each component, over RGB or CMY; grey unchanged) keeping each colour's model; honours the Appearance panel's active item and a selected object of a dynamic symbol instance as paint.invert does; with nothing selected, the default; no undo step when no color changes → {changed}",
has_doc,
|s, p| proxy_recolor(s, p, "paint.complement", "Complement", &|c: Color| c.complement_keep_model())
),
+1 -1
View File
@@ -88,7 +88,7 @@ pub fn specs() -> Vec<CommandSpec> {
fn artboard_reorder(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "artboard.reorder";
let i = artboard_index(&s.doc()?.doc, p, C)?;
let to = p.get("to").and_then(Value::as_u64).map(index).ok_or_else(|| bad(C, "missing to"))?;
let to = super::index_opt(p, "to", C)?.ok_or_else(|| bad(C, "missing to"))?;
s.edit("Reorder Artboards", |d, _| {
if i >= d.artboards.len() {
return Err(EngineError::Other("no such artboard".into()));
+26 -5
View File
@@ -10,7 +10,7 @@
//! save or Export for Screens: those are checked against the options of the formats the command
//! can write, in `marks`, `bleed` and the other objects too ([`check_export_options`]); and in the
//! objects of an array whose keys `MEMBER_KEYS` lists, such as the `items` of
//! `object.setLiveShape`.
//! `object.setLiveShape` and `addon.pathtools.cornerSet`.
//!
//! [`Session::execute`] answers a key the description doesn't name with a parameter error
//! ([`check_params`]), for every caller (the app, the control channel, MCP, the CLI) and for the
@@ -256,6 +256,22 @@ pub fn check_keys(id: &str, doc: &'static str, params: &Value) -> Result<()> {
}
}
/// Parameters a command takes instead of one another: (command, key, other key). Giving both,
/// neither null, is a parameter error ([`check_exclusive_keys`]).
const EXCLUSIVE_KEYS: &[(&str, &str, &str)] = &[("addon.pathtools.cornerSet", "items", "ids"), ("addon.pathtools.cornerRemove", "items", "ids")];
/// `params` of command `id` give at most one of each pair in [`EXCLUSIVE_KEYS`], or the parameter
/// error naming the pair.
fn check_exclusive_keys(id: &str, params: &Value) -> Result<()> {
let given = |key: &str| params.get(key).filter(|v| !v.is_null());
for (_, key, other) in EXCLUSIVE_KEYS.iter().filter(|(c, ..)| *c == id) {
if given(key).is_some() && given(other).is_some() {
return Err(bad(id, format!("give `{key}` or `{other}`, not both")));
}
}
Ok(())
}
/// The parameter error of command `id` for `key`, which isn't one of `keys`: with the nearest of
/// them, or all of them.
pub(crate) fn unknown(id: &str, key: &str, keys: &[&str]) -> crate::EngineError {
@@ -273,7 +289,11 @@ pub(crate) fn unknown(id: &str, key: &str, keys: &[&str]) -> crate::EngineError
/// Commands whose params hold an array of objects with keys of their own: the command, the key of
/// the array and the keys each of its objects takes.
const MEMBER_KEYS: &[(&str, &str, &[&str])] = &[("object.setLiveShape", "items", &["id", "corners"])];
const MEMBER_KEYS: &[(&str, &str, &[&str])] = &[
("object.setLiveShape", "items", &["id", "corners"]),
("addon.pathtools.cornerSet", "items", &["id", "anchors"]),
("addon.pathtools.cornerRemove", "items", &["id", "anchors"]),
];
/// Each object in the arrays [`MEMBER_KEYS`] names for command `id` has only the keys it lists, or
/// the parameter error naming the first other one with its place (`items[0].corner`), and the
@@ -848,9 +868,9 @@ fn check_export_options(id: &str, params: &Value) -> Result<()> {
check_option_keys(id, "", given, &keys, why_not, &trees)
}
/// [`check_keys`] for an engine command, the steps of a `command.batch` or an `action.batch` included,
/// [`check_effect_params`] for the effect `effect.apply` adds and [`check_export_options`] for an
/// export. A command the engine doesn't have passes: running it reports that.
/// [`check_keys`], [`check_exclusive_keys`] and [`check_member_keys`] for an engine command, the steps of a `command.batch` or an
/// `action.batch` included, [`check_effect_params`] for the effect `effect.apply` adds and
/// [`check_export_options`] for an export. A command the engine doesn't have passes: running it reports that.
pub fn check_params(id: &str, params: &Value) -> Result<()> {
check_params_in(id, params, false)
}
@@ -869,6 +889,7 @@ fn check_params_in(id: &str, params: &Value, in_batch: bool) -> Result<()> {
return Ok(());
}
check_keys(id, spec.params, params)?;
check_exclusive_keys(id, params)?;
check_member_keys(id, params)?;
if in_batch {
crate::schemas::check(spec, params, false)?;
+32 -7
View File
@@ -12,7 +12,7 @@ use super::draw2::usize_opt;
use super::pathops::Beside;
use super::{
CommandSpec, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, f64_req, finite_numbers, has_anchors, has_doc, has_selected_path,
has_selection, ids_param, index, number_or, object_param, ok, str_param, switch_or, targets,
has_selection, ids_param, index_opt, number_or, object_param, ok, str_param, switch_or, targets,
};
use crate::EngineError;
@@ -170,7 +170,7 @@ pub(super) fn path_mut(d: &mut vectorcraft_doc::Document, id: NodeId) -> Result<
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")?;
let subpath = p.get("subpath").and_then(Value::as_u64).map(|u| u as usize);
let subpath = index_opt(p, "subpath", "path.appendAnchor")?;
s.edit("Pen", |d, sel| {
let path = path_mut(d, id)?;
let si = match subpath {
@@ -208,7 +208,7 @@ fn append_anchor(s: &mut Session, p: &Value) -> Result<Value> {
/// `at` first moves the anchor, its handles with it (the Pen's closing drag with Space held).
fn close(s: &mut Session, p: &Value) -> Result<Value> {
let id = object_param(p, "id", "path.close")?.ok_or_else(|| bad("path.close", "missing id"))?;
let subpath = p.get("subpath").and_then(Value::as_u64).map(|u| u as usize);
let subpath = index_opt(p, "subpath", "path.close")?;
let handle = |key: &str| match p.get(key).filter(|h| !h.is_null()) {
None => Ok(None),
Some(h) => finite_numbers(h).map(|[x, y]| Some(Point::new(x, y))).ok_or_else(|| bad("path.close", format!("`{key}` must be [x, y]"))),
@@ -310,10 +310,19 @@ pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_ge
fn set_handle(s: &mut Session, p: &Value) -> Result<Value> {
let id = object_param(p, "id", "path.setHandle")?.ok_or_else(|| bad("path.setHandle", "missing id"))?;
let si = usize_opt(p, "subpath", "path.setHandle")?.unwrap_or(0);
let ai = p.get("anchor").and_then(Value::as_u64).map(index).ok_or_else(|| bad("path.setHandle", "missing anchor"))?;
let ai = index_opt(p, "anchor", "path.setHandle")?.ok_or_else(|| bad("path.setHandle", "missing anchor"))?;
let out = str_param(p, "which") != Some("in");
let pos = Point::new(f64_req(p, "x", "path.setHandle")?, f64_req(p, "y", "path.setHandle")?);
let independent = switch_or(p, "independent", false, "path.setHandle")?;
// A handle already there, on an anchor already of the kind it would get, changes nothing and
// records no undo step.
if let Some(a) = anchor_of(s, id, si, ai)? {
let mut b = a;
b.set_handle(out, pos, independent);
if b == a {
return ok();
}
}
s.edit("Reshape", |d, _| {
let path = path_mut(d, id)?;
let a = path.anchor_mut(si, ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
@@ -328,8 +337,14 @@ fn set_handle(s: &mut Session, p: &Value) -> Result<Value> {
fn move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
let id = object_param(p, "id", "path.moveAnchor")?.ok_or_else(|| bad("path.moveAnchor", "missing id"))?;
let si = usize_opt(p, "subpath", "path.moveAnchor")?.unwrap_or(0);
let ai = p.get("anchor").and_then(Value::as_u64).map(index).ok_or_else(|| bad("path.moveAnchor", "missing anchor"))?;
let ai = index_opt(p, "anchor", "path.moveAnchor")?.ok_or_else(|| bad("path.moveAnchor", "missing anchor"))?;
let pos = Point::new(f64_req(p, "x", "path.moveAnchor")?, f64_req(p, "y", "path.moveAnchor")?);
// An anchor already at (x, y) changes nothing and records no undo step.
if let Some(a) = anchor_of(s, id, si, ai)?
&& a.transform(vectorcraft_geom::Affine::translate(pos - a.p)) == a
{
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()))?;
@@ -345,6 +360,16 @@ fn move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
ok()
}
/// Anchor `ai` of subpath `si` of path `id` in the active document, when `id` is a path that has it.
/// Busy while a script runs, as [`Session::edit`] is.
fn anchor_of(s: &Session, id: NodeId, si: usize, ai: usize) -> Result<Option<Anchor>> {
if s.script_running() {
return Err(EngineError::Busy);
}
let d = &s.doc()?.doc;
Ok(d.node(id).and_then(|n| n.path_data()).and_then(|path| path.subpaths.get(si)).and_then(|sp| sp.anchors.get(ai)).copied())
}
fn set_anchors(s: &mut Session, p: &Value) -> Result<Value> {
let id = object_param(p, "id", "path.setAnchors")?.ok_or_else(|| bad("path.setAnchors", "missing id"))?;
let subs = p.get("subpaths").and_then(Value::as_array).ok_or_else(|| bad("path.setAnchors", "missing subpaths"))?;
@@ -428,7 +453,7 @@ pub(super) fn paths_in(d: &vectorcraft_doc::Document, ids: &[NodeId]) -> Vec<Nod
fn reverse(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "path.reverse";
let want = p.get("reversed").map(|v| v.as_bool().ok_or_else(|| bad(C, "`reversed` must be true or false"))).transpose()?;
let subpath = p.get("subpath").and_then(Value::as_u64).map(|u| u as usize);
let subpath = index_opt(p, "subpath", C)?;
let ids = paths_in(&s.doc()?.doc, &targets(s, p)?);
if ids.is_empty() {
return Err(bad(C, "select paths"));
@@ -1759,7 +1784,7 @@ fn reshape(s: &mut Session, p: &Value) -> Result<Value> {
fn insert_anchor(s: &mut Session, p: &Value) -> Result<Value> {
let id = object_param(p, "id", "path.insertAnchor")?.ok_or_else(|| bad("path.insertAnchor", "missing id"))?;
let si = usize_opt(p, "subpath", "path.insertAnchor")?.unwrap_or(0);
let seg = p.get("segment").and_then(Value::as_u64).map(index).ok_or_else(|| bad("path.insertAnchor", "missing segment"))?;
let seg = index_opt(p, "segment", "path.insertAnchor")?.ok_or_else(|| bad("path.insertAnchor", "missing segment"))?;
let t = number_or(p, "t", 0.5, "path.insertAnchor")?.clamp(0.0, 1.0);
let idx = s.edit("Add Anchor Point", |d, sel| {
let path = path_mut(d, id)?;
+1 -1
View File
@@ -962,7 +962,7 @@ pub(crate) fn ordered_map<T: Sync, R: Send>(
// ---------- Outline Stroke ----------
/// Can Outline Stroke turn `st` into filled art?
fn outlinable(st: &StrokeLayer) -> bool {
pub(crate) fn outlinable(st: &StrokeLayer) -> bool {
st.visible && !st.paint.is_none() && st.width > 0.0
}
+21 -13
View File
@@ -793,7 +793,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export Preferences",
[],
None,
"{path?} write the preferences as a JSON file {format: \"vectorcraft-preferences\", version: 1, prefs: {key: value, …}}: every preference prefs.list lists and the eyedropper, perspectiveWidget, pathfinder, glyphSnap and pixelSnap groups, without the folder preferences fontsFolder, pluginsFolder, recoveryFolder and templatesFolder and without saved presets; a file over 1 MB, which prefs.import would refuse, is an error and is not written → {path, count}; without path → {data: the file's text, count}",
"{path?} write the preferences as a JSON file {format: \"vectorcraft-preferences\", version: 1, prefs: {key: value, …}}: every preference prefs.list lists and the eyedropper, perspectiveWidget, pathfinder, glyphSnap and pixelSnap groups, without the folder preferences fontsFolder, pluginsFolder, scratchPrimary, scratchSecondary, recoveryFolder and templatesFolder and without saved presets; a file over 1 MB, which prefs.import would refuse, is an error and is not written → {path, count}; without path → {data: the file's text, count}",
always,
export
),
@@ -802,7 +802,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Import Preferences",
[],
None,
"{path? | data?: the file's text} apply the preferences of a file prefs.export wrote (at most 1 MB). Every value is checked first, as prefs.set checks it: another format, a newer version, an unknown preference, a value of the wrong type or out of range, or a folder preference is an error, and nothing changes. Preferences the file leaves out keep their values; the open document's units stay as they are; no undo step; not a command.batch step → {imported: count}",
"{path? | data?: the file's text} apply the preferences of a file prefs.export wrote (at most 1 MB). Every value is checked first, as prefs.set checks it: another format, a newer version, an unknown preference, a value of the wrong type or out of range, or a folder preference (for scratchPrimary and scratchSecondary, a folder; the choices Startup and None are read) is an error, and nothing changes. Preferences the file leaves out keep their values; the open document's units stay as they are; no undo step; not a command.batch step → {imported: count}",
always,
import
),
@@ -818,8 +818,20 @@ pub const PREFS_VERSION: u64 = 1;
/// The largest preferences file `prefs.import` reads.
const MAX_PREFS_FILE_BYTES: usize = 1 << 20;
/// Folder preferences, which name folders on one computer: a preferences file leaves them out.
const FOLDER_PREFS: &[&str] = &["fontsFolder", "pluginsFolder", "recoveryFolder", "templatesFolder"];
/// Folder preferences, which name folders on one computer: a preferences file leaves them out, and
/// under automation read roots one outside them is not shown.
pub const FOLDER_PREFS: [&str; 6] = ["fontsFolder", "pluginsFolder", "scratchPrimary", "scratchSecondary", "recoveryFolder", "templatesFolder"];
/// The scratch disk choices that are not folders.
pub const SCRATCH_CHOICES: [&str; 2] = ["Startup", "None"];
/// Does `value`, set as preference `key`, name a folder: is `key` a folder preference
/// ([`FOLDER_PREFS`]) and `value`, trimmed as the app uses it, neither empty (the default folder)
/// nor a scratch disk choice ([`SCRATCH_CHOICES`])?
pub fn names_a_folder(key: &str, value: &str) -> bool {
let path = value.trim();
FOLDER_PREFS.contains(&key) && !path.is_empty() && !(key.starts_with("scratch") && SCRATCH_CHOICES.contains(&path))
}
/// The preferences `prefs.export` writes: every [`PREF_SPECS`] key but the [`FOLDER_PREFS`], and
/// the [`PREF_GROUPS`].
@@ -868,7 +880,9 @@ fn read_prefs_file(bytes: &[u8]) -> std::result::Result<Map<String, Value>, Stri
if prefs.is_empty() {
return Err("the file holds no preferences".into());
}
if let Some(key) = prefs.keys().find(|k| FOLDER_PREFS.contains(&k.as_str())) {
// A scratch disk choice or an empty scratch disk names no folder, and is read.
let folder = |k: &str, v: &Value| FOLDER_PREFS.contains(&k) && (!k.starts_with("scratch") || v.as_str().is_some_and(|v| names_a_folder(k, v)));
if let Some(key) = prefs.iter().find(|(k, v)| folder(k, v)).map(|(k, _)| k) {
return Err(format!("`{key}` names a folder, which preferences files leave out"));
}
Ok(prefs.clone())
@@ -893,14 +907,8 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "imported": values.len() }))
}
/// The preferences that name a folder: the [`FOLDER_PREFS`] and the scratch disks.
const PATH_PREFS: [&str; 6] = ["fontsFolder", "pluginsFolder", "scratchPrimary", "scratchSecondary", "recoveryFolder", "templatesFolder"];
/// The scratch disk choices that are not folders.
const SCRATCH_CHOICES: [&str; 2] = ["Startup", "None"];
/// The preferences as `prefs.get`, `prefs.list`, `prefs.set` and `prefs.reset` show them to the
/// request being served. Under automation read roots, a folder preference ([`PATH_PREFS`]) outside
/// request being served. Under automation read roots, a folder preference ([`FOLDER_PREFS`]) outside
/// them is `null`, as `ui.inspect` leaves it out, and an export preset's `folder` outside them is
/// left out. An empty value (the default folder) and a scratch
/// disk choice ([`SCRATCH_CHOICES`]) are shown. Without roots the preferences are shown as they are.
@@ -911,7 +919,7 @@ fn shown_prefs(prefs: &Prefs) -> Value {
}
// The app trims a folder before it uses it.
let hidden = |path: &str| !path.trim().is_empty() && crate::file_access::check_read(path.trim()).is_err();
for key in PATH_PREFS {
for key in FOLDER_PREFS {
let Some(path) = all[key].as_str() else { continue };
if hidden(path) && !(key.starts_with("scratch") && SCRATCH_CHOICES.contains(&path.trim())) {
all[key] = Value::Null;
+8 -5
View File
@@ -15,7 +15,7 @@ use vectorcraft_doc::swatches::{node_colors, node_paints, override_paints};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use vectorcraft_geom::{Point, Rect};
use super::colorcmds::{NotChanged, Recolor, Scope, keeping_series_paint, left_out};
use super::colorcmds::{NotChanged, Recolor, Scope, edit_if_changed, keeping_series_paint, left_out};
use super::{CommandSpec, Result, Session, always, bad, checked_ids_param, cmd, color_value, has_doc, index, str_param, switch_or, text_param};
pub fn specs() -> Vec<CommandSpec> {
@@ -34,7 +34,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Recolor Artwork",
["Edit", "Edit Colors"],
None,
"{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex)], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour] (what `group` is rewritten with; default: the rows' new colours, in order, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step. On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}",
"{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex)], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour] (what `group` is rewritten with; default: the rows' new colours, in order, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}",
has_doc,
apply
),
@@ -1661,7 +1661,7 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
};
let rename = text_param(p, "rename", C)?;
let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok();
let (changed, edit, added, converted, not_changed) = s.edit(label, |d, _| {
let (changed, edit, added, converted, not_changed) = edit_if_changed(s, label, |now, d| {
// The rows' library swatches join the document (one it has with that name and colour is
// used as it is).
let mut added = vec![];
@@ -1716,12 +1716,15 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
let not_changed = NotChanged::of(
before.iter().filter(|(id, colors, _)| d.node(*id).is_some_and(|now| shown_colors(d, now) == *colors)).map(|(_, _, hidden)| *hidden),
);
Ok((changed, edit, added, map.converted.get(), not_changed))
// Rewriting the group's swatches and relinking its art are not counted in `changed`, so a
// pass that counts nothing compares the documents.
let any = changed > 0 || !added.is_empty() || *d != *now;
Ok(((changed, edit, added, map.converted.get(), not_changed), any))
})?;
let mut out = json!({ "changed": changed, "swatches": added });
not_changed.report(&mut out);
if let Some(e) = edit {
e.defaults(s);
e.defaults(s)?;
out["relinked"] = json!(e.relinked());
}
if converted {
+1
View File
@@ -1176,6 +1176,7 @@ pub fn jobs(s: &mut Session, store: &Arc<dyn RecoveryStore>) -> Result<(Vec<Reco
modified: None,
notes: Vec::new(),
lossy_source: None,
kept: serde_json::Map::new(),
};
let save = fileio::job_for(s, st, plan)?;
let meta = Meta {
File diff suppressed because one or more lines are too long
+4 -4
View File
@@ -21,7 +21,7 @@ use vectorcraft_color::Paint;
use vectorcraft_doc::{Appearance, DEFAULT_GRAPHIC_STYLE, Document, GraphicStyle, Node, NodeId, NodeKind, Shared};
use vectorcraft_geom::Rect;
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, index, object_param, ok, str_param, unique_name};
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, index_opt, object_param, ok, str_param, unique_name};
use crate::EngineError;
pub fn specs() -> Vec<CommandSpec> {
@@ -332,7 +332,7 @@ fn style_apply(s: &mut Session, p: &Value) -> Result<Value> {
let i = style_index(&s.doc()?.doc, name)?;
let add = bool_or(p, "add", false);
let chars = s.prefs.override_char_color;
let own = super::appearance::appearance_targets(s, p)?;
let own = super::appearance::edit_targets(s, p)?;
let ids = super::appearance::rowless_series_marks(&s.doc()?.doc, &own);
// The series groups their paths stand for: a style that replaces the appearance clears what they hold themselves,
// and a style added on top unlinks them.
@@ -585,10 +585,10 @@ fn style_merge(s: &mut Session, p: &Value) -> Result<Value> {
fn style_move(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "graphicStyle.move";
let name = str_param(p, "name").ok_or_else(|| bad(cmd, "missing name"))?;
let to = p.get("to").and_then(Value::as_u64).ok_or_else(|| bad(cmd, "missing `to` (an index)"))?;
let to = index_opt(p, "to", cmd)?.ok_or_else(|| bad(cmd, "missing `to` (an index)"))?;
let d = &s.doc()?.doc;
let from = style_index(d, name)?;
let to = index(to).min(d.graphic_styles.len() - 1);
let to = to.min(d.graphic_styles.len() - 1);
if from == to {
return ok();
}
+6 -4
View File
@@ -161,11 +161,13 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "graphicStyle.addFromLibrary";
let (info, lib) = library_param(s, p, C)?;
let (apply, add) = (switch_or(p, "apply", false, C)?, switch_or(p, "add", false, C)?);
if p.get("ids").is_some_and(|v| !v.is_null()) {
let ids_given = p.get("ids").is_some_and(|v| !v.is_null());
if ids_given {
checked_ids_param(s, p, "ids", C)?;
} else if apply {
// A selection that can't take a style is refused before any style is added.
super::appearance::appearance_targets(s, &json!({}))?;
}
if apply {
// Objects that can't take a style are refused before any style is added.
super::appearance::edit_targets(s, &if ids_given { json!({"ids": p["ids"]}) } else { json!({}) })?;
}
let mut names = names_param(p, C)?;
names.extend(text_param(p, "name", C)?.map(str::to_string));
+40 -16
View File
@@ -322,7 +322,7 @@ fn swatch_delete(s: &mut Session, p: &Value) -> Result<Value> {
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))?;
Ok(unlinked)
})?;
map_default_paints(s, &mut unlink);
map_default_paints(s, &mut unlink)?;
Ok(json!({"deleted": names, "unlinked": unlinked}))
}
@@ -660,20 +660,41 @@ impl Relink {
renamed || recolored
}
fn defaults(&self, s: &mut Session) {
map_default_paints(s, &mut |c, l, t| self.apply(c, l, t));
fn defaults(&self, s: &mut Session) -> Result<()> {
map_default_paints(s, &mut |c, l, t| self.apply(c, l, t))
}
}
/// Apply a swatch-link rewrite to the default fill and stroke for new art, except during a live
/// preview (Cancel rolls the document back, not the session).
pub(super) fn map_default_paints(s: &mut Session, f: &mut LinkFn) {
if s.in_interaction() {
return;
/// Apply a swatch-link rewrite to the fill and stroke new art takes and to the paints of its
/// template appearance, except during a live preview (Cancel rolls the document back, not the
/// session). A `command.batch` step rewrites them as the command run on its own does: a failed
/// batch, and a canceled batch preview, put back the paints the batch started with. A change is
/// recorded with the step just made, so Undo and Redo put these paints back with the document.
pub(super) fn map_default_paints(s: &mut Session, f: &mut LinkFn) -> Result<()> {
if s.in_interaction() && s.batch_stash.is_none() {
return Ok(());
}
for p in [&mut s.paint.fill, &mut s.paint.stroke] {
p.map_links(f);
let start = super::colormgmt::new_art_colors_before(s)?;
let pd = &mut s.paint;
let template = pd.appearance.iter_mut().flat_map(|a| a.items.iter_mut()).map(|it| match it {
vectorcraft_doc::AppearanceItem::Fill(f) => &mut f.paint,
vectorcraft_doc::AppearanceItem::Stroke(s) => &mut s.paint,
});
let mut changed = false;
for p in [&mut pd.fill, &mut pd.stroke].into_iter().chain(template) {
changed |= p.map_links(f);
}
if changed {
super::colormgmt::record_new_art_colors(s, start)?;
// The step takes the paints the command finally leaves, after the selection's appearance
// is inherited.
let st = s.doc()?;
if st.interaction.is_none() {
let uid = st.uid;
s.batch_paint_docs.push(uid);
}
}
Ok(())
}
/// Apply a swatch-link rewrite to the document ([`Document::map_solid_paints`]) and to the art of
@@ -888,7 +909,7 @@ fn swatch_edit(s: &mut Session, p: &Value) -> Result<Value> {
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))?;
Ok(relinked)
})?;
relink.defaults(s);
relink.defaults(s)?;
Ok(json!({"name": to, "relinked": relinked}))
}
@@ -1084,7 +1105,7 @@ fn swatch_merge(s: &mut Session, p: &Value) -> Result<Value> {
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))?;
Ok(relinked)
})?;
map_default_paints(s, &mut relink);
map_default_paints(s, &mut relink)?;
Ok(json!({"name": keep, "merged": merged, "relinked": relinked}))
}
@@ -1141,7 +1162,7 @@ fn swatch_spot_options(s: &mut Session, p: &Value) -> Result<Value> {
let relinked = map_swatch_links(d, &mut follow_bases(&bases));
Ok((relinked, bases))
})?;
map_default_paints(s, &mut follow_bases(&bases));
map_default_paints(s, &mut follow_bases(&bases))?;
Ok(json!({"useLab": use_lab, "relinked": relinked}))
}
@@ -1165,8 +1186,11 @@ pub(super) struct GroupEdit {
impl GroupEdit {
/// Apply the link changes to the default fill and stroke for new art.
pub(super) fn defaults(&self, s: &mut Session) {
self.relinks.iter().for_each(|r| r.defaults(s));
pub(super) fn defaults(&self, s: &mut Session) -> Result<()> {
if self.relinks.is_empty() {
return Ok(());
}
map_default_paints(s, &mut |c, l, t| self.relinks.iter().any(|r| r.apply(c, l, t)))
}
/// How many paints linked to the group's swatches the rewrite changed.
@@ -1242,6 +1266,6 @@ fn swatch_edit_group(s: &mut Session, p: &Value) -> Result<Value> {
colors.into_iter().enumerate().map(|(i, c)| if old.get(i) == Some(&Some(c)) { c } else { super::paint::new_color(s, p, c) }).collect();
let rename = str_param(p, "rename");
let e = s.edit("Edit Color Group", |d, _| rewrite_group(d, group, &colors, rename, C))?;
e.defaults(s);
e.defaults(s)?;
Ok(json!({"name": e.name, "swatches": e.swatches, "relinked": e.relinked}))
}
+1 -1
View File
@@ -980,7 +980,7 @@ fn reset_defaults(s: &mut Session, p: &Value) -> Result<Value> {
Ok(added)
})?;
if replace {
map_default_paints(s, &mut |_, l, _| unlink_dead(&live, l));
map_default_paints(s, &mut |_, l, _| unlink_dead(&live, l))?;
}
Ok(json!({ "added": added }))
}
+34 -3
View File
@@ -17,7 +17,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Make",
["Object", "Text Wrap"],
None,
"{offset?: pt (6), invert?: bool, ids?} area type below the selected objects (same layer) wraps around them → {ids}",
"{offset?: pt (6), invert?: bool, ids?} area type below the selected objects (same layer) wraps around them; a negative offset (to -1000) lets the text that far into them → {ids}",
has_selection,
make
),
@@ -27,15 +27,19 @@ pub fn specs() -> Vec<CommandSpec> {
"Text Wrap Options…",
["Object", "Text Wrap"],
None,
"{offset?: pt, invert?: bool, ids?} set the options of the selected wrap objects; no options → the current {offset, invert}",
"{offset?: pt, invert?: bool, ids?} set the options of the selected wrap objects (offset -1000 to 1000; a negative one lets text into the objects); no options → the current {offset, invert}",
has_selection,
options
),
]
}
/// The Offset a wrap object takes, in points.
pub const TEXT_WRAP_OFFSET_RANGE: std::ops::RangeInclusive<f64> = -1000.0..=1000.0;
fn wrap_param(p: &Value, base: TextWrap) -> TextWrap {
TextWrap { offset: f64_or(p, "offset", base.offset).clamp(-1000.0, 1000.0), invert: bool_or(p, "invert", base.invert) }
let (lo, hi) = (*TEXT_WRAP_OFFSET_RANGE.start(), *TEXT_WRAP_OFFSET_RANGE.end());
TextWrap { offset: f64_or(p, "offset", base.offset).clamp(lo, hi), invert: bool_or(p, "invert", base.invert) }
}
fn make(s: &mut Session, p: &Value) -> Result<Value> {
@@ -186,6 +190,33 @@ mod tests {
assert_eq!(lines(&s, t), plain);
}
/// A negative offset from Text Wrap Options lets the lines beside a wrap object run that far
/// into it, the options report it, and one undo puts back the offset before it.
#[test]
fn text_wrap_options_negative_offset_reflows_and_round_trips() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
let t = s
.execute("text.create", &json!({"x": 0, "y": 0, "text": "word ".repeat(200), "size": 12, "area": {"width": 400, "height": 400}}))
.unwrap()["id"]
.as_u64()
.unwrap();
let r = s.execute("shape.rectangle", &json!({"x": -50, "y": 50, "width": 250, "height": 100})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [r]})).unwrap();
s.execute("object.textWrap.make", &json!({})).unwrap();
let beside = |s: &Session| lines(s, t).into_iter().filter(|l| l.0 > 1.0).map(|l| l.0).collect::<Vec<_>>();
assert!(!beside(&s).is_empty() && beside(&s).iter().all(|x| (x - 206.0).abs() < 1e-6), "{:?}", beside(&s));
assert_eq!(s.execute("object.textWrap.options", &json!({"offset": -20})).unwrap()["offset"], json!(-20.0));
assert!(!beside(&s).is_empty() && beside(&s).iter().all(|x| (x - 180.0).abs() < 1e-6), "{:?}", beside(&s));
assert_eq!(s.execute("object.textWrap.options", &json!({})).unwrap()["offset"], json!(-20.0));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.execute("object.textWrap.options", &json!({})).unwrap()["offset"], json!(6.0));
assert!(beside(&s).iter().all(|x| (x - 206.0).abs() < 1e-6), "{:?}", beside(&s));
// An offset past -1000 is kept at -1000: the whole object lets text through.
assert_eq!(s.execute("object.textWrap.options", &json!({"offset": -5000})).unwrap()["offset"], json!(-1000.0));
assert!(lines(&s, t).iter().all(|l| l.0 < 1.0 && l.1 > 300.0));
}
#[test]
fn text_flows_on_both_sides_of_a_centred_object() {
let mut s = Session::new();
+47
View File
@@ -395,9 +395,25 @@ pub(crate) fn mark_continued(doc: &mut Document) {
}
}
#[cfg(test)]
thread_local! {
/// Tests: how many times [`story_of`] and [`ThreadIndex::of`] went through the document's
/// threads on this thread.
static THREAD_SCANS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Tests: how many times [`story_of`] and [`ThreadIndex::of`] have gone through the document's
/// threads on this thread.
#[cfg(test)]
pub(crate) fn thread_scans() -> usize {
THREAD_SCANS.with(std::cell::Cell::get)
}
/// The frames of the thread that `id` is a frame of, in thread order, each area type or type on a
/// path; empty when `id` is in no thread or the thread has fewer than two such frames.
pub(crate) fn story_of(d: &Document, id: NodeId) -> Vec<NodeId> {
#[cfg(test)]
THREAD_SCANS.with(|c| c.set(c.get() + 1));
let Some(thread) = d.text_threads.iter().find(|t| t.contains(&id)) else { return vec![] };
story_in(d, thread, id)
}
@@ -408,6 +424,37 @@ pub(crate) fn story_in(d: &Document, thread: &[NodeId], id: NodeId) -> Vec<NodeI
if frames.len() >= 2 && frames.contains(&id) { frames } else { vec![] }
}
/// A document's text threads looked up by frame, built in one pass over them, for a command that
/// asks [`ThreadIndex::threaded`] of each of many objects.
pub(crate) struct ThreadIndex<'a> {
doc: &'a Document,
/// Each object the threads list, with the index of the first thread that lists it.
first: std::collections::HashMap<NodeId, usize>,
/// Each thread's count of entries that are area type or type on a path.
live: Vec<usize>,
}
impl<'a> ThreadIndex<'a> {
pub(crate) fn of(doc: &'a Document) -> Self {
#[cfg(test)]
THREAD_SCANS.with(|c| c.set(c.get() + 1));
let mut first = std::collections::HashMap::new();
let mut live = Vec::with_capacity(doc.text_threads.len());
for (i, thread) in doc.text_threads.iter().enumerate() {
for id in thread {
first.entry(*id).or_insert(i);
}
live.push(thread.iter().filter(|id| text_of(doc, **id).is_some()).count());
}
Self { doc, first, live }
}
/// Whether `id` is a frame of a thread: [`story_of`] is not empty for it.
pub(crate) fn threaded(&self, id: NodeId) -> bool {
self.first.get(&id).and_then(|i| self.live.get(*i)).is_some_and(|n| *n >= 2) && text_of(self.doc, id).is_some()
}
}
/// `ids` followed by the other frames of the threads they are in, each once, in thread order.
pub(crate) fn with_threads(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
let given: Ids = ids.iter().copied().collect();
+22
View File
@@ -245,6 +245,28 @@ fn a_frame_left_alone_by_a_dropped_repeat_stops_continuing() {
assert_eq!(t.plain_text(), "Tail");
}
/// [`ThreadIndex::threaded`] answers as [`story_of`] does, by the first thread that lists an
/// object, also for threads listed more than once, with point type, other art and missing ids.
#[test]
fn thread_index_matches_story_of() {
let (mut s, a, b) = setup();
s.execute("text.thread.create", &json!({})).unwrap();
let c = s.execute("text.create", &json!({"x": 400, "y": 10, "text": "C", "area": {"width": 150, "height": 60}})).unwrap()["id"].as_u64().unwrap();
let p = s.execute("text.create", &json!({"x": 10, "y": 250, "text": "Point"})).unwrap()["id"].as_u64().unwrap();
let r = s.execute("shape.rectangle", &json!({"x": 400, "y": 200, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap();
let mut d = (*s.doc().unwrap().doc).clone();
let [fa, fb, fc, fp, fr, fx] = [a, b, c, p, r, 9_999_999].map(NodeId);
// a's first thread has one frame beside point type, c's has one beside a rectangle, and b's
// lists a twice.
d.text_threads = vec![vec![fp, fa], vec![fa, fb, fa], vec![fc, fr], vec![fc, fb], vec![fx, fb]];
let index = ThreadIndex::of(&d);
let got: Vec<(bool, bool)> = [fa, fb, fc, fp, fr, fx].iter().map(|id| (index.threaded(*id), !story_of(&d, *id).is_empty())).collect();
let want: Vec<(bool, bool)> = [false, true, false, false, false, false].iter().map(|t| (*t, *t)).collect();
assert_eq!(got, want);
d.text_threads.clear();
assert!(!ThreadIndex::of(&d).threaded(fb));
}
#[test]
fn edits_copy_only_the_stories_of_threads_whose_frames_changed() {
let (mut s, a, b) = setup();
+35 -7
View File
@@ -4,14 +4,16 @@
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{AreaFit, Document, Justify, Node, NodeId, NodeKind, RubyAlign, RubyPosition, RubySpan, TextObject};
use vectorcraft_doc::{
Appearance, AppearanceItem, AreaFit, Document, Justify, Node, NodeId, NodeKind, RubyAlign, RubyPosition, RubySpan, TextObject,
};
use vectorcraft_geom::{Affine, PathData, Vec2};
use super::edit::selected_roots;
use super::pathops::{length_given, number_given, shape_node};
use super::{
CommandSpec, EngineError, Result, Session, bad, check_numbers, cmd, color_value, f64_req, has_doc, has_selection, index, number_or, object_param,
ok, str_param, switch_or, targets, text_param,
CommandSpec, EngineError, Result, Session, bad, check_numbers, cmd, color_value, f64_req, has_doc, has_selection, index, index_opt, number_or,
object_param, ok, str_param, switch_or, targets, text_param,
};
pub fn specs() -> Vec<CommandSpec> {
@@ -39,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Create Outlines",
["Type"],
Some("Cmd+Shift+O"),
"{} convert the selected text to groups of compound paths (one per glyph); a frame of threaded text leaves its thread with the text it shows; a dimension whose label is outlined becomes a plain group of its art → {ids}",
"{} convert the selected text to groups of compound paths (one per glyph); the type object's own fills and strokes (not its characters') go on paths of its whole outline, below or above the glyphs as its Characters row places them; a frame of threaded text leaves its thread with the text it shows; a dimension whose label is outlined becomes a plain group of its art → {ids}",
has_selection,
create_outlines
),
@@ -672,13 +674,39 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> {
}
placed.extend(ruby.map(|(_, r)| r));
let mut children = placed;
// The whole outline the object's own fills and strokes paint: every glyph, ruby glyph
// and bar, as the canvas paints them.
let mut all = kurbo::BezPath::new();
for g in lay.glyphs.iter().chain(&lay.ruby) {
all.extend(g.outline.iter());
}
// Underline and strikethrough bars become paths of their run's paint too (#847).
for (run, bar) in vectorcraft_text::decorations(&lay, vectorcraft_text::FontDb::global(), t) {
all.extend(bar.iter());
let st = t.runs.get(run).map(|r| r.style.clone()).unwrap_or_else(|| t.first_style());
let mut node = shape_node(d, PathData::from_bezpath(&bar).transformed(t.xf), None);
node.appearance = st.appearance().into();
children.push(Arc::new(node));
}
// The object's own fills and strokes (not its characters') paint the whole outline:
// those below the Characters row under the characters, the others over them, with
// their unplaced gradients fixed to the layout's bounds in the document.
let all = PathData::from_bezpath(&all).transformed(t.xf);
if !n.appearance.items.is_empty() && !all.is_empty() {
let (below, above) = n.appearance.split_contents();
let tb = t.xf.transform_rect_bbox(lay.bounds);
let mut whole = |items: &[AppearanceItem]| {
let mut ap = Appearance { items: items.to_vec(), ..Default::default() };
ap.pin_gradients(tb);
Arc::new(Node::path(d.alloc_id(), all.clone(), ap))
};
if !below.is_empty() {
children.insert(0, whole(below));
}
if !above.is_empty() {
children.push(whole(above));
}
}
let (par, idx, _) = d.position(tid).ok_or(EngineError::NoNode(tid))?;
d.remove(tid)?;
if children.is_empty() {
@@ -1225,8 +1253,8 @@ fn area_options(s: &mut Session, p: &Value) -> Result<Value> {
.map(|(id, t)| merged(&t.area, t.dynamic_text).map(|o| (id, o)))
.collect::<Result<_>>()?;
// Dynamic Text's Block is refused for threaded frames, as `type.dynamicText` refuses it.
let frames: Vec<String> =
planned.iter().filter(|(id, (_, block))| *block && !super::threads::story_of(d, *id).is_empty()).map(|(id, _)| id.0.to_string()).collect();
let threads = super::threads::ThreadIndex::of(d);
let frames: Vec<String> = planned.iter().filter(|(id, (_, block))| *block && threads.threaded(*id)).map(|(id, _)| id.0.to_string()).collect();
if !frames.is_empty() {
let frames = frames.join(", ");
return Err(bad(C, format!("area type in a thread cannot use Dynamic Text: {frames}")));
@@ -1348,7 +1376,7 @@ fn set_path_handle(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "text.setPathHandle";
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?;
let si = super::draw2::usize_opt(p, "subpath", C)?.unwrap_or(0);
let ai = p.get("anchor").and_then(Value::as_u64).map(index).ok_or_else(|| bad(C, "missing anchor"))?;
let ai = index_opt(p, "anchor", C)?.ok_or_else(|| bad(C, "missing anchor"))?;
let out = super::object::choice(p, C, "which", &["in", "out"])? != Some("in");
let pos = vectorcraft_geom::Point::new(f64_req(p, "x", C)?, f64_req(p, "y", C)?);
let independent = switch_or(p, "independent", false, C)?;
+3 -4
View File
@@ -1688,10 +1688,9 @@ fn warichu_is_a_character_attribute_set_saved_and_exported() {
assert!(["warichu", "warichuLines", "warichuGap", "warichuScale", "warichuAlign"].iter().all(|k| saved.get(*k).is_none()), "{saved}");
let plain_svg = vectorcraft_svg::export(&s.doc().unwrap().doc, &Default::default());
let plain_pdf = vectorcraft_pdf::export(&s.doc().unwrap().doc, &vectorcraft_pdf::PdfOptions::uncompressed()).unwrap();
let text_ops = |pdf: &[u8]| {
let s = String::from_utf8_lossy(pdf);
s.contains("Tj") || s.contains("TJ")
};
// Only text objects count: the file ID in the trailer and the XMP is base64 that changes each
// second and now and then spells `Tj` or `TJ`.
let text_ops = |pdf: &[u8]| String::from_utf8_lossy(pdf).lines().any(|l| l.starts_with("BT ") && (l.contains("Tj") || l.contains("TJ")));
assert!(plain_svg.contains("<text") && text_ops(&plain_pdf));
// text.setFormat with the values the characters already have changes nothing and records no
+21 -14
View File
@@ -7,6 +7,7 @@ use vectorcraft_doc::{AreaFit, CharStyle, Document, Justify, LockedArtboards, No
use vectorcraft_geom::{Affine, Rect, shapes};
use super::object::choice;
use super::threads::ThreadIndex;
use super::typecmd::{area_text, block_gaps, needed_room, refresh_bounds};
use super::{
CommandSpec, EngineError, Result, Session, bad, checked_ids_param, cmd, find_command, has_clipboard, has_doc, has_selection, number_or,
@@ -137,7 +138,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Paste without Formatting",
["Edit"],
Some("Cmd+Alt+V"),
"{center?, dx?, dy?, swatchConflict?} paste as edit.paste; pasted text takes the default character style (one run) and leaves its character and paragraph styles behind → {ids, added, merged, renamed}",
"{center?, dx?, dy?, swatchConflict?} paste as edit.paste; pasted text takes the default character style (one run) and leaves its character and paragraph styles behind, as do the labels of pasted graphs → {ids, added, merged, renamed}",
has_clipboard,
paste_plain
),
@@ -556,7 +557,7 @@ fn path_center_refusal(d: &Document, ids: &[NodeId]) -> Option<String> {
let open = open.join(", ");
return Some(format!("type on an open or compound path cannot be centered on its top or bottom: {open}"));
}
let frames = threaded_ids(d, ids);
let frames = threaded_ids(&ThreadIndex::of(d), ids);
(!frames.is_empty()).then(|| format!("type on a path in a thread cannot be centered on its top or bottom: {frames}"))
}
@@ -783,11 +784,6 @@ fn path_options(s: &mut Session, p: &Value) -> Result<Value> {
options(s)
}
/// Whether type `id` is a frame of a thread.
fn threaded(d: &Document, id: NodeId) -> bool {
!super::threads::story_of(d, id).is_empty()
}
/// Type on a path or area type: the type Dynamic Text works on.
fn dynamic_type(n: Option<&Node>) -> Option<&TextObject> {
path_text(n).or_else(|| area_text(n))
@@ -820,17 +816,18 @@ fn has_dynamic_type(s: &Session) -> std::result::Result<(), String> {
/// path first; None when none is.
fn threaded_refusal(d: &Document, ids: &[NodeId]) -> Option<String> {
let (paths, areas): (Vec<NodeId>, Vec<NodeId>) = ids.iter().copied().partition(|id| path_text(d.node(*id)).is_some());
let frames = threaded_ids(d, &paths);
let threads = ThreadIndex::of(d);
let frames = threaded_ids(&threads, &paths);
if !frames.is_empty() {
return Some(format!("type on a path in a thread cannot use Dynamic Text: {frames}"));
}
let frames = threaded_ids(d, &areas);
let frames = threaded_ids(&threads, &areas);
(!frames.is_empty()).then(|| format!("area type in a thread cannot use Dynamic Text: {frames}"))
}
/// The ids among `ids` of frames of threads, as a list for a message; empty when there are none.
fn threaded_ids(d: &Document, ids: &[NodeId]) -> String {
ids.iter().filter(|id| threaded(d, **id)).map(|id| id.0.to_string()).collect::<Vec<_>>().join(", ")
/// The ids among `ids` of frames of `threads`, as a list for a message; empty when there are none.
fn threaded_ids(threads: &ThreadIndex, ids: &[NodeId]) -> String {
ids.iter().filter(|id| threads.threaded(**id)).map(|id| id.0.to_string()).collect::<Vec<_>>().join(", ")
}
/// Type › Dynamic Text: set `on` (without it, the opposite of the first object's setting, or on
@@ -969,7 +966,7 @@ fn has_preset_type(s: &Session) -> std::result::Result<(), String> {
if ids.is_empty() {
return Err("select point type or type on a path".into());
}
let frames = threaded_ids(d, &ids);
let frames = threaded_ids(&ThreadIndex::of(d), &ids);
if !frames.is_empty() {
return Err(format!("type on a path in a thread cannot use Dynamic Text: {frames}"));
}
@@ -1108,7 +1105,7 @@ fn dynamic_text_preset(s: &mut Session, p: &Value) -> Result<Value> {
if ids.is_empty() {
return Err(bad(C, "select point type or type on a path"));
}
let frames = threaded_ids(d, &ids);
let frames = threaded_ids(&ThreadIndex::of(d), &ids);
if !frames.is_empty() {
return Err(bad(C, format!("type on a path in a thread cannot use Dynamic Text: {frames}")));
}
@@ -1463,6 +1460,16 @@ fn strip_formatting(n: &mut vectorcraft_doc::Node) {
t.set_all_paras(Default::default());
refresh_bounds(t);
}
// A graph keeps the names of its labels' character and paragraph styles for each redraw.
if let Some(g) = n.extras_if_any().and_then(|e| e.graph.as_deref_mut()) {
let l = &mut g.label_styles;
for st in [&mut l.values, &mut l.categories, &mut l.legend].into_iter().flatten() {
st.style_name = None;
}
for pa in [&mut l.values_para, &mut l.categories_para, &mut l.legend_para].into_iter().flatten() {
pa.style_name = None;
}
}
if let Some(ch) = n.children_mut() {
for c in ch.iter_mut() {
strip_formatting(std::sync::Arc::make_mut(c));

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