mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-27 16:59:43 +01:00
Merge remote-tracking branch 'upstream/main' into pencil-redraw-extend
# Conflicts: # docs/target-app-parity.md # docs/ui-parity.md
This commit is contained in:
commit
5850bdead9
256 files changed
+10103
-892
No files matched your search
@@ -27,8 +27,8 @@ permissions:
|
||||
|
||||
jobs:
|
||||
windows-arm64:
|
||||
# Immutable supporting workflow revision until the new install contract lands upstream.
|
||||
uses: storytold/craft-common-actions/.github/workflows/windows-arm64.yml@8bb4e5ab95443171104ad88113fe1ef9b0e5ce3f
|
||||
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
|
||||
uses: storytold/craft-common-actions/.github/workflows/windows-arm64.yml@main
|
||||
with:
|
||||
app-name: vectorcraft
|
||||
app-dir: VectorCraft
|
||||
|
||||
@@ -86,3 +86,8 @@ When a task lands, update in the same PR: the area row in `docs/target-app-parit
|
||||
GitHub profiles). Never hand-edit `contributors.json`.
|
||||
- Maintainers refresh the stats with `python3 ../../craftrules/scripts/contributors.py .` (it also
|
||||
re-verifies who wrote each `people.toml` entry; `--check` only verifies).
|
||||
|
||||
## CI workflows
|
||||
- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here.
|
||||
- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time.
|
||||
- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it.
|
||||
@@ -69,3 +69,8 @@ The progress docs follow craftrules' [`standards/progress-docs.md`](https://gith
|
||||
When a task lands, update in the same PR: the area row in `docs/target-app-parity.md` (score, missing items, hours) and its evidence list, the gap entry in `docs/gaps.md` if it closed or shrank, the checklist it belongs to, the milestone row in `docs/roadmap.md`, and the ROADMAP's tables and progress log when a headline number moves. Update each touched doc's status line and revision history.
|
||||
- Grade by behaviour against the public documentation (`plan/illustrator/` notes), not by whether a menu item exists. Scores are self-assessed, so err low; mark each number measured or estimated.
|
||||
- Keep the README's Status section in step with the ROADMAP headline.
|
||||
|
||||
## CI workflows
|
||||
- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here.
|
||||
- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time.
|
||||
- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it.
|
||||
Generated
+19
-18
@@ -217,7 +217,7 @@ dependencies = [
|
||||
"objc2-foundation 0.3.2",
|
||||
"parking_lot",
|
||||
"percent-encoding",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.59.0",
|
||||
"wl-clipboard-rs",
|
||||
"x11rb",
|
||||
]
|
||||
@@ -1017,7 +1017,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13af
|
||||
dependencies = [
|
||||
"craft-winprint-gdi",
|
||||
"miniz_oxide 0.9.1",
|
||||
"roxmltree 0.21.1",
|
||||
"roxmltree 0.21.2",
|
||||
"tempfile",
|
||||
"winprint",
|
||||
"winsafe",
|
||||
@@ -1047,13 +1047,14 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-update"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1065653e75854e9c17e1ff563acdd344c1b185f0#1065653e75854e9c17e1ff563acdd344c1b185f0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"dunce",
|
||||
"egui",
|
||||
"flate2",
|
||||
"getrandom 0.3.4",
|
||||
"image",
|
||||
"log",
|
||||
"plist",
|
||||
"semver",
|
||||
@@ -1562,7 +1563,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3617,7 +3618,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4139,7 +4140,7 @@ dependencies = [
|
||||
"once_cell",
|
||||
"socket2",
|
||||
"tracing",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4445,9 +4446,9 @@ checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97"
|
||||
|
||||
[[package]]
|
||||
name = "roxmltree"
|
||||
version = "0.21.1"
|
||||
version = "0.21.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f1964b10c76125c36f8afe190065a4bf9a87bf324842c05701330bba9f1cacbb"
|
||||
checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
@@ -4496,7 +4497,7 @@ dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys 0.12.1",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4555,7 +4556,7 @@ dependencies = [
|
||||
"security-framework",
|
||||
"security-framework-sys",
|
||||
"webpki-root-certs",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5414,10 +5415,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
|
||||
dependencies = [
|
||||
"fastrand",
|
||||
"getrandom 0.4.3",
|
||||
"getrandom 0.3.4",
|
||||
"once_cell",
|
||||
"rustix 1.1.5",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5992,7 +5993,7 @@ dependencies = [
|
||||
"kurbo 0.13.1",
|
||||
"log",
|
||||
"pico-args",
|
||||
"roxmltree 0.21.1",
|
||||
"roxmltree 0.21.2",
|
||||
"simplecss",
|
||||
"siphasher",
|
||||
"skrifa 0.44.0",
|
||||
@@ -6196,7 +6197,7 @@ dependencies = [
|
||||
"kurbo 0.13.1",
|
||||
"log",
|
||||
"proptest",
|
||||
"roxmltree 0.21.1",
|
||||
"roxmltree 0.21.2",
|
||||
"rustix 1.1.5",
|
||||
"ruzstd",
|
||||
"serde",
|
||||
@@ -6335,7 +6336,7 @@ dependencies = [
|
||||
"kurbo 0.13.1",
|
||||
"log",
|
||||
"md-5",
|
||||
"roxmltree 0.21.1",
|
||||
"roxmltree 0.21.2",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
@@ -7181,7 +7182,7 @@ version = "0.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7907,9 +7908,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "zip"
|
||||
version = "9.1.0"
|
||||
version = "9.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2886b00003a72c4ccee3f42cfc34908d33b2508a74d827dc2a4244706475c704"
|
||||
checksum = "1156b39d142a34b999c2310a50455e0cb3760bf7efad0122f796d813bee26ccb"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
|
||||
+2
-1
@@ -19,7 +19,8 @@ craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "92d392c
|
||||
# Decides who draws the window frame (desktop vs. app) so the suite shares one native titlebar per
|
||||
# desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.)
|
||||
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["egui"] }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["egui"] }
|
||||
# craft-update with storytold/craft-libs#434: the update prompt shows the app's icon, accent and developer.
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "1065653e75854e9c17e1ff563acdd344c1b185f0", features = ["egui"] }
|
||||
# internal
|
||||
vectorcraft-geom = { path = "crates/geom" }
|
||||
vectorcraft-color = { path = "crates/color" }
|
||||
|
||||
@@ -144,6 +144,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
|
||||
| Date | What landed |
|
||||
|---|---|
|
||||
| 2026-10-29 | Linux: a clipboard that can't be opened (the Flatpak on GNOME, where arboard has neither data-control nor X11) is retried after 1 s, doubling to a minute, and logged once, where the background Paste check used to reconnect and log a warning every 250 ms (267k warnings in 18 h). Scores and estimates unchanged. |
|
||||
| 2026-10-21 | 3D lighting: four original lighting presets shared by Revolve, Extrude & Bevel, Inflate and Rotate, with command access and manual Custom settings; scores and estimates unchanged. |
|
||||
| 2026-10-21 | Print: the Print dialog's Media list has the Japanese papers — JIS B4 (257 × 364 mm), JIS B5 (182 × 257 mm) and JIS B6 next to the ISO B4/B5 (which keep their ISO 216 dimensions for settings saved before them), はがき 100 × 148 mm, 往復はがき 148 × 200 mm, 封筒 長形3号 120 × 235 mm / 長形4号 90 × 225 mm / 角形2号 240 × 332 mm / 角形3号 216 × 277 mm and 四六判 127 × 188 mm. A paper is named by its JSON id or its dialog label, any case and spacing (`B5 (JIS)` or `b5jis`), and every added size prints as its own PDF page size. Headline numbers unchanged. |
|
||||
| 2026-10-18 | Inch rulers divide the inch in half, not in ten. Zooming in stepped an inch ruler through 0.2, 0.1 and 0.05 of an inch, marks an inch ruler does not carry; below an inch the steps are binary fractions now, 1/2 down to 1/16, with the unlabelled ticks between them binary too (down to 1/128, so the 32nds, 64ths and 128ths appear as the report expects), while the metric units, points, pixels and picas keep their tenths. A label carries the decimals its step needs, so a sixteenth reads 0.0625 rather than the rounded 0.06, with trailing zeros dropped (#2827). Headline numbers unchanged. |
|
||||
@@ -198,6 +199,7 @@ The full pre-standard record of what landed is kept in [docs/roadmap.md](docs/ro
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-29 | minor | Progress log row for the Linux clipboard retry backoff; headline numbers unchanged. |
|
||||
| 2026-10-23 | minor | Progress log row for Pathfinder › Trap; Live vector effects hours 6–10 → 4–8; headline numbers unchanged. |
|
||||
| 2026-10-23 | minor | Progress log row for OpenType SVG colour fonts; headline numbers unchanged. |
|
||||
| 2026-10-23 | minor | Progress log row for COLR colour fonts; headline numbers unchanged. |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#[cfg(all(target_os = "macos", feature = "accessibility", feature = "wgpu"))]
|
||||
use super::gpu;
|
||||
use super::prefs::save_prefs;
|
||||
use super::prefs::{save_prefs, save_prefs_soon};
|
||||
#[cfg(all(windows, not(target_vendor = "win7")))]
|
||||
use super::windows_stylus;
|
||||
use super::{App, VectorcraftApp, file_access, window};
|
||||
@@ -71,6 +71,9 @@ impl eframe::App for App {
|
||||
// (the system shutting down, the process ended or crashing) used to lose them (#1747).
|
||||
if self.app.take_prefs_changed() {
|
||||
file_access::unconfined(|| save_prefs(&self.app));
|
||||
} else {
|
||||
// The workspace, panels and other UI settings change without the dialog (#4625).
|
||||
file_access::unconfined(|| save_prefs_soon(&self.app));
|
||||
}
|
||||
// Not while a file dialog's sheet has the keyboard: its name field's composition would go.
|
||||
#[cfg(target_os = "macos")]
|
||||
|
||||
@@ -9,7 +9,8 @@
|
||||
//! and EPS as vector art (#1499) and its PNG or TIFF as they are, as screenshots copy them (on
|
||||
//! Linux arboard reads no other formats). On Wayland, arboard's data-control
|
||||
//! backend reads the compositor's clipboard (X11 through XWayland only sees what X11 apps
|
||||
//! copied), falling back to X11 where the compositor lacks the protocol.
|
||||
//! copied), falling back to X11 where the compositor lacks the protocol. A clipboard that can't
|
||||
//! be opened is tried again after a wait that grows to a minute, not each time Paste asks.
|
||||
//! - Everywhere: files copied in a file manager paste as the first one that is art (SVG, PDF, EPS,
|
||||
//! a metafile or a bitmap), before the clipboard's other formats (the files' paths as text).
|
||||
|
||||
@@ -310,6 +311,8 @@ mod win {
|
||||
#[cfg_attr(windows, allow(dead_code))]
|
||||
mod portable {
|
||||
use std::borrow::Cow;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use super::{BITMAP, Flavour, PNG, SystemClipboard, TEXT, copied_file, decode_png, png_flavour, text_of};
|
||||
|
||||
@@ -319,19 +322,113 @@ mod portable {
|
||||
Image(usize, usize),
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
/// Who asks for the clipboard: the background paste check waits out the whole wait after a
|
||||
/// failure, a Copy or Paste of the user's [`USER_RETRY`] at most.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
pub(super) enum Asker {
|
||||
Probe,
|
||||
User,
|
||||
}
|
||||
|
||||
/// The wait after the first failure to open the clipboard; it doubles with each failed retry.
|
||||
const FIRST_WAIT: Duration = Duration::from_secs(1);
|
||||
/// The longest wait between retries.
|
||||
const MAX_WAIT: Duration = Duration::from_secs(60);
|
||||
/// A Copy or Paste of the user's retries at most this often.
|
||||
const USER_RETRY: Duration = Duration::from_secs(1);
|
||||
|
||||
/// Whether "unavailable" has been logged and not yet answered by "available again": the
|
||||
/// clipboard and its background check hold a handle each, and their failures are one outage.
|
||||
static UNAVAILABLE_LOGGED: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// A failure to open, and when to try again.
|
||||
struct Failed {
|
||||
at: Instant,
|
||||
wait: Duration,
|
||||
}
|
||||
|
||||
/// A handle opened on first use and kept, or after a failure opened again only once its wait is
|
||||
/// over: where the clipboard can't be opened, asking a few times a second must not reconnect each time.
|
||||
pub(super) struct Reopen<B> {
|
||||
handle: Option<B>,
|
||||
failed: Option<Failed>,
|
||||
/// The outage flag shared with the other handles ([`UNAVAILABLE_LOGGED`]).
|
||||
logged: &'static AtomicBool,
|
||||
}
|
||||
|
||||
impl<B> Reopen<B> {
|
||||
pub(super) fn new(logged: &'static AtomicBool) -> Self {
|
||||
Self { handle: None, failed: None, logged }
|
||||
}
|
||||
|
||||
/// The open handle, opened with `open` when there is none and `asker` may try at `now`.
|
||||
/// `name` names an opened handle in the log.
|
||||
pub(super) fn get(
|
||||
&mut self,
|
||||
asker: Asker,
|
||||
now: Instant,
|
||||
open: impl FnOnce() -> Result<B, String>,
|
||||
name: impl Fn(&B) -> &'static str,
|
||||
) -> Option<&mut B> {
|
||||
if self.handle.is_none() {
|
||||
if let Some(f) = &self.failed {
|
||||
let wait = match asker {
|
||||
Asker::Probe => f.wait,
|
||||
Asker::User => f.wait.min(USER_RETRY),
|
||||
};
|
||||
if now.saturating_duration_since(f.at) < wait {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
match open() {
|
||||
Ok(handle) => {
|
||||
if self.logged.swap(false, Ordering::Relaxed) {
|
||||
log::info!("the system clipboard is available again, through {}", name(&handle));
|
||||
} else {
|
||||
log::debug!("system clipboard opened through {}", name(&handle));
|
||||
}
|
||||
self.failed = None;
|
||||
self.handle = Some(handle);
|
||||
}
|
||||
Err(why) => {
|
||||
let wait = match &self.failed {
|
||||
Some(f) => (f.wait * 2).min(MAX_WAIT),
|
||||
None => FIRST_WAIT,
|
||||
};
|
||||
if self.logged.swap(true, Ordering::Relaxed) {
|
||||
log::debug!("the system clipboard is still unavailable ({why}); next try in {wait:?}");
|
||||
} else {
|
||||
log::warn!("the system clipboard is unavailable ({why}): Copy and Paste stay inside VectorCraft");
|
||||
}
|
||||
self.failed = Some(Failed { at: now, wait });
|
||||
}
|
||||
}
|
||||
}
|
||||
self.handle.as_mut()
|
||||
}
|
||||
|
||||
/// The handle if one is open, without trying to open one.
|
||||
pub(super) fn opened(&mut self) -> Option<&mut B> {
|
||||
self.handle.as_mut()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Clipboard {
|
||||
/// Kept open: on Linux the copied data lives as long as the handle does.
|
||||
cb: Option<arboard::Clipboard>,
|
||||
cb: Reopen<arboard::Clipboard>,
|
||||
ours: Option<Ours>,
|
||||
}
|
||||
|
||||
impl Default for Clipboard {
|
||||
fn default() -> Self {
|
||||
Self { cb: Reopen::new(&UNAVAILABLE_LOGGED), ours: None }
|
||||
}
|
||||
}
|
||||
|
||||
impl Clipboard {
|
||||
fn cb(&mut self) -> Result<&mut arboard::Clipboard, String> {
|
||||
if self.cb.is_none() {
|
||||
self.cb = Some(arboard::Clipboard::new().map_err(|e| e.to_string())?);
|
||||
}
|
||||
self.cb.as_mut().ok_or_else(|| "no system clipboard".to_string())
|
||||
fn cb(&mut self, asker: Asker) -> Result<&mut arboard::Clipboard, String> {
|
||||
let open = || arboard::Clipboard::new().map_err(|e| e.to_string());
|
||||
self.cb.get(asker, Instant::now(), open, |_| "arboard").ok_or_else(|| "no system clipboard".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -342,7 +439,7 @@ mod portable {
|
||||
Some(_) => None,
|
||||
None => flavours.iter().find(|f| f.mime == PNG).and_then(|f| decode_png(&f.data)),
|
||||
};
|
||||
let cb = self.cb()?;
|
||||
let cb = self.cb(Asker::User)?;
|
||||
let ours = match (text, image) {
|
||||
(Some(t), _) => {
|
||||
cb.set_text(t.as_str()).map_err(|e| e.to_string())?;
|
||||
@@ -363,7 +460,7 @@ mod portable {
|
||||
}
|
||||
|
||||
fn holds_ours(&mut self) -> bool {
|
||||
let Some(cb) = self.cb.as_mut() else { return false };
|
||||
let Some(cb) = self.cb.opened() else { return false };
|
||||
match &self.ours {
|
||||
Some(Ours::Text(t)) => cb.get_text().is_ok_and(|now| now == *t),
|
||||
Some(Ours::Image(w, h)) => cb.get_image().is_ok_and(|now| (now.width, now.height) == (*w, *h)),
|
||||
@@ -372,7 +469,7 @@ mod portable {
|
||||
}
|
||||
|
||||
fn read(&mut self, mimes: &[&'static str]) -> Option<Flavour> {
|
||||
let cb = self.cb().ok()?;
|
||||
let cb = self.cb(Asker::User).ok()?;
|
||||
if let Some(f) = cb.get().file_list().ok().and_then(|paths| copied_file(paths, mimes)) {
|
||||
return Some(f);
|
||||
}
|
||||
@@ -402,7 +499,126 @@ mod portable {
|
||||
if super::mac::has(mimes) {
|
||||
return true;
|
||||
}
|
||||
mimes.contains(&TEXT) && self.cb().is_ok_and(|cb| cb.get_text().is_ok_and(|t| !t.is_empty()))
|
||||
mimes.contains(&TEXT) && self.cb(Asker::Probe).is_ok_and(|cb| cb.get_text().is_ok_and(|t| !t.is_empty()))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::cell::Cell;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A clock that starts now and moves only when told.
|
||||
struct Clock(Cell<Instant>);
|
||||
|
||||
impl Clock {
|
||||
fn new() -> Self {
|
||||
Self(Cell::new(Instant::now()))
|
||||
}
|
||||
fn now(&self) -> Instant {
|
||||
self.0.get()
|
||||
}
|
||||
fn advance(&self, by: Duration) {
|
||||
self.0.set(self.0.get() + by);
|
||||
}
|
||||
}
|
||||
|
||||
fn fail() -> Result<u8, String> {
|
||||
Err("no compositor".into())
|
||||
}
|
||||
|
||||
fn name(_: &u8) -> &'static str {
|
||||
"fake"
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_paste_check_retries_with_a_growing_wait() {
|
||||
static LOGGED: AtomicBool = AtomicBool::new(false);
|
||||
let (clock, attempts) = (Clock::new(), Cell::new(0));
|
||||
let mut cb = Reopen::new(&LOGGED);
|
||||
// Every 250 ms for a minute, as `clipboard_probe` asks.
|
||||
for _ in 0..240 {
|
||||
let open = || {
|
||||
attempts.set(attempts.get() + 1);
|
||||
fail()
|
||||
};
|
||||
assert!(cb.get(Asker::Probe, clock.now(), open, name).is_none());
|
||||
clock.advance(Duration::from_millis(250));
|
||||
}
|
||||
// 0, 1, 3, 7, 15 and 31 s: not one connection a check.
|
||||
assert_eq!(attempts.get(), 6);
|
||||
assert!(LOGGED.load(Ordering::Relaxed), "the outage is logged");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_wait_stops_growing_at_a_minute() {
|
||||
static LOGGED: AtomicBool = AtomicBool::new(false);
|
||||
let (clock, attempts) = (Clock::new(), Cell::new(0));
|
||||
let mut cb = Reopen::new(&LOGGED);
|
||||
for _ in 0..(20 * 60) {
|
||||
let open = || {
|
||||
attempts.set(attempts.get() + 1);
|
||||
fail()
|
||||
};
|
||||
let _ = cb.get(Asker::Probe, clock.now(), open, name);
|
||||
clock.advance(Duration::from_secs(1));
|
||||
}
|
||||
// 0, 1, 3, 7, 15, 31, 63 s, then a minute apart until 20 minutes are up.
|
||||
assert_eq!(attempts.get(), 7 + (20 * 60 - 63 - 1) / 60);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_copy_or_paste_retries_at_most_once_a_second() {
|
||||
static LOGGED: AtomicBool = AtomicBool::new(false);
|
||||
let (clock, attempts) = (Clock::new(), Cell::new(0));
|
||||
let mut cb = Reopen::new(&LOGGED);
|
||||
let mut ask = |asker| {
|
||||
let open = || {
|
||||
attempts.set(attempts.get() + 1);
|
||||
fail()
|
||||
};
|
||||
let _ = cb.get(asker, clock.now(), open, name);
|
||||
};
|
||||
// Long after the paste check gave up for a minute, a held Ctrl+V for 3 s at 30 a second.
|
||||
for _ in 0..8 {
|
||||
ask(Asker::Probe);
|
||||
clock.advance(Duration::from_secs(70));
|
||||
}
|
||||
let before = attempts.get();
|
||||
for _ in 0..90 {
|
||||
ask(Asker::User);
|
||||
clock.advance(Duration::from_millis(33));
|
||||
}
|
||||
assert_eq!(attempts.get() - before, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_success_is_kept_and_ends_the_outage() {
|
||||
static LOGGED: AtomicBool = AtomicBool::new(false);
|
||||
let clock = Clock::new();
|
||||
let mut cb = Reopen::new(&LOGGED);
|
||||
assert!(cb.get(Asker::Probe, clock.now(), fail, name).is_none());
|
||||
assert!(LOGGED.load(Ordering::Relaxed));
|
||||
clock.advance(FIRST_WAIT);
|
||||
assert_eq!(cb.get(Asker::Probe, clock.now(), || Ok(7), name).copied(), Some(7));
|
||||
assert!(!LOGGED.load(Ordering::Relaxed), "the recovery is logged");
|
||||
// Kept: not opened again, even where opening would now fail.
|
||||
assert_eq!(cb.get(Asker::Probe, clock.now(), fail, name).copied(), Some(7));
|
||||
assert_eq!(cb.opened().copied(), Some(7));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_outage_is_logged_once_across_handles() {
|
||||
static LOGGED: AtomicBool = AtomicBool::new(false);
|
||||
let clock = Clock::new();
|
||||
let (mut ui, mut probe) = (Reopen::new(&LOGGED), Reopen::new(&LOGGED));
|
||||
assert!(probe.get(Asker::Probe, clock.now(), fail, name).is_none());
|
||||
assert!(LOGGED.load(Ordering::Relaxed));
|
||||
// The other handle's failure is the same outage: `swap` reports it already logged.
|
||||
assert!(ui.get(Asker::User, clock.now(), fail, name).is_none());
|
||||
assert!(LOGGED.load(Ordering::Relaxed));
|
||||
assert!(probe.opened().is_none() && ui.opened().is_none());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+29
-14
@@ -140,33 +140,48 @@ pub fn backends(default: Backends, env_set: bool, opengl: bool) -> Backends {
|
||||
}
|
||||
|
||||
/// Whether a Windows start lists OpenGL's adapters beside Direct3D 12's: only when it leaves an
|
||||
/// adapter out (an earlier start crashed on it, or a restart failed on it) or DX12 lists none
|
||||
/// (Windows 7). wgpu's OpenGL backend keeps a hidden window on a thread that pumps no messages,
|
||||
/// and Windows waits on it when the input language changes, so the whole app hung on a switch to
|
||||
/// another keyboard layout (#4150, gfx-rs/wgpu#10504), even drawing with DX12.
|
||||
/// adapter out (an earlier start crashed on it, or a restart failed on it), when
|
||||
/// `WGPU_ADAPTER_NAME` names one (it may be an OpenGL adapter), or when DX12 lists no hardware
|
||||
/// adapter (Windows 7, or a GPU without a DX12 driver, which then draws through OpenGL as before
|
||||
/// rather than on the CPU with WARP). wgpu's OpenGL backend keeps a hidden window on a thread that
|
||||
/// pumps no messages, and Windows waits on it when the input language changes, so the whole app
|
||||
/// hung on a switch to another keyboard layout (#4150, gfx-rs/wgpu#10504), even drawing with DX12.
|
||||
pub fn windows_opengl(left_out: &LeftOut) -> bool {
|
||||
left_out.opengl_only || !left_out.adapters.is_empty() || !skipped().is_empty() || !dx12_lists_adapters()
|
||||
opengl_needed(left_out, !skipped().is_empty(), std::env::var_os(NAME_ENV).is_some(), dx12_lists_hardware)
|
||||
}
|
||||
|
||||
/// Whether Direct3D 12 lists any adapter, WARP's software one included. A driver that crashes here
|
||||
/// crashes a start while it lists the adapters, which the next start answers with OpenGL alone.
|
||||
/// [`windows_opengl`], with a restart leaving adapters out (`skipping`) and an adapter named
|
||||
/// (`named`): `dx12_hardware` is asked only when nothing else decides.
|
||||
fn opengl_needed(left_out: &LeftOut, skipping: bool, named: bool, dx12_hardware: impl FnOnce() -> bool) -> bool {
|
||||
left_out.opengl_only || !left_out.adapters.is_empty() || skipping || named || !dx12_hardware()
|
||||
}
|
||||
|
||||
/// Whether Direct3D 12 lists a hardware adapter; WARP, its software one, doesn't count. A driver
|
||||
/// that crashes here crashes a start while it lists the adapters, which the next start answers with
|
||||
/// OpenGL alone.
|
||||
#[cfg(windows)]
|
||||
fn dx12_lists_adapters() -> bool {
|
||||
fn dx12_lists_hardware() -> bool {
|
||||
let mut descriptor = wgpu::InstanceDescriptor::new_without_display_handle();
|
||||
descriptor.backends = Backends::DX12;
|
||||
// FXC is part of Windows, as for the window's own instance (#1194).
|
||||
descriptor.backend_options.dx12.shader_compiler = wgpu::Dx12Compiler::Fxc;
|
||||
// The shader compiler the window's own instance takes (#1194).
|
||||
descriptor.backend_options.dx12.shader_compiler = wgpu::Dx12Compiler::from_env().unwrap_or(wgpu::Dx12Compiler::Fxc);
|
||||
let instance = wgpu::Instance::new(descriptor);
|
||||
let found = pollster::block_on(instance.enumerate_adapters(Backends::DX12)).len();
|
||||
log::info!("Direct3D 12 lists {found} graphics adapters");
|
||||
found > 0
|
||||
let kinds: Vec<DeviceType> = pollster::block_on(instance.enumerate_adapters(Backends::DX12)).iter().map(|a| a.get_info().device_type).collect();
|
||||
log::info!("Direct3D 12 lists these graphics adapters: {kinds:?}");
|
||||
any_hardware(&kinds)
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn dx12_lists_adapters() -> bool {
|
||||
fn dx12_lists_hardware() -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Is one of the adapters of these kinds hardware, not software such as WARP?
|
||||
#[cfg(any(windows, test))]
|
||||
fn any_hardware(kinds: &[DeviceType]) -> bool {
|
||||
kinds.iter().any(|k| *k != DeviceType::Cpu)
|
||||
}
|
||||
|
||||
/// The largest texture side to ask the device for, which bounds the window's surface: the
|
||||
/// adapter's own limit when it is above eframe's `default` (8192 px), so a window larger than
|
||||
/// that keeps its surface (#1459). Never below `default`, which is what was asked for before.
|
||||
|
||||
@@ -472,6 +472,31 @@ fn windows_lists_opengl_once_a_start_leaves_an_adapter_out() {
|
||||
assert_eq!(listing.backends(backends(Backends::all(), false, true)), Backends::GL);
|
||||
}
|
||||
|
||||
/// OpenGL stays where it drew before #4150's fix: a GPU without a Direct3D 12 driver (DX12 lists
|
||||
/// WARP alone) and an adapter `WGPU_ADAPTER_NAME` names; a start with a DX12 GPU lists DX12 alone.
|
||||
#[test]
|
||||
fn windows_lists_opengl_without_a_dx12_gpu_or_with_an_adapter_named() {
|
||||
let start = LeftOut::default();
|
||||
let asked = std::cell::Cell::new(false);
|
||||
let hardware = |found: bool| {
|
||||
asked.set(true);
|
||||
found
|
||||
};
|
||||
assert!(!opengl_needed(&start, false, false, || hardware(true)), "a DX12 GPU: DX12 alone (#4150)");
|
||||
assert!(asked.replace(false));
|
||||
assert!(opengl_needed(&start, false, false, || hardware(false)), "WARP alone: the GPU draws through OpenGL, not the CPU");
|
||||
assert!(opengl_needed(&start, false, true, || hardware(true)), "a named adapter may be an OpenGL one");
|
||||
assert!(opengl_needed(&start, true, false, || hardware(true)), "a restart left an adapter out");
|
||||
let listing = LeftOut { opengl_only: true, ..LeftOut::default() };
|
||||
asked.set(false);
|
||||
assert!(opengl_needed(&listing, false, false, || hardware(true)));
|
||||
assert!(!asked.get(), "DX12 isn't listed once OpenGL must be");
|
||||
assert!(any_hardware(&[DeviceType::Cpu, DeviceType::IntegratedGpu]));
|
||||
assert!(any_hardware(&[DeviceType::VirtualGpu]));
|
||||
assert!(!any_hardware(&[DeviceType::Cpu]), "WARP");
|
||||
assert!(!any_hardware(&[]), "Windows 7");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn power_preference_follows_the_environment_then_the_preference() {
|
||||
assert_eq!(power_preference(None, None), AUTOMATIC);
|
||||
|
||||
@@ -128,7 +128,7 @@ Without a window (converting, scripting, the MCP server), use vectorcraft-cli:
|
||||
fn main() -> std::process::ExitCode {
|
||||
// Windows: the update helper is a copy of this program started with `--finish-update`.
|
||||
#[cfg(windows)]
|
||||
if let Some(result) = craft_update::self_update::finish(&craft_update::suite::VECTORCRAFT, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
|
||||
if let Some(result) = craft_update::self_update::finish(&vectorcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
|
||||
std::process::exit(i32::from(result.is_err()));
|
||||
}
|
||||
// Before any thread starts: the pointer must find a cursor theme on Wayland (#2450).
|
||||
|
||||
@@ -84,24 +84,200 @@ pub(crate) fn load_prefs(app: &mut VectorcraftApp, saved: Option<vectorcraft_ui_
|
||||
app.ui = ui.sanitized();
|
||||
}
|
||||
vectorcraft_ui_egui::prefs_dialog::restore(app);
|
||||
// What this window started from: only what changes after it is this window's to save.
|
||||
set_saved_base(prefs_value(app).ok());
|
||||
}
|
||||
|
||||
/// Save what this window changed since it last read or saved the preferences, merged into the
|
||||
/// file as it is now ([`merge_changes`]): another VectorCraft window open at the same time, which
|
||||
/// read the file before this one saved, then keeps this window's changes when it saves or quits
|
||||
/// (#4625). Nothing is written when nothing changed.
|
||||
pub(crate) fn save_prefs(app: &VectorcraftApp) {
|
||||
if !prefs_enabled() || KEEP_UI_PREFS.load(std::sync::atomic::Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
if let Some(p) = prefs_path() {
|
||||
let _ = std::fs::create_dir_all(p.parent().unwrap_or(std::path::Path::new(".")));
|
||||
if let Ok(bytes) = prefs_bytes(app) {
|
||||
// Preferences are best effort: a failed write keeps the previous file.
|
||||
let _ = fileio::write_atomic(&p, &bytes);
|
||||
}
|
||||
let Some(p) = prefs_path() else { return };
|
||||
let Ok(mine) = prefs_value(app) else { return };
|
||||
let base = saved_base();
|
||||
if base.as_ref().is_some_and(|b| same_lasting(b, &mine)) {
|
||||
return;
|
||||
}
|
||||
// The file as another window may have saved it since (none, or unreadable: this one's own).
|
||||
let on_disk = std::fs::read(&p).ok().and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).ok());
|
||||
let merged = match (base.as_ref(), on_disk) {
|
||||
(Some(base), Some(on_disk)) => merge_changes(base, &mine, on_disk),
|
||||
_ => mine.clone(),
|
||||
};
|
||||
let _ = std::fs::create_dir_all(p.parent().unwrap_or(std::path::Path::new(".")));
|
||||
let Ok(bytes) = serde_json::to_vec_pretty(&merged) else { return };
|
||||
// Preferences are best effort: a failed write keeps the previous file, and the changes are
|
||||
// tried again on the next save.
|
||||
if fileio::write_atomic(&p, &bytes).is_ok() {
|
||||
set_saved_base(Some(mine));
|
||||
}
|
||||
}
|
||||
|
||||
/// How often [`save_prefs_soon`] looks for changes to save.
|
||||
const SAVE_EVERY: std::time::Duration = std::time::Duration::from_secs(2);
|
||||
|
||||
/// Save the preferences at most every [`SAVE_EVERY`] while the app runs, when something changed:
|
||||
/// the workspace, panels, toolbars and the other UI settings kept only in the UI state were saved
|
||||
/// only on quitting, so a session ended any other way (the window closed by the system, the
|
||||
/// process ended or crashing) started the next one from the settings before it (#4625).
|
||||
pub(crate) fn save_prefs_soon(app: &VectorcraftApp) {
|
||||
static LAST: std::sync::Mutex<Option<std::time::Instant>> = std::sync::Mutex::new(None);
|
||||
let Ok(mut last) = LAST.lock() else { return };
|
||||
if last.is_some_and(|t| t.elapsed() < SAVE_EVERY) {
|
||||
return;
|
||||
}
|
||||
*last = Some(std::time::Instant::now());
|
||||
drop(last);
|
||||
save_prefs(app);
|
||||
}
|
||||
|
||||
/// The preferences as this window last read or saved them (`None`: not read yet).
|
||||
static SAVED_BASE: std::sync::Mutex<Option<serde_json::Value>> = std::sync::Mutex::new(None);
|
||||
|
||||
fn saved_base() -> Option<serde_json::Value> {
|
||||
SAVED_BASE.lock().ok().and_then(|b| b.clone())
|
||||
}
|
||||
|
||||
fn set_saved_base(value: Option<serde_json::Value>) {
|
||||
if let Ok(mut b) = SAVED_BASE.lock() {
|
||||
*b = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// Fields of the UI state that a start resets ([`vectorcraft_ui_egui::UiState::sanitized`]): a
|
||||
/// change to them alone isn't saved, and they are never merged over another window's.
|
||||
const PASSING: &[&str] = &["status", "dialog", "flyout", "palette_open", "palette_query", "about", "open_panel"];
|
||||
|
||||
/// Do `a` and `b` hold the same preferences, leaving out what a start resets ([`PASSING`])?
|
||||
fn same_lasting(a: &serde_json::Value, b: &serde_json::Value) -> bool {
|
||||
match (a.as_object(), b.as_object()) {
|
||||
(Some(a), Some(b)) => {
|
||||
let keys: std::collections::BTreeSet<&String> = a.keys().chain(b.keys()).filter(|k| !PASSING.contains(&k.as_str())).collect();
|
||||
keys.into_iter().all(|k| a.get(k) == b.get(k))
|
||||
}
|
||||
_ => a == b,
|
||||
}
|
||||
}
|
||||
|
||||
/// `on_disk` with what changed from `base` to `mine` put over it: each top-level field of the UI
|
||||
/// state, and each engine preference (`engine_prefs`) on its own, so two windows that change
|
||||
/// different settings keep both. A field both changed takes this window's value (it saves last).
|
||||
fn merge_changes(base: &serde_json::Value, mine: &serde_json::Value, on_disk: serde_json::Value) -> serde_json::Value {
|
||||
use serde_json::Value;
|
||||
let (Some(base), Some(mine), Value::Object(mut out)) = (base.as_object(), mine.as_object(), on_disk) else {
|
||||
return mine.clone();
|
||||
};
|
||||
let keys: std::collections::BTreeSet<&String> = base.keys().chain(mine.keys()).collect();
|
||||
for key in keys {
|
||||
if PASSING.contains(&key.as_str()) {
|
||||
if let Some(v) = mine.get(key) {
|
||||
out.entry(key.clone()).or_insert_with(|| v.clone());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let (was, now) = (base.get(key), mine.get(key));
|
||||
if was == now {
|
||||
continue;
|
||||
}
|
||||
if key == "engine_prefs"
|
||||
&& let (Some(Value::Object(was)), Some(Value::Object(now)), Some(Value::Object(theirs))) = (was, now, out.get_mut(key))
|
||||
{
|
||||
let names: std::collections::BTreeSet<&String> = was.keys().chain(now.keys()).collect();
|
||||
for name in names {
|
||||
match (was.get(name), now.get(name)) {
|
||||
(a, b) if a == b => {}
|
||||
(_, Some(v)) => {
|
||||
theirs.insert(name.clone(), v.clone());
|
||||
}
|
||||
(_, None) => {
|
||||
theirs.remove(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
match now {
|
||||
Some(v) => {
|
||||
out.insert(key.clone(), v.clone());
|
||||
}
|
||||
None => {
|
||||
out.remove(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
Value::Object(out)
|
||||
}
|
||||
|
||||
/// The preferences file's contents: the UI state with the engine preferences.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn prefs_bytes(app: &VectorcraftApp) -> serde_json::Result<Vec<u8>> {
|
||||
serde_json::to_vec_pretty(&prefs_value(app)?)
|
||||
}
|
||||
|
||||
/// [`prefs_bytes`] as JSON.
|
||||
fn prefs_value(app: &VectorcraftApp) -> serde_json::Result<serde_json::Value> {
|
||||
let mut ui = app.ui.clone();
|
||||
ui.engine_prefs = app.session.prefs.to_json();
|
||||
serde_json::to_vec_pretty(&ui)
|
||||
serde_json::to_value(&ui)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
|
||||
use super::{merge_changes, same_lasting};
|
||||
|
||||
/// Two windows open at once (#4625): the one that saves last keeps the other's changes and
|
||||
/// adds its own, instead of putting back the preferences it started from.
|
||||
#[test]
|
||||
fn a_window_saves_only_what_it_changed_over_another_windows_save() {
|
||||
let base = json!({"workspace": "Essentials", "toolbar": true, "engine_prefs": {"uiAccent": "blue", "uiScaling": 1.0}});
|
||||
// The other window switched the workspace and the accent, and saved.
|
||||
let on_disk = json!({"workspace": "Painting", "toolbar": true, "engine_prefs": {"uiAccent": "violet", "uiScaling": 1.0}});
|
||||
// This one changed only the UI scaling.
|
||||
let mine = json!({"workspace": "Essentials", "toolbar": true, "engine_prefs": {"uiAccent": "blue", "uiScaling": 1.25}});
|
||||
let merged = merge_changes(&base, &mine, on_disk);
|
||||
assert_eq!(merged, json!({"workspace": "Painting", "toolbar": true, "engine_prefs": {"uiAccent": "violet", "uiScaling": 1.25}}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_setting_both_windows_changed_takes_the_last_saved() {
|
||||
let base = json!({"workspace": "Essentials", "engine_prefs": {"uiAccent": "blue"}});
|
||||
let on_disk = json!({"workspace": "Painting", "engine_prefs": {"uiAccent": "violet"}});
|
||||
let mine = json!({"workspace": "Typography", "engine_prefs": {"uiAccent": "green"}});
|
||||
assert_eq!(merge_changes(&base, &mine, on_disk), json!({"workspace": "Typography", "engine_prefs": {"uiAccent": "green"}}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fields_added_or_removed_by_this_window_are_saved() {
|
||||
let base = json!({"docking": {"root": 1}, "engine_prefs": {"old": 1}});
|
||||
let on_disk = json!({"docking": {"root": 1}, "recent_files": ["a.svg"], "engine_prefs": {"old": 1}});
|
||||
let mine = json!({"dock_width": 300.0, "engine_prefs": {"new": 2}});
|
||||
assert_eq!(merge_changes(&base, &mine, on_disk), json!({"dock_width": 300.0, "recent_files": ["a.svg"], "engine_prefs": {"new": 2}}));
|
||||
}
|
||||
|
||||
/// The status line and open dialogs reset at start: they don't make a save, and they don't
|
||||
/// replace another window's.
|
||||
#[test]
|
||||
fn what_a_start_resets_is_left_out() {
|
||||
let base = json!({"status": "", "dialog": null, "workspace": "Essentials"});
|
||||
let mine = json!({"status": "Saved", "dialog": {"kind": "preferences"}, "workspace": "Essentials"});
|
||||
assert!(same_lasting(&base, &mine));
|
||||
let on_disk = json!({"status": "Opened", "dialog": null, "workspace": "Painting"});
|
||||
let mine = json!({"status": "Saved", "dialog": {"kind": "preferences"}, "workspace": "Essentials", "toolbar": false});
|
||||
let merged = merge_changes(&base, &mine, on_disk);
|
||||
assert_eq!(merged, json!({"status": "Opened", "dialog": null, "workspace": "Painting", "toolbar": false}));
|
||||
assert!(!same_lasting(&base, &mine));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_is_not_an_object_is_replaced() {
|
||||
let base = json!({"workspace": "Essentials"});
|
||||
let mine = json!({"workspace": "Painting"});
|
||||
assert_eq!(merge_changes(&base, &mine, json!([1, 2])), mine);
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,11 @@
|
||||
# To remove your names, delete your entry (or set fields empty) in a PR. The next
|
||||
# contributors.py run, and the next build, drop them.
|
||||
|
||||
[people.el-j]
|
||||
real_name = "Fabian Althaus"
|
||||
display_name = "faff (el-j)"
|
||||
sync_github_name = false
|
||||
|
||||
[people.lollinoo]
|
||||
sync_github_name = true
|
||||
|
||||
@@ -172,3 +177,6 @@ sync_github_name = false
|
||||
|
||||
[people.krosk93]
|
||||
sync_github_name = true
|
||||
|
||||
[people.ashokram-si]
|
||||
real_name = "Ashok Ram"
|
||||
@@ -441,8 +441,34 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
|
||||
_ => self.warn("layer effects of other kinds (left out)"),
|
||||
}
|
||||
}
|
||||
for a in s.objs(id, b"AdCh") {
|
||||
if let Some(effect) = self.attached_recolor(a) {
|
||||
out.push(effect);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
fn attached_recolor(&mut self, a: ObjId) -> Option<Effect> {
|
||||
let s = self.s;
|
||||
if !s.is(a, b"RcRA") {
|
||||
return None;
|
||||
}
|
||||
if s.bool(a, b"Visi") == Some(false) {
|
||||
return None;
|
||||
}
|
||||
let adjp = s.obj(a, b"AdjP")?;
|
||||
if !s.is(adjp, b"RecP") {
|
||||
return None;
|
||||
}
|
||||
let h = s.f64(adjp, b"RecH").unwrap_or(0.0);
|
||||
let sat = s.f64(adjp, b"RecS").unwrap_or(1.0);
|
||||
let l = s.f64(adjp, b"RecL").unwrap_or(0.5);
|
||||
let (r, g, b) = crate::paint::hsl(h, sat, l);
|
||||
let color = crate::paint::Color::Rgb { r, g, b, a: 1.0 };
|
||||
let opacity = s.f64(a, b"Opac").filter(|v| v.is_finite()).unwrap_or(1.0).clamp(0.0, 1.0);
|
||||
let blend = self.effect_blend(a);
|
||||
Some(Effect::ColorOverlay { color, opacity, blend })
|
||||
}
|
||||
|
||||
/// A layer effect's blend mode (`BlnM`); unknown modes are Normal (warned).
|
||||
fn effect_blend(&mut self, e: ObjId) -> Blend {
|
||||
@@ -479,6 +505,8 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
|
||||
Some(_) => self.warn("several pixel masks on one layer (only the first is used)"),
|
||||
None => {}
|
||||
}
|
||||
} else if class == Tag::of(b"RcRA") {
|
||||
// Handled in `effects` as a colour overlay.
|
||||
} else {
|
||||
self.warn(format!("{} layers attached to other layers (imported without them)", describe(class)));
|
||||
}
|
||||
|
||||
@@ -194,7 +194,7 @@ fn color_within(r: &mut Reader, id: ObjId, depth: u32) -> Option<Color> {
|
||||
})
|
||||
}
|
||||
|
||||
fn hsl(h: f64, s: f64, l: f64) -> (f64, f64, f64) {
|
||||
pub(crate) fn hsl(h: f64, s: f64, l: f64) -> (f64, f64, f64) {
|
||||
let c = (1.0 - (2.0 * l - 1.0).abs()) * s;
|
||||
let hp = (h.rem_euclid(1.0)) * 6.0;
|
||||
let x = c * (1.0 - (hp % 2.0 - 1.0).abs());
|
||||
@@ -355,3 +355,17 @@ pub(crate) fn stroke(r: &mut Reader, pen: ObjId, ldsc: ObjId, local: Affine, beh
|
||||
}
|
||||
Some(Stroke { paint, width, cap, join, miter_limit, align, dash, behind })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn hsl_lightness_1_is_white_and_0_is_black() {
|
||||
assert_eq!(hsl(0.0, 1.0, 1.0), (1.0, 1.0, 1.0));
|
||||
assert_eq!(hsl(0.5, 1.0, 1.0), (1.0, 1.0, 1.0));
|
||||
assert_eq!(hsl(0.0, 1.0, 0.0), (0.0, 0.0, 0.0));
|
||||
let (r, g, b) = hsl(0.0, 1.0, 0.5);
|
||||
assert!((r - 1.0).abs() < 1e-6 && g.abs() < 1e-6 && b.abs() < 1e-6);
|
||||
}
|
||||
}
|
||||
+34
-10
@@ -27,10 +27,16 @@ fn near(a: f64, b: f64, tol: f64) -> bool {
|
||||
(a - b).abs() <= tol
|
||||
}
|
||||
|
||||
/// Points along every outline under `n`, its anchors among them. Bent art keeps its curves and
|
||||
/// long lines since #3926, so its anchors alone no longer trace it.
|
||||
fn all_points(n: &Node, out: &mut Vec<Point>) {
|
||||
n.walk(&mut |c| {
|
||||
if let Some(p) = c.path_data() {
|
||||
out.extend(p.anchors().map(|(_, _, a)| a.p));
|
||||
for sp in c.path_data().into_iter().flat_map(|p| &p.subpaths) {
|
||||
out.extend(sp.anchors.iter().map(|a| a.p));
|
||||
for i in 0..sp.segment_count() {
|
||||
let seg = sp.segment(i);
|
||||
out.extend((1..32).map(|j| kurbo::ParamCurve::eval(&seg, j as f64 / 32.0)));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -185,9 +191,12 @@ fn art_brush_follows_curves() {
|
||||
}
|
||||
}
|
||||
let out = stroke_pieces(&Document::new(1.0, 1.0), &art_brush(rect_art(10.0, 4.0), ArtScale::Stretch), &bp_open, &stroke(1.0));
|
||||
// The long edges bend as curves (#3926), where they used to be cut into some 400 chords. The
|
||||
// path is run along in 0.05 pt chords, which the curves follow, so a few dozen remain.
|
||||
let (anchors, curved) = anchors_and_curved(&out[0]);
|
||||
assert!(anchors < 100 && curved > anchors / 2, "long edges bend as curves: {curved} of {anchors} anchors with handles");
|
||||
let mut pts = vec![];
|
||||
all_points(&out[0], &mut pts);
|
||||
assert!(pts.len() > 40, "long edges are subdivided so they bend: {}", pts.len());
|
||||
for p in pts {
|
||||
let r = p.distance(Point::new(100.0, 100.0));
|
||||
assert!((r - 100.0).abs() <= 2.0 + 0.3, "point {p:?} is {r} from the centre");
|
||||
@@ -1226,11 +1235,12 @@ fn a_pattern_tile_keeps_its_curves_on_a_straight_path() {
|
||||
assert!(near(b.height(), 40.0, 1.0), "and still stand the tile's height: {}", b.height());
|
||||
}
|
||||
|
||||
/// The other half of the same behaviour: where the path really does bend, the tile is still
|
||||
/// subdivided, because an affine cannot reproduce a bend. The fit is checked before it is used,
|
||||
/// so a bent run falls back to exactly what it did before.
|
||||
/// The other half of the same behaviour: where the path really does bend, an affine cannot
|
||||
/// reproduce the bend, so the tile is bent, and it still comes out as curves: cubics fitted to the
|
||||
/// bent art rather than the chords it used to be flattened into (#3926). Here a 4-anchor circle
|
||||
/// tile runs round a circle of radius 200, so its outline stays in the band 20 either side of it.
|
||||
#[test]
|
||||
fn a_pattern_tile_on_a_bent_path_is_still_subdivided() {
|
||||
fn a_pattern_tile_on_a_bent_path_keeps_its_curves() {
|
||||
let circle =
|
||||
Node::path(NodeId(0), shapes::ellipse(Rect::new(0.0, -20.0, 40.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
|
||||
let brush = Brush {
|
||||
@@ -1240,9 +1250,23 @@ fn a_pattern_tile_on_a_bent_path_is_still_subdivided() {
|
||||
// A circle to run along: every tile sits on a curving section.
|
||||
let round = shapes::ellipse(Rect::new(0.0, 0.0, 400.0, 400.0)).to_bezpath();
|
||||
let out = stroke_pieces(&Document::new(1.0, 1.0), &brush, &round, &stroke(1.0));
|
||||
assert!(!out.is_empty());
|
||||
let bent = out.iter().filter(|n| anchors_and_curved(n).0 > 8).count();
|
||||
assert!(bent > out.len() / 2, "tiles on a bend are still densified: {bent} of {}", out.len());
|
||||
assert!(out.len() > 20, "tiles all the way round: {}", out.len());
|
||||
let (mut lo, mut hi) = (f64::MAX, f64::MIN);
|
||||
for n in &out {
|
||||
let (anchors, curved) = anchors_and_curved(n);
|
||||
assert!((4..=16).contains(&anchors), "a bent circle tile is a few curves, not a polygon: {anchors} anchors");
|
||||
assert!(curved == anchors, "every anchor keeps a handle: {curved} of {anchors}");
|
||||
let mut pts = vec![];
|
||||
all_points(n, &mut pts);
|
||||
for q in pts {
|
||||
let r = q.distance(Point::new(200.0, 200.0));
|
||||
(lo, hi) = (lo.min(r), hi.max(r));
|
||||
}
|
||||
}
|
||||
// The path is a cubic circle (0.06 out at most) run along in chords of 0.05, and the fit holds
|
||||
// a quarter of the 0.25 flattening tolerance, so the band holds to 0.2.
|
||||
assert!(lo > 179.8 && hi < 220.2, "the curves stay in the tile's band round the path: {lo:.3}..{hi:.3}");
|
||||
assert!(lo < 180.2 && hi > 219.8, "and reach both edges of it: {lo:.3}..{hi:.3}");
|
||||
}
|
||||
|
||||
/// The kind of every node in a piece of brushed art, in paint order.
|
||||
|
||||
+268
-56
@@ -1,13 +1,15 @@
|
||||
//! Art, scatter and pattern brushes: art bent along the path by arc length.
|
||||
//!
|
||||
//! Art coordinates `(x, y)` map to the path point at arc length `s(x)` offset by
|
||||
//! `(y - centre) × cross` along the path's left normal. Art outlines are flattened and
|
||||
//! subdivided first so long straight edges bend with the path instead of cutting chords.
|
||||
//! `(y - centre) × cross` along the path's left normal. Art outlines come out as cubics fitted
|
||||
//! to the bent art, so curves stay curves and long straight edges bend with the path (#3926);
|
||||
//! where that would take more anchors than chords, they are flattened and subdivided instead.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use kurbo::ParamCurveNearest;
|
||||
use vectorcraft_doc::{Appearance, Node, NodeId, NodeKind, PressureProfile};
|
||||
use vectorcraft_geom::{Affine, BezPath, PathData, PathEl, Point, Rect, SubPath, Vec2};
|
||||
use vectorcraft_geom::{Affine, BezPath, CubicBez, ParamCurve, PathData, PathEl, Point, Rect, SubPath, Vec2};
|
||||
|
||||
use crate::track::{Rng, Track, normal, seed_of, tracks};
|
||||
use crate::{ArtBrush, ArtScale, CornerSource, Direction, PatternBrush, PatternFit, Scatter, Variation, tolerance};
|
||||
@@ -34,22 +36,26 @@ const MAX_WALK: usize = 10_000;
|
||||
/// Points on each side of the box an Auto-Sliced pattern brush corner masks its tiles with.
|
||||
const MASK_STEPS: usize = 32;
|
||||
|
||||
/// Bend every path under `n` through `f`. Paths are flattened with `flat_tol` (art space) and
|
||||
/// segments subdivided so none is longer than `max_du` along x. Stroke widths scale by
|
||||
/// `width_scale`. Text, images and symbol instances can't bend and are dropped.
|
||||
pub(crate) fn warp_node(n: &Node, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64, width_scale: f64) -> Option<Node> {
|
||||
/// Bend every path under `n` through `f`. Each art segment comes out as cubics that follow it
|
||||
/// through the bend to within [`fit_tol`] of `doc_tol`, the flattening tolerance in document
|
||||
/// space, so the art keeps its curves (#3926). Where that cannot be done in no more anchors than
|
||||
/// chords would take, the path is flattened with `flat_tol` (art space) and subdivided so no chord
|
||||
/// is longer than `max_du` along x, as it always was. Stroke widths scale by `width_scale`.
|
||||
/// Text, images and symbol instances can't bend and are dropped.
|
||||
pub(crate) fn warp_node(n: &Node, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64, doc_tol: f64, width_scale: f64) -> Option<Node> {
|
||||
let mut out = n.clone();
|
||||
out.appearance.scale_strokes(width_scale);
|
||||
match &mut out.kind {
|
||||
NodeKind::Path { path, live, .. } => {
|
||||
*live = None;
|
||||
*path = warp_path(path, f, flat_tol, max_du);
|
||||
*path = warp_path(path, f, flat_tol, max_du, fit_tol(doc_tol));
|
||||
if path.is_empty() {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } | NodeKind::Compound { children, .. } => {
|
||||
let kids: Vec<Arc<Node>> = children.iter().filter_map(|c| warp_node(c, f, flat_tol, max_du, width_scale)).map(Arc::new).collect();
|
||||
let kids: Vec<Arc<Node>> =
|
||||
children.iter().filter_map(|c| warp_node(c, f, flat_tol, max_du, doc_tol, width_scale)).map(Arc::new).collect();
|
||||
if kids.is_empty() {
|
||||
return None;
|
||||
}
|
||||
@@ -60,54 +66,156 @@ pub(crate) fn warp_node(n: &Node, f: &dyn Fn(Point) -> Point, flat_tol: f64, max
|
||||
Some(out)
|
||||
}
|
||||
|
||||
fn warp_path(p: &PathData, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64) -> PathData {
|
||||
let bp = p.to_bezpath();
|
||||
/// Each subpath of `p` through `f`: fitted cubics when they take no more anchors than the chords
|
||||
/// would, else the chords. Points `f` cannot place (not finite) are left out of the chords.
|
||||
fn warp_path(p: &PathData, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64, fit_tol: f64) -> PathData {
|
||||
let mut subs = vec![];
|
||||
let mut cur: Vec<Point> = vec![];
|
||||
let mut els = vec![];
|
||||
kurbo::flatten(bp.iter(), flat_tol.max(1e-4), |e| els.push(e));
|
||||
let finish = |cur: &mut Vec<Point>, closed: bool, subs: &mut Vec<SubPath>| {
|
||||
let pts = std::mem::take(cur);
|
||||
if pts.len() < 2 {
|
||||
return;
|
||||
for sp in &p.subpaths {
|
||||
let Some(dense) = densified(sp, flat_tol, max_du) else { continue };
|
||||
if let Some(fit) = fitted(sp, f, fit_tol, dense.len()) {
|
||||
subs.push(fit);
|
||||
continue;
|
||||
}
|
||||
let mut dense = vec![pts[0]];
|
||||
let n = pts.len();
|
||||
let segs = if closed { n } else { n - 1 };
|
||||
for i in 0..segs {
|
||||
let (a, b) = (pts[i], pts[(i + 1) % n]);
|
||||
let k = (((b.x - a.x).abs() / max_du).ceil() as usize).clamp(1, MAX_SUB);
|
||||
for j in 1..=k {
|
||||
let q = a.lerp(b, j as f64 / k as f64);
|
||||
if closed && i == segs - 1 && j == k {
|
||||
break;
|
||||
}
|
||||
dense.push(q);
|
||||
}
|
||||
}
|
||||
let mapped: Vec<Point> = dense.into_iter().map(f).collect();
|
||||
subs.push(SubPath::polyline(&mapped, closed));
|
||||
};
|
||||
for e in els {
|
||||
match e {
|
||||
PathEl::MoveTo(q) => {
|
||||
finish(&mut cur, false, &mut subs);
|
||||
cur.push(q);
|
||||
}
|
||||
PathEl::LineTo(q) => cur.push(q),
|
||||
PathEl::ClosePath => {
|
||||
if cur.len() > 1 && cur[0].distance(cur[cur.len() - 1]) < 1e-9 {
|
||||
cur.pop();
|
||||
}
|
||||
finish(&mut cur, true, &mut subs);
|
||||
}
|
||||
_ => {}
|
||||
let mapped: Vec<Point> = dense.into_iter().map(f).filter(|q| q.is_finite()).collect();
|
||||
if mapped.len() >= 2 {
|
||||
subs.push(SubPath::polyline(&mapped, sp.closed));
|
||||
}
|
||||
}
|
||||
finish(&mut cur, false, &mut subs);
|
||||
PathData::new(subs)
|
||||
}
|
||||
|
||||
/// `sp` flattened with `flat_tol` and its chords subdivided so none is longer than `max_du` along
|
||||
/// x, in art space: the points the chord route maps. `None` below two points.
|
||||
fn densified(sp: &SubPath, flat_tol: f64, max_du: f64) -> Option<Vec<Point>> {
|
||||
let mut bp = BezPath::new();
|
||||
sp.to_bezpath_into(&mut bp);
|
||||
let mut pts = vec![];
|
||||
kurbo::flatten(bp.iter(), flat_tol.max(1e-4), |e| {
|
||||
if let PathEl::MoveTo(q) | PathEl::LineTo(q) = e {
|
||||
pts.push(q);
|
||||
}
|
||||
});
|
||||
if sp.closed && pts.len() > 1 && pts.first()?.distance(*pts.last()?) < 1e-9 {
|
||||
pts.pop();
|
||||
}
|
||||
if pts.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
let segs = if sp.closed { pts.len() } else { pts.len() - 1 };
|
||||
let mut dense = vec![*pts.first()?];
|
||||
for (i, (&a, &b)) in pts.iter().zip(pts.iter().cycle().skip(1)).take(segs).enumerate() {
|
||||
let k = (((b.x - a.x).abs() / max_du).ceil() as usize).clamp(1, MAX_SUB);
|
||||
for j in 1..=k {
|
||||
if sp.closed && i == segs - 1 && j == k {
|
||||
break;
|
||||
}
|
||||
dense.push(a.lerp(b, j as f64 / k as f64));
|
||||
}
|
||||
}
|
||||
Some(dense)
|
||||
}
|
||||
|
||||
/// Times an art segment is halved at most while looking for cubics that fit it.
|
||||
const FIT_DEPTH: u32 = 12;
|
||||
/// Parameter step of the finite differences that stand in for the bend's derivative.
|
||||
const FIT_DT: f64 = 1e-6;
|
||||
/// Sections a fitted piece is checked at the ends of (the ends themselves are exact).
|
||||
const FIT_CHECKS: usize = 8;
|
||||
/// Share of the flattening tolerance the fitted curves hold to. The chords were exact at their
|
||||
/// points and a few hundredths off between them, so a straight edge bends about as closely.
|
||||
const FIT_SHARE: f64 = 0.25;
|
||||
/// Tolerance paths are flattened to before art is laid along them.
|
||||
const TRACK_TOL: f64 = 0.05;
|
||||
|
||||
/// The distance (document space) fitted curves keep to the bent art, for flattening tolerance
|
||||
/// `doc_tol`: never below [`TRACK_TOL`], since following the flattened path more closely than it
|
||||
/// follows the real one only traces its chords.
|
||||
fn fit_tol(doc_tol: f64) -> f64 {
|
||||
(doc_tol * FIT_SHARE).max(TRACK_TOL)
|
||||
}
|
||||
|
||||
/// `sp` through `f` as cubics within `tol` (document space), one or more per art segment so its
|
||||
/// anchors, corners included, stay anchors. `None` when that takes more than `most` anchors, when
|
||||
/// a piece still does not fit after [`FIT_DEPTH`] halvings, or when `f` cannot place a point.
|
||||
///
|
||||
/// Each piece is the cubic with the bent piece's ends and their derivatives, which is the piece
|
||||
/// itself where the bend is affine and converges fast where it is not. It is checked against the
|
||||
/// bend at the same parameters, so the distance measured is never less than the true one. The
|
||||
/// halving is our own rather than kurbo's `fit_to_bezpath`, which halves until the floats run out
|
||||
/// on a map that never fits; the depth and the anchor count bound this one.
|
||||
fn fitted(sp: &SubPath, f: &dyn Fn(Point) -> Point, tol: f64, most: usize) -> Option<SubPath> {
|
||||
if !(tol.is_finite() && tol > 0.0) {
|
||||
return None;
|
||||
}
|
||||
let start = f(sp.anchors.first()?.p);
|
||||
if !start.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to(start);
|
||||
// Pieces allowed: an open subpath's first anchor is one more, a closed one's last piece ends on it.
|
||||
let mut room = if sp.closed { most } else { most.checked_sub(1)? };
|
||||
for i in 0..sp.segment_count() {
|
||||
let c = sp.segment(i);
|
||||
let line = sp.segment_is_line(i);
|
||||
// A line's handles sit on its ends, which stalls its parameter there; thirds keep it even.
|
||||
let c = if line { CubicBez::new(c.p0, c.p0.lerp(c.p3, 1.0 / 3.0), c.p0.lerp(c.p3, 2.0 / 3.0), c.p3) } else { c };
|
||||
let at = |t: f64| Some(f(c.eval(t))).filter(|q| q.is_finite());
|
||||
fit_into(&at, (0.0, 1.0), line, tol, FIT_DEPTH, &mut bp, &mut room)?;
|
||||
}
|
||||
if sp.closed {
|
||||
bp.close_path();
|
||||
}
|
||||
// The last piece ends on the first anchor's image, so a closed subpath merges it back in; the
|
||||
// count is checked again for a map that jumps right there and keeps the two apart.
|
||||
PathData::from_bezpath(&bp).subpaths.into_iter().next().filter(|s| s.anchors.len() <= most)
|
||||
}
|
||||
|
||||
/// Pieces for parameters `t0..t1` of the bent segment `at` onto `bp`, which ends at `at(t0)`:
|
||||
/// halved until each is within `tol`, at most `depth` times and `room` pieces. A `line` that is
|
||||
/// still straight within `tol` stays a line.
|
||||
fn fit_into(
|
||||
at: &dyn Fn(f64) -> Option<Point>,
|
||||
(t0, t1): (f64, f64),
|
||||
line: bool,
|
||||
tol: f64,
|
||||
depth: u32,
|
||||
bp: &mut BezPath,
|
||||
room: &mut usize,
|
||||
) -> Option<()> {
|
||||
let span = t1 - t0;
|
||||
let (p0, p3) = (at(t0)?, at(t1)?);
|
||||
// Derivatives read from inside the piece, so a kink at either end (a corner, a turn of the
|
||||
// track) stays one.
|
||||
let d0 = (at(t0 + FIT_DT)? - p0) * (span / FIT_DT);
|
||||
let d1 = (p3 - at(t1 - FIT_DT)?) * (span / FIT_DT);
|
||||
let c = CubicBez::new(p0, p0 + d0 / 3.0, p3 - d1 / 3.0, p3);
|
||||
let chord = kurbo::Line::new(p0, p3);
|
||||
let (mut curve_fits, mut line_fits) = (c.is_finite(), line);
|
||||
for k in 1..FIT_CHECKS {
|
||||
if !(curve_fits || line_fits) {
|
||||
break;
|
||||
}
|
||||
let u = k as f64 / FIT_CHECKS as f64;
|
||||
let q = at(t0 + span * u)?;
|
||||
curve_fits &= q.distance(c.eval(u)) <= tol;
|
||||
line_fits &= chord.nearest(q, 1e-9).distance_sq <= tol * tol;
|
||||
}
|
||||
if line_fits || curve_fits {
|
||||
*room = room.checked_sub(1)?;
|
||||
if line_fits {
|
||||
bp.line_to(p3);
|
||||
} else {
|
||||
bp.curve_to(c.p1, c.p2, p3);
|
||||
}
|
||||
return Some(());
|
||||
}
|
||||
let depth = depth.checked_sub(1)?;
|
||||
let mid = t0 + span / 2.0;
|
||||
fit_into(at, (t0, mid), line, tol, depth, bp, room)?;
|
||||
fit_into(at, (mid, t1), line, tol, depth, bp, room)
|
||||
}
|
||||
|
||||
/// Art turned so it runs left → right, flipped as requested; returns it with its bounds.
|
||||
fn oriented(art: &Node, dir: Direction, flip_along: bool, flip_across: bool) -> Option<(Node, Rect)> {
|
||||
let mut a = art.clone();
|
||||
@@ -281,7 +389,7 @@ fn bend(t: &Track, art: &Node, b: Rect, along: AlongMap, cross: f64) -> Option<N
|
||||
{
|
||||
return affine_node(art, a, cross.abs());
|
||||
}
|
||||
warp_node(art, &f, flat_tol, MAX_SEG / along.max_scale(), cross.abs())
|
||||
warp_node(art, &f, flat_tol, MAX_SEG / along.max_scale(), flat_tol * scale, cross.abs())
|
||||
}
|
||||
|
||||
/// [`bend`], with the cross scale at arc length `s` multiplied by `widen(s)` (0..=1). The strokes
|
||||
@@ -297,7 +405,7 @@ fn bend_widened(t: &Track, art: &Node, b: Rect, along: AlongMap, cross: f64, wid
|
||||
let art = widen_strokes(art, &factor);
|
||||
let scale = along.max_scale().max(cross.abs()).max(1e-6);
|
||||
let flat_tol = tolerance(b.height().max(b.width()) * scale) / scale;
|
||||
warp_node(&art, &f, flat_tol, MAX_SEG / along.max_scale(), cross.abs())
|
||||
warp_node(&art, &f, flat_tol, MAX_SEG / along.max_scale(), flat_tol * scale, cross.abs())
|
||||
}
|
||||
|
||||
/// `n` with the strokes of it and of everything inside it scaled by `factor` of the object they
|
||||
@@ -377,7 +485,7 @@ pub(crate) fn art(a: &ArtBrush, bp: &BezPath, weight: f64, pressure: Option<&Pre
|
||||
let width = light.max(heavy);
|
||||
let cross = weight * width / 100.0;
|
||||
let mut out = vec![];
|
||||
for t in tracks(bp, 0.05) {
|
||||
for t in tracks(bp, TRACK_TOL) {
|
||||
let l = t.len();
|
||||
if l <= 1e-9 {
|
||||
continue;
|
||||
@@ -419,7 +527,7 @@ pub(crate) fn scatter(sc: &Scatter, bp: &BezPath, weight: f64, pressure: Option<
|
||||
let mut rng = Rng::new(seed_of(bp, name));
|
||||
let [size_mode, spacing_mode, scatter_mode, rotation_mode] = sc.modes();
|
||||
let mut out = Budget::default();
|
||||
for t in tracks(bp, 0.05) {
|
||||
for t in tracks(bp, TRACK_TOL) {
|
||||
if out.full() {
|
||||
break;
|
||||
}
|
||||
@@ -588,7 +696,7 @@ fn auto_corner(t: &Track, i: usize, source: CornerSource, side: &(Node, Rect), k
|
||||
}
|
||||
let s = if tw > 1e-9 { len / tw } else { 1.0 };
|
||||
let max_du = MAX_SEG / (2.0 * k * s.max(1.0));
|
||||
let warp = |f: &dyn Fn(Point) -> Point| warp_node(art, f, flat_tol, max_du, k);
|
||||
let warp = |f: &dyn Fn(Point) -> Point| warp_node(art, f, flat_tol, max_du, flat_tol * k, k);
|
||||
// Art point → (distance along from the left edge, stretched to `len`, and offset across).
|
||||
let along = move |q: Point| {
|
||||
let (x, y) = local(q);
|
||||
@@ -686,7 +794,7 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec<Node>
|
||||
let outer_tile = outer.as_ref().map(Corner::Art).or(pb.outer_source.map(Corner::Source));
|
||||
let inner_tile = inner.as_ref().map(Corner::Art).or(pb.inner_source.map(Corner::Source));
|
||||
let mut out = Budget::default();
|
||||
for t in tracks(bp, 0.05) {
|
||||
for t in tracks(bp, TRACK_TOL) {
|
||||
if out.full() {
|
||||
break;
|
||||
}
|
||||
@@ -921,4 +1029,108 @@ mod tests {
|
||||
let moved = bend(&straight, &circle, b, along, cross).expect("the straight run still draws something");
|
||||
assert_eq!(anchors(&moved), 4, "the straight run keeps the tile's curves");
|
||||
}
|
||||
|
||||
/// A 4-anchor circle tile filling `b`.
|
||||
fn circle_tile(b: Rect) -> Node {
|
||||
Node::path(
|
||||
NodeId(0),
|
||||
vectorcraft_geom::shapes::ellipse(b),
|
||||
Appearance::basic(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), vectorcraft_color::Paint::None, 0.0),
|
||||
)
|
||||
}
|
||||
|
||||
/// `per` points along each segment of `sp`, through `f`.
|
||||
fn traced(sp: &SubPath, f: &dyn Fn(Point) -> Point, per: usize) -> Vec<Point> {
|
||||
(0..sp.segment_count())
|
||||
.flat_map(|i| {
|
||||
let c = sp.segment(i);
|
||||
(0..per).map(move |j| f(c.eval(j as f64 / per as f64)))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// How far apart two closed outlines get (Hausdorff distance, each taken as a polygon).
|
||||
fn apart(a: &[Point], b: &[Point]) -> f64 {
|
||||
let to = |q: Point, pts: &[Point]| {
|
||||
pts.iter()
|
||||
.zip(pts.iter().cycle().skip(1))
|
||||
.map(|(&a, &b)| {
|
||||
let ab = b - a;
|
||||
let t = ((q - a).dot(ab) / ab.hypot2().max(1e-18)).clamp(0.0, 1.0);
|
||||
q.distance(a + ab * t)
|
||||
})
|
||||
.fold(f64::MAX, f64::min)
|
||||
};
|
||||
let one_way = |a: &[Point], b: &[Point]| a.iter().map(|&q| to(q, b)).fold(0.0, f64::max);
|
||||
one_way(a, b).max(one_way(b, a))
|
||||
}
|
||||
|
||||
/// #3926: on a bend the tile is fitted with cubics instead of flattened into chords. A circle
|
||||
/// tile bent round a circle stays a handful of smooth curves, closer to the bent art than the
|
||||
/// chords were, in a small fraction of their anchors.
|
||||
#[test]
|
||||
fn a_circle_tile_bent_round_a_circle_stays_a_few_curves() {
|
||||
let round = vectorcraft_geom::shapes::ellipse(Rect::new(0.0, 0.0, 400.0, 400.0)).to_bezpath();
|
||||
let t = tracks(&round, 0.05).remove(0);
|
||||
let b = Rect::new(0.0, -20.0, 40.0, 20.0);
|
||||
let along = AlongMap::linear(b.width(), 100.0, 140.0);
|
||||
let tile = circle_tile(b);
|
||||
let NodeKind::Path { path: art, .. } = &tile.kind else { panic!("the tile is a path") };
|
||||
let art = &art.subpaths[0];
|
||||
|
||||
let bent = bend(&t, &tile, b, along, 1.0).expect("the tile is drawn");
|
||||
let NodeKind::Path { path, .. } = &bent.kind else { panic!("a bent path is a path") };
|
||||
assert_eq!(path.subpaths.len(), 1);
|
||||
let sp = &path.subpaths[0];
|
||||
assert!(sp.closed, "still a closed outline");
|
||||
let n = sp.anchors.len();
|
||||
assert!((4..=16).contains(&n), "a few anchors, the tile's own four among them: {n}");
|
||||
assert!(sp.anchors.iter().all(|a| a.has_in() && a.has_out()), "every anchor keeps both handles");
|
||||
assert!(sp.anchors.first().map(|a| a.p) != sp.anchors.last().map(|a| a.p), "closed without a duplicate anchor");
|
||||
|
||||
// The same map `bend` uses, at scale 1, and the tolerance it fits to.
|
||||
let (cy, x0) = (b.center().y, b.x0);
|
||||
let f = |p: Point| t.map(along.at(p.x - x0), p.y - cy);
|
||||
let tol = tolerance(b.height().max(b.width()));
|
||||
let exact = traced(art, &f, 1000);
|
||||
let chords: Vec<Point> = densified(art, tol, MAX_SEG).expect("the tile flattens").into_iter().map(f).collect();
|
||||
let curves = traced(sp, &|p| p, 200);
|
||||
let (e_curves, e_chords) = (apart(&curves, &exact), apart(&chords, &exact));
|
||||
// Checked at eight points a piece, so a little room between them.
|
||||
assert!(e_curves <= fit_tol(tol) * 1.5, "the curves follow the bent art within {}: {e_curves:.4}", fit_tol(tol));
|
||||
assert!(e_curves < e_chords, "closer than the chords were: {e_curves:.4} against {e_chords:.4}");
|
||||
assert!(chords.len() >= 4 * n, "far fewer anchors than the {} chords took: {n}", chords.len());
|
||||
}
|
||||
|
||||
/// Fitting is bounded however badly the map behaves: where it gives points that are not finite
|
||||
/// the tile falls back to chords with those points left out (or to nothing), and where it never
|
||||
/// fits (a map that jumps everywhere) the halving stops at its depth and anchor count. Either
|
||||
/// way the call comes back promptly with finite geometry.
|
||||
#[test]
|
||||
fn a_map_that_misbehaves_still_returns_promptly_and_finite() {
|
||||
let b = Rect::new(0.0, -20.0, 40.0, 20.0);
|
||||
let tile = circle_tile(b);
|
||||
let finite = |n: &Node| match &n.kind {
|
||||
NodeKind::Path { path, .. } => {
|
||||
path.subpaths.iter().flat_map(|s| &s.anchors).all(|a| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite())
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
let maps: [&dyn Fn(Point) -> Point; 4] = [
|
||||
&|p| if p.x > 25.0 { Point::new(f64::NAN, p.y) } else { p },
|
||||
&|p| if p.y > 10.0 { Point::new(f64::INFINITY, p.y) } else { p + Vec2::new(p.x.sin(), 0.0) },
|
||||
&|p| Point::new(p.x, p.y + if (p.x * 1e3).sin() > 0.0 { 5.0 } else { 0.0 }),
|
||||
&|_| Point::new(f64::NAN, f64::NAN),
|
||||
];
|
||||
for (i, f) in maps.iter().enumerate() {
|
||||
let t0 = std::time::Instant::now();
|
||||
let out = warp_node(&tile, f, 0.25, 1.5, 0.25, 1.0);
|
||||
assert!(t0.elapsed() < std::time::Duration::from_secs(2), "map {i} took {:?}", t0.elapsed());
|
||||
match (i, &out) {
|
||||
(3, out) => assert!(out.is_none(), "a map that places nothing draws nothing"),
|
||||
(_, Some(n)) => assert!(finite(n), "map {i} drew non-finite geometry"),
|
||||
(_, None) => panic!("map {i} places most points, so something is drawn"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+11
-1
@@ -196,7 +196,11 @@ pub fn lerp_paint(a: &Paint, b: &Paint, t: f32) -> Paint {
|
||||
/// so dashes open out of a solid line; patterns of different lengths repeat to a common one.
|
||||
fn lerp_dash(x: Option<&Dash>, y: Option<&Dash>, t: f64) -> Option<Dash> {
|
||||
let solid_like = |d: &Dash| Dash {
|
||||
pattern: d.pattern.chunks(2).flat_map(|c| [c.iter().sum::<f64>(), 0.0]).take(d.pattern.len().max(2)).collect(),
|
||||
// An odd pattern repeats twice per period, so pair up the doubled one to keep every gap closed.
|
||||
pattern: if d.pattern.len() % 2 == 1 { d.pattern.repeat(2) } else { d.pattern.clone() }
|
||||
.chunks(2)
|
||||
.flat_map(|c| [c.iter().sum::<f64>(), 0.0])
|
||||
.collect(),
|
||||
offset: d.offset,
|
||||
align_corners: d.align_corners,
|
||||
};
|
||||
@@ -1423,6 +1427,12 @@ mod tests {
|
||||
assert_eq!(p.at(0.5), (1.0, 1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn odd_dash_blends_to_solid_with_closed_gaps() {
|
||||
let d = lerp_dash(Some(&Dash { pattern: vec![2.0, 3.0, 4.0], ..Default::default() }), None, 1.0).unwrap();
|
||||
assert!(d.pattern.iter().skip(1).step_by(2).all(|g| *g == 0.0), "{:?}", d.pattern);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copied_steps_get_new_members() {
|
||||
let rect = |x: f64| Arc::new(Node::path(NodeId(7), shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0)), Appearance::default()));
|
||||
|
||||
@@ -125,7 +125,7 @@ pub fn oversized_tiff(bytes: &[u8]) -> Option<(u32, u32)> {
|
||||
}
|
||||
|
||||
/// The color type of TIFF `bytes` and its decoder; `None` for [`oversized_tiff`] images too.
|
||||
fn tiff(bytes: &[u8]) -> Option<(tiff::ColorType, tiff::decoder::Decoder<Cursor<&[u8]>>)> {
|
||||
pub(crate) fn tiff(bytes: &[u8]) -> Option<(tiff::ColorType, tiff::decoder::Decoder<Cursor<&[u8]>>)> {
|
||||
if !is_tiff(bytes) || oversized_tiff(bytes).is_some() {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
//! Compound shapes (Pathfinder panel › Make Compound Shape): a group whose members each have a
|
||||
//! shape mode. It draws as the one area the modes make, from the backmost member up, painted with
|
||||
//! the group's own appearance; the members stay editable. Evaluated in `vectorcraft-effects`.
|
||||
|
||||
use serde::{Deserialize, Deserializer, Serialize};
|
||||
|
||||
use crate::{Node, NodeKind};
|
||||
|
||||
/// How a compound shape's member combines with the area of the members below it. The backmost
|
||||
/// member's mode does not matter: it starts the area.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ShapeMode {
|
||||
/// Adds the member's area.
|
||||
#[default]
|
||||
Add,
|
||||
/// Takes the member's area away.
|
||||
Subtract,
|
||||
/// Keeps only what the member's area overlaps.
|
||||
Intersect,
|
||||
/// Keeps where exactly one of the area and the member's area is.
|
||||
Exclude,
|
||||
}
|
||||
|
||||
impl ShapeMode {
|
||||
/// Every mode, in the Pathfinder panel's order.
|
||||
pub const ALL: [ShapeMode; 4] = [ShapeMode::Add, ShapeMode::Subtract, ShapeMode::Intersect, ShapeMode::Exclude];
|
||||
|
||||
/// The mode's name in commands and files.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
ShapeMode::Add => "add",
|
||||
ShapeMode::Subtract => "subtract",
|
||||
ShapeMode::Intersect => "intersect",
|
||||
ShapeMode::Exclude => "exclude",
|
||||
}
|
||||
}
|
||||
|
||||
/// The mode named `s` ([`ShapeMode::name`]).
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|m| m.name() == s)
|
||||
}
|
||||
}
|
||||
|
||||
/// Files are untrusted: a mode that isn't one of the names reads as Add.
|
||||
impl<'de> Deserialize<'de> for ShapeMode {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let v = serde_json::Value::deserialize(d)?;
|
||||
Ok(v.as_str().and_then(ShapeMode::parse).unwrap_or_default())
|
||||
}
|
||||
}
|
||||
|
||||
impl Node {
|
||||
/// Is this a compound shape? Only a group that doesn't clip can be one: the mark on anything
|
||||
/// else (from a file) is ignored.
|
||||
pub fn is_compound_shape(&self) -> bool {
|
||||
matches!(self.kind, NodeKind::Group { clip: false, .. }) && self.extras().compound_shape
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn modes_read_back_and_unknown_ones_are_add() {
|
||||
for m in ShapeMode::ALL {
|
||||
let v = serde_json::to_value(m).unwrap();
|
||||
assert_eq!(v, serde_json::json!(m.name()));
|
||||
assert_eq!(serde_json::from_value::<ShapeMode>(v).unwrap(), m);
|
||||
}
|
||||
for v in [serde_json::json!("divide"), serde_json::json!(3), serde_json::json!(null), serde_json::json!({"a": [1]})] {
|
||||
assert_eq!(serde_json::from_value::<ShapeMode>(v).unwrap(), ShapeMode::Add);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -109,9 +109,9 @@ fn visit_paint(p: &mut Paint, f: &mut ColorVisitor) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Visit every colour of a node tree (fills, strokes, gradient stops, text runs, mesh points, not
|
||||
/// opacity masks) with its swatch link and tint. Mesh points have no link: changes to it are
|
||||
/// dropped.
|
||||
/// Visit every colour of a node tree (fills, strokes, gradient stops, text runs, mesh points, an
|
||||
/// image's colorize color, not opacity masks) with its swatch link and tint. Mesh points have no
|
||||
/// link: changes to it are dropped.
|
||||
pub fn visit_node_colors(n: &mut Node, f: &mut ColorVisitor) {
|
||||
for it in &mut n.appearance.items {
|
||||
match it {
|
||||
@@ -119,6 +119,9 @@ pub fn visit_node_colors(n: &mut Node, f: &mut ColorVisitor) {
|
||||
AppearanceItem::Stroke(l) => visit_paint(&mut l.paint, f),
|
||||
}
|
||||
}
|
||||
if let Some(p) = n.extras.0.as_deref_mut().and_then(|e| e.colorize.as_deref_mut()) {
|
||||
visit_paint(p, f);
|
||||
}
|
||||
match &mut n.kind {
|
||||
NodeKind::Text(t) => {
|
||||
for r in &mut t.runs {
|
||||
|
||||
@@ -11,6 +11,7 @@ pub mod blend;
|
||||
pub mod cancel;
|
||||
pub mod clipnest;
|
||||
pub mod cmyk;
|
||||
pub mod compound_shape;
|
||||
pub mod corners;
|
||||
pub mod depth;
|
||||
pub mod dimension;
|
||||
@@ -42,7 +43,7 @@ pub mod overprint;
|
||||
pub mod pattern;
|
||||
pub mod perspective;
|
||||
mod pixels;
|
||||
pub use pixels::MAX_RASTER_ALLOC;
|
||||
pub use pixels::{GraySource, MAX_RASTER_ALLOC};
|
||||
pub mod placed_document;
|
||||
pub mod plugin_data;
|
||||
pub mod profiles;
|
||||
@@ -76,6 +77,7 @@ pub use appearance::{
|
||||
StrokeAlign, StrokeLayer, WidthProfile,
|
||||
};
|
||||
pub use assets::ExportAsset;
|
||||
pub use compound_shape::ShapeMode;
|
||||
pub use corners::LiveCorners;
|
||||
pub use depth::{MAX_DEPTH, MAX_SYMBOL_NODES};
|
||||
pub use graph::{
|
||||
|
||||
@@ -221,6 +221,25 @@ mod tests {
|
||||
assert!(matches!(m.color_at(0, 0, 0.5, 0.5).0, Color::Rgb { .. }));
|
||||
}
|
||||
|
||||
/// #3232: the Appearance highlight lightens each point towards white in its own model, so a
|
||||
/// CMYK mesh stays CMYK (K shrinks with the other inks) and a grey one stays grey.
|
||||
#[test]
|
||||
fn mesh_highlight_keeps_each_points_model() {
|
||||
let square = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0));
|
||||
let ink = Color::Cmyk { c: 0.0, m: 0.4, y: 0.6, k: 0.1 };
|
||||
let m = GradientMesh::for_path(&square, 2, 2, ink, MeshAppearance::ToCenter, 50.0).unwrap();
|
||||
assert_eq!(m.points[0].color, ink, "corners stay");
|
||||
let centre = m.points[m.idx(1, 1)].color;
|
||||
let Color::Cmyk { c, m: mg, y, k } = centre else { panic!("{centre:?}") };
|
||||
assert!(c.abs() < 1e-6 && (mg - 0.2).abs() < 1e-6 && (y - 0.3).abs() < 1e-6 && (k - 0.05).abs() < 1e-6, "{c} {mg} {y} {k}");
|
||||
assert!(matches!(m.color_at(0, 0, 0.5, 0.5).0, Color::Cmyk { .. }), "patches mix in CMYK");
|
||||
let m = GradientMesh::for_path(&square, 2, 2, Color::gray(0.8), MeshAppearance::ToEdge, 100.0).unwrap();
|
||||
assert_eq!((m.points[0].color, m.points[m.idx(1, 1)].color), (Color::gray(0.0), Color::gray(0.8)));
|
||||
// RGB lightens in RGB as before.
|
||||
let m = GradientMesh::for_path(&square, 2, 2, Color::rgb(1.0, 0.0, 0.0), MeshAppearance::ToCenter, 100.0).unwrap();
|
||||
assert_eq!(m.points[m.idx(1, 1)].color.to_hex(), "#ffffff");
|
||||
}
|
||||
|
||||
/// Alt-clicking a point of a mesh from a file with fewer points than its rows and columns need
|
||||
/// deletes nothing (it indexed past the points, a panic).
|
||||
#[test]
|
||||
|
||||
@@ -267,7 +267,8 @@ impl GradientMesh {
|
||||
}
|
||||
|
||||
/// Create Gradient Mesh → Appearance: lighten the points towards white, to the centre or to
|
||||
/// the edges, by at most `highlight` %.
|
||||
/// the edges, by at most `highlight` %. Each point lightens towards white in its own colour
|
||||
/// model (paper white, no ink, for CMYK), so a CMYK or grey mesh keeps its inks (#3232).
|
||||
pub fn highlight(&mut self, appearance: MeshAppearance, highlight: f64) {
|
||||
let h = (highlight / 100.0).clamp(0.0, 1.0) as f32;
|
||||
let (rows, cols) = (self.rows as usize, self.cols as usize);
|
||||
@@ -282,7 +283,8 @@ impl GradientMesh {
|
||||
};
|
||||
if w > 0.0 {
|
||||
let i = self.idx(r, c);
|
||||
self.points[i].color = lerp_color(&self.points[i].color, &Color::WHITE, w);
|
||||
let color = self.points[i].color;
|
||||
self.points[i].color = lerp_color(&color, &Color::WHITE.in_model(color.model()), w);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -250,7 +250,7 @@ fn node_bytes(n: &Node, other: Option<&Node>) -> usize {
|
||||
if let Some(e) = n.extras_box() {
|
||||
b += ALLOC + size_of::<NodeExtras>();
|
||||
b += boxed(&e.mask) + boxed(&e.graph) + boxed(&e.shaper) + boxed(&e.attrs) + boxed(&e.slice) + boxed(&e.perspective);
|
||||
b += boxed(&e.dimension) + boxed(&e.live_paint_gaps);
|
||||
b += boxed(&e.dimension) + boxed(&e.live_paint_gaps) + boxed(&e.colorize);
|
||||
b += e.trace.as_ref().map_or(0, |t| ALLOC + size_of::<Value>() + json_bytes(t));
|
||||
b += e.intertwine.as_deref().map_or(0, |a| ALLOC + size_of::<PathData>() + path_bytes(a));
|
||||
b += e.objects_on_path.as_deref().map_or(0, |o| {
|
||||
|
||||
@@ -49,6 +49,15 @@ pub struct NodeExtras {
|
||||
/// Object › Objects on Path: the group's path and the objects attached to it (see
|
||||
/// [`crate::objects_on_path`]).
|
||||
pub objects_on_path: Option<Box<crate::objects_on_path::ObjectsOnPath>>,
|
||||
/// A grayscale or 1-bit image's fill color (`paint.setFill` on the image): a solid paint that
|
||||
/// colorizes it. Each pixel is drawn in this color, as opaque as the pixel is dark, so white
|
||||
/// pixels are transparent. `None`: the image shows its own pixels.
|
||||
pub colorize: Option<Box<vectorcraft_color::Paint>>,
|
||||
/// Pathfinder panel › Make Compound Shape: this group is a compound shape
|
||||
/// ([`Node::is_compound_shape`], [`crate::compound_shape`]).
|
||||
pub compound_shape: bool,
|
||||
/// As a member of a compound shape, how this object combines with the members below it.
|
||||
pub shape_mode: crate::ShapeMode,
|
||||
}
|
||||
|
||||
/// No extras: what [`Node::extras`] gives for a node without any.
|
||||
@@ -69,6 +78,9 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras {
|
||||
intertwine: None,
|
||||
live_paint_gaps: None,
|
||||
objects_on_path: None,
|
||||
colorize: None,
|
||||
compound_shape: false,
|
||||
shape_mode: crate::ShapeMode::Add,
|
||||
};
|
||||
|
||||
/// A node's [`NodeExtras`], if it has any ([`Node::extras`]). Extras that are all unset equal
|
||||
|
||||
@@ -127,6 +127,7 @@ impl Node {
|
||||
NodeKind::Layer { .. } => "Layer",
|
||||
NodeKind::Group { clip: true, .. } => "Clip Group",
|
||||
NodeKind::Group { .. } if self.extras().objects_on_path.is_some() => "Objects on Path",
|
||||
NodeKind::Group { .. } if self.extras().compound_shape => "Compound Shape",
|
||||
NodeKind::Group { .. } => "Group",
|
||||
NodeKind::Path { live: Some(l), .. } => l.label(),
|
||||
NodeKind::Path { guide: true, .. } => "Guide",
|
||||
@@ -545,9 +546,16 @@ impl Node {
|
||||
/// item) stands in for the topmost fill or stroke when it is of the proxy's kind. Otherwise
|
||||
/// type objects paint their runs (the first run speaks for all) in text space, fitted to the
|
||||
/// layout bounds; everything else paints its fill or stroke in the document, fitted to the
|
||||
/// geometric bounds. Strokes fit the box grown by half their weight.
|
||||
/// geometric bounds. Strokes fit the box grown by half their weight. A colorized image shows
|
||||
/// its colorize paint as its fill.
|
||||
pub fn proxy_paint(&self, stroke: bool, item: Option<usize>) -> Option<(&vectorcraft_color::Paint, Affine, Rect)> {
|
||||
let item = self.appearance.item_of_kind(item, !stroke);
|
||||
if item.is_none()
|
||||
&& !stroke
|
||||
&& let Some(c) = self.extras().colorize.as_deref()
|
||||
{
|
||||
return Some((c, Affine::IDENTITY, self.geometric_bounds().unwrap_or(Rect::ZERO)));
|
||||
}
|
||||
if item.is_none()
|
||||
&& let NodeKind::Text(t) = &self.kind
|
||||
{
|
||||
|
||||
@@ -19,6 +19,8 @@ fn extras_are_written_flat_in_order() {
|
||||
e.slice = Some(Box::default());
|
||||
e.perspective = Some(Box::new(crate::PerspectiveAttachment::new("left", 1.0)));
|
||||
e.live_paint_gaps = Some(Box::default());
|
||||
e.compound_shape = true;
|
||||
e.shape_mode = crate::ShapeMode::Exclude;
|
||||
}
|
||||
/// The top-level keys of a JSON object, in the order written.
|
||||
struct Keys(Vec<String>);
|
||||
@@ -61,8 +63,11 @@ fn extras_are_written_flat_in_order() {
|
||||
"bbox_angle",
|
||||
"perspective",
|
||||
"live_paint_gaps",
|
||||
"compound_shape",
|
||||
"shape_mode",
|
||||
];
|
||||
assert_eq!(keys, order);
|
||||
assert_eq!(v["shape_mode"], "exclude");
|
||||
assert_eq!(serde_json::from_value::<Node>(v).unwrap(), n);
|
||||
let plain = Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 4.0, 2.0)), Appearance::default_art());
|
||||
let back: Node = serde_json::from_value(serde_json::to_value(&plain).unwrap()).unwrap();
|
||||
|
||||
@@ -5,6 +5,12 @@ use super::kind::NodeKind;
|
||||
use super::opacity::{Knockout, OpacityMask};
|
||||
use super::{Appearance, BlendMode, Deserialize, Node, PathData, Serialize, one, yes};
|
||||
|
||||
/// Field `name` of a [`Node`] written as `v`, or skipped. A function of its own, so the long field
|
||||
/// list stays one straight run of calls.
|
||||
fn write_field<S: serde::ser::SerializeStruct, T: Serialize + ?Sized>(st: &mut S, skip: bool, name: &'static str, v: &T) -> Result<(), S::Error> {
|
||||
if skip { st.skip_field(name) } else { st.serialize_field(name, v) }
|
||||
}
|
||||
|
||||
/// How a [`Node`] is written: the flat field list of the file format, in its order, borrowed from
|
||||
/// the node and its extras (nothing is copied). The node reads back through `NodeWire`.
|
||||
impl Serialize for Node {
|
||||
@@ -42,16 +48,15 @@ impl Serialize for Node {
|
||||
e.intertwine.is_none(),
|
||||
e.live_paint_gaps.is_none(),
|
||||
e.objects_on_path.is_none(),
|
||||
e.colorize.is_none(),
|
||||
is_default(&e.compound_shape),
|
||||
is_default(&e.shape_mode),
|
||||
];
|
||||
let mut st = s.serialize_struct("Node", skips.iter().filter(|s| !**s).count())?;
|
||||
let mut skip = skips.into_iter();
|
||||
macro_rules! field {
|
||||
($name:literal, $v:expr) => {
|
||||
if skip.next().unwrap_or(false) {
|
||||
st.skip_field($name)?;
|
||||
} else {
|
||||
st.serialize_field($name, $v)?;
|
||||
}
|
||||
write_field(&mut st, skip.next().unwrap_or(false), $name, $v)?;
|
||||
};
|
||||
}
|
||||
field!("id", &self.id);
|
||||
@@ -82,6 +87,9 @@ impl Serialize for Node {
|
||||
field!("intertwine", &e.intertwine);
|
||||
field!("live_paint_gaps", &e.live_paint_gaps);
|
||||
field!("objects_on_path", &e.objects_on_path);
|
||||
field!("colorize", &e.colorize);
|
||||
field!("compound_shape", &e.compound_shape);
|
||||
field!("shape_mode", &e.shape_mode);
|
||||
st.end()
|
||||
}
|
||||
}
|
||||
@@ -182,6 +190,12 @@ pub(super) struct NodeWire {
|
||||
live_paint_gaps: Option<Box<crate::live_paint::GapOptions>>,
|
||||
#[serde(default)]
|
||||
objects_on_path: Option<Box<crate::objects_on_path::ObjectsOnPath>>,
|
||||
#[serde(default)]
|
||||
colorize: Option<Box<vectorcraft_color::Paint>>,
|
||||
#[serde(default)]
|
||||
compound_shape: bool,
|
||||
#[serde(default)]
|
||||
shape_mode: crate::ShapeMode,
|
||||
}
|
||||
|
||||
impl From<NodeWire> for Node {
|
||||
@@ -203,6 +217,9 @@ impl From<NodeWire> for Node {
|
||||
intertwine: w.intertwine,
|
||||
live_paint_gaps: w.live_paint_gaps,
|
||||
objects_on_path: w.objects_on_path,
|
||||
colorize: w.colorize,
|
||||
compound_shape: w.compound_shape,
|
||||
shape_mode: w.shape_mode,
|
||||
};
|
||||
Node {
|
||||
id: w.id,
|
||||
|
||||
@@ -62,6 +62,61 @@ impl ImageBlob {
|
||||
}
|
||||
}
|
||||
|
||||
/// How a grayscale image's file stores its pixels ([`ImageBlob::gray_source`]).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct GraySource {
|
||||
/// One bit a pixel: black and white only.
|
||||
pub one_bit: bool,
|
||||
/// The file has an alpha channel.
|
||||
pub alpha: bool,
|
||||
}
|
||||
|
||||
impl ImageBlob {
|
||||
/// Whether the image's file stores grayscale or 1-bit pixels (the images a fill color
|
||||
/// colorizes), and how; `None` for color images and data that isn't an image. Reads only its
|
||||
/// header.
|
||||
pub fn gray_source(&self) -> Option<GraySource> {
|
||||
let gray = |one_bit: bool, alpha: bool| Some(GraySource { one_bit, alpha });
|
||||
if let Some((kind, _)) = crate::cmyk::tiff(&self.bytes) {
|
||||
return match kind {
|
||||
tiff::ColorType::Gray(bits) => gray(bits == 1, false),
|
||||
tiff::ColorType::GrayA(bits) => gray(bits == 1, true),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
if crate::cmyk::jpeg_components(&self.bytes) == Some(1) {
|
||||
return gray(false, false);
|
||||
}
|
||||
use image::{ExtendedColorType as E, ImageDecoder as _};
|
||||
let reader = image::ImageReader::new(Cursor::new(self.bytes.as_slice())).with_guessed_format().ok()?;
|
||||
match reader.into_decoder().ok()?.original_color_type() {
|
||||
E::L1 => gray(true, false),
|
||||
E::La1 => gray(true, true),
|
||||
E::L2 | E::L4 | E::L8 | E::L16 => gray(false, false),
|
||||
E::La2 | E::La4 | E::La8 | E::La16 => gray(false, true),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// How much of a colorize paint each pixel shows, row by row from the top: how dark the pixel
|
||||
/// is (255 less its Rec. 709 luma) scaled by its alpha, so white and transparent pixels are 0.
|
||||
/// Returns the width, the height and one byte a pixel; `None` when the image can't be decoded
|
||||
/// within [`MAX_RASTER_ALLOC`].
|
||||
pub fn coverage(&self) -> Option<(u32, u32, Vec<u8>)> {
|
||||
let img = rgba_within(&self.bytes, MAX_RASTER_ALLOC)?;
|
||||
let (w, h) = img.dimensions();
|
||||
let cover = img
|
||||
.pixels()
|
||||
.map(|p| {
|
||||
let [r, g, b, a] = p.0;
|
||||
let luma = 0.2126 * r as f32 + 0.7152 * g as f32 + 0.0722 * b as f32;
|
||||
((255.0 - luma).clamp(0.0, 255.0) * a as f32 / 255.0).round() as u8
|
||||
})
|
||||
.collect();
|
||||
Some((w, h, cover))
|
||||
}
|
||||
}
|
||||
|
||||
impl ImageBlob {
|
||||
/// The colour around pixel (`x`, `y`) (pixel space): the alpha-weighted average of the `size` ×
|
||||
/// `size` pixels centred on it, clipped to the image, as straight RGBA. `None` outside the
|
||||
@@ -298,4 +353,66 @@ mod tests {
|
||||
assert!(b.map_rgb(|c| c).is_none(), "nothing changed");
|
||||
assert!(ImageBlob::png(vec![1, 2, 3]).map_rgb(|c| c).is_none(), "undecodable");
|
||||
}
|
||||
|
||||
/// An uncompressed 1-bit TIFF, BlackIsZero, of `w` × `h` pixels: `rows` holds each row's bits,
|
||||
/// padded to a byte, most significant bit first.
|
||||
fn bilevel_tiff(w: u16, h: u16, rows: &[u8]) -> Vec<u8> {
|
||||
// Tag, type (3 short, 4 long) and value of each entry, in tag order.
|
||||
let data_at = 8 + 2 + 9 * 12 + 4;
|
||||
let entries: [(u16, u16, u32); 9] = [
|
||||
(256, 3, w.into()),
|
||||
(257, 3, h.into()),
|
||||
(258, 3, 1),
|
||||
(259, 3, 1),
|
||||
(262, 3, 1),
|
||||
(273, 4, data_at),
|
||||
(277, 3, 1),
|
||||
(278, 3, h.into()),
|
||||
(279, 4, rows.len() as u32),
|
||||
];
|
||||
let mut out = b"II*\0".to_vec();
|
||||
out.extend_from_slice(&8u32.to_le_bytes());
|
||||
out.extend_from_slice(&(entries.len() as u16).to_le_bytes());
|
||||
for (tag, kind, value) in entries {
|
||||
out.extend_from_slice(&tag.to_le_bytes());
|
||||
out.extend_from_slice(&kind.to_le_bytes());
|
||||
out.extend_from_slice(&1u32.to_le_bytes());
|
||||
out.extend_from_slice(&value.to_le_bytes());
|
||||
}
|
||||
out.extend_from_slice(&0u32.to_le_bytes());
|
||||
out.extend_from_slice(rows);
|
||||
out
|
||||
}
|
||||
|
||||
fn png_of(img: image::DynamicImage) -> ImageBlob {
|
||||
let mut png = Vec::new();
|
||||
img.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
ImageBlob::png(png)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grayscale_and_1_bit_files_are_told_from_color_ones() {
|
||||
let gray = |one_bit, alpha| Some(GraySource { one_bit, alpha });
|
||||
let l8 = png_of(image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(2, 1, vec![0, 255]).unwrap()));
|
||||
assert_eq!(l8.gray_source(), gray(false, false));
|
||||
let la8 = png_of(image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(1, 1, vec![0, 128]).unwrap()));
|
||||
assert_eq!(la8.gray_source(), gray(false, true));
|
||||
let mut jpeg = Vec::new();
|
||||
jpeg_encoder::Encoder::new(&mut jpeg, 90).encode(&[0, 255, 0, 255], 2, 2, jpeg_encoder::ColorType::Luma).unwrap();
|
||||
assert_eq!(ImageBlob::new("image/jpeg", jpeg).gray_source(), gray(false, false));
|
||||
// Black, white; white, black.
|
||||
let tif = ImageBlob::new("image/tiff", bilevel_tiff(2, 2, &[0b0100_0000, 0b1000_0000]));
|
||||
assert_eq!(tif.gray_source(), gray(true, false));
|
||||
assert_eq!(tif.coverage(), Some((2, 2, vec![255, 0, 0, 255])), "black covers, white doesn't");
|
||||
// Color images and data that isn't an image.
|
||||
assert_eq!(blob(&[[0, 0, 0, 255], [9, 9, 9, 255]], 2, 1).gray_source(), None);
|
||||
assert_eq!(ImageBlob::png(vec![1, 2, 3]).gray_source(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coverage_is_darkness_times_alpha() {
|
||||
let la8 = png_of(image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(4, 1, vec![0, 255, 255, 255, 51, 255, 0, 128]).unwrap()));
|
||||
assert_eq!(la8.coverage(), Some((4, 1, vec![255, 0, 204, 128])));
|
||||
assert_eq!(ImageBlob::png(vec![1, 2, 3]).coverage(), None);
|
||||
}
|
||||
}
|
||||
@@ -229,13 +229,14 @@ fn item_paint_mut(it: &mut AppearanceItem) -> &mut Paint {
|
||||
}
|
||||
}
|
||||
|
||||
/// The paints a node holds itself (not its children): appearance items, then text runs.
|
||||
/// The paints a node holds itself (not its children): appearance items, then text runs, then an
|
||||
/// image's colorize paint.
|
||||
pub fn node_paints(n: &Node) -> impl Iterator<Item = &Paint> {
|
||||
let runs = match &n.kind {
|
||||
NodeKind::Text(t) => t.runs.as_slice(),
|
||||
_ => &[],
|
||||
};
|
||||
n.appearance.items.iter().map(item_paint).chain(runs.iter().flat_map(|r| [&r.style.fill, &r.style.stroke]))
|
||||
n.appearance.items.iter().map(item_paint).chain(runs.iter().flat_map(|r| [&r.style.fill, &r.style.stroke])).chain(n.extras().colorize.as_deref())
|
||||
}
|
||||
|
||||
/// Mutable [`node_paints`], in the same order.
|
||||
@@ -244,7 +245,8 @@ pub fn node_paints_mut(n: &mut Node) -> impl Iterator<Item = &mut Paint> {
|
||||
NodeKind::Text(t) => t.runs.as_mut_slice(),
|
||||
_ => &mut [],
|
||||
};
|
||||
n.appearance.items.iter_mut().map(item_paint_mut).chain(runs.iter_mut().flat_map(|r| [&mut r.style.fill, &mut r.style.stroke]))
|
||||
let colorize = n.extras.0.as_deref_mut().and_then(|e| e.colorize.as_deref_mut());
|
||||
n.appearance.items.iter_mut().map(item_paint_mut).chain(runs.iter_mut().flat_map(|r| [&mut r.style.fill, &mut r.style.stroke])).chain(colorize)
|
||||
}
|
||||
|
||||
/// `n` with `f` applied to its subtree's linkable colours, or `None` when nothing changed (then
|
||||
|
||||
@@ -42,6 +42,20 @@ pub fn is_length(id: &str, key: &str, relative: bool) -> bool {
|
||||
catalog_index().get(id).is_some_and(|info| info.lengths.keys(relative).any(|k| k == key))
|
||||
}
|
||||
|
||||
/// The range in points that distance parameter `key` of effect `id` is kept within, as its
|
||||
/// parameter documentation gives it (`{maxRadius: pt 4..127 (8), …}`); `None` when it gives none.
|
||||
pub fn length_range(id: &str, key: &str) -> Option<std::ops::RangeInclusive<f64>> {
|
||||
let doc = catalog_index().get(id)?.params;
|
||||
let starts = |at: usize| doc.get(..at).and_then(|s| s.chars().last()).is_some_and(|c| c == '{' || c == ' ');
|
||||
let rest = doc.match_indices(key).map(|(at, _)| at).filter(|at| starts(*at)).find_map(|at| {
|
||||
let rest = doc.get(at + key.len()..)?;
|
||||
rest.strip_prefix(": pt ").or_else(|| rest.strip_prefix("?: pt "))
|
||||
})?;
|
||||
let (lo, hi) = rest.split_whitespace().next()?.split_once("..")?;
|
||||
let (lo, hi) = (lo.parse::<f64>().ok()?, hi.trim_end_matches(',').parse::<f64>().ok()?);
|
||||
(lo.is_finite() && hi.is_finite() && lo <= hi).then_some(lo..=hi)
|
||||
}
|
||||
|
||||
/// The distance parameters of effect `id` (none for unknown effects).
|
||||
fn lengths_of(id: &str) -> Lengths {
|
||||
let always = |always| Lengths { always, absolute: &[] };
|
||||
|
||||
@@ -114,16 +114,67 @@ pub fn apply_geometry_with(effects: &[Effect], path: &PathData, bounds: Rect, ct
|
||||
apply_geometry_within(effects, path, bounds, ctx, Budget::EFFECTS)
|
||||
}
|
||||
|
||||
/// Does effect `e` safely commute with pure translation when it is terminal?
|
||||
/// Only positive offsets with round joins commute exactly with pure translations for non-zero fills (#4145).
|
||||
fn is_terminal_offset_eligible(e: &Effect) -> bool {
|
||||
if e.id != "path.offsetPath" {
|
||||
return false;
|
||||
}
|
||||
let p = merged_params(&e.id, &e.params);
|
||||
util::join(&p, "joins") == vectorcraft_pathops::Join::Round && util::num(&p, "offset", 10.0) >= 0.0
|
||||
}
|
||||
|
||||
/// Optimize a list of visible geometry effects: move pure-translation Transform effects with
|
||||
/// copies after a terminal Offset Path effect when the effective style is safe (NonZero fill and
|
||||
/// no stroke), so that the offset path is evaluated once on the base path rather than on dozens
|
||||
/// of overlapping copies, avoiding combinatorial explosions in the planar sweep (#4145).
|
||||
pub(crate) fn optimize_geometry_effects<'a>(effects: &[&'a Effect], style_safe: bool) -> Vec<&'a Effect> {
|
||||
let mut out: Vec<&'a Effect> = effects.to_vec();
|
||||
if !style_safe || out.len() < 2 {
|
||||
return out;
|
||||
}
|
||||
let mut changed = true;
|
||||
while changed {
|
||||
changed = false;
|
||||
for i in 0..out.len().saturating_sub(1) {
|
||||
let e1 = out[i];
|
||||
if e1.id == "distort.transform" {
|
||||
let p1 = merged_params(&e1.id, &e1.params);
|
||||
if let Some((_, copies)) = crate::distort::transform_move(&p1)
|
||||
&& copies > 0
|
||||
&& is_terminal_offset_eligible(out[i + 1])
|
||||
&& out.get(i + 2..).is_some_and(|tail| tail.iter().all(|e| e.id == "distort.transform"))
|
||||
{
|
||||
out.swap(i, i + 1);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// [`apply_geometry_with`] whose effects keep to `budget`, raised to what `path` costs where that
|
||||
/// is more.
|
||||
pub(crate) fn apply_geometry_within(effects: &[Effect], path: &PathData, bounds: Rect, ctx: &GeomContext, budget: Budget) -> PathData {
|
||||
// `budget` raised to what `path` costs, measured once, and only for a path that has geometry
|
||||
// effects.
|
||||
let has_stroke = match (ctx.item, ctx.appearance) {
|
||||
(Some(idx), Some(app)) => match app.items.get(idx) {
|
||||
Some(AppearanceItem::Stroke(s)) => !s.paint.is_none() && s.width > 0.0,
|
||||
Some(AppearanceItem::Fill(_)) => false,
|
||||
None => ctx.stroke.is_some_and(|s| !s.paint.is_none() && s.width > 0.0),
|
||||
},
|
||||
_ => ctx.stroke.is_some_and(|s| !s.paint.is_none() && s.width > 0.0),
|
||||
};
|
||||
let style_safe = ctx.rule == FillRule::NonZero && !has_stroke;
|
||||
let visible_fx: Vec<&Effect> = effects.iter().filter(|e| e.visible && is_geometry(&e.id)).collect();
|
||||
let fx = optimize_geometry_effects(&visible_fx, style_safe);
|
||||
let mut limit = None;
|
||||
let mut cur = path.clone();
|
||||
let mut b = bounds;
|
||||
let mut first = true;
|
||||
for e in effects.iter().filter(|e| e.visible && is_geometry(&e.id)) {
|
||||
for e in fx {
|
||||
if !first {
|
||||
b = cur.bounds().unwrap_or(b);
|
||||
}
|
||||
|
||||
@@ -7,6 +7,10 @@
|
||||
//! result keeps the appearance of the object whose paint it takes. Trap ([`crate::trap`]) keeps the
|
||||
//! children and adds its traps above them.
|
||||
//!
|
||||
//! **Compound shapes** ([`compound_shape_area`]): a compound shape draws as the one area its
|
||||
//! members' shape modes make, painted by its own appearance as a group's own fills and strokes
|
||||
//! paint its members.
|
||||
//!
|
||||
//! **Container appearance** ([`evaluate_container`]): a group's or layer's own fills and strokes
|
||||
//! paint every member's geometry, below or above the members as its contents slot says
|
||||
//! ([`Appearance::contents_at`]); its geometry effects reshape the members as one piece; its raster
|
||||
@@ -16,7 +20,7 @@ use std::sync::Arc;
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_doc::color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Node, NodeId, NodeKind, StrokeLayer};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Node, NodeId, NodeKind, ShapeMode, StrokeLayer};
|
||||
use vectorcraft_geom::{FillRule, PathData, Rect};
|
||||
use vectorcraft_pathops::{self as po, PathfinderOp};
|
||||
|
||||
@@ -45,10 +49,11 @@ fn op_of(id: &str) -> Option<PathfinderOp> {
|
||||
PATHFINDER_EFFECTS.iter().find(|e| e.0 == id).map(|e| e.2)
|
||||
}
|
||||
|
||||
/// Does `n` (a group or layer) carry a visible Pathfinder effect?
|
||||
/// Does `n` (a group or layer) carry a visible Pathfinder effect, or is it a compound shape?
|
||||
pub fn has_pathfinder(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::Group { clip: false, .. } | NodeKind::Layer { .. })
|
||||
&& n.appearance.effects.iter().any(|e| e.visible && is_pathfinder(&e.id))
|
||||
n.is_compound_shape()
|
||||
|| (matches!(n.kind, NodeKind::Group { clip: false, .. } | NodeKind::Layer { .. })
|
||||
&& n.appearance.effects.iter().any(|e| e.visible && is_pathfinder(&e.id)))
|
||||
}
|
||||
|
||||
/// Converts objects that aren't paths (e.g. text) to outline art, if possible. The paths and
|
||||
@@ -62,11 +67,15 @@ fn leaves(n: &Node, hook: Option<OutlineHook>, out: &mut Vec<Node>) {
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => out.push(n.clone()),
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => {
|
||||
for c in children {
|
||||
leaves(c, hook, out);
|
||||
// A compound shape takes part as its area, styled like it.
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => match compound_shape_art(n, hook) {
|
||||
Some(art) => out.push(art),
|
||||
None => {
|
||||
for c in children {
|
||||
leaves(c, hook, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
_ => {
|
||||
// Every path of the outline art, at any depth, takes the object's opacity and blend
|
||||
// mode.
|
||||
@@ -91,6 +100,63 @@ fn geometry(n: &Node) -> Option<(PathData, FillRule)> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The operation that combines a compound shape's member in `mode` with the area below it.
|
||||
fn shape_op(mode: ShapeMode) -> po::BoolOp {
|
||||
match mode {
|
||||
ShapeMode::Add => po::BoolOp::Union,
|
||||
ShapeMode::Subtract => po::BoolOp::Difference,
|
||||
ShapeMode::Intersect => po::BoolOp::Intersect,
|
||||
ShapeMode::Exclude => po::BoolOp::Xor,
|
||||
}
|
||||
}
|
||||
|
||||
/// The area compound shape `n` draws: each visible member's shape (a group's leaves together, type
|
||||
/// as its outlines through `hook`, open paths closed) combined with the area of the members below
|
||||
/// it by the member's shape mode; the backmost member starts the area. `None` when `n` is not a
|
||||
/// compound shape, or its members are past a live Pathfinder's budget ([`PATHFINDER_MAX_SEGMENTS`],
|
||||
/// [`PATHFINDER_MAX_OVERLAPS`]).
|
||||
pub fn compound_shape_area(n: &Node, hook: Option<OutlineHook>) -> Option<PathData> {
|
||||
if !n.is_compound_shape() {
|
||||
return None;
|
||||
}
|
||||
let mut all: Vec<Node> = vec![];
|
||||
// Each member that has a shape: its operation and how many of the leaves are its.
|
||||
let mut members: Vec<(po::BoolOp, usize)> = vec![];
|
||||
for c in n.children()? {
|
||||
let before = all.len();
|
||||
leaves(c, hook, &mut all);
|
||||
if all.len() > before {
|
||||
members.push((shape_op(c.extras().shape_mode), all.len() - before));
|
||||
}
|
||||
}
|
||||
if !within_budget(&all) {
|
||||
return None;
|
||||
}
|
||||
if all.is_empty() {
|
||||
return Some(PathData::default());
|
||||
}
|
||||
let parts: Vec<(PathData, FillRule)> = all.iter().map(|l| geometry(l).unwrap_or_default()).collect();
|
||||
let refs: Vec<(&PathData, FillRule)> = parts.iter().map(|(p, r)| (p, *r)).collect();
|
||||
Some(po::boolean_n(&refs, |inside| {
|
||||
let (mut start, mut area) = (0, false);
|
||||
for (k, (op, count)) in members.iter().enumerate() {
|
||||
let here = inside.get(start..start + count).is_some_and(|flags| flags.contains(&true));
|
||||
start += count;
|
||||
area = if k == 0 { here } else { op.apply(area, here) };
|
||||
}
|
||||
area
|
||||
}))
|
||||
}
|
||||
|
||||
/// Compound shape `n` as one path of its area ([`compound_shape_area`]) with its appearance,
|
||||
/// opacity and blend mode: how it takes part in a Pathfinder operation.
|
||||
pub fn compound_shape_art(n: &Node, hook: Option<OutlineHook>) -> Option<Node> {
|
||||
let area = compound_shape_area(n, hook)?;
|
||||
let mut art = Node::path(n.id, area, Appearance { items: n.appearance.items.clone(), ..Default::default() });
|
||||
(art.opacity, art.blend) = (n.opacity, n.blend);
|
||||
Some(art)
|
||||
}
|
||||
|
||||
/// A result path styled like `src` (its appearance, opacity and blend mode).
|
||||
fn styled(src: &Node, path: PathData, outline: bool) -> Node {
|
||||
let mut appearance = Appearance { items: src.appearance.items.clone(), ..Default::default() };
|
||||
@@ -196,7 +262,16 @@ pub fn pathfinder_children(group: &Node, hook: Option<OutlineHook>) -> Option<Ve
|
||||
return None;
|
||||
}
|
||||
let source: &[Arc<Node>] = group.children()?;
|
||||
let mut stack: Vec<Arc<Node>> = source.to_vec();
|
||||
let mut stack: Vec<Arc<Node>> = if group.is_compound_shape() {
|
||||
// The group's own appearance paints the area ([`evaluate_container`]), so the art has none.
|
||||
match compound_shape_area(group, hook) {
|
||||
Some(area) if area.is_empty() => vec![],
|
||||
Some(area) => vec![Arc::new(Node::path(group.id, area, Appearance::default()))],
|
||||
None => return Some(source.to_vec()),
|
||||
}
|
||||
} else {
|
||||
source.to_vec()
|
||||
};
|
||||
for e in group.appearance.effects.iter().filter(|e| e.visible) {
|
||||
if e.id == crate::trap::TRAP {
|
||||
let mut lv = vec![];
|
||||
@@ -375,6 +450,13 @@ pub fn member_shapes(doc: Option<&Document>, n: &Node) -> Vec<(PathData, FillRul
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => out.extend(crate::reshape::leaf_geometry(n)),
|
||||
NodeKind::Group { .. } if n.is_compound_shape() => {
|
||||
let hook: &dyn Fn(&Node) -> Option<Node> = &crate::outline_text;
|
||||
match compound_shape_area(n, Some(hook)) {
|
||||
Some(area) => out.push((area, FillRule::NonZero)),
|
||||
None => members(doc, n, out),
|
||||
}
|
||||
}
|
||||
NodeKind::Text(t) => {
|
||||
let (_, all) = crate::reshape::glyph_outlines(t);
|
||||
if !all.elements().is_empty() {
|
||||
@@ -454,6 +536,8 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
if let Some(ch) = m.children_mut() {
|
||||
*ch = result;
|
||||
}
|
||||
// The area is art now: drawn again, it is no compound shape of its own.
|
||||
m.extras_mut().compound_shape = false;
|
||||
}
|
||||
if !fx.is_empty() {
|
||||
m = crate::reshape::outlined_members(doc, &m);
|
||||
|
||||
@@ -347,3 +347,72 @@ fn pathfinder_on_many_stacked_bars_still_runs() {
|
||||
let out = pathfinder_children(&g, None).unwrap();
|
||||
assert_eq!(out.len(), 1);
|
||||
}
|
||||
|
||||
/// Two overlapping squares (0–10 and 5–15 by 10 high) as a compound shape, the front one in `mode`.
|
||||
fn compound_shape(mode: ShapeMode) -> Node {
|
||||
let mut front = (*sq(2, 5.0, Color::rgb(0.0, 0.0, 1.0))).clone();
|
||||
front.extras_mut().shape_mode = mode;
|
||||
let mut g = Node::group(NodeId(10), vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), Arc::new(front)]);
|
||||
g.extras_mut().compound_shape = true;
|
||||
g.appearance = Appearance::basic(Paint::solid(Color::rgb(0.0, 1.0, 0.0)), Paint::None, 0.0).into();
|
||||
g
|
||||
}
|
||||
|
||||
/// A compound shape draws the area its members' modes make, one unpainted path that its own
|
||||
/// appearance paints; evaluated, it is plain art painted with that appearance.
|
||||
#[test]
|
||||
fn compound_shapes_draw_the_area_their_shape_modes_make() {
|
||||
for (mode, want) in [(ShapeMode::Add, 150.0), (ShapeMode::Subtract, 50.0), (ShapeMode::Intersect, 50.0), (ShapeMode::Exclude, 100.0)] {
|
||||
let g = compound_shape(mode);
|
||||
assert!(has_pathfinder(&g), "{mode:?}");
|
||||
let area_path = compound_shape_area(&g, None).unwrap();
|
||||
assert!((po::area(&area_path, FillRule::NonZero).abs() - want).abs() < 0.01, "{mode:?}");
|
||||
let out = pathfinder_children(&g, None).unwrap();
|
||||
assert_eq!(out.len(), 1, "{mode:?}");
|
||||
assert!(out[0].appearance.items.is_empty(), "the group's own appearance paints it");
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
assert!(!art.is_compound_shape(), "evaluated, it is art");
|
||||
let painted: Vec<&Arc<Node>> = art.children().unwrap().iter().filter(|c| !c.appearance.items.is_empty()).collect();
|
||||
assert_eq!(painted.len(), 1);
|
||||
assert_eq!(painted[0].appearance.fill_paint().color(), Some(Color::rgb(0.0, 1.0, 0.0)), "{mode:?}");
|
||||
assert!((area(painted[0]) - want).abs() < 0.01, "{mode:?}");
|
||||
}
|
||||
// The backmost member's mode doesn't change the area.
|
||||
let mut g = compound_shape(ShapeMode::Add);
|
||||
if let Some(ch) = g.children_mut() {
|
||||
let mut back = (*ch[0]).clone();
|
||||
back.extras_mut().shape_mode = ShapeMode::Subtract;
|
||||
ch[0] = Arc::new(back);
|
||||
}
|
||||
assert!((po::area(&compound_shape_area(&g, None).unwrap(), FillRule::NonZero).abs() - 150.0).abs() < 0.01);
|
||||
// Hidden members take no part; the mark on a clip group is ignored.
|
||||
let mut g = compound_shape(ShapeMode::Subtract);
|
||||
if let Some(ch) = g.children_mut() {
|
||||
let mut front = (*ch[1]).clone();
|
||||
front.visible = false;
|
||||
ch[1] = Arc::new(front);
|
||||
}
|
||||
assert!((po::area(&compound_shape_area(&g, None).unwrap(), FillRule::NonZero).abs() - 100.0).abs() < 0.01);
|
||||
let mut clip = compound_shape(ShapeMode::Add);
|
||||
clip.kind = NodeKind::Group { children: clip.children().unwrap().clone(), clip: true };
|
||||
assert!(!clip.is_compound_shape() && compound_shape_area(&clip, None).is_none());
|
||||
}
|
||||
|
||||
/// A compound shape inside another (and inside an Effect › Pathfinder group) takes part as its area,
|
||||
/// styled like it.
|
||||
#[test]
|
||||
fn nested_compound_shapes_take_part_as_their_area() {
|
||||
let inner = compound_shape(ShapeMode::Subtract);
|
||||
let mut cutter = (*sq(3, 2.0, Color::BLACK)).clone();
|
||||
cutter.extras_mut().shape_mode = ShapeMode::Intersect;
|
||||
let mut outer = Node::group(NodeId(20), vec![Arc::new(inner.clone()), Arc::new(cutter)]);
|
||||
outer.extras_mut().compound_shape = true;
|
||||
// (0–5 of the inner area) ∩ (2–12) = 2–5 by 10 high.
|
||||
assert!((po::area(&compound_shape_area(&outer, None).unwrap(), FillRule::NonZero).abs() - 30.0).abs() < 0.01);
|
||||
let mut effect = Node::group(NodeId(30), vec![Arc::new(inner)]);
|
||||
effect.appearance.effects.push(Effect { id: "pathfinder.add".into(), params: serde_json::json!({}), visible: true });
|
||||
let out = pathfinder_children(&effect, None).unwrap();
|
||||
assert_eq!(out.len(), 1);
|
||||
assert!((area(&out[0]) - 50.0).abs() < 0.01);
|
||||
assert_eq!(out[0].appearance.fill_paint().color(), Some(Color::rgb(0.0, 1.0, 0.0)), "styled like the compound shape");
|
||||
}
|
||||
@@ -69,8 +69,8 @@ pub use adjust::{
|
||||
pub use bake::{StrokeArt, bake_appearance, bake_document, expand_art, expand_leaf, fresh_ids, needs_bake};
|
||||
pub use clip::clip_outline;
|
||||
pub use group::{
|
||||
OutlineHook, PATHFINDER_EFFECTS, evaluate_container, has_container_appearance, has_pathfinder, is_pathfinder, member_shapes, paints,
|
||||
pathfinder_children,
|
||||
OutlineHook, PATHFINDER_EFFECTS, compound_shape_area, compound_shape_art, evaluate_container, has_container_appearance, has_pathfinder,
|
||||
is_pathfinder, member_shapes, paints, pathfinder_children,
|
||||
};
|
||||
pub use lighting_presets::{LIGHTING_PRESETS, LightingPreset, lighting_preset_params, matching_lighting_preset};
|
||||
pub use live::{expand_live, expand_live_deep, expanded_live_group, text_outliner};
|
||||
@@ -94,7 +94,7 @@ mod catalog;
|
||||
mod geometry;
|
||||
mod params;
|
||||
|
||||
pub use catalog::{EffectInfo, Lengths, WARP_STYLES, effect_catalog, effect_info, is_length, plugin_effects};
|
||||
pub use catalog::{EffectInfo, Lengths, WARP_STYLES, effect_catalog, effect_info, is_length, length_range, plugin_effects};
|
||||
pub(crate) use geometry::{Budget, apply_one};
|
||||
pub use geometry::{GeomContext, apply_geometry, apply_geometry_bez, apply_geometry_with};
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -431,6 +431,22 @@ pub(crate) fn reshape_leaves_within(art: &mut Node, fx: &[&Effect], budget: Budg
|
||||
if fx.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut leaves_safe = true;
|
||||
for_each_leaf(art, &mut |leaf| {
|
||||
if !leaves_safe {
|
||||
return;
|
||||
}
|
||||
if let Some((_, rule)) = leaf_geometry(leaf) {
|
||||
let has_stroke = leaf.appearance.stroke().is_some_and(|s| !s.paint.is_none() && s.width > 0.0);
|
||||
if rule != FillRule::NonZero || has_stroke {
|
||||
leaves_safe = false;
|
||||
}
|
||||
}
|
||||
});
|
||||
let art_stroke = art.appearance.stroke().is_some_and(|s| !s.paint.is_none() && s.width > 0.0);
|
||||
let style_safe = leaves_safe && !art_stroke;
|
||||
let opt_fx = crate::geometry::optimize_geometry_effects(fx, style_safe);
|
||||
let fx = opt_fx.as_slice();
|
||||
let seed = art.id.0;
|
||||
// The placed gradients of type's outlines in `art` (`outline_text`) move and scale with the
|
||||
// pieces, from the outlines' bounds before the effects to their bounds after them.
|
||||
|
||||
@@ -438,6 +438,93 @@ fn three_max_detail_roughens_stay_within_the_effect_budget() {
|
||||
assert_ne!(out, apply_geometry(&[rough], &rect, rect.bounds().unwrap()), "more than one Roughen applies");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transform_copies_before_offset_path_evaluates_without_ram_spike() {
|
||||
let effects = [
|
||||
fx("distort.transform", json!({"moveH": -0.66, "moveV": 0.66, "copies": 30})),
|
||||
fx("path.offsetPath", json!({"offset": 10.0, "joins": "round"})),
|
||||
];
|
||||
let path = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0));
|
||||
let start = std::time::Instant::now();
|
||||
let out = apply_geometry(&effects, &path, path.bounds().unwrap());
|
||||
let elapsed = start.elapsed();
|
||||
assert!(elapsed < std::time::Duration::from_secs(2), "elapsed: {:?}", elapsed);
|
||||
assert_eq!(out.subpaths.len(), 31);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reshape_leaves_within_optimizes_transform_before_terminal_offset_path() {
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_doc::{Appearance, Node, NodeId};
|
||||
|
||||
let id = NodeId(10);
|
||||
let leaf = |x: f64| Arc::new(Node::path(id, shapes::rectangle(Rect::new(x, 0.0, x + 20.0, 20.0)), Appearance::default()));
|
||||
let mut art = Node::group(id, (0..5).map(|k| leaf(k as f64 * 30.0)).collect());
|
||||
let transform = fx("distort.transform", json!({"moveH": 2.0, "moveV": 2.0, "copies": 10}));
|
||||
let offset = fx("path.offsetPath", json!({"offset": 4.0, "joins": "round"}));
|
||||
|
||||
let start = std::time::Instant::now();
|
||||
crate::reshape::reshape_leaves_within(&mut art, &[&transform, &offset], Budget::EFFECTS);
|
||||
let elapsed = start.elapsed();
|
||||
assert!(elapsed < std::time::Duration::from_secs(2));
|
||||
|
||||
let children = art.children().unwrap();
|
||||
assert_eq!(children.len(), 5);
|
||||
for c in children {
|
||||
let (p, _) = crate::reshape::leaf_geometry(c).unwrap();
|
||||
// Base rectangle offset once, then copied 10 times -> 11 subpaths
|
||||
assert_eq!(p.subpaths.len(), 11);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reshape_leaves_within_preserves_order_when_not_terminal_or_not_style_safe() {
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_doc::{Appearance, Node, NodeId, NodeKind};
|
||||
|
||||
let id = NodeId(11);
|
||||
// 1. EvenOdd fill rule: preserving order causes Transform copies to union in Offset Path into 1 subpath.
|
||||
let mut leaf = Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::default());
|
||||
if let NodeKind::Path { rule, .. } = &mut leaf.kind {
|
||||
*rule = FillRule::EvenOdd;
|
||||
}
|
||||
let mut art_evenodd = Node::group(id, vec![Arc::new(leaf)]);
|
||||
let transform = fx("distort.transform", json!({"moveH": 2.0, "moveV": 2.0, "copies": 2}));
|
||||
let offset = fx("path.offsetPath", json!({"offset": 4.0}));
|
||||
crate::reshape::reshape_leaves_within(&mut art_evenodd, &[&transform, &offset], Budget::EFFECTS);
|
||||
let p = art_evenodd.children().unwrap()[0].path_data().unwrap();
|
||||
assert_eq!(p.subpaths.len(), 1, "EvenOdd does not swap; copies union into 1 outer subpath");
|
||||
|
||||
// 2. Non-terminal Offset Path: followed by Round Corners, must preserve order.
|
||||
let leaf_round = Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::default()));
|
||||
let mut art_round = Node::group(id, vec![leaf_round]);
|
||||
let round_corners = fx("stylize.roundCorners", json!({"radius": 2.0}));
|
||||
crate::reshape::reshape_leaves_within(&mut art_round, &[&transform, &offset, &round_corners], Budget::EFFECTS);
|
||||
let p = art_round.children().unwrap()[0].path_data().unwrap();
|
||||
assert_eq!(p.subpaths.len(), 1, "Non-terminal Offset Path does not swap; copies union into 1 outer subpath");
|
||||
|
||||
// 3. Non-round join (e.g. miter): preserving order is required as corners differ (#4145).
|
||||
let leaf_miter = Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::default()));
|
||||
let mut art_miter = Node::group(id, vec![leaf_miter]);
|
||||
let offset_miter = fx("path.offsetPath", json!({"offset": 4.0, "joins": "miter"}));
|
||||
crate::reshape::reshape_leaves_within(&mut art_miter, &[&transform, &offset_miter], Budget::EFFECTS);
|
||||
let p = art_miter.children().unwrap()[0].path_data().unwrap();
|
||||
assert_eq!(p.subpaths.len(), 1, "Miter join does not swap; copies union into 1 outer subpath");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn consecutive_transforms_before_terminal_offset_path_all_move_after() {
|
||||
let t1 = fx("distort.transform", json!({"moveH": 1.0, "moveV": 0.0, "copies": 2}));
|
||||
let t2 = fx("distort.transform", json!({"moveH": 0.0, "moveV": 1.0, "copies": 3}));
|
||||
let offset = fx("path.offsetPath", json!({"offset": 4.0, "joins": "round"}));
|
||||
|
||||
let opt = crate::geometry::optimize_geometry_effects(&[&t1, &t2, &offset], true);
|
||||
assert_eq!(opt.len(), 3);
|
||||
assert_eq!(opt[0].id, "path.offsetPath");
|
||||
assert_eq!(opt[1].id, "distort.transform");
|
||||
assert_eq!(opt[2].id, "distort.transform");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transform_copies_stop_before_they_overflow() {
|
||||
let out = run("distort.transform", json!({"scaleH": 100000, "scaleV": 100000, "copies": 1000}), &square());
|
||||
@@ -1120,3 +1207,17 @@ fn a_repeat_of_a_symbol_whose_art_is_a_repeat_shares_the_instance_budget() {
|
||||
let small = Node::new(NodeId(0), NodeKind::Repeat(RepeatSpec::mirror(vec![instance("Small")], 90.0, 5.0)));
|
||||
assert_eq!(expand_live(Some(&d), &small).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_distance_parameters_range_comes_from_its_documentation() {
|
||||
assert_eq!(length_range("pixelate.colorHalftone", "maxRadius"), Some(4.0..=127.0));
|
||||
// The effect applies the range's floor to a radius below it.
|
||||
assert_eq!(
|
||||
crate::pixel::parse("pixelate.colorHalftone", &json!({"maxRadius": 1})),
|
||||
crate::pixel::parse("pixelate.colorHalftone", &json!({"maxRadius": 4}))
|
||||
);
|
||||
// A distance documented without a range, and unknown effects and parameters, have none.
|
||||
assert_eq!(length_range("path.offsetPath", "offset"), None);
|
||||
assert_eq!(length_range("pixelate.colorHalftone", "channel1"), None);
|
||||
assert_eq!(length_range("no.such", "maxRadius"), None);
|
||||
}
|
||||
@@ -10,6 +10,7 @@ pub mod clipboard;
|
||||
mod colorcmds;
|
||||
pub mod colormgmt;
|
||||
pub mod colortheme;
|
||||
mod compoundshape;
|
||||
pub(crate) mod create;
|
||||
mod css;
|
||||
mod cut;
|
||||
@@ -249,6 +250,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(xform::specs());
|
||||
v.extend(effectcmd::specs());
|
||||
v.extend(pathops::specs());
|
||||
v.extend(compoundshape::specs());
|
||||
v.extend(typecmd::specs());
|
||||
v.extend(menucmds::specs());
|
||||
v.extend(live::specs());
|
||||
@@ -378,6 +380,15 @@ pub(crate) fn check_switches(p: &Value, keys: &[&str], cmd: &str) -> Result<()>
|
||||
pub(crate) fn str_param<'a>(p: &'a Value, key: &str) -> Option<&'a str> {
|
||||
p.get(key).and_then(Value::as_str)
|
||||
}
|
||||
/// The string `p` gives for `key`, or `None` when `p` leaves it out or gives null. Any other
|
||||
/// value, such as `5`, is an error: "`{key}` must be a string".
|
||||
pub(crate) fn text_param<'a>(p: &'a Value, key: &str, cmd: &str) -> Result<Option<&'a str>> {
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::String(v)) => Ok(Some(v)),
|
||||
Some(_) => Err(bad(cmd, format!("`{key}` must be a string"))),
|
||||
}
|
||||
}
|
||||
pub(crate) fn id_param(p: &Value, key: &str) -> Option<NodeId> {
|
||||
p.get(key).and_then(Value::as_u64).map(NodeId)
|
||||
}
|
||||
@@ -514,26 +525,30 @@ pub(crate) fn ok() -> Result<Value> {
|
||||
}
|
||||
|
||||
/// Leaves whose appearance a paint command changes: groups and layers expand to their contents,
|
||||
/// and compound paths own their children's appearance, so a member stands for its compound path
|
||||
/// (#3692), which is listed once.
|
||||
/// and compound paths and compound shapes own their members' appearance, so a member stands for
|
||||
/// its compound path (#3692) or compound shape, which is listed once.
|
||||
pub(crate) fn leaf_targets(s: &Session, ids: &[NodeId]) -> Result<Vec<NodeId>> {
|
||||
use vectorcraft_doc::NodeKind;
|
||||
let d = &s.doc()?.doc;
|
||||
let compound = |id: NodeId| d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })));
|
||||
let owns = |n: &vectorcraft_doc::Node| matches!(n.kind, NodeKind::Compound { .. }) || n.is_compound_shape();
|
||||
let compound = |id: NodeId| d.parent_of(id).filter(|p| d.node(*p).is_some_and(owns));
|
||||
let mut out = vec![];
|
||||
for id in ids {
|
||||
let Some(n) = d.node(*id) else { continue };
|
||||
match &n.kind {
|
||||
NodeKind::Group { .. } | NodeKind::Layer { .. } => n.walk(&mut |c| {
|
||||
if !c.is_container() || matches!(c.kind, NodeKind::Compound { .. }) {
|
||||
NodeKind::Group { .. } | NodeKind::Layer { .. } if !n.is_compound_shape() => n.walk(&mut |c| {
|
||||
if !c.is_container() || owns(c) {
|
||||
out.push(c.id)
|
||||
}
|
||||
}),
|
||||
_ => out.push(compound(*id).unwrap_or(*id)),
|
||||
}
|
||||
}
|
||||
let comp: Vec<NodeId> = out.iter().filter(|id| matches!(d.node(**id).map(|n| &n.kind), Some(NodeKind::Compound { .. }))).copied().collect();
|
||||
out.retain(|id| !comp.iter().any(|c| d.parent_of(*id) == Some(*c)));
|
||||
let comp: std::collections::HashSet<NodeId> = out.iter().filter(|id| d.node(**id).is_some_and(owns)).copied().collect();
|
||||
if !comp.is_empty() {
|
||||
// A compound shape's members lie at any depth in it.
|
||||
out.retain(|id| !d.ancestry(*id).is_some_and(|up| up.iter().rev().skip(1).any(|a| comp.contains(a))));
|
||||
}
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
out.retain(|id| seen.insert(*id));
|
||||
Ok(out)
|
||||
@@ -581,6 +596,9 @@ pub use opacitymask::TransparencyInfo;
|
||||
/// Eyedropper Options (`Prefs::eyedropper`).
|
||||
pub use xform::{AppearanceAttrs, EyedropperAttrs, EyedropperOptions, FillAttrs, StrokeAttrs};
|
||||
|
||||
/// The shape modes of the selected compound-shape members (the Pathfinder panel lights theirs).
|
||||
pub use compoundshape::selected_member_modes;
|
||||
|
||||
/// Pathfinder Options (`Prefs::pathfinder`).
|
||||
pub use pathops::{PATHFINDER_PRECISION_RANGE, PathfinderOptions};
|
||||
|
||||
|
||||
@@ -377,8 +377,11 @@ fn grouped(d: &mut Document, nodes: Vec<Node>, parents: &[Option<usize>]) -> Vec
|
||||
struct TraceInputs {
|
||||
target: NodeId,
|
||||
image: Box<ImageObject>,
|
||||
/// The settings traced with, as JSON, the library's colours in.
|
||||
/// The settings traced with, as JSON.
|
||||
params: Value,
|
||||
/// Document Library: the library's colours, which the JSON leaves out
|
||||
/// ([`tr::TraceParams::swatches`]).
|
||||
swatches: Vec<[u8; 3]>,
|
||||
}
|
||||
|
||||
/// What `imageTrace.make` and `imageTrace.makeAndExpand` take from the session before they trace.
|
||||
@@ -431,7 +434,7 @@ fn prepare(s: &Session, c: &str, p: &Value) -> Result<Prepared> {
|
||||
let bytes = Arc::clone(&blob.bytes);
|
||||
let library = trace_library(c, s, &mut params)?;
|
||||
let traced_with = serde_json::to_value(¶ms).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
let inputs = TraceInputs { target, image, params: traced_with };
|
||||
let inputs = TraceInputs { target, image, params: traced_with, swatches: params.swatches.clone() };
|
||||
Ok(Prepared { inputs, trace: params, view, params_json, preset_label, library, bytes })
|
||||
}
|
||||
|
||||
@@ -544,7 +547,7 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
Some(traced) if traced.inputs == inputs => traced,
|
||||
_ => trace_now(&inputs, &trace, &bytes, &|_, _| true)?,
|
||||
};
|
||||
let TraceInputs { target, image: img, params: _ } = inputs;
|
||||
let TraceInputs { target, image: img, .. } = inputs;
|
||||
let warnings = trace_warnings((img.width, img.height), raster, res.worked_at);
|
||||
// Pixel space of the decoded raster → the image object's pixel space → document.
|
||||
let sx = img.width.max(1) as f64 / raster.0.max(1) as f64;
|
||||
|
||||
@@ -645,6 +645,7 @@ fn set_spot(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
if sw.spot != spot {
|
||||
let n = name.clone();
|
||||
let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok();
|
||||
s.edit("Swatch Options", |d, _| {
|
||||
if let Some(w) = d.swatch_mut(&n) {
|
||||
w.spot = spot;
|
||||
@@ -652,7 +653,7 @@ fn set_spot(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
w.global = true;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))
|
||||
})?;
|
||||
}
|
||||
Ok(json!({"name": name, "spot": spot}))
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
//! Pathfinder panel › compound shapes (`object.compoundShape.*`): Make Compound Shape (what
|
||||
//! Alt-clicking a Shape Mode button does), a member's shape mode, Release and Expand Compound
|
||||
//! Shape. A compound shape is a group marked so ([`Node::is_compound_shape`]) whose members each
|
||||
//! have a [`ShapeMode`]; `vectorcraft-effects` draws it as the area they make
|
||||
//! ([`effects::compound_shape_area`]).
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, ShapeMode};
|
||||
use vectorcraft_render::effects;
|
||||
|
||||
use super::edit::{roots_of, selected_roots};
|
||||
use super::pathops::{pf_leaves, shape_node, style_of};
|
||||
use super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_multi};
|
||||
|
||||
const MODE_NAMES: [&str; 4] = ["add", "subtract", "intersect", "exclude"];
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"object.compoundShape.make",
|
||||
"Make Compound Shape",
|
||||
["Window", "Pathfinder"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection), mode?: \"add\"|\"subtract\"|\"intersect\"|\"exclude\" (default add; Alt-clicking a Shape Mode button gives its mode)} the two or more selected objects (paths, compound paths, groups, compound shapes, type) become the members of one compound shape, each with the shape mode, in their stacking order where the frontmost was: it draws as the area they make from the backmost up (open paths closed), painted with the appearance and transparency of the topmost member in Add, Intersect or Exclude mode (with every member in Subtract, the backmost), and the members stay editable (Direct Selection, Layers panel, isolation mode) → {id}",
|
||||
has_multi,
|
||||
make
|
||||
),
|
||||
cmd!(
|
||||
"object.compoundShape.setMode",
|
||||
"Shape Mode",
|
||||
["Window", "Pathfinder"],
|
||||
None,
|
||||
"{mode: \"add\"|\"subtract\"|\"intersect\"|\"exclude\", ids?: [id…] (selected first; default: the selection)} the members of compound shapes that the selected objects are or are in take the shape mode (what clicking a Shape Mode button does with members selected); the backmost member's mode doesn't change the shape → {ids}",
|
||||
has_member,
|
||||
set_mode
|
||||
),
|
||||
cmd!(
|
||||
"object.compoundShape.release",
|
||||
"Release Compound Shape",
|
||||
["Window", "Pathfinder"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection)} the selected compound shapes (and those holding the selected objects) become their members again, as they were before Make Compound Shape, selected → {ids}",
|
||||
has_compound_shape,
|
||||
release
|
||||
),
|
||||
cmd!(
|
||||
"object.compoundShape.expand",
|
||||
"Expand Compound Shape",
|
||||
["Window", "Pathfinder"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection)} the selected compound shapes (and those holding the selected objects) become the path, or compound path, of the area they draw, painted as they are, selected → {ids}",
|
||||
has_compound_shape,
|
||||
expand
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// The innermost compound shape holding `id` (not `id` itself), with the member of it that `id` is
|
||||
/// or is in.
|
||||
fn holder(d: &Document, id: NodeId) -> Option<(NodeId, NodeId)> {
|
||||
let up = d.ancestry(id)?;
|
||||
up.windows(2).rev().find_map(|w| match w {
|
||||
[shape, member] if d.node(*shape).is_some_and(Node::is_compound_shape) => Some((*shape, *member)),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The compound shape `id` is or is in (the innermost).
|
||||
fn shape_of(d: &Document, id: NodeId) -> Option<NodeId> {
|
||||
if d.node(id)?.is_compound_shape() { Some(id) } else { holder(d, id).map(|(shape, _)| shape) }
|
||||
}
|
||||
|
||||
/// The compound shapes the selection is or is in, outermost only, in paint order.
|
||||
fn selected_shapes(s: &Session) -> Result<Vec<NodeId>> {
|
||||
let st = s.doc()?;
|
||||
let mut shapes: Vec<NodeId> = vec![];
|
||||
for id in st.selection.in_paint_order(&st.doc) {
|
||||
if let Some(shape) = shape_of(&st.doc, id).filter(|shape| !shapes.contains(shape)) {
|
||||
shapes.push(shape);
|
||||
}
|
||||
}
|
||||
Ok(roots_of(&st.doc, shapes))
|
||||
}
|
||||
|
||||
/// The members of compound shapes that the selected objects are or are in.
|
||||
fn selected_members(s: &Session) -> Result<Vec<NodeId>> {
|
||||
let st = s.doc()?;
|
||||
let mut members: Vec<NodeId> = vec![];
|
||||
for id in &st.selection.objects {
|
||||
if let Some((_, member)) = holder(&st.doc, *id).filter(|(_, m)| !members.contains(m)) {
|
||||
members.push(member);
|
||||
}
|
||||
}
|
||||
Ok(members)
|
||||
}
|
||||
|
||||
/// The shape modes of the compound-shape members the selection is or is in (none when it is in
|
||||
/// none): the Pathfinder panel lights the Shape Mode button they share.
|
||||
pub fn selected_member_modes(s: &Session) -> Vec<ShapeMode> {
|
||||
let Some(st) = s.active() else { return vec![] };
|
||||
let members = selected_members(s).unwrap_or_default();
|
||||
members.iter().filter_map(|id| st.doc.node(*id)).map(|n| n.extras().shape_mode).collect()
|
||||
}
|
||||
|
||||
/// The selection is or is in a compound shape.
|
||||
fn has_compound_shape(s: &Session) -> std::result::Result<(), String> {
|
||||
let st = s.active().ok_or("no document open")?;
|
||||
if st.selection.objects.iter().any(|id| shape_of(&st.doc, *id).is_some()) { Ok(()) } else { Err("select a compound shape".into()) }
|
||||
}
|
||||
|
||||
/// The selection is or is in a member of a compound shape.
|
||||
fn has_member(s: &Session) -> std::result::Result<(), String> {
|
||||
let st = s.active().ok_or("no document open")?;
|
||||
if st.selection.objects.iter().any(|id| holder(&st.doc, *id).is_some()) { Ok(()) } else { Err("select members of a compound shape".into()) }
|
||||
}
|
||||
|
||||
/// The `mode` param: one of [`MODE_NAMES`], or `default` when it is missing (`None`: required).
|
||||
fn mode_param(p: &Value, cmd: &str, default: Option<ShapeMode>) -> Result<ShapeMode> {
|
||||
match super::object::choice(p, cmd, "mode", &MODE_NAMES)? {
|
||||
Some(name) => ShapeMode::parse(name),
|
||||
None => default,
|
||||
}
|
||||
.ok_or_else(|| bad(cmd, format!("`mode` must be one of {}", MODE_NAMES.join(", "))))
|
||||
}
|
||||
|
||||
fn ids_json(ids: &[NodeId]) -> Value {
|
||||
json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() })
|
||||
}
|
||||
|
||||
fn make(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.compoundShape.make";
|
||||
let mode = mode_param(p, C, Some(ShapeMode::Add))?;
|
||||
let roots = selected_roots(s)?;
|
||||
if roots.len() < 2 {
|
||||
return Err(bad(C, "select at least two objects"));
|
||||
}
|
||||
let d = &s.doc()?.doc;
|
||||
let mut members = Vec::with_capacity(roots.len());
|
||||
for id in &roots {
|
||||
let n = d.node(*id).ok_or(EngineError::NoNode(*id))?;
|
||||
if !matches!(n.kind, NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } | NodeKind::Group { .. } | NodeKind::Text(_)) {
|
||||
return Err(bad(C, "compound shapes take paths, compound paths, groups, compound shapes and type"));
|
||||
}
|
||||
members.push(n);
|
||||
}
|
||||
// The paint and transparency of the topmost member in Add, Intersect or Exclude mode: as they
|
||||
// all have `mode`, the topmost, or the backmost when they all subtract.
|
||||
let order: Vec<&Node> = if mode == ShapeMode::Subtract { members } else { members.into_iter().rev().collect() };
|
||||
let style = order.into_iter().find_map(|n| {
|
||||
let mut lv = vec![];
|
||||
pf_leaves(n, &mut lv);
|
||||
lv.last().map(style_of)
|
||||
});
|
||||
let id = s.edit("Make Compound Shape", |d, sel| {
|
||||
let gid = d.alloc_id();
|
||||
let id = d.wrap(&roots, |children| {
|
||||
let children = children
|
||||
.into_iter()
|
||||
.map(|c| {
|
||||
let mut c = Arc::unwrap_or_clone(c);
|
||||
c.extras_mut().shape_mode = mode;
|
||||
Arc::new(c)
|
||||
})
|
||||
.collect();
|
||||
let mut g = Node::group(gid, children);
|
||||
g.extras_mut().compound_shape = true;
|
||||
if let Some(style) = &style {
|
||||
style.apply(&mut g);
|
||||
}
|
||||
g
|
||||
})?;
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
})?;
|
||||
Ok(json!({ "id": id.0 }))
|
||||
}
|
||||
|
||||
fn set_mode(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.compoundShape.setMode";
|
||||
let mode = mode_param(p, C, None)?;
|
||||
let members = selected_members(s)?;
|
||||
if members.is_empty() {
|
||||
return Err(bad(C, "select members of a compound shape"));
|
||||
}
|
||||
// Members already in the mode leave the document and its undo history as they are.
|
||||
let d = &s.doc()?.doc;
|
||||
if members.iter().all(|id| d.node(*id).is_some_and(|n| n.extras().shape_mode == mode)) {
|
||||
return Ok(ids_json(&members));
|
||||
}
|
||||
s.edit("Shape Mode", |d, _| {
|
||||
for id in &members {
|
||||
d.node_mut(*id).ok_or(EngineError::NoNode(*id))?.extras_mut().shape_mode = mode;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(ids_json(&members))
|
||||
}
|
||||
|
||||
fn release(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let shapes = selected_shapes(s)?;
|
||||
if shapes.is_empty() {
|
||||
return Err(bad("object.compoundShape.release", "select a compound shape"));
|
||||
}
|
||||
let ids = s.edit("Release Compound Shape", |d, sel| {
|
||||
let (mut items, mut released) = (vec![], vec![]);
|
||||
for id in &shapes {
|
||||
let members = d.node(*id).and_then(Node::children).ok_or(EngineError::NoNode(*id))?;
|
||||
let out: Vec<Node> = members
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let mut c = (**c).clone();
|
||||
c.extras_mut().shape_mode = ShapeMode::Add;
|
||||
released.push(c.id);
|
||||
c
|
||||
})
|
||||
.collect();
|
||||
items.push((*id, out));
|
||||
}
|
||||
d.insert_beside(items, true)?;
|
||||
sel.set(released.iter().copied());
|
||||
Ok(released)
|
||||
})?;
|
||||
Ok(ids_json(&ids))
|
||||
}
|
||||
|
||||
fn expand(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
const LABEL: &str = "Expand Compound Shape";
|
||||
let shapes = selected_shapes(s)?;
|
||||
if shapes.is_empty() {
|
||||
return Err(bad("object.compoundShape.expand", "select a compound shape"));
|
||||
}
|
||||
let ids = s.edit(LABEL, |d, sel| {
|
||||
let (mut items, mut made) = (vec![], vec![]);
|
||||
for id in &shapes {
|
||||
let shape = d.node(*id).cloned().ok_or(EngineError::NoNode(*id))?;
|
||||
let area = effects::compound_shape_area(&shape, effects::text_outliner())
|
||||
.ok_or_else(|| EngineError::Other("the compound shape is too complex to expand".into()))?;
|
||||
if area.is_empty() {
|
||||
return Err(EngineError::Other(format!("{LABEL} produced an empty result")));
|
||||
}
|
||||
let mut n = shape_node(d, area, None);
|
||||
let mut appearance = (*shape.appearance).clone();
|
||||
appearance.contents_index = None;
|
||||
n.appearance = appearance.into();
|
||||
(n.opacity, n.blend, n.name) = (shape.opacity, shape.blend, shape.name.clone());
|
||||
made.push(n.id);
|
||||
items.push((*id, vec![n]));
|
||||
}
|
||||
d.insert_beside(items, true)?;
|
||||
sel.set(made.iter().copied());
|
||||
Ok(made)
|
||||
})?;
|
||||
Ok(ids_json(&ids))
|
||||
}
|
||||
@@ -92,7 +92,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Eraser",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…], size?: pt (10), angle?: ° (0), roundness?: % (100, kept within 1–100)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one",
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1), size?: pt (10), sizeMode?: \"fixed\" (default) | \"pressure\" (Eraser Tool Options' Size set to Pressure: the tip is size − sizeVariation across where the pen presses lightest and size + sizeVariation where it presses hardest, as path.blob), sizeVariation?: pt (0), angle?: ° (0), roundness?: % (100, kept within 1–100)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one",
|
||||
has_doc,
|
||||
erase_region
|
||||
),
|
||||
@@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Blob Brush",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…], size?: pt (10), fidelity?: pt (0.01–100; the brush follows the stroke fitted at this tolerance as path.freehand fits a Pencil stroke, and a higher value gives a smoother shape; without it the brush follows every point), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with the topmost touching same-color blob and the touching ones next to it in stacking order in its group or layer → {id}",
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1), size?: pt (10), sizeMode?: \"fixed\" (default) | \"pressure\" (Blob Brush Tool Options' Size set to Pressure: the brush is size − sizeVariation wide at the lightest pen pressure and size + sizeVariation at the heaviest, at least 0.1 pt; a stroke without pressure keeps the size), sizeVariation?: pt (0), fidelity?: pt (0.01–100; the brush follows the stroke fitted at this tolerance as path.freehand fits a Pencil stroke, and a higher value gives a smoother shape; without it the brush follows every point), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with the topmost touching same-color blob and the touching ones next to it in stacking order in its group or layer → {id}",
|
||||
has_doc,
|
||||
blob
|
||||
),
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
use super::{
|
||||
Appearance, Arc, Beside, Cap, Color, Document, EngineError, FillRule, Join, Node, NodeId, NodeKind, Paint, PathData, Point, PressureProfile,
|
||||
Rect, Result, Selection, Session, SubPath, Value, Vec2, bad, index, json, po,
|
||||
Rect, Result, Selection, Session, SubPath, Value, Vec2, bad, index, json, number_or, po,
|
||||
};
|
||||
use vectorcraft_doc::{LineCap, LineJoin, StrokeLayer, WidthProfile};
|
||||
|
||||
// ---------- helpers ----------
|
||||
|
||||
@@ -64,6 +65,36 @@ pub(super) fn stroke_pressure(samples: &[(Point, Option<f64>)]) -> Option<Pressu
|
||||
PressureProfile::from_samples(along.into_iter().map(|(s, p)| (if at > 1e-9 { s / at } else { 0.0 }, p)))
|
||||
}
|
||||
|
||||
/// Blob Brush and Eraser Tool Options' Size set to Pressure (`sizeMode: "pressure"`, with
|
||||
/// `sizeVariation` in points): the stroke's pen pressure along it and the variation, `None` for
|
||||
/// Fixed (the default), no variation or a stroke without pressure (a mouse), which keeps the size.
|
||||
pub(super) fn size_pressure(p: &Value, samples: &[(Point, Option<f64>)], cmd: &str) -> Result<Option<(PressureProfile, f64)>> {
|
||||
match p.get("sizeMode").filter(|v| !v.is_null()).map(|v| v.as_str().ok_or(v)) {
|
||||
None | Some(Ok("fixed")) => Ok(None),
|
||||
Some(Ok("pressure")) => {
|
||||
let variation = number_or(p, "sizeVariation", 0.0, cmd)?;
|
||||
if !(variation.is_finite() && variation >= 0.0) {
|
||||
return Err(bad(cmd, "sizeVariation must be 0 or more"));
|
||||
}
|
||||
Ok(stroke_pressure(samples).filter(|_| variation > 0.0).map(|prof| (prof, variation)))
|
||||
}
|
||||
Some(Ok(other)) => Err(bad(cmd, format!("sizeMode is \"fixed\" or \"pressure\", not `{other}`"))),
|
||||
Some(Err(other)) => Err(bad(cmd, format!("sizeMode is \"fixed\" or \"pressure\", not {other}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The area a stroke along `spine` covers with Size set to Pressure: as wide at each point as
|
||||
/// [`vectorcraft_tools::draw2::pressure_size`] gives for the pressure `prof` records there, with
|
||||
/// round ends and joins, its overlaps united into one outline.
|
||||
pub(super) fn pressure_region(spine: &PathData, size: f64, variation: f64, prof: &PressureProfile) -> Result<PathData> {
|
||||
let widest = size + variation;
|
||||
let width = |t: f64| vectorcraft_tools::draw2::pressure_size(size, variation, prof.at(t)) / widest;
|
||||
let profile = WidthProfile { points: prof.points.iter().map(|&(t, _)| (t, width(t), width(t))).collect() };
|
||||
let round = StrokeLayer { cap: LineCap::Round, join: LineJoin::Round, ..StrokeLayer::new(Paint::None, widest) };
|
||||
let outline = PathData::from_bezpath(&vectorcraft_render::width_outline(&spine.to_bezpath(), widest, &profile, &round, 0.05));
|
||||
po::try_unite_all(&[(&outline, FillRule::NonZero)]).map_err(|e| EngineError::Other(e.to_string()))
|
||||
}
|
||||
|
||||
/// The length of a subpath.
|
||||
pub(super) fn subpath_len(sp: &SubPath) -> f64 {
|
||||
use kurbo::ParamCurveArclen;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::common::{
|
||||
dist_to_polyline, fill_targets, ids_json, path_mut, path_of, points_param, poly_bounds, replace_with_pieces, sibling_with, target_paths,
|
||||
usize_opt,
|
||||
dist_to_polyline, fill_targets, ids_json, path_mut, path_of, points_param, poly_bounds, pressure_region, replace_with_pieces, samples_param,
|
||||
sibling_with, size_pressure, target_paths, usize_opt,
|
||||
};
|
||||
use super::{
|
||||
Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, ParamCurve, PathData, Point, Result, Session, SubPath,
|
||||
@@ -264,30 +264,47 @@ pub(super) fn knife(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "path.eraseRegion";
|
||||
let pts = points_param(p, "points", C)?;
|
||||
let samples = samples_param(p, "points", C)?;
|
||||
let size = number_or(p, "size", 10.0, C)?;
|
||||
if !(size.is_finite() && size > 0.0) {
|
||||
return Err(bad(C, "size must be positive"));
|
||||
}
|
||||
let angle = number_or(p, "angle", 0.0, C)?;
|
||||
let roundness = number_or(p, "roundness", 100.0, C)?;
|
||||
let pressure = size_pressure(p, &samples, C)?;
|
||||
let pts: Vec<Point> = samples.into_iter().map(|(pt, _)| pt).collect();
|
||||
let r = size / 2.0;
|
||||
// The tip's short axis: an open path is sampled at least every half of it.
|
||||
let short = size * roundness.clamp(1.0, 100.0) / 100.0;
|
||||
// The tip's short axis (its narrowest with Pressure): an open path is sampled at least every half of it.
|
||||
let narrowest = pressure.as_ref().map_or(size, |(_, v)| vectorcraft_tools::draw2::pressure_size(size, *v, 0.0));
|
||||
let short = narrowest * roundness.clamp(1.0, 100.0) / 100.0;
|
||||
let st = s.doc()?;
|
||||
let region = eraser_area(&pts, size, angle, roundness);
|
||||
// A point is under the tip when, with the tip squashed back into a circle, it is within the
|
||||
// circle's radius of the squashed drag.
|
||||
let squash = eraser_tip(angle, roundness).inverse();
|
||||
let stretch = eraser_tip(angle, roundness);
|
||||
let squash = stretch.inverse();
|
||||
let round: Vec<Point> = pts.iter().map(|q| squash * *q).collect();
|
||||
// With Size set to Pressure the tip is as wide as the pen pressed: the area is the squashed
|
||||
// drag outlined at those widths, stretched back, and a point is under it when the area holds it.
|
||||
let pressed = match (&pressure, round.len() > 1) {
|
||||
(Some((prof, v)), true) => Some(pressure_region(&PathData::single(SubPath::polyline(&round, false)), size, *v, prof)?.transformed(stretch)),
|
||||
(Some((prof, v)), false) => Some(eraser_area(&pts, vectorcraft_tools::draw2::pressure_size(size, *v, prof.at(0.0)), angle, roundness)),
|
||||
(None, _) => None,
|
||||
};
|
||||
let reach = pressure.as_ref().map_or(r, |(_, v)| (size + v) / 2.0);
|
||||
let region = pressed.clone().unwrap_or_else(|| eraser_area(&pts, size, angle, roundness));
|
||||
let outline = pressed.map(|pd| pd.to_bezpath());
|
||||
let under = |q: Point| match &outline {
|
||||
Some(bp) => fill_contains(bp, FillRule::NonZero, q),
|
||||
None => dist_to_polyline(&round, squash * q) <= r,
|
||||
};
|
||||
let mut plan: Vec<(NodeId, Vec<PathData>)> = vec![];
|
||||
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, r))? {
|
||||
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, reach))? {
|
||||
if pd.is_closed() {
|
||||
if po::area(&po::boolean(&pd, rule, ®ion, FillRule::NonZero, BoolOp::Intersect), FillRule::NonZero) <= 1e-6 {
|
||||
continue;
|
||||
}
|
||||
plan.push((id, components(&po::boolean(&pd, rule, ®ion, FillRule::NonZero, BoolOp::Difference))));
|
||||
} else if let Some(pieces) = erase_outline(&pd, short / 2.0, &|q| dist_to_polyline(&round, squash * q) <= r) {
|
||||
} else if let Some(pieces) = erase_outline(&pd, short / 2.0, &under) {
|
||||
plan.push((id, pieces));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::common::{
|
||||
brush_region, path_kind, path_mut, path_of, points_param, poly_bounds, samples_param, stroke_paint, stroke_pressure, subpath_len, target_paths,
|
||||
within_input_bound,
|
||||
brush_region, path_kind, path_mut, path_of, poly_bounds, pressure_region, samples_param, size_pressure, stroke_paint, stroke_pressure,
|
||||
subpath_len, target_paths, within_input_bound,
|
||||
};
|
||||
use super::{
|
||||
Anchor, Appearance, BTreeSet, BoolOp, Cap, Color, Document, EngineError, FillRule, Join, NewArt, Node, NodeId, NodeKind, Paint, PathData, Point,
|
||||
@@ -602,11 +602,15 @@ fn adjacent_to_topmost(doc: &Document, touched: &[NodeId], paint: &Paint) -> Vec
|
||||
|
||||
pub(super) fn blob(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "path.blob";
|
||||
let pts = points_param(p, "points", C)?;
|
||||
let samples = samples_param(p, "points", C)?;
|
||||
let size = number_or(p, "size", 10.0, C)?;
|
||||
if !(size.is_finite() && size > 0.0) {
|
||||
return Err(bad(C, "size must be positive"));
|
||||
}
|
||||
let pressure = size_pressure(p, &samples, C)?;
|
||||
let pts: Vec<Point> = samples.into_iter().map(|(pt, _)| pt).collect();
|
||||
// The widest the brush gets: the area merges look in.
|
||||
let reach = pressure.as_ref().map_or(size, |(_, v)| size + v);
|
||||
// With `fidelity` (pt), the brush follows the stroke fitted by [`fit_freehand`], as a Pencil
|
||||
// stroke is fitted. Without it, or when the fitted stroke has no length (a short stroke back to
|
||||
// its start), the brush follows every point.
|
||||
@@ -614,11 +618,31 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(_) => Some(number_or(p, "fidelity", 0.0, C)?.clamp(vectorcraft_tools::draw2::MIN_FIDELITY, 100.0)),
|
||||
};
|
||||
let fitted = fidelity
|
||||
.filter(|_| pts.len() > 1)
|
||||
.map(|tol| po::outline_stroke(&PathData::single(fit_freehand(&pts, tol, false)), size, Cap::Round, Join::Round, 4.0))
|
||||
.filter(|r| !r.is_empty());
|
||||
let region = fitted.unwrap_or_else(|| brush_region(&pts, size));
|
||||
let spine = |tol: Option<f64>| match tol {
|
||||
Some(tol) => PathData::single(fit_freehand(&pts, tol, false)),
|
||||
None => PathData::single(SubPath::polyline(&pts, false)),
|
||||
};
|
||||
let region = match (&pressure, pts.len() > 1) {
|
||||
(Some((prof, variation)), true) => {
|
||||
let fitted = match fidelity {
|
||||
Some(tol) => Some(pressure_region(&spine(Some(tol)), size, *variation, prof)?).filter(|r| !r.is_empty()),
|
||||
None => None,
|
||||
};
|
||||
match fitted {
|
||||
Some(r) => r,
|
||||
None => pressure_region(&spine(None), size, *variation, prof)?,
|
||||
}
|
||||
}
|
||||
// A click: one dab as wide as the pen pressed.
|
||||
(Some((prof, variation)), false) => brush_region(&pts, vectorcraft_tools::draw2::pressure_size(size, *variation, prof.at(0.0))),
|
||||
(None, _) => {
|
||||
let fitted = fidelity
|
||||
.filter(|_| pts.len() > 1)
|
||||
.map(|tol| po::outline_stroke(&spine(Some(tol)), size, Cap::Round, Join::Round, 4.0))
|
||||
.filter(|r| !r.is_empty());
|
||||
fitted.unwrap_or_else(|| brush_region(&pts, size))
|
||||
}
|
||||
};
|
||||
if region.is_empty() {
|
||||
return Err(EngineError::Other("empty brush stroke".into()));
|
||||
}
|
||||
@@ -638,7 +662,7 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let all = Selection::default();
|
||||
let from = if only_selection { &st.selection } else { &all };
|
||||
// A fitted stroke can curve outside the points' bounds, so the area also takes in the shape.
|
||||
let area = region.control_bounds().map_or_else(|| poly_bounds(&pts, size), |b| b.union(poly_bounds(&pts, size)));
|
||||
let area = region.control_bounds().map_or_else(|| poly_bounds(&pts, reach), |b| b.union(poly_bounds(&pts, reach)));
|
||||
for id in target_paths(&st.doc, from, area) {
|
||||
let Some(n) = st.doc.node(id) else { continue };
|
||||
if !blob_match(n, &paint) {
|
||||
|
||||
@@ -68,7 +68,7 @@ fn solid_effects_apply_save_edit_export_expand_and_undo() {
|
||||
assert!(s.execute("effect.setParams", &json!({"index": 0, "params": {"bevel": "nope"}, "ids": [id.0], "item": null})).is_err());
|
||||
let svg = s.execute("document.serialize", &json!({"format": "svg"})).unwrap();
|
||||
let svg = svg["data"].as_str().or_else(|| svg["text"].as_str()).map(str::to_string).unwrap_or_else(|| svg.to_string());
|
||||
assert!(svg.matches("<path").count() >= 2, "{effect}: exported as vector faces");
|
||||
assert!(vectorcraft_testkit::svg_shapes(&svg) >= 2, "{effect}: exported as vector faces");
|
||||
s.execute("effect.expandAppearance", &json!({"ids": [id.0]})).unwrap();
|
||||
assert!(matches!(node(&s, id).kind, NodeKind::Group { .. }), "{effect}");
|
||||
assert!(!effects::has_solid(&node(&s, id)));
|
||||
|
||||
@@ -36,6 +36,7 @@ pub(crate) use load::{MAX_RASTER_ALLOC, size_note};
|
||||
mod metafile;
|
||||
mod naming;
|
||||
mod native;
|
||||
mod pcxread;
|
||||
pub mod pdf;
|
||||
mod pdfimport;
|
||||
pub mod pngtext;
|
||||
@@ -192,6 +193,9 @@ mod tests_psd;
|
||||
#[cfg(test)]
|
||||
mod tests_psdread;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests_pcxread;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests_epsimport;
|
||||
|
||||
|
||||
@@ -489,6 +489,8 @@ pub const FORMATS: &[Format] = &[
|
||||
reader("psb", "PSB", &["psb"], "image/x-psb", true),
|
||||
// PostScript programs, read as EPS files are; Print to PostScript writes them, exports don't.
|
||||
reader("ps", "PostScript", &["ps"], "application/postscript", false),
|
||||
// ZSoft PCX images, read by `pcxread` and stored as PNG; exports don't write them.
|
||||
reader("pcx", "PCX", &["pcx"], "image/x-pcx", true),
|
||||
];
|
||||
|
||||
/// Every extension `document.open` reads (the "All readable files" filter of open dialogs).
|
||||
@@ -512,6 +514,7 @@ pub const OPEN_EXTS: &[&str] = &[
|
||||
"vda",
|
||||
"icb",
|
||||
"vst",
|
||||
"pcx",
|
||||
"psd",
|
||||
"psb",
|
||||
"vctemplate",
|
||||
@@ -528,10 +531,10 @@ pub const OPEN_EXTS: &[&str] = &[
|
||||
|
||||
/// Extensions in [`OPEN_EXTS`] the packaging declares no type for: Photoshop documents belong to
|
||||
/// raster editors, so Finder and file managers don't offer a vector app for them, and there is no
|
||||
/// `.epsf`, `.ps` or Targa type (File › Open and Place still read them all). On Linux the desktop
|
||||
/// entry's EPS type (shared-mime-info's) also covers `.epsf`, so file managers offer VectorCraft
|
||||
/// for it.
|
||||
pub const UNASSOCIATED_EXTS: &[&str] = &["psd", "psb", "epsf", "ps", "tga", "vda", "icb", "vst"];
|
||||
/// `.epsf`, `.ps`, Targa or PCX type (File › Open and Place still read them all). On Linux the
|
||||
/// desktop entry's EPS type (shared-mime-info's) also covers `.epsf`, so file managers offer
|
||||
/// VectorCraft for it.
|
||||
pub const UNASSOCIATED_EXTS: &[&str] = &["psd", "psb", "epsf", "ps", "tga", "vda", "icb", "vst", "pcx"];
|
||||
|
||||
/// The extension that picks each writable format when exporting (the format's first; PNG-8 shares
|
||||
/// `.png` with PNG, so `.png` comes once), in [`FORMATS`] order.
|
||||
@@ -577,6 +580,7 @@ pub const PLACE_EXTS: &[&str] = &[
|
||||
"vda",
|
||||
"icb",
|
||||
"vst",
|
||||
"pcx",
|
||||
"psd",
|
||||
"psb",
|
||||
"vctemplate",
|
||||
|
||||
@@ -197,6 +197,13 @@ fn from_editing_data_alone(bytes: &[u8], opts: &LoadOptions) -> Option<Result<(D
|
||||
)
|
||||
}
|
||||
|
||||
/// Does `doc` hold no art: only layers, with nothing in them?
|
||||
fn draws_nothing(doc: &Document) -> bool {
|
||||
let mut art = false;
|
||||
doc.walk(|n| art |= !n.is_layer());
|
||||
!art
|
||||
}
|
||||
|
||||
/// Is `e` the error of a file whose pages are only a placeholder
|
||||
/// ([`vectorcraft_pdf::PdfError::PlaceholderOnly`])?
|
||||
pub(crate) fn is_placeholder(e: &EngineError) -> bool {
|
||||
@@ -272,8 +279,13 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
restore_or_import(editing, || match super::pdfimport::import(bytes, opts, format.id != "pdf") {
|
||||
Ok(r) => {
|
||||
// Pages of text alone: the editing copy alone where it reads, as for a file
|
||||
// saved without its PDF part (#1387: else the page, which is the art).
|
||||
let alone = r.only_text.then(|| from_editing_data_alone(bytes, opts)).flatten().and_then(|read| read.ok());
|
||||
// saved without its PDF part (#1387: else the page, which is the art). So too
|
||||
// pages that draw nothing at all: there is no page art to check the layers
|
||||
// against, and the empty page would lose all of it.
|
||||
let alone = (r.only_text || draws_nothing(&r.document))
|
||||
.then(|| from_editing_data_alone(bytes, opts))
|
||||
.flatten()
|
||||
.and_then(|read| read.ok());
|
||||
let (doc, warnings, read) = match alone {
|
||||
Some((doc, warnings)) => (doc, warnings, true),
|
||||
None => through_editing_data(bytes, opts, r.document, r.warnings, r.user_unit),
|
||||
@@ -561,6 +573,8 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option<String> {
|
||||
/// too ([`vectorcraft_doc::cmyk::group3_tiff_rgba`]).
|
||||
/// Grayscale TIFFs with an alpha channel or other extra channels, which the decoder can't read
|
||||
/// either, become RGBA too, whether they store their channels together or one plane per channel.
|
||||
/// A PCX file is recognized by its header ([`super::pcxread::is_pcx`]) and read by
|
||||
/// [`super::pcxread::decode`], which refuses an image past [`MAX_RASTER_ALLOC`] before decoding.
|
||||
/// A Targa file, which starts with no signature, is recognized by its header
|
||||
/// ([`super::tgaread::is_targa`]) and becomes RGBA with the transparency it stores
|
||||
/// ([`super::tgaread::fix_alpha`]). An image stored as PNG whose decoded samples, or whose pixels
|
||||
@@ -580,6 +594,9 @@ pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
|
||||
if reader.format().is_none() && super::tgaread::is_targa(bytes) {
|
||||
reader.set_format(image::ImageFormat::Tga);
|
||||
}
|
||||
if reader.format().is_none() && super::pcxread::is_pcx(bytes) {
|
||||
return as_png(super::pcxread::decode(bytes, MAX_RASTER_ALLOC).map_err(err)?, ppi);
|
||||
}
|
||||
let mut limits = image::Limits::default();
|
||||
limits.max_alloc = Some(MAX_RASTER_ALLOC);
|
||||
reader.limits(limits);
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
//! Reading PCX files (`.pcx`) for File › Open and File › Place, from the ZSoft PCX Technical
|
||||
//! Reference Manual (release 5). [`is_pcx`] recognizes a file by the first fields of its 128-byte
|
||||
//! header, and [`decode`] reads its run-length encoded scan lines into RGBA pixels: 1-bit with two
|
||||
//! colors; 1-bit in two to four planes and 4-bit with up to 16 colors; 2-bit CGA pictures in the
|
||||
//! four colors their CGA palette settings pick; 8-bit with the
|
||||
//! 256-color palette after the image data (gray levels without one); and 24-bit color in three
|
||||
//! 8-bit planes. The file is untrusted: every read is checked.
|
||||
|
||||
/// The size of the header, after which the image data starts.
|
||||
const HEADER: usize = 128;
|
||||
|
||||
/// The message for a file whose header or image data ends early.
|
||||
const TRUNCATED: &str = "the PCX file is cut short";
|
||||
|
||||
/// The message for a header whose window or line length can't hold its image.
|
||||
const DAMAGED: &str = "the PCX file's header is damaged";
|
||||
|
||||
/// The 16 colors of the EGA palette, which files of versions 0 and 3 use instead of the header's.
|
||||
const EGA: [[u8; 3]; 16] = [
|
||||
[0x00, 0x00, 0x00],
|
||||
[0x00, 0x00, 0xaa],
|
||||
[0x00, 0xaa, 0x00],
|
||||
[0x00, 0xaa, 0xaa],
|
||||
[0xaa, 0x00, 0x00],
|
||||
[0xaa, 0x00, 0xaa],
|
||||
[0xaa, 0x55, 0x00],
|
||||
[0xaa, 0xaa, 0xaa],
|
||||
[0x55, 0x55, 0x55],
|
||||
[0x55, 0x55, 0xff],
|
||||
[0x55, 0xff, 0x55],
|
||||
[0x55, 0xff, 0xff],
|
||||
[0xff, 0x55, 0x55],
|
||||
[0xff, 0x55, 0xff],
|
||||
[0xff, 0xff, 0x55],
|
||||
[0xff, 0xff, 0xff],
|
||||
];
|
||||
|
||||
/// Does `bytes` start with a PCX header? The manufacturer byte is `0x0A`, the version 0, 2, 3, 4
|
||||
/// or 5, the encoding 1 (run-length) and the bits per pixel of each plane 1, 2, 4 or 8.
|
||||
pub(super) fn is_pcx(bytes: &[u8]) -> bool {
|
||||
matches!(bytes, [0x0a, 0 | 2 | 3 | 4 | 5, 1, 1 | 2 | 4 | 8, ..])
|
||||
}
|
||||
|
||||
/// The resolution in the header's HDpi and VDpi fields; `None` when either is 0 or the header is
|
||||
/// cut short.
|
||||
pub(super) fn resolution(bytes: &[u8]) -> Option<(f64, f64)> {
|
||||
let le = |at: usize| Some(u16::from_le_bytes([*bytes.get(at)?, *bytes.get(at + 1)?]));
|
||||
let (x, y) = (le(12)?, le(14)?);
|
||||
(x > 0 && y > 0).then(|| (f64::from(x), f64::from(y)))
|
||||
}
|
||||
|
||||
/// The pixels of PCX file `bytes`, which [`is_pcx`] accepts, refused when they or the decoded
|
||||
/// scan lines take more than `max_alloc` bytes (the pixels counted as RGBA) before anything is
|
||||
/// decoded.
|
||||
pub(super) fn decode(bytes: &[u8], max_alloc: u64) -> Result<image::RgbaImage, String> {
|
||||
let head = bytes.get(..HEADER).ok_or(TRUNCATED)?;
|
||||
let le = |at: usize| usize::from(u16::from_le_bytes([head[at], head[at + 1]]));
|
||||
let (version, bits, planes) = (head[1], head[3], head[65]);
|
||||
let (x_min, y_min, x_max, y_max) = (le(4), le(6), le(8), le(10));
|
||||
let line = le(66);
|
||||
if !matches!((bits, planes), (1, 1..=4) | (2 | 4, 1) | (8, 1 | 3)) {
|
||||
return Err(format!("PCX files with {bits}-bit pixels in {planes} planes can't be read"));
|
||||
}
|
||||
if x_max < x_min || y_max < y_min {
|
||||
return Err(DAMAGED.into());
|
||||
}
|
||||
let (w, h) = (x_max - x_min + 1, y_max - y_min + 1);
|
||||
// Each plane's line holds the row's pixels, padded to an even number of bytes.
|
||||
if line * 8 < w * usize::from(bits) {
|
||||
return Err(DAMAGED.into());
|
||||
}
|
||||
let scan = line * usize::from(planes);
|
||||
let rgba = w as u64 * h as u64 * 4;
|
||||
if rgba > max_alloc || scan as u64 * h as u64 > max_alloc {
|
||||
return Err(format!("an image of {w} × {h} pixels is too large to draw"));
|
||||
}
|
||||
// An 8-bit image's 256-color palette is its last 769 bytes, `0x0C` and then the colors; the
|
||||
// image data ends before it. A `0x0C` there is image data instead when the image data runs to
|
||||
// the end of the file.
|
||||
let candidate = bytes.len().checked_sub(769).filter(|at| *at >= HEADER && (bits, planes) == (8, 1) && bytes.get(*at) == Some(&0x0c));
|
||||
let body = bytes.get(HEADER..).unwrap_or_default();
|
||||
let (tail, decoded) = match candidate {
|
||||
Some(at) => match unpack(body, scan * h) {
|
||||
Ok((data, used)) if used == body.len() => (None, Ok((data, used))),
|
||||
_ => (Some(at), unpack(bytes.get(HEADER..at).unwrap_or_default(), scan * h)),
|
||||
},
|
||||
None => (None, unpack(body, scan * h)),
|
||||
};
|
||||
let (data, used) = decoded?;
|
||||
// A palette marker right after the image data with fewer than 768 colors after it is a palette
|
||||
// cut short.
|
||||
let after = bytes.get(HEADER + used..).unwrap_or_default();
|
||||
if tail.is_none() && (bits, planes) == (8, 1) && after.first() == Some(&0x0c) && after.len() < 769 {
|
||||
return Err(TRUNCATED.into());
|
||||
}
|
||||
let palette: Vec<[u8; 3]> = match (bits, planes) {
|
||||
(8, 1) => match tail.and_then(|at| bytes.get(at + 1..)) {
|
||||
Some(colors) => colors.as_chunks::<3>().0.to_vec(),
|
||||
None => (0..=255).map(|v| [v; 3]).collect(),
|
||||
},
|
||||
// A 1-bit image takes the header palette's first two colors; versions without a palette,
|
||||
// and headers whose two colors are the same (left unset), give black and white.
|
||||
(1, 1) if matches!(version, 0 | 3) || head[16..19] == head[19..22] => vec![[0; 3], [255; 3]],
|
||||
// A 2-bit image is a CGA picture, whose header holds CGA palette settings instead of colors.
|
||||
(2, 1) => cga(head[16], head[19]),
|
||||
_ if matches!(version, 0 | 3) => EGA.to_vec(),
|
||||
_ => head[16..64].as_chunks::<3>().0.to_vec(),
|
||||
};
|
||||
let mut img = image::RgbaImage::new(w as u32, h as u32);
|
||||
for (y, row) in data.chunks_exact(scan).enumerate() {
|
||||
let plane = |p: usize| row.get(p * line..(p + 1) * line).unwrap_or_default();
|
||||
for x in 0..w {
|
||||
let rgb = if bits == 8 && planes == 3 {
|
||||
[0, 1, 2].map(|p| plane(p).get(x).copied().unwrap_or(0))
|
||||
} else {
|
||||
// Plane p gives bits p × bits and up of the color index.
|
||||
let index = (0..usize::from(planes)).fold(0, |index, p| {
|
||||
let at = x * usize::from(bits);
|
||||
let byte = plane(p).get(at / 8).copied().unwrap_or(0);
|
||||
let value = (byte >> (8 - usize::from(bits) - at % 8)) & (0xff >> (8 - bits));
|
||||
index | usize::from(value) << (p * usize::from(bits))
|
||||
});
|
||||
palette.get(index).copied().unwrap_or([0; 3])
|
||||
};
|
||||
img.put_pixel(x as u32, y as u32, image::Rgba([rgb[0], rgb[1], rgb[2], 255]));
|
||||
}
|
||||
}
|
||||
Ok(img)
|
||||
}
|
||||
|
||||
/// The four colors of a CGA picture from header bytes 16 and 19. The top four bits of `background`
|
||||
/// are the EGA color of index 0. The top three bits of `settings` are the color burst, palette and
|
||||
/// intensity bits (C, P, I), which pick the other three: with color burst on (C = 0), P = 0 gives
|
||||
/// green, red and brown and P = 1 gives cyan, magenta and light gray; with it off (C = 1) they are
|
||||
/// cyan, red and light gray. I = 1 gives the bright version of each (brown becomes yellow).
|
||||
fn cga(background: u8, settings: u8) -> Vec<[u8; 3]> {
|
||||
let foreground: [usize; 3] = match settings >> 6 {
|
||||
0 => [2, 4, 6],
|
||||
1 => [3, 5, 7],
|
||||
_ => [3, 4, 7],
|
||||
};
|
||||
let bright = if settings & 0x20 != 0 { 8 } else { 0 };
|
||||
let ega = |i: usize| EGA.get(i).copied().unwrap_or([0; 3]);
|
||||
let mut colors = vec![ega(usize::from(background >> 4))];
|
||||
colors.extend(foreground.map(|i| ega(i + bright)));
|
||||
colors
|
||||
}
|
||||
|
||||
/// `len` bytes of run-length encoded image data: a byte with its top two bits set repeats the
|
||||
/// next byte as many times as its other six bits count, and any other byte stands for itself.
|
||||
/// Runs may cross the end of a scan line. Also returns how many bytes of `data` were read.
|
||||
fn unpack(data: &[u8], len: usize) -> Result<(Vec<u8>, usize), String> {
|
||||
let mut out = Vec::with_capacity(len);
|
||||
let mut bytes = data.iter();
|
||||
while out.len() < len {
|
||||
let &b = bytes.next().ok_or(TRUNCATED)?;
|
||||
if b & 0xc0 == 0xc0 {
|
||||
let &v = bytes.next().ok_or(TRUNCATED)?;
|
||||
let n = usize::from(b & 0x3f).min(len - out.len());
|
||||
out.resize(out.len() + n, v);
|
||||
} else {
|
||||
out.push(b);
|
||||
}
|
||||
}
|
||||
Ok((out, data.len() - bytes.len()))
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Image resolution metadata (pixels per inch): PNG `pHYs`, JPEG JFIF density or EXIF, TIFF and
|
||||
//! WebP EXIF resolution tags, BMP pixels per metre, a Photoshop document's ResolutionInfo. Place
|
||||
//! WebP EXIF resolution tags, BMP pixels per metre, a Photoshop document's ResolutionInfo, a PCX
|
||||
//! header's HDpi and VDpi. Place
|
||||
//! sizes an image by it (72 ppi when the file has none); images converted to PNG on import keep it
|
||||
//! as a `pHYs` chunk.
|
||||
|
||||
@@ -21,6 +22,8 @@ pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> {
|
||||
bmp(bytes)
|
||||
} else if super::psdread::is_psd(bytes) {
|
||||
super::psdread::resolution(bytes)
|
||||
} else if super::pcxread::is_pcx(bytes) {
|
||||
super::pcxread::resolution(bytes)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
@@ -535,6 +535,47 @@ fn an_ai_file_whose_pdf_part_is_only_text_still_opens_from_editing_data_that_rea
|
||||
check_sample(&s);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ai_file_whose_pdf_part_is_cropped_to_its_art_opens_from_its_layers() {
|
||||
// A 400 × 200 pt artboard with two red bars across (100, 50)–(300, 150). The PDF part's page
|
||||
// is that art's box, 200 × 100 pt (the editing data's bounding box), not the artboard.
|
||||
let red = "0 1 1 0 1 0 0 Xa\n";
|
||||
let art = ai::layer("Art", &format!("{red}{}f\n{red}{}f\n", ai::rect(100.0, 50.0, 180.0, 150.0), ai::rect(220.0, 50.0, 300.0, 150.0)));
|
||||
let data = ai::editing_data_in([100.0, 50.0, 300.0, 150.0], [0.0, 0.0, 400.0, 200.0], &art);
|
||||
let page = "1 0 0 rg 0 0 80 100 re f 120 0 80 100 re f";
|
||||
let mut s = Session::new();
|
||||
let r = open(&mut s, "cropped.ai", &ai::ai(&compressed(data.as_bytes()), page), json!({})).unwrap();
|
||||
assert!(!r["warnings"].to_string().contains("weren't read"), "{r}");
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert_eq!(names(&doc.layers), ["Art"]);
|
||||
assert_eq!(doc.artboards.len(), 1);
|
||||
assert_eq!(doc.artboards[0].rect, vectorcraft_geom::Rect::new(0.0, 0.0, 400.0, 200.0), "the file's artboard, not its page");
|
||||
let bars = doc.layers[0].children().unwrap();
|
||||
assert_eq!(bars.len(), 2);
|
||||
let b = bars[0].geometric_bounds().unwrap();
|
||||
assert!((b.x0 - 100.0).abs() < 0.01 && (b.y0 - 50.0).abs() < 0.01, "where the artboard has it: {b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ai_file_whose_pdf_part_draws_nothing_opens_from_its_editing_data() {
|
||||
// A PDF-compatible `.ai` whose PDF part is a page with nothing on it (no notice text either),
|
||||
// with or without the boxes that say where its art is: its editing data is the art.
|
||||
for boxed in ["", "/ArtBox [0 0 200 100] /TrimBox [0 0 200 100]"] {
|
||||
let mut s = Session::new();
|
||||
let r = open(&mut s, "blank.ai", &ai::ai_with(&compressed(&ai::sample_data()), "", boxed), json!({})).unwrap();
|
||||
assert_eq!(r["warnings"], json!([]), "{boxed:?}: {r}");
|
||||
check_sample(&s);
|
||||
// The PDF part alone, as asked: its empty page.
|
||||
open(&mut s, "blank.ai", &ai::ai_with(&compressed(&ai::sample_data()), "", boxed), json!({"editingData": false})).unwrap();
|
||||
let layers = &s.doc().unwrap().doc.layers;
|
||||
assert!(layers.iter().all(|l| l.children().is_none_or(|c| c.is_empty())), "{boxed:?}");
|
||||
}
|
||||
// Editing data that can't be read leaves the empty page, as before.
|
||||
let mut s = Session::new();
|
||||
open(&mut s, "blank.ai", &ai::ai(b"%AI24_ZStandard_Data\0\0\0\0\0\0\0\0", ""), json!({})).unwrap();
|
||||
assert_ne!(names(&s.doc().unwrap().doc.layers), ["Art", "Hidden"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editing_data_false_opens_only_what_the_page_prints() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -101,7 +101,7 @@ fn selected_only_exports_the_selection_in_its_layers() {
|
||||
// Other formats take it too.
|
||||
s.execute("select.set", &json!({"ids": [line]})).unwrap();
|
||||
let svg = s.execute("document.serialize", &json!({"format": "svg", "selectedOnly": true})).unwrap()["text"].as_str().unwrap().to_string();
|
||||
assert_eq!((svg.matches("<path").count(), svg.matches("<rect").count()), (1, 0), "{svg}");
|
||||
assert_eq!((vectorcraft_testkit::svg_shapes(&svg), svg.matches("<line ").count()), (1, 1), "{svg}");
|
||||
assert!(svg.contains("id=\"Top\"") && !svg.contains("Layer"), "{svg}");
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
//! Reading PCX files: every depth and plane layout decodes to the pixels it stores, the files open,
|
||||
//! place and paste at the resolution their header gives, and damaged files are refused with a
|
||||
//! message.
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
use super::pcxread::{decode, is_pcx};
|
||||
use super::*;
|
||||
|
||||
/// A PCX file of `version`, `bits` per pixel in `planes` planes, `w` × `h` pixels from (`x0`, 0),
|
||||
/// `line` bytes per plane line, `dpi` both ways, the header palette `colors` (up to 16 entries),
|
||||
/// then the encoded image data `data`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn pcx(version: u8, bits: u8, planes: u8, x0: u16, (w, h): (u16, u16), line: u16, dpi: u16, colors: &[[u8; 3]], data: &[u8]) -> Vec<u8> {
|
||||
let mut f = vec![0x0a, version, 1, bits];
|
||||
for v in [x0, 0, x0.wrapping_add(w).wrapping_sub(1), h.wrapping_sub(1), dpi, dpi] {
|
||||
f.extend(v.to_le_bytes());
|
||||
}
|
||||
let mut palette = [0; 48];
|
||||
for (i, c) in colors.iter().take(16).enumerate() {
|
||||
palette[i * 3..i * 3 + 3].copy_from_slice(c);
|
||||
}
|
||||
f.extend(palette);
|
||||
f.extend([0, planes]);
|
||||
f.extend(line.to_le_bytes());
|
||||
f.extend(1u16.to_le_bytes());
|
||||
f.resize(128, 0);
|
||||
f.extend(data);
|
||||
f
|
||||
}
|
||||
|
||||
/// `raw` run-length encoded as the manual describes: runs of up to 63 bytes, and single bytes with
|
||||
/// their top two bits set written as runs of one.
|
||||
fn rle(raw: &[u8]) -> Vec<u8> {
|
||||
let mut out = vec![];
|
||||
let mut i = 0;
|
||||
while i < raw.len() {
|
||||
let n = raw[i..].iter().take(63).take_while(|b| **b == raw[i]).count();
|
||||
if n > 1 || raw[i] >= 0xc0 {
|
||||
out.extend([0xc0 | n as u8, raw[i]]);
|
||||
} else {
|
||||
out.push(raw[i]);
|
||||
}
|
||||
i += n;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The pixels `raster_image` stores for `f`, row by row.
|
||||
fn pixels(f: &[u8]) -> Vec<[u8; 4]> {
|
||||
let img = raster_image(f).unwrap();
|
||||
image::load_from_memory(&img.blob.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect()
|
||||
}
|
||||
|
||||
/// The 16 colors of a header palette: entry `i` is (16 i, 255 − 16 i, i).
|
||||
fn header_colors() -> Vec<[u8; 3]> {
|
||||
(0..16u8).map(|i| [i * 16, 255 - i * 16, i]).collect()
|
||||
}
|
||||
|
||||
fn opaque([r, g, b]: [u8; 3]) -> [u8; 4] {
|
||||
[r, g, b, 255]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_depth_and_plane_layout_reads() {
|
||||
let colors = header_colors();
|
||||
let (white, black) = ([255; 4], [0, 0, 0, 255]);
|
||||
|
||||
// 1 bit, three pixels in a two-byte line: 101 and 010, in the header palette's first two colors
|
||||
// (here inverted: white, then black).
|
||||
let bits = rle(&[0b1010_0000, 0, 0b0100_0000, 0]);
|
||||
let f = pcx(5, 1, 1, 0, (3, 2), 2, 0, &[[255; 3], [0; 3]], &bits);
|
||||
assert_eq!(pixels(&f), [black, white, black, white, black, white]);
|
||||
let f = pcx(5, 1, 1, 0, (3, 2), 2, 0, &colors, &bits);
|
||||
let (zero, one) = (opaque(colors[0]), opaque(colors[1]));
|
||||
assert_eq!(pixels(&f), [one, zero, one, zero, one, zero]);
|
||||
// Black and white when the palette is left unset or the version has none.
|
||||
for (version, palette) in [(5, &[][..]), (3, &colors[..])] {
|
||||
let f = pcx(version, 1, 1, 0, (3, 2), 2, 0, palette, &bits);
|
||||
assert_eq!(pixels(&f), [white, black, white, black, white, black], "version {version}");
|
||||
}
|
||||
|
||||
// 1 bit in four planes: plane p gives bit p of the index; indices 5 and 10.
|
||||
let planes = rle(&[0x80, 0, 0x40, 0, 0x80, 0, 0x40, 0]);
|
||||
let f = pcx(5, 1, 4, 0, (2, 1), 2, 0, &colors, &planes);
|
||||
assert_eq!(pixels(&f), [opaque(colors[5]), opaque(colors[10])], "the header palette");
|
||||
// Versions 0 and 3 have no palette in their header: the EGA colors.
|
||||
for version in [0, 3] {
|
||||
let f = pcx(version, 1, 4, 0, (2, 1), 2, 0, &colors, &planes);
|
||||
assert_eq!(pixels(&f), [[0xaa, 0, 0xaa, 255], [0x55, 0xff, 0x55, 255]], "version {version}");
|
||||
}
|
||||
// Two planes give four colors, three give eight: index 3 and 6 (planes 1 and 2).
|
||||
let f = pcx(5, 1, 3, 0, (2, 1), 2, 0, &colors, &rle(&[0x80, 0, 0xc0, 0, 0x40, 0]));
|
||||
assert_eq!(pixels(&f), [opaque(colors[3]), opaque(colors[6])]);
|
||||
|
||||
// 2 bits: indices 0 to 3 in one byte, the first pixel in the top bits, in the CGA colors that
|
||||
// header bytes 16 (the background, in its top four bits) and 19 (C, P and I) pick.
|
||||
let cga = |background: u8, settings: u8| {
|
||||
let f = pcx(5, 2, 1, 0, (4, 1), 2, 0, &[[background, 0, 0], [settings, 0, 0]], &rle(&[0b0001_1011, 0]));
|
||||
pixels(&f)
|
||||
};
|
||||
let (blue, cyan, magenta, light_gray) = ([0, 0, 0xaa, 255], [0, 0xaa, 0xaa, 255], [0xaa, 0, 0xaa, 255], [0xaa; 3]);
|
||||
assert_eq!(cga(0x10, 0b0100_0000), [blue, cyan, magenta, opaque(light_gray)], "P = 1, dim");
|
||||
let (light_green, light_red, yellow) = ([0x55, 0xff, 0x55, 255], [0xff, 0x55, 0x55, 255], [0xff, 0xff, 0x55, 255]);
|
||||
assert_eq!(cga(0x0f, 0b0011_1111), [black, light_green, light_red, yellow], "P = 0, bright; low bits ignored");
|
||||
assert_eq!(cga(0xf0, 0b1010_0000), [white, [0x55, 0xff, 0xff, 255], light_red, white], "C = 1, bright");
|
||||
assert_eq!(cga(0, 0)[1..], [[0, 0xaa, 0, 255], [0xaa, 0, 0, 255], [0xaa, 0x55, 0, 255]], "P = 0, dim");
|
||||
|
||||
// 4 bits: indices 15, 1 and 7.
|
||||
let f = pcx(5, 4, 1, 0, (3, 1), 2, 0, &colors, &rle(&[0xf1, 0x70]));
|
||||
assert_eq!(pixels(&f), [opaque(colors[15]), opaque(colors[1]), opaque(colors[7])]);
|
||||
|
||||
// 8 bits with the 256-color palette after the image data, from a window that starts at x 10:
|
||||
// entry i is (i, 255 − i, 7).
|
||||
let mut f = pcx(5, 8, 1, 10, (2, 2), 2, 0, &[], &rle(&[0, 1, 254, 255]));
|
||||
f.push(0x0c);
|
||||
f.extend((0..=255u8).flat_map(|i| [i, 255 - i, 7]));
|
||||
assert_eq!(pixels(&f), [[0, 255, 7, 255], [1, 254, 7, 255], [254, 1, 7, 255], [255, 0, 7, 255]]);
|
||||
// Without it, the index is a gray level.
|
||||
let f = pcx(5, 8, 1, 0, (2, 2), 2, 0, &[], &rle(&[0, 1, 254, 255]));
|
||||
assert_eq!(pixels(&f), [[0, 0, 0, 255], [1, 1, 1, 255], [254, 254, 254, 255], [255; 4]]);
|
||||
// A gray level 12 769 bytes before the end of image data that runs to the end of the file.
|
||||
let mut levels = vec![1; 1000];
|
||||
levels[231] = 0x0c;
|
||||
let f = pcx(5, 8, 1, 0, (1000, 1), 1000, 0, &[], &levels);
|
||||
assert_eq!(f.len() - 769, 128 + 231);
|
||||
let read = pixels(&f);
|
||||
assert_eq!((read.len(), read[231], read[232]), (1000, [12, 12, 12, 255], [1, 1, 1, 255]));
|
||||
// A run may cross the end of a scan line.
|
||||
let f = pcx(5, 8, 1, 0, (2, 2), 2, 0, &[], &[0xc4, 9]);
|
||||
assert_eq!(pixels(&f), [[9, 9, 9, 255]; 4]);
|
||||
|
||||
// 24 bits: each line holds its red, green and blue planes in turn; the padding byte is skipped.
|
||||
let f = pcx(5, 8, 3, 0, (1, 2), 2, 0, &[], &rle(&[10, 0, 30, 0, 50, 0, 20, 0, 40, 0, 60, 0]));
|
||||
assert_eq!(pixels(&f), [[10, 30, 50, 255], [20, 40, 60, 255]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pcx_files_open_place_and_paste_at_their_resolution() {
|
||||
use crate::cmd::clipboard::{PASTE_ORDER, file_flavour};
|
||||
let b64 = vectorcraft_format::base64_encode;
|
||||
let f = pcx(5, 8, 3, 0, (2, 1), 2, 144, &[], &rle(&[10, 20, 30, 40, 50, 60]));
|
||||
assert_eq!(ppi::resolution(&f), Some((144.0, 144.0)));
|
||||
assert_eq!(ppi::resolution(&pcx(5, 8, 3, 0, (2, 1), 2, 0, &[], &[])), None, "no resolution");
|
||||
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("document.open", &json!({"name": "art.pcx", "dataBase64": b64(&f)})).unwrap();
|
||||
assert_eq!((&r["format"], &r["warnings"]), (&json!("pcx"), &json!([])), "{r}");
|
||||
assert_eq!(s.doc().unwrap().doc.artboards[0].rect.size(), vectorcraft_geom::Size::new(1.0, 0.5), "2 × 1 px at 144 ppi");
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let r = s.execute("file.place", &json!({"name": "ART.PCX", "dataBase64": b64(&f)})).unwrap();
|
||||
assert_eq!((&r["format"], r["ids"].as_array().map(Vec::len)), (&json!("pcx"), Some(1)), "{r}");
|
||||
|
||||
// Copied in a file manager, a PCX file pastes as a bitmap.
|
||||
assert_eq!(file_flavour("art.pcx", &f, &PASTE_ORDER), Some("image/x-pcx"));
|
||||
let r = s.execute("clipboard.importImage", &json!({"mime": "image/x-pcx", "dataBase64": b64(&f)})).unwrap();
|
||||
assert_eq!((&r["count"], &r["pixelWidth"], &r["pixelHeight"]), (&json!(1), &json!(2), &json!(1)), "{r}");
|
||||
// Glass's Load Texture… reads it too.
|
||||
assert!(texture_image(&f).is_ok());
|
||||
|
||||
// The dialogs list PCX; the desktop packaging doesn't associate it; nothing writes it.
|
||||
assert!(OPEN_EXTS.contains(&"pcx") && PLACE_EXTS.contains(&"pcx") && UNASSOCIATED_EXTS.contains(&"pcx"));
|
||||
let filter = ("PCX", &["pcx"][..]);
|
||||
assert!(open_filters().any(|f| f == filter) && place_filters().any(|f| f == filter));
|
||||
let r = s.execute("document.formats", &json!({})).unwrap();
|
||||
let pcx_format = r["formats"].as_array().unwrap().iter().find(|f| f["id"] == "pcx").unwrap().clone();
|
||||
assert_eq!((pcx_format["read"].as_bool(), pcx_format["write"].as_bool()), (Some(true), Some(false)));
|
||||
assert_eq!(format_for_name("a.pcx").map(|f| f.id), Some("pcx"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn damaged_and_unsupported_files_are_refused_with_a_message() {
|
||||
let message = |f: &[u8]| raster_image(f).err().expect("refused").to_string();
|
||||
let gray = pcx(5, 8, 1, 0, (2, 2), 2, 0, &[], &[1, 2, 3, 4]);
|
||||
|
||||
// A header or image data cut short.
|
||||
assert_eq!(message(&gray[..60]), "the PCX file is cut short");
|
||||
assert_eq!(message(&gray[..131]), "the PCX file is cut short");
|
||||
assert_eq!(message(&pcx(5, 8, 1, 0, (2, 2), 2, 0, &[], &[1, 0xc2])), "the PCX file is cut short", "a run without its byte");
|
||||
// The palette after the image data isn't read as pixels the image data lacks.
|
||||
let mut short = pcx(5, 8, 1, 0, (2, 2), 2, 0, &[], &[1, 2, 3]);
|
||||
short.push(0x0c);
|
||||
short.extend([7; 768]);
|
||||
assert_eq!(message(&short), "the PCX file is cut short", "three pixels and a palette");
|
||||
// A palette marker after the image data with fewer than 768 colors after it.
|
||||
let mut cut_palette = gray.clone();
|
||||
cut_palette.push(0x0c);
|
||||
cut_palette.extend([7; 767]);
|
||||
assert_eq!(message(&cut_palette), "the PCX file is cut short", "a palette cut short");
|
||||
assert_eq!(message(&[&gray[..], &[0x0c]].concat()), "the PCX file is cut short", "a marker alone");
|
||||
let mut s = Session::new();
|
||||
let e = s.execute("document.open", &json!({"name": "a.pcx", "dataBase64": vectorcraft_format::base64_encode(&gray[..131])}));
|
||||
assert!(e.expect_err("refused").to_string().contains("the PCX file is cut short"));
|
||||
|
||||
// Planes and depths the manual doesn't define.
|
||||
assert_eq!(message(&pcx(5, 8, 2, 0, (2, 2), 2, 0, &[], &[])), "PCX files with 8-bit pixels in 2 planes can't be read");
|
||||
assert_eq!(message(&pcx(5, 4, 3, 0, (2, 2), 2, 0, &[], &[])), "PCX files with 4-bit pixels in 3 planes can't be read");
|
||||
assert_eq!(message(&pcx(5, 1, 5, 0, (2, 2), 2, 0, &[], &[])), "PCX files with 1-bit pixels in 5 planes can't be read");
|
||||
|
||||
// A window that ends before it starts, and lines too short for the width.
|
||||
let mut backwards = gray.clone();
|
||||
backwards[8..10].copy_from_slice(&0u16.to_le_bytes());
|
||||
backwards[4..6].copy_from_slice(&5u16.to_le_bytes());
|
||||
assert_eq!(message(&backwards), "the PCX file's header is damaged");
|
||||
assert_eq!(message(&pcx(5, 8, 1, 0, (3, 1), 2, 0, &[], &[1, 2, 3, 4])), "the PCX file's header is damaged");
|
||||
assert_eq!(message(&pcx(5, 1, 1, 0, (17, 1), 2, 0, &[], &[0; 4])), "the PCX file's header is damaged");
|
||||
|
||||
// Past the allowance, from the header: the pixels as RGBA, and the scan lines of a narrow image
|
||||
// with long lines.
|
||||
let huge = pcx(5, 1, 1, 0, (0, 0), 8192, 0, &[], &[]);
|
||||
assert_eq!(message(&huge), "an image of 65536 × 65536 pixels is too large to draw");
|
||||
let long = pcx(5, 8, 3, 0, (1, 0), 65535, 0, &[], &[]);
|
||||
assert_eq!(message(&long), "an image of 1 × 65536 pixels is too large to draw");
|
||||
assert!(decode(&long, 1 << 20).is_err());
|
||||
|
||||
// Headers with values the manual doesn't define aren't PCX files.
|
||||
assert!(is_pcx(&gray));
|
||||
for bad in [[0x0a, 1, 1, 8], [0x0a, 6, 1, 8], [0x0a, 5, 0, 8], [0x0a, 5, 1, 3], [0x0b, 5, 1, 8]] {
|
||||
assert!(!is_pcx(&bad), "{bad:?}");
|
||||
}
|
||||
}
|
||||
@@ -50,7 +50,7 @@ fn every_option_changes_the_output() {
|
||||
changed(&mut s, json!({"svg": {"styling": "css"}}), &|o| o.contains("<style>") && o.contains("class=\"cls-1\""));
|
||||
changed(&mut s, json!({"objectIds": "minimal"}), &|o| !o.contains(" id=\""));
|
||||
changed(&mut s, json!({"objectIds": "unique"}), &|o| o.contains(" id=\"u") && o.contains("-Layer_1\""));
|
||||
changed(&mut s, json!({"decimals": 1}), &|o| o.contains("M10.1 ") && !o.contains("10.123"));
|
||||
changed(&mut s, json!({"decimals": 1}), &|o| o.contains("x=\"10.1\"") && !o.contains("10.123"));
|
||||
changed(&mut s, json!({"decimals": 6}), &|o| o.contains("10.123456"));
|
||||
changed(&mut s, json!({"minify": true}), &|o| !o.trim_end().contains('\n') && !o.contains("<?xml"));
|
||||
changed(&mut s, json!({"responsive": true}), &|o| !o.contains(" width=\"200\"") && o.contains("viewBox=\"0 0 200 100\""));
|
||||
@@ -218,7 +218,7 @@ fn save_writes_svg_and_remembers_its_options() {
|
||||
s.execute("shape.ellipse", &json!({"x": 100, "y": 10, "width": 30, "height": 30})).unwrap();
|
||||
s.execute("document.save", &json!({})).unwrap();
|
||||
let text = std::fs::read_to_string(&path).unwrap();
|
||||
assert!(text.contains("<style>") && text.matches("<path").count() == 2, "Save reuses the options: {text}");
|
||||
assert!(text.contains("<style>") && vectorcraft_testkit::svg_shapes(&text) == 2, "Save reuses the options: {text}");
|
||||
assert!(s.execute("document.save", &json!({"path": dir.join("x.png").to_string_lossy()})).is_err(), "PNG is an export");
|
||||
// A native save switches back.
|
||||
let native = dir.join("doc.vectorcraft").to_string_lossy().to_string();
|
||||
|
||||
@@ -61,7 +61,7 @@ fn a_chosen_artboard_s_svg_holds_only_its_own_art() {
|
||||
s.execute("shape.rectangle", &json!({"x": first + 10.0, "y": 10, "width": 30, "height": 30})).unwrap();
|
||||
s.execute("shape.ellipse", &json!({"x": third + 10.0, "y": 10, "width": 30, "height": 30})).unwrap();
|
||||
// A rectangle has straight sides only; the ellipse is curves.
|
||||
let shapes = |svg: &str| (svg.matches("<path").count() + svg.matches("<rect").count(), svg.contains(" C") || svg.contains("<ellipse"));
|
||||
let shapes = |svg: &str| (vectorcraft_testkit::svg_shapes(svg), svg.contains(" C") || svg.contains("<ellipse") || svg.contains("<circle"));
|
||||
let text = |v: &serde_json::Value| v["text"].as_str().unwrap().to_string();
|
||||
let third_only = text(&s.execute("document.serialize", &json!({"format": "svg", "useArtboards": true, "range": "3"})).unwrap());
|
||||
assert_eq!(shapes(&third_only), (1, true), "{third_only}");
|
||||
@@ -88,8 +88,8 @@ fn a_chosen_artboard_s_svg_leaves_out_its_neighbours_art_in_a_shared_group() {
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
let text = |v: &serde_json::Value| v["text"].as_str().unwrap().to_string();
|
||||
let third_only = text(&s.execute("document.serialize", &json!({"format": "svg", "useArtboards": true, "range": "3"})).unwrap());
|
||||
assert_eq!(third_only.matches("<path").count() + third_only.matches("<rect").count(), 1, "{third_only}");
|
||||
assert!(third_only.contains(" C") || third_only.contains("<ellipse"), "{third_only}");
|
||||
assert_eq!(vectorcraft_testkit::svg_shapes(&third_only), 1, "{third_only}");
|
||||
assert!(third_only.contains(" C") || third_only.contains("<ellipse") || third_only.contains("<circle"), "{third_only}");
|
||||
}
|
||||
|
||||
/// An object off a chosen artboard whose drop shadow reaches onto it is in that artboard's SVG.
|
||||
@@ -102,7 +102,7 @@ fn a_chosen_artboard_s_svg_keeps_an_object_whose_shadow_reaches_it() {
|
||||
let paths = |s: &mut Session| {
|
||||
let svg = s.execute("document.serialize", &json!({"format": "svg", "artboard": 0})).unwrap();
|
||||
let text = svg["text"].as_str().unwrap().to_string();
|
||||
text.matches("<path").count() + text.matches("<rect").count()
|
||||
vectorcraft_testkit::svg_shapes(&text)
|
||||
};
|
||||
assert_eq!(paths(&mut s), 0, "the plain rectangle is off the artboard");
|
||||
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [id], "params": {"x": 20, "y": 0, "blur": 0}})).unwrap();
|
||||
|
||||
@@ -7,7 +7,7 @@ use super::envelope::{
|
||||
env_edit_contents, env_expand, env_info, env_make_mesh, env_make_top, env_make_warp, env_options, env_release, env_reset_mesh, env_reset_warp,
|
||||
env_set_mesh_point,
|
||||
};
|
||||
use super::mesh::{mesh_add_line, mesh_create, mesh_delete_point, mesh_expand, mesh_move_point, mesh_set_color};
|
||||
use super::mesh::{mesh_add_line, mesh_create, mesh_delete_point, mesh_expand, mesh_move_point, mesh_move_points, mesh_set_color};
|
||||
use super::{CommandSpec, always, cmd, has_doc, has_multi, has_selection};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -245,7 +245,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Set Mesh Point Color",
|
||||
[],
|
||||
None,
|
||||
"{id, index, color, keepModel?: bool (as paint.setFill), opacity?: 0..1} colour of one mesh point",
|
||||
"{id, index | points: [index…] | items: [{id, index | points}…], color?, keepModel?: bool (as paint.setFill), opacity?: 0..1} colour and/or opacity of gradient mesh points (one undo step; an index out of range changes nothing)",
|
||||
has_doc,
|
||||
mesh_set_color
|
||||
),
|
||||
@@ -258,6 +258,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
mesh_move_point
|
||||
),
|
||||
cmd!(
|
||||
"object.mesh.movePoints",
|
||||
"Move Mesh Points",
|
||||
[],
|
||||
None,
|
||||
"{id, points: [index…] | items: [{id, index | points}…], dx, dy} move points of gradient meshes or mesh envelopes by (dx, dy), their handles with them (one undo step; an index out of range changes nothing)",
|
||||
has_doc,
|
||||
mesh_move_points
|
||||
),
|
||||
cmd!(
|
||||
"object.mesh.addLine",
|
||||
"Add Mesh Line",
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use super::common::{fix_ids, ids_json, is_mesh, replace_with, roots_param, selected_of};
|
||||
use super::envelope::{outline_of, rows_cols};
|
||||
use super::{
|
||||
Color, Document, EngineError, EnvelopeKind, GradientMesh, MeshAppearance, Node, NodeKind, Paint, Point, Result, Session, Value, bad,
|
||||
Color, Document, EngineError, EnvelopeKind, GradientMesh, MeshAppearance, Node, NodeId, NodeKind, Paint, Point, Result, Session, Value, bad,
|
||||
check_numbers, color_value, f64_or, f64_req, finite_numbers, gradient_sampler, id_param, json, live, ok, str_param,
|
||||
};
|
||||
|
||||
@@ -106,25 +108,86 @@ fn image_mesh(d: &Document, im: &vectorcraft_doc::ImageObject, rows: u32, cols:
|
||||
}
|
||||
|
||||
/// Run `f` on the gradient mesh `p.id` (one undo step `label`); with `envelopes`, a mesh
|
||||
/// envelope's grid too (its points and handles are written back: editing fills in the handles).
|
||||
/// envelope's grid too (see [`edit_grid`]).
|
||||
fn with_mesh<T>(s: &mut Session, p: &Value, cmd: &str, label: &str, envelopes: bool, f: impl FnOnce(&mut GradientMesh) -> Result<T>) -> Result<T> {
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(cmd, "missing `id`"))?;
|
||||
let c = cmd.to_string();
|
||||
s.edit(label, move |d, _| match d.node_mut(id).map(|n| &mut n.kind) {
|
||||
s.edit(label, move |d, _| edit_grid(d, id, cmd, envelopes, f))
|
||||
}
|
||||
|
||||
/// Run `f` on the gradient mesh `id` of `d`; with `envelopes`, a mesh envelope's grid too (its
|
||||
/// points and handles are written back: editing fills in the handles).
|
||||
fn edit_grid<T>(d: &mut Document, id: NodeId, cmd: &str, envelopes: bool, f: impl FnOnce(&mut GradientMesh) -> Result<T>) -> Result<T> {
|
||||
match d.node_mut(id).map(|n| &mut n.kind) {
|
||||
Some(NodeKind::Mesh(m)) => f(m),
|
||||
Some(NodeKind::Envelope { kind, .. }) if envelopes && matches!(**kind, EnvelopeKind::Mesh { .. }) => {
|
||||
let EnvelopeKind::Mesh { rows, cols, points, handles } = &mut **kind else {
|
||||
return Err(bad(&c, "not a gradient mesh or mesh envelope"));
|
||||
return Err(bad(cmd, "not a gradient mesh or mesh envelope"));
|
||||
};
|
||||
let mut m = live::envelope_grid(*rows, *cols, points, handles).ok_or_else(|| bad(&c, "the envelope's mesh is malformed"))?;
|
||||
let mut m = live::envelope_grid(*rows, *cols, points, handles).ok_or_else(|| bad(cmd, "the envelope's mesh is malformed"))?;
|
||||
let r = f(&mut m)?;
|
||||
(*rows, *cols) = (m.rows, m.cols);
|
||||
*points = m.points.iter().map(|q| q.p).collect();
|
||||
*handles = m.points.iter().map(|q| q.handles).collect();
|
||||
Ok(r)
|
||||
}
|
||||
Some(_) => Err(bad(&c, if envelopes { "not a gradient mesh or mesh envelope" } else { "not a gradient mesh" })),
|
||||
Some(_) => Err(bad(cmd, if envelopes { "not a gradient mesh or mesh envelope" } else { "not a gradient mesh" })),
|
||||
None => Err(EngineError::NoNode(id)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Most mesh points one command names, over all its meshes.
|
||||
const MAX_POINTS: usize = 1 << 20;
|
||||
|
||||
/// The mesh points `p` names: `{id, index}`, `{id, points: [index…]}` or `{items: [{id, index |
|
||||
/// points}…]}`. Each mesh comes once, with its points in order and without repeats.
|
||||
fn point_items(p: &Value, cmd: &str) -> Result<Vec<(NodeId, BTreeSet<usize>)>> {
|
||||
let one = |q: &Value| -> Result<(NodeId, BTreeSet<usize>)> {
|
||||
let id = id_param(q, "id").ok_or_else(|| bad(cmd, "missing `id`"))?;
|
||||
let points = match q.get("points") {
|
||||
None | Some(Value::Null) => BTreeSet::from([index_param(q, "index", cmd)?]),
|
||||
Some(Value::Array(v)) if v.len() <= MAX_POINTS => v
|
||||
.iter()
|
||||
.map(|i| index_of(i.as_f64().ok_or_else(|| bad(cmd, "`points` must be point indexes"))?, "points", cmd))
|
||||
.collect::<Result<_>>()?,
|
||||
Some(_) => return Err(bad(cmd, "`points` must be a list of point indexes")),
|
||||
};
|
||||
Ok((id, points))
|
||||
};
|
||||
let items: Vec<(NodeId, BTreeSet<usize>)> = match p.get("items") {
|
||||
None | Some(Value::Null) => vec![one(p)?],
|
||||
Some(Value::Array(v)) if v.len() <= MAX_POINTS => v.iter().map(one).collect::<Result<_>>()?,
|
||||
Some(_) => return Err(bad(cmd, "`items` must be a list of {id, points}")),
|
||||
};
|
||||
let mut merged: BTreeMap<NodeId, BTreeSet<usize>> = BTreeMap::new();
|
||||
for (id, points) in items {
|
||||
merged.entry(id).or_default().extend(points);
|
||||
}
|
||||
if merged.values().map(BTreeSet::len).sum::<usize>() > MAX_POINTS {
|
||||
return Err(bad(cmd, format!("at most {MAX_POINTS} points")));
|
||||
}
|
||||
Ok(merged.into_iter().collect())
|
||||
}
|
||||
|
||||
/// Run `f` on each mesh point `items` names, as one undo step `label` (an index out of range
|
||||
/// fails it, changing nothing); with `envelopes`, on mesh envelopes' points too.
|
||||
fn with_points(
|
||||
s: &mut Session,
|
||||
items: &[(NodeId, BTreeSet<usize>)],
|
||||
cmd: &str,
|
||||
label: &str,
|
||||
envelopes: bool,
|
||||
mut f: impl FnMut(&mut live::MeshPoint) -> Result<()>,
|
||||
) -> Result<()> {
|
||||
s.edit(label, |d, _| {
|
||||
for (id, points) in items {
|
||||
edit_grid(d, *id, cmd, envelopes, |m| {
|
||||
for i in points {
|
||||
f(m.points.get_mut(*i).ok_or_else(|| bad(cmd, "index out of range"))?)?;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
@@ -140,7 +203,11 @@ pub(super) fn handle_param(p: &Value, cmd: &str) -> Result<Option<usize>> {
|
||||
}
|
||||
|
||||
pub(super) fn index_param(p: &Value, key: &str, cmd: &str) -> Result<usize> {
|
||||
let i = f64_req(p, key, cmd)?;
|
||||
index_of(f64_req(p, key, cmd)?, key, cmd)
|
||||
}
|
||||
|
||||
/// `i`, the value of `key`, as an index: a whole number ≥ 0.
|
||||
fn index_of(i: f64, key: &str, cmd: &str) -> Result<usize> {
|
||||
if i < 0.0 {
|
||||
return Err(bad(cmd, "index must be ≥ 0"));
|
||||
}
|
||||
@@ -156,14 +223,13 @@ pub(super) fn mesh_set_color(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.mesh.setPointColor";
|
||||
check_numbers(p, &["opacity"], C)?;
|
||||
crate::cmd::paint::check_keep_model(p, C)?;
|
||||
let index = index_param(p, "index", C)?;
|
||||
let items = point_items(p, C)?;
|
||||
let color = p.get("color").and_then(color_value).map(|c| crate::cmd::paint::new_color(s, p, c));
|
||||
let opacity = p.get("opacity").and_then(Value::as_f64);
|
||||
if color.is_none() && opacity.is_none() {
|
||||
return Err(bad(C, "missing `color` or `opacity`"));
|
||||
}
|
||||
with_mesh(s, p, C, "Mesh Point Color", false, |m| {
|
||||
let pt = m.points.get_mut(index).ok_or_else(|| bad(C, "index out of range"))?;
|
||||
with_points(s, &items, C, "Mesh Point Color", false, |pt| {
|
||||
if let Some(c) = color {
|
||||
pt.color = c;
|
||||
}
|
||||
@@ -191,6 +257,18 @@ pub(super) fn mesh_move_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
pub(super) fn mesh_move_points(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.mesh.movePoints";
|
||||
let items = point_items(p, C)?;
|
||||
let (dx, dy) = (f64_req(p, "dx", C)?, f64_req(p, "dy", C)?);
|
||||
// `Session::edit` refuses a move past the canvas's coordinate range.
|
||||
with_points(s, &items, C, "Move Mesh Points", true, |pt| {
|
||||
pt.p = Point::new(pt.p.x + dx, pt.p.y + dy);
|
||||
Ok(())
|
||||
})?;
|
||||
ok()
|
||||
}
|
||||
|
||||
pub(super) fn mesh_add_line(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.mesh.addLine";
|
||||
let q = Point::new(f64_req(p, "x", C)?, f64_req(p, "y", C)?);
|
||||
|
||||
@@ -183,7 +183,7 @@ fn ids_json(ids: &[NodeId]) -> Value {
|
||||
/// The whole number `p` gives for `key`, written `4` or `4.0`, or `default` when `p` gives none or null. A value that
|
||||
/// is not a number gives the [`check_numbers`] error, and a fraction or a negative number gives
|
||||
/// "`{key}` must be a whole number".
|
||||
fn whole_or(p: &Value, key: &str, default: u64, cmd: &str) -> Result<u64> {
|
||||
pub(crate) fn whole_or(p: &Value, key: &str, default: u64, cmd: &str) -> Result<u64> {
|
||||
check_numbers(p, &[key], cmd)?;
|
||||
let Some(v) = p.get(key).filter(|v| !v.is_null()) else { return Ok(default) };
|
||||
match (v.as_u64(), v.as_f64()) {
|
||||
|
||||
@@ -3,6 +3,7 @@ use super::{
|
||||
Affine, Document, EngineError, NodeId, OrientedBox, Point, Rect, Result, Scaling, Session, Value, Vec2, bad, check_numbers, check_switches,
|
||||
effects, has_multi, ok, selected_roots, str_param,
|
||||
};
|
||||
use vectorcraft_doc::{NodeKind, TextKind};
|
||||
|
||||
impl Session {
|
||||
/// The bounds of `ids` the Transform panel, the bounding box, Align and Distribute measure:
|
||||
@@ -18,12 +19,51 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// Measure with preview (visual) bounds? The `bounds` param, else Use Preview Bounds.
|
||||
fn preview_bounds(s: &Session, p: &Value, cmd: &str) -> Result<bool> {
|
||||
match choice(p, cmd, "bounds", &["preview", "geometric"])? {
|
||||
None => Ok(s.prefs.use_preview_bounds),
|
||||
Some(b) => Ok(b == "preview"),
|
||||
/// How Align and Distribute measure each object: by visual bounds as drawn (`preview`, see
|
||||
/// [`effects::preview::bounds_of`]) or geometric bounds, and point type (`point`) or area type
|
||||
/// (`area`) by the ink of its glyphs instead of its em box or frame (Align to Glyph Bounds).
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct Measure {
|
||||
preview: bool,
|
||||
point: bool,
|
||||
area: bool,
|
||||
}
|
||||
|
||||
impl Measure {
|
||||
/// The bounds of `ids` together.
|
||||
fn bounds(self, d: &Document, ids: &[NodeId]) -> Option<Rect> {
|
||||
if !(self.point || self.area) {
|
||||
return effects::preview::bounds_of(d, ids, self.preview);
|
||||
}
|
||||
ids.iter().filter_map(|id| self.of(d, *id)).reduce(|a, b| a.union(b))
|
||||
}
|
||||
/// The bounds of `id`: with Align to Glyph Bounds on for its kind of type, its glyphs' ink
|
||||
/// (with the characters' strokes when measuring visual bounds). Type on a path, and type that
|
||||
/// draws nothing, is measured as before.
|
||||
fn of(self, d: &Document, id: NodeId) -> Option<Rect> {
|
||||
if let Some(NodeKind::Text(t)) = d.node(id).map(|n| &n.kind)
|
||||
&& match t.kind {
|
||||
TextKind::Point => self.point,
|
||||
TextKind::Area { .. } => self.area,
|
||||
TextKind::OnPath { .. } => false,
|
||||
}
|
||||
&& let Some(ink) = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).ink_bounds()
|
||||
{
|
||||
let r = t.xf.transform_rect_bbox(ink);
|
||||
return Some(if self.preview { r.inflate(t.char_stroke_outset(), t.char_stroke_outset()) } else { r });
|
||||
}
|
||||
effects::preview::bounds_of(d, &[id], self.preview)
|
||||
}
|
||||
}
|
||||
|
||||
/// How the Align commands measure: preview (visual) bounds from the `bounds` param, else Use
|
||||
/// Preview Bounds, and type by its glyphs as Align to Glyph Bounds says.
|
||||
fn measure(s: &Session, p: &Value, cmd: &str) -> Result<Measure> {
|
||||
let preview = match choice(p, cmd, "bounds", &["preview", "geometric"])? {
|
||||
None => s.prefs.use_preview_bounds,
|
||||
Some(b) => b == "preview",
|
||||
};
|
||||
Ok(Measure { preview, point: s.prefs.align_glyph_bounds_point, area: s.prefs.align_glyph_bounds_area })
|
||||
}
|
||||
|
||||
/// Param `key` of the Align commands, Shear, Unlock All, Show All and `text.setFormat`'s lists: one
|
||||
@@ -50,9 +90,9 @@ fn spacing(p: &Value, cmd: &str) -> Result<Option<f64>> {
|
||||
.transpose()
|
||||
}
|
||||
|
||||
/// `ids` with their bounds (`preview`: visual bounds as drawn, see [`effects::preview::bounds_of`]).
|
||||
fn items_bounds(d: &Document, ids: &[NodeId], preview: bool) -> Vec<(NodeId, Rect)> {
|
||||
ids.iter().filter_map(|id| Some((*id, effects::preview::bounds_of(d, &[*id], preview)?))).collect()
|
||||
/// `ids` with their bounds, measured by `m`.
|
||||
fn items_bounds(d: &Document, ids: &[NodeId], m: Measure) -> Vec<(NodeId, Rect)> {
|
||||
ids.iter().filter_map(|id| Some((*id, m.of(d, *id)?))).collect()
|
||||
}
|
||||
|
||||
/// Move each object of `moves` by its offset and each ruler guide of `guides` (index, position)
|
||||
@@ -101,13 +141,13 @@ fn key_guide(s: &Session, p: &Value) -> Option<(f64, bool)> {
|
||||
/// Where Align puts the objects, `r`, and the axes it moves them along (x, y): a key guide gives
|
||||
/// the line across its axis only (a vertical guide fixes x, a horizontal one y), so the other
|
||||
/// axis stays as it is.
|
||||
fn align_reference(s: &Session, p: &Value, ids: &[NodeId], preview: bool, own: Option<Rect>) -> Result<(Rect, bool, bool)> {
|
||||
fn align_reference(s: &Session, p: &Value, ids: &[NodeId], m: Measure, own: Option<Rect>) -> Result<(Rect, bool, bool)> {
|
||||
if let Some((pos, vertical)) = key_guide(s, p) {
|
||||
return Ok((Rect::new(pos, pos, pos, pos), vertical, !vertical));
|
||||
}
|
||||
let r = match own {
|
||||
Some(b) if align_to(s, p) != Some("artboard") => b,
|
||||
_ => reference_rect(s, p, ids, preview)?,
|
||||
_ => reference_rect(s, p, ids, m)?,
|
||||
};
|
||||
Ok((r, true, true))
|
||||
}
|
||||
@@ -121,13 +161,11 @@ fn selected_guides_bounds(st: &crate::DocState) -> Option<Rect> {
|
||||
})
|
||||
}
|
||||
|
||||
fn reference_rect(s: &Session, p: &Value, ids: &[NodeId], preview: bool) -> Result<Rect> {
|
||||
fn reference_rect(s: &Session, p: &Value, ids: &[NodeId], m: Measure) -> Result<Rect> {
|
||||
let st = s.doc()?;
|
||||
match align_to(s, p) {
|
||||
Some("artboard") => {
|
||||
let b = effects::preview::bounds_of(&st.doc, ids, preview)
|
||||
.or_else(|| ids.is_empty().then(|| selected_guides_bounds(st)).flatten())
|
||||
.unwrap_or_default();
|
||||
let b = m.bounds(&st.doc, ids).or_else(|| ids.is_empty().then(|| selected_guides_bounds(st)).flatten()).unwrap_or_default();
|
||||
// Align to Artboard uses artboard `artboard` (the app passes the active one). Without
|
||||
// it, or with an index the document doesn't have, it uses the artboard under the center
|
||||
// of the selection, or the first one when no artboard is there.
|
||||
@@ -137,13 +175,13 @@ fn reference_rect(s: &Session, p: &Value, ids: &[NodeId], preview: bool) -> Resu
|
||||
}
|
||||
Some("key") => {
|
||||
let k = st.selection.key.ok_or_else(|| EngineError::Other("no key object".into()))?;
|
||||
effects::preview::bounds_of(&st.doc, &[k], preview).ok_or(EngineError::NoNode(k))
|
||||
m.of(&st.doc, k).ok_or(EngineError::NoNode(k))
|
||||
}
|
||||
_ => {
|
||||
if ids.is_empty() {
|
||||
selected_guides_bounds(st).ok_or_else(|| EngineError::Other("nothing to align".into()))
|
||||
} else {
|
||||
effects::preview::bounds_of(&st.doc, ids, preview).ok_or_else(|| EngineError::Other("nothing to align".into()))
|
||||
m.bounds(&st.doc, ids).ok_or_else(|| EngineError::Other("nothing to align".into()))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -153,9 +191,9 @@ fn reference_rect(s: &Session, p: &Value, ids: &[NodeId], preview: bool) -> Resu
|
||||
/// (command `cmd`), the same artboard as `object.align` uses ([`reference_rect`]). It returns
|
||||
/// `None` for the other choices. A `to` outside the choices is an error. Both commands call it
|
||||
/// before they space selected anchor points, and they space those points without the artboard.
|
||||
fn distribute_to(s: &Session, p: &Value, ids: &[NodeId], preview: bool, cmd: &str) -> Result<Option<Rect>> {
|
||||
fn distribute_to(s: &Session, p: &Value, ids: &[NodeId], m: Measure, cmd: &str) -> Result<Option<Rect>> {
|
||||
match choice(p, cmd, "to", &["selection", "artboard", "key"])? {
|
||||
Some("artboard") => reference_rect(s, p, ids, preview).map(Some),
|
||||
Some("artboard") => reference_rect(s, p, ids, m).map(Some),
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
@@ -171,7 +209,7 @@ fn key_root(s: &Session, ids: &[NodeId]) -> Option<NodeId> {
|
||||
|
||||
pub(super) fn align(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = selected_roots(s)?;
|
||||
let preview = preview_bounds(s, p, "object.align")?;
|
||||
let m = measure(s, p, "object.align")?;
|
||||
let (h, v) = direction(p, "object.align")?;
|
||||
choice(p, "object.align", "to", &["selection", "artboard", "key"])?;
|
||||
check_switches(p, &["patterns"], "object.align")?;
|
||||
@@ -183,12 +221,12 @@ pub(super) fn align(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !s.doc()?.selection.anchors.is_empty() {
|
||||
return align_anchors(s, p, &ids, (h, v));
|
||||
}
|
||||
let (r, along_x, along_y) = align_reference(s, p, &ids, preview, None)?;
|
||||
let (r, along_x, along_y) = align_reference(s, p, &ids, m, None)?;
|
||||
let (h, v) = (h.filter(|_| along_x), v.filter(|_| along_y));
|
||||
let key = key_root(s, &ids);
|
||||
let moves: Vec<(NodeId, Vec2)> = {
|
||||
let d = &s.doc()?.doc;
|
||||
items_bounds(d, &ids, preview)
|
||||
items_bounds(d, &ids, m)
|
||||
.into_iter()
|
||||
.filter(|(id, _)| Some(*id) != key || align_to(s, p) != Some("key"))
|
||||
.map(|(id, b)| {
|
||||
@@ -261,7 +299,7 @@ fn align_anchors(s: &mut Session, p: &Value, ids: &[NodeId], (h, v): (Option<&st
|
||||
};
|
||||
// shortcut: no key anchor yet, so Align To Key Object aligns to the points' bounds as Selection does
|
||||
// (or to a key guide).
|
||||
let (r, along_x, along_y) = align_reference(s, p, ids, false, Some(bounds))?;
|
||||
let (r, along_x, along_y) = align_reference(s, p, ids, Measure::default(), Some(bounds))?;
|
||||
let (h, v) = (h.filter(|_| along_x), v.filter(|_| along_y));
|
||||
let target = |q: Point| {
|
||||
let x = match h {
|
||||
@@ -316,12 +354,12 @@ enum Spaced {
|
||||
Guide(usize),
|
||||
}
|
||||
|
||||
/// The selected objects `ids` with their bounds (`preview`: visual bounds), and the selected
|
||||
/// The selected objects `ids` with their bounds (measured by `m`), and the selected
|
||||
/// ruler guides across the axis (vertical ones when `horiz`) with their line as their bounds.
|
||||
/// Guides along the axis are left out, so they stay where they are.
|
||||
fn spaced_items(s: &Session, ids: &[NodeId], preview: bool, horiz: bool) -> Result<Vec<(Spaced, Rect)>> {
|
||||
fn spaced_items(s: &Session, ids: &[NodeId], m: Measure, horiz: bool) -> Result<Vec<(Spaced, Rect)>> {
|
||||
let st = s.doc()?;
|
||||
let objects = items_bounds(&st.doc, ids, preview).into_iter().map(|(id, r)| (Spaced::Object(id), r));
|
||||
let objects = items_bounds(&st.doc, ids, m).into_iter().map(|(id, r)| (Spaced::Object(id), r));
|
||||
let guides = st.selection.guides.iter().filter_map(|&i| {
|
||||
let g = st.doc.guides.get(i).filter(|g| g.vertical == horiz)?;
|
||||
Some((Spaced::Guide(i), Rect::new(g.pos, g.pos, g.pos, g.pos)))
|
||||
@@ -405,8 +443,8 @@ pub(super) fn distribute(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_switches(p, &["patterns"], "object.distribute")?;
|
||||
check_numbers(p, &["artboard"], "object.distribute")?;
|
||||
let ids = selected_roots(s)?;
|
||||
let preview = preview_bounds(s, p, "object.distribute")?;
|
||||
let board = distribute_to(s, p, &ids, preview, "object.distribute")?;
|
||||
let m = measure(s, p, "object.distribute")?;
|
||||
let board = distribute_to(s, p, &ids, m, "object.distribute")?;
|
||||
let spacing = spacing(p, "object.distribute")?;
|
||||
// Anchor points selected with Direct Selection are distributed themselves, as Align aligns them.
|
||||
if !s.doc()?.selection.anchors.is_empty() {
|
||||
@@ -436,7 +474,7 @@ pub(super) fn distribute(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
// The selected guides across the axis are spaced with the objects (#1597). A guide has no
|
||||
// size, so its left edge, center and right edge are all its line.
|
||||
let mut items = spaced_items(s, &ids, preview, horiz)?;
|
||||
let mut items = spaced_items(s, &ids, m, horiz)?;
|
||||
items.sort_by(|a, b| key(&a.1, horiz).total_cmp(&key(&b.1, horiz)));
|
||||
let n = items.len();
|
||||
if spacing.is_some() && key_guide_along(s, p, horiz) {
|
||||
@@ -481,14 +519,14 @@ pub(super) fn distribute_spacing(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_numbers(p, &["artboard"], "object.distributeSpacing")?;
|
||||
let ids = selected_roots(s)?;
|
||||
let horiz = choice(p, "object.distributeSpacing", "axis", &["horizontal", "vertical"])? != Some("vertical");
|
||||
let preview = preview_bounds(s, p, "object.distributeSpacing")?;
|
||||
let board = distribute_to(s, p, &ids, preview, "object.distributeSpacing")?;
|
||||
let m = measure(s, p, "object.distributeSpacing")?;
|
||||
let board = distribute_to(s, p, &ids, m, "object.distributeSpacing")?;
|
||||
let spacing = spacing(p, "object.distributeSpacing")?;
|
||||
if !s.doc()?.selection.anchors.is_empty() {
|
||||
return distribute_anchors(s, "Distribute Spacing", horiz, spacing);
|
||||
}
|
||||
// The selected guides across the axis are spaced with the objects, as items with no size (#1597).
|
||||
let mut items = spaced_items(s, &ids, preview, horiz)?;
|
||||
let mut items = spaced_items(s, &ids, m, horiz)?;
|
||||
items.sort_by(|a, b| if horiz { a.1.x0.total_cmp(&b.1.x0) } else { a.1.y0.total_cmp(&b.1.y0) });
|
||||
if spacing.is_some() && key_guide_along(s, p, horiz) {
|
||||
return ok();
|
||||
|
||||
@@ -10,7 +10,7 @@ use std::collections::HashSet;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::BlendMode;
|
||||
use vectorcraft_doc::{Document, Knockout, Node, NodeId, OpacityMask, Selection};
|
||||
use vectorcraft_doc::{Document, Knockout, Node, NodeId, NodeKind, OpacityMask, Selection};
|
||||
|
||||
use super::maskedit::{begin, finish, mask_group, mask_parts, show_editing};
|
||||
use super::pathops::{Beside, separate};
|
||||
@@ -368,12 +368,19 @@ impl TransparencyInfo {
|
||||
}
|
||||
}
|
||||
|
||||
/// The opacity of the focused gradient mesh `point` (see `transparency.set`) instead of its
|
||||
/// object's.
|
||||
fn with_mesh_point(mut self, point: Option<(NodeId, usize, f32)>) -> Self {
|
||||
if let Some((_, _, o)) = point {
|
||||
self.opacity = Some((o as f64 * 10_000.0).round() / 100.0);
|
||||
}
|
||||
/// The opacity of the picked gradient mesh `points` (see `transparency.set`) instead of their
|
||||
/// objects': `None` where they differ.
|
||||
fn with_mesh_points(mut self, d: &Document, points: Option<Vec<(NodeId, Vec<usize>)>>) -> Self {
|
||||
let Some(points) = points else { return self };
|
||||
let mut all = points.iter().flat_map(|(id, v)| {
|
||||
let m = match d.node(*id).map(|n| &n.kind) {
|
||||
Some(NodeKind::Mesh(m)) => Some(m),
|
||||
_ => None,
|
||||
};
|
||||
v.iter().filter_map(move |i| m?.points.get(*i)).map(|q| (q.opacity as f64 * 10_000.0).round() as i64)
|
||||
});
|
||||
let first = all.next();
|
||||
self.opacity = first.filter(|f| all.all(|o| o == *f)).map(|o| o as f64 / 100.0);
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -404,8 +411,8 @@ impl Session {
|
||||
pub fn transparency_info(&self) -> TransparencyInfo {
|
||||
match (self.active(), transparency_targets(self, &Value::Null)) {
|
||||
(Some(st), Ok(ids)) => {
|
||||
let point = super::paint::focused_mesh_point_of(self, &ids);
|
||||
TransparencyInfo::of(&st.doc, ids).with_mesh_point(point)
|
||||
let points = super::paint::picked_mesh_points_of(self, &ids);
|
||||
TransparencyInfo::of(&st.doc, ids).with_mesh_points(&st.doc, points)
|
||||
}
|
||||
_ => TransparencyInfo::default(),
|
||||
}
|
||||
@@ -415,8 +422,8 @@ impl Session {
|
||||
fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let ids = transparency_targets(s, p)?;
|
||||
let point = super::paint::focused_mesh_point_of(s, &ids);
|
||||
let i = TransparencyInfo::of(&st.doc, ids).with_mesh_point(point);
|
||||
let points = super::paint::picked_mesh_points_of(s, &ids);
|
||||
let i = TransparencyInfo::of(&st.doc, ids).with_mesh_points(&st.doc, points);
|
||||
Ok(json!({
|
||||
"ids": i.ids.iter().map(|id| id.0).collect::<Vec<_>>(),
|
||||
"opacity": i.opacity,
|
||||
|
||||
+133
-23
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Fill",
|
||||
[],
|
||||
None,
|
||||
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|freeform, method?: classic|perceptual (as paint.editGradient; default classic), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg, start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits), dither?: bool (linear and radial fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear or radial `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid colour recolours only the gradient mesh point last clicked with the Mesh tool or Direct Selection; while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}",
|
||||
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|freeform, method?: classic|perceptual (as paint.editGradient; default classic), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg, start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits), dither?: bool (linear and radial fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear or radial `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid colour recolours only the gradient mesh point last clicked with the Mesh tool or Direct Selection; while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white) → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}",
|
||||
has_doc,
|
||||
|s, p| set_paint(s, p, true)
|
||||
),
|
||||
@@ -462,9 +462,15 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
|
||||
let selected = item.targets(s, p)?;
|
||||
let ids = super::graph::paint_targets(&s.doc()?.doc, &selected);
|
||||
let paint = if span { placed_across(&s.doc()?.doc, &ids, paint, p, fill) } else { paint };
|
||||
// The gradient mesh point last clicked with the Mesh tool or Direct Selection: a solid fill
|
||||
// recolours just that point of its mesh.
|
||||
let mesh_point = if fill && matches!(paint, Paint::Solid { .. }) { focused_mesh_point(s) } else { None };
|
||||
// The gradient mesh points picked with the Mesh tool or Direct Selection: a solid fill
|
||||
// recolours just those points of their meshes.
|
||||
let mesh_points = if fill && matches!(paint, Paint::Solid { .. }) { picked_mesh_points(s, &ids) } else { vec![] };
|
||||
// Without `item`, unless the Appearance panel's active fill item takes the paint.
|
||||
let colorized = if fill && p.get("item").is_none() && item == ItemTarget::Top {
|
||||
colorized_images(&s.doc()?.doc, &ids, &paint).map_err(|e| bad(cmd, e))?
|
||||
} else {
|
||||
vec![]
|
||||
};
|
||||
let label = if fill { "Fill Color" } else { "Stroke Color" };
|
||||
edit_items_then(
|
||||
s,
|
||||
@@ -474,13 +480,20 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
|
||||
label,
|
||||
fill,
|
||||
|n, index| {
|
||||
if index.is_none() && colorized.contains(&n.id) {
|
||||
n.extras_mut().colorize = paint.color().map(|_| Box::new(paint.clone()));
|
||||
return Ok(());
|
||||
}
|
||||
if index.is_none()
|
||||
&& let Paint::Solid { color, .. } = &paint
|
||||
&& let Some((_, i)) = mesh_point.filter(|(id, _)| *id == n.id)
|
||||
&& let Some((_, points)) = mesh_points.iter().find(|(id, _)| *id == n.id)
|
||||
&& let NodeKind::Mesh(m) = &mut n.kind
|
||||
&& let Some(q) = m.points.get_mut(i)
|
||||
{
|
||||
q.color = *color;
|
||||
for i in points {
|
||||
if let Some(q) = m.points.get_mut(*i) {
|
||||
q.color = *color;
|
||||
}
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if index.is_none()
|
||||
@@ -594,20 +607,116 @@ fn placed_across(d: &Document, ids: &[NodeId], paint: Paint, p: &Value, fill: bo
|
||||
}
|
||||
}
|
||||
|
||||
/// The mesh point the active tool has focused (its `meshPoint` option: the Mesh tool's or Direct
|
||||
/// Selection's point last clicked).
|
||||
fn focused_mesh_point(s: &Session) -> Option<(NodeId, usize)> {
|
||||
let o = s.tool_options();
|
||||
let pt = o.get("meshPoint")?;
|
||||
Some((NodeId(pt.get("id")?.as_u64()?), usize::try_from(pt.get("index")?.as_u64()?).ok()?))
|
||||
/// The images among `ids` that a fill of `paint` colorizes: grayscale and 1-bit images, for a solid
|
||||
/// color (or none on a colorized image, which takes the color off). The color may be black, white,
|
||||
/// a process color or a spot color; on an image with an alpha channel, only a spot color, black or
|
||||
/// white, and other colors are an error.
|
||||
fn colorized_images(d: &Document, ids: &[NodeId], paint: &Paint) -> std::result::Result<Vec<NodeId>, String> {
|
||||
let mut out = vec![];
|
||||
for id in ids {
|
||||
let Some(n) = d.node(*id) else { continue };
|
||||
let NodeKind::Image(im) = &n.kind else { continue };
|
||||
// `none` takes a color off whatever the image's pixels have become since.
|
||||
if matches!(paint, Paint::None) && n.extras().colorize.is_some() {
|
||||
out.push(*id);
|
||||
continue;
|
||||
}
|
||||
let Some(gray) = d.image_blob(im).and_then(|b| b.gray_source()) else { continue };
|
||||
match paint {
|
||||
// Without a color, `none` goes to the image's fill item.
|
||||
Paint::None => continue,
|
||||
Paint::Solid { .. } => {
|
||||
if gray.alpha && !colorizes_transparency(d, paint) {
|
||||
return Err(PROCESS_ON_TRANSPARENCY.into());
|
||||
}
|
||||
}
|
||||
_ => continue,
|
||||
}
|
||||
out.push(*id);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The focused mesh point (see [`focused_mesh_point`]) with its opacity, when `ids` is just the
|
||||
/// gradient mesh it belongs to.
|
||||
pub(crate) fn focused_mesh_point_of(s: &Session, ids: &[NodeId]) -> Option<(NodeId, usize, f32)> {
|
||||
let (id, index) = focused_mesh_point(s).filter(|(id, _)| ids == [*id])?;
|
||||
let NodeKind::Mesh(m) = &s.doc().ok()?.doc.node(id)?.kind else { return None };
|
||||
Some((id, index, m.points.get(index)?.opacity))
|
||||
/// The message for a process color on a grayscale image with an alpha channel.
|
||||
const PROCESS_ON_TRANSPARENCY: &str = "a process color can't colorize a grayscale image with transparency: use a spot color, black or white";
|
||||
|
||||
/// Can `paint` colorize a grayscale image with an alpha channel: a color linked to a spot swatch
|
||||
/// of `d`, black or white?
|
||||
fn colorizes_transparency(d: &Document, paint: &Paint) -> bool {
|
||||
match paint {
|
||||
Paint::Solid { color, swatch, .. } => swatch.as_deref().and_then(|name| d.swatch(name)).is_some_and(|w| w.spot) || black_or_white(color),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// An error when an image with an alpha channel in `d` (its art, opacity masks, symbols, graph
|
||||
/// designs and pattern tiles) is colorized with a color that [`colorizes_transparency`] refuses,
|
||||
/// as a swatch edit that turns a spot color into a process color or recolors a process swatch
|
||||
/// can leave one.
|
||||
pub(super) fn check_colorized(d: &Document) -> std::result::Result<(), String> {
|
||||
let mut refused = false;
|
||||
let mut visit = |n: &Node| {
|
||||
vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| {
|
||||
if let (NodeKind::Image(im), Some(paint)) = (&m.kind, m.extras().colorize.as_deref())
|
||||
&& !refused
|
||||
&& !colorizes_transparency(d, paint)
|
||||
&& d.image_blob(im).and_then(|b| b.gray_source()).is_some_and(|g| g.alpha)
|
||||
{
|
||||
refused = true;
|
||||
}
|
||||
})
|
||||
};
|
||||
d.layers
|
||||
.iter()
|
||||
.chain(d.symbols.iter().map(|s| &s.art))
|
||||
.chain(d.graph_designs.iter().map(|g| &g.art))
|
||||
.chain(d.patterns.iter().flat_map(|p| &p.art))
|
||||
.for_each(|n| visit(n));
|
||||
if refused { Err(PROCESS_ON_TRANSPARENCY.into()) } else { Ok(()) }
|
||||
}
|
||||
|
||||
/// [`check_colorized`] after an edit, when the document passed it before the edit (`was_ok`), so
|
||||
/// an edit doesn't fail over an image it didn't change.
|
||||
pub(super) fn check_colorized_kept(was_ok: bool, d: &Document) -> std::result::Result<(), String> {
|
||||
if was_ok { check_colorized(d) } else { Ok(()) }
|
||||
}
|
||||
|
||||
/// Is `c` black or white (white, or black alone at 100%)?
|
||||
fn black_or_white(c: &Color) -> bool {
|
||||
let (none, full) = (|v: f32| v <= 0.0, |v: f32| v >= 1.0);
|
||||
match *c {
|
||||
Color::Gray { k } => none(k) || full(k),
|
||||
Color::Cmyk { c, m, y, k } => none(c) && none(m) && none(y) && (none(k) || full(k)),
|
||||
Color::Rgb { r, g, b } => [r, g, b].into_iter().all(none) || [r, g, b].into_iter().all(full),
|
||||
Color::Lab { .. } => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The points the active tool has picked (its `meshPoints` option: the Mesh tool's or Direct
|
||||
/// Selection's) on the gradient meshes among `ids`, in range, each mesh with its points.
|
||||
fn picked_mesh_points(s: &Session, ids: &[NodeId]) -> Vec<(NodeId, Vec<usize>)> {
|
||||
let o = s.tool_options();
|
||||
let (Some(picked), Ok(st)) = (o.get("meshPoints").and_then(Value::as_array), s.doc()) else { return vec![] };
|
||||
let mut out: Vec<(NodeId, Vec<usize>)> = vec![];
|
||||
for pt in picked {
|
||||
let (Some(id), Some(index)) = (pt.get("id").and_then(Value::as_u64).map(NodeId), pt.get("index").and_then(Value::as_u64)) else { continue };
|
||||
let Ok(index) = usize::try_from(index) else { continue };
|
||||
if !ids.contains(&id) || !matches!(st.doc.node(id).map(|n| &n.kind), Some(NodeKind::Mesh(m)) if index < m.points.len()) {
|
||||
continue;
|
||||
}
|
||||
match out.iter_mut().find(|(m, _)| *m == id) {
|
||||
Some((_, v)) => v.push(index),
|
||||
None => out.push((id, vec![index])),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The picked gradient mesh points (see [`picked_mesh_points`]) when each of `ids` is a gradient
|
||||
/// mesh with points picked: the Transparency panel's opacity is theirs then.
|
||||
pub(crate) fn picked_mesh_points_of(s: &Session, ids: &[NodeId]) -> Option<Vec<(NodeId, Vec<usize>)>> {
|
||||
let v = picked_mesh_points(s, ids);
|
||||
(!ids.is_empty() && ids.iter().all(|id| v.iter().any(|(m, _)| m == id))).then_some(v)
|
||||
}
|
||||
|
||||
/// A type run's stroke; a painted stroke on a run without one gets 1 pt.
|
||||
@@ -753,15 +862,16 @@ fn transparency(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
q.remove("item");
|
||||
q.remove("id");
|
||||
q.insert("ids".into(), json!(ids.iter().map(|id| id.0).collect::<Vec<_>>()));
|
||||
// The gradient mesh point last clicked with the Mesh tool or Direct Selection takes the
|
||||
// opacity itself, so only the mesh around it fades (#4206).
|
||||
// The gradient mesh points picked with the Mesh tool or Direct Selection take the opacity
|
||||
// themselves, so only the mesh around them fades (#4206, #4170, #4208).
|
||||
if matches!(item, ItemTarget::Top)
|
||||
&& let Some(o) = q.get("opacity").and_then(Value::as_f64)
|
||||
&& let Some((id, index, _)) = focused_mesh_point_of(s, &ids)
|
||||
&& let Some(points) = picked_mesh_points_of(s, &ids)
|
||||
{
|
||||
q.remove("opacity");
|
||||
let opacity = f64::from(super::opacitymask::percent(o));
|
||||
s.execute("object.mesh.setPointColor", &json!({"id": id.0, "index": index, "opacity": opacity}))?;
|
||||
let items: Vec<Value> = points.iter().map(|(id, v)| json!({"id": id.0, "points": v})).collect();
|
||||
s.execute("object.mesh.setPointColor", &json!({"items": items, "opacity": opacity}))?;
|
||||
if q.keys().all(|k| k == "ids") {
|
||||
return ok();
|
||||
}
|
||||
|
||||
+114
-38
@@ -98,6 +98,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_selection,
|
||||
average
|
||||
),
|
||||
cmd!(
|
||||
"path.averageJoin",
|
||||
"Average & Join…",
|
||||
["Object", "Path"],
|
||||
Some("Cmd+Alt+Shift+J"),
|
||||
"{to: \"corner\"|\"smooth\" (the joined anchor: corner retracts both handles, smooth pulls handles in line with the neighbours), ids?: [path, ...] (default: the selection; a compound path ID expands to its open member paths)} move two open path ends to their midpoint and join them there, as one undo step: the two direct-selected anchors when they are open path ends, else the nearest ends of the two open paths in ids or the selection (or both ends of one open path, closing it) → the joined path stays selected",
|
||||
has_selection,
|
||||
average_join
|
||||
),
|
||||
cmd!(
|
||||
"path.convertAnchors",
|
||||
"Convert Anchor Points",
|
||||
@@ -802,29 +811,11 @@ fn join(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
};
|
||||
if ida == idb {
|
||||
if sa == sb {
|
||||
s.edit("Join", |d, sel| {
|
||||
close_subpath_in_node(d, ida, sa, join_kind)?;
|
||||
sel.set([compound_or_self(d, ida)]);
|
||||
Ok(())
|
||||
})?;
|
||||
} else {
|
||||
s.edit("Join", |d, sel| {
|
||||
join_subpaths_in_node(d, ida, (sa, sb), (rx, ry), join_kind)?;
|
||||
sel.set([compound_or_self(d, ida)]);
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
return ok();
|
||||
} else {
|
||||
s.edit("Join", |d, sel| {
|
||||
join_two(d, ida, idb, (sa, sb), (rx, ry), join_kind)?;
|
||||
sel.set([compound_or_self(d, ida)]);
|
||||
Ok(())
|
||||
})?;
|
||||
return ok();
|
||||
}
|
||||
s.edit("Join", |d, sel| {
|
||||
sel.set([join_pair(d, (ida, sa), (idb, sb), (rx, ry), join_kind)?]);
|
||||
Ok(())
|
||||
})?;
|
||||
return ok();
|
||||
}
|
||||
|
||||
let ids = selected_paths(s)?;
|
||||
@@ -865,21 +856,11 @@ fn join(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some((rx, ry)) = ends
|
||||
&& open_subs.len() == 2
|
||||
{
|
||||
let (a, sa) = open_subs[0];
|
||||
let (b, sb) = open_subs[1];
|
||||
if a == b {
|
||||
s.edit("Join", |d, sel| {
|
||||
join_subpaths_in_node(d, a, (sa, sb), (rx, ry), join_kind)?;
|
||||
sel.set([compound_or_self(d, a)]);
|
||||
Ok(())
|
||||
})?;
|
||||
} else {
|
||||
s.edit("Join", |d, sel| {
|
||||
join_two(d, a, b, (sa, sb), (rx, ry), join_kind)?;
|
||||
sel.set([compound_or_self(d, a)]);
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
let (a, b) = (open_subs[0], open_subs[1]);
|
||||
s.edit("Join", |d, sel| {
|
||||
sel.set([join_pair(d, a, b, (rx, ry), join_kind)?]);
|
||||
Ok(())
|
||||
})?;
|
||||
return ok();
|
||||
}
|
||||
|
||||
@@ -992,6 +973,17 @@ fn join_two(d: &mut Document, a: NodeId, b: NodeId, (sa, sb): (usize, usize), (r
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Join subpath `sa` of path `a` and subpath `sb` of path `b` oriented as [`join_two`] takes them
|
||||
/// (one subpath: close it). Returns what to select: the joined path, or its compound path.
|
||||
fn join_pair(d: &mut Document, (a, sa): (NodeId, usize), (b, sb): (NodeId, usize), r: (bool, bool), join_kind: Option<bool>) -> Result<NodeId> {
|
||||
if a == b {
|
||||
join_subpaths_in_node(d, a, (sa, sb), r, join_kind)?;
|
||||
} else {
|
||||
join_two(d, a, b, (sa, sb), r, join_kind)?;
|
||||
}
|
||||
Ok(compound_or_self(d, a))
|
||||
}
|
||||
|
||||
pub(super) type AnchorTargets = Vec<(NodeId, Vec<(usize, usize)>)>;
|
||||
|
||||
pub(super) fn anchor_targets(s: &Session) -> Result<AnchorTargets> {
|
||||
@@ -1039,6 +1031,90 @@ fn average(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
/// An open path end: (path, subpath, anchor).
|
||||
type End = (NodeId, usize, usize);
|
||||
|
||||
/// Average & Join: the two ends Average moves to their midpoint, joined there as Join joins them.
|
||||
fn average_join(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "path.averageJoin";
|
||||
let smooth = match str_param(p, "to") {
|
||||
Some("smooth") => true,
|
||||
Some("corner") => false,
|
||||
_ => return Err(bad(C, "`to` must be \"corner\" or \"smooth\"")),
|
||||
};
|
||||
let ends = average_join_ends(s, p, C)?;
|
||||
let [a, b] = ends.ok_or_else(|| bad(C, "select two open path ends, or two open paths, to average and join"))?;
|
||||
let doc = &s.doc()?.doc;
|
||||
let point = |(id, si, ai): End| doc.node(id)?.path_data()?.subpaths.get(si)?.anchors.get(ai).map(|a| a.p);
|
||||
let (Some(pa), Some(pb)) = (point(a), point(b)) else { return Err(bad(C, "join needs open paths")) };
|
||||
let mid = pa.midpoint(pb);
|
||||
// The first end must come last in its subpath, the second first (as `ends` takes them in Join).
|
||||
let r = (a.2 == 0, b.2 != 0);
|
||||
s.edit("Average & Join", |d, sel| {
|
||||
for (id, si, ai) in [a, b] {
|
||||
if let Some(anchor) = path_mut(d, id)?.anchor_mut(si, ai) {
|
||||
anchor.translate(mid - anchor.p);
|
||||
}
|
||||
}
|
||||
sel.set([join_pair(d, (a.0, a.1), (b.0, b.1), r, Some(smooth))?]);
|
||||
Ok(())
|
||||
})?;
|
||||
ok()
|
||||
}
|
||||
|
||||
/// The two ends Average & Join brings together: the two direct-selected anchors when they are
|
||||
/// open path ends; else, of the paths in `ids` or the selected ones, the nearest ends of their two
|
||||
/// open subpaths, or both ends of their one. `None` when there are no such two ends, or when they
|
||||
/// are the two ends of a line, which the midpoint would collapse.
|
||||
fn average_join_ends(s: &Session, p: &Value, c: &str) -> Result<Option<[End; 2]>> {
|
||||
let st = s.doc()?;
|
||||
let doc = &st.doc;
|
||||
let subpath = |id: NodeId, si: usize| doc.node(id)?.path_data()?.subpaths.get(si).filter(|sp| !sp.closed && !sp.anchors.is_empty());
|
||||
let last = |sp: &SubPath| sp.anchors.len().saturating_sub(1);
|
||||
let ids = ids_param(p, "ids");
|
||||
let ends = if ids.is_none() && !st.selection.anchors.is_empty() {
|
||||
let picked: Vec<End> = st.selection.anchors.iter().flat_map(|(&id, set)| set.iter().map(move |&(si, ai)| (id, si, ai))).collect();
|
||||
match picked.as_slice() {
|
||||
&[a, b] if [a, b].iter().all(|&(id, si, ai)| subpath(id, si).is_some_and(|sp| ai == 0 || ai == last(sp))) => [a, b],
|
||||
_ => return Ok(None),
|
||||
}
|
||||
} else {
|
||||
let paths = match ids {
|
||||
None => selected_paths(s)?,
|
||||
Some(ids) => {
|
||||
let mut out = vec![];
|
||||
for id in ids {
|
||||
match doc.node(id).map(|n| (n, &n.kind)) {
|
||||
Some((_, NodeKind::Path { .. })) => out.push(id),
|
||||
Some((n, NodeKind::Compound { .. })) => out.extend(open_members(n)),
|
||||
_ => return Err(bad(c, format!("{} isn't a path", id.0))),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
};
|
||||
let open: Vec<(NodeId, usize, &SubPath)> = paths
|
||||
.iter()
|
||||
.filter_map(|&id| Some((id, doc.node(id)?.path_data()?)))
|
||||
.flat_map(|(id, pd)| {
|
||||
pd.subpaths.iter().enumerate().filter(|(_, sp)| !sp.closed && !sp.anchors.is_empty()).map(move |(si, sp)| (id, si, sp))
|
||||
})
|
||||
.collect();
|
||||
match *open.as_slice() {
|
||||
[(id, si, sp)] => [(id, si, 0), (id, si, last(sp))],
|
||||
[(ia, sa, x), (ib, sb, y)] => {
|
||||
let Some((rx, ry)) = nearest_ends(x, y) else { return Ok(None) };
|
||||
[(ia, sa, if rx { 0 } else { last(x) }), (ib, sb, if ry { last(y) } else { 0 })]
|
||||
}
|
||||
_ => return Ok(None),
|
||||
}
|
||||
};
|
||||
// A subpath's two ends: it needs an anchor between them to close around.
|
||||
let [a, b] = ends;
|
||||
let line = (a.0, a.1) == (b.0, b.1) && subpath(a.0, a.1).is_none_or(|sp| sp.anchors.len() <= 2);
|
||||
Ok((!line).then_some(ends))
|
||||
}
|
||||
|
||||
fn convert_anchors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "path.convertAnchors";
|
||||
let smooth = match str_param(p, "to") {
|
||||
|
||||
@@ -226,7 +226,7 @@ fn ids_json(ids: &[NodeId]) -> Value {
|
||||
|
||||
/// Paint identity carried through a Pathfinder operation.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
struct Style {
|
||||
pub(crate) struct Style {
|
||||
appearance: Appearance,
|
||||
opacity: f32,
|
||||
blend: BlendMode,
|
||||
@@ -236,7 +236,7 @@ impl Style {
|
||||
fn of(n: &Node) -> Self {
|
||||
Style { appearance: (*n.appearance).clone(), opacity: n.opacity, blend: n.blend }
|
||||
}
|
||||
fn apply(&self, n: &mut Node) {
|
||||
pub(crate) fn apply(&self, n: &mut Node) {
|
||||
n.appearance = self.appearance.clone().into();
|
||||
n.opacity = self.opacity;
|
||||
n.blend = self.blend;
|
||||
@@ -267,7 +267,7 @@ pub(crate) fn text_outline(t: &TextObject) -> PathData {
|
||||
PathData::from_bezpath(&lay.to_bezpath()).transformed(t.xf)
|
||||
}
|
||||
|
||||
fn style_of(n: &Node) -> Style {
|
||||
pub(crate) fn style_of(n: &Node) -> Style {
|
||||
match &n.kind {
|
||||
NodeKind::Text(t) => Style { appearance: t.first_style().appearance(), opacity: n.opacity, blend: n.blend },
|
||||
_ => Style::of(n),
|
||||
@@ -294,6 +294,20 @@ fn each_leaf(n: &Node, f: &mut impl FnMut(&Node)) {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`leaves`] as a Pathfinder operation takes them: a compound shape is one shape, the area it
|
||||
/// draws painted as it is (its members as they are past a live Pathfinder's budget).
|
||||
pub(crate) fn pf_leaves(n: &Node, out: &mut Vec<Node>) {
|
||||
match &n.kind {
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => {
|
||||
match vectorcraft_render::effects::compound_shape_art(n, vectorcraft_render::effects::text_outliner()) {
|
||||
Some(art) => out.push(art),
|
||||
None => children.iter().for_each(|c| pf_leaves(c, out)),
|
||||
}
|
||||
}
|
||||
_ => leaves(n, out),
|
||||
}
|
||||
}
|
||||
|
||||
/// How many shapes a Pathfinder operation takes from `n` selected alone: its leaf shapes, however
|
||||
/// deep its groups nest (an expanded stroke is a group inside the group, #1635).
|
||||
pub fn shape_count(n: &Node) -> usize {
|
||||
@@ -554,7 +568,7 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> {
|
||||
for id in &roots {
|
||||
let n = d.node(*id).ok_or(EngineError::NoNode(*id))?;
|
||||
let mut lv = vec![];
|
||||
leaves(n, &mut lv);
|
||||
pf_leaves(n, &mut lv);
|
||||
if lv.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -377,6 +377,9 @@ pub const PREF_SPECS: &[PrefSpec] = &[
|
||||
choice(&[("default", "Default"), ("object", "Transform Object Only"), ("pattern", "Transform Pattern Only"), ("both", "Transform Both")])
|
||||
),
|
||||
p!("useRegistrationPointForSymbol", "General", "Transform Panel", "Use Registration Point for Symbol", bool),
|
||||
// The Align panel menu's Align to Glyph Bounds: Align and Distribute measure type by its glyphs' ink.
|
||||
p!("alignGlyphBoundsPoint", "Type", "Align to Glyph Bounds", "Point Text", bool),
|
||||
p!("alignGlyphBoundsArea", "Type", "Align to Glyph Bounds", "Area Text", bool),
|
||||
];
|
||||
|
||||
pub fn spec(key: &str) -> Option<&'static PrefSpec> {
|
||||
@@ -385,10 +388,11 @@ pub fn spec(key: &str) -> Option<&'static PrefSpec> {
|
||||
|
||||
/// Preferences kept as one object with a command of their own instead of [`PREF_SPECS`] rows (they
|
||||
/// aren't in the Preferences dialog): the Eyedropper Options (`eyedropper.setOptions`), the
|
||||
/// Perspective Grid Options (`perspective.widget.options`) and the Pathfinder Options
|
||||
/// (`object.pathfinder.options`). `prefs.get` and `prefs.set` take them by key (a partial object
|
||||
/// updates what it names) and `prefs.reset` without a category resets them.
|
||||
pub const PREF_GROUPS: &[&str] = &["eyedropper", "perspectiveWidget", "pathfinder"];
|
||||
/// Perspective Grid Options (`perspective.widget.options`), the Pathfinder Options
|
||||
/// (`object.pathfinder.options`) and the Snap to Glyph options (`view.snapToGlyph.options`).
|
||||
/// `prefs.get` and `prefs.set` take them by key (a partial object updates what it names) and
|
||||
/// `prefs.reset` without a category resets them.
|
||||
pub const PREF_GROUPS: &[&str] = &["eyedropper", "perspectiveWidget", "pathfinder", "glyphSnap"];
|
||||
|
||||
/// Validate a value for preference group `key` against `current`.
|
||||
fn validate_group(key: &str, current: &Value, v: &Value) -> std::result::Result<Value, String> {
|
||||
@@ -401,6 +405,10 @@ fn validate_group(key: &str, current: &Value, v: &Value) -> std::result::Result<
|
||||
let cur: super::PathfinderOptions = serde_json::from_value(current.clone()).unwrap_or_default();
|
||||
cur.merged(v).map(|o| json!(o))
|
||||
}
|
||||
"glyphSnap" => {
|
||||
let cur: vectorcraft_tools::GlyphSnap = serde_json::from_value(current.clone()).unwrap_or_default();
|
||||
cur.merged(v).map(|o| json!(o))
|
||||
}
|
||||
"perspectiveWidget" => {
|
||||
let mut merged = current.clone();
|
||||
if let (Some(o), Some(p)) = (merged.as_object_mut(), v.as_object()) {
|
||||
|
||||
@@ -13,7 +13,9 @@ use vectorcraft_doc::swatches::{node_colors, node_paints};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
|
||||
use super::colorcmds::{Recolor, Scope};
|
||||
use super::{CommandSpec, Result, Session, always, bad, bool_or, checked_ids_param, cmd, color_value, has_doc, index, str_param};
|
||||
use super::{
|
||||
CommandSpec, Result, Session, always, bad, check_switches, checked_ids_param, cmd, color_value, has_doc, index, str_param, switch_or, text_param,
|
||||
};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -152,15 +154,18 @@ fn colors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "colors": v }))
|
||||
}
|
||||
|
||||
/// The `method` parameter (`default` without one).
|
||||
/// The `method` parameter (`default` without one, or for null). A `method` that is not a string,
|
||||
/// such as `5`, names no method.
|
||||
fn method_param(p: &Value, cmd: &str, default: Method) -> Result<Method> {
|
||||
match str_param(p, "method") {
|
||||
None => Ok(default),
|
||||
Some(m) => Method::parse(m).ok_or_else(|| {
|
||||
let ids: Vec<&str> = Method::ALL.iter().map(|m| m.id()).collect();
|
||||
bad(cmd, format!("unknown method `{m}` ({})", ids.join("|")))
|
||||
}),
|
||||
}
|
||||
let (m, named) = match p.get("method") {
|
||||
None | Some(Value::Null) => return Ok(default),
|
||||
Some(Value::String(m)) => (m.clone(), true),
|
||||
Some(v) => (v.to_string(), false),
|
||||
};
|
||||
Method::parse(&m).filter(|_| named).ok_or_else(|| {
|
||||
let ids: Vec<&str> = Method::ALL.iter().map(|m| m.id()).collect();
|
||||
bad(cmd, format!("unknown method `{m}` ({})", ids.join("|")))
|
||||
})
|
||||
}
|
||||
|
||||
fn key_str(c: &Color) -> Value {
|
||||
@@ -172,8 +177,17 @@ fn reduce(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let method = method_param(p, C, Method::ScaleTints)?;
|
||||
let palette = super::swatchlib::limit_param(s, p, C)?;
|
||||
let def = Preserve::default();
|
||||
let flag = |k: &str, d: bool| p.get("preserve").map_or(d, |v| bool_or(v, k, d));
|
||||
let preserve = Preserve { white: flag("white", def.white), black: flag("black", def.black), grays: flag("grays", def.grays) };
|
||||
let given = match p.get("preserve") {
|
||||
None | Some(Value::Null) => &Value::Null,
|
||||
Some(v @ Value::Object(_)) => v,
|
||||
Some(_) => return Err(bad(C, "`preserve` must be an object")),
|
||||
};
|
||||
let flag = |k: &str, d: bool| switch_or(given, k, d, C);
|
||||
let preserve = Preserve { white: flag("white", def.white)?, black: flag("black", def.black)?, grays: flag("grays", def.grays)? };
|
||||
let colors = match p.get("colors") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(_) => Some(index(super::menucmds::whole_or(p, "colors", 0, C)?)),
|
||||
};
|
||||
let (ids, only) = scope_ids(s, p, C)?;
|
||||
let st = s.doc()?;
|
||||
let (kept, used): (Vec<Used>, Vec<Used>) = used_colors(&st.doc, &ids, only.as_ref()).into_iter().partition(|u| preserve.keeps(&u.color));
|
||||
@@ -186,7 +200,7 @@ fn reduce(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
let unit_colors = |g: &[&Used]| g.iter().map(|u| u.color).collect::<Vec<_>>();
|
||||
let rows: Vec<Vec<&Used>> = match p.get("colors").and_then(Value::as_u64).map(index) {
|
||||
let rows: Vec<Vec<&Used>> = match colors {
|
||||
Some(n) if n < units.len() => {
|
||||
let keys: Vec<Color> = units.iter().map(|g| method.key_color(&unit_colors(g)).unwrap_or_default()).collect();
|
||||
let weights: Vec<f32> = units.iter().map(|g| g.iter().map(|u| u.count as f32).sum()).collect();
|
||||
@@ -275,7 +289,7 @@ fn parse_rows(p: &Value, cmd: &str) -> Result<Vec<Row>> {
|
||||
Some(v) => vec![cur(v)?],
|
||||
None => return Err(bad(cmd, "each row needs `from`")),
|
||||
};
|
||||
Ok(Row { from, to: new(r.get("to"))?, exclude: bool_or(r, "exclude", false) })
|
||||
Ok(Row { from, to: new(r.get("to"))?, exclude: switch_or(r, "exclude", false, cmd)? })
|
||||
})
|
||||
.collect(),
|
||||
_ => Err(bad(cmd, "missing `map` (rows [{from, to}] or {current: new})")),
|
||||
@@ -419,10 +433,11 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let row_swatches: Vec<Option<Swatch>> =
|
||||
rows.iter().map(|r| r.new_color().and_then(|c| lib_swatches.iter().find(|w| w.paint.color() == Some(c)).cloned())).collect();
|
||||
let ids = s.doc()?.selection.objects.clone();
|
||||
let group = str_param(p, "group");
|
||||
let group = text_param(p, "group", C)?;
|
||||
if ids.is_empty() && group.is_none() {
|
||||
return Err(bad(C, "select artwork to recolour, or give a colour `group`"));
|
||||
}
|
||||
check_switches(p, &["includeImages", "includePatterns"], C)?;
|
||||
let scope = Scope { fill: true, stroke: true, ..Scope::of(p) };
|
||||
let label = if ids.is_empty() { "Edit Color Group" } else { "Recolor Artwork" };
|
||||
// `model`: keep each colour's model (default), take the new colour's own, or the document's.
|
||||
@@ -448,7 +463,12 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
// The colours a colour group takes follow the model too (`document` converts them).
|
||||
let in_doc_model = |c: Color| doc_model.map_or(c, |m| c.in_model(m));
|
||||
let new: Vec<Color> = match p.get("groupColors").and_then(Value::as_array) {
|
||||
let group_colors = match p.get("groupColors") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(Value::Array(cs)) => Some(cs),
|
||||
Some(_) => return Err(bad(C, "`groupColors` must be an array")),
|
||||
};
|
||||
let new: Vec<Color> = match group_colors {
|
||||
Some(cs) => cs
|
||||
.iter()
|
||||
.map(|v| {
|
||||
@@ -459,7 +479,7 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.collect::<Result<_>>()?,
|
||||
None => rows.iter().filter_map(Row::new_color).collect(),
|
||||
};
|
||||
let rename = str_param(p, "rename");
|
||||
let rename = text_param(p, "rename", C)?;
|
||||
let (changed, edit, added, converted) = s.edit(label, |d, _| {
|
||||
// The rows' library swatches join the document (one it has with that name and colour is
|
||||
// used as it is).
|
||||
@@ -518,12 +538,13 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn randomize(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "recolor.randomize";
|
||||
let rows = parse_rows(p, C)?;
|
||||
let mut rng = Rng::new(p.get("seed").and_then(Value::as_u64).unwrap_or(0));
|
||||
let mut rng = Rng::new(super::menucmds::whole_or(p, "seed", 0, C)?);
|
||||
let (order, saturation_brightness) = (switch_or(p, "order", true, C)?, switch_or(p, "saturationBrightness", false, C)?);
|
||||
let mut news: Vec<Color> = rows.iter().filter_map(Row::new_color).collect();
|
||||
if bool_or(p, "order", true) {
|
||||
if order {
|
||||
rng.shuffle(&mut news);
|
||||
}
|
||||
if bool_or(p, "saturationBrightness", false) {
|
||||
if saturation_brightness {
|
||||
news = news.into_iter().map(|c| rng.saturation_brightness(c)).collect();
|
||||
}
|
||||
let mut news = news.into_iter();
|
||||
|
||||
@@ -14,9 +14,8 @@ use vectorcraft_doc::style_libs::{self, STYLE_LIBRARIES, STYLES_EXT, builtin_sty
|
||||
use vectorcraft_doc::{Document, GraphicStyle, PatternDef, StyleLibrary};
|
||||
|
||||
use super::menucmds::squash;
|
||||
use super::swatch::str_list;
|
||||
use super::swatchlib::{FileData, LibraryFile, LibraryInfo, stem};
|
||||
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, str_param, unique_name};
|
||||
use super::swatchlib::{FileData, LibraryFile, LibraryInfo, names_param, stem};
|
||||
use super::{CommandSpec, Result, Session, always, bad, checked_ids_param, cmd, has_doc, str_param, switch_or, text_param, unique_name};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -154,8 +153,12 @@ fn adopt(d: &mut Document, lib: &StyleLibrary, g: &GraphicStyle, renamed: &mut H
|
||||
fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "graphicStyle.addFromLibrary";
|
||||
let (info, lib) = library_param(s, p, C)?;
|
||||
let mut names = str_list(p, "names");
|
||||
names.extend(str_param(p, "name").map(str::to_string));
|
||||
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()) {
|
||||
checked_ids_param(s, p, "ids", C)?;
|
||||
}
|
||||
let mut names = names_param(p, C)?;
|
||||
names.extend(text_param(p, "name", C)?.map(str::to_string));
|
||||
if let Some(n) = names.iter().find(|n| lib.style(n).is_none()) {
|
||||
return Err(bad(C, format!("no graphic style `{n}` in `{}`", lib.name)));
|
||||
}
|
||||
@@ -192,8 +195,8 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
});
|
||||
let first = picked.first().map(|g| doc_name(&g.name));
|
||||
let targets = p.get("ids").is_some() || !super::appearance::appearance_targets(s, &json!({}))?.is_empty();
|
||||
if let Some(name) = first.filter(|_| bool_or(p, "apply", false) && targets) {
|
||||
let mut params = json!({"name": name, "add": bool_or(p, "add", false)});
|
||||
if let Some(name) = first.filter(|_| apply && targets) {
|
||||
let mut params = json!({"name": name, "add": add});
|
||||
if let Some(ids) = p.get("ids") {
|
||||
params["ids"] = ids.clone();
|
||||
}
|
||||
@@ -208,8 +211,9 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "graphicStyle.saveLibrary";
|
||||
let st = s.doc()?;
|
||||
let name = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).map_or_else(|| stem(&st.title()).to_string(), str::to_string);
|
||||
let lib = StyleLibrary::from_document(&st.doc, &str_list(p, "names"), name).map_err(|e| bad(C, e))?;
|
||||
let name = text_param(p, "name", C)?.map(str::trim).filter(|n| !n.is_empty()).map_or_else(|| stem(&st.title()).to_string(), str::to_string);
|
||||
let names = names_param(p, C)?;
|
||||
let lib = StyleLibrary::from_document(&st.doc, &names, name).map_err(|e| bad(C, e))?;
|
||||
let mut out = json!({ "count": lib.len() });
|
||||
s.style_libraries.write(p, &lib.name, STYLES_EXT, FileData::Text(style_libs::write(&lib)), &mut out, C)?;
|
||||
Ok(out)
|
||||
|
||||
@@ -252,12 +252,15 @@ fn swatch_delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let mut unlink =
|
||||
|_: &mut Color, link: &mut Option<String>, _: &mut f32| link.as_ref().is_some_and(|l| global.contains(l)) && link.take().is_some();
|
||||
let colorized_ok = super::paint::check_colorized(d).is_ok();
|
||||
let unlinked = s.edit("Delete Swatch", |d, _| {
|
||||
d.swatch_groups.retain(|g| !names.contains(&g.name));
|
||||
for n in &names {
|
||||
d.remove_swatch(n);
|
||||
}
|
||||
Ok(map_swatch_links(d, &mut unlink))
|
||||
let unlinked = map_swatch_links(d, &mut unlink);
|
||||
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))?;
|
||||
Ok(unlinked)
|
||||
})?;
|
||||
map_default_paints(s, &mut unlink);
|
||||
Ok(json!({"deleted": names, "unlinked": unlinked}))
|
||||
@@ -703,6 +706,7 @@ fn swatch_edit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let global = spot || bool_or(p, "global", sw.global);
|
||||
let to = name_param(p, "newName").filter(|n| *n != name).map_or_else(|| name.clone(), |n| d.free_swatch_name(&n));
|
||||
let relink = Relink { from: name.clone(), to: to.clone(), color: color.filter(|_| global).map(|c| d.linked_color(c, spot)), keep: global };
|
||||
let colorized_ok = super::paint::check_colorized(d).is_ok();
|
||||
let relinked = s.edit("Swatch Options", |d, _| {
|
||||
let w = d.swatch_mut(&name).ok_or_else(|| bad(C, format!("no swatch `{name}`")))?;
|
||||
w.name = to.clone();
|
||||
@@ -716,7 +720,9 @@ fn swatch_edit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(map_swatch_links(d, &mut |c, l, t| relink.apply(c, l, t)))
|
||||
let relinked = map_swatch_links(d, &mut |c, l, t| relink.apply(c, l, t));
|
||||
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))?;
|
||||
Ok(relinked)
|
||||
})?;
|
||||
relink.defaults(s);
|
||||
Ok(json!({"name": to, "relinked": relinked}))
|
||||
@@ -867,11 +873,14 @@ fn swatch_merge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
*l = link.clone();
|
||||
true
|
||||
};
|
||||
let colorized_ok = super::paint::check_colorized(d).is_ok();
|
||||
let relinked = s.edit("Merge Swatches", |d, _| {
|
||||
for n in merged {
|
||||
d.remove_swatch(n);
|
||||
}
|
||||
Ok(map_swatch_links(d, &mut relink))
|
||||
let relinked = map_swatch_links(d, &mut relink);
|
||||
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))?;
|
||||
Ok(relinked)
|
||||
})?;
|
||||
map_default_paints(s, &mut relink);
|
||||
Ok(json!({"name": keep, "merged": merged, "relinked": relinked}))
|
||||
@@ -980,6 +989,7 @@ pub(super) fn rewrite_group(d: &mut Document, group: &str, colors: &[Color], ren
|
||||
{
|
||||
return Err(bad(cmd, format!("`{}` can't be edited or removed", w.name)));
|
||||
}
|
||||
let colorized_ok = super::paint::check_colorized(d).is_ok();
|
||||
let mut relinks = vec![];
|
||||
let mut swatches = std::mem::take(&mut d.swatch_groups[gi].swatches);
|
||||
for gone in swatches.split_off(colors.len().min(swatches.len())) {
|
||||
@@ -1005,6 +1015,7 @@ pub(super) fn rewrite_group(d: &mut Document, group: &str, colors: &[Color], ren
|
||||
(g.name, g.swatches) = (name.clone(), swatches);
|
||||
let names = g.swatches.iter().map(|w| w.name.clone()).collect();
|
||||
let relinked = if relinks.is_empty() { 0 } else { map_swatch_links(d, &mut |c, l, t| relinks.iter().any(|r| r.apply(c, l, t))) };
|
||||
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(cmd, e))?;
|
||||
Ok(GroupEdit { name, swatches: names, relinks, relinked })
|
||||
}
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ use super::fileio::{create_dir, extension, read_file, write_file, write_new_file
|
||||
use super::menucmds::squash;
|
||||
use super::package::free_name;
|
||||
use super::swatch::{map_default_paints, map_swatch_links, str_list, swatch_json};
|
||||
use super::{Color, CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, str_param};
|
||||
use super::{Color, CommandSpec, Result, Session, always, bad, cmd, has_doc, switch_or, text_param};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -201,7 +201,8 @@ impl<L: LibraryFile> Libraries<L> {
|
||||
FileData::Text(text) => text.as_bytes(),
|
||||
FileData::Binary(bytes) => bytes.as_slice(),
|
||||
};
|
||||
if bool_or(p, "user", false) {
|
||||
let path = text_param(p, "path", cmd)?;
|
||||
if switch_or(p, "user", false, cmd)? {
|
||||
let dir = self
|
||||
.user_dir()
|
||||
.ok_or_else(|| bad(cmd, "no user library folder here (save with a path, or without one to get the data)"))?
|
||||
@@ -213,7 +214,7 @@ impl<L: LibraryFile> Libraries<L> {
|
||||
self.rescan();
|
||||
out["path"] = json!(path);
|
||||
out["library"] = json!(format!("user/{file}"));
|
||||
} else if let Some(path) = str_param(p, "path") {
|
||||
} else if let Some(path) = path {
|
||||
write_file(path, bytes)?;
|
||||
out["path"] = json!(path);
|
||||
} else {
|
||||
@@ -230,14 +231,14 @@ impl<L: LibraryFile> Libraries<L> {
|
||||
/// or a file with the same extension and bytes as one there, is that User Defined library;
|
||||
/// others are listed as loaded until the app quits.
|
||||
pub(crate) fn load(&mut self, p: &Value, cmd: &str, parse: impl FnOnce(&[u8], &str) -> Result<L>) -> Result<(LibraryInfo, Arc<L>)> {
|
||||
let path = str_param(p, "path");
|
||||
let bytes = match (path, str_param(p, "data"), str_param(p, "dataBase64")) {
|
||||
let path = text_param(p, "path", cmd)?;
|
||||
let bytes = match (path, text_param(p, "data", cmd)?, text_param(p, "dataBase64", cmd)?) {
|
||||
(Some(path), ..) => read_file(path)?,
|
||||
(None, Some(text), _) => text.as_bytes().to_vec(),
|
||||
(None, None, Some(b64)) => vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(cmd, "bad dataBase64"))?,
|
||||
_ => return Err(bad(cmd, "give `path`, `data` or `dataBase64`")),
|
||||
};
|
||||
let file = str_param(p, "name").map(str::to_string).or_else(|| path.map(file_name)).unwrap_or_else(|| "Library".into());
|
||||
let file = text_param(p, "name", cmd)?.map(str::to_string).or_else(|| path.map(file_name)).unwrap_or_else(|| "Library".into());
|
||||
let lib = parse(&bytes, &file)?;
|
||||
self.rescan();
|
||||
let user =
|
||||
@@ -428,19 +429,36 @@ pub fn library_swatches(s: &Session, key: &str) -> Option<Vec<Swatch>> {
|
||||
Some(library(s, key)?.1.iter().filter(own).cloned().collect())
|
||||
}
|
||||
|
||||
/// The `limitTo` parameter's palette ([`limit_palette`]); `None` without one (or for "").
|
||||
/// The `limitTo` parameter's palette ([`limit_palette`]); `None` without one (or for "" or null).
|
||||
/// A `limitTo` that is not a string, such as `5`, names no library.
|
||||
pub(crate) fn limit_param(s: &Session, p: &Value, cmd: &str) -> Result<Option<Palette>> {
|
||||
let Some(key) = str_param(p, "limitTo").filter(|k| !k.is_empty()) else { return Ok(None) };
|
||||
let palette = limit_palette(s, key)
|
||||
.ok_or_else(|| bad(cmd, format!("no swatch library `{key}` (see swatch.library.list; \"{DOCUMENT_SWATCHES}\": the document's swatches)")))?;
|
||||
let no_library =
|
||||
|key: &str| bad(cmd, format!("no swatch library `{key}` (see swatch.library.list; \"{DOCUMENT_SWATCHES}\": the document's swatches)"));
|
||||
let key = match p.get("limitTo") {
|
||||
None | Some(Value::Null) => return Ok(None),
|
||||
Some(Value::String(k)) if k.is_empty() => return Ok(None),
|
||||
Some(Value::String(k)) => k.as_str(),
|
||||
Some(v) => return Err(no_library(&v.to_string())),
|
||||
};
|
||||
let palette = limit_palette(s, key).ok_or_else(|| no_library(key))?;
|
||||
if palette.is_empty() {
|
||||
return Err(bad(cmd, format!("`{key}` has no colours")));
|
||||
}
|
||||
Ok(Some(palette))
|
||||
}
|
||||
|
||||
/// The `names` parameter ([`str_list`]): empty when it is left out or null; anything but a list of
|
||||
/// strings is an error.
|
||||
pub(super) fn names_param(p: &Value, cmd: &str) -> Result<Vec<String>> {
|
||||
match p.get("names") {
|
||||
None | Some(Value::Null) => Ok(vec![]),
|
||||
Some(Value::Array(a)) if a.iter().all(Value::is_string) => Ok(str_list(p, "names")),
|
||||
Some(_) => Err(bad(cmd, "`names` must be a list of names")),
|
||||
}
|
||||
}
|
||||
|
||||
fn library_param(s: &Session, p: &Value, cmd: &str) -> Result<(LibraryInfo, Arc<SwatchLibrary>)> {
|
||||
let key = str_param(p, "library").ok_or_else(|| bad(cmd, "missing `library` (see swatch.library.list)"))?;
|
||||
let key = text_param(p, "library", cmd)?.ok_or_else(|| bad(cmd, "missing `library` (see swatch.library.list)"))?;
|
||||
library(s, key).ok_or_else(|| bad(cmd, format!("no swatch library `{key}` (see swatch.library.list)")))
|
||||
}
|
||||
|
||||
@@ -479,14 +497,15 @@ fn document_library(d: &vectorcraft_doc::Document, names: &[String], name: Strin
|
||||
|
||||
fn save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "swatch.library.save";
|
||||
let path = str_param(p, "path");
|
||||
let format = match str_param(p, "format").or_else(|| path.map(|p| p.rsplit_once('.').map_or("", |(_, e)| e))).filter(|f| !f.is_empty()) {
|
||||
let path = text_param(p, "path", C)?;
|
||||
let format = match text_param(p, "format", C)?.or_else(|| path.map(|p| p.rsplit_once('.').map_or("", |(_, e)| e))).filter(|f| !f.is_empty()) {
|
||||
Some(f) => PaletteFormat::parse(f).ok_or_else(|| bad(C, format!("unknown format `{f}` (vcswatches, gpl, ase or css)")))?,
|
||||
None => PaletteFormat::Native,
|
||||
};
|
||||
let names = names_param(p, C)?;
|
||||
let st = s.doc()?;
|
||||
let name = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).map_or_else(|| stem(&st.title()).to_string(), str::to_string);
|
||||
let lib = document_library(&st.doc, &str_list(p, "names"), name, C)?;
|
||||
let name = text_param(p, "name", C)?.map(str::trim).filter(|n| !n.is_empty()).map_or_else(|| stem(&st.title()).to_string(), str::to_string);
|
||||
let lib = document_library(&st.doc, &names, name, C)?;
|
||||
let bytes = palette_io::write(&lib, format).map_err(|e| bad(C, e))?;
|
||||
let data = if format.binary() { FileData::Binary(bytes) } else { FileData::Text(String::from_utf8_lossy(&bytes).into_owned()) };
|
||||
let mut out = json!({"format": format.id(), "count": lib.iter().filter(|w| format.holds(&w.paint)).count()});
|
||||
@@ -571,13 +590,14 @@ fn picked<'a>(lib: &'a SwatchLibrary, names: &[String], cmd: &str) -> Result<Vec
|
||||
fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "swatch.library.add";
|
||||
let (info, lib) = library_param(s, p, C)?;
|
||||
let apply = match str_param(p, "apply") {
|
||||
let apply = match text_param(p, "apply", C)? {
|
||||
None => None,
|
||||
Some("fill") => Some("paint.setFill"),
|
||||
Some("stroke") => Some("paint.setStroke"),
|
||||
Some(other) => return Err(bad(C, format!("apply is \"fill\" or \"stroke\", not `{other}`"))),
|
||||
};
|
||||
let picked = picked(&lib, &str_list(p, "names"), C)?;
|
||||
let focus = switch_or(p, "focus", true, C)?;
|
||||
let picked = picked(&lib, &names_param(p, C)?, C)?;
|
||||
// Swatches the document already has (same name and paint) are reused, not added again.
|
||||
let d = &s.doc()?.doc;
|
||||
let (existing, fresh): (Vec<_>, Vec<_>) = picked.iter().partition(|(_, w)| d.swatch(&w.name).is_some_and(|x| x.paint == w.paint));
|
||||
@@ -622,7 +642,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut out = json!({"library": info.id, "added": added.iter().map(|(_, n)| n).collect::<Vec<_>>(), "existing": existing});
|
||||
if let (Some(cmd), Some((_, first))) = (apply, picked.first()) {
|
||||
let name = added.iter().find(|(l, _)| *l == first.name).map_or(first.name.clone(), |(_, n)| n.clone());
|
||||
s.execute(cmd, &json!({"swatch": name, "focus": bool_or(p, "focus", true)}))?;
|
||||
s.execute(cmd, &json!({"swatch": name, "focus": focus}))?;
|
||||
// Adding and applying undo together.
|
||||
squash(s, undo_before, "Add to Swatches");
|
||||
out["applied"] = json!(name);
|
||||
@@ -631,12 +651,13 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn reset_defaults(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let replace = bool_or(p, "replace", false);
|
||||
let replace = switch_or(p, "replace", false, "swatch.resetDefaults")?;
|
||||
let model = s.doc()?.doc.color_mode.model();
|
||||
let (defaults, groups) = default_swatches(model);
|
||||
// With replace, links to swatches that are no longer global ones are dropped (the art keeps
|
||||
// its colour); filled in by the edit.
|
||||
let mut live: Vec<String> = vec![];
|
||||
let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok();
|
||||
let added = s.edit("Default Swatches", |d, _| {
|
||||
let mut added = vec![];
|
||||
if replace {
|
||||
@@ -645,6 +666,7 @@ fn reset_defaults(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
added.extend(d.swatches_iter().filter(|w| !before.contains(&w.name)).map(|w| w.name.clone()));
|
||||
live.extend(d.swatches_iter().filter(|w| w.global).map(|w| w.name.clone()));
|
||||
map_swatch_links(d, &mut |_, l, _| unlink_dead(&live, l));
|
||||
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad("swatch.resetDefaults", e))?;
|
||||
return Ok(added);
|
||||
}
|
||||
for (i, w) in defaults.into_iter().enumerate() {
|
||||
|
||||
@@ -366,11 +366,27 @@ pub(crate) fn selected_style_attrs(s: &Session, para: bool) -> Result<Option<Map
|
||||
selection_attrs(s, &json!({}), if para { Kind::Para } else { Kind::Char })
|
||||
}
|
||||
|
||||
/// The attributes `charStyle.new` (`para`: `paraStyle.new`) would give a style made now from
|
||||
/// `target` (its `id`, `start` and `end`; empty for the selected objects). `None` without text
|
||||
/// there.
|
||||
pub fn target_style_attrs(s: &Session, target: &Value, para: bool) -> Option<Map<String, Value>> {
|
||||
selection_attrs(s, target, if para { Kind::Para } else { Kind::Char }).ok().flatten()
|
||||
}
|
||||
|
||||
/// Whether the document has a character (`para`: paragraph) style `name`, and its attributes.
|
||||
pub(crate) fn style_attrs(d: &Document, para: bool, name: &str) -> Option<Map<String, Value>> {
|
||||
if para { Kind::Para } else { Kind::Char }.attrs(d, name)
|
||||
}
|
||||
|
||||
/// The name `charStyle.new` (`para`: `paraStyle.new`) gives a style when it is given none: the
|
||||
/// first "Character Style N" ("Paragraph Style N") that no character style (paragraph style) of the
|
||||
/// document has.
|
||||
pub fn new_style_name(d: &Document, para: bool) -> String {
|
||||
let kind = if para { Kind::Para } else { Kind::Char };
|
||||
let base = if para { "Paragraph Style" } else { "Character Style" };
|
||||
(1..).map(|i| format!("{base} {i}")).find(|n| kind.attrs(d, n).is_none()).unwrap_or_else(|| base.to_string())
|
||||
}
|
||||
|
||||
fn name_param<'a>(p: &'a Value, kind: Kind, verb: &str) -> Result<&'a str> {
|
||||
str_param(p, "name").ok_or_else(|| bad(&kind.cmd(verb), "missing `name`"))
|
||||
}
|
||||
@@ -436,10 +452,9 @@ fn new(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
|
||||
},
|
||||
};
|
||||
let d = &s.doc()?.doc;
|
||||
let base = if kind == Kind::Char { "Character Style" } else { "Paragraph Style" };
|
||||
let name = match str_param(p, "name") {
|
||||
Some(n) => n.trim().to_string(),
|
||||
None => (1..).map(|i| format!("{base} {i}")).find(|n| kind.attrs(d, n).is_none()).unwrap_or_else(|| base.to_string()),
|
||||
None => new_style_name(d, kind == Kind::Para),
|
||||
};
|
||||
if name.is_empty() {
|
||||
return Err(bad(&c, "give the style a name"));
|
||||
|
||||
@@ -96,7 +96,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reshape Type Area",
|
||||
[],
|
||||
None,
|
||||
"{id, anchors: [[subpath, anchor]…], dx, dy} move anchors of area type's frame (the type area) by dx, dy points, with their handles; the text reflows at its size, through its thread too (what Direct Selection does dragging a frame corner or edge)",
|
||||
"{id, anchors: [[subpath, anchor]…], dx, dy} or {items: [{id, anchors}…], dx, dy} move anchors of area type's frame (the type area) by dx, dy points, with their handles; the text reflows at its size, through its thread too (what Direct Selection does dragging a frame corner or edge, or the frame anchors its marquee selected, and the arrow keys nudging those); with items, every listed frame moves in one step",
|
||||
has_doc,
|
||||
reshape_area
|
||||
),
|
||||
@@ -1063,22 +1063,45 @@ fn area_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn reshape_area(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.reshapeArea";
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?;
|
||||
let mut refs = super::select::checked_refs(p.get("anchors"), C)?;
|
||||
refs.sort_unstable();
|
||||
refs.dedup();
|
||||
if refs.is_empty() {
|
||||
return Err(bad(C, "missing anchors [[subpath, anchor]…]"));
|
||||
// One area type (`id`, `anchors`), or several (`items`: [{id, anchors}…]).
|
||||
let raw: Vec<&Value> = match p.get("items") {
|
||||
Some(items) => {
|
||||
if p.get("id").is_some() || p.get("anchors").is_some() {
|
||||
return Err(bad(C, "give `id` and `anchors`, or `items`, not both"));
|
||||
}
|
||||
let items = items.as_array().ok_or_else(|| bad(C, "`items` must be an array of {id, anchors}"))?;
|
||||
if items.is_empty() {
|
||||
return Err(bad(C, "`items` is empty"));
|
||||
}
|
||||
items.iter().collect()
|
||||
}
|
||||
None => vec![p],
|
||||
};
|
||||
let mut items = Vec::with_capacity(raw.len());
|
||||
for it in raw {
|
||||
let id = id_param(it, "id").ok_or_else(|| bad(C, "missing id"))?;
|
||||
let mut refs = super::select::checked_refs(it.get("anchors"), C)?;
|
||||
refs.sort_unstable();
|
||||
refs.dedup();
|
||||
if refs.is_empty() {
|
||||
return Err(bad(C, "missing anchors [[subpath, anchor]…]"));
|
||||
}
|
||||
if items.iter().any(|(other, _)| *other == id) {
|
||||
return Err(bad(C, format!("area type {} is named twice", id.0)));
|
||||
}
|
||||
let node = s.doc()?.doc.node(id);
|
||||
if area_text(node).is_none() || node.is_some_and(|n| n.extras().perspective.is_some()) {
|
||||
return Err(bad(C, "not area type (text in a frame) outside perspective"));
|
||||
}
|
||||
items.push((id, refs));
|
||||
}
|
||||
let d = Vec2::new(f64_req(p, "dx", C)?, f64_req(p, "dy", C)?);
|
||||
let node = s.doc()?.doc.node(id);
|
||||
if area_text(node).is_none() || node.is_some_and(|n| n.extras().perspective.is_some()) {
|
||||
return Err(bad(C, "not area type (text in a frame) outside perspective"));
|
||||
}
|
||||
s.edit("Reshape Type Area", |doc, _| {
|
||||
let Some(NodeKind::Text(t)) = doc.node_mut(id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(id)) };
|
||||
if !reshape_area_with(t, |t| t.move_area_anchors(&refs, d)) {
|
||||
return Err(bad(C, "no such frame anchor, or the frame would reach past the canvas"));
|
||||
for (id, refs) in &items {
|
||||
let Some(NodeKind::Text(t)) = doc.node_mut(*id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(*id)) };
|
||||
if !reshape_area_with(t, |t| t.move_area_anchors(refs, d)) {
|
||||
return Err(bad(C, "no such frame anchor, or the frame would reach past the canvas"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
//! View → New View… / Edit Views…: saved views stored in the document; per-document view
|
||||
//! toggles (Show Transparency Grid).
|
||||
//! toggles (Show Transparency Grid); the Character panel's Snap to Glyph options.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::SavedView;
|
||||
use vectorcraft_geom::Point;
|
||||
|
||||
use super::{CommandSpec, Result, Session, bad, bool_or, cmd, f64_req, finite_numbers, has_doc, str_param};
|
||||
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, f64_req, finite_numbers, has_doc, str_param};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -37,9 +37,23 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
transparency_grid
|
||||
),
|
||||
cmd!(
|
||||
query "view.snapToGlyph.options",
|
||||
"Snap to Glyph Options",
|
||||
[],
|
||||
None,
|
||||
"{baseline?: bool, xHeight?: bool, bounds?: bool, proximity?: bool, angular?: bool, anchors?: bool} the Character panel's Snap to Glyph options, kept in the preferences (the glyphSnap group, all on by default): which guides View › Snap to Glyph gives — the baseline and x-height of a single line of type, Glyph Bounds (each glyph's edges), Proximity Guides (both edges of each character's width), Angular Guides (a glyph's slanted strokes, and every guide of rotated type) and the glyphs' anchor points; {} reads them → the options",
|
||||
always,
|
||||
glyph_snap_options
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
fn glyph_snap_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.prefs.glyph_snap = s.prefs.glyph_snap.merged(p).map_err(|e| bad("view.snapToGlyph.options", e))?;
|
||||
Ok(json!(s.prefs.glyph_snap))
|
||||
}
|
||||
|
||||
fn transparency_grid(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let st = s.doc_mut()?;
|
||||
st.transparency_grid = p.get("on").and_then(Value::as_bool).unwrap_or(!st.transparency_grid);
|
||||
|
||||
@@ -77,6 +77,10 @@ pub(crate) const SELECTS_GIVEN_IDS: &[&str] = &[
|
||||
"object.clippingMask.release",
|
||||
"object.compoundPath.make",
|
||||
"object.compoundPath.release",
|
||||
"object.compoundShape.expand",
|
||||
"object.compoundShape.make",
|
||||
"object.compoundShape.release",
|
||||
"object.compoundShape.setMode",
|
||||
"object.group",
|
||||
"object.hide",
|
||||
"object.lock",
|
||||
|
||||
@@ -27,6 +27,12 @@ pub struct Prefs {
|
||||
pub select_same_tint_percent: bool,
|
||||
pub show_home_screen: bool,
|
||||
pub use_preview_bounds: bool,
|
||||
/// Align panel menu › Align to Glyph Bounds › Point Text: Align and Distribute measure point
|
||||
/// type by the ink of its glyphs instead of its em box.
|
||||
pub align_glyph_bounds_point: bool,
|
||||
/// Align panel menu › Align to Glyph Bounds › Area Text: the same for area type, instead of
|
||||
/// its frame.
|
||||
pub align_glyph_bounds_area: bool,
|
||||
pub display_print_size: bool,
|
||||
pub double_click_to_isolate: bool,
|
||||
pub transform_pattern_tiles: bool,
|
||||
@@ -197,6 +203,9 @@ pub struct Prefs {
|
||||
/// Pathfinder panel › Pathfinder Options (`object.pathfinder.options`; a preference group, see
|
||||
/// [`cmd::prefscmds::PREF_GROUPS`]).
|
||||
pub pathfinder: PathfinderOptions,
|
||||
/// Character panel › Show Snap to Glyph Options: which guides View › Snap to Glyph gives
|
||||
/// (`view.snapToGlyph.options`; a preference group, see [`cmd::prefscmds::PREF_GROUPS`]).
|
||||
pub glyph_snap: vectorcraft_tools::GlyphSnap,
|
||||
/// Edit → Transparency Flattener Presets: the user's presets (the built-in ones aren't stored).
|
||||
/// Not a `prefs.set` key or group (resetting the preferences keeps them): `flattener.presets.*`
|
||||
/// edit it.
|
||||
@@ -317,6 +326,8 @@ impl Default for Prefs {
|
||||
select_same_tint_percent: false,
|
||||
show_home_screen: true,
|
||||
use_preview_bounds: false,
|
||||
align_glyph_bounds_point: false,
|
||||
align_glyph_bounds_area: false,
|
||||
display_print_size: false,
|
||||
double_click_to_isolate: true,
|
||||
transform_pattern_tiles: false,
|
||||
@@ -434,6 +445,7 @@ impl Default for Prefs {
|
||||
},
|
||||
eyedropper: Default::default(),
|
||||
pathfinder: Default::default(),
|
||||
glyph_snap: Default::default(),
|
||||
flattener_presets: vec![],
|
||||
trace_presets: vec![],
|
||||
width_profiles: vec![],
|
||||
|
||||
@@ -26,9 +26,11 @@ mod cmdsplit;
|
||||
mod cmykflatten;
|
||||
mod colorguide;
|
||||
mod colorguidelib;
|
||||
mod colorize;
|
||||
pub(super) mod colormgmt;
|
||||
mod colorthemes;
|
||||
mod colourfonts;
|
||||
mod compound_shape;
|
||||
mod compoundpaint;
|
||||
mod constrain_new;
|
||||
mod constrain_tools;
|
||||
@@ -57,6 +59,7 @@ mod fontfiles;
|
||||
mod fontlist;
|
||||
mod freeform;
|
||||
mod globaledit;
|
||||
mod glyphbounds;
|
||||
mod gradient;
|
||||
mod gradpanel;
|
||||
mod gradspan;
|
||||
|
||||
@@ -2768,6 +2768,21 @@ fn a_trace_run_hands_its_trace_to_the_command() {
|
||||
assert!((bb.center().x - 160.0).abs() < 1.5, "traced where the image is now: {bb:?}");
|
||||
}
|
||||
|
||||
/// A Document Library trace made away from its command no longer applies once the library's
|
||||
/// colours change: the settings' JSON leaves them out (#4605 review).
|
||||
#[test]
|
||||
fn a_trace_run_needs_the_library_colours_it_traced_with() {
|
||||
let mut s = session();
|
||||
image_doc(&mut s);
|
||||
let p = json!({"preset": "6 Colors", "params": {"palette": "documentLibrary"}});
|
||||
let run = cmd::TraceRun::prepare(&s, "imageTrace.make", &p).unwrap();
|
||||
assert!(run.current(&s));
|
||||
let swatch = |w: &&vectorcraft_color::Swatch| matches!(w.paint, Paint::Solid { .. }) && !w.name.starts_with('[');
|
||||
let name = s.doc().unwrap().doc.swatches_iter().find(swatch).map(|w| w.name.clone()).unwrap();
|
||||
s.execute("swatch.edit", &json!({"name": name, "color": "#123456"})).unwrap();
|
||||
assert!(!run.current(&s), "{name} changed");
|
||||
}
|
||||
|
||||
/// Shapes: the disc of the test image comes out as a live ellipse where the image lies, the same
|
||||
/// circle as its traced path; without the option it is a plain path.
|
||||
#[test]
|
||||
|
||||
@@ -69,7 +69,7 @@ fn a_clipping_paths_fill_and_stroke_show_in_render_svg_and_pdf() {
|
||||
assert_eq!(rgb(&doc, 120), [255, 255, 255]);
|
||||
assert_eq!(rgb(&doc, 45), [255, 255, 255]);
|
||||
let svg = vectorcraft_svg::export(&doc, &Default::default());
|
||||
assert_eq!(svg.matches("<path").count(), 2, "the clip region and the red art: {svg}");
|
||||
assert_eq!(vectorcraft_testkit::svg_shapes(&svg), 2, "the clip region and the red art: {svg}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -48,6 +48,19 @@ fn every_guide_colour_is_a_library_member() {
|
||||
assert!(s.execute("color.harmony", &json!({"color": "#3a7bd5", "rule": "triad", "limitTo": "document"})).is_err(), "no document");
|
||||
}
|
||||
|
||||
/// A `limitTo` that is not a string names no library: `color.harmony` refuses it with the error it
|
||||
/// gives for a name it does not know, and reads a null as no limit.
|
||||
#[test]
|
||||
fn a_limit_that_is_not_a_string_names_no_library() {
|
||||
let mut s = Session::new();
|
||||
for (limit, shown) in [(json!(5), "`5`"), (json!(true), "`true`"), (json!(["web-safe-216"]), "`[\"web-safe-216\"]`")] {
|
||||
let e = s.execute("color.harmony", &json!({"color": "#3a7bd5", "rule": "triad", "limitTo": limit})).unwrap_err().to_string();
|
||||
assert!(e.contains(&format!("no swatch library {shown}")), "{limit}: {e}");
|
||||
}
|
||||
let free = s.execute("color.harmony", &json!({"color": "#3a7bd5", "rule": "triad", "limitTo": null})).unwrap();
|
||||
assert_eq!(free["colors"][0], "#3a7bd5");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_swatches_limit_the_guide_and_recolor() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
//! A fill color colorizes grayscale and 1-bit images (`paint.setFill` on the image).
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::{ImageBlob, Node, NodeKind};
|
||||
|
||||
use crate::*;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 100, "k": 0}, "spot": true})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn png(img: image::DynamicImage) -> ImageBlob {
|
||||
let mut out = Vec::new();
|
||||
img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
|
||||
ImageBlob::png(out)
|
||||
}
|
||||
|
||||
/// A gray 2 × 1 image (black, white), with an alpha channel when `alpha`.
|
||||
fn gray(alpha: bool) -> ImageBlob {
|
||||
if alpha {
|
||||
png(image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(2, 1, vec![0, 255, 255, 128]).unwrap()))
|
||||
} else {
|
||||
png(image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(2, 1, vec![0, 255]).unwrap()))
|
||||
}
|
||||
}
|
||||
|
||||
/// A selected embedded 2 × 1 image of `blob`.
|
||||
fn image(s: &mut Session, key: &str, blob: ImageBlob) -> NodeId {
|
||||
let key = key.to_string();
|
||||
s.edit("Place", |d, sel| {
|
||||
d.images.insert(key.clone(), blob);
|
||||
let id = d.alloc_id();
|
||||
let im = vectorcraft_doc::ImageObject {
|
||||
key,
|
||||
width: 2,
|
||||
height: 1,
|
||||
xf: Default::default(),
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
d.insert(d.default_layer(), 0, Node::new(id, NodeKind::Image(Box::new(im))))?;
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn colorize(s: &Session, id: NodeId) -> Option<Paint> {
|
||||
s.doc().unwrap().doc.node(id).unwrap().extras().colorize.as_deref().cloned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fill_color_colorizes_a_gray_image_and_none_takes_it_off() {
|
||||
let mut s = session();
|
||||
let id = image(&mut s, "gray", gray(false));
|
||||
s.execute("paint.setFill", &json!({"swatch": "Ink", "tint": 40})).unwrap();
|
||||
let Some(Paint::Solid { swatch, tint, .. }) = colorize(&s, id) else { panic!("not colorized: {:?}", colorize(&s, id)) };
|
||||
assert_eq!((swatch.as_deref(), tint), (Some("Ink"), 0.4));
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
assert!(n.appearance.items.is_empty(), "no fill item over the image");
|
||||
assert_eq!(s.proxy_paints().0, colorize(&s, id).unwrap(), "the Fill proxy shows the color");
|
||||
// A process color too.
|
||||
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
|
||||
assert!(matches!(colorize(&s, id), Some(Paint::Solid { swatch: None, .. })));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(matches!(colorize(&s, id), Some(Paint::Solid { swatch: Some(_), .. })), "undo restores the spot color");
|
||||
s.execute("paint.setFill", &json!({"none": true})).unwrap();
|
||||
assert_eq!(colorize(&s, id), None);
|
||||
// `none` takes the color off after an edit of the pixels leaves the image in color.
|
||||
s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap();
|
||||
s.execute("edit.colors.invert", &json!({"includeImages": true})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let NodeKind::Image(im) = &d.node(id).unwrap().kind else { panic!() };
|
||||
assert_eq!(d.image_blob(im).and_then(|b| b.gray_source()), None, "the pixels are no longer gray");
|
||||
s.execute("paint.setFill", &json!({"none": true})).unwrap();
|
||||
assert_eq!(colorize(&s, id), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_with_alpha_takes_a_spot_color_black_or_white_only() {
|
||||
let mut s = session();
|
||||
let id = image(&mut s, "alpha", gray(true));
|
||||
let e = s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap_err().to_string();
|
||||
assert!(e.contains("a process color can't colorize a grayscale image with transparency"), "{e}");
|
||||
assert_eq!(colorize(&s, id), None);
|
||||
s.execute("paint.setFill", &json!({"color": {"gray": 100}})).unwrap();
|
||||
assert!(colorize(&s, id).is_some(), "black");
|
||||
s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap();
|
||||
assert!(matches!(colorize(&s, id), Some(Paint::Solid { swatch: Some(_), .. })));
|
||||
}
|
||||
|
||||
/// A swatch edit that would leave an image with alpha in a process color is refused, as
|
||||
/// `paint.setFill` refuses one.
|
||||
#[test]
|
||||
fn swatch_edits_keep_an_image_with_alpha_out_of_process_colors() {
|
||||
let mut s = session();
|
||||
s.execute("swatch.new", &json!({"name": "Other", "color": {"c": 100, "m": 0, "y": 0, "k": 0}, "global": true})).unwrap();
|
||||
let id = image(&mut s, "alpha", gray(true));
|
||||
s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap();
|
||||
let before = colorize(&s, id);
|
||||
let message = "a process color can't colorize a grayscale image with transparency";
|
||||
for (cmd, p) in [
|
||||
("swatch.edit", json!({"name": "Ink", "spot": false})),
|
||||
("swatch.edit", json!({"name": "Ink", "spot": false, "global": false})),
|
||||
("swatch.setSpot", json!({"name": "Ink", "spot": false})),
|
||||
("swatch.delete", json!({"names": ["Ink"]})),
|
||||
("swatch.merge", json!({"names": ["Other", "Ink"]})),
|
||||
("swatch.resetDefaults", json!({"replace": true})),
|
||||
] {
|
||||
let e = s.execute(cmd, &p).unwrap_err().to_string();
|
||||
assert!(e.contains(message), "{cmd} {p}: {e}");
|
||||
assert_eq!(colorize(&s, id), before, "{cmd} {p} left the image as it was");
|
||||
}
|
||||
// A new color for the spot swatch keeps it a spot color.
|
||||
s.execute("swatch.edit", &json!({"name": "Ink", "color": {"c": 100, "m": 0, "y": 0, "k": 0}})).unwrap();
|
||||
// An image without alpha takes a process color.
|
||||
let mut s = session();
|
||||
let id = image(&mut s, "gray", gray(false));
|
||||
s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap();
|
||||
s.execute("swatch.edit", &json!({"name": "Ink", "spot": false})).unwrap();
|
||||
assert!(colorize(&s, id).is_some());
|
||||
}
|
||||
|
||||
/// With the Appearance panel's active item on a fill of the image, the paint goes to that fill.
|
||||
#[test]
|
||||
fn the_active_fill_item_takes_the_paint_instead() {
|
||||
let mut s = session();
|
||||
let id = image(&mut s, "alpha", gray(true));
|
||||
s.execute("appearance.addFill", &json!({})).unwrap();
|
||||
let index = s.doc().unwrap().doc.node(id).unwrap().appearance.items.iter().position(|it| it.is_fill()).unwrap();
|
||||
s.execute("appearance.setActiveItem", &json!({"index": index})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
|
||||
assert_eq!(colorize(&s, id), None);
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
let blue = vectorcraft_color::Color::rgb(0.0, 0.0, 1.0);
|
||||
assert_eq!(n.appearance.fill().and_then(|f| f.paint.color()), Some(blue), "the fill item took the color");
|
||||
}
|
||||
|
||||
/// `none` on a gray image without a color takes the paint off its fill item.
|
||||
#[test]
|
||||
fn none_on_a_gray_image_without_a_color_clears_its_fill_item() {
|
||||
let mut s = session();
|
||||
let id = image(&mut s, "gray", gray(false));
|
||||
s.execute("appearance.addFill", &json!({})).unwrap();
|
||||
let index = s.doc().unwrap().doc.node(id).unwrap().appearance.items.iter().position(|it| it.is_fill()).unwrap();
|
||||
s.execute("appearance.setActiveItem", &json!({"index": index})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
|
||||
s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"none": true})).unwrap();
|
||||
assert_eq!(colorize(&s, id), None);
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
assert_eq!(n.appearance.fill().map(|f| &f.paint), Some(&Paint::None), "the fill item's paint is none");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_color_image_takes_a_fill_item_as_before() {
|
||||
let mut s = session();
|
||||
let rgb = png(image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(2, 1, vec![255, 0, 0, 0, 0, 255]).unwrap()));
|
||||
let id = image(&mut s, "rgb", rgb);
|
||||
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
|
||||
assert_eq!(colorize(&s, id), None);
|
||||
assert!(s.doc().unwrap().doc.node(id).unwrap().appearance.fill().is_some(), "a fill item, as before");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colorized_images_save_and_open_with_their_color() {
|
||||
let mut s = session();
|
||||
let id = image(&mut s, "gray", gray(false));
|
||||
s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let back = vectorcraft_format::load(&vectorcraft_format::save(d, false)).unwrap();
|
||||
assert_eq!(&back.layers, &d.layers);
|
||||
assert!(back.node(id).unwrap().extras().colorize.is_some());
|
||||
// Swatch edits reach it as they reach fills.
|
||||
s.execute("swatch.edit", &json!({"name": "Ink", "color": {"c": 100, "m": 0, "y": 0, "k": 0}})).unwrap();
|
||||
let Some(Paint::Solid { color, .. }) = colorize(&s, id) else { panic!() };
|
||||
assert_eq!(color, vectorcraft_color::Color::Cmyk { c: 1.0, m: 0.0, y: 0.0, k: 0.0 });
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
//! Pathfinder panel › compound shapes (`object.compoundShape.*`): Make Compound Shape in each
|
||||
//! shape mode, a member's mode, Release, Expand, Undo, saving and exporting.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Color;
|
||||
use vectorcraft_doc::{Node, ShapeMode};
|
||||
use vectorcraft_render::effects;
|
||||
|
||||
use crate::*;
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
s.execute(id, &p).unwrap()
|
||||
}
|
||||
|
||||
fn node(s: &Session, id: NodeId) -> Node {
|
||||
s.doc().unwrap().doc.node(id).cloned().unwrap()
|
||||
}
|
||||
|
||||
fn area(path: &vectorcraft_geom::PathData) -> f64 {
|
||||
vectorcraft_pathops::area(path, vectorcraft_geom::FillRule::NonZero).abs()
|
||||
}
|
||||
|
||||
/// The area a path or compound path fills.
|
||||
fn node_area(n: &Node) -> f64 {
|
||||
area(&crate::cmd::pathops::node_path(n).unwrap().0)
|
||||
}
|
||||
|
||||
fn square(s: &mut Session, x: f64, color: &str) -> NodeId {
|
||||
let id = NodeId(run(s, "shape.rectangle", json!({"x": x, "y": 0, "width": 100, "height": 100}))["id"].as_u64().unwrap());
|
||||
run(s, "paint.setFill", json!({"color": color}));
|
||||
id
|
||||
}
|
||||
|
||||
/// A red square (0–100) behind a blue one (50–150), both 100 high and selected → (session, back, front).
|
||||
fn two_squares() -> (Session, NodeId, NodeId) {
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "file.new", json!({"width": 400, "height": 300}));
|
||||
let back = square(&mut s, 0.0, "#ff0000");
|
||||
let front = square(&mut s, 50.0, "#0000ff");
|
||||
run(&mut s, "select.set", json!({"ids": [back.0, front.0]}));
|
||||
(s, back, front)
|
||||
}
|
||||
|
||||
fn selected(s: &Session) -> Vec<NodeId> {
|
||||
s.doc().unwrap().selection.objects.clone()
|
||||
}
|
||||
|
||||
/// Make Compound Shape (Alt-clicking a Shape Mode gives its mode) keeps both squares as members in
|
||||
/// the mode, takes the paint of the topmost member not subtracting, draws the area the modes make,
|
||||
/// and Expand turns it into that area as one path; Undo brings each step back.
|
||||
#[test]
|
||||
fn make_and_expand_each_shape_mode() {
|
||||
for (mode, want, fill, kind) in [
|
||||
("add", 15_000.0, Color::rgb(0.0, 0.0, 1.0), "Path"),
|
||||
("subtract", 5_000.0, Color::rgb(1.0, 0.0, 0.0), "Path"),
|
||||
("intersect", 5_000.0, Color::rgb(0.0, 0.0, 1.0), "Path"),
|
||||
("exclude", 10_000.0, Color::rgb(0.0, 0.0, 1.0), "Compound Path"),
|
||||
] {
|
||||
let (mut s, back, front) = two_squares();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let id = NodeId(run(&mut s, "object.compoundShape.make", json!({"mode": mode}))["id"].as_u64().unwrap());
|
||||
assert_eq!(selected(&s), vec![id]);
|
||||
let shape = node(&s, id);
|
||||
assert!(shape.is_compound_shape(), "{mode}");
|
||||
assert_eq!(shape.kind_label(), "Compound Shape");
|
||||
let members: Vec<NodeId> = shape.children().unwrap().iter().map(|m| m.id).collect();
|
||||
assert_eq!(members, vec![back, front], "the members, in their stacking order");
|
||||
assert!(shape.children().unwrap().iter().all(|m| m.extras().shape_mode.name() == mode));
|
||||
assert_eq!(shape.appearance.fill_paint().color(), Some(fill), "{mode}");
|
||||
let drawn = effects::compound_shape_area(&shape, None).unwrap();
|
||||
assert!((area(&drawn) - want).abs() < 0.5, "{mode}: {}", area(&drawn));
|
||||
// Expand: the path, or compound path, of the area, painted as the compound shape.
|
||||
let made = run(&mut s, "object.compoundShape.expand", json!({}));
|
||||
let path = NodeId(made["ids"][0].as_u64().unwrap());
|
||||
let n = node(&s, path);
|
||||
assert_eq!(n.kind_label(), kind, "{mode}");
|
||||
assert!((node_area(&n) - want).abs() < 0.5, "{mode}");
|
||||
assert_eq!(n.appearance.fill_paint().color(), Some(fill));
|
||||
assert_eq!(selected(&s), vec![path]);
|
||||
assert!(s.doc().unwrap().doc.node(back).is_none() && s.doc().unwrap().doc.node(id).is_none());
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert!(node(&s, id).is_compound_shape());
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(s.doc().unwrap().doc.layers, before.layers, "{mode}: Undo leaves the squares as they were");
|
||||
}
|
||||
}
|
||||
|
||||
/// Make Compound Shape from the panel menu gives every member Add; Release gives the members back
|
||||
/// as they were, selected, in one undo step.
|
||||
#[test]
|
||||
fn release_returns_the_members_as_they_were() {
|
||||
let (mut s, back, front) = two_squares();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let id = NodeId(run(&mut s, "object.compoundShape.make", json!({}))["id"].as_u64().unwrap());
|
||||
assert!(node(&s, id).children().unwrap().iter().all(|m| m.extras().shape_mode == ShapeMode::Add));
|
||||
run(&mut s, "object.compoundShape.setMode", json!({"mode": "subtract", "ids": [front.0]}));
|
||||
run(&mut s, "select.set", json!({"ids": [id.0]}));
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let out = run(&mut s, "object.compoundShape.release", json!({}));
|
||||
assert_eq!(out["ids"], json!([back.0, front.0]));
|
||||
assert_eq!(selected(&s), vec![back, front]);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
assert_eq!(s.doc().unwrap().doc.layers, before.layers, "the members' paint and place, no shape modes");
|
||||
// Nothing selected is in a compound shape: Release and Expand are off.
|
||||
assert!(s.execute("object.compoundShape.release", &json!({})).is_err());
|
||||
assert!(s.execute("object.compoundShape.expand", &json!({})).is_err());
|
||||
assert!(s.execute("object.compoundShape.setMode", &json!({"mode": "add"})).is_err());
|
||||
}
|
||||
|
||||
/// A member selected (Direct Selection) takes the mode of the Shape Mode clicked; the area follows,
|
||||
/// and Undo puts the mode back. Release and Expand act on the compound shape it is in.
|
||||
#[test]
|
||||
fn a_selected_member_takes_a_shape_mode() {
|
||||
let (mut s, _, front) = two_squares();
|
||||
let id = NodeId(run(&mut s, "object.compoundShape.make", json!({}))["id"].as_u64().unwrap());
|
||||
run(&mut s, "select.set", json!({"ids": [front.0]}));
|
||||
assert_eq!(cmd::selected_member_modes(&s), vec![ShapeMode::Add]);
|
||||
run(&mut s, "object.compoundShape.setMode", json!({"mode": "intersect"}));
|
||||
assert_eq!(cmd::selected_member_modes(&s), vec![ShapeMode::Intersect]);
|
||||
assert!((area(&effects::compound_shape_area(&node(&s, id), None).unwrap()) - 5_000.0).abs() < 0.5);
|
||||
// The same mode again is no edit.
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
run(&mut s, "object.compoundShape.setMode", json!({"mode": "intersect"}));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
assert!(s.execute("object.compoundShape.setMode", &json!({"mode": "divide"})).is_err());
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(node(&s, front).extras().shape_mode, ShapeMode::Add);
|
||||
run(&mut s, "select.set", json!({"ids": [front.0]}));
|
||||
let made = run(&mut s, "object.compoundShape.expand", json!({}));
|
||||
assert!((node_area(&node(&s, NodeId(made["ids"][0].as_u64().unwrap()))) - 15_000.0).abs() < 0.5);
|
||||
}
|
||||
|
||||
/// A compound shape holds its paint: a fill given to it (or to a member) paints the compound shape,
|
||||
/// whose members keep theirs.
|
||||
#[test]
|
||||
fn paint_goes_to_the_compound_shape() {
|
||||
let (mut s, back, front) = two_squares();
|
||||
let id = NodeId(run(&mut s, "object.compoundShape.make", json!({}))["id"].as_u64().unwrap());
|
||||
let out = run(&mut s, "paint.setFill", json!({"color": "#00ff00"}));
|
||||
assert_eq!(out["objects"], 1);
|
||||
assert_eq!(node(&s, id).appearance.fill_paint().color(), Some(Color::rgb(0.0, 1.0, 0.0)));
|
||||
run(&mut s, "paint.setFill", json!({"color": "#ffff00", "ids": [front.0]}));
|
||||
assert_eq!(node(&s, id).appearance.fill_paint().color(), Some(Color::rgb(1.0, 1.0, 0.0)));
|
||||
assert_eq!(node(&s, back).appearance.fill_paint().color(), Some(Color::rgb(1.0, 0.0, 0.0)));
|
||||
assert_eq!(node(&s, front).appearance.fill_paint().color(), Some(Color::rgb(0.0, 0.0, 1.0)));
|
||||
}
|
||||
|
||||
/// Make Compound Shape needs two or more objects it can take.
|
||||
#[test]
|
||||
fn make_needs_two_objects_it_can_take() {
|
||||
let (mut s, back, _) = two_squares();
|
||||
run(&mut s, "select.set", json!({"ids": [back.0]}));
|
||||
assert!(s.execute("object.compoundShape.make", &json!({})).is_err());
|
||||
let (mut s, back, front) = two_squares();
|
||||
assert!(s.execute("object.compoundShape.make", &json!({"mode": "divide"})).is_err());
|
||||
assert_eq!(selected(&s), vec![back, front], "nothing changed");
|
||||
}
|
||||
|
||||
/// Saved and opened again, a compound shape keeps its members and their modes; a mode a file names
|
||||
/// that isn't one reads as Add.
|
||||
#[test]
|
||||
fn compound_shapes_survive_a_save() {
|
||||
let (mut s, _, front) = two_squares();
|
||||
let id = NodeId(run(&mut s, "object.compoundShape.make", json!({"mode": "subtract"}))["id"].as_u64().unwrap());
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let bytes = vectorcraft_format::save(&doc, false);
|
||||
let back = vectorcraft_format::load(&bytes).unwrap();
|
||||
assert_eq!(back.node(id), doc.node(id));
|
||||
assert!(back.node(id).unwrap().is_compound_shape());
|
||||
assert_eq!(back.node(front).unwrap().extras().shape_mode, ShapeMode::Subtract);
|
||||
let text = String::from_utf8(bytes).unwrap().replace("\"shape_mode\":\"subtract\"", "\"shape_mode\":\"divide\"");
|
||||
let odd = vectorcraft_format::load(text.as_bytes()).unwrap();
|
||||
assert_eq!(odd.node(front).unwrap().extras().shape_mode, ShapeMode::Add);
|
||||
}
|
||||
|
||||
/// SVG export draws the area, painted as the compound shape, not the members.
|
||||
#[test]
|
||||
fn svg_export_draws_the_area() {
|
||||
let (mut s, _, _) = two_squares();
|
||||
run(&mut s, "object.compoundShape.make", json!({"mode": "subtract"}));
|
||||
let svg = vectorcraft_svg::export(&s.doc().unwrap().doc, &Default::default());
|
||||
assert!(svg.contains("#ff0000"), "the back square's red paints the area");
|
||||
assert!(!svg.contains("#0000ff"), "the front square isn't drawn: {svg}");
|
||||
}
|
||||
|
||||
/// The Shape Modes and Pathfinders take a compound shape as the area it draws.
|
||||
#[test]
|
||||
fn pathfinder_operations_take_the_area() {
|
||||
let (mut s, _, _) = two_squares();
|
||||
let id = NodeId(run(&mut s, "object.compoundShape.make", json!({"mode": "subtract"}))["id"].as_u64().unwrap());
|
||||
let r = NodeId(run(&mut s, "shape.rectangle", json!({"x": 200, "y": 0, "width": 50, "height": 100}))["id"].as_u64().unwrap());
|
||||
run(&mut s, "select.set", json!({"ids": [id.0, r.0]}));
|
||||
let out = run(&mut s, "object.pathfinder.unite", json!({}));
|
||||
let n = node(&s, NodeId(out["ids"][0].as_u64().unwrap()));
|
||||
assert!((node_area(&n) - 10_000.0).abs() < 0.5, "the 50 × 100 area and the 50 × 100 rectangle: {}", node_area(&n));
|
||||
}
|
||||
@@ -336,7 +336,7 @@ fn type_in_a_group_with_a_geometry_effect_exports_and_expands_with_its_look() {
|
||||
run(&mut s, "select.set", json!({"ids": [t.0]}));
|
||||
run(&mut s, "object.hide", json!({}));
|
||||
let hidden = svg(&s);
|
||||
assert_eq!(hidden.matches("<path").count() + 1, shown.matches("<path").count(), "{hidden}");
|
||||
assert_eq!(vectorcraft_testkit::svg_shapes(&hidden) + 1, vectorcraft_testkit::svg_shapes(&shown), "{hidden}");
|
||||
// Expand Appearance keeps the type's opacity and visibility on its outlines.
|
||||
run(&mut s, "select.set", json!({"ids": [g.0]}));
|
||||
run(&mut s, "effect.expandAppearance", json!({}));
|
||||
@@ -355,5 +355,5 @@ fn hidden_type_with_a_geometry_effect_is_left_out_of_svg_export() {
|
||||
run(&mut s, "select.set", json!({"ids": [t.0]}));
|
||||
run(&mut s, "object.hide", json!({}));
|
||||
let hidden = svg(&s);
|
||||
assert_eq!((shown.matches("<path").count(), hidden.matches("<path").count()), (1, 0), "{hidden}");
|
||||
assert_eq!((vectorcraft_testkit::svg_shapes(&shown), vectorcraft_testkit::svg_shapes(&hidden)), (1, 0), "{hidden}");
|
||||
}
|
||||
@@ -473,6 +473,65 @@ fn blob_brush_merges_only_with_the_selection_and_keep_selected_off_deselects() {
|
||||
assert!(s.doc().unwrap().doc.node(all).is_some() && s.doc().unwrap().doc.node(other).is_some());
|
||||
}
|
||||
|
||||
/// Blob Brush Tool Options' Size set to Pressure (#4590): the brush is Size − Variation wide where
|
||||
/// the pen pressed lightest and Size + Variation where it pressed hardest. A stroke without
|
||||
/// pressure keeps the Size, and Fixed leaves the pressure out.
|
||||
#[test]
|
||||
fn blob_brush_size_follows_the_pen_pressure() {
|
||||
let mut s = session();
|
||||
let inside = |s: &Session, id: NodeId, x: f64, y: f64| {
|
||||
vectorcraft_geom::hit::fill_contains(&path(s, id).to_bezpath(), FillRule::NonZero, Point::new(x, y))
|
||||
};
|
||||
let blob = |s: &mut Session, p: serde_json::Value| NodeId(s.execute("path.blob", &p).unwrap()["id"].as_u64().unwrap());
|
||||
// Lightest at the left end, hardest at the right: about 2 pt wide to 18 pt wide.
|
||||
let pressed = |y: f64| (0..=20).map(|i| json!([100.0 + f64::from(i) * 10.0, y, f64::from(i) / 20.0])).collect::<Vec<_>>();
|
||||
let a = blob(&mut s, json!({"points": pressed(100.0), "size": 10, "sizeMode": "pressure", "sizeVariation": 8}));
|
||||
assert!(inside(&s, a, 290.0, 107.0) && !inside(&s, a, 110.0, 103.0), "wide where pressed hard, thin where light");
|
||||
// Fixed, and Pressure on a stroke without pressure: 10 pt wide all along.
|
||||
let fixed = blob(&mut s, json!({"points": pressed(300.0), "size": 10, "sizeMode": "fixed", "sizeVariation": 8}));
|
||||
let mouse = blob(&mut s, json!({"points": [[100, 500], [300, 500]], "size": 10, "sizeMode": "pressure", "sizeVariation": 8}));
|
||||
for (id, y) in [(fixed, 300.0), (mouse, 500.0)] {
|
||||
assert!(inside(&s, id, 110.0, y + 3.0) && !inside(&s, id, 290.0, y + 7.0), "10 pt at y {y}");
|
||||
}
|
||||
let err = s.execute("path.blob", &json!({"points": [[0, 0], [10, 0]], "sizeMode": "random"})).unwrap_err();
|
||||
assert!(err.to_string().contains("sizeMode"), "{err}");
|
||||
// The tool records the pen while its Size varies with Pressure.
|
||||
let v = view();
|
||||
s.select_tool("blobBrush", v).unwrap();
|
||||
s.set_tool_option("sizeMode", &json!("pressure"));
|
||||
s.set_tool_option("sizeVariation", &json!(8));
|
||||
assert_eq!((s.tool_options()["sizeMode"].clone(), s.tool_options()["sizeVariation"].clone()), (json!("pressure"), json!(8.0)));
|
||||
let ev = |kind, i: i32| PointerEvent { pressure: i as f32 / 20.0, ..PointerEvent::new(kind, 100.0 + f64::from(i) * 10.0, 700.0) };
|
||||
s.pointer(&ev(PointerKind::Down, 0), v).unwrap();
|
||||
for i in 1..20 {
|
||||
s.pointer(&ev(PointerKind::Drag, i), v).unwrap();
|
||||
}
|
||||
s.pointer(&ev(PointerKind::Up, 20), v).unwrap();
|
||||
let (drawn, _) = paths(&s).into_iter().find(|(_, p)| p.control_bounds().is_some_and(|b| b.y0 > 650.0)).unwrap();
|
||||
assert!(inside(&s, drawn, 290.0, 707.0) && !inside(&s, drawn, 110.0, 703.0), "the tool's stroke follows the pen");
|
||||
}
|
||||
|
||||
/// Eraser Tool Options' Size set to Pressure (#3961): the tip is Size − Variation across where the
|
||||
/// pen pressed lightest and Size + Variation where it pressed hardest; Fixed erases at the Size.
|
||||
#[test]
|
||||
fn eraser_size_follows_the_pen_pressure() {
|
||||
let pressed = |y: f64| (0..=20).map(|i| json!([100.0 + f64::from(i) * 10.0, y, f64::from(i) / 20.0])).collect::<Vec<_>>();
|
||||
// (mode, erased 3 pt off the stroke at the light end, erased 7 pt off it at the hard end).
|
||||
for (mode, light, hard) in [("pressure", false, true), ("fixed", true, false)] {
|
||||
let mut s = session();
|
||||
rect(&mut s, 0.0, 0.0, 400.0, 200.0);
|
||||
s.execute("path.eraseRegion", &json!({"points": pressed(100.0), "size": 10, "sizeMode": mode, "sizeVariation": 8})).unwrap();
|
||||
let filled = |x: f64, y: f64| {
|
||||
paths(&s).iter().any(|(_, pd)| vectorcraft_geom::hit::fill_contains(&pd.to_bezpath(), FillRule::NonZero, Point::new(x, y)))
|
||||
};
|
||||
assert_eq!((!filled(110.0, 103.0), !filled(290.0, 107.0)), (light, hard), "{mode}");
|
||||
assert!(!filled(200.0, 100.0) && filled(110.0, 150.0), "{mode}: the stroke is erased, the rest stays");
|
||||
}
|
||||
let mut s = session();
|
||||
let err = s.execute("path.eraseRegion", &json!({"points": [[0, 0], [10, 0]], "sizeMode": 5})).unwrap_err();
|
||||
assert!(err.to_string().contains("sizeMode"), "{err}");
|
||||
}
|
||||
|
||||
/// A Blob Brush stroke merges with the topmost matching path it touches and with the touched
|
||||
/// matching paths next to it in stacking order in the same group or layer; matching paths in other
|
||||
/// layers or groups, or below an object of another kind, are left alone.
|
||||
@@ -2672,6 +2731,88 @@ fn join_takes_the_paths_and_the_ends_to_join() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Average & Join (Cmd+Alt+Shift+J): the two ends meet at their midpoint and become one anchor of
|
||||
/// one path, a corner or a smooth point as asked, in one undo step; from two selected paths (their
|
||||
/// nearest ends) or from two direct-selected ends (the ends picked, not the nearest).
|
||||
#[test]
|
||||
fn average_join_meets_at_the_midpoint_as_a_corner_or_smooth_point() {
|
||||
let pts = |s: &Session, id: NodeId| path(s, id).subpaths[0].anchors.iter().map(|x| (x.p.x, x.p.y)).collect::<Vec<_>>();
|
||||
for (to, picks) in [("corner", false), ("smooth", false), ("corner", true), ("smooth", true)] {
|
||||
let mut s = session();
|
||||
let a = line(&mut s, 0.0, 0.0, 100.0, 0.0);
|
||||
let b = line(&mut s, 110.0, 40.0, 200.0, 40.0);
|
||||
let want = if picks {
|
||||
// a's first and b's last, the far ends.
|
||||
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0]], "mode": "set"})).unwrap();
|
||||
s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 1]], "mode": "add"})).unwrap();
|
||||
[(100.0, 0.0), (100.0, 20.0), (110.0, 40.0)]
|
||||
} else {
|
||||
s.select(|_, sel| sel.set([a, b])).unwrap();
|
||||
[(0.0, 0.0), (105.0, 20.0), (200.0, 40.0)]
|
||||
};
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("path.averageJoin", &json!({ "to": to })).unwrap();
|
||||
assert_eq!(pts(&s, a), want, "{to} picks:{picks}");
|
||||
assert!(s.doc().unwrap().doc.node(b).is_none(), "b was joined into a");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [a]);
|
||||
let joined = path(&s, a).subpaths[0].anchors[1];
|
||||
let (din, dout) = (joined.h_in - joined.p, joined.h_out - joined.p);
|
||||
if to == "corner" {
|
||||
assert!(din.hypot() < 1e-9 && dout.hypot() < 1e-9, "a corner has no handles: {joined:?}");
|
||||
} else {
|
||||
assert!(din.hypot() > 1.0 && dout.hypot() > 1.0 && din.cross(dout).abs() < 1e-6 && din.dot(dout) < 0.0, "smooth: {joined:?}");
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(pts(&s, a), [(0.0, 0.0), (100.0, 0.0)]);
|
||||
assert_eq!(pts(&s, b), [(110.0, 40.0), (200.0, 40.0)]);
|
||||
}
|
||||
}
|
||||
|
||||
/// Average & Join closes one open path at the midpoint of its ends, and refuses a bad `to` and a
|
||||
/// selection without two open ends to join (a closed path, three paths, one picked end, a line's
|
||||
/// two ends), leaving the document as it was; `ids` names the paths over the selection.
|
||||
#[test]
|
||||
fn average_join_closes_one_path_and_refuses_what_it_cannot_join() {
|
||||
let mut s = session();
|
||||
let v = NodeId(s.execute("path.create", &json!({"d": "M0 0 L50 100 L100 10"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.select(|_, sel| sel.set([v])).unwrap();
|
||||
s.execute("path.averageJoin", &json!({"to": "corner"})).unwrap();
|
||||
let pd = path(&s, v);
|
||||
assert!(pd.subpaths[0].closed);
|
||||
assert_eq!(pd.subpaths[0].anchors.iter().map(|x| (x.p.x, x.p.y)).collect::<Vec<_>>(), [(50.0, 5.0), (50.0, 100.0)]);
|
||||
|
||||
let mut s = session();
|
||||
let a = line(&mut s, 0.0, 0.0, 100.0, 0.0);
|
||||
let b = line(&mut s, 110.0, 0.0, 200.0, 0.0);
|
||||
let c = line(&mut s, 210.0, 0.0, 300.0, 0.0);
|
||||
let r = rect(&mut s, 0.0, 50.0, 10.0, 10.0);
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let corner = json!({"to": "corner"});
|
||||
let cases = [
|
||||
(vec![a, b], None, json!({})),
|
||||
(vec![a, b], None, json!({"to": "round"})),
|
||||
(vec![r], None, corner.clone()),
|
||||
(vec![a, b, c], None, corner.clone()),
|
||||
(vec![a], None, corner.clone()),
|
||||
(vec![r], None, json!({"to": "corner", "ids": [a.0, 999]})),
|
||||
(vec![r], None, json!({"to": "corner", "ids": [r.0, a.0]})),
|
||||
(vec![a, b], Some(json!({"id": a.0, "anchors": [[0, 0]], "mode": "set"})), corner.clone()),
|
||||
(vec![a, b], Some(json!({"id": a.0, "anchors": [[0, 0], [0, 1]], "mode": "set"})), corner.clone()),
|
||||
];
|
||||
for (picked, anchors, p) in cases {
|
||||
s.select(|_, sel| sel.set(picked.clone())).unwrap();
|
||||
if let Some(anchors) = anchors {
|
||||
s.execute("select.anchors", &anchors).unwrap();
|
||||
}
|
||||
assert!(s.execute("path.averageJoin", &p).is_err(), "{picked:?} {p}");
|
||||
assert_eq!(s.doc().unwrap().doc, before, "{picked:?} {p}: nothing changed");
|
||||
}
|
||||
s.select(|_, sel| sel.set([r])).unwrap();
|
||||
s.execute("path.averageJoin", &json!({"to": "corner", "ids": [b.0, c.0]})).unwrap();
|
||||
assert_eq!(path(&s, b).subpaths[0].anchors.iter().map(|x| (x.p.x, x.p.y)).collect::<Vec<_>>(), [(110.0, 0.0), (205.0, 0.0), (300.0, 0.0)]);
|
||||
}
|
||||
|
||||
/// `path.join {ends}` on selected paths honors the requested ends, not the nearest pair.
|
||||
#[test]
|
||||
fn join_selected_paths_honors_ends_parameter() {
|
||||
|
||||
@@ -233,6 +233,81 @@ fn a_clicked_mesh_point_takes_the_opacity() {
|
||||
assert!(mesh_opacities(&s, m).iter().all(|a| *a == 1.0));
|
||||
}
|
||||
|
||||
/// Mesh points picked together (Shift-clicks with the Mesh tool, a Direct Selection marquee) all
|
||||
/// take a solid fill colour and the Transparency panel's opacity, and only they do; the panel
|
||||
/// shows their opacity, blank when it differs; a drag of one moves them all as one undo step
|
||||
/// (#4207, #4208, #4170).
|
||||
#[test]
|
||||
fn picked_mesh_points_take_the_fill_opacity_and_drag_together() {
|
||||
let mut s = session();
|
||||
let m = rect(&mut s, json!("#ff0000"));
|
||||
s.execute("object.mesh.create", &json!({"rows": 2, "cols": 2})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [m.0]})).unwrap();
|
||||
let v = ViewInfo::default();
|
||||
let point = |s: &Session, i: usize| {
|
||||
let NodeKind::Mesh(g) = &s.doc().unwrap().doc.node(m).unwrap().kind else { panic!("not a mesh") };
|
||||
g.points[i].p
|
||||
};
|
||||
let pointer = |s: &mut Session, kind: PointerKind, q: vectorcraft_geom::Point, shift: bool| {
|
||||
let mut ev = PointerEvent::new(kind, q.x, q.y);
|
||||
ev.mods.shift = shift;
|
||||
s.pointer(&ev, v).unwrap();
|
||||
};
|
||||
let click = |s: &mut Session, i: usize, shift: bool| {
|
||||
let q = point(s, i);
|
||||
pointer(s, PointerKind::Down, q, shift);
|
||||
pointer(s, PointerKind::Up, q, shift);
|
||||
};
|
||||
let check = |s: &Session, picked: &[usize], hex: &str, opacity: f32, what: &str| {
|
||||
let (c, o) = (mesh_colors(s, m), mesh_opacities(s, m));
|
||||
for i in 0..c.len() {
|
||||
let on = picked.contains(&i);
|
||||
assert_eq!(c[i].to_hex() == hex, on, "{what}: point {i} colour {c:?}");
|
||||
assert_eq!((o[i] - opacity).abs() < 1e-6, on, "{what}: point {i} opacity {o:?}");
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().doc.node(m).unwrap().opacity, 1.0, "{what}: the object stays opaque");
|
||||
};
|
||||
// The Mesh tool: a click, then Shift-clicks add points (and a second one takes one away).
|
||||
s.select_tool("mesh", v).unwrap();
|
||||
click(&mut s, 1, false);
|
||||
for i in [4, 8, 8] {
|
||||
click(&mut s, i, true);
|
||||
}
|
||||
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("transparency.set", &json!({"opacity": 40})).unwrap();
|
||||
check(&s, &[1, 4], "#0000ff", 0.4, "mesh tool");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step for both points");
|
||||
assert_eq!(s.transparency_info().opacity, Some(40.0), "the panel shows the points' opacity");
|
||||
s.execute("object.mesh.setPointColor", &json!({"id": m.0, "index": 4, "opacity": 0.9})).unwrap();
|
||||
assert_eq!(s.transparency_info().opacity, None, "mixed: blank");
|
||||
// Direct Selection: a marquee over the top-left patch picks its four points.
|
||||
s.select_tool("directSelection", v).unwrap();
|
||||
let corner = point(&s, 0);
|
||||
pointer(&mut s, PointerKind::Down, corner - vectorcraft_geom::Vec2::new(8.0, 8.0), false);
|
||||
let far = point(&s, 4) + vectorcraft_geom::Vec2::new(5.0, 5.0);
|
||||
pointer(&mut s, PointerKind::Drag, far, false);
|
||||
pointer(&mut s, PointerKind::Up, far, false);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [m], "the marquee selects the mesh");
|
||||
s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap();
|
||||
s.execute("transparency.set", &json!({"opacity": 20})).unwrap();
|
||||
check(&s, &[0, 1, 3, 4], "#00ff00", 0.2, "marquee");
|
||||
// A drag of one picked point moves all four by the same offset, in one step.
|
||||
let before: Vec<_> = (0..9).map(|i| point(&s, i)).collect();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let d = vectorcraft_geom::Vec2::new(4.0, 6.0);
|
||||
pointer(&mut s, PointerKind::Down, before[4], false);
|
||||
pointer(&mut s, PointerKind::Drag, before[4] + d, false);
|
||||
pointer(&mut s, PointerKind::Up, before[4] + d, false);
|
||||
for (i, was) in before.iter().enumerate() {
|
||||
let want = if [0, 1, 3, 4].contains(&i) { *was + d } else { *was };
|
||||
assert!(point(&s, i).distance(want) < 1e-9, "point {i}: {:?} ≠ {want:?}", point(&s, i));
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!((0..9).map(|i| point(&s, i)).collect::<Vec<_>>(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blend_moves_a_mesh_to_the_blended_colour() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -409,7 +409,7 @@ fn export_selection_crops_to_the_selection() {
|
||||
assert_eq!(u32::from_be_bytes([png[16], png[17], png[18], png[19]]), (w * 2.0).round() as u32);
|
||||
let svg = s.execute("document.exportSelection", &json!({"format": "svg"})).unwrap();
|
||||
let text = String::from_utf8(vectorcraft_format::base64_decode(svg["dataBase64"].as_str().unwrap()).unwrap()).unwrap();
|
||||
assert_eq!(text.matches("<path").count(), 1, "{text}");
|
||||
assert_eq!(vectorcraft_testkit::svg_shapes(&text), 1, "{text}");
|
||||
}
|
||||
|
||||
/// The crop of a selection export takes in the object's effects: a drop shadow, an outer glow and
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
//! Align panel menu › Align to Glyph Bounds (#4231): with Point Text or Area Text on, Align and
|
||||
//! Distribute measure that kind of type by the ink of its glyphs instead of its em box or frame.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
use crate::*;
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}"))
|
||||
}
|
||||
|
||||
fn id(v: Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
/// A document with a 50 pt square at (10, 10), lowercase "ace" (no ascenders or descenders, so
|
||||
/// its ink sits inside its em box) as point type with its baseline at (100, 300), and as area
|
||||
/// type in a 200 × 100 pt frame at (100, 350); Align to Glyph Bounds set as `point` and `area`.
|
||||
fn doc(point: bool, area: bool) -> (Session, NodeId, NodeId, NodeId) {
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "file.new", json!({"width": 600, "height": 600}));
|
||||
let square = id(run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})));
|
||||
let pt = id(run(&mut s, "text.create", json!({"x": 100, "y": 300, "size": 48, "text": "ace"})));
|
||||
let ar = id(run(&mut s, "text.create", json!({"x": 100, "y": 350, "size": 48, "area": {"width": 200, "height": 100}, "text": "ace"})));
|
||||
run(&mut s, "prefs.set", json!({"values": {"alignGlyphBoundsPoint": point, "alignGlyphBoundsArea": area}}));
|
||||
(s, square, pt, ar)
|
||||
}
|
||||
|
||||
/// The em box (point type) or frame (area type): what Align measures by default.
|
||||
fn em(s: &Session, id: NodeId) -> Rect {
|
||||
s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap()
|
||||
}
|
||||
|
||||
/// The ink of the type's glyphs on the page.
|
||||
fn ink(s: &Session, id: NodeId) -> Rect {
|
||||
let NodeKind::Text(t) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("type") };
|
||||
t.xf.transform_rect_bbox(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).ink_bounds().unwrap())
|
||||
}
|
||||
|
||||
fn close(a: f64, b: f64) -> bool {
|
||||
(a - b).abs() < 1e-6
|
||||
}
|
||||
|
||||
/// Aligns `ids` to the left and the top of the selection (the square is left and above them).
|
||||
fn align_top_left(s: &mut Session, ids: &[NodeId]) {
|
||||
run(s, "select.set", json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()}));
|
||||
run(s, "object.align", json!({"horizontal": "left"}));
|
||||
run(s, "object.align", json!({"vertical": "top"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn glyph_ink_sits_inside_the_em_box_of_lowercase_type() {
|
||||
let (s, _, pt, ar) = doc(false, false);
|
||||
for t in [pt, ar] {
|
||||
let (e, i) = (em(&s, t), ink(&s, t));
|
||||
assert!(i.y0 > e.y0 + 1.0 && i.x0 > e.x0, "{t:?}: ink {i:?} inside {e:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn point_text_aligns_by_its_glyphs_with_point_text_on() {
|
||||
for on in [false, true] {
|
||||
let (mut s, square, pt, _) = doc(on, false);
|
||||
align_top_left(&mut s, &[square, pt]);
|
||||
let r = if on { ink(&s, pt) } else { em(&s, pt) };
|
||||
assert!(close(r.x0, 10.0) && close(r.y0, 10.0), "Point Text {on}: {r:?}");
|
||||
// The square stays where it is: it is the selection's top-left.
|
||||
assert_eq!(em(&s, square), Rect::new(10.0, 10.0, 60.0, 60.0));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn area_text_aligns_by_its_glyphs_with_area_text_on() {
|
||||
for on in [false, true] {
|
||||
let (mut s, square, _, ar) = doc(false, on);
|
||||
align_top_left(&mut s, &[square, ar]);
|
||||
let r = if on { ink(&s, ar) } else { em(&s, ar) };
|
||||
assert!(close(r.x0, 10.0) && close(r.y0, 10.0), "Area Text {on}: {r:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Point Text leaves area type measured by its frame, and Area Text leaves point type measured
|
||||
/// by its em box.
|
||||
#[test]
|
||||
fn the_two_toggles_are_independent() {
|
||||
let (mut s, square, _, ar) = doc(true, false);
|
||||
align_top_left(&mut s, &[square, ar]);
|
||||
let r = em(&s, ar);
|
||||
assert!(close(r.x0, 10.0) && close(r.y0, 10.0), "area type by its frame: {r:?}");
|
||||
let (mut s, square, pt, _) = doc(false, true);
|
||||
align_top_left(&mut s, &[square, pt]);
|
||||
let r = em(&s, pt);
|
||||
assert!(close(r.x0, 10.0) && close(r.y0, 10.0), "point type by its em box: {r:?}");
|
||||
}
|
||||
|
||||
/// Distribute measures type by its glyphs too: the point type's ink left edge lands halfway
|
||||
/// between the two squares' left edges.
|
||||
#[test]
|
||||
fn distribute_spaces_point_text_by_its_glyphs() {
|
||||
for on in [false, true] {
|
||||
let (mut s, square, pt, _) = doc(on, false);
|
||||
let far = id(run(&mut s, "shape.rectangle", json!({"x": 410, "y": 10, "width": 50, "height": 50})));
|
||||
run(&mut s, "select.set", json!({"ids": [square.0, pt.0, far.0]}));
|
||||
run(&mut s, "object.distribute", json!({"horizontal": "left"}));
|
||||
let r = if on { ink(&s, pt) } else { em(&s, pt) };
|
||||
assert!(close(r.x0, 210.0), "Point Text {on}: {r:?}");
|
||||
}
|
||||
}
|
||||
@@ -851,6 +851,63 @@ fn mesh_point_colour_move_and_undo() {
|
||||
assert!(s.execute("object.mesh.setPointColor", &json!({"id": a.0, "index": 99, "color": "#000000"})).is_err());
|
||||
}
|
||||
|
||||
/// `object.mesh.movePoints` moves just the points it names (their handles with them), over one or
|
||||
/// several meshes, as one undo step; `object.mesh.setPointColor` colours and fades several points
|
||||
/// alike. A bad index, a non-number or a move past the coordinate range fails and changes nothing
|
||||
/// (#4207, #4208).
|
||||
#[test]
|
||||
fn mesh_points_move_and_colour_together() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
let b = rect(&mut s, 200.0, 0.0, 100.0, 100.0);
|
||||
sel(&mut s, &[a, b]);
|
||||
s.execute("object.mesh.create", &json!({"rows": 2, "cols": 2})).unwrap();
|
||||
let (ma, mb) = (mesh_of(&s, a), mesh_of(&s, b));
|
||||
let n = undo_len(&s);
|
||||
s.execute("object.mesh.movePoints", &json!({"id": a.0, "points": [0, 4, 4], "dx": 10, "dy": -5})).unwrap();
|
||||
let m = mesh_of(&s, a);
|
||||
for (i, (q, was)) in m.points.iter().zip(&ma.points).enumerate() {
|
||||
let want = if i == 0 || i == 4 { Point::new(was.p.x + 10.0, was.p.y - 5.0) } else { was.p };
|
||||
assert_eq!((q.p, q.handles), (want, was.handles), "point {i}: moved once if named, its handles with it");
|
||||
}
|
||||
assert_eq!(undo_len(&s), n + 1);
|
||||
s.execute("object.mesh.movePoints", &json!({"items": [{"id": a.0, "points": [1]}, {"id": b.0, "index": 2}], "dx": 1, "dy": 1})).unwrap();
|
||||
assert_eq!(mesh_of(&s, a).points[1].p, Point::new(ma.points[1].p.x + 1.0, ma.points[1].p.y + 1.0));
|
||||
assert_eq!(mesh_of(&s, b).points[2].p, Point::new(mb.points[2].p.x + 1.0, mb.points[2].p.y + 1.0));
|
||||
assert_eq!(undo_len(&s), n + 2, "both meshes in one step");
|
||||
// A move that would take a point past the coordinate range fails.
|
||||
assert!(s.execute("object.mesh.movePoints", &json!({"id": a.0, "points": [0], "dx": 1e308, "dy": 0})).is_err());
|
||||
assert_eq!(undo_len(&s), n + 2);
|
||||
for _ in 0..2 {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
assert_eq!((mesh_of(&s, a), mesh_of(&s, b)), (ma.clone(), mb.clone()));
|
||||
// Several points take one colour and opacity, in one step.
|
||||
s.execute("object.mesh.setPointColor", &json!({"id": a.0, "points": [2, 6], "color": "#0000ff", "opacity": 0.25})).unwrap();
|
||||
for (i, q) in mesh_of(&s, a).points.iter().enumerate() {
|
||||
let named = i == 2 || i == 6;
|
||||
assert_eq!((q.color.to_hex() == "#0000ff", q.opacity == 0.25), (named, named), "point {i}");
|
||||
}
|
||||
assert_eq!(undo_len(&s), n + 1);
|
||||
let n = undo_len(&s);
|
||||
let before = (mesh_of(&s, a), mesh_of(&s, b));
|
||||
for p in [
|
||||
json!({"id": a.0, "points": [0, 99], "dx": 1, "dy": 1}),
|
||||
json!({"items": [{"id": a.0, "points": [0]}, {"id": b.0, "points": [99]}], "dx": 1, "dy": 1}),
|
||||
json!({"id": a.0, "points": [-1], "dx": 1, "dy": 1}),
|
||||
json!({"id": a.0, "points": [1.5], "dx": 1, "dy": 1}),
|
||||
json!({"id": a.0, "points": ["1"], "dx": 1, "dy": 1}),
|
||||
json!({"id": a.0, "points": 1, "dx": 1, "dy": 1}),
|
||||
json!({"id": a.0, "points": [0], "dx": "1", "dy": 1}),
|
||||
json!({"items": 3, "dx": 1, "dy": 1}),
|
||||
json!({"points": [0], "dx": 1, "dy": 1}),
|
||||
] {
|
||||
assert!(s.execute("object.mesh.movePoints", &p).is_err(), "{p}");
|
||||
}
|
||||
assert!(s.execute("object.mesh.setPointColor", &json!({"id": a.0, "points": [0, 9], "color": "#000000"})).is_err());
|
||||
assert_eq!(((mesh_of(&s, a), mesh_of(&s, b)), undo_len(&s)), (before, n), "nothing changed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mesh_add_line_and_delete_point() {
|
||||
let mut s = session();
|
||||
@@ -1037,7 +1094,7 @@ fn svg_export_expands_live_objects() {
|
||||
let s = live_doc();
|
||||
let svg = vectorcraft_svg::export(&s.doc().unwrap().doc, &Default::default());
|
||||
// 4 blend objects + envelope content + 4 patches × 64 mesh pieces.
|
||||
let paths = svg.matches("<path").count();
|
||||
let paths = vectorcraft_testkit::svg_shapes(&svg);
|
||||
assert!(paths >= 4 + 1 + 256, "{paths}");
|
||||
assert!(vectorcraft_svg::import(&svg).is_ok());
|
||||
}
|
||||
@@ -1153,3 +1210,102 @@ fn mesh_create_on_an_image_keeps_alpha_and_refuses_linked_and_big_grids() {
|
||||
assert!(e.contains("linked"), "{e}");
|
||||
assert_eq!(node(&s, id).kind_label(), "Image", "left as it was");
|
||||
}
|
||||
|
||||
/// A CMYK document with the #3232 rectangle filled C0 M40 Y60 K10, made a 4×4 mesh with `create`.
|
||||
fn cmyk_mesh(create: Value) -> (Session, NodeId) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 226.77, "height": 170.08, "colorMode": "cmyk"})).unwrap();
|
||||
let a = rect(&mut s, 28.35, 28.35, 170.08, 113.39);
|
||||
s.execute("paint.setStroke", &json!({"ids": [a.0], "none": true})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [a.0], "color": {"c": 0, "m": 0.4, "y": 0.6, "k": 0.1}})).unwrap();
|
||||
let mut p = json!({"ids": [a.0], "rows": 4, "cols": 4});
|
||||
p.as_object_mut().unwrap().extend(create.as_object().unwrap().clone());
|
||||
s.execute("object.mesh.create", &p).unwrap();
|
||||
(s, a)
|
||||
}
|
||||
|
||||
/// The fill colours `document.exportPdf {standard: pdfX4}` writes (`… scn` operands, and the
|
||||
/// corner colours of its gradient meshes, which are patch shadings, as PDF import reads them
|
||||
/// back), and its warnings.
|
||||
fn pdf_fill_colours(s: &mut Session) -> (Vec<Vec<f32>>, Vec<String>) {
|
||||
let v = s.execute("document.exportPdf", &json!({"standard": "pdfX4", "compression": {"compressText": false}})).unwrap();
|
||||
let bytes = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap();
|
||||
let text = String::from_utf8_lossy(&bytes).into_owned();
|
||||
let mut out = vec![];
|
||||
for line in text.lines() {
|
||||
let words: Vec<&str> = line.split_whitespace().collect();
|
||||
for (i, w) in words.iter().enumerate() {
|
||||
if *w == "scn" {
|
||||
let nums: Vec<f32> = words[..i].iter().rev().map_while(|x| x.parse().ok()).collect();
|
||||
// A pattern (`/P0 scn`) has no colour of its own.
|
||||
if !nums.is_empty() {
|
||||
out.push(nums.into_iter().rev().collect());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
vectorcraft_pdf::import(&bytes).unwrap().walk(|n| {
|
||||
if let NodeKind::Mesh(m) = &n.kind {
|
||||
out.extend(m.points.iter().map(|p| match p.color {
|
||||
Color::Cmyk { c, m, y, k } => vec![c, m, y, k],
|
||||
c => c.to_rgb().to_vec(),
|
||||
}));
|
||||
}
|
||||
});
|
||||
(out, serde_json::from_value(v["warnings"].clone()).unwrap())
|
||||
}
|
||||
|
||||
/// #3232: a mesh made from a CMYK fill in a CMYK document keeps its points in CMYK, and the PDF
|
||||
/// writes them with their K, not separated again from RGB (C/M/Y with K = 0).
|
||||
#[test]
|
||||
fn cmyk_mesh_keeps_its_inks_in_pdf() {
|
||||
for app in ["flat", "center", "edge"] {
|
||||
let (mut s, a) = cmyk_mesh(json!({"appearance": app, "highlight": 0}));
|
||||
assert!(mesh_of(&s, a).points.iter().all(|p| p.color == Color::cmyk(0.0, 0.4, 0.6, 0.1)), "{app}");
|
||||
let (fills, warnings) = pdf_fill_colours(&mut s);
|
||||
assert!(!fills.is_empty() && warnings.is_empty(), "{app}: {warnings:?}");
|
||||
for f in &fills {
|
||||
let [c, m, y, k] = f[..] else { panic!("{app}: not CMYK {f:?}") };
|
||||
// The writer keeps 8 bits per ink: within one step of C0 M40 Y60 K10.
|
||||
let near = |a: f32, b: f32| (a - b).abs() <= 1.0 / 255.0 + 1e-6;
|
||||
assert!(near(c, 0.0) && near(m, 0.4) && near(y, 0.6) && near(k, 0.1), "{app}: {f:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// #3232: lightening to the centre or the edges lightens CMYK points towards paper white in CMYK,
|
||||
/// so K shrinks with the other inks instead of being dropped.
|
||||
#[test]
|
||||
fn cmyk_mesh_highlight_lightens_in_cmyk() {
|
||||
for app in ["center", "edge"] {
|
||||
let (mut s, a) = cmyk_mesh(json!({"appearance": app, "highlight": 50}));
|
||||
let m = mesh_of(&s, a);
|
||||
let (corner, centre) = (m.points[0].color, m.points[m.idx(2, 2)].color);
|
||||
let (lit, plain) = if app == "center" { (centre, corner) } else { (corner, centre) };
|
||||
assert_eq!(plain, Color::cmyk(0.0, 0.4, 0.6, 0.1), "{app}");
|
||||
let Color::Cmyk { c, m: mg, y, k } = lit else { panic!("{app}: {lit:?}") };
|
||||
assert!(c.abs() < 1e-6 && (mg - 0.2).abs() < 1e-5 && (y - 0.3).abs() < 1e-5 && (k - 0.05).abs() < 1e-5, "{app}: {lit:?}");
|
||||
assert!(m.points.iter().all(|p| matches!(p.color, Color::Cmyk { .. })), "{app}");
|
||||
let (fills, warnings) = pdf_fill_colours(&mut s);
|
||||
assert!(warnings.is_empty(), "{app}: no RGB to separate {warnings:?}");
|
||||
assert!(!fills.is_empty(), "{app}: no PDF fills");
|
||||
for f in &fills {
|
||||
let [c, m, y, k] = f[..] else { panic!("{app}: not CMYK {f:?}") };
|
||||
// Every ink in proportion to C0 M40 Y60 K10, lightened by at most half.
|
||||
assert!(c < 1.5 / 255.0 && (0.05 - 1.5 / 255.0..=0.1 + 1.5 / 255.0).contains(&k), "{app}: {f:?}");
|
||||
assert!((m / 0.4 - k / 0.1).abs() < 0.06 && (y / 0.6 - k / 0.1).abs() < 0.06, "{app}: {f:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// #3232: a CMYK colour given to a mesh point stays CMYK, and the PDF keeps its K.
|
||||
#[test]
|
||||
fn cmyk_mesh_point_colour_keeps_k() {
|
||||
let (mut s, a) = cmyk_mesh(json!({"appearance": "flat"}));
|
||||
s.execute("object.mesh.setPointColor", &json!({"id": a.0, "index": 0, "color": {"c": 0, "m": 0, "y": 0, "k": 1}})).unwrap();
|
||||
assert_eq!(mesh_of(&s, a).points[0].color, Color::cmyk(0.0, 0.0, 0.0, 1.0));
|
||||
let (fills, warnings) = pdf_fill_colours(&mut s);
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
assert!(fills.iter().all(|f| f.len() == 4 && f[0] < 1.5 / 255.0), "no cyan from a CMY black: {fills:?}");
|
||||
assert!(fills.iter().any(|f| f[3] > 0.8), "the black corner prints on K: {fills:?}");
|
||||
}
|
||||
@@ -495,7 +495,7 @@ fn svg_export_writes_pattern_def() {
|
||||
// The tile art is inside the pattern.
|
||||
let start = svg.find("<pattern").unwrap();
|
||||
let end = svg.find("</pattern>").unwrap();
|
||||
assert!(svg[start..end].contains("<path"));
|
||||
assert!(vectorcraft_testkit::svg_shapes(&svg[start..end]) > 0);
|
||||
}
|
||||
|
||||
/// A pattern fill is written as a PDF tiling pattern, which PDF import reads back as a pattern
|
||||
|
||||
@@ -1616,6 +1616,23 @@ fn real_time_drawing_off_skips_tool_previews_until_commit() {
|
||||
assert!(s.doc().unwrap().revision > rev, "on again: previews run while dragging");
|
||||
}
|
||||
|
||||
/// #4646: with Real-time Drawing off, a ruler guide moved with the Selection tool still moves
|
||||
/// while it is dragged (the guide is all the drag shows).
|
||||
#[test]
|
||||
fn real_time_drawing_off_still_shows_a_dragged_guide() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
s.execute("guide.add", &json!({"vertical": true, "pos": 100})).unwrap();
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("selection", v).unwrap();
|
||||
set_pref(&mut s, "realTimeDrawing", json!(false));
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 200.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 150.0, 200.0), v).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.guides[0].pos, 150.0, "the guide moves while dragged");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 150.0, 200.0), v).unwrap();
|
||||
assert_eq!((s.doc().unwrap().doc.guides[0].pos, s.doc().unwrap().history.undo.last().map(|e| e.label.as_str())), (150.0, Some("Move Guide")));
|
||||
}
|
||||
|
||||
/// Real-time Drawing turned on mid-drag still applies the deferred preview on commit.
|
||||
#[test]
|
||||
fn real_time_drawing_turned_on_mid_drag_still_commits_deferred_preview() {
|
||||
@@ -1868,3 +1885,27 @@ fn transform_panel_patterns_defaults_to_following_the_general_preference() {
|
||||
s.execute("prefs.reset", &json!({"category": "General"})).unwrap();
|
||||
assert_eq!(s.prefs.transform_panel_patterns, "default");
|
||||
}
|
||||
|
||||
/// Character panel › Show Snap to Glyph Options (#4232): `view.snapToGlyph.options` reads and sets
|
||||
/// the options, all on by default, kept as the `glyphSnap` preference group; bad keys and values
|
||||
/// change nothing, and resetting the preferences turns them all back on.
|
||||
#[test]
|
||||
fn snap_to_glyph_options_read_set_and_reset() {
|
||||
let mut s = Session::new();
|
||||
let all = json!({"baseline": true, "xHeight": true, "bounds": true, "proximity": true, "angular": true, "anchors": true});
|
||||
assert_eq!(s.execute("view.snapToGlyph.options", &json!({})).unwrap(), all);
|
||||
let mut set = all.clone();
|
||||
(set["xHeight"], set["angular"]) = (json!(false), json!(false));
|
||||
assert_eq!(s.execute("view.snapToGlyph.options", &json!({"xHeight": false, "angular": false})).unwrap(), set);
|
||||
assert_eq!(s.execute("prefs.get", &json!({"key": "glyphSnap"})).unwrap(), set);
|
||||
assert!(!s.prefs.glyph_snap.x_height && s.prefs.glyph_snap.baseline);
|
||||
for bad in [json!({"xHeight": 1}), json!({"glyphBounds": false})] {
|
||||
assert!(s.execute("view.snapToGlyph.options", &bad).is_err(), "{bad}");
|
||||
assert!(s.execute("prefs.set", &json!({"key": "glyphSnap", "value": bad})).is_err(), "{bad}");
|
||||
}
|
||||
s.execute("prefs.set", &json!({"key": "glyphSnap", "value": {"anchors": false}})).unwrap();
|
||||
set["anchors"] = json!(false);
|
||||
assert_eq!(s.execute("view.snapToGlyph.options", &json!({})).unwrap(), set);
|
||||
s.execute("prefs.reset", &json!({})).unwrap();
|
||||
assert_eq!(s.execute("view.snapToGlyph.options", &json!({})).unwrap(), all);
|
||||
}
|
||||
@@ -572,6 +572,54 @@ fn model_param_must_be_a_string_when_given() {
|
||||
assert_eq!(fill(&s, art).to_hex(), "#1a1a1a", "nothing changed");
|
||||
}
|
||||
|
||||
/// Recolor Artwork's commands refuse a parameter of the wrong form, such as `limitTo: 5` or
|
||||
/// `includeImages: "false"`, with an error that names it; the art keeps its color and no undo
|
||||
/// step is recorded. A null counts as a value left out.
|
||||
#[test]
|
||||
fn recolor_commands_refuse_params_of_the_wrong_form() {
|
||||
let mut s = session();
|
||||
let art = rect(&mut s, json!("#1a1a1a"));
|
||||
select_all(&mut s);
|
||||
let undo = |s: &Session| s.doc().unwrap().history.undo.len();
|
||||
let before = undo(&s);
|
||||
let map = json!({"#1a1a1a": "#ff0000"});
|
||||
let rows = json!([{"from": ["#1a1a1a"], "to": "#ff0000", "exclude": "true"}]);
|
||||
for (cmd, p, msg) in [
|
||||
("recolor.apply", json!({"map": map, "limitTo": 5}), "no swatch library `5`"),
|
||||
("recolor.apply", json!({"map": map, "limitTo": true}), "no swatch library `true`"),
|
||||
("recolor.reduce", json!({"limitTo": 216}), "no swatch library `216`"),
|
||||
("recolor.apply", json!({"map": map, "includeImages": "false"}), "`includeImages` must be true or false"),
|
||||
("recolor.apply", json!({"map": map, "includePatterns": 0}), "`includePatterns` must be true or false"),
|
||||
("recolor.apply", json!({"map": map, "method": 5}), "unknown method `5`"),
|
||||
("recolor.reduce", json!({"method": true}), "unknown method `true`"),
|
||||
("recolor.reduce", json!({"colors": "2"}), "`colors` must be a number"),
|
||||
("recolor.reduce", json!({"colors": 2.5}), "`colors` must be a whole number"),
|
||||
("recolor.reduce", json!({"preserve": "none"}), "`preserve` must be an object"),
|
||||
("recolor.reduce", json!({"preserve": {"white": "false"}}), "`white` must be true or false"),
|
||||
("recolor.apply", json!({"map": rows}), "`exclude` must be true or false"),
|
||||
("recolor.apply", json!({"map": map, "group": 5}), "`group` must be a string"),
|
||||
("recolor.apply", json!({"map": map, "rename": 5}), "`rename` must be a string"),
|
||||
("recolor.apply", json!({"map": map, "groupColors": "#00ff00"}), "`groupColors` must be an array"),
|
||||
("recolor.randomize", json!({"map": rows}), "`exclude` must be true or false"),
|
||||
("recolor.randomize", json!({"map": map, "seed": "4"}), "`seed` must be a number"),
|
||||
("recolor.randomize", json!({"map": map, "seed": -1}), "`seed` must be a whole number"),
|
||||
("recolor.randomize", json!({"map": map, "order": "false"}), "`order` must be true or false"),
|
||||
("recolor.randomize", json!({"map": map, "saturationBrightness": 1}), "`saturationBrightness` must be true or false"),
|
||||
] {
|
||||
let e = s.execute(cmd, &p).unwrap_err().to_string();
|
||||
assert!(e.contains(msg), "{cmd} {p}: {e}");
|
||||
}
|
||||
assert_eq!(fill(&s, art).to_hex(), "#1a1a1a", "nothing changed");
|
||||
assert_eq!(undo(&s), before, "no undo step");
|
||||
let r = run(&mut s, "recolor.reduce", json!({"colors": null, "method": null, "limitTo": null, "preserve": null}));
|
||||
assert_eq!(r["method"], "scaleTints");
|
||||
let r = run(&mut s, "recolor.randomize", json!({"map": map, "seed": null, "order": null, "saturationBrightness": null}));
|
||||
assert_eq!(r["map"][0]["to"], "rgb 255 0 0");
|
||||
let p = json!({"map": map, "limitTo": null, "method": null, "includeImages": null, "includePatterns": null, "group": null, "rename": null, "groupColors": null});
|
||||
run(&mut s, "recolor.apply", p);
|
||||
assert_eq!(fill(&s, art).to_hex(), "#ff0000");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_model_converts_the_colours_of_a_group_too() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -157,9 +157,9 @@ fn crop_marks_effect_follows_the_object() {
|
||||
run(&mut s, "object.move", json!({"dx": 10, "dy": 0}));
|
||||
assert_eq!(mark(&s, 48)[0], 255, "nothing left behind");
|
||||
assert!(mark(&s, 88)[0] < 200);
|
||||
// SVG export and Expand Appearance draw the marks as paths.
|
||||
// SVG export and Expand Appearance draw the marks as shapes.
|
||||
let svg = vectorcraft_svg::export(&s.doc().unwrap().doc, &Default::default());
|
||||
assert_eq!(svg.matches("<path").count(), 9, "{svg}");
|
||||
assert_eq!(vectorcraft_testkit::svg_shapes(&svg), 9, "{svg}");
|
||||
run(&mut s, "effect.expandAppearance", json!({}));
|
||||
let n = node(&s, a);
|
||||
assert!(n.appearance.effects.is_empty() && n.children().unwrap().len() == 2, "a group of the object and its marks");
|
||||
|
||||
@@ -562,3 +562,25 @@ fn eps_save_bounds_large_page_preview_without_cropping_vector_or_editing_data()
|
||||
assert_eq!(native.artboards, s.doc().unwrap().doc.artboards);
|
||||
assert_eq!(native.layers, s.doc().unwrap().doc.layers);
|
||||
}
|
||||
|
||||
/// #4646: a new document's units and ruler guides survive Save, Close and Open in every format
|
||||
/// that carries the whole document (an SVG keeps them only with Preserve Editing).
|
||||
#[test]
|
||||
fn units_and_ruler_guides_survive_save_and_reopen() {
|
||||
let d = dir("units-guides");
|
||||
for ext in ["vectorcraft", "pdf", "ai", "eps"] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100, "units": "Millimeters"})).unwrap();
|
||||
s.execute("guide.add", &json!({"vertical": true, "pos": 50})).unwrap();
|
||||
s.execute("guide.add", &json!({"vertical": false, "pos": 30})).unwrap();
|
||||
rect(&mut s);
|
||||
let p = path(&d, &format!("a.{ext}"));
|
||||
s.execute("document.save", &json!({"path": p})).unwrap();
|
||||
s.execute("file.close", &json!({})).unwrap();
|
||||
s.execute("document.open", &json!({"path": p})).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let guides: Vec<_> = doc.guides.iter().map(|g| (g.vertical, g.pos)).collect();
|
||||
assert_eq!((doc.units, guides), (vectorcraft_doc::Unit::Millimeters, vec![(true, 50.0), (false, 30.0)]), "{ext}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
@@ -73,6 +73,17 @@ fn ids_are_selected_first() {
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
vec![c]
|
||||
};
|
||||
let shape = |s: &mut Session, ids: &[u64]| {
|
||||
s.execute("select.set", &json!({"ids": &ids[..2]})).unwrap();
|
||||
let c = s.execute("object.compoundShape.make", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
c
|
||||
};
|
||||
let shaped = |s: &mut Session, ids: &[u64]| vec![shape(s, ids)];
|
||||
let member = |s: &mut Session, ids: &[u64]| {
|
||||
shape(s, ids);
|
||||
vec![ids[1]]
|
||||
};
|
||||
let one = |_: &mut Session, ids: &[u64]| vec![ids[1]];
|
||||
let cases: Vec<(&str, Value, Setup<'_>)> = vec![
|
||||
("object.group", json!({}), &none),
|
||||
@@ -81,6 +92,10 @@ fn ids_are_selected_first() {
|
||||
("object.clippingMask.release", json!({}), &clipped),
|
||||
("object.compoundPath.make", json!({}), &none),
|
||||
("object.compoundPath.release", json!({}), &compound),
|
||||
("object.compoundShape.make", json!({"mode": "intersect"}), &none),
|
||||
("object.compoundShape.setMode", json!({"mode": "subtract"}), &member),
|
||||
("object.compoundShape.release", json!({}), &shaped),
|
||||
("object.compoundShape.expand", json!({}), &shaped),
|
||||
("object.arrange.bringToFront", json!({}), &one),
|
||||
("object.arrange.bringForward", json!({}), &one),
|
||||
("object.arrange.sendBackward", json!({}), &one),
|
||||
|
||||
@@ -162,6 +162,59 @@ fn save_and_load_round_trip_keeps_cmyk_spot_and_groups() {
|
||||
assert!(s.execute("swatch.library.save", &json!({"user": true})).is_err(), "no user folder in a headless session");
|
||||
}
|
||||
|
||||
/// The swatch library commands, and the graphic style library save and load that share their file
|
||||
/// handling, refuse a parameter of the wrong form, such as `user: "true"` or `names: "Grays"`, with
|
||||
/// an error that names it; the document keeps its swatches and no undo step is recorded. A null
|
||||
/// counts as a value left out.
|
||||
#[test]
|
||||
fn library_commands_refuse_params_of_the_wrong_form() {
|
||||
let mut s = session();
|
||||
run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}));
|
||||
let swatches = |s: &Session| doc(s).swatches_iter().map(|w| w.name.clone()).collect::<Vec<_>>();
|
||||
let (names, before) = (swatches(&s), undo_len(&s));
|
||||
let data = run(&mut s, "swatch.library.save", json!({"names": ["Grays"]}))["data"].clone();
|
||||
for (cmd, p, msg) in [
|
||||
("swatch.library.get", json!({"library": 5}), "`library` must be a string"),
|
||||
("swatch.library.add", json!({"library": "earth-tones", "names": "Clay"}), "`names` must be a list of names"),
|
||||
("swatch.library.add", json!({"library": "earth-tones", "names": ["Clay", 3]}), "`names` must be a list of names"),
|
||||
("swatch.library.add", json!({"library": "earth-tones", "names": ["Clay"], "apply": 5}), "`apply` must be a string"),
|
||||
("swatch.library.add", json!({"library": "earth-tones", "apply": "fill", "focus": "true"}), "`focus` must be true or false"),
|
||||
("swatch.resetDefaults", json!({"replace": "true"}), "`replace` must be true or false"),
|
||||
("swatch.library.save", json!({"user": "true"}), "`user` must be true or false"),
|
||||
("swatch.library.save", json!({"path": 5}), "`path` must be a string"),
|
||||
("swatch.library.save", json!({"format": 5}), "`format` must be a string"),
|
||||
("swatch.library.save", json!({"name": 5}), "`name` must be a string"),
|
||||
("swatch.library.save", json!({"names": "Grays"}), "`names` must be a list of names"),
|
||||
("swatch.library.load", json!({"path": 5, "data": data}), "`path` must be a string"),
|
||||
("swatch.library.load", json!({"data": 5}), "`data` must be a string"),
|
||||
("swatch.library.load", json!({"dataBase64": 5}), "`dataBase64` must be a string"),
|
||||
("swatch.library.load", json!({"data": data, "name": 5}), "`name` must be a string"),
|
||||
("graphicStyle.saveLibrary", json!({"user": "true"}), "`user` must be true or false"),
|
||||
("graphicStyle.saveLibrary", json!({"names": "Halo"}), "`names` must be a list of names"),
|
||||
("graphicStyle.saveLibrary", json!({"name": 5}), "`name` must be a string"),
|
||||
("graphicStyle.addFromLibrary", json!({"library": "shadows-glows", "names": "Halo"}), "`names` must be a list of names"),
|
||||
("graphicStyle.addFromLibrary", json!({"library": "shadows-glows", "name": 5}), "`name` must be a string"),
|
||||
("graphicStyle.addFromLibrary", json!({"library": "shadows-glows", "apply": "true"}), "`apply` must be true or false"),
|
||||
("graphicStyle.addFromLibrary", json!({"library": "shadows-glows", "apply": true, "add": "true"}), "`add` must be true or false"),
|
||||
("graphicStyle.addFromLibrary", json!({"library": "shadows-glows", "apply": true, "ids": "x"}), "ids must be an array"),
|
||||
("graphicStyle.loadLibrary", json!({"path": 5, "data": "{}"}), "`path` must be a string"),
|
||||
] {
|
||||
let e = s.execute(cmd, &p).unwrap_err().to_string();
|
||||
assert!(e.contains(msg), "{cmd} {p}: {e}");
|
||||
}
|
||||
assert_eq!((swatches(&s), undo_len(&s)), (names.clone(), before), "nothing changed");
|
||||
let r = run(&mut s, "swatch.library.save", json!({"path": null, "format": null, "name": null, "names": null, "user": null}));
|
||||
assert_eq!(r["format"], "vcswatches");
|
||||
let r = run(&mut s, "swatch.library.load", json!({"path": null, "data": data, "dataBase64": null, "name": null}));
|
||||
assert_eq!(r["count"], 9);
|
||||
run(&mut s, "swatch.resetDefaults", json!({"replace": null}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": "earth-tones", "names": null, "apply": null, "focus": null}));
|
||||
assert!(r["added"].as_array().is_some_and(|a| !a.is_empty()) && r.get("applied").is_none(), "{r}");
|
||||
run(&mut s, "graphicStyle.saveLibrary", json!({"name": null, "names": null}));
|
||||
let r = run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "shadows-glows", "name": null, "names": null}));
|
||||
assert!(r["added"].as_array().is_some_and(|a| !a.is_empty()), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn libraries_saved_in_the_user_folder_are_user_defined() {
|
||||
let dir = temp_dir("user");
|
||||
|
||||
@@ -7,7 +7,7 @@ use vectorcraft_doc::{NodeKind, TextKind, TextObject};
|
||||
use vectorcraft_geom::{Affine, Point, Rect};
|
||||
use vectorcraft_text::TextLayout;
|
||||
use vectorcraft_tools::bbox::Handle;
|
||||
use vectorcraft_tools::{Mods, PointerEvent, PointerKind};
|
||||
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
|
||||
|
||||
use crate::*;
|
||||
|
||||
@@ -194,6 +194,87 @@ fn direct_selection_drags_a_frame_corner_or_edge() {
|
||||
assert_eq!(text(&s, id).runs[0].style.size, 12.0);
|
||||
}
|
||||
|
||||
/// Direct Selection's marquee selects the frame anchors of area type inside it: a drag of one moves
|
||||
/// only those, the arrow keys nudge them, and Shift-click takes one out.
|
||||
#[test]
|
||||
fn direct_selection_marquee_selects_frame_anchors() {
|
||||
let mut s = session();
|
||||
let id = area(&mut s, 40.0, 40.0, 120.0, 40.0, STORY);
|
||||
let other = area(&mut s, 300.0, 40.0, 120.0, 40.0, STORY);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let v = ViewInfo::default();
|
||||
let shift = Mods { shift: true, ..Mods::default() };
|
||||
// A marquee round the right-hand corners, (160, 40) and (160, 80).
|
||||
drag(&mut s, "directSelection", Point::new(150.0, 20.0), Point::new(180.0, 100.0));
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![id]);
|
||||
let n = undo_len(&s);
|
||||
drag(&mut s, "directSelection", Point::new(160.0, 80.0), Point::new(180.0, 100.0));
|
||||
assert_eq!(undo_len(&s), n + 1, "one step");
|
||||
assert_eq!(last_step(&s), "Reshape Type Area");
|
||||
assert_eq!(corners(&s, id), vec![Point::ZERO, Point::new(140.0, 20.0), Point::new(140.0, 60.0), Point::new(0.0, 40.0)]);
|
||||
// The arrow keys nudge them, each press one step, and Shift-click takes (179, 60) out.
|
||||
assert!(s.tool_claims_key(ToolKey::Left, v));
|
||||
s.tool_key(ToolKey::Left, Mods::default(), v).unwrap();
|
||||
assert_eq!(undo_len(&s), n + 2);
|
||||
assert_eq!(corners(&s, id), vec![Point::ZERO, Point::new(139.0, 20.0), Point::new(139.0, 60.0), Point::new(0.0, 40.0)]);
|
||||
for kind in [PointerKind::Down, PointerKind::Up] {
|
||||
s.pointer(&PointerEvent::new(kind, 179.0, 60.0).with_mods(shift), v).unwrap();
|
||||
}
|
||||
s.tool_key(ToolKey::Down, shift, v).unwrap();
|
||||
assert_eq!(corners(&s, id), vec![Point::ZERO, Point::new(139.0, 20.0), Point::new(139.0, 70.0), Point::new(0.0, 40.0)]);
|
||||
// A marquee across both frames' facing corners moves both frames in one step.
|
||||
drag(&mut s, "directSelection", Point::new(170.0, 10.0), Point::new(310.0, 65.0));
|
||||
assert_eq!(s.doc().unwrap().selection.objects.len(), 2);
|
||||
let n = undo_len(&s);
|
||||
drag(&mut s, "directSelection", Point::new(300.0, 40.0), Point::new(300.0, 30.0));
|
||||
assert_eq!(undo_len(&s), n + 1, "one step");
|
||||
assert_eq!(corners(&s, id)[1], Point::new(139.0, 10.0));
|
||||
assert_eq!(corners(&s, other), vec![Point::new(0.0, -10.0), Point::new(120.0, 0.0), Point::new(120.0, 40.0), Point::new(0.0, 40.0)]);
|
||||
// Shift-click on the other frame's only selected corner deselects that type; the corner of the
|
||||
// first frame still nudges.
|
||||
for kind in [PointerKind::Down, PointerKind::Up] {
|
||||
s.pointer(&PointerEvent::new(kind, 300.0, 30.0).with_mods(shift), v).unwrap();
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![id]);
|
||||
s.tool_key(ToolKey::Up, Mods::default(), v).unwrap();
|
||||
assert_eq!(corners(&s, id)[1], Point::new(139.0, 9.0));
|
||||
// Deselect, then the same two selected again: they are selected whole, so the arrow keys move
|
||||
// them as objects.
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
sel(&mut s, &[id, other]);
|
||||
assert!(!s.tool_claims_key(ToolKey::Left, v));
|
||||
// A click on empty canvas deselects; the arrow keys are then no longer the tool's.
|
||||
drag(&mut s, "directSelection", Point::new(600.0, 500.0), Point::new(600.0, 500.0));
|
||||
assert!(!s.tool_claims_key(ToolKey::Left, v));
|
||||
}
|
||||
|
||||
/// `text.reshapeArea` with `items` moves several frames' anchors in one step, and fails whole.
|
||||
#[test]
|
||||
fn reshape_area_moves_the_anchors_of_several_frames() {
|
||||
let mut s = session();
|
||||
let a = area(&mut s, 40.0, 40.0, 120.0, 40.0, STORY);
|
||||
let b = area(&mut s, 300.0, 40.0, 120.0, 40.0, STORY);
|
||||
let n = undo_len(&s);
|
||||
let items = json!([{"id": a.0, "anchors": [[0, 2]]}, {"id": b.0, "anchors": [[0, 0], [0, 3]]}]);
|
||||
s.execute("text.reshapeArea", &json!({"items": items, "dx": -10, "dy": 5})).unwrap();
|
||||
assert_eq!(undo_len(&s), n + 1, "one step");
|
||||
assert_eq!(corners(&s, a)[2], Point::new(110.0, 45.0));
|
||||
assert_eq!(corners(&s, b), vec![Point::new(-10.0, 5.0), Point::new(120.0, 0.0), Point::new(120.0, 40.0), Point::new(-10.0, 45.0)]);
|
||||
for bad in [
|
||||
json!({"items": [], "dx": 1, "dy": 1}),
|
||||
json!({"items": {"id": a.0}, "dx": 1, "dy": 1}),
|
||||
json!({"items": [{"id": a.0, "anchors": [[0, 2]]}], "id": a.0, "dx": 1, "dy": 1}),
|
||||
json!({"items": [{"id": a.0, "anchors": [[0, 2]]}, {"id": a.0, "anchors": [[0, 1]]}], "dx": 1, "dy": 1}),
|
||||
// A bad item fails the whole step: the good one does not move either.
|
||||
json!({"items": [{"id": a.0, "anchors": [[0, 2]]}, {"id": b.0, "anchors": [[0, 9]]}], "dx": 1, "dy": 1}),
|
||||
json!({"items": [{"id": a.0, "anchors": [[0, 2]]}, {"anchors": [[0, 1]]}], "dx": 1, "dy": 1}),
|
||||
] {
|
||||
assert!(s.execute("text.reshapeArea", &bad).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(undo_len(&s), n + 1, "nothing more changed");
|
||||
assert_eq!(corners(&s, a)[2], Point::new(110.0, 45.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_resized_frame_reflows_its_thread() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -271,6 +271,7 @@ impl Session {
|
||||
snap_tangent: self.prefs.snap_tangent,
|
||||
snap_perpendicular: self.prefs.snap_perpendicular,
|
||||
snap_to_glyph: view.snap_to_glyph && view.smart_guides && !view.snap_to_grid,
|
||||
glyph_snap: self.prefs.glyph_snap,
|
||||
corner_widgets: view.corner_widgets,
|
||||
fill_active: self.fill_active,
|
||||
gradient_stop: self.selected_stop(),
|
||||
@@ -742,8 +743,9 @@ impl Session {
|
||||
Action::Begin(label) => self.begin_interaction(&label)?,
|
||||
Action::Preview(cmd, p) => {
|
||||
// Performance › Real-time Drawing and Editing (#394): off, remember the latest
|
||||
// params and apply them once on Commit instead of every move.
|
||||
if !self.prefs.real_time_drawing {
|
||||
// params and apply them once on Commit instead of every move. A ruler guide
|
||||
// being dragged still shows: the guide is all there is to see (#4646).
|
||||
if !self.prefs.real_time_drawing && !matches!(cmd.as_str(), "guide.add" | "guide.move") {
|
||||
self.clear_deferred_overlay_cache();
|
||||
let st = self.doc_mut()?;
|
||||
if let Some(it) = &mut st.interaction {
|
||||
|
||||
@@ -1719,6 +1719,60 @@ proptest! {
|
||||
}
|
||||
}
|
||||
|
||||
/// PCX files of each layout, 3 × 2 pixels at 150 dpi: 1 bit in two colors, 1 bit in four planes,
|
||||
/// 2 bits with CGA palette settings, 4 bits with the header palette, 8 bits with the 256-color palette after the image data,
|
||||
/// and 24 bits in three planes, with runs that cross a scan line.
|
||||
fn pcx_samples() -> Vec<(&'static str, Vec<u8>)> {
|
||||
let pcx = |bits: u8, planes: u8, line: u16, data: &[u8]| {
|
||||
let mut f = vec![0x0a, 5, 1, bits, 0, 0, 0, 0, 2, 0, 1, 0, 150, 0, 150, 0];
|
||||
f.extend((0..48u8).map(|i| i.wrapping_mul(37)));
|
||||
f.extend([0, planes]);
|
||||
f.extend(line.to_le_bytes());
|
||||
f.extend(1u16.to_le_bytes());
|
||||
f.resize(128, 0);
|
||||
f.extend(data);
|
||||
f
|
||||
};
|
||||
let mut paletted = pcx(8, 1, 4, &[0xc5, 7, 0xc1, 0xff, 1, 2]);
|
||||
paletted.push(0x0c);
|
||||
paletted.extend((0..=255u8).flat_map(|i| [i, 255 - i, i / 2]));
|
||||
vec![
|
||||
("a.pcx", pcx(1, 1, 2, &[0xa0, 0, 0x40, 0])),
|
||||
("b.pcx", pcx(1, 4, 2, &[0xc8, 0xe0, 0x20, 0, 0x60, 0, 0xc4, 0x80])),
|
||||
("c.pcx", pcx(2, 1, 2, &[0x1b, 0, 0xc2, 0xe4])),
|
||||
("d.pcx", pcx(4, 1, 2, &[0xf1, 0x70, 0x23, 0x40])),
|
||||
("e.pcx", paletted),
|
||||
("f.pcx", pcx(8, 3, 4, &[0xc9, 200, 0xcf, 40])),
|
||||
]
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(config())]
|
||||
|
||||
/// Mutated PCX files (header fields, run-length bytes and the palette after the image data)
|
||||
/// never crash placing, opening or pasting them.
|
||||
#[test]
|
||||
fn mutated_pcx_files_place_without_panics(which in 0usize..6, cut in 0usize..960, edits in prop::collection::vec((0usize..960, any::<u8>()), 0..12)) {
|
||||
let (name, mut bytes) = pcx_samples().swap_remove(which);
|
||||
for (at, b) in edits {
|
||||
if let Some(x) = bytes.get_mut(at) {
|
||||
*x = b;
|
||||
}
|
||||
}
|
||||
bytes.truncate(cut.max(4));
|
||||
let r = catch_quiet(|| {
|
||||
let mut s = vectorcraft_engine::Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let p = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&bytes), "thumbnail": 8});
|
||||
let _ = no_panic(s.execute("file.place.info", &p));
|
||||
let _ = no_panic(s.execute("file.place", &p));
|
||||
let _ = no_panic(s.execute("document.open", &json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&bytes)})));
|
||||
let _ = no_panic(s.execute("clipboard.importImage", &json!({"dataBase64": vectorcraft_format::base64_encode(&bytes)})));
|
||||
});
|
||||
prop_assert!(r.is_ok(), "{name}: panicked: {:?}", r.err());
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- SVG saved with hidden layers and editing data ----------
|
||||
|
||||
/// The rich document with a hidden layer, saved as SVG with its editing data.
|
||||
@@ -3850,8 +3904,8 @@ fn pdf_a_huge_form_drawn_over_and_over_is_refused_in_bounded_time() {
|
||||
#[test]
|
||||
fn a_stream_past_the_cap_is_named() {
|
||||
let image = "/Type /XObject /Subtype /Image /Width 10 /Height 10 /ColorSpace /DeviceRGB /BitsPerComponent 8";
|
||||
let page = |entries: &str| {
|
||||
format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 4 0 R /Resources << /XObject << /Im 5 0 R >> >> {entries} >>")
|
||||
let page = |contents: &str, entries: &str| {
|
||||
format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents {contents} /Resources << /XObject << /Im 5 0 R >> >> {entries} >>")
|
||||
.into_bytes()
|
||||
};
|
||||
let plain = |content: &str| format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len() + 1).into_bytes();
|
||||
@@ -3864,17 +3918,27 @@ fn a_stream_past_the_cap_is_named() {
|
||||
let files = [
|
||||
(
|
||||
"an image",
|
||||
pdf(page(""), vec![plain("q 10 0 0 10 0 0 cm /Im Do Q"), packed_as_is(image, &spaces)]),
|
||||
pdf(page("4 0 R", ""), vec![plain("q 10 0 0 10 0 0 cm /Im Do Q"), packed_as_is(image, &spaces)]),
|
||||
"an image of 10 × 10 px in it (object 5) would decode to more than 256 MB",
|
||||
),
|
||||
(
|
||||
"a page's content",
|
||||
pdf(page(""), vec![packed_as_is("", &spaces), packed(image, "\0\0\0")]),
|
||||
pdf(page("4 0 R", ""), vec![packed_as_is("", &spaces), packed(image, "\0\0\0")]),
|
||||
"a page's content in it (object 4) would decode to more than 256 MB",
|
||||
),
|
||||
(
|
||||
"a page's content in an array",
|
||||
pdf(page("[4 0 R]", ""), vec![packed_as_is("", &spaces), packed(image, "\0\0\0")]),
|
||||
"a page's content in it (object 4) would decode to more than 256 MB",
|
||||
),
|
||||
(
|
||||
"a page's content in an array of its own",
|
||||
pdf(page("6 0 R", ""), vec![packed_as_is("", &spaces), packed(image, "\0\0\0"), b"[4 0 R]".to_vec()]),
|
||||
"a page's content in it (object 4) would decode to more than 256 MB",
|
||||
),
|
||||
(
|
||||
"the editing data",
|
||||
pdf(page(editing), vec![plain("0 0 5 5 re f"), packed(image, "\0\0\0"), packed_as_is("", &spaces)]),
|
||||
pdf(page("4 0 R", editing), vec![plain("0 0 5 5 re f"), packed(image, "\0\0\0"), packed_as_is("", &spaces)]),
|
||||
"its editing data (object 6) would decode to more than 256 MB",
|
||||
),
|
||||
];
|
||||
@@ -3888,6 +3952,39 @@ fn a_stream_past_the_cap_is_named() {
|
||||
});
|
||||
}
|
||||
|
||||
// Pages that share one `Contents` array, the array an object of its own: its stream is named as
|
||||
// a page's content, and a refused stream elsewhere is still found past the pages (#4612 review).
|
||||
#[test]
|
||||
fn pages_sharing_a_contents_array_name_its_stream() {
|
||||
let image = "/Type /XObject /Subtype /Image /Width 10 /Height 10 /ColorSpace /DeviceRGB /BitsPerComponent 8";
|
||||
let plain = |content: &str| format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len() + 1).into_bytes();
|
||||
let spaces = spaces_past_the_cap();
|
||||
// 1 catalog, 2 pages, 3 the shared array, 4 its stream, 5 to 7 the pages, 8 an image they draw.
|
||||
let pdf = |content: Vec<u8>, image: Vec<u8>| {
|
||||
let page = b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 3 0 R /Resources << /XObject << /Im 8 0 R >> >> >>";
|
||||
let head = [
|
||||
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
|
||||
b"<< /Type /Pages /Kids [5 0 R 6 0 R 7 0 R] /Count 3 >>".to_vec(),
|
||||
b"[4 0 R]".to_vec(),
|
||||
content,
|
||||
];
|
||||
pdf_of(&head.into_iter().chain([page.to_vec(), page.to_vec(), page.to_vec(), image]).collect::<Vec<_>>())
|
||||
};
|
||||
let files = [
|
||||
(pdf(packed_as_is("", &spaces), packed(image, "\0\0\0")), "a page's content in it (object 4) would decode to more than 256 MB"),
|
||||
(
|
||||
pdf(plain("q 10 0 0 10 0 0 cm /Im Do Q"), packed_as_is(image, &spaces)),
|
||||
"an image of 10 × 10 px in it (object 8) would decode to more than 256 MB",
|
||||
),
|
||||
];
|
||||
on_a_small_stack(move || {
|
||||
for (bytes, why) in &files {
|
||||
let e = vectorcraft_engine::cmd::fileio::load("shared.pdf", bytes).err().map(|e| e.to_string());
|
||||
assert!(e.as_deref().is_some_and(|e| e.contains(why)), "{why}: {e:?}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pdf_art_that_draws_itself() {
|
||||
let own = "<< /XObject << /F 5 0 R >> /Pattern << /P 5 0 R >> /Font << /F1 5 0 R >> /ExtGState << /G << /SMask << /S /Alpha /G 5 0 R >> >> >> >>";
|
||||
|
||||
@@ -702,3 +702,21 @@ fn objects_beyond_the_document_range_are_left_out() {
|
||||
assert!(names.iter().any(|n| n == "Magenta box") && !names.iter().any(|n| n == "Far box"), "{names:?}");
|
||||
assert!(loaded.warnings.iter().any(|w| w.contains("beyond the document range")), "{:?}", loaded.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_af_g_symbol_fill_is_white() {
|
||||
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../test.af");
|
||||
let Ok(bytes) = std::fs::read(&path) else {
|
||||
return;
|
||||
};
|
||||
let loaded = vectorcraft_engine::cmd::fileio::load("test.af", &bytes).unwrap();
|
||||
assert!(!loaded.preview_only, "{:?}", loaded.warnings);
|
||||
let d = &loaded.doc;
|
||||
// The visible "g41" group holds the "g" symbol (path43).
|
||||
let g41 = all(d).into_iter().find(|n| n.visible && n.name.as_deref() == Some("g41")).expect("visible g41 group must be present");
|
||||
let path43 = g41.children().and_then(|c| c.iter().find(|n| n.name.as_deref() == Some("path43"))).expect("path43 inside g41 must be present");
|
||||
let Some(AppearanceItem::Fill(fill)) = path43.appearance.items.first() else {
|
||||
panic!("path43 has no fill: {:?}", path43.appearance);
|
||||
};
|
||||
assert_eq!(fill.paint, Paint::solid(Color::rgb(1.0, 1.0, 1.0)), "The 'g' symbol must have a white fill in test.af, got {:?}", fill.paint);
|
||||
}
|
||||
@@ -48,7 +48,7 @@ fn all_four_light_colors_save_reopen_undo_and_expand_without_editing_source() {
|
||||
assert_eq!(doc(&s), &red);
|
||||
let svg = s.execute("document.serialize", &json!({"format":"svg"})).unwrap();
|
||||
let text = svg["text"].as_str().unwrap();
|
||||
assert!(text.contains("<path") && !text.contains("<image"), "{effect}");
|
||||
assert!(vectorcraft_testkit::svg_shapes(text) > 0 && !text.contains("<image"), "{effect}");
|
||||
if effect == "threeD.rotate" {
|
||||
assert!(text.contains("#ff4040"), "front plane is white under red light and neutral 25% ambient: {text}");
|
||||
}
|
||||
|
||||
+29
-12
@@ -13,7 +13,7 @@
|
||||
//! groups, paths, colours, gradients, images) with newer ones (transparency, hidden objects) and
|
||||
//! dictionaries (names, artboards, type). `lex` scans it, `read` builds the document.
|
||||
//!
|
||||
//! Reading is bounded: the data decompresses to at most [`MAX_DATA`], and the reader caps nesting,
|
||||
//! Reading is bounded: the data decompresses to at most [`max_data`], and the reader caps nesting,
|
||||
//! objects and points. Anything it doesn't read is an error: the caller opens the file the way it
|
||||
//! did before (the printed page, or the PDF), with a warning saying why.
|
||||
|
||||
@@ -39,10 +39,27 @@ pub(crate) use read::{slot_frame, slot_of};
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
/// Largest editing data read, decompressed (bytes). Files with embedded rasters reach 340 MB (a
|
||||
/// 30 MB poker box template unpacks to 322 MiB), so 64-bit builds read twice the old 256 MiB; a
|
||||
/// 32-bit address space (wasm) keeps it.
|
||||
pub const MAX_DATA: u64 = if cfg!(target_pointer_width = "64") { 512 << 20 } else { 256 << 20 };
|
||||
/// Least editing data read, decompressed (bytes), whatever the machine: 512 MiB on 64-bit builds (a
|
||||
/// 30 MB poker box template with embedded rasters unpacks to 322 MiB), 256 MiB in a 32-bit address
|
||||
/// space (wasm).
|
||||
pub const MIN_DATA: u64 = if cfg!(target_pointer_width = "64") { 512 << 20 } else { 256 << 20 };
|
||||
/// Most editing data read on any machine (bytes). Reading takes about as much memory again as the
|
||||
/// data (1.1 GB of data with 24 embedded 4096 x 4096 images peaked 1.1 GB above the start).
|
||||
pub const MAX_DATA: u64 = if cfg!(target_pointer_width = "64") { 2 << 30 } else { 256 << 20 };
|
||||
|
||||
/// Largest editing data read, decompressed (bytes): an eighth of installed memory, from
|
||||
/// [`MIN_DATA`] to [`MAX_DATA`], so a file whose embedded rasters unpack past 512 MiB keeps its
|
||||
/// layers on a machine with room for it (#3510), while a small file that unpacks without end
|
||||
/// still stops early.
|
||||
pub fn max_data() -> u64 {
|
||||
static LIMIT: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
|
||||
*LIMIT.get_or_init(|| data_limit(vectorcraft_render::installed_memory()))
|
||||
}
|
||||
|
||||
/// [`max_data`] on a machine with `memory` bytes installed (`None`: not known).
|
||||
fn data_limit(memory: Option<u64>) -> u64 {
|
||||
memory.map_or(MIN_DATA, |m| (m / 8).clamp(MIN_DATA, MAX_DATA))
|
||||
}
|
||||
/// Largest Zstandard window accepted (a frame asking for more is damaged data).
|
||||
const MAX_ZSTD_WINDOW: u64 = 64 << 20;
|
||||
/// Most Zstandard frames read (the app writes one).
|
||||
@@ -81,13 +98,13 @@ fn eps_section(section: &[u8]) -> Result<Vec<u8>, String> {
|
||||
}
|
||||
header.extend_from_slice(line);
|
||||
header.extend_from_slice(b"\n");
|
||||
if header.len() as u64 > MAX_DATA {
|
||||
if header.len() as u64 > max_data() {
|
||||
return Err(too_large());
|
||||
}
|
||||
}
|
||||
let Some(codec) = codec else {
|
||||
// Not compressed: the section is the data, as it is (images' samples are binary).
|
||||
if section.len() as u64 > MAX_DATA {
|
||||
if section.len() as u64 > max_data() {
|
||||
return Err(too_large());
|
||||
}
|
||||
return Ok(section.to_vec());
|
||||
@@ -96,7 +113,7 @@ fn eps_section(section: &[u8]) -> Result<Vec<u8>, String> {
|
||||
for line in lines {
|
||||
let body = line.strip_prefix(b"%").unwrap_or(line);
|
||||
text.push_str(std::str::from_utf8(body).map_err(|_| damaged("its ASCII85 encoding"))?);
|
||||
if text.len() as u64 > MAX_DATA {
|
||||
if text.len() as u64 > max_data() {
|
||||
return Err(too_large());
|
||||
}
|
||||
}
|
||||
@@ -105,21 +122,21 @@ fn eps_section(section: &[u8]) -> Result<Vec<u8>, String> {
|
||||
}
|
||||
let packed = ps::ascii85_decode(&text).ok_or_else(|| damaged("its ASCII85 encoding"))?;
|
||||
let mut data = header;
|
||||
data.extend(codec.decode(&packed, MAX_DATA.saturating_sub(data.len() as u64))?);
|
||||
data.extend(codec.decode(&packed, max_data().saturating_sub(data.len() as u64))?);
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
/// The editing data of a `.ai` file: its `AIPrivateData` streams joined (`raw`), decompressed. The
|
||||
/// compressed data may follow header comments that aren't.
|
||||
pub fn decode_private(raw: &[u8]) -> Result<Vec<u8>, String> {
|
||||
if raw.len() as u64 > MAX_DATA {
|
||||
if raw.len() as u64 > max_data() {
|
||||
return Err(too_large());
|
||||
}
|
||||
for (marker, codec) in [(&b"%AI24_ZStandard_Data"[..], Codec::Zstd), (b"%AI12_CompressedData", Codec::Zlib)] {
|
||||
if let Some(at) = find(raw, marker) {
|
||||
let (header, body) = raw.split_at(at);
|
||||
let mut data = header.to_vec();
|
||||
data.extend(codec.decode(body.get(marker.len()..).unwrap_or_default(), MAX_DATA.saturating_sub(header.len() as u64))?);
|
||||
data.extend(codec.decode(body.get(marker.len()..).unwrap_or_default(), max_data().saturating_sub(header.len() as u64))?);
|
||||
return Ok(data);
|
||||
}
|
||||
}
|
||||
@@ -172,5 +189,5 @@ fn damaged(what: &str) -> String {
|
||||
}
|
||||
|
||||
fn too_large() -> String {
|
||||
format!("it decompresses to more than {} MB", MAX_DATA >> 20)
|
||||
format!("it decompresses to more than {} MB", max_data() >> 20)
|
||||
}
|
||||
Loaded 100 of 256 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user