Merge remote-tracking branch 'upstream/main' into feat/view-zoom-to-selection-5601

# Conflicts:
#	docs/ui-parity.md
This commit is contained in:
Don Omondi committed 2026-11-05 19:49:16 -05:00
commit 3338f1ab85
270 files changed
+21349 -1530

No files matched your search

Generated
+3
View File
@@ -6100,6 +6100,7 @@ dependencies = [
"serde_json",
"smithay-clipboard",
"socket2",
"tempfile",
"vectorcraft-engine",
"vectorcraft-render",
"vectorcraft-text",
@@ -6163,6 +6164,7 @@ dependencies = [
"objc2-core-foundation",
"objc2-core-text",
"serde_json",
"tempfile",
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-engine",
@@ -6469,6 +6471,7 @@ dependencies = [
"vectorcraft-doc",
"vectorcraft-effects",
"vectorcraft-geom",
"vectorcraft-pathops",
"vectorcraft-testkit",
"vectorcraft-text",
]
+1
View File
@@ -45,5 +45,6 @@ objc2-core-foundation = { version = "0.3", default-features = false, features =
objc2-core-text = { version = "0.3", default-features = false, features = ["std", "CTFontManager"] }
[dev-dependencies]
tempfile = "3"
vectorcraft-testkit = { workspace = true }
serde_json = { workspace = true }
+45 -19
View File
@@ -2,9 +2,9 @@
//!
//! ```text
//! vectorcraft-cli mcp [--connect 127.0.0.1:7979 | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]...
//! vectorcraft-cli run [--in FILE] [--cmd id [--params '{json}'] | --commands FILE|-]... [--export out.svg]... [--scale 2]
//! vectorcraft-cli run [--in FILE] [--cmd id [--params '{json}'] | --commands FILE|-]... [--export out.svg]... [--scale 2] [--ppi 300]
//! vectorcraft-cli commands
//! vectorcraft-cli convert IN OUT [--scale 2] [--artboard 0 | --range 1-3,5] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
//! vectorcraft-cli convert IN OUT [--scale 2] [--ppi 300] [--artboard 0 | --range 1-3,5] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
//! vectorcraft-cli info FILE
//! vectorcraft-cli bench FILE [--size 2880x1800] [--iters 5]
//! vectorcraft-cli perf [--paths 50000] [--deep]
@@ -81,11 +81,12 @@ USAGE:
allowed, and a kind left out grants none of its access. They imply --headless: a running app
enforces its own (vectorcraft --control PORT --automation-read-root DIR …).
vectorcraft-cli run [--in FILE] [--cmd ID [--params JSON] | --commands FILE|-]... [--export FILE]... [--scale N]
vectorcraft-cli run [--in FILE] [--cmd ID [--params JSON] | --commands FILE|-]... [--export FILE]... [--scale N] [--ppi N]
Headless batch: open FILE (any readable format) or start a new document, run commands in
order, export each FILE in the format its extension picks (see Writable formats; a .ait FILE
is a template, written as file.saveAsTemplate writes it). --scale sizes raster exports
(pixels per point, default 1); other formats leave it out. Prints one JSON result per step.
is a template, written as file.saveAsTemplate writes it). Raster exports use the document's
raster effects resolution unless --scale (pixels per point) or --ppi (pixels per inch, wins
over --scale) is given; other formats leave them out. Prints one JSON result per step.
--commands reads steps from FILE, or from standard input for -, where it stands among the
--cmd and --export steps: a JSON array of {\"command\": ID, \"params\": {...}} (or \"id\" for
\"command\"), or one such object per line (JSON Lines), at most 64 MiB and 100000 steps.
@@ -94,10 +95,10 @@ USAGE:
vectorcraft-cli commands
Print the command catalogue as JSON.
vectorcraft-cli convert IN OUT [--scale N] [--artboard I | --range R] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
vectorcraft-cli convert IN OUT [--scale N] [--ppi N] [--artboard I | --range R] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
Open IN (any readable format) and export OUT in the format its extension picks (see Writable
formats). --scale sizes a raster OUT (pixels per point, default 1); other formats leave it
out. --artboard is 0-based, --range 1-based (\"1-3,5\"); a PDF gets every artboard
formats). Raster resolution: --ppi, else 72 times --scale, else the document's raster effects
resolution; other formats leave them out. --artboard is 0-based, --range 1-based (\"1-3,5\"); a PDF gets every artboard
unless one of them is given, EPS the bounds of the art, the other formats the first artboard.
A .ait OUT is a template of every artboard, written as file.saveAsTemplate writes it (not with
--artboard or --range).
@@ -279,13 +280,15 @@ fn commands() -> Result<(), String> {
}
fn convert(args: &[String]) -> Result<(), String> {
let valued = ["--scale", "-s", "--artboard", "-a", "--range", "-r", "--decimals", "--ai-version", "--hidden-objects", "--transparent-images"];
let valued =
["--scale", "-s", "--ppi", "--artboard", "-a", "--range", "-r", "--decimals", "--ai-version", "--hidden-objects", "--transparent-images"];
if help_requested(args, &valued) {
return help();
}
let mut files = vec![];
let (mut scale, mut artboard, mut range, mut outline_text, mut replace_lossy, mut editing_data, mut preserve_editing) =
(1.0f64, None::<u64>, None::<String>, false, false, false, false);
(None::<f64>, None::<u64>, None::<String>, false, false, false, false);
let mut ppi = None::<f64>;
let mut decimals = None::<u64>;
// Legacy `.ai` options, passed on as the export's own (`aiVersion`, `hiddenObjects`,
// `transparentImages`); the engine checks their values.
@@ -293,7 +296,15 @@ fn convert(args: &[String]) -> Result<(), String> {
let mut it = args.iter();
while let Some(a) = it.next() {
match a.as_str() {
"--scale" | "-s" => scale = it.next().and_then(|v| v.parse().ok()).ok_or("--scale needs a number")?,
"--scale" | "-s" => scale = Some(it.next().and_then(|v| v.parse().ok()).ok_or("--scale needs a number")?),
"--ppi" => {
ppi = Some(
it.next()
.and_then(|v| v.parse().ok())
.filter(|n: &f64| n.is_finite() && *n > 0.0)
.ok_or("--ppi needs a positive finite number")?,
);
}
"--artboard" | "-a" => artboard = Some(it.next().and_then(|v| v.parse().ok()).ok_or("--artboard needs an index")?),
"--range" | "-r" => range = Some(it.next().cloned().ok_or("--range needs artboards such as 1-3,5")?),
"--outline-text" => outline_text = true,
@@ -326,7 +337,7 @@ fn convert(args: &[String]) -> Result<(), String> {
// 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 mut params = with_pixel_scale(params, &output, scale);
let mut params = with_pixel_scale(params, &output, scale, ppi);
if let Some(decimals) = decimals {
params["decimals"] = json!(decimals);
}
@@ -372,12 +383,17 @@ fn is_template(path: &str) -> bool {
vectorcraft_engine::cmd::fileio::format_for_name(path).is_some_and(|f| f.id == "ait")
}
/// The export `params` for `path`, with `--scale` (pixels per point) when its format is raster.
/// The export `params` for `path`, with explicit raster resolution options only for raster formats.
/// DXF has a `scale` of its own (drawing units per unit), which would resize the drawing and leave
/// its units unset.
fn with_pixel_scale(mut params: Value, path: &str, scale: f64) -> Value {
fn with_pixel_scale(mut params: Value, path: &str, scale: Option<f64>, ppi: Option<f64>) -> Value {
if vectorcraft_engine::cmd::fileio::writable_format(None, Some(path)).is_ok_and(|f| f.raster) {
params["scale"] = json!(scale);
if let Some(scale) = scale {
params["scale"] = json!(scale);
}
if let Some(ppi) = ppi {
params["ppi"] = json!(ppi);
}
}
params
}
@@ -485,7 +501,7 @@ fn command_step(v: Value) -> Result<Step, String> {
}
fn run(args: &[String]) -> Result<(), String> {
let valued = ["--in", "-i", "--cmd", "-c", "--params", "-p", "--commands", "--export", "-o", "--scale", "-s"];
let valued = ["--in", "-i", "--cmd", "-c", "--params", "-p", "--commands", "--export", "-o", "--scale", "-s", "--ppi"];
if help_requested(args, &valued) {
return help();
}
@@ -494,7 +510,8 @@ fn run(args: &[String]) -> Result<(), String> {
// The step of the `--cmd` just given, which a `--params` sets.
let mut params_for: Option<usize> = None;
let mut stdin_read = false;
let mut scale = 1.0;
let mut scale = None::<f64>;
let mut ppi = None::<f64>;
let mut it = args.iter();
while let Some(a) = it.next() {
let mut val = |what: &str| it.next().cloned().ok_or_else(|| format!("{a} needs {what}"));
@@ -531,7 +548,16 @@ fn run(args: &[String]) -> Result<(), String> {
}
"--scale" | "-s" => {
let raw = val("a number")?;
scale = raw.parse::<f64>().map_err(|_| format!("--scale {raw}: not a number"))?;
scale = Some(raw.parse::<f64>().map_err(|_| format!("--scale {raw}: not a number"))?);
}
"--ppi" => {
let raw = val("a number")?;
ppi = Some(
raw.parse::<f64>()
.ok()
.filter(|n| n.is_finite() && *n > 0.0)
.ok_or_else(|| format!("--ppi {raw}: needs a positive finite number"))?,
);
}
other => return Err(format!("unknown run option `{other}`")),
}
@@ -576,7 +602,7 @@ fn run(args: &[String]) -> Result<(), String> {
let r = if is_template(&path) {
h.call("engine.execute", json!({"command": "file.saveAsTemplate", "params": {"path": path, "format": "ait"}}))
} else {
h.call("app.export", with_pixel_scale(json!({"path": path}), &path, scale))
h.call("app.export", with_pixel_scale(json!({"path": path}), &path, scale, ppi))
};
let r = r.map_err(|e| format!("step {n}: export {path}: {e}"))?;
emit(json!({"step": "export", "result": r}))?;
+44
View File
@@ -187,6 +187,48 @@ fn budget_row(name: &str, ms: f64, budget: f64, ok: bool) -> String {
format!(" {name:<42} {ms:>8.2} ms {budget:>7.0} ms {}", if ok { "ok" } else { "OVER" })
}
/// Tracked rows for pointing at things in an n-path document: what hovering, clicking, marquee
/// selection and snapping cost when nothing narrows the search.
fn pointing(n: usize, rows: &mut Vec<(String, f64)>) -> Result<(), String> {
use vectorcraft_engine::tools::{Mods, PointerEvent, PointerKind};
let err = |e: vectorcraft_engine::EngineError| e.to_string();
let mut s = vectorcraft_engine::Session::new();
s.add_document(synthetic(n)?, None);
let view = vectorcraft_engine::ViewInfo { zoom: 1.0, ..Default::default() };
s.select_tool("selection", view).map_err(err)?;
// Off the art (nothing under the pointer), the case every hover over empty canvas pays.
let off = Point::new(-200.0, -200.0);
let hover = |s: &mut vectorcraft_engine::Session| {
let _ = s.pointer(&PointerEvent::new(PointerKind::Move, off.x, off.y), view);
let _ = s.cursor(off, Mods::default(), view);
};
rows.push((format!("hover over empty canvas ({n} paths)"), median_ms(5, || hover(&mut s))));
s.execute("select.all", &json!({})).map_err(err)?;
rows.push((format!("hover over empty canvas, all selected ({n} paths)"), median_ms(5, || hover(&mut s))));
let doc = s.doc().map_err(err)?.doc.clone();
rows.push((format!("hit test, a miss ({n} paths)"), median_ms(5, || drop(hit::hit_test(&doc, off, hit::HitOptions::default())))));
let r = Rect::new(600.0, 450.0, 1000.0, 750.0);
rows.push((format!("marquee 400×300 ({n} paths)"), median_ms(5, || drop(hit::marquee(&doc, r, None, false)))));
let view_rect = Rect::new(0.0, 0.0, 1600.0, 1200.0);
rows.push((
format!("smart guide targets in view ({n} paths)"),
median_ms(5, || drop(vectorcraft_engine::tools::guides::Targets::collect(&doc, &[], Some(view_rect)))),
));
// Adding one more object to a selection of half the document: the command a shift-click ends
// in, without the pointer handling and hit test before it.
let ids: Vec<u64> = doc.layers[0].children().map(|c| c.iter().map(|n| n.id.0).collect()).unwrap_or_default();
s.execute("select.set", &json!({"ids": ids[..ids.len() / 2]})).map_err(err)?;
let mut k = ids.len() / 2;
rows.push((
format!("select.toggle in a {}-object selection", ids.len() / 2),
median_ms(5, || {
k += 1;
let _ = s.execute("select.toggle", &json!({"id": ids[k % ids.len()]}));
}),
));
Ok(())
}
/// `--deep`: tracked rows (no budget yet) for work the budgets above don't reach: editing a whole
/// selection, live effects, every Pathfinder operation, typing in a long story, and memory, with
/// the peak so far where `rss_mb` reads one.
@@ -282,6 +324,8 @@ fn deep(n: usize) -> Result<(), String> {
}),
));
note("after typing");
pointing(n, &mut rows)?;
note("after pointing");
// Four embedded 24 MP photos drawn at fit page by three renderers, as the app's canvas, render
// worker and a panel each draw them.
{
+32
View File
@@ -105,6 +105,38 @@ fn images_open_at_their_pixel_size() {
assert_eq!(&std::fs::read(&png).unwrap()[16..24], [0, 0, 0, 6, 0, 0, 0, 4], "IHDR 6×4");
}
#[test]
fn raster_exports_use_document_resolution_unless_overridden() {
let source = tmp("resolution.vectorcraft");
ok(&["run", "--cmd", "file.new", "--params", r#"{"width":72,"height":36,"rasterEffectsPpi":300}"#, "--export", &source]);
for (flags, width, height) in [(vec![], 300u32, 150u32), (vec!["--scale", "1"], 72, 36), (vec!["--ppi", "150", "--scale", "2"], 150, 75)] {
for mode in ["run", "convert"] {
for format in ["png", "psd"] {
let path = tmp(&format!("resolution-{mode}-{width}.{format}"));
let mut args = if mode == "run" { vec!["run", "--in", &source, "--export", &path] } else { vec!["convert", &source, &path] };
args.extend_from_slice(&flags);
ok(&args);
let bytes = std::fs::read(&path).unwrap();
let dimensions = if format == "png" { &bytes[16..24] } else { &bytes[14..22] };
let expected =
if format == "png" { [width.to_be_bytes(), height.to_be_bytes()] } else { [height.to_be_bytes(), width.to_be_bytes()] };
assert_eq!(dimensions, expected.concat(), "{args:?}");
}
}
}
}
#[test]
fn raster_export_rejects_invalid_ppi() {
for ppi in ["0", "-150", "NaN", "inf", "high"] {
for args in [vec!["run", "--export", "unused.png", "--ppi", ppi], vec!["convert", "unused.svg", "unused.png", "--ppi", ppi]] {
let out = Command::new(BIN).args(&args).output().unwrap();
assert!(!out.status.success(), "{args:?}");
assert!(String::from_utf8_lossy(&out.stderr).contains("positive finite number"), "{args:?}: {out:?}");
}
}
}
#[test]
fn help_lists_readable_formats() {
let out = ok(&["--help"]);
+1
View File
@@ -119,6 +119,7 @@ zbus = "=5.19.0"
winresource = "0.1"
[dev-dependencies]
tempfile = "3"
# Bound socket buffers in real loopback transport deadline regressions.
socket2 = { workspace = true }
# src/portal_save.rs's tests build and read the portal's D-Bus values on every system.
+17 -8
View File
@@ -978,10 +978,17 @@ mod tests {
use super::*;
fn dir(name: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("vectorcraft-clipboard-{name}-{}", std::process::id()));
std::fs::create_dir_all(&d).unwrap();
d
fn dir(name: &str) -> tempfile::TempDir {
tempfile::Builder::new().prefix(&format!("vectorcraft-clipboard-{name}-")).tempdir().unwrap()
}
#[test]
fn test_directory_is_removed_when_its_handle_is_dropped() {
let dir = dir("cleanup");
let path = dir.path().to_path_buf();
assert!(path.exists());
drop(dir);
assert!(!path.exists());
}
fn png(w: u32, h: u32) -> Vec<u8> {
@@ -993,12 +1000,12 @@ mod tests {
#[test]
fn the_first_copied_file_that_is_art_pastes() {
let d = dir("art");
let (notes, red, art) = (d.join("notes.txt"), d.join("red image.png"), d.join("art.svg"));
let (notes, red, art) = (d.path().join("notes.txt"), d.path().join("red image.png"), d.path().join("art.svg"));
std::fs::write(&notes, "not art").unwrap();
std::fs::write(&red, png(3, 2)).unwrap();
std::fs::write(&art, "<svg xmlns=\"http://www.w3.org/2000/svg\"/>").unwrap();
// Missing files, folders and text are skipped.
let f = copied_file(vec![d.join("gone.png"), d.clone(), notes.clone(), red.clone(), art.clone()], &PASTE_ORDER).unwrap();
let f = copied_file(vec![d.path().join("gone.png"), d.path().to_path_buf(), notes.clone(), red.clone(), art.clone()], &PASTE_ORDER).unwrap();
assert_eq!((f.mime, f.data), (PNG, png(3, 2)));
assert_eq!(copied_file(vec![art.clone(), red.clone()], &PASTE_ORDER).map(|f| f.mime), Some(SVG));
// Only what Paste asks for.
@@ -1032,7 +1039,8 @@ mod tests {
/// An .eps file copied in a file manager pastes as EPS.
#[test]
fn a_copied_eps_file_pastes() {
let eps = dir("eps").join("equation.eps");
let d = dir("eps");
let eps = d.path().join("equation.eps");
std::fs::write(&eps, "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 10 10\n0 0 10 10 rectfill\n").unwrap();
assert_eq!(copied_file(vec![eps.clone()], &PASTE_ORDER).map(|f| f.mime), Some(EPS));
assert!(copied_file(vec![eps], &[BITMAP, TEXT]).is_none());
@@ -1040,7 +1048,8 @@ mod tests {
#[test]
fn a_crlf_left_by_the_uri_list_is_ignored() {
let red = dir("crlf").join("red.png");
let d = dir("crlf");
let red = d.path().join("red.png");
std::fs::write(&red, png(2, 2)).unwrap();
let with_cr = PathBuf::from(format!("{}\r", red.display()));
assert_eq!(copied_file(vec![with_cr], &PASTE_ORDER).map(|f| f.mime), Some(PNG));
+8 -10
View File
@@ -150,18 +150,16 @@ mod tests {
#[cfg(target_os = "linux")]
#[test]
fn the_gpu_behind_a_device_number_comes_from_sysfs() -> std::io::Result<()> {
let dir = std::env::temp_dir().join(format!("vectorcraft-dev-char-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let dir = tempfile::Builder::new().prefix("vectorcraft-dev-char-").tempdir()?;
// /sys/dev/char/226:128 links to the render node, whose `device` is the PCI GPU.
std::fs::create_dir_all(dir.join("226:128/device"))?;
std::fs::write(dir.join("226:128/device/vendor"), "0x10de\n")?;
std::fs::write(dir.join("226:128/device/device"), "0x25ac\n")?;
std::fs::create_dir_all(dir.path().join("226:128/device"))?;
std::fs::write(dir.path().join("226:128/device/vendor"), "0x10de\n")?;
std::fs::write(dir.path().join("226:128/device/device"), "0x25ac\n")?;
// A device that isn't a PCI GPU (a virtual one) has no ids.
std::fs::create_dir_all(dir.join("226:0/device"))?;
let render = super::pci_ids(&dir, makedev(226, 128));
let virtual_gpu = super::pci_ids(&dir, makedev(226, 0));
let missing = super::pci_ids(&dir, makedev(226, 1));
std::fs::remove_dir_all(&dir)?;
std::fs::create_dir_all(dir.path().join("226:0/device"))?;
let render = super::pci_ids(dir.path(), makedev(226, 128));
let virtual_gpu = super::pci_ids(dir.path(), makedev(226, 0));
let missing = super::pci_ids(dir.path(), makedev(226, 1));
assert_eq!(render, Some((0x10de, 0x25ac)));
assert_eq!(virtual_gpu, None);
assert_eq!(missing, None);
+24 -14
View File
@@ -242,8 +242,8 @@ fn internal_panels_are_edp_lvds_and_dsi_connectors() {
/// PCI ids. Each GPU is listed once, the one with the panel as primary.
#[test]
fn linux_display_gpus_come_from_the_connected_connectors() -> std::io::Result<()> {
let dir = std::env::temp_dir().join(format!("vectorcraft-drm-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let temp = tempfile::Builder::new().prefix("vectorcraft-drm-").tempdir()?;
let dir = temp.path();
let card = |name: &str, (vendor, device): (u32, u32)| -> std::io::Result<()> {
std::fs::create_dir_all(dir.join(name).join("device"))?;
std::fs::write(dir.join(name).join("device/vendor"), format!("{vendor:#06x}\n"))?;
@@ -262,11 +262,11 @@ fn linux_display_gpus_come_from_the_connected_connectors() -> std::io::Result<()
connector("card1-DP-2", "connected")?;
connector("card2-Virtual-1", "connected")?;
std::fs::write(dir.join("renderD128"), "")?;
let mut gpus = linux_display_gpus(&dir);
let mut gpus = linux_display_gpus(dir);
gpus.sort_by_key(|g| g.pci);
assert_eq!(gpus, [primary(AMD_IGPU), monitor(NVIDIA_3090)]);
assert!(linux_display_gpus(&dir.join("no such dir")).is_empty());
std::fs::remove_dir_all(&dir)
Ok(())
}
#[test]
@@ -616,11 +616,26 @@ fn a_normal_exit_or_another_failure_does_not_restart() {
/// A log folder of its own for each test, and the guard that keeps other tests from starting a
/// program while it runs: the test releases the start file's lock and takes it again, and a child
/// starting meanwhile would keep it held (`crate::no_spawns`).
fn start_dir(tag: &str) -> (std::path::PathBuf, std::sync::RwLockReadGuard<'static, ()>) {
struct TestDir(tempfile::TempDir);
impl std::ops::Deref for TestDir {
type Target = std::path::Path;
fn deref(&self) -> &Self::Target {
self.0.path()
}
}
impl AsRef<std::path::Path> for TestDir {
fn as_ref(&self) -> &std::path::Path {
self.0.path()
}
}
fn start_dir(tag: &str) -> (TestDir, std::sync::RwLockReadGuard<'static, ()>) {
let spawns = crate::no_spawns();
let d = std::env::temp_dir().join(format!("vectorcraft-gpu-start-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
(d, spawns)
let dir = tempfile::Builder::new().prefix(&format!("vectorcraft-gpu-start-{tag}-")).tempdir().unwrap();
(TestDir(dir), spawns)
}
/// What a start in `dir` leaves out; it then ends without crashing.
@@ -670,7 +685,6 @@ fn a_start_that_never_showed_a_frame_leaves_its_adapter_out_of_the_next() {
assert_eq!(left_out.adapters, ["Dx12:8086:3184"], "kept");
assert_eq!(left_out.crash, None, "the note is shown once");
third.ended();
let _ = std::fs::remove_dir_all(&dir);
}
/// A start whose first frame reached the screen, or that ended without crashing (a normal exit,
@@ -693,7 +707,6 @@ fn a_start_that_showed_its_first_frame_or_ended_is_cleared() {
assert!(finish(Ok(Ok(())), &first).is_ok());
drop(first);
assert_eq!(next_start(&dir, false), LeftOut::default());
let _ = std::fs::remove_dir_all(&dir);
}
/// The process ended while the adapters were being listed (wgpu's DX12 backend creates a
@@ -721,7 +734,6 @@ fn a_crash_while_listing_lists_opengl_alone() {
second.none_left();
second.ended();
assert_eq!(next_start(&dir, false), LeftOut::default());
let _ = std::fs::remove_dir_all(&dir);
}
/// `WGPU_BACKEND` or `WGPU_ADAPTER_NAME` choose for a start whatever crashed before; when that
@@ -742,7 +754,6 @@ fn wgpu_backend_or_adapter_name_ignores_the_crashes() {
explicit.picked(&c[0].key, &c[0].name, true);
explicit.presented();
assert_eq!(next_start(&dir, false), LeftOut::default(), "a new driver shows the window");
let _ = std::fs::remove_dir_all(&dir);
}
/// A damaged record, a file that can't be opened and one another starting copy of the app holds
@@ -777,10 +788,9 @@ fn a_damaged_or_unreadable_start_file_is_ignored() {
assert_eq!(next_start(&dir, false).adapters, ["Dx12:8086:3184"]);
// A folder in the file's place.
let _ = std::fs::remove_dir_all(&dir);
std::fs::remove_file(dir.join(START_FILE)).unwrap();
std::fs::create_dir_all(dir.join(START_FILE)).unwrap();
assert_eq!(next_start(&dir, false), LeftOut::default());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
+35 -12
View File
@@ -198,6 +198,30 @@ fn read_file_refuses_what_is_not_a_regular_file() {
assert!(read_file("/dev/zero").is_err());
}
/// Read the first `max` bytes of a file (all of it when it is shorter), and nothing past them. Only
/// a regular file is read.
fn read_file_head(path: &str, max: usize) -> Result<Vec<u8>, String> {
use std::io::Read;
if !std::fs::metadata(path).map_err(|e| e.to_string())?.is_file() {
return Err(format!("{path}: not a file"));
}
let mut out = vec![];
std::fs::File::open(path).and_then(|f| f.take(max as u64).read_to_end(&mut out)).map_err(|e| e.to_string())?;
Ok(out)
}
#[cfg(test)]
#[test]
fn read_file_head_reads_no_more_than_it_is_asked_for() {
use std::io::Write as _;
let mut f = tempfile::Builder::new().prefix("vectorcraft-read-head-").tempfile().unwrap();
f.write_all(b"0123456789").unwrap();
let p = f.path().to_string_lossy();
assert_eq!(read_file_head(&p, 4).unwrap(), b"0123");
assert_eq!(read_file_head(&p, 20).unwrap(), b"0123456789", "a shorter file is read whole");
assert!(read_file_head(&std::env::temp_dir().to_string_lossy(), 4).is_err(), "a folder is not read");
}
/// Write a file the safe way: a failed write keeps the old file ([`fileio::write_atomic`]).
fn write_file(path: &str, bytes: &[u8]) -> Result<(), String> {
fileio::write_atomic(std::path::Path::new(path), bytes).map_err(|e| e.to_string())
@@ -325,6 +349,8 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
#[cfg(windows)]
stylus: Some(windows_stylus::start()),
read: Some(Box::new(read_file)),
// Load Actions… refuses a file over its size limit without reading all of it.
read_head: Some(Box::new(read_file_head)),
write: Some(Box::new(write_file)),
exists: Some(Box::new(|p: &str| std::path::Path::new(p).exists())),
// Background Save and Export write from a worker thread.
@@ -569,22 +595,20 @@ mod open_with_tests {
use super::{check_app, find_photocraft, photocraft_candidates, registered_path, windows_candidates};
/// A fresh, empty folder under the system's temporary folder.
fn scratch(name: &str) -> std::path::PathBuf {
let d = std::env::temp_dir().join(format!("vc-open-with-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d
fn scratch(name: &str) -> tempfile::TempDir {
tempfile::Builder::new().prefix(&format!("vc-open-with-{name}-")).tempdir().unwrap()
}
/// #5236: only an application counts as PhotoCraft, never a document, a folder or a missing
/// path.
#[test]
fn only_applications_are_started() {
let d = scratch("check");
let temp = scratch("check");
let d = temp.path();
let doc = d.join("notes.txt");
std::fs::write(&doc, "hi").unwrap();
assert!(check_app(&doc).is_err(), "a document");
assert!(check_app(&d).is_err(), "a folder");
assert!(check_app(d).is_err(), "a folder");
assert!(check_app(&d.join("Missing.app")).is_err(), "a missing path");
if cfg!(target_os = "macos") {
let app = d.join("Editor.app");
@@ -600,19 +624,19 @@ mod open_with_tests {
std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).unwrap();
assert!(check_app(&tool).is_ok(), "an executable file");
}
let _ = std::fs::remove_dir_all(&d);
}
/// PhotoCraft is looked for only where it installs.
#[test]
fn photocraft_is_found_where_it_installs() {
let d = scratch("find");
let temp = scratch("find");
let d = temp.path();
if cfg!(target_os = "macos") {
let candidates = photocraft_candidates(Some(&d), None);
let candidates = photocraft_candidates(Some(d), None);
assert_eq!(candidates.first().map(|p| p.to_string_lossy().into_owned()).as_deref(), Some("/Applications/PhotoCraft.app"));
assert!(candidates.contains(&d.join("Applications/PhotoCraft.app")), "{candidates:?}");
std::fs::create_dir_all(d.join("Applications/PhotoCraft.app")).unwrap();
assert!(find_photocraft(Some(&d), None).unwrap().ends_with("PhotoCraft.app"));
assert!(find_photocraft(Some(d), None).unwrap().ends_with("PhotoCraft.app"));
} else {
let bin = d.join("bin");
std::fs::create_dir_all(&bin).unwrap();
@@ -636,7 +660,6 @@ mod open_with_tests {
assert_eq!(find_photocraft(None, Some(&path_var)), Some(exe));
}
}
let _ = std::fs::remove_dir_all(&d);
}
/// #5327 review: on Windows PhotoCraft is looked for where its installer puts it: the path it
+23 -6
View File
@@ -1,12 +1,29 @@
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, UNIX_EPOCH};
fn temp_dir(tag: &str) -> PathBuf {
static N: AtomicUsize = AtomicUsize::new(0);
let d = std::env::temp_dir().join(format!("vectorcraft-logging-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed)));
let _ = std::fs::remove_dir_all(&d);
d
struct TestPath {
_parent: tempfile::TempDir,
path: PathBuf,
}
impl std::ops::Deref for TestPath {
type Target = Path;
fn deref(&self) -> &Self::Target {
&self.path
}
}
impl AsRef<Path> for TestPath {
fn as_ref(&self) -> &Path {
&self.path
}
}
fn temp_dir(tag: &str) -> TestPath {
let parent = tempfile::Builder::new().prefix(&format!("vectorcraft-logging-{tag}-")).tempdir().unwrap();
let path = parent.path().join("log");
TestPath { _parent: parent, path }
}
fn read(path: &Path) -> String {
+2 -4
View File
@@ -63,11 +63,10 @@ mod tests {
/// fonts, is listed while it is registered.
#[test]
fn fonts_registered_from_other_folders_are_listed() {
let dir = std::env::temp_dir().join(format!("vectorcraft-mac-fonts-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let dir = tempfile::Builder::new().prefix("vectorcraft-mac-fonts-").tempdir().unwrap();
// A space in the name: the URL's escapes are decoded. The bundled serif isn't a font macOS
// installs.
let file = dir.join("Registered Font.ttf");
let file = dir.path().join("Registered Font.ttf");
std::fs::copy(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/SourceSerif4-Regular.ttf"), &file).unwrap();
let want = std::fs::canonicalize(&file).unwrap();
let listed = || super::font_files().iter().any(|f| f.ends_with("/Registered Font.ttf") && std::fs::canonicalize(f).is_ok_and(|p| p == want));
@@ -78,7 +77,6 @@ mod tests {
let registered = listed();
// SAFETY: as above.
unsafe { CTFontManagerUnregisterFontsForURL(&url, CTFontManagerScope::Process, std::ptr::null_mut()) };
std::fs::remove_dir_all(&dir).unwrap();
assert!(registered);
}
}
+2 -4
View File
@@ -335,13 +335,11 @@ mod tests {
#[test]
fn a_kept_preferences_copy_is_owner_only() {
use std::os::unix::fs::PermissionsExt as _;
let dir = std::env::temp_dir().join(format!("vc-prefs-copy-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let temp = tempfile::Builder::new().prefix("vc-prefs-copy-").tempdir().unwrap();
let dir = temp.path();
super::keep_prefs_copy(&dir.join("ui.json"), b"{}", "ui.unreadable");
let mode = std::fs::metadata(dir.join("ui.unreadable.json")).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
+18 -7
View File
@@ -192,7 +192,22 @@ fn copy_dir_into(from: &Path, to: &Path, skip: &mut impl FnMut(String)) {
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
struct TestDir(tempfile::TempDir);
impl std::ops::Deref for TestDir {
type Target = Path;
fn deref(&self) -> &Self::Target {
self.0.path()
}
}
impl AsRef<Path> for TestDir {
fn as_ref(&self) -> &Path {
self.0.path()
}
}
fn environment(key: &str) -> Option<OsString> {
match key {
@@ -287,12 +302,8 @@ mod tests {
assert_eq!(install_dir("macos", mounted, &appimage), Some("/tmp/.mount_vc/usr/bin".into()));
}
fn temp(tag: &str) -> PathBuf {
static N: AtomicUsize = AtomicUsize::new(0);
let d = std::env::temp_dir().join(format!("vectorcraft-profile-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed)));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d
fn temp(tag: &str) -> TestDir {
TestDir(tempfile::Builder::new().prefix(&format!("vectorcraft-profile-{tag}-")).tempdir().unwrap())
}
#[test]
+18 -15
View File
@@ -263,15 +263,23 @@ mod tests {
use super::*;
struct TestDir(tempfile::TempDir);
impl std::ops::Deref for TestDir {
type Target = Path;
fn deref(&self) -> &Self::Target {
self.0.path()
}
}
/// A fresh folder for one test, with an existing file in it.
fn folder(name: &str) -> (PathBuf, PathBuf, String) {
let dir = std::env::temp_dir().join(format!("vc-single-instance-{}-{name}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
let file = dir.join("a b.svg");
fn folder(name: &str) -> (PathBuf, TestDir, String) {
let dir = tempfile::Builder::new().prefix(&format!("vc-single-instance-{name}-")).tempdir().unwrap();
let file = dir.path().join("a b.svg");
fs::write(&file, "<svg/>").unwrap();
let file = file.to_string_lossy().into_owned();
(dir.join(FILE_NAME), dir, file)
(dir.path().join(FILE_NAME), TestDir(dir), file)
}
fn primary(path: &Path) -> (Primary, mpsc::Receiver<Vec<String>>) {
@@ -303,12 +311,11 @@ mod tests {
assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]);
drop(primary);
assert!(!path.exists(), "the endpoint file goes with the app");
let _ = fs::remove_dir_all(dir);
}
#[test]
fn a_wrong_token_garbage_and_oversized_messages_are_refused() {
let (path, dir, file) = folder("refused");
let (path, _dir, file) = folder("refused");
let (_primary, rx) = primary(&path);
let token = read_endpoint(&path).unwrap().token;
let wrong = format!("{}\n", json!({ "token": "0".repeat(token.len()), "files": [file] }));
@@ -323,12 +330,11 @@ mod tests {
// The listener still serves a launch with the right token.
forward(&path, std::slice::from_ref(&file)).unwrap();
assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]);
let _ = fs::remove_dir_all(dir);
}
#[test]
fn a_stale_endpoint_file_is_ignored_and_replaced() {
let (path, dir, file) = folder("stale");
let (path, _dir, file) = folder("stale");
// The recorded app is gone: whatever holds the port closes without a greeting. (A freed
// port can be taken by another test's listener meanwhile, which would then accept this
// connection in place of its own client's.)
@@ -357,18 +363,16 @@ mod tests {
let (_primary, rx) = primary(&path);
forward(&path, std::slice::from_ref(&file)).unwrap();
assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]);
let _ = fs::remove_dir_all(dir);
}
#[test]
fn a_replaced_endpoint_file_stays_when_the_earlier_app_ends() {
let (path, dir, _) = folder("replaced");
let (path, _dir, _) = folder("replaced");
let (first, _rx1) = primary(&path);
let (_second, _rx2) = primary(&path);
let second_token = read_endpoint(&path).unwrap().token;
drop(first);
assert_eq!(read_endpoint(&path).map(|e| e.token), Some(second_token));
let _ = fs::remove_dir_all(dir);
}
#[test]
@@ -383,9 +387,8 @@ mod tests {
#[test]
fn the_endpoint_file_is_the_users_alone() {
use std::os::unix::fs::PermissionsExt as _;
let (path, dir, _) = folder("mode");
let (path, _dir, _) = folder("mode");
let _primary = primary(&path);
assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
let _ = fs::remove_dir_all(dir);
}
}
+2 -3
View File
@@ -284,8 +284,8 @@ mod tests {
#[test]
fn fonts_only_gdi_has_loaded_are_listed_by_their_files() {
use windows::Win32::Graphics::Gdi::{AddFontResourceExW, FR_PRIVATE, RemoveFontResourceExW};
let dir = std::env::temp_dir().join(format!("vc-gdi-fonts-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let temp = tempfile::Builder::new().prefix("vc-gdi-fonts-").tempdir().unwrap();
let dir = temp.path();
let file = dir.join("29457");
let source = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts/SourceSans3-Regular.ttf");
let mut data = std::fs::read(source).unwrap();
@@ -303,7 +303,6 @@ mod tests {
assert_eq!(unsafe { AddFontResourceExW(&path, FR_PRIVATE, None) }, 1);
let files = super::font_files();
let _ = unsafe { RemoveFontResourceExW(&path, FR_PRIVATE.0, None) };
let _ = std::fs::remove_dir_all(&dir);
let wanted = file.to_string_lossy().to_lowercase();
assert!(files.iter().any(|f| f.to_lowercase() == wanted), "{wanted} not in {} files", files.len());
}
+2 -4
View File
@@ -99,9 +99,8 @@ fn unreadable_saved_docking_keeps_preferences_and_every_workspace() {
#[test]
fn an_unreadable_ui_json_is_kept_beside_it() {
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let dir = std::env::temp_dir().join(format!("vectorcraft-ui-prefs-{}-{stamp}", std::process::id()));
std::fs::create_dir(&dir).unwrap();
let temp = tempfile::Builder::new().prefix("vectorcraft-ui-prefs-").tempdir().unwrap();
let dir = temp.path();
let path = dir.join("ui.json");
super::keep_prefs_copy(&path, b"{\"docking\": {\"root\": {\"FutureNode\": {}}}}", "ui.unreadable");
super::keep_prefs_copy(&path, b"not json", "ui.unreadable");
@@ -109,7 +108,6 @@ fn an_unreadable_ui_json_is_kept_beside_it() {
let first = std::fs::read(dir.join("ui.unreadable.json")).unwrap();
let second = std::fs::read(dir.join("ui.unreadable-2.json")).unwrap();
let before = std::fs::read(dir.join("ui.before-layout-migration.json")).unwrap();
let _ = std::fs::remove_dir_all(&dir);
assert!(first.starts_with(b"{\"docking\""), "the first copy is not replaced");
assert_eq!(second, b"not json");
assert_eq!(before, b"{}");
+50 -13
View File
@@ -16,6 +16,14 @@
//! mouse message that Windows did not make from a pen or a touch
//! (<https://learn.microsoft.com/en-us/windows/win32/tablet/system-events-and-mouse-messages>)
//! clears the feed.
//!
//! The same `POINTER_PEN_INFO` gives the pen's tilt and barrel rotation (#372: a 6D Art Pen turns a
//! Calligraphic brush's nib with its barrel), each only where its `PEN_MASK_*` bit says the pen
//! reports it (<https://learn.microsoft.com/en-us/windows/win32/inputmsg/pen-mask-constants>):
//! `tiltX` and `tiltY` in degrees −90..90, positive to the right and toward the user, and
//! `rotation` in degrees 0..359 clockwise
//! (<https://learn.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-pointer_pen_info>).
//! Toward the user is down the screen, so they are [`PenPose`]'s axes and direction as they come.
#![cfg_attr(not(windows), allow(dead_code))]
use std::cell::RefCell;
@@ -37,6 +45,11 @@ const PEN_FLAG_INVERTED: u32 = 0x0002;
const PEN_FLAG_ERASER: u32 = 0x0004;
/// `PEN_MASK_PRESSURE` (`winuser.h`), in `POINTER_PEN_INFO::penMask`: the pen reports pressure.
const PEN_MASK_PRESSURE: u32 = 0x0001;
/// `PEN_MASK_ROTATION`, `PEN_MASK_TILT_X` and `PEN_MASK_TILT_Y` (`winuser.h`): the pen reports its
/// barrel rotation, its tilt along x and its tilt along y.
const PEN_MASK_ROTATION: u32 = 0x0002;
const PEN_MASK_TILT_X: u32 = 0x0004;
const PEN_MASK_TILT_Y: u32 = 0x0008;
/// `MI_WP_SIGNATURE` and `SIGNATURE_MASK`: the extra information of a mouse message that Windows
/// made from a pen or a touch.
const MI_WP_SIGNATURE: u32 = 0xFF51_5700;
@@ -94,7 +107,8 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool {
// pointer that is not a pen.
unsafe { GetPointerPenInfo((msg.wParam.0 & 0xffff) as u32, &mut info) }.ok()?;
let in_contact = info.pointerInfo.pointerFlags.0 & POINTER_FLAG_INCONTACT.0 != 0;
Some(pen_sample(info.pressure, info.penMask, info.penFlags, in_contact))
let pose = pen_pose(info.penMask, info.tiltX, info.tiltY, info.rotation);
Some(pen_sample(info.pressure, info.penMask, info.penFlags, in_contact, pose))
};
// SAFETY: `GetMessageExtraInfo` reads the extra information of the thread's last message.
let from_mouse = || is_mouse(unsafe { GetMessageExtraInfo() }.0 as u32);
@@ -106,15 +120,25 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool {
/// What a pen whose `POINTER_PEN_INFO` holds `pressure` (0..1024), `pen_mask` and `pen_flags`
/// reports: the pressure as winit gives it to a touch, 0 while it hovers, a full press for a pen
/// in contact that reports none; and the eraser end while it is inverted or its eraser button is
/// pressed.
fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool) -> PenSample {
/// in contact that reports none; the eraser end while it is inverted or its eraser button is
/// pressed; and how it is held, `pose` ([`pen_pose`]).
fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool, pose: PenPose) -> PenSample {
let pressure = match pressure {
1..=1024 if pen_mask & PEN_MASK_PRESSURE != 0 => pressure as f32 / 1024.0,
_ if in_contact => 1.0,
_ => 0.0,
};
PenSample { pressure, eraser: pen_flags & (PEN_FLAG_INVERTED | PEN_FLAG_ERASER) != 0, pose: PenPose::default() }
PenSample { pressure, eraser: pen_flags & (PEN_FLAG_INVERTED | PEN_FLAG_ERASER) != 0, pose }
}
/// How a pen whose `POINTER_PEN_INFO` holds `pen_mask`, `tilt_x`, `tilt_y` and `rotation` is
/// held: the tilt when the pen reports it along either axis (0 along an axis it doesn't), the
/// rotation when it reports one, each kept within [`PenPose`]'s ranges.
fn pen_pose(pen_mask: u32, tilt_x: i32, tilt_y: i32, rotation: u32) -> PenPose {
let along = |mask: u32, t: i32| if pen_mask & mask != 0 { t as f32 } else { 0.0 };
let tilt = (pen_mask & (PEN_MASK_TILT_X | PEN_MASK_TILT_Y) != 0).then(|| [along(PEN_MASK_TILT_X, tilt_x), along(PEN_MASK_TILT_Y, tilt_y)]);
let rotation = (pen_mask & PEN_MASK_ROTATION != 0).then_some(rotation as f32);
PenPose { tilt, rotation }.sanitized()
}
/// Whether a mouse message with this extra information (`GetMessageExtraInfo`) comes from a mouse,
@@ -390,7 +414,7 @@ mod tests {
#[test]
fn an_inverted_pen_or_its_eraser_button_is_the_eraser_end() {
let eraser = |flags| pen_sample(512, PEN_MASK_PRESSURE, flags, true).eraser;
let eraser = |flags| pen_sample(512, PEN_MASK_PRESSURE, flags, true, PenPose::default()).eraser;
assert!(!eraser(0), "the tip");
assert!(!eraser(PEN_FLAG_BARREL), "the barrel button");
assert!(eraser(PEN_FLAG_INVERTED), "turned over");
@@ -399,19 +423,32 @@ mod tests {
assert!(eraser(PEN_FLAG_INVERTED | PEN_FLAG_BARREL));
}
#[test]
fn a_pens_tilt_and_rotation_come_where_it_reports_them() {
let all = PEN_MASK_TILT_X | PEN_MASK_TILT_Y | PEN_MASK_ROTATION;
assert_eq!(pen_pose(all, 30, -45, 90), PenPose { tilt: Some([30.0, -45.0]), rotation: Some(90.0) });
assert_eq!(pen_pose(PEN_MASK_PRESSURE, 30, -45, 90), PenPose::default(), "a pen that reports neither");
assert_eq!(pen_pose(PEN_MASK_TILT_X, 30, -45, 90), PenPose { tilt: Some([30.0, 0.0]), rotation: None }, "one axis");
assert_eq!(pen_pose(PEN_MASK_ROTATION, 0, 0, 359), PenPose { tilt: None, rotation: Some(359.0) }, "a 6D Art Pen's barrel");
let wild = pen_pose(all, 400, i32::MIN, 720);
assert_eq!(wild, PenPose { tilt: Some([90.0, -90.0]), rotation: Some(0.0) }, "kept within the ranges");
let pose = pen_pose(all, 10, 20, 180);
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE | all, 0, true, pose).pose, pose);
}
#[test]
fn a_pens_pressure_is_the_one_winit_gives_its_touch() {
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true).pressure, 0.5);
assert_eq!(pen_sample(1024, PEN_MASK_PRESSURE, 0, true).pressure, 1.0);
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, PenPose::default()).pressure, 0.5);
assert_eq!(pen_sample(1024, PEN_MASK_PRESSURE, 0, true, PenPose::default()).pressure, 1.0);
assert_eq!(
pen_sample(0, PEN_MASK_PRESSURE, PEN_FLAG_INVERTED, false),
pen_sample(0, PEN_MASK_PRESSURE, PEN_FLAG_INVERTED, false, PenPose::default()),
PenSample { pressure: 0.0, eraser: true, pose: PenPose::default() },
"hovering"
);
assert_eq!(pen_sample(0, 0, 0, true).pressure, 1.0, "a pen in contact that reports no pressure presses fully");
assert_eq!(pen_sample(300, 0, 0, true).pressure, 1.0, "a pressure without the pressure mask is not one");
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, 0, true).pressure, 1.0, "as winit, which gives no force for 0");
assert_eq!(pen_sample(2000, PEN_MASK_PRESSURE, 0, false).pressure, 0.0);
assert_eq!(pen_sample(0, 0, 0, true, PenPose::default()).pressure, 1.0, "a pen in contact that reports no pressure presses fully");
assert_eq!(pen_sample(300, 0, 0, true, PenPose::default()).pressure, 1.0, "a pressure without the pressure mask is not one");
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, 0, true, PenPose::default()).pressure, 1.0, "as winit, which gives no force for 0");
assert_eq!(pen_sample(2000, PEN_MASK_PRESSURE, 0, false, PenPose::default()).pressure, 0.0);
}
#[test]
+50
View File
@@ -195,6 +195,24 @@ impl ImageBlob {
jpeg_components(&self.bytes) == Some(4) || tiff(&self.bytes).is_some_and(|(t, _)| matches!(t, tiff::ColorType::CMYK(8 | 16)))
}
/// Does the image hold CMYK samples of 16 bits (a CMYK TIFF), which [`Self::cmyk`] gives at 8
/// bits? Reads only its header.
pub fn is_cmyk16(&self) -> bool {
tiff(&self.bytes).is_some_and(|(t, _)| matches!(t, tiff::ColorType::CMYK(16)))
}
/// The width and height a JPEG or TIFF says it has, for any color type. Reads only its header.
pub fn header_size(&self) -> Option<(u32, u32)> {
let bytes = self.bytes.as_slice();
if bytes.starts_with(&[0xFF, 0xD8]) {
let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), DecoderOptions::default());
d.decode_headers().ok()?;
let (w, h) = d.dimensions()?;
return Some((u32::try_from(w).ok()?, u32::try_from(h).ok()?));
}
tiff(bytes).and_then(|(_, mut d)| d.dimensions().ok())
}
/// The ink amounts of a CMYK image; `None` for other images, and ones that can't be decoded
/// or are larger than [`MAX_CMYK_PIXELS`].
pub fn cmyk(&self) -> Option<Inks> {
@@ -633,6 +651,38 @@ mod tests {
assert_eq!(rgb.get_pixel(1, 0).0, [0, 255, 255]);
}
#[test]
fn a_header_gives_the_size_without_the_samples() {
assert_eq!(ImageBlob::cmyk_tiff(&inks()).unwrap().header_size(), Some((3, 2)));
// A CMYK TIFF of 6000 × 6000 pixels whose samples aren't there.
let mut t = b"II*\0\x08\0\0\0\x07\0".to_vec();
// Bits per sample: four values, after the entries (8 + 2 + 7 × 12 + 4 = 98).
let entries = [
(256u16, 4u16, 1u32, 6000u32),
(257, 4, 1, 6000),
(258, 3, 4, 98),
(262, 3, 1, 5),
(273, 4, 1, 106),
(277, 3, 1, 4),
(279, 4, 1, 144_000_000),
];
for (tag, kind, count, value) in entries {
t.extend_from_slice(&tag.to_le_bytes());
t.extend_from_slice(&kind.to_le_bytes());
t.extend_from_slice(&count.to_le_bytes());
t.extend_from_slice(&value.to_le_bytes());
}
t.extend_from_slice(&0u32.to_le_bytes());
t.extend_from_slice(&[8, 0, 8, 0, 8, 0, 8, 0]);
let big = ImageBlob::new("image/tiff", t);
assert!(big.is_cmyk());
assert_eq!(big.header_size(), Some((6000, 6000)));
assert_eq!(big.cmyk(), None);
let mut png = Vec::new();
image::RgbaImage::new(2, 2).write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
assert_eq!(ImageBlob::png(png).header_size(), None, "not a JPEG or TIFF");
}
#[test]
fn a_cmyk_image_samples_its_ink_amounts() {
let b = ImageBlob::cmyk_tiff(&inks()).unwrap();
+2
View File
@@ -72,6 +72,7 @@ impl Document {
new_art,
dimensions,
retired_artboard_id: _,
opened_artboard: _,
index: _,
} = self;
*version == other.version
@@ -248,6 +249,7 @@ impl Document {
new_art: Default::default(),
dimensions: false,
retired_artboard_id: Default::default(),
opened_artboard: None,
index: Default::default(),
};
let id = d.alloc_id();
+5
View File
@@ -325,6 +325,11 @@ pub struct Document {
/// Never saved.
#[serde(skip)]
pub retired_artboard_id: RetiredArtboardId,
/// The id of the artboard an imported file names as its active one (a `.ai` file's
/// `CropAreaActive`): the document opens with that artboard active. `None`: the first. Never
/// saved.
#[serde(skip)]
pub opened_artboard: Option<u32>,
/// Some object is a dimension (the Dimension tool): edits refresh dimensions only while this
/// is set, so documents without any pay nothing for them.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
+78 -2
View File
@@ -46,10 +46,26 @@ impl LinkInfo {
Self { path: path.into(), ..Self::default() }
}
/// The file name: the path's last component, whichever system's separators it uses.
/// The file name: the path's last component, whichever system's separators it uses
/// ([`path_separators`]).
pub fn name(&self) -> &str {
self.path.rsplit(['/', '\\']).next().unwrap_or(&self.path)
self.path.rsplit(path_separators(&self.path)).next().unwrap_or(&self.path)
}
/// The folder the file is in: the path without its name and the separators before it.
pub fn folder(&self) -> &str {
let folder = self.path.get(..self.path.len().saturating_sub(self.name().len())).unwrap_or_default();
folder.trim_end_matches(path_separators(&self.path))
}
}
/// The characters that separate the folders of `path`. A path with a colon and no `/` or `\` is a
/// classic Mac OS path (`Disk:Folder:file.tif`, as older documents store links), whose folders are
/// separated by colons. Any other path is separated by `/` and `\`: its file name may hold a colon
/// (`/Users/a/x:y.png`) and never holds a `/` or `\`.
pub fn path_separators(path: &str) -> &'static [char] {
const SLASHES: &[char] = &['/', '\\'];
if path.contains(':') && !path.contains(SLASHES) { &[':'] } else { SLASHES }
}
impl From<&str> for LinkInfo {
@@ -164,6 +180,31 @@ impl ImageBlob {
pub fn is_proxy(&self) -> bool {
self.proxy.as_ref().is_some_and(|p| Arc::ptr_eq(p, &self.bytes))
}
/// Does a colorize paint ([`crate::NodeExtras::colorize`]) show on these bytes? Not while
/// they are a preview whose pixels aren't grayscale, such as [`missing_placeholder`]: until
/// the file is relinked the image shows the preview as it is, and keeps the paint.
pub fn takes_colorize(&self) -> bool {
!self.is_proxy() || self.gray_source().is_some()
}
}
/// The side of [`missing_placeholder`]'s image, in pixels.
pub const MISSING_SIDE: u32 = 64;
/// What a linked image shows when an importer has no pixels for it (its file is missing or isn't
/// in the data): a light tile, crossed out, [`MISSING_SIDE`] pixels a side, as a PNG. `None` when
/// it can't be encoded.
pub fn missing_placeholder() -> Option<Vec<u8>> {
let last = MISSING_SIDE - 1;
let img = image::RgbaImage::from_fn(MISSING_SIDE, MISSING_SIDE, |x, y| {
let edge = x == 0 || y == 0 || x == last || y == last;
let cross = x.abs_diff(y) <= 1 || (x + y).abs_diff(last) <= 1;
image::Rgba(if edge || cross { [200, 60, 60, 255] } else { [236, 236, 236, 255] })
});
let mut png = Vec::new();
img.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?;
Some(png)
}
/// `bytes` decoded and shrunk to fit [`PROXY_SIZE`] as a PNG; `None` when small enough already or
@@ -445,6 +486,12 @@ mod tests {
.unwrap()
}
#[test]
fn the_placeholder_is_a_png() {
let png = missing_placeholder().unwrap();
assert_eq!(image::load_from_memory(&png).unwrap().width(), MISSING_SIDE);
}
#[test]
fn a_path_string_from_older_files_reads_as_a_link() {
let old: ImageObject = serde_json::from_str(r#"{"key":"k","width":2,"height":1,"xf":[1,0,0,1,0,0],"link":"C:\\art\\photo.png"}"#).unwrap();
@@ -460,6 +507,35 @@ mod tests {
assert_eq!(v["link"], serde_json::json!({"path": "/a/b.png", "size": 9, "page": 2}));
}
/// A classic Mac OS path is named by its last colon-separated component, and its folder is
/// what comes before; other paths keep their `/` and `\` separators, and a name never holds
/// one.
#[test]
fn a_classic_mac_path_is_named_by_its_last_component() {
let parts = |path: &str| {
let l = LinkInfo::new(path);
(l.name().to_string(), l.folder().to_string())
};
assert_eq!(parts("Macintosh HD:Images:photo.tif"), ("photo.tif".into(), "Macintosh HD:Images".into()));
assert_eq!(parts("Disk:photo.tif"), ("photo.tif".into(), "Disk".into()));
assert_eq!(parts("Disk:Art/2024:a\\b.tif"), ("b.tif".into(), "Disk:Art/2024:a".into()));
assert_eq!(parts("Disk:Images:../other.png"), ("other.png".into(), "Disk:Images:..".into()), "a name reaches no other folder");
assert_eq!(parts("C:\\art\\photo.png"), ("photo.png".into(), "C:\\art".into()));
assert_eq!(parts("c:/art/photo.png"), ("photo.png".into(), "c:/art".into()));
assert_eq!(parts("/Users/a/x:y.png"), ("x:y.png".into(), "/Users/a".into()), "a POSIX name may hold a colon");
assert_eq!(parts("./art/x:y.png"), ("x:y.png".into(), "./art".into()));
assert_eq!(parts("..\\art\\x:y.png"), ("x:y.png".into(), "..\\art".into()));
assert_eq!(parts("\\\\?\\C:\\art\\photo.png"), ("photo.png".into(), "\\\\?\\C:\\art".into()));
assert_eq!(parts("file:///art/photo.png"), ("photo.png".into(), "file:///art".into()));
assert_eq!(parts("file:/art/photo.png"), ("photo.png".into(), "file:/art".into()));
assert_eq!(parts("assets/icon:dark.png"), ("icon:dark.png".into(), "assets".into()), "a relative path with slashes");
assert_eq!(parts(":Images:photo.tif"), ("photo.tif".into(), ":Images".into()), "a classic path relative to its folder");
assert_eq!(parts("/Users/a//photo.png").1, "/Users/a", "repeated separators");
assert_eq!(parts("photo.png"), ("photo.png".into(), String::new()));
assert_eq!(parts("C:photo.png"), ("photo.png".into(), "C".into()), "a drive-relative path has the same shape");
assert_eq!(LinkInfo::new("Macintosh HD:Images:photo.tif").path, "Macintosh HD:Images:photo.tif", "the stored path is kept");
}
#[test]
fn a_reader_hashes_as_its_bytes_do() {
// Several 64 KB reads, and none.
+42
View File
@@ -501,3 +501,45 @@ fn a_stroke_narrower_than_the_shape_keeps_its_hole() {
assert_eq!(moves(&outline), 3, "{join:?}: two contours for the ring, one for the blob");
}
}
/// A subpixel stroke must retain its geometric thickness even when the normal display tolerance
/// is close to its weight. Original uneven circular arcs, independent of any user fixture.
#[test]
fn thin_curved_strokes_keep_their_width_between_notches() {
use kurbo::{CubicBez, ParamCurve, ParamCurveDeriv, Shape};
for (radius, degrees) in [(450.0, 47.0_f64), (438.0, 77.0), (450.0, 54.0)] {
let a = degrees.to_radians();
let k = 4.0 / 3.0 * (a / 4.0).tan();
let curve = CubicBez::new(
(radius, 0.0),
(radius, k * radius),
(radius * a.cos() + k * radius * a.sin(), radius * a.sin() - k * radius * a.cos()),
(radius * a.cos(), radius * a.sin()),
);
let mut line = BezPath::new();
line.move_to(curve.p0);
line.curve_to(curve.p1, curve.p2, curve.p3);
for width in [0.25, 1.0 / 3.0, 0.5, 1.0] {
let st = StrokeLayer::new(Paint::solid(Color::BLACK), width);
let outline = line_outline(&line, &st, width, 0.25);
for step in 1..40 {
let t = step as f64 / 40.0;
let p = curve.eval(t);
let tangent = curve.deriv().eval(t).to_vec2().normalize();
let normal = kurbo::Vec2::new(-tangent.y, tangent.x);
for side in [-1.0, 1.0] {
assert_ne!(
outline.winding(p + normal * (side * width * 0.45)),
0,
"missing inner band at radius {radius}, {degrees} degrees, width {width}, t {t}"
);
assert_eq!(
outline.winding(p + normal * (side * width * 0.55)),
0,
"outside intended band at radius {radius}, {degrees} degrees, width {width}, t {t}"
);
}
}
}
}
}
+11
View File
@@ -168,6 +168,17 @@ pub fn has_selection(s: &Session) -> std::result::Result<(), String> {
let st = s.active().ok_or("no document open")?;
if st.selection.is_empty() { Err("nothing selected".into()) } else { Ok(()) }
}
/// A path is selected, or inside a selected group or compound path: Object › Path's items that
/// work on paths (not on text, images or other objects alone).
pub fn has_selected_path(s: &Session) -> std::result::Result<(), String> {
has_selection(s)?;
let st = s.active().ok_or("no document open")?;
// Stops at the first path: menus ask this every frame, and a selected group can hold many.
fn holds_path(n: &vectorcraft_doc::Node) -> bool {
matches!(n.kind, vectorcraft_doc::NodeKind::Path { guide: false, .. }) || n.children().is_some_and(|c| c.iter().any(|c| holds_path(c)))
}
if st.selection.objects.iter().filter_map(|id| st.doc.node(*id)).any(holds_path) { Ok(()) } else { Err("select a path".into()) }
}
/// Objects or ruler guides are selected, or the Artboard tool is chosen (what Copy and Cut take).
pub fn has_selection_guides_or_artboard_tool(s: &Session) -> std::result::Result<(), String> {
if s.tool_id() == "artboard" { has_doc(s) } else { has_selection_or_guides(s) }
+2
View File
@@ -9,6 +9,7 @@ mod document;
mod pathtools;
mod pen;
mod select;
mod shapes;
mod typetools;
use super::CommandSpec;
@@ -23,6 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
v.extend(pathtools::specs());
v.extend(pen::specs());
v.extend(select::specs());
v.extend(shapes::specs());
v.extend(typetools::specs());
v
}
+71 -22
View File
@@ -13,7 +13,7 @@ use vectorcraft_geom::{Affine, Point, Vec2};
use vectorcraft_text::{FontDb, FontMatch, TextLayout, edit};
use crate::cmd::fonts::{edit_symbol_texts, symbol_texts};
use crate::cmd::textedit::editing_range;
use crate::cmd::textedit::{editing_range, editing_story};
use crate::cmd::typecmd::refresh_bounds;
use crate::cmd::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, switch_or, text_param};
use crate::{EngineError, Result, Session};
@@ -72,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Remove Breaks",
["Object", "Plug-ins", "Artwork Cleanup"],
None,
"{kind: \"line\"|\"paragraph\", ids?: [id…]} remove the forced line breaks (line) or paragraph returns (paragraph) in the characters selected with a Type tool, else in all the text of the selected type, as one undo step; a break between two words becomes a space → {ids, removed}",
"{kind: \"line\"|\"paragraph\", ids?: [id…]} remove the forced line breaks (line) or paragraph returns (paragraph) in the characters selected with a Type tool (after Select All in a frame of threaded text, in the text of every frame of the story), else in all the text of the selected type, as one undo step; a break between two words becomes a space, the frames of a threaded story selected all together being read as one text → {ids, removed}",
has_selection,
remove_breaks
),
@@ -730,12 +730,11 @@ fn join_text(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "id": id.0, "joined": joined, "lines": count }))
}
/// Remove the breaks `brk` in bytes `a..b` of `t`: one between two words becomes a space → how many
/// went.
fn strip_breaks(t: &mut TextObject, a: usize, b: usize, brk: char) -> usize {
let text = t.plain_text();
let (a, b) = (edit::floor_char(&text, a), edit::floor_char(&text, b));
let Some(range) = text.get(a..b) else { return 0 };
/// The breaks `brk` in bytes `a..b` of `text`, each with whether it becomes a space (it is between
/// two words).
fn break_cuts(text: &str, a: usize, b: usize, brk: char) -> Vec<(usize, bool)> {
let (a, b) = (edit::floor_char(text, a), edit::floor_char(text, b));
let Some(range) = text.get(a..b) else { return vec![] };
let mut prev = text.get(..a).and_then(|s| s.chars().next_back());
let mut cuts = vec![];
for (i, c) in range.char_indices() {
@@ -753,6 +752,12 @@ fn strip_breaks(t: &mut TextObject, a: usize, b: usize, brk: char) -> usize {
}
cuts.push((at, space));
}
cuts
}
/// Remove the breaks `brk` at the bytes of `cuts` from `t`, each one that `cuts` marks becoming a
/// space → how many went.
fn apply_cuts(t: &mut TextObject, cuts: &[(usize, bool)], brk: char) -> usize {
for &(at, space) in cuts.iter().rev() {
let insert = if space { " " } else { "" };
let end = at + brk.len_utf8();
@@ -763,6 +768,30 @@ fn strip_breaks(t: &mut TextObject, a: usize, b: usize, brk: char) -> usize {
cuts.len()
}
/// The breaks `brk` in the text of the frames of `story`, read as one text: a break at the end or
/// start of a frame between words of the frames on either side becomes a space. Each editable frame
/// comes with its own breaks, at its own bytes.
fn story_cuts(d: &Document, story: &[NodeId], brk: char) -> Vec<(NodeId, Vec<(usize, bool)>)> {
let texts: Vec<(NodeId, String)> = story.iter().filter_map(|id| Some((*id, text_of(d, *id)?.plain_text()))).collect();
let joined: String = texts.iter().map(|(_, t)| t.as_str()).collect();
// The breaks in story order, handed to the frames in one pass.
let mut cuts = break_cuts(&joined, 0, joined.len(), brk).into_iter().peekable();
let mut out = vec![];
let mut start = 0;
for (id, text) in texts {
let end = start + text.len();
let mut own = vec![];
while let Some((at, space)) = cuts.next_if(|(at, _)| *at < end) {
own.push((at - start, space));
}
if d.is_editable(id) {
out.push((id, own));
}
start = end;
}
out
}
fn remove_breaks(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.cleanup.removeBreaks";
let (brk, label, none) = match text_param(p, "kind", C)? {
@@ -771,21 +800,41 @@ fn remove_breaks(s: &mut Session, p: &Value) -> Result<Value> {
Some(other) => return Err(bad(C, format!("`kind` must be \"line\" or \"paragraph\", not {other:?}"))),
None => return Err(bad(C, "missing `kind`")),
};
// The characters a Type tool has selected, else all the text of the selected type.
// The characters a Type tool has selected (after Select All in threaded text, all the text of
// every frame of the story), else all the text of the selected type.
let editing = if p.get("ids").is_some() { None } else { editing_range(s)?.filter(|(_, a, b)| a != b) };
let story = if editing.is_some() { editing_story(s) } else { vec![] };
let d = &s.doc()?.doc;
let targets: Vec<(NodeId, usize, usize)> = match editing {
Some((id, a, b)) => vec![(id, a.min(b), a.max(b))].into_iter().filter(|(id, ..)| d.is_editable(*id)).collect(),
None => texts_under(d, &checked_ids_or_selection(s, p, C)?)?.into_iter().map(|id| (id, 0, usize::MAX)).collect(),
// Each type object with the breaks that go from it.
let targets: Vec<(NodeId, Vec<(usize, bool)>)> = match editing {
Some(_) if !story.is_empty() => story_cuts(d, &story, brk),
Some((id, a, b)) => vec![(id, a.min(b), a.max(b))]
.into_iter()
.filter(|(id, ..)| d.is_editable(*id))
.filter_map(|(id, a, b)| Some((id, break_cuts(&text_of(d, id)?.plain_text(), a, b, brk))))
.collect(),
None => {
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 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);
if !story.is_empty() && story.iter().all(|f| named.contains(f)) {
done.extend(story.iter().copied());
out.extend(story_cuts(d, &story, brk));
} else if let Some(t) = text_of(d, id) {
out.push((id, break_cuts(&t.plain_text(), 0, usize::MAX, brk)));
}
}
out
}
};
let count: usize = targets
.iter()
.filter_map(|(id, a, b)| {
let text = text_of(d, *id)?.plain_text();
let (a, b) = (edit::floor_char(&text, *a), edit::floor_char(&text, *b));
Some(text.get(a..b)?.matches(brk).count())
})
.sum();
let count: usize = targets.iter().map(|(_, cuts)| cuts.len()).sum();
if count == 0 {
return Err(EngineError::Other(none.into()));
}
@@ -794,9 +843,9 @@ fn remove_breaks(s: &mut Session, p: &Value) -> Result<Value> {
}
let (removed, ids) = s.edit(label, |d, _| {
let (mut removed, mut ids) = (0, vec![]);
for (id, a, b) in targets {
for (id, cuts) in targets {
let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) else { continue };
let n = strip_breaks(t, a, b, brk);
let n = apply_cuts(t, &cuts, brk);
if n > 0 {
refresh_bounds(t);
removed += n;
+120 -6
View File
@@ -3,9 +3,10 @@
//! Filter writes any colour adjustment into the colours themselves, Select by Color Kind selects the
//! objects that use spot colours, carry a live colour adjustment, or are images of a colour model,
//! Print Ink Fixes ([`print_fixes`]) prepares a CMYK document's inks for print, Find Nearest
//! Swatch ([`nearest`]) matches colours to a swatch library's, and Create Swatch Legend
//! ([`legend`]) draws labelled chips of the document's swatches. Its panel and its submenu, Object ›
//! Plug-ins › Color Effects, are the UI's.
//! Swatch ([`nearest`]) matches colours to a swatch library's, Create Swatch Legend
//! ([`legend`]) draws labelled chips of the document's swatches, and Apply Fill to Stroke and Apply
//! Stroke to Fill ([`copy_paint`]) copy each object's own paint across. Its panel and its submenu,
//! Object › Plug-ins › Color Effects, are the UI's.
pub mod legend;
mod nearest;
@@ -14,13 +15,14 @@ mod print_fixes;
mod tests;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use vectorcraft_doc::{CharStyle, Document, Node, NodeId, NodeKind};
use vectorcraft_render::effects;
use super::super::colorcmds::recolor_links;
use super::super::paint::{restore_unpainted_stroke, set_run_stroke};
use super::super::select::walk_selectable;
use super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, text_param};
use crate::{Result, Session};
use super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, paint_targets, switch_or, text_param};
use crate::{EngineError, Result, Session};
/// The kinds Select by Color Kind selects (`addon.color.select`).
pub const SELECT_KINDS: [&str; 5] = ["spotColors", "colorEffects", "rgbImages", "cmykImages", "grayImages"];
@@ -72,6 +74,24 @@ pub fn specs() -> Vec<CommandSpec> {
has_selection,
nearest::apply
),
cmd!(
"addon.color.fillToStroke",
"Apply Fill to Stroke",
["Object", "Plug-ins", "Color Effects"],
None,
"{ids?|id?, skipNone?: bool} each target's top stroke takes its own top fill, as it is (a colour in its model, a global or spot colour linked at its tint, a gradient or pattern with its placement, None); a stroke given paint at width 0 gets 1 pt, as Swap Fill and Stroke does. Type: each run's stroke takes its own fill, and while the Type tool has characters selected (no ids), only those. A graph's series marks and labels keep the paint when the graph is drawn again. skipNone: leave alone a target whose fill is None. A target whose stroke already has that paint is left as it is, and when nothing changes no undo step is recorded. The default stroke takes the default fill the same way → {objects}",
has_doc,
|s, p| copy_paint(s, p, true)
),
cmd!(
"addon.color.strokeToFill",
"Apply Stroke to Fill",
["Object", "Plug-ins", "Color Effects"],
None,
"{ids?|id?, skipNone?: bool} each target's top fill takes its own top stroke's paint, as addon.color.fillToStroke does the other way; the stroke itself is unchanged. The default fill takes the default stroke → {objects}",
has_doc,
|s, p| copy_paint(s, p, false)
),
]
.into_iter()
.chain(legend::specs())
@@ -156,3 +176,97 @@ fn filter(s: &mut Session, p: &Value) -> Result<Value> {
let swatches = |name: &str| kinds.get(name).copied();
recolor_links(s, &given, label, &|c| map.apply(c), &|c, link, tint| map.apply_link(c, link, tint, &swatches))
}
/// Apply Fill to Stroke (`to_stroke`) or Apply Stroke to Fill: each target copies one of its own
/// paints onto the other, so a mixed selection keeps each object's colour (#5530). Aimed and
/// undone like Swap Fill and Stroke; characters selected with the Type tool are the only ones that
/// change, as for `paint.setFill`. A graph's series marks and labels give the graph the paint in
/// the same undo step, as `paint.setFill` does, so drawing the graph again keeps it. When nothing
/// changes, the document and its undo history stay as they are.
fn copy_paint(s: &mut Session, p: &Value, to_stroke: bool) -> Result<Value> {
let (cmd, label) =
if to_stroke { ("addon.color.fillToStroke", "Apply Fill to Stroke") } else { ("addon.color.strokeToFill", "Apply Stroke to Fill") };
let skip_none = switch_or(p, "skipNone", false, cmd)?;
// One text style: its stroke takes its fill, or the other way.
let copy_run = |st: &mut CharStyle| {
let from = if to_stroke { st.fill.clone() } else { st.stroke.clone() };
if (skip_none && from.is_none()) || from == if to_stroke { st.stroke.clone() } else { st.fill.clone() } {
return;
}
if to_stroke {
set_run_stroke(st, from);
} else {
st.fill = from;
}
};
if p.get("ids").is_none()
&& p.get("id").is_none()
&& let Some((id, a, b)) = super::super::textedit::editing_range(s)?
&& a != b
{
// After Select All in threaded text, every frame's text takes it.
let story = super::super::textedit::editing_story(s);
let ranges: Vec<(NodeId, usize, usize)> =
if story.is_empty() { vec![(id, a, b)] } else { story.iter().map(|f| (*f, 0, usize::MAX)).collect() };
let ids: Vec<NodeId> = ranges.iter().map(|(f, _, _)| *f).collect();
let before = s.doc()?.doc.clone();
let n = super::super::overprint::edit_counted(s, label, |d| {
for &(id, a, b) in &ranges {
let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(id)) };
vectorcraft_text::edit::style_range(&mut t.runs, a, b, copy_run);
super::super::typecmd::refresh_bounds(t);
}
Ok(super::super::appearance::count_changed(d, &before, &ids))
})?;
return Ok(json!({"objects": n}));
}
// A graph's series group stands for its marks, as for `paint.setFill`.
let ids = super::super::graph::paint_targets(&s.doc()?.doc, &paint_targets(s, p)?);
let mut objects = 0;
if !ids.is_empty() {
let before = s.doc()?.doc.clone();
super::super::overprint::edit_counted(s, label, |d| {
for id in &ids {
let Some(node) = d.node_mut(*id) else { continue };
if let NodeKind::Text(t) = &mut node.kind {
for r in &mut t.runs {
copy_run(&mut r.style);
}
super::super::typecmd::refresh_bounds(t);
continue;
}
let ap = &mut node.appearance;
let (from, to) = if to_stroke { (ap.fill_paint(), ap.stroke_paint()) } else { (ap.stroke_paint(), ap.fill_paint()) };
// A missing item reads as None: copying None onto it would add an item that
// changes nothing.
if (skip_none && from.is_none()) || from == to {
continue;
}
if to_stroke {
restore_unpainted_stroke(ap, None, &from);
ap.set_stroke(from);
} else {
ap.set_fill(from);
}
}
objects = super::super::appearance::count_changed(d, &before, &ids);
// The graph keeps the paint its series marks and labels now have.
let series = super::super::graph::capture_series_paints(d, &ids, !to_stroke);
let labels = super::super::graph::capture_label_styles(d, &ids, &copy_run);
Ok(objects + usize::from(series || labels))
})?;
}
// The defaults for new art change the same way, as Swap Fill and Stroke changes them.
let from = if to_stroke { s.paint.fill.clone() } else { s.paint.stroke.clone() };
if !(skip_none && from.is_none()) {
if to_stroke {
if s.paint.stroke.is_none() && !from.is_none() && s.paint.stroke_width == 0.0 {
s.paint.stroke_width = 1.0;
}
s.paint.stroke = from;
} else {
s.paint.fill = from;
}
}
Ok(json!({"objects": objects}))
}
+1 -1
View File
@@ -47,7 +47,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Batch Trace Folder",
["Object", "Plug-ins", "Document Tools"],
None,
"{folder, destinationFolder, preset?: name (imageTrace.presets; default: Default), expand?: false (true: trace and expand, as Make and Expand), format?: vectorcraft (default)|svg|pdf|ai|eps, includeSubdirs?: false} open each image in folder (png, jpg, tif, bmp, gif, webp, psd), select it, trace it with the preset, save it into destinationFolder as <name>.<ext> (-2, -3… added when that name is taken, so no file is replaced) and close it again, whether it traced or not; the document that was active stays active. Caps: 500 images, 8 folder levels; a folder with more than 1,000 entries is refused. Not on the web (no file system) → {traced: [{path, output}], failed: [{path, error}], format} (#4921)",
"{folder, destinationFolder, preset?: name (imageTrace.presets; default: Default), expand?: false (true: trace and expand, as Make and Expand), format?: vectorcraft (default)|svg|pdf|ai|eps, includeSubdirs?: false} open each image in folder (png, jpg, tif, bmp, gif, webp, psd), select it, trace it with the preset, save it into destinationFolder as <name>.<ext> (-2, -3… added when that name is taken, so no file is replaced) and close it again, whether it traced or not; the document that was active stays active. Optional settings use their defaults only when omitted; null and values of the wrong type return an error before any image is opened. Caps: 500 images, 8 folder levels; a folder with more than 1,000 entries is refused. Not on the web (no file system) → {traced: [{path, output}], failed: [{path, error}], format} (#4921)",
always,
batch_trace::batch_trace_folder
),
@@ -8,9 +8,9 @@ use serde_json::json;
#[cfg(not(target_arch = "wasm32"))]
use super::super::super::fileio;
use super::super::super::{Result, Session, bad};
#[cfg(not(target_arch = "wasm32"))]
use super::super::super::{bool_or, str_param};
use super::super::super::str_param;
use super::super::super::{Result, Session, bad};
/// The command id.
pub(super) const ID: &str = "addon.document.batchTraceFolder";
@@ -69,20 +69,39 @@ fn images(folder: &str, deep: bool, depth: usize, out: &mut Vec<String>) -> Resu
pub(super) fn batch_trace_folder(s: &mut Session, p: &Value) -> Result<Value> {
let folder = str_param(p, "folder").map(fileio::absolute_path).ok_or_else(|| bad(ID, "missing `folder`"))?;
let dest = str_param(p, "destinationFolder").map(fileio::absolute_path).ok_or_else(|| bad(ID, "missing `destinationFolder`"))?;
let format = str_param(p, "format").unwrap_or("vectorcraft");
let format = match p.get("format") {
None => "vectorcraft",
Some(Value::String(value)) => value.as_str(),
Some(_) => return Err(bad(ID, "`format` must be a string")),
};
let preset = match p.get("preset") {
None => "Default",
Some(Value::String(value)) => value.as_str(),
Some(_) => return Err(bad(ID, "`preset` must be a string")),
};
let expand = match p.get("expand") {
None => false,
Some(Value::Bool(value)) => *value,
Some(_) => return Err(bad(ID, "`expand` must be true or false")),
};
let include_subdirs = match p.get("includeSubdirs") {
None => false,
Some(Value::Bool(value)) => *value,
Some(_) => return Err(bad(ID, "`includeSubdirs` must be true or false")),
};
if !FORMATS.contains(&format) {
return Err(bad(ID, format!("`format` must be one of {}", FORMATS.join(", "))));
}
let preset = str_param(p, "preset").unwrap_or("Default").to_string();
let preset = preset.to_string();
let presets = s.execute("imageTrace.presets", &json!({}))?;
if !presets["presets"].as_array().into_iter().flatten().any(|q| q["name"].as_str().is_some_and(|n| n.eq_ignore_ascii_case(&preset))) {
return Err(bad(ID, format!("no tracing preset `{preset}` (see imageTrace.presets)")));
}
let trace = if bool_or(p, "expand", false) { "imageTrace.makeAndExpand" } else { "imageTrace.make" };
let trace = if expand { "imageTrace.makeAndExpand" } else { "imageTrace.make" };
fileio::may_read(&folder)?;
fileio::may_write(&dest)?;
let mut files = vec![];
images(&folder, bool_or(p, "includeSubdirs", false), 0, &mut files)?;
images(&folder, include_subdirs, 0, &mut files)?;
files.sort();
if files.is_empty() {
return Err(bad(ID, "no images in the folder"));
@@ -333,6 +333,35 @@ fn batch_trace_folder_traces_and_saves_each_image() {
let _ = std::fs::remove_dir_all(&dir);
}
/// Batch Trace Folder rejects optional values with the wrong type before opening images.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn batch_trace_folder_rejects_wrong_typed_options() {
const C: &str = "addon.document.batchTraceFolder";
let dir = folder("batch-trace-bad-options");
let src = dir.join("in");
let out = dir.join("out");
std::fs::create_dir_all(&src).unwrap();
let mut s = Session::new();
for (key, value) in [
("format", json!(42)),
("format", Value::Null),
("preset", json!(false)),
("preset", Value::Null),
("expand", json!("true")),
("expand", Value::Null),
("includeSubdirs", json!(1)),
("includeSubdirs", Value::Null),
] {
let mut params = json!({"folder": src, "destinationFolder": out});
params[key] = value;
let error = s.execute(C, &params).unwrap_err();
assert!(error.to_string().contains(&format!("`{key}`")), "{key}: {error}");
assert!(!out.exists(), "invalid options must not create a destination folder");
}
let _ = std::fs::remove_dir_all(&dir);
}
/// A folder too big to list in full is refused rather than traced in part.
#[cfg(not(target_arch = "wasm32"))]
#[test]
+147 -15
View File
@@ -1,33 +1,56 @@
//! Selection Tools (`addon.select.*`), a built-in add-on: Select by Artboards selects the objects
//! overlapping, fully inside or fully outside one or more chosen artboards (#5525). Its submenu
//! (Object › Plug-ins › Selection Tools) and dialog are the UI's.
//! overlapping, fully inside or fully outside one or more chosen artboards (#5525), and Select by
//! Link Status selects the images and placed documents whose file is linked, embedded, missing or
//! modified (#5526), saying which ones it had to leave out and why. Its submenu (Object › Plug-ins
//! › Selection Tools), the Links panel's menu items and the dialogs are the UI's.
#[cfg(test)]
mod tests;
use std::collections::BTreeSet;
use serde_json::{Value, json};
use vectorcraft_doc::NodeId;
use vectorcraft_doc::{LockedArtboards, Node, NodeId, NodeKind};
use vectorcraft_geom::Point;
use super::super::select::{on_artboard, selectable};
use super::super::{CommandSpec, bad, cmd, has_doc, point_indices, text_param};
use crate::{Result, Session};
use super::super::links::{Status, statuses};
use super::super::select::{is_selectable, on_artboard, selectable};
use super::super::{CommandSpec, bad, checked_ids_param, cmd, has_doc, point_indices, switch_or, text_param};
use crate::{DocState, Result, Session};
/// How Select by Artboards relates an object to the chosen artboards (`relation`).
pub const RELATIONS: [&str; 3] = ["overlap", "inside", "outside"];
/// The link statuses Select by Link Status takes (`status`): a file found unchanged, pixels kept
/// in the document, a file not found, a file changed since it was read.
pub const LINK_STATUSES: [&str; 4] = ["linked", "embedded", "missing", "modified"];
/// The add-on's commands: Select by Artboards and Select by Link Status.
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"addon.select.byArtboards",
"Select by Artboards",
["Object", "Plug-ins", "Selection Tools"],
None,
"{artboards: [index…] (0-based, at least one), relation?: \"overlap\" (default: on at least one of them, as select.allOnArtboard takes it: the bounds overlap the artboard or the centre is on it) | \"inside\" (the bounds lie wholly within one of them, edges included) | \"outside\" (on none of them)} select those objects among the ones Select All takes (in isolation mode, the isolated container's); hidden and locked objects, objects on hidden, locked or template layers and art held by a locked artboard are left out. Bounds are geometric, a symbol instance's measured by its art → {count}",
has_doc,
by_artboards
)]
vec![
cmd!(
"addon.select.byArtboards",
"Select by Artboards",
["Object", "Plug-ins", "Selection Tools"],
None,
"{artboards: [index…] (0-based, at least one), relation?: \"overlap\" (default: on at least one of them, as select.allOnArtboard takes it: the bounds overlap the artboard or the centre is on it) | \"inside\" (the bounds lie wholly within one of them, edges included) | \"outside\" (on none of them)} select those objects among the ones Select All takes (in isolation mode, the isolated container's); hidden and locked objects, objects on hidden, locked or template layers and art held by a locked artboard are left out. Bounds are geometric, a symbol instance's measured by its art → {count}",
has_doc,
by_artboards
),
cmd!(
"addon.select.byLinkStatus",
"Select by Link Status",
["Object", "Plug-ins", "Selection Tools"],
None,
"{status: \"linked\" (its file found unchanged) | \"embedded\" | \"missing\" | \"modified\" (its file changed since it was read) | [several of them] (at least one), ids?: [object ids] (pick only among these; default: every image and placed document in the layers), add?: false (add to the selection instead of replacing it), zoom?: false (then zoom to the selection: the desktop app runs addon.arrange.zoomSelection when something was selected; elsewhere the result's zoom flag asks the caller to)} select the image objects and placed documents whose link has that status, as links.list reports it. Those that are hidden or locked, inside a hidden or locked object or layer, on a template layer, on a locked artboard while nothing is isolated, or outside the isolated group or layer are left out and listed with the reason. Only the selection changes, not the document → {count (how many it selected), selected: [ids] (in stacking order, bottom first), skipped: [{id, reason: hidden|locked|template|isolation}], zoom?: true}",
has_doc,
by_link_status
),
]
}
/// `addon.select.byArtboards`: select the objects Select All takes that overlap, lie inside or lie
/// outside the chosen artboards.
fn by_artboards(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.select.byArtboards";
let relation = text_param(p, "relation", C)?.unwrap_or("overlap");
@@ -61,3 +84,112 @@ fn by_artboards(s: &mut Session, p: &Value) -> Result<Value> {
s.select(|_, sel| sel.set(ids))?;
Ok(json!({ "count": s.doc()?.selection.objects.len() }))
}
/// The link statuses `p` asks for (`status`: one, or a list of them), each once.
fn link_statuses(p: &Value, cmd: &str) -> Result<Vec<&'static str>> {
let given: Vec<&Value> = match p.get("status") {
None | Some(Value::Null) => return Err(bad(cmd, "missing `status`: linked, embedded, missing or modified")),
Some(Value::Array(v)) => v.iter().collect(),
Some(v) => vec![v],
};
let mut out = vec![];
for v in given {
let s = v.as_str().ok_or_else(|| bad(cmd, "`status` must be linked, embedded, missing or modified, or a list of them"))?;
let known =
LINK_STATUSES.iter().find(|k| **k == s).ok_or_else(|| bad(cmd, format!("status `{s}`: linked, embedded, missing or modified")))?;
if !out.contains(known) {
out.push(*known);
}
}
if out.is_empty() {
return Err(bad(cmd, "choose at least one status"));
}
Ok(out)
}
/// The link status of every image object and placed document in the layers of `st`, as
/// `links.list` reports it (`ok` named `linked`), in stacking order (bottom first). Each file is
/// looked at once.
pub(crate) fn link_status_of_objects(st: &DocState) -> Vec<(NodeId, &'static str)> {
let linked = statuses(st);
let mut out = vec![];
st.doc.walk(|n| {
if matches!(n.kind, NodeKind::Image(_) | NodeKind::PlacedDocument(_)) {
let status = match linked.get(&n.id).map(|(s, ..)| *s) {
Some(Status::Ok) => "linked",
Some(Status::Modified) => "modified",
Some(Status::Missing) => "missing",
None => "embedded",
};
out.push((n.id, status));
}
});
out
}
/// Why object `id` of `st` can't be selected now ([`is_selectable`]): it is outside the isolated
/// group or layer, on a template layer, hidden (or inside something hidden), or locked (or inside
/// something locked, or on a locked artboard); `None` when it can be. `locks` is the document's
/// [`vectorcraft_doc::Document::locked_artboards`].
fn skip_reason(st: &DocState, locks: &LockedArtboards, id: NodeId) -> Option<&'static str> {
let d = &st.doc;
if is_selectable(d, st.isolation, locks, id) {
return None;
}
let ancestry = d.ancestry(id).unwrap_or_default();
// Outside the isolated container, or the isolated container itself (its art is what's taken).
if let Some(c) = st.isolation.and_then(|i| d.node(i))
&& ancestry.iter().position(|i| *i == c.id).is_none_or(|at| at + 1 == ancestry.len() && c.is_container())
{
return Some("isolation");
}
let held: Vec<&Node> = ancestry.iter().filter_map(|i| d.node(*i)).collect();
Some(if held.iter().any(|n| n.is_template()) {
"template"
} else if held.iter().any(|n| !n.visible) {
"hidden"
} else {
// A locked object, group or layer, or the locked artboard that holds it.
"locked"
})
}
/// `addon.select.byLinkStatus`: select the images and placed documents whose link has one of the
/// statuses asked for (among `ids` when given), replacing the selection or adding to it, and list
/// those left out with the reason ([`skip_reason`]).
fn by_link_status(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.select.byLinkStatus";
let wanted = link_statuses(p, C)?;
let add = switch_or(p, "add", false, C)?;
let zoom = switch_or(p, "zoom", false, C)?;
let only: Option<BTreeSet<NodeId>> = match p.get("ids") {
None | Some(Value::Null) => None,
Some(_) => Some(checked_ids_param(s, p, "ids", C)?.into_iter().collect()),
};
let st = s.doc()?;
let locks = st.doc.locked_artboards();
let (mut picked, mut skipped) = (vec![], vec![]);
for (id, status) in link_status_of_objects(st) {
if !wanted.contains(&status) || only.as_ref().is_some_and(|o| !o.contains(&id)) {
continue;
}
match skip_reason(st, &locks, id) {
None => picked.push(id),
Some(reason) => skipped.push(json!({ "id": id.0, "reason": reason })),
}
}
s.select(|_, sel| {
if add {
for id in &picked {
sel.add(*id);
}
} else {
sel.set(picked.iter().copied());
}
})?;
let mut out = json!({ "count": picked.len(), "selected": picked.iter().map(|id| id.0).collect::<Vec<_>>(), "skipped": skipped });
if zoom {
out["zoom"] = json!(true);
}
Ok(out)
}
@@ -126,3 +126,185 @@ fn a_symbol_instance_is_measured_by_its_art() {
assert_eq!(pick(&mut s, json!({"artboards": [0], "relation": "inside"})), vec![instance]);
assert_eq!(pick(&mut s, json!({"artboards": [0], "relation": "outside"})), vec![]);
}
/// Select by Link Status.
mod by_link_status {
use serde_json::{Value, json};
use vectorcraft_doc::{Document, NodeId};
use crate::Session;
use crate::tests_links::{BLUE, Folder, RED, place, png, session, write};
const C: &str = "addon.select.byLinkStatus";
/// One linked image whose file stays as it is (`ok`), one whose file changes (`modified`),
/// one whose file goes (`missing`), an embedded one, and a placed document whose file goes
/// (missing too), bottom to top.
struct Links {
s: Session,
ok: NodeId,
modified: NodeId,
missing: NodeId,
embedded: NodeId,
document: NodeId,
_dir: Folder,
}
/// [`Links`] in a fresh folder named after `name`: the files placed, then one changed and two
/// removed.
fn links(name: &str) -> Links {
let dir = Folder::new(name);
let (a, b, c, e, d) = (dir.file("ok.png"), dir.file("changes.png"), dir.file("goes.png"), dir.file("kept.png"), dir.file("page.vectorcraft"));
write(&a, &png(10, 10, RED));
write(&b, &png(12, 10, RED));
write(&c, &png(14, 10, BLUE));
write(&e, &png(16, 10, BLUE));
write(&d, &vectorcraft_format::save_file(&Document::new(80.0, 50.0)));
let mut s = session();
let (ok, modified, missing) = (place(&mut s, &a), place(&mut s, &b), place(&mut s, &c));
let embedded = NodeId(s.execute("file.place", &json!({"path": e, "at": [100, 100], "link": false})).unwrap()["ids"][0].as_u64().unwrap());
let document = place(&mut s, &d);
write(&b, &png(13, 10, BLUE));
std::fs::remove_file(&c).unwrap();
std::fs::remove_file(&d).unwrap();
Links { s, ok, modified, missing, embedded, document, _dir: dir }
}
/// Run the command with `p`, which must succeed.
fn run(s: &mut Session, p: Value) -> Value {
s.execute(C, &p).unwrap_or_else(|e| panic!("{p}: {e}"))
}
/// `v` sorted.
fn sorted(mut v: Vec<NodeId>) -> Vec<NodeId> {
v.sort();
v
}
/// The selected objects, sorted.
fn selection(s: &Session) -> Vec<NodeId> {
sorted(s.doc().unwrap().selection.objects.clone())
}
/// The ids of a JSON list, sorted.
fn ids(v: &Value) -> Vec<NodeId> {
sorted(v.as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect())
}
#[test]
fn each_status_selects_its_images_and_placed_documents() {
let Links { mut s, ok, modified, missing, embedded, document, _dir } = links("select-status");
// As the Links panel lists them.
let listed = s.execute("links.list", &json!({})).unwrap();
let status = |id: NodeId| listed["links"].as_array().unwrap().iter().find(|r| r["id"] == id.0).unwrap()["status"].clone();
assert_eq!([ok, modified, missing, embedded, document].map(status), ["ok", "modified", "missing", "embedded", "missing"].map(|s| json!(s)));
let undo = s.doc().unwrap().history.undo.len();
for (status, want) in [("linked", vec![ok]), ("modified", vec![modified]), ("missing", vec![missing, document]), ("embedded", vec![embedded])]
{
s.execute("select.none", &json!({})).unwrap();
let r = run(&mut s, json!({"status": status}));
assert_eq!((ids(&r["selected"]), r["count"].as_u64()), (sorted(want.clone()), Some(want.len() as u64)), "{status}: {r}");
assert_eq!(selection(&s), sorted(want), "{status}");
assert_eq!(r["skipped"], json!([]));
assert!(r.get("zoom").is_none());
}
// Several at once, in stacking order (bottom first); a status listed twice counts once.
let r = run(&mut s, json!({"status": ["missing", "linked", "missing"]}));
assert_eq!(r["selected"], json!([ok.0, missing.0, document.0]));
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "only the selection changes");
}
#[test]
fn ids_add_and_zoom() {
let Links { mut s, ok, modified, embedded, document, _dir, .. } = links("select-options");
// Only among the ids given; other objects among them (a rectangle) are passed over.
let rect = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap()["id"].as_u64().unwrap();
let r = run(&mut s, json!({"status": "missing", "ids": [document.0, ok.0, rect]}));
assert_eq!(r["selected"], json!([document.0]));
assert_eq!(selection(&s), vec![document]);
// Added to the selection.
let r = run(&mut s, json!({"status": "embedded", "add": true}));
assert_eq!((r["count"].as_u64(), r["selected"].clone()), (Some(1), json!([embedded.0])));
assert_eq!(selection(&s), sorted(vec![document, embedded]));
// Replacing it by default.
run(&mut s, json!({"status": "modified"}));
assert_eq!(selection(&s), vec![modified]);
// Nothing to select: added, the selection stays; replacing, it empties.
let r = run(&mut s, json!({"status": "linked", "ids": [embedded.0], "add": true}));
assert_eq!((r["count"].as_u64(), r["selected"].clone(), r["skipped"].clone()), (Some(0), json!([]), json!([])));
assert_eq!(selection(&s), vec![modified]);
run(&mut s, json!({"status": "linked", "ids": [embedded.0]}));
assert_eq!(selection(&s), vec![]);
// Zoom is reported for the caller (the desktop app zooms).
assert_eq!(run(&mut s, json!({"status": "linked", "zoom": true}))["zoom"], true);
assert!(run(&mut s, json!({"status": "linked", "zoom": false})).get("zoom").is_none());
}
#[test]
fn hidden_locked_template_and_isolated_ones_are_skipped_with_the_reason() {
let dir = Folder::new("select-skipped");
let files: Vec<String> = (0..6).map(|i| dir.file(&format!("img{i}.png"))).collect();
for (i, f) in files.iter().enumerate() {
write(f, &png(10 + i as u32, 10, RED));
}
let mut s = session();
let [free, hidden, locked, in_group, mate] = [0, 1, 2, 3, 4].map(|i| place(&mut s, &files[i]));
s.execute("object.setProps", &json!({"ids": [hidden.0], "visible": false})).unwrap();
s.execute("object.setProps", &json!({"ids": [locked.0], "locked": true})).unwrap();
// Inside a locked group.
s.execute("select.set", &json!({"ids": [in_group.0]})).unwrap();
let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("object.setProps", &json!({"ids": [g], "locked": true})).unwrap();
// On a template layer.
let layer = s.execute("layer.new", &json!({"name": "Trace"})).unwrap()["id"].as_u64().unwrap();
let on_template = place(&mut s, &files[5]);
s.execute("layer.setProps", &json!({"id": layer, "template": true})).unwrap();
let r = run(&mut s, json!({"status": "linked"}));
assert_eq!(ids(&r["selected"]), sorted(vec![free, mate]), "{r}");
let mut reasons: Vec<(u64, String)> =
r["skipped"].as_array().unwrap().iter().map(|k| (k["id"].as_u64().unwrap(), k["reason"].as_str().unwrap().to_string())).collect();
reasons.sort();
let mut want: Vec<(u64, String)> = [(hidden, "hidden"), (locked, "locked"), (in_group, "locked"), (on_template, "template")]
.into_iter()
.map(|(id, why)| (id.0, why.to_string()))
.collect();
want.sort();
assert_eq!(reasons, want, "{r}");
assert!(reasons.iter().all(|(_, why)| ["hidden", "locked", "template", "isolation"].contains(&why.as_str())));
// In isolation mode, those outside the isolated group are left out.
s.execute("select.set", &json!({"ids": [mate.0]})).unwrap();
let iso = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("object.isolate", &json!({"id": iso})).unwrap();
let r = run(&mut s, json!({"status": "linked"}));
assert_eq!(r["selected"], json!([mate.0]), "{r}");
let why = |id: NodeId| r["skipped"].as_array().unwrap().iter().find(|k| k["id"] == id.0).map(|k| k["reason"].clone());
assert_eq!(why(free), Some(json!("isolation")));
assert_eq!(why(hidden), Some(json!("isolation")));
}
#[test]
fn bad_params_are_errors_and_leave_the_selection() {
let Links { mut s, ok, _dir, .. } = links("select-bad");
for p in [
json!({}),
json!({"status": null}),
json!({"status": []}),
json!({"status": "lost"}),
json!({"status": ["linked", "lost"]}),
json!({"status": 3}),
json!({"status": [true]}),
json!({"status": "linked", "add": "yes"}),
json!({"status": "linked", "zoom": 1}),
json!({"status": "linked", "ids": "1"}),
json!({"status": "linked", "ids": [999_999]}),
json!({"status": "linked", "ids": [-1]}),
json!({"status": "linked", "stauts": "missing"}),
] {
s.execute("select.set", &json!({"ids": [ok.0]})).unwrap();
assert!(s.execute(C, &p).is_err(), "{p}");
assert_eq!(s.doc().unwrap().selection.objects, vec![ok], "{p}");
}
// Without a document it is off, not a crash.
assert!(Session::new().execute(C, &json!({"status": "linked"})).is_err());
}
}
+477
View File
@@ -0,0 +1,477 @@
//! 3D Box and customizable shapes (`addon.shapes.*`), a built-in add-on: creates rotatable 3D boxes
//! (`addon.shapes.box3d`) and customizable rectangles, ellipses, polygons, stars and spirals
//! (`addon.shapes.rectangle`, `addon.shapes.ellipse`, `addon.shapes.polygon`, `addon.shapes.star`,
//! `addon.shapes.spiral`), and configures extended live-shape parameters on selected shapes
//! (`addon.shapes.configure`: symmetric or per-corner radii, pie/chord/arc/whole modes, polygon/star
//! spoke ratio, corner rounding, randomization, spiral turns/divergence/inner radius, and 3D box
//! rotation angles).
#[cfg(test)]
mod tests;
use serde_json::{Value, json};
use vectorcraft_doc::{LiveShape, NodeId, NodeKind};
use vectorcraft_geom::{Affine, FillRule, Point, Rect, shapes};
use vectorcraft_tools::addons::box3d::CustomShape;
use super::super::create::insert_look;
use super::super::{
CommandSpec, Result, Session, bool_or, check_numbers, check_switches, cmd, f64_or, f64_req, has_doc, has_selection, str_param, targets,
};
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"addon.shapes.rectangle",
"Rectangle",
[],
None,
"{x, y, width, height, radius?: pt, radii?: [tl,tr,br,bl], startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, rotation?: deg} → {id}",
has_doc,
rectangle
),
cmd!(
"addon.shapes.ellipse",
"Ellipse",
[],
None,
"{x, y, width, height, startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, rotation?: deg} → {id}",
has_doc,
ellipse
),
cmd!(
"addon.shapes.polygon",
"Polygon",
[],
None,
"{cx, cy, radius, sides=6, rounded=0, randomized=0, startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, rotation?: deg} → {id}",
has_doc,
polygon
),
cmd!(
"addon.shapes.star",
"Star",
[],
None,
"{cx, cy, radius1, radius2?, points=5, rounded=0, randomized=0, startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, rotation?: deg} → {id}",
has_doc,
star
),
cmd!(
"addon.shapes.spiral",
"Spiral",
[],
None,
"{cx, cy, radius, turns=3, divergence=1, innerRadius=0, clockwise=true} → {id}",
has_doc,
spiral
),
cmd!(
"addon.shapes.box3d",
"3D Box",
[],
None,
"{x, y, width, height, angleX=30, angleY=30, angleZ=0, parallelX=false, parallelY=true, parallelZ=false} → {id}",
has_doc,
box3d
),
cmd!(
"addon.shapes.configure",
"Configure Shape",
[],
None,
"{ids?, radius?, radii?: [tl,tr,br,bl], startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, sides?, isStar?, spokeRatio?, rounded?, randomized?, turns?, divergence?, innerRadius?, angleX?, angleY?, angleZ?, parallelX?, parallelY?, parallelZ?, reset?: bool} → {updated}",
has_selection,
configure
),
]
}
fn parse_arc_params(p: &Value) -> ((f64, f64), shapes::EllipseMode) {
let start = f64_or(p, "startAngle", 0.0);
let end = f64_or(p, "endAngle", 360.0);
let mode = match str_param(p, "arcMode") {
Some("pie" | "slice") => shapes::EllipseMode::Slice,
Some("chord") => shapes::EllipseMode::Chord,
Some("arc" | "open") => shapes::EllipseMode::Arc,
_ => shapes::EllipseMode::Whole,
};
let span = (end - start).rem_euclid(360.0);
let pie = if mode == shapes::EllipseMode::Whole && (span < 1e-6 || (span - 360.0).abs() < 1e-6) { (0.0, 360.0) } else { (start, end) };
(pie, mode)
}
fn rect_of(p: &Value, c: &str) -> Result<Rect> {
let x = f64_req(p, "x", c)?;
let y = f64_req(p, "y", c)?;
let w = f64_req(p, "width", c)?;
let h = f64_req(p, "height", c)?;
Ok(Rect::new(x, y, x + w.abs(), y + h.abs()).abs())
}
fn rect_xf(r: Rect, rot: f64) -> Affine {
if rot == 0.0 || !rot.is_finite() {
Affine::translate(r.origin().to_vec2())
} else {
Affine::translate(r.center().to_vec2()) * vectorcraft_geom::rotate_deg(rot) * Affine::translate((-r.width() / 2.0, -r.height() / 2.0))
}
}
fn insert_custom(s: &mut Session, label: &str, live: Option<LiveShape>, cs: CustomShape) -> Result<Value> {
let path = match (&live, cs.needs_extra_storage()) {
(Some(l), false) => l.to_path(),
_ => cs.to_path(),
};
let kind = NodeKind::Path { path, rule: FillRule::NonZero, live: live.map(Box::new), clipping: false, guide: false };
let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
let val = insert_look(s, label, kind, look, None, true)?;
if cs.needs_extra_storage()
&& let Some(raw_id) = val.get("id").and_then(Value::as_u64)
&& let Ok(st) = s.doc_mut()
&& let Some(n) = std::sync::Arc::make_mut(&mut st.doc).node_mut(NodeId(raw_id))
{
cs.write_to_node(n);
}
Ok(val)
}
fn rectangle(s: &mut Session, p: &Value) -> Result<Value> {
let c = "addon.shapes.rectangle";
check_numbers(p, &["radius", "startAngle", "endAngle", "rotation"], c)?;
let r = rect_of(p, c)?;
let radius = f64_or(p, "radius", 0.0).max(0.0);
let mut radii = [radius; 4];
if let Some(arr) = p.get("radii").and_then(Value::as_array)
&& arr.len() == 4
{
for (i, item) in arr.iter().enumerate() {
if let Some(val) = item.as_f64().filter(|n| n.is_finite()) {
radii[i] = val.max(0.0);
}
}
}
let (pie, arc_mode) = parse_arc_params(p);
let xf = rect_xf(r, f64_or(p, "rotation", 0.0));
let live = LiveShape::Rectangle { w: r.width(), h: r.height(), radii, kinds: Default::default(), radii_relative: false, xf };
let cs = CustomShape::Rectangle { w: r.width(), h: r.height(), radii, kinds: Default::default(), radii_relative: false, xf, pie, arc_mode };
let label = if radii.iter().any(|&v| v > 0.0) { "Rounded Rectangle" } else { "Rectangle" };
insert_custom(s, label, Some(live), cs)
}
fn ellipse(s: &mut Session, p: &Value) -> Result<Value> {
let c = "addon.shapes.ellipse";
check_numbers(p, &["startAngle", "endAngle", "rotation"], c)?;
let r = rect_of(p, c)?;
let (pie, arc_mode) = parse_arc_params(p);
let xf = rect_xf(r, f64_or(p, "rotation", 0.0));
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie, xf };
let cs = CustomShape::Ellipse { w: r.width(), h: r.height(), pie, arc_mode, xf };
insert_custom(s, "Ellipse", Some(live), cs)
}
fn polygon(s: &mut Session, p: &Value) -> Result<Value> {
let c = "addon.shapes.polygon";
let center = Point::new(f64_req(p, "cx", c)?, f64_req(p, "cy", c)?);
let r = f64_req(p, "radius", c)?.abs();
check_numbers(p, &["sides", "rotation", "rounded", "randomized", "startAngle", "endAngle"], c)?;
let sides = (f64_or(p, "sides", 6.0).round() as i64).clamp(3, 1000) as u32;
let rot = f64_or(p, "rotation", 0.0);
let rounded = f64_or(p, "rounded", 0.0).clamp(-10.0, 10.0);
let randomized = f64_or(p, "randomized", 0.0).clamp(-10.0, 10.0);
let (pie, arc_mode) = parse_arc_params(p);
let xf = Affine::translate(center.to_vec2()) * vectorcraft_geom::rotate_deg(rot);
let live = LiveShape::Polygon { radius: r, sides, xf, radii: vec![], kinds: vec![], radii_relative: false };
let cs = CustomShape::Polygon {
radius: r,
sides,
xf,
radii: vec![],
kinds: vec![],
radii_relative: false,
spoke_ratio: None,
rounded,
randomized,
pie,
arc_mode,
};
insert_custom(s, "Polygon", Some(live), cs)
}
fn star(s: &mut Session, p: &Value) -> Result<Value> {
let c = "addon.shapes.star";
let center = Point::new(f64_req(p, "cx", c)?, f64_req(p, "cy", c)?);
let r1 = f64_req(p, "radius1", c)?.abs();
check_numbers(p, &["radius2", "points", "rotation", "rounded", "randomized", "startAngle", "endAngle"], c)?;
let r2 = f64_or(p, "radius2", r1 / 2.0).abs();
let points = (f64_or(p, "points", 5.0).round() as i64).clamp(3, 1000) as u32;
let rot = f64_or(p, "rotation", 0.0);
let rounded = f64_or(p, "rounded", 0.0).clamp(-10.0, 10.0);
let randomized = f64_or(p, "randomized", 0.0).clamp(-10.0, 10.0);
let (pie, arc_mode) = parse_arc_params(p);
let xf = Affine::translate(center.to_vec2()) * vectorcraft_geom::rotate_deg(rot);
let ratio = if r1 > 1e-9 { (r2 / r1).clamp(0.01, 1.0) } else { 0.5 };
let cs = CustomShape::Polygon {
radius: r1,
sides: points,
xf,
radii: vec![],
kinds: vec![],
radii_relative: false,
spoke_ratio: Some(ratio),
rounded,
randomized,
pie,
arc_mode,
};
insert_custom(s, "Star", None, cs)
}
fn spiral(s: &mut Session, p: &Value) -> Result<Value> {
let c = "addon.shapes.spiral";
let center = Point::new(f64_req(p, "cx", c)?, f64_req(p, "cy", c)?);
let r = f64_req(p, "radius", c)?.abs();
check_numbers(p, &["turns", "divergence", "innerRadius"], c)?;
check_switches(p, &["clockwise"], c)?;
let turns = f64_or(p, "turns", 3.0).clamp(0.01, 1024.0);
let divergence = f64_or(p, "divergence", 1.0).clamp(0.0, 1000.0);
let inner_radius = f64_or(p, "innerRadius", 0.0).clamp(0.0, 0.999);
let clockwise = bool_or(p, "clockwise", true);
let cs = CustomShape::Spiral { center, radius: r, turns, divergence, inner_radius, clockwise };
insert_custom(s, "Spiral", None, cs)
}
fn box3d(s: &mut Session, p: &Value) -> Result<Value> {
let c = "addon.shapes.box3d";
let r = rect_of(p, c)?;
check_numbers(p, &["angleX", "angleY", "angleZ"], c)?;
check_switches(p, &["parallelX", "parallelY", "parallelZ"], c)?;
let angle_x = f64_or(p, "angleX", 30.0);
let angle_y = f64_or(p, "angleY", 30.0);
let angle_z = f64_or(p, "angleZ", 0.0);
let parallel_x = bool_or(p, "parallelX", false);
let parallel_y = bool_or(p, "parallelY", true);
let parallel_z = bool_or(p, "parallelZ", false);
let cs = CustomShape::Box3d {
w: r.width(),
h: r.height(),
angle_x,
angle_y,
angle_z,
parallel_x,
parallel_y,
parallel_z,
xf: Affine::translate(r.origin().to_vec2()),
};
let kind = NodeKind::Path { path: cs.to_path(), rule: FillRule::NonZero, live: None, clipping: false, guide: false };
let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
let val = insert_look(s, "3D Box", kind, look, Some("3D Box".into()), true)?;
if let Some(raw_id) = val.get("id").and_then(Value::as_u64)
&& let Ok(st) = s.doc_mut()
&& let Some(n) = std::sync::Arc::make_mut(&mut st.doc).node_mut(NodeId(raw_id))
{
cs.write_to_node(n);
}
Ok(val)
}
fn configure(s: &mut Session, p: &Value) -> Result<Value> {
let c = "addon.shapes.configure";
check_numbers(
p,
&[
"radius",
"startAngle",
"endAngle",
"sides",
"spokeRatio",
"rounded",
"randomized",
"turns",
"divergence",
"innerRadius",
"angleX",
"angleY",
"angleZ",
],
c,
)?;
check_switches(p, &["isStar", "parallelX", "parallelY", "parallelZ", "reset"], c)?;
let ids = targets(s, p)?;
let reset = bool_or(p, "reset", false);
let spiral_hint = p.get("turns").is_some() || p.get("divergence").is_some() || p.get("innerRadius").is_some();
let updated = s.edit("Live Shape", |d, _| {
let mut count = 0usize;
for id in ids {
let Some(n) = d.node_mut(id) else { continue };
let Some(mut cs) = CustomShape::read_for_update(n, spiral_hint) else { continue };
if apply_shape_params(&mut cs, p, reset) {
cs.write_to_node(n);
count += 1;
}
}
Ok(count)
})?;
Ok(json!({ "updated": updated }))
}
fn num_param(p: &Value, k: &str) -> Option<f64> {
p.get(k).and_then(Value::as_f64).filter(|v| v.is_finite())
}
fn apply_arc_params(p: &Value, pie: &mut (f64, f64), arc_mode: &mut shapes::EllipseMode) -> bool {
let mut changed = false;
if let Some(a0) = num_param(p, "startAngle") {
pie.0 = a0.rem_euclid(360.0);
changed = true;
}
if let Some(a1) = num_param(p, "endAngle") {
pie.1 = a1.rem_euclid(360.0);
changed = true;
}
if let Some(m) = str_param(p, "arcMode") {
*arc_mode = parse_mode(m);
if *arc_mode == shapes::EllipseMode::Whole {
*pie = (0.0, 360.0);
} else if (pie.1 - pie.0).abs() < 1e-6 || ((pie.1 - pie.0).abs() - 360.0).abs() < 1e-6 {
*pie = (0.0, 270.0);
}
changed = true;
}
changed
}
fn apply_rect_params(p: &Value, reset: bool, max_r: f64, radii: &mut [f64; 4], pie: &mut (f64, f64), arc_mode: &mut shapes::EllipseMode) -> bool {
let mut changed = false;
if reset {
*radii = [0.0; 4];
*pie = (0.0, 360.0);
*arc_mode = shapes::EllipseMode::Whole;
changed = true;
}
if let Some(r) = num_param(p, "radius") {
*radii = [r.clamp(0.0, max_r); 4];
changed = true;
}
if let Some(arr) = p.get("radii").and_then(Value::as_array)
&& arr.len() == 4
{
for (i, v) in arr.iter().enumerate() {
if let Some(r) = v.as_f64().filter(|x| x.is_finite()) {
radii[i] = r.clamp(0.0, max_r);
changed = true;
}
}
}
changed | apply_arc_params(p, pie, arc_mode)
}
fn apply_poly_params(p: &Value, reset: bool, sides: &mut u32, spoke_ratio: &mut Option<f64>, rounded: &mut f64, randomized: &mut f64) -> bool {
let mut changed = false;
if reset {
*rounded = 0.0;
*randomized = 0.0;
if spoke_ratio.is_some() {
*spoke_ratio = Some(0.5);
}
changed = true;
}
if let Some(n_sides) = p.get("sides").and_then(Value::as_u64) {
*sides = (n_sides as u32).clamp(3, 1000);
changed = true;
}
if let Some(star) = p.get("isStar").and_then(Value::as_bool) {
*spoke_ratio = if star { Some(spoke_ratio.unwrap_or(0.5)) } else { None };
changed = true;
}
if let Some(sr) = num_param(p, "spokeRatio") {
*spoke_ratio = Some(sr.clamp(0.01, 1.0));
changed = true;
}
if let Some(rnd) = num_param(p, "rounded") {
*rounded = rnd.clamp(-10.0, 10.0);
changed = true;
}
if let Some(rand) = num_param(p, "randomized") {
*randomized = rand.clamp(-10.0, 10.0);
changed = true;
}
changed
}
fn apply_shape_params(cs: &mut CustomShape, p: &Value, reset: bool) -> bool {
match cs {
CustomShape::Rectangle { w, h, radii, pie, arc_mode, .. } => apply_rect_params(p, reset, w.min(*h) / 2.0, radii, pie, arc_mode),
CustomShape::Ellipse { pie, arc_mode, .. } => {
let mut changed = false;
if reset {
*pie = (0.0, 360.0);
*arc_mode = shapes::EllipseMode::Whole;
changed = true;
}
changed | apply_arc_params(p, pie, arc_mode)
}
CustomShape::Polygon { sides, spoke_ratio, rounded, randomized, pie, arc_mode, .. } => {
if reset {
*pie = (0.0, 360.0);
*arc_mode = shapes::EllipseMode::Whole;
}
apply_poly_params(p, reset, sides, spoke_ratio, rounded, randomized) | apply_arc_params(p, pie, arc_mode)
}
CustomShape::Spiral { turns, divergence, inner_radius, .. } => {
let mut changed = false;
if reset {
*turns = 3.0;
*divergence = 1.0;
*inner_radius = 0.0;
changed = true;
}
if let Some(t) = num_param(p, "turns") {
*turns = t.clamp(0.01, 1024.0);
changed = true;
}
if let Some(div) = num_param(p, "divergence") {
*divergence = div.clamp(0.0, 1000.0);
changed = true;
}
if let Some(ir) = num_param(p, "innerRadius") {
*inner_radius = ir.clamp(0.0, 0.999);
changed = true;
}
changed
}
CustomShape::Box3d { angle_x, angle_y, angle_z, parallel_x, parallel_y, parallel_z, .. } => {
let mut changed = false;
if reset {
*angle_x = 30.0;
*angle_y = 30.0;
*angle_z = 0.0;
*parallel_x = false;
*parallel_y = true;
*parallel_z = false;
changed = true;
}
for (k, slot) in [("angleX", angle_x), ("angleY", angle_y), ("angleZ", angle_z)] {
if let Some(v) = num_param(p, k) {
*slot = v;
changed = true;
}
}
for (k, slot) in [("parallelX", parallel_x), ("parallelY", parallel_y), ("parallelZ", parallel_z)] {
if let Some(v) = p.get(k).and_then(Value::as_bool) {
*slot = v;
changed = true;
}
}
changed
}
}
}
fn parse_mode(m: &str) -> shapes::EllipseMode {
match m {
"pie" | "slice" => shapes::EllipseMode::Slice,
"chord" => shapes::EllipseMode::Chord,
"arc" | "open" => shapes::EllipseMode::Arc,
_ => shapes::EllipseMode::Whole,
}
}
@@ -0,0 +1,137 @@
use serde_json::json;
use vectorcraft_doc::{LiveShape, NodeId, NodeKind};
use vectorcraft_geom::{Affine, Rect, shapes};
use vectorcraft_tools::addons::box3d::CustomShape;
use crate::Session;
fn new_session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
s
}
#[test]
fn default_shapes_do_not_alter_standard_documents() {
let mut s = new_session();
// Default rectangle: standard LiveShape::Rectangle, no vc-shape-tools attribute.
let rect_id =
NodeId(s.execute("shape.rectangle", &json!({"x": 10.0, "y": 20.0, "width": 100.0, "height": 50.0})).unwrap()["id"].as_u64().unwrap());
let n = s.doc().unwrap().doc.node(rect_id).unwrap();
assert!(n.extras().attrs.is_none());
let NodeKind::Path { path, live: Some(live), .. } = &n.kind else { panic!("expected live path") };
assert_eq!(
**live,
LiveShape::Rectangle {
w: 100.0,
h: 50.0,
radii: [0.0; 4],
kinds: Default::default(),
radii_relative: false,
xf: Affine::translate((10.0, 20.0))
}
);
assert_eq!(path, &shapes::rectangle(Rect::new(10.0, 20.0, 110.0, 70.0)));
// Default ellipse: standard LiveShape::Ellipse, no vc-shape-tools attribute.
let ell_id = NodeId(s.execute("shape.ellipse", &json!({"x": 0.0, "y": 0.0, "width": 80.0, "height": 60.0})).unwrap()["id"].as_u64().unwrap());
let n = s.doc().unwrap().doc.node(ell_id).unwrap();
assert!(n.extras().attrs.is_none());
let NodeKind::Path { path, live: Some(live), .. } = &n.kind else { panic!("expected live path") };
assert_eq!(**live, LiveShape::Ellipse { w: 80.0, h: 60.0, pie: (0.0, 360.0), xf: Affine::IDENTITY });
assert_eq!(path, &shapes::ellipse(Rect::new(0.0, 0.0, 80.0, 60.0)));
}
#[test]
fn addon_shapes_commands_and_format_roundtrip_preserve_paths() {
let mut s = new_session();
// Create customizable shapes through addon.shapes.* commands.
let box_id = NodeId(
s.execute(
"addon.shapes.box3d",
&json!({"x": 10.0, "y": 10.0, "width": 100.0, "height": 80.0, "angleX": 30.0, "angleY": 35.0, "angleZ": 0.0}),
)
.unwrap()["id"]
.as_u64()
.unwrap(),
);
let n = s.doc().unwrap().doc.node(box_id).unwrap();
let NodeKind::Path { path, .. } = &n.kind else { panic!("expected path") };
assert_eq!(path.subpaths.len(), 3);
assert!(
matches!(CustomShape::read(n), Some(CustomShape::Box3d { angle_x, angle_y, .. }) if (angle_x - 30.0).abs() < 1e-6 && (angle_y - 35.0).abs() < 1e-6)
);
s.execute("addon.shapes.configure", &json!({"angleX": 45.0, "parallelX": true})).unwrap();
let n = s.doc().unwrap().doc.node(box_id).unwrap();
assert!(matches!(CustomShape::read(n), Some(CustomShape::Box3d { angle_x, parallel_x: true, .. }) if (angle_x - 45.0).abs() < 1e-6));
let ell_id = NodeId(
s.execute(
"addon.shapes.ellipse",
&json!({"x": 0.0, "y": 0.0, "width": 100.0, "height": 100.0, "arcMode": "arc", "startAngle": 30.0, "endAngle": 210.0}),
)
.unwrap()["id"]
.as_u64()
.unwrap(),
);
let n = s.doc().unwrap().doc.node(ell_id).unwrap();
let NodeKind::Path { path, .. } = &n.kind else { panic!("expected path") };
assert!(!path.subpaths[0].closed);
s.execute("addon.shapes.configure", &json!({"arcMode": "chord"})).unwrap();
let n = s.doc().unwrap().doc.node(ell_id).unwrap();
let NodeKind::Path { path, .. } = &n.kind else { panic!("expected path") };
assert!(path.subpaths[0].closed);
let rect_id = NodeId(
s.execute("addon.shapes.rectangle", &json!({"x": 0.0, "y": 0.0, "width": 100.0, "height": 80.0, "radii": [10.0, 20.0, 5.0, 0.0], "arcMode": "pie", "startAngle": 0.0, "endAngle": 180.0}))
.unwrap()["id"]
.as_u64()
.unwrap(),
);
let n = s.doc().unwrap().doc.node(rect_id).unwrap();
assert!(
matches!(CustomShape::read(n), Some(CustomShape::Rectangle { radii, arc_mode: shapes::EllipseMode::Slice, .. }) if radii == [10.0, 20.0, 5.0, 0.0])
);
let poly_id = NodeId(
s.execute("addon.shapes.polygon", &json!({"cx": 50.0, "cy": 50.0, "radius": 40.0, "sides": 5, "rounded": 0.25, "randomized": 0.1})).unwrap()
["id"]
.as_u64()
.unwrap(),
);
s.execute("addon.shapes.configure", &json!({"isStar": true, "spokeRatio": 0.4})).unwrap();
let n = s.doc().unwrap().doc.node(poly_id).unwrap();
assert!(
matches!(CustomShape::read(n), Some(CustomShape::Polygon { spoke_ratio: Some(sr), rounded, .. }) if (sr - 0.4).abs() < 1e-6 && (rounded - 0.25).abs() < 1e-6)
);
let spiral_id = NodeId(
s.execute("addon.shapes.spiral", &json!({"cx": 60.0, "cy": 60.0, "radius": 45.0, "turns": 4.0, "divergence": 1.4, "innerRadius": 0.2}))
.unwrap()["id"]
.as_u64()
.unwrap(),
);
let n = s.doc().unwrap().doc.node(spiral_id).unwrap();
assert!(
matches!(CustomShape::read(n), Some(CustomShape::Spiral { turns, divergence, .. }) if (turns - 4.0).abs() < 1e-6 && (divergence - 1.4).abs() < 1e-6)
);
// Verify that saving and reopening a document containing add-on shapes preserves both the
// baked PathData/LiveShape (for a build that ignores the add-on attribute) and the stored
// extras attribute across a save/load roundtrip.
let doc_before = s.doc().unwrap().doc.clone();
let bytes = vectorcraft_format::save(&doc_before, false);
let doc_after = vectorcraft_format::load(&bytes).unwrap();
let re_saved = vectorcraft_format::save(&doc_after, false);
assert_eq!(bytes, re_saved);
for id in [box_id, ell_id, rect_id, poly_id, spiral_id] {
let a = doc_before.node(id).unwrap();
let b = doc_after.node(id).unwrap();
assert_eq!(a.kind, b.kind);
assert_eq!(CustomShape::read(a), CustomShape::read(b));
}
}
+131 -7
View File
@@ -12,14 +12,14 @@
mod flavours;
pub(crate) mod resources;
use std::collections::BTreeMap;
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_brush::Brush;
use vectorcraft_color::Swatch;
use vectorcraft_doc::{Document, GraphicStyle, ImageBlob, Node, NodeId, PatternDef, Symbol, TextStyleDef};
use vectorcraft_geom::Rect;
use vectorcraft_doc::{Document, GraphicStyle, ImageBlob, Node, NodeId, NodeKind, PatternDef, Selection, Symbol, TextStyleDef};
use vectorcraft_geom::{PathData, Rect};
pub use flavours::{AI, BITMAP, EMF, EPS, FILE_HEAD, Flavour, PASTE_ORDER, PDF, PNG, SVG, TEXT, file_flavour, is_address, names_a_picture};
pub use flavours::{ImageRead, read_image};
@@ -98,6 +98,114 @@ pub struct Clipboard {
pub guides: Vec<vectorcraft_doc::Guide>,
}
/// Indices of segments selected on `sp` (either explicitly or via incident anchors).
pub(crate) fn subpath_selected_segments(
sp: &vectorcraft_geom::SubPath,
si: usize,
seg_refs: Option<&BTreeSet<(usize, usize)>>,
anchor_refs: Option<&BTreeSet<(usize, usize)>>,
) -> BTreeSet<usize> {
let seg_count = sp.segment_count();
if seg_count == 0 {
return BTreeSet::new();
}
let n = sp.anchors.len();
let mut selected_segs = BTreeSet::new();
let has_explicit_segs = seg_refs.is_some_and(|segments| segments.iter().any(|&(s, _)| s == si));
if has_explicit_segs {
if let Some(segments) = seg_refs {
for &(s, seg) in segments {
if s == si && seg < seg_count {
selected_segs.insert(seg);
}
}
}
return selected_segs;
}
if let Some(anchors) = anchor_refs {
let sub_anchors: BTreeSet<usize> = anchors.iter().filter_map(|&(s, a)| (s == si && a < n).then_some(a)).collect();
if !sub_anchors.is_empty() {
for i in 0..seg_count {
let next = (i + 1) % n;
if sub_anchors.contains(&i) && sub_anchors.contains(&next) {
selected_segs.insert(i);
}
}
for &i in &sub_anchors {
let prev_selected = if sp.closed { sub_anchors.contains(&((i + n - 1) % n)) } else { i > 0 && sub_anchors.contains(&(i - 1)) };
let next_selected = if sp.closed { sub_anchors.contains(&((i + 1) % n)) } else { i + 1 < n && sub_anchors.contains(&(i + 1)) };
if !prev_selected && !next_selected {
if sp.closed {
selected_segs.insert((i + n - 1) % n);
selected_segs.insert(i);
} else {
if i > 0 {
selected_segs.insert(i - 1);
}
if i < seg_count {
selected_segs.insert(i);
}
}
}
}
}
}
selected_segs
}
/// When direct selection is active on a path (some anchors or segments selected), extract only
/// the selected runs as new open path nodes (with retracted endpoint handles). Returns `None`
/// when the node is selected whole or is not a path.
pub(crate) fn extract_direct_selection(node: &Node, selection: &Selection) -> Option<Vec<Node>> {
let seg_refs = selection.segments.get(&node.id);
let anchor_refs = selection.anchors.get(&node.id);
if seg_refs.is_none() && anchor_refs.is_none() {
return None;
}
let path = node.path_data()?;
let mut subpath_segs = Vec::new();
let mut total_segs = 0;
let mut total_selected = 0;
for (si, sp) in path.subpaths.iter().enumerate() {
let segs = subpath_selected_segments(sp, si, seg_refs, anchor_refs);
total_segs += sp.segment_count();
total_selected += segs.len();
subpath_segs.push(segs);
}
if total_selected == 0 {
return None;
}
// When every segment of the path is selected, copy the object unchanged.
if total_segs > 0 && total_selected == total_segs {
return None;
}
let mut pieces = vec![];
for (sp, selected_segs) in path.subpaths.iter().zip(subpath_segs) {
let seg_count = sp.segment_count();
if selected_segs.is_empty() || seg_count == 0 {
continue;
}
let unselected: BTreeSet<usize> = (0..seg_count).filter(|i| !selected_segs.contains(i)).collect();
let surviving = if unselected.is_empty() { vec![sp.clone()] } else { super::path::without_segments(sp.clone(), &unselected) };
for surviving_sp in surviving {
let mut piece = node.clone();
if let NodeKind::Path { rule, clipping, guide, .. } = &node.kind {
piece.kind = NodeKind::Path { path: PathData::single(surviving_sp), rule: *rule, live: None, clipping: *clipping, guide: *guide };
}
pieces.push(piece);
}
}
if pieces.is_empty() { None } else { Some(pieces) }
}
impl Clipboard {
pub fn is_empty(&self) -> bool {
self.nodes.is_empty() && self.artboards.is_empty() && self.guides.is_empty()
@@ -118,15 +226,31 @@ impl Clipboard {
}
/// Objects `roots` of `st`'s document with their resources, source artboard and layers.
pub(crate) fn copy(st: &DocState, roots: &[NodeId]) -> Self {
pub(crate) fn copy(st: &DocState, roots: &[NodeId], direct: bool) -> Self {
let d = &*st.doc;
let mut nodes = vec![];
let mut source_layers = vec![];
for id in roots {
let (Some(n), Some(anc)) = (d.node(*id), d.ancestry(*id)) else { continue };
nodes.push(n.clone());
// The nearest enclosing layer (or sublayer).
source_layers.push(anc.iter().rev().skip(1).find_map(|a| d.node(*a).filter(|l| l.is_layer())).and_then(|l| l.name.clone()));
let layer_name = anc.iter().rev().skip(1).find_map(|a| d.node(*a).filter(|l| l.is_layer())).and_then(|l| l.name.clone());
let compound_parent = anc.iter().rev().skip(1).find_map(|a| d.node(*a).filter(|p| matches!(p.kind, NodeKind::Compound { .. })));
let inherit_appearance = |mut piece: Node| {
if let Some(parent) = compound_parent
&& piece.appearance.items.is_empty()
{
piece.appearance = parent.appearance.clone();
}
piece
};
if direct && let Some(pieces) = extract_direct_selection(n, &st.selection) {
for piece in pieces {
nodes.push(inherit_appearance(piece));
source_layers.push(layer_name.clone());
}
} else {
nodes.push(inherit_appearance(n.clone()));
source_layers.push(layer_name);
}
}
// Symbol instances are measured by their art.
let symbols = d.symbol_boxes();
+2 -2
View File
@@ -11,7 +11,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Pencil",
[],
None,
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks), fidelity?: pt (1.5), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: it is not, and the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end; with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it",
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks), fidelity?: pt (1.5), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end; with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it",
has_doc,
freehand
),
@@ -119,7 +119,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Join",
[],
None,
"{points: [[x,y]…], tolerance?: pt (12)} join the open-path endpoints scrubbed over → {id}",
"{points: [[x,y]…], tolerance?: pt (12)} join the open-path endpoints scrubbed over, or trim two crossing open paths whose overhanging ends are scrubbed and join them at the crossing → {id}",
has_doc,
join_scrub
),
+7 -1
View File
@@ -336,7 +336,13 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(st) = look.appearance.stroke_mut() {
pen.write(st);
}
insert_look(s, if brush { "Paintbrush" } else { "Pencil" }, path_kind(PathData::single(sp)), look, None, keep_selected)
let out = insert_look(s, if brush { "Paintbrush" } else { "Pencil" }, path_kind(PathData::single(sp)), look, None, keep_selected)?;
if !keep_selected {
// A new stroke with Keep selected off leaves nothing selected: Illustrator starts the stroke
// by dropping the earlier selection, it does not keep it (#5752).
s.select(|_, sel| sel.clear())?;
}
Ok(out)
}
// ---------- Blob Brush ----------
+114 -2
View File
@@ -1,4 +1,6 @@
use super::common::{dist_to_polyline, ids_json, path_mut, path_of, points_param, poly_bounds, target_paths};
use vectorcraft_pathops::addons::pathtools as pt;
use super::common::{dist_to_polyline, ids_json, path_mut, path_of, points_param, poly_bounds, subpath_len, target_paths};
use super::{
Anchor, BezPath, CubicBez, NodeId, ParamCurve, ParamCurveNearest, PathData, Point, Result, Session, SimplifyOptions, SubPath, Value, json,
number_or, po,
@@ -179,11 +181,121 @@ pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result<Value> {
// ---------- Join tool ----------
/// Most open subpaths the Join tool compares pairwise for crossings before it only joins ends.
const MAX_TRIM_SUBPATHS: usize = 64;
/// One end of an open subpath that runs on past where it crosses another: the part kept, which
/// ends at the crossing, and the part past it.
struct Overhang {
kept: SubPath,
cut: SubPath,
}
impl Overhang {
fn at(&self) -> Option<Point> {
self.kept.anchors.last().map(|a| a.p)
}
}
/// The overhangs of `sp` at its first and last crossing (`places`: subpath, segment, t, in order).
/// A crossing on an end anchor leaves no overhang there.
fn overhangs(sp: &SubPath, places: &[(usize, usize, f64)]) -> Vec<Overhang> {
let mut out = vec![];
for (place, at_start) in [(places.first(), true), (places.last(), false)] {
let Some(&(_, seg, t)) = place else { continue };
let (split, marks) = pt::insert_at(sp, &[(seg, t)]);
let Ok([first, second]) = <[SubPath; 2]>::try_from(split.cut_at(&marks)) else { continue };
let (mut kept, cut) = if at_start { (second, first) } else { (first, second) };
if at_start {
kept.reverse();
}
out.push(Overhang { kept, cut });
}
out
}
/// Does the scrub `pts` (`scrub` as a path) cross `cut` or pass within `tol` of it?
fn scrubbed(cut: &SubPath, pts: &[Point], scrub: &PathData, tol: f64) -> bool {
let pd = PathData::single(cut.clone());
pt::crossings(&[&pd, scrub], false).is_some_and(|c| c.first().is_some_and(|v| !v.is_empty()))
|| cut.anchors.iter().any(|a| dist_to_polyline(pts, a.p) <= tol)
|| pts.iter().any(|q| pd.nearest(*q).is_some_and(|n| n.4 <= tol))
}
/// Two crossing open subpaths, each `(path, subpath)`, trimmed and joined at the crossing.
struct TrimJoin {
a: (NodeId, usize),
b: (NodeId, usize),
joined: SubPath,
}
/// #5844: two open subpaths among `ids` that cross, where the scrub runs over the part of each
/// that overhangs the crossing, trimmed at the crossing and joined there with a corner. When
/// several pairs or ends qualify, the one trimming the least wins.
fn trim_join(d: &vectorcraft_doc::Document, ids: &[NodeId], pts: &[Point], tol: f64) -> Result<Option<TrimJoin>> {
let mut open = vec![];
for &id in ids {
let (pd, _) = path_of(d, id)?;
open.extend(pd.subpaths.into_iter().enumerate().filter(|(_, sp)| !sp.closed && sp.anchors.len() >= 2).map(|(si, sp)| (id, si, sp)));
}
if open.len() > MAX_TRIM_SUBPATHS {
return Ok(None);
}
let scrub = PathData::single(SubPath::polyline(pts, false));
let mut best: Option<(f64, TrimJoin)> = None;
for (i, (ida, sa, a)) in open.iter().enumerate() {
for (idb, sb, b) in open.iter().skip(i + 1) {
let (pa, pb) = (PathData::single(a.clone()), PathData::single(b.clone()));
let Some(places) = pt::crossings(&[&pa, &pb], false) else { continue };
let (Some(on_a), Some(on_b)) = (places.first(), places.get(1)) else { continue };
let (oa, ob) = (overhangs(a, on_a), overhangs(b, on_b));
for x in oa.iter().filter(|o| scrubbed(&o.cut, pts, &scrub, tol)) {
for y in ob.iter().filter(|o| scrubbed(&o.cut, pts, &scrub, tol)) {
let (Some(xa), Some(ya)) = (x.at(), y.at()) else { continue };
let trimmed = subpath_len(&x.cut) + subpath_len(&y.cut);
if xa.distance(ya) > 1e-2 || best.as_ref().is_some_and(|b| b.0 <= trimmed) {
continue;
}
// `x` ends at the crossing; `y`, reversed, starts there: one corner anchor.
let mut joined = x.kept.clone();
let mut rest = y.kept.clone();
rest.reverse();
let (Some(last), Some(first)) = (joined.anchors.last_mut(), rest.anchors.first()) else { continue };
*last =
Anchor { p: last.p, h_in: last.h_in, h_out: first.h_out + (last.p - first.p), kind: vectorcraft_geom::AnchorKind::Corner };
joined.anchors.extend(rest.anchors.into_iter().skip(1));
best = Some((trimmed, TrimJoin { a: (*ida, *sa), b: (*idb, *sb), joined }));
}
}
}
}
Ok(best.map(|(_, t)| t))
}
pub(super) fn join_scrub(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "path.joinScrub";
let pts = points_param(p, "points", C)?;
let tol = number_or(p, "tolerance", 12.0, C)?.max(0.0);
let st = s.doc()?;
let targets = target_paths(&st.doc, &st.selection, poly_bounds(&pts, tol));
// Paths that cross with their ends scrubbed are trimmed there and joined (#5844).
if let Some(TrimJoin { a: (ida, sa), b: (idb, sb), joined }) = trim_join(&st.doc, &targets, &pts, tol)? {
s.edit("Join", |d, sel| {
let missing = || crate::EngineError::Other("Join: a subpath went missing".into());
*path_mut(d, ida)?.subpaths.get_mut(sa).ok_or_else(missing)? = joined;
let pbm = path_mut(d, idb)?;
if sb >= pbm.subpaths.len() {
return Err(missing());
}
pbm.subpaths.remove(sb);
if ida != idb && pbm.is_empty() {
d.remove(idb)?;
}
sel.set([ida]);
Ok(())
})?;
return Ok(json!({ "id": ida.0 }));
}
// Open endpoints near the scrub, ordered along it: (order, id, subpath, at_start).
let poly = {
let mut bp = BezPath::new();
@@ -202,7 +314,7 @@ pub(super) fn join_scrub(s: &mut Session, p: &Value) -> Result<Value> {
};
let (first_pt, last_pt) = (pts.first().copied(), pts.last().copied());
let mut ends: Vec<(f64, NodeId, usize, bool, Point)> = vec![];
for id in target_paths(&st.doc, &st.selection, poly_bounds(&pts, tol)) {
for id in targets {
let (pd, _) = path_of(&st.doc, id)?;
for (si, sp) in pd.subpaths.iter().enumerate() {
if sp.closed || sp.anchors.len() < 2 {
+156 -27
View File
@@ -4,7 +4,7 @@ use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, RulerMode, Unit};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, RulerMode, Unit};
use vectorcraft_geom::{Affine, Point, Vec2};
use super::clipboard::SwatchChoices;
@@ -626,7 +626,7 @@ pub(crate) fn selected_roots(s: &Session) -> Result<Vec<NodeId>> {
/// rest still go to the compound path, which holds the paint.
pub(crate) fn selected_roots_to_transform(s: &Session) -> Result<Vec<NodeId>> {
let st = s.doc()?;
Ok(roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |_| true))
Ok(roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |_, _| true))
}
/// [`selected_roots`] for the selected objects inside the isolated object `root`
@@ -637,18 +637,18 @@ pub(crate) fn selected_roots_to_transform(s: &Session) -> Result<Vec<NodeId>> {
pub(crate) fn selected_roots_inside(s: &Session, root: NodeId, members: bool) -> Result<Vec<NodeId>> {
let st = s.doc()?;
let ids = st.selection.in_paint_order(&st.doc).into_iter().filter(|id| super::inside_isolation(&st.doc, root, *id)).collect();
Ok(roots_within(&st.doc, ids, |compound| members || compound == root))
Ok(roots_within(&st.doc, ids, |compound, _| members || compound == root))
}
/// The top-level objects among `ids` (in paint order): compound-path members stand for their
/// compound, and ids whose ancestor is also listed, and layers, are dropped.
pub(crate) fn roots_of(doc: &Document, ids: Vec<NodeId>) -> Vec<NodeId> {
roots_within(doc, ids, |_| false)
roots_within(doc, ids, |_, _| false)
}
/// [`roots_of`]; a compound path's member listed stays itself when `members` holds for the
/// compound's id.
fn roots_within(doc: &Document, ids: Vec<NodeId>, members: impl Fn(NodeId) -> bool) -> Vec<NodeId> {
/// [`roots_of`]; a compound path's member listed stays itself when `keep_member` holds for the
/// compound's id or the member's id.
fn roots_within(doc: &Document, ids: Vec<NodeId>, keep_member: impl Fn(NodeId, NodeId) -> bool) -> Vec<NodeId> {
// Every id's place in the tree, found in one walk (a lookup per id is a walk per id).
let paths = doc.index_paths(ids.iter().copied());
// A compound-path member acts as its compound (compounds are one object).
@@ -658,7 +658,7 @@ fn roots_within(doc: &Document, ids: Vec<NodeId>, members: impl Fn(NodeId) -> bo
let path = paths.get(&id);
let parent = path.and_then(|p| p.split_last()).map(|(_, up)| up).filter(|up| !up.is_empty());
match parent.and_then(|up| doc.node_at(up).map(|n| (up, n))) {
Some((up, n)) if matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. }) && !members(n.id) => (n.id, Some(up.to_vec())),
Some((up, n)) if matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. }) && !keep_member(n.id, id) => (n.id, Some(up.to_vec())),
_ => (id, path.cloned()),
}
})
@@ -689,11 +689,24 @@ fn without_inner(doc: &Document, placed: Vec<(NodeId, Option<Vec<usize>>)>) -> i
})
}
/// The direct-selection flag and resolved root nodes for Copy and Cut operations.
fn copy_cut_targets(s: &Session) -> Result<(bool, Vec<NodeId>)> {
let st = s.doc()?;
let in_drawing_tool = matches!(s.tool_id(), "pen" | "curvature");
let direct = !in_drawing_tool && (!st.selection.anchors.is_empty() || !st.selection.segments.is_empty());
let in_isolated_compound = st.isolation.is_some_and(|iso| st.doc.node(iso).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })));
let roots = roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |_compound, member| {
in_isolated_compound || (direct && (st.selection.partial(member).is_some() || st.selection.segments.contains_key(&member)))
});
Ok((direct, roots))
}
fn copy(s: &mut Session, _: &Value) -> Result<Value> {
// The Artboard tool copies its artboard (and the art on it).
if s.tool_id() == "artboard" {
return super::panelcmds::artboard_copy(s, &json!({}), false);
}
let (direct, targets) = copy_cut_targets(s)?;
let st = s.doc()?;
// Selected ruler guides come along (#3226), as canvas guides: their layer and artboard stay
// behind.
@@ -704,9 +717,13 @@ fn copy(s: &mut Session, _: &Value) -> Result<Value> {
.filter_map(|i| st.doc.guides.get(*i))
.map(|g| vectorcraft_doc::Guide { layer: None, artboard: None, ..g.clone() })
.collect();
let roots = if st.selection.is_empty() && !guides.is_empty() { vec![] } else { selected_roots(s)? };
let st = s.doc()?;
let mut clip = Clipboard::copy(st, &roots);
let roots = if st.selection.is_empty() && !guides.is_empty() { vec![] } else { targets };
let mut clip = Clipboard::copy(st, &roots, direct);
// Direct-selected anchors or segments that make no segment: nothing to copy, so the
// clipboard keeps what it held.
if direct && clip.nodes.is_empty() {
return Ok(json!({ "copied": 0 }));
}
// Guides alone: the artboard the first one belongs to, or crosses, is where in-place pastes
// measure from, as the objects' artboard is.
if clip.nodes.is_empty()
@@ -729,23 +746,80 @@ fn cut(s: &mut Session, p: &Value) -> Result<Value> {
if s.tool_id() == "artboard" {
return super::panelcmds::artboard_copy(s, &json!({}), true);
}
// Copy promotes a compound member to its compound. Cut must remove the same objects it
// copied, while Clear on its own deletes exactly the selected members.
// Ruler guides selected on their own: Copy takes them, Clear removes them.
if s.doc()?.selection.is_empty() {
copy(s, p)?;
return clear(s, &json!({}));
}
let ids = selected_roots(s)?;
copy(s, p)?;
// Copy promotes a compound member to its compound. Cut must remove the same objects it
// copied, while Clear on its own deletes exactly the selected members.
let (direct, roots) = copy_cut_targets(s)?;
let res = copy(s, p)?;
if res.get("copied").and_then(Value::as_u64) == Some(0) {
return Ok(res);
}
// The selected ruler guides it copied go with the objects, in the same undo step (#3226).
if s.doc()?.selection.anchors.is_empty() { clear(s, &json!({ "ids": ids, "guides": true })) } else { clear(s, &json!({ "guides": true })) }
if !direct { clear(s, &json!({ "ids": roots, "guides": true })) } else { cut_direct_selection(s, &roots) }
}
fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
let st = s.doc()?;
let sel = st.selection.clone();
s.edit("Cut", |d, selection| {
// The selected ruler guides were copied too (#3226): they go in the same undo step.
let gone = selection.guides.clone();
d.retain_guides(selection, |i, _| !gone.contains(&i));
let mut survivors = vec![];
for id in roots {
let Some(node) = d.node(*id) else { continue };
let has_direct = sel.anchors.contains_key(id) || sel.segments.contains_key(id);
if !has_direct {
d.remove(*id)?;
continue;
}
let Some(path) = node.path_data() else {
d.remove(*id)?;
continue;
};
let seg_refs = sel.segments.get(id);
let anchor_refs = sel.anchors.get(id);
let mut subpaths = Vec::new();
for (si, sp) in path.subpaths.iter().enumerate() {
let cuts = super::clipboard::subpath_selected_segments(sp, si, seg_refs, anchor_refs);
if cuts.is_empty() {
subpaths.push(sp.clone());
} else {
subpaths.extend(super::path::without_segments(sp.clone(), &cuts));
}
}
subpaths.retain(|sp| sp.anchors.len() >= 2);
if subpaths.is_empty() {
let parent = d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })));
d.remove(*id)?;
if let Some(p) = parent
&& d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty()))
{
d.remove(p)?;
}
} else {
let path_node = super::path::path_mut(d, *id)?;
path_node.subpaths = subpaths;
survivors.push(*id);
}
}
selection.set(survivors);
selection.anchors.clear();
selection.segments.clear();
Ok(())
})?;
ok()
}
fn clear(s: &mut Session, p: &Value) -> Result<Value> {
let explicit = if p.get("ids").is_some() { Some(checked_ids_param(s, p, "ids", "edit.clear")?) } else { None };
// Direct-selected anchors or segments: remove those, and any objects selected whole with them.
if explicit.is_none() && !s.doc()?.selection.anchors.is_empty() {
if explicit.is_none() && (!s.doc()?.selection.anchors.is_empty() || !s.doc()?.selection.segments.is_empty()) {
return super::path::delete_anchors(s, p);
}
// Selected ruler guides (selected on their own).
@@ -756,6 +830,7 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
// Guides selected with the art go with it (not when ids are given, unless `guides` says so:
// Cut, which names the objects it copied).
let with_guides = explicit.is_none() || bool_or(p, "guides", false);
let is_explicit = explicit.is_some();
let targets = explicit.unwrap_or_else(|| st.selection.in_paint_order(&st.doc));
// Keep the selected ids themselves, without promoting compound members. Delete a selected
// ancestor just once; its selected descendants leave with it. Layers themselves are kept.
@@ -769,12 +844,26 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
return ok();
}
s.edit("Clear", |d, sel| {
let parents: Vec<_> =
ids.iter().filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })))).collect();
d.remove_many(&ids)?;
for p in parents {
if d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())) {
d.remove(p)?;
}
}
if with_guides {
let gone = sel.guides.clone();
d.retain_guides(sel, |i, _| !gone.contains(&i));
}
sel.clear();
if is_explicit {
for id in &ids {
sel.remove(*id);
}
sel.prune(d);
} else {
sel.clear();
}
Ok(())
})?;
ok()
@@ -803,7 +892,7 @@ fn drop_selection(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(id) = ids.iter().find(|id| !paths.contains_key(id)) {
return Err(EngineError::NoNode(*id));
}
let clip = Clipboard::copy(source, &roots_of(&source.doc, ids));
let clip = Clipboard::copy(source, &roots_of(&source.doc, ids), false);
let bounds = clip.bounds().ok_or_else(|| bad(CMD, "the art has no bounds"))?;
let center = bounds.center() + Vec2::new(at[0] - grab[0], at[1] - grab[1]);
if !center.x.is_finite() || !center.y.is_finite() {
@@ -874,7 +963,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
let off = s.prefs.paste_offset;
let st = s.doc()?;
let same_doc = clip.source_doc == Some(st.uid);
let parent = st.target_parent()?;
let parent = st.target_parent_for_path()?;
// Copied artboards come back with their art: together right of the last artboard, as they lay,
// or where they were (Paste in Place, in Front, in Back). Paste on All Artboards pastes only the
// art.
@@ -907,8 +996,10 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
let anchor = if front || back {
let order = st.selection.in_paint_order(&st.doc);
let a = if front { order.last() } else { order.first() };
let paths_only = clip.nodes.iter().all(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Path { .. }));
a.map(|id| paste_anchor(&st.doc, *id, paths_only)).and_then(|id| st.doc.position(id))
let isolated_compound = st.isolation.is_some_and(|iso| st.doc.node(iso).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })));
let can_enter_compound = clip.nodes.iter().all(|n| matches!(n.kind, NodeKind::Path { .. }))
|| (isolated_compound && clip.nodes.iter().all(|n| matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })));
a.map(|id| paste_anchor(&st.doc, *id, can_enter_compound)).and_then(|id| st.doc.position(id))
} else {
None
};
@@ -975,7 +1066,45 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
}
};
*placed.entry(par).or_default() += 1;
new_ids.push(d.insert(par, idx, c)?);
let compound_par = par.filter(|p| d.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })));
if let Some(par_id) = compound_par {
match c.kind {
NodeKind::Compound { children, .. } => {
let count = children.len();
for (offset, child) in children.into_iter().enumerate() {
let mut child_node = Arc::unwrap_or_clone(child);
let child_id = d.alloc_id();
child_node.id = child_id;
child_node.appearance = Default::default();
if let NodeKind::Path { live, .. } = &mut child_node.kind {
*live = None;
}
let insert_idx = if idx == usize::MAX { usize::MAX } else { idx.saturating_add(offset) };
new_ids.push(d.insert(par, insert_idx, child_node)?);
}
if count > 1 {
*placed.entry(par).or_default() += count - 1;
}
}
NodeKind::Path { .. } => {
c.appearance = Default::default();
if let NodeKind::Path { live, .. } = &mut c.kind {
*live = None;
}
new_ids.push(d.insert(par, idx, c)?);
}
_ => {
let outer_par = d.parent_of(par_id);
let beside_idx = d.position(par_id).map(|(_, i, _)| i + 1).unwrap_or(usize::MAX);
let offset = *placed.entry(outer_par).or_default();
*placed.entry(outer_par).or_default() += 1;
let insert_idx = if beside_idx == usize::MAX { usize::MAX } else { beside_idx.saturating_add(offset) };
new_ids.push(d.insert(outer_par, insert_idx, c)?);
}
}
} else {
new_ids.push(d.insert(par, idx, c)?);
}
}
}
sel.set(new_ids.iter().copied());
@@ -1016,11 +1145,11 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
}))
}
/// What pasted art goes beside: `id`, or the compound path holding it when the art isn't only
/// paths (a compound path holds paths only).
fn paste_anchor(doc: &Document, id: NodeId, paths_only: bool) -> NodeId {
/// What pasted art goes beside: `id`, or the compound path holding it when the art cannot enter
/// the compound path (a compound path holds paths only; compound paths unpack into isolated compounds).
fn paste_anchor(doc: &Document, id: NodeId, can_enter_compound: bool) -> NodeId {
match doc.parent_of(id) {
Some(p) if !paths_only && doc.node(p).is_some_and(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. })) => p,
Some(p) if !can_enter_compound && doc.node(p).is_some_and(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. })) => p,
_ => id,
}
}
+2 -2
View File
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export Document",
[],
None,
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in their layers), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: 72 (raster formats: pixels per inch, stored in the file; wins over scale), scale?: 1 (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. Never changes the document's path",
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in their layers), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. Never changes the document's path",
has_doc,
export::export
),
@@ -45,7 +45,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export Selection…",
["File"],
None,
"{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|vectorcraft|template (default: from the extension, else png), scale?: 1, …the format's options} the selected objects cropped to their bounds (template layers left out) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export",
"{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects cropped to their bounds (template layers left out) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export",
has_selection,
export::export_selection
),
+5 -4
View File
@@ -202,13 +202,14 @@ impl RasterOptions {
}
}
/// The render and encoder settings: `ppi`, else 72 × `scale`, within 0.01–64 pixels per point;
/// The render and encoder settings: `ppi`, else 72 × `scale`, else the document's resolution,
/// within 0.01–64 pixels per point;
/// `background`, else `page` (the document's background).
fn settings(&self, page: Option<[u8; 3]>) -> Result<RasterExportOptions> {
fn settings(&self, page: Option<[u8; 3]>, document_ppi: f64) -> Result<RasterExportOptions> {
if let Some(ppi) = self.ppi.filter(|p| !(p.is_finite() && *p > 0.0)) {
return Err(bad(C, format!("ppi must be a positive number, not {ppi}")));
}
let ppi = self.ppi.unwrap_or(72.0 * self.scale.unwrap_or(1.0));
let ppi = self.ppi.unwrap_or_else(|| self.scale.map_or(document_ppi, |scale| 72.0 * scale));
let color_model = parse(self.color_model.as_deref(), jpeg::ColorModel::from_id, "colorModel", "rgb, cmyk or gray")?;
let embed_icc = self.embed_icc.unwrap_or(true);
Ok(RasterExportOptions {
@@ -544,7 +545,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
// New Document → Background Contents: White makes the export opaque, unless `background`
// says otherwise (JPEG has no alpha: white either way).
let page = (doc.setup.background == vectorcraft_doc::Background::White).then_some([255; 3]);
let mut settings = o.settings(page)?;
let mut settings = o.settings(page, doc.raster_ppi())?;
let size = o.pixel_size()?;
let format = match f.id {
"png" => RasterFormat::Png,
+8 -3
View File
@@ -76,7 +76,12 @@ pub(super) const RANGE: FormatOption = FormatOption {
description: "1-based artboards such as \"1-3, 5\", or \"all\" (wins over artboards and artboard)",
};
const SCALE: FormatOption = FormatOption { name: "scale", ty: "number", default: "1", description: "pixels per point (0.01–64)" };
const SCALE: FormatOption = FormatOption {
name: "scale",
ty: "number",
default: "null",
description: "pixels per point (0.01–64); without ppi or scale, uses the document's raster effects resolution",
};
const WIDTH: FormatOption = FormatOption {
name: "width",
@@ -112,8 +117,8 @@ const RECT: FormatOption = FormatOption {
const PPI: FormatOption = FormatOption {
name: "ppi",
ty: "number",
default: "72",
description: "resolution in pixels per inch (72 = one pixel per point; 150, 300…), stored in the file except in GIF, WebP and Targa; wins over scale",
default: "null",
description: "resolution in pixels per inch (72 = one pixel per point; 150, 300…), stored in the file except in GIF, WebP and Targa; wins over scale; without either, uses the document's raster effects resolution",
};
const BACKGROUND: FormatOption = FormatOption {
+1 -1
View File
@@ -109,7 +109,7 @@ pub const AI_OPTIONS: &[FormatOption] = &[
name: "editingData",
ty: "boolean",
default: "true",
description: "also carry an editing copy of the artwork in the form other apps that open .ai files read: layers and sublayers, groups, compound paths, paths, fills and strokes, colors, swatches, artboards, the transparency of objects and layers, objects' opacity masks, and clipping groups and layers clipped by a path, with type, gradients, patterns, images, symbols, other clipping objects and live objects as plain filled and stroked paths (written only with every artboard, as Preserve Editing is)",
description: "also carry an editing copy of the artwork in the form other apps that open .ai files read: layers and sublayers, groups, compound paths, paths, fills and strokes, colors, linear and radial gradients, patterns on a grid of tiles, swatches, artboards, the transparency of objects and layers, objects' opacity masks, clipping groups and layers clipped by a path, embedded images with their pixels, and linked images as placed files with a preview, with type, other patterns, symbols, other clipping objects and live objects as plain filled and stroked paths, freeform gradients, gradients along or across a stroke and gradients of more than 256 stops as their average color, gradients that dither or mix perceptually as classic ones, and gradient stops linked to global process colors as their colors (written only with every artboard, as Preserve Editing is)",
},
FormatOption {
name: "aiVersion",
+1 -1
View File
@@ -459,7 +459,7 @@ fn formats_query_lists_readers_writers_and_options() {
);
assert!(ids("readable").contains(&"tiff".to_string()) && ids("readable").contains(&"ait".to_string()));
let png = r["formats"].as_array().unwrap().iter().find(|f| f["id"] == "png").unwrap();
assert_eq!(png["options"]["scale"]["default"], 1);
assert_eq!(png["options"]["scale"]["default"], Value::Null);
assert_eq!(r["openExtensions"].as_array().unwrap().len(), OPEN_EXTS.len());
}
@@ -124,6 +124,30 @@ fn an_ai_file_opens_with_its_artboard_options_raster_settings_and_author() {
assert_eq!(d.metadata.author, "Ann Lee");
}
#[test]
fn an_ai_file_opens_with_its_active_artboard() {
let board = |x: i32, name: &str| {
format!(
"%_/Dictionary :\n%_{x} 100 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_{} 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_({name}) /UnicodeString (Name) ,\n%_; ,\n",
x + 200
)
};
let document = format!(
"%_/Document :\n%_/Dictionary :\n%_/Array :\n{}{}%_; (ArtboardArray) ,\n%_1 /Int (CropAreaActive) ,\n%_; /NotRecorded ,\n%_;\n",
board(0, "One"),
board(300, "Two")
);
let data = ai::sample_data();
let at = data.windows(15).position(|w| w == b"%AI5_BeginLayer").unwrap();
let data = [&data[..at], document.as_bytes(), &data[at..]].concat();
let mut s = Session::new();
let r = open(&mut s, "art.ai", &ai::ai(&compressed(&data), PLACEHOLDER), json!({})).unwrap();
let d = &s.doc().unwrap().doc;
let names: Vec<&str> = d.artboards.iter().map(|a| a.name.as_str()).collect();
assert_eq!(names, ["One", "Two"], "{r}");
assert_eq!(d.opened_artboard, Some(d.artboards[1].id), "{r}");
}
#[test]
fn an_ai_unread_group_keeps_its_layers_and_live_neighbor() {
let live = format!("0 0 1 0 k\n{}f", ai::rect(10.0, 10.0, 14.0, 14.0));
@@ -287,6 +311,38 @@ fn a_swatch_library_in_a_ai_file_without_layers_loads_its_palette() {
assert!(matches!(sky, Some(vectorcraft_color::Paint::Gradient(_))), "{sky:?}");
}
/// Other Library… on a `.ai` graphic style library (art styles, their list and no layers) gives the
/// library the styles of its list, in the list's order, not the default styles; the file opens with
/// them too.
#[test]
fn a_graphic_style_library_in_a_ai_file_without_layers_loads_its_styles() {
let style = |name: &str, xa: &str| {
format!(
"/KnownStyle :\n({name}) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\
/BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n{xa}0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n;\n"
)
};
let styles = format!(
"%AI9_BeginArtStyles\n{}{}{}%AI9_EndArtStyles\n%AI9_BeginArtStyleList\n(Red)\n(Green)\n(Blue)\n%AI9_EndArtStyleList\n",
style("Blue", "0 0 0 0 0 0 1 Xa\n"),
style("Green", "0 0 0 0 0 1 0 Xa\n"),
style("Red", "0 0 0 0 1 0 0 Xa\n")
);
let data = ai::editing_data(200.0, 100.0, &styles);
let file = ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f");
let mut s = Session::new();
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&file), "name": "fills.ai"});
let r = s.execute("graphicStyle.loadLibrary", &p).unwrap();
assert_eq!((&r["name"], &r["count"]), (&json!("fills"), &json!(3)), "{r}");
let lib = s.execute("graphicStyle.library", &json!({"library": r["library"]})).unwrap();
let names: Vec<&str> = lib["styles"].as_array().unwrap().iter().map(|g| g["name"].as_str().unwrap()).collect();
assert_eq!(names, ["Red", "Green", "Blue"], "{lib}");
let r = open(&mut s, "fills.ai", &file, json!({})).unwrap();
let doc = &s.doc().unwrap().doc;
let styles: Vec<(&str, u32)> = doc.graphic_styles.iter().map(|g| (g.name.as_str(), g.id)).collect();
assert_eq!(styles, [("Red", 1), ("Green", 2), ("Blue", 3)], "{r}");
}
/// A 1-bit RGB image opens from the editing data in the colors its PDF part shows.
#[test]
fn a_one_bit_rgb_image_opens_from_the_editing_data_in_its_colors() {
@@ -1023,6 +1079,46 @@ fn an_empty_page_with_type_as_outlines_outlines_the_editing_datas_type() {
assert_eq!(names(&s.doc().unwrap().doc.layers), ["Art"], "the editing data's layers");
}
/// A story of a `.ai` file's text document with no character or paragraph runs is set in
/// `[Normal Character Style]` and `[Normal Paragraph Style]`; the base attributes give only what
/// those styles leave out.
#[test]
fn an_ai_story_without_runs_takes_the_normal_styles() {
let story = "<< /0 << /0 (Hi\r) >> \
/1 << /0 [ << /0 0 >> ] /2 [ << /99 /PC /6 [ << /99 /F /0 << /0 [ 8191.5 8191.5 ] >> /6 [ << /99 /R /6 [ << /99 /R /6 [ << /99 /L /6 [ \
<< /99 /S /0 << /0 [ 0.0 0.0 ] >> /15 << /0 3 >> >> ] >> ] >> ] >> ] >> ] >> ] >> >>";
let char_sheets = "/5 << /0 [ << /0 << /0 ([Normal Character Style]) /6 << /0 0 /1 9.0 \
/53 << /99 /SimplePaint /0 << /0 1 /1 [ 1.0 0.0 0.0 1.0 ] >> >> >> >> >> ] >>";
let para_sheets = "/6 << /0 [ << /0 << /0 ([Normal Paragraph Style]) /5 << /1 6.0 /9 false >> >> >> ] >>";
let document = format!(
"/0 << /1 << /0 [ << /0 << /0 << /0 (Helvetica) >> >> >> ] >> {char_sheets} {para_sheets} \
/8 << /0 [ << /0 << /0 [ 0 0 ] /2 << /2 [ 1 0 0 1 0 0 ] >> >> >> ] >> >>\n\
/1 << /1 [ {story} ] /2 << /1 12.0 /53 << /99 /SimplePaint /0 << /0 0 /1 [ 1.0 1.0 ] >> >> >> /3 << /1 2.0 /9 true >> >>\n"
);
let lines: Vec<String> = ascii85(document.as_bytes()).as_bytes().chunks(60).map(|c| format!("%{}", String::from_utf8_lossy(c))).collect();
let text = "/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n2 /TextAntialiasing ,\n;\n";
let data = format!(
"%!PS-Adobe-3.0 \n%%BoundingBox: 0 0 100 100\n%%HiResBoundingBox: 0 0 100 100\n%AI3_Cropmarks: 0 0 100 100\n%AI3_TemplateBox: 50 50 50 50\n\
%AI5_NumLayers: 1\n{}%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n{}\n%AI11_EndTextDocument\n%%Trailer\n",
ai::layer("Art", text),
lines.join("\n")
);
let mut s = Session::new();
let r = open(&mut s, "plain.ai", &ai::ai(&compressed(data.as_bytes()), ""), json!({})).unwrap();
let mut texts = vec![];
s.doc().unwrap().doc.walk(|c| {
if let NodeKind::Text(t) = &c.kind {
texts.push((**t).clone());
}
});
let [t] = texts.as_slice() else { panic!("one text object: {r}") };
assert_eq!(t.plain_text(), "Hi");
let style = &t.runs[0].style;
assert_eq!(style.size, 9.0, "{r}");
assert_eq!(style.fill, vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0)));
assert_eq!((t.para.first_line_indent, t.para.hyphenate), (6.0, false));
}
/// Type asked for as outlines in a `.ai` saved without PDF compatibility (its page only a
/// placeholder): the editing data's type, outlined, as for an empty page.
#[test]
@@ -652,3 +652,265 @@ fn transparency_clipping_and_opacity_masks_come_back_from_the_editing_copy() {
let kinds = see_through_outline(&legacy.doc);
assert!(kinds.iter().any(|l| l.contains(" compound ")) && kinds.iter().any(|l| l.contains("group clip=true")), "{kinds:#?}");
}
/// The paths and compound paths of `doc`'s art and of its patterns' tiles with their geometric
/// bounds (rounded) and fills and strokes, one line each, then its gradient and pattern swatches: a
/// gradient by its kind, its swatch link (`-` when it names no gradient swatch of `doc`), its stops
/// (place, color, opacity, midpoint, swatch link and tint) and the gradient's place at the corners and
/// center of the paint's bounds (rounded to hundredths); a pattern by its name and placement.
fn paint_outline(doc: &vectorcraft_doc::Document) -> Vec<String> {
use std::sync::Arc;
use vectorcraft_color::Paint;
use vectorcraft_doc::{AppearanceItem, Node, NodeKind};
let link = |name: &Option<String>| match name.as_deref().and_then(|n| doc.swatch(n)) {
Some(sw) if matches!(sw.paint, Paint::Gradient(_)) => sw.name.clone(),
_ => "-".into(),
};
let drawn = |p: &Paint, b: vectorcraft_geom::Rect| match p {
Paint::Gradient(g) => {
let geom = g.resolve(b);
let at: Vec<f64> = [(b.x0, b.y0), (b.x1, b.y0), (b.x0, b.y1), (b.x1, b.y1), (b.center().x, b.center().y)]
.map(|(x, y)| (geom.param_at(g.gradient.kind, (x, y).into()) * 100.0).round() / 100.0)
.to_vec();
let stops: Vec<String> = g
.gradient
.stops
.iter()
.map(|s| {
let rgb = s.color.to_rgb().map(|v| (v * 100.0).round());
format!("{:.3} {rgb:?} {:.2} mid {:.2} {:?} {:.2}", s.offset, s.opacity, s.midpoint, s.swatch, s.tint)
})
.collect();
format!("{:?} link {} {stops:?} {at:?}", g.gradient.kind, link(&g.swatch))
}
Paint::Pattern { pattern, xf } => format!("pattern {pattern} {:?}", xf.as_coeffs().map(|v| (v * 1000.0).round() / 1000.0)),
Paint::Solid { color, .. } => format!("{:?}", color.to_rgb().map(|v| (v * 100.0).round())),
Paint::None => "none".into(),
};
// A compound path's paint is its own: its members' paint isn't drawn (Release gives them the
// compound path's), so a compound path's line lists only its members' bounds.
fn walk(nodes: &[Arc<Node>], f: &mut dyn FnMut(&Node)) {
for n in nodes {
f(n);
if !matches!(n.kind, NodeKind::Compound { .. }) {
walk(n.children().map(Vec::as_slice).unwrap_or_default(), f);
}
}
}
let bounds = |n: &Node| n.geometric_bounds().map(|b| [b.x0, b.y0, b.x1, b.y1].map(|v| v.round() as i64));
let lines = |nodes: &[Arc<Node>]| {
let mut lines = vec![];
walk(nodes, &mut |n| {
if !matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) {
return;
}
let Some(b) = n.geometric_bounds() else { return };
let kind = match n.children() {
Some(members) => format!("compound of {:?}", members.iter().map(|m| bounds(m)).collect::<Vec<_>>()),
None => "path".into(),
};
let mut line = format!("{kind} {:?}", [b.x0, b.y0, b.x1, b.y1].map(|v| v.round() as i64));
for it in n.appearance.items.iter().filter(|i| !i.paint().is_none()) {
line += &match it {
AppearanceItem::Fill(f) => format!(" fill {}", drawn(&f.paint, b)),
AppearanceItem::Stroke(st) => format!(" stroke {} {}", st.width, drawn(&st.paint, st.paint_bounds(b))),
};
}
lines.push(line);
});
lines
};
let mut out = lines(&doc.layers);
for p in doc.patterns.iter() {
out.push(format!("pattern {} tile {:?}", p.name, [p.tile.x0, p.tile.y0, p.tile.x1, p.tile.y1]));
out.extend(lines(&p.art));
}
for sw in doc.swatches_iter() {
match &sw.paint {
// A gradient swatch reads back linked to itself.
Paint::Gradient(g) => {
let own = Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(g.gradient.clone())));
out.push(format!("swatch {} {}", sw.name, drawn(&own, vectorcraft_geom::Rect::ZERO)));
}
Paint::Pattern { pattern, .. } => out.push(format!("swatch {} pattern {pattern}", sw.name)),
_ => {}
}
}
out
}
/// The images of `doc`'s art, one line each: its pixel size, where its corners land (rounded to
/// hundredths), its link's path and relative path, and its pixels (RGBA).
fn image_outline(doc: &vectorcraft_doc::Document) -> Vec<String> {
use vectorcraft_doc::NodeKind;
let mut out = vec![];
doc.walk(|n| {
if let NodeKind::Image(im) = &n.kind {
let r = vectorcraft_geom::Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height));
let corners = [(r.x0, r.y0), (r.x1, r.y0), (r.x0, r.y1)].map(|(x, y)| {
let p = im.xf * vectorcraft_geom::Point::new(x, y);
((p.x * 100.0).round() / 100.0, (p.y * 100.0).round() / 100.0)
});
let link = im.link.as_ref().map(|l| (l.path.clone(), l.relative.clone()));
let pixels = doc.image_blob(im).and_then(|b| image::load_from_memory(&b.bytes).ok()).map(|i| i.to_rgba8().into_raw());
out.push(format!("{}x{} {corners:?} {link:?} {pixels:?}", im.width, im.height));
}
});
out
}
/// An embedded image (RGBA, part of it see-through, turned) and a linked one come back from the
/// editing copy for other apps alone, pixel for pixel, with every save option that writes the copy;
/// the linked image keeps its path and its path relative to the document's folder.
#[test]
fn images_come_back_from_the_editing_copy() {
let dir = tmp("ai-images");
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(format!("{dir}/art")).unwrap();
let png = |w: u32, h: u32, f: &dyn Fn(u32, u32) -> [u8; 4]| {
let mut out = vec![];
image::RgbaImage::from_fn(w, h, |x, y| image::Rgba(f(x, y))).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
out
};
let linked = format!("{dir}/art/linked.png");
std::fs::write(&linked, png(5, 4, &|x, y| [(x * 50) as u8, (y * 60) as u8, 90, 255])).unwrap();
let mut s = Session::new();
s.execute("file.new", &json!({"width": 300, "height": 200})).unwrap();
let data = vectorcraft_format::base64_encode(&png(6, 3, &|x, y| [200, (x * 40) as u8, (y * 80) as u8, if x < 2 { 100 } else { 255 }]));
s.execute("file.place", &json!({"name": "embedded.png", "dataBase64": data})).unwrap();
// The placed image is selected.
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
s.execute("file.place", &json!({"path": linked, "link": true})).unwrap();
let path = format!("{dir}/images.ai");
s.execute("document.save", &json!({"path": path})).unwrap();
let before = image_outline(&s.doc().unwrap().doc);
assert_eq!(before.len(), 2, "{before:#?}");
assert!(before[1].contains("art/linked.png"), "{before:#?}");
for opts in [
json!({"format": "ai"}),
json!({"format": "ai", "compress": false}),
json!({"format": "ai", "embedProfiles": false}),
json!({"format": "ai", "includeLinked": true}),
json!({"format": "ai", "range": "all"}),
json!({"format": "ai", "pdfCompatible": false}),
] {
let r = s.execute("document.export", &opts).unwrap();
assert!(!r["warnings"].to_string().contains("image"), "{r}");
let copy = load::load_with(&path, &b64(&r), &LoadOptions { native: false, ..Default::default() }).unwrap();
assert!(copy.editing_data && !copy.restored, "{opts} {:?}", copy.warnings);
assert!(!copy.warnings.iter().any(|w| w.contains("editing data")), "{opts} {:?}", copy.warnings);
assert_eq!(image_outline(&copy.doc), before, "{opts}");
}
}
/// A document of two artboards (the art on the first): a rectangle filled with a linear gradient of
/// three stops placed across part of it, an ellipse filled with an elliptical radial gradient whose
/// focal point is off its center, a rectangle stroked with a gradient, rectangles filled and
/// stroked with the pattern `Dots`, one of them turned, an even-odd compound path filled with a
/// gradient of a gray, a CMYK color and the spot color `Ink` at 70%, and the gradient swatch `Dawn`.
fn gradient_session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 300, "height": 200, "artboards": 2})).unwrap();
let id = |v: serde_json::Value| v["id"].as_u64().unwrap();
let rect = |s: &mut Session, x: f64, y: f64, w: f64, h: f64| {
id(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap())
};
let three = json!({"kind": "linear", "stops": [
{"offset": 0, "color": "#ff0000", "midpoint": 0.3},
{"offset": 0.4, "color": "#00ff00", "opacity": 0.5},
{"offset": 1, "color": "#0000ff"}
], "start": [20, 40], "end": [60, 17]});
let a = rect(&mut s, 10.0, 10.0, 80.0, 40.0);
s.execute("paint.setFill", &json!({"ids": [a], "gradient": three})).unwrap();
let e = id(s.execute("shape.ellipse", &json!({"x": 100, "y": 10, "width": 80, "height": 40})).unwrap());
let glow = json!({"kind": "radial", "stops": [{"offset": 0, "color": "#ffffff"}, {"offset": 1, "color": "#1a33cc"}],
"start": [140, 30], "end": [180, 30], "aspect": 50, "focal": [150, 25]});
s.execute("paint.setFill", &json!({"ids": [e], "gradient": glow})).unwrap();
let c = rect(&mut s, 190.0, 10.0, 90.0, 40.0);
let two = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#ffff00"}, {"offset": 1, "color": "#000000"}]});
s.execute("paint.setStroke", &json!({"ids": [c], "gradient": two, "width": 6})).unwrap();
let tile = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
s.execute("paint.setFill", &json!({"ids": [tile], "color": "#ff0000"})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [tile], "none": true})).unwrap();
s.execute("object.pattern.make", &json!({"ids": [tile], "name": "Dots", "edit": false})).unwrap();
let p = rect(&mut s, 10.0, 70.0, 80.0, 40.0);
s.execute("paint.setFill", &json!({"ids": [p], "swatch": "Dots"})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [p], "swatch": "Dots", "width": 4})).unwrap();
let turned = rect(&mut s, 100.0, 70.0, 80.0, 40.0);
s.execute("paint.setFill", &json!({"ids": [turned], "swatch": "Dots"})).unwrap();
// Turned 30° and scaled to half about (140, 90).
let (c, k) = (30f64.to_radians().cos() * 0.5, 30f64.to_radians().sin() * 0.5);
let m = [c, k, -k, c, 140.0 - 140.0 * c + 90.0 * k, 90.0 - 140.0 * k - 90.0 * c];
s.execute("pattern.transform", &json!({"ids": [turned], "matrix": m})).unwrap();
s.execute("swatch.new", &json!({"name": "Ink", "color": "#ff9900", "spot": true})).unwrap();
let outer = rect(&mut s, 190.0, 70.0, 90.0, 40.0);
let hole = rect(&mut s, 210.0, 80.0, 40.0, 20.0);
let ring = id(s.execute("object.compoundPath.make", &json!({"ids": [outer, hole]})).unwrap());
let mixed = json!({"kind": "linear", "stops": [
{"offset": 0, "color": {"gray": 0.8}},
{"offset": 0.5, "color": {"c": 1, "m": 0, "y": 0, "k": 0}, "midpoint": 0.7},
{"offset": 1, "swatch": "Ink", "tint": 70}
]});
s.execute("paint.setFill", &json!({"ids": [ring], "gradient": mixed})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [ring], "none": true})).unwrap();
let dawn = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#ffcc00"}, {"offset": 1, "color": "#cc3300"}]});
s.execute("swatch.new", &json!({"name": "Dawn", "gradient": dawn})).unwrap();
s
}
/// Gradients and patterns come back from the editing copy for other apps alone (the native
/// document left out), with every save option that writes the copy; where the file has PDF pages,
/// the reader takes the copy only when it draws as its page does. The version 7 `.ai` keeps each
/// gradient.
#[test]
fn gradients_and_patterns_come_back_from_the_editing_copy() {
let mut s = gradient_session();
let before = (*s.doc().unwrap().doc).clone();
let want = paint_outline(&before);
assert!(want.iter().filter(|l| l.starts_with("path") && l.contains("pattern Dots")).count() == 2, "{want:#?}");
assert!(want.iter().any(|l| l.starts_with("compound") && l.contains("Ink") && l.contains(") 0.70")), "{want:#?}");
assert!(want.iter().any(|l| l.contains("mid 0.30")) && want.iter().any(|l| l.starts_with("swatch Dawn")), "{want:#?}");
for opts in [
json!({"format": "ai"}),
json!({"format": "ai", "compress": false}),
json!({"format": "ai", "embedProfiles": false}),
json!({"format": "ai", "includeLinked": true}),
json!({"format": "ai", "range": "all"}),
json!({"format": "ai", "pdfCompatible": false}),
] {
let r = s.execute("document.export", &opts).unwrap();
assert!(!r["warnings"].to_string().contains("gradient") && !r["warnings"].to_string().contains("pattern"), "{r}");
let copy = editing_copy(&b64(&r));
assert_eq!(paint_outline(&copy), want, "{opts}");
}
let path = tmp("gradients.ai");
let r = s.execute("document.save", &json!({"path": path, "separateArtboards": true})).unwrap();
let files: Vec<String> = r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect();
assert_eq!(files.len(), 3, "{r}");
for f in files.iter().filter(|f| !f.ends_with("-2.ai")) {
assert_eq!(paint_outline(&editing_copy(&std::fs::read(f).unwrap())), want, "{f}");
}
let r = s.execute("document.export", &json!({"format": "ai", "aiVersion": 7})).unwrap();
let legacy = load::load_with("art.ai", &b64(&r), &LoadOptions::default()).unwrap();
// Each gradient the art paints with, by its kind and its stops' places and colors to 5% (version
// 7 writes a gradient stroke as its filled outline, so the objects differ, and a spot color's
// tint through its CMYK equivalent, 2% off here).
let gradients = |doc: &vectorcraft_doc::Document| {
let mut all = std::collections::BTreeSet::new();
doc.walk(|node| {
for it in node.appearance.items.iter() {
if let vectorcraft_color::Paint::Gradient(g) = it.paint() {
let stops: Vec<String> = g
.gradient
.stops
.iter()
.map(|s| format!("{:.3} {:?}", s.offset, s.color.to_rgb().map(|v| (v * 20.0).round() * 5.0)))
.collect();
all.insert(format!("{:?} {stops:?}", g.gradient.kind));
}
}
});
all
};
assert_eq!(gradients(&legacy.doc), gradients(&before));
}
+39 -1
View File
@@ -32,6 +32,44 @@ fn png_chunk<'a>(file: &'a [u8], ty: &[u8; 4]) -> Option<&'a [u8]> {
None
}
#[test]
fn raster_export_defaults_to_document_resolution() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 72, "height": 36, "rasterEffectsPpi": 300})).unwrap();
assert_eq!(s.doc().unwrap().doc.raster_effects_ppi, 300.0);
for format in ["png", "psd"] {
for (options, size, ppi) in [
(json!({}), (300, 150), 300.0),
(json!({"scale": 1}), (72, 36), 72.0),
(json!({"scale": 2}), (144, 72), 144.0),
(json!({"ppi": 150, "scale": 2}), (150, 75), 150.0),
] {
let mut params = options;
params["format"] = json!(format);
let bytes = b64(&s.execute("document.export", &params).unwrap());
assert_eq!(super::ppi::resolution(&bytes), Some((ppi, ppi)), "{params}");
let image = super::load::raster_image(&bytes).unwrap();
assert_eq!((image.width, image.height), size, "{params}");
}
}
}
#[test]
fn raster_export_default_uses_the_sanitised_document_resolution() {
// A stored resolution that isn't finite or is outside 1–2400 ppi exports at the resolution the
// document reports (72 when not finite, else clamped), not at a zero, huge or failed size.
for (stored, (width, height), size) in [(f64::NAN, (72, 36), (72, 36)), (0.0, (144, 72), (2, 1)), (1e9, (36, 18), (1200, 600))] {
let mut s = Session::new();
s.execute("file.new", &json!({"width": width, "height": height})).unwrap();
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).raster_effects_ppi = stored;
for format in ["png", "psd"] {
let bytes = b64(&s.execute("document.export", &json!({"format": format})).unwrap());
let image = super::load::raster_image(&bytes).unwrap();
assert_eq!((image.width, image.height), size, "{format} with a stored {stored} ppi");
}
}
}
#[test]
fn png_options_resolution_background_interlace_and_anti_aliasing() {
let mut s = session(40.0, 30.0, 1);
@@ -183,7 +221,7 @@ fn formats_list_the_raster_options() {
assert!(opts("png").get(k).is_some(), "png lists {k}");
}
assert_eq!(opts("png")["antiAlias"]["default"], "art");
assert_eq!(opts("png")["ppi"]["default"], 72);
assert_eq!(opts("png")["ppi"]["default"], Value::Null);
assert!(opts("jpg").get("quality").is_some() && opts("jpg").get("interlaced").is_none());
assert!(opts("webp").get("antiAlias").is_some() && opts("svg").get("antiAlias").is_none());
}
+7 -2
View File
@@ -151,11 +151,16 @@ impl FlattenOptions {
/// Whether colorized image `n`, art of `d`, counts as transparency by itself. With
/// [`Self::keeps_colorize`], an image colorized with a solid paint whose pixels are grayscale
/// or 1-bit doesn't: the EPS writer draws it in that paint.
/// or 1-bit doesn't: the EPS writer draws it in that paint. An image whose pixels don't take
/// the paint ([`vectorcraft_doc::ImageBlob::takes_colorize`]) never counts: it draws uncolorized.
pub(crate) fn counts_colorize(&self, d: &Document, n: &Node) -> bool {
let NodeKind::Image(im) = &n.kind else { return true };
let blob = d.image_blob(im);
if blob.is_some_and(|b| !b.takes_colorize()) {
return false;
}
let solid = matches!(n.extras().colorize.as_deref(), Some(Paint::Solid { .. }));
!self.keeps_colorize || !solid || d.image_blob(im).is_some_and(|b| b.gray_source().is_none())
!self.keeps_colorize || !solid || blob.is_some_and(|b| b.gray_source().is_none())
}
/// `n` shows an image whose see-through pixels count as transparency.
+83 -17
View File
@@ -2,7 +2,7 @@
//! another everywhere or in the selection, and selecting the text that uses a font. Also the fonts
//! available (the bundled and installed ones) and rescanning the installed fonts.
use std::collections::{BTreeMap, BTreeSet};
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::sync::Arc;
use serde_json::{Value, json};
@@ -64,18 +64,19 @@ pub fn specs() -> Vec<CommandSpec> {
}
/// Text objects in scope: the selection's (and their descendants') or the whole document's.
fn scope(s: &Session, selection_only: bool) -> Result<Vec<NodeId>> {
fn scope(s: &Session, selection_only: bool, selected: Option<&[NodeId]>) -> Result<Vec<NodeId>> {
let st = s.doc()?;
let mut v = vec![];
let mut seen = HashSet::new();
let mut add = |n: &vectorcraft_doc::Node| {
n.walk(&mut |c| {
if matches!(c.kind, NodeKind::Text(_)) && !v.contains(&c.id) {
if matches!(c.kind, NodeKind::Text(_)) && seen.insert(c.id) {
v.push(c.id);
}
})
};
if selection_only {
for id in &st.selection.objects {
for id in selected.unwrap_or(&st.selection.objects) {
if let Some(n) = st.doc.node(*id) {
add(n);
}
@@ -97,7 +98,7 @@ fn being_edited(d: &Document, name: &str) -> bool {
/// descendants, and of the instances in those symbols' art that are not hidden or locked, nor in a
/// hidden or locked group of the art. Returned as (all of them, those shown by instances the
/// Selection tool can reach: not hidden or locked, as `Document::editable` says).
fn selected_symbols(s: &Session) -> Result<(BTreeSet<String>, BTreeSet<String>)> {
fn selected_symbols(s: &Session, selected: Option<&[NodeId]>) -> Result<(BTreeSet<String>, BTreeSet<String>)> {
fn open_instances(n: &Node, out: &mut BTreeSet<String>) {
if !n.visible || n.locked {
return;
@@ -123,7 +124,7 @@ fn selected_symbols(s: &Session) -> Result<(BTreeSet<String>, BTreeSet<String>)>
let st = s.doc()?;
let (mut all, mut open) = (BTreeSet::new(), BTreeSet::new());
let editable = st.doc.editable();
for id in &st.selection.objects {
for id in selected.unwrap_or(&st.selection.objects) {
if let Some(n) = st.doc.node(*id) {
n.walk(&mut |c| {
if let NodeKind::SymbolInstance { symbol, .. } = &c.kind {
@@ -482,12 +483,66 @@ fn text(d: &Document, id: NodeId) -> Option<&vectorcraft_doc::TextObject> {
}
fn fonts(s: &mut Session, p: &Value) -> Result<Value> {
let selection_only = bool_or(p, "selectionOnly", false);
let ids = scope(s, selection_only)?;
if bool_or(p, "selectionOnly", false) {
let selected = s.doc()?.selection.objects.clone();
font_inventory(s, Some(&selected))
} else {
font_inventory(s, None)
}
}
impl Session {
/// List the fonts in the document, or in the given objects and their symbols.
pub fn font_inventory(&self, selected: Option<&[NodeId]>) -> Result<Value> {
font_inventory(self, selected)
}
/// List text currently unavailable to a Replace Font request in its original selection.
pub fn skipped_font_ids(&self, params: &Value, selected: Option<&[NodeId]>) -> Result<Vec<NodeId>> {
let (family, style) = font_param(params, "from", "text.replaceFont")?;
let selection_only = bool_or(params, "selectionOnly", false);
let selected_symbols = selection_only.then(|| selected_symbols(self, selected)).transpose()?;
let d = &self.doc()?.doc;
let other: Vec<NodeId> = {
let editable = d.editable();
scope(self, selection_only, selected)?.into_iter().filter(|id| !editable(*id)).collect()
};
let uses = |t: &TextObject| {
t.runs.iter().any(|r| {
r.style.font_family.eq_ignore_ascii_case(&family) && style.as_ref().is_none_or(|name| r.style.font_style.eq_ignore_ascii_case(name))
})
};
let mut ids = other.into_iter().filter(|id| text(d, *id).is_some_and(uses)).collect::<Vec<_>>();
fn visit(n: &Node, open: bool, closed: bool, uses: &impl Fn(&TextObject) -> bool, ids: &mut Vec<NodeId>) {
let open = open && n.visible && !n.locked;
if let NodeKind::Text(t) = &n.kind
&& (!open || closed)
&& uses(t)
{
ids.push(n.id);
}
for child in n.children().map(Vec::as_slice).unwrap_or_default() {
visit(child, open, closed, uses, ids);
}
}
for symbol in d
.symbols
.iter()
.filter(|symbol| !being_edited(d, &symbol.name) && selected_symbols.as_ref().is_none_or(|(all, _)| all.contains(&symbol.name)))
{
let closed = selected_symbols.as_ref().is_some_and(|(_, open)| !open.contains(&symbol.name));
visit(&symbol.art, true, closed, &uses, &mut ids);
}
Ok(ids)
}
}
fn font_inventory(s: &Session, selected: Option<&[NodeId]>) -> Result<Value> {
let ids = scope(s, selected.is_some(), selected)?;
let d = &s.doc()?.doc;
let db = vectorcraft_text::FontDb::global();
// The type in the art of the symbols in scope too: all of them, or those the selection shows.
let symbols = if selection_only { Some(selected_symbols(s)?.0) } else { None };
let symbols = if selected.is_some() { Some(selected_symbols(s, selected)?.0) } else { None };
let mut texts: Vec<&TextObject> = ids.iter().filter_map(|id| text(d, *id)).collect();
texts.extend(symbol_texts(d, symbols.as_ref()).into_iter().map(|(t, _)| t));
let mut found: BTreeMap<UsedFont, (usize, usize, String)> = BTreeMap::new();
@@ -536,6 +591,21 @@ fn font_param(p: &Value, k: &str, c: &str) -> Result<(String, Option<String>)> {
Ok((family.to_string(), v.get("style").and_then(Value::as_str).map(str::to_string)))
}
fn skipped_font_texts(
d: &Document,
other: &[NodeId],
symbols: &[(&TextObject, bool)],
closed: &BTreeSet<String>,
uses: &impl Fn(&TextObject) -> bool,
) -> usize {
let mut skipped = other.iter().filter(|id| text(d, **id).is_some_and(uses)).count();
skipped += symbols.iter().filter(|(t, open)| !open && uses(t)).count();
if !closed.is_empty() {
skipped += symbol_texts(d, Some(closed)).into_iter().filter(|(t, _)| uses(t)).count();
}
skipped
}
fn replace(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "text.replaceFont";
let (ff, fs) = font_param(p, "from", C)?;
@@ -567,7 +637,7 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> {
// With selectionOnly: the symbols the selection shows; those shown only by hidden or locked
// instances keep their type, counted in `skipped`.
let (symbols, closed) = if selection_only {
let (all, open) = selected_symbols(s)?;
let (all, open) = selected_symbols(s, None)?;
let closed: BTreeSet<String> = all.difference(&open).cloned().collect();
(Some(open), closed)
} else {
@@ -579,13 +649,9 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> {
let (ids, skipped, in_symbols) = {
let d = &s.doc()?.doc;
let editable = d.editable();
let (ids, other): (Vec<NodeId>, Vec<NodeId>) = scope(s, selection_only)?.into_iter().partition(|id| editable(*id));
let mut skipped = other.into_iter().filter(|id| text(d, *id).is_some_and(uses)).count();
let (ids, other): (Vec<NodeId>, Vec<NodeId>) = scope(s, selection_only, None)?.into_iter().partition(|id| editable(*id));
let texts = symbol_texts(d, symbols.as_ref());
skipped += texts.iter().filter(|(t, open)| !open && uses(t)).count();
if !closed.is_empty() {
skipped += symbol_texts(d, Some(&closed)).into_iter().filter(|(t, _)| uses(t)).count();
}
let skipped = skipped_font_texts(d, &other, &texts, &closed, &uses);
// The text that changes: when none does, the document and its undo history stay as they are.
let ids: Vec<NodeId> = ids.into_iter().filter(|id| text(d, *id).is_some_and(changes)).collect();
let in_symbols = texts.iter().any(|(t, open)| *open && changes(t));
@@ -646,7 +712,7 @@ const REPLACE_SKIPPED: &str = "some text is hidden or locked, so its font wasn't
fn select_font(s: &mut Session, p: &Value) -> Result<Value> {
let family = str_param(p, "family").ok_or_else(|| bad("select.font", "missing `family`"))?.to_string();
let style = str_param(p, "style").map(str::to_string);
let ids = scope(s, false)?;
let ids = scope(s, false, None)?;
let d = &s.doc()?.doc;
// Only text the Selection tool can reach: not hidden or locked, in a hidden or locked group
// or layer, or on a locked artboard.
+45 -8
View File
@@ -10,7 +10,10 @@
//!
//! An overlap area is a face of the planar arrangement of what the members paint (their fills and
//! strokes, type outlined; other objects by their bounds): the part where two or more of them
//! overlap, split wherever a member's edge crosses it.
//! overlap, split wherever a member's edge crosses it. The area a member is raised in is that
//! face grown a little ([`SEAM`]) into the parts where only that member paints ([`raised_area`]),
//! so its edge does not lie on the edge of the member it passes over: there, both edges would be
//! anti-aliased and the member below would show through as a hairline (#5337).
//!
//! Behaviour: <https://helpx.adobe.com/illustrator/using/intertwine-objects.html> (Make,
//! Release, clicking or drawing around an overlap, Bring to Front, Bring Forward, Send Backward
@@ -23,7 +26,7 @@ use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use vectorcraft_geom::{FillRule, PathData, Point, SubPath};
use vectorcraft_pathops as po;
use vectorcraft_tools::intertwine::{Face, drawn_order, face_at, faces, faces_in, is_intertwine, nonempty};
use vectorcraft_tools::intertwine::{Face, drawn_order, face_at, faces_in, faces_of, is_intertwine, nonempty, painted_areas};
use super::edit::selected_roots;
use super::pathops::Beside;
@@ -302,13 +305,46 @@ fn tiers(order: &[usize]) -> Vec<(usize, usize)> {
.collect()
}
/// How far (pt) the area a member is raised in reaches past its overlap face, into the parts only
/// that member paints ([`raised_area`]).
const SEAM: f64 = 2.0;
/// The area member `i` is raised in for `face`: the face, and the parts within [`SEAM`] of it
/// where only `i` paints (`areas`: what each member paints, [`painted_areas`]). Drawing `i` again
/// there changes nothing, and the edge of the area then lies inside `i`, not on the edge of a
/// member it passes over (where the anti-aliased edges of both would let that member show
/// through as a hairline).
fn raised_area(face: &PathData, i: usize, areas: &[Option<PathData>]) -> PathData {
let Some(own) = areas.get(i).and_then(Option::as_ref) else { return face.clone() };
let ring = po::offset_path(face, SEAM, po::Join::Round, 4.0);
let Some(near) = ring.bounds() else { return face.clone() };
let mut paths = vec![(&ring, FillRule::NonZero), (own, FillRule::NonZero)];
paths.extend(
areas
.iter()
.enumerate()
.filter(|(k, _)| *k != i)
.filter_map(|(_, a)| a.as_ref())
.filter(|a| a.bounds().is_some_and(|b| b.overlaps(near)))
.map(|a| (a, FillRule::NonZero)),
);
let only = po::boolean_n(&paths, |inside| inside.first() == Some(&true) && inside.get(1) == Some(&true) && !inside.iter().skip(2).any(|b| *b));
if only.is_empty() {
return face.clone();
}
nonempty(po::boolean(face, FillRule::NonZero, &only, FillRule::NonZero, po::BoolOp::Union)).unwrap_or_else(|| face.clone())
}
/// Draw the members of `face` in `order` there (bottom first), leaving the other areas as they
/// are.
fn arrange_face(children: &mut [Arc<Node>], face: &Face, order: &[usize]) {
/// are (`areas`: what each member paints, [`painted_areas`]).
fn arrange_face(children: &mut [Arc<Node>], face: &Face, order: &[usize], areas: &[Option<PathData>]) {
for (i, tier) in tiers(order) {
if let Some(c) = children.get_mut(i) {
set_tier(Arc::make_mut(c), &face.path, tier);
let Some(c) = children.get_mut(i) else { continue };
// A member drawn in its own order there with no areas has nothing to change.
if tier == 0 && c.extras().intertwine.is_none() && c.extras().intertwine_tiers.is_empty() {
continue;
}
set_tier(Arc::make_mut(c), &raised_area(&face.path, i, areas), tier);
}
}
@@ -379,7 +415,8 @@ fn arrange(s: &mut Session, p: &Value) -> Result<Value> {
Some(m) => Some(children.iter().position(|c| c.id == m).ok_or_else(|| bad(C, format!("object {} is not in this Intertwine group", m.0)))?),
None => None,
};
let all = faces(&children);
let painted = painted_areas(&children);
let all = faces_of(&painted);
let found = match (at, &lasso) {
(Some(p), _) => face_at(&all, p).into_iter().collect(),
(None, Some(l)) => faces_in(&all, l),
@@ -423,7 +460,7 @@ fn arrange(s: &mut Session, p: &Value) -> Result<Value> {
let n = d.node_mut(group).ok_or(EngineError::NoNode(group))?;
let NodeKind::Intertwine { children } = &mut n.kind else { return Err(EngineError::NoNode(group)) };
for (face, new) in &plans {
arrange_face(children, face, new);
arrange_face(children, face, new, &painted);
}
Ok(())
})?;
+105 -21
View File
@@ -100,7 +100,31 @@ pub enum ItemKind {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LibraryColor {
pub name: String,
/// The colour; a spot colour's full-strength ink (its swatch's colour), without the tint.
pub color: Color,
/// A spot colour's ink (its swatch's name): using it adds the document's spot swatch of that
/// name and links the paint to it (#5812). Files written before spot colours have none.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub spot: Option<String>,
/// A spot colour's tint (0..1; 1 for a process colour).
#[serde(default = "full_tint", skip_serializing_if = "is_full_tint")]
pub tint: f32,
}
fn full_tint() -> f32 {
1.0
}
fn is_full_tint(t: &f32) -> bool {
*t >= 1.0
}
/// A library colour as `library.add` reads it from the selection or params.
struct NewColor {
name: String,
color: Color,
spot: Option<String>,
tint: f32,
}
/// A graphic: the art as a native document (its own resources included) and its thumbnail.
@@ -369,6 +393,13 @@ impl Library {
fn sanitize(&mut self) {
clip(&mut self.name);
self.colors.truncate(MAX_ITEMS);
for c in &mut self.colors {
if let Some(ink) = &mut c.spot {
clip(ink);
}
c.spot = c.spot.take().filter(|ink| !ink.trim().is_empty());
c.tint = if c.spot.is_some() && c.tint.is_finite() { c.tint.clamp(0.0, 1.0) } else { 1.0 };
}
self.gradients.retain_mut(|g| clean_gradient(&mut g.gradient));
self.gradients.truncate(MAX_ITEMS);
self.patterns.truncate(MAX_ITEMS);
@@ -598,7 +629,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Library",
[],
None,
"{library?: id or name (default: the current library)} → {id, name, graphics: [{id, name, width, height, thumbnail: PNG base64}], colors: [{name, hex, color}], gradients: [{name, gradient: {gradient: {kind, stops}, angle}}], patterns: [{name, pattern: its name in the item, thumbnail: PNG base64}], charStyles: [{name, attrs}], paraStyles: [{name, attrs}], groups: [{name, items: [{kind: color|gradient|pattern|charStyle|paraStyle|graphic, item: name (graphic: id)}]}] (an item is in one group at most; the others are ungrouped)}",
"{library?: id or name (default: the current library)} → {id, name, graphics: [{id, name, width, height, thumbnail: PNG base64}], colors: [{name, hex, color, spot: ink name or null, tint: 0..1}], gradients: [{name, gradient: {gradient: {kind, stops}, angle}}], patterns: [{name, pattern: its name in the item, thumbnail: PNG base64}], charStyles: [{name, attrs}], paraStyles: [{name, attrs}], groups: [{name, items: [{kind: color|gradient|pattern|charStyle|paraStyle|graphic, item: name (graphic: id)}]}] (an item is in one group at most; the others are ungrouped)}",
always,
get
),
@@ -643,7 +674,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add to Library",
[],
None,
"{library?: id or name (default: the current library, made when there is none), kind: graphic|fillColor|strokeColor|fillGradient|strokeGradient|fillPattern|strokePattern|charStyle|paraStyle, ids?: objects (default: the selection), name?, color?: colour (a colour to add, instead of the selection's; #rrggbbaa and #rgba are refused), swatch?: a gradient or pattern swatch of the document (fillGradient…strokePattern: added instead of the selection's paint), group?: name, before?: item | after?: item (an item of the same kind)} add an item from the selection: graphic: a copy of the objects with every resource they use; fillColor/strokeColor: the first selected object's solid fill/stroke colour (else the default fill/stroke); fillGradient/strokeGradient: the first selected object's fill/stroke gradient (else the default's), without its placement or swatch links, named after its swatch, else \"Gradient\"; fillPattern/strokePattern: the first selected object's fill/stroke pattern (else the default's) with the resources its art uses, named after it; charStyle/paraStyle: the selected text's character/paragraph attributes (the Type tool's range, else the first selected text object). A new item goes into `group` (default: none) and, with `before` or `after`, just before or after that item in the order its kind is shown in, as dropping it among the Libraries panel's items does; an item the library already has (same kind and contents) isn't added again, nor moved → {library, kind, name, id?: graphic id, existing: bool, group?: name or null (a new item's)}",
"{library?: id or name (default: the current library, made when there is none), kind: graphic|fillColor|strokeColor|fillGradient|strokeGradient|fillPattern|strokePattern|charStyle|paraStyle, ids?: objects (default: the selection), name?, color?: colour (a colour to add, instead of the selection's; #rrggbbaa and #rgba are refused), swatch?: a gradient or pattern swatch of the document (fillGradient…strokePattern: added instead of the selection's paint; with `color`, the spot swatch it is, kept as a spot colour), tint?: 0..100 (with `color` and a spot `swatch`: its %), group?: name, before?: item | after?: item (an item of the same kind)} add an item from the selection: graphic: a copy of the objects with every resource they use; fillColor/strokeColor: the first selected object's solid fill/stroke colour (else the default fill/stroke), a colour linked to a spot swatch kept as a spot colour (the swatch's name, its colour and the tint); fillGradient/strokeGradient: the first selected object's fill/stroke gradient (else the default's), without its placement or swatch links, named after its swatch, else \"Gradient\"; fillPattern/strokePattern: the first selected object's fill/stroke pattern (else the default's) with the resources its art uses, named after it; charStyle/paraStyle: the selected text's character/paragraph attributes (the Type tool's range, else the first selected text object). A new item goes into `group` (default: none) and, with `before` or `after`, just before or after that item in the order its kind is shown in, as dropping it among the Libraries panel's items does; an item the library already has (same kind and contents) isn't added again, nor moved → {library, kind, name, id?: graphic id, existing: bool, group?: name or null (a new item's)}",
has_doc,
add
),
@@ -652,7 +683,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Use Library Item",
[],
None,
"{library?, kind, item: name (graphic: id or name), center?: [x, y] (graphic; default: the first artboard's centre), to?: fill|stroke (colors, gradients, patterns; default: the kind's), recorded?: the item as it was when used (recorded in the journal so a replay matches)} graphic: place a copy centred on `center`, its resources pasted along, selected, one undo step; colors and gradients: paint the selection (and the defaults) as paint.setFill/paint.setStroke, a gradient fitting each object; patterns: add the pattern and its swatch to the document (a name the document gives another pattern gets a number; the same pattern is reused) and paint the selection (and the defaults) with it, one undo step; charStyle/paraStyle: add the style to the document (a name taken by different attributes gets a number) and apply it to the selected text, one undo step → {kind, ids?, style?}",
"{library?, kind, item: name (graphic: id or name), center?: [x, y] (graphic; default: the first artboard's centre), to?: fill|stroke (colors, gradients, patterns; default: the kind's), recorded?: the item as it was when used (recorded in the journal so a replay matches)} graphic: place a copy centred on `center`, its resources pasted along, selected, one undo step; colors and gradients: paint the selection (and the defaults) as paint.setFill/paint.setStroke, a gradient fitting each object; a spot color links to the document's spot swatch of its ink's name, added when the document has none of that colour (a name taken by another colour gets a number), one undo step; patterns: add the pattern and its swatch to the document (a name the document gives another pattern gets a number; the same pattern is reused) and paint the selection (and the defaults) with it, one undo step; charStyle/paraStyle: add the style to the document (a name taken by different attributes gets a number) and apply it to the selected text, one undo step → {kind, ids?, style?}",
has_doc,
use_item
),
@@ -782,7 +813,7 @@ fn get(s: &mut Session, p: &Value) -> Result<Value> {
"id": id,
"name": lib.name,
"graphics": lib.graphics.iter().map(|g| json!({"id": g.id, "name": g.name, "width": g.width, "height": g.height, "thumbnail": g.thumbnail})).collect::<Vec<_>>(),
"colors": lib.colors.iter().map(|c| json!({"name": c.name, "hex": c.color.to_hex(), "color": c.color})).collect::<Vec<_>>(),
"colors": lib.colors.iter().map(|c| json!({"name": c.name, "hex": c.color.to_hex(), "color": c.color, "spot": c.spot, "tint": c.tint})).collect::<Vec<_>>(),
"gradients": lib.gradients.iter().map(|g| json!({"name": g.name, "gradient": g.gradient})).collect::<Vec<_>>(),
"patterns": lib.patterns.iter().map(|p| json!({"name": p.name, "pattern": p.pattern, "thumbnail": p.thumbnail})).collect::<Vec<_>>(),
"charStyles": lib.char_styles.iter().map(|t| json!({"name": t.name, "attrs": t.attrs})).collect::<Vec<_>>(),
@@ -856,13 +887,14 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
lib.graphics.push(g);
placed(lib, &place, ItemRef { kind: item_kind, item: key }, v)?
}
Item::Color((name, color)) => {
Item::Color(NewColor { name, color, spot, tint }) => {
full(lib.colors.len())?;
if let Some(old) = lib.colors.iter().find(|o| o.color == color) {
// A spot colour is its ink: one of another ink (or a process colour) is another item.
if let Some(old) = lib.colors.iter().find(|o| o.color == color && o.spot == spot && o.tint == tint) {
return Ok(json!({ "name": old.name, "existing": true }));
}
let name = unique(&given.clone().unwrap_or(name), |n| lib.colors.iter().any(|o| o.name == n));
lib.colors.push(LibraryColor { name: name.clone(), color });
lib.colors.push(LibraryColor { name: name.clone(), color, spot, tint });
placed(lib, &place, ItemRef { kind: item_kind, item: name.clone() }, json!({ "name": name, "existing": false }))?
}
Item::Gradient(mut g) => {
@@ -925,7 +957,7 @@ fn placed(lib: &mut Library, place: &Placement, r: ItemRef, mut v: Value) -> Res
enum Item {
Graphic(LibraryGraphic),
Color((String, Color)),
Color(NewColor),
Gradient(LibraryGradient),
Pattern(LibraryPattern),
Style(bool, Map<String, Value>),
@@ -942,7 +974,7 @@ fn graphic_of(s: &Session, p: &Value, cmd: &str) -> Result<LibraryGraphic> {
if roots.is_empty() {
return Err(bad(cmd, "select the art to add first"));
}
let clip = Clipboard::copy(st, &roots);
let clip = Clipboard::copy(st, &roots, false);
let bounds = clip.bounds().ok_or_else(|| bad(cmd, "the selection draws nothing"))?;
let mut doc = clip.to_document();
let board = bounds.inflate(1.0, 1.0);
@@ -963,23 +995,38 @@ fn graphic_of(s: &Session, p: &Value, cmd: &str) -> Result<LibraryGraphic> {
}
/// The first selected object's solid fill (`stroke`: stroke) colour, else the default one, with a
/// name: its swatch's, else its hex.
fn color_of(s: &Session, p: &Value, stroke: bool, cmd: &str) -> Result<(String, Color)> {
// A colour given (a swatch dropped on the panel).
/// name: its swatch's, else its hex. A colour linked to a spot swatch keeps the ink (the swatch's
/// name and full-strength colour) and its tint.
fn color_of(s: &Session, p: &Value, stroke: bool, cmd: &str) -> Result<NewColor> {
// A colour given (a swatch dropped on the panel), with its spot swatch's name when it has one.
if let Some(c) = p.get("color").filter(|v| !v.is_null()) {
let color = color_value(c).ok_or_else(|| bad(cmd, "bad colour"))?;
return Ok((color.to_hex(), color));
let swatch = str_param(p, "swatch").map(str::to_string);
let tint = super::paint::tint_param(p, cmd)?.unwrap_or(1.0);
let given = NewColor { name: color.to_hex(), color, spot: None, tint: 1.0 };
return Ok(spot_color(s, given, swatch, tint));
}
match selected_paint(s, p, stroke)? {
Paint::Solid { color, swatch, .. } => {
let name = swatch.filter(|n| !n.is_empty()).unwrap_or_else(|| color.to_hex());
Ok((name, color))
Paint::Solid { color, swatch, tint } => {
let swatch = swatch.filter(|n| !n.is_empty());
let name = swatch.clone().unwrap_or_else(|| color.to_hex());
Ok(spot_color(s, NewColor { name, color, spot: None, tint: 1.0 }, swatch, tint))
}
Paint::None => Err(bad(cmd, if stroke { "the selection has no stroke colour" } else { "the selection has no fill colour" })),
_ => Err(bad(cmd, "only solid colours can be added (not gradients or patterns)")),
}
}
/// `c` as the spot colour of the active document's spot swatch `swatch` at `tint` (0..1), when
/// there is one: named after it, with its full-strength colour; else `c` as it is.
fn spot_color(s: &Session, c: NewColor, swatch: Option<String>, tint: f32) -> NewColor {
let Some(doc) = s.active().map(|st| &st.doc) else { return c };
let Some(name) = swatch else { return c };
let Some(ink) = doc.swatch(&name).filter(|w| w.spot).and_then(|w| w.paint.color()) else { return c };
let tint = if tint.is_finite() { tint.clamp(0.0, 1.0) } else { 1.0 };
NewColor { name: name.clone(), color: ink, spot: Some(name), tint }
}
/// The first selected object's (or `ids`') fill (`stroke`: stroke) paint (type's: its first
/// character's, as the proxy shows it), else the default one.
fn selected_paint(s: &Session, p: &Value, stroke: bool) -> Result<Paint> {
@@ -989,11 +1036,13 @@ fn selected_paint(s: &Session, p: &Value, stroke: bool) -> Result<Paint> {
None => st.selection.objects.clone(),
};
let from_art = ids.iter().filter_map(|id| st.doc.node(*id)).find_map(|n| {
let (paint, to_doc, _) = n.proxy_paint(stroke, None)?;
let (paint, to_doc, bounds) = n.proxy_paint(stroke, None)?;
// Type's characters paint in its own space: a gradient there takes its placement in the
// document, so that it keeps the direction it shows.
match (paint, n.proxy_gradient(stroke, None)) {
(Paint::Gradient(g), Some((_, geom))) if to_doc != vectorcraft_geom::Affine::IDENTITY => {
match paint {
Paint::Gradient(g) if to_doc != vectorcraft_geom::Affine::IDENTITY => {
let mut geom = g.resolve(bounds);
geom.transform(to_doc, g.gradient.kind);
Some(Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..(**g).clone() })))
}
_ => Some(paint.clone()),
@@ -1100,7 +1149,10 @@ fn use_item(s: &mut Session, p: &Value) -> Result<Value> {
}
Kind::FillColor | Kind::StrokeColor => {
let c = lib.colors.iter().find(|c| c.name == item).ok_or_else(missing)?;
json!({ "color": c.color })
match &c.spot {
Some(ink) => json!({ "color": c.color, "spot": ink, "tint": c.tint }),
None => json!({ "color": c.color }),
}
}
Kind::FillGradient | Kind::StrokeGradient => {
let g = lib.gradients.iter().find(|g| g.name == item).ok_or_else(missing)?;
@@ -1143,7 +1195,13 @@ fn use_item(s: &mut Session, p: &Value) -> Result<Value> {
Kind::FillColor | Kind::StrokeColor => {
let stroke = to_stroke(p, kind)?;
let color = data.get("color").cloned().ok_or_else(|| bad(C, "no colour"))?;
s.execute(if stroke { "paint.setStroke" } else { "paint.setFill" }, &json!({ "color": color }))?;
let set = if stroke { "paint.setStroke" } else { "paint.setFill" };
match str_param(&data, "spot").map(str::trim).filter(|n| !n.is_empty()) {
Some(ink) => use_spot(s, set, ink, &color, &data)?,
None => {
s.execute(set, &json!({ "color": color }))?;
}
}
Ok(json!({ "kind": if stroke { "strokeColor" } else { "fillColor" } }))
}
Kind::FillGradient | Kind::StrokeGradient => {
@@ -1185,6 +1243,32 @@ fn use_item(s: &mut Session, p: &Value) -> Result<Value> {
}
}
/// Paint with library spot colour `ink` (`color` its full-strength colour, `data`'s `tint` its
/// tint) through `set` (paint.setFill or paint.setStroke), linked to the document's spot swatch of
/// that name: the one it has when it is the same colour, else a new one (a name taken by another
/// colour gets a number), one undo step (#5812).
fn use_spot(s: &mut Session, set: &str, ink: &str, color: &Value, data: &Value) -> Result<()> {
const C: &str = "library.use";
let c = color_value(color).ok_or_else(|| bad(C, "the library item is damaged"))?;
let tint = data.get("tint").and_then(Value::as_f64).filter(|t| t.is_finite()).map_or(1.0, |t| t.clamp(0.0, 1.0));
let doc = &s.doc()?.doc;
let have = doc.swatch(ink).is_some_and(|w| w.spot && w.paint.color() == Some(c));
in_one_step(s, |s| {
let swatch = if have {
ink.to_string()
} else {
let r = s.execute("swatch.new", &json!({ "name": ink, "color": color, "spot": true, "keepModel": true }))?;
r.get("name").and_then(Value::as_str).ok_or_else(|| bad(C, "the spot colour couldn't be added"))?.to_string()
};
let mut p = json!({ "swatch": swatch });
if tint < 1.0 {
p["tint"] = json!(tint * 100.0);
}
s.execute(set, &p)?;
Ok(())
})
}
/// The `to` param of `library.use`: whether the item paints the stroke (default: the kind's).
fn to_stroke(p: &Value, kind: Kind) -> Result<bool> {
match str_param(p, "to") {
+24 -5
View File
@@ -2,7 +2,7 @@
//! subfolders (`links.findFiles`, searched on separate threads: [`super::findfiles`]). A file with
//! a linked file's name, in any letter case, is ranked by what the link saved
//! ([`vectorcraft_doc::LinkInfo`]): the same file (its size and hash), the same size (when the link
//! saved no hash, or the file is larger than 1 GB and isn't hashed), or the name only.
//! saved no hash, or the file is larger than 1 GiB and isn't hashed), or the name only.
use std::collections::HashMap;
use std::path::{Component, Path, PathBuf};
@@ -29,7 +29,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Find Linked Files",
[],
None,
"{folder?: an absolute path, ids?: [image or placed document ids] (default: the active document's missing links), maxSeconds?: 60 (1 to 600), stop?: false (true: stop the last search)} with folder: look in it and its subfolders, on separate threads, for files with the names of the linked files (in any letter case), and answer at once with the search's state (searching while it runs); without folder: the last search's state, with the files found so far. Each linked file's files come best first: same (the size and hash saved with the link), size (the saved size, where there is no saved hash or the file is larger than 1 GB), then name. Within each kind, a file whose name has the link's letter case comes first. Then each file's folder names are compared with the saved path's, from the innermost outward up to the first one that differs, and a file with more matching names comes first; files that still tie are listed by path. A search looks for at most 1000 linked files and keeps the first 10 files of each one's name, and up to 10 that are the same file; it ends once every linked file has its same file, and searches only the folders text.findFontFiles may search, with the same maxSeconds, depth and count limits; none on the web → {id (absent while idle), state: idle|searching|done|stopped|failed, folder?, links: [{name, path, ids, files: [{path, size, match: same|size|name, caseDiffers?: true}]}], searched?: {folders, files, read}, skipped?, unreadable?, stopped?: stop|time|limit, error?, seconds?}",
"{folder?: an absolute path, ids?: [image or placed document ids] (default: the active document's missing links), maxSeconds?: 60 (1 to 600), stop?: false (true: stop the last search)} with folder: look in it and its subfolders, on separate threads, for files with the names of the linked files (in any letter case), and answer at once with the search's state (searching while it runs); without folder: the last search's state, with the files found so far. Each linked file's files come best first: same (the size and hash saved with the link), size (the saved size, where there is no saved hash or the file is larger than 1 GiB), then name. Within each kind, a file whose name has the link's letter case comes first. Then each file's folder names are compared with the saved path's, from the innermost outward up to the first one that differs, and a file with more matching names comes first; files that still tie are listed by path. Before the comparison, the saved path's parent-folder steps (.., or the empty components of a classic Mac :: run) are resolved, and . components in a slash path are skipped. A search looks for at most 1000 linked files and keeps the first 10 files of each one's name, and up to 10 that are the same file; it ends once every linked file has its same file, and searches only the folders text.findFontFiles may search, with the same maxSeconds, depth and count limits; none on the web → {id (absent while idle), state: idle|searching|done|stopped|failed, folder?, links: [{name, path, ids, files: [{path, size, match: same|size|name, caseDiffers?: true}]}], searched?: {folders, files, read}, skipped?, unreadable?, stopped?: stop|time|limit, error?, seconds?}",
always,
find
)]
@@ -176,10 +176,29 @@ fn find(s: &mut Session, p: &Value) -> Result<Value> {
}
/// How many folder names the file at `found` has in common with the saved path `saved` (whichever
/// system's separators it uses), counted from the innermost out up to the first that differs,
/// compared in lowercase.
/// system's separators it uses, [`vectorcraft_doc::links::path_separators`]), counted from the
/// innermost out up to the first that differs, compared in lowercase. The saved path's parent
/// components are resolved first: `..` in a `/` or `\` path, and each colon after the first in a
/// run of colons in a classic Mac OS path (`Disk:Projects:Art::photo.png` is in `Projects`).
fn shared_folders(saved: &str, found: &Path) -> usize {
let saved = saved.rsplit(['/', '\\']).skip(1).filter(|c| !c.is_empty());
let separators = vectorcraft_doc::links::path_separators(saved);
let classic = separators == [':'];
let mut up = 0usize;
let saved = saved.rsplit(separators).skip(1).filter(move |c| {
let parent = if classic { c.is_empty() } else { *c == ".." };
if parent {
up += 1;
return false;
}
if c.is_empty() || *c == "." && !classic {
return false;
}
if up > 0 {
up -= 1;
return false;
}
true
});
let found = found.parent().into_iter().flat_map(|p| p.components().rev()).map_while(|c| match c {
Component::Normal(n) => n.to_str(),
_ => None,
+2 -3
View File
@@ -1110,7 +1110,7 @@ fn linked_param(st: &crate::DocState, p: &Value, cmd: &str) -> Result<NodeId> {
/// Per linked image in the layers of `st`: its file's status, where it was found when away from
/// its path, and whether the image shows its preview (each file probed once).
fn statuses(st: &crate::DocState) -> BTreeMap<NodeId, (Status, Option<String>, bool)> {
pub(crate) fn statuses(st: &crate::DocState) -> BTreeMap<NodeId, (Status, Option<String>, bool)> {
let mut out = BTreeMap::new();
for g in groups(&st.doc, None).iter().filter(|g| !g.ids.is_empty()) {
let (status, found) = probe(g, st.path.as_deref());
@@ -1349,12 +1349,11 @@ fn file_fields_here(st: &crate::DocState, id: NodeId, l: &LinkInfo, out: &mut Va
let doc_path = st.path.as_deref();
let path = fileio::document_path(&l.path, doc_path).ok();
let stamp = path.as_deref().and_then(file_stamp);
let folder_len = l.path.len().saturating_sub(l.name().len());
out["status"] = json!(status.as_str());
note_refused(out, l, doc_path);
out["path"] = json!(l.path);
out["fileName"] = json!(l.name());
out["location"] = json!(l.path.get(..folder_len).unwrap_or_default().trim_end_matches(['/', '\\']));
out["location"] = json!(l.folder());
for (k, v) in [
("page", l.page.map(u64::from)),
("fileSize", stamp.map(|s| s.0).or(l.size)),
+24 -3
View File
@@ -1,3 +1,5 @@
use std::collections::BTreeSet;
use super::common::{
DEFAULT_DISTANCE, DEFAULT_STEPS, ease_param, fix_ids, ids_json, is_blend, orientation_param, percent_param, roots_param, selected_of,
spacing_param, starts_param, wrap,
@@ -180,6 +182,17 @@ fn finite_point(p: &Value, cmd: &str) -> Result<Point> {
if q.x.is_finite() && q.y.is_finite() && q.x.abs() < 1e9 && q.y.abs() < 1e9 { Ok(q) } else { Err(bad(cmd, "x and y must be finite")) }
}
/// Most spine points `with` names.
const MAX_SPINE_POINTS: usize = 10_000;
/// The optional `with` list of spine point indexes (empty when absent).
fn spine_points_param(p: &Value, cmd: &str) -> Result<Vec<usize>> {
let Some(v) = p.get("with").filter(|v| !v.is_null()) else { return Ok(vec![]) };
let wrong = || bad(cmd, "`with` must be a list of at most 10000 spine point indexes");
let list = v.as_array().filter(|l| l.len() <= MAX_SPINE_POINTS).ok_or_else(wrong)?;
list.iter().map(|i| i.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or_else(wrong)).collect()
}
pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "object.blend.spine.moveAnchor";
let index = index_param(p, "anchor", C)?;
@@ -191,6 +204,10 @@ pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
Some(_) => return Err(bad(C, "handle must be in or out")),
};
let independent = switch_or(p, "independent", false, C)?;
let with = spine_points_param(p, C)?;
if handle.is_some() && !with.is_empty() {
return Err(bad(C, "`with` moves points, not a handle"));
}
edit_spine(s, p, C, "Reshape Spine", |sp, anchors, keys| {
let a = sp.anchors.get_mut(index).ok_or_else(|| bad(C, "no such spine point"))?;
if let Some(out) = handle {
@@ -198,9 +215,13 @@ pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
return Ok(());
}
let delta = q - a.p;
a.translate(delta);
// The key objects on the point move with it.
for (k, _) in anchors.iter().enumerate().filter(|(_, a)| **a == index) {
// The other points selected with it (#5285) move as far.
let moved: BTreeSet<usize> = with.iter().copied().chain([index]).collect();
for &i in &moved {
sp.anchors.get_mut(i).ok_or_else(|| bad(C, "no such spine point"))?.translate(delta);
}
// The key objects on the points move with them.
for (k, _) in anchors.iter().enumerate().filter(|(_, a)| moved.contains(*a)) {
if let Some(key) = keys.get_mut(k) {
Arc::make_mut(key).transform(Affine::translate(delta), false);
}
+1 -1
View File
@@ -81,7 +81,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Spine Point",
[],
None,
"{id? (default: the selected blend), anchor: index, x, y, handle?: in|out, independent?: bool} move a point of the blend's spine (its handles along), or with `handle` place that handle's end at (x, y) (a smooth point keeps the other handle in line unless `independent`). A key object sitting on the point moves with it. The first edit turns the straight spine into a path",
"{id? (default: the selected blend), anchor: index, x, y, with?: [index…], handle?: in|out, independent?: bool} move a point of the blend's spine (its handles along), and the points `with` names by as much, or with `handle` place that handle's end at (x, y) (a smooth point keeps the other handle in line unless `independent`). A key object sitting on a moved point moves with it. The first edit turns the straight spine into a path",
has_doc,
spine_move_anchor
),
+1 -1
View File
@@ -732,7 +732,7 @@ pub(crate) fn picked_mesh_points_of(s: &Session, ids: &[NodeId]) -> Option<Vec<(
}
/// A type run's stroke; a painted stroke on a run without one gets 1 pt.
fn set_run_stroke(style: &mut CharStyle, paint: Paint) {
pub(super) fn set_run_stroke(style: &mut CharStyle, paint: Paint) {
if !paint.is_none() {
run_stroke_weight(style);
}
+23 -6
View File
@@ -52,7 +52,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Convert to Text",
[],
None,
"{ids?|id?, start?: byte, end?: byte} (Type › Bullets and Numbering › Convert to Text: the paragraphs of the selected type, or of `ids`, or those a start/end range touches) the marker of each list paragraph becomes characters of its text: the bullet, or the number and its period as the paragraph showed it, then a tab, at the start of the paragraph in the marker's font, size and color; the list is turned off. When the marker's tab went to the left indent, the paragraph gets a left-aligned tab stop without a leader there, in place of any stop there, which keeps the text after the tab where it started; when it went to a tab stop and a stop there or past it has a leader or is not left-aligned, or a right, center or decimal stop lies between the marker and that place, the paragraph gets a left-aligned stop without a leader where the marker's tab ended, in place of any stop there and of those right, center and decimal stops before it (past the left indent only in a paragraph with no tab of its own). In threaded type the numbers are those counted through the story's frames, and a paragraph that continues into a later frame is converted where its text starts. An empty list paragraph has no marker and only leaves the list. A paragraph with no direction set gets the direction it ran in when the characters would change it (a letter or roman numeral before right-to-left text). With the Every-line Composer, a paragraph with a tab is broken line by line, so a converted paragraph can break its lines at other places. While the Type tool edits, its typing ends first and its anchor and caret move past the characters inserted at or before them; in threaded type, when the caret's character moved to another frame, the tool edits that frame, which becomes the selection when it was not selected. One undo step → {ids, converted: paragraphs, inserted: [{id, at: byte before the change, length: bytes}]}",
"{ids?|id?, start?: byte, end?: byte} (Type › Bullets and Numbering › Convert to Text: the paragraphs of the selected type, or of `ids`, or those a start/end range touches; after Select All in a frame of threaded text, without `ids`, `id` or a range, every paragraph of the story's frames that are neither locked nor hidden; while the story is selected, its locked and hidden frames are not converted even when named, nor a paragraph whose text starts in one) the marker of each list paragraph becomes characters of its text: the bullet, or the number and its period as the paragraph showed it, then a tab, at the start of the paragraph in the marker's font, size and color; the list is turned off. When the marker's tab went to the left indent, the paragraph gets a left-aligned tab stop without a leader there, in place of any stop there, which keeps the text after the tab where it started; when it went to a tab stop and a stop there or past it has a leader or is not left-aligned, or a right, center or decimal stop lies between the marker and that place, the paragraph gets a left-aligned stop without a leader where the marker's tab ended, in place of any stop there and of those right, center and decimal stops before it (past the left indent only in a paragraph with no tab of its own). In threaded type the numbers are those counted through the story's frames, and a paragraph that continues into a later frame is converted where its text starts. An empty list paragraph has no marker and only leaves the list. A paragraph with no direction set gets the direction it ran in when the characters would change it (a letter or roman numeral before right-to-left text). With the Every-line Composer, a paragraph with a tab is broken line by line, so a converted paragraph can break its lines at other places. While the Type tool edits, its typing ends first and its anchor and caret move past the characters inserted at or before them (a whole story that Select All selected stays selected when the call converts all of it); in threaded type, when the caret's character moved to another frame, the tool edits that frame, which becomes the selection when it was not selected. One undo step → {ids, converted: paragraphs, inserted: [{id, at: byte before the change, length: bytes}]}",
has_doc,
convert_list_to_text
),
@@ -207,7 +207,7 @@ pub(crate) fn artboard_copy(s: &mut Session, p: &Value, cut: bool) -> Result<Val
}
let art = st.doc.paint_order(arts.into_iter().flat_map(|(_, a)| a));
let boards: Vec<_> = indices.iter().filter_map(|i| st.doc.artboards.get(*i).cloned()).collect();
let clip = Clipboard { source_artboard: boards.first().map(|a| a.rect), artboards: boards, ..Clipboard::copy(st, &art) };
let clip = Clipboard { source_artboard: boards.first().map(|a| a.rect), artboards: boards, ..Clipboard::copy(st, &art, false) };
let copied = clip.nodes.len();
if cut {
s.edit("Cut Artboard", |d, sel| {
@@ -876,8 +876,23 @@ fn move_editing_selection(
fn convert_list_to_text(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "text.convertListToText";
use vectorcraft_doc::text::ParaList;
let ids = super::typecmd::text_targets(s, p, C)?;
let range = super::typecmd::TextRange::parse(p, C)?;
// After Select All in a frame of threaded text, a call that names no type and no range takes
// every paragraph of the story's editable frames; its locked and hidden frames stay as they are
// whichever way they are named.
let full = super::textedit::editing_story(s);
let story: Vec<NodeId> = full.iter().copied().filter(|f| s.doc().is_ok_and(|st| st.doc.is_editable(*f))).collect();
let named = ["ids", "id"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null()));
let ids = if !story.is_empty() && !named && range.is_none() {
story.clone()
} else {
super::typecmd::text_targets(s, p, C)?.into_iter().filter(|id| !full.contains(id) || story.contains(id)).collect()
};
// The selected story's locked and hidden frames: no paragraph whose text starts in one is
// converted, and none of their paragraphs is restyled.
let held: Vec<NodeId> = full.iter().copied().filter(|f| !story.contains(f)).collect();
// Converting the whole story leaves it selected.
let whole_story = !story.is_empty() && range.is_none() && story.iter().all(|f| ids.contains(f));
let editing = match super::textedit::editing_range(s)? {
Some((id, _, _)) => {
let options = s.tool_options();
@@ -909,6 +924,7 @@ fn convert_list_to_text(s: &mut Session, p: &Value) -> Result<Value> {
let mut converted = 0;
for story in &stories {
let frames: Vec<&vectorcraft_doc::TextObject> = story.iter().filter_map(|id| text(*id)).collect();
let is_held = |f: usize| story.get(f).is_some_and(|id| held.contains(id));
let mut paras: Vec<StoryParagraph> = vec![];
let mut named_parts = vec![];
let plains: Vec<String> = frames.iter().map(|t| t.plain_text()).collect();
@@ -934,7 +950,7 @@ fn convert_list_to_text(s: &mut Session, p: &Value) -> Result<Value> {
}
for (i, named) in named_parts {
if let Some(para) = paras.get_mut(i) {
let listed = para.main_part().is_some_and(|p| p.list.is_some());
let listed = para.main_part().is_some_and(|p| p.list.is_some() && !is_held(p.frame));
para.converts |= named && listed;
}
}
@@ -1021,7 +1037,7 @@ fn convert_list_to_text(s: &mut Session, p: &Value) -> Result<Value> {
let tab = vectorcraft_doc::TabStop { position: x, align: vectorcraft_doc::TabAlign::Left, leader: String::new(), align_on: '.' };
style.tabs.insert(i, tab);
}
for part in story_para.parts.iter().filter(|q| std::ptr::eq(*q, para) || q.bytes.is_empty()) {
for part in story_para.parts.iter().filter(|q| (std::ptr::eq(*q, para) || q.bytes.is_empty()) && !is_held(q.frame)) {
if let Some((stops, _)) = frame_edits.get_mut(part.frame) {
stops.push((part.index, style.clone()));
}
@@ -1058,7 +1074,8 @@ fn convert_list_to_text(s: &mut Session, p: &Value) -> Result<Value> {
}
Ok(())
})?;
if let Some(editing) = editing {
// A whole story selected by Select All stays selected, with the characters inserted.
if let Some(editing) = editing.filter(|_| !whole_story) {
move_editing_selection(s, editing, &story_before, &insertions)?;
}
}
+6 -6
View File
@@ -10,8 +10,8 @@ use super::create::anchor_from_json;
use super::draw2::usize_opt;
use super::pathops::Beside;
use super::{
CommandSpec, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, f64_req, finite_numbers, has_anchors, has_doc, has_selection,
id_param, ids_param, index, number_or, ok, str_param, switch_or, targets,
CommandSpec, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, f64_req, finite_numbers, has_anchors, has_doc, has_selected_path,
has_selection, id_param, ids_param, index, number_or, ok, str_param, switch_or, targets,
};
use crate::EngineError;
@@ -77,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> {
["Object", "Path"],
None,
"{ids?|id?, subpath?: usize (reverse only this subpath of each path, 0 included; default: every subpath), reversed?: bool (true: every subpath runs counter-clockwise on screen, false: clockwise, the Attributes panel's Reverse Path Direction On / Off; omitted: flip each path; with subpath, the direction is not read: that subpath is flipped)} the paths in ids or the selection (groups and compound paths: the paths inside), as one undo step → {changed: paths}",
has_doc,
has_selected_path,
reverse
),
cmd!(
@@ -86,7 +86,7 @@ pub fn specs() -> Vec<CommandSpec> {
["Object", "Path"],
Some("Cmd+J"),
"{ids?: [path, ...] (default: the selected paths; a compound path ID expands to its open member paths), subpaths?: [usize, usize] (which subpaths to join), ends?: [\"first\"|\"last\", \"first\"|\"last\"] (which end of each path to join, for two paths/subpaths; default without ids: direct-selected ends if any, else the nearest pair; default with ids: the nearest pair), to?: \"corner\"|\"smooth\" (the joined anchor: corner retracts both handles, smooth pulls handles in line with the neighbours)} join two or more open paths/subpaths into one (the first keeps its id, selected), or close a single open path; without ids, direct-selected anchors lying on one another along a path merge into one anchor instead",
has_selection,
has_selected_path,
join
),
cmd!(
@@ -95,7 +95,7 @@ pub fn specs() -> Vec<CommandSpec> {
["Object", "Path"],
Some("Cmd+Alt+J"),
"{axis?: \"horizontal\"|\"vertical\"|\"both\"}",
has_selection,
has_selected_path,
average
),
cmd!(
@@ -104,7 +104,7 @@ pub fn specs() -> Vec<CommandSpec> {
["Object", "Path"],
Some("Cmd+Alt+Shift+J"),
"{to: \"corner\"|\"smooth\" (the joined anchor: corner retracts both handles, smooth pulls handles in line with the neighbours), ids?: [path, ...] (default: the selection; a compound path ID expands to its open member paths)} move two open path ends to their midpoint and join them there, as one undo step: the two direct-selected anchors when they are open path ends, else the nearest ends of the two open paths in ids or the selection (or both ends of one open path, closing it) → the joined path stays selected",
has_selection,
has_selected_path,
average_join
),
cmd!(
+17 -8
View File
@@ -15,8 +15,8 @@ use vectorcraft_pathops::{BoolOp, PathfinderOp};
use super::edit::selected_roots;
use super::{
CommandSpec, EngineError, Result, Session, always, bad, bool_or, checked_ids_or_selection, cmd, has_doc, has_selection, number_or, str_param,
switch_or,
CommandSpec, EngineError, Result, Session, always, bad, bool_or, checked_ids_or_selection, cmd, has_doc, has_selected_path, has_selection,
number_or, str_param, switch_or,
};
pub fn specs() -> Vec<CommandSpec> {
@@ -153,7 +153,7 @@ pub fn specs() -> Vec<CommandSpec> {
["Object", "Path"],
None,
"{tolerance?: pt (1), level?: 0..100 (the Simplify slider, in place of tolerance: 0 fewest anchor points, 50 is 1 pt, every 10 levels halves or doubles it), auto?: bool (Auto-Simplify: the lowest level whose tolerance is at most 1/400 of the selection's longer side, or 100 when that side is under 12.5 pt), cornerAngle?: deg (30), straightLines?: bool, wholePaths?: bool (false: a path with segments direct-selected, or between direct-selected anchors, simplifies only each run of them between its end anchors, which stay as they are, and keeps the runs selected; true simplifies those paths whole)} → {ids, before, after} anchor counts, and the level used with level or auto",
has_selection,
has_selected_path,
simplify
),
cmd!(
@@ -162,17 +162,17 @@ pub fn specs() -> Vec<CommandSpec> {
["Object", "Path"],
None,
"{level?: 0..100 (50; the Smooth slider: 0 minimum smoothing, the path staying within 0.1% of its longer side, 100 maximum: smoothed along its length by up to 5% of it and refitted with curves within up to 2.5% of it, corners kept only where the path turns back, never with more anchor points), auto?: bool (Auto-Smooth: level 50), ids?: [id…] (default: the selection)} smooth each path under the objects, compound path members included, as one undo step; without ids, a path with anchor points or segments direct-selected smooths only the sections between them, which stay selected → {ids, before, after} anchor counts, and the level used",
has_selection,
has_selected_path,
smooth
),
cmd!("object.path.addAnchorPoints", "Add Anchor Points", ["Object", "Path"], None, "{} → {ids}", has_selection, add_anchor_points),
cmd!("object.path.addAnchorPoints", "Add Anchor Points", ["Object", "Path"], None, "{} → {ids}", has_selected_path, add_anchor_points),
cmd!(
"object.path.divideObjectsBelow",
"Divide Objects Below",
["Object", "Path"],
None,
"{} cut the objects below with the selected path (which is removed) → {ids}",
has_selection,
has_selected_path,
divide_objects_below
),
cmd!(
@@ -181,7 +181,7 @@ pub fn specs() -> Vec<CommandSpec> {
["Object", "Path"],
None,
"{rows?: 2, columns?: 2, gutter?: pt (12; rowGutter?, columnGutter?: one of the two), totalHeight?, totalWidth?: pt (the grid's size; the selected paths' when left out), height?, width?: pt (each row's and column's size, which then sets the total), addGuides?: false (ruler guides along the row and column edges)} one grid of rectangles over the selected paths replaces them, painted as the topmost one → {ids, guides: count}",
has_selection,
has_selected_path,
split_into_grid
),
cmd!(
@@ -770,7 +770,14 @@ fn offset_path(s: &mut Session, p: &Value) -> Result<Value> {
let Some((path, rule)) = node_path(l) else { continue };
paths = true;
let base = if matches!(l.kind, NodeKind::Compound { .. }) && path.is_closed() { po::normalize(&path, rule) } else { path };
let off = po::offset_path(&base, delta, join, miter);
let off = match po::try_offset_path(&base, delta, join, miter) {
Ok(p) => p,
Err(po::PathOpsError::NonFinite) => continue,
Err(po::PathOpsError::TooComplex) => {
return Err(EngineError::Other("Offset Path: the path is too complex to offset".into()));
}
Err(e) => return Err(EngineError::Other(format!("Offset Path: {e}"))),
};
if off.is_empty() {
continue;
}
@@ -890,6 +897,8 @@ pub(crate) fn outline_strokes(d: &mut Document, brushes: &[vectorcraft_brush::Br
return None;
}
let (path, rule) = node_path(l)?;
// A fill belongs to the source path, whether open or closed. Converting its stroke
// preserves that fill on a separate copy (including compound member geometry).
let mut parts: Vec<Node> = vec![];
let mut fills: Vec<AppearanceItem> = vec![];
for item in &l.appearance.items {
+51 -12
View File
@@ -452,27 +452,66 @@ impl DocState {
pub fn current_layer(&self) -> Option<NodeId> {
self.active_layer.filter(|l| self.doc.node(*l).is_some_and(|n| n.is_layer()))
}
/// Where new art is inserted: the isolation container (or its parent if the container cannot hold
/// the art type), else the active layer.
pub fn insertion_parent(&self) -> Option<NodeId> {
// Ids are reused after undo (the id counter is part of the document), so a remembered
// layer or isolated group must still be one: a pasted group must never land in a path.
if let Some(i) = self.isolation
&& self.doc.node(i).is_some_and(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }))
{
return Some(i);
self.insertion_parent_for(false)
}
/// Where new path art is inserted. When a compound path is isolated, returns the compound path
/// so new paths become members of the compound path.
pub fn insertion_parent_for_path(&self) -> Option<NodeId> {
self.insertion_parent_for(true)
}
fn insertion_parent_for(&self, for_path: bool) -> Option<NodeId> {
if let Some(i) = self.isolation {
if self.doc.node(i).is_some_and(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. })) {
return Some(i);
}
if for_path && self.doc.node(i).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })) {
return Some(i);
}
}
// A single object isolated: new art goes beside it, in its group or layer.
if let Some(p) = self.isolation.filter(|i| self.doc.node(*i).is_some_and(|n| !n.is_container())).and_then(|i| self.doc.parent_of(i))
&& self.doc.node(p).is_some_and(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }))
{
return Some(p);
if let Some(p) = self.isolation.filter(|i| self.doc.node(*i).is_some_and(|n| !n.is_container())).and_then(|i| self.doc.parent_of(i)) {
if self.doc.node(p).is_some_and(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. })) {
return Some(p);
}
if for_path && self.doc.node(p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })) {
return Some(p);
}
}
// Non-path art created while a compound path is isolated goes into the compound's parent container:
if let Some(iso) = self.isolation {
let compound = if self.doc.node(iso).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })) {
Some(iso)
} else {
self.doc.parent_of(iso).filter(|p| self.doc.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })))
};
if let Some(c) = compound
&& let Some(p) = self.doc.parent_of(c)
&& self.doc.is_editable(p)
{
return Some(p);
}
}
// A sublayer takes new art only while it and the layers around it are shown and unlocked.
self.active_layer.filter(|l| self.doc.node(*l).is_some_and(|n| n.is_layer()) && self.doc.is_editable(*l)).or_else(|| self.doc.default_layer())
}
/// [`Self::insertion_parent`] for new art, which a locked or hidden layer never takes: an error
/// when no layer is shown and unlocked, so the art is refused rather than hidden or locked away.
pub fn target_parent(&self) -> Result<Option<NodeId>> {
match self.insertion_parent() {
self.target_parent_for(false)
}
/// [`Self::insertion_parent_for_path`] for new path art.
pub fn target_parent_for_path(&self) -> Result<Option<NodeId>> {
self.target_parent_for(true)
}
fn target_parent_for(&self, for_path: bool) -> Result<Option<NodeId>> {
match self.insertion_parent_for(for_path) {
Some(p) if !self.doc.is_editable(p) => Err(EngineError::Other("the target layer is locked or hidden".into())),
parent => Ok(parent),
}
+1
View File
@@ -109,6 +109,7 @@ mod paintproxy;
mod panelcmds;
mod paragraphs;
mod params;
mod path_menu_enabled;
mod pathops;
mod pathtype;
mod pattern;
+28
View File
@@ -66,6 +66,34 @@ fn a_spine_point_added_and_moved_bends_the_blend() {
assert!(center(&steps(&s, g)[1]).distance(Point::new(55.0, 5.0)) < 1e-6);
}
/// #5285: `with` moves other spine points by as much as the one dragged, and the key objects on
/// them along, in one undo step; it can't go with a handle or name a point the spine lacks.
#[test]
fn spine_points_move_together() {
let mut s = session();
let (a, b, g) = blend(&mut s);
s.execute("object.blend.spine.addAnchor", &json!({"x": 55, "y": 5})).unwrap();
let before = spec(&s, g);
assert!(s.execute("object.blend.spine.moveAnchor", &json!({"anchor": 1, "x": 55, "y": 45, "with": [9]})).is_err());
assert!(s.execute("object.blend.spine.moveAnchor", &json!({"anchor": 1, "x": 55, "y": 45, "with": [2], "handle": "in"})).is_err());
assert!(s.execute("object.blend.spine.moveAnchor", &json!({"anchor": 1, "x": 55, "y": 45, "with": "2"})).is_err());
assert_eq!(spec(&s, g), before, "refused requests change nothing");
s.execute("object.blend.spine.moveAnchor", &json!({"anchor": 1, "x": 55, "y": 45, "with": [2, 1]})).unwrap();
let sp = spec(&s, g).spine.unwrap();
let pts: Vec<Point> = sp.subpaths[0].anchors.iter().map(|x| x.p).collect();
let want = [Point::new(5.0, 5.0), Point::new(55.0, 45.0), Point::new(105.0, 45.0)];
assert!(pts.len() == 3 && pts.iter().zip(want).all(|(p, w)| p.distance(w) < 1e-9), "{pts:?}");
let keys = match node(&s, g).kind {
NodeKind::Blend { children, .. } => children,
_ => panic!("not a blend"),
};
let at = |id: NodeId| keys.iter().find(|k| k.id == id).map(|k| center(k)).unwrap();
assert!(at(b).distance(Point::new(105.0, 45.0)) < 1e-9, "the key on the point went along: {:?}", at(b));
assert!(at(a).distance(Point::new(5.0, 5.0)) < 1e-9, "the other stayed: {:?}", at(a));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(spec(&s, g), before, "one undo step");
}
/// #2544: an Anchor Point drag on a blend spine must create two symmetric
/// handles, not bend the adjacent segment and leave one handle behind.
#[test]
+33
View File
@@ -830,6 +830,39 @@ fn shape_builder_drag_from_a_merged_shape_over_a_line_under_its_edge_makes_one_r
assert!(left_half_gone(&s, h));
}
#[test]
fn shape_builder_removes_the_stretch_of_every_line_under_a_merged_edge() {
// Two lines along the same stretch, under the bottom edge of the merged top row: merging the
// row with the cell below takes the stretch between them from both lines.
for erase in [false, true] {
let mut s = session();
let h1 = line(&mut s, (100.0, 200.0), (300.0, 200.0));
let h2 = line(&mut s, (100.0, 200.0), (300.0, 200.0));
let v = line(&mut s, (200.0, 100.0), (200.0, 300.0));
let sq = rect(&mut s, 100.0, 100.0, 200.0, 200.0);
s.edit("t", |d, _| {
for id in [h1, h2, v, sq] {
d.node_mut(id).unwrap().appearance.set_fill(Paint::None);
}
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [h1.0, h2.0, v.0, sq.0]})).unwrap();
s.execute("shapeBuilder.merge", &json!({"points": [[150, 150], [250, 150]]})).unwrap();
s.execute("shapeBuilder.merge", &json!({"points": [[250, 150], [150, 250]], "erase": erase})).unwrap();
let d = &s.doc().unwrap().doc;
let left: Vec<Rect> = d
.children(d.default_layer())
.into_iter()
.flatten()
.filter(|n| !outline(n).0.is_closed())
.filter_map(|n| n.geometric_bounds())
.filter(|b| b.height() < 1e-6 && (b.y0 - 200.0).abs() < 1e-6 && b.x0 < 199.0)
.collect();
assert!(left.is_empty(), "erase {erase}: {left:?}");
}
}
#[test]
fn shape_builder_alt_deletes_a_region_or_a_line_piece() {
let mut s = session();
+21
View File
@@ -411,6 +411,27 @@ fn eps_export_still_flattens_a_colorize_paint_on_a_color_image() {
assert!(out["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("transparency is flattened")), "{}", out["warnings"]);
}
/// A linked image showing the missing-link placeholder draws uncolorized, so its colorize paint
/// doesn't flatten it in EPS or PDF 1.3 export.
#[test]
fn a_colorized_missing_link_placeholder_is_not_flattened() {
let mut s = session();
let bytes = std::sync::Arc::new(vectorcraft_doc::links::missing_placeholder().unwrap());
let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) });
s.edit("Colorize", |d, _| {
d.node_mut(id).unwrap().extras_mut().colorize = Some(Box::new(Paint::solid(Color::rgb8(255, 0, 0))));
Ok(())
})
.unwrap();
let flattened =
|out: &serde_json::Value| out["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("transparency is flattened"));
let eps = s.execute("document.exportEps", &json!({"previewFormat": "none", "useArtboards": false})).unwrap();
assert!(!flattened(&eps), "{}", eps["warnings"]);
let pdf = s.execute("document.exportPdf", &json!({"compatibility": "1.3"})).unwrap();
assert!(!flattened(&pdf), "{}", pdf["warnings"]);
assert_eq!(colorize(&s, id), Some(Paint::solid(Color::rgb8(255, 0, 0))), "the image keeps its paint");
}
#[test]
fn flattened_colorized_image_shows_the_art_under_white_pixels() {
let mut s = session();
+89 -4
View File
@@ -386,10 +386,11 @@ fn pencil_redraws_the_shorter_way_round_a_closed_path() {
assert!(s.execute("path.freehand", &json!({"points": [[0, 0], [1, 1]], "redraw": {"id": id.0, "within": -1}})).is_err());
}
/// With Keep selected off, the path a stroke draws or continues is not selected afterwards, the
/// rest of the selection stays, and the stroke is one undo step.
/// With Keep selected off, a new stroke leaves nothing selected (the earlier selection goes too,
/// as Illustrator starts the stroke by dropping it, #5752); a continued or redrawn path is
/// deselected and the rest of the selection stays. The stroke is one undo step.
#[test]
fn pencil_with_keep_selected_off_leaves_the_new_path_unselected() {
fn pencil_with_keep_selected_off_leaves_nothing_selected() {
let mut s = session();
let r = rect(&mut s, 400.0, 400.0, 50.0, 50.0);
let selected = |s: &Session| s.doc().unwrap().selection.objects.clone();
@@ -401,7 +402,7 @@ fn pencil_with_keep_selected_off_leaves_the_new_path_unselected() {
let off = s.execute("path.freehand", &json!({"points": [[100, 200], [150, 220], [200, 200]], "keepSelected": false})).unwrap();
let off = NodeId(off["id"].as_u64().unwrap());
assert!(s.doc().unwrap().doc.node(off).is_some());
assert_eq!(selected(&s), vec![r]);
assert!(selected(&s).is_empty(), "a new stroke with Keep selected off leaves nothing selected, the rectangle included");
assert_eq!(undo_steps(&s), undo + 1);
// Continuing a selected open path deselects it and keeps the rest.
let l = line(&mut s, 100.0, 300.0, 200.0, 300.0);
@@ -1342,6 +1343,54 @@ fn join_tool_joins_endpoints_near_the_scrub_ends() {
assert_eq!(p.subpaths[0].anchors[1].p, Point::new(202.5, 100.0));
}
/// #5844: scrubbing over the ends of two crossing open paths that run past the crossing trims
/// those ends and joins the paths there with a corner, rather than drawing a segment between the
/// ends.
#[test]
fn join_tool_trims_crossing_paths_and_joins_them_at_the_crossing() {
let mut s = session();
let a = line(&mut s, 100.0, 300.0, 400.0, 300.0);
let b = line(&mut s, 300.0, 100.0, 300.0, 380.0);
s.execute("select.all", &json!({})).unwrap();
drag(&mut s, "join", &[(380.0, 285.0), (285.0, 365.0)], Mods::default());
let ps = paths(&s);
assert_eq!(ps.len(), 1, "one path is left: {ps:?}");
let (id, p) = &ps[0];
assert!(*id == a || *id == b);
assert_eq!(p.subpaths.len(), 1);
let mut got: Vec<Point> = p.subpaths[0].anchors.iter().map(|x| x.p).collect();
if got.first() != Some(&Point::new(100.0, 300.0)) {
got.reverse();
}
let near = |q: Point, r: Point| q.distance(r) < 1e-6;
assert_eq!(got.len(), 3, "{got:?}");
assert!(near(got[0], Point::new(100.0, 300.0)) && near(got[1], Point::new(300.0, 300.0)) && near(got[2], Point::new(300.0, 100.0)), "{got:?}");
assert!(!p.subpaths[0].closed);
assert_eq!(s.doc().unwrap().selection.objects.len(), 1);
}
/// #5844: a curve with a hook past a straight line (the report's case) is trimmed at the crossing
/// and joined to the line's kept part; nothing of either overhang is left.
#[test]
fn join_tool_trims_a_curve_hooking_past_a_line() {
let mut s = session();
line(&mut s, 0.0, 300.0, 480.0, 300.0);
s.execute("path.create", &json!({"anchors": [{"x": 260, "y": 0, "out": [290, 150]}, {"x": 378, "y": 368, "in": [310, 380]}]})).unwrap();
s.execute("select.all", &json!({})).unwrap();
drag(&mut s, "join", &[(470.0, 280.0), (420.0, 330.0), (370.0, 380.0)], Mods::default());
let ps = paths(&s);
assert_eq!(ps.len(), 1, "{ps:?}");
let sp = &ps[0].1.subpaths[0];
assert!(!sp.closed);
// Every anchor is on the kept sides: the line left of the crossing, the curve above it.
let joint = sp.anchors.iter().find(|x| (x.p.y - 300.0).abs() < 1e-6 && x.p.x > 100.0).expect("an anchor at the crossing");
for x in &sp.anchors {
assert!(x.p.y <= 300.0 + 1e-6 && x.p.x <= joint.p.x + 1e-6, "{x:?} is past the crossing at {joint:?}");
}
let bounds = ps[0].1.bounds().unwrap();
assert!(bounds.y1 <= 300.0 + 1e-6 && bounds.x1 <= joint.p.x + 1e-6, "{bounds:?}");
}
#[test]
fn line_family_tools_draw_and_click_asks_dialog() {
let mut s = session();
@@ -2708,6 +2757,42 @@ fn cmd_alt_lends_group_selection_while_direct_selection_is_active() {
s.pointer(&PointerEvent::new(PointerKind::Up, 80.0, 80.0).with_mods(cmd_alt), v).unwrap();
}
#[test]
fn cmd_lends_the_selection_tool_and_its_bounding_box_to_direct_selection() {
// #3901: with Direct Selection, Cmd held gives the Selection tool for the press: its cursor,
// and its bounding box's handles scale the object; Direct Selection is back on the release.
let (none, cmd) = (Mods::default(), Mods { cmd: true, ..Mods::default() });
let v = view();
let mut s = session();
let anchors = json!([{"x": 100, "y": 100}, {"x": 200, "y": 100}, {"x": 200, "y": 200}, {"x": 100, "y": 200}]);
let id = NodeId(s.execute("path.create", &json!({"anchors": anchors, "closed": true})).unwrap()["id"].as_u64().unwrap());
s.select_tool("directSelection", v).unwrap();
assert_eq!(s.lent_tool_id(&none), None);
assert_eq!(s.lent_tool_id(&cmd), Some("selection"));
// The path selected whole: the bottom-right handle scales it.
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
assert_eq!(s.cursor(Point::new(200.0, 200.0), cmd, v), vectorcraft_tools::Cursor::ResizeNwSe);
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap();
assert_eq!(s.tool_id(), "selection");
for at in [250.0, 300.0] {
s.pointer(&PointerEvent::new(PointerKind::Drag, at, at).with_mods(cmd), v).unwrap();
}
s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 300.0).with_mods(cmd), v).unwrap();
assert_eq!(s.tool_id(), "directSelection");
let b = s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap();
assert!((b.x0 - 100.0).abs() < 1e-6 && (b.x1 - 300.0).abs() < 1e-6 && (b.y1 - 300.0).abs() < 1e-6, "{b:?}");
// An anchor selected: a Cmd drag inside moves the whole path and the anchor stays selected.
gesture(&mut s, &[(300.0, 300.0)], none);
let picked = s.doc().unwrap().selection.anchors.clone();
assert!(!picked.is_empty(), "Direct Selection picked the anchor");
let before: Vec<_> = path(&s, id).subpaths[0].anchors.iter().map(|a| a.p).collect();
gesture(&mut s, &[(150.0, 150.0), (160.0, 160.0), (170.0, 150.0)], cmd);
let after: Vec<_> = path(&s, id).subpaths[0].anchors.iter().map(|a| a.p).collect();
assert_eq!(after, before.iter().map(|p| *p + kurbo::Vec2::new(20.0, 0.0)).collect::<Vec<_>>());
assert_eq!(s.doc().unwrap().selection.anchors, picked, "the anchor is still selected");
assert_eq!(s.tool_id(), "directSelection");
}
#[test]
fn the_pen_drops_the_new_path_asterisk_once_a_path_is_started() {
// The Pen's asterisk means a click starts a new path: it shows until the first anchor is
+22
View File
@@ -82,6 +82,28 @@ fn clicking_an_overlap_brings_the_object_below_to_the_front_there_only() {
assert_eq!(hit(&s, 50.0, 70.0), Some(b));
}
/// #5337: where A is brought over B, the edges of B that cross A leave no blue hairline in A.
#[test]
fn the_object_brought_over_shows_no_seam_of_the_one_below() {
let mut s = session();
intertwined(&mut s);
arrange(&mut s, json!({"at": [50, 30]}));
let zoom = 8.0;
let r = vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 800, 800, Affine::scale(zoom), &Default::default());
let mut worst = 0;
for y in 160..360 {
for x in 320..480 {
let (px, py) = ((x as f64 + 0.5) / zoom, (y as f64 + 0.5) / zoom);
// Well inside ring A's 8 pt stroke (radius 21 to 29), A covers every pixel.
let d = ((px - 35.0).powi(2) + (py - 50.0).powi(2)).sqrt();
if (22.0..28.0).contains(&d) {
worst = worst.max(r.pixel(x, y)[2]);
}
}
}
assert!(worst < 8, "blue shows through ring A at the top crossing (blue {worst})");
}
#[test]
fn clicking_the_same_overlap_again_swaps_back() {
let mut s = session();
+63
View File
@@ -111,6 +111,69 @@ fn colours_come_from_the_selection_and_paint_it() {
assert!(s.execute("library.use", &json!({"library": lib, "kind": "fillColor", "item": "#nope"})).is_err());
}
/// The spot swatch of object `id`'s fill: its name, whether it is spot, the paint's tint.
fn spot_of(s: &Session, id: &Value) -> (String, bool, f32) {
match paint_of(s, id, false) {
vectorcraft_color::Paint::Solid { swatch: Some(name), tint, .. } => {
let spot = s.doc().unwrap().doc.swatch(&name).is_some_and(|w| w.spot);
(name, spot, tint)
}
other => panic!("not linked to a swatch: {other:?}"),
}
}
/// A spot colour added to a library keeps its ink, kept in the library's file: used in a new
/// document (or after its own was closed) it adds the spot swatch of that name and colour and
/// links the paint to it, at its tint; one the document has already is reused (#5812).
#[test]
fn a_spot_colour_stays_spot_in_another_document() {
let dir = std::env::temp_dir().join(format!("vc-libraries-spot-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let folder = dir.to_string_lossy().to_string();
let mut s = session();
s.libraries.set_dir(Some(folder.clone()));
let lib = run(&mut s, "library.create", json!({"name": "Inks"}))["id"].as_str().unwrap().to_string();
let ink = vectorcraft_color::Color::cmyk(0.0, 1.0, 0.0, 0.0);
run(&mut s, "swatch.new", json!({"name": "Kiss-cut", "color": ink, "spot": true}));
let a = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Kiss-cut", "ids": [a]}));
run(&mut s, "select.set", json!({"ids": [a]}));
assert_eq!(run(&mut s, "library.add", json!({"library": lib, "kind": "fillColor"}))["name"], "Kiss-cut");
// A swatch dropped on the panel: its colour with its spot swatch's name and tint.
let r = run(&mut s, "library.add", json!({"library": lib, "kind": "fillColor", "color": ink, "swatch": "Kiss-cut", "tint": 40, "name": "Light"}));
assert_eq!(r["existing"], false, "a tint is another colour");
// The same colour as a process colour is another item.
run(&mut s, "paint.setFill", json!({"color": ink, "ids": [a]}));
assert_eq!(run(&mut s, "library.add", json!({"library": lib, "kind": "fillColor"}))["existing"], false);
run(&mut s, "file.close", json!({}));
// Another session reads the library's file into a new document.
let mut t = session();
t.libraries.set_dir(Some(folder));
let got = run(&mut t, "library.get", json!({"library": "Inks"}));
assert_eq!(got["colors"][0]["spot"], "Kiss-cut");
assert_eq!(got["colors"][2]["spot"], Value::Null);
let b = run(&mut t, "shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20}))["id"].clone();
run(&mut t, "select.set", json!({"ids": [b]}));
run(&mut t, "library.use", json!({"library": "Inks", "kind": "fillColor", "item": "Kiss-cut"}));
assert_eq!(spot_of(&t, &b), ("Kiss-cut".to_string(), true, 1.0));
let doc = &t.doc().unwrap().doc;
assert_eq!(doc.swatch("Kiss-cut").unwrap().paint.color(), Some(ink), "the ink keeps its values");
assert!(doc.spot_names().contains(&"Kiss-cut".to_string()));
// Its tint links to the same swatch: none is added again.
let swatches = doc.swatches.len();
run(&mut t, "library.use", json!({"library": "Inks", "kind": "fillColor", "item": "Light"}));
let (name, spot, tint) = spot_of(&t, &b);
assert_eq!((name.as_str(), spot), ("Kiss-cut", true));
assert!((tint - 0.4).abs() < 1e-4, "{tint}");
assert_eq!(t.doc().unwrap().doc.swatches.len(), swatches);
// One undo step takes back the new swatch along with the paint.
run(&mut t, "edit.undo", json!({}));
run(&mut t, "edit.undo", json!({}));
assert!(t.doc().unwrap().doc.swatch("Kiss-cut").is_none());
let _ = std::fs::remove_dir_all(&dir);
}
/// The fill (`stroke`: stroke) paint of object `id`.
fn paint_of(s: &Session, id: &Value, stroke: bool) -> vectorcraft_color::Paint {
let n = s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().clone();
+61
View File
@@ -123,6 +123,67 @@ fn files_found_are_ranked_by_what_the_link_saved() {
assert_eq!(photo_row["path"], json!(root.join("orig/photo.png")));
}
/// A link saved as a classic Mac OS path (`Disk:Folder:file`) is looked for by its file name, and
/// the files found are ranked by the folder names they share with that path.
#[test]
fn a_classic_mac_path_is_found_by_its_name_and_folders() {
let root = folder("classic");
let mut s = session_for(&root);
let photo = png(50, 30, BLUE);
write(&root.join("orig/photo.png"), &photo);
let id = placed(&mut s, &root.join("orig/photo.png"));
s.edit("classic path", |d, _| {
if let NodeKind::Image(im) = &mut d.node_mut(NodeId(id)).unwrap().kind {
im.link.as_mut().unwrap().path = "Old Disk:Art:Images:photo.png".into();
}
Ok(())
})
.unwrap();
std::fs::remove_dir_all(root.join("orig")).unwrap();
// Other files of the name (a search ends once it finds the same file).
let search = root.join("search");
let mut changed = photo.clone();
*changed.last_mut().unwrap() ^= 1;
write(&search.join("a/photo.png"), &changed);
write(&search.join("z/Art/Images/photo.png"), &changed);
s.execute("links.findFiles", &json!({"folder": search})).unwrap();
let r = finished(&mut s);
assert_eq!(r["state"].as_str(), Some("done"), "{r}");
let files = [("search/z/Art/Images/photo.png", "name", false), ("search/a/photo.png", "name", false)];
assert_eq!(found(&r, "photo.png", &root), files.map(|(p, k, c)| (p.to_string(), k.to_string(), c)));
}
/// The folders a saved path shares with a file found are counted after its parent components are
/// resolved: `Art::` in a classic Mac OS path and `Art/..` in any other path go back to `Projects`.
#[test]
fn parent_components_in_a_saved_path_are_resolved_before_ranking() {
for (tag, saved) in [("classic-up", "Old Disk:Projects:Art::photo.png"), ("slash-up", "/old/Projects/Art/../photo.png")] {
let root = folder(tag);
let mut s = session_for(&root);
let photo = png(50, 30, BLUE);
write(&root.join("orig/photo.png"), &photo);
let id = placed(&mut s, &root.join("orig/photo.png"));
s.edit("saved path", |d, _| {
if let NodeKind::Image(im) = &mut d.node_mut(NodeId(id)).unwrap().kind {
im.link.as_mut().unwrap().path = saved.into();
}
Ok(())
})
.unwrap();
std::fs::remove_dir_all(root.join("orig")).unwrap();
let search = root.join("search");
let mut changed = photo.clone();
*changed.last_mut().unwrap() ^= 1;
write(&search.join("Art/photo.png"), &changed);
write(&search.join("Projects/photo.png"), &changed);
s.execute("links.findFiles", &json!({"folder": search})).unwrap();
let r = finished(&mut s);
assert_eq!(r["state"].as_str(), Some("done"), "{saved}: {r}");
let files = [("search/Projects/photo.png", "name", false), ("search/Art/photo.png", "name", false)];
assert_eq!(found(&r, "photo.png", &root), files.map(|(p, k, c)| (p.to_string(), k.to_string(), c)), "{saved}");
}
}
/// Without `ids`, a search looks for the files that can't be found; with them, for those objects'
/// files, whatever their status.
#[test]
+38
View File
@@ -283,6 +283,44 @@ fn a_missing_link_renders_its_preview_and_relinks() {
assert!(s.execute("links.relink", &json!({"ids": [id.0]})).is_err(), "path or folder");
}
/// A link stored as a classic Mac OS path (`Disk:Folder:file`, as older `.ai` files keep them) is
/// named by its last component: the Links panel shows that name and its folder, Relink to Folder
/// looks for that name, and the document's own folder is searched for it. The stored path is kept.
#[test]
fn a_classic_mac_path_is_found_by_its_file_name() {
const CLASSIC: &str = "Macintosh HD:Images:photo.png";
let dir = Folder::new("classic-mac");
let pic = dir.file("art/photo.png");
write(&pic, &png(600, 300, RED));
let mut s = session();
place(&mut s, &pic);
let mut v: Value = serde_json::from_slice(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
saved_image(&mut v)["link"] = json!({ "path": CLASSIC });
let doc_path = dir.file("poster.vectorcraft");
write(&doc_path, &serde_json::to_vec(&v).unwrap());
let r = open(&mut s, &doc_path);
let id = s.doc().unwrap().doc.layers[0].children().unwrap()[0].id;
assert_eq!(r["missingLinks"], json!([{"name": "photo.png", "path": CLASSIC, "ids": [id.0]}]));
let i = s.execute("links.info", &json!({"id": id.0})).unwrap();
assert_eq!(
(i["fileName"].as_str(), i["location"].as_str(), i["path"].as_str()),
(Some("photo.png"), Some("Macintosh HD:Images"), Some(CLASSIC)),
"{i}"
);
// Relink to Folder: the file of the link's name there.
let r = s.execute("links.relink", &json!({"ids": [id.0], "folder": dir.file("found")})).unwrap();
assert_eq!(r, json!({"relinked": [], "notFound": ["photo.png"]}));
write(&dir.file("found/photo.png"), &png(600, 300, BLUE));
let r = s.execute("links.relink", &json!({"ids": [id.0], "folder": dir.file("found")})).unwrap();
assert_eq!(r, json!({"relinked": [id.0], "notFound": []}));
assert!(near(centre_colour(&s.doc().unwrap().doc), BLUE));
// The document's folder: the file of the link's name beside the document.
write(&dir.file("photo.png"), &png(600, 300, RED));
let r = open(&mut s, &doc_path);
assert_eq!((r["missingLinks"].clone(), r["modifiedLinks"].clone()), (json!([]), json!([])), "{r}");
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
}
/// A `w`×`h` PNG of noise cut to half its length: its header reads, its pixels don't.
pub(crate) fn cut_png(w: u32, h: u32) -> Vec<u8> {
let img = image::RgbImage::from_fn(w, h, |x, y| {
+255
View File
@@ -414,3 +414,258 @@ fn a_group_shows_its_contents_in_the_proxies() {
s.execute("select.none", &json!({})).unwrap();
assert_eq!(s.proxy_paints().0, s.paint.fill);
}
/// The top fill and top stroke of object `id`.
fn paints(s: &Session, id: NodeId) -> (Paint, Paint, f64) {
let n = node(s, id);
(n.appearance.fill_paint(), n.appearance.stroke_paint(), n.appearance.stroke().map_or(0.0, |st| st.width))
}
/// Apply Fill to Stroke gives each selected object a stroke of its own fill, not the first
/// object's; Apply Stroke to Fill does the other way (#5530). A stroke that had no paint and no
/// width gets the 1 pt Swap Fill and Stroke gives it, and the paint copied from stays.
#[test]
fn each_object_copies_its_own_paint_onto_the_other() {
let mut s = session();
let (a, b) = (rect(&mut s), rect(&mut s));
for (id, hex) in [(a, "#ff0000"), (b, "#0080ff")] {
s.execute("paint.setFill", &json!({"ids": [id.0], "color": hex})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [id.0], "none": true})).unwrap();
s.execute("object.setStrokeWidth", &json!({"ids": [id.0], "width": 0})).ok();
}
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let r = s.execute("addon.color.fillToStroke", &json!({})).unwrap();
assert_eq!(r["objects"], 2);
for (id, hex) in [(a, "#ff0000"), (b, "#0080ff")] {
let (fill, stroke, width) = paints(&s, id);
assert_eq!(fill.color().unwrap().to_hex(), hex, "the fill stays");
assert_eq!(stroke, fill, "the stroke is the object's own fill");
assert!(width > 0.0, "and shows: {width}");
}
s.execute("paint.setStroke", &json!({"ids": [a.0], "color": "#00ff00"})).unwrap();
s.execute("addon.color.strokeToFill", &json!({"ids": [a.0]})).unwrap();
let (fill, stroke, _) = paints(&s, a);
assert_eq!((fill.color().unwrap().to_hex(), stroke.color().unwrap().to_hex()), ("#00ff00".into(), "#00ff00".into()));
assert_eq!(paints(&s, b).0.color().unwrap().to_hex(), "#0080ff", "an object not aimed at is left alone");
}
/// A global swatch at a tint stays linked at that tint, and a gradient keeps its stops and
/// placement: the paint is copied as it is.
#[test]
fn a_linked_swatch_and_a_gradient_copy_as_they_are() {
let mut s = session();
let a = rect(&mut s);
s.execute("swatch.new", &json!({"name": "Ink", "color": "#c82828", "global": true})).unwrap();
s.execute("paint.setFill", &json!({"ids": [a.0], "swatch": "Ink", "tint": 40})).unwrap();
s.execute("addon.color.fillToStroke", &json!({"ids": [a.0]})).unwrap();
let (fill, stroke, _) = paints(&s, a);
assert!(matches!(&stroke, Paint::Solid { swatch: Some(name), .. } if name == "Ink"), "{stroke:?}");
assert_eq!(stroke, fill);
let g = json!({"gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}], "angle": 30}});
let mut q = g.clone();
q["ids"] = json!([a.0]);
s.execute("paint.setFill", &q).unwrap();
s.execute("addon.color.fillToStroke", &json!({"ids": [a.0]})).unwrap();
let (fill, stroke, _) = paints(&s, a);
assert!(matches!(stroke, Paint::Gradient { .. }), "{stroke:?}");
assert_eq!(stroke, fill, "the same stops and placement");
}
/// None copies as None, as Swap moves it; `skipNone` leaves an object whose source is None alone.
#[test]
fn none_copies_unless_skipped() {
let mut s = session();
let (a, b) = (rect(&mut s), rect(&mut s));
s.execute("paint.setFill", &json!({"ids": [a.0], "none": true})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [a.0, b.0], "color": "#123456"})).unwrap();
s.execute("paint.setFill", &json!({"ids": [b.0], "color": "#ff8000"})).unwrap();
let r = s.execute("addon.color.fillToStroke", &json!({"ids": [a.0, b.0], "skipNone": true})).unwrap();
assert_eq!(r["objects"], 1, "only the object with a fill changed");
assert_eq!(paints(&s, a).1.color().unwrap().to_hex(), "#123456", "skipped: its stroke stays");
assert_eq!(paints(&s, b).1.color().unwrap().to_hex(), "#ff8000");
s.execute("addon.color.fillToStroke", &json!({"ids": [a.0]})).unwrap();
assert!(paints(&s, a).1.is_none(), "without skipNone, no fill gives no stroke");
}
/// The objects inside a group each copy their own paint, as for Swap Fill and Stroke.
#[test]
fn a_groups_members_each_copy_their_own() {
let mut s = session();
let (a, b) = (rect(&mut s), rect(&mut s));
s.execute("paint.setFill", &json!({"ids": [a.0], "color": "#ff0000"})).unwrap();
s.execute("paint.setFill", &json!({"ids": [b.0], "color": "#00ff00"})).unwrap();
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
s.execute("addon.color.fillToStroke", &json!({})).unwrap();
assert_eq!(paints(&s, a).1.color().unwrap().to_hex(), "#ff0000");
assert_eq!(paints(&s, b).1.color().unwrap().to_hex(), "#00ff00");
}
/// Type: each run's stroke takes its own fill, so multi-colour text keeps its colours.
#[test]
fn each_text_run_copies_its_own_fill() {
let mut s = session();
let id = NodeId(s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Hi"})).unwrap()["id"].as_u64().unwrap());
s.execute("paint.setFill", &json!({"ids": [id.0], "color": "#aa0000"})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [id.0], "none": true})).unwrap();
s.execute("addon.color.fillToStroke", &json!({"ids": [id.0]})).unwrap();
let NodeKind::Text(t) = &node(&s, id).kind else { panic!("not text") };
for r in &t.runs {
assert_eq!(r.style.stroke, r.style.fill, "{:?}", r.text);
assert!(r.style.stroke_width > 0.0, "a painted stroke is visible");
}
}
/// One undo step each; when nothing changes, none, and the document stays unmodified. Bad
/// parameters change nothing, not even the defaults.
#[test]
fn one_undo_step_none_when_nothing_changes_and_bad_params_change_nothing() {
let mut s = session();
let id = rect(&mut s);
s.execute("paint.setFill", &json!({"ids": [id.0], "color": "#ff0000"})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [id.0], "color": "#ff0000"})).unwrap();
select_with_a_step_to_redo(&mut s, &[id]);
let before = history(&s);
s.execute("addon.color.fillToStroke", &json!({})).unwrap();
s.execute("addon.color.strokeToFill", &json!({})).unwrap();
assert_eq!(history(&s), before, "the paints were already the same");
s.execute("paint.setStroke", &json!({"ids": [id.0], "color": "#0000ff"})).unwrap();
let before = history(&s);
s.execute("addon.color.fillToStroke", &json!({})).unwrap();
assert_eq!(history(&s), (before.0 + 1, 0, true), "one step");
assert_eq!(s.doc().unwrap().history.undo.last().map(|e| e.label.as_str()), Some("Apply Fill to Stroke"));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(paints(&s, id).1.color().unwrap().to_hex(), "#0000ff");
let defaults = (s.paint.fill.clone(), s.paint.stroke.clone());
for (cmd, p) in [("addon.color.fillToStroke", json!({"ids": "not an array"})), ("addon.color.strokeToFill", json!({"skipNone": "yes"}))] {
assert!(s.execute(cmd, &p).is_err(), "{cmd} {p}");
}
assert_eq!((s.paint.fill.clone(), s.paint.stroke.clone()), defaults, "the defaults are as they were");
}
/// With nothing selected the defaults for new art change the same way: the default stroke takes
/// the default fill, with the weight Swap gives a stroke that had none.
#[test]
fn with_nothing_selected_the_defaults_take_it() {
let mut s = session();
s.execute("select.set", &json!({"ids": []})).unwrap();
s.execute("paint.setFill", &json!({"color": "#336699"})).unwrap();
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
let r = s.execute("addon.color.fillToStroke", &json!({})).unwrap();
assert_eq!(r["objects"], 0);
assert_eq!(s.paint.stroke, s.paint.fill);
assert!(s.paint.stroke_width > 0.0);
s.execute("paint.setStroke", &json!({"color": "#ff00ff"})).unwrap();
s.execute("addon.color.strokeToFill", &json!({})).unwrap();
assert_eq!(s.paint.fill.color().unwrap().to_hex(), "#ff00ff");
}
/// Copying None onto an item the object doesn't have adds nothing: with no fill and no stroke
/// item at all, neither command records an undo step or touches the object.
#[test]
fn copying_none_onto_a_missing_item_changes_nothing() {
let mut s = session();
let id = rect(&mut s);
s.edit("No paint items", |d, _| {
d.node_mut(id).unwrap().appearance.items.clear();
Ok(())
})
.unwrap();
assert_eq!((paints(&s, id).0, paints(&s, id).1), (Paint::None, Paint::None));
select_with_a_step_to_redo(&mut s, &[id]);
let (before, art) = (history(&s), node(&s, id));
for cmd in ["addon.color.fillToStroke", "addon.color.strokeToFill"] {
assert_eq!(s.execute(cmd, &json!({})).unwrap()["objects"], 0, "{cmd}");
assert_eq!(history(&s), before, "{cmd}: no undo step");
assert_eq!(node(&s, id), art, "{cmd}: no item added");
}
}
/// A graph's series and its labels keep the copied paint when the graph is drawn again: the
/// graph takes it in the same undo step, as it does from paint.setFill.
#[test]
fn a_graph_series_and_its_labels_keep_the_copied_paint_when_drawn_again() {
let mut s = session();
let csv = ",2024,2025\nQ1,3,2\nQ2,5,4";
let g = NodeId(
s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"]
.as_u64()
.unwrap(),
);
let series = |s: &Session| node(s, g).children().unwrap().iter().find(|c| c.extras().series_index == Some(0)).unwrap().clone();
let label = |s: &Session| {
let axes = node(s, g).children().unwrap().iter().find(|c| c.name.as_deref() == Some("Axes")).unwrap().clone();
axes.children().unwrap().iter().find(|c| matches!(&c.kind, NodeKind::Text(t) if t.plain_text() == "4")).unwrap().clone()
};
let sid = series(&s).id;
s.execute("paint.setFill", &json!({"ids": [sid.0], "color": "#12ab34"})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [sid.0], "none": true})).unwrap();
let lid = label(&s).id;
s.execute("paint.setFill", &json!({"ids": [lid.0], "color": "#e8573f"})).unwrap();
let steps = s.doc().unwrap().history.undo.len();
s.execute("addon.color.fillToStroke", &json!({"ids": [sid.0, lid.0]})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one step");
let kept = s.doc().unwrap().doc.node(g).unwrap().extras().graph.as_deref().unwrap().clone();
assert_eq!(kept.series_paints[0].stroke.as_ref().and_then(Paint::color).map(|c| c.to_hex()), Some("#12ab34".into()));
assert_eq!(kept.label_styles.values.as_ref().and_then(|st| st.stroke.color()).map(|c| c.to_hex()), Some("#e8573f".into()));
s.execute("graph.setData", &json!({"id": g.0, "rows": [[1, 2], [3, 4]]})).unwrap();
let marks = series(&s).children().unwrap().to_vec();
let bars: Vec<_> = marks.iter().filter(|m| matches!(m.kind, NodeKind::Path { .. })).collect();
assert!(!bars.is_empty());
for m in bars {
assert_eq!(m.appearance.stroke_paint().color().map(|c| c.to_hex()), Some("#12ab34".into()), "a redrawn mark keeps the stroke");
}
let redrawn = node(&s, g).children().unwrap().iter().find(|c| c.name.as_deref() == Some("Axes")).unwrap().clone();
let text = redrawn.children().unwrap().iter().find_map(|c| if let NodeKind::Text(t) = &c.kind { Some(t.clone()) } else { None }).unwrap();
assert_eq!(text.runs[0].style.stroke.color().map(|c| c.to_hex()), Some("#e8573f".into()), "a redrawn value label keeps the stroke");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
let back = s.doc().unwrap().doc.node(g).unwrap().extras().graph.as_deref().unwrap().clone();
assert!(
back.series_paints[0].stroke.as_ref().is_none_or(|p| p.is_none()),
"undo takes the graph's stroke back: {:?}",
back.series_paints[0].stroke
);
}
/// A series drawn with a marker design: its own marks copy their paint, but the design's art
/// keeps the design's paint, as paint.setFill leaves it (painting it would last only until the
/// graph is drawn again).
#[test]
fn a_marker_designs_art_in_a_series_keeps_its_paint() {
let mut s = session();
let r = s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setFill", &json!({"ids": [r], "color": "#0000ff"})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [r], "none": true})).unwrap();
s.execute("select.set", &json!({"ids": [r]})).unwrap();
s.execute("graph.design", &json!({"new": "Square"})).unwrap();
let csv = ",2024,2025\nQ1,3,2\nQ2,5,4";
let g = NodeId(
s.execute("graph.create", &json!({"type": "line", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"]
.as_u64()
.unwrap(),
);
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
s.execute("graph.marker", &json!({"design": "Square"})).unwrap();
let series = node(&s, g).children().unwrap().iter().find(|c| c.extras().series_index == Some(0)).unwrap().clone();
// The design's paths sit in groups inside the series; its own marks are its direct children.
let design_strokes = |s: &Session| {
let grp = node(s, series.id);
let mut out = vec![];
for c in grp.children().unwrap() {
if !matches!(c.kind, NodeKind::Path { .. }) {
c.walk(&mut |n| {
if let NodeKind::Path { .. } = n.kind {
out.push(n.appearance.stroke_paint());
}
});
}
}
out
};
let before = design_strokes(&s);
assert!(!before.is_empty(), "the series draws the design");
s.execute("addon.color.fillToStroke", &json!({"ids": [series.id.0]})).unwrap();
assert_eq!(design_strokes(&s), before, "the design's art keeps its paint");
}
@@ -0,0 +1,35 @@
//! Object → Path items that work on paths are disabled while only non-path objects are selected.
use serde_json::json;
use crate::*;
const PATH_ITEMS: [&str; 9] = [
"path.reverse",
"path.join",
"path.average",
"path.averageJoin",
"object.path.simplify",
"object.path.smooth",
"object.path.addAnchorPoints",
"object.path.divideObjectsBelow",
"object.path.splitIntoGrid",
];
fn enabled(s: &Session, id: &str) -> bool {
command_specs().iter().find(|c| c.id == id).is_some_and(|c| (c.enabled)(s).is_ok())
}
#[test]
fn path_items_need_a_path_selected() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Hi"})).unwrap();
for id in PATH_ITEMS {
assert!(!enabled(&s, id), "{id} enabled for text");
}
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
for id in PATH_ITEMS {
assert!(enabled(&s, id), "{id} disabled for a path");
}
}
+221
View File
@@ -459,6 +459,26 @@ fn outline_stroke_of_line() {
assert!((area_of(&s, r[0]) - 1000.0).abs() < 1.0);
}
#[test]
fn outline_stroke_preserves_a_zero_area_fill_without_retaining_a_live_stroke() {
let mut s = session();
s.execute("shape.line", &json!({"x1": 10, "y1": 20, "x2": 60, "y2": 90})).unwrap();
s.execute("paint.setFill", &json!({"color":"#ffffff"})).unwrap();
let before = s.doc().unwrap().doc.clone();
let result = ids(&s.execute("object.path.outlineStroke", &json!({})).unwrap());
let n = node(&s, result[0]);
let children = n.children().expect("the original fill and the outlined stroke");
assert_eq!(children.len(), 2);
assert!(children.iter().all(|n| n.appearance.stroke().is_none()));
assert!(children.iter().any(|n| n.appearance.fill_paint() == Paint::solid(Color::WHITE)), "an invisible fill is not a live stroke");
assert!(n.appearance.stroke().is_none());
assert!(children.iter().any(|n| n.appearance.fill_paint() == Paint::solid(Color::BLACK)));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc.layers, before.layers);
s.execute("edit.redo", &json!({})).unwrap();
assert!(node(&s, result[0]).appearance.stroke().is_none());
}
#[test]
fn outline_stroke_with_fill_makes_group() {
let mut s = session();
@@ -1076,6 +1096,207 @@ fn trim_merge_and_crop_remove_strokes() {
}
}
#[test]
fn outline_stroke_preserves_tiny_and_signed_area_canceling_closed_fills() {
for points in [vec![[0.0, 0.0], [100.0, 100.0], [0.0, 100.0], [100.0, 0.0]], vec![[0.0, 0.0], [1e-8, 0.0], [1e-8, 1e-8]]] {
let mut s = session();
let anchors: Vec<Value> = points.into_iter().map(|[x, y]| json!({"x":x,"y":y})).collect();
s.execute("path.create", &json!({"anchors":anchors,"closed":true})).unwrap();
let result = ids(&s.execute("object.path.outlineStroke", &json!({})).unwrap());
let n = node(&s, result[0]);
let retains_fill = n.children().is_some_and(|ch| ch.iter().any(|c| c.appearance.fill_paint() == Paint::solid(Color::WHITE)))
|| n.appearance.fill_paint() == Paint::solid(Color::WHITE);
assert!(retains_fill, "a real fill survives independently of its signed area or scale");
}
}
#[test]
fn outline_stroke_preserves_bent_open_fill_and_history() {
let mut s = session();
s.execute("path.create", &json!({"anchors":[{"x":0,"y":0},{"x":60,"y":0},{"x":75,"y":-15},{"x":110,"y":-15}],"closed":false})).unwrap();
let before = s.doc().unwrap().doc.clone();
let result = ids(&s.execute("object.path.outlineStroke", &json!({})).unwrap());
let n = node(&s, result[0]);
let children = n.children().expect("original fill beside the outlined stroke");
assert_eq!(children.len(), 2);
let fill = children.iter().find(|n| n.appearance.fill_paint() == Paint::solid(Color::WHITE)).unwrap();
assert!(!fill.path_data().unwrap().subpaths[0].closed);
assert!(children.iter().all(|n| n.appearance.stroke().is_none()));
let after = s.doc().unwrap().doc.layers.clone();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc.layers, before.layers);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc.layers, after);
}
#[test]
fn outline_stroke_mixed_contours_preserve_all_fill() {
use vectorcraft_geom::{Anchor, Point, SubPath};
let mut s = session();
let id = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
s.edit("mixed contours", |d, _| {
let n = d.node_mut(id).unwrap();
if let NodeKind::Path { path, .. } = &mut n.kind {
path.subpaths.push(SubPath::new(
vec![Anchor::corner(Point::new(50.0, 0.0)), Anchor::corner(Point::new(80.0, 0.0)), Anchor::corner(Point::new(80.0, 20.0))],
false,
));
}
Ok(())
})
.unwrap();
let result = ids(&s.execute("object.path.outlineStroke", &json!({})).unwrap());
let outlined = node(&s, result[0]);
let children = outlined.children().unwrap();
let fill = children.iter().find(|n| n.appearance.fill_paint() == Paint::solid(Color::WHITE)).unwrap();
let NodeKind::Path { path, .. } = &fill.kind else { panic!("fill is a path") };
assert_eq!(path.subpaths.len(), 2);
assert!(path.subpaths[0].closed);
assert!(!path.subpaths[1].closed);
}
#[test]
fn outline_stroke_keeps_closed_compound_members_editable() {
check_outlined_compound_members(false);
}
#[test]
fn outline_stroke_keeps_open_compound_contours_and_members() {
check_outlined_compound_members(true);
}
fn check_outlined_compound_members(mixed: bool) {
use vectorcraft_geom::{Anchor, Point, SubPath};
let mut s = session();
let outer = rect(&mut s, 10.0, 10.0, 100.0, 100.0);
let inner = rect(&mut s, 35.0, 35.0, 30.0, 30.0);
let mut members = vec![outer.0, inner.0];
if mixed {
let open = s.execute("path.create", &json!({"anchors":[{"x":140,"y":10},{"x":170,"y":30},{"x":140,"y":50}]})).unwrap();
members.push(open["id"].as_u64().unwrap());
s.edit("Mixed compound member", |d, _| {
let NodeKind::Path { path, .. } = &mut d.node_mut(inner).unwrap().kind else { panic!("path") };
path.subpaths.push(SubPath::new(vec![Anchor::corner(Point::new(45.0, 80.0)), Anchor::corner(Point::new(70.0, 90.0))], false));
Ok(())
})
.unwrap();
}
s.execute("select.set", &json!({"ids":members})).unwrap();
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
s.edit("Compound member names and rule", |d, _| {
d.node_mut(outer).unwrap().name = Some("outer-member".into());
d.node_mut(inner).unwrap().name = Some("inner-member".into());
let NodeKind::Compound { rule, .. } = &mut d.node_mut(compound).unwrap().kind else { panic!("compound") };
*rule = FillRule::EvenOdd;
Ok(())
})
.unwrap();
let original = node(&s, compound);
let expected: Vec<_> = original
.children()
.unwrap()
.iter()
.map(|child| {
let path = child.path_data().unwrap().clone();
(child.name.clone(), path)
})
.collect();
let before = s.doc().unwrap().doc.layers.clone();
let result = ids(&s.execute("object.path.outlineStroke", &json!({})).unwrap())[0];
let group = node(&s, result);
let fill = group.children().unwrap().iter().find(|child| child.appearance.fill_paint() == Paint::solid(Color::WHITE)).unwrap();
let NodeKind::Compound { children, rule } = &fill.kind else { panic!("closed fill must retain editable compound members") };
assert_eq!(*rule, FillRule::EvenOdd);
assert_eq!(children.len(), if mixed { 3 } else { 2 });
for (child, (name, path)) in children.iter().zip(expected) {
assert_eq!(child.name, name);
assert_eq!(child.path_data().unwrap(), &path);
assert_ne!(child.id, outer);
assert_ne!(child.id, inner);
}
let member = children[0].id;
let sibling = children[1].id;
let member_bounds = children[0].geometric_bounds().unwrap();
let sibling_before = children[1].clone();
let after = s.doc().unwrap().doc.layers.clone();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc.layers, before);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc.layers, after);
// Group Selection can still address one retained child without moving its sibling.
s.execute("select.set", &json!({"ids":[member.0]})).unwrap();
s.execute("object.move", &json!({"dx":7,"dy":3})).unwrap();
assert!(close(
node(&s, member).geometric_bounds().unwrap(),
Rect::new(member_bounds.x0 + 7.0, member_bounds.y0 + 3.0, member_bounds.x1 + 7.0, member_bounds.y1 + 3.0),
1e-6
));
assert_eq!(node(&s, sibling), *sibling_before);
}
/// Exercise the real Group Selection pointer route, not select.set by id.
#[test]
fn outline_fill_and_stroke_move_independently_with_group_selection() {
use vectorcraft_tools::{PointerEvent, PointerKind};
for closed in [true, false] {
for move_fill in [false, true] {
for click_first in [false, true] {
let mut s = session();
s.execute(
"path.create",
&json!({"anchors":[{"x":100,"y":100},{"x":200,"y":100},{"x":200,"y":200},{"x":100,"y":200}],"closed":closed}),
)
.unwrap();
s.execute("paint.setFill", &json!({"color":"#ff0000"})).unwrap();
s.execute("paint.setStroke", &json!({"color":"#000000"})).unwrap();
s.execute("stroke.set", &json!({"weight":10})).unwrap();
let root = ids(&s.execute("object.path.outlineStroke", &json!({})).unwrap())[0];
let group = node(&s, root);
let children = group.children().expect("fill and outlined stroke stay separate");
assert_eq!(children.len(), 2);
let fill = children.iter().find(|c| c.appearance.fill_paint().color().is_some_and(|c| c.to_hex() == "#ff0000")).unwrap().id;
let stroke = children.iter().find(|c| c.id != fill).unwrap().id;
group.walk(&mut |n| assert!(n.appearance.stroke().is_none(), "no retained live stroke"));
let moved = if move_fill { fill } else { stroke };
let other = if move_fill { stroke } else { fill };
let other_before = node(&s, other);
let bounds_before = bounds(&s, moved);
let layers_before_move = s.doc().unwrap().doc.layers.clone();
let v = ViewInfo { smart_guides: false, snap_to_point: false, ..ViewInfo::default() };
s.select_tool("groupSelection", v).unwrap();
// Start empty, as clicking the art with Group Selection does after deselection.
s.execute("select.none", &json!({})).unwrap();
let (x, y) = if move_fill { (150.0, 150.0) } else { (150.0, 100.0) };
let compound_stroke = !move_fill && matches!(node(&s, stroke).kind, NodeKind::Compound { .. });
for _ in 0..if compound_stroke {
2
} else if click_first {
1
} else {
0
} {
s.pointer(&PointerEvent::new(PointerKind::Down, x, y), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, x, y), v).unwrap();
}
for (kind, x, y) in [(PointerKind::Down, x, y), (PointerKind::Drag, x + 30.0, y + 15.0), (PointerKind::Up, x + 30.0, y + 15.0)] {
s.pointer(&PointerEvent::new(kind, x, y), v).unwrap();
}
assert_eq!(node(&s, other), other_before, "sibling unchanged: closed={closed}, fill={move_fill}, click_first={click_first}");
let b = bounds(&s, moved);
assert!(
close(b, Rect::new(bounds_before.x0 + 30.0, bounds_before.y0 + 15.0, bounds_before.x1 + 30.0, bounds_before.y1 + 15.0), 1e-6),
"moved leaf: {b:?}"
);
let layers_after_move = s.doc().unwrap().doc.layers.clone();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc.layers, layers_before_move);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc.layers, layers_after_move);
}
}
}
}
/// #1590: an inset larger than the shape leaves nothing, and the error says so rather than asking
/// for paths that are selected.
#[test]
+10 -3
View File
@@ -1126,8 +1126,8 @@ fn a_drag_from_a_fill_moves_only_the_selected_anchors_of_partly_selected_paths()
}
/// A path selected whole inside a selected group moves once, with the group, when the selection
/// also holds a direct-selected anchor: a Group Selection drag from the path's fill (which adds
/// the group) and an arrow key move both by 10 pt.
/// also holds a direct-selected anchor: a completed Group Selection click adds the group, then
/// a drag and an arrow key move both by 10 pt. A leaf drag before that click keeps its sibling still.
#[test]
fn a_path_in_a_selected_group_moves_once_with_selected_anchors() {
use vectorcraft_tools::PointerKind::{Down, Drag, Up};
@@ -1142,7 +1142,14 @@ fn a_path_in_a_selected_group_moves_once_with_selected_anchors() {
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
s.execute("select.anchors", &json!({"id": other.0, "anchors": [[0, 0]], "mode": "add"})).unwrap();
gesture(&mut s, v, &[(Down, 125.0, 125.0), (Drag, 130.0, 125.0), (Drag, 135.0, 125.0), (Up, 135.0, 125.0)]);
assert!(s.doc().unwrap().selection.contains(g), "the press added the group");
assert!(!s.doc().unwrap().selection.contains(g), "the leaf drag keeps its selection");
assert_eq!((top_left(&s, a), top_left(&s, b), first_x(&s)), ((110.0, 100.0), (160.0, 100.0), 310.0), "the leaf and selected anchor move");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
s.execute("select.anchors", &json!({"id": other.0, "anchors": [[0, 0]], "mode": "add"})).unwrap();
gesture(&mut s, v, &[(Down, 125.0, 125.0), (Up, 125.0, 125.0)]);
assert!(s.doc().unwrap().selection.contains(g), "the completed click added the group");
gesture(&mut s, v, &[(Down, 125.0, 125.0), (Drag, 130.0, 125.0), (Drag, 135.0, 125.0), (Up, 135.0, 125.0)]);
assert_eq!((top_left(&s, a), top_left(&s, b), first_x(&s)), ((110.0, 100.0), (170.0, 100.0), 310.0), "the drag");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [g.0, a.0]})).unwrap();
+25
View File
@@ -878,6 +878,31 @@ fn a_handle_drag_keeps_the_opposite_edge_of_the_offset_shape() {
}
}
#[test]
fn a_hover_checks_the_memo_as_often_however_many_objects_are_selected() {
let checks = |objects: u32| {
let mut s = session();
for i in 0..objects {
rect(&mut s, f64::from(i), 1.0, 0.0);
}
run(&mut s, "select.all", json!({}));
let v = ViewInfo::default();
s.select_tool("selection", v).unwrap();
// Off the art, so the hover walks every selected object and finds no anchor or center.
let hover = |s: &mut Session| {
s.pointer(&PointerEvent::new(PointerKind::Move, 350.0, 350.0), v).unwrap();
s.cursor(Point::new(350.0, 350.0), Mods::default(), v)
};
hover(&mut s);
let before = s.preview_memo.checks();
hover(&mut s);
s.preview_memo.checks() - before
};
let few = checks(3);
assert!(few > 0, "a hover asks the memo");
assert_eq!(checks(60), few, "a check compares the whole selection: one per object is quadratic");
}
#[test]
fn hovering_over_an_unchanged_document_measures_nothing_again() {
// A selected square with Offset Path 10, drawn from 90 to 210, with Use Preview Bounds and Smart
+196 -2
View File
@@ -1645,6 +1645,173 @@ fn select_all_in_one_frame_selects_only_its_text_once_the_caret_moves() {
assert!(s.execute("text.editRange", &json!({"id": a.0, "start": 0, "end": 0, "clear": "x"})).is_err());
}
/// A story of bulleted paragraphs threaded from area type `a` into frame `b`, each frame holding
/// paragraph returns, with the Type tool editing `b` at its start.
fn threaded_list_edited_in_its_second_frame() -> (Session, NodeId, NodeId, String) {
let mut s = session();
let story = "Alpha beta.\n".repeat(12);
let a = s.execute("text.create", &json!({"x": 10, "y": 10, "text": story, "size": 12, "area": {"width": 150, "height": 60}})).unwrap()["id"]
.as_u64()
.unwrap();
let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 300})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
s.execute("text.thread.create", &json!({})).unwrap();
s.execute("text.setFormat", &json!({"ids": [a, b], "list": "bullet"})).unwrap();
let (a, b) = (NodeId(a), NodeId(b));
for id in [a, b] {
let t = obj(&s, id);
assert!(t.plain_text().contains('\n'), "frame {} holds paragraph returns", id.0);
assert!((0..t.paragraph_count()).all(|k| t.para_at(k).list.is_some()), "frame {} is a list", id.0);
}
s.execute("select.set", &json!({"ids": [b.0]})).unwrap();
s.select_tool("type", ViewInfo::default()).unwrap();
s.set_tool_option("textSelection", &json!({"editing": b.0, "anchor": 0, "caret": 0}));
(s, a, b, story)
}
#[test]
fn remove_breaks_takes_the_whole_story_that_select_all_selected() {
let (mut s, a, b, story) = threaded_list_edited_in_its_second_frame();
s.execute("select.all", &json!({})).unwrap();
let steps = undo_labels(&s).len();
s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph"})).unwrap();
assert_eq!(undo_labels(&s).len(), steps + 1, "one undo step");
let joined = format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text());
assert_eq!(joined, story.trim_end_matches('\n').replace('\n', " "), "every frame's returns go, each between words as a space");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()), story);
assert!(obj(&s, a).plain_text().contains('\n') && obj(&s, b).plain_text().contains('\n'));
}
#[test]
fn remove_breaks_on_a_selected_threaded_story_puts_a_space_between_its_frames() {
let (mut s, a, b, story) = threaded_list_edited_in_its_second_frame();
assert!(obj(&s, a).plain_text().ends_with('\n'), "the first frame ends with a paragraph return");
s.select_tool("selection", ViewInfo::default()).unwrap();
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph"})).unwrap();
let joined = format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text());
assert_eq!(joined, story.trim_end_matches('\n').replace('\n', " "), "the return at the end of the first frame becomes a space");
}
#[test]
fn remove_breaks_in_one_frames_selection_leaves_the_other_frames() {
let (mut s, a, b, _) = threaded_list_edited_in_its_second_frame();
let (in_a, b_len) = (obj(&s, a).plain_text(), obj(&s, b).plain_text().len());
s.set_tool_option("textSelection", &json!({"editing": b.0, "anchor": 0, "caret": b_len}));
s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph"})).unwrap();
assert_eq!(obj(&s, a).plain_text(), in_a, "the first frame keeps its returns");
assert!(!obj(&s, b).plain_text().contains('\n'), "the edited frame's returns go");
}
#[test]
fn convert_to_text_takes_the_whole_story_that_select_all_selected() {
let (mut s, a, b, _) = threaded_list_edited_in_its_second_frame();
s.execute("select.all", &json!({})).unwrap();
let steps = undo_labels(&s).len();
s.execute("text.convertListToText", &json!({})).unwrap();
assert_eq!(undo_labels(&s).len(), steps + 1, "one undo step");
for id in [a, b] {
let t = obj(&s, id);
assert!((0..t.paragraph_count()).all(|k| t.para_at(k).list.is_none()), "frame {} leaves its list", id.0);
assert!(t.plain_text().contains("\u{2022}\t"), "frame {} holds its bullets as characters", id.0);
}
assert!(s.tool_options().get("story").is_some(), "the whole story stays selected");
s.execute("edit.undo", &json!({})).unwrap();
for id in [a, b] {
let t = obj(&s, id);
assert!((0..t.paragraph_count()).all(|k| t.para_at(k).list.is_some()), "frame {} is a list again", id.0);
}
}
#[test]
fn convert_to_text_of_the_whole_story_leaves_a_locked_frame() {
// Over MCP without ids, and as the Paragraph panel sends it, with every frame of the story.
for named in [false, true] {
let (mut s, a, b, _) = threaded_list_edited_in_its_second_frame();
s.execute("object.lock", &json!({"ids": [b.0]})).unwrap();
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
s.set_tool_option("textSelection", &json!({"editing": a.0, "anchor": 0, "caret": 0}));
assert_eq!(s.execute("select.all", &json!({})).unwrap()["story"], json!([a.0, b.0]));
// The first frame ends with a paragraph return, so the paragraph that starts the locked
// frame takes in the first frame's empty last part and starts its text there.
let in_a = obj(&s, a).plain_text();
assert!(in_a.ends_with('\n'));
let own = in_a.split('\n').filter(|piece| !piece.is_empty()).count();
let p = if named { json!({"ids": [a.0, b.0]}) } else { json!({}) };
let r = s.execute("text.convertListToText", &p).unwrap();
assert_eq!(r["ids"], json!([a.0]), "only the editable frame is changed (ids named: {named})");
assert_eq!(r["converted"], json!(own), "only the paragraphs whose text starts in the editable frame convert");
assert!(r["inserted"].as_array().unwrap().iter().all(|i| i["id"] == json!(a.0)));
let (ta, tb) = (obj(&s, a), obj(&s, b));
assert!(ta.plain_text().contains("\u{2022}\t"), "the editable frame is converted");
let markers = ta.plain_text().matches("\u{2022}\t").count() + tb.plain_text().matches("\u{2022}\t").count();
assert_eq!(markers, own, "the locked frame's first paragraph keeps its list");
// The converted text is longer, so the story flows on into the locked frame; its own
// paragraphs stay a list.
let last = tb.paragraph_count() - 2;
assert!(tb.para_at(last).list.is_some(), "the locked frame's paragraphs stay a list (ids named: {named})");
assert!(!tb.plain_text().ends_with("\u{2022}\tAlpha beta.\n"));
assert!(s.tool_options().get("story").is_some(), "the whole story stays selected");
}
}
#[test]
fn convert_to_text_of_the_whole_story_leaves_a_paragraph_that_starts_in_a_locked_frame() {
for named in [false, true] {
let mut s = session();
let story = format!("Alpha beta.\nAlpha beta.\n{}end.\nAlpha beta.\nAlpha beta.\n", "Gamma delta ".repeat(40));
let a = NodeId(
s.execute("text.create", &json!({"x": 10, "y": 10, "text": story, "size": 12, "area": {"width": 150, "height": 60}})).unwrap()["id"]
.as_u64()
.unwrap(),
);
let b = NodeId(s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 900})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("text.thread.create", &json!({})).unwrap();
s.execute("text.setFormat", &json!({"ids": [a.0, b.0], "list": "bullet"})).unwrap();
let in_a = obj(&s, a).plain_text();
assert!(!in_a.ends_with('\n') && !obj(&s, b).plain_text().starts_with('\n'), "a paragraph runs on from the first frame into the second");
s.execute("object.lock", &json!({"ids": [a.0]})).unwrap();
s.execute("select.set", &json!({"ids": [b.0]})).unwrap();
s.select_tool("type", ViewInfo::default()).unwrap();
s.set_tool_option("textSelection", &json!({"editing": b.0, "anchor": 0, "caret": 0}));
assert_eq!(s.execute("select.all", &json!({})).unwrap()["story"], json!([a.0, b.0]));
let p = if named { json!({"ids": [a.0, b.0]}) } else { json!({}) };
let r = s.execute("text.convertListToText", &p).unwrap();
assert_eq!(r["ids"], json!([b.0]), "only the editable frame is changed (ids named: {named})");
// The two paragraphs that start in the editable frame, and the empty one that ends the story.
assert_eq!(r["converted"], json!(3), "only the paragraphs that start in the editable frame convert");
let (ta, tb) = (obj(&s, a), obj(&s, b));
assert_eq!(ta.plain_text(), in_a, "the locked frame's text is as it was");
assert!((0..ta.paragraph_count()).all(|k| ta.para_at(k).list.is_some()), "the locked frame stays a list");
assert!(tb.para_at(0).list.is_some(), "the paragraph the locked frame starts stays a list");
assert!(!tb.plain_text().starts_with('\u{2022}'));
assert_eq!(tb.plain_text().matches("\u{2022}\t").count(), 2);
}
}
#[test]
fn convert_to_text_of_named_frames_ends_the_story_selection() {
let (mut s, _, b, _) = threaded_list_edited_in_its_second_frame();
s.execute("select.all", &json!({})).unwrap();
s.execute("text.convertListToText", &json!({"ids": [b.0]})).unwrap();
assert!(obj(&s, b).plain_text().contains("\u{2022}\t"));
assert!(s.tool_options().get("story").is_none(), "the Type tool's selection moves past the characters inserted");
}
#[test]
fn convert_to_text_in_one_frame_leaves_the_other_frames() {
let (mut s, a, b, _) = threaded_list_edited_in_its_second_frame();
let in_a = obj(&s, a).plain_text();
s.execute("text.convertListToText", &json!({})).unwrap();
let (ta, tb) = (obj(&s, a), obj(&s, b));
assert_eq!(ta.plain_text(), in_a, "the first frame's text is as it was");
assert!(ta.para_at(0).list.is_some(), "the first frame stays a list");
assert!((0..tb.paragraph_count()).all(|k| tb.para_at(k).list.is_none()), "the edited frame leaves its list");
assert!(tb.plain_text().contains("\u{2022}\t"), "the edited frame holds its bullets as characters");
}
#[test]
fn a_frame_dragged_with_the_type_tools_is_the_dragged_rectangle() {
for tool in ["type", "verticalType"] {
@@ -2823,9 +2990,11 @@ fn the_fallback_glyph_of_a_consonant_after_its_vowel_sign_is_reported() {
let glyphs = vectorcraft_text::layout(db, &obj(&s, open)).glyphs;
let fallback = db.face_by_id(glyphs[0].font_id).expect("the fallback face");
assert_ne!(fallback.id(), requested.id());
let (ka, sign) = (fallback.glyph_for('क'), fallback.glyph_for('\u{93F}'));
let ka = fallback.glyph_for('क');
let drawn: Vec<_> = glyphs.iter().map(|g| (g.gid, g.byte)).collect();
assert_eq!(drawn, [(sign, 0), (ka, 0)], "the vowel sign is drawn first, in Ka's cluster ({} or {MATRA_FAMILY})", fallback.family);
// A face may draw the vowel sign with a glyph other than its own, so only its place is checked.
let sign_first = matches!(drawn[..], [(sign, 0), (k, 0)] if sign != 0 && sign != ka && k == ka);
assert!(sign_first, "the vowel sign is drawn first, in Ka's cluster ({} or {MATRA_FAMILY}): {drawn:?}", fallback.family);
let query = s.execute("text.glyphAlternates", &json!({"id": open.0, "start": 0})).unwrap();
assert_eq!(query["chosen"], json!(ka), "the fallback face's glyph for Ka");
@@ -2834,3 +3003,28 @@ fn the_fallback_glyph_of_a_consonant_after_its_vowel_sign_is_reported() {
let query = s.execute("text.glyphAlternates", &json!({"id": boxed.0, "start": 0})).unwrap();
assert_eq!(query["chosen"], json!(ka), "an overflowing Ka reports the fallback face's glyph for Ka");
}
/// Apply Fill to Stroke with characters selected with the Type tool: only those characters take
/// a stroke of their own fill, as one undo step (#5530).
#[test]
fn apply_fill_to_stroke_with_characters_selected_changes_only_them() {
let mut s = session();
let v = ViewInfo::default();
s.select_tool("type", v).unwrap();
click(&mut s, 50.0, 300.0);
let id = s.doc().unwrap().selection.objects[0];
s.tool_text("Sample Text", v).unwrap();
// All of it red, then the first word green: a stroke on the rest would show.
s.execute("paint.setFill", &json!({"ids": [id.0], "color": "#ff0000"})).unwrap();
s.set_tool_option("select", &json!({"start": 0, "end": 6}));
s.execute("paint.setFill", &json!({"color": "#00a000"})).unwrap();
let steps = undo_labels(&s).len();
s.execute("addon.color.fillToStroke", &json!({})).unwrap();
let t = obj(&s, id);
assert_eq!(t.runs[0].text, "Sample");
assert_eq!(t.runs[0].style.stroke, t.runs[0].style.fill, "the selected characters take their fill as a stroke");
assert!(t.runs[0].style.stroke_width > 0.0);
assert!(t.runs[1].style.stroke.is_none(), "the rest of the type keeps its stroke");
let labels = undo_labels(&s);
assert_eq!((labels.len(), labels.last().map(String::as_str)), (steps + 1, Some("Apply Fill to Stroke")));
}
+14 -2
View File
@@ -154,6 +154,8 @@ impl Session {
/// Direct Selection to the tools that edit anchors (the Pen) and Selection to the others.
/// Cmd+Alt lends Group Selection while Direct Selection is active. Cmd still lends the last
/// selection tool from other tools (Alt on the lent Direct Selection gesture stays copy/subtract).
/// Cmd alone lends Direct Selection the Selection tool, whose bounding box transforms the
/// object (#3901; <https://community.adobe.com/t5/illustrator-discussions/handles-disappar-on-shape-with-direct-selection-tool/m-p/14848662>).
/// Perspective Selection keeps Cmd+Alt drags to copy objects on their perspective plane.
/// None for the other selection tools and the view tools.
fn lent_tool(&self, id: &str, mods: &Mods) -> Option<&'static str> {
@@ -161,8 +163,8 @@ impl Session {
if matches!(id, "hand" | "zoom" | "rotateView") {
return None;
}
if id == "directSelection" && mods.cmd && mods.alt {
return Some("groupSelection");
if id == "directSelection" && mods.cmd {
return Some(if mods.alt { "groupSelection" } else { "selection" });
}
if id == "perspectiveSelection" && mods.cmd && mods.alt {
return None;
@@ -173,6 +175,16 @@ impl Session {
Some(self.last_selection_tool.unwrap_or(if edits_anchors(id) { "directSelection" } else { "selection" }))
}
/// The selection tool a press with `mods` would borrow from the active tool
/// ([`Self::lend_selection_tool`]), as [`Self::cursor`] shows it: the canvas also shows what
/// that tool shows (Direct Selection with Cmd held shows the bounding box).
pub fn lent_tool_id(&self, mods: &Mods) -> Option<&'static str> {
if !mods.cmd || self.lender.is_some() {
return None;
}
self.lent_tool(self.tool.id(), mods)
}
/// A press with Cmd held (Ctrl elsewhere) and any other tool than a selection tool: the
/// selection tool [`Self::lent_tool`] takes the gesture, pressing without Cmd (a plain click,
/// not Select Behind). The tool lent to stays as it was, unaware, until the release.
+4
View File
@@ -239,6 +239,10 @@ fn structured_junk() {
("addon.select.byArtboards", json!({"artboards": [0, u64::MAX, -1, "x", null, 1.5], "relation": "inside"})),
("addon.select.byArtboards", json!({"artboards": [1e308], "relation": [1]})),
("addon.select.byArtboards", json!({"artboards": {"a": 1}, "relation": "outside"})),
("addon.select.byLinkStatus", json!({"status": ["linked", "missing", null, 7, {"a": 1}], "ids": [2, u64::MAX, -1, "x", 1.5]})),
("addon.select.byLinkStatus", json!({"status": "embedded", "ids": {"a": 1}, "add": [1], "zoom": "yes"})),
("addon.select.byLinkStatus", json!({"status": ["modified", "embedded"], "ids": [], "add": true, "zoom": true})),
("addon.select.byLinkStatus", json!({"status": [[["linked"]]], "ids": null})),
("object.transform", json!({"matrix": [0, 0, 0, 0, 0, 0]})),
("object.transform", json!({"matrix": [1e308, 1e308, 1e308, 1e308, 1e308, 1e308]})),
("object.transform", json!({"matrix": [1, 2, 3]})),
+334 -5
View File
@@ -2763,6 +2763,10 @@ fn editing_text() -> String {
"%AI5_File:\n%AI5_BeginRaster\n() 1 XG\n/DeviceCMYK XN\n[ 4 0 0 4 10 30 ] 2 1 0 Xh\n[ 4 0 0 4 10 30 ] 0 0 2 1 2 1 8 4 1 0 0 0 4 4 0 0\n\
%%BeginData: 18\rXI\nff000000000000ff80ff\n%%EndData\nXH\n%AI5_EndRaster\nN"
.into(),
// A 9 × 2 1-bit image mask (ImageMask 1) colorized by the global fill before it, in hex.
"0 0 0 1 (Black global) 0.4 0 Xk\n%AI5_File:\n%AI5_BeginRaster\n() 1 XG\n/DeviceGray XN\n[ 4 0 0 4 10 30 ] 9 2 0 Xh\n\
[ 4 0 0 4 10 30 ] 0 0 9 2 9 2 1 1 0 0 0 1 4 4 0 0\n%%BeginData: 8\rXI\n6080ff00\n%%EndData\nXH\n%AI5_EndRaster\nN"
.into(),
]
.join("\n");
let layer = |name: &str, visible: u8, body: &str| {
@@ -2849,6 +2853,23 @@ fn the_editing_fixture_reads_its_cmyk_image_with_its_mask() {
assert!(layers && found.contains(&(Some(vec![255, 0, 0, 0, 0, 0, 0, 255]), true)), "{found:?} {warnings:?}");
}
/// The fuzzed editing data, as it is, reads its 1-bit image mask as an image colorized with the
/// global color before it.
#[test]
fn the_editing_fixture_reads_its_image_mask_colorized() {
let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&editing_text())].concat();
let (doc, warnings, layers) = vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, true, 1.0);
let mut found = vec![];
doc.visit_images(|n, im| {
if let Some(vectorcraft_color::Paint::Solid { swatch, .. }) = n.extras().colorize.as_deref() {
found.push((swatch.clone(), im.width, im.height, doc.images[&im.key].coverage().map(|c| c.2)));
}
});
// Clear bits (black) show the color; set bits (white) are transparent.
let cover = vec![255, 0, 0, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255];
assert!(layers && found == [(Some("Black global".to_string()), 9, 2, Some(cover))], "{found:?} {warnings:?}");
}
/// The text document of a story of centred type with two styles, as an editing copy keeps it.
fn text_document_text() -> String {
"/0 << /1 << /0 [ << /0 << /0 << /0 (Helvetica) >> >> >> ] >> /8 << /0 [ << /0 << /0 [ 0 0 ] /2 << /2 [ 1 0 0 1 3 4 ] >> >> >> ] >> >>\n\
@@ -3291,7 +3312,7 @@ proptest! {
#[test]
fn ai_line_widths_never_panic(
width in prop::sample::select(vec!["0", "0.0", "-0", "-1", "1e308", "1e-308", "nan", "inf", "2"]),
render in prop::sample::select(vec!["0", "1", "2", "5", "6", "7", "-1", "99"]),
render in prop::sample::select(vec!["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "4.5", "-1", "99"]),
cut in 0usize..2_000,
edits in prop::collection::vec((0usize..2_000, prop::sample::select(vec!['0', '1', '-', '.', ' ', '\n', '(', ')', 'w', 'B', 'S', 'T'])), 0..8),
) {
@@ -3307,6 +3328,88 @@ proptest! {
survive("hostile .ai line widths", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?;
}
/// A `.ai` whose pattern definition (a marked tile box, a gradient placed by `Bg`'s matrix) and
/// pattern fill are damaged or hostile.
#[test]
fn ai_pattern_definitions_never_panic(
cut in 0usize..2_000,
edits in prop::collection::vec((0usize..2_000, prop::sample::select(vec!['0', '1', '-', '.', ' ', '\n', '(', ')', '[', ']', '%', '_', 'n', 'E', 'p', 'B'])), 0..12),
) {
use vectorcraft_testkit::ai;
let gradient = "%AI5_BeginGradient: (G)\n(G) 1 2 Bd\n[\n%_0 0 0 0 1 0 0 2 1 6 50 0 Bs\n%_0 0 0 0 0 0 1 2 1 6 50 100 Bs\nBD\n%AI5_EndGradient\n";
let pattern = "%AI3_BeginPattern: (P)\n(P) 0 -10 10 0\n%_0 A\n%_0 Xw\n%_0 XR\n%_0 0 m\n%_10 0 L\n%_10 -10 L\n%_0 -10 L\n%_0 0 L\n%_n\n\
%_/ArtDictionary :\n%_1 /Bool (AIPattern_Editor_Backing_Tile_Rect) ,\n%_;\n%_\n%_2 -2 m\n%_8 -2 L\n%_8 -8 L\n%_2 -8 L\n%_Bb\n\
%_0.1 0.2 45 0.3 Bh\n%_1 (G) 0.1 0.2 0 1.5 3 0 0 3 0 0 1 Bg\n%_3 0 0 3 -8000 8000 Bm\n%_f\n%_0 BB\nE\n%AI3_EndPattern\n";
let art = format!("(P) 0 0 1 1 0 0 0 0 0 [0.5 0.2 -0.2 0.5 3 -4] p\n{}f\n", ai::rect(20.0, 20.0, 80.0, 80.0));
let data = mutate_text(&ai::editing_data(100.0, 100.0, &format!("{gradient}{pattern}{}", ai::layer("L", &art))), cut, &edits);
let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&data)].concat();
survive("hostile .ai patterns", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?;
}
/// A `.ai` whose gradients and patterns have names with newlines (blank before one, several,
/// repeated, one shown like another's numbered name), used by fills and a palette, damaged or
/// hostile.
#[test]
fn ai_global_names_with_newlines_never_panic(
names in prop::collection::vec(prop::sample::select(vec!["Sky\\n1", "Sky\\n2", "Sky", "Sky 2", "\\n3", "\\n", "Sky\\n\\n1", "\\012x"]), 1..6),
cut in 0usize..3_000,
edits in prop::collection::vec((0usize..3_000, prop::sample::select(vec!['\\', 'n', '(', ')', ' ', '\n', 'B', 'p', 'E', '%'])), 0..10),
) {
use vectorcraft_testkit::ai;
let mut setup = String::new();
let mut art = String::new();
let mut cells = String::new();
for name in &names {
setup.push_str(&format!(
"%AI5_BeginGradient: ({name})\n({name}) 0 2 Bd\n[\n%_1 0 50 0 Bs\n%_0 0 50 100 Bs\nBD\n%AI5_EndGradient\n\
%AI3_BeginPattern: ({name})\n({name}) 0 0 6 6\n%_0 A\n%_0 0 m\n%_0 6 L\n%_6 6 L\n%_6 0 L\n%_0 0 0 1 k\n%_f\nE\n%AI3_EndPattern\n"
));
art.push_str(&format!("Bb\n1 ({name}) 0 0 0 50 1 0 0 1 0 0 Bg\n{}f\n0 BB\n", ai::rect(10.0, 10.0, 40.0, 40.0)));
art.push_str(&format!("({name}) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}f\n", ai::rect(50.0, 50.0, 90.0, 90.0)));
cells.push_str(&format!("Bb\n2 ({name}) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\nPc\n({name}) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\nPc\n"));
}
setup.push_str(&format!("%AI5_BeginPalette\n0 0 Pb\n{cells}PB\n%AI5_EndPalette\n"));
let data = mutate_text(&ai::editing_data(100.0, 100.0, &format!("{setup}{}", ai::layer("L", &art))), cut, &edits);
let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&data)].concat();
survive("hostile .ai global names", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?;
}
/// A `.ai` whose images (binary samples with an alpha channel, the operators that end a raster,
/// then a name and an opacity mask) and placed file (an empty relative folder, a preview) are
/// damaged or hostile, bytes of the samples included.
#[test]
fn ai_images_and_placed_files_never_panic(
cut in 0usize..3_000,
edits in prop::collection::vec((0usize..3_000, prop::sample::select(vec![b'0', b'1', b'9', b' ', b'\r', b'\n', b'(', b')', b'[', b']', b'%', b'_', b'N', b'X', b'~', 0u8, 255u8])), 0..12),
) {
use vectorcraft_testkit::ai;
let raster = "%AI5_File:\n%AI5_BeginRaster\n() 1 XG\n/DeviceRGB XN\n[10 0 0 10 20 -30] 2 1 0 Xh\n[10 0 0 10 20 -30] 0 0 2 1 2 1 8 3 1 17 1 0 4 4 0 0\n%%BeginData: 10\nXI\n@@%%EndData\nXH\n\
%AI17_Begin_Content_if_version_gt:24 17\n72 72 Xr\n%AI17_End_Versioned_Content\n%AI5_EndRaster\nN\n\
%_/ArtDictionary :\n%_/Mask :\n%_X=\n%_0 g\n%_0 0 m\n%_5 0 l\n%_5 -5 l\n%_f\n%_X+\n%_ (Art) ,\n%_; (AI9_Mask) ,\n%_/XMLUID : (Photo) ; (AI10_ArtUID) ,\n%_;\n%_\n";
let place = "%AI5_BeginPlace\n%%FileType: 1\n[1 0 0 -1 -8000 8000] 8000 8000 8002 8001 4 4 0\n(/tmp/p.png)`\n%%IncludeFile:/tmp/p.png\n\
%AI17_Begin_Content_if_version_gt:24 12\n%AI28_BeginPlacedRelativePath\n()\n%AI28_EndPlacedRelativePath\n%AI17_Alternate_Content\n%AI17_End_Versioned_Content\n\
%AI17_Begin_Content_if_version_gt:24 5\n%AI26_BeginPlacedObjectPreview\n2 1 8 32 17 @@\n%AI26_EndPlacedObjectPreview\n%AI17_End_Versioned_Content\n~\n%AI5_EndPlace\n";
let text = ai::editing_data(100.0, 100.0, &ai::layer("L", &format!("{raster}{place}")));
let samples: &[u8] = &[255, 0, 0, 0, 0, 255, 128, 0];
let preview: &[u8] = &[255, 255, 0, 0, 0, 0, 0, 0];
let mut data = Vec::new();
for (i, part) in text.split("@@").enumerate() {
if i > 0 {
data.extend_from_slice(if i == 1 { samples } else { preview });
}
data.extend_from_slice(part.as_bytes());
}
for &(i, b) in &edits {
let n = data.len();
if n > 0 {
data[i % n] = b;
}
}
data.truncate(cut.min(data.len()));
let private = [b"%AI24_ZStandard_Data".as_slice(), &ruzstd::encoding::compress_to_vec(data.as_slice(), ruzstd::encoding::CompressionLevel::Fastest)].concat();
survive("hostile .ai images and placed files", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?;
}
/// A `.ai` whose variable library is damaged or hostile: the library is counted for the warning
/// whether the layers are read or not (an inserted `Z` can make an operator the reader doesn't
/// handle, and then the layers aren't read).
@@ -3420,6 +3523,7 @@ proptest! {
], 0..12),
ended in any::<bool>(),
objects in prop::collection::vec((prop_oneof![arb_num(), prop::sample::select(vec!["1".to_string(), "6".into(), "9".into()])], prop::sample::select(vec!["A", "B", "", "Caf\u{e9}", "Missing"]), any::<bool>()), 0..6),
unit in prop::sample::select(vec![1.0, 2.0, 0.0, -1.0, f64::NAN, f64::INFINITY]),
) {
use vectorcraft_testkit::ai;
let style = |name: &str| {
@@ -3448,6 +3552,11 @@ proptest! {
survive("style lists and links", || Some(vectorcraft_eps::layered_ai(data.as_bytes(), Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?;
let eps = ai::eps(data.as_bytes(), ai::page_ps());
survive("style lists and links in an EPS", || vectorcraft_engine::cmd::fileio::load("x.eps", &eps).ok().map(|l| l.doc))?;
// A graphic style library: the styles and their list, no layers.
let library = ai::editing_data(200.0, 100.0, &header);
survive("style library", || Some(vectorcraft_eps::layered_ai(library.as_bytes(), Document::new(200.0, 100.0), vec![], false, false, unit).0))?;
let eps = ai::eps(library.as_bytes(), ai::page_ps());
survive("style library in an EPS", || vectorcraft_engine::cmd::fileio::load("x.eps", &eps).ok().map(|l| l.doc))?;
}
/// Objects on Path records of any shape: ids in any order, repeated or missing, any number of
@@ -3512,6 +3621,114 @@ proptest! {
Some(d)
})?;
}
/// A `.ai` whose symbols are damaged or hostile: their definitions, the symbol list and the
/// instances (on the page and in a symbol's art), cut short or edited.
#[test]
fn ai_symbols_never_panic(cut in 0usize..2_000, edits in prop::collection::vec((0usize..2_000, prop::sample::select(vec!['0', '9', '-', '.', 'e', ' ', '\n', '(', ')', '/', ':', ';', ',', '%', 'u', 'U', 'A', 'Z'])), 0..12)) {
let text = mutate_text(&symbols_text(), cut, &edits);
let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&text)].concat();
survive("mutated .ai symbols", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?;
survive("mutated .ai symbols, trusted", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0).0))?;
}
}
/// Editing data with two symbols (S2's art holds an instance of S1), the symbol list and a layer of
/// instances, as the format writes them.
fn symbols_text() -> String {
use vectorcraft_testkit::ai;
let def = |name: &str, art: &str, reg: u32| {
format!(
"%AI14_BeginSymbol\n({name})\n0 A\n0 Xw\n0 Ae\nu\n{art}U\n%_/ArtDictionary :\n%_{reg} /Int (AI13PatternRegistrationType) ,\n%_;\n%_\n9 () XW\n%AI10_EndSymbol\n"
)
};
let inst = |name: &str, m: &str| format!("/SymbolInstance :\n({name}) /SymbolRef ,\n{m} /RTransformMatrix\n;\n9 () XW\n");
let defs = def("S1", "0 1 1 0 1 0 0 Xa\n-2 -2 m\n2 -2 L\n2 2 L\n-2 2 L\nf\n", 5) + &def("S2", &inst("S1", "1 0 0 -1 -8081 8237"), 1);
let list = "%AI24_BeginSymbolList\n(S2)\n(S1)\n%AI24_EndSymbolList\n";
let page = ai::layer(
"L",
&format!(
"1 Xw\n{}0 Xw\n{}1 0.5 0 2 0 Xy\n0 0 Xd\n6 () XW\n0 Ae\nq\n{}10 10 m\n30 10 L\n30 30 L\nh\nW\nn\nQ\n",
inst("S1", "1 0 0 -1 20 50"),
inst("S2", "2 0 0 -2 100 50"),
inst("S1", "1 0 0 -1 20 20")
),
);
let data = ai::editing_data(
200.0,
100.0,
&format!("%AI5_Begin_NonPrinting\n{defs}%AI5_End_NonPrinting--\n%AI5_Begin_NonPrinting\n{list}%AI5_End_NonPrinting--\n{page}"),
);
data.replacen("%%EndComments", "%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n%%EndComments", 1)
}
/// The data [`ai_symbols_never_panic`] damages, as it is, opens with its symbols and instances live.
#[test]
fn the_symbols_fuzz_data_opens_live() {
let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&symbols_text())].concat();
let (doc, warnings, layered) = vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0);
assert!(layered, "{warnings:?}");
let names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect();
assert_eq!(names, ["S2", "S1"]);
let mut instances = 0;
doc.walk(|n| instances += usize::from(matches!(n.kind, vectorcraft_doc::NodeKind::SymbolInstance { .. })));
assert_eq!(instances, 3);
}
/// Symbols the reader must stop at: sections that don't end, references and matrices it can't
/// use, definitions nested deeper than it reads, and symbols that hold each other.
#[test]
fn ai_symbol_limits_never_panic() {
use vectorcraft_testkit::ai;
let inst = |name: &str, m: &str| format!("/SymbolInstance :\n{name} /SymbolRef ,\n{m} /RTransformMatrix\n;\n");
let def = |name: &str, art: &str| format!("%AI14_BeginSymbol\n({name})\n0 A\n0 Xw\n0 Ae\nu\n{art}U\n%AI10_EndSymbol\n");
let mut nested = String::new();
for i in 0..400 {
nested.push_str(&format!("%AI14_BeginSymbol\n(N{i})\n0 Ae\nu\n"));
}
for _ in 0..400 {
nested.push_str("U\n%AI10_EndSymbol\n");
}
let mut chain = String::new();
for i in 0..300 {
chain.push_str(&def(&format!("C{i}"), &inst(&format!("(C{})", i + 1), "1 0 0 -1 0 0")));
}
let cases = [
format!("%AI14_BeginSymbol\n(Open)\n0 Ae\nu\n{}", ai::layer("L", &inst("(Open)", "1 0 0 -1 20 50"))),
format!("%AI24_BeginSymbolList\n(A)\n(B)\n{}", ai::layer("L", "")),
format!(
"{}{}",
def("S", "-2 -2 m\n2 2 L\nS\n"),
ai::layer("L", &(inst("", "1 0 0 -1 20 50") + &inst("/SymbolRef", "1 0 0 -1 20 50") + &inst("(S)", "")))
),
format!(
"{}{}",
def("S", "-2 -2 m\n2 2 L\nS\n"),
ai::layer(
"L",
&(inst("(S)", "1 0 0") + &inst("(S)", "1 0 0 -1 20 50 7") + &inst("(S)", "1e400 0 0 -1 20 50") + &inst("(S)", "0 0 0 0 20 50"))
)
),
format!("{nested}{}", ai::layer("L", &inst("(N0)", "1 0 0 -1 20 50"))),
format!("{chain}{}", ai::layer("L", &inst("(C0)", "1 0 0 -1 20 50"))),
format!(
"{}{}{}",
def("S1", &inst("(S2)", "1 0 0 -1 0 0")),
def("S2", &inst("(S1)", "1 0 0 -1 0 0")),
ai::layer("L", &inst("(S1)", "1 0 0 -1 20 50"))
),
format!("{}{}", def("S1", &inst("(S2)", "1 0 0 -1 0 0")), def("S2", &inst("(S1)", "1 0 0 -1 0 0"))),
];
for body in cases {
let data = ai::editing_data(200.0, 100.0, &body).replacen("%%EndComments", "%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n%%EndComments", 1);
let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&data)].concat();
survive("hostile .ai symbols", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, false, 1.0).0))
.unwrap();
survive("hostile .ai symbols, trusted", || {
Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0).0)
})
.unwrap();
}
}
/// The data [`ai_objects_on_path_never_panics`] damages, as it is, opens with its Objects on Path group.
@@ -3657,6 +3874,19 @@ proptest! {
let text = mutate_text(&fixture, cut, &edits);
survive("mutated PostScript-form .ai with placed files", || vectorcraft_engine::cmd::fileio::load("x.ai", text.as_bytes()).ok().map(|l| l.doc))?;
}
/// The same file with linked images in the version 7 form (`XG`, then `XF` with no samples),
/// one with an embedded image between its `XG` and `XF`, damaged.
#[test]
fn ps_form_ai_with_linked_images_never_panics(cut in 0usize..1_400, edits in prop::collection::vec((0usize..1_400, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '(', ')', '[', ']', '%', 'X', 'F', 'G'])), 0..12)) {
let linked = "%AI5_File:\n%AI5_BeginRaster\n(a.tif) 0 XG\n[ 2 0 0 3 10 80 ] 0 0 10 20 10 20 8 3 0 0 0 0 XF\n%AI5_EndRaster\n\
%AI5_File:\n%AI5_BeginRaster\n(b.tif) 1 XG\n[ 1 0 0 1 0 100 ] 0 0 1 1 1 1 8 3 0 0 0 0 XI\n%FF0000\n%AI5_EndRaster\n\
[ 0 1 -1 0 50 50 ] 0 0 4 4 4 4 8 3 0 0 0 0 XF\n";
let fixture = NAMED_PROLOG_AI.replacen("0 Ap\nu\n", &format!("0 Ap\n{linked}u\n"), 1);
prop_assert!(fixture.contains("(a.tif)"));
let text = mutate_text(&fixture, cut, &edits);
survive("mutated PostScript-form .ai with linked images", || vectorcraft_engine::cmd::fileio::load("x.ai", text.as_bytes()).ok().map(|l| l.doc))?;
}
}
/// A `.ai` in the legacy format without layers (Illustrator 3) whose prolog is included: its
@@ -3722,6 +3952,47 @@ proptest! {
}
}
/// Area type in the version 7 form (§15.5.3) whose story flows through two linked areas: a small
/// one, and one a quarter turn round, each area's characters after its `TP`.
const LINKED_AREAS: &str = "1 To\n1 0 0 1 120 90 0 Tp\n120 60 m\n120 90 L\n180 90 L\n180 60 L\n120 60 L\nn\nTP\n0 Tr\n0 g\n/_Helvetica 9 Tf\n\
(one two three four five six seven eight nine ten ) Tx\n0 1 -1 0 190 10 0 Tp\n130 10 m\n130 55 L\n190 55 L\n190 10 L\n130 10 L\nn\nTP\n\
(eleven twelve thirteen fourteen fifteen) Tx\n(\\r) TX\nTO\n";
/// [`NAMED_PROLOG_AI`] with `text` on its layer.
fn linked_areas_ai(text: &str) -> String {
NAMED_PROLOG_AI.replace("u\n0.5 g\n", &format!("{text}u\n0.5 g\n"))
}
/// The fixture, as it is, opens with its area type as two threaded frames, the story flowing from
/// the first into the second.
#[test]
fn the_linked_areas_fixture_opens_as_threaded_frames() {
let l = vectorcraft_engine::cmd::fileio::load("x.ai", linked_areas_ai(LINKED_AREAS).as_bytes()).unwrap();
let [thread] = &l.doc.text_threads[..] else { panic!("one thread: {:?} {:?}", l.doc.text_threads, l.warnings) };
let texts: Vec<String> = thread
.iter()
.map(|id| match &l.doc.node(*id).unwrap().kind {
vectorcraft_doc::NodeKind::Text(t) => t.plain_text(),
k => panic!("type: {k:?}"),
})
.collect();
let [first, second] = texts.as_slice() else { panic!("two frames: {texts:?}") };
assert!(!first.is_empty() && !second.is_empty(), "the story flows on into the second frame: {texts:?}");
assert_eq!(format!("{first}{second}"), "one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen");
}
proptest! {
#![proptest_config(config())]
/// That `.ai` with its linked areas damaged (their text paths, frames and characters): read, or
/// refused.
#[test]
fn ps_form_ai_linked_areas_never_panic(cut in 0usize..400, edits in prop::collection::vec((0usize..400, prop::sample::select(vec!['0', '1', '-', '.', ' ', '\n', '(', ')', '\\', 'T', 'p', 'P', 'O', 'o', 'x', 'X', 'm', 'L', 'n'])), 0..12)) {
let text = linked_areas_ai(&mutate_text(LINKED_AREAS, cut, &edits));
survive("PostScript-form .ai with damaged linked areas", || vectorcraft_engine::cmd::fileio::load("x.ai", text.as_bytes()).ok().map(|l| l.doc))?;
}
}
/// An operand of a layer's options (`Lb`): a flag, a colour index or component, a percentage, or
/// anything else.
fn arb_layer_operand() -> impl Strategy<Value = String> {
@@ -3784,6 +4055,12 @@ fn arb_ai_token() -> impl Strategy<Value = String> {
"*U",
"q",
"Q",
// Several clipping paths in one clipping group or layer clip to their intersection (AI7 spec §5.6.2), each
// nesting a clipping group.
"0 0 m 9 0 L 9 9 L h W n 1 1 m 8 1 L 8 8 L h W f",
"q 0 0 m 9 0 L 9 9 L h W n 1 1 m 8 1 L 8 8 L h W n 0 0 m 5 5 L 0 5 L f Q",
"u 0 0 m 9 0 L 9 9 L h W n 1 1 m 8 1 L 8 8 L h W n U",
"q 0 0 m 9 0 L 9 9 L h W n 0 0 m 9 0 L 9 9 L h W n 0 0 m 9 0 L 9 9 L h W n 0 0 m 9 0 L 9 9 L h W n 0 0 m 9 0 L 9 9 L h W n 0 0 m 9 0 L 9 9 L h W n 0 0 m 9 0 L 9 9 L h W n 0 0 m 9 0 L 9 9 L h W n",
"LB",
"Lb",
"Ln",
@@ -3816,6 +4093,12 @@ fn arb_ai_token() -> impl Strategy<Value = String> {
"\n%AI3_Note:\n",
"\n%AI5_NoteMore:more\n",
"\n%%Note:old\n",
// Object tags (version 7 §7).
"XT",
"/AdobeURL (https://example.com) XT",
"/tag () XT",
"/ (x) XT",
"(x) (y) XT",
"w",
"J",
"j",
@@ -3854,6 +4137,12 @@ fn arb_ai_token() -> impl Strategy<Value = String> {
"[ 1 0 0 1 0 0 ] 0 0 2 2 2 2 8 3 1 0 1 0",
"[ 1 0 0 1 0 0 ] 0 0 3 2 3 2 1 4 1 0 1 0",
"[ 1 0 0 1 0 0 ] 0 0 99999 99999 99999 99999 1 1 0 0 0 0",
// A linked image in the version 7 form (§8.2, §8.3): `(path) modified XG`, then `XF`.
"XG",
"(a.tif) 0 XG",
"XF",
"[ 1 0 0 1 0 0 ] 0 0 2 2 2 2 8 3 0 0 0 0 XF",
"[ 1e308 0 0 1e308 0 0 ] 0 0 1e6 1e6 1e6 1e6 8 3 0 0 0 0 XF",
"[",
"]",
"/Name",
@@ -3906,7 +4195,17 @@ fn arb_ai_token() -> impl Strategy<Value = String> {
"(\\r) TX",
"() Tj",
"(x) Tx",
"(\\t) 1 TS",
"() /x TS",
"Te",
"0 0 1e308 -1e308 Te",
"TM",
"7 Tr",
"4 Tr",
"9 Tr",
"4.5 Tr",
"*w",
"*W",
"-1e308 Ts",
"1e308 0 Tz",
"1e308 Tt",
@@ -3922,10 +4221,23 @@ fn arb_ai_token() -> impl Strategy<Value = String> {
"7 Tq",
"1 1 1e308 -1e308 4e9 Th",
"1 1 (2) 3 4 Th",
"36 2 Xb",
"Xb",
"0 0 4 1e308 Xe",
"0 0 2 -1e308 Xe",
"0 0 3 72 Xe",
"0 0 1e308 72 Xe",
"(x) /y Xe",
"XB",
"[39/quotesingle 128/Euro/eacute/nosuch 300/x TE",
"[1e308/a -1/b TE",
"\n%AI3_BeginEncoding: _Helvetica Helvetica\n[/_Helvetica/Helvetica 0 0 1 TZ\n%AI3_EndEncoding AdobeType\n",
"\n%AI3_BeginEncoding:\n",
"[ 39/quotesingle 1e308/a -1/b 200/eacute\n/_Helvetica/Helvetica 0 0 1 [0.5 1e308] TZ",
"/_ 0 TZ",
"[ ] ] [ /a /b (c) TZ",
"\n%AI3_EndEncoding AdobeType\n",
"\n%%BeginEncoding: _x x\n[ 39/grave\n/_x/x 0 1 TZ\n%%EndEncoding\n",
"800 Ar",
"frobnicate",
"\n%AI5_BeginLayer\n",
@@ -4125,6 +4437,15 @@ fn arb_ai_token() -> impl Strategy<Value = String> {
"\n%\n",
"\n%AI5_EndPlace\n",
"\n%%PageTrailer\n",
"\n%AI14_BeginSymbol\n(S1)\n0 A 0 Xw 0 Ae\n",
"\n%AI10_EndSymbol\n",
"\n%AI24_BeginSymbolList\n(S1)\n",
"\n%AI24_EndSymbolList\n",
"/SymbolInstance :",
"(S1) /SymbolRef ,",
"/RTransformMatrix",
"5 /Int (AI13PatternRegistrationType) ,",
"; (AI19SymbolAppearanceMap) ,",
])
.prop_map(str::to_string),
]
@@ -4343,8 +4664,9 @@ proptest! {
/// Art styles with a Distort & Transform effect (Transform, Free Distort, Pucker & Bloat, Roughen,
/// Tweak, Twist, Zig Zag) whose dictionary holds any of its entries, and unknown ones, as any kind,
/// with any value (huge, tiny, not a number, a string), repeated or left out, on a path and on type,
/// on the whole object or on its fill.
/// with any value (huge, tiny, not a number, a string), repeated or left out, on a path, on type and
/// on a group nested any number of levels around a curved path, stroked or not, on the whole object
/// or on its fill.
#[test]
fn ai_distort_effects_never_panic(
name in prop::sample::select(vec![
@@ -4371,6 +4693,8 @@ proptest! {
],
), 0..24),
on_fill in any::<bool>(),
depth in 0usize..300,
stroked in any::<bool>(),
) {
use vectorcraft_testkit::ai;
let keys: String = entries.iter().map(|(k, kind, v)| format!("{v} /{kind} ({k}) ,\n")).collect();
@@ -4385,10 +4709,15 @@ proptest! {
};
let styles = format!("%AI9_BeginArtStyles\n/KnownStyle :\n(Fx) /Name ,\n/ActiveStyle :\n{root}%AI9_EndArtStyles\n");
let hidden = ai::rect(20.0, 20.0, 80.0, 60.0).replace('\n', "\n%_");
let paint = if stroked { "0 0 1 0 K\n2 w\nB\n" } else { "f\n" };
let curve = format!("0 0 1 0 k\n20 70 m\n20 90 80 90 80 70 c\n80 50 20 50 20 70 c\n{paint}");
let nested = format!("0 Ae\n{}{curve}{}", "u\n".repeat(depth + 1), "U\n".repeat(depth + 1)).replace('\n', "\n%_");
let art = format!(
"0 Ae\nu\n0 0 1 0 k\n{}f\nU\n%_{hidden}f\n1 (Fx) XW\nu\n/AI11Text :\n1 /FreeUndo ,\n;\n0 0 1 0 k\n{}f\nU\n1 (Fx) XW\n",
"0 Ae\nu\n0 0 1 0 k\n{}f\nU\n%_{hidden}f\n1 (Fx) XW\nu\n/AI11Text :\n1 /FreeUndo ,\n;\n0 0 1 0 k\n{}f\nU\n1 (Fx) XW\n\
0 Ae\nu\n0 0 1 0 k\n{}f\nU\n%_{nested}1 (Fx) XW\n",
ai::rect(20.0, 20.0, 80.0, 60.0),
ai::rect(100.0, 20.0, 180.0, 60.0)
ai::rect(100.0, 20.0, 180.0, 60.0),
ai::rect(20.0, 50.0, 80.0, 90.0)
);
let data = ai::editing_data(200.0, 100.0, &format!("{styles}{}", ai::layer("L", &art)));
survive("distort art style", || Some(vectorcraft_eps::layered_ai(data.as_bytes(), Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?;
+21
View File
@@ -202,3 +202,24 @@ fn cut_direct_selected_anchors_retains_anchor_deletion() {
assert_eq!(s.active().unwrap().doc.node(a).unwrap().path_data().unwrap().anchor_count(), 3);
assert_eq!(s.active().unwrap().doc.parent_of(b), Some(c));
}
#[test]
fn clear_explicit_ids_preserves_unrelated_selection() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let r1 = NodeId(s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap());
let r2 = NodeId(s.execute("shape.rectangle", &json!({"x": 50, "y": 10, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [r1.0, r2.0]})).unwrap();
assert_eq!(s.active().unwrap().selection.objects, vec![r1, r2]);
// Clearing r1 explicitly should remove r1 from doc and from selection, keeping r2 selected.
s.execute("edit.clear", &json!({"ids": [r1.0]})).unwrap();
assert!(s.active().unwrap().doc.node(r1).is_none());
assert!(s.active().unwrap().doc.node(r2).is_some());
assert_eq!(s.active().unwrap().selection.objects, vec![r2]);
// Parameterless clear clears the rest of the selection.
s.execute("edit.clear", &json!({})).unwrap();
assert!(s.active().unwrap().doc.node(r2).is_none());
assert!(s.active().unwrap().selection.is_empty());
}
@@ -0,0 +1,806 @@
//! Direct-selection Copy and Cut tests (#2122).
use serde_json::{Value, json};
use vectorcraft_doc::{NodeId, NodeKind};
use vectorcraft_engine::Session;
use vectorcraft_geom::FillRule;
use vectorcraft_testkit::invariants::check_session;
fn run(s: &mut Session, command: &str, params: Value) -> Value {
s.execute(command, &params).unwrap()
}
fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId {
NodeId(run(s, "shape.rectangle", json!({"x": x, "y": y, "width": w, "height": h}))["id"].as_u64().unwrap())
}
#[test]
fn copy_and_paste_direct_selected_segment_of_rect() {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 200, "height": 200}));
let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0);
// Select segment 0 of the rectangle.
run(&mut s, "select.segments", json!({"id": r.0, "segments": [[0, 0]]}));
run(&mut s, "edit.copy", json!({}));
let pasted = run(&mut s, "edit.paste", json!({}));
let ids: Vec<u64> = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
assert_eq!(ids.len(), 1);
let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap();
if let NodeKind::Path { live, .. } = &pasted_node.kind {
assert!(live.is_none(), "extracted partial path must not retain live shape metadata");
}
let path = pasted_node.path_data().unwrap();
assert_eq!(path.subpaths.len(), 1);
let sp = &path.subpaths[0];
assert!(!sp.closed);
assert_eq!(sp.anchors.len(), 2);
}
#[test]
fn copy_and_paste_direct_selected_adjacent_anchors_of_rect() {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 200, "height": 200}));
let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0);
// Direct-select two adjacent anchors: 0 and 1.
run(&mut s, "select.anchors", json!({"id": r.0, "anchors": [[0, 0], [0, 1]], "mode": "set"}));
run(&mut s, "edit.copy", json!({}));
let pasted = run(&mut s, "edit.paste", json!({}));
let ids: Vec<u64> = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
assert_eq!(ids.len(), 1);
let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap();
let path = pasted_node.path_data().unwrap();
assert_eq!(path.subpaths.len(), 1);
let sp = &path.subpaths[0];
assert!(!sp.closed);
assert_eq!(sp.anchors.len(), 2);
}
#[test]
fn copy_single_anchor_of_rect_copies_three_anchors_with_two_segments() {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 200, "height": 200}));
let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0);
// Direct-select only anchor 1 of the closed 4-anchor rectangle.
run(&mut s, "select.anchors", json!({"id": r.0, "anchors": [[0, 1]], "mode": "set"}));
run(&mut s, "edit.copy", json!({}));
let pasted = run(&mut s, "edit.paste", json!({}));
let ids: Vec<u64> = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
assert_eq!(ids.len(), 1);
let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap();
let path = pasted_node.path_data().unwrap();
assert_eq!(path.subpaths.len(), 1);
let sp = &path.subpaths[0];
assert!(!sp.closed);
// Copying a single anchor on a closed path copies the anchor and both its incident segments.
assert_eq!(sp.anchors.len(), 3);
assert_eq!(sp.segment_count(), 2);
}
#[test]
fn copy_disjoint_segments_does_not_copy_unselected_segment_in_between() {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 200, "height": 200}));
let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0);
// Rectangle has 4 segments (0, 1, 2, 3). Select disjoint segments 0 and 2.
run(&mut s, "select.segments", json!({"id": r.0, "segments": [[0, 0], [0, 2]]}));
run(&mut s, "edit.copy", json!({}));
let pasted = run(&mut s, "edit.paste", json!({}));
let ids: Vec<u64> = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
// Two separate open path pieces should be created, each with 2 anchors.
assert_eq!(ids.len(), 2);
for id in ids {
let node = s.doc().unwrap().doc.node(NodeId(id)).unwrap();
let path = node.path_data().unwrap();
assert_eq!(path.subpaths.len(), 1);
let sp = &path.subpaths[0];
assert!(!sp.closed);
assert_eq!(sp.anchors.len(), 2);
}
}
#[test]
fn cut_direct_selected_segment_cuts_source_and_pastes_segment() {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 200, "height": 200}));
let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0);
// Select segment 0 and cut it.
run(&mut s, "select.segments", json!({"id": r.0, "segments": [[0, 0]]}));
run(&mut s, "edit.cut", json!({}));
// Source rectangle should now have segment 0 removed, turning it into an open path.
let src_node = s.doc().unwrap().doc.node(r).unwrap();
let src_path = src_node.path_data().unwrap();
assert_eq!(src_path.subpaths.len(), 1);
assert!(!src_path.subpaths[0].closed);
// Paste the cut segment:
let pasted = run(&mut s, "edit.paste", json!({}));
let ids: Vec<u64> = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
assert_eq!(ids.len(), 1);
let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap();
let pasted_path = pasted_node.path_data().unwrap();
assert_eq!(pasted_path.subpaths.len(), 1);
assert!(!pasted_path.subpaths[0].closed);
assert_eq!(pasted_path.subpaths[0].anchors.len(), 2);
}
#[test]
fn copy_compound_path_direct_selected_segment_inherits_appearance() {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 200, "height": 200}));
let outer = NodeId(run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 80, "height": 80}))["id"].as_u64().unwrap());
let inner = NodeId(run(&mut s, "shape.rectangle", json!({"x": 30, "y": 30, "width": 40, "height": 40}))["id"].as_u64().unwrap());
run(&mut s, "select.set", json!({"ids": [outer.0, inner.0]}));
let compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap());
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
// Select segment 0 of the inner member.
run(&mut s, "select.segments", json!({"id": inner.0, "segments": [[0, 0]]}));
run(&mut s, "edit.copy", json!({}));
let pasted = run(&mut s, "edit.paste", json!({}));
let ids: Vec<u64> = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
assert_eq!(ids.len(), 1);
let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap();
let compound_node = s.doc().unwrap().doc.node(compound).unwrap();
assert_eq!(pasted_node.appearance, compound_node.appearance);
}
#[test]
fn direct_selection_copy_preserves_fill_rule_and_attributes() {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 200, "height": 200}));
let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0);
run(&mut s, "path.setFillRule", json!({"rule": "evenOdd"}));
run(&mut s, "select.segments", json!({"id": r.0, "segments": [[0, 0]]}));
run(&mut s, "edit.copy", json!({}));
let pasted = run(&mut s, "edit.paste", json!({}));
let ids: Vec<u64> = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap();
assert!(matches!(pasted_node.kind, NodeKind::Path { rule: FillRule::EvenOdd, .. }));
}
#[test]
fn pen_tool_drawing_copies_whole_path_not_single_anchor() {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 200, "height": 200}));
// Start drawing with Pen tool
s.select_tool("pen", vectorcraft_engine::ViewInfo::default()).unwrap();
let id = NodeId(run(&mut s, "path.create", json!({"anchors": [{"x": 10, "y": 10}]}))["id"].as_u64().unwrap());
run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 50, "y": 10}));
run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 50, "y": 50}));
// Pen tool has the last anchor in sel.anchors, but active tool is pen
run(&mut s, "edit.copy", json!({}));
let pasted = run(&mut s, "edit.paste", json!({}));
let ids: Vec<u64> = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
assert_eq!(ids.len(), 1);
// The whole 3-point path must be copied, not just the last anchor!
let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap();
let path = pasted_node.path_data().unwrap();
assert_eq!(path.subpaths[0].anchors.len(), 3);
}
#[test]
fn cut_adjacent_anchors_clipboard_plus_remaining_equals_original() {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 200, "height": 200}));
let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0);
// Direct-select two adjacent anchors: 1 and 2 of the 4-anchor rectangle.
run(&mut s, "select.anchors", json!({"id": r.0, "anchors": [[0, 1], [0, 2]], "mode": "set"}));
run(&mut s, "edit.cut", json!({}));
// Cut placed 1 segment on the clipboard (anchors 1 to 2).
assert_eq!(s.clipboard.nodes.len(), 1);
let clip_path = s.clipboard.nodes[0].path_data().unwrap();
assert_eq!(clip_path.subpaths[0].segment_count(), 1);
assert_eq!(clip_path.subpaths[0].anchors.len(), 2);
// Remaining source path must have the remaining 3 segments (segments 0, 2, 3), not 1.
let src_node = s.doc().unwrap().doc.node(r).unwrap();
let src_path = src_node.path_data().unwrap();
assert_eq!(src_path.subpaths[0].segment_count(), 3);
assert_eq!(src_path.subpaths[0].anchors.len(), 4);
assert!(!src_path.subpaths[0].closed);
// Sum of segments in clipboard + remaining = 1 + 3 = 4 (the original 4 segments).
assert_eq!(clip_path.subpaths[0].segment_count() + src_path.subpaths[0].segment_count(), 4);
}
#[test]
fn copy_non_adjacent_anchors_on_rect_copies_full_object() {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 200, "height": 200}));
let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0);
// Select non-adjacent anchors 1 and 3 of the 4-anchor rectangle.
// Incident segments for anchor 1 are segments 0 and 1; for anchor 3 are segments 2 and 3.
// Together they cover all 4 segments, so the path is copied whole.
run(&mut s, "select.anchors", json!({"id": r.0, "anchors": [[0, 1], [0, 3]], "mode": "set"}));
run(&mut s, "edit.copy", json!({}));
let pasted = run(&mut s, "edit.paste", json!({}));
let ids: Vec<u64> = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
assert_eq!(ids.len(), 1);
let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap();
if let NodeKind::Path { live, .. } = &pasted_node.kind {
assert!(live.is_some(), "copying all segments keeps live shape metadata");
}
let path = pasted_node.path_data().unwrap();
assert!(path.subpaths[0].closed);
assert_eq!(path.subpaths[0].segment_count(), 4);
}
#[test]
fn copy_non_adjacent_anchors_on_five_point_path_extracts_selected_segments() {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 200, "height": 200}));
let id = NodeId(run(&mut s, "path.create", json!({"anchors": [{"x": 10, "y": 10}]}))["id"].as_u64().unwrap());
run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 50, "y": 10}));
run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 60, "y": 50}));
run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 30, "y": 80}));
run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 10, "y": 50}));
run(&mut s, "path.close", json!({"id": id.0}));
// Path has 5 anchors (0..4) and 5 segments (0..4).
// Select non-adjacent anchors 1 and 3.
// Anchor 1 gives segments 0, 1. Anchor 3 gives segments 2, 3. Segment 4 is unselected.
run(&mut s, "select.anchors", json!({"id": id.0, "anchors": [[0, 1], [0, 3]], "mode": "set"}));
run(&mut s, "edit.copy", json!({}));
let pasted = run(&mut s, "edit.paste", json!({}));
let ids: Vec<u64> = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
assert_eq!(ids.len(), 1);
let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap();
let path = pasted_node.path_data().unwrap();
assert!(!path.subpaths[0].closed);
assert_eq!(path.subpaths[0].segment_count(), 4);
assert_eq!(path.subpaths[0].anchors.len(), 5);
}
#[test]
fn copy_when_all_segments_selected_preserves_live_shape() {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 200, "height": 200}));
let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0);
// Select all 4 segments explicitly (like Select > Object > Direction Handles).
run(&mut s, "select.segments", json!({"id": r.0, "segments": [[0, 0], [0, 1], [0, 2], [0, 3]]}));
run(&mut s, "edit.copy", json!({}));
let pasted = run(&mut s, "edit.paste", json!({}));
let ids: Vec<u64> = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
assert_eq!(ids.len(), 1);
let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap();
if let NodeKind::Path { live, .. } = &pasted_node.kind {
assert!(live.is_some(), "all segments selected preserves live shape");
}
}
#[test]
fn compound_member_selected_whole_with_direct_selection_promotes_member() {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 200, "height": 200}));
let outer = NodeId(run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 80, "height": 80}))["id"].as_u64().unwrap());
let inner = NodeId(run(&mut s, "shape.rectangle", json!({"x": 30, "y": 30, "width": 40, "height": 40}))["id"].as_u64().unwrap());
run(&mut s, "select.set", json!({"ids": [outer.0, inner.0]}));
let compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap());
let standalone = rect(&mut s, 120.0, 10.0, 50.0, 50.0);
// Select outer compound member whole, and direct-select anchor 0 on standalone.
let outer_anchors: Vec<Vec<usize>> = (0..4).map(|i| vec![0, i]).collect();
run(
&mut s,
"select.anchorsMany",
json!({
"items": [
{"id": outer.0, "anchors": outer_anchors},
{"id": standalone.0, "anchors": [[0, 0]]}
]
}),
);
// outer is selected whole, standalone is partially selected.
assert!(s.active().unwrap().selection.partial(outer).is_none());
assert!(s.active().unwrap().selection.partial(standalone).is_some());
run(&mut s, "edit.copy", json!({}));
// Clipboard should have:
// 1. The compound path (outer promoted to compound #786)
// 2. The extracted segment piece from standalone
let clip_ids: Vec<NodeId> = s.clipboard.nodes.iter().map(|n| n.id).collect();
assert_eq!(clip_ids.len(), 2, "promoted compound plus the extracted standalone piece");
assert!(clip_ids.contains(&compound), "whole compound member must be promoted to compound parent");
}
#[test]
fn cut_whole_compound_member_with_direct_selection_cuts_compound_and_extracted_piece() {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 200, "height": 200}));
let outer = NodeId(run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 80, "height": 80}))["id"].as_u64().unwrap());
let inner = NodeId(run(&mut s, "shape.rectangle", json!({"x": 30, "y": 30, "width": 40, "height": 40}))["id"].as_u64().unwrap());
run(&mut s, "select.set", json!({"ids": [outer.0, inner.0]}));
let compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap());
let standalone = NodeId(run(&mut s, "shape.rectangle", json!({"x": 100, "y": 100, "width": 50, "height": 50}))["id"].as_u64().unwrap());
let outer_anchors = (0..4).map(|i| vec![0, i]).collect::<Vec<_>>();
run(
&mut s,
"select.anchorsMany",
json!({
"items": [
{"id": outer.0, "anchors": outer_anchors},
{"id": standalone.0, "anchors": [[0, 0]]}
]
}),
);
run(&mut s, "edit.cut", json!({}));
let clip_ids: Vec<NodeId> = s.clipboard.nodes.iter().map(|n| n.id).collect();
assert_eq!(clip_ids.len(), 2, "promoted compound plus the extracted standalone piece");
assert!(clip_ids.contains(&compound), "whole compound member must be promoted to compound parent");
// Compound was removed because member was selected whole
let doc = &s.doc().unwrap().doc;
assert!(doc.node(compound).is_none(), "compound path must be removed on cut");
// Standalone has cut pieces remaining
assert!(doc.node(standalone).is_some(), "partially cut standalone path remains");
}
#[test]
fn cut_direct_selected_only_path_in_layer_preserves_layer() {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 200, "height": 200}));
// Create a new layer
let layer_id = NodeId(run(&mut s, "layer.new", json!({}))["id"].as_u64().unwrap());
// Create a path inside the layer
let rect = NodeId(run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50}))["id"].as_u64().unwrap());
let doc = &s.doc().unwrap().doc;
assert_eq!(doc.parent_of(rect), Some(layer_id));
// Direct-select all 4 anchors of rect and cut
let all_anchors = (0..4).map(|i| vec![0, i]).collect::<Vec<_>>();
run(&mut s, "select.anchors", json!({"id": rect.0, "anchors": all_anchors, "mode": "set"}));
run(&mut s, "edit.cut", json!({}));
// The rect was cut, but the layer must NOT be deleted
let doc = &s.doc().unwrap().doc;
assert!(doc.node(rect).is_none(), "rect was cut");
assert!(doc.node(layer_id).is_some(), "layer must remain even when empty");
assert_eq!(doc.node(layer_id).unwrap().children().unwrap().len(), 0);
}
#[test]
fn copy_and_paste_path_in_compound_path_isolation_adds_member_to_compound() {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 200, "height": 200}));
let outer = NodeId(run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 80, "height": 80}))["id"].as_u64().unwrap());
let inner = NodeId(run(&mut s, "shape.rectangle", json!({"x": 30, "y": 30, "width": 40, "height": 40}))["id"].as_u64().unwrap());
run(&mut s, "select.set", json!({"ids": [outer.0, inner.0]}));
let compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap());
// Enter isolation mode on the compound path.
run(&mut s, "object.isolate", json!({"id": compound.0}));
assert_eq!(s.doc().unwrap().isolation, Some(compound));
// In isolation mode, select member `inner` whole.
run(&mut s, "select.set", json!({"ids": [inner.0]}));
run(&mut s, "edit.copy", json!({}));
// Clipboard copies the selected member path, NOT the entire compound path.
assert_eq!(s.clipboard.nodes.len(), 1);
assert_eq!(s.clipboard.nodes[0].id, inner);
// Paste in isolation mode: the pasted path must be inserted into the compound path,
// not as a new path beside the compound path.
let pasted = run(&mut s, "edit.paste", json!({}));
let ids: Vec<u64> = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
assert_eq!(ids.len(), 1);
let pasted_id = NodeId(ids[0]);
let doc = &s.doc().unwrap().doc;
assert_eq!(doc.parent_of(pasted_id), Some(compound), "pasted path must be added to the compound path");
let compound_node = doc.node(compound).unwrap();
assert_eq!(compound_node.children().unwrap().len(), 3, "compound path now has 3 member paths");
}
#[test]
fn cut_and_paste_direct_selected_anchors_in_compound_path_isolation() {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 200, "height": 200}));
let outer = NodeId(run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 80, "height": 80}))["id"].as_u64().unwrap());
let inner = NodeId(run(&mut s, "shape.rectangle", json!({"x": 30, "y": 30, "width": 40, "height": 40}))["id"].as_u64().unwrap());
run(&mut s, "select.set", json!({"ids": [outer.0, inner.0]}));
let compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap());
// Enter isolation mode on the compound path.
run(&mut s, "object.isolate", json!({"id": compound.0}));
// Direct-select anchor 0 of `inner` and cut.
run(&mut s, "select.anchors", json!({"id": inner.0, "anchors": [[0, 0]], "mode": "set"}));
run(&mut s, "edit.cut", json!({}));
// Clipboard holds the cut segment piece.
assert_eq!(s.clipboard.nodes.len(), 1);
// Paste inside isolation mode:
let pasted = run(&mut s, "edit.paste", json!({}));
let ids: Vec<u64> = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
assert_eq!(ids.len(), 1);
let pasted_id = NodeId(ids[0]);
let doc = &s.doc().unwrap().doc;
assert_eq!(doc.parent_of(pasted_id), Some(compound), "cut and pasted anchors must be inserted into compound path");
let compound_node = doc.node(compound).unwrap();
assert_eq!(compound_node.children().unwrap().len(), 3);
check_session(&s).unwrap();
}
#[test]
fn paste_non_path_in_compound_path_isolation_inserts_into_layer() {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 200, "height": 200}));
let a = rect(&mut s, 10.0, 10.0, 40.0, 40.0);
let b = rect(&mut s, 60.0, 10.0, 40.0, 40.0);
run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
let _group = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap());
// Copy the group to the clipboard.
run(&mut s, "edit.copy", json!({}));
// Create a compound path on the layer.
let c1 = rect(&mut s, 10.0, 100.0, 80.0, 80.0);
let c2 = rect(&mut s, 30.0, 120.0, 40.0, 40.0);
run(&mut s, "select.set", json!({"ids": [c1.0, c2.0]}));
let compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap());
let layer_id = s.doc().unwrap().doc.parent_of(compound).unwrap();
// Isolate the compound path.
run(&mut s, "object.isolate", json!({"id": compound.0}));
assert_eq!(s.doc().unwrap().isolation, Some(compound));
// Generic insertion parent inside compound isolation resolves to the layer, not the compound.
assert_eq!(s.doc().unwrap().insertion_parent(), Some(layer_id));
// Paste the group while in compound path isolation.
// The group cannot be inserted into the compound path; it must be pasted into the layer beside the compound.
let pasted = run(&mut s, "edit.paste", json!({}));
let ids: Vec<u64> = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
assert_eq!(ids.len(), 1);
let pasted_group = NodeId(ids[0]);
let doc = &s.doc().unwrap().doc;
assert_eq!(doc.parent_of(pasted_group), Some(layer_id), "pasted group must be added to layer, not compound");
let compound_node = doc.node(compound).unwrap();
assert_eq!(compound_node.children().unwrap().len(), 2, "compound path must keep only its 2 path children");
// All document invariants (including compound children being paths only) must hold.
check_session(&s).unwrap();
}
#[test]
fn shape_creation_in_compound_path_isolation_inserts_into_layer() {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 200, "height": 200}));
let outer = rect(&mut s, 10.0, 10.0, 80.0, 80.0);
let inner = rect(&mut s, 30.0, 30.0, 40.0, 40.0);
run(&mut s, "select.set", json!({"ids": [outer.0, inner.0]}));
let compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap());
// Isolate the compound path.
run(&mut s, "object.isolate", json!({"id": compound.0}));
// Draw a new rectangle while isolating the compound path.
let new_rect = rect(&mut s, 40.0, 40.0, 20.0, 20.0);
let doc = &s.doc().unwrap().doc;
assert_ne!(doc.parent_of(new_rect), Some(compound), "new shape path is placed outside compound path in layer");
let compound_node = doc.node(compound).unwrap();
assert_eq!(compound_node.children().unwrap().len(), 2, "compound path maintains original member paths");
check_session(&s).unwrap();
}
#[test]
fn paste_compound_into_isolated_compound_preserves_child_order() {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 300, "height": 300}));
let r1 = rect(&mut s, 10.0, 10.0, 10.0, 10.0);
let r2 = rect(&mut s, 30.0, 10.0, 10.0, 10.0);
let r3 = rect(&mut s, 50.0, 10.0, 10.0, 10.0);
run(&mut s, "select.set", json!({"ids": [r1.0, r2.0, r3.0]}));
let src_compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap());
// Copy src_compound (contains [r1, r2, r3] in order)
run(&mut s, "select.set", json!({"ids": [src_compound.0]}));
run(&mut s, "edit.copy", json!({}));
// Create target compound
let t1 = rect(&mut s, 100.0, 100.0, 80.0, 80.0);
let t2 = rect(&mut s, 120.0, 120.0, 40.0, 40.0);
run(&mut s, "select.set", json!({"ids": [t1.0, t2.0]}));
let target_compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap());
// Isolate target compound and select member t1 so paste-in-front targets index 1
run(&mut s, "object.isolate", json!({"id": target_compound.0}));
run(&mut s, "select.set", json!({"ids": [t1.0]}));
// Paste in front of t1
let pasted = run(&mut s, "edit.pasteInFront", json!({}));
let ids: Vec<u64> = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
assert_eq!(ids.len(), 3, "unpacked all 3 children");
let doc = &s.doc().unwrap().doc;
let target_node = doc.node(target_compound).unwrap();
let children = target_node.children().unwrap();
assert_eq!(children.len(), 5);
// Verify the 3 pasted children appear in children in exact forward order [r1_copy, r2_copy, r3_copy]
let child_ids: Vec<u64> = children.iter().map(|c| c.id.0).collect();
let pos0 = child_ids.iter().position(|&id| id == ids[0]).unwrap();
let pos1 = child_ids.iter().position(|&id| id == ids[1]).unwrap();
let pos2 = child_ids.iter().position(|&id| id == ids[2]).unwrap();
assert_eq!(pos1, pos0 + 1, "child 1 must immediately follow child 0");
assert_eq!(pos2, pos1 + 1, "child 2 must immediately follow child 1");
check_session(&s).unwrap();
}
#[test]
fn copy_and_paste_direct_selected_segment_of_open_path() {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 200, "height": 200}));
let id = NodeId(run(&mut s, "path.create", json!({"anchors": [{"x": 10, "y": 20}]}))["id"].as_u64().unwrap());
run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 60, "y": 20}));
run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 100, "y": 80}));
run(&mut s, "select.set", json!({"ids": [id.0]}));
run(&mut s, "paint.setStroke", json!({"color": "#0000ff"}));
run(&mut s, "stroke.set", json!({"weight": 4.0}));
// Select segment 0 of the open path (from (10, 20) to (60, 20)).
run(&mut s, "select.segments", json!({"id": id.0, "segments": [[0, 0]]}));
run(&mut s, "edit.copy", json!({}));
// Paste in place: position and appearance must be preserved.
let pasted = run(&mut s, "edit.pasteInPlace", json!({}));
let ids: Vec<u64> = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
assert_eq!(ids.len(), 1);
let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap();
let src_node = s.doc().unwrap().doc.node(id).unwrap();
assert_eq!(pasted_node.appearance, src_node.appearance, "appearance (stroke & fill) must match source");
let path = pasted_node.path_data().unwrap();
assert_eq!(path.subpaths.len(), 1);
let sp = &path.subpaths[0];
assert!(!sp.closed);
assert_eq!(sp.segment_count(), 1);
assert_eq!(sp.anchors.len(), 2);
assert_eq!(sp.anchors[0].p.x, 10.0);
assert_eq!(sp.anchors[0].p.y, 20.0);
assert_eq!(sp.anchors[1].p.x, 60.0);
assert_eq!(sp.anchors[1].p.y, 20.0);
check_session(&s).unwrap();
}
#[test]
fn copy_two_non_adjacent_segments_of_open_path_pastes_two_paths() {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 300, "height": 200}));
let id = NodeId(run(&mut s, "path.create", json!({"anchors": [{"x": 10, "y": 10}]}))["id"].as_u64().unwrap());
run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 40, "y": 10}));
run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 80, "y": 10}));
run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 120, "y": 10}));
run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 160, "y": 10}));
// Path has 5 anchors (0..4) and 4 segments (0..3).
// Select disjoint/non-adjacent segments 0 and 2.
run(&mut s, "select.segments", json!({"id": id.0, "segments": [[0, 0], [0, 2]]}));
run(&mut s, "edit.copy", json!({}));
let pasted = run(&mut s, "edit.paste", json!({}));
let ids: Vec<u64> = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
assert_eq!(ids.len(), 2, "two non-adjacent segments paste as two independent paths");
for node_id in ids {
let node = s.doc().unwrap().doc.node(NodeId(node_id)).unwrap();
let path = node.path_data().unwrap();
assert_eq!(path.subpaths.len(), 1);
assert!(!path.subpaths[0].closed);
assert_eq!(path.subpaths[0].segment_count(), 1);
assert_eq!(path.subpaths[0].anchors.len(), 2);
}
check_session(&s).unwrap();
}
#[test]
fn copy_all_anchors_of_open_path_copies_whole_path() {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 200, "height": 200}));
let id = NodeId(run(&mut s, "path.create", json!({"anchors": [{"x": 10, "y": 10}]}))["id"].as_u64().unwrap());
run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 50, "y": 10}));
run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 80, "y": 40}));
// Select all 3 anchors.
run(&mut s, "select.anchors", json!({"id": id.0, "anchors": [[0, 0], [0, 1], [0, 2]], "mode": "set"}));
run(&mut s, "edit.copy", json!({}));
let pasted = run(&mut s, "edit.paste", json!({}));
let ids: Vec<u64> = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
assert_eq!(ids.len(), 1);
let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap();
let path = pasted_node.path_data().unwrap();
assert_eq!(path.subpaths.len(), 1);
assert!(!path.subpaths[0].closed);
assert_eq!(path.subpaths[0].segment_count(), 2);
assert_eq!(path.subpaths[0].anchors.len(), 3);
check_session(&s).unwrap();
}
#[test]
fn copy_single_anchor_on_open_path_and_lone_point_states_what_is_pasted() {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 200, "height": 200}));
// 1. Single interior anchor of an open path:
// Path: (10, 10) -> (50, 10) -> (90, 50).
// Selecting interior anchor 1 selects both incident segments (0 and 1).
// Stated behavior: pasting pastes an open path containing the anchor and both its incident segments (3 anchors, 2 segments).
let p1 = NodeId(run(&mut s, "path.create", json!({"anchors": [{"x": 10, "y": 10}]}))["id"].as_u64().unwrap());
run(&mut s, "path.appendAnchor", json!({"id": p1.0, "x": 50, "y": 10}));
run(&mut s, "path.appendAnchor", json!({"id": p1.0, "x": 90, "y": 50}));
run(&mut s, "select.anchors", json!({"id": p1.0, "anchors": [[0, 1]], "mode": "set"}));
run(&mut s, "edit.copy", json!({}));
let pasted1 = run(&mut s, "edit.paste", json!({}));
let ids1: Vec<u64> = pasted1["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
assert_eq!(ids1.len(), 1);
let path1 = s.doc().unwrap().doc.node(NodeId(ids1[0])).unwrap().path_data().unwrap();
assert!(!path1.subpaths[0].closed);
assert_eq!(path1.subpaths[0].anchors.len(), 3);
assert_eq!(path1.subpaths[0].segment_count(), 2);
// 2. Single endpoint anchor of an open path:
// Selecting endpoint anchor 0 selects its single incident segment (segment 0).
// Stated behavior: pasting pastes an open path for that segment (2 anchors, 1 segment).
run(&mut s, "select.anchors", json!({"id": p1.0, "anchors": [[0, 0]], "mode": "set"}));
run(&mut s, "edit.copy", json!({}));
let pasted2 = run(&mut s, "edit.paste", json!({}));
let ids2: Vec<u64> = pasted2["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
assert_eq!(ids2.len(), 1);
let path2 = s.doc().unwrap().doc.node(NodeId(ids2[0])).unwrap().path_data().unwrap();
assert!(!path2.subpaths[0].closed);
assert_eq!(path2.subpaths[0].anchors.len(), 2);
assert_eq!(path2.subpaths[0].segment_count(), 1);
// 3. A lone point path (a path with only 1 anchor and 0 segments):
// Selecting the lone anchor on a single-point path copies the object whole.
// Stated behavior: pasting pastes a standalone lone-point path (1 anchor, 0 segments).
let p_lone = NodeId(run(&mut s, "path.create", json!({"anchors": [{"x": 100, "y": 100}]}))["id"].as_u64().unwrap());
run(&mut s, "select.anchors", json!({"id": p_lone.0, "anchors": [[0, 0]], "mode": "set"}));
run(&mut s, "edit.copy", json!({}));
let pasted_lone = run(&mut s, "edit.paste", json!({}));
let ids_lone: Vec<u64> = pasted_lone["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
assert_eq!(ids_lone.len(), 1);
let path_lone = s.doc().unwrap().doc.node(NodeId(ids_lone[0])).unwrap().path_data().unwrap();
assert_eq!(path_lone.subpaths[0].anchors.len(), 1);
assert_eq!(path_lone.subpaths[0].segment_count(), 0);
check_session(&s).unwrap();
}
#[test]
fn cut_anchor_of_closed_path_opens_it_with_single_undo_step() {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 200, "height": 200}));
let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0);
// Direct-select anchor 1 of the closed 4-anchor rectangle.
run(&mut s, "select.anchors", json!({"id": r.0, "anchors": [[0, 1]], "mode": "set"}));
let undo_before = s.doc().unwrap().history.undo.len();
// Cut the anchor.
run(&mut s, "edit.cut", json!({}));
assert_eq!(s.doc().unwrap().history.undo.len(), undo_before + 1, "cut is recorded as one undo step");
// Source rectangle opens: 1 open subpath with 3 anchors remaining.
let src_node = s.doc().unwrap().doc.node(r).unwrap();
let src_path = src_node.path_data().unwrap();
assert_eq!(src_path.subpaths.len(), 1);
assert!(!src_path.subpaths[0].closed, "cutting anchor of closed path opens the path");
assert_eq!(src_path.subpaths[0].anchors.len(), 3);
assert_eq!(src_path.subpaths[0].segment_count(), 2);
// Clipboard holds the cut portion (the anchor and its two incident segments: 3 anchors).
assert_eq!(s.clipboard.nodes.len(), 1);
let clip_path = s.clipboard.nodes[0].path_data().unwrap();
assert!(!clip_path.subpaths[0].closed);
assert_eq!(clip_path.subpaths[0].anchors.len(), 3);
assert_eq!(clip_path.subpaths[0].segment_count(), 2);
// Verify undo restores the closed path in one step.
run(&mut s, "edit.undo", json!({}));
let restored_node = s.doc().unwrap().doc.node(r).unwrap();
let restored_path = restored_node.path_data().unwrap();
assert_eq!(restored_path.subpaths.len(), 1);
assert!(restored_path.subpaths[0].closed, "undo restores closed path");
assert_eq!(restored_path.subpaths[0].anchors.len(), 4);
assert_eq!(restored_path.subpaths[0].segment_count(), 4);
// Verify redo re-applies the cut.
run(&mut s, "edit.redo", json!({}));
let redone_node = s.doc().unwrap().doc.node(r).unwrap();
let redone_path = redone_node.path_data().unwrap();
assert!(!redone_path.subpaths[0].closed);
assert_eq!(redone_path.subpaths[0].anchors.len(), 3);
check_session(&s).unwrap();
}
#[test]
fn cut_middle_segment_of_open_path_splits_into_two_open_paths_with_single_undo_step() {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 200, "height": 200}));
let id = NodeId(run(&mut s, "path.create", json!({"anchors": [{"x": 10, "y": 10}]}))["id"].as_u64().unwrap());
run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 50, "y": 10}));
run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 90, "y": 10}));
run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 130, "y": 10}));
// Open path has 4 anchors (0, 1, 2, 3) and 3 segments (0, 1, 2).
// Direct-select middle segment 1 (between anchor 1 and 2).
run(&mut s, "select.segments", json!({"id": id.0, "segments": [[0, 1]]}));
let undo_before = s.doc().unwrap().history.undo.len();
// Cut the middle segment.
run(&mut s, "edit.cut", json!({}));
assert_eq!(s.doc().unwrap().history.undo.len(), undo_before + 1, "cut is recorded as one undo step");
// Source path should now be split into two surviving open runs.
let src_node = s.doc().unwrap().doc.node(id).unwrap();
let src_path = src_node.path_data().unwrap();
assert_eq!(src_path.subpaths.len(), 2, "two open paths/subpaths remain after cutting middle segment");
assert!(!src_path.subpaths[0].closed);
assert_eq!(src_path.subpaths[0].anchors.len(), 2);
assert_eq!(src_path.subpaths[0].anchors[0].p.x, 10.0);
assert_eq!(src_path.subpaths[0].anchors[1].p.x, 50.0);
assert!(!src_path.subpaths[1].closed);
assert_eq!(src_path.subpaths[1].anchors.len(), 2);
assert_eq!(src_path.subpaths[1].anchors[0].p.x, 90.0);
assert_eq!(src_path.subpaths[1].anchors[1].p.x, 130.0);
// Clipboard holds the cut middle segment:
assert_eq!(s.clipboard.nodes.len(), 1);
let clip_path = s.clipboard.nodes[0].path_data().unwrap();
assert_eq!(clip_path.subpaths[0].anchors.len(), 2);
assert_eq!(clip_path.subpaths[0].anchors[0].p.x, 50.0);
assert_eq!(clip_path.subpaths[0].anchors[1].p.x, 90.0);
// Verify undo restores the original intact path in one step:
run(&mut s, "edit.undo", json!({}));
let restored_node = s.doc().unwrap().doc.node(id).unwrap();
let restored_path = restored_node.path_data().unwrap();
assert_eq!(restored_path.subpaths.len(), 1, "undo restores single subpath");
assert_eq!(restored_path.subpaths[0].anchors.len(), 4, "undo restores all 4 anchors");
// Redo re-applies the split:
run(&mut s, "edit.redo", json!({}));
let redone_path = s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap();
assert_eq!(redone_path.subpaths.len(), 2);
check_session(&s).unwrap();
}
+1
View File
@@ -13,6 +13,7 @@ mod artboard_click;
mod beyond_canvas;
mod clear_commands;
mod compound_attributes;
mod copy_direct_selection;
mod dimensions;
mod eyedropper_sources;
mod find_replace_paras;
+89 -21
View File
@@ -18,11 +18,16 @@
//! `%AI5_ArtFlags`, `%AI5_TargetResolution`, `%AI5_NumLayers`, `%AI5_OpenViewLayers` (a digit for
//! each layer, 7 shown and 6 hidden), `%AI7_GridSettings` (§2.1.1), and the version comment
//! `%%AI8_CreatorVersion` ([`CREATOR_VERSION`]).
//! - Setup: `0 Bn` (no gradient definitions, §3), the color swatches (`%AI5_BeginPalette`,
//! `0 0 Pb`, the Registration swatch, each swatch's color operator and `(name) Pc`, a color group as `0 (name) count Pg`
//! before its swatches, `PB`), then the artboards as the `ArtboardArray` of the `/Document`
//! dictionary's `/Recorded` part and the canvas size as its `AIDocumentCanvasSize`, on `%_`
//! lines.
//! - Setup: the gradients the art uses as `n Bn` and a definition of each (§3.5: `%AI5_BeginGradient:
//! (name)`, `(name) type stops Bd`, `[`, each stop on a `%_` line as `color style opacity 6 midpoint
//! rampPoint Bs`, `BD`, `%AI5_EndGradient`), those only the swatches use in a non-printing block
//! (§14: `%AI5_Begin_NonPrinting`, `Np`, `%AI5_End_NonPrinting--`); the patterns the same way
//! (§3.4: `%AI3_BeginPattern: (name)`, `(name) llx lly urx ury`, the tile's art on `%_` lines, `E`,
//! `%AI3_EndPattern`); the swatches (`%AI5_BeginPalette`, `0 0 Pb`, the Registration swatch, each
//! swatch's color operator, gradient instance or pattern operator and `(name) Pc`, a color group as
//! `0 (name) count Pg` before its swatches, `PB`), then the artboards as the `ArtboardArray` of the
//! `/Document` dictionary's `/Recorded` part and the canvas size as its `AIDocumentCanvasSize`, on
//! `%_` lines.
//! - Layers: `%AI5_BeginLayer`, `visible preview unlocked printing dimmed 0 1 colorIndex r g b 0
//! dimPercent clipping Lb` (14 operands; a color that isn't one of the preset layer colors has the
//! index -1; `clipping` is 1 for a clipping layer), `(name) Ln`, the layer's name as an XML id in an
@@ -30,10 +35,22 @@
//! - Colors: `g` gray, `k` CMYK, `c m y k r g b Xa` RGB (Lab is written as RGB); a spot color
//! `c m y k (name) tint x` (CMYK) or `c m y k r g b|L a b (name) tint 1|2 Xx` (RGB or Lab); a
//! global process color `… (name) tint model Xk`; Registration `1 1 1 1 ([Registration]) tint
//! Xs`. Upper case paints the stroke.
//! Xs`; a pattern `(name) 0 0 1 1 0 0 0 0 0 [matrix] p` (`P`), the matrix taking the pattern's
//! space (its tile's lower left corner the origin) to art space. Upper case paints the stroke.
//! - Gradients (§3.5.3): around the painting operator of a path (of a compound path's last path),
//! `Bb` (`1 Bb` for the stroke), a radial gradient's focal point `x y angle fraction Bh`, then
//! `flag (name) x y angle length a b c d tx ty 1 Bg`, which places the gradient on the path: a
//! linear one with the identity matrix, `x` the start and `length` the length as fractions of the
//! path's extent along `angle`; a radial one with the matrix taking the unit circle onto its
//! extent ellipse, `x` and `y` its center as fractions of the path's bounds there and `length` its
//! radius as a multiple of the one the bounds give (`writer::paints::placement`). The imaging data
//! follows (a linear gradient's `a b c d tx ty Xm`, its caps `Bc` and a `Bm` for each pair of
//! stops; a radial one's `Bm`), then the operator and `0 BB` (`2 BB` or `1 BB` when the path is
//! stroked too; a fill's instance ends `2 BB` before a stroke's). In a pattern's tile the matrices
//! are in the canvas's space (y down, from art space's origin there).
//! - State before each object: locked `A`, hidden `Xw` (`1` or `0`). An object's name follows it as
//! an `/ArtDictionary` whose `AI10_ArtUID` is the name as an XML id. Guides are `(N) *`, the
//! path, `(N) *` (`(n) *` when closed).
//! an `/ArtDictionary` whose `AI10_ArtUID` is the name as an XML id. Guides are the path
//! followed by `(N) *` (`(n) *` when closed), without the `(N) *` that §6 also puts before it.
//! - Transparency: `mode opacity isolate knockout shape Xy` (the blending mode's number, Knockout
//! Group 0 off, 1 on, 2 neutral), written when it changes: in a path's paint after its colors,
//! before a guide, and after a group's end (`U` or `Q`) followed by `0 0 Xd` and `6 () XW`; a
@@ -45,19 +62,42 @@
//! - Opacity masks: an `AI9_Mask` entry in the object's `/ArtDictionary`, a `/Mask` dictionary
//! holding the mask's art between `X=` and `X+` on `%_` lines, `(Art) ,`, and `Clipping`,
//! `Inverted`, `Disabled` and `Linked` as `/Bool` entries.
//! - Embedded images (§8): `%AI5_File:`, `%AI5_BeginRaster`, `() 1 XG`, the color space
//! (`/DeviceGray`, `/DeviceRGB` or `/DeviceCMYK`) with `XN`, `[matrix] w h 0 Xh`, `[matrix] 0 0
//! w h w h 8 type alpha flags 1 0 4 4 0 0` (type 1 gray, 3 RGB, 4 CMYK; alpha 1 with an alpha
//! channel; flags 0 gray, 1 RGB, 2 CMYK, 16 more with an alpha channel), `%%BeginData:` counting
//! `XI`, its line end and the color samples, `XI`, the samples in binary (8 bits, rows from the
//! top, CMYK images with their ink amounts) followed by the alpha channel, `%%EndData`, `XH`,
//! `%AI5_EndRaster`, `N`. The matrix (to ten decimals) is an art-space matrix applied to the
//! pixels with their rows running downwards. In a part on `%_` lines, `XI` and the samples are
//! not, and `%_%%EndData` ends them.
//! - Linked images (version 7 specification §16, with the newer sections): `%AI5_BeginPlace`,
//! `%%FileType: 1`, `[matrix] llx lly urx ury 4 4 0` and `(path)` with `` ` ``, `%%IncludeFile:`,
//! the folder relative to the document's between `%AI28_BeginPlacedRelativePath` and its end,
//! a preview of at most 256 pixels a side between `%AI26_BeginPlacedObjectPreview` and its end
//! (`w h rowBytes 32 17 `, then rows of premultiplied ARGB), each in versioned content, `~`,
//! `%AI5_EndPlace`. The box is the file's pixels at art space's origin on the canvas; the matrix
//! takes it into art space. In opacity masks and pattern tiles, linked images are embedded.
//!
//! Lines end in CR LF. Strings are written in UTF-8. Art space is ruler space: y up, its origin at
//! the first artboard's top-left corner. On the canvas ([`CANVAS_SIZE`] points square, y down) the
//! artboards together are centered; each artboard's `RulerOrigin` is its top-left corner there, and
//! `%AI3_TemplateBox` holds the canvas's center in art space. What the form above can't hold is written as plain filled and stroked paths, each such
//! loss a warning: type as its outlines and its inline graphics' art, gradients as their average color, pattern fills as their
//! tiles cut to the shape, clipping groups and clipping layers whose clipping object isn't a path,
//! loss a warning: type as its outlines and its inline graphics' art, freeform gradients, gradients
//! along or across a stroke and gradients without stops, with more than 256 stops or without extent
//! as their average color
//! (gradients that dither or mix perceptually are written as classic ones, and gradient stops linked
//! to global process colors as their colors), pattern fills whose tiles aren't a grid, whose art reaches past
//! the tile or is painted with patterns as their tiles cut to the shape, clipping groups and clipping layers whose clipping object isn't a path,
//! and the clipping groups inside them, as their art cut to that object (its fill cut too, its
//! stroke not), images as their outlines filled with
//! their average color, symbols and live objects as their art (symbol art past
//! stroke not; an image in a clipping group of the region it is cut to), images that can't be
//! decoded or have more than 33,554,432 pixels as their outlines filled mid gray, images of 16 bits
//! a channel at 8 bits, linked images in opacity masks and pattern tiles as embedded images,
//! symbols and live objects (placed documents included) as their art (symbol art past
//! [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects in all left out), strokes a plain line can't draw
//! as their filled outlines, several fills or strokes as a group of a path for each, gradient and
//! pattern swatches, the opacity and blending modes of single fills and strokes, opacity masks on
//! as their filled outlines, several fills or strokes as a group of a path for each, freeform
//! gradient swatches, gradient swatches of more than 256 stops, swatches of patterns written as
//! tiles and the placement of pattern swatches that move, turn or scale their pattern, the opacity and blending modes of single fills and strokes, opacity masks on
//! layers and opacity masks nested too deep, and live effects other than geometry effects left out.
//!
//! The data streams hold the program compressed with Zstandard after `%AI24_ZStandard_Data`, with
@@ -160,10 +200,15 @@ pub fn export_ai_editing(doc: &Document, o: &AiEditingOptions) -> Result<AiEditi
// The document is y down; art space is ruler space: y up, its origin the first artboard's
// top-left corner.
let to_art = Affine::new([1.0, 0.0, 0.0, -1.0, -board.x0, board.y0]);
let mut w = Writer::new(doc, to_art);
let origin = ruler_origin(doc, to_art);
let mut w = Writer::new(doc, to_art, origin);
w.reserve_swatch_gradients();
for layer in &doc.layers {
w.layer(layer);
}
// The palette first: its gradient and pattern swatches add definitions.
let mut palette = String::new();
w.palette(&mut palette);
let first = to_art.transform_rect_bbox(board);
let art = doc
.layers
@@ -174,18 +219,18 @@ pub fn export_ai_editing(doc: &Document, o: &AiEditingOptions) -> Result<AiEditi
.filter(|b| b.is_finite())
.reduce(|a, b| a.union(b))
.unwrap_or(first);
let origin = ruler_origin(doc, to_art);
let header = header(doc, o, &w, art, first, origin, scale);
let mut s = header.clone();
// No gradient definitions: gradients are written as their average color.
s.push_str("%%BeginProlog\n%%EndProlog\n%%BeginSetup\n0 Bn\n");
w.palette(&mut s);
s.push_str("%%BeginProlog\n%%EndProlog\n%%BeginSetup\n");
w.definitions(&mut s);
s.push_str(&palette);
artboards(&mut s, doc, to_art, origin);
s.push_str("%%EndSetup\n");
s.push_str(&w.body);
s.push_str("%%PageTrailer\ngsave annotatepage grestore showpage\n%%Trailer\n%%EOF\n");
// Lines end in CR LF, as in the files users sent; line breaks inside strings are escaped.
Ok(AiEditingOutput { program: crlf(&s), header: crlf(&header), warnings: w.warnings })
let program = splice(&crlf(&s), &w.payloads);
Ok(AiEditingOutput { program, header: crlf(&header), warnings: w.warnings })
}
/// `s` with each line ending in CR LF.
@@ -193,6 +238,29 @@ fn crlf(s: &str) -> Vec<u8> {
s.replace('\n', "\r\n").into_bytes()
}
/// `text` with each payload's mark (`\u{1}`, its index in `payloads`, `\u{1}`) replaced by its
/// bytes. Strings are written with that byte escaped, so a mark is never part of one.
fn splice(text: &[u8], payloads: &[Vec<u8>]) -> Vec<u8> {
let mark = writer::PAYLOAD as u8;
if payloads.is_empty() {
return text.to_vec();
}
let mut out = Vec::with_capacity(text.len() + payloads.iter().map(Vec::len).sum::<usize>());
let mut parts = text.split(|b| *b == mark);
if let Some(first) = parts.next() {
out.extend_from_slice(first);
}
// The parts alternate: an index, then the text up to the next mark.
while let (Some(index), Some(rest)) = (parts.next(), parts.next()) {
let payload = std::str::from_utf8(index).ok().and_then(|i| i.parse::<usize>().ok()).and_then(|i| payloads.get(i));
if let Some(p) = payload {
out.extend_from_slice(p);
}
out.extend_from_slice(rest);
}
out
}
/// `doc` with its geometry effects and group paint baked ([`vectorcraft_effects::bake_document`]),
/// in its symbols' art and its patterns' tile art too (which instances and pattern fills are
/// written as); `None` when nothing changes.
@@ -305,7 +373,7 @@ fn header(doc: &Document, o: &AiEditingOptions, w: &Writer, art: Rect, first: Re
s.push('\n');
s.push_str("%%DocumentProcessColors: Cyan Magenta Yellow Black\n");
s.push_str("%AI5_FileFormat 14.0\n%AI3_ColorUsage: Color\n");
// Linked images aren't embedded (the data holds no images).
// Linked files aren't included (their previews are).
s.push_str("%AI7_ImageSettings: 0\n");
let spots = w.spot_swatches();
for (i, (name, _)) in spots.iter().enumerate() {
File diff suppressed because it is too large. Load diff
+156 -117
View File
@@ -9,29 +9,32 @@ use vectorcraft_color::swatch::{REGISTRATION, Swatch};
use vectorcraft_color::{BlendMode, Color, Paint};
use vectorcraft_doc::{AppearanceItem, Document, FillLayer, Knockout, LAYER_COLORS, LayerColor, Node, NodeKind, OpacityMask, StrokeLayer};
use vectorcraft_effects::stroke;
use vectorcraft_geom::{Affine, FillRule, PathData, Rect, Shape, SubPath};
use vectorcraft_geom::{Affine, FillRule, PathData, Shape, SubPath};
use vectorcraft_pathops::BoolOp;
use crate::ai_ops::{self, average, unit};
use crate::ai_ops::{self, unit};
use crate::ps;
mod images;
mod paints;
pub(super) use images::PAYLOAD;
#[cfg(test)]
pub(super) use images::{IMAGE_DEPTH, IMAGES, LINKS_EMBEDDED};
#[cfg(test)]
pub(super) use paints::{GRADIENT_MIX, GRADIENT_SHAPES, GRADIENTS, STOP_LINKS, SWATCH_PLACEMENT, free_gradient_name};
/// How deep symbols, live objects and pattern tiles may nest in one another (deeper art is left
/// out). Groups and layers need no limit of their own: a document is never deeper than
/// [`vectorcraft_doc::MAX_DEPTH`].
const MAX_NEST: u32 = 8;
/// The side of the image whose pixels are averaged (larger ones are scaled down to it first).
const AVERAGE_SIDE: u32 = 64;
/// Most pixels an image may have to be decoded and averaged (more: mid gray).
const MAX_AVERAGED_PIXELS: u64 = 1 << 24;
pub(super) const TYPE: &str = "type is written as its outlines in the editing data for other apps";
pub(super) const GRADIENTS: &str = "gradients are written as their average color in the editing data for other apps";
const PATTERNS: &str = "pattern fills are written as their tiles cut to the shape in the editing data for other apps";
pub(super) const PATTERNS: &str = "pattern fills whose tiles aren't a grid or whose art reaches past the tile, pattern fills in another pattern's tile and pattern fills nested more than 8 deep are written as their tiles cut to the shape in the editing data for other apps";
pub(super) const PATTERN_TILES: &str = "pattern fills with more tiles than a fill places are written filled gray in the editing data for other apps";
pub(super) const CLIPPING: &str = "clipping groups and clipping layers whose clipping object isn't a path, and the clipping groups inside them, are written as their art cut to that object in the editing data for other apps";
pub(super) const CLIP_PAINT: &str = "the fills and strokes of clipping paths that a plain fill and line can't draw are written as paths of their own inside the clipping (fills under the clipped art, strokes over it) in the editing data for other apps";
pub(super) const CLIP_PAINT_MASKS: &str = "the opacity masks of clipping paths whose fills and strokes are written as paths of their own stay on the clipping path, not on those paths, in the editing data for other apps";
pub(super) const IMAGES: &str = "images are written as their outlines filled with their average color in the editing data for other apps";
pub(super) const LIVE: &str =
"symbols, blends, envelopes, meshes, repeats, placed documents and intertwines are written as their art in the editing data for other apps";
const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, dots, dashes fitted to corners, gradients, patterns, arrowheads) are written as filled outlines, and brushed strokes as their brush's art, in the editing data for other apps";
@@ -43,7 +46,7 @@ pub(super) const DEEP_MASKS: &str =
const GROUPED_LAYER: &str =
"the transparency and opacity masks of layers that an effect made into a group are left out of the editing data for other apps";
pub(super) const EFFECTS: &str = "live effects other than geometry effects are left out of the editing data for other apps";
const SWATCHES: &str = "gradient and pattern swatches are left out of the editing data for other apps";
pub(super) const SWATCHES: &str = "freeform gradient swatches, gradient swatches of more than 256 stops, and pattern swatches whose patterns the data can't define, are left out of the editing data for other apps";
pub(super) const SYMBOL_LIMIT: &str = "symbol instances past 16,000,000 objects of symbol art in all are left out of the editing data for other apps";
const TEMPLATES: &str = "template layers are written as dimmed layers that don't print in the editing data for other apps";
@@ -127,13 +130,52 @@ pub(super) struct Writer<'a> {
brushes: Option<Vec<vectorcraft_brush::Brush>>,
/// The objects of the symbol art written so far, within [`vectorcraft_doc::MAX_SYMBOL_NODES`].
symbol_nodes: u64,
/// The document → the space gradients' matrices (`Xm`, `Bm`, `Bc`) and focal points are
/// written in: art space, and in a pattern's definition [`Self::tile_grad_space`].
grad_space: Affine,
/// The pattern's space (y down) → the space a pattern's definition writes gradients' matrices
/// in: the canvas's (y down), from art space's origin there.
tile_grad_space: Affine,
/// The document → the canvas (y down), the space of a gradient's transformation in `Bg`; in a
/// pattern's definition, the pattern's space turned y up.
canvas: Affine,
/// The gradient definitions, in the order they are first used.
gradients: Vec<paints::GradientDef>,
/// The number the next new gradient definition's name tries first (1 is `Gradient`).
next_gradient: u64,
/// The pattern definitions written, each after those its art uses.
patterns: Vec<paints::PatternOut>,
/// The patterns whose definitions are being written.
defining: Vec<String>,
/// Writing the palette: the definitions it adds are for its swatches only.
in_palette: bool,
/// Art space's origin on the canvas (y down), where a placed file's box starts.
canvas_origin: (f64, f64),
/// The binary parts of the program (images' samples, placed files' previews), each in the
/// text as a mark ([`PAYLOAD`], its index, [`PAYLOAD`]).
pub(super) payloads: Vec<Vec<u8>>,
/// How many parts of the data written on `%_` lines (opacity masks' art, patterns' tiles) the
/// art being written is in.
hidden: u32,
}
impl<'a> Writer<'a> {
pub(super) fn new(doc: &'a Document, to_art: Affine) -> Self {
/// A writer of `doc`'s art through `to_art`; `origin` is art space's origin on the canvas.
pub(super) fn new(doc: &'a Document, to_art: Affine, origin: (f64, f64)) -> Self {
Self {
doc,
to_art,
grad_space: to_art,
tile_grad_space: Affine::translate((-origin.0, origin.1)),
canvas: Affine::new([1.0, 0.0, 0.0, -1.0, origin.0, origin.1]) * to_art,
gradients: vec![],
next_gradient: 1,
patterns: vec![],
defining: vec![],
in_palette: false,
canvas_origin: origin,
payloads: vec![],
hidden: 0,
cms: vectorcraft_color::cms::active(),
body: String::new(),
warnings: vec![],
@@ -358,12 +400,7 @@ impl<'a> Writer<'a> {
}
NodeKind::Compound { rule, .. } => self.shape(n, &compound_path(n), *rule, xy),
NodeKind::Text(_) => self.text(n, xy),
NodeKind::Image(im) => {
let bounds = PathData::from_bezpath(&(im.xf * Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height)).to_path(0.1)));
let color = image_average(self.doc.image_blob(im).map(|b| b.bytes.as_slice()));
self.warn(IMAGES);
self.fill_object(&bounds, FillRule::NonZero, &FillLayer::new(Paint::solid(color)), xy);
}
NodeKind::Image(im) => self.image(im, xy),
NodeKind::SymbolInstance { symbol, xf } => {
self.warn(LIVE);
self.line("u");
@@ -498,19 +535,15 @@ impl<'a> Writer<'a> {
_ => std::slice::from_ref(art),
};
self.nest += 1;
self.hidden += 1;
for c in members {
self.node(c);
}
self.hidden -= 1;
self.nest -= 1;
let lines = std::mem::replace(&mut self.body, outer);
self.body.push_str("%_/Mask :\n%_X=\n");
for l in lines.lines() {
if !l.starts_with("%_") {
self.body.push_str("%_");
}
self.body.push_str(l);
self.body.push('\n');
}
hide(&lines, &mut self.body);
self.body.push_str("%_X+\n%_(Art) ,\n");
for (key, on) in [("Clipping", m.clip), ("Inverted", m.invert), ("Disabled", m.disabled), ("Linked", m.linked)] {
let _ = writeln!(self.body, "%_{} /Bool ({key}) ,", u8::from(on));
@@ -560,16 +593,17 @@ impl<'a> Writer<'a> {
self.warn_cut(Some(first));
return self.clip_contents(children);
};
let painted = plain_paint(first);
if visible_items(first).iter().any(|i| i.opacity() < 1.0 || i.blend() != BlendMode::Normal) {
let items = self.items(first, path.to_bezpath().bounding_box());
let painted = self.plain_paint(&items);
if items.iter().any(|i| i.opacity() < 1.0 || i.blend() != BlendMode::Normal) {
self.warn(ITEM_TRANSPARENCY);
}
// Paint the clipping path can't carry: its fills under the others, its strokes over them.
let (fills, strokes): (Vec<&AppearanceItem>, Vec<&AppearanceItem>) =
if painted.is_none() { visible_items(first).into_iter().partition(|i| matches!(i, AppearanceItem::Fill(_))) } else { (vec![], vec![]) };
if painted.is_none() { items.iter().partition(|i| matches!(i, AppearanceItem::Fill(_))) } else { (vec![], vec![]) };
if painted.is_none() {
self.warn(CLIP_PAINT);
if first.extras().mask.is_some() && !visible_items(first).is_empty() {
if first.extras().mask.is_some() && !items.is_empty() {
self.warn(CLIP_PAINT_MASKS);
}
}
@@ -588,10 +622,13 @@ impl<'a> Writer<'a> {
if several {
self.line("*u");
}
for sp in subpaths {
let last = subpaths.len().saturating_sub(1);
let outline = path.to_bezpath();
for (i, sp) in subpaths.into_iter().enumerate() {
ai_ops::subpath(&mut self.body, self.to_art, sp);
let op = if sp.closed { op } else { op.to_ascii_uppercase() };
let _ = writeln!(self.body, "{}\nW\n{op}", if sp.closed { 'h' } else { 'H' });
let _ = writeln!(self.body, "{}\nW", if sp.closed { 'h' } else { 'H' });
let gradients = if i == last { (gradient(fill.map(|f| &f.paint)), gradient(stroke.map(|s| &s.paint))) } else { (None, None) };
self.painted(op, sp.closed, gradients, stroke.is_some(), true, &outline);
}
if several {
self.line("*U");
@@ -658,11 +695,11 @@ impl<'a> Writer<'a> {
if path.is_empty() {
return;
}
let items = visible_items(n);
let items = self.items(n, path.to_bezpath().bounding_box());
if items.iter().any(|i| i.opacity() < 1.0 || i.blend() != BlendMode::Normal) {
self.warn(ITEM_TRANSPARENCY);
}
match (plain_paint(n), items.as_slice()) {
match (self.plain_paint(&items), items.as_slice()) {
(Some((fill, stroke)), _) => self.path_object(path, rule, fill, stroke, xy),
(None, [one]) => self.item(path, rule, one, xy),
(None, items) => {
@@ -679,7 +716,7 @@ impl<'a> Writer<'a> {
fn item(&mut self, path: &PathData, rule: FillRule, item: &AppearanceItem, xy: Xy) {
match item {
AppearanceItem::Fill(f) => self.fill_object(path, rule, f, xy),
AppearanceItem::Stroke(s) if direct_stroke(s) => self.path_object(path, rule, None, Some(s), xy),
AppearanceItem::Stroke(s) if self.direct_stroke(s) => self.path_object(path, rule, None, Some(s), xy),
AppearanceItem::Stroke(s) => {
self.warn(STROKES);
if self.brush_art(path, s, xy) {
@@ -716,15 +753,17 @@ impl<'a> Writer<'a> {
true
}
/// A fill as an object of its own, of transparency `xy`: a gradient as its average color, a
/// pattern as its tiles cut to the path.
/// A fill as an object of its own, of transparency `xy`: a color, a placed gradient or a
/// pattern the data can define as the path's fill, another pattern as its tiles cut to the path.
fn fill_object(&mut self, path: &PathData, rule: FillRule, f: &FillLayer, xy: Xy) {
if !matches!(f.paint, Paint::None) && self.direct(&f.paint) {
return self.path_object(path, rule, Some(f), None, xy);
}
match &f.paint {
Paint::Solid { .. } => self.path_object(path, rule, Some(f), None, xy),
Paint::Gradient(g) => {
self.warn(GRADIENTS);
let flat = FillLayer { paint: Paint::solid(average(&g.gradient)), ..f.clone() };
self.path_object(path, rule, Some(&flat), None, xy);
// A gradient not placed yet: placed on the path, or its average color.
Paint::Solid { .. } | Paint::Gradient(_) => {
let flat = self.placed(&f.paint, path.to_bezpath().bounding_box());
self.path_object(path, rule, Some(&FillLayer { paint: flat, ..f.clone() }), None, xy);
}
Paint::Pattern { pattern, xf } => {
self.warn(PATTERNS);
@@ -826,11 +865,13 @@ impl<'a> Writer<'a> {
if several {
self.line("*u");
}
for sp in subpaths {
// A gradient's instance paints the last subpath; the compound path takes its paint.
let last = subpaths.len().saturating_sub(1);
let outline = path.to_bezpath();
for (i, sp) in subpaths.into_iter().enumerate() {
ai_ops::subpath(&mut self.body, self.to_art, sp);
let op = if sp.closed { op } else { op.to_ascii_uppercase() };
self.body.push(op);
self.body.push('\n');
let gradients = if i == last { (gradient(fill.map(|f| &f.paint)), gradient(stroke.map(|s| &s.paint))) } else { (None, None) };
self.painted(op, sp.closed, gradients, stroke.is_some(), false, &outline);
}
if several {
self.line("*U");
@@ -899,11 +940,15 @@ impl<'a> Writer<'a> {
// ---------- color ----------
/// Set the fill (or with `stroke`, the stroke) color to solid paint `p`: a spot or global
/// swatch by its name, Registration, else the color itself.
/// Set the fill (or with `stroke`, the stroke) to paint `p`: a spot or global swatch by its
/// name, Registration, the color itself, or a pattern ([`Self::pattern_paint`]). A gradient sets
/// nothing: its instance paints ([`Self::painted`]).
fn color(&mut self, p: &Paint, stroke: bool) {
let Paint::Solid { color, swatch, tint } = p else {
return self.plain_color(Color::gray(1.0), stroke);
let (color, swatch, tint) = match p {
Paint::Solid { color, swatch, tint } => (color, swatch, tint),
Paint::Pattern { pattern, xf } => return self.pattern_paint(pattern, *xf, stroke),
Paint::Gradient(_) => return,
Paint::None => return self.plain_color(Color::gray(1.0), stroke),
};
if swatch.as_deref() == Some(REGISTRATION) {
let mut s = String::from("1 1 1 1 ");
@@ -989,6 +1034,7 @@ impl<'a> Writer<'a> {
/// (the ungrouped ones first, then each color group's after `0 (name) count Pg`), `PB`,
/// `%AI5_EndPalette`.
pub(super) fn palette(&mut self, s: &mut String) {
self.in_palette = true;
s.push_str("%AI5_BeginPalette\n0 0 Pb\n");
self.registration_cell(s);
let doc = self.doc;
@@ -996,13 +1042,13 @@ impl<'a> Writer<'a> {
self.swatch(s, sw);
}
for g in doc.swatch_groups.iter() {
let colors: Vec<&Swatch> = g.swatches.iter().filter(|sw| writable(sw)).collect();
let _ = writeln!(s, "0 {} {} Pg", ps::bytes(g.name.as_bytes()), colors.len());
for sw in &g.swatches {
self.swatch(s, sw);
}
let mut cells = String::new();
let count = g.swatches.iter().filter(|sw| self.swatch(&mut cells, sw)).count();
let _ = writeln!(s, "0 {} {count} Pg", ps::bytes(g.name.as_bytes()));
s.push_str(&cells);
}
s.push_str("PB\n%AI5_EndPalette\n");
self.in_palette = false;
}
/// The Registration swatch, which every palette in the files users sent starts with: in a
@@ -1021,24 +1067,31 @@ impl<'a> Writer<'a> {
let _ = writeln!(s, "{name} Pc");
}
/// One swatch of the palette: a color swatch's color and `(name) Pc`; gradient and pattern
/// swatches are left out.
fn swatch(&mut self, s: &mut String, sw: &Swatch) {
/// One swatch of the palette: a color swatch's color, a gradient swatch's or pattern swatch's
/// paint ([`Self::swatch_paint`]), then `(name) Pc`. False when it isn't written: Registration
/// (written first), the None swatch, and paint the data can't hold (with a warning).
fn swatch(&mut self, s: &mut String, sw: &Swatch) -> bool {
if sw.name == REGISTRATION || matches!(sw.paint, Paint::None) {
return;
return false;
}
if !writable(sw) {
return self.warn(SWATCHES);
}
let Paint::Solid { color, swatch, .. } = &sw.paint else { return };
if swatch.is_none() && (sw.global || sw.spot) {
self.named(s, &sw.name, *color, 1.0, sw.spot, false);
} else {
let body = std::mem::take(&mut self.body);
self.plain_color(*color, false);
s.push_str(&std::mem::replace(&mut self.body, body));
match &sw.paint {
Paint::Solid { color, swatch, .. } => {
if swatch.is_none() && (sw.global || sw.spot) {
self.named(s, &sw.name, *color, 1.0, sw.spot, false);
} else {
let body = std::mem::take(&mut self.body);
self.plain_color(*color, false);
s.push_str(&std::mem::replace(&mut self.body, body));
}
}
_ if self.swatch_paint(s, sw) => {}
_ => {
self.warn(SWATCHES);
return false;
}
}
let _ = writeln!(s, "{} Pc", ps::bytes(sw.name.as_bytes()));
true
}
/// The spot color swatches, with their full colors' CMYK equivalents, for the header.
@@ -1057,14 +1110,12 @@ impl<'a> Writer<'a> {
}
}
/// Is `sw` a color swatch the palette writes?
fn writable(sw: &Swatch) -> bool {
matches!(sw.paint, Paint::Solid { .. }) && sw.name != REGISTRATION
}
/// Does a plain line of one color draw `s` (the line style operators can write it)?
fn direct_stroke(s: &StrokeLayer) -> bool {
matches!(s.paint, Paint::Solid { .. }) && stroke::is_plain(s)
/// The gradient of paint `p`, when it has one.
fn gradient(p: Option<&Paint>) -> Option<&vectorcraft_color::GradientPaint> {
match p {
Some(Paint::Gradient(g)) => Some(g),
_ => None,
}
}
/// `n`'s fills and strokes that paint.
@@ -1079,19 +1130,6 @@ fn visible_items(n: &Node) -> Vec<&AppearanceItem> {
.collect()
}
/// `n`'s paint as one path object paints: no paint, a fill of a color, a plain line of a color,
/// or both, the line over the fill; `None` when it has other paint.
fn plain_paint(n: &Node) -> Option<(Option<&FillLayer>, Option<&StrokeLayer>)> {
let solid = |p: &Paint| matches!(p, Paint::Solid { .. });
match visible_items(n).as_slice() {
[] => Some((None, None)),
[AppearanceItem::Fill(f)] if solid(&f.paint) => Some((Some(f), None)),
[AppearanceItem::Stroke(s)] if direct_stroke(s) => Some((None, Some(s))),
[AppearanceItem::Fill(f), AppearanceItem::Stroke(s)] if solid(&f.paint) && direct_stroke(s) => Some((Some(f), Some(s))),
_ => None,
}
}
/// The painting operator of a closed subpath (§5.3.3): `b` fill and stroke, `f` fill, `s`
/// stroke, `n` neither; an open one's is upper case.
fn paint_op(fill: bool, stroke: bool) -> char {
@@ -1124,42 +1162,43 @@ fn clip_path(n: &Node) -> Option<(PathData, FillRule)> {
path.subpaths.iter().any(|sp| !sp.anchors.is_empty()).then_some((path, rule))
}
/// The image `bytes` decoded, when its header gives at most [`MAX_AVERAGED_PIXELS`] pixels; the
/// decoder may allocate at most 8 bytes a pixel.
fn decode_bounded(bytes: &[u8]) -> Option<image::DynamicImage> {
/// `text`'s lines on `%_` lines, as a part of the data that readers of the printed form skip (an
/// opacity mask's art, a pattern's tile) has them. An image's samples stay as they are after an
/// `XI` without `%_`, and `%_%%EndData` ends them, as in the files users sent. Samples hidden
/// already (an opacity mask's art in a pattern's tile) keep their one `%_`.
pub(super) fn hide(text: &str, out: &mut String) {
for l in text.lines() {
if l.starts_with(images::SAMPLES_LINE) {
match l.strip_suffix("%%EndData") {
Some(samples) if !samples.ends_with("%_") => {
out.push_str(samples);
out.push_str("%_%%EndData");
}
_ => out.push_str(l),
}
} else {
if !l.starts_with("%_") {
out.push_str("%_");
}
out.push_str(l);
}
out.push('\n');
}
}
/// The image `bytes` decoded, when its header gives at most `max` pixels; the decoder may allocate
/// at most 8 bytes a pixel.
fn decode_bounded(bytes: &[u8], max: u64) -> Option<image::DynamicImage> {
let reader = || -> image::ImageResult<image::ImageReader<std::io::Cursor<&[u8]>>> {
let mut r = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format()?;
let mut limits = image::Limits::default();
limits.max_alloc = Some(MAX_AVERAGED_PIXELS * 8);
limits.max_alloc = Some(max * 8);
r.limits(limits);
Ok(r)
};
let (w, h) = reader().and_then(|r| r.into_dimensions()).ok()?;
if u64::from(w) * u64::from(h) > MAX_AVERAGED_PIXELS {
if u64::from(w) * u64::from(h) > max {
return None;
}
reader().and_then(|r| r.decode()).ok()
}
/// The average color of the image `bytes` (scaled down first), transparent pixels over white;
/// mid gray when it can't be decoded or has more than [`MAX_AVERAGED_PIXELS`] pixels.
fn image_average(bytes: Option<&[u8]>) -> Color {
let Some(img) = bytes.and_then(decode_bounded) else { return Color::gray(0.5) };
let img = if img.width() > AVERAGE_SIDE || img.height() > AVERAGE_SIDE { img.thumbnail(AVERAGE_SIDE, AVERAGE_SIDE) } else { img };
let rgba = img.to_rgba8();
let mut sum = [0u64; 3];
let mut n = 0u64;
for px in rgba.pixels() {
let [r, g, b, a] = px.0;
let over = |c: u8| (u64::from(c) * u64::from(a) + 255 * (255 - u64::from(a))) / 255;
sum[0] += over(r);
sum[1] += over(g);
sum[2] += over(b);
n += 1;
}
if n == 0 {
return Color::gray(0.5);
}
let c = |v: u64| (v as f32 / n as f32 / 255.0).clamp(0.0, 1.0);
Color::rgb(c(sum[0]), c(sum[1]), c(sum[2]))
}
+326
View File
@@ -0,0 +1,326 @@
//! Images: embedded ones as a raster with its samples, linked ones as a placed file with a preview
//! (see [`crate::ai_editing`] for the form).
use std::fmt::Write;
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{FillLayer, ImageBlob, ImageObject, LinkInfo};
use vectorcraft_geom::{Affine, FillRule, PathData, Rect, Shape};
use super::{Writer, Xy};
use crate::ps;
pub(in crate::ai_editing) const IMAGES: &str = "images that can't be decoded or have more than 33,554,432 pixels are written as their outlines filled mid gray in the editing data for other apps";
pub(in crate::ai_editing) const IMAGE_DEPTH: &str = "images of 16 bits a channel are written at 8 bits a channel in the editing data for other apps";
pub(in crate::ai_editing) const LINKS_EMBEDDED: &str =
"linked images in opacity masks and pattern tiles are written as embedded images in the editing data for other apps";
/// The most pixels an image is written with: as many as the reader reads.
pub(super) const MAX_PIXELS: u64 = 1 << 25;
/// The longer side of a placed file's preview at most (a smaller image's preview is its own
/// pixels): the files users sent have previews 256 pixels wide.
const PREVIEW_SIDE: u32 = 256;
/// What marks a binary payload in the program text: `\u{1}`, its index, `\u{1}`
/// ([`super::super::splice`] puts the bytes in its place). Strings never hold the byte unescaped.
pub(in crate::ai_editing) const PAYLOAD: char = '\u{1}';
/// What starts the line of an image's samples: `XI` and its payload, then `%%EndData`.
pub(super) const SAMPLES_LINE: &str = "XI\u{1}";
/// An image's pixels as the data holds them.
struct Samples {
/// `/DeviceGray`, `/DeviceRGB` or `/DeviceCMYK`.
space: &'static str,
/// The image type of `XI` (§8.1): 1 gray, 3 RGB, 4 CMYK.
kind: u8,
width: u32,
height: u32,
/// The color samples, 8 bits each, rows from the top.
color: Vec<u8>,
/// The alpha channel, a byte a pixel, when a pixel isn't opaque.
alpha: Option<Vec<u8>>,
}
impl Samples {
/// The pixels of `blob`: a CMYK image's ink amounts, else gray samples when every pixel is gray
/// or RGB samples, with an alpha channel when they need one. `None` when they can't be decoded or are more than
/// [`MAX_PIXELS`]; the flag is set when the image had 16 bits a channel.
fn of(blob: &ImageBlob) -> Option<(Samples, bool)> {
// The header's size is checked before the inks are decoded.
if blob.is_cmyk()
&& blob.header_size().is_some_and(|(w, h)| u64::from(w) * u64::from(h) <= MAX_PIXELS)
&& let Some(inks) = blob.cmyk()
&& u64::from(inks.width) * u64::from(inks.height) <= MAX_PIXELS
{
let s = Samples { space: "/DeviceCMYK", kind: 4, width: inks.width, height: inks.height, color: inks.data, alpha: None };
return Some((s, blob.is_cmyk16()));
}
let img = super::decode_bounded(&blob.bytes, MAX_PIXELS)?;
let deep = matches!(
img.color(),
image::ColorType::L16
| image::ColorType::La16
| image::ColorType::Rgb16
| image::ColorType::Rgba16
| image::ColorType::Rgb32F
| image::ColorType::Rgba32F
);
let rgba = img.to_rgba8();
// Gray when every pixel is, whatever the file's color type (an image read back from the data
// is RGBA): the same pixels are written the same way.
let gray = rgba.pixels().all(|p| p.0[0] == p.0[1] && p.0[1] == p.0[2]);
let (width, height) = rgba.dimensions();
if width == 0 || height == 0 {
return None;
}
let opaque = rgba.pixels().all(|p| p.0[3] == 255);
let alpha = (!opaque).then(|| rgba.pixels().map(|p| p.0[3]).collect());
let color = if gray { rgba.pixels().map(|p| p.0[0]).collect() } else { rgba.pixels().flat_map(|p| [p.0[0], p.0[1], p.0[2]]).collect() };
let (space, kind) = if gray { ("/DeviceGray", 1) } else { ("/DeviceRGB", 3) };
Some((Samples { space, kind, width, height, color, alpha }, deep))
}
/// `XI`'s fourth flag as the files users sent have it: 0 gray, 1 RGB, 2 CMYK, 16 more with an
/// alpha channel.
fn reserved(&self) -> u8 {
let space = match self.kind {
1 => 0,
4 => 2,
_ => 1,
};
space + if self.alpha.is_some() { 16 } else { 0 }
}
}
impl Writer<'_> {
/// Image object `im` of transparency `xy`: embedded, a raster ([`Self::raster`]); linked, a
/// placed file with a preview ([`Self::placed_file`]), except in a part of the data written on
/// `%_` lines. One whose pixels can't be read is its outline filled mid gray. Where the art is
/// cut to a clipping path, the image is in a clipping group of that path.
pub(super) fn image(&mut self, im: &ImageObject, xy: Xy) {
let doc = self.doc;
let Some((samples, deep)) = doc.image_blob(im).and_then(Samples::of) else {
let bounds = PathData::from_bezpath(&(im.xf * Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height)).to_path(0.1)));
self.warn(IMAGES);
return self.fill_object(&bounds, FillRule::NonZero, &FillLayer::new(Paint::solid(Color::gray(0.5))), xy);
};
// A region that has nothing left hides the image.
if self.clip.as_ref().is_some_and(|c| c.subpaths.iter().all(|sp| sp.anchors.is_empty())) {
return;
}
if deep {
self.warn(IMAGE_DEPTH);
}
let cut = self.clip.take();
let at_q = (self.state, self.gs);
if cut.is_some() {
self.line("q");
}
self.set_xy(xy.object());
// The object places the image's own pixel grid (its width × height) wherever the file's is.
let fit =
Affine::scale_non_uniform(f64::from(im.width.max(1)) / f64::from(samples.width), f64::from(im.height.max(1)) / f64::from(samples.height));
match &im.link {
Some(link) if self.hidden == 0 => self.placed_file(link, &samples, (im.width.max(1), im.height.max(1)), im.xf),
other => {
if other.is_some() {
self.warn(LINKS_EMBEDDED);
}
self.raster(&samples, im.xf * fit);
}
}
if let Some(region) = &cut {
self.line("0 XR");
// Several subpaths clip as one compound path (`*u` … `*U`), as a clipping group's do.
let subpaths: Vec<_> = region.subpaths.iter().filter(|sp| !sp.anchors.is_empty()).collect();
let several = subpaths.len() > 1;
if several {
self.line("*u");
}
for sp in subpaths {
crate::ai_ops::subpath(&mut self.body, self.to_art, sp);
self.line("h\nW\nn");
}
if several {
self.line("*U");
}
(self.state, self.gs) = at_q;
self.end_group("Q", Xy::PLAIN);
}
self.clip = cut;
}
/// An embedded image whose pixels `xf` places in the document: `%AI5_File:`,
/// `%AI5_BeginRaster`, `() 1 XG` (no file), the color space `XN`, `[matrix] w h 0 Xh`,
/// `[matrix] 0 0 w h w h 8 type alpha reserved 1 0 4 4 0 0`, `%%BeginData:` counting `XI`, its
/// line end and the color samples, `XI`, the color samples then the alpha channel in binary,
/// `%%EndData`, `XH`, `%AI5_EndRaster`, `N`. The matrix is an art-space matrix applied to the
/// pixels with their rows running downwards, `(u, -v)`, as §8.1's image matrix.
fn raster(&mut self, s: &Samples, xf: Affine) {
let m = matrix(self.to_art * xf * Affine::FLIP_Y);
let (w, h) = (s.width, s.height);
let alpha = u8::from(s.alpha.is_some());
let mut payload = Vec::with_capacity(2 + s.color.len() + s.alpha.as_ref().map_or(0, Vec::len));
payload.extend_from_slice(b"\r\n");
payload.extend_from_slice(&s.color);
if let Some(a) = &s.alpha {
payload.extend_from_slice(a);
}
let mark = self.payload(payload);
let _ = writeln!(
self.body,
"%AI5_File:\n%AI5_BeginRaster\n() 1 XG\n{} XN\n{m} {w} {h} 0 Xh\n{m} 0 0 {w} {h} {w} {h} 8 {} {alpha} {} 1 0 4 4 0 0\n%%BeginData: {}\nXI{mark}%%EndData\nXH\n%AI5_EndRaster\nN",
s.space,
s.kind,
s.reserved(),
// `XI`, CR LF.
4 + s.color.len(),
);
}
/// A linked image whose pixels `xf` places in the document: `%AI5_BeginPlace`,
/// `%%FileType: 1`, `[matrix] llx lly urx ury 4 4 0` and the file's path with `` ` ``,
/// `%%IncludeFile:` and the path, the folder relative to the document's between
/// `%AI28_BeginPlacedRelativePath` and its end (`()` for the document's own folder), the preview between
/// `%AI26_BeginPlacedObjectPreview` and its end (`w h rowBytes 32 17 ` and rows of
/// premultiplied ARGB, the top one first, of the pixels `s`), `~`, `%AI5_EndPlace`. The box is
/// as large as the file has pixels (`w` × `h`, the object's pixel grid, which `xf` places in the
/// document), at art space's origin on the canvas (y down); the matrix takes it from there into
/// art space. Each marked part newer releases read is in versioned content, as in the files
/// users sent.
fn placed_file(&mut self, link: &LinkInfo, s: &Samples, (w, h): (u32, u32), xf: Affine) {
let (x, y) = self.canvas_origin;
let m = matrix(self.to_art * xf * Affine::translate((-x, -y)));
let (w, h) = (f64::from(w), f64::from(h));
let path = ps::bytes(link.path.as_bytes());
let _ = write!(self.body, "%AI5_BeginPlace\n%%FileType: 1\n{m} ");
ps::push_nums(&mut self.body, &[x, y, x + w, y + h, 4.0, 4.0, 0.0]);
self.body.pop();
let _ = writeln!(self.body, "\n{path}`");
if !link.path.chars().any(char::is_control) {
let _ = writeln!(self.body, "%%IncludeFile:{}", link.path);
}
// The section holds a folder only, the file's name comes from the path: a relative path to a
// file of another name isn't written. On Windows and macOS, whose file names ignore letter
// case, names that differ only in case are the same file.
let same_name = |r: &&str| r.rsplit(['/', '\\']).next().is_some_and(|n| same_file_name(n, link.name()));
if let Some(folder) = link.relative.as_deref().filter(same_name).map(relative_folder) {
let _ = writeln!(
self.body,
"%AI17_Begin_Content_if_version_gt:24 12\n%AI28_BeginPlacedRelativePath\n{}\n%AI28_EndPlacedRelativePath\n%AI17_Alternate_Content\n%AI17_End_Versioned_Content",
ps::bytes(folder.as_bytes())
);
}
let (pw, ph, rows) = preview(s);
let mark = self.payload(rows);
let _ = writeln!(
self.body,
"%AI17_Begin_Content_if_version_gt:24 5\n%AI26_BeginPlacedObjectPreview\n{pw} {ph} {} 32 17 {mark}\n%AI26_EndPlacedObjectPreview\n%AI17_End_Versioned_Content\n~\n%AI5_EndPlace",
pw * 4
);
}
/// Keep `bytes` to go in the program where the mark this returns is.
fn payload(&mut self, bytes: Vec<u8>) -> String {
self.payloads.push(bytes);
format!("{PAYLOAD}{}{PAYLOAD}", self.payloads.len() - 1)
}
}
/// `[a b c d tx ty]`, each number to ten decimals ([`ps::num`] writes four).
fn matrix(m: Affine) -> String {
let n: Vec<String> = m.as_coeffs().iter().map(|v| precise(*v)).collect();
format!("[{}]", n.join(" "))
}
/// `v` rounded to ten decimals, without trailing zeros (0 when not finite).
fn precise(v: f64) -> String {
let r = (v * 1e10).round() / 1e10;
if !r.is_finite() {
return if v.is_finite() { format!("{}", v + 0.0) } else { "0".into() };
}
format!("{}", r + 0.0)
}
/// The folder of a path relative to the document's (`src/checker.png` → `src/`); empty when the file
/// is in the document's own folder. `\` separators are read as `/`.
fn relative_folder(relative: &str) -> String {
match relative.replace('\\', "/").rsplit_once('/') {
Some((folder, _)) if !folder.is_empty() => format!("{folder}/"),
_ => String::new(),
}
}
/// Do file names `a` and `b` name the same file in one folder: equal, or on Windows and macOS equal
/// but for letter case?
fn same_file_name(a: &str, b: &str) -> bool {
a == b || (cfg!(any(windows, target_os = "macos")) && a.to_lowercase() == b.to_lowercase())
}
/// A placed file's preview of `s`: its width, height and rows of premultiplied ARGB, the top one
/// first; the image's own pixels when neither side is longer than [`PREVIEW_SIDE`], else scaled
/// down to it, each preview pixel the average of the premultiplied pixels it covers.
fn preview(s: &Samples) -> (u32, u32, Vec<u8>) {
let (w, h) = (u64::from(s.width), u64::from(s.height));
let longer = s.width.max(s.height);
let (pw, ph) = if longer > PREVIEW_SIDE {
let k = f64::from(PREVIEW_SIDE) / f64::from(longer);
let side = |v: u32| ((f64::from(v) * k).round() as u32).clamp(1, PREVIEW_SIDE);
(side(s.width), side(s.height))
} else {
(s.width, s.height)
};
let n = usize::from(channels(s.kind));
let cmyk_memo = std::cell::RefCell::new(std::collections::HashMap::new());
// Pixel `i` premultiplied: r, g, b, a.
let pixel = |i: usize| -> [u64; 4] {
let c = |k: usize| s.color.get(i * n + k).copied().unwrap_or(0);
let rgb = match s.kind {
1 => [c(0); 3],
4 => {
let mut memo = cmyk_memo.borrow_mut();
if memo.len() > 1 << 16 {
memo.clear();
}
*memo.entry([c(0), c(1), c(2), c(3)]).or_insert_with(|| {
let f = |v: u8| f32::from(v) / 255.0;
let [r, g, b, _] = Color::cmyk(f(c(0)), f(c(1)), f(c(2)), f(c(3))).to_rgba8(1.0);
[r, g, b]
})
}
_ => [c(0), c(1), c(2)],
};
let a = u64::from(s.alpha.as_ref().and_then(|a| a.get(i)).copied().unwrap_or(255));
let pre = |v: u8| (u64::from(v) * a + 127) / 255;
[pre(rgb[0]), pre(rgb[1]), pre(rgb[2]), a]
};
let (pw64, ph64) = (u64::from(pw), u64::from(ph));
let mut rows = Vec::with_capacity((pw64 * ph64 * 4) as usize);
for py in 0..ph64 {
let (y0, y1) = (py * h / ph64, ((py + 1) * h / ph64).max(py * h / ph64 + 1));
for px in 0..pw64 {
let (x0, x1) = (px * w / pw64, ((px + 1) * w / pw64).max(px * w / pw64 + 1));
let mut sum = [0u64; 4];
for y in y0..y1.min(h) {
for x in x0..x1.min(w) {
let p = pixel((y * w + x) as usize);
for (t, v) in sum.iter_mut().zip(p) {
*t += v;
}
}
}
let count = ((y1.min(h) - y0) * (x1.min(w) - x0)).max(1);
let [r, g, b, a] = sum.map(|t| ((t + count / 2) / count).min(255) as u8);
rows.extend_from_slice(&[a, r, g, b]);
}
}
(pw, ph, rows)
}
/// The samples a pixel of image type `kind` has.
fn channels(kind: u8) -> u8 {
match kind {
1 => 1,
4 => 4,
_ => 3,
}
}
+565
View File
@@ -0,0 +1,565 @@
//! Gradients and patterns: their definitions in the setup, gradient instances on paths and the
//! pattern operators (see [`crate::ai_editing`] for the form).
use std::fmt::Write;
use vectorcraft_color::gradient::GradientGeom;
use vectorcraft_color::swatch::REGISTRATION;
use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint};
use vectorcraft_doc::{AppearanceItem, FillLayer, PatternDef, StrokeLayer, TileType};
use vectorcraft_effects::stroke;
use vectorcraft_geom::{Affine, BezPath, Rect, Shape, Vec2};
use super::{MAX_NEST, Writer, Xy};
use crate::ai_ops::{average, unit};
use crate::ps;
pub(in crate::ai_editing) const GRADIENTS: &str =
"freeform gradients, and gradients along or across strokes, are written as their average color in the editing data for other apps";
pub(in crate::ai_editing) const GRADIENT_SHAPES: &str = "gradients without stops or with more than 256, gradients whose ramp has no length and radial gradients flattened to a line are written as their average color in the editing data for other apps";
pub(in crate::ai_editing) const SWATCH_PLACEMENT: &str =
"the placement of pattern swatches that move, turn or scale their pattern is left out of the editing data for other apps";
pub(in crate::ai_editing) const GRADIENT_MIX: &str =
"gradients that mix their colors perceptually or dither are written as classic gradients in the editing data for other apps";
pub(in crate::ai_editing) const STOP_LINKS: &str =
"gradient stops linked to global process colors are written as their colors in the editing data for other apps";
/// The length of a linear gradient's caps (`Bc`): the canvas's side.
const CAP: f64 = super::super::CANVAS_SIZE as f64;
/// A gradient definition: its name, its gradient, whether it is a gradient swatch's (named after
/// the swatch) and whether the art uses it (else only the palette does).
pub(super) struct GradientDef {
name: String,
gradient: Gradient,
swatch: bool,
used: bool,
}
/// A pattern definition written: its name, its text (`%AI3_BeginPattern` to `%AI3_EndPattern`)
/// and whether the art uses it.
pub(super) struct PatternOut {
name: String,
text: String,
used: bool,
}
/// Can `g` be written as a gradient (a linear or radial one with stops, no more than the `.ai`
/// reader reads)?
fn writable_gradient(g: &Gradient) -> bool {
g.kind != GradientKind::Freeform && !g.stops.is_empty() && g.stops.len() <= crate::import::MAX_GRADIENT_STOPS
}
/// The first name of `Gradient`, `Gradient 2`, `Gradient 3`, … numbered `next` or higher for
/// which `taken` returns false (`Gradient` is number 1); `next` is set past it.
pub(in crate::ai_editing) fn free_gradient_name(next: &mut u64, mut taken: impl FnMut(&str) -> bool) -> String {
loop {
let name = if *next <= 1 { String::from("Gradient") } else { format!("Gradient {next}") };
*next = next.saturating_add(1);
if !taken(&name) {
return name;
}
}
}
/// The stops of `g` in order of their place on the ramp.
fn sorted_stops(g: &Gradient) -> Vec<&GradientStop> {
let mut stops: Vec<&GradientStop> = g.stops.iter().collect();
stops.sort_by(|a, b| a.offset.total_cmp(&b.offset));
stops
}
impl Writer<'_> {
/// Each gradient swatch's definition, named after the swatch, before the art is written.
pub(in crate::ai_editing) fn reserve_swatch_gradients(&mut self) {
let doc = self.doc;
for sw in doc.swatches_iter() {
if let Paint::Gradient(g) = &sw.paint
&& writable_gradient(&g.gradient)
&& !self.gradients.iter().any(|d| d.name == sw.name)
{
self.gradients.push(GradientDef { name: sw.name.clone(), gradient: g.gradient.clone(), swatch: true, used: false });
}
}
}
/// The name of the definition of `g`: the swatch `swatch` names when it is a gradient swatch
/// of the same gradient, else a definition of the same gradient that no swatch names, else a
/// new one ([`free_gradient_name`]: `Gradient`, numbered when taken by another definition, a
/// swatch or a pattern).
fn define_gradient(&mut self, g: &Gradient, swatch: Option<&str>) -> String {
let used = !self.in_palette;
let found = swatch
.and_then(|s| self.gradients.iter().position(|d| d.swatch && d.name == s && d.gradient == *g))
.or_else(|| self.gradients.iter().position(|d| !d.swatch && d.gradient == *g));
if let Some(d) = found.and_then(|i| self.gradients.get_mut(i)) {
d.used |= used;
return d.name.clone();
}
let (doc, gradients) = (self.doc, &self.gradients);
let name = free_gradient_name(&mut self.next_gradient, |name| {
gradients.iter().any(|d| d.name == name) || doc.swatch(name).is_some() || doc.pattern(name).is_some()
});
self.gradients.push(GradientDef { name: name.clone(), gradient: g.clone(), swatch: false, used });
name
}
/// `p` as the paint of a fill or stroke whose gradient is placed on `bounds`: a gradient is
/// placed there (it then no longer depends on the shape it paints, which may be cut); one the
/// data can't hold is its average color, with a warning.
pub(super) fn placed(&mut self, p: &Paint, bounds: Rect) -> Paint {
let Paint::Gradient(g) = p else { return p.clone() };
let geom = g.resolve(bounds);
let finite = [geom.start.x, geom.start.y, geom.end.x, geom.end.y, geom.aspect].iter().all(|v| v.is_finite());
let radial = g.gradient.kind == GradientKind::Radial;
if g.gradient.kind == GradientKind::Freeform {
self.warn(GRADIENTS);
return Paint::solid(average(&g.gradient));
}
if !writable_gradient(&g.gradient) || !finite || geom.length() < 1e-9 || (radial && geom.aspect <= 1e-9) {
self.warn(GRADIENT_SHAPES);
return Paint::solid(average(&g.gradient));
}
Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..(**g).clone() }))
}
/// The fills and strokes of `n` that paint (outline `bounds`), their gradients placed
/// ([`Self::placed`]): a fill's on the shape's bounds, a stroke's on what it paints. A gradient
/// along or across a stroke is its average color (the stroke is written as its outline).
pub(super) fn items(&mut self, n: &vectorcraft_doc::Node, bounds: Rect) -> Vec<AppearanceItem> {
super::visible_items(n)
.into_iter()
.map(|i| match i {
AppearanceItem::Fill(f) => AppearanceItem::Fill(FillLayer { paint: self.placed(&f.paint, bounds), ..f.clone() }),
AppearanceItem::Stroke(s) => {
let paint = match s.path_gradient() {
Some(g) => {
self.warn(GRADIENTS);
Paint::solid(average(&g.gradient))
}
None => self.placed(&s.paint, s.paint_bounds(bounds)),
};
AppearanceItem::Stroke(StrokeLayer { paint, ..s.clone() })
}
})
.collect()
}
/// Can paint `p` be written as the paint of a path object: a color, a placed gradient, or a
/// pattern [`Self::pattern_writable`]?
pub(super) fn direct(&self, p: &Paint) -> bool {
match p {
Paint::Solid { .. } => true,
Paint::Gradient(g) => g.geom.is_some() && writable_gradient(&g.gradient),
Paint::Pattern { pattern, .. } => self.pattern_writable(pattern),
Paint::None => false,
}
}
/// Does a plain line of `s`'s paint draw it ([`Self::direct`], and the line style operators can
/// write it)?
pub(super) fn direct_stroke(&self, s: &StrokeLayer) -> bool {
self.direct(&s.paint) && stroke::is_plain(s)
}
/// `n`'s paint `items` as one path object paints: no paint, a fill, a plain line, or both, the
/// line over the fill; `None` when it has other paint.
pub(super) fn plain_paint<'i>(&self, items: &'i [AppearanceItem]) -> Option<(Option<&'i FillLayer>, Option<&'i StrokeLayer>)> {
match items {
[] => Some((None, None)),
[AppearanceItem::Fill(f)] if self.direct(&f.paint) => Some((Some(f), None)),
[AppearanceItem::Stroke(s)] if self.direct_stroke(s) => Some((None, Some(s))),
[AppearanceItem::Fill(f), AppearanceItem::Stroke(s)] if self.direct(&f.paint) && self.direct_stroke(s) => Some((Some(f), Some(s))),
_ => None,
}
}
/// The painting operator `op` of a subpath (`closed` or open), with the gradient instances of
/// the fill (`fill`) and the stroke (`stroke`) around it when it is the last subpath of its
/// object: `Bb` … `op` `flag BB`, the stroke's `1 Bb` … after the fill's `BB`; the flag is 0, or
/// with a stroke 2 (closed) or 1 (open). `stroked`: the object has a stroke. A clipping path's
/// instances (`clip`) don't issue a clip of their own. `path`: the path the operator paints (all
/// its subpaths), in the document.
pub(super) fn painted(
&mut self,
op: char,
closed: bool,
gradients: (Option<&GradientPaint>, Option<&GradientPaint>),
stroked: bool,
clip: bool,
path: &BezPath,
) {
let op = if closed { op } else { op.to_ascii_uppercase() };
let flag = match (stroked, closed) {
(false, _) => "0 BB",
(true, true) => "2 BB",
(true, false) => "1 BB",
};
let (fill, stroke) = gradients;
if let Some(f) = fill {
self.instance(f, false, clip, path);
if stroke.is_some() {
self.line(if closed { "2 BB" } else { "1 BB" });
}
}
if let Some(s) = stroke {
self.instance(s, true, clip, path);
}
self.body.push(op);
self.body.push('\n');
if fill.is_some() || stroke.is_some() {
self.line(flag);
}
}
/// A gradient instance's start (placed gradient `g`, on the stroke when `stroke`, on `path` in
/// the document), before its painting operator: `Bb` (`1 Bb` on the stroke); a radial
/// gradient's focal point `x y angle fraction Bh` (its offset from the center in the space of the
/// gradient's matrices, then its angle and fraction as [`placement`] gives them; `0 0 0 0 Bh` at
/// the center); `flag (name) x y angle length a b c d tx ty 1 Bg` (flag 1, or 0 for a clipping
/// path; the rest as [`placement`] gives them); then the gradient's place: a linear one's `a b c d tx ty Xm` (the
/// unit vector onto its whole ramp), its cap before the first stop `… Bc`, a `… Bm` for each pair
/// of stops next to each other (the unit vector onto the part between them) and its cap past the
/// last stop; a radial one's `… Bm` (the unit circle onto its extent ellipse).
fn instance(&mut self, g: &GradientPaint, stroke: bool, clip: bool, path: &BezPath) {
let Some(geom) = g.geom else { return };
let name = self.define_gradient(&g.gradient, g.swatch.as_deref());
self.line(if stroke { "1 Bb" } else { "Bb" });
let m = self.grad_space;
let u = geom.end - geom.start;
let radial = g.gradient.kind == GradientKind::Radial;
let place = placement(&geom, radial, &(self.canvas * path.clone()), self.canvas);
if radial {
let c = m * geom.start;
let off = geom.focal.map_or(Vec2::ZERO, |f| m * f - c);
let (angle, fraction) = if off.hypot() > 1e-9 { place.focal } else { (0.0, 0.0) };
let off = if fraction > 0.0 { off } else { Vec2::ZERO };
ps::push_nums(&mut self.body, &[off.x, off.y, angle, fraction]);
self.line("Bh");
}
let _ = write!(self.body, "{} {} ", u8::from(!clip), ps::bytes(name.as_bytes()));
ps::push_nums(&mut self.body, &place.bg);
ps::push_nums(&mut self.body, &place.transform.as_coeffs());
self.line("1 Bg");
// The unit vector along the gradient, and across it as long.
let frame = |from: f64, to: f64| {
let p = geom.start + u * from;
m * Affine::new([u.x * (to - from), u.y * (to - from), -u.y, u.x, p.x, p.y])
};
let mut matrix = |a: Affine, op: &str| {
ps::push_nums(&mut self.body, &a.as_coeffs());
self.body.push_str(op);
self.body.push('\n');
};
if radial {
matrix(m * geom.unit_frame().unwrap_or(Affine::new([u.x, u.y, -u.y, u.x, geom.start.x, geom.start.y])), "Bm");
return;
}
matrix(frame(0.0, 1.0), "Xm");
let offsets: Vec<f64> = sorted_stops(&g.gradient).iter().map(|s| f64::from(s.offset)).collect();
let len = u.hypot().max(1e-9);
let (first, last) = (offsets.first().copied().unwrap_or(0.0), offsets.last().copied().unwrap_or(1.0));
matrix(frame(first - CAP / len, first), "Bc");
for pair in offsets.windows(2) {
if let [a, b] = pair {
matrix(frame(*a, *b), "Bm");
}
}
matrix(frame(last, last + CAP / len), "Bc");
}
/// A gradient definition: `%AI5_BeginGradient: (name)`, `(name) type stops Bd` (type 0 linear,
/// 1 radial), `[`, each stop on a `%_` line (`color style opacity 6 midpoint rampPoint Bs`), a
/// linear gradient's from the last to the first and a radial one's from the first to the last,
/// `BD`, `%AI5_EndGradient`.
fn gradient_def(&mut self, s: &mut String, d: &GradientDef) {
if d.gradient.dither || !d.gradient.method.is_classic() {
self.warn(GRADIENT_MIX);
}
let name = ps::bytes(d.name.as_bytes());
let radial = d.gradient.kind == GradientKind::Radial;
let _ = writeln!(s, "%AI5_BeginGradient: {name}\n{name} {} {} Bd\n[", u8::from(radial), d.gradient.stops.len());
let mut stops = sorted_stops(&d.gradient);
if !radial {
stops.reverse();
}
for stop in stops {
s.push_str("%_");
self.stop_color(s, stop);
ps::push_nums(s, &[f64::from(unit(stop.opacity)), 6.0, f64::from(stop.midpoint) * 100.0, f64::from(stop.offset) * 100.0]);
s.push_str("Bs\n");
}
s.push_str("BD\n%AI5_EndGradient\n");
}
/// A stop's color and its style: gray `lightness 0`, CMYK `c m y k 1`, RGB (and Lab, as RGB)
/// `c m y k r g b 2` with its CMYK equivalent; a spot color its full color's CMYK equivalent,
/// then its RGB values when it isn't CMYK, its name and how much lighter than the full color,
/// then `3` (CMYK), or `1 4` (RGB, and Lab as RGB).
fn stop_color(&mut self, s: &mut String, stop: &GradientStop) {
let doc = self.doc;
let intent = self.cms.settings().intent;
if let Some(name) = stop.swatch.as_deref().filter(|n| *n != REGISTRATION)
&& let Some(sw) = doc.swatch(name)
&& let Paint::Solid { color: full, swatch: None, .. } = sw.paint
{
if sw.spot {
let cmyk = self.cms.to_cmyk(&doc.linked_color(full, true), intent).map(unit);
ps::push_nums(s, &cmyk.map(f64::from));
let rgb = !matches!(full, Color::Cmyk { .. });
if rgb {
ps::push_nums(s, &full.to_rgb().map(|v| f64::from(unit(v))));
}
s.push_str(&ps::bytes(name.as_bytes()));
s.push(' ');
ps::push_num(s, f64::from(1.0 - unit(stop.tint)));
s.push_str(if rgb { " 1 4 " } else { " 3 " });
return;
}
if sw.global {
self.warn(STOP_LINKS);
}
}
match stop.color {
Color::Gray { k } => {
ps::push_num(s, f64::from(1.0 - unit(k)));
s.push_str(" 0 ");
}
Color::Cmyk { c, m, y, k } => {
ps::push_nums(s, &[c, m, y, k].map(|v| f64::from(unit(v))));
s.push_str("1 ");
}
color @ (Color::Rgb { .. } | Color::Lab { .. }) => {
let cmyk = self.cms.to_cmyk(&color, intent).map(unit);
ps::push_nums(s, &cmyk.map(f64::from));
ps::push_nums(s, &color.to_rgb().map(|v| f64::from(unit(v))));
s.push_str("2 ");
}
}
}
// ---------- patterns ----------
/// Can pattern `name` be written as a definition and painted with from here: the document has
/// it, its tiles make a grid, its art is within its tile and holds something, and it isn't used
/// in another pattern's tile or nested more than [`MAX_NEST`] deep?
pub(super) fn pattern_writable(&self, name: &str) -> bool {
if !self.defining.is_empty() || self.nest >= MAX_NEST {
return false;
}
if self.patterns.iter().any(|p| p.name == name) {
return true;
}
self.doc.pattern(name).is_some_and(tile_holds_art)
}
/// Write pattern `name`'s definition, once: `%AI3_BeginPattern: (name)`, `(name) llx lly urx
/// ury` (the tile, y up), the tile's box (an unpainted path whose dictionary marks it,
/// `AIPattern_Editor_Backing_Tile_Rect`) and the art on `%_` lines, `E`, `%AI3_EndPattern`.
/// False when it can't be ([`Self::pattern_writable`]).
fn define_pattern(&mut self, name: &str) -> bool {
if !self.pattern_writable(name) {
return false;
}
let used = !self.in_palette;
if let Some(p) = self.patterns.iter_mut().find(|p| p.name == name) {
p.used |= used;
return true;
}
let doc = self.doc;
let Some(def) = doc.pattern(name) else { return false };
self.defining.push(name.to_string());
// The art is written in the pattern's space, y up, from the state a definition starts in.
let saved = (
std::mem::take(&mut self.body),
(self.to_art, self.grad_space, self.canvas),
self.state.take(),
self.gs.replace(Xy::OPAQUE),
self.clip.take(),
self.block_end,
);
// `Bg` places a gradient in a pattern's tile as on the canvas, mirrored top to bottom: its
// placement is worked out in the tile's space turned y up.
(self.to_art, self.grad_space, self.canvas, self.block_end) = (Affine::FLIP_Y, self.tile_grad_space, Affine::FLIP_Y, usize::MAX);
// The tile's box first, unpainted and marked as the box: the tile is that box.
self.state(false, false);
self.line("0 XR");
if let Some(sp) = vectorcraft_geom::shapes::rectangle(def.tile).subpaths.first() {
crate::ai_ops::subpath(&mut self.body, self.to_art, sp);
}
self.line("n\n%_/ArtDictionary :\n%_1 /Bool (AIPattern_Editor_Backing_Tile_Rect) ,\n%_;\n%_");
self.nest += 1;
self.hidden += 1;
for a in &def.art {
self.node(a);
}
self.hidden -= 1;
self.nest -= 1;
let art;
(art, (self.to_art, self.grad_space, self.canvas), self.state, self.gs, self.clip, self.block_end) = saved;
let art = std::mem::replace(&mut self.body, art);
self.defining.pop();
let tile = Affine::FLIP_Y.transform_rect_bbox(def.tile);
let quoted = ps::bytes(name.as_bytes());
let mut text = format!("%AI3_BeginPattern: {quoted}\n{quoted} ");
ps::push_nums(&mut text, &[tile.x0, tile.y0, tile.x1, tile.y1]);
text.pop();
text.push('\n');
super::hide(&art, &mut text);
text.push_str("E\n%AI3_EndPattern\n");
self.patterns.push(PatternOut { name: name.to_string(), text, used });
true
}
/// Set the fill (or with `stroke`, the stroke) to pattern `name` placed by `xf` (the pattern's
/// space → the document): `(name) 0 0 1 1 0 0 0 0 0 [matrix] p` (`P` for the stroke), the
/// matrix taking the pattern's space (y up, the tile's lower left corner its origin) to the
/// art's. A pattern that can't be defined paints mid gray.
pub(super) fn pattern_paint(&mut self, name: &str, xf: Affine, stroke: bool) {
let height = self.doc.pattern(name).map(|d| d.tile.height());
let Some(h) = height.filter(|_| self.define_pattern(name)) else {
self.warn(super::PATTERNS);
return self.plain_color(Color::gray(0.5), stroke);
};
let m = self.to_art * xf * Affine::translate((0.0, h)) * Affine::FLIP_Y;
let _ = writeln!(self.body, "{} 0 0 1 1 0 0 0 0 0 {} {}", ps::bytes(name.as_bytes()), ps::matrix(m), if stroke { 'P' } else { 'p' });
}
/// The definitions, in the setup before the palette: the gradients the art uses (`n Bn`, then
/// each), those only the palette uses between `%AI5_Begin_NonPrinting`, `Np` and
/// `%AI5_End_NonPrinting--`, then the patterns in the same way (a pattern after those its art
/// uses).
pub(in crate::ai_editing) fn definitions(&mut self, s: &mut String) {
let defs = std::mem::take(&mut self.gradients);
let (used, unused): (Vec<&GradientDef>, Vec<&GradientDef>) = defs.iter().partition(|d| d.used);
let _ = writeln!(s, "{} Bn", used.len());
for d in &used {
self.gradient_def(s, d);
}
if !unused.is_empty() {
let _ = writeln!(s, "%AI5_Begin_NonPrinting\nNp\n{} Bn", unused.len());
for d in &unused {
self.gradient_def(s, d);
}
s.push_str("%AI5_End_NonPrinting--\n");
}
self.gradients = defs;
for p in self.patterns.iter().filter(|p| p.used) {
s.push_str(&p.text);
}
if self.patterns.iter().any(|p| !p.used) {
s.push_str("%AI5_Begin_NonPrinting\nNp\n");
for p in self.patterns.iter().filter(|p| !p.used) {
s.push_str(&p.text);
}
s.push_str("%AI5_End_NonPrinting--\n");
}
}
/// A gradient swatch's or pattern swatch's paint in the palette: `Bb`, a radial gradient's
/// `0 0 0 0 Bh`, `2 (name) 0 0 0 1 1 0 0 1 0 0 1 Bg`, `0 BB`; a pattern's
/// `(name) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p`. False for other paint, and for paint that can't
/// be written.
pub(super) fn swatch_paint(&mut self, s: &mut String, sw: &vectorcraft_color::swatch::Swatch) -> bool {
match &sw.paint {
Paint::Gradient(g) if writable_gradient(&g.gradient) => {
let swatch = Some(sw.name.as_str());
let name = self.define_gradient(&g.gradient, swatch);
s.push_str("Bb\n");
if g.gradient.kind == GradientKind::Radial {
s.push_str("0 0 0 0 Bh\n");
}
let _ = writeln!(s, "2 {} 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB", ps::bytes(name.as_bytes()));
true
}
Paint::Pattern { pattern, xf } if self.define_pattern(pattern) => {
if *xf != Affine::IDENTITY {
self.warn(SWATCH_PLACEMENT);
}
let _ = writeln!(s, "{} 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p", ps::bytes(pattern.as_bytes()));
true
}
_ => false,
}
}
}
/// Where `Bg` places a gradient: its `x y angle length` operands, its matrix, and a radial
/// gradient's focal point as `Bh`'s angle and fraction ([`placement`]).
struct Placement {
bg: [f64; 4],
transform: Affine,
focal: (f64, f64),
}
impl Placement {
/// The gradient's place on the path before it is moved: `0 0 0 1`, the identity.
const UNMOVED: Placement = Placement { bg: [0.0, 0.0, 0.0, 1.0], transform: Affine::IDENTITY, focal: (0.0, 0.0) };
}
/// The `Bg` operands that place gradient `geom` (`radial` or linear) on `path`, both in the canvas's
/// space (y down; `canvas` takes the document there; in a pattern's tile, the tile's space turned y
/// up). `Bg` places a gradient in the space its matrix takes to the canvas's, on the path as it lies
/// there:
///
/// - a linear one's ramp runs at `angle` degrees (counterclockwise, y up) from `x` times the path's
/// extent along that angle past where the path starts along it, `length` times that extent long
/// (`y` doesn't move it);
/// - a radial one's center lies `x` times the width and `y` times the height (y down) of the path's
/// bounds from their center, and its radius is `length` times √((dx² + dy²) / 2), `dx` and `dy` the
/// center's distances to the right side and to the bottom of the bounds, whether or not those are
/// the nearer sides; its focal point lies at `Bh`'s angle (y up), its distance from the center a
/// fraction of the radius.
///
/// A linear gradient is written with the identity, a radial one with the matrix that takes the
/// unit circle onto its extent ellipse at the origin (so that its circle there is the unit circle).
/// [`Placement::UNMOVED`] when the path has no extent along the gradient or the gradient has none.
fn placement(geom: &GradientGeom, radial: bool, path: &BezPath, canvas: Affine) -> Placement {
let s = canvas * geom.start;
let u = canvas * geom.end - s;
if !radial {
let turn = Affine::rotate(-u.atan2());
let along = (turn * path.clone()).bounding_box();
let extent = along.width();
if !(extent > 1e-9 && extent.is_finite() && u.hypot() > 1e-9) {
return Placement::UNMOVED;
}
let bg = [((turn * s).x - along.x0) / extent, 0.0, (-u.y).atan2(u.x).to_degrees(), u.hypot() / extent];
return Placement { bg, ..Placement::UNMOVED };
}
// The unit circle's image: `u` along the vector, `v` across it (the aspect ratio), turning the same way.
let across = geom.end - geom.start;
let mut v = canvas * (geom.start + Vec2::new(-across.y, across.x) * geom.aspect) - s;
if u.cross(v) < 0.0 {
v = -v;
}
let m = Affine::new([u.x, u.y, v.x, v.y, 0.0, 0.0]);
let det = m.determinant().abs();
if det.is_nan() || det <= 1e-12 {
return Placement::UNMOVED;
}
let back = m.inverse();
let b = (back * path.clone()).bounding_box();
let c = back * s;
let (dx, dy) = (b.x1 - c.x, b.y1 - c.y);
let unit = ((dx * dx + dy * dy) / 2.0).sqrt();
if !(b.width() > 1e-9 && b.height() > 1e-9 && unit > 1e-9 && unit.is_finite()) {
return Placement::UNMOVED;
}
let off = geom.focal.map_or(Vec2::ZERO, |f| back * (canvas * f) - c);
let focal = if off.hypot() > 1e-9 { ((-off.y).atan2(off.x).to_degrees(), off.hypot()) } else { (0.0, 0.0) };
let bg = [(c.x - b.center().x) / b.width(), (c.y - b.center().y) / b.height(), 0.0, 1.0 / unit];
Placement { bg, transform: m, focal }
}
/// Do `def`'s tiles make a grid, with its art (something) within the tile? Art past the tile would
/// be cut off at the tile's edge.
fn tile_holds_art(def: &PatternDef) -> bool {
let t = def.tile;
let tile_ok = [t.x0, t.y0, t.x1, t.y1].iter().all(|v| v.is_finite()) && t.width() > 0.0 && t.height() > 0.0;
tile_ok
&& def.tile_type == TileType::Grid
&& def.art_bounds().is_some_and(|b| {
let room = t.inflate(1e-6, 1e-6);
b.x0 >= room.x0 && b.y0 >= room.y0 && b.x1 <= room.x1 && b.y1 <= room.y1
})
}
+8 -5
View File
@@ -49,13 +49,16 @@ pub(crate) fn subpath(s: &mut String, xf: Affine, sp: &SubPath) {
}
}
/// A guide (§6): for each subpath, `(N) *`, its points, `(N) *`; with `closing`, a closed
/// subpath ends `(n) *` (the painting operator that closes it first).
pub(crate) fn guide(s: &mut String, xf: Affine, path: &PathData, closing: bool) {
/// A guide (§6): for each subpath, `(N) *`, its points, `(N) *`. In `editing` data (see
/// [`crate::ai_editing`]) a subpath is its points and `(N) *` alone, `(n) *` when closed (the
/// painting operator that closes it first).
pub(crate) fn guide(s: &mut String, xf: Affine, path: &PathData, editing: bool) {
for sp in path.subpaths.iter().filter(|sp| !sp.anchors.is_empty()) {
s.push_str("(N) *\n");
if !editing {
s.push_str("(N) *\n");
}
subpath(s, xf, sp);
s.push_str(if closing && sp.closed { "(n) *\n" } else { "(N) *\n" });
s.push_str(if editing && sp.closed { "(n) *\n" } else { "(N) *\n" });
}
}
+1
View File
@@ -70,6 +70,7 @@ use graphics::{GState, Out};
use interp::{Fault, Interp};
use obj::PsError;
pub(crate) use ai::MAX_GRADIENT_STOPS;
pub(crate) use native::scale_document;
pub use native::{AiLayers, ai_alone, ai_alone_on_page, ai_layers_alone, is_loss, layered_ai, layered_ai_from};
pub use text::family_style;
+3 -1
View File
@@ -36,8 +36,10 @@ use crate::ps;
pub(crate) use envelope::DRAWN as ENVELOPE_DRAWN;
pub(crate) use frames::text_frames;
pub(crate) use paint::MAX_STOPS as MAX_GRADIENT_STOPS;
pub use read::{
BindingRef, Brushes, IMAGE_TOO_LARGE, PaletteSwatches, Structure, artboards, bindings_note, brushes, palette, read, read_beside, variables,
BindingRef, Brushes, IMAGE_TOO_LARGE, PaletteSwatches, Structure, artboards, bindings_note, brushes, graphic_styles, palette, read, read_beside,
variables,
};
pub(crate) use read::{join_and, slot_frame, slot_of};
+42 -12
View File
@@ -7,8 +7,18 @@
//! - One object, the brush manager's order, has the order of the Brushes panel: its parameters
//! are the plug-in name and brush name of each brush, each one after a `/` and a space.
//! - A Calligraphic brush's parameters are 11 numbers: the first is 1; the diameter, roundness and
//! angle as (low, high) pairs; how the diameter, roundness and angle vary (0 Fixed, 1 Random, 2
//! Pressure, other codes the pen's other channels); a last number.
//! angle as (low, high) pairs; how the diameter, roundness and angle vary; a last number. The
//! codes follow the order of the Brush Options menu: 0 Fixed, 1 Random, 2 Pressure, 3 Stylus
//! Wheel, 4 Tilt, 5 Bearing, 6 Rotation. A user's 6D Art Pen brushes (#372) vary the diameter
//! with 2, the roundness with 5 and the angle with 6, the angle over a whole turn, as the barrel
//! rotation turns the nib. VectorCraft reads no stylus wheel: 3 is read as Random when the value
//! varies, as an unknown code is.
//! - A path with a Calligraphic brush is a stroke in its art style ([`super::style`]): the filter
//! `(Adobe Calligraphic Brush Tool)`, its stroke's paint and weight (the weight scales the brush:
//! 1 pt draws it at its own size), the brush by name (`/GObjRef : (name) (plug-in)
//! /PluginObject`), and the brush's settings for this path as entries: `Diameter`, `Roundness`,
//! `Angle`, their `…Variation` either side and `…DependsOn` codes, and `AngleRelativeTo` (0 the
//! page).
//! - A Scatter, Art or Pattern brush's parameters are fields split by `/`: a number, the art's
//! section names (one for Scatter, five for Art and Pattern, empty where there is none, each
//! after a space for Art and Pattern), more fields, and last 15 numbers.
@@ -168,12 +178,15 @@ fn numbers(s: &str) -> Option<Vec<f64>> {
s.split_whitespace().map(|w| w.parse::<f64>().ok().filter(|v| v.is_finite())).collect()
}
/// How a value varies, by its code: `None` for a code that isn't Fixed, Random or Pressure.
/// How a value varies, by its code: `None` for the stylus wheel and codes that aren't known.
fn variation(code: f64) -> Option<Variation> {
match code {
0.0 => Some(Variation::Fixed),
1.0 => Some(Variation::Random),
2.0 => Some(Variation::Pressure),
4.0 => Some(Variation::Tilt),
5.0 => Some(Variation::Bearing),
6.0 => Some(Variation::Rotation),
_ => None,
}
}
@@ -183,6 +196,27 @@ fn mode(code: f64, varies: bool) -> Variation {
variation(code).unwrap_or(if varies { Variation::Random } else { Variation::Fixed })
}
/// A Calligraphic brush of angle, roundness and size `values`, each varying `variation` either side
/// as its code in `codes` says.
pub(super) fn calligraphic(values: [f64; 3], variation: [f64; 3], codes: [f64; 3]) -> Calligraphic {
let [angle, roundness, size] = values;
let modes = [0, 1, 2].map(|i| mode(codes[i], variation[i] != 0.0));
Calligraphic { angle, roundness, size, variation, modes: Some(modes) }
}
/// Does the brush `draft` draw as `c`, the settings a path's art style gives it? A path whose
/// settings differ (Options of Selected Object) keeps its drawn look: a stroke names a brush, and
/// has no settings of its own.
pub(super) fn draws_as(draft: &BrushDraft, c: &Calligraphic) -> bool {
let DraftKind::Calligraphic(d) = &draft.kind else { return false };
let close = |a: f64, b: f64| (a - b).abs() <= 1e-3 * a.abs().max(b.abs()).max(1.0);
close(d.angle, c.angle)
&& close(d.roundness, c.roundness)
&& close(d.size, c.size)
&& d.variation.iter().zip(&c.variation).all(|(a, b)| close(*a, *b))
&& d.modes() == c.modes()
}
/// The brush named `name` of kind `kind` from its parameters `params`.
pub(super) fn parse_tool_object(kind: Tool, name: &str, params: &str) -> Result<BrushDraft, BrushError> {
let kind = match kind {
@@ -191,15 +225,11 @@ pub(super) fn parse_tool_object(kind: Tool, name: &str, params: &str) -> Result<
let [_, d0, d1, r0, r1, a0, a1, dm, rm, am, ..] = n.as_slice() else { return Err(BrushError::Values) };
let mid = |a: f64, b: f64| (a + b) / 2.0;
let half = |a: f64, b: f64| (b - a).abs() / 2.0;
let variation = [half(*a0, *a1), half(*r0, *r1), half(*d0, *d1)];
let modes = [mode(*am, variation[0] != 0.0), mode(*rm, variation[1] != 0.0), mode(*dm, variation[2] != 0.0)];
DraftKind::Calligraphic(Calligraphic {
angle: mid(*a0, *a1),
roundness: mid(*r0, *r1),
size: mid(*d0, *d1),
variation,
modes: Some(modes),
})
DraftKind::Calligraphic(calligraphic(
[mid(*a0, *a1), mid(*r0, *r1), mid(*d0, *d1)],
[half(*a0, *a1), half(*r0, *r1), half(*d0, *d1)],
[*am, *rm, *dm],
))
}
Tool::Scatter | Tool::Art | Tool::Pattern => {
let fields: Vec<&str> = params.split('/').collect();
+340 -63
View File
@@ -1,40 +1,73 @@
//! Type in the legacy format (version 7 specification §15): text objects `type To` … `TO`, their
//! text path (`a b c d tx ty startPt Tp`, an area's frame or the path type runs along, `TP`), the
//! modal character and paragraph attributes (`Tr Tf Ts Tz Tt TA Tl Ta Ti`, and §15.4.7 and §22's
//! letter and word spacing `TC TW`, hanging punctuation `Tq` and hyphenation `Th`), the paint style, and
//! the characters (`Tx`, `Tj`, overflow `TX`; `\r` ends a paragraph). Final-form operators (the
//! text paths (`a b c d tx ty startPt Tp`, an area's frame, one for each linked area, or the path
//! type runs along, `TP`), the modal character and paragraph attributes
//! (`Tr Tf Ts Tz Tt TA Tl Ta Ti`, and §15.4.7 and §22's letter and word spacing `TC TW`, hanging
//! punctuation `Tq`, hyphenation `Th` and tab stops `Xb Xe XB`), the paint style, and the characters (`Tx`, `Tj`,
//! overflow `TX`; `\r` ends a paragraph). Type set in rendering modes 4 to 7 is a mask (§5.7): the
//! text object clips the objects of its clipping group. Final-form operators (the
//! computed positions, §15.1) are skipped: the type is laid out again. Strings are decoded by the
//! file's `TE` encoding, else as Windows-1252; a re-encoded font `/_name` is the font its
//! `%AI3_BeginEncoding` names (else `name`).
//! encoding pairs of the current font's `TZ`, then by the file's `TE` encoding unless that `TZ`'s
//! `useDefault` is 0, else as Windows-1252; a re-encoded font `/_name` is the font its `%AI3_BeginEncoding` or `TZ` names
//! (else `name`).
use kurbo::{Affine, BezPath, ParamCurve, ParamCurveArclen};
use vectorcraft_color::Paint;
use vectorcraft_doc::{CharStyle, Justify, NodeKind, ParaStyle, TextKind, TextObject, TextRun};
use vectorcraft_doc::{CharStyle, Justify, NodeKind, ParaStyle, TabAlign, TabStop, TextKind, TextObject, TextRun};
use vectorcraft_geom::AnchorKind;
use super::super::obj::V;
use super::art::path_data;
use super::{FLIP, GState, Reader};
use super::{FLIP, GState, HashSet, Kind, Node, NodeId, Reader};
use crate::latin;
/// Most characters of type read in one file.
const MAX_CHARS: usize = 1 << 22;
/// Largest type size and indent read (points).
const MAX_SIZE: f64 = 1e4;
/// Most re-encoded fonts read in one file, for their names and for their encodings each.
const MAX_FONTS: usize = 4096;
/// Most tab stops read in one tab definition.
const MAX_TABS: usize = 1024;
/// Largest tab stop position read (points), as `text.tabs.set` takes it.
const MAX_TAB_POSITION: f64 = 100_000.0;
/// Most values read before one operator in a re-encoding section.
const MAX_ENCODING_VALUES: usize = 1024;
/// Most text paths read in one text object (its linked areas); the frames of others are left out,
/// with a warning.
const MAX_TEXT_PATHS: usize = 4096;
/// Most frames of linked areas times characters of their story: the story is laid out again
/// through its frames when the file opens. The frames of the areas past it are left out, with a
/// warning.
const MAX_THREAD_WORK: usize = MAX_CHARS;
/// The warning when [`MAX_TEXT_PATHS`] or [`MAX_THREAD_WORK`] leaves frames of linked areas out.
const LINKED_AREAS_LEFT_OUT: &str = "linked type areas past VectorCraft's limits were left out";
/// The warning when type set in a mask rendering mode can't be a clipping path: type in linked
/// areas (several frames), in wraparound text or in a compound path doesn't clip.
const MASK_NOT_CLIPPED: &str = "type used as a mask in linked areas, wraparound text or a compound path doesn't clip";
/// A text path (`Tp` … `TP`).
#[derive(Debug, Default)]
struct TextPath {
/// `Tp`'s matrix: text space (y up) → art space.
matrix: Option<Affine>,
/// Where type on a path starts: a segment's index plus how far along it.
start: f64,
/// The frame or path, in art space, and the kind of the anchor each of its segments ends on.
path: Option<(BezPath, Vec<AnchorKind>)>,
}
/// A text object being read.
#[derive(Debug, Default)]
pub(super) struct LegacyText {
/// `To`'s type: 0 point type, 1 area type, 2 type on a path.
kind: i64,
/// `Tp`'s matrix: text space (y up) → art space.
matrix: Option<Affine>,
/// Where type on a path starts: a segment's index plus how far along it.
start: f64,
/// Its text paths in file order: area type has one for each linked area (§15.5.3).
paths: Vec<TextPath>,
/// Between `Tp` and `TP`: the path read is the text path.
in_path: bool,
/// The frame or path, in art space, and the kind of the anchor each of its segments ends on.
path: Option<(BezPath, Vec<AnchorKind>)>,
/// It has more than [`MAX_TEXT_PATHS`] text paths: the paths read past them are left out.
past_limit: bool,
/// The story: the characters after every text path, in file order.
runs: Vec<TextRun>,
/// Each paragraph's attributes, as they were at its first character.
paras: Vec<ParaStyle>,
@@ -42,6 +75,9 @@ pub(super) struct LegacyText {
para_taken: bool,
/// An overflow paragraph break (`(\r) TX`) not yet followed by type: the story's end.
pending_break: bool,
/// Characters were set in a mask rendering mode (`Tr` 4 to 7): the text object is a clipping
/// path (§5.7).
clips: bool,
/// The state when it began (lock, visibility), and whether it began on a `%_` line.
gs: GState,
hidden: bool,
@@ -56,14 +92,31 @@ pub(super) struct TypeState {
render: i64,
/// The encoding strings are in, by code (`TE`); None where it says nothing.
encoding: Vec<Option<char>>,
/// Re-encoded fonts' original names (`%AI3_BeginEncoding: _new old`).
/// Re-encoded fonts' original names (`%AI3_BeginEncoding: _new old`, or `TZ`'s).
fonts: Vec<(String, String)>,
/// Re-encoded fonts' own encodings (`TZ`), by the new font's name: what its encoding pairs
/// change, by code (None where they say nothing), and whether `TE`'s encoding applies to it.
font_encodings: Vec<(String, Vec<Option<char>>, bool)>,
/// The font `Tf` set last, as the file names it.
font: Option<String>,
/// Between `Xb` and `XB`: the tab stops of the tab definition read so far.
tabs: Option<Vec<TabStop>>,
chars: usize,
}
impl Default for TypeState {
fn default() -> Self {
Self { style: CharStyle::default(), para: ParaStyle::default(), render: 0, encoding: vec![None; 256], fonts: vec![], chars: 0 }
Self {
style: CharStyle::default(),
para: ParaStyle::default(),
render: 0,
encoding: vec![None; 256],
fonts: vec![],
font_encodings: vec![],
font: None,
tabs: None,
chars: 0,
}
}
}
@@ -72,10 +125,51 @@ impl TypeState {
pub(super) fn encoding_comment(&mut self, line: &str) {
let Some((_, names)) = line.split_once(':') else { return };
let mut words = names.split_whitespace();
if let (Some(new), Some(old)) = (words.next(), words.next())
&& self.fonts.len() < 4096
{
self.fonts.push((new.trim_start_matches('/').to_string(), old.trim_start_matches('/').to_string()));
if let (Some(new), Some(old)) = (words.next(), words.next()) {
self.font_names(new.trim_start_matches('/'), old.trim_start_matches('/'));
}
}
/// Re-encoded font `new` is font `old`. The first statement for a name is used.
fn font_names(&mut self, new: &str, old: &str) {
if self.fonts.len() < MAX_FONTS && !self.fonts.iter().any(|(n, _)| n == new) {
self.fonts.push((new.to_string(), old.to_string()));
}
}
/// A string's bytes, in the current font.
fn decode(&self, bytes: &[u8]) -> String {
let own = self.font.as_ref().and_then(|f| self.font_encodings.iter().find(|(n, _, _)| n == f));
let (own, te) = own.map_or((None, true), |(_, e, te)| (Some(e.as_slice()), *te));
bytes
.iter()
.map(|&b| {
if b == b'\r' {
return '\n';
}
own.and_then(|e| e.get(usize::from(b)).copied().flatten())
.or_else(|| if te { self.encoding.get(usize::from(b)).copied().flatten() } else { None })
.unwrap_or_else(|| latin::decode(b))
})
.collect()
}
}
/// Encoding pairs (§3.3.1): codes, each followed by the glyph names from it on, into `table`.
fn encoding_pairs(table: &mut [Option<char>], vals: &[V]) {
let mut code: Option<usize> = None;
for v in vals {
match v {
V::Num(n) if n.is_finite() && (0.0..256.0).contains(n) => code = Some(*n as usize),
V::Name(name) => {
if let Some(c) = code {
if let (Some(slot), Ok(b)) = (table.get_mut(c), u8::try_from(c)) {
*slot = latin::glyph(b, name);
}
code = Some(c + 1);
}
}
_ => {}
}
}
}
@@ -102,19 +196,86 @@ fn flag(v: f64) -> Option<bool> {
impl Reader<'_> {
/// `[encodingPairs TE`: codes, each followed by the glyph names from it on (§3.3.1).
pub(super) fn te(&mut self, vals: &[V]) {
let mut code: Option<usize> = None;
for v in vals {
match v {
V::Num(n) if n.is_finite() && (0.0..256.0).contains(n) => code = Some(*n as usize),
V::Name(name) => {
if let Some(c) = code {
if let (Some(slot), Ok(b)) = (self.type_state.encoding.get_mut(c), u8::try_from(c)) {
*slot = latin::glyph(b, name);
}
code = Some(c + 1);
encoding_pairs(&mut self.type_state.encoding, vals);
}
/// `[encodingPairs newFontName oldFontName direction fontScript useDefault TZ`, with a Multiple
/// Master weight vector `[w0 … wn]` after it, and without the encoding pairs or the direction
/// in some versions (§3.3.1): the new font's own encoding pairs, which strings in it are
/// decoded by first. `useDefault` 1 (or no number after the names) decodes the codes the pairs
/// leave out by `TE`'s encoding, and 0 leaves `TE`'s encoding out for the font. The font names
/// are the last two names; only numbers and the weight vector follow them. The first `TZ` for
/// a font is used.
pub(super) fn tz(&mut self, vals: &[V]) {
let mut names = vals.iter().enumerate().filter_map(|(i, v)| if let V::Name(n) = v { Some((i, n)) } else { None }).rev();
let (Some((old_at, old)), Some((new_at, new))) = (names.next(), names.next()) else { return };
if new_at + 1 != old_at {
return;
}
let tail = vals.get(old_at + 1..).unwrap_or_default();
let weights = matches!(tail.last(), Some(V::Arr(_)));
let numbers = tail.get(..tail.len() - usize::from(weights)).unwrap_or_default();
if !numbers.iter().all(|v| matches!(v, V::Num(_))) {
return;
}
let te = !matches!(numbers.last(), Some(V::Num(n)) if *n == 0.0);
let st = &mut self.type_state;
st.font_names(new, old);
if st.font_encodings.iter().any(|(n, _, _)| n == new) || st.font_encodings.len() >= MAX_FONTS {
return;
}
// The pairs start after the `[` that opens them.
let pairs = vals.get(..new_at).unwrap_or_default();
let pairs = pairs.iter().rposition(|v| matches!(v, V::Mark)).map_or(pairs, |m| pairs.get(m + 1..).unwrap_or_default());
let mut table = vec![None; 256];
encoding_pairs(&mut table, pairs);
st.font_encodings.push((new.clone(), table, te));
}
/// What is between `%AI3_BeginEncoding` and `%AI3_EndEncoding` (§3.3): its `TZ` is read, and
/// every other operator is skipped with its operands.
pub(super) fn encoding_section(&mut self, section: &[u8]) {
let mut lex = super::Lexer::new(section);
let mut vals: Vec<V> = Vec::new();
let mut marks: Vec<usize> = Vec::new();
// `[`s past the value limit, which are not kept: as many `]`s after them are skipped.
let mut dropped: usize = 0;
while let Some(t) = lex.next_token() {
let v = match t.tok {
super::Tok::Num(n) => V::Num(n),
super::Tok::Name(n) => V::Name(super::obj::text(n)),
super::Tok::Str(s) | super::Tok::Hex(s) => V::Str(s),
super::Tok::Word(b"[") => {
// Each `[` kept is a value, so the open arrays are no more than the values.
if vals.len() >= MAX_ENCODING_VALUES {
dropped = dropped.saturating_add(1);
continue;
}
marks.push(vals.len());
V::Mark
}
_ => {}
super::Tok::Word(b"]") => {
if dropped > 0 {
dropped -= 1;
continue;
}
let Some(m) = marks.pop() else { continue };
let items: Vec<V> = vals.split_off(m.min(vals.len())).into_iter().skip(1).collect();
V::Arr(items)
}
super::Tok::Word(w) => {
if w == b"TZ" {
self.tz(&vals);
}
vals.clear();
marks.clear();
dropped = 0;
continue;
}
_ => continue,
};
if vals.len() < MAX_ENCODING_VALUES {
vals.push(v);
}
}
}
@@ -131,6 +292,8 @@ impl Reader<'_> {
self.unreadable("type in a pattern", false);
}
let kind = nums::<1>(vals).map_or(0, |[k]| k as i64);
// A tab definition left open by an earlier text object (an `Xb` with no `XB`) ends here.
self.type_state.tabs = None;
self.text = Some(LegacyText { kind, gs: self.gs.clone(), hidden, ..LegacyText::default() });
}
@@ -144,27 +307,28 @@ impl Reader<'_> {
6 => (nums::<6>(vals), None),
_ => (None, None),
};
if let Some(m) = m {
let m = Affine::new(m);
let matrix = m.map(Affine::new).filter(|m| {
let det = m.determinant();
if det.is_finite() && det.abs() > 1e-12 {
t.matrix = Some(m);
}
det.is_finite() && det.abs() > 1e-12
});
let start = start.filter(|s| s.is_finite() && *s >= 0.0).unwrap_or(0.0);
t.past_limit |= t.paths.len() >= MAX_TEXT_PATHS;
if !t.past_limit {
t.paths.push(TextPath { matrix, start, path: None });
}
t.start = start.filter(|s| s.is_finite() && *s >= 0.0).unwrap_or(0.0);
t.in_path = true;
}
/// The path painted (or `TP`, ending the text path): the text object's frame or path.
/// The path painted (or `TP`, ending the text path): the text path's frame or path.
pub(super) fn text_path(&mut self) {
let path = std::mem::take(&mut self.path);
let kinds = std::mem::take(&mut self.path_kinds);
self.end_path_quietly();
if let Some(t) = self.text.as_mut()
&& t.path.is_none()
if let Some(p) = self.text.as_mut().filter(|t| !t.past_limit).and_then(|t| t.paths.last_mut())
&& p.path.is_none()
&& !path.elements().is_empty()
{
t.path = Some((path, kinds));
p.path = Some((path, kinds));
}
}
@@ -182,8 +346,9 @@ impl Reader<'_> {
let st = &mut self.type_state;
let n0 = nums::<1>(vals).map(|[v]| v);
match w {
// `render Tr`: a mode from 0 to 9 (§15.4.5.1).
"Tr" => {
if let Some(v) = n0 {
if let Some(v) = n0.filter(|v| v.fract() == 0.0 && (0.0..=9.0).contains(v)) {
st.render = v as i64;
}
}
@@ -191,6 +356,7 @@ impl Reader<'_> {
// `/name size Tf`, or `/name size ascent descent Tf`.
let Some(at) = vals.iter().position(|v| matches!(v, V::Name(_))) else { return };
if let Some(V::Name(name)) = vals.get(at) {
st.font = Some(name.clone());
let name =
st.fonts.iter().find(|(new, _)| new == name).map_or_else(|| name.trim_start_matches('_').to_string(), |(_, old)| old.clone());
let (family, style) = super::super::super::text::family_style(&name);
@@ -293,6 +459,37 @@ impl Reader<'_> {
h.before_last = letters(tail, 1.0, 15.0);
h.hyphen_limit = if limit { letters(max, 0.0, 25.0) } else { 0 };
}
// A tab definition (§22.6): `numDots numTabs Xb` begins it, each
// `leader decimal tabType tabPosition Xe` describes one tab stop, and `XB` ends it. The
// stops it describes replace the paragraph's tab stops, sorted by position, one stop at
// each position; a definition with none (or whose descriptions were all skipped) leaves
// the default stops. The dot-leader distance, the count and the two reserved operands are
// not read. A description whose type is not 1 to 4 (left, center, right, decimal) or
// whose position is not a number from 0 to [`MAX_TAB_POSITION`] is skipped, and so is one
// outside a tab definition or past the first [`MAX_TABS`] of one. A text object's `To`
// ends a definition that an earlier object left open.
"Xb" => st.tabs = Some(vec![]),
"Xe" => {
let Some(tabs) = st.tabs.as_mut().filter(|t| t.len() < MAX_TABS) else { return };
let Some([kind, position]) = nums::<2>(vals) else { return };
let align = match kind {
1.0 => TabAlign::Left,
2.0 => TabAlign::Center,
3.0 => TabAlign::Right,
4.0 => TabAlign::Decimal,
_ => return,
};
if (0.0..=MAX_TAB_POSITION).contains(&position) {
tabs.push(TabStop { position, align, leader: String::new(), align_on: '.' });
}
}
"XB" => {
if let Some(mut tabs) = st.tabs.take() {
tabs.sort_by(|a, b| a.position.total_cmp(&b.position));
tabs.dedup_by(|a, b| (a.position - b.position).abs() < 1e-6);
st.para.tabs = tabs;
}
}
_ => {}
}
}
@@ -302,10 +499,7 @@ impl Reader<'_> {
let Some(bytes) = vals.iter().rev().find_map(|v| if let V::Str(s) = v { Some(s.clone()) } else { None }) else { return };
let st = &mut self.type_state;
let Some(t) = self.text.as_mut() else { return };
let decoded: String = bytes
.iter()
.map(|&b| if b == b'\r' { '\n' } else { st.encoding.get(usize::from(b)).copied().flatten().unwrap_or_else(|| latin::decode(b)) })
.collect();
let decoded = st.decode(&bytes);
if decoded.is_empty() {
return;
}
@@ -323,6 +517,9 @@ impl Reader<'_> {
st.chars += decoded.chars().count();
let gs = &self.gs;
let mut style = st.style.clone();
// Characters in modes 4 to 7 make the whole text object the mask, not each run (§5.7); 7
// paints nothing, nor does 3 (invisible).
t.clips |= (4..=7).contains(&st.render);
let (fill, stroke) = match st.render {
0 | 4 => (true, false),
1 | 5 => (false, true),
@@ -358,35 +555,115 @@ impl Reader<'_> {
}
}
/// `TO`: the text object ends.
/// `TO`: the text object ends. Area type with several linked areas becomes one frame for each
/// area, threaded in file order: the first frame holds the story, and the flow from area to
/// area (final-form, §15.1) is laid out again. The frames are added last to first, so the
/// object's dictionary that follows names the first one ([`Reader::each_linked_frame`]).
/// Point type is read at its first text path; area type and type on a path at the first one
/// that has a frame or path (else at the first one, as point type).
pub(super) fn end_text(&mut self, hidden: bool) -> Result<(), String> {
let Some(t) = self.text.take() else { return Ok(()) };
if t.runs.is_empty() {
return Ok(());
}
let m = t.matrix.unwrap_or(Affine::IDENTITY);
let to_doc = self.space();
// Art space → text space (y down).
let to_text = FLIP * m.inverse();
let kind = match (t.kind, &t.path) {
(1, Some((p, kinds))) => TextKind::Area { frame: path_data(&(to_text * p.clone()), kinds) },
(2, Some((p, kinds))) => {
TextKind::OnPath { path: path_data(&(to_text * p.clone()), kinds), start: start_fraction(p, t.start), end: None }
}
_ => TextKind::Point,
let chars: usize = t.runs.iter().map(|r| r.text.chars().count()).sum();
let most = (MAX_THREAD_WORK / chars.max(1)).max(1);
let all_areas = t.paths.iter().filter(|p| p.path.is_some()).count();
// Area type with linked areas, also when the limits leave one frame of it.
let linked = t.kind == 1 && (all_areas > 1 || t.past_limit);
let areas: Vec<&TextPath> = t.paths.iter().filter(|p| p.path.is_some()).take(most).collect();
let placed: Vec<(Affine, TextKind)> = match t.kind {
1 if areas.len() > 1 => areas.into_iter().map(|p| placed(1, Some(p))).collect(),
0 => vec![placed(0, t.paths.first())],
kind => vec![placed(kind, areas.first().copied().or(t.paths.first()))],
};
let mut obj = TextObject::point(kurbo::Point::ZERO, "", CharStyle::default());
obj.kind = kind;
obj.xf = to_doc * m * FLIP;
obj.runs = t.runs;
if t.kind == 1 && (t.past_limit || all_areas > placed.len()) {
self.warn(LINKED_AREAS_LEFT_OUT);
}
let mut paras = t.paras;
if paras.is_empty() {
paras.push(self.type_state.para.clone());
}
obj.set_paragraph_styles(paras);
let node = self.new_node(NodeKind::Text(Box::new(obj)), &t.gs);
self.add(node, t.hidden || hidden)
let last_para = paras.last().cloned().unwrap_or_default();
let last_style = t.runs.last().map(|r| r.style.clone()).unwrap_or_default();
let mut story = Some((t.runs, paras));
let mut nodes = Vec::with_capacity(placed.len());
for (m, kind) in placed {
let mut obj = TextObject::point(kurbo::Point::ZERO, "", last_style.clone());
obj.kind = kind;
obj.xf = to_doc * m * FLIP;
match story.take() {
Some((runs, paras)) => {
obj.runs = runs;
obj.set_paragraph_styles(paras);
}
None => obj.set_paragraph_styles(vec![last_para.clone()]),
}
nodes.push(self.new_node(NodeKind::Text(Box::new(obj)), &t.gs));
}
let frames: Vec<NodeId> = nodes.iter().map(|n| n.id).collect();
// Type used as a mask clips the objects of its clipping group, as a `W` path does. A
// clipping path is one object, and wraparound text and compound paths don't clip their
// objects with type, so the frames of linked areas and type in those don't clip, with a
// warning. The frames up to the clipping group or opacity mask's art are checked, a group in
// either included.
let in_wrap_or_compound = self
.frames
.iter()
.rev()
.take_while(|f| !matches!(f.kind, Kind::Clip | Kind::Mask | Kind::Layer(_)))
.any(|f| matches!(f.kind, Kind::Wrap | Kind::Compound));
let can_clip = !linked && nodes.len() == 1 && !in_wrap_or_compound;
if t.clips && !can_clip {
self.warn(MASK_NOT_CLIPPED);
}
for node in nodes.into_iter().rev() {
if t.clips
&& can_clip
&& let Some(f) = self.frames.last_mut()
{
f.clips.push(f.children.len());
}
self.add(node, t.hidden || hidden)?;
}
if frames.len() > 1 {
self.doc.text_threads.push(frames);
}
Ok(())
}
/// Call `f` on the other frames of the threaded text object just read, whose first frame is
/// the last object ([`Reader::end_text`]): the opacity mask and text wrap of the object's
/// dictionary apply to every frame.
pub(super) fn each_linked_frame(&mut self, mut f: impl FnMut(&mut Node)) {
if !self.after_object {
return;
}
let Some(first) = self.frames.last().and_then(|fr| fr.children.last()).map(|n| n.id) else { return };
let Some(thread) = self.doc.text_threads.last().filter(|t| t.first() == Some(&first)) else { return };
let rest: HashSet<NodeId> = thread.iter().skip(1).copied().collect();
let Some(fr) = self.frames.last_mut() else { return };
for n in fr.children.iter_mut().rev().skip(1).take(rest.len()).filter(|n| rest.contains(&n.id)) {
f(n);
}
}
}
/// A text object of type `kind` on text path `p` (none: at the origin): the matrix from text space
/// (y up) to art space, and the kind of type with its frame or path in text space (y down).
fn placed(kind: i64, p: Option<&TextPath>) -> (Affine, TextKind) {
let m = p.and_then(|p| p.matrix).unwrap_or(Affine::IDENTITY);
// Art space → text space (y down).
let to_text = FLIP * m.inverse();
let kind = match (kind, p.and_then(|p| p.path.as_ref().map(|path| (path, p.start)))) {
(1, Some(((path, kinds), _))) => TextKind::Area { frame: path_data(&(to_text * path.clone()), kinds) },
(2, Some(((path, kinds), start))) => {
TextKind::OnPath { path: path_data(&(to_text * path.clone()), kinds), start: start_fraction(path, start), end: None }
}
_ => TextKind::Point,
};
(m, kind)
}
/// Where type on `path` starts (`index.fraction`: a segment and how far along it, §15.5.2), as a
+61 -5
View File
@@ -55,6 +55,56 @@ const RELATIVE: [&[u8]; 2] = [b"%AI28_BeginPlacedRelativePath", b"%AI28_EndPlace
/// A document included whole: (begin, end) markers.
const DOCUMENT: (&[u8], &[u8]) = (b"%%BeginDocument", b"%%EndDocument");
/// The line of `src` before the one that starts at `at`, without its line end, when it ends within
/// [`OPERAND_LINE`] bytes of `at` and is no longer than that.
fn previous_line(src: &[u8], at: usize) -> Option<&[u8]> {
let before = src.get(at.saturating_sub(OPERAND_LINE)..at)?;
let end = before.iter().rposition(|b| !is_eol(*b))? + 1;
let start = before.get(..end)?.iter().rposition(|b| is_eol(*b))? + 1;
before.get(start..end)
}
/// The longest line of an image's `XI` operands looked at.
const OPERAND_LINE: usize = 1024;
/// How many bytes the alpha channel of an image whose `XI` operands are on `line` takes (`[matrix]
/// llx lly urx ury w h bits type alpha …`, `%_` before them in a hidden object): a byte a pixel when
/// the alpha count isn't 0, else none (or when the operands aren't of that shape).
fn alpha_bytes(line: &[u8]) -> usize {
let line = line.strip_prefix(b"%_").unwrap_or(line);
let Some(after) = line.iter().rposition(|b| *b == b']').and_then(|i| line.get(i + 1..)) else { return 0 };
let nums: Vec<f64> = std::str::from_utf8(after).unwrap_or_default().split_whitespace().take(9).map_while(|w| w.parse().ok()).collect();
match (nums.get(4), nums.get(5), nums.get(8)) {
// At most the pixels the reader reads an image with.
(Some(&w), Some(&h), Some(&a)) if a > 0.0 && w >= 1.0 && h >= 1.0 && w * h <= (1u64 << 25) as f64 => (w * h) as usize,
_ => 0,
}
}
/// Where in `w` the `%%EndData` that ends an image's samples starts: the first one on a line whose
/// next line is `XH` (`%_XH` in a hidden object), as an image's is; else the first one that a line
/// end, or the end of `w`, follows.
fn end_data(w: &[u8]) -> Option<usize> {
const MARK: &[u8] = b"%%EndData";
let mut first = None;
let mut at = 0;
while let Some(i) = w.get(at..).and_then(|r| find(r, MARK)) {
let i = at + i;
let rest = w.get(i + MARK.len()..).unwrap_or_default();
if rest.first().is_none_or(|b| matches!(b, b'\r' | b'\n')) {
let next = rest.strip_prefix(b"\r").unwrap_or(rest);
let next = next.strip_prefix(b"\n").unwrap_or(next);
let next = next.strip_prefix(b"%_").unwrap_or(next);
if next.starts_with(b"XH") {
return Some(i);
}
first = first.or(Some(i));
}
at = i + 1;
}
first
}
fn is_space(b: u8) -> bool {
matches!(b, b' ' | b'\t' | b'\r' | b'\n' | b'\x0c' | b'\0')
}
@@ -232,12 +282,18 @@ impl<'a> Lexer<'a> {
(Some(b'\r' | b'\n'), _) => data += 1,
_ => {}
}
// The count leaves out an alpha channel: the data ends where `%%EndData` starts.
// The count leaves out an alpha channel: the data ends where `%%EndData` starts, the first one
// that a line end or the end of the data follows (samples can hold the marker's bytes).
let declared = from.saturating_add(n).min(self.src.len()).max(data);
let window =
self.src.get(declared.saturating_sub(4).max(data)..declared.saturating_add(n.saturating_mul(2)).saturating_add(64).min(self.src.len()));
let end = match window.and_then(|w| find(w, b"%%EndData")) {
Some(i) => declared.saturating_sub(4).max(data) + i,
// The alpha channel the line before gives the image (its `XI` operands) follows the counted
// samples: the marker is looked for after it.
let line_start = self.pos.saturating_sub(line.len());
let line_start = if line_start >= 2 && self.src.get(line_start - 2..line_start) == Some(b"%_") { line_start - 2 } else { line_start };
let alpha = previous_line(self.src, line_start).map_or(0, alpha_bytes);
let start = if alpha > 0 { declared.saturating_add(alpha).saturating_sub(2) } else { declared.saturating_sub(4) }.max(data);
let stop = declared.saturating_add(n.saturating_mul(2)).saturating_add(64).max(start.saturating_add(64)).min(self.src.len());
let end = match self.src.get(start..stop).and_then(end_data) {
Some(i) => start + i,
None => declared,
};
self.pos = end;
+233 -11
View File
@@ -18,19 +18,24 @@
//! `Bm` for each pair in the order of the ramp (`Bc`, around them, are the caps past the first and
//! last stops). Without `Xm`, a radial gradient's one `Bm` takes the unit circle onto it.
//!
//! - The name shown for a gradient's or a pattern's name in the file is the part before its first
//! newline (`\n`) ([`ShownNames`]).
//!
//! "AI7 spec": Adobe Illustrator File Format Specification, version 7.0 (1998), listed by PRONOM at
//! https://www.nationalarchives.gov.uk/PRONOM/fmt/423; §3.5 documents the gradient operators.
//! https://www.nationalarchives.gov.uk/PRONOM/fmt/423; §3.5 documents the gradient operators and §4
//! the names of global objects.
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use kurbo::{Affine, Point, Vec2};
use vectorcraft_color::gradient::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
use vectorcraft_color::{Color, Paint};
use super::lex::{Lexer, Tok};
use super::obj::V;
/// Largest number of stops read in one gradient.
const MAX_STOPS: usize = 256;
pub(crate) const MAX_STOPS: usize = 256;
/// A colour read with the swatch it names (spot and global colours).
#[derive(Clone, Debug, PartialEq)]
@@ -172,7 +177,16 @@ impl GradientDef {
}
// Stops are listed along the ramp from either end: listed downwards they're reversed, so
// stops sharing a ramp point keep their order (and each its midpoint, to the next stop).
if self.gradient.stops.first().zip(self.gradient.stops.last()).is_some_and(|(first, last)| first.offset > last.offset) {
// When every stop shares one ramp point, a linear gradient's are taken as listed from the
// last, as newer files list a linear gradient's stops.
let linear = self.gradient.kind == GradientKind::Linear;
if self
.gradient
.stops
.first()
.zip(self.gradient.stops.last())
.is_some_and(|(first, last)| first.offset > last.offset || (linear && self.gradient.stops.len() > 1 && first.offset == last.offset))
{
self.gradient.stops.reverse();
}
self.gradient.stops.sort_by(|a, b| a.offset.total_cmp(&b.offset));
@@ -180,6 +194,157 @@ impl GradientDef {
}
}
/// The names of the named colors in the tokens [`Self::token`] is given: those the color operators
/// (`x`, `Xx`, `Xk` and their stroke forms) and gradient stops (`Bs` between `Bd` and `BD`) use,
/// also in the color and tile strings of patterns in the version 7 form (`(…) @`, `(…) &`). It
/// also keeps the names of the gradients `BD` finishes ([`GradientDef::finish`]).
#[derive(Default)]
pub(super) struct ColorNames {
pub names: HashSet<String>,
pub gradients: Vec<String>,
vals: Vec<V>,
def: Option<GradientDef>,
spots: Vec<Named>,
}
impl ColorNames {
pub fn token(&mut self, tok: Tok<'_>) {
self.take(tok, true);
}
/// [`Self::token`], with the names in the strings of a version 7 pattern's layer when `outer`.
fn take(&mut self, tok: Tok<'_>, outer: bool) {
let w = match tok {
Tok::Num(n) => {
if self.vals.len() < MAX_STOPS {
self.vals.push(V::Num(n));
}
return;
}
Tok::Str(s) | Tok::Hex(s) => {
if self.vals.len() < MAX_STOPS {
self.vals.push(V::Str(s));
}
return;
}
Tok::Word(w) => w,
_ => return,
};
let vals = std::mem::take(&mut self.vals);
match w {
b"Bd" => self.def = GradientDef::begin(&vals),
b"BD" => {
if let Some((name, _)) = self.def.take().and_then(GradientDef::finish) {
self.gradients.push(name);
}
}
b"Bs" => {
if let Some(d) = self.def.as_mut() {
d.stop(&vals, &mut self.spots);
}
}
b"x" | b"X" | b"Xx" | b"XX" | b"Xk" | b"XK" => {
if let Some((_, Some(n))) = std::str::from_utf8(w).ok().and_then(|op| color_op(op, &vals)) {
self.spots.push(n);
}
}
b"@" | b"&" if outer => {
for v in &vals {
if let V::Str(s) = v {
let mut inner = ColorNames::default();
let mut lex = Lexer::new(s);
while let Some(t) = lex.next_token() {
inner.take(t.tok, false);
}
self.names.extend(inner.names);
}
}
}
_ => {}
}
self.names.extend(self.spots.drain(..).map(|n| n.name));
}
}
/// A kind of global object.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Global {
Gradient,
Pattern,
}
/// The names the gradients and patterns get in the document, by their kind and names in the file.
/// The name shown for a name in the file is the part before its first newline (AI7 spec §4):
/// `(Sky\n1)` is shown as "Sky". Gradients and patterns share their swatches' names. A name with a
/// newline is shown as the part before it unless that name is reserved (a custom color's, or a
/// gradient's or pattern's name without a newline) or an object defined earlier (of either kind)
/// got it; then it is the first free "Sky 2", "Sky 3"… A name shown as nothing (`(\n3)`) is shown
/// as "Gradient" or "Pattern", numbered the same way. A name without a newline is kept. An object
/// defined again under the same name in the file keeps the name it got.
#[derive(Debug, Default)]
pub(super) struct ShownNames {
gradients: HashMap<String, String>,
patterns: HashMap<String, String>,
taken: HashSet<String>,
/// The number to try first for each shown name already taken.
next: HashMap<String, usize>,
}
impl ShownNames {
fn by_file(&self, kind: Global) -> &HashMap<String, String> {
match kind {
Global::Gradient => &self.gradients,
Global::Pattern => &self.patterns,
}
}
/// The name the object of `kind` defined as `name` in the file got ([`Self::define`]), or
/// `name` for one not defined.
pub fn get<'n>(&'n self, kind: Global, name: &'n str) -> &'n str {
self.by_file(kind).get(name).map_or(name, String::as_str)
}
/// Keep `name` from the objects defined after.
pub fn reserve(&mut self, name: &str) {
self.taken.insert(name.to_string());
}
/// The name the object of `kind` defined as `name` in the file gets.
pub fn define(&mut self, kind: Global, name: &str) -> String {
if let Some(shown) = self.by_file(kind).get(name) {
return shown.clone();
}
let shown = match name.split_once('\n') {
None => name.to_string(),
Some((base, _)) => {
let base = match (base.is_empty(), kind) {
(false, _) => base,
(true, Global::Gradient) => "Gradient",
(true, Global::Pattern) => "Pattern",
};
if self.taken.contains(base) {
// The first free number from the one after the last number this base got. Of
// the numbers `from..=tries`, at least one is free.
let from = self.next.get(base).copied().unwrap_or(2);
let tries = from.saturating_add(self.taken.len());
let i = (from..tries).find(|i| !self.taken.contains(&format!("{base} {i}"))).unwrap_or(tries);
self.next.insert(base.to_string(), i.saturating_add(1));
format!("{base} {i}")
} else {
base.to_string()
}
}
};
self.taken.insert(shown.clone());
let by_file = match kind {
Global::Gradient => &mut self.gradients,
Global::Pattern => &mut self.patterns,
};
by_file.insert(name.to_string(), shown.clone());
shown
}
}
/// A gradient instance on an object, between `Bb` and `BB`.
#[derive(Clone, Debug, Default)]
pub(super) struct Instance {
@@ -258,8 +423,9 @@ impl Instance {
self.xm.is_some() || self.bm.is_some()
}
/// The paint, through `to_doc` (art space → the document), when the gradient is defined.
pub fn paint(&self, defs: &HashMap<String, Gradient>, to_doc: Affine) -> Option<Paint> {
/// The paint, through `to_doc` (art space → the document), when the gradient is defined, linked
/// to the gradient's swatch by the name `shown` gave it.
pub fn paint(&self, defs: &HashMap<String, Gradient>, shown: &ShownNames, to_doc: Affine) -> Option<Paint> {
let name = self.name.as_ref()?;
let gradient = defs.get(name)?.clone();
let radial = gradient.kind == GradientKind::Radial;
@@ -310,7 +476,8 @@ impl Instance {
let focal = (self.hilight.hypot() > 1e-9).then_some(focal).filter(|p| p.is_finite());
let geom = GradientGeom { start, end, aspect, focal: if radial { focal } else { None } };
let angle = -(end - start).atan2().to_degrees();
Some(Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), angle, swatch: Some(name.clone()), ..GradientPaint::new(gradient) })))
let swatch = Some(shown.get(Global::Gradient, name).to_string());
Some(Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), angle, swatch, ..GradientPaint::new(gradient) })))
}
}
@@ -406,22 +573,59 @@ mod tests {
bg.extend(nums(&[100.0, 100.0, 0.0, 50.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0]));
i.bg(&bg);
i.bm(&nums(&[50.0, 0.0, 0.0, -50.0, 100.0, 100.0]));
let Some(Paint::Gradient(gp)) = i.paint(&defs, Affine::IDENTITY) else { panic!() };
let shown = ShownNames::default();
let Some(Paint::Gradient(gp)) = i.paint(&defs, &shown, Affine::IDENTITY) else { panic!() };
assert_eq!(gp.swatch.as_deref(), Some("G"));
let geom = gp.geom.unwrap();
assert_eq!(geom.start, Point::new(100.0, 100.0));
assert_eq!(geom.end, Point::new(150.0, 100.0));
assert!((geom.aspect - 1.0).abs() < 1e-9);
assert!(i.paint(&HashMap::new(), Affine::IDENTITY).is_none());
assert!(i.paint(&HashMap::new(), &shown, Affine::IDENTITY).is_none());
// Newer files give the matrix with `Xm`; the `Bm`s after it are bands of a cached ramp.
let mut i = Instance::begin(&[]);
i.bg(&bg);
i.xm(&nums(&[40.0, 0.0, 0.0, -40.0, 10.0, 10.0]));
i.bm(&nums(&[5.0, 0.0, 0.0, -40.0, 30.0, 10.0]));
let Some(Paint::Gradient(gp)) = i.paint(&defs, Affine::IDENTITY) else { panic!() };
let Some(Paint::Gradient(gp)) = i.paint(&defs, &shown, Affine::IDENTITY) else { panic!() };
let geom = gp.geom.unwrap();
assert_eq!((geom.start, geom.end), (Point::new(10.0, 10.0), Point::new(50.0, 10.0)));
}
/// A name is shown up to its first newline, numbered when a reserved name or an earlier object
/// of either kind has it; a name defined again keeps the name it got, and a blank one gets its
/// kind's stand-in. A name without a newline is kept.
#[test]
fn global_names_are_shown_up_to_their_newline() {
let mut shown = ShownNames::default();
// A color's name, and the names without a newline the file defines.
for name in ["Ink", "Sky", "Sky 2", "Sea"] {
shown.reserve(name);
}
let got: Vec<String> = [
(Global::Gradient, "Sky\n1"),
(Global::Gradient, "Sky\n2"),
(Global::Gradient, "Sky"),
(Global::Gradient, "Sky\n1"),
(Global::Pattern, "Sky\n1"),
(Global::Gradient, "Sea\nA\nB"),
(Global::Gradient, "\n3"),
(Global::Pattern, "\n4"),
(Global::Gradient, "Sky 2"),
(Global::Pattern, "Ink\n1"),
(Global::Gradient, "Ink"),
(Global::Pattern, "Sea"),
(Global::Pattern, "Tide\n1"),
(Global::Pattern, ""),
]
.iter()
.map(|(kind, n)| shown.define(*kind, n))
.collect();
assert_eq!(got, ["Sky 3", "Sky 4", "Sky", "Sky 3", "Sky 5", "Sea 2", "Gradient", "Pattern", "Sky 2", "Ink 2", "Ink", "Sea", "Tide", ""]);
assert_eq!(shown.get(Global::Gradient, "Sky\n2"), "Sky 4");
assert_eq!(shown.get(Global::Pattern, "Sky\n1"), "Sky 5");
assert_eq!(shown.get(Global::Pattern, "Sky\n2"), "Sky\n2", "not a pattern's name");
}
#[test]
fn gradient_stops_beyond_the_cap_are_ignored() {
let mut d = GradientDef::begin(&[V::Str(b"H".to_vec()), V::Num(0.0)]).unwrap();
@@ -434,6 +638,24 @@ mod tests {
assert_eq!(g.stops.len(), MAX_STOPS);
}
/// A hard edge: every stop at one ramp point. A linear gradient's are listed from the last, a
/// radial one's from the first.
#[test]
fn stops_at_one_ramp_point_keep_their_sides() {
for (kind, listed) in [(0.0, [0.75, 0.25]), (1.0, [0.25, 0.75])] {
let mut d = GradientDef::begin(&[V::Str(b"E".to_vec()), V::Num(kind), V::Num(2.0)]).unwrap();
for (gray, mid) in listed.into_iter().zip([40.0, 70.0]) {
d.stop(&nums(&[gray, 0.0, 1.0, 6.0, mid, 30.0]), &mut vec![]);
}
let (_, g) = d.finish().unwrap();
let lightness: Vec<f32> = g.stops.iter().map(|s| (s.color.to_rgb()[0] * 100.0).round() / 100.0).collect();
let first_mid = if kind == 0.0 { 0.7 } else { 0.4 };
assert_eq!(lightness, vec![0.25, 0.75], "kind {kind}");
assert!((g.stops[0].midpoint - first_mid).abs() < 1e-6, "kind {kind}: {:?}", g.stops);
assert!(g.stops.iter().all(|s| (s.offset - 0.3).abs() < 1e-6));
}
}
/// A linear gradient of three stops as newer files place it: `Bg` with numbers that aren't in
/// art space, `Xm` for the whole ramp and a `Bm` for each pair of stops.
#[test]
@@ -454,7 +676,7 @@ mod tests {
// From the stop at 20 to the one at 60, then on to the one at 100.
i.bm(&nums(&[0.0, -80.0, -30.0, 0.0, 10.0, 260.0]));
i.bm(&nums(&[0.0, -80.0, -30.0, 0.0, 10.0, 180.0]));
let Some(Paint::Gradient(gp)) = i.paint(&defs, Affine::IDENTITY) else { panic!() };
let Some(Paint::Gradient(gp)) = i.paint(&defs, &ShownNames::default(), Affine::IDENTITY) else { panic!() };
gp.geom.unwrap()
};
for xm in [true, false] {
+8
View File
@@ -63,6 +63,14 @@ impl Palette {
pub fn is_empty(&self) -> bool {
self.swatches.is_empty() && self.groups.iter().all(|(_, s)| s.is_empty())
}
/// The names the palette gives its color groups and swatches, except the name a swatch takes
/// from its gradient or pattern.
pub fn own_names(&self) -> impl Iterator<Item = &str> {
let named = |e: &Entry| !matches!(&e.cell, Cell::Gradient(n) | Cell::Pattern(n) if *n == e.name);
let swatches = self.swatches.iter().chain(self.groups.iter().flat_map(|(_, s)| s)).filter(move |e| named(e));
self.groups.iter().map(|(name, _)| name.as_str()).chain(swatches.map(|e| e.name.as_str()))
}
}
/// The palette of `data`: what follows `%AI5_BeginPalette`, up to its end.
+195 -10
View File
@@ -35,6 +35,11 @@
//! and the samples after `XI`. 8-bit CMYK samples keep their ink amounts in a CMYK TIFF, and
//! an alpha channel that hides part of such an image becomes its opacity mask; other samples
//! become an RGBA PNG.
//! - Linked images in the version 7 form (§8.2, §8.3): `(path) modified XG`, then `XF` with the
//! operands `XI` takes and no samples. Each is a linked image of that file showing a placeholder
//! over the image's place until its file is found. An `XF` without a file name before it, or
//! with operands `XI` couldn't read, is left out with a warning. An `XI` after `XG` (newer files
//! write `() 1 XG` before their embedded images) stays an embedded image.
//! - Placed (linked) files, as written in files users sent: `%AI5_BeginPlace`, `[matrix] llx lly urx
//! ury … (path)` and the operator `` ` ``, the file's preview between `%AI26_BeginPlacedObjectPreview`
//! and its end (`w h rowBytes 32 n `, then rows of premultiplied ARGB, the top one first), `~`. The
@@ -52,7 +57,9 @@
//! lines and `1 (style) XW`: the drawn look is kept, named after the object.
//! - Patterns: `%AI3_BeginPattern: (name)`, `(name) llx lly urx ury` (the tile, in the pattern's
//! space, y up), the tile's art (on `%_` lines in newer files), `E`, `%AI3_EndPattern`; each is
//! read by a reader of its own and becomes a pattern swatch. In the version 7 form (§3.4) a list
//! read by a reader of its own and becomes a pattern swatch. An unpainted path whose dictionary
//! marks it as the tile's box (`AIPattern_Editor_Backing_Tile_Rect`) is left out of the art. In
//! the version 7 form (§3.4) a list
//! of layers follows the tile, `[ (colors) @ (tile) & … ] E`, each layer's tile read from its
//! string with the colors' state (`_ &`: the tile's box filled). A fill or stroke with one:
//! `(name) x y scaleX scaleY angle reflect axis shear shearAxis [matrix] p` (`P`), the matrix
@@ -80,8 +87,18 @@
//! style's appearance and transparency is linked to it. A `1` naming a style the list doesn't
//! have is the object's own appearance, not a link.
//!
//! Sections the reader doesn't need (symbols, styles, filters) are skipped;
//! type, symbols, fills with a pattern it can't read, placed files without a preview and operators
//! - Symbols: `%AI14_BeginSymbol` (or `%AI10_`), `(name)`, `0 A 0 Xw 0 Ae`, the art (in the
//! symbol's space, y down), a dictionary whose `AI13PatternRegistrationType` is the registration
//! point (1 to 9, from the top left, row by row), `%AI10_EndSymbol`; each is read by a reader of
//! its own into the document's symbols. `%AI24_BeginSymbolList` (or `%AI10_`) lists their names
//! in the Symbols panel's order. An instance: `/SymbolInstance : (name) /SymbolRef , a b c d tx
//! ty /RTransformMatrix ;`, the matrix taking the symbol's art to art space; in a symbol's art,
//! it takes it to art space about the canvas point of art space's origin, as a pattern's
//! gradients are. Its hide and lock come before it (`Xw`, `A`) and its transparency (`Xy`) after
//! it.
//!
//! Sections the reader doesn't need (styles, filters) are skipped; type, instances of symbols it
//! can't read, fills with a pattern it can't read, placed files without a preview and operators
//! it doesn't know are errors. So is data that ends inside a layer, a group or a compound path.
use std::collections::{BTreeSet, HashMap, HashSet};
@@ -103,7 +120,7 @@ use super::super::ate::CANVAS_CENTRE;
use super::super::graphics::HAIRLINE;
use super::lex::{Lexer, Tok};
use super::obj::{self, Obj, V};
use super::paint::{self, GradientDef, Instance, Named};
use super::paint::{self, Global, GradientDef, Instance, Named, ShownNames};
use crate::ps;
mod art;
@@ -117,12 +134,12 @@ mod types;
pub(crate) use art::join_and;
use art::preview_png;
pub use document::{BindingRef, Brushes, PaletteSwatches, VariableRead, artboards, bindings_note, brushes, palette, variables};
pub use document::{BindingRef, Brushes, PaletteSwatches, VariableRead, artboards, bindings_note, brushes, graphic_styles, palette, variables};
pub(crate) use document::{slot_frame, slot_of};
pub use types::IMAGE_TOO_LARGE;
use types::{BLEND_BUDGET, FLIP, Frame, GState, Graph, Kind, PatternHead, PendingEnvelope, Place, Raster};
use types::{BLEND_BUDGET, FLIP, Frame, GState, Graph, Kind, PatternHead, PendingEnvelope, Place, Raster, SymbolHead};
#[cfg(test)]
pub use types::{GRAPH_PLAIN, GRAPH_UNENDED, NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, VERSIONED_UNENDED};
pub use types::{GRAPH_PLAIN, GRAPH_UNENDED, LINKED_PLACEHOLDERS, NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, VERSIONED_UNENDED};
pub(super) use types::{blend_mode, blend_name};
#[path = "legacy_text.rs"]
@@ -153,6 +170,10 @@ pub struct Structure {
/// Where the drawn looks lay that objects read with their art style took the place of (the
/// document's coordinates): the page draws Illustrator's rendering of those styles there.
pub restyled: Vec<Rect>,
/// Where linked images whose pixels the data doesn't keep (`XF`) show a placeholder (the
/// document's coordinates). A PostScript page doesn't draw them there; a PDF part draws the
/// image's pixels.
pub placeholders: Vec<Rect>,
/// Placed files whose pixels the file puts at another point too: their image's id and the
/// move, in its pixels, that places them there (the corner of the box they are written with,
/// in place of the canvas point of art space's origin).
@@ -199,7 +220,7 @@ pub(super) fn remember_xml_id(xml_ids: &mut HashMap<String, Option<NodeId>>, byt
/// when `large_canvas` is set: an EPS's page is drawn at the full size, but a `.ai`'s PDF part may
/// keep the reduced one, which the PDF import reads as it is (#2031).
pub fn read(data: &[u8], large_canvas: bool) -> Result<Structure, String> {
let mut r = Reader::new(data);
let mut r = Reader::with_names(data);
r.large_canvas = large_canvas.then_some(1.0);
r.run()?;
r.finish()
@@ -209,13 +230,129 @@ pub fn read(data: &[u8], large_canvas: bool) -> Result<Structure, String> {
/// data): the program's header gives the author and the custom colors the editing data's header
/// doesn't.
pub fn read_beside(data: &[u8], large_canvas: bool, ps: &[u8]) -> Result<Structure, String> {
let mut r = Reader::new(data);
let header = Reader::header_of(ps);
let mut r = Reader::with_names(data);
r.large_canvas = large_canvas.then_some(1.0);
// The program's custom colors have swatches of their names, which no gradient or pattern takes.
for n in &header.custom_colors {
r.global_names.reserve(&n.name);
}
r.run()?;
r.program_header(ps);
r.program_header(header);
r.finish()
}
/// The names the gradients and patterns of the editing data `data` get in the document
/// ([`ShownNames`]), with the names its other swatches can have reserved first: Registration, the
/// default swatches of both color modes when the palette the reader keeps is missing or empty, the
/// names that palette gives, the named colors, and the names without a newline of the gradients
/// and patterns. Names come only from what the reader reads: not from the alternates of versioned
/// content, the prolog, resources, sections it skips (such as symbols and the text document) or
/// what follows the trailer. The palette the reader keeps is the last one outside those and the
/// sections it reads on their own.
fn swatch_names(data: &[u8]) -> ShownNames {
/// The sections the reader reads on their own whose definitions and colors it keeps.
const READ_APART: &[&str] = &["BeginPattern", "BeginBrushPattern", "BeginPluginObject", "BeginArtStyles", "BeginArtStyleList"];
/// Whether the marker `m` ends what began with `begin` and ends with `end`, `depth` of its kind
/// open inside it.
fn closes(begin: &str, end: &str, depth: &mut usize, m: &str) -> bool {
if !begin.is_empty() && m == begin {
*depth += 1;
} else if m == end {
match depth.checked_sub(1) {
Some(d) => *depth = d,
None => return true,
}
}
false
}
let mut names = ShownNames::default();
names.reserve(vectorcraft_color::swatch::REGISTRATION);
let mut colors = paint::ColorNames::default();
let mut lex = Lexer::new(data);
// What the reader skips wherever it is (the marker of one of its kind nested in it, its end
// marker, how many are open inside it, and where reading goes on when it doesn't end), the
// top-level section being passed over (the first three, and whether the reader reads it on its
// own), and where the palette being found starts.
let mut skip: Option<(&str, &str, usize, Option<usize>)> = None;
let mut section: Option<(&str, &str, usize, bool)> = None;
let (mut palette_at, mut palette) = (None, None);
// A pattern's name is the first string of its definition.
let mut head = false;
loop {
let before = lex.offset();
let Some(t) = lex.next_token() else {
// Versioned content that doesn't end is read whole, as the reader reads it.
match skip.take() {
Some((.., Some(at))) => {
lex.seek(at);
continue;
}
_ => break,
}
};
match &t.tok {
Tok::Comment(c) => {
let line = String::from_utf8_lossy(c);
let m = marker(&line);
if let Some((begin, end, depth, _)) = skip.as_mut() {
if closes(begin, end, depth, m) {
skip = None;
}
} else if let Some(at) = palette_at {
if m == "EndPalette" {
palette = Some(lex.slice(at, before));
palette_at = None;
}
} else if m.starts_with("Alternate_Content") && section.is_none_or(|s| s.3) {
skip = Some(("Begin_Content_if_version_gt", "End_Versioned_Content", 0, Some(lex.offset())));
} else if m == "%BeginProlog" {
skip = Some(("", "%EndProlog", 0, None));
} else if m == "%BeginResource" {
skip = Some(("", "%EndResource", 0, None));
} else if let Some((begin, end, depth, _)) = section.as_mut() {
if closes(begin, end, depth, m) {
section = None;
}
} else if m == "BeginPalette" {
palette_at = Some(lex.offset());
} else if let Some((begin, end)) = types::SKIPPED.iter().find(|(b, _)| *b == m) {
section = Some((begin, end, 0, READ_APART.contains(begin)));
head = m == "BeginPattern";
} else if matches!(m, "%PageTrailer" | "%Trailer") {
break;
}
continue;
}
// A palette's names are those of the palette kept, as the palette reads them.
_ if skip.is_some() || palette_at.is_some() || section.is_some_and(|s| !s.3) => continue,
Tok::Str(s) | Tok::Hex(s) if std::mem::take(&mut head) => {
let text = obj::text(s);
if !text.contains('\n') {
names.reserve(&text);
}
}
_ => {}
}
colors.token(t.tok);
}
colors.gradients.iter().filter(|n| !n.contains('\n')).for_each(|n| names.reserve(n));
let palette = palette.map(super::palette::palette).unwrap_or_default();
if palette.is_empty() {
for mode in [ColorMode::Rgb, ColorMode::Cmyk] {
let (swatches, groups) = vectorcraft_color::default_swatches(mode.model());
for g in &groups {
names.reserve(&g.name);
g.swatches.iter().for_each(|s| names.reserve(&s.name));
}
swatches.iter().for_each(|s| names.reserve(&s.name));
}
}
palette.own_names().for_each(|n| names.reserve(n));
colors.names.iter().for_each(|n| names.reserve(n));
names
}
struct Reader<'a> {
lex: Lexer<'a>,
stack: Vec<V>,
@@ -234,6 +371,8 @@ struct Reader<'a> {
to_doc: Option<Affine>,
cropmarks: Option<Rect>,
artboards: Vec<document::AiArtboard>,
/// The index in `artboards` of the active artboard (`CropAreaActive`).
active_board: Option<usize>,
/// The user the header's `%%For` names.
author: Option<String>,
/// The custom colors the header's `%%CMYKCustomColor` and `%%RGBCustomColor` define.
@@ -247,6 +386,8 @@ struct Reader<'a> {
/// The Objects on Path records of the `/Document` dictionary and the ids of the objects.
on_path: on_path::OnPath,
gradients: HashMap<String, Gradient>,
/// The names the gradients and patterns get in the document, by their names in the file.
global_names: ShownNames,
gradient_def: Option<GradientDef>,
instance: Option<Instance>,
pending_fill: Option<Paint>,
@@ -257,10 +398,15 @@ struct Reader<'a> {
/// a global process colour, so these make swatches only for names no colour operator defines.
stop_spots: Vec<Named>,
raster: Option<Raster>,
/// The file `XG` names for the image after it (`XF`), until an image is read.
image_link: Option<String>,
/// The placed file being read (`%AI5_BeginPlace` … `~`).
place: Option<Place>,
/// The last object read is the last child of the innermost frame, and nothing started since.
after_object: bool,
/// The last object read is an image, and only the operators that end its raster (`XH`, `Xr`,
/// `N`) came since: its name and opacity mask still follow.
image_tail: bool,
nodes: usize,
/// What layers that show have that this reader doesn't read (errors).
unsupported: BTreeSet<String>,
@@ -269,7 +415,24 @@ struct Reader<'a> {
/// What layers that don't show have that this reader doesn't read.
hidden_unread: BTreeSet<String>,
unread: Vec<(NodeId, Vec<String>)>,
/// The art boxes (symbol space) of symbols whose definition can be measured but not read
/// whole, by their name in the file: their instances come in as the page draws them.
symbol_bounds: HashMap<String, Rect>,
/// The symbols read, by their name in the file → their name in the document.
symbol_names: HashMap<String, String>,
/// The names the symbols read have in the document, and for each name read more than once,
/// the number its next copy is tried with.
symbol_taken: HashSet<String>,
symbol_suffix: HashMap<String, usize>,
/// The art boxes (symbol space) of symbols read, by their name in the file, once measured for
/// an instance that comes in as the page draws it.
symbol_art_bounds: HashMap<String, Option<Rect>>,
/// The symbol list's names, in the Symbols panel's order (`%AI24_BeginSymbolList`).
symbol_list: Option<Vec<String>>,
/// The symbols read were checked for instances of symbols the file doesn't have.
symbols_checked: bool,
/// This reader reads a symbol's definition (see [`Reader::define_symbol`]).
symbol: Option<SymbolHead>,
/// Depth shared by pattern and symbol readers.
subreader_depth: usize,
pending_unread_fill: bool,
@@ -341,6 +504,8 @@ struct Reader<'a> {
palette: super::palette::Palette,
/// See [`Structure::restyled`].
restyled: Vec<Rect>,
/// See [`Structure::placeholders`].
placeholders: Vec<Rect>,
/// See [`Structure::placed_elsewhere`].
placed_elsewhere: Vec<(NodeId, Affine)>,
unread_elsewhere: Vec<(NodeId, Rect)>,
@@ -410,6 +575,14 @@ pub(crate) fn is_look_slot(name: Option<&str>) -> bool {
}
impl<'a> Reader<'a> {
/// A reader of the editing data `data` as a whole, with the names its gradients and patterns
/// get in the document found first ([`swatch_names`]).
fn with_names(data: &'a [u8]) -> Self {
let mut r = Self::new(data);
r.global_names = swatch_names(data);
r
}
fn new(data: &'a [u8]) -> Self {
let mut doc = Document::new(1.0, 1.0);
doc.layers.clear();
@@ -427,6 +600,7 @@ impl<'a> Reader<'a> {
to_doc: None,
cropmarks: None,
artboards: Vec::new(),
active_board: None,
author: None,
custom_colors: Vec::new(),
custom_more: None,
@@ -434,6 +608,7 @@ impl<'a> Reader<'a> {
variables: VariableRead::default(),
on_path: on_path::OnPath::default(),
gradients: HashMap::new(),
global_names: ShownNames::default(),
gradient_def: None,
instance: None,
pending_fill: None,
@@ -441,15 +616,24 @@ impl<'a> Reader<'a> {
spots: Vec::new(),
stop_spots: Vec::new(),
raster: None,
image_link: None,
place: None,
foreign_data: None,
after_object: false,
image_tail: false,
nodes: 0,
unsupported: BTreeSet::new(),
unknown: BTreeSet::new(),
hidden_unread: BTreeSet::new(),
unread: Vec::new(),
symbol_bounds: HashMap::new(),
symbol_names: HashMap::new(),
symbol_taken: HashSet::new(),
symbol_suffix: HashMap::new(),
symbol_art_bounds: HashMap::new(),
symbol_list: None,
symbols_checked: false,
symbol: None,
subreader_depth: 0,
pending_unread_fill: false,
pending_unread_stroke: false,
@@ -485,6 +669,7 @@ impl<'a> Reader<'a> {
style_links: vec![],
palette: super::palette::Palette::default(),
restyled: vec![],
placeholders: vec![],
placed_elsewhere: vec![],
unread_elsewhere: vec![],
mesh: None,
+217 -27
View File
@@ -1,13 +1,14 @@
use super::containers::close;
use super::document::TEXT_SLOT;
use super::types::{
FLIP, Frame, IMAGE_TOO_LARGE, Kind, LINKED_PREVIEWS, MAX_PIXELS, MAX_PLACED_ELSEWHERE, MAX_POINTS, MAX_SIDE, NON_NATIVE_ART,
FLIP, Frame, IMAGE_TOO_LARGE, Kind, LINKED_PLACEHOLDERS, LINKED_PREVIEWS, MAX_PIXELS, MAX_PLACED_ELSEWHERE, MAX_POINTS, MAX_SIDE, NON_NATIVE_ART,
NON_NATIVE_ART_UNREAD, Place,
};
use super::{
Affine, AnchorKind, Appearance, AppearanceItem, Arc, BezPath, CANVAS_CENTRE, FillLayer, ImageBlob, ImageObject, Inks, Instance, LinkInfo, Node,
NodeId, NodeKind, Obj, OpacityMask, Paint, PathData, PathEl, Point, Reader, Rect, StrokeLayer, V, ps,
};
use vectorcraft_doc::links::missing_placeholder;
impl<'a> Reader<'a> {
/// A text object (`/AI11Text`): an empty group standing for it, named after its story.
@@ -15,6 +16,7 @@ impl<'a> Reader<'a> {
if self.pattern.is_some() {
self.unreadable("type in a pattern", false);
}
self.left_out_of_symbol();
// `1 /FreeUndo`: type in a drawn look. Its story is one of another text document
// (`/AI11UndoFreeTextDocument`), which counts its stories on its own, so its slot has none.
// In the look of a text object that has an appearance, the object itself follows the look,
@@ -45,6 +47,11 @@ impl<'a> Reader<'a> {
/// group. Without data, or with a PDF that can't be read, nothing is drawn.
pub(super) fn foreign_art(&mut self, o: &Obj) -> Result<(), String> {
let Some(text) = self.foreign_data.take() else { return Ok(()) };
// Where a symbol's art puts it isn't known.
if self.symbol.is_some() {
self.left_out_of_symbol();
return Ok(());
}
// One `%` starts each line; the rest, `_` included, is data.
let mut encoded = String::with_capacity(text.len());
for line in text.split(|b| matches!(b, b'\r' | b'\n')) {
@@ -164,6 +171,9 @@ impl<'a> Reader<'a> {
self.path_kinds.clear();
self.points = 0;
self.clip_next = false;
if let Some(head) = self.symbol.as_mut() {
(head.missing_fill, head.missing_stroke) = (false, false);
}
}
/// Paint the current path (`op`), as a guide when `guide`.
@@ -176,6 +186,7 @@ impl<'a> Reader<'a> {
self.set_instance(&i);
}
let (fill_paint, stroke_paint) = (self.pending_fill.take(), self.pending_stroke.take());
let missing = self.symbol.as_mut().map_or((false, false), |h| (std::mem::take(&mut h.missing_fill), std::mem::take(&mut h.missing_stroke)));
if bp.elements().is_empty() {
return Ok(());
}
@@ -195,6 +206,10 @@ impl<'a> Reader<'a> {
"b" => (true, true),
_ => (false, false),
};
// A symbol's art painted with a gradient the file doesn't define is left out.
if (missing.0 && fill) || (missing.1 && stroke) {
self.left_out_of_symbol();
}
// A gradient instance's paint replaces the missing pattern.
let unread = (fill && self.pending_unread_fill && fill_paint.is_none()) || (stroke && self.pending_unread_stroke && stroke_paint.is_none());
let mut items = Vec::new();
@@ -352,15 +367,20 @@ impl<'a> Reader<'a> {
pub(super) fn set_instance(&mut self, i: &Instance) {
let mut to_doc = self.space();
// In a pattern's definition a gradient's `Xm` and `Bm` are written y down about the canvas point of art space's
// origin, as the file's PDF part draws them.
if self.pattern.is_some()
// origin, as the file's PDF part draws them; in a symbol's, as the instances in its art are.
if (self.pattern.is_some() || self.symbol.is_some())
&& i.has_matrix()
&& let Some(t) = self.template
{
let (cx, cy) = ((t[0] + t[2]) / 2.0, (t[1] + t[3]) / 2.0);
to_doc *= Affine::new([1.0, 0.0, 0.0, -1.0, CANVAS_CENTRE - cx, CANVAS_CENTRE + cy]);
}
match i.paint(&self.gradients, to_doc) {
let paint = i.paint(&self.gradients, &self.global_names, to_doc);
if let Some(head) = self.symbol.as_mut() {
let missing = if i.stroke { &mut head.missing_stroke } else { &mut head.missing_fill };
*missing = paint.is_none();
}
match paint {
Some(p) if i.stroke => self.pending_stroke = Some(p),
Some(p) => self.pending_fill = Some(p),
None => {
@@ -383,25 +403,59 @@ impl<'a> Reader<'a> {
self.image_from(vals, data)
}
/// The matrix and the numbers of an image's operands (`[a b c d tx ty] llx lly urx ury w h bits
/// ImageType AlphaChannelCount reserved bin-ascii ImageMask`, as `XI` and `XF` take them); `None`
/// without a matrix or with fewer numbers than up to the encoding (bin-ascii).
fn image_operands(vals: &[V]) -> Option<(Vec<f64>, Vec<f64>)> {
let m = vals.iter().find_map(|v| if let V::Arr(a) = v { Some(Self::nums(a)) } else { None })?;
let n = Self::nums(vals);
(n.len() >= 11).then_some((m, n))
}
/// `XG` (`w`, which names the file of the image after it) or `XF` (that image), with their
/// operands `vals`. Before the art, the setup's procedures run: there they do nothing.
pub(super) fn image_link_op(&mut self, w: &str, vals: Vec<V>, hidden: bool) -> Result<(), String> {
if self.frames.is_empty() {
return Ok(());
}
if w == "XG" {
self.image_link = Self::image_link(&vals);
return Ok(());
}
self.linked_image(vals, hidden)
}
/// The file `XG`'s operands (`(path) modified`) name; `None` for operands of another shape or
/// an empty path.
fn image_link(vals: &[V]) -> Option<String> {
match vals {
[.., V::Str(path), V::Num(_)] if !path.is_empty() => Some(super::obj::text(path)),
_ => None,
}
}
/// An image of operands `vals` and samples `data`.
pub(super) fn image_from(&mut self, vals: Vec<V>, data: &[u8]) -> Result<(), String> {
// A file `XG` named before this image isn't the file of a later `XF`.
self.image_link = None;
let space = self.raster.as_ref().and_then(|r| r.space.clone()).unwrap_or_default();
let Some(m) = vals.iter().find_map(|v| if let V::Arr(a) = v { Some(Self::nums(a)) } else { None }) else {
self.warn("an image VectorCraft can't read was left out");
let Some((m, n)) = Self::image_operands(&vals) else {
self.image_left_out("an image VectorCraft can't read was left out");
return Ok(());
};
let n = Self::nums(&vals);
let [_, _, _, _, w, h, bits, kind, alpha, _, binary, ..] = n.as_slice() else {
self.warn("an image VectorCraft can't read was left out");
let [_, _, _, _, w, h, bits, kind, alpha, _, binary, rest @ ..] = n.as_slice() else {
self.image_left_out("an image VectorCraft can't read was left out");
return Ok(());
};
// ImageMask 1: the image is transparent and takes a color (version 7 specification §8.1).
let image_mask = rest.first() == Some(&1.0);
let (w, h) = (*w as u64, *h as u64);
if w.saturating_mul(h) > MAX_PIXELS {
self.warn(IMAGE_TOO_LARGE);
self.image_left_out(IMAGE_TOO_LARGE);
return Ok(());
}
if w == 0 || h == 0 || ![1.0, 8.0].contains(bits) {
self.warn("an image VectorCraft can't read was left out");
self.image_left_out("an image VectorCraft can't read was left out");
return Ok(());
}
let channels: usize = match space.as_str() {
@@ -427,7 +481,7 @@ impl<'a> Reader<'a> {
// An alpha channel follows the colour samples, one byte a pixel.
let alpha_len = if *alpha > 0.0 { (w * h) as usize } else { 0 };
let (Some(samples), opacity) = (data.get(..need), data.get(need..need.saturating_add(alpha_len))) else {
self.warn("an image whose data is cut short was left out");
self.image_left_out("an image whose data is cut short was left out");
return Ok(());
};
let opacity = opacity.filter(|_| alpha_len > 0);
@@ -437,7 +491,10 @@ impl<'a> Reader<'a> {
&& *bits == 8.0
&& let Some(blob) = Inks::new(w as u32, h as u32, samples.to_vec()).and_then(|i| ImageBlob::cmyk_tiff(&i))
{
return self.add_raster(blob, opacity, &m, (w as u32, h as u32));
return self.add_raster(blob, opacity, &m, (w as u32, h as u32), None);
}
if image_mask && channels == 1 && *bits == 1.0 {
return self.colorized_raster(samples, row, opacity, &m, (w as u32, h as u32));
}
let mut rgba = Vec::with_capacity((w * h * 4) as usize);
for y in 0..h as usize {
@@ -465,38 +522,145 @@ impl<'a> Reader<'a> {
}
}
let Some(img) = image::RgbaImage::from_raw(w as u32, h as u32, rgba) else {
self.warn("an image VectorCraft can't read was left out");
self.image_left_out("an image VectorCraft can't read was left out");
return Ok(());
};
let mut png = vec![];
if img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).is_err() {
self.warn("an image VectorCraft can't read was left out");
self.image_left_out("an image VectorCraft can't read was left out");
return Ok(());
}
self.add_raster(ImageBlob::new("image/png", png), None, &m, (w as u32, h as u32))
self.add_raster(ImageBlob::new("image/png", png), None, &m, (w as u32, h as u32), None)
}
/// A 1-bit gray image whose ImageMask is 1 (`samples`, `row` bytes a row): a grayscale image
/// colorized with the fill color. Its 0 bits, which open black with ImageMask 0, take that color,
/// and its 1 bits are transparent. A fill that isn't a solid color colorizes it black.
fn colorized_raster(&mut self, samples: &[u8], row: usize, alpha: Option<&[u8]>, m: &[f64], (w, h): (u32, u32)) -> Result<(), String> {
let mut gray = Vec::with_capacity(w as usize * h as usize);
for y in 0..h as usize {
let line = samples.get(y * row..(y + 1) * row).unwrap_or_default();
for x in 0..w as usize {
let v = line.get(x / 8).map_or(0, |b| ((b >> (7 - x % 8)) & 1) * 255);
gray.push(v);
}
}
let mut png = vec![];
let written = image::GrayImage::from_raw(w, h, gray).map(|img| img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png));
if !matches!(written, Some(Ok(()))) {
self.image_left_out("an image VectorCraft can't read was left out");
return Ok(());
}
let paint = self.mask_paint();
self.add_raster(ImageBlob::new("image/png", png), alpha, m, (w, h), Some(paint))
}
/// The color that colorizes an image mask: the fill color, or black when the fill isn't a
/// solid color.
fn mask_paint(&self) -> Paint {
match &self.gs.fill {
p @ Paint::Solid { .. } => p.clone(),
_ => Paint::solid(vectorcraft_color::Color::BLACK),
}
}
/// `XF` (§8.2): an image whose pixels are in the file the `XG` before it names becomes a linked
/// image of that file, of its `w` × `h` pixels placed as the matrix maps them, as `XI` places an
/// image. The data keeps no pixels or preview of it, so a placeholder is spread over those pixels
/// until its file is found. A 1-bit image mask is colorized as `XI` colorizes one. One without
/// that file name, or whose operands `XI` couldn't read (no
/// matrix, too few numbers, no pixels, or samples of other than 1 or 8 bits), is left out with a
/// warning. No pixels are read, so its size isn't held to the limit on `XI`'s samples.
fn linked_image(&mut self, vals: Vec<V>, hidden: bool) -> Result<(), String> {
let path = self.image_link.take();
let operands = Self::image_operands(&vals);
let (Some(path), Some((m, n))) = (path, operands) else {
self.image_left_out("an image VectorCraft can't read was left out");
return Ok(());
};
let (&[a, b, c, d, tx, ty], &[_, _, _, _, w, h, bits, ..]) = (m.as_slice(), n.as_slice()) else {
self.image_left_out("an image VectorCraft can't read was left out");
return Ok(());
};
if !(1.0..=MAX_SIDE).contains(&w) || !(1.0..=MAX_SIDE).contains(&h) || ![1.0, 8.0].contains(&bits) {
self.image_left_out("an image VectorCraft can't read was left out");
return Ok(());
}
let (w, h) = (w as u32, h as u32);
let Some(to_doc) = self.image_space() else {
self.image_left_out("an image VectorCraft can't read was left out");
return Ok(());
};
let xf = to_doc * Affine::new([a, b, c, d, tx, ty]) * FLIP;
if !xf.as_coeffs().iter().all(|v| v.is_finite()) || xf.determinant().abs() < 1e-12 {
self.image_left_out("an image VectorCraft can't read was left out");
return Ok(());
}
let Some(png) = missing_placeholder() else {
self.image_left_out("an image VectorCraft can't read was left out");
return Ok(());
};
// The placeholder is all the document has of the file: what a missing link shows.
let bytes = Arc::new(png);
let blob = ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) };
let key = linked_key(&blob, &path);
self.doc.images.entry(key.clone()).or_insert(blob);
self.warn(LINKED_PLACEHOLDERS);
// A PostScript page doesn't draw the placeholder: there its pixels are left out of the
// comparisons with the page.
if !hidden && !self.gs.hidden && self.shown() {
self.placeholders.push(xf.transform_rect_bbox(Rect::new(0.0, 0.0, f64::from(w), f64::from(h))));
}
let im = ImageObject { key, width: w, height: h, xf, link: Some(LinkInfo::new(path)), placement: Default::default(), pixels: None };
// A 1-bit image mask (ImageMask 1) keeps the color that colorizes it once its file is relinked.
let image_mask = bits == 1.0 && n.get(7) == Some(&1.0) && n.get(11) == Some(&1.0);
let colorize = image_mask.then(|| self.mask_paint());
self.add_image_colorized(im, None, colorize, hidden)
}
/// Add the image `blob` (`w` × `h` pixels), which the matrix `m` maps into art space, with
/// `alpha` (its alpha channel, one byte a pixel) as its opacity mask when it hides part of the
/// image.
fn add_raster(&mut self, blob: ImageBlob, alpha: Option<&[u8]>, m: &[f64], (w, h): (u32, u32)) -> Result<(), String> {
/// image, and `colorize` as the color that colorizes it.
fn add_raster(&mut self, blob: ImageBlob, alpha: Option<&[u8]>, m: &[f64], (w, h): (u32, u32), colorize: Option<Paint>) -> Result<(), String> {
// The matrix is an art-space matrix (y up) applied to the pixels with their rows running
// downwards, (u, -v): pixels → (u, -v) → art space. Flipping the matrix's result instead
// gives the same place only when the image isn't rotated (b = c = 0).
let [a, b, c, d, tx, ty] = m else {
self.warn("an image VectorCraft can't read was left out");
self.image_left_out("an image VectorCraft can't read was left out");
return Ok(());
};
let Some(to_doc) = self.image_space() else {
self.image_left_out("an image VectorCraft can't read was left out");
return Ok(());
};
let to_doc = self.space();
let xf = to_doc * Affine::new([*a, *b, *c, *d, *tx, *ty]) * FLIP;
if !xf.as_coeffs().iter().all(|v| v.is_finite()) || xf.determinant().abs() < 1e-12 {
self.warn("an image VectorCraft can't read was left out");
self.image_left_out("an image VectorCraft can't read was left out");
return Ok(());
}
let mask = alpha.and_then(|a| self.alpha_mask(a, w, h, xf));
let key = blob.content_key();
self.doc.images.entry(key.clone()).or_insert(blob);
self.add_image_masked(ImageObject { key, width: w, height: h, xf, link: None, placement: Default::default(), pixels: None }, mask, false)
let im = ImageObject { key, width: w, height: h, xf, link: None, placement: Default::default(), pixels: None };
self.add_image_colorized(im, mask, colorize, false)
}
/// An image that isn't read is left out, with `warning`; in a symbol's art, the symbol isn't
/// read whole, so its instances come in as the page draws them.
fn image_left_out(&mut self, warning: &str) {
if self.symbol.is_some() {
self.left_out_of_symbol();
} else {
self.warn(warning);
}
}
/// Note art of a symbol's definition that is left out: the symbol isn't kept, and its
/// instances come in as the page draws them, within the box of the art that is read.
pub(super) fn left_out_of_symbol(&mut self) {
if let Some(head) = self.symbol.as_mut() {
head.left_out = true;
}
}
/// An image's alpha channel (`w` × `h` bytes) as a grayscale image over the image (`xf`): its
@@ -524,18 +688,33 @@ impl<'a> Reader<'a> {
/// Add an image object with the state's transparency and `mask` as its opacity mask.
fn add_image_masked(&mut self, im: ImageObject, mask: Option<OpacityMask>, hidden: bool) -> Result<(), String> {
self.add_image_colorized(im, mask, None, hidden)
}
/// Add an image object with the state's transparency, `mask` as its opacity mask and
/// `colorize` as the color that colorizes it.
fn add_image_colorized(&mut self, im: ImageObject, mask: Option<OpacityMask>, colorize: Option<Paint>, hidden: bool) -> Result<(), String> {
let gs = self.gs.clone();
let mut node = self.new_node(NodeKind::Image(Box::new(im)), &gs);
node.opacity = gs.opacity;
node.blend = gs.blend;
node.extras_mut().mask = mask.map(Box::new);
self.add(node, hidden)
node.extras_mut().colorize = colorize.map(Box::new);
self.add(node, hidden)?;
self.image_tail = self.after_object;
Ok(())
}
/// `~`: the placed file read since `%AI5_BeginPlace` becomes a linked image in its place that
/// shows the preview the data keeps of it, as a linked image whose file is missing does. One
/// without a preview, a path or a matrix isn't read.
pub(super) fn end_place(&mut self, hidden: bool) -> Result<(), String> {
// Where a symbol's art puts a placed file's pixels isn't known.
if self.symbol.is_some() {
self.place = None;
self.left_out_of_symbol();
return Ok(());
}
let (m, b, path, png, w, h, folder) = match self.place.take() {
Some(Place { broken: true, .. }) => {
self.unreadable("placed files", hidden);
@@ -597,7 +776,7 @@ impl<'a> Reader<'a> {
// The preview is all the document has of the file: what a missing link shows.
let bytes = Arc::new(png);
let blob = ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) };
let key = blob.content_key();
let key = linked_key(&blob, &path);
self.doc.images.entry(key.clone()).or_insert(blob);
self.warn(LINKED_PREVIEWS);
if let Some(shift) = elsewhere
@@ -712,17 +891,28 @@ pub(super) fn preview_png(data: &[u8]) -> Option<(Vec<u8>, u32, u32)> {
}
/// A placed file's path relative to the document's folder (`/` separators): its relative `folder`
/// (`src/`, `..\art`) followed by its file `name`. `None` when the folder is empty, absolute, or
/// holds control characters, or when there is no name.
/// (`src/`, `..\art`) followed by its file `name`; the name alone when the folder is empty (the
/// document's own folder). `None` when the folder is absolute or holds control characters, or
/// when there is no name.
pub(super) fn relative_path(folder: &str, name: &str) -> Option<String> {
let folder = folder.replace('\\', "/");
let absolute = folder.starts_with('/') || folder.as_bytes().get(1) == Some(&b':') || folder.contains("://");
if folder.is_empty() || absolute || name.is_empty() || folder.chars().chain(name.chars()).any(char::is_control) {
if absolute || name.is_empty() || folder.chars().chain(name.chars()).any(char::is_control) {
return None;
}
if folder.is_empty() {
return Some(name.to_string());
}
Some(format!("{}/{name}", folder.trim_end_matches('/')))
}
/// The image key of a linked image of the file at `path` that shows `blob` (its preview or a
/// placeholder): the blob's own key and the path's. Images of other files that show the same pixels
/// have keys of their own, and reading one file's pixels in changes that file's images only.
fn linked_key(blob: &ImageBlob, path: &str) -> String {
format!("{}-{}", blob.content_key(), vectorcraft_doc::links::hash_bytes(path.as_bytes()))
}
pub(super) fn sane(r: Rect) -> bool {
[r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite() && v.abs() <= MAX_SIDE)
}
+286 -20
View File
@@ -1,7 +1,9 @@
use super::document::slot_of;
use super::ops::{paints_apart, path_rule};
use super::types::{Frame, GState, Kind, MAX_DEPTH, MAX_NODES, PendingEnvelope};
use super::{AppearanceItem, Arc, BezPath, BlendMode, FillRule, HashSet, LayerColor, Node, NodeId, NodeKind, Obj, Paint, PathEl, Rc, Reader, V, obj};
use super::{
AppearanceItem, Arc, BezPath, BlendMode, FillRule, HashMap, HashSet, LayerColor, Node, NodeId, NodeKind, Obj, Paint, PathEl, Rc, Reader, V, obj,
};
use vectorcraft_doc::TextWrap;
impl<'a> Reader<'a> {
@@ -13,6 +15,7 @@ impl<'a> Reader<'a> {
}
if matches!(kind, Kind::Layer(_)) {
self.ensure_space();
self.check_symbols();
}
let base = if matches!(kind, Kind::Obj(_)) { self.stack.len() } else { self.frames.last().map_or(0, |f| f.base) };
self.frames.push(Frame {
@@ -133,7 +136,7 @@ impl<'a> Reader<'a> {
// Some files mark every group so, the plain one holding the subpaths too (#980): one
// paint for all its paths keeps it one compound path, its holes cut.
Kind::Compound if kids.iter().any(|k| self.looks.contains(&k.id) && paints_apart(k)) => {
let (children, clip) = self.clip_first(kids, &clips);
let (children, clip) = self.clip_first(kids, &clips, true, self.nesting() + 1)?;
self.new_node(NodeKind::Group { children, clip }, &gs)
}
Kind::Compound => {
@@ -153,7 +156,7 @@ impl<'a> Reader<'a> {
}
// A group with a clipping path (`q` … `Q`, or a `W` path in a group) is a clipping group.
_ => {
let (children, clip) = self.clip_first(kids, &clips);
let (children, clip) = self.clip_first(kids, &clips, false, self.nesting() + 1)?;
self.new_node(NodeKind::Group { children, clip }, &gs)
}
};
@@ -200,9 +203,76 @@ impl<'a> Reader<'a> {
Some(n)
}
/// How deep in the document the objects the open frames hold are, less one: a dictionary adds no level, and an
/// opacity mask's art is two under the frames around the object it masks.
fn nesting(&self) -> usize {
self.frames
.iter()
.map(|f| match f.kind {
Kind::Obj(_) => 0,
Kind::Mask => 2,
_ => 1,
})
.sum()
}
/// `kids` with the clipping paths among them (indexes `clips`) first → the children and whether they clip.
///
/// Several clipping paths in a clipping group or a layer clip to their intersection, as each `W` reduces the clip
/// set by the ones before it: each clipping path after the first clips a clipping group nested in the one before
/// it, and the innermost one holds the art. As with one clipping path, every object in the group is clipped by all
/// of them, wherever it is written. A clipping path's painted fill stays at its path's level. In a compound path
/// (`union`), several clipping paths are one compound path. `at`: how deep the group or layer made of them is in the
/// document.
fn clip_first(&mut self, kids: Vec<Node>, clips: &[usize], union: bool, at: usize) -> Result<(Vec<Arc<Node>>, bool), String> {
if union || clips.len() < 2 {
return Ok(self.clip_union(kids, clips));
}
let clips: std::collections::HashSet<usize> = clips.iter().copied().collect();
let (clip, rest): (Vec<Indexed>, Vec<Indexed>) = kids.into_iter().enumerate().partition(|(i, _)| clips.contains(i));
let innermost = clip.len() - 1;
// A painted fill follows its clipping path; the art goes in the innermost level.
let level = |i: usize, n: &Node| {
if self.clip_fills.contains(&n.id) { clip.iter().rposition(|(c, _)| *c < i).unwrap_or(0) } else { innermost }
};
// Each nested clipping group adds a level over the nodes placed in it, the clipping paths included. Past the
// reader's limit, or past the document's when the nodes fit in it without those levels (the document would merge
// the deepest groups and drop their clipping paths), the editing data isn't read.
let deepest =
rest.iter().map(|(i, n)| level(*i, n) + depth(n)).chain(clip.iter().enumerate().map(|(k, (_, n))| k + depth(n))).max().unwrap_or(0);
let flat = rest.iter().map(|(_, n)| depth(n)).chain(clip.iter().map(|(_, n)| depth(n))).max().unwrap_or(0);
if at + deepest > MAX_DEPTH || (at + deepest > vectorcraft_doc::MAX_DEPTH && at + flat <= vectorcraft_doc::MAX_DEPTH) {
return Err("its clipping masks are nested too deeply".into());
}
// Each level: its clipping path, the clipping paths' own fills, which paint under the art they clip, then the
// art.
let mut fills_at: Vec<Vec<Node>> = clip.iter().map(|_| Vec::new()).collect();
let mut art_at: Vec<Vec<Node>> = clip.iter().map(|_| Vec::new()).collect();
for (i, n) in rest {
let k = level(i, &n);
let at = if self.clip_fills.contains(&n.id) { &mut fills_at } else { &mut art_at };
if let Some(v) = at.get_mut(k) {
v.push(n);
}
}
let mut children: Vec<Arc<Node>> = Vec::new();
let mut levels = clip.into_iter().map(|(_, n)| n).zip(fills_at.into_iter().zip(art_at)).rev().peekable();
while let Some((path, (fills, art))) = levels.next() {
let mut inner: Vec<Arc<Node>> = Vec::with_capacity(fills.len() + art.len() + children.len() + 1);
inner.push(Arc::new(path));
inner.extend(fills.into_iter().chain(art).map(Arc::new));
inner.append(&mut children);
if levels.peek().is_none() {
return Ok((inner, true));
}
children = vec![Arc::new(Node::new(self.doc.alloc_id(), NodeKind::Group { children: inner, clip: true }))];
}
Ok((children, false))
}
/// `kids` with the clipping paths among them (indexes `clips`) first, several as one compound
/// path → the children and whether they clip.
fn clip_first(&mut self, kids: Vec<Node>, clips: &[usize]) -> (Vec<Arc<Node>>, bool) {
fn clip_union(&mut self, kids: Vec<Node>, clips: &[usize]) -> (Vec<Arc<Node>>, bool) {
let clips: std::collections::HashSet<usize> = clips.iter().copied().collect();
let (mut clip, rest): (Vec<Indexed>, Vec<Indexed>) = kids.into_iter().enumerate().partition(|(i, _)| clips.contains(i));
let clip_node = match clip.len() {
@@ -245,7 +315,7 @@ impl<'a> Reader<'a> {
(mesh.opacity, mesh.blend, mesh.isolate, mesh.knockout) = before;
}
let Kind::Layer(a) = f.kind else { return Ok(()) };
let (children, clip) = self.clip_first(f.children, &f.clips);
let (children, clip) = self.clip_first(f.children, &f.clips, false, self.nesting() + 1)?;
let color = a.color.unwrap_or(LayerColor::Preset(0));
let mut layer = Node::new(
self.doc.alloc_id(),
@@ -307,7 +377,8 @@ impl<'a> Reader<'a> {
pub(super) fn end_mask(&mut self) -> Result<(), String> {
self.end_path_quietly();
let f = self.close("X+", |k| matches!(k, Kind::Mask))?;
let (children, clip) = self.clip_first(f.children, &f.clips);
// The mask's art is one level under the object it masks.
let (children, clip) = self.clip_first(f.children, &f.clips, false, self.nesting() + 2)?;
let art = self.new_node(NodeKind::Group { children, clip }, &f.gs);
self.gs = f.gs;
self.pending_unread_fill = f.pending_unread_fill;
@@ -480,24 +551,141 @@ impl<'a> Reader<'a> {
Ok(Some(id))
}
/// A symbol instance (`/SymbolInstance`): the symbol its `SymbolRef` names, placed by its
/// `RTransformMatrix`, hidden and locked as the state says. In a symbol's art the matrix is
/// written about the canvas point of art space's origin, and the name is the file's until the
/// symbols are checked ([`Self::check_symbols`]). An instance of a symbol that wasn't read, one
/// whose appearance differs from its symbol's, or one placed only by a `Matrix` or `Transform`,
/// comes in as the page draws it, within the symbol's box placed by the matrix when the box is
/// known.
fn symbol_instance(&mut self, o: &Obj) -> Result<(), String> {
let bounds = o.get("SymbolRef").and_then(|v| v.iter().find_map(V::text)).and_then(|name| self.symbol_bounds.get(&name).copied());
let matrix = o
.get("Matrix")
.or_else(|| o.get("Transform"))
.map(|v| v.iter().find_map(|item| if let V::Arr(a) = item { Some(Self::nums(a)) } else { None }).unwrap_or_else(|| Self::nums(v)));
let box_at_canvas = match (bounds, matrix.as_deref()) {
(Some(b), Some([a, c, d, e, x, y])) if [*a, *c, *d, *e, *x, *y].iter().all(|n| n.is_finite()) => {
Some(self.space().transform_rect_bbox(super::Affine::new([*a, *c, *d, *e, *x, *y]).transform_rect_bbox(b)))
}
let name = o.text("SymbolRef");
let affine = |n: &[f64]| match n {
[a, b, c, d, e, f] if [a, b, c, d, e, f].iter().all(|v| v.is_finite()) => Some(super::Affine::new([*a, *b, *c, *d, *e, *f])),
_ => None,
};
match box_at_canvas {
Some(b) => self.unread_box("symbols", b, self.obj_hidden).map(|_| ()),
None => {
self.unreadable("symbols", self.obj_hidden);
Ok(())
let live = affine(&o.nums("RTransformMatrix"));
let boxed_only = live.is_none();
let matrix = live.or_else(|| {
o.get("Matrix")
.or_else(|| o.get("Transform"))
.map(|v| v.iter().find_map(|item| if let V::Arr(a) = item { Some(Self::nums(a)) } else { None }).unwrap_or_else(|| Self::nums(v)))
.and_then(|n| affine(&n))
});
let hidden = self.obj_hidden;
let place = if self.symbol.is_some() {
self.canvas_origin().map(|o| super::Affine::new([1.0, 0.0, 0.0, -1.0, o.x, o.y]))
} else {
Some(self.space())
};
let (Some(name), Some(m), Some(place)) = (name, matrix, place) else {
self.unreadable("symbols", hidden);
return Ok(());
};
let xf = place * m;
let usable = xf.determinant().abs() >= 1e-12 && xf.as_coeffs().iter().all(|v| v.is_finite());
let symbol = if self.symbol.is_some() { Some(name.clone()) } else { self.symbol_names.get(&name).cloned() };
match symbol.filter(|_| usable && !boxed_only && !overrides(o)) {
Some(symbol) => {
// Its transparency is the `Xy` after it, as a group's is.
let gs = self.gs.clone();
let node = self.new_node(NodeKind::SymbolInstance { symbol, xf }, &gs);
self.add(node, hidden)
}
None => {
let bounds = self.symbol_art_bounds(&name).or_else(|| self.symbol_bounds.get(&name).copied());
match bounds.map(|b| xf.transform_rect_bbox(b)).filter(|_| usable && self.symbol.is_none()) {
Some(b) => self.unread_box("symbols", b, hidden).map(|_| ()),
None => {
self.unreadable("symbols", hidden);
Ok(())
}
}
}
}
}
/// The art box (symbol space) of the symbol read under `name` (its name in the file), measured
/// once.
fn symbol_art_bounds(&mut self, name: &str) -> Option<super::Rect> {
if let Some(b) = self.symbol_art_bounds.get(name) {
return *b;
}
let named = self.symbol_names.get(name)?;
let boxes = self.doc.symbol_boxes();
let b = self.doc.symbols.iter().find(|s| &s.name == named).and_then(|s| s.art.visual_bounds_with(&boxes));
drop(boxes);
self.symbol_art_bounds.insert(name.to_string(), b);
b
}
/// Check the symbols read for instances in their art of symbols the file doesn't have, before
/// the first layer: a symbol with one isn't kept, and so on for the symbols holding its
/// instances. The instances in the art kept then name the symbols as the document does.
pub(super) fn check_symbols(&mut self) {
if std::mem::replace(&mut self.symbols_checked, true) {
return;
}
// Each symbol's name in the file (none for one named as an earlier one), and the names its
// instances use.
let files: HashMap<&str, &str> = self.symbol_names.iter().map(|(file, named)| (named.as_str(), file.as_str())).collect();
let defs: Vec<(Option<String>, Vec<String>)> = self
.doc
.symbols
.iter()
.map(|s| {
let mut uses = vec![];
symbol_uses(&s.art, &mut uses, 0);
(files.get(s.name.as_str()).map(|f| f.to_string()), uses.into_iter().map(str::to_string).collect())
})
.collect();
// A symbol goes when one of its instances names a symbol that isn't kept: first those
// naming one the file doesn't have, then, one at a time, those using a symbol that went.
let mut kept: Vec<bool> = vec![true; defs.len()];
let mut users: HashMap<&str, Vec<usize>> = HashMap::new();
let mut going: Vec<usize> = vec![];
for (i, (_, uses)) in defs.iter().enumerate() {
for u in uses {
users.entry(u.as_str()).or_default().push(i);
}
if uses.iter().any(|u| !self.symbol_names.contains_key(u)) {
going.push(i);
}
}
while let Some(i) = going.pop() {
match kept.get_mut(i) {
Some(k) if *k => *k = false,
_ => continue,
}
if let Some(file) = defs.get(i).and_then(|(file, _)| file.as_deref()) {
going.extend(users.get(file).into_iter().flatten().copied().filter(|j| kept.get(*j).copied().unwrap_or(false)));
}
}
drop(users);
if kept.iter().any(|k| !k) {
let left: Vec<(Option<String>, String)> = defs
.iter()
.zip(&self.doc.symbols)
.zip(&kept)
.filter(|(_, k)| !**k)
.map(|(((file, _), s), _)| (file.clone(), s.name.clone()))
.collect();
let mut i = 0;
self.doc.symbols.retain(|_| {
i += 1;
kept.get(i - 1).copied().unwrap_or(false)
});
// Their art's box isn't known (the instances that made them go have none), so their
// instances have no box either.
for (file, named) in left {
self.doc.set_symbol_registration(&named, vectorcraft_doc::SymbolRegistration::CENTER);
let Some(file) = file else { continue };
self.symbol_names.remove(&file);
}
}
let names = self.symbol_names.clone();
for s in &mut self.doc.symbols {
rename_uses(Arc::make_mut(&mut s.art), &names, 0);
}
}
@@ -573,6 +761,8 @@ impl<'a> Reader<'a> {
let mut blend = Node::new(self.doc.alloc_id(), kind);
(blend.name, blend.visible, blend.locked) = (steps.name.take(), steps.visible, steps.locked);
(blend.opacity, blend.blend, blend.isolate, blend.knockout) = (steps.opacity, steps.blend, steps.isolate, steps.knockout);
// Its note, URL and data (object tags) too.
blend.extras_mut().attrs = steps.extras_mut().attrs.take();
f.children.push(blend);
}
None => {
@@ -723,6 +913,68 @@ pub(super) fn drop_commented_copies(layers: &mut [Arc<Node>], hidden: &HashSet<N
/// A node and its index among its siblings.
type Indexed = (usize, Node);
/// The names of the symbols the instances in `node`, and in the art of its opacity masks, use.
fn symbol_uses<'n>(node: &'n Node, out: &mut Vec<&'n str>, depth: usize) {
if depth > MAX_DEPTH {
return;
}
if let NodeKind::SymbolInstance { symbol, .. } = &node.kind {
out.push(symbol);
}
if let Some(m) = &node.extras().mask {
symbol_uses(&m.art, out, depth + 1);
}
for c in node.children().into_iter().flatten() {
symbol_uses(c, out, depth + 1);
}
}
/// The instances in `node`, and in the art of its opacity masks, named by `names` (a name in the
/// file → the symbol's in the document).
fn rename_uses(node: &mut Node, names: &HashMap<String, String>, depth: usize) {
if depth > MAX_DEPTH {
return;
}
if let NodeKind::SymbolInstance { symbol, .. } = &mut node.kind
&& let Some(named) = names.get(symbol.as_str())
{
symbol.clone_from(named);
}
if let Some(m) = node.extras_if_any().and_then(|e| e.mask.as_mut()) {
rename_uses(Arc::make_mut(&mut m.art), names, depth + 1);
}
for c in node.children_mut().into_iter().flatten() {
rename_uses(Arc::make_mut(c), names, depth + 1);
}
}
/// Whether a symbol instance's dictionary carries appearance of its own (a dynamic symbol's
/// edits), which isn't read.
fn overrides(o: &Obj) -> bool {
const KEYS: [&str; 5] = [
"AI19SymbolAppearanceMap",
"AI19SymbolOverriddenSymbolMap",
"AI Local Art of Symbol Instance",
"AI15 Layer In Symbol",
"AI15 Color Of Layer In Symbol",
];
// In a dictionary or array nested in it, as a keyed entry's value, in an array or among the
// values closed without a key.
fn has(o: &Obj, depth: usize) -> bool {
depth <= 8
&& (o.entries.iter().any(|(k, v)| k.as_deref().is_some_and(|k| KEYS.contains(&k)) || v.iter().any(|v| in_value(v, depth + 1)))
|| o.content.iter().any(|v| in_value(v, depth + 1)))
}
fn in_value(v: &V, depth: usize) -> bool {
match v {
V::Obj(c) => has(c, depth),
V::Arr(items) => depth <= 8 && items.iter().any(|v| in_value(v, depth + 1)),
_ => false,
}
}
has(o, 0)
}
/// Close the subpath `bp` ends with, if it has one open.
pub(super) fn close(bp: &mut BezPath) {
if bp.elements().last().is_some_and(|e| !matches!(e, PathEl::ClosePath)) {
@@ -730,6 +982,20 @@ pub(super) fn close(bp: &mut BezPath) {
}
}
/// How many levels of nodes `n` holds, itself included, its opacity masks' art included.
fn depth(n: &Node) -> usize {
let mut deepest = 0;
let mut todo = vec![(n, 1)];
while let Some((n, d)) = todo.pop() {
deepest = deepest.max(d);
todo.extend(n.children().into_iter().flatten().map(|c| (c.as_ref(), d + 1)));
if let Some(m) = n.extras().mask.as_ref() {
todo.push((m.art.as_ref(), d + 1));
}
}
deepest
}
/// The fill rule of a path or compound node.
/// `kids` with the members of each plain group among them in the group's place, at any depth.
fn ungrouped(kids: Vec<Node>) -> Vec<Node> {
+273 -27
View File
@@ -1,10 +1,13 @@
use std::collections::HashMap;
use super::super::brush;
use super::art::{four, sane, two};
use super::types::{
FLIP, GState, Kind, MAX_HEX, MAX_NOTE, MAX_PATTERNS, MAX_PLACED_FOLDER, MAX_STACK, MAX_SUBREADERS, PatternHead, Place, Raster, SKIPPED,
VERSIONED_UNENDED,
FLIP, GState, Kind, MAX_DEPTH, MAX_HEX, MAX_LISTED, MAX_NODES, MAX_NOTE, MAX_PATTERNS, MAX_PLACED_FOLDER, MAX_STACK, MAX_SUBREADERS, MAX_SYMBOLS,
PatternHead, Place, Raster, SKIPPED, SymbolHead, VERSIONED_UNENDED,
};
use super::{Arc, Lexer, Node, PatternDef, Reader, Rect, Tok, V, marker, obj};
use super::{Arc, Global, Lexer, Node, NodeKind, PatternDef, Reader, Rect, Tok, V, marker, obj};
use vectorcraft_doc::{NodeId, Symbol, SymbolRegistration};
impl<'a> Reader<'a> {
pub(super) fn push(&mut self, v: V) -> Result<(), String> {
@@ -85,7 +88,7 @@ impl<'a> Reader<'a> {
}
let m = marker(line);
// A pattern's definition. One inside another's isn't read, and the outer tile is then incomplete.
if m == "BeginPattern" {
if m == "BeginPattern" && self.symbol.is_none() {
let section = self.section("EndPattern")?;
if self.pattern.is_some() {
self.unsupported.insert("patterns inside patterns".into());
@@ -96,7 +99,12 @@ impl<'a> Reader<'a> {
}
if m == "BeginSymbol" {
let section = self.section("EndSymbol")?;
self.symbol_bounds(section);
self.define_symbol(section);
return Ok(());
}
if m == "BeginSymbolList" {
let section = self.section("EndSymbolList")?;
self.symbol_list(section);
return Ok(());
}
// Brushes and their art (those in a pattern's or a brush's art aren't read).
@@ -127,6 +135,9 @@ impl<'a> Reader<'a> {
}
if m == "BeginEncoding" {
self.type_state.encoding_comment(line);
let section = self.section("EndEncoding")?;
self.encoding_section(section);
return Ok(());
}
// Versioned content holds alternatives of the same art, the newest first: the first is
// read, and the next one (`%AI17_Alternate_Content`, or `…_if_version_gt:` for a version
@@ -160,8 +171,12 @@ impl<'a> Reader<'a> {
return Ok(());
}
if line.starts_with("AI5_BeginRaster") {
// An `XG` outside a raster object names no image in it.
self.image_link = None;
self.raster = Some(Raster::default());
} else if line.starts_with("AI5_EndRaster") {
// A file `XG` named in this raster object is no later one's.
self.image_link = None;
if let Some(Raster { operands: Some(vals), hex, .. }) = self.raster.take() {
return self.image_from(vals, &hex);
}
@@ -303,6 +318,8 @@ impl<'a> Reader<'a> {
_ => return,
};
if !name.trim().is_empty() && !self.custom_colors.iter().any(|n| n.name == name) {
// A gradient or pattern defined after it does not take its swatch's name.
self.global_names.reserve(&name);
self.custom_colors.push(super::Named { name, color, tint: 1.0, spot: true });
}
}
@@ -355,13 +372,15 @@ impl<'a> Reader<'a> {
let mut sub = Reader::new(section);
sub.subreader_depth = self.subreader_depth + 1;
sub.pattern = Some(PatternHead::default());
// The gradients defined so far, lent (and those it defines kept).
// The gradients defined so far and the names given, lent (and those it defines kept).
sub.gradients = std::mem::take(&mut self.gradients);
sub.global_names = std::mem::take(&mut self.global_names);
sub.nodes = self.nodes;
sub.template = self.template;
let read = sub.open(Kind::Group, false).and_then(|()| sub.run());
self.nodes = sub.nodes;
self.gradients = std::mem::take(&mut sub.gradients);
self.global_names = std::mem::take(&mut sub.global_names);
// Unread art in the definition, hidden or not, leaves the tile incomplete.
let whole = read.is_ok()
&& sub.unsupported.is_empty()
@@ -380,6 +399,7 @@ impl<'a> Reader<'a> {
sub.subreader_depth = self.subreader_depth + 1;
sub.pattern = Some(PatternHead { taken: true, name: def.name.clone(), tile: Some(def.tile) });
sub.gradients = std::mem::take(&mut self.gradients);
sub.global_names = std::mem::take(&mut self.global_names);
sub.nodes = self.nodes;
sub.template = self.template;
let mut read = sub.open(Kind::Group, false);
@@ -391,6 +411,7 @@ impl<'a> Reader<'a> {
}
self.nodes = sub.nodes;
self.gradients = std::mem::take(&mut sub.gradients);
self.global_names = std::mem::take(&mut sub.global_names);
let whole = read.is_ok()
&& sub.unsupported.is_empty()
&& sub.unknown.is_empty()
@@ -466,15 +487,17 @@ impl<'a> Reader<'a> {
return;
};
let art: Vec<Arc<Node>> = frame.children.iter().map(|n| Arc::new(self.doc.reid(n))).collect();
let mut def = PatternDef::new(&head.name, art);
// Fills and the tables look the pattern up by its name in the file; the document has it by
// the name it shows.
let mut def = PatternDef::new(&self.global_names.define(Global::Pattern, &head.name), art);
def.tile = FLIP.transform_rect_bbox(tile);
if self.pattern_tiles.insert(def.name.clone(), def.tile).is_some() {
if self.pattern_tiles.insert(head.name.clone(), def.tile).is_some() {
self.doc.patterns.retain(|p| p.name != def.name);
}
if v7 {
self.v7_patterns.insert(def.name.clone());
self.v7_patterns.insert(head.name);
} else {
self.v7_patterns.remove(&def.name);
self.v7_patterns.remove(&head.name);
}
self.doc.patterns.push(def);
for (key, blob) in sub.doc.images {
@@ -489,32 +512,165 @@ impl<'a> Reader<'a> {
}
}
/// Read a definition's box for an instance whose art must come from the page.
fn symbol_bounds(&mut self, section: &[u8]) {
if self.symbol_bounds.len() >= MAX_PATTERNS || self.subreader_depth >= MAX_SUBREADERS {
/// A symbol's definition (`section`: what follows `%AI14_BeginSymbol`), read by a reader of its
/// own into a symbol of the document, its art in the symbol's space (y down), named as the file
/// names it unless another symbol has that name. A definition inside another one or inside a
/// pattern's isn't read, nor is one after the first layer (the symbols were checked there, see
/// [`Reader::check_symbols`]). One it can't read whole (an operator it doesn't know, type, unbalanced
/// groups, art it leaves out) isn't kept: its instances come in as the page draws them, within
/// its art's box when that can be measured.
fn define_symbol(&mut self, section: &[u8]) {
if self.symbol.is_some()
|| self.pattern.is_some()
|| self.symbols_checked
|| self.subreader_depth >= MAX_SUBREADERS
|| self.doc.symbols.len() + self.symbol_bounds.len() >= MAX_SYMBOLS
{
return;
}
let mut lex = super::Lexer::new(section);
let name = match lex.next_token().map(|t| t.tok) {
Some(Tok::Str(bytes)) => super::obj::text(&bytes),
let name = match Lexer::new(section).next_token().map(|t| t.tok) {
Some(Tok::Str(bytes)) => obj::text(&bytes),
_ => return,
};
let mut sub = Reader::new(section);
sub.subreader_depth = self.subreader_depth + 1;
sub.cropmarks = self.cropmarks;
sub.symbol = Some(SymbolHead::default());
sub.template = self.template;
// The gradients, art styles and patterns defined so far and the names given, lent.
sub.gradients = std::mem::take(&mut self.gradients);
sub.global_names = std::mem::take(&mut self.global_names);
sub.styles = std::mem::take(&mut self.styles);
sub.pattern_tiles = std::mem::take(&mut self.pattern_tiles);
sub.v7_patterns.clone_from(&self.v7_patterns);
sub.nodes = self.nodes;
let read = sub.open(Kind::Group, false).and_then(|()| sub.run());
self.nodes = sub.nodes;
if read.is_err() || !sub.unsupported.is_empty() || !sub.unknown.is_empty() || sub.frames.len() != 1 {
self.gradients = std::mem::take(&mut sub.gradients);
self.global_names = std::mem::take(&mut sub.global_names);
self.styles = std::mem::take(&mut sub.styles);
self.pattern_tiles = std::mem::take(&mut sub.pattern_tiles);
// Art stopped by a trailer, or with an array, type, image, placed file, gradient mesh or
// gradient still open at the end (as [`Reader::run_string`] checks), isn't whole.
let open = sub.done
|| sub.stack.iter().any(|v| matches!(v, V::Mark))
|| !sub.marks.is_empty()
|| sub.text.is_some()
|| sub.raster.is_some()
|| sub.place.is_some()
|| sub.mesh.is_some()
|| sub.gradient_def.is_some();
let head = sub.symbol.take().unwrap_or_default();
let registration = head.registration;
let measured = read.is_ok() && !open && sub.unsupported.is_empty() && sub.unknown.is_empty() && sub.frames.len() == 1;
let Some(frame) = sub.frames.pop().filter(|_| measured) else { return };
let mut kids = frame.children;
// Where a symbol's art puts a pattern's tiles isn't known.
let whole = !head.left_out && sub.unread.is_empty() && sub.hidden_unread.is_empty() && !kids.iter().any(|n| paints_pattern(n, 0));
if !whole {
let boxes = self.doc.symbol_boxes();
let bounds = kids.iter().fold(None, |acc, n| vectorcraft_geom::union_opt(acc, n.visual_bounds_with(&boxes)));
drop(boxes);
if let Some(b) = bounds.filter(|b| sane(*b) && b.area() > 0.0) {
self.symbol_bounds.insert(name, b);
}
return;
}
let Some(frame) = sub.frames.pop() else { return };
let bounds = frame.children.iter().fold(None, |acc, n| vectorcraft_geom::union_opt(acc, n.visual_bounds()));
let Some(bounds) = bounds.map(|b| sub.space().inverse().transform_rect_bbox(b)) else { return };
if sane(bounds) && bounds.area() > 0.0 {
self.symbol_bounds.insert(name, bounds);
let art = match (kids.len(), kids.pop()) {
(1, Some(one)) => one,
(_, last) => Node::group(self.doc.alloc_id(), kids.into_iter().chain(last).map(Arc::new).collect()),
};
// The group a definition holds its art in, when it holds one object and isn't linked to a
// graphic style.
let linked = sub.style_links.iter().any(|(id, _)| *id == art.id);
let art = match symbol_art_member(&art).filter(|_| !linked).cloned() {
Some(m) => Arc::unwrap_or_clone(m),
None => art,
};
let read_art = art;
let mut art = self.doc.reid(&read_art);
self.reid_masks(&mut art, 0);
// The objects of the art linked to graphic styles, by their ids in the document.
if !sub.style_links.is_empty() {
let mut ids = HashMap::new();
pair_ids(&read_art, &art, &mut ids, 0);
for (id, style) in &sub.style_links {
if let Some(new) = ids.get(id)
&& self.style_links.len() < MAX_NODES
{
self.style_links.push((*new, style.clone()));
}
}
}
let named = self.unique_symbol_name(if name.is_empty() { "Symbol" } else { &name });
self.doc.symbols.push(Symbol { name: named.clone(), art: Arc::new(art), dynamic: false });
if let Some(reg) = registration.and_then(symbol_registration) {
self.doc.set_symbol_registration(&named, reg);
}
self.symbol_names.entry(name).or_insert(named);
for (key, blob) in sub.doc.images {
self.doc.images.entry(key).or_insert(blob);
}
self.spots.extend(sub.spots);
self.stop_spots.extend(sub.stop_spots);
self.cmyk_colors += sub.cmyk_colors;
self.rgb_colors += sub.rgb_colors;
self.drawn_looks += sub.drawn_looks;
for w in &sub.warnings {
self.warn(w);
}
}
/// `base`, or the first free "`base` N" (N from 2) when a symbol read has that name, as
/// [`vectorcraft_doc::Document::unique_symbol_name`] names it, without looking at every symbol
/// for each N.
fn unique_symbol_name(&mut self, base: &str) -> String {
let mut named = base.to_string();
if self.symbol_taken.contains(&named) {
let next = self.symbol_suffix.entry(named.clone()).or_insert(2);
while self.symbol_taken.contains(&format!("{base} {next}")) {
*next += 1;
}
named = format!("{base} {next}");
*next += 1;
}
self.symbol_taken.insert(named.clone());
named
}
/// Give the art of the opacity masks in `n` (a copy of a symbol's art with ids of this
/// document, [`vectorcraft_doc::Document::reid`], which leaves masks as they are) ids of this
/// document too.
fn reid_masks(&mut self, n: &mut Node, depth: usize) {
if depth > MAX_DEPTH {
return;
}
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) {
let mut art = self.doc.reid(&m.art);
self.reid_masks(&mut art, depth + 1);
m.art = Arc::new(art);
}
for c in n.children_mut().into_iter().flatten() {
self.reid_masks(Arc::make_mut(c), depth + 1);
}
}
/// The symbol list (`section`: what follows `%AI24_BeginSymbolList`): the symbols' names in the
/// Symbols panel's order. The first list is kept.
fn symbol_list(&mut self, section: &[u8]) {
if self.symbol.is_some() || self.pattern.is_some() || self.symbol_list.is_some() {
return;
}
let mut lex = Lexer::new(section);
let mut names = vec![];
while let Some(t) = lex.next_token() {
if let Tok::Str(bytes) = t.tok {
if names.len() >= MAX_LISTED {
break;
}
names.push(obj::text(&bytes));
}
}
self.symbol_list = Some(names);
}
/// A plug-in object (`section`: what follows `%AI8_BeginPluginObject`): the brush manager's
@@ -560,15 +716,19 @@ impl<'a> Reader<'a> {
// In a space of its own (y down), with no head to take.
sub.pattern = Some(PatternHead { taken: true, ..PatternHead::default() });
sub.subreader_depth = self.subreader_depth + 1;
// The gradients and patterns defined so far, lent.
// The gradients and patterns defined so far, and which patterns are in the version 7 form, lent.
sub.gradients = std::mem::take(&mut self.gradients);
sub.pattern_tiles = std::mem::take(&mut self.pattern_tiles);
sub.v7_patterns = std::mem::take(&mut self.v7_patterns);
sub.global_names = std::mem::take(&mut self.global_names);
sub.nodes = self.nodes;
sub.template = self.template;
let read = sub.open(Kind::Group, false).and_then(|()| sub.run());
self.nodes = sub.nodes;
self.gradients = std::mem::take(&mut sub.gradients);
self.pattern_tiles = std::mem::take(&mut sub.pattern_tiles);
self.v7_patterns = std::mem::take(&mut sub.v7_patterns);
self.global_names = std::mem::take(&mut sub.global_names);
// Images aren't kept: the document's images don't count a brush's art among their users. Art
// read with a note (something left out of it) isn't kept either.
let whole = read.is_ok()
@@ -769,6 +929,64 @@ fn ps_string(v: &[u8]) -> Option<String> {
None
}
/// The one member of `n` when `n` is a plain group holding only it (not clipping, unnamed, shown,
/// unlocked, opaque, Normal, not isolated, knockout neutral, no knockout shape, appearance, opacity
/// mask or other extras such as object attributes): a symbol's art written as such a group
/// (definitions hold a group) is that member.
pub(crate) fn symbol_art_member(n: &Node) -> Option<&Arc<Node>> {
let NodeKind::Group { children, clip: false } = &n.kind else { return None };
let [one] = children.as_slice() else { return None };
let plain = n.name.as_deref().is_none_or(str::is_empty)
&& n.visible
&& !n.locked
&& n.opacity == 1.0
&& n.blend == vectorcraft_color::BlendMode::Normal
&& !n.isolate
&& n.knockout == vectorcraft_doc::Knockout::Neutral
&& !n.knockout_shape
&& n.appearance.items.is_empty()
&& n.appearance.effects.is_empty()
&& *n.extras() == vectorcraft_doc::NodeExtras::default();
plain.then_some(one)
}
/// Whether `n`, an object in it or the art of an opacity mask in it is filled or stroked with a
/// pattern.
fn paints_pattern(n: &Node, depth: usize) -> bool {
if depth > MAX_DEPTH {
return true;
}
let pattern = |p: &super::Paint| matches!(p, super::Paint::Pattern { .. });
n.appearance.items.iter().any(|item| match item {
super::AppearanceItem::Fill(f) => pattern(&f.paint),
super::AppearanceItem::Stroke(s) => pattern(&s.paint),
}) || n.extras().mask.as_ref().is_some_and(|m| paints_pattern(&m.art, depth + 1))
|| n.children().into_iter().flatten().any(|c| paints_pattern(c, depth + 1))
}
/// Each id of `old` and its descendants → the id of the object in its place in `new`, a copy of
/// `old` with new ids ([`vectorcraft_doc::Document::reid`]).
fn pair_ids(old: &Node, new: &Node, ids: &mut HashMap<NodeId, NodeId>, depth: usize) {
ids.insert(old.id, new.id);
if depth > MAX_DEPTH {
return;
}
if let (Some(a), Some(b)) = (old.extras().mask.as_ref(), new.extras().mask.as_ref()) {
pair_ids(&a.art, &b.art, ids, depth + 1);
}
if let (Some(a), Some(b)) = (old.children(), new.children()) {
for (a, b) in a.iter().zip(b) {
pair_ids(a, b, ids, depth + 1);
}
}
}
/// The registration point `AI13PatternRegistrationType` `v` gives a symbol: 1 to 9 from the top
/// left, row by row (5 the center); `None` for other numbers.
pub(super) fn symbol_registration(v: f64) -> Option<SymbolRegistration> {
(v.fract() == 0.0 && (1.0..=9.0).contains(&v)).then(|| SymbolRegistration(v as u8 - 1))
}
#[cfg(test)]
mod tests {
use super::*;
@@ -786,9 +1004,11 @@ mod tests {
assert_eq!(ps_string(longest.as_bytes()).map(|s| s.len()), Some(MAX_STRING));
}
/// Definitions nested in a definition aren't read, however deep, and none is read past the
/// limit of nested readers.
#[test]
fn deeply_nested_symbol_definitions_stop_at_subreader_limit() {
let mut definition = String::from("(Outer) 0 Ae\n");
let mut definition = String::from("(Outer) 0 A 0 Xw 0 Ae\n");
for i in 0..300 {
definition.push_str(&format!("%AI14_BeginSymbol\n(S{i}) 0 Ae\n"));
}
@@ -798,8 +1018,34 @@ mod tests {
}
let mut reader = Reader::new(b"");
reader.subreader_depth = MAX_SUBREADERS;
reader.symbol_bounds(definition.as_bytes());
assert!(reader.symbol_bounds.is_empty());
reader.define_symbol(definition.as_bytes());
assert!(reader.doc.symbols.is_empty());
reader.subreader_depth = 0;
reader.define_symbol(definition.as_bytes());
let names: Vec<&str> = reader.doc.symbols.iter().map(|s| s.name.as_str()).collect();
assert_eq!(names, ["Outer"]);
}
/// Definitions past the limit aren't read, however they are named.
#[test]
fn symbol_definitions_stop_at_the_limit_even_with_one_name() {
let mut reader = Reader::new(b"");
for _ in 0..MAX_SYMBOLS + 10 {
reader.define_symbol(b"(Same) 0 A 0 Xw 0 Ae\nu\nU\n");
}
assert_eq!(reader.doc.symbols.len(), MAX_SYMBOLS);
assert_eq!(reader.doc.symbols.last().map(|s| s.name.as_str()), Some(format!("Same {MAX_SYMBOLS}").as_str()));
}
/// The registration points 1 to 9 run from the top left, row by row; other numbers give none.
#[test]
fn symbol_registration_numbers_run_row_by_row() {
assert_eq!(symbol_registration(1.0), Some(SymbolRegistration(0)));
assert_eq!(symbol_registration(5.0), Some(SymbolRegistration::CENTER));
assert_eq!(symbol_registration(9.0), Some(SymbolRegistration(8)));
for v in [0.0, 10.0, 2.5, -1.0, f64::NAN] {
assert_eq!(symbol_registration(v), None);
}
}
#[test]
+210 -46
View File
@@ -4,10 +4,10 @@ use super::containers::drop_commented_copies;
use super::ops::appearance_from_art_style;
use super::types::{FLIP, Kind, MAX_DEPTH};
use super::{
Affine, Arc, Artboard, CANVAS_CENTRE, ColorMode, Document, HashMap, Node, NodeId, NodeKind, Obj, OpacityMask, Paint, Point, Reader, Rect,
Affine, Arc, Artboard, CANVAS_CENTRE, ColorMode, Document, Global, HashMap, Node, NodeId, NodeKind, Obj, OpacityMask, Paint, Point, Reader, Rect,
Structure, Swatch, Unit, V, obj,
};
use vectorcraft_doc::{DataSet, DataValue, GraphicStyle, Guide, ImageBlob, PatternDef, TextWrap, Variable, VariableKind, Variables};
use vectorcraft_doc::{DataSet, DataValue, GraphicStyle, Guide, ImageBlob, PatternDef, Symbol, TextWrap, Variable, VariableKind, Variables};
/// `%AI5_RulerUnits` → [`Unit`] (Illustrator 7 spec table 3; centimeters is 4; pixels is 6 in later files).
fn ruler_unit(v: u8) -> Option<Unit> {
@@ -128,27 +128,41 @@ pub(crate) const LOOK_SLOT: &str = "\u{0}text:look";
/// The artboards (names, and rects in art space) of the editing data `data` that [`read`] can't
/// read as a whole, as far as it gets: where to put the pages of its PDF part instead, and what to
/// call them (#1068).
pub fn artboards(data: &[u8]) -> Vec<(String, Rect)> {
/// call them (#1068); and the index among them of the active artboard (`CropAreaActive`).
pub fn artboards(data: &[u8]) -> (Vec<(String, Rect)>, Option<usize>) {
let found = artboards_read(data);
if !found.is_empty() {
if !found.0.is_empty() && found.1.is_some() {
return found;
}
// Reading can stop before the artboards (art kept in the document's data comes first): read
// their array on its own.
artboard_array(data).map_or(found, |array| {
let mut alone = b"%_/Document :\n%_/Dictionary :\n".to_vec();
alone.extend_from_slice(array);
alone.extend_from_slice(b"\n%_; /NotRecorded ,\n%_;\n");
artboards_read(&alone)
})
// Reading can stop before the artboards (art kept in the document's data comes first), or
// between them and the active artboard's entry: read their array on its own.
let Some((array, active)) = artboard_array(data) else { return found };
let mut alone = b"%_/Document :\n%_/Dictionary :\n".to_vec();
alone.extend_from_slice(array);
if let Some(active) = active {
alone.push(b'\n');
alone.extend_from_slice(active);
}
alone.extend_from_slice(b"\n%_; /NotRecorded ,\n%_;\n");
let (boards, active) = artboards_read(&alone);
if found.0.is_empty() {
(boards, active)
} else if boards == found.0 {
// The same array: its names and rects read alike.
(found.0, active)
} else {
found
}
}
/// The key that ends the `ArtboardArray` entry of the editing data.
const ARTBOARD_ARRAY: &[u8] = b"%_; (ArtboardArray) ,";
/// The `ArtboardArray` entry of the editing data `data`, from its `/Array :` to its key: found
/// from the key back, counting the dictionaries its artboards open and close.
fn artboard_array(data: &[u8]) -> Option<&[u8]> {
const KEY: &[u8] = b"%_; (ArtboardArray) ,";
let end = data.windows(KEY.len()).rposition(|w| w == KEY)? + KEY.len();
/// from the key back, counting the dictionaries its artboards open and close; and the
/// `CropAreaActive` entry of the dictionary that holds it ([`crop_area_active`]).
fn artboard_array(data: &[u8]) -> Option<(&[u8], Option<&[u8]>)> {
let end = data.windows(ARTBOARD_ARRAY.len()).rposition(|w| w == ARTBOARD_ARRAY)? + ARTBOARD_ARRAY.len();
let head = data.get(..end)?;
let mut depth = 0usize;
let mut line_end = head.len();
@@ -160,7 +174,10 @@ fn artboard_array(data: &[u8]) -> Option<&[u8]> {
} else if text.starts_with(b"/") && text.windows(2).any(|w| w == b" :") {
depth = depth.checked_sub(1)?;
if depth == 0 {
return head.get(line_start..);
let breaks = |b: &u8| *b == b'\n' || *b == b'\r';
let after = data.get(end..).and_then(|rest| crop_area_active(rest.split(breaks), true));
let active = after.or_else(|| data.get(..line_start).and_then(|before| crop_area_active(before.rsplit(breaks), false)));
return Some((head.get(line_start..)?, active));
}
}
}
@@ -168,6 +185,33 @@ fn artboard_array(data: &[u8]) -> Option<&[u8]> {
}
}
/// The `CropAreaActive` entry (`%_<n> /Int (CropAreaActive) ,`) among the entries of the dictionary
/// that holds the `ArtboardArray` entry, skipping the dictionaries and arrays inside it: `lines` are
/// the lines after that entry, in order (`forward`), or those before it, last first.
fn crop_area_active<'a>(lines: impl Iterator<Item = &'a [u8]>, forward: bool) -> Option<&'a [u8]> {
const KEY: &[u8] = b" /Int (CropAreaActive) ,";
let mut depth = 0usize;
for line in lines {
let Some(text) = line.strip_prefix(b"%_") else { continue };
let closes = text.starts_with(b";") || text.starts_with(b"/Def ;");
let opens = !closes && text.starts_with(b"/") && text.windows(2).any(|w| w == b" :");
let (enters, leaves) = if forward { (opens, closes) } else { (closes, opens) };
if enters {
// Into a dictionary or array inside the holder.
depth += 1;
} else if leaves {
// Out of one, or out of the holder itself.
depth = depth.checked_sub(1)?;
} else if depth == 0 {
let digits = text.iter().take_while(|b| b.is_ascii_digit()).count();
if digits > 0 && text.get(digits..) == Some(KEY) {
return Some(line);
}
}
}
None
}
/// The palette of a `.ai` file's editing data, as [`palette`] reads it.
pub struct PaletteSwatches {
pub swatches: Vec<Swatch>,
@@ -231,7 +275,7 @@ fn repoint(n: &mut Node, renamed: &std::collections::BTreeMap<String, String>) {
/// editing data defines, which are named apart from `patterns` ([`beside`]); `None` when the
/// palette is empty or reading stops before it.
pub fn palette(data: &[u8], patterns: &[PatternDef]) -> Option<PaletteSwatches> {
let mut r = Reader::new(data);
let mut r = Reader::with_names(data);
// The palette, the gradients and the patterns it names come before the art, so an error in the
// art leaves them read.
let _ = r.run();
@@ -281,7 +325,7 @@ pub struct Brushes {
pub fn brushes(data: &[u8], patterns: &[PatternDef]) -> Option<Brushes> {
// Brush objects are plug-in objects: data without one isn't read again.
memchr::memmem::find(data, b"BeginPluginObject")?;
let mut r = Reader::new(data);
let mut r = Reader::with_names(data);
// The brushes come before the art, so an error in the art leaves them read.
let _ = r.run();
let (mut lib, unread) = r.brush_library()?;
@@ -317,9 +361,25 @@ pub fn brushes(data: &[u8], patterns: &[PatternDef]) -> Option<Brushes> {
Some(Brushes { brushes: lib, patterns: added, images, note: (unread > 0).then(|| brush::left_out_note(unread)) })
}
/// The graphic styles of the editing data `data`, for a file whose layers aren't read (a graphic
/// style library has none), as [`read`] makes them, with ids from 1, and the data's declared large
/// canvas scale (1 when it declares none). `large_canvas`: as [`read`] takes it. The styles are
/// those the list names before reading stops, and none when the data has no style list or lists no
/// style this reads.
pub fn graphic_styles(data: &[u8], large_canvas: bool) -> (Vec<GraphicStyle>, f64) {
if crate::import::ai::find(data, b"BeginArtStyleList").is_none() {
return (vec![], 1.0);
}
let mut r = Reader::with_names(data);
r.large_canvas = large_canvas.then_some(1.0);
// The styles come before the art, so an error in the art leaves them read.
let _ = r.run();
(r.graphic_styles().0, r.canvas_scale)
}
/// [`artboards`] as far as reading `data` from its start gets: those read before an error, and
/// those of a `/Document` still open when it stopped (its art can be what stopped it).
fn artboards_read(data: &[u8]) -> Vec<(String, Rect)> {
fn artboards_read(data: &[u8]) -> (Vec<(String, Rect)>, Option<usize>) {
let mut r = Reader::new(data);
let _ = r.run();
let open: Vec<Obj> = r.frames.iter().filter_map(|f| if let Kind::Obj(o) = &f.kind { Some((**o).clone()) } else { None }).collect();
@@ -328,7 +388,8 @@ fn artboards_read(data: &[u8]) -> Vec<(String, Rect)> {
r.document(o);
}
}
r.artboards.into_iter().map(|b| (b.name, b.rect)).collect()
let active = r.active_board.filter(|i| *i < r.artboards.len());
(r.artboards.into_iter().map(|b| (b.name, b.rect)).collect(), active)
}
/// An object bound to a variable of the library: the variable's name, and the XML id of the object
@@ -406,10 +467,23 @@ pub fn variables(data: &[u8]) -> VariableRead {
}
impl<'a> Reader<'a> {
/// Take the author and custom colors that the header of the program `ps` gives (its comment
/// lines up to `%%EndComments`), where the editing data's own header gives none: the program of
/// an EPS whose editing data is kept apart from it.
pub(super) fn program_header(&mut self, ps: &[u8]) {
/// Take the author and custom colors that the header of a program gives (`outer`, from
/// [`Self::header_of`]), where the editing data's own header gives none: the program of an EPS
/// whose editing data is kept apart from it.
pub(super) fn program_header(&mut self, outer: Reader<'_>) {
if self.author.is_none() {
self.author = outer.author;
}
for n in outer.custom_colors {
if self.custom_colors.len() < super::directives::MAX_CUSTOM_COLORS && !self.custom_colors.iter().any(|c| c.name == n.name) {
self.custom_colors.push(n);
}
}
}
/// A reader that has read the header of the program `ps` (its comment lines up to
/// `%%EndComments`).
pub(super) fn header_of(ps: &[u8]) -> Reader<'_> {
let mut end = 0;
for line in ps.split_inclusive(|&b| b == b'\n' || b == b'\r') {
if !line.starts_with(b"%") && !line.trim_ascii().is_empty() {
@@ -422,14 +496,7 @@ impl<'a> Reader<'a> {
}
let mut outer = Reader::new(ps.get(..end).unwrap_or_default());
let _ = outer.run();
if self.author.is_none() {
self.author = outer.author;
}
for n in outer.custom_colors {
if self.custom_colors.len() < super::directives::MAX_CUSTOM_COLORS && !self.custom_colors.iter().any(|c| c.name == n.name) {
self.custom_colors.push(n);
}
}
outer
}
}
@@ -495,9 +562,27 @@ fn text_wrap(o: &Obj, scale: f64) -> Option<TextWrap> {
}
impl<'a> Reader<'a> {
/// An object's dictionary: its name (`AIArtName`, or the XML id `AI10_ArtUID`), and the
/// opacity mask it may carry.
/// An object's dictionary: its name (`AIArtName`, or the XML id `AI10_ArtUID`), the opacity
/// mask it may carry, and in a pattern's definition the mark of the tile's box
/// (`AIPattern_Editor_Backing_Tile_Rect`), which leaves that box out of the art.
pub(super) fn art_dictionary(&mut self, o: &Obj) {
// The unpainted box that a pattern's definition marks as its tile's box isn't art.
if self.pattern.is_some()
&& o.nums("AIPattern_Editor_Backing_Tile_Rect").first().copied() == Some(1.0)
&& self.after_object
&& let Some(f) = self.frames.last_mut()
&& f.children.last().is_some_and(|n| matches!(n.kind, NodeKind::Path { .. }) && n.appearance.items.iter().all(|i| i.paint().is_none()))
{
f.children.pop();
return;
}
// The dictionary after a symbol's art: its registration point.
if self.frames.len() == 1
&& let Some(head) = self.symbol.as_mut()
&& let Some(r) = o.nums("AI13PatternRegistrationType").first()
{
head.registration = Some(*r);
}
self.constraint_art(o);
// A blend's key object or spine.
if let Some(kind) = o.text("ShapeBlendPathType")
@@ -519,7 +604,8 @@ impl<'a> Reader<'a> {
let value =
OpacityMask { art: art.clone(), clip: on("Clipping"), invert: on("Inverted"), disabled: on("Disabled"), linked: on("Linked") };
if let Some(n) = self.last_object().filter(|n| !matches!(n.kind, NodeKind::Layer { .. })) {
n.extras_mut().mask = Some(Box::new(value));
n.extras_mut().mask = Some(Box::new(value.clone()));
self.each_linked_frame(|n| n.extras_mut().mask = Some(Box::new(value.clone())));
} else if !on("Disabled") {
self.unreadable("opacity masks without an owning object", false);
}
@@ -542,6 +628,7 @@ impl<'a> Reader<'a> {
&& let Some(n) = self.last_object().filter(|n| !matches!(n.kind, NodeKind::Layer { .. }))
{
n.extras_mut().wrap = Some(wrap);
self.each_linked_frame(|n| n.extras_mut().wrap = Some(wrap));
}
// The object's XML id, which the variable library's bindings name it by.
if let Some(uid) = o.obj("AI10_ArtUID").and_then(Obj::content_text).filter(|u| !u.is_empty())
@@ -565,8 +652,9 @@ impl<'a> Reader<'a> {
}
}
/// The `/Document` dictionary: the artboards and their display options, Document Raster Effects
/// Settings, its variable library (the first one read), and its Objects on Path records.
/// The `/Document` dictionary: the artboards and their display options, the active artboard
/// (`CropAreaActive`, `/Int`: its index in the `ArtboardArray`, next to it), Document Raster
/// Effects Settings, its variable library (the first one read), and its Objects on Path records.
pub(super) fn document(&mut self, o: &Obj) {
if !self.variables.present {
self.variables = variable_library(o);
@@ -575,7 +663,9 @@ impl<'a> Reader<'a> {
if let Some(r) = find_entry(o, "AI Auto Rasterize", 0) {
raster_settings(r, &mut self.doc);
}
let Some(list) = find_entry(o, "ArtboardArray", 0) else { return };
let Some(holder) = find_holder(o, "ArtboardArray", 0) else { return };
let Some(list) = holder.obj("ArtboardArray") else { return };
let active = typed(holder, "CropAreaActive", "Int");
for (i, ab) in list.items().enumerate().take(1000) {
let (p1, p2) = (ab.nums("PositionPoint1"), ab.nums("PositionPoint2"));
let ([x0, y0, ..], [x1, y1, ..]) = (p1.as_slice(), p2.as_slice()) else { continue };
@@ -586,6 +676,9 @@ impl<'a> Reader<'a> {
let name = ab.text("Name").unwrap_or_else(|| format!("Artboard {}", i + 1));
let mut board = AiArtboard::new(name, r);
display_options(ab, &mut board);
if active == Some(i as f64) {
self.active_board = Some(self.artboards.len());
}
self.artboards.push(board);
}
}
@@ -639,9 +732,50 @@ impl<'a> Reader<'a> {
}
/// Art space → where the art being read goes: the document, or while a pattern's definition is
/// read, the pattern's space (y down).
/// read, the pattern's space (y down). A symbol's definition is written in the symbol's space.
pub(crate) fn space(&mut self) -> Affine {
if self.pattern.is_some() { FLIP } else { self.ensure_space() }
if self.pattern.is_some() {
FLIP
} else if self.symbol.is_some() {
Affine::IDENTITY
} else {
self.ensure_space()
}
}
/// The space an image's matrix is in → where the art being read goes: [`Self::space`], and in a
/// symbol's art (outside a pattern's definition) the canvas's space turned y up about art space's
/// origin there, as an instance's matrix in it is; `None` there without a template box.
pub(super) fn image_space(&mut self) -> Option<Affine> {
if self.pattern.is_none() && self.symbol.is_some() {
return self.canvas_origin().map(|o| Affine::new([1.0, 0.0, 0.0, -1.0, o.x, o.y]));
}
Some(self.space())
}
/// The canvas point of art space's origin, from the template box's center (the canvas's): what
/// a pattern's gradients and the instances in a symbol's art are written about.
pub(super) fn canvas_origin(&self) -> Option<Point> {
let t = self.template?;
let (cx, cy) = ((t[0] + t[2]) / 2.0, (t[1] + t[3]) / 2.0);
let origin = Point::new(CANVAS_CENTRE - cx, CANVAS_CENTRE + cy);
(origin.x.is_finite() && origin.y.is_finite()).then_some(origin)
}
/// The symbols in the symbol list's order, those it doesn't name after them as they were
/// defined; names it has twice or that no symbol has don't count.
fn order_symbols(&mut self) {
let Some(list) = self.symbol_list.take() else { return };
let mut slots: Vec<Option<Symbol>> = std::mem::take(&mut self.doc.symbols).into_iter().map(Some).collect();
let at: HashMap<String, usize> = slots.iter().enumerate().filter_map(|(i, s)| s.as_ref().map(|s| (s.name.clone(), i))).collect();
let mut ordered = Vec::with_capacity(slots.len());
for name in &list {
if let Some(s) = self.symbol_names.get(name).and_then(|named| at.get(named)).and_then(|i| slots.get_mut(*i)).and_then(Option::take) {
ordered.push(s);
}
}
ordered.extend(slots.into_iter().flatten());
self.doc.symbols = ordered;
}
/// The swatches of the palette, `[None]` first, in its order, and its color groups; a gradient
@@ -652,18 +786,26 @@ impl<'a> Reader<'a> {
return None;
}
let palette = std::mem::take(&mut self.palette);
let swatch = |e: crate::import::ai::palette::Entry| -> Option<Swatch> {
let swatch = |mut e: crate::import::ai::palette::Entry| -> Option<Swatch> {
use crate::import::ai::palette::Cell;
let (paint, global, spot) = match e.cell {
Cell::Color { color, global, spot } => (Paint::solid(color), global, spot),
// A swatch named by its gradient or pattern takes the name that got in the document.
Cell::Gradient(g) => {
let mut gp = vectorcraft_color::gradient::GradientPaint::new(self.gradients.get(&g)?.clone());
if e.name == g {
e.name = self.global_names.get(Global::Gradient, &g).to_string();
}
gp.swatch = Some(e.name.clone());
(Paint::Gradient(Box::new(gp)), false, false)
}
Cell::Pattern(p) => {
patterns.iter().find(|d| d.name == p)?;
(Paint::Pattern { pattern: p, xf: Affine::IDENTITY }, false, false)
let pattern = self.global_names.get(Global::Pattern, &p).to_string();
patterns.iter().find(|d| d.name == pattern)?;
if e.name == p {
e.name.clone_from(&pattern);
}
(Paint::Pattern { pattern, xf: Affine::IDENTITY }, false, false)
}
};
Some(Swatch { name: e.name, paint, global, spot })
@@ -740,9 +882,13 @@ impl<'a> Reader<'a> {
}
let to_doc = self.ensure_space();
let artboard = self.first_board();
self.check_symbols();
self.order_symbols();
drop_commented_copies(&mut self.doc.layers, &self.hidden_ids);
super::on_path::apply(&mut self.doc, &self.on_path);
let mut doc = std::mem::replace(&mut self.doc, Document::new(1.0, 1.0));
// The active artboard, when it is not the first (the default).
let active = self.active_board.filter(|i| *i > 0 && *i < self.artboards.len());
let boards: Vec<AiArtboard> = if self.artboards.is_empty() {
artboard.or_else(|| self.bbox_board()).map(|r| vec![AiArtboard::new("Artboard 1".to_string(), r)]).unwrap_or_default()
} else {
@@ -778,6 +924,7 @@ impl<'a> Reader<'a> {
color: None,
}];
}
doc.opened_artboard = active.and_then(|i| doc.artboards.get(i)).map(|a| a.id);
if !self.ruler_guides.is_empty() {
let ids: Vec<u32> = doc.artboards.iter().map(|a| a.id).collect();
let (candidates, centre) = (std::mem::take(&mut self.ruler_guides), self.template_center);
@@ -850,6 +997,9 @@ impl<'a> Reader<'a> {
let links: HashMap<NodeId, u32> = self.style_links.iter().filter_map(|(node, name)| Some((*node, *ids.get(name)?))).collect();
if !links.is_empty() {
link_styles(&mut doc.layers, &links, &styles, 0);
for symbol in &mut doc.symbols {
link_styles(std::slice::from_mut(&mut symbol.art), &links, &styles, 0);
}
}
doc.graphic_styles = styles.into();
}
@@ -872,6 +1022,11 @@ impl<'a> Reader<'a> {
doc.variables = variables.variables.into();
}
let (bindings, bindings_skipped) = (variables.bindings, variables.bindings_skipped);
// Symbols that hold instances of themselves can't be drawn: those instances go before the
// layers are compared with the page.
if !doc.symbols.is_empty() {
doc.limit_depth_noting(&mut warnings);
}
Ok(Structure {
doc,
to_doc,
@@ -883,6 +1038,7 @@ impl<'a> Reader<'a> {
unread_elsewhere: self.unread_elsewhere,
slot_names: self.slot_names,
restyled: self.restyled,
placeholders: self.placeholders,
placed_elsewhere: self.placed_elsewhere,
envelopes_drawn: self.envelopes_drawn,
styles_read,
@@ -981,10 +1137,18 @@ fn take_ruler_guides(nodes: &mut [Arc<Node>], pick: &dyn Fn(NodeId) -> Option<Gu
}
pub(super) fn find_entry<'o>(o: &'o Obj, key: &str, depth: usize) -> Option<&'o Obj> {
find_holder(o, key, depth).and_then(|h| h.obj(key))
}
/// The dictionary that [`find_entry`] finds the entry `key` in: `o` or one it holds.
fn find_holder<'o>(o: &'o Obj, key: &str, depth: usize) -> Option<&'o Obj> {
if depth > 8 {
return None;
}
o.obj(key).or_else(|| o.entries.iter().flat_map(|(_, v)| v.iter()).filter_map(V::obj).find_map(|c| find_entry(c, key, depth + 1)))
if o.obj(key).is_some() {
return Some(o);
}
o.entries.iter().flat_map(|(_, v)| v.iter()).filter_map(V::obj).find_map(|c| find_holder(c, key, depth + 1))
}
// ---- the variable library -----------------------------------------------------------------
+271 -24
View File
@@ -1,9 +1,12 @@
use super::containers::close;
use super::document::slot_of;
use super::types::{BLENDS, FLIP, Frame, GRAPH_OPS, GRAPH_PLAIN, GRAPH_UNENDED, IGNORED, Kind, MAX_DEPTH, MAX_NODES, Place, line_width};
use super::types::{
BLENDS, FLIP, Frame, GRAPH_OPS, GRAPH_PLAIN, GRAPH_UNENDED, IGNORED, Kind, MAX_DEPTH, MAX_NODES, MAX_TAG_TEXT, MAX_TAGS, Place, URL_TAG,
line_width,
};
use super::{
Affine, Appearance, AppearanceItem, Arc, BlendMode, Dash, FillLayer, FillRule, Gradient, GradientDef, Graph, HashMap, HashSet, Instance,
Knockout, LayerColor, LineCap, LineJoin, Node, NodeId, NodeKind, Paint, Reader, Rect, StrokeLayer, V, obj, paint,
Affine, Appearance, AppearanceItem, Arc, BlendMode, Dash, FillLayer, FillRule, Global, Gradient, GradientDef, Graph, HashMap, HashSet, Instance,
Knockout, LayerColor, LineCap, LineJoin, Node, NodeId, NodeKind, Paint, Reader, Rect, ShownNames, StrokeLayer, V, obj, paint,
};
impl<'a> Reader<'a> {
@@ -73,6 +76,36 @@ impl<'a> Reader<'a> {
}
}
/// `/identifier (string) XT` (version 7 specification §7): a tag on the object before it. The
/// `AdobeURL` tag sets the object's URL, and every other tag is added to the object's data in
/// order, up to [`MAX_TAGS`]. A tag with no object before it, with an empty identifier, or with
/// an identifier or string longer than [`MAX_TAG_TEXT`] bytes is ignored, and so are tags in a
/// pattern's or brush's art, which is not an object of the document. A clipping path's tags are
/// its own, not those of the copy that paints its fill.
fn object_tag(&mut self, vals: &[V], hidden: bool) {
let [.., V::Name(id), V::Str(value)] = vals else {
self.note_unknown("XT", hidden);
return;
};
if id.is_empty() || id.len() > MAX_TAG_TEXT || value.len() > MAX_TAG_TEXT || !self.after_object || self.pattern.is_some() {
return;
}
let (id, value) = (id.clone(), obj::text(value));
let Some(kids) = self.frames.last_mut().map(|f| &mut f.children) else { return };
let Some(mut at) = kids.len().checked_sub(1) else { return };
if at > 0 && kids.get(at).is_some_and(|n| self.clip_fills.contains(&n.id)) {
at -= 1;
}
let Some(n) = kids.get_mut(at) else { return };
n.edit_attrs(|a| {
if id == URL_TAG {
a.url = value;
} else if a.data.len() < MAX_TAGS {
a.data.push((id, value));
}
});
}
pub(super) fn op(&mut self, w: &str, hidden: bool) -> Result<(), String> {
if self.blend_record.is_some() {
self.end_blend();
@@ -124,6 +157,7 @@ impl<'a> Reader<'a> {
"Bs" => d.stop(&vals, &mut self.stop_spots),
"BD" => {
if let Some((name, g)) = self.gradient_def.take().and_then(GradientDef::finish) {
self.global_names.define(Global::Gradient, &name);
self.gradients.insert(name, g);
}
}
@@ -211,6 +245,12 @@ impl<'a> Reader<'a> {
Some(0.0) => self.gs.show_center = None,
_ => {}
},
// Object tags (§7): `/identifier (string) XT` after the object it tags. The state written
// after a group or a mesh is still theirs after its tags.
"XT" => {
self.object_tag(&vals, hidden);
(self.group_ended, self.mesh_ended) = (group_ended, mesh_ended);
}
"w" => {
if let Some(v) = Self::nums(&vals).last().filter(|v| v.is_finite() && **v >= 0.0) {
self.gs.width = *v;
@@ -317,21 +357,28 @@ impl<'a> Reader<'a> {
"Tp" => self.begin_text_path(&vals),
"TP" => self.end_text_path(),
"TO" => self.end_text(hidden)?,
"Tx" | "Tj" | "TX" => self.text_body(w, &vals),
"Tr" | "Tf" | "Ts" | "Tz" | "Tt" | "TA" | "Tl" | "Ta" | "Ti" | "TC" | "TW" | "Tq" | "Th" => self.text_attr(w, &vals),
// `(text) justified TS`, special characters (§22.6): the reader adds its characters like `Tx`.
"Tx" | "Tj" | "TX" | "TS" => self.text_body(w, &vals),
"Tr" | "Tf" | "Ts" | "Tz" | "Tt" | "TA" | "Tl" | "Ta" | "Ti" | "TC" | "TW" | "Tq" | "Th" | "Xb" | "Xe" | "XB" => self.text_attr(w, &vals),
// Attributes the reader doesn't keep (kerning pairs, Far-Eastern type) and final-form
// positions (§15.3).
"Tk" | "TK" | "Tc" | "Tw" | "Tm" | "Td" | "T*" | "TR" | "T+" | "T-" | "TV" | "Tv" | "Ty" | "TY" | "TG" | "Tg" | "Tu" | "Xu" => {}
// The hyphenation language and tab rulers, which the reader doesn't keep either (§22): `XL`,
// `Xb`/`XB` a tab definition (and the `Xe` tab descriptions between them).
"XL" | "Xb" | "XB" | "Xe" => {}
// `TM` (pop text matrix) and `Te` (end render), listed in §22.6, keep nothing either; the
// reader takes `Te` with any number of operands.
"TM" | "Te" => {}
// The hyphenation language (`XL`), which the reader doesn't keep either (§22).
"XL" => {}
"TE" => self.te(&vals),
"TZ" => self.tz(&vals),
// An image whose samples follow in comment lines (read at `%AI5_EndRaster`).
"XI" if self.raster.is_some() => {
if let Some(r) = self.raster.as_mut() {
r.operands = Some(vals);
}
}
// A linked image (§8.2, §8.3): `(path) modified XG` names the file of the `XF` image after
// it, which has `XI`'s operands and no samples.
"XG" | "XF" => self.image_link_op(w, vals, hidden)?,
// A plugin group ends; a blend's record follows on `%` lines.
"XP" => {
let name = vals.iter().find_map(V::text).unwrap_or_default();
@@ -431,7 +478,7 @@ impl<'a> Reader<'a> {
self.unread_pattern(w);
return;
};
let p = Paint::Pattern { pattern: name.unwrap_or_default(), xf };
let p = Paint::Pattern { pattern: name.as_deref().map(|n| self.global_names.get(Global::Pattern, n).to_string()).unwrap_or_default(), xf };
if w == "p" {
self.pending_unread_fill = false;
self.gs.fill = p;
@@ -473,10 +520,16 @@ impl<'a> Reader<'a> {
self.gs.fill = p;
self.pending_fill = None;
self.pending_unread_fill = false;
if let Some(head) = self.symbol.as_mut() {
head.missing_fill = false;
}
} else {
self.gs.stroke = p;
self.pending_stroke = None;
self.pending_unread_stroke = false;
if let Some(head) = self.symbol.as_mut() {
head.missing_stroke = false;
}
}
}
@@ -496,8 +549,16 @@ impl<'a> Reader<'a> {
/// The state block of a layer whose art ended (`Xy`, `Xd`, `XW`, then `LB`) is read at the
/// `LB`, and can have the stroke style between its `Xy` and `Xd`: that keeps the layer's state,
/// and what a mesh or blend before it had (`mesh_undo`).
/// After an image, the operators that end its raster (`XH`, `Xr` and the `N` after
/// `%AI5_EndRaster`) keep it the object its name and opacity mask go to.
fn state_block_continues(&mut self, w: &str) {
if matches!(w, "Xy" | "Xd" | "XW" | "BB" | "LB") {
if self.image_tail && matches!(w, "XH" | "XT" | "Xr" | "N") {
return;
}
self.image_tail = false;
// An object's tags (`XT`) follow it one after another, and an image's follow the `XH` that
// ends its data.
if matches!(w, "Xy" | "Xd" | "XW" | "BB" | "LB" | "XT" | "XH") {
return;
}
self.after_object = false;
@@ -530,14 +591,18 @@ impl<'a> Reader<'a> {
let gs = &self.gs;
let state = (gs.opacity, gs.blend, gs.isolate, gs.knockout, gs.knockout_shape);
let Some(Frame { kind: Kind::Layer(_), children, .. }) = self.frames.last_mut() else { return };
let Some(n) = children.last_mut().filter(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Compound { .. })) else { return };
let Some(n) =
children.last_mut().filter(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Compound { .. } | NodeKind::SymbolInstance { .. }))
else {
return;
};
(n.opacity, n.blend, n.isolate, n.knockout, n.knockout_shape) = before;
self.layer_state = Some(state);
}
/// `mode opacity isolate knockout shape Xy`; after a group's end, the group's too, and right
/// after a gradient mesh's `/End X!` or a blend's record (before their `Xd` and `6 () XW`),
/// theirs, unless the layer's `LB` follows: then it is the layer's (see `end_layer`).
/// `mode opacity isolate knockout shape Xy`; after a group's end or a symbol instance, theirs
/// too, and right after a gradient mesh's `/End X!` or a blend's record (before their `Xd` and
/// `6 () XW`), theirs, unless the layer's `LB` follows: then it is the layer's (see `end_layer`).
fn transparency(&mut self, vals: &[V], mesh_ended: bool) {
let n = Self::nums(vals);
let [mode, opacity, rest @ ..] = n.as_slice() else { return };
@@ -567,6 +632,12 @@ impl<'a> Reader<'a> {
// The layer's instead when the layer's `7 () XW` follows (`layer_state_block`).
self.container_undo = in_layer.then_some(before);
self.layer_state = None;
} else if let Some(n) = self.last_object().filter(|n| matches!(n.kind, NodeKind::SymbolInstance { .. })) {
// A symbol instance's, as a group's.
let before = (n.opacity, n.blend, n.isolate, n.knockout, n.knockout_shape);
(n.opacity, n.blend, n.isolate, n.knockout, n.knockout_shape) = (gs.opacity, gs.blend, gs.isolate, gs.knockout, gs.knockout_shape);
self.container_undo = in_layer.then_some(before);
self.layer_state = None;
} else {
// After a layer's art and before its `LB`: the layer's own state (#2003). Kept until
// an operator that isn't part of the state block (or the `LB` that takes it) says the
@@ -652,7 +723,14 @@ impl<'a> Reader<'a> {
object,
look,
st,
&StylePaints { gradients: &self.gradients, patterns: &self.pattern_tiles, v7_patterns: &self.v7_patterns, space },
&StylePaints {
gradients: &self.gradients,
patterns: &self.pattern_tiles,
names: &self.global_names,
v7_patterns: &self.v7_patterns,
brushes: &self.brush_drafts,
space,
},
)
}) {
// Strokes and effects at the document's scale, as the art (a Large Canvas copy's is scaled up).
@@ -714,6 +792,23 @@ impl<'a> Reader<'a> {
look.name = object.name.clone().or(look.name.take());
look.visible = object.visible;
look.locked = object.locked;
// The object's note, Show Center, URL and data (object tags) stay with the look that stands
// for it, in place of the look's own where the object has them.
if let Some(a) = object.extras().attrs.as_deref().cloned() {
look.edit_attrs(|l| {
if a.show_center.is_some() {
l.show_center = a.show_center;
}
if !a.url.is_empty() {
l.url = a.url;
}
if !a.note.is_empty() {
l.note = a.note;
}
let room = MAX_TAGS.saturating_sub(l.data.len());
l.data.extend(a.data.into_iter().take(room));
});
}
if !hidden {
self.drawn_looks += 1;
}
@@ -769,12 +864,15 @@ fn pattern_controls(n: &[f64]) -> Option<Affine> {
xf.as_coeffs().iter().all(|v| v.is_finite()).then_some(xf)
}
/// What a style's fills paint with: the file's gradients and pattern tiles, the patterns defined in
/// the version 7 form, and art space → the document.
/// What a style's fills paint with: the file's gradients and pattern tiles with the names they get
/// in the document, the patterns defined in the version 7 form, and art space → the document.
struct StylePaints<'a> {
gradients: &'a HashMap<String, Gradient>,
patterns: &'a HashMap<String, Rect>,
names: &'a ShownNames,
v7_patterns: &'a HashSet<String>,
/// The brushes the file defines, which a brushed stroke names.
brushes: &'a [super::super::brush::BrushDraft],
space: Affine,
}
@@ -813,21 +911,88 @@ fn placed_paints(look: &Node, out: &mut HashMap<String, Paint>, depth: usize) {
}
}
/// Is `n` a path, a compound path or a group without a clip, with no opacity mask, the objects
/// whose outline the effects that move it (Transform, Twist, Free Distort) are read on? Images,
/// type (and a text object's slot, filled with type placed where the page has it) and live objects
/// draw more than their outline, and a mask stays where it is.
fn outlines_only(n: &Node) -> bool {
matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Group { clip: false, .. })
&& n.extras().mask.is_none()
&& slot_of(n.name.as_deref()).is_none()
}
/// Does `n`, inside an object whose outline an effect moves, move with it: is it and everything in
/// it [`outlines_only`], painting with no gradient or pattern (which stay where they are placed)
/// and with no effects of its own (drawn after the outer effect, not before)? Deeper than
/// [`MAX_DEPTH`] counts as no.
fn moves_alike(n: &Node, depth: usize) -> bool {
depth <= MAX_DEPTH
&& outlines_only(n)
&& n.appearance.effects.is_empty()
&& n.appearance.items.iter().all(|i| i.effects().is_empty() && !matches!(i.paint(), Paint::Gradient(_) | Paint::Pattern { .. }))
&& n.children().into_iter().flatten().all(|c| moves_alike(c, depth + 1))
}
/// Does `n` or anything in it (to [`MAX_DEPTH`]) have a stroke that paints?
fn strokes(n: &Node, depth: usize) -> bool {
depth > MAX_DEPTH
|| n.appearance.items.iter().any(|i| !i.is_fill() && !i.paint().is_none())
|| n.children().into_iter().flatten().any(|c| strokes(c, depth + 1))
}
/// Are all of path or compound path `n`'s segments straight, each anchor's handles on it?
fn straight(n: &Node) -> bool {
match &n.kind {
NodeKind::Path { path, .. } => path.subpaths.iter().flat_map(|s| &s.anchors).all(|a| a.h_in == a.p && a.h_out == a.p),
NodeKind::Compound { children, .. } => children.iter().all(|c| matches!(c.kind, NodeKind::Path { .. }) && straight(c)),
_ => false,
}
}
/// Is `object` one that style `st`, whose effect moves the outline, is read on? It and everything
/// in it [`moves_alike`], and the style paints no gradient. Twist is read only on an unstroked path
/// or compound path with straight segments, and Transform that scales, turns or reflects only when
/// nothing is stroked (its reference point lies on the bounds without strokes).
fn moves_with(object: &Node, st: &crate::import::ai::style::ArtStyle) -> bool {
use crate::import::ai::style::StyleItem;
let stroked = st.items.iter().any(|i| matches!(i, StyleItem::Stroke { paint, .. } if !paint.is_none()))
|| object.children().into_iter().flatten().any(|c| strokes(c, 1));
!st.items.iter().any(|i| matches!(i, StyleItem::Gradient { .. }))
&& outlines_only(object)
&& object.children().into_iter().flatten().all(|c| moves_alike(c, 1))
&& st.effects.iter().all(|e| match e.id.as_str() {
"distort.twist" => !stroked && matches!(object.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && straight(object),
"distort.transform" => {
let p = &e.params;
!stroked
|| (p["scaleH"].as_f64() == Some(100.0)
&& p["scaleV"].as_f64() == Some(100.0)
&& p["rotate"].as_f64() == Some(0.0)
&& p["reflectX"].as_bool() == Some(false)
&& p["reflectY"].as_bool() == Some(false))
}
_ => true,
})
}
/// What [`placed_paints`] keys a pattern's name with, apart from the gradients' names.
const PATTERN_KEY: &str = "\u{1}pattern ";
/// `object`'s appearance with style `st`, its drawn look `look`: `None` when the style isn't one
/// this reads, asks a group for fills or strokes, or has Pathfinder effects on anything but a group
/// with no fills or strokes.
/// this reads, asks a group for fills or strokes, has Pathfinder effects on anything but a group
/// with no fills or strokes, or moves the outline of an object it isn't read on ([`moves_with`]).
fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, paints: &StylePaints) -> Option<Appearance> {
use crate::import::ai::style::StyleItem;
// A text object's slot (an empty group standing for it) takes the style as the type will.
let slot = slot_of(object.name.as_deref()).is_some();
// A symbol instance draws its symbol's art: it keeps its drawn look.
if !st.plain
|| matches!(object.kind, NodeKind::SymbolInstance { .. })
|| (!slot && !st.simple)
|| (object.is_container() && !slot && !matches!(object.kind, NodeKind::Compound { .. }) && !st.items.is_empty())
|| (st.pathfinder
&& (slot || !st.items.is_empty() || object.is_compound_shape() || !matches!(object.kind, NodeKind::Group { clip: false, .. })))
|| (!slot && st.moves_outline() && !moves_with(object, st))
{
return None;
}
@@ -843,7 +1008,8 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p
let mut layer = match item {
StyleItem::Fill(paint) => AppearanceItem::Fill(FillLayer::new(paint.clone())),
StyleItem::Gradient { name, angle } => {
let paint = match (name.as_ref().and_then(|n| placed.get(n)), gradients, own_gradient) {
// The drawn look's gradients are keyed by the names they got in the document.
let paint = match (name.as_ref().and_then(|n| placed.get(paints.names.get(Global::Gradient, n))), gradients, own_gradient) {
// Other objects than type: the object's own, as they always were.
(_, 1, Some(own)) if !slot => own.paint.clone(),
(Some(p), ..) => p.clone(),
@@ -858,7 +1024,7 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p
};
AppearanceItem::Fill(FillLayer::new(paint))
}
StyleItem::Pattern { name, matrix, controls } => match placed.get(&format!("{PATTERN_KEY}{name}")) {
StyleItem::Pattern { name, matrix, controls } => match placed.get(&format!("{PATTERN_KEY}{}", paints.names.get(Global::Pattern, name))) {
Some(p) => AppearanceItem::Fill(FillLayer::new(p.clone())),
None => {
let tile = paints.patterns.get(name).copied()?;
@@ -867,10 +1033,20 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p
matrix = Some(matrix.unwrap_or(Affine::IDENTITY) * pattern_controls(controls)?);
}
let xf = pattern_xf(paints.space, matrix, tile)?;
AppearanceItem::Fill(FillLayer::new(Paint::Pattern { pattern: name.clone(), xf }))
AppearanceItem::Fill(FillLayer::new(Paint::Pattern { pattern: paints.names.get(Global::Pattern, name).to_string(), xf }))
}
},
StyleItem::Stroke { .. } => stroke_layer(item)?,
StyleItem::Stroke { brush, .. } => {
// A brushed stroke draws as its look only with the brush the file defines (the
// first of its name, as the Brushes panel keeps it) at the object's settings.
if let Some((name, settings)) = brush {
let draft = paints.brushes.iter().find(|d| &d.name == name)?;
if !super::super::brush::draws_as(draft, settings) {
return None;
}
}
stroke_layer(item)?
}
};
if let Some(look) = st.looks.get(n) {
with_look(&mut layer, look);
@@ -896,6 +1072,8 @@ pub(super) fn appearance_from_art_style(st: &crate::import::ai::style::ArtStyle)
for (n, item) in st.items.iter().enumerate() {
let mut layer = match item {
StyleItem::Fill(paint) => AppearanceItem::Fill(FillLayer::new(paint.clone())),
// A graphic style's brush isn't checked against the file's brushes: it is left out.
StyleItem::Stroke { brush: Some(_), .. } => return None,
StyleItem::Stroke { .. } => stroke_layer(item)?,
StyleItem::Gradient { .. } | StyleItem::Pattern { .. } => return None,
};
@@ -909,9 +1087,10 @@ pub(super) fn appearance_from_art_style(st: &crate::import::ai::style::ArtStyle)
/// A style's stroke as an appearance item (`None` for a fill).
fn stroke_layer(item: &crate::import::ai::style::StyleItem) -> Option<AppearanceItem> {
let crate::import::ai::style::StyleItem::Stroke { paint, width, cap, join, miter, dash, profile } = item else { return None };
let crate::import::ai::style::StyleItem::Stroke { paint, width, cap, join, miter, dash, profile, brush } = item else { return None };
let mut layer = StrokeLayer::new(paint.clone(), line_width(*width));
(layer.cap, layer.join, layer.miter_limit, layer.dash, layer.profile) = (*cap, *join, *miter, dash.clone(), profile.clone());
layer.brush = brush.as_ref().map(|(name, _)| name.clone());
Some(AppearanceItem::Stroke(layer))
}
@@ -942,3 +1121,71 @@ fn strip(n: &mut Node, hidden: &HashSet<NodeId>) {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use vectorcraft_doc::ImageObject;
use vectorcraft_geom::shapes;
fn square(id: u64, fill: Paint) -> Arc<Node> {
Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(fill, Paint::None, 0.0)))
}
#[test]
fn only_outlines_without_gradients_move_alike() {
// GUARDS: an image's pixels and a placed gradient stay behind when an effect moves the outline.
let solid = || square(2, Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0)));
assert!(moves_alike(&Node::group(NodeId(1), vec![solid(), solid()]), 1));
let gradient = square(3, Paint::Gradient(Box::new(vectorcraft_color::gradient::GradientPaint::new(Gradient::default()))));
assert!(!moves_alike(&Node::group(NodeId(1), vec![solid(), gradient]), 1));
let image =
ImageObject { key: "a".into(), width: 1, height: 1, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None };
let image = Arc::new(Node::new(NodeId(4), NodeKind::Image(Box::new(image))));
assert!(!moves_alike(&Node::group(NodeId(1), vec![Arc::new(Node::group(NodeId(5), vec![image.clone()]))]), 1));
assert!(!outlines_only(&image));
// A text object's slot, and a member with an opacity mask.
let mut slot = Node::group(NodeId(6), vec![]);
slot.name = Some(format!("{}0", super::super::document::TEXT_SLOT));
assert!(!moves_alike(&Node::group(NodeId(1), vec![solid(), Arc::new(slot)]), 1));
let mut masked = Node::clone(&solid());
masked.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(Node::group(NodeId(7), vec![]), true)));
assert!(!moves_alike(&Node::group(NodeId(1), vec![solid(), Arc::new(masked)]), 1));
// A member with an effect of its own.
let mut turned = Node::clone(&solid());
turned.appearance.effects.push(vectorcraft_doc::Effect {
id: "distort.twist".into(),
params: serde_json::json!({"angle": 30.0}),
visible: true,
});
assert!(!moves_alike(&Node::group(NodeId(1), vec![solid(), Arc::new(turned)]), 1));
// A member painting a pattern, whose tiles stay where they are, and a clipping group.
let tiled = square(8, Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY });
assert!(!moves_alike(&Node::group(NodeId(1), vec![solid(), tiled]), 1));
let mut clipped = Node::group(NodeId(9), vec![solid(), solid()]);
if let NodeKind::Group { clip, .. } = &mut clipped.kind {
*clip = true;
}
assert!(!moves_alike(&Node::group(NodeId(1), vec![Arc::new(clipped)]), 1));
}
#[test]
fn an_outline_moves_with_its_effect_only_on_outlines() {
// GUARDS: a top-level image or masked path took an effect that moves the outline.
use crate::import::ai::style::ArtStyle;
let effect = |id: &str, params| vectorcraft_doc::Effect { id: id.into(), params, visible: true };
let style = |e| ArtStyle { effects: vec![e], ..ArtStyle::default() };
let twist = style(effect("distort.twist", serde_json::json!({"angle": 30.0})));
let path = square(2, Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0)));
assert!(moves_with(&path, &twist));
let mut masked = Node::clone(&path);
masked.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(Node::group(NodeId(7), vec![]), true)));
assert!(!moves_with(&masked, &twist));
let image =
ImageObject { key: "a".into(), width: 1, height: 1, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None };
let image = Node::new(NodeId(4), NodeKind::Image(Box::new(image)));
let distort = style(effect("distort.freeDistort", serde_json::json!({"corners": [[0.1, 0.0], [1.1, 0.0], [1.0, 1.0], [0.0, 1.0]]})));
assert!(!moves_with(&image, &distort));
assert!(moves_with(&path, &distort));
}
}
Loaded 100 of 270 files, more files were not shown because too many files have changed in this diff. Show more