Merge main into blend redraw bounds fix

This commit is contained in:
yoriswind committed 2026-11-13 19:10:12 -08:00
commit f77654591b
804 files changed
+100912 -7425

No files matched your search

+22 -22
View File
@@ -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
+1 -43
View File
@@ -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
+1 -1
View File
@@ -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
+4 -1
View File
@@ -6341,7 +6341,6 @@ dependencies = [
"raw-window-handle",
"rfd",
"serde_json",
"smithay-clipboard",
"socket2",
"tempfile",
"vectorcraft-engine",
@@ -6476,6 +6475,8 @@ dependencies = [
"vectorcraft-plugins",
"vectorcraft-text",
"vectorcraft-three-d",
"vectorcraft-trace",
"wat",
]
[[package]]
@@ -6664,6 +6665,7 @@ dependencies = [
"serde",
"serde_json",
"sha2",
"siphasher",
"skrifa 0.47.0",
"smallvec",
"thiserror 2.0.21",
@@ -6854,6 +6856,7 @@ dependencies = [
"serde",
"serde_json",
"toml",
"vectorcraft-apischema",
"vectorcraft-brush",
"vectorcraft-cad",
"vectorcraft-color",
+2
View File
@@ -123,6 +123,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-05: Window › Toolbars › Keep Tools Beside the Canvas, off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge, and the canvas's left edge then also docks a floating Tools panel (`window.toolsBesideCanvas`, #5395). Workspaces keep the setting; workspaces saved without it keep Tools at the window's edge. An optional VectorCraft layout choice; headline numbers unchanged.
- 2026-11-12: Stencil Bridges in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): strips of a set width are cut out of the selected art so that every island of a stencil cut from it (the inside of an O, a hole in a shape) stays attached to the sheet, by the shortest crossings first, vertical, horizontal or the shortest among 12 directions 15° apart, with up to 16 bridges per island; type is measured by its glyph outlines and stays type, and the original goes to a hidden layer or is replaced. One undo step (`addon.cutting.bridges`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-13: Banner Hems and Grommets in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): on the chosen sides of the selected art's bounds, or of each artboard, a hem line at a set depth inside the edge and grommet marks (a circle with a cross) at a set inset, one at each end of a side and the rest spread evenly at most a set spacing apart, stroked in a chosen swatch; a dialog with Preview, one undo step (`addon.cutting.banner`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged.
- 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged.
- 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged.
@@ -141,6 +142,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged.
- 2026-10-31: Arrange Tools, a built-in add-on (Object › Plug-ins › Arrange Tools): Arrange in Grid lays the selected objects out in rows and columns, a row or a column with gaps, from the selection's top-left or centred on the artboard; Swap Objects swaps two objects' places (and, with Swap Objects and Sizes, their sizes); Replace with Top Object puts a copy of the topmost selected object in place of each of the others, kept, stretched or fitted in proportion; Set Size of Each gives every selected object an exact width and/or height about a reference point; Zoom to Selection fits the view to the selection. Each is one undo step with a previewed dialog where it has options. A VectorCraft addition: headline numbers unchanged.
- 2026-11-11: Window › Swatch Libraries › Gradients › Organic Fades: fifteen soft fades (ten linear, five radial) through three to five unevenly spaced stops with off-center midpoints, mixed with the Perceptual method, that thin out to transparent at the end of a linear one and at the edge of a radial one; they also list in the Swatches panel's library menu, `swatch.library.list` and the Gradient panel's Presets.
- 2026-11-13: Gradient panel › Method: Hue Clockwise and Hue Counterclockwise mix a linear, radial, conic or diamond gradient's colors around the hue wheel in one direction, so red to blue passes through magenta one way and through yellow and green the other (`paint.editGradient` `method`: `hue-clockwise`, `hue-counterclockwise`); SVG and PDF exports write such a gradient as an image.
- 2026-11-11: Window › Swatch Libraries › Gradients › Holographic: seven foils (opaque linear gradients of six narrow pastel and pearl bands with off-center midpoints) and seven glows (radial gradients from a bright center out to a clear edge), mixed with the Perceptual method; they also list in the Swatches panel's library menu, `swatch.library.list` and the Gradient panel's Presets.
- 2026-10-30: Gradient panel presets: a Presets menu applies one of the built-in gradient libraries' presets (grouped by theme) or a saved one to the gradient behind the active proxy, keeping its placement, as one undo step; the panel menu saves the current gradient as a preset, kept with the preferences, and deletes saved ones (`gradient.presets.list/apply/save/delete`).
- 2026-10-23: Pathfinder › Trap: the Pathfinder panel's Trap… and Effect › Pathfinder › Trap… add a thin overprinting strip of the lighter colour inside the darker one where two solid colours meet, so misregistered plates leave no gap ([trapping](https://helpx.adobe.com/illustrator/using/trapping.html)), with Thickness, Height/Width, Tint Reduction, Traps with Process Color and Reverse Traps. Illustrator effects 49/50 (SVG Filters remains); Live vector effects hours 6–10 → 4–8; headline numbers unchanged.
+11 -3
View File
@@ -418,10 +418,18 @@ fn convert(args: &[String]) -> Result<(), String> {
// Save as Template writes every artboard, with the .ai options.
("file.saveAsTemplate", json!({"path": output, "format": "ait", "outlineText": outline_text, "acknowledgeLoss": replace_lossy}))
} else {
// A conversion keeps hidden layers and objects, written hidden, where the format can (SVG,
// PSD).
let params = json!({"path": output, "artboard": artboard, "range": range, "outlineText": outline_text, "hiddenLayers": true, "acknowledgeLoss": replace_lossy});
let params = json!({"path": output, "artboard": artboard, "range": range, "acknowledgeLoss": replace_lossy});
let mut params = with_pixel_scale(params, &output, scale, ppi);
// An option the format doesn't read comes back in the warnings, so each goes out only
// when it was asked for: `outlineText` with --outline-text, and `hiddenLayers` to the
// formats that have it (SVG, PSD), where a conversion keeps hidden layers and objects,
// written hidden.
if outline_text {
params["outlineText"] = json!(true);
}
if vectorcraft_engine::cmd::fileio::writable_format(None, Some(&output)).is_ok_and(|f| f.options.iter().any(|o| o.name == "hiddenLayers")) {
params["hiddenLayers"] = json!(true);
}
if let Some(decimals) = decimals {
params["decimals"] = json!(decimals);
}
+21
View File
@@ -177,6 +177,27 @@ fn convert_reports_import_warnings() {
assert!(w.iter().any(|w| w.as_str().unwrap().contains("nowhere-to-be-found.png")), "{out}");
}
/// A conversion sends each format only the options it reads, so its warnings name an unused
/// option only when the command line gave one: `--outline-text` for a format without it.
#[test]
fn convert_warns_about_an_unused_option_only_when_one_was_given() {
let svg = tmp("unused-option.svg");
std::fs::write(&svg, r#"<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40"><rect width="20" height="10"/></svg>"#).unwrap();
let unused = |out: &Value| -> Vec<String> {
let w = out["warnings"].as_array().unwrap_or_else(|| panic!("{out}"));
w.iter().filter_map(Value::as_str).filter(|w| w.contains("was not used")).map(str::to_string).collect()
};
for ext in ["png", "jpg", "pdf", "ai", "eps", "psd", "dxf", "svg", "txt", "vectorcraft", "vctemplate"] {
let path = tmp(&format!("unused-option.{ext}"));
let out: Value = serde_json::from_str(ok(&["convert", &svg, &path]).trim()).unwrap();
assert!(unused(&out).is_empty(), "{ext}: {out}");
}
let out: Value = serde_json::from_str(ok(&["convert", &svg, &tmp("unused-option-outlined.svg"), "--outline-text"]).trim()).unwrap();
assert!(unused(&out).is_empty(), "{out}");
let out: Value = serde_json::from_str(ok(&["convert", &svg, &tmp("unused-option-outlined.png"), "--outline-text"]).trim()).unwrap();
assert_eq!(unused(&out), ["`outlineText` was not used: PNG files don't read it"], "{out}");
}
#[test]
fn convert_writes_legacy_ai_with_its_options() {
// Two artboards, a shown rectangle and a hidden one.
+14 -10
View File
@@ -58,7 +58,10 @@ pollster = "1"
# cores the process may run on. Win32_UI_Input_KeyboardAndMouse has `GetKeyState`, which
# src/caps_lock.rs uses to read whether Caps Lock is on. Win32_System_Registry has `RegGetValueW`,
# which src/host_services.rs uses to read the path PhotoCraft registers under App Paths.
windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_System_Registry", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Input_Pointer", "Win32_UI_WindowsAndMessaging"] }
# Win32_Devices_Display has `QueryDisplayConfig`, Win32_UI_ColorSystem the display's ICC profile and
# Win32_System_LibraryLoader `GetProcAddress`, which src/display_profile.rs uses to read the
# display's color profile for the canvas.
windows = { version = "0.62", features = ["Win32_Devices_Display", "Win32_Foundation", "Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_System_Threading", "Win32_UI_ColorSystem", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Input_Pointer", "Win32_UI_WindowsAndMessaging"] }
# The renderer's worker count follows those cores (src/windows_cores.rs).
vectorcraft-render = { workspace = true }
@@ -93,29 +96,30 @@ winit = { version = "0.30", default-features = false, features = ["wayland-csd-a
# A drawing tablet's pen pressure under X11 and XWayland (src/tablet.rs): XInput2 raw events on a
# second X connection, x11rb's pure-Rust `RustConnection`. MIT OR Apache-2.0, already in the build
# through winit with the `xinput` feature. XKB reads Caps Lock's locked modifier state (src/caps_lock.rs).
x11rb = { version = "0.13", default-features = false, features = ["xinput", "xkb"] }
# RandR reads a display's `_ICC_PROFILE` for the canvas (src/display_profile.rs).
x11rb = { version = "0.13", default-features = false, features = ["randr", "xinput", "xkb"] }
# Asks the Wayland compositor which GPU it draws with (linux-dmabuf feedback, src/compositor_gpu.rs),
# so Automatic draws on that one. Both are already in the build through winit.
# so Automatic draws on that one, and copies and pastes text, SVG and PNG through the compositor's
# core data-device protocol on the window's connection (src/clipboard.rs), where arboard has neither
# data-control (GNOME) nor X11 (a Flatpak on a Wayland session). Both are already in the build
# through winit.
wayland-client = "0.31"
# Copy and Paste of text through the compositor's core data-device protocol on the window's
# connection (src/clipboard.rs), where arboard has neither data-control (GNOME) nor X11 (a Flatpak
# on a Wayland session). MIT, already in the build through egui-winit.
smithay-clipboard = "0.7"
wayland-protocols = { version = "0.32", features = ["client", "unstable"] }
# The save dialog's parent window on Wayland (src/portal_save.rs): an xdg-foreign handle (in
# wayland-protocols' `unstable` set) made on the window's own connection. MIT, already in the build
# through winit and rfd.
wayland-backend = { version = "0.3", features = ["client_system"] }
# Waits for the screen color sampler's portal answer and for the portal leaving the bus at the same
# time (src/linux_screen_color/request.rs). Apache-2.0 OR MIT, already in the build through zbus.
futures-lite = "2"
# The save dialog's file type (src/portal_save.rs, #2679): the desktop portal over D-Bus, on the
# systems where rfd shows the portal's dialog. MIT, already in the build through accesskit. Pinned
# exactly: review the diff before bumping.
[target.'cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))'.dependencies]
zbus = "=5.19.0"
# Waits for a portal answer (the save dialog's and the screen color sampler's) and for the portal
# leaving the bus at the same time (src/portal_request.rs). Apache-2.0 OR MIT, already in the build
# through zbus.
futures-lite = "2"
# Tells whether arboard reads through the compositor's data-control protocol or through X11, the
# same check arboard makes (src/clipboard.rs). MIT OR Apache-2.0, already in the build through
# arboard.
+30
View File
@@ -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,
@@ -192,6 +219,9 @@ impl App {
self.app.services.dock_monitors = window::dock_monitors(w, zoom);
self.monitors_listed = Some((now, zoom));
}
if let Some(w) = &self.winit_window {
self.display_profile.tick(w, now, self.app.session.prefs.monitor_profile_display, &self.app.display_profile, ctx);
}
self.app.tick(ctx);
if self.pending_maximize {
if let Some(w) = &self.winit_window {
File diff suppressed because it is too large. Load diff
+629
View File
@@ -0,0 +1,629 @@
//! Reads the ICC profile of the display that shows most of the main window, for Preferences ›
//! Performance › Use Monitor Profile for Canvas, and hands it to [`DisplayProfile::report`].
//!
//! - Windows: the display's default profile for its standard color mode. A display with Advanced
//! Color on (HDR or Automatic Color Management) is converted by Windows, and nothing is read.
//! - X11: colord's profile for the RandR output, then the output's `_ICC_PROFILE` property, then
//! the screen's `_ICC_PROFILE` when only one output is active.
//! - Wayland, XWayland included: the compositor gives applications no display profile, and the
//! canvas stays sRGB.
//! - macOS: the window's layer is tagged sRGB and macOS converts it (`mac_color_space`).
//!
//! While the preference is on, a background thread reads the display every [`EVERY`] seconds,
//! and at once when the window moves to another display.
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use vectorcraft_ui_egui::display_profile::{DisplayProfile, Found, Reading};
/// Seconds between two readings of the same display.
const EVERY: f64 = 10.0;
/// Seconds between two checks of which display shows the window.
const LOOK_EVERY: f64 = 1.0;
/// Starts the readings from the main window's frames.
#[derive(Default)]
pub(crate) struct Reader {
/// When the last reading started, and the display it was for.
last: Option<(f64, Option<String>)>,
/// When the window's display was last looked up.
looked: Option<f64>,
/// A reading is running.
busy: Arc<AtomicBool>,
}
/// Clears [`Reader::busy`] when the reading thread ends, also by a panic.
struct Done(Arc<AtomicBool>);
impl Drop for Done {
fn drop(&mut self) {
self.0.store(false, Ordering::Release);
}
}
impl Reader {
/// Starts a reading when one is due and none is running. `now` is the frame's time in seconds.
pub(crate) fn tick(&mut self, window: &winit::window::Window, now: f64, enabled: bool, profile: &DisplayProfile, ctx: &egui::Context) {
if !enabled || self.busy.load(Ordering::Acquire) || self.looked.is_some_and(|at| (at..at + LOOK_EVERY).contains(&now)) {
return;
}
self.looked = Some(now);
let display = window.current_monitor().and_then(|m| m.name());
if !due(self.last.as_ref(), now, display.as_deref()) {
return;
}
self.last = Some((now, display.clone()));
profile.pending();
self.busy.store(true, Ordering::Release);
let done = Done(self.busy.clone());
let (profile, ctx) = (profile.clone(), ctx.clone());
let spawned = std::thread::Builder::new().name("display profile".into()).spawn(move || {
let _done = done;
if profile.report(read(display)) {
ctx.request_repaint();
}
});
if let Err(e) = spawned {
log::warn!("couldn't start reading the display profile: {e}");
}
}
}
/// Whether a reading of `display` is due at `now`, after the last one (`last`): none yet, another
/// display, [`EVERY`] seconds later, or a clock that went back.
fn due(last: Option<&(f64, Option<String>)>, now: f64, display: Option<&str>) -> bool {
last.is_none_or(|(at, shown)| shown.as_deref() != display || !(*at..at + EVERY).contains(&now))
}
#[cfg(windows)]
fn read(display: Option<String>) -> Reading {
let found = win::read(display.as_deref());
Reading { display, found }
}
#[cfg(target_os = "linux")]
fn read(display: Option<String>) -> Reading {
let found = if wayland_session(|k| std::env::var_os(k)) {
Found::NoProfile("a Wayland session doesn't give applications the display's profile".into())
} else {
x11::read(display.as_deref())
};
Reading { display, found }
}
#[cfg(all(target_os = "macos", feature = "wgpu"))]
fn read(display: Option<String>) -> Reading {
Reading { display, found: Found::System("macOS converts the window to the display's profile".into()) }
}
#[cfg(not(any(windows, target_os = "linux", all(target_os = "macos", feature = "wgpu"))))]
fn read(display: Option<String>) -> Reading {
Reading { display, found: Found::NoProfile("this build doesn't read display profiles on this system".into()) }
}
/// Whether the app runs in a Wayland session, read from the environment `var` gives. XWayland
/// windows count: the variables stay set for them.
#[cfg(any(target_os = "linux", test))]
fn wayland_session(var: impl Fn(&str) -> Option<std::ffi::OsString>) -> bool {
["WAYLAND_DISPLAY", "WAYLAND_SOCKET"].iter().any(|k| var(k).is_some_and(|v| !v.is_empty()))
}
/// The X11 reading from colord's answer `colord` (the profile file it names, read) and the X11
/// properties `properties`: colord's profile when its file can be read, otherwise the
/// properties' profile. When neither has one, the reason colord gave is kept.
#[cfg(any(target_os = "linux", test))]
fn x11_choice(colord: Option<Result<Option<Found>, String>>, properties: impl FnOnce() -> Result<Option<Found>, String>) -> Found {
let colord_reason = match colord {
Some(Ok(Some(found @ Found::Profile { .. }))) => return found,
Some(Ok(Some(Found::NoProfile(e) | Found::System(e)))) | Some(Err(e)) => Some(e),
Some(Ok(None)) | None => None,
};
match properties() {
Ok(Some(found)) => found,
Ok(None) => Found::NoProfile(match colord_reason {
Some(e) => format!("no profile is set for this display ({e})"),
None => "no profile is set for this display".into(),
}),
Err(e) => Found::NoProfile(e),
}
}
/// `found` when it is not a profile or the profile can be used, otherwise why it can't, so the
/// next source is tried.
#[cfg(any(target_os = "linux", test))]
fn usable(found: Found) -> Found {
match found {
Found::Profile { icc, from } => match vectorcraft_ui_egui::display_profile::check_profile(&icc) {
Ok(()) => Found::Profile { icc, from },
Err(e) => Found::NoProfile(format!("{from}: {e}")),
},
other => other,
}
}
/// The ICC file at `path`, refused before it is read when it is larger than [`MAX_PROFILE_BYTES`].
///
/// [`MAX_PROFILE_BYTES`]: vectorcraft_ui_egui::display_profile::MAX_PROFILE_BYTES
#[cfg(any(windows, target_os = "linux", test))]
fn read_icc(path: &std::path::Path) -> Result<Vec<u8>, String> {
use std::io::Read as _;
let max = vectorcraft_ui_egui::display_profile::MAX_PROFILE_BYTES;
let too_large = || format!("{} is larger than {} MiB", path.display(), max >> 20);
let file = std::fs::File::open(path).map_err(|e| format!("couldn't open {}: {e}", path.display()))?;
let len = file.metadata().map_err(|e| format!("couldn't read {}: {e}", path.display()))?.len();
if len > max as u64 {
return Err(too_large());
}
let mut bytes = Vec::with_capacity(len as usize);
file.take(max as u64 + 1).read_to_end(&mut bytes).map_err(|e| format!("couldn't read {}: {e}", path.display()))?;
if bytes.len() > max { Err(too_large()) } else { Ok(bytes) }
}
/// The file a profile `name` stands for: `name` itself when it is a path, otherwise the file of
/// that name in the system's color folder `dir`.
#[cfg(any(windows, test))]
fn profile_path(dir: Option<&std::path::Path>, name: &str) -> std::path::PathBuf {
match dir {
Some(dir) if !name.contains(['\\', '/']) => dir.join(name),
_ => std::path::PathBuf::from(name),
}
}
/// `path`'s profile, or why there is none.
#[cfg(any(windows, target_os = "linux"))]
fn profile_file(path: &std::path::Path) -> Found {
let from = path.file_name().map_or_else(|| path.display().to_string(), |n| n.to_string_lossy().into_owned());
match read_icc(path) {
Ok(icc) => Found::Profile { icc, from },
Err(e) => Found::NoProfile(e),
}
}
#[cfg(windows)]
#[allow(unsafe_code)]
mod win {
use std::path::PathBuf;
use std::sync::OnceLock;
use vectorcraft_ui_egui::display_profile::Found;
use windows::Win32::Devices::Display::{
DISPLAYCONFIG_DEVICE_INFO_GET_ADVANCED_COLOR_INFO, DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME, DISPLAYCONFIG_DEVICE_INFO_HEADER,
DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO, DISPLAYCONFIG_MODE_INFO, DISPLAYCONFIG_PATH_INFO, DISPLAYCONFIG_SOURCE_DEVICE_NAME,
DisplayConfigGetDeviceInfo, GetDisplayConfigBufferSizes, QDC_ONLY_ACTIVE_PATHS, QueryDisplayConfig,
};
use windows::Win32::Foundation::{ERROR_INSUFFICIENT_BUFFER, ERROR_SUCCESS, HLOCAL, LUID, LocalFree};
use windows::Win32::Graphics::Gdi::{CreateDCW, DeleteDC};
use windows::Win32::System::LibraryLoader::{GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW};
use windows::Win32::UI::ColorSystem::{
CPST_STANDARD_DISPLAY_COLOR_MODE, CPT_ICC, GetColorDirectoryW, GetICMProfileW, WCS_PROFILE_MANAGEMENT_SCOPE_CURRENT_USER,
};
use windows::core::{HRESULT, PCWSTR, PWSTR, s, w};
/// `ColorProfileGetDisplayDefault` and `ColorProfileGetDisplayUserScope` (mscms.dll), which
/// older Windows versions don't have.
type GetDefault = unsafe extern "system" fn(i32, LUID, u32, i32, i32, *mut PWSTR) -> HRESULT;
type GetScope = unsafe extern "system" fn(LUID, u32, *mut i32) -> HRESULT;
/// The display path that shows a GDI device.
struct Path {
source: u32,
target_adapter: LUID,
target: u32,
}
pub(super) fn read(display: Option<&str>) -> Found {
let Some(device) = display else { return Found::NoProfile("Windows didn't name the window's display".into()) };
let path = match find_path(device) {
Ok(path) => path,
Err(e) => return Found::NoProfile(e),
};
if path.as_ref().is_some_and(advanced_color) {
return Found::System("Windows manages this display's colors (Advanced Color)".into());
}
let name = match path.as_ref().and_then(default_profile) {
Some(Ok(name)) => name,
Some(Err(e)) => return Found::NoProfile(e),
// Older Windows, or a display without an active path: GDI's profile for the device.
None => match icm_profile(device) {
Ok(name) => name,
Err(e) => return Found::NoProfile(e),
},
};
match name {
Some(name) => super::profile_file(&super::profile_path(color_directory().as_deref(), &name)),
None => Found::NoProfile("no color profile is set for this display".into()),
}
}
fn wide(s: &str) -> Vec<u16> {
s.encode_utf16().chain([0]).collect()
}
fn until_nul(w: &[u16]) -> String {
String::from_utf16_lossy(&w[..w.iter().position(|&c| c == 0).unwrap_or(w.len())])
}
/// The active display paths.
fn paths() -> Result<Vec<DISPLAYCONFIG_PATH_INFO>, String> {
for _ in 0..4 {
let (mut paths_len, mut modes_len) = (0u32, 0u32);
// SAFETY: both pointers are to live `u32`s.
let e = unsafe { GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, &mut paths_len, &mut modes_len) };
if e != ERROR_SUCCESS {
return Err(format!("Windows couldn't list the displays (error {})", e.0));
}
let mut paths = vec![DISPLAYCONFIG_PATH_INFO::default(); paths_len as usize];
let mut modes = vec![DISPLAYCONFIG_MODE_INFO::default(); modes_len as usize];
// SAFETY: the arrays hold as many elements as the lengths passed with them.
let e =
unsafe { QueryDisplayConfig(QDC_ONLY_ACTIVE_PATHS, &mut paths_len, paths.as_mut_ptr(), &mut modes_len, modes.as_mut_ptr(), None) };
if e == ERROR_INSUFFICIENT_BUFFER {
// The displays changed between the two calls.
continue;
}
if e != ERROR_SUCCESS {
return Err(format!("Windows couldn't list the displays (error {})", e.0));
}
paths.truncate(paths_len as usize);
return Ok(paths);
}
Err("the displays kept changing while Windows listed them".into())
}
/// The path whose source is the GDI device `device` (`\\.\DISPLAY1`), if one is active.
fn find_path(device: &str) -> Result<Option<Path>, String> {
for p in paths()? {
let mut name = DISPLAYCONFIG_SOURCE_DEVICE_NAME {
header: DISPLAYCONFIG_DEVICE_INFO_HEADER {
r#type: DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME,
size: size_of::<DISPLAYCONFIG_SOURCE_DEVICE_NAME>() as u32,
adapterId: p.sourceInfo.adapterId,
id: p.sourceInfo.id,
},
..Default::default()
};
// SAFETY: the header starts a `DISPLAYCONFIG_SOURCE_DEVICE_NAME` of the size it states.
if unsafe { DisplayConfigGetDeviceInfo(&mut name.header) } == 0 && until_nul(&name.viewGdiDeviceName).eq_ignore_ascii_case(device) {
return Ok(Some(Path { source: p.sourceInfo.id, target_adapter: p.targetInfo.adapterId, target: p.targetInfo.id }));
}
}
Ok(None)
}
/// Whether Windows color-manages the path's display itself: Advanced Color is on (HDR), or
/// wide color is enforced (Automatic Color Management on an SDR display).
fn advanced_color(path: &Path) -> bool {
let mut info = DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO {
header: DISPLAYCONFIG_DEVICE_INFO_HEADER {
r#type: DISPLAYCONFIG_DEVICE_INFO_GET_ADVANCED_COLOR_INFO,
size: size_of::<DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO>() as u32,
adapterId: path.target_adapter,
id: path.target,
},
..Default::default()
};
// SAFETY: the header starts a `DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO` of the size it states.
if unsafe { DisplayConfigGetDeviceInfo(&mut info.header) } != 0 {
return false;
}
// SAFETY: every bit pattern is a valid `u32`.
let bits = unsafe { info.Anonymous.value };
// advancedColorEnabled is bit 1 and wideColorEnforced bit 2.
bits & 0b110 != 0
}
fn api() -> Option<(GetDefault, GetScope)> {
static API: OnceLock<Option<(GetDefault, GetScope)>> = OnceLock::new();
*API.get_or_init(|| {
// SAFETY: mscms.dll is loaded from System32 only, and stays loaded for the process.
let module = unsafe { LoadLibraryExW(w!("mscms.dll"), None, LOAD_LIBRARY_SEARCH_SYSTEM32) }.ok()?;
// SAFETY: the names are NUL-terminated, and the module is loaded.
let (default, scope) = unsafe {
(GetProcAddress(module, s!("ColorProfileGetDisplayDefault"))?, GetProcAddress(module, s!("ColorProfileGetDisplayUserScope"))?)
};
// SAFETY: both exports have these signatures (icm.h).
unsafe {
Some((
std::mem::transmute::<unsafe extern "system" fn() -> isize, GetDefault>(default),
std::mem::transmute::<unsafe extern "system" fn() -> isize, GetScope>(scope),
))
}
})
}
/// The display's default profile name for its standard color mode, `None` without the API.
fn default_profile(path: &Path) -> Option<Result<Option<String>, String>> {
let (get_default, get_scope) = api()?;
let mut scope = WCS_PROFILE_MANAGEMENT_SCOPE_CURRENT_USER.0;
// SAFETY: `scope` is a live `i32`.
if unsafe { get_scope(path.target_adapter, path.source, &mut scope) }.is_err() {
scope = WCS_PROFILE_MANAGEMENT_SCOPE_CURRENT_USER.0;
}
let mut name = PWSTR::null();
// SAFETY: `name` is a live pointer the function fills with a string it allocates.
let hr = unsafe { get_default(scope, path.target_adapter, path.source, CPT_ICC.0, CPST_STANDARD_DISPLAY_COLOR_MODE.0, &mut name) };
if hr.is_err() {
return Some(Err(format!("Windows couldn't give the display's profile (error {:#010x})", hr.0)));
}
if name.is_null() {
return Some(Ok(None));
}
// SAFETY: `name` is a NUL-terminated string from the call above, freed once with LocalFree.
let text = unsafe { name.to_string() };
// SAFETY: as above.
let _ = unsafe { LocalFree(Some(HLOCAL(name.0.cast()))) };
Some(text.map(|t| Some(t).filter(|t| !t.is_empty())).map_err(|e| format!("the display's profile name isn't readable: {e}")))
}
/// GDI's profile file for the display device `device`.
fn icm_profile(device: &str) -> Result<Option<String>, String> {
let device = wide(device);
// SAFETY: both strings are NUL-terminated and outlive the call.
let dc = unsafe { CreateDCW(w!("DISPLAY"), PCWSTR(device.as_ptr()), PCWSTR::null(), None) };
if dc.is_invalid() {
return Err("Windows couldn't open the display".into());
}
let mut len = 0u32;
// SAFETY: a null buffer asks for the length only.
let _ = unsafe { GetICMProfileW(dc, &mut len, None) };
let mut buf = vec![0u16; len.clamp(1, 32 * 1024) as usize];
len = buf.len() as u32;
// SAFETY: `buf` holds `len` characters.
let ok = unsafe { GetICMProfileW(dc, &mut len, Some(PWSTR(buf.as_mut_ptr()))) }.as_bool();
// SAFETY: `dc` came from CreateDCW above.
let _ = unsafe { DeleteDC(dc) };
Ok(ok.then(|| until_nul(&buf)).filter(|n| !n.is_empty()))
}
/// The system's color folder (`…\spool\drivers\color`).
fn color_directory() -> Option<PathBuf> {
let mut bytes = 0u32;
// SAFETY: a null buffer asks for the size only, in bytes.
let _ = unsafe { GetColorDirectoryW(PCWSTR::null(), None, &mut bytes) };
let mut buf = vec![0u16; (bytes as usize / 2).clamp(1, 32 * 1024)];
bytes = (buf.len() * 2) as u32;
// SAFETY: `buf` holds `bytes` bytes.
unsafe { GetColorDirectoryW(PCWSTR::null(), Some(PWSTR(buf.as_mut_ptr())), &mut bytes) }.as_bool().then(|| PathBuf::from(until_nul(&buf)))
}
#[cfg(test)]
mod tests {
use windows::Win32::Graphics::Gdi::{DISPLAY_DEVICE_ATTACHED_TO_DESKTOP, DISPLAY_DEVICEW, EnumDisplayDevicesW};
use super::*;
/// The GDI names (`\\.\DISPLAY1`) of the displays attached to the desktop.
fn attached_displays() -> Vec<String> {
let mut names = Vec::new();
for i in 0.. {
let mut device = DISPLAY_DEVICEW { cb: size_of::<DISPLAY_DEVICEW>() as u32, ..Default::default() };
// SAFETY: `device` is a live `DISPLAY_DEVICEW` with `cb` set to its size.
if !unsafe { EnumDisplayDevicesW(PCWSTR::null(), i, &mut device, 0) }.as_bool() {
break;
}
if device.StateFlags.contains(DISPLAY_DEVICE_ATTACHED_TO_DESKTOP) {
names.push(until_nul(&device.DeviceName));
}
}
names
}
#[test]
fn windows_reads_each_attached_display_and_refuses_an_unknown_one() {
assert_eq!(read(None), Found::NoProfile("Windows didn't name the window's display".into()));
assert!(color_directory().is_none_or(|dir| dir.is_absolute()));
match find_path(r"\\.\DISPLAY999") {
Ok(path) => {
assert!(path.is_none());
assert_eq!(read(Some(r"\\.\DISPLAY999")), Found::NoProfile("Windows couldn't open the display".into()));
}
// A session without displays (a service): the reading gives Windows' error.
Err(e) => {
eprintln!("the displays couldn't be listed: {e}");
assert_eq!(read(Some(r"\\.\DISPLAY999")), Found::NoProfile(e));
return;
}
}
for name in attached_displays() {
// A display without an active path is read through GDI (`icm_profile`).
let path = find_path(&name).unwrap();
// winit names the display in GDI's spelling; the match ignores letter case.
let lower = find_path(&name.to_lowercase()).unwrap();
assert_eq!(lower.map(|p| (p.source, p.target)), path.as_ref().map(|p| (p.source, p.target)), "{name} in lowercase");
match read(Some(&name)) {
Found::Profile { icc, from } => {
eprintln!("{name}: profile {from}, {} bytes", icc.len());
assert!(!icc.is_empty() && !from.is_empty());
assert!(!path.as_ref().is_some_and(advanced_color));
}
Found::System(e) => {
eprintln!("{name}: system, {e}");
assert!(path.as_ref().is_some_and(advanced_color));
}
Found::NoProfile(e) => {
eprintln!("{name}: no profile, {e}");
assert!(!e.is_empty());
}
}
}
}
}
}
#[cfg(target_os = "linux")]
mod x11 {
use std::collections::HashMap;
use std::path::Path;
use std::time::Duration;
use vectorcraft_ui_egui::display_profile::{Found, MAX_PROFILE_BYTES};
use x11rb::connection::Connection as _;
use x11rb::protocol::randr;
use x11rb::protocol::xproto::{self, AtomEnum};
use zbus::blocking::{connection::Builder, proxy::Proxy};
use zbus::zvariant::OwnedObjectPath;
const COLORD: &str = "org.freedesktop.ColorManager";
const COLORD_ROOT: &str = "/org/freedesktop/ColorManager";
const COLORD_MANAGER: &str = "org.freedesktop.ColorManager";
const COLORD_DEVICE: &str = "org.freedesktop.ColorManager.Device";
const COLORD_PROFILE: &str = "org.freedesktop.ColorManager.Profile";
pub(super) fn read(output: Option<&str>) -> Found {
let colord = output.map(|o| colord_profile(o).map(|path| path.map(|path| super::usable(super::profile_file(Path::new(&path))))));
super::x11_choice(colord, || properties(output))
}
/// The file colord assigns the RandR output `output`.
fn colord_profile(output: &str) -> Result<Option<String>, String> {
let connection = Builder::system()
.map_err(|e| format!("couldn't connect to the system bus: {e}"))?
.method_timeout(Duration::from_secs(2))
.build()
.map_err(|e| format!("couldn't connect to the system bus: {e}"))?;
let manager = Proxy::new(&connection, COLORD, COLORD_ROOT, COLORD_MANAGER).map_err(|e| format!("couldn't reach colord: {e}"))?;
let devices: Vec<OwnedObjectPath> =
manager.call("GetDevicesByKind", &("display",)).map_err(|e| format!("colord couldn't list the displays: {e}"))?;
for path in devices {
let Ok(device) = Proxy::new(&connection, COLORD, &path, COLORD_DEVICE) else { continue };
let Ok(metadata) = device.get_property::<HashMap<String, String>>("Metadata") else { continue };
if metadata.get("XRANDR_name").map(String::as_str) != Some(output) {
continue;
}
// `*` asks for the device's default profile.
let Ok(profile_path) = device.call::<_, _, OwnedObjectPath>("GetProfileForQualifiers", &(vec!["*"],)) else { return Ok(None) };
let profile =
Proxy::new(&connection, COLORD, &profile_path, COLORD_PROFILE).map_err(|e| format!("couldn't reach colord's profile: {e}"))?;
return Ok(profile.get_property::<String>("Filename").ok().filter(|f| !f.is_empty()));
}
Ok(None)
}
/// The `_ICC_PROFILE` property of the RandR output `output`, or of the screen when only one
/// output is active.
fn properties(output: Option<&str>) -> Result<Option<Found>, String> {
let (conn, screen) = x11rb::connect(None).map_err(|e| format!("couldn't connect to the X11 display: {e}"))?;
let root = conn.setup().roots.get(screen).ok_or_else(|| "the X11 display has no screen".to_string())?.root;
let atom = xproto::intern_atom(&conn, true, b"_ICC_PROFILE")
.map_err(|e| format!("couldn't ask the X11 display for profiles: {e}"))?
.reply()
.map_err(|e| format!("couldn't ask the X11 display for profiles: {e}"))?
.atom;
if atom == 0 {
return Ok(None);
}
let resources = randr::get_screen_resources_current(&conn, root)
.map_err(|e| format!("couldn't list the X11 outputs: {e}"))?
.reply()
.map_err(|e| format!("couldn't list the X11 outputs: {e}"))?;
let (mut active, mut shown) = (0usize, None);
for o in resources.outputs {
let Ok(Ok(info)) = randr::get_output_info(&conn, o, resources.config_timestamp).map(|c| c.reply()) else { continue };
if info.connection != randr::Connection::CONNECTED || info.crtc == 0 {
continue;
}
active += 1;
if output.is_some_and(|name| info.name == name.as_bytes()) {
shown = Some(o);
}
}
let longs = (MAX_PROFILE_BYTES / 4) as u32;
let too_large = || Found::NoProfile(format!("the display's profile is larger than {} MiB", MAX_PROFILE_BYTES >> 20));
if let Some(o) = shown
&& let Ok(Ok(p)) = randr::get_output_property(&conn, o, atom, AtomEnum::ANY, 0, longs, false, false).map(|c| c.reply())
&& !p.data.is_empty()
{
if p.bytes_after > 0 {
return Ok(Some(too_large()));
}
return Ok(Some(Found::Profile { icc: p.data, from: "the X11 output's _ICC_PROFILE".into() }));
}
if active != 1 {
return Ok(None);
}
let Ok(Ok(p)) = xproto::get_property(&conn, false, root, atom, AtomEnum::ANY, 0, longs).map(|c| c.reply()) else { return Ok(None) };
if p.value.is_empty() {
return Ok(None);
}
if p.bytes_after > 0 {
return Ok(Some(too_large()));
}
Ok(Some(Found::Profile { icc: p.value, from: "the X11 screen's _ICC_PROFILE".into() }))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_reading_is_due_first_after_ten_seconds_and_when_the_window_changes_display() {
assert!(due(None, 0.0, None));
let last = (100.0, Some("DP-1".to_string()));
assert!(!due(Some(&last), 100.0, Some("DP-1")));
assert!(!due(Some(&last), 109.9, Some("DP-1")));
assert!(due(Some(&last), 110.0, Some("DP-1")));
assert!(due(Some(&last), 101.0, Some("HDMI-1")));
assert!(due(Some(&last), 101.0, None));
// A clock that went back.
assert!(due(Some(&last), 50.0, Some("DP-1")));
}
#[test]
fn wayland_sessions_are_told_apart_from_x11_by_the_environment() {
let env = |pairs: &'static [(&'static str, &'static str)]| {
move |k: &str| pairs.iter().find(|(n, _)| *n == k).map(|(_, v)| std::ffi::OsString::from(v))
};
assert!(wayland_session(env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0")])));
assert!(wayland_session(env(&[("WAYLAND_SOCKET", "5")])));
assert!(!wayland_session(env(&[("DISPLAY", ":0")])));
assert!(!wayland_session(env(&[("WAYLAND_DISPLAY", ""), ("DISPLAY", ":0")])));
}
#[test]
fn profile_files_larger_than_the_limit_are_refused_before_they_are_read() {
let dir = tempfile::tempdir().unwrap();
let small = dir.path().join("small.icc");
std::fs::write(&small, [1u8, 2, 3]).unwrap();
assert_eq!(read_icc(&small).unwrap(), [1, 2, 3]);
let big = dir.path().join("big.icc");
let f = std::fs::File::create(&big).unwrap();
f.set_len(vectorcraft_ui_egui::display_profile::MAX_PROFILE_BYTES as u64 + 1).unwrap();
assert!(read_icc(&big).unwrap_err().contains("larger than 1 MiB"));
assert!(read_icc(&dir.path().join("missing.icc")).unwrap_err().starts_with("couldn't open"));
}
#[test]
fn x11_takes_the_output_property_when_colord_s_file_cannot_be_read() {
let icc = |b: u8| Found::Profile { icc: vec![b], from: "test".into() };
let property = || Ok(Some(icc(2)));
// colord's profile, read: the property is not asked for.
assert_eq!(x11_choice(Some(Ok(Some(icc(1)))), || panic!("not asked")), icc(1));
// colord names a file that can't be read, or has no profile, or isn't running.
assert_eq!(x11_choice(Some(Ok(Some(Found::NoProfile("couldn't open a.icc".into())))), property), icc(2));
assert_eq!(x11_choice(Some(Ok(None)), property), icc(2));
assert_eq!(x11_choice(Some(Err("no colord".into())), property), icc(2));
assert_eq!(x11_choice(None, property), icc(2));
// Neither has a profile: colord's reason is kept.
assert_eq!(
x11_choice(Some(Ok(Some(Found::NoProfile("couldn't open a.icc".into())))), || Ok(None)),
Found::NoProfile("no profile is set for this display (couldn't open a.icc)".into())
);
assert_eq!(x11_choice(None, || Ok(None)), Found::NoProfile("no profile is set for this display".into()));
assert_eq!(x11_choice(None, || Err("no X11".into())), Found::NoProfile("no X11".into()));
// colord's file holds no usable profile: the property is used.
let broken = usable(Found::Profile { icc: vec![1, 2, 3], from: "a.icc".into() });
assert_eq!(broken, Found::NoProfile("a.icc: the file is not an ICC profile".into()));
assert_eq!(x11_choice(Some(Ok(Some(broken))), property), icc(2));
assert_eq!(usable(Found::NoProfile("none".into())), Found::NoProfile("none".into()));
}
#[test]
fn a_profile_name_is_found_in_the_color_folder_and_a_path_is_kept() {
let dir = std::path::Path::new("C:/Windows/System32/spool/drivers/color");
assert_eq!(profile_path(Some(dir), "Display.icm"), dir.join("Display.icm"));
assert_eq!(profile_path(Some(dir), "D:\\profiles\\Display.icm"), std::path::PathBuf::from("D:\\profiles\\Display.icm"));
assert_eq!(profile_path(None, "Display.icm"), std::path::PathBuf::from("Display.icm"));
}
}
+3 -2
View File
@@ -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.
@@ -4,7 +4,6 @@
//! parent is the window, named on that thread as for the portal's save dialog (`portal_save`).
mod portal;
mod request;
/// The portal's color sampler over the window `parent` holds; `ui` is woken when it answers.
pub fn sampler(ui: egui::Context, parent: super::host_services::Parent) -> vectorcraft_ui_egui::screen_color::StartSampler {
@@ -61,9 +61,9 @@ pub(super) fn connect(builder: zbus::Result<zbus::blocking::connection::Builder<
/// after it has no bound, and ends when the portal answers or leaves the bus.
pub(super) fn pick(conn: &Connection, parent: &str) -> Result<Option<[f32; 3]>, Failure> {
const DESKTOP: &str = "org.freedesktop.portal.Desktop";
let token = super::request::token("vectorcraft_color").map_err(Failure::Failed)?;
let token = crate::portal_request::token("vectorcraft_color").map_err(Failure::Failed)?;
// Made before the call: a portal can send its answer before the call returns.
let replies = super::request::Responses::new(conn).map_err(Failure::Failed)?;
let replies = crate::portal_request::Responses::new(conn).map_err(Failure::Failed)?;
let proxy = Proxy::new(conn, DESKTOP, "/org/freedesktop/portal/desktop", "org.freedesktop.portal.Screenshot")
.map_err(|e| Failure::Failed(e.to_string()))?;
let options = HashMap::from([("handle_token", Value::from(token.as_str()))]);
@@ -106,6 +106,7 @@ fn answer(code: u32, results: &HashMap<String, OwnedValue>) -> Result<Option<[f3
#[cfg(test)]
mod tests {
use super::*;
use crate::portal_request::test_bus::private_bus;
fn color(rgb: (f64, f64, f64)) -> HashMap<String, OwnedValue> {
HashMap::from([("color".into(), OwnedValue::try_from(Value::from(rgb)).unwrap())])
@@ -186,35 +187,6 @@ mod tests {
}
}
/// A session bus of its own (`dbus-daemon`), `None` when there is none to run.
fn private_bus() -> Option<(Daemon, String)> {
use std::io::BufRead as _;
let spawning = crate::spawning();
let daemon = std::process::Command::new("dbus-daemon")
.args(["--session", "--nofork", "--print-address=1"])
.stdout(std::process::Stdio::piped())
.spawn();
drop(spawning);
let Ok(daemon) = daemon else {
eprintln!("no dbus-daemon: skipped");
return None;
};
let mut daemon = Daemon(daemon);
let mut address = String::new();
std::io::BufReader::new(daemon.0.stdout.take().unwrap()).read_line(&mut address).unwrap();
Some((daemon, address.trim().to_string()))
}
/// Stops the private bus when the test ends, unwinding included.
struct Daemon(std::process::Child);
impl Drop for Daemon {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
/// The client's connection to the private bus at `address`, made as the sampler makes its own.
fn client(address: &str) -> Connection {
connect(zbus::blocking::connection::Builder::address(address)).unwrap()
@@ -1,127 +0,0 @@
//! The answer to the color sampler's XDG desktop portal request
//! (<https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Request.html>).
//! The wait ends with the request's `Response`, or with an error when the portal leaves the bus
//! first.
use std::io::Read as _;
use futures_lite::{StreamExt as _, future};
use zbus::blocking::{Connection, MessageIterator};
use zbus::zvariant::OwnedObjectPath;
const DESKTOP: &str = "org.freedesktop.portal.Desktop";
/// A request token: `prefix`, then 128 bits from the operating system's random device, so the
/// token is unique and can't be guessed, as the Request documentation asks.
pub(super) fn token(prefix: &str) -> Result<String, String> {
let mut bytes = [0; 16];
std::fs::File::open("/dev/urandom")
.and_then(|mut file| file.read_exact(&mut bytes))
.map_err(|e| format!("could not create a portal request token: {e}"))?;
let random: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
Ok(format!("{prefix}_{random}"))
}
/// Subscriptions made before a portal method call, on every request path: a portal older than
/// version 0.9 ignores `handle_token` and answers on the request path it returns, and its answer
/// can come before the call's reply. Each stream keeps every signal from the time it is made.
pub(super) struct Responses {
replies: MessageIterator,
owners: MessageIterator,
}
impl Responses {
pub(super) fn new(conn: &Connection) -> Result<Self, String> {
let reply_rule = zbus::MatchRule::builder()
.msg_type(zbus::message::Type::Signal)
.sender(DESKTOP)
.and_then(|b| b.interface("org.freedesktop.portal.Request"))
.and_then(|b| b.member("Response"))
.map_err(|e| e.to_string())?
.build();
let owner_rule = zbus::MatchRule::builder()
.msg_type(zbus::message::Type::Signal)
.sender("org.freedesktop.DBus")
.and_then(|b| b.path("/org/freedesktop/DBus"))
.and_then(|b| b.interface("org.freedesktop.DBus"))
.and_then(|b| b.member("NameOwnerChanged"))
.and_then(|b| b.arg(0, DESKTOP))
.map_err(|e| e.to_string())?
.build();
Ok(Self {
replies: MessageIterator::for_match_rule(reply_rule, conn, None).map_err(|e| e.to_string())?,
owners: MessageIterator::for_match_rule(owner_rule, conn, None).map_err(|e| e.to_string())?,
})
}
/// The `Response` on the request path `call` returned, from the connection that returned it.
/// An error when that connection leaves the bus first, or the bus connection closes.
pub(super) fn wait(self, call: &zbus::Message) -> Result<zbus::Message, String> {
enum Event {
Reply(Option<zbus::Result<zbus::Message>>),
Owner(Option<zbus::Result<zbus::Message>>),
}
let handle: OwnedObjectPath = call.body().deserialize().map_err(|e| e.to_string())?;
let portal = call.header().sender().map(|s| s.as_str().to_string()).ok_or("the portal answered without a sender")?;
let mut replies = self.replies.into_inner();
let mut owners = self.owners.into_inner();
future::block_on(async {
loop {
let event = future::or(async { Event::Reply(replies.next().await) }, async { Event::Owner(owners.next().await) }).await;
match event {
Event::Reply(reply) => {
let reply = reply.ok_or("the portal closed without an answer")?.map_err(|e| e.to_string())?;
let header = reply.header();
if header.path().map(|p| p.as_str()) == Some(handle.as_str()) && header.sender().map(|s| s.as_str()) == Some(portal.as_str())
{
return Ok(reply);
}
}
Event::Owner(message) => {
let message = message.ok_or("the portal connection closed")?.map_err(|e| e.to_string())?;
if owner_disappeared(&message, &portal)? {
return Err("the desktop portal disappeared while waiting for its answer".into());
}
}
}
}
})
}
}
/// Whether `message` is the bus's `NameOwnerChanged` saying that the connection `portal` no longer
/// owns the portal's name. The bus itself must send it: another connection can't end the wait.
fn owner_disappeared(message: &zbus::Message, portal: &str) -> Result<bool, String> {
if message.header().sender().map(|s| s.as_str()) != Some("org.freedesktop.DBus") {
return Ok(false);
}
let (name, old, new): (String, String, String) = message.body().deserialize().map_err(|e| e.to_string())?;
Ok(name == DESKTOP && old == portal && new != portal)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_the_bus_can_report_portal_owner_loss() {
let changed = |sender, name, old, new| {
zbus::Message::signal("/org/freedesktop/DBus", "org.freedesktop.DBus", "NameOwnerChanged")
.unwrap()
.sender(sender)
.unwrap()
.build(&(name, old, new))
.unwrap()
};
let forged = changed(":1.42", DESKTOP, ":1.7", "");
assert!(!owner_disappeared(&forged, ":1.7").unwrap());
let real = changed("org.freedesktop.DBus", DESKTOP, ":1.7", "");
assert!(owner_disappeared(&real, ":1.7").unwrap());
let other = changed("org.freedesktop.DBus", "org.example.Other", ":1.7", "");
assert!(!owner_disappeared(&other, ":1.7").unwrap());
let old = changed("org.freedesktop.DBus", DESKTOP, ":1.8", "");
assert!(!owner_disappeared(&old, ":1.7").unwrap());
let acquired = changed("org.freedesktop.DBus", DESKTOP, "", ":1.7");
assert!(!owner_disappeared(&acquired, ":1.7").unwrap());
}
}
+13 -3
View File
@@ -28,6 +28,7 @@ mod clipboard;
mod compositor_gpu;
mod control_server;
mod cursor_theme;
mod display_profile;
#[cfg(feature = "wgpu")]
mod gpu;
mod hang_watch;
@@ -53,6 +54,8 @@ mod mac_tablet;
mod mac_window;
#[cfg(target_os = "macos")]
mod open_documents;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
mod portal_request;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd", test))]
mod portal_save;
mod prefs_dir;
@@ -87,6 +90,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};
@@ -102,7 +107,7 @@ use titlebar::opted_into_system_title_bar;
#[cfg(windows)]
use titlebar::set_taskbar_icon;
#[cfg(all(test, feature = "wgpu"))]
use titlebar::{app_draws_frame, opted_into_app_title_bar, start_frame, system_title_bar_applies};
use titlebar::{app_draws_frame, caption_layout_from, opted_into_app_title_bar, start_frame, system_title_bar_applies};
use titlebar::{custom_titlebar, native_options, titlebar_from_env};
struct App {
@@ -116,7 +121,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,
@@ -126,6 +132,8 @@ struct App {
held_files: Vec<String>,
/// The time and UI zoom of the last monitor list ([`window::monitors_due`]).
monitors_listed: Option<(f64, f32)>,
/// Reads the profile of the display that shows the main window, for the canvas.
display_profile: display_profile::Reader,
/// When this frame's input hook started, for the hang report's frame times (`hang_watch`).
frame_start: Option<std::time::Instant>,
}
@@ -359,7 +367,7 @@ fn main() -> std::process::ExitCode {
};
#[cfg(feature = "wgpu")]
let crash = left_out.crash.clone();
let custom_titlebar = custom_titlebar(saved.as_ref());
let (custom_titlebar, caption_layout) = custom_titlebar(saved.as_ref());
let options = native_options(custom_titlebar);
// winit picks Wayland whenever `WAYLAND_DISPLAY` is set; Preferences › Performance › Linux
// Display Server › X11 opens the window through XWayland instead, where file drops work (#1151),
@@ -585,6 +593,7 @@ fn main() -> std::process::ExitCode {
}
app.titlebar_from_env = titlebar_from_env();
app.custom_titlebar = custom_titlebar;
app.caption_layout = caption_layout;
app.desktop_frame = !custom_titlebar;
if let Some(port) = control_port {
let rx = control_server::start(port, cc.egui_ctx.clone());
@@ -629,6 +638,7 @@ fn main() -> std::process::ExitCode {
maximize_tries: 8,
held_files,
monitors_listed: None,
display_profile: Default::default(),
frame_start: None,
}))
}),
+231
View File
@@ -0,0 +1,231 @@
//! Linux and the BSDs: the answer to an XDG desktop portal request
//! (<https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Request.html>),
//! for the save dialog (`portal_save`) and, on Linux, the screen color sampler
//! (`linux_screen_color`). The wait ends with the request's `Response`, or with an error when the
//! portal leaves the bus first.
use futures_lite::{StreamExt as _, future};
use zbus::blocking::{Connection, MessageIterator};
use zbus::zvariant::OwnedObjectPath;
const DESKTOP: &str = "org.freedesktop.portal.Desktop";
/// A request token: `prefix`, then 128 bits from the operating system's random device, so the
/// token is unique and can't be guessed, as the Request documentation asks.
#[cfg(target_os = "linux")]
pub(crate) fn token(prefix: &str) -> Result<String, String> {
use std::io::Read as _;
let mut bytes = [0; 16];
std::fs::File::open("/dev/urandom")
.and_then(|mut file| file.read_exact(&mut bytes))
.map_err(|e| format!("could not create a portal request token: {e}"))?;
let random: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
Ok(format!("{prefix}_{random}"))
}
/// Subscriptions made before a portal method call, on every request path: a portal older than
/// version 0.9 ignores `handle_token` and answers on the request path it returns, and its answer
/// can come before the call's reply. Each stream keeps every signal from the time it is made.
pub(crate) struct Responses {
replies: MessageIterator,
owners: MessageIterator,
}
impl Responses {
pub(crate) fn new(conn: &Connection) -> Result<Self, String> {
let reply_rule = zbus::MatchRule::builder()
.msg_type(zbus::message::Type::Signal)
.sender(DESKTOP)
.and_then(|b| b.interface("org.freedesktop.portal.Request"))
.and_then(|b| b.member("Response"))
.map_err(|e| e.to_string())?
.build();
let owner_rule = zbus::MatchRule::builder()
.msg_type(zbus::message::Type::Signal)
.sender("org.freedesktop.DBus")
.and_then(|b| b.path("/org/freedesktop/DBus"))
.and_then(|b| b.interface("org.freedesktop.DBus"))
.and_then(|b| b.member("NameOwnerChanged"))
.and_then(|b| b.arg(0, DESKTOP))
.map_err(|e| e.to_string())?
.build();
Ok(Self {
replies: MessageIterator::for_match_rule(reply_rule, conn, None).map_err(|e| e.to_string())?,
owners: MessageIterator::for_match_rule(owner_rule, conn, None).map_err(|e| e.to_string())?,
})
}
/// The `Response` on the request path `call` returned, from the connection that returned it.
/// An error when that connection leaves the bus first, or the bus connection closes. A
/// `Response` the portal sent before it left is still the answer.
pub(crate) fn wait(self, call: &zbus::Message) -> Result<zbus::Message, String> {
enum Event {
Reply(Option<zbus::Result<zbus::Message>>),
Owner(Option<zbus::Result<zbus::Message>>),
}
let handle: OwnedObjectPath = call.body().deserialize().map_err(|e| e.to_string())?;
let portal = call.header().sender().map(|s| s.as_str().to_string()).ok_or("the portal answered without a sender")?;
let answers = |reply: &zbus::Message| {
let header = reply.header();
header.path().map(|p| p.as_str()) == Some(handle.as_str()) && header.sender().map(|s| s.as_str()) == Some(portal.as_str())
};
let mut replies = self.replies.into_inner();
let mut owners = self.owners.into_inner();
future::block_on(async {
loop {
let event = future::or(async { Event::Owner(owners.next().await) }, async { Event::Reply(replies.next().await) }).await;
match event {
Event::Reply(reply) => {
let reply = reply.ok_or("the portal closed without an answer")?.map_err(|e| e.to_string())?;
if answers(&reply) {
return Ok(reply);
}
}
Event::Owner(message) => {
let message = message.ok_or("the portal connection closed")?.map_err(|e| e.to_string())?;
if owner_disappeared(&message, &portal)? {
// zbus puts each message in every matching stream before it reads the
// next one, so a `Response` that came before the bus's report is
// already queued: it is still the answer.
while let Some(Some(reply)) = future::poll_once(replies.next()).await {
if let Ok(reply) = reply
&& answers(&reply)
{
return Ok(reply);
}
}
return Err("the desktop portal disappeared while waiting for its answer".into());
}
}
}
}
})
}
}
/// Whether `message` is the bus's `NameOwnerChanged` saying that the connection `portal` no longer
/// owns the portal's name. The bus itself must send it: another connection can't end the wait.
fn owner_disappeared(message: &zbus::Message, portal: &str) -> Result<bool, String> {
if message.header().sender().map(|s| s.as_str()) != Some("org.freedesktop.DBus") {
return Ok(false);
}
let (name, old, new): (String, String, String) = message.body().deserialize().map_err(|e| e.to_string())?;
Ok(name == DESKTOP && old == portal && new != portal)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_the_bus_can_report_portal_owner_loss() {
let changed = |sender, name, old, new| {
zbus::Message::signal("/org/freedesktop/DBus", "org.freedesktop.DBus", "NameOwnerChanged")
.unwrap()
.sender(sender)
.unwrap()
.build(&(name, old, new))
.unwrap()
};
let forged = changed(":1.42", DESKTOP, ":1.7", "");
assert!(!owner_disappeared(&forged, ":1.7").unwrap());
let real = changed("org.freedesktop.DBus", DESKTOP, ":1.7", "");
assert!(owner_disappeared(&real, ":1.7").unwrap());
let other = changed("org.freedesktop.DBus", "org.example.Other", ":1.7", "");
assert!(!owner_disappeared(&other, ":1.7").unwrap());
let old = changed("org.freedesktop.DBus", DESKTOP, ":1.8", "");
assert!(!owner_disappeared(&old, ":1.7").unwrap());
let acquired = changed("org.freedesktop.DBus", DESKTOP, "", ":1.7");
assert!(!owner_disappeared(&acquired, ":1.7").unwrap());
}
/// Through a real D-Bus: when the bus has reported the portal gone, a `Response` the portal sent
/// before it left is still the answer; without one the wait ends with an error.
#[test]
fn a_queued_answer_wins_over_the_portal_leaving() {
use std::collections::HashMap;
use zbus::blocking::connection::Builder;
use zbus::zvariant::OwnedValue;
for answered in [true, false] {
let Some((_daemon, address)) = test_bus::private_bus() else { return };
let address = address.as_str();
let portal = Builder::address(address).unwrap().name(DESKTOP).unwrap().build().unwrap();
let unique = portal.unique_name().unwrap().to_string();
let client = Builder::address(address).unwrap().build().unwrap();
let responses = Responses::new(&client).unwrap();
// zbus puts each message in every matching stream before it reads the next one
// (`src/connection/socket_reader.rs`), so once this stream has the bus's report,
// `responses` holds the `Response` sent before it.
let gone_rule = zbus::MatchRule::builder()
.msg_type(zbus::message::Type::Signal)
.sender("org.freedesktop.DBus")
.unwrap()
.member("NameOwnerChanged")
.unwrap()
.arg(0, DESKTOP)
.unwrap()
.build();
let gone = MessageIterator::for_match_rule(gone_rule, &client, None).unwrap();
let path = "/org/freedesktop/portal/desktop/request/test/t1";
if answered {
let results = HashMap::<String, OwnedValue>::new();
portal.emit_signal(None::<&str>, path, "org.freedesktop.portal.Request", "Response", &(0_u32, results)).unwrap();
}
portal.close().unwrap();
// On a thread of its own, so a report that never comes fails the test instead of
// hanging it.
let (seen, report) = std::sync::mpsc::channel();
let left = unique.clone();
std::thread::spawn(move || {
let mut gone = gone;
let _ = seen.send(gone.any(|m| m.is_ok_and(|m| owner_disappeared(&m, &left).unwrap_or(false))));
});
assert_eq!(report.recv_timeout(std::time::Duration::from_secs(30)), Ok(true), "the bus did not report the portal gone");
// The call's reply as `wait` reads it: the request path, from the portal's connection.
let call = zbus::Message::signal("/", "org.example.Test", "Reply")
.unwrap()
.sender(unique.as_str())
.unwrap()
.build(&OwnedObjectPath::try_from(path).unwrap())
.unwrap();
let waited = responses.wait(&call);
assert_eq!(waited.is_ok(), answered, "{waited:?}");
}
}
}
/// The private session bus that the D-Bus tests of the portal requests run on.
#[cfg(test)]
pub(crate) mod test_bus {
/// A session bus of its own (`dbus-daemon`), `None` when there is none to run.
pub(crate) fn private_bus() -> Option<(Daemon, String)> {
use std::io::BufRead as _;
let spawning = crate::spawning();
let daemon = std::process::Command::new("dbus-daemon")
.args(["--session", "--nofork", "--print-address=1"])
.stdout(std::process::Stdio::piped())
.spawn();
drop(spawning);
let Ok(daemon) = daemon else {
eprintln!("no dbus-daemon: skipped");
return None;
};
let mut daemon = Daemon(daemon);
let mut address = String::new();
std::io::BufReader::new(daemon.0.stdout.take().unwrap()).read_line(&mut address).unwrap();
Some((daemon, address.trim().to_string()))
}
/// Stops the private bus when the test ends, unwinding included.
pub(crate) struct Daemon(std::process::Child);
impl Drop for Daemon {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
}
+56 -45
View File
@@ -8,6 +8,7 @@
//! ([`vectorcraft_ui_egui::picks::PickAnswer`]); the app gives the name that type's extension.
//! rfd shows the dialog when the portal can't (no session bus, no file chooser), with zenity as its
//! own fallback. PhotoCraft's `portal_save.rs` (storytold/photocraft#6151) makes the same call.
//! rfd also shows the dialog when the portal leaves the bus before it answers.
//!
//! The dialog's parent is the window: `x11:<window id>` on X11, and on Wayland (Linux) a handle
//! from the compositor's xdg-foreign protocol, as rfd names it (its `window_identifier`).
@@ -183,37 +184,18 @@ pub fn pick(pick: &FilePick, window: Option<&winit::window::Window>) -> Option<V
fn save_file(conn: &zbus::blocking::Connection, request: &SaveRequest) -> Result<Option<Saved>, String> {
use std::sync::atomic::{AtomicU32, Ordering};
use zbus::blocking::{MessageIterator, Proxy};
use zbus::zvariant::OwnedObjectPath;
use zbus::blocking::Proxy;
const DESKTOP: &str = "org.freedesktop.portal.Desktop";
const REQUEST: &str = "org.freedesktop.portal.Request";
static NEXT: AtomicU32 = AtomicU32::new(0);
let token = format!("vectorcraft_save_{}_{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed));
// Listen before asking, on every request path: a portal older than version 0.9 ignores
// `handle_token` and answers on the request path it returns, and its answer can come before
// the call's reply. The stream keeps every `Response` from the time it is made.
let rule = zbus::MatchRule::builder()
.msg_type(zbus::message::Type::Signal)
.sender(DESKTOP)
.and_then(|b| b.interface(REQUEST))
.and_then(|b| b.member("Response"))
.map_err(|e| e.to_string())?
.build();
let responses = MessageIterator::for_match_rule(rule, conn, None).map_err(|e| e.to_string())?;
// Made before the call: a portal can send its answer before the call returns, and a portal
// that leaves the bus while its dialog is open ends the wait.
let responses = crate::portal_request::Responses::new(conn)?;
let chooser = Proxy::new(conn, DESKTOP, "/org/freedesktop/portal/desktop", "org.freedesktop.portal.FileChooser").map_err(|e| e.to_string())?;
// The title is empty, as rfd sends it for a save.
let call = chooser.call_method("SaveFile", &(request.parent.as_str(), "", options(request, &token))).map_err(|e| e.to_string())?;
let handle: OwnedObjectPath = call.body().deserialize().map_err(|e| e.to_string())?;
// The answer is the `Response` on the path returned, from the connection that returned it.
let portal = call.header().sender().map(|s| s.as_str().to_string());
let reply = responses
.filter_map(Result::ok)
.find(|m| {
let header = m.header();
header.path().map(|p| p.as_str()) == Some(handle.as_str()) && header.sender().map(|s| s.as_str()) == portal.as_deref()
})
.ok_or("the save dialog closed without an answer")?;
let reply = responses.wait(&call)?;
let (code, results): (u32, HashMap<String, OwnedValue>) = reply.body().deserialize().map_err(|e| e.to_string())?;
answer(code, &results)
}
@@ -495,26 +477,22 @@ mod tests {
Old,
/// As `Old`, with the `Response` sent before the reply that names its path.
OldEarly,
/// As `Current`, but it leaves the bus 300 ms after its reply without a `Response`, as a
/// portal that exits while its dialog is open.
Exits,
/// Leaves the bus right after its reply, without a `Response`.
ExitsAtOnce,
/// Sends its `Response` right after its reply, then leaves the bus.
AnswersAndExits,
}
/// A session bus of its own (`dbus-daemon`) with a mock `org.freedesktop.portal.FileChooser`
/// that answers `SaveFile` from `script` as `portal` says, as PhotoCraft's portal tests run it.
/// `None` when there is no `dbus-daemon` to run.
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
fn mock_portal(script: Script, portal: Portal) -> Option<(zbus::blocking::Connection, Seen, std::process::Child)> {
use std::io::BufRead as _;
fn mock_portal(script: Script, portal: Portal) -> Option<(zbus::blocking::Connection, Seen, crate::portal_request::test_bus::Daemon)> {
use zbus::zvariant::OwnedObjectPath;
let spawning = crate::spawning();
let daemon = std::process::Command::new("dbus-daemon")
.args(["--session", "--nofork", "--print-address=1"])
.stdout(std::process::Stdio::piped())
.spawn();
drop(spawning);
let mut daemon = daemon.ok()?;
let mut address = String::new();
std::io::BufReader::new(daemon.stdout.take()?).read_line(&mut address).ok()?;
let address = address.trim().to_string();
let (daemon, address) = crate::portal_request::test_bus::private_bus()?;
let server =
zbus::blocking::connection::Builder::address(address.as_str()).ok()?.name("org.freedesktop.portal.Desktop").ok()?.build().ok()?;
let seen = Seen::default();
@@ -539,8 +517,8 @@ mod tests {
});
let Some(sender) = header.sender().map(|s| s.as_str().trim_start_matches(':').replace('.', "_")) else { break };
let token = match portal {
Portal::Current => text("handle_token").unwrap_or_default(),
Portal::Old | Portal::OldEarly => format!("old{}", calls.unwrap_or_default()),
Portal::Current | Portal::Exits | Portal::ExitsAtOnce | Portal::AnswersAndExits => text("handle_token").unwrap_or_default(),
};
let path = format!("/org/freedesktop/portal/desktop/request/{sender}/{token}");
let Ok(handle) = OwnedObjectPath::try_from(path.as_str()) else { break };
@@ -558,14 +536,22 @@ mod tests {
if server.reply(&header, &handle).is_err() {
break;
}
if portal == Portal::Old {
if matches!(portal, Portal::Old | Portal::Exits) {
// As a person answers the dialog: after the caller has the path returned.
std::thread::sleep(std::time::Duration::from_millis(300));
}
if matches!(portal, Portal::Exits | Portal::ExitsAtOnce) {
break;
}
if portal != Portal::OldEarly && respond().is_err() {
break;
}
if portal == Portal::AnswersAndExits {
break;
}
}
// The portal leaves the bus: the bus sends `NameOwnerChanged` for its name.
let _ = server.close();
});
let client = zbus::blocking::connection::Builder::address(address.as_str()).ok()?.build().ok()?;
Some((client, seen, daemon))
@@ -589,7 +575,7 @@ mod tests {
#[test]
fn the_portal_is_asked_on_the_first_file_type_and_answers_the_one_picked() {
let script = vec![(0, Some(("file:///home/me/Art/poster", "PDF-compatible .ai"))), (1, None)];
let Some((conn, seen, mut daemon)) = mock_portal(script, Portal::Current) else {
let Some((conn, seen, _daemon)) = mock_portal(script, Portal::Current) else {
eprintln!("no dbus-daemon: skipped");
return;
};
@@ -599,7 +585,6 @@ mod tests {
assert_eq!(save_within(&conn, &request), Ok(None));
let seen = seen.lock().map(|s| s.clone()).unwrap_or_default();
assert_eq!(seen.first(), Some(&(Some("Untitled-1.vectorcraft".to_string()), Some(request.filters[0].0.clone()))));
let _ = daemon.kill();
}
/// A portal older than 0.9 answers on the request path it returns, and the answer is awaited
@@ -607,13 +592,12 @@ mod tests {
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
#[test]
fn the_answer_is_awaited_on_the_path_the_portal_returns() {
let Some((conn, _seen, mut daemon)) = mock_portal(vec![(0, Some(("file:///tmp/card", "SVG")))], Portal::Old) else {
let Some((conn, _seen, _daemon)) = mock_portal(vec![(0, Some(("file:///tmp/card", "SVG")))], Portal::Old) else {
eprintln!("no dbus-daemon: skipped");
return;
};
let request = request();
assert_eq!(pick_answer(save_within(&conn, &request).unwrap(), &request), ["/tmp/card", "svg"]);
let _ = daemon.kill();
}
/// A portal older than 0.9 can answer before its reply names the request path: the answer is
@@ -622,14 +606,41 @@ mod tests {
#[test]
fn an_answer_that_comes_before_the_path_is_kept() {
let script = vec![(0, Some(("file:///tmp/card", "SVG"))), (1, None)];
let Some((conn, _seen, mut daemon)) = mock_portal(script, Portal::OldEarly) else {
let Some((conn, _seen, _daemon)) = mock_portal(script, Portal::OldEarly) else {
eprintln!("no dbus-daemon: skipped");
return;
};
let request = request();
assert_eq!(pick_answer(save_within(&conn, &request).unwrap(), &request), ["/tmp/card", "svg"]);
assert_eq!(save_within(&conn, &request), Ok(None));
let _ = daemon.kill();
}
/// A portal that leaves the bus after its reply without answering, while its dialog is open or
/// at once, ends the wait with an error, and rfd shows the dialog.
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
#[test]
fn a_portal_that_exits_during_the_dialog_ends_the_wait() {
for portal in [Portal::Exits, Portal::ExitsAtOnce] {
let Some((conn, _seen, _daemon)) = mock_portal(vec![(0, Some(("file:///tmp/card", "SVG")))], portal) else {
eprintln!("no dbus-daemon: skipped");
return;
};
assert_eq!(save_within(&conn, &request()), Err("the desktop portal disappeared while waiting for its answer".to_string()));
}
}
/// A portal that answers and then leaves the bus: the save reads the answer. Whether the answer
/// or the bus's report comes first depends on timing here; `portal_request`'s
/// `a_queued_answer_wins_over_the_portal_leaving` queues both before the wait.
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
#[test]
fn an_answer_sent_just_before_the_portal_exits_is_kept() {
let Some((conn, _seen, _daemon)) = mock_portal(vec![(0, Some(("file:///tmp/card", "SVG")))], Portal::AnswersAndExits) else {
eprintln!("no dbus-daemon: skipped");
return;
};
let request = request();
assert_eq!(pick_answer(save_within(&conn, &request).unwrap(), &request), ["/tmp/card", "svg"]);
}
/// The labels go to the dialog in the interface's language, which is how the answer is matched.
+51 -6
View File
@@ -220,8 +220,10 @@ fn the_app_title_bar_preference_gives_the_app_frame_on_desktop_frames() {
}
/// The frame a start uses: the preference turns the desktop frame the probe chose into the app frame
/// with the default window buttons, a probed app frame keeps its own buttons, and the desktop frame
/// stays where the app frame is not drawn. System Title Bar takes precedence over the preference.
/// with the default window buttons, an app frame the desktop left to the app keeps its own buttons,
/// one that `VECTORCRAFT_TITLEBAR=app` forced or the preference kept through XWayland gets the
/// default buttons, and the desktop frame stays
/// where the app frame is not drawn. System Title Bar takes precedence over the preference.
#[test]
fn the_start_frame_applies_the_app_title_bar_preference() {
use craft_window::{Button, Frame, Layout};
@@ -233,9 +235,10 @@ fn the_start_frame_applies_the_app_title_bar_preference() {
((Frame::Desktop, None, true, true), Frame::App(Layout::default())),
((Frame::App(gnome.clone()), None, false, false), Frame::App(gnome.clone())),
((Frame::App(gnome.clone()), None, true, false), Frame::Desktop),
((Frame::App(gnome.clone()), None, true, true), Frame::App(gnome.clone())),
((Frame::App(gnome.clone()), None, true, true), Frame::App(Layout::default())),
((Frame::Desktop, Some(false), false, true), Frame::Desktop),
((Frame::App(gnome.clone()), Some(true), true, false), Frame::App(gnome.clone())),
((Frame::App(gnome.clone()), Some(true), true, false), Frame::App(Layout::default())),
((Frame::App(gnome.clone()), Some(true), false, false), Frame::App(Layout::default())),
];
for ((probed, overridden, forced_to_x11, opted_into_app), expected) in cases {
let label = format!("{probed:?} {overridden:?} {forced_to_x11} {opted_into_app}");
@@ -246,6 +249,30 @@ fn the_start_frame_applies_the_app_title_bar_preference() {
assert!(!super::custom_titlebar_from(&both, true), "System Title Bar takes precedence over the app title bar preference");
}
/// The app bar's caption buttons follow the window-button layout of the app frame on Linux and the
/// BSDs (Close alone at the right, or all three at the left with Close outermost); the desktop frame,
/// macOS and Windows keep all three at the right.
#[test]
fn the_caption_buttons_follow_the_frame_layout() {
use craft_window::{Button, Frame, Layout};
use vectorcraft_ui_egui::titlebar::{Caption, CaptionLayout};
let close_only = Layout::parse("appmenu:close");
let at_left = Layout { left: vec![Button::Close, Button::Minimize, Button::Maximize], right: vec![] };
let split = Layout { left: vec![Button::Close], right: vec![Button::Minimize, Button::Maximize] };
let probed = [
(close_only, CaptionLayout { left: vec![], right: vec![Caption::Close] }),
(at_left, CaptionLayout { left: vec![Caption::Close, Caption::Minimize, Caption::Maximize], right: vec![] }),
(split, CaptionLayout { left: vec![Caption::Close], right: vec![Caption::Minimize, Caption::Maximize] }),
];
for (layout, expected) in probed {
let shown = super::caption_layout_from(&Frame::App(layout.clone()));
let expected = if cfg!(any(target_os = "macos", target_os = "windows")) { CaptionLayout::default() } else { expected };
assert_eq!(shown, expected, "{layout:?}");
}
assert_eq!(super::caption_layout_from(&Frame::Desktop), CaptionLayout::default());
assert_eq!(CaptionLayout::default().right, vec![Caption::Minimize, Caption::Maximize, Caption::Close]);
}
/// `VECTORCRAFT_TITLEBAR` chooses the frame for the run it is set in, with System Title Bar off and
/// on. The saved preference still decides while the variable is unset.
#[test]
@@ -303,7 +330,7 @@ fn the_titlebar_variable_decides_the_frame_before_the_window_opens() {
let off = ui_state_with_prefs(serde_json::json!({"systemTitleBar": false}));
let on = ui_state_with_prefs(serde_json::json!({"systemTitleBar": true}));
for (saved, opted_into_system) in [(None, false), (Some(&off), false), (Some(&on), true)] {
let custom = super::custom_titlebar(saved);
let (custom, _) = super::custom_titlebar(saved);
let expected = match value.as_str() {
_ if not_read => !cfg!(target_os = "macos") && !opted_into_system,
"app" => true,
@@ -312,7 +339,7 @@ fn the_titlebar_variable_decides_the_frame_before_the_window_opens() {
// `craft-window` probe decides, the same with System Title Bar off as with no saved
// preferences.
_ if opted_into_system => false,
_ => super::custom_titlebar(None),
_ => super::custom_titlebar(None).0,
};
assert_eq!(custom, expected, "{value}, preference {opted_into_system}");
assert_eq!(super::native_options(custom).viewport.decorations, Some(!custom), "{value}, preference {opted_into_system}");
@@ -460,3 +487,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);
}
+37 -9
View File
@@ -31,7 +31,7 @@ pub(crate) fn adapter_summary(info: &eframe::wgpu::AdapterInfo) -> String {
format!("{} ({:?}, {:?})", info.name.trim(), info.backend, info.device_type)
}
/// Windows and Linux: no OS title bar; the app bar is the title bar (`vectorcraft_ui_egui::titlebar`).
/// Windows: no OS title bar; the app bar is the title bar (`vectorcraft_ui_egui::titlebar`).
/// macOS keeps its traffic lights over the integrated title strip.
///
/// Used on macOS and Windows (where VectorCraft keeps today's frame regardless of the
@@ -68,18 +68,45 @@ pub(crate) fn app_draws_frame(probed_app: bool, overridden: Option<bool>, forced
}
/// The frame this start uses, before the System Title Bar preference is applied
/// ([`custom_titlebar_from`]): [`app_draws_frame`] applied to the frame the probe chose. A probed
/// app frame keeps its window-button layout; an app frame the probe did not choose gets the default
/// layout, since `custom_titlebar_from` reads only which frame it is.
/// ([`custom_titlebar_from`]): [`app_draws_frame`] applied to the frame the probe chose. An app frame
/// the desktop left to the app (no `VECTORCRAFT_TITLEBAR` override, not forced onto XWayland) keeps
/// its window-button layout. An app frame turned on by `VECTORCRAFT_TITLEBAR=app` or by VectorCraft
/// Title Bar on Every Desktop gets the default layout: on those desktops the `button-layout` key that `craft-window` reads can
/// hold its schema default (`appmenu:close`) rather than the desktop's own buttons.
pub(crate) fn start_frame(probed: craft_window::Frame, overridden: Option<bool>, forced_to_x11: bool, opted_into_app: bool) -> craft_window::Frame {
let probed_app = matches!(probed, craft_window::Frame::App(_));
match (app_draws_frame(probed_app, overridden, forced_to_x11, opted_into_app), probed) {
(true, frame @ craft_window::Frame::App(_)) => frame,
(true, craft_window::Frame::Desktop) => craft_window::Frame::App(craft_window::Layout::default()),
(true, frame @ craft_window::Frame::App(_)) if overridden.is_none() && !forced_to_x11 => frame,
(true, _) => craft_window::Frame::App(craft_window::Layout::default()),
(false, _) => craft_window::Frame::Desktop,
}
}
/// Where the app bar puts its caption buttons for `frame`: on Linux and the BSDs, the window-button
/// layout of an app frame, which `craft-window` reads from the desktop (the `button-layout` key of
/// `org.gnome.desktop.wm.preferences`); otherwise all three at the right. Each list is copied in the
/// key's order, first item leftmost, so `close,minimize,maximize:` puts Close at the left edge.
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
pub(crate) fn caption_layout_from(frame: &craft_window::Frame) -> vectorcraft_ui_egui::titlebar::CaptionLayout {
use vectorcraft_ui_egui::titlebar::{Caption, CaptionLayout};
let caption = |b: &craft_window::Button| match b {
craft_window::Button::Minimize => Caption::Minimize,
craft_window::Button::Maximize => Caption::Maximize,
craft_window::Button::Close => Caption::Close,
};
match frame.layout() {
Some(layout) => CaptionLayout { left: layout.left.iter().map(caption).collect(), right: layout.right.iter().map(caption).collect() },
None => CaptionLayout::default(),
}
}
/// macOS and Windows: all three caption buttons at the right, whatever the probe says (see
/// [`custom_titlebar_from`]).
#[cfg(any(target_os = "macos", target_os = "windows"))]
pub(crate) fn caption_layout_from(_frame: &craft_window::Frame) -> vectorcraft_ui_egui::titlebar::CaptionLayout {
vectorcraft_ui_egui::titlebar::CaptionLayout::default()
}
/// The `craft-window` probe's answer for this process (its override variable is
/// `VECTORCRAFT_TITLEBAR`). The probe runs once; on a Wayland session it opens a connection.
fn probed_choice() -> &'static craft_window::Choice {
@@ -131,7 +158,8 @@ pub(crate) fn custom_titlebar_from(_frame: &craft_window::Frame, opted_into_syst
CUSTOM_TITLEBAR && !opted_into_system
}
/// Whether this start draws its own title bar. Probes the shared `craft-window` crate once (its
/// Whether this start draws its own title bar, and where its caption buttons go
/// ([`caption_layout_from`]). Probes the shared `craft-window` crate once (its
/// override variable is `VECTORCRAFT_TITLEBAR`) and combines its decision with the saved System
/// Title Bar preference, which does not apply while the variable is set to `app`, `system` or
/// `desktop`. Call once at startup,
@@ -142,7 +170,7 @@ pub(crate) fn custom_titlebar_from(_frame: &craft_window::Frame, opted_into_syst
/// on X11, whose window manager draws the frame — so when XWayland is being forced, keep the native
/// frame, the same as a real X11 session. A recognized `VECTORCRAFT_TITLEBAR` override still wins,
/// and so does VectorCraft Title Bar on Every Desktop ([`app_draws_frame`]).
pub(crate) fn custom_titlebar(saved: Option<&vectorcraft_ui_egui::UiState>) -> bool {
pub(crate) fn custom_titlebar(saved: Option<&vectorcraft_ui_egui::UiState>) -> (bool, vectorcraft_ui_egui::titlebar::CaptionLayout) {
let choice = probed_choice();
let opted_into_system = system_title_bar_applies(opted_into_system_title_bar(saved), titlebar_from_env());
// macOS and Windows never read VectorCraft Title Bar on Every Desktop (`custom_titlebar_from`
@@ -160,7 +188,7 @@ pub(crate) fn custom_titlebar(saved: Option<&vectorcraft_ui_egui::UiState>) -> b
#[cfg(not(target_os = "linux"))]
let forced_to_x11 = false;
let frame = start_frame(choice.frame().clone(), choice.overridden(), forced_to_x11, opted_into_app);
custom_titlebar_from(&frame, opted_into_system)
(custom_titlebar_from(&frame, opted_into_system), caption_layout_from(&frame))
}
pub(crate) fn native_options(custom_titlebar: bool) -> eframe::NativeOptions {
+5 -1
View File
@@ -78,7 +78,11 @@ fn samples(t: &Track, step: Option<f64>) -> Vec<(Point, Vec2, f64)> {
let pieces = (seg / step).ceil().clamp(1.0, MAX_STEPS) as usize;
for k in 1..pieces {
let u = k as f64 / pieces as f64;
out.push((p.lerp(t.verts[i + 1], u), t.dirs[i], (t.cum[i] + seg * u) / len));
let s = t.cum[i] + seg * u;
// On a chord of a flattened curve the samples follow the smooth frame through the
// vertices.
let (q, tg) = if t.curved.get(i).copied().unwrap_or(false) { t.frame_in(i, u) } else { (p.lerp(t.verts[i + 1], u), t.dirs[i]) };
out.push((q, tg, s / len));
}
}
}
+33 -2
View File
@@ -762,9 +762,40 @@ pub fn library(doc: &Document) -> Vec<Brush> {
}
/// Parse a stored library value (malformed entries are skipped, values kept within their
/// ranges; see [`Brush::from_json`]).
/// ranges; see [`Brush::from_json`]). A name that repeats is kept by its first brush, and each
/// later brush of that name is numbered ([`number_repeated_names`]).
pub fn parse_library(v: &serde_json::Value) -> Vec<Brush> {
v.as_array().map(|a| a.iter().filter_map(|b| Brush::from_json(b.clone()).ok()).collect()).unwrap_or_default()
let mut lib: Vec<Brush> = v.as_array().map(|a| a.iter().filter_map(|b| Brush::from_json(b.clone()).ok()).collect()).unwrap_or_default();
number_repeated_names(&mut lib);
lib
}
/// Renames the second and later brushes of each repeated name in `lib` to the first "Name 2",
/// "Name 3"… that no brush in `lib` has. The first brush of a name keeps it, so a stroke that names
/// it draws the brush [`find`] gave it before.
fn number_repeated_names(lib: &mut [Brush]) {
let mut seen = std::collections::HashSet::new();
if lib.iter().all(|b| seen.insert(b.name.as_str())) {
return;
}
let mut taken: std::collections::HashSet<String> = lib.iter().map(|b| b.name.clone()).collect();
let mut kept = std::collections::HashSet::new();
// The next number to try for each repeated name, so the brushes of one name try each number
// once between them.
let mut next: std::collections::HashMap<String, u64> = std::collections::HashMap::new();
for b in lib.iter_mut() {
if kept.insert(b.name.clone()) {
continue;
}
let from = next.entry(b.name.clone()).or_insert(2);
// `taken` is finite, so one of the numbers is free.
if let Some((i, name)) = (*from..).map(|i| (i, format!("{} {i}", b.name))).find(|(_, n)| !taken.contains(n)) {
*from = i.saturating_add(1);
taken.insert(name.clone());
kept.insert(name.clone());
b.name = name;
}
}
}
/// Store `lib` as the document's brush library.
+77
View File
@@ -945,6 +945,34 @@ fn library_defaults_store_and_find() {
assert_eq!(unique_name(&lib, "Arrow"), "Arrow 2");
}
/// A stored library that repeats a name reads with the first brush of that name as stored and each
/// later one numbered, past every name the library already has; strokes of the name keep drawing
/// the first brush.
#[test]
fn repeated_brush_names_are_numbered_when_read() {
let mut d = Document::new(100.0, 100.0);
let named = |name: &str, size: f64| Brush { name: name.into(), ..calli(0.0, 100.0, size) };
store(&mut d, &[named("Nib", 1.0), named("Nib 2", 2.0), named("Nib", 3.0), named("Other", 4.0), named("Nib", 5.0), named("Nib 2", 6.0)]);
let lib = library(&d);
let names: Vec<&str> = lib.iter().map(|b| b.name.as_str()).collect();
assert_eq!(names, ["Nib", "Nib 2", "Nib 3", "Other", "Nib 4", "Nib 2 2"]);
let size = |b: &Brush| if let BrushKind::Calligraphic(c) = &b.kind { c.size } else { 0.0 };
assert_eq!(lib.iter().map(size).collect::<Vec<_>>(), [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
assert_eq!(find(&d, "Nib").map(|b| size(&b)), Some(1.0));
assert_eq!(find(&d, "Nib 3").map(|b| size(&b)), Some(3.0));
// Reading again gives the same names, and the numbered library stored again reads as stored.
assert_eq!(library(&d), lib);
store(&mut d, &lib);
assert_eq!(library(&d), lib);
// Many brushes of one name take the numbers in order, past the numbered names the file has.
let many: Vec<Brush> = (0..5000).map(|i| named(if i == 1 { "Nib 3" } else { "Nib" }, 1.0)).collect();
store(&mut d, &many);
let names: Vec<String> = library(&d).into_iter().map(|b| b.name).collect();
assert_eq!(names[..5], ["Nib", "Nib 3", "Nib 2", "Nib 4", "Nib 5"]);
assert_eq!(names.last().map(String::as_str), Some("Nib 5000"));
assert_eq!(names.iter().collect::<std::collections::HashSet<_>>().len(), names.len());
}
#[test]
fn brushes_serde_round_trip() {
let lib = defaults().to_vec();
@@ -1009,6 +1037,26 @@ fn pressed(points: Vec<(f64, f64)>) -> StrokeLayer {
StrokeLayer { pressure: Some(vectorcraft_doc::PressureProfile { points }), ..stroke(1.0) }
}
/// A nib that follows the pen is sampled between the vertices of the flattened path too. Along a
/// curve those samples sit on the curve, and the outline keeps its distance from it.
#[test]
fn pen_driven_nib_outline_follows_the_curve_between_vertices() {
// The top half of a circle of radius 50; a round nib 20 pt across, the same at any pressure.
let (r, half) = (50.0, 10.0);
let c = Point::new(r, r);
let ring = shapes::ellipse(Rect::new(0.0, 0.0, 2.0 * r, 2.0 * r)).to_bezpath();
let half_circle: BezPath = ring.elements().iter().take(3).copied().collect();
let out = stroke_pieces(&Document::new(1.0, 1.0), &pressure_calli(20.0, 0.0), &half_circle, &pressed(vec![(0.0, 0.5), (1.0, 0.5)]));
let mut pts = vec![];
for n in &out {
all_points(n, &mut pts);
}
// Away from the round caps at the two ends, every outline point is `half` from the curve.
let middle = pts.iter().filter(|p| ((p.y - c.y).atan2(p.x - c.x).abs() - std::f64::consts::FRAC_PI_2).abs() <= 1.2);
let worst = middle.map(|p| ((p.distance(c) - (r + half)).abs()).min((p.distance(c) - (r - half)).abs())).fold(0.0, f64::max);
assert!(worst < 0.05, "an outline point strays {worst:.4} pt from the nib's reach");
}
/// #852: with Size on Pressure the nib goes from size − variation at the lightest pressure to
/// size + variation at the heaviest, along the stroke where the pen pressed.
#[test]
@@ -1658,6 +1706,35 @@ fn an_ordinary_stroke_is_unaffected_by_the_budget() {
assert!(anchors(&out) < 2_000_000);
}
/// A straight-sided art brush on a smooth curve draws smooth edges: they do not turn at the smooth
/// anchors the fit puts along them.
#[test]
fn art_brush_edges_stay_smooth_along_a_curve() {
for &(r, w, h, sw) in &[(100.0, 100.0, 10.0, 1.0), (300.0, 100.0, 10.0, 2.0), (30.0, 100.0, 10.0, 1.0), (2000.0, 100.0, 10.0, 1.0)] {
// The top half of a circle, as one open path of two curves.
let ring = shapes::ellipse(Rect::new(0.0, 0.0, 2.0 * r, 2.0 * r)).to_bezpath();
let half_circle: BezPath = ring.elements().iter().take(3).copied().collect();
let out = stroke_pieces(&Document::new(1.0, 1.0), &art_brush(rect_art(w, h), ArtScale::Stretch), &half_circle, &stroke(sw));
let NodeKind::Path { path, .. } = &out[0].kind else { panic!("an art brush on a path draws a path") };
// The turn at each smooth anchor of the edges: the angle between the incoming and the
// outgoing direction. Real corners (the ends of the art) turn by far more than 60°.
let mut kink = 0.0f64;
for sp in &path.subpaths {
for (k, a) in sp.anchors.iter().enumerate().skip(1).take(sp.anchors.len().saturating_sub(2)) {
let h_in = if a.h_in != a.p { a.h_in } else { sp.anchors[k - 1].p };
let h_out = if a.h_out != a.p { a.h_out } else { sp.anchors[k + 1].p };
let (u, v) = (a.p - h_in, h_out - a.p);
if u.hypot() < 1e-9 || v.hypot() < 1e-9 || u.dot(v) < 0.5 * u.hypot() * v.hypot() {
continue;
}
kink = kink.max(u.cross(v).atan2(u.dot(v)).abs().to_degrees());
}
}
assert!(kink < 0.5, "r={r} art={w}x{h} weight {sw}: an edge turns by {kink:.3}° at a smooth anchor");
}
}
/// Anchors under `n`, and how many of them keep a handle (so the segment is a curve).
fn anchors_and_curved(n: &Node) -> (usize, usize) {
let NodeKind::Path { path, .. } = &n.kind else { return (0, 0) };
+346 -35
View File
@@ -1,8 +1,9 @@
//! Arc-length parameterised polylines ("tracks") that brushes lay art along.
//!
//! A track is one flattened subpath. `frame(s)` gives the point and unit tangent at arc length
//! `s`; tangents are blended across the gentle vertices of flattened curves (so warped art bends
//! smoothly) but stay discontinuous at real corners (so art folds there, like Illustrator).
//! `s`. Along a flattened curve the frame runs on a smooth curve through the vertices, so warped
//! art bends smoothly; along a line of the path it stays on the line. At real corners the tangent
//! stays discontinuous, so art folds there.
use vectorcraft_geom::{BezPath, PathEl, Point, Vec2};
@@ -22,6 +23,11 @@ pub struct Track {
pub tangents: Vec<Vec2>,
/// Is the vertex a corner (turn > [`CORNER_DEG`])? Open ends are never corners.
pub corner: Vec<bool>,
/// Does the segment come from flattening a curve (rather than from a line of the path)?
pub curved: Vec<bool>,
/// How far (radians) a curved segment's end tangents may turn from its direction for `frame`
/// to follow a curve through them; 0 for a line.
turn: Vec<f64>,
}
fn unit(v: Vec2) -> Vec2 {
@@ -35,16 +41,53 @@ fn aligned(a: Vec2, b: Vec2) -> bool {
a.dot(b) > 1.0 - 1e-12
}
/// How far a vertex tangent may turn from a chord of a flattened curve, as a multiple of the
/// flattening tolerance over the chord's length. A circular arc needs 4; the rest is slack for
/// flattening that lands a little inside its tolerance.
const TURN_PER_TOL: f64 = 6.0;
/// `t` turned by the smallest angle that brings it within `limit` radians of each `dir`. When no
/// angle satisfies every limit, `t` turns to the middle of the gap between them.
fn held_within(t: Vec2, limits: [Option<(Vec2, f64)>; 2]) -> Vec2 {
let (mut lo, mut hi) = (f64::NEG_INFINITY, f64::INFINITY);
for (d, limit) in limits.into_iter().flatten() {
let to = t.cross(d).atan2(t.dot(d));
lo = lo.max(to - limit);
hi = hi.min(to + limit);
}
let turn = if lo <= hi { 0f64.max(lo).min(hi) } else { (lo + hi) / 2.0 };
if turn == 0.0 || !turn.is_finite() {
return t;
}
let (sin, cos) = turn.sin_cos();
Vec2::new(t.x * cos - t.y * sin, t.x * sin + t.y * cos)
}
/// Left-hand normal in y-down document space (for a path running +x it points +y).
pub fn normal(t: Vec2) -> Vec2 {
Vec2::new(-t.y, t.x)
}
impl Track {
fn new(mut pts: Vec<Point>, closed: bool) -> Option<Track> {
pts.dedup_by(|a, b| a.distance(*b) < 1e-9);
/// `raw` pairs each vertex with the tolerance the segment ending at it was flattened with
/// when it comes from a curve, and `None` when it is a line of the path.
fn new(raw: Vec<(Point, Option<f64>)>, closed: bool) -> Option<Track> {
let mut pts: Vec<Point> = Vec::with_capacity(raw.len());
// `ends_curve[k]`: the flattening tolerance of the segment ending at vertex `k`, when it
// comes from a curve.
let mut ends_curve: Vec<Option<f64>> = Vec::with_capacity(raw.len());
for (p, c) in raw {
// A duplicate vertex adds no segment, so it is dropped with its tolerance.
if pts.last().is_some_and(|q| q.distance(p) < 1e-9) {
continue;
}
pts.push(p);
ends_curve.push(c);
}
let mut closing_curve = None;
if closed && pts.len() > 2 && pts[0].distance(pts[pts.len() - 1]) < 1e-9 {
pts.pop();
closing_curve = ends_curve.pop().flatten();
}
if pts.len() < 2 {
return None;
@@ -52,8 +95,11 @@ impl Track {
let closed = closed && pts.len() > 2;
if closed {
pts.push(pts[0]);
ends_curve.push(closing_curve);
}
let nseg = pts.len() - 1;
let curve_tol: Vec<Option<f64>> = (0..nseg).map(|i| ends_curve.get(i + 1).copied().flatten()).collect();
let curved: Vec<bool> = curve_tol.iter().map(Option::is_some).collect();
let dirs: Vec<Vec2> = (0..nseg).map(|i| unit(pts[i + 1] - pts[i])).collect();
let mut cum = vec![0.0];
for i in 0..nseg {
@@ -62,34 +108,78 @@ impl Track {
let mut tangents = Vec::with_capacity(nseg + 1);
let mut corner = Vec::with_capacity(nseg + 1);
let cos_limit = CORNER_DEG.to_radians().cos();
let seg = |i: usize| (dirs[i], cum[i + 1] - cum[i], curved[i]);
for i in 0..=nseg {
let incoming = if i > 0 {
Some(dirs[i - 1])
Some(seg(i - 1))
} else if closed {
Some(dirs[nseg - 1])
Some(seg(nseg - 1))
} else {
None
};
let outgoing = if i < nseg {
Some(dirs[i])
Some(seg(i))
} else if closed {
Some(dirs[0])
Some(seg(0))
} else {
None
};
match (incoming, outgoing) {
(Some(a), Some(b)) => {
(Some((a, la, ca)), Some((b, lb, cb))) => {
corner.push(a.dot(b) < cos_limit);
tangents.push(unit(a + b));
tangents.push(match (ca, cb) {
// Between two chords of a flattened curve: each direction weighted by the
// length of the other chord, which is the tangent of the circle through
// the vertex and its two neighbors.
(true, true) => unit(a * lb + b * la),
// Where a line of the path meets a curve, the line's direction.
(false, true) => a,
(true, false) => b,
(false, false) => unit(a + b),
});
}
(a, b) => {
// An end of an open track (both `None` only for a track without segments).
corner.push(false);
tangents.push(a.or(b).unwrap_or(Vec2::new(1.0, 0.0)));
tangents.push(a.or(b).map_or(Vec2::new(1.0, 0.0), |(d, _, _)| d));
}
}
}
Some(Track { verts: pts, cum, closed, dirs, tangents, corner })
// An open track's end on a curve continues the bend of its last chord: the tangent there
// is the neighboring vertex's tangent mirrored about the chord, as on the circle through
// the last three vertices.
if !closed && nseg >= 2 {
for (end, inner, d) in [(0, 1, dirs[0]), (nseg, nseg - 1, dirs[nseg - 1])] {
let (s_end, s_inner) = if end == 0 { (0, 1) } else { (nseg - 1, nseg - 2) };
if !corner[inner] && curved[s_end] && curved[s_inner] {
let t = tangents[inner];
tangents[end] = unit(d * (2.0 * d.dot(t)) - t);
}
}
}
// A curve lies within its flattening tolerance `tol` of each of its chords, so its tangent
// at a vertex turns only a little from a chord: at most about `4 * tol / len` on a
// circular arc. Next to a long chord the estimates above can turn much further (a
// straight curve element beside a tight bend), and `frame` would then bow off the chord.
// Between curved chords, each vertex tangent is held within `TURN_PER_TOL * tol / len` of
// both chords. Where a line meets a curve the tangent stays the line's direction, and a
// curved chord whose end tangents turn further than that from it keeps to the chord.
let turn: Vec<f64> = (0..nseg)
.map(|j| match curve_tol.get(j) {
Some(Some(tol)) => (TURN_PER_TOL * tol / (cum[j + 1] - cum[j]).max(1e-12)).min(1.0).asin(),
_ => 0.0,
})
.collect();
for (i, t) in tangents.iter_mut().enumerate() {
let incoming = if i > 0 { Some(i - 1) } else { closed.then_some(nseg - 1) };
let outgoing = if i < nseg { Some(i) } else { closed.then_some(0) };
let sides = [incoming, outgoing];
if corner[i] || sides.iter().flatten().any(|&j| !curved[j]) {
continue;
}
*t = held_within(*t, sides.map(|j| j.map(|j| (dirs[j], turn[j]))));
}
Some(Track { verts: pts, cum, closed, dirs, tangents, corner, curved, turn })
}
pub fn len(&self) -> f64 {
@@ -135,11 +225,11 @@ impl Track {
let n = self.segments();
let s = if self.closed && l > 0.0 { s.rem_euclid(l) } else { s };
if s <= 0.0 && !self.closed {
let t = self.dirs[0];
let t = self.tangents[0];
return (self.verts[0] + t * s, t);
}
if s >= l && !self.closed {
let t = self.dirs[n - 1];
let t = self.tangents[n];
return (self.verts[n] + t * (s - l), t);
}
// Binary search the segment.
@@ -149,10 +239,44 @@ impl Track {
};
let seg = self.cum[i + 1] - self.cum[i];
let u = if seg > 1e-12 { ((s - self.cum[i]) / seg).clamp(0.0, 1.0) } else { 0.0 };
let p = self.verts[i].lerp(self.verts[i + 1], u);
let t0 = if self.corner[i] { self.dirs[i] } else { self.tangents[i] };
let t1 = if self.corner[i + 1] { self.dirs[i] } else { self.tangents[i + 1] };
(p, unit(t0 + (t1 - t0) * u))
self.frame_in(i, u)
}
/// Segment `i`'s direction and the tangents [`Self::frame`] uses at its two ends: the vertex
/// tangents, or the segment's direction at a corner.
fn end_tangents(&self, i: usize) -> Option<(Vec2, Vec2, Vec2)> {
let (&d, &c0, &c1, &t0, &t1) =
(self.dirs.get(i)?, self.corner.get(i)?, self.corner.get(i + 1)?, self.tangents.get(i)?, self.tangents.get(i + 1)?);
Some((d, if c0 { d } else { t0 }, if c1 { d } else { t1 }))
}
/// Point and unit tangent at the fraction `u` (0 to 1) of segment `i`, as [`Self::frame`]
/// gives them. `i` must be below [`Self::segments`].
pub fn frame_in(&self, i: usize, u: f64) -> (Point, Vec2) {
let (Some(&p0), Some(&p1), Some((d, t0, t1))) = (self.verts.get(i), self.verts.get(i + 1), self.end_tangents(i)) else {
return (self.verts.last().copied().unwrap_or(Point::ZERO), Vec2::new(1.0, 0.0));
};
let seg = self.cum.get(i + 1).zip(self.cum.get(i)).map_or(0.0, |(b, a)| b - a);
if aligned(t0, d) && aligned(t1, d) {
return (p0.lerp(p1, u), d);
}
// The tangents may turn this far from a curved chord, a little beyond it for rounding.
let within = self.turn.get(i).map_or(-1.0, |a| a.sin() + 1e-9);
let bends = |t: Vec2| t.dot(d) <= 0.0 || t.cross(d).abs() > within;
if !self.curved.get(i).copied().unwrap_or(false) || bends(t0) || bends(t1) {
// A line of the path, or a curved chord at a sharper turn than the curve can make
// there: the point stays on it, and the tangent turns across it toward the vertex
// tangents.
return (p0.lerp(p1, u), unit(t0 + (t1 - t0) * u));
}
// On a chord of a flattened curve the frame follows the cubic through both vertices with
// their tangents, at the chord's length per unit of `u`. Its position and tangent then
// meet those of the next segment at each vertex.
let (u2, u3) = (u * u, u * u * u);
let (m0, m1) = (t0 * seg, t1 * seg);
let p = p0 + (p1 - p0) * (3.0 * u2 - 2.0 * u3) + m0 * (u3 - 2.0 * u2 + u) + m1 * (u3 - u2);
let dp = (p1 - p0) * (6.0 * u - 6.0 * u2) + m0 * (3.0 * u2 - 4.0 * u + 1.0) + m1 * (3.0 * u2 - 2.0 * u);
(p, unit(dp))
}
/// The point at arc length `s`, offset `d` along the left normal.
@@ -183,8 +307,8 @@ impl Track {
if self.closed && (lo < -1e-9 || hi > l + 1e-9) {
return false;
}
// Past an open track's ends `frame` extrapolates along the end segment's direction, so
// those segments are part of the span too.
// Past an open track's ends `frame` extrapolates along the end tangent, which is checked
// against the end segment's direction below, so those segments are part of the span too.
let ends = [(!self.closed && lo < 0.0).then_some(0), (!self.closed && hi > l).then(|| n - 1)];
let touched = (0..n).filter(|&i| {
let (a, b) = (self.cum.get(i), self.cum.get(i + 1));
@@ -193,9 +317,7 @@ impl Track {
let mut dir: Option<Vec2> = None;
let mut any = false;
for i in touched.chain(ends.into_iter().flatten()) {
let (Some(&d), Some(&t0), Some(&t1), Some(&c0), Some(&c1)) =
(self.dirs.get(i), self.tangents.get(i), self.tangents.get(i + 1), self.corner.get(i), self.corner.get(i + 1))
else {
let Some((d, t0, t1)) = self.end_tangents(i) else {
return false;
};
if dir.is_some_and(|first: Vec2| !aligned(first, d)) {
@@ -203,11 +325,11 @@ impl Track {
}
dir = Some(d);
any = true;
// `frame` blends the two vertex tangents across the segment unless the vertex is a
// corner, where it uses the segment's own direction. So a neighbour outside the span
// can still bend the tangent inside it, and checking the directions alone would miss
// that: segments d, d, e leave vertex 2's tangent at unit(d + e).
if !(c0 || aligned(t0, d)) || !(c1 || aligned(t1, d)) {
// `frame` blends the two end tangents across a line, and follows a curve through them
// on a curved chord. So a neighbour outside the span can still bend the tangent
// inside it, and checking the directions alone would miss that: segments d, d, e
// leave vertex 2's tangent at unit(d + e).
if !aligned(t0, d) || !aligned(t1, d) {
return false;
}
}
@@ -220,9 +342,10 @@ const MAX_FLATTENED: usize = 4_000_000;
/// Flatten `bp` into tracks (one per subpath) with `tol` accuracy.
pub fn tracks(bp: &BezPath, tol: f64) -> Vec<Track> {
let tol = tol.max(1e-4);
let mut out = vec![];
let mut cur: Vec<Point> = vec![];
let flush = |cur: &mut Vec<Point>, closed: bool, out: &mut Vec<Track>| {
let mut cur: Vec<(Point, Option<f64>)> = vec![];
let flush = |cur: &mut Vec<(Point, Option<f64>)>, closed: bool, out: &mut Vec<Track>| {
if let Some(t) = Track::new(std::mem::take(cur), closed) {
out.push(t);
}
@@ -236,19 +359,40 @@ pub fn tracks(bp: &BezPath, tol: f64) -> Vec<Track> {
return out;
}
let mut els = vec![];
// When the element being flattened is a curve, the tolerance `flatten` uses for it: `flatten`
// pulls each element before it reports that element's lines, and raises the tolerance of a
// long curve as `vectorcraft_geom::flatten` describes.
let in_curve = std::cell::Cell::new(None);
let (last, start) = (std::cell::Cell::new(Point::ZERO), std::cell::Cell::new(Point::ZERO));
let source = bp.iter().inspect(|el| {
let from = last.get();
let (curve, to) = match *el {
PathEl::MoveTo(p) => {
start.set(p);
(None, p)
}
PathEl::LineTo(p) => (None, p),
PathEl::QuadTo(a, p) => (Some(from.distance(a) + a.distance(p)), p),
PathEl::CurveTo(a, b, p) => (Some(from.distance(a) + a.distance(b) + b.distance(p)), p),
PathEl::ClosePath => (None, start.get()),
};
last.set(to);
let per = vectorcraft_geom::MAX_FLATTEN_PER_CURVE * vectorcraft_geom::MAX_FLATTEN_PER_CURVE;
in_curve.set(curve.map(|length| if length.is_finite() { tol.max(length / per) } else { f64::INFINITY }));
});
// Guarded: kurbo works out every subdivision of a curve even when the callback drops them.
vectorcraft_geom::flatten(bp.iter(), tol.max(1e-4), |el| {
vectorcraft_geom::flatten(source, tol, |el| {
if els.len() < MAX_FLATTENED {
els.push(el);
els.push((el, in_curve.get()));
}
});
for el in els {
for (el, from_curve) in els {
match el {
PathEl::MoveTo(p) => {
flush(&mut cur, false, &mut out);
cur.push(p);
cur.push((p, None));
}
PathEl::LineTo(p) => cur.push(p),
PathEl::LineTo(p) => cur.push((p, from_curve)),
PathEl::ClosePath => flush(&mut cur, true, &mut out),
_ => {}
}
@@ -368,6 +512,173 @@ mod tests {
assert_eq!(t.map(110.0, 0.0), Point::new(110.0, 0.0));
}
/// Between two lines that meet at a gentle turn, the frame stays on the lines: only the chords
/// of a flattened curve are smoothed. Where a line meets a curve at a gentle turn, the frame
/// stays on the line with the line's direction, and its tangent does not jump at the join.
#[test]
fn a_polylines_frame_stays_on_its_lines() {
// A line, then a line or a nearly straight curve at a 20° turn, below the corner angle, so
// the vertex is not a corner.
let turn = 20f64.to_radians();
let (c, s) = (100.0 * turn.cos(), 100.0 * turn.sin());
for curve in [false, true] {
let mut bp = BezPath::new();
bp.move_to((0.0, 0.0));
bp.line_to((100.0, 0.0));
if curve {
bp.curve_to((100.0 + c / 3.0, s / 3.0 + 0.5), (100.0 + 2.0 * c / 3.0, 2.0 * s / 3.0 + 0.5), (100.0 + c, s));
} else {
bp.line_to((100.0 + c, s));
}
let t = &tracks(&bp, 0.05)[0];
for at in [10.0, 30.0, 50.0, 70.0, 90.0] {
let (p, tg) = t.frame(at);
assert!(p.y.abs() < 1e-9 && (p.x - at).abs() < 1e-9, "curve {curve}: at {at} the frame left the first line: {p:?}");
if curve {
assert!(tg.y.abs() < 1e-12, "at {at} the line's tangent turned toward the curve: {tg:?}");
}
}
if curve {
// The curve's first chord keeps to the chord rather than bending toward the line.
let (a, b) = (t.cum[1], t.cum[2]);
let (p, q) = (t.verts[1], t.verts[2]);
let mid = t.frame((a + b) / 2.0).0;
assert!((mid - p.midpoint(q)).hypot() < 1e-9, "the first curve chord bows: {mid:?}");
}
let (before, after) = (t.frame(100.0 - 1e-7).1, t.frame(100.0 + 1e-7).1);
assert!(before.dot(after) > 1.0 - 1e-9, "curve {curve}: the tangent jumps at the join: {before:?} {after:?}");
}
}
/// A curve of no length between two lines leaves them lines.
#[test]
fn a_curve_of_no_length_leaves_a_line_a_line() {
let turn = 20f64.to_radians();
let mut bp = BezPath::new();
bp.move_to((0.0, 0.0));
bp.line_to((100.0, 0.0));
bp.curve_to((100.0, 0.0), (100.0, 0.0), (100.0, 0.0));
bp.line_to((100.0 + 100.0 * turn.cos(), 100.0 * turn.sin()));
let t = &tracks(&bp, 0.05)[0];
assert!(t.curved.iter().all(|c| !c), "no segment is a curve: {:?}", t.curved);
for at in [10.0, 50.0, 90.0] {
let (p, _) = t.frame(at);
assert!(p.y.abs() < 1e-9 && (p.x - at).abs() < 1e-9, "at {at} the frame left the first line: {p:?}");
}
}
/// Where a line joins a curve smoothly, the line keeps its direction up to the join.
#[test]
fn a_line_into_a_smooth_curve_keeps_its_direction() {
// A line along y = 0 into a quarter circle of radius 50 that starts along +x.
let r = 50.0;
let mut bp = BezPath::new();
bp.move_to((-100.0, 0.0));
bp.line_to((0.0, 0.0));
bp.curve_to((r * K, 0.0), (r, r - r * K), (r, r));
let t = &tracks(&bp, 0.05)[0];
for s in [10.0, 50.0, 90.0, 99.0] {
let (p, tg) = t.frame(s);
assert!(p.y.abs() < 1e-9 && tg.y.abs() < 1e-9, "at {s} the line's frame turned: {p:?} {tg:?}");
}
}
/// The handle length of a cubic quarter circle.
const K: f64 = 0.552_284_749_8;
/// A curve element whose handles lie on its chord is a line drawn as a curve. Next to a tight
/// bend, at either end of a track, the frame along it stays within the flattening tolerance
/// of the line.
#[test]
fn a_straight_curve_element_beside_a_tight_bend_stays_on_its_line() {
let tol = 0.05;
for bend_first in [false, true] {
// A 200 pt line along y = 0 drawn as a cubic, joined smoothly to a quarter circle of
// radius 5 that turns toward +y.
let mut bp = BezPath::new();
if bend_first {
bp.move_to((-5.0, -5.0));
bp.curve_to((-5.0, -5.0 + 5.0 * K), (-5.0 * K, 0.0), (0.0, 0.0));
bp.curve_to((50.0, 0.0), (150.0, 0.0), (200.0, 0.0));
} else {
bp.move_to((0.0, 0.0));
bp.curve_to((50.0, 0.0), (150.0, 0.0), (200.0, 0.0));
bp.curve_to((200.0 + 5.0 * K, 0.0), (205.0, 5.0 - 5.0 * K), (205.0, 5.0));
}
let t = &tracks(&bp, tol)[0];
// The bend lies outside 0 <= x <= 200, so every frame point in that range is on the
// line's stretch of the track.
let on_line: Vec<(Point, Vec2)> =
(0..=2000).map(|k| t.frame(t.len() * k as f64 / 2000.0)).filter(|(p, _)| (0.0..=200.0).contains(&p.x)).collect();
let worst = on_line.iter().map(|(p, _)| p.y.abs()).fold(0.0, f64::max);
assert!(worst <= 2.0 * tol, "bend first {bend_first}: the frame strays {worst:.4} pt off the line");
// Along the line the tangent turns by no more than the line's flattening allows.
let lean = on_line.iter().map(|(_, tg)| tg.y.abs()).fold(0.0, f64::max);
assert!(lean <= 0.01, "bend first {bend_first}: the tangent turns {lean:.4} off the line");
}
}
/// A curve long enough that flattening raises its tolerance still has its frame follow the
/// curve between the vertices, not the chords.
#[test]
fn a_long_curve_flattened_coarser_is_still_followed() {
// A line along y = 0 into a cubic quarter circle of radius 5,000,000 that starts along +x.
let r = 5.0e6;
let curve = kurbo::CubicBez::new((0.0, 0.0), (r * K, 0.0), (r, r - r * K), (r, r));
let mut bp = BezPath::new();
bp.move_to((-100.0, 0.0));
bp.line_to((0.0, 0.0));
bp.curve_to(curve.p1, curve.p2, curve.p3);
let t = &tracks(&bp, 0.05)[0];
let worst = (1..400)
.map(|k| t.frame(100.0 + (t.len() - 100.0) * k as f64 / 400.0).0)
.map(|p| kurbo::ParamCurveNearest::nearest(&curve, p, 1e-9).distance_sq.sqrt())
.fold(0.0, f64::max);
assert!(worst < 0.05, "the frame strays {worst:.4} pt from the curve");
}
/// A closed curve is smooth across its seam: the frame stays on the circle and at right angles
/// to its radius all the way round, the start included.
#[test]
fn a_closed_curves_frame_is_smooth_across_its_seam() {
let (r, tol) = (50.0, 0.05);
let mut bp = BezPath::new();
bp.move_to((r, 0.0));
bp.curve_to((r, r * K), (r * K, r), (0.0, r));
bp.curve_to((-r * K, r), (-r, r * K), (-r, 0.0));
bp.curve_to((-r, -r * K), (-r * K, -r), (0.0, -r));
bp.curve_to((r * K, -r), (r, -r * K), (r, 0.0));
bp.close_path();
let t = &tracks(&bp, tol)[0];
assert!(t.closed && t.curved.iter().all(|c| *c), "every chord of the circle is a chord of a curve");
for k in -20..=20 {
let (p, tg) = t.frame(k as f64 * 0.37);
let radial = p.to_vec2() / p.to_vec2().hypot();
assert!((p.to_vec2().hypot() - r).abs() <= tol, "at {k} the frame is off the circle: {p:?}");
assert!(tg.dot(radial).abs() < 0.5f64.to_radians().sin(), "at {k} the tangent leans off the circle: {tg:?}");
}
}
/// A closed path whose last side is the implicit line back to the start keeps that line
/// straight.
#[test]
fn an_implicit_closing_line_is_not_a_curve() {
let r = 50.0;
let mut bp = BezPath::new();
bp.move_to((r, 0.0));
bp.curve_to((r, r * K), (r * K, r), (0.0, r));
bp.curve_to((-r * K, r), (-r, r * K), (-r, 0.0));
bp.close_path();
let t = &tracks(&bp, 0.05)[0];
assert!(t.closed);
assert_eq!(t.curved.last(), Some(&false), "the closing line is a line");
let n = t.segments();
for u in [0.1, 0.5, 0.9] {
let (p, _) = t.frame(t.cum[n - 1] + (t.cum[n] - t.cum[n - 1]) * u);
assert!(p.y.abs() < 1e-9, "the frame leaves the closing line: {p:?}");
}
}
#[test]
fn closed_square_has_four_corners() {
let mut bp = BezPath::new();
+1 -1
View File
@@ -672,7 +672,7 @@ impl<'a> Scene<'a> {
self.shape(n, &bp, *rule);
}
NodeKind::Text(t) => self.text(n, t),
NodeKind::Image(im) => self.image(im),
NodeKind::Image(im) => self.image(&self.doc.shown_image(n, im)),
NodeKind::SymbolInstance { symbol, xf } => {
let doc = self.doc;
if self.symbol_nodes >= vectorcraft_doc::MAX_SYMBOL_NODES {
+4 -2
View File
@@ -2,7 +2,8 @@
//! gamut checks and soft-proof transforms.
//!
//! * **RGB working spaces** are ICC matrix/shaper profiles via [`moxcms`] (sRGB, Wide Gamut RGB
//! (1998 primaries), Display P3, ProPhoto RGB) or user `.icc` files. Display output is sRGB.
//! (1998 primaries), Display P3, ProPhoto RGB) or user `.icc` files. Display output is sRGB;
//! the desktop canvas converts it into the display's own profile last ([`display`]).
//! * **CMYK spaces:** [`GENERIC_CMYK`] is our own documented parametric press model
//! ([`generic`]); [`DEVICE_CMYK`] is the old profile-free formula (kept for exact legacy numbers);
//! any CMYK `.icc` the user loads goes through `moxcms` (LUT-based profiles).
@@ -10,6 +11,7 @@
//! the profiles [`use_document_profiles`] last put in place of the working spaces;
//! [`crate::Color::to_rgb`] uses them. Code that needs deterministic numbers builds its own [`Cms`] with [`Cms::new`].
pub mod display;
pub mod generic;
pub mod icc;
pub mod lab;
@@ -531,7 +533,7 @@ impl Cms {
}
}
/// Gamut warning: can this colour be printed in the working CMYK space?
/// Gamut warning: can this color be printed in this context's CMYK space?
pub fn out_of_gamut(&self, c: &Color) -> bool {
self.gamut_error(c) > GAMUT_THRESHOLD
}
+327
View File
@@ -0,0 +1,327 @@
//! The canvas's last step before the screen: the sRGB the canvas draws, converted into a display's
//! ICC profile (Preferences › Performance › Use Monitor Profile for Canvas).
//!
//! The display profile is a destination only. Document colors, proofs, exports and the web build
//! keep their sRGB output; a soft proof is applied first, then this conversion.
//!
//! [`DisplayTransform::from_icc`] accepts an RGB display-class (`mntr`) profile of at most
//! [`MAX_PROFILE_BYTES`] whose declared length fits the data and from which a transform can be built.
//! The conversion is relative colorimetric, sampled once into a [`LUT_N`]³ table, so drawing a frame
//! costs a table lookup per pixel and never builds a transform.
use std::hash::{Hash, Hasher};
use super::{Intent, ProfileKind, icc::IccProfile};
/// The largest display profile read: VectorCraft's own limit. Display profiles are a few kilobytes
/// (matrix/shaper) to a few hundred (table-based).
pub const MAX_PROFILE_BYTES: usize = 1 << 20;
/// Grid points per channel of the conversion table.
const LUT_N: usize = 33;
/// Why a display profile can't be used. The canvas then stays sRGB.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ProfileError {
/// More bytes than [`MAX_PROFILE_BYTES`].
TooLarge(usize),
/// No ICC header (`acsp` signature) or a header cut short.
NotIcc,
/// The header's length is shorter than a header or longer than the data.
BadLength { declared: usize, len: usize },
/// The profile class isn't a display's (`mntr`): an input, output or other profile.
NotDisplay(String),
/// The profile's data color space isn't RGB.
NotRgb(String),
/// The profile doesn't parse.
Unreadable(String),
/// No conversion from sRGB into the profile can be built.
NoTransform,
}
impl std::fmt::Display for ProfileError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::TooLarge(n) => write!(f, "the profile is {n} bytes, more than the {MAX_PROFILE_BYTES} a display profile may have"),
Self::NotIcc => f.write_str("the file is not an ICC profile"),
Self::BadLength { declared, len } => write!(f, "the profile's header gives a length of {declared} bytes for {len} bytes of data"),
Self::NotDisplay(class) => write!(f, "the profile's class is `{class}`, not a display profile (`mntr`)"),
Self::NotRgb(space) => write!(f, "the profile's color space is `{space}`, not RGB"),
Self::Unreadable(e) => write!(f, "the profile can't be read: {e}"),
Self::NoTransform => f.write_str("no conversion into the profile can be built"),
}
}
}
/// Four header bytes as text, for an error message.
fn signature(b: &[u8]) -> String {
String::from_utf8_lossy(b).trim_end().to_string()
}
/// sRGB → a display profile, as a table.
pub struct DisplayTransform {
name: String,
fingerprint: u64,
/// `LUT_N`³ display values, red slowest; `None` when the profile shows sRGB unchanged (every
/// grid point within half an 8-bit step of itself).
table: Option<Vec<[f32; 3]>>,
}
impl std::fmt::Debug for DisplayTransform {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DisplayTransform").field("name", &self.name).field("identity", &self.is_identity()).finish()
}
}
impl DisplayTransform {
/// Checks `bytes` as a display profile, as [`Self::from_icc`] does, without building the
/// conversion table.
pub fn check(bytes: &[u8]) -> Result<(), ProfileError> {
Self::parse(bytes).map(|_| ())
}
/// Checks `bytes` as a display profile and builds the conversion into it.
pub fn from_icc(bytes: &[u8]) -> Result<Self, ProfileError> {
let (profile, bytes) = Self::parse(bytes)?;
let to_display =
|rgb: [f32; 3]| profile.from_srgb(rgb, Intent::RelativeColorimetric).and_then(|v| Some([*v.first()?, *v.get(1)?, *v.get(2)?]));
let s = (LUT_N - 1) as f32;
let mut table = Vec::with_capacity(LUT_N.pow(3));
for r in 0..LUT_N {
for g in 0..LUT_N {
for b in 0..LUT_N {
let rgb = [r as f32 / s, g as f32 / s, b as f32 / s];
table.push(to_display(rgb).ok_or(ProfileError::NoTransform)?);
}
}
}
let grid = |i: usize| [i / (LUT_N * LUT_N), i / LUT_N % LUT_N, i % LUT_N].map(|v| v as f32 / s);
let identity = table.iter().enumerate().all(|(i, v)| v.iter().zip(grid(i)).all(|(a, b)| (a - b).abs() <= 0.5 / 255.0));
let mut h = std::collections::hash_map::DefaultHasher::new();
bytes.hash(&mut h);
Ok(Self { name: profile.name.clone(), fingerprint: h.finish(), table: (!identity).then_some(table) })
}
/// The parsed profile and its bytes up to its declared length, when `bytes` is an RGB display
/// profile from which a conversion can be built.
fn parse(bytes: &[u8]) -> Result<(IccProfile, &[u8]), ProfileError> {
if bytes.len() > MAX_PROFILE_BYTES {
return Err(ProfileError::TooLarge(bytes.len()));
}
if bytes.len() < 132 || bytes.get(36..40) != Some(b"acsp") {
return Err(ProfileError::NotIcc);
}
let declared = bytes.get(0..4).map_or(0, |b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]) as usize);
if declared < 132 || declared > bytes.len() {
return Err(ProfileError::BadLength { declared, len: bytes.len() });
}
let bytes = &bytes[..declared];
if &bytes[12..16] != b"mntr" {
return Err(ProfileError::NotDisplay(signature(&bytes[12..16])));
}
if &bytes[16..20] != b"RGB " {
return Err(ProfileError::NotRgb(signature(&bytes[16..20])));
}
let profile = IccProfile::from_bytes(None, bytes).map_err(|e| ProfileError::Unreadable(e.to_string()))?;
if profile.kind != ProfileKind::Rgb {
return Err(ProfileError::NotRgb(format!("{:?}", profile.kind)));
}
let to_display =
|rgb: [f32; 3]| profile.from_srgb(rgb, Intent::RelativeColorimetric).and_then(|v| Some([*v.first()?, *v.get(1)?, *v.get(2)?]));
if to_display([0.5; 3]).is_none() {
return Err(ProfileError::NoTransform);
}
Ok((profile, bytes))
}
/// The profile's description.
pub fn name(&self) -> &str {
&self.name
}
/// A hash of the profile's bytes, which tells two profiles with the same name apart.
pub fn fingerprint(&self) -> u64 {
self.fingerprint
}
/// The profile shows sRGB unchanged, so nothing is converted.
pub fn is_identity(&self) -> bool {
self.table.is_none()
}
/// One sRGB color (0..1) in the display profile.
pub fn apply(&self, rgb: [f32; 3]) -> [f32; 3] {
let Some(table) = &self.table else { return rgb.map(|v| v.clamp(0.0, 1.0)) };
let n = LUT_N;
let s = (n - 1) as f32;
let p = rgb.map(|v| if v.is_nan() { 0.0 } else { v.clamp(0.0, 1.0) * s });
let i = p.map(|v| (v.floor() as usize).min(n - 2));
let t = [p[0] - i[0] as f32, p[1] - i[1] as f32, p[2] - i[2] as f32];
let mut out = [0.0f32; 3];
for (dr, wr) in [(0, 1.0 - t[0]), (1, t[0])] {
for (dg, wg) in [(0, 1.0 - t[1]), (1, t[1])] {
for (db, wb) in [(0, 1.0 - t[2]), (1, t[2])] {
let w = wr * wg * wb;
if w == 0.0 {
continue;
}
let v = table[((i[0] + dr) * n + i[1] + dg) * n + i[2] + db];
for c in 0..3 {
out[c] += w * v[c];
}
}
}
}
out.map(|v| v.clamp(0.0, 1.0))
}
/// One 8-bit sRGB color in the display profile.
pub fn apply8(&self, rgb: [u8; 3]) -> [u8; 3] {
if self.table.is_none() {
return rgb;
}
self.apply(rgb.map(|v| f32::from(v) / 255.0)).map(|v| (v * 255.0).round() as u8)
}
/// Premultiplied RGBA8 pixels, converted in place. Alpha is kept, and fully transparent
/// pixels are left as they are.
pub fn apply_premultiplied(&self, pixels: &mut [u8]) {
if self.table.is_none() {
return;
}
let mut last_in = [0u8; 4];
let mut last_out = [0u8; 4];
for px in pixels.as_chunks_mut::<4>().0 {
let a = px[3];
if a == 0 {
continue;
}
if *px == last_in {
*px = last_out;
continue;
}
last_in = *px;
let un = |c: u8| if a == 255 { c } else { ((u32::from(c) * 255 + u32::from(a) / 2) / u32::from(a)).min(255) as u8 };
let out = self.apply8([un(px[0]), un(px[1]), un(px[2])]);
for (c, o) in px.iter_mut().zip(out) {
*c = if a == 255 { o } else { ((u32::from(o) * u32::from(a) + 127) / 255) as u8 };
}
last_out = *px;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cms::{DISPLAY_P3, GENERIC_CMYK, SRGB, icc_bytes};
/// `name`'s ICC file, marked as a display profile.
fn display(name: &str) -> Vec<u8> {
let mut b = icc_bytes(name).unwrap().to_vec();
b[12..16].copy_from_slice(b"mntr");
b
}
#[test]
fn a_wide_gamut_display_shows_srgb_red_less_saturated_and_srgb_is_left_alone() {
let p3 = DisplayTransform::from_icc(&display(DISPLAY_P3)).unwrap();
assert!(!p3.is_identity());
assert_eq!(p3.name(), DISPLAY_P3);
// sRGB red is inside Display P3: its display values have green and blue above 0 and less red.
let [r, g, b] = p3.apply8([255, 0, 0]);
assert!(r < 245 && g > 40 && b > 10, "{:?}", [r, g, b]);
// White and black stay where they are (relative colorimetric).
assert_eq!(p3.apply8([255; 3]), [255; 3]);
assert_eq!(p3.apply8([0; 3]), [0; 3]);
let srgb = DisplayTransform::from_icc(&display(SRGB)).unwrap();
assert!(srgb.is_identity());
assert_eq!(srgb.apply8([255, 0, 0]), [255, 0, 0]);
assert_ne!(srgb.fingerprint(), p3.fingerprint());
}
#[test]
fn the_table_matches_the_profile_between_its_grid_points() {
let bytes = display(DISPLAY_P3);
let p3 = DisplayTransform::from_icc(&bytes).unwrap();
let profile = IccProfile::from_bytes(None, &bytes).unwrap();
for rgb in [[0.1, 0.7, 0.33], [0.9, 0.05, 0.6], [0.47, 0.47, 0.47], [0.0, 0.2, 1.0]] {
let want = profile.from_srgb(rgb, Intent::RelativeColorimetric).unwrap();
let got = p3.apply(rgb);
for c in 0..3 {
assert!((got[c] - want[c]).abs() < 1.0 / 255.0, "{rgb:?}: {got:?} vs {want:?}");
}
}
}
#[test]
fn premultiplied_pixels_keep_their_alpha_and_transparent_ones_stay_empty() {
let p3 = DisplayTransform::from_icc(&display(DISPLAY_P3)).unwrap();
let mut px = vec![255, 0, 0, 255, 128, 0, 0, 128, 0, 0, 0, 0, 255, 0, 0, 255];
p3.apply_premultiplied(&mut px);
let opaque = p3.apply8([255, 0, 0]);
assert_eq!(&px[0..4], &[opaque[0], opaque[1], opaque[2], 255]);
assert_eq!(&px[12..16], &px[0..4], "a repeated pixel converts the same");
assert_eq!(px[7], 128);
// Half-covered red: the same color at half coverage, within rounding.
for c in 0..3 {
assert!((i32::from(px[4 + c]) - i32::from(opaque[c]) / 2).abs() <= 1, "{:?}", &px[4..8]);
}
assert_eq!(&px[8..12], &[0, 0, 0, 0]);
}
#[test]
fn profiles_that_are_not_rgb_display_profiles_are_refused() {
let cmyk = icc_bytes(GENERIC_CMYK).unwrap().to_vec();
assert!(matches!(DisplayTransform::from_icc(&cmyk), Err(ProfileError::NotDisplay(_))));
let mut cmyk_display = cmyk.clone();
cmyk_display[12..16].copy_from_slice(b"mntr");
assert!(matches!(DisplayTransform::from_icc(&cmyk_display), Err(ProfileError::NotRgb(s)) if s == "CMYK"));
let mut input = display(DISPLAY_P3);
input[12..16].copy_from_slice(b"scnr");
assert_eq!(DisplayTransform::from_icc(&input).unwrap_err(), ProfileError::NotDisplay("scnr".into()));
}
#[test]
fn malformed_short_and_oversized_data_is_refused() {
assert_eq!(DisplayTransform::from_icc(&[]).unwrap_err(), ProfileError::NotIcc);
assert_eq!(DisplayTransform::from_icc(&[0; 132]).unwrap_err(), ProfileError::NotIcc);
let good = display(DISPLAY_P3);
assert_eq!(DisplayTransform::from_icc(&good[..100]).unwrap_err(), ProfileError::NotIcc);
let mut long = good.clone();
long[0..4].copy_from_slice(&(good.len() as u32 + 1).to_be_bytes());
assert_eq!(DisplayTransform::from_icc(&long).unwrap_err(), ProfileError::BadLength { declared: good.len() + 1, len: good.len() });
let mut short = good.clone();
short[0..4].copy_from_slice(&64u32.to_be_bytes());
assert!(matches!(DisplayTransform::from_icc(&short), Err(ProfileError::BadLength { declared: 64, .. })));
// Trailing bytes past the declared length are not part of the profile.
let mut padded = good.clone();
padded.extend([0xAB; 16]);
let a = DisplayTransform::from_icc(&padded).unwrap();
assert_eq!(a.fingerprint(), DisplayTransform::from_icc(&good).unwrap().fingerprint());
let mut garbage_tags = good.clone();
for b in &mut garbage_tags[128..] {
*b = 0xFF;
}
assert!(matches!(DisplayTransform::from_icc(&garbage_tags), Err(ProfileError::Unreadable(_) | ProfileError::NoTransform)));
let huge = vec![0u8; MAX_PROFILE_BYTES + 1];
assert_eq!(DisplayTransform::from_icc(&huge).unwrap_err(), ProfileError::TooLarge(MAX_PROFILE_BYTES + 1));
}
#[test]
fn check_accepts_and_refuses_what_from_icc_does() {
assert_eq!(DisplayTransform::check(&display(DISPLAY_P3)), Ok(()));
assert_eq!(DisplayTransform::check(&display(SRGB)), Ok(()));
let cmyk = icc_bytes(GENERIC_CMYK).unwrap().to_vec();
assert_eq!(DisplayTransform::check(&cmyk), Err(DisplayTransform::from_icc(&cmyk).unwrap_err()));
assert_eq!(DisplayTransform::check(&[1, 2, 3]), Err(ProfileError::NotIcc));
}
#[test]
fn nan_and_out_of_range_values_stay_in_range() {
let p3 = DisplayTransform::from_icc(&display(DISPLAY_P3)).unwrap();
for v in p3.apply([f32::NAN, -1.0, 9.0]) {
assert!((0.0..=1.0).contains(&v));
}
}
}
+135 -25
View File
@@ -65,24 +65,62 @@ pub enum GradientMethod {
/// Mixed in a perceptual colour space (OKLab), so the steps look even to the eye: blue to
/// yellow passes through a light blue-grey rather than a dull mid grey.
Perceptual,
/// Mixed around the hue wheel, clockwise as the color wheels draw it: the hue angle falls
/// from each stop to the next (red, magenta, blue, cyan, green, yellow, red), and saturation
/// and brightness change evenly ([`hue_mix`]).
HueClockwise,
/// Mixed around the hue wheel the other way: the hue angle rises from each stop to the next
/// (red, yellow, green, cyan, blue, magenta, red).
HueCounterclockwise,
}
impl GradientMethod {
/// Parse a method name (`classic`, `perceptual`; any case).
/// Every method, in the order the Gradient panel lists them.
pub const ALL: [GradientMethod; 4] = [Self::Classic, Self::Perceptual, Self::HueClockwise, Self::HueCounterclockwise];
/// Parse a method name (`classic`, `perceptual`, `hue-clockwise`, `hue-counterclockwise`;
/// any case, and the hyphen may be a space or an underscore, or left out). Any other text,
/// one with a separator elsewhere included, is `None`.
pub fn parse(s: &str) -> Option<Self> {
[Self::Classic, Self::Perceptual].into_iter().find(|m| m.label().eq_ignore_ascii_case(s))
let name = s.to_ascii_lowercase();
Self::ALL.into_iter().find(|m| ["-", " ", "_", ""].iter().any(|sep| m.id().replace('-', sep) == name))
}
pub fn label(self) -> &'static str {
match self {
Self::Classic => "Classic",
Self::Perceptual => "Perceptual",
Self::HueClockwise => "Hue Clockwise",
Self::HueCounterclockwise => "Hue Counterclockwise",
}
}
/// The method's name in command params (`classic`, `perceptual`, `hue-clockwise`,
/// `hue-counterclockwise`).
pub fn id(self) -> &'static str {
match self {
Self::Classic => "classic",
Self::Perceptual => "perceptual",
Self::HueClockwise => "hue-clockwise",
Self::HueCounterclockwise => "hue-counterclockwise",
}
}
pub fn is_classic(&self) -> bool {
*self == Self::Classic
}
/// `a` and `b` mixed at `t` (0..1): in display RGB (Classic), or in OKLab (Perceptual: an
/// RGB colour between the two).
/// Does it mix around the hue wheel (Hue Clockwise or Hue Counterclockwise)? The colors
/// between two stops then are not mixes of the stops' inks.
pub fn is_hue(&self) -> bool {
matches!(self, Self::HueClockwise | Self::HueCounterclockwise)
}
/// The method that mixes `b` to `a` through the colors this one mixes `a` to `b` through: a
/// hue method turned the other way, Classic and Perceptual as they are.
pub fn mirrored(self) -> Self {
match self {
Self::HueClockwise => Self::HueCounterclockwise,
Self::HueCounterclockwise => Self::HueClockwise,
m => m,
}
}
/// `a` and `b` mixed at `t` (0..1): in display RGB (Classic), in OKLab (Perceptual: an
/// RGB colour between the two), or around the hue wheel ([`hue_mix`]: an RGB colour).
pub fn mix(self, a: &Color, b: &Color, t: f32) -> Color {
match self {
Self::Classic => Color::lerp(a, b, t),
@@ -93,10 +131,68 @@ impl GradientMethod {
let c = |v: f64| if v.is_finite() { v.clamp(0.0, 1.0) as f32 } else { 0.0 };
Color::rgb(c(r), c(g), c(bl))
}
Self::HueClockwise => hue_mix(a, b, t, false),
Self::HueCounterclockwise => hue_mix(a, b, t, true),
}
}
}
/// The brightness (0..1) at or below which a color is black for [`hue_mix`], and the spread
/// between its largest and smallest RGB numbers (saturation × brightness) at or below which it
/// has no hue of its own: under half a color level.
const NO_HUE: f32 = 0.4 / 255.0;
/// The hue difference (degrees) that moves an RGB number by half a color level in a color whose
/// largest and smallest RGB numbers are 1 apart; a color with a smaller spread takes
/// proportionally more degrees. [`hue_mix`] counts two hues closer than this as one hue.
const SAME_HUE: f32 = 60.0 * 0.5 / 255.0;
/// `a` and `b` mixed at `t` (0..1) around the hue wheel, as display RGB: hue (degrees),
/// saturation and brightness each change evenly from `a`'s to `b`'s. The hue angle only rises
/// (`rising`) or only falls, by the fixed-direction rules of
/// <https://www.w3.org/TR/css-color-4/#hue-interpolation>, and two equal hues stay where they are.
/// Two hues that differ by less than half a color level ([`SAME_HUE`]) count as equal and take the
/// short way, so a color and a tint or shade of it, whose computed hues differ by rounding, do
/// not turn the whole wheel. A color whose RGB numbers are less than half a color level apart
/// ([`NO_HUE`]) has no hue and takes the other color's; black has no saturation either and takes
/// the other color's too. Two colors without a hue mix as grays. A `t` that is not a number
/// gives `a`.
pub fn hue_mix(a: &Color, b: &Color, t: f32, rising: bool) -> Color {
let t = if t.is_nan() { 0.0 } else { t.clamp(0.0, 1.0) };
let ([mut h0, mut s0, v0], [mut h1, mut s1, v1]) = (a.to_hsb(), b.to_hsb());
let (black0, black1) = (v0 <= NO_HUE, v1 <= NO_HUE);
// The spread between each color's own largest and smallest RGB numbers.
let (spread0, spread1) = (s0 * v0, s1 * v1);
// Black takes the other color's saturation, so it darkens that color rather than graying it.
if black0 && !black1 {
s0 = s1;
} else if black1 && !black0 {
s1 = s0;
}
let (gray0, gray1) = (black0 || spread0 <= NO_HUE, black1 || spread1 <= NO_HUE);
match (gray0, gray1) {
(true, _) => h0 = h1,
(false, true) => h1 = h0,
(false, false) => {
// The short way from the first hue to the second, -180..180.
let short = (h1 - h0 + 180.0).rem_euclid(360.0) - 180.0;
h1 = if short.abs() * spread0.min(spread1) <= SAME_HUE {
h0 + short
} else if rising {
h0 + short.rem_euclid(360.0)
} else {
h0 + short.rem_euclid(360.0) - 360.0
};
}
}
let at = |p: f32, q: f32| p + (q - p) * t;
let (h, s, v) = (at(h0, h1), at(s0, s1), at(v0, v1));
if !(h.is_finite() && s.is_finite() && v.is_finite()) {
return Color::rgb(0.0, 0.0, 0.0);
}
Color::from_hsb(h.rem_euclid(360.0), s.clamp(0.0, 1.0), v.clamp(0.0, 1.0))
}
/// What a linear, radial, conic or diamond gradient paints past the ends of its stops (the
/// Gradient panel's Spread). With Repeat and Reflect, the stops run [`Gradient::repeats`] times
/// along the vector (around the circle, for a conic), and keep going past both of its ends.
@@ -192,10 +288,11 @@ const MAX_INK_TINTS: usize = 4096;
const INK_MIX_STEPS: u32 = 64;
/// The mix positions (0..1, after `v0`, before `v1`) between which display RGB mixed linearly
/// stays within [`PERCEPTUAL_TOLERANCE`] of the perceptual mix of `a` and `b`: the span halved
/// where a straight line strays, at most [`PERCEPTUAL_DEPTH`] times, in order.
fn perceptual_steps(a: &Color, b: &Color, (v0, v1): (f32, f32), depth: u32, out: &mut Vec<f32>) {
let at = |v: f32| GradientMethod::Perceptual.mix(a, b, v).to_rgb();
/// stays within [`PERCEPTUAL_TOLERANCE`] of `method`'s mix of `a` and `b` (Perceptual, or around
/// the hue wheel): the span halved where a straight line strays, at most [`PERCEPTUAL_DEPTH`]
/// times, in order.
fn perceptual_steps(method: GradientMethod, a: &Color, b: &Color, (v0, v1): (f32, f32), depth: u32, out: &mut Vec<f32>) {
let at = |v: f32| method.mix(a, b, v).to_rgb();
let (c0, c1) = (at(v0), at(v1));
let stray = [0.25, 0.5, 0.75]
.into_iter()
@@ -206,19 +303,20 @@ fn perceptual_steps(a: &Color, b: &Color, (v0, v1): (f32, f32), depth: u32, out:
.fold(0.0, f32::max);
if depth < PERCEPTUAL_DEPTH && stray > PERCEPTUAL_TOLERANCE {
let m = (v0 + v1) / 2.0;
perceptual_steps(a, b, (v0, m), depth + 1, out);
perceptual_steps(method, a, b, (v0, m), depth + 1, out);
out.push(m);
perceptual_steps(a, b, (m, v1), depth + 1, out);
perceptual_steps(method, a, b, (m, v1), depth + 1, out);
}
}
/// The mix positions (`v`, 0..1) of the stops a Perceptual gradient's curve has between stops `a`
/// and `b`, in order: [`perceptual_steps`] on either side of the midpoint, and the midpoint (½).
fn perceptual_mixes(a: &GradientStop, b: &GradientStop) -> Vec<f32> {
/// The mix positions (`v`, 0..1) of the stops the curve of a gradient mixed by `method`
/// (Perceptual, or around the hue wheel) has between stops `a` and `b`, in order:
/// [`perceptual_steps`] on either side of the midpoint, and the midpoint (½).
fn perceptual_mixes(method: GradientMethod, a: &GradientStop, b: &GradientStop) -> Vec<f32> {
let mut vs = Vec::new();
perceptual_steps(&a.color, &b.color, (0.0, 0.5), 1, &mut vs);
perceptual_steps(method, &a.color, &b.color, (0.0, 0.5), 1, &mut vs);
vs.push(0.5);
perceptual_steps(&a.color, &b.color, (0.5, 1.0), 1, &mut vs);
perceptual_steps(method, &a.color, &b.color, (0.5, 1.0), 1, &mut vs);
vs
}
@@ -512,10 +610,11 @@ impl Gradient {
};
(t, c, o, Some(s.midpoint), None)
});
// Perceptual: stops along the mix (`v`) where a straight line would stray from it, the
// midpoint (v = ½) among them, placed through the midpoint as [`Self::sample`] maps them.
// Perceptual and the hue methods: stops along the mix (`v`) where a straight line would
// stray from it, the midpoint (v = ½) among them, placed through the midpoint as
// [`Self::sample`] maps them.
let perceptual = next.filter(|_| !self.method.is_classic()).map(|n| {
perceptual_mixes(s, n).into_iter().map(move |v| {
perceptual_mixes(self.method, s, n).into_iter().map(move |v| {
let mid = v == 0.5;
let t = curve_offset(s, n, v);
let o = s.opacity + (n.opacity - s.opacity) * v;
@@ -571,11 +670,12 @@ impl Gradient {
/// position itself when the two colors' lightness differs by less than
/// [`MIN_INK_LIGHTNESS_SPAN`], or when the display RGB mix's lightness turns back somewhere
/// on the way from one color's lightness to the other's (checked at [`INK_MIX_STEPS`] even
/// steps), as from red to blue. `None` for a Classic gradient, and when the curve has more
/// than [`MAX_INK_TINTS`] stops ([`Self::fits_ink_tints`]).
/// steps), as from red to blue. `None` for a Classic gradient, for one mixed around the hue
/// wheel (its colors between two stops are not mixes of the stops' inks), and when the curve
/// has more than [`MAX_INK_TINTS`] stops ([`Self::fits_ink_tints`]).
pub fn ink_mixes(&self) -> Option<Vec<(f32, usize, f32, f32)>> {
use crate::libraries::srgb_to_oklab;
if self.method.is_classic() || !self.fits_ink_tints() {
if self.method != GradientMethod::Perceptual || !self.fits_ink_tints() {
return None;
}
let lightness = |c: &Color| srgb_to_oklab(c.to_rgb())[0];
@@ -592,7 +692,7 @@ impl Gradient {
.collect::<Vec<_>>()
.windows(2)
.all(|w| (w[1] - w[0]) * (l1 - l0) >= 0.0);
for v in perceptual_mixes(s, n) {
for v in perceptual_mixes(self.method, s, n) {
let weight = if by_position {
v
} else {
@@ -650,8 +750,10 @@ impl Gradient {
Some(Ramp { stops })
}
/// The same ramp the other way round: the stops in reverse order at mirrored offsets, each
/// segment's midpoint mirrored with it.
/// segment's midpoint mirrored with it, and a hue method turned the other way (red to blue
/// through magenta, reversed, is blue to red through magenta).
pub fn reverse(&mut self) {
self.method = self.method.mirrored();
self.stops.reverse();
for i in 0..self.stops.len() {
// A midpoint belongs to the segment after its stop: reversed, stop i's segment is the
@@ -666,6 +768,13 @@ impl Gradient {
pub fn sort(&mut self) {
self.stops.sort_by(|a, b| a.offset.total_cmp(&b.offset));
}
/// The gradient's colors as a Classic gradient: its curve's stops ([`Self::expanded_stops`]) as
/// stops of their own, mixed in display RGB, within [`PERCEPTUAL_TOLERANCE`] of it. The stops
/// keep no swatch links, tints or process plates.
pub fn as_classic_curve(&self) -> Gradient {
let stops = self.expanded().map(|(t, color, opacity, _)| GradientStop { opacity, ..GradientStop::new(t, color) }).collect();
Gradient { kind: self.kind, stops, dither: self.dither, method: GradientMethod::Classic, spread: self.spread, repeats: self.repeats }
}
/// The part of the gradient from `from` to `to` (0..1, either way round) as a linear gradient
/// of its own running 0 → 1: the same colours (midpoints become stops, as in
/// [`Self::expanded_stops`]). One colour throughout when `from == to`.
@@ -1261,8 +1370,9 @@ impl GradientPaint {
}
/// Is this gradient drawn as pixels rather than as a vector gradient when it paints a fill
/// (`fill`) or a stroke (SVG and PDF draw such gradients as images): a freeform gradient, a
/// dithered fill (dither applies to fills only), or a Perceptual one (its colours don't mix
/// linearly between the stops, as SVG's and PDF's gradients do)?
/// dithered fill (dither applies to fills only), or a Perceptual one or one mixed around the
/// hue wheel (its colours don't mix linearly between the stops, as SVG's and PDF's gradients
/// do)?
pub fn draws_as_pixels(&self, fill: bool) -> bool {
self.gradient.kind == GradientKind::Freeform || (fill && self.gradient.dither) || !self.gradient.method.is_classic()
}
+16
View File
@@ -59,6 +59,9 @@ impl Gradient {
if !self.is_spread() || matches!(kind, GradientKind::Conic | GradientKind::Freeform) || self.stops.is_empty() {
return None;
}
if self.mirrors_a_hue_turn() {
return self.as_classic_curve().padded_within(geom, area, max_stops);
}
let period = geom.period(kind, self.repeat_count());
let corners = [Point::new(area.x0, area.y0), Point::new(area.x1, area.y0), Point::new(area.x1, area.y1), Point::new(area.x0, area.y1)];
let ts = corners.map(|p| period.param_at(kind, p));
@@ -128,6 +131,9 @@ impl Gradient {
if self.stops.is_empty() {
return Cow::Owned(Gradient { spread: GradientSpread::Pad, repeats: 1, ..self.clone() });
}
if self.mirrors_a_hue_turn() {
return Cow::Owned(self.as_classic_curve().unrolled_within(max_stops).into_owned());
}
let n = self.repeat_count() as usize;
let budget = max_stops.min(MAX_SPREAD_STOPS);
let kept = n.min(budget / 2).max(1);
@@ -159,12 +165,22 @@ impl Gradient {
if !self.is_spread() || self.stops.is_empty() {
return None;
}
if self.mirrors_a_hue_turn() {
return self.as_classic_curve().cycle();
}
let one = whole_run(&self.stops);
let runs = if self.spread == GradientSpread::Reflect { 2 } else { 1 };
let stops = self.runs(&one, false, 0.0, runs, runs as f64);
Some((Gradient { stops, spread: GradientSpread::Pad, repeats: 1, ..self.clone() }, runs as u32))
}
/// Does the gradient reflect while mixing around the hue wheel? A mirrored run of its stops
/// would turn the wheel the other way, and one gradient has one method, so its runs are
/// written from its curve's stops ([`Self::as_classic_curve`]), which mirror as they are.
fn mirrors_a_hue_turn(&self) -> bool {
self.method.is_hue() && self.spread == GradientSpread::Reflect
}
/// `n` runs of `one` (one run of the stops, [`whole_run`]) on a line of `of` runs from 0 to 1,
/// the first of them `start` runs along it and an odd-numbered run when `first_odd` (with
/// Reflect, the odd-numbered runs are mirrored).
+40
View File
@@ -118,6 +118,46 @@ fn reflect_mirrors_every_other_run_and_its_midpoints() {
assert!((p.gradient.stops[2].midpoint - 0.7).abs() < 1e-6, "{:?}", p.gradient.stops);
}
/// A gradient mixed around the hue wheel that reflects: a mirrored run turns the wheel back the
/// way it came, so every point keeps its color when the runs are written out as a gradient that
/// pads, unrolled along the vector, or as one cycle, with a repeating one's too.
#[test]
fn reflected_and_repeated_hue_turns_keep_every_color() {
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(10.0, 0.0), aspect: 1.0, focal: None };
let stops = || {
let mut red = GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0));
red.midpoint = 0.3;
vec![red, GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))]
};
let near = |a: Color, b: Color, what: &str| {
assert!(a.to_rgb().iter().zip(b.to_rgb()).all(|(x, y)| (x - y).abs() < 1.0 / 255.0), "{what}: {a:?} vs {b:?}");
};
for method in [GradientMethod::HueClockwise, GradientMethod::HueCounterclockwise] {
for spread in [GradientSpread::Reflect, GradientSpread::Repeat] {
let g = Gradient { method, spread, repeats: 2, ..Gradient::new(GradientKind::Linear, stops()) };
let p = g.padded_over(&geom, Rect::new(-10.0, 0.0, 20.0, 10.0)).unwrap();
assert_eq!((p.gradient.spread, p.gradient.repeats), (GradientSpread::Pad, 1));
for k in 0..300 {
let q = Point::new(-10.0 + f64::from(k) * 0.1 + 0.013, 5.0);
let want = g.sample(g.spread_param(geom.param_at(GradientKind::Linear, q)) as f32).0;
let got = p.gradient.sample(p.geom.param_at(GradientKind::Linear, q) as f32).0;
near(want, got, &format!("{method:?} {spread:?} padded at {}", q.x));
}
let unrolled = g.unrolled();
let (cycle, runs) = g.cycle().unwrap();
for k in 0..=200 {
let t = (k as f32 + 0.37) / 201.0;
let want = g.sample(g.spread_param(f64::from(t)) as f32).0;
near(want, unrolled.sample(t).0, &format!("{method:?} {spread:?} unrolled at {t}"));
// One cycle covers `runs` of the two runs between 0 and 1.
let along = t * runs as f32 / 2.0;
let want = g.sample(g.spread_param(f64::from(along)) as f32).0;
near(want, cycle.sample(t).0, &format!("{method:?} {spread:?} cycle at {t}"));
}
}
}
}
#[test]
fn stops_inside_a_run_hold_their_colors_to_its_ends() {
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(10.0, 0.0), aspect: 1.0, focal: None };
+277
View File
@@ -514,6 +514,283 @@ fn perceptual_gradients_draw_as_pixels() {
}
}
fn two_stops(a: Color, b: Color, method: GradientMethod) -> Gradient {
let mut g = Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, a), GradientStop::new(1.0, b)]);
g.method = method;
g
}
/// The hue methods mix around the hue wheel in one direction: Hue Counterclockwise raises the
/// hue angle from each stop to the next and Hue Clockwise lowers it, by the fixed-direction rules
/// of <https://www.w3.org/TR/css-color-4/#hue-interpolation> (the angles below are that
/// section's own examples), with saturation and brightness changing evenly.
#[test]
fn hue_methods_turn_one_way_around_the_wheel() {
let (red, blue) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0));
let rising = two_stops(red, blue, GradientMethod::HueCounterclockwise);
assert_eq!(rising.sample(0.0).0.to_hex(), "#ff0000");
assert_eq!(rising.sample(0.25).0.to_hex(), "#ffff00", "60°");
assert_eq!(rising.sample(0.5).0.to_hex(), "#00ff00", "120°");
assert_eq!(rising.sample(1.0).0.to_hex(), "#0000ff");
let falling = two_stops(red, blue, GradientMethod::HueClockwise);
assert_eq!(falling.sample(0.0).0.to_hex(), "#ff0000");
assert_eq!(falling.sample(0.5).0.to_hex(), "#ff00ff", "300°");
assert_eq!(falling.sample(1.0).0.to_hex(), "#0000ff");
assert_eq!(two_stops(red, blue, GradientMethod::Classic).sample(0.5).0.to_rgb(), [0.5, 0.0, 0.5], "classic: the RGB mix");
// 30° to 190° and to 230°: halfway is 110° and 130° rising, 290° and 310° falling.
for (to, up, down) in [(190.0, 110.0, 290.0), (230.0, 130.0, 310.0)] {
let (a, b) = (Color::from_hsb(30.0, 0.5, 0.8), Color::from_hsb(to, 0.9, 0.4));
for (method, want) in [(GradientMethod::HueCounterclockwise, up), (GradientMethod::HueClockwise, down)] {
let [h, s, v] = method.mix(&a, &b, 0.5).to_hsb();
assert!((h - want).abs() < 0.05, "{method:?} to {to}: hue {h}, not {want}");
assert!((s - 0.7).abs() < 1e-3 && (v - 0.6).abs() < 1e-3, "{method:?}: saturation {s}, brightness {v}");
}
}
// The other way round, each method takes the arc the other took.
let back = two_stops(blue, red, GradientMethod::HueClockwise);
assert_eq!(back.sample(0.5).0.to_hex(), "#00ff00");
// A position that is not a number gives the first color.
assert_eq!(hue_mix(&red, &blue, f32::NAN, true).to_hex(), "#ff0000");
}
/// A color without a hue does not turn the wheel: a gray takes the hue of the stop it mixes
/// with, black its saturation too, two grays mix as grays, and two stops of one hue keep that
/// hue, whichever way the method turns.
#[test]
fn hue_methods_keep_the_hue_where_a_stop_has_none() {
let red = Color::rgb(1.0, 0.0, 0.0);
let close = |c: Color, want: [f32; 3], what: &str| {
let got = c.to_rgb();
assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-3), "{what}: {got:?}, not {want:?}");
};
let green = Color::rgb(0.0, 1.0, 0.0);
for method in [GradientMethod::HueClockwise, GradientMethod::HueCounterclockwise] {
close(method.mix(&Color::WHITE, &green, 0.5), [0.5, 1.0, 0.5], "white to green: a light green");
close(method.mix(&green, &Color::WHITE, 0.5), [0.5, 1.0, 0.5], "green to white: a light green");
close(method.mix(&Color::rgb(0.5, 0.5, 0.5), &green, 0.5), [0.375, 0.75, 0.375], "gray to green");
close(method.mix(&Color::BLACK, &green, 0.5), [0.0, 0.5, 0.0], "black to green: a dark green, not a gray green");
close(method.mix(&green, &Color::BLACK, 0.25), [0.0, 0.75, 0.0], "green to black");
close(method.mix(&Color::BLACK, &Color::WHITE, 0.5), [0.5, 0.5, 0.5], "black to white: gray");
close(method.mix(&Color::BLACK, &Color::BLACK, 0.5), [0.0, 0.0, 0.0], "black to black");
let dark = Color::rgb(0.5, 0.0, 0.0);
close(method.mix(&red, &dark, 0.5), [0.75, 0.0, 0.0], "one hue: a red between the two");
close(method.mix(&red, &red, 0.5), [1.0, 0.0, 0.0], "one color stays");
// One hue with saturation and brightness both changing: the hue stays, and the color is
// the even mix of saturation and brightness, which is not Classic's RGB mix.
let pink = Color::rgb(1.0, 0.8, 0.8);
close(method.mix(&dark, &pink, 0.5), [0.75, 0.3, 0.3], "dark red to pink");
assert!((Color::lerp(&dark, &pink, 0.5).to_rgb()[1] - 0.4).abs() < 1e-3, "classic differs");
// A color whose RGB numbers are under half a color level apart has no hue of its own: a
// near gray leaning blue takes green's hue rather than turning from blue.
let near_gray = Color::rgb(0.5, 0.5, 0.5 + 0.3 / 255.0);
let [h, _, _] = method.mix(&near_gray, &green, 0.5).to_hsb();
assert!((h - 120.0).abs() < 0.5, "{method:?}: near gray to green passes hue {h}");
// One a whole color level apart has its hue (240°) and turns from it.
let bluish = Color::rgb(128.0 / 255.0, 128.0 / 255.0, 129.0 / 255.0);
let [h, _, _] = method.mix(&bluish, &green, 0.5).to_hsb();
let want = if method == GradientMethod::HueClockwise { 180.0 } else { 0.0 };
assert!(((h - want + 180.0).rem_euclid(360.0) - 180.0).abs() < 0.5, "{method:?}: bluish gray to green passes hue {h}, not {want}");
}
}
/// Hues that differ only by rounding are one hue: a color and a tint or shade of it, whose
/// computed hue angles differ in their last digits, mix without turning the wheel, with either
/// method, and a stop added to a ramp leaves the ramp's colors as they were. Hues a whole color
/// level apart still turn.
#[test]
fn hue_methods_take_hues_within_half_a_color_level_as_one() {
let level = |n: u8| f32::from(n) / 255.0;
let rgb8 = |r: u8, g: u8, b: u8| Color::rgb(level(r), level(g), level(b));
let methods = [GradientMethod::HueClockwise, GradientMethod::HueCounterclockwise];
// Colors against their 50% tint toward white and a shade at 40% brightness. At least one
// pair's computed hues differ, or the test checks nothing.
let colors = [rgb8(60, 253, 230), rgb8(241, 194, 107), rgb8(68, 32, 130), rgb8(13, 200, 77), rgb8(250, 3, 201), rgb8(90, 91, 200)];
let mut uneven = 0;
for c in colors {
let [h, s, v] = c.to_hsb();
let tint = Color::lerp(&c, &Color::WHITE, 0.5);
let shade = Color::from_hsb(h, s, v * 0.4);
for other in [tint, shade] {
let [h1, _, _] = other.to_hsb();
assert!((h1 - h).abs() < 0.01, "{c:?} and {other:?} are one hue: {h} and {h1}");
uneven += usize::from(h1 != h);
for method in methods {
for (a, b) in [(c, other), (other, c)] {
for k in 0..=20 {
let [hm, _, _] = method.mix(&a, &b, k as f32 / 20.0).to_hsb();
let off = (hm - h + 180.0).rem_euclid(360.0) - 180.0;
assert!(off.abs() < 0.5, "{method:?} {a:?} → {b:?} at {k}/20: hue {hm}, not {h}");
}
}
}
}
}
assert!(uneven > 0, "no pair's hues differ by rounding");
// Across 0°: 359.99° and 0.01° are one hue too.
for method in methods {
let [h, _, _] = method.mix(&Color::from_hsb(359.99, 1.0, 1.0), &Color::from_hsb(0.01, 1.0, 1.0), 0.5).to_hsb();
assert!(!(1.0..=359.0).contains(&h), "{method:?} across 0°: {h}");
}
// A stop added to a ramp samples the ramp's color there, and the ramp keeps its colors:
// white to red, a color to its tint, and a turn from red to blue.
let ramps = [
(Color::WHITE, rgb8(255, 0, 0)),
(rgb8(60, 253, 230), Color::lerp(&rgb8(60, 253, 230), &Color::WHITE, 0.5)),
(rgb8(255, 0, 0), rgb8(0, 0, 255)),
];
for method in methods {
for (a, b) in ramps {
let g = two_stops(a, b, method);
for at in [0.21, 0.5, 0.83] {
let (stops, i) = insert_stop(&g, at);
assert_eq!((stops.len(), i), (3, 1));
let with = Gradient { stops, ..g.clone() };
for k in 0..=200 {
let t = k as f32 / 200.0;
let (was, now) = (g.sample(t).0.to_rgb(), with.sample(t).0.to_rgb());
let off = was.iter().zip(now).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max);
assert!(off < 1.0 / 255.0, "{method:?} {a:?} → {b:?}, a stop at {at}: {was:?} became {now:?} at {t}");
}
}
}
}
// One color level of hue is a hue of its own: red to a red one level toward yellow turns
// nearly the whole wheel one way and stays put the other.
let (red, next) = (rgb8(255, 0, 0), rgb8(255, 1, 0));
let [h, _, _] = GradientMethod::HueClockwise.mix(&red, &next, 0.5).to_hsb();
assert!((h - 180.0).abs() < 1.0, "the long way: {h}");
let [h, _, _] = GradientMethod::HueCounterclockwise.mix(&red, &next, 0.5).to_hsb();
assert!(h < 1.0, "the short way: {h}");
}
/// Renderers mix linearly between stops: a hue segment becomes stops on its way around the
/// wheel, close enough that the linear ramp between them stays within half a color level of it,
/// through the midpoint and with the opacity changing evenly.
#[test]
fn hue_segments_expand_into_stops_on_the_curve() {
let pairs = [
(Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0)),
(Color::rgb(1.0, 0.0, 0.0), Color::rgb(1.0, 0.02, 0.0)),
(Color::from_hsb(30.0, 0.5, 0.8), Color::from_hsb(190.0, 0.9, 0.4)),
(Color::cmyk(0.0, 0.9, 0.9, 0.0), Color::WHITE),
(Color::BLACK, Color::rgb(0.0, 1.0, 0.0)),
];
for method in [GradientMethod::HueClockwise, GradientMethod::HueCounterclockwise] {
for (a, b) in pairs {
let mut g = two_stops(a, b, method);
g.stops[0].midpoint = 0.3;
g.stops[1].opacity = 0.5;
let ex: Vec<_> = g.expanded().collect();
assert!((3..=600).contains(&ex.len()), "{method:?} {a:?} → {b:?}: {} stops", ex.len());
assert!(ex.windows(2).all(|w| w[0].0 < w[1].0), "in order");
assert!(ex.iter().any(|s| s.3 == Some(0.3) && (s.0 - 0.3).abs() < 1e-6), "a stop stands for the midpoint");
let ramp = Ramp::new(&g, &Color::to_rgb);
for k in 0..=4000 {
let t = k as f32 / 4000.0;
let (c, o) = g.sample(t);
let [r, gr, bl] = c.to_rgb();
let off = [r, gr, bl, o].iter().zip(ramp.at(t)).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max);
assert!(off < 0.5 / 255.0, "{method:?} {a:?} → {b:?} at {t}: {off}");
}
assert_eq!(g.sample_keep_model(0.4), g.sample(0.4), "one mix");
}
}
}
/// Reversing a gradient gives the same ramp the other way round: a hue method turns the other
/// way with the stops, so every color keeps its place mirrored, and reversing twice gives the
/// gradient back. Classic and Perceptual keep their method. A backward span and the curve as a
/// Classic gradient hold the same colors.
#[test]
fn reversing_a_hue_gradient_keeps_its_colors_mirrored() {
let near = |a: Color, b: Color, what: &str| {
assert!(a.to_rgb().iter().zip(b.to_rgb()).all(|(x, y)| (x - y).abs() < 1.0 / 255.0), "{what}: {a:?} vs {b:?}");
};
for (method, other) in
[(GradientMethod::HueClockwise, GradientMethod::HueCounterclockwise), (GradientMethod::HueCounterclockwise, GradientMethod::HueClockwise)]
{
let mut g = Gradient::new(
GradientKind::Linear,
vec![
GradientStop { midpoint: 0.3, ..GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)) },
GradientStop { opacity: 0.5, ..GradientStop::new(0.6, Color::rgb(0.0, 0.0, 1.0)) },
GradientStop::new(1.0, Color::rgb(0.9, 0.8, 0.1)),
],
);
g.method = method;
let mut back = g.clone();
back.reverse();
assert_eq!(back.method, other);
let (span, curve) = (g.span(1.0, 0.0), g.as_classic_curve());
assert!(span.method.is_classic() && curve.method.is_classic());
assert!(curve.stops.len() > g.stops.len() && curve.stops.iter().all(|s| s.swatch.is_none() && s.midpoint == 0.5));
for k in 0..=400 {
let t = k as f32 / 400.0;
let (want, opacity) = g.sample(1.0 - t);
near(want, back.sample(t).0, &format!("{method:?} reversed at {t}"));
assert!((opacity - back.sample(t).1).abs() < 1e-4, "{method:?} opacity at {t}");
near(want, span.sample(t).0, &format!("{method:?} backward span at {t}"));
near(g.sample(t).0, curve.sample(t).0, &format!("{method:?} curve at {t}"));
}
back.reverse();
assert_eq!(back.method, method);
assert_eq!(back.stops.len(), g.stops.len());
}
for method in [GradientMethod::Classic, GradientMethod::Perceptual] {
assert_eq!(method.mirrored(), method);
let mut g = blue_yellow(method);
g.reverse();
assert_eq!(g.method, method);
}
}
/// The hue methods are written by name, read back, and parsed from their param names; their
/// gradients draw as pixels in SVG and PDF, and are not mixes of the stops' inks.
#[test]
fn hue_methods_save_parse_and_draw_as_pixels() {
for (method, name, id) in [
(GradientMethod::HueClockwise, "HueClockwise", "hue-clockwise"),
(GradientMethod::HueCounterclockwise, "HueCounterclockwise", "hue-counterclockwise"),
] {
let g = two_stops(Color::cmyk(0.0, 1.0, 1.0, 0.0), Color::cmyk(1.0, 1.0, 0.0, 0.0), method);
let v = serde_json::to_value(&g).unwrap();
assert_eq!(v["method"], name);
assert_eq!(serde_json::from_value::<Gradient>(v).unwrap(), g);
assert_eq!(method.id(), id);
for written in [id.to_string(), id.to_uppercase(), id.replace('-', " "), id.replace('-', "_"), name.to_string(), method.label().to_string()] {
assert_eq!(GradientMethod::parse(&written), Some(method), "{written}");
}
assert!(method.is_hue() && !method.is_classic());
let paint = GradientPaint::new(g.clone());
assert!(paint.draws_as_pixels(true) && paint.draws_as_pixels(false));
assert!(g.ink_mixes().is_none(), "not mixes of the stops' inks");
assert!(
paint.ink_pixels(Rect::new(0.0, 0.0, 10.0, 10.0), Rect::new(0.0, 0.0, 10.0, 10.0), 4, 4, true).is_none(),
"an RGB image, not an ink image"
);
}
assert!(!GradientMethod::Perceptual.is_hue() && !GradientMethod::Classic.is_hue());
for (id, method) in [("classic", GradientMethod::Classic), ("perceptual", GradientMethod::Perceptual)] {
assert_eq!(method.id(), id);
assert_eq!(GradientMethod::parse(id), Some(method));
}
for bad in [
"hue",
"clockwise",
"hue-",
"",
"hue clockwise wise",
"c-l-a-s-s-i-c",
"per ceptual",
"hue--clockwise",
"hue-clock_wise",
" classic",
"hue- clockwise",
] {
assert_eq!(GradientMethod::parse(bad), None, "{bad}");
}
}
/// A Perceptual gradient of an ink's tints as tints: its stops keep their tints, and each tint on
/// the curve has the lightness of the color mixed there, so the tints between the stops are not
/// a straight line.
+4 -3
View File
@@ -102,12 +102,13 @@ impl Color {
pub fn to_lab(&self) -> cms::Lab {
cms::active().lab(self)
}
/// Colour-managed CMYK in the working CMYK space with `intent` (see [`Color::to_cmyk`] for the
/// profile-free formula).
/// Color-managed CMYK in the active CMYK space (the front document's assigned CMYK profile, else
/// the working CMYK space) with `intent` (see [`Color::to_cmyk`] for the profile-free formula).
pub fn to_cmyk_managed(&self, intent: cms::Intent) -> [f32; 4] {
cms::active().to_cmyk(self, intent)
}
/// Gamut warning: true when this colour can't be reproduced in the working CMYK space.
/// Gamut warning: true when this color can't be reproduced in the active CMYK space (the front
/// document's assigned CMYK profile, else the working CMYK space).
pub fn out_of_gamut(&self) -> bool {
cms::active().out_of_gamut(self)
}
+157
View File
@@ -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));
}
}
+474 -45
View File
@@ -1205,6 +1205,13 @@ pub fn blend_step_count(a: &Node, b: &Node, spacing: BlendSpacing, len: f64) ->
// Spine
// =====================================================================================
#[cfg(test)]
thread_local! {
/// How many times [`Spine::new`] has run on this thread, for tests that count how often a path
/// is flattened.
pub(crate) static SPINES_BUILT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// A spine (the first subpath of a path) flattened to a polyline, with cumulative lengths and the
/// arc length at each of its anchors.
pub struct Spine {
@@ -1223,6 +1230,8 @@ impl Spine {
/// arc lengths, and the arc length at each anchor. `None` when `path` has no subpath, or when
/// the first one flattens to fewer than two points (so it has no length to walk).
pub fn new(path: &PathData) -> Option<Self> {
#[cfg(test)]
SPINES_BUILT.with(|n| n.set(n.get() + 1));
let sp = path.subpaths.first()?;
let mut pts: Vec<Point> = Vec::new();
let mut cum: Vec<f64> = Vec::new();
@@ -1326,27 +1335,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 +1390,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)
@@ -1435,7 +1464,7 @@ pub fn pin_spine(keys: &[Arc<Node>], spec: &BlendSpec) -> Option<(PathData, Vec<
}
/// Do `keys` sit where a spine from Replace Spine spreads them: evenly along `spine` by arc length
/// (within a hundredth of a point, as [`anchor_at_length`] matches anchors)?
/// (within a hundredth of a point, as [`SpreadLengths::anchor_at_length`] matches anchors)?
fn keys_spread_along(keys: &[Arc<Node>], spine: &Spine) -> bool {
let k = keys.len();
keys.iter().enumerate().all(|(i, key)| {
@@ -1460,40 +1489,204 @@ fn open_at_start(sp: &mut SubPath, ka: &mut [usize]) {
}
/// The anchors of `path`'s first subpath that `k` keys spread evenly along it by arc length sit
/// on, splitting segments where none is.
/// on, splitting segments where none is. `None`, leaving `path` as it was, when the subpath has no
/// length to spread along, when its length is not finite (a path so large its length overflows),
/// or when an arc length it would split at is not finite.
fn spread_anchors(path: &mut PathData, k: usize) -> Option<Vec<usize>> {
let total = Spine::new(path)?.length();
let closed = path.subpaths.first().is_some_and(|s| s.closed);
spread_anchors_with(path, k, |_| {})
}
/// [`spread_anchors`], calling `work` for each step of work it does.
fn spread_anchors_with(path: &mut PathData, k: usize, mut work: impl FnMut(SpreadWork)) -> Option<Vec<usize>> {
let sp = path.subpaths.first_mut()?;
let lengths = SpreadLengths::new(sp, &mut work);
let total = lengths.total().filter(|t| t.is_finite())?;
let targets = (1..k.saturating_sub(1)).map(|i| total * i as f64 / (k - 1) as f64);
let mut out = vec![0usize];
for i in 1..k.saturating_sub(1) {
let s = total * i as f64 / (k - 1) as f64;
out.push(anchor_at_length(path, s)?);
}
let last = path.subpaths.first().map_or(0, |sp| if closed { 0 } else { sp.anchors.len().saturating_sub(1) });
out.push(last);
out.extend(anchors_at_lengths(sp, lengths, targets, &mut work)?);
out.push(if sp.closed { 0 } else { sp.anchors.len().saturating_sub(1) });
Some(out)
}
/// The anchor of the first subpath at arc length `s`: an existing one within a hundredth of a
/// point, else a new one splitting the segment there.
fn anchor_at_length(path: &mut PathData, s: f64) -> Option<usize> {
let spine = Spine::new(path)?;
let sp = path.subpaths.first_mut()?;
let n = sp.segment_count();
let seg = (0..n).rev().find(|i| spine.anchor_length(*i).is_some_and(|l| l <= s)).unwrap_or(0);
let from = spine.anchor_length(seg).unwrap_or(0.0);
let to = spine.anchor_length(seg + 1).unwrap_or(spine.length());
if s - from < 0.01 {
return Some(seg);
/// The anchors of `sp` at each arc length in `targets`, in order, splitting segments where none is
/// (see [`SpreadLengths::anchor_at_length`]); `lengths` measures `sp`. The splits are made on a copy
/// of `sp`, which replaces it only when every target has its anchor: `None` leaves `sp` as it was.
fn anchors_at_lengths(
sp: &mut SubPath,
mut lengths: SpreadLengths,
targets: impl IntoIterator<Item = f64>,
work: &mut impl FnMut(SpreadWork),
) -> Option<Vec<usize>> {
let mut split = sp.clone();
let mut out = Vec::new();
for s in targets {
out.push(lengths.anchor_at_length(&mut split, s, work)?);
}
if to - s < 0.01 {
return Some((seg + 1) % sp.anchors.len().max(1));
*sp = split;
Some(out)
}
/// A step of the work [`spread_anchors_with`] does.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum SpreadWork {
/// Flattening every segment of the subpath.
WholePath,
/// Flattening one segment after a split.
Segment,
/// Adding one segment's flattened points to the arc lengths.
Measure,
/// Comparing an anchor's arc length with the one looked for.
Compare,
}
/// Where the measurement of a subpath's flattened points stands at the start of a segment: the last
/// point kept, the arc length there (0 before any point), and how many points were kept.
#[derive(Clone, Copy)]
struct Measured {
last: Option<Point>,
len: f64,
kept: usize,
}
impl Measured {
const START: Self = Self { last: None, len: 0.0, kept: 0 };
/// The measurement after `pts`, keeping each point more than 1e-9 from the last one kept, as
/// [`Spine::new`] does.
fn then(mut self, pts: &[Point]) -> Self {
for &p in pts {
if self.last.is_none_or(|q| q.distance(p) > 1e-9) {
self.len = match self.last {
Some(q) => self.len + q.distance(p),
None => 0.0,
};
self.last = Some(p);
self.kept += 1;
}
}
self
}
}
/// The arc lengths of a subpath's anchors, as [`Spine::new`] measures them, kept up to date while
/// [`spread_anchors`] splits its segments. Each segment is flattened once, and again only when it
/// is split. A split leaves the arc lengths of the anchors before it as they are; those after it
/// are measured again, in order from the split, only as far as the next arc length looked for, so
/// the sums are the same as [`Spine::new`]'s on the split subpath.
struct SpreadLengths {
/// The finite points the segments flatten to, each segment's in one run.
pts: Vec<Point>,
/// Where each segment's run is in `pts`. A split segment's halves get runs at the end, and its
/// old run is not used again.
flat: Vec<std::ops::Range<usize>>,
/// The measurement at the start of each segment, up to the first one not measured since the
/// last split; after the last segment too once every segment is measured.
marks: Vec<Measured>,
}
impl SpreadLengths {
/// Flatten and measure every segment of `sp`.
fn new(sp: &SubPath, work: &mut impl FnMut(SpreadWork)) -> Self {
work(SpreadWork::WholePath);
let n = sp.segment_count();
let mut lengths = Self { pts: Vec::new(), flat: Vec::with_capacity(n), marks: Vec::with_capacity(n + 1) };
for i in 0..n {
let run = lengths.flatten(sp, i);
lengths.flat.push(run);
}
lengths.marks.push(Measured::START);
lengths.measure_to(f64::INFINITY, work);
lengths
}
/// Flatten segment `i` of `sp` as [`Spine::new`] does, adding its finite points to `pts`, and
/// return where they are.
fn flatten(&mut self, sp: &SubPath, i: usize) -> std::ops::Range<usize> {
let start = self.pts.len();
let c = sp.segment(i);
let mut bp = BezPath::new();
bp.move_to(c.p0);
if sp.segment_is_line(i) {
bp.line_to(c.p3);
} else {
bp.curve_to(c.p1, c.p2, c.p3);
}
vectorcraft_geom::kurbo::flatten(bp.iter(), 0.1, |el| {
if let vectorcraft_geom::PathEl::MoveTo(p) | vectorcraft_geom::PathEl::LineTo(p) = el
&& p.x.is_finite()
&& p.y.is_finite()
{
self.pts.push(p);
}
});
start..self.pts.len()
}
/// The subpath's flattened length, `None` when it flattens to fewer than two points.
fn total(&self) -> Option<f64> {
self.marks.last().filter(|m| self.marks.len() > self.flat.len() && m.kept >= 2).map(|m| m.len)
}
/// Measure the segments that are not measured, from the first, until one starts past `s` (with
/// two points kept before it) or every one is measured.
fn measure_to(&mut self, s: f64, work: &mut impl FnMut(SpreadWork)) {
while let Some(run) = self.flat.get(self.marks.len() - 1) {
let Some(&m) = self.marks.last() else { return };
if self.marks.len() >= 2 && m.kept >= 2 && m.len > s {
return;
}
work(SpreadWork::Measure);
self.marks.push(m.then(self.pts.get(run.clone()).unwrap_or_default()));
}
}
/// The anchor of `sp` at arc length `s`: an existing one within a hundredth of a point, else a
/// new one splitting the segment there. The segment is the last one starting at or before `s`
/// (the first one when none does), found by a binary search. `None`, leaving `sp` as it was,
/// when `s` or the arc length at the end of the segment is not finite, or when `sp` flattens
/// to fewer than two points.
fn anchor_at_length(&mut self, sp: &mut SubPath, s: f64, work: &mut impl FnMut(SpreadWork)) -> Option<usize> {
if !s.is_finite() {
return None;
}
self.measure_to(s, work);
let n = self.flat.len();
if self.marks.last().is_none_or(|m| m.kept < 2) {
return None;
}
let starts = &self.marks[..self.marks.len().min(n)];
let seg = starts
.partition_point(|m| {
work(SpreadWork::Compare);
m.len <= s
})
.saturating_sub(1);
let from = self.marks.get(seg)?.len;
let to = self.marks.get(seg + 1)?.len;
if s - from < 0.01 {
return Some(seg);
}
if to - s < 0.01 {
return Some((seg + 1) % sp.anchors.len().max(1));
}
if !from.is_finite() || !to.is_finite() {
return None;
}
let c = sp.segment(seg);
// The flattened length and the curve's own differ slightly: scale into the curve's.
let arc = c.arclen(1e-4).max(1e-12);
let t = c.inv_arclen((s - from) / (to - from).max(1e-12) * arc, 1e-4).clamp(1e-4, 1.0 - 1e-4);
if !t.is_finite() {
return None;
}
let at = sp.insert_anchor(seg, t);
work(SpreadWork::Segment);
work(SpreadWork::Segment);
let halves = [self.flatten(sp, seg), self.flatten(sp, seg + 1)];
self.flat.splice(seg..=seg, halves);
self.marks.truncate(seg + 1);
Some(at)
}
let c = sp.segment(seg);
// The flattened length and the curve's own differ slightly: scale into the curve's.
let arc = c.arclen(1e-4).max(1e-12);
let t = c.inv_arclen((s - from) / (to - from).max(1e-12) * arc, 1e-4).clamp(1e-4, 1.0 - 1e-4);
Some(sp.insert_anchor(seg, t))
}
/// Where a blend's keys and steps go along its spine (see [`blend_spine`]).
@@ -1840,6 +2033,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 +2106,220 @@ 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}");
}
}
/// [`spread_anchors`] by measuring the whole spine again for each key and walking its segments
/// from the last, as a reference for the measurement kept up to date between keys.
fn rebuilt_spread_anchors(path: &mut PathData, k: usize) -> Option<Vec<usize>> {
let total = Spine::new(path)?.length();
let closed = path.subpaths.first().is_some_and(|s| s.closed);
let mut out = vec![0usize];
for i in 1..k.saturating_sub(1) {
let s = total * i as f64 / (k - 1) as f64;
let spine = Spine::new(path)?;
let sp = path.subpaths.first_mut()?;
let n = sp.segment_count();
let seg = (0..n).rev().find(|i| spine.anchor_length(*i).is_some_and(|l| l <= s)).unwrap_or(0);
let from = spine.anchor_length(seg).unwrap_or(0.0);
let to = spine.anchor_length(seg + 1).unwrap_or(spine.length());
out.push(if s - from < 0.01 {
seg
} else if to - s < 0.01 {
(seg + 1) % sp.anchors.len().max(1)
} else {
let c = sp.segment(seg);
let arc = c.arclen(1e-4).max(1e-12);
let t = c.inv_arclen((s - from) / (to - from).max(1e-12) * arc, 1e-4).clamp(1e-4, 1.0 - 1e-4);
sp.insert_anchor(seg, t)
});
}
let last = path.subpaths.first().map_or(0, |sp| if closed { 0 } else { sp.anchors.len().saturating_sub(1) });
out.push(last);
Some(out)
}
/// Spreading keys along a spine measured once and kept up to date gives the same anchors and
/// the same spine as measuring it again for each key: on open and closed polylines and curves,
/// zero-length segments, keys exactly on anchors, keys within, at and just past a hundredth of
/// a point from an anchor, a closed curve whose keys go round past its first anchor, many keys
/// in one segment, and paths with no segment. The closed spines open as [`pin_spine`] opens
/// them.
#[test]
fn spreading_keys_matches_measuring_the_spine_for_each_key() {
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 mut spines = vec![
PathData::default(),
PathData::single(SubPath::default()),
PathData::single(SubPath::polyline(&[p(5.0, 5.0)], false)),
PathData::single(SubPath::polyline(&[p(5.0, 5.0), p(5.0, 5.0)], false)),
PathData::single(SubPath::polyline(&[p(0.0, 0.0), p(100.0, 0.0)], false)),
PathData::single(SubPath::polyline(&[p(0.0, 0.0), p(100.0, 0.0)], true)),
PathData::single(SubPath::polyline(&[p(0.0, 0.0), p(10.0, 0.0), p(20.0, 0.0), p(30.0, 0.0)], false)),
PathData::single(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)),
PathData::single(SubPath::polyline(&[p(0.0, 0.0), p(0.0, 0.0), p(40.0, 0.0), p(40.0, 30.0)], true)),
PathData::single(SubPath::polyline(&[p(0.0, 0.0), p(40.0, 0.0), p(40.0, 30.0), p(0.0, 0.0)], true)),
PathData::single(bow.clone()),
PathData::single(SubPath { closed: true, ..bow }),
shapes::ellipse(Rect::new(0.0, 0.0, 120.0, 80.0)),
];
// An anchor near where the middle of three keys goes, 10 along a spine 20 long.
for d in [0.0, 0.005, 0.0099, 0.01, 0.0101, 0.02] {
for x in [10.0 - d, 10.0 + d] {
spines.push(PathData::single(SubPath::polyline(&[p(0.0, 0.0), p(x, 0.0), p(20.0, 0.0)], false)));
}
}
let mut compared = 0;
for spine in &spines {
for k in (0..=12).chain([17, 50, 200]) {
let (mut a, mut b) = (spine.clone(), spine.clone());
let (ka, kb) = (spread_anchors(&mut a, k), rebuilt_spread_anchors(&mut b, k));
assert_eq!(ka, kb, "{k} keys on {spine:?}");
assert_eq!(a, b, "{k} keys on {spine:?}");
if let (Some(mut ka), Some(mut kb)) = (ka, kb) {
let (mut sa, mut sb) = (a.subpaths[0].clone(), b.subpaths[0].clone());
open_at_start(&mut sa, &mut ka);
open_at_start(&mut sb, &mut kb);
assert_eq!((sa, ka), (sb, kb), "{k} keys on {spine:?}, opened");
compared += 1;
}
}
}
assert!(compared > 200, "{compared} spreads compared");
}
/// Spreading 1,000 keys along a spine of 4,096 segments flattens the spine once and then only
/// the two halves of each split segment, finds each key's segment in a few comparisons, and
/// measures about as many segments as the spine ends up with, not the whole spine per key.
#[test]
fn spreading_keys_measures_the_spine_once() {
let pts: Vec<Point> = (0..=4096).map(|i| Point::new(i as f64, if i % 2 == 0 { 0.0 } else { 1.0 })).collect();
let mut path = PathData::single(SubPath::polyline(&pts, false));
let (mut whole, mut segments, mut measured, mut compared) = (0, 0, 0, 0);
let ka = spread_anchors_with(&mut path, 1000, |w| match w {
SpreadWork::WholePath => whole += 1,
SpreadWork::Segment => segments += 1,
SpreadWork::Measure => measured += 1,
SpreadWork::Compare => compared += 1,
})
.unwrap();
assert_eq!(ka.len(), 1000);
let n = path.subpaths[0].segment_count();
assert!(n > 4096 + 900, "{n} segments");
assert_eq!(whole, 1);
assert!(segments <= 2 * 998, "{segments} segments flattened");
assert!(compared <= 998 * 14, "{compared} comparisons");
assert!(measured <= 4096 + n + 3 * 1000, "{measured} segments measured for {n}");
let mut reference = PathData::single(SubPath::polyline(&pts, false));
assert_eq!(rebuilt_spread_anchors(&mut reference, 1000), Some(ka));
assert_eq!(reference, path);
}
/// A spine so large that its length overflows spreads no keys, and is left as it was, rather
/// than getting an anchor split at a parameter that is not a number. Two keys, which split
/// nothing, get no anchors either.
#[test]
fn spreading_keys_along_a_spine_whose_length_overflows_changes_nothing() {
let p = Point::new;
for closed in [false, true] {
for k in [2, 3, 5] {
let spine = PathData::single(SubPath::polyline(&[p(-1e308, 0.0), p(0.0, 0.0), p(1e308, 0.0)], closed));
let mut path = spine.clone();
assert_eq!(spread_anchors(&mut path, k), None, "closed {closed}, {k} keys");
assert_eq!(path, spine);
assert!(path.subpaths[0].anchors.iter().all(|a| a.p.x.is_finite() && a.h_in.x.is_finite() && a.h_out.x.is_finite()));
}
}
}
/// When a later arc length has no anchor (here one that is not finite, as when a spine's length
/// overflows only after earlier splits), the splits already made are dropped with it.
#[test]
fn a_failed_anchor_keeps_none_of_the_earlier_splits() {
let sp = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0)], false);
for bad in [f64::NAN, f64::INFINITY] {
let mut split = sp.clone();
let lengths = SpreadLengths::new(&split, &mut |_| {});
assert_eq!(anchors_at_lengths(&mut split, lengths, [25.0, 50.0, bad], &mut |_| {}), None);
assert_eq!(split, sp);
}
let mut split = sp.clone();
let lengths = SpreadLengths::new(&split, &mut |_| {});
assert_eq!(anchors_at_lengths(&mut split, lengths, [25.0, 50.0], &mut |_| {}), Some(vec![1, 2]));
assert_eq!(split.anchors.len(), 4);
}
#[test]
fn easing_keeps_the_ends_and_stays_monotone() {
use crate::live::{BlendEase, BlendEaseType as K};
+237 -44
View File
@@ -3,6 +3,7 @@
//! the ruler origin and the objects an edit touches), so a file holding something beyond it could be
//! opened but not edited: one object, artboard or guide out there made every move fail.
use std::collections::BTreeSet;
use std::sync::Arc;
use vectorcraft_geom::{Point, Rect};
@@ -72,27 +73,41 @@ fn clipping(n: &Node) -> Option<bool> {
}
}
/// Does `n`, or any object in it, reach beyond the canvas? A container is looked into object by
/// object: its own bounds leave out a layer's hidden objects and, when it clips, all but its
/// clipping path.
fn reaches_beyond(n: &Node) -> bool {
match clipping(n) {
None => beyond(n),
Some(_) => n.children().is_some_and(|c| c.iter().any(|c| reaches_beyond(c))),
/// The objects of a layer or group that a walk picked, by index in order, each with what was
/// picked inside it (nothing for an object that is not a container).
#[derive(Debug, Default)]
struct Picked(Vec<(usize, Picked)>);
/// What in `n` reaches beyond the canvas, by `far`, or `None` when nothing does. A container is
/// looked into object by object: its own bounds leave out a layer's hidden objects and, when it
/// clips, all but its clipping path. Each object is measured once, and the objects a clipping
/// path beyond the canvas clips are not measured: they go with it (see [`clips_beyond`]).
fn reach(n: &Node, far: &impl Fn(&Node) -> bool) -> Option<Picked> {
let Some(clip) = clipping(n) else { return far(n).then(Picked::default) };
let mut inner = Vec::new();
for (i, c) in n.children().into_iter().flatten().enumerate() {
if let Some(p) = reach(c, far) {
inner.push((i, p));
if clip && i == 0 {
break;
}
}
}
(!inner.is_empty()).then_some(Picked(inner))
}
/// Does `n` clip by a path that reaches beyond the canvas? Then the path and the objects it clips
/// go together, so no other object becomes the clipping path.
fn clips_beyond(n: &Node) -> bool {
clipping(n) == Some(true) && n.children().and_then(|c| c.first()).is_some_and(|c| reaches_beyond(c))
/// Does `n`, whose objects beyond the canvas are `found`, clip by a path that reaches beyond it?
/// Then the path and the objects it clips go together, so no other object becomes the clipping
/// path.
fn clips_beyond(n: &Node, found: &Picked) -> bool {
clipping(n) == Some(true) && found.0.first().is_some_and(|(i, _)| *i == 0)
}
/// Add the ids of `n` and the layers in it, if it is a layer, to `layers`: their layer guides go
/// with them.
fn layers_in(n: &Node, layers: &mut Vec<NodeId>) {
fn layers_in(n: &Node, layers: &mut BTreeSet<NodeId>) {
if matches!(n.kind, NodeKind::Layer { .. }) {
layers.push(n.id);
layers.insert(n.id);
}
if clipping(n).is_some() {
for c in n.children().into_iter().flatten() {
@@ -109,22 +124,22 @@ fn guides_in(n: &Node) -> usize {
}
}
/// Remove the objects in `node` that reach beyond the canvas: a layer or group keeps those of its
/// objects within it, unless its clipping path reaches beyond (see [`clips_beyond`]); anything
/// else goes whole. Only containers holding such an object are copied. Recursion follows the
/// nesting, which [`Document::limit_depth`] bounds. The layers removed are added to `layers`, and
/// the ruler guides they held to `guides`.
fn drop_children_beyond(node: &mut Arc<Node>, dropped: &mut usize, layers: &mut Vec<NodeId>, guides: &mut usize) {
if !node.children().is_some_and(|c| c.iter().any(|c| reaches_beyond(c))) {
return;
}
/// Remove the objects in `node` that reach beyond the canvas, which [`reach`] `found`: a layer or
/// group keeps those of its objects within it, unless its clipping path reaches beyond (see
/// [`clips_beyond`]); anything else goes whole. Only containers holding such an object are
/// copied, and only those are visited again. Recursion follows the nesting, which
/// [`Document::limit_depth`] bounds. The layers removed are added to `layers`, and the ruler
/// guides they held to `guides`.
fn drop_children_beyond(node: &mut Arc<Node>, found: Picked, dropped: &mut usize, layers: &mut BTreeSet<NodeId>, guides: &mut usize) {
let Some(children) = Arc::make_mut(node).children_mut() else { return };
let mut found = found.0.into_iter().peekable();
let mut next = 0;
children.retain_mut(|c| {
if !reaches_beyond(c) {
return true;
}
if clipping(c).is_some() && !clips_beyond(c) {
drop_children_beyond(c, dropped, layers, guides);
let at = next;
next += 1;
let Some((_, inner)) = found.next_if(|(i, _)| *i == at) else { return true };
if clipping(c).is_some() && !clips_beyond(c, &inner) {
drop_children_beyond(c, inner, dropped, layers, guides);
return true;
}
layers_in(c, layers);
@@ -134,21 +149,49 @@ fn drop_children_beyond(node: &mut Arc<Node>, dropped: &mut usize, layers: &mut
});
}
/// Is `id` unset, or not one of `ids`? The check takes time logarithmic in the number of ids.
fn not_in<T: Ord>(id: Option<T>, ids: &BTreeSet<T>) -> bool {
id.is_none_or(|i| !ids.contains(&i))
}
/// Remove the ruler guides of layer `layer` and of its sublayers that `out` picks, adding how many
/// to `dropped`. Only layers holding one are copied.
/// to `dropped`. `out` looks at each object in the layers once. Only layers holding one are
/// copied.
fn drop_guides(layer: &mut Arc<Node>, out: &impl Fn(&Node) -> bool, dropped: &mut usize) {
fn holds(n: &Node, out: &impl Fn(&Node) -> bool) -> bool {
n.is_layer() && n.children().is_some_and(|ch| ch.iter().any(|c| out(c) || holds(c, out)))
/// The objects of `n`, if it is a layer, that `out` picks (with nothing inside), and its
/// sublayers holding one (with what they hold), or `None` when it holds none.
fn holds(n: &Node, out: &impl Fn(&Node) -> bool) -> Option<Picked> {
if !n.is_layer() {
return None;
}
let inner: Vec<(usize, Picked)> = n
.children()
.into_iter()
.flatten()
.enumerate()
.filter_map(|(i, c)| if out(c) { Some((i, Picked::default())) } else { holds(c, out).map(|p| (i, p)) })
.collect();
(!inner.is_empty()).then_some(Picked(inner))
}
if !holds(layer, out) {
return;
fn drop(layer: &mut Arc<Node>, held: Picked, dropped: &mut usize) {
let Some(children) = Arc::make_mut(layer).children_mut() else { return };
let mut held = held.0.into_iter().peekable();
let mut next = 0;
children.retain_mut(|c| {
let at = next;
next += 1;
let Some((_, inner)) = held.next_if(|(i, _)| *i == at) else { return true };
// A sublayer holds something; an object picked itself has nothing inside.
if inner.0.is_empty() {
*dropped += 1;
return false;
}
drop(c, inner, dropped);
true
});
}
let Some(children) = Arc::make_mut(layer).children_mut() else { return };
let before = children.len();
children.retain(|c| !out(c));
*dropped += before - children.len();
for c in children.iter_mut().filter(|c| c.is_layer()) {
drop_guides(c, out, dropped);
if let Some(held) = holds(layer, out) {
drop(layer, held, dropped);
}
}
@@ -162,9 +205,10 @@ impl Document {
/// whose artboards were all removed has none left.
pub fn drop_beyond_canvas(&mut self) -> BeyondCanvas {
let mut gone = BeyondCanvas::default();
let mut layers = vec![];
let mut layers = BTreeSet::new();
for layer in &mut self.layers {
if clips_beyond(layer) {
let Some(found) = reach(layer, &beyond) else { continue };
if clips_beyond(layer, &found) {
let layer = Arc::make_mut(layer);
if let NodeKind::Layer { children, clip, .. } = &mut layer.kind {
for c in children.iter() {
@@ -177,7 +221,7 @@ impl Document {
*clip = false;
}
} else {
drop_children_beyond(layer, &mut gone.objects, &mut layers, &mut gone.guides);
drop_children_beyond(layer, found, &mut gone.objects, &mut layers, &mut gone.guides);
}
}
if gone.objects > 0 {
@@ -192,13 +236,13 @@ impl Document {
self.retire_artboard_id(*id);
}
gone.artboards = removed.len();
let removed: BTreeSet<u32> = removed.into_iter().collect();
// The saved list, when the guides are not nodes yet ([`Document::guides_into_nodes`]).
let guides = self.saved_guides.len();
self.saved_guides
.retain(|g| in_range(g.pos) && g.artboard.is_none_or(|a| !removed.contains(&a)) && g.layer.is_none_or(|l| !layers.contains(&l)));
self.saved_guides.retain(|g| in_range(g.pos) && not_in(g.artboard, &removed) && not_in(g.layer, &layers));
gone.guides += guides - self.saved_guides.len();
let out = |n: &Node| match n.kind {
NodeKind::RulerGuide { pos, artboard, .. } => !in_range(pos) || artboard.is_some_and(|a| removed.contains(&a)),
NodeKind::RulerGuide { pos, artboard, .. } => !in_range(pos) || !not_in(artboard, &removed),
_ => false,
};
for layer in &mut self.layers {
@@ -392,4 +436,153 @@ mod tests {
assert_eq!(d.assets.iter().map(|a| (a.id, a.nodes.clone())).collect::<Vec<_>>(), [(2, vec![NodeId(10)])]);
assert_eq!(d.variables.bindings.keys().copied().collect::<Vec<_>>(), [NodeId(10)]);
}
#[test]
fn guides_of_many_removed_artboards_and_layers_go_and_the_rest_keep_their_order() {
let probe = Document::new(1.0, 1.0);
// Sublayers 40 to 43 clip by a path beyond the canvas, so they go whole; 50 stays.
let far: Vec<Arc<Node>> = (40..44).map(|id| sublayer(&probe, id, vec![rect(id * 10, 1e17), rect(id * 10 + 1, 0.0)], true)).collect();
let near = sublayer(&probe, 50, vec![rect(500, 0.0)], false);
let mut d = doc(far.into_iter().chain([near, rect(10, 0.0)]).collect());
let kept = d.artboards[0].id;
for id in 9..13 {
d.artboards.push(Artboard { id, rect: Rect::new(0.0, 1e17, 100.0, 1e17 + 100.0), ..d.artboards[0].clone() });
}
let top = d.layers[0].id;
let guide = |pos: f64, artboard: Option<u32>, layer: Option<NodeId>| Guide { artboard, layer, ..Guide::new(false, pos) };
d.saved_guides = vec![
guide(1.0, Some(9), None),
guide(2.0, None, None),
guide(3.0, Some(kept), Some(NodeId(41))),
guide(4.0, Some(kept), None),
guide(5.0, Some(12), None),
guide(6.0, None, Some(NodeId(50))),
guide(7.0, None, Some(NodeId(43))),
guide(8.0, Some(10), Some(top)),
guide(9.0, None, Some(top)),
];
d.saved_selections = vec![crate::records::SavedSelection { name: "s".into(), objects: vec![NodeId(42), NodeId(10), NodeId(500)] }].into();
let mut nodes = d.clone();
assert_eq!(nodes.guides_into_nodes(), 9);
let gone = d.drop_beyond_canvas();
assert_eq!(gone, BeyondCanvas { objects: 4, artboards: 4, guides: 5, ruler_origin: false });
assert_eq!(d.artboards.iter().map(|a| a.id).collect::<Vec<_>>(), [kept]);
let left: Vec<f64> = d.saved_guides.iter().map(|g| g.pos).collect();
assert_eq!(left, [2.0, 4.0, 6.0, 9.0], "the guides that stay keep their order");
assert_eq!(d.saved_selections[0].objects, [NodeId(10), NodeId(500)]);
assert_eq!(nodes.drop_beyond_canvas(), gone, "guide nodes go as saved guides do");
let mut left: Vec<f64> = nodes.ruler_guides().iter().map(|g| g.pos).collect();
left.sort_by(f64::total_cmp);
assert_eq!(left, [2.0, 4.0, 6.0, 9.0]);
assert_eq!(nodes.saved_selections, d.saved_selections);
}
thread_local! {
static COMPARISONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// An id that counts how often it is compared.
#[derive(Debug)]
struct Counted(u32);
impl Ord for Counted {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
COMPARISONS.with(|c| c.set(c.get() + 1));
self.0.cmp(&other.0)
}
}
impl PartialOrd for Counted {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for Counted {
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == std::cmp::Ordering::Equal
}
}
impl Eq for Counted {}
#[test]
fn a_guide_is_checked_without_scanning_every_removed_id() {
let per_guide = |removed: u32| {
let ids: BTreeSet<Counted> = (0..removed).map(|i| Counted(i * 2)).collect();
COMPARISONS.with(|c| c.set(0));
// Guides on removed ids, on ids between them, on ids past them and on none.
let guides: Vec<Option<Counted>> = (0..64).map(|i| (i % 4 != 3).then(|| Counted(i * 31 % (removed * 2 + 8)))).collect();
let kept = guides.into_iter().filter(|g| not_in(g.as_ref().map(|c| Counted(c.0)), &ids)).count();
assert!(kept > 0 && kept < 64);
COMPARISONS.with(|c| c.get()) as f64 / 64.0
};
let small = per_guide(16);
let large = per_guide(16_384);
// A sorted lookup grows with the depth of the tree; a scan of 16,384 ids compares thousands per guide.
assert!(large < small * 32.0 && large < 256.0, "{small} comparisons per guide among 16 ids, {large} among 16,384");
}
#[test]
fn each_object_is_measured_once_however_deep_the_nesting() {
// 32 groups, each inside the one before and holding an object within the canvas; the
// innermost also holds one beyond it. Beside them, a group with nothing beyond and a clip
// group whose clipping path reaches beyond.
let mut chain = Arc::new(Node::group(NodeId(100), vec![rect(200, 0.0), rect(201, 1e17)]));
for depth in 1..32 {
chain = Arc::new(Node::group(NodeId(100 + depth), vec![rect(300 + depth, 0.0), chain]));
}
let still = Arc::new(Node::group(NodeId(400), vec![rect(401, 0.0), rect(402, 5.0)]));
let clip = Arc::new(Node::new(NodeId(600), NodeKind::Group { children: vec![rect(601, 1e17), rect(602, 0.0), rect(603, 0.0)], clip: true }));
let mut d = doc(vec![chain, Arc::clone(&still), clip]);
let mut whole = d.clone();
let measured = std::cell::Cell::new(0_usize);
let far = |n: &Node| {
measured.set(measured.get() + 1);
beyond(n)
};
let layer = &mut d.layers[0];
let found = reach(layer, &far).unwrap();
assert_eq!(
measured.get(),
36,
"the 33 objects in the groups, the 2 beside them and the clipping path, each measured once; not what the path clips"
);
assert!(!clips_beyond(layer, &found));
let (mut dropped, mut layers, mut guides) = (0, BTreeSet::new(), 0);
drop_children_beyond(layer, found, &mut dropped, &mut layers, &mut guides);
assert_eq!(measured.get(), 36, "removing measures nothing again");
assert_eq!((dropped, layers.len(), guides), (2, 0, 0));
assert!(d.layers[0].children().is_some_and(|c| Arc::ptr_eq(&c[1], &still)), "a group with nothing beyond is not copied");
assert_eq!(whole.drop_beyond_canvas(), BeyondCanvas { objects: 2, ..Default::default() });
assert_eq!(ids(&whole), ids(&d));
assert!(!ids(&d).contains(&201) && !ids(&d).contains(&600) && ids(&d).contains(&200) && ids(&d).contains(&331));
}
#[test]
fn each_object_is_looked_at_once_when_guides_go_from_nested_layers() {
let guide = |id: u64, pos: f64| Arc::new(Node::new(NodeId(id), NodeKind::RulerGuide { vertical: false, pos, artboard: None }));
let probe = Document::new(1.0, 1.0);
// 32 sublayers, each inside the one before, each holding a guide within the canvas and one
// beyond it. Beside them, a sublayer with nothing to remove.
let mut chain = sublayer(&probe, 100, vec![guide(200, 5.0), guide(201, 1e17)], false);
for depth in 1..32 {
chain = sublayer(&probe, 100 + depth, vec![guide(300 + depth * 2, 5.0), guide(301 + depth * 2, 1e17), chain], false);
}
let still = sublayer(&probe, 500, vec![guide(501, 5.0), rect(502, 0.0)], false);
let mut d = doc(vec![chain, Arc::clone(&still)]);
let looked = std::cell::Cell::new(0_usize);
let out = |n: &Node| {
looked.set(looked.get() + 1);
matches!(n.kind, NodeKind::RulerGuide { pos, .. } if !in_range(pos))
};
let mut dropped = 0;
drop_guides(&mut d.layers[0], &out, &mut dropped);
assert_eq!(dropped, 32);
assert_eq!(looked.get(), 2 + 2 + 31 * 3 + 2, "each object in the layers is looked at once");
assert!(d.layers[0].children().is_some_and(|c| Arc::ptr_eq(&c[1], &still)), "a sublayer with nothing to remove is not copied");
let left = d.ruler_guides();
assert_eq!(left.len(), 33);
assert!(left.iter().all(|g| g.pos == 5.0));
}
}
+205 -38
View File
@@ -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)
@@ -150,25 +165,181 @@ fn planar(d: &mut tiff::decoder::Decoder<Cursor<&[u8]>>) -> bool {
/// stores each pixel's samples together or one plane per channel. `None` when they don't decode to
/// that many samples, which includes images whose planes together need more than the decoder's
/// limit (256 MB of samples).
fn read_samples(d: &mut tiff::decoder::Decoder<Cursor<&[u8]>>, n: usize, per: usize) -> Option<Vec<u8>> {
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
+197
View File
@@ -0,0 +1,197 @@
//! Image Tools › Color Mask: colors of an image object that are hidden while its pixels stay as
//! they are.
//!
//! A masked image is an ordinary image ([`NodeKind::Image`]) with a [`ColorMask`] in its extras
//! ([`crate::node::NodeExtras::color_mask`]). The record holds the mask's settings and the key of
//! the image's pixels with the hidden colors made clear ([`ColorMask::key`]), made by the engine
//! from the pixels named by [`ColorMask::from`]. The image's own key keeps naming its own pixels,
//! so removing the mask gives them back. While the image's key is [`ColorMask::from`], it is drawn
//! and output with the masked pixels ([`Document::shown_image`]); when another key replaced it
//! (a link updated, the image cropped), it shows its own pixels until the engine makes the masked
//! pixels again.
//!
//! The concept is that of PDF's color key masking (ISO 32000-1, 8.9.6.4): samples in the chosen
//! colors are not painted and what is behind the image shows through. Which colors match, and how
//! near ones fade out, are VectorCraft's own rules.
use std::borrow::Cow;
use serde::{Deserialize, Serialize};
use crate::{Document, ImageObject, Node, NodeKind};
/// Where a color mask's colors come from.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MaskBackground {
/// The most common color along the image's edges.
#[default]
Edges,
/// The average of the image's corner pixels that are not clear.
Corners,
/// The colors in [`ColorMask::colors`].
Colors,
}
/// How near a color must be to a masked one.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MaskMatch {
/// The RGB distance, as a percentage of the largest one.
#[default]
Distance,
/// The largest difference on one of red, green and blue, as a percentage of a channel's range.
Channels,
}
/// The colors an image object hides (see the module docs).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ColorMask {
/// Key into [`Document::images`]: the pixels of [`Self::from`] with the hidden colors made
/// clear. Named `key` in the file, so the file keeps those pixels with the document.
pub key: String,
/// The image's own key when the masked pixels were made.
pub from: String,
#[serde(default)]
pub background: MaskBackground,
/// The hidden colors (8-bit RGB) with [`MaskBackground::Colors`].
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub colors: Vec<[u8; 3]>,
/// Only the matching pixels that reach in from an edge are hidden. A record without it reads
/// as `true`, the command's default.
#[serde(default = "default_contiguous")]
pub contiguous: bool,
#[serde(default, rename = "match")]
pub measure: MaskMatch,
/// How near a color must be to be hidden, 0 to 100 (see [`MaskMatch`]). A record without it
/// reads as 10, the command's default.
#[serde(default = "default_percent")]
pub tolerance: f64,
/// The band past the tolerance over which pixels fade from hidden to shown, 0 to 100. A record
/// without it reads as 10, the command's default.
#[serde(default = "default_percent")]
pub softness: f64,
}
fn default_contiguous() -> bool {
true
}
fn default_percent() -> f64 {
10.0
}
impl ColorMask {
/// Whether the masked pixels were made from the pixels of `im`.
pub fn made_for(&self, im: &ImageObject) -> bool {
im.pixels.is_none() && self.from == im.key
}
}
impl Document {
/// Image `im` of node `n` as it is drawn and output. With a color mask whose masked pixels were
/// made from the image's own pixels and are in this document ([`ColorMask::made_for`]): a copy
/// that shows those pixels and links to no file, so an output that refers to a linked file
/// writes the masked pixels instead. Otherwise, and for a mask that hides nothing (its masked
/// pixels are the image's own), `im` itself.
pub fn shown_image<'a>(&self, n: &Node, im: &'a ImageObject) -> Cow<'a, ImageObject> {
match n.extras().color_mask.as_deref() {
Some(m) if m.key != im.key && m.made_for(im) && self.images.contains_key(&m.key) => {
Cow::Owned(ImageObject { key: m.key.clone(), link: None, ..im.clone() })
}
_ => Cow::Borrowed(im),
}
}
/// The color mask of image node `n`, if it has one.
pub fn color_mask_of(n: &Node) -> Option<&ColorMask> {
matches!(n.kind, NodeKind::Image(_)).then(|| n.extras().color_mask.as_deref()).flatten()
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use vectorcraft_geom::Affine;
use super::*;
use crate::{ImageBlob, NodeId};
fn image(key: &str) -> ImageObject {
ImageObject { key: key.into(), width: 2, height: 2, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }
}
fn mask(key: &str, from: &str) -> ColorMask {
ColorMask {
key: key.into(),
from: from.into(),
background: MaskBackground::Colors,
colors: vec![[255, 255, 255]],
contiguous: false,
measure: MaskMatch::Distance,
tolerance: 10.0,
softness: 0.0,
}
}
#[test]
fn a_masked_image_shows_its_masked_pixels_while_they_were_made_from_its_own() {
let mut d = Document::new(100.0, 100.0);
d.images.insert("own".into(), ImageBlob::png(vec![1]));
d.images.insert("masked".into(), ImageBlob::png(vec![2]));
let mut n = Node::new(NodeId(5), NodeKind::Image(Box::new(image("own"))));
let NodeKind::Image(im) = &n.kind else { unreachable_kind() };
assert_eq!(d.shown_image(&n, im).key, "own", "no mask: its own pixels");
n.extras_mut().color_mask = Some(Box::new(mask("masked", "own")));
let NodeKind::Image(im) = &n.kind else { unreachable_kind() };
assert_eq!(d.shown_image(&n, im).key, "masked");
// Linked: the shown copy links to nothing, so outputs write the masked pixels.
let mut linked = (**im).clone();
linked.link = Some(crate::LinkInfo::new("/a.png"));
assert_eq!(d.shown_image(&n, &linked).link, None);
// Made from other pixels: its own until they are made again.
assert_eq!(d.shown_image(&n, &image("other")).key, "other");
// Masked pixels the document doesn't have: its own.
n.extras_mut().color_mask = Some(Box::new(mask("gone", "own")));
let NodeKind::Image(im) = &n.kind else { unreachable_kind() };
assert_eq!(d.shown_image(&n, im).key, "own");
// Pixels an image holds itself are drawn as they are.
let own = ImageObject { pixels: Some(Arc::new(ImageBlob::png(vec![3]))), ..image("own") };
n.extras_mut().color_mask = Some(Box::new(mask("masked", "own")));
assert_eq!(d.shown_image(&n, &own).key, "own");
// A mask that hides nothing (its masked pixels are the image's own): the image itself, so
// a linked image stays linked in outputs.
n.extras_mut().color_mask = Some(Box::new(mask("own", "own")));
assert_eq!(d.shown_image(&n, &linked).link, linked.link);
}
#[test]
fn a_mask_saves_and_reads_back_with_its_node() {
let mut n = Node::new(NodeId(5), NodeKind::Image(Box::new(image("own"))));
n.extras_mut().color_mask = Some(Box::new(mask("masked", "own")));
let json = serde_json::to_value(&n).unwrap();
assert_eq!(json["color_mask"]["key"], "masked", "the masked pixels' key is a `key` member: {json}");
assert_eq!(json["color_mask"]["match"], "distance");
let back: Node = serde_json::from_value(json).unwrap();
assert_eq!(back, n);
// A node without one writes none.
let plain = Node::new(NodeId(6), NodeKind::Image(Box::new(image("own"))));
assert!(serde_json::to_value(&plain).unwrap().get("color_mask").is_none());
}
/// A record that leaves out settings reads them as the command's defaults: edge color,
/// contiguous, distance, tolerance and softness 10.
#[test]
fn a_record_without_settings_reads_the_defaults() {
let m: ColorMask = serde_json::from_value(serde_json::json!({"key": "masked", "from": "own"})).unwrap();
assert_eq!(
(m.background, m.colors.len(), m.contiguous, m.measure, m.tolerance, m.softness),
(MaskBackground::Edges, 0, true, MaskMatch::Distance, 10.0, 10.0)
);
}
fn unreachable_kind() -> ! {
panic!("an image node")
}
}
+7 -4
View File
@@ -78,6 +78,7 @@ impl Document {
units_from_file: _,
index: _,
guide_cache: _,
inline_cycles: _,
} = self;
*version == other.version
&& *title == other.title
@@ -262,6 +263,7 @@ impl Document {
units_from_file: false,
index: Default::default(),
guide_cache: Default::default(),
inline_cycles: Default::default(),
};
let id = d.alloc_id();
d.layers.push(Arc::new(Node::layer(id, "Layer 1", LayerColor::Preset(0))));
@@ -286,7 +288,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 +301,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.
+453 -86
View File
@@ -183,8 +183,8 @@ impl Document {
self.layers.retain(|l| !l.is_ruler_guide());
gone -= self.layers.len();
for l in &mut self.layers {
if layer_untidy(l) {
gone += tidy_layer(Arc::make_mut(l));
if let Some(found) = untidy(l, &Node::is_ruler_guide) {
gone += tidy_layer(Arc::make_mut(l), found);
}
}
let others = self
@@ -198,8 +198,8 @@ impl Document {
if root.is_ruler_guide() {
*root = Arc::new(Node::group(root.id, vec![]));
gone += 1;
} else if any_guide(root) {
gone += drop_guides_below(Arc::make_mut(root));
} else if let Some(found) = guides_below(root, &Node::is_ruler_guide) {
gone += drop_guides_below(Arc::make_mut(root), found);
}
}
gone
@@ -272,8 +272,8 @@ impl Document {
return;
}
for l in &mut self.layers {
if l.holds_ruler_guides() {
Arc::make_mut(l).strip_ruler_guides();
if let Some(held) = picked_in_layers(l, &Node::is_ruler_guide) {
drop_picked(l, held);
}
}
self.saved_guides.extend(guides);
@@ -347,16 +347,14 @@ impl Document {
/// saved guide whose layer is gone opens. Returns the removed node, without the guides.
pub fn remove_edit_layer(&mut self, id: NodeId) -> Result<Arc<Node>, crate::DocError> {
let mut layer = self.remove(id)?;
if !layer.holds_ruler_guides() {
return Ok(layer);
}
let Some(held) = picked_in_layers(&layer, &Node::is_ruler_guide) else { return Ok(layer) };
let mut guides = vec![];
layer.walk(&mut |c| {
if c.is_ruler_guide() {
guides.push(Arc::new(c.clone()));
}
});
Arc::make_mut(&mut layer).strip_ruler_guides();
drop_picked(&mut layer, held);
let home = self.default_layer().unwrap_or_else(|| self.add_layer(None));
self.children_mut(Some(home))?.extend(guides);
Ok(layer)
@@ -418,21 +416,11 @@ impl Document {
if gone.is_empty() {
return 0;
}
fn drop(layer: &mut Arc<Node>, gone: &HashSet<NodeId>) {
fn holds(n: &Node, gone: &HashSet<NodeId>) -> bool {
n.is_layer() && n.children().is_some_and(|ch| ch.iter().any(|c| gone.contains(&c.id) || holds(c, gone)))
}
if !holds(layer, gone) {
return;
}
let Some(ch) = Arc::make_mut(layer).children_mut() else { return };
ch.retain(|c| !(c.is_ruler_guide() && gone.contains(&c.id)));
for c in ch.iter_mut().filter(|c| c.is_layer()) {
drop(c, gone);
}
}
let pick = |n: &Node| n.is_ruler_guide() && gone.contains(&n.id);
for l in &mut self.layers {
drop(l, &gone);
if let Some(held) = picked_in_layers(l, &pick) {
drop_picked(l, held);
}
}
sel.guides.retain(|id| !gone.contains(id));
if sel.key_guide.is_some_and(|k| gone.contains(&k)) {
@@ -444,29 +432,11 @@ impl Document {
/// Change the line of every ruler guide on artboard `id` with `f` (whether it is vertical, its
/// position).
fn edit_artboard_guides(&mut self, id: u32, f: &mut impl FnMut(bool, &mut f64)) {
fn visit(layer: &mut Arc<Node>, id: u32, f: &mut impl FnMut(bool, &mut f64)) {
fn holds(n: &Node, id: u32) -> bool {
n.is_layer()
&& n.children().is_some_and(|ch| {
ch.iter().any(|c| matches!(c.kind, NodeKind::RulerGuide { artboard: Some(a), .. } if a == id) || holds(c, id))
})
}
if !holds(layer, id) {
return;
}
let Some(ch) = Arc::make_mut(layer).children_mut() else { return };
for c in ch.iter_mut() {
if matches!(c.kind, NodeKind::RulerGuide { artboard: Some(a), .. } if a == id) {
if let NodeKind::RulerGuide { vertical, pos, .. } = &mut Arc::make_mut(c).kind {
f(*vertical, pos);
}
} else if c.is_layer() {
visit(c, id, f);
}
}
}
let pick = |n: &Node| matches!(n.kind, NodeKind::RulerGuide { artboard: Some(a), .. } if a == id);
for l in &mut self.layers {
visit(l, id, f);
if let Some(held) = picked_in_layers(l, &pick) {
edit_picked(l, held, f);
}
}
}
@@ -554,6 +524,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() {
@@ -573,65 +550,172 @@ impl Document {
}
}
/// Does `n`, or anything below it (opacity-mask art included), hold a ruler guide?
fn any_guide(n: &Node) -> bool {
let mut any = false;
crate::swatches::walk_with_masks(n, &mut |m| any |= m.is_ruler_guide());
any
/// What a walk picked in a node: its children by index in order, each with what was picked
/// inside it, and what was picked in its opacity-mask art. Empty for a node picked itself.
#[derive(Debug, Default)]
struct Picked {
children: Vec<(usize, Picked)>,
mask: Option<Box<Picked>>,
}
/// Remove every ruler guide below `n`, in its members and its opacity-mask art (`n` itself
/// stays). Mask art that is a ruler guide becomes an empty group. Returns how many went.
fn drop_guides_below(n: &mut Node) -> usize {
let mut gone = drop_mask_guides(n);
if let Some(ch) = n.children_mut() {
let before = ch.len();
ch.retain(|c| !c.is_ruler_guide());
gone += before - ch.len();
for c in ch.iter_mut().filter(|c| any_guide(c)) {
gone += drop_guides_below(Arc::make_mut(c));
impl Picked {
fn is_empty(&self) -> bool {
self.children.is_empty() && self.mask.is_none()
}
/// `self`, or `None` when nothing was picked.
fn some(self) -> Option<Self> {
(!self.is_empty()).then_some(self)
}
}
/// The children of `n`, if it is a layer, that `pick` picks (with nothing inside), and its
/// sublayers holding one (with what they hold), or `None` when it holds none. `pick` looks at
/// each child of the layers once.
fn picked_in_layers(n: &Node, pick: &impl Fn(&Node) -> bool) -> Option<Picked> {
if !n.is_layer() {
return None;
}
let children = n
.children()
.into_iter()
.flatten()
.enumerate()
.filter_map(|(i, c)| if pick(c) { Some((i, Picked::default())) } else { picked_in_layers(c, pick).map(|p| (i, p)) })
.collect();
Picked { children, mask: None }.some()
}
/// Remove the children of `layer` and of its sublayers that [`picked_in_layers`] picked (`held`).
/// Only the layers holding one are copied, and only those are visited.
fn drop_picked(layer: &mut Arc<Node>, held: Picked) {
let Some(ch) = Arc::make_mut(layer).children_mut() else { return };
let mut held = held.children.into_iter().peekable();
let mut next = 0;
ch.retain_mut(|c| {
let at = next;
next += 1;
let Some((_, inner)) = held.next_if(|(i, _)| *i == at) else { return true };
// A sublayer holds something; a child picked itself has nothing inside.
if inner.is_empty() {
return false;
}
drop_picked(c, inner);
true
});
}
/// Change with `f` (whether it is vertical, its position) the line of each ruler guide of `layer`
/// and of its sublayers that [`picked_in_layers`] picked (`held`), in the order they lie in. Only
/// the layers holding one, and the guides, are copied, and only those layers are visited.
fn edit_picked(layer: &mut Arc<Node>, held: Picked, f: &mut impl FnMut(bool, &mut f64)) {
let Some(ch) = Arc::make_mut(layer).children_mut() else { return };
for (i, inner) in held.children {
let Some(c) = ch.get_mut(i) else { continue };
if !inner.is_empty() {
edit_picked(c, inner, f);
} else if let NodeKind::RulerGuide { vertical, pos, .. } = &mut Arc::make_mut(c).kind {
f(*vertical, pos);
}
}
}
/// `n` picked itself when it is a ruler guide by `is_guide`, else the ruler guides below it
/// ([`guides_below`]).
fn guide_or_below(n: &Node, is_guide: &impl Fn(&Node) -> bool) -> Option<Picked> {
if is_guide(n) { Some(Picked::default()) } else { guides_below(n, is_guide) }
}
/// The ruler guides below `n`, by `is_guide`: those among its members and its opacity-mask art
/// (each with nothing inside), and the members and mask art holding one further down (with what
/// they hold), or `None` when there is none. `is_guide` looks at each node below `n` once, and at
/// nothing inside a ruler guide.
fn guides_below(n: &Node, is_guide: &impl Fn(&Node) -> bool) -> Option<Picked> {
let mask = n.extras().mask.as_deref().and_then(|m| guide_or_below(&m.art, is_guide)).map(Box::new);
let children = n.children().into_iter().flatten().enumerate().filter_map(|(i, c)| guide_or_below(c, is_guide).map(|p| (i, p))).collect();
Picked { children, mask }.some()
}
/// Remove the ruler guides below `n` that [`guides_below`] `found`, in its members and its
/// opacity-mask art (`n` itself stays). Mask art that is a ruler guide becomes an empty group.
/// Only the nodes holding one are copied, and only those are visited. Returns how many went.
fn drop_guides_below(n: &mut Node, found: Picked) -> usize {
let mut gone = drop_mask_guides(n, found.mask);
if let Some(ch) = n.children_mut() {
let mut found = found.children.into_iter().peekable();
let mut next = 0;
ch.retain_mut(|c| {
let at = next;
next += 1;
let Some((_, inner)) = found.next_if(|(i, _)| *i == at) else { return true };
if inner.is_empty() {
gone += 1;
return false;
}
gone += drop_guides_below(Arc::make_mut(c), inner);
true
});
}
gone
}
/// Remove every ruler guide in the opacity-mask art of `n`. Mask art that is a ruler guide
/// becomes an empty group. Returns how many went.
fn drop_mask_guides(n: &mut Node) -> usize {
/// Remove the ruler guides `found` in the opacity-mask art of `n` ([`guides_below`]'s mask
/// part). Mask art that is a ruler guide becomes an empty group. Returns how many went.
fn drop_mask_guides(n: &mut Node, found: Option<Box<Picked>>) -> usize {
let Some(found) = found else { return 0 };
let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()) else { return 0 };
if mask.art.is_ruler_guide() {
if found.is_empty() {
mask.art = Arc::new(Node::group(mask.art.id, vec![]));
1
} else if any_guide(&mask.art) {
drop_guides_below(Arc::make_mut(&mut mask.art))
} else {
0
drop_guides_below(Arc::make_mut(&mut mask.art), *found)
}
}
/// Does layer `l` hold a ruler guide out of place: below art, in an object or in mask art, or so
/// in one of its sublayers?
fn layer_untidy(l: &Node) -> bool {
let Some(ch) = l.children() else { return false };
let start = Node::guide_run_start(ch);
l.extras().mask.as_deref().is_some_and(|m| any_guide(&m.art))
|| ch.iter().take(start).any(|c| c.is_ruler_guide() || if c.is_layer() { layer_untidy(c) } else { any_guide(c) })
/// The ruler guides, by `is_guide`, that layer `l` holds out of place, or `None` when it holds
/// none: those below art (each with nothing inside), those in its mask art and in its objects
/// ([`guides_below`]), and its sublayers holding one out of place (with what they hold).
/// `is_guide` looks at each node once; the guides at the end of a layer are in place and are
/// not looked at.
fn untidy(l: &Node, is_guide: &impl Fn(&Node) -> bool) -> Option<Picked> {
let ch = l.children()?;
let mask = l.extras().mask.as_deref().and_then(|m| guide_or_below(&m.art, is_guide)).map(Box::new);
let children = ch
.iter()
.enumerate()
.take(Node::guide_run_start(ch))
.filter_map(|(i, c)| {
let found = if is_guide(c) {
Some(Picked::default())
} else if c.is_layer() {
untidy(c, is_guide)
} else {
guides_below(c, is_guide)
};
found.map(|p| (i, p))
})
.collect();
Picked { children, mask }.some()
}
/// [`Document::tidy_ruler_guides`] for layer `l`. Returns how many guides were removed.
fn tidy_layer(l: &mut Node) -> usize {
let mut gone = drop_mask_guides(l);
/// [`Document::tidy_ruler_guides`] for layer `l`, whose guides out of place [`untidy`] `found`.
/// Only the nodes holding one are copied, and only those are visited. Returns how many guides
/// were removed.
fn tidy_layer(l: &mut Node, found: Picked) -> usize {
let mut gone = drop_mask_guides(l, found.mask);
let Some(ch) = l.children_mut() else { return gone };
for c in ch.iter_mut() {
if c.is_layer() {
if layer_untidy(c) {
gone += tidy_layer(Arc::make_mut(c));
}
} else if !c.is_ruler_guide() && any_guide(c) {
gone += drop_guides_below(Arc::make_mut(c));
let mut below_art = false;
for (i, inner) in found.children {
let Some(c) = ch.get_mut(i) else { continue };
if inner.is_empty() {
below_art = true;
} else if c.is_layer() {
gone += tidy_layer(Arc::make_mut(c), inner);
} else {
gone += drop_guides_below(Arc::make_mut(c), inner);
}
}
if ch.iter().take(Node::guide_run_start(ch)).any(|c| c.is_ruler_guide()) {
if below_art {
let (guides, art): (Vec<_>, Vec<_>) = std::mem::take(ch).into_iter().partition(|c| c.is_ruler_guide());
*ch = art;
ch.extend(guides);
@@ -691,3 +775,286 @@ impl std::fmt::Debug for GuideCache {
f.write_str("GuideCache")
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Appearance, OpacityMask, Symbol};
use std::cell::Cell;
use vectorcraft_geom::shapes;
/// The sublayers in [`nested`]'s chain: with the top-level layer around them and the objects in
/// the innermost, the deepest a document goes ([`crate::MAX_DEPTH`]).
const CHAIN: u64 = 30;
fn rect(id: u64) -> Arc<Node> {
Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()))
}
fn guide(id: u64, artboard: Option<u32>) -> Arc<Node> {
Arc::new(Node::new(NodeId(id), NodeKind::RulerGuide { vertical: false, pos: id as f64, artboard }))
}
fn group(id: u64, children: Vec<Arc<Node>>) -> Arc<Node> {
Arc::new(Node::group(NodeId(id), children))
}
/// `n` with `art` as its opacity-mask art.
fn masked(n: Arc<Node>, art: Arc<Node>) -> Arc<Node> {
let mut n = (*n).clone();
n.extras_mut().mask = Some(Box::new(OpacityMask { art, clip: true, invert: false, disabled: false, linked: true }));
Arc::new(n)
}
/// A sublayer like a new document's first layer, holding `children`.
fn sublayer(id: u64, children: Vec<Arc<Node>>) -> Arc<Node> {
let mut l = (*Document::new(1.0, 1.0).layers[0]).clone();
l.id = NodeId(id);
if let Some(ch) = l.children_mut() {
*ch = children;
}
Arc::new(l)
}
/// A document whose first layer holds `children`.
fn doc(children: Vec<Arc<Node>>) -> Document {
let mut d = Document::new(100.0, 100.0);
if let Some(ch) = d.layers.first_mut().and_then(|l| Arc::make_mut(l).children_mut()) {
*ch = children;
}
d
}
/// The ids of the nodes in the layers, in tree order.
fn ids(d: &Document) -> Vec<u64> {
fn walk(n: &Node, out: &mut Vec<u64>) {
out.push(n.id.0);
for c in n.children().into_iter().flatten() {
walk(c, out);
}
}
let mut out = vec![];
for l in &d.layers {
walk(l, &mut out);
}
out
}
/// [`CHAIN`] sublayers, each inside the one before and holding an object, a canvas guide and a
/// guide of artboard 7 (the innermost: object 150, guides 200 and 201). Beside the chain, a
/// sublayer with a canvas guide only. Returns the document and that sublayer.
fn nested() -> (Document, Arc<Node>) {
let mut chain = sublayer(100, vec![rect(150), guide(200, None), guide(201, Some(7))]);
for depth in 1..CHAIN {
chain = sublayer(100 + depth, vec![rect(600 + depth), chain, guide(300 + depth * 2, None), guide(301 + depth * 2, Some(7))]);
}
let still = sublayer(500, vec![rect(502), guide(501, None)]);
(doc(vec![chain, Arc::clone(&still)]), still)
}
/// How many children the layers of [`nested`] hold: the first layer's 2, the untouched
/// sublayer's 2, the innermost sublayer's 3 and 4 in each sublayer around it.
const NESTED_CHILDREN: usize = 2 + 2 + 3 + (CHAIN as usize - 1) * 4;
fn on_artboard_7(n: &Node) -> bool {
matches!(n.kind, NodeKind::RulerGuide { artboard: Some(7), .. })
}
#[test]
fn removing_guides_looks_at_each_child_of_nested_layers_once() {
let (mut d, still) = nested();
assert!(!d.clone().limit_depth(), "the chain is as deep as a document goes");
let mut deeper = doc(vec![sublayer(999, d.layers[0].children().cloned().unwrap_or_default())]);
assert!(deeper.limit_depth(), "a document nested deeper is brought within the cap when it is read");
let mut whole = d.clone();
let looked = Cell::new(0_usize);
let pick = |n: &Node| {
looked.set(looked.get() + 1);
on_artboard_7(n)
};
let held = picked_in_layers(&d.layers[0], &pick).unwrap();
assert_eq!(looked.get(), NESTED_CHILDREN, "each child of the layers is looked at once");
drop_picked(&mut d.layers[0], held);
assert_eq!(looked.get(), NESTED_CHILDREN, "removing looks at nothing again");
assert!(d.layers[0].children().is_some_and(|c| Arc::ptr_eq(&c[1], &still)), "a sublayer with nothing to remove is not copied");
// The command's own entry point removes the same guides.
let before = whole.clone();
let mut sel = Selection::default();
sel.set_guides([NodeId(200), NodeId(201), NodeId(501)]);
sel.objects.push(NodeId(150));
sel.key_guide = Some(NodeId(201));
assert_eq!(whole.retain_guides(&mut sel, |g| g.artboard != Some(7)), CHAIN as usize);
assert_eq!(ids(&whole), ids(&d));
assert_eq!(ids(&whole).len(), ids(&before).len() - CHAIN as usize);
assert!(whole.ruler_guides().iter().all(|g| g.artboard.is_none()));
assert_eq!(whole.ruler_guides().len(), CHAIN as usize + 1);
assert_eq!((sel.objects.as_slice(), sel.guides.as_slice(), sel.key_guide), (&[NodeId(150)][..], &[NodeId(200), NodeId(501)][..], None));
assert!(whole.layers[0].children().is_some_and(|c| Arc::ptr_eq(&c[1], &still)));
// The document as it was (an undo step's copy) still holds every guide.
assert_eq!(before.ruler_guides().len(), CHAIN as usize * 2 + 1);
// Saving the guides as a list, and removing a layer but not its guides, take the guides
// out of the nested layers too.
let mut saved = before.clone();
saved.guides_to_saved();
assert_eq!(saved.saved_guides, before.ruler_guides());
assert_eq!(ids(&saved).len(), 1 + CHAIN as usize * 2 + 2);
assert!(saved.layers[0].children().is_some_and(|c| !Arc::ptr_eq(&c[1], &still) && c[1].children().is_some_and(|c| c.len() == 1)));
let mut edited = before.clone();
let chain = edited.remove_edit_layer(NodeId(100 + CHAIN - 1)).unwrap();
assert!(!chain.holds_ruler_guides());
assert_eq!(edited.ruler_guides().len(), before.ruler_guides().len(), "the removed layer's guides stay in the document");
assert_eq!(edited.guides_on(edited.layers[0].id).len(), CHAIN as usize * 2);
// Keeping every guide changes nothing and copies no layer.
let kept = whole.clone();
assert_eq!(whole.retain_guides(&mut sel, |_| true), 0);
assert!(Arc::ptr_eq(&whole.layers[0], &kept.layers[0]));
// Removing every guide leaves the objects.
assert_eq!(whole.retain_guides(&mut sel, |_| false), CHAIN as usize + 1);
assert!(whole.ruler_guides().is_empty() && sel.guides.is_empty());
assert_eq!(ids(&whole).len(), 1 + CHAIN as usize * 2 + 2);
assert_eq!(sel.objects, [NodeId(150)]);
// A document without layers, and one without guides, have nothing to remove.
let mut empty = Document::new(10.0, 10.0);
assert_eq!(empty.retain_guides(&mut sel, |_| false), 0);
empty.layers.clear();
assert_eq!(empty.retain_guides(&mut sel, |_| false), 0);
}
#[test]
fn moving_an_artboards_guides_looks_at_each_child_of_nested_layers_once() {
let (mut d, still) = nested();
let mut whole = d.clone();
let looked = Cell::new(0_usize);
let pick = |n: &Node| {
looked.set(looked.get() + 1);
on_artboard_7(n)
};
let held = picked_in_layers(&d.layers[0], &pick).unwrap();
assert_eq!(looked.get(), NESTED_CHILDREN, "each child of the layers is looked at once");
let mut seen = vec![];
edit_picked(&mut d.layers[0], held, &mut |vertical, pos: &mut f64| {
seen.push((vertical, *pos));
*pos += 9.0;
});
assert_eq!(looked.get(), NESTED_CHILDREN, "changing looks at nothing again");
// A sublayer comes before its layer's own guides, so the innermost guide is changed first.
let order: Vec<(bool, f64)> = [201.0].into_iter().chain((1..CHAIN).map(|depth| (301 + depth * 2) as f64)).map(|pos| (false, pos)).collect();
assert_eq!(seen, order, "each guide of the artboard is changed once, in the order the guides lie in");
assert!(d.layers[0].children().is_some_and(|c| Arc::ptr_eq(&c[1], &still)), "a sublayer with no guide of the artboard is not copied");
// The public moves change the same guides by the same amount.
let before = whole.clone();
whole.move_artboard_guides(7, Vec2::new(5.0, 9.0));
assert_eq!(whole, d);
assert_eq!(ids(&whole), ids(&before));
for g in whole.ruler_guides() {
let id = g.id.map_or(0, |id| id.0) as f64;
assert_eq!(g.pos, if g.artboard == Some(7) { id + 9.0 } else { id }, "guide {id}");
}
assert!(whole.layers[0].children().is_some_and(|c| Arc::ptr_eq(&c[1], &still)));
assert_eq!(before.ruler_guide(NodeId(201)).map(|g| g.pos), Some(201.0), "the document as it was keeps its guides");
whole.map_artboard_guides(7, Affine::scale(2.0));
assert_eq!(whole.ruler_guide(NodeId(201)).map(|g| g.pos), Some(420.0));
assert_eq!(whole.ruler_guide(NodeId(200)).map(|g| g.pos), Some(200.0), "a canvas guide stays");
// An artboard without guides, and a document without layers, change nothing and copy no layer.
let kept = whole.clone();
whole.move_artboard_guides(99, Vec2::new(5.0, 9.0));
assert!(Arc::ptr_eq(&whole.layers[0], &kept.layers[0]));
let mut empty = Document::new(10.0, 10.0);
empty.layers.clear();
empty.move_artboard_guides(7, Vec2::new(5.0, 9.0));
assert!(empty.layers.is_empty());
}
#[test]
fn guides_in_objects_are_found_by_looking_at_each_node_once() {
// Groups, each inside the one before and holding an object and a guide. Beside them, an
// object whose mask art holds a guide, one whose mask art is a guide, and a group with none.
let mut chain = group(100, vec![rect(150), guide(200, None)]);
for depth in 1..CHAIN {
chain = group(100 + depth, vec![rect(600 + depth), chain, guide(300 + depth, None)]);
}
let still = group(700, vec![rect(701)]);
let root = group(
1,
vec![chain, masked(rect(800), group(801, vec![guide(802, None), rect(803)])), masked(rect(810), guide(811, None)), Arc::clone(&still)],
);
let looked = Cell::new(0_usize);
let is_guide = |n: &Node| {
looked.set(looked.get() + 1);
n.is_ruler_guide()
};
// The chain's groups, objects and guides; a masked object, its mask group and the two in
// it; a masked object and its mask guide; the last group and its object.
let nodes = CHAIN as usize * 3 + 4 + 2 + 2;
let found = guides_below(&root, &is_guide).unwrap();
assert_eq!(looked.get(), nodes, "each node below the root is looked at once");
let mut cleared = (*root).clone();
assert_eq!(drop_guides_below(&mut cleared, found), CHAIN as usize + 2);
assert_eq!(looked.get(), nodes, "removing looks at nothing again");
assert!(guides_below(&cleared, &Node::is_ruler_guide).is_none());
let ch = cleared.children().unwrap();
assert!(Arc::ptr_eq(&ch[3], &still), "a group without guides is not copied");
assert_eq!(
ch[1].extras().mask.as_deref().map(|m| m.art.children().map(|c| c.iter().map(|c| c.id.0).collect::<Vec<_>>())),
Some(Some(vec![803]))
);
assert_eq!(ch[2].extras().mask.as_deref().map(|m| (m.art.id, m.art.children().map(Vec::len))), Some((NodeId(811), Some(0))));
// Opening a file removes the same guides from an object on a layer and from a symbol's art.
let mut d = doc(vec![Arc::clone(&root), guide(900, None)]);
d.symbols = vec![Symbol { name: "s".into(), art: Arc::clone(&root), dynamic: false }];
assert_eq!(d.tidy_ruler_guides(), (CHAIN as usize + 2) * 2);
assert_eq!(d.layers[0].children().map(|c| (*c[0]).clone()), Some(cleared.clone()));
assert_eq!(*d.symbols[0].art, cleared);
assert_eq!(d.ruler_guides().iter().map(|g| g.id).collect::<Vec<_>>(), [Some(NodeId(900))]);
}
#[test]
fn guides_out_of_place_are_found_by_looking_at_each_node_once() {
// Sublayers, each inside the one before, with their guides in place; the innermost also
// holds a guide below its art. Beside them, a group holding a guide, a sublayer with its
// guide in place, and a sublayer whose mask art holds a guide.
let mut chain = sublayer(100, vec![guide(200, None), rect(150), guide(201, None)]);
for depth in 1..CHAIN {
chain = sublayer(100 + depth, vec![rect(600 + depth), chain, guide(300 + depth, None)]);
}
let still = sublayer(500, vec![rect(502), guide(501, None)]);
let with_mask = masked(sublayer(510, vec![rect(513)]), group(511, vec![guide(512, None)]));
let mut d = doc(vec![chain, group(700, vec![rect(701), guide(702, None)]), Arc::clone(&still), with_mask, guide(900, None)]);
let mut whole = d.clone();
let looked = Cell::new(0_usize);
let is_guide = |n: &Node| {
looked.set(looked.get() + 1);
n.is_ruler_guide()
};
// Below the guides at the end of each layer: the first layer's 4, the group's 2, the
// untouched sublayer's 1, the masked sublayer's mask group, its guide and the object, 2 in
// the innermost sublayer and 2 in each sublayer around it.
let nodes = 4 + 2 + 1 + 3 + 2 + (CHAIN as usize - 1) * 2;
let found = untidy(&d.layers[0], &is_guide).unwrap();
assert_eq!(looked.get(), nodes, "each node below the guides in place is looked at once");
assert_eq!(tidy_layer(Arc::make_mut(&mut d.layers[0]), found), 2);
assert_eq!(looked.get(), nodes, "tidying looks at nothing again");
assert!(d.layers[0].children().is_some_and(|c| Arc::ptr_eq(&c[2], &still)), "a sublayer with its guides in place is not copied");
assert!(untidy(&d.layers[0], &Node::is_ruler_guide).is_none());
// Opening a file does the same.
let before = whole.clone();
assert_eq!(whole.tidy_ruler_guides(), 2);
assert_eq!(whole, d);
let all = ids(&whole);
assert!(!all.contains(&702) && all.len() == ids(&before).len() - 1);
let innermost = whole.node(NodeId(100)).and_then(|n| n.children()).map(|c| c.iter().map(|c| c.id.0).collect::<Vec<_>>());
assert_eq!(innermost, Some(vec![150, 200, 201]), "a guide below art moves up to the other guides");
assert!(whole.node(NodeId(510)).is_some_and(|n| n.extras().mask.as_deref().is_some_and(|m| m.art.children().is_some_and(Vec::is_empty))));
// A tidy document is left alone, and no layer is copied.
let kept = whole.clone();
assert_eq!(whole.tidy_ruler_guides(), 0);
assert!(Arc::ptr_eq(&whole.layers[0], &kept.layers[0]));
}
}
+26
View File
@@ -166,6 +166,16 @@ pub struct LabelStyles {
/// The anti-aliasing method the legend labels keep once set. `None` draws them Sharp.
#[serde(skip_serializing_if = "Option::is_none")]
pub legend_anti_alias: Option<crate::text::TypeAntiAlias>,
/// The object fill and stroke rows the value axis numbers keep once set with the Appearance controls ([`LabelRows`]).
/// `None`: no rows, opaque and Normal.
#[serde(skip_serializing_if = "Option::is_none")]
pub values_rows: Option<LabelRows>,
/// The object fill and stroke rows the category labels keep, as [`Self::values_rows`].
#[serde(skip_serializing_if = "Option::is_none")]
pub categories_rows: Option<LabelRows>,
/// The object fill and stroke rows the legend labels keep, as [`Self::values_rows`].
#[serde(skip_serializing_if = "Option::is_none")]
pub legend_rows: Option<LabelRows>,
}
impl LabelStyles {
@@ -355,6 +365,22 @@ pub struct SeriesPaint {
pub blend: Option<vectorcraft_color::BlendMode>,
}
/// The object rows one kind of graph label keeps ([`LabelStyles::values_rows`]): the paint, weight, opacity and blend mode
/// of a label's topmost visible fill and stroke row (an absent paint: no row of that kind), the label's object opacity and
/// blend mode, and where the two rows paint relative to each other and to the characters.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct LabelRows {
#[serde(flatten)]
pub paint: SeriesPaint,
/// How many of the kept rows paint below the characters, counted from the bottom. Absent: none.
#[serde(skip_serializing_if = "Option::is_none")]
pub below: Option<u8>,
/// The stroke row paints below the fill row.
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub stroke_under: bool,
}
/// Graph data and options. `rows` are categories (one per row of the Graph Data window), each
/// holding one value per series; `series` are the legend labels (the first row of the window).
/// Scatter graphs read each series as (y, x) column pairs, like Illustrator.
+431 -43
View File
@@ -2,10 +2,13 @@
//! from the document's symbols, which the text layout needs to size and place it.
use std::borrow::Cow;
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, RwLock, Weak};
use vectorcraft_geom::{Affine, Rect};
use crate::{Document, NodeId, NodeKind, TextObject};
use crate::{Document, Node, NodeId, NodeKind, Symbol, TextObject};
/// The document key under which the app records each symbol's natural size (`{name: [w, h]}`).
pub const SYMBOL_SIZES: &str = "symbolSizes";
@@ -39,9 +42,27 @@ impl Document {
usable(Some(self.symbol_natural_xf(name).transform_rect_bbox(b)))
}
/// The art bounds an inline graphic of the symbol named `name` takes: [`Self::symbol_art_bounds`],
/// or `None` (an empty slot) when the symbol's art shows the symbol itself inline, directly or
/// through the inline graphics in other symbols' art, so that its size would depend on itself.
pub fn inline_art_bounds(&self, name: &str) -> Option<Rect> {
if self.inline_cycles().contains(name) { None } else { self.symbol_art_bounds(name) }
}
/// The names of the symbols that reach themselves through the inline graphics in symbol art,
/// found once while the symbols stay as they are.
fn inline_cycles(&self) -> Arc<HashSet<String>> {
if let Some(found) = self.inline_cycles.get(&self.symbols) {
return found;
}
let found = Arc::new(InlineGraph::of(self).cyclic);
self.inline_cycles.set(&self.symbols, &found);
found
}
/// Does `t` have inline graphics whose resolved bounds differ from the document's symbols?
fn inline_stale(&self, t: &TextObject) -> bool {
t.runs.iter().filter_map(|r| r.inline.as_ref()).any(|a| a.bounds != self.symbol_art_bounds(&a.symbol))
stale_by(t, &|n| self.inline_art_bounds(n))
}
/// `t` with its inline graphics' art bounds resolved from this document's symbols (borrowed
@@ -56,54 +77,421 @@ impl Document {
Cow::Owned(t)
}
/// Fill in the art bounds of `t`'s inline graphics; returns whether any changed (the text's
/// cached layout bounds are then cleared).
/// Fill in the art bounds of `t`'s inline graphics ([`Self::inline_art_bounds`]); returns
/// whether any changed (the text's cached layout is then cleared).
pub fn resolve_text_inline(&self, t: &mut TextObject) -> bool {
let mut changed = false;
for r in &mut t.runs {
if let Some(a) = &mut r.inline {
let b = self.symbol_art_bounds(&a.symbol);
if a.bounds != b {
a.bounds = b;
changed = true;
}
}
}
if changed {
t.cached_bounds = None;
t.cached_ink = None;
}
changed
resolve_runs(t, &|n| self.inline_art_bounds(n))
}
/// Resolve the inline graphics of every text object in the layers (after opening a document
/// or changing its symbols). Returns the ids of the texts that changed: their cached layout
/// bounds were cleared and need recomputing.
/// Resolve the inline graphics of every text object in the document (after opening a document
/// or changing its symbols), without laying the type out again: see
/// [`Self::resolve_inline_art_with`].
pub fn resolve_inline_art(&mut self) -> Vec<NodeId> {
let mut stale = vec![];
self.walk(|n| {
if let NodeKind::Text(t) = &n.kind
&& t.runs.iter().any(|r| r.inline.is_some())
&& self.inline_stale(t)
{
stale.push(n.id);
}
});
self.resolve_inline_art_with(&mut |_| {})
}
/// Resolve the inline graphics of every text object in the document: in the layers, the art
/// of symbols, graph designs and pattern tiles, and the opacity masks and live objects in
/// them. Each text whose inline graphics changed has its cached layout cleared and is passed
/// to `layout` to be laid out again. The symbols are resolved first, each after the symbols its
/// inline graphics show, so a symbol's art is measured with its type already laid out; a
/// symbol that shows itself inline ([`Self::inline_art_bounds`]) is shown as an empty slot.
/// Returns the ids of the texts in the layers that changed.
pub fn resolve_inline_art_with(&mut self, layout: &mut dyn FnMut(&mut TextObject)) -> Vec<NodeId> {
let mut out = vec![];
for id in stale {
let Some(mut t) = self.node(id).and_then(|n| match &n.kind {
NodeKind::Text(t) => Some(t.clone()),
_ => None,
}) else {
continue;
};
if self.resolve_text_inline(&mut t)
&& let Some(n) = self.node_mut(id)
{
n.kind = NodeKind::Text(t);
out.push(id);
let mut unused = vec![];
let graph = InlineGraph::of(self);
let measured = Measured::default();
for &i in &graph.order {
let mut art = self.symbols[i].art.clone();
if resolve_tree(&mut art, &|n| measured.get(n, || graph.bounds(self, n)), layout, &mut unused) {
self.symbols[i].art = art;
}
}
for i in 0..self.layers.len() {
let mut layer = self.layers[i].clone();
if resolve_tree(&mut layer, &|n| measured.get(n, || graph.bounds(self, n)), layout, &mut out) {
self.layers[i] = layer;
}
}
for i in 0..self.graph_designs.len() {
let mut art = self.graph_designs[i].art.clone();
if resolve_tree(&mut art, &|n| measured.get(n, || graph.bounds(self, n)), layout, &mut unused) {
self.graph_designs[i].art = art;
}
}
for i in 0..self.patterns.len() {
for j in 0..self.patterns[i].art.len() {
let mut art = self.patterns[i].art[j].clone();
if resolve_tree(&mut art, &|n| measured.get(n, || graph.bounds(self, n)), layout, &mut unused) {
self.patterns[i].art[j] = art;
}
}
}
out
}
}
/// Whether `t` has inline graphics whose bounds differ from what `bounds` gives their symbols.
fn stale_by(t: &TextObject, bounds: &dyn Fn(&str) -> Option<Rect>) -> bool {
t.runs.iter().filter_map(|r| r.inline.as_ref()).any(|a| a.bounds != bounds(&a.symbol))
}
/// Gives `t`'s inline graphics the bounds `bounds` gives their symbols; returns whether any changed
/// (the text's cached layout is then cleared).
fn resolve_runs(t: &mut TextObject, bounds: &dyn Fn(&str) -> Option<Rect>) -> bool {
let mut changed = false;
for a in t.runs.iter_mut().filter_map(|r| r.inline.as_mut()) {
let b = bounds(&a.symbol);
if a.bounds != b {
a.bounds = b;
changed = true;
}
}
if changed {
t.cached_bounds = None;
t.cached_baselines.clear();
t.cached_ink = None;
}
changed
}
/// Resolves the inline graphics of the type in tree `n` (opacity mask art included) with
/// `bounds`, passing each text that changed to `layout` and adding its id to `changed`; returns
/// whether the tree changed. Each node is visited once, and only the nodes on the way to changed
/// type are copied.
fn resolve_tree(
n: &mut Arc<Node>,
bounds: &dyn Fn(&str) -> Option<Rect>,
layout: &mut dyn FnMut(&mut TextObject),
changed: &mut Vec<NodeId>,
) -> bool {
let mut copied = false;
if matches!(&n.kind, NodeKind::Text(t) if stale_by(t, bounds)) {
let node = Arc::make_mut(n);
if let NodeKind::Text(t) = &mut node.kind
&& resolve_runs(t, bounds)
{
layout(t);
changed.push(node.id);
}
copied = true;
}
let mask = n.extras().mask.as_deref().and_then(|m| {
let mut art = m.art.clone();
resolve_tree(&mut art, bounds, layout, changed).then_some(art)
});
let mut kids = vec![];
for (i, c) in n.children().into_iter().flatten().enumerate() {
let mut c = c.clone();
if resolve_tree(&mut c, bounds, layout, changed) {
kids.push((i, c));
}
}
if mask.is_none() && kids.is_empty() {
return copied;
}
let node = Arc::make_mut(n);
if let Some(art) = mask
&& let Some(m) = node.extras_if_any().and_then(|e| e.mask.as_deref_mut())
{
m.art = art;
}
if let Some(ch) = node.children_mut() {
for (i, c) in kids {
ch[i] = c;
}
}
true
}
/// The art bounds of each symbol, measured once in a pass of [`Document::resolve_inline_art_with`].
/// A symbol is first asked for after its own type is resolved (the pass goes in
/// [`InlineGraph::order`]), so its measurement stays current for the rest of the pass.
#[derive(Default)]
struct Measured(RefCell<HashMap<String, Option<Rect>>>);
impl Measured {
/// The bounds kept for `name`, or `measure`'s, kept for later.
fn get(&self, name: &str, measure: impl FnOnce() -> Option<Rect>) -> Option<Rect> {
if let Some(&b) = self.0.borrow().get(name) {
return b;
}
let b = measure();
self.0.borrow_mut().insert(name.to_owned(), b);
b
}
}
/// The names of the symbols the inline graphics in tree `n` show (opacity mask art included).
fn inline_symbols(n: &Node) -> Vec<String> {
fn collect(n: &Node, out: &mut Vec<String>) {
if let NodeKind::Text(t) = &n.kind {
out.extend(t.runs.iter().filter_map(|r| r.inline.as_ref().map(|a| a.symbol.clone())));
}
if let Some(m) = n.extras().mask.as_deref() {
collect(&m.art, out);
}
for c in n.children().into_iter().flatten() {
collect(c, out);
}
}
let mut out = vec![];
collect(n, &mut out);
out
}
/// Each symbol name of `d` → the index of the first symbol of that name (the one a name finds).
fn symbol_index(d: &Document) -> HashMap<&str, usize> {
let mut index = HashMap::with_capacity(d.symbols.len());
for (i, s) in d.symbols.iter().enumerate() {
index.entry(s.name.as_str()).or_insert(i);
}
index
}
/// The symbols of a document as their inline graphics depend on each other.
struct InlineGraph {
/// Every symbol index, each after the symbols its art shows inline (except along a cycle).
order: Vec<usize>,
/// The names of the symbols that reach themselves through inline graphics.
cyclic: HashSet<String>,
}
impl InlineGraph {
/// The graph of `d`'s symbols: each symbol's art is walked once, and the order and cycles are
/// found in time linear in the symbols and their inline references (Tarjan's strongly
/// connected components, without recursion).
fn of(d: &Document) -> Self {
let index = symbol_index(d);
let edges: Vec<Vec<usize>> = d
.symbols
.iter()
.map(|s| {
let mut e: Vec<usize> = inline_symbols(&s.art).iter().filter_map(|n| index.get(n.as_str()).copied()).collect();
e.sort_unstable();
e.dedup();
e
})
.collect();
let (order, cyclic) = components(&edges);
let cyclic = order.iter().filter(|&&i| cyclic[i]).map(|&i| d.symbols[i].name.clone()).collect();
Self { order, cyclic }
}
/// [`Document::inline_art_bounds`] with the cycles found in this graph.
fn bounds(&self, d: &Document, name: &str) -> Option<Rect> {
if self.cyclic.contains(name) { None } else { d.symbol_art_bounds(name) }
}
}
/// The nodes of the graph `edges` (node → the nodes it depends on), each after the nodes it
/// depends on except within a cycle, and whether each node is on a cycle (a component of more than
/// one node, or an edge to itself).
fn components(edges: &[Vec<usize>]) -> (Vec<usize>, Vec<bool>) {
const UNSEEN: usize = usize::MAX;
let n = edges.len();
let (mut index, mut low, mut on_stack) = (vec![UNSEEN; n], vec![0; n], vec![false; n]);
let (mut stack, mut order, mut cyclic) = (vec![], Vec::with_capacity(n), vec![false; n]);
let mut next = 0;
// The nodes being visited, each with the position of its next edge.
let mut calls: Vec<(usize, usize)> = vec![];
for root in 0..n {
if index[root] != UNSEEN {
continue;
}
index[root] = next;
low[root] = next;
next += 1;
stack.push(root);
on_stack[root] = true;
calls.push((root, 0));
while let Some(top) = calls.last_mut() {
let v = top.0;
if let Some(&w) = edges[v].get(top.1) {
top.1 += 1;
if index[w] == UNSEEN {
index[w] = next;
low[w] = next;
next += 1;
stack.push(w);
on_stack[w] = true;
calls.push((w, 0));
} else if on_stack[w] {
low[v] = low[v].min(index[w]);
}
continue;
}
calls.pop();
if let Some(&(u, _)) = calls.last() {
low[u] = low[u].min(low[v]);
}
if low[v] == index[v] {
let start = order.len();
while let Some(w) = stack.pop() {
on_stack[w] = false;
order.push(w);
if w == v {
break;
}
}
if order.len() - start > 1 || edges[v].contains(&v) {
for &w in &order[start..] {
cyclic[w] = true;
}
}
}
}
}
(order, cyclic)
}
/// The symbols [`Document::inline_cycles`] last found, with the name of each symbol and a weak
/// pointer to its art. While a weak pointer to an art's allocation is held, nothing else can be at
/// that address, and the art can't be changed in place (`Arc::get_mut` refuses it and
/// `Arc::make_mut` moves it), so any edit inside a symbol's art, and any symbol added, removed,
/// renamed or replaced, gives symbols the cache does not match. Clones of a document share it.
#[derive(Default)]
pub(crate) struct InlineCycles(RwLock<Option<Arc<Found>>>);
/// The name and art of each symbol the cycles were found in, and the names of the symbols on one.
type Found = (Vec<(String, Weak<Node>)>, Arc<HashSet<String>>);
impl InlineCycles {
/// The cached names, when they were found in `symbols`.
fn get(&self, symbols: &[Symbol]) -> Option<Arc<HashSet<String>>> {
let g = self.0.read().ok()?;
let (from, found) = &**g.as_ref()?;
let same = from.len() == symbols.len()
&& from.iter().zip(symbols).all(|((name, art), s)| *name == s.name && std::ptr::eq(art.as_ptr(), Arc::as_ptr(&s.art)));
same.then(|| found.clone())
}
/// Keep `found`, found in `symbols`.
fn set(&self, symbols: &[Symbol], found: &Arc<HashSet<String>>) {
if let Ok(mut g) = self.0.write() {
*g = Some(Arc::new((symbols.iter().map(|s| (s.name.clone(), Arc::downgrade(&s.art))).collect(), found.clone())));
}
}
}
impl Clone for InlineCycles {
fn clone(&self) -> Self {
InlineCycles(RwLock::new(self.0.read().ok().and_then(|g| g.clone())))
}
}
/// A cache, not document content: two documents are equal whatever their caches hold.
impl PartialEq for InlineCycles {
fn eq(&self, _: &Self) -> bool {
true
}
}
impl std::fmt::Debug for InlineCycles {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("InlineCycles")
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The position of each node in `order`.
fn positions(order: &[usize]) -> Vec<usize> {
let mut at = vec![0; order.len()];
for (p, &i) in order.iter().enumerate() {
at[i] = p;
}
at
}
#[test]
fn components_put_dependencies_first_and_find_every_cycle_member() {
// 0 → 1 → 2 → 0 is a cycle, and 3, reached from 1, joins it through 2.
// 4 depends on 0 and is on no cycle; 5 shows itself.
let edges = vec![vec![1], vec![2, 3], vec![0], vec![2], vec![0], vec![5]];
let (order, cyclic) = components(&edges);
let mut sorted = order.clone();
sorted.sort_unstable();
assert_eq!(sorted, [0, 1, 2, 3, 4, 5]);
assert_eq!(cyclic, [true, true, true, true, false, true]);
let at = positions(&order);
assert!(at[4] > at[0], "{order:?}");
// A chain: each node after the one it depends on.
let (order, cyclic) = components(&[vec![], vec![0], vec![1]]);
assert_eq!(order, [0, 1, 2]);
assert!(cyclic.iter().all(|c| !c));
}
/// Type at the bottom of 2,000 nested groups is checked once, not once for each group above it,
/// and only the groups on the way to it are copied.
#[test]
fn resolving_deeply_nested_type_visits_each_node_once() {
use std::cell::Cell;
use vectorcraft_geom::Point;
let mut t = TextObject::point(Point::ZERO, "Type", crate::CharStyle::default());
t.runs.push(crate::TextRun::new("", crate::CharStyle::default()));
t.runs[1].inline = Some(crate::InlineArt { symbol: "S".into(), scale: 1.0, baseline_shift: 0.0, bounds: None });
let depth = 2_000;
let mut tree = Arc::new(Node::new(NodeId(0), NodeKind::Text(Box::new(t))));
for i in 1..=depth {
let side = Arc::new(Node::group(NodeId(depth + i), vec![]));
tree = Arc::new(Node::group(NodeId(i), vec![side, tree]));
}
let before = tree.clone();
let asked = Cell::new(0);
let r = Rect::new(0.0, 0.0, 10.0, 20.0);
let bounds = |_: &str| {
asked.set(asked.get() + 1);
Some(r)
};
let (mut laid_out, mut changed) = (0, vec![]);
assert!(resolve_tree(&mut tree, &bounds, &mut |_| laid_out += 1, &mut changed));
assert!(asked.get() <= 2, "bounds asked {} times for one inline graphic", asked.get());
assert_eq!(laid_out, 1);
assert_eq!(changed, [NodeId(0)]);
// The bottom of the new tree holds the resolved type; the side groups are shared.
let (mut new, mut old) = (&tree, &before);
while let (Some(n), Some(o)) = (new.children(), old.children()) {
assert!(Arc::ptr_eq(&n[0], &o[0]));
(new, old) = (&n[1], &o[1]);
}
let NodeKind::Text(t) = &new.kind else { panic!("the type is at the bottom") };
assert_eq!(t.runs[1].inline.as_ref().and_then(|a| a.bounds), Some(r));
// Nothing left to change: the tree is kept and the type is checked once.
asked.set(0);
let kept = tree.clone();
assert!(!resolve_tree(&mut tree, &bounds, &mut |_| laid_out += 1, &mut changed));
assert!(Arc::ptr_eq(&tree, &kept));
assert_eq!(asked.get(), 1);
}
#[test]
fn a_symbol_is_measured_once_in_a_pass() {
let measured = Measured::default();
let count = std::cell::Cell::new(0);
let measure = |b: Option<Rect>| {
count.set(count.get() + 1);
b
};
let r = Some(Rect::new(0.0, 0.0, 1.0, 1.0));
for _ in 0..3 {
assert_eq!(measured.get("A", || measure(r)), r);
assert_eq!(measured.get("Missing", || measure(None)), None);
}
assert_eq!(count.get(), 2);
}
#[test]
fn components_handle_a_long_chain_without_recursion() {
let n = 200_000;
let edges: Vec<Vec<usize>> = (0..n).map(|i| if i + 1 < n { vec![i + 1] } else { vec![] }).collect();
let (order, cyclic) = components(&edges);
assert_eq!(order.first(), Some(&(n - 1)));
assert_eq!(order.last(), Some(&0));
assert!(cyclic.iter().all(|c| !c));
}
}
+15 -6
View File
@@ -11,6 +11,7 @@ pub mod blend;
pub mod cancel;
pub mod clipnest;
pub mod cmyk;
pub mod color_mask;
pub mod compound_shape;
pub mod corners;
pub mod depth;
@@ -32,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};
@@ -61,6 +62,7 @@ pub mod rastersettings;
mod reach;
pub mod recolor;
pub mod selection;
pub mod separated;
pub mod setup;
pub mod shaper;
pub mod slices;
@@ -90,8 +92,8 @@ pub use compound_shape::ShapeMode;
pub use corners::LiveCorners;
pub use depth::{MAX_DEPTH, MAX_SYMBOL_NODES};
pub use graph::{
ColumnDesign, ColumnType, Fractions, GraphDesign, GraphKind, GraphSpec, LabelStyles, MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES, PiePosition,
PieSort, SeriesPaint, TickLength, ValueAxisSide,
ColumnDesign, ColumnType, Fractions, GraphDesign, GraphKind, GraphSpec, LabelRows, LabelStyles, MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES,
PiePosition, PieSort, SeriesPaint, TickLength, ValueAxisSide,
};
pub use hit::{Hit, HitKind};
pub use links::{LinkInfo, PlacementOptions};
@@ -115,6 +117,7 @@ pub use slices::{CellAlign, CellVAlign, Slice, SliceArea, SliceKind, SliceOption
pub use style_libs::StyleLibrary;
pub use text::FontHeightReference;
pub use text::GlyphChoice;
pub use text::WarichuAlign;
pub use text::{
AreaFit, AreaOptions, Burasagari, CharAlign, CharPosition, CharStyle, Composer, Digits, FirstBaseline, HyphenationOptions, InlineArt,
JustificationOptions, Justify, Kinsoku, KinsokuShoriType, LeadingModel, Mojikumi, ParaDirection, ParaStyle, PathAlign, PathEffect, RubyAlign,
@@ -140,6 +143,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};
@@ -152,6 +156,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)]
@@ -263,8 +268,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`]).
@@ -358,6 +363,10 @@ pub struct Document {
/// The ruler guides as [`Document::ruler_guides`] lists them: a cache, never saved.
#[serde(skip)]
guide_cache: document_guides::GuideCache,
/// The symbols that show themselves inline ([`Document::inline_art_bounds`]): a cache, never
/// saved.
#[serde(skip)]
inline_cycles: inline::InlineCycles,
}
fn ppi72() -> f64 {
+248 -17
View File
@@ -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,
};
@@ -54,8 +54,8 @@ pub use blend_spec::{BlendDefaults, BlendEase, BlendEaseType, BlendOrientation,
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,
envelope_content_boxes, envelope_content_boxes_with, envelope_expand, envelope_frame, envelope_grid, envelope_mapper, envelope_of,
envelope_overlay, envelope_stroke_margin, 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]
@@ -1025,6 +1169,37 @@ mod tests {
assert_eq!(m.locate_within(Point::new(30.0, 60.0), 3.0), m.locate(Point::new(30.0, 60.0)));
}
/// A point on a mesh's outline locates on the edge it lies on, on all four sides alike, with no
/// tolerance; a point just outside does not, and a tolerance reaches only as far as it says.
/// A point that isn't finite locates nowhere.
#[test]
fn mesh_locate_takes_a_point_on_any_side_of_the_outline() {
for (rows, cols) in [(1, 1), (2, 3)] {
let m =
GradientMesh::for_path(&shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), rows, cols, Color::BLACK, MeshAppearance::Flat, 0.0)
.unwrap();
let sides = [
("top", Point::new(30.0, 0.0), Vec2::new(0.0, -0.01)),
("bottom", Point::new(30.0, 100.0), Vec2::new(0.0, 0.01)),
("left", Point::new(0.0, 70.0), Vec2::new(-0.01, 0.0)),
("right", Point::new(100.0, 70.0), Vec2::new(0.01, 0.0)),
];
for (side, p, out) in sides {
let (r, c, u, v) = m.locate(p).unwrap_or_else(|| panic!("{rows}×{cols} {side}: {p:?} is not located"));
assert!(r < m.rows as usize && c < m.cols as usize && (0.0..=1.0).contains(&u) && (0.0..=1.0).contains(&v), "{side}");
assert!(m.eval(r, c, u, v).distance(p) < 1e-3, "{rows}×{cols} {side}: {:?}", m.eval(r, c, u, v));
let mut e = m.clone();
assert!(e.add_lines_at(p, 0.0).is_some(), "{rows}×{cols} {side}: no line at {p:?}");
assert_eq!(m.locate(p + out), None, "{rows}×{cols} {side}: just outside");
assert_eq!(m.locate_within(p + out * 100.0, 0.5), None, "{rows}×{cols} {side}: past the tolerance");
assert!(m.locate_within(p + out * 100.0, 1.5).is_some(), "{rows}×{cols} {side}: within the tolerance");
}
for p in [Point::new(f64::NAN, 0.0), Point::new(30.0, f64::INFINITY)] {
assert_eq!(m.locate_within(p, f64::INFINITY), None, "{p:?}");
}
}
}
/// Corners all in CMYK mix in CMYK (the inks halfway), not in RGB.
#[test]
fn a_cmyk_mesh_mixes_its_inks() {
@@ -1072,4 +1247,60 @@ mod tests {
assert_eq!(m, before);
}
}
/// The pieces of a mesh-warped image make a knockout group, each knocking out its triangle
/// (clipping path or opacity mask art); the group keeps the image's transparency.
#[test]
fn mesh_warp_image_pieces_knock_out_by_their_triangles() {
let im = crate::ImageObject {
key: "pic".into(),
width: 4,
height: 4,
xf: Affine::scale(10.0),
link: None,
placement: Default::default(),
pixels: None,
};
let mut n = Node::new(NodeId(3), NodeKind::Image(Box::new(im.clone())));
n.opacity = 0.5;
n.blend = crate::color::BlendMode::Multiply;
let same = |p: Point| p;
for masked in [false, true] {
let g = mesh_warp_image(&n, &im, &same, 2, false, masked);
assert_eq!((g.knockout, g.opacity, g.blend, g.isolate), (crate::Knockout::On, 0.5, crate::color::BlendMode::Multiply, false));
let NodeKind::Group { children, clip: false } = &g.kind else { panic!("a group") };
assert_eq!(children.len(), 8);
for c in children {
assert!(c.extras().warp_piece);
let outline = c.knockout_outline().unwrap_or_else(|| panic!("masked {masked}: an outline"));
let NodeKind::Path { path, .. } = &outline.kind else { panic!("a path") };
assert_eq!(path.anchor_count(), 3);
}
}
// A clip group or masked image that is not a piece knocks out by what it paints.
let mut plain = mesh_warp_image(&n, &im, &same, 1, false, false);
let NodeKind::Group { children, .. } = &mut plain.kind else { panic!("a group") };
let piece = Arc::make_mut(&mut children[0]);
piece.extras_mut().warp_piece = false;
assert!(piece.knockout_outline().is_none());
}
/// More cells than the objects live art may make cut no pieces (the count overflowed).
#[test]
fn mesh_warp_image_past_the_budget_makes_an_empty_group() {
let im = crate::ImageObject {
key: "pic".into(),
width: 4,
height: 4,
xf: Affine::IDENTITY,
link: None,
placement: Default::default(),
pixels: None,
};
let n = Node::new(NodeId(3), NodeKind::Image(Box::new(im.clone())));
for cells in [usize::MAX, 1000] {
let g = mesh_warp_image(&n, &im, &|p| p, cells, false, false);
assert!(matches!(&g.kind, NodeKind::Group { children, .. } if children.is_empty()), "{cells}");
}
}
}
+293 -28
View File
@@ -149,20 +149,31 @@ impl EnvelopeOptions {
/// its glyph outlines (see [`envelope_content_bounds`]). Strokes scale with the frame as
/// [`Node::transform`] scales them.
pub fn envelope_content_boxes(content: &[Arc<Node>], frame: Affine) -> Option<(Rect, Rect)> {
envelope_content_boxes_with(content, frame, false).or_else(|| envelope_content_boxes_with(content, frame, true))
}
/// [`envelope_content_boxes`] with type that draws nothing given its laid-out box when
/// `blank_type_box` is set and no box when it is not. A caller that measures the members of an
/// envelope's contents one at a time passes `true` only when the whole contents have no box with
/// `false`, so each member is measured as the whole contents measure it.
pub fn envelope_content_boxes_with(content: &[Arc<Node>], frame: Affine, blank_type_box: bool) -> Option<(Rect, Rect)> {
let frame = if frame.is_finite() && frame.determinant().abs() > 1e-12 { frame } else { Affine::IDENTITY };
let to_frame = frame.inverse();
let (stroked, plain) = content.iter().fold((None, None), |(stroked, plain), c| {
(vectorcraft_geom::union_opt(stroked, content_box(c, true, to_frame)), vectorcraft_geom::union_opt(plain, content_box(c, false, to_frame)))
});
Some((stroked?, plain?))
Some((content_set_box(content, true, to_frame, blank_type_box)?, content_set_box(content, false, to_frame, blank_type_box)?))
}
/// The geometric bounds an envelope around `content` on the page axes maps from: type, alone or
/// in groups and layers, is measured by its glyph outlines, underlines and strikethroughs instead
/// of its laid-out box. Type keeps its laid-out box while nothing is registered with
/// [`set_type_ink`], and when it draws nothing.
/// [`set_type_ink`]. Type that draws nothing adds no box while other content has one; when
/// nothing else has a box, it keeps its laid-out box.
pub fn envelope_content_bounds(content: &[Arc<Node>]) -> Option<Rect> {
content.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, content_box(c, false, Affine::IDENTITY)))
content_set_box(content, false, Affine::IDENTITY, false).or_else(|| content_set_box(content, false, Affine::IDENTITY, true))
}
/// The union of the boxes [`content_box`] gives each of `content`.
fn content_set_box(content: &[Arc<Node>], stroked: bool, to: Affine, blank_type_box: bool) -> Option<Rect> {
content.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, content_box(c, stroked, to, blank_type_box)))
}
/// The box of type's glyph outlines, underlines and strikethroughs with its text space mapped by
@@ -367,15 +378,16 @@ fn find_type(n: &Node, typed: &mut std::collections::HashSet<usize>) -> bool {
/// or with `stroked` its visual bounds (strokes scaled by `to` as [`Node::transform`] scales them),
/// with type measured by its glyph outlines ([`type_ink`]) instead of its laid-out box, in groups
/// and layers too. Type is laid out as it is on the page, and its outlines are then taken into
/// those axes. A character's strokes reach as far past its glyphs as past the laid-out box.
fn content_box(n: &Arc<Node>, stroked: bool, to: Affine) -> Option<Rect> {
/// those axes. A character's strokes reach as far past its glyphs as past the laid-out box. Type
/// that draws nothing has its laid-out box with `blank_type_box`, and no box without it.
fn content_box(n: &Arc<Node>, stroked: bool, to: Affine, blank_type_box: bool) -> Option<Rect> {
let mut typed = std::collections::HashSet::new();
find_type(n, &mut typed);
content_box_in(n, stroked, to, &typed)
content_box_in(n, stroked, to, &typed, blank_type_box)
}
/// [`content_box`], with the addresses of the objects in `n` that hold type ([`find_type`]).
fn content_box_in(n: &Arc<Node>, stroked: bool, to: Affine, typed: &std::collections::HashSet<usize>) -> Option<Rect> {
fn content_box_in(n: &Arc<Node>, stroked: bool, to: Affine, typed: &std::collections::HashSet<usize>, blank_type_box: bool) -> Option<Rect> {
// `n` in the axes of `to`.
let moved = || {
if to == Affine::IDENTITY {
@@ -395,10 +407,13 @@ fn content_box_in(n: &Arc<Node>, stroked: bool, to: Affine, typed: &std::collect
let ink = match n.projection() {
None => type_ink(n, t, to * t.xf, None),
Some(h) => type_ink(n, t, t.xf, Some((h, to))),
}
.flatten();
};
let m = moved();
let Some(ink) = ink else { return own(&m) };
let ink = match ink {
Some(Some(ink)) => ink,
Some(None) if !blank_type_box => return None,
_ => return own(&m),
};
if !stroked {
return Some(ink);
}
@@ -413,7 +428,13 @@ fn content_box_in(n: &Arc<Node>, stroked: bool, to: Affine, typed: &std::collect
NodeKind::Group { children, clip: true } | NodeKind::Layer { children, clip: true, .. } => {
// A clipping path that paints strokes over the clip edge, as in `Node::visual_bounds`.
let clip = children.first()?;
content_box_in(clip, stroked && matches!(clip.kind, NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Text(_)), to, typed)
content_box_in(
clip,
stroked && matches!(clip.kind, NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Text(_)),
to,
typed,
blank_type_box,
)
}
NodeKind::Layer { .. } | NodeKind::Group { .. } => {
let layer = matches!(n.kind, NodeKind::Layer { .. });
@@ -424,9 +445,11 @@ fn content_box_in(n: &Arc<Node>, stroked: bool, to: Affine, typed: &std::collect
let mut own_strokes = Node::new(n.id, NodeKind::Group { children: Vec::new(), clip: false });
own_strokes.appearance = n.appearance.clone();
own_strokes.transform(to, true);
own_strokes.visual_of_members(members.map(|c| content_box_in(c, true, to, typed)))
own_strokes.visual_of_members(members.map(|c| content_box_in(c, true, to, typed, blank_type_box)))
} else {
members.filter(|c| c.visible || !layer).fold(None, |acc, c| vectorcraft_geom::union_opt(acc, content_box_in(c, false, to, typed)))
members
.filter(|c| c.visible || !layer)
.fold(None, |acc, c| vectorcraft_geom::union_opt(acc, content_box_in(c, false, to, typed, blank_type_box)))
}
}
_ => own(&moved()),
@@ -525,21 +548,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.
@@ -564,7 +672,7 @@ impl<'a> EnvelopeMap<'a> {
pub fn new(content: &[Arc<Node>], kind: &'a EnvelopeKind, frame: Affine, options: EnvelopeOptions) -> Option<Self> {
let frame = if frame.is_finite() && frame.determinant().abs() > 1e-12 { frame } else { Affine::IDENTITY };
let to_frame = frame.inverse();
let src = content.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, content_box(c, false, to_frame)))?;
let src = content_set_box(content, false, to_frame, false).or_else(|| content_set_box(content, false, to_frame, true))?;
let src = options.source_box(src);
Some(Self { src, frame, to_frame, surface: surface_of(kind, src, frame) })
}
@@ -750,14 +858,171 @@ mod tests {
let to = Affine::scale(2.0);
let mut moved = (*group).clone();
moved.transform(to, true);
let want = moved.visual_of_members(std::iter::once(content_box(&text, true, to)));
let want = moved.visual_of_members(std::iter::once(content_box(&text, true, to, true)));
assert!(want.is_some());
assert_eq!(content_box(&group, true, to), want);
assert_eq!(content_box(&group, true, to, true), want);
let mut nested = group;
for i in 0..300 {
nested = Arc::new(Node::group(NodeId(10 + i), vec![nested]));
}
assert!(content_box(&nested, false, Affine::IDENTITY).is_some());
assert!(content_box(&nested, false, Affine::IDENTITY, true).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
+23 -8
View File
@@ -206,12 +206,26 @@ pub fn mesh_warp_cost(cells: usize) -> usize {
/// that takes the triangle where `f` takes its corners (with `masked`, the image masked by the
/// triangle instead; with `pixelated`, drawn without smoothing). Each piece reaches a little past
/// its edges (at most half a point) so neighbors overlap and no seams show. Each piece keeps the
/// color `n` colorizes a grayscale image with. The result is a group with `n`'s id, name,
/// transparency, opacity mask and appearance.
/// color `n` colorizes a grayscale image with, and `n`'s color mask. The result is a group with `n`'s id, name,
/// transparency, opacity mask and appearance. It is a knockout group and each piece is a
/// [`crate::NodeExtras::warp_piece`], so where pieces overlap only the top one draws and a
/// partly transparent image keeps its own alpha there. More cells than [`MAX_GENERATED`] objects
/// allow make an empty group.
pub fn mesh_warp_image(n: &Node, im: &ImageObject, f: &dyn Fn(Point) -> Point, cells: usize, pixelated: bool, masked: bool) -> Node {
let k = cells.max(1);
let mut g = n.clone();
g.kind = NodeKind::Group { children: vec![], clip: false };
g.knockout = crate::Knockout::On;
if let Some(e) = g.extras_if_any() {
e.colorize = None;
}
if mesh_warp_cost(k) > MAX_GENERATED {
return g;
}
// A grayscale image's fill color colorizes each piece; the group of pieces takes none.
let colorize = n.extras().colorize.clone();
// Each piece shows what the image shows: its color mask's masked pixels.
let color_mask = n.extras().color_mask.clone();
let (pw, ph) = (im.width as f64, im.height as f64);
let at = |i: usize, j: usize| Point::new(pw * i as f64 / k as f64, ph * j as f64 / k as f64);
let mut pieces = Vec::with_capacity(2 * k * k);
@@ -236,26 +250,27 @@ pub fn mesh_warp_image(n: &Node, im: &ImageObject, f: &dyn Fn(Point) -> Point, c
let mut image = Node::new(n.id, NodeKind::Image(Box::new(ImageObject { xf, ..im.clone() })));
image.extras_mut().pixelated = pixelated;
image.extras_mut().colorize = colorize.clone();
image.extras_mut().color_mask = color_mask.clone();
if masked {
// Preserve Shape Using Transparency: the triangle is the piece's alpha (a
// white opacity mask) instead of its clipping path.
let white = Node::path(n.id, shape, Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0));
pieces.push(Arc::new(image.with_mask(Some(Box::new(crate::OpacityMask::new(white, true))))));
let mut piece = image.with_mask(Some(Box::new(crate::OpacityMask::new(white, true))));
piece.extras_mut().warp_piece = true;
pieces.push(Arc::new(piece));
continue;
}
let mut clip = Node::path(n.id, shape, Appearance::default());
if let NodeKind::Path { clipping, .. } = &mut clip.kind {
*clipping = true;
}
pieces.push(Arc::new(Node::new(n.id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(image)], clip: true })));
let mut piece = Node::new(n.id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(image)], clip: true });
piece.extras_mut().warp_piece = true;
pieces.push(Arc::new(piece));
}
}
}
let mut g = n.clone();
g.kind = NodeKind::Group { children: pieces, clip: false };
if let Some(e) = g.extras_if_any() {
e.colorize = None;
}
g
}
+118 -22
View File
@@ -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;
@@ -530,6 +608,10 @@ pub(super) const MAX_BORDER_LINES: usize = 256;
/// The most rounds of new lines a mesh made from a path takes to keep its border on the outline.
const MAX_BORDER_ROUNDS: usize = 64;
/// A point this close (in points) to a mesh's outline is on it, for [`GradientMesh::locate_within`]
/// with any tolerance.
const ON_OUTLINE: f64 = 1e-6;
/// An anchor whose directions in and out differ by more than this (radians) is a corner: a border
/// edge that can't follow the outline takes a mesh line through its sharpest corner first.
const SHARP_TURN: f64 = 0.01;
@@ -1436,17 +1518,23 @@ impl GradientMesh {
}
/// As [`Self::locate`], and for a point outside the mesh within `tol` of its outline, the
/// patch and local (u, v) of the nearest point of the mesh's edge.
/// patch and local (u, v) of the nearest point of the mesh's edge. A point on the outline
/// (within [`ON_OUTLINE`]) locates on its edge on every side, with any `tol`.
pub fn locate_within(&self, p: Point, tol: f64) -> Option<(usize, usize, f64, f64)> {
if !self.is_valid() {
if !self.is_valid() || !p.is_finite() {
return None;
}
let bp = self.outline().to_bezpath();
if bp.winding(p) == 0 {
// A point on the outline takes the nearest point of the edge on every side: the nonzero
// winding number counts a point on some edges as outside (a rectangle's bottom and right
// edges) and on the others as inside.
if let Some((_, r, c, u, v)) = self.nearest_edge(p, ON_OUTLINE).filter(|e| e.0 <= ON_OUTLINE * ON_OUTLINE) {
return Some((r, c, u, v));
}
if self.outline().to_bezpath().winding(p) == 0 {
if tol.is_nan() || tol <= 0.0 {
return None;
}
return self.nearest_edge(p).filter(|e| e.0 <= tol * tol).map(|(_, r, c, u, v)| (r, c, u, v));
return self.nearest_edge(p, tol).filter(|e| e.0 <= tol * tol).map(|(_, r, c, u, v)| (r, c, u, v));
}
const N: usize = 16;
let mut best = (f64::INFINITY, 0, 0, 0.0, 0.0);
@@ -1484,12 +1572,20 @@ impl GradientMesh {
}
/// The point of the mesh's outer edge nearest `p`: its squared distance from `p`, and its
/// boundary patch and local (u, v).
fn nearest_edge(&self, p: Point) -> Option<(f64, usize, usize, f64, f64)> {
/// boundary patch and local (u, v). Edges whose control points all lie farther than `within`
/// from `p` are skipped, so `None` means no edge is within `within`.
fn nearest_edge(&self, p: Point, within: f64) -> Option<(f64, usize, usize, f64, f64)> {
use vectorcraft_geom::kurbo::ParamCurveNearest;
let (rows, cols) = (self.rows as usize, self.cols as usize);
let mut best: Option<(f64, usize, usize, f64, f64)> = None;
let mut take = |e: CubicBez, at: (usize, usize, Option<f64>, Option<f64>)| {
// The edge lies inside its control points' box, so a box farther than `within` holds
// no point of the edge within it.
let b = Rect::from_points(e.p0, e.p1).union_pt(e.p2).union_pt(e.p3);
let (dx, dy) = ((b.x0 - p.x).max(p.x - b.x1).max(0.0), (b.y0 - p.y).max(p.y - b.y1).max(0.0));
if dx * dx + dy * dy > within * within {
return;
}
let n = e.nearest(p, 1e-9);
if best.is_none_or(|b| n.distance_sq < b.0) {
let (r, c, u, v) = at;
+4
View File
@@ -261,6 +261,10 @@ fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet<usize>) -> u
b += ALLOC + size_of::<NodeExtras>();
b += boxed(&e.mask) + boxed(&e.graph) + boxed(&e.shaper) + boxed(&e.attrs) + boxed(&e.slice) + boxed(&e.perspective);
b += boxed(&e.dimension) + boxed(&e.live_paint_gaps) + boxed(&e.colorize);
b += e
.color_mask
.as_deref()
.map_or(0, |m| ALLOC + size_of::<crate::color_mask::ColorMask>() + m.key.capacity() + m.from.capacity() + m.colors.capacity() * 3);
b += e.trace.as_ref().map_or(0, |t| ALLOC + size_of::<Value>() + json_bytes(t));
b += e.intertwine.as_deref().map_or(0, |a| ALLOC + size_of::<PathData>() + path_bytes(a));
if e.intertwine_tiers.capacity() > 0 {
+9
View File
@@ -72,6 +72,13 @@ pub struct NodeExtras {
/// Transform panel › Align to Pixel Grid: the path's or compound path's horizontal and vertical
/// segments stay on the pixel grid when it is transformed.
pub pixel_aligned: bool,
/// Image Tools › Color Mask: the colors an image hides while its pixels stay as they are
/// ([`crate::color_mask`]).
pub color_mask: Option<Box<crate::color_mask::ColorMask>>,
/// A piece of an image a raster mesh warp cut up ([`crate::live::mesh_warp_image`]): in a
/// knockout group its knockout shape is the whole area of its triangle, not only where the
/// image is opaque ([`Node::knockout_outline`]).
pub warp_piece: bool,
}
/// No extras: what [`Node::extras`] gives for a node without any.
@@ -99,6 +106,8 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras {
symbol_overrides: Vec::new(),
envelope_edit_margin: None,
pixel_aligned: false,
color_mask: None,
warp_piece: false,
};
/// A node's [`NodeExtras`], if it has any ([`Node::extras`]). Extras that are all unset equal
+116 -33
View File
@@ -716,6 +716,37 @@ impl Node {
out
}
/// As a piece of a mesh-warped image ([`crate::NodeExtras::warp_piece`]), the art whose area is its
/// knockout shape at full coverage: the art of its opacity mask (on and not inverted), or the
/// clipping path of its clip group. `None` for other objects, whose knockout shape is what they
/// paint.
pub fn knockout_outline(&self) -> Option<&Arc<Node>> {
let e = self.extras();
if !e.warp_piece {
return None;
}
if let Some(m) = e.mask.as_deref() {
return (!m.disabled && !m.invert).then_some(&m.art);
}
match &self.kind {
NodeKind::Group { children, clip: true } => children.first(),
_ => None,
}
}
/// The image a piece of a mesh-warped image draws ([`Self::knockout_outline`]): the piece itself
/// when an opacity mask cuts it, else the image its clip group clips. `None` for other objects.
pub fn warp_piece_image(&self) -> Option<&Node> {
if !self.extras().warp_piece {
return None;
}
match &self.kind {
NodeKind::Image(_) => Some(self),
NodeKind::Group { children, clip: true } => children.get(1).map(|c| &**c).filter(|c| matches!(c.kind, NodeKind::Image(_))),
_ => None,
}
}
/// Whether this is a clip group or a layer with a clipping mask: its first child clips the rest.
/// A layer whose first child is a ruler guide holds no art, so a guide never clips it.
pub fn clips(&self) -> bool {
@@ -732,33 +763,19 @@ impl Node {
children.iter().rposition(|c| !c.is_ruler_guide()).map_or(0, |i| i + 1)
}
/// Remove the ruler guides of this layer and of its sublayers. Other nodes hold none.
/// Remove the ruler guides of this layer and of its sublayers. Other nodes hold none. Only
/// layers that hold one are copied.
pub fn strip_ruler_guides(&mut self) {
if !self.holds_ruler_guides() {
return;
}
if let Some(ch) = self.children_mut() {
ch.retain(|c| !c.is_ruler_guide());
for c in ch.iter_mut().filter(|c| c.holds_ruler_guides()) {
Arc::make_mut(c).strip_ruler_guides();
}
if let Some(held) = held_guides(self, &Self::is_ruler_guide) {
strip_held(self, held);
}
}
/// Call `f` on the position (along the axis it crosses) of each ruler guide of this layer and
/// of its sublayers, with whether the guide is vertical. Only layers that hold one are copied.
pub fn map_ruler_guide_positions(&mut self, f: &mut impl FnMut(bool, &mut f64)) {
if !self.holds_ruler_guides() {
return;
}
if let Some(ch) = self.children_mut() {
for c in ch.iter_mut().filter(|c| c.is_ruler_guide() || c.holds_ruler_guides()) {
let c = Arc::make_mut(c);
match &mut c.kind {
NodeKind::RulerGuide { vertical, pos, .. } => f(*vertical, pos),
_ => c.map_ruler_guide_positions(f),
}
}
if let Some(held) = held_guides(self, &Self::is_ruler_guide) {
map_held(self, held, f);
}
}
@@ -803,6 +820,61 @@ impl Node {
}
}
/// The ruler guides a layer holds: its children that are one, by index in order (each with
/// nothing inside), and its sublayers holding one (with what they hold).
#[derive(Debug, Default)]
pub(super) struct HeldGuides(Vec<(usize, HeldGuides)>);
/// The ruler guides, by `is_guide`, that `n` holds if it is a layer, or `None` when it holds
/// none. `is_guide` looks at each child of `n` and of its sublayers once.
pub(super) fn held_guides(n: &Node, is_guide: &impl Fn(&Node) -> bool) -> Option<HeldGuides> {
if !n.is_layer() {
return None;
}
let held: Vec<_> = n
.children()
.into_iter()
.flatten()
.enumerate()
.filter_map(|(i, c)| if is_guide(c) { Some((i, HeldGuides::default())) } else { held_guides(c, is_guide).map(|h| (i, h)) })
.collect();
(!held.is_empty()).then_some(HeldGuides(held))
}
/// Remove the ruler guides of `layer` and of its sublayers that [`held_guides`] found (`held`).
/// Only the sublayers holding one are copied, and only those are visited.
pub(super) fn strip_held(layer: &mut Node, held: HeldGuides) {
let Some(ch) = layer.children_mut() else { return };
let mut held = held.0.into_iter().peekable();
let mut next = 0;
ch.retain_mut(|c| {
let at = next;
next += 1;
let Some((_, inner)) = held.next_if(|(i, _)| *i == at) else { return true };
// A sublayer holds something; a ruler guide has nothing inside.
if inner.0.is_empty() {
return false;
}
strip_held(Arc::make_mut(c), inner);
true
});
}
/// Call `f` (whether it is vertical, its position) on each ruler guide of `layer` and of its
/// sublayers that [`held_guides`] found (`held`), in the order they lie in. Only the sublayers
/// holding one, and the guides, are copied, and only those sublayers are visited.
pub(super) fn map_held(layer: &mut Node, held: HeldGuides, f: &mut impl FnMut(bool, &mut f64)) {
let Some(ch) = layer.children_mut() else { return };
for (i, inner) in held.0 {
let Some(c) = ch.get_mut(i) else { continue };
if !inner.0.is_empty() {
map_held(Arc::make_mut(c), inner, f);
} else if let NodeKind::RulerGuide { vertical, pos, .. } = &mut Arc::make_mut(c).kind {
f(*vertical, pos);
}
}
}
impl Node {
/// The Appearance panel's row for what this object's own fills and strokes paint around:
/// "Contents" for a group or layer (its members) and for an image (its pixels), "Characters"
@@ -819,7 +891,8 @@ impl Node {
impl Node {
/// Whether this object shows any transparency, itself or anything inside it: object, fill or
/// stroke opacity below 100%, a blend mode, an opacity mask, effects, transparent gradient
/// stops or a colorized image. Hidden objects show none.
/// stops (characters' fills and strokes included) or a colorized image. Hidden objects show
/// none.
pub fn shows_transparency(&self) -> bool {
self.shows_transparency_with(&|_| true)
}
@@ -827,21 +900,31 @@ impl Node {
/// [`Self::shows_transparency`], counting a colorized image by itself only when `colorize`
/// accepts it, for files that write some colorized images in their colorize paint (EPS).
pub fn shows_transparency_with(&self, colorize: &dyn Fn(&Node) -> bool) -> bool {
self.visible && (self.own_transparency(colorize) || self.children().is_some_and(|ch| ch.iter().any(|c| c.shows_transparency_with(colorize))))
}
/// [`Self::shows_transparency`] of the object alone, what it holds left out.
pub fn shows_own_transparency(&self) -> bool {
self.visible && self.own_transparency(&|_| true)
}
/// The object's own transparency, as [`Self::shows_transparency_with`] counts it.
fn own_transparency(&self, colorize: &dyn Fn(&Node) -> bool) -> bool {
use vectorcraft_color::Paint;
let see_through = |p: &Paint| matches!(p, Paint::Gradient(g) if g.gradient.stops.iter().any(|s| s.opacity < 1.0));
let effects = |fx: &[crate::Effect]| fx.iter().any(|e| e.visible);
self.visible
&& (self.opacity < 1.0
|| self.blend != BlendMode::Normal
|| self.extras().mask.as_ref().is_some_and(|m| !m.disabled)
|| (matches!(self.kind, NodeKind::Image(_)) && self.extras().colorize.is_some() && colorize(self))
|| effects(&self.appearance.effects)
|| self
.appearance
.items
.iter()
.any(|i| i.visible() && (i.opacity() < 1.0 || i.blend() != BlendMode::Normal || see_through(i.paint()) || effects(i.effects())))
|| self.children().is_some_and(|ch| ch.iter().any(|c| c.shows_transparency_with(colorize))))
self.opacity < 1.0
|| self.blend != BlendMode::Normal
|| self.extras().mask.as_ref().is_some_and(|m| !m.disabled)
|| (matches!(self.kind, NodeKind::Image(_)) && self.extras().colorize.is_some() && colorize(self))
|| effects(&self.appearance.effects)
|| self
.appearance
.items
.iter()
.any(|i| i.visible() && (i.opacity() < 1.0 || i.blend() != BlendMode::Normal || see_through(i.paint()) || effects(i.effects())))
// Characters' own fills and strokes, which draw with the object.
|| matches!(&self.kind, NodeKind::Text(t) if t.runs.iter().any(|r| see_through(&r.style.fill) || (r.style.stroke_width > 0.0 && see_through(&r.style.stroke))))
}
}
+207
View File
@@ -23,6 +23,7 @@ fn extras_are_written_flat_in_order() {
e.shape_mode = crate::ShapeMode::Exclude;
e.envelope_edit_margin = Some([0.5, 0.5, 0.25, 0.25]);
e.pixel_aligned = true;
e.warp_piece = true;
}
/// The top-level keys of a JSON object, in the order written.
struct Keys(Vec<String>);
@@ -69,10 +70,12 @@ fn extras_are_written_flat_in_order() {
"shape_mode",
"envelope_edit_margin",
"pixel_aligned",
"warp_piece",
];
assert_eq!(keys, order);
assert_eq!(v["shape_mode"], "exclude");
assert_eq!(v["pixel_aligned"], true);
assert_eq!(v["warp_piece"], true);
assert_eq!(serde_json::from_value::<Node>(v).unwrap(), n);
let plain = Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 4.0, 2.0)), Appearance::default_art());
let back: Node = serde_json::from_value(serde_json::to_value(&plain).unwrap()).unwrap();
@@ -595,3 +598,207 @@ fn compound_stroke_path_is_its_members_in_order() {
assert_eq!(bp.elements(), expected.elements());
assert!(!bp.elements().is_empty());
}
/// The sublayers in [`guide_layers`]'s chain, each inside the one before.
const GUIDE_CHAIN: u64 = 30;
/// How many children the layers of [`guide_layers`] hold: the layer's 6, 1 in the sublayer
/// without a guide, 2 at each of the two places the shared sublayer lies, the innermost
/// sublayer's 2 and 3 in each sublayer around it.
const GUIDE_LAYER_CHILDREN: usize = 6 + 1 + 2 * 2 + 2 + (GUIDE_CHAIN as usize - 1) * 3;
/// How many ruler guides the layers of [`guide_layers`] hold: one in each sublayer of the chain,
/// one at each place the shared sublayer lies and the layer's own.
const GUIDE_LAYER_GUIDES: usize = GUIDE_CHAIN as usize + 2 + 1;
/// A layer holding, in order: [`GUIDE_CHAIN`] sublayers, each inside the one before and holding an
/// object and a ruler guide; a sublayer with an object only; a sublayer with an object and a
/// guide; an object; that last sublayer again; and a guide. Guides differ in direction, artboard
/// and lock. Returns the layer, the sublayer without a guide and the one that lies twice.
fn guide_layers() -> (Node, Arc<Node>, Arc<Node>) {
let rect = |id| Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()));
let guide = |id: u64| {
let kind = NodeKind::RulerGuide { vertical: id.is_multiple_of(2), pos: id as f64, artboard: id.is_multiple_of(3).then_some(7) };
let mut g = Node::new(NodeId(id), kind);
g.locked = id.is_multiple_of(5);
Arc::new(g)
};
let sublayer = |id, children: Vec<Arc<Node>>| {
let mut l = Node::layer(NodeId(id), "Sub", LayerColor::Preset(1));
if let Some(ch) = l.children_mut() {
*ch = children;
}
Arc::new(l)
};
let mut chain = sublayer(100, vec![rect(150), guide(200)]);
for depth in 1..GUIDE_CHAIN {
chain = sublayer(100 + depth, vec![rect(600 + depth), chain, guide(300 + depth)]);
}
let still = sublayer(500, vec![rect(501)]);
let twice = sublayer(510, vec![rect(511), guide(512)]);
let mut layer = Node::layer(NodeId(1), "Layer", LayerColor::Preset(0));
if let Some(ch) = layer.children_mut() {
*ch = vec![chain, Arc::clone(&still), Arc::clone(&twice), rect(2), Arc::clone(&twice), guide(3)];
}
(layer, still, twice)
}
/// Whether `a` and `b` hold the same children, none of them copied.
fn same_children(a: &Node, b: &Node) -> bool {
let (a, b) = (a.children().unwrap(), b.children().unwrap());
a.len() == b.len() && a.iter().zip(b).all(|(a, b)| Arc::ptr_eq(a, b))
}
/// Stripping the ruler guides of a layer looks at each child of the layer and of its sublayers
/// once, however deep the sublayers nest. The art and its order stay, a sublayer without a guide is
/// not copied, and a copy of the layer held elsewhere keeps its guides.
#[test]
fn stripping_ruler_guides_looks_at_each_child_of_nested_layers_once() {
use std::cell::Cell;
let (whole, still, twice) = guide_layers();
let ids = |n: &Node| {
let mut out = vec![];
n.walk(&mut |c| out.push(c.id));
out
};
let mut art = vec![];
whole.walk(&mut |c| {
if !c.is_ruler_guide() {
art.push(c.id);
}
});
assert_eq!(ids(&whole).len(), art.len() + GUIDE_LAYER_GUIDES);
let mut n = whole.clone();
let looked = Cell::new(0_usize);
let pick = |c: &Node| {
looked.set(looked.get() + 1);
c.is_ruler_guide()
};
let held = super::ops::held_guides(&n, &pick).unwrap();
assert_eq!(looked.get(), GUIDE_LAYER_CHILDREN, "each child of the layers is looked at once");
super::ops::strip_held(&mut n, held);
assert_eq!(looked.get(), GUIDE_LAYER_CHILDREN, "removing looks at nothing again");
assert_eq!(ids(&n), art, "the art stays, in its order");
let ch = n.children().unwrap();
assert!(Arc::ptr_eq(&ch[1], &still), "a sublayer without a guide is not copied");
assert!(Arc::ptr_eq(&ch[3], &whole.children().unwrap()[3]), "an object is not copied");
assert!(!Arc::ptr_eq(&ch[2], &twice) && !Arc::ptr_eq(&ch[4], &twice) && !Arc::ptr_eq(&ch[2], &ch[4]));
assert_eq!(
(ch[2].children().map(Vec::len), ch[4].children().map(Vec::len)),
(Some(1), Some(1)),
"a sublayer lying twice is stripped at both places"
);
// The copies held elsewhere (an undo step's, say) keep their guides.
assert_eq!(twice.children().map(Vec::len), Some(2));
assert_eq!(ids(&whole).len(), art.len() + GUIDE_LAYER_GUIDES);
// The method strips the same guides.
let mut same = whole.clone();
same.strip_ruler_guides();
assert_eq!(same, n);
assert!(Arc::ptr_eq(&same.children().unwrap()[1], &still));
// With no guide left there is nothing to remove, and nothing is copied.
let before = n.clone();
n.strip_ruler_guides();
assert!(same_children(&n, &before));
let mut empty = Node::layer(NodeId(900), "Empty", LayerColor::Preset(0));
empty.strip_ruler_guides();
assert_eq!(empty.children().map(Vec::len), Some(0));
// Only a layer holds ruler guides: a group is left as it is, on its own and in a layer.
let mut group = Node::group(NodeId(901), vec![Arc::clone(&twice)]);
assert!(super::ops::held_guides(&group, &Node::is_ruler_guide).is_none());
group.strip_ruler_guides();
assert!(Arc::ptr_eq(&group.children().unwrap()[0], &twice));
let group = Arc::new(group);
let mut around = Node::layer(NodeId(902), "Around", LayerColor::Preset(0));
around.children_mut().unwrap().push(Arc::clone(&group));
around.strip_ruler_guides();
assert!(Arc::ptr_eq(&around.children().unwrap()[0], &group));
}
/// Changing the positions of the ruler guides of a layer looks at each child of the layer and of
/// its sublayers once, however deep the sublayers nest. Each guide is changed once, in the order
/// the guides lie in, and keeps everything else about it; the art is unchanged, a sublayer without
/// a guide is not copied, and a copy of the layer held elsewhere keeps its positions.
#[test]
fn mapping_ruler_guide_positions_looks_at_each_child_of_nested_layers_once() {
use std::cell::Cell;
let (whole, still, twice) = guide_layers();
let mut lines = vec![];
whole.walk(&mut |c| {
if let NodeKind::RulerGuide { vertical, pos, .. } = c.kind {
lines.push((vertical, pos));
}
});
assert_eq!(lines.len(), GUIDE_LAYER_GUIDES);
assert!(lines.iter().any(|l| l.0) && lines.iter().any(|l| !l.0), "guides in both directions");
let mut n = whole.clone();
let looked = Cell::new(0_usize);
let pick = |c: &Node| {
looked.set(looked.get() + 1);
c.is_ruler_guide()
};
let held = super::ops::held_guides(&n, &pick).unwrap();
assert_eq!(looked.get(), GUIDE_LAYER_CHILDREN, "each child of the layers is looked at once");
let mut seen = vec![];
super::ops::map_held(&mut n, held, &mut |vertical, pos| {
seen.push((vertical, *pos));
*pos = *pos * 2.0 + 1.0;
});
assert_eq!(looked.get(), GUIDE_LAYER_CHILDREN, "changing looks at nothing again");
assert_eq!(seen, lines, "each guide once, in the order the guides lie in");
// The same nodes in the same order: a guide differs in its position alone, and the art not
// at all.
let (mut was, mut now) = (vec![], vec![]);
whole.walk(&mut |c| was.push(c));
n.walk(&mut |c| now.push(c));
assert_eq!(was.len(), now.len());
for (a, b) in was.into_iter().zip(now) {
if a.is_layer() {
assert_eq!((b.id, b.is_layer(), b.children().map(Vec::len)), (a.id, true, a.children().map(Vec::len)));
continue;
}
let mut want = a.clone();
if let NodeKind::RulerGuide { pos, .. } = &mut want.kind {
*pos = *pos * 2.0 + 1.0;
}
assert_eq!(b, &want);
}
let ch = n.children().unwrap();
assert!(Arc::ptr_eq(&ch[1], &still), "a sublayer without a guide is not copied");
assert!(Arc::ptr_eq(&ch[3], &whole.children().unwrap()[3]), "an object is not copied");
assert!(!Arc::ptr_eq(&ch[2], &twice) && !Arc::ptr_eq(&ch[4], &twice) && !Arc::ptr_eq(&ch[2], &ch[4]));
// The copy held elsewhere keeps its position.
assert!(matches!(twice.children().unwrap()[1].kind, NodeKind::RulerGuide { pos, .. } if pos == 512.0));
// The method changes the same guides, each once.
let mut same = whole.clone();
let mut calls = 0;
same.map_ruler_guide_positions(&mut |_, pos| {
calls += 1;
*pos = *pos * 2.0 + 1.0;
});
assert_eq!((calls, &same), (GUIDE_LAYER_GUIDES, &n));
assert!(Arc::ptr_eq(&same.children().unwrap()[1], &still));
// A function that leaves the positions as they are is still called on each guide.
let mut kept = whole.clone();
let mut calls = 0;
kept.map_ruler_guide_positions(&mut |_, _| calls += 1);
assert_eq!((calls, &kept), (GUIDE_LAYER_GUIDES, &whole));
// A layer without a guide, an empty layer and a group: nothing to change, nothing copied.
let mut bare = whole.clone();
bare.strip_ruler_guides();
let before = bare.clone();
let mut calls = 0;
bare.map_ruler_guide_positions(&mut |_, _| calls += 1);
assert!(same_children(&bare, &before));
let mut empty = Node::layer(NodeId(900), "Empty", LayerColor::Preset(0));
empty.map_ruler_guide_positions(&mut |_, _| calls += 1);
let mut group = Node::group(NodeId(901), vec![Arc::clone(&twice)]);
group.map_ruler_guide_positions(&mut |_, _| calls += 1);
assert!(Arc::ptr_eq(&group.children().unwrap()[0], &twice));
assert_eq!(calls, 0);
}
+10
View File
@@ -55,6 +55,8 @@ impl Serialize for Node {
e.symbol_overrides.is_empty(),
e.envelope_edit_margin.is_none(),
is_default(&e.pixel_aligned),
e.color_mask.is_none(),
is_default(&e.warp_piece),
];
let mut st = s.serialize_struct("Node", skips.iter().filter(|s| !**s).count())?;
let mut skip = skips.into_iter();
@@ -98,6 +100,8 @@ impl Serialize for Node {
field!("symbol_overrides", &e.symbol_overrides);
field!("envelope_edit_margin", &e.envelope_edit_margin);
field!("pixel_aligned", &e.pixel_aligned);
field!("color_mask", &e.color_mask);
field!("warp_piece", &e.warp_piece);
st.end()
}
}
@@ -241,6 +245,10 @@ pub(super) struct NodeWire {
envelope_edit_margin: Option<[f32; 4]>,
#[serde(default)]
pixel_aligned: bool,
#[serde(default)]
color_mask: Option<Box<crate::color_mask::ColorMask>>,
#[serde(default)]
warp_piece: bool,
}
impl From<NodeWire> for Node {
@@ -269,6 +277,8 @@ impl From<NodeWire> for Node {
symbol_overrides: w.symbol_overrides,
envelope_edit_margin: w.envelope_edit_margin,
pixel_aligned: w.pixel_aligned,
color_mask: w.color_mask,
warp_piece: w.warp_piece,
};
Node {
id: w.id,
+120 -30
View File
@@ -121,19 +121,22 @@ impl ObjectsOnPath {
if a.determinant() < 0.0 && self.rotate != 0.0 {
self.rotate = -self.rotate;
}
let along = paths.and_then(|(old, new)| {
let s = path_length(new)?.0 / path_length(old)?.0;
(s.is_finite() && s > 0.0).then_some(s)
});
let scale = along.unwrap_or_else(|| a.determinant().abs().sqrt());
// A move leaves the distances along the path as they are.
let moves = a0 == 1.0 && a1 == 0.0 && a2 == 0.0 && a3 == 1.0;
if !moves && scale.is_finite() && scale > 0.0 {
let scaled = |v: f64| Some(v * scale).filter(|s| s.is_finite()).unwrap_or(v);
let moved = paths.and_then(|(old, new)| self.moved_along(a, old, new, scale));
let (spacing, start) = moved.unwrap_or((None, None));
self.spacing = self.spacing.map(|g| spacing.unwrap_or_else(|| scaled(g)));
self.start = start.unwrap_or_else(|| scaled(self.start));
if !moves {
let measured = paths.and_then(|(old, new)| Some((Measured::new(old)?, Measured::new(new)?)));
let along = measured.as_ref().and_then(|(was, is)| {
let s = is.len / was.len;
(s.is_finite() && s > 0.0).then_some(s)
});
let scale = along.unwrap_or_else(|| a.determinant().abs().sqrt());
if scale.is_finite() && scale > 0.0 {
let scaled = |v: f64| Some(v * scale).filter(|s| s.is_finite()).unwrap_or(v);
let moved = measured.as_ref().and_then(|(was, is)| self.moved_along(a, was, is, scale));
let (spacing, start) = moved.unwrap_or((None, None));
self.spacing = self.spacing.map(|g| spacing.unwrap_or_else(|| scaled(g)));
self.start = start.unwrap_or_else(|| scaled(self.start));
}
}
let after = tilt(self.rotate);
for m in &mut self.members {
@@ -150,11 +153,10 @@ impl ObjectsOnPath {
/// point on `old`, mapped by `a`, measured along `new` near `scale` times its distance along
/// `old`. Either one is `None` when it cannot be followed that way: a start before or beyond the
/// ends of an open path, or a Space value of 0, one the path has no room for, or one with fewer
/// than two objects. `None` for a path without length or a start that is not finite.
fn moved_along(&self, a: Affine, old: &PathData, new: &PathData, scale: f64) -> Option<(Option<f64>, Option<f64>)> {
let (was, is) = (Spine::new(old)?, Spine::new(new)?);
let (len, closed) = path_length(old)?;
let (new_len, _) = path_length(new)?;
/// than two objects. `None` for a start that is not finite.
fn moved_along(&self, a: Affine, old: &Measured, new: &Measured, scale: f64) -> Option<(Option<f64>, Option<f64>)> {
let (was, is) = (&old.spine, &new.spine);
let (len, closed, new_len) = (old.len, old.closed, new.len);
if !self.start.is_finite() {
return None;
}
@@ -230,10 +232,10 @@ pub fn is_objects_on_path(n: &Node) -> bool {
}
/// The path of `n` if it is a path object an Objects on Path group can attach objects to: a path
/// (not a guide) whose first subpath has some length.
/// (not a guide) whose first subpath has a length ([`path_length`]).
pub fn attachable_path(n: &Node) -> Option<&PathData> {
match &n.kind {
NodeKind::Path { path, guide: false, .. } if Spine::new(path).is_some_and(|s| s.length() > 1e-9) => Some(path),
NodeKind::Path { path, guide: false, .. } if path_length(path).is_some() => Some(path),
_ => None,
}
}
@@ -292,11 +294,27 @@ pub fn upright_frame(n: &Node) -> Affine {
}
/// The length of `path`'s first subpath and whether it is closed. `None` for a path without
/// length.
/// length, or with a length too large to be finite.
pub fn path_length(path: &PathData) -> Option<(f64, bool)> {
let len = Spine::new(path)?.length();
let closed = path.subpaths.first().is_some_and(|s| s.closed);
(len.is_finite() && len > 1e-9).then_some((len, closed))
Measured::new(path).map(|m| (m.len, m.closed))
}
/// A path's first subpath flattened ([`Spine`]), with its length and whether it is closed, so that
/// one flattening serves both measuring the path and finding points along it.
struct Measured {
spine: Spine,
len: f64,
closed: bool,
}
impl Measured {
/// `None` for a path without length, or with a length too large to be finite.
fn new(path: &PathData) -> Option<Self> {
let spine = Spine::new(path)?;
let len = spine.length();
let closed = path.subpaths.first().is_some_and(|s| s.closed);
(len.is_finite() && len > 1e-9).then_some(Self { spine, len, closed })
}
}
/// Where the first of `n` objects attaches along a path of length `len` (closed or not), and the
@@ -341,18 +359,20 @@ fn wrap(s: f64, len: f64) -> f64 {
/// (radians, as `atan2` gives in the document's axes). They go along it as [`layout`] spaces them
/// for Space `spacing` (`None`: Auto) from `start`. `None` for a path without length.
pub fn stops(path: &PathData, n: usize, spacing: Option<f64>, start: f64) -> Option<Vec<(Point, f64)>> {
let spine = Spine::new(path)?;
let (len, closed) = path_length(path)?;
let Measured { spine, len, closed } = Measured::new(path)?;
let (start, gap) = layout(len, closed, n, spacing, start);
Some((0..n).map(|i| spine.at_length(nth_length(len, closed, start, gap, i))).collect())
}
/// Where object `i` of `n` attaches along `path`, as [`stops`] places it, without the others.
/// `None` for an `i` of `n` or more, without measuring the path.
pub fn stop(path: &PathData, n: usize, spacing: Option<f64>, start: f64, i: usize) -> Option<(Point, f64)> {
let spine = Spine::new(path)?;
let (len, closed) = path_length(path)?;
if i >= n {
return None;
}
let Measured { spine, len, closed } = Measured::new(path)?;
let (start, gap) = layout(len, closed, n, spacing, start);
(i < n).then(|| spine.at_length(nth_length(len, closed, start, gap, i)))
Some(spine.at_length(nth_length(len, closed, start, gap, i)))
}
/// The distance along a path of length `len` (closed or not) to object `i`, from `start` and
@@ -400,11 +420,15 @@ pub fn place(g: &mut Node, symbols: &SymbolBoxes) -> bool {
let old = rec.clone();
let NodeKind::Group { children, .. } = &mut g.kind else { return false };
let path_id = rec.path;
let Some(path) = children.iter().find(|c| c.id == path_id).filter(|c| matches!(c.kind, NodeKind::Path { .. })) else {
let Some(path) = children.iter().find(|c| c.id == path_id).filter(|c| matches!(c.kind, NodeKind::Path { .. })).cloned() else {
g.extras_mut().objects_on_path = None;
return true;
};
let path = attachable_path(path).cloned();
// `stops` measures the path: on a path without length no object moves.
let path = match &path.kind {
NodeKind::Path { path, guide: false, .. } => Some(path),
_ => None,
};
let at: HashMap<NodeId, usize> = children.iter().enumerate().map(|(i, c)| (c.id, i)).collect();
rec.members.retain(|m| m.id != path_id && at.contains_key(&m.id));
let mut listed: HashSet<NodeId> = rec.members.iter().map(|m| m.id).collect();
@@ -414,7 +438,7 @@ pub fn place(g: &mut Node, symbols: &SymbolBoxes) -> bool {
}
}
let mut moved = false;
if let Some(stops) = path.and_then(|p| stops(&p, rec.members.len(), rec.spacing, rec.start)) {
if let Some(stops) = path.and_then(|p| stops(p, rec.members.len(), rec.spacing, rec.start)) {
let turn = tilt(rec.rotate);
for (m, (p, dir)) in rec.members.iter_mut().zip(stops) {
let Some(c) = at.get(&m.id).and_then(|i| children.get_mut(*i)) else { continue };
@@ -709,6 +733,72 @@ mod tests {
assert!((back.angle - 0.5).abs() < 1e-12, "{back:?}");
}
/// What `f` returns, and how many times it flattened a path ([`Spine::new`]).
fn flattenings<T>(f: impl FnOnce() -> T) -> (T, usize) {
crate::blend::SPINES_BUILT.with(|n| n.set(0));
let out = f();
(out, crate::blend::SPINES_BUILT.with(|n| n.get()))
}
#[test]
fn stops_and_stop_flatten_the_path_once() {
let open = shapes::line(Point::new(0.0, 0.0), Point::new(300.0, 0.0));
let closed = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0));
for path in [&open, &closed] {
let (all, count) = flattenings(|| stops(path, 4, Some(40.0), 25.0));
let all = all.unwrap();
assert_eq!((all.len(), count), (4, 1));
for (i, s) in all.iter().enumerate() {
assert_eq!(flattenings(|| stop(path, 4, Some(40.0), 25.0, i)), (Some(*s), 1), "object {i}");
}
assert_eq!(flattenings(|| stop(path, 4, Some(40.0), 25.0, 4)), (None, 0), "an index past the last object");
assert_eq!(flattenings(|| stop(path, 0, None, 0.0, 0)), (None, 0), "no objects");
}
let point = shapes::line(Point::ZERO, Point::ZERO);
assert!(stops(&point, 2, None, 0.0).is_none() && stop(&point, 2, None, 0.0, 0).is_none());
}
#[test]
fn transforming_the_group_flattens_each_path_once() {
let a = rect(2, Rect::new(0.0, 0.0, 10.0, 10.0));
let b = rect(3, Rect::new(20.0, 0.0, 30.0, 10.0));
let level = shapes::line(Point::new(0.0, 0.0), Point::new(300.0, 0.0));
let stretch = Affine::scale_non_uniform(2.0, 1.0);
let wide = level.transformed(stretch);
let mut rec = ObjectsOnPath { spacing: Some(40.0), start: 10.0, ..ObjectsOnPath::new(NodeId(1), &[&a, &b], CENTER, 0.0) };
let ((), count) = flattenings(|| rec.transform(stretch, Some((&level, &wide))));
assert_eq!(count, 2, "the path before the transform and after it");
assert!((rec.start - 20.0).abs() < 1e-9 && (rec.spacing.unwrap() - 80.0).abs() < 1e-9, "{rec:?}");
let moved = level.transformed(Affine::translate((5.0, 5.0)));
let ((), count) = flattenings(|| rec.transform(Affine::translate((5.0, 5.0)), Some((&level, &moved))));
assert_eq!(count, 0, "a move leaves the distances along the path as they are");
}
#[test]
fn placing_the_objects_flattens_the_path_once() {
let line = Node::path(NodeId(1), shapes::line(Point::new(0.0, 100.0), Point::new(300.0, 100.0)), Default::default());
let (a, b) = (rect(2, Rect::new(0.0, 0.0, 10.0, 10.0)), rect(3, Rect::new(20.0, 0.0, 30.0, 10.0)));
let mut g = Node::new(NodeId(4), NodeKind::Group { children: vec![Arc::new(line), Arc::new(a.clone()), Arc::new(b.clone())], clip: false });
g.extras_mut().objects_on_path = Some(Box::new(ObjectsOnPath::new(NodeId(1), &[&a, &b], CENTER, 0.0)));
let empty = crate::Document::new(1.0, 1.0);
let symbols = empty.symbol_boxes();
assert_eq!(flattenings(|| place(&mut g, &symbols)), (true, 1));
let x = |id| g.children().and_then(|c| c.iter().find(|c| c.id == id).cloned()).unwrap().geometric_bounds().unwrap().center().x;
assert!((x(NodeId(2))).abs() < 1e-9 && (x(NodeId(3)) - 300.0).abs() < 1e-9, "{} {}", x(NodeId(2)), x(NodeId(3)));
}
/// A path whose length adds up past the largest finite number cannot be measured, so nothing
/// attaches to it.
#[test]
fn a_path_too_long_to_measure_is_not_attachable() {
let huge = Node::path(NodeId(1), shapes::line(Point::new(-1e308, 0.0), Point::new(1e308, 0.0)), Default::default());
let NodeKind::Path { path, .. } = &huge.kind else { panic!("a path") };
assert!(path_length(path).is_none() && stops(path, 2, None, 0.0).is_none());
assert!(attachable_path(&huge).is_none());
let square = rect(2, Rect::new(0.0, 0.0, 10.0, 10.0));
assert!(attachable_path(&square).is_some());
}
#[test]
fn a_group_without_its_path_is_a_plain_group() {
let a = rect(2, Rect::new(0.0, 0.0, 10.0, 10.0));
+49 -12
View File
@@ -11,9 +11,9 @@ use crate::ImageBlob;
/// address and aborts when an allocation fails, so it keeps the decoder's own 512 MB.
pub const MAX_RASTER_ALLOC: u64 = if cfg!(target_arch = "wasm32") { 512 << 20 } else { 2 << 30 };
/// A box of an image to sample, in 0 to 1 units of its width and height (`None`: all of it), and
/// the pixel centres to take from it ([`ImageBlob::sample_pixels`]).
pub type PixelPick<'a> = (Option<[f64; 4]>, &'a dyn Fn(f64, f64) -> bool);
/// A box of an image to sample, in 0 to 1 units of its width and height (`None`: all of it), the
/// pixels to sample from it at most, and the pixel centres to take ([`ImageBlob::sample_pixels`]).
pub type PixelPick<'a> = (Option<[f64; 4]>, usize, &'a dyn Fn(f64, f64) -> bool);
/// The pixels of encoded image `bytes` as RGBA; `None` when they can't be decoded, would take
/// more than `max` bytes as RGBA, or need more than `max` bytes to decode. The size is read from
@@ -65,13 +65,13 @@ impl ImageBlob {
Some(Self::png(png))
}
/// For each of `picks`, at most `budget` of the image's pixels (at least one), spread evenly
/// For each of `picks`, at most its budget of the image's pixels (at least one), spread evenly
/// in rows and columns over the pick's box (`[u0, v0, u1, v1]`, where 0 to 1 spans the
/// image's width and height from the top left; clipped to the image; `None`: the whole image),
/// as straight RGBA. Only pixels whose centres the pick's function takes (in the same 0 to 1
/// units) are given. The image is decoded once for all the picks. `None` when it can't be
/// decoded within [`MAX_RASTER_ALLOC`].
pub fn sample_pixels(&self, picks: &[PixelPick<'_>], budget: usize) -> Option<Vec<Vec<[u8; 4]>>> {
/// units) are given, and the function is called once for each pixel sampled. The image is
/// decoded once for all the picks. `None` when it can't be decoded within [`MAX_RASTER_ALLOC`].
pub fn sample_pixels(&self, picks: &[PixelPick<'_>]) -> Option<Vec<Vec<[u8; 4]>>> {
let img = rgba_within(&self.bytes, MAX_RASTER_ALLOC)?;
let (w, h) = img.dimensions();
let (fw, fh) = (f64::from(w), f64::from(h));
@@ -79,7 +79,7 @@ impl ImageBlob {
let (a, b) = (a.min(b), a.max(b));
((a * n).floor().clamp(0.0, n) as u32, (b * n).ceil().clamp(0.0, n) as u32)
};
let sample = |area: Option<[f64; 4]>, keep: &dyn Fn(f64, f64) -> bool| {
let sample = |area: Option<[f64; 4]>, budget: usize, keep: &dyn Fn(f64, f64) -> bool| {
let [u0, v0, u1, v1] = area.unwrap_or([0.0, 0.0, 1.0, 1.0]);
let (x0, x1) = span(u0, u1, fw);
let (y0, y1) = span(v0, v1, fh);
@@ -105,7 +105,7 @@ impl ImageBlob {
}
out
};
Some(picks.iter().map(|(area, keep)| sample(*area, *keep)).collect())
Some(picks.iter().map(|(area, budget, keep)| sample(*area, *budget, *keep)).collect())
}
/// The image as a grayscale PNG: `f` gives each pixel's gray level from its (straight) RGB, and
@@ -194,6 +194,27 @@ impl ImageBlob {
.collect();
Some((w, h, cover))
}
/// The pixels as straight RGBA, row by row from the top, with the width and the height;
/// `None` when the image can't be decoded within [`MAX_RASTER_ALLOC`].
pub fn rgba(&self) -> Option<(u32, u32, Vec<u8>)> {
let img = rgba_within(&self.bytes, MAX_RASTER_ALLOC)?;
let (w, h) = img.dimensions();
Some((w, h, img.into_raw()))
}
/// The width and height in pixels the image's file says it has; `None` for data that isn't an
/// image the decoder reads. Reads only its header.
pub fn pixel_size(&self) -> Option<(u32, u32)> {
image::ImageReader::new(Cursor::new(self.bytes.as_slice())).with_guessed_format().ok()?.into_dimensions().ok()
}
/// Whether the image's file is a PNG that stores palette indices (an indexed-color image).
/// Reads only its header.
pub fn indexed_png(&self) -> bool {
// The signature, then the IHDR chunk: length, type, width, height, bit depth, color type.
self.bytes.starts_with(b"\x89PNG\r\n\x1a\n") && self.bytes.get(12..16) == Some(b"IHDR".as_slice()) && self.bytes.get(25) == Some(&3)
}
}
impl ImageBlob {
@@ -266,6 +287,20 @@ impl ImageBlob {
Some(out)
}
/// Whether any pixel of the image is less than fully opaque. `false` when the image can't be
/// decoded. The last image decoded is kept, as for [`Self::sample`].
pub fn has_transparency(&self) -> bool {
self.decoded().is_some_and(|img| img.pixels().any(|p| p.0[3] < 255))
}
/// The alpha of each pixel, row by row from the top: the width, the height and one byte a
/// pixel. `None` when the image can't be decoded. The last image decoded is kept, as for
/// [`Self::sample`].
pub fn alpha(&self) -> Option<(u32, u32, Vec<u8>)> {
let img = self.decoded()?;
Some((img.width(), img.height(), img.pixels().map(|p| p.0[3]).collect()))
}
/// The decoded pixels (the last image decoded is kept for the next sample).
fn decoded(&self) -> Option<Arc<image::RgbaImage>> {
thread_local! {
@@ -331,7 +366,7 @@ mod tests {
let (r, b) = ([255, 0, 0, 255], [0, 0, 255, 255]);
let img = blob(&[r, r, b, b, r, r, b, b], 4, 2);
let any = |_: f64, _: f64| true;
let one = |b: &ImageBlob, area: Option<[f64; 4]>, budget: usize| b.sample_pixels(&[(area, &any)], budget).unwrap().remove(0);
let one = |b: &ImageBlob, area: Option<[f64; 4]>, budget: usize| b.sample_pixels(&[(area, budget, &any)]).unwrap().remove(0);
assert_eq!(one(&img, None, 100).len(), 8, "the budget covers every pixel");
assert_eq!(one(&img, Some([0.5, 0.0, 1.0, 1.0]), 100), vec![b; 4], "the right half");
assert_eq!(one(&img, Some([1.0, 1.0, 0.5, 0.0]), 100), vec![b; 4], "a box given backwards");
@@ -339,13 +374,15 @@ mod tests {
assert_eq!(one(&img, None, 2).len(), 2, "every second pixel of every second row");
assert_eq!(one(&img, None, 0), vec![r], "a budget of 0 counts as 1");
let left = |u: f64, _: f64| u < 0.5;
let both = img.sample_pixels(&[(None, &left), (Some([0.5, 0.0, 1.0, 1.0]), &any)], 100).unwrap();
let both = img.sample_pixels(&[(None, 100, &left), (Some([0.5, 0.0, 1.0, 1.0]), 100, &any)]).unwrap();
assert_eq!(both, vec![vec![r; 4], vec![b; 4]], "several picks, each with the centres its function takes");
let sizes: Vec<usize> = img.sample_pixels(&[(None, 2, &any), (None, 100, &any)]).unwrap().iter().map(Vec::len).collect();
assert_eq!(sizes, [2, 8], "each pick keeps to its own budget");
// A narrow image keeps to the budget too.
let tall = blob(&vec![r; 5000], 1, 5000);
let n = one(&tall, None, 100).len();
assert!((50..=100).contains(&n), "{n} pixels");
assert!(ImageBlob::png(b"not a png".to_vec()).sample_pixels(&[(None, &any)], 100).is_none());
assert!(ImageBlob::png(b"not a png".to_vec()).sample_pixels(&[(None, 100, &any)]).is_none());
}
/// A GIF whose `w` × `h` screen holds one opaque red pixel at the top left. The file holds no
+30 -1
View File
@@ -517,7 +517,12 @@ fn rename(n: &mut Node, prefix: &str) {
paint(&mut r.style.stroke);
}
}
NodeKind::Image(im) => im.key = format!("{prefix}{}", im.key),
NodeKind::Image(im) => {
im.key = format!("{prefix}{}", im.key);
if let Some(m) = n.extras.0.as_deref_mut().and_then(|e| e.color_mask.as_deref_mut()) {
(m.key, m.from) = (format!("{prefix}{}", m.key), format!("{prefix}{}", m.from));
}
}
NodeKind::PlacedDocument(p) => p.key = format!("{prefix}{}", p.key),
NodeKind::SymbolInstance { symbol, .. } => *symbol = format!("{prefix}{symbol}"),
_ => {}
@@ -681,6 +686,30 @@ mod tests {
Some((d, Node::new(NodeId(0), NodeKind::Group { children, clip: false }), Rect::new(0.0, 0.0, 40.0, 20.0)))
}
/// A color-masked image in a placed document's art keeps its masked pixels under the prefixed
/// names its resources get.
#[test]
fn a_color_mask_takes_the_prefixed_image_names() {
let im =
ImageObject { key: "own".into(), width: 2, height: 2, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None };
let mut n = Node::new(NodeId(7), NodeKind::Image(Box::new(im)));
n.extras_mut().color_mask = Some(Box::new(crate::color_mask::ColorMask {
key: "masked".into(),
from: "own".into(),
background: Default::default(),
colors: vec![],
contiguous: true,
measure: Default::default(),
tolerance: 10.0,
softness: 10.0,
}));
rename(&mut n, "p:");
let NodeKind::Image(im) = &n.kind else { panic!("an image") };
let m = Document::color_mask_of(&n).unwrap();
assert_eq!((im.key.as_str(), m.key.as_str(), m.from.as_str()), ("p:own", "p:masked", "p:own"));
assert!(m.made_for(im));
}
#[test]
fn round_trips_through_json() {
let n = Node::new(NodeId(3), NodeKind::PlacedDocument(Box::new(placed("doc1-1"))));
+19
View File
@@ -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();
+29
View File
@@ -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();
+533
View File
@@ -0,0 +1,533 @@
//! Separated images: an image whose inks come as one plate each (a DCS file placed linked), kept
//! as a TIFF of several images. The first is the composite, the plates mixed into CMYK
//! ([`Separated::composite`]), which every reader of a CMYK TIFF sees. Each later image is one
//! plate's ink amounts in grayscale (0 is no ink), with its ink's name and CMYK equivalent in its
//! ImageDescription. Print separations take each plate from these ([`Separated::coverage`]).
use std::io::Cursor;
use std::sync::Arc;
use vectorcraft_color::cms::PROCESS_PLATES;
use vectorcraft_geom::PathData;
use crate::ImageBlob;
use crate::cmyk::{Inks, MAX_CMYK_PIXELS};
/// Most plates a separated image holds.
pub const MAX_PLATES: usize = 64;
/// Most directories a separated image's TIFF holds: its composite and its plates.
const MAX_DIRECTORIES: usize = MAX_PLATES + 1;
/// Longest ink name kept (bytes).
pub const MAX_NAME: usize = 255;
/// Most ink amounts the plates of one image hold together (512 MB).
pub const MAX_SAMPLES: u64 = 1 << 29;
/// How a plate's ImageDescription starts.
const MARK: &str = "VectorCraft plate ";
/// How the composite's ImageDescription starts when plates were read from files of their own.
const FILES_MARK: &str = "VectorCraft plate files";
/// A plate file of its own that a separated image was read from, as it was then: a change to it
/// changes the image as a change to the DCS file does.
#[derive(Clone, Debug, PartialEq)]
pub struct PlateFile {
/// Its file name, in the DCS file's folder.
pub name: String,
/// Its size (bytes).
pub size: u64,
/// Its modification time (ms since the Unix epoch; 0 when the file system keeps none).
pub modified: u64,
}
/// `text` in hexadecimal (TIFF text is ASCII).
fn hex(text: &str) -> String {
text.bytes().map(|b| format!("{b:02x}")).collect()
}
/// The text [`hex`] wrote, of at most `max` bytes.
fn unhex(hex: &str, max: usize) -> Option<String> {
if !hex.len().is_multiple_of(2) || hex.len() > max * 2 {
return None;
}
let bytes: Option<Vec<u8>> = (0..hex.len()).step_by(2).map(|i| u8::from_str_radix(hex.get(i..i + 2)?, 16).ok()).collect();
String::from_utf8(bytes?).ok()
}
/// One ink's plate: its ink amounts, one byte a pixel (0 is none, 255 is solid), row by row from
/// the top.
#[derive(Clone, Debug, PartialEq)]
pub struct InkPlate {
/// "Cyan", "Magenta", "Yellow", "Black", or a spot ink's name.
pub name: String,
/// The process inks the ink stands for (C, M, Y, K, 0..1): one process ink at 100% for a
/// process plate.
pub cmyk: [f32; 4],
pub data: Vec<u8>,
}
impl InkPlate {
/// Is it a spot ink's plate (not one of the four process inks)?
pub fn spot(&self) -> bool {
!PROCESS_PLATES.contains(&self.name.as_str())
}
}
/// The plates of a separated image, all of one size.
#[derive(Clone, Debug, PartialEq)]
pub struct Separated {
pub width: u32,
pub height: u32,
pub plates: Vec<InkPlate>,
}
impl Separated {
/// `plates` as a `width` × `height` image; `None` when there are none or more than
/// [`MAX_PLATES`], two have the same name, a name is empty or longer than [`MAX_NAME`], a plate
/// doesn't hold that many pixels, an equivalent isn't within 0..1, or the image is empty, has
/// more than [`MAX_CMYK_PIXELS`], or its plates together hold more than [`MAX_SAMPLES`]
/// ([`Self::fits`]). A process plate's equivalent is its own ink.
pub fn new(width: u32, height: u32, mut plates: Vec<InkPlate>) -> Option<Self> {
let n = u64::from(width) * u64::from(height);
if !Self::fits(width, height, plates.len()) {
return None;
}
for p in plates.iter_mut() {
if p.name.is_empty() || p.name.len() > MAX_NAME || p.data.len() as u64 != n {
return None;
}
if let Some(j) = PROCESS_PLATES.iter().position(|q| *q == p.name) {
p.cmyk = [0.0; 4];
p.cmyk[j] = 1.0;
}
if !p.cmyk.iter().all(|v| (0.0..=1.0).contains(v)) {
return None;
}
}
let mut names = std::collections::HashSet::new();
if !plates.iter().all(|p| names.insert(p.name.as_str())) {
return None;
}
Some(Self { width, height, plates })
}
/// May an image of `width` × `height` pixels hold `plates` plates? Not when it is empty, has
/// more than [`MAX_CMYK_PIXELS`], has no plate or more than [`MAX_PLATES`], or the plates
/// together would hold more than [`MAX_SAMPLES`].
pub fn fits(width: u32, height: u32, plates: usize) -> bool {
let n = u64::from(width) * u64::from(height);
n > 0 && n <= MAX_CMYK_PIXELS && (1..=MAX_PLATES).contains(&plates) && n * plates as u64 <= MAX_SAMPLES
}
/// The plates of spot inks.
pub fn spots(&self) -> impl Iterator<Item = &InkPlate> {
self.plates.iter().filter(|p| p.spot())
}
/// The plates mixed into process inks: each plate's ink amount times its equivalent, the
/// plates over one another as inks print (`1 − (1 − a)(1 − b)` for each process ink).
pub fn composite(&self) -> Inks {
let n = self.data_len();
let mut data = vec![0u8; n * 4];
for (i, px) in data.as_chunks_mut::<4>().0.iter_mut().enumerate() {
let mut clear = [1.0f32; 4];
for p in &self.plates {
let t = f32::from(p.data[i]) / 255.0;
for (c, e) in clear.iter_mut().zip(p.cmyk) {
*c *= 1.0 - t * e;
}
}
for (o, c) in px.iter_mut().zip(clear) {
*o = ((1.0 - c) * 255.0).round() as u8;
}
}
Inks { width: self.width, height: self.height, data }
}
/// The ink amounts that print on plate `plate` (a process ink's name or a spot ink's), one byte
/// a pixel. A spot plate for which `own` is true prints on its own plate only; every other spot
/// plate (the job prints no plate of that name) prints as its process equivalent, mixed as
/// [`Self::composite`] mixes it. A plate name the image has no plate for, and a spot plate that
/// prints as process, print nothing.
pub fn coverage(&self, plate: &str, own: &dyn Fn(&str) -> bool) -> Vec<u8> {
self.coverage_as(plate, own, &|p| p.cmyk)
}
/// [`Self::coverage`], a spot plate that prints as process printing as the process inks
/// `equivalent` gives it (the document's swatch of its ink, when there is one).
pub fn coverage_as(&self, plate: &str, own: &dyn Fn(&str) -> bool, equivalent: &dyn Fn(&InkPlate) -> [f32; 4]) -> Vec<u8> {
let n = self.data_len();
if let Some(j) = PROCESS_PLATES.iter().position(|q| *q == plate) {
let mixed: Vec<(&InkPlate, f32)> = self
.plates
.iter()
.filter(|p| !p.spot() || !own(&p.name))
.map(|p| (p, if p.spot() { equivalent(p)[j].clamp(0.0, 1.0) } else { p.cmyk[j] }))
.filter(|(_, e)| *e > 0.0)
.collect();
return (0..n)
.map(|i| {
let clear = mixed.iter().fold(1.0f32, |c, (p, e)| c * (1.0 - f32::from(p.data[i]) / 255.0 * e));
((1.0 - clear) * 255.0).round() as u8
})
.collect();
}
match self.plates.iter().find(|p| p.name == plate && p.spot() && own(&p.name)) {
Some(p) => p.data.clone(),
None => vec![0; n],
}
}
/// [`Self::coverage_as`] as a grayscale PNG, black for solid ink and white for none, as a plate
/// prints; `None` when it can't be written.
pub fn plate_png(&self, plate: &str, own: &dyn Fn(&str) -> bool, equivalent: &dyn Fn(&InkPlate) -> [f32; 4]) -> Option<ImageBlob> {
let gray: Vec<u8> = self.coverage_as(plate, own, equivalent).into_iter().map(|v| 255 - v).collect();
let img = image::GrayImage::from_raw(self.width, self.height, gray)?;
let mut png = Vec::new();
img.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?;
Some(ImageBlob::png(png))
}
fn data_len(&self) -> usize {
self.width as usize * self.height as usize
}
}
/// A plate's ImageDescription: the mark, its equivalent and its name in hexadecimal (TIFF text is
/// ASCII).
fn description(p: &InkPlate) -> String {
let [c, m, y, k] = p.cmyk;
format!("{MARK}{c} {m} {y} {k} {}", hex(&p.name))
}
/// A plate's name and equivalent from its ImageDescription; `None` when it isn't one.
fn parse_description(s: &str) -> Option<(String, [f32; 4])> {
let rest = s.strip_prefix(MARK)?;
let mut words = rest.split(' ');
let mut cmyk = [0.0f32; 4];
for v in &mut cmyk {
*v = words.next()?.parse().ok().filter(|v: &f32| v.is_finite())?;
}
let name = unhex(words.next()?, MAX_NAME)?;
words.next().is_none().then_some((name, cmyk))
}
/// Longest plate file name kept (bytes).
const MAX_FILE_NAME: usize = 4096;
/// The composite's ImageDescription line for `files`: the mark, then each file's name in
/// hexadecimal, its size and its modification time.
fn files_description(files: &[PlateFile]) -> String {
let mut out = String::from(FILES_MARK);
for f in files.iter().take(MAX_PLATES) {
out.push_str(&format!(" {} {} {}", hex(&f.name), f.size, f.modified));
}
out
}
/// How the composite's ImageDescription line holding the clipping path starts.
const CLIP_MARK: &str = "VectorCraft clip ";
/// Longest clipping path kept (bytes of its JSON).
const MAX_CLIP: usize = 16 << 20;
/// The composite's ImageDescription line for clipping path `clip`: the mark, then the path's JSON
/// in hexadecimal; `None` when it is longer than [`MAX_CLIP`].
fn clip_description(clip: &PathData) -> Option<String> {
let json = serde_json::to_string(clip).ok().filter(|j| j.len() <= MAX_CLIP)?;
Some(format!("{CLIP_MARK}{}", hex(&json)))
}
/// The plate files of a composite's ImageDescription; none when it isn't one.
fn parse_files(s: &str) -> Vec<PlateFile> {
let Some(rest) = s.lines().find_map(|l| l.strip_prefix(FILES_MARK)) else { return vec![] };
let words: Vec<&str> = rest.split(' ').filter(|w| !w.is_empty()).collect();
let file =
|w: &[&str]| Some(PlateFile { name: unhex(w.first()?, MAX_FILE_NAME)?, size: w.get(1)?.parse().ok()?, modified: w.get(2)?.parse().ok()? });
words.chunks(3).take(MAX_PLATES).filter_map(file).collect()
}
impl ImageBlob {
/// A TIFF of separated image `s`: its composite in CMYK, then its plates (Deflate-compressed),
/// declaring the resolution `ppi` when it is given and both are finite and above 0, and noting
/// `files`, the plate files of their own the plates were read from ([`Self::plate_files`]);
/// `None` when it can't be written.
pub fn separated_tiff(s: &Separated, ppi: Option<(f64, f64)>, files: &[PlateFile]) -> Option<Self> {
Self::separated_tiff_clipped(s, ppi, files, None)
}
/// [`Self::separated_tiff`], noting `clip` too, the clipping path its file draws it through, in
/// its pixel space ([`Self::separated_clip`]).
pub fn separated_tiff_clipped(s: &Separated, ppi: Option<(f64, f64)>, files: &[PlateFile], clip: Option<&PathData>) -> Option<Self> {
use tiff::encoder::{Compression, Rational, TiffEncoder, colortype, compression::DeflateLevel};
use tiff::tags::{ResolutionUnit, Tag};
let ppi = 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 };
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::<colortype::CMYK8>(s.width, s.height).ok()?;
if let Some((x, y)) = ppi {
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()?;
}
// One line for the plate files, one for the clipping path.
let lines: Vec<String> =
[(!files.is_empty()).then(|| files_description(files)), clip.and_then(clip_description)].into_iter().flatten().collect();
if !lines.is_empty() {
img.encoder().write_tag(Tag::ImageDescription, lines.join("\n").as_str()).ok()?;
}
img.write_data(&s.composite().data).ok()?;
for p in &s.plates {
// White is no ink, so a viewer that shows a plate shows it as it prints.
let mut img = enc.new_image::<colortype::Gray8>(s.width, s.height).ok()?;
img.encoder().write_tag(Tag::ImageDescription, description(p).as_str()).ok()?;
let inverted: Vec<u8> = p.data.iter().map(|v| 255 - v).collect();
img.write_data(&inverted).ok()?;
}
Some(Self::new("image/tiff", out.into_inner()))
}
/// Does the image hold plates ([`ImageBlob::separated_tiff`]), at most [`MAX_PLATES`] of them?
/// One with more, or with more directories than its composite and [`MAX_PLATES`] plates, is the
/// CMYK image of its composite only, as [`Self::separated`] refuses it. Reads only the TIFF's
/// directories, at most [`MAX_DIRECTORIES`].
pub fn is_separated(&self) -> bool {
let Some((_, mut d)) = crate::cmyk::tiff(&self.bytes) else { return false };
let (mut plates, mut directories) = (0usize, 1usize);
while d.more_images() {
directories += 1;
if directories > MAX_DIRECTORIES || d.next_image().is_err() {
return false;
}
if d.get_tag_ascii_string(tiff::tags::Tag::ImageDescription).ok().is_some_and(|s| s.starts_with(MARK)) {
plates += 1;
if plates > MAX_PLATES {
return false;
}
}
}
plates > 0
}
/// The plate files of their own a separated image was read from, as they were then; none for
/// other images. Reads only the TIFF's first directory.
pub fn plate_files(&self) -> Vec<PlateFile> {
let Some((_, mut d)) = crate::cmyk::tiff(&self.bytes) else { return vec![] };
d.get_tag_ascii_string(tiff::tags::Tag::ImageDescription).ok().as_deref().map(parse_files).unwrap_or_default()
}
/// The clipping path a separated image's file draws it through, in its pixel space, as
/// [`Self::separated_tiff_clipped`] noted it; `None` for other images. Reads only the TIFF's
/// first directory.
pub fn separated_clip(&self) -> Option<PathData> {
let (_, mut d) = crate::cmyk::tiff(&self.bytes)?;
let text = d.get_tag_ascii_string(tiff::tags::Tag::ImageDescription).ok()?;
let json = unhex(text.lines().find_map(|l| l.strip_prefix(CLIP_MARK))?, MAX_CLIP)?;
serde_json::from_str(&json).ok()
}
/// The spot inks a separated image has plates for, each with its CMYK equivalent; none for
/// other images. Reads only the TIFF's directories.
pub fn spot_plates(&self) -> Vec<(String, [f32; 4])> {
if !self.is_separated() {
return vec![];
}
let Some((_, mut d)) = crate::cmyk::tiff(&self.bytes) else { return vec![] };
let mut inks = vec![];
while d.more_images() && inks.len() < MAX_PLATES {
if d.next_image().is_err() {
break;
}
let plate = d.get_tag_ascii_string(tiff::tags::Tag::ImageDescription).ok().as_deref().and_then(parse_description);
inks.extend(plate.filter(|(name, _)| !PROCESS_PLATES.contains(&name.as_str())));
}
inks
}
/// The plates of a separated image; `None` for other images, and ones whose plates can't be
/// read. The plates of the last image read are kept for the next call (print separates one
/// image plate after plate).
pub fn separated(&self) -> Option<Arc<Separated>> {
thread_local! {
static LAST: std::cell::RefCell<Option<(String, Arc<Separated>)>> = const { std::cell::RefCell::new(None) };
}
if !self.is_separated() {
return None;
}
let key = self.content_key();
LAST.with_borrow_mut(|last| match last {
Some((k, s)) if *k == key => Some(s.clone()),
_ => {
let s = Arc::new(read_plates(&self.bytes)?);
*last = Some((key, s.clone()));
Some(s)
}
})
}
}
/// The plates of TIFF `bytes`, each the size of its first image.
fn read_plates(bytes: &[u8]) -> Option<Separated> {
let (_, mut d) = crate::cmyk::tiff(bytes)?;
let (w, h) = d.dimensions().ok()?;
let n = usize::try_from(u64::from(w) * u64::from(h)).ok()?;
let mut plates = vec![];
// Every plate is read: a file with more than [`MAX_PLATES`] is refused ([`Separated::fits`]),
// not cut short, and so is one with more than [`MAX_DIRECTORIES`] directories.
let mut directories = 1usize;
while d.more_images() {
directories += 1;
if directories > MAX_DIRECTORIES {
return None;
}
d.next_image().ok()?;
let Some((name, cmyk)) = d.get_tag_ascii_string(tiff::tags::Tag::ImageDescription).ok().as_deref().and_then(parse_description) else {
continue;
};
// Checked before the plate is decoded.
if d.dimensions().ok()? != (w, h) || !matches!(d.colortype().ok()?, tiff::ColorType::Gray(8)) || !Separated::fits(w, h, plates.len() + 1) {
return None;
}
let data = crate::cmyk::read_samples(&mut d, n, 1)?.into_iter().map(|v| 255 - v).collect();
plates.push(InkPlate { name, cmyk, data });
}
Separated::new(w, h, plates)
}
#[cfg(test)]
mod tests {
use super::*;
fn plate(name: &str, cmyk: [f32; 4], data: &[u8]) -> InkPlate {
InkPlate { name: name.into(), cmyk, data: data.to_vec() }
}
/// Two pixels: cyan 100% and a spot ink at 50% on the first, nothing on the second.
fn two() -> Separated {
let plates = vec![plate("Cyan", [0.0; 4], &[255, 0]), plate("Spot Orange", [0.0, 0.6, 1.0, 0.0], &[128, 0])];
Separated::new(2, 1, plates).unwrap()
}
#[test]
fn plates_mix_into_the_composite_as_inks_print() {
let s = two();
assert_eq!(s.plates[0].cmyk, [1.0, 0.0, 0.0, 0.0], "a process plate stands for its own ink");
let c = s.composite();
// Magenta: 0.6 × 128/255; yellow: 128/255.
assert_eq!(&c.data[..4], &[255, 77, 128, 0]);
assert_eq!(&c.data[4..], &[0, 0, 0, 0]);
}
#[test]
fn a_spot_plate_prints_on_its_own_plate_or_as_process() {
let s = two();
let own = |_: &str| true;
assert_eq!(s.coverage("Spot Orange", &own), [128, 0]);
assert_eq!(s.coverage("Magenta", &own), [0, 0], "nothing of the spot on a process plate");
assert_eq!(s.coverage("Cyan", &own), [255, 0]);
assert_eq!(s.coverage("Black", &own), [0, 0]);
let process = |_: &str| false;
assert_eq!(s.coverage("Spot Orange", &process), [0, 0]);
assert_eq!(s.coverage("Magenta", &process), [77, 0]);
assert_eq!(s.coverage("Yellow", &process), [128, 0]);
assert_eq!(s.coverage("Other", &own), [0, 0]);
}
#[test]
fn the_tiff_keeps_every_plate_and_shows_the_composite() {
let s = two();
let files =
[PlateFile { name: "pic (1).C".into(), size: 1234, modified: 1_700_000_000_000 }, PlateFile { name: "ü.K".into(), size: 0, modified: 0 }];
let b = ImageBlob::separated_tiff(&s, Some((300.0, 300.0)), &files).unwrap();
assert_eq!(b.plate_files(), files);
assert!(ImageBlob::separated_tiff(&s, None, &[]).unwrap().plate_files().is_empty());
assert!(b.is_separated());
assert!(b.is_cmyk(), "readers of a CMYK TIFF see the composite");
assert_eq!(b.cmyk(), Some(s.composite()));
assert_eq!(*b.separated().unwrap(), s);
assert_eq!(b.spot_plates(), [("Spot Orange".to_string(), [0.0, 0.6, 1.0, 0.0])]);
assert!(ImageBlob::cmyk_tiff(&s.composite()).unwrap().spot_plates().is_empty());
assert!(!ImageBlob::cmyk_tiff(&s.composite()).unwrap().is_separated());
}
#[test]
fn the_tiff_keeps_the_clipping_path_beside_the_plate_files() {
let s = two();
let clip = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 1.5, 1.0));
let files = [PlateFile { name: "a.C".into(), size: 1, modified: 2 }];
let b = ImageBlob::separated_tiff_clipped(&s, None, &files, Some(&clip)).unwrap();
assert_eq!(b.separated_clip(), Some(clip.clone()));
assert_eq!(b.plate_files(), files);
let alone = ImageBlob::separated_tiff_clipped(&s, None, &[], Some(&clip)).unwrap();
assert_eq!(alone.separated_clip(), Some(clip));
assert!(alone.plate_files().is_empty());
assert_eq!(ImageBlob::separated_tiff(&s, None, &files).unwrap().separated_clip(), None);
}
#[test]
fn a_tiff_with_more_plates_than_are_read_is_refused() {
use tiff::encoder::{TiffEncoder, colortype};
let tiff = |plates: usize| {
let mut out = Cursor::new(Vec::new());
let mut enc = TiffEncoder::new(&mut out).unwrap();
enc.write_image::<colortype::CMYK8>(1, 1, &[0, 0, 0, 0]).unwrap();
for i in 0..plates {
let mut img = enc.new_image::<colortype::Gray8>(1, 1).unwrap();
img.encoder().write_tag(tiff::tags::Tag::ImageDescription, description(&plate(&format!("S{i}"), [0.0; 4], &[0])).as_str()).unwrap();
img.write_data(&[255]).unwrap();
}
ImageBlob::new("image/tiff", out.into_inner())
};
assert_eq!(tiff(MAX_PLATES).separated().map(|s| s.plates.len()), Some(MAX_PLATES));
let over = tiff(MAX_PLATES + 1);
assert!(over.separated().is_none(), "not cut short to the first {MAX_PLATES}");
assert!(!over.is_separated() && over.spot_plates().is_empty(), "the CMYK image of its composite only");
assert!(tiff(MAX_PLATES).is_separated());
}
#[test]
fn a_tiff_with_more_directories_than_a_composite_and_its_plates_is_refused() {
use tiff::encoder::{TiffEncoder, colortype};
let tiff = |others: usize| {
let mut out = Cursor::new(Vec::new());
let mut enc = TiffEncoder::new(&mut out).unwrap();
enc.write_image::<colortype::CMYK8>(1, 1, &[0, 0, 0, 0]).unwrap();
let mut img = enc.new_image::<colortype::Gray8>(1, 1).unwrap();
img.encoder().write_tag(tiff::tags::Tag::ImageDescription, description(&plate("S", [0.0; 4], &[0])).as_str()).unwrap();
img.write_data(&[255]).unwrap();
// Directories that are not plates.
for _ in 0..others {
enc.write_image::<colortype::Gray8>(1, 1, &[255]).unwrap();
}
ImageBlob::new("image/tiff", out.into_inner())
};
let most = tiff(MAX_PLATES - 1);
assert!(most.is_separated() && most.separated().is_some());
let over = tiff(MAX_PLATES);
assert!(!over.is_separated() && over.separated().is_none() && over.spot_plates().is_empty());
assert!(read_plates(&over.bytes).is_none(), "read_plates stops at the limit too");
}
#[test]
fn names_that_are_not_ascii_are_kept() {
let s = Separated::new(1, 1, vec![plate("Grün 100 % (A)", [0.5, 0.0, 1.0, 0.0], &[9])]).unwrap();
let b = ImageBlob::separated_tiff(&s, None, &[]).unwrap();
assert_eq!(b.separated().unwrap().plates[0].name, "Grün 100 % (A)");
}
#[test]
fn bad_plates_are_refused() {
assert!(Separated::new(2, 1, vec![]).is_none(), "no plates");
assert!(Separated::new(2, 1, vec![plate("Cyan", [0.0; 4], &[1])]).is_none(), "too few pixels");
assert!(Separated::new(1, 1, vec![plate("A", [0.0; 4], &[1]), plate("A", [0.0; 4], &[1])]).is_none(), "the same name twice");
assert!(Separated::new(1, 1, vec![plate("", [0.0; 4], &[1])]).is_none(), "no name");
assert!(Separated::new(1, 1, vec![plate("A", [2.0, 0.0, 0.0, 0.0], &[1])]).is_none(), "equivalent past 100%");
assert!(Separated::new(0, 1, vec![plate("A", [0.0; 4], &[])]).is_none(), "empty");
let many: Vec<InkPlate> = (0..=MAX_PLATES).map(|i| plate(&format!("S{i}"), [0.0; 4], &[1])).collect();
assert!(Separated::new(1, 1, many).is_none(), "too many plates");
assert!(Separated::fits(1 << 13, 1 << 13, 8), "512 MB of ink amounts");
assert!(!Separated::fits(1 << 13, 1 << 13, 9), "more than 512 MB together");
assert!(!Separated::fits(1 << 14, 1 << 13, 1), "more pixels than a CMYK image is decoded with");
}
}
+376
View File
@@ -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]]);
}
}
+169 -42
View File
@@ -5,7 +5,7 @@
//! tint (`Paint::Solid.swatch` / `.tint`, `GradientStop.swatch` / `.tint`); a tint swatch is a
//! swatch whose own paint links to its base that way. [`Document::map_solid_paints`] rewrites
//! those links (and colours) wherever art and swatches hold them, copying only the nodes that
//! change.
//! change; [`Document::map_paints`] replaces whole paints of any kind in the same places.
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
@@ -124,6 +124,52 @@ impl Document {
/// ([`Paint::map_links`]). Only nodes holding a changed paint (and the paths to them) are
/// copied. Returns the number of changed paints.
pub fn map_solid_paints(&mut self, f: &mut LinkFn) -> usize {
let mut n = self.map_art_paints(&mut relink(f));
for gs in &mut self.graphic_styles {
for it in &mut gs.appearance.items {
n += usize::from(item_paint_mut(it).map_links(f));
}
}
for w in self.swatches_iter_mut() {
n += usize::from(w.paint.map_links(f));
}
let mut g = relink(f);
for def in &mut self.char_styles {
for key in ["fill", "stroke"] {
n += usize::from(map_style_paint(&mut def.attrs, key, &mut g));
}
}
n
}
/// Visit every paint in the places [`Document::map_solid_paints`] visits (fills, strokes, text
/// runs, image colorize paints, dynamic symbol instances' own paints and graphs' stored series and
/// label paints in the art, opacity masks included, symbol definitions, graph designs, pattern tiles and the tile that pattern
/// editing's Cancel puts back; graphic styles; the swatches; character styles' fill and
/// stroke), whatever its kind. `f(paint)` gives the paint to put in its place, or `None` to keep
/// it. Only nodes holding a changed paint (and the paths to them) are copied. Returns the number
/// of changed paints.
pub fn map_paints(&mut self, f: &mut PaintFn) -> usize {
let mut n = self.map_art_paints(f);
for gs in &mut self.graphic_styles {
for it in &mut gs.appearance.items {
n += usize::from(replace_paint(item_paint_mut(it), f));
}
}
for w in self.swatches_iter_mut() {
n += usize::from(replace_paint(&mut w.paint, f));
}
for def in &mut self.char_styles {
for key in ["fill", "stroke"] {
n += usize::from(map_style_paint(&mut def.attrs, key, f));
}
}
n
}
/// [`Document::map_paints`] limited to the node trees: the art, symbol definitions, graph
/// designs, pattern tiles and the tile that pattern editing's Cancel puts back.
fn map_art_paints(&mut self, f: &mut PaintFn) -> usize {
let mut n = map_trees(&mut self.layers, f);
for s in &mut self.symbols {
n += map_tree(&mut s.art, f);
@@ -134,19 +180,6 @@ impl Document {
for p in self.patterns.iter_mut().chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut())) {
n += map_trees(&mut p.art, f);
}
for gs in &mut self.graphic_styles {
for it in &mut gs.appearance.items {
n += usize::from(item_paint_mut(it).map_links(f));
}
}
for w in self.swatches_iter_mut() {
n += usize::from(w.paint.map_links(f));
}
for def in &mut self.char_styles {
for key in ["fill", "stroke"] {
n += usize::from(map_style_paint(&mut def.attrs, key, f));
}
}
n
}
@@ -156,9 +189,10 @@ impl Document {
let roots: Vec<NodeId> =
ids.iter().copied().filter(|id| !self.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| ids.contains(p)))).collect();
let mut n = 0;
let mut g = relink(f);
for id in roots {
let Some(node) = self.node(id) else { continue };
if let Some((new, count)) = map_node(node, f)
if let Some((new, count)) = map_node(node, &mut g)
&& let Some(slot) = self.node_mut(id)
{
*slot = new;
@@ -176,7 +210,7 @@ impl Document {
pub fn visit_paints(&self, f: &mut dyn FnMut(&Paint)) {
let mut tree = |n: &Node| {
walk_with_masks(n, &mut |m| {
node_paints(m).chain(override_paints(m)).for_each(&mut *f);
node_paints(m).chain(override_paints(m)).chain(graph_paints(m)).for_each(&mut *f);
if let NodeKind::Mesh(mesh) = &m.kind {
mesh.points.iter().for_each(|p| f(&Paint::solid(p.color)));
}
@@ -258,14 +292,39 @@ impl FreeSwatchNames {
/// true when it changed them.
pub type LinkFn<'a> = dyn FnMut(&mut Color, &mut Option<String>, &mut f32) -> bool + 'a;
/// Apply `f` to the paint a character style's attribute `key` holds, as [`Paint::map_links`]
/// does, and store the result in the attribute. True when it changed.
fn map_style_paint(attrs: &mut serde_json::Map<String, serde_json::Value>, key: &str, f: &mut LinkFn) -> bool {
let Some(value) = attrs.get_mut(key) else { return false };
let Ok(mut paint) = serde_json::from_value::<Paint>(value.clone()) else { return false };
if !paint.map_links(f) {
return false;
/// What [`Document::map_paints`] applies to each paint: the paint to put in its place, or `None`
/// to keep it.
pub type PaintFn<'a> = dyn FnMut(&Paint) -> Option<Paint> + 'a;
/// `f` as a [`PaintFn`]: a solid or gradient paint with `f` applied ([`Paint::map_links`]) when
/// `f` changed it, `None` for every other paint.
fn relink<'a>(f: &'a mut LinkFn<'_>) -> impl FnMut(&Paint) -> Option<Paint> + 'a {
move |p| match p {
Paint::Solid { .. } | Paint::Gradient(_) => {
let mut q = p.clone();
q.map_links(f).then_some(q)
}
_ => None,
}
}
/// Put `f(p)` in place of `p` when it gives a paint. True when it did.
fn replace_paint(p: &mut Paint, f: &mut PaintFn) -> bool {
match f(p) {
Some(q) => {
*p = q;
true
}
None => false,
}
}
/// Apply `f` to the paint a character style's attribute `key` holds and store the result in the
/// attribute. An attribute that is not a paint stays as it is. True when it changed.
fn map_style_paint(attrs: &mut serde_json::Map<String, serde_json::Value>, key: &str, f: &mut PaintFn) -> bool {
let Some(value) = attrs.get_mut(key) else { return false };
let Ok(paint) = serde_json::from_value::<Paint>(value.clone()) else { return false };
let Some(paint) = f(&paint) else { return false };
match serde_json::to_value(&paint) {
Ok(changed) => {
*value = changed;
@@ -323,6 +382,28 @@ pub fn override_paints(n: &Node) -> impl Iterator<Item = &Paint> {
n.extras().symbol_overrides.iter().flat_map(|o| [o.fill.as_ref(), o.stroke.as_ref()]).flatten()
}
/// The paints a graph keeps for its series and its labels ([`crate::graph::GraphSpec`]), which its
/// marks and labels take each time it is drawn again and which [`node_paints`] leaves out.
pub fn graph_paints(n: &Node) -> impl Iterator<Item = &Paint> {
let g = n.extras().graph.as_deref();
let series = g.into_iter().flat_map(|g| &g.series_paints).flat_map(|s| [s.fill.as_ref(), s.stroke.as_ref()]).flatten();
let labels = g.into_iter().flat_map(|g| [&g.label_styles.values, &g.label_styles.categories, &g.label_styles.legend]).flatten();
let l = g.map(|g| &g.label_styles);
let rows = l.into_iter().flat_map(|l| [&l.values_rows, &l.categories_rows, &l.legend_rows]).flatten();
series.chain(labels.flat_map(|st| [&st.fill, &st.stroke])).chain(rows.flat_map(|r| [r.paint.fill.as_ref(), r.paint.stroke.as_ref()]).flatten())
}
/// Mutable [`graph_paints`] of graph `g`, in the same order.
fn graph_paints_mut(g: &mut crate::graph::GraphSpec) -> impl Iterator<Item = &mut Paint> {
let series = g.series_paints.iter_mut().flat_map(|s| [s.fill.as_mut(), s.stroke.as_mut()]).flatten();
let l = &mut g.label_styles;
let labels = [&mut l.values, &mut l.categories, &mut l.legend].into_iter().flatten();
let rows = [&mut l.values_rows, &mut l.categories_rows, &mut l.legend_rows].into_iter().flatten();
series
.chain(labels.flat_map(|st| [&mut st.fill, &mut st.stroke]))
.chain(rows.flat_map(|r| [r.paint.fill.as_mut(), r.paint.stroke.as_mut()]).flatten())
}
/// Mutable [`node_paints`], in the same order.
pub fn node_paints_mut(n: &mut Node) -> impl Iterator<Item = &mut Paint> {
let runs = match &mut n.kind {
@@ -333,20 +414,11 @@ pub fn node_paints_mut(n: &mut Node) -> impl Iterator<Item = &mut Paint> {
n.appearance.items.iter_mut().map(item_paint_mut).chain(runs.iter_mut().flat_map(|r| [&mut r.style.fill, &mut r.style.stroke])).chain(colorize)
}
/// `n` with `f` applied to its subtree's linkable colours, or `None` when nothing changed (then
/// nothing was copied). Also returns the number of changed paints.
fn map_node(n: &Node, f: &mut LinkFn) -> Option<(Node, usize)> {
// Try each own solid or gradient paint on a scratch copy first, so unchanged nodes are never
// cloned.
let mut changes: Vec<(usize, Paint)> = vec![];
for (i, p) in node_paints(n).enumerate() {
if matches!(p, Paint::Solid { .. } | Paint::Gradient(_)) {
let mut q = p.clone();
if q.map_links(f) {
changes.push((i, q));
}
}
}
/// `n` with `f` applied to its subtree's paints, or `None` when nothing changed (then nothing was
/// copied). Also returns the number of changed paints.
fn map_node(n: &Node, f: &mut PaintFn) -> Option<(Node, usize)> {
// `f` gives each own paint's replacement first, so unchanged nodes are never cloned.
let changes: Vec<(usize, Paint)> = node_paints(n).enumerate().filter_map(|(i, p)| f(p).map(|q| (i, q))).collect();
let mut count = changes.len();
let mut out: Option<Node> = None;
if !changes.is_empty() {
@@ -366,15 +438,29 @@ fn map_node(n: &Node, f: &mut LinkFn) -> Option<(Node, usize)> {
let mut overrides = n.extras().symbol_overrides.clone();
let mut k = 0;
for p in overrides.iter_mut().flat_map(|o| [&mut o.fill, &mut o.stroke]).flatten() {
if matches!(p, Paint::Solid { .. } | Paint::Gradient(_)) && p.map_links(f) {
k += 1;
}
k += usize::from(replace_paint(p, f));
}
if k > 0 {
out.get_or_insert_with(|| n.clone()).extras_mut().symbol_overrides = overrides;
count += k;
}
}
// A graph's series and label paints, which its marks and labels take when it is drawn again.
let graph: Vec<(usize, Paint)> = graph_paints(n).enumerate().filter_map(|(i, p)| f(p).map(|q| (i, q))).collect();
if !graph.is_empty() {
count += graph.len();
let m = out.get_or_insert_with(|| n.clone());
if let Some(spec) = m.extras_if_any().and_then(|e| e.graph.as_deref_mut()) {
let mut graph = graph.into_iter().peekable();
for (i, p) in graph_paints_mut(spec).enumerate() {
if graph.peek().is_some_and(|c| c.0 == i)
&& let Some((_, q)) = graph.next()
{
*p = q;
}
}
}
}
if let Some(ch) = n.children() {
for (i, c) in ch.iter().enumerate() {
if let Some((new, k)) = map_node(c, f) {
@@ -415,6 +501,13 @@ pub fn walk_with_masks<'a>(n: &'a Node, f: &mut dyn FnMut(&'a Node)) {
/// brush: `f` applied to the linkable colors of `n` and its subtree (opacity masks included). Only
/// the nodes holding a changed paint are copied. Returns the number of changed paints.
pub fn map_node_solid_paints(n: &mut Node, f: &mut LinkFn) -> usize {
map_node_paints(n, &mut relink(f))
}
/// [`Document::map_paints`] for art a document keeps outside its trees, such as the art of a brush:
/// `f` applied to every paint of `n` and its subtree (opacity masks included). Only the nodes
/// holding a changed paint are copied. Returns the number of changed paints.
pub fn map_node_paints(n: &mut Node, f: &mut PaintFn) -> usize {
match map_node(n, f) {
Some((new, count)) => {
*n = new;
@@ -424,7 +517,7 @@ pub fn map_node_solid_paints(n: &mut Node, f: &mut LinkFn) -> usize {
}
}
fn map_tree(n: &mut Arc<Node>, f: &mut LinkFn) -> usize {
fn map_tree(n: &mut Arc<Node>, f: &mut PaintFn) -> usize {
match map_node(n, f) {
Some((new, count)) => {
*n = Arc::new(new);
@@ -434,7 +527,7 @@ fn map_tree(n: &mut Arc<Node>, f: &mut LinkFn) -> usize {
}
}
fn map_trees(v: &mut [Arc<Node>], f: &mut LinkFn) -> usize {
fn map_trees(v: &mut [Arc<Node>], f: &mut PaintFn) -> usize {
v.iter_mut().map(|n| map_tree(n, f)).sum()
}
@@ -593,6 +686,40 @@ mod tests {
assert_eq!(map_node_solid_paints(&mut loose, &mut to_blue), 0, "nothing left to change");
}
#[test]
fn mapping_reaches_the_series_and_label_paints_a_graph_keeps() {
let (mut d, a, _) = doc();
let red = linked(Color::rgb(1.0, 0.0, 0.0), "Brand");
let spec = crate::graph::GraphSpec {
series_paints: vec![crate::SeriesPaint { fill: Some(red.clone()), stroke: Some(red.clone()), ..Default::default() }],
label_styles: crate::graph::LabelStyles {
legend: Some(crate::CharStyle { fill: red.clone(), stroke: Paint::None, ..Default::default() }),
values_rows: Some(crate::LabelRows {
paint: crate::SeriesPaint { fill: Some(red.clone()), ..Default::default() },
..Default::default()
}),
..Default::default()
},
..Default::default()
};
d.node_mut(a).unwrap().extras_mut().graph = Some(Box::new(spec));
let mut seen = 0;
d.visit_paints(&mut |p| seen += usize::from(*p == red));
assert_eq!(seen, 5, "the fill and the graph's series fill, series stroke, legend fill and value label fill row");
let blue = Color::rgb(0.0, 0.0, 1.0);
let mut to_blue = |c: &mut Color, s: &mut Option<String>, _: &mut f32| s.as_deref() == Some("Brand") && std::mem::replace(c, blue) != blue;
assert_eq!(d.map_solid_paints(&mut to_blue), 5);
let g = d.node(a).unwrap().extras().graph.clone().unwrap();
assert_eq!(g.series_paints[0].fill, Some(linked(blue, "Brand")));
assert_eq!(g.series_paints[0].stroke, Some(linked(blue, "Brand")));
let legend = g.label_styles.legend.unwrap();
assert_eq!((legend.fill, legend.stroke), (linked(blue, "Brand"), Paint::None));
assert_eq!(g.label_styles.values_rows.unwrap().paint.fill, Some(linked(blue, "Brand")));
let mut cleared = |p: &Paint| (*p == linked(blue, "Brand")).then_some(Paint::None);
assert_eq!(d.map_paints(&mut cleared), 5, "the fill and the graph's four");
assert!(graph_paints(d.node(a).unwrap()).all(Paint::is_none));
}
#[test]
fn mapping_within_ids_visits_each_paint_once() {
let (mut d, a, b) = doc();
+180 -30
View File
@@ -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)));
+15
View File
@@ -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
+4 -1
View File
@@ -17,7 +17,10 @@ mod wrap;
pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextFlow, TextWrap, VerticalAlign, WrapShape};
use char_style::yes;
pub use char_style::{CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, MAX_AKI, ScriptMetrics};
pub use char_style::{
CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, MAX_AKI, MAX_WARICHU_GAP, ScriptMetrics, WARICHU_LINES,
WARICHU_SCALE, WarichuAlign,
};
pub use composite::{
COMPOSITE_BASELINE, COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, COMPOSITE_SCALE, COMPOSITE_SIZE, CharClass, CompositeFont, CompositePart,
CompositeParts,
+112 -1
View File
@@ -145,6 +145,29 @@ pub struct CharStyle {
/// <https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html>
#[serde(default, rename = "standardVerticalRoman", skip_serializing_if = "crate::skip::is_default")]
pub standard_vertical_roman: bool,
/// Warichu (Character panel menu, East Asian options): these characters are set at
/// [`Self::warichu_scale`] percent of their size and stacked on [`Self::warichu_lines`] lines
/// inside their line, one above the other in horizontal type and side by side in vertical type.
/// A stretch of marked characters is one block that takes the settings of its first character
/// and stays whole on one line. Type on a path sets them at their own size on the path.
/// <https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html>
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
pub warichu: bool,
/// Warichu Settings › Lines: how many lines a warichu block is stacked on, within
/// [`WARICHU_LINES`]. Saved only when not 2.
#[serde(default = "two", rename = "warichuLines", skip_serializing_if = "is_two")]
pub warichu_lines: u8,
/// Warichu Settings › Line Gap, in points from 0 to [`MAX_WARICHU_GAP`]: the space between the
/// lines of a warichu block. Saved only when not 0.
#[serde(default, rename = "warichuGap", skip_serializing_if = "crate::skip::is_default")]
pub warichu_gap: f64,
/// Warichu Settings › Scale: the size of warichu characters as a percentage of their size,
/// within [`WARICHU_SCALE`]. Saved only when not 50.
#[serde(default = "fifty", rename = "warichuScale", skip_serializing_if = "is_fifty")]
pub warichu_scale: f64,
/// Warichu Settings › Alignment: how the lines of a warichu block line up along the block.
#[serde(default, rename = "warichuAlign", skip_serializing_if = "crate::skip::is_default")]
pub warichu_align: WarichuAlign,
/// Digits (Character panel menu, Middle Eastern options): the numeral system the digits of
/// these characters are drawn in, whatever digits were typed.
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
@@ -417,6 +440,82 @@ fn hundred() -> f64 {
/// The largest Insert Aki Left or Right ([`CharStyle::aki_left`]), in 1/1000 em: one em.
pub const MAX_AKI: f64 = 1000.0;
/// The number of lines a warichu block may be stacked on ([`CharStyle::warichu_lines`]).
pub const WARICHU_LINES: std::ops::RangeInclusive<u8> = 1..=6;
/// The largest Warichu Settings Line Gap ([`CharStyle::warichu_gap`]), in points.
pub const MAX_WARICHU_GAP: f64 = 100.0;
/// The Warichu Settings Scale ([`CharStyle::warichu_scale`]) range, in percent of the size.
pub const WARICHU_SCALE: std::ops::RangeInclusive<f64> = 10.0..=100.0;
fn two() -> u8 {
2
}
fn is_two(v: &u8) -> bool {
*v == 2
}
fn fifty() -> f64 {
50.0
}
fn is_fifty(v: &f64) -> bool {
*v == 50.0
}
/// How the lines of a warichu block line up along the block ([`CharStyle::warichu_align`]):
/// each line set flush left (top, in vertical type), centered or flush right (bottom), or spread
/// to the block's length with the last line set flush left, centered or flush right, or spread as
/// well. Auto is the default and sets the lines as [`WarichuAlign::JustifyLeft`] does.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum WarichuAlign {
#[default]
Auto,
Left,
Center,
Right,
JustifyLeft,
JustifyCenter,
JustifyRight,
JustifyAll,
}
impl WarichuAlign {
/// Every alignment, in the order Warichu Settings lists them.
pub const ALL: [WarichuAlign; 8] = [
WarichuAlign::Auto,
WarichuAlign::Left,
WarichuAlign::Center,
WarichuAlign::Right,
WarichuAlign::JustifyLeft,
WarichuAlign::JustifyCenter,
WarichuAlign::JustifyRight,
WarichuAlign::JustifyAll,
];
/// The name files and commands give this alignment (as it is saved).
pub fn id(self) -> &'static str {
match self {
WarichuAlign::Auto => "auto",
WarichuAlign::Left => "left",
WarichuAlign::Center => "center",
WarichuAlign::Right => "right",
WarichuAlign::JustifyLeft => "justifyLeft",
WarichuAlign::JustifyCenter => "justifyCenter",
WarichuAlign::JustifyRight => "justifyRight",
WarichuAlign::JustifyAll => "justifyAll",
}
}
/// The alignment [`WarichuAlign::id`] names; `None` for any other name.
pub fn from_id(id: &str) -> Option<WarichuAlign> {
WarichuAlign::ALL.into_iter().find(|a| a.id() == id)
}
}
pub(super) fn yes() -> bool {
true
}
@@ -464,6 +563,11 @@ impl Default for CharStyle {
tcy_up_down: 0.0,
tcy_left_right: 0.0,
standard_vertical_roman: false,
warichu: false,
warichu_lines: 2,
warichu_gap: 0.0,
warichu_scale: 50.0,
warichu_align: WarichuAlign::Auto,
small_caps: None,
digits: Digits::Default,
font_height_reference: FontHeightReference::EmBox,
@@ -484,7 +588,10 @@ impl CharStyle {
/// becomes the nearer end. A leading of 0, which legacy `.ai` import stores, stays, and a
/// baseline shift that is not a number becomes 0. The Tate-chu-yoko Up/Down and Left/Right
/// offsets are kept as the baseline shift is. Insert Aki Left and Right are kept from 0 to
/// [`MAX_AKI`], and one that is not a number becomes 0.
/// [`MAX_AKI`], and one that is not a number becomes 0. The Warichu Settings Lines and Scale
/// are kept to [`WARICHU_LINES`] and [`WARICHU_SCALE`]; a gap or scale that is not a number becomes its default. The gap is kept to 0 to
/// [`crate::MAX_COORD`], as the baseline shift is, since a scaled type object holds it in its
/// own units.
pub fn keep_dimensions_in_range(&mut self) {
let default = Self::default();
let within = |v: f64, or: f64| if v > 0.0 { v.min(crate::MAX_COORD) } else { or };
@@ -499,6 +606,10 @@ impl CharStyle {
let aki = |v: f64| if v.is_nan() { 0.0 } else { v.clamp(0.0, MAX_AKI) };
self.aki_left = aki(self.aki_left);
self.aki_right = aki(self.aki_right);
self.warichu_lines = self.warichu_lines.clamp(*WARICHU_LINES.start(), *WARICHU_LINES.end());
self.warichu_gap = if self.warichu_gap.is_nan() { default.warichu_gap } else { self.warichu_gap.clamp(0.0, crate::MAX_COORD) };
self.warichu_scale =
if self.warichu_scale.is_nan() { default.warichu_scale } else { self.warichu_scale.clamp(*WARICHU_SCALE.start(), *WARICHU_SCALE.end()) };
}
/// Do the characters draw a stroke (a paint and a positive weight)?
pub fn has_stroke(&self) -> bool {
+33 -3
View File
@@ -34,10 +34,19 @@ impl TextObject {
style.baseline_shift *= scale.points;
style.tcy_up_down *= scale.points;
style.tcy_left_right *= scale.points;
style.warichu_gap *= scale.points;
style.h_scale *= scale.horizontal;
if ![style.size, style.leading.unwrap_or(0.0), style.baseline_shift, style.tcy_up_down, style.tcy_left_right, style.h_scale]
.iter()
.all(|v| v.is_finite())
if ![
style.size,
style.leading.unwrap_or(0.0),
style.baseline_shift,
style.tcy_up_down,
style.tcy_left_right,
style.warichu_gap,
style.h_scale,
]
.iter()
.all(|v| v.is_finite())
{
return None;
}
@@ -114,6 +123,12 @@ impl TextObject {
pub fn plain_text(&self) -> String {
self.runs.iter().map(|r| r.text.as_str()).collect()
}
/// Does layout stack some of this type's characters as warichu ([`CharStyle::warichu`])? Not
/// on a path, which sets them as they are. Exports that write live text write such type as
/// outlines, as they do ruby: their text can't place the stacked lines.
pub fn stacks_warichu(&self) -> bool {
!matches!(self.kind, TextKind::OnPath { .. }) && self.runs.iter().any(|r| r.style.warichu && !r.text.is_empty())
}
/// Clamp the ruby spans to the plain text, drop empty/empty-reading ones and sort them.
///
/// Called after loading and editing text: ranges from a file or an edit are untrusted, and a
@@ -492,8 +507,23 @@ impl crate::Document {
st.tcy_left_right = num("tcyLeftRight").unwrap_or(st.tcy_left_right);
st.aki_left = num("akiLeft").unwrap_or(st.aki_left);
st.aki_right = num("akiRight").unwrap_or(st.aki_right);
st.warichu_gap = num("warichuGap").unwrap_or(st.warichu_gap);
st.warichu_scale = num("warichuScale").unwrap_or(st.warichu_scale);
st.keep_dimensions_in_range();
// Lines is a whole number: a stored number outside the range, or with a fraction,
// becomes the nearest whole number within it.
if let Some(old) = def.attrs.get_mut("warichuLines")
&& old.is_number()
&& old.as_u64().is_none_or(|v| !super::WARICHU_LINES.contains(&u8::try_from(v).unwrap_or(u8::MAX)))
{
let (lo, hi) = (*super::WARICHU_LINES.start(), *super::WARICHU_LINES.end());
let v = old.as_f64().filter(|v| v.is_finite()).map_or(2.0, |v| v.round().clamp(f64::from(lo), f64::from(hi)));
// Within 1..6 after the clamp, so the cast keeps the value.
*old = (v as u8).into();
}
let kept = [
("warichuGap", Some(st.warichu_gap)),
("warichuScale", Some(st.warichu_scale)),
("size", Some(st.size)),
("h_scale", Some(st.h_scale)),
("v_scale", Some(st.v_scale)),
+15
View File
@@ -508,6 +508,21 @@ pub enum Mojikumi {
/// Consecutive punctuation shares one half-em space (JLREQ 3.1.4), and a closing bracket,
/// comma or full stop ending a line is set half width.
LineEndHalf,
/// YakumonoHankaku: every opening and closing bracket, comma and full stop is set half width,
/// a middle dot loses a quarter em on each side, and a quarter em separates Japanese and Latin
/// letters or digits.
YakumonoHankaku,
/// GyomatsuYakumonoHankaku: punctuation keeps its full width, except that an opening bracket
/// starting a line is set flush with the line's start, a closing bracket, comma or full stop
/// ending a line is set half width and a middle dot ending a line loses the quarter em after
/// it; a quarter em separates Japanese and Latin letters or digits.
GyomatsuYakumonoHankaku,
/// GyomatsuYakumonoZenkaku: punctuation keeps its full width at a line's end too; a quarter em
/// separates Japanese and Latin letters or digits.
GyomatsuYakumonoZenkaku,
/// YakumonoZenkaku: punctuation keeps its full width, with no added space between Japanese and
/// Latin text.
YakumonoZenkaku,
}
impl Mojikumi {
+2 -1
View File
@@ -357,7 +357,7 @@ impl ParaList {
/// The style the marker is set in: `first` (the style of the paragraph's first character)
/// without its baseline shift, rotation, superscript or subscript, tracking, manual kerning,
/// Insert Aki, tate-chu-yoko, underline and strikethrough.
/// Insert Aki, tate-chu-yoko, warichu, underline and strikethrough.
pub fn marker_style(first: &CharStyle) -> CharStyle {
CharStyle {
baseline_shift: 0.0,
@@ -370,6 +370,7 @@ impl ParaList {
aki_right: 0.0,
optical_kerning: first.optical_kerning,
tate_chu_yoko: false,
warichu: false,
underline: false,
strikethrough: false,
..first.clone()
+49
View File
@@ -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");
}
+3
View File
@@ -15,6 +15,7 @@ vectorcraft-doc = { workspace = true }
vectorcraft-pathops = { workspace = true }
vectorcraft-text = { workspace = true }
vectorcraft-plugins = { workspace = true }
vectorcraft-trace = { workspace = true }
image = { workspace = true }
kurbo = { workspace = true }
# Effect › SVG Filters draws its filters with resvg (MIT OR Apache-2.0), at the usvg version the
@@ -28,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 }
+64 -7
View File
@@ -435,11 +435,19 @@ impl ColorVisitor for Live<'_, '_> {
/// adjustments of an object `n` is the art of) on everything it paints. The adjustment effects
/// are gone from the result; embedded images take the keys `images` gives. `swatches` tells the
/// document's global and spot swatches apart ([`crate::addons::duotone::swatch_kind`]).
pub fn adjust(n: &Node, outer: Option<&ColorMap>, swatches: &SwatchKinds, images: &mut ImageHook<'_>) -> Option<Node> {
/// `has_image` tells whether the document holds an image: an image whose color mask's pixels are
/// missing is recoloured from its own pixels, as it is drawn without the adjustment.
pub fn adjust(
n: &Node,
outer: Option<&ColorMap>,
swatches: &SwatchKinds,
images: &mut ImageHook<'_>,
has_image: &dyn Fn(&str) -> bool,
) -> Option<Node> {
let mut m: Option<Node> = None;
if let Some(ch) = n.children() {
for (i, c) in ch.iter().enumerate() {
if let Some(new) = adjust(c, None, swatches, images)
if let Some(new) = adjust(c, None, swatches, images, has_image)
&& let Some(slot) = m.get_or_insert_with(|| n.clone()).children_mut().and_then(|ch| ch.get_mut(i))
{
*slot = Arc::new(new);
@@ -462,11 +470,57 @@ pub fn adjust(n: &Node, outer: Option<&ColorMap>, swatches: &SwatchKinds, images
if let Some(map) = map {
let mm = m.get_or_insert_with(|| n.clone());
mm.appearance.effects.retain(|e| !is_adjustment(&e.id));
show_color_masks(mm, has_image);
recolor_node(mm, Reach::ALL, &mut Live { map: &map, swatches, images });
}
m
}
/// Whether `n` is an image that [`recolor_node`] recolours (embedded, not colorized, without
/// pixels of its own) with a color mask made from its pixels.
fn recoloured_with_mask(n: &Node) -> bool {
match (&n.kind, Document::color_mask_of(n)) {
(NodeKind::Image(im), Some(m)) => im.link.is_none() && n.extras().colorize.is_none() && m.made_for(im),
_ => false,
}
}
/// Whether `n` is or holds an image [`recoloured_with_mask`] counts.
fn holds_recoloured_with_mask(n: &Node) -> bool {
recoloured_with_mask(n) || n.children().is_some_and(|ch| ch.iter().any(|c| holds_recoloured_with_mask(c)))
}
/// Give each image in `n` that [`recoloured_with_mask`] counts its masked pixels as its own,
/// without the mask, so [`recolor_node`] recolours the pixels it shows and the colors the mask
/// hides stay hidden. An image whose masked pixels the document does not hold (`has_image`) is
/// drawn from its own pixels ([`Document::shown_image`]): it keeps its key and loses the mask, so
/// the recoloured copy is drawn the same way.
fn show_color_masks(n: &mut Node, has_image: &dyn Fn(&str) -> bool) {
if recoloured_with_mask(n)
&& let Some(masked) = Document::color_mask_of(n).map(|m| m.key.clone())
{
if let NodeKind::Image(im) = &mut n.kind
&& has_image(&masked)
{
im.key = masked;
}
n.extras_mut().color_mask = None;
}
for c in n.children_mut().into_iter().flatten() {
if holds_recoloured_with_mask(c) {
show_color_masks(Arc::make_mut(c), has_image);
}
}
}
/// The keys of the masked pixels of the color masks in `n` and its members.
fn color_mask_keys<'a>(n: &'a Node, out: &mut Vec<&'a str>) {
out.extend(Document::color_mask_of(n).map(|m| m.key.as_str()));
for c in n.children().into_iter().flatten() {
color_mask_keys(c, out);
}
}
/// [`adjust`] for export and Expand Appearance: recoloured embedded images become new images in
/// `d` (named by their content), and a symbol instance stands for its symbol's art: `symbol_art`
/// when given, otherwise the symbol's art with the instance's own appearance changes.
@@ -482,13 +536,16 @@ pub fn adjust_in_document(d: &mut Document, n: &Node, symbol_art: Option<Node>)
_ => n,
};
let kinds = crate::addons::duotone::swatch_kinds(d);
let mut masked = vec![];
color_mask_keys(src, &mut masked);
masked.retain(|k| d.images.contains_key(*k));
let mut hook = |key: &str, map: &ColorMap| -> Option<String> {
let blob = d.images.get(key)?.map_rgb(|rgb| map.apply_rgb8(rgb))?;
let k = blob.content_key();
d.images.entry(k.clone()).or_insert(blob);
Some(k)
};
adjust(src, None, &|name| kinds.get(name).copied(), &mut hook)
adjust(src, None, &|name| kinds.get(name).copied(), &mut hook, &|key| masked.contains(&key))
}
#[cfg(test)]
@@ -551,17 +608,17 @@ mod tests {
let mut g = Node::group(NodeId(1), vec![leaf(2), leaf(3)]);
g.appearance.effects.push(Effect { id: "adjust.hueSaturation".into(), params: json!({"hue": 120}), visible: true });
assert!(has_adjustment(&g));
let out = adjust(&g, None, &|_| None, &mut |_, _| None).unwrap();
let out = adjust(&g, None, &|_| None, &mut |_, _| None, &|_| true).unwrap();
assert!(out.appearance.effects.is_empty());
for c in out.children().unwrap() {
assert_eq!(c.appearance.fill_paint().color().unwrap().to_hex(), "#00ff00");
}
// A hidden effect does nothing; a stroke's own effect recolours just that stroke.
g.appearance.effects[0].visible = false;
assert!(!has_adjustment(&g) && adjust(&g, None, &|_| None, &mut |_, _| None).is_none());
assert!(!has_adjustment(&g) && adjust(&g, None, &|_| None, &mut |_, _| None, &|_| true).is_none());
let mut p = Node::path(NodeId(5), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art());
p.appearance.items[1].effects_mut().push(Effect { id: "adjust.levels".into(), params: json!({"outputBlack": 255}), visible: true });
let out = adjust(&p, None, &|_| None, &mut |_, _| None).unwrap();
let out = adjust(&p, None, &|_| None, &mut |_, _| None, &|_| true).unwrap();
assert_eq!(out.appearance.items[1].paint().color().unwrap().to_hex(), "#ffffff");
assert_eq!(out.appearance.items[0].paint(), p.appearance.items[0].paint());
assert!(out.appearance.items[1].effects().is_empty());
@@ -576,7 +633,7 @@ mod tests {
let fill = Appearance::basic(Paint::Gradient(Box::new(gp)), Paint::None, 0.0);
let mut p = Node::path(NodeId(1), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), fill);
p.appearance.effects.push(Effect { id: "adjust.hueSaturation".into(), params: json!({"hue": 120}), visible: true });
let out = adjust(&p, None, &|_| None, &mut |_, _| None).unwrap();
let out = adjust(&p, None, &|_| None, &mut |_, _| None, &|_| true).unwrap();
let Paint::Gradient(g) = out.appearance.fill_paint() else { panic!("a gradient fill") };
// The points are what a freeform gradient draws from, not its stops.
let hexes: Vec<String> = g.freeform.as_ref().unwrap().points.iter().map(|p| p.color.to_hex()).collect();
+10 -5
View File
@@ -83,15 +83,17 @@ fn apply(effects: &[vectorcraft_doc::Effect], path: &PathData, ctx: &GeomContext
/// The geometry `g` with the own effects of `item` (one of the fills and strokes `ctx` is the
/// context of) applied, and `carried` (`item` as the object's effects left it) with its gradient
/// moved along with them.
/// moved along with them and the Transform effects the geometry pass left out hidden
/// ([`crate::Carry::hide_skipped`]).
fn apply_item(item: &AppearanceItem, carried: &AppearanceItem, g: &PathData, ctx: &GeomContext) -> (PathData, AppearanceItem) {
let (ig, carry) = apply(item_effects(item), g, &ctx.item(item));
let mut ap = Appearance { items: vec![carried.clone()], ..Default::default() };
if !carry.moves(&ap) {
return (ig, carried.clone());
if carry.moves(&ap) {
carry.apply(&mut ap);
}
carry.apply(&mut ap);
(ig, ap.items.pop().unwrap_or_else(|| carried.clone()))
let mut out = ap.items.pop().unwrap_or_else(|| carried.clone());
carry.hide_skipped(out.effects_mut());
(ig, out)
}
/// A path node of `kind`'s flavour (compound when the result has several subpaths).
@@ -424,6 +426,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));
@@ -468,6 +472,7 @@ fn leaf_base(n: &Node) -> Option<(PathData, FillRule, GeomContext<'_>, Node)> {
if carry.moves(&m.appearance) {
carry.apply(&mut m.appearance);
}
carry.hide_skipped(&mut m.appearance.effects);
// The raster effects of its fills and strokes follow its Transform effects, as on the canvas.
crate::raster::follow_items(&mut m);
m.appearance.effects = crate::raster::without_geometry(&m.appearance.effects);
+3 -3
View File
@@ -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,
@@ -296,7 +296,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
"path.outlineObject",
"Outline Object",
PATH,
"{} type is drawn, exported and expanded as its glyph outlines and stays editable, and the effects after it reshape those outlines; paths and images do not change",
"{} type is drawn, exported and expanded as its glyph outlines and stays editable, and the effects after it reshape those outlines; paths and images do not change. On an image's own fill or stroke it gives the outline of the image's pixels that are at least half opaque (VectorCraft's own cutoff), and nothing when no pixel is; it gives the image's frame when the image has no transparency, its pixels can't be read, or the image or its outline is too large to trace",
json!({}),
),
g(
+205 -1
View File
@@ -1,7 +1,8 @@
//! The region a clip group clips to ([`Node::clip_outline`]) with text outlined by the font engine
//! and several shapes united, so the renderer and the SVG and PDF writers clip alike.
use vectorcraft_doc::{Appearance, Node, NodeKind};
use vectorcraft_doc::color::{Color, Paint};
use vectorcraft_doc::{Appearance, Document, Node, NodeKind};
use vectorcraft_geom::{BezPath, FillRule, PathData};
/// The clipping path `clip` of a clip group as one path and fill rule: compound paths keep their
@@ -11,6 +12,209 @@ pub fn clip_outline(clip: &Node) -> Option<(BezPath, FillRule)> {
clip.clip_outline(Some(&outline_text), &unite)
}
/// The knockout shape of a piece of a mesh-warped image ([`Node::knockout_outline`]) painted opaque
/// in `color`, which the SVG and PDF writers put in their knockout masks: for a clip group, a
/// rectangle clipped by the same clipping path (so a viewer covers the same pixels of its edges as
/// when it clips the piece), else the path of its opacity mask's art, filled. `None` for other
/// objects and for a piece with nothing to clip by.
pub fn knockout_silhouette(n: &Node, color: Color) -> Option<Node> {
let outline = n.knockout_outline()?;
let (bp, rule) = clip_outline(outline)?;
let paint = Appearance::basic(Paint::solid(color), Paint::None, 0.0);
if n.clips() && n.extras().mask.is_none() {
let cover = Node::path(n.id, vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Shape::bounding_box(&bp).inflate(1.0, 1.0)), paint);
let children = vec![outline.clone(), std::sync::Arc::new(cover)];
return Some(Node::new(n.id, NodeKind::Group { children, clip: true }));
}
let mut p = Node::path(n.id, PathData::from_bezpath(&bp), paint);
if let NodeKind::Path { rule: r, .. } = &mut p.kind {
*r = rule;
}
Some(p)
}
/// Whether any of `pieces`, pieces of a mesh-warped image ([`Node::warp_piece_image`]), paints less
/// than opaque anywhere inside its triangle: it or its image is partly transparent, a color mask
/// clears some of its colors, a colorize paint draws its light pixels partly transparent, or the
/// pixels of its image (looked up in `doc`) are. Each distinct
/// image's pixels are scanned once. Pieces of an opaque image overlap without showing it, so the SVG
/// and PDF writers draw them one over another without masks.
pub fn warp_pieces_translucent(doc: &Document, pieces: &[&Node]) -> bool {
let mut scanned: Vec<*const vectorcraft_doc::ImageBlob> = vec![];
for n in pieces {
let Some(image) = n.warp_piece_image() else { continue };
let NodeKind::Image(im) = &image.kind else { continue };
let e = image.extras();
if n.opacity < 1.0 || image.opacity < 1.0 || e.color_mask.is_some() || e.colorize.is_some() {
return true;
}
let Some(blob) = doc.image_blob(im) else { continue };
if scanned.contains(&std::ptr::from_ref(blob)) {
continue;
}
scanned.push(std::ptr::from_ref(blob));
if blob.has_transparency() {
return true;
}
}
false
}
/// Which overlaps of the pieces of a mesh-warped image ([`Node::warp_piece_image`]) can show
/// through. Where an upper piece overlaps a lower one only over fully opaque pixels of the image,
/// the SVG and PDF writers draw the upper piece over the lower one without a knockout mask for it:
/// a mask there would make the opaque pixels on the upper piece's antialiased edge lighter.
pub struct WarpSeams {
pieces: Vec<Option<SeamPiece>>,
alphas: Vec<(u32, u32, Vec<u8>)>,
}
/// A piece of a mesh-warped image whose pixels decide whether its overlaps show through.
struct SeamPiece {
/// The piece's triangle, in document space.
triangle: [vectorcraft_geom::Point; 3],
/// Maps document space to the pixels of its image as decoded.
to_pixels: vectorcraft_geom::Affine,
/// The index of its image's alpha in [`WarpSeams::alphas`].
alpha: usize,
}
/// How far from an overlap, in image pixels, a less than opaque pixel makes the overlap show
/// through: a smoothed image blends each pixel with its neighbors.
const SEAM_MARGIN: f64 = 2.0;
impl WarpSeams {
/// The overlaps of `pieces` (pieces of a mesh-warped image, in paint order), with the pixels of
/// their images looked up in `doc`. Each distinct image is decoded once.
pub fn new(doc: &Document, pieces: &[&Node]) -> Self {
let mut images: Vec<*const vectorcraft_doc::ImageBlob> = vec![];
let mut alphas = vec![];
let pieces = pieces
.iter()
.map(|n| {
let image = n.warp_piece_image()?;
let NodeKind::Image(im) = &image.kind else { return None };
let e = image.extras();
if n.opacity < 1.0 || image.opacity < 1.0 || e.color_mask.is_some() || e.colorize.is_some() {
return None;
}
let triangle = triangle(n.knockout_outline()?)?;
let blob = doc.image_blob(im)?;
let alpha = match images.iter().position(|b| std::ptr::eq(*b, blob)) {
Some(i) => i,
None => {
alphas.push(blob.alpha()?);
images.push(std::ptr::from_ref(blob));
alphas.len() - 1
}
};
let (w, h, _) = &alphas[alpha];
if im.width == 0 || im.height == 0 || im.xf.determinant().abs() < 1e-12 {
return None;
}
let scale = vectorcraft_geom::Affine::scale_non_uniform(f64::from(*w) / f64::from(im.width), f64::from(*h) / f64::from(im.height));
Some(SeamPiece { triangle, to_pixels: scale * im.xf.inverse(), alpha })
})
.collect();
WarpSeams { pieces, alphas }
}
/// Whether piece `above` (an index into the pieces) drawn over piece `below` can show the
/// lower piece through where they overlap: either piece or its image is partly transparent, a
/// color mask or a colorize paint changes its alpha, or a pixel of either image within
/// [`SEAM_MARGIN`] of the overlap is less than opaque. `true` for a piece that is not a
/// triangle of an image that can be decoded; `false` when the triangles do not overlap.
pub fn shows_through(&self, below: usize, above: usize) -> bool {
let (Some(Some(a)), Some(Some(b))) = (self.pieces.get(below), self.pieces.get(above)) else { return true };
let overlap = convex_intersection(&a.triangle, &b.triangle);
overlap.len() >= 3 && [a, b].into_iter().any(|p| self.translucent_near(p, &overlap))
}
/// Whether a pixel of piece `p`'s image within [`SEAM_MARGIN`] of the convex polygon `overlap`
/// (document space) is less than opaque.
fn translucent_near(&self, p: &SeamPiece, overlap: &[vectorcraft_geom::Point]) -> bool {
let Some((w, h, alpha)) = self.alphas.get(p.alpha) else { return true };
let poly: Vec<vectorcraft_geom::Point> = overlap.iter().map(|q| p.to_pixels * *q).collect();
let (mut x0, mut y0, mut x1, mut y1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
for q in &poly {
(x0, y0, x1, y1) = (x0.min(q.x), y0.min(q.y), x1.max(q.x), y1.max(q.y));
}
let span = |lo: f64, hi: f64, n: u32| {
let lo = (lo - SEAM_MARGIN).floor().clamp(0.0, f64::from(n)) as u32;
let hi = (hi + SEAM_MARGIN).ceil().clamp(0.0, f64::from(n)) as u32;
lo..hi
};
let orientation = signed_area(&poly).signum();
for y in span(y0, y1, *h) {
for x in span(x0, x1, *w) {
let c = vectorcraft_geom::Point::new(f64::from(x) + 0.5, f64::from(y) + 0.5);
let near = poly.iter().zip(poly.iter().cycle().skip(1)).all(|(s, e)| {
let edge = *e - *s;
orientation * edge.cross(c - *s) >= -SEAM_MARGIN * edge.hypot()
});
let i = y as usize * *w as usize + x as usize;
if near && alpha.get(i).is_none_or(|a| *a < 255) {
return true;
}
}
}
false
}
}
/// The three corners of the straight-sided triangle `outline` draws, in document space.
fn triangle(outline: &Node) -> Option<[vectorcraft_geom::Point; 3]> {
let (bp, _) = clip_outline(outline)?;
let mut points = vec![];
for el in bp.elements() {
match el {
vectorcraft_geom::PathEl::MoveTo(p) | vectorcraft_geom::PathEl::LineTo(p) if points.is_empty() || points.last() != Some(p) => {
points.push(*p)
}
vectorcraft_geom::PathEl::MoveTo(_) | vectorcraft_geom::PathEl::LineTo(_) | vectorcraft_geom::PathEl::ClosePath => {}
_ => return None,
}
}
if points.len() == 4 && points.first() == points.last() {
points.pop();
}
let [a, b, c] = points.as_slice() else { return None };
Some([*a, *b, *c])
}
/// Twice the signed area of polygon `poly`.
fn signed_area(poly: &[vectorcraft_geom::Point]) -> f64 {
poly.iter().zip(poly.iter().cycle().skip(1)).map(|(a, b)| a.to_vec2().cross(b.to_vec2())).sum()
}
/// The intersection of convex polygons `subject` and `clip`, as a convex polygon (empty when they
/// do not overlap).
fn convex_intersection(subject: &[vectorcraft_geom::Point], clip: &[vectorcraft_geom::Point]) -> Vec<vectorcraft_geom::Point> {
let orientation = signed_area(clip).signum();
if orientation == 0.0 {
return vec![];
}
let mut out = subject.to_vec();
for (s, e) in clip.iter().zip(clip.iter().cycle().skip(1)) {
let edge = *e - *s;
let side = |p: vectorcraft_geom::Point| orientation * edge.cross(p - *s);
let input = std::mem::take(&mut out);
for (p, q) in input.iter().zip(input.iter().cycle().skip(1)) {
let (sp, sq) = (side(*p), side(*q));
if sp >= 0.0 {
out.push(*p);
}
if (sp >= 0.0) != (sq >= 0.0) {
out.push(*p + (*q - *p) * (sp / (sp - sq)));
}
}
if out.is_empty() {
break;
}
}
out
}
/// Text as one path of its glyph outlines, in document space.
fn outline_text(n: &Node) -> Option<Node> {
let NodeKind::Text(t) = &n.kind else { return None };
+37 -2
View File
@@ -200,8 +200,12 @@ pub fn apply_geometry_bez_carrying(effects: &[Effect], path: &BezPath, bounds: R
/// it unevenly (a map after which a refit would not match the mapped gradient): it is fixed to its
/// fit on the geometry that effect takes, and then follows that effect and the ones after it as a
/// placed gradient does.
///
/// It also lists the visible Transform effects that move the art once and that the pass left out,
/// their results past the budget, by their index in the effect list it was given: the raster
/// effects before such an effect stay as they are, as the art does ([`Self::hide_skipped`]).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Carry(Vec<CarryStep>);
pub struct Carry(Vec<CarryStep>, Vec<usize>);
/// Does `m` fix a gradient fitted to the object to its fit before mapping it? It does when a refit
/// would not reproduce the map (a turn, a reflection or an uneven scale) and `m` keeps area: a map
@@ -265,7 +269,7 @@ impl Carry {
_ => None,
},
};
Carry(step.into_iter().collect())
Carry(step.into_iter().collect(), vec![])
}
/// Does it leave gradients where they are?
@@ -310,6 +314,30 @@ impl Carry {
pub(crate) fn push(&mut self, more: Carry) {
self.0.extend(more.0);
self.1.extend(more.1);
}
/// Did the pass leave out a Transform effect that moves the art once ([`Self::hide_skipped`])?
pub fn skipped(&self) -> bool {
!self.1.is_empty()
}
/// Hide each Transform effect of `effects`, the list the pass was given, that it left out (its
/// result past the budget): the art stays where it was, so the raster effects listed before it
/// do not follow it ([`crate::raster::followed`]). Other effects stay as they are.
pub fn hide_skipped(&self, effects: &mut [Effect]) {
for &i in &self.1 {
if let Some(e) = effects.get_mut(i).filter(|e| e.id == "distort.transform") {
e.visible = false;
}
}
}
/// Note that the Transform effect at index `i` of the pass's list was left out.
pub(crate) fn skip(&mut self, i: usize) {
if !self.1.contains(&i) {
self.1.push(i);
}
}
}
@@ -354,6 +382,13 @@ pub(crate) fn apply_geometry_carrying_within(
c.push(Carry::of(&e.id, &p, b, cur.bounds(), next.bounds(), ctx.seed));
}
cur = next;
} else if let Some(c) = carry.as_deref_mut()
&& e.id == "distort.transform"
&& !crate::raster::holds_back(e)
&& let Some(i) = effects.iter().position(|x| std::ptr::eq(x, e))
{
// The raster effects before it stay as the art does.
c.skip(i);
}
}
cur
+95 -3
View File
@@ -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) {
@@ -258,8 +261,17 @@ fn reshaped(src: &Node, n: &Node, doc: Option<&Document>) -> Node {
carry.apply(&mut m.appearance);
}
// So do the raster effects of its fills and strokes, by `n`'s Transform effects
// ([`crate::follow_items`]).
crate::raster::follow_items_of(&mut m, &n.appearance.effects);
// ([`crate::follow_items`]) that moved the outline.
let mut owner = std::borrow::Cow::Borrowed(n.appearance.effects.as_slice());
if carry.skipped() {
carry.hide_skipped(owner.to_mut());
if m.appearance.effects == n.appearance.effects {
let mut ap = (*m.appearance).clone();
ap.effects = owner.to_vec();
m.appearance = ap.into();
}
}
crate::raster::follow_items_of(&mut m, &owner);
}
without_geometry_effects(&mut m);
m
@@ -754,7 +766,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 +803,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 +835,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;
+292
View File
@@ -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.
+5 -4
View File
@@ -69,7 +69,7 @@ pub use adjust::{
is_channel,
};
pub use bake::{StrokeArt, bake_appearance, bake_document, bake_type_appearance, expand_art, expand_leaf, fresh_ids, needs_bake};
pub use clip::clip_outline;
pub use clip::{WarpSeams, clip_outline, knockout_silhouette, warp_pieces_translucent};
pub use group::{
OutlineHook, PATHFINDER_EFFECTS, compound_shape_area, compound_shape_art, evaluate_container, has_container_appearance, has_pathfinder,
is_pathfinder, member_leaves, member_shapes, paints, pathfinder_children, shape_art,
@@ -80,8 +80,8 @@ pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks};
pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace};
pub use raster::{RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, without_geometry};
pub use reshape::{
SYMBOL_ART_MAX_NODES, expand_outlined, gives_image_shape, has_gradient_copies, has_item_geometry, has_painted_effects, has_transform_art,
has_transform_copies, has_transform_options, image_paint, needs_outline, outline_art, outline_text, reshape,
SYMBOL_ART_MAX_NODES, expand_outlined, follows_image_pixels, gives_image_shape, has_gradient_copies, has_item_geometry, has_painted_effects,
has_transform_art, has_transform_copies, has_transform_options, image_paint, needs_outline, outline_art, outline_text, reshape,
};
pub use revolve::{
CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in,
@@ -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;
+15 -5
View File
@@ -96,6 +96,18 @@ pub(crate) fn rgb_gradient_art(
composed_art(id, path, paint, Ramp::Rgb(light), 0.75)
}
/// The narrow stroke of a facet's own `paint`, `width` wide, that closes the hairline seam between
/// it and its neighbors where each is antialiased alone. Its joins are round: a facet seen almost
/// edge-on is a sharp sliver, and a mitered seam would reach far past its tip as a thorn, where a
/// round one reaches no more than half its width past the facet. Revolve's meets() counts on a
/// stroked seam reaching no more than half its width; faces drawn as clipped groups (whose clip,
/// in `composed_art`, already outlines the seam with round joins) are measured by their box.
pub(crate) fn seam_stroke(paint: Paint, width: f64) -> vectorcraft_doc::StrokeLayer {
let mut edge = vectorcraft_doc::StrokeLayer::new(paint, width);
edge.join = vectorcraft_doc::LineJoin::Round;
edge
}
/// Smooth Inflate triangles keep the seam within their narrow projected footprint.
pub(crate) fn facet_art(
id: vectorcraft_doc::NodeId,
@@ -109,8 +121,7 @@ pub(crate) fn facet_art(
let light = vectorcraft_three_d::LightGradient { diffuse: r, ambient: 0.0, color: [1.0; 3] };
if let Some(color) = paint.color() {
let paint = smooth_paint(light, color);
let mut edge = vectorcraft_doc::StrokeLayer::new(paint.clone(), seam);
edge.join = vectorcraft_doc::LineJoin::Round;
let edge = seam_stroke(paint.clone(), seam);
return vectorcraft_doc::Node::path(
id,
path.clone(),
@@ -131,7 +142,7 @@ pub(crate) fn solid_surface(id: vectorcraft_doc::NodeId, facets: &[vectorcraft_t
use kurbo::Shape;
use std::sync::Arc;
use vectorcraft_doc::color::BlendMode;
use vectorcraft_doc::{Appearance, Node, NodeKind, StrokeLayer};
use vectorcraft_doc::{Appearance, Node, NodeKind};
use vectorcraft_geom::{BezPath, PathData, Rect, shapes};
let mut boundary = BezPath::new();
@@ -163,8 +174,7 @@ pub(crate) fn solid_surface(id: vectorcraft_doc::NodeId, facets: &[vectorcraft_t
} else {
Paint::solid(shade(Color::WHITE, color.map(|c| c * face.illumination[channel])))
};
let mut edge = StrokeLayer::new(paint.clone(), (face.thickness() / 2.0).clamp(0.05, 0.75));
edge.join = vectorcraft_doc::LineJoin::Round;
let edge = seam_stroke(paint.clone(), (face.thickness() / 2.0).clamp(0.05, 0.75));
Arc::new(Node::path(
id,
face.path(),
+601 -109
View File
@@ -10,12 +10,13 @@
//! inline graphics whose own fills or strokes have geometry effects is outlined too: each of those
//! effects reshapes the whole outline that its fill or stroke paints. An image's own fills and
//! strokes paint only the shape that a Convert to Shape or Outline Object effect on them gives
//! them ([`image_rows`]).
//! them ([`image_rows`]): Outline Object follows the outline of the image's opaque area
//! ([`opaque_area`]).
use std::collections::{HashMap, HashSet};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::rc::Rc;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, OnceLock, PoisonError, Weak};
use vectorcraft_doc::live::Hooks;
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, ImageObject, Node, NodeId, NodeKind};
@@ -287,8 +288,8 @@ pub fn gives_image_shape(effects: &[Effect]) -> bool {
/// The fills and strokes of `items` (an image's own) that paint something ([`shapes_image`]), each
/// without the effects before its first Convert to Shape or Outline Object. Convert to Shape sizes
/// its shape from the image's box, and Outline Object gives the image's frame. The others paint
/// nothing.
/// its shape from the image's box, and Outline Object gives the outline of the image's opaque
/// area ([`opaque_area`]), or its frame when it has no transparency. The others paint nothing.
fn image_rows(items: &[AppearanceItem]) -> Vec<AppearanceItem> {
items
.iter()
@@ -303,11 +304,109 @@ fn image_rows(items: &[AppearanceItem]) -> Vec<AppearanceItem> {
.collect()
}
/// Does `item`, one of [`image_rows`], start from the outline of the image's opaque area (is its
/// first effect Outline Object rather than Convert to Shape)?
fn follows_opaque_area(item: &AppearanceItem) -> bool {
item.effects().first().is_some_and(|e| e.id == "path.outlineObject")
}
/// Is `n` an image with a fill or stroke of its own that follows the outline of the image's opaque
/// area ([`image_rows`], [`opaque_area`])? The shape that fill or stroke paints then changes with
/// the image's pixels in the document while `n` stays the same.
pub fn follows_image_pixels(n: &Node) -> bool {
matches!(n.kind, NodeKind::Image(_))
&& n.appearance
.items
.iter()
.any(|i| shapes_image(i) && i.effects().iter().find(|e| gives_shape(e)).is_some_and(|e| e.id == "path.outlineObject"))
}
/// The outline of a set of pixels' opaque area, in the pixel space they decode to, with that size
/// ([`traced_opaque_area`]). `None` for pixels that have no transparency or could not be traced.
type Traced = Option<(Arc<PathData>, (u32, u32))>;
/// One of [`Outlines`]' entries: the pixels, held weakly, and their outline once it is traced.
type Entry = (Weak<Vec<u8>>, Arc<OnceLock<Traced>>);
/// The outlines [`opaque_area`] has traced, by the address of the pixels each was traced from.
struct Outlines {
/// Each outline with its pixels. An entry does not keep its pixels, and while it is kept no
/// other pixels can take their address. Entries whose pixels are gone are dropped before a
/// new outline is traced and every [`PRUNE_EVERY`] lookups.
kept: BTreeMap<usize, Entry>,
/// The lookups since the last pruning.
lookups: usize,
}
static OUTLINES: Mutex<Outlines> = Mutex::new(Outlines { kept: BTreeMap::new(), lookups: 0 });
/// How many lookups [`OUTLINES`] takes between two prunings of its entries for pixels that are gone.
const PRUNE_EVERY: usize = 256;
#[cfg(test)]
thread_local! {
/// The outlines [`traced_opaque_area`] has traced on this thread.
pub(crate) static TRACES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Does [`OUTLINES`] keep an entry for `pixels`?
#[cfg(test)]
pub(crate) fn keeps_outline(pixels: &Weak<Vec<u8>>) -> bool {
OUTLINES.lock().unwrap_or_else(PoisonError::into_inner).kept.values().any(|(w, _)| w.ptr_eq(pixels))
}
/// The outline of the opaque area of the image `im` in the document
/// ([`vectorcraft_trace::opaque_outline`]: its pixels that are at least half opaque, outlined with
/// fitted curves), its pixels taken from `im` itself or from the first of `docs` that holds them.
/// `None` when the image has no transparency, its pixels can't be read or are too large to read
/// ([`vectorcraft_trace::decode_alpha`]), or its outline would be too complex: Outline Object then
/// follows the image's frame. The outline is traced once for each set of pixels and kept while
/// those pixels are: a caller that asks while another thread traces the same pixels waits for that
/// trace.
pub(crate) fn opaque_area(docs: &[Option<&Document>], im: &ImageObject) -> Option<PathData> {
let blob = im.pixels.as_deref().or_else(|| docs.iter().flatten().find_map(|d| d.images.get(&im.key)))?;
let bytes = &blob.bytes;
let cell = {
let mut o = OUTLINES.lock().unwrap_or_else(PoisonError::into_inner);
o.lookups += 1;
if o.lookups >= PRUNE_EVERY {
o.lookups = 0;
o.kept.retain(|_, (w, _)| w.strong_count() > 0);
}
let key = Arc::as_ptr(bytes).addr();
match o.kept.get(&key) {
Some((_, cell)) => Arc::clone(cell),
None => {
o.kept.retain(|_, (w, _)| w.strong_count() > 0);
let cell = Arc::new(OnceLock::new());
o.kept.insert(key, (Arc::downgrade(bytes), Arc::clone(&cell)));
cell
}
}
};
// Traced without the lock: another image's outline need not wait for this one.
let (path, (w, h)) = cell.get_or_init(|| traced_opaque_area(bytes)).clone()?;
let to_image = Affine::scale_non_uniform(f64::from(im.width) / f64::from(w.max(1)), f64::from(im.height) / f64::from(h.max(1)));
Some(path.transformed(im.xf * to_image))
}
/// [`opaque_area`]'s outline of the encoded image `bytes`. An image whose format has no alpha is
/// not decoded.
fn traced_opaque_area(bytes: &[u8]) -> Traced {
#[cfg(test)]
TRACES.with(|t| t.set(t.get() + 1));
let (w, h, alpha) = vectorcraft_trace::decode_alpha(bytes).ok()??;
let outline = vectorcraft_trace::opaque_outline(w, h, alpha).ok()??;
Some((Arc::new(outline), (w, h)))
}
/// The shapes that the image `n`'s own fills and strokes paint ([`image_rows`]), each with its fill
/// rule and the fill or stroke that paints it: the paths (or compound paths) along its frame that
/// [`reshape`] makes, with each fill's or stroke's geometry effects applied as the renderer applies
/// them. Empty for anything but an image with such fills or strokes. The swatches and patterns that
/// live-effect plug-ins painting their pieces name are looked up in `doc`.
/// rule and the fill or stroke that paints it: the paths (or compound paths) that [`reshape`]
/// makes along its frame or, for those whose first effect is Outline Object, along the outline of
/// its opaque area ([`opaque_area`]), with each fill's or stroke's geometry effects applied as the
/// renderer applies them. Empty for anything but an image with such fills or strokes. The swatches
/// and patterns that live-effect plug-ins painting their pieces name are looked up in `doc`, and
/// the image's pixels in `doc` when the image does not hold them.
pub fn image_paint(doc: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> {
if !matches!(n.kind, NodeKind::Image(_)) || !has_item_geometry(n) {
return vec![];
@@ -425,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.
@@ -463,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;
@@ -608,9 +704,10 @@ pub(crate) fn outline_nested_text(doc: Option<&Document>, n: &mut Node, clipping
/// `n` (see [`needs_outline`]) with its object-level geometry effects and its perspective applied:
/// its [`outline_art`] reshaped as one piece, or for an image the image clipped by its reshaped
/// frame. Type's own fills and strokes keep their effects on its whole outline. An image's own
/// fills and strokes that paint a shape ([`image_rows`]) become paths along its frame below and
/// above it, reshaped with it, and keep their effects from their first Convert to Shape or Outline
/// Object on. The result is a group with `n`'s id, name, visibility, transparency, opacity mask
/// fills and strokes that paint a shape ([`image_rows`]) become paths below and above it, along
/// its frame or, from Outline Object, along the outline of its opaque area ([`opaque_area`]),
/// reshaped with it, and keep their effects from their first Convert to Shape or Outline Object
/// on. The result is a group with `n`'s id, name, visibility, transparency, opacity mask
/// and remaining (raster) effects; `None` when `n` has no visible geometry effect, no perspective
/// and is not type or an image with a fill or stroke of its own that [`has_item_geometry`] counts,
/// or has no art (a symbol instance without `symbol_art`). A path with [`has_transform_art`] is
@@ -682,12 +779,13 @@ fn as_art_opts(
NodeKind::Image(im) => {
let frame = shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf);
let mut image = Node::new(n.id, n.kind.clone());
// Its pixels draw as the image's do: colorized by a grayscale image's fill color, and
// smoothed or not.
// Its pixels draw as the image's do: colorized by a grayscale image's fill color,
// smoothed or not, and with its color mask's masked pixels.
{
let mut e = image.extras_mut();
e.colorize = n.extras().colorize.clone();
e.pixelated = n.extras().pixelated;
e.color_mask = n.extras().color_mask.clone();
}
let clipped = || {
let mut clip = Node::path(n.id, frame.clone(), Appearance::default());
@@ -696,15 +794,33 @@ fn as_art_opts(
}
Node::new(n.id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(image.clone())], clip: true })
};
// The fills and strokes that paint a shape, as paths along the frame below and above
// the image.
// The fills and strokes that paint a shape, as paths below and above the image: along
// the frame, or for those whose first effect is Outline Object along the outline of
// the image's opaque area (traced only when one of them needs it). A run of either
// kind is one path; a fill or stroke whose outline is empty (an image with no opaque
// pixel) paints nothing.
let (below, above) = n.appearance.split_contents();
let (below, above) = (image_rows(below), image_rows(above));
if below.is_empty() && above.is_empty() {
clipped()
} else {
let opaque = std::cell::OnceCell::new();
let rows = |items: Vec<AppearanceItem>| {
(!items.is_empty()).then(|| Arc::new(Node::path(n.id, frame.clone(), Appearance { items, ..Default::default() })))
let mut out = vec![];
let mut items = items.into_iter().peekable();
while let Some(first) = items.next() {
let follows = follows_opaque_area(&first);
let mut run = vec![first];
while let Some(next) = items.next_if(|i| follows_opaque_area(i) == follows) {
run.push(next);
}
let path = if follows { opaque.get_or_init(|| opaque_area(&[symbols, paint_doc], im)).as_ref() } else { None };
let path = path.unwrap_or(&frame);
if !path.is_empty() {
out.push(Arc::new(Node::path(n.id, path.clone(), Appearance { items: run, ..Default::default() })));
}
}
out
};
// Without geometry effects, the image is not clipped.
let image = if fx.is_empty() { image.clone() } else { clipped() };
@@ -724,18 +840,71 @@ 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);
let carry = reshape_leaves_carrying(&mut art, &fx, &n.appearance.effects, doc);
transform_items(&mut art, doc);
let mut art = dressed(art, n);
// The raster effects before a Transform effect the path did not take stay as the path does.
if carry.skipped() {
let mut ran = n.appearance.effects.clone();
carry.hide_skipped(&mut ran);
art.appearance.effects = crate::raster::without_geometry(&ran);
}
Some(art)
}
/// Map every path under `art` (and its gradients), and every path in the art of the linked opacity
@@ -835,7 +1004,8 @@ fn hoist_copies(art: &mut Node) {
/// of their own ([`copy_leaf`]) whatever paints them, as Expand Appearance makes them. A live-effect
/// plug-in that paints what it returns makes each path a group of its pieces ([`paint_leaf`]),
/// whose swatches and patterns must be in `doc` (without one, pieces that name one are refused).
/// Returns how gradients that paint the art as a whole follow the effects. A deferred live-effect
/// Returns how gradients that paint the art as a whole follow the effects, and the Transform
/// effects that nothing in the art took past the budget ([`crate::Carry::skipped`]). A deferred live-effect
/// plug-in is listed by its index in `owner`, the effect list `fx` was taken from, or in `fx` when
/// `owner` does not hold it. The art of the linked opacity masks of the objects in `art` (not of
/// `art` itself) takes each effect as the paths it masks do ([`Step::reshape_masks`]), with the
@@ -891,6 +1061,16 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget
used = cost;
continue;
}
// A Transform effect that moves the art once and that nothing in it took (past the budget)
// is left out ([`crate::Carry::hide_skipped`]), listed by its index in `owner`.
if ran.kept
&& !ran.took
&& e.id == "distort.transform"
&& !crate::raster::holds_back(e)
&& let Some(i) = owner.iter().position(|x| std::ptr::eq(x, *e))
{
whole.skip(i);
}
if let Some(carry) = ran.whole {
whole.push(carry);
}
@@ -922,6 +1102,8 @@ struct Step<'a> {
struct Ran {
/// A path in the art kept its shape (past the budget).
kept: bool,
/// A path, image or symbol instance in the art took the effect.
took: bool,
/// The linked opacity mask of an object in the art stayed as it was while the paths it masks
/// took the effect, or could have ([`Step::reshape_masks`]).
masks: bool,
@@ -961,7 +1143,7 @@ impl Step<'_> {
depth: usize,
) -> Ran {
let (e, params, bounds, seed) = (self.e, self.params, self.bounds, self.seed);
let stayed = Ran { kept: false, masks: true, short: false, whole: None };
let stayed = Ran { kept: false, took: false, masks: true, short: false, whole: None };
if let Some(plugin) = painted_plugin(e) {
if own || has_linked_mask(art, false) {
return stayed;
@@ -975,7 +1157,7 @@ impl Step<'_> {
*used = used.minus(before).plus(made);
}
});
return Ran { kept: false, masks: false, short: false, whole: None };
return Ran { kept: false, took: true, masks: false, short: false, whole: None };
}
// A Warp effect that bends images ([`mark_warped_images`]) bends an image's pixels, not the
// art of its linked mask.
@@ -1028,7 +1210,7 @@ impl Step<'_> {
// ([`transform_placed`]): a mask's art that holds one can't take another effect as the art
// it masks does.
if own && transform.is_none() && (is_placed(art) || placed_count(art) > 0) {
return Ran { kept: false, masks: true, short: false, whole: None };
return Ran { kept: false, took: false, masks: true, short: false, whole: None };
}
// Art of several objects is copied whole, so the copies don't interleave member by member.
// The copies of its members carry their linked masks, moved with them.
@@ -1038,7 +1220,7 @@ impl Step<'_> {
{
if !own {
*used = copy_art(art, m, copies, copy_scaling(options), max);
return Ran { kept: false, masks: false, short: false, whole: None };
return Ran { kept: false, took: true, masks: false, short: false, whole: None };
}
// A mask's art: its copies keep to what the rest of the art leaves of `max`, and the
// linked mask of the art itself takes them too. That mask's art stays in `used`, as
@@ -1050,7 +1232,7 @@ impl Step<'_> {
let short = art.children().is_some_and(|c| c.iter().filter(|c| !c.is_guide()).count() <= copies);
let none = HashSet::new();
let masks = self.reshape_own_mask(art, &Skip { moved: &none, kept: &none }, max, used, depth);
return Ran { kept: false, masks, short, whole: None };
return Ran { kept: false, took: true, masks, short, whole: None };
}
// A shortfall in the copies matters for the objects a linked mask above them covers, which
// the mask would take a different number of copies than, and anywhere in a mask's art.
@@ -1061,6 +1243,7 @@ impl Step<'_> {
}
let counts = |id: NodeId| watch && (own || covered.contains(&id));
let mut short = false;
let mut took = false;
for_each_leaf(art, &mut |leaf| {
let at = leaf_at;
leaf_at += 1;
@@ -1085,6 +1268,7 @@ impl Step<'_> {
if options.reach_appearance() {
let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, raster_map.is_some(), None);
*used = used.minus(before).plus(made);
took |= moved;
if moved {
// With Transform Objects off the path stays, and its mask takes the
// effect's stroke and pattern changes as its own art.
@@ -1101,6 +1285,7 @@ impl Step<'_> {
let scaling = vectorcraft_doc::Scaling { keep_fit_when_flat: true, ..Default::default() };
let made = copy_leaf(leaf, &path, m, copies, scaling, room, None);
*used = used.minus(before).plus(made);
took = true;
moved_ids.insert(leaf.id);
short |= counts(leaf.id) && copied(leaf) <= copies;
return;
@@ -1112,6 +1297,7 @@ impl Step<'_> {
kept_leaves.insert(at);
return;
};
took = true;
// A Transform effect's copies of a path are subpaths of it, each with the path's anchors.
if counts(leaf.id)
&& let Some((_, copies, _, _)) = transform
@@ -1153,6 +1339,8 @@ impl Step<'_> {
*art = Node::group(id, vec![Arc::new(one)]);
}
let placed = if watch { masked_placed(art, own) } else { 0 };
// Images and symbol instances take the effect whatever the budget.
took = took || placed_count(art) > 0;
// Scale Strokes & Effects leaves the raster effects that follow the effect to
// [`follow_art`].
let mut scaling = copy_scaling(options);
@@ -1186,7 +1374,7 @@ impl Step<'_> {
}
let drawn = warped.as_deref().map_or_else(|| art.geometric_bounds(), |w| w.bounds(art));
let whole = (follows && !held).then(|| crate::Carry::of(&e.id, params, bounds, Some(bounds), drawn, seed));
Ran { kept: !kept_ids.is_empty(), masks, short, whole }
Ran { kept: !kept_ids.is_empty(), took, masks, short, whole }
}
/// Run the effect over the art of the linked opacity mask of `n` (with `own`) and of each path,
@@ -1739,22 +1927,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,
@@ -1762,7 +1958,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) {
@@ -1904,9 +2100,14 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
// effects before this one back from every Transform effect ([`crate::raster::followed`]).
let held_later = fx.get(at + 1..).unwrap_or_default().iter().any(crate::raster::holds_back);
// The effects before the Transform effect that it keeps, each raster effect following the
// geometry effects before it ([`crate::raster::without_geometry`]) unless held back.
// geometry effects before it that moved the geometry ([`crate::raster::without_geometry`],
// [`crate::Carry::hide_skipped`]) unless held back.
let mut ran = std::borrow::Cow::Borrowed(before);
if carry.skipped() {
carry.hide_skipped(ran.to_mut());
}
let kept_before: Vec<Effect> =
if held_later { before.iter().filter(|e| !is_geometry(&e.id)).cloned().collect() } else { crate::without_geometry(before) };
if held_later { before.iter().filter(|e| !is_geometry(&e.id)).cloned().collect() } else { crate::without_geometry(&ran) };
if let Some(plugin) = painted_plugin(&fx[at]) {
let mut it = item.clone();
let rest: Vec<Effect> = kept_before.iter().chain(&fx[at + 1..]).cloned().collect();
@@ -1931,7 +2132,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;
}
@@ -1954,7 +2155,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() {
@@ -1967,7 +2168,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
@@ -1976,19 +2177,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());
}
});
@@ -1996,60 +2210,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, &params, seed);
let options = crate::distort::TransformOptions::of(&params);
let map = crate::distort::transform_affine(bounds, &params, 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);
}
@@ -2061,6 +2422,137 @@ 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, &params), 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, &params, at.seed);
let options = crate::distort::TransformOptions::of(&params);
let map = crate::distort::transform_affine(at.bounds, &params, 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);
// A Transform effect left out (past the budget) leaves the path and its raster effects as they were.
if !carry.skipped() {
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.
+165 -35
View File
@@ -4,7 +4,7 @@ use std::sync::Arc;
use serde_json::Value;
use vectorcraft_doc::color::{Color, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, LineJoin, Node, NodeId, NodeKind, StrokeLayer};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, Node, NodeId, NodeKind};
use vectorcraft_geom::{PathData, PathEl, Point, Rect, Vec2};
use vectorcraft_three_d::{Edge, Revolve};
@@ -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, &params, &mut graphic_copies);
if i == target {
graphics?;
}
check_shadow(&params, [&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
@@ -404,17 +494,26 @@ fn surface(
.into_iter()
.flat_map(|item| {
let AppearanceItem::Fill(fill) = &item else { return vec![item] };
let mut edge = StrokeLayer::new(fill.paint.clone(), SEAM_WIDTH);
// Acute face corners must stay within the overlap width. Miter joins
// amplify this seam stroke into visible spikes along the silhouette.
edge.join = LineJoin::Round;
// Acute face corners must stay within the overlap width: meets() counts on a
// stroked seam reaching no more than half its width; faces drawn as clipped
// groups are measured by their box.
let mut edge = crate::lighting::seam_stroke(fill.paint.clone(), SEAM_WIDTH);
edge.opacity = fill.opacity;
vec![item, AppearanceItem::Stroke(edge)]
})
.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, &params).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:?}");
}
File diff suppressed because it is too large. Load diff
+12 -7
View File
@@ -5,7 +5,7 @@ use std::sync::Arc;
use serde_json::Value;
use vectorcraft_doc::color::{BlendMode, Color, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, Node, StrokeLayer};
use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, Node};
use vectorcraft_geom::Rect;
use vectorcraft_three_d::{Bevel, BevelShape, ClassicShading, ClassicSurface, Extrude, Facet, Light};
@@ -207,8 +207,8 @@ pub(crate) fn surface(n: &Node, facets: Vec<Facet>, source: &Paint, opacity: f32
.into_iter()
.map(|face| {
if wire {
let mut edge = StrokeLayer::new(paint.clone(), WIRE);
edge.join = vectorcraft_doc::LineJoin::Round;
// A wire edge is drawn as a seam is: a round-joined stroke of the paint.
let edge = crate::lighting::seam_stroke(paint.clone(), WIRE);
return Arc::new(Node::path(n.id, face.path(), Appearance { items: vec![AppearanceItem::Stroke(edge)], ..Default::default() }));
}
let (tone, spec) = shading.tone(face.normal, &lights);
@@ -218,18 +218,23 @@ pub(crate) fn surface(n: &Node, facets: Vec<Facet>, source: &Paint, opacity: f32
// Unshaded (No Shading, no shading color, or a face in full light) with no
// highlight: the paint itself, its color space and swatch kept.
Some(_) if (tone >= 1.0 || shade.is_none()) && spec <= 0.0 => {
vec![AppearanceItem::Fill(FillLayer::new(paint.clone())), AppearanceItem::Stroke(StrokeLayer::new(paint.clone(), seam))]
vec![
AppearanceItem::Fill(FillLayer::new(paint.clone())),
AppearanceItem::Stroke(crate::lighting::seam_stroke(paint.clone(), seam)),
]
}
Some(c) => {
let fill = Paint::solid(shaded(c, tone, spec, shade));
vec![AppearanceItem::Fill(FillLayer::new(fill.clone())), AppearanceItem::Stroke(StrokeLayer::new(fill, seam))]
vec![AppearanceItem::Fill(FillLayer::new(fill.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(fill, seam))]
}
// Gradients and patterns keep their paint, darkened by a layer of the shading color
// and lightened by one of white. As with the other 3D effects' pattern shadow, the
// layers cover the whole face, transparent pattern cells included.
None => {
let mut items =
vec![AppearanceItem::Fill(FillLayer::new(paint.clone())), AppearanceItem::Stroke(StrokeLayer::new(paint.clone(), seam))];
let mut items = vec![
AppearanceItem::Fill(FillLayer::new(paint.clone())),
AppearanceItem::Stroke(crate::lighting::seam_stroke(paint.clone(), seam)),
];
for (color, share) in [(shade, 1.0 - tone), (Some(Color::WHITE), spec)] {
if let Some(color) = color.filter(|_| share > 0.0) {
let mut layer = FillLayer::new(Paint::solid(color));
+448 -7
View File
@@ -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)?;
File diff suppressed because it is too large. Load diff
+212 -1
View File
@@ -365,6 +365,41 @@ fn members_with_their_own_blending_get_graphics_of_their_own() {
assert_eq!(blended, 1);
}
#[test]
fn a_graphic_stays_under_a_solid_painted_after_its_own() {
let d = document();
let member = |id: u64, r: Rect, color: Color, opacity: f32| {
let mut n = square(id, r, Paint::solid(color));
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
f.opacity = opacity;
}
Arc::new(n)
};
let gray = Color::rgb(0.5, 0.5, 0.5);
// A and C share their fill's opacity; B, painted between them, has its own and covers part of A.
let a = member(1, Rect::new(0.0, 0.0, 60.0, 100.0), gray, 1.0);
let b = member(2, Rect::new(40.0, 0.0, 100.0, 100.0), Color::rgb(0.0, 0.0, 1.0), 0.5);
let c = member(4, Rect::new(200.0, 0.0, 260.0, 100.0), gray, 1.0);
let mut group = Node::group(NodeId(3), vec![a, b, c]);
let p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": false, "graphics": [{"symbol": "Mark", "scale": 3000.0}]});
group.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap());
let art = solid_art_in(Some(&d), &group).unwrap();
// In drawing order: 'G' for a graphic, 'B' for a face of B's solid.
let mut order = String::new();
art.walk(&mut |n| {
if matches!(n.kind, NodeKind::Group { clip: true, .. }) && !graphics_in(n).is_empty() {
order.push('G');
} else if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first()
&& f.paint.color().is_some_and(|c| c.to_rgb()[2] > 0.9 && c.to_rgb()[0] < 0.1)
{
order.push('B');
}
});
// A's graphic is drawn right after A, under B; C's is drawn after B.
assert_eq!(graphics_in(&art).len(), 3, "{order}");
assert!(order.starts_with('G'), "{order}");
}
/// [`document`] with symbol "Dense" too: a red polygon of 30,000 sides, straight or `curved`.
fn dense_document(curved: bool) -> Document {
let mut d = document();
@@ -470,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);
}
@@ -585,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();
@@ -657,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)));
}
+30
View File
@@ -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, &params);
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();
+1 -1
View File
@@ -1,6 +1,6 @@
use serde_json::json;
use vectorcraft_doc::color::Color;
use vectorcraft_doc::{Document, NodeId};
use vectorcraft_doc::{Document, NodeId, StrokeLayer};
use vectorcraft_geom::{Affine, BezPath};
use super::*;
+11 -19
View File
@@ -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_paint_sources, solid_parts, union_bounds,
};
use crate::{GeomContext, is_geometry};
@@ -105,16 +105,16 @@ fn solid_face_paths(doc: Option<&Document>, n: &Node) -> Result<Vec<PathData>, S
let label = n.appearance.effects.iter().find(|e| e.visible && is_three_d(&e.id)).map_or("This effect", |e| label_of(&e.id));
let (path, rule) = object_profile(n, label)?;
let ctx = GeomContext::of(n);
let paints = solid_paints(n);
let (sources, paints) = solid_paint_sources(n);
if let Some((index, fx)) = solid(&n.appearance.effects) {
let path = geometry(&path, n.appearance.effects.get(..index).unwrap_or_default(), &ctx);
return facet_paths(fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }]);
}
let path = geometry(&path, &n.appearance.effects, &ctx);
let mut out = vec![];
for item in &paints {
for (source, item) in sources.into_iter().zip(&paints) {
if let Some((index, fx)) = solid(item.effects()) {
let p = geometry(&path, item.effects().get(..index).unwrap_or_default(), &ctx.item(item));
let p = geometry(&path, item.effects().get(..index).unwrap_or_default(), &ctx.item(source.unwrap_or(item)));
let faces = facet_paths(fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }])?;
out.extend(reshaped(faces, item.effects().get(index + 1..).unwrap_or_default(), &GeomContext { doc, ..ctx }));
}
@@ -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 -1
View File
@@ -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::*;
+105
View File
@@ -4,8 +4,11 @@ use vectorcraft_geom::{Affine, PathData, Point, Rect, Shape, SubPath, shapes};
use super::*;
mod imageoutline;
mod painted;
mod rasterfollow;
mod scale;
mod solidcontext;
mod transformfx;
fn fx(id: &str, params: Value) -> Effect {
@@ -886,6 +889,108 @@ fn a_hidden_path_past_the_budget_leaves_a_layers_gradients_free_to_move() {
}
}
/// Under a Warp effect a hidden path in a layer that keeps its shape past the budget does not hold
/// the layer's gradient in place either: it moves and scales from the layer's bounds to the warped
/// square's bounds, as the art and inside the art.
#[test]
fn a_hidden_path_past_the_budget_leaves_a_layers_gradients_free_to_follow_a_warp() {
use std::sync::Arc;
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
use vectorcraft_doc::{AppearanceItem, FillLayer, LayerColor, NodeId, NodeKind, color::Paint};
let stops = vec![GradientStop::new(0.0, vectorcraft_color::Color::BLACK), GradientStop::new(1.0, vectorcraft_color::Color::WHITE)];
let geom = GradientGeom { start: (0.0, 50.0).into(), end: (100.0, 50.0).into(), aspect: 1.0, focal: None };
let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..GradientPaint::new(Gradient::new(GradientKind::Linear, stops)) }));
let ends = |ap: &Appearance| match ap.fill_paint() {
Paint::Gradient(g) => g.geom.map(|g| (g.start, g.end)),
_ => None,
};
let oval = || shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 100.0));
// A layer with a visible square and a hidden circle, both 0..100, and a gradient fill of its own.
let layer = || {
let square = Arc::new(Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default()));
let mut circle = Node::path(NodeId(4), oval(), Appearance::default());
circle.visible = false;
let mut layer = Node::layer(NodeId(2), "Layer 1", LayerColor::Preset(0));
if let NodeKind::Layer { children, .. } = &mut layer.kind {
*children = vec![square, Arc::new(circle)];
}
layer.appearance.items.push(AppearanceItem::Fill(FillLayer::new(placed.clone())));
layer
};
// The box map from the layer's bounds (the square's) to `b`: (0, 50) and (100, 50) go to the
// middles of b's sides.
let near = |got: Option<(Point, Point)>, b: Rect| {
let mid = (b.y0 + b.y1) / 2.0;
got.is_some_and(|(s, e)| s.distance(Point::new(b.x0, mid)) < 1e-6 && e.distance(Point::new(b.x1, mid)) < 1e-6)
};
for style in ["arc", "inflate", "flag"] {
let warp = fx(&format!("warp.{style}"), json!({"bend": 40.0, "horizontal": 20.0}));
// Room for the warped square beside the circle as it was, and not for the warped circle
// beside the warped square: the paths take the budget in turn, so the circle keeps its shape.
let mut probe = layer();
crate::reshape::reshape_leaves_within(&mut probe, &[&warp], Budget::EFFECTS, None);
let warped = |k: usize| util::line_estimate(probe.children().unwrap()[k].path_data().unwrap());
let circle = util::line_estimate(&oval());
assert!(warped(1) > circle, "warp.{style}: the warped circle is drawn with more lines");
let budget = Budget { anchors: usize::MAX, lines: warped(0) + circle };
let mut art = layer();
let carry = crate::reshape::reshape_leaves_within(&mut art, &[&warp], budget, None);
assert_eq!(art.children().unwrap()[1].path_data(), Some(&oval()), "{}: the hidden circle keeps its shape", warp.id);
let square = art.children().unwrap()[0].geometric_bounds().unwrap();
assert!(square != Rect::new(0.0, 0.0, 100.0, 100.0), "{}: the square takes the effect: {square:?}", warp.id);
let mut own = Appearance::clone(&art.appearance);
carry.apply(&mut own);
assert!(near(ends(&own), square), "{}: the layer's gradient, as the art: {:?} for {square:?}", warp.id, ends(&own));
let mut art = Node::group(NodeId(9), vec![Arc::new(layer())]);
crate::reshape::reshape_leaves_within(&mut art, &[&warp], budget, None);
let got = ends(&art.children().unwrap()[0].appearance);
assert!(near(got, square), "{}: the layer's gradient, inside the art: {got:?} for {square:?}", warp.id);
}
}
/// A freeform gradient whose points were edited moves its points with a Warp effect from the
/// bounds before the warp to the bounds after it, on a path, on a group inside the art and on the
/// art itself, as a placed gradient does.
#[test]
fn edited_freeform_points_follow_a_warp() {
use std::sync::Arc;
use vectorcraft_color::{Color, Freeform, FreeformPoint, Gradient, GradientKind, GradientPaint};
use vectorcraft_doc::{AppearanceItem, FillLayer, NodeId, color::Paint};
let mut ramp = GradientPaint::new(Gradient { kind: GradientKind::Freeform, ..Gradient::default() });
let pt = |x: f64, c| FreeformPoint::new(Point::new(x, 50.0), c);
ramp.set_freeform(Freeform { points: vec![pt(0.0, Color::BLACK), pt(100.0, Color::WHITE)], ..Default::default() });
assert!(ramp.geom.is_none() && !ramp.is_placed());
let freeform = Paint::Gradient(Box::new(ramp));
let points = |ap: &Appearance| match ap.fill_paint() {
Paint::Gradient(g) => g.freeform.as_ref().map(|f| f.points.iter().map(|p| p.at).collect::<Vec<_>>()),
_ => None,
};
let square = |ap: Appearance| Arc::new(Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), ap));
// The box map from the square's bounds to `b`: (0, 50) and (100, 50) go to the middles of b's sides.
let near = |got: Option<Vec<Point>>, b: Rect| {
let mid = (b.y0 + b.y1) / 2.0;
got.is_some_and(|p| p.len() == 2 && p[0].distance(Point::new(b.x0, mid)) < 1e-6 && p[1].distance(Point::new(b.x1, mid)) < 1e-6)
};
for style in ["arc", "inflate", "rise"] {
let e = fx(&format!("warp.{style}"), json!({"bend": 40.0, "vertical": 20.0}));
let mut inner = Node::group(NodeId(2), vec![square(Appearance::default())]);
inner.appearance.items.push(AppearanceItem::Fill(FillLayer::new(freeform.clone())));
let mut art = Node::group(NodeId(9), vec![square(Appearance::basic(freeform.clone(), Paint::None, 0.0)), Arc::new(inner)]);
art.appearance.items.push(AppearanceItem::Fill(FillLayer::new(freeform.clone())));
let carry = crate::reshape::reshape_leaves_within(&mut art, &[&e], Budget::EFFECTS, None);
let b = art.geometric_bounds().unwrap();
assert!(b != Rect::new(0.0, 0.0, 100.0, 100.0), "{}: the warp changes the bounds: {b:?}", e.id);
let members = art.children().unwrap();
assert!(near(points(&members[0].appearance), b), "{}: the path's points {:?} for {b:?}", e.id, points(&members[0].appearance));
assert!(near(points(&members[1].appearance), b), "{}: the inner group's points {:?} for {b:?}", e.id, points(&members[1].appearance));
let mut own = Appearance::clone(&art.appearance);
carry.apply(&mut own);
assert!(near(points(&own), b), "{}: the art's own points {:?} for {b:?}", e.id, points(&own));
}
}
/// A freeform gradient whose points were edited (its vector still fitted to the bounds) moves its
/// points with a Transform effect and Free Distort, on a path, on a group inside the art and on the
/// art itself, as a placed gradient does.
+338
View File
@@ -0,0 +1,338 @@
//! Outline Object on an image's own fill or stroke: the outline of the image's opaque area, for
//! every pixel format with alpha, and the frame for one without.
use std::sync::Arc;
use serde_json::json;
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{AppearanceItem, Document, Effect, FillLayer, ImageBlob, ImageObject, Node, NodeId, NodeKind, StrokeLayer};
use vectorcraft_geom::{Affine, Rect};
use crate::*;
fn fx(id: &str) -> Effect {
Effect { id: id.into(), params: json!({}), visible: true }
}
/// `img` encoded as `format`.
fn encoded(img: image::DynamicImage, format: image::ImageFormat) -> Vec<u8> {
let mut out = vec![];
img.write_to(&mut std::io::Cursor::new(&mut out), format).unwrap();
out
}
/// A 100×100 RGBA image, transparent but for an opaque disc of radius 30 in its middle.
fn disc() -> image::DynamicImage {
image::DynamicImage::ImageRgba8(image::RgbaImage::from_fn(100, 100, |x, y| {
let r = (f64::from(x) + 0.5 - 50.0).hypot(f64::from(y) + 0.5 - 50.0);
image::Rgba([255, 0, 0, if r <= 30.0 { 255 } else { 0 }])
}))
}
/// A document holding the encoded image `bytes` (key "img") and an image object of 100×100 pixels
/// placed at (50, 50) with the appearance items `items`, the image's own row at `contents`.
/// → (document, the image's node).
fn image_doc(bytes: Vec<u8>, items: Vec<AppearanceItem>, contents: usize) -> (Document, Node) {
let mut d = Document::new(200.0, 200.0);
d.images.insert("img".into(), ImageBlob::new("image/png", bytes));
let mut n = Node::new(
NodeId(0),
NodeKind::Image(Box::new(ImageObject {
key: "img".into(),
width: 100,
height: 100,
xf: Affine::translate((50.0, 50.0)),
link: None,
placement: Default::default(),
pixels: None,
})),
);
n.id = d.alloc_id();
n.appearance.items = items;
n.appearance.set_contents_at(contents);
let l = d.layers[0].id;
d.insert(Some(l), 0, n.clone()).unwrap();
(d, n)
}
/// A PNG of `w × h` pixels with the color type `color` at `depth` bits, the chunks `extra` before
/// its pixels, and the filtered rows `rows` stored without compression.
fn png(w: u32, h: u32, color: u8, depth: u8, extra: &[(&[u8; 4], Vec<u8>)], rows: &[u8]) -> Vec<u8> {
fn crc(data: &[u8]) -> u32 {
let mut c = !0u32;
for &b in data {
c ^= u32::from(b);
for _ in 0..8 {
c = if c & 1 == 1 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 };
}
}
!c
}
let mut out = b"\x89PNG\r\n\x1a\n".to_vec();
let mut chunk = |kind: &[u8; 4], data: &[u8]| {
let mut body = kind.to_vec();
body.extend_from_slice(data);
out.extend_from_slice(&u32::try_from(data.len()).unwrap().to_be_bytes());
out.extend_from_slice(&body);
out.extend_from_slice(&crc(&body).to_be_bytes());
};
let mut ihdr = [w.to_be_bytes(), h.to_be_bytes()].concat();
ihdr.extend([depth, color, 0, 0, 0]);
chunk(b"IHDR", &ihdr);
for (kind, data) in extra {
chunk(kind, data);
}
// A zlib stream of stored blocks.
let mut z = vec![0x78, 0x01];
let blocks: Vec<&[u8]> = if rows.is_empty() { vec![rows] } else { rows.chunks(65_535).collect() };
for (i, block) in blocks.iter().enumerate() {
let len = u16::try_from(block.len()).unwrap();
z.push(u8::from(i + 1 == blocks.len()));
z.extend(len.to_le_bytes());
z.extend((!len).to_le_bytes());
z.extend_from_slice(block);
}
let (mut a, mut b) = (1u32, 0u32);
for &byte in rows {
a = (a + u32::from(byte)) % 65_521;
b = (b + a) % 65_521;
}
z.extend(((b << 16) | a).to_be_bytes());
chunk(b"IDAT", &z);
chunk(b"IEND", &[]);
out
}
fn stroke(effects: Vec<Effect>) -> AppearanceItem {
let mut s = StrokeLayer::new(Paint::solid(Color::BLACK), 4.0);
s.effects = effects;
AppearanceItem::Stroke(s)
}
/// The bounds of the paths the image's own fills and strokes paint, below it first.
fn row_bounds(d: &Document, n: &Node) -> Vec<Rect> {
let art = reshape::reshape(Some(d), n, None).unwrap();
let mut out = vec![];
for c in art.children().unwrap() {
if matches!(c.kind, NodeKind::Path { .. }) {
out.push(c.geometric_bounds().unwrap());
}
}
out
}
fn near(r: Rect, want: [f64; 4], tol: f64) -> bool {
[r.x0 - want[0], r.y0 - want[1], r.x1 - want[2], r.y1 - want[3]].iter().all(|d| d.abs() < tol)
}
#[test]
fn outline_object_follows_the_opaque_area_of_an_image_with_alpha() {
let gray_alpha = image::DynamicImage::ImageLumaA8(disc().to_luma_alpha8());
let deep = image::DynamicImage::ImageRgba16(disc().to_rgba16());
for (name, img) in [("rgba", disc()), ("gray and alpha", gray_alpha), ("16 bits a channel", deep)] {
let (d, n) = image_doc(encoded(img, image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
let rows = row_bounds(&d, &n);
assert_eq!(rows.len(), 1, "{name}");
// The disc runs from 70 to 130; the frame from 50 to 150.
assert!(near(rows[0], [70.0, 70.0, 130.0, 130.0], 0.5), "{name}: {:?}", rows[0]);
}
}
#[test]
fn outline_object_follows_the_frame_of_an_image_without_transparency() {
let opaque = image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(100, 100, image::Rgb([0, 0, 255])));
let solid = image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(100, 100, image::Rgba([0, 0, 255, 200])));
let formats = [
("jpeg", encoded(opaque.clone(), image::ImageFormat::Jpeg)),
("rgb png", encoded(opaque, image::ImageFormat::Png)),
("rgba png, every pixel more than half opaque", encoded(solid, image::ImageFormat::Png)),
];
for (name, bytes) in formats {
let (d, n) = image_doc(bytes, vec![stroke(vec![fx("path.outlineObject")])], 1);
let rows = row_bounds(&d, &n);
assert!(rows.len() == 1 && near(rows[0], [50.0, 50.0, 150.0, 150.0], 1e-9), "{name}: {rows:?}");
}
// Pixels that can't be read keep the frame too.
let (d, n) = image_doc(b"not an image".to_vec(), vec![stroke(vec![fx("path.outlineObject")])], 1);
assert!(near(row_bounds(&d, &n)[0], [50.0, 50.0, 150.0, 150.0], 1e-9));
}
#[test]
fn convert_to_shape_keeps_the_frame_beside_outline_object() {
// Below the image: a fill with Convert to Shape, then a stroke with Outline Object; above it
// a stroke with Convert to Shape before Outline Object, which starts from the frame.
let rect = Effect { id: "convertToShape.rectangle".into(), params: json!({"relative": true, "extraW": 0, "extraH": 0}), visible: true };
let mut fill = FillLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0)));
fill.effects = vec![rect.clone()];
let items = vec![AppearanceItem::Fill(fill), stroke(vec![fx("path.outlineObject")]), stroke(vec![rect, fx("path.outlineObject")])];
let (d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), items, 2);
let rows = row_bounds(&d, &n);
assert_eq!(rows.len(), 3, "{rows:?}");
assert!(near(rows[0], [50.0, 50.0, 150.0, 150.0], 1e-9), "{rows:?}");
assert!(near(rows[1], [70.0, 70.0, 130.0, 130.0], 0.5), "{rows:?}");
assert!(near(rows[2], [50.0, 50.0, 150.0, 150.0], 1e-9), "{rows:?}");
// The image keeps its place between them.
let art = reshape::reshape(Some(&d), &n, None).unwrap();
assert!(matches!(art.children().unwrap()[2].kind, NodeKind::Image(_)));
}
#[test]
fn a_transparent_image_gives_outline_object_nothing_to_paint() {
let clear = image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(100, 100, image::Rgba([0, 0, 0, 100])));
let (d, n) = image_doc(encoded(clear, image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
assert!(row_bounds(&d, &n).is_empty());
let art = reshape::reshape(Some(&d), &n, None).unwrap();
assert!(matches!(art.children().unwrap().as_slice(), [only] if matches!(only.kind, NodeKind::Image(_))));
}
#[test]
fn the_outline_follows_the_images_own_pixels_and_placement() {
// Pixels kept on the image itself (art made outside a document), placed at half size.
let (_, mut n) = image_doc(vec![], vec![stroke(vec![fx("path.outlineObject")])], 1);
if let NodeKind::Image(im) = &mut n.kind {
im.pixels = Some(Arc::new(ImageBlob::new("image/png", encoded(disc(), image::ImageFormat::Png))));
im.xf = Affine::translate((10.0, 20.0)) * Affine::scale(0.5);
}
let art = reshape::reshape(None, &n, None).unwrap();
let b = art.children().unwrap()[0].geometric_bounds().unwrap();
// The disc runs from 20 to 80 pixels: half that, moved by (10, 20).
assert!(near(b, [20.0, 30.0, 50.0, 60.0], 0.3), "{b:?}");
}
#[test]
fn an_off_center_outline_turns_and_reflects_with_a_smaller_copy_of_the_pixels() {
// A 120×60 image whose opaque area is the rectangle from (12, 6) to (40, 24), its pixels a
// copy at half size (as a linked image's preview is), turned a quarter and reflected.
let half = image::DynamicImage::ImageRgba8(image::RgbaImage::from_fn(60, 30, |x, y| {
image::Rgba([255, 0, 0, if (6..20).contains(&x) && (3..12).contains(&y) { 255 } else { 0 }])
}));
let (d, mut n) = image_doc(encoded(half, image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
let xf = Affine::translate((100.0, 40.0)) * Affine::rotate(std::f64::consts::FRAC_PI_2) * Affine::scale_non_uniform(-1.0, 1.0);
if let NodeKind::Image(im) = &mut n.kind {
(im.width, im.height, im.xf) = (120, 60, xf);
}
let rows = row_bounds(&d, &n);
let want = xf.transform_rect_bbox(Rect::new(12.0, 6.0, 40.0, 24.0));
// The rectangle runs from (76, 0) to (94, 28); a flip in either direction, or the copy's
// width and height swapped, would move it.
assert!(near(want, [76.0, 0.0, 94.0, 28.0], 1e-9), "{want:?}");
assert!(rows.len() == 1 && near(rows[0], [want.x0, want.y0, want.x1, want.y1], 0.5), "{rows:?}");
}
#[test]
fn an_image_in_a_group_exports_with_its_outline() {
let (mut d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
let l = d.layers[0].id;
d.remove(n.id).unwrap();
let g = d.alloc_id();
d.insert(Some(l), 0, Node::group(g, vec![Arc::new(n)])).unwrap();
let baked = bake_document(&d).unwrap();
let mut paths = vec![];
for layer in &baked.layers {
layer.walk(&mut |c| {
if matches!(c.kind, NodeKind::Path { .. }) && (c.appearance.stroke_width() - 4.0).abs() < 1e-9 {
paths.push(c.geometric_bounds().unwrap());
}
});
}
assert!(matches!(paths.as_slice(), [b] if near(*b, [70.0, 70.0, 130.0, 130.0], 0.5)), "{paths:?}");
}
/// The bounds of the paths stroked 4 pt in `d` with its effects baked, as exports write it.
fn baked_strokes(d: &Document) -> Vec<Rect> {
let baked = bake_document(d).unwrap();
let mut paths = vec![];
for layer in &baked.layers {
layer.walk(&mut |c| {
if matches!(c.kind, NodeKind::Path { .. }) && (c.appearance.stroke_width() - 4.0).abs() < 1e-9 {
paths.push(c.geometric_bounds().unwrap());
}
});
}
paths
}
#[test]
fn an_image_under_a_clipping_mask_or_with_an_opacity_mask_exports_with_its_outline() {
let disc_outline = |paths: &[Rect]| matches!(paths, [b] if near(*b, [70.0, 70.0, 130.0, 130.0], 0.5));
// Under a clipping mask that covers the whole image.
let (mut d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
let l = d.layers[0].id;
d.remove(n.id).unwrap();
let clip = Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 200.0)), Default::default());
let g = d.alloc_id();
d.insert(Some(l), 0, Node::new(g, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(n)], clip: true })).unwrap();
let paths = baked_strokes(&d);
assert!(disc_outline(&paths), "{paths:?}");
// With an opacity mask.
let (mut d, mut n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
let mut white = Node::path(NodeId(999), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 200.0)), Default::default());
white.appearance.set_fill(Paint::solid(Color::WHITE));
n.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(Node::group(NodeId(998), vec![Arc::new(white)]), true)));
let id = n.id;
*d.node_mut(id).unwrap() = n;
let paths = baked_strokes(&d);
assert!(disc_outline(&paths), "{paths:?}");
}
#[test]
fn outline_object_on_a_fill_and_on_an_indexed_image_follows_the_opaque_area() {
let mut fill = FillLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0)));
fill.effects = vec![fx("path.outlineObject")];
let (d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![AppearanceItem::Fill(fill)], 1);
let rows = row_bounds(&d, &n);
assert!(matches!(rows.as_slice(), [b] if near(*b, [70.0, 70.0, 130.0, 130.0], 0.5)), "{rows:?}");
// A palette image whose first color is transparent (a tRNS chunk).
let mut rows = vec![];
for y in 0..100 {
rows.push(0);
for x in 0..100 {
let r = (f64::from(x) + 0.5 - 50.0).hypot(f64::from(y) + 0.5 - 50.0);
rows.push(u8::from(r <= 30.0));
}
}
let palette = png(100, 100, 3, 8, &[(b"PLTE", vec![0, 0, 0, 255, 0, 0]), (b"tRNS", vec![0, 255])], &rows);
let (d, n) = image_doc(palette, vec![stroke(vec![fx("path.outlineObject")])], 1);
let rows = row_bounds(&d, &n);
assert!(matches!(rows.as_slice(), [b] if near(*b, [70.0, 70.0, 130.0, 130.0], 0.5)), "{rows:?}");
}
#[test]
fn an_image_too_large_or_too_complex_to_outline_keeps_its_frame() {
// 72 megapixels at 8 bits a channel, and 42 at 16: refused before their pixels are read.
for (w, h, depth) in [(9000, 8000, 8), (7000, 6000, 16)] {
let bytes = png(w, h, 6, depth, &[], &[]);
assert!(matches!(vectorcraft_trace::decode_alpha(&bytes), Err(vectorcraft_trace::TraceError::TooLarge { .. })), "{w}×{h}");
let (d, n) = image_doc(bytes, vec![stroke(vec![fx("path.outlineObject")])], 1);
assert!(matches!(row_bounds(&d, &n).as_slice(), [b] if near(*b, [50.0, 50.0, 150.0, 150.0], 1e-9)), "{w}×{h}");
}
// A checkerboard of 2 px squares, whose outline would need more than 100,000 anchor points.
let checker = image::RgbaImage::from_fn(640, 640, |x, y| image::Rgba([0, 0, 0, if (x / 2 + y / 2) % 2 == 0 { 255 } else { 0 }]));
let (d, n) =
image_doc(encoded(image::DynamicImage::ImageRgba8(checker), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
assert!(matches!(row_bounds(&d, &n).as_slice(), [b] if near(*b, [50.0, 50.0, 150.0, 150.0], 1e-9)));
}
#[test]
fn an_outline_is_traced_once_for_its_pixels_and_dropped_with_them() {
let traces = || reshape::TRACES.with(std::cell::Cell::get);
let (d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
let NodeKind::Image(im) = &n.kind else { panic!("not an image") };
let before = traces();
let first = reshape::opaque_area(&[Some(&d)], im).unwrap();
assert_eq!(traces(), before + 1);
for _ in 0..3 {
row_bounds(&d, &n);
}
assert_eq!(reshape::opaque_area(&[Some(&d)], im).unwrap(), first);
assert_eq!(traces(), before + 1);
let pixels = Arc::downgrade(&d.images.get(&im.key).unwrap().bytes);
assert!(reshape::keeps_outline(&pixels));
// Once the document and its pixels are gone, the next trace drops their entry.
drop(d);
assert!(pixels.upgrade().is_none());
let (other, _) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![], 1);
reshape::opaque_area(&[Some(&other)], im).unwrap();
assert_eq!(traces(), before + 2);
assert!(!reshape::keeps_outline(&pixels));
}
+270
View File
@@ -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());
}
+197 -6
View File
@@ -4,9 +4,10 @@
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, Document, Effect, Node, NodeId};
use vectorcraft_geom::{Rect, shapes};
use vectorcraft_geom::{Affine, Anchor, PathData, Point, Rect, SubPath, shapes};
use crate::{RasterFx, bake_document, expand_outlined, raster_effects};
use crate::geometry::{Budget, MAX_EFFECT_LINES, apply_geometry_carrying_within};
use crate::{Carry, GeomContext, RasterFx, apply_geometry_carrying, bake_document, expand_outlined, raster_effects};
fn fx(id: &str, params: Value) -> Effect {
Effect { id: id.into(), params, visible: true }
@@ -523,11 +524,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,8 +647,197 @@ 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:?}");
}
}
}
/// A closed path of `n` curves along the x axis, 2 pt apart, each drawn with 14 lines at 1 px/pt
/// and with 425 once scaled 1000 times ([`crate::util::line_estimate`]).
fn wavy(n: usize) -> PathData {
let anchors = (0..=n)
.map(|i| {
let x = 2.0 * i as f64;
Anchor::with_handles(Point::new(x, 0.0), Point::new(x - 0.5, -20.0), Point::new(x + 0.5, 20.0))
})
.collect();
PathData::single(SubPath::new(anchors, true))
}
/// A red path `id` along `path` with object effects `effects`.
fn path_node(id: u64, path: PathData, effects: Vec<Effect>) -> Node {
let mut n = Node::path(NodeId(id), path, Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0));
n.appearance.effects = effects;
n
}
/// A Transform effect scaling 1000 times.
fn thousandfold() -> Effect {
transform(json!({"scaleH": 100000, "scaleV": 100000}))
}
/// `n` baked on its own ([`bake_document`]).
fn baked(n: Node) -> Node {
let id = n.id;
let mut d = Document::new(800.0, 800.0);
let layer = d.layers[0].id;
d.insert(Some(layer), 0, n).unwrap();
bake_document(&d).unwrap().node(id).unwrap().clone()
}
/// A Transform effect whose result passes the 8 million lines of the effect budget is left out, so
/// the art stays where it is, and the shadow before it keeps its offset and blur with it: drawn,
/// baked for export, and once shown after baking when it is hidden. One within the budget moves
/// and scales both.
#[test]
fn a_transform_past_the_line_budget_moves_the_art_with_its_shadow() {
let path = wavy(30_000);
assert!(Budget::EFFECTS.fits(Budget::of(&path)), "{:?}", Budget::of(&path));
let candidate = Budget::of(&path.transformed(Affine::scale(1000.0)));
assert!(candidate.lines > MAX_EFFECT_LINES, "{candidate:?}");
let b = path.bounds().unwrap();
let n = path_node(30, path.clone(), vec![shadow(10.0, 5.0, 4.0), thousandfold()]);
let (g, carry) = apply_geometry_carrying(&n.appearance.effects, &path, b, &GeomContext::of(&n));
assert_eq!(g, path, "the art stays where it is");
assert!(carry.skipped());
let mut drawn = n.appearance.effects.clone();
carry.hide_skipped(&mut drawn);
assert!(close(drawn_shadow(&drawn), (10.0, 5.0, 4.0)), "drawn {:?}", drawn_shadow(&drawn));
let out = baked(n.clone());
assert_eq!(out.geometric_bounds(), Some(b));
assert!(close(drawn_shadow(&out.appearance.effects), (10.0, 5.0, 4.0)), "baked {:?}", drawn_shadow(&out.appearance.effects));
// A hidden shadow keeps its values too, once shown.
let mut hidden = shadow(10.0, 5.0, 4.0);
hidden.visible = false;
let out = baked(path_node(31, path.clone(), vec![hidden, thousandfold()]));
let mut shown = out.appearance.effects.clone();
shown.iter_mut().for_each(|e| e.visible = true);
assert!(close(drawn_shadow(&shown), (10.0, 5.0, 4.0)), "shown {:?}", drawn_shadow(&shown));
// A fill's own shadow before its own Transform effect stays too.
let mut fill = path_node(35, path.clone(), vec![]);
if let Some(item) = fill.appearance.items.first_mut() {
*item.effects_mut() = vec![shadow(10.0, 5.0, 4.0), thousandfold()];
}
let out = baked(fill);
assert!(near(&shadows_in(&out), &[(10.0, 5.0)]), "baked fill {:?}", shadows_in(&out));
// Within the budget, both move.
let doubled = path_node(32, path.clone(), vec![shadow(10.0, 5.0, 4.0), transform(json!({"scaleH": 200, "scaleV": 200}))]);
let (g, carry) = apply_geometry_carrying(&doubled.appearance.effects, &path, b, &GeomContext::of(&doubled));
assert!(g != path && !carry.skipped());
let out = baked(doubled);
assert!(close(drawn_shadow(&out.appearance.effects), (20.0, 10.0, 8.0)), "baked {:?}", drawn_shadow(&out.appearance.effects));
}
/// The art of a path whose Transform effect is left out past the budget ([`crate::shape_art`],
/// as a group's or a mask's member is drawn) keeps the object's shadow and its fill's shadow with
/// their own offsets.
#[test]
fn the_shape_art_of_a_skipped_transform_keeps_its_shadows() {
let mut n = path_node(34, wavy(30_000), vec![shadow(10.0, 5.0, 4.0), thousandfold()]);
if let Some(item) = n.appearance.items.first_mut() {
*item.effects_mut() = vec![shadow(1.0, 0.5, 0.0)];
}
let art = crate::shape_art(None, &n, None).unwrap();
assert!(near(&shadows_in(&art), &[(10.0, 5.0), (1.0, 0.5)]), "{:?}", shadows_in(&art));
}
/// A path whose own Transform effect is left out past the budget, in a group whose geometry effect
/// (a move, which leaves offsets as they are) runs after its members' own, is drawn with its shadow
/// at its own offset; one within the budget scales the shadow with the path.
#[test]
fn a_members_skipped_transform_keeps_its_shadow_under_its_groups_effects() {
for (last, want) in [(thousandfold(), (10.0, 5.0)), (transform(json!({"scaleH": 200, "scaleV": 200})), (20.0, 10.0))] {
let member = path_node(38, wavy(30_000), vec![shadow(10.0, 5.0, 4.0), last.clone()]);
let g = group(37, vec![member], vec![transform(json!({"moveH": 5, "moveV": 5}))]);
let art = crate::evaluate_container(None, &g).unwrap();
assert!(near(&shadows_in(&node_in(&art, 38)), &[want]), "{last:?}: {:?}", shadows_in(&node_in(&art, 38)));
}
}
/// Of two Transform effects after a shadow, the shadow follows only the ones that ran: the first
/// left out past the budget, or hidden, and the second within it; and both when the first's
/// result is exactly at the limit.
#[test]
fn only_transforms_that_ran_move_a_preceding_shadow() {
let circle = shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 100.0));
let b = circle.bounds().unwrap();
let doubled = Budget::of(&circle.transformed(Affine::scale(2.0))).lines;
assert!(doubled > Budget::of(&circle).lines);
let run = |effects: &[Effect], lines: usize| {
let mut carry = Carry::default();
apply_geometry_carrying_within(effects, &circle, b, &GeomContext::default(), Budget { anchors: 1000, lines }, Some(&mut carry));
let mut drawn = effects.to_vec();
carry.hide_skipped(&mut drawn);
drawn_shadow(&drawn)
};
let effects = vec![shadow(10.0, 0.0, 4.0), transform(json!({"scaleH": 200, "scaleV": 200})), transform(json!({"rotate": 90}))];
// Turned 90° counterclockwise on screen, (10, 0) goes to (0, -10).
let only_turned = run(&effects, doubled - 1);
assert!(only_turned.0.abs() < 1e-9 && (only_turned.1 + 10.0).abs() < 1e-9 && (only_turned.2 - 4.0).abs() < 1e-9, "{only_turned:?}");
let both = run(&effects, doubled);
assert!(both.0.abs() < 1e-9 && (both.1 + 20.0).abs() < 1e-9 && (both.2 - 8.0).abs() < 1e-9, "{both:?}");
let mut hidden = effects.clone();
hidden[1].visible = false;
let turned = run(&hidden, doubled);
assert!(turned.0.abs() < 1e-9 && (turned.1 + 10.0).abs() < 1e-9 && (turned.2 - 4.0).abs() < 1e-9, "{turned:?}");
}
/// A fill's own Transform effect left out past the budget, after a Transform effect of that fill
/// that makes it a piece of its own (Transform Patterns), leaves the piece and the shadow before it
/// as they were. One within the budget scales both.
#[test]
fn a_skipped_item_transform_keeps_its_shadow() {
let path = wavy(30_000);
let b = path.bounds().unwrap();
for (last, want) in [(thousandfold(), (10.0, 5.0)), (transform(json!({"scaleH": 200, "scaleV": 200})), (20.0, 10.0))] {
let mut n = path_node(33, path.clone(), vec![]);
if let Some(item) = n.appearance.items.first_mut() {
*item.effects_mut() = vec![transform(json!({"patterns": true})), shadow(10.0, 5.0, 4.0), last.clone()];
}
let art = crate::reshape(None, &n, None).unwrap();
assert!(near(&shadows_in(&art), &[want]), "{last:?}: {:?}", shadows_in(&art));
if want == (10.0, 5.0) {
assert_eq!(art.geometric_bounds(), Some(b), "the piece stays where it is");
}
// The same with the Transform effect before the one that makes the piece.
let mut n = path_node(36, path.clone(), vec![]);
if let Some(item) = n.appearance.items.first_mut() {
*item.effects_mut() = vec![shadow(10.0, 5.0, 4.0), last.clone(), transform(json!({"patterns": true}))];
}
let art = crate::reshape(None, &n, None).unwrap();
assert!(near(&shadows_in(&art), &[want]), "{last:?} first: {:?}", shadows_in(&art));
}
}
/// A group's Transform effect moves each member's shadow as it moves that member: the member whose
/// result would pass what the budget leaves keeps its shape and its shadow, and the other takes
/// both.
#[test]
fn a_group_transform_follows_only_the_members_it_moved() {
let small = path_node(41, shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), vec![shadow(1.0, 0.5, 0.0)]);
let large = path_node(42, wavy(30_000), vec![shadow(1.0, 0.5, 0.0)]);
let g = group(40, vec![small, large], vec![thousandfold()]);
let art = crate::evaluate_container(None, &g).unwrap();
assert!(near(&shadows_in(&node_in(&art, 41)), &[(1000.0, 500.0)]), "{:?}", shadows_in(&node_in(&art, 41)));
assert!(near(&shadows_in(&node_in(&art, 42)), &[(1.0, 0.5)]), "{:?}", shadows_in(&node_in(&art, 42)));
}
/// A Transform effect that makes copies, or has Transform Objects off, keeps its own rule for the
/// shadow before it, past the budget or not: the shadow stays as it is, and the pass does not
/// report it as left out.
#[test]
fn copying_and_object_disabled_transforms_keep_their_existing_shadow_rules() {
let path = wavy(30_000);
let b = path.bounds().unwrap();
for t in [
transform(json!({"scaleH": 100000, "scaleV": 100000, "copies": 1})),
transform(json!({"scaleH": 100000, "scaleV": 100000, "objects": false})),
] {
let effects = vec![shadow(10.0, 5.0, 4.0), t.clone()];
let (_, carry) = apply_geometry_carrying(&effects, &path, b, &GeomContext::default());
assert!(!carry.skipped(), "{t:?}");
assert!(close(drawn_shadow(&effects), (10.0, 5.0, 4.0)), "{t:?}: {:?}", drawn_shadow(&effects));
}
}
+74
View File
@@ -0,0 +1,74 @@
//! A live-effect plug-in before a fill's or stroke's own 3D effect is told which fill or stroke it
//! is on, in the drawn art, the exported meshes and the wireframe.
use serde_json::json;
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, Effect, FillLayer, Node, NodeId};
use vectorcraft_geom::{PathData, Rect, shapes};
use vectorcraft_plugins::wat as tpl;
use crate::{EXTRUDE, solid_art, three_d_meshes_in, three_d_wireframe_in};
/// Widths the plug-in's squares are drawn at: `LARGE` when it is told it is on the item it looks
/// for, `SMALL` otherwise.
const LARGE: f64 = 600.0;
const SMALL: f64 = 6.0;
/// A rectangle with a fill, a 1 pt stroke and a second fill on top. The item at `at` (an index in
/// its appearance items) has, in its own effects, live-effect plug-in `name` and then Extrude &
/// Bevel. The plug-in returns a `LARGE` square when it is given `item`, and a `SMALL` one otherwise.
fn plugin_then_extrude(name: &str, at: usize, item: &str) -> Node {
let square = |w: f64| shapes::rectangle(Rect::new(0.0, 0.0, w, w));
let id = format!("test.effects.solidcontext.{name}");
let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"effect","params":{{}}}}"#);
let (large, small) = (json!({"objects": [{"path": square(LARGE)}]}).to_string(), json!({"objects": [{"path": square(SMALL)}]}).to_string());
let module = wat::parse_str(tpl::when_given_else(&manifest, tpl::Given::Params, item, &large, &small)).unwrap();
vectorcraft_plugins::registry::install_bytes(&module).unwrap();
let mut appearance = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::BLACK), 1.0);
appearance.items.push(AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)))));
let effects = appearance.items[at].effects_mut();
effects.push(Effect { id: format!("plugin.{id}"), params: json!({}), visible: true });
effects.push(crate::new_effect(EXTRUDE, &json!({})).unwrap());
Node::path(NodeId(7), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), appearance)
}
/// The width of the union of `paths`' bounds.
fn width(paths: impl IntoIterator<Item = PathData>) -> f64 {
paths.into_iter().filter_map(|p| p.bounds()).reduce(|a, b| a.union(b)).map_or(0.0, |b| b.width())
}
/// Whether each of the art, the meshes and the wireframe `n`'s 3D effect draws is wider than half
/// of `LARGE`, with the widths.
fn drawn_large(n: &Node) -> ([bool; 3], [f64; 3]) {
let art = solid_art(n).unwrap();
let mut paths = vec![];
art.walk(&mut |c| paths.extend(c.path_data().cloned()));
let meshes = three_d_meshes_in(None, n).unwrap();
let xs = meshes.iter().flat_map(|m| m.mesh.positions.iter().map(|p| p[0]));
let mesh_width = xs.clone().fold(f64::NEG_INFINITY, f64::max) - xs.fold(f64::INFINITY, f64::min);
let widths = [width(paths), mesh_width, width(three_d_wireframe_in(None, n).unwrap())];
(widths.map(|w| w > LARGE / 2.0), widths)
}
/// A plug-in before the second fill's Extrude & Bevel is given `{"fill": 1}`, not `"object"`, so
/// the art, meshes and wireframe are all built from the square it returns for that fill.
#[test]
fn a_plugin_before_a_fills_extrude_is_told_its_fill() {
let (large, widths) = drawn_large(&plugin_then_extrude("fill", 2, r#""item":{"fill":1}"#));
assert_eq!(large, [true; 3], "the art, meshes and wireframe are {widths:?} wide");
}
/// A plug-in before the stroke's Extrude & Bevel is given `{"stroke": 0}`.
#[test]
fn a_plugin_before_a_strokes_extrude_is_told_its_stroke() {
let (large, widths) = drawn_large(&plugin_then_extrude("stroke", 1, r#""item":{"stroke":0}"#));
assert_eq!(large, [true; 3], "the art, meshes and wireframe are {widths:?} wide");
}
/// A plug-in on a fill is not told it is on the object: the square it returns otherwise is the one
/// extruded.
#[test]
fn a_plugin_on_a_fill_is_not_told_it_is_on_the_object() {
let (large, widths) = drawn_large(&plugin_then_extrude("object", 2, r#""item":"object""#));
assert_eq!(large, [false; 3], "the art, meshes and wireframe are {widths:?} wide");
}
+34 -7
View File
@@ -46,7 +46,7 @@ pub mod importmatches;
pub(crate) mod inline;
mod interactivity;
mod intertwine;
mod layer;
pub(crate) mod layer;
mod layerpanel;
pub mod library;
pub mod linkfiles;
@@ -82,7 +82,7 @@ pub mod rasterfx;
mod recolor;
pub mod recovery;
pub mod scripts;
mod select;
pub(crate) mod select;
pub(crate) mod shaper;
pub mod shortcutset;
pub(crate) mod slices;
@@ -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),
}
}
@@ -777,7 +802,9 @@ pub(crate) fn unique_name_from(base: &str, next: &mut std::collections::HashMap<
/// The most presets one presets file imports: each is looked up among the saved ones.
pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000;
pub(crate) use addons::DecodedImages;
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;
+1 -1
View File
@@ -14,7 +14,7 @@ mod select;
mod shapes;
mod typetools;
pub(crate) use image::DecodedImages;
pub(crate) use image::{DecodedImages, refresh_color_masks};
use super::CommandSpec;
+20 -3
View File
@@ -20,7 +20,9 @@ use vectorcraft_doc::{Node, NodeId, OrientedBox};
use vectorcraft_geom::{Affine, Point, Rect};
use vectorcraft_render::effects;
use super::super::appearance::series_children_in_paint_order;
use super::super::edit::selected_roots;
use super::super::graph::capture_series_object_opacity;
use super::super::menucmds::whole_or;
use super::super::object::{choice, object_bounds_transform, scaling, transform_node, transform_patterns};
use super::super::typecmd::refresh_bounds_of;
@@ -90,7 +92,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Randomize Opacity",
["Object", "Plug-ins", "Arrange Tools"],
None,
"{min?: % 0..100 (30), max?: % 0..100 (100; not less than min), seed?: whole number (0; the same seed, objects and range give the same opacities), ids?: [id…] (default: the selection)} give each selected object (the top-level ones) its own opacity, picked at random and evenly from min to max, as one undo step; it is the object's opacity, as the Transparency panel sets it → {count}",
"{min?: % 0..100 (30), max?: % 0..100 (100; not less than min), seed?: whole number (0; the same seed, objects and range give the same opacities), ids?: [id…] (default: the selection)} give each selected object (the top-level ones) its own opacity, picked at random and evenly from min to max, as one undo step; it is the object's opacity, as the Transparency panel sets it. On paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw (docs/mcp.md) → {count}",
has_selection,
randomize_opacity
),
@@ -99,7 +101,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Sort Objects",
["Object", "Plug-ins", "Arrange Tools"],
None,
"{by?: \"width\" | \"height\" | \"area\" (width × height) | \"x\" (left edge) | \"y\" (top edge) | \"opacity\" (%) | \"stacking\" (stacking order, from the back) (\"area\"), apply?: one of the same (\"stacking\"), order?: \"ascending\" (small to large) | \"descending\" (large to small) | \"random\" (\"ascending\"), distribute?: false (true: the values step evenly from the smallest to the largest; false: the objects trade the values they have), seed?: whole number (0; the order \"random\" picks), scaleStrokes?: the Scale Strokes & Effects preference (width, height and area), ids?: [id…] (default: the selection)} sort the selected objects (the top-level ones, at most 20000) by the attribute `by` and give them the values of `apply` in that order, as one undo step: the first in order gets the smallest value. Sizes and places are measured and set as object.setBounds measures them (Use Preview Bounds), a width, height or area about each object's centre (an area in proportion); stacking order always trades places, and only among the objects in the same layer or group. A run that changes nothing makes no step → {count}",
"{by?: \"width\" | \"height\" | \"area\" (width × height) | \"x\" (left edge) | \"y\" (top edge) | \"opacity\" (%) | \"stacking\" (stacking order, from the back) (\"area\"), apply?: one of the same (\"stacking\"), order?: \"ascending\" (small to large) | \"descending\" (large to small) | \"random\" (\"ascending\"), distribute?: false (true: the values step evenly from the smallest to the largest; false: the objects trade the values they have), seed?: whole number (0; the order \"random\" picks), scaleStrokes?: the Scale Strokes & Effects preference (width, height and area), ids?: [id…] (default: the selection)} sort the selected objects (the top-level ones, at most 20000) by the attribute `by` and give them the values of `apply` in that order, as one undo step: the first in order gets the smallest value. Sizes and places are measured and set as object.setBounds measures them (Use Preview Bounds), a width, height or area about each object's centre (an area in proportion); stacking order always trades places, and only among the objects in the same layer or group. With apply \"opacity\", on paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw (docs/mcp.md). A run that changes nothing makes no step → {count}",
has_multi,
sort
),
@@ -396,17 +398,30 @@ fn randomize_opacity(s: &mut Session, p: &Value) -> Result<Value> {
}
let (lo, hi) = ((min / 100.0) as f32, (max / 100.0) as f32);
s.edit("Randomize Opacity", |d, _| {
let mut changed = vec![];
for id in &ids {
let o = rng.range(lo, hi);
if let Some(n) = d.node_mut(*id) {
if let Some(n) = d.node_mut(*id)
&& n.opacity != o
{
n.opacity = o;
changed.push(*id);
}
}
keep_series_opacity(d, &changed);
Ok(())
})?;
Ok(json!({ "count": ids.len() }))
}
/// Store on their graphs the opacity just given to the paths among `changed` (objects whose opacity changed) that are
/// directly in a graph series, with their blend mode, so that every path of the series has them when the graph is drawn
/// again; the frontmost of them in a series sets them.
fn keep_series_opacity(d: &mut vectorcraft_doc::Document, changed: &[NodeId]) {
let marks = series_children_in_paint_order(d, changed);
capture_series_object_opacity(d, &marks);
}
/// An object Sort Objects sorts: its layer or group, its place in it, its box as
/// `object.setBounds` measures it and its opacity (%).
struct Sorted {
@@ -510,6 +525,8 @@ fn sort(s: &mut Session, p: &Value) -> Result<Value> {
n.opacity = (v / 100.0) as f32;
}
}
let changed: Vec<NodeId> = wanted.iter().filter(|(o, v)| (o.opacity - v).abs() >= 1e-6).map(|(o, _)| o.id).collect();
keep_series_opacity(d, &changed);
Ok(())
})?;
return Ok(count);
+35 -13
View File
@@ -10,7 +10,7 @@ use vectorcraft_geom::{PathData, Point, Rect};
use vectorcraft_pathops::addons as po;
use super::super::super::edit::outermost;
use super::super::super::layer::empty_artboards;
use super::super::super::layer::{empty_artboards, remove_artboards};
use crate::Result;
/// Sine of the turn below which an anchor on a straight run is collinear.
@@ -369,11 +369,7 @@ fn restructure(d: &mut Document, scope: &mut Scope, kind: Kind) -> Result<Outcom
break;
}
if let Scope::Objects(roots) = scope {
for (id, nodes) in &found {
if let Some(at) = roots.iter().position(|r| r == id) {
roots.splice(at..=at, nodes.iter().map(|n| n.id));
}
}
*roots = replace_roots(roots, &found);
}
out.ids.extend(found.iter().map(|(id, _)| *id));
d.insert_beside(found, true)?;
@@ -382,6 +378,36 @@ fn restructure(d: &mut Document, scope: &mut Scope, kind: Kind) -> Result<Outcom
Ok(out)
}
#[cfg(test)]
thread_local! {
/// Tests: how many scope roots [`replace_roots`] looked at on this thread.
pub(super) static ROOTS_SEEN: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// The scope's objects after a pass replaced `found`: each found object gives way to the ids of
/// what replaces it, in its place, and the others keep their order. An id that `roots` lists more
/// than once is replaced at its first places, once for each time `found` lists it. One walk of
/// `roots`.
pub(super) fn replace_roots(roots: &[NodeId], found: &[(NodeId, Vec<Node>)]) -> Vec<NodeId> {
let mut with: HashMap<NodeId, (&[Node], usize)> = HashMap::with_capacity(found.len());
for (id, nodes) in found {
with.entry(*id).or_insert((nodes.as_slice(), 0)).1 += 1;
}
let mut out = Vec::with_capacity(roots.len());
for r in roots {
#[cfg(test)]
ROOTS_SEEN.set(ROOTS_SEEN.get() + 1);
match with.get_mut(r) {
Some((nodes, left)) if *left > 0 => {
*left -= 1;
out.extend(nodes.iter().map(|n| n.id));
}
_ => out.push(*r),
}
}
out
}
/// Run `f` on a copy of each path in scope (not guides), and keep the copies it changed: `f`
/// returns how many issues it fixed.
fn reshape(d: &mut Document, scope: &Scope, f: impl Fn(&Node, &mut PathData) -> usize) -> Result<Outcome> {
@@ -479,13 +505,9 @@ fn near_points(d: &mut Document, scope: &Scope) -> Result<Outcome> {
fn artboards(d: &mut Document, sel: &mut Selection, scope: &Scope) -> Result<Outcome> {
let Scope::Document = scope else { return Ok(Outcome::default()) };
let empty = empty_artboards(d);
// The last first, so the others keep their places.
for &i in empty.iter().rev() {
if i < d.artboards.len() {
let id = d.artboards.remove(i).id;
d.retire_artboard_id(id);
d.retain_guides(sel, |g| g.artboard != Some(id));
}
if empty.is_empty() {
return Ok(Outcome::default());
}
remove_artboards(d, sel, &empty)?;
Ok(Outcome { count: empty.len(), ids: vec![], artboards: empty })
}
@@ -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();
@@ -362,6 +389,150 @@ fn the_scope_is_the_selection_or_the_document() {
}
}
/// The ids of the first layer's objects, bottom to top.
fn layer_ids(s: &Session) -> Vec<NodeId> {
match &s.doc().unwrap().doc.layers[0].kind {
NodeKind::Layer { children, .. } => children.iter().map(|c| c.id).collect(),
other => panic!("not a layer: {other:?}"),
}
}
/// A plain group of the one object `id`.
fn group(s: &mut Session, id: NodeId) -> NodeId {
wrap(s, id, |children| NodeKind::Group { children, clip: false })
}
#[test]
fn unwrapping_selected_groups_keeps_their_places_and_order() {
let mut s = session();
let c1 = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
let a = rect(&mut s, 40.0, 10.0, 20.0, 20.0);
let g1 = group(&mut s, a);
let c2 = rect(&mut s, 70.0, 10.0, 20.0, 20.0);
let empty = s
.edit("t", |d, _| {
let (parent, i, _) = d.position(c2).unwrap();
let g = d.alloc_id();
Ok(d.insert(parent, i + 1, Node::new(g, NodeKind::Group { children: vec![], clip: false }))?)
})
.unwrap();
let c3 = rect(&mut s, 100.0, 10.0, 20.0, 20.0);
let b = rect(&mut s, 130.0, 10.0, 20.0, 20.0);
let inner = group(&mut s, b);
let outer = group(&mut s, inner);
let c4 = rect(&mut s, 160.0, 10.0, 20.0, 20.0);
let x = rect(&mut s, 190.0, 10.0, 20.0, 20.0);
let unselected = group(&mut s, x);
assert_eq!(layer_ids(&s), [c1, g1, c2, empty, c3, outer, c4, unselected]);
select(&mut s, &[c1, g1, c2, empty, c3, outer, c4]);
let check = s.execute("addon.cleanup.check", &json!({"kinds": ["needlessGroups"], "scope": "selection"})).unwrap();
let r = s.execute("addon.cleanup.fix", &json!({"kinds": ["needlessGroups"], "scope": "selection"})).unwrap();
// The inner group is found only once its outer group is gone: on a later pass, as a root.
assert_eq!(r["fixed"]["needlessGroups"], 4, "{r}");
assert_eq!(check["total"], 4, "the check finds what Fix fixes: {check}");
let mut listed: Vec<u64> = check["findings"][0]["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
listed.sort_unstable();
let mut gone: Vec<u64> = [g1, empty, outer, inner].iter().map(|i| i.0).collect();
gone.sort_unstable();
assert_eq!(listed, gone);
assert_eq!(layer_ids(&s), [c1, a, c2, c3, b, c4, unselected], "each member takes its group's place");
for id in [g1, empty, outer, inner] {
assert!(node(&s, id).is_none(), "{id:?} unwrapped");
}
}
#[test]
fn fix_all_reaches_the_members_of_unwrapped_selected_groups() {
let mut s = session();
rect(&mut s, 200.0, 20.0, 80.0, 60.0);
let below = rect(&mut s, 20.0, 150.0, 30.0, 30.0);
let copy = s
.edit("t", |d, _| {
let mut copy = d.node(below).unwrap().clone();
copy.id = d.alloc_id();
let (parent, i, _) = d.position(below).unwrap();
Ok(d.insert(parent, i + 1, copy)?)
})
.unwrap();
let g = group(&mut s, copy);
select(&mut s, &[below, g]);
// The copy sits apart from the object it doubles until its group is unwrapped.
assert_eq!(found(&mut s, "duplicateObjects", "selection"), 0);
assert_eq!(found(&mut s, "needlessGroups", "selection"), 1);
let r = s.execute("addon.cleanup.fix", &json!({"scope": "selection"})).unwrap();
assert_eq!((r["fixed"]["needlessGroups"].as_u64(), r["fixed"]["duplicateObjects"].as_u64()), (Some(1), Some(1)), "{r}");
assert!(node(&s, g).is_none() && node(&s, copy).is_none());
assert!(node(&s, below).is_some());
}
#[test]
fn replacing_roots_takes_each_found_object_at_its_first_place() {
use super::checks::replace_roots;
let n = |id: u64| Node::new(NodeId(id), NodeKind::Group { children: vec![], clip: false });
let ids = |v: &[u64]| v.iter().map(|i| NodeId(*i)).collect::<Vec<_>>();
let roots = ids(&[1, 2, 1, 3]);
assert_eq!(replace_roots(&roots, &[(NodeId(1), vec![n(10), n(11)])]), ids(&[10, 11, 2, 1, 3]));
assert_eq!(replace_roots(&roots, &[(NodeId(1), vec![]), (NodeId(1), vec![])]), ids(&[2, 3]), "listed twice: both places");
assert_eq!(replace_roots(&roots, &[(NodeId(3), vec![]), (NodeId(2), vec![n(20)])]), ids(&[1, 20, 1]));
// A found object inside a root leaves the roots as they are.
assert_eq!(replace_roots(&roots, &[(NodeId(7), vec![n(70)])]), roots);
assert_eq!(replace_roots(&[], &[(NodeId(7), vec![])]), ids(&[]));
}
/// How many scope roots fixing `n` selected stray points above `n` selected clean objects looks at.
fn roots_seen_removing(n: usize) -> usize {
use super::checks::ROOTS_SEEN;
let mut s = session();
let mut ids: Vec<NodeId> = (0..n).map(|i| rect(&mut s, (i % 20) as f64 * 15.0, (i / 20) as f64 * 15.0, 10.0, 10.0)).collect();
ids.extend((0..n).map(|i| path(&mut s, json!([{"x": i % 300, "y": i / 300}]), false)));
select(&mut s, &ids);
ROOTS_SEEN.set(0);
let r = s.execute("addon.cleanup.fix", &json!({"kinds": ["strayPoints"], "scope": "selection"})).unwrap();
assert_eq!(r["total"].as_u64(), Some(n as u64));
assert_eq!(layer_ids(&s), ids[..n]);
ROOTS_SEEN.get()
}
#[test]
fn removing_many_selected_objects_looks_at_each_root_once_a_pass() {
let (small, large) = (roots_seen_removing(150), roots_seen_removing(300));
assert_eq!(small, 300, "one pass over the 300 roots");
assert!(large <= 2 * small, "{small} roots looked at for 150 removals, {large} for 300");
}
#[test]
fn deleting_many_empty_artboards_walks_the_artboards_and_guides_once() {
use crate::cmd::layer::ARTBOARD_PASSES;
let mut s = session();
rect(&mut s, 200.0, 20.0, 80.0, 60.0);
let (keep, gone) = s
.edit("t", |d, _| {
let first = d.artboards[0].id;
let keep = d.add_ruler_guide(&vectorcraft_doc::Guide { artboard: Some(first), ..vectorcraft_doc::Guide::new(true, 100.0) });
let mut gone = vec![];
for i in 0..40 {
let mut a = d.artboards[0].clone();
a.id = d.next_artboard_id();
let x = 1000.0 + i as f64 * 200.0;
a.rect = Rect::new(x, 1000.0, x + 100.0, 1100.0);
gone.push(d.add_ruler_guide(&vectorcraft_doc::Guide { artboard: Some(a.id), ..vectorcraft_doc::Guide::new(true, x + 50.0) }));
d.artboards.push(a);
}
Ok((keep, gone))
})
.unwrap();
let first = s.doc().unwrap().doc.artboards[0].clone();
ARTBOARD_PASSES.set(0);
let r = s.execute("addon.cleanup.fix", &json!({"kinds": ["emptyArtboards"], "scope": "document"})).unwrap();
assert_eq!(r["total"].as_u64(), Some(40), "{r}");
assert_eq!(ARTBOARD_PASSES.get(), 2, "one walk over the artboards and one over the guides");
let d = &s.doc().unwrap().doc;
assert_eq!(d.artboards, vec![first]);
let left: Vec<Option<NodeId>> = d.ruler_guides().into_iter().map(|g| g.id).collect();
assert_eq!(left, vec![Some(keep)]);
assert!(gone.iter().all(|id| !left.contains(&Some(*id))));
}
#[test]
fn show_selects_the_objects_with_the_issue() {
let mut s = session();
+34 -7
View File
@@ -206,11 +206,31 @@ struct Source {
text: String,
}
#[cfg(test)]
thread_local! {
/// Tests: how many times [`thread_index`] went through the document's threads on this thread.
static THREAD_SCANS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Each object the document's text threads list, with the index of the first thread that lists it.
fn thread_index(d: &Document) -> std::collections::HashMap<NodeId, usize> {
#[cfg(test)]
THREAD_SCANS.with(|c| c.set(c.get() + 1));
let mut out = std::collections::HashMap::new();
for (i, thread) in d.text_threads.iter().enumerate() {
for id in thread {
out.entry(*id).or_insert(i);
}
}
out
}
impl Source {
/// Horizontal point or area type that isn't threaded and whose text all fits; None otherwise.
fn of(d: &Document, id: NodeId) -> Option<Self> {
/// Horizontal point or area type that isn't threaded (`threaded` false) and whose text all
/// fits; None otherwise.
fn of(d: &Document, id: NodeId, threaded: bool) -> Option<Self> {
let t = text_of(d, id)?;
if t.vertical || matches!(t.kind, TextKind::OnPath { .. }) || d.text_threads.iter().any(|th| th.contains(&id)) {
if t.vertical || matches!(t.kind, TextKind::OnPath { .. }) || threaded {
return None;
}
let lay = layout(t);
@@ -376,8 +396,10 @@ fn break_text(s: &mut Session, p: &Value) -> Result<Value> {
};
let d = &s.doc()?.doc;
let (mut items, mut skipped, mut count) = (vec![], vec![], 0);
for id in texts_under(d, &checked_ids_or_selection(s, p, C)?)? {
let (Some(src), Some(node)) = (Source::of(d, id), d.node(id)) else {
let ids = texts_under(d, &checked_ids_or_selection(s, p, C)?)?;
let threads = thread_index(d);
for id in ids {
let (Some(src), Some(node)) = (Source::of(d, id, threads.contains_key(&id)), d.node(id)) else {
skipped.push(id);
continue;
};
@@ -405,7 +427,8 @@ fn split_text(s: &mut Session, _: &Value) -> Result<Value> {
return Err(EngineError::Other("Click in type with a Type tool to split it".into()));
};
let d = &s.doc()?.doc;
let (Some(src), Some(node)) = (Source::of(d, id), d.node(id).filter(|_| d.is_editable(id))) else {
let threaded = d.text_threads.iter().any(|th| th.contains(&id));
let (Some(src), Some(node)) = (Source::of(d, id, threaded), d.node(id).filter(|_| d.is_editable(id))) else {
return Err(EngineError::Other("Select horizontal point or area type whose text fits".into()));
};
let text = &src.text;
@@ -821,13 +844,17 @@ fn remove_breaks(s: &mut Session, p: &Value) -> Result<Value> {
let ids = texts_under(d, &checked_ids_or_selection(s, p, C)?)?;
// A threaded story whose frames are all among them is read as one text, once.
let named: std::collections::HashSet<NodeId> = ids.iter().copied().collect();
let threads = thread_index(d);
let mut done = std::collections::HashSet::new();
let mut out: Vec<(NodeId, Vec<(usize, bool)>)> = vec![];
for &id in &ids {
if !done.insert(id) {
continue;
}
let story = crate::cmd::threads::story_of(d, id);
let story = match threads.get(&id).and_then(|&i| d.text_threads.get(i)) {
Some(thread) => crate::cmd::threads::story_in(d, thread, id),
None => vec![],
};
if !story.is_empty() && story.iter().all(|f| named.contains(f)) {
done.extend(story.iter().copied());
out.extend(story_cuts(d, &story, brk));
Loaded 100 of 804 files, more files were not shown because too many files have changed in this diff. Show more