mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-24 03:12:57 +01:00
6582: reconcile documentation with current main
This commit is contained in:
commit
0ccb8d2a77
422 files changed
+32276
-2967
No files matched your search
@@ -17,25 +17,25 @@ concurrency:
|
||||
|
||||
jobs:
|
||||
affinity3:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
env:
|
||||
AFFINITY_CORPUS_REQUIRED: "1"
|
||||
CARGO_PROFILE_DEV_DEBUG: "0"
|
||||
CARGO_PROFILE_TEST_DEBUG: "0"
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Install Rust
|
||||
uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
with:
|
||||
toolchain: "1.95"
|
||||
- name: Fetch pinned and checksum-verified corpus
|
||||
run: cargo xtask corpus --affinity
|
||||
- name: Parse every file and freeze actual Affinity 3 feature retention
|
||||
run: cargo test -p vectorcraft-affinity --all-features -- --nocapture
|
||||
- name: Check every artboard, native save, SVG, PDF and PSD exports
|
||||
run: cargo test -p vectorcraft-engine --test affinity_artboards --test affinity_text --test affinity_corpus -- --nocapture
|
||||
# Tracks @main so suite-wide CI fixes reach every app without a PR in each repository.
|
||||
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
|
||||
with:
|
||||
timeout-minutes: 30
|
||||
toolchain: "1.95"
|
||||
# As before: no craft-fonts, apt packages, wasm target or nextest.
|
||||
craft-fonts-ref: ""
|
||||
targets: ""
|
||||
tools: ""
|
||||
dev-debug: "0"
|
||||
env: |
|
||||
AFFINITY_CORPUS_REQUIRED=1
|
||||
CARGO_PROFILE_TEST_DEBUG=0
|
||||
# Its own cache, apart from ci.yml's gate.
|
||||
cache-version: v1-affinity
|
||||
command: |
|
||||
# Pinned and checksum-verified corpus.
|
||||
cargo xtask corpus --affinity
|
||||
# Parse every file and freeze actual Affinity 3 feature retention.
|
||||
cargo test -p vectorcraft-affinity --all-features -- --nocapture
|
||||
# Every artboard, native save, SVG, PDF and PSD export.
|
||||
cargo test -p vectorcraft-engine --test affinity_artboards --test affinity_text --test affinity_corpus -- --nocapture
|
||||
@@ -30,51 +30,9 @@ jobs:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
uses: storytold/craft-common-actions/.github/workflows/refresh-contributors.yml@main
|
||||
git-sources:
|
||||
name: Git dependencies come from storytold
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Git dependencies come from storytold
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test -f Cargo.lock || { echo "Cargo.lock is missing"; exit 1; }
|
||||
# Source replacement, patches and path overrides in cargo config never show up
|
||||
# in Cargo.lock. Parsed rather than grepped: TOML has many spellings of one key.
|
||||
# Cargo still reads the legacy .cargo/config.
|
||||
python3 - <<'PY'
|
||||
import os, sys, tomllib
|
||||
for path in (".cargo/config", ".cargo/config.toml"):
|
||||
if not os.path.exists(path):
|
||||
continue
|
||||
config = tomllib.load(open(path, "rb"))
|
||||
replaced = [name for name, source in config.get("source", {}).items()
|
||||
if isinstance(source, dict) and "replace-with" in source]
|
||||
if replaced or "patch" in config or "paths" in config:
|
||||
print(f"{path} replaces, patches or overrides a source")
|
||||
sys.exit(1)
|
||||
PY
|
||||
# Fails when Cargo.lock is out of date with the manifests.
|
||||
cargo metadata --locked --format-version 1 > /dev/null
|
||||
python3 - <<'PY'
|
||||
import sys, tomllib
|
||||
lock = tomllib.load(open("Cargo.lock", "rb"))
|
||||
bad = sorted({p["source"] for p in lock.get("package", [])
|
||||
if p.get("source", "").startswith("git+")
|
||||
and not p["source"].startswith("git+https://github.com/storytold/")})
|
||||
if bad:
|
||||
print("Git dependencies outside github.com/storytold:", *bad, sep="\n")
|
||||
sys.exit(1)
|
||||
PY
|
||||
|
||||
release:
|
||||
needs: [git-sources, credits]
|
||||
needs: credits
|
||||
permissions:
|
||||
contents: write
|
||||
packages: write
|
||||
|
||||
@@ -20,7 +20,7 @@ Every non-code asset in this repository (icons, images, fonts, example art, colo
|
||||
|
||||
**Policy (mandatory):** VectorCraft contains **no Adobe iconography, images, artwork, presets, swatch/brush/symbol/pattern libraries or ICC profiles**. Every asset is either original work by VectorCraft contributors, or third-party material under an open licence (OSI open source, public domain / CC0, or Creative Commons that allows redistribution), and it is attributed below. Screenshots of Adobe software are never committed. The one exception is the ArtCraft name, wordmark and logos in `docs/brand/`: ArtCraft trademarks, not open source, usable only under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt).
|
||||
|
||||
Generated-in-code art is original and has no file to list. This covers the default swatches, brushes, symbols, patterns, graphic styles, image-trace presets and the vector tool cursors (`crates/ui-egui/src/cursors.rs`).
|
||||
Generated-in-code art is original and has no file to list. This covers the default swatches, brushes, symbols, patterns, graphic styles, image-trace presets, the vector tool cursors (`crates/ui-egui/src/cursors.rs`) and the Learn panel's practice samples (`crates/ui-egui/src/panels/learn/samples.rs`).
|
||||
|
||||
**Font files are never committed here.** Fonts shared by the Crafting Apps live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts). The small Latin UI/document fonts below predate that rule and stay.
|
||||
|
||||
|
||||
Generated
+2
@@ -6477,6 +6477,7 @@ dependencies = [
|
||||
"vectorcraft-text",
|
||||
"vectorcraft-three-d",
|
||||
"vectorcraft-trace",
|
||||
"wat",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6855,6 +6856,7 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"toml",
|
||||
"vectorcraft-apischema",
|
||||
"vectorcraft-brush",
|
||||
"vectorcraft-cad",
|
||||
"vectorcraft-color",
|
||||
|
||||
@@ -108,10 +108,37 @@ impl eframe::App for App {
|
||||
self.app.start_pending_update();
|
||||
#[cfg(target_os = "macos")]
|
||||
super::mac_cursor::release();
|
||||
#[cfg(not(any(target_os = "macos", windows)))]
|
||||
hide_before_teardown(self.winit_window.as_deref());
|
||||
end_before_teardown(self.frames);
|
||||
}
|
||||
}
|
||||
|
||||
/// The main window as [`hide_before_teardown`] sees it.
|
||||
#[cfg(not(any(target_os = "macos", windows)))]
|
||||
pub(crate) trait QuittingWindow {
|
||||
fn hide(&self);
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "macos", windows)))]
|
||||
impl QuittingWindow for winit::window::Window {
|
||||
fn hide(&self) {
|
||||
self.set_visible(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// On Linux and the BSDs, hide the main window before eframe drops the app. Dropping the app waits
|
||||
/// up to [`vectorcraft_ui_egui::CLIPBOARD_PROBE_STOP_WAIT`] for the clipboard handles to let go, and
|
||||
/// the window would stay on screen for that time. The window is hidden, not closed: the Wayland
|
||||
/// clipboard reads text on the window's connection. winit hides X11 windows (XWayland included) and
|
||||
/// cannot hide a Wayland window.
|
||||
#[cfg(not(any(target_os = "macos", windows)))]
|
||||
pub(crate) fn hide_before_teardown<W: QuittingWindow + ?Sized>(window: Option<&W>) {
|
||||
if let Some(window) = window {
|
||||
window.hide();
|
||||
}
|
||||
}
|
||||
|
||||
impl App {
|
||||
/// The frame's times for the hang report, and its last stage ([`hang_beacon::after_frame`]): a
|
||||
/// focused, shown window whose windows had input waits for the renderer and the next frame,
|
||||
|
||||
@@ -1504,6 +1504,16 @@ mod portable {
|
||||
assert_eq!(finish(true), Duration::ZERO);
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
#[test]
|
||||
fn quitting_waits_for_the_paste_checks_handle_as_long_as_its_reads_last() {
|
||||
// The Paste check's handle is one of these: when the app quits, its unanswered X11 read
|
||||
// ends `X11_READ_LIMIT` after it was sent, and an idle worker stops within `LOAD_WAIT`.
|
||||
// Quitting waits for that handle until both are over.
|
||||
assert!(vectorcraft_ui_egui::CLIPBOARD_PROBE_STOP_WAIT >= finish(false) + super::super::loads::LOAD_WAIT);
|
||||
assert!(vectorcraft_ui_egui::CLIPBOARD_PROBE_STOP_WAIT >= finish(true) + super::super::loads::LOAD_WAIT);
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
#[test]
|
||||
fn a_bitmap_paste_waits_for_the_owner_off_the_ui_thread() {
|
||||
|
||||
@@ -393,8 +393,9 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
|
||||
// Its calls are marked for the hang report (`hang_watch`).
|
||||
system_clipboard: Some(Box::new(vectorcraft_ui_egui::hang_beacon::Marked(clipboard::system_clipboard(clip)))),
|
||||
// Linux checks whether Paste has something to take on a background thread: an X11 clipboard
|
||||
// owner that never answers holds a read for up to 4 s. Windows only asks which formats the
|
||||
// clipboard holds and macOS asks the pasteboard server, so they check in line.
|
||||
// owner that never answers holds a text read for up to 4 s for each format it tries, and
|
||||
// quitting waits up to `CLIPBOARD_PROBE_STOP_WAIT` for that thread. Windows only asks which
|
||||
// formats the clipboard holds and macOS asks the pasteboard server, so they check in line.
|
||||
// The probe's handle is made on its own thread, from the window (`Send`), not its raw display.
|
||||
clipboard_probe: cfg!(target_os = "linux").then(|| Box::new(move || clipboard::system_clipboard(clip_probe)) as ClipboardProbeFactory),
|
||||
// Help → Discord / website / GitHub, the Discord button, About and Home links.
|
||||
|
||||
@@ -87,6 +87,8 @@ mod titlebar;
|
||||
use app::bring_window_forward;
|
||||
use app::native_input_hook;
|
||||
use app::open_or_hold;
|
||||
#[cfg(all(test, not(any(target_os = "macos", windows))))]
|
||||
use app::{QuittingWindow, hide_before_teardown};
|
||||
use host_services::services;
|
||||
#[cfg(all(test, feature = "wgpu"))]
|
||||
use prefs::{KEEP_UI_PREFS, decode_saved_prefs, keep_prefs_copy, prefs_bytes};
|
||||
@@ -116,7 +118,8 @@ struct App {
|
||||
frames: u64,
|
||||
/// Keeps the custom title bar's window borderless (Windows, #1758).
|
||||
window_frame: Option<window_frame::WindowFrameFn>,
|
||||
/// The main window; used to read and set maximized state the UI layer does not see on Linux (#3635).
|
||||
/// The main window; used to read and set maximized state the UI layer does not see on Linux (#3635),
|
||||
/// and to hide the window on quit before the clipboard handles let go (`app::hide_before_teardown`).
|
||||
winit_window: Option<std::sync::Arc<winit::window::Window>>,
|
||||
/// A saved or fitted geometry asked for maximize once the window is mapped (Linux).
|
||||
pending_maximize: bool,
|
||||
|
||||
@@ -460,3 +460,21 @@ fn the_linux_desktop_entry_opens_every_readable_format() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// On Linux and the BSDs, quitting hides the main window before eframe drops the app, whose
|
||||
/// clipboard handles may take up to `CLIPBOARD_PROBE_STOP_WAIT` to let go.
|
||||
#[cfg(not(any(target_os = "macos", windows)))]
|
||||
#[test]
|
||||
fn quitting_hides_the_window_before_the_clipboards_let_go() {
|
||||
struct Window(std::cell::Cell<u32>);
|
||||
impl QuittingWindow for Window {
|
||||
fn hide(&self) {
|
||||
self.0.set(self.0.get() + 1);
|
||||
}
|
||||
}
|
||||
let window = Window(std::cell::Cell::new(0));
|
||||
hide_before_teardown(Some(&window));
|
||||
assert_eq!(window.0.get(), 1, "the window was not hidden");
|
||||
// Without a window (none was made), there is nothing to hide.
|
||||
hide_before_teardown::<Window>(None);
|
||||
}
|
||||
@@ -567,6 +567,112 @@ pub fn theme_palette(samples: &[(Color, f32)], n: usize) -> Vec<Color> {
|
||||
groups.into_iter().map(|g| g.2).collect()
|
||||
}
|
||||
|
||||
/// Colors that [`weigh`] moves from one row to another as one: a color they are shown by, how
|
||||
/// often the art uses them and the row they are in. A fixed unit (such as the color a row is
|
||||
/// shown by) stays in its row.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct WeighUnit {
|
||||
pub color: Color,
|
||||
pub uses: f64,
|
||||
pub row: usize,
|
||||
pub fixed: bool,
|
||||
}
|
||||
|
||||
/// The unit-by-row comparisons one [`weigh`] makes, at most.
|
||||
const WEIGH_WORK: usize = 50_000_000;
|
||||
|
||||
/// The uses of `u` that count: a positive finite number, else 0.
|
||||
fn unit_uses(u: &WeighUnit) -> f64 {
|
||||
if u.uses.is_finite() && u.uses > 0.0 { u.uses } else { 0.0 }
|
||||
}
|
||||
|
||||
/// Each row's share of the uses of `units`, in percent (0 for every row when nothing is used).
|
||||
/// Units whose row is past `rows`, or whose uses are not a positive finite number, count nothing.
|
||||
pub fn row_shares(units: &[WeighUnit], rows: usize) -> Vec<f64> {
|
||||
let mut sums = vec![0.0; rows];
|
||||
for u in units {
|
||||
if let Some(s) = sums.get_mut(u.row) {
|
||||
*s += unit_uses(u);
|
||||
}
|
||||
}
|
||||
let total: f64 = sums.iter().sum();
|
||||
if total <= 0.0 {
|
||||
return vec![0.0; rows];
|
||||
}
|
||||
sums.iter().map(|s| s / total * 100.0).collect()
|
||||
}
|
||||
|
||||
/// For Recolor Artwork's Prominent Colors (our own rule): the row each of `units` goes to so that
|
||||
/// each row's share of the uses comes as near its share of `weights` as whole units allow. One
|
||||
/// unit moves at a time, while a move brings the rows' shares nearer their weights (the sum of
|
||||
/// every row's distance from its weight falls); of those moves, the one taken is the unit nearest
|
||||
/// in Lab (CIEDE2000) to the color of the row it goes to (`anchors`), compared with the row it
|
||||
/// leaves; on a tie, the move that brings the shares nearest. Fixed units, units in a row past
|
||||
/// `anchors` and units used no times stay where they are. Weights that are negative or not finite
|
||||
/// count as 0; when no weight is positive, every unit stays. The moves stop after
|
||||
/// [`WEIGH_WORK`] comparisons of a unit with a row, and when the movable units times the rows pass
|
||||
/// it, every unit stays.
|
||||
pub fn weigh(units: &[WeighUnit], anchors: &[Color], weights: &[f64]) -> Vec<usize> {
|
||||
let mut row: Vec<usize> = units.iter().map(|u| u.row).collect();
|
||||
let n = anchors.len();
|
||||
let given = |r: usize| weights.get(r).copied().filter(|x| x.is_finite() && *x > 0.0).unwrap_or(0.0);
|
||||
// Scaled by the largest weight first, so the sum stays finite.
|
||||
let top = (0..n).map(given).fold(0.0, f64::max);
|
||||
let w = |r: usize| if top > 0.0 { given(r) / top } else { 0.0 };
|
||||
let sum_w: f64 = (0..n).map(w).sum();
|
||||
let movable: Vec<usize> = (0..units.len()).filter(|&i| !units[i].fixed && units[i].row < n && unit_uses(&units[i]) > 0.0).collect();
|
||||
let per_pass = movable.len().saturating_mul(n);
|
||||
if sum_w <= 0.0 || n < 2 || movable.is_empty() || per_pass > WEIGH_WORK {
|
||||
return row;
|
||||
}
|
||||
let mut sums = vec![0.0; n];
|
||||
for u in units.iter().filter(|u| u.row < n) {
|
||||
sums[u.row] += unit_uses(u);
|
||||
}
|
||||
let total: f64 = sums.iter().sum();
|
||||
let target: Vec<f64> = (0..n).map(|r| w(r) / sum_w * total).collect();
|
||||
let anchor_labs: Vec<Lab> = anchors.iter().map(|c| c.to_lab()).collect();
|
||||
// Each movable unit's distance to each row's color.
|
||||
let dist: Vec<Vec<f32>> = movable
|
||||
.iter()
|
||||
.map(|&i| {
|
||||
let l = units[i].color.to_lab();
|
||||
anchor_labs.iter().map(|a| delta_e2000(*a, l)).collect()
|
||||
})
|
||||
.collect();
|
||||
// A move must bring the shares nearer by more than rounding.
|
||||
let eps = total * 1e-9;
|
||||
for _ in 0..WEIGH_WORK / per_pass {
|
||||
let mut best: Option<(f32, f64, usize, usize)> = None;
|
||||
for (m, &i) in movable.iter().enumerate() {
|
||||
let (a, x) = (row[i], unit_uses(&units[i]));
|
||||
let before_a = (sums[a] - target[a]).abs();
|
||||
let after_a = (sums[a] - x - target[a]).abs();
|
||||
for b in (0..n).filter(|&b| b != a) {
|
||||
let gain = before_a + (sums[b] - target[b]).abs() - after_a - (sums[b] + x - target[b]).abs();
|
||||
if gain <= eps {
|
||||
continue;
|
||||
}
|
||||
let cost = dist[m][b] - dist[m][a];
|
||||
let better = match best {
|
||||
None => true,
|
||||
Some((c, g, ..)) => cost < c || (cost == c && gain > g),
|
||||
};
|
||||
if better {
|
||||
best = Some((cost, gain, m, b));
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some((_, _, m, b)) = best else { break };
|
||||
let i = movable[m];
|
||||
let x = unit_uses(&units[i]);
|
||||
sums[row[i]] -= x;
|
||||
sums[b] += x;
|
||||
row[i] = b;
|
||||
}
|
||||
row
|
||||
}
|
||||
|
||||
/// A set of colours to snap to (Limit to Library), with their Lab values cached.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Palette(Vec<(Color, Lab)>);
|
||||
@@ -911,4 +1017,55 @@ mod tests {
|
||||
assert!(matches!(Rng::new(3).saturation_brightness(Color::lab(50.0, 40.0, 20.0)), Color::Lab { .. }));
|
||||
assert_eq!(Rng::new(3).saturation_brightness(Color::gray(0.4)).to_hsb()[1], 0.0, "greys stay grey");
|
||||
}
|
||||
|
||||
fn unit(color: Color, uses: f64, row: usize, fixed: bool) -> WeighUnit {
|
||||
WeighUnit { color, uses, row, fixed }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn row_shares_are_percent_of_the_uses() {
|
||||
let units = [unit(Color::rgb(1.0, 0.0, 0.0), 3.0, 0, true), unit(Color::rgb(0.0, 0.0, 1.0), 1.0, 1, true), unit(Color::WHITE, 5.0, 4, false)];
|
||||
assert_eq!(row_shares(&units, 2), vec![75.0, 25.0]);
|
||||
assert_eq!(row_shares(&[], 2), vec![0.0, 0.0]);
|
||||
assert_eq!(row_shares(&[unit(Color::WHITE, f64::NAN, 0, false)], 1), vec![0.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weigh_moves_the_nearest_colors_toward_the_weights() {
|
||||
let (red, blue) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0));
|
||||
let units = [
|
||||
unit(red, 1.0, 0, true),
|
||||
unit(Color::rgb(0.9, 0.1, 0.3), 1.0, 0, false),
|
||||
unit(Color::rgb(0.5, 0.0, 0.8), 1.0, 0, false),
|
||||
unit(blue, 1.0, 1, true),
|
||||
];
|
||||
// Equal weights: the reddish purple, nearer blue than the red-pink is, moves.
|
||||
assert_eq!(weigh(&units, &[red, blue], &[1.0, 1.0]), vec![0, 0, 1, 1]);
|
||||
// Most of the weight on blue: both movable colors go, the row's own color stays.
|
||||
assert_eq!(weigh(&units, &[red, blue], &[0.0, 1.0]), vec![0, 1, 1, 1]);
|
||||
// Weights already met, or none positive: nothing moves.
|
||||
assert_eq!(weigh(&units, &[red, blue], &[3.0, 1.0]), vec![0, 0, 0, 1]);
|
||||
assert_eq!(weigh(&units, &[red, blue], &[0.0, f64::NAN]), vec![0, 0, 0, 1]);
|
||||
assert_eq!(weigh(&units, &[red, blue], &[1e308, 1e308]), vec![0, 0, 1, 1], "huge weights act as equal ones");
|
||||
assert_eq!(weigh(&units, &[red], &[1.0]), vec![0, 0, 0, 1], "a row past the anchors keeps its units");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weigh_takes_whole_units_and_stops_when_no_move_helps() {
|
||||
let (red, blue) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0));
|
||||
// A heavy unit: moving it would overshoot by more than staying misses.
|
||||
let units = [unit(red, 1.0, 0, true), unit(Color::rgb(0.8, 0.0, 0.2), 10.0, 0, false), unit(blue, 10.0, 1, true)];
|
||||
assert_eq!(weigh(&units, &[red, blue], &[1.0, 1.4]), vec![0, 0, 1]);
|
||||
assert_eq!(weigh(&units, &[red, blue], &[1.0, 20.0]), vec![0, 1, 1]);
|
||||
// Many units: the result still follows the weights.
|
||||
let many: Vec<WeighUnit> = (0..400).map(|i| unit(Color::rgb(i as f32 / 400.0, 0.2, 1.0 - i as f32 / 400.0), 1.0, 0, i == 0)).collect();
|
||||
let rows = weigh(&many, &[Color::rgb(0.0, 0.2, 1.0), Color::rgb(1.0, 0.2, 0.0)], &[1.0, 3.0]);
|
||||
assert_eq!(rows.iter().filter(|r| **r == 1).count(), 300);
|
||||
assert!(rows[399] == 1 && rows[1] == 0, "the reddest colors go to the red row");
|
||||
// Past the work limit (8,000 units by 7,000 rows) nothing moves.
|
||||
let units: Vec<WeighUnit> = (0..8_000).map(|i| unit(Color::WHITE, 1.0, 0, i == 0)).collect();
|
||||
let anchors = vec![Color::BLACK; 7_000];
|
||||
let weights = vec![1.0; 7_000];
|
||||
assert!(weigh(&units, &anchors, &weights).iter().all(|r| *r == 0));
|
||||
}
|
||||
}
|
||||
+129
-17
@@ -1326,27 +1326,39 @@ impl Spine {
|
||||
let s = if s.is_finite() { s.clamp(0.0, self.length()) } else { 0.0 };
|
||||
let sp = &self.subpath;
|
||||
let n = sp.segment_count();
|
||||
let mut start = 0.0;
|
||||
for i in 0..n {
|
||||
let c = sp.segment(i);
|
||||
let end = self.anchor_length(i + 1).unwrap_or(self.length());
|
||||
if s <= end || i + 1 == n {
|
||||
let local_s = (s - start).max(0.0) / (end - start).max(1e-12) * c.arclen(1e-9);
|
||||
let t = c.inv_arclen(local_s, 1e-9).clamp(0.0, 1.0);
|
||||
let e = c.eval(t);
|
||||
let tv = c.deriv().eval(t).to_vec2();
|
||||
// Where a handle sits on its anchor the derivative vanishes there: take the
|
||||
// direction between points a little before and after instead.
|
||||
let tv = if tv.hypot2() < 1e-24 { c.eval((t + 1e-3).min(1.0)) - c.eval((t - 1e-3).max(0.0)) } else { tv };
|
||||
return (Point::new(e.x, e.y), tv.y.atan2(tv.x));
|
||||
}
|
||||
start = end;
|
||||
if n == 0 {
|
||||
return (self.pts.first().copied().unwrap_or_default(), 0.0);
|
||||
}
|
||||
// Only a spine without segments gets here: the loop returns at the last one.
|
||||
(self.pts.first().copied().unwrap_or_default(), 0.0)
|
||||
let i = segment_at(&self.anchors, n, s, || {});
|
||||
let c = sp.segment(i);
|
||||
let start = if i == 0 { 0.0 } else { self.anchor_length(i).unwrap_or(0.0) };
|
||||
let end = self.anchor_length(i + 1).unwrap_or(self.length());
|
||||
let local_s = (s - start).max(0.0) / (end - start).max(1e-12) * c.arclen(1e-9);
|
||||
let t = c.inv_arclen(local_s, 1e-9).clamp(0.0, 1.0);
|
||||
let e = c.eval(t);
|
||||
let tv = c.deriv().eval(t).to_vec2();
|
||||
// Where a handle sits on its anchor the derivative vanishes there: take the
|
||||
// direction between points a little before and after instead.
|
||||
let tv = if tv.hypot2() < 1e-24 { c.eval((t + 1e-3).min(1.0)) - c.eval((t - 1e-3).max(0.0)) } else { tv };
|
||||
(Point::new(e.x, e.y), tv.y.atan2(tv.x))
|
||||
}
|
||||
}
|
||||
|
||||
/// The segment of a spine with `n` segments (`n > 0`) that holds arc length `s`: the first one whose
|
||||
/// end is at or past `s`, or the last one when none is. `anchors` holds the arc length at each
|
||||
/// anchor, so segment `i` ends at `anchors[i + 1]`, and the last segment of a closed spine, which has
|
||||
/// no entry for its end, ends at the spine's length. The lengths never decrease (each is a sum of
|
||||
/// distances that are not negative, at most `+inf` and never NaN), so a binary search finds the
|
||||
/// segment in about `log2(n)` comparisons. `probe` is called once for each comparison.
|
||||
fn segment_at(anchors: &[f64], n: usize, s: f64, mut probe: impl FnMut()) -> usize {
|
||||
let ends = anchors.get(1..n.min(anchors.len())).unwrap_or_default();
|
||||
ends.partition_point(|&end| {
|
||||
probe();
|
||||
end < s
|
||||
})
|
||||
.min(n.saturating_sub(1))
|
||||
}
|
||||
|
||||
/// The anchor of the first subpath each key sits on, when they are all valid for `n` anchors.
|
||||
fn pinned(spec: &BlendSpec, keys: usize, n: usize) -> Option<Vec<usize>> {
|
||||
(spec.key_anchors.len() == keys && keys >= 2 && spec.key_anchors.iter().all(|a| (*a as usize) < n))
|
||||
@@ -1369,6 +1381,14 @@ pub fn blend_spine(keys: &[Arc<Node>], spec: &BlendSpec) -> Option<(PathData, Op
|
||||
layout_spine(keys, spec)
|
||||
}
|
||||
|
||||
/// The line the steps of a blend of `keys` are placed along: [`blend_spine`]'s path for a blend
|
||||
/// with a spine, and the straight lines between the key centers, in key order, for a blend made
|
||||
/// without one ([`BlendSpec::no_spine`]). For a blend without a spine the line places the steps
|
||||
/// only; it is not a spine and is not drawn as one. `None` with fewer than two keys.
|
||||
pub fn blend_layout_line(keys: &[Arc<Node>], spec: &BlendSpec) -> Option<PathData> {
|
||||
layout_spine(keys, spec).map(|(path, _)| path)
|
||||
}
|
||||
|
||||
/// The spine `spec` stores, unless the blend was made without one.
|
||||
fn stored_spine(spec: &BlendSpec) -> Option<&PathData> {
|
||||
spec.spine.as_ref().filter(|_| !spec.no_spine)
|
||||
@@ -1840,6 +1860,28 @@ mod tests {
|
||||
assert_eq!(moved.subpaths[0].anchors[2].p, Point::new(305.0, 5.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_blend_without_a_spine_has_a_layout_line_through_its_key_centers() {
|
||||
let at =
|
||||
|x: f64, y: f64| Arc::new(Node::path(NodeId(1), shapes::rectangle(Rect::new(x - 5.0, y - 5.0, x + 5.0, y + 5.0)), Appearance::default()));
|
||||
let line_of = |path: &PathData| path.subpaths.iter().flat_map(|s| s.anchors.iter().map(|a| a.p)).collect::<Vec<_>>();
|
||||
// A stored spine is ignored once the blend is made without one.
|
||||
let stored = PathData::single(SubPath::polyline(&[Point::new(0.0, 50.0), Point::new(300.0, 50.0)], false));
|
||||
let spec = BlendSpec { no_spine: true, spine: Some(stored), ..Default::default() };
|
||||
for keys in [vec![at(10.0, 20.0), at(110.0, 20.0)], vec![at(10.0, 20.0), at(110.0, 20.0), at(110.0, 220.0), at(-40.0, 0.0)]] {
|
||||
assert!(blend_spine(&keys, &spec).is_none(), "still no spine");
|
||||
let line = blend_layout_line(&keys, &spec).unwrap();
|
||||
assert_eq!(line.subpaths.len(), 1);
|
||||
assert!(!line.subpaths[0].closed);
|
||||
let centers: Vec<Point> = keys.iter().map(|k| center_of(k)).collect();
|
||||
assert_eq!(line_of(&line), centers, "in key order");
|
||||
}
|
||||
// With a spine, the layout line is the spine.
|
||||
let keys = vec![key(0.0), key(100.0), key(300.0)];
|
||||
assert_eq!(blend_layout_line(&keys, &BlendSpec::default()), blend_spine(&keys, &BlendSpec::default()).map(|(p, _)| p));
|
||||
assert!(blend_layout_line(&keys[..1], &spec).is_none(), "one key");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn steps_follow_a_bent_spine() {
|
||||
let keys = vec![key(0.0), key(100.0)];
|
||||
@@ -1891,6 +1933,76 @@ mod tests {
|
||||
assert!(end.is_finite(), "{end}");
|
||||
}
|
||||
|
||||
/// [`Spine::at_length`] by walking the segments from the first, as a reference for the search.
|
||||
fn walked_at_length(sp: &Spine, s: f64) -> (Point, f64) {
|
||||
let s = if s.is_finite() { s.clamp(0.0, sp.length()) } else { 0.0 };
|
||||
let n = sp.subpath.segment_count();
|
||||
let mut start = 0.0;
|
||||
for i in 0..n {
|
||||
let c = sp.subpath.segment(i);
|
||||
let end = sp.anchor_length(i + 1).unwrap_or(sp.length());
|
||||
if s <= end || i + 1 == n {
|
||||
let local_s = (s - start).max(0.0) / (end - start).max(1e-12) * c.arclen(1e-9);
|
||||
let t = c.inv_arclen(local_s, 1e-9).clamp(0.0, 1.0);
|
||||
let e = c.eval(t);
|
||||
let tv = c.deriv().eval(t).to_vec2();
|
||||
let tv = if tv.hypot2() < 1e-24 { c.eval((t + 1e-3).min(1.0)) - c.eval((t - 1e-3).max(0.0)) } else { tv };
|
||||
return (Point::new(e.x, e.y), tv.y.atan2(tv.x));
|
||||
}
|
||||
start = end;
|
||||
}
|
||||
panic!("a spine without segments")
|
||||
}
|
||||
|
||||
/// The search picks the same segment as walking them in order, so points and tangents stay the
|
||||
/// same: on open and closed spines, one segment, curves, and zero-length segments whose anchors
|
||||
/// share an arc length; at every anchor, between anchors, at both ends, past them, and for
|
||||
/// values that are not finite.
|
||||
#[test]
|
||||
fn spine_lookup_matches_walking_the_segments() {
|
||||
let p = Point::new;
|
||||
let bow = SubPath::new(
|
||||
vec![Anchor::smooth(p(0.0, 0.0), p(50.0, 50.0)), Anchor::smooth(p(100.0, 0.0), p(150.0, -50.0)), Anchor::corner(p(200.0, 0.0))],
|
||||
false,
|
||||
);
|
||||
let spines = [
|
||||
SubPath::polyline(&[p(0.0, 0.0), p(10.0, 0.0), p(10.0, 0.0), p(10.0, 0.0), p(30.0, 5.0), p(30.0, 5.0)], false),
|
||||
SubPath::polyline(&[p(0.0, 0.0), p(0.0, 0.0), p(40.0, 0.0), p(40.0, 30.0)], true),
|
||||
SubPath::polyline(&[p(0.0, 0.0), p(40.0, 0.0), p(40.0, 30.0), p(0.0, 0.0)], true),
|
||||
SubPath::polyline(&[p(0.0, 0.0), p(25.0, 25.0)], false),
|
||||
SubPath::polyline(&[p(0.0, 0.0), p(25.0, 25.0)], true),
|
||||
bow.clone(),
|
||||
SubPath { closed: true, ..bow },
|
||||
];
|
||||
for sub in spines {
|
||||
let sp = Spine::new(&PathData::single(sub)).unwrap();
|
||||
let len = sp.length();
|
||||
let mut lengths = vec![0.0, len, -1.0, len + 1.0, -len, f64::NAN, f64::INFINITY, f64::NEG_INFINITY, f64::MAX, f64::MIN];
|
||||
lengths.extend(sp.anchors.iter().flat_map(|&a| [a, a - 1e-9, a + 1e-9]));
|
||||
lengths.extend((0..=400).map(|k| len * k as f64 / 400.0));
|
||||
for s in lengths {
|
||||
assert_eq!(sp.at_length(s), walked_at_length(&sp, s), "s = {s} on {:?}", sp.anchors);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Finding the segment for an arc length on a spine of thousands of segments takes a few
|
||||
/// comparisons, not one for each segment before it.
|
||||
#[test]
|
||||
fn spine_lookup_compares_a_few_segment_ends() {
|
||||
let pts: Vec<Point> = (0..=4096).map(|i| Point::new(i as f64, if i % 2 == 0 { 0.0 } else { 1.0 })).collect();
|
||||
let sp = Spine::new(&PathData::single(SubPath::polyline(&pts, false))).unwrap();
|
||||
let n = sp.subpath.segment_count();
|
||||
assert_eq!(n, 4096);
|
||||
for s in [sp.length() - 0.5, sp.length(), sp.length() / 2.0, 0.25] {
|
||||
let mut compared = 0;
|
||||
let i = segment_at(&sp.anchors, n, s, || compared += 1);
|
||||
assert!(compared <= 13, "{compared} comparisons at {s}");
|
||||
assert_eq!(sp.at_length(s), walked_at_length(&sp, s));
|
||||
assert!(sp.anchors[i] <= s && (i + 1 == n || s <= sp.anchors[i + 1]), "segment {i} at {s}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn easing_keeps_the_ends_and_stays_monotone() {
|
||||
use crate::live::{BlendEase, BlendEaseType as K};
|
||||
|
||||
+204
-37
@@ -140,6 +140,21 @@ pub fn tiff_orientation(bytes: &[u8]) -> Option<u16> {
|
||||
d.find_tag_unsigned::<u16>(tiff::tags::Tag::Orientation).ok().flatten()
|
||||
}
|
||||
|
||||
/// The EXIF orientation of encoded image `bytes` when it turns or flips the pixels; `None` when
|
||||
/// it leaves them as stored, or the image has none. A TIFF the image decoder can't open (one with
|
||||
/// extra samples) has its Orientation tag read from its first image ([`tiff_orientation`]). Reads
|
||||
/// only the image's header and metadata; `None` for an [`oversized_tiff`], which no decoder opens.
|
||||
pub fn exif_orientation(bytes: &[u8]) -> Option<image::metadata::Orientation> {
|
||||
use image::ImageDecoder as _;
|
||||
use image::metadata::Orientation;
|
||||
if oversized_tiff(bytes).is_some() {
|
||||
return None;
|
||||
}
|
||||
let decoded = || image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?.into_decoder().ok()?.orientation().ok();
|
||||
let tagged = || tiff_orientation(bytes).and_then(|v| Orientation::from_exif(u8::try_from(v).ok()?));
|
||||
decoded().or_else(tagged).filter(|o| *o != Orientation::NoTransforms)
|
||||
}
|
||||
|
||||
/// Does the TIFF `d` reads store one plane per channel (PlanarConfiguration 2)?
|
||||
fn planar(d: &mut tiff::decoder::Decoder<Cursor<&[u8]>>) -> bool {
|
||||
d.find_tag_unsigned::<u16>(tiff::tags::Tag::PlanarConfiguration).ok().flatten().is_some_and(|p| p != 1)
|
||||
@@ -151,24 +166,180 @@ fn planar(d: &mut tiff::decoder::Decoder<Cursor<&[u8]>>) -> bool {
|
||||
/// that many samples, which includes images whose planes together need more than the decoder's
|
||||
/// limit (256 MB of samples).
|
||||
pub(crate) fn read_samples(d: &mut tiff::decoder::Decoder<Cursor<&[u8]>>, n: usize, per: usize) -> Option<Vec<u8>> {
|
||||
Some(match read_samples_at_depth(d, n, per)? {
|
||||
Samples::Eight(v) => v,
|
||||
Samples::Sixteen(v) => v.iter().map(|s| (s >> 8) as u8).collect(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Samples of an image, pixel by pixel, at the depth its file stores them.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
enum Samples {
|
||||
Eight(Vec<u8>),
|
||||
Sixteen(Vec<u16>),
|
||||
}
|
||||
|
||||
impl Samples {
|
||||
fn as_slice(&self) -> SampleSlice<'_> {
|
||||
match self {
|
||||
Self::Eight(v) => SampleSlice::Eight(v),
|
||||
Self::Sixteen(v) => SampleSlice::Sixteen(v),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Samples`], borrowed.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum SampleSlice<'a> {
|
||||
Eight(&'a [u8]),
|
||||
Sixteen(&'a [u16]),
|
||||
}
|
||||
|
||||
/// [`read_samples`], keeping 16-bit samples at 16 bits.
|
||||
fn read_samples_at_depth(d: &mut tiff::decoder::Decoder<Cursor<&[u8]>>, n: usize, per: usize) -> Option<Samples> {
|
||||
let mut buf = tiff::decoder::DecodingResult::U8(Vec::new());
|
||||
let layout = d.read_image_to_buffer(&mut buf).ok()?;
|
||||
let data = match buf {
|
||||
tiff::decoder::DecodingResult::U8(v) => v,
|
||||
tiff::decoder::DecodingResult::U16(v) => v.iter().map(|s| (s >> 8) as u8).collect(),
|
||||
_ => return None,
|
||||
};
|
||||
match buf {
|
||||
tiff::decoder::DecodingResult::U8(v) => chunky(v, layout.planes, n, per).map(Samples::Eight),
|
||||
tiff::decoder::DecodingResult::U16(v) => chunky(v, layout.planes, n, per).map(Samples::Sixteen),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `data`, the samples of `n` pixels, `per` to a pixel, stored in `planes` planes, as the samples
|
||||
/// pixel by pixel; `None` when it doesn't hold that many samples or a plane per sample.
|
||||
fn chunky<T: Copy>(data: Vec<T>, planes: usize, n: usize, per: usize) -> Option<Vec<T>> {
|
||||
if Some(data.len()) != n.checked_mul(per) {
|
||||
return None;
|
||||
}
|
||||
if layout.planes <= 1 {
|
||||
if planes <= 1 {
|
||||
return Some(data);
|
||||
}
|
||||
if layout.planes != per {
|
||||
if planes != per {
|
||||
return None;
|
||||
}
|
||||
let planes: Vec<&[u8]> = data.chunks_exact(n).collect();
|
||||
Some((0..n).flat_map(|i| planes.iter().map(move |p| p.get(i).copied().unwrap_or(0))).collect())
|
||||
let planes: Vec<&[T]> = data.chunks_exact(n).collect();
|
||||
Some((0..n).flat_map(|i| planes.iter().filter_map(move |p| p.get(i).copied())).collect())
|
||||
}
|
||||
|
||||
/// The color space an ICC profile's header names (bytes 16 to 19, such as `RGB `, `GRAY` or
|
||||
/// `CMYK`); `None` when `icc` is shorter than a header.
|
||||
pub fn icc_color_space(icc: &[u8]) -> Option<[u8; 4]> {
|
||||
if icc.len() < 128 {
|
||||
return None;
|
||||
}
|
||||
icc.get(16..20)?.try_into().ok()
|
||||
}
|
||||
|
||||
/// The ICC profile of TIFF tag 34675 (ICCProfile) of the image `d` reads; `None` without one.
|
||||
fn tiff_icc(d: &mut tiff::decoder::Decoder<Cursor<&[u8]>>) -> Option<Vec<u8>> {
|
||||
d.get_tag_u8_vec(tiff::tags::Tag::IccProfile).ok().filter(|icc| !icc.is_empty())
|
||||
}
|
||||
|
||||
/// The ICC profile of TIFF `bytes`' first image (tag 34675), read with the `tiff` decoder's own
|
||||
/// limits, whatever the size of the image; `None` for other images and TIFFs without one.
|
||||
pub fn tiff_icc_profile(bytes: &[u8]) -> Option<Vec<u8>> {
|
||||
let (_, mut d) = tiff(bytes)?;
|
||||
tiff_icc(&mut d)
|
||||
}
|
||||
|
||||
/// The ICC profile of a JPEG, put together from all its numbered `ICC_PROFILE` APP2 segments;
|
||||
/// `None` without one.
|
||||
fn jpeg_icc(bytes: &[u8]) -> Option<Vec<u8>> {
|
||||
let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), DecoderOptions::default());
|
||||
d.decode_headers().ok()?;
|
||||
d.icc_profile().filter(|icc| !icc.is_empty())
|
||||
}
|
||||
|
||||
/// `icc` when it is a profile of CMYK colors, which the samples of a CMYK image are in.
|
||||
fn cmyk_icc(icc: Option<Vec<u8>>) -> Option<Vec<u8>> {
|
||||
icc.filter(|icc| icc_color_space(icc) == Some(*b"CMYK"))
|
||||
}
|
||||
|
||||
/// The CMYK samples of a CMYK image at the depth its file stores them, and its ICC profile.
|
||||
struct CmykSource {
|
||||
width: u32,
|
||||
height: u32,
|
||||
samples: Samples,
|
||||
icc: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// The samples of CMYK TIFF `bytes` (8 or 16 bits), their inks together or one plane per ink, with
|
||||
/// the TIFF's CMYK ICC profile; `None` for other images and ones larger than [`MAX_CMYK_PIXELS`].
|
||||
fn tiff_source(bytes: &[u8]) -> Option<CmykSource> {
|
||||
let (kind, mut d) = tiff(bytes)?;
|
||||
if !matches!(kind, tiff::ColorType::CMYK(8 | 16)) {
|
||||
return None;
|
||||
}
|
||||
let (width, height) = d.dimensions().ok()?;
|
||||
let n = usize::try_from(pixels(width, height)?).ok()?;
|
||||
let icc = cmyk_icc(tiff_icc(&mut d));
|
||||
let samples = read_samples_at_depth(&mut d, n, 4)?;
|
||||
Some(CmykSource { width, height, samples, icc })
|
||||
}
|
||||
|
||||
/// The ink amounts of a four-component JPEG, 8 bits each, with its CMYK ICC profile.
|
||||
fn jpeg_source(bytes: &[u8]) -> Option<CmykSource> {
|
||||
let Inks { width, height, data } = jpeg_inks(bytes)?;
|
||||
Some(CmykSource { width, height, samples: Samples::Eight(data), icc: cmyk_icc(jpeg_icc(bytes)) })
|
||||
}
|
||||
|
||||
/// A Deflate-compressed CMYK TIFF of `width` × `height` pixels of `samples` (inks together, 8 or 16
|
||||
/// bits as they are given), declaring the resolution `ppi` when both of its values are finite and
|
||||
/// above 0, and carrying `icc` as tag 34675 (ICCProfile, of type UNDEFINED); `None` when it can't be
|
||||
/// written.
|
||||
fn write_cmyk_tiff(width: u32, height: u32, samples: SampleSlice<'_>, ppi: Option<(f64, f64)>, icc: Option<&[u8]>) -> Option<Vec<u8>> {
|
||||
use tiff::encoder::colortype::{CMYK8, CMYK16, ColorType};
|
||||
use tiff::encoder::{Compression, ImageEncoder, Rational, TiffEncoder, TiffKind, compression::DeflateLevel};
|
||||
use tiff::tags::{ResolutionUnit, Tag};
|
||||
fn tags<W: std::io::Write + std::io::Seek, C: ColorType, K: TiffKind>(
|
||||
img: &mut ImageEncoder<'_, W, C, K>,
|
||||
ppi: Option<(f64, f64)>,
|
||||
icc: Option<&[u8]>,
|
||||
) -> Option<()> {
|
||||
if let Some((x, y)) = ppi.filter(|(x, y)| [x, y].iter().all(|v| v.is_finite() && **v > 0.0)) {
|
||||
// Ten-thousandths of a pixel per inch.
|
||||
let r = |v: f64| Rational { n: (v * 10_000.0).round() as u32, d: 10_000 };
|
||||
img.encoder().write_tag(Tag::XResolution, r(x)).ok()?;
|
||||
img.encoder().write_tag(Tag::YResolution, r(y)).ok()?;
|
||||
img.encoder().write_tag(Tag::ResolutionUnit, ResolutionUnit::Inch).ok()?;
|
||||
}
|
||||
if let Some(icc) = icc {
|
||||
img.encoder().write_tag(Tag::IccProfile, Undefined(icc)).ok()?;
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
let mut out = Cursor::new(Vec::new());
|
||||
let mut enc = TiffEncoder::new(&mut out).ok()?.with_compression(Compression::Deflate(DeflateLevel::Balanced));
|
||||
match samples {
|
||||
SampleSlice::Eight(data) => {
|
||||
let mut img = enc.new_image::<CMYK8>(width, height).ok()?;
|
||||
tags(&mut img, ppi, icc)?;
|
||||
img.write_data(data).ok()?;
|
||||
}
|
||||
SampleSlice::Sixteen(data) => {
|
||||
let mut img = enc.new_image::<CMYK16>(width, height).ok()?;
|
||||
tags(&mut img, ppi, icc)?;
|
||||
img.write_data(data).ok()?;
|
||||
}
|
||||
}
|
||||
Some(out.into_inner())
|
||||
}
|
||||
|
||||
/// Bytes written as a TIFF field of type UNDEFINED, the type of an embedded ICC profile.
|
||||
struct Undefined<'a>(&'a [u8]);
|
||||
|
||||
impl tiff::encoder::TiffValue for Undefined<'_> {
|
||||
const BYTE_LEN: u8 = 1;
|
||||
const FIELD_TYPE: tiff::tags::Type = tiff::tags::Type::UNDEFINED;
|
||||
|
||||
fn count(&self) -> usize {
|
||||
self.0.len()
|
||||
}
|
||||
|
||||
fn data(&self) -> std::borrow::Cow<'_, [u8]> {
|
||||
std::borrow::Cow::Borrowed(self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl ImageBlob {
|
||||
@@ -180,20 +351,8 @@ impl ImageBlob {
|
||||
/// [`ImageBlob::cmyk_tiff`], declaring the resolution `ppi` (horizontal, vertical pixels per
|
||||
/// inch) when it is given and both are finite and above 0.
|
||||
pub fn cmyk_tiff_at(inks: &Inks, ppi: Option<(f64, f64)>) -> Option<Self> {
|
||||
use tiff::encoder::{Compression, Rational, TiffEncoder, colortype::CMYK8, compression::DeflateLevel};
|
||||
use tiff::tags::{ResolutionUnit, Tag};
|
||||
let mut out = Cursor::new(Vec::new());
|
||||
let mut enc = TiffEncoder::new(&mut out).ok()?.with_compression(Compression::Deflate(DeflateLevel::Balanced));
|
||||
let mut img = enc.new_image::<CMYK8>(inks.width, inks.height).ok()?;
|
||||
if let Some((x, y)) = ppi.filter(|(x, y)| [x, y].iter().all(|v| v.is_finite() && **v > 0.0)) {
|
||||
// Ten-thousandths of a pixel per inch.
|
||||
let r = |v: f64| Rational { n: (v * 10_000.0).round() as u32, d: 10_000 };
|
||||
img.encoder().write_tag(Tag::XResolution, r(x)).ok()?;
|
||||
img.encoder().write_tag(Tag::YResolution, r(y)).ok()?;
|
||||
img.encoder().write_tag(Tag::ResolutionUnit, ResolutionUnit::Inch).ok()?;
|
||||
}
|
||||
img.write_data(&inks.data).ok()?;
|
||||
Some(Self::new("image/tiff", out.into_inner()))
|
||||
let tiff = write_cmyk_tiff(inks.width, inks.height, SampleSlice::Eight(&inks.data), ppi, None)?;
|
||||
Some(Self::new("image/tiff", tiff))
|
||||
}
|
||||
|
||||
/// Does the image hold CMYK samples (a four-component JPEG or a CMYK TIFF)? Reads only its
|
||||
@@ -318,30 +477,38 @@ fn tiff_inks(bytes: &[u8]) -> Option<Inks> {
|
||||
|
||||
/// CMYK TIFF `bytes` that no orientation turns ([`turned_cmyk`] stores the others) as Open and
|
||||
/// Place store them: as they are, or, when they store one plane per ink, which the image decoder
|
||||
/// doesn't read, their ink amounts written again by [`ImageBlob::cmyk_tiff_at`] with the resolution
|
||||
/// `ppi`. `None` for other images and for CMYK TIFFs whose inks [`ImageBlob::cmyk`] doesn't read.
|
||||
/// doesn't read, their inks together in a CMYK TIFF with the resolution `ppi`, at the 8 or 16 bits
|
||||
/// the file has, carrying the file's CMYK ICC profile. `None` for other images and for CMYK TIFFs
|
||||
/// whose inks [`ImageBlob::cmyk`] doesn't read.
|
||||
pub fn stored_cmyk_tiff(bytes: &[u8], ppi: Option<(f64, f64)>) -> Option<Vec<u8>> {
|
||||
let inks = tiff_inks(bytes)?;
|
||||
let source = tiff_source(bytes)?;
|
||||
let (_, mut d) = tiff(bytes)?;
|
||||
if !planar(&mut d) {
|
||||
return Some(bytes.to_vec());
|
||||
}
|
||||
ImageBlob::cmyk_tiff_at(&inks, ppi).map(|b| Arc::unwrap_or_clone(b.bytes))
|
||||
write_cmyk_tiff(source.width, source.height, source.samples.as_slice(), ppi, source.icc.as_deref())
|
||||
}
|
||||
|
||||
/// CMYK JPEG or TIFF `bytes` that `orientation` turns or flips, as Open and Place store them: their
|
||||
/// ink amounts ([`ImageBlob::cmyk`], 8 bits each) turned and written again by
|
||||
/// [`ImageBlob::cmyk_tiff_at`] with the resolution `ppi` of the turned pixels, with the turned
|
||||
/// width and height. `None` for other images and for CMYK images whose inks [`ImageBlob::cmyk`]
|
||||
/// doesn't read.
|
||||
/// inks turned and written again as a CMYK TIFF with the resolution `ppi` of the turned pixels,
|
||||
/// with the turned width and height. A TIFF keeps its 8 or 16 bits, a JPEG has 8, and both keep
|
||||
/// their CMYK ICC profile (a JPEG's put together from all its APP2 segments). `None` for other
|
||||
/// images and for CMYK images whose inks [`ImageBlob::cmyk`] doesn't read.
|
||||
pub fn turned_cmyk(bytes: &[u8], orientation: image::metadata::Orientation, ppi: Option<(f64, f64)>) -> Option<(Vec<u8>, (u32, u32))> {
|
||||
let inks = if bytes.starts_with(&[0xFF, 0xD8]) { jpeg_inks(bytes) } else { tiff_inks(bytes) }?;
|
||||
// Four 8-bit inks to a pixel, turned as four 8-bit channels are.
|
||||
let mut px = image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(inks.width, inks.height, inks.data)?);
|
||||
let CmykSource { width, height, samples, icc } = if bytes.starts_with(&[0xFF, 0xD8]) { jpeg_source(bytes) } else { tiff_source(bytes) }?;
|
||||
// Four inks to a pixel, turned as four channels of the same depth are.
|
||||
let mut px = match samples {
|
||||
Samples::Eight(v) => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(width, height, v)?),
|
||||
Samples::Sixteen(v) => image::DynamicImage::ImageRgba16(image::ImageBuffer::from_raw(width, height, v)?),
|
||||
};
|
||||
px.apply_orientation(orientation);
|
||||
let inks = Inks::new(px.width(), px.height(), px.into_bytes())?;
|
||||
let tiff = ImageBlob::cmyk_tiff_at(&inks, ppi)?;
|
||||
Some((Arc::unwrap_or_clone(tiff.bytes), (inks.width, inks.height)))
|
||||
let size = (px.width(), px.height());
|
||||
let samples = match px {
|
||||
image::DynamicImage::ImageRgba16(v) => Samples::Sixteen(v.into_raw()),
|
||||
other => Samples::Eight(other.into_rgba8().into_raw()),
|
||||
};
|
||||
let tiff = write_cmyk_tiff(size.0, size.1, samples.as_slice(), ppi, icc.as_deref())?;
|
||||
Some((tiff, size))
|
||||
}
|
||||
|
||||
/// A TIFF whose pixels have samples after their colour, which the image decoder doesn't read at
|
||||
|
||||
@@ -286,7 +286,9 @@ impl Document {
|
||||
self.next_id = self.next_id.max(id);
|
||||
}
|
||||
|
||||
/// Ensure `next_id` is above every id in the tree (after deserializing foreign data).
|
||||
/// Ensure `next_id` is above every id in the tree (after deserializing foreign data), then give
|
||||
/// the objects outside the layer tree (opacity-mask art, symbols, graph designs and patterns)
|
||||
/// whose id is missing or already taken a new one, so each stored object has an id of its own.
|
||||
pub fn fix_next_id(&mut self) {
|
||||
// Ids from [`MAX_NEXT_ID`] up (a damaged or hand-made file: #1718) are left out, as is a
|
||||
// counter up there: new ids start under them and never reach them, where counting on from
|
||||
@@ -297,13 +299,12 @@ impl Document {
|
||||
max = max.max(id);
|
||||
}
|
||||
};
|
||||
for l in &self.layers {
|
||||
l.walk(&mut |n| see(n.id.0));
|
||||
}
|
||||
self.visit_stored(|n, _| see(n.id.0));
|
||||
self.slices.iter().for_each(|s| see(s.id.0));
|
||||
self.assets.iter().for_each(|a| see(a.id));
|
||||
let counter = Some(self.next_id).filter(|n| *n <= MAX_NEXT_ID).unwrap_or(0);
|
||||
self.next_id = counter.max(max.saturating_add(1));
|
||||
self.renumber_stored_duplicates();
|
||||
}
|
||||
|
||||
/// Find a node anywhere in the tree.
|
||||
|
||||
@@ -554,6 +554,13 @@ impl Document {
|
||||
t.cached_baselines.clear();
|
||||
t.cached_ink = None;
|
||||
}
|
||||
// Opacity-mask art is stored art too: the copy's gets ids of its own.
|
||||
if let Some(art) = n.extras().mask.as_ref().map(|m| Arc::clone(&m.art)) {
|
||||
let art = Arc::new(self.reid(&art));
|
||||
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) {
|
||||
m.art = art;
|
||||
}
|
||||
}
|
||||
let on_path = n.extras().objects_on_path.is_some();
|
||||
let mut renamed = std::collections::HashMap::new();
|
||||
if let Some(ch) = n.children_mut() {
|
||||
|
||||
@@ -33,8 +33,8 @@ pub use inline::{SYMBOL_HALF, SYMBOL_SIZES};
|
||||
pub use shared::Shared;
|
||||
pub use symbol_export_type::{SYMBOL_EXPORT_TYPE, SymbolExportType};
|
||||
pub use symbol_nine_slice::{
|
||||
EditedNineSlice, MAX_SLICE_GROWTH, MIN_CENTER_BAND, NineSliceGuide, NineSliceMap, PAINTED_EFFECTS, SYMBOL_NINE_SLICE, SymbolNineSlice,
|
||||
charge_symbol_art,
|
||||
EditedNineSlice, MAX_GUIDE_FRACTION, MAX_SLICE_GROWTH, MIN_CENTER_BAND, NineSliceGuide, NineSliceMap, PAINTED_EFFECTS, SYMBOL_NINE_SLICE,
|
||||
SymbolNineSlice, charge_symbol_art,
|
||||
};
|
||||
pub use symbol_overrides::SymbolOverride;
|
||||
pub use symbol_registration::{SYMBOL_REGISTRATION, SymbolRegistration};
|
||||
@@ -142,6 +142,7 @@ mod graphic_style;
|
||||
mod guides;
|
||||
mod limits;
|
||||
mod records;
|
||||
mod stored_art;
|
||||
mod units;
|
||||
|
||||
pub use artboard::{ARTBOARD_GAP, Artboard, ArtboardSide, LockedArtboards, RetiredArtboardId, VIDEO_PIXEL_ASPECT_RANGE, VIDEO_SAFE_INSETS};
|
||||
@@ -154,6 +155,7 @@ pub use guides::{GridPrefs, Guide, RulerMode};
|
||||
use limits::MAX_NEXT_ID;
|
||||
pub use limits::{DocError, FORMAT_VERSION, MAX_COORD};
|
||||
pub use records::{ImageBlob, MaskEdit, NewArtIds, SavedSelection, SavedView, SvgFilter, Symbol, SymbolEdit};
|
||||
pub use stored_art::{StoredPlace, StoredRoot};
|
||||
pub use units::{ColorMode, Unit, parse_number};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
@@ -265,8 +267,8 @@ pub struct Document {
|
||||
/// File → Document Setup (bleed, transparency grid, paper, type options).
|
||||
#[serde(default, skip_serializing_if = "skip::is_default")]
|
||||
pub setup: DocSetup,
|
||||
/// Layers panel → Paste Remembers Layers: pasted objects go back into the layers (by name)
|
||||
/// they were copied from instead of the current layer.
|
||||
/// Layers panel → Paste Remembers Layers: pasted objects go back into the layers and
|
||||
/// sublayers they were copied from instead of the current layer.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub paste_remembers_layers: bool,
|
||||
/// File → File Info (its title is [`Document::info_title`]).
|
||||
|
||||
+160
-16
@@ -39,7 +39,7 @@ fn fifty() -> f64 {
|
||||
// =====================================================================================
|
||||
|
||||
pub use crate::blend::{
|
||||
Spine, blend_expand, blend_spine, blend_step_count, lerp_appearance, lerp_color, lerp_node, lerp_paint, lerp_path, pin_spine,
|
||||
Spine, blend_expand, blend_layout_line, blend_spine, blend_step_count, lerp_appearance, lerp_color, lerp_node, lerp_paint, lerp_path, pin_spine,
|
||||
steps_knockout_shows,
|
||||
};
|
||||
|
||||
@@ -55,7 +55,7 @@ use blend_spec::{blend_color_shift, blend_ramp};
|
||||
pub use envelope::{
|
||||
EnvelopeKind, EnvelopeMap, EnvelopeOptions, H_DOWN, H_LEFT, H_RIGHT, H_UP, PreserveShape, TypeInk, envelope_bounds, envelope_content_bounds,
|
||||
envelope_content_boxes, envelope_expand, envelope_frame, envelope_grid, envelope_mapper, envelope_of, envelope_overlay, envelope_stroke_margin,
|
||||
set_type_ink, smooth_handles,
|
||||
set_type_ink, smooth_handles, warp_grid,
|
||||
};
|
||||
pub(crate) use expand::max_outset;
|
||||
pub use expand::{
|
||||
@@ -568,23 +568,167 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The outline of a 200 × 100 box whose top side is `pieces`, end to end from (0, 0) to
|
||||
/// (200, 0), and whose other sides are straight.
|
||||
fn top_of_pieces(pieces: &[CubicBez]) -> PathData {
|
||||
let pt = |p: Point| (p.x, p.y);
|
||||
let mut knots: Vec<Knot> = vec![];
|
||||
for (k, c) in pieces.iter().enumerate() {
|
||||
let h_in = if k == 0 { pt(c.p0) } else { pt(pieces[k - 1].p2) };
|
||||
knots.push((pt(c.p0), h_in, pt(c.p1)));
|
||||
}
|
||||
let last = pieces.last().unwrap();
|
||||
knots.push(((200.0, 0.0), pt(last.p2), (200.0, 0.0)));
|
||||
knots.extend([((200.0, 100.0), (200.0, 100.0), (200.0, 100.0)), ((0.0, 100.0), (0.0, 100.0), (0.0, 100.0))]);
|
||||
outline(&knots)
|
||||
}
|
||||
|
||||
/// A top curve whose parameter runs fast at its start and slow at its end.
|
||||
const UNEVEN_TOP: CubicBez =
|
||||
CubicBez { p0: Point::new(0.0, 0.0), p1: Point::new(120.0, -60.0), p2: Point::new(190.0, -30.0), p3: Point::new(200.0, 0.0) };
|
||||
|
||||
#[test]
|
||||
fn a_split_curve_moves_the_top_object_share_to_its_new_anchor() {
|
||||
// Splitting the top curve at t = 0.3 keeps its shape but changes the polygon shares: the
|
||||
// new anchor lands at the first piece's share, not at u = 0.3.
|
||||
let top = CubicBez::new((0.0, 0.0), (40.0, -40.0), (160.0, -40.0), (200.0, 0.0));
|
||||
let (a, b) = (top.subsegment(0.0..0.3), top.subsegment(0.3..1.0));
|
||||
let path = outline(&[
|
||||
((0.0, 0.0), (0.0, 0.0), a.p1.into()),
|
||||
(a.p3.into(), a.p2.into(), b.p1.into()),
|
||||
((200.0, 0.0), b.p2.into(), (200.0, 0.0)),
|
||||
((200.0, 100.0), (200.0, 100.0), (200.0, 100.0)),
|
||||
((0.0, 100.0), (0.0, 100.0), (0.0, 100.0)),
|
||||
]);
|
||||
let c = Coons::from_top_object(&path, None).unwrap();
|
||||
fn a_split_curve_keeps_the_top_object_patch() {
|
||||
// Splitting the top curve at t = 0.3, or into thirds, keeps its shape, and the patch stays
|
||||
// the unsplit curve's: the new anchors land at u = 0.3, 1/3 and 2/3 (to within how finely
|
||||
// the side is sampled), where the pieces' control polygons would have put them several
|
||||
// points away.
|
||||
let whole = Coons::from_top_object(&top_of_pieces(&[UNEVEN_TOP]), None).unwrap();
|
||||
for cuts in [vec![0.3], vec![1.0 / 3.0, 2.0 / 3.0]] {
|
||||
let ends: Vec<f64> = std::iter::once(0.0).chain(cuts.iter().copied()).chain([1.0]).collect();
|
||||
let pieces: Vec<CubicBez> = ends.windows(2).map(|w| UNEVEN_TOP.subsegment(w[0]..w[1])).collect();
|
||||
let c = Coons::from_top_object(&top_of_pieces(&pieces), None).unwrap();
|
||||
let total: f64 = pieces.iter().map(|p| polygon(*p)).sum();
|
||||
for (k, t) in cuts.iter().enumerate() {
|
||||
let anchor = pieces[k].p3;
|
||||
assert!(c.eval(*t, 0.0).distance(anchor) < 0.02, "{cuts:?}: u {t} → {:?}, want {anchor:?}", c.eval(*t, 0.0));
|
||||
let share: f64 = pieces[..=k].iter().map(|p| polygon(*p)).sum::<f64>() / total;
|
||||
assert!(c.eval(share, 0.0).distance(anchor) > 2.0, "{cuts:?}: the polygon share {share} lands on the anchor");
|
||||
}
|
||||
for (u, v) in [(0.1, 0.0), (0.3, 0.2), (0.5, 0.5), (0.62, 0.0), (0.9, 0.7), (0.97, 1.0)] {
|
||||
let (p, q) = (c.eval(u, v), whole.eval(u, v));
|
||||
assert!(p.distance(q) < 1e-9, "{cuts:?}: ({u}, {v}) → {p:?}, unsplit {q:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_split_curve_keeps_the_top_object_patch_when_split_at_a_cusp() {
|
||||
// The top curve stops at t = 0.25 (a cusp), and an anchor splits it there: both handles at
|
||||
// the split lie on the anchor, and the patch with the corners given stays the unsplit
|
||||
// curve's.
|
||||
let cusp = CubicBez::new((0.0, 0.0), (30.0, -40.0), (-58.0, 24.0), (200.0, 0.0));
|
||||
let pieces = [cusp.subsegment(0.0..0.25), cusp.subsegment(0.25..1.0)];
|
||||
assert!(pieces[0].p2.distance(pieces[0].p3) < 1e-9 && pieces[1].p1.distance(pieces[1].p0) < 1e-9);
|
||||
let whole = Coons::from_top_object(&top_of_pieces(&[cusp]), Some([0, 1, 2, 3])).unwrap();
|
||||
let c = Coons::from_top_object(&top_of_pieces(&pieces), Some([0, 2, 3, 4])).unwrap();
|
||||
for (u, v) in [(0.1, 0.0), (0.25, 0.0), (0.3, 0.2), (0.5, 0.5), (0.62, 0.0), (0.9, 0.7), (0.97, 1.0)] {
|
||||
let (p, q) = (c.eval(u, v), whole.eval(u, v));
|
||||
assert!(p.distance(q) < 1e-6, "({u}, {v}) → {p:?}, unsplit {q:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_split_curve_keeps_the_top_object_patch_where_it_barely_moves_and_runs_straight() {
|
||||
// A straight top curve that barely moves at t = 0.25 and doesn't bend there: split there,
|
||||
// the handles at the split are a few thousandths of a point long and the pieces don't bend
|
||||
// at all, and the patch with the corners given stays the unsplit curve's.
|
||||
let slow = CubicBez::new((0.0, 0.0), (28.578125, 0.0), (-57.109375, 0.0), (200.0, 0.0));
|
||||
let pieces = [slow.subsegment(0.0..0.25), slow.subsegment(0.25..1.0)];
|
||||
let (into, out) = (pieces[0].p3.distance(pieces[0].p2), pieces[1].p0.distance(pieces[1].p1));
|
||||
assert!(into > 0.0 && out > 0.0 && into.max(out) < 0.01, "{into} {out}");
|
||||
let whole = Coons::from_top_object(&top_of_pieces(&[slow]), Some([0, 1, 2, 3])).unwrap();
|
||||
let c = Coons::from_top_object(&top_of_pieces(&pieces), Some([0, 2, 3, 4])).unwrap();
|
||||
for (u, v) in [(0.1, 0.0), (0.25, 0.0), (0.3, 0.2), (0.5, 0.5), (0.62, 0.0), (0.9, 0.7), (0.97, 1.0)] {
|
||||
let (p, q) = (c.eval(u, v), whole.eval(u, v));
|
||||
assert!(p.distance(q) < 1e-6, "({u}, {v}) → {p:?}, unsplit {q:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_top_object_joins_a_split_curve_saved_with_rounded_coordinates() {
|
||||
// A file saves the pieces of a curve split into thirds, or into tenths, with its
|
||||
// coordinates rounded to 0.001 pt, on an outline 5, 200 or 5,000 pt wide: the side is
|
||||
// still that curve, to within 0.02 pt.
|
||||
let round = |p: Point| Point::new((p.x * 1000.0).round() / 1000.0, (p.y * 1000.0).round() / 1000.0);
|
||||
for cuts in [3u32, 10] {
|
||||
let pieces: Vec<CubicBez> =
|
||||
(0..cuts).map(|k| UNEVEN_TOP.subsegment(f64::from(k) / f64::from(cuts)..f64::from(k + 1) / f64::from(cuts))).collect();
|
||||
for scale in [0.025, 1.0, 25.0] {
|
||||
let mut split = top_of_pieces(&pieces);
|
||||
split.transform(Affine::scale(scale));
|
||||
for a in split.subpaths.iter_mut().flat_map(|sp| sp.anchors.iter_mut()) {
|
||||
(a.p, a.h_in, a.h_out) = (round(a.p), round(a.h_in), round(a.h_out));
|
||||
}
|
||||
let mut whole = top_of_pieces(&[UNEVEN_TOP]);
|
||||
whole.transform(Affine::scale(scale));
|
||||
let (c, whole) = (Coons::from_top_object(&split, None).unwrap(), Coons::from_top_object(&whole, None).unwrap());
|
||||
for (u, v) in [(1.0 / 6.0, 0.0), (1.0 / 3.0, 0.0), (0.45, 0.0), (0.5, 0.5), (2.0 / 3.0, 0.0), (0.9, 0.3)] {
|
||||
let (p, q) = (c.eval(u, v), whole.eval(u, v));
|
||||
assert!(p.distance(q) < 0.02, "{cuts} pieces at {scale}x: ({u}, {v}) → {p:?}, unsplit {q:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_top_object_keeps_smoothly_joined_curves_apart() {
|
||||
// The top side's second piece leaves the split anchor in line with the first piece's
|
||||
// handle, but its far handle is 1 pt off the split curve's: the pieces are two curves, and
|
||||
// each takes the share of its control polygon.
|
||||
let (a, b) = (UNEVEN_TOP.subsegment(0.0..0.3), UNEVEN_TOP.subsegment(0.3..1.0));
|
||||
let b = CubicBez::new(b.p0, b.p1, b.p2 + Vec2::new(0.0, 1.0), b.p3);
|
||||
let c = Coons::from_top_object(&top_of_pieces(&[a, b]), None).unwrap();
|
||||
let share = polygon(a) / (polygon(a) + polygon(b));
|
||||
assert!(c.eval(share, 0.0).distance(a.p3) < 1e-9, "{:?}", c.eval(share, 0.0));
|
||||
assert!((share - 0.3).abs() > 0.01, "{share}");
|
||||
assert!((share - 0.3).abs() > 0.02, "{share}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_top_object_side_partly_of_one_curve_keeps_the_polygon_shares() {
|
||||
// The top side is a curve split at t = 0.3, then a straight segment: not all of it is one
|
||||
// curve, so each piece keeps the share of its control polygon.
|
||||
let curve = CubicBez::new((0.0, 0.0), (90.0, -45.0), (142.5, -22.5), (150.0, 0.0));
|
||||
let (a, b) = (curve.subsegment(0.0..0.3), curve.subsegment(0.3..1.0));
|
||||
let line = CubicBez::new((150.0, 0.0), (150.0 + 50.0 / 3.0, 0.0), (200.0 - 50.0 / 3.0, 0.0), (200.0, 0.0));
|
||||
let c = Coons::from_top_object(&top_of_pieces(&[a, b, line]), None).unwrap();
|
||||
let share = polygon(a) / (polygon(a) + polygon(b) + polygon(line));
|
||||
assert!(c.eval(share, 0.0).distance(a.p3) < 1e-9, "{:?}", c.eval(share, 0.0));
|
||||
// Joined into their curve, the two pieces would have put the anchor 0.3 of the way along
|
||||
// their part of the side.
|
||||
let joined = 0.3 * (polygon(a) + polygon(b)) / (polygon(a) + polygon(b) + polygon(line));
|
||||
assert!(c.eval(joined, 0.0).distance(a.p3) > 1.0, "{share} vs {joined}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_top_object_side_of_many_arcs_stays_on_them() {
|
||||
// A 120° arc of radius 500 drawn as `n` circular arcs, each close to a piece of one cubic
|
||||
// while the whole arc is not one: the side stays on the circle, and the content's middle
|
||||
// stays on the middle anchor, as the arcs' polygon shares put it.
|
||||
let centre = Point::new(300.0, 600.0);
|
||||
for n in [64u32, 128, 256] {
|
||||
let step = 120f64.to_radians() / f64::from(n);
|
||||
let reach = 500.0 * 4.0 / 3.0 * (step / 4.0).tan();
|
||||
let on = |a: f64| centre + Vec2::new(a.cos(), a.sin()) * 500.0;
|
||||
let tangent = |a: f64| Vec2::new(-a.sin(), a.cos()) * reach;
|
||||
let mut anchors: Vec<Anchor> = (0..=n)
|
||||
.map(|i| {
|
||||
let a = (-150f64).to_radians() + step * f64::from(i);
|
||||
let p = on(a);
|
||||
let h_in = if i == 0 { p } else { p - tangent(a) };
|
||||
let h_out = if i == n { p } else { p + tangent(a) };
|
||||
Anchor { p, h_in, h_out, ..Anchor::corner(p) }
|
||||
})
|
||||
.collect();
|
||||
let (start, end) = (on((-150f64).to_radians()), on((-30f64).to_radians()));
|
||||
anchors.extend([Anchor::corner(Point::new(end.x, 800.0)), Anchor::corner(Point::new(start.x, 800.0))]);
|
||||
let path = PathData::single(SubPath::new(anchors, true));
|
||||
let c = Coons::from_top_object(&path, Some([0, n, n + 1, n + 2])).unwrap();
|
||||
let off = (0..=4000).map(|k| (c.eval(f64::from(k) / 4000.0, 0.0).distance(centre) - 500.0).abs()).fold(0.0, f64::max);
|
||||
assert!(off < 0.001, "{n} arcs: the side lies {off} pt off the circle");
|
||||
let mid = c.eval(0.5, 0.0);
|
||||
assert!(mid.distance(Point::new(300.0, 100.0)) < 0.001, "{n} arcs: the middle lands at {mid:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -525,21 +525,106 @@ pub fn envelope_of(doc: &crate::Document, id: NodeId) -> Option<&Node> {
|
||||
doc.ancestry(id)?.into_iter().rev().find_map(|a| doc.node(a).filter(|n| matches!(n.kind, NodeKind::Envelope { .. })))
|
||||
}
|
||||
|
||||
/// What a selected envelope shows on the canvas: its mesh lines (a warp's surface on a 4×4 grid,
|
||||
/// a mesh envelope's own grid) or its top object's outline, and for a mesh envelope the grid to
|
||||
/// edit (its points and handles).
|
||||
/// What a selected envelope shows on the canvas: its mesh lines (a warp's surface on its
|
||||
/// [`warp_grid`], a mesh envelope's own grid) or its top object's outline, and for a warp or mesh
|
||||
/// envelope the grid to edit (its points and handles; none while its contents are edited).
|
||||
pub fn envelope_overlay(n: &Node) -> Option<(PathData, Option<GradientMesh>)> {
|
||||
let NodeKind::Envelope { kind, .. } = &n.kind else { return None };
|
||||
let NodeKind::Envelope { kind, editing, .. } = &n.kind else { return None };
|
||||
let points = |grid: GradientMesh| (!*editing).then_some(grid);
|
||||
match &**kind {
|
||||
EnvelopeKind::Mesh { rows, cols, points, handles } => {
|
||||
let grid = envelope_grid(*rows, *cols, points, handles)?;
|
||||
Some((grid.lines(), Some(grid)))
|
||||
EnvelopeKind::Mesh { rows, cols, points: at, handles } => {
|
||||
let grid = envelope_grid(*rows, *cols, at, handles)?;
|
||||
Some((grid.lines(), points(grid)))
|
||||
}
|
||||
EnvelopeKind::Warp { .. } => Some((EnvelopeMap::of(n)?.surface_mesh(4, 4, Color::BLACK).lines(), None)),
|
||||
EnvelopeKind::Warp { .. } => match warp_grid(n) {
|
||||
Some(grid) => Some((grid.lines(), points(grid))),
|
||||
None => Some((EnvelopeMap::of(n)?.surface_mesh(4, 4, Color::BLACK).lines(), None)),
|
||||
},
|
||||
EnvelopeKind::TopObject { path, .. } => Some((path.clone(), None)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The grid sizes [`warp_grid`] tries, in order: patches per row and per column.
|
||||
const WARP_GRIDS: [u32; 3] = [4, 8, 16];
|
||||
|
||||
/// How far a [`warp_grid`] may draw from the warp it replaces, as a share of the diagonal of the
|
||||
/// warp's bounds.
|
||||
const WARP_GRID_TOLERANCE: f64 = 1e-3;
|
||||
|
||||
/// The grid a warp envelope's points and handles are edited on: its surface sampled on the first
|
||||
/// of 4×4, 8×8 and 16×16 patches whose curves draw within [`WARP_GRID_TOLERANCE`] of the warp, with
|
||||
/// handles along it, as a gradient mesh with black points. Editing a point makes the envelope a
|
||||
/// mesh envelope with this grid. `None` for other nodes, for content with no bounds, and for a warp
|
||||
/// that no such grid follows closely enough or whose grid isn't finite.
|
||||
/// Built again only when the envelope's content objects, warp, frame or options change, or what
|
||||
/// type is measured with ([`set_type_ink`]).
|
||||
pub fn warp_grid(n: &Node) -> Option<GradientMesh> {
|
||||
let NodeKind::Envelope { content, kind, frame, options, .. } = &n.kind else { return None };
|
||||
if !matches!(**kind, EnvelopeKind::Warp { .. }) {
|
||||
return None;
|
||||
}
|
||||
// `None` until a measure is registered, so a grid kept before then is built again after.
|
||||
let inputs = TYPE_INK.get().map(|(_, inputs)| inputs());
|
||||
let key: Vec<usize> = content.iter().map(|c| Arc::as_ptr(c) as usize).collect();
|
||||
let same = |k: &KeptGrid| k.kind == **kind && k.frame == **frame && k.options == *options && k.inputs == inputs;
|
||||
if let Some(grid) = WARP_GRIDS_KEPT.with_borrow(|kept| kept.get(&key).filter(|k| same(k)).map(|k| k.grid.clone())) {
|
||||
return grid;
|
||||
}
|
||||
let grid = build_warp_grid(n);
|
||||
WARP_GRIDS_KEPT.with_borrow_mut(|kept| {
|
||||
if kept.len() >= WARP_GRID_KEPT {
|
||||
// Entries for content that no longer exists go first, then one entry at a time.
|
||||
kept.retain(|_, k| k.content.iter().all(|c| c.strong_count() > 0));
|
||||
if kept.len() >= WARP_GRID_KEPT
|
||||
&& let Some(any) = kept.keys().next().cloned()
|
||||
{
|
||||
kept.remove(&any);
|
||||
}
|
||||
}
|
||||
// The weak pointers keep the content's addresses from being reused while the entry is kept.
|
||||
let kept_content = content.iter().map(Arc::downgrade).collect();
|
||||
kept.insert(key, KeptGrid { content: kept_content, kind: (**kind).clone(), frame: **frame, options: *options, inputs, grid: grid.clone() });
|
||||
});
|
||||
grid
|
||||
}
|
||||
|
||||
/// A grid [`warp_grid`] built, with what it was built from.
|
||||
struct KeptGrid {
|
||||
content: Vec<std::sync::Weak<Node>>,
|
||||
kind: EnvelopeKind,
|
||||
frame: Affine,
|
||||
options: EnvelopeOptions,
|
||||
inputs: Option<u64>,
|
||||
grid: Option<GradientMesh>,
|
||||
}
|
||||
|
||||
/// How many grids [`warp_grid`] keeps on one thread.
|
||||
const WARP_GRID_KEPT: usize = 1024;
|
||||
|
||||
std::thread_local! {
|
||||
/// The grids [`warp_grid`] built on this thread, by the addresses of their envelopes' content.
|
||||
static WARP_GRIDS_KEPT: std::cell::RefCell<std::collections::HashMap<Vec<usize>, KeptGrid>> = Default::default();
|
||||
}
|
||||
|
||||
/// [`warp_grid`], built from scratch.
|
||||
fn build_warp_grid(n: &Node) -> Option<GradientMesh> {
|
||||
let map = EnvelopeMap::of(n)?;
|
||||
let bounds = map.bounds()?;
|
||||
let tol = bounds.width().hypot(bounds.height()) * WARP_GRID_TOLERANCE;
|
||||
if !tol.is_finite() {
|
||||
return None;
|
||||
}
|
||||
WARP_GRIDS.into_iter().find_map(|k| {
|
||||
let m = map.surface_mesh(k, k, Color::BLACK);
|
||||
let finite = m.points.iter().all(|q| q.p.is_finite() && q.handles.iter().all(|h| h.is_finite()));
|
||||
// Each patch is checked at its corners, the middles of its sides and its middle.
|
||||
let steps = 2 * k as usize;
|
||||
let at = |i: usize| i as f64 / steps as f64;
|
||||
let fits = || (0..=steps).all(|j| (0..=steps).all(|i| mesh_at(&m, at(i), at(j)).distance(map.at(at(i), at(j))) <= tol));
|
||||
(finite && fits()).then_some(m)
|
||||
})
|
||||
}
|
||||
|
||||
/// The frame an envelope keeps after transform `m` (its frame so far composed with the
|
||||
/// transform): identity when its axes stay square to the page, unflipped, since evaluating on
|
||||
/// the page axes gives the same result then.
|
||||
@@ -760,6 +845,163 @@ mod tests {
|
||||
assert!(content_box(&nested, false, Affine::IDENTITY).is_some());
|
||||
}
|
||||
|
||||
/// A warp envelope of `style` at `bend` with map `version` around a 200×100 rectangle at
|
||||
/// (100, 50).
|
||||
fn warp_node(style: &str, bend: f64, h: f64, version: u32) -> Node {
|
||||
let rect = vectorcraft_geom::shapes::rectangle(Rect::new(100.0, 50.0, 300.0, 150.0));
|
||||
let content = Arc::new(Node::path(NodeId(1), rect, crate::Appearance::default_art()));
|
||||
let kind = EnvelopeKind::Warp { style: style.into(), bend, h, v: 0.0, horizontal: true, version };
|
||||
Node::new(
|
||||
NodeId(2),
|
||||
NodeKind::Envelope {
|
||||
content: vec![content],
|
||||
kind: Box::new(kind),
|
||||
fidelity: 50.0,
|
||||
editing: false,
|
||||
options: EnvelopeOptions::NEW,
|
||||
frame: Box::new(Affine::IDENTITY),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
const STYLES: [&str; 15] = [
|
||||
"arc",
|
||||
"arcLower",
|
||||
"arcUpper",
|
||||
"arch",
|
||||
"bulge",
|
||||
"shellLower",
|
||||
"shellUpper",
|
||||
"flag",
|
||||
"wave",
|
||||
"fish",
|
||||
"rise",
|
||||
"fisheye",
|
||||
"inflate",
|
||||
"squeeze",
|
||||
"twist",
|
||||
];
|
||||
|
||||
/// Every warp style's Bézier net has a grid to edit: its points lie on the warp, and the grid
|
||||
/// draws within a thousandth of the warp's diagonal of it, between the grid lines too. The
|
||||
/// overlay shows that grid's lines and points.
|
||||
#[test]
|
||||
fn every_warp_style_has_a_grid_that_keeps_its_shape() {
|
||||
for style in STYLES {
|
||||
for (bend, h) in [(50.0, 0.0), (100.0, 0.0), (-100.0, 60.0)] {
|
||||
let n = warp_node(style, bend, h, crate::live::WARP_NET);
|
||||
let grid = warp_grid(&n).unwrap_or_else(|| panic!("{style} {bend} {h}: no grid"));
|
||||
assert!(WARP_GRIDS.contains(&grid.rows) && grid.rows == grid.cols, "{style}: {}×{}", grid.rows, grid.cols);
|
||||
let map = EnvelopeMap::of(&n).unwrap();
|
||||
let b = map.bounds().unwrap();
|
||||
let tol = b.width().hypot(b.height()) * 1e-3;
|
||||
let k = grid.cols as usize;
|
||||
for (i, q) in grid.points.iter().enumerate() {
|
||||
let want = map.at((i % (k + 1)) as f64 / k as f64, (i / (k + 1)) as f64 / k as f64);
|
||||
assert!(q.p.distance(want) < 1e-9, "{style}: point {i} at {:?}, the warp at {want:?}", q.p);
|
||||
}
|
||||
for j in 0..=20 {
|
||||
for i in 0..=20 {
|
||||
let (u, v) = (i as f64 / 20.0, j as f64 / 20.0);
|
||||
let off = mesh_at(&grid, u, v).distance(map.at(u, v));
|
||||
assert!(off <= tol, "{style} {bend} {h}: {off} off at ({u}, {v})");
|
||||
}
|
||||
}
|
||||
let (lines, shown) = envelope_overlay(&n).unwrap();
|
||||
assert_eq!(shown.as_ref(), Some(&grid), "{style}");
|
||||
assert_eq!(lines, grid.lines(), "{style}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A kept warp grid is built again when the content, the warp, the frame or the options change,
|
||||
/// and is the grid built from scratch otherwise.
|
||||
#[test]
|
||||
fn a_kept_warp_grid_follows_changes() {
|
||||
let n = warp_node("arc", 50.0, 0.0, crate::live::WARP_NET);
|
||||
let first = warp_grid(&n);
|
||||
assert!(first.is_some());
|
||||
assert_eq!(warp_grid(&n), first);
|
||||
assert_eq!(build_warp_grid(&n), first);
|
||||
let changed = |f: &dyn Fn(&mut Node)| {
|
||||
let mut m = n.clone();
|
||||
f(&mut m);
|
||||
let grid = warp_grid(&m);
|
||||
assert_eq!(grid, build_warp_grid(&m));
|
||||
assert_ne!(grid, first);
|
||||
};
|
||||
changed(&|m| {
|
||||
if let NodeKind::Envelope { content, .. } = &mut m.kind {
|
||||
Arc::make_mut(&mut content[0]).transform(Affine::translate((40.0, 0.0)), true);
|
||||
}
|
||||
});
|
||||
changed(&|m| {
|
||||
if let NodeKind::Envelope { kind, .. } = &mut m.kind
|
||||
&& let EnvelopeKind::Warp { bend, .. } = &mut **kind
|
||||
{
|
||||
*bend = -30.0;
|
||||
}
|
||||
});
|
||||
changed(&|m| {
|
||||
if let NodeKind::Envelope { frame, .. } = &mut m.kind {
|
||||
**frame = Affine::rotate(0.3);
|
||||
}
|
||||
});
|
||||
changed(&|m| {
|
||||
if let NodeKind::Envelope { options, .. } = &mut m.kind {
|
||||
options.bounds_margin = [0.1; 4];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// The table of kept warp grids stays bounded: full of envelopes that still exist, it drops one
|
||||
/// entry at a time instead of emptying, and it drops the entries of envelopes that are gone
|
||||
/// first.
|
||||
#[test]
|
||||
fn the_kept_warp_grids_stay_bounded() {
|
||||
let nodes: Vec<Node> = (0..WARP_GRID_KEPT + 10).map(|i| warp_node("arc", (i % 100) as f64, 0.0, crate::live::WARP_NET)).collect();
|
||||
for n in &nodes {
|
||||
assert!(warp_grid(n).is_some());
|
||||
}
|
||||
assert_eq!(WARP_GRIDS_KEPT.with_borrow(|kept| kept.len()), WARP_GRID_KEPT);
|
||||
// Once the envelopes are gone, their entries are the ones dropped.
|
||||
drop(nodes);
|
||||
assert!(warp_grid(&warp_node("arc", 10.0, 0.0, crate::live::WARP_NET)).is_some());
|
||||
assert_eq!(WARP_GRIDS_KEPT.with_borrow(|kept| kept.len()), 1);
|
||||
}
|
||||
|
||||
/// A warp drawn by the old point map that no grid of up to 16×16 patches follows closely
|
||||
/// enough, content without bounds and other envelopes have no warp grid; the overlay still
|
||||
/// draws the old warp's lines. While an envelope's contents are edited, it shows no points.
|
||||
#[test]
|
||||
fn a_warp_no_grid_follows_has_no_grid_to_edit() {
|
||||
let n = warp_node("fisheye", 100.0, 0.0, 0);
|
||||
assert!(warp_grid(&n).is_none());
|
||||
let (lines, grid) = envelope_overlay(&n).unwrap();
|
||||
assert!(grid.is_none());
|
||||
assert!(lines.anchor_count() > 0);
|
||||
// The same style on its Bézier net has one.
|
||||
assert!(warp_grid(&warp_node("fisheye", 100.0, 0.0, crate::live::WARP_NET)).is_some());
|
||||
let mut empty = warp_node("arc", 50.0, 0.0, crate::live::WARP_NET);
|
||||
if let NodeKind::Envelope { content, .. } = &mut empty.kind {
|
||||
content.clear();
|
||||
}
|
||||
assert!(warp_grid(&empty).is_none());
|
||||
let mut mesh = warp_node("arc", 50.0, 0.0, crate::live::WARP_NET);
|
||||
if let NodeKind::Envelope { kind, .. } = &mut mesh.kind {
|
||||
**kind = EnvelopeKind::Mesh { rows: 1, cols: 1, points: grid_points(Rect::new(0.0, 0.0, 1.0, 1.0), 1, 1), handles: vec![] };
|
||||
}
|
||||
assert!(warp_grid(&mesh).is_none());
|
||||
// While the contents are edited, a warp's and a mesh envelope's lines show without points.
|
||||
for mut n in [warp_node("arc", 50.0, 0.0, crate::live::WARP_NET), mesh] {
|
||||
if let NodeKind::Envelope { editing, .. } = &mut n.kind {
|
||||
*editing = true;
|
||||
}
|
||||
let (lines, grid) = envelope_overlay(&n).unwrap();
|
||||
assert!(grid.is_none() && lines.anchor_count() > 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// A table that fills up is emptied instead of growing, and what is looked up after that is
|
||||
/// measured again.
|
||||
#[test]
|
||||
|
||||
+93
-15
@@ -147,14 +147,18 @@ impl Coons {
|
||||
/// The patch of a top object's outline (the largest subpath of `path`), split into four sides
|
||||
/// at its corners. Each piece of a side between two anchors or corners takes a share of `u` or
|
||||
/// `v` in proportion to the length of its control polygon, spread along the piece by its own
|
||||
/// curve parameter. A segment without handles counts as a cubic with its handles a third of
|
||||
/// the way along, so the content spreads evenly along it. `corners` are the anchors (indices
|
||||
/// into the outline, in its own order) at the top left, top right, bottom right and bottom
|
||||
/// left, as a saved file gives them. They stay on those anchors when they run the way the
|
||||
/// outline does or the opposite way, so a reflected outline keeps them; without them, or when
|
||||
/// they don't fit the outline, each corner is found from the outline ([`top_object_corner`]).
|
||||
/// A straight segment closes an open subpath, and segments of no length are left out. A top
|
||||
/// object's envelope maps onto this patch.
|
||||
/// curve parameter. A side whose pieces, from corner to corner, are all one cubic curve split at
|
||||
/// anchors (each within 0.02 pt of that curve's piece) runs along that curve instead, by its
|
||||
/// parameter: splitting the curve of such a side at more anchors, without changing its shape,
|
||||
/// leaves how the side shares out the content as it was (corners found from the outline can
|
||||
/// still move). A segment without handles counts as a cubic with its handles a third of the way
|
||||
/// along, so the content spreads evenly along it. `corners` are the anchors (indices into the
|
||||
/// outline, in its own order) at the top left, top right, bottom right and bottom left, as a
|
||||
/// saved file gives them. They stay on those anchors when they run the way the outline does or
|
||||
/// the opposite way, so a reflected outline keeps them; without them, or when they don't fit
|
||||
/// the outline, each corner is found from the outline ([`top_object_corner`]). A straight
|
||||
/// segment closes an open subpath, and segments of no length are left out. A top object's
|
||||
/// envelope maps onto this patch.
|
||||
pub fn from_top_object(path: &PathData, corners: Option<[u32; 4]>) -> Option<Self> {
|
||||
let sp = path.subpaths.iter().filter(|s| s.anchors.len() >= 2).max_by(|a, b| a.area().abs().total_cmp(&b.area().abs()))?;
|
||||
let mut sp = sp.clone();
|
||||
@@ -212,11 +216,12 @@ impl Coons {
|
||||
segs.get(i).map_or(Point::ZERO, |(c, _)| c.eval((s - i as f64).clamp(0.0, 1.0)))
|
||||
};
|
||||
// The side from `a` to `b`: its points, and where along it (0 to 1) each lies. It runs
|
||||
// through pieces of segments, split at `a` and `b`. Each piece takes its share of the side
|
||||
// by the length of its control polygon and holds points at even steps of its parameter
|
||||
// (at least 16, and at least `SIDE` points on the side), its ends included. A side of
|
||||
// many pieces takes fewer points in each, so it holds at most `MAX_SIDE_POINTS` points,
|
||||
// or one for each piece when it has more pieces than that.
|
||||
// through pieces of segments, split at `a` and `b`; when all of them are one curve split
|
||||
// at anchors ([`one_curve`]), it runs along that curve instead. Each piece takes its share
|
||||
// of the side by the length of its control polygon and holds points at even steps of its
|
||||
// parameter (at least 16, and at least `SIDE` points on the side), its ends included. A
|
||||
// side of many pieces takes fewer points in each, so it holds at most `MAX_SIDE_POINTS`
|
||||
// points, or one for each piece when it has more pieces than that.
|
||||
let side = |a: f64, b: f64| {
|
||||
let span = (b - a).rem_euclid(n);
|
||||
if !(span.is_finite() && span > 0.0) {
|
||||
@@ -232,8 +237,11 @@ impl Coons {
|
||||
}
|
||||
s = next;
|
||||
}
|
||||
let polygon = |c: &CubicBez| c.p0.distance(c.p1) + c.p1.distance(c.p2) + c.p2.distance(c.p3);
|
||||
let mut weights: Vec<f64> = pieces.iter().map(polygon).collect();
|
||||
let pieces = match one_curve(&pieces) {
|
||||
Some(one) => vec![one],
|
||||
None => pieces,
|
||||
};
|
||||
let mut weights: Vec<f64> = pieces.iter().map(control_polygon).collect();
|
||||
let mut total: f64 = weights.iter().sum();
|
||||
if !(total.is_finite() && total > 0.0) {
|
||||
weights.iter_mut().for_each(|w| *w = 1.0);
|
||||
@@ -336,6 +344,76 @@ impl Coons {
|
||||
/// anchors.
|
||||
const MAX_SIDE_POINTS: usize = 1 << 16;
|
||||
|
||||
/// How far, in points, each control point of each piece of a top object's side may lie from the
|
||||
/// matching piece of one cubic curve for the side to run along that curve ([`one_curve`]); the side
|
||||
/// then lies within this of the pieces it is drawn with. A curve split into thirds or tenths and
|
||||
/// saved with its coordinates rounded to 0.001 pt stays within it, on outlines from 5 to 5,000 pt
|
||||
/// wide; coarser rounding, or a piece of a much smaller share of the curve, can take it past this.
|
||||
/// A smooth side that isn't one curve, such as an arc of a circle drawn in many pieces, lies
|
||||
/// further off as a whole, even where each pair of its pieces would not.
|
||||
const ONE_CURVE: f64 = 0.02;
|
||||
|
||||
/// The length of `c`'s control polygon.
|
||||
fn control_polygon(c: &CubicBez) -> f64 {
|
||||
c.p0.distance(c.p1) + c.p1.distance(c.p2) + c.p2.distance(c.p3)
|
||||
}
|
||||
|
||||
/// The cubic curve that `pieces`, two or more end to end, are all pieces of, split at the anchors
|
||||
/// between them, when each control point of each piece lies within [`ONE_CURVE`] of the matching
|
||||
/// piece of that curve; `None` otherwise. Split at parameter `t`, a curve's handles on either side
|
||||
/// of the split lie in line, their lengths in proportion to the spans of its parameter the two
|
||||
/// pieces take; split where the curve stops (a cusp), both handles lie on the anchor, and the
|
||||
/// pieces' second derivatives there, in proportion to the squares of the spans, give the proportion
|
||||
/// instead (whichever of the two pairs is the longer). Those proportions give each piece's span, and the curve follows from the first
|
||||
/// piece's start and its handle, and the last piece's end and its handle, scaled up by their spans.
|
||||
/// Every piece is then checked against that curve's piece over its span, so error can't build up
|
||||
/// from one split to the next (the first piece's start and handle, and the last piece's end and
|
||||
/// handle, match by construction).
|
||||
fn one_curve(pieces: &[CubicBez]) -> Option<CubicBez> {
|
||||
let (first, last) = (pieces.first()?, pieces.last()?);
|
||||
if pieces.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
let mut spans = Vec::with_capacity(pieces.len());
|
||||
spans.push(1.0);
|
||||
for pair in pieces.windows(2) {
|
||||
let [a, b] = pair else { return None };
|
||||
let (into, out) = (a.p3.distance(a.p2), b.p0.distance(b.p1));
|
||||
// How far each piece bends away from the anchor goes with the squares of the spans. Split
|
||||
// where the curve stops (a cusp), both handles lie on the anchor and say nothing of the
|
||||
// spans, and the bends say it; where the curve runs straight through the split, the bends
|
||||
// are nothing and the handles say it. Whichever pair is the longer is the one to go by.
|
||||
let bend_in = ((a.p3 - a.p2) - (a.p2 - a.p1)).hypot();
|
||||
let bend_out = ((b.p2 - b.p1) - (b.p1 - b.p0)).hypot();
|
||||
let ratio = if into.min(out) >= bend_in.min(bend_out) { out / into } else { (bend_out / bend_in).sqrt() };
|
||||
let next = spans.last().copied().unwrap_or(1.0) * ratio;
|
||||
if !(next.is_finite() && next > 0.0) {
|
||||
return None;
|
||||
}
|
||||
spans.push(next);
|
||||
}
|
||||
let total: f64 = spans.iter().sum();
|
||||
let (head, tail) = (spans.first().copied().unwrap_or(1.0) / total, spans.last().copied().unwrap_or(1.0) / total);
|
||||
if !(total.is_finite() && head > 0.0 && tail > 0.0) {
|
||||
return None;
|
||||
}
|
||||
let one = CubicBez::new(first.p0, first.p0 + (first.p1 - first.p0) / head, last.p3 + (last.p2 - last.p3) / tail, last.p3);
|
||||
if ![one.p1, one.p2].iter().all(|p| p.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let near = |p: Point, q: Point| p.distance(q) <= ONE_CURVE;
|
||||
let mut from = 0.0;
|
||||
for (k, (piece, span)) in pieces.iter().zip(&spans).enumerate() {
|
||||
let to = if k + 1 == pieces.len() { 1.0 } else { (from + span / total).min(1.0) };
|
||||
let part = one.subsegment(from..to);
|
||||
if !(near(part.p0, piece.p0) && near(part.p1, piece.p1) && near(part.p2, piece.p2) && near(part.p3, piece.p3)) {
|
||||
return None;
|
||||
}
|
||||
from = to;
|
||||
}
|
||||
Some(one)
|
||||
}
|
||||
|
||||
/// How far into the outline's bounding box, as a share of its width and of its height, a corner
|
||||
/// of a top object looks for an anchor.
|
||||
const CORNER_REACH: f64 = 0.475;
|
||||
|
||||
@@ -144,6 +144,25 @@ impl Selection {
|
||||
self.key = None;
|
||||
}
|
||||
}
|
||||
/// [`Self::remove`] for each of `ids`, going through the selected objects once.
|
||||
pub fn remove_all(&mut self, ids: impl IntoIterator<Item = NodeId>) {
|
||||
let ids: HashSet<NodeId> = ids.into_iter().collect();
|
||||
if ids.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.target = None;
|
||||
self.slices.clear();
|
||||
self.symbol_part = None;
|
||||
self.on_path_member = None;
|
||||
self.objects.retain(|x| !ids.contains(x));
|
||||
for id in &ids {
|
||||
self.anchors.remove(id);
|
||||
self.segments.remove(id);
|
||||
}
|
||||
if self.key.is_some_and(|k| ids.contains(&k)) {
|
||||
self.key = None;
|
||||
}
|
||||
}
|
||||
/// Select slices `ids` (see [`Selection::slices`]) and nothing else.
|
||||
pub fn set_slices(&mut self, ids: impl IntoIterator<Item = NodeId>) {
|
||||
self.clear();
|
||||
|
||||
@@ -16,6 +16,35 @@ fn basic_ops() {
|
||||
assert!(s.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_all_does_what_removing_each_does() {
|
||||
let mut s = Selection::default();
|
||||
for i in 1..=6 {
|
||||
s.add(NodeId(i));
|
||||
}
|
||||
for i in [2, 4, 5] {
|
||||
s.anchors.insert(NodeId(i), BTreeSet::from([(0, 1)]));
|
||||
s.segments.insert(NodeId(i), BTreeSet::from([(0, 0)]));
|
||||
}
|
||||
s.key = Some(NodeId(4));
|
||||
s.target = Some(NodeId(3));
|
||||
s.slices = vec![NodeId(9)];
|
||||
s.guides = vec![NodeId(10)];
|
||||
s.on_path_member = Some(NodeId(11));
|
||||
let mut one_by_one = s.clone();
|
||||
for id in [NodeId(4), NodeId(1), NodeId(4), NodeId(7)] {
|
||||
one_by_one.remove(id);
|
||||
}
|
||||
let mut all = s.clone();
|
||||
all.remove_all([NodeId(4), NodeId(1), NodeId(4), NodeId(7)]);
|
||||
assert_eq!(all, one_by_one);
|
||||
assert_eq!(all.objects, [NodeId(2), NodeId(3), NodeId(5), NodeId(6)]);
|
||||
// Removing nothing leaves the selection as it was.
|
||||
let mut none = s.clone();
|
||||
none.remove_all([]);
|
||||
assert_eq!(none, s);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guides_are_selected_on_their_own() {
|
||||
let mut s = Selection::default();
|
||||
|
||||
@@ -0,0 +1,376 @@
|
||||
//! Every object a document stores, wherever it is kept: in the layers, in opacity-mask art, and in
|
||||
//! the art of symbols, graph designs and pattern swatches. [`Document::node`] finds objects in the
|
||||
//! layer tree only; the lookups here find the others by their ids too, which
|
||||
//! [`Document::fix_next_id`] keeps unique across all of them.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::limits::MAX_NEXT_ID;
|
||||
use super::{Document, Node, NodeId};
|
||||
|
||||
/// The art a stored object belongs to.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum StoredRoot {
|
||||
/// Layer `index` of [`Document::layers`].
|
||||
Layer(usize),
|
||||
/// Symbol `index` of [`Document::symbols`].
|
||||
Symbol(usize),
|
||||
/// Graph design `index` of [`Document::graph_designs`].
|
||||
GraphDesign(usize),
|
||||
/// Object `art` of pattern swatch `pattern` of [`Document::patterns`].
|
||||
Pattern { pattern: usize, art: usize },
|
||||
}
|
||||
|
||||
/// Where a stored object is: its root and, inside opacity-mask art, the object that mask belongs
|
||||
/// to (the innermost one when masks hold masks).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct StoredPlace {
|
||||
pub root: StoredRoot,
|
||||
pub mask_of: Option<NodeId>,
|
||||
}
|
||||
|
||||
impl StoredPlace {
|
||||
/// Is the object in the layer tree itself, where [`Document::node`] finds it and the canvas
|
||||
/// draws it as itself?
|
||||
pub fn in_layers(self) -> bool {
|
||||
matches!(self.root, StoredRoot::Layer(_)) && self.mask_of.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
/// One step down from a node: to its child at an index, or to its opacity-mask art.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Step {
|
||||
Child(usize),
|
||||
Mask,
|
||||
}
|
||||
|
||||
/// `n` and everything below it with its place, the opacity-mask art right after the object it
|
||||
/// masks, then the children.
|
||||
fn visit<'a>(n: &'a Arc<Node>, place: StoredPlace, f: &mut dyn FnMut(&'a Arc<Node>, StoredPlace)) {
|
||||
f(n, place);
|
||||
if let Some(m) = &n.extras().mask {
|
||||
visit(&m.art, StoredPlace { mask_of: Some(n.id), ..place }, f);
|
||||
}
|
||||
for c in n.children().into_iter().flatten() {
|
||||
visit(c, place, f);
|
||||
}
|
||||
}
|
||||
|
||||
/// The steps from `n` to the first node in [`visit`] order with id `id`, and the object whose mask
|
||||
/// holds it last on the way.
|
||||
fn find(n: &Node, id: NodeId, steps: &mut Vec<Step>, mask_of: &mut Option<NodeId>) -> bool {
|
||||
if n.id == id {
|
||||
return true;
|
||||
}
|
||||
if let Some(m) = &n.extras().mask {
|
||||
steps.push(Step::Mask);
|
||||
let before = *mask_of;
|
||||
*mask_of = Some(n.id);
|
||||
if find(&m.art, id, steps, mask_of) {
|
||||
return true;
|
||||
}
|
||||
*mask_of = before;
|
||||
steps.pop();
|
||||
}
|
||||
for (i, c) in n.children().into_iter().flatten().enumerate() {
|
||||
steps.push(Step::Child(i));
|
||||
if find(c, id, steps, mask_of) {
|
||||
return true;
|
||||
}
|
||||
steps.pop();
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// The node `steps` below `n`.
|
||||
fn at<'a>(mut n: &'a Arc<Node>, steps: &[Step]) -> Option<&'a Arc<Node>> {
|
||||
for s in steps {
|
||||
n = match s {
|
||||
Step::Mask => &n.extras().mask.as_ref()?.art,
|
||||
Step::Child(i) => n.children()?.get(*i)?,
|
||||
};
|
||||
}
|
||||
Some(n)
|
||||
}
|
||||
|
||||
/// The node `steps` below `n` to change, the nodes on the way copied when shared.
|
||||
fn at_mut<'a>(mut n: &'a mut Arc<Node>, steps: &[Step]) -> Option<&'a mut Node> {
|
||||
for s in steps {
|
||||
let node = Arc::make_mut(n);
|
||||
n = match s {
|
||||
Step::Mask => &mut node.extras_if_any()?.mask.as_mut()?.art,
|
||||
Step::Child(i) => node.children_mut()?.get_mut(*i)?,
|
||||
};
|
||||
}
|
||||
Some(Arc::make_mut(n))
|
||||
}
|
||||
|
||||
/// Gives every node from `n` down that `fresh` names a new id from `next`, counting nodes in
|
||||
/// [`visit`] order from `*count`; only the nodes on the way to one are copied. Each part below is
|
||||
/// renumbered through a second handle, so a new pointer marks a change.
|
||||
fn renumber(n: &mut Arc<Node>, fresh: &HashSet<usize>, count: &mut usize, next: &mut u64) {
|
||||
let own = fresh.contains(count);
|
||||
*count += 1;
|
||||
let mask = n.extras().mask.as_ref().and_then(|m| {
|
||||
let mut art = Arc::clone(&m.art);
|
||||
renumber(&mut art, fresh, count, next);
|
||||
(!Arc::ptr_eq(&art, &m.art)).then_some(art)
|
||||
});
|
||||
let mut slots = vec![];
|
||||
// Children's new ids by their old ones, for an Objects on Path group, which names its path and
|
||||
// members by id. An id another child keeps still names that child.
|
||||
let mut renamed = std::collections::HashMap::new();
|
||||
let mut kept = HashSet::new();
|
||||
for (i, c) in n.children().into_iter().flatten().enumerate() {
|
||||
let mut new = Arc::clone(c);
|
||||
renumber(&mut new, fresh, count, next);
|
||||
if new.id == c.id {
|
||||
kept.insert(c.id);
|
||||
} else {
|
||||
renamed.insert(c.id, new.id);
|
||||
}
|
||||
if !Arc::ptr_eq(&new, c) {
|
||||
slots.push((i, new));
|
||||
}
|
||||
}
|
||||
renamed.retain(|old, _| !kept.contains(old));
|
||||
if !own && mask.is_none() && slots.is_empty() {
|
||||
return;
|
||||
}
|
||||
let node = Arc::make_mut(n);
|
||||
if own {
|
||||
node.id = NodeId(*next);
|
||||
*next += 1;
|
||||
}
|
||||
if let (Some(art), Some(m)) = (mask, node.extras_if_any().and_then(|e| e.mask.as_mut())) {
|
||||
m.art = art;
|
||||
}
|
||||
if let Some(children) = node.children_mut() {
|
||||
for (i, c) in slots {
|
||||
if let Some(slot) = children.get_mut(i) {
|
||||
*slot = c;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !renamed.is_empty()
|
||||
&& let Some(on_path) = node.extras_if_any().and_then(|e| e.objects_on_path.as_mut())
|
||||
{
|
||||
on_path.rename(&renamed);
|
||||
}
|
||||
}
|
||||
|
||||
impl Document {
|
||||
/// The roots of the art kept outside the layers, each with its [`StoredRoot`].
|
||||
fn definition_roots(&self) -> impl Iterator<Item = (&Arc<Node>, StoredRoot)> {
|
||||
let symbols = self.symbols.iter().enumerate().map(|(i, s)| (&s.art, StoredRoot::Symbol(i)));
|
||||
let designs = self.graph_designs.iter().enumerate().map(|(i, g)| (&g.art, StoredRoot::GraphDesign(i)));
|
||||
let patterns = self
|
||||
.patterns
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(p, def)| def.art.iter().enumerate().map(move |(a, n)| (n, StoredRoot::Pattern { pattern: p, art: a })));
|
||||
symbols.chain(designs).chain(patterns)
|
||||
}
|
||||
|
||||
/// Every root of stored art: the layers, then the art of symbols, graph designs and patterns.
|
||||
fn stored_roots(&self) -> impl Iterator<Item = (&Arc<Node>, StoredRoot)> {
|
||||
self.layers.iter().enumerate().map(|(i, l)| (l, StoredRoot::Layer(i))).chain(self.definition_roots())
|
||||
}
|
||||
|
||||
/// The root `root` names, to change.
|
||||
fn stored_root_mut(&mut self, root: StoredRoot) -> Option<&mut Arc<Node>> {
|
||||
match root {
|
||||
StoredRoot::Layer(i) => self.layers.get_mut(i),
|
||||
StoredRoot::Symbol(i) => self.symbols.get_mut(i).map(|s| &mut s.art),
|
||||
StoredRoot::GraphDesign(i) => self.graph_designs.get_mut(i).map(|g| &mut g.art),
|
||||
StoredRoot::Pattern { pattern, art } => self.patterns.get_mut(pattern)?.art.get_mut(art),
|
||||
}
|
||||
}
|
||||
|
||||
/// Visit every stored object with its place: the layer tree with the opacity-mask art of its
|
||||
/// objects, then the art of symbols, graph designs and pattern swatches (their definitions,
|
||||
/// once each, never the copies instances and tiles draw).
|
||||
pub fn visit_stored<'a>(&'a self, mut f: impl FnMut(&'a Node, StoredPlace)) {
|
||||
self.visit_stored_arcs(|n, place| f(n, place));
|
||||
}
|
||||
|
||||
/// [`Self::visit_stored`] with each object's shared handle, which keeps its identity from one
|
||||
/// look to the next while the object is unchanged (for caches such as thumbnails).
|
||||
pub fn visit_stored_arcs<'a>(&'a self, mut f: impl FnMut(&'a Arc<Node>, StoredPlace)) {
|
||||
for (root, r) in self.stored_roots() {
|
||||
visit(root, StoredPlace { root: r, mask_of: None }, &mut f);
|
||||
}
|
||||
}
|
||||
|
||||
/// Where object `id` is stored: the root, and the steps from it.
|
||||
fn stored_path(&self, id: NodeId) -> Option<(StoredPlace, Vec<Step>)> {
|
||||
if let Some(path) = self.index_path(id) {
|
||||
let (first, rest) = path.split_first()?;
|
||||
return Some((StoredPlace { root: StoredRoot::Layer(*first), mask_of: None }, rest.iter().map(|i| Step::Child(*i)).collect()));
|
||||
}
|
||||
// Not in the layer tree: in mask art (in the layers too) or in a definition's art.
|
||||
for (root, r) in self.stored_roots() {
|
||||
let (mut steps, mut mask_of) = (vec![], None);
|
||||
if find(root, id, &mut steps, &mut mask_of) {
|
||||
return Some((StoredPlace { root: r, mask_of }, steps));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Stored object `id` (see [`Self::visit_stored`]) with its place: one in the layer tree as
|
||||
/// [`Self::node`] finds it, else the first in visiting order.
|
||||
pub fn stored_node(&self, id: NodeId) -> Option<(&Arc<Node>, StoredPlace)> {
|
||||
let (place, steps) = self.stored_path(id)?;
|
||||
let root = self.stored_roots().find(|(_, r)| *r == place.root)?.0;
|
||||
Some((at(root, &steps)?, place))
|
||||
}
|
||||
|
||||
/// [`Self::stored_node`] to change; the nodes on the way are copied when shared.
|
||||
pub fn stored_node_mut(&mut self, id: NodeId) -> Option<&mut Node> {
|
||||
let (place, steps) = self.stored_path(id)?;
|
||||
at_mut(self.stored_root_mut(place.root)?, &steps)
|
||||
}
|
||||
|
||||
/// Gives the objects outside the layer tree (in opacity-mask art and in the art of symbols,
|
||||
/// graph designs and patterns) whose id is 0, past the id range, or already taken by an object
|
||||
/// visited before them (the layer tree's own objects first) a new id, so every stored object
|
||||
/// can be named by its id. Returns how many changed; the id counter then stands above them.
|
||||
pub(crate) fn renumber_stored_duplicates(&mut self) -> usize {
|
||||
let mut seen: HashSet<NodeId> = HashSet::new();
|
||||
for l in &self.layers {
|
||||
l.walk(&mut |n| {
|
||||
seen.insert(n.id);
|
||||
});
|
||||
}
|
||||
self.slices.iter().for_each(|s| {
|
||||
seen.insert(s.id);
|
||||
});
|
||||
// Per root, the visiting indices of the nodes that take a new id.
|
||||
let mut fresh: Vec<(StoredRoot, HashSet<usize>)> = vec![];
|
||||
for (root, r) in self.stored_roots() {
|
||||
let (mut i, mut here) = (0, HashSet::new());
|
||||
visit(root, StoredPlace { root: r, mask_of: None }, &mut |n, place| {
|
||||
if !place.in_layers() && (n.id.0 == 0 || n.id.0 >= MAX_NEXT_ID || !seen.insert(n.id)) {
|
||||
here.insert(i);
|
||||
}
|
||||
i += 1;
|
||||
});
|
||||
if !here.is_empty() {
|
||||
fresh.push((r, here));
|
||||
}
|
||||
}
|
||||
let total = fresh.iter().map(|(_, f)| f.len()).sum();
|
||||
if total == 0 {
|
||||
return 0;
|
||||
}
|
||||
// No id left to give: the objects keep theirs rather than share one given out later.
|
||||
if self.peek_next_id().saturating_add(total as u64) > MAX_NEXT_ID {
|
||||
return 0;
|
||||
}
|
||||
let mut next = self.peek_next_id();
|
||||
for (r, f) in fresh {
|
||||
if let Some(root) = self.stored_root_mut(r) {
|
||||
renumber(root, &f, &mut 0, &mut next);
|
||||
}
|
||||
}
|
||||
self.raise_next_id(next);
|
||||
total
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{GraphDesign, OpacityMask, PatternDef, Symbol};
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
fn rect(id: u64) -> Node {
|
||||
Node::path(NodeId(id), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), crate::Appearance::default_art())
|
||||
}
|
||||
|
||||
fn masked(id: u64, art: Node) -> Node {
|
||||
rect(id).with_mask(Some(Box::new(OpacityMask::new(art, true))))
|
||||
}
|
||||
|
||||
/// A document with object 10 in its layer, mask art 11 on it, and one object in a symbol,
|
||||
/// a graph design and a pattern (ids `defs`).
|
||||
fn doc(defs: [u64; 3]) -> Document {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 0, masked(10, rect(11))).unwrap();
|
||||
d.symbols.push(Symbol { name: "S".into(), art: Arc::new(rect(defs[0])), dynamic: false });
|
||||
d.graph_designs.push(GraphDesign { name: "G".into(), art: Arc::new(rect(defs[1])) });
|
||||
d.patterns.push(PatternDef::new("P", vec![Arc::new(rect(defs[2]))]));
|
||||
d.raise_next_id(20);
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stored_objects_are_found_in_every_art() {
|
||||
let d = doc([12, 13, 14]);
|
||||
let place = |id: u64| d.stored_node(NodeId(id)).map(|(n, p)| (n.id.0, p));
|
||||
assert!(place(10).unwrap().1.in_layers());
|
||||
assert_eq!(place(11).unwrap().1, StoredPlace { root: StoredRoot::Layer(0), mask_of: Some(NodeId(10)) });
|
||||
assert_eq!(place(12).unwrap().1.root, StoredRoot::Symbol(0));
|
||||
assert_eq!(place(13).unwrap().1.root, StoredRoot::GraphDesign(0));
|
||||
assert_eq!(place(14).unwrap().1.root, StoredRoot::Pattern { pattern: 0, art: 0 });
|
||||
assert!(d.node(NodeId(11)).is_none() && d.node(NodeId(12)).is_none(), "the layer lookup stays the layer tree's");
|
||||
assert!(d.stored_node(NodeId(99)).is_none());
|
||||
let mut seen = vec![];
|
||||
d.visit_stored(|n, _| seen.push(n.id.0));
|
||||
assert_eq!(seen, [d.layers[0].id.0, 10, 11, 12, 13, 14]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stored_objects_change_by_id() {
|
||||
let mut d = doc([12, 13, 14]);
|
||||
let before = d.clone();
|
||||
d.stored_node_mut(NodeId(13)).unwrap().name = Some("changed".into());
|
||||
assert_eq!(d.graph_designs[0].art.name.as_deref(), Some("changed"));
|
||||
assert!(Arc::ptr_eq(&d.symbols[0].art, &before.symbols[0].art), "other art is not copied");
|
||||
assert_eq!(before.graph_designs[0].art.name, None, "the earlier document is unchanged");
|
||||
d.stored_node_mut(NodeId(11)).unwrap().name = Some("mask".into());
|
||||
assert_eq!(d.stored_node(NodeId(11)).unwrap().0.name.as_deref(), Some("mask"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fix_next_id_gives_nested_duplicates_new_ids() {
|
||||
// The symbol's object repeats the layer's object, the design's has no id, and the pattern's
|
||||
// repeats the mask art's.
|
||||
let mut d = doc([10, 0, 11]);
|
||||
d.next_id = 1;
|
||||
d.fix_next_id();
|
||||
let mut ids = vec![];
|
||||
d.visit_stored(|n, _| ids.push(n.id.0));
|
||||
let unique: HashSet<u64> = ids.iter().copied().collect();
|
||||
assert_eq!(unique.len(), ids.len(), "{ids:?}");
|
||||
assert!(!ids.contains(&0));
|
||||
assert_eq!(&ids[..3], &[d.layers[0].id.0, 10, 11], "the layer tree and the first mask art keep theirs");
|
||||
assert!(ids.iter().all(|id| *id < d.peek_next_id()), "{ids:?} {}", d.peek_next_id());
|
||||
// Ids already unique are kept, and a second pass changes nothing.
|
||||
let again = d.clone();
|
||||
assert_eq!(d.renumber_stored_duplicates(), 0);
|
||||
assert_eq!(d, again);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renumbered_objects_on_path_keep_their_path_and_members() {
|
||||
// A symbol's Objects on Path group whose path repeats the layer's object 10 and whose
|
||||
// member has no id.
|
||||
let mut d = doc([12, 13, 14]);
|
||||
let (path, member) = (rect(10), rect(0));
|
||||
let rec = crate::objects_on_path::ObjectsOnPath::new(path.id, &[&member], crate::objects_on_path::CENTER, 0.0);
|
||||
let mut g = Node::new(NodeId(15), crate::NodeKind::Group { children: vec![Arc::new(path), Arc::new(member)], clip: false });
|
||||
g.extras_mut().objects_on_path = Some(Box::new(rec));
|
||||
d.symbols[0].art = Arc::new(g);
|
||||
d.fix_next_id();
|
||||
let art = &d.symbols[0].art;
|
||||
let kids: Vec<NodeId> = art.children().unwrap().iter().map(|c| c.id).collect();
|
||||
assert!(kids.iter().all(|id| id.0 != 10 && id.0 != 0), "{kids:?}");
|
||||
let on_path = art.extras().objects_on_path.as_ref().unwrap();
|
||||
assert_eq!(on_path.path, kids[0]);
|
||||
assert_eq!(on_path.members.iter().map(|m| m.id).collect::<Vec<_>>(), [kids[1]]);
|
||||
}
|
||||
}
|
||||
@@ -10,9 +10,19 @@
|
||||
//! The cells are sized along the symbol's own axes, and the instance's rotation, shear, reflection
|
||||
//! and position then apply to them.
|
||||
//!
|
||||
//! The guides are stored as fractions (0..1) of the symbol's natural size, measured from the left
|
||||
//! and top edges and from the right and bottom edges, so they survive resizing the art. Stored
|
||||
//! under [`SYMBOL_NINE_SLICE`] keyed by symbol name; symbols without 9-slice have no entry.
|
||||
//! A guide may lie outside the art, and the instance still scales, by the slices the art falls in
|
||||
//! ([the help page](https://help.adobe.com/archive/en/illustrator/cs6/illustrator_reference.pdf),
|
||||
//! Use 9-slice scaling section). VectorCraft's own rules for that: a guide past an edge of the art
|
||||
//! cuts the art at that edge, so the outer cell on its side holds no art; with both guides of an
|
||||
//! axis past opposite edges the art scales as a whole along it; with both past the same edge the
|
||||
//! art lies in the outer cell at the other edge and keeps its size, from that edge of the instance,
|
||||
//! or shrinks to the instance's width or height when the instance is smaller than the art.
|
||||
//!
|
||||
//! The guides are stored as fractions of the symbol's natural size, measured from the left and top
|
||||
//! edges and from the right and bottom edges, so they survive resizing the art. A fraction below 0
|
||||
//! puts a guide past its own edge, and one above 1 past the opposite edge; each lies within
|
||||
//! ±[`MAX_GUIDE_FRACTION`], and the two guides of an axis keep their order. Stored under
|
||||
//! [`SYMBOL_NINE_SLICE`] keyed by symbol name; symbols without 9-slice have no entry.
|
||||
//!
|
||||
//! [`NineSliceMap`] places such an instance's art for the canvas, bounds, Break Link, Expand and
|
||||
//! the exporters ([`Document::place_symbol_art`]).
|
||||
@@ -49,11 +59,16 @@ impl Default for SymbolNineSlice {
|
||||
}
|
||||
}
|
||||
|
||||
/// The farthest a guide may lie from its edge, as a fraction of the symbol's width or height, in
|
||||
/// either direction (VectorCraft's own rule).
|
||||
pub const MAX_GUIDE_FRACTION: f64 = 16.0;
|
||||
|
||||
impl SymbolNineSlice {
|
||||
/// Guides from `[left, top, right, bottom]`; `None` unless each is finite, within 0..1, and the
|
||||
/// two on each axis leave a gap between them.
|
||||
/// Guides from `[left, top, right, bottom]`; `None` unless each is finite and within
|
||||
/// ±[`MAX_GUIDE_FRACTION`], and the two on each axis leave a gap between them
|
||||
/// (`left + right < 1`, `top + bottom < 1`).
|
||||
pub fn new(left: f64, top: f64, right: f64, bottom: f64) -> Option<Self> {
|
||||
let ok = |v: f64| v.is_finite() && (0.0..=1.0).contains(&v);
|
||||
let ok = |v: f64| v.is_finite() && (-MAX_GUIDE_FRACTION..=MAX_GUIDE_FRACTION).contains(&v);
|
||||
(ok(left) && ok(top) && ok(right) && ok(bottom) && left + right < 1.0 && top + bottom < 1.0).then_some(Self { left, top, right, bottom })
|
||||
}
|
||||
|
||||
@@ -102,7 +117,8 @@ pub struct EditedNineSlice {
|
||||
}
|
||||
|
||||
impl EditedNineSlice {
|
||||
/// Guide `g` as a line across the art's box, from one edge to the other, in the document.
|
||||
/// Guide `g` as a line across the art's box, from one edge to the other, in the document. A
|
||||
/// guide outside the art spans the art's height or width beside it.
|
||||
pub fn line(&self, g: NineSliceGuide) -> (Point, Point) {
|
||||
let (b, s) = (self.art, self.guides);
|
||||
let (a, c) = match g {
|
||||
@@ -126,14 +142,17 @@ impl EditedNineSlice {
|
||||
})
|
||||
}
|
||||
|
||||
/// The guides with guide `g` moved across its axis to document point `p`. The guide stays
|
||||
/// within the art's box, and [`MIN_CENTER_BAND`] short of the opposite guide, or where it is
|
||||
/// when the guides are already closer than that. A point that is not finite leaves the guides
|
||||
/// as they are.
|
||||
/// The guides with guide `g` moved across its axis to document point `p`. The guide may pass
|
||||
/// either edge of the art, up to [`MAX_GUIDE_FRACTION`] from its own edge, and stops
|
||||
/// [`MIN_CENTER_BAND`] short of the opposite guide, or where it is when the guides are already
|
||||
/// closer than that. A point that is not finite, or that gives a fraction that is not, leaves
|
||||
/// the guides as they are.
|
||||
pub fn moved(&self, g: NineSliceGuide, p: Point) -> SymbolNineSlice {
|
||||
let (b, mut out) = (self.art, self.guides);
|
||||
let q = self.to_doc.inverse() * p;
|
||||
let fit = |v: f64, other: f64, now: f64| if v.is_finite() { v.clamp(0.0, (1.0 - other - MIN_CENTER_BAND).max(now)) } else { now };
|
||||
let fit = |v: f64, other: f64, now: f64| {
|
||||
if v.is_finite() { v.clamp(-MAX_GUIDE_FRACTION, (1.0 - other - MIN_CENTER_BAND).min(MAX_GUIDE_FRACTION).max(now)) } else { now }
|
||||
};
|
||||
match g {
|
||||
NineSliceGuide::Left => out.left = fit((q.x - b.x0) / b.width(), out.right, out.left),
|
||||
NineSliceGuide::Right => out.right = fit((b.x1 - q.x) / b.width(), out.left, out.right),
|
||||
@@ -181,20 +200,27 @@ const MAX_SLICE_DEPTH: u32 = 64;
|
||||
/// One axis of a 9-slice map: the three cells between the cuts and where each one goes.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
struct AxisMap {
|
||||
/// The cuts in the art at its natural size: its start, the two guides, its end.
|
||||
/// The cuts in the art at its natural size: its start, the two guides, its end. A guide
|
||||
/// outside the art cuts it at the nearer end, so a cell can be empty.
|
||||
src: [f64; 4],
|
||||
/// Where the cuts go. The outer cells keep their length unless the scaled length is shorter
|
||||
/// than both together; then both shrink in proportion and the middle cell is empty.
|
||||
/// than both together; then both shrink in proportion and the middle cell is empty. An empty
|
||||
/// cell's start is where the cell before it ends, so the map stays continuous.
|
||||
dst: [f64; 4],
|
||||
}
|
||||
|
||||
impl AxisMap {
|
||||
/// The axis from `lo` to `hi` with guides `near` and `far` (fractions of its length in from
|
||||
/// each end), scaled by `k` (above 0).
|
||||
/// The axis from `lo` to `hi` (`lo < hi`) with guides `near` and `far` (fractions of its
|
||||
/// length in from each end, `near + far < 1`; either may lie past an end), scaled by `k`
|
||||
/// (above 0). With both guides past the far end the art keeps its length from the scaled
|
||||
/// start, and with both past the near end it keeps its length up to the scaled end; when the
|
||||
/// scaled length is shorter than the art, the art shrinks to the scaled length.
|
||||
fn new(lo: f64, hi: f64, near: f64, far: f64, k: f64) -> Self {
|
||||
let len = hi - lo;
|
||||
let (a, b) = (near * len, far * len);
|
||||
let src = [lo, lo + a, hi - b, hi];
|
||||
let c1 = (lo + near * len).clamp(lo, hi);
|
||||
let c2 = (hi - far * len).clamp(c1, hi);
|
||||
let src = [lo, c1, c2, hi];
|
||||
let (a, b) = (c1 - lo, hi - c2);
|
||||
let (t0, t3) = (k * lo, k * hi);
|
||||
let room = t3 - t0;
|
||||
let (a, b) = if a + b <= room {
|
||||
@@ -203,9 +229,15 @@ impl AxisMap {
|
||||
let f = (room / (a + b)).max(0.0);
|
||||
(a * f, b * f)
|
||||
};
|
||||
let t1 = t0 + a;
|
||||
let t2 = (t3 - b).max(t1);
|
||||
Self { src, dst: [t0, t1, t2, t3] }
|
||||
let dst = if c2 > c1 {
|
||||
let t1 = t0 + a;
|
||||
[t0, t1, (t3 - b).max(t1), t3]
|
||||
} else if a > 0.0 {
|
||||
[t0, t0 + a, t0 + a, t3]
|
||||
} else {
|
||||
[t3 - b, t3 - b, t3 - b, t3]
|
||||
};
|
||||
Self { src, dst }
|
||||
}
|
||||
|
||||
/// The cell `v` lies in; values outside the art belong to the outer cells.
|
||||
@@ -279,10 +311,11 @@ pub struct NineSliceMap {
|
||||
|
||||
impl NineSliceMap {
|
||||
/// The map for an instance placed by `xf` that shows art with natural-size transform
|
||||
/// `natural` and geometric bounds `art` (in symbol space). `None` when the art or the
|
||||
/// transform is degenerate, or when the instance is at its natural size on both axes (then
|
||||
/// `xf` places the art as it is).
|
||||
/// `natural` and geometric bounds `art` (in symbol space). `None` when the guides are not ones
|
||||
/// [`SymbolNineSlice::new`] accepts, when the art or the transform is degenerate, or when the
|
||||
/// instance is at its natural size on both axes (then `xf` places the art as it is).
|
||||
pub fn new(guides: SymbolNineSlice, art: Rect, natural: Affine, xf: Affine) -> Option<Self> {
|
||||
let guides = SymbolNineSlice::new(guides.left, guides.top, guides.right, guides.bottom)?;
|
||||
let b = natural.transform_rect_bbox(art);
|
||||
if ![b.x0, b.y0, b.x1, b.y1].into_iter().all(f64::is_finite) || b.width() <= 1e-9 || b.height() <= 1e-9 {
|
||||
return None;
|
||||
@@ -894,6 +927,113 @@ mod tests {
|
||||
assert!(got.iter().all(|b| finite(*b)), "{got:?}");
|
||||
}
|
||||
|
||||
/// Guides may lie outside the art, up to 16 times its size from their edge, as long as the
|
||||
/// two on each axis keep their order; values that are not finite are refused.
|
||||
#[test]
|
||||
fn guides_outside_the_art_are_accepted_in_order_and_within_the_limit() {
|
||||
let ok = |l, t, r, b| SymbolNineSlice::new(l, t, r, b).is_some();
|
||||
assert!(ok(-0.25, 0.25, 0.25, 0.25));
|
||||
assert!(ok(1.25, 0.25, -0.5, 0.25), "both past the right edge");
|
||||
assert!(ok(0.25, -16.0, 0.25, 16.0) && ok(-16.0, 0.25, -16.0, 0.25));
|
||||
assert!(!ok(-16.5, 0.25, 0.25, 0.25) && !ok(0.25, 0.25, 0.25, 17.0));
|
||||
assert!(!ok(f64::NAN, 0.25, 0.25, 0.25) && !ok(0.25, f64::INFINITY, 0.25, 0.25) && !ok(0.25, 0.25, f64::NEG_INFINITY, 0.25));
|
||||
assert!(!ok(1.2, 0.25, -0.2, 0.25), "the left guide on the right one");
|
||||
assert!(!ok(0.25, 0.6, 0.25, 0.6), "crossed");
|
||||
let g = SymbolNineSlice::from_value(&json!([-0.25, 1.5, 0.5, -1.0])).unwrap();
|
||||
assert_eq!(g, SymbolNineSlice { left: -0.25, top: 1.5, right: 0.5, bottom: -1.0 });
|
||||
assert_eq!(SymbolNineSlice::from_value(&g.to_value()), Some(g));
|
||||
assert!(SymbolNineSlice::from_value(&json!([-0.25, 0.1, 1.5])).is_none());
|
||||
assert!(SymbolNineSlice::from_value(&json!([-20.0, 0.1, 0.5, 0.1])).is_none());
|
||||
// Guides built without the check are not used to place art.
|
||||
let bad = SymbolNineSlice { left: f64::NAN, ..SymbolNineSlice::default() };
|
||||
assert!(NineSliceMap::new(bad, Rect::new(0.0, 0.0, 100.0, 100.0), Affine::IDENTITY, Affine::scale(2.0)).is_none());
|
||||
// Art without width or height has no map, whatever the guides.
|
||||
let out = SymbolNineSlice::new(-0.25, 1.25, 0.25, -0.5).unwrap();
|
||||
for art in [Rect::new(0.0, 0.0, 0.0, 100.0), Rect::new(0.0, 0.0, 100.0, 0.0)] {
|
||||
assert!(NineSliceMap::new(out, art, Affine::IDENTITY, Affine::scale(2.0)).is_none(), "{art:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// At 200 × 150, a left guide 25 % outside the art leaves the art in the center and right
|
||||
/// columns: the left column holds no art, the center one (0..75) stretches to 0..175 and the
|
||||
/// right one keeps its 25. Both guides outside on opposite sides scale the art as a whole on
|
||||
/// that axis; both past the same side keep the art at its size in the outer cell at the other
|
||||
/// side, from that side of the instance.
|
||||
#[test]
|
||||
fn art_scales_by_the_cells_it_falls_in_when_guides_lie_outside_it() {
|
||||
let xf = Affine::scale_non_uniform(2.0, 1.5);
|
||||
let d = markers(SymbolNineSlice::new(-0.25, 0.25, 0.25, 0.25));
|
||||
let got = boxes(&d, xf);
|
||||
let k = 175.0 / 75.0;
|
||||
assert!(near(got[0], Rect::new(0.0, 0.0, 200.0, 150.0)), "{:?}", got[0]);
|
||||
assert!(near(got[1], Rect::new(0.0, 0.0, 10.0 * k, 10.0)), "the top-left square stretches: {:?}", got[1]);
|
||||
assert!(near(got[2], Rect::new(190.0, 0.0, 200.0, 10.0)), "the top-right corner keeps its size: {:?}", got[2]);
|
||||
assert!(near(got[5], Rect::new(45.0 * k, 65.0, 55.0 * k, 85.0)), "{:?}", got[5]);
|
||||
// Both vertical guides outside, on opposite sides: the art scales as a whole across.
|
||||
let d = markers(SymbolNineSlice::new(-0.25, 0.25, -1.0, 0.25));
|
||||
let got = boxes(&d, xf);
|
||||
assert!(near(got[1], Rect::new(0.0, 0.0, 20.0, 10.0)) && near(got[2], Rect::new(180.0, 0.0, 200.0, 10.0)), "{got:?}");
|
||||
assert!(near(got[5], Rect::new(90.0, 65.0, 110.0, 85.0)), "{:?}", got[5]);
|
||||
// Both past the right edge: the art keeps its width from the instance's left edge.
|
||||
let d = markers(SymbolNineSlice::new(1.2, 0.25, -0.5, 0.25));
|
||||
let got = boxes(&d, xf);
|
||||
assert!(near(got[0], Rect::new(0.0, 0.0, 100.0, 150.0)), "{:?}", got[0]);
|
||||
assert!(near(got[2], Rect::new(90.0, 0.0, 100.0, 10.0)) && near(got[5], Rect::new(45.0, 65.0, 55.0, 85.0)), "{got:?}");
|
||||
// Both past the left edge: the art keeps its width up to the instance's right edge.
|
||||
let d = markers(SymbolNineSlice::new(-0.5, 0.25, 1.2, 0.25));
|
||||
let got = boxes(&d, xf);
|
||||
assert!(near(got[0], Rect::new(100.0, 0.0, 200.0, 150.0)), "{:?}", got[0]);
|
||||
assert!(near(got[1], Rect::new(100.0, 0.0, 110.0, 10.0)), "{:?}", got[1]);
|
||||
// The same rules apply to rows: both horizontal guides above the art keep its height up to
|
||||
// the instance's bottom edge.
|
||||
let d = markers(SymbolNineSlice::new(0.25, -0.5, 0.25, 1.2));
|
||||
let got = boxes(&d, xf);
|
||||
assert!(near(got[0], Rect::new(0.0, 50.0, 200.0, 150.0)), "{:?}", got[0]);
|
||||
assert!(near(got[3], Rect::new(0.0, 140.0, 10.0, 150.0)), "{:?}", got[3]);
|
||||
// Smaller than the art, an art-covered outer cell shrinks in proportion.
|
||||
let d = markers(SymbolNineSlice::new(1.2, 0.25, -0.5, 0.25));
|
||||
let got = boxes(&d, Affine::scale_non_uniform(0.5, 1.5));
|
||||
assert!(near(got[0], Rect::new(0.0, 0.0, 50.0, 150.0)) && near(got[1], Rect::new(0.0, 0.0, 5.0, 10.0)), "{got:?}");
|
||||
}
|
||||
|
||||
/// With guides outside the art, the map stays finite, never runs backward, and does not jump
|
||||
/// at the art's edges or at the guides; objects keep to the cells that hold art.
|
||||
#[test]
|
||||
fn the_map_with_guides_outside_the_art_is_continuous_and_monotone() {
|
||||
let cases = [(-0.25, 0.25), (-0.25, -1.0), (1.2, -0.5), (-0.5, 1.2), (0.0, -16.0), (-16.0, 16.0), (0.25, 0.25)];
|
||||
for (l, r) in cases {
|
||||
let d = markers(SymbolNineSlice::new(l, 0.25, r, 0.25));
|
||||
for sx in [0.3, 2.0, 1e6] {
|
||||
let m = d.symbol_slice_map("S", Affine::scale_non_uniform(sx, 1.5)).unwrap();
|
||||
let at = |x: f64| m.map_point(Point::new(x, 40.0)).x;
|
||||
let mut last = f64::NEG_INFINITY;
|
||||
for i in 0..=1200 {
|
||||
let x = -10.0 + i as f64 * 0.1;
|
||||
let v = at(x);
|
||||
assert!(v.is_finite() && v >= last - 1e-12 * last.abs().max(1.0), "{l} {r} {sx}: {x} → {v} after {last}");
|
||||
last = v;
|
||||
}
|
||||
for edge in [0.0, 75.0, 100.0] {
|
||||
let jump = (at(edge + 1e-9) - at(edge - 1e-9)).abs();
|
||||
assert!(jump < 1e-6 * sx.max(1.0), "{l} {r} {sx}: a jump of {jump} at {edge}");
|
||||
}
|
||||
}
|
||||
}
|
||||
// A gradient bar across the art with the left guide outside is drawn in the two columns
|
||||
// that hold art, not three.
|
||||
let mut d = markers(SymbolNineSlice::new(-0.25, 0.25, 0.25, 0.25));
|
||||
let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::default())));
|
||||
let bar = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 40.0, 100.0, 60.0)), Appearance::basic(gradient, Paint::None, 0.0));
|
||||
let m = d.symbol_slice_map("S", Affine::scale_non_uniform(2.0, 1.5)).unwrap();
|
||||
assert_eq!(m.place(&bar, &d).children().map(Vec::len), Some(2));
|
||||
assert_eq!(m.most_placed(&bar, &d), 7);
|
||||
// With both guides outside on opposite sides, the bar lies in one cell and is moved whole.
|
||||
let d = markers(SymbolNineSlice::new(-0.25, 0.25, -0.25, 0.25));
|
||||
let m = d.symbol_slice_map("S", Affine::scale_non_uniform(2.0, 1.5)).unwrap();
|
||||
assert!(matches!(m.place(&bar, &d).kind, NodeKind::Path { .. }));
|
||||
assert_eq!(m.most_placed(&bar, &d), 1);
|
||||
}
|
||||
|
||||
/// A negative scale reflects the sized cells; a rotation turns them, the corners keeping
|
||||
/// their size along the symbol's own axes.
|
||||
#[test]
|
||||
@@ -1456,27 +1596,37 @@ mod tests {
|
||||
assert!(d.edited_nine_slice().is_none());
|
||||
}
|
||||
|
||||
/// Moving a guide changes that guide alone, follows the pointer across its axis only, stays
|
||||
/// within the art's box and stops short of the opposite guide.
|
||||
/// Moving a guide changes that guide alone, follows the pointer across its axis only, may pass
|
||||
/// either edge of the art up to [`MAX_GUIDE_FRACTION`], and stops short of the opposite guide.
|
||||
#[test]
|
||||
fn a_moved_guide_stays_in_the_art_and_short_of_the_opposite_guide() {
|
||||
fn a_moved_guide_passes_the_arts_edges_and_stops_short_of_the_opposite_guide() {
|
||||
let xf = Affine::translate((10.0, 20.0)) * Affine::scale(2.0);
|
||||
let e = editing(Some(SymbolNineSlice::default()), xf).edited_nine_slice().unwrap();
|
||||
let q = SymbolNineSlice { left: 0.25, top: 0.25, right: 0.25, bottom: 0.25 };
|
||||
assert_eq!(e.moved(NineSliceGuide::Left, Point::new(30.0, 999.0)), SymbolNineSlice { left: 0.1, ..q });
|
||||
assert_eq!(e.moved(NineSliceGuide::Bottom, Point::new(-50.0, 180.0)), SymbolNineSlice { bottom: 0.2, ..q });
|
||||
assert_eq!(e.moved(NineSliceGuide::Top, Point::new(0.0, -500.0)), SymbolNineSlice { top: 0.0, ..q });
|
||||
assert_eq!(e.moved(NineSliceGuide::Right, Point::new(1e6, 0.0)), SymbolNineSlice { right: 0.0, ..q });
|
||||
// Past the art's near edges: the art spans 10..210 across and 20..220 down.
|
||||
assert_eq!(e.moved(NineSliceGuide::Left, Point::new(-40.0, 50.0)), SymbolNineSlice { left: -0.25, ..q });
|
||||
assert_eq!(e.moved(NineSliceGuide::Top, Point::new(0.0, -500.0)), SymbolNineSlice { top: -2.6, ..q });
|
||||
assert_eq!(e.moved(NineSliceGuide::Right, Point::new(1e6, 0.0)), SymbolNineSlice { right: -MAX_GUIDE_FRACTION, ..q });
|
||||
assert_eq!(e.moved(NineSliceGuide::Left, Point::new(-1e300, 0.0)), SymbolNineSlice { left: -MAX_GUIDE_FRACTION, ..q });
|
||||
let crossed = e.moved(NineSliceGuide::Left, Point::new(200.0, 50.0));
|
||||
assert!((crossed.left - (0.75 - MIN_CENTER_BAND)).abs() < 1e-12, "{crossed:?}");
|
||||
assert!(SymbolNineSlice::new(crossed.left, crossed.top, crossed.right, crossed.bottom).is_some());
|
||||
assert_eq!(e.moved(NineSliceGuide::Top, Point::new(f64::NAN, f64::NAN)), q);
|
||||
assert_eq!(e.moved(NineSliceGuide::Top, Point::new(0.0, f64::INFINITY)), q);
|
||||
// With the right guide past the art's right edge, the left one may pass that edge too.
|
||||
let wide = SymbolNineSlice { right: -0.5, ..q };
|
||||
let e = editing(Some(wide), xf).edited_nine_slice().unwrap();
|
||||
assert_eq!(e.moved(NineSliceGuide::Left, Point::new(260.0, 50.0)), SymbolNineSlice { left: 1.25, ..wide });
|
||||
assert!(near_point(e.line(NineSliceGuide::Right).0, Point::new(310.0, 20.0)));
|
||||
assert!(near_point(e.line(NineSliceGuide::Right).1, Point::new(310.0, 220.0)));
|
||||
// Saved guides closer than the minimum center band keep their place when a drag does not
|
||||
// move them closer.
|
||||
let narrow = SymbolNineSlice::new(0.00005, 0.25, 0.9999, 0.25).unwrap();
|
||||
let e = editing(Some(narrow), xf).edited_nine_slice().unwrap();
|
||||
assert_eq!(e.moved(NineSliceGuide::Left, Point::new(200.0, 50.0)), narrow);
|
||||
assert_eq!(e.moved(NineSliceGuide::Left, Point::new(0.0, 50.0)), SymbolNineSlice { left: 0.0, ..narrow });
|
||||
assert_eq!(e.moved(NineSliceGuide::Left, Point::new(0.0, 50.0)), SymbolNineSlice { left: -0.05, ..narrow });
|
||||
// A mirrored placement measures along the symbol's own axes.
|
||||
let e = editing(Some(SymbolNineSlice::default()), Affine::scale_non_uniform(-1.0, 1.0)).edited_nine_slice().unwrap();
|
||||
assert!(near_point(e.line(NineSliceGuide::Left).0, Point::new(-25.0, 0.0)));
|
||||
|
||||
@@ -87,6 +87,8 @@ pub struct SymbolBoxes<'a> {
|
||||
sliced_placed: Cell<u64>,
|
||||
/// The most objects of symbol art [`Self::sliced_visual`] places: [`MAX_SYMBOL_NODES`].
|
||||
sliced_most: u64,
|
||||
/// The widths [`Self::measured_width`] has measured, by kind and symbol name.
|
||||
widths: RefCell<HashMap<(&'static str, String), Option<f64>>>,
|
||||
}
|
||||
|
||||
impl Document {
|
||||
@@ -107,6 +109,7 @@ impl Document {
|
||||
sliced: RefCell::default(),
|
||||
sliced_placed: Cell::new(0),
|
||||
sliced_most: MAX_SYMBOL_NODES,
|
||||
widths: RefCell::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -247,6 +250,18 @@ impl<'a> SymbolBoxes<'a> {
|
||||
self.art(name)?.brush
|
||||
}
|
||||
|
||||
/// The width `measure` gives for the symbol named `name`, measured once for these boxes for each
|
||||
/// `kind`, which names what `measure` measures. `measure` may call this again for other names.
|
||||
pub fn measured_width(&self, kind: &'static str, name: &str, measure: impl FnOnce() -> Option<f64>) -> Option<f64> {
|
||||
let key = (kind, name.to_string());
|
||||
if let Some(w) = self.widths.borrow().get(&key) {
|
||||
return *w;
|
||||
}
|
||||
let w = measure();
|
||||
self.widths.borrow_mut().insert(key, w);
|
||||
w
|
||||
}
|
||||
|
||||
/// How far the visual box of an instance of the symbol named `name` grows in boxes made by
|
||||
/// [`Self::with_brush_art`]: `16 × max(w, 1) + 8` for the widest stroke `w` that
|
||||
/// [`Self::brush_width`] finds, as far as the renderer grows the cull bounds of a brushed path
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
//! A warp grid kept before type's measure is registered is built again once it is, even when the
|
||||
//! registered inputs number is 0. One test in its own process, so nothing has registered the
|
||||
//! measure before it runs.
|
||||
// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_doc::live::{EnvelopeOptions, set_type_ink, warp_grid};
|
||||
use vectorcraft_doc::{CharStyle, EnvelopeKind, Node, NodeId, NodeKind, TextObject};
|
||||
use vectorcraft_geom::{Affine, Point, Rect};
|
||||
|
||||
/// A measure that gives every type the same box, well away from its laid-out box.
|
||||
fn fixed_ink(_: &TextObject, _: Affine, _: Option<(vectorcraft_geom::Homography, Affine)>) -> Option<Rect> {
|
||||
Some(Rect::new(0.0, 0.0, 400.0, 300.0))
|
||||
}
|
||||
|
||||
fn no_inputs() -> u64 {
|
||||
0
|
||||
}
|
||||
|
||||
/// An arc warp around `t`, its content in a new `Arc`.
|
||||
fn warp_of(t: &TextObject) -> Node {
|
||||
let content = Arc::new(Node::new(NodeId(1), NodeKind::Text(Box::new(t.clone()))));
|
||||
let kind = EnvelopeKind::Warp { style: "arc".into(), bend: 50.0, h: 0.0, v: 0.0, horizontal: true, version: 1 };
|
||||
Node::new(
|
||||
NodeId(2),
|
||||
NodeKind::Envelope {
|
||||
content: vec![content],
|
||||
kind: Box::new(kind),
|
||||
fidelity: 50.0,
|
||||
editing: false,
|
||||
options: EnvelopeOptions::NEW,
|
||||
frame: Box::new(Affine::IDENTITY),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_warp_grid_kept_before_the_type_measure_is_built_again() {
|
||||
let t = TextObject::point(Point::new(100.0, 100.0), "Type", CharStyle::default());
|
||||
let n = warp_of(&t);
|
||||
let before = warp_grid(&n);
|
||||
set_type_ink(fixed_ink, no_inputs);
|
||||
let fresh = warp_grid(&warp_of(&t));
|
||||
assert!(fresh.is_some());
|
||||
assert_ne!(fresh, before, "the registered measure moves the grid");
|
||||
assert_eq!(warp_grid(&n), fresh, "the grid kept from before the registration is built again");
|
||||
}
|
||||
@@ -29,3 +29,5 @@ serde_json = { workspace = true }
|
||||
vectorcraft-color = { workspace = true }
|
||||
# A face built in code from the bundled Source Sans 3 (no font file is committed).
|
||||
vectorcraft-text = { workspace = true, features = ["test-fonts"] }
|
||||
# Test live-effect plug-ins written in WebAssembly text.
|
||||
wat = { workspace = true }
|
||||
@@ -424,6 +424,8 @@ fn container_keeping_type(d: &Document, n: &Node) -> Option<Node> {
|
||||
if !kept {
|
||||
return None;
|
||||
}
|
||||
// The members' own effects run first, as on the canvas.
|
||||
crate::group::members_as_drawn(Some(d), &mut m);
|
||||
reshape_leaves(&mut m, &fx, &n.appearance.effects, Some(d));
|
||||
m.appearance.effects = crate::raster::without_geometry(&m.appearance.effects);
|
||||
m.appearance.effects.retain(|e| !is_pathfinder(&e.id));
|
||||
|
||||
@@ -182,8 +182,8 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
REVOLVE,
|
||||
"Revolve…",
|
||||
&["Effect", "3D and Materials"],
|
||||
"{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true, close circular ends of open profiles; partial-sweep cut sides stay open), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.",
|
||||
json!({"angle":360.0,"offset":0.0,"edge":"left","rotationX":0.0,"rotationY":0.0,"rotationZ":0.0,"perspectiveAngle":0.0,"segments":64,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"cap":true,"expandVisibleOnly":true}),
|
||||
"{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true, close circular ends of open profiles; partial-sweep cut sides stay open), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.",
|
||||
json!({"angle":360.0,"offset":0.0,"edge":"left","rotationX":0.0,"rotationY":0.0,"rotationZ":0.0,"perspectiveAngle":0.0,"segments":64,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"cap":true,"expandVisibleOnly":true,"graphics":[]}),
|
||||
),
|
||||
g(
|
||||
EXTRUDE,
|
||||
|
||||
@@ -209,6 +209,8 @@ fn reshaped_art(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>, nod
|
||||
Some(area) => Some(reshaped(&area, n, doc)),
|
||||
None => {
|
||||
let mut m = crate::reshape::outlined_members_with(None, doc, n, outline, nodes);
|
||||
// The members' own effects run first, as on the canvas.
|
||||
members_as_drawn(doc, &mut m);
|
||||
let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, &n.appearance.effects, doc);
|
||||
// The group's own fills and strokes follow the effects as its members do.
|
||||
if carry.moves(&m.appearance) {
|
||||
@@ -225,6 +227,7 @@ fn reshaped_art(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>, nod
|
||||
let art = h(n).filter(|art| nodes.charge(art))?;
|
||||
let mut art = crate::reshape::symbol_art_with(&art, h, nodes, symbol);
|
||||
crate::reshape::outline_nested_text(doc, &mut art, false);
|
||||
members_as_drawn(doc, &mut art);
|
||||
let carry = crate::reshape::reshape_leaves_carrying(&mut art, &fx, &n.appearance.effects, doc);
|
||||
// The art's own fills and strokes follow the effects as its members do.
|
||||
if carry.moves(&art.appearance) {
|
||||
@@ -754,7 +757,8 @@ fn take_sublayer_guides(n: &mut Node, out: &mut Vec<Arc<Node>>, hidden: bool, lo
|
||||
}
|
||||
|
||||
/// `n`, a group or layer, as plain art: its Pathfinder effects evaluated, its geometry effects
|
||||
/// reshaping all its members as one piece (the whole art's bounds as their reference box), and its
|
||||
/// reshaping all its members as one piece (the whole art's bounds as their reference box) after
|
||||
/// the members' own geometry and Pathfinder effects ([`members_as_drawn`]), and its
|
||||
/// own fills and strokes turned into art painting the members' geometry ([`member_shapes`]) below
|
||||
/// the members (after a clipping path) or above them, as its contents slot says. Its
|
||||
/// transparency, opacity mask and raster effects stay. `None` when it has none of these. Live
|
||||
@@ -790,6 +794,7 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
}
|
||||
if !fx.is_empty() {
|
||||
m = crate::reshape::outlined_members(doc, &m);
|
||||
members_as_drawn(doc, &mut m);
|
||||
let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, &n.appearance.effects, doc);
|
||||
// The group's own fills and strokes paint the members as a whole: their gradients follow
|
||||
// the effects as the members' do.
|
||||
@@ -821,5 +826,83 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
Some(m)
|
||||
}
|
||||
|
||||
/// Replace each visible member of `n` with geometry or Pathfinder effects of its own, at every
|
||||
/// depth of its groups and layers, by the art it draws ([`evaluate_container`],
|
||||
/// [`crate::reshape::own_effects_art`]), so the geometry effects of `n` reshape what its members
|
||||
/// draw. A clip group's clipping path stays as it is, and so do images, symbol instances and the
|
||||
/// other objects that `own_effects_art` leaves alone, and a group or layer with a 3D effect with
|
||||
/// everything in it. Calls nested in one another, through the
|
||||
/// groups and layers it walks and the art it evaluates (symbol art and Pathfinder members
|
||||
/// included), stop at [`vectorcraft_doc::depth::MAX_DEPTH`] deep, and together they replace at
|
||||
/// most [`crate::SYMBOL_ART_MAX_NODES`] members: past either limit, members stay as they are.
|
||||
pub(crate) fn members_as_drawn(doc: Option<&Document>, n: &mut Node) {
|
||||
let Some(_frame) = DrawnFrame::enter() else { return };
|
||||
let clip = usize::from(n.clips());
|
||||
let Some(ch) = n.children_mut() else { return };
|
||||
for c in ch.iter_mut().skip(clip).filter(|c| c.visible) {
|
||||
if !DrawnFrame::take_member() {
|
||||
return;
|
||||
}
|
||||
// A group or layer with a 3D effect stays whole: the geometry effects listed after its 3D
|
||||
// effect reshape its 3D art.
|
||||
if is_container(c) && (crate::has_solid(c) || crate::has_revolve(c)) {
|
||||
continue;
|
||||
}
|
||||
let art = if !is_container(c) {
|
||||
crate::reshape::own_effects_art(doc, c)
|
||||
} else if has_pathfinder(c) || !crate::reshape::geometry_effects(c).is_empty() {
|
||||
evaluate_container(doc, c)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
match art {
|
||||
Some(a) => *c = Arc::new(a),
|
||||
None if is_container(c) => members_as_drawn(doc, Arc::make_mut(c)),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// How many [`members_as_drawn`] calls are running, one inside another, and how many members
|
||||
/// they have visited since the outermost one started.
|
||||
static DRAWN: std::cell::Cell<(usize, u64)> = const { std::cell::Cell::new((0, 0)) };
|
||||
}
|
||||
|
||||
/// One running [`members_as_drawn`] call, counted in [`DRAWN`] until it is dropped.
|
||||
struct DrawnFrame;
|
||||
|
||||
impl DrawnFrame {
|
||||
/// Count one more call; `None` when [`vectorcraft_doc::depth::MAX_DEPTH`] are running. The
|
||||
/// outermost call starts the count of members again.
|
||||
fn enter() -> Option<Self> {
|
||||
let (frames, members) = DRAWN.with(|d| d.get());
|
||||
if frames >= vectorcraft_doc::depth::MAX_DEPTH {
|
||||
return None;
|
||||
}
|
||||
DRAWN.with(|d| d.set((frames + 1, if frames == 0 { 0 } else { members })));
|
||||
Some(DrawnFrame)
|
||||
}
|
||||
|
||||
/// Count one more member visited; `false` once [`crate::SYMBOL_ART_MAX_NODES`] have been.
|
||||
fn take_member() -> bool {
|
||||
let (frames, members) = DRAWN.with(|d| d.get());
|
||||
if members >= crate::SYMBOL_ART_MAX_NODES {
|
||||
return false;
|
||||
}
|
||||
DRAWN.with(|d| d.set((frames, members + 1)));
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for DrawnFrame {
|
||||
fn drop(&mut self) {
|
||||
DRAWN.with(|d| {
|
||||
let (frames, members) = d.get();
|
||||
d.set((frames.saturating_sub(1), members));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -555,6 +555,298 @@ fn a_nested_groups_own_gradient_follows_the_outer_groups_transform_and_free_dist
|
||||
assert!(near(s, Point::new(0.0, 5.0)) && near(e, Point::new(20.0, 5.0)), "{s:?} {e:?}");
|
||||
}
|
||||
|
||||
/// The bounds of what `n` draws, as the renderer draws it: a group or layer with an appearance of
|
||||
/// its own as the art [`evaluate_container`] makes of it, and each visible path and compound path
|
||||
/// with the geometry effects still on it applied, then those of each visible fill and stroke that
|
||||
/// has some.
|
||||
fn drawn_bounds(n: &Node) -> Option<Rect> {
|
||||
if !n.visible {
|
||||
return None;
|
||||
}
|
||||
if let Some(m) = evaluate_container(None, n) {
|
||||
return drawn_bounds(&m);
|
||||
}
|
||||
if let Some(ch) = n.children()
|
||||
&& !matches!(n.kind, NodeKind::Compound { .. })
|
||||
{
|
||||
return ch.iter().filter_map(|c| drawn_bounds(c)).reduce(|a, b| a.union(b));
|
||||
}
|
||||
let (path, _) = crate::reshape::leaf_geometry(n)?;
|
||||
let geometry = |fx: &[Effect]| -> Vec<Effect> { fx.iter().filter(|e| e.visible && crate::is_geometry(&e.id)).cloned().collect() };
|
||||
let apply = |fx: &[Effect], p: &PathData| crate::apply_geometry(&geometry(fx), p, p.bounds().unwrap());
|
||||
let g = apply(&n.appearance.effects, &path);
|
||||
let items: Vec<&AppearanceItem> = n.appearance.items.iter().filter(|i| paints(i) && !geometry(i.effects()).is_empty()).collect();
|
||||
if items.is_empty() {
|
||||
return g.bounds();
|
||||
}
|
||||
items.iter().filter_map(|i| apply(i.effects(), &g).bounds()).reduce(|a, b| a.union(b))
|
||||
}
|
||||
|
||||
fn black() -> Appearance {
|
||||
Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)
|
||||
}
|
||||
|
||||
/// A black 100 pt square from (100, 100).
|
||||
fn square_at_100() -> Node {
|
||||
Node::path(NodeId(1), shapes::rectangle(Rect::new(100.0, 100.0, 200.0, 200.0)), black())
|
||||
}
|
||||
|
||||
fn effect(id: &str, params: serde_json::Value) -> Effect {
|
||||
Effect { id: id.into(), params, visible: true }
|
||||
}
|
||||
|
||||
fn offset_10() -> Effect {
|
||||
effect("path.offsetPath", serde_json::json!({"offset": 10}))
|
||||
}
|
||||
|
||||
fn scaled(s: f64) -> Effect {
|
||||
effect("distort.transform", serde_json::json!({"scaleH": s, "scaleV": s}))
|
||||
}
|
||||
|
||||
fn with_effect(mut n: Node, e: Effect) -> Node {
|
||||
n.appearance.effects.push(e);
|
||||
n
|
||||
}
|
||||
|
||||
/// The width that a group with `e` holding `member` draws at.
|
||||
fn drawn_width(member: Node, e: Effect) -> f64 {
|
||||
let g = with_effect(Node::group(NodeId(10), vec![Arc::new(member)]), e);
|
||||
drawn_bounds(&g).unwrap().width()
|
||||
}
|
||||
|
||||
/// A member's own Offset Path runs before its group's Transform: the square offset by 10 pt to
|
||||
/// 120 pt, then scaled by half, is 60 pt wide (70 pt the other way round).
|
||||
#[test]
|
||||
fn a_members_own_offset_runs_before_its_groups_scale() {
|
||||
let w = drawn_width(with_effect(square_at_100(), offset_10()), scaled(50.0));
|
||||
assert!((w - 60.0).abs() < 1e-6, "{w}");
|
||||
}
|
||||
|
||||
/// A member's own Transform runs before its group's Offset Path: the square scaled to 200 pt, then
|
||||
/// offset by 10 pt, is 220 pt wide (240 pt the other way round).
|
||||
#[test]
|
||||
fn a_members_own_scale_runs_before_its_groups_offset() {
|
||||
let w = drawn_width(with_effect(square_at_100(), scaled(200.0)), offset_10());
|
||||
assert!((w - 220.0).abs() < 1e-6, "{w}");
|
||||
}
|
||||
|
||||
/// A member inside a plain group inside the group takes its own effects first too.
|
||||
#[test]
|
||||
fn a_member_of_a_plain_nested_group_takes_its_own_effects_first() {
|
||||
let w = drawn_width(Node::group(NodeId(5), vec![Arc::new(with_effect(square_at_100(), offset_10()))]), scaled(50.0));
|
||||
assert!((w - 60.0).abs() < 1e-6, "{w}");
|
||||
}
|
||||
|
||||
/// A nested group's own geometry effects run before the outer group's.
|
||||
#[test]
|
||||
fn a_nested_groups_own_effects_run_before_its_groups() {
|
||||
let w = drawn_width(with_effect(Node::group(NodeId(5), vec![Arc::new(square_at_100())]), offset_10()), scaled(50.0));
|
||||
assert!((w - 60.0).abs() < 1e-6, "{w}");
|
||||
}
|
||||
|
||||
/// A nested group's Pathfinder effect runs before the outer group's geometry effects: the back
|
||||
/// square minus the front one is 50 pt wide, and offset by 10 pt it is 70 pt (offsetting the
|
||||
/// squares first leaves 50 pt).
|
||||
#[test]
|
||||
fn a_nested_groups_pathfinder_runs_before_its_groups_effects() {
|
||||
let back = square_at_100();
|
||||
let front = Node::path(NodeId(2), shapes::rectangle(Rect::new(150.0, 100.0, 250.0, 200.0)), black());
|
||||
let nested = with_effect(Node::group(NodeId(5), vec![Arc::new(back), Arc::new(front)]), effect("pathfinder.subtract", serde_json::json!({})));
|
||||
let w = drawn_width(nested, offset_10());
|
||||
assert!((w - 70.0).abs() < 1e-6, "{w}");
|
||||
}
|
||||
|
||||
/// The geometry effects of a member's own fill run before its group's: 60 pt, as for the
|
||||
/// member's own effect.
|
||||
#[test]
|
||||
fn a_members_fill_effects_run_before_its_groups() {
|
||||
let mut member = square_at_100();
|
||||
member.appearance.items[0].effects_mut().push(offset_10());
|
||||
let w = drawn_width(member, scaled(50.0));
|
||||
assert!((w - 60.0).abs() < 1e-6, "{w}");
|
||||
}
|
||||
|
||||
/// A member whose fills have geometry effects stays one element of a knockout group: its fills do
|
||||
/// not knock each other out.
|
||||
#[test]
|
||||
fn a_member_drawn_as_its_fills_stays_one_knockout_element() {
|
||||
let mut member = square_at_100();
|
||||
member.appearance.items.push(AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(Color::rgb(1.0, 0.0, 0.0)))));
|
||||
member.appearance.items[0].effects_mut().push(offset_10());
|
||||
let mut g = with_effect(Node::group(NodeId(10), vec![Arc::new(member)]), scaled(50.0));
|
||||
g.knockout = vectorcraft_doc::Knockout::On;
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let elements = Node::knockout_elements(art.children().unwrap());
|
||||
assert_eq!(elements.len(), 1, "{:?}", elements.iter().map(|e| (e.id, &e.kind)).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
/// The art a Pathfinder operation or compound shape takes from a group with geometry effects has
|
||||
/// the members' own effects applied first, as the canvas draws it.
|
||||
#[test]
|
||||
fn shape_art_of_a_group_applies_its_members_effects_first() {
|
||||
let g = with_effect(Node::group(NodeId(10), vec![Arc::new(with_effect(square_at_100(), offset_10()))]), scaled(50.0));
|
||||
let art = shape_art(None, &g, None).unwrap();
|
||||
let w = drawn_bounds(&art).unwrap().width();
|
||||
assert!((w - 60.0).abs() < 1e-6, "{w}");
|
||||
let leaves = member_leaves(None, &g, None);
|
||||
let w = leaves.iter().filter_map(drawn_bounds).reduce(|a, b| a.union(b)).unwrap().width();
|
||||
assert!((w - 60.0).abs() < 1e-6, "leaves: {w}");
|
||||
}
|
||||
|
||||
/// A symbol instance's own geometry effects run after those of its symbol's members, as the canvas
|
||||
/// draws it and in the art a Pathfinder operation takes from it.
|
||||
#[test]
|
||||
fn a_symbol_instances_effects_run_after_its_symbols_members_own() {
|
||||
let art = Node::group(NodeId(20), vec![Arc::new(with_effect(square_at_100(), offset_10()))]);
|
||||
let instance =
|
||||
with_effect(Node::new(NodeId(6), NodeKind::SymbolInstance { symbol: "s".into(), xf: vectorcraft_geom::Affine::IDENTITY }), scaled(50.0));
|
||||
let drawn = crate::reshape(None, &instance, Some(&art)).unwrap();
|
||||
let w = drawn_bounds(&drawn).unwrap().width();
|
||||
assert!((w - 60.0).abs() < 1e-6, "drawn: {w}");
|
||||
let hook = move |_: &Node| Some(art.clone());
|
||||
let w = drawn_bounds(&shape_art(None, &instance, Some(&hook)).unwrap()).unwrap().width();
|
||||
assert!((w - 60.0).abs() < 1e-6, "shape art: {w}");
|
||||
}
|
||||
|
||||
/// Export bakes the group as the canvas draws it.
|
||||
#[test]
|
||||
fn a_baked_group_applies_its_members_effects_first() {
|
||||
let mut d = Document::new(800.0, 800.0);
|
||||
let layer = d.layers[0].id;
|
||||
let g = with_effect(Node::group(NodeId(10), vec![Arc::new(with_effect(square_at_100(), offset_10()))]), scaled(50.0));
|
||||
d.insert(Some(layer), 0, g).unwrap();
|
||||
let baked = crate::bake_document(&d).unwrap();
|
||||
let w = baked.node(NodeId(10)).unwrap().geometric_bounds().unwrap().width();
|
||||
assert!((w - 60.0).abs() < 1e-6, "{w}");
|
||||
}
|
||||
|
||||
/// A group whose Transform effect only moves and copies keeps its type when baked; a nested
|
||||
/// group's own Transform still runs before the copies: the nested square scaled by half to 50 pt
|
||||
/// and copied 200 pt to the right spans 250 pt (copying first, then scaling both copies about
|
||||
/// their middle, spans 150 pt).
|
||||
#[test]
|
||||
fn a_baked_group_that_keeps_its_type_applies_its_members_effects_first() {
|
||||
if skip_without_craft_fonts() {
|
||||
return;
|
||||
}
|
||||
let style = CharStyle { size: 24.0, fill: Paint::solid(Color::BLACK), ..Default::default() };
|
||||
let text = Node::new(NodeId(3), NodeKind::Text(Box::new(TextObject::point(Point::new(20.0, 60.0), "Type", style))));
|
||||
let nested = with_effect(Node::group(NodeId(5), vec![Arc::new(square_at_100())]), scaled(50.0));
|
||||
let g = with_effect(
|
||||
Node::group(NodeId(10), vec![Arc::new(text), Arc::new(nested)]),
|
||||
effect("distort.transform", serde_json::json!({"moveH": 200, "copies": 1})),
|
||||
);
|
||||
let mut d = Document::new(800.0, 800.0);
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 0, g).unwrap();
|
||||
let baked = crate::bake_document(&d).unwrap();
|
||||
let mut text = 0;
|
||||
baked.walk(|n| text += usize::from(matches!(n.kind, NodeKind::Text(_))));
|
||||
assert_eq!(text, 2, "the type stays type, copied");
|
||||
let w = baked.node(NodeId(5)).unwrap().geometric_bounds().unwrap().width();
|
||||
assert!((w - 250.0).abs() < 1e-6, "{w}");
|
||||
}
|
||||
|
||||
/// A clip group's clipping path keeps its own effects; the clipped members take theirs first.
|
||||
#[test]
|
||||
fn a_clipping_path_keeps_its_own_effects_under_a_groups_effects() {
|
||||
let mut clip = with_effect(square_at_100(), offset_10());
|
||||
clip.id = NodeId(2);
|
||||
if let NodeKind::Path { clipping, .. } = &mut clip.kind {
|
||||
*clipping = true;
|
||||
}
|
||||
let clipped =
|
||||
Node::new(NodeId(5), NodeKind::Group { children: vec![Arc::new(clip), Arc::new(with_effect(square_at_100(), offset_10()))], clip: true });
|
||||
let g = with_effect(Node::group(NodeId(10), vec![Arc::new(clipped)]), scaled(50.0));
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let clip_group = art.children().unwrap()[0].clone();
|
||||
let ch = clip_group.children().unwrap();
|
||||
assert!(matches!(ch[0].kind, NodeKind::Path { clipping: true, .. }), "{:?}", ch[0].kind);
|
||||
assert_eq!(crate::reshape::geometry_effects(&ch[0]).len(), 1, "the clipping path keeps its Offset Path");
|
||||
assert!(matches!(ch[1].kind, NodeKind::Group { .. }) && crate::reshape::geometry_effects(&ch[1]).is_empty(), "the member is drawn as its art");
|
||||
}
|
||||
|
||||
/// A member with a linked opacity mask keeps its own effects on it, so its mask moves with it
|
||||
/// under the group's Transform; so does a member with a 3D effect, whose later geometry effects
|
||||
/// apply to its 3D art.
|
||||
#[test]
|
||||
fn members_with_linked_masks_or_3d_effects_keep_their_own_effects() {
|
||||
let mut masked = with_effect(square_at_100(), offset_10());
|
||||
masked.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(
|
||||
Node::path(NodeId(2), shapes::rectangle(Rect::new(100.0, 100.0, 200.0, 200.0)), black()),
|
||||
true,
|
||||
)));
|
||||
let mut solid = with_effect(square_at_100(), effect(crate::solids::EXTRUDE, serde_json::json!({})));
|
||||
solid.id = NodeId(3);
|
||||
solid.appearance.effects.push(scaled(50.0));
|
||||
let moved = effect("distort.transform", serde_json::json!({"moveH": 50, "strokes": true}));
|
||||
let g = with_effect(Node::group(NodeId(10), vec![Arc::new(masked), Arc::new(solid)]), moved);
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let ch = art.children().unwrap();
|
||||
assert!(matches!(ch[0].kind, NodeKind::Path { .. }) && crate::reshape::geometry_effects(&ch[0]).len() == 1, "{:?}", ch[0].kind);
|
||||
let mask = ch[0].extras().mask.as_deref().unwrap().art.geometric_bounds().unwrap();
|
||||
assert!((mask.x0 - 150.0).abs() < 1e-6, "the mask moves with the square: {mask:?}");
|
||||
assert!(matches!(ch[1].kind, NodeKind::Path { .. }) && ch[1].appearance.effects.len() == 2, "{:?}", ch[1].kind);
|
||||
}
|
||||
|
||||
/// A nested group with a 3D effect stays as it is, with its members: the Transform listed after
|
||||
/// its Extrude still applies to its 3D art.
|
||||
#[test]
|
||||
fn a_nested_group_with_a_3d_effect_keeps_its_own_effects() {
|
||||
let inner = with_effect(square_at_100(), offset_10());
|
||||
let mut solid = with_effect(Node::group(NodeId(5), vec![Arc::new(inner)]), effect(crate::solids::EXTRUDE, serde_json::json!({})));
|
||||
solid.appearance.effects.push(scaled(50.0));
|
||||
let moved = effect("distort.transform", serde_json::json!({"moveH": 50}));
|
||||
let g = with_effect(Node::group(NodeId(10), vec![Arc::new(solid)]), moved);
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let ch = art.children().unwrap();
|
||||
assert!(
|
||||
matches!(ch[0].kind, NodeKind::Group { .. }) && ch[0].id == NodeId(5) && ch[0].appearance.effects.len() == 2,
|
||||
"{:?}",
|
||||
ch[0].appearance.effects
|
||||
);
|
||||
let member = &ch[0].children().unwrap()[0];
|
||||
assert!(matches!(member.kind, NodeKind::Path { .. }) && crate::reshape::geometry_effects(member).len() == 1, "{:?}", member.kind);
|
||||
}
|
||||
|
||||
/// Members nested deeper than the depth limit keep their own effects as they are.
|
||||
#[test]
|
||||
fn members_past_the_depth_limit_stay_as_they_are() {
|
||||
let mut n = with_effect(square_at_100(), offset_10());
|
||||
for i in 0..vectorcraft_doc::depth::MAX_DEPTH {
|
||||
n = Node::group(NodeId(100 + i as u64), vec![Arc::new(n)]);
|
||||
}
|
||||
let g = with_effect(Node::group(NodeId(10), vec![Arc::new(n)]), scaled(50.0));
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let mut deepest = None;
|
||||
art.walk(&mut |c: &Node| {
|
||||
if c.id == NodeId(1) {
|
||||
deepest = Some(c.clone());
|
||||
}
|
||||
});
|
||||
let deepest = deepest.unwrap();
|
||||
assert!(matches!(deepest.kind, NodeKind::Path { .. }), "{:?}", deepest.kind);
|
||||
assert_eq!(crate::reshape::geometry_effects(&deepest).len(), 1);
|
||||
}
|
||||
|
||||
/// The depth limit counts nested groups with effects of their own too.
|
||||
#[test]
|
||||
fn nested_groups_with_effects_count_toward_the_depth_limit() {
|
||||
let mut n = with_effect(square_at_100(), offset_10());
|
||||
for i in 0..vectorcraft_doc::depth::MAX_DEPTH {
|
||||
n = with_effect(Node::group(NodeId(100 + i as u64), vec![Arc::new(n)]), effect("distort.transform", serde_json::json!({"moveH": 1})));
|
||||
}
|
||||
let g = with_effect(Node::group(NodeId(10), vec![Arc::new(n)]), scaled(50.0));
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let mut deepest = None;
|
||||
art.walk(&mut |c: &Node| {
|
||||
if c.id == NodeId(1) && matches!(c.kind, NodeKind::Path { .. }) {
|
||||
deepest = Some(c.clone());
|
||||
}
|
||||
});
|
||||
assert!(deepest.is_some_and(|d| crate::reshape::geometry_effects(&d).len() == 1), "the deepest member keeps its effect");
|
||||
}
|
||||
|
||||
/// An image or a symbol instance that a group's Transform effect moves takes the placed gradients
|
||||
/// of its own fills along, as a path does, and each copy takes them as many times as it takes the
|
||||
/// transform.
|
||||
|
||||
@@ -95,7 +95,8 @@ pub use solids::{
|
||||
validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options, with_graphic,
|
||||
};
|
||||
pub use solids::{
|
||||
GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, appearance_graphic_symbols, graphic_frame_at, graphics_reshaped_after, rename_appearance_graphic_symbol,
|
||||
GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, graphic_frame_at, graphics_reshaped_after,
|
||||
rename_appearance_graphic_symbol,
|
||||
};
|
||||
pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings};
|
||||
pub use svg_filter::SVG_FILTER;
|
||||
|
||||
+422
-83
@@ -524,9 +524,10 @@ fn with_id(art: &Node, id: NodeId) -> Node {
|
||||
/// `n` as plain art that geometry effects can reshape, without its transparency and object
|
||||
/// effects: type outlined ([`outline_text`]), live objects evaluated (type inside them outlined),
|
||||
/// a symbol instance as `symbol_art` (the symbol's art, stained as the caller draws it) placed by
|
||||
/// the instance's transform (through the symbol's 9-slice guides in `doc`, when it has them), its
|
||||
/// fills and strokes carrying the geometry effects of the instance's active fill and stroke
|
||||
/// ([`add_instance_row_effects`]).
|
||||
/// the instance's transform (through the symbol's 9-slice guides in `doc`, when it has them), as
|
||||
/// the art its members draw when the instance has geometry effects of its own
|
||||
/// ([`crate::group::members_as_drawn`]), its fills and strokes carrying the geometry effects of the
|
||||
/// instance's active fill and stroke ([`add_instance_row_effects`]).
|
||||
/// `None` for other kinds (images, paths, containers), and for an instance whose art placed
|
||||
/// through the guides could hold more than [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects. A Repeat counts the Repeats in the art of
|
||||
/// `doc`'s symbols that its instances show toward its instance budget.
|
||||
@@ -562,20 +563,16 @@ fn outline_art_with(
|
||||
Node::group(n.id, vec![Arc::new(a)])
|
||||
}
|
||||
// The object as the one piece the copies of its Transform effect are made from.
|
||||
_ if has_transform_art(n) || (apart && has_transform_copies(n)) => {
|
||||
let mut one = n.clone();
|
||||
one.opacity = 1.0;
|
||||
one.blend = Default::default();
|
||||
one.isolate = false;
|
||||
one.extras_mut().mask = None;
|
||||
one.appearance.effects.clear();
|
||||
Node::group(n.id, vec![Arc::new(one)])
|
||||
}
|
||||
_ if has_transform_art(n) || (apart && has_transform_copies(n)) => one_piece(n),
|
||||
_ if vectorcraft_doc::live::is_live(n) => evaluated_with(symbols, n, outline, nodes),
|
||||
_ => return None,
|
||||
};
|
||||
outline_nested_text(paint_doc, &mut art, false);
|
||||
if matches!(n.kind, NodeKind::SymbolInstance { .. }) {
|
||||
// The instance's own geometry effects reshape what the symbol's members draw.
|
||||
if !geometry_effects(n).is_empty() {
|
||||
crate::group::members_as_drawn(paint_doc, &mut art);
|
||||
}
|
||||
add_instance_row_effects(symbols, n, &mut art);
|
||||
}
|
||||
art.opacity = 1.0;
|
||||
@@ -843,18 +840,64 @@ fn as_art_opts(
|
||||
}
|
||||
// The art is a group with `n`'s id (for an image without fills or strokes that paint, a clip
|
||||
// group).
|
||||
let mut out = art;
|
||||
out.name = n.name.clone();
|
||||
out.visible = n.visible;
|
||||
out.opacity = n.opacity;
|
||||
out.blend = n.blend;
|
||||
out.isolate = n.isolate;
|
||||
Some(dressed(art, n))
|
||||
}
|
||||
|
||||
/// `art`, the art made of `n`, with `n`'s name, visibility, transparency, opacity mask and
|
||||
/// remaining (raster) effects.
|
||||
fn dressed(mut art: Node, n: &Node) -> Node {
|
||||
art.name = n.name.clone();
|
||||
art.visible = n.visible;
|
||||
art.opacity = n.opacity;
|
||||
art.blend = n.blend;
|
||||
art.isolate = n.isolate;
|
||||
// One element: its pieces never knock each other out.
|
||||
out.knockout = vectorcraft_doc::Knockout::Off;
|
||||
out.knockout_shape = n.knockout_shape;
|
||||
out.extras_mut().mask = n.extras().mask.clone();
|
||||
out.appearance.effects = crate::raster::without_geometry(&n.appearance.effects);
|
||||
Some(out)
|
||||
art.knockout = vectorcraft_doc::Knockout::Off;
|
||||
art.knockout_shape = n.knockout_shape;
|
||||
art.extras_mut().mask = n.extras().mask.clone();
|
||||
art.appearance.effects = crate::raster::without_geometry(&n.appearance.effects);
|
||||
art
|
||||
}
|
||||
|
||||
/// A group with `n`'s id holding `n` without its transparency, opacity mask and effects: the one
|
||||
/// piece that `n`'s own geometry effects reshape.
|
||||
fn one_piece(n: &Node) -> Node {
|
||||
let mut one = n.clone();
|
||||
one.opacity = 1.0;
|
||||
one.blend = Default::default();
|
||||
one.isolate = false;
|
||||
one.extras_mut().mask = None;
|
||||
one.appearance.effects.clear();
|
||||
Node::group(n.id, vec![Arc::new(one)])
|
||||
}
|
||||
|
||||
/// Path or compound path `n` with its own geometry effects applied, as the art it draws: with
|
||||
/// geometry effects in a visible fill or stroke of its own, a group of one path for each fill and
|
||||
/// stroke, its effects and that fill's or stroke's applied ([`crate::bake_type_appearance`]);
|
||||
/// otherwise a group with `n`'s id holding the path reshaped by its effects ([`reshape_leaves`]).
|
||||
/// The art keeps `n`'s id, name, visibility, transparency, opacity mask and raster effects. `None`
|
||||
/// for a guide, for other kinds of objects, for a path with a linked opacity mask or a 3D effect,
|
||||
/// and when `n` has no visible geometry effect of its own or in a visible fill or stroke.
|
||||
pub(crate) fn own_effects_art(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
if !matches!(n.kind, NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. })
|
||||
|| n.extras().mask.as_ref().is_some_and(|m| m.linked)
|
||||
|| crate::has_solid(n)
|
||||
|| crate::has_revolve(n)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
if n.appearance.items.iter().any(|i| crate::paints(i) && crate::has_geometry(i.effects())) {
|
||||
// One element: its pieces never knock each other out.
|
||||
return crate::bake_type_appearance(doc, n).map(|art| Node { knockout: vectorcraft_doc::Knockout::Off, ..art });
|
||||
}
|
||||
let fx = geometry_effects(n);
|
||||
if fx.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut art = one_piece(n);
|
||||
reshape_leaves(&mut art, &fx, &n.appearance.effects, doc);
|
||||
transform_items(&mut art, doc);
|
||||
Some(dressed(art, n))
|
||||
}
|
||||
|
||||
/// Map every path under `art` (and its gradients), and every path in the art of the linked opacity
|
||||
@@ -1858,22 +1901,30 @@ fn paint_leaf(
|
||||
/// effects' budget for the object it becomes, so that a budget of [`Budget::EFFECTS`] holds at most
|
||||
/// [`MAX_OBJECTS`](vectorcraft_plugins::objects::MAX_OBJECTS) pieces however small their paths.
|
||||
fn piece_cost(path: &PathData) -> Budget {
|
||||
Budget::of(path).plus(piece_share())
|
||||
}
|
||||
|
||||
/// The share of the effects' budget each painted piece costs besides its path ([`piece_cost`]).
|
||||
fn piece_share() -> Budget {
|
||||
let max = vectorcraft_plugins::objects::MAX_OBJECTS;
|
||||
Budget::of(path).plus(Budget { anchors: Budget::EFFECTS.anchors / max, lines: Budget::EFFECTS.lines / max })
|
||||
Budget { anchors: Budget::EFFECTS.anchors / max, lines: Budget::EFFECTS.lines / max }
|
||||
}
|
||||
|
||||
/// Live-effect plug-in `plugin` (one that paints what it returns) with `params`, a later effect of
|
||||
/// `item`, run on `leaf`, a path of [`transform_piece`] painted by copies of `item`, with reference
|
||||
/// box `bounds`: `leaf` becomes a group of one path for each piece returned, in order. A piece that
|
||||
/// gives fills (on a fill) or strokes (on a stroke) is painted by copies of `item`, the leaf's first
|
||||
/// fill or stroke, with those paints ([`vectorcraft_plugins::painted::items`]), under the leaf's
|
||||
/// other fills and strokes; one that gives none keeps the leaf's. Returns
|
||||
/// `item`, run on `leaf`, a path of [`transform_piece`] painted by `item` (its first fill or stroke),
|
||||
/// with reference box `bounds`: `leaf` becomes a group of one path for each piece returned, in
|
||||
/// order. The plug-in is given `appearance`'s fills and strokes and told that it is on item `index`
|
||||
/// of them. A piece that gives fills (on a fill) or strokes (on a stroke) is painted by copies of
|
||||
/// `item` with those paints ([`vectorcraft_plugins::painted::items`]), under the leaf's other fills
|
||||
/// and strokes; one that gives none keeps the leaf's. Returns
|
||||
/// what the paths cost ([`piece_cost`]); `None` (the leaf stays as it is) when the plug-in fails,
|
||||
/// the pieces are refused (a swatch or pattern not in `doc`, or any without one), or they would pass
|
||||
/// `budget`. A deferred run is listed by `at`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn paint_piece(
|
||||
leaf: &mut Node,
|
||||
item: &AppearanceItem,
|
||||
(appearance, index): (&Appearance, usize),
|
||||
(plugin, params): (&str, &serde_json::Value),
|
||||
bounds: Rect,
|
||||
budget: Budget,
|
||||
@@ -1881,7 +1932,7 @@ fn paint_piece(
|
||||
at: Option<vectorcraft_plugins::deferred::Stage>,
|
||||
) -> Option<Budget> {
|
||||
let (path, rule) = leaf_geometry(leaf)?;
|
||||
let paints = vectorcraft_plugins::effect::Paints { appearance: Some(&leaf.appearance), item: Some(0), at };
|
||||
let paints = vectorcraft_plugins::effect::Paints { appearance: Some(appearance), item: Some(index), at };
|
||||
let pieces = vectorcraft_plugins::effect::apply_painted(plugin, params, &path, bounds, rule, paints, doc)?;
|
||||
let made = pieces.iter().map(|p| piece_cost(&p.path)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus);
|
||||
if !budget.fits(made) {
|
||||
@@ -2050,7 +2101,7 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
|
||||
group.push(Arc::new(p));
|
||||
}
|
||||
let mut p = Node::group(leaf.id, group);
|
||||
transform_piece(&mut p, (ctx.seed, i, &kept), crate::raster::held_back(before), limit, used, doc);
|
||||
transform_piece(&mut p, (ctx.seed, i, &kept), crate::raster::held_back(before), true, limit, used, doc);
|
||||
pieces.push(Arc::new(p));
|
||||
continue;
|
||||
}
|
||||
@@ -2073,7 +2124,7 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
|
||||
if moved && !held_later {
|
||||
follow_piece(&mut p, kept_before.get(from..).unwrap_or_default(), from, &fx[at]);
|
||||
}
|
||||
transform_piece(&mut p, (ctx.seed, i, &kept), crate::raster::held_back(&fx[..=at]), limit, used, doc);
|
||||
transform_piece(&mut p, (ctx.seed, i, &kept), crate::raster::held_back(&fx[..=at]), false, limit, used, doc);
|
||||
pieces.push(Arc::new(p));
|
||||
}
|
||||
if !plain.is_empty() {
|
||||
@@ -2086,7 +2137,7 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
|
||||
leaf.kind = NodeKind::Group { children: pieces, clip: false };
|
||||
}
|
||||
|
||||
/// Apply the visible geometry effects left on the one fill or stroke of each path under `p` (a
|
||||
/// Apply the visible geometry effects left on the fills or strokes of each path under `p` (a
|
||||
/// transformed piece of [`transform_item_leaf`] and its copies) to all of `p`'s paths as one piece:
|
||||
/// each effect takes the bounds of all the paths as its reference box and `seed`, as an object's
|
||||
/// own effects reshape all its paths ([`reshape_leaves_carrying`]). Each path applies its own copy of
|
||||
@@ -2095,19 +2146,32 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
|
||||
/// the effects after it, and with Transform Objects off those before it, as they are
|
||||
/// ([`keep_listed`]).
|
||||
/// A live-effect plug-in that paints what it returns ([`painted_plugin`]) makes each path one path
|
||||
/// for each piece it returns ([`paint_piece`]). The raster effects before a Transform effect
|
||||
/// follow it ([`follow_piece`]), except the first `held` effects, which a Transform effect before
|
||||
/// the piece's effects that makes copies or moves at random holds back, and the effects before
|
||||
/// such a Transform effect among the piece's effects. The geometry effects then
|
||||
/// for each piece it returns ([`paint_piece`]). A path with several fills or strokes (those a
|
||||
/// painted plug-in returned) takes such an effect, a live-effect plug-in or a geometry effect on
|
||||
/// strokes once for each of them, in paint order, given its own place among them
|
||||
/// ([`shares_stage`]): each run's pieces replace only that fill or stroke, and a run that fails or
|
||||
/// would pass the budget leaves that fill or stroke on the path as it was. The raster effects
|
||||
/// before a Transform effect follow it ([`follow_piece`]), except the first `held` effects, which
|
||||
/// a Transform effect before the piece's effects that makes copies or moves at random holds back,
|
||||
/// and the effects before such a Transform effect among the piece's effects. The geometry effects then
|
||||
/// leave the fills and strokes; their other effects stay. The paths keep to `max` together with
|
||||
/// the rest of the art (`used`), and the swatches and patterns painted pieces name must be in
|
||||
/// `doc`. `(seed, source, kept)`: the object's seed, the index in the object's appearance of the
|
||||
/// fill or stroke the piece was made from, and the index among that item's effects of each effect
|
||||
/// the piece kept, which a deferred live-effect plug-in is listed by.
|
||||
fn transform_piece(p: &mut Node, (seed, source, kept): (u64, usize, &[usize]), held: usize, max: Budget, used: &mut Budget, doc: Option<&Document>) {
|
||||
/// the piece kept, which a deferred live-effect plug-in is listed by. `painted`: `p`'s paths are
|
||||
/// the pieces of a painted run, each of which `used` counts at [`piece_cost`].
|
||||
fn transform_piece(
|
||||
p: &mut Node,
|
||||
(seed, source, kept): (u64, usize, &[usize]),
|
||||
held: usize,
|
||||
painted: bool,
|
||||
max: Budget,
|
||||
used: &mut Budget,
|
||||
doc: Option<&Document>,
|
||||
) {
|
||||
let mut count = 0;
|
||||
for_each_leaf(p, &mut |l| {
|
||||
if let Some(item) = l.appearance.items.first() {
|
||||
for item in &l.appearance.items {
|
||||
count = count.max(item.effects().len());
|
||||
}
|
||||
});
|
||||
@@ -2115,60 +2179,207 @@ fn transform_piece(p: &mut Node, (seed, source, kept): (u64, usize, &[usize]), h
|
||||
// random are held back from the Transform effects before it too.
|
||||
let mut held = held;
|
||||
for_each_leaf(p, &mut |l| {
|
||||
if let Some(last) = l.appearance.items.first().and_then(|item| item.effects().iter().rposition(crate::raster::holds_back)) {
|
||||
held = held.max(last);
|
||||
for item in &l.appearance.items {
|
||||
if let Some(last) = item.effects().iter().rposition(crate::raster::holds_back) {
|
||||
held = held.max(last);
|
||||
}
|
||||
}
|
||||
});
|
||||
// Whether `used` counts each path under `p`, in the order `for_each_leaf` visits them, at
|
||||
// [`piece_cost`] (its geometry and a painted piece's share) rather than at its geometry alone.
|
||||
// The pieces of a painted run are counted so, and so is the first path an effect makes of one
|
||||
// that was: the paths of a Transform effect's copies share their original's share.
|
||||
let mut shares = vec![painted; leaf_count(p)];
|
||||
for j in 0..count {
|
||||
let Some(bounds) = p.geometric_bounds() else { break };
|
||||
let from = held.min(j);
|
||||
let mut holds = false;
|
||||
for_each_leaf(p, &mut |leaf| {
|
||||
let Some(item) = leaf.appearance.items.first().cloned() else { return };
|
||||
let Some(e) = item.effects().get(j).filter(|e| e.visible && is_geometry(&e.id)).cloned() else { return };
|
||||
holds |= crate::raster::holds_back(&e);
|
||||
// The effects before this one as they were before it moved the path.
|
||||
let was = item.effects().get(from..j).unwrap_or_default();
|
||||
let Some((path, rule)) = leaf_geometry(leaf) else { return };
|
||||
// What the other paths leave of the budget.
|
||||
let before = Budget::of(&path);
|
||||
let room = max.minus(used.minus(before));
|
||||
let stage = vectorcraft_plugins::deferred::Stage { object: seed, effect: kept.get(j).copied().unwrap_or(j), item: Some(source) };
|
||||
if let Some(plugin) = painted_plugin(&e) {
|
||||
if let Some(made) = paint_piece(leaf, &item, (plugin, &merged_params(&e.id, &e.params)), bounds, room, doc, Some(stage)) {
|
||||
*used = used.minus(before).plus(made);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if reaches_appearance(&e) {
|
||||
let params = merged_params(&e.id, &e.params);
|
||||
let (_, copies) = crate::distort::transform_map(bounds, ¶ms, seed);
|
||||
let options = crate::distort::TransformOptions::of(¶ms);
|
||||
let map = crate::distort::transform_affine(bounds, ¶ms, seed);
|
||||
let keep = |k: usize| k > j || (k < j && !options.objects);
|
||||
let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, false, Some((item.effects(), &keep)));
|
||||
let stage = vectorcraft_plugins::deferred::Stage { object: seed, effect: kept.get(j).copied().unwrap_or(j), item: Some(source) };
|
||||
let at = PieceStage { j, from, seed, bounds, doc, stage };
|
||||
// Stage `j` on `leaf`, a path `used` counts at `piece_cost` when `share`: whether `used`
|
||||
// counts each path it became so, or `None` when it stays as it was.
|
||||
let mut on_leaf = |leaf: &mut Node, share: bool| -> Option<Vec<bool>> {
|
||||
let effect = |item: &AppearanceItem| item.effects().get(j).filter(|e| e.visible && is_geometry(&e.id)).cloned();
|
||||
let items = &leaf.appearance.items;
|
||||
let first = items.first()?;
|
||||
let (path, _) = leaf_geometry(leaf)?;
|
||||
// What `used` counts the path at; what the other paths leave of the budget is the rest.
|
||||
let geometry = Budget::of(&path);
|
||||
let counted = if share { piece_cost(&path) } else { geometry };
|
||||
if shares_stage(items, j) {
|
||||
let e = effect(first)?;
|
||||
holds |= crate::raster::holds_back(&e);
|
||||
let appearance = leaf.appearance.clone();
|
||||
// A painted run's pieces each cost a share of their own ([`paint_piece`]); the
|
||||
// paths of any other effect keep the leaf's.
|
||||
let painted = painted_plugin(&e).is_some();
|
||||
let before = if painted { counted } else { geometry };
|
||||
let room = max.minus(used.minus(before));
|
||||
let made = piece_stage(leaf, &e, &at, (&appearance, 0), room)?;
|
||||
*used = used.minus(before).plus(made);
|
||||
if moved {
|
||||
follow_piece(leaf, was, from, &e);
|
||||
}
|
||||
return;
|
||||
return Some((0..leaf_count(leaf)).map(|k| painted || (share && k == 0)).collect());
|
||||
}
|
||||
// Each fill or stroke takes the effect on its own path, given the leaf's fills and
|
||||
// strokes and its own place among them; those left with the same path as the one
|
||||
// before them stay on it. Each path costs its geometry and a painted piece's share.
|
||||
// Each run is first given all the room the art leaves. When a fill or stroke that keeps
|
||||
// the leaf's path then finds no room for its copy of it, the results are placed again,
|
||||
// each but the last leaving room for one more copy of the leaf's own path; a result
|
||||
// that does not fit that room is left out. Only a fill or stroke that keeps the leaf's
|
||||
// path right after one that changed costs such a copy (the ones after it stay on that
|
||||
// copy), so every copy fits but the first fill's or stroke's, when the art leaves no
|
||||
// room for it: the leaf then stays as it was. A live-effect plug-in is given all the
|
||||
// room the art leaves, and each placing checks that its result fits; a built-in effect
|
||||
// builds within the room of each placing.
|
||||
let appearance = leaf.appearance.clone();
|
||||
let stroke = match &item {
|
||||
AppearanceItem::Stroke(s) => Some(s),
|
||||
AppearanceItem::Fill(_) => None,
|
||||
let one = piece_cost(&path);
|
||||
let n = appearance.items.len();
|
||||
let base = used.minus(counted);
|
||||
let alone = |item: &AppearanceItem| {
|
||||
let mut sub = leaf.clone();
|
||||
sub.appearance.items = vec![item.clone()];
|
||||
sub
|
||||
};
|
||||
let ctx = GeomContext { stroke, rule, seed, appearance: Some(&appearance), item: Some(0), doc, stage: Some(stage) };
|
||||
let mut carry = crate::Carry::default();
|
||||
let out = crate::geometry::apply_geometry_carrying_within(std::slice::from_ref(&e), &path, bounds, &ctx, room, Some(&mut carry));
|
||||
*used = used.minus(before).plus(Budget::of(&out));
|
||||
// The fill's or stroke's gradient follows the effect as the object's does.
|
||||
if carry.moves(&leaf.appearance) {
|
||||
carry.apply(&mut leaf.appearance);
|
||||
}
|
||||
set_geometry(leaf, out, rule);
|
||||
follow_piece(leaf, was, from, &e);
|
||||
// `item`, the `k`th fill or stroke, alone on the leaf's path with effect `e` applied
|
||||
// within `room`, and what its paths cost; `None` when it failed or found no room.
|
||||
let apply = |item: &AppearanceItem, k: usize, e: &Effect, room: Budget| {
|
||||
let painted = painted_plugin(e).is_some();
|
||||
let room = if painted { room } else { room.minus(piece_share()) };
|
||||
let mut sub = alone(item);
|
||||
let made = piece_stage(&mut sub, e, &at, (&appearance, k), room)?;
|
||||
Some((sub, if painted { made } else { made.plus(piece_share()) }))
|
||||
};
|
||||
// Each fill's or stroke's live-effect plug-in run. A result is kept only while a
|
||||
// placing places it on a path of its own; one that does not fit is dropped, with what
|
||||
// it cost, and the plug-in runs again in the second placing only when that much room
|
||||
// is left there (a result small enough to cache comes back from the cache). A result
|
||||
// with the same path as the one before it costs nothing: it is placed on that path
|
||||
// whatever room is left, and dropped once its fill or stroke is moved there. The
|
||||
// results kept at once cost at most what the two placings place.
|
||||
let mut runs: Vec<PluginRun> = vec![PluginRun::Not; n];
|
||||
let mut kept_cost = Budget { anchors: 0, lines: 0 };
|
||||
// Each placing gives the paths, whether `used` counts each of the paths they hold at
|
||||
// `piece_cost` (all of a painted run's, and the first of any other result's), and what
|
||||
// the art then spends.
|
||||
let mut split = |reserve: bool| -> Option<(Vec<Node>, Vec<bool>, Budget)> {
|
||||
let mut spent = base;
|
||||
let mut out: Vec<Node> = vec![];
|
||||
let mut counts: Vec<bool> = vec![];
|
||||
for (k, (item, ran)) in appearance.items.iter().zip(runs.iter_mut()).enumerate() {
|
||||
let room = if reserve && k + 1 < n { max.minus(spent).minus(one) } else { max.minus(spent) };
|
||||
let e = effect(item);
|
||||
let paints = e.as_ref().is_some_and(|e| painted_plugin(e).is_some());
|
||||
// Does `sub` stay on the path of the result before it, at no cost?
|
||||
let merges = |sub: &Node| out.last().is_some_and(|last| same_path(last, sub));
|
||||
// What the kept plug-in result this fill or stroke takes cost.
|
||||
let mut taken = None;
|
||||
let result = match e {
|
||||
None => None,
|
||||
Some(e) => {
|
||||
holds |= crate::raster::holds_back(&e);
|
||||
if vectorcraft_plugins::effect::plugin_id(&e.id).is_some() {
|
||||
let again = match ran {
|
||||
PluginRun::Not | PluginRun::Merged => true,
|
||||
PluginRun::Left(cost) => room.fits(*cost),
|
||||
PluginRun::Kept(..) | PluginRun::Failed => false,
|
||||
};
|
||||
if again {
|
||||
#[cfg(test)]
|
||||
PLUGIN_RUNS.with(|n| n.set(n.get() + 1));
|
||||
*ran = match apply(item, k, &e, max.minus(base)) {
|
||||
None => PluginRun::Failed,
|
||||
Some((sub, cost)) if !room.fits(cost) && !merges(&sub) => PluginRun::Left(cost),
|
||||
Some((sub, cost)) => {
|
||||
kept_cost = kept_cost.plus(cost);
|
||||
PluginRun::Kept(sub, cost)
|
||||
}
|
||||
};
|
||||
}
|
||||
match ran {
|
||||
PluginRun::Kept(sub, cost) if room.fits(*cost) || merges(sub) => {
|
||||
taken = Some(*cost);
|
||||
Some((sub.clone(), *cost))
|
||||
}
|
||||
PluginRun::Kept(_, cost) => {
|
||||
let cost = *cost;
|
||||
kept_cost = kept_cost.minus(cost);
|
||||
*ran = PluginRun::Left(cost);
|
||||
None
|
||||
}
|
||||
PluginRun::Not | PluginRun::Merged | PluginRun::Left(_) | PluginRun::Failed => None,
|
||||
}
|
||||
} else {
|
||||
// A built-in effect that finds no room within `room` leaves the
|
||||
// leaf's path. When its result is not on the path before it, it
|
||||
// is built again with all the room the art leaves and taken only
|
||||
// when that result is on the path before it, which costs nothing.
|
||||
let made = apply(item, k, &e, room);
|
||||
let short = match &made {
|
||||
None => true,
|
||||
Some((sub, cost)) => !merges(sub) && (!room.fits(*cost) || same_path(sub, leaf)),
|
||||
};
|
||||
match out.last() {
|
||||
Some(_) if short => match apply(item, k, &e, max.minus(base)) {
|
||||
Some((sub, cost)) if merges(&sub) => Some((sub, cost)),
|
||||
_ => made,
|
||||
},
|
||||
_ => made,
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
let placed = match result {
|
||||
Some((sub, cost)) if room.fits(cost) || merges(&sub) => Some((sub, cost, paints)),
|
||||
_ => None,
|
||||
};
|
||||
// A fill or stroke whose result is not placed stays on the leaf's path, which
|
||||
// is copied only when the path before it is another.
|
||||
let (mut sub, cost, all) = match placed {
|
||||
Some(placed) => placed,
|
||||
None => match out.last_mut() {
|
||||
Some(last) if same_path(last, leaf) => {
|
||||
last.appearance.items.push(item.clone());
|
||||
continue;
|
||||
}
|
||||
_ => (alone(item), one, true),
|
||||
},
|
||||
};
|
||||
match out.last_mut() {
|
||||
Some(last) if same_path(last, &sub) => {
|
||||
last.appearance.items.append(&mut sub.appearance.items);
|
||||
if let Some(cost) = taken {
|
||||
kept_cost = kept_cost.minus(cost);
|
||||
*ran = PluginRun::Merged;
|
||||
}
|
||||
}
|
||||
_ if !max.minus(spent).fits(cost) => return None,
|
||||
_ => {
|
||||
spent = spent.plus(cost);
|
||||
counts.extend((0..leaf_count(&sub)).map(|k| all || k == 0));
|
||||
out.push(sub);
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
HELD_PEAK.with(|p| p.set(p.get().at_least(kept_cost)));
|
||||
}
|
||||
Some((out, counts, spent))
|
||||
};
|
||||
let (mut out, counts, spent) = split(false).or_else(|| split(true))?;
|
||||
*used = spent;
|
||||
*leaf = match out.len() {
|
||||
1 => out.pop().unwrap_or_else(|| leaf.clone()),
|
||||
_ => Node::group(leaf.id, out.into_iter().map(Arc::new).collect()),
|
||||
};
|
||||
Some(counts)
|
||||
};
|
||||
let mut next: Vec<bool> = vec![];
|
||||
let mut visited = 0;
|
||||
for_each_leaf(p, &mut |leaf| {
|
||||
let share = shares.get(visited).copied().unwrap_or(false);
|
||||
visited += 1;
|
||||
next.extend(on_leaf(leaf, share).unwrap_or_else(|| vec![share]));
|
||||
});
|
||||
shares = next;
|
||||
if holds {
|
||||
held = held.max(j);
|
||||
}
|
||||
@@ -2180,6 +2391,134 @@ fn transform_piece(p: &mut Node, (seed, source, kept): (u64, usize, &[usize]), h
|
||||
});
|
||||
}
|
||||
|
||||
/// A fill's or stroke's live-effect plug-in run in a placing of [`transform_piece`]: not run yet,
|
||||
/// its result and what that costs while a placing places it on a path of its own, what a result
|
||||
/// that did not fit cost (the result itself is dropped), a result dropped once its fill or stroke
|
||||
/// was placed on the path before it, or failed.
|
||||
#[derive(Clone)]
|
||||
enum PluginRun {
|
||||
Not,
|
||||
Kept(Node, Budget),
|
||||
Left(Budget),
|
||||
Merged,
|
||||
Failed,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// The most the live-effect plug-in results [`transform_piece`] keeps from one fill or stroke
|
||||
/// to the next have cost at once on this thread.
|
||||
pub(crate) static HELD_PEAK: std::cell::Cell<Budget> = const { std::cell::Cell::new(Budget { anchors: 0, lines: 0 }) };
|
||||
/// How many times [`transform_piece`] has run a fill's or stroke's live-effect plug-in on this
|
||||
/// thread when they did not share the stage.
|
||||
pub(crate) static PLUGIN_RUNS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Where a stage of [`transform_piece`] runs: `j`, the index of its effect among the piece's
|
||||
/// effects; `from`, the first of the effects before it whose raster effects follow a Transform
|
||||
/// effect; the object's `seed`; the reference box `bounds` of all the piece's paths; the document
|
||||
/// that painted pieces' swatches and patterns must be in; and the `stage` a deferred live-effect
|
||||
/// plug-in is listed by.
|
||||
struct PieceStage<'a> {
|
||||
j: usize,
|
||||
from: usize,
|
||||
seed: u64,
|
||||
bounds: Rect,
|
||||
doc: Option<&'a Document>,
|
||||
stage: vectorcraft_plugins::deferred::Stage,
|
||||
}
|
||||
|
||||
/// Can stage `j` of [`transform_piece`] run once for all of a path's `items`: there is at most one,
|
||||
/// or they hold the same effects and the effect at `j` is not a visible geometry effect, is a
|
||||
/// Transform effect, or is a built-in geometry effect and they are all fills (an effect that
|
||||
/// changes a fill's path does not depend on which fill it is on)?
|
||||
fn shares_stage(items: &[AppearanceItem], j: usize) -> bool {
|
||||
let Some(first) = items.first() else { return true };
|
||||
if items.len() == 1 {
|
||||
return true;
|
||||
}
|
||||
if !items.iter().all(|i| i.effects() == first.effects()) {
|
||||
return false;
|
||||
}
|
||||
match first.effects().get(j) {
|
||||
Some(e) if e.visible && is_geometry(&e.id) => {
|
||||
vectorcraft_plugins::effect::plugin_id(&e.id).is_none() && (reaches_appearance(e) || items.iter().all(AppearanceItem::is_fill))
|
||||
}
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Effect `e`, a visible geometry effect at stage `at` of [`transform_piece`], applied to `leaf`, a
|
||||
/// path painted by its first fill or stroke (and, when they share the stage, [`shares_stage`], the
|
||||
/// others): `appearance` is what the effect is given of the path's fills and strokes and `index`
|
||||
/// which of them it is on. A live-effect plug-in that paints what it returns makes `leaf` a group
|
||||
/// of its pieces ([`paint_piece`]), and a Transform effect that reaches its appearance transforms
|
||||
/// it ([`transform_leaf`]). Returns what the new paths cost, within `room`; `None` when `leaf`
|
||||
/// stays as it is.
|
||||
fn piece_stage(leaf: &mut Node, e: &Effect, at: &PieceStage, (appearance, index): (&Appearance, usize), room: Budget) -> Option<Budget> {
|
||||
let item = leaf.appearance.items.first()?.clone();
|
||||
// The effects before this one as they were before it moved the path.
|
||||
let was = item.effects().get(at.from..at.j).unwrap_or_default();
|
||||
let (path, rule) = leaf_geometry(leaf)?;
|
||||
if let Some(plugin) = painted_plugin(e) {
|
||||
let params = merged_params(&e.id, &e.params);
|
||||
return paint_piece(leaf, &item, (appearance, index), (plugin, ¶ms), at.bounds, room, at.doc, Some(at.stage));
|
||||
}
|
||||
if reaches_appearance(e) {
|
||||
let params = merged_params(&e.id, &e.params);
|
||||
let (_, copies) = crate::distort::transform_map(at.bounds, ¶ms, at.seed);
|
||||
let options = crate::distort::TransformOptions::of(¶ms);
|
||||
let map = crate::distort::transform_affine(at.bounds, ¶ms, at.seed);
|
||||
let j = at.j;
|
||||
let keep = |k: usize| k > j || (k < j && !options.objects);
|
||||
let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, false, Some((item.effects(), &keep)));
|
||||
if moved {
|
||||
follow_piece(leaf, was, at.from, e);
|
||||
}
|
||||
return Some(made);
|
||||
}
|
||||
let stroke = match &item {
|
||||
AppearanceItem::Stroke(s) => Some(s),
|
||||
AppearanceItem::Fill(_) => None,
|
||||
};
|
||||
let ctx = GeomContext { stroke, rule, seed: at.seed, appearance: Some(appearance), item: Some(index), doc: at.doc, stage: Some(at.stage) };
|
||||
let mut carry = crate::Carry::default();
|
||||
let out = crate::geometry::apply_geometry_carrying_within(std::slice::from_ref(e), &path, at.bounds, &ctx, room, Some(&mut carry));
|
||||
let made = Budget::of(&out);
|
||||
// The fill's or stroke's gradient follows the effect as the object's does.
|
||||
if carry.moves(&leaf.appearance) {
|
||||
carry.apply(&mut leaf.appearance);
|
||||
}
|
||||
set_geometry(leaf, out, rule);
|
||||
follow_piece(leaf, was, at.from, e);
|
||||
Some(made)
|
||||
}
|
||||
|
||||
/// Are `a` and `b` paths or compound paths that differ only in their fills and strokes?
|
||||
fn same_path(a: &Node, b: &Node) -> bool {
|
||||
let leaf = |n: &Node| matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. });
|
||||
if !leaf(a) || !leaf(b) {
|
||||
return false;
|
||||
}
|
||||
// Every field but the fills and strokes, compared in place; the geometry last.
|
||||
let Node { id, name, visible, locked, opacity, blend, isolate, knockout, knockout_shape, appearance, kind, bbox_angle, extras } = a;
|
||||
let Appearance { items: _, effects, contents_index } = &**appearance;
|
||||
*id == b.id
|
||||
&& *name == b.name
|
||||
&& *visible == b.visible
|
||||
&& *locked == b.locked
|
||||
&& *opacity == b.opacity
|
||||
&& *blend == b.blend
|
||||
&& *isolate == b.isolate
|
||||
&& *knockout == b.knockout
|
||||
&& *knockout_shape == b.knockout_shape
|
||||
&& *bbox_angle == b.bbox_angle
|
||||
&& *extras == b.extras
|
||||
&& *effects == b.appearance.effects
|
||||
&& *contents_index == b.appearance.contents_index
|
||||
&& *kind == b.kind
|
||||
}
|
||||
|
||||
/// The effects a Transform effect in a fill's or stroke's own list leaves as they were
|
||||
/// ([`keep_listed`]): the list as it was before the Transform effect was applied, and which of its
|
||||
/// indices keep their values. `None` for an object's own Transform effect.
|
||||
|
||||
+160
-30
@@ -27,7 +27,16 @@ pub fn is_revolve(id: &str) -> bool {
|
||||
/// Most bytes the copies of the object's paint in the faces may take together. Each face and the
|
||||
/// seam stroke around it gets a copy of the paint, so a gradient of many stops times tens of
|
||||
/// thousands of faces took gigabytes; past this the source path is drawn.
|
||||
const MAX_PAINT_COPIES: usize = 256 << 20;
|
||||
pub(crate) const MAX_PAINT_COPIES: usize = 256 << 20;
|
||||
|
||||
/// The bytes of an object's paint copies so far: those of its surfaces' faces, and those of the parts
|
||||
/// of its graphics, each within [`MAX_PAINT_COPIES`] of its own. Graphics past their budget are left
|
||||
/// out without taking room the surfaces need.
|
||||
#[derive(Default)]
|
||||
struct Copies {
|
||||
surfaces: usize,
|
||||
graphics: usize,
|
||||
}
|
||||
|
||||
/// The most face and box tests a group's transparent members' faces take together to rejoin their
|
||||
/// members' last runs; past them each starts a run of its own.
|
||||
@@ -96,13 +105,18 @@ pub fn revolve_options(p: &Value) -> Revolve {
|
||||
smooth_shading: true,
|
||||
cap_ends: flag(p, "cap", true),
|
||||
curve_samples: None,
|
||||
map_surface: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The options Revolve (`id` [`REVOLVE`]) or Revolve (Classic) ([`CLASSIC_REVOLVE`]) with
|
||||
/// parameters `p` sweeps its surface with.
|
||||
/// parameters `p` sweeps its surface with. A Revolve with graphics lays out its side for them.
|
||||
fn options_of(id: &str, p: &Value) -> Revolve {
|
||||
if id == CLASSIC_REVOLVE { classic::options(p) } else { revolve_options(p) }
|
||||
if id == CLASSIC_REVOLVE {
|
||||
classic::options(p)
|
||||
} else {
|
||||
Revolve { map_surface: id == REVOLVE && !crate::solids::mapped_graphics(p).is_empty(), ..revolve_options(p) }
|
||||
}
|
||||
}
|
||||
|
||||
/// The options effect `fx`, a Revolve or a Revolve (Classic), sweeps its surface with.
|
||||
@@ -140,6 +154,17 @@ pub(crate) fn validate_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value)
|
||||
let options = shared_options(&shapes, options_of(id, p))?;
|
||||
let mut copies = 0;
|
||||
shapes.iter().try_for_each(|s| check_surface(&s.path, b, options, surface_item(&s.items), &mut copies))?;
|
||||
// Without graphics, or without the document they draw from, no member is measured for them.
|
||||
if let Some(doc) = doc.filter(|_| id == REVOLVE && !crate::solids::mapped_graphics(p).is_empty()) {
|
||||
match graphics_member(&shapes, b, options).and_then(|k| shapes.get(k)) {
|
||||
Some(s) => check_graphics(Some(doc), id, &s.path, b, options, p, &mut 0)?,
|
||||
// With no member to carry them, the graphics' art must still fit its limits.
|
||||
None => {
|
||||
crate::solids::graphics::validate_symbols(doc, p)?;
|
||||
crate::solids::graphics::validate_surface_symbols(doc, p)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
let casting = shapes.iter().filter(|s| surface_item(&s.items).is_some_and(|i| paint_of(i).1 * s.opacity > 0.0));
|
||||
return check_shadow(p, casting.map(|s| &s.path), b, options);
|
||||
}
|
||||
@@ -151,9 +176,44 @@ pub(crate) fn validate_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value)
|
||||
let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?;
|
||||
let paints = solid_paints(n);
|
||||
check_surface(&path, b, options_of(id, p), surface_item(&paints), &mut 0)?;
|
||||
check_graphics(doc, id, &path, b, options_of(id, p), p, &mut 0)?;
|
||||
check_shadow(p, [&path], b, options_of(id, p))
|
||||
}
|
||||
|
||||
/// An error when the graphics in Revolve (`id`) parameters `p`, with the symbols of `doc`, are past
|
||||
/// their limits on the surface of `path` about the axis of `b`: their art, or the parts they draw
|
||||
/// on its faces ([`crate::solids::graphics::surface_parts`]), whose paint copies count after
|
||||
/// `copies`, the bytes of the copies of the object's graphics so far ([`Copies`]). The parts'
|
||||
/// copies are added to `copies` when they fit, as drawing adds them. Without `doc` nothing is
|
||||
/// drawn, and nothing is checked.
|
||||
fn check_graphics(doc: Option<&Document>, id: &str, path: &PathData, b: Rect, options: Revolve, p: &Value, copies: &mut usize) -> Result<(), String> {
|
||||
let graphics = crate::solids::mapped_graphics(p);
|
||||
let Some(doc) = doc.filter(|_| id == REVOLVE && !graphics.is_empty()) else { return Ok(()) };
|
||||
crate::solids::graphics::validate_symbols(doc, p)?;
|
||||
crate::solids::graphics::validate_surface_symbols(doc, p)?;
|
||||
let faces = vectorcraft_three_d::revolve(path, b, options)?;
|
||||
let mut used = *copies;
|
||||
match crate::solids::graphics::surface_parts(Some(doc), NodeId(0), &graphics, &faces, &|_, c| Paint::solid(c), &mut used) {
|
||||
Some(_) => {
|
||||
*copies = used;
|
||||
Ok(())
|
||||
}
|
||||
None => Err("The graphics are too complex for this surface: simplify the symbols' art or reduce Segments".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The member of a group whose side takes the group's graphics: the first with the longest
|
||||
/// profile among those with a fill or stroke.
|
||||
fn graphics_member(shapes: &[Profile], b: Rect, options: Revolve) -> Option<usize> {
|
||||
shapes
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, s)| surface_item(&s.items).is_some())
|
||||
.filter_map(|(k, s)| vectorcraft_three_d::revolve_surface_size(&s.path, b, options).map(|(_, h)| (k, h)))
|
||||
.fold(None, |best: Option<(usize, f64)>, (k, h)| if best.is_some_and(|(_, top)| top >= h) { best } else { Some((k, h)) })
|
||||
.map(|(k, _)| k)
|
||||
}
|
||||
|
||||
/// With the shadow of Revolve parameters `p` on, an error when the surfaces of `paths` it is cast
|
||||
/// from, about the axis of `b`, are past the limits together.
|
||||
fn check_shadow<'a>(p: &Value, paths: impl IntoIterator<Item = &'a PathData>, b: Rect, options: Revolve) -> Result<(), String> {
|
||||
@@ -168,16 +228,17 @@ fn check_shadow<'a>(p: &Value, paths: impl IntoIterator<Item = &'a PathData>, b:
|
||||
/// appearance item `target` of `n` ([`validate_item_of`]).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn validate_item_revolve(n: &Node, p: &Value, target: usize, index: usize) -> Result<(), String> {
|
||||
validate_item_of(n, REVOLVE, p, target, index)
|
||||
validate_item_of(None, n, REVOLVE, p, target, index)
|
||||
}
|
||||
|
||||
/// [`validate_revolve`] for a Revolve or Revolve (Classic), `id`, with parameters `p` at index
|
||||
/// `index` of the effects of appearance item `target` of `n`. The surfaces of every fill and stroke
|
||||
/// that carries one, `target`'s included, share one budget of paint copies, as in [`art`]. A visible
|
||||
/// object-level Revolve draws in place of those surfaces.
|
||||
pub(crate) fn validate_item_of(n: &Node, id: &str, p: &Value, target: usize, index: usize) -> Result<(), String> {
|
||||
/// object-level Revolve draws in place of those surfaces. With `doc`, `target`'s graphics must fit
|
||||
/// its surface ([`check_graphics`]).
|
||||
pub(crate) fn validate_item_of(doc: Option<&Document>, n: &Node, id: &str, p: &Value, target: usize, index: usize) -> Result<(), String> {
|
||||
if is_container(n) || visible(&n.appearance.effects) || target >= n.appearance.items.len() {
|
||||
return validate_in(None, n, id, p);
|
||||
return validate_in(doc, n, id, p);
|
||||
}
|
||||
validate_params_of(id, p)?;
|
||||
const EMPTY: &str = "Revolve requires a shape with at least two anchors";
|
||||
@@ -187,7 +248,7 @@ pub(crate) fn validate_item_of(n: &Node, id: &str, p: &Value, target: usize, ind
|
||||
}
|
||||
let ctx = GeomContext::of(n);
|
||||
let path = geometry(&path, &n.appearance.effects, &ctx);
|
||||
let mut copies = 0;
|
||||
let (mut copies, mut graphic_copies) = (0, 0);
|
||||
for (i, item) in n.appearance.items.iter().enumerate() {
|
||||
let effects = item.effects();
|
||||
let at = if i == target { Some(index) } else { effects.iter().position(|e| e.visible && is_revolve(&e.id)) };
|
||||
@@ -200,6 +261,12 @@ pub(crate) fn validate_item_of(n: &Node, id: &str, p: &Value, target: usize, ind
|
||||
let path = geometry(&path, at.and_then(|at| effects.get(..at)).unwrap_or(effects), &ctx.item(item));
|
||||
let b = path.bounds().ok_or(EMPTY)?;
|
||||
check_surface(&path, b, options, crate::paints(item).then_some(item), &mut copies)?;
|
||||
// The graphics of every item add their paints' copies to the graphics' budget, as they
|
||||
// are drawn; only the edited item's graphics are refused here.
|
||||
let graphics = check_graphics(doc, kind, &path, b, options, ¶ms, &mut graphic_copies);
|
||||
if i == target {
|
||||
graphics?;
|
||||
}
|
||||
check_shadow(¶ms, [&path], b, options)?;
|
||||
}
|
||||
Ok(())
|
||||
@@ -234,7 +301,7 @@ fn shared_options(shapes: &[Profile], options: Revolve) -> Result<Revolve, Strin
|
||||
}
|
||||
|
||||
/// The item whose paint an object's surface takes: its top fill, else its top stroke.
|
||||
fn surface_item(items: &[AppearanceItem]) -> Option<&AppearanceItem> {
|
||||
pub(crate) fn surface_item(items: &[AppearanceItem]) -> Option<&AppearanceItem> {
|
||||
items.iter().rev().find(|i| matches!(i, AppearanceItem::Fill(_))).or_else(|| items.last())
|
||||
}
|
||||
|
||||
@@ -255,6 +322,7 @@ pub(crate) fn validate_revolve_params(p: &Value) -> Result<(), String> {
|
||||
/// only its own parameters, each in its range.
|
||||
pub(crate) fn validate_params_of(id: &str, p: &Value) -> Result<(), String> {
|
||||
validate_revolve_params(p)?;
|
||||
crate::solids::graphics::validate(id, p)?;
|
||||
if id == CLASSIC_REVOLVE {
|
||||
classic::validate(p)?;
|
||||
}
|
||||
@@ -303,10 +371,13 @@ fn group_shadow(id: NodeId, fx: &Effect, shapes: &[Profile], b: Rect, options: R
|
||||
}
|
||||
|
||||
/// One object's surface of revolution about the axis of `b`, and each face's depth. `copies` counts
|
||||
/// the bytes of the paint copies of every surface of the object. Revolve (Classic) draws every face
|
||||
/// with its classic surface, as Extrude & Bevel (Classic) does.
|
||||
/// the bytes of the paint copies of every surface and graphic of the object. Revolve (Classic) draws every face
|
||||
/// with its classic surface, as Extrude & Bevel (Classic) does. Revolve's graphics, with the
|
||||
/// symbols of `doc`, are drawn on the faces of the side ([`crate::solids::graphics::surface_parts`]):
|
||||
/// a face with a part of a graphic is a group of the face and that part.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn surface(
|
||||
doc: Option<&Document>,
|
||||
n: &Node,
|
||||
path: &PathData,
|
||||
b: Rect,
|
||||
@@ -316,14 +387,14 @@ fn surface(
|
||||
opacity: f32,
|
||||
blend: vectorcraft_doc::color::BlendMode,
|
||||
expand: bool,
|
||||
copies: &mut usize,
|
||||
copies: &mut Copies,
|
||||
) -> Option<(Vec<f64>, Node)> {
|
||||
// A loaded file or a profile edited past the limits keeps drawing its source path instead
|
||||
// of crashing the frame. Commands validate the same evaluator and report its errors.
|
||||
if fx.id == CLASSIC_REVOLVE {
|
||||
let facets = vectorcraft_three_d::revolve_facets(path, b, options).ok()?;
|
||||
*copies = copies.saturating_add(paint_copies(facets.len(), &paint));
|
||||
if *copies > MAX_PAINT_COPIES {
|
||||
copies.surfaces = copies.surfaces.saturating_add(paint_copies(facets.len(), &paint));
|
||||
if copies.surfaces > MAX_PAINT_COPIES {
|
||||
return None;
|
||||
}
|
||||
let depths = facets.iter().map(|f| f.depth).collect();
|
||||
@@ -332,14 +403,33 @@ fn surface(
|
||||
}
|
||||
let colored = options.light_color != [1.0; 3] || options.lights.is_some();
|
||||
let faces = vectorcraft_three_d::revolve(path, b, options).ok()?;
|
||||
*copies = copies.saturating_add(paint_copies(faces.len(), &paint));
|
||||
if *copies > MAX_PAINT_COPIES {
|
||||
copies.surfaces = copies.surfaces.saturating_add(paint_copies(faces.len(), &paint));
|
||||
if copies.surfaces > MAX_PAINT_COPIES {
|
||||
return None;
|
||||
}
|
||||
let graphics = crate::solids::mapped_graphics(&merged_params(&fx.id, &fx.params));
|
||||
let shade = |face: &vectorcraft_three_d::Face, c: Color| graphic_paint(face, c, colored);
|
||||
// Graphics past the limits are left out, and the surface draws without them and their paints'
|
||||
// copies.
|
||||
let mut used = copies.graphics;
|
||||
let mut parts = if graphics.is_empty() {
|
||||
vec![]
|
||||
} else {
|
||||
match crate::solids::graphics::surface_parts(doc, n.id, &graphics, &faces, &shade, &mut used) {
|
||||
Some(parts) => {
|
||||
copies.graphics = used;
|
||||
parts
|
||||
}
|
||||
None => vec![],
|
||||
}
|
||||
};
|
||||
let drawn = parts.iter().any(|p| !p.is_empty());
|
||||
// Visibility is an expansion option, never a change to live geometry or export baking.
|
||||
// Keep all faces for paints whose coverage we cannot prove opaque. A bounded visibility
|
||||
// failure also retains the complete surface rather than losing any of the user's art.
|
||||
// failure also retains the complete surface rather than losing any of the user's art. With
|
||||
// graphics drawn, every face stays, each with its part of the graphics.
|
||||
let visible = (expand
|
||||
&& !drawn
|
||||
&& flag(&fx.params, "expandVisibleOnly", true)
|
||||
&& paint.color().is_some()
|
||||
&& opacity == 1.0
|
||||
@@ -414,7 +504,16 @@ fn surface(
|
||||
.collect();
|
||||
Arc::new(Node::path(n.id, face.path, Appearance { items, ..Default::default() }))
|
||||
})
|
||||
.collect();
|
||||
.collect::<Vec<_>>();
|
||||
let children = if drawn {
|
||||
children
|
||||
.into_iter()
|
||||
.zip(parts.iter_mut().map(std::mem::take).chain(std::iter::repeat_with(Vec::new)))
|
||||
.map(|(face, part)| if part.is_empty() { face } else { Arc::new(Node::group(n.id, std::iter::once(face).chain(part).collect())) })
|
||||
.collect()
|
||||
} else {
|
||||
children
|
||||
};
|
||||
let mut group = Node::group(n.id, children);
|
||||
group.opacity = opacity;
|
||||
group.blend = blend;
|
||||
@@ -422,11 +521,33 @@ fn surface(
|
||||
}
|
||||
|
||||
/// A surface of one object about the bounds of `path`, built with options derived from `fx`.
|
||||
/// `copies` is the count [`surface`] adds to.
|
||||
fn object_surface(n: &Node, path: &PathData, fx: &Effect, item: &AppearanceItem, expand: bool, copies: &mut usize) -> Option<Node> {
|
||||
/// `copies` is the count [`surface`] adds to; its graphics take the symbols of `doc`.
|
||||
fn object_surface(
|
||||
doc: Option<&Document>,
|
||||
n: &Node,
|
||||
path: &PathData,
|
||||
fx: &Effect,
|
||||
item: &AppearanceItem,
|
||||
expand: bool,
|
||||
copies: &mut Copies,
|
||||
) -> Option<Node> {
|
||||
let b = path.bounds()?;
|
||||
let (paint, opacity, blend) = paint_of(item);
|
||||
surface(n, path, b, fx_options(fx), fx, paint, opacity, blend, expand, copies).map(|(_, art)| art)
|
||||
surface(doc, n, path, b, fx_options(fx), fx, paint, opacity, blend, expand, copies).map(|(_, art)| art)
|
||||
}
|
||||
|
||||
/// The paint of a graphic's solid color `c` on `face`, shaded as the face shades a solid fill of
|
||||
/// that color: across the face with its smooth shading, under colored lights (`colored`) with
|
||||
/// their color.
|
||||
fn graphic_paint(face: &vectorcraft_three_d::Face, c: Color, colored: bool) -> Paint {
|
||||
if colored {
|
||||
return face
|
||||
.light_gradient
|
||||
.map_or_else(|| Paint::solid(crate::lighting::shade(c, face.illumination)), |g| crate::lighting::smooth_paint(g, c));
|
||||
}
|
||||
let [r, g, b] = c.to_rgb();
|
||||
let color = |s: f64| Color::rgb(r * s as f32, g * s as f32, b * s as f32);
|
||||
face.gradient.map_or_else(|| Paint::solid(color(face.brightness)), |g| shading_paint(g, color, |_| 1.0))
|
||||
}
|
||||
|
||||
fn shading_paint(g: vectorcraft_three_d::ShadeGradient, color: impl Fn(f64) -> Color, opacity: impl Fn(f64) -> f32) -> Paint {
|
||||
@@ -592,12 +713,12 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
}
|
||||
let n = &*resolve_for(doc, n, "Revolve", false).ok()?;
|
||||
if is_container(n) {
|
||||
return group_art(n, expand);
|
||||
return group_art(doc, n, expand);
|
||||
}
|
||||
let (path, rule) = profile(n)?;
|
||||
let ctx = GeomContext::of(n);
|
||||
let mut children = vec![];
|
||||
let mut copies = 0;
|
||||
let mut copies = Copies::default();
|
||||
let mut remaining = n.appearance.effects.clone();
|
||||
if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id)) {
|
||||
let fx = n.appearance.effects.get(index)?;
|
||||
@@ -606,7 +727,7 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
let paints = solid_paints(n);
|
||||
let item = surface_item(&paints)?;
|
||||
let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
|
||||
let surface = object_surface(n, &path, fx, item, expand, &mut copies)?;
|
||||
let surface = object_surface(doc, n, &path, fx, item, expand, &mut copies)?;
|
||||
if let Some(b) = path.bounds()
|
||||
&& let Some(shadow) = shadow_of(n.id, fx, &path, item, b, fx_options(fx)).ok()?
|
||||
{
|
||||
@@ -632,7 +753,7 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
let fx = item.effects().get(index)?;
|
||||
let p = geometry(&path, item.effects().get(..index)?, &ctx.item(original));
|
||||
let expand = expand && !item.effects().iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
|
||||
let mut art = object_surface(n, &p, fx, item, expand, &mut copies)?;
|
||||
let mut art = object_surface(doc, n, &p, fx, item, expand, &mut copies)?;
|
||||
art.appearance.effects = item.effects().iter().skip(index + 1).filter(|e| !is_revolve(&e.id)).cloned().collect();
|
||||
if let Some(b) = p.bounds()
|
||||
&& let Some(mut shadow) = shadow_of(n.id, fx, &p, item, b, fx_options(fx)).ok()?
|
||||
@@ -774,7 +895,7 @@ pub(crate) fn overlaps(a: Rect, b: Rect) -> bool {
|
||||
/// [`art`] of group or layer `n`: every member swept about one axis on the bounds of all of them,
|
||||
/// each in its own paint. Every member's faces are drawn in one back-to-front order. `None` when
|
||||
/// the effect is only on the group's own fills or strokes or when its members can't be revolved.
|
||||
fn group_art(n: &Node, expand: bool) -> Option<Node> {
|
||||
fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
let index = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id))?;
|
||||
let fx = n.appearance.effects.get(index)?;
|
||||
let mut shapes = members(n, "").ok()?;
|
||||
@@ -782,17 +903,22 @@ fn group_art(n: &Node, expand: bool) -> Option<Node> {
|
||||
let b = union_bounds(&shapes)?;
|
||||
let options = shared_options(&shapes, fx_options(fx)).ok()?;
|
||||
let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
|
||||
let mut copies = 0;
|
||||
let mut copies = Copies::default();
|
||||
let mut surfaces = vec![];
|
||||
let mut opaque = true;
|
||||
for s in &shapes {
|
||||
// The graphics go once, on the side of the member with the longest profile. Without graphics
|
||||
// no member is measured for them.
|
||||
let mapped = fx.id == REVOLVE && !crate::solids::mapped_graphics(&merged_params(&fx.id, &fx.params)).is_empty();
|
||||
let longest = if mapped { graphics_member(&shapes, b, options) } else { None };
|
||||
for (k, s) in shapes.iter().enumerate() {
|
||||
let Some(item) = surface_item(&s.items) else { continue };
|
||||
// The opacity and blending of the member and the groups it is in apply through its scopes.
|
||||
let (paint, opacity, blend) = paint_of(item);
|
||||
opaque &= opacity >= 1.0 && blend == Default::default() && s.scopes.is_empty();
|
||||
// A member with transparency of its own keeps every face, as a transparent object does.
|
||||
let expand = expand && s.scopes.is_empty();
|
||||
let (depths, art) = surface(n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies)?;
|
||||
let doc = doc.filter(|_| longest == Some(k));
|
||||
let (depths, art) = surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies)?;
|
||||
surfaces.push((depths, art, s.scopes.as_slice()));
|
||||
}
|
||||
if surfaces.is_empty() {
|
||||
@@ -1351,7 +1477,7 @@ mod tests {
|
||||
group.appearance = Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0).into();
|
||||
for id in [REVOLVE, crate::EXTRUDE] {
|
||||
assert!(crate::validate_three_d(&group, id, &json!({})).is_ok(), "{id} on the group itself");
|
||||
let refused = crate::validate_three_d_at(&group, id, &json!({}), Some((0, 0))).unwrap_err();
|
||||
let refused = crate::validate_three_d_at(&group, id, &json!({}), (Some(0), 0)).unwrap_err();
|
||||
assert!(refused.contains("on the group itself"), "{id}: {refused}");
|
||||
}
|
||||
}
|
||||
@@ -1517,3 +1643,7 @@ mod tests {
|
||||
assert_eq!(expand_revolve_art(&sample), revolve_art(&sample));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "revolve/tests_graphics.rs"]
|
||||
mod tests_graphics;
|
||||
@@ -0,0 +1,576 @@
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::Symbol;
|
||||
use vectorcraft_doc::color::Color;
|
||||
use vectorcraft_geom::{BezPath, shapes};
|
||||
|
||||
use super::*;
|
||||
use crate::solids::three_d_params_as;
|
||||
|
||||
fn bar(r: Rect, color: Color) -> Node {
|
||||
Node::path(NodeId(0), shapes::rectangle(r), Appearance::basic(Paint::solid(color), Paint::None, 0.0))
|
||||
}
|
||||
|
||||
/// A document with symbols "Red" and "Blue" (10 × 20 bars) and "Wide" (a red 300 × 10 bar).
|
||||
fn document() -> Document {
|
||||
let mut d = Document::new(1000.0, 1000.0);
|
||||
for (name, r, color) in [
|
||||
("Red", Rect::new(0.0, 0.0, 10.0, 20.0), Color::rgb(1.0, 0.0, 0.0)),
|
||||
("Blue", Rect::new(0.0, 0.0, 10.0, 20.0), Color::rgb(0.0, 0.0, 1.0)),
|
||||
("Wide", Rect::new(0.0, 0.0, 300.0, 10.0), Color::rgb(1.0, 0.0, 0.0)),
|
||||
("Flat", Rect::new(0.0, 0.0, 10.0, 2.0), Color::rgb(1.0, 0.0, 0.0)),
|
||||
] {
|
||||
d.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(bar(r, color)) });
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
/// A gray open profile through `points` (its first and last on the axis at x 0), revolved with
|
||||
/// `params` over a view straight on without shading.
|
||||
fn revolved(points: &[(f64, f64)], params: Value) -> Node {
|
||||
let mut b = BezPath::new();
|
||||
b.move_to(points[0]);
|
||||
points[1..].iter().for_each(|p| b.line_to(*p));
|
||||
let mut p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": false});
|
||||
p.as_object_mut().unwrap().extend(params.as_object().unwrap().clone());
|
||||
let mut n = Node::path(NodeId(7), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(Color::rgb(0.5, 0.5, 0.5)), Paint::None, 0.0));
|
||||
n.appearance.effects.push(crate::new_effect(REVOLVE, &p).unwrap());
|
||||
n
|
||||
}
|
||||
|
||||
/// A cylinder of radius 50 about x 0, from y 0 to 200.
|
||||
const CYLINDER: [(f64, f64); 4] = [(0.0, 0.0), (50.0, 0.0), (50.0, 200.0), (0.0, 200.0)];
|
||||
|
||||
/// A profile that narrows from 50 to 20 from the axis at y 100 and widens again.
|
||||
const NECK: [(f64, f64); 5] = [(0.0, 0.0), (50.0, 0.0), (20.0, 100.0), (50.0, 200.0), (0.0, 200.0)];
|
||||
|
||||
/// The red channel of each color `paint` draws when it is a shade of pure red or pure blue (`blue`):
|
||||
/// a solid color or the stops of a gradient. `None` for any other paint.
|
||||
fn shade_of(paint: &Paint, blue: bool) -> Option<Vec<f32>> {
|
||||
let hue = |c: &Color| {
|
||||
let [r, g, b] = c.to_rgb();
|
||||
let (on, off) = if blue { (b, r) } else { (r, b) };
|
||||
(on > 0.02 && off < 0.01 && g < 0.01).then_some(on)
|
||||
};
|
||||
match paint {
|
||||
Paint::Solid { .. } => Some(vec![hue(&paint.color()?)?]),
|
||||
Paint::Gradient(g) => g.gradient.stops.iter().map(|s| hue(&s.color)).collect(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The paths in `art` filled in a shade of red (or blue), with their shades.
|
||||
fn parts(art: &Node, blue: bool) -> Vec<(PathData, Vec<f32>)> {
|
||||
let mut out = vec![];
|
||||
art.walk(&mut |n| {
|
||||
let Some(path) = n.path_data() else { return };
|
||||
let fill = n.appearance.items.iter().find_map(|i| match i {
|
||||
AppearanceItem::Fill(f) => shade_of(&f.paint, blue),
|
||||
AppearanceItem::Stroke(_) => None,
|
||||
});
|
||||
if let Some(shades) = fill {
|
||||
out.push((path.clone(), shades));
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
fn reach(parts: &[(PathData, Vec<f32>)]) -> Rect {
|
||||
parts.iter().filter_map(|(p, _)| p.bounds()).reduce(|a, b| a.union(b)).unwrap()
|
||||
}
|
||||
|
||||
fn near(a: f64, b: f64, tolerance: f64) -> bool {
|
||||
(a - b).abs() <= tolerance
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_graphic_wraps_around_the_side_and_narrows_toward_the_silhouette() {
|
||||
let d = document();
|
||||
let n = revolved(&CYLINDER, json!({"graphics": [{"symbol": "Red"}, {"symbol": "Blue", "x": 60.0}]}));
|
||||
let art = revolve_art_in(Some(&d), &n).unwrap();
|
||||
// At the middle of the side, facing the viewer, the bar keeps its size: 10 wide at the axis's
|
||||
// line, from 10 above the middle of the profile to 10 below.
|
||||
let front = reach(&parts(&art, false));
|
||||
let half = 50.0 * (5.0f64 / 50.0).sin();
|
||||
assert!(near(front.x0, -half, 0.05) && near(front.x1, half, 0.05), "{front:?}");
|
||||
assert!(near(front.y0, 90.0, 1e-6) && near(front.y1, 110.0, 1e-6), "{front:?}");
|
||||
// 60 to its right the side has turned 1.1 to 1.3 radians away: the same bar draws less than
|
||||
// half as wide, at the sine of those angles.
|
||||
let turned = reach(&parts(&art, true));
|
||||
assert!(near(turned.x0, 50.0 * 1.1f64.sin(), 0.15) && near(turned.x1, 50.0 * 1.3f64.sin(), 0.15), "{turned:?}");
|
||||
assert!(turned.width() < front.width() / 2.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_part_past_the_silhouette_and_on_the_back_is_not_drawn() {
|
||||
let d = document();
|
||||
// A bar wider than the half of the side seen from the front reaches the silhouette and no
|
||||
// further.
|
||||
let n = revolved(&CYLINDER, json!({"graphics": [{"symbol": "Wide"}]}));
|
||||
let wide = reach(&parts(&revolve_art_in(Some(&d), &n).unwrap(), false));
|
||||
assert!(wide.x0 > -50.0 - 1e-6 && wide.x1 < 50.0 + 1e-6, "{wide:?}");
|
||||
assert!(wide.x0 < -49.5 && wide.x1 > 49.5, "{wide:?}");
|
||||
// On the back, half a turn around the axis, nothing is drawn.
|
||||
let n = revolved(&CYLINDER, json!({"graphics": [{"symbol": "Red", "x": 150.0}]}));
|
||||
assert!(parts(&revolve_art_in(Some(&d), &n).unwrap(), false).is_empty());
|
||||
// Turned half a turn, the back faces the viewer.
|
||||
let n = revolved(&CYLINDER, json!({"rotationY": 180.0, "graphics": [{"symbol": "Red", "x": 150.0}]}));
|
||||
assert!(!parts(&revolve_art_in(Some(&d), &n).unwrap(), false).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_graphic_follows_the_profile_and_keeps_its_size_where_it_comes_nearer_the_axis() {
|
||||
let d = document();
|
||||
// A 10 wide bar keeps its length around the axis at every distance from it: at the neck, 20
|
||||
// from the axis, it spans 0.5 radians; half way up the slanted side (52.2 along it, 35 from
|
||||
// the axis, at y 50), 2/7 of a radian. Straight on, both draw nearly 10 wide.
|
||||
let slant = (30.0f64 * 30.0 + 100.0 * 100.0).sqrt();
|
||||
let n = revolved(&NECK, json!({"graphics": [{"symbol": "Flat"}, {"symbol": "Flat", "y": -slant / 2.0}]}));
|
||||
let art = revolve_art_in(Some(&d), &n).unwrap();
|
||||
let all = parts(&art, false);
|
||||
let neck: Vec<_> = all.iter().filter(|(p, _)| p.bounds().unwrap().center().y > 75.0).cloned().collect();
|
||||
let up: Vec<_> = all.iter().filter(|(p, _)| p.bounds().unwrap().center().y <= 75.0).cloned().collect();
|
||||
let (neck, up) = (reach(&neck), reach(&up));
|
||||
// Each bar is 2 tall, so its ends are up to 0.3 farther from the axis than its middle.
|
||||
assert!(near(neck.width(), 2.0 * 20.0 * 0.25f64.sin(), 0.15), "{neck:?}");
|
||||
assert!(near(neck.center().y, 100.0, 0.05), "{neck:?}");
|
||||
assert!(near(up.width(), 2.0 * 35.0 * (5.0f64 / 35.0).sin(), 0.15), "{up:?}");
|
||||
assert!(near(up.center().y, 50.0, 0.05), "{up:?}");
|
||||
// At the neck a bar 25 to the right lies 1 to 1.5 radians around, near the silhouette; one 40
|
||||
// to the right lies 1.75 to 2.25 radians around, past the silhouette, and is not drawn.
|
||||
let n = revolved(&NECK, json!({"graphics": [{"symbol": "Flat", "x": 25.0}]}));
|
||||
let side = reach(&parts(&revolve_art_in(Some(&d), &n).unwrap(), false));
|
||||
assert!(near(side.x0, 20.0 * 1.0f64.sin(), 0.3) && near(side.x1, 20.0 * 1.5f64.sin(), 0.3), "{side:?}");
|
||||
let n = revolved(&NECK, json!({"graphics": [{"symbol": "Flat", "x": 40.0}]}));
|
||||
assert!(parts(&revolve_art_in(Some(&d), &n).unwrap(), false).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_the_axis_on_the_right_a_graphic_starts_on_the_front() {
|
||||
let d = document();
|
||||
// The cylinder of radius 50 about x 0, swept from its right edge.
|
||||
let profile = [(0.0, 0.0), (-50.0, 0.0), (-50.0, 200.0), (0.0, 200.0)];
|
||||
let n = revolved(&profile, json!({"edge": "right", "graphics": [{"symbol": "Red"}]}));
|
||||
let front = reach(&parts(&revolve_art_in(Some(&d), &n).unwrap(), false));
|
||||
let half = 50.0 * (5.0f64 / 50.0).sin();
|
||||
assert!(near(front.x0, -half, 0.05) && near(front.x1, half, 0.05), "{front:?}");
|
||||
assert!(near(front.y0, 90.0, 1e-6) && near(front.y1, 110.0, 1e-6), "{front:?}");
|
||||
// x increases to the viewer's right here too.
|
||||
let n = revolved(&profile, json!({"edge": "right", "graphics": [{"symbol": "Red", "x": 25.0}]}));
|
||||
let right = reach(&parts(&revolve_art_in(Some(&d), &n).unwrap(), false));
|
||||
assert!(near(right.center().x, 50.0 * 0.5f64.sin(), 0.3), "{right:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_graphic_is_shaded_with_the_surface() {
|
||||
let d = document();
|
||||
// The light is on the left: the bar left of the middle is lighter than the one on its right,
|
||||
// and neither keeps its unlit red.
|
||||
let n = revolved(&CYLINDER, json!({"shade": true, "graphics": [{"symbol": "Red", "x": -30.0}, {"symbol": "Red", "x": 30.0}]}));
|
||||
let all = parts(&revolve_art_in(Some(&d), &n).unwrap(), false);
|
||||
let mean = |left: bool| {
|
||||
let shades: Vec<f32> =
|
||||
all.iter().filter(|(p, _)| (p.bounds().unwrap().center().x < 0.0) == left).flat_map(|(_, s)| s.iter().copied()).collect();
|
||||
shades.iter().sum::<f32>() / shades.len() as f32
|
||||
};
|
||||
assert!(mean(true) > mean(false) + 0.05, "{} {}", mean(true), mean(false));
|
||||
assert!(all.iter().all(|(_, s)| s.iter().all(|r| *r < 0.999)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_graphics_keep_their_order_on_every_face() {
|
||||
let d = document();
|
||||
// The wide red bar, listed second, reaches across the narrow blue one, listed first. Shaded,
|
||||
// each face is one triangle.
|
||||
let n = revolved(&CYLINDER, json!({"shade": true, "graphics": [{"symbol": "Blue", "x": 30.0}, {"symbol": "Wide"}]}));
|
||||
let art = revolve_art_in(Some(&d), &n).unwrap();
|
||||
let mut both = 0;
|
||||
art.walk(&mut |g| {
|
||||
// A face with parts of graphics: the face's path, then the parts' paths.
|
||||
let NodeKind::Group { children, clip: false } = &g.kind else { return };
|
||||
if !children.iter().all(|c| matches!(c.kind, NodeKind::Path { .. })) {
|
||||
return;
|
||||
}
|
||||
let colors: Vec<bool> = children
|
||||
.iter()
|
||||
.filter_map(|c| {
|
||||
let blue = !parts(c, true).is_empty();
|
||||
(blue || !parts(c, false).is_empty()).then_some(blue)
|
||||
})
|
||||
.collect();
|
||||
if colors.contains(&true) && colors.contains(&false) {
|
||||
both += 1;
|
||||
assert!(colors.iter().position(|b| !b) > colors.iter().position(|b| *b), "{colors:?}");
|
||||
}
|
||||
});
|
||||
assert!(both > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_graphic_past_the_end_reaches_the_curved_rim_and_no_further() {
|
||||
let d = document();
|
||||
// A tube 50 from the axis with a cap at each end, in 10 segments, tilted to show its top: the
|
||||
// bottom rim is an arc on the page whose lowest point, in front, lies between two corners of
|
||||
// the faces. The wide bar runs 5 past the bottom of the profile.
|
||||
for shade in [true, false] {
|
||||
let mut b = BezPath::new();
|
||||
b.move_to((0.0, 0.0));
|
||||
b.line_to((0.0, 200.0));
|
||||
let p = json!({"offset": 50.0, "segments": 10, "rotationX": -30.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": shade, "graphics": [{"symbol": "Wide", "y": 100.0}]});
|
||||
let mut n = Node::path(NodeId(7), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(Color::rgb(0.5, 0.5, 0.5)), Paint::None, 0.0));
|
||||
n.appearance.effects.push(crate::new_effect(REVOLVE, &p).unwrap());
|
||||
let art = revolve_art_in(Some(&d), &n).unwrap();
|
||||
let mut lowest = f64::NEG_INFINITY;
|
||||
art.walk(&mut |c| {
|
||||
if let Some(b) = c.path_data().and_then(PathData::bounds) {
|
||||
lowest = lowest.max(b.y1);
|
||||
}
|
||||
});
|
||||
let bar = reach(&parts(&art, false));
|
||||
assert!(near(bar.y1, lowest, 0.05), "shade {shade}: {bar:?} {lowest}");
|
||||
// A thin bar wholly past the end, 0.35 to 0.85 below it in front, lies between the faces'
|
||||
// straight lower edge and the rim's arc there: it is drawn, inside the rim.
|
||||
let mut thin = n.clone();
|
||||
let p = json!({"offset": 50.0, "segments": 10, "rotationX": -30.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": shade, "graphics": [{"symbol": "Flat", "y": 100.6, "scale": 25.0}]});
|
||||
thin.appearance.effects = vec![crate::new_effect(REVOLVE, &p).unwrap()];
|
||||
let past = parts(&revolve_art_in(Some(&d), &thin).unwrap(), false);
|
||||
assert!(!past.is_empty(), "shade {shade}");
|
||||
assert!(reach(&past).y1 <= lowest + 1e-6, "shade {shade}: {:?} {lowest}", reach(&past));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn under_several_lights_a_graphic_takes_each_faces_own_lit_art() {
|
||||
let d = document();
|
||||
let lights = json!([{"color": "#ff8080", "rotation": 120.0}, {"color": "#8080ff", "rotation": -30.0}]);
|
||||
let clips = |n: &Node| {
|
||||
let mut count = 0;
|
||||
revolve_art_in(Some(&d), n).unwrap().walk(&mut |c| count += usize::from(matches!(c.kind, NodeKind::Group { clip: true, .. })));
|
||||
count
|
||||
};
|
||||
let plain = revolved(&CYLINDER, json!({"shade": true, "lights": lights}));
|
||||
let mapped = revolved(&CYLINDER, json!({"shade": true, "lights": lights, "graphics": [{"symbol": "Red"}]}));
|
||||
// Each part of the bar is the face's lit art clipped to the part: one clip more for the
|
||||
// part, one for the face's own art inside it.
|
||||
assert!(clips(&mapped) > clips(&plain), "{} {}", clips(&mapped), clips(&plain));
|
||||
// A lit face draws its paint under the face's light: a layer of the light's three channels,
|
||||
// multiplied over the paint. Every part of the bar takes such a layer of its own, so the bar
|
||||
// is shaded with each face's colored light; a bar drawn in flat red would add none.
|
||||
let lit = |n: &Node| {
|
||||
let mut count = 0;
|
||||
revolve_art_in(Some(&d), n).unwrap().walk(&mut |c| count += usize::from(c.blend == vectorcraft_doc::color::BlendMode::Multiply));
|
||||
count
|
||||
};
|
||||
assert!(lit(&mapped) > lit(&plain), "{} {}", lit(&mapped), lit(&plain));
|
||||
// An opaque part also draws its lit art clipped to the band of its seam stroke; a translucent
|
||||
// part, whose overlap would show, does not.
|
||||
let mut d = d.clone();
|
||||
let mut clear = bar(Rect::new(0.0, 0.0, 10.0, 20.0), Color::rgb(1.0, 0.0, 0.0));
|
||||
if let Some(AppearanceItem::Fill(f)) = clear.appearance.items.first_mut() {
|
||||
f.opacity = 0.5;
|
||||
}
|
||||
d.symbols.push(Symbol { dynamic: false, name: "Clear".into(), art: Arc::new(clear) });
|
||||
let clips = |n: &Node| {
|
||||
let mut count = 0;
|
||||
revolve_art_in(Some(&d), n).unwrap().walk(&mut |c| count += usize::from(matches!(c.kind, NodeKind::Group { clip: true, .. })));
|
||||
count
|
||||
};
|
||||
let translucent = revolved(&CYLINDER, json!({"shade": true, "lights": lights, "graphics": [{"symbol": "Clear"}]}));
|
||||
let (base, opaque, translucent) = (clips(&plain), clips(&mapped), clips(&translucent));
|
||||
assert!(translucent > base && opaque - base == 2 * (translucent - base), "{base} {opaque} {translucent}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn graphics_past_the_point_limit_are_refused() {
|
||||
let mut d = document();
|
||||
let dots: Vec<Arc<Node>> = (0..2000)
|
||||
.map(|i| {
|
||||
let c = Point::new(f64::from(i % 50) * 12.0, f64::from(i / 50) * 12.0);
|
||||
Arc::new(Node::path(
|
||||
NodeId(0),
|
||||
shapes::ellipse(Rect::new(c.x, c.y, c.x + 10.0, c.y + 10.0)),
|
||||
Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0),
|
||||
))
|
||||
})
|
||||
.collect();
|
||||
d.symbols.push(Symbol { dynamic: false, name: "Dots".into(), art: Arc::new(Node::group(NodeId(0), dots)) });
|
||||
let n = revolved(&CYLINDER, json!({}));
|
||||
let p = |scale: f64| json!({"graphics": [{"symbol": "Dots", "scale": scale}]});
|
||||
assert!(validate_revolve_in(Some(&d), &n, &p(100.0)).is_ok());
|
||||
// At 100 times the size each dot is cut into hundreds of straight pieces.
|
||||
let e = validate_revolve_in(Some(&d), &n, &p(10_000.0)).unwrap_err();
|
||||
assert!(e.contains("too complex"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn graphics_cut_into_too_many_parts_are_refused_on_the_object_and_on_a_fill() {
|
||||
let mut d = document();
|
||||
// 4,000 thin bars across the side: few points each, but each is cut at every face it crosses.
|
||||
let bars: Vec<Arc<Node>> =
|
||||
(0..4000).map(|i| Arc::new(bar(Rect::new(0.0, f64::from(i) * 0.05, 300.0, f64::from(i) * 0.05 + 0.02), Color::BLACK))).collect();
|
||||
d.symbols.push(Symbol { dynamic: false, name: "Bars".into(), art: Arc::new(Node::group(NodeId(0), bars)) });
|
||||
let p = json!({"segments": 128, "graphics": [{"symbol": "Bars"}]});
|
||||
let n = revolved(&CYLINDER, json!({}));
|
||||
let e = validate_revolve_in(Some(&d), &n, &p).unwrap_err();
|
||||
assert!(e.contains("too complex for this surface"), "{e}");
|
||||
assert!(validate_revolve_in(Some(&d), &n, &json!({"graphics": [{"symbol": "Red"}]})).is_ok());
|
||||
// The same on a Revolve on the object's fill.
|
||||
let mut filled = n.clone();
|
||||
let fx = filled.appearance.effects.remove(0);
|
||||
if let Some(AppearanceItem::Fill(f)) = filled.appearance.items.first_mut() {
|
||||
f.effects.push(fx);
|
||||
}
|
||||
let e = crate::solids::validate_three_d_at_in(Some(&d), &filled, REVOLVE, &p, (Some(0), 0)).unwrap_err();
|
||||
assert!(e.contains("too complex for this surface"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_the_document_nothing_is_drawn_and_expand_keeps_the_graphics() {
|
||||
let d = document();
|
||||
let n = revolved(&CYLINDER, json!({"graphics": [{"symbol": "Red"}]}));
|
||||
assert!(parts(&revolve_art(&n).unwrap(), false).is_empty());
|
||||
let shown = parts(&revolve_art_in(Some(&d), &n).unwrap(), false);
|
||||
let expanded = parts(&expand_revolve_art_in(Some(&d), &n).unwrap(), false);
|
||||
assert!(!shown.is_empty());
|
||||
assert_eq!(shown, expanded);
|
||||
// In a group the graphics go once, on the side of the member with the longest profile.
|
||||
let mut member = n.clone();
|
||||
member.appearance.effects.clear();
|
||||
let mut short = member.clone();
|
||||
if let NodeKind::Path { path, .. } = &mut short.kind {
|
||||
*path = PathData::from_bezpath(&{
|
||||
let mut b = BezPath::new();
|
||||
b.move_to((0.0, 80.0));
|
||||
b.line_to((30.0, 80.0));
|
||||
b.line_to((30.0, 120.0));
|
||||
b.line_to((0.0, 120.0));
|
||||
b
|
||||
});
|
||||
}
|
||||
let mut group = Node::group(NodeId(9), vec![Arc::new(short), Arc::new(member)]);
|
||||
group.appearance.effects = n.appearance.effects.clone();
|
||||
assert_eq!(parts(&revolve_art_in(Some(&d), &group).unwrap(), false).len(), shown.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revolve_takes_graphics_on_its_side_only() {
|
||||
let front = json!({"graphics": [{"symbol": "Red"}]});
|
||||
let back = json!({"graphics": [{"symbol": "Red", "face": "back"}]});
|
||||
assert!(crate::solids::graphics::validate(REVOLVE, &front).is_ok());
|
||||
assert!(crate::solids::graphics::validate(REVOLVE, &back).unwrap_err().contains("side"));
|
||||
assert!(crate::solids::graphics::validate(CLASSIC_REVOLVE, &front).is_err());
|
||||
let n = revolved(&CYLINDER, json!({}));
|
||||
assert!(validate_revolve(&n, &back).is_err());
|
||||
// Changing the type keeps the front's graphics on Revolve's side and drops the back's.
|
||||
let both = json!({"graphics": [{"symbol": "Red"}, {"symbol": "Blue", "face": "back"}]});
|
||||
let kept = three_d_params_as(crate::EXTRUDE, &both, REVOLVE);
|
||||
assert_eq!(kept["graphics"].as_array().map(Vec::len), Some(1));
|
||||
assert_eq!(kept["graphics"][0]["symbol"], "Red");
|
||||
assert_eq!(three_d_params_as(REVOLVE, &front, crate::INFLATE).get("graphics"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revolve_classic_draws_no_graphics_its_parameters_carry() {
|
||||
let d = document();
|
||||
let mut n = revolved(&CYLINDER, json!({"graphics": [{"symbol": "Red"}]}));
|
||||
assert!(!parts(&revolve_art_in(Some(&d), &n).unwrap(), false).is_empty());
|
||||
// A file can hold graphics on Revolve (Classic), which commands refuse: Revolve (Classic)
|
||||
// draws its classic surface, without them.
|
||||
if let Some(fx) = n.appearance.effects.first_mut() {
|
||||
fx.id = CLASSIC_REVOLVE.into();
|
||||
}
|
||||
assert!(parts(&revolve_art_in(Some(&d), &n).unwrap(), false).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_with_no_member_to_carry_graphics_still_checks_their_art() {
|
||||
let mut d = document();
|
||||
let dots: Vec<Arc<Node>> = (0..2000)
|
||||
.map(|i| {
|
||||
let c = Point::new(f64::from(i % 50) * 12.0, f64::from(i / 50) * 12.0);
|
||||
Arc::new(Node::path(
|
||||
NodeId(0),
|
||||
shapes::ellipse(Rect::new(c.x, c.y, c.x + 10.0, c.y + 10.0)),
|
||||
Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0),
|
||||
))
|
||||
})
|
||||
.collect();
|
||||
d.symbols.push(Symbol { dynamic: false, name: "Dots".into(), art: Arc::new(Node::group(NodeId(0), dots)) });
|
||||
let n = revolved(&CYLINDER, json!({}));
|
||||
let mut member = n.clone();
|
||||
member.appearance.effects.clear();
|
||||
member.appearance.items.clear();
|
||||
let mut group = Node::group(NodeId(9), vec![Arc::new(member)]);
|
||||
group.appearance.effects = n.appearance.effects.clone();
|
||||
// No member has a fill or stroke, so none carries the graphics, but art past the limits is
|
||||
// refused as it is on a group whose member carries them.
|
||||
let e = validate_in(Some(&d), &group, REVOLVE, &json!({"graphics": [{"symbol": "Dots", "scale": 10_000.0}]})).unwrap_err();
|
||||
assert!(e.contains("too complex"), "{e}");
|
||||
assert!(validate_in(Some(&d), &group, REVOLVE, &json!({"graphics": [{"symbol": "Red"}]})).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_turn_draws_a_graphic_on_either_side_of_the_cut_at_the_back() {
|
||||
let mut d = document();
|
||||
d.symbols.push(Symbol { dynamic: false, name: "Thin".into(), art: Arc::new(bar(Rect::new(0.0, 0.0, 2.0, 20.0), Color::rgb(1.0, 0.0, 0.0))) });
|
||||
// Half a turn around a radius of 50 is about 157 to each side of the middle: turned to face
|
||||
// the viewer, a graphic just inside either end is drawn.
|
||||
for x in [155.0, -155.0] {
|
||||
let n = revolved(&CYLINDER, json!({"rotationY": 180.0, "graphics": [{"symbol": "Thin", "x": x}]}));
|
||||
assert!(!parts(&revolve_art_in(Some(&d), &n).unwrap(), false).is_empty(), "x {x}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A gray cylinder of radius 50 whose side is 200 edges along the profile, from y 0 to 200.
|
||||
fn ribbed() -> Vec<(f64, f64)> {
|
||||
let mut points = vec![(0.0, 0.0)];
|
||||
points.extend((0..=200).map(|k| (50.0, f64::from(k))));
|
||||
points.push((0.0, 200.0));
|
||||
points
|
||||
}
|
||||
|
||||
/// A symbol `name` of one red path whose contours are `contours`, each a polygon through its
|
||||
/// points.
|
||||
fn contours_symbol(name: &str, contours: &[Vec<Point>]) -> Symbol {
|
||||
let mut b = BezPath::new();
|
||||
for contour in contours {
|
||||
b.move_to(contour[0]);
|
||||
contour[1..].iter().for_each(|p| b.line_to(*p));
|
||||
b.close_path();
|
||||
}
|
||||
let art = Node::path(NodeId(0), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0));
|
||||
Symbol { dynamic: false, name: name.into(), art: Arc::new(art) }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contours_away_from_a_face_are_not_cut_at_it() {
|
||||
// 2,000 small squares in two clusters on the back, at opposite corners of the side: the path's
|
||||
// bounds reach across every face, but no square reaches a face that is drawn.
|
||||
let squares: Vec<Vec<Point>> = (0..2000)
|
||||
.map(|i| {
|
||||
let (x, y) = if i < 1000 { (0.0, 0.0) } else { (290.0, 190.0) };
|
||||
let (x, y) = (x + f64::from(i % 10) * 0.1, y + f64::from(i % 1000 / 10) * 0.1);
|
||||
vec![Point::new(x, y), Point::new(x + 0.05, y), Point::new(x + 0.05, y + 0.05), Point::new(x, y + 0.05)]
|
||||
})
|
||||
.collect();
|
||||
let mut d = document();
|
||||
d.symbols.push(contours_symbol("Clusters", &squares));
|
||||
let n = revolved(&ribbed(), json!({}));
|
||||
let p = json!({"graphics": [{"symbol": "Clusters"}]});
|
||||
assert_eq!(validate_revolve_in(Some(&d), &n, &p), Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_contour_that_reaches_every_face_and_draws_on_none_is_refused() {
|
||||
// One contour of 10,000 points: a thin frame around the whole side, past its ends and on the
|
||||
// back, so it is cut at every face and keeps nothing.
|
||||
let edge = |from: Point, to: Point| (0..2500).map(move |k| from.lerp(to, f64::from(k) / 2500.0));
|
||||
let (outer, inner) = ([(0.0, 0.0), (400.0, 0.0), (400.0, 400.0), (0.0, 400.0)], [(1.0, 1.0), (1.0, 399.0), (399.0, 399.0), (399.0, 1.0)]);
|
||||
let ring = |corners: [(f64, f64); 4]| (0..4).flat_map(move |k| edge(corners[k].into(), corners[(k + 1) % 4].into())).collect::<Vec<Point>>();
|
||||
let mut frame = ring(outer);
|
||||
frame.extend(ring(inner));
|
||||
let mut d = document();
|
||||
d.symbols.push(contours_symbol("Frame", &[frame]));
|
||||
let n = revolved(&ribbed(), json!({}));
|
||||
let e = validate_revolve_in(Some(&d), &n, &json!({"graphics": [{"symbol": "Frame"}]})).unwrap_err();
|
||||
assert!(e.contains("too complex for this surface"), "{e}");
|
||||
assert!(parts(&revolve_art_in(Some(&d), &n).unwrap(), false).is_empty());
|
||||
}
|
||||
|
||||
/// A red linear gradient of `stops` stops, each with `opacity`.
|
||||
fn ramp(stops: usize, opacity: f32) -> Paint {
|
||||
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
|
||||
let stops = (0..stops)
|
||||
.map(|i| {
|
||||
let mut stop = GradientStop::new(i as f32 / stops as f32, Color::rgb(1.0, 0.0, 0.0));
|
||||
stop.opacity = opacity;
|
||||
stop
|
||||
})
|
||||
.collect();
|
||||
Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_copies_of_a_graphics_paint_have_a_budget_of_their_own() {
|
||||
let mut d = document();
|
||||
for (name, opacity) in [("Ramp", 1.0), ("Clear ramp", 0.5)] {
|
||||
let art =
|
||||
Node::path(NodeId(0), shapes::rectangle(Rect::new(0.0, 0.0, 300.0, 10.0)), Appearance::basic(ramp(4096, opacity), Paint::None, 0.0));
|
||||
d.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(art) });
|
||||
}
|
||||
let p = json!({"graphics": [{"symbol": "Ramp"}]});
|
||||
let n = revolved(&CYLINDER, json!({}));
|
||||
let NodeKind::Path { path, .. } = &n.kind else { panic!("a path") };
|
||||
let faces = vectorcraft_three_d::revolve(path, path.bounds().unwrap(), options_of(REVOLVE, &p)).unwrap();
|
||||
let parts_of = |symbol: &str, copies: &mut usize| {
|
||||
let graphics = crate::solids::mapped_graphics(&json!({"graphics": [{"symbol": symbol}]}));
|
||||
crate::solids::graphics::surface_parts(Some(&d), NodeId(0), &graphics, &faces, &|_, c| Paint::solid(c), copies).map(|p| p.concat().len())
|
||||
};
|
||||
// Each opaque part copies the paint into its fill and its seam stroke; a part with
|
||||
// transparent stops takes no seam stroke and copies it once.
|
||||
let (opaque, clear) = (paint_bytes(&ramp(4096, 1.0)), paint_bytes(&ramp(4096, 0.5)));
|
||||
let mut used = 0;
|
||||
let count = parts_of("Ramp", &mut used).unwrap();
|
||||
assert!(count >= 2, "the graphic draws on several faces");
|
||||
assert_eq!(used, 2 * count * opaque);
|
||||
let mut used = 0;
|
||||
assert_eq!(parts_of("Clear ramp", &mut used), Some(count));
|
||||
assert_eq!(used, count * clear);
|
||||
// Past the budget the graphic is refused.
|
||||
assert_eq!(parts_of("Ramp", &mut (MAX_PAINT_COPIES - opaque)), None);
|
||||
// A surface whose own gradient takes nearly the whole budget for surfaces still takes the
|
||||
// graphic, on the object, on one fill of two and on a member of a group.
|
||||
let stop = paint_bytes(&ramp(2, 1.0)) - paint_bytes(&ramp(1, 1.0));
|
||||
let base = paint_bytes(&ramp(1, 1.0)) - stop;
|
||||
let gray = Paint::solid(Color::rgb(0.5, 0.5, 0.5));
|
||||
let full = ramp(((MAX_PAINT_COPIES - paint_copies(faces.len(), &gray)) / (faces.len() * 4) - base) / stop, 1.0);
|
||||
assert!(MAX_PAINT_COPIES - paint_copies(faces.len(), &gray) - paint_copies(faces.len(), &full) < opaque);
|
||||
let mut object = n.clone();
|
||||
if let Some(AppearanceItem::Fill(f)) = object.appearance.items.first_mut() {
|
||||
f.paint = ramp(((MAX_PAINT_COPIES - opaque) / (faces.len() * 4) - base) / stop, 1.0);
|
||||
}
|
||||
assert_eq!(validate_revolve_in(Some(&d), &object, &p), Ok(()));
|
||||
let fill = |paint: Paint, params: Value| {
|
||||
let mut fill = FillLayer::new(paint);
|
||||
fill.effects.push(crate::new_effect(REVOLVE, ¶ms).unwrap());
|
||||
AppearanceItem::Fill(fill)
|
||||
};
|
||||
let mut two = n.clone();
|
||||
two.appearance = Appearance { items: vec![fill(gray.clone(), p.clone()), fill(full.clone(), json!({}))], ..Default::default() }.into();
|
||||
assert_eq!(crate::solids::validate_three_d_at_in(Some(&d), &two, REVOLVE, &json!({}), (Some(1), 0)), Ok(()));
|
||||
let mut member = n.clone();
|
||||
member.appearance.effects.clear();
|
||||
let mut second = member.clone();
|
||||
if let Some(AppearanceItem::Fill(f)) = second.appearance.items.first_mut() {
|
||||
f.paint = full;
|
||||
}
|
||||
let mut group = Node::group(NodeId(9), vec![Arc::new(member), Arc::new(second)]);
|
||||
group.appearance.effects = n.appearance.effects.clone();
|
||||
assert_eq!(validate_in(Some(&d), &group, REVOLVE, &p), Ok(()));
|
||||
}
|
||||
|
||||
/// Whether each part of `art` filled with a gradient has a stroke over its seams.
|
||||
fn gradient_seams(art: &Node) -> Vec<bool> {
|
||||
let mut out = vec![];
|
||||
art.walk(&mut |n| {
|
||||
let items = &n.appearance.items;
|
||||
let red = |p: &Paint| matches!(p, Paint::Gradient(_)) && shade_of(p, false).is_some();
|
||||
if n.path_data().is_some() && matches!(items.first(), Some(AppearanceItem::Fill(f)) if red(&f.paint)) {
|
||||
out.push(items.iter().any(|i| matches!(i, AppearanceItem::Stroke(_))));
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gradient_with_transparent_stops_takes_no_stroke_over_its_seams() {
|
||||
let mut d = document();
|
||||
for (name, opacity) in [("Opaque", 1.0), ("Clear", 0.5)] {
|
||||
let art = Node::path(NodeId(0), shapes::rectangle(Rect::new(0.0, 0.0, 60.0, 10.0)), Appearance::basic(ramp(2, opacity), Paint::None, 0.0));
|
||||
d.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(art) });
|
||||
}
|
||||
let seams = |symbol: &str| gradient_seams(&revolve_art_in(Some(&d), &revolved(&CYLINDER, json!({"graphics": [{"symbol": symbol}]}))).unwrap());
|
||||
let opaque = seams("Opaque");
|
||||
assert!(!opaque.is_empty() && opaque.iter().all(|s| *s), "{opaque:?}");
|
||||
let clear = seams("Clear");
|
||||
assert!(!clear.is_empty() && clear.iter().all(|s| !*s), "{clear:?}");
|
||||
}
|
||||
+729
-97
File diff suppressed because it is too large.
Load diff
@@ -8,6 +8,11 @@
|
||||
//! seen from the front of that face), its size as a share of the symbol's own, and its turn
|
||||
//! (degrees, counterclockwise). On the back cap, x runs to the right as the back is seen from
|
||||
//! behind, so the graphic reads the right way round there.
|
||||
//!
|
||||
//! On Revolve the graphics lie on the swept side surface, unrolled flat
|
||||
//! ([`vectorcraft_three_d::SurfaceCell`]): x and y are the offset of the graphic's center from the
|
||||
//! middle of that surface, x around the axis and y along the profile, and each face of the side
|
||||
//! draws the part of the graphics that falls on it ([`surface_parts`]).
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -15,7 +20,7 @@ use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::color::{BlendMode, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind, Symbol};
|
||||
use vectorcraft_geom::kurbo::{CubicBez, ParamCurve, PathEl, Shape};
|
||||
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, SubPath};
|
||||
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, SubPath, Vec2};
|
||||
use vectorcraft_three_d::{FaceMap, Facet, PlanarFace};
|
||||
|
||||
/// The effect parameter that holds the graphics.
|
||||
@@ -41,6 +46,33 @@ const MAX_NESTING: usize = 8;
|
||||
/// places: as deep as an object may be drawn.
|
||||
const MAX_LEVELS: usize = 4 * vectorcraft_doc::MAX_DEPTH;
|
||||
|
||||
/// The error for graphics on a 3D effect that takes none.
|
||||
pub const NOT_TAKEN: &str = "Graphics map onto the Plane, Extrude and Revolve object types";
|
||||
|
||||
/// The buckets around the unrolled side surface that the pieces of Revolve's graphics are sorted
|
||||
/// into, so each face looks only at the pieces near it.
|
||||
const SURFACE_BUCKETS: usize = 256;
|
||||
|
||||
/// How closely the curves of a graphic on Revolve's side follow their shape when they are cut into
|
||||
/// straight pieces, in points of the unrolled surface.
|
||||
const SURFACE_TOLERANCE: f64 = 0.05;
|
||||
|
||||
/// How far from the middle of Revolve's unrolled side a curve of a graphic may reach, in points:
|
||||
/// as far as a Revolve profile's coordinates may.
|
||||
const SURFACE_REACH: f64 = 1e8;
|
||||
|
||||
/// The most points the parts of Revolve's graphics draw on its faces together, a graphic's area cut
|
||||
/// at every face it crosses. Past it no graphic is drawn on that surface.
|
||||
const MAX_SURFACE_POINTS: usize = 2_000_000;
|
||||
|
||||
/// The most points of Revolve's graphics cut at its faces together, counted before each cut whether
|
||||
/// or not it keeps any of them. Past it no graphic is drawn on that surface.
|
||||
const MAX_SURFACE_CUTS: usize = 32 * MAX_SURFACE_POINTS;
|
||||
|
||||
/// The width of the stroke of the same paint around each opaque part of a graphic on Revolve's
|
||||
/// side, which covers the seams between the parts on neighboring faces.
|
||||
const SURFACE_SEAM: f64 = 0.3;
|
||||
|
||||
/// The size range of a graphic, as a percentage of its symbol's own size.
|
||||
pub const SCALE_RANGE: (f64, f64) = (1.0, 10_000.0);
|
||||
|
||||
@@ -116,10 +148,10 @@ impl MappedGraphic {
|
||||
}
|
||||
}
|
||||
|
||||
/// The 3D effects that take graphics: Extrude & Bevel (its caps) and Rotate (the plane), the two
|
||||
/// object types of the 3D and Materials panel with planar faces.
|
||||
/// The 3D effects that take graphics: Extrude & Bevel (its caps), Rotate (the plane) and Revolve
|
||||
/// (its swept side).
|
||||
pub fn takes_graphics(id: &str) -> bool {
|
||||
id == super::EXTRUDE || id == super::ROTATE
|
||||
id == super::EXTRUDE || id == super::ROTATE || id == crate::REVOLVE
|
||||
}
|
||||
|
||||
/// The graphics in parameters `p`, leaving out entries that are not valid (a file may hold
|
||||
@@ -131,8 +163,9 @@ pub fn mapped_graphics(p: &Value) -> Vec<MappedGraphic> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Are the graphics in parameters `p` of 3D effect `id` valid? Only Extrude & Bevel and Rotate take
|
||||
/// graphics, and a plane has only a front.
|
||||
/// Are the graphics in parameters `p` of 3D effect `id` valid? Only Extrude & Bevel, Rotate and
|
||||
/// Revolve take graphics; a plane has only a front, and Revolve's graphics go on its side, named
|
||||
/// the front.
|
||||
pub fn validate(id: &str, p: &Value) -> Result<(), String> {
|
||||
let list = match p.get(GRAPHICS) {
|
||||
None => return Ok(()),
|
||||
@@ -143,7 +176,7 @@ pub fn validate(id: &str, p: &Value) -> Result<(), String> {
|
||||
return Ok(());
|
||||
}
|
||||
if !takes_graphics(id) {
|
||||
return Err("Graphics map onto planar faces: use the Extrude or Plane object type".into());
|
||||
return Err(NOT_TAKEN.into());
|
||||
}
|
||||
if list.len() > MAX_GRAPHICS {
|
||||
return Err(format!("`{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics"));
|
||||
@@ -153,6 +186,9 @@ pub fn validate(id: &str, p: &Value) -> Result<(), String> {
|
||||
if id == super::ROTATE && g.face == PlanarFace::Back {
|
||||
return Err("A plane has one face: map its graphics onto the front".into());
|
||||
}
|
||||
if id == crate::REVOLVE && g.face == PlanarFace::Back {
|
||||
return Err("Revolve maps graphics onto its side: map them onto the front".into());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -483,6 +519,411 @@ pub(super) fn face_art(
|
||||
Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, children))], clip: true }))
|
||||
}
|
||||
|
||||
/// One area of a graphic placed on Revolve's unrolled side surface, cut into straight pieces.
|
||||
struct Unrolled {
|
||||
polygons: Vec<Vec<Point>>,
|
||||
/// The bounds of each of `polygons`.
|
||||
boxes: Vec<Rect>,
|
||||
bounds: Rect,
|
||||
rule: FillRule,
|
||||
paint: Paint,
|
||||
opacity: f32,
|
||||
blend: BlendMode,
|
||||
/// Where the graphic's art goes on the surface: its gradients and patterns are placed with it.
|
||||
place: Affine,
|
||||
}
|
||||
|
||||
/// The areas of `graphics` (those of the front: Revolve's side) placed on the unrolled side
|
||||
/// surface, cut into straight pieces. A graphic whose symbol `doc` does not have, or whose art is
|
||||
/// past the limits of [`pieces_of`], is left out. `None` when the pieces take more than
|
||||
/// [`MAX_ELEMENTS`] points together.
|
||||
fn unrolled(doc: &Document, graphics: &[MappedGraphic]) -> Option<Vec<Unrolled>> {
|
||||
let mut pieces = vec![];
|
||||
let mut points = 0usize;
|
||||
for g in graphics.iter().filter(|g| g.face == PlanarFace::Front) {
|
||||
let Some(symbol) = doc.symbols.iter().find(|s| s.name == g.symbol) else { continue };
|
||||
let Ok(art) = pieces_of(doc, symbol) else { continue };
|
||||
let Some(bounds) = art.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) else { continue };
|
||||
let place = g.placement(bounds, Point::ZERO);
|
||||
for piece in art {
|
||||
let placed = place * piece.path.to_bezpath();
|
||||
let mut polygons = straight_pieces(&placed, &mut points)?;
|
||||
polygons.retain(|p| p.len() >= 3 && p.iter().all(|q| q.is_finite()));
|
||||
let boxes: Vec<Rect> =
|
||||
polygons.iter().filter_map(|polygon| polygon.iter().map(|p| Rect::from_points(*p, *p)).reduce(|a, b| a.union(b))).collect();
|
||||
let Some(bounds) = boxes.iter().copied().reduce(|a, b| a.union(b)) else { continue };
|
||||
pieces.push(Unrolled {
|
||||
polygons,
|
||||
boxes,
|
||||
bounds,
|
||||
rule: piece.rule,
|
||||
paint: piece.paint,
|
||||
opacity: piece.opacity,
|
||||
blend: piece.blend,
|
||||
place,
|
||||
});
|
||||
}
|
||||
}
|
||||
Some(pieces)
|
||||
}
|
||||
|
||||
/// The contours of `path` cut into straight pieces within [`SURFACE_TOLERANCE`], adding the points
|
||||
/// made to `points`. Each curve is cut on its own and the count is checked before the next one, so
|
||||
/// the work stops at the first curve past [`MAX_ELEMENTS`] points: `None` then, and for a path with
|
||||
/// a coordinate of a line or a curve farther than [`SURFACE_REACH`] from the origin, which bounds
|
||||
/// the pieces of one curve and the arithmetic of the cuts at the faces.
|
||||
fn straight_pieces(path: &BezPath, points: &mut usize) -> Option<Vec<Vec<Point>>> {
|
||||
let near = |p: &Point| p.x.abs() <= SURFACE_REACH && p.y.abs() <= SURFACE_REACH;
|
||||
let mut polygons: Vec<Vec<Point>> = vec![];
|
||||
let mut current: Vec<Point> = vec![];
|
||||
let (mut start, mut last) = (Point::ZERO, Point::ZERO);
|
||||
for el in path.elements() {
|
||||
if *points > MAX_ELEMENTS {
|
||||
return None;
|
||||
}
|
||||
match *el {
|
||||
PathEl::MoveTo(p) | PathEl::LineTo(p) if !near(&p) => return None,
|
||||
PathEl::MoveTo(p) => {
|
||||
polygons.push(std::mem::take(&mut current));
|
||||
current.push(p);
|
||||
*points += 1;
|
||||
(start, last) = (p, p);
|
||||
}
|
||||
PathEl::LineTo(p) => {
|
||||
current.push(p);
|
||||
*points += 1;
|
||||
last = p;
|
||||
}
|
||||
PathEl::ClosePath => {
|
||||
polygons.push(std::mem::take(&mut current));
|
||||
last = start;
|
||||
}
|
||||
PathEl::QuadTo(a, p) | PathEl::CurveTo(_, a, p) => {
|
||||
let first = if let PathEl::CurveTo(b, ..) = *el { b } else { a };
|
||||
if ![last, first, a, p].iter().all(near) {
|
||||
return None;
|
||||
}
|
||||
vectorcraft_geom::kurbo::flatten([PathEl::MoveTo(last), *el], SURFACE_TOLERANCE, |cut| {
|
||||
if let PathEl::LineTo(q) = cut {
|
||||
current.push(q);
|
||||
*points += 1;
|
||||
}
|
||||
});
|
||||
last = p;
|
||||
}
|
||||
}
|
||||
}
|
||||
polygons.push(current);
|
||||
(*points <= MAX_ELEMENTS).then_some(polygons)
|
||||
}
|
||||
|
||||
/// Do the graphics in Revolve parameters `p` fit the limits with the symbols of `doc`? Their art,
|
||||
/// cut into straight pieces on the side surface, may take up to [`MAX_ELEMENTS`] points together.
|
||||
pub(crate) fn validate_surface_symbols(doc: &Document, p: &Value) -> Result<(), String> {
|
||||
let list = mapped_graphics(p);
|
||||
if list.is_empty() || unrolled(doc, &list).is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
Err("The graphics are too complex: simplify the symbols' art".into())
|
||||
}
|
||||
|
||||
/// The parts of `graphics` that fall on each of `faces`, a revolved surface's faces in drawing
|
||||
/// order, for an object with id `id`: for each face, the nodes to draw right after it. Only faces
|
||||
/// of the swept side that show their outside to the viewer carry a part, so a graphic narrows
|
||||
/// toward the silhouette, is hidden past it and is covered by the nearer faces drawn after it.
|
||||
/// `shade` gives the paint of a solid color on a face, as the surface under it is shaded; the
|
||||
/// colors of gradients and patterns are multiplied by the face's light. A graphic whose symbol
|
||||
/// `doc` does not have, or that is past the limits of its art, draws nothing. `None` past
|
||||
/// [`MAX_ELEMENTS`] points together before they are cut at the faces, [`MAX_SURFACE_POINTS`]
|
||||
/// after, [`MAX_SURFACE_CUTS`] points cut, or when the copies of their paints in the parts take
|
||||
/// `copies`, the bytes of the copies of the object's graphics so far, past Revolve's budget for
|
||||
/// them: commands refuse such graphics, and a loaded file draws the surface without them.
|
||||
pub(crate) fn surface_parts(
|
||||
doc: Option<&Document>,
|
||||
id: NodeId,
|
||||
graphics: &[MappedGraphic],
|
||||
faces: &[vectorcraft_three_d::Face],
|
||||
shade: &dyn Fn(&vectorcraft_three_d::Face, vectorcraft_doc::color::Color) -> Paint,
|
||||
copies: &mut usize,
|
||||
) -> Option<Vec<Vec<Arc<Node>>>> {
|
||||
let mut out: Vec<Vec<Arc<Node>>> = vec![vec![]; faces.len()];
|
||||
let Some(doc) = doc else { return Some(out) };
|
||||
let pieces = unrolled(doc, graphics)?;
|
||||
let Some(all) = pieces.iter().map(|p| p.bounds).reduce(|a, b| a.union(b)) else { return Some(out) };
|
||||
// Each piece listed in the buckets of the surface's x its bounds reach across.
|
||||
let width = (all.width() / SURFACE_BUCKETS as f64).max(1e-9);
|
||||
let bucket = |x: f64| (((x - all.x0) / width).floor().max(0.0) as usize).min(SURFACE_BUCKETS - 1);
|
||||
let mut buckets: Vec<Vec<usize>> = vec![vec![]; SURFACE_BUCKETS];
|
||||
for (k, p) in pieces.iter().enumerate() {
|
||||
for b in buckets.get_mut(bucket(p.bounds.x0)..=bucket(p.bounds.x1)).into_iter().flatten() {
|
||||
b.push(k);
|
||||
}
|
||||
}
|
||||
let mut seen = vec![usize::MAX; pieces.len()];
|
||||
let mut drawn = 0usize;
|
||||
let mut cut_points = 0usize;
|
||||
let mut triangle_id = 0usize;
|
||||
for (face, parts) in faces.iter().zip(out.iter_mut()) {
|
||||
let Some(cell) = face.surface.as_ref().filter(|c| c.outward && !face.cap) else { continue };
|
||||
if cell.uv.len() != cell.page.len() || !(3..=4).contains(&cell.uv.len()) {
|
||||
continue;
|
||||
}
|
||||
let triangles: &[[usize; 3]] = if cell.uv.len() == 3 { &[[0, 1, 2]] } else { &[[0, 1, 2], [0, 2, 3]] };
|
||||
for corners in triangles {
|
||||
triangle_id += 1;
|
||||
let pick = |of: &[Point]| corners.iter().map(|k| of.get(*k).copied()).collect::<Option<Vec<Point>>>();
|
||||
let (Some(uv), Some(page)) = (pick(&cell.uv), pick(&cell.page)) else { continue };
|
||||
let (Some(map), Some(window)) = (triangle_map(&uv, &page), counterclockwise(&uv)) else { continue };
|
||||
// A face along an end cap's ring has that edge curved on the page: its parts are cut
|
||||
// from a larger triangle and then to the face's own outline, so they reach the curve
|
||||
// where the graphic runs past the end of the profile. A four-cornered face is cut into
|
||||
// two triangles along its diagonal from corner 0 to corner 2: each takes the part of
|
||||
// the outline on its own side of it.
|
||||
let window = if face.outline.is_some() { grown(window, 3.0) } else { window };
|
||||
// The pieces are looked up over the whole of the window they are cut to.
|
||||
let Some(reach) = window.iter().map(|p| Rect::from_points(*p, *p)).reduce(|a, b| a.union(b)) else { continue };
|
||||
if reach.x1 < all.x0 || reach.x0 > all.x1 || reach.y1 < all.y0 || reach.y0 > all.y1 {
|
||||
continue;
|
||||
}
|
||||
// The pieces near the triangle, each once, in the graphics' drawing order.
|
||||
let mut near = vec![];
|
||||
for b in buckets.get(bucket(reach.x0)..=bucket(reach.x1)).into_iter().flatten() {
|
||||
for &k in b {
|
||||
let Some(slot) = seen.get_mut(k) else { continue };
|
||||
if *slot != triangle_id {
|
||||
*slot = triangle_id;
|
||||
near.push(k);
|
||||
}
|
||||
}
|
||||
}
|
||||
near.retain(|k| {
|
||||
pieces
|
||||
.get(*k)
|
||||
.is_some_and(|p| p.bounds.x1 >= reach.x0 && p.bounds.x0 <= reach.x1 && p.bounds.y1 >= reach.y0 && p.bounds.y0 <= reach.y1)
|
||||
});
|
||||
if near.is_empty() {
|
||||
continue;
|
||||
}
|
||||
near.sort_unstable();
|
||||
let own = corners.iter().find(|k| **k != 0 && **k != 2).and_then(|k| cell.page.get(*k)).filter(|_| triangles.len() == 2);
|
||||
let rim = face.outline.as_ref().map(|outline| match (own, cell.page.first(), cell.page.get(2)) {
|
||||
(Some(&toward), Some(&a), Some(&b)) => {
|
||||
let side = side_of(a, b, toward);
|
||||
vectorcraft_pathops::boolean(outline, FillRule::NonZero, &side, FillRule::NonZero, vectorcraft_pathops::BoolOp::Intersect)
|
||||
}
|
||||
_ => outline.clone(),
|
||||
});
|
||||
let rim = rim.as_ref();
|
||||
for k in near {
|
||||
let Some(piece) = pieces.get(k) else { continue };
|
||||
let mut path = BezPath::new();
|
||||
// Each contour is cut only where its own bounds reach the triangle.
|
||||
for (polygon, b) in piece.polygons.iter().zip(&piece.boxes) {
|
||||
if b.x1 < reach.x0 || b.x0 > reach.x1 || b.y1 < reach.y0 || b.y0 > reach.y1 {
|
||||
continue;
|
||||
}
|
||||
cut_points = cut_points.saturating_add(polygon.len());
|
||||
if cut_points > MAX_SURFACE_CUTS {
|
||||
return None;
|
||||
}
|
||||
let cut = clip_to(polygon, &window);
|
||||
let Some((first, rest)) = cut.split_first() else { continue };
|
||||
path.move_to(map * *first);
|
||||
rest.iter().for_each(|q| path.line_to(map * *q));
|
||||
path.close_path();
|
||||
drawn = drawn.saturating_add(cut.len());
|
||||
}
|
||||
if drawn > MAX_SURFACE_POINTS {
|
||||
return None;
|
||||
}
|
||||
if path.elements().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let (path, rule) = match rim {
|
||||
Some(outline) => {
|
||||
let cut = vectorcraft_pathops::boolean(
|
||||
&PathData::from_bezpath(&path),
|
||||
piece.rule,
|
||||
outline,
|
||||
FillRule::NonZero,
|
||||
vectorcraft_pathops::BoolOp::Intersect,
|
||||
);
|
||||
(cut.to_bezpath(), FillRule::NonZero)
|
||||
}
|
||||
None => (path, piece.rule),
|
||||
};
|
||||
if path.elements().is_empty() {
|
||||
continue;
|
||||
}
|
||||
// Each part copies its paint into its fill, and into the stroke over its seams when
|
||||
// it takes one.
|
||||
if !crate::revolve::paint_copies_add(copies, 1 + usize::from(takes_seam(piece)), &piece.paint) {
|
||||
return None;
|
||||
}
|
||||
parts.push(Arc::new(surface_piece(id, piece, (path, rule), map, face, shade)));
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// The node of the part `path` (on the page, filled under `rule`) of `piece`, which `map` takes
|
||||
/// from the unrolled surface onto `face`.
|
||||
fn surface_piece(
|
||||
id: NodeId,
|
||||
piece: &Unrolled,
|
||||
(path, rule): (BezPath, FillRule),
|
||||
map: Affine,
|
||||
face: &vectorcraft_three_d::Face,
|
||||
shade: &dyn Fn(&vectorcraft_three_d::Face, vectorcraft_doc::color::Color) -> Paint,
|
||||
) -> Node {
|
||||
let gradient_map = map * piece.place;
|
||||
// Under several lights a face's light varies across it in each channel: a solid color draws
|
||||
// as the face's own lit art in that color, clipped to the part. An opaque part also draws that
|
||||
// art clipped to a band of the seam stroke's width around its edges, as the other parts take
|
||||
// a stroke over their seams.
|
||||
if let (Some(c), Some(light)) = (piece.paint.color().filter(|_| matches!(piece.paint, Paint::Solid { .. })), face.rgb_gradient) {
|
||||
let lit = Arc::new(crate::lighting::rgb_gradient_art(id, &face.path(), &Paint::solid(c), light));
|
||||
let clipped = |area: &BezPath, rule: FillRule| {
|
||||
let mut clip = Node::path(id, PathData::from_bezpath(area), Appearance::default());
|
||||
if let NodeKind::Path { rule: r, .. } = &mut clip.kind {
|
||||
*r = rule;
|
||||
}
|
||||
Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), lit.clone()], clip: true })
|
||||
};
|
||||
let mut group = clipped(&path, rule);
|
||||
if takes_seam(piece) {
|
||||
let style = vectorcraft_geom::kurbo::Stroke::new(SURFACE_SEAM).with_join(vectorcraft_geom::kurbo::Join::Round);
|
||||
let band = vectorcraft_geom::kurbo::stroke(path.iter(), &style, &vectorcraft_geom::kurbo::StrokeOpts::default(), SURFACE_TOLERANCE);
|
||||
group = Node::group(id, vec![Arc::new(group), Arc::new(clipped(&band, FillRule::NonZero))]);
|
||||
}
|
||||
group.opacity = piece.opacity;
|
||||
group.blend = piece.blend;
|
||||
return group;
|
||||
}
|
||||
let mut paint = piece.paint.clone();
|
||||
if let Paint::Pattern { xf, .. } = &mut paint {
|
||||
*xf = gradient_map * *xf;
|
||||
}
|
||||
let solid = paint.color().filter(|_| matches!(paint, Paint::Solid { .. }));
|
||||
let mut fill = FillLayer::new(paint);
|
||||
fill.opacity = piece.opacity;
|
||||
fill.blend = piece.blend;
|
||||
let mut appearance = Appearance { items: vec![AppearanceItem::Fill(fill)], ..Default::default() };
|
||||
appearance.transform_gradients(gradient_map);
|
||||
for item in appearance.items.iter_mut() {
|
||||
if let AppearanceItem::Fill(f) = item {
|
||||
match solid {
|
||||
Some(c) => f.paint = shade(face, c),
|
||||
None => {
|
||||
vectorcraft_doc::recolor::map_paint(&mut f.paint, &|c| crate::lighting::shade(c, face.illumination));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Parts on neighboring faces meet edge to edge: an opaque part takes a narrow stroke of its
|
||||
// paint over the seam, as the faces do.
|
||||
if takes_seam(piece)
|
||||
&& let Some(AppearanceItem::Fill(f)) = appearance.items.first()
|
||||
{
|
||||
let mut seam = vectorcraft_doc::StrokeLayer::new(f.paint.clone(), SURFACE_SEAM);
|
||||
seam.join = vectorcraft_doc::LineJoin::Round;
|
||||
appearance.items.push(AppearanceItem::Stroke(seam));
|
||||
}
|
||||
let mut node = Node::path(id, PathData::from_bezpath(&path), appearance);
|
||||
if let NodeKind::Path { rule: r, .. } = &mut node.kind {
|
||||
*r = rule;
|
||||
}
|
||||
node
|
||||
}
|
||||
|
||||
/// Does each part of `piece` take a stroke of its paint over its seams? Only an opaque part does:
|
||||
/// the overlap of a transparent one, of one whose gradient has a stop or a freeform point that is
|
||||
/// not fully opaque, or of a pattern, whose tile may hold transparent art, would show.
|
||||
fn takes_seam(piece: &Unrolled) -> bool {
|
||||
let clear = match &piece.paint {
|
||||
Paint::Gradient(g) => {
|
||||
g.gradient.stops.iter().any(|s| s.opacity < 1.0) || g.freeform.as_ref().is_some_and(|f| f.points.iter().any(|p| p.opacity < 1.0))
|
||||
}
|
||||
Paint::Pattern { .. } => true,
|
||||
_ => false,
|
||||
};
|
||||
piece.opacity >= 1.0 && piece.blend == BlendMode::Normal && !clear
|
||||
}
|
||||
|
||||
/// A region far larger than the face on the side of the line through `a` and `b` that `toward` is
|
||||
/// on: a rectangle with one edge along the line, reaching a thousand times the line's length past
|
||||
/// its ends and away from it.
|
||||
fn side_of(a: Point, b: Point, toward: Point) -> PathData {
|
||||
let along = b - a;
|
||||
let mut across = Vec2::new(-along.y, along.x);
|
||||
if across.dot(toward - a) < 0.0 {
|
||||
across = -across;
|
||||
}
|
||||
let (far, wide) = (across * 1000.0, along * 1000.0);
|
||||
let mut out = BezPath::new();
|
||||
out.move_to(a - wide);
|
||||
out.line_to(b + wide);
|
||||
out.line_to(b + wide + far);
|
||||
out.line_to(a - wide + far);
|
||||
out.close_path();
|
||||
PathData::from_bezpath(&out)
|
||||
}
|
||||
|
||||
/// Triangle `t` scaled by `factor` about its centroid, wound as it was.
|
||||
fn grown(t: [Point; 3], factor: f64) -> [Point; 3] {
|
||||
let c = Point::new((t[0].x + t[1].x + t[2].x) / 3.0, (t[0].y + t[1].y + t[2].y) / 3.0);
|
||||
t.map(|p| c + (p - c) * factor)
|
||||
}
|
||||
|
||||
/// The affine map that takes the corners `from` of a triangle onto `to`. `None` for a triangle
|
||||
/// with no area or a map that is not finite.
|
||||
fn triangle_map(from: &[Point], to: &[Point]) -> Option<Affine> {
|
||||
let ([u0, u1, u2], [p0, p1, p2]) = (<[Point; 3]>::try_from(from).ok()?, <[Point; 3]>::try_from(to).ok()?);
|
||||
let (a, b) = (u1 - u0, u2 - u0);
|
||||
let det = a.x * b.y - b.x * a.y;
|
||||
if det.abs() <= 1e-12 * (a.hypot2() + b.hypot2()).max(1e-300) {
|
||||
return None;
|
||||
}
|
||||
let (c, d) = (p1 - p0, p2 - p0);
|
||||
let m = [(c.x * b.y - d.x * a.y) / det, (c.y * b.y - d.y * a.y) / det, (d.x * a.x - c.x * b.x) / det, (d.y * a.x - c.y * b.x) / det];
|
||||
let xf = Affine::new([m[0], m[1], m[2], m[3], p0.x - m[0] * u0.x - m[2] * u0.y, p0.y - m[1] * u0.x - m[3] * u0.y]);
|
||||
xf.as_coeffs().iter().all(|v| v.is_finite()).then_some(xf)
|
||||
}
|
||||
|
||||
/// Triangle `t` wound counterclockwise (y up), as [`clip_to`] reads its window. `None` without
|
||||
/// three corners.
|
||||
fn counterclockwise(t: &[Point]) -> Option<[Point; 3]> {
|
||||
let [a, b, c] = <[Point; 3]>::try_from(t).ok()?;
|
||||
Some(if (b - a).cross(c - a) < 0.0 { [a, c, b] } else { [a, b, c] })
|
||||
}
|
||||
|
||||
/// The part of `polygon` inside the convex `window` (one step of Sutherland and Hodgman's clip for
|
||||
/// each of its edges). A polygon that is not convex keeps its area, with edges along the window's
|
||||
/// sides where it leaves and comes back.
|
||||
fn clip_to(polygon: &[Point], window: &[Point; 3]) -> Vec<Point> {
|
||||
let mut out = polygon.to_vec();
|
||||
for k in 0..3 {
|
||||
let (a, b) = (window[k], window[(k + 1) % 3]);
|
||||
let side = |p: Point| (b - a).cross(p - a);
|
||||
let input = std::mem::take(&mut out);
|
||||
for (i, &p) in input.iter().enumerate() {
|
||||
let q = input[(i + 1) % input.len()];
|
||||
let (sp, sq) = (side(p), side(q));
|
||||
if sp >= 0.0 {
|
||||
out.push(p);
|
||||
}
|
||||
if (sp >= 0.0) != (sq >= 0.0) {
|
||||
out.push(p.lerp(q, sp / (sp - sq)));
|
||||
}
|
||||
}
|
||||
if out.len() < 3 {
|
||||
return vec![];
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The bounds of the art symbol `name` of `doc` draws as a graphic, in the symbol's coordinates.
|
||||
pub(super) fn art_bounds(doc: &Document, name: &str) -> Option<Rect> {
|
||||
let symbol = doc.symbols.iter().find(|s| s.name == name)?;
|
||||
|
||||
@@ -253,6 +253,468 @@ fn a_fills_walls_are_drawn_before_the_stroke_faces_over_them() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The faces of the solids effect `id` with `params` builds for `n`, in the order they are drawn,
|
||||
/// as [`surfaces_for`] orders them, each with the index of the part ([`solid_parts`]) it was built
|
||||
/// from and whether it is a stroke's.
|
||||
fn drawn_parts(n: &Node, id: &str, params: &Value) -> Vec<(Facet, usize, bool)> {
|
||||
let (path, rule) = profile(n).unwrap();
|
||||
let shapes = [Profile { path, rule, items: solid_paints(n), opacity: 1.0, scopes: vec![] }];
|
||||
let p = crate::merged_params(id, params);
|
||||
let (parts, bounds) = solid_parts(&shapes, union_bounds(&shapes).unwrap());
|
||||
let mut solids = vec![];
|
||||
for (part, ((item, _, _, _, _, member), f)) in parts.iter().zip(built_solids(id, &p, &parts, bounds, MAX_OBJECT_FACES)).enumerate() {
|
||||
let Some(f) = f.unwrap() else { continue };
|
||||
let closed = holds_edge(id, &shapes[*member].path);
|
||||
solids.push((Paints::of(item, closed), *member, f, part, matches!(item, AppearanceItem::Stroke(_))));
|
||||
}
|
||||
let mut cuts: Vec<(Paints, usize, &mut Vec<Facet>)> = solids.iter_mut().map(|(paints, member, f, _, _)| (*paints, *member, f)).collect();
|
||||
cut_stroke_faces(&mut cuts, MAX_OBJECT_FACES);
|
||||
let (mut placed, mut all) = (vec![], vec![]);
|
||||
for (paints, member, f, part, stroke) in solids {
|
||||
for facet in f {
|
||||
placed.push(Placed::of(&facet, member, paints));
|
||||
all.push((facet, part, stroke));
|
||||
}
|
||||
}
|
||||
let sealed = match id {
|
||||
INFLATE => inflate_options(&p).cap,
|
||||
CLASSIC_EXTRUDE => classic_extrude_options(&p).cap,
|
||||
_ => extrude_options(&p).cap,
|
||||
};
|
||||
draw_order(&placed, sealed).into_iter().map(|k| all[k].clone()).collect()
|
||||
}
|
||||
|
||||
/// Is `p` inside the polygon of `f` (nonzero winding)?
|
||||
fn facet_contains(f: &Facet, p: Point) -> bool {
|
||||
let mut winding = 0i32;
|
||||
for c in &f.contours {
|
||||
for (a, b) in c.iter().zip(c.iter().cycle().skip(1)).take(c.len()) {
|
||||
let cross = (b.x - a.x) * (p.y - a.y) - (p.x - a.x) * (b.y - a.y);
|
||||
if a.y <= p.y && b.y > p.y && cross > 0.0 {
|
||||
winding += 1;
|
||||
} else if a.y > p.y && b.y <= p.y && cross < 0.0 {
|
||||
winding -= 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
winding != 0
|
||||
}
|
||||
|
||||
/// The points of a 1 pt grid over `faces` (drawn in that order, each with whether it is a stroke's)
|
||||
/// where the face drawn on top is the fill's while a face of the stroke turned toward the viewer is
|
||||
/// nearer the viewer there by more than 0.5 pt, or the other way round. Points within 0.3 pt of an
|
||||
/// edge are left out.
|
||||
fn wrong_on_top(faces: &[(Facet, bool)]) -> Vec<Point> {
|
||||
let polygons: Vec<&Facet> = faces.iter().map(|(f, _)| f).collect();
|
||||
let extent =
|
||||
polygons.iter().flat_map(|f| f.contours.iter().flatten()).fold(Rect::new(f64::MAX, f64::MAX, f64::MIN, f64::MIN), |r, p| r.union_pt(*p));
|
||||
let mut wrong = vec![];
|
||||
let mut y = extent.y0.floor() + 0.5;
|
||||
while y < extent.y1 {
|
||||
let mut x = extent.x0.floor() + 0.5;
|
||||
while x < extent.x1 {
|
||||
let p = Point::new(x, y);
|
||||
let well_inside = |f: &Facet| {
|
||||
[(-0.3, -0.3), (0.3, -0.3), (-0.3, 0.3), (0.3, 0.3), (0.0, 0.0)].iter().all(|(dx, dy)| facet_contains(f, Point::new(x + dx, y + dy)))
|
||||
};
|
||||
let top = faces.iter().rposition(|(f, _)| facet_contains(f, p));
|
||||
if let Some((f, stroke)) = top.and_then(|k| faces.get(k)).filter(|(f, _)| !f.away && well_inside(f)) {
|
||||
let nearest = |of_stroke: bool| {
|
||||
faces.iter().filter(|(g, s)| *s == of_stroke && !g.away && well_inside(g)).filter_map(|(g, _)| g.depth_at(p)).reduce(f64::max)
|
||||
};
|
||||
if let (Some(ds), Some(df)) = (nearest(true), nearest(false))
|
||||
&& (ds - df).abs() > 0.5
|
||||
&& (ds > df) != *stroke
|
||||
&& f.depth_at(p).is_some()
|
||||
{
|
||||
wrong.push(p);
|
||||
}
|
||||
}
|
||||
x += 1.0;
|
||||
}
|
||||
y += 1.0;
|
||||
}
|
||||
wrong
|
||||
}
|
||||
|
||||
/// The points of a 1 pt grid over `faces` (drawn in that order) where the face drawn on top is
|
||||
/// farther from the viewer than another face turned toward the viewer, of any part, by more than
|
||||
/// 0.5 pt. Points within 0.3 pt of an edge, and faces without a plane, are left out.
|
||||
fn misdrawn(faces: &[(Facet, usize, bool)]) -> Vec<Point> {
|
||||
let extent =
|
||||
faces.iter().flat_map(|(f, ..)| f.contours.iter().flatten()).fold(Rect::new(f64::MAX, f64::MAX, f64::MIN, f64::MIN), |r, p| r.union_pt(*p));
|
||||
let mut wrong = vec![];
|
||||
let mut y = extent.y0.floor() + 0.5;
|
||||
while y < extent.y1 {
|
||||
let mut x = extent.x0.floor() + 0.5;
|
||||
while x < extent.x1 {
|
||||
let p = Point::new(x, y);
|
||||
let well_inside = |f: &Facet| {
|
||||
[(-0.3, -0.3), (0.3, -0.3), (-0.3, 0.3), (0.3, 0.3), (0.0, 0.0)].iter().all(|(dx, dy)| facet_contains(f, Point::new(x + dx, y + dy)))
|
||||
};
|
||||
let top = faces.iter().rposition(|(f, ..)| facet_contains(f, p)).and_then(|k| faces.get(k)).filter(|(f, ..)| !f.away && well_inside(f));
|
||||
if let Some(on_top) = top.and_then(|(f, ..)| f.depth_at(p)) {
|
||||
let nearest = faces.iter().filter(|(g, ..)| !g.away && well_inside(g)).filter_map(|(g, ..)| g.depth_at(p)).reduce(f64::max);
|
||||
if nearest.is_some_and(|d| d - on_top > 0.5) {
|
||||
wrong.push(p);
|
||||
}
|
||||
}
|
||||
x += 1.0;
|
||||
}
|
||||
y += 1.0;
|
||||
}
|
||||
wrong
|
||||
}
|
||||
|
||||
/// The faces of a shape's fill and strokes are drawn in the order of their depths where they
|
||||
/// overlap: on a turned C, with or without perspective, under a stroke that does not cover the
|
||||
/// fill's whole edge (dashed, with a width profile, or with a brush), under a plain stroke and
|
||||
/// under two strokes whose faces pass through each other, no point shows a face farther from the
|
||||
/// viewer than another, in Extrude & Bevel and Extrude & Bevel (Classic), and only a few in
|
||||
/// Inflate, where curved puffs cross.
|
||||
#[test]
|
||||
fn fill_walls_and_strokes_that_leave_gaps_draw_in_the_order_of_their_depths_where_they_overlap() {
|
||||
use vectorcraft_doc::{Dash, WidthProfile};
|
||||
let views = [
|
||||
json!({"rotationX": -20, "rotationY": -40, "rotationZ": 0}),
|
||||
json!({"rotationX": 25, "rotationY": -55, "rotationZ": 10}),
|
||||
json!({"rotationX": -30, "rotationY": 50, "rotationZ": 5, "perspectiveAngle": 40}),
|
||||
json!({"rotationX": -30, "rotationY": 20, "rotationZ": 5, "perspectiveAngle": 40}),
|
||||
];
|
||||
type Style<'a> = (&'a str, &'a dyn Fn(&mut Node));
|
||||
let first = |n: &mut Node, set: &dyn Fn(&mut StrokeLayer)| {
|
||||
if let Some(AppearanceItem::Stroke(s)) = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Stroke(_))) {
|
||||
set(s);
|
||||
}
|
||||
};
|
||||
let dash = |pattern: Vec<f64>, offset: f64| Some(Dash { pattern, offset, align_corners: false });
|
||||
let styles: [Style; 6] = [
|
||||
("plain", &|_| {}),
|
||||
("dashed", &|n| first(n, &|s| s.dash = dash(vec![12.0, 12.0], 0.0))),
|
||||
("profiled", &|n| first(n, &|s| s.profile = Some(WidthProfile::lens()))),
|
||||
("brushed", &|n| first(n, &|s| s.brush = Some("brush".into()))),
|
||||
("dashed with perspective", &|n| first(n, &|s| s.dash = dash(vec![20.0, 6.0], 3.0))),
|
||||
("two strokes", &|n| {
|
||||
first(n, &|s| s.dash = dash(vec![12.0, 12.0], 0.0));
|
||||
let mut wide = StrokeLayer::new(Paint::solid(RED), 14.0);
|
||||
wide.profile = Some(WidthProfile::lens());
|
||||
n.appearance.items.push(AppearanceItem::Stroke(wide));
|
||||
}),
|
||||
];
|
||||
for id in [EXTRUDE, CLASSIC_EXTRUDE, INFLATE] {
|
||||
for (v, view) in views.iter().enumerate() {
|
||||
for (style, set) in &styles {
|
||||
// The last two views, for the plain and the two strokes only.
|
||||
if v >= 2 && !["plain", "two strokes"].contains(style) {
|
||||
continue;
|
||||
}
|
||||
let mut params = view.clone();
|
||||
params["depth"] = json!(60);
|
||||
if style.contains("perspective") {
|
||||
params["perspectiveAngle"] = json!(40);
|
||||
}
|
||||
let mut n = stroked(&letter_c());
|
||||
set(&mut n);
|
||||
let parts = drawn_parts(&n, id, ¶ms);
|
||||
let faces: Vec<(Facet, bool)> = parts.iter().map(|(f, _, s)| (f.clone(), *s)).collect();
|
||||
assert!(faces.iter().any(|(_, s)| *s) && faces.iter().any(|(_, s)| !*s), "{id} {view} {style}: faces of both");
|
||||
// Inflate's curved puffs cross each other along curves its flat facets only follow
|
||||
// roughly: a few points next to those crossings may still show the farther face.
|
||||
let allowed = if id == INFLATE { 5 } else { 0 };
|
||||
let wrong = wrong_on_top(&faces);
|
||||
assert!(wrong.len() <= allowed, "{id} {view} {style}: {} points drawn in the wrong paint, first {:?}", wrong.len(), wrong.first());
|
||||
let wrong = misdrawn(&parts);
|
||||
assert!(wrong.len() <= allowed, "{id} {view} {style}: {} points show a farther face, first {:?}", wrong.len(), wrong.first());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The paths of `art`'s faces in drawing order, leaving out the graphics (clip groups).
|
||||
fn face_paths(art: &Node) -> Vec<PathData> {
|
||||
fn walk(n: &Node, out: &mut Vec<PathData>) {
|
||||
match &n.kind {
|
||||
NodeKind::Group { clip: true, .. } => {}
|
||||
NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, out)),
|
||||
_ => out.extend(n.path_data().cloned()),
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
walk(art, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// A member of a 3D group with an opacity mask or a blending mode of its own draws its fill's and
|
||||
/// its strokes' faces in one order inside that mask, the order the same member draws them in
|
||||
/// without it, its dashes cut where they pass through the fill's walls. A member whose stroke is
|
||||
/// translucent still draws each surface whole.
|
||||
#[test]
|
||||
fn a_masked_members_fill_and_stroke_faces_go_in_one_order() {
|
||||
let mut member = stroked(&letter_c());
|
||||
if let Some(AppearanceItem::Stroke(s)) = member.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Stroke(_))) {
|
||||
s.dash = Some(vectorcraft_doc::Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false });
|
||||
}
|
||||
let solid = |member: Node| {
|
||||
let mut g = Node::group(NodeId(2), vec![Arc::new(member)]);
|
||||
g.appearance.effects.push(fx(EXTRUDE, json!({"rotationX": -20, "rotationY": -40, "rotationZ": 0, "depth": 60})));
|
||||
solid_art(&g).unwrap()
|
||||
};
|
||||
let cover = Node::path(
|
||||
NodeId(900),
|
||||
vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 400.0, 400.0)),
|
||||
Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0),
|
||||
);
|
||||
let mut masked = member.clone();
|
||||
masked.extras_mut().mask = Some(Box::new(OpacityMask::new(cover, true)));
|
||||
let mut multiplied = member.clone();
|
||||
multiplied.blend = BlendMode::Multiply;
|
||||
let unmasked = face_paths(&solid(member.clone()));
|
||||
for (what, scoped) in [("masked", masked.clone()), ("multiplied", multiplied)] {
|
||||
let art = solid(scoped);
|
||||
let mut scopes = 0;
|
||||
art.walk(&mut |n| scopes += usize::from(n.extras().mask.is_some() || n.blend == BlendMode::Multiply));
|
||||
assert!(scopes > 0, "{what}: drawn in its scope");
|
||||
assert_eq!(face_paths(&art), unmasked, "{what}: the faces in the member's one order");
|
||||
}
|
||||
// A translucent stroke keeps its surface whole: the fill's faces, then the stroke's.
|
||||
if let Some(AppearanceItem::Stroke(s)) = masked.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Stroke(_))) {
|
||||
s.opacity = 0.5;
|
||||
}
|
||||
let art = solid(masked);
|
||||
let mut groups = vec![];
|
||||
art.walk(&mut |n| {
|
||||
if n.opacity == 0.5 {
|
||||
groups.push(n.children().map_or(0, Vec::len));
|
||||
}
|
||||
});
|
||||
assert_eq!(groups.len(), 1, "the stroke's surface is one translucent group");
|
||||
}
|
||||
|
||||
/// Under a light that is not white, Inflate in gradients, whose faces are drawn one by one, draws the
|
||||
/// fill's and the dashed stroke's faces in one order, as it does under a white light. A solid color,
|
||||
/// drawn as one composite of each surface's facets, still draws each surface whole.
|
||||
#[test]
|
||||
fn a_colored_inflate_in_gradients_draws_its_faces_in_one_order() {
|
||||
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
|
||||
let gradient = |c: Color| {
|
||||
Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(
|
||||
GradientKind::Linear,
|
||||
vec![GradientStop::new(0.0, c), GradientStop::new(1.0, Color::WHITE)],
|
||||
))))
|
||||
};
|
||||
let mut n = stroked(&letter_c());
|
||||
for item in &mut n.appearance.items {
|
||||
match item {
|
||||
AppearanceItem::Fill(f) => f.paint = gradient(RED),
|
||||
AppearanceItem::Stroke(s) => {
|
||||
s.paint = gradient(BLUE);
|
||||
s.dash = Some(vectorcraft_doc::Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false });
|
||||
}
|
||||
}
|
||||
}
|
||||
// How many surfaces the art draws, and how many faces the first holds.
|
||||
let drawn = |n: &Node, lights: Option<Value>| {
|
||||
let mut n = n.clone();
|
||||
let mut p = json!({"rotationX": -20, "rotationY": -40, "rotationZ": 0, "depth": 60});
|
||||
if let Some(lights) = lights {
|
||||
p["lights"] = lights;
|
||||
}
|
||||
n.appearance.effects.push(fx(INFLATE, p));
|
||||
let art = solid_art(&n).unwrap();
|
||||
let surfaces = art.children().unwrap();
|
||||
(surfaces.len(), surfaces[0].children().map_or(0, Vec::len))
|
||||
};
|
||||
let colored = json!([{"color": "#ff8080"}]);
|
||||
let white = drawn(&n, None);
|
||||
assert_eq!(white.0, 1, "one order");
|
||||
let cut = drawn_parts(&n, INFLATE, &json!({"rotationX": -20, "rotationY": -40, "rotationZ": 0, "depth": 60})).len();
|
||||
assert_eq!(white.1, cut, "the white light's faces, cut");
|
||||
assert_eq!(drawn(&n, Some(colored.clone())).0, 1, "one order under the colored light");
|
||||
// A solid color under the colored light: a composite for each of the fill and the stroke.
|
||||
let solid = stroked(&letter_c());
|
||||
assert_eq!(drawn(&solid, Some(colored)).0, 2);
|
||||
}
|
||||
|
||||
/// A face of a stroke that leaves gaps passing through the plane of its fill's wall where they
|
||||
/// overlap is cut along the line where their depths meet, into the piece in front of the wall and
|
||||
/// the piece behind it; a face on one side of the wall, another shape's stroke, a covering stroke
|
||||
/// and a cut past the room left are left whole.
|
||||
#[test]
|
||||
fn a_stroke_face_through_a_fill_wall_is_cut_where_their_depths_meet() {
|
||||
let facet = |x: f64, normal: [f64; 3], offset: f64| Facet {
|
||||
contours: vec![vec![Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)]],
|
||||
depth: 0.0,
|
||||
brightness: 1.0,
|
||||
illumination: [1.0; 3],
|
||||
normal,
|
||||
rgb_gradient: None,
|
||||
outline: None,
|
||||
side: true,
|
||||
away: false,
|
||||
end: None,
|
||||
plane: Some(DepthPlane { normal, offset, center: Point::ZERO, eye: None }),
|
||||
};
|
||||
let wall = facet(0.0, [0.0, 0.0, 1.0], 0.0);
|
||||
// z = x - 8: behind the wall left of x = 8, in front of it right of it.
|
||||
let r = std::f64::consts::FRAC_1_SQRT_2;
|
||||
let mut through = facet(5.0, [-r, 0.0, r], -8.0 * r);
|
||||
// Its curved outline: the top edge bows up to y = -2.
|
||||
let mut curved = BezPath::new();
|
||||
curved.move_to((5.0, 0.0));
|
||||
curved.curve_to((8.0, -8.0 / 3.0), (12.0, -8.0 / 3.0), (15.0, 0.0));
|
||||
curved.line_to((15.0, 10.0));
|
||||
curved.line_to((5.0, 10.0));
|
||||
curved.close_path();
|
||||
through.outline = Some(PathData::from_bezpath(&curved));
|
||||
let extent = |f: &Facet| polygon_bounds(&f.contours[0]);
|
||||
let cut_with = |paints: Paints, member: usize, room: usize| {
|
||||
let (mut fill, mut stroke) = (vec![wall.clone()], vec![through.clone()]);
|
||||
let mut solids: Vec<(Paints, usize, &mut Vec<Facet>)> = vec![(Paints::Fill, 0, &mut fill), (paints, member, &mut stroke)];
|
||||
cut_stroke_faces(&mut solids, room);
|
||||
stroke
|
||||
};
|
||||
let pieces = cut_with(Paints::Other, 0, 10);
|
||||
assert_eq!(pieces.len(), 2);
|
||||
let (near, far) = (extent(&pieces[0]), extent(&pieces[1]));
|
||||
assert!((near.x0 - 8.0).abs() < 1e-9 && near.x1 == 15.0 && far.x0 == 5.0 && (far.x1 - 8.0).abs() < 1e-9, "{near:?} {far:?}");
|
||||
assert!(pieces[0].depth > 0.0 && pieces[1].depth < 0.0);
|
||||
// Each piece keeps its side of the curved outline, the bowed edge included.
|
||||
let curve = |f: &Facet| f.outline.as_ref().and_then(PathData::bounds).unwrap();
|
||||
let (near, far) = (curve(&pieces[0]), curve(&pieces[1]));
|
||||
assert!((near.x0 - 8.0).abs() < 1e-6 && (near.x1 - 15.0).abs() < 1e-6 && near.y0 < -1.5, "{near:?}");
|
||||
assert!((far.x0 - 5.0).abs() < 1e-6 && (far.x1 - 8.0).abs() < 1e-6 && far.y0 < -1.5, "{far:?}");
|
||||
let whole = std::slice::from_ref(&through);
|
||||
assert_eq!(cut_with(Paints::Other, 1, 10), whole, "another shape's stroke");
|
||||
assert_eq!(cut_with(Paints::Stroke, 0, 10), whole, "a covering stroke");
|
||||
assert_eq!(cut_with(Paints::Other, 0, 0), whole, "no room");
|
||||
let (mut fill, mut stroke) = (vec![wall.clone()], vec![facet(5.0, [0.0, 0.0, 1.0], 1.0)]);
|
||||
cut_stroke_faces(&mut [(Paints::Fill, 0, &mut fill), (Paints::Other, 0, &mut stroke)], 10);
|
||||
assert_eq!(stroke.len(), 1, "in front of the wall wherever they overlap");
|
||||
// Of two of a shape's strokes whose faces pass through each other, the later stroke's face is
|
||||
// cut against the earlier one's; a covering stroke's face is never cut, and the other stroke's
|
||||
// face is cut against it. Two shapes' strokes are left whole.
|
||||
for (case, (first, second, cut_first)) in
|
||||
[(Paints::Other, Paints::Other, false), (Paints::Stroke, Paints::Other, false), (Paints::Other, Paints::Stroke, true)].into_iter().enumerate()
|
||||
{
|
||||
let (mut a, mut b) = (vec![wall.clone()], vec![through.clone()]);
|
||||
cut_stroke_faces(&mut [(first, 0, &mut a), (second, 0, &mut b)], 10);
|
||||
assert_eq!((a.len(), b.len()), if cut_first { (2, 1) } else { (1, 2) }, "case {case}");
|
||||
}
|
||||
let (mut a, mut b) = (vec![wall.clone()], vec![through.clone()]);
|
||||
cut_stroke_faces(&mut [(Paints::Other, 0, &mut a), (Paints::Other, 1, &mut b)], 10);
|
||||
assert_eq!((a.len(), b.len()), (1, 1), "two shapes");
|
||||
}
|
||||
|
||||
/// A small polygon far from the origin keeps its area and centroid.
|
||||
#[test]
|
||||
fn a_small_polygon_far_away_has_a_centroid() {
|
||||
let far = 100_000_000.0;
|
||||
let square = [Point::new(far, far), Point::new(far + 1.0, far), Point::new(far + 1.0, far + 1.0), Point::new(far, far + 1.0)];
|
||||
let c = centroid(&square).unwrap();
|
||||
assert!((c.x - far - 0.5).abs() < 1e-6 && (c.y - far - 0.5).abs() < 1e-6, "{c:?}");
|
||||
assert!(centroid(&[]).is_none() && centroid(&square[..2]).is_none());
|
||||
}
|
||||
|
||||
/// Cutting adds no more faces than the object's face limit and the paint-copy allowance leave room
|
||||
/// for, so an effect that draws with its faces uncut still draws.
|
||||
#[test]
|
||||
fn cutting_stays_within_the_face_limit_and_the_paint_allowance() {
|
||||
let items = stroked(&letter_c()).appearance.items.clone();
|
||||
let stroke = items.iter().find(|i| matches!(i, AppearanceItem::Stroke(_))).unwrap();
|
||||
let mut one = 0usize;
|
||||
crate::revolve::paint_copies_add(&mut one, 6, paint_ref(stroke));
|
||||
let max = crate::revolve::MAX_PAINT_COPIES;
|
||||
assert_eq!(cut_room(items.iter(), 10, 0), (MAX_OBJECT_FACES - 10).min(max / one));
|
||||
assert_eq!(cut_room(items.iter(), MAX_OBJECT_FACES + 5, 0), 0);
|
||||
assert_eq!(cut_room(items.iter(), 10, max - 3 * one), 3);
|
||||
assert_eq!(cut_room(items.iter(), 10, max + 1), 0);
|
||||
}
|
||||
|
||||
/// Where a shape's fill wall and a face of its stroke that leaves gaps overlap, the one nearer the
|
||||
/// viewer there is drawn after the other, whichever their depths put first; a stroke face that
|
||||
/// overlaps no fill wall keeps its place.
|
||||
#[test]
|
||||
fn local_order_puts_overlapping_fill_walls_and_stroke_faces_in_depth_order() {
|
||||
let square = |x: f64| vec![Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)];
|
||||
let at = |depth: f64, x: f64, z: f64, paints: Paints| Placed {
|
||||
depth,
|
||||
side: true,
|
||||
away: false,
|
||||
bounds: Rect::new(x, 0.0, x + 10.0, 10.0),
|
||||
member: 0,
|
||||
paints,
|
||||
outline: square(x),
|
||||
plane: Some(DepthPlane { normal: [0.0, 0.0, 1.0], offset: z, center: Point::ZERO, eye: None }),
|
||||
};
|
||||
// 0 a fill wall at z 0; 1 a stroke face over half of it, nearer, sorted before it; 2 a stroke
|
||||
// face elsewhere; 3 a stroke face over it, farther, sorted after it.
|
||||
let faces =
|
||||
[at(5.0, 0.0, 0.0, Paints::Fill), at(2.0, 5.0, 1.0, Paints::Other), at(1.0, 20.0, 1.0, Paints::Other), at(6.0, 2.0, -1.0, Paints::Other)];
|
||||
assert_eq!(draw_order(&faces, true), [2, 3, 0, 1]);
|
||||
assert_eq!(draw_order(&faces, false), [2, 3, 0, 1]);
|
||||
// A covering stroke's faces keep the wall's own rule.
|
||||
let covering: Vec<Placed> = faces
|
||||
.iter()
|
||||
.map(|f| Placed { paints: if f.paints == Paints::Other { Paints::Stroke } else { f.paints }, outline: vec![], plane: None, ..*f })
|
||||
.collect();
|
||||
assert_eq!(draw_order(&covering, false), [2, 1, 0, 3]);
|
||||
// Another shape's stroke, and a stroke face at the same depth where they overlap, move nothing.
|
||||
let other_shape: Vec<Placed> =
|
||||
faces[..3].iter().map(|f| Placed { member: usize::from(f.paints == Paints::Other), outline: f.outline.clone(), ..*f }).collect();
|
||||
assert_eq!(draw_order(&other_shape, true), [2, 1, 0]);
|
||||
let level = [at(5.0, 0.0, 0.0, Paints::Fill), at(2.0, 5.0, 0.0, Paints::Other)];
|
||||
assert_eq!(draw_order(&level, true), [1, 0]);
|
||||
// A stroke face moved after its fill's wall does not pass a nearer face of another shape that
|
||||
// it overlaps: 0 a stroke face, 1 another shape's face in front of both, 2 the fill's wall.
|
||||
let in_front = Placed { member: 1, ..at(2.0, 5.0, 2.0, Paints::Fill) };
|
||||
let shapes = [at(1.0, 5.0, 1.0, Paints::Other), in_front, at(3.0, 0.0, 0.0, Paints::Fill)];
|
||||
assert_eq!(draw_order(&shapes, true), [2, 0, 1]);
|
||||
// A shape with a covering stroke as well keeps its fill wall before the covering stroke's face,
|
||||
// even where that face is the farther: 0 the fill's wall, 1 the covering stroke's face behind
|
||||
// it, 2 the other stroke's face in front.
|
||||
let both = [at(3.0, 0.0, 0.0, Paints::Fill), at(3.0, 0.0, -1.0, Paints::Stroke), at(2.0, 5.0, 1.0, Paints::Other)];
|
||||
assert_eq!(draw_order(&both, true), [0, 1, 2]);
|
||||
// Faces of a shape's strokes go in the order of their depths where they overlap too, with no
|
||||
// fill face among them: 1 is nearer than 0 there, though sorted before it.
|
||||
for (case, (back, front)) in
|
||||
[(Paints::Other, Paints::Other), (Paints::Stroke, Paints::Other), (Paints::Stroke, Paints::Stroke)].into_iter().enumerate()
|
||||
{
|
||||
let strokes = [at(5.0, 0.0, 0.0, back), at(2.0, 5.0, 1.0, front)];
|
||||
assert_eq!(draw_order(&strokes, true), [0, 1], "case {case}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A cycle of overlapping stroke faces is broken at the face that comes first by depth, and a cap
|
||||
/// drawn last stays after every wall: 0 at x 0 to 10, flat at z 0; 1 at x 4 to 14, z = x - 8; 2 at
|
||||
/// x 8 to 18, flat at z 1. Where they overlap, 0 is nearer than 1, 1 nearer than 2 and 2 nearer
|
||||
/// than 0. 3 is the cap.
|
||||
#[test]
|
||||
fn a_depth_cycle_keeps_the_cap_last() {
|
||||
let square = |x: f64| vec![Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)];
|
||||
let at = |depth: f64, x: f64, normal: [f64; 3], offset: f64| Placed {
|
||||
depth,
|
||||
side: true,
|
||||
away: false,
|
||||
bounds: Rect::new(x, 0.0, x + 10.0, 10.0),
|
||||
member: 0,
|
||||
paints: Paints::Other,
|
||||
outline: square(x),
|
||||
plane: Some(DepthPlane { normal, offset, center: Point::ZERO, eye: None }),
|
||||
};
|
||||
let cap = Placed {
|
||||
depth: f64::MAX,
|
||||
side: false,
|
||||
away: false,
|
||||
bounds: Rect::new(0.0, 0.0, 18.0, 10.0),
|
||||
member: 0,
|
||||
paints: Paints::Other,
|
||||
outline: vec![],
|
||||
plane: None,
|
||||
};
|
||||
let faces = [at(1.0, 0.0, [0.0, 0.0, 1.0], 0.0), at(2.0, 4.0, [-1.0, 0.0, 1.0], -8.0), at(3.0, 8.0, [0.0, 0.0, 1.0], 1.0), cap];
|
||||
assert_eq!(draw_order(&faces, true), [0, 2, 1, 3]);
|
||||
}
|
||||
|
||||
/// The order keeps depths except where a shape's fill wall turned toward the viewer overlaps a
|
||||
/// face of the same shape's stroke drawn before it: the wall then goes just before that face. A
|
||||
/// cap, a face turned away, another shape's stroke, a stroke face the wall does not overlap and an
|
||||
@@ -266,6 +728,8 @@ fn the_draw_order_moves_a_fill_wall_before_the_stroke_faces_it_overlaps() {
|
||||
bounds: Rect::new(x, 0.0, x + 10.0, 10.0),
|
||||
member,
|
||||
paints,
|
||||
outline: vec![],
|
||||
plane: None,
|
||||
};
|
||||
// 0 the fill's wall; 1 the stroke's wall over it; 2 another shape's stroke over it; 3 a stroke
|
||||
// wall elsewhere; 4 a stroke face turned away; 5 a fill cap; 6 the stroke's cap, nearer; 7 a
|
||||
@@ -292,6 +756,9 @@ fn the_draw_order_moves_a_fill_wall_before_the_stroke_faces_it_overlaps() {
|
||||
};
|
||||
assert!(Paints::of(&stroke(&|_| {}), true) == Paints::Stroke);
|
||||
assert!(Paints::of(&stroke(&|_| {}), false) == Paints::Other, "an open shape");
|
||||
let closed = profile(&stroked(&letter_c())).unwrap().0;
|
||||
assert!(holds_edge(EXTRUDE, &closed) && holds_edge(CLASSIC_EXTRUDE, &closed));
|
||||
assert!(!holds_edge(INFLATE, &closed), "an inflated fill can rise in front of its stroke");
|
||||
assert!(Paints::of(&stroke(&|s| s.width = 0.0), true) == Paints::Other, "no width");
|
||||
let dash = vectorcraft_doc::Dash { pattern: vec![4.0, 4.0], offset: 0.0, align_corners: false };
|
||||
assert!(Paints::of(&stroke(&|s| s.dash = Some(dash.clone())), true) == Paints::Other, "dashes");
|
||||
@@ -353,6 +820,142 @@ fn a_stroke_past_the_limits_is_left_out() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Each solid [`built_solids`] gives for effect `id` on `n` within `limit` faces together, as its
|
||||
/// face count (`None` for a stroke left out) or the error, every result the iterator gives.
|
||||
fn solid_faces(id: &str, n: &Node, limit: usize) -> Vec<Result<Option<usize>, String>> {
|
||||
let shapes = [Profile { path: profile(n).unwrap().0, rule: FillRule::NonZero, items: solid_paints(n), opacity: 1.0, scopes: vec![] }];
|
||||
let p = crate::merged_params(id, &json!({}));
|
||||
let (parts, bounds) = solid_parts(&shapes, union_bounds(&shapes).unwrap());
|
||||
built_solids(id, &p, &parts, bounds, limit).map(|r| r.map(|f| f.map(|f| f.len()))).collect()
|
||||
}
|
||||
|
||||
/// The solids of one object count their faces together: at the limit they all build, one face past
|
||||
/// it is an error, and the solids after the one that passes it are never built.
|
||||
#[test]
|
||||
fn an_objects_solids_count_their_faces_together() {
|
||||
for id in [EXTRUDE, CLASSIC_EXTRUDE, INFLATE] {
|
||||
let mut n = square_node();
|
||||
// A second stroke, so a solid follows the one that passes the limit.
|
||||
let stroke = n.appearance.items[1].clone();
|
||||
n.appearance.items.push(stroke);
|
||||
let counts: Vec<usize> = solid_faces(id, &n, MAX_OBJECT_FACES).into_iter().map(|c| c.unwrap().unwrap()).collect();
|
||||
assert!(counts.len() == 3 && counts.iter().all(|c| *c > 0), "{id}: {counts:?}");
|
||||
let total: usize = counts.iter().sum();
|
||||
assert!(solid_faces(id, &n, total).iter().all(Result::is_ok), "{id}: at the limit");
|
||||
let past = solid_faces(id, &n, total - 1);
|
||||
assert_eq!(past.last(), Some(&Err(vectorcraft_three_d::TOO_COMPLEX_SOLID.to_string())), "{id}");
|
||||
SOLIDS_BUILT.with(|b| b.set(0));
|
||||
let past = solid_faces(id, &n, counts[0] + counts[1] - 1);
|
||||
assert!(past.len() == 2 && past[1].is_err(), "{id}: {past:?}");
|
||||
assert_eq!(SOLIDS_BUILT.with(std::cell::Cell::get), 2, "{id}: the second stroke's solid is never built");
|
||||
}
|
||||
}
|
||||
|
||||
/// A convex polygon of `corners` corners about (20,000, 20,000), filled red, with no stroke.
|
||||
fn polygon_node(id: u64, corners: usize) -> Node {
|
||||
let points: Vec<Point> = (0..corners)
|
||||
.map(|k| {
|
||||
let (s, c) = (k as f64 * std::f64::consts::TAU / corners as f64).sin_cos();
|
||||
Point::new(20_000.0 + 10_000.0 * c, 20_000.0 + 10_000.0 * s)
|
||||
})
|
||||
.collect();
|
||||
let path = PathData::single(vectorcraft_geom::SubPath::polyline(&points, true));
|
||||
Node::path(NodeId(id), path, Appearance::basic(Paint::solid(RED), Paint::None, 0.0))
|
||||
}
|
||||
|
||||
/// A group whose members' solids each fit, but not all of them together, draws its source art, and
|
||||
/// the commands that check the effect report the error, as do its mesh and its wireframe; one
|
||||
/// member fewer, within the limit, draws.
|
||||
#[test]
|
||||
fn a_groups_solids_together_past_the_limit_draw_the_source() {
|
||||
let member = polygon_node(1, 16_384);
|
||||
let mut alone = member.clone();
|
||||
alone.appearance.effects.push(fx(EXTRUDE, json!({})));
|
||||
let [Ok(Some(each))] = solid_faces(EXTRUDE, &alone, MAX_OBJECT_FACES)[..] else { panic!("one solid") };
|
||||
// Members stacked in one place each build the same solid.
|
||||
let fits = MAX_OBJECT_FACES / each;
|
||||
let group = |count: usize| {
|
||||
let members = (0..count)
|
||||
.map(|k| {
|
||||
let mut m = member.clone();
|
||||
m.id = NodeId(k as u64 + 1);
|
||||
Arc::new(m)
|
||||
})
|
||||
.collect();
|
||||
let mut g = Node::group(NodeId(9999), members);
|
||||
g.appearance.effects.push(fx(EXTRUDE, json!({})));
|
||||
g
|
||||
};
|
||||
let within = group(fits);
|
||||
assert!(validate_solid(&within, EXTRUDE, &json!({})).is_ok(), "{fits} × {each} faces");
|
||||
assert!(solid_art(&within).is_some());
|
||||
let past = group(fits + 1);
|
||||
assert_eq!(validate_solid(&past, EXTRUDE, &json!({})), Err(vectorcraft_three_d::TOO_COMPLEX_SOLID.to_string()));
|
||||
assert!(solid_art(&past).is_none(), "the source art draws");
|
||||
assert_eq!(three_d_meshes(&past), Err(vectorcraft_three_d::TOO_COMPLEX_SOLID.to_string()));
|
||||
assert_eq!(three_d_wireframe_in(None, &past), Err(vectorcraft_three_d::TOO_COMPLEX_SOLID.to_string()));
|
||||
}
|
||||
|
||||
/// A fill and strokes whose solids each fit, but not all of them together, draw the source art,
|
||||
/// and the strokes after the one past the limit are not left out to make room.
|
||||
#[test]
|
||||
fn a_fill_and_strokes_together_past_the_limit_draw_the_source() {
|
||||
let mut n = polygon_node(1, 16_384);
|
||||
n.appearance.effects.push(fx(EXTRUDE, json!({})));
|
||||
let stroke = AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(BLUE), 20.0));
|
||||
n.appearance.items.push(stroke.clone());
|
||||
// Strokes alike each build the same solid.
|
||||
let [Ok(Some(fill)), Ok(Some(each))] = solid_faces(EXTRUDE, &n, MAX_OBJECT_FACES)[..] else { panic!("a fill's solid and a stroke's") };
|
||||
let fits = (MAX_OBJECT_FACES - fill) / each;
|
||||
assert!(fits >= 2, "{fill} + {fits} × {each}");
|
||||
n.appearance.items.extend(std::iter::repeat_n(stroke, fits - 1));
|
||||
assert!(validate_solid(&n, EXTRUDE, &json!({})).is_ok(), "{fill} + {fits} × {each}");
|
||||
let art = solid_art(&n).unwrap();
|
||||
assert!(faces(&art).iter().any(|f| blue(f)));
|
||||
n.appearance.items.push(AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(BLUE), 20.0)));
|
||||
assert_eq!(validate_solid(&n, EXTRUDE, &json!({})), Err(vectorcraft_three_d::TOO_COMPLEX_SOLID.to_string()));
|
||||
assert!(solid_art(&n).is_none(), "the source art draws");
|
||||
}
|
||||
|
||||
/// The check builds the solids from the shapes the art draws them from: after the geometry effects
|
||||
/// before the 3D effect, on an object, on its fill and on a group. Copies a Transform effect before
|
||||
/// it makes that take the solids past the limit fail the check, as the art then draws the source.
|
||||
#[test]
|
||||
fn the_check_counts_the_faces_after_the_geometry_effects_before() {
|
||||
let mut alone = polygon_node(1, 16_384);
|
||||
alone.appearance.effects.push(fx(EXTRUDE, json!({})));
|
||||
let [Ok(Some(each))] = solid_faces(EXTRUDE, &alone, MAX_OBJECT_FACES)[..] else { panic!("one solid") };
|
||||
// Side by side, each copy builds the same solid.
|
||||
let copies = |k: usize| fx("distort.transform", json!({"moveH": 30_000.0, "copies": k}));
|
||||
for (k, fits) in [(1, true), (MAX_OBJECT_FACES / each, false)] {
|
||||
let mut n = polygon_node(1, 16_384);
|
||||
n.appearance.effects = vec![copies(k), fx(EXTRUDE, json!({}))];
|
||||
assert_eq!(validate_solid(&n, EXTRUDE, &json!({})).is_ok(), fits, "on the object, {k} copies");
|
||||
assert_eq!(solid_art(&n).is_some(), fits, "on the object, {k} copies");
|
||||
let mut f = polygon_node(1, 16_384);
|
||||
f.appearance.items[0].effects_mut().extend([copies(k), fx(EXTRUDE, json!({}))]);
|
||||
assert_eq!(validate_three_d_at(&f, EXTRUDE, &json!({}), (Some(0), 1)).is_ok(), fits, "on the fill, {k} copies");
|
||||
assert_eq!(solid_art(&f).is_some(), fits, "on the fill, {k} copies");
|
||||
let mut g = Node::group(NodeId(9999), vec![Arc::new(polygon_node(1, 16_384))]);
|
||||
g.appearance.effects = vec![copies(k), fx(EXTRUDE, json!({}))];
|
||||
assert_eq!(validate_solid(&g, EXTRUDE, &json!({})).is_ok(), fits, "on a group, {k} copies");
|
||||
assert_eq!(solid_art(&g).is_some(), fits, "on a group, {k} copies");
|
||||
// A new effect goes after the copies.
|
||||
let mut new = polygon_node(1, 16_384);
|
||||
new.appearance.effects = vec![copies(k)];
|
||||
assert_eq!(validate_three_d_at(&new, EXTRUDE, &json!({}), (None, 1)).is_ok(), fits, "a new effect, {k} copies");
|
||||
}
|
||||
// A hidden effect checked at its own index counts only the effects before it: copies after it
|
||||
// copy the drawn art once it is shown again.
|
||||
let mut hidden = polygon_node(1, 16_384);
|
||||
let mut extrude = fx(EXTRUDE, json!({}));
|
||||
extrude.visible = false;
|
||||
hidden.appearance.effects = vec![extrude, copies(MAX_OBJECT_FACES / each)];
|
||||
assert!(validate_three_d_at(&hidden, EXTRUDE, &json!({}), (None, 0)).is_ok());
|
||||
hidden.appearance.effects[0].visible = true;
|
||||
assert!(solid_art(&hidden).is_some());
|
||||
}
|
||||
|
||||
/// At no volume Inflate's front is flat: turned, the fill's cells are all drawn before the stroke's,
|
||||
/// whatever their depths, as the extrusion's caps are. When the fill puffs, a stroke too narrow to
|
||||
/// puff on the grid stays flat and keeps its depths: the fill's puff is drawn over its far side.
|
||||
|
||||
@@ -505,7 +505,10 @@ fn graphics_are_checked() {
|
||||
}
|
||||
assert!(check(ROTATE, json!([{"symbol": "Mark", "face": "back"}])).is_err());
|
||||
assert!(check(INFLATE, json!([{"symbol": "Mark"}])).is_err());
|
||||
assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark"}]})).is_err());
|
||||
// Revolve takes graphics on its side, named the front; Revolve (Classic) takes none.
|
||||
assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark"}]})).is_ok());
|
||||
assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark", "face": "back"}]})).is_err());
|
||||
assert!(validate_three_d_params(crate::CLASSIC_REVOLVE, &json!({"graphics": [{"symbol": "Mark"}]})).is_err());
|
||||
// A loaded file's invalid entries are left out when drawn.
|
||||
assert_eq!(mapped_graphics(&json!({"graphics": [{"symbol": "Mark"}, {"face": "back"}, 3]})).len(), 1);
|
||||
}
|
||||
@@ -620,6 +623,110 @@ fn a_solid_in_a_transparent_gradient_keeps_its_graphic() {
|
||||
assert_eq!(masks(&solid_art_in(Some(&d), &n).unwrap()), vec![true, false]);
|
||||
}
|
||||
|
||||
/// The paths of `art`'s faces in drawing order (a face lit by a colored light is a clip group: its
|
||||
/// clipping path), leaving out the graphics (clip groups of solid-color paths).
|
||||
fn face_paths(art: &Node) -> Vec<PathData> {
|
||||
fn walk(n: &Node, out: &mut Vec<PathData>) {
|
||||
match &n.kind {
|
||||
NodeKind::Group { children, clip: true } => {
|
||||
let graphic = children.get(1).is_some_and(|inner| match &inner.kind {
|
||||
NodeKind::Group { children: paths, clip: false } => paths.iter().all(|p| {
|
||||
p.path_data().is_some()
|
||||
&& p.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if f.paint.color().is_some()))
|
||||
}),
|
||||
_ => false,
|
||||
});
|
||||
if !graphic {
|
||||
out.extend(children.first().and_then(|c| c.path_data()).cloned());
|
||||
}
|
||||
}
|
||||
NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, out)),
|
||||
_ => out.extend(n.path_data().cloned()),
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
walk(art, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// A turned solid in a gradient with transparent stops under a colored light, with a dashed stroke
|
||||
/// and a graphic, draws its fill's and its stroke's faces in the one order it draws them in without
|
||||
/// the graphic, and the graphic keeps the cap's mask and goes after the fill's cap, not the stroke's.
|
||||
#[test]
|
||||
fn a_transparent_gradient_with_a_graphic_keeps_the_shared_face_order() {
|
||||
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
|
||||
let d = document();
|
||||
let mut stop = GradientStop::new(1.0, red());
|
||||
stop.opacity = 0.25;
|
||||
let gradient = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), stop]));
|
||||
let solid = |graphics: Value| {
|
||||
let mut n = object(
|
||||
EXTRUDE,
|
||||
json!({"rotationX": -20.0, "rotationY": -40.0, "depth": 60.0, "shade": true, "lights": [{"color": "#ff8080"}], "graphics": graphics}),
|
||||
);
|
||||
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
|
||||
f.paint = Paint::Gradient(Box::new(gradient.clone()));
|
||||
}
|
||||
// A gradient stroke: a solid color under the colored light would be one composite.
|
||||
let blues = Gradient::new(
|
||||
GradientKind::Linear,
|
||||
vec![GradientStop::new(0.0, Color::rgb(0.0, 0.0, 1.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 0.5))],
|
||||
);
|
||||
let mut stroke = StrokeLayer::new(Paint::Gradient(Box::new(GradientPaint::new(blues))), 6.0);
|
||||
stroke.dash = Some(vectorcraft_doc::Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false });
|
||||
n.appearance.items.push(AppearanceItem::Stroke(stroke));
|
||||
solid_art_in(Some(&d), &n).unwrap()
|
||||
};
|
||||
let with = solid(json!([{"symbol": "Mark"}]));
|
||||
let without = solid(json!([]));
|
||||
assert!(face_paths(&without).len() > 20, "the faces are found");
|
||||
assert_eq!(face_paths(&with), face_paths(&without), "the faces in one order");
|
||||
// The graphic is drawn on the fill's cap and on the stroke's (the clip groups holding the
|
||||
// symbol's red square); the fill's, whose surface carries the mask, carries it too.
|
||||
let mut masked = vec![];
|
||||
with.walk(&mut |c| {
|
||||
if let NodeKind::Group { children, clip: true } = &c.kind
|
||||
&& let [_, inner] = children.as_slice()
|
||||
&& let NodeKind::Group { children: paths, clip: false } = &inner.kind
|
||||
&& paths.iter().any(|p| {
|
||||
p.appearance.items.iter().any(|i| match i {
|
||||
AppearanceItem::Fill(f) => f.paint.color().is_some_and(|c| c.to_rgb()[1] < 0.1 && c.to_rgb()[0] > 0.3),
|
||||
AppearanceItem::Stroke(_) => false,
|
||||
})
|
||||
})
|
||||
{
|
||||
masked.push(c.extras().mask.is_some());
|
||||
}
|
||||
});
|
||||
masked.sort_unstable();
|
||||
assert_eq!(masked, [false, true], "the fill's graphic carries the cap's mask");
|
||||
// The fill's graphic goes right after the fill's cap, so the dashes on the cap's edge, drawn
|
||||
// after it, cover it. Drawn in order: the fill's graphic (the masked clip group), and each face,
|
||||
// the fill's or the stroke's by its gradient's first stop (red or blue), with its bounds.
|
||||
let mut drawn: Vec<(&str, Rect)> = vec![];
|
||||
with.walk(&mut |c| {
|
||||
if let NodeKind::Group { children, clip: true } = &c.kind
|
||||
&& c.extras().mask.is_some()
|
||||
&& let Some(bounds) = children.first().and_then(|clip| clip.path_data()).and_then(PathData::bounds)
|
||||
{
|
||||
drawn.push(("graphic", bounds));
|
||||
}
|
||||
let first_stop = c.appearance.items.iter().find_map(|i| match i {
|
||||
AppearanceItem::Fill(f) => match &f.paint {
|
||||
Paint::Gradient(g) => g.gradient.stops.first().map(|s| s.color.to_rgb()),
|
||||
_ => None,
|
||||
},
|
||||
AppearanceItem::Stroke(_) => None,
|
||||
});
|
||||
if let (Some(rgb), Some(bounds)) = (first_stop, c.path_data().and_then(PathData::bounds)) {
|
||||
drawn.push((if rgb[0] > rgb[2] { "fill" } else { "stroke" }, bounds));
|
||||
}
|
||||
});
|
||||
let graphic = drawn.iter().position(|(kind, _)| *kind == "graphic").unwrap();
|
||||
let covering = |(kind, b): &(&str, Rect)| *kind == "stroke" && b.intersect(drawn[graphic].1).area() > 0.0;
|
||||
assert!(drawn[graphic..].iter().any(covering), "a dash on the cap's edge is drawn over the fill's graphic");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cap_with_a_hole_keeps_the_hole_out_of_the_graphic() {
|
||||
let d = document();
|
||||
@@ -692,3 +799,72 @@ fn a_symbol_instance_in_a_graphic_draws_as_the_canvas_shows_it() {
|
||||
let area: f64 = pieces.iter().map(|p| p.path.to_bezpath().area().abs()).sum();
|
||||
assert!((area - 30_000.0).abs() < 1e-3, "{area}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curves_are_cut_one_at_a_time_and_the_work_stops_at_the_limit() {
|
||||
let ellipse = shapes::ellipse(Rect::new(0.0, 0.0, 10.0, 6.0)).to_bezpath();
|
||||
// Cut curve by curve, a path gives the points it gives cut whole.
|
||||
for scale in [1.0, 100.0, 10_000.0] {
|
||||
let placed = Affine::scale(scale) * ellipse.clone();
|
||||
let mut whole = vec![];
|
||||
vectorcraft_geom::kurbo::flatten(placed.iter(), SURFACE_TOLERANCE, |el| {
|
||||
if let PathEl::MoveTo(p) | PathEl::LineTo(p) = el {
|
||||
whole.push(p);
|
||||
}
|
||||
});
|
||||
let mut points = 0;
|
||||
let cut: Vec<Point> = straight_pieces(&placed, &mut points).unwrap().into_iter().flatten().collect();
|
||||
assert_eq!(points, cut.len());
|
||||
assert_eq!(cut.len(), whole.len(), "{scale}");
|
||||
assert!(cut.iter().zip(&whole).all(|(a, b)| a.distance(*b) < 1e-9), "{scale}");
|
||||
}
|
||||
// Past the limit no further curve is cut: of 1,000 ellipses that each take more than 3,000
|
||||
// points, the count stops within one curve of the limit.
|
||||
let mut many = BezPath::new();
|
||||
(0..1000).for_each(|_| many.extend(Affine::scale(10_000.0) * ellipse.clone()));
|
||||
let mut points = 0;
|
||||
assert!(straight_pieces(&many, &mut points).is_none());
|
||||
assert!(points > MAX_ELEMENTS && points < MAX_ELEMENTS + 2000, "{points}");
|
||||
// A curve that reaches farther than any surface, or to no finite point, is not cut at all.
|
||||
for scale in [1e12, f64::INFINITY] {
|
||||
let mut points = 0;
|
||||
assert!(straight_pieces(&(Affine::scale(scale) * ellipse.clone()), &mut points).is_none());
|
||||
assert!(points <= 1, "{scale}: {points}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_that_reaches_farther_than_any_surface_is_not_cut() {
|
||||
let triangle = |far: f64| {
|
||||
let mut b = BezPath::new();
|
||||
b.move_to((0.0, 0.0));
|
||||
b.line_to((far, 0.0));
|
||||
b.line_to((0.0, 1.0));
|
||||
b.close_path();
|
||||
b
|
||||
};
|
||||
assert!(straight_pieces(&triangle(1e7), &mut 0).is_some());
|
||||
for far in [1e12, 1e300] {
|
||||
assert!(straight_pieces(&triangle(far), &mut 0).is_none(), "{far}");
|
||||
assert!(straight_pieces(&(Affine::translate((far, 0.0)) * triangle(1.0)), &mut 0).is_none(), "{far}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_an_opaque_part_on_revolve_takes_a_seam_stroke() {
|
||||
let piece = |paint: Paint, opacity: f32, blend: BlendMode| Unrolled {
|
||||
polygons: vec![],
|
||||
boxes: vec![],
|
||||
bounds: Rect::ZERO,
|
||||
rule: FillRule::NonZero,
|
||||
paint,
|
||||
opacity,
|
||||
blend,
|
||||
place: Affine::IDENTITY,
|
||||
};
|
||||
assert!(takes_seam(&piece(Paint::solid(red()), 1.0, BlendMode::Normal)));
|
||||
assert!(!takes_seam(&piece(Paint::solid(red()), 0.5, BlendMode::Normal)));
|
||||
assert!(!takes_seam(&piece(Paint::solid(red()), 1.0, BlendMode::Multiply)));
|
||||
// A pattern's tile may hold transparent art, which the overlap would show.
|
||||
assert!(!takes_seam(&piece(Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }, 1.0, BlendMode::Normal)));
|
||||
}
|
||||
@@ -59,6 +59,20 @@ fn the_meshes_of_one_object_share_one_triangle_budget() {
|
||||
assert!(meshes_for(effect, &shapes, &mut total, MAX_MESH_TRIANGLES).is_err_and(|e| e.contains("too complex")));
|
||||
}
|
||||
|
||||
/// A mesh past the budget stops the export before the solids after it are built.
|
||||
#[test]
|
||||
fn the_solids_after_a_mesh_past_the_budget_are_not_built() {
|
||||
let mut n = square_node(1, 100.0);
|
||||
n.appearance.effects.push(fx(EXTRUDE, json!({})));
|
||||
let first = three_d_meshes(&n).unwrap()[0].mesh.triangles.len();
|
||||
let shapes = [Profile { path: profile(&n).unwrap().0, rule: FillRule::NonZero, items: solid_paints(&n), opacity: 1.0, scopes: vec![] }];
|
||||
let Some(effect) = n.appearance.effects.first() else { panic!("no effect") };
|
||||
let mut total = MAX_MESH_TRIANGLES - first + 1;
|
||||
SOLIDS_BUILT.with(|b| b.set(0));
|
||||
assert!(meshes_for(effect, &shapes, &mut total, MAX_MESH_TRIANGLES).is_err_and(|e| e.contains("too complex")));
|
||||
assert_eq!(SOLIDS_BUILT.with(std::cell::Cell::get), 1, "the stroke's solid is never built");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revolve_stops_at_the_first_mesh_past_the_budget() {
|
||||
// The fill revolves into a mesh; the stroke's profile, copied 1000 times, is too complex to
|
||||
@@ -109,6 +123,22 @@ fn an_extruded_mesh_is_as_deep_as_the_effect() {
|
||||
assert!((hi[2] - lo[2] - 30.0).abs() < 1e-9 && (hi[0] - lo[0] - 100.0).abs() < 1e-9, "{lo:?} {hi:?}");
|
||||
}
|
||||
|
||||
/// Extrude & Bevel (Classic) exports the solid it draws: its bevel as wide as it is high.
|
||||
#[test]
|
||||
fn a_classic_extrusion_exports_its_own_bevel() {
|
||||
let mut n = square_node(1, 100.0);
|
||||
n.appearance.items.truncate(1);
|
||||
let params = json!({ "bevel": "classic", "bevelHeight": 10.0 });
|
||||
n.appearance.effects.push(fx(CLASSIC_EXTRUDE, params.clone()));
|
||||
let meshes = three_d_meshes(&n).unwrap();
|
||||
let p = crate::merged_params(CLASSIC_EXTRUDE, ¶ms);
|
||||
let path = profile(&n).unwrap().0;
|
||||
let bounds = path.bounds().unwrap();
|
||||
let own = vectorcraft_three_d::extrude_mesh(&path, FillRule::NonZero, bounds, classic_extrude_options(&p), view_options(&p)).unwrap();
|
||||
assert_eq!(meshes.len(), 1);
|
||||
assert_eq!(meshes[0].mesh, own);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revolve_gives_a_mesh_in_the_top_fill() {
|
||||
let mut b = BezPath::new();
|
||||
|
||||
@@ -4,13 +4,13 @@ use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_doc::color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeId};
|
||||
use vectorcraft_doc::{Appearance, Document, Effect, Node, NodeId};
|
||||
use vectorcraft_geom::{Anchor, CubicBez, PathData, Point, SubPath};
|
||||
use vectorcraft_three_d::Facet;
|
||||
|
||||
use super::{
|
||||
INFLATE, Profile, ROTATE, facets, geometry, has_solid, inflate_options, is_container, is_plane, is_three_d, label_of, members, object_profile,
|
||||
region, reshape_members, resolve, resolve_for, solid, solid_paints, solid_parts, union_bounds, view_options,
|
||||
Profile, ROTATE, built_solids, facets, geometry, has_solid, is_container, is_plane, is_three_d, label_of, members, object_profile, region,
|
||||
reshape_members, resolve, resolve_for, solid, solid_paints, solid_parts, union_bounds,
|
||||
};
|
||||
use crate::{GeomContext, is_geometry};
|
||||
|
||||
@@ -125,7 +125,8 @@ fn solid_face_paths(doc: Option<&Document>, n: &Node) -> Result<Vec<PathData>, S
|
||||
/// The outlines of the facets effect `fx` builds from `shapes`, as `art_for` builds them: Rotate and
|
||||
/// Rotate (Classic) turn every fill and stroke; Extrude & Bevel and Inflate build a solid from each shape's
|
||||
/// top fill and from the outline of each stroke. A stroke whose solid is past the limits is left out,
|
||||
/// as it is left out of the drawn art.
|
||||
/// as it is left out of the drawn art; past the limits of the object's solids together, the result
|
||||
/// is an error, as the canvas draws the source art.
|
||||
fn facet_paths(fx: &Effect, shapes: &[Profile]) -> Result<Vec<PathData>, String> {
|
||||
let label = label_of(&fx.id);
|
||||
let b = union_bounds(shapes).ok_or_else(|| format!("{label} requires a shape with at least two anchors"))?;
|
||||
@@ -141,18 +142,9 @@ fn facet_paths(fx: &Effect, shapes: &[Profile]) -> Result<Vec<PathData>, String>
|
||||
return Ok(out);
|
||||
}
|
||||
let (parts, bounds) = solid_parts(shapes, b);
|
||||
let built: Vec<Result<Vec<Facet>, String>> = if fx.id == INFLATE {
|
||||
let shapes: Vec<(&PathData, vectorcraft_geom::FillRule)> = parts.iter().map(|(_, _, area, rule, ..)| (area, *rule)).collect();
|
||||
vectorcraft_three_d::inflate_together(&shapes, bounds, inflate_options(&p), view_options(&p))
|
||||
} else {
|
||||
parts.iter().map(|(_, _, area, rule, ..)| facets(&fx.id, area, *rule, bounds, &p)).collect()
|
||||
};
|
||||
for ((item, ..), f) in parts.iter().zip(built) {
|
||||
match f {
|
||||
Ok(f) => out.extend(f.iter().map(Facet::path)),
|
||||
Err(_) if matches!(item, AppearanceItem::Stroke(_)) => {}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
// The solids the art draws, each past the limits of the object's solids together as it is.
|
||||
for f in built_solids(&fx.id, &p, &parts, bounds, vectorcraft_three_d::MAX_OBJECT_FACES) {
|
||||
out.extend(f?.iter().flatten().map(Facet::path));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Node, NodeId};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Node, NodeId};
|
||||
use vectorcraft_geom::{BezPath, Rect};
|
||||
|
||||
use super::*;
|
||||
|
||||
@@ -5,6 +5,7 @@ use vectorcraft_geom::{Affine, PathData, Point, Rect, Shape, SubPath, shapes};
|
||||
use super::*;
|
||||
|
||||
mod imageoutline;
|
||||
mod painted;
|
||||
mod rasterfollow;
|
||||
mod scale;
|
||||
mod transformfx;
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
//! Live-effect plug-ins that paint what they return, run on each fill a painted effect returned.
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Effect, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Anchor, PathData, Point, Rect, SubPath, shapes};
|
||||
use vectorcraft_plugins::wat as tpl;
|
||||
|
||||
use crate::geometry::Budget;
|
||||
use crate::reshape;
|
||||
use crate::reshape::{HELD_PEAK, PLUGIN_RUNS};
|
||||
|
||||
/// Installs live-effect plug-in `id`, which paints what it returns, replacing one with the same id:
|
||||
/// its effect returns `output` whatever it is given.
|
||||
fn install_painting(id: &str, output: &serde_json::Value) {
|
||||
let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"effect","api":2,"paintOutput":true,"params":{{}}}}"#);
|
||||
let module = wat::parse_str(tpl::returning(&manifest, &output.to_string())).unwrap();
|
||||
vectorcraft_plugins::registry::install_bytes(&module).unwrap();
|
||||
}
|
||||
|
||||
/// An open path of `curves` tall curves, each drawn with about 5,200 lines.
|
||||
fn tall_curves(curves: u32) -> PathData {
|
||||
let h = 3_000_000.0;
|
||||
let anchors = (0..=curves)
|
||||
.map(|i| {
|
||||
let x = 40.0 + f64::from(i);
|
||||
Anchor::with_handles(Point::new(x, 0.0), Point::new(x, -h), Point::new(x, h))
|
||||
})
|
||||
.collect();
|
||||
PathData::single(SubPath::new(anchors, false))
|
||||
}
|
||||
|
||||
/// Installs live-effect plug-in `id`, which reshapes the path it is given: its effect returns
|
||||
/// `output` whatever it is given.
|
||||
fn install_reshaping(id: &str, output: &serde_json::Value) {
|
||||
let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"effect","params":{{}}}}"#);
|
||||
let module = wat::parse_str(tpl::returning(&manifest, &output.to_string())).unwrap();
|
||||
vectorcraft_plugins::registry::install_bytes(&module).unwrap();
|
||||
}
|
||||
|
||||
/// `curves` curves from `x`, each `h` tall at its handles.
|
||||
fn curves_at(x: f64, curves: u32, h: f64) -> SubPath {
|
||||
let anchors = (0..=curves)
|
||||
.map(|i| {
|
||||
let x = x + f64::from(i);
|
||||
Anchor::with_handles(Point::new(x, 0.0), Point::new(x, -h), Point::new(x, h))
|
||||
})
|
||||
.collect();
|
||||
SubPath::new(anchors, false)
|
||||
}
|
||||
|
||||
/// An open path, `dx` to the right of 40, drawn with about `lines` lines: tall curves and one
|
||||
/// curve that makes up the rest.
|
||||
fn drawn_with(lines: usize, dx: f64) -> PathData {
|
||||
let h = 3_000_000.0;
|
||||
let per = Budget::of(&PathData::single(curves_at(0.0, 1, h))).lines;
|
||||
let tall = u32::try_from(lines / per).unwrap();
|
||||
let rest = lines % per;
|
||||
let mut subpaths = vec![curves_at(40.0 + dx, tall, h)];
|
||||
if rest > 0 {
|
||||
// A curve `h` tall at its handles is drawn with about √(9h) lines.
|
||||
let rest = rest as f64;
|
||||
subpaths.push(curves_at(40.0 + dx + f64::from(tall) + 2.0, 1, rest * rest / 9.0));
|
||||
}
|
||||
PathData::new(subpaths)
|
||||
}
|
||||
|
||||
/// Stacks a painted effect that returns `first` on a path drawn with about `lines` lines with five
|
||||
/// later effects on a square's fill, the `k`th returning that path `k` to the right (`later`
|
||||
/// installs each). Each piece's share of the budget is counted once, so every effect fits, and the
|
||||
/// art ends on the last effect's path, painted by `paints`.
|
||||
fn later_effects_count_each_piece_once(name: &str, lines: usize, first: &serde_json::Value, later: fn(&str, &serde_json::Value), paints: &[Paint]) {
|
||||
let near = drawn_with(lines, 0.0);
|
||||
let drawn = Budget::of(&near).lines;
|
||||
assert!(drawn.abs_diff(lines) <= 2, "the path is drawn with {drawn} lines");
|
||||
let first_id = format!("test.effects.{name}.first");
|
||||
let mut first = first.clone();
|
||||
first["objects"][0]["path"] = serde_json::to_value(&near).unwrap();
|
||||
install_painting(&first_id, &first);
|
||||
let mut ids = vec![format!("plugin.{first_id}")];
|
||||
for k in 1..=5u8 {
|
||||
let id = format!("test.effects.{name}.later{k}");
|
||||
later(&id, &json!({"objects": [{"path": drawn_with(lines, f64::from(k))}]}));
|
||||
ids.push(format!("plugin.{id}"));
|
||||
}
|
||||
let mut n =
|
||||
Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
|
||||
let fill = n.appearance.items.iter().position(|i| i.is_fill()).unwrap();
|
||||
for id in ids {
|
||||
n.appearance.items[fill].effects_mut().push(Effect { id, params: json!({}), visible: true });
|
||||
}
|
||||
let art = reshape(None, &n, None).unwrap();
|
||||
let mut paths = vec![];
|
||||
// The path is a compound path of two (the tall curves and the one that makes up the rest).
|
||||
art.walk(&mut |c| {
|
||||
let bounds = match &c.kind {
|
||||
NodeKind::Compound { children, .. } => children.iter().filter_map(|k| k.path_data().and_then(PathData::bounds)).reduce(|a, b| a.union(b)),
|
||||
_ => c.path_data().and_then(PathData::bounds),
|
||||
};
|
||||
let paints: Vec<Paint> = c.appearance.items.iter().map(|i| i.paint().clone()).filter(|p| !p.is_none()).collect();
|
||||
if bounds.is_some() && !paints.is_empty() {
|
||||
paths.push((bounds, paints));
|
||||
}
|
||||
});
|
||||
assert_eq!(paths, [(drawn_with(lines, 5.0).bounds(), paints.to_vec())]);
|
||||
}
|
||||
|
||||
/// Later geometry effects on the two fills a painted effect returned run on each fill, and the
|
||||
/// path they both stay on counts its piece's share of the budget once: each fill's result, drawn
|
||||
/// with about 200 lines fewer than half the budget allows, fits at every stage.
|
||||
#[test]
|
||||
fn later_geometry_effects_on_two_fills_count_the_piece_once() {
|
||||
let colors = [Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 1.0, 0.0))];
|
||||
let fills: Vec<_> = colors.iter().map(|p| serde_json::to_value(p).unwrap()).collect();
|
||||
let lines = Budget::EFFECTS.lines / 2 - 200;
|
||||
later_effects_count_each_piece_once("twofills", lines, &json!({"objects": [{"fills": fills}]}), install_reshaping, &colors);
|
||||
}
|
||||
|
||||
/// Later painted effects on a painted effect's piece count the piece's share of the budget once:
|
||||
/// each run's pieces take the place of the piece they were made of, so a result drawn with about
|
||||
/// 300 lines fewer than the budget allows fits at every stage.
|
||||
#[test]
|
||||
fn later_painted_effects_on_a_painted_piece_count_it_once() {
|
||||
let lines = Budget::EFFECTS.lines - 300;
|
||||
later_effects_count_each_piece_once("painted", lines, &json!({"objects": [{}]}), install_painting, &[Paint::solid(Color::BLACK)]);
|
||||
}
|
||||
|
||||
/// A path's bounds and the paints of its fills and strokes.
|
||||
type PaintedPath = (Option<Rect>, Vec<Paint>);
|
||||
|
||||
/// The paths of the art a painted effect `name` that returns `square` with eight fills makes, each
|
||||
/// path with its paints, when a later effect returns `first` on the first fill and `rest` on the
|
||||
/// others, painting what it returns when `paints`; and the eight paints. Checks that the plug-in
|
||||
/// results kept from one fill to the next never cost more than the effects' budget together.
|
||||
fn eight_fills_then(name: &str, square: &PathData, paints: bool, results: (&PathData, &PathData)) -> (Vec<PaintedPath>, Vec<Paint>) {
|
||||
let (paths, colors, _) = fills_then(name, 8, square, paints, results);
|
||||
(paths, colors)
|
||||
}
|
||||
|
||||
/// [`eight_fills_then`] with `n` fills, and how many times the later effect ran on a fill.
|
||||
fn fills_then(name: &str, n: u8, square: &PathData, paints: bool, (first, rest): (&PathData, &PathData)) -> (Vec<PaintedPath>, Vec<Paint>, usize) {
|
||||
let colors: Vec<Paint> = (0..n).map(|i| Paint::solid(Color::rgb(f32::from(i) / f32::from(n), 0.0, 0.0))).collect();
|
||||
let fills: Vec<_> = colors.iter().map(|p| serde_json::to_value(p).unwrap()).collect();
|
||||
let fills_id = format!("test.effects.{name}.fills");
|
||||
install_painting(&fills_id, &json!({"objects": [{"path": square, "fills": fills}]}));
|
||||
let each_id = format!("test.effects.{name}.each");
|
||||
let declared = if paints { r#","api":2,"paintOutput":true"# } else { "" };
|
||||
let manifest = format!(r#"{{"id":"{each_id}","name":"Test {each_id}","version":"1","kind":"effect"{declared},"params":{{}}}}"#);
|
||||
let (on_first, on_rest) = (json!({"objects": [{"path": first}]}).to_string(), json!({"objects": [{"path": rest}]}).to_string());
|
||||
let module = wat::parse_str(tpl::when_given_else(&manifest, tpl::Given::Params, r#""item":{"fill":0}"#, &on_first, &on_rest)).unwrap();
|
||||
vectorcraft_plugins::registry::install_bytes(&module).unwrap();
|
||||
let mut n =
|
||||
Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
|
||||
let fill = n.appearance.items.iter().position(|i| i.is_fill()).unwrap();
|
||||
for id in [fills_id, each_id] {
|
||||
n.appearance.items[fill].effects_mut().push(Effect { id: format!("plugin.{id}"), params: json!({}), visible: true });
|
||||
}
|
||||
HELD_PEAK.with(|p| p.set(Budget { anchors: 0, lines: 0 }));
|
||||
PLUGIN_RUNS.with(|r| r.set(0));
|
||||
let art = reshape(None, &n, None).unwrap();
|
||||
let runs = PLUGIN_RUNS.with(std::cell::Cell::get);
|
||||
let mut paths = vec![];
|
||||
art.walk(&mut |c| {
|
||||
if let Some(p) = c.path_data() {
|
||||
let paints: Vec<Paint> = c.appearance.items.iter().map(|i| i.paint().clone()).filter(|p| !p.is_none()).collect();
|
||||
if !paints.is_empty() {
|
||||
paths.push((p.bounds(), paints));
|
||||
}
|
||||
}
|
||||
});
|
||||
let peak = HELD_PEAK.with(std::cell::Cell::get);
|
||||
assert!(Budget::EFFECTS.fits(peak), "the results kept cost {peak:?}");
|
||||
(paths, colors, runs)
|
||||
}
|
||||
|
||||
/// A later painted effect's results on eight fills, each costing more than half the effects'
|
||||
/// budget and the first fill's on another path than the rest: only the first fill's result fits,
|
||||
/// the other fills stay together on the square, and the results kept never cost more than the
|
||||
/// budget together.
|
||||
#[test]
|
||||
fn painted_results_that_do_not_fit_are_not_kept() {
|
||||
let square = shapes::rectangle(Rect::new(40.0, 40.0, 60.0, 60.0));
|
||||
let (large, other) = (tall_curves(900), PathData::single(curves_at(3_000.0, 900, 3_000_000.0)));
|
||||
let (paths, colors) = eight_fills_then("held", &square, true, (&large, &other));
|
||||
assert_eq!(paths, [(large.bounds(), colors[..1].to_vec()), (square.bounds(), colors[1..].to_vec())]);
|
||||
}
|
||||
|
||||
/// A later effect that reshapes each of eight painted fills to the same path, drawn with about a
|
||||
/// fifth of the effects' budget: the fills share that one path, and the results that move onto it
|
||||
/// are not kept as well, so what is kept never costs more than the budget.
|
||||
#[test]
|
||||
fn results_on_one_path_are_not_kept_for_each_fill() {
|
||||
let square = shapes::rectangle(Rect::new(40.0, 40.0, 60.0, 60.0));
|
||||
let same = tall_curves(300);
|
||||
let (paths, colors) = eight_fills_then("merged", &square, false, (&same, &same));
|
||||
assert_eq!(paths, [(same.bounds(), colors)]);
|
||||
}
|
||||
|
||||
/// A later effect that reshapes each of eight painted fills to the same path, drawn with more than
|
||||
/// half the effects' budget: the path costs the art once, so every fill moves onto it, although a
|
||||
/// second copy of it would not fit.
|
||||
#[test]
|
||||
fn results_on_one_path_share_it_near_the_budget() {
|
||||
let square = shapes::rectangle(Rect::new(40.0, 40.0, 60.0, 60.0));
|
||||
let large = tall_curves(900);
|
||||
let (paths, colors) = eight_fills_then("shared", &square, false, (&large, &large));
|
||||
assert_eq!(paths, [(large.bounds(), colors)]);
|
||||
}
|
||||
|
||||
/// An open path of tall curves `dx` to the right of 40, drawn with about `share` of the effects'
|
||||
/// budget's lines.
|
||||
fn drawn_share(share: f64, dx: f64) -> PathData {
|
||||
let h = 3_000_000.0;
|
||||
let per = Budget::of(&PathData::single(curves_at(0.0, 1, h))).lines as f64;
|
||||
let curves = (Budget::EFFECTS.lines as f64 * share / per) as u32;
|
||||
PathData::single(curves_at(40.0 + dx, curves, h))
|
||||
}
|
||||
|
||||
/// A later painted effect runs once on each of three fills although the results are placed twice:
|
||||
/// a result that fits both placings is kept between them, and one that did not fit in the first is
|
||||
/// not run again when it does not fit the second either. The first fill's result (a tenth of the
|
||||
/// budget) and the second's (half of it) fit, the third's (half of it) does not, and the square
|
||||
/// (45%) left for the third fill then has no room; in the second placing the second fill's result
|
||||
/// does not fit beside the square kept for the fills after it.
|
||||
#[test]
|
||||
fn a_later_plug_in_runs_once_on_each_fill_across_both_placings() {
|
||||
let (square, first, rest) = (drawn_share(0.45, 0.0), drawn_share(0.1, 2_000.0), drawn_share(0.5, 4_000.0));
|
||||
let (paths, colors, runs) = fills_then("once", 3, &square, true, (&first, &rest));
|
||||
assert_eq!(paths, [(first.bounds(), colors[..1].to_vec()), (square.bounds(), colors[1..].to_vec())]);
|
||||
assert_eq!(runs, 3, "the later effect ran {runs} times on three fills");
|
||||
}
|
||||
|
||||
/// A built-in geometry effect on two strokes that a painted effect returned, which doubles the lines
|
||||
/// of a path drawn with 30% of the budget: the second stroke's result does not fit beside the
|
||||
/// first's, but it is the same path, so it is built again with all the room the art leaves and
|
||||
/// both strokes are drawn on that one path.
|
||||
#[test]
|
||||
fn a_built_in_result_on_the_path_before_it_is_taken_near_the_budget() {
|
||||
let square = drawn_share(0.3, 0.0);
|
||||
let transform = json!({"scaleV": 400});
|
||||
let tall = crate::distort::transform_within(&square, square.bounds().unwrap(), &transform, 0, usize::MAX);
|
||||
let (s, t) = (Budget::of(&square).lines, Budget::of(&tall).lines);
|
||||
let lines = Budget::EFFECTS.lines;
|
||||
assert!(t > lines / 2 + lines / 20 && t < lines - lines / 20 && s + t < lines, "the paths are drawn with {s} and {t} lines");
|
||||
let colors = [Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 1.0, 0.0))];
|
||||
let strokes: Vec<_> = colors.iter().map(|p| json!({"paint": p, "width": 1})).collect();
|
||||
let id = "test.effects.builtin.strokes";
|
||||
install_painting(id, &json!({"objects": [{"path": square, "strokes": strokes}]}));
|
||||
let mut n =
|
||||
Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0));
|
||||
let stroke = n.appearance.items.iter().position(|i| !i.is_fill()).unwrap();
|
||||
n.appearance.items[stroke].effects_mut().push(Effect { id: format!("plugin.{id}"), params: json!({}), visible: true });
|
||||
n.appearance.items[stroke].effects_mut().push(Effect { id: "distort.transform".into(), params: transform, visible: true });
|
||||
let art = reshape(None, &n, None).unwrap();
|
||||
let mut paths = vec![];
|
||||
art.walk(&mut |c| {
|
||||
if let Some(p) = c.path_data() {
|
||||
let paints: Vec<Paint> = c.appearance.items.iter().map(|i| i.paint().clone()).filter(|p| !p.is_none()).collect();
|
||||
if !paints.is_empty() {
|
||||
paths.push((p.bounds(), paints));
|
||||
}
|
||||
}
|
||||
});
|
||||
// One path, scaled about a reference point of the piece's own, painted by both strokes.
|
||||
assert_eq!(paths.len(), 1, "{paths:?}");
|
||||
let (bounds, paints) = &paths[0];
|
||||
assert_eq!(paints, &colors.to_vec());
|
||||
let height = |b: Option<Rect>| b.map_or(0.0, |b| b.height());
|
||||
assert!((height(*bounds) - height(tall.bounds())).abs() < 1.0, "{bounds:?} is not {:?} tall", tall.bounds());
|
||||
}
|
||||
@@ -523,11 +523,12 @@ fn a_groups_transform_applies_after_its_members_own() {
|
||||
let mut on_fill = fill_square(33, vec![shadow(10.0, 0.0, 0.0)]);
|
||||
on_fill.appearance.effects = vec![turn()];
|
||||
let art = crate::evaluate_container(None, &group(32, vec![on_fill], vec![uneven()])).unwrap();
|
||||
assert!(near(&[fill_shadow(&node_in(&art, 33))], &[want]), "fill: {:?}", fill_shadow(&node_in(&art, 33)));
|
||||
// The member is drawn as its art: a group with its id holding the turned square.
|
||||
let filled = node_in(&art, 33).children().and_then(|ch| ch.first().map(|c| (**c).clone())).unwrap();
|
||||
assert!(near(&[fill_shadow(&filled)], &[want]), "fill: {:?}", fill_shadow(&filled));
|
||||
let nested = group(34, vec![group(35, vec![square(36, vec![shadow(10.0, 0.0, 0.0)])], vec![turn()])], vec![uneven()]);
|
||||
let art = crate::evaluate_container(None, &nested).unwrap();
|
||||
let inner = crate::evaluate_container(None, &node_in(&art, 35)).unwrap();
|
||||
assert!(near(&shadows_in(&inner), &[want]), "nested: {:?}", shadows_in(&inner));
|
||||
assert!(near(&shadows_in(&art), &[want]), "nested: {:?}", shadows_in(&art));
|
||||
}
|
||||
|
||||
/// An object's Transform effect transforms the raster effects of its fills and strokes with the
|
||||
@@ -645,7 +646,8 @@ fn a_groups_transform_moves_its_members_fills_shadows_beside_their_own_transform
|
||||
let art = crate::evaluate_container(None, &g).unwrap();
|
||||
for (id, _, want) in &cases {
|
||||
let member = node_in(&art, *id);
|
||||
let drawn = shadows_in(&crate::reshape(None, &member, None).unwrap());
|
||||
// The member is drawn as its art, its fill's own Transform effect applied.
|
||||
let drawn = shadows_in(&member);
|
||||
assert!(!drawn.is_empty() && near(&drawn, &vec![*want; drawn.len()]), "Scale Strokes & Effects {strokes}: {id} {drawn:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -245,6 +245,12 @@ pub fn has_selected_member(s: &Session) -> std::result::Result<(), String> {
|
||||
let Some(root) = ordinary_isolation(st) else { return has_selection(s) };
|
||||
if st.selection.objects.iter().any(|id| inside_isolation(&st.doc, root, *id)) { Ok(()) } else { Err("nothing selected".into()) }
|
||||
}
|
||||
/// [`has_selected_member`], or a ruler guide is selected outside isolation mode: Object › Lock ›
|
||||
/// Selection and Object › Hide › Selection.
|
||||
pub fn has_selected_member_or_guide(s: &Session) -> std::result::Result<(), String> {
|
||||
let st = s.active().ok_or("no document open")?;
|
||||
if ordinary_isolation(st).is_none() && !st.selection.guides.is_empty() { Ok(()) } else { has_selected_member(s) }
|
||||
}
|
||||
/// Whether `id` lies inside the isolated object `root` (the root itself does not).
|
||||
pub(crate) fn inside_isolation(d: &vectorcraft_doc::Document, root: vectorcraft_doc::NodeId, id: vectorcraft_doc::NodeId) -> bool {
|
||||
id != root && d.ancestry(id).is_some_and(|a| a.contains(&root))
|
||||
@@ -506,8 +512,13 @@ fn id_entry(value: &Value, key: &str, index: usize, cmd: &str) -> Result<NodeId>
|
||||
/// them), each checked ([`checked_id`]): a malformed one, or one naming no object, is an error,
|
||||
/// never the selection. `None` when it gives neither (or gives them as `null`).
|
||||
pub(crate) fn given_objects(s: &Session, p: &Value, command: &str) -> Result<Option<Vec<NodeId>>> {
|
||||
given_nodes(s, p, command, false)
|
||||
}
|
||||
/// The nodes `p` gives `command`, as [`given_objects`] reads them; ruler guide nodes are taken
|
||||
/// too when `guides`, else refused.
|
||||
pub(crate) fn given_nodes(s: &Session, p: &Value, command: &str, guides: bool) -> Result<Option<Vec<NodeId>>> {
|
||||
if p.get("ids").is_some_and(|v| !v.is_null()) {
|
||||
return checked_ids_param(s, p, "ids", command).map(Some);
|
||||
return checked_nodes_param(s, p, "ids", command, guides).map(Some);
|
||||
}
|
||||
match p.get("id").filter(|v| !v.is_null()) {
|
||||
None => Ok(None),
|
||||
@@ -515,7 +526,7 @@ pub(crate) fn given_objects(s: &Session, p: &Value, command: &str) -> Result<Opt
|
||||
Some(Value::String(r)) if r.starts_with('$') => {
|
||||
Err(bad(command, format!("`id` is the step reference {r:?}, which only `run` and `command_batch` resolve")))
|
||||
}
|
||||
Some(v) => Ok(Some(vec![checked_id(s, v, command)?])),
|
||||
Some(v) => Ok(Some(vec![checked_node(s, v, command, guides)?])),
|
||||
}
|
||||
}
|
||||
/// The objects `p` gives `command`, as [`given_objects`] reads them, checked only for their form:
|
||||
@@ -541,9 +552,18 @@ pub(crate) fn index(v: u64) -> usize {
|
||||
}
|
||||
/// Validate all explicit targets before a command changes the document or selection.
|
||||
pub(crate) fn checked_ids_param(s: &Session, p: &Value, key: &str, command: &str) -> Result<Vec<NodeId>> {
|
||||
checked_nodes_param(s, p, key, command, false)
|
||||
}
|
||||
/// The `key` list as [`checked_ids_param`] checks it; ruler guide nodes are taken too when
|
||||
/// `guides`, else refused.
|
||||
pub(crate) fn checked_nodes_param(s: &Session, p: &Value, key: &str, command: &str, guides: bool) -> Result<Vec<NodeId>> {
|
||||
let values =
|
||||
p.get(key).and_then(Value::as_array).ok_or_else(|| bad(command, format!("{key} must be an array of non-negative integer object ids")))?;
|
||||
values.iter().enumerate().map(|(index, value)| id_entry(value, key, index, command).and_then(|_| checked_id(s, value, command))).collect()
|
||||
values
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, value)| id_entry(value, key, index, command).and_then(|_| checked_node(s, value, command, guides)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The objects a command acts on: `ids` when given (every one checked, and those inside another
|
||||
@@ -557,11 +577,16 @@ pub(crate) fn checked_ids_or_selection(s: &Session, p: &Value, command: &str) ->
|
||||
}
|
||||
|
||||
pub(crate) fn checked_id(s: &Session, value: &Value, command: &str) -> Result<NodeId> {
|
||||
checked_node(s, value, command, false)
|
||||
}
|
||||
/// `value` as the id of a node of the active document; a ruler guide's is taken only when
|
||||
/// `guides`.
|
||||
pub(crate) fn checked_node(s: &Session, value: &Value, command: &str, guides: bool) -> Result<NodeId> {
|
||||
let id = value.as_u64().map(NodeId).ok_or_else(|| bad(command, format!("invalid object id {value}: expected a non-negative integer")))?;
|
||||
match s.doc()?.doc.node(id) {
|
||||
None => Err(bad(command, format!("no such object id {value}"))),
|
||||
// The guide commands take ruler guides by index.
|
||||
Some(n) if n.is_ruler_guide() => Err(bad(command, format!("id {value} is a ruler guide, not an object"))),
|
||||
Some(n) if n.is_ruler_guide() && !guides => Err(bad(command, format!("id {value} is a ruler guide, not an object"))),
|
||||
Some(_) => Ok(id),
|
||||
}
|
||||
}
|
||||
@@ -778,6 +803,8 @@ pub(crate) fn unique_name_from(base: &str, next: &mut std::collections::HashMap<
|
||||
pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000;
|
||||
|
||||
pub(crate) use addons::{DecodedImages, refresh_color_masks};
|
||||
/// Document Info's category titles and the Objects category's count labels.
|
||||
pub use docinfo::{CATEGORIES, OBJECT_LABELS};
|
||||
pub use docmenu::guide_indexes;
|
||||
pub(crate) use edit::{settle_interaction, typing_in_progress};
|
||||
pub(crate) use object::bounds_rewrite;
|
||||
|
||||
@@ -341,6 +341,33 @@ fn fix_all_is_one_undo_step() {
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), doc.artboards.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_straight_run_loses_its_inner_anchors_in_one_step() {
|
||||
let mut s = session();
|
||||
let n: u32 = 5_000;
|
||||
let mut pts: Vec<(f64, f64)> = (0..n).map(|i| (10.0 + f64::from(i) * 0.05, 150.0)).collect();
|
||||
pts.push((260.0, 190.0));
|
||||
let id = line(&mut s, &pts);
|
||||
let other = rect(&mut s, 300.0, 20.0, 40.0, 40.0);
|
||||
select(&mut s, &[other]);
|
||||
let check = s.execute("addon.cleanup.check", &json!({"kinds": ["collinearAnchors"], "scope": "document"})).unwrap();
|
||||
assert_eq!(check["total"], n - 2, "{check}");
|
||||
assert_eq!(check["findings"][0]["ids"], json!([id.0]));
|
||||
let shown = s.execute("addon.cleanup.show", &json!({"kind": "collinearAnchors", "scope": "document"})).unwrap();
|
||||
assert_eq!(shown["count"], n - 2);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [id], "Show selects the path");
|
||||
select(&mut s, &[other]);
|
||||
let (steps, before) = (undo_steps(&s), node(&s, id).unwrap());
|
||||
let r = s.execute("addon.cleanup.fix", &json!({"kinds": ["collinearAnchors"], "scope": "document"})).unwrap();
|
||||
assert_eq!((r["total"].as_u64(), r["fixed"]["collinearAnchors"].as_u64()), (Some(u64::from(n) - 2), Some(u64::from(n) - 2)));
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [other], "Fix keeps the selection");
|
||||
let ends: Vec<(f64, f64)> = node(&s, id).unwrap().path_data().unwrap().subpaths[0].anchors.iter().map(|a| (a.p.x, a.p.y)).collect();
|
||||
assert_eq!(ends, [(10.0, 150.0), (10.0 + f64::from(n - 1) * 0.05, 150.0), (260.0, 190.0)]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(node(&s, id).unwrap(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_scope_is_the_selection_or_the_document() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -132,8 +132,10 @@ fn export_all_open(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let active = s.active;
|
||||
for i in 0..s.docs.len() {
|
||||
// Each document in turn is the one Save a Copy writes; switching tabs this way leaves every
|
||||
// document's tool and interaction alone, and the active one comes back below.
|
||||
// document's tool and interaction alone, and the active one comes back below. Its colors
|
||||
// are written through its own profiles.
|
||||
s.active = Some(i);
|
||||
s.sync_front_profiles();
|
||||
let Ok(st) = s.doc() else { continue };
|
||||
let title = st.doc.title.clone();
|
||||
let stem = fileio::file_stem(st.path.as_deref().unwrap_or(&title));
|
||||
@@ -160,6 +162,7 @@ fn export_all_open(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
s.active = active;
|
||||
s.sync_front_profiles();
|
||||
Ok(json!({ "files": files, "failed": failed, "format": format.id }))
|
||||
}
|
||||
|
||||
|
||||
@@ -19,7 +19,10 @@
|
||||
//! shape that a Convert to Shape or Outline Object effect on them gives them, below or above the
|
||||
//! image as its Contents row says; new ones go right below that row.
|
||||
|
||||
use std::{collections::HashMap, sync::Arc};
|
||||
use std::{
|
||||
collections::{HashMap, HashSet},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{BlendMode, Paint};
|
||||
@@ -45,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add New Fill",
|
||||
["Window", "Appearance"],
|
||||
Some("Cmd+/"),
|
||||
"{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
"{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
|s, p| add_item(s, p, true)
|
||||
),
|
||||
@@ -54,7 +57,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add New Stroke",
|
||||
["Window", "Appearance"],
|
||||
Some("Cmd+Alt+/"),
|
||||
"{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
"{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
|s, p| add_item(s, p, false)
|
||||
),
|
||||
@@ -63,7 +66,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Clear Appearance",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own) and reset its opacity and blend mode. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md)",
|
||||
"{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own) and reset its opacity and blend mode. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
clear_appearance
|
||||
),
|
||||
@@ -72,7 +75,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reduce to Basic Appearance",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
"{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
reduce_basic
|
||||
),
|
||||
@@ -81,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Appearance Item",
|
||||
[],
|
||||
None,
|
||||
"{index: paint-order item index, ids?|id? (default: the selection), target?: \"object\"|\"contents\", opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), tint?: 0..100, keepModel?: bool (both as paint.setFill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} edit one fill/stroke of each target object's own appearance stack. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
"{index: paint-order item index, ids?|id? (default: the selection), target?: \"object\"|\"contents\", opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), tint?: 0..100, keepModel?: bool (both as paint.setFill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} edit one fill/stroke of each target object's own appearance stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
set_item
|
||||
),
|
||||
@@ -90,7 +93,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Remove Item",
|
||||
[],
|
||||
None,
|
||||
"{index | indices: [..] (paint-order item indices), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} remove those fills/strokes from each target object's own stack. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
"{index | indices: [..] (paint-order item indices), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} remove those fills/strokes from each target object's own stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
remove_item
|
||||
),
|
||||
@@ -108,7 +111,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Duplicate Item",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{index | indices: [..] (paint-order item indices), to?: paint-order index of the copy (with several, of the lowest copy: they land together in their order; default: each right above its item; not with aligned rows of a mixed selection), contents?: count (with `to`: how many items paint below the Contents (Characters) row afterwards; default: it stays between the same items), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} copy fills/strokes with their effects, as Alt-dragging rows places them. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
"{index | indices: [..] (paint-order item indices), to?: paint-order index of the copy (with several, of the lowest copy: they land together in their order; default: each right above its item; not with aligned rows of a mixed selection), contents?: count (with `to`: how many items paint below the Contents (Characters) row afterwards; default: it stays between the same items), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} copy fills/strokes with their effects, as Alt-dragging rows places them. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
duplicate_item
|
||||
),
|
||||
@@ -117,7 +120,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reorder Appearance Item",
|
||||
[],
|
||||
None,
|
||||
"{from: paint-order item index | \"contents\", indices?: [..] (several items instead of from: they move as one block in their order, the lowest landing at `to`; a block landing next to the Contents row keeps its lowest item's side), to, contents?: count, ids?|id?, target?, aligned?: bool (refused when the targets' appearances differ)} move fill/stroke `from` to paint-order index `to`; on a group, layer or type the Contents (Characters) row stays between the same items (a moved item landing next to it keeps its side) unless `contents` says how many items paint below it afterwards. from \"contents\": move that row so `to` items paint below the members (characters) and the rest above. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md) → {index: where the item landed | contents: the row's slot}",
|
||||
"{from: paint-order item index | \"contents\", indices?: [..] (several items instead of from: they move as one block in their order, the lowest landing at `to`; a block landing next to the Contents row keeps its lowest item's side), to, contents?: count, ids?|id?, target?, aligned?: bool (refused when the targets' appearances differ)} move fill/stroke `from` to paint-order index `to`; on a group, layer or type the Contents (Characters) row stays between the same items (a moved item landing next to it keeps its side) unless `contents` says how many items paint below it afterwards. from \"contents\": move that row so `to` items paint below the members (characters) and the rest above. On a path directly in a graph series (a series group's id stands for those paths, except with from \"contents\", which moves the group's own row), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md) → {index: where the item landed | contents: the row's slot}",
|
||||
has_doc,
|
||||
move_item
|
||||
),
|
||||
@@ -144,7 +147,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Show All Hidden Attributes",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{ids?|id?, target?} make every hidden fill, stroke and effect (the object's and each item's) of each selected object visible again; errors when nothing is hidden. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md) → {ids}",
|
||||
"{ids?|id?, target?} make every hidden fill, stroke and effect (the object's and each item's) of each selected object visible again; errors when nothing is hidden. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md) → {ids}",
|
||||
has_doc,
|
||||
show_all_hidden
|
||||
),
|
||||
@@ -162,7 +165,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Appearance",
|
||||
[],
|
||||
None,
|
||||
"{source: id, target: id, copy?: bool} give `target` (a layer, group or object) the appearance (fills, strokes, effects) and transparency (opacity, blend mode, isolation, knockout) of `source`, as dragging a target circle onto another in the Layers panel does; the source is left with a cleared appearance (as appearance.clear) unless `copy` (Alt-drag). Opacity masks stay; placed gradients keep their place relative to each object's bounds. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md) → {source, target}",
|
||||
"{source: id, target: id, copy?: bool} give `target` (a layer, group or object) the appearance (fills, strokes, effects) and transparency (opacity, blend mode, isolation, knockout) of `source`, as dragging a target circle onto another in the Layers panel does; the source is left with a cleared appearance (as appearance.clear) unless `copy` (Alt-drag). Opacity masks stay; placed gradients keep their place relative to each object's bounds. On a path directly in a graph series (a series group's id stands for those paths; as `source`, when the group has no effect, opacity, blend mode, isolation, knockout or style link of its own, the topmost one is read and a move clears them all; as `target` each takes the appearance and the group is cleared, a `source` among them keeps its look, and a `source` that is the group's only path is an error), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md) → {source, target}",
|
||||
has_doc,
|
||||
transfer
|
||||
),
|
||||
@@ -416,9 +419,87 @@ pub(crate) fn appearance_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>>
|
||||
if targets_contents(p)? { leaf_targets(s, &roots) } else { Ok(roots) }
|
||||
}
|
||||
|
||||
/// [`appearance_targets`] of `cmd`, which needs at least one.
|
||||
fn require_targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
|
||||
/// `ids` with each graph series group that has no fill or stroke row of its own replaced by the paths directly inside
|
||||
/// it ([`super::graph::series_group_marks`]). A series group with rows, as a document saved earlier can hold, stays:
|
||||
/// the Appearance panel lists those rows and edits them by index.
|
||||
pub(crate) fn rowless_series_marks(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
super::graph::series_group_marks_where(d, ids, |group| group.appearance.items.is_empty())
|
||||
}
|
||||
|
||||
/// Whether series group `group` holds nothing of its own, as the graph draws it: no fill or stroke row, no effect, the
|
||||
/// default opacity, blend mode, isolation and knockout, and no graphic style link.
|
||||
fn holds_no_look(group: &Node) -> bool {
|
||||
let ap = &group.appearance;
|
||||
ap.items.is_empty()
|
||||
&& ap.effects.is_empty()
|
||||
&& group.opacity == 1.0
|
||||
&& group.blend == BlendMode::Normal
|
||||
&& !group.isolate
|
||||
&& group.knockout == Default::default()
|
||||
&& !group.knockout_shape
|
||||
&& group.extras().graphic_style.is_none()
|
||||
}
|
||||
|
||||
/// The objects whose appearance a command reads for `id`: a graph series group that holds nothing of its own
|
||||
/// ([`holds_no_look`]) gives the paths directly inside it, backmost first. A series group with an effect, an opacity or
|
||||
/// another attribute of its own is read itself, with that attribute.
|
||||
fn look_holders(d: &Document, id: NodeId) -> Vec<NodeId> {
|
||||
super::graph::series_group_marks_where(d, &[id], holds_no_look)
|
||||
}
|
||||
|
||||
/// The object whose appearance a command reads for `n`: a graph series group that holds nothing of its own stands for
|
||||
/// the topmost path directly inside it ([`look_holders`]).
|
||||
pub(crate) fn look_holder<'a>(d: &'a Document, n: &'a Node) -> &'a Node {
|
||||
look_holders(d, n.id).last().and_then(|id| d.node(*id)).unwrap_or(n)
|
||||
}
|
||||
|
||||
/// Objects whose fill and stroke rows a command edits: the [`appearance_targets`], with a graph series group standing
|
||||
/// for the paths directly inside it ([`rowless_series_marks`]), so the graph can store the edit.
|
||||
pub(crate) fn row_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
let ids = appearance_targets(s, p)?;
|
||||
Ok(rowless_series_marks(&s.doc()?.doc, &ids))
|
||||
}
|
||||
|
||||
/// Objects whose whole appearance a command edits: the [`row_targets`], then each graph series group they stand for,
|
||||
/// which can hold effects and a graphic style link of its own.
|
||||
pub(crate) fn whole_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
let own = appearance_targets(s, p)?;
|
||||
let mut ids = rowless_series_marks(&s.doc()?.doc, &own);
|
||||
let groups = stood_for(&own, &ids);
|
||||
ids.extend(groups);
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
/// The series groups among `own` that `ids` ([`rowless_series_marks`] of `own`) replaced with their paths.
|
||||
pub(crate) fn stood_for(own: &[NodeId], ids: &[NodeId]) -> Vec<NodeId> {
|
||||
let kept: HashSet<NodeId> = ids.iter().copied().collect();
|
||||
own.iter().copied().filter(|id| !kept.contains(id)).collect()
|
||||
}
|
||||
|
||||
/// Clear Appearance on each series group a command gave a whole new appearance through its paths, so the group's own
|
||||
/// opacity, blend mode, isolation, knockout, effects and style link do not stay on top of it.
|
||||
pub(crate) fn clear_stood_for(d: &mut Document, groups: &[NodeId]) {
|
||||
for id in groups {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
clear(n);
|
||||
(n.isolate, n.knockout, n.knockout_shape) = (false, Default::default(), false);
|
||||
n.extras_mut().graphic_style = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`whole_targets`] of `cmd`, which needs at least one.
|
||||
fn require_whole_targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
|
||||
let ids = whole_targets(s, p)?;
|
||||
if ids.is_empty() {
|
||||
return Err(bad(cmd, "select objects or give ids"));
|
||||
}
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
/// [`row_targets`] of `cmd`, which needs at least one.
|
||||
fn require_targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
|
||||
let ids = row_targets(s, p)?;
|
||||
if ids.is_empty() {
|
||||
return Err(bad(cmd, "select objects or give ids"));
|
||||
}
|
||||
@@ -616,7 +697,7 @@ fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn clear_appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = require_targets(s, p, "appearance.clear")?;
|
||||
let ids = require_whole_targets(s, p, "appearance.clear")?;
|
||||
// When every object is cleared already, the document and its undo history stay as they are.
|
||||
let before = s.doc()?.doc.clone();
|
||||
super::overprint::edit_counted(s, "Clear Appearance", |d| {
|
||||
@@ -732,35 +813,64 @@ fn transfer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "`source` and `target` are the same object"));
|
||||
}
|
||||
let copy = switch_or(p, "copy", false, C)?;
|
||||
// A graph series group stands for the paths directly inside it: as the source, the topmost of them is read and a
|
||||
// move clears them all; as the target, each of them other than a source takes the appearance.
|
||||
let sources = look_holders(&s.doc()?.doc, source);
|
||||
let read = sources.last().copied().unwrap_or(source);
|
||||
let from: Vec<NodeId> = sources.iter().copied().chain(stood_for(&[source], &sources)).collect();
|
||||
let marks = rowless_series_marks(&s.doc()?.doc, &[target]);
|
||||
let stands = !marks.contains(&target);
|
||||
let within: HashSet<NodeId> = from.iter().copied().collect();
|
||||
let mut targets: Vec<NodeId> = marks.iter().copied().filter(|id| !within.contains(id)).collect();
|
||||
if targets.is_empty() {
|
||||
if stands {
|
||||
return Err(bad(C, "`source` is the only path in series group `target`"));
|
||||
}
|
||||
targets.push(target);
|
||||
}
|
||||
// A source that is one of the target group's paths keeps its look: the group stands for it too.
|
||||
let part: HashSet<NodeId> = if stands { marks.into_iter().collect() } else { HashSet::new() };
|
||||
let from: Vec<NodeId> = stood_for(&from, &targets);
|
||||
let cleared: Vec<NodeId> = if copy { vec![] } else { from.iter().copied().filter(|id| !part.contains(id)).collect() };
|
||||
// The group its paths stand for loses its own opacity, blend mode and effects, which would stay on top of them.
|
||||
let group: Vec<NodeId> = if stands { vec![target] } else { vec![] };
|
||||
// When both objects come out as they were, the document and its undo history stay as they are.
|
||||
let before = s.doc()?.doc.clone();
|
||||
super::overprint::edit_counted(s, if copy { "Copy Appearance" } else { "Move Appearance" }, |d| {
|
||||
let src = d.node(source).cloned().ok_or(EngineError::NoNode(source))?;
|
||||
let to = d.node_mut(target).ok_or(EngineError::NoNode(target))?;
|
||||
let mut ap = src.appearance.clone();
|
||||
if let (Some(f), Some(t)) = (src.geometric_bounds(), to.geometric_bounds()) {
|
||||
ap.rebase_gradients(f, t);
|
||||
d.node(source).ok_or(EngineError::NoNode(source))?;
|
||||
let src = d.node(read).cloned().ok_or(EngineError::NoNode(read))?;
|
||||
for id in &targets {
|
||||
let to = d.node_mut(*id).ok_or(EngineError::NoNode(*id))?;
|
||||
let mut ap = src.appearance.clone();
|
||||
if let (Some(f), Some(t)) = (src.geometric_bounds(), to.geometric_bounds()) {
|
||||
ap.rebase_gradients(f, t);
|
||||
}
|
||||
// Only groups, layers, type and images have a Contents (Characters) row to keep a slot for.
|
||||
if to.contents_label().is_none() {
|
||||
ap.contents_index = None;
|
||||
}
|
||||
to.appearance = ap;
|
||||
(to.opacity, to.blend, to.isolate, to.knockout, to.knockout_shape) =
|
||||
(src.opacity, src.blend, src.isolate, src.knockout, src.knockout_shape);
|
||||
super::object::snap_if_aligned(to);
|
||||
}
|
||||
// Only groups, layers, type and images have a Contents (Characters) row to keep a slot for.
|
||||
if to.contents_label().is_none() {
|
||||
ap.contents_index = None;
|
||||
clear_stood_for(d, &group);
|
||||
for id in &cleared {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
clear(n);
|
||||
(n.isolate, n.knockout, n.knockout_shape) = (false, Default::default(), false);
|
||||
super::object::snap_if_aligned(n);
|
||||
}
|
||||
}
|
||||
to.appearance = ap;
|
||||
(to.opacity, to.blend, to.isolate, to.knockout, to.knockout_shape) = (src.opacity, src.blend, src.isolate, src.knockout, src.knockout_shape);
|
||||
super::object::snap_if_aligned(to);
|
||||
if !copy && let Some(n) = d.node_mut(source) {
|
||||
clear(n);
|
||||
(n.isolate, n.knockout, n.knockout_shape) = (false, Default::default(), false);
|
||||
super::object::snap_if_aligned(n);
|
||||
}
|
||||
let changed = if copy { vec![target] } else { vec![source, target] };
|
||||
let changed: Vec<NodeId> = cleared.iter().chain(&targets).copied().collect();
|
||||
let kept = super::graph::capture_series_opacity(d, &both_kinds(&changed));
|
||||
// The target last: on marks of one series, its paint is the one the series keeps.
|
||||
// The targets last: on marks of one series, their paint is the one the series keeps.
|
||||
let mut rows = top_paint_changed(&before, d, &changed);
|
||||
rows.extend(painted_rows(d, both_kinds(&[target])));
|
||||
rows.extend(painted_rows(d, both_kinds(&targets)));
|
||||
let painted = super::graph::capture_series_top_paints(d, &rows);
|
||||
let object = super::graph::capture_series_object_opacity(d, &changed);
|
||||
Ok(count_changed(d, &before, &[source, target]) + usize::from(kept || painted || object))
|
||||
let all: Vec<NodeId> = from.iter().chain(&targets).chain(&group).copied().collect();
|
||||
Ok(count_changed(d, &before, &all) + usize::from(kept || painted || object))
|
||||
})?;
|
||||
s.active_appearance_item = None;
|
||||
Ok(json!({ "source": source.0, "target": target.0 }))
|
||||
@@ -772,7 +882,7 @@ fn is_group(n: &Node) -> bool {
|
||||
}
|
||||
|
||||
fn reduce_basic(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = require_targets(s, p, "appearance.reduceToBasic")?;
|
||||
let ids = require_whole_targets(s, p, "appearance.reduceToBasic")?;
|
||||
// When every object comes out as it was, the document and its undo history stay as they are.
|
||||
let before = s.doc()?.doc.clone();
|
||||
// The Appearance panel's active row (a row of the first selected object's stack, and in each
|
||||
@@ -828,7 +938,7 @@ fn set_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_numbers(p, &["weight", "opacity"], "appearance.setItem")?;
|
||||
check_switches(p, &["visible"], "appearance.setItem")?;
|
||||
let paint = paint_from(s, p)?;
|
||||
let ids = appearance_targets(s, p)?;
|
||||
let ids = row_targets(s, p)?;
|
||||
if ids.is_empty() {
|
||||
return Err(bad("appearance.setItem", "select objects or give ids"));
|
||||
}
|
||||
@@ -1039,7 +1149,7 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
/// `appearance.showAllHidden`: shows every hidden fill, stroke and effect of the selected objects.
|
||||
fn show_all_hidden(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let roots = require_targets(s, p, "appearance.showAllHidden")?;
|
||||
let roots = require_whole_targets(s, p, "appearance.showAllHidden")?;
|
||||
let before = s.doc()?.doc.clone();
|
||||
let ids = s.edit("Show All Hidden Attributes", |d, _| {
|
||||
let shown: Vec<NodeId> = roots
|
||||
@@ -1069,11 +1179,16 @@ fn show_all_hidden(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn move_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "appearance.moveItem";
|
||||
let to = index_param(p, "to", C)?;
|
||||
let ids = require_targets(s, p, C)?;
|
||||
let aligned = aligned(p, C)?;
|
||||
if p.get("from").and_then(Value::as_str) == Some("contents") {
|
||||
// A graph series group's own Contents row, not its paths, which have none.
|
||||
let ids = appearance_targets(s, p)?;
|
||||
if ids.is_empty() {
|
||||
return Err(bad(C, "select objects or give ids"));
|
||||
}
|
||||
return move_contents(s, &ids, to);
|
||||
}
|
||||
let ids = require_targets(s, p, C)?;
|
||||
// Where an aligned row would go in each of several different stacks isn't one place.
|
||||
if aligned && appearances_differ(&s.doc()?.doc, &ids) {
|
||||
return Err(bad(C, "rows of objects whose appearances differ can't be reordered together"));
|
||||
@@ -1365,17 +1480,19 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (fill, stroke) = (attrs.appearance.fill, attrs.appearance.stroke);
|
||||
let source_has = |kind: bool| picked.appearance.items.iter().any(|it| it.is_fill() == kind);
|
||||
let source_shows = |kind: bool| picked.appearance.items.iter().any(|it| it.is_fill() == kind && it.visible());
|
||||
// A whole pick replaces the stack: it removes the rows of a kind the source has no row of.
|
||||
let whole = fill == FillAttrs::ALL && stroke == StrokeAttrs::ALL;
|
||||
let (paints, opacities) = if append {
|
||||
let rows = (fill.color && source_shows(true), stroke.color && source_shows(false));
|
||||
(rows, rows)
|
||||
} else {
|
||||
(
|
||||
(fill.color, stroke.color || (stroke.weight && source_has(false))),
|
||||
(fill.transparency && source_has(true), stroke.transparency && source_has(false)),
|
||||
(fill.transparency && (whole || source_has(true)), stroke.transparency && (whole || source_has(false))),
|
||||
)
|
||||
};
|
||||
// A pick of some attributes edits the topmost row of its kind, which may be hidden; `append` and a whole pick write rows.
|
||||
let rows_written = append || (fill == FillAttrs::ALL && stroke == StrokeAttrs::ALL);
|
||||
let rows_written = append || whole;
|
||||
let top_shows = |id: NodeId, kind: bool| {
|
||||
let items = d.node(id).map_or(&[][..], |n| &n.appearance.items[..]);
|
||||
items.iter().rev().find(|it| it.is_fill() == kind).is_some_and(|it| it.visible())
|
||||
@@ -1389,6 +1506,9 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.collect()
|
||||
};
|
||||
let mut opacity_rows = top_opacity_changed(&before, d, &targets);
|
||||
// A written row that had paint before the pick counts too when the pick left it without paint, as in
|
||||
// `capture_series_writes`.
|
||||
opacity_rows.extend(painted_rows(&before, written(opacities)));
|
||||
opacity_rows.extend(painted_rows(d, written(opacities)));
|
||||
let mut rows = top_paint_changed(&before, d, &targets);
|
||||
rows.extend(painted_rows(d, written(paints)));
|
||||
|
||||
@@ -199,7 +199,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New Symbol…",
|
||||
[],
|
||||
None,
|
||||
"{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type)} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions 0..1 of the natural size (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions → {name, id, registration, exportType, nineSlice, type}",
|
||||
"{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type)} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions → {name, id, registration, exportType, nineSlice, type}",
|
||||
has_selection,
|
||||
symbol_new
|
||||
),
|
||||
@@ -208,7 +208,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Symbol Options…",
|
||||
[],
|
||||
None,
|
||||
"{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic} rename a symbol (its instances and the graphics mapped onto 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions 0..1) and Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes); default name: current → {name, registration, exportType, nineSlice, type}",
|
||||
"{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic} rename a symbol (its instances and the graphics mapped onto 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions in from each edge, each -16..16, with left + right < 1 and top + bottom < 1) and Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes); default name: current → {name, registration, exportType, nineSlice, type}",
|
||||
has_doc,
|
||||
symbol_options
|
||||
),
|
||||
|
||||
@@ -47,21 +47,20 @@ fn export_type_param(p: &Value, cmd: &str) -> Result<Option<SymbolExportType>> {
|
||||
}
|
||||
|
||||
/// `nineSlice` (bool) and `nineSliceGuides` ([left, top, right, bottom] fractions of the natural
|
||||
/// size): `None` leaves the symbol alone, `Some(None)` turns 9-slice off, `Some(Some(g))` turns it
|
||||
/// on with guides `g` (the symbol's current ones, else a quarter in from each edge, when none are
|
||||
/// given).
|
||||
/// size, below 0 or above 1 for a guide outside the art): `None` leaves the symbol alone,
|
||||
/// `Some(None)` turns 9-slice off, `Some(Some(g))` turns it on with guides `g` (the symbol's
|
||||
/// current ones, else a quarter in from each edge, when none are given).
|
||||
fn nine_slice_param(p: &Value, cmd: &str, current: Option<SymbolNineSlice>) -> Result<Option<Option<SymbolNineSlice>>> {
|
||||
let on = match p.get("nineSlice") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(v) => Some(v.as_bool().ok_or_else(|| bad(cmd, "nineSlice must be true or false"))?),
|
||||
};
|
||||
let guides =
|
||||
match p.get("nineSliceGuides") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(v) => Some(SymbolNineSlice::from_value(v).ok_or_else(|| {
|
||||
bad(cmd, "nineSliceGuides must be [left, top, right, bottom], each 0..1, with left + right < 1 and top + bottom < 1")
|
||||
})?),
|
||||
};
|
||||
let guides = match p.get("nineSliceGuides") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(v) => Some(SymbolNineSlice::from_value(v).ok_or_else(|| {
|
||||
bad(cmd, "nineSliceGuides must be [left, top, right, bottom], each -16..16, with left + right < 1 and top + bottom < 1")
|
||||
})?),
|
||||
};
|
||||
Ok(match (on, guides) {
|
||||
(Some(false), _) => Some(None),
|
||||
(None, None) => None,
|
||||
|
||||
@@ -527,8 +527,9 @@ fn color_groups(cmd: &str, d: &mut Document, items: Vec<Arc<Node>>) -> Result<Ve
|
||||
}
|
||||
|
||||
/// What a trace depends on: the object traced (an image, or an Image Trace object traced again),
|
||||
/// its image, and the settings it is traced with. The tracer makes the same paths of the same
|
||||
/// inputs, so a trace made away from the command ([`TraceRun`]) stands in for the command's own.
|
||||
/// its image, the image's encoded bytes, and the settings it is traced with. The tracer makes the
|
||||
/// same paths of the same inputs, so a trace made away from the command ([`TraceRun`]) stands in
|
||||
/// for the command's own.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
struct TraceInputs {
|
||||
target: NodeId,
|
||||
@@ -538,6 +539,9 @@ struct TraceInputs {
|
||||
/// Document Library: the library's colours, which the JSON leaves out
|
||||
/// ([`tr::TraceParams::swatches`]).
|
||||
swatches: Vec<[u8; 3]>,
|
||||
/// The encoded image the tracer decodes: the blob under the image's key, shared with the
|
||||
/// document. Two blobs are equal when they are the same allocation or hold the same bytes.
|
||||
bytes: Arc<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// What `imageTrace.make` and `imageTrace.makeAndExpand` take from the session before they trace.
|
||||
@@ -549,7 +553,6 @@ struct Prepared {
|
||||
params_json: Value,
|
||||
preset_label: String,
|
||||
library: Vec<([u8; 3], Paint)>,
|
||||
bytes: Arc<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// What command `c` with params `p` traces, and how, from the session: everything but the trace.
|
||||
@@ -597,8 +600,8 @@ 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, swatches: params.swatches.clone() };
|
||||
Ok(Prepared { inputs, trace: params, view, params_json, preset_label, library, bytes })
|
||||
let inputs = TraceInputs { target, image, params: traced_with, swatches: params.swatches.clone(), bytes };
|
||||
Ok(Prepared { inputs, trace: params, view, params_json, preset_label, library })
|
||||
}
|
||||
|
||||
/// What a trace made of an image: the size in pixels it was decoded at, and the paths.
|
||||
@@ -616,11 +619,11 @@ impl Traced {
|
||||
}
|
||||
}
|
||||
|
||||
/// Decode the image `bytes` and trace it with `params`, telling `steps` how far it has got
|
||||
/// ([`tr::trace_watched`]); [`EngineError::Cancelled`] once `steps` answers `false`.
|
||||
fn trace_now(inputs: &TraceInputs, params: &tr::TraceParams, bytes: &[u8], steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result<Traced> {
|
||||
/// Decode the image bytes of `inputs` and trace them with `params`, telling `steps` how far it has
|
||||
/// got ([`tr::trace_watched`]); [`EngineError::Cancelled`] once `steps` answers `false`.
|
||||
fn trace_now(inputs: &TraceInputs, params: &tr::TraceParams, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result<Traced> {
|
||||
// An image over the tracer's size is traced scaled down (the paths are scaled back).
|
||||
let raster = tr::Raster::decode_to_fit(bytes).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
let raster = tr::Raster::decode_to_fit(&inputs.bytes).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
if !steps(0, 0) {
|
||||
return Err(EngineError::Cancelled);
|
||||
}
|
||||
@@ -682,7 +685,8 @@ impl TraceRun {
|
||||
(self.prepared.inputs.image.width, self.prepared.inputs.image.height)
|
||||
}
|
||||
|
||||
/// Does it still apply: would the command trace the same object, image and settings now?
|
||||
/// Does it still apply: would the command trace the same object, image, pixels and settings
|
||||
/// now?
|
||||
pub fn current(&self, s: &Session) -> bool {
|
||||
prepare(s, self.command, &self.params).is_ok_and(|now| now.inputs == self.prepared.inputs)
|
||||
}
|
||||
@@ -691,13 +695,13 @@ impl TraceRun {
|
||||
/// failed or stopped ([`EngineError::Cancelled`] once `steps` answers `false`). It touches no
|
||||
/// document, so it can run on any thread.
|
||||
pub fn run(&self, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result<Traced> {
|
||||
trace_now(&self.prepared.inputs, &self.prepared.trace, &self.prepared.bytes, steps)
|
||||
trace_now(&self.prepared.inputs, &self.prepared.trace, steps)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Value> {
|
||||
let c = if expand { "imageTrace.makeAndExpand" } else { "imageTrace.make" };
|
||||
let Prepared { inputs, trace, view, params_json, preset_label, library, bytes } = prepare(s, c, p)?;
|
||||
let Prepared { inputs, trace, view, params_json, preset_label, library } = prepare(s, c, p)?;
|
||||
let group_by_color = expand && by_color_param(c, p)?;
|
||||
// A saved preset's settings join the journal entry, so a replay traces as this run did after
|
||||
// the preset is changed, renamed or deleted.
|
||||
@@ -709,7 +713,7 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
// A trace handed in for these very inputs ([`TraceRun`]), else one made now.
|
||||
let Traced { raster, res, .. } = match s.trace_hand_off.take() {
|
||||
Some(traced) if traced.inputs == inputs => traced,
|
||||
_ => trace_now(&inputs, &trace, &bytes, &|_, _| true)?,
|
||||
_ => trace_now(&inputs, &trace, &|_, _| true)?,
|
||||
};
|
||||
let TraceInputs { target, image: img, .. } = inputs;
|
||||
let mut warnings = keep_warnings(&trace, &res);
|
||||
|
||||
@@ -88,8 +88,9 @@ pub struct Clipboard {
|
||||
/// The artboard the objects were copied from (none when they lie on no artboard; the first of
|
||||
/// [`Self::artboards`] when there are any): Paste on All Artboards keeps their offset to it.
|
||||
pub source_artboard: Option<Rect>,
|
||||
/// Per object: the name of the layer it was copied from (Paste Remembers Layers).
|
||||
pub source_layers: Vec<Option<String>>,
|
||||
/// Per object: the layer or sublayer it was copied from and the layers around it (Paste
|
||||
/// Remembers Layers); none when that layer has no name.
|
||||
pub source_layers: Vec<Option<SourceLayer>>,
|
||||
/// The open document the objects came from ([`DocState::uid`]): pasting back into it uses its
|
||||
/// own resources as they are now.
|
||||
pub source_doc: Option<u64>,
|
||||
@@ -101,6 +102,29 @@ pub struct Clipboard {
|
||||
pub guides: Vec<vectorcraft_doc::Guide>,
|
||||
}
|
||||
|
||||
/// The layer an object was copied from, as Paste Remembers Layers finds it again: the top-level
|
||||
/// layer first, down to the layer or sublayer that holds the object.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub struct SourceLayer {
|
||||
/// The layers' ids in the source document ([`Clipboard::source_doc`]).
|
||||
pub ids: Vec<NodeId>,
|
||||
/// The layers' names (an unnamed layer above the one that holds the object is "").
|
||||
pub names: Vec<String>,
|
||||
}
|
||||
|
||||
impl SourceLayer {
|
||||
/// The layers around the object `anc` ends with ([`Document::ancestry`]); none when the layer
|
||||
/// that holds it has no name.
|
||||
fn of(d: &Document, anc: &[NodeId]) -> Option<Self> {
|
||||
let layers: Vec<&Node> = anc.iter().rev().skip(1).filter_map(|a| d.node(*a).filter(|l| l.is_layer())).collect();
|
||||
layers.first()?.name.as_ref()?;
|
||||
Some(Self {
|
||||
ids: layers.iter().rev().map(|l| l.id).collect(),
|
||||
names: layers.iter().rev().map(|l| l.name.clone().unwrap_or_default()).collect(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Indices of segments selected on `sp` (either explicitly or via incident anchors).
|
||||
pub(crate) fn subpath_selected_segments(
|
||||
sp: &vectorcraft_geom::SubPath,
|
||||
@@ -119,17 +143,13 @@ pub(crate) fn subpath_selected_segments(
|
||||
let has_explicit_segs = seg_refs.is_some_and(|segments| !segments.is_empty());
|
||||
if has_explicit_segs {
|
||||
if let Some(segments) = seg_refs {
|
||||
for &(s, seg) in segments {
|
||||
if s == si && seg < seg_count {
|
||||
selected_segs.insert(seg);
|
||||
}
|
||||
}
|
||||
selected_segs.extend(super::path::subpath_refs(segments, si).filter(|&seg| seg < seg_count));
|
||||
}
|
||||
return selected_segs;
|
||||
}
|
||||
|
||||
if let Some(anchors) = anchor_refs {
|
||||
let sub_anchors: BTreeSet<usize> = anchors.iter().filter_map(|&(s, a)| (s == si && a < n).then_some(a)).collect();
|
||||
let sub_anchors: BTreeSet<usize> = super::path::subpath_refs(anchors, si).filter(|&a| a < n).collect();
|
||||
if !sub_anchors.is_empty() {
|
||||
for i in 0..seg_count {
|
||||
let next = (i + 1) % n;
|
||||
@@ -256,7 +276,7 @@ impl Clipboard {
|
||||
let mut compound_bounds: std::collections::HashMap<NodeId, Option<vectorcraft_geom::Rect>> = std::collections::HashMap::new();
|
||||
for id in roots {
|
||||
let (Some(n), Some(anc)) = (d.node(*id), d.ancestry(*id)) else { continue };
|
||||
let layer_name = anc.iter().rev().skip(1).find_map(|a| d.node(*a).filter(|l| l.is_layer())).and_then(|l| l.name.clone());
|
||||
let source_layer = SourceLayer::of(d, &anc);
|
||||
let compound_parent = anc.iter().rev().skip(1).find_map(|a| d.node(*a).filter(|p| matches!(p.kind, NodeKind::Compound { .. })));
|
||||
// Gradients fitted to the compound's bounds are pinned there, as a split pins them.
|
||||
let gradient_box = compound_parent
|
||||
@@ -299,11 +319,11 @@ impl Clipboard {
|
||||
if direct && let Some(pieces) = extract_direct_selection(n, &st.selection) {
|
||||
for piece in pieces {
|
||||
nodes.push(inherit_appearance(piece));
|
||||
source_layers.push(layer_name.clone());
|
||||
source_layers.push(source_layer.clone());
|
||||
}
|
||||
} else {
|
||||
nodes.push(inherit_appearance(n.clone()));
|
||||
source_layers.push(layer_name);
|
||||
source_layers.push(source_layer);
|
||||
}
|
||||
}
|
||||
// Symbol instances are measured by their art.
|
||||
|
||||
@@ -5,9 +5,11 @@
|
||||
//! Colour settings and the proof view are process-wide (`vectorcraft_color::cms::active`,
|
||||
//! `vectorcraft_render::proof::view`). A document's assigned profiles are stored in
|
||||
//! `Document::color_profiles` (files before format v3: `Document.unknown["colorProfiles"]`) and
|
||||
//! take the place of the working spaces in the active settings when assigned, and when the working
|
||||
//! settings change while the document is in front ([`use_front_profiles`]); the working spaces stay
|
||||
//! as Edit → Color Settings set them.
|
||||
//! take the place of the working spaces in the active settings while the document is in front
|
||||
//! ([`use_front_profiles`]): when they are assigned, when the working settings change, and when the
|
||||
//! document comes to the front or its assignment comes back (an open, a switch, a close, a revert,
|
||||
//! an undo or a rollback, [`Session::sync_front_profiles`]); the working spaces stay as Edit → Color
|
||||
//! Settings set them.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
@@ -181,7 +183,7 @@ fn touch_all(s: &mut Session) {
|
||||
/// Make the active settings the working settings with the profiles the front document is assigned
|
||||
/// in place of the working spaces (none, or no document open: the working spaces). The open
|
||||
/// documents redraw when the active settings change.
|
||||
fn use_front_profiles(s: &mut Session) {
|
||||
pub(crate) fn use_front_profiles(s: &mut Session) {
|
||||
let (rgb, cmyk) = s.active().map(|d| doc_profiles(&d.doc)).unwrap_or_default();
|
||||
if cms::use_document_profiles(rgb.as_deref(), cmyk.as_deref()) {
|
||||
touch_all(s);
|
||||
|
||||
@@ -52,7 +52,7 @@ pub const CATEGORIES: [(&str, &str); 13] = [
|
||||
];
|
||||
|
||||
/// The object counts of `document.info` and their labels.
|
||||
const OBJECT_LABELS: [(&str, &str); 19] = [
|
||||
pub const OBJECT_LABELS: [(&str, &str); 19] = [
|
||||
("paths", "Paths"),
|
||||
("compoundPaths", "Compound Paths"),
|
||||
("groups", "Groups"),
|
||||
|
||||
@@ -210,7 +210,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Guides",
|
||||
[],
|
||||
None,
|
||||
"{} → [{index, vertical, pos, selected, artboard?: index (an artboard guide's), layer?: id (the layer it is on), shown, editable (its layer shown and unlocked)}…] the ruler guides",
|
||||
"{} → [{index, id (its node, which `layer.setProps` hides or locks on its own), vertical, pos, selected, artboard?: index (an artboard guide's), layer?: id (the layer it is on), hidden, locked (its own visibility and lock), shown, editable (it and its layer shown and unlocked)}…] the ruler guides",
|
||||
has_doc,
|
||||
guide_list
|
||||
),
|
||||
@@ -219,7 +219,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Select Guides",
|
||||
[],
|
||||
None,
|
||||
"{indexes: [index…], toggle?: bool} select ruler guides on their own (deselecting the art); toggle adds or removes them instead, keeping the selected art (a Shift-click on a guide) → {selected: [index…]}",
|
||||
"{indexes: [index…] (at most 10,000), toggle?: bool} select ruler guides on their own (deselecting the art); toggle adds or removes them instead, keeping the selected art (a Shift-click on a guide) → {selected: [index…]}",
|
||||
guides_unlocked,
|
||||
guide_select
|
||||
),
|
||||
@@ -228,7 +228,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Remove Guide",
|
||||
[],
|
||||
None,
|
||||
"{index?} delete ruler guide `index`, else the selected ones (as Delete / edit.clear does) → {count}",
|
||||
"{index?, indexes?: [index…] (at most 10,000)} delete ruler guide `index` (or guides `indexes`, as dragging their rows onto the Layers panel's trash does), else the selected ones (as Delete / edit.clear does), in one undo step; give `index` or `indexes`, not both, and an index given twice counts once; a hidden or locked guide, or one on a hidden or locked layer, is an error → {count}",
|
||||
guides_unlocked,
|
||||
guide_remove
|
||||
),
|
||||
@@ -246,7 +246,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Guide to Layer",
|
||||
[],
|
||||
None,
|
||||
"{index?, indexes?: [index…], layer: id} put ruler guide `index` (or guides `indexes`), else the selected guides, on layer `layer` (a layer or sublayer), as dragging their rows onto that layer's row in the Layers panel does → {count}",
|
||||
"{index?, indexes?: [index…] (at most 10,000), layer: id} put ruler guide `index` (or guides `indexes`), else the selected guides, on layer `layer` (a layer or sublayer), as dragging their rows onto that layer's row in the Layers panel does; give `index` or `indexes`, not both, and an index given twice counts once → {count}",
|
||||
guides_unlocked,
|
||||
guide_set_layer
|
||||
),
|
||||
@@ -805,12 +805,17 @@ fn guide_list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let row = |(i, g): (usize, &Guide)| {
|
||||
let selected = g.id.is_some_and(|id| st.selection.guides.contains(&id));
|
||||
let mut r = json!({ "index": i, "vertical": g.vertical, "pos": g.pos, "selected": selected });
|
||||
if let Some(id) = g.id {
|
||||
r["id"] = json!(id.0);
|
||||
}
|
||||
if let Some(ab) = st.doc.artboards.iter().position(|a| Some(a.id) == g.artboard) {
|
||||
r["artboard"] = json!(ab);
|
||||
}
|
||||
if let Some(l) = g.layer {
|
||||
r["layer"] = json!(l.0);
|
||||
}
|
||||
r["hidden"] = json!(g.hidden);
|
||||
r["locked"] = json!(g.locked);
|
||||
r["shown"] = json!(st.doc.guide_shown(g));
|
||||
r["editable"] = json!(st.doc.guide_editable(g));
|
||||
r
|
||||
@@ -824,27 +829,44 @@ fn guide_index_in(ids: &[NodeId], v: Option<&Value>, cmd: &str) -> Result<NodeId
|
||||
ids.get(i).copied().ok_or_else(|| bad(cmd, format!("no guide {i}")))
|
||||
}
|
||||
|
||||
/// The most guide indexes one `indexes` list may hold.
|
||||
const MAX_GUIDE_INDEXES: usize = 10_000;
|
||||
|
||||
/// `indexes` as a list of at most [`MAX_GUIDE_INDEXES`] entries.
|
||||
fn guide_index_list<'a>(v: &'a Value, cmd: &str) -> Result<&'a Vec<Value>> {
|
||||
let list = v.as_array().ok_or_else(|| bad(cmd, "indexes must be an array of guide indexes"))?;
|
||||
if list.len() > MAX_GUIDE_INDEXES {
|
||||
return Err(bad(cmd, format!("indexes may hold at most {MAX_GUIDE_INDEXES} entries")));
|
||||
}
|
||||
Ok(list)
|
||||
}
|
||||
|
||||
/// The id of ruler guide `index` of the active document (`index` validated).
|
||||
fn guide_index(s: &Session, v: Option<&Value>, cmd: &str) -> Result<NodeId> {
|
||||
guide_index_in(&guide_ids(&s.doc()?.doc), v, cmd)
|
||||
}
|
||||
|
||||
/// Is ruler guide `id` one that can be moved or deleted: not on a hidden or locked layer?
|
||||
/// Is ruler guide `id` one that can be moved or deleted: not hidden or locked itself, nor on a
|
||||
/// hidden or locked layer?
|
||||
fn check_editable_guide(s: &Session, id: NodeId) -> Result<NodeId> {
|
||||
let d = &s.doc()?.doc;
|
||||
if !d.ruler_guide(id).is_some_and(|g| d.guide_editable(&g)) {
|
||||
let guide = d.ruler_guide(id);
|
||||
if guide.as_ref().is_some_and(|g| g.hidden || g.locked) {
|
||||
return Err(EngineError::Other("the guide is hidden or locked".into()));
|
||||
}
|
||||
if !guide.is_some_and(|g| d.guide_editable(&g)) {
|
||||
return Err(EngineError::Other("the guide is on a hidden or locked layer".into()));
|
||||
}
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// [`guide_index`] of a guide that can be moved or deleted: not on a hidden or locked layer.
|
||||
/// [`guide_index`] of a guide that can be moved or deleted ([`check_editable_guide`]).
|
||||
fn editable_guide_index(s: &Session, v: Option<&Value>, cmd: &str) -> Result<NodeId> {
|
||||
check_editable_guide(s, guide_index(s, v, cmd)?)
|
||||
}
|
||||
|
||||
fn guide_select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let list = p.get("indexes").and_then(Value::as_array).ok_or_else(|| bad("guide.select", "missing indexes"))?;
|
||||
let list = guide_index_list(p.get("indexes").ok_or_else(|| bad("guide.select", "missing indexes"))?, "guide.select")?;
|
||||
let ids = guide_ids(&s.doc()?.doc);
|
||||
let picked = list.iter().map(|v| guide_index_in(&ids, Some(v), "guide.select")).collect::<Result<Vec<_>>>()?;
|
||||
if switch_or(p, "toggle", false, "guide.select")? {
|
||||
@@ -861,18 +883,30 @@ fn guide_select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "selected": guide_indexes(&st.doc, &st.selection.guides) }))
|
||||
}
|
||||
|
||||
/// Delete ruler guide `index`, else the selected guides, in one undo step → {count}.
|
||||
/// Delete ruler guide `index` (or guides `indexes`), else the selected guides, in one undo step
|
||||
/// → {count}.
|
||||
pub(crate) fn guide_remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let gone: Vec<NodeId> = match p.get("index") {
|
||||
Some(v) => vec![editable_guide_index(s, Some(v), "guide.remove")?],
|
||||
None => s.doc()?.selection.guides.clone(),
|
||||
const C: &str = "guide.remove";
|
||||
let mut gone: Vec<NodeId> = match (p.get("index"), p.get("indexes")) {
|
||||
(Some(_), Some(_)) => return Err(bad(C, "give index or indexes, not both")),
|
||||
(Some(v), None) => vec![editable_guide_index(s, Some(v), C)?],
|
||||
(None, Some(list)) => {
|
||||
let list = guide_index_list(list, C)?;
|
||||
let ids = guide_ids(&s.doc()?.doc);
|
||||
// A set, so an index given twice deletes its guide once and the ids held never outnumber the guides.
|
||||
let set = list.iter().map(|v| check_editable_guide(s, guide_index_in(&ids, Some(v), C)?)).collect::<Result<BTreeSet<_>>>()?;
|
||||
set.into_iter().collect()
|
||||
}
|
||||
(None, None) => s.doc()?.selection.guides.clone(),
|
||||
};
|
||||
gone.sort_unstable();
|
||||
gone.dedup();
|
||||
if gone.is_empty() {
|
||||
return Err(bad("guide.remove", "no guide selected"));
|
||||
return Err(bad(C, "no guide selected"));
|
||||
}
|
||||
let label = if gone.len() == 1 { "Delete Guide" } else { "Delete Guides" };
|
||||
s.edit(label, |d, sel| {
|
||||
d.retain_guides(sel, |g| !g.id.is_some_and(|id| gone.contains(&id)));
|
||||
d.retain_guides(sel, |g| !g.id.is_some_and(|id| gone.binary_search(&id).is_ok()));
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "count": gone.len() }))
|
||||
@@ -888,14 +922,19 @@ fn guide_set_layer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if super::layer::locked_within(d, layer) {
|
||||
return Err(EngineError::Other("the layer or group is locked".into()));
|
||||
}
|
||||
let moving: Vec<NodeId> = match (p.get("index"), p.get("indexes").and_then(Value::as_array)) {
|
||||
(Some(v), _) => vec![editable_guide_index(s, Some(v), C)?],
|
||||
let mut moving: Vec<NodeId> = match (p.get("index"), p.get("indexes")) {
|
||||
(Some(_), Some(_)) => return Err(bad(C, "give index or indexes, not both")),
|
||||
(Some(v), None) => vec![editable_guide_index(s, Some(v), C)?],
|
||||
(None, Some(list)) => {
|
||||
let list = guide_index_list(list, C)?;
|
||||
let ids = guide_ids(&s.doc()?.doc);
|
||||
list.iter().take(10_000).map(|v| check_editable_guide(s, guide_index_in(&ids, Some(v), C)?)).collect::<Result<Vec<_>>>()?
|
||||
list.iter().map(|v| check_editable_guide(s, guide_index_in(&ids, Some(v), C)?)).collect::<Result<Vec<_>>>()?
|
||||
}
|
||||
(None, None) => s.doc()?.selection.guides.clone(),
|
||||
};
|
||||
// An index given twice moves (and counts) its guide once; the others keep their order.
|
||||
let mut seen = HashSet::new();
|
||||
moving.retain(|id| seen.insert(*id));
|
||||
if moving.is_empty() {
|
||||
return Err(bad(C, "no guide selected (or give an index)"));
|
||||
}
|
||||
|
||||
@@ -116,8 +116,11 @@ pub(super) fn remove_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(EngineError::Other("no such anchor".into()));
|
||||
}
|
||||
let mut emptied = Beside::replacing(d, &[id]);
|
||||
let removed = remove_anchors_of(d, sel, &mut emptied, id, [(si, ai)], curvature)?;
|
||||
let removed = remove_anchors_of(d, sel, &mut emptied, id, vec![(si, ai)], curvature)?;
|
||||
emptied.finish(d)?;
|
||||
if removed {
|
||||
sel.remove(id);
|
||||
}
|
||||
Ok(removed)
|
||||
})?;
|
||||
Ok(json!({ "removedObject": removed }))
|
||||
@@ -136,14 +139,14 @@ pub(super) fn remove_anchors(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
return Err(bad("path.removeAnchors", "direct-select anchor points of a path"));
|
||||
}
|
||||
let removed = s.edit("Remove Anchor Points", |d, sel| {
|
||||
let mut removed = 0;
|
||||
let mut gone = Vec::new();
|
||||
let mut emptied = Beside::replacing(d, &jobs.iter().map(|(id, _)| *id).collect::<Vec<_>>());
|
||||
for (id, anchors) in jobs {
|
||||
let shape: Vec<(usize, bool)> =
|
||||
d.node(id).and_then(Node::path_data).map(|p| p.subpaths.iter().map(|sp| (sp.anchors.len(), sp.closed)).collect()).unwrap_or_default();
|
||||
let next = following_anchors(&shape, &anchors);
|
||||
if remove_anchors_of(d, sel, &mut emptied, id, anchors, false)? {
|
||||
removed += 1;
|
||||
gone.push(id);
|
||||
} else if !next.is_empty() {
|
||||
// The next anchor along is selected, so the next Remove Anchor Points goes on from
|
||||
// there without picking it first (#2241).
|
||||
@@ -151,7 +154,8 @@ pub(super) fn remove_anchors(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
emptied.finish(d)?;
|
||||
Ok(removed)
|
||||
sel.remove_all(gone.iter().copied());
|
||||
Ok(gone.len())
|
||||
})?;
|
||||
Ok(json!({ "removedObjects": removed }))
|
||||
}
|
||||
@@ -160,19 +164,32 @@ pub(super) fn remove_anchors(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
/// path whose subpaths have `shape` (anchor count, closed): in each subpath, the anchor after its
|
||||
/// last removed one, round the end of a closed subpath, or the one before it at an open subpath's
|
||||
/// end. Indexes are those after the removal, without the subpaths left with fewer than two anchors.
|
||||
/// `removed` is in ascending order without repeats, as a selection holds it, and each subpath reads
|
||||
/// only its own pairs.
|
||||
fn following_anchors(shape: &[(usize, bool)], removed: &[(usize, usize)]) -> BTreeSet<(usize, usize)> {
|
||||
let mut next = BTreeSet::new();
|
||||
let mut kept = 0;
|
||||
let mut rest = removed;
|
||||
for (si, &(n, closed)) in shape.iter().enumerate() {
|
||||
let gone: BTreeSet<usize> = removed.iter().filter(|&&(s, a)| s == si && a < n).map(|&(_, a)| a).collect();
|
||||
let (mine, after) = rest.split_at(rest.iter().take_while(|&&(s, _)| s == si).count());
|
||||
rest = after;
|
||||
let gone = &mine[..mine.partition_point(|&(_, a)| a < n)];
|
||||
if n - gone.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
if let Some(&last) = gone.last() {
|
||||
let wrap = if closed { 0..last } else { 0..0 };
|
||||
let after = (last + 1..n).chain(wrap).find(|a| !gone.contains(a));
|
||||
if let Some(a) = after.or_else(|| (0..last).rev().find(|a| !gone.contains(a))) {
|
||||
next.insert((kept, a - gone.range(..a).count()));
|
||||
if let Some(&(_, last)) = gone.last() {
|
||||
// Anchors past `last` are all left. Below it, the first one left (round a closed
|
||||
// subpath's end) is past the removed run from 0, and the last one left is below the
|
||||
// removed run down from `last`.
|
||||
let a = if last + 1 < n {
|
||||
Some(last + 1)
|
||||
} else if closed {
|
||||
Some(gone.iter().zip(0..).take_while(|&(&(_, g), k)| g == k).count())
|
||||
} else {
|
||||
last.checked_sub(gone.iter().rev().zip((0..=last).rev()).take_while(|&(&(_, g), k)| g == k).count())
|
||||
};
|
||||
if let Some(a) = a {
|
||||
next.insert((kept, a - gone.partition_point(|&(_, g)| g < a)));
|
||||
}
|
||||
}
|
||||
kept += 1;
|
||||
@@ -183,34 +200,37 @@ fn following_anchors(shape: &[(usize, bool)], removed: &[(usize, usize)]) -> BTr
|
||||
/// Remove `anchors` (subpath, anchor) of path `id` without opening it, refitting the curve round
|
||||
/// each one, or with `curvature` re-curving it as the Curvature tool curves its points
|
||||
/// ([`vectorcraft_tools::draw2::curvature_remove`]). A subpath left with one anchor is removed,
|
||||
/// and a path left with no subpath is removed through `emptied`. True when the path went.
|
||||
/// and a path left with no subpath is removed through `emptied`; the caller then takes it out of
|
||||
/// the selection. True when the path went.
|
||||
fn remove_anchors_of(
|
||||
d: &mut Document,
|
||||
sel: &mut Selection,
|
||||
emptied: &mut Beside,
|
||||
id: NodeId,
|
||||
anchors: impl IntoIterator<Item = (usize, usize)>,
|
||||
mut anchors: Vec<(usize, usize)>,
|
||||
curvature: bool,
|
||||
) -> Result<bool> {
|
||||
let mut anchors: Vec<(usize, usize)> = anchors.into_iter().collect();
|
||||
// The last first, so the indexes still to come stay valid.
|
||||
anchors.sort_unstable_by(|a, b| b.cmp(a));
|
||||
anchors.dedup();
|
||||
let path = path_mut(d, id)?;
|
||||
for (si, ai) in anchors {
|
||||
if let Some(sp) = path.subpaths.get_mut(si) {
|
||||
if curvature {
|
||||
let mut rest = &anchors[..];
|
||||
while let Some(&(si, _)) = rest.first() {
|
||||
let (mine, after) = rest.split_at(rest.iter().take_while(|&&(s, _)| s == si).count());
|
||||
rest = after;
|
||||
let Some(sp) = path.subpaths.get_mut(si) else { continue };
|
||||
if curvature {
|
||||
for &(_, ai) in mine {
|
||||
vectorcraft_tools::draw2::curvature_remove(sp, ai);
|
||||
} else {
|
||||
po::remove_anchor(sp, ai);
|
||||
}
|
||||
} else {
|
||||
po::remove_anchors(sp, &mine.iter().map(|&(_, ai)| ai).collect::<Vec<_>>());
|
||||
}
|
||||
}
|
||||
path.subpaths.retain(|sp| sp.anchors.len() >= 2);
|
||||
let gone = path.is_empty();
|
||||
if gone {
|
||||
emptied.put(d, id, vec![])?;
|
||||
sel.remove(id);
|
||||
} else {
|
||||
sel.anchors.remove(&id);
|
||||
sel.segments.remove(&id);
|
||||
@@ -277,3 +297,47 @@ pub(super) fn reshape_segment(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})?;
|
||||
ok()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// [`following_anchors`] by its definition: for each subpath, a search of the anchors after
|
||||
/// its last removed one, round a closed end, then before it.
|
||||
fn following_by_search(shape: &[(usize, bool)], removed: &[(usize, usize)]) -> BTreeSet<(usize, usize)> {
|
||||
let mut next = BTreeSet::new();
|
||||
let mut kept = 0;
|
||||
for (si, &(n, closed)) in shape.iter().enumerate() {
|
||||
let gone: BTreeSet<usize> = removed.iter().filter(|&&(s, a)| s == si && a < n).map(|&(_, a)| a).collect();
|
||||
if n - gone.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
if let Some(&last) = gone.last() {
|
||||
let wrap = if closed { 0..last } else { 0..0 };
|
||||
let after = (last + 1..n).chain(wrap).find(|a| !gone.contains(a));
|
||||
if let Some(a) = after.or_else(|| (0..last).rev().find(|a| !gone.contains(a))) {
|
||||
next.insert((kept, a - gone.range(..a).count()));
|
||||
}
|
||||
}
|
||||
kept += 1;
|
||||
}
|
||||
next
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn following_anchors_matches_a_search_along_each_subpath() {
|
||||
let mut seed = 0x2545_f491_4f6c_dd1d_u64;
|
||||
let mut rnd = |m: u64| {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 7;
|
||||
seed ^= seed << 17;
|
||||
(seed % m) as usize
|
||||
};
|
||||
for case in 0..2000 {
|
||||
let shape: Vec<(usize, bool)> = (0..rnd(5) + 1).map(|_| (rnd(9), rnd(2) == 0)).collect();
|
||||
let removed: BTreeSet<(usize, usize)> = (0..rnd(14)).map(|_| (rnd(shape.len() as u64 + 1), rnd(11))).collect();
|
||||
let removed: Vec<_> = removed.into_iter().collect();
|
||||
assert_eq!(following_anchors(&shape, &removed), following_by_search(&shape, &removed), "case {case}: {shape:?} removing {removed:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Pencil",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks), fidelity?: pt (1.5), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end; with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it",
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end; with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it",
|
||||
has_doc,
|
||||
freehand
|
||||
),
|
||||
|
||||
@@ -151,7 +151,11 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let pen = PenRecord::of_samples(&samples);
|
||||
let mut pts: Vec<Point> = samples.into_iter().map(|s| s.pt).collect();
|
||||
let tol = number_or(p, "fidelity", 1.5, C)?.clamp(vectorcraft_tools::draw2::MIN_FIT_TOLERANCE, 100.0);
|
||||
let tol = number_or(p, "fidelity", 1.5, C)?;
|
||||
let (lo, hi) = (vectorcraft_tools::draw2::MIN_FIT_TOLERANCE, vectorcraft_tools::draw2::MAX_FIT_TOLERANCE);
|
||||
if !(lo..=hi).contains(&tol) {
|
||||
return Err(bad(C, format!("`fidelity` must be from {lo} to {hi} pt")));
|
||||
}
|
||||
// The tolerance the stroke is fitted at; with `fit: false` it is not fitted.
|
||||
let fit_tol = switch_or(p, "fit", true, C)?.then_some(tol);
|
||||
let closed = switch_or(p, "closed", false, C)?;
|
||||
@@ -200,7 +204,9 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let close_tol = (tol * 4.0).max(6.0);
|
||||
// An extending stroke that ends within four Fidelities of the path's other end closes it:
|
||||
// at least 6 pt and at most 400 pt, whatever the Fidelity it is fitted at.
|
||||
let close_tol = (tol * 4.0).clamp(6.0, 400.0);
|
||||
let closing = connect.is_none() && sp.anchors.len() >= 2 && pts.last().is_some_and(|p| p.distance(first) <= close_tol);
|
||||
if closing && let Some(l) = pts.last_mut() {
|
||||
*l = first;
|
||||
|
||||
@@ -8,10 +8,22 @@ use super::{
|
||||
|
||||
// ---------- Smooth ----------
|
||||
|
||||
/// Refit the anchors of an open run `a[lo..=hi]` keeping its end points and outer handles.
|
||||
fn refit_run(anchors: &[Anchor], tol: f64) -> Vec<Anchor> {
|
||||
/// The spread (points) of the Gaussian the Smooth tool smooths a path along its length with before
|
||||
/// refitting it, as a share of the tool's reach: a third, so each point is averaged with the stretch
|
||||
/// of path within the reach on either side of it. VectorCraft's own value.
|
||||
const SMOOTH_SPREAD: f64 = 1.0 / 3.0;
|
||||
|
||||
/// The options the Smooth tool refits with: the path smoothed along its length by a Gaussian of
|
||||
/// spread `sigma` (none at 0), then refitted within `tol` of that and within twice the distance the
|
||||
/// smoothing moved it, keeping a corner only where the path turns back on itself.
|
||||
fn refit_options(tol: f64, sigma: f64) -> SimplifyOptions {
|
||||
SimplifyOptions { tolerance: tol, corner_angle_deg: 179.0, straight_lines: false, smooth: sigma, smooth_moved_only: true }
|
||||
}
|
||||
|
||||
/// Smooth and refit the anchors of an open run `a[lo..=hi]` keeping its end points and outer handles.
|
||||
fn refit_run(anchors: &[Anchor], tol: f64, sigma: f64) -> Vec<Anchor> {
|
||||
let piece = PathData::single(SubPath::new(anchors.to_vec(), false));
|
||||
let fitted = po::simplify_with(&piece, &SimplifyOptions { tolerance: tol, corner_angle_deg: 179.0, straight_lines: false, ..Default::default() });
|
||||
let fitted = po::simplify_with(&piece, &refit_options(tol, sigma));
|
||||
let Some(mut out) = fitted.subpaths.into_iter().next().map(|s| s.anchors).filter(|a| a.len() >= 2) else { return anchors.to_vec() };
|
||||
let (f, l) = (anchors[0], anchors[anchors.len() - 1]);
|
||||
let last = out.len() - 1;
|
||||
@@ -25,7 +37,7 @@ fn refit_run(anchors: &[Anchor], tol: f64) -> Vec<Anchor> {
|
||||
out
|
||||
}
|
||||
|
||||
fn smooth_subpath(sp: &SubPath, near: &dyn Fn(Point) -> bool, tol: f64) -> Option<SubPath> {
|
||||
fn smooth_subpath(sp: &SubPath, near: &dyn Fn(Point) -> bool, tol: f64, sigma: f64) -> Option<SubPath> {
|
||||
let n = sp.anchors.len();
|
||||
let marked: Vec<bool> = sp.anchors.iter().map(|a| near(a.p)).collect();
|
||||
if n < 3 || !marked.iter().any(|m| *m) {
|
||||
@@ -33,11 +45,8 @@ fn smooth_subpath(sp: &SubPath, near: &dyn Fn(Point) -> bool, tol: f64) -> Optio
|
||||
}
|
||||
if sp.closed {
|
||||
let Some(k) = marked.iter().position(|m| !m) else {
|
||||
// Everything is in range: smooth the whole closed path.
|
||||
let f = po::simplify_with(
|
||||
&PathData::single(sp.clone()),
|
||||
&SimplifyOptions { tolerance: tol, corner_angle_deg: 179.0, straight_lines: false, ..Default::default() },
|
||||
);
|
||||
// Everything is in range: smooth the whole closed path, across its start too.
|
||||
let f = po::simplify_with(&PathData::single(sp.clone()), &refit_options(tol, sigma));
|
||||
return f.subpaths.into_iter().next();
|
||||
};
|
||||
// Rotate so an untouched anchor comes first, duplicate it at the end and treat as open.
|
||||
@@ -48,14 +57,14 @@ fn smooth_subpath(sp: &SubPath, near: &dyn Fn(Point) -> bool, tol: f64) -> Optio
|
||||
open.anchors.push(open.anchors[0]);
|
||||
m.push(false);
|
||||
open.closed = false;
|
||||
let mut res = smooth_open(&open.anchors, &m, near, tol);
|
||||
let mut res = smooth_open(&open.anchors, &m, near, tol, sigma);
|
||||
let l = res.pop()?;
|
||||
if let Some(r0) = res.first_mut() {
|
||||
r0.h_in = l.h_in;
|
||||
}
|
||||
return Some(SubPath::new(res, true));
|
||||
}
|
||||
Some(SubPath::new(smooth_open(&sp.anchors, &marked, near, tol), false))
|
||||
Some(SubPath::new(smooth_open(&sp.anchors, &marked, near, tol, sigma), false))
|
||||
}
|
||||
|
||||
/// The segment `c`, which ends in the drag's reach (`near`) and starts outside it, split where it
|
||||
@@ -84,10 +93,11 @@ fn split_at_reach(c: CubicBez, near: &dyn Fn(Point) -> bool) -> Option<(CubicBez
|
||||
(hi > 0.02).then(|| (part(0.0..hi), part(hi..1.0)))
|
||||
}
|
||||
|
||||
/// `anchors` with each run of `marked` ones refitted, together with the stretch of the segments
|
||||
/// leading into the run that is in the drag's reach (`near`): a short drag smooths what is under
|
||||
/// it, and the rest of a long segment next to it stays as it was (#1512).
|
||||
fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool, tol: f64) -> Vec<Anchor> {
|
||||
/// `anchors` with each run of `marked` ones smoothed by a Gaussian of spread `sigma` and refitted
|
||||
/// within `tol`, together with the stretch of the segments leading into the run that is in the
|
||||
/// drag's reach (`near`): a short drag smooths what is under it, and the rest of a long segment next
|
||||
/// to it stays as it was (#1512).
|
||||
fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool, tol: f64, sigma: f64) -> Vec<Anchor> {
|
||||
let n = anchors.len();
|
||||
let mut runs = vec![];
|
||||
let mut i = 0;
|
||||
@@ -127,7 +137,7 @@ fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool
|
||||
head = Some(Anchor { h_out: far.p1, ..*outer });
|
||||
*outer = Anchor::with_handles(far.p3, far.p2, reach.p1);
|
||||
}
|
||||
let new = refit_run(&piece, tol);
|
||||
let new = refit_run(&piece, tol, sigma);
|
||||
out.splice(lo..=hi, head.into_iter().chain(new).chain(tail));
|
||||
}
|
||||
out
|
||||
@@ -138,6 +148,7 @@ pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let pts = points_param(p, "points", C)?;
|
||||
let radius = number_or(p, "radius", 12.0, C)?.max(0.0);
|
||||
let tol = number_or(p, "fidelity", 2.5, C)?.clamp(vectorcraft_tools::draw2::SMOOTH_MIN_FIDELITY, 100.0);
|
||||
let sigma = radius * SMOOTH_SPREAD;
|
||||
let st = s.doc()?;
|
||||
let near = |q: Point| dist_to_polyline(&pts, q) <= radius;
|
||||
let mut plan = vec![];
|
||||
@@ -148,7 +159,7 @@ pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let subs: Vec<SubPath> = pd
|
||||
.subpaths
|
||||
.iter()
|
||||
.map(|sp| match smooth_subpath(sp, &near, tol) {
|
||||
.map(|sp| match smooth_subpath(sp, &near, tol, sigma) {
|
||||
Some(n) if n != *sp && n.anchors.len() >= 2 => {
|
||||
changed = true;
|
||||
n
|
||||
@@ -167,9 +178,13 @@ pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Ok(json!({ "ids": [], "before": 0, "after": 0 }));
|
||||
}
|
||||
let ids: Vec<NodeId> = plan.iter().map(|(id, _)| *id).collect();
|
||||
s.edit("Smooth", |d, _| {
|
||||
s.edit("Smooth", |d, sel| {
|
||||
for (id, np) in plan {
|
||||
*path_mut(d, id)? = np;
|
||||
// The smoothed path has new anchors, so the old anchor and segment indices are
|
||||
// dropped and the path stays selected whole.
|
||||
sel.anchors.remove(&id);
|
||||
sel.segments.remove(&id);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
+128
-19
@@ -1,6 +1,6 @@
|
||||
//! File (document-level) and Edit commands, plus document queries.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
@@ -13,7 +13,7 @@ use super::{
|
||||
f64_req, finite_numbers, has_clipboard, has_doc, has_selection, has_selection_guides_or_artboard_tool, has_selection_or_guides, index, number_or,
|
||||
object_param, ok, point_param, str_param, switch_or,
|
||||
};
|
||||
use crate::{Clipboard, EngineError, inspect};
|
||||
use crate::{Clipboard, EngineError, SourceLayer, inspect};
|
||||
|
||||
/// Register editing commands, including document-to-document artwork drops and their parameter contracts.
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -179,7 +179,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Paste",
|
||||
["Edit"],
|
||||
Some("Cmd+V"),
|
||||
"{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers they came from (by name; made when missing). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}",
|
||||
"{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}",
|
||||
has_clipboard,
|
||||
|s, p| paste(s, p, PasteMode::Offset)
|
||||
),
|
||||
@@ -678,12 +678,22 @@ fn undo_group_end(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// under an interaction that would then preview on, or cancel to, the document from before (#1719).
|
||||
/// A typing session also ends in the Type tool, whose caret and marked text (IME) must follow the
|
||||
/// document. A preview that Real-time Drawing off left unapplied is applied first, as the tool's own
|
||||
/// commit applies it; when it fails, the interaction is canceled.
|
||||
/// commit applies it; when it fails, the interaction is canceled. The applied preview's warning
|
||||
/// goes to the running command's result or the tool's status messages, as the tool's own commit
|
||||
/// reports it ([`Session::note_settled_warning`]).
|
||||
pub(crate) fn settle_interaction(s: &mut Session) -> Result<()> {
|
||||
let typing = typing_in_progress(s);
|
||||
match s.unapplied_interaction_preview().filter(|_| !s.previewing) {
|
||||
Some((cmd, p)) if s.preview(&cmd, &p).is_err() => s.cancel_interaction()?,
|
||||
_ => s.commit_interaction()?,
|
||||
Some((cmd, p)) => match s.preview(&cmd, &p) {
|
||||
Ok(v) => {
|
||||
if let Some(w) = v.get("warning").and_then(Value::as_str) {
|
||||
s.note_settled_warning(w);
|
||||
}
|
||||
s.commit_interaction()?
|
||||
}
|
||||
Err(_) => s.cancel_interaction()?,
|
||||
},
|
||||
None => s.commit_interaction()?,
|
||||
}
|
||||
if typing {
|
||||
s.set_tool_option("endTyping", &Value::Bool(true));
|
||||
@@ -1086,7 +1096,7 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
|
||||
subpaths.extend(super::path::without_segments(sp, &cuts));
|
||||
} else {
|
||||
// Picked anchors leave the path with their connections, as Clear removes them.
|
||||
let gone: BTreeSet<usize> = anchor_refs.into_iter().flatten().filter_map(|&(s, a)| (s == si).then_some(a)).collect();
|
||||
let gone: BTreeSet<usize> = anchor_refs.into_iter().flat_map(|refs| super::path::subpath_refs(refs, si)).collect();
|
||||
subpaths.extend(super::path::without_anchors(sp, &gone));
|
||||
}
|
||||
}
|
||||
@@ -1380,6 +1390,9 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
&& inside.is_none()
|
||||
&& (st.doc.paste_remembers_layers || boards.is_some())
|
||||
&& parent.is_some_and(|p| st.doc.node(p).is_some_and(Node::is_layer));
|
||||
// Each object's remembered layer, found before anything is pasted: a hidden or locked one
|
||||
// refuses the whole paste.
|
||||
let remembered = if remember { remembered_layers(&st.doc, &clip.source_layers, same_doc)? } else { vec![] };
|
||||
// Front/back: relative to the selection (top-most / bottom-most selected object); with
|
||||
// nothing selected, the top / bottom of the current layer. Art other than paths goes beside
|
||||
// the compound path that holds the selected object, not into it.
|
||||
@@ -1423,7 +1436,8 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
.flat_map(|(all, dv)| all.iter().map(move |a| (a, dv)))
|
||||
.map(|(a, dv)| super::panelcmds::push_artboard_copy(d, a, a.rect + dv))
|
||||
.collect();
|
||||
let mut layers: BTreeMap<&str, NodeId> = BTreeMap::new();
|
||||
// The layers made for remembered layers the document lacks, by parent and name.
|
||||
let mut made = HashMap::new();
|
||||
// Objects pasted into each parent so far (keeps their order in front and back pastes).
|
||||
let mut placed: BTreeMap<Option<NodeId>, usize> = BTreeMap::new();
|
||||
let mut new_ids = vec![];
|
||||
@@ -1437,8 +1451,9 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
// including the pattern phase, independently of transform-tool settings.
|
||||
c.transform(xf, sc);
|
||||
}
|
||||
let layer = match clip.source_layers.get(k) {
|
||||
Some(Some(name)) if remember => Some(*layers.entry(name).or_insert_with(|| layer_named(d, name))),
|
||||
let layer = match remembered.get(k) {
|
||||
Some(Some(Remembered::Layer(l))) => Some(*l),
|
||||
Some(Some(Remembered::Make { parent, names })) => make_layers(d, &mut made, *parent, names)?,
|
||||
_ => None,
|
||||
};
|
||||
// In a clip group or a clipping layer the bottom child is the clipping path: art pasted
|
||||
@@ -1557,17 +1572,111 @@ fn paste_anchor(doc: &Document, id: NodeId, can_enter_compound: bool) -> NodeId
|
||||
}
|
||||
}
|
||||
|
||||
/// The first unlocked layer or sublayer called `name` (topmost first), or a new top layer.
|
||||
fn layer_named(d: &mut Document, name: &str) -> NodeId {
|
||||
let mut found = None;
|
||||
for l in d.layers.iter().rev() {
|
||||
l.walk(&mut |n| {
|
||||
if found.is_none() && n.is_layer() && !n.locked && n.name.as_deref() == Some(name) {
|
||||
found = Some(n.id);
|
||||
/// Where Paste Remembers Layers puts an object: a layer or sublayer of the document, or new
|
||||
/// layers `names`, each inside the one before, the first under `parent` (none: on top).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
enum Remembered {
|
||||
Layer(NodeId),
|
||||
Make { parent: Option<NodeId>, names: Vec<String> },
|
||||
}
|
||||
|
||||
/// [`remembered_layer`] for each object's source layer, worked out once for each layer.
|
||||
fn remembered_layers(d: &Document, sources: &[Option<SourceLayer>], same_doc: bool) -> Result<Vec<Option<Remembered>>> {
|
||||
let mut found: HashMap<&SourceLayer, Remembered> = HashMap::new();
|
||||
sources
|
||||
.iter()
|
||||
.map(|src| {
|
||||
let Some(src) = src else { return Ok(None) };
|
||||
if let Some(r) = found.get(src) {
|
||||
return Ok(Some(r.clone()));
|
||||
}
|
||||
});
|
||||
let r = remembered_layer(d, src, same_doc)?;
|
||||
found.insert(src, r.clone());
|
||||
Ok(Some(r))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The layer `src` names in `d`. In the document it was copied from, the layer that held the
|
||||
/// object is kept while it is there with its name, wherever it was moved; else the layers around
|
||||
/// it still where they were (by id) are kept. Below them, and in another document from the top,
|
||||
/// each name is matched among the layers inside the one above (the topmost of the same name whose
|
||||
/// layers match the most names, a shown and unlocked one first). The names left unmatched are
|
||||
/// made. A matched layer that is hidden or locked, or inside one that is, is an error.
|
||||
fn remembered_layer(d: &Document, src: &SourceLayer, same_doc: bool) -> Result<Remembered> {
|
||||
let held = |id: &NodeId| d.node(*id).is_some_and(|n| n.is_layer() && n.name.as_ref() == src.names.last());
|
||||
let kept = if same_doc && src.ids.last().is_some_and(held) {
|
||||
src.ids.len()
|
||||
} else if same_doc {
|
||||
(1..=src.ids.len())
|
||||
.rev()
|
||||
.find(|&j| d.node(src.ids[j - 1]).is_some_and(Node::is_layer) && d.ancestry(src.ids[j - 1]).is_some_and(|a| a == src.ids[..j]))
|
||||
.unwrap_or(0)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let rest = &src.names[kept..];
|
||||
let (end, matched, _) = named_chain(d, kept.checked_sub(1).map(|j| src.ids[j]), rest);
|
||||
if let Some(l) = end
|
||||
&& !d.ancestry(l).is_some_and(|a| a.iter().all(|i| d.node(*i).is_some_and(|n| n.visible && !n.locked)))
|
||||
{
|
||||
return Err(EngineError::Other("the target layer is locked or hidden".into()));
|
||||
}
|
||||
found.unwrap_or_else(|| d.add_layer(Some(name)))
|
||||
Ok(match end {
|
||||
Some(l) if matched == rest.len() => Remembered::Layer(l),
|
||||
parent => Remembered::Make { parent, names: rest[matched..].to_vec() },
|
||||
})
|
||||
}
|
||||
|
||||
/// The deepest chain of layers inside `parent` (none: the top level) named `names` one inside the
|
||||
/// other: its last layer (`parent` when none matches), how many names it matched and whether all
|
||||
/// its layers are shown and unlocked. Of chains as deep, the topmost shown and unlocked one wins.
|
||||
fn named_chain(d: &Document, parent: Option<NodeId>, names: &[String]) -> (Option<NodeId>, usize, bool) {
|
||||
let mut best = (parent, 0, true);
|
||||
let Some((name, rest)) = names.split_first() else { return best };
|
||||
let siblings = match parent {
|
||||
None => Some(&d.layers),
|
||||
Some(p) => d.node(p).and_then(Node::children),
|
||||
};
|
||||
for l in siblings.into_iter().flatten().rev().filter(|l| l.is_layer() && l.name.as_deref() == Some(name.as_str())) {
|
||||
let (end, n, open) = named_chain(d, Some(l.id), rest);
|
||||
let chain = (end, n + 1, open && l.visible && !l.locked);
|
||||
if (chain.1, chain.2) > (best.1, best.2) {
|
||||
best = chain;
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
/// Layers `names`, each inside the one before, the first under `parent` (none: on top); `made`
|
||||
/// keeps the ones a paste has made, by parent and name, so they are made once. The last one, or
|
||||
/// none when `names` is empty.
|
||||
fn make_layers(
|
||||
d: &mut Document,
|
||||
made: &mut HashMap<(Option<NodeId>, String), NodeId>,
|
||||
parent: Option<NodeId>,
|
||||
names: &[String],
|
||||
) -> Result<Option<NodeId>> {
|
||||
let mut at = parent;
|
||||
for name in names {
|
||||
let key = (at, name.clone());
|
||||
let id = match made.get(&key) {
|
||||
Some(id) => *id,
|
||||
None => {
|
||||
let id = match at {
|
||||
None => d.add_layer(Some(name)),
|
||||
Some(p) => {
|
||||
let layer = super::layer::make_layer(d, Some(name));
|
||||
d.insert(Some(p), usize::MAX, layer)?
|
||||
}
|
||||
};
|
||||
made.insert(key, id);
|
||||
id
|
||||
}
|
||||
};
|
||||
at = Some(id);
|
||||
}
|
||||
Ok(at.filter(|_| !names.is_empty()))
|
||||
}
|
||||
|
||||
fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -457,9 +457,10 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for (target, at) in targets.iter().copied().zip(item.per_target(s, &targets)) {
|
||||
let d = &s.doc()?.doc;
|
||||
let n = d.node(target).ok_or(EngineError::NoNode(target))?;
|
||||
// A new effect goes after the item's others.
|
||||
// A new effect goes after the item's (or the object's) others.
|
||||
let on = at.and_then(|at| at.effects_item(&n.appearance, C).ok()).flatten();
|
||||
let on = on.and_then(|i| Some((i, n.appearance.items.get(i)?.effects().len())));
|
||||
let on = on.and_then(|i| Some((Some(i), n.appearance.items.get(i)?.effects().len())));
|
||||
let on = on.unwrap_or((None, n.appearance.effects.len()));
|
||||
effects::validate_three_d_at_in(Some(d), n, id, &effect.params, on).map_err(|e| bad(C, e))?;
|
||||
if let Some(name) = effects::missing_symbol(d, &effect.params, None) {
|
||||
return Err(bad(C, format!("no symbol named `{name}`")));
|
||||
@@ -786,7 +787,7 @@ fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, format!("no symbol named `{name}`")));
|
||||
}
|
||||
if visible != Some(false) {
|
||||
effects::validate_three_d_at_in(Some(d), n, to, &prospective, target.map(|item| (item, index))).map_err(|e| bad(C, e))?;
|
||||
effects::validate_three_d_at_in(Some(d), n, to, &prospective, (target, index)).map_err(|e| bad(C, e))?;
|
||||
} else {
|
||||
// Hidden, the effect draws nothing, so its object need not fit. The values given are
|
||||
// checked, and after a change of 3D type so is every value it keeps.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Window › 3D and Materials › Materials › Graphics: art kept as a document symbol (Add as Single
|
||||
//! Graphic) and mapped onto the planar faces of 3D objects (Extrude & Bevel's caps, a plane). The
|
||||
//! Graphic) and mapped onto 3D objects (Extrude & Bevel's caps, a plane, Revolve's side). The
|
||||
//! graphics an object shows are the `graphics` parameter of its 3D effect, which `effect.setParams`
|
||||
//! also edits.
|
||||
|
||||
@@ -28,7 +28,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"Map Graphic",
|
||||
[],
|
||||
None,
|
||||
"{symbol: name of a document symbol, face?: front|back (front; Plane has only a front; the back reads left to right as seen from behind), x?: pt, y?: pt (0, 0: the offset of the graphic's center from the center of the object's bounds, in the face's own plane), scale?: % (1..10000; default 100, or less so the graphic fits inside the object), rotation?: degrees (-360..360, 0; counterclockwise), index?: int (the 3D effect's position; default: each object's first 3D effect, its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} add a graphic to the 3D effect of each selected object, drawn on that face turned, foreshortened and shaded with it and clipped to it; every object's 3D effect must be Extrude & Bevel (on a solid cap) or Rotate (the Plane type); one undo step → {ids, graphic}",
|
||||
"{symbol: name of a document symbol, face?: front|back (front; Plane has only a front; the back reads left to right as seen from behind; on Revolve the front is its swept side, which is the only face), x?: pt, y?: pt (0, 0: the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on Revolve from the middle of the side unrolled flat, x around the axis and y along the profile), scale?: % (1..10000; default 100, or less so the graphic fits inside the object, on Revolve inside the half of the side seen from the front), rotation?: degrees (-360..360, 0; counterclockwise), index?: int (the 3D effect's position; default: each object's first 3D effect, its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} add a graphic to the 3D effect of each selected object, drawn on that face turned, foreshortened and shaded with it and clipped to it (on Revolve wrapped around the side, and drawn only where its outside faces the viewer); every object's 3D effect must be Extrude & Bevel (on a solid cap), Rotate (the Plane type) or Revolve; one undo step → {ids, graphic}",
|
||||
has_doc,
|
||||
map_graphic
|
||||
),
|
||||
@@ -111,7 +111,7 @@ fn map_graphic(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, format!("object {} needs a 3D effect at index {index}", id.0)));
|
||||
};
|
||||
if !effects::takes_graphics(&effect.id) {
|
||||
return Err(bad(C, format!("object {}: Graphics map onto planar faces: use the Extrude or Plane object type", id.0)));
|
||||
return Err(bad(C, format!("object {}: {}", id.0, effects::GRAPHICS_NOT_TAKEN)));
|
||||
}
|
||||
// A hollow Extrude & Bevel keeps the graphics it has, to show when Cap is turned on again,
|
||||
// but has no cap to show a new one on.
|
||||
@@ -131,7 +131,7 @@ fn map_graphic(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
graphic.scale = frame.fitting_scale(art);
|
||||
}
|
||||
let params = effects::with_graphic(&effects::merged_params(&effect.id, &effect.params), &graphic);
|
||||
effects::validate_three_d_at_in(Some(d), n, &effect.id, ¶ms, item.map(|i| (i, index))).map_err(|e| bad(C, e))?;
|
||||
effects::validate_three_d_at_in(Some(d), n, &effect.id, ¶ms, (item, index)).map_err(|e| bad(C, e))?;
|
||||
edits.push((id, item, index, graphic));
|
||||
}
|
||||
let first = edits.first().map(|(.., g)| g.to_value());
|
||||
|
||||
@@ -68,12 +68,37 @@ fn a_large_graphic_starts_inside_its_object() {
|
||||
assert!((scale - 100.0 * 100.0 / 401.0).abs() < 1e-9, "{scale}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn map_graphic_puts_a_graphic_on_the_side_of_a_revolve() {
|
||||
let (mut s, id) = setup("threeD.revolve");
|
||||
let plain = vectorcraft_render::effects::revolve_art_in(Some(&s.doc().unwrap().doc), s.doc().unwrap().doc.node(id).unwrap());
|
||||
let history = undo_len(&s);
|
||||
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).unwrap();
|
||||
assert_eq!(graphics(&s, id), json!([{"symbol": "Mark", "face": "front", "x": 0.0, "y": 0.0, "scale": 100.0, "rotation": 0.0}]));
|
||||
assert_eq!(undo_len(&s), history + 1);
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_ne!(vectorcraft_render::effects::revolve_art_in(Some(d), d.node(id).unwrap()), plain, "the graphic is drawn");
|
||||
// A large graphic starts inside the half of the side seen from the front: 100π around the
|
||||
// axis (the square's far edge is 100 from it) and 300 along the profile (its edge on the axis
|
||||
// sweeps nothing).
|
||||
let big = s.execute("path.create", &json!({"d":"M0 0L400 0L400 200L0 200Z"})).unwrap()["id"].clone();
|
||||
s.execute("threeD.addGraphic", &json!({"name": "Big", "ids": [big]})).unwrap();
|
||||
s.execute("threeD.mapGraphic", &json!({"symbol": "Big", "ids": [id.0]})).unwrap();
|
||||
let scale = graphics(&s, id)[1]["scale"].as_f64().unwrap();
|
||||
assert!((scale - 100.0 * 100.0 * std::f64::consts::PI / 401.0).abs() < 1e-6, "{scale}");
|
||||
// The side is its only face.
|
||||
let history = undo_len(&s);
|
||||
let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "back", "ids": [id.0]})).unwrap_err().to_string();
|
||||
assert!(e.contains("side"), "{e}");
|
||||
assert_eq!(undo_len(&s), history);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn map_graphic_refuses_what_cannot_take_it_and_changes_nothing() {
|
||||
let (mut s, id) = setup("threeD.inflate");
|
||||
let history = undo_len(&s);
|
||||
let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).unwrap_err().to_string();
|
||||
assert!(e.contains("Extrude or Plane"), "{e}");
|
||||
assert!(e.contains("Plane, Extrude and Revolve"), "{e}");
|
||||
let (mut s, id) = setup("threeD.rotate");
|
||||
for (p, says) in [
|
||||
(json!({"symbol": "Gone"}), "no symbol named"),
|
||||
|
||||
@@ -169,6 +169,44 @@ fn solid_effects_apply_to_a_group_and_its_members_stay_editable() {
|
||||
assert_eq!(s.doc().unwrap().doc, before, "nothing changed");
|
||||
}
|
||||
|
||||
/// Extrude & Bevel is refused, and nothing changes, on a path whose fill's and strokes' solids each
|
||||
/// fit but together pass the limit of their faces; with one stroke the effect applies.
|
||||
#[test]
|
||||
fn extrude_is_refused_when_its_solids_together_are_too_complex() {
|
||||
use vectorcraft_doc::color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem};
|
||||
let (mut s, id) = session_with_rect();
|
||||
let points: Vec<vectorcraft_geom::Point> = (0..16_384)
|
||||
.map(|k| {
|
||||
let (sin, cos) = (k as f64 * std::f64::consts::TAU / 16_384.0).sin_cos();
|
||||
vectorcraft_geom::Point::new(20_000.0 + 10_000.0 * cos, 20_000.0 + 10_000.0 * sin)
|
||||
})
|
||||
.collect();
|
||||
let polygon = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&points, true));
|
||||
let painted = |strokes: usize| {
|
||||
let mut items = Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0).items;
|
||||
let stroke = AppearanceItem::Stroke(vectorcraft_doc::StrokeLayer::new(Paint::solid(Color::WHITE), 20.0));
|
||||
items.extend(std::iter::repeat_n(stroke, strokes));
|
||||
items
|
||||
};
|
||||
let set = |s: &mut Session, strokes: usize| {
|
||||
let n = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap();
|
||||
let NodeKind::Path { path, live, .. } = &mut n.kind else { panic!("a path") };
|
||||
*path = polygon.clone();
|
||||
*live = None;
|
||||
n.appearance.items = painted(strokes);
|
||||
};
|
||||
// The fill's solid and each stroke's fit on their own; sixty strokes' together do not.
|
||||
set(&mut s, 60);
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let err = s.execute("effect.apply", &json!({"effect": "threeD.extrude", "ids": [id.0], "item": null})).unwrap_err().to_string();
|
||||
assert!(err.contains("The 3D surface is too complex; simplify the shape"), "{err}");
|
||||
assert_eq!(s.doc().unwrap().doc, before, "nothing changed");
|
||||
set(&mut s, 1);
|
||||
s.execute("effect.apply", &json!({"effect": "threeD.extrude", "ids": [id.0], "item": null})).unwrap();
|
||||
assert!(effects::solid_art(&node(&s, id)).is_some());
|
||||
}
|
||||
|
||||
/// A group of a clipping group (a rectangle clipped by an ellipse) and a rectangle: the session,
|
||||
/// the clipping group and the group.
|
||||
fn group_with_a_clipping_group() -> (Session, NodeId, NodeId) {
|
||||
|
||||
@@ -18,8 +18,8 @@ use vectorcraft_color::{BlendMode, Color, Gradient, GradientKind, GradientPaint,
|
||||
use vectorcraft_doc::appearance::{AppearanceItem, FillLayer};
|
||||
use vectorcraft_doc::live::GradientMesh;
|
||||
use vectorcraft_doc::pattern::{PatternDef, place_art};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, Scaling};
|
||||
use vectorcraft_geom::{Affine, PathData, Point, Rect, SubPath, Vec2, shapes};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, Scaling, TextObject};
|
||||
use vectorcraft_geom::{Affine, BezPath, PathData, Point, Rect, SubPath, Vec2, shapes};
|
||||
|
||||
use super::dimension::EndedLink;
|
||||
use super::edit::selected_roots;
|
||||
@@ -56,7 +56,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Expand Options",
|
||||
[],
|
||||
None,
|
||||
"{} what each Expand option would change in the selection → {object, fill, stroke, gradient, appearance, symbolArt?: {fill, stroke, gradient}} (true: something to expand; gradient: a gradient fill that Fill expands, which Expand Gradient To applies to; appearance: appearance attributes Expand Appearance expands first, for which Object › Expand… is dimmed in the menus; symbolArt, when the selection holds symbol instances that Object expands: true when only their art holds it, which Fill and Stroke reach only with Object on)",
|
||||
"{} what each Expand option would change in the selection → {object, fill, stroke, gradient, appearance, symbolArt?: {fill, stroke, gradient}} (true: something to expand; gradient: a gradient fill that Fill expands (in type, on the outline Object makes of a character), which Expand Gradient To applies to; appearance: appearance attributes Expand Appearance expands first, for which Object › Expand… is dimmed in the menus; symbolArt, when the selection holds symbol instances that Object expands: true when only their art holds it, which Fill and Stroke reach only with Object on)",
|
||||
has_selection,
|
||||
|s, _| {
|
||||
let roots = selected_roots(s)?;
|
||||
@@ -197,7 +197,7 @@ impl Expandable {
|
||||
// Once one is found, the next path is not measured.
|
||||
e.gradient = e.gradient
|
||||
|| match &c.kind {
|
||||
NodeKind::Text(t) => t.runs.iter().any(|r| matches!(r.style.fill, Paint::Gradient(_))),
|
||||
NodeKind::Text(t) => text_gradient_expands(d, t),
|
||||
_ => shape && gradient_expands(d, c),
|
||||
};
|
||||
e.fill |= e.gradient;
|
||||
@@ -247,6 +247,34 @@ fn gradient_expands(d: &Document, l: &Node) -> bool {
|
||||
any
|
||||
}
|
||||
|
||||
/// Whether type `t` has a gradient fill that Fill expands once Object has outlined it: one of the
|
||||
/// paths `type.createOutlines` makes of its glyphs, ruby glyphs and underline and strikethrough
|
||||
/// bars, each painted as its run, has one ([`gradient_expands`] on that path's own box). Inline
|
||||
/// graphics and color glyphs become other art. Leaves the document as it is and stops at the
|
||||
/// first such path.
|
||||
fn text_gradient_expands(d: &Document, t: &TextObject) -> bool {
|
||||
if !t.runs.iter().any(|r| matches!(r.style.fill, Paint::Gradient(_))) {
|
||||
return false;
|
||||
}
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
let expands = |run: usize, outline: &BezPath| {
|
||||
let style = t.runs.get(run).map(|r| &r.style);
|
||||
if !matches!(style.map_or_else(|| t.first_style().fill, |s| s.fill.clone()), Paint::Gradient(_)) {
|
||||
return false;
|
||||
}
|
||||
let path = PathData::from_bezpath(outline).transformed(t.xf);
|
||||
if path.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let appearance = style.map_or_else(|| t.first_style().appearance(), |s| s.appearance());
|
||||
gradient_expands(d, &Node::path(NodeId(u64::MAX), path, appearance))
|
||||
};
|
||||
let inline = |gi: usize| lay.inlines.iter().find(|i| i.glyph == gi).is_some_and(|i| t.runs.get(i.run).is_some_and(|r| r.inline.is_some()));
|
||||
lay.glyphs.iter().enumerate().any(|(gi, g)| !inline(gi) && g.image.is_none() && g.colour.is_none() && expands(g.run, &g.outline))
|
||||
|| lay.ruby.iter().any(|g| expands(g.run, &g.outline))
|
||||
|| vectorcraft_text::decorations(&lay, vectorcraft_text::FontDb::global(), t).iter().any(|(run, bar)| expands(*run, bar))
|
||||
}
|
||||
|
||||
/// [`gradient_expands`] for a path that no live-effect plug-in paints ([`expand_piece_fills`]).
|
||||
fn piece_gradient_expands(d: &Document, l: &Node) -> bool {
|
||||
if !l.appearance.items.iter().filter_map(gradient_fill).any(|(_, g)| g.gradient.is_spread()) {
|
||||
|
||||
@@ -41,6 +41,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
roll_back(s, start, &stash);
|
||||
s.notify_text_tool("batch.rollBack");
|
||||
s.active = active;
|
||||
s.sync_front_profiles();
|
||||
(s.paint, s.fill_active, s.draw_mode, s.draw_inside, s.clipboard, s.untitled_counter, s.explicit_undo_group) = saved;
|
||||
s.pending_paint = None;
|
||||
return Err(e);
|
||||
@@ -78,8 +79,11 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// `artboard`, as the Artboards panel shows it in the document the step runs in: past that
|
||||
/// document's last artboard, the last one; a Paste in Place, in Front or in Back step that names
|
||||
/// `artboards` keeps them, and one that names neither, while the Artboard tool is chosen with
|
||||
/// several artboards selected, pastes on those. A step that resizes the active artboard
|
||||
/// ([`crate::FIT_ACTIVE_ARTBOARD`]) and names no `index` gets that artboard as its `index`.
|
||||
/// several artboards selected, pastes on those. A Fit to Artwork Bounds step that names neither
|
||||
/// `index` nor `indices`, while the Artboard tool is chosen with several artboards selected when the
|
||||
/// step runs, gets those as its `indices`, which its journal entry records. Otherwise a step that
|
||||
/// resizes the active artboard ([`crate::FIT_ACTIVE_ARTBOARD`]) and names no `index` (nor
|
||||
/// `indices`, for Fit to Artwork Bounds) gets that artboard as its `index`.
|
||||
/// `grouped` gets each step's undo groups, as [`Session::batch_steps`] keeps them.
|
||||
fn run_steps(
|
||||
s: &mut Session,
|
||||
@@ -110,9 +114,22 @@ fn run_steps(
|
||||
// Artboard tool is chosen with several artboards selected, pastes on those.
|
||||
let names_artboards = id.starts_with("edit.pasteIn")
|
||||
&& (params.get("artboards").is_some() || (params.get("artboard").is_none() && !crate::cmd::edit::artboard_tool_picks(s).is_empty()));
|
||||
// A Fit to Artwork Bounds step that names neither `index` nor `indices`, while the Artboard
|
||||
// tool is chosen with several artboards selected, fits those, as the command does on its own.
|
||||
let fit_picks = if id == "artboard.fitToArt" && params.get("index").is_none() && params.get("indices").is_none() {
|
||||
crate::cmd::edit::artboard_tool_picks(s)
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
if !fit_picks.is_empty()
|
||||
&& let Some(o) = params.as_object_mut()
|
||||
{
|
||||
o.insert("indices".into(), json!(fit_picks));
|
||||
}
|
||||
if let Some(a) = artboard
|
||||
&& let Some(key) = key
|
||||
&& params.get(key).is_none()
|
||||
&& !(id == "artboard.fitToArt" && params.get("indices").is_some())
|
||||
&& !names_artboards
|
||||
&& let Some(last) = s.active().and_then(|d| d.doc.artboards.len().checked_sub(1))
|
||||
&& let Some(o) = params.as_object_mut()
|
||||
@@ -129,8 +146,9 @@ fn run_steps(
|
||||
}
|
||||
grouped.push(step_groups(s, start, &held));
|
||||
// The step's journal entry records what it took from the preferences or the clock (a
|
||||
// save's date, a new document's), as a command of its own would.
|
||||
if noted != params
|
||||
// save's date, a new document's), as a command of its own would, and the artboards a Fit to
|
||||
// Artwork Bounds step took from the Artboard tool.
|
||||
if (noted != params || !fit_picks.is_empty())
|
||||
&& let Some(c) = c.as_object_mut()
|
||||
{
|
||||
c.insert("params".into(), noted);
|
||||
|
||||
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the visible art), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the
Line truncated
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the visible art), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditabilit
Line truncated
|
||||
has_doc,
|
||||
export::export
|
||||
),
|
||||
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Batch",
|
||||
[],
|
||||
None,
|
||||
"{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing, select.allOnArtboard or symbol.edit step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included",
|
||||
"{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing, select.allOnArtboard or symbol.edit step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer; an artboard.fitToArt step that names neither index nor indices, while the Artboard tool is chosen with several artboards selected when the step runs, gets those as indices instead, and the journal records them)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included",
|
||||
has_doc,
|
||||
batch::batch
|
||||
),
|
||||
|
||||
@@ -629,6 +629,13 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
{
|
||||
return Ok(Encoded::one_with_notes(bytes, notes));
|
||||
}
|
||||
// So does a `.ai` file of the art's bounds (a legacy version 7 `.ai` file has none to leave out).
|
||||
if use_artboards == Some(false)
|
||||
&& f.id == "ai"
|
||||
&& let Some(enc) = super::save::encode_ai_art_page(C, f, doc, p)?
|
||||
{
|
||||
return Ok(enc);
|
||||
}
|
||||
if use_artboards == Some(false)
|
||||
&& let Some((art, q)) = art_page(C, doc, p)?
|
||||
{
|
||||
|
||||
@@ -868,9 +868,12 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option<String> {
|
||||
/// A TIFF with more strips or tiles than the decoder can count
|
||||
/// ([`vectorcraft_doc::cmyk::oversized_tiff`]) is refused as too large to draw. JPEG XL images are
|
||||
/// read with [`jxlread`] and stored as PNG, with the ICC profile their colors are left in.
|
||||
/// A PNG, JPEG, GIF, WebP or TIFF whose orientation ([`exif_orientation`]) turns or flips it is
|
||||
/// A PNG, JPEG, GIF, WebP or TIFF whose orientation ([`vectorcraft_doc::cmyk::exif_orientation`]) turns or flips it is
|
||||
/// stored as it is shown, with its resolution's axes swapped when it turns a quarter; a CMYK JPEG
|
||||
/// or TIFF keeps its inks, 8 bits each, as a CMYK TIFF ([`vectorcraft_doc::cmyk::turned_cmyk`]).
|
||||
/// or TIFF keeps its inks, at the 8 or 16 bits the file has, and its CMYK ICC profile as a CMYK
|
||||
/// TIFF ([`vectorcraft_doc::cmyk::turned_cmyk`]). An image the decoder reads and that is stored as
|
||||
/// PNG keeps its gray or RGB samples at 8 or 16 bits, and the gray or RGB ICC profile they are in;
|
||||
/// other samples become 8-bit RGBA.
|
||||
pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
|
||||
let ppi = super::ppi::resolution(bytes);
|
||||
if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) {
|
||||
@@ -909,7 +912,7 @@ pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
|
||||
let f = image_format(kind).ok_or_else(|| err(format!("{kind:?} images can't be opened (see document.formats)")))?;
|
||||
// A photo whose EXIF orientation turns or flips it (a camera held upright) is stored as it is
|
||||
// seen, so it places the way it was taken (#4284); the others keep their own bytes.
|
||||
let orientation = matches!(f.id, "png" | "jpg" | "gif" | "webp" | "tiff").then(|| exif_orientation(bytes)).flatten();
|
||||
let orientation = matches!(f.id, "png" | "jpg" | "gif" | "webp" | "tiff").then(|| vectorcraft_doc::cmyk::exif_orientation(bytes)).flatten();
|
||||
let turned = orientation.is_some();
|
||||
// The resolution describes the stored pixels; a quarter turn swaps its axes.
|
||||
let quarter = orientation.is_some_and(|o| o.to_exif() >= 5);
|
||||
@@ -933,47 +936,60 @@ pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
vectorcraft_doc::cmyk::extra_samples_tiff_rgba(bytes, |c| cms.cmyk_to_srgb(c, false))
|
||||
};
|
||||
// The ICC profile of the samples the image decoder reads; the other readers give sRGB pixels.
|
||||
let mut icc = None;
|
||||
let mut img = match (f.id == "tiff").then(extra_samples).flatten() {
|
||||
Some(img) => image::DynamicImage::ImageRgba8(img),
|
||||
None => match (f.id == "tiff").then(|| vectorcraft_doc::cmyk::group3_tiff_rgba(bytes)).flatten() {
|
||||
Some(read) => image::DynamicImage::ImageRgba8(read.map_err(err)?),
|
||||
None => {
|
||||
use image::ImageDecoder as _;
|
||||
let decoder = reader.into_decoder().map_err(err)?;
|
||||
let mut decoder = reader.into_decoder().map_err(err)?;
|
||||
// The allowance counts the decoded samples and the RGBA pixels they become (#1717).
|
||||
let (w, h) = decoder.dimensions();
|
||||
if decoder.total_bytes() > MAX_RASTER_ALLOC || u64::from(w) * u64::from(h) * 4 > MAX_RASTER_ALLOC {
|
||||
return Err(err(format!("an image of {w} × {h} pixels is too large to draw")));
|
||||
}
|
||||
// A profile the decoder can't read leaves the image without one. The image decoder
|
||||
// reads a TIFF's tags within the size of its pixels, so a small TIFF's profile is
|
||||
// read by the TIFF decoder itself.
|
||||
icc = match f.id {
|
||||
"tiff" => vectorcraft_doc::cmyk::tiff_icc_profile(bytes),
|
||||
_ => decoder.icc_profile().ok().flatten(),
|
||||
};
|
||||
image::DynamicImage::from_decoder(decoder).map_err(err)?
|
||||
}
|
||||
},
|
||||
};
|
||||
img.apply_orientation(orientation.unwrap_or(image::metadata::Orientation::NoTransforms));
|
||||
let mut img = img.into_rgba8();
|
||||
if f.id == "tga" {
|
||||
let mut img = img.into_rgba8();
|
||||
super::tgaread::fix_alpha(bytes, &mut img);
|
||||
return as_png(img, None, shown_ppi);
|
||||
}
|
||||
as_png(img, None, shown_ppi)
|
||||
use image::DynamicImage as D;
|
||||
let img = match img {
|
||||
D::ImageLuma8(_) | D::ImageLumaA8(_) | D::ImageRgb8(_) | D::ImageRgba8(_) => img,
|
||||
D::ImageLuma16(_) | D::ImageLumaA16(_) | D::ImageRgb16(_) | D::ImageRgba16(_) => img,
|
||||
other => D::ImageRgba8(other.into_rgba8()),
|
||||
};
|
||||
let icc = icc.filter(|icc| png_takes_icc(&img, icc));
|
||||
as_png(img, icc, shown_ppi)
|
||||
}
|
||||
|
||||
/// The EXIF orientation of encoded image `bytes` when it turns or flips the pixels; `None` when
|
||||
/// it leaves them as stored, or the image has none. A TIFF the image decoder can't open (one with
|
||||
/// extra samples) has its Orientation tag read from its first image
|
||||
/// ([`vectorcraft_doc::cmyk::tiff_orientation`]).
|
||||
pub(crate) fn exif_orientation(bytes: &[u8]) -> Option<image::metadata::Orientation> {
|
||||
use image::ImageDecoder as _;
|
||||
use image::metadata::Orientation;
|
||||
let decoded = || image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?.into_decoder().ok()?.orientation().ok();
|
||||
let tagged = || vectorcraft_doc::cmyk::tiff_orientation(bytes).and_then(|v| Orientation::from_exif(u8::try_from(v).ok()?));
|
||||
decoded().or_else(tagged).filter(|o| *o != Orientation::NoTransforms)
|
||||
/// Can a PNG of `img`'s samples carry ICC profile `icc`? Its color space must be the samples':
|
||||
/// `GRAY` for gray samples, `RGB ` for RGB ones.
|
||||
fn png_takes_icc(img: &image::DynamicImage, icc: &[u8]) -> bool {
|
||||
let want = if img.color().has_color() { *b"RGB " } else { *b"GRAY" };
|
||||
vectorcraft_doc::cmyk::icc_color_space(icc) == Some(want)
|
||||
}
|
||||
|
||||
/// `img` stored as a PNG that keeps the file's resolution and carries `icc`, the ICC profile its
|
||||
/// colors are in.
|
||||
pub(super) fn as_png(img: image::RgbaImage, icc: Option<Vec<u8>>, ppi: Option<(f64, f64)>) -> Result<RasterImage> {
|
||||
/// colors are in. `img` has samples a PNG holds: 8 or 16 bits of gray or RGB, with or without alpha.
|
||||
pub(super) fn as_png(img: impl Into<image::DynamicImage>, icc: Option<Vec<u8>>, ppi: Option<(f64, f64)>) -> Result<RasterImage> {
|
||||
use image::ImageEncoder as _;
|
||||
let size = img.dimensions();
|
||||
let img: image::DynamicImage = img.into();
|
||||
let size = (img.width(), img.height());
|
||||
let mut png = Vec::new();
|
||||
let mut encoder = image::codecs::png::PngEncoder::new(&mut png);
|
||||
if let Some(icc) = icc {
|
||||
|
||||
@@ -98,8 +98,8 @@ pub(crate) const OPTIONS: &[FormatOption] = &[
|
||||
FormatOption {
|
||||
name: "longPagesInPoints",
|
||||
ty: "boolean",
|
||||
default: "false",
|
||||
description: "a page with a side longer than 14,400 pt (200 in) is written at its size in points, without a UserUnit, at every PDF version, in files without a standard (PDF/A files keep the UserUnit)",
|
||||
default: "true",
|
||||
description: "a page with a side longer than 14,400 pt (200 in) is written at its size in points, without a UserUnit, at every PDF version, in files without a standard (PDF/A files keep the UserUnit); false writes it with a UserUnit from PDF 1.6 on",
|
||||
},
|
||||
FormatOption {
|
||||
name: "createLayers",
|
||||
@@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export PDF",
|
||||
[],
|
||||
None,
|
||||
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art, as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: false (true: such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdf
Line truncated
|
||||
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art, as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMY
Line truncated
|
||||
has_doc,
|
||||
export_pdf
|
||||
),
|
||||
|
||||
@@ -685,6 +685,31 @@ struct AiEditingData {
|
||||
editing_data: Option<bool>,
|
||||
}
|
||||
|
||||
/// Why a `.ai` file of the art's bounds (`useArtboards: false`) carries no editing data.
|
||||
pub const AI_EDITING_NEEDS_THE_ARTBOARDS: &str =
|
||||
"Preserve editing was left out: an .ai file of the art's bounds would replace the document's artboards when reopened";
|
||||
|
||||
/// The error for a `.ai` file of the art's bounds without PDF content.
|
||||
pub const ART_PAGE_NEEDS_PDF: &str = "pdfCompatible: false needs the artboards to keep the editable artwork when useArtboards is false";
|
||||
|
||||
/// With `useArtboards: false` in `p`: the PDF-compatible `.ai` file of one page, the bounds of
|
||||
/// `doc`'s visible art ([`super::encode::art_page`]). It carries neither the native document nor
|
||||
/// the editing copy for other apps, and its notes end with [`AI_EDITING_NEEDS_THE_ARTBOARDS`].
|
||||
/// `pdfCompatible: false` is refused. `None` when `p` asks for the artboards or for a legacy
|
||||
/// version 7 `.ai` file.
|
||||
pub(super) fn encode_ai_art_page(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result<Option<Encoded>> {
|
||||
if super::encode::use_artboards(cmd, p)? != Some(false) || super::legacy_ai::wanted(cmd, f, p)? {
|
||||
return Ok(None);
|
||||
}
|
||||
if !bool_or(p, "pdfCompatible", true) {
|
||||
return Err(bad(cmd, ART_PAGE_NEEDS_PDF));
|
||||
}
|
||||
let Some((art, q)) = super::encode::art_page(cmd, doc, p)? else { return Ok(None) };
|
||||
let mut enc = encode_ai_pages(cmd, f, &art, &q, false)?;
|
||||
enc.setting_notes.push(AI_EDITING_NEEDS_THE_ARTBOARDS.to_string());
|
||||
Ok(Some(enc))
|
||||
}
|
||||
|
||||
/// The shared Save and Export encoder for `.ai` files (and `.ait` templates, the same file):
|
||||
/// PDF-compatible by default, without PDF content (`pdfCompatible: false`), or legacy version 7
|
||||
/// `.ai` files (`aiVersion: "7"`).
|
||||
@@ -692,13 +717,23 @@ pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Res
|
||||
if super::legacy_ai::wanted(cmd, f, p)? {
|
||||
return super::legacy_ai::encode(cmd, f, doc, p);
|
||||
}
|
||||
encode_ai_pages(cmd, f, doc, p, true)
|
||||
}
|
||||
|
||||
/// [`encode_ai`] of a `.ai` file with or without PDF content, carrying the native document and
|
||||
/// the editing copy for other apps when `editing` is true, and neither otherwise.
|
||||
fn encode_ai_pages(cmd: &str, f: &Format, doc: &Document, p: &Value, editing: bool) -> Result<Encoded> {
|
||||
let mut params = if p.is_object() { p.clone() } else { json!({}) };
|
||||
if let Some(o) = params.as_object_mut() {
|
||||
o.insert("preserveEditing".into(), json!(true));
|
||||
o.insert("preserveEditing".into(), json!(editing));
|
||||
// Keep upstream AI PDF layers, including hidden layers, unless a standard decides.
|
||||
if o.get("standard").is_none_or(Value::is_null) {
|
||||
o.entry("createLayers").or_insert(json!(true));
|
||||
}
|
||||
// A page longer than 14,400 pt keeps its `UserUnit` (PDF export writes it in points).
|
||||
if o.get("longPagesInPoints").is_none_or(Value::is_null) {
|
||||
o.insert("longPagesInPoints".into(), json!(false));
|
||||
}
|
||||
if let Some(c) = o.get("compress").and_then(Value::as_bool) {
|
||||
let compression = o.entry("compression").or_insert_with(|| json!({}));
|
||||
if let Some(m) = compression.as_object_mut() {
|
||||
|
||||
@@ -1171,6 +1171,216 @@ fn png_webp_and_rgb_tiff_turned_a_quarter_swap_their_resolution() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A made-up ICC profile of `len` bytes (at least a header's 128) whose header names the color
|
||||
/// space `space`; the bytes after the header differ from place to place.
|
||||
fn icc_profile(space: &[u8; 4], len: usize) -> Vec<u8> {
|
||||
let mut icc: Vec<u8> = (0..len).map(|i| (i % 251) as u8).collect();
|
||||
icc[..4].copy_from_slice(&u32::try_from(len).unwrap().to_be_bytes());
|
||||
icc[12..16].copy_from_slice(b"mntr");
|
||||
icc[16..20].copy_from_slice(space);
|
||||
icc[36..40].copy_from_slice(b"acsp");
|
||||
icc
|
||||
}
|
||||
|
||||
/// `tiff` (little-endian) with an ICCProfile tag (34675, of type UNDEFINED) holding `icc`: its first
|
||||
/// directory copied to the end of the file with the tag added in order, as [`tiff_oriented`] adds
|
||||
/// its tag.
|
||||
fn tiff_with_icc(tiff: &[u8], icc: &[u8]) -> Vec<u8> {
|
||||
let at = usize::try_from(u32::from_le_bytes(tiff[4..8].try_into().unwrap())).unwrap();
|
||||
let n = usize::from(u16::from_le_bytes([tiff[at], tiff[at + 1]]));
|
||||
let mut entries: Vec<Vec<u8>> = tiff[at + 2..at + 2 + 12 * n].chunks(12).map(<[u8]>::to_vec).collect();
|
||||
let mut out = tiff.to_vec();
|
||||
if out.len() % 2 == 1 {
|
||||
out.push(0);
|
||||
}
|
||||
let data = u32::try_from(out.len()).unwrap();
|
||||
out.extend(icc);
|
||||
if out.len() % 2 == 1 {
|
||||
out.push(0);
|
||||
}
|
||||
let i = entries.iter().position(|e| u16::from_le_bytes([e[0], e[1]]) > 34675).unwrap_or(n);
|
||||
let count = u32::try_from(icc.len()).unwrap();
|
||||
entries.insert(i, [&34675u16.to_le_bytes()[..], &7u16.to_le_bytes(), &count.to_le_bytes(), &data.to_le_bytes()].concat());
|
||||
let ifd = u32::try_from(out.len()).unwrap();
|
||||
out[4..8].copy_from_slice(&ifd.to_le_bytes());
|
||||
out.extend(u16::try_from(n + 1).unwrap().to_le_bytes());
|
||||
out.extend(entries.concat());
|
||||
out.extend([0; 4]);
|
||||
out
|
||||
}
|
||||
|
||||
/// The ICC profile and pixels of a stored image, read by the image decoder for its format.
|
||||
fn stored_pixels(what: &str, img: &RasterImage) -> (Option<Vec<u8>>, image::ExtendedColorType, image::DynamicImage) {
|
||||
use image::ImageDecoder as _;
|
||||
let bytes = Cursor::new(img.blob.bytes.as_slice());
|
||||
let mut d: Box<dyn image::ImageDecoder> = match img.blob.mime.as_str() {
|
||||
"image/png" => Box::new(image::codecs::png::PngDecoder::new(bytes).unwrap()),
|
||||
"image/tiff" => Box::new(image::codecs::tiff::TiffDecoder::new(bytes).unwrap()),
|
||||
other => panic!("{what}: stored as {other}"),
|
||||
};
|
||||
let icc = d.icc_profile().unwrap();
|
||||
let color = d.original_color_type();
|
||||
(icc, color, image::DynamicImage::from_decoder(d).unwrap())
|
||||
}
|
||||
|
||||
/// An image turned by its orientation and stored as PNG keeps the gray or RGB ICC profile its file
|
||||
/// carries, and its 16-bit samples at 16 bits, from a PNG, a JPEG, a WebP and a TIFF; a TIFF the
|
||||
/// image decoder reads, stored as PNG without a turn, keeps them too. A profile of another color
|
||||
/// space than the samples' is left out.
|
||||
#[test]
|
||||
fn images_stored_as_png_keep_their_icc_profile_and_16_bit_samples() {
|
||||
use image::{DynamicImage, ImageEncoder as _};
|
||||
let (rgb_icc, gray_icc, cmyk_icc) = (icc_profile(b"RGB ", 600), icc_profile(b"GRAY", 300), icc_profile(b"CMYK", 400));
|
||||
// 3 × 2, every sample's low byte different.
|
||||
let rgb16 = image::ImageBuffer::from_fn(3, 2, |x, y| {
|
||||
let v = u16::try_from(x * 0x1111 + y * 0x2345).unwrap();
|
||||
image::Rgb([0x1000 + v, 0x8001 + v, 0xF0F3 - v])
|
||||
});
|
||||
let rgb16 = DynamicImage::ImageRgb16(rgb16);
|
||||
let gray16 = DynamicImage::ImageLuma16(image::ImageBuffer::from_fn(3, 2, |x, y| image::Luma([u16::try_from(x * 0x3001 + y * 0x0107).unwrap()])));
|
||||
let rgb8 = DynamicImage::ImageRgb8(image::RgbImage::from_fn(3, 2, |x, y| image::Rgb([u8::try_from(x * 70 + y * 9).unwrap(), 200, 13])));
|
||||
let png = |img: &DynamicImage, icc: &[u8], orientation: u16| {
|
||||
let mut out = Vec::new();
|
||||
let mut enc = image::codecs::png::PngEncoder::new(&mut out);
|
||||
enc.set_icc_profile(icc.to_vec()).unwrap();
|
||||
enc.set_exif_metadata(exif_block(orientation, (150, 150))).unwrap();
|
||||
img.write_with_encoder(enc).unwrap();
|
||||
out
|
||||
};
|
||||
let webp = {
|
||||
let mut out = Vec::new();
|
||||
let mut enc = image::codecs::webp::WebPEncoder::new_lossless(&mut out);
|
||||
enc.set_icc_profile(rgb_icc.clone()).unwrap();
|
||||
enc.set_exif_metadata(exif_block(6, (150, 150))).unwrap();
|
||||
rgb8.write_with_encoder(enc).unwrap();
|
||||
out
|
||||
};
|
||||
let tiff = |orientation: Option<u16>| {
|
||||
let mut out = Vec::new();
|
||||
let mut enc = image::codecs::tiff::TiffEncoder::new(Cursor::new(&mut out));
|
||||
enc.set_icc_profile(rgb_icc.clone()).unwrap();
|
||||
rgb16.write_with_encoder(enc).unwrap();
|
||||
match orientation {
|
||||
Some(o) => tiff_oriented(&out, o, false, None),
|
||||
None => out,
|
||||
}
|
||||
};
|
||||
// (what, file, the ICC profile to keep, the pixels as they show, 16 bits)
|
||||
type Case<'a> = (&'a str, Vec<u8>, Option<&'a [u8]>, DynamicImage, bool);
|
||||
let cases: Vec<Case> = vec![
|
||||
("16-bit RGB PNG, orientation 6", png(&rgb16, &rgb_icc, 6), Some(&rgb_icc), rgb16.rotate90(), true),
|
||||
("16-bit gray PNG, orientation 8", png(&gray16, &gray_icc, 8), Some(&gray_icc), gray16.rotate270(), true),
|
||||
("8-bit RGB PNG, orientation 3", png(&rgb8, &rgb_icc, 3), Some(&rgb_icc), rgb8.rotate180(), false),
|
||||
("RGB PNG with a CMYK profile, orientation 6", png(&rgb8, &cmyk_icc, 6), None, rgb8.rotate90(), false),
|
||||
("WebP, orientation 6", webp, Some(&rgb_icc), rgb8.rotate90(), false),
|
||||
("16-bit RGB TIFF, not turned", tiff(None), Some(&rgb_icc), rgb16.clone(), true),
|
||||
("16-bit RGB TIFF, orientation 6", tiff(Some(6)), Some(&rgb_icc), rgb16.rotate90(), true),
|
||||
];
|
||||
for (what, file, icc, want, wide) in cases {
|
||||
let img = raster_image(&file).unwrap_or_else(|e| panic!("{what}: {e}"));
|
||||
assert_eq!((img.width, img.height, img.blob.mime.as_str()), (want.width(), want.height(), "image/png"), "{what}");
|
||||
let (kept, color, px) = stored_pixels(what, &img);
|
||||
assert_eq!(kept.as_deref(), icc, "{what}: the ICC profile");
|
||||
assert_eq!(color.bits_per_pixel() / u16::from(color.channel_count()), if wide { 16 } else { 8 }, "{what}: the sample depth");
|
||||
if wide {
|
||||
assert_eq!(px.to_rgb16(), want.to_rgb16(), "{what}: the samples");
|
||||
} else {
|
||||
assert_eq!(px.to_rgb8(), want.to_rgb8(), "{what}: the samples");
|
||||
}
|
||||
}
|
||||
// A JPEG's samples change in encoding; its profile is kept.
|
||||
let mut jpg = Vec::new();
|
||||
let mut enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpg, 95);
|
||||
enc.set_icc_profile(rgb_icc.clone()).unwrap();
|
||||
rgb8.write_with_encoder(enc).unwrap();
|
||||
let exif = [b"Exif\0\0".as_slice(), &exif_block(6, (150, 150))].concat();
|
||||
let mut turned = jpg[..2].to_vec();
|
||||
turned.extend([0xff, 0xe1]);
|
||||
turned.extend(u16::try_from(exif.len() + 2).unwrap().to_be_bytes());
|
||||
turned.extend(&exif);
|
||||
turned.extend(&jpg[2..]);
|
||||
let img = raster_image(&turned).unwrap();
|
||||
assert_eq!((img.width, img.height, img.blob.mime.as_str()), (2, 3, "image/png"), "JPEG");
|
||||
assert_eq!(stored_pixels("JPEG", &img).0, Some(rgb_icc.clone()), "JPEG: the ICC profile");
|
||||
// Not turned, a PNG keeps its own bytes.
|
||||
let plain = png(&rgb16, &rgb_icc, 1);
|
||||
assert_eq!(raster_image(&plain).unwrap().blob.bytes.as_slice(), plain.as_slice(), "a PNG as taken keeps its bytes");
|
||||
}
|
||||
|
||||
/// A CMYK TIFF stored again, because it stores one plane per ink or because its orientation turns
|
||||
/// it, keeps its ICC profile as tag 34675 and its 8 or 16 bits a sample, exactly; one that stores
|
||||
/// its inks together and isn't turned keeps its own bytes.
|
||||
#[test]
|
||||
fn cmyk_tiffs_written_again_keep_their_icc_profile_and_depth() {
|
||||
use image::DynamicImage;
|
||||
let icc = icc_profile(b"CMYK", 900);
|
||||
// 3 × 2, no black, every sample's low byte different.
|
||||
let ink = |c: usize, p: usize| -> u16 { u16::try_from(0x0101 * (c * 5 + p + 1) + 0x10 * p + c).unwrap() };
|
||||
for bits in [8u16, 16] {
|
||||
let sample = |c: usize, p: usize| match (c, bits) {
|
||||
(3, _) => 0,
|
||||
(_, 16) => ink(c, p),
|
||||
_ => ink(c, p) & 0xFF,
|
||||
};
|
||||
let channels: Vec<Vec<u16>> = (0..4).map(|c| (0..6).map(|p| sample(c, p)).collect()).collect();
|
||||
// The image decoder shows a CMYK pixel without black as 1 - C, 1 - M, 1 - Y, exactly.
|
||||
let full = if bits == 16 { 0xFFFF } else { 0xFF };
|
||||
let shown: Vec<u16> = (0..6).flat_map(|p| (0..3).map(|c| full - channels[c][p]).collect::<Vec<_>>()).collect();
|
||||
let shown = if bits == 16 {
|
||||
DynamicImage::ImageRgb16(image::ImageBuffer::from_raw(3, 2, shown).unwrap())
|
||||
} else {
|
||||
DynamicImage::ImageRgb8(image::RgbImage::from_raw(3, 2, shown.iter().map(|v| u8::try_from(*v).unwrap()).collect()).unwrap())
|
||||
};
|
||||
for planar in [false, true] {
|
||||
let file = tiff_with_icc(&hand_tiff(5, bits, &[], planar, &channels), &icc);
|
||||
for (orientation, want) in [(None, shown.clone()), (Some(6), shown.rotate90()), (Some(3), shown.rotate180())] {
|
||||
let what = format!("{bits} bits, planar {planar}, orientation {orientation:?}");
|
||||
let file = orientation.map_or_else(|| file.clone(), |o| tiff_oriented(&file, o, false, Some(150)));
|
||||
let img = raster_image(&file).unwrap_or_else(|e| panic!("{what}: {e}"));
|
||||
if orientation.is_none() && !planar {
|
||||
assert_eq!(img.blob.bytes.as_slice(), file.as_slice(), "{what}: kept as it is");
|
||||
}
|
||||
let (kept, color, px) = stored_pixels(&what, &img);
|
||||
assert_eq!(kept.as_deref(), Some(icc.as_slice()), "{what}: the ICC profile");
|
||||
let depth = if bits == 16 { image::ExtendedColorType::Cmyk16 } else { image::ExtendedColorType::Cmyk8 };
|
||||
assert_eq!(color, depth, "{what}: the sample depth");
|
||||
assert_eq!(px, want, "{what}: the samples");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A CMYK JPEG turned by its orientation and stored as a CMYK TIFF keeps its whole ICC profile,
|
||||
/// put together from the two APP2 segments a profile larger than one segment is split into.
|
||||
#[test]
|
||||
fn a_turned_cmyk_jpeg_keeps_its_icc_profile_from_every_segment() {
|
||||
use vectorcraft_render::encode::jpeg::{self, ColorModel, JpegOptions};
|
||||
let icc = icc_profile(b"CMYK", 70_000);
|
||||
let inks: Vec<u8> = (0..16u32 * 8).flat_map(|i| [u8::try_from(i).unwrap(), 0, 0, 40]).collect();
|
||||
let o = JpegOptions { color_model: ColorModel::Cmyk, embed_icc: false, ..Default::default() };
|
||||
let jpg = jpeg::encode(&inks, 16, 8, 100, None, &o).unwrap();
|
||||
let exif = [b"Exif\0\0".as_slice(), &exif_block(6, (300, 300))].concat();
|
||||
let mut file = jpg[..2].to_vec();
|
||||
file.extend([0xff, 0xe1]);
|
||||
file.extend(u16::try_from(exif.len() + 2).unwrap().to_be_bytes());
|
||||
file.extend(&exif);
|
||||
let chunks: Vec<&[u8]> = icc.chunks(65_519).collect();
|
||||
assert_eq!(chunks.len(), 2, "the profile takes two segments");
|
||||
for (i, chunk) in chunks.iter().enumerate() {
|
||||
file.extend([0xff, 0xe2]);
|
||||
file.extend(u16::try_from(chunk.len() + 16).unwrap().to_be_bytes());
|
||||
file.extend(b"ICC_PROFILE\0");
|
||||
file.extend([u8::try_from(i + 1).unwrap(), 2]);
|
||||
file.extend(*chunk);
|
||||
}
|
||||
file.extend(&jpg[2..]);
|
||||
let img = raster_image(&file).unwrap();
|
||||
assert_eq!((img.width, img.height, img.blob.mime.as_str()), (8, 16, "image/tiff"));
|
||||
let (kept, color, _) = stored_pixels("CMYK JPEG", &img);
|
||||
assert_eq!(color, image::ExtendedColorType::Cmyk8);
|
||||
assert!(kept.as_deref() == Some(icc.as_slice()), "the whole ICC profile: {:?} bytes", kept.map(|k| k.len()));
|
||||
}
|
||||
|
||||
/// With `importer` named, a file up to the importer's limit is read whole and a larger one is an
|
||||
/// error, whatever its content.
|
||||
#[test]
|
||||
|
||||
@@ -424,25 +424,45 @@ fn a_graphic_style_library_in_a_ai_file_without_layers_loads_its_styles() {
|
||||
/BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n{xa}0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n;\n"
|
||||
)
|
||||
};
|
||||
// Styles of one paint (`/SimpleStyle`): a red 2 pt stroke and no fill, and a gradient fill,
|
||||
// which isn't read, so it is left out rather than listed with no paint.
|
||||
let one_paint = |name: &str, paint: &str| format!("/KnownStyle :\n({name}) /Name ,\n/SimpleStyle :\n{paint}/Paint ;\n/Def ;\n");
|
||||
let styles = format!(
|
||||
"%AI9_BeginArtStyles\n{}{}{}%AI9_EndArtStyles\n%AI9_BeginArtStyleList\n(Red)\n(Green)\n(Blue)\n%AI9_EndArtStyleList\n",
|
||||
"%AI9_BeginArtStyles\n{}{}{}{}{}%AI9_EndArtStyles\n\
|
||||
%AI9_BeginArtStyleList\n(Red)\n(Green)\n(Blue)\n(Red outline)\n(Sky fill)\n%AI9_EndArtStyleList\n",
|
||||
style("Blue", "0 0 0 0 0 0 1 Xa\n"),
|
||||
style("Green", "0 0 0 0 0 1 0 Xa\n"),
|
||||
style("Red", "0 0 0 0 1 0 0 Xa\n")
|
||||
style("Red", "0 0 0 0 1 0 0 Xa\n"),
|
||||
one_paint("Red outline", "0 R\n0 1 1 0 K\n0 J 0 j 2 w 10 M []0 d\n1 0 Xd\n"),
|
||||
one_paint("Sky fill", "0 O\n0 Bb\n2 (Sky) 0 0 0 100 1 0 0 1 0 0 Bg\n0 BB\n0 1 Xd\n")
|
||||
);
|
||||
let data = ai::editing_data(200.0, 100.0, &styles);
|
||||
let file = ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f");
|
||||
let mut s = Session::new();
|
||||
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&file), "name": "fills.ai"});
|
||||
let r = s.execute("graphicStyle.loadLibrary", &p).unwrap();
|
||||
assert_eq!((&r["name"], &r["count"]), (&json!("fills"), &json!(3)), "{r}");
|
||||
let lib = s.execute("graphicStyle.library", &json!({"library": r["library"]})).unwrap();
|
||||
assert_eq!((&r["name"], &r["count"]), (&json!("fills"), &json!(4)), "{r}");
|
||||
let library = r["library"].clone();
|
||||
let lib = s.execute("graphicStyle.library", &json!({"library": library})).unwrap();
|
||||
let names: Vec<&str> = lib["styles"].as_array().unwrap().iter().map(|g| g["name"].as_str().unwrap()).collect();
|
||||
assert_eq!(names, ["Red", "Green", "Blue"], "{lib}");
|
||||
assert_eq!(names, ["Red", "Green", "Blue", "Red outline"], "{lib}");
|
||||
// The outline style strokes a rectangle red, 2 pt wide, and leaves it unfilled.
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let id = NodeId(s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap());
|
||||
let r = s.execute("graphicStyle.addFromLibrary", &json!({"library": library, "names": ["Red outline"], "apply": true, "ids": [id.0]})).unwrap();
|
||||
assert_eq!(r["added"], json!(["Red outline"]), "{r}");
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let look = &doc.node(id).unwrap().appearance;
|
||||
assert!(look.fill().is_none(), "{look:?}");
|
||||
let strokes: Vec<_> = look.items.iter().filter(|i| matches!(i, vectorcraft_doc::AppearanceItem::Stroke(_))).collect();
|
||||
assert_eq!(strokes.len(), 1, "{look:?}");
|
||||
let stroke = look.stroke().unwrap();
|
||||
assert_eq!((stroke.paint.color(), stroke.width), (Some(vectorcraft_color::Color::cmyk(0.0, 1.0, 1.0, 0.0)), 2.0), "{look:?}");
|
||||
assert_eq!(doc.graphic_style("Red outline").map(|g| &g.appearance), Some(&**look));
|
||||
let r = open(&mut s, "fills.ai", &file, json!({})).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let styles: Vec<(&str, u32)> = doc.graphic_styles.iter().map(|g| (g.name.as_str(), g.id)).collect();
|
||||
assert_eq!(styles, [("Red", 1), ("Green", 2), ("Blue", 3)], "{r}");
|
||||
assert_eq!(styles, [("Red", 1), ("Green", 2), ("Blue", 3), ("Red outline", 4)], "{r}");
|
||||
}
|
||||
|
||||
/// A `.ai` symbol library (symbols and their list, no layers) opens with its symbols, and Other
|
||||
|
||||
@@ -402,28 +402,75 @@ fn ai_export_validates_options_even_when_editing_data_is_omitted() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ai_export_without_artboards_keeps_art_outside_the_original_pages() {
|
||||
/// Two artboards, a visible 30 × 20 pt rectangle outside them at (180, 100) and a hidden one.
|
||||
fn art_outside_the_artboards() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 80, "artboards": 2})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 180, "y": 100, "width": 30, "height": 20})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 1000, "y": 1000, "width": 50, "height": 40})).unwrap();
|
||||
s.execute("object.hide", &json!({})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// Whether the `.ai` file `bytes` carries the editing copy of its art for other apps.
|
||||
fn carries_private_data(bytes: &[u8]) -> bool {
|
||||
let opts = LoadOptions { native: false, ..Default::default() };
|
||||
load::load_with("a.ai", bytes, &opts).unwrap().editing_data
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ai_of_the_arts_bounds_carries_no_editing_data() {
|
||||
let mut s = art_outside_the_artboards();
|
||||
let before = comparable(&s.doc().unwrap().doc);
|
||||
let r = s.execute("document.export", &json!({"format": "ai", "useArtboards": false, "range": "2"})).unwrap();
|
||||
let bytes = b64(&r);
|
||||
let pages = vectorcraft_pdf::import(&bytes).unwrap();
|
||||
assert_eq!(pages.artboards.len(), 1);
|
||||
assert_eq!((pages.artboards[0].rect.width(), pages.artboards[0].rect.height()), (30.0, 20.0));
|
||||
let editing = vectorcraft_pdf::editing(&bytes).unwrap();
|
||||
let exported = vectorcraft_format::load(&editing.data).unwrap();
|
||||
assert_eq!(exported.artboards.len(), 1);
|
||||
assert_eq!(exported.artboards[0].rect, vectorcraft_geom::Rect::new(180.0, 100.0, 210.0, 120.0));
|
||||
assert_eq!(comparable(&s.doc().unwrap().doc), before);
|
||||
let left_out = |v: &Value| v["warnings"].as_array().unwrap().iter().any(|w| w == super::save::AI_EDITING_NEEDS_THE_ARTBOARDS);
|
||||
let path = tmp("art-bounds.ai");
|
||||
for extra in [json!({}), json!({"range": "2"}), json!({"editingData": false}), json!({"path": path})] {
|
||||
let mut params = json!({"format": "ai", "useArtboards": false});
|
||||
params.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
|
||||
let r = s.execute("document.export", ¶ms).unwrap();
|
||||
let bytes = if params.get("path").is_some() { std::fs::read(&path).unwrap() } else { b64(&r) };
|
||||
// One page, the visible art's bounds, whatever range names.
|
||||
let pages = vectorcraft_pdf::import(&bytes).unwrap();
|
||||
assert_eq!(pages.artboards.len(), 1, "{params}");
|
||||
assert_eq!((pages.artboards[0].rect.width(), pages.artboards[0].rect.height()), (30.0, 20.0), "{params}");
|
||||
assert!(vectorcraft_pdf::editing(&bytes).is_none(), "{params}");
|
||||
assert!(!carries_private_data(&bytes), "{params}");
|
||||
assert!(left_out(&r), "{params}: {r}");
|
||||
assert_eq!(comparable(&s.doc().unwrap().doc), before);
|
||||
}
|
||||
// The artboards keep both editing copies, without the warning.
|
||||
for params in [json!({"format": "ai"}), json!({"format": "ai", "useArtboards": true})] {
|
||||
let r = s.execute("document.export", ¶ms).unwrap();
|
||||
let bytes = b64(&r);
|
||||
let editing = vectorcraft_pdf::editing(&bytes).expect("editing data");
|
||||
assert_eq!(vectorcraft_format::load(&editing.data).unwrap().artboards.len(), 2, "{params}");
|
||||
assert!(carries_private_data(&bytes), "{params}");
|
||||
assert!(!left_out(&r), "{params}: {r}");
|
||||
}
|
||||
assert!(s.execute("document.export", &json!({"format": "ai", "useArtboards": "yes"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ai_of_the_arts_bounds_without_pdf_is_refused() {
|
||||
let mut s = art_outside_the_artboards();
|
||||
let before = comparable(&s.doc().unwrap().doc);
|
||||
for extra in [json!({}), json!({"editingData": false}), json!({"editingData": true})] {
|
||||
for command in ["document.export", "document.serialize"] {
|
||||
let mut params = json!({"format": "ai", "useArtboards": false, "pdfCompatible": false});
|
||||
params.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
|
||||
let e = s.execute(command, ¶ms).unwrap_err().to_string();
|
||||
assert!(e.contains(super::save::ART_PAGE_NEEDS_PDF), "{command} {params}: {e}");
|
||||
assert_eq!(comparable(&s.doc().unwrap().doc), before);
|
||||
}
|
||||
}
|
||||
// A document with no visible art is still refused for that.
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 80})).unwrap();
|
||||
let e = s.execute("document.export", &json!({"format": "ai", "useArtboards": false})).unwrap_err().to_string();
|
||||
assert!(e.contains("no visible art"), "{e}");
|
||||
}
|
||||
|
||||
/// Color Halftone's Max Radius is in pixels of the raster effects resolution since document
|
||||
/// version 3 (#3260). A PDF saved with Preserve Editing carries the native document, so one from
|
||||
/// before that opens with the radius converted, drawing the same dots; one saved since opens as
|
||||
|
||||
@@ -135,6 +135,9 @@ fn touch(a: &Rect, b: &Rect) -> bool {
|
||||
struct Sets {
|
||||
parent: Vec<usize>,
|
||||
seeded: Vec<bool>,
|
||||
/// How many open boxes the sweep's boxes met.
|
||||
#[cfg(test)]
|
||||
meets: usize,
|
||||
}
|
||||
|
||||
impl Sets {
|
||||
@@ -180,17 +183,25 @@ impl Sets {
|
||||
/// tops that knows the lowest bottom below each of its branches, so each box meets only the open
|
||||
/// boxes it overlaps, not every open one (many objects stacked in a column, sharing their
|
||||
/// horizontal extent, would otherwise compare every pair). An open box inside a later box of
|
||||
/// its group, ending no further right, is closed early: whatever overlaps it overlaps that box.
|
||||
/// Fails only when cancelled ([`vectorcraft_doc::cancel`]).
|
||||
/// its group, ending no further right, is closed early, and a box inside an open box of its group,
|
||||
/// ending no further right, isn't opened: whatever overlaps it overlaps that box. Fails only when
|
||||
/// cancelled ([`vectorcraft_doc::cancel`]).
|
||||
pub(super) fn overlapping(bounds: &[Option<Rect>]) -> Result<Vec<Vec<usize>>, Cancelled> {
|
||||
Ok(sweep(bounds, None)?.groups())
|
||||
}
|
||||
|
||||
/// [`overlapping`]'s sweep. With `see_through`, two boxes are joined only when one of them is
|
||||
/// see-through, and an open box is closed early only inside a later see-through box.
|
||||
/// see-through, and an open box is closed early, or a box isn't opened, only inside a see-through
|
||||
/// box. The open
|
||||
/// see-through boxes and the open boxes without transparency are then in trees of their own, and
|
||||
/// a box without transparency meets only the see-through ones.
|
||||
fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets, Cancelled> {
|
||||
let mut sets = Sets { parent: (0..bounds.len()).collect(), seeded: (0..bounds.len()).map(|i| see_through.is_some_and(|s| s[i])).collect() };
|
||||
let joins = |a: usize, b: usize| see_through.is_none_or(|s| s[a] || s[b]);
|
||||
let mut sets = Sets {
|
||||
parent: (0..bounds.len()).collect(),
|
||||
seeded: (0..bounds.len()).map(|i| see_through.is_some_and(|s| s[i])).collect(),
|
||||
#[cfg(test)]
|
||||
meets: 0,
|
||||
};
|
||||
let boxes: Vec<(usize, Rect)> = bounds.iter().enumerate().filter_map(|(i, b)| b.filter(finite).map(|b| (i, b))).collect();
|
||||
let n = boxes.len();
|
||||
// Each box's place in the tree: by top (then index).
|
||||
@@ -201,9 +212,11 @@ fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets,
|
||||
for (pos, &k) in by_top.iter().enumerate() {
|
||||
leaf[k] = pos;
|
||||
}
|
||||
// The lowest bottom of the open boxes below each node (−∞: none open).
|
||||
// The lowest bottom of the open boxes below each node (−∞: none open), in the tree of the
|
||||
// boxes without transparency (every box without `see_through`) and the see-through boxes'.
|
||||
let size = n.next_power_of_two().max(1);
|
||||
let mut low = vec![f64::NEG_INFINITY; 2 * size];
|
||||
let mut low = [vec![f64::NEG_INFINITY; 2 * size], if see_through.is_some() { vec![f64::NEG_INFINITY; 2 * size] } else { vec![] }];
|
||||
let tree = |k: usize| usize::from(see_through.is_some_and(|s| s[boxes[k].0]));
|
||||
let set = |low: &mut [f64], pos: usize, v: f64| {
|
||||
let mut i = pos + size;
|
||||
low[i] = v;
|
||||
@@ -226,43 +239,63 @@ fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets,
|
||||
while let Some(&c) = by_right.get(closing)
|
||||
&& boxes[c].1.x1 < b.x0
|
||||
{
|
||||
set(&mut low, leaf[c], f64::NEG_INFINITY);
|
||||
set(&mut low[tree(c)], leaf[c], f64::NEG_INFINITY);
|
||||
closing += 1;
|
||||
}
|
||||
// The open boxes with their top at most this bottom and their bottom at least this top.
|
||||
// The open boxes it joins with their top at most this bottom and their bottom at least
|
||||
// this top: every one, or with `see_through` the see-through ones and, for a see-through
|
||||
// box, the others too.
|
||||
let shadows = see_through.is_none_or(|s| s[boxes[k].0]);
|
||||
let looks: &[usize] = match see_through {
|
||||
None => &[0],
|
||||
Some(_) if shadows => &[0, 1],
|
||||
Some(_) => &[1],
|
||||
};
|
||||
let below = tops.partition_point(|t| *t <= b.y1);
|
||||
met.clear();
|
||||
stack.clear();
|
||||
stack.push((1, 0, size));
|
||||
while let Some((node, lo, hi)) = stack.pop() {
|
||||
work += 1;
|
||||
if work.is_multiple_of(4096) {
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
for &t in looks {
|
||||
stack.clear();
|
||||
stack.push((1, 0, size));
|
||||
while let Some((node, lo, hi)) = stack.pop() {
|
||||
work += 1;
|
||||
if work.is_multiple_of(4096) {
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
}
|
||||
if lo >= below || low[t][node] < b.y0 {
|
||||
continue;
|
||||
}
|
||||
if hi - lo == 1 {
|
||||
met.push(by_top[lo]);
|
||||
continue;
|
||||
}
|
||||
let mid = (lo + hi) / 2;
|
||||
stack.push((2 * node + 1, mid, hi));
|
||||
stack.push((2 * node, lo, mid));
|
||||
}
|
||||
if lo >= below || low[node] < b.y0 {
|
||||
continue;
|
||||
}
|
||||
if hi - lo == 1 {
|
||||
met.push(by_top[lo]);
|
||||
continue;
|
||||
}
|
||||
let mid = (lo + hi) / 2;
|
||||
stack.push((2 * node + 1, mid, hi));
|
||||
stack.push((2 * node, lo, mid));
|
||||
}
|
||||
#[cfg(test)]
|
||||
{
|
||||
sets.meets += met.len();
|
||||
}
|
||||
// An open box it met that holds it, ending no further right, and that joins whatever it
|
||||
// overlaps: whatever later overlaps this box overlaps that one and joins it, so this box
|
||||
// isn't opened.
|
||||
let holder = met.iter().copied().find(|&o| {
|
||||
let ob = boxes[o].1;
|
||||
see_through.is_none_or(|s| s[boxes[o].0]) && b.x1 <= ob.x1 && ob.y0 <= b.y0 && b.y1 <= ob.y1
|
||||
});
|
||||
// Whatever overlaps a box inside this one overlaps this one, and joins it when this one is
|
||||
// see-through.
|
||||
let shadows = see_through.is_none_or(|s| s[boxes[k].0]);
|
||||
for &o in &met {
|
||||
if joins(boxes[k].0, boxes[o].0) {
|
||||
sets.join(boxes[k].0, boxes[o].0);
|
||||
}
|
||||
sets.join(boxes[k].0, boxes[o].0);
|
||||
let ob = boxes[o].1;
|
||||
if shadows && ob.x1 <= b.x1 && b.y0 <= ob.y0 && ob.y1 <= b.y1 {
|
||||
set(&mut low, leaf[o], f64::NEG_INFINITY);
|
||||
if shadows && Some(o) != holder && ob.x1 <= b.x1 && b.y0 <= ob.y0 && ob.y1 <= b.y1 {
|
||||
set(&mut low[tree(o)], leaf[o], f64::NEG_INFINITY);
|
||||
}
|
||||
}
|
||||
set(&mut low, leaf[k], b.y1);
|
||||
if holder.is_none() {
|
||||
set(&mut low[tree(k)], leaf[k], b.y1);
|
||||
}
|
||||
}
|
||||
Ok(sets)
|
||||
}
|
||||
@@ -392,6 +425,11 @@ mod tests {
|
||||
|
||||
/// What [`overlapping`] gives, comparing every pair.
|
||||
fn every_pair(bounds: &[Option<Rect>]) -> Vec<Vec<usize>> {
|
||||
every_pair_joining(bounds, |_, _| true)
|
||||
}
|
||||
|
||||
/// The groups of `bounds` comparing every pair, joining overlapping pairs that `joins`.
|
||||
fn every_pair_joining(bounds: &[Option<Rect>], joins: impl Fn(usize, usize) -> bool) -> Vec<Vec<usize>> {
|
||||
let n = bounds.len();
|
||||
let mut group: Vec<usize> = (0..n).collect();
|
||||
let hit = |a: &Rect, b: &Rect| a.x0 <= b.x1 && b.x0 <= a.x1 && a.y0 <= b.y1 && b.y0 <= a.y1;
|
||||
@@ -401,6 +439,7 @@ mod tests {
|
||||
for j in 0..n {
|
||||
if let (Some(a), Some(b)) = (bounds[i], bounds[j])
|
||||
&& hit(&a, &b)
|
||||
&& joins(i, j)
|
||||
&& group[j] < group[i]
|
||||
{
|
||||
group[i] = group[j];
|
||||
@@ -464,6 +503,69 @@ mod tests {
|
||||
assert_eq!(overlapping(&odd).unwrap(), vec![vec![0, 2], vec![1]]);
|
||||
}
|
||||
|
||||
/// `n` boxes sharing their left and top edges, each inside the one before.
|
||||
fn shrinking_nest(n: usize) -> Vec<Option<Rect>> {
|
||||
(0..n).map(|i| Some(Rect::new(0.0, 0.0, 2.0 * (n - i) as f64, 2.0 * (n - i) as f64))).collect()
|
||||
}
|
||||
|
||||
/// Each box of a nest that shrinks to the right and bottom meets only the outermost box, which
|
||||
/// stays open and holds it, not every box around it.
|
||||
#[test]
|
||||
fn a_shrinking_nest_meets_only_its_outermost_box() {
|
||||
let n = 512;
|
||||
let bounds = shrinking_nest(n);
|
||||
let mut sets = sweep(&bounds, None).unwrap();
|
||||
assert_eq!(sets.meets, n - 1);
|
||||
assert_eq!(sets.groups(), every_pair(&bounds));
|
||||
assert_eq!(sets.groups(), vec![(0..n).collect::<Vec<_>>()]);
|
||||
// Equal boxes: the later one isn't opened and the earlier one stays open for the third.
|
||||
let same = [Some(Rect::new(0.0, 0.0, 10.0, 10.0)), Some(Rect::new(0.0, 0.0, 10.0, 10.0)), Some(Rect::new(9.0, 9.0, 20.0, 20.0))];
|
||||
assert_eq!(overlapping(&same).unwrap(), vec![vec![0, 1, 2]]);
|
||||
// With transparency, an opaque box isn't opened inside a see-through box, and boxes inside
|
||||
// an opaque box are opened: an opaque box that overlaps only the inner one still joins it
|
||||
// when that one is see-through.
|
||||
let see = [true, false];
|
||||
let mut sets = sweep(&bounds[..2], Some(&see)).unwrap();
|
||||
assert_eq!(sets.groups(), vec![vec![0, 1]]);
|
||||
let held = [Some(Rect::new(0.0, 0.0, 20.0, 20.0)), Some(Rect::new(0.0, 0.0, 10.0, 10.0)), Some(Rect::new(5.0, 5.0, 8.0, 8.0))];
|
||||
let mut sets = sweep(&held, Some(&[false, true, false])).unwrap();
|
||||
assert_eq!(sets.groups(), vec![vec![0, 1, 2]]);
|
||||
let mut sets = sweep(&held, Some(&[true, false, false])).unwrap();
|
||||
assert_eq!(sets.groups(), vec![vec![0, 1, 2]]);
|
||||
let mut sets = sweep(&held, Some(&[false, false, true])).unwrap();
|
||||
assert_eq!(sets.groups(), vec![vec![0, 1, 2]]);
|
||||
let mut sets = sweep(&held, Some(&[false, false, false])).unwrap();
|
||||
assert_eq!(sets.groups(), vec![vec![0], vec![1], vec![2]]);
|
||||
}
|
||||
|
||||
/// Boxes nested at shared corners and placed at random, some see-through, group with and
|
||||
/// without transparency as comparing every pair groups them.
|
||||
#[test]
|
||||
fn nested_and_scattered_boxes_group_as_comparing_every_pair() {
|
||||
let mut seed = 0x51_7cc1_b727_220au64;
|
||||
let mut next = |m: f64| {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 7;
|
||||
seed ^= seed << 17;
|
||||
(seed % 1000) as f64 / 1000.0 * m
|
||||
};
|
||||
for round in 0..40 {
|
||||
let n = 6 + round * 3;
|
||||
let bounds: Vec<Option<Rect>> = (0..n)
|
||||
.map(|_| {
|
||||
// Corners on a coarse grid so that edges are often shared and boxes often nest.
|
||||
let (x, y) = ((next(6.0).floor()) * 10.0, (next(6.0).floor()) * 10.0);
|
||||
let (w, h) = ((next(5.0).floor() + 1.0) * 10.0, (next(5.0).floor() + 1.0) * 10.0);
|
||||
Some(Rect::new(x, y, x + w, y + h))
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(overlapping(&bounds).unwrap(), every_pair(&bounds), "round {round}");
|
||||
let see: Vec<bool> = (0..n).map(|_| next(1.0) < 0.3).collect();
|
||||
let mut sets = sweep(&bounds, Some(&see)).unwrap();
|
||||
assert_eq!(sets.groups(), every_pair_joining(&bounds, |i, j| see[i] || see[j]), "round {round}, with transparency");
|
||||
}
|
||||
}
|
||||
|
||||
/// A filled rectangle, unstroked.
|
||||
fn filled(id: u64, r: Rect) -> Node {
|
||||
let look = vectorcraft_doc::Appearance::basic(
|
||||
@@ -583,6 +685,62 @@ mod tests {
|
||||
assert_eq!(flatten_groups(&reach, &painted, &vec![false; n], 0.0).unwrap().len(), n);
|
||||
}
|
||||
|
||||
/// A small see-through box, then `n` opaque boxes nested around it, each inside the one
|
||||
/// before and sharing its left and top edges.
|
||||
fn nest_around_a_see_through_box(n: usize) -> (Vec<Option<Rect>>, Vec<bool>) {
|
||||
let mut bounds = vec![Some(Rect::new(0.0, 0.0, 1.0, 1.0))];
|
||||
bounds.extend((0..n).map(|i| Some(Rect::new(0.0, 0.0, 2.0 * (n - i) as f64 + 1.0, 2.0 * (n - i) as f64 + 1.0))));
|
||||
let mut see = vec![false; n + 1];
|
||||
see[0] = true;
|
||||
(bounds, see)
|
||||
}
|
||||
|
||||
/// Opaque boxes nested in each other around a see-through box each meet only the see-through
|
||||
/// box, not the open opaque boxes they can't join, and all join it.
|
||||
#[test]
|
||||
fn nested_opaque_boxes_meet_only_the_see_through_box() {
|
||||
let n = 512;
|
||||
let (bounds, see) = nest_around_a_see_through_box(n);
|
||||
let mut sets = sweep(&bounds, Some(&see)).unwrap();
|
||||
assert_eq!(sets.meets, n);
|
||||
assert_eq!(sets.groups(), vec![(0..=n).collect::<Vec<_>>()]);
|
||||
// The unfiltered sweep that runs before it meets each box once too.
|
||||
let mut sets = sweep(&bounds, None).unwrap();
|
||||
assert_eq!(sets.meets, n);
|
||||
assert_eq!(sets.groups(), vec![(0..=n).collect::<Vec<_>>()]);
|
||||
let (painted, see) = nest_around_a_see_through_box(40);
|
||||
let reach: Vec<Option<Rect>> = painted.iter().map(|b| b.map(|b| b.inflate(1.0, 1.0))).collect();
|
||||
for fringe in [0.0, 0.7] {
|
||||
let groups = flatten_groups(&reach, &painted, &see, fringe).unwrap();
|
||||
check(&reach, &painted, &see, fringe, &groups, &format!("nest, fringe {fringe}"));
|
||||
assert_eq!(groups, vec![(0..=40).collect::<Vec<_>>()]);
|
||||
}
|
||||
}
|
||||
|
||||
/// An opaque box inside a later see-through box is closed: later boxes meet the see-through
|
||||
/// box instead, and join the opaque one through it.
|
||||
#[test]
|
||||
fn a_see_through_box_closes_an_opaque_box_inside_it() {
|
||||
// An opaque box, a see-through box around it, a see-through box over both and an opaque
|
||||
// box over the first.
|
||||
let bounds = [
|
||||
Some(Rect::new(0.0, 0.0, 10.0, 10.0)),
|
||||
Some(Rect::new(0.0, 0.0, 20.0, 20.0)),
|
||||
Some(Rect::new(5.0, 5.0, 30.0, 30.0)),
|
||||
Some(Rect::new(8.0, 8.0, 12.0, 12.0)),
|
||||
];
|
||||
let see = [false, true, true, false];
|
||||
let mut sets = sweep(&bounds, Some(&see)).unwrap();
|
||||
// The second box meets the first; the third meets the second; the fourth meets the second
|
||||
// and the third.
|
||||
assert_eq!(sets.meets, 4);
|
||||
assert_eq!(sets.groups(), vec![vec![0, 1, 2, 3]]);
|
||||
// Opaque boxes alone meet nothing.
|
||||
let mut sets = sweep(&bounds, Some(&[false; 4])).unwrap();
|
||||
assert_eq!(sets.meets, 0);
|
||||
assert_eq!(sets.groups().len(), 4);
|
||||
}
|
||||
|
||||
/// An opaque box between a member and its group's top that paints over the member joins, and
|
||||
/// so on along a chain; one under the member stays, but for one within the fringe.
|
||||
#[test]
|
||||
|
||||
@@ -46,7 +46,8 @@ use generate::generate;
|
||||
use series::default_series_color;
|
||||
pub(crate) use series::{
|
||||
capture_label_anti_alias, capture_label_paragraphs, capture_label_styles, capture_series_object_opacity, capture_series_opacity,
|
||||
capture_series_paints, capture_series_top_paints, paint_targets, series_object_opacity_differs, shown_paint,
|
||||
capture_series_paints, capture_series_top_paints, paint_targets, series_group_marks, series_group_marks_where, series_object_opacity_differs,
|
||||
shown_paint,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -79,6 +79,11 @@ struct SeriesRef {
|
||||
index: usize,
|
||||
}
|
||||
|
||||
/// How many series groups `spec`'s graph has: a group whose index is past it (the index comes from the file) is not one.
|
||||
fn series_count(spec: &GraphSpec) -> usize {
|
||||
spec.rows.iter().map(Vec::len).max().unwrap_or(0).clamp(1, vectorcraft_doc::MAX_GRAPH_SERIES)
|
||||
}
|
||||
|
||||
/// Every node in a graph's series groups (the groups too), found in one pass over the document.
|
||||
/// Axes, the legend and groups whose index is past the graph's series (the index comes from the
|
||||
/// file) are left out.
|
||||
@@ -86,7 +91,7 @@ fn series_members(doc: &Document) -> HashMap<NodeId, SeriesRef> {
|
||||
let mut out = HashMap::new();
|
||||
doc.walk(|n| {
|
||||
let Some(spec) = n.extras().graph.as_deref() else { return };
|
||||
let count = spec.rows.iter().map(Vec::len).max().unwrap_or(0).clamp(1, vectorcraft_doc::MAX_GRAPH_SERIES);
|
||||
let count = series_count(spec);
|
||||
for group in n.children().into_iter().flatten() {
|
||||
let Some(index) = group.extras().series_index.and_then(|i| usize::try_from(i).ok()).filter(|i| *i < count) else { continue };
|
||||
let r = SeriesRef { graph: n.id, group: group.id, index };
|
||||
@@ -124,6 +129,38 @@ pub(crate) fn paint_targets(doc: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
out
|
||||
}
|
||||
|
||||
/// `ids` with each graph series group replaced by the paths directly inside it, as [`paint_targets`] reads a series
|
||||
/// group: the graph draws its series groups again with no rows of their own. A series group with no such path, other
|
||||
/// ids and the art of a graph design pass through, and the order of `ids` is kept.
|
||||
pub(crate) fn series_group_marks(doc: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
series_group_marks_where(doc, ids, |_| true)
|
||||
}
|
||||
|
||||
/// [`series_group_marks`] for the series groups `stands` accepts; the others pass through.
|
||||
pub(crate) fn series_group_marks_where(doc: &Document, ids: &[NodeId], stands: impl Fn(&Node) -> bool) -> Vec<NodeId> {
|
||||
// A series group is a child of a graph with one of the graph's series indexes ([`series_members`]). Each id is
|
||||
// looked up through its parent, with no pass over the document: the panels call this while they draw.
|
||||
let is_series_group = |n: &Node| {
|
||||
let Some(index) = n.extras().series_index.and_then(|i| usize::try_from(i).ok()) else { return false };
|
||||
let graph = doc.parent_of(n.id).and_then(|parent| doc.node(parent)).and_then(|parent| parent.extras().graph.as_deref());
|
||||
graph.is_some_and(|spec| index < series_count(spec))
|
||||
};
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut out = Vec::new();
|
||||
for id in ids {
|
||||
match doc.node(*id) {
|
||||
Some(group) if is_series_group(group) && stands(group) => {
|
||||
let marks: Vec<NodeId> =
|
||||
group.children().into_iter().flatten().filter(|m| matches!(m.kind, NodeKind::Path { .. })).map(|m| m.id).collect();
|
||||
if marks.is_empty() { out.push(*id) } else { out.extend(marks) }
|
||||
}
|
||||
_ => out.push(*id),
|
||||
}
|
||||
}
|
||||
out.retain(|id| seen.insert(*id));
|
||||
out
|
||||
}
|
||||
|
||||
/// Copy the paint just applied to generated series art into that series' fill or stroke. Called
|
||||
/// inside the same document edit, so the visible paint and future regeneration undo together.
|
||||
/// Gradients, patterns and swatch links are kept as [`Paint`], not reduced to a solid colour.
|
||||
|
||||
@@ -1034,6 +1034,85 @@ fn an_opaque_pick_replaces_the_opacity_the_series_stores() {
|
||||
assert_eq!(spec(&s, id).series_paints[0].fill_opacity, None);
|
||||
}
|
||||
|
||||
/// A column graph whose series 0 stores the 40% Multiply fill set on its first mark, and a mark of series 1 whose top fill
|
||||
/// row has no paint and is opaque and Normal: the session, the graph, series 0's marks and that source.
|
||||
fn marks_and_unpainted_source() -> (Session, NodeId, Vec<NodeId>, NodeId) {
|
||||
let (mut s, id, _, marks) = column_marks();
|
||||
let source = series(s.doc().unwrap().doc.node(id).unwrap(), 1).children().unwrap()[0].id;
|
||||
s.execute("appearance.setItem", &json!({"ids": [source.0], "index": top_row(&s, source, true), "none": true})).unwrap();
|
||||
let fill = top_row(&s, marks[0], true);
|
||||
s.execute("appearance.setItem", &json!({"ids": [marks[0].0], "index": fill, "opacity": 40, "blend": "multiply"})).unwrap();
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.fill_opacity, kept.fill_blend), (Some(0.4), Some(BlendMode::Multiply)));
|
||||
(s, id, marks, source)
|
||||
}
|
||||
|
||||
/// An Eyedropper pick from a fill row without paint onto a mark whose fill had paint replaces the fill opacity and blend
|
||||
/// mode another mark of the series stored: the series is drawn opaque and Normal again.
|
||||
#[test]
|
||||
fn an_eyedropper_pick_that_unpaints_a_series_fill_clears_its_stored_transparency() {
|
||||
let (mut s, id, marks, source) = marks_and_unpainted_source();
|
||||
let mark = s.doc().unwrap().doc.node(marks[1]).unwrap().appearance.fill().unwrap().clone();
|
||||
assert_eq!((mark.paint.is_none(), mark.opacity, mark.blend), (false, 1.0, BlendMode::Normal), "the target's fill row");
|
||||
s.execute("appearance.copyFrom", &json!({"source": source.0, "ids": [marks[1].0]})).unwrap();
|
||||
let picked = s.doc().unwrap().doc.node(marks[1]).unwrap().appearance.fill().unwrap().clone();
|
||||
assert_eq!((picked.paint.is_none(), picked.opacity, picked.blend), (true, 1.0, BlendMode::Normal));
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.fill_opacity, kept.fill_blend), (None, None));
|
||||
s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4]]})).unwrap();
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
let fills: Vec<_> = series(&n, 0).children().unwrap().iter().filter_map(|m| m.appearance.fill().map(|f| (f.opacity, f.blend))).collect();
|
||||
assert!(fills.iter().all(|f| *f == (1.0, BlendMode::Normal)), "{fills:?}");
|
||||
}
|
||||
|
||||
/// An Eyedropper pick from a fill row without paint onto a mark whose fill had no paint before the pick either leaves the
|
||||
/// fill opacity and blend mode another mark of the series stored.
|
||||
#[test]
|
||||
fn an_eyedropper_pick_of_an_already_unpainted_row_leaves_series_transparency() {
|
||||
let (mut s, id, marks, source) = marks_and_unpainted_source();
|
||||
s.execute("appearance.setItem", &json!({"ids": [marks[1].0], "index": top_row(&s, marks[1], true), "none": true})).unwrap();
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.fill_opacity, kept.fill_blend), (Some(0.4), Some(BlendMode::Multiply)), "a color set to None writes no opacity");
|
||||
s.execute("appearance.copyFrom", &json!({"source": source.0, "ids": [marks[1].0]})).unwrap();
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.fill_opacity, kept.fill_blend), (Some(0.4), Some(BlendMode::Multiply)));
|
||||
}
|
||||
|
||||
/// A whole Eyedropper pick from a source with no fill row, or no stroke row, removes that row from the mark. Where the
|
||||
/// mark's row had paint, the pick replaces the opacity and blend mode another mark of the series stored for that kind
|
||||
/// of row. Where the mark's row had no paint, the stored values stay.
|
||||
#[test]
|
||||
fn a_whole_eyedropper_pick_that_removes_a_painted_row_clears_its_stored_transparency() {
|
||||
let stored = |s: &Session, id: NodeId, fill: bool| {
|
||||
let kept = spec(s, id).series_paints[0].clone();
|
||||
if fill { (kept.fill_opacity, kept.fill_blend) } else { (kept.stroke_opacity, kept.stroke_blend) }
|
||||
};
|
||||
for (fill, painted) in [(true, true), (false, true), (false, false)] {
|
||||
let (mut s, id, _, marks) = column_marks();
|
||||
let row = top_row(&s, marks[0], fill);
|
||||
if painted {
|
||||
s.execute("appearance.setItem", &json!({"ids": [marks[1].0], "index": row, "color": "#ff0000"})).unwrap();
|
||||
}
|
||||
s.execute("appearance.setItem", &json!({"ids": [marks[0].0], "index": row, "color": "#ff0000", "opacity": 40, "blend": "multiply"})).unwrap();
|
||||
assert_eq!(stored(&s, id, fill), (Some(0.4), Some(BlendMode::Multiply)), "fill {fill}, painted {painted}");
|
||||
let source = series(s.doc().unwrap().doc.node(id).unwrap(), 1).children().unwrap()[0].id;
|
||||
s.execute("appearance.removeItem", &json!({"ids": [source.0], "index": top_row(&s, source, fill)})).unwrap();
|
||||
let was = spec(&s, id).series_paints;
|
||||
s.execute("appearance.copyFrom", &json!({"source": source.0, "ids": [marks[1].0]})).unwrap();
|
||||
let mark = s.doc().unwrap().doc.node(marks[1]).unwrap().clone();
|
||||
assert!(!mark.appearance.items.iter().any(|it| it.is_fill() == fill), "the pick removed the row: fill {fill}");
|
||||
let want = if painted { (None, None) } else { (Some(0.4), Some(BlendMode::Multiply)) };
|
||||
assert_eq!(stored(&s, id, fill), want, "fill {fill}, painted {painted}");
|
||||
if painted {
|
||||
let after = spec(&s, id).series_paints;
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(spec(&s, id).series_paints, was);
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(spec(&s, id).series_paints, after);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An appearance moved between two marks of one series leaves the series with the target's paint, not the source's
|
||||
/// empty one, and the series still shows when the graph is drawn again.
|
||||
#[test]
|
||||
@@ -1251,6 +1330,45 @@ fn a_style_that_removes_a_marks_stroke_replaces_the_kept_stroke_opacity() {
|
||||
}
|
||||
}
|
||||
|
||||
/// An Eyedropper pick from a stroke row without paint onto a marker whose stroke had paint replaces the stroke opacity and
|
||||
/// blend mode the series' Filled Lines band left, in the pick's undo step: the band's outline is drawn opaque and Normal
|
||||
/// again. A pick onto a marker whose stroke had no paint before the pick leaves them as they are.
|
||||
#[test]
|
||||
fn an_eyedropper_pick_that_unpaints_a_series_stroke_clears_its_stored_transparency() {
|
||||
for stroked in [true, false] {
|
||||
let (mut s, id, band) = band_graph();
|
||||
let parts = series_parts(&s, id, 0);
|
||||
let (marker, source) = (parts[1].id, parts[2].id);
|
||||
let st = parts[2].appearance.stroke().unwrap();
|
||||
assert_eq!((st.paint.is_none(), st.opacity, st.blend), (true, 1.0, BlendMode::Normal), "the source's stroke row");
|
||||
if stroked {
|
||||
let row = top_row(&s, marker, false);
|
||||
s.execute("appearance.setItem", &json!({"ids": [marker.0], "index": row, "color": "#ff0000"})).unwrap();
|
||||
}
|
||||
let row = top_row(&s, band, false);
|
||||
s.execute("appearance.setItem", &json!({"ids": [band.0], "index": row, "opacity": 40, "blend": "multiply"})).unwrap();
|
||||
let was = spec(&s, id).series_paints;
|
||||
assert_eq!((was[0].stroke_opacity, was[0].stroke_blend), (Some(0.4), Some(BlendMode::Multiply)));
|
||||
s.execute("appearance.copyFrom", &json!({"source": source.0, "ids": [marker.0]})).unwrap();
|
||||
let picked = s.doc().unwrap().doc.node(marker).unwrap().appearance.stroke().unwrap().clone();
|
||||
assert_eq!((picked.paint.is_none(), picked.opacity, picked.blend), (true, 1.0, BlendMode::Normal), "stroked {stroked}");
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
let want = if stroked { (None, None) } else { (Some(0.4), Some(BlendMode::Multiply)) };
|
||||
assert_eq!((kept.stroke_opacity, kept.stroke_blend), want, "stroked {stroked}");
|
||||
if stroked {
|
||||
let after = spec(&s, id).series_paints;
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(spec(&s, id).series_paints, was);
|
||||
assert!(!s.doc().unwrap().doc.node(marker).unwrap().appearance.stroke_paint().is_none(), "the undo took back the pick");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(spec(&s, id).series_paints, after);
|
||||
}
|
||||
redrawn_band(&mut s, id);
|
||||
let st = series_parts(&s, id, 0)[0].appearance.stroke().unwrap().clone();
|
||||
assert_eq!((Some(st.opacity).filter(|o| *o < 1.0), Some(st.blend).filter(|b| *b != BlendMode::Normal)), want, "stroked {stroked}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A Filled Lines band's stroke row removed with the Appearance panel or set to None with `paint.setStroke` leaves the
|
||||
/// band its color: an empty stored stroke is not a color for the band.
|
||||
#[test]
|
||||
@@ -1686,6 +1804,364 @@ fn redefining_a_graphic_style_from_a_series_mark_keeps_the_paint_another_mark_st
|
||||
assert_eq!(spec(&s, id).series_paints, was);
|
||||
}
|
||||
|
||||
/// Series 0's group, and whether it is as the graph draws it: the group has no rows of its own and each path directly
|
||||
/// inside it has rows.
|
||||
fn series_0_group(s: &Session, id: NodeId) -> (NodeId, bool) {
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
let g = series(&n, 0);
|
||||
let drawn = g.appearance.items.is_empty() && g.children().unwrap().iter().all(|m| !m.appearance.items.is_empty());
|
||||
(g.id, drawn)
|
||||
}
|
||||
|
||||
/// `appearance.setItem` given a series group's id edits the paths directly inside it, so the graph stores the color and
|
||||
/// opacity and every mark has them after the graph is drawn again. The group keeps no rows of its own.
|
||||
#[test]
|
||||
fn an_appearance_item_set_on_a_series_group_edits_its_marks() {
|
||||
let (mut s, id, _, marks) = column_marks();
|
||||
let (group, drawn) = series_0_group(&s, id);
|
||||
assert!(drawn);
|
||||
let was = spec(&s, id).series_paints;
|
||||
let row = top_row(&s, marks[0], true);
|
||||
s.execute("appearance.setItem", &json!({"ids": [group.0], "index": row, "color": "#0000ff", "opacity": 40})).unwrap();
|
||||
assert!(series_0_group(&s, id).1, "the group has no rows of its own");
|
||||
let blue = s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.fill_paint();
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.fill.clone(), kept.fill_opacity), (Some(blue.clone()), Some(0.4)));
|
||||
let (stroke, weight) = {
|
||||
let m = s.doc().unwrap().doc.node(marks[0]).unwrap().clone();
|
||||
(m.appearance.stroke_paint(), m.appearance.stroke_width())
|
||||
};
|
||||
series_0_is(&mut s, id, (&blue, 0.4, &stroke, weight), &was);
|
||||
}
|
||||
|
||||
/// The other Appearance commands given a series group's id, picked with Group Selection or given in `ids`, edit the
|
||||
/// paths directly inside it, and the graph stores what they change: Add New Fill, Clear Appearance, Move Appearance onto
|
||||
/// the group, and an opacity set on a row with `transparency.set`.
|
||||
#[test]
|
||||
fn appearance_commands_given_a_series_group_edit_its_marks() {
|
||||
let (mut s, id, marks) = stored_red_stroke();
|
||||
let (group, _) = series_0_group(&s, id);
|
||||
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
|
||||
s.execute("appearance.addFill", &json!({})).unwrap();
|
||||
assert!(series_0_group(&s, id).1, "Add New Fill on the selected group");
|
||||
let rows = s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.items.iter().filter(|it| it.is_fill()).count();
|
||||
assert_eq!(rows, 2, "each mark has a new fill row");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
|
||||
let row = top_row(&s, marks[0], true);
|
||||
s.execute("transparency.set", &json!({"ids": [group.0], "item": row, "opacity": 30})).unwrap();
|
||||
assert!(series_0_group(&s, id).1);
|
||||
assert_eq!(spec(&s, id).series_paints[0].fill_opacity, Some(0.3));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
|
||||
s.execute("appearance.clear", &json!({"ids": [group.0]})).unwrap();
|
||||
assert_eq!(spec(&s, id).series_paints[0].fill, Some(Paint::None));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
|
||||
let (rect, blue) = blue_style(&mut s, "Blue", false);
|
||||
let was = spec(&s, id).series_paints;
|
||||
s.execute("object.setProps", &json!({"ids": [group.0], "opacity": 50})).unwrap();
|
||||
s.execute("appearance.transfer", &json!({"source": rect.0, "target": group.0, "copy": true})).unwrap();
|
||||
assert!(series_0_group(&s, id).1);
|
||||
assert_eq!(s.doc().unwrap().doc.node(group).unwrap().opacity, 1.0, "the appearance replaces the group's own opacity");
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.fill.clone(), kept.fill_opacity, kept.stroke), (Some(blue.clone()), Some(0.5), Some(Paint::None)));
|
||||
series_0_is(&mut s, id, (&blue, 0.5, &Paint::None, 0.0), &was);
|
||||
}
|
||||
|
||||
/// Moving the Contents row of a series group as the graph draws it, with no rows of its own, moves the group's own
|
||||
/// row: the paths inside it have none.
|
||||
#[test]
|
||||
fn moving_a_series_groups_contents_row_moves_its_own_row() {
|
||||
let (mut s, id, _, _) = column_marks();
|
||||
let (group, drawn) = series_0_group(&s, id);
|
||||
assert!(drawn);
|
||||
let out = s.execute("appearance.moveItem", &json!({"ids": [group.0], "from": "contents", "to": 0})).unwrap();
|
||||
assert_eq!(out["contents"], json!(0));
|
||||
}
|
||||
|
||||
/// Add New Stroke, Duplicate Item, Reorder Appearance Item and Remove Item given a series group's id edit the rows of
|
||||
/// the paths directly inside it, and the group keeps no rows of its own.
|
||||
#[test]
|
||||
fn row_commands_given_a_series_group_edit_its_marks_rows() {
|
||||
let (mut s, id, _, marks) = column_marks();
|
||||
let (group, _) = series_0_group(&s, id);
|
||||
let count = |s: &Session, fill: bool| -> Vec<usize> {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
marks.iter().map(|m| d.node(*m).unwrap().appearance.items.iter().filter(|it| it.is_fill() == fill).count()).collect()
|
||||
};
|
||||
let (fills, strokes) = (count(&s, true), count(&s, false));
|
||||
s.execute("appearance.addStroke", &json!({"ids": [group.0]})).unwrap();
|
||||
assert_eq!(count(&s, false), strokes.iter().map(|n| n + 1).collect::<Vec<_>>(), "each mark has a new stroke row");
|
||||
let fill = top_row(&s, marks[0], true);
|
||||
s.execute("appearance.duplicateItem", &json!({"ids": [group.0], "index": fill})).unwrap();
|
||||
assert_eq!(count(&s, true), fills.iter().map(|n| n + 1).collect::<Vec<_>>(), "each mark has a copy of its fill row");
|
||||
let rows = s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.items.len();
|
||||
let out = s.execute("appearance.moveItem", &json!({"ids": [group.0], "from": 0, "to": rows - 1})).unwrap();
|
||||
assert_eq!(out["index"], json!(rows - 1));
|
||||
s.execute("appearance.removeItem", &json!({"ids": [group.0], "index": top_row(&s, marks[0], true)})).unwrap();
|
||||
assert_eq!(count(&s, true), fills);
|
||||
assert!(series_0_group(&s, id).1, "the group has no rows of its own");
|
||||
}
|
||||
|
||||
/// Reduce to Basic Appearance given a series group's id reduces the paths directly inside it and drops an effect the
|
||||
/// group holds.
|
||||
#[test]
|
||||
fn reducing_a_series_group_reduces_its_marks_and_drops_its_own_effect() {
|
||||
let (mut s, id, _, marks) = column_marks();
|
||||
let (group, _) = series_0_group(&s, id);
|
||||
s.execute("appearance.addFill", &json!({"ids": [group.0]})).unwrap();
|
||||
s.execute("effect.apply", &json!({"ids": [group.0], "effect": "distort.twist"})).unwrap();
|
||||
s.execute("appearance.reduceToBasic", &json!({"ids": [group.0]})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.node(group).unwrap().appearance.effects.is_empty(), "the group's effect is dropped");
|
||||
assert!(marks.iter().all(|m| d.node(*m).unwrap().appearance.items.iter().filter(|it| it.is_fill()).count() == 1));
|
||||
assert!(series_0_group(&s, id).1);
|
||||
}
|
||||
|
||||
/// A graphic style added on top (Alt-click) given a series group's id adds its rows to the paths directly inside the
|
||||
/// group and unlinks a group that held a style link.
|
||||
#[test]
|
||||
fn a_graphic_style_added_to_a_series_group_adds_rows_to_its_marks_and_unlinks_the_group() {
|
||||
let (mut s, id, _, marks) = column_marks();
|
||||
let (group, _) = series_0_group(&s, id);
|
||||
blue_style(&mut s, "Blue", false);
|
||||
let style = s.doc().unwrap().doc.graphic_style("Blue").unwrap().id;
|
||||
s.edit("Link", |d, _| {
|
||||
d.node_mut(group).unwrap().extras_mut().graphic_style = Some(style);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let fills = |s: &Session, m: NodeId| s.doc().unwrap().doc.node(m).unwrap().appearance.items.iter().filter(|it| it.is_fill()).count();
|
||||
let was = fills(&s, marks[0]);
|
||||
s.execute("graphicStyle.apply", &json!({"name": "Blue", "ids": [group.0], "add": true})).unwrap();
|
||||
assert!(marks.iter().all(|m| fills(&s, *m) == was + 1), "each mark has the style's fill on top");
|
||||
assert!(series_0_group(&s, id).1, "the group takes no rows of the style");
|
||||
assert_eq!(s.doc().unwrap().doc.node(group).unwrap().extras().graphic_style, None, "the group is unlinked");
|
||||
}
|
||||
|
||||
/// Move Appearance from one of a series group's paths onto the group gives the other paths its look and leaves that
|
||||
/// path as it was. When the path is the only one directly in the group, the command is refused and the group takes no
|
||||
/// rows.
|
||||
#[test]
|
||||
fn moving_an_appearance_from_a_mark_onto_its_own_series_group_keeps_the_mark() {
|
||||
let (mut s, id, _, marks) = column_marks();
|
||||
let (group, _) = series_0_group(&s, id);
|
||||
s.execute("appearance.setItem", &json!({"ids": [marks[0].0], "index": top_row(&s, marks[0], true), "color": "#00ff00"})).unwrap();
|
||||
let green = s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.fill_paint();
|
||||
s.execute("appearance.transfer", &json!({"source": marks[0].0, "target": group.0})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(marks.iter().all(|m| d.node(*m).unwrap().appearance.fill_paint() == green), "every mark, the source too, is green");
|
||||
assert_eq!(spec(&s, id).series_paints[0].fill, Some(green));
|
||||
|
||||
s.edit("One path", |d, _| {
|
||||
d.children_mut(Some(group)).unwrap().truncate(1);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let only = s.doc().unwrap().doc.node(group).unwrap().children().unwrap()[0].id;
|
||||
let err = s.execute("appearance.transfer", &json!({"source": only.0, "target": group.0})).unwrap_err();
|
||||
assert!(err.to_string().contains("only path"), "{err}");
|
||||
assert!(series_0_group(&s, id).1, "the group has no rows of its own");
|
||||
}
|
||||
|
||||
/// A series group that holds an opacity and an effect of its own is read itself as a source, as any group is: a new
|
||||
/// graphic style and Move Appearance take the group's opacity and effect, and the group, not a path, is linked.
|
||||
#[test]
|
||||
fn a_series_group_with_a_look_of_its_own_is_read_itself_as_a_source() {
|
||||
let (mut s, id, _, marks) = column_marks();
|
||||
let (group, _) = series_0_group(&s, id);
|
||||
s.execute("transparency.set", &json!({"ids": [group.0], "opacity": 50, "item": null})).unwrap();
|
||||
s.execute("effect.apply", &json!({"ids": [group.0], "effect": "distort.twist"})).unwrap();
|
||||
s.execute("graphicStyle.new", &json!({"id": group.0, "name": "Series"})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let style = d.graphic_style("Series").unwrap();
|
||||
assert_eq!((style.opacity, style.appearance.effects.len()), (0.5, 1));
|
||||
assert_eq!(d.node(group).unwrap().extras().graphic_style, Some(style.id));
|
||||
assert!(marks.iter().all(|m| d.node(*m).unwrap().extras().graphic_style.is_none()));
|
||||
|
||||
let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("appearance.transfer", &json!({"source": group.0, "target": rect.0, "copy": true})).unwrap();
|
||||
let r = s.doc().unwrap().doc.node(rect).unwrap().clone();
|
||||
assert_eq!((r.opacity, r.appearance.effects.len()), (0.5, 1));
|
||||
}
|
||||
|
||||
/// Clear Appearance and Show All Hidden Attributes given a series group's id also reach an effect the group holds, and
|
||||
/// Break Link to Graphic Style unlinks the paths a style applied to the group linked.
|
||||
#[test]
|
||||
fn whole_appearance_commands_given_a_series_group_edit_the_group_and_its_marks() {
|
||||
let (mut s, id, marks) = stored_red_stroke();
|
||||
let (group, _) = series_0_group(&s, id);
|
||||
let effects = |s: &Session| s.doc().unwrap().doc.node(group).unwrap().appearance.effects.clone();
|
||||
s.execute("effect.apply", &json!({"ids": [group.0], "effect": "distort.twist"})).unwrap();
|
||||
s.execute("effect.setParams", &json!({"ids": [group.0], "index": 0, "visible": false, "item": null})).unwrap();
|
||||
assert!(!effects(&s)[0].visible);
|
||||
let shown = s.execute("appearance.showAllHidden", &json!({"ids": [group.0]})).unwrap();
|
||||
assert_eq!(shown["ids"], json!([group.0]));
|
||||
assert!(effects(&s)[0].visible);
|
||||
s.execute("appearance.clear", &json!({"ids": [group.0]})).unwrap();
|
||||
assert!(effects(&s).is_empty(), "the group's effect is cleared with its marks' rows");
|
||||
assert_eq!(spec(&s, id).series_paints[0].fill, Some(Paint::None));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
|
||||
blue_style(&mut s, "Blue", false);
|
||||
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
|
||||
s.execute("graphicStyle.apply", &json!({"name": "Blue"})).unwrap();
|
||||
assert_eq!(s.selection_graphic_style().map(|(g, linked)| (g.name.clone(), linked)), Some(("Blue".into(), true)));
|
||||
s.execute("graphicStyle.breakLink", &json!({})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(marks.iter().all(|m| d.node(*m).unwrap().extras().graphic_style.is_none()), "each mark is unlinked");
|
||||
assert!(s.selection_graphic_style().is_none());
|
||||
}
|
||||
|
||||
/// Redefine Graphic Style on a selected series group whose paths a style links takes the look of the topmost of them.
|
||||
#[test]
|
||||
fn redefining_a_graphic_style_from_a_selected_series_group_reads_its_topmost_mark() {
|
||||
let (mut s, id, marks) = stored_red_stroke();
|
||||
let (group, _) = series_0_group(&s, id);
|
||||
blue_style(&mut s, "Blue", false);
|
||||
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
|
||||
s.execute("graphicStyle.apply", &json!({"name": "Blue"})).unwrap();
|
||||
let top = *marks.last().unwrap();
|
||||
s.execute("appearance.setItem", &json!({"ids": [top.0], "index": top_row(&s, top, true), "color": "#00ff00"})).unwrap();
|
||||
let green = s.doc().unwrap().doc.node(top).unwrap().appearance.fill_paint();
|
||||
s.execute("graphicStyle.redefine", &json!({})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.graphic_style("Blue").unwrap().appearance.fill_paint(), green);
|
||||
assert!(marks.iter().all(|m| d.node(*m).unwrap().appearance.fill_paint() == green), "the marks still linked follow");
|
||||
}
|
||||
|
||||
/// A series group as the graph draws it, read as a source, gives the look of the topmost path directly inside it: New
|
||||
/// Graphic Style keeps that path's fill and links it, Move Appearance copies it, and a move clears every path of the
|
||||
/// group.
|
||||
#[test]
|
||||
fn a_series_group_read_as_a_source_gives_its_topmost_marks_look() {
|
||||
let (mut s, id, marks) = stored_red_stroke();
|
||||
let (group, _) = series_0_group(&s, id);
|
||||
let top = *marks.last().unwrap();
|
||||
s.execute("appearance.setItem", &json!({"ids": [group.0], "index": top_row(&s, marks[0], true), "color": "#0000ff", "opacity": 30})).unwrap();
|
||||
s.execute("appearance.setItem", &json!({"ids": [marks[0].0], "index": top_row(&s, marks[0], true), "color": "#00ff00"})).unwrap();
|
||||
let look = s.doc().unwrap().doc.node(top).unwrap().appearance.clone();
|
||||
assert_ne!(look.fill_paint(), s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.fill_paint());
|
||||
s.execute("graphicStyle.new", &json!({"id": group.0, "name": "Series"})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.graphic_style("Series").unwrap().appearance.fill_paint(), look.fill_paint());
|
||||
assert_eq!(d.node(top).unwrap().extras().graphic_style, Some(d.graphic_style("Series").unwrap().id));
|
||||
|
||||
let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("appearance.transfer", &json!({"source": group.0, "target": rect.0})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.node(rect).unwrap().appearance.fill_paint(), look.fill_paint());
|
||||
assert!(marks.iter().all(|m| d.node(*m).unwrap().appearance.fill_paint() == Paint::None), "the move clears each mark");
|
||||
assert_eq!(spec(&s, id).series_paints[0].fill, Some(Paint::None));
|
||||
}
|
||||
|
||||
/// A series group that has a row of its own, as a document saved earlier can hold, is edited itself: the Appearance
|
||||
/// panel lists that row and edits it by its index.
|
||||
#[test]
|
||||
fn a_series_group_with_a_row_of_its_own_is_edited_itself() {
|
||||
let (mut s, id, _, marks) = column_marks();
|
||||
let (group, _) = series_0_group(&s, id);
|
||||
s.edit("Row", |d, _| {
|
||||
let g = d.node_mut(group).unwrap();
|
||||
g.appearance = vectorcraft_doc::Appearance::basic(Paint::None, Paint::None, 1.0).into();
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let was = s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.clone();
|
||||
s.execute("appearance.setItem", &json!({"ids": [group.0], "index": top_row(&s, group, true), "color": "#0000ff"})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_ne!(d.node(group).unwrap().appearance.fill_paint(), Paint::None);
|
||||
assert_eq!(d.node(marks[0]).unwrap().appearance, was, "the marks keep their rows");
|
||||
}
|
||||
|
||||
/// A graphic style applied to a series group's id styles and links the paths directly inside it, and the graph stores
|
||||
/// the style's fill and stroke.
|
||||
#[test]
|
||||
fn a_graphic_style_applied_to_a_series_group_styles_its_marks() {
|
||||
let (mut s, id, marks) = stored_red_stroke();
|
||||
let (group, _) = series_0_group(&s, id);
|
||||
let (_, blue) = blue_style(&mut s, "Blue", false);
|
||||
let was = spec(&s, id).series_paints;
|
||||
let own = json!({"ids": [group.0], "opacity": 50, "blend": "multiply", "isolate": true, "knockout": "on", "item": null});
|
||||
s.execute("transparency.set", &own).unwrap();
|
||||
s.execute("effect.apply", &json!({"ids": [group.0], "effect": "distort.twist"})).unwrap();
|
||||
let g = s.doc().unwrap().doc.node(group).unwrap().clone();
|
||||
assert!(g.isolate && g.knockout != Default::default() && g.blend != vectorcraft_color::BlendMode::Normal);
|
||||
s.execute("graphicStyle.apply", &json!({"name": "Blue", "ids": [group.0]})).unwrap();
|
||||
assert!(series_0_group(&s, id).1, "the group takes no rows of the style");
|
||||
let g = s.doc().unwrap().doc.node(group).unwrap().clone();
|
||||
assert_eq!((g.opacity, g.isolate), (1.0, false), "the style replaces the group's own opacity and isolation");
|
||||
assert_eq!((g.blend, g.knockout), (vectorcraft_color::BlendMode::Normal, Default::default()), "and its blend mode and knockout");
|
||||
assert!(g.appearance.effects.is_empty(), "and its effects");
|
||||
let style = s.doc().unwrap().doc.graphic_style("Blue").unwrap().id;
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(marks.iter().all(|m| d.node(*m).unwrap().extras().graphic_style == Some(style)), "each mark is linked to the style");
|
||||
assert_eq!(d.node(group).unwrap().extras().graphic_style, None);
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.fill.clone(), kept.fill_opacity, kept.stroke), (Some(blue.clone()), Some(0.5), Some(Paint::None)));
|
||||
series_0_is(&mut s, id, (&blue, 0.5, &Paint::None, 0.0), &was);
|
||||
}
|
||||
|
||||
/// Redefine Graphic Style on a series group linked to the style (as a file can hold it) restyles the paths directly
|
||||
/// inside the group and links them, and the graph stores the new look; the group goes back to no rows of its own.
|
||||
#[test]
|
||||
fn redefining_a_graphic_style_restyles_the_marks_of_a_linked_series_group() {
|
||||
let (mut s, id, marks) = stored_red_stroke();
|
||||
let (group, _) = series_0_group(&s, id);
|
||||
let (rect, _) = blue_style(&mut s, "Blue", false);
|
||||
let style = s.doc().unwrap().doc.graphic_style("Blue").unwrap().clone();
|
||||
s.edit("Link", |d, _| {
|
||||
let g = d.node_mut(group).unwrap();
|
||||
g.appearance = style.appearance.clone().into();
|
||||
g.extras_mut().graphic_style = Some(style.id);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("appearance.setItem", &json!({"ids": [rect.0], "index": top_row(&s, rect, true), "color": "#00ff00", "opacity": 100})).unwrap();
|
||||
let green = s.doc().unwrap().doc.node(rect).unwrap().appearance.fill_paint();
|
||||
let was = spec(&s, id).series_paints;
|
||||
s.execute("graphicStyle.redefine", &json!({"name": "Blue", "id": rect.0})).unwrap();
|
||||
assert!(series_0_group(&s, id).1, "the group has no rows of its own");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.node(group).unwrap().extras().graphic_style, None);
|
||||
assert!(marks.iter().all(|m| d.node(*m).unwrap().extras().graphic_style == Some(style.id)));
|
||||
assert!(marks.iter().all(|m| d.node(*m).unwrap().appearance.fill_paint() == green));
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.fill.clone(), kept.fill_opacity, kept.stroke), (Some(green.clone()), None, Some(Paint::None)));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(spec(&s, id).series_paints, was, "one undo takes back the redefinition and what the graph stored");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
series_0_is(&mut s, id, (&green, 1.0, &Paint::None, 0.0), &was);
|
||||
}
|
||||
|
||||
/// Redefine Graphic Style on a linked series group leaves a path of the group that is linked to the style but no
|
||||
/// longer has its look as it is, unlinked, and restyles the group's other paths.
|
||||
#[test]
|
||||
fn redefining_a_graphic_style_keeps_an_edited_mark_of_a_linked_series_group() {
|
||||
let (mut s, id, _, marks) = column_marks();
|
||||
let (group, _) = series_0_group(&s, id);
|
||||
let (rect, _) = blue_style(&mut s, "Blue", false);
|
||||
let style = s.doc().unwrap().doc.graphic_style("Blue").unwrap().clone();
|
||||
s.edit("Link", |d, _| {
|
||||
let g = d.node_mut(group).unwrap();
|
||||
g.appearance = style.appearance.clone().into();
|
||||
g.extras_mut().graphic_style = Some(style.id);
|
||||
d.node_mut(marks[0]).unwrap().extras_mut().graphic_style = Some(style.id);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let edited = s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.clone();
|
||||
s.execute("appearance.setItem", &json!({"ids": [rect.0], "index": top_row(&s, rect, true), "color": "#00ff00", "opacity": 100})).unwrap();
|
||||
let green = s.doc().unwrap().doc.node(rect).unwrap().appearance.fill_paint();
|
||||
s.execute("graphicStyle.redefine", &json!({"name": "Blue", "id": rect.0})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let first = d.node(marks[0]).unwrap();
|
||||
assert_eq!((&first.appearance, first.extras().graphic_style), (&edited, None), "the edited mark keeps its look, unlinked");
|
||||
assert!(marks[1..].iter().all(|m| d.node(*m).unwrap().appearance.fill_paint() == green));
|
||||
assert!(marks[1..].iter().all(|m| d.node(*m).unwrap().extras().graphic_style == Some(style.id)));
|
||||
}
|
||||
|
||||
/// Default Fill and Stroke on a series mark stores a white fill and a 1 pt black stroke, both opaque, on the graph.
|
||||
#[test]
|
||||
fn default_fill_and_stroke_on_a_series_mark_is_kept() {
|
||||
|
||||
@@ -14,8 +14,8 @@ use vectorcraft_doc::{Artboard, ArtboardSide, Document, LAYER_COLORS, LayerColor
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
|
||||
use super::{
|
||||
CommandSpec, Result, Session, bad, bool_or, check_numbers, check_switches, checked_id, checked_ids_param, cmd, color_value, f64_or, has_doc,
|
||||
has_selection, ids_param, index, object_param, ok, str_param, switch_or,
|
||||
CommandSpec, Result, Session, bad, bool_or, check_numbers, check_switches, checked_id, checked_ids_param, checked_node, checked_nodes_param, cmd,
|
||||
color_value, f64_or, has_doc, has_selection, ids_param, index, object_param, ok, str_param, switch_or,
|
||||
};
|
||||
use crate::EngineError;
|
||||
|
||||
@@ -83,7 +83,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Layer Options…",
|
||||
["Window", "Layers"],
|
||||
None,
|
||||
"{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. One undo step",
|
||||
"{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked, and `ids` may name ruler guides (their `guide.list` id), which hide or lock on their own. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. One undo step",
|
||||
has_doc,
|
||||
set_props
|
||||
),
|
||||
@@ -200,7 +200,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Paste Remembers Layers",
|
||||
["Window", "Layers"],
|
||||
None,
|
||||
"{on?} (default: toggle) the document option: on, the Paste commands put objects back into the layers they were copied from (by name; a missing one is made on top), off into the current layer; one undo step when it changes (document.inspect → pasteRemembersLayers) → {on}",
|
||||
"{on?} (default: toggle) the document option: on, the Paste commands put objects back into the layers or sublayers they were copied from (in that document while they are still there, else by the names of the layer and the layers around it, the topmost match first; a missing sublayer is made inside its layer, a missing top-level layer on top; a hidden or locked one is an error and nothing is pasted), off into the current layer; one undo step when it changes (document.inspect → pasteRemembersLayers) → {on}",
|
||||
has_doc,
|
||||
paste_remembers_layers
|
||||
),
|
||||
@@ -210,11 +210,16 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
/// The rows a panel command acts on: `ids` or `id`, else the highlighted rows, else the current
|
||||
/// layer (capped at [`MAX_ROWS`]).
|
||||
pub(crate) fn rows_param(s: &Session, p: &Value, command: &str) -> Result<Vec<NodeId>> {
|
||||
rows_or_guides_param(s, p, command, false)
|
||||
}
|
||||
|
||||
/// The rows [`rows_param`] reads; given ruler guide ids are taken too when `guides`, else refused.
|
||||
fn rows_or_guides_param(s: &Session, p: &Value, command: &str, guides: bool) -> Result<Vec<NodeId>> {
|
||||
// Presence is explicit intent: validate every target before fallback, truncation or edits.
|
||||
let mut ids = if p.get("ids").is_some() {
|
||||
checked_ids_param(s, p, "ids", command)?
|
||||
checked_nodes_param(s, p, "ids", command, guides)?
|
||||
} else if let Some(id) = p.get("id") {
|
||||
vec![checked_id(s, id, command)?]
|
||||
vec![checked_node(s, id, command, guides)?]
|
||||
} else {
|
||||
let st = s.doc()?;
|
||||
let rows = st.highlighted_rows();
|
||||
@@ -637,7 +642,8 @@ fn set_props(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "layer.setProps";
|
||||
let xml_id = s.prefs.identify_objects_by == "xmlId";
|
||||
check_options(C, p, xml_id)?;
|
||||
let ids = rows_param(s, p, C)?;
|
||||
// A ruler guide's row takes visible and locked: its own eye and lock.
|
||||
let ids = rows_or_guides_param(s, p, C, true)?;
|
||||
if ids.is_empty() {
|
||||
return Err(bad(C, "no rows"));
|
||||
}
|
||||
|
||||
@@ -346,6 +346,36 @@ impl Library {
|
||||
}
|
||||
}
|
||||
|
||||
/// Name item `r` `name`, in its place in its kind's list; an item keyed by its name keeps its
|
||||
/// group under the new name (a graphic is keyed by its id, which stays).
|
||||
fn rename_item(&mut self, r: &ItemRef, name: &str) {
|
||||
fn set<'a>(mut names: impl Iterator<Item = &'a mut String>, from: &str, to: &str) {
|
||||
if let Some(n) = names.find(|n| n.as_str() == from) {
|
||||
*n = to.to_string();
|
||||
}
|
||||
}
|
||||
let from = r.item.as_str();
|
||||
match r.kind {
|
||||
ItemKind::Color => set(self.colors.iter_mut().map(|c| &mut c.name), from, name),
|
||||
ItemKind::Gradient => set(self.gradients.iter_mut().map(|g| &mut g.name), from, name),
|
||||
ItemKind::Pattern => set(self.patterns.iter_mut().map(|p| &mut p.name), from, name),
|
||||
ItemKind::CharStyle => set(self.char_styles.iter_mut().map(|t| &mut t.name), from, name),
|
||||
ItemKind::ParaStyle => set(self.para_styles.iter_mut().map(|t| &mut t.name), from, name),
|
||||
ItemKind::Graphic => {
|
||||
if let Some(g) = self.graphics.iter_mut().find(|g| g.id == from) {
|
||||
g.name = name.to_string();
|
||||
}
|
||||
return;
|
||||
}
|
||||
ItemKind::Unknown => return,
|
||||
}
|
||||
for x in self.groups.iter_mut().flat_map(|g| g.items.iter_mut()) {
|
||||
if x == r {
|
||||
x.item = name.to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Move item `r` next to `to`, an item of its kind: just before it, or just after it when
|
||||
/// `after`, in their kind's list (the order the panel shows them in).
|
||||
fn place_next_to(&mut self, r: &ItemRef, to: &ItemRef, after: bool) {
|
||||
@@ -683,7 +713,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Use Library Item",
|
||||
[],
|
||||
None,
|
||||
"{library?, kind, item: name (graphic: id or name), center?: [x, y] (graphic; default: the first artboard's centre), to?: fill|stroke (colors, gradients, patterns; default: the kind's), recorded?: the item as it was when used (recorded in the journal so a replay matches)} graphic: place a copy centred on `center`, its resources pasted along, selected, one undo step; colors and gradients: paint the selection (and the defaults) as paint.setFill/paint.setStroke, a gradient fitting each object; a spot color links to the document's spot swatch of its ink's name, added when the document has none of that colour (a name taken by another colour gets a number), one undo step; patterns: add the pattern and its swatch to the document (a name the document gives another pattern gets a number; the same pattern is reused) and paint the selection (and the defaults) with it, one undo step; charStyle/paraStyle: add the style to the document (a name taken by different attributes gets a number) and apply it to the selected text, one undo step → {kind, ids?, style?}",
|
||||
"{library?, kind, item: name (graphic: id or name), center?: [x, y] (graphic; default: the first artboard's centre), to?: fill|stroke (colors, gradients, patterns; default: the kind's), recorded?: the item as it was when used (recorded in the journal so a replay matches)} graphic: place a copy centred on `center`, its resources pasted along, selected, one undo step; colors and gradients: paint the selection (and the defaults) as paint.setFill/paint.setStroke, a gradient fitting each object; a spot color links to the document's spot swatch of its ink's name, added when the document has none of that colour (a name taken by another colour gets a number), one undo step; patterns: add the pattern and its swatch to the document (a name the document gives another pattern gets a number; the same pattern is reused) and paint the selection (and the defaults) with it, one undo step; charStyle/paraStyle: add the style to the document (a name taken by different attributes gets a number; a character style's color linked to a swatch that isn't a global or spot swatch of the document keeps the color it shows, unlinked) and apply it to the selected text, one undo step → {kind, ids?, style?}",
|
||||
has_doc,
|
||||
use_item
|
||||
),
|
||||
@@ -696,6 +726,24 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
remove_item
|
||||
),
|
||||
cmd!(
|
||||
"library.renameItem",
|
||||
"Rename Library Item",
|
||||
[],
|
||||
None,
|
||||
"{library?, kind, item: name (graphic: id or name), name: string (trimmed; 1 to 256 characters)} rename an item; it keeps its place and its group; another item of its kind with that name is an error, and its own name changes nothing; not undoable → {library, kind, item: its key now (graphic: its id), name}",
|
||||
always,
|
||||
rename_item
|
||||
),
|
||||
cmd!(
|
||||
"library.addToCharacterStyles",
|
||||
"Add to Character Styles",
|
||||
[],
|
||||
None,
|
||||
"{library?, item: a character style's name, recorded?: the style as it was when added (recorded in the journal so a replay matches)} add a library character style to the document's character styles without applying it (no text needs to be selected): a document style of that name with the same attributes is reused, a name taken by different attributes gets a number; a color linked to a swatch that isn't a global or spot swatch of the document keeps the color it shows, unlinked; a new style is one undo step, a reused one none → {style: its name in the document, existing: bool}",
|
||||
has_doc,
|
||||
add_to_char_styles
|
||||
),
|
||||
cmd!(
|
||||
"library.createGroup",
|
||||
"New Library Group",
|
||||
@@ -1231,8 +1279,13 @@ fn use_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Kind::CharStyle | Kind::ParaStyle => {
|
||||
let para = kind == Kind::ParaStyle;
|
||||
let name = data.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).unwrap_or("Style").to_string();
|
||||
let attrs = data.get("attrs").and_then(Value::as_object).cloned().unwrap_or_default();
|
||||
let mut attrs = data.get("attrs").and_then(Value::as_object).cloned().unwrap_or_default();
|
||||
let doc = &s.doc()?.doc;
|
||||
if !para {
|
||||
unlink_missing_swatches(doc, &mut attrs);
|
||||
}
|
||||
// Compared in the form the document stores them in.
|
||||
let attrs = super::textstyles::stored_style_attrs(doc, para, &attrs).unwrap_or(attrs);
|
||||
// The document's style of that name when it is the same; else a new one.
|
||||
let same = super::textstyles::style_attrs(doc, para, &name).is_some_and(|a| a == attrs);
|
||||
let style = if same { name } else { unique(&name, |n| super::textstyles::style_attrs(doc, para, n).is_some()) };
|
||||
@@ -1361,6 +1414,109 @@ fn remove_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
fn rename_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "library.renameItem";
|
||||
let (id, kind, item) = item_param(s, p, C)?;
|
||||
let name = match p.get("name") {
|
||||
None | Some(Value::Null) => return Err(bad(C, "missing `name`")),
|
||||
Some(Value::String(n)) => n.trim().to_string(),
|
||||
Some(_) => return Err(bad(C, "`name` must be a string")),
|
||||
};
|
||||
if name.is_empty() {
|
||||
return Err(bad(C, "missing `name`"));
|
||||
}
|
||||
if name.chars().count() > MAX_NAME {
|
||||
let (label, max) = ("`name`", MAX_NAME);
|
||||
return Err(bad(C, format!("{label} must be at most {max} characters")));
|
||||
}
|
||||
let lib = s.libraries.get(&id).ok_or_else(|| bad(C, format!("no library `{id}`")))?;
|
||||
let r = lib.item_ref(kind.item_kind(), item).ok_or_else(|| bad(C, format!("the library has no item `{item}`")))?;
|
||||
// The item's name now, and whether another item of its kind has the new one.
|
||||
let mut same = false;
|
||||
let mut taken = false;
|
||||
for (_, key, shown) in lib.items().filter(|(k, ..)| *k == r.kind) {
|
||||
if key == r.item {
|
||||
same = shown == name;
|
||||
} else if shown == name {
|
||||
taken = true;
|
||||
}
|
||||
}
|
||||
let key = if r.kind == ItemKind::Graphic { r.item.clone() } else { name.clone() };
|
||||
let out = json!({ "library": id, "kind": str_param(p, "kind"), "item": key, "name": name });
|
||||
if same {
|
||||
return Ok(out);
|
||||
}
|
||||
if taken {
|
||||
return Err(bad(C, format!("the library has another item of that kind named `{name}`")));
|
||||
}
|
||||
s.libraries.change(&id, |lib| {
|
||||
lib.rename_item(&r, &name);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn add_to_char_styles(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "library.addToCharacterStyles";
|
||||
// A replay (the journal) carries what the style was, so it doesn't depend on the library.
|
||||
let data = match p.get("recorded").cloned() {
|
||||
Some(r) => r,
|
||||
None => {
|
||||
let id = library_id(s, p, C)?;
|
||||
let item = str_param(p, "item").ok_or_else(|| bad(C, "missing `item`"))?;
|
||||
let lib = s.libraries.get(&id).ok_or_else(|| bad(C, format!("no library `{id}`")))?;
|
||||
let t = lib.char_styles.iter().find(|t| t.name == item).ok_or_else(|| bad(C, format!("the library has no item `{item}`")))?;
|
||||
let data = json!({ "name": t.name, "attrs": t.attrs });
|
||||
s.note_journal("recorded", data.clone());
|
||||
data
|
||||
}
|
||||
};
|
||||
let name = data.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).unwrap_or("Style").to_string();
|
||||
let mut attrs = data.get("attrs").and_then(Value::as_object).cloned().ok_or_else(|| bad(C, "the library item is damaged"))?;
|
||||
let doc = &s.doc()?.doc;
|
||||
unlink_missing_swatches(doc, &mut attrs);
|
||||
// Compared in the form the document stores them in.
|
||||
let attrs = super::textstyles::stored_style_attrs(doc, false, &attrs).unwrap_or(attrs);
|
||||
// The document's style of that name when it is the same; else a new one, which isn't applied.
|
||||
if super::textstyles::style_attrs(doc, false, &name).is_some_and(|a| a == attrs) {
|
||||
return Ok(json!({ "style": name, "existing": true }));
|
||||
}
|
||||
let style = unique(&name, |n| super::textstyles::style_attrs(doc, false, n).is_some());
|
||||
s.execute("charStyle.new", &json!({ "name": style, "attrs": attrs }))?;
|
||||
Ok(json!({ "style": style, "existing": false }))
|
||||
}
|
||||
|
||||
/// Unlink a library character style's `fill` and `stroke` colors (solid, and each gradient stop)
|
||||
/// from swatches that are not global or spot swatches of `doc`: an unlinked color keeps the color
|
||||
/// it shows at full tint, as [`clean_gradient`] keeps a library gradient's stops. A link to a
|
||||
/// global or spot swatch `doc` has stays, and takes that swatch's color.
|
||||
fn unlink_missing_swatches(doc: &vectorcraft_doc::Document, attrs: &mut Map<String, Value>) {
|
||||
let keep = |name: &str| doc.global_color(name).is_some();
|
||||
for key in ["fill", "stroke"] {
|
||||
let Some(mut paint) = attrs.get(key).and_then(|v| serde_json::from_value::<Paint>(v.clone()).ok()) else { continue };
|
||||
let mut changed = false;
|
||||
let mut unlink = |swatch: &mut Option<String>, tint: &mut f32| {
|
||||
if swatch.as_deref().is_some_and(|n| !keep(n)) {
|
||||
*swatch = None;
|
||||
*tint = 1.0;
|
||||
changed = true;
|
||||
}
|
||||
};
|
||||
match &mut paint {
|
||||
Paint::Solid { swatch, tint, .. } => unlink(swatch, tint),
|
||||
Paint::Gradient(g) => {
|
||||
for st in &mut g.gradient.stops {
|
||||
unlink(&mut st.swatch, &mut st.tint);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if changed && let Ok(v) = serde_json::to_value(&paint) {
|
||||
attrs.insert(key.to_string(), v);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `p`'s `name`, trimmed and clipped, else `default`.
|
||||
fn name_param(p: &Value, default: &str) -> String {
|
||||
let mut name = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).unwrap_or(default).to_string();
|
||||
|
||||
@@ -13,7 +13,7 @@ use serde_json::{Value, json};
|
||||
use vectorcraft_doc::NodeKind;
|
||||
|
||||
use super::findfiles::{self, Limits, Visitor};
|
||||
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, bool_or, checked_ids_param, cmd};
|
||||
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, bool_or, cmd, ids_param};
|
||||
|
||||
/// The most linked files one search looks for.
|
||||
const MAX_LINKS: usize = 1_000;
|
||||
@@ -143,8 +143,14 @@ fn find(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = match p.get("ids") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(_) => {
|
||||
let ids = checked_ids_param(s, p, "ids", C)?;
|
||||
let linkable = |id: &NodeId| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Image(_) | NodeKind::PlacedDocument(_)));
|
||||
// Images and placed documents in opacity-mask art and in the art of symbols, graph
|
||||
// designs and patterns are named by their ids too (`links.list`).
|
||||
let ids = ids_param(p, "ids", C)?.unwrap_or_default();
|
||||
let kind = |id: &NodeId| st.doc.stored_node(*id).map(|(n, _)| &n.kind);
|
||||
if let Some(value) = ids.iter().find(|id| kind(id).is_none()).map(|id| id.0) {
|
||||
return Err(bad(C, format!("no such object id {value}")));
|
||||
}
|
||||
let linkable = |id: &NodeId| matches!(kind(id), Some(NodeKind::Image(_) | NodeKind::PlacedDocument(_)));
|
||||
if let Some(id) = ids.iter().find(|id| !linkable(id)) {
|
||||
return Err(bad(C, format!("object {} is not an image or a linked file", id.0)));
|
||||
}
|
||||
|
||||
+256
-99
@@ -30,6 +30,7 @@ use serde_json::{Value, json};
|
||||
use vectorcraft_doc::links::{Align, Preserve, hash_bytes};
|
||||
use vectorcraft_doc::{
|
||||
Appearance, DataValue, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeId, NodeKind, PageBox, PlacedDocument, PlacementOptions,
|
||||
StoredPlace, StoredRoot,
|
||||
};
|
||||
use vectorcraft_geom::{Affine, FillRule, PathData, Rect, shapes};
|
||||
|
||||
@@ -43,7 +44,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Check Links",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [image or placed document ids] (default: every linked image and placed document)} where each linked file is and whether it changed since it was read → {links: [{name, path?, status: ok|modified|missing, ids, found?: path (found away from its path: relative to the document, or by name in its folder), preview: true (showing the low-resolution preview, not the file), refused?: why the path is not followed (another computer, a device or a URL: it counts as missing)}], missing, modified}; under automation read roots, path and found are left out when the file they name is outside the roots",
|
||||
"{ids?: [image or placed document ids] (default: every linked image and placed document, in the layers and in opacity-mask art, symbols, graph designs and patterns)} where each linked file is and whether it changed since it was read → {links: [{name, path?, status: ok|modified|missing, ids, found?: path (found away from its path: relative to the document, or by name in its folder), preview: true (showing the low-resolution preview, not the file), refused?: why the path is not followed (another computer, a device or a URL: it counts as missing)}], missing, modified}; under automation read roots, path and found are left out when the file they name is outside the roots",
|
||||
has_doc,
|
||||
check
|
||||
),
|
||||
@@ -52,7 +53,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Update Links",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. The images and placed documents inside symbols, graph designs, patterns and opacity masks that show the same content are read again too (by default also those only that art shows); they have no ids to list. One undo step → {updated: [ids], missing: [ids], warnings?: [a DCS file's spot plate whose ink a swatch of the document already names, as file.place warns]}",
|
||||
"{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. Images and placed documents inside symbols, graph designs, patterns and opacity masks have ids of their own, as links.list gives them; those that show the same content as one read again are read again too. One undo step → {updated: [ids], missing: [ids], warnings?: [a DCS file's spot plate whose ink a swatch of the document already names, as file.place warns]}",
|
||||
has_doc,
|
||||
update
|
||||
),
|
||||
@@ -70,7 +71,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Relink",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, scope?: selected (default: ids) | all (ids and every other object in the layers linked to the same file as one of them) | missingInFolder (with path: ids, then every other missing link whose file name is in path's folder, each to the file of its name there; names not there are in notFound; with copy, only images are looked for) | each (with paths), paths?: [{ids, path}] (with scope each, in place of ids, path and folder: each link to its own file; an id in two entries is an error), copy?: false (with path or paths, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used; an error for a DCS file that reads plate files of its own), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy; to is the file name alone when the document's folder is outside the automation read roots), warnings?: (as links.update's)}",
|
||||
"{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, scope?: selected (default: ids) | all (ids and every other object linked to the same file as one of them, in the layers, opacity-mask art, symbols, graph designs and patterns) | missingInFolder (with path: ids, then every other missing link whose file name is in path's folder, each to the file of its name there; names not there are in notFound; with copy, only images are looked for) | each (with paths), paths?: [{ids, path}] (with scope each, in place of ids, path and folder: each link to its own file; an id in two entries is an error), copy?: false (with path or paths, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used; an error for a DCS file that reads plate files of its own), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy; to is the file name alone when the document's folder is outside the automation read roots), warnings?: (as links.update's)}",
|
||||
has_doc,
|
||||
relink
|
||||
),
|
||||
@@ -79,7 +80,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Links",
|
||||
[],
|
||||
None,
|
||||
"{show?: all (default)|missing|modified|embedded, sort?: name|kind (file format)|status (missing, modified, ok, embedded); default: stacking order; top first, dcsTransparency?: false (Show DCS Transparency Interactions: mark the images placed from DCS files that are transparent, themselves or a group or layer holding them, or that overlap a visible object with its own transparency; it looks at every object, so it takes longer)} every image object and placed document in the layers, as the Links panel lists them → {links: [{id, name, linked, status: ok|modified|missing|embedded, format (DCS for an image placed from a DCS file), pixelWidth, pixelHeight, path?, found?: path (found away from its path), page?, preview?: true (showing the saved preview), note?: said of an image past the decode allowance (shown at reduced size, or too large to draw), document?: true (a placed document: pageWidth and pageHeight in pt instead of pixels), dcsTransparency?: true (with dcsTransparency)}], missing, modified, embedded}; under automation read roots, path and found are left out when the file they name is outside the roots",
|
||||
"{show?: all (default)|missing|modified|embedded, sort?: name|kind (file format)|status (missing, modified, ok, embedded); default: stacking order; top first, dcsTransparency?: false (Show DCS Transparency Interactions: mark the images placed from DCS files that are transparent, themselves or a group or layer holding them, or that overlap a visible object with its own transparency; it looks at every object, so it takes longer)} every image object and placed document the document stores, as the Links panel lists them: those in the layers, then those in opacity-mask art and in the art of symbols, graph designs and patterns (one row per stored object, never one per symbol instance or pattern tile) → {links: [{id, name, linked, status: ok|modified|missing|embedded, format (DCS for an image placed from a DCS file), pixelWidth, pixelHeight, path?, found?: path (found away from its path), page?, preview?: true (showing the saved preview), note?: said of an image past the decode allowance (shown at reduced size, or too large to draw), document?: true (a placed document: pageWidth and pageHeight in pt instead of pixels), dcsTransparency?: true (with dcsTransparency), owner?: {kind: layers|symbol|graphDesign|pattern, name? (of the symbol, graph design or pattern), maskOf?: id (in the opacity-mask art of that object)} (an object outside the layer tree)}], missing, modified, embedded}; under automation read roots, path and found are left out when the file they name is outside the roots",
|
||||
has_doc,
|
||||
list
|
||||
),
|
||||
@@ -88,7 +89,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Go To Link",
|
||||
[],
|
||||
None,
|
||||
"{id?} select image or placed document `id` (default: the first selected one); the Links panel scrolls it into view → {id, bounds: [x0, y0, x1, y1]}",
|
||||
"{id?} select image or placed document `id` (default: the first selected one); the Links panel scrolls it into view → {id, bounds: [x0, y0, x1, y1], onCanvas: true}; one in opacity-mask art or in the art of a symbol, graph design or pattern has no place of its own on the canvas: the selection is cleared → {id, onCanvas: false, owner} (owner as links.list gives it)",
|
||||
has_doc,
|
||||
go_to
|
||||
),
|
||||
@@ -156,7 +157,8 @@ impl Status {
|
||||
struct Group {
|
||||
link: LinkInfo,
|
||||
key: String,
|
||||
/// The objects in the layers (images in symbols and patterns share the content, not an id).
|
||||
/// The stored objects showing it: in the layers, in opacity-mask art and in the art of symbols,
|
||||
/// graph designs and patterns ([`Document::visit_stored`]), each once.
|
||||
ids: Vec<NodeId>,
|
||||
/// Placed documents: what they show.
|
||||
document: Option<Shown>,
|
||||
@@ -177,8 +179,9 @@ fn linked(n: &Node) -> Option<(&LinkInfo, &str, Option<Shown>)> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Every linked file of `d` with the ids of the objects showing it (for [`crate::link_watch`]): an
|
||||
/// image placed from a DCS file has its plate files of their own too, beside its file.
|
||||
/// Every linked file of `d` with the ids of the objects showing it, wherever they are stored (for
|
||||
/// [`crate::link_watch`]): an image placed from a DCS file has its plate files of their own too,
|
||||
/// beside its file.
|
||||
pub(crate) fn linked_groups(d: &Document) -> Vec<(String, Vec<u64>)> {
|
||||
let mut out = vec![];
|
||||
for g in groups(d, None).into_iter().filter(|g| !g.ids.is_empty()) {
|
||||
@@ -190,8 +193,10 @@ pub(crate) fn linked_groups(d: &Document) -> Vec<(String, Vec<u64>)> {
|
||||
out
|
||||
}
|
||||
|
||||
/// The linked images and placed documents of `d` by file and content: those in the layers (only `ids` when
|
||||
/// given), then, without `ids`, the ones only symbols and patterns show.
|
||||
/// The linked images and placed documents of `d` by file and content, wherever they are stored
|
||||
/// (only `ids` when given), in [`Document::visit_stored`] order. An object whose id an object
|
||||
/// visited before it has (art being edited on a layer and its definition) counts once, by its
|
||||
/// first place; without `ids` its content is still grouped.
|
||||
fn groups(d: &Document, ids: Option<&[NodeId]>) -> Vec<Group> {
|
||||
let mut out: Vec<Group> = vec![];
|
||||
let mut index: BTreeMap<(String, String, bool), usize> = BTreeMap::new();
|
||||
@@ -210,24 +215,48 @@ fn groups(d: &Document, ids: Option<&[NodeId]>) -> Vec<Group> {
|
||||
g.ids.push(id);
|
||||
}
|
||||
};
|
||||
d.walk(|n| {
|
||||
if let Some((l, key, document)) = linked(n)
|
||||
&& wanted.as_ref().is_none_or(|ids| ids.contains(&n.id))
|
||||
{
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
d.visit_stored(|n, _| {
|
||||
let Some((l, key, document)) = linked(n) else { return };
|
||||
// Id 0 names no object.
|
||||
let first = n.id.0 != 0 && seen.insert(n.id);
|
||||
if first && wanted.as_ref().is_none_or(|ids| ids.contains(&n.id)) {
|
||||
add(l, key, document, Some(n.id));
|
||||
} else if ids.is_none() {
|
||||
add(l, key, document, None);
|
||||
}
|
||||
});
|
||||
if ids.is_none() {
|
||||
d.visit_images(|_, im| {
|
||||
if let Some(l) = &im.link {
|
||||
add(l, &im.key, None, None);
|
||||
}
|
||||
});
|
||||
d.visit_placed(|_, p| add(&p.link, &p.key, Some((p.bounding, p.page_box)), None));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Stored object `id` of `d` ([`Document::stored_node`]).
|
||||
fn stored(d: &Document, id: NodeId) -> Option<&Node> {
|
||||
d.stored_node(id).map(|(n, _)| &**n)
|
||||
}
|
||||
|
||||
/// Of `ids`, the objects of `d` outside the layer tree (where [`Document::node`] finds none).
|
||||
fn nested_ids(d: &Document, ids: &[NodeId]) -> std::collections::HashSet<NodeId> {
|
||||
ids.iter().copied().filter(|id| d.node(*id).is_none()).collect()
|
||||
}
|
||||
|
||||
/// `links.list`'s `owner` of an object stored at `place` of `d`, when it is not in the layer tree
|
||||
/// itself: `{kind: layers|symbol|graphDesign|pattern, name?, maskOf?}`.
|
||||
fn owner_json(d: &Document, place: StoredPlace) -> Option<Value> {
|
||||
if place.in_layers() {
|
||||
return None;
|
||||
}
|
||||
let mut owner = match place.root {
|
||||
StoredRoot::Layer(_) => json!({ "kind": "layers" }),
|
||||
StoredRoot::Symbol(i) => json!({ "kind": "symbol", "name": d.symbols.get(i).map(|s| s.name.as_str()) }),
|
||||
StoredRoot::GraphDesign(i) => json!({ "kind": "graphDesign", "name": d.graph_designs.get(i).map(|g| g.name.as_str()) }),
|
||||
StoredRoot::Pattern { pattern, .. } => json!({ "kind": "pattern", "name": d.patterns.get(pattern).map(|p| p.name.as_str()) }),
|
||||
};
|
||||
if let Some(m) = place.mask_of {
|
||||
owner["maskOf"] = json!(m.0);
|
||||
}
|
||||
Some(owner)
|
||||
}
|
||||
|
||||
/// A linked file where it was found.
|
||||
struct Found {
|
||||
path: String,
|
||||
@@ -387,6 +416,26 @@ fn keep_eps_preview(low_res_proxy_eps: bool, g: &Group, d: &Document) -> bool {
|
||||
low_res_proxy_eps && g.document.is_none() && linked_eps(&g.link) && previewing(d, &g.key)
|
||||
}
|
||||
|
||||
/// Is the linked file `f` found a DCS file? Only the start of the file is read, unless a binary EPS
|
||||
/// header puts its PostScript further on; a DCS file read in full stays in `f`. A file that can't
|
||||
/// be read is not one.
|
||||
fn is_dcs_file(f: &mut Found) -> bool {
|
||||
use super::place::dcs;
|
||||
if let Some(b) = &f.bytes {
|
||||
return dcs::is_dcs(b);
|
||||
}
|
||||
let Ok(head) = fileio::read_file_head(&f.path, dcs::HEAD_BYTES) else { return false };
|
||||
if let Some(is) = dcs::head_is_dcs(&head, f.size) {
|
||||
return is;
|
||||
}
|
||||
let Ok(b) = f.read() else { return false };
|
||||
let is = dcs::is_dcs(&b);
|
||||
if is {
|
||||
f.bytes = Some(b);
|
||||
}
|
||||
is
|
||||
}
|
||||
|
||||
/// Does group `g` of `d` show something other than its file: an image its preview, a placed
|
||||
/// document nothing (its file's bytes are gone)?
|
||||
fn stale(d: &Document, g: &Group) -> bool {
|
||||
@@ -473,8 +522,8 @@ pub(crate) fn full_linked_images<'a>(d: &'a Document, base: LinkBase) -> (Cow<'a
|
||||
}
|
||||
|
||||
/// The linked files of the open document `st` that `links.findFiles` looks for, each with the
|
||||
/// objects in the layers that show it: the files of objects `ids` whatever their status, else the
|
||||
/// files that can't be found.
|
||||
/// stored objects that show it: the files of objects `ids` whatever their status, else the files
|
||||
/// that can't be found.
|
||||
pub(crate) fn files_to_find(st: &crate::DocState, ids: Option<&[NodeId]>) -> Vec<(LinkInfo, Vec<NodeId>)> {
|
||||
groups(&st.doc, ids)
|
||||
.into_iter()
|
||||
@@ -609,9 +658,13 @@ fn clip_shape((frame, room): Clip) -> PathData {
|
||||
enum ClipTo {
|
||||
/// It stays as it is.
|
||||
Keep,
|
||||
/// It is clipped to this path: the clipping path of the clip group holding just it changes,
|
||||
/// else it goes into a new clip group.
|
||||
/// It is clipped to this path (Placement Options' clip): the clipping path of the clip group
|
||||
/// holding just it changes, else it goes into a new clip group.
|
||||
Path(PathData),
|
||||
/// It is clipped to this path, the clipping path its DCS file draws it through: as [`ClipTo::Path`],
|
||||
/// except that a plain group holding just it (as [`ClipTo::Off`] leaves one) becomes a clip group
|
||||
/// again.
|
||||
File(PathData),
|
||||
/// It goes into a new clip group of this path, inside the clip group that holds it.
|
||||
Nest(PathData),
|
||||
/// The clipping path of the clip group holding just it goes (a DCS file's clipping path that
|
||||
@@ -673,7 +726,7 @@ fn clip_to(
|
||||
match img.clip.as_ref().map(|path| path.transformed(new_xf)) {
|
||||
// A clipping mask made in the document stays, with the file's clip group inside it.
|
||||
Some(path) if held.is_some() && !file_held => ClipTo::Nest(path),
|
||||
Some(path) => ClipTo::Path(path),
|
||||
Some(path) => ClipTo::File(path),
|
||||
None if file_held => ClipTo::Off,
|
||||
None => ClipTo::Keep,
|
||||
}
|
||||
@@ -684,7 +737,7 @@ fn clip_to(
|
||||
type Remake<'a> = dyn FnMut(&Node, Option<(&PathData, FillRule)>) -> (Node, ClipTo) + 'a;
|
||||
|
||||
/// Remakes the linked objects outside the layer tree (in symbols, graph designs, patterns and
|
||||
/// opacity masks, where [`Document::node`] finds no ids) that `pick` holds for.
|
||||
/// opacity masks, where [`Document::node`] does not find them) that `pick` holds for.
|
||||
struct Nested<'a> {
|
||||
pick: &'a dyn Fn(&Node) -> bool,
|
||||
make: &'a mut Remake<'a>,
|
||||
@@ -722,7 +775,7 @@ impl Nested<'_> {
|
||||
let mut new = Arc::new(new);
|
||||
self.update(&mut new, true);
|
||||
*n = match clip {
|
||||
ClipTo::Path(path) | ClipTo::Nest(path) => Arc::new(self.clip_group(new, path)),
|
||||
ClipTo::Path(path) | ClipTo::File(path) | ClipTo::Nest(path) => Arc::new(self.clip_group(new, path)),
|
||||
ClipTo::Keep | ClipTo::Off => new,
|
||||
};
|
||||
}
|
||||
@@ -738,12 +791,16 @@ impl Nested<'_> {
|
||||
let mut slots: Vec<(usize, Arc<Node>)> = vec![];
|
||||
// The object a clip group that loses its clipping path holds alone.
|
||||
let mut declipped = None;
|
||||
// The clipping path and object of a plain group holding just the object, which becomes a
|
||||
// clip group again.
|
||||
let mut reclipped = None;
|
||||
if let Some(children) = n.children() {
|
||||
// A clip group holding just the object: its clipping path changes.
|
||||
let clip_path = match (&n.kind, &children[..]) {
|
||||
(NodeKind::Group { clip: true, .. }, [c, _]) if matches!(c.kind, NodeKind::Path { clipping: true, .. }) => Some(c),
|
||||
_ => None,
|
||||
};
|
||||
let plain = matches!((&n.kind, &children[..]), (NodeKind::Group { clip: false, .. }, [_]));
|
||||
for (i, c) in children.iter().enumerate() {
|
||||
if !(nested && (self.pick)(c)) {
|
||||
let mut new = Arc::clone(c);
|
||||
@@ -762,14 +819,15 @@ impl Nested<'_> {
|
||||
self.update(&mut new, true);
|
||||
match (clip, clip_path) {
|
||||
(ClipTo::Keep, _) => slots.push((i, new)),
|
||||
(ClipTo::Path(clip), Some(path)) if i == 1 => {
|
||||
(ClipTo::Path(clip) | ClipTo::File(clip), Some(path)) if i == 1 => {
|
||||
let mut path = Node::clone(path);
|
||||
if let NodeKind::Path { path: p, .. } = &mut path.kind {
|
||||
*p = clip;
|
||||
}
|
||||
slots.extend([(0, Arc::new(path)), (1, new)]);
|
||||
}
|
||||
(ClipTo::Path(clip) | ClipTo::Nest(clip), _) => {
|
||||
(ClipTo::File(clip), None) if plain => reclipped = Some((clip, new)),
|
||||
(ClipTo::Path(clip) | ClipTo::File(clip) | ClipTo::Nest(clip), _) => {
|
||||
let group = self.clip_group(new, clip);
|
||||
slots.push((i, Arc::new(group)));
|
||||
}
|
||||
@@ -778,13 +836,21 @@ impl Nested<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
if mask.is_none() && slots.is_empty() && declipped.is_none() {
|
||||
if mask.is_none() && slots.is_empty() && declipped.is_none() && reclipped.is_none() {
|
||||
return;
|
||||
}
|
||||
let reclipped = reclipped.map(|(clip, object)| (Arc::new(self.clipping_path(clip)), object));
|
||||
let n = Arc::make_mut(n);
|
||||
if let (Some(art), Some(m)) = (mask, n.extras_if_any().and_then(|e| e.mask.as_mut())) {
|
||||
m.art = art;
|
||||
}
|
||||
// A plain group of just the object that becomes a clip group again.
|
||||
if let Some((path, object)) = reclipped {
|
||||
if let NodeKind::Group { children, clip } = &mut n.kind {
|
||||
(*children, *clip) = (vec![path, object], true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// A clip group that stays as a plain group of just the object.
|
||||
if let Some(object) = declipped {
|
||||
if let NodeKind::Group { children, clip } = &mut n.kind {
|
||||
@@ -803,21 +869,24 @@ impl Nested<'_> {
|
||||
|
||||
/// A clip group of `object` clipped to `clip`, as [`clip_image_to`] makes one in the layers.
|
||||
fn clip_group(&mut self, object: Arc<Node>, clip: PathData) -> Node {
|
||||
let (path_id, group_id) = (NodeId(self.next), NodeId(self.next + 1));
|
||||
self.next += 2;
|
||||
let none = vectorcraft_color::Paint::None;
|
||||
let mut path = Node::path(path_id, clip, Appearance::basic(none.clone(), none, 0.0));
|
||||
if let NodeKind::Path { clipping, .. } = &mut path.kind {
|
||||
*clipping = true;
|
||||
}
|
||||
let path = self.clipping_path(clip);
|
||||
let group_id = NodeId(self.next);
|
||||
self.next += 1;
|
||||
Node::new(group_id, NodeKind::Group { children: vec![Arc::new(path), object], clip: true })
|
||||
}
|
||||
|
||||
/// A clipping path of `clip`, with the next node id.
|
||||
fn clipping_path(&mut self, clip: PathData) -> Node {
|
||||
let id = NodeId(self.next);
|
||||
self.next += 1;
|
||||
clipping_path(id, clip)
|
||||
}
|
||||
}
|
||||
|
||||
/// Placed documents `ids` show `src`, read from the file `link` points at, each placed as its
|
||||
/// Placement Options say (`force`: as that Preserve choice says, whatever they say); with `also`
|
||||
/// (a file's path and the content shown), so do the placed documents outside the layer tree that
|
||||
/// show that content.
|
||||
/// Placed documents `ids` (in the layers or outside them) show `src`, read from the file `link`
|
||||
/// points at, each placed as its Placement Options say (`force`: as that Preserve choice says,
|
||||
/// whatever they say); with `also` (a file's path and the content shown), so do the placed
|
||||
/// documents outside the layer tree that show that content.
|
||||
fn install_document(
|
||||
d: &mut Document,
|
||||
ids: &[NodeId],
|
||||
@@ -832,8 +901,10 @@ fn install_document(
|
||||
let o = PlacementOptions { preserve: force.unwrap_or(p.placement.preserve), ..p.placement };
|
||||
placed_xf(p.xf, (p.width, p.height), (1.0, 1.0), (w, h), (1.0, 1.0), o)
|
||||
};
|
||||
if let Some(also) = also {
|
||||
let pick = |n: &Node| shows(n, also, true);
|
||||
let nested = nested_ids(d, ids);
|
||||
if also.is_some() || !nested.is_empty() {
|
||||
let pick =
|
||||
|n: &Node| matches!(n.kind, NodeKind::PlacedDocument(_)) && (nested.contains(&n.id) || also.is_some_and(|also| shows(n, also, true)));
|
||||
let mut make = |n: &Node, _: Option<(&PathData, FillRule)>| {
|
||||
let mut n = n.clone();
|
||||
let mut clip = ClipTo::Keep;
|
||||
@@ -944,15 +1015,41 @@ fn clip_image_to(d: &mut Document, id: NodeId, path: PathData) -> Result<()> {
|
||||
new_clip_group(d, id, path)
|
||||
}
|
||||
|
||||
/// Clip object `id` of `d` to `path`, the clipping path its DCS file draws it through: the clipping
|
||||
/// path of the clip group holding just it changes, a plain group holding just it (as [`unclip`]
|
||||
/// leaves one) becomes a clip group again, else it goes into a new clip group.
|
||||
fn clip_file_to(d: &mut Document, id: NodeId, path: PathData) -> Result<()> {
|
||||
if set_clip_path(d, id, path.clone()) {
|
||||
return Ok(());
|
||||
}
|
||||
let plain = d.parent_of(id).filter(|g| match d.node(*g).map(|n| &n.kind) {
|
||||
Some(NodeKind::Group { children, clip: false }) => matches!(&children[..], [o] if o.id == id),
|
||||
_ => false,
|
||||
});
|
||||
let Some(g) = plain else { return new_clip_group(d, id, path) };
|
||||
let clip = clipping_path(d.alloc_id(), path);
|
||||
d.insert(Some(g), 0, clip)?;
|
||||
if let Some(Node { kind: NodeKind::Group { clip, .. }, .. }) = d.node_mut(g) {
|
||||
*clip = true;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A clipping path `id` of `path`, unpainted.
|
||||
fn clipping_path(id: NodeId, path: PathData) -> Node {
|
||||
let none = vectorcraft_color::Paint::None;
|
||||
let mut clip = Node::path(id, path, Appearance::basic(none.clone(), none, 0.0));
|
||||
if let NodeKind::Path { clipping, .. } = &mut clip.kind {
|
||||
*clipping = true;
|
||||
}
|
||||
clip
|
||||
}
|
||||
|
||||
/// Put object `id` of `d` into a new clip group of `path`, where it is.
|
||||
fn new_clip_group(d: &mut Document, id: NodeId, path: PathData) -> Result<()> {
|
||||
let (par, index, _) = d.position(id).ok_or(EngineError::NoNode(id))?;
|
||||
let image = d.remove(id)?;
|
||||
let none = vectorcraft_color::Paint::None;
|
||||
let mut clip = Node::path(d.alloc_id(), path, Appearance::basic(none.clone(), none, 0.0));
|
||||
if let NodeKind::Path { clipping, .. } = &mut clip.kind {
|
||||
*clipping = true;
|
||||
}
|
||||
let clip = clipping_path(d.alloc_id(), path);
|
||||
let group = Node::new(d.alloc_id(), NodeKind::Group { children: vec![std::sync::Arc::new(clip), image], clip: true });
|
||||
d.insert(par, index, group)?;
|
||||
Ok(())
|
||||
@@ -971,26 +1068,39 @@ pub(crate) fn set_image_from_path(d: &mut Document, id: NodeId, path: &str, doc_
|
||||
install(d, &[id], read, Some(Preserve::Bounds), None)
|
||||
}
|
||||
|
||||
/// Image objects `ids` show the file read for `link` (`img`), each placed as its Placement
|
||||
/// Options say (`force`: as that Preserve choice says, whatever they say); with `also` (a file's
|
||||
/// path and the content shown), so do the images outside the layer tree that show that content.
|
||||
/// Image objects `ids` (in the layers or outside them) show the file read for `link` (`img`), each
|
||||
/// placed as its Placement Options say (`force`: as that Preserve choice says, whatever they say);
|
||||
/// with `also` (a file's path and the content shown), so do the images outside the layer tree that
|
||||
/// show that content.
|
||||
fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Option<Preserve>, also: Option<(&str, &str)>) -> Result<()> {
|
||||
let new_pt = super::place::pt_per_px(img.ppi);
|
||||
let mut clips = vec![];
|
||||
if let Some(also) = also {
|
||||
// Every image picked shows content `also.1`, so one resolution serves them all.
|
||||
let old_pt = file_pt(d, also.1);
|
||||
let pick = |n: &Node| shows(n, also, false);
|
||||
// The clipping path the old content's DCS file drew it through.
|
||||
let old_clip = d.images.get(also.1).and_then(ImageBlob::separated_clip);
|
||||
let nested = nested_ids(d, ids);
|
||||
if also.is_some() || !nested.is_empty() {
|
||||
let pick = |n: &Node| matches!(n.kind, NodeKind::Image(_)) && (nested.contains(&n.id) || also.is_some_and(|also| shows(n, also, false)));
|
||||
// The resolution of each content the images picked show, and the clipping path its DCS file
|
||||
// drew it through, looked up once each.
|
||||
let mut old: BTreeMap<String, ((f64, f64), Option<PathData>)> = BTreeMap::new();
|
||||
d.visit_stored(|n, _| {
|
||||
if let NodeKind::Image(im) = &n.kind
|
||||
&& pick(n)
|
||||
&& !old.contains_key(&im.key)
|
||||
{
|
||||
old.insert(im.key.clone(), (file_pt(d, &im.key), d.images.get(&im.key).and_then(ImageBlob::separated_clip)));
|
||||
}
|
||||
});
|
||||
let mut make = |n: &Node, held: Option<(&PathData, FillRule)>| {
|
||||
let mut n = n.clone();
|
||||
let mut clip = ClipTo::Keep;
|
||||
if let NodeKind::Image(im) = &mut n.kind {
|
||||
let o = PlacementOptions { preserve: force.unwrap_or(im.placement.preserve), ..im.placement };
|
||||
let size = |w: u32, h: u32| (w as f64, h as f64);
|
||||
let (old_pt, old_clip) = match old.get(&im.key) {
|
||||
Some((pt, clip)) => (*pt, clip.as_ref()),
|
||||
None => (super::place::pt_per_px(None), None),
|
||||
};
|
||||
let (xf, c) = placed_xf(im.xf, size(im.width, im.height), old_pt, size(img.width, img.height), new_pt, o);
|
||||
clip = clip_to(im.xf, old_clip.as_ref(), c, &img, xf, held);
|
||||
clip = clip_to(im.xf, old_clip, c, &img, xf, held);
|
||||
(im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, Some(link.clone()));
|
||||
}
|
||||
(n, clip)
|
||||
@@ -1017,6 +1127,7 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio
|
||||
clips.into_iter().try_for_each(|(id, clip)| match clip {
|
||||
ClipTo::Keep => Ok(()),
|
||||
ClipTo::Path(path) => clip_image_to(d, id, path),
|
||||
ClipTo::File(path) => clip_file_to(d, id, path),
|
||||
ClipTo::Nest(path) => new_clip_group(d, id, path),
|
||||
ClipTo::Off => unclip(d, id),
|
||||
})
|
||||
@@ -1159,6 +1270,9 @@ pub fn resolve(d: &mut Document, base: LinkBase, update: bool, low_res_proxy_eps
|
||||
}
|
||||
(Status::Ok, Some(mut f)) => {
|
||||
let preview = previewing(d, &g.key);
|
||||
// A DCS file is read in full even with the proxy: its plates print and separate on
|
||||
// their own inks.
|
||||
let eps_preview = eps_preview && !is_dcs_file(&mut f);
|
||||
if let Some((blob, hash)) = read_images.get(&f.path).filter(|_| preview && !eps_preview).cloned() {
|
||||
store_image(d, &g.key, blob, true);
|
||||
let link = f.link_hashed(hash, &g.link);
|
||||
@@ -1197,7 +1311,7 @@ pub fn resolve(d: &mut Document, base: LinkBase, update: bool, low_res_proxy_eps
|
||||
}
|
||||
}
|
||||
// The objects in symbols, graph designs, patterns and opacity masks that show the same file and
|
||||
// content, which have no ids here, whatever else their links hold.
|
||||
// content, whatever else their links hold, those whose id an earlier object has included.
|
||||
if !moved.is_empty() {
|
||||
let mut by_path: BTreeMap<String, Vec<(String, bool, LinkInfo)>> = BTreeMap::new();
|
||||
for (path, key, document, new) in moved {
|
||||
@@ -1232,13 +1346,25 @@ fn link_mut(n: &mut Node) -> Option<&mut LinkInfo> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Linked image objects (or placed documents) `ids` link to `link`.
|
||||
/// Linked image objects (or placed documents) `ids`, in the layers or outside them, link to `link`.
|
||||
fn set_links(d: &mut Document, ids: &[NodeId], link: &LinkInfo) {
|
||||
for id in ids {
|
||||
let nested = nested_ids(d, ids);
|
||||
for id in ids.iter().filter(|id| !nested.contains(id)) {
|
||||
if let Some(l) = d.node_mut(*id).and_then(link_mut) {
|
||||
*l = link.clone();
|
||||
}
|
||||
}
|
||||
if !nested.is_empty() {
|
||||
let pick = |n: &Node| nested.contains(&n.id) && linked(n).is_some();
|
||||
let mut make = |n: &Node, _: Option<(&PathData, FillRule)>| {
|
||||
let mut out = n.clone();
|
||||
if let Some(l) = link_mut(&mut out) {
|
||||
*l = link.clone();
|
||||
}
|
||||
(out, ClipTo::Keep)
|
||||
};
|
||||
Nested { pick: &pick, make: &mut make, next: 0 }.run(d);
|
||||
}
|
||||
}
|
||||
|
||||
/// Placed documents of the document saved at `path` (document `saved` of `s`) in the other open
|
||||
@@ -1261,14 +1387,17 @@ pub(crate) fn refresh_placed(s: &mut Session, saved: u64, path: &str) {
|
||||
if targets.is_empty() {
|
||||
return;
|
||||
}
|
||||
// Each document is updated as the active one, without switching tools.
|
||||
// Each document is updated as the active one, through its own profiles, without switching
|
||||
// tools.
|
||||
let back = s.active;
|
||||
for i in targets {
|
||||
s.active = Some(i);
|
||||
s.sync_front_profiles();
|
||||
// A file that can't be read leaves what its objects show: links.check reports it.
|
||||
let _ = update_where(s, None, Some(&path));
|
||||
}
|
||||
s.active = back;
|
||||
s.sync_front_profiles();
|
||||
}
|
||||
|
||||
// ---------- relative paths ----------
|
||||
@@ -1467,7 +1596,7 @@ fn update(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// Update Links in the active document of `s` for objects `ids` (default: the linked files that
|
||||
/// changed or show their preview), or with `path`, for the placed documents of the file at `path`
|
||||
/// whatever their status. The objects in symbols, graph designs, patterns and opacity masks that
|
||||
/// show the same content are read again too, and have no ids to report.
|
||||
/// show the same content are read again too.
|
||||
fn update_where(s: &mut Session, ids: Option<Vec<NodeId>>, path: Option<&str>) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let (mut reads, mut missing) = (vec![], vec![]);
|
||||
@@ -1533,7 +1662,7 @@ enum Scope {
|
||||
Each,
|
||||
/// The objects given or selected.
|
||||
Selected,
|
||||
/// Every object in the layers linked to the same file as one given or selected.
|
||||
/// Every stored object linked to the same file as one given or selected.
|
||||
All,
|
||||
/// The objects given or selected, then every other missing link whose file name is in the new
|
||||
/// file's folder.
|
||||
@@ -1617,7 +1746,7 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
// An image or a placed document, with its link.
|
||||
let image = |id: &NodeId| {
|
||||
st.doc.node(*id).and_then(|n| match &n.kind {
|
||||
stored(&st.doc, *id).and_then(|n| match &n.kind {
|
||||
NodeKind::Image(im) => Some(im.link.as_ref()),
|
||||
NodeKind::PlacedDocument(p) => Some(Some(&p.link)),
|
||||
_ => None,
|
||||
@@ -1642,22 +1771,23 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if ids.is_empty() {
|
||||
return Err(bad(C, "select the images to relink, or pass ids"));
|
||||
}
|
||||
// All Instances: the other objects in the layers linked to the same files.
|
||||
// All Instances: the other stored objects linked to the same files, each once.
|
||||
if scope == Scope::All {
|
||||
let paths: BTreeSet<&str> = ids.iter().filter_map(|id| image(id).flatten()).map(|l| l.path.as_str()).collect();
|
||||
let given: BTreeSet<NodeId> = ids.iter().copied().collect();
|
||||
let mut given: BTreeSet<NodeId> = ids.iter().copied().collect();
|
||||
let mut more = vec![];
|
||||
st.doc.walk(|n| {
|
||||
st.doc.visit_stored(|n, _| {
|
||||
if let Some((l, _, _)) = linked(n)
|
||||
&& paths.contains(l.path.as_str())
|
||||
&& !given.contains(&n.id)
|
||||
&& n.id.0 != 0
|
||||
&& given.insert(n.id)
|
||||
{
|
||||
more.push(n.id);
|
||||
}
|
||||
});
|
||||
ids.extend(more);
|
||||
}
|
||||
if copy_to.is_some() && ids.iter().any(|id| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::PlacedDocument(_)))) {
|
||||
if copy_to.is_some() && ids.iter().any(|id| matches!(stored(&st.doc, *id).map(|n| &n.kind), Some(NodeKind::PlacedDocument(_)))) {
|
||||
return Err(bad(C, "copy takes images only: relink placed documents where their files are"));
|
||||
}
|
||||
// (ids, the file) per file to read.
|
||||
@@ -1693,7 +1823,7 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut images = vec![];
|
||||
let mut documents: Vec<((u32, bool, PageBox), Vec<NodeId>)> = vec![];
|
||||
for id in ids {
|
||||
match st.doc.node(id).map(|n| &n.kind) {
|
||||
match stored(&st.doc, id).map(|n| &n.kind) {
|
||||
Some(NodeKind::PlacedDocument(pl)) => {
|
||||
let k = (pl.page(), pl.bounding, pl.page_box);
|
||||
match documents.iter_mut().find(|(e, _)| *e == k) {
|
||||
@@ -1843,9 +1973,9 @@ fn copy_into_folder(_: &str, _: &[u8], _: &Path) -> Result<(String, bool)> {
|
||||
|
||||
// ---------- the Links panel ----------
|
||||
|
||||
/// Image object `id` of `d`.
|
||||
/// Image object `id` of `d`, wherever it is stored.
|
||||
fn image_of(d: &Document, id: NodeId) -> Option<&ImageObject> {
|
||||
match &d.node(id)?.kind {
|
||||
match &stored(d, id)?.kind {
|
||||
NodeKind::Image(im) => Some(im),
|
||||
_ => None,
|
||||
}
|
||||
@@ -1863,7 +1993,7 @@ fn image_param(st: &crate::DocState, p: &Value, cmd: &str) -> Result<NodeId> {
|
||||
.ok_or_else(|| bad(cmd, "select an image, or pass id"))?;
|
||||
match image_of(&st.doc, id) {
|
||||
Some(_) => Ok(id),
|
||||
None if st.doc.node(id).is_none() => Err(crate::EngineError::NoNode(id)),
|
||||
None if stored(&st.doc, id).is_none() => Err(crate::EngineError::NoNode(id)),
|
||||
None => Err(bad(cmd, format!("object {} is not an image", id.0))),
|
||||
}
|
||||
}
|
||||
@@ -1877,9 +2007,9 @@ fn placement_mut(n: &mut Node) -> Option<&mut PlacementOptions> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Placement Options of image or placed document `id` of `d`.
|
||||
/// The Placement Options of image or placed document `id` of `d`, wherever it is stored.
|
||||
fn placement_of(d: &Document, id: NodeId) -> Option<PlacementOptions> {
|
||||
match &d.node(id)?.kind {
|
||||
match &stored(d, id)?.kind {
|
||||
NodeKind::Image(im) => Some(im.placement),
|
||||
NodeKind::PlacedDocument(p) => Some(p.placement),
|
||||
_ => None,
|
||||
@@ -1892,12 +2022,12 @@ fn linked_param(st: &crate::DocState, p: &Value, cmd: &str) -> Result<NodeId> {
|
||||
let id = object_param(p, "id", cmd)?.or_else(first).ok_or_else(|| bad(cmd, "select an image, or pass id"))?;
|
||||
match placement_of(&st.doc, id) {
|
||||
Some(_) => Ok(id),
|
||||
None if st.doc.node(id).is_none() => Err(crate::EngineError::NoNode(id)),
|
||||
None if stored(&st.doc, id).is_none() => Err(crate::EngineError::NoNode(id)),
|
||||
None => Err(bad(cmd, format!("object {} is not an image or a linked file", id.0))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Per linked image in the layers of `st`: its file's status, where it was found when away from
|
||||
/// Per linked image or placed document of `st`, wherever it is stored: its file's status, where it was found when away from
|
||||
/// its path, and whether the image shows its preview (each file probed once).
|
||||
pub(crate) fn statuses(st: &crate::DocState) -> BTreeMap<NodeId, (Status, Option<String>, bool)> {
|
||||
let mut out = BTreeMap::new();
|
||||
@@ -1939,15 +2069,21 @@ fn status_rank(status: &str) -> usize {
|
||||
/// holds them) or overlap an object that is, as Show DCS Transparency Interactions marks them.
|
||||
fn dcs_transparency(d: &Document) -> BTreeSet<NodeId> {
|
||||
/// Each visible DCS image's id, bounds and whether it is transparent, and the bounds of each
|
||||
/// other visible object with its own transparency.
|
||||
fn walk(d: &Document, n: &Node, held: bool, images: &mut Vec<(NodeId, Rect, bool)>, see_through: &mut Vec<Rect>) {
|
||||
/// other visible object with its own transparency; bounds are cut to `clip`, the bounds of the
|
||||
/// clipping paths of the clip groups and layers holding the object.
|
||||
fn walk(d: &Document, n: &Node, held: bool, clip: Option<Rect>, images: &mut Vec<(NodeId, Rect, bool)>, see_through: &mut Vec<Rect>) {
|
||||
if !n.visible {
|
||||
return;
|
||||
}
|
||||
let own = n.shows_own_transparency();
|
||||
// The part of the object that shows through `clip`; none when it is clipped away.
|
||||
let shown = n.geometric_bounds().and_then(|b| match clip {
|
||||
Some(c) => Some(c.intersect(b)).filter(|i| i.area() > 0.0),
|
||||
None => Some(b),
|
||||
});
|
||||
match &n.kind {
|
||||
NodeKind::Image(im) if d.images.get(&im.key).is_some_and(ImageBlob::is_separated) => {
|
||||
if let Some(b) = n.geometric_bounds() {
|
||||
if let Some(b) = shown {
|
||||
images.push((n.id, b, held || own));
|
||||
// A transparent DCS image is an object with its own transparency for the
|
||||
// others it overlaps.
|
||||
@@ -1956,16 +2092,25 @@ fn dcs_transparency(d: &Document) -> BTreeSet<NodeId> {
|
||||
}
|
||||
}
|
||||
}
|
||||
_ if own => see_through.extend(n.geometric_bounds()),
|
||||
_ if own => see_through.extend(shown),
|
||||
_ => {}
|
||||
}
|
||||
for c in n.children().into_iter().flatten() {
|
||||
walk(d, c, held || own, images, see_through);
|
||||
let Some(children) = n.children() else { return };
|
||||
// A clip group's or clipping layer's first child clips the others.
|
||||
let clip = match &n.kind {
|
||||
NodeKind::Group { clip: true, .. } | NodeKind::Layer { clip: true, .. } => match children.first().and_then(|c| c.geometric_bounds()) {
|
||||
Some(c) => Some(clip.map_or(c, |o| o.intersect(c))),
|
||||
None => clip,
|
||||
},
|
||||
_ => clip,
|
||||
};
|
||||
for c in children {
|
||||
walk(d, c, held || own, clip, images, see_through);
|
||||
}
|
||||
}
|
||||
let (mut images, mut see_through) = (vec![], vec![]);
|
||||
for l in &d.layers {
|
||||
walk(d, l, false, &mut images, &mut see_through);
|
||||
walk(d, l, false, None, &mut images, &mut see_through);
|
||||
}
|
||||
images
|
||||
.into_iter()
|
||||
@@ -1983,17 +2128,20 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let interactions = if switch_or(p, "dcsTransparency", false, C)? { dcs_transparency(&st.doc) } else { BTreeSet::new() };
|
||||
let statuses = statuses(st);
|
||||
let mut objects = vec![];
|
||||
st.doc.walk(|n| {
|
||||
if matches!(n.kind, NodeKind::Image(_) | NodeKind::PlacedDocument(_)) {
|
||||
objects.push(n);
|
||||
// The layer tree's objects, top first as the Layers panel lists them, then the others in the
|
||||
// order they are stored (opacity-mask art, symbols, graph designs, patterns), each once.
|
||||
let (mut objects, mut nested) = (vec![], vec![]);
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
st.doc.visit_stored(|n, place| {
|
||||
if matches!(n.kind, NodeKind::Image(_) | NodeKind::PlacedDocument(_)) && n.id.0 != 0 && seen.insert(n.id) {
|
||||
if place.in_layers() { objects.push((n, place)) } else { nested.push((n, place)) }
|
||||
}
|
||||
});
|
||||
// Top first, as the Layers panel lists them.
|
||||
objects.reverse();
|
||||
objects.extend(nested);
|
||||
let mut counts: BTreeMap<&str, usize> = BTreeMap::new();
|
||||
let mut rows = vec![];
|
||||
for n in objects {
|
||||
for (n, place) in objects {
|
||||
let (status, found, preview) = match statuses.get(&n.id) {
|
||||
Some((s, f, p)) => (s.as_str(), f.as_deref(), *p),
|
||||
None => ("embedded", None, false),
|
||||
@@ -2036,6 +2184,9 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if preview {
|
||||
row["preview"] = json!(true);
|
||||
}
|
||||
if let Some(owner) = owner_json(&st.doc, place) {
|
||||
row["owner"] = owner;
|
||||
}
|
||||
if interactions.contains(&n.id) {
|
||||
row["dcsTransparency"] = json!(true);
|
||||
}
|
||||
@@ -2056,15 +2207,21 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn go_to(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let id = linked_param(st, p, "links.goTo")?;
|
||||
// An object in mask art or a definition has no place of its own on the canvas: the selection
|
||||
// is cleared, and the reply names what holds it.
|
||||
if let Some(owner) = st.doc.stored_node(id).and_then(|(_, place)| owner_json(&st.doc, place)) {
|
||||
s.select(|_, sel| sel.set([]))?;
|
||||
return Ok(json!({ "id": id.0, "onCanvas": false, "owner": owner }));
|
||||
}
|
||||
let b = st.doc.node(id).and_then(Node::geometric_bounds).unwrap_or_default();
|
||||
s.select(|_, sel| sel.set([id]))?;
|
||||
Ok(json!({ "id": id.0, "bounds": [b.x0, b.y0, b.x1, b.y1] }))
|
||||
Ok(json!({ "id": id.0, "bounds": [b.x0, b.y0, b.x1, b.y1], "onCanvas": true }))
|
||||
}
|
||||
|
||||
fn embed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "links.embed";
|
||||
let st = s.doc()?;
|
||||
let kind = |id: &NodeId| st.doc.node(*id).map(|n| &n.kind);
|
||||
let kind = |id: &NodeId| stored(&st.doc, *id).map(|n| &n.kind);
|
||||
let linked = |id: &NodeId| match kind(id) {
|
||||
Some(NodeKind::Image(im)) => im.link.is_some(),
|
||||
Some(NodeKind::PlacedDocument(_)) => true,
|
||||
@@ -2122,7 +2279,7 @@ fn embed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
install(d, &ids, read, Some(Preserve::Bounds), None)?;
|
||||
}
|
||||
for id in &done {
|
||||
if let Some(Node { kind: NodeKind::Image(im), .. }) = d.node_mut(*id) {
|
||||
if let Some(Node { kind: NodeKind::Image(im), .. }) = d.stored_node_mut(*id) {
|
||||
im.link = None;
|
||||
}
|
||||
}
|
||||
@@ -2150,7 +2307,7 @@ fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "links.unembed";
|
||||
let st = s.doc()?;
|
||||
let id = image_param(st, p, C)?;
|
||||
let n = st.doc.node(id).ok_or(crate::EngineError::NoNode(id))?;
|
||||
let n = stored(&st.doc, id).ok_or(crate::EngineError::NoNode(id))?;
|
||||
let im = image_of(&st.doc, id).ok_or_else(|| bad(C, format!("object {} is not an image", id.0)))?;
|
||||
if im.link.is_some() {
|
||||
return Err(bad(C, format!("image {} is linked already", id.0)));
|
||||
@@ -2236,7 +2393,7 @@ fn scale_rotation(xf: Affine, (px, py): (f64, f64)) -> (Value, Value) {
|
||||
|
||||
/// Link Info of placed document `id`.
|
||||
fn placed_info(st: &crate::DocState, id: NodeId) -> Result<Value> {
|
||||
let n = st.doc.node(id).ok_or(crate::EngineError::NoNode(id))?;
|
||||
let n = stored(&st.doc, id).ok_or(crate::EngineError::NoNode(id))?;
|
||||
let NodeKind::PlacedDocument(pl) = &n.kind else { return Err(bad("links.info", format!("object {} is not a placed document", id.0))) };
|
||||
let size = n.geometric_bounds().unwrap_or_default();
|
||||
let (scale, rotation) = scale_rotation(pl.xf, (1.0, 1.0));
|
||||
@@ -2316,7 +2473,7 @@ fn placement_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
s.edit("Placement Options", |d, _| {
|
||||
for id in &ids {
|
||||
if let Some(o) = d.node_mut(*id).and_then(placement_mut) {
|
||||
if let Some(o) = d.stored_node_mut(*id).and_then(placement_mut) {
|
||||
set(o);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -172,7 +172,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Make with Top Object",
|
||||
["Object", "Envelope Distort"],
|
||||
Some("Cmd+Alt+C"),
|
||||
"{ids?} the topmost selected path becomes the envelope of the others: its outline splits into four sides at its corners, and each piece of a side takes a share of the content in proportion to its control polygon's length (type maps from its glyph outline bounds) → {id}",
|
||||
"{ids?} the topmost selected path becomes the envelope of the others: its outline splits into four sides at its corners, and each piece of a side takes a share of the content in proportion to its control polygon's length, and a side whose pieces are all one curve split at anchors follows that curve's parameter (type maps from its glyph outline bounds) → {id}",
|
||||
has_multi,
|
||||
env_make_top
|
||||
),
|
||||
@@ -244,7 +244,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Envelope Mesh Point",
|
||||
[],
|
||||
None,
|
||||
"{id, index, x, y, handle?: 0 right|1 left|2 down|3 up} move a point of a mesh envelope (its handles follow), or with `handle` place that handle end at (x, y); object.mesh.movePoint, addLine and deletePoint edit mesh envelopes too",
|
||||
"{id, index, x, y, handle?: 0 right|1 left|2 down|3 up} move a point of a mesh or warp envelope (its handles follow), or with `handle` place that handle end at (x, y); a warp's points are those of its grid (4×4 patches, or 8×8 or 16×16 where 4×4 draws more than 0.1% of its diagonal away from the warp), and its first edit makes it a mesh envelope on that grid in the same undo step (a warp no such grid follows is refused: Reset with Mesh first); object.mesh.movePoint, movePoints, addLine and deletePoint edit mesh and warp envelopes too",
|
||||
has_doc,
|
||||
env_set_mesh_point
|
||||
),
|
||||
@@ -263,7 +263,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Set Mesh Point Color",
|
||||
[],
|
||||
None,
|
||||
"{id, index | points: [index…] | items: [{id, index | points}…], color? (#rrggbbaa and #rgba are refused), 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)",
|
||||
"{id, index | points: [index…] | items: [{id, index | points}…], color? (#rrggbbaa and #rgba are refused), 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, and so does a call that changes no point, with no undo step)",
|
||||
has_doc,
|
||||
mesh_set_color
|
||||
),
|
||||
@@ -272,7 +272,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Mesh Point",
|
||||
[],
|
||||
None,
|
||||
"{id, index, x, y, handle?: 0 right|1 left|2 down|3 up} move a point of a gradient mesh or mesh envelope (its handles follow), or with `handle` place that handle end at (x, y)",
|
||||
"{id, index, x, y, handle?: 0 right|1 left|2 down|3 up} move a point of a gradient mesh or a mesh or warp envelope (its handles follow; a warp becomes a mesh envelope, see object.envelope.setMeshPoint), or with `handle` place that handle end at (x, y)",
|
||||
has_doc,
|
||||
mesh_move_point
|
||||
),
|
||||
@@ -281,7 +281,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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)",
|
||||
"{id, points: [index…] | items: [{id, index | points}…], dx, dy} move points of gradient meshes or mesh or warp envelopes by (dx, dy), their handles with them (warps become mesh envelopes, see object.envelope.setMeshPoint; one undo step; an index out of range changes nothing, and so does a call that moves no point, with no undo step)",
|
||||
has_doc,
|
||||
mesh_move_points
|
||||
),
|
||||
@@ -290,7 +290,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add Mesh Line",
|
||||
[],
|
||||
None,
|
||||
"{id, x, y, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), tolerance?: pt (0)} add a row and a column through (x, y), inside or on the edge, to a gradient mesh (new point in `color`) or a mesh envelope; a point outside within `tolerance` of the edge adds them through the nearest point of the edge; at a point that is already a mesh point it adds no line, and records no undo step unless `color` changes a gradient mesh's point (a mesh envelope's points have no color) → {index}",
|
||||
"{id, x, y, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), tolerance?: pt (0)} add a row and a column through (x, y), inside or on the edge, to a gradient mesh (new point in `color`) or a mesh or warp envelope (a warp becomes a mesh envelope, see object.envelope.setMeshPoint); a point outside within `tolerance` of the edge adds them through the nearest point of the edge; at a point that is already a mesh point it adds no line, and records no undo step unless `color` changes a gradient mesh's point (an envelope's points have no color) → {index}",
|
||||
has_doc,
|
||||
mesh_add_line
|
||||
),
|
||||
@@ -299,7 +299,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Delete Mesh Point",
|
||||
[],
|
||||
None,
|
||||
"{id, index} delete the mesh lines through a point of a gradient mesh or mesh envelope",
|
||||
"{id, index} delete the mesh lines through a point of a gradient mesh or a mesh or warp envelope (a warp becomes a mesh envelope, see object.envelope.setMeshPoint)",
|
||||
has_doc,
|
||||
mesh_delete_point
|
||||
),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::super::object::choice;
|
||||
use super::common::{fix_ids, ids_json, is_envelope, roots_param, selected_of, wrap};
|
||||
use super::mesh::{handle_param, index_param, whole};
|
||||
use super::mesh::{envelope_edit_grid, handle_param, index_param, mesh_envelope, warp_point_stays, whole};
|
||||
use super::{
|
||||
Affine, Appearance, Arc, Beside, Color, Document, EngineError, EnvelopeKind, EnvelopeMap, EnvelopeOptions, Node, NodeId, NodeKind, Paint,
|
||||
PathData, Point, PreserveShape, Result, Session, Value, bad, check_numbers, f64_or, f64_req, json, live, object_param, ok, switch_or, text_param,
|
||||
@@ -79,8 +79,7 @@ fn mesh_kind(map: &EnvelopeMap, maintain: bool, rows: u32, cols: u32) -> Envelop
|
||||
return EnvelopeKind::Mesh { rows, cols, points: map.grid(rows, cols), handles: vec![] };
|
||||
}
|
||||
// The surface's points with handles along it: the grid lines keep the current shape.
|
||||
let m = map.surface_mesh(rows, cols, Color::BLACK);
|
||||
EnvelopeKind::Mesh { rows, cols, points: m.points.iter().map(|q| q.p).collect(), handles: m.points.iter().map(|q| q.handles).collect() }
|
||||
mesh_envelope(&map.surface_mesh(rows, cols, Color::BLACK))
|
||||
}
|
||||
|
||||
pub(super) fn env_make_mesh(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -428,7 +427,20 @@ pub(super) fn env_set_mesh_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let index = index_param(p, "index", C)?;
|
||||
let q = Point::new(f64_req(p, "x", C)?, f64_req(p, "y", C)?);
|
||||
let handle = handle_param(p, C)?;
|
||||
// A warp whose point or handle stays where it is stays a warp.
|
||||
if warp_point_stays(&s.doc()?.doc, id, index, handle, q, C)? {
|
||||
return ok();
|
||||
}
|
||||
s.edit("Move Envelope Point", |d, _| {
|
||||
// A warp's first edited point makes it a mesh envelope on its grid, in the same step.
|
||||
if let Some(n) = d.node(id)
|
||||
&& matches!(&n.kind, NodeKind::Envelope { kind, .. } if matches!(**kind, EnvelopeKind::Warp { .. }))
|
||||
{
|
||||
let grid = envelope_edit_grid(n, C).ok_or_else(|| bad(C, "not a mesh envelope point"))??;
|
||||
if let Some(NodeKind::Envelope { kind, .. }) = d.node_mut(id).map(|n| &mut n.kind) {
|
||||
**kind = mesh_envelope(&grid);
|
||||
}
|
||||
}
|
||||
let Some(NodeKind::Envelope { kind, .. }) = d.node_mut(id).map(|n| &mut n.kind) else {
|
||||
return Err(bad(C, "not a mesh envelope point"));
|
||||
};
|
||||
|
||||
@@ -119,31 +119,90 @@ fn with_mesh<T>(s: &mut Session, p: &Value, cmd: &str, label: &str, envelopes: b
|
||||
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> {
|
||||
edit_kind(&mut d.node_mut(id).ok_or(EngineError::NoNode(id))?.kind, cmd, envelopes, f)
|
||||
/// The grid an edit of envelope `n`'s points starts from: a mesh envelope's own grid, or a warp's
|
||||
/// grid ([`live::warp_grid`]), which the edit turns into a mesh envelope. `None` for other nodes.
|
||||
pub(super) fn envelope_edit_grid(n: &Node, cmd: &str) -> Option<Result<GradientMesh>> {
|
||||
let NodeKind::Envelope { kind, .. } = &n.kind else { return None };
|
||||
match &**kind {
|
||||
EnvelopeKind::Mesh { rows, cols, points, handles } => {
|
||||
Some(live::envelope_grid(*rows, *cols, points, handles).ok_or_else(|| bad(cmd, "the envelope's mesh is malformed")))
|
||||
}
|
||||
EnvelopeKind::Warp { .. } => {
|
||||
Some(live::warp_grid(n).ok_or_else(|| bad(cmd, "this warp's points can't be edited: use Reset with Mesh first")))
|
||||
}
|
||||
EnvelopeKind::TopObject { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// [`edit_grid`] on a node's kind.
|
||||
fn edit_kind<T>(k: &mut NodeKind, cmd: &str, envelopes: bool, f: impl FnOnce(&mut GradientMesh) -> Result<T>) -> Result<T> {
|
||||
match k {
|
||||
NodeKind::Mesh(m) => f(m),
|
||||
NodeKind::Envelope { kind, .. } if envelopes && matches!(**kind, EnvelopeKind::Mesh { .. }) => {
|
||||
let EnvelopeKind::Mesh { rows, cols, points, handles } = &mut **kind else {
|
||||
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(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)
|
||||
}
|
||||
_ => Err(bad(cmd, if envelopes { "not a gradient mesh or mesh envelope" } else { "not a gradient mesh" })),
|
||||
/// The mesh envelope kind of grid `m`, with its points' handles.
|
||||
pub(super) fn mesh_envelope(m: &GradientMesh) -> EnvelopeKind {
|
||||
EnvelopeKind::Mesh {
|
||||
rows: m.rows,
|
||||
cols: m.cols,
|
||||
points: m.points.iter().map(|q| q.p).collect(),
|
||||
handles: m.points.iter().map(|q| q.handles).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Does placing point `index` of warp envelope `id` of `d`, or that point's `handle` end, at `q`
|
||||
/// leave it where it is? Such a placement is no edit. `false` for other objects and for an index
|
||||
/// out of range, whose edits run as before.
|
||||
pub(super) fn warp_point_stays(d: &Document, id: NodeId, index: usize, handle: Option<usize>, q: Point, cmd: &str) -> Result<bool> {
|
||||
let Some(n) = d.node(id).filter(|n| matches!(&n.kind, NodeKind::Envelope { kind, .. } if matches!(**kind, EnvelopeKind::Warp { .. }))) else {
|
||||
return Ok(false);
|
||||
};
|
||||
let grid = envelope_grid_to_edit(n, cmd, true)?;
|
||||
Ok(grid.points.get(index).is_some_and(|pt| match handle {
|
||||
// The caller sends a handle's end as point plus handle; `q - p` can round away from it.
|
||||
Some(h) => pt.handles.get(h).is_some_and(|v| pt.p + *v == q),
|
||||
None => pt.p == q,
|
||||
}))
|
||||
}
|
||||
|
||||
/// The grid of envelope `n` that [`edit_grid`] edits (only `envelopes`), or the error it fails with.
|
||||
fn envelope_grid_to_edit(n: &Node, cmd: &str, envelopes: bool) -> Result<GradientMesh> {
|
||||
match envelope_edit_grid(n, cmd).filter(|_| envelopes) {
|
||||
Some(grid) => grid,
|
||||
None => Err(bad(cmd, if envelopes { "not a gradient mesh or mesh envelope" } else { "not a gradient mesh" })),
|
||||
}
|
||||
}
|
||||
|
||||
/// The grid of mesh `id` of `d` that [`edit_grid`] edits, as it is now.
|
||||
fn grid_to_edit(d: &Document, id: NodeId, cmd: &str, envelopes: bool) -> Result<GradientMesh> {
|
||||
match d.node(id) {
|
||||
Some(Node { kind: NodeKind::Mesh(m), .. }) => Ok(m.clone()),
|
||||
Some(n) => envelope_grid_to_edit(n, cmd, envelopes),
|
||||
None => Err(EngineError::NoNode(id)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Run `f` on the gradient mesh `id` of `d`; with `envelopes`, a warp or mesh envelope's grid too
|
||||
/// (see [`edit_node`]).
|
||||
fn edit_grid<T>(d: &mut Document, id: NodeId, cmd: &str, envelopes: bool, f: impl FnOnce(&mut GradientMesh) -> Result<T>) -> Result<T> {
|
||||
edit_node(d.node_mut(id).ok_or(EngineError::NoNode(id))?, cmd, envelopes, f)
|
||||
}
|
||||
|
||||
/// [`edit_grid`] on a node: with `envelopes`, a warp or mesh envelope's grid
|
||||
/// ([`envelope_edit_grid`]) is edited too, and its points and handles are written back as a mesh
|
||||
/// envelope (editing fills in the handles, and makes a warp a mesh envelope).
|
||||
fn edit_node<T>(n: &mut Node, cmd: &str, envelopes: bool, f: impl FnOnce(&mut GradientMesh) -> Result<T>) -> Result<T> {
|
||||
if let NodeKind::Mesh(m) = &mut n.kind {
|
||||
return f(m);
|
||||
}
|
||||
let start = envelope_grid_to_edit(n, cmd, envelopes)?;
|
||||
let mut m = start.clone();
|
||||
let r = f(&mut m)?;
|
||||
// A warp stays a warp when the edit changed nothing.
|
||||
let warp = matches!(&n.kind, NodeKind::Envelope { kind, .. } if matches!(**kind, EnvelopeKind::Warp { .. }));
|
||||
if warp && m == start {
|
||||
return Ok(r);
|
||||
}
|
||||
if let NodeKind::Envelope { kind, .. } = &mut n.kind {
|
||||
**kind = mesh_envelope(&m);
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// Most mesh points one command names, over all its meshes.
|
||||
const MAX_POINTS: usize = 1 << 20;
|
||||
|
||||
@@ -178,7 +237,8 @@ fn point_items(p: &Value, cmd: &str) -> Result<Vec<(NodeId, BTreeSet<usize>)>> {
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// fails it, changing nothing); with `envelopes`, on warp and mesh envelopes' points too. When `f`
|
||||
/// changes no point, nothing changes and no undo step is recorded.
|
||||
fn with_points(
|
||||
s: &mut Session,
|
||||
items: &[(NodeId, BTreeSet<usize>)],
|
||||
@@ -187,6 +247,20 @@ fn with_points(
|
||||
envelopes: bool,
|
||||
mut f: impl FnMut(&mut live::MeshPoint) -> Result<()>,
|
||||
) -> Result<()> {
|
||||
let doc = &s.doc()?.doc;
|
||||
let mut changes = false;
|
||||
for (id, points) in items {
|
||||
let mut m = grid_to_edit(doc, *id, cmd, envelopes)?;
|
||||
for i in points {
|
||||
let q = m.points.get_mut(*i).ok_or_else(|| bad(cmd, "index out of range"))?;
|
||||
let before = q.clone();
|
||||
f(q)?;
|
||||
changes |= *q != before;
|
||||
}
|
||||
}
|
||||
if !changes {
|
||||
return Ok(());
|
||||
}
|
||||
s.edit(label, |d, _| {
|
||||
for (id, points) in items {
|
||||
edit_grid(d, *id, cmd, envelopes, |m| {
|
||||
@@ -255,6 +329,10 @@ pub(super) fn mesh_move_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let index = index_param(p, "index", C)?;
|
||||
let q = Point::new(f64_req(p, "x", C)?, f64_req(p, "y", C)?);
|
||||
let handle = handle_param(p, C)?;
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?;
|
||||
if warp_point_stays(&s.doc()?.doc, id, index, handle, q, C)? {
|
||||
return ok();
|
||||
}
|
||||
with_mesh(s, p, C, "Move Mesh Point", true, |m| {
|
||||
let pt = m.points.get_mut(index).ok_or_else(|| bad(C, "index out of range"))?;
|
||||
match handle {
|
||||
@@ -298,12 +376,12 @@ pub(super) fn mesh_add_line(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// The lines are added to a copy of the object. A point that is already a mesh point adds none:
|
||||
// when its color stays too, nothing changes and no undo step is recorded. The grid is compared,
|
||||
// not the node: a mesh envelope stored without handles takes them in any edit, and keeps no
|
||||
// colors, so only its points and handles count.
|
||||
let orig = s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?.kind.clone();
|
||||
let colored = matches!(orig, NodeKind::Mesh(_));
|
||||
let mut kind = orig.clone();
|
||||
let (i, same) = edit_kind(&mut kind, C, true, |m| {
|
||||
// not the node: a mesh envelope stored without handles takes them in any edit, a warp becomes
|
||||
// a mesh envelope, and neither keeps colors, so only their points and handles count.
|
||||
let orig = s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?.clone();
|
||||
let colored = matches!(orig.kind, NodeKind::Mesh(_));
|
||||
let mut node = orig.clone();
|
||||
let (i, same) = edit_node(&mut node, C, true, |m| {
|
||||
let before = m.clone();
|
||||
let i = add(m)?;
|
||||
let shape = |g: &GradientMesh| (g.rows, g.cols, g.points.iter().map(|q| (q.p, q.handles)).collect::<Vec<_>>());
|
||||
@@ -315,10 +393,10 @@ pub(super) fn mesh_add_line(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let index = s.edit("Add Mesh Line", move |d, _| {
|
||||
let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?;
|
||||
// Settling typed values before the edit may have changed the object: add the lines again.
|
||||
if n.kind != orig {
|
||||
return edit_kind(&mut n.kind, C, true, add);
|
||||
if n.kind != orig.kind {
|
||||
return edit_node(n, C, true, add);
|
||||
}
|
||||
n.kind = kind;
|
||||
n.kind = node.kind;
|
||||
Ok(i)
|
||||
})?;
|
||||
Ok(json!({ "index": index }))
|
||||
|
||||
@@ -169,28 +169,47 @@ pub(super) fn lock(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
/// The selected objects ([`selected_roots`]) that Lock › Selection and Hide › Selection change: in
|
||||
/// isolation mode, only those inside the isolated object, where a path of the isolated compound
|
||||
/// path is an object of its own.
|
||||
/// The selected objects ([`selected_roots`]) and ruler guides that Lock › Selection and Hide ›
|
||||
/// Selection change: in isolation mode, only the objects inside the isolated object, where a path
|
||||
/// of the isolated compound path is an object of its own. A guide counts while it can be edited
|
||||
/// (it and its layer shown and unlocked, and Lock Guides off).
|
||||
fn selected_lock_hide_roots(s: &Session) -> Result<Vec<NodeId>> {
|
||||
match crate::cmd::ordinary_isolation(s.doc()?) {
|
||||
let st = s.doc()?;
|
||||
match crate::cmd::ordinary_isolation(st) {
|
||||
Some(root) => crate::cmd::edit::selected_roots_inside(s, root, false),
|
||||
None => selected_roots(s),
|
||||
None => {
|
||||
let mut ids = selected_roots(s)?;
|
||||
if !s.guides_locked() {
|
||||
let d = &st.doc;
|
||||
ids.extend(st.selection.guides.iter().copied().filter(|id| d.ruler_guide(*id).is_some_and(|g| d.guide_editable(&g))));
|
||||
}
|
||||
Ok(ids)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The objects and ruler guides in `d` that `f` picks (layers never).
|
||||
fn collect_flag(d: &Document, f: impl Fn(&Node) -> bool) -> Vec<NodeId> {
|
||||
let mut v = vec![];
|
||||
d.walk(|n| {
|
||||
if !n.is_layer() && !n.is_ruler_guide() && f(n) {
|
||||
if !n.is_layer() && f(n) {
|
||||
v.push(n.id)
|
||||
}
|
||||
});
|
||||
v
|
||||
}
|
||||
|
||||
/// Select what Unlock All or Show All changed (`ids`): the objects, and the ruler guides among
|
||||
/// them as guides (a guide that still can't be edited is then dropped from the selection).
|
||||
fn select_changed(d: &Document, sel: &mut vectorcraft_doc::Selection, ids: &[NodeId]) {
|
||||
let guides: std::collections::HashSet<NodeId> = d.ruler_guides().into_iter().filter_map(|g| g.id).collect();
|
||||
let (on_guides, objects): (Vec<NodeId>, Vec<NodeId>) = ids.iter().copied().partition(|id| guides.contains(id));
|
||||
sel.set(objects);
|
||||
sel.guides = on_guides;
|
||||
}
|
||||
|
||||
/// The objects that `f` picks for `object.unlockAll` and `object.showAll` (`cmd`): in the whole
|
||||
/// document, inside the isolated object in isolation mode, or with `scope: "group"` inside the
|
||||
/// document (its ruler guides included), inside the isolated object in isolation mode, or with `scope: "group"` inside the
|
||||
/// groups that hold the selected objects (in isolation mode, only the objects of those groups
|
||||
/// that are inside the isolated object). A selected group is the group that holds its own
|
||||
/// members, and the objects of a group inside another such group are taken once. With
|
||||
@@ -253,7 +272,7 @@ pub(super) fn unlock_all(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
n.locked = false;
|
||||
}
|
||||
}
|
||||
sel.set(ids.iter().copied());
|
||||
select_changed(d, sel, &ids);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "count": ids.len() }))
|
||||
@@ -292,7 +311,7 @@ pub(super) fn show_all(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
n.visible = true;
|
||||
}
|
||||
}
|
||||
sel.set(ids.iter().copied());
|
||||
select_changed(d, sel, &ids);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "count": ids.len() }))
|
||||
|
||||
@@ -7,7 +7,7 @@ use super::props::set_props;
|
||||
use super::shape::{expand_shape, set_live_shape};
|
||||
use super::transform::{move_cmd, nudge, reflect, rotate, scale, shear, transform, transform_again};
|
||||
use super::{CommandSpec, cmd, has_doc, has_multi, has_selection, has_selection_or_guides};
|
||||
use crate::cmd::has_selected_member;
|
||||
use crate::cmd::has_selected_member_or_guide;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -151,8 +151,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Selection",
|
||||
["Object", "Lock"],
|
||||
Some("Cmd+2"),
|
||||
"{ids?: [id…] (selected first; default: the selection; in isolation mode, only those inside the isolated object)}",
|
||||
has_selected_member,
|
||||
"{ids?: [id…] (selected first; default: the selection, selected ruler guides included; in isolation mode, only the objects inside the isolated object)}",
|
||||
has_selected_member_or_guide,
|
||||
lock
|
||||
),
|
||||
cmd!(
|
||||
@@ -160,7 +160,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Unlock All",
|
||||
["Object"],
|
||||
Some("Cmd+Alt+2"),
|
||||
"{scope?: \"document\"|\"group\" (default document, which in isolation mode is the isolated object; group: only the objects inside the groups that hold the selected objects, a selected group holding its own; the in-window menu item chosen with Shift+Alt)} unlock the locked objects and select them → {count}",
|
||||
"{scope?: \"document\"|\"group\" (default document, which in isolation mode is the isolated object; group: only the objects inside the groups that hold the selected objects, a selected group holding its own; the in-window menu item chosen with Shift+Alt)} unlock the locked objects and select them; document scope outside isolation mode also unlocks ruler guides locked on their own → {count}",
|
||||
has_doc,
|
||||
unlock_all
|
||||
),
|
||||
@@ -169,8 +169,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Selection",
|
||||
["Object", "Hide"],
|
||||
Some("Cmd+3"),
|
||||
"{ids?: [id…] (selected first; default: the selection; in isolation mode, only those inside the isolated object)}",
|
||||
has_selected_member,
|
||||
"{ids?: [id…] (selected first; default: the selection, selected ruler guides included; in isolation mode, only the objects inside the isolated object)}",
|
||||
has_selected_member_or_guide,
|
||||
hide
|
||||
),
|
||||
cmd!(
|
||||
@@ -178,7 +178,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Show All",
|
||||
["Object"],
|
||||
Some("Cmd+Alt+3"),
|
||||
"{scope?: \"document\"|\"group\" (default document, which in isolation mode is the isolated object; group: only the objects inside the groups that hold the selected objects, a selected group holding its own; the in-window menu item chosen with Shift+Alt)} show the hidden objects and select them → {count}",
|
||||
"{scope?: \"document\"|\"group\" (default document, which in isolation mode is the isolated object; group: only the objects inside the groups that hold the selected objects, a selected group holding its own; the in-window menu item chosen with Shift+Alt)} show the hidden objects and select them; document scope outside isolation mode also shows ruler guides hidden on their own → {count}",
|
||||
has_doc,
|
||||
show_all
|
||||
),
|
||||
|
||||
@@ -12,7 +12,8 @@
|
||||
//! `object.objectsOnPath.selectMember` chooses one object of a selected group (its Select/Move
|
||||
//! widget), and `object.objectsOnPath.moveMember` moves one object to another's place along the
|
||||
//! path, the objects between it and that place each moving one place toward where it was; hidden
|
||||
//! and locked objects keep their places.
|
||||
//! and locked objects keep their places. `object.objectsOnPath.detach` takes one object out of its
|
||||
//! group, just above it, and the others move up the path.
|
||||
//!
|
||||
//! After every edit, [`refresh`] puts the objects of each Objects on Path group that changed back
|
||||
//! on its path: editing the path moves them, an object moved on its own goes back to its place,
|
||||
@@ -21,7 +22,8 @@
|
||||
//!
|
||||
//! Behavior: <https://helpx.adobe.com/illustrator/using/objects-on-path.html> (the tool and
|
||||
//! Object › Objects on Path › Attach; the order on the path, the attachment point, the distribution,
|
||||
//! the objects squared to the path; Pivot and Rotate; path edits realign the objects; Expand).
|
||||
//! the objects squared to the path; Pivot and Rotate; path edits realign the objects; Detach and
|
||||
//! the objects that move up the path after it; Expand).
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
@@ -75,6 +77,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
move_member
|
||||
),
|
||||
cmd!(
|
||||
"object.objectsOnPath.detach",
|
||||
"Detach Object from Path",
|
||||
[],
|
||||
None,
|
||||
"{member?: id of an object of an Objects on Path group (default: the object chosen with the selected group's Select/Move widget); neither the object nor the group may be hidden or locked} take one object off the path, out of its group and just above the group in the Layers panel, where it stays as drawn and is selected alone. The group's other objects move up the path in their order: with Auto Space they spread evenly again, and a Space value and the start are kept. The group and its path stay, even with one object or none left → {group, member}",
|
||||
has_doc,
|
||||
detach
|
||||
),
|
||||
cmd!(
|
||||
"object.objectsOnPath.expand",
|
||||
"Expand",
|
||||
@@ -383,6 +394,47 @@ fn move_member(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "group": g.0, "member": member.0, "index": index }))
|
||||
}
|
||||
|
||||
// ---------- Detach ----------
|
||||
|
||||
/// The object chosen with the Select/Move widget of the one selected Objects on Path group.
|
||||
fn chosen_member(s: &Session) -> Option<NodeId> {
|
||||
let st = s.active()?;
|
||||
match st.selection.objects[..] {
|
||||
[_] => st.selection.on_path_member,
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn detach(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.objectsOnPath.detach";
|
||||
const CHOOSE: &str = "choose the object to detach with its Select/Move widget";
|
||||
let (g, member) = if p.get("member").is_none_or(Value::is_null) {
|
||||
let chosen = chosen_member(s).ok_or_else(|| bad(C, CHOOSE))?;
|
||||
let found = member_param(s, &json!({ "member": chosen.0 }), "member", C)?;
|
||||
if s.active().is_none_or(|st| st.selection.objects[..] != [found.0]) {
|
||||
return Err(bad(C, CHOOSE));
|
||||
}
|
||||
found
|
||||
} else {
|
||||
member_param(s, p, "member", C)?
|
||||
};
|
||||
// The object goes just above the group, in the group's parent, and keeps where it is drawn.
|
||||
// When the group is itself an object on another group's path, the object goes above that
|
||||
// group instead (and so on outward), so it does not join that path. The refresh after the edit
|
||||
// removes it from the group's record and moves the others up the path.
|
||||
s.edit("Detach Object from Path", |d, sel| {
|
||||
let mut above = g;
|
||||
while let Some(p) = d.parent_of(above).filter(|p| d.node(*p).is_some_and(is_objects_on_path)) {
|
||||
above = p;
|
||||
}
|
||||
let (parent, index, _) = d.position(above).ok_or(EngineError::NoNode(above))?;
|
||||
d.move_node(member, parent, index + 1)?;
|
||||
sel.set([member]);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "group": g.0, "member": member.0 }))
|
||||
}
|
||||
|
||||
// ---------- Expand ----------
|
||||
|
||||
fn expand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -6,7 +6,7 @@ use serde_json::{Value, json};
|
||||
use vectorcraft_color::{BlendMode, Color, GradientPaint, Paint};
|
||||
use vectorcraft_doc::{Appearance, CharStyle, Document, GraySource, Node, NodeId, NodeKind};
|
||||
|
||||
use super::appearance::{ItemTarget, appearance_targets, edit_items, edit_items_then, item_target};
|
||||
use super::appearance::{ItemTarget, edit_items, edit_items_then, item_target, row_targets};
|
||||
use super::gradient::{item_paint_bounds, place_paint, place_run_paint, run_paint_mut, run_stroke_weight, unplaced};
|
||||
use super::{
|
||||
Affine, CommandSpec, Result, Session, always, bad, bool_or, check_numbers, check_switches, cmd, color_value, has_doc, leaf_targets, ok,
|
||||
@@ -73,7 +73,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Transparency",
|
||||
["Window", "Transparency"],
|
||||
None,
|
||||
"{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, item?: appearance item index|null, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects; a gradient mesh point last clicked with the Mesh tool or Direct Selection takes the opacity itself). With an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, opacity and blend change that object for this instance only (isolate, knockout, knockoutShape, aligned and target are refused). On a path directly in a graph series, the graph also stores the opacity and blend mode of the object and of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
"{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, item?: appearance item index|null, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects; a gradient mesh point last clicked with the Mesh tool or Direct Selection takes the opacity itself). With an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, opacity and blend change that object for this instance only (isolate, knockout, knockoutShape, aligned and target are refused). On a path directly in a graph series (for a fill or stroke item, a series group's id stands for those paths), the graph also stores the opacity and blend mode of the object and of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
transparency
|
||||
),
|
||||
@@ -1062,7 +1062,7 @@ fn transparency(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return s.execute("object.setProps", &Value::Object(q));
|
||||
};
|
||||
// Opacity and blend belong to the targeted fill/stroke; isolate/knockout/knockoutShape stay object-level.
|
||||
let item_ids = if editing_mask { ids } else { appearance_targets(s, p)? };
|
||||
let item_ids = if editing_mask { ids } else { row_targets(s, p)? };
|
||||
if explicit {
|
||||
let d = &s.doc()?.doc;
|
||||
if !item_ids.iter().any(|id| d.node(*id).is_some_and(|n| index < n.appearance.items.len())) {
|
||||
|
||||
+216
-11
@@ -481,6 +481,12 @@ fn join_point(sp: &mut SubPath, ai: usize, smooth: bool) {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Anchors that [`merge_coincident`] moved to a lower index of their vector on this thread.
|
||||
static ANCHOR_MOVES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Merge each run of `picked` neighbours of `sp` that lie on one another into one anchor, which
|
||||
/// keeps the first one's incoming handle and the last one's outgoing handle. Returns how many
|
||||
/// anchors went.
|
||||
@@ -501,23 +507,68 @@ fn merge_coincident(sp: &mut SubPath, picked: impl Fn(usize) -> bool, join_kind:
|
||||
join_point(sp, 0, smooth);
|
||||
}
|
||||
}
|
||||
// Back to front, so the indices `picked` knows stay true for the anchors still to visit.
|
||||
for i in (1..sp.anchors.len()).rev() {
|
||||
// Back to front, so the indices `picked` knows stay true for the anchors still to visit. A
|
||||
// merged anchor is only marked here; the marked anchors are removed in one pass at the end.
|
||||
let closed = sp.closed;
|
||||
let anchors = &mut sp.anchors;
|
||||
let len = anchors.len();
|
||||
let mut gone = vec![false; len];
|
||||
// The anchor after `i` that is still on the path, and the last one still on it.
|
||||
let mut next = None;
|
||||
let mut last = len.saturating_sub(1);
|
||||
for i in (1..len).rev() {
|
||||
if picked(i - 1)
|
||||
&& picked(i)
|
||||
&& let Some([a, b]) = sp.anchors.get_mut(i - 1..=i)
|
||||
&& let Some([a, b]) = anchors.get_mut(i - 1..=i)
|
||||
&& same(a, b)
|
||||
{
|
||||
a.h_out = b.h_out;
|
||||
sp.anchors.remove(i);
|
||||
if let Some(smooth) = join_kind {
|
||||
join_point(sp, i - 1, smooth);
|
||||
if let Some(slot) = gone.get_mut(i) {
|
||||
*slot = true;
|
||||
}
|
||||
if next.is_none() {
|
||||
last = i - 1;
|
||||
}
|
||||
if let Some(smooth) = join_kind {
|
||||
// The neighbors the anchor has on the path as it now stands, as `join_point` sees them.
|
||||
let prev = if i > 1 { Some(i - 2) } else { closed.then_some(last) };
|
||||
let after = next.or(closed.then_some(0));
|
||||
join_point_between(anchors, i - 1, prev, after, smooth);
|
||||
}
|
||||
} else {
|
||||
next = Some(i);
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
if let Some(first) = gone.iter().position(|&g| g) {
|
||||
// `retain` moves each anchor it keeps after the first one it drops.
|
||||
let dropped = gone.iter().filter(|&&g| g).count();
|
||||
ANCHOR_MOVES.set(ANCHOR_MOVES.get() + (len - first - dropped));
|
||||
}
|
||||
if gone.contains(&true) {
|
||||
let mut k = 0;
|
||||
anchors.retain(|_| {
|
||||
let keep = !gone.get(k).copied().unwrap_or(false);
|
||||
k += 1;
|
||||
keep
|
||||
});
|
||||
}
|
||||
before - sp.anchors.len()
|
||||
}
|
||||
|
||||
/// [`join_point`] on anchor `ai` of `anchors` with its neighbors given by index.
|
||||
fn join_point_between(anchors: &mut [Anchor], ai: usize, prev: Option<usize>, next: Option<usize>, smooth: bool) {
|
||||
let at = |j: Option<usize>| j.and_then(|j| anchors.get(j)).map(|a| a.p);
|
||||
let (prev, next) = (at(prev), at(next));
|
||||
if let Some(a) = anchors.get_mut(ai) {
|
||||
if smooth {
|
||||
a.smooth_between(prev, next);
|
||||
} else {
|
||||
a.retract();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Close subpath `si` of path `id`, merging coincident endpoints if present.
|
||||
fn close_subpath_in_node(d: &mut Document, id: NodeId, si: usize, join_kind: Option<bool>) -> Result<()> {
|
||||
let path = path_mut(d, id)?;
|
||||
@@ -751,8 +802,19 @@ pub(super) fn join(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut merged = vec![];
|
||||
for (id, picked) in &st.selection.anchors {
|
||||
let Some(mut path) = st.doc.node(*id).and_then(|n| n.path_data()).cloned() else { continue };
|
||||
let n: usize =
|
||||
path.subpaths.iter_mut().enumerate().map(|(si, sp)| merge_coincident(sp, |ai| picked.contains(&(si, ai)), join_kind)).sum();
|
||||
// One flag per anchor; references past the end of a subpath or to a missing one pick nothing.
|
||||
let mut masks: Vec<Vec<bool>> = path.subpaths.iter().map(|sp| vec![false; sp.anchors.len()]).collect();
|
||||
for &(si, ai) in picked {
|
||||
if let Some(flag) = masks.get_mut(si).and_then(|m| m.get_mut(ai)) {
|
||||
*flag = true;
|
||||
}
|
||||
}
|
||||
let n: usize = path
|
||||
.subpaths
|
||||
.iter_mut()
|
||||
.zip(&masks)
|
||||
.map(|(sp, mask)| merge_coincident(sp, |ai| mask.get(ai).copied().unwrap_or(false), join_kind))
|
||||
.sum();
|
||||
if n > 0 {
|
||||
merged.push((*id, path));
|
||||
}
|
||||
@@ -1276,7 +1338,7 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.flat_map(|(si, sp)| {
|
||||
let cuts = refs.iter().filter_map(|&(s, seg)| (s == si).then_some(seg)).collect();
|
||||
let cuts = subpath_refs(refs, si).collect();
|
||||
without_segments(sp, &cuts)
|
||||
})
|
||||
.filter(|s| s.anchors.len() >= 2)
|
||||
@@ -1288,7 +1350,7 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.flat_map(|(si, sp)| {
|
||||
let gone = set.iter().filter_map(|&(s, ai)| (s == si).then_some(ai)).collect();
|
||||
let gone = subpath_refs(set, si).collect();
|
||||
without_anchors(sp, &gone)
|
||||
})
|
||||
.filter(|s| s.anchors.len() >= 2)
|
||||
@@ -1314,6 +1376,12 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
/// The anchor or segment indexes in `refs` that belong to subpath `si`, in index order.
|
||||
/// `refs` is ordered by subpath first, so this reads only that subpath's entries.
|
||||
pub(super) fn subpath_refs(refs: &BTreeSet<(usize, usize)>, si: usize) -> impl Iterator<Item = usize> + '_ {
|
||||
refs.range((si, 0)..=(si, usize::MAX)).map(|&(_, i)| i)
|
||||
}
|
||||
|
||||
/// Retain path `id` from `d` without copying its geometry before deletion takes its subpaths.
|
||||
/// The shared snapshot supplies the original path classification and, only if needed, gradient
|
||||
/// bounds after the working node's geometry has moved. Returns `NoNode` for a missing/non-path ID.
|
||||
@@ -1722,7 +1790,7 @@ fn cut_at_anchors(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let Some(pd) = st.doc.node(*id).and_then(|n| n.path_data()) else { continue };
|
||||
let (mut subs, mut starts) = (vec![], vec![]);
|
||||
for (si, sp) in pd.subpaths.iter().enumerate() {
|
||||
let at: BTreeSet<usize> = set.iter().filter(|(s, _)| *s == si).map(|(_, a)| *a).collect();
|
||||
let at: BTreeSet<usize> = subpath_refs(set, si).collect();
|
||||
let pieces = sp.cut_at(&at);
|
||||
// The pieces that start at a cut: every piece of an opened closed subpath, all but the
|
||||
// first of an open one.
|
||||
@@ -1763,3 +1831,140 @@ fn cut_at_anchors(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
})?;
|
||||
Ok(super::draw2::ids_json(&ids))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// `merge_coincident` removing each merged anchor from the vector straight away, kept as the
|
||||
/// reference the one-pass version must match.
|
||||
fn merge_coincident_by_removal(sp: &mut SubPath, picked: impl Fn(usize) -> bool, join_kind: Option<bool>) -> usize {
|
||||
let same = |a: &Anchor, b: &Anchor| a.p.distance(b.p) < 1e-6;
|
||||
let before = sp.anchors.len();
|
||||
if sp.closed
|
||||
&& before > 2
|
||||
&& picked(0)
|
||||
&& picked(before - 1)
|
||||
&& let [first, .., last] = sp.anchors.as_mut_slice()
|
||||
&& same(first, last)
|
||||
{
|
||||
first.h_in = last.h_in;
|
||||
sp.anchors.pop();
|
||||
if let Some(smooth) = join_kind {
|
||||
join_point(sp, 0, smooth);
|
||||
}
|
||||
}
|
||||
for i in (1..sp.anchors.len()).rev() {
|
||||
if picked(i - 1)
|
||||
&& picked(i)
|
||||
&& let Some([a, b]) = sp.anchors.get_mut(i - 1..=i)
|
||||
&& same(a, b)
|
||||
{
|
||||
a.h_out = b.h_out;
|
||||
sp.anchors.remove(i);
|
||||
if let Some(smooth) = join_kind {
|
||||
join_point(sp, i - 1, smooth);
|
||||
}
|
||||
}
|
||||
}
|
||||
before - sp.anchors.len()
|
||||
}
|
||||
|
||||
/// Every field of every anchor, bit for bit.
|
||||
fn bits(sp: &SubPath) -> (Vec<[u64; 6]>, Vec<AnchorKind>, bool) {
|
||||
let b = |p: Point| [p.x.to_bits(), p.y.to_bits()];
|
||||
let fields = sp.anchors.iter().map(|a| [b(a.p), b(a.h_in), b(a.h_out)].concat().try_into().unwrap()).collect();
|
||||
(fields, sp.anchors.iter().map(|a| a.kind).collect(), sp.closed)
|
||||
}
|
||||
|
||||
/// A small linear congruential generator, so the cases are the same on every run.
|
||||
struct Lcg(u64);
|
||||
impl Lcg {
|
||||
fn below(&mut self, n: u64) -> u64 {
|
||||
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
|
||||
(self.0 >> 33) % n
|
||||
}
|
||||
}
|
||||
|
||||
fn same_as_removal(sp: &SubPath, picked: &dyn Fn(usize) -> bool, join_kind: Option<bool>) {
|
||||
let (mut ours, mut theirs) = (sp.clone(), sp.clone());
|
||||
let n = merge_coincident(&mut ours, picked, join_kind);
|
||||
let m = merge_coincident_by_removal(&mut theirs, picked, join_kind);
|
||||
assert_eq!(n, m, "{sp:?} {join_kind:?}");
|
||||
assert_eq!(bits(&ours), bits(&theirs), "{sp:?} {join_kind:?}");
|
||||
}
|
||||
|
||||
/// Short paths with points on, near and just past the merge distance, selections with stale
|
||||
/// indices, every anchor kind and every join kind give the same anchors, bit for bit, as
|
||||
/// removing each merged anchor straight away.
|
||||
#[test]
|
||||
fn merging_coincident_anchors_matches_removing_them_one_by_one() {
|
||||
let spots = [(0.0, 0.0), (0.0, 0.0), (0.0, 0.0), (5e-7, 0.0), (0.0, 1.5e-6), (10.0, 0.0), (5.0, 5.0), (10.0, 0.0)];
|
||||
let mut rng = Lcg(7);
|
||||
for _ in 0..30_000 {
|
||||
let n = rng.below(9) as usize;
|
||||
let anchors = (0..n)
|
||||
.map(|_| {
|
||||
let (x, y) = spots[rng.below(spots.len() as u64) as usize];
|
||||
let p = Point::new(x, y);
|
||||
let handle = |rng: &mut Lcg| match rng.below(3) {
|
||||
0 => p,
|
||||
_ => p + Vec2::new(rng.below(7) as f64 - 3.0, rng.below(7) as f64 - 3.0),
|
||||
};
|
||||
let (h_in, h_out) = (handle(&mut rng), handle(&mut rng));
|
||||
let kind = if rng.below(2) == 0 { AnchorKind::Corner } else { AnchorKind::Smooth };
|
||||
Anchor { p, h_in, h_out, kind }
|
||||
})
|
||||
.collect();
|
||||
let sp = SubPath::new(anchors, rng.below(2) == 0);
|
||||
let picks: Vec<bool> = (0..n + 2).map(|_| rng.below(4) != 0).collect();
|
||||
let join_kind = [None, Some(false), Some(true)][rng.below(3) as usize];
|
||||
same_as_removal(&sp, &|i| picks.get(i).copied().unwrap_or(false), join_kind);
|
||||
}
|
||||
}
|
||||
|
||||
/// A smooth join of three anchors on one another takes the outgoing handle the middle anchor
|
||||
/// was given when it joined the right one: an already smooth left anchor keeps that handle.
|
||||
#[test]
|
||||
fn a_smooth_join_of_three_anchors_keeps_the_handle_the_middle_one_got() {
|
||||
let o = Point::ZERO;
|
||||
let left = Anchor { p: o, h_in: Point::new(-2.0, 0.0), h_out: o, kind: AnchorKind::Smooth };
|
||||
let right = Anchor { p: o, h_in: o, h_out: Point::new(0.0, 5.0), kind: AnchorKind::Corner };
|
||||
let mut sp = SubPath::new(vec![left, Anchor::corner(o), right, Anchor::corner(Point::new(10.0, 0.0))], false);
|
||||
assert_eq!(merge_coincident(&mut sp, |i| i < 3, Some(true)), 2);
|
||||
let a = sp.anchors[0];
|
||||
assert_eq!((a.h_in, a.h_out, a.kind), (Point::new(-2.0, 0.0), Point::new(10.0 / 3.0, 0.0), AnchorKind::Smooth));
|
||||
assert_eq!(sp.anchors.len(), 2);
|
||||
}
|
||||
|
||||
/// One long run of selected anchors on one another, open or closed, becomes one anchor.
|
||||
#[test]
|
||||
fn a_long_run_of_anchors_on_one_another_becomes_one() {
|
||||
for closed in [false, true] {
|
||||
for join_kind in [None, Some(false), Some(true)] {
|
||||
let anchors = (0..50_000).map(|i| Anchor::smooth(Point::ZERO, Point::new(1.0, i as f64))).collect();
|
||||
let sp = SubPath::new(anchors, closed);
|
||||
same_as_removal(&sp, &|_| true, join_kind);
|
||||
let mut ours = sp.clone();
|
||||
assert_eq!(merge_coincident(&mut ours, |_| true, join_kind), 49_999);
|
||||
assert_eq!((ours.anchors.len(), ours.closed), (1, closed));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A long selected run at the start of a path followed by as many anchors that stay: each
|
||||
/// anchor after the run moves once, not once per merged anchor.
|
||||
#[test]
|
||||
fn a_long_run_before_many_other_anchors_merges_in_one_pass() {
|
||||
let run = 300_000;
|
||||
let anchors = (0..run).map(|_| Anchor::corner(Point::ZERO)).chain((1..=run).map(|i| Anchor::corner(Point::new(i as f64, 1.0)))).collect();
|
||||
let mut sp = SubPath::new(anchors, false);
|
||||
ANCHOR_MOVES.set(0);
|
||||
assert_eq!(merge_coincident(&mut sp, |i| i < run, Some(false)), run - 1);
|
||||
assert_eq!(ANCHOR_MOVES.get(), run);
|
||||
assert_eq!(sp.anchors.len(), run + 1);
|
||||
assert_eq!(sp.anchors[0].p, Point::ZERO);
|
||||
assert_eq!(sp.anchors[1].p, Point::new(1.0, 1.0));
|
||||
assert_eq!(sp.anchors[run].p, Point::new(run as f64, 1.0));
|
||||
}
|
||||
}
|
||||
@@ -1228,7 +1228,7 @@ fn simplify(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(l) => po::simplify_level_tolerance(l),
|
||||
None => given_tolerance.unwrap_or(1.0),
|
||||
};
|
||||
let opts = po::SimplifyOptions { tolerance: tolerance.clamp(1e-4, 1e4), corner_angle_deg: corner_angle, straight_lines, smooth: 0.0 };
|
||||
let opts = po::SimplifyOptions { tolerance: tolerance.clamp(1e-4, 1e4), corner_angle_deg: corner_angle, straight_lines, ..Default::default() };
|
||||
// A path with segments direct-selected simplifies only their runs, and keeps those runs (and the
|
||||
// other anchors it had selected) direct-selected.
|
||||
let roots = selected_roots(s)?;
|
||||
|
||||
@@ -58,6 +58,9 @@ use crate::{EngineError, MAX_COORD};
|
||||
|
||||
const PLACE: &str = "file.place";
|
||||
const QUEUE: &str = "file.place.queue";
|
||||
/// The error of a file read apart from the session while another document is active, or after the
|
||||
/// document it was read for closed ([`Session::place_read`], [`Session::place_queue_read`]).
|
||||
const NOT_ACTIVE: &str = "the document it was prepared for is no longer active";
|
||||
/// The most files one `file.place.queue` loads.
|
||||
const MAX_QUEUE: usize = 100;
|
||||
/// The longest thumbnail side `thumbnail` may ask for (px).
|
||||
@@ -503,11 +506,13 @@ fn fit(natural: Rect, r: Rect) -> Affine {
|
||||
Affine::translate(r.center().to_vec2()) * Affine::scale(k) * Affine::translate(-natural.center().to_vec2())
|
||||
}
|
||||
|
||||
/// What `file.place` takes from the session before it reads the file: the params, the object
|
||||
/// Replace swaps and the artboard under `at`, which a DXF drawing is laid out on
|
||||
/// ([`Session::prepare_place`]). [`PlaceJob::read`] reads and decodes the file without the session,
|
||||
/// on any thread.
|
||||
/// What `file.place` takes from the session before it reads the file: the document it places into,
|
||||
/// the params, the object Replace swaps and the artboard under `at`, which a DXF drawing is laid
|
||||
/// out on ([`Session::prepare_place`]). [`PlaceJob::read`] reads and decodes the file without the
|
||||
/// session, on any thread.
|
||||
pub struct PlaceJob {
|
||||
/// The document it was prepared in (`DocState::uid`).
|
||||
doc: u64,
|
||||
params: Value,
|
||||
old: Option<NodeId>,
|
||||
/// The object Replace swaps as it was when Place started.
|
||||
@@ -560,10 +565,14 @@ impl Session {
|
||||
|
||||
/// Run `file.place` with the params of `read` as a command (checked and journaled as any
|
||||
/// other) that places the file `read` holds instead of reading it again → `file.place`'s
|
||||
/// reply. The object Replace swaps must still be in the document as it was when Place started;
|
||||
/// when the selection changed meanwhile, `select.set` selects that object again first, so a
|
||||
/// replay of the journal replaces the same object.
|
||||
/// reply. The document Place started in must be the active one, and the object Replace swaps
|
||||
/// must still be in it as it was when Place started; when the selection changed meanwhile,
|
||||
/// `select.set` selects that object again first, so a replay of the journal replaces the same
|
||||
/// object.
|
||||
pub fn place_read(&mut self, read: PlaceRead) -> Result<Value> {
|
||||
if self.doc()?.uid != read.job.doc {
|
||||
return Err(bad(PLACE, NOT_ACTIVE));
|
||||
}
|
||||
let params = read.job.params.clone();
|
||||
if let Some(old) = read.job.old {
|
||||
let st = self.doc()?;
|
||||
@@ -615,7 +624,7 @@ fn prepare(s: &Session, p: &Value) -> Result<PlaceJob> {
|
||||
(true, _) => return Err(bad(PLACE, "replace: select the one object to replace")),
|
||||
};
|
||||
let replaced = old.and_then(|id| st.doc.node(id)).cloned();
|
||||
Ok(PlaceJob { params: p.clone(), old, replaced, target: board_at(&st.doc, at) })
|
||||
Ok(PlaceJob { doc: st.uid, params: p.clone(), old, replaced, target: board_at(&st.doc, at) })
|
||||
}
|
||||
|
||||
/// Place the file `read` holds in the active document.
|
||||
@@ -755,6 +764,8 @@ fn queued_files(p: &Value) -> Result<Vec<Value>> {
|
||||
/// ([`Session::prepare_place_queue`]). [`QueueJob::read`] reads them without the session, on any
|
||||
/// thread.
|
||||
pub struct QueueJob {
|
||||
/// The document it was prepared in (`DocState::uid`).
|
||||
doc: u64,
|
||||
params: Value,
|
||||
files: Vec<Value>,
|
||||
}
|
||||
@@ -762,6 +773,8 @@ pub struct QueueJob {
|
||||
/// The files [`QueueJob::read`] read, which [`Session::place_queue_read`] loads the place cursor
|
||||
/// with.
|
||||
pub struct QueueRead {
|
||||
/// The document the files were read for (`DocState::uid`).
|
||||
doc: u64,
|
||||
params: Value,
|
||||
entries: Vec<Value>,
|
||||
files: Vec<Value>,
|
||||
@@ -776,13 +789,13 @@ impl QueueJob {
|
||||
|
||||
/// Read every file for its size and thumbnail, as `file.place.queue` does, without the session.
|
||||
pub fn read(self) -> Result<QueueRead> {
|
||||
read_queue(self.params, self.files)
|
||||
read_queue(self.doc, self.params, self.files)
|
||||
}
|
||||
}
|
||||
|
||||
/// Read each of `queued`, the files of `file.place.queue` with params `p`, for its size and
|
||||
/// thumbnail.
|
||||
fn read_queue(p: Value, queued: Vec<Value>) -> Result<QueueRead> {
|
||||
/// Read each of `queued`, the files of `file.place.queue` with params `p` for the document `doc`,
|
||||
/// for its size and thumbnail.
|
||||
fn read_queue(doc: u64, p: Value, queued: Vec<Value>) -> Result<QueueRead> {
|
||||
let thumbnail = p.get("thumbnail").and_then(Value::as_f64);
|
||||
let (mut entries, mut files, mut skipped) = (vec![], vec![], vec![]);
|
||||
for mut q in queued {
|
||||
@@ -823,7 +836,7 @@ fn read_queue(p: Value, queued: Vec<Value>) -> Result<QueueRead> {
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(QueueRead { params: p, entries, files, skipped })
|
||||
Ok(QueueRead { doc, params: p, entries, files, skipped })
|
||||
}
|
||||
|
||||
impl Session {
|
||||
@@ -834,12 +847,17 @@ impl Session {
|
||||
has_doc(self).map_err(|why| EngineError::Disabled(QUEUE.into(), why))?;
|
||||
check_switches(params, &["link", "template"], QUEUE)?;
|
||||
check_numbers(params, &["thumbnail"], QUEUE)?;
|
||||
Ok(QueueJob { params: params.clone(), files: queued_files(params)? })
|
||||
let files = queued_files(params)?;
|
||||
Ok(QueueJob { doc: self.doc()?.uid, params: params.clone(), files })
|
||||
}
|
||||
|
||||
/// Run `file.place.queue` with the params of `read` as a command that loads the place cursor
|
||||
/// with the files `read` holds instead of reading them again → `file.place.queue`'s reply.
|
||||
/// with the files `read` holds instead of reading them again → `file.place.queue`'s reply. The
|
||||
/// document the files were read for must be the active one.
|
||||
pub fn place_queue_read(&mut self, read: QueueRead) -> Result<Value> {
|
||||
if self.doc()?.uid != read.doc {
|
||||
return Err(bad(QUEUE, NOT_ACTIVE));
|
||||
}
|
||||
let params = read.params.clone();
|
||||
self.queue_hand_off = Some(read);
|
||||
let r = self.execute(QUEUE, ¶ms);
|
||||
@@ -944,7 +962,8 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
(None, [id]) => *id,
|
||||
_ => return Err(bad(C, "select one image or pass id")),
|
||||
};
|
||||
let n = st.doc.node(id).ok_or(EngineError::NoNode(id))?;
|
||||
// An image in opacity-mask art or a definition's art is found by its id too (`links.list`).
|
||||
let n = st.doc.stored_node(id).map(|(n, _)| &**n).ok_or(EngineError::NoNode(id))?;
|
||||
let NodeKind::Image(im) = &n.kind else { return Err(bad(C, format!("object {} is not an image", id.0))) };
|
||||
// Effective resolution: 72 pt per inch over the points one pixel spans along each axis.
|
||||
let [a, b, c, d, ..] = im.xf.as_coeffs();
|
||||
|
||||
@@ -10,7 +10,7 @@ use std::sync::Arc;
|
||||
|
||||
use vectorcraft_brush::{Brush, BrushKind};
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::{AppearanceItem, Document, Node, NodeKind};
|
||||
use vectorcraft_doc::{AppearanceItem, Document, Node, NodeKind, PatternDef, Symbol};
|
||||
|
||||
use super::unique_name;
|
||||
|
||||
@@ -118,11 +118,12 @@ impl Used {
|
||||
type Renames = BTreeMap<String, (Option<String>, bool)>;
|
||||
|
||||
/// Names in `dst` for the `used` definitions of `src` (`def`): the same name when `dst` has none
|
||||
/// (copied) or an equal one (shared), else a free variant (`taken`, copied).
|
||||
fn names<T: PartialEq>(
|
||||
/// (copied) or one that is the `same` (shared), else a free variant (`taken`, copied).
|
||||
fn names<T>(
|
||||
used: &[String],
|
||||
def: impl Fn(&str) -> Option<T>,
|
||||
existing: impl Fn(&str) -> Option<T>,
|
||||
same: impl Fn(&T, &T) -> bool,
|
||||
taken: impl Fn(&str) -> bool,
|
||||
) -> Renames {
|
||||
let mut out = Renames::new();
|
||||
@@ -130,7 +131,7 @@ fn names<T: PartialEq>(
|
||||
let Some(d) = def(name) else { continue };
|
||||
let entry = match existing(name) {
|
||||
None => (Some(name.clone()), true),
|
||||
Some(e) if e == d => (Some(name.clone()), false),
|
||||
Some(e) if same(&e, &d) => (Some(name.clone()), false),
|
||||
Some(_) => {
|
||||
(Some(unique_name(name, |c| taken(c) || used.iter().any(|u| u == c) || out.values().any(|(n, _)| n.as_deref() == Some(c)))), true)
|
||||
}
|
||||
@@ -140,6 +141,65 @@ fn names<T: PartialEq>(
|
||||
out
|
||||
}
|
||||
|
||||
/// `n` as `dst` would copy it in ([`Document::reid`]), with the ids a document of its own gives it:
|
||||
/// art copied in once, which differs from the file's only in its ids, compares equal to the file's.
|
||||
fn canon(dst: &Document, n: &Node) -> Node {
|
||||
let mut own = Document::new(0.0, 0.0);
|
||||
// Pixels the art carries take a key `dst` doesn't use for other pixels, as they do in `dst`.
|
||||
let mut keys = vec![];
|
||||
vectorcraft_doc::swatches::walk_with_masks(n, &mut |c| {
|
||||
if let NodeKind::Image(im) = &c.kind
|
||||
&& im.pixels.is_some()
|
||||
{
|
||||
keys.push(im.key.clone());
|
||||
}
|
||||
});
|
||||
for (k, blob) in &dst.images {
|
||||
if keys.iter().any(|key| k == key || k.strip_prefix(key.as_str()).is_some_and(|rest| rest.starts_with('-'))) {
|
||||
own.images.insert(k.clone(), blob.clone());
|
||||
}
|
||||
}
|
||||
own.reid(n)
|
||||
}
|
||||
|
||||
/// Do symbols `a` and `b` draw the same, whatever ids their art has ([`canon`])?
|
||||
fn same_symbol(dst: &Document, a: &Symbol, b: &Symbol) -> bool {
|
||||
let own = |s: &Symbol| Symbol { art: Arc::new(canon(dst, &s.art)), ..s.clone() };
|
||||
own(a) == own(b)
|
||||
}
|
||||
|
||||
/// Do patterns `a` and `b` draw the same, whatever ids their art has ([`canon`])?
|
||||
fn same_pattern(dst: &Document, a: &PatternDef, b: &PatternDef) -> bool {
|
||||
let bare = |p: &PatternDef| PatternDef { art: vec![], ..p.clone() };
|
||||
bare(a) == bare(b) && a.art.len() == b.art.len() && a.art.iter().zip(&b.art).all(|(x, y)| canon(dst, x) == canon(dst, y))
|
||||
}
|
||||
|
||||
/// Does art `a` use a resource that `m` (images, symbols, patterns, brushes, swatches) gives
|
||||
/// another name, or a swatch whose link `m` drops?
|
||||
fn uses_moved(a: &Node, m: [&Renames; 5]) -> bool {
|
||||
let moved = |map: &Renames, k: &str| map.get(k).is_some_and(|(new, _)| new.as_deref() != Some(k));
|
||||
let (mut a, mut any) = (a.clone(), false);
|
||||
refs(&mut a, &mut |r| {
|
||||
any |= match r {
|
||||
Ref::Image(k) => moved(m[0], k),
|
||||
Ref::Symbol(k) => moved(m[1], k),
|
||||
Ref::Pattern(k) => moved(m[2], k),
|
||||
Ref::Brush(k) => moved(m[3], k),
|
||||
Ref::Swatch(link) => link.as_deref().is_some_and(|k| moved(m[4], k)),
|
||||
}
|
||||
});
|
||||
any
|
||||
}
|
||||
|
||||
/// Copy each of `shared` in `map` under a free name, as [`names`] does for a definition `dst`
|
||||
/// holds differently.
|
||||
fn unshare(map: &mut Renames, shared: &[String], used: &[String], taken: impl Fn(&str) -> bool) {
|
||||
for name in shared {
|
||||
let free = unique_name(name, |c| taken(c) || used.iter().any(|u| u == c) || map.values().any(|(n, _)| n.as_deref() == Some(c)));
|
||||
map.insert(name.clone(), (Some(free), true));
|
||||
}
|
||||
}
|
||||
|
||||
/// The renamed resources whose definitions are copied: (name in `src`, name in `dst`).
|
||||
fn copies(m: &Renames) -> Vec<(&str, &str)> {
|
||||
m.iter().filter(|(_, (_, copy))| *copy).filter_map(|(old, (new, _))| Some((old.as_str(), new.as_deref()?))).collect()
|
||||
@@ -194,14 +254,17 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
|
||||
}
|
||||
}
|
||||
|
||||
let images = names(&used.images, |k| src.images.get(k), |k| dst.images.get(k), |c| dst.images.contains_key(c));
|
||||
let symbols = names(
|
||||
let images = names(&used.images, |k| src.images.get(k), |k| dst.images.get(k), |a, b| a == b, |c| dst.images.contains_key(c));
|
||||
// Symbol and pattern art copied in takes ids of `dst`, so their art is compared by what it
|
||||
// draws: placing the same file again shares what the first placement brought.
|
||||
let mut symbols = names(
|
||||
&used.symbols,
|
||||
|n| src.symbols.iter().find(|s| s.name == n),
|
||||
|n| dst.symbols.iter().find(|s| s.name == n),
|
||||
|a, b| same_symbol(dst, a, b),
|
||||
|c| dst.symbols.iter().any(|s| s.name == c),
|
||||
);
|
||||
let patterns = names(&used.patterns, |n| src.pattern(n), |n| dst.pattern(n), |c| dst.pattern(c).is_some());
|
||||
let mut patterns = names(&used.patterns, |n| src.pattern(n), |n| dst.pattern(n), |a, b| same_pattern(dst, a, b), |c| dst.pattern(c).is_some());
|
||||
// A swatch the document defines differently isn't renamed (that would add look-alike swatches):
|
||||
// the colours linked to it keep their look, unlinked.
|
||||
let swatches: Renames = used
|
||||
@@ -236,12 +299,33 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
|
||||
any
|
||||
};
|
||||
let mut dst_brushes = vectorcraft_brush::library(dst);
|
||||
let brushes = names(
|
||||
let mut brushes = names(
|
||||
&used.brushes,
|
||||
|n| src_brushes.iter().find(|b| b.name == n).map(|b| (b, moves_art(b))),
|
||||
|n| dst_brushes.iter().find(|b| b.name == n).map(|b| (b, false)),
|
||||
|a, b| a == b,
|
||||
|c| dst_brushes.iter().any(|b| b.name == c),
|
||||
);
|
||||
// Likewise a symbol, pattern or brush whose art uses a resource that moves isn't the
|
||||
// document's of that name: it is copied under a free name, which can move what uses it in turn.
|
||||
loop {
|
||||
let maps = [&images, &symbols, &patterns, &brushes, &swatches];
|
||||
let shared = |map: &Renames| map.iter().filter(|(_, (_, copy))| !*copy).map(|(k, _)| k.clone()).collect::<Vec<_>>();
|
||||
let sym: Vec<String> =
|
||||
shared(&symbols).into_iter().filter(|n| src.symbols.iter().any(|s| s.name == *n && uses_moved(&s.art, maps))).collect();
|
||||
let pat: Vec<String> =
|
||||
shared(&patterns).into_iter().filter(|n| src.pattern(n).is_some_and(|p| p.art.iter().any(|a| uses_moved(a, maps)))).collect();
|
||||
let bru: Vec<String> = shared(&brushes)
|
||||
.into_iter()
|
||||
.filter(|n| src_brushes.iter().find(|b| b.name == *n).is_some_and(|b| brush_art(&mut b.clone()).into_iter().any(|a| uses_moved(a, maps))))
|
||||
.collect();
|
||||
if sym.is_empty() && pat.is_empty() && bru.is_empty() {
|
||||
break;
|
||||
}
|
||||
unshare(&mut symbols, &sym, &used.symbols, |c| dst.symbols.iter().any(|s| s.name == c));
|
||||
unshare(&mut patterns, &pat, &used.patterns, |c| dst.pattern(c).is_some());
|
||||
unshare(&mut brushes, &bru, &used.brushes, |c| dst_brushes.iter().any(|b| b.name == c));
|
||||
}
|
||||
|
||||
let mut rename = |r: Ref| {
|
||||
let (map, k) = match r {
|
||||
@@ -272,6 +356,8 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
|
||||
if let Some(mut def) = src.symbols.iter().find(|s| s.name == old).cloned() {
|
||||
def.name = new.to_string();
|
||||
refs(Arc::make_mut(&mut def.art), &mut rename);
|
||||
// The art takes ids of `dst`: those of `src` may name objects of `dst` already.
|
||||
def.art = Arc::new(dst.reid(&def.art));
|
||||
dst.symbols.push(def);
|
||||
}
|
||||
}
|
||||
@@ -280,6 +366,7 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
|
||||
def.name = new.to_string();
|
||||
for a in &mut def.art {
|
||||
refs(Arc::make_mut(a), &mut rename);
|
||||
*a = Arc::new(dst.reid(a));
|
||||
}
|
||||
dst.patterns.push(def);
|
||||
}
|
||||
|
||||
@@ -39,6 +39,55 @@ pub(crate) fn is_dcs(bytes: &[u8]) -> bool {
|
||||
vectorcraft_eps::dcs::read(bytes).is_some()
|
||||
}
|
||||
|
||||
/// The most bytes read from the start of a file to look at its DCS header.
|
||||
pub(crate) const HEAD_BYTES: usize = 1 << 20;
|
||||
|
||||
/// Does the header of the PostScript in file `head` (the first bytes of a file `size` bytes long,
|
||||
/// at most [`HEAD_BYTES`]) name DCS plates? `None` when `head` can't tell: that PostScript doesn't
|
||||
/// start within it (a binary EPS header that puts it further on), or its header goes on past it. A
|
||||
/// `head` that holds the whole file is read as [`is_dcs`] reads it, and a binary EPS header whose
|
||||
/// PostScript or TIFF preview ends past `size` names none, as [`is_dcs`] finds for the whole file.
|
||||
pub(crate) fn head_is_dcs(head: &[u8], size: u64) -> Option<bool> {
|
||||
const DOS_MAGIC: [u8; 4] = [0xC5, 0xD0, 0xD3, 0xC6];
|
||||
if head.len() < HEAD_BYTES || head.len() as u64 >= size {
|
||||
return Some(is_dcs(head));
|
||||
}
|
||||
let (ps, whole) = if head.starts_with(&DOS_MAGIC) {
|
||||
let word = |at: usize| head.get(at..at + 4).and_then(|b| <[u8; 4]>::try_from(b).ok()).map(|b| u32::from_le_bytes(b) as usize);
|
||||
let fits = |at: usize| Some((word(at)? as u64).checked_add(word(at + 4)? as u64).is_some_and(|end| end <= size));
|
||||
if !fits(4)? || (word(24)? != 0 && !fits(20)?) {
|
||||
return Some(false);
|
||||
}
|
||||
let (start, len) = (word(4)?, word(8)?);
|
||||
let ps = head.get(start..).filter(|ps| !ps.is_empty())?;
|
||||
(ps.get(..len).unwrap_or(ps), start.checked_add(len).is_some_and(|end| end <= head.len()))
|
||||
} else {
|
||||
(head, false)
|
||||
};
|
||||
if is_dcs(ps) {
|
||||
return Some(true);
|
||||
}
|
||||
(whole || header_ended(ps)).then_some(false)
|
||||
}
|
||||
|
||||
/// Does `ps`, the start of some PostScript, hold all of the header [`vectorcraft_eps::dcs::read`]
|
||||
/// looks at (up to `%%EndComments`, a line that isn't a comment, or its 10,000th line)? Its last
|
||||
/// line may be cut off, so it doesn't count.
|
||||
fn header_ended(ps: &[u8]) -> bool {
|
||||
let mut lines = ps.split(|b| matches!(b, b'\n' | b'\r')).filter(|l| !l.is_empty()).peekable();
|
||||
let mut n = 0;
|
||||
while let Some(line) = lines.next() {
|
||||
if lines.peek().is_none() {
|
||||
return false;
|
||||
}
|
||||
n += 1;
|
||||
if line.starts_with(b"%%EndComments") || !line.starts_with(b"%") || n >= 10_000 {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// DCS file `bytes`, read from `path` (when there is one: plate files of their own are found in its
|
||||
/// folder), with every plate.
|
||||
pub(crate) fn read(bytes: &[u8], path: Option<&str>) -> Result<DcsArt> {
|
||||
|
||||
@@ -378,8 +378,10 @@ pub(crate) fn full_documents(d: &Document) -> (Cow<'_, Document>, Vec<String>) {
|
||||
/// Placed document `id` of `d` replaced by an editable copy of its art, as placing its file
|
||||
/// without Link gives (its resources joining `d`, renamed where `d` uses a name for something
|
||||
/// else), keeping the object's id, place, name and transparency: Break Link and Object › Expand.
|
||||
/// A placed document in opacity-mask art or in the art of a symbol, graph design or pattern is
|
||||
/// replaced where it is stored.
|
||||
pub(crate) fn expand(d: &mut Document, id: NodeId, cmd: &str) -> Result<()> {
|
||||
let n = d.node(id).cloned().ok_or(EngineError::NoNode(id))?;
|
||||
let n = d.stored_node(id).map(|(n, _)| Node::clone(n)).ok_or(EngineError::NoNode(id))?;
|
||||
let NodeKind::PlacedDocument(p) = &n.kind else { return Err(bad(cmd, format!("object {} is not a placed document", id.0))) };
|
||||
let blob = d.images.get(&p.key).ok_or_else(|| bad(cmd, format!("object {} has lost its file's contents: relink it", id.0)))?;
|
||||
let bytes = vectorcraft_doc::placed_document::full_bytes(p, blob)
|
||||
@@ -395,6 +397,10 @@ pub(crate) fn expand(d: &mut Document, id: NodeId, cmd: &str) -> Result<()> {
|
||||
let art = super::transformed(Node::new(d.alloc_id(), NodeKind::Group { children, clip: a.clip.is_some() }), m);
|
||||
let mut out = n.clone();
|
||||
out.kind = art.kind;
|
||||
if d.node(id).is_none() {
|
||||
*d.stored_node_mut(id).ok_or(EngineError::NoNode(id))? = out;
|
||||
return Ok(());
|
||||
}
|
||||
let (par, index, _) = d.position(id).ok_or(EngineError::NoNode(id))?;
|
||||
d.remove(id)?;
|
||||
d.insert(par, index, out)?;
|
||||
|
||||
+123
-31
@@ -672,13 +672,53 @@ fn takes_over(s: &Session, plugin: &Plugin) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Tests: runs once in the next `plugin.install` on this thread after its checks and before it
|
||||
/// installs, as another session changing the plug-ins in between would.
|
||||
pub(crate) static BEFORE_INSTALL: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
|
||||
/// Tests: runs once in the next `plugin.install` on this thread right after it reads the grant
|
||||
/// held for the id.
|
||||
pub(crate) static AFTER_GRANT_READ: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
|
||||
/// Tests: runs once in the next `plugin.install` on this thread after it installs and before it
|
||||
/// writes the store.
|
||||
pub(crate) static BEFORE_STORE: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
|
||||
/// Tests: runs once on this thread when [`hold_plugin_changes`] finds the lock held and waits.
|
||||
pub(crate) static WHILE_WAITING: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Held by `plugin.install` from its first read of the grant until the store holds what it
|
||||
/// installed, and throughout by `plugin.remove`, by loads of the stored plug-ins
|
||||
/// ([`Session::load_stored_plugins`]) and by loads of a plug-ins folder: these run one after the
|
||||
/// other across sessions.
|
||||
static PLUGIN_CHANGES: Mutex<()> = Mutex::new(());
|
||||
|
||||
/// Takes [`PLUGIN_CHANGES`], waiting while another session holds it.
|
||||
pub(crate) fn hold_plugin_changes() -> std::sync::MutexGuard<'static, ()> {
|
||||
match PLUGIN_CHANGES.try_lock() {
|
||||
Ok(held) => held,
|
||||
Err(std::sync::TryLockError::Poisoned(e)) => e.into_inner(),
|
||||
Err(std::sync::TryLockError::WouldBlock) => {
|
||||
#[cfg(test)]
|
||||
if let Some(waiting) = WHILE_WAITING.take() {
|
||||
waiting();
|
||||
}
|
||||
PLUGIN_CHANGES.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `plugin.install`: loads and checks the module, refuses `grant` and `allowHeavy` that neither an
|
||||
/// [`InstallApproval`] for this module nor the session allows, one that asks for a heavy budget
|
||||
/// unless `allowHeavy` says a person agreed, one that lists permissions no person has granted this
|
||||
/// very module unless `grant` lists them all, one that would take another module's place
|
||||
/// ([`takes_over`]) unless `replace` is true, and one whose SHA-256 isn't the `hash` given; records
|
||||
/// the grant with the module's hash, keeps it for the next start and installs it → its
|
||||
/// `plugin.list` entry. A module that lists no permissions ends any grant held for its id.
|
||||
/// ([`takes_over`]) unless `replace` is true, and one whose SHA-256 isn't the `hash` given. It then
|
||||
/// checks the plug-in installed under the id and its grant again while it records the grant with
|
||||
/// the module's hash and installs it ([`registry::install_checked`]), and only then keeps both for
|
||||
/// the next start → its `plugin.list` entry. A refused install changes neither the plug-in store
|
||||
/// nor the plug-ins and grants of the process. A module that lists no permissions ends any grant
|
||||
/// held for its id. A `plugin.remove` in another session waits until the install has written the
|
||||
/// store.
|
||||
fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "plugin.install";
|
||||
// One use: spent whatever this install does.
|
||||
@@ -696,21 +736,36 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
{
|
||||
return Err(bad(C, "the module doesn't have the SHA-256 `hash` gives: nothing was installed"));
|
||||
}
|
||||
if replace == Some(false) && registry::get(plugin.id()).is_some() {
|
||||
return Err(bad(C, format!("a plug-in with id {:?} is already installed", plugin.id())));
|
||||
// A removal in another session waits until the store holds what this install wrote.
|
||||
let _held = hold_plugin_changes();
|
||||
// The grant the checks below count on, the approval included. The install checks it again,
|
||||
// with the plug-in installed under the id, before anything is stored: another session may
|
||||
// change either in between.
|
||||
let seen_grant = registry::granted(plugin.id());
|
||||
#[cfg(test)]
|
||||
if let Some(between) = AFTER_GRANT_READ.take() {
|
||||
between();
|
||||
}
|
||||
// Another module under the id gets the settings and cache kept for it: whoever installs it asks
|
||||
// the user first.
|
||||
if replace != Some(true) && takes_over(s, &plugin) {
|
||||
let installed_already = || bad(C, format!("a plug-in with id {:?} is already installed", plugin.id()));
|
||||
let taken_over = || {
|
||||
let name = permissions::display_text(&plugin.manifest().name, permissions::MAX_SHOWN_NAME);
|
||||
return Err(bad(
|
||||
bad(
|
||||
C,
|
||||
format!(
|
||||
"“{name}” is another module than the plug-in with id {:?} and would get the settings and cache kept for it: install it with `replace: true` once the user agrees",
|
||||
plugin.id()
|
||||
),
|
||||
));
|
||||
)
|
||||
};
|
||||
if replace == Some(false) && registry::get(plugin.id()).is_some() {
|
||||
return Err(installed_already());
|
||||
}
|
||||
// Another module under the id gets the settings and cache kept for it: whoever installs it asks
|
||||
// the user first.
|
||||
if replace != Some(true) && takes_over(s, &plugin) {
|
||||
return Err(taken_over());
|
||||
}
|
||||
let (installed_already, taken_over) = (installed_already(), taken_over());
|
||||
// `grant` and `allowHeavy` say that a person agreed, and a request alone can't say that.
|
||||
let approval = approval.filter(|a| a.covers(&plugin));
|
||||
if !s.plugin_grants_from_requests && ((grant.is_some() && approval.is_none()) || (allow_heavy && !approval.is_some_and(|a| a.heavy))) {
|
||||
@@ -744,15 +799,55 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// this very module already covers all of them.
|
||||
let m = plugin.manifest();
|
||||
let wanted = m.permissions();
|
||||
if !s.plugin_approved(&plugin) && !grant.as_ref().is_some_and(|g| wanted.iter().all(|w| g.contains(w))) {
|
||||
let needs_approval = || {
|
||||
let name = permissions::display_text(&m.name, permissions::MAX_SHOWN_NAME);
|
||||
let asked = permissions::names(&wanted).join(", ");
|
||||
return Err(bad(
|
||||
bad(
|
||||
C,
|
||||
format!(
|
||||
"“{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants"
|
||||
),
|
||||
));
|
||||
)
|
||||
};
|
||||
let granted_here = grant.as_ref().is_some_and(|g| wanted.iter().all(|w| g.contains(w)));
|
||||
// Without a plug-in store, the grant read above approves the module or doesn't.
|
||||
let approved = match s.plugin_dir {
|
||||
None => !m.asks_permissions() || seen_grant.as_ref().is_some_and(|g| g.covers(&m.id, plugin.hash(), &wanted)),
|
||||
Some(_) => s.plugin_approved(&plugin),
|
||||
};
|
||||
if !approved && !granted_here {
|
||||
return Err(needs_approval());
|
||||
}
|
||||
let needs_approval = needs_approval();
|
||||
let (id, hash, asks) = (m.id.clone(), plugin.hash().to_string(), m.asks_permissions());
|
||||
let g = Grant { id: id.clone(), hash: hash.clone(), permissions: wanted };
|
||||
let update = if asks { registry::GrantUpdate::Record(GrantToken::after_engine_approval(g.clone())) } else { registry::GrantUpdate::Revoke };
|
||||
// Another module installed under the id since the checks above takes the place they found free,
|
||||
// or held by these bytes. A grant that changed since no longer approves what they approved,
|
||||
// unless `grant` approves this module by itself or the new grant covers it.
|
||||
let check = |installed: Option<&Plugin>, held: Option<&Grant>| {
|
||||
if let Some(installed) = installed {
|
||||
match replace {
|
||||
Some(false) => return Err(installed_already),
|
||||
None if installed.hash() != hash => return Err(taken_over),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if asks && !granted_here && held != seen_grant.as_ref() && !held.is_some_and(|h| h.covers(&id, &hash, &g.permissions)) {
|
||||
return Err(needs_approval);
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
#[cfg(test)]
|
||||
if let Some(between) = BEFORE_INSTALL.take() {
|
||||
between();
|
||||
}
|
||||
// The plug-in gets the settings and cache kept for its id. A module without permissions takes
|
||||
// the id over, so nothing the user approved for the id applies any more.
|
||||
let installed = registry::install_checked(plugin, update, check, || s.attach_plugin_storage(&id), err)?;
|
||||
#[cfg(test)]
|
||||
if let Some(between) = BEFORE_STORE.take() {
|
||||
between();
|
||||
}
|
||||
// Installed plug-ins stay installed after a restart (#2541). The module is written first and its
|
||||
// grant only once it is there; when the grant can't be written, the store gets the module it
|
||||
@@ -760,18 +855,14 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// which the grant doesn't cover. A write that reports a failure may still have put the old
|
||||
// module back, so the store is read again to tell which module it holds. A stored module that
|
||||
// can't be read back isn't replaced by one that needs a grant.
|
||||
let previous = s.stored_plugin_bytes(plugin.id());
|
||||
let mut stored = (previous.is_ok() || !m.asks_permissions()) && s.store_plugin(plugin.id(), &bytes);
|
||||
let holds_new = |s: &Session| s.stored_plugin_bytes(plugin.id()).is_ok_and(|held| held.as_deref() == Some(&bytes[..]));
|
||||
if m.asks_permissions() {
|
||||
let g = Grant { id: m.id.clone(), hash: plugin.hash().to_string(), permissions: wanted };
|
||||
registry::grant(GrantToken::after_engine_approval(g.clone()));
|
||||
if stored && !s.store_grant(&m.id, Some(g)) {
|
||||
stored = !s.put_back_plugin(plugin.id(), previous.ok().flatten().as_deref()) && holds_new(s);
|
||||
let previous = s.stored_plugin_bytes(&id);
|
||||
let mut stored = (previous.is_ok() || !asks) && s.store_plugin(&id, &bytes);
|
||||
let holds_new = |s: &Session| s.stored_plugin_bytes(&id).is_ok_and(|held| held.as_deref() == Some(&bytes[..]));
|
||||
if asks {
|
||||
if stored && !s.store_grant(&id, Some(g)) {
|
||||
stored = !s.put_back_plugin(&id, previous.ok().flatten().as_deref()) && holds_new(s);
|
||||
}
|
||||
} else {
|
||||
// This module takes the id over, so nothing the user approved for the id applies any more.
|
||||
registry::revoke(&m.id);
|
||||
// When the write failed, the old stored module stays in the folder and needs its grant at
|
||||
// the next launch. A grant that can't be removed still approves the old bytes, so the store
|
||||
// gets the module it held back. When that module can't be read or written back, or there
|
||||
@@ -780,23 +871,21 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// approves nothing, and the new module stays; one that can't be opened or read may approve
|
||||
// the old bytes once it reads again.
|
||||
let writes = s.grant_writes();
|
||||
if stored && !s.store_grant(&m.id, None) && s.holds_plugin_grant(&m.id) {
|
||||
let back = previous.as_ref().is_ok_and(|held| s.put_back_plugin(plugin.id(), held.as_deref()));
|
||||
if stored && !s.store_grant(&id, None) && s.holds_plugin_grant(&id) {
|
||||
let back = previous.as_ref().is_ok_and(|held| s.put_back_plugin(&id, held.as_deref()));
|
||||
stored = !back && holds_new(s);
|
||||
if !back || matches!(previous, Ok(None)) {
|
||||
s.ignore_stored_grant(&m.id, writes);
|
||||
s.ignore_stored_grant(&id, writes);
|
||||
}
|
||||
}
|
||||
}
|
||||
// It gets the settings and cache kept for its id.
|
||||
s.attach_plugin_storage(plugin.id());
|
||||
// Installing a disabled plug-in again (an updated version) turns it on for the next launch too,
|
||||
// also when it is disabled by its stored file alone (it stopped a launch while loading). When
|
||||
// the new version could not replace the stored file, the old one stays disabled.
|
||||
let file = s.stored_plugin_file(plugin.id());
|
||||
let file = s.stored_plugin_file(&id);
|
||||
let mut changed = false;
|
||||
if file.is_none() || stored {
|
||||
changed = safe_mode::set_enabled(&safe_mode::Item::of(&plugin), true);
|
||||
changed = safe_mode::set_enabled(&safe_mode::Item::of(&installed), true);
|
||||
if let Some(file) = file {
|
||||
changed |= safe_mode::set_enabled(&safe_mode::Item::file(file), true);
|
||||
}
|
||||
@@ -804,7 +893,6 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if changed {
|
||||
s.store_disabled_plugins();
|
||||
}
|
||||
let installed = registry::install(plugin).map_err(err)?;
|
||||
let mut v = describe_installed(&installed);
|
||||
if !unknown.is_empty() {
|
||||
v["unknownCommands"] = json!(unknown);
|
||||
@@ -904,6 +992,8 @@ fn load_folder(s: &Session, folder: &str) -> Value {
|
||||
None if crate::file_access::current().is_none() => Ok(()),
|
||||
None => Err(format!("automation path rejected: {} isn't valid text", f.display())),
|
||||
};
|
||||
// A `plugin.install` in another session finishes writing the store first.
|
||||
let _held = hold_plugin_changes();
|
||||
match registry::load_folder_where(std::path::Path::new(folder), allow, s.plugin_folder_approver()) {
|
||||
Ok(r) => {
|
||||
for id in &r.loaded {
|
||||
@@ -1074,6 +1164,8 @@ fn info(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = str_param(p, "id").ok_or_else(|| bad("plugin.remove", "missing `id`"))?;
|
||||
// An install in another session finishes its store writes first.
|
||||
let _held = hold_plugin_changes();
|
||||
let installed = registry::get(id).is_some();
|
||||
// Settings and cache the store keeps for an id that isn't installed are deleted too.
|
||||
let stored = !installed && vectorcraft_plugins::manifest::valid_id(id) && s.has_plugin_storage(id);
|
||||
|
||||
@@ -413,6 +413,7 @@ pub(crate) fn transaction(s: &mut Session, label: &str, f: impl FnOnce(&mut Sess
|
||||
st.interaction = None;
|
||||
}
|
||||
saved.restore(s);
|
||||
s.sync_front_profiles();
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -314,6 +314,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"object.move",
|
||||
"object.nudge",
|
||||
"object.objectsOnPath.attach",
|
||||
"object.objectsOnPath.detach",
|
||||
"object.objectsOnPath.expand",
|
||||
"object.objectsOnPath.moveMember",
|
||||
"object.objectsOnPath.options",
|
||||
@@ -478,6 +479,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"recolor.pickTheme",
|
||||
"recolor.randomize",
|
||||
"recolor.reduce",
|
||||
"recolor.weigh",
|
||||
"select.add",
|
||||
"select.all",
|
||||
"select.allOnArtboard",
|
||||
|
||||
@@ -454,10 +454,10 @@ 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`), 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"];
|
||||
/// (`object.pathfinder.options`), the Snap to Glyph options (`view.snapToGlyph.options`) and the
|
||||
/// Pixel Snapping Options (`view.snapToPixel.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", "pixelSnap"];
|
||||
|
||||
/// Validate a value for preference group `key` against `current`.
|
||||
fn validate_group(key: &str, current: &Value, v: &Value) -> std::result::Result<Value, String> {
|
||||
@@ -477,6 +477,10 @@ fn validate_group(key: &str, current: &Value, v: &Value) -> std::result::Result<
|
||||
let cur: vectorcraft_tools::GlyphSnap = serde_json::from_value(current.clone()).unwrap_or_default();
|
||||
cur.merged(v).map(|o| json!(o))
|
||||
}
|
||||
"pixelSnap" => {
|
||||
let cur: vectorcraft_tools::PixelSnap = 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()) {
|
||||
@@ -788,7 +792,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Preferences",
|
||||
[],
|
||||
None,
|
||||
"{path?} write the preferences as a JSON file {format: \"vectorcraft-preferences\", version: 1, prefs: {key: value, …}}: every preference prefs.list lists and the eyedropper, perspectiveWidget, pathfinder and glyphSnap groups, without the folder preferences fontsFolder, pluginsFolder, recoveryFolder and templatesFolder and without saved presets; a file over 1 MB, which prefs.import would refuse, is an error and is not written → {path, count}; without path → {data: the file's text, count}",
|
||||
"{path?} write the preferences as a JSON file {format: \"vectorcraft-preferences\", version: 1, prefs: {key: value, …}}: every preference prefs.list lists and the eyedropper, perspectiveWidget, pathfinder, glyphSnap and pixelSnap groups, without the folder preferences fontsFolder, pluginsFolder, recoveryFolder and templatesFolder and without saved presets; a file over 1 MB, which prefs.import would refuse, is an error and is not written → {path, count}; without path → {data: the file's text, count}",
|
||||
always,
|
||||
export
|
||||
),
|
||||
|
||||
@@ -7,7 +7,9 @@
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::recolor::{ColorKey, GlobalAdjust, Method, Preserve, Rng, RowMap, cluster, same_ink};
|
||||
use vectorcraft_color::recolor::{
|
||||
ColorKey, GlobalAdjust, Method, Preserve, Rng, RowMap, WeighUnit, cluster, row_shares, same_ink, weigh as weigh_rows,
|
||||
};
|
||||
use vectorcraft_color::{Color, Paint, Swatch};
|
||||
use vectorcraft_doc::swatches::{node_colors, node_paints, override_paints};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
@@ -63,6 +65,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
pick_theme
|
||||
),
|
||||
cmd!(
|
||||
query "recolor.weigh",
|
||||
"Prominent Colors",
|
||||
[],
|
||||
None,
|
||||
"{map: rows [{from, to, …}] or {current: new} as recolor.apply, weights?: [numbers ≥ 0, one per row; an excluded row's is ignored, and at least one other must be above 0], ids?: as recolor.colors} → {map: the rows as given, each with its current colours (from) moved as below, shares: [one per row: its percent of the uses (recolor.colors' count) of the current colours of the rows that aren't excluded; 0 for an excluded row]} for Recolor Artwork's Prominent Colors (VectorCraft's own rule): without weights the rows stay as they are. With weights, current colours move one at a time between the rows that aren't excluded and have a new colour (to), while a move brings each row's share of the uses nearer its share of the weights, first the colour nearest in Lab to the first colour of the row it goes to compared with the row it leaves; a row's first colour stays in it, the tints of one global swatch in a row move together, a colour that another row with a new colour lists first stays where it is, the other rows with a new colour drop their entries for a colour that moves, and a use counts for the row recolor.apply recolors it with (rows with a new colour first, an exact colour before a hex one, the first row that lists it), else for the first other row that isn't excluded and lists it. The colours that can move are compared with the rows at most 50,000,000 times in all, and when they times the rows that aren't excluded pass that, none move. Changes nothing",
|
||||
has_doc,
|
||||
weigh
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1062,6 +1073,181 @@ fn colors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "colors": v }))
|
||||
}
|
||||
|
||||
/// `recolor.weigh`'s rows as given, each with `from` as a list (a `{current: new}` map gives a
|
||||
/// row per entry). The rows have already been read by [`parse_rows`].
|
||||
fn given_rows(p: &Value) -> Vec<Value> {
|
||||
match p.get("map") {
|
||||
Some(Value::Array(rows)) => rows
|
||||
.iter()
|
||||
.map(|r| {
|
||||
let mut r = r.clone();
|
||||
if let Some(f) = r.get("from").filter(|f| !f.is_array()).cloned() {
|
||||
r["from"] = json!([f]);
|
||||
}
|
||||
r
|
||||
})
|
||||
.collect(),
|
||||
Some(Value::Object(m)) => m.iter().map(|(k, v)| json!({"from": [k], "to": v})).collect(),
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
fn weigh(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "recolor.weigh";
|
||||
let rows = parse_rows(p, C)?;
|
||||
let weights = match p.get("weights") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(Value::Array(a)) if a.len() == rows.len() => Some(
|
||||
a.iter()
|
||||
.map(|v| {
|
||||
v.as_f64()
|
||||
.filter(|x| x.is_finite() && *x >= 0.0)
|
||||
.ok_or_else(|| bad(C, format!("each weight must be a number of 0 or more (got {v})")))
|
||||
})
|
||||
.collect::<Result<Vec<f64>>>()?,
|
||||
),
|
||||
Some(v) => return Err(bad(C, format!("`weights` must be a list of {} numbers, one per row (got {v})", rows.len()))),
|
||||
};
|
||||
let active: Vec<usize> = (0..rows.len()).filter(|&i| !rows[i].exclude).collect();
|
||||
if let Some(w) = &weights
|
||||
&& !active.is_empty()
|
||||
&& !active.iter().any(|&i| w[i] > 0.0)
|
||||
{
|
||||
return Err(bad(C, "at least one row that isn't excluded needs a weight above 0"));
|
||||
}
|
||||
let (ids, only) = scope_ids(s, p, C)?;
|
||||
let st = s.doc()?;
|
||||
let mut used: Vec<Option<Used>> = used_colors(&st.doc, &ids, only.as_ref()).into_iter().map(Some).collect();
|
||||
let mut by_key: HashMap<ColorKey, usize> = HashMap::new();
|
||||
let mut by_hex: HashMap<String, Vec<usize>> = HashMap::new();
|
||||
for (i, u) in used.iter().enumerate().filter_map(|(i, u)| Some((i, u.as_ref()?))) {
|
||||
by_key.insert(ColorKey::of(&u.color), i);
|
||||
by_hex.entry(u.color.to_hex()).or_default().push(i);
|
||||
}
|
||||
// Each current colour's uses and global swatch. A use counts where recolor.apply recolors it:
|
||||
// rows with a new colour first, exact colours before hex colours, the first row that lists it;
|
||||
// then the other rows that aren't excluded, in the same way. `owner` holds the row and entry that took each colour,
|
||||
// and `shadows` the entries of rows with a new colour whose colours other entries took.
|
||||
let mut owner: Vec<Option<(usize, usize)>> = vec![None; used.len()];
|
||||
let mut shadows: Vec<(usize, usize, Vec<usize>)> = vec![];
|
||||
let mut found: Vec<Vec<(usize, Option<String>)>> = rows.iter().map(|r| vec![(0, None); r.from.len()]).collect();
|
||||
for recolors in [true, false] {
|
||||
for hex in [false, true] {
|
||||
for (r, row) in rows.iter().enumerate().filter(|(_, r)| !r.exclude && r.new_color().is_some() == recolors) {
|
||||
for (e, m) in row.from.iter().enumerate().filter(|(_, m)| matches!(m, Match::Hex(_)) == hex) {
|
||||
let hits: Vec<usize> = match m {
|
||||
Match::Key(k) => by_key.get(k).copied().into_iter().collect(),
|
||||
Match::Hex(h) => by_hex.get(h).cloned().unwrap_or_default(),
|
||||
};
|
||||
let (mut uses, mut link, mut took, mut taken) = (0, None, false, vec![]);
|
||||
for i in hits {
|
||||
match used[i].take() {
|
||||
Some(u) => {
|
||||
uses += u.count;
|
||||
link = link.or(u.swatch);
|
||||
took = true;
|
||||
owner[i] = Some((r, e));
|
||||
}
|
||||
None => taken.push(i),
|
||||
}
|
||||
}
|
||||
found[r][e] = (uses, link);
|
||||
if recolors && !took && !taken.is_empty() {
|
||||
shadows.push((r, e, taken));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// The units that move: in each row that isn't excluded, the colours linked to one global
|
||||
// swatch go together, each other colour on its own, and the unit of the first colour stays.
|
||||
let (mut units, mut members): (Vec<WeighUnit>, Vec<(usize, Vec<usize>)>) = (vec![], vec![]);
|
||||
let mut unit_of: HashMap<(usize, usize), usize> = HashMap::new();
|
||||
for (n, &r) in active.iter().enumerate() {
|
||||
let mut groups: Vec<(Option<&String>, Vec<usize>, usize)> = vec![];
|
||||
let mut by_link: HashMap<&String, usize> = HashMap::new();
|
||||
for (e, (uses, link)) in found[r].iter().enumerate() {
|
||||
let g = match link {
|
||||
Some(l) => *by_link.entry(l).or_insert_with(|| {
|
||||
groups.push((Some(l), vec![], 0));
|
||||
groups.len() - 1
|
||||
}),
|
||||
None => {
|
||||
groups.push((None, vec![], 0));
|
||||
groups.len() - 1
|
||||
}
|
||||
};
|
||||
groups[g].1.push(e);
|
||||
groups[g].2 += uses;
|
||||
}
|
||||
for (k, (_, entries, uses)) in groups.into_iter().enumerate() {
|
||||
for &e in &entries {
|
||||
unit_of.insert((r, e), units.len());
|
||||
}
|
||||
units.push(WeighUnit { color: rows[r].from[entries[0]].color(), uses: uses as f64, row: n, fixed: k == 0 });
|
||||
members.push((r, entries));
|
||||
}
|
||||
}
|
||||
// recolor.apply matches a colour to the first row with a new colour that lists it. A colour
|
||||
// that another such row's first colour also lists stays where it is; another row's other
|
||||
// entries for a colour that moves are dropped from that row below.
|
||||
let owners = |taken: &[usize]| -> Vec<usize> { taken.iter().filter_map(|&i| unit_of.get(&owner[i]?).copied()).collect() };
|
||||
for (_, _, taken) in shadows.iter().filter(|(_, e, _)| *e == 0) {
|
||||
for u in owners(taken) {
|
||||
units[u].fixed = true;
|
||||
}
|
||||
}
|
||||
if let Some(w) = &weights {
|
||||
// Only rows with a new colour recolor what they hold, so only they give and take colours.
|
||||
let movers: Vec<usize> = (0..active.len()).filter(|&n| rows[active[n]].new_color().is_some()).collect();
|
||||
let anchors: Vec<Color> =
|
||||
movers.iter().map(|&n| rows[active[n]].from.first().map(Match::color).or(rows[active[n]].to).unwrap_or_default()).collect();
|
||||
let mut mover_of = vec![None; active.len()];
|
||||
for (m, &n) in movers.iter().enumerate() {
|
||||
mover_of[n] = Some(m);
|
||||
}
|
||||
let at: Vec<Option<usize>> = units.iter().map(|u| mover_of[u.row]).collect();
|
||||
let sub: Vec<WeighUnit> = units.iter().zip(&at).filter_map(|(u, m)| Some(WeighUnit { row: (*m)?, ..*u })).collect();
|
||||
let to = weigh_rows(&sub, &anchors, &movers.iter().map(|&n| w[active[n]]).collect::<Vec<_>>());
|
||||
for ((u, _), m) in units.iter_mut().zip(&at).filter(|(_, m)| m.is_some()).zip(to) {
|
||||
u.row = movers[m];
|
||||
}
|
||||
}
|
||||
let mut out = given_rows(p);
|
||||
if weights.is_some() {
|
||||
// Each row's colours: those that stayed, in their order, then those that came to it.
|
||||
// A row's entry for a colour that moved to another row would take it back, so it goes.
|
||||
let moved = |u: usize| active[units[u].row] != members[u].0;
|
||||
let dropped: std::collections::HashSet<(usize, usize)> =
|
||||
shadows.iter().filter(|(_, e, taken)| *e != 0 && owners(taken).into_iter().any(moved)).map(|(r, e, _)| (*r, *e)).collect();
|
||||
let old: Vec<Vec<Value>> = out.iter().map(|r| r["from"].as_array().cloned().unwrap_or_default()).collect();
|
||||
let mut stayed: Vec<Vec<usize>> = active.iter().map(|_| vec![]).collect();
|
||||
let mut came: Vec<Vec<Value>> = active.iter().map(|_| vec![]).collect();
|
||||
for (u, (r, entries)) in units.iter().zip(&members) {
|
||||
let kept = entries.iter().copied().filter(|&e| !dropped.contains(&(*r, e)));
|
||||
if active[u.row] == *r {
|
||||
stayed[u.row].extend(kept);
|
||||
} else {
|
||||
came[u.row].extend(kept.filter_map(|e| old[*r].get(e).cloned()));
|
||||
}
|
||||
}
|
||||
for (n, &r) in active.iter().enumerate() {
|
||||
stayed[n].sort_unstable();
|
||||
let mut from: Vec<Value> = stayed[n].iter().filter_map(|&e| old[r].get(e).cloned()).collect();
|
||||
from.append(&mut came[n]);
|
||||
if let Some(row) = out.get_mut(r) {
|
||||
row["from"] = Value::Array(from);
|
||||
}
|
||||
}
|
||||
}
|
||||
let shares = row_shares(&units, active.len());
|
||||
let mut all = vec![0.0; rows.len()];
|
||||
for (n, &r) in active.iter().enumerate() {
|
||||
all[r] = shares[n];
|
||||
}
|
||||
Ok(json!({"map": out, "shares": all}))
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
//! paint shows instead of the character colour under it.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Paint;
|
||||
@@ -31,7 +31,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Apply Graphic Style",
|
||||
["Window", "Graphic Styles"],
|
||||
None,
|
||||
"{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (with `add`: of the kinds of row the style shows) and, without `add`, the object's opacity and blend mode (exceptions: docs/mcp.md). With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}",
|
||||
"{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (with `add`: of the kinds of row the style shows) and, without `add`, the object's opacity and blend mode (exceptions: docs/mcp.md). With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}",
|
||||
has_doc,
|
||||
style_apply
|
||||
),
|
||||
@@ -40,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New Graphic Style",
|
||||
["Window", "Graphic Styles"],
|
||||
None,
|
||||
"{name?, id?} a style from object `id` or the first selected object: its appearance, opacity, blend mode, isolate and knockout (a group without fills or strokes of its own lends its topmost object's, type its characters'; placed gradients are kept relative to its bounds); links the object. Names are made unique → {name}",
|
||||
"{name?, id?} a style from object `id` or the first selected object: its appearance, opacity, blend mode, isolate and knockout (a group without fills or strokes of its own lends its topmost object's, type its characters'; a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own stands for the topmost path directly in it; placed gradients are kept relative to its bounds); links the object. Names are made unique → {name}",
|
||||
has_doc,
|
||||
style_new
|
||||
),
|
||||
@@ -68,7 +68,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Redefine Graphic Style",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{name?, id?} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object; the objects still linked to it update, and that object becomes linked. On a linked path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md) → {name}",
|
||||
"{name?, id?} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object (a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own: the topmost path directly in it); the objects still linked to it update, and that object becomes linked. A linked graph series group passes the style to the paths directly in it, other than the source and paths linked to the style whose look was edited, and is left cleared (as appearance.clear) and unlinked. On a linked path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md) → {name}",
|
||||
has_doc,
|
||||
style_redefine
|
||||
),
|
||||
@@ -77,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Break Link to Graphic Style",
|
||||
["Window", "Graphic Styles"],
|
||||
None,
|
||||
"{ids?|id?, target?: \"object\"|\"contents\"} unlink the objects (default: the selection) from their graphic style; they keep their look",
|
||||
"{ids?|id?, target?: \"object\"|\"contents\"} unlink the objects (default: the selection) from their graphic style; they keep their look. A graph series group's id stands for the group and the paths directly in it",
|
||||
has_doc,
|
||||
style_break_link
|
||||
),
|
||||
@@ -307,10 +307,11 @@ fn source<'a>(s: &'a Session, p: &Value, cmd: &str) -> Result<(NodeId, &'a Node)
|
||||
|
||||
impl Session {
|
||||
/// The graphic style of the first selected object: the one it was last linked to, and whether
|
||||
/// it is still linked (still has that style's look).
|
||||
/// it is still linked (still has that style's look). A graph series group that holds nothing of its own stands
|
||||
/// for the topmost path directly inside it, which a style applied to the group links.
|
||||
pub fn selection_graphic_style(&self) -> Option<(&GraphicStyle, bool)> {
|
||||
let st = self.active()?;
|
||||
let n = st.doc.node(*st.selection.subjects().first()?)?;
|
||||
let n = super::appearance::look_holder(&st.doc, st.doc.node(*st.selection.subjects().first()?)?);
|
||||
let g = st.doc.graphic_style_by_id(n.extras().graphic_style?)?;
|
||||
Some((g, in_sync(n, g)))
|
||||
}
|
||||
@@ -331,7 +332,11 @@ fn style_apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let i = style_index(&s.doc()?.doc, name)?;
|
||||
let add = bool_or(p, "add", false);
|
||||
let chars = s.prefs.override_char_color;
|
||||
let ids = super::appearance::appearance_targets(s, p)?;
|
||||
let own = super::appearance::appearance_targets(s, p)?;
|
||||
let ids = super::appearance::rowless_series_marks(&s.doc()?.doc, &own);
|
||||
// The series groups their paths stand for: a style that replaces the appearance clears what they hold themselves,
|
||||
// and a style added on top unlinks them.
|
||||
let groups = super::appearance::stood_for(&own, &ids);
|
||||
if ids.is_empty() {
|
||||
if p.get("ids").is_some() || p.get("id").is_some() {
|
||||
return Err(bad("graphicStyle.apply", "no such objects"));
|
||||
@@ -353,6 +358,8 @@ fn style_apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
n.extras_mut().graphic_style = None;
|
||||
}
|
||||
}
|
||||
// The series groups their paths stand for are unlinked with them.
|
||||
set_link(d, &groups, None);
|
||||
// The graph stores the rows of the kinds the style shows, now on top of each stack.
|
||||
let shows = |kind: bool| g.appearance.items.iter().any(|it| it.is_fill() == kind && it.visible());
|
||||
let kinds = (shows(true), shows(false));
|
||||
@@ -364,6 +371,7 @@ fn style_apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for id in &ids {
|
||||
apply_style(d, *id, &g, &mut shared, chars);
|
||||
}
|
||||
super::appearance::clear_stood_for(d, &groups);
|
||||
super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false, true);
|
||||
}
|
||||
Ok(())
|
||||
@@ -372,8 +380,11 @@ fn style_apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn style_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (src, n) = source(s, p, "graphicStyle.new")?;
|
||||
let (_, n) = source(s, p, "graphicStyle.new")?;
|
||||
let d = &s.doc()?.doc;
|
||||
// A series group that holds nothing of its own shows the look of its paths: the style is made from the topmost.
|
||||
let n = super::appearance::look_holder(d, n);
|
||||
let src = n.id;
|
||||
let name = match str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()) {
|
||||
Some(n) => unique_name(n, |x| d.graphic_style(x).is_some()),
|
||||
None => d.new_graphic_style_name(),
|
||||
@@ -459,6 +470,9 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "graphicStyle.redefine";
|
||||
let (src, n) = source(s, p, cmd)?;
|
||||
let d = &s.doc()?.doc;
|
||||
// A series group that holds nothing of its own is redefined from the topmost of its paths, which a style links.
|
||||
let n = super::appearance::look_holder(d, n);
|
||||
let src = if n.id == src { src } else { n.id };
|
||||
let i = match str_param(p, "name") {
|
||||
Some(name) => style_index(d, name)?,
|
||||
None => n
|
||||
@@ -480,12 +494,18 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let linked = objects_where(d, |n| n.extras().graphic_style == Some(id) && n.id != src);
|
||||
let (follow, edited): (Vec<NodeId>, Vec<NodeId>) = linked.into_iter().partition(|nid| d.node(*nid).is_some_and(|n| in_sync(n, &old)));
|
||||
set_link(d, &edited, None);
|
||||
// A linked graph series group passes the style to the paths directly inside it, so the graph stores it, and
|
||||
// goes back to the empty appearance the graph draws it with. The source and the edited paths keep their look.
|
||||
let mut follow_marks = super::graph::series_group_marks(d, &follow);
|
||||
let edited: HashSet<NodeId> = edited.into_iter().collect();
|
||||
follow_marks.retain(|nid| *nid != src && !edited.contains(nid));
|
||||
super::appearance::clear_stood_for(d, &super::appearance::stood_for(&follow, &follow_marks));
|
||||
let g = d.graphic_styles[i].clone();
|
||||
let mut shared = None;
|
||||
for nid in &follow {
|
||||
for nid in &follow_marks {
|
||||
apply_style(d, *nid, &g, &mut shared, chars);
|
||||
}
|
||||
super::appearance::capture_series_writes(&before, d, &follow, (true, true), (true, true), false, true);
|
||||
super::appearance::capture_series_writes(&before, d, &follow_marks, (true, true), (true, true), false, true);
|
||||
set_link(d, &[src], Some(id));
|
||||
Ok(())
|
||||
})?;
|
||||
@@ -493,7 +513,7 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn style_break_link(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = super::appearance::appearance_targets(s, p)?;
|
||||
let ids = super::appearance::whole_targets(s, p)?;
|
||||
s.edit("Break Link to Graphic Style", |d, _| {
|
||||
set_link(d, &ids, None);
|
||||
Ok(())
|
||||
|
||||
Loaded 100 of 422 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user