Merge remote-tracking branch 'upstream/main' into fix/3260-halftone-radius-pixels

# Conflicts:
#	crates/doc/src/limits.rs
#	crates/engine/src/cmd/fileio/tests_pdfedit.rs
#	crates/format/src/lib.rs
#	docs/target-app-parity.md
This commit is contained in:
datatimp
2026-11-04 12:30:23 -05:00
428 changed files with 30074 additions and 2532 deletions
+2
View File
@@ -7,6 +7,7 @@ mod color;
mod document;
mod pathtools;
mod pen;
mod select;
mod typetools;
use super::CommandSpec;
@@ -19,6 +20,7 @@ pub fn specs() -> Vec<CommandSpec> {
v.extend(document::specs());
v.extend(pathtools::specs());
v.extend(pen::specs());
v.extend(select::specs());
v.extend(typetools::specs());
v
}
+1 -1
View File
@@ -59,7 +59,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Find Nearest Swatch",
["Object", "Plug-ins", "Color Effects"],
None,
"{library?: a swatch library's id or name (swatch.library.list: the built-in ones, and the colour books and libraries the user saved or loaded) or \"document\" (the document's swatches; the default), color?: colour (look this colour up; default: the selection's), fill?: true, stroke?: true (the selected objects' fills and strokes, their type's and those of the objects inside them: solid colours and gradient stops, once each, the first 100), count?: 1..50 (5), ids?: [id…] (default: the selection)} list the library's colour swatches closest to each colour, closest first, by CIEDE2000 difference (ΔE; under 1 hardly tells apart, about 2 to 3 close). Tint swatches, None and Registration aren't matched → {library, colors: [{values, hex, matches: [{name, values, hex, spot, deltaE}]}]}",
"{library?: a swatch library's id or name (swatch.library.list: the built-in ones, and the colour books and libraries the user saved or loaded) or \"document\" (the document's swatches; the default), color?: colour (look this colour up, #rrggbbaa and #rgba refused; default: the selection's), fill?: true, stroke?: true (the selected objects' fills and strokes, their type's and those of the objects inside them: solid colours and gradient stops, once each, the first 100), count?: 1..50 (5), ids?: [id…] (default: the selection)} list the library's colour swatches closest to each colour, closest first, by CIEDE2000 difference (ΔE; under 1 hardly tells apart, about 2 to 3 close). Tint swatches, None and Registration aren't matched → {library, colors: [{values, hex, matches: [{name, values, hex, spot, deltaE}]}]}",
has_doc,
nearest::find
),
+14 -3
View File
@@ -1,9 +1,11 @@
//! Document Tools (`addon.document.*`), a built-in add-on: Save a Timestamped Copy writes a copy of
//! the document named with the date and time through File › Save a Copy's save; New Symbols from
//! Layers makes a symbol of each layer's art as New Symbol does; Export All Open Documents writes a
//! copy of every open document to one folder as Save a Copy does (#4920). Its submenu (Object › Plug-ins ›
//! Document Tools) is the UI's.
//! copy of every open document to one folder as Save a Copy does (#4920); Batch Trace Folder traces
//! each image of a folder and saves the results to another ([`batch_trace`], #4921). Its submenu
//! (Object › Plug-ins › Document Tools) is the UI's.
mod batch_trace;
#[cfg(test)]
mod tests;
@@ -14,7 +16,7 @@ use vectorcraft_doc::{Node, NodeId, NodeKind, SymbolRegistration};
use super::super::brushsym::{instance_in_place, normalize, place_xf, store_symbol};
use super::super::fileio::{self, SaveMode};
use super::super::{CommandSpec, bad, checked_ids_param, clock_date, cmd, date_param, has_doc, str_param, switch_or};
use super::super::{CommandSpec, always, bad, checked_ids_param, clock_date, cmd, date_param, has_doc, str_param, switch_or};
use crate::{Result, Session};
/// The most numbers (`-2`, `-3`…) tried after a timestamped name that is taken.
@@ -40,6 +42,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
export_all_open
),
cmd!(
"addon.document.batchTraceFolder",
"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)",
always,
batch_trace::batch_trace_folder
),
cmd!(
"addon.document.symbolsFromLayers",
"New Symbols from Layers",
@@ -0,0 +1,127 @@
//! Batch Trace Folder (`addon.document.batchTraceFolder`, #4921): each image in a folder is opened,
//! traced with a preset (and expanded when asked), saved into a destination folder under its own
//! name, and closed again, whether it traced or not.
use serde_json::Value;
#[cfg(not(target_arch = "wasm32"))]
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};
/// The command id.
pub(super) const ID: &str = "addon.document.batchTraceFolder";
#[cfg(target_arch = "wasm32")]
pub(super) fn batch_trace_folder(_: &mut Session, _: &Value) -> Result<Value> {
Err(bad(ID, "no file system here"))
}
#[cfg(not(target_arch = "wasm32"))]
/// The image files a batch traces, by extension.
const IMAGE_EXTS: [&str; 10] = ["png", "jpg", "jpeg", "tif", "tiff", "bmp", "gif", "webp", "psd", "psb"];
#[cfg(not(target_arch = "wasm32"))]
/// Caps on a batch (folders and MCP payloads are untrusted).
pub(super) const MAX_FILES: usize = 500;
#[cfg(not(target_arch = "wasm32"))]
const MAX_DEPTH: usize = 8;
#[cfg(not(target_arch = "wasm32"))]
const FORMATS: [&str; 5] = ["vectorcraft", "svg", "pdf", "ai", "eps"];
#[cfg(not(target_arch = "wasm32"))]
/// The image files in `folder` (and its subfolders with `deep`), sorted.
fn images(folder: &str, deep: bool, depth: usize, out: &mut Vec<String>) -> Result<()> {
if depth > MAX_DEPTH {
return Err(bad(ID, format!("folders deeper than {MAX_DEPTH} levels")));
}
let max = MAX_FILES.saturating_mul(2);
let (entries, truncated) = fileio::list_dir(folder, max)?;
// The listing is cut before it is sorted, so a cut one could skip any image: refuse it.
if truncated {
return Err(bad(ID, format!("{folder}: more than {max} files and folders")));
}
let mut subdirs = vec![];
for e in entries {
let name = e.get("name").and_then(Value::as_str).unwrap_or("");
if name.is_empty() || name.starts_with('.') {
continue;
}
let path = std::path::Path::new(folder).join(name).to_string_lossy().into_owned();
match e.get("kind").and_then(Value::as_str) {
Some("file") if IMAGE_EXTS.contains(&fileio::extension(&path).as_str()) => out.push(path),
Some("folder") if deep => subdirs.push(path),
_ => {}
}
if out.len() > MAX_FILES {
return Err(bad(ID, format!("more than {MAX_FILES} images")));
}
}
for d in subdirs {
images(&d, deep, depth + 1, out)?;
}
Ok(())
}
#[cfg(not(target_arch = "wasm32"))]
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");
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 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" };
fileio::may_read(&folder)?;
fileio::may_write(&dest)?;
let mut files = vec![];
images(&folder, bool_or(p, "includeSubdirs", false), 0, &mut files)?;
files.sort();
if files.is_empty() {
return Err(bad(ID, "no images in the folder"));
}
std::fs::create_dir_all(&dest).map_err(|e| bad(ID, format!("{dest}: {e}")))?;
let ext = fileio::save_format(Some(format), None).map_err(|e| bad(ID, e))?.extensions.first().copied().unwrap_or(format);
let active = s.active_index();
let (mut traced, mut failed, mut taken) = (vec![], vec![], Vec::<String>::new());
for path in &files {
let opened_before = s.documents().len();
let one = |s: &mut Session| -> Result<String> {
s.execute("document.open", &json!({ "path": path }))?;
s.execute("select.all", &json!({}))?;
s.execute(trace, &json!({ "preset": preset }))?;
let stem = fileio::file_stem(path);
// Names this batch already took count as taken, as do files on disk.
let free = super::free_name(&dest, &stem, ext, |o| taken.iter().any(|t| t == o) || std::path::Path::new(o).exists())
.ok_or_else(|| bad(ID, "every numbered name for the result is taken"))?;
s.execute("document.save", &json!({ "path": free, "format": format }))?;
Ok(free)
};
let result = one(s);
// The image's document closes whatever happened, so a failure leaves no tab behind.
if s.documents().len() > opened_before
&& let Some(i) = s.active_index()
{
// A just-opened image has no work to lose; if closing fails, one extra tab stays open.
let _ = s.execute("file.close", &json!({ "index": i }));
}
match result {
Ok(out) => {
taken.push(out.clone());
traced.push(json!({ "path": path, "output": out }));
}
Err(e) => failed.push(json!({ "path": path, "error": e.to_string() })),
}
}
if let Some(i) = active.filter(|i| *i < s.documents().len()) {
s.set_active(i);
}
Ok(json!({ "traced": traced, "failed": failed, "format": format }))
}
+75 -1
View File
@@ -1,5 +1,5 @@
//! Document Tools' commands: the timestamped copy's name and place with the document left as it
//! was, symbols made of layers, and bad params refused.
//! was, symbols made of layers, a folder of images traced, and bad params refused.
use std::path::{Path, PathBuf};
@@ -276,3 +276,77 @@ fn export_all_open_documents_keeps_every_page_and_artboard() {
assert!(w > 19.0 && w < 30.0, "the SVG shows the art (the square on the second artboard), not the first artboard: viewBox {view}");
let _ = std::fs::remove_dir_all(&dir);
}
/// A 24×24 white PNG with a dark (or red) square in it.
#[cfg(not(target_arch = "wasm32"))]
fn png(path: &Path, dark: bool) {
let mut img = image::RgbaImage::from_pixel(24, 24, image::Rgba([255, 255, 255, 255]));
for y in 6..18 {
for x in 6..18 {
img.put_pixel(x, y, if dark { image::Rgba([0, 0, 0, 255]) } else { image::Rgba([200, 30, 30, 255]) });
}
}
img.save(path).unwrap();
}
/// #4921: each image of the folder is traced and saved under its own name; a file that isn't an
/// image is left alone, one that can't be read is reported, and every document the batch opened
/// is closed again, the active one staying active.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn batch_trace_folder_traces_and_saves_each_image() {
const C: &str = "addon.document.batchTraceFolder";
let dir = folder("batch-trace");
let (src, out) = (dir.join("in"), dir.join("out"));
std::fs::create_dir_all(&src).unwrap();
png(&src.join("logo.png"), true);
png(&src.join("mark.png"), false);
std::fs::write(src.join("notes.txt"), "not an image").unwrap();
std::fs::write(src.join("broken.png"), b"not a png").unwrap();
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
let docs = s.documents().len();
let r = s.execute(C, &json!({"folder": src, "destinationFolder": out, "format": "svg", "expand": true})).unwrap();
assert_eq!(r["traced"].as_array().unwrap().len(), 2, "{r}");
assert_eq!(r["failed"].as_array().unwrap().len(), 1, "{r}");
assert!(r["failed"][0]["path"].as_str().unwrap().ends_with("broken.png"));
let mut names: Vec<String> = std::fs::read_dir(&out).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
names.sort();
assert_eq!(names, ["logo.svg", "mark.svg"]);
let svg = std::fs::read_to_string(out.join("logo.svg")).unwrap();
assert!(svg.contains("<path") && !svg.contains("<image"), "traced and expanded, not the image");
assert_eq!(s.documents().len(), docs, "the opened images are closed");
assert_eq!(s.active_index(), Some(0));
// Again: the taken names are numbered, nothing is replaced.
s.execute(C, &json!({"folder": src, "destinationFolder": out, "format": "svg"})).unwrap();
assert!(out.join("logo-2.svg").exists() && out.join("mark-2.svg").exists());
// Refused: no folders, an unknown preset or format, a folder without images.
for bad in [
json!({"destinationFolder": out}),
json!({"folder": src}),
json!({"folder": src, "destinationFolder": out, "preset": "No Such Preset"}),
json!({"folder": src, "destinationFolder": out, "format": "docx"}),
json!({"folder": out.join("empty"), "destinationFolder": out}),
] {
assert!(s.execute(C, &bad).is_err(), "{bad}");
}
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]
fn batch_trace_folder_refuses_a_folder_it_cannot_list_in_full() {
let dir = folder("batch-trace-big");
let src = dir.join("in");
std::fs::create_dir_all(&src).unwrap();
for i in 0..=super::batch_trace::MAX_FILES * 2 {
std::fs::write(src.join(format!("note-{i}.txt")), "").unwrap();
}
png(&src.join("logo.png"), true);
let mut s = Session::new();
let e = s.execute("addon.document.batchTraceFolder", &json!({"folder": src, "destinationFolder": dir.join("out")})).unwrap_err();
assert!(e.to_string().contains("more than"), "{e}");
assert!(!dir.join("out").exists(), "nothing traced");
let _ = std::fs::remove_dir_all(&dir);
}
+63
View File
@@ -0,0 +1,63 @@
//! 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.
#[cfg(test)]
mod tests;
use serde_json::{Value, json};
use vectorcraft_doc::NodeId;
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};
/// How Select by Artboards relates an object to the chosen artboards (`relation`).
pub const RELATIONS: [&str; 3] = ["overlap", "inside", "outside"];
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
)]
}
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");
if !RELATIONS.contains(&relation) {
return Err(bad(C, "`relation` must be overlap, inside or outside"));
}
let listed = p.get("artboards").ok_or_else(|| bad(C, "missing `artboards`"))?;
let indices = point_indices(listed).ok_or_else(|| bad(C, "`artboards` must be a list of artboard indices"))?;
if indices.is_empty() {
return Err(bad(C, "choose at least one artboard"));
}
let st = s.doc()?;
let rects =
indices.iter().map(|i| st.doc.artboards.get(*i).map(|a| a.rect)).collect::<Option<Vec<_>>>().ok_or_else(|| bad(C, "no such artboard"))?;
let symbols = st.doc.symbol_boxes();
let ids: Vec<NodeId> = selectable(&st.doc, st.isolation)
.into_iter()
.filter(|id| {
let Some(n) = st.doc.node(*id) else { return false };
match relation {
"inside" => n.geometric_bounds_with(&symbols).is_some_and(|b| {
rects.iter().any(|r| {
vectorcraft_doc::artboard_holds(*r, Point::new(b.x0, b.y0)) && vectorcraft_doc::artboard_holds(*r, Point::new(b.x1, b.y1))
})
}),
"outside" => !rects.iter().any(|r| on_artboard(n, &symbols, *r)),
_ => rects.iter().any(|r| on_artboard(n, &symbols, *r)),
}
})
.collect();
s.select(|_, sel| sel.set(ids))?;
Ok(json!({ "count": s.doc()?.selection.objects.len() }))
}
@@ -0,0 +1,128 @@
//! Select by Artboards.
use serde_json::{Value, json};
use vectorcraft_doc::NodeId;
use crate::Session;
const C: &str = "addon.select.byArtboards";
/// A document with three 100 × 100 artboards in a row, 50 pt apart: 0 at x 0, 1 at x 150, 2 at x 300.
fn three_boards() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
for x in [150, 300] {
s.execute("artboard.new", &json!({"x": x, "y": 0, "width": 100, "height": 100})).unwrap();
}
s
}
fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId {
NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap())
}
fn pick(s: &mut Session, p: Value) -> Vec<NodeId> {
s.execute("select.none", &json!({})).unwrap();
let r = s.execute(C, &p).unwrap();
let mut ids = s.doc().unwrap().selection.objects.clone();
assert_eq!(r["count"], json!(ids.len()));
ids.sort();
ids
}
#[test]
fn selects_by_overlap_inside_and_outside_several_artboards() {
let mut s = three_boards();
let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0); // inside 0
let ab = rect(&mut s, 90.0, 40.0, 80.0, 20.0); // across 0 and 1
let b = rect(&mut s, 160.0, 10.0, 20.0, 20.0); // inside 1
let c = rect(&mut s, 310.0, 10.0, 20.0, 20.0); // inside 2
let off = rect(&mut s, 0.0, 200.0, 20.0, 20.0); // on no board
let edge = rect(&mut s, 0.0, 0.0, 100.0, 100.0); // flush with board 0
let want = |mut v: Vec<NodeId>| {
v.sort();
v
};
assert_eq!(pick(&mut s, json!({"artboards": [0, 1]})), want(vec![a, ab, b, edge]));
assert_eq!(pick(&mut s, json!({"artboards": [0, 1], "relation": "overlap"})), want(vec![a, ab, b, edge]));
// Wholly within one board, edges included; straddling two boards is not inside either.
assert_eq!(pick(&mut s, json!({"artboards": [0, 1], "relation": "inside"})), want(vec![a, b, edge]));
assert_eq!(pick(&mut s, json!({"artboards": [0, 1], "relation": "outside"})), want(vec![c, off]));
assert_eq!(pick(&mut s, json!({"artboards": [2], "relation": "outside"})), want(vec![a, ab, b, off, edge]));
// One board does what All on Active Artboard does.
for i in 0..3u64 {
s.execute("select.allOnArtboard", &json!({"artboard": i})).unwrap();
let mut on = s.doc().unwrap().selection.objects.clone();
on.sort();
assert_eq!(pick(&mut s, json!({"artboards": [i]})), on, "board {i}");
}
// A board listed twice counts once.
assert_eq!(pick(&mut s, json!({"artboards": [2, 2]})), vec![c]);
}
#[test]
fn hidden_locked_and_isolated_art_follow_select_all() {
let mut s = three_boards();
let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
let hidden = rect(&mut s, 40.0, 10.0, 20.0, 20.0);
let locked = rect(&mut s, 70.0, 10.0, 20.0, 20.0);
let far = rect(&mut s, 0.0, 300.0, 20.0, 20.0);
s.execute("object.setProps", &json!({"ids": [hidden.0], "visible": false})).unwrap();
s.execute("object.setProps", &json!({"ids": [locked.0], "locked": true})).unwrap();
assert_eq!(pick(&mut s, json!({"artboards": [0]})), vec![a]);
assert_eq!(pick(&mut s, json!({"artboards": [0], "relation": "outside"})), vec![far]);
// Art held by a locked artboard is left out.
s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap();
assert_eq!(pick(&mut s, json!({"artboards": [0]})), vec![]);
s.execute("artboard.setProps", &json!({"index": 0, "locked": false})).unwrap();
// In isolation mode only the isolated group's objects are looked at.
let b = rect(&mut s, 20.0, 50.0, 10.0, 10.0);
s.execute("select.none", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("object.isolate", &json!({"id": g})).unwrap();
let mut both = vec![a, b];
both.sort();
assert_eq!(pick(&mut s, json!({"artboards": [0], "relation": "inside"})), both);
assert_eq!(pick(&mut s, json!({"artboards": [1]})), vec![]);
}
#[test]
fn bad_params_are_errors_and_leave_the_selection() {
let mut s = three_boards();
let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
for p in [
json!({}),
json!({"artboards": []}),
json!({"artboards": [3]}),
json!({"artboards": [-1]}),
json!({"artboards": [0.5]}),
json!({"artboards": "0"}),
json!({"artboards": [0], "relation": "near"}),
json!({"artboards": [0], "relation": 1}),
json!({"artboards": [0], "relatoin": "inside"}),
] {
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
assert!(s.execute(C, &p).is_err(), "{p}");
assert_eq!(s.doc().unwrap().selection.objects, vec![a], "{p}");
}
}
#[test]
fn a_symbol_instance_is_measured_by_its_art() {
// The symbol's art, (100, 60) to (140, 80), drawn 50 pt up and left: (50, 10) to (90, 30), on
// the 200 × 120 artboard, while the 20 × 20 square around the instance's origin lies off it.
let svg = r##"<svg xmlns="http://www.w3.org/2000/svg" width="200" height="120"><defs><symbol id="Far"><rect x="100" y="60" width="40" height="20" fill="#f00"/></symbol></defs><use href="#Far" x="-50" y="-50"/></svg>"##;
let mut s = Session::new();
s.execute("document.open", &json!({"name": "far.svg", "dataBase64": vectorcraft_format::base64_encode(svg.as_bytes())})).unwrap();
let mut instance = None;
s.doc().unwrap().doc.walk(|n| {
if matches!(n.kind, vectorcraft_doc::NodeKind::SymbolInstance { .. }) {
instance = Some(n.id);
}
});
let instance = instance.unwrap();
assert_eq!(pick(&mut s, json!({"artboards": [0]})), vec![instance]);
assert_eq!(pick(&mut s, json!({"artboards": [0], "relation": "inside"})), vec![instance]);
assert_eq!(pick(&mut s, json!({"artboards": [0], "relation": "outside"})), vec![]);
}
+28 -4
View File
@@ -46,7 +46,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Text Tweaker",
["Object", "Plug-ins", "Type Tools"],
None,
"{attribute?: \"size\" (pt 0.1..1296) | \"baselineShift\" (pt −1296..1296) | \"rotation\" (° −360..360) | \"hScale\" (% 1..10000) | \"vScale\" (% 1..10000) | \"tracking\" (1/1000 em −1000..10000) | \"leading\" (pt 0.1..5000) | \"strokeWidth\" (pt 0..1000) (\"size\"), from?: the first character's value, to?: the last character's value (each in the attribute's units and range; defaults: size 12 → 36, baselineShift 0 → 12, rotation 0 → 30, hScale and vScale 100 → 150, tracking 0 → 200, leading 12 → 36, strokeWidth 0 → 2), shape?: \"straight\" (an even ramp) | \"ease\" (slow at both ends) | \"bow\" (from at both ends, rising smoothly to `to` in the middle) | \"spike\" (from at both ends, straight up to `to` in the middle) | \"random\" (each character anywhere from `from` to `to`) (\"straight\"), seed?: whole number (0; random: the same seed and text give the same values), skipSpaces?: true (spaces and line breaks keep their values and don't count), id?, start?: byte, end?: byte, ids?: [id…] (instead of id)} give the characters one character attribute letter by letter, from `from` to `to` along the shape, as the Character panel sets it, as one undo step; the text stays live and editable. The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: all its text), else every selected type object; each object gets its own ramp. Stroke weight only shows on characters with a stroke → {count (characters changed), ids}",
"{attribute?: \"size\" (pt 0.1..1296) | \"baselineShift\" (pt −1296..1296) | \"rotation\" (° −360..360) | \"hScale\" (% 1..10000) | \"vScale\" (% 1..10000) | \"tracking\" (1/1000 em −1000..10000) | \"leading\" (pt 0.1..5000) | \"strokeWidth\" (pt 0..1000) (\"size\"), from?: the first character's value, to?: the last character's value (each in the attribute's units and range; defaults: size 12 → 36, baselineShift 0 → 12, rotation 0 → 30, hScale and vScale 100 → 150, tracking 0 → 200, leading 12 → 36, strokeWidth 0 → 2), shape?: \"straight\" (an even ramp) | \"ease\" (slow at both ends) | \"bow\" (from at both ends, rising smoothly to `to` in the middle) | \"spike\" (from at both ends, straight up to `to` in the middle) | \"random\" (each character anywhere from `from` to `to`) (\"straight\"), seed?: whole number (0; random: the same seed and text give the same values), skipSpaces?: true (spaces and line breaks keep their values and don't count), id?, start?: byte, end?: byte (range endpoints inside a character round down to its start), ids?: [id…] (instead of id)} give the characters one character attribute letter by letter, from `from` to `to` along the shape, as the Character panel sets it, as one undo step; the text stays live and editable. The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: all its text), else every selected type object; each object gets its own ramp. Stroke weight only shows on characters with a stroke → {count (characters changed), ids}",
has_selection,
text_tweaker
)]
@@ -93,25 +93,49 @@ fn text_tweaker(s: &mut Session, p: &Value) -> Result<Value> {
let ranges = type_ranges(s, p, C, |text, _| Some((0, text.len())))?;
// Each object's changed characters: (byte, its change), worked out before the edit.
let mut plans: Vec<(NodeId, Vec<(usize, CharChange)>)> = vec![];
let mut count = 0;
let (mut seen, mut count) = (0, 0);
for (id, a, b, _) in ranges {
let t = text_ref(s, id)?;
let text = t.plain_text();
let (a, b) = (edit::floor_char(&text, a), edit::floor_char(&text, b));
let chars: Vec<usize> =
text.char_indices().filter(|&(i, c)| (a..b).contains(&i) && !(skip && (c.is_whitespace() || c.is_control()))).map(|(i, _)| i).collect();
count += chars.len();
if count > MAX_CHARS {
seen += chars.len();
if seen > MAX_CHARS {
return Err(bad(C, format!("too many characters: at most {MAX_CHARS}")));
}
// Each run's end byte, to find the style a character has now.
let ends: Vec<usize> = t
.runs
.iter()
.scan(0, |off, r| {
*off += r.text.len();
Some(*off)
})
.collect();
let n = chars.len();
let mut changes = Vec::with_capacity(n);
let mut run = 0;
for (i, at) in chars.into_iter().enumerate() {
let random = if shape == "random" { unit(&mut rng) } else { 0.0 };
let value = from + (to - from) * amount(shape, i, n, random);
let mut change = CharChange::parse(&json!({ key: value }), C, &setup)?;
change.localize(&t, C)?;
while ends.get(run).is_some_and(|&e| e <= at) {
run += 1;
}
// A character that already has the value is left out, so a run that changes nothing
// makes no step.
if let Some(r) = t.runs.get(run) {
let mut style = r.style.clone();
change.apply(&mut style);
if style == r.style {
continue;
}
}
changes.push((at, change));
}
count += changes.len();
if !changes.is_empty() {
plans.push((id, changes));
}
@@ -62,7 +62,8 @@ fn a_straight_ramp_sizes_each_letter_and_skips_spaces() {
select(&mut s, &[id]);
let n = steps(&s);
let out = s.execute(C, &json!({"attribute": "size", "from": 10, "to": 40})).unwrap();
assert_eq!(out, json!({"count": 4, "ids": [id.0]}));
// `b` is 20 pt already: three characters change.
assert_eq!(out, json!({"count": 3, "ids": [id.0]}));
assert_eq!(steps(&s), n + 1, "one undo step");
let sizes: Vec<(char, f64)> = styles(&s, id).into_iter().map(|(c, st)| (c, st.size)).collect();
assert_eq!(sizes, [('a', 10.0), ('b', 20.0), (' ', 20.0), ('c', 30.0), ('d', 40.0)], "the space keeps its size");
@@ -108,7 +109,8 @@ fn each_object_gets_its_own_ramp() {
let (a, b) = (text(&mut s, "abc"), text(&mut s, "de"));
select(&mut s, &[a, b]);
let out = s.execute(C, &json!({"attribute": "rotation", "from": 0, "to": 30})).unwrap();
assert_eq!(out["count"], json!(5));
// Each first character is upright already.
assert_eq!(out["count"], json!(3));
let turns = |id| styles(&s, id).iter().map(|(_, st)| st.rotation).collect::<Vec<_>>();
assert_eq!((turns(a), turns(b)), (vec![0.0, 15.0, 30.0], vec![0.0, 30.0]));
}
@@ -122,6 +124,16 @@ fn a_range_changes_only_its_characters() {
assert_eq!(tracking, [0.0, 100.0, 200.0, 300.0, 0.0]);
}
#[test]
fn a_range_inside_a_multibyte_character_uses_character_boundaries() {
let mut s = session();
let id = text(&mut s, "éx");
let out = s.execute(C, &json!({"id": id.0, "start": 1, "end": 2, "attribute": "tracking", "from": 100, "to": 300})).unwrap();
assert_eq!(out["count"], 1);
let tracking: Vec<f64> = styles(&s, id).iter().map(|(_, st)| st.tracking).collect();
assert_eq!(tracking, [100.0, 0.0]);
}
#[test]
fn random_values_stay_in_range_and_repeat_with_the_seed() {
let mut s = session();
@@ -161,6 +173,19 @@ fn empty_text_and_only_spaces_change_nothing() {
assert_eq!(steps(&s), n, "no step");
}
#[test]
fn characters_that_already_have_the_value_are_left_out() {
let mut s = session();
let id = text(&mut s, "abc");
select(&mut s, &[id]);
let p = json!({"attribute": "rotation", "from": 0, "to": 30});
// The first character already has 0°.
assert_eq!(s.execute(C, &p).unwrap(), json!({"count": 2, "ids": [id.0]}));
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
assert_eq!(s.execute(C, &p).unwrap(), json!({"count": 0, "ids": []}), "again: nothing to change");
assert_eq!((s.doc().unwrap().doc.clone(), steps(&s)), (before, n), "no step");
}
#[test]
fn bad_params_are_refused_without_a_change() {
let mut s = session();
@@ -179,6 +204,9 @@ fn bad_params_are_refused_without_a_change() {
json!({"seed": -1}),
json!({"skipSpaces": "yes"}),
json!({"ids": [999_999]}),
json!({"id": id.0, "start": -1}),
json!({"id": id.0, "start": 1, "end": 1.5}),
json!({"id": id.0, "end": "2"}),
] {
assert!(s.execute(C, &p).is_err(), "{p}");
assert_eq!(s.doc().unwrap().doc, before, "{p}");
+117 -36
View File
@@ -45,7 +45,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add New Fill",
["Window", "Appearance"],
Some("Cmd+/"),
"{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row (a copy of its top fill; type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids` and no `target: \"contents\"`, the new fill is a copy of that row, right above it, and becomes the active row",
"{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row",
has_doc,
|s, p| add_item(s, p, true)
),
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add New Stroke",
["Window", "Appearance"],
Some("Cmd+Alt+/"),
"{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row (a copy of its top stroke, else the default stroke)",
"{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt",
has_doc,
|s, p| add_item(s, p, false)
),
@@ -178,6 +178,23 @@ pub(crate) struct ActiveItem {
}
impl Session {
/// The method returns explicit target parameters and the selected appearance effect list.
pub fn appearance_effect_target(&self, params: &Value) -> Option<(Value, &[vectorcraft_doc::Effect])> {
let mut ids = appearance_targets(self, params).ok()?;
let item = item_target(self, params, "effect.apply").ok()?;
let anchor = item.anchor(self, &ids);
let node = self.active()?.doc.node(*ids.get(anchor)?)?;
let at = item.effects_item(&node.appearance, "effect.apply").ok()?;
let effects = node.appearance.effects_at(at)?;
ids.swap(0, anchor);
let ids: Vec<u64> = ids.into_iter().map(|id| id.0).collect();
let aligned = match item {
ItemTarget::Item { aligned, .. } => aligned,
ItemTarget::Top => aligned(params),
};
Some((json!({"ids": ids, "item": at, "aligned": aligned}), effects.as_slice()))
}
/// The Appearance panel's active fill/stroke: a paint-order index into the first selected
/// object's stack, while the selection it was chosen for is unchanged.
pub fn appearance_item(&self) -> Option<usize> {
@@ -340,11 +357,23 @@ pub(crate) fn appearances_differ(d: &vectorcraft_doc::Document, ids: &[NodeId])
/// Indices `idx` of the first target's items (aligned with `aligned`) in each of `ids`: the first
/// target's own, and in each other one the items equal to them there (see [`SharedStack`]), each
/// index on its own: one the targets don't share is left out of the others (never taken as the
/// same index there). Not aligned, or one target: the same indices in each.
/// index and each target on its own: an index a target doesn't share with the first is left out
/// of that target (never taken as the same index there), whatever the other targets have. Not
/// aligned, or one target: the same indices in each.
pub(crate) fn items_per_target(d: &vectorcraft_doc::Document, ids: &[NodeId], idx: &[usize], aligned: bool) -> Vec<Vec<usize>> {
match shared_stack(d, ids).filter(|_| aligned) {
Some(sh) => (0..ids.len()).map(|k| if k == 0 { idx.to_vec() } else { idx.iter().filter_map(|i| sh.item_in(*i, k)).collect() }).collect(),
let aps: Option<Vec<&Appearance>> = ids.iter().map(|id| d.node(*id).map(|n| &*n.appearance)).collect();
match aps.filter(|aps| aligned && aps.len() >= 2) {
Some(aps) => aps
.iter()
.enumerate()
.map(|(k, ap)| match aps.first() {
Some(first) if k > 0 => {
let sh = SharedStack::of(&[*first, *ap]);
idx.iter().filter_map(|i| sh.item_in(*i, 1)).collect()
}
_ => idx.to_vec(),
})
.collect(),
None => vec![idx.to_vec(); ids.len()],
}
}
@@ -490,8 +519,8 @@ fn set_active_item(s: &mut Session, p: &Value) -> Result<Value> {
fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
let ids = require_targets(s, p, if fill { "appearance.addFill" } else { "appearance.addStroke" })?;
let defaults = s.paint.clone();
// The panel's active Fill row, when the new fill goes on the selection: the new fill is a copy
// of that row, right above it in each target that has it (others get a copy of their top fill).
// The panel's active Fill row, when the new fill goes on the selection: the new fill takes that
// row's paint, right above it in each target that has it (others take their top fill's paint).
// Where the new item went in on the active item's object, when it is an image.
let active = s.active_appearance_item.as_ref().and_then(|a| a.objects.first().copied());
// The active row is a row of the active object's stack, which need not come first in `ids`
@@ -514,6 +543,7 @@ fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
}
_ => vec![None; ids.len()],
};
let before = s.doc()?.doc.clone();
let mut inserted = None;
// Where the new fill went in on the active item's object, when it went above the active row.
let mut above = None;
@@ -529,8 +559,9 @@ fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
}
continue;
}
// A copy of the top fill (stroke); without one, type's characters' and otherwise the
// default paint, so a new fill on a group or type shows.
// The top fill's (stroke's) paint; without one, type's characters' and otherwise the
// default paint, so a new fill on a group or type shows. A new stroke takes the top
// stroke's weight when that stroke has paint, at least 1 pt.
let paint = match (n.appearance.paint_at(None, fill), &n.kind) {
(Some(p), _) => p.clone(),
(None, NodeKind::Text(_)) => super::paint::proxy_paint(n, !fill, None),
@@ -560,6 +591,7 @@ fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
}
}
}
super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids));
Ok(())
})?;
// A fill added above the active row becomes the active row; otherwise the rows above the new
@@ -578,12 +610,28 @@ fn clear_appearance(s: &mut Session, p: &Value) -> Result<Value> {
clear(n);
}
}
Ok(count_changed(d, &before, &ids))
let kept = super::graph::capture_series_opacity(d, &both_kinds(&ids));
Ok(count_changed(d, &before, &ids) + usize::from(kept))
})?;
s.active_appearance_item = None;
ok()
}
/// Each of `ids` with both kinds of row (fill, then stroke), for [`super::graph::capture_series_opacity`] after an
/// edit that replaces whole stacks.
fn both_kinds(ids: &[NodeId]) -> Vec<(NodeId, bool)> {
ids.iter().flat_map(|id| [(*id, true), (*id, false)]).collect()
}
/// Each of `ids` with each kind of row (fill `true`, stroke `false`) whose topmost row has another opacity in `d` than
/// in `before` (no row counts as opaque), for [`super::graph::capture_series_opacity`].
fn top_opacity_changed(before: &vectorcraft_doc::Document, d: &vectorcraft_doc::Document, ids: &[NodeId]) -> Vec<(NodeId, bool)> {
let top = |d: &vectorcraft_doc::Document, id: NodeId, fill: bool| {
d.node(id).and_then(|n| n.appearance.items.iter().rev().find(|it| it.is_fill() == fill).map(AppearanceItem::opacity)).unwrap_or(1.0)
};
ids.iter().flat_map(|id| [(*id, true), (*id, false)]).filter(|(id, fill)| top(before, *id, *fill) != top(d, *id, *fill)).collect()
}
/// Clear Appearance on `n`: no fill, no stroke, and the object's Opacity row back to Default. A
/// group keeps no fill or stroke rows of its own.
fn clear(n: &mut Node) {
@@ -619,7 +667,9 @@ fn transfer(s: &mut Session, p: &Value) -> Result<Value> {
clear(n);
(n.isolate, n.knockout, n.knockout_shape) = (false, Default::default(), false);
}
Ok(count_changed(d, &before, &[source, target]))
let changed = if copy { vec![target] } else { vec![source, target] };
let kept = super::graph::capture_series_opacity(d, &both_kinds(&changed));
Ok(count_changed(d, &before, &[source, target]) + usize::from(kept))
})?;
s.active_appearance_item = None;
Ok(json!({ "source": source.0, "target": target.0 }))
@@ -672,7 +722,8 @@ fn reduce_basic(s: &mut Session, p: &Value) -> Result<Value> {
}
}
}
Ok(count_changed(d, &before, &ids))
let kept = super::graph::capture_series_opacity(d, &both_kinds(&ids));
Ok(count_changed(d, &before, &ids) + usize::from(kept))
})?;
s.active_appearance_item = None;
ok()
@@ -694,9 +745,14 @@ fn set_item(s: &mut Session, p: &Value) -> Result<Value> {
let before = s.doc()?.doc.clone();
let per = items_per_target(&before, &ids, &[idx], aligned(p));
super::overprint::edit_counted(s, "Appearance", |d| {
let mut edited = Vec::new();
for (id, at) in ids.iter().zip(&per) {
let Some(&idx) = at.first() else { continue };
let Some(n) = d.node_mut(*id) else { continue };
let items = &n.appearance.items;
if let Some(fill) = items.get(idx).map(AppearanceItem::is_fill).filter(|f| items.iter().rposition(|it| it.is_fill() == *f) == Some(idx)) {
edited.push((*id, fill));
}
if p.get("weight").is_none()
&& let Some(pa) = &paint
{
@@ -727,7 +783,9 @@ fn set_item(s: &mut Session, p: &Value) -> Result<Value> {
*vis = v;
}
}
Ok(count_changed(d, &before, &ids))
// The graph keeps an opacity set on the topmost fill or stroke of its series art for when it is drawn again.
let kept = p.get("opacity").and_then(Value::as_f64).is_some() && super::graph::capture_series_opacity(d, &edited);
Ok(count_changed(d, &before, &ids) + usize::from(kept))
})?;
if let Some(pa) = &paint {
s.remember_paint(pa);
@@ -770,7 +828,8 @@ fn remove_item(s: &mut Session, p: &Value) -> Result<Value> {
}
}
}
Ok(count_changed(d, &before, &ids))
let kept = super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids));
Ok(count_changed(d, &before, &ids) + usize::from(kept))
})?;
s.remap_appearance_item(&ids, |a| (!idx.contains(&a)).then(|| a - idx.iter().filter(|i| **i < a).count()));
ok()
@@ -796,7 +855,8 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
if aligned(p) && to.is_some() && shared_stack(&s.doc()?.doc, &ids).is_some() {
return Err(bad(C, "`to` takes the rows of one object's stack, not aligned rows"));
}
let per = items_per_target(&s.doc()?.doc, &ids, &idx, aligned(p));
let before = s.doc()?.doc.clone();
let per = items_per_target(&before, &ids, &idx, aligned(p));
s.edit("Duplicate Item", |d, _| {
let mut any = false;
for (id, idx) in ids.iter().zip(&per) {
@@ -834,7 +894,11 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
}
}
}
if any { Ok(()) } else { Err(bad(C, format!("no item at index {}", idx[0]))) }
if !any {
return Err(bad(C, format!("no item at index {}", idx[0])));
}
super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids));
Ok(())
})?;
// Rows at or above each copy move up by one (by the block, for copies placed at `to`).
let m = idx.len();
@@ -893,7 +957,8 @@ fn move_item(s: &mut Session, p: &Value) -> Result<Value> {
n.appearance.set_contents_at(k);
}
}
Ok(count_changed(d, &before, &ids))
let kept = super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids));
Ok(count_changed(d, &before, &ids) + usize::from(kept))
})?;
// The moved row stays the active one; the rows it passed shift by one.
s.remap_appearance_item(&ids, |a| {
@@ -936,7 +1001,8 @@ fn move_items(s: &mut Session, p: &Value, ids: &[NodeId], to: usize) -> Result<V
n.appearance.set_contents_at(k);
}
}
Ok(count_changed(d, &before, ids))
let kept = super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, ids));
Ok(count_changed(d, &before, ids) + usize::from(kept))
})?;
let m = idx.len();
let landed = first_landed.unwrap_or(to);
@@ -1034,15 +1100,25 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
s.eyedropper_sample = Some(node);
}
let range = range.filter(|(id, _, _)| targets.contains(id));
// The highlighted characters' type objects and ranges: after Select All in threaded text, all
// the text of every frame of the story.
let story = super::textedit::editing_story(s);
let ranges: Vec<(NodeId, Option<(usize, usize)>)> = match range {
Some((id, _, _)) if story.contains(&id) => story.iter().map(|f| (*f, None)).collect(),
Some((id, start, end)) => vec![(id, Some((start, end)))],
None => vec![],
};
// Character styles cannot represent object transparency. Refuse before even changing
// paint defaults; applying it to the object would also alter the unselected characters.
if let Some((id, _, _)) = range.filter(|_| attrs.appearance.transparency) {
let target = s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?;
if picked.opacity != 1.0 || picked.blend != BlendMode::Normal || target.opacity != 1.0 || target.blend != BlendMode::Normal {
return Err(bad(
C,
"object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object",
));
if attrs.appearance.transparency {
for (id, _) in &ranges {
let target = s.doc()?.doc.node(*id).ok_or(EngineError::NoNode(*id))?;
if picked.opacity != 1.0 || picked.blend != BlendMode::Normal || target.opacity != 1.0 || target.blend != BlendMode::Normal {
return Err(bad(
C,
"object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object",
));
}
}
}
if !reverse {
@@ -1051,19 +1127,23 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
if targets.is_empty() || attrs.is_empty() {
return Ok(json!({ "ids": [] }));
}
if let Some((id, start, end)) = range {
if !ranges.is_empty() {
let ids: Vec<NodeId> = ranges.iter().map(|(f, _)| *f).collect();
let before = s.doc()?.doc.clone();
super::overprint::edit_counted(s, "Eyedropper", |d| {
let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(id)) };
let placed = picked.placed(Some(t.local_bounds()));
vectorcraft_text::edit::style_range(&mut t.runs, start, end, |st| picked.run(st, &placed, &attrs));
if let Some((_, para)) = picked.text.as_ref().filter(|_| attrs.paragraph) {
t.edit_paras(Some(t.paragraphs_in(start, end)), |p| *p = para.clone());
for &(id, range) in &ranges {
let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(id)) };
let (start, end) = range.unwrap_or((0, vectorcraft_text::edit::runs_len(&t.runs)));
let placed = picked.placed(Some(t.local_bounds()));
vectorcraft_text::edit::style_range(&mut t.runs, start, end, |st| picked.run(st, &placed, &attrs));
if let Some((_, para)) = picked.text.as_ref().filter(|_| attrs.paragraph) {
t.edit_paras(Some(t.paragraphs_in(start, end)), |p| *p = para.clone());
}
super::typecmd::refresh_bounds(t);
}
super::typecmd::refresh_bounds(t);
Ok(count_changed(d, &before, &[id]))
Ok(count_changed(d, &before, &ids))
})?;
return Ok(json!({ "ids": [id.0] }));
return Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }));
}
// When every target comes out as it was, the document and its undo history stay as they are.
let before = s.doc()?.doc.clone();
@@ -1073,7 +1153,8 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
picked.apply(n, &attrs, append);
}
}
Ok(count_changed(d, &before, &targets))
let kept = super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &targets));
Ok(count_changed(d, &before, &targets) + usize::from(kept))
})?;
Ok(json!({ "ids": targets.iter().map(|i| i.0).collect::<Vec<_>>() }))
}
+6 -4
View File
@@ -19,7 +19,7 @@ use super::edit::{outermost, selected_roots};
use super::pathops::{remove_each, separate};
use super::swatch::{anchor, names_param};
use super::{
CommandSpec, Result, Session, bad, check_numbers, cmd, color_value, find_command, has_doc, has_selection, id_param, named_ids, number_or, ok,
CommandSpec, Result, Session, bad, check_numbers, cmd, color_param, find_command, has_doc, has_selection, id_param, named_ids, number_or, ok,
str_param, switch_or,
};
use crate::EngineError;
@@ -35,7 +35,9 @@ use brushes::{
};
use dynamic::{symbol_instance_reset, symbol_instance_set_appearance};
use symbols::selected_instances;
pub(crate) use symbols::{instance_in_place, natural_size, normalize, place_xf, set_natural_size, store_symbol};
pub(crate) use symbols::{
expand_instances_under, expandable_instances, instance_in_place, natural_size, normalize, place_xf, set_natural_size, store_symbol,
};
use symbols::{
symbol_adjust, symbol_break_link, symbol_delete, symbol_duplicate, symbol_list, symbol_new, symbol_options, symbol_place, symbol_replace,
symbol_select_instances, symbol_set_current, symbol_spray, symbol_unused, symbol_update,
@@ -201,7 +203,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Break Link to Symbol",
[],
None,
"{ids?|id?} expand selected instances into plain art (with their appearance changes to a dynamic symbol), placed through the symbol's 9-slice guides when it has them → {ids}",
"{ids?|id?} expand selected instances into plain art (with their appearance changes to a dynamic symbol), placed through the symbol's 9-slice guides when it has them, with the instance's opacity mask → {ids}",
has_selection,
symbol_break_link
),
@@ -302,7 +304,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Symbolism Tool",
[],
None,
"{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y]…], radius?: 40, intensity?: 1..10 (5), alt?: bool, color?, keepModel?: bool (as paint.setFill), style?: name} adjust instances near the points (selection, else all) → {count}",
"{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y]…], radius?: 40, intensity?: 1..10 (5), alt?: bool, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} adjust instances near the points (selection, else all) → {count}",
has_doc,
symbol_adjust
),
+73 -6
View File
@@ -1,7 +1,7 @@
use super::dynamic::{fit_overrides, type_id, type_param};
use super::{
Affine, AppearanceItem, Arc, CURRENT_SYMBOL, Color, Document, EngineError, FillLayer, HALF, Node, NodeId, NodeKind, Paint, Point, Result,
SIZES_KEY, Session, Symbol, SymbolExportType, SymbolNineSlice, SymbolRegistration, Value, Vec2, bad, brush, color_value, ids_json, json,
SIZES_KEY, Session, Symbol, SymbolExportType, SymbolNineSlice, SymbolRegistration, Value, Vec2, bad, brush, color_param, ids_json, json,
name_param, number_or, ok, remove_each, roots, selection_art, separate, set_unknown, str_param, switch_or,
};
@@ -341,7 +341,8 @@ pub(super) fn symbol_place(s: &mut Session, p: &Value) -> Result<Value> {
/// The plain art of instance `inst` in document space (fresh ids), with the instance's own
/// appearance changes to a dynamic symbol's art when `own`, placed through its symbol's 9-slice
/// guides when it has them.
/// guides when it has them. The instance's opacity mask goes on the art, or on a group around it
/// when the art has a mask of its own.
fn expanded_instance(d: &mut Document, inst: &Node, own: bool) -> Option<Node> {
let NodeKind::SymbolInstance { symbol, xf } = &inst.kind else { return None };
let sym = d.symbols.iter().find(|s| &s.name == symbol)?;
@@ -361,13 +362,21 @@ fn expanded_instance(d: &mut Document, inst: &Node, own: bool) -> Option<Node> {
art.opacity *= inst.opacity;
art.blend = inst.blend;
}
if let Some(mask) = &inst.extras().mask {
if art.extras().mask.is_some() {
let id = d.alloc_id();
art = Node::group(id, vec![Arc::new(art)]);
}
art.extras_mut().mask = Some(mask.clone());
}
Some(art)
}
/// The most objects [`expanded_instance`] makes of instance `inst` in `d` (`own` as there): its
/// symbol's object count with the art of its opacity masks, or
/// [`vectorcraft_doc::NineSliceMap::most_placed`] when it is placed through 9-slice guides, plus
/// the group that opacity or a blending mode adds. 0 for any other object.
/// the group that opacity, a blending mode or the instance's opacity mask adds, plus the art of
/// the instance's opacity mask. 0 for any other object.
fn expanded_bound(d: &Document, inst: &Node, own: bool) -> u64 {
let NodeKind::SymbolInstance { symbol, xf } = &inst.kind else { return 0 };
let Some(sym) = d.symbols.iter().find(|s| &s.name == symbol) else { return 0 };
@@ -378,7 +387,8 @@ fn expanded_bound(d: &Document, inst: &Node, own: bool) -> u64 {
None if dynamic => vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, inst).count_with_masks() as u64,
None => sym.art.count_with_masks() as u64,
};
most.saturating_add(1)
let mask = inst.extras().mask.as_ref().map_or(0, |m| m.art.count_with_masks() as u64);
most.saturating_add(1).saturating_add(mask)
}
/// Replace instances `ids` with their art ([`expanded_instance`], `own` as there). Returns the
@@ -402,7 +412,64 @@ fn break_links(d: &mut Document, ids: &[NodeId], own: bool) -> Result<Vec<NodeId
Ok(out)
}
/// How many objects [`break_links`] may make at once.
/// Object › Expand: the symbol instances under `roots` of `d` ([`expandable_instances`]) replaced
/// by their art, as Break Link places it, each keeping the instance's id and place. The instances
/// that art holds stay instances. A hidden or locked instance's art stays hidden or locked. When
/// the instances together would make more than [`MAX_EXPAND_NODES`] objects, all of them stay
/// instances. Returns whether any instance was expanded.
pub(crate) fn expand_instances_under(d: &mut Document, roots: &[NodeId]) -> Result<bool> {
let ids = expandable_instances(d, roots);
let total = ids.iter().filter_map(|id| d.node(*id)).fold(0u64, |sum, n| sum.saturating_add(expanded_bound(d, n, true)));
if total > MAX_EXPAND_NODES as u64 {
return Ok(false);
}
let mut any = false;
for id in ids {
let Some(inst) = d.node(id).cloned() else { continue };
let Some(mut art) = expanded_instance(d, &inst, true) else { continue };
let (par, idx, _) = d.position(id).ok_or(EngineError::NoNode(id))?;
art.id = id;
art.visible &= inst.visible;
art.locked |= inst.locked;
d.remove(id)?;
d.insert(par, idx, art)?;
any = true;
}
Ok(any)
}
/// The symbol instances under `roots` of `d` that Object › Expand turns into their art: those
/// without effects (Expand Appearance bakes the others), with no effects on their fills and
/// strokes, not in perspective, and whose symbol `d` holds. The instances in blends, repeats and
/// Intertwine groups are left to Expand, which turns those into plain groups.
pub(crate) fn expandable_instances(d: &Document, roots: &[NodeId]) -> Vec<NodeId> {
fn collect(d: &Document, n: &Node, out: &mut Vec<NodeId>) {
match &n.kind {
NodeKind::SymbolInstance { symbol, .. } => {
if n.appearance.effects.is_empty()
&& n.appearance.items.iter().all(|i| i.effects().is_empty())
&& n.projection().is_none()
&& d.symbols.iter().any(|s| &s.name == symbol)
{
out.push(n.id);
}
}
NodeKind::Blend { .. } | NodeKind::Repeat(_) | NodeKind::Intertwine { .. } => {}
_ => {
for c in n.children().into_iter().flatten() {
collect(d, c, out);
}
}
}
}
let mut out = vec![];
for n in roots.iter().filter_map(|r| d.node(*r)) {
collect(d, n, &mut out);
}
out
}
/// How many objects [`break_links`] and [`expand_instances_under`] may make at once.
const MAX_EXPAND_NODES: usize = 1_000_000;
pub(super) fn selected_instances(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
@@ -767,7 +834,7 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
let intensity = number_or(p, "intensity", 5.0, C)?.clamp(1.0, 10.0) / 10.0;
let alt = switch_or(p, "alt", false, C)?;
let st = s.doc()?;
let color = match p.get("color").and_then(color_value) {
let color = match color_param(p, "color", C)? {
Some(c) => crate::cmd::paint::new_color(s, p, c),
None => s.paint.fill.color().unwrap_or(Color::BLACK),
};
+3 -3
View File
@@ -72,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Make",
["Object", "Live Paint"],
Some("Cmd+Alt+X"),
"{ids?|id?} build a Live Paint group from the selected paths (paths, compound paths and groups of them; type, images and other objects are refused, nothing changes); with a Live Paint group among them, add the others to it as livePaint.merge does → {id, faces, edges}",
"{ids?|id?} build a Live Paint group from the selected paths (paths, compound paths and groups of them; type, images and other objects are refused, nothing changes); each covered face starts with its front-most covering source's fill; with a Live Paint group among them, add the others to it as livePaint.merge does → {id, faces, edges}",
has_selection_or_ids,
lp_make
),
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Gap Options",
[],
None,
"{id?, ids?: [id…] (instead of id; default: the selected Live Paint groups), detect?: bool (Gap Detection: paint stops at gaps up to size wide), size?: \"small\" (3 pt) | \"medium\" (6 pt) | \"large\" (12 pt) | pt (custom, over 0 up to 72) (Paint Stops At), color?: #rrggbb or a layer color's name such as \"Red\" (Gap Preview Color), closeGaps?: bool (add an unpainted path across each gap up to size wide to the group's paths)} set the Gap Options of Live Paint groups (what is not given stays as it was; a group starts with detect false, small and Red) and make their faces again, keeping their paint → {ids, faces, gaps: [[x0,y0,x1,y1]…] (the gaps up to size wide that no path closes, from a loose end of a path to where it closes to; detect closes them for paint), closed (paths added)}",
"{id?, ids?: [id…] (instead of id; default: the selected Live Paint groups), detect?: bool (Gap Detection: paint stops at gaps up to size wide), size?: \"small\" (3 pt) | \"medium\" (6 pt) | \"large\" (12 pt) | pt (custom, over 0 up to 72) (Paint Stops At), color?: #rrggbb or a layer color's name such as \"Red\" (Gap Preview Color; a hex color with an alpha part, #rrggbbaa or #rgba, is an error), closeGaps?: bool (add an unpainted path across each gap up to size wide to the group's paths)} set the Gap Options of Live Paint groups (what is not given stays as it was; a group starts with detect false, small and Red) and make their faces again, keeping their paint → {ids, faces, gaps: [[x0,y0,x1,y1]…] (the gaps up to size wide that no path closes, from a loose end of a path to where it closes to; detect closes them for paint), closed (paths added)}",
has_selection_or_ids,
lp_gap_options
),
@@ -117,7 +117,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Live Paint Bucket",
[],
None,
"{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], color?|swatch?|gradient?|none? (default: current fill), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces → {group, face}",
"{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], color?|swatch?|gradient?|none? (default: current fill; a color in #rrggbbaa or #rgba is refused), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces → {group, face}",
has_doc,
lp_fill
),
+11 -2
View File
@@ -93,11 +93,20 @@ pub struct Clipboard {
/// The artboards copied with the Artboard tool (`artboard.copy`); `nodes` are then their art.
/// Pasting adds a copy of each with the art.
pub artboards: Vec<vectorcraft_doc::Artboard>,
/// The selected ruler guides copied with (or without) the objects (#3226), as canvas guides on
/// no layer: pasting puts them on the layer new art goes to, moved as the objects are.
pub guides: Vec<vectorcraft_doc::Guide>,
}
impl Clipboard {
pub fn is_empty(&self) -> bool {
self.nodes.is_empty() && self.artboards.is_empty()
self.nodes.is_empty() && self.artboards.is_empty() && self.guides.is_empty()
}
/// Does it hold art (objects or artboards) for other apps? Ruler guides stay in VectorCraft:
/// a Copy of guides alone empties the system clipboard (#3226).
pub fn has_art(&self) -> bool {
!self.nodes.is_empty() || !self.artboards.is_empty()
}
/// Objects `roots` of `st`'s document with their resources, source artboard and layers.
@@ -195,7 +204,7 @@ impl Clipboard {
/// The objects as standalone SVG (`None` when there are none).
pub fn svg(&self) -> Option<String> {
if self.is_empty() {
if !self.has_art() {
return None;
}
let d = self.to_document();
+1 -1
View File
@@ -286,7 +286,7 @@ impl Clipboard {
/// The MIME types of [`Self::flavours`], without making them.
pub fn flavour_types(&self, svg: bool, pdf: bool) -> Vec<&'static str> {
if self.is_empty() {
if !self.has_art() {
return vec![];
}
let text = (svg && self.image_bytes() <= COPY_TEXT_IMAGE_BYTES) || self.nodes.iter().all(type_only);
+1 -1
View File
@@ -116,7 +116,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Color Guide",
[],
None,
"{color, rule: complementary|complementary2|splitComplementary|leftComplement|rightComplement|analogous|analogous2|monochromatic|shades|triad|triad2|triad3|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast2|highContrast3|pentagram (or its label), steps?: 1..20 (4), variation?: \"tintsShades\"|\"warmCool\"|\"vividMuted\", amount?: 0..100 (50; how far the outermost steps go), limitTo?: swatch library id or name; or \"document\" (the document's swatches): every colour snaps to its nearest colour there (ΔE 2000)} the Color Guide for a base colour → {rule, colors: [\"#rrggbb\", the base first], grid: [per colour, 2·steps+1 variations from shades/cool/muted to tints/warm/vivid with the colour itself in the centre]}",
"{color (#rrggbbaa and #rgba are refused), rule: complementary|complementary2|splitComplementary|leftComplement|rightComplement|analogous|analogous2|monochromatic|shades|triad|triad2|triad3|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast2|highContrast3|pentagram (or its label), steps?: 1..20 (4), variation?: \"tintsShades\"|\"warmCool\"|\"vividMuted\", amount?: 0..100 (50; how far the outermost steps go), limitTo?: swatch library id or name; or \"document\" (the document's swatches): every colour snaps to its nearest colour there (ΔE 2000)} the Color Guide for a base colour → {rule, colors: [\"#rrggbb\", the base first], grid: [per colour, 2·steps+1 variations from shades/cool/muted to tints/warm/vivid with the colour itself in the centre]}",
always,
harmony
),
+206 -39
View File
@@ -77,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Convert Color",
[],
None,
"{color, to: \"rgb\"|\"cmyk\"|\"gray\"|\"lab\", intent?} → {model, values, hex, lab: [L,a,b], outOfGamut, deltaE}",
"{color (#rrggbbaa and #rgba are refused), to: \"rgb\"|\"cmyk\"|\"gray\"|\"lab\", intent?} → {model, values, hex, lab: [L,a,b], outOfGamut, deltaE}",
always,
convert_color
),
@@ -86,7 +86,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Gamut Warning",
[],
None,
"{ids?|id?, colors?: [color]} colours that can't be printed in the working CMYK (selection, or the whole document when nothing is selected) → {checked, outOfGamut: [{hex, deltaE, count}]}",
"{ids?|id?, colors?: [color] (#rrggbbaa and #rgba are refused)} colours that can't be printed in the working CMYK (selection, or the whole document when nothing is selected) → {checked, outOfGamut: [{hex, deltaE, count}]}",
has_doc,
gamut_check
),
@@ -319,17 +319,138 @@ pub(crate) fn convert_mode(s: &mut Session, p: &Value) -> Result<Value> {
changed = set_color_mode(d, mode, convert, intent, grays);
Ok(())
})?;
if convert {
if s.in_interaction() && s.batch_stash.is_none() {
if let Some(it) = &mut s.doc_mut()?.interaction {
it.deferred_color_mode = Some(DeferredColorMode { mode, intent, grays });
}
} else {
let before = new_art_colors_before(s)?;
convert_new_art_colors(s, mode, intent, grays)?;
record_new_art_colors(s, before)?;
}
} else if s.batch_stash.is_some() || s.doc()?.undo_group.is_some() {
let before = new_art_colors_before(s)?;
record_new_art_colors(s, before)?;
}
Ok(json!({ "changed": changed }))
}
/// Put `d` in color `mode` and, with `convert`, convert every color of its art (opacity masks
/// included), symbols, graph designs, pattern tiles (the tile that pattern editing's Cancel puts
/// back included), graphic styles, brushes (their art and a Hue Shift key color) and swatches
/// through the color settings (`intent`, default: theirs) → how many colors of the art (opacity
/// masks included), symbols, graph designs and pattern tiles changed; the colors of graphic
/// styles and brushes convert without being counted. Gray colors stay
/// Gray (they print on the black plate in either mode); RGB grays are colors like any other and
/// separate through the CMYK profile, unless `grays` puts them on the black plate. Lab colors
/// The validated conversion choices of the current tentative color-mode preview.
#[derive(Clone, Copy, Debug)]
pub(crate) struct DeferredColorMode {
mode: ColorMode,
intent: Option<Intent>,
grays: Grays,
}
/// Complete the deferred new-art conversion before the interaction becomes an Undo step.
pub(crate) fn commit_new_art_colors(s: &mut Session) -> Result<()> {
let pending =
s.doc()?.interaction.as_ref().filter(|it| it.preview.is_some() && it.color_mode_paints.is_none()).and_then(|it| it.deferred_color_mode);
if let Some(DeferredColorMode { mode, intent, grays }) = pending {
let before = new_art_colors_before(s)?;
convert_new_art_colors(s, mode, intent, grays)?;
record_new_art_colors(s, before)?;
}
Ok(())
}
fn record_new_art_colors(s: &mut Session, before: vectorcraft_tools::PaintDefaults) -> Result<()> {
let after = s.paint.clone();
if before != after || s.batch_stash.is_some() || s.doc()?.undo_group.is_some() {
let st = s.doc_mut()?;
let slot = if let Some(it) = &mut st.interaction {
Some(&mut it.color_mode_paints)
} else {
st.history.undo.last_mut().map(|e| &mut e.color_mode_paints)
};
if let Some(slot) = slot {
match slot {
Some((_, end)) => *end = after,
slot => *slot = Some((before, after)),
}
}
if st.interaction.is_none() {
if let Some(e) = st.history.undo.last_mut() {
e.recost_paints();
}
st.history.trim();
}
}
Ok(())
}
fn new_art_colors_before(s: &Session) -> Result<vectorcraft_tools::PaintDefaults> {
let st = s.doc()?;
Ok(st.undo_group.as_ref().map(|g| &g.paint).or_else(|| st.interaction.as_ref().map(|it| &it.paint)).cloned().unwrap_or_else(|| s.paint.clone()))
}
/// Convert the fill and stroke that new art takes, and the colors of its template appearance
/// (paints and effect colors), as [`set_color_mode`] converted the active document's art. The
/// command records their original values for Undo. Previews defer this until acceptance;
/// a batch converts immediately and restores the values itself when it fails.
fn convert_new_art_colors(s: &mut Session, mode: ColorMode, intent: Option<Intent>, grays: Grays) -> Result<()> {
let d = &s.doc()?.doc;
let bases = global_bases(d);
let conv = mode_converter(mode, intent, grays);
let mut f = |col: &Color, link: proof::Link| mode_color(col, link, &bases, &conv);
map_paint_colors(&mut s.paint.fill, &mut f);
map_paint_colors(&mut s.paint.stroke, &mut f);
if let Some(a) = s.paint.appearance.as_mut() {
for it in &mut a.items {
let paint = match it {
vectorcraft_doc::AppearanceItem::Fill(l) => &mut l.paint,
vectorcraft_doc::AppearanceItem::Stroke(l) => &mut l.paint,
};
map_paint_colors(paint, &mut f);
}
map_effect_colors(a, &mut f);
}
Ok(())
}
/// How Document Color Mode converts a color to `mode` through the color settings (`intent`,
/// default: theirs): Gray and Lab colors stay as they are; with `grays` on the black plate, an RGB
/// gray becomes K only in CMYK.
fn mode_converter(mode: ColorMode, intent: Option<Intent>, grays: Grays) -> impl Fn(&Color) -> Color {
let c = cms::active();
let intent = intent.unwrap_or(c.settings().intent);
let model = if mode == ColorMode::Cmyk { Model::Cmyk } else { Model::Rgb };
let k_only = model == Model::Cmyk && grays == Grays::Black;
move |col: &Color| match col {
Color::Gray { .. } | Color::Lab { .. } => *col,
// Grey ink percentage, then K only (a Gray colour's CMYK).
Color::Rgb { .. } if k_only && Neutral::of(col).is_some() => c.convert(&c.convert(col, Model::Gray, intent), Model::Cmyk, intent),
_ => c.convert(col, model, intent),
}
}
/// The name and color of each global swatch of `d`, for [`mode_color`].
fn global_bases(d: &vectorcraft_doc::Document) -> Vec<(String, Color)> {
d.swatches_iter().filter_map(|w| Some((w.name.clone(), d.global_color(&w.name)?))).collect()
}
/// The color Document Color Mode gives `col` (swatch link `link`): a tint of a global swatch in
/// `bases` (already converted) is that swatch's color at its tint; any other color goes through
/// `conv` ([`mode_converter`]).
fn mode_color(col: &Color, link: proof::Link, bases: &[(String, Color)], conv: &dyn Fn(&Color) -> Color) -> Color {
match link.and_then(|(name, tint)| Some((bases.iter().find(|(n, _)| n == name)?, tint))) {
Some(((_, base), tint)) if tint < 1.0 => base.tinted(tint),
_ => conv(col),
}
}
/// Put `d` in color `mode` and, with `convert`, convert every color of its art (opacity masks,
/// effect colors and the series paints and label styles that graphs keep included), symbols,
/// graph designs, pattern tiles (the tile that pattern editing's Cancel puts back included),
/// graphic styles (their effects included), brushes (their art and a Hue Shift key color) and
/// swatches through the color settings (`intent`, default: theirs) → how many colors of the art
/// (opacity masks, effect colors and graphs' paints included), symbols, graph designs and pattern
/// tiles changed; the colors of graphic styles and brushes convert without being counted. Gray
/// colors stay Gray (they print on the black plate in either mode); RGB grays are colors like any
/// other and separate through the CMYK profile, unless `grays` puts them on the black plate
/// ([`mode_converter`]). Lab colors
/// (spot color definitions) are device independent and fit either mode. A tint of a global
/// swatch becomes the converted swatch's color at its tint. Document Color Mode and
/// `document.open {colorMode}` both convert this way.
@@ -338,16 +459,7 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode,
if !convert {
return 0;
}
let c = cms::active();
let intent = intent.unwrap_or(c.settings().intent);
let model = if mode == ColorMode::Cmyk { Model::Cmyk } else { Model::Rgb };
let k_only = model == Model::Cmyk && grays == Grays::Black;
let conv = |col: &Color| match col {
Color::Gray { .. } | Color::Lab { .. } => *col,
// Grey ink percentage, then K only (a Gray colour's CMYK).
Color::Rgb { .. } if k_only && Neutral::of(col).is_some() => c.convert(&c.convert(col, Model::Gray, intent), Model::Cmyk, intent),
_ => c.convert(col, model, intent),
};
let conv = mode_converter(mode, intent, grays);
for sw in d.swatches_iter_mut() {
match &mut sw.paint {
Paint::Solid { color, .. } => *color = conv(color),
@@ -360,13 +472,10 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode,
}
}
// Tints are their converted swatch's colour at their tint (exact ink percentages).
let bases: Vec<(String, Color)> = d.swatches_iter().filter_map(|w| Some((w.name.clone(), d.global_color(&w.name)?))).collect();
let bases = global_bases(d);
let changed = std::cell::Cell::new(0usize);
let mut count = |col: &Color, link: proof::Link| {
let n = match link.and_then(|(name, tint)| Some((bases.iter().find(|(n, _)| n == name)?, tint))) {
Some(((_, base), tint)) if tint < 1.0 => base.tinted(tint),
_ => conv(col),
};
let n = mode_color(col, link, &bases, &conv);
if n != *col {
changed.set(changed.get() + 1);
}
@@ -384,12 +493,15 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode,
}
// The reply counts the colors of the document's art only, not those of the graphic styles and brushes.
let in_art = changed.get();
for it in d.graphic_styles.iter_mut().flat_map(|g| &mut g.appearance.items) {
let paint = match it {
vectorcraft_doc::AppearanceItem::Fill(l) => &mut l.paint,
vectorcraft_doc::AppearanceItem::Stroke(l) => &mut l.paint,
};
map_paint_colors(paint, &mut count);
for g in &mut d.graphic_styles {
for it in &mut g.appearance.items {
let paint = match it {
vectorcraft_doc::AppearanceItem::Fill(l) => &mut l.paint,
vectorcraft_doc::AppearanceItem::Stroke(l) => &mut l.paint,
};
map_paint_colors(paint, &mut count);
}
map_effect_colors(&mut g.appearance, &mut count);
}
// Convert each brush's art. A Hue Shift key color takes the converted color of the art color
// it matches (a tint of a global swatch included), so the key still matches the converted art;
@@ -438,19 +550,28 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode,
in_art
}
/// [`proof::map_node_colors`] over `n`'s subtree and the art of every opacity mask in it.
/// [`proof::map_node_colors`] over `n`'s subtree, then [`map_more_colors`].
fn map_art_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof::Link) -> Color) {
proof::map_node_colors(n, f);
map_mask_colors(n, f);
map_more_colors(n, f);
}
fn map_mask_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof::Link) -> Color) {
if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()) {
map_art_colors(Arc::make_mut(&mut mask.art), f);
/// `f` applied to the colors in `n`'s subtree that [`proof::map_node_colors`] does not visit: the
/// effect colors ([`map_effect_colors`]), the series paints and label styles a graph keeps
/// ([`map_graph_colors`]) and the art of every opacity mask.
fn map_more_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof::Link) -> Color) {
map_effect_colors(&mut n.appearance, f);
if let Some(e) = n.extras_if_any() {
if let Some(g) = e.graph.as_deref_mut() {
map_graph_colors(g, f);
}
if let Some(mask) = e.mask.as_deref_mut() {
map_art_colors(Arc::make_mut(&mut mask.art), f);
}
}
if let Some(ch) = n.children_mut() {
for c in ch.iter_mut() {
map_mask_colors(Arc::make_mut(c), f);
map_more_colors(Arc::make_mut(c), f);
}
}
}
@@ -461,7 +582,46 @@ fn matches_key(c: &Color, key: &Color) -> bool {
c.to_rgb().iter().zip(key.to_rgb()).map(|(a, b)| (a - b).abs()).sum::<f32>() < 0.02
}
/// `f` applied to a solid paint's color or a gradient's stop colors, given their swatch link.
/// `f` applied to the `color` of each effect in appearance `a` (the object's effects and those of
/// each fill and stroke) that has one ([`super::params::effect_color`]). An effect that draws its
/// default color stores the new color as its own. The light colors of the 3D effects stay as they
/// are.
fn map_effect_colors(a: &mut vectorcraft_doc::Appearance, f: &mut dyn FnMut(&Color, proof::Link) -> Color) {
let items = a.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut());
for e in a.effects.iter_mut().chain(items) {
if !(e.params.is_object() || e.params.is_null()) {
continue;
}
let Some(color) = super::params::effect_color(&e.id, &e.params) else { continue };
let n = f(&color, None);
if n == color {
continue;
}
match &mut e.params {
Value::Object(m) => {
m.insert("color".into(), json!(n));
}
p => *p = json!({ "color": n }),
}
}
}
/// `f` applied to the series paints and the label styles that graph `g` keeps, which its marks and
/// labels take each time it is drawn again.
fn map_graph_colors(g: &mut vectorcraft_doc::GraphSpec, f: &mut dyn FnMut(&Color, proof::Link) -> Color) {
for p in g.series_paints.iter_mut() {
for paint in [&mut p.fill, &mut p.stroke].into_iter().flatten() {
map_paint_colors(paint, f);
}
}
let styles = &mut g.label_styles;
for st in [&mut styles.values, &mut styles.categories, &mut styles.legend].into_iter().flatten() {
map_paint_colors(&mut st.fill, f);
map_paint_colors(&mut st.stroke, f);
}
}
/// `f` applied to solid, gradient-stop and freeform-control colors, with any swatch link.
fn map_paint_colors(p: &mut Paint, f: &mut dyn FnMut(&Color, proof::Link) -> Color) {
match p {
Paint::Solid { color, swatch, tint } => *color = f(color, swatch.as_deref().map(|s| (s, *tint))),
@@ -469,6 +629,11 @@ fn map_paint_colors(p: &mut Paint, f: &mut dyn FnMut(&Color, proof::Link) -> Col
for st in &mut g.gradient.stops {
st.color = f(&st.color, st.swatch.as_deref().map(|s| (s, st.tint)));
}
if let Some(freeform) = &mut g.freeform {
for point in &mut freeform.points {
point.color = f(&point.color, None);
}
}
}
_ => {}
}
@@ -510,7 +675,9 @@ fn convert_color(_: &mut Session, p: &Value) -> Result<Value> {
fn gamut_check(s: &mut Session, p: &Value) -> Result<Value> {
let mut cols: Vec<Color> = vec![];
if let Some(a) = p.get("colors").and_then(Value::as_array) {
cols.extend(a.iter().filter_map(color_value));
for v in a {
cols.push(color_value(v).ok_or_else(|| bad("color.gamutCheck", format!("bad color {v}")))?);
}
} else {
let st = s.doc()?;
let ids = targets(s, p)?;
+1 -1
View File
@@ -39,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Save Theme",
["Window", "Color Themes"],
None,
"{colors: [1–5 colours] | color + rule (a harmony rule id or label, see color.harmony: its 5-colour theme from that base colour, base first), rule?: the rule it was made with, name?: (default \"Theme N\"), replace?: a saved theme's name (overwrite that theme in place, e.g. after editing it; it may be renamed), color?: one colour (as colors: [colour])} save a colour theme to the local theme library (the preferences) → {name, count: themes saved}",
"{colors: [1–5 colours] (#rrggbbaa and #rgba are refused) | color + rule (a harmony rule id or label, see color.harmony: its 5-colour theme from that base colour, base first), rule?: the rule it was made with, name?: (default \"Theme N\"), replace?: a saved theme's name (overwrite that theme in place, e.g. after editing it; it may be renamed), color?: one colour (as colors: [colour])} save a colour theme to the local theme library (the preferences) → {name, count: themes saved}",
always,
save
),
+2 -1
View File
@@ -85,7 +85,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Create Text",
[],
None,
"{x, y, text, rotation?: deg (about x, y), vertical?: bool = false, size?: pt, font?: family, style? (default Regular, or the family's closest style when it has no Regular), color?, keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText, fitMinPercent?}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on",
"{x, y, text, rotation?: deg (about x, y), vertical?: bool = false, size?: pt, font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText, fitMinPercent?}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on",
has_doc,
text_create
),
@@ -706,6 +706,7 @@ fn text_create(s: &mut Session, p: &Value) -> Result<Value> {
super::paint::check_keep_model(p, "text.create")?;
check_numbers(p, &["size"], "text.create")?;
check_switches(p, &["vertical", "placeholder"], "text.create")?;
super::color_param(p, "color", "text.create")?;
if let Some(a) = p.get("area") {
check_numbers(a, &["width", "height"], "text.create")?;
}
+71 -31
View File
@@ -138,8 +138,12 @@ fn cut_targets(s: &Session) -> Result<Vec<NodeId>> {
/// What a cut does to one object: its new pieces (none deletes it).
type Plan = Vec<(NodeId, Vec<PathData>)>;
/// Run `cut` on every target's geometry (`None`: unchanged) and apply the result as one undo step.
fn run_cut(s: &mut Session, cmd: &str, label: &str, cut: &dyn Fn(&PathData, FillRule) -> Option<Vec<PathData>>) -> Result<Value> {
/// What a cut makes of one object: its pieces (`None`: unchanged), or the pathops refusal.
type Cut = std::result::Result<Option<Vec<PathData>>, po::PathOpsError>;
/// Run `cut` on every target's geometry (`None`: unchanged) and apply the result as one undo step. A shape the
/// booleans refuse (too complex, too far out) fails the command with the art untouched: it is not "nothing on that side".
fn run_cut(s: &mut Session, cmd: &str, label: &str, cut: &dyn Fn(&PathData, FillRule) -> Cut) -> Result<Value> {
let targets = cut_targets(s)?;
if targets.is_empty() {
return Err(bad(cmd, "select paths or compound paths"));
@@ -151,7 +155,8 @@ fn run_cut(s: &mut Session, cmd: &str, label: &str, cut: &dyn Fn(&PathData, Fill
if pd.subpaths.iter().flat_map(|sp| &sp.anchors).any(|a| !(a.p.x.is_finite() && a.p.y.is_finite())) {
return Err(bad(cmd, "paths contain invalid coordinates"));
}
if let Some(pieces) = cut(&pd, rule) {
let pieces = cut(&pd, rule).map_err(|e| bad(cmd, format!("the cut cannot be made on this art: {e}")))?;
if let Some(pieces) = pieces {
plan.push((id, pieces));
}
}
@@ -184,9 +189,9 @@ fn reach(pd: &PathData) -> Rect {
}
/// `pd ∩ region`, dropping slivers.
fn intersect(pd: &PathData, rule: FillRule, region: &PathData) -> PathData {
let r = po::boolean(pd, rule, region, FillRule::NonZero, BoolOp::Intersect);
if po::area(&r, FillRule::NonZero) <= 1e-6 { PathData::default() } else { r }
fn intersect(pd: &PathData, rule: FillRule, region: &PathData) -> std::result::Result<PathData, po::PathOpsError> {
let r = po::try_boolean(pd, rule, region, FillRule::NonZero, BoolOp::Intersect, po::DEFAULT_PRECISION)?;
Ok(if po::try_area(&r, FillRule::NonZero)? <= 1e-6 { PathData::default() } else { r })
}
// ---------- Line Cut ----------
@@ -198,24 +203,26 @@ fn line_cut(s: &mut Session, p: &Value) -> Result<Value> {
}
/// `pd` split by the line: the pieces on both sides, `None` when the line misses it.
fn split_by_line(pd: &PathData, rule: FillRule, axis: &Axis) -> Option<Vec<PathData>> {
fn split_by_line(pd: &PathData, rule: FillRule, axis: &Axis) -> Cut {
if pd.is_closed() {
let around = reach(pd);
let a = intersect(pd, rule, &axis.half_plane(1.0, around));
let b = intersect(pd, rule, &axis.half_plane(-1.0, around));
let a = intersect(pd, rule, &axis.half_plane(1.0, around))?;
let b = intersect(pd, rule, &axis.half_plane(-1.0, around))?;
if a.is_empty() || b.is_empty() {
return None;
return Ok(None);
}
return Some(components(&a).into_iter().chain(components(&b)).collect());
return Ok(Some(components(&a).into_iter().chain(components(&b)).collect()));
}
// Open paths: the parts on each side (each pass removes the other side).
let a = erase_outline(pd, f64::INFINITY, &|q| axis.side(q) < 0.0)?;
let b = erase_outline(pd, f64::INFINITY, &|q| axis.side(q) >= 0.0)?;
Some(if pd.subpaths.len() == 1 {
let (Some(a), Some(b)) = (erase_outline(pd, f64::INFINITY, &|q| axis.side(q) < 0.0), erase_outline(pd, f64::INFINITY, &|q| axis.side(q) >= 0.0))
else {
return Ok(None);
};
Ok(Some(if pd.subpaths.len() == 1 {
a.into_iter().chain(b).collect()
} else {
vec![PathData::new(a.into_iter().chain(b).flat_map(|p| p.subpaths).collect())]
})
}))
}
// ---------- Rectangle Cut ----------
@@ -238,25 +245,34 @@ fn rect_cut(s: &mut Session, p: &Value) -> Result<Value> {
}
/// `pd` cropped to `rect`: `None` when it lies inside, no pieces when it lies outside.
fn crop(pd: &PathData, rule: FillRule, rect: Rect) -> Option<Vec<PathData>> {
let b = pd.bounds()?;
fn crop(pd: &PathData, rule: FillRule, rect: Rect) -> Cut {
let Some(b) = pd.bounds() else { return Ok(None) };
if rect.inflate(1e-9, 1e-9).contains_rect(b) {
return None;
return Ok(None);
}
if pd.is_closed() {
let r =
intersect(pd, rule, &polygon(&[rect.origin(), Point::new(rect.x1, rect.y0), Point::new(rect.x1, rect.y1), Point::new(rect.x0, rect.y1)]));
return Some(if r.is_empty() { vec![] } else { vec![r] });
// Wholly outside: nothing is left, whatever the booleans would make of the rectangle's coordinates.
if rect.intersect(b).is_zero_area() {
return Ok(Some(vec![]));
}
let r = intersect(
pd,
rule,
&polygon(&[rect.origin(), Point::new(rect.x1, rect.y0), Point::new(rect.x1, rect.y1), Point::new(rect.x0, rect.y1)]),
)?;
return Ok(Some(if r.is_empty() { vec![] } else { vec![r] }));
}
let inside = rect.inflate(1e-9, 1e-9);
// Sampled at least every half of the rectangle's shorter side, so a line through it is found.
let step = rect.width().min(rect.height()) / 2.0;
let pieces = erase_outline(pd, step, &|q| !(q.x >= inside.x0 && q.x <= inside.x1 && q.y >= inside.y0 && q.y <= inside.y1))?;
Some(if pd.subpaths.len() == 1 || pieces.is_empty() {
let Some(pieces) = erase_outline(pd, step, &|q| !(q.x >= inside.x0 && q.x <= inside.x1 && q.y >= inside.y0 && q.y <= inside.y1)) else {
return Ok(None);
};
Ok(Some(if pd.subpaths.len() == 1 || pieces.is_empty() {
pieces
} else {
vec![PathData::new(pieces.into_iter().flat_map(|p| p.subpaths).collect())]
})
}))
}
// ---------- Mirror & Cut ----------
@@ -287,7 +303,7 @@ fn mirror_cut(s: &mut Session, p: &Value) -> Result<Value> {
other => return Err(bad(C, format!("unknown axis `{other}` (vertical|horizontal|free)"))),
};
let sign = keep_sign(&axis, str_param(p, "keep")).map_err(|e| bad(C, e))?;
run_cut(s, C, "Mirror & Cut", &|pd, rule| Some(mirror(pd, rule, &axis, sign)))
run_cut(s, C, "Mirror & Cut", &|pd, rule| mirror(pd, rule, &axis, sign).map(Some))
}
/// The sign of [`Axis::side`] on the side `keep` names (default: left, or top when the axis runs
@@ -309,22 +325,22 @@ fn keep_sign(axis: &Axis, keep: Option<&str>) -> std::result::Result<f64, String
}
/// The kept half of `pd` and its reflection, joined (no pieces when nothing is on the kept side).
fn mirror(pd: &PathData, rule: FillRule, axis: &Axis, sign: f64) -> Vec<PathData> {
fn mirror(pd: &PathData, rule: FillRule, axis: &Axis, sign: f64) -> std::result::Result<Vec<PathData>, po::PathOpsError> {
let m = axis.reflection();
if pd.is_closed() {
let kept = intersect(pd, rule, &axis.half_plane(sign, reach(pd)));
let kept = intersect(pd, rule, &axis.half_plane(sign, reach(pd)))?;
if kept.is_empty() {
return vec![];
return Ok(vec![]);
}
let joined = po::boolean(&kept, FillRule::NonZero, &kept.transformed(m), FillRule::NonZero, BoolOp::Union);
return if joined.is_empty() { vec![] } else { vec![joined] };
let joined = po::try_boolean(&kept, FillRule::NonZero, &kept.transformed(m), FillRule::NonZero, BoolOp::Union, po::DEFAULT_PRECISION)?;
return Ok(if joined.is_empty() { vec![] } else { vec![joined] });
}
let kept = match erase_outline(pd, f64::INFINITY, &|q| axis.side(q) * sign < 0.0) {
Some(pieces) => pieces.into_iter().flat_map(|p| p.subpaths).collect(),
None => pd.subpaths.clone(),
};
let subs: Vec<SubPath> = kept.iter().flat_map(|sp| mirror_open(sp, axis, m)).collect();
if subs.is_empty() { vec![] } else { vec![PathData::new(subs)] }
Ok(if subs.is_empty() { vec![] } else { vec![PathData::new(subs)] })
}
/// An open run and its reflection, joined where its ends touch the axis (closed when both do);
@@ -399,4 +415,28 @@ mod tests {
let out = mirror_open(&sp, &axis, axis.reflection());
assert_eq!((out.len(), out[0].closed, out[0].anchors.len()), (1, false, 3));
}
/// A shape the booleans refuse (here: so far from the origin that the sweep tolerance exceeds the precision) is an error,
/// not "no pieces": that would make Mirror & Cut delete it and Rectangle Cut crop it to nothing.
#[test]
fn a_shape_the_booleans_refuse_is_an_error_not_no_pieces() {
let far = polygon(&[
Point::new(1e15, 1e15),
Point::new(1e15 + 100.0, 1e15),
Point::new(1e15 + 100.0, 1e15 + 100.0),
Point::new(1e15, 1e15 + 100.0),
]);
let axis = Axis { p: Point::ZERO, d: Vec2::new(0.0, 1.0) };
let refused = Some(po::PathOpsError::Degenerate);
assert_eq!(mirror(&far, FillRule::NonZero, &axis, 1.0).err(), refused);
assert_eq!(split_by_line(&far, FillRule::NonZero, &axis).err(), refused);
// A rectangle that far out, against art near the origin, still crops it to nothing.
let far_rect = Rect::new(1e15, 1e15, 1e15 + 100.0, 1e15 + 100.0);
let near_art = polygon(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)]);
assert_eq!(crop(&near_art, FillRule::NonZero, far_rect).unwrap(), Some(vec![]));
// Near the origin the same cuts work.
let near = polygon(&[Point::new(-50.0, 0.0), Point::new(50.0, 0.0), Point::new(50.0, 100.0), Point::new(-50.0, 100.0)]);
assert_eq!(mirror(&near, FillRule::NonZero, &axis, 1.0).unwrap().len(), 1);
assert_eq!(split_by_line(&near, FillRule::NonZero, &axis).unwrap().map(|p| p.len()), Some(2));
}
}
+37 -26
View File
@@ -11,7 +11,7 @@ use vectorcraft_geom::Vec2;
use super::edit::selected_roots;
use super::pathops::Beside;
use super::select::{is_selectable, selectable_ids, walk_selectable};
use super::select::{first_selectable, is_selectable, selectable_ids, walk_selectable};
use super::{
CommandSpec, EngineError, Point, Result, Session, bad, bool_or, checked_ids_param, cmd, f64_or, f64_req, has_doc, has_selection, id_param, ok,
str_param,
@@ -19,14 +19,18 @@ use super::{
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!("select.same.symbolInstance", "Symbol Instance", ["Select", "Same"], None, "{} → {count}", has_selection, |s, _| same(
s,
cmd!(
"select.same.symbolInstance",
|a, b| match (&a.kind, &b.kind) {
"Symbol Instance",
["Select", "Same"],
None,
"{} select the instances of the symbol of the first selected object that can be selected, including a group member selected on its own; when that object is not a symbol instance, such as a group, nothing is selected; objects 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 (new art while it stays selected excepted), or outside the isolated group or layer are passed over → {count}",
has_selection,
|s, _| same(s, "select.same.symbolInstance", |a, b| match (&a.kind, &b.kind) {
(NodeKind::SymbolInstance { symbol: x, .. }, NodeKind::SymbolInstance { symbol: y, .. }) => x == y,
_ => false,
}
)),
})
),
cmd!(
"select.same.linkBlockSeries",
"Link Block Series",
@@ -252,7 +256,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Document Color Mode",
["File", "Document Color Mode"],
None,
"{mode: \"cmyk\"|\"rgb\", convert?: true (convert every color of the art (opacity masks included), symbols, graph designs, pattern tiles, graphic styles, brushes and swatches through the color settings; swatch links kept; Gray colors stay Gray, on the black plate), intent?, grays?: \"profile\" (default: RGB grays separate through the CMYK profile like any color, into four-color grays and a rich black) | \"black\" (to CMYK, RGB grays with R = G = B go on the black plate only, K = their gray value)} → {changed: how many colors of the art, symbols, graph designs and pattern tiles changed; the colors of graphic styles and brushes are not counted}",
"{mode: \"cmyk\"|\"rgb\", convert?: true (convert every color of the art (opacity masks, effect colors and graphs' series and label paints included), symbols, graph designs, pattern tiles, graphic styles (their effect colors included), brushes, swatches and the paints new art takes through the color settings, together in one undo step (Undo restores their original values; Redo reapplies the conversion); swatch links kept; Gray colors stay Gray, on the black plate), intent?, grays?: \"profile\" (default: RGB grays separate through the CMYK profile like any color, into four-color grays and a rich black) | \"black\" (to CMYK, RGB grays with R = G = B go on the black plate only, K = their gray value)} → {changed: how many colors of the art, symbols, graph designs and pattern tiles changed; the colors of graphic styles and brushes are not counted}",
has_doc,
super::colormgmt::convert_mode
),
@@ -297,28 +301,23 @@ fn finish_same(s: &mut Session, cmd: &str, ids: Vec<NodeId>) -> Result<Value> {
Ok(json!({ "count": st.selection.objects.len() }))
}
/// The objects `eq` matches with the [`first_selectable`] selected object.
fn same(s: &mut Session, cmd: &str, eq: fn(&Node, &Node) -> bool) -> Result<Value> {
let st = s.doc()?;
let r = st.selection.objects.first().and_then(|id| st.doc.node(*id)).cloned().ok_or_else(|| bad(cmd, "nothing selected"))?;
let r = first_selectable(s.doc()?).cloned().ok_or_else(|| bad(cmd, "nothing selected"))?;
let ids = candidates(s, |n| eq(n, &r))?;
finish_same(s, cmd, ids)
}
/// The first character style of the first type object [`each_selected_text`] gives.
fn first_text_style(s: &Session) -> Option<CharStyle> {
let st = s.active()?;
let mut out = None;
for id in &st.selection.objects {
st.doc.node(*id)?.walk(&mut |n| {
if out.is_none()
&& let NodeKind::Text(t) = &n.kind
{
out = Some(t.first_style());
}
});
if out.is_some() {
break;
each_selected_text(s, |id| {
if let Some(NodeKind::Text(t)) = st.doc.node(id).map(|n| &n.kind) {
out = Some(t.first_style());
}
}
out.is_none()
});
out
}
@@ -333,11 +332,12 @@ fn same_text(s: &mut Session, cmd: &str, eq: fn(&CharStyle, &CharStyle) -> bool)
/// Call `f` with each type object among the selected objects and inside them, in selection order,
/// keeping only those [`walk_selectable`] visits: none that is hidden, locked, on a hidden, locked
/// or template layer, or outside the isolated group. A type object inside two selected objects is
/// given twice. The walk stops when `f` returns false.
/// or template layer, or outside the isolated group. A selected layer or sublayer, or a selected
/// group that holds the isolated group, gives the type in it that passes the same test. A type
/// object inside two selected objects is given twice. The walk stops when `f` returns false.
fn each_selected_text(s: &Session, mut f: impl FnMut(NodeId) -> bool) {
fn inside(n: &Node, f: &mut impl FnMut(NodeId) -> bool) -> bool {
if !n.visible || n.locked {
if !n.visible || n.locked || n.is_template() {
return true;
}
if matches!(n.kind, NodeKind::Text(_)) && !f(n.id) {
@@ -345,12 +345,23 @@ fn each_selected_text(s: &Session, mut f: impl FnMut(NodeId) -> bool) {
}
n.children().into_iter().flatten().all(|c| inside(c, f))
}
fn from(n: &Node, selectable: &impl Fn(NodeId) -> bool, holds_isolated: &[NodeId], f: &mut impl FnMut(NodeId) -> bool) -> bool {
if selectable(n.id) {
return inside(n, f);
}
if n.is_layer() || holds_isolated.contains(&n.id) {
return n.children().into_iter().flatten().all(|c| from(c, selectable, holds_isolated, f));
}
true
}
let Some(st) = s.active() else { return };
let locks = st.doc.locked_artboards();
let selectable = |id| is_selectable(&st.doc, st.isolation, &locks, id);
// The isolated group and the groups and layers that hold it.
let holds_isolated = st.isolation.and_then(|i| st.doc.ancestry(i)).unwrap_or_default();
for id in &st.selection.objects {
if is_selectable(&st.doc, st.isolation, &locks, *id)
&& let Some(n) = st.doc.node(*id)
&& !inside(n, &mut f)
if let Some(n) = st.doc.node(*id)
&& !from(n, &selectable, &holds_isolated, &mut f)
{
return;
}
+1 -1
View File
@@ -17,7 +17,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Document Setup",
[],
None,
"{units?: \"Points\"|\"Inches\"|\"Millimeters\"|…, bleed?: pt (all sides)|[top, bottom, left, right]|{top?, bottom?, left?, right?} (0–72 pt), outlineImages?: bool (show images in Outline mode), highlightSubstitutedGlyphs?: bool (Highlight Substituted Fonts is a preference: prefs.set highlightSubstitutedFonts; a highlightSubstitutedFonts key is ignored and the reply carries a warning),gridSize?: \"small\"|\"medium\"|\"large\", gridColors?: \"Light\"|\"Medium\"|\"Dark\"|\"Red\"|\"Orange\"|\"Green\"|\"Blue\"|\"Purple\"|[colour, colour] (transparency grid; the first is also the paper colour), simulatePaper?: bool, flattenerPreset?: \"High Resolution\"|\"Medium Resolution\"|\"Low Resolution\"|a saved preset (flattener.presets.list), discardWhiteOverprint?: bool, language?: \"English: USA\"|\"German\"|\"French\"|… (also picks its quotes), quotes?: {double?: \"“”\", single?: \"‘’\"} (beside a language: only if they differ from the current ones), typographersQuotes?: bool (typed straight quotes become the document's quotes), superscript?: {size?: %, position?: %}, subscript?: {size?: %, position?: %}, smallCapsSize?: %, exportText?: \"editable\"|\"appearance\" (SVG text as text or as outlines), backgroundContents?: \"transparent\"|\"white\" (white: raster exports are white behind the art), …the keys of its own reply (it can be passed back; the values it only reports are ignored)} change the document setup in one undo step; no params → the current setup",
"{units?: \"Points\"|\"Inches\"|\"Millimeters\"|…, bleed?: pt (all sides)|[top, bottom, left, right]|{top?, bottom?, left?, right?} (0–72 pt), outlineImages?: bool (show images in Outline mode), highlightSubstitutedGlyphs?: bool (Highlight Substituted Fonts is a preference: prefs.set highlightSubstitutedFonts; a highlightSubstitutedFonts key is ignored and the reply carries a warning),gridSize?: \"small\"|\"medium\"|\"large\", gridColors?: \"Light\"|\"Medium\"|\"Dark\"|\"Red\"|\"Orange\"|\"Green\"|\"Blue\"|\"Purple\"|[colour, colour] (transparency grid; the first is also the paper colour; #rrggbbaa and #rgba are refused), simulatePaper?: bool, flattenerPreset?: \"High Resolution\"|\"Medium Resolution\"|\"Low Resolution\"|a saved preset (flattener.presets.list), discardWhiteOverprint?: bool, language?: \"English: USA\"|\"German\"|\"French\"|… (also picks its quotes), quotes?: {double?: \"“”\", single?: \"‘’\"} (beside a language: only if they differ from the current ones), typographersQuotes?: bool (typed straight quotes become the document's quotes), superscript?: {size?: %, position?: %}, subscript?: {size?: %, position?: %}, smallCapsSize?: %, exportText?: \"editable\"|\"appearance\" (SVG text as text or as outlines), backgroundContents?: \"transparent\"|\"white\" (white: raster exports are white behind the art), …the keys of its own reply (it can be passed back; the values it only reports are ignored)} change the document setup in one undo step; no params → the current setup",
has_doc,
setup
)]
+94 -11
View File
@@ -10,8 +10,8 @@ use vectorcraft_geom::{Affine, Point, Vec2};
use super::clipboard::SwatchChoices;
use super::{
CommandSpec, Result, Session, always, bad, bool_or, can_clear_history, can_redo, can_undo, checked_ids_param, cmd, f64_or, f64_req,
finite_numbers, has_clipboard, has_doc, has_selection, has_selection_or_artboard_tool, has_selection_or_guides, id_param, index, ok, point_param,
str_param,
finite_numbers, has_clipboard, has_doc, has_selection, has_selection_guides_or_artboard_tool, has_selection_or_guides, id_param, index, ok,
point_param, str_param,
};
use crate::{Clipboard, EngineError, inspect};
@@ -125,8 +125,24 @@ pub fn specs() -> Vec<CommandSpec> {
always,
undo_group_end
),
cmd!("edit.cut", "Cut", ["Edit"], Some("Cmd+X"), "{} (the Artboard tool chosen: artboard.cut)", has_selection_or_artboard_tool, cut),
cmd!("edit.copy", "Copy", ["Edit"], Some("Cmd+C"), "{} (the Artboard tool chosen: artboard.copy)", has_selection_or_artboard_tool, copy),
cmd!(
"edit.cut",
"Cut",
["Edit"],
Some("Cmd+X"),
"{} (selected ruler guides go too; the Artboard tool chosen: artboard.cut)",
has_selection_guides_or_artboard_tool,
cut
),
cmd!(
"edit.copy",
"Copy",
["Edit"],
Some("Cmd+C"),
"{} the selection with what it uses, and the selected ruler guides (pasted on the layer new art goes to, moved as the objects are; alone, where they were); the Artboard tool chosen: artboard.copy → {copied, guides}",
has_selection_guides_or_artboard_tool,
copy
),
cmd!(
"edit.paste",
"Paste",
@@ -177,7 +193,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Clear",
["Edit"],
Some("Delete"),
"{ids?} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides)",
"{ids?, guides?: bool (with ids: also delete the selected ruler guides)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides)",
has_selection_or_guides,
clear
),
@@ -487,6 +503,9 @@ fn undo(s: &mut Session, _: &Value) -> Result<Value> {
let selection = shared_selection(selection, st.history.redo.last());
let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs);
turned.named = e.named;
let paints = e.color_mode_paints.clone();
turned.color_mode_paints = e.color_mode_paints;
turned.recost_paints();
st.history.redo.push(turned);
st.history.trim();
st.revision += 1;
@@ -499,6 +518,9 @@ fn undo(s: &mut Session, _: &Value) -> Result<Value> {
leave_isolation_if_gone(st);
super::globaledit::follow_history(st);
st.drop_stale_variables_highlight();
if let Some((before, _)) = paints {
s.paint = before;
}
Ok(json!({ "undone": label }))
}
@@ -516,6 +538,9 @@ fn redo(s: &mut Session, _: &Value) -> Result<Value> {
let selection = shared_selection(selection, st.history.undo.last());
let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs);
turned.named = e.named;
let paints = e.color_mode_paints.clone();
turned.color_mode_paints = e.color_mode_paints;
turned.recost_paints();
st.history.undo.push(turned);
st.history.trim();
st.revision += 1;
@@ -527,6 +552,9 @@ fn redo(s: &mut Session, _: &Value) -> Result<Value> {
leave_isolation_if_gone(st);
super::globaledit::follow_history(st);
st.drop_stale_variables_highlight();
if let Some((_, after)) = paints {
s.paint = after;
}
Ok(json!({ "redone": label }))
}
@@ -640,9 +668,35 @@ fn copy(s: &mut Session, _: &Value) -> Result<Value> {
if s.tool_id() == "artboard" {
return super::panelcmds::artboard_copy(s, &json!({}), false);
}
let roots = selected_roots(s)?;
s.clipboard = Clipboard::copy(s.doc()?, &roots);
Ok(json!({ "copied": s.clipboard.nodes.len() }))
let st = s.doc()?;
// Selected ruler guides come along (#3226), as canvas guides: their layer and artboard stay
// behind.
let guides: Vec<vectorcraft_doc::Guide> = st
.selection
.guides
.iter()
.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);
// 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()
&& let Some(g) = st.selection.guides.first().and_then(|i| st.doc.guides.get(*i))
{
let board = g.artboard.and_then(|id| st.doc.artboards.iter().find(|a| a.id == id)).or_else(|| {
st.doc
.artboards
.iter()
.find(|a| if g.vertical { (a.rect.x0..=a.rect.x1).contains(&g.pos) } else { (a.rect.y0..=a.rect.y1).contains(&g.pos) })
});
clip.source_artboard = board.map(|a| a.rect);
}
clip.guides = guides;
s.clipboard = clip;
Ok(json!({ "copied": s.clipboard.nodes.len(), "guides": s.clipboard.guides.len() }))
}
fn cut(s: &mut Session, p: &Value) -> Result<Value> {
@@ -651,9 +705,15 @@ fn cut(s: &mut Session, p: &Value) -> Result<Value> {
}
// 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)?;
if s.doc()?.selection.anchors.is_empty() { clear(s, &json!({ "ids": ids })) } else { clear(s, &json!({})) }
// 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 })) }
}
fn clear(s: &mut Session, p: &Value) -> Result<Value> {
@@ -667,8 +727,9 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
return super::docmenu::guide_remove(s, &json!({}));
}
let st = s.doc()?;
// Guides selected with the art go with it (not when ids are given).
let with_guides = explicit.is_none();
// 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 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.
@@ -838,6 +899,13 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
// In place, in front, in back: onto the active artboard when the UI names it.
_ => vec![onto_artboard(&st.doc, p, clip)],
};
// Guides alone don't follow a plain paste's offset or the view centre: they stay where they
// were. With objects they move as the objects do.
let guide_placements: Vec<Affine> = if !clip.nodes.is_empty() || !matches!(mode, PasteMode::Offset | PasteMode::Library | PasteMode::Drag) {
placements.clone()
} else {
vec![Affine::IDENTITY]
};
let (ids, imported, artboards, into) = s.edit(mode.label(), |d, sel| {
let imported = clip.import_into(d, choices, same_doc);
// Draw Inside: the clip group of the object drawn into, made on the first paste.
@@ -885,6 +953,20 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
}
}
sel.set(new_ids.iter().copied());
// Copied ruler guides (#3226): on the layer new art goes to, moved as the objects are (a
// paste of guides alone keeps them where they were, but onto another artboard or every
// artboard as the in-place pastes put art); they are selected with the objects.
let guide_layer = parent.and_then(|p| if d.node(p).is_some_and(Node::is_layer) { Some(p) } else { d.layer_containing(p) });
for xf in &guide_placements {
let dv = xf.translation();
for g in &clip.guides {
let pos = g.pos + if g.vertical { dv.x } else { dv.y };
if pos.is_finite() {
sel.guides.push(d.guides.len());
d.guides.push(vectorcraft_doc::Guide { pos, layer: guide_layer, ..g.clone() });
}
}
}
// Pasted type arrives without the layout bounds cache: fill it so boxes and alignment are
// right away (opening the file later would, but paste must not depend on a reopen).
super::typecmd::refresh_bounds_of(d, &new_ids);
@@ -899,6 +981,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
}
Ok(json!({
"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(),
"guides": clip.guides.len() * guide_placements.len(),
"artboard": artboards.first(),
"artboards": artboards,
"added": imported.added,
+92 -32
View File
@@ -1,6 +1,7 @@
//! Object → Expand: live shapes, type and effects (Object), strokes (Stroke) and gradient and pattern
//! fills (Fill) into plain art in one undo step; blends, repeats and Intertwine groups become groups of their steps, of their instances and of what they draw. Placed documents (Object) become editable copies of the
//! art they show, their resources joining the document. A linear or radial gradient fill becomes a
//! art they show, their resources joining the document. Symbol instances (Object) become their art,
//! as Break Link to Symbol places it. A linear or radial gradient fill becomes a
//! gradient mesh, or solid strips / concentric ellipses, inside a clip group shaped like the object; a freeform
//! gradient becomes a mesh shaped like the object. A pattern fill becomes the tiles it paints inside a clip
//! group shaped like the object. Create Gradient Mesh shares the sampling.
@@ -40,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Expand…",
["Object"],
None,
"{object?: true (type → outlines, live shapes → paths, effects baked, blends → groups of their steps, repeats → groups of their instances, Intertwine groups → groups of their objects and of the parts drawn over the others (clip groups), envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art, pattern fills → their tiles in a clip group shaped like the object), stroke?: true (strokes → filled outlines, the stroked paths that baking effects leaves included), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients) | \"mesh\" (a gradient mesh); both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255)} one undo step → {ids}",
"{object?: true (symbol instances without effects (their fills' and strokes' included) and not in perspective → their art, as Break Link to Symbol places it (the instances that art holds stay instances), type → outlines, live shapes → paths, effects baked, blends → groups of their steps, repeats → groups of their instances, Intertwine groups → groups of their objects and of the parts drawn over the others (clip groups), envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art, pattern fills → their tiles in a clip group shaped like the object), stroke?: true (strokes → filled outlines, the stroked paths that baking effects leaves included), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients) | \"mesh\" (a gradient mesh); both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255)} one undo step → {ids}",
has_selection,
expand
),
@@ -49,11 +50,17 @@ pub fn specs() -> Vec<CommandSpec> {
"Expand Options",
[],
None,
"{} what each Expand option would change in the selection → {object, fill, stroke, gradient, appearance} (true: something to expand; gradient: a gradient fill that Fill expands, which Expand Gradient To applies to; appearance: appearance attributes Expand Appearance expands first, for which Object › Expand… is dimmed in the menus)",
"{} what each Expand option would change in the selection → {object, fill, stroke, gradient, appearance, symbolArt?: {fill, stroke, gradient}} (true: something to expand; gradient: a gradient fill that Fill expands, which Expand Gradient To applies to; appearance: appearance attributes Expand Appearance expands first, for which Object › Expand… is dimmed in the menus; symbolArt, when the selection holds symbol instances that Object expands: true when only their art holds it, which Fill and Stroke reach only with Object on)",
has_selection,
|s, _| {
let e = Expandable::of(&s.doc()?.doc, &selected_roots(s)?);
Ok(json!({"object": e.object(), "fill": e.fill, "stroke": e.stroke, "gradient": e.gradient, "appearance": has_appearance(s)}))
let mut info =
json!({"object": e.object(), "fill": e.fill, "stroke": e.stroke, "gradient": e.gradient, "appearance": has_appearance(s)});
if e.symbols {
let [fill, stroke, gradient] = e.symbol_art;
info["symbolArt"] = json!({"fill": fill, "stroke": stroke, "gradient": gradient});
}
Ok(info)
}
),
]
@@ -124,45 +131,74 @@ struct Expandable {
repeats: bool,
/// Intertwine groups (Object expands them into groups of what they draw).
intertwines: bool,
/// Symbol instances (Object expands them into their art, as Break Link to Symbol does).
symbols: bool,
/// Fill, stroke and gradient that only the art of those symbol instances holds: Fill and Stroke
/// reach them only when Object expands the instances.
symbol_art: [bool; 3],
}
impl Expandable {
fn of(d: &Document, roots: &[NodeId]) -> Self {
let mut e = Self::default();
for n in roots.iter().filter_map(|r| d.node(*r)) {
n.walk(&mut |c| {
let shape = matches!(c.kind, NodeKind::Path { .. } | NodeKind::Compound { .. });
e.text |= matches!(c.kind, NodeKind::Text(_));
e.live |= matches!(c.kind, NodeKind::Path { live: Some(_), .. });
e.effects |= !c.appearance.effects.is_empty();
e.envelope |= matches!(c.kind, NodeKind::Envelope { .. });
e.blends |= matches!(c.kind, NodeKind::Blend { .. });
e.placed |= matches!(c.kind, NodeKind::PlacedDocument(_));
e.repeats |= matches!(c.kind, NodeKind::Repeat(_));
e.intertwines |= matches!(c.kind, NodeKind::Intertwine { .. });
e.stroke |= match &c.kind {
// Type's outlines take its characters' stroke (see `type.createOutlines`).
NodeKind::Text(t) => t.runs.iter().any(|r| r.style.has_stroke()),
_ => shape && !c.appearance.stroke_paint().is_none(),
};
e.gradient |= match &c.kind {
NodeKind::Text(t) => t.runs.iter().any(|r| matches!(r.style.fill, Paint::Gradient(_))),
_ => shape && c.appearance.items.iter().any(|i| gradient_fill(i).is_some()),
};
e.fill |= e.gradient;
e.fill |= match &c.kind {
NodeKind::Text(t) => {
t.runs.iter().any(|r| matches!(&r.style.fill, Paint::Pattern { pattern, .. } if d.pattern(pattern).is_some()))
}
_ => shape && c.appearance.items.iter().any(|i| pattern_fill(d, i).is_some()),
};
});
e.add(d, n);
}
let own = [e.fill, e.stroke, e.gradient];
// The Fill and Stroke options also reach the art of the symbol instances that Object
// expands: a dynamic instance's art with its own changes, and each other symbol's art once.
let instances = super::brushsym::expandable_instances(d, roots);
e.symbols = !instances.is_empty();
let mut seen = std::collections::HashSet::new();
for inst in instances.iter().filter_map(|id| d.node(*id)) {
let NodeKind::SymbolInstance { symbol, .. } = &inst.kind else { continue };
let Some(sym) = d.symbols.iter().find(|s| &s.name == symbol) else { continue };
let mut a = Self::default();
if !inst.extras().symbol_overrides.is_empty() {
a.add(d, &vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, inst));
} else if seen.insert(symbol.clone()) {
a.add(d, &sym.art);
}
e.fill |= a.fill;
e.gradient |= a.gradient;
e.stroke |= a.stroke;
}
e.symbol_art = [e.fill && !own[0], e.stroke && !own[1], e.gradient && !own[2]];
e
}
/// Adds what `n` and the nodes under it hold.
fn add(&mut self, d: &Document, n: &Node) {
let e = self;
n.walk(&mut |c| {
let shape = matches!(c.kind, NodeKind::Path { .. } | NodeKind::Compound { .. });
e.text |= matches!(c.kind, NodeKind::Text(_));
e.live |= matches!(c.kind, NodeKind::Path { live: Some(_), .. });
e.effects |= !c.appearance.effects.is_empty();
e.envelope |= matches!(c.kind, NodeKind::Envelope { .. });
e.blends |= matches!(c.kind, NodeKind::Blend { .. });
e.placed |= matches!(c.kind, NodeKind::PlacedDocument(_));
e.repeats |= matches!(c.kind, NodeKind::Repeat(_));
e.intertwines |= matches!(c.kind, NodeKind::Intertwine { .. });
e.stroke |= match &c.kind {
// Type's outlines take its characters' stroke (see `type.createOutlines`).
NodeKind::Text(t) => t.runs.iter().any(|r| r.style.has_stroke()),
_ => shape && !c.appearance.stroke_paint().is_none(),
};
e.gradient |= match &c.kind {
NodeKind::Text(t) => t.runs.iter().any(|r| matches!(r.style.fill, Paint::Gradient(_))),
_ => shape && c.appearance.items.iter().any(|i| gradient_fill(i).is_some()),
};
e.fill |= e.gradient;
e.fill |= match &c.kind {
NodeKind::Text(t) => t.runs.iter().any(|r| matches!(&r.style.fill, Paint::Pattern { pattern, .. } if d.pattern(pattern).is_some())),
_ => shape && c.appearance.items.iter().any(|i| pattern_fill(d, i).is_some()),
};
});
}
fn object(&self) -> bool {
self.text || self.live || self.effects || self.envelope || self.blends || self.placed || self.repeats || self.intertwines
self.text || self.live || self.effects || self.envelope || self.blends || self.placed || self.repeats || self.intertwines || self.symbols
}
}
@@ -209,6 +245,30 @@ fn expand_steps(s: &mut Session, p: &Value) -> Result<Value> {
if object && e.placed {
let roots = selected_roots(s)?;
s.edit("Expand", |d, _| expand_placed_under(d, &roots))?;
e = Expandable::of(&s.doc()?.doc, &selected_roots(s)?);
}
// Then the symbol instances, those in the placed documents' art included: their art expands
// below, and the instances it holds stay instances.
if object && e.symbols {
let roots = selected_roots(s)?;
// An edit that expands no instance (too many objects to make) is undone, and the
// instances stay as they are.
let mut expanded = None;
let r = s.edit("Expand", |d, _| {
let any = super::brushsym::expand_instances_under(d, &roots)?;
expanded = Some(any);
if any { Ok(()) } else { Err(EngineError::Other("Expand: nothing to expand".into())) }
});
if !matches!((&r, expanded), (Err(_), Some(false))) {
r?;
}
e = Expandable::of(&s.doc()?.doc, &selected_roots(s)?);
// The placed documents in the instances' art too.
if e.placed {
let roots = selected_roots(s)?;
s.edit("Expand", |d, _| expand_placed_under(d, &roots))?;
e = Expandable::of(&s.doc()?.doc, &selected_roots(s)?);
}
}
// Intertwine groups before what they hold: their objects, and the copies of the parts drawn
// over the others, expand below.
+2 -2
View File
@@ -108,7 +108,7 @@ mod export_names;
mod formats;
#[cfg(not(target_arch = "wasm32"))]
use access::list_dir;
pub(crate) use access::list_dir;
pub use access::write_file_with;
#[cfg(not(target_arch = "wasm32"))]
pub(crate) use access::{Placed, copy_new, file_metadata};
@@ -120,7 +120,7 @@ pub(crate) use access::{drive_share_of, share_of};
#[cfg(test)]
pub(crate) use access::{drive_share_path, share_path, touched};
#[cfg(not(target_arch = "wasm32"))]
use access::{may_read, may_write};
pub(crate) use access::{may_read, may_write};
pub use commands::specs;
pub use export_names::artboard_file_names;
pub(crate) use export_names::{default_name, merge, unique_file_names, with_black_output, write_or_return};
+4 -4
View File
@@ -10,7 +10,7 @@ use super::{EngineError, Result, Session, Value, bad, json};
/// `path` checked for reading against the automation roots in force.
#[cfg(not(target_arch = "wasm32"))]
pub(super) fn may_read(path: &str) -> Result<()> {
pub(crate) fn may_read(path: &str) -> Result<()> {
#[cfg(test)]
touch(path);
crate::file_access::check_read(path).map_err(EngineError::Other)
@@ -44,7 +44,7 @@ pub(crate) fn touched<T>(f: impl FnOnce() -> T) -> (T, Vec<String>) {
/// `path` checked for writing against the automation roots in force.
#[cfg(not(target_arch = "wasm32"))]
pub(super) fn may_write(path: &str) -> Result<()> {
pub(crate) fn may_write(path: &str) -> Result<()> {
crate::file_access::check_write(path).map_err(EngineError::Other)
}
@@ -169,7 +169,7 @@ pub(super) fn file_list(_: &mut Session, p: &Value) -> Result<Value> {
/// The entries of folder `path`, sorted by name: at most `max`, and whether there were more. A
/// link isn't followed: its target may lie outside the automation roots.
#[cfg(not(target_arch = "wasm32"))]
pub(super) fn list_dir(path: &str, max: usize) -> Result<(Vec<Value>, bool)> {
pub(crate) fn list_dir(path: &str, max: usize) -> Result<(Vec<Value>, bool)> {
may_read(path)?;
let dir = std::fs::read_dir(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
let mut entries: Vec<(String, Value)> = vec![];
@@ -195,7 +195,7 @@ pub(super) fn list_dir(path: &str, max: usize) -> Result<(Vec<Value>, bool)> {
}
#[cfg(target_arch = "wasm32")]
pub(super) fn list_dir(_: &str, _: usize) -> Result<(Vec<Value>, bool)> {
pub(crate) fn list_dir(_: &str, _: usize) -> Result<(Vec<Value>, bool)> {
Err(EngineError::Other("no file system here".into()))
}
+20 -7
View File
@@ -15,12 +15,12 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
let artboard = p.get("artboard").and_then(Value::as_u64);
// What an error rolls back besides the documents: session-level state a step may change
// (paint defaults, drawing mode, clipboard, the Untitled-N count, a begun undo group).
let saved = (s.paint.clone(), s.fill_active, s.draw_mode, s.draw_inside, s.clipboard.clone(), s.untitled_counter, s.explicit_undo_group.clone());
// A drag or typing still in progress is a step of its own, as before Undo: the batch's steps
// would otherwise run inside it and take its baseline as theirs (#1697).
if s.active().is_some() {
if s.active().is_some() && !s.previewing {
super::super::edit::settle_interaction(s)?;
}
let saved = (s.paint.clone(), s.fill_active, s.draw_mode, s.draw_inside, s.clipboard.clone(), s.untitled_counter, s.explicit_undo_group.clone());
// The documents as they are now, whole: what a failed step brings back. Their art, history,
// file, format and saved state share their data with the open ones until a step changes them.
let start = s.docs.clone();
@@ -47,10 +47,18 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
}
};
// Each document the steps edited keeps them as one undo step.
s.remember_pending_paint();
for st in &mut s.docs {
if let Some(it) = st.interaction.take() {
st.keep_interaction(it);
if !s.previewing {
s.remember_pending_paint();
for st in &mut s.docs {
if let Some(mut it) = st.interaction.take() {
// Redo restores the new-art colors the whole batch left, not the ones right after a
// color-mode step.
if let Some((_, after)) = &mut it.color_mode_paints {
after.clone_from(&s.paint);
s.batch_paint_docs.push(st.uid);
}
st.keep_interaction(it);
}
}
}
// The batch journals itself, whichever document it ends in.
@@ -58,7 +66,9 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(o) = entry.as_object_mut() {
o.insert("commands".into(), Value::Array(cmds));
}
s.journal.push(("command.batch".into(), entry));
if !s.previewing {
s.journal.push(("command.batch".into(), entry));
}
Ok(json!({ "results": results }))
}
@@ -104,6 +114,9 @@ fn run_steps(
let held: Vec<(u64, Arc<Document>)> = s.docs.iter().filter(|st| st.undo_group.is_some()).map(|st| (st.uid, st.doc.clone())).collect();
let (v, noted) =
s.execute_step(&id, &params).map_err(|e| EngineError::Other(format!("batch step {} (`{id}`) failed: {e}", results.len())))?;
if s.previewing && s.active().map(|d| d.uid) != start {
return Err(bad("command.batch", "a batch preview cannot switch documents"));
}
grouped.push(step_groups(s, start, &held));
// The step's journal entry records what it took from the preferences or the clock (a
// save's date, a new document's), as a command of its own would.
+1 -1
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), 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?: 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",
has_doc,
export::export
),
+4 -1
View File
@@ -420,7 +420,10 @@ pub fn encode(doc: &Document, format: &str, p: &Value) -> Result<Vec<u8>> {
/// font; PDF, EPS, SVG, EMF, WMF and the raster formats: type that doesn't fit its frame).
pub fn encode_with_warnings(doc: &Document, format: &str, p: &Value) -> Result<(Vec<u8>, Vec<String>)> {
let f = super::writable(C, Some(format), None)?;
encode_all(doc, f.id, p)?.single(f)
let enc = encode_all(doc, f.id, p)?;
// The error for a version 7 .ai of several artboards names the legacy .ai.
let legacy = f.id == "ai" && super::legacy_ai::wanted(C, f, p)?;
enc.single(&if legacy { super::legacy_ai::named(f) } else { *f })
}
/// [`encode`], with every file the export writes.
+9 -3
View File
@@ -41,7 +41,7 @@ use super::super::{Affine, EngineError, NodeId, Result, bad};
use super::{ArtboardPick, Encoded, Format};
/// Does `p` ask a save in `f` for a legacy `.ai` file of version 7 (`aiVersion: "7"`)? An unknown
/// version is an error, and so is version 7 for a `.ait` template, which is PDF-compatible only.
/// version is an error, and so is version 7 for a `.ait` template, which is never a legacy file.
pub(super) fn wanted(cmd: &str, f: &Format, p: &Value) -> Result<bool> {
let legacy = match p.get("aiVersion") {
None | Some(Value::Null) => false,
@@ -51,11 +51,17 @@ pub(super) fn wanted(cmd: &str, f: &Format, p: &Value) -> Result<bool> {
Some(v) => return Err(bad(cmd, format!("aiVersion {v}: \"pdf\" (PDF-compatible, the default) or \"7\" (legacy .ai, version 7)"))),
};
if legacy && f.id == "ait" {
return Err(bad(cmd, "aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible"));
return Err(bad(cmd, "aiVersion 7 writes legacy .ai files, not .ait templates"));
}
Ok(legacy)
}
/// `f` (the `.ai` format, whose label names the PDF-compatible file) named, in its errors, as the
/// legacy `.ai` file.
pub(super) fn named(f: &Format) -> Format {
Format { label: "legacy .ai (version 7)", ..*f }
}
/// What a legacy `.ai` does with the images it can't hold (`transparentImages`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum SeeThrough {
@@ -109,7 +115,7 @@ pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result
}
let mode = see_through(cmd, p)?;
let (hidden, outline_text) = (hidden_objects(cmd, p)?, outline_text(cmd, p)?);
let picked: ArtboardPick = super::encode::options(f, p)?;
let picked: ArtboardPick = super::encode::options(&named(f), p)?;
let boards = picked.resolve(n).map_err(|e| bad(cmd, e))?.unwrap_or_else(|| (0..n).collect());
let mut enc = Encoded { warnings: vec![FIDELITY.to_string()], ..Encoded::default() };
if boards.len() > 1 {
+123 -55
View File
@@ -165,14 +165,18 @@ pub fn load(name: &str, bytes: &[u8]) -> Result<Loaded> {
/// of its art, which it carries: its layers and hidden objects as they were, and the art outside
/// its artboard (its PDF part has only what is on the artboards), as an EPS of the editor is read.
/// Anything else as it was. `unit`: the size in points of a unit of the PDF part's user space (its
/// first page's `UserUnit`) → (document, warnings, whether its layers were read).
fn through_editing_data(bytes: &[u8], opts: &LoadOptions, doc: Document, warnings: Vec<String>, unit: f64) -> (Document, Vec<String>, bool) {
if opts.pages.is_some() || !opts.layers || !opts.editing_data {
return (doc, warnings, false);
}
let Some(private) = vectorcraft_pdf::illustrator_data(bytes, opts.password.as_deref()) else { return (doc, warnings, false) };
/// first page's `UserUnit`) → (document, warnings, whether its layers were read). `layers`: the
/// editor's copy ([`editing_copy`]), as far as it was decoded and read.
fn through_editing_data(
layers: Option<vectorcraft_eps::AiLayers>,
opts: &LoadOptions,
doc: Document,
warnings: Vec<String>,
unit: f64,
) -> (Document, Vec<String>, bool) {
let Some(layers) = layers else { return (doc, warnings, false) };
let outlined = opts.text_as == vectorcraft_pdf::TextAs::Outlines;
let (doc, mut warnings, read) = vectorcraft_eps::layered_ai(&private, doc, warnings, outlined, opts.trust_editing_data, unit);
let (doc, mut warnings, read) = vectorcraft_eps::layered_ai_from(layers, doc, warnings, outlined, opts.trust_editing_data, unit);
// The layers weren't read (or couldn't be): the notes of reading the PDF part still hold.
if !read {
return (doc, warnings, false);
@@ -189,18 +193,41 @@ fn through_editing_data(bytes: &[u8], opts: &LoadOptions, doc: Document, warning
(doc, warnings, true)
}
/// A `.ai` saved without PDF compatibility (its PDF part is a placeholder page) from the editor's
/// own copy of its art alone: `None` when the file has none (or pages are picked, or layers or the
/// editing data are off), an error when it can't be read.
fn from_editing_data_alone(bytes: &[u8], opts: &LoadOptions) -> Option<Result<(Document, Vec<String>)>> {
if opts.pages.is_some() || !opts.layers || !opts.editing_data {
/// A `.ai` saved without PDF compatibility (its PDF part is a placeholder page), `opened`, from the
/// editor's own copy of its art alone: `None` when the file has none (or the pages picked don't
/// name every page, or layers or the editing data are off), an error when it can't be read.
fn from_editing_data_alone(opened: &vectorcraft_pdf::Opened, opts: &LoadOptions) -> Option<Result<(Document, Vec<String>)>> {
if !every_page(opened.page_count(), opts) || !opts.layers || !opts.editing_data {
return None;
}
let private = vectorcraft_pdf::illustrator_data(bytes, opts.password.as_deref())?;
Some(
vectorcraft_eps::ai_alone(&private)
.map_err(|why| err(format!("this file was saved without PDF compatibility, and its editing data can't be read ({why})"))),
)
let private = opened.illustrator_data()?;
Some(editing_copy_alone(&private))
}
/// [`from_editing_data_alone`] of `private`, the editor's copy already read.
fn editing_copy_alone(private: &[u8]) -> Result<(Document, Vec<String>)> {
vectorcraft_eps::ai_alone(private)
.map_err(|why| err(format!("this file was saved without PDF compatibility, and its editing data can't be read ({why})")))
}
/// Does a file opened with `opts` read the editor's own copy of its art: no pages picked, and
/// layers and the editing data on?
fn reads_editing_copy(opts: &LoadOptions) -> bool {
opts.pages.is_none() && opts.layers && opts.editing_data
}
/// May a file opened with `opts` open from the editor's own copy of its art without its PDF part
/// being imported ([`vectorcraft_eps::ai_layers_alone`]): it reads the editor's copy, on the pages'
/// trim boxes (the crop box asked for, as a file with the editor's copy opens on them), with its
/// type as text?
fn reads_layers_alone(opts: &LoadOptions) -> bool {
reads_editing_copy(opts) && opts.crop == vectorcraft_pdf::CropTo::Crop && opts.text_as != vectorcraft_pdf::TextAs::Outlines
}
/// The editor's own copy of its art that `opened` carries (as [`vectorcraft_pdf::illustrator_data`]
/// reads it), when `opts` read it ([`reads_editing_copy`]).
fn editing_copy(opened: &vectorcraft_pdf::Opened, opts: &LoadOptions) -> Option<Vec<u8>> {
reads_editing_copy(opts).then(|| opened.illustrator_data()).flatten()
}
/// A `.ai`, or a PDF saved with the editing data, whose PDF part can't be read (`e`, the import's
@@ -266,10 +293,10 @@ pub(crate) fn is_placeholder(e: &EngineError) -> bool {
e.to_string() == vectorcraft_pdf::PdfError::PlaceholderOnly.to_string()
}
/// Do `opts` read every page of the PDF `bytes`: no `pages`, or a range that names each one?
fn every_page(bytes: &[u8], opts: &LoadOptions) -> bool {
/// Do `opts` read every page of a PDF of `count` pages: no `pages`, or a range that names each one?
fn every_page(count: usize, opts: &LoadOptions) -> bool {
let Some(range) = &opts.pages else { return true };
vectorcraft_pdf::info(bytes, opts.password.as_deref()).is_ok_and(|i| parse_range(range, i.pages.len()).is_ok_and(|p| p.len() == i.pages.len()))
parse_range(range, count).is_ok_and(|p| p.len() == count)
}
/// Page `page_index` (0-based) read from a PDF or `.ai` (`read`, as [`super::page_document`] reads
@@ -306,6 +333,8 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
None => err(format!("can't open `{name}`: not a format VectorCraft reads (see document.formats)")),
})?;
let title = file_name(name);
// The File Info a PDF, `.ai` or `.ait` gives.
let mut file_info = None;
let mut converted = false;
let mut preview_only = false;
let mut editing_data = false;
@@ -332,47 +361,86 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
restore_or_import(editing, || import_svg(&text, folder.as_deref()))?
}
"pdf" | "ai" | "ait" => {
// The file is read and checked once, for the document it carries, its pages, the
// editor's copy and its File Info.
let opened = vectorcraft_pdf::open_pdf(bytes, opts.password.as_deref());
// Saved with Preserve Editing: the document it carries, unless some pages are picked.
let editing = opts
.pages
.is_none()
.then(|| vectorcraft_pdf::editing_with(bytes, opts.password.as_deref()))
let editing = (opts.pages.is_none() && opts.native)
.then(|| opened.as_ref().ok().and_then(|o| o.editing()))
.flatten()
.map(|e| (e.intact, move || Some(e.data)));
restore_or_import(editing, || match super::pdfimport::import(bytes, opts, format.id != "pdf") {
Ok(r) => {
// Pages of text alone: the editing copy alone where it reads, as for a file
// saved without its PDF part (#1387: else the page, which is the art). So too
// pages that draw nothing at all: there is no page art to check the layers
// against, and the empty page would lose all of it.
// A page is empty only when nothing on it was skipped (an image that can't be
// decoded draws nothing either): its notes are at most the page's own.
let empty = draws_nothing(&r.document) && r.warnings.iter().all(|w| is_page_note(w));
let alone = (r.only_text || empty)
.then(|| from_editing_data_alone(bytes, opts))
.flatten()
.and_then(|read| read.ok())
.map(|(doc, warnings)| outlined_if_asked(doc, warnings, opts));
let (doc, warnings, read) = match alone {
Some((doc, warnings)) => (doc, warnings, true),
None => through_editing_data(bytes, opts, r.document, r.warnings, r.user_unit),
};
editing_data = read;
Ok((doc, warnings))
let imported = || match &opened {
Ok(o) => super::pdfimport::import(bytes, o, opts, format.id != "pdf"),
Err(e) => Err(err(e)),
};
let read = restore_or_import(editing, || {
// Type all from the text document and nothing that needs the PDF part: the layers
// alone, the PDF part not imported. Else what was read of the layers is kept for
// reading them with the PDF part.
let mut layers = None;
if let Some((o, private)) = opened.as_ref().ok().filter(|_| reads_layers_alone(opts)).and_then(|o| Some((o, editing_copy(o, opts)?)))
{
let pages = o.trim_pages();
match vectorcraft_eps::ai_layers_alone(&private, &pages.sizes, pages.user_unit) {
Ok((mut doc, warnings)) => {
doc.setup.bleed = pages.bleed;
editing_data = true;
return Ok((doc, warnings));
}
Err(read) => layers = Some(read),
}
}
// Saved without its PDF part: the editing copy is all the file has (`pages` that
// name every page read it as the whole file).
Err(e) if is_placeholder(&e) => {
let whole = LoadOptions { pages: None, ..opts.clone() };
from_editing_data_alone(bytes, if every_page(bytes, opts) { &whole } else { opts })
match imported() {
Ok(r) => {
// The editor's copy, read once the import is done with the pages, unless
// its layers were read before it.
let private = layers.is_none().then(|| opened.as_ref().ok().and_then(|o| editing_copy(o, opts))).flatten();
// Pages of text alone: the editing copy alone where it reads, as for a file
// saved without its PDF part (#1387: else the page, which is the art). So too
// pages that draw nothing at all: there is no page art to check the layers
// against, and the empty page would lose all of it.
// A page is empty only when nothing on it was skipped (an image that can't be
// decoded draws nothing either): its notes are at most the page's own.
let empty = draws_nothing(&r.document) && r.warnings.iter().all(|w| is_page_note(w));
let copy_alone = || match &private {
Some(private) => Some(editing_copy_alone(private)),
None if layers.is_some() => opened.as_ref().ok().and_then(|o| editing_copy(o, opts)).map(|p| editing_copy_alone(&p)),
None => None,
};
let alone = (r.only_text || empty)
.then(copy_alone)
.flatten()
.and_then(|read| read.ok())
.map(|(doc, warnings)| outlined_if_asked(doc, warnings, opts));
let (doc, warnings, read) = match alone {
Some((doc, warnings)) => (doc, warnings, true),
None => {
let layers = layers.or_else(|| private.as_deref().map(vectorcraft_eps::AiLayers::decode));
through_editing_data(layers, opts, r.document, r.warnings, r.user_unit)
}
};
editing_data = read;
Ok((doc, warnings))
}
// Saved without its PDF part: the editing copy is all the file has (`pages` that
// name every page read it as the whole file).
Err(e) if is_placeholder(&e) => opened
.as_ref()
.ok()
.and_then(|o| from_editing_data_alone(o, opts))
.unwrap_or(Err(e))
.map(|(doc, warnings)| outlined_if_asked(doc, warnings, opts))
.inspect(|_| editing_data = true)
.inspect(|_| editing_data = true),
// A PDF part that can't be read (a stream the import refuses): the editing copy
// alone where it reads, else the error.
Err(e) => without_pdf_part(bytes, opts, &e).inspect(|_| editing_data = true).ok_or(e),
}
// A PDF part that can't be read (a stream the import refuses): the editing copy
// alone where it reads, else the error.
Err(e) => without_pdf_part(bytes, opts, &e).inspect(|_| editing_data = true).ok_or(e),
})?
})?;
// The File Info of a file read from its pages or its editing copy.
if !read.2 {
file_info = opened.as_ref().ok().map(|o| o.file_info());
}
read
}
"dxf" => {
let (doc, warnings) = super::dxfimport::import(bytes, &opts.dxf)?;
@@ -394,7 +462,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
// it carries, opens with the File Info it gives (a PostScript `.ai` gives none).
if matches!(format.id, "pdf" | "ai" | "ait")
&& !restored
&& let Some(info) = vectorcraft_pdf::file_info(bytes, opts.password.as_deref())
&& let Some(info) = file_info
{
super::super::fileinfo::read_pdf(&mut doc.metadata, info);
}
+6
View File
@@ -105,6 +105,12 @@ pub const AI_OPTIONS: &[FormatOption] = &[
default: "true",
description: "compress the PDF's content and the native document it carries (the PDF option compression.compressText)",
},
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)",
},
FormatOption {
name: "aiVersion",
ty: "string",
+14 -3
View File
@@ -263,7 +263,7 @@ pub const EDITING_NEEDS_EVERY_ARTBOARD: &str =
pub fn encode(cmd: &str, doc: &Document, p: &Value) -> Result<(Vec<u8>, Vec<String>)> {
// Keep the editable object tree independent of preview fallbacks used by the drawn pages.
let (full, mut warnings) = crate::cmd::place::document::full_documents(doc);
let (bytes, drawn_warnings) = encode_carrying(cmd, &full, p, || Ok(vectorcraft_format::save(doc, false)))?;
let (bytes, drawn_warnings) = encode_carrying(cmd, &full, p, || Ok(vectorcraft_format::save(doc, false)), || Ok(None))?;
warnings.extend(drawn_warnings);
warnings.extend(overflow_warning(cmd, &full, p)?);
Ok((bytes, warnings))
@@ -281,8 +281,15 @@ fn overflow_warning(cmd: &str, doc: &Document, p: &Value) -> Result<Option<Strin
}
/// [`encode`] the pages of `doc`, carrying `native()` as the editing data (a `.ai` file: the
/// native document with its save options, whose pages may be left blank).
pub(super) fn encode_carrying(cmd: &str, doc: &Document, p: &Value, native: impl FnOnce() -> Result<Vec<u8>>) -> Result<(Vec<u8>, Vec<String>)> {
/// native document with its save options, whose pages may be left blank), and `private()`, the
/// editing copy of the art for other apps with what it couldn't hold, on every page.
pub(super) fn encode_carrying(
cmd: &str,
doc: &Document,
p: &Value,
native: impl FnOnce() -> Result<Vec<u8>>,
private: impl FnOnce() -> Result<Option<(vectorcraft_pdf::PrivateData, Vec<String>)>>,
) -> Result<(Vec<u8>, Vec<String>)> {
let mut opts = options(cmd, doc, p)?;
// The pages' background colors, behind the art (the editing data keeps them as colors).
let pages = opts.artboards.clone().unwrap_or_else(|| (0..doc.artboards.len()).collect());
@@ -295,6 +302,10 @@ pub(super) fn encode_carrying(cmd: &str, doc: &Document, p: &Value, native: impl
if opts.settings.preserve_editing {
if opts.artboards.as_ref().is_none_or(|v| v.iter().copied().eq(0..doc.artboards.len())) {
opts.native = Some(native()?);
if let Some((data, lost)) = private()? {
opts.private_data = Some(data);
warnings.extend(lost);
}
} else {
opts.settings.preserve_editing = false;
warnings.push(EDITING_NEEDS_EVERY_ARTBOARD.to_string());
+37 -25
View File
@@ -39,6 +39,9 @@ pub struct LoadOptions {
/// A `.ai` opens from its editing copy even where that draws differently from its PDF part
/// (which can be older than it), with a warning, instead of from the PDF part.
pub trust_editing_data: bool,
/// A PDF or `.ai` saved with Preserve Editing opens from the VectorCraft document it carries;
/// off, it opens as another app would open it, from the editing copy of its art or its pages.
pub native: bool,
}
impl Default for LoadOptions {
@@ -54,6 +57,7 @@ impl Default for LoadOptions {
dxf: Default::default(),
editing_data: true,
trust_editing_data: false,
native: true,
}
}
}
@@ -91,28 +95,25 @@ impl LoadOptions {
Some(v) => (v.as_bool().ok_or_else(|| bad(cmd, "editingData must be true, false or \"always\""))?, false),
};
let dxf = super::dxfimport::options(cmd, p.get("dxf"))?;
Ok(Self { pages, crop, password, color_mode, grays, text_as, layers, dxf, editing_data, trust_editing_data })
Ok(Self { pages, crop, password, color_mode, grays, text_as, layers, dxf, editing_data, trust_editing_data, native: true })
}
/// Does the document read only part of the file, or read it differently (a page range, another
/// box, a password, without its hidden layers)? Writing it back would lose the rest, so Save
/// doesn't (it asks for a name).
/// box, a password, without its hidden layers, without the VectorCraft document it carries)?
/// Writing it back would lose the rest, so Save doesn't (it asks for a name).
pub fn is_partial(&self) -> bool {
self.pages.is_some() || self.crop != CropTo::default() || self.password.is_some() || !self.layers
self.pages.is_some() || self.crop != CropTo::default() || self.password.is_some() || !self.layers || !self.native
}
/// The PDF import options: `pages` resolved against the file's page count. A PDF-compatible
/// `.ai`, or a PDF saved with its editing data, asked for its crop box opens on its trim boxes,
/// its editor's artboards, with the bleed round them (its crop box takes the bleed in).
fn import_options(&self, bytes: &[u8], editor_document: bool) -> Result<ImportOptions> {
fn import_options(&self, opened: &vectorcraft_pdf::Opened, editor_document: bool) -> Result<ImportOptions> {
let pages = match &self.pages {
None => None,
Some(range) => {
let count = vectorcraft_pdf::info(bytes, self.password.as_deref()).map_err(err)?.pages.len();
Some(parse_range(range, count).map_err(|e| err(format!("pages: {e}")))?)
}
Some(range) => Some(parse_range(range, opened.page_count()).map_err(|e| err(format!("pages: {e}")))?),
};
let is_ai = self.crop == CropTo::Crop && vectorcraft_pdf::has_illustrator_data(bytes, self.password.as_deref());
let is_ai = self.crop == CropTo::Crop && opened.has_illustrator_data();
Ok(ImportOptions {
pages,
crop: if is_ai { CropTo::Trim } else { self.crop },
@@ -136,24 +137,33 @@ fn choice<T: Choice + Default>(cmd: &str, key: &str, id: Option<&str>) -> Result
.ok_or_else(|| bad(cmd, format!("{key} must be one of {}", T::IDS.join(", "))))
}
/// Import the pages `o` pick → the document, import notes and what else the import tells.
/// Import the pages `o` pick of `opened`, the PDF `bytes` already read
/// ([`vectorcraft_pdf::open_pdf`]) → the document, import notes and what else the import tells.
/// `editor_document`: a `.ai` file.
pub(super) fn import(bytes: &[u8], o: &LoadOptions, editor_document: bool) -> Result<vectorcraft_pdf::ImportReport> {
vectorcraft_pdf::import_with_report(bytes, &o.import_options(bytes, editor_document)?).map_err(err)
pub(super) fn import(
bytes: &[u8],
opened: &vectorcraft_pdf::Opened,
o: &LoadOptions,
editor_document: bool,
) -> Result<vectorcraft_pdf::ImportReport> {
let options = o.import_options(opened, editor_document)?;
vectorcraft_pdf::import_opened(bytes, opened, &options).map_err(err)
}
/// Page `page` (0-based) of a PDF as a document of one artboard (its `o.crop` box) and one
/// layer of what it shows, with the same text choice as Open, and the import notes.
pub fn page_document(bytes: &[u8], page: usize, o: &LoadOptions) -> Result<(Document, Vec<String>)> {
let opts = ImportOptions {
pages: Some(vec![page]),
crop: o.crop,
password: o.password.clone(),
text_as: o.text_as,
layers: false,
..Default::default()
};
vectorcraft_pdf::import_with_report(bytes, &opts).map(|r| (r.document, r.warnings)).map_err(err)
vectorcraft_pdf::import_with_report(bytes, &page_options(page, o)).map(|r| (r.document, r.warnings)).map_err(err)
}
/// [`page_document`] of `opened`, the PDF `bytes` already read.
fn opened_page_document(bytes: &[u8], opened: &vectorcraft_pdf::Opened, page: usize, o: &LoadOptions) -> Result<(Document, Vec<String>)> {
vectorcraft_pdf::import_opened(bytes, opened, &page_options(page, o)).map(|r| (r.document, r.warnings)).map_err(err)
}
/// The import options of [`page_document`].
fn page_options(page: usize, o: &LoadOptions) -> ImportOptions {
ImportOptions { pages: Some(vec![page]), crop: o.crop, password: o.password.clone(), text_as: o.text_as, layers: false, ..Default::default() }
}
const INFO: &str = "document.pdfInfo";
@@ -166,13 +176,15 @@ pub(super) fn pdf_info(_: &mut Session, p: &Value) -> Result<Value> {
if bytes.starts_with(b"%!") || vectorcraft_pdf::is_postscript(&bytes) {
return postscript_info(&bytes, p);
}
let info = match vectorcraft_pdf::info(&bytes, o.password.as_deref()) {
Ok(i) => i,
// The file is read once, for its pages and the thumbnail.
let opened = match vectorcraft_pdf::open_pdf(&bytes, o.password.as_deref()) {
Ok(opened) => opened,
Err(e @ (PdfError::NeedsPassword | PdfError::WrongPassword)) => {
return Ok(json!({"pages": 0, "needsPassword": true, "wrongPassword": e == PdfError::WrongPassword, "pageInfo": []}));
}
Err(e) => return Err(err(e)),
};
let info = opened.info();
let r4 = |r: vectorcraft_geom::Rect| json!([r.x0, r.y0, r.x1, r.y1]);
let pages: Vec<Value> = info
.pages
@@ -184,7 +196,7 @@ pub(super) fn pdf_info(_: &mut Session, p: &Value) -> Result<Value> {
.collect();
let mut out = json!({"pages": pages.len(), "needsPassword": false, "pageInfo": pages});
if let Some(page) = thumbnail_page(p, info.pages.len(), "PDF")? {
let (doc, _) = page_document(&bytes, page, &o)?;
let (doc, _) = opened_page_document(&bytes, &opened, page, &o)?;
out["thumbnail"] = json!(thumbnail(&doc, p)?);
}
Ok(out)
+10 -3
View File
@@ -24,8 +24,8 @@ const TRUNCATED: &str = "the Pixar file is cut short";
/// define.
const DAMAGED: &str = "the Pixar file's header is damaged";
/// The message for encoded tile data with a packet the format doesn't define, or one that runs
/// past the end of its scan line.
/// The message for a tile pointer into the header or the tile pointer table, and for encoded tile
/// data with a packet the format doesn't define, or one that runs past the end of its scan line.
const BAD_DATA: &str = "the Pixar file's image data is damaged";
/// The channel bits of the picture format field (header byte 424): R, G, B and A, stored in this
@@ -115,7 +115,9 @@ pub(super) fn decode(bytes: &[u8], max_alloc: u64) -> Result<image::RgbaImage, S
let layout =
Layout { gray: format & 0b1110 == 0b1000, matted: alpha_mode == 0, alpha: format & 1 != 0, sample: if wide { 2 } else { 1 }, wide, stored };
let (across, down) = (w.div_ceil(tile_w), h.div_ceil(tile_h));
let table = bytes.get(HEADER..HEADER + across * down * 8).ok_or(TRUNCATED)?;
// A table end past the largest address is past the end of the file too.
let table_end = across.checked_mul(down).and_then(|n| n.checked_mul(8)).and_then(|n| n.checked_add(HEADER)).ok_or(TRUNCATED)?;
let table = bytes.get(HEADER..table_end).ok_or(TRUNCATED)?;
let empty = if layout.alpha { [0; 4] } else { [0, 0, 0, 255] };
let mut img = image::RgbaImage::from_pixel(w as u32, h as u32, image::Rgba(empty));
// The encoded data read in all, which a file whose tiles each hold their own data stays within.
@@ -131,6 +133,11 @@ pub(super) fn decode(bytes: &[u8], max_alloc: u64) -> Result<image::RgbaImage, S
if length == -1 || pointer >= bytes.len() {
return Err(TRUNCATED.into());
}
// Tile data follows the tile pointer table; a pointer into the header or the table would
// read them as pixels.
if pointer < table_end {
return Err(BAD_DATA.into());
}
let (x0, y0) = (n % across * tile_w, n / across * tile_h);
// The part of the tile inside the picture; the pixels of border tiles past its edges are
// stored and skipped.
+104 -14
View File
@@ -249,11 +249,6 @@ pub fn save_plan(s: &Session, mode: SaveMode, p: &Value) -> Result<SavePlan> {
if let Some((key, top, inner)) = disagreeing_option(p, is_svg(format)).map_err(|e| bad(cmd, e))? {
return Err(bad(cmd, format!("`{key}: {top}` and `options.{key}: {inner}` disagree: give the option once")));
}
let notes = NATIVE_OPTIONS
.iter()
.filter(|k| p.get(**k).is_some_and(|v| !v.is_null()) && !reads_option(format, k))
.map(|k| format!("`{k}` was not used: {} files don't read it", format.label))
.collect();
let mut given: Map<String, Value> = match p.get("options") {
Some(Value::Object(o)) => o.iter().filter(|(k, _)| reads_option(format, k)).map(|(k, v)| (k.clone(), v.clone())).collect(),
None | Some(Value::Null) => Map::new(),
@@ -293,6 +288,12 @@ pub fn save_plan(s: &Session, mode: SaveMode, p: &Value) -> Result<SavePlan> {
if let Some(path) = &path {
super::check_not_lossy_overwrite(st, path, p, cmd)?;
}
let written = written_as(cmd, format, &Value::Object(options.clone()));
let notes = NATIVE_OPTIONS
.iter()
.filter(|k| p.get(**k).is_some_and(|v| !v.is_null()) && !reads_option(format, k))
.map(|k| format!("`{k}` was not used: {} files don't read it", written.label))
.collect();
Ok(SavePlan { mode, path, format, options, name, folder, modified, notes })
}
@@ -575,6 +576,28 @@ fn blank_pages(doc: &Document) -> Document {
/// Why a `.ai` file saved without PDF content looks empty elsewhere.
const NOT_PDF_COMPATIBLE: &str = "saved without PDF content: VectorCraft opens it as before, other apps show empty pages";
/// The same, for a file that carries the editing copy of its art.
const NOT_PDF_COMPATIBLE_EDITING: &str =
"saved without PDF content: VectorCraft and apps that read its editing data open it, other apps show empty pages";
/// `f` (`.ai` or `.ait`) named, in its option errors, as a file saved without PDF content.
fn without_pdf(f: &Format) -> Format {
let label = if f.id == "ait" { "non-PDF-compatible .ait template" } else { "non-PDF-compatible .ai" };
Format { label, ..*f }
}
/// `f` named, in its errors and notes, as the file a save with options `p` writes: a version 7
/// `.ai` as the legacy `.ai`, and a `.ai` or `.ait` with `pdfCompatible: false` as one saved
/// without PDF content.
fn written_as(cmd: &str, f: &Format, p: &Value) -> Format {
if f.id == "ai" && super::legacy_ai::wanted(cmd, f, p).unwrap_or(false) {
super::legacy_ai::named(f)
} else if matches!(f.id, "ai" | "ait") && !bool_or(p, "pdfCompatible", true) {
without_pdf(f)
} else {
*f
}
}
/// `e`, an error of the export encoders, under the save command `cmd` instead of
/// `document.export`.
@@ -585,8 +608,39 @@ fn named_for_save(cmd: &str, e: crate::EngineError) -> crate::EngineError {
}
}
/// The shared Save and Export encoder for PDF-compatible `.ai` files (and `.ait` templates, the
/// same file).
/// Refuse the artboards a `.ai` or `.ait` save is given (`artboard`, `artboards`, or a `range`
/// that isn't empty) when one of them is not in `doc`, with the error an export gives. The save
/// then writes every artboard, or a legacy `.ai` file's `range`, whatever `artboard` and
/// `artboards` name. An empty `artboards` list is not refused: the save writes every artboard.
fn named_artboards_exist(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result<()> {
let n = doc.artboards.len();
// The encoders refuse a document without artboards themselves.
if n == 0 {
return Ok(());
}
// The encoders refuse a value of the wrong type themselves, each with its own label.
let Ok(mut picked) = super::encode::options::<ArtboardPick>(&written_as(cmd, f, p), p) else {
return Ok(());
};
picked.range = picked.range.filter(|r| !r.trim().is_empty());
if picked.range.is_none() && picked.artboards.as_ref().is_some_and(Vec::is_empty) {
return Ok(());
}
picked.resolve(n).map_err(|e| bad(cmd, e))?;
Ok(())
}
/// The `.ai` option `editingData`: whether the file also carries the editing copy of the art that
/// other apps read (default on).
#[derive(Default, serde::Deserialize)]
#[serde(default, rename_all = "camelCase")]
struct AiEditingData {
editing_data: Option<bool>,
}
/// The shared Save and Export encoder for `.ai` files (and `.ait` templates, the same file):
/// PDF-compatible by default, without PDF content (`pdfCompatible: false`), or legacy version 7
/// `.ai` files (`aiVersion: "7"`).
pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result<Encoded> {
if super::legacy_ai::wanted(cmd, f, p)? {
return super::legacy_ai::encode(cmd, f, doc, p);
@@ -605,8 +659,9 @@ pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Res
}
}
}
let native_options = super::native::ai_options(cmd, f, doc, &params)?;
let pdf_compatible = bool_or(&params, "pdfCompatible", true);
let f = &if pdf_compatible { *f } else { without_pdf(f) };
let native_options = super::native::ai_options(cmd, f, doc, &params)?;
if !pdf_compatible {
let picked: ArtboardPick = super::encode::options(f, &params)?;
let picked = picked.resolve(doc.artboards.len()).map_err(|e| bad(cmd, e))?;
@@ -614,16 +669,46 @@ pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Res
return Err(bad(cmd, "pdfCompatible: false needs every artboard to keep the editable artwork"));
}
}
let pages = doc.without_edit_modes();
let edited = doc.without_edit_modes();
// Resolve placed files only for the drawn pages. Missing files become preview images there;
// the native attachment keeps the original placed objects and their relinkable metadata.
let (pages, placed_warnings) =
if pdf_compatible { crate::cmd::place::document::full_documents(&pages) } else { (std::borrow::Cow::Owned(blank_pages(&pages)), Vec::new()) };
let (pages, placed_warnings) = if pdf_compatible {
crate::cmd::place::document::full_documents(&edited)
} else {
(std::borrow::Cow::Owned(blank_pages(&edited)), Vec::new())
};
let native = || super::native::ai_native(cmd, doc, &native_options);
let (bytes, mut warnings) = super::pdf::encode_carrying(cmd, &pages, &params, native)?;
let other_apps: AiEditingData = super::encode::options(f, &params)?;
let carries_editing = std::cell::Cell::new(false);
let private = || {
if !other_apps.editing_data.unwrap_or(true) {
return Ok(None);
}
// The art with placed files resolved as the pages draw them, also when the pages are blank.
let resolved;
let (art, mut resolved_warnings): (&Document, Vec<String>) = if pdf_compatible {
(&pages, Vec::new())
} else {
let (d, w) = crate::cmd::place::document::full_documents(&edited);
resolved = d;
(&resolved, w)
};
// With the artboards' background colors, as the pages draw them.
let art = super::export::with_artboard_fills(art, &params, 0..art.artboards.len()).map_err(|e| bad(cmd, e))?;
let o = vectorcraft_eps::AiEditingOptions {
title: doc.title.clone(),
created: doc.metadata.created.or_else(vectorcraft_doc::metadata::output_time),
};
let (data, lost) = vectorcraft_eps::ai_private_data(&art, &o).map_err(|e| bad(cmd, e))?;
// Placed files that weren't found are written as their previews here too.
resolved_warnings.extend(lost);
carries_editing.set(true);
Ok(Some((data, resolved_warnings)))
};
let (bytes, mut warnings) = super::pdf::encode_carrying(cmd, &pages, &params, native, private)?;
warnings.extend(placed_warnings);
if !pdf_compatible {
warnings.push(NOT_PDF_COMPATIBLE.to_string());
warnings.push(if carries_editing.get() { NOT_PDF_COMPATIBLE_EDITING } else { NOT_PDF_COMPATIBLE }.to_string());
}
Ok(Encoded { warnings, ..Encoded::one(bytes) })
}
@@ -673,11 +758,16 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option<i
let boards = separate_boards(cmd, plan.format, &doc, &params)?;
let mut params = super::pdf::expand_preset(s, cmd, &params)?.into_owned();
let legacy = super::legacy_ai::wanted(cmd, plan.format, &params)?;
if matches!(plan.format.id, "ai" | "ait") {
named_artboards_exist(cmd, plan.format, &doc, &params)?;
}
if let (Some(o), "ai" | "ait") = (params.as_object_mut(), plan.format.id) {
// Save keeps every artboard; exports may choose a subset instead. A legacy .ai file per
// artboard keeps a range given: the artboards to save.
let chosen = legacy && plan.format.id == "ai" && o.get("range").and_then(Value::as_str).is_some_and(|r| !r.trim().is_empty());
if !chosen {
// A `range` that isn't text is left for the encoder to refuse, as an export refuses it.
let text = o.get("range").is_none_or(|r| r.is_string() || r.is_null());
if !chosen && text {
o.insert("range".into(), json!("all"));
}
}
+205 -16
View File
@@ -82,6 +82,25 @@ fn an_illustrator_ai_file_opens_from_its_editing_data() {
assert_ne!(names(&s.doc().unwrap().doc.layers), ["Art", "Hidden"]);
}
/// Opening a `.ai` or a PDF whose PDF part reads, or a `.ai` saved without PDF compatibility,
/// reads and checks the file once, on any thread, for the document it may carry, its pages, its
/// editing data and its File Info, with pages picked or not.
#[test]
fn an_ai_or_pdf_file_is_read_once_when_it_opens() {
let ai_file = ai::ai(&compressed(&ai::sample_data()), ai::page_pdf());
let pdf_file = pdf_with(&[PdfPage::new(100.0, 100.0, "0 0 1 rg 10 10 50 50 re f")], &[], None);
let placeholder = ai::ai(&compressed(&ai::sample_data()), PLACEHOLDER);
for (name, file) in [("art.ai", &ai_file), ("art.pdf", &pdf_file), ("placeholder.ai", &placeholder)] {
for opts in [LoadOptions::default(), LoadOptions { pages: Some("1".into()), ..Default::default() }] {
let before = vectorcraft_pdf::reads_of(file);
let loaded = load_with(name, file, &opts).unwrap();
assert_eq!(vectorcraft_pdf::reads_of(file) - before, 1, "{name}, pages {:?}", opts.pages);
let editing_data = name == "placeholder.ai" || (name == "art.ai" && opts.pages.is_none());
assert_eq!(loaded.editing_data, editing_data, "{name}, pages {:?}", opts.pages);
}
}
}
#[test]
fn an_ai_file_opens_with_its_artboard_options_raster_settings_and_author() {
let document = "%_/Document :\n%_/Dictionary :\n%_/Dictionary :\n%_150 /Int (dpi.) ,\n%_1 /Bool (mask) ,\n%_; (AI Auto Rasterize) ,\n\
@@ -127,6 +146,45 @@ fn an_ai_unread_group_keeps_its_layers_and_live_neighbor() {
assert!(result["warnings"].to_string().contains("`ZZ` (1)"), "{result}");
}
#[test]
fn a_differing_object_keeps_the_layers_with_a_note() {
let square = |cmyk: &str, x: f64| format!("{cmyk} k\n{}f\n", ai::rect(x, 40.0, x + 16.0, 56.0));
let front = square("0 0 0 1", 90.0) + &square("0 0 1 0", 160.0);
let data = ai::editing_data(200.0, 100.0, &(ai::layer("Back", &square("0 0 1 0", 20.0)) + &ai::layer("Front", &front)));
let page = "0 0 1 0 k 20 40 16 16 re f 1 0 0 0 k 90 40 16 16 re f 0 0 1 0 k 160 40 16 16 re f";
let mut session = Session::new();
let result = open(&mut session, "differs.ai", &ai::ai(&compressed(data.as_bytes()), page), json!({})).unwrap();
let doc = &session.doc().unwrap().doc;
assert_eq!(names(&doc.layers), ["Back", "Front"], "{result}");
let front = doc.layers[1].children().unwrap();
assert!(matches!(front[0].kind, NodeKind::Group { .. }) && matches!(front[1].kind, NodeKind::Path { .. }), "{result}");
let replacement = &front[0].children().unwrap()[0];
assert!(
matches!(replacement.appearance.items.first(), Some(vectorcraft_doc::AppearanceItem::Fill(fill))
if fill.paint == vectorcraft_color::Paint::solid(vectorcraft_color::Color::cmyk(1.0, 0.0, 0.0, 0.0))),
"{result}"
);
assert!(
result["warnings"].to_string().contains("objects that drew differently from the file's own page came in as its art: Front (1)"),
"{result}"
);
// An export to the file's own path is refused unless it is given `acknowledgeLoss`.
let d = std::env::temp_dir().join(format!("vc-aidiffers-{}", std::process::id()));
std::fs::create_dir_all(&d).unwrap();
let path = d.join("differs.ai");
let file = ai::ai(&compressed(data.as_bytes()), page);
std::fs::write(&path, &file).unwrap();
let path = path.to_string_lossy().to_string();
let mut s = Session::new();
s.execute("document.open", &json!({"path": path})).unwrap();
let e = s.execute("document.export", &json!({"path": path})).unwrap_err().to_string();
assert!(e.contains("left things out") && e.contains("objects that drew differently"), "{e}");
assert_eq!(std::fs::read(&path).unwrap(), file);
s.execute("document.export", &json!({"path": path, "acknowledgeLoss": true})).unwrap();
assert_ne!(std::fs::read(&path).unwrap(), file);
std::fs::remove_dir_all(d).ok();
}
/// A palette of three swatches and a color group `Inks` holding a fourth.
const INKS_PALETTE: &str = "%AI5_BeginPalette\n0 0 Pb\n0 0 0 0 1 1 1 Xa\n(White)\nPc\n0.04 0.3 0 0 81.96 21 -8 (Pink ink) 0 2 Xx\n(Pink ink)\nPc\n\
0.06 0.98 1 0 (Red ink) 0 x\n(Red ink)\nPc\n1 (Inks) 1 Pg\n0.02 0.1 1 0 (Yellow ink) 0 x\n(Yellow ink)\nPc\nPB\n%AI5_EndPalette\n";
@@ -617,21 +675,25 @@ fn what_the_reader_doesnt_read_opens_as_before_with_a_warning() {
/// A `.ai` whose document data has a variable library opens with its variables, data sets, active
/// data set and lock, whether its layers are read or it comes in as its PDF part: `variable.list`
/// and `dataset.list` report them. A variable of unknown kind can't be bound. What of the library
/// can't be read is noted.
/// can't be read is noted. With its layers read, the object a variable is bound to comes in bound,
/// and selecting a data set changes it; the bindings to objects the file doesn't have are noted.
#[test]
fn an_ai_file_opens_its_variable_library() {
let library = ai::variable_library_data(&ai::sample_variable_sets("variableAndTypes", &[]));
let square = format!("0 1 1 0 1 0 0 Xa\n{}f\n", ai::rect(10.0, 50.0, 40.0, 90.0));
let square = format!("0 1 1 0 1 0 0 Xa\n{}f\n{}", ai::rect(10.0, 50.0, 40.0, 90.0), ai::named("path_x5F_1"));
let notes = |r: &Value| {
r["warnings"].as_array().map_or(vec![], |w| w.iter().filter(|w| w.as_str().unwrap().contains("variable")).cloned().collect::<Vec<_>>())
};
let check = |s: &mut Session| {
let skipped = |n: usize| {
json!(format!("the file's variable bindings weren't all read (bindings skipped: {n}): those objects aren't bound to their variables"))
};
let check = |s: &mut Session, bound: usize| {
let r = s.execute("variable.list", &json!({})).unwrap();
assert_eq!(
r,
json!({"variables": [
{"name": "v_text", "kind": "text", "bindings": 0},
{"name": "v_visible", "kind": "visibility", "bindings": 0},
{"name": "v_visible", "kind": "visibility", "bindings": bound},
{"name": "v_file", "kind": "image", "bindings": 0},
{"name": "v_graph", "kind": "graph", "bindings": 0},
{"name": "v_unbound", "kind": "unknown", "bindings": 0},
@@ -651,23 +713,34 @@ fn an_ai_file_opens_its_variable_library() {
let file = ai::ai(&compressed(layered.as_bytes()), "1 0 0 rg 10 50 30 40 re f");
let r = open(&mut s, "variables.ai", &file, json!({})).unwrap();
assert_eq!(names(&s.doc().unwrap().doc.layers), ["Art"], "{r}");
assert!(notes(&r).is_empty(), "{r}");
check(&mut s);
let id = s.doc().unwrap().doc.layers[0].children().unwrap()[0].id.0;
let e = s.execute("variable.bind", &json!({"variable": "v_unbound", "ids": [id]})).unwrap_err();
// The library's text and image variables are bound to objects the file doesn't have.
assert_eq!(notes(&r), [skipped(2)], "{r}");
check(&mut s, 1);
let id = s.doc().unwrap().doc.layers[0].children().unwrap()[0].id;
assert_eq!(s.doc().unwrap().doc.variables.objects_of("v_visible"), [id]);
s.execute("dataset.select", &json!({"name": "ds_two"})).unwrap();
assert!(!s.doc().unwrap().doc.node(id).unwrap().visible, "ds_two hides the square");
s.execute("dataset.select", &json!({"name": "ds_one"})).unwrap();
assert!(s.doc().unwrap().doc.node(id).unwrap().visible, "ds_one shows it");
let e = s.execute("variable.bind", &json!({"variable": "v_unbound", "ids": [id.0]})).unwrap_err();
assert!(e.to_string().contains("a variable of unknown kind can't be bound to objects"), "{e}");
// Its layers can't be read (a symbol): it comes in as its PDF part, with the library.
// Its layers can't be read (a symbol): it comes in as its PDF part, with the library and none
// of its bindings.
let symbols = ai::editing_data(200.0, 100.0, &format!("{library}{}", ai::layer("Art", "/SymbolInstance :\n(Dot) /SymbolRef ,\n;\n")));
let r = open(&mut s, "symbols.ai", &ai::ai(&compressed(symbols.as_bytes()), ai::page_pdf()), json!({})).unwrap();
assert!(r["warnings"].to_string().contains("PDF part"), "{r}");
assert!(notes(&r).is_empty(), "{r}");
check(&mut s);
assert_eq!(notes(&r), [skipped(3)], "{r}");
check(&mut s, 0);
// A graph value isn't read: the note says how many entries were left out.
let graph = ai::xml_element("v_graph", &[], &[ai::xml_text(ai::XmlValue::Str("a,b"))]);
let partly = ai::variable_library_data(&ai::sample_variable_sets("none", &[graph]));
let layered = ai::editing_data(200.0, 100.0, &format!("{partly}{}", ai::layer("Art", &square)));
let r = open(&mut s, "graph.ai", &ai::ai(&compressed(layered.as_bytes()), "1 0 0 rg 10 50 30 40 re f"), json!({})).unwrap();
assert_eq!(notes(&r), [json!("the file's variable library was partly read (entries skipped: 1): the Variables panel lists the rest")], "{r}");
assert_eq!(
notes(&r),
[json!("the file's variable library was partly read (entries skipped: 1): the Variables panel lists the rest"), skipped(2)],
"{r}"
);
// Without a library, no note and no variables.
let plain = ai::editing_data(200.0, 100.0, &ai::layer("Art", &square));
let r = open(&mut s, "plain.ai", &ai::ai(&compressed(plain.as_bytes()), "1 0 0 rg 10 50 30 40 re f"), json!({})).unwrap();
@@ -1148,10 +1221,16 @@ fn half_outlined_line(y: f64, rest: &str, mode: u8) -> String {
/// text document (a line starting at (14, 65)), then `more` of a story the text document doesn't
/// have. Without `story` the file has no text document.
fn half_outlined_ai(story: Option<&str>, more: usize, type_content: &str) -> Vec<u8> {
half_outlined_ai_on(story, more, type_content, "", |page| page)
}
/// [`half_outlined_ai`] with the editing data's comments `head` before its art, whose page is
/// `page_of` the 200 × 100 pt page it draws on (other boxes, more entries).
fn half_outlined_ai_on(story: Option<&str>, more: usize, type_content: &str, head: &str, page_of: impl FnOnce(PdfPage) -> PdfPage) -> Vec<u8> {
let text = |story: u32| format!("/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n{story} /StoryIndex ,\n;\n");
let texts: String = std::iter::once(text(0)).chain((0..more).map(|_| text(99))).collect();
let mut body =
format!("%AI3_TemplateBox: 100 50 100 50\n{}", ai::layer("Art", &format!("0.5 g\n{}f\n{texts}", ai::rect(120.0, 20.0, 160.0, 60.0))));
format!("{head}%AI3_TemplateBox: 100 50 100 50\n{}", ai::layer("Art", &format!("0.5 g\n{}f\n{texts}", ai::rect(120.0, 20.0, 160.0, 60.0))));
if let Some(story) = story {
// The story's one line starts at the canvas center (8191.5, the template box's center) moved
// to (14, 65): its y runs down the page.
@@ -1182,7 +1261,7 @@ fn half_outlined_ai(story: Option<&str>, more: usize, type_content: &str) -> Vec
};
let cmap = "begincmap\n1 begincodespacerange\n<00> <FF>\nendcodespacerange\n1 beginbfchar\n<41> <FFFD>\nendbfchar\nendcmap\n";
pdf_with(
&[page],
&[page_of(page)],
&[&format!("<< /Length {} >>\nstream\n{data}\nendstream", data.len()), &format!("<< /Length {} >>\nstream\n{cmap}endstream", cmap.len())],
None,
)
@@ -1214,6 +1293,12 @@ fn texts(s: &Session) -> Vec<String> {
/// (art x 10 to 90 and 110 to 190, y 10 to 90), then a band across the first frame (y 30 to 70),
/// made a wrap object with no offset when `wrap` is set.
fn wrapped_thread_ai(wrap: bool) -> Vec<u8> {
ai::ai(&wrapped_thread_data(wrap.then_some(0.0)), PLACEHOLDER)
}
/// The editing data of [`wrapped_thread_ai`], compressed, with the band a wrap object of `offset`
/// when one is given.
fn wrapped_thread_data(offset: Option<f64>) -> Vec<u8> {
// The template box is centred at (100, 50), the canvas centre 8191.5: y runs down the canvas.
let canvas = |x: f64, y: f64| (x + 8091.5, 8241.5 - y);
let rect = |x0: f64, y0: f64, x1: f64, y1: f64| {
@@ -1233,14 +1318,47 @@ fn wrapped_thread_ai(wrap: bool) -> Vec<u8> {
);
let lines: Vec<String> = ascii85(document.as_bytes()).as_bytes().chunks(60).map(|c| format!("%{}", String::from_utf8_lossy(c))).collect();
let frame = |f: u32| format!("/AI11Text :\n0 /FreeUndo ,\n{f} /FrameIndex ,\n0 /StoryIndex ,\n;\n");
let dict = if wrap { "%_/ArtDictionary :\n%_0 /Real (AI11TextWrapOffset) ,\n%_0 /Bool (AI11TextWrapInvert) ,\n%_;\n%_\n" } else { "" };
let dict = offset
.map(|o| format!("%_/ArtDictionary :\n%_{o} /Real (AI11TextWrapOffset) ,\n%_0 /Bool (AI11TextWrapInvert) ,\n%_;\n%_\n"))
.unwrap_or_default();
let art = format!("{}{}0.5 g\n{}f\n{dict}", frame(0), frame(1), ai::rect(10.0, 30.0, 90.0, 70.0));
let body = format!(
"%AI3_TemplateBox: 100 50 100 50\n{}%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n{}\n%AI11_EndTextDocument\n",
ai::layer("Art", &art),
lines.join("\n")
);
ai::ai(&compressed(ai::editing_data(200.0, 100.0, &body).as_bytes()), PLACEHOLDER)
compressed(ai::editing_data(200.0, 100.0, &body).as_bytes())
}
/// The wrap offset of the first frame of `doc`'s threaded type, as its text resolves it.
fn first_frame_wrap_offset(doc: &vectorcraft_doc::Document) -> f64 {
match &doc.node(doc.text_threads[0][0]).unwrap().kind {
NodeKind::Text(t) => t.wrap[0].wrap.offset,
_ => panic!("area type"),
}
}
/// A `.ai` in units of 10 points whose threaded area type flows around a wrap object of a 2 unit
/// offset opens with the type flowing round it 20 pt off, its PDF part read or not, and when its
/// PDF part can't be read. The default graphic styles of a file without its own aren't scaled.
#[test]
fn wrapped_type_in_units_of_ten_points_flows_round_the_wrap_at_its_size_in_points() {
let private = wrapped_thread_data(Some(2.0));
let page = "0.5 g 10 30 80 40 re f";
let refused = ai::ai_with_entries_and_content(&private, page, "/UserUnit 10", REFUSED_CONTENT);
// On the trim boxes the PDF part is imported, and the refused stream stops it.
let trim = LoadOptions { crop: vectorcraft_pdf::CropTo::Trim, ..Default::default() };
let files = [(ai::ai_with(&private, page, "/UserUnit 10"), LoadOptions::default()), (refused, trim)];
for (file, opts) in &files {
let loaded = load_with("thread.ai", file, opts).unwrap();
assert!(loaded.editing_data, "{:?}", loaded.warnings);
assert!((first_frame_wrap_offset(&loaded.doc) - 20.0).abs() < 0.01, "{:?}", loaded.warnings);
}
let loaded = load_with("thread.ai", &files[1].0, &files[1].1).unwrap();
assert!(loaded.warnings.iter().any(|w| w.starts_with("the PDF part couldn't be read")), "{:?}", loaded.warnings);
// The file has no graphic styles of its own: the default ones aren't scaled either way.
let read = load_with("thread.ai", &files[0].0, &files[0].1).unwrap();
assert_eq!(loaded.doc.graphic_styles, read.doc.graphic_styles);
}
/// Threaded area type below a wrap object flows around it when the file opens: the text the wrap
@@ -1285,6 +1403,77 @@ fn type_from_the_text_document_opens_without_the_pdf_parts_note_on_outlines() {
assert!(!r["warnings"].as_array().unwrap().contains(&without_outlines_note(1)), "{r}");
}
/// A `.ai` whose text document makes all of its type, with nothing unread, opens from its layers
/// without its PDF part being imported: a page that draws more than the layers isn't compared with
/// them. On its trim box it takes the pages' bleed, and pages in units of 10 points draw it ten
/// times as large, as when its PDF part is imported. With type the text document can't make,
/// editing data on a large canvas, its type asked for as outlines, another box or pages picked, the
/// PDF part is imported as before.
#[test]
fn type_all_from_the_text_document_opens_without_importing_the_pdf_part() {
let line = half_outlined_line(65.0, "rst draft", 0);
// The page draws a red square the layers don't have.
let differs = half_outlined_ai(Some("first draft"), 0, &format!("{line} 1 0 0 rg 20 20 30 30 re f"));
let mut s = Session::new();
let before = vectorcraft_pdf::imports_of(&differs);
let loaded = load_with("draft.ai", &differs, &LoadOptions::default()).unwrap();
assert_eq!(vectorcraft_pdf::imports_of(&differs), before, "{:?}", loaded.warnings);
assert!(loaded.editing_data, "{:?}", loaded.warnings);
assert!(!loaded.warnings.iter().any(|w| w.contains("differently")), "{:?}", loaded.warnings);
let r = open(&mut s, "draft.ai", &differs, json!({})).unwrap();
assert_eq!(names(&s.doc().unwrap().doc.layers), ["Art"], "{r}");
assert_eq!(texts(&s), ["first draft"], "{r}");
assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2, "the square and the type, without the page's red square: {r}");
// A 10 pt bleed round the trim box, the art drawn in the trim box.
let bled = half_outlined_ai_on(Some("first draft"), 0, &line, "", |p| PdfPage {
media: [0.0, 0.0, 220.0, 120.0],
bleed: Some([0.0, 0.0, 220.0, 120.0]),
trim: Some([10.0, 10.0, 210.0, 110.0]),
content: format!("1 0 0 1 10 10 cm {}", p.content),
..p
});
let before = vectorcraft_pdf::imports_of(&bled);
let loaded = load_with("bled.ai", &bled, &LoadOptions::default()).unwrap();
assert_eq!(vectorcraft_pdf::imports_of(&bled), before);
assert_eq!(loaded.doc.setup.bleed, [10.0; 4]);
// Pages of 10 pt units.
let large = half_outlined_ai_on(Some("first draft"), 0, &line, "", |p| PdfPage { entries: format!("{} /UserUnit 10", p.entries), ..p });
let before = vectorcraft_pdf::imports_of(&large);
let loaded = load_with("large.ai", &large, &LoadOptions::default()).unwrap();
assert_eq!(vectorcraft_pdf::imports_of(&large), before);
let board = loaded.doc.artboards[0].rect;
assert!((board.width() - 2000.0).abs() < 0.01 && (board.height() - 1000.0).abs() < 0.01, "{board:?}");
// Opened on the trim boxes with the PDF part imported and compared, as before, both files have
// the same artboards and bleed.
for file in [&bled, &large] {
let alone = load_with("draft.ai", file, &LoadOptions::default()).unwrap();
let compared = load_with("draft.ai", file, &LoadOptions { crop: vectorcraft_pdf::CropTo::Trim, ..Default::default() }).unwrap();
assert!(compared.editing_data, "{:?}", compared.warnings);
let boards = |d: &vectorcraft_doc::Document| d.artboards.iter().map(|a| a.rect).collect::<Vec<_>>();
assert_eq!(boards(&alone.doc), boards(&compared.doc));
assert_eq!(alone.doc.setup.bleed, compared.doc.setup.bleed);
assert_eq!(names(&alone.doc.layers), names(&compared.doc.layers));
// The file has no graphic styles of its own: the default ones aren't scaled.
assert_eq!(alone.doc.graphic_styles, compared.doc.graphic_styles);
}
// The PDF part is imported, once.
let unmade = half_outlined_ai(Some("first draft"), 1, &line);
// Editing data on a large canvas reads at its own scale when the file has no PDF part.
let canvas = half_outlined_ai_on(Some("first draft"), 0, &line, "%AI24_LargeCanvasScale: 2\n", |p| p);
let cases = [
(&unmade, LoadOptions::default()),
(&canvas, LoadOptions::default()),
(&differs, LoadOptions { text_as: vectorcraft_pdf::TextAs::Outlines, ..Default::default() }),
(&differs, LoadOptions { crop: vectorcraft_pdf::CropTo::Trim, ..Default::default() }),
(&differs, LoadOptions { pages: Some("1".into()), ..Default::default() }),
];
for (file, opts) in cases {
let before = vectorcraft_pdf::imports_of(file);
load_with("draft.ai", file, &opts).unwrap();
assert_eq!(vectorcraft_pdf::imports_of(file) - before, 1, "{opts:?}");
}
}
/// A text object that takes the page's type lacks the glyphs next to it that the page kept as
/// outlines: a note counts such objects, in place of the PDF part's notes. Stroked glyphs that
/// come in with the stroked type keep the PDF part's notes.
@@ -97,6 +97,18 @@ fn pdf_and_svg_show_the_color_and_their_editing_data_keeps_it_as_the_artboards()
assert_eq!(back.layers.len(), doc.layers.len(), "no art made of it");
}
#[test]
fn the_ai_editing_copy_for_other_apps_draws_the_color_as_the_pages_do() {
let mut s = session();
let opts = LoadOptions { native: false, ..Default::default() };
for (more, fill) in [(json!({}), true), (json!({"includeArtboardFill": false}), false)] {
let l = load::load_with("a.ai", &file(&mut s, with(json!({"format": "ai"}), &more)), &opts).unwrap();
assert!(l.editing_data && !l.restored, "{more}: {:?}", l.warnings);
let names: Vec<String> = l.doc.layers.iter().filter_map(|l| l.name.clone()).collect();
assert_eq!(names.iter().any(|n| n == "Artboard Fill"), fill, "{more}: {names:?}");
}
}
#[test]
fn eps_and_postscript_print_draw_the_color() {
let mut s = session();
+221 -1
View File
@@ -405,7 +405,7 @@ fn ai_export_without_artboards_keeps_art_outside_the_original_pages() {
}
/// Color Halftone's Max Radius is in pixels of the raster effects resolution since document
/// version 2 (#3260). A PDF saved with Preserve Editing carries the native document, so one from
/// version 3 (#3260). A PDF saved with Preserve Editing carries the native document, so one from
/// before that opens with the radius converted, drawing the same dots; one saved since opens as
/// it was.
#[test]
@@ -432,3 +432,223 @@ fn a_preserve_editing_pdf_opens_with_its_halftone_radius_in_pixels() {
assert!((halftone(true) - 8.0 * 300.0 / 72.0).abs() < 1e-9, "{}", halftone(true));
assert_eq!(halftone(false), 8.0);
}
/// The layers of `doc` as their names and the kinds and bounds of what they hold, rounded.
fn outline(doc: &vectorcraft_doc::Document) -> Vec<String> {
fn walk(nodes: &[std::sync::Arc<vectorcraft_doc::Node>], depth: usize, out: &mut Vec<String>) {
for n in nodes {
let b = n.visual_bounds().map(|b| [b.x0, b.y0, b.x1, b.y1].map(|v| v.round() as i64));
let kind = match &n.kind {
vectorcraft_doc::NodeKind::Layer { .. } => "layer",
vectorcraft_doc::NodeKind::Group { .. } => "group",
vectorcraft_doc::NodeKind::Path { .. } => "path",
_ => "other",
};
out.push(format!("{depth} {kind} {:?} {} {b:?}", n.name, n.visible));
walk(n.children().map(Vec::as_slice).unwrap_or_default(), depth + 1, out);
}
}
let mut out = vec![];
walk(&doc.layers, 0, &mut out);
out
}
/// A `.ai` also carries the editing copy of its art that other apps read: opened without the
/// VectorCraft document it carries, it gives back the same layers, groups and paths, its page
/// matching them. `editingData: false` leaves the copy out.
#[test]
fn ai_files_carry_an_editing_copy_for_other_apps() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 30})).unwrap();
s.execute("shape.ellipse", &json!({"x": 60, "y": 10, "width": 50, "height": 30})).unwrap();
s.execute("select.all", &json!({})).unwrap();
s.execute("object.group", &json!({})).unwrap();
s.execute("layer.new", &json!({"name": "Top"})).unwrap();
s.execute("shape.rectangle", &json!({"x": 120, "y": 50, "width": 60, "height": 40})).unwrap();
let before = outline(&s.doc().unwrap().doc);
let bytes = b64(&s.execute("document.export", &json!({"format": "ai"})).unwrap());
let private = vectorcraft_pdf::illustrator_data(&bytes, None).expect("the editing copy for other apps");
assert!(private.starts_with(b"%AI24_ZStandard_Data"));
let opts = LoadOptions { native: false, ..Default::default() };
let l = load::load_with("art.ai", &bytes, &opts).unwrap();
assert!(l.editing_data && !l.restored);
assert!(!l.warnings.iter().any(|w| w.contains("editing data")), "{:?}", l.warnings);
assert_eq!(outline(&l.doc), before);
let r = s.execute("document.export", &json!({"format": "ai", "editingData": false})).unwrap();
assert_eq!(vectorcraft_pdf::illustrator_data(&b64(&r), None), None);
assert!(s.execute("document.export", &json!({"format": "ai", "editingData": "no"})).is_err());
}
/// A `.ai` whose editing copy for other apps differs from the VectorCraft document it carries (the
/// copy leaves the live effect out) opens in VectorCraft from the VectorCraft document.
#[test]
fn an_ai_file_opens_from_its_vectorcraft_document_when_the_editing_copy_differs() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 30})).unwrap()["id"].as_u64().unwrap();
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [id]})).unwrap();
let r = s.execute("document.export", &json!({"format": "ai"})).unwrap();
assert!(r["warnings"].to_string().contains("live effects"), "{r}");
let bytes = b64(&r);
let effects = |doc: &vectorcraft_doc::Document| {
let mut out = vec![];
doc.walk(|n| {
if matches!(n.kind, vectorcraft_doc::NodeKind::Path { .. }) {
out.push(n.appearance.effects.len());
}
});
out
};
let copy = load::load_with("art.ai", &bytes, &LoadOptions { native: false, trust_editing_data: true, ..Default::default() }).unwrap();
assert!(copy.editing_data && !copy.restored);
assert_eq!(effects(&copy.doc), [0]);
let opened = load::load_with("art.ai", &bytes, &LoadOptions::default()).unwrap();
assert!(opened.restored);
assert_eq!(effects(&opened.doc), [1]);
}
/// The layers, groups, compound paths and paths of `doc` with their names, visibility, geometric
/// bounds (rounded), transparency, clipping and opacity masks, one line each; a mask's art after
/// its object.
fn see_through_outline(doc: &vectorcraft_doc::Document) -> Vec<String> {
use vectorcraft_doc::NodeKind;
fn walk(nodes: &[std::sync::Arc<vectorcraft_doc::Node>], depth: usize, out: &mut Vec<String>) {
for n in nodes {
let kind = match &n.kind {
NodeKind::Layer { clip, .. } => format!("layer clip={clip}"),
NodeKind::Group { clip, .. } => format!("group clip={clip}"),
NodeKind::Compound { .. } => "compound".into(),
NodeKind::Path { clipping, .. } => format!("path clipping={clipping}"),
_ => "other".into(),
};
let b = n.geometric_bounds().map(|b| [b.x0, b.y0, b.x1, b.y1].map(|v| v.round() as i64));
let mask = n.extras().mask.clone();
out.push(format!(
"{depth} {kind} {:?} {} {b:?} {} {:?} isolate={} {:?} shape={} mask={:?}",
n.name,
n.visible,
(n.opacity * 100.0).round(),
n.blend,
n.isolate,
n.knockout,
n.knockout_shape,
mask.as_ref().map(|m| (m.clip, m.invert, m.disabled, m.linked))
));
if let Some(m) = mask {
walk(std::slice::from_ref(&m.art), depth + 1, out);
}
walk(n.children().map(Vec::as_slice).unwrap_or_default(), depth + 1, out);
}
}
let mut out = vec![];
walk(&doc.layers, 0, &mut out);
out
}
/// A document of two artboards (the art on the first) with a compound path at 70% in Screen, a
/// clipping group at 50% in Multiply, a named group (isolated, knockout on, knockout shape) and a
/// square with an opacity mask that doesn't clip on layer `Layer 1`, and layer `Cut` (40%,
/// clipping) holding two squares.
fn see_through_session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 300, "height": 200, "artboards": 2})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000"})).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())
};
// A compound path at 70% in Screen.
let (a, b) = (rect(&mut s, 10.0, 10.0, 40.0, 40.0), rect(&mut s, 20.0, 20.0, 20.0, 20.0));
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
s.execute("object.compoundPath.make", &json!({})).unwrap();
s.execute("transparency.set", &json!({"opacity": 70, "blend": "Screen"})).unwrap();
// A clipping group at 50% in Multiply.
let (art, clip) = (rect(&mut s, 60.0, 10.0, 60.0, 40.0), rect(&mut s, 70.0, 20.0, 30.0, 20.0));
s.execute("select.set", &json!({"ids": [art, clip]})).unwrap();
s.execute("object.clippingMask.make", &json!({})).unwrap();
s.execute("transparency.set", &json!({"opacity": 50, "blend": "Multiply"})).unwrap();
// A named group, isolated, knockout on, whose opacity defines the knockout shape.
let (a, b) = (rect(&mut s, 60.0, 60.0, 30.0, 30.0), rect(&mut s, 75.0, 75.0, 30.0, 30.0));
let g = id(s.execute("object.group", &json!({"ids": [a, b]})).unwrap());
s.execute("object.setProps", &json!({"ids": [g], "name": "Knock", "opacity": 80, "isolate": true, "knockout": "on", "knockoutShape": true}))
.unwrap();
// A square with an opacity mask that doesn't clip.
let masked = rect(&mut s, 130.0, 10.0, 40.0, 40.0);
s.execute("paint.setFill", &json!({"color": "#808080"})).unwrap();
let mask = rect(&mut s, 140.0, 20.0, 20.0, 20.0);
s.execute("select.set", &json!({"ids": [masked, mask]})).unwrap();
s.execute("transparency.makeOpacityMask", &json!({"clip": false})).unwrap();
// A clipping layer at 40%.
let cut = id(s.execute("layer.new", &json!({"name": "Cut"})).unwrap());
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
rect(&mut s, 10.0, 100.0, 80.0, 60.0);
rect(&mut s, 30.0, 110.0, 40.0, 40.0);
s.execute("layer.clippingMask.toggle", &json!({})).unwrap();
s.execute("object.setProps", &json!({"ids": [cut], "opacity": 40})).unwrap();
s
}
/// The editing copy of `bytes` read alone, checked against its page.
fn editing_copy(bytes: &[u8]) -> vectorcraft_doc::Document {
let l = load::load_with("art.ai", bytes, &LoadOptions { native: false, ..Default::default() }).unwrap();
assert!(l.editing_data && !l.restored, "{:?}", l.warnings);
assert!(!l.warnings.iter().any(|w| w.contains("editing data")), "{:?}", l.warnings);
l.doc
}
/// `nodes` as the editing copy reads them back: an opacity mask's art that isn't a group comes
/// back as a plain group holding it.
fn mask_art_grouped(nodes: &mut [std::sync::Arc<vectorcraft_doc::Node>]) {
use vectorcraft_doc::{Node, NodeKind};
for n in nodes {
let n = std::sync::Arc::make_mut(n);
if let Some(m) = n.extras_mut().mask.as_mut()
&& !matches!(m.art.kind, NodeKind::Group { .. })
{
let art = m.art.clone();
m.art = std::sync::Arc::new(Node::new(art.id, NodeKind::Group { children: vec![art], clip: false }));
}
if let Some(c) = n.children_mut() {
mask_art_grouped(c);
}
}
}
/// Transparency, a compound path, a clipping group, an opacity mask and a clipping layer come back
/// from the editing copy for other apps alone, its page matching it, with every save option that
/// writes the copy; the version 7 `.ai` keeps the compound path and the clipping group.
#[test]
fn transparency_clipping_and_opacity_masks_come_back_from_the_editing_copy() {
let mut s = see_through_session();
let mut before = (*s.doc().unwrap().doc).clone();
// The mask's art is one path; it reads back as a group holding the path.
let mut arts = vec![];
before.walk(|n| arts.extend(n.extras().mask.as_ref().map(|m| matches!(m.art.kind, vectorcraft_doc::NodeKind::Path { .. }))));
assert_eq!(arts, [true]);
mask_art_grouped(&mut before.layers);
let want = see_through_outline(&before);
for opts in [json!({"format": "ai"}), json!({"format": "ai", "compress": false}), json!({"format": "ai", "pdfCompatible": true})] {
let bytes = b64(&s.execute("document.export", &opts).unwrap());
assert_eq!(see_through_outline(&editing_copy(&bytes)), want, "{opts}");
}
// Each artboard in a file of its own: the first holds all the art.
let path = tmp("see-through.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 {
let copy = editing_copy(&std::fs::read(f).unwrap());
if f.ends_with("-2.ai") {
assert!(copy.layers.iter().all(|l| l.children().is_none_or(Vec::is_empty)), "{f} {:#?}", see_through_outline(&copy));
} else {
assert_eq!(see_through_outline(&copy), want, "{f}");
}
}
// Version 7 has no transparency; it keeps the compound path and the clipping group.
let r = s.execute("document.export", &json!({"format": "ai", "aiVersion": 7})).unwrap();
let legacy = load::load_with("art.ai", &b64(&r), &LoadOptions::default()).unwrap();
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:#?}");
}
@@ -141,6 +141,8 @@ fn load_options_read_text_and_layers() {
assert!(o.is_partial(), "without its hidden layers, Save doesn't write the file back");
let d = LoadOptions::default();
assert_eq!((d.text_as, d.layers, d.is_partial()), (TextAs::Text, true, false));
let n = LoadOptions { native: false, ..Default::default() };
assert!(n.is_partial(), "without the document it carries, Save doesn't write the file back");
}
#[test]
@@ -361,3 +361,17 @@ fn damaged_files_are_refused_with_a_message() {
assert!(!is_pxr(&bad), "{bad:?}");
}
}
#[test]
fn tile_pointers_into_the_header_or_table_are_refused() {
// Tile data follows the tile pointer table, which ends at byte 520 in a one-tile picture.
let rgb = one(head(2, 1, RGB, 2), &[1, 2, 3, 4, 5, 6]);
for pointer in [4u32, 511, 512, 519] {
let mut inside = rgb.clone();
inside[512..516].copy_from_slice(&pointer.to_le_bytes());
let e = raster_image(&inside).err().expect("refused").to_string();
assert_eq!(e, "the Pixar file's image data is damaged", "a pointer to byte {pointer}");
}
// A pointer at the table's end reads.
assert_eq!(pixels(&rgb), [[1, 2, 3, 255], [4, 5, 6, 255]]);
}
+2 -2
View File
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add Freeform Point",
[],
None,
"{at: [x,y] (document coordinates), color? (default: the gradient's colour there), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it → {index}",
"{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it → {index}",
has_doc,
add_point
),
@@ -28,7 +28,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Edit Freeform Point",
[],
None,
"{index? (default: the selected point), at?: [x,y] (document coordinates), color?, keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient → {index}",
"{index? (default: the selected point), at?: [x,y] (document coordinates), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient → {index}",
has_doc,
set_point
),
+1 -1
View File
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Gradient",
["Window", "Gradient"],
None,
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|freeform (freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual (how the colours between the stops mix: in display RGB, or perceptually (OKLab) so the steps look even, which SVG and PDF exports draw as an image, except that PDF writes one with spot color stops in its inks when every other stop is paper white, CMYK or gray; freeform gradients mix their own way), stops?: [{offset 0..1, color? (needed without swatch), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg, aspect?: %, reverse?: bool, dither?: bool (fills only: a linear or radial gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient",
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|freeform (freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual (how the colours between the stops mix: in display RGB, or perceptually (OKLab) so the steps look even; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear or radial, has spot color stops, every other stop is paper white, CMYK or gray, it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg, aspect?: %, reverse?: bool, dither?: bool (fills only: a linear or radial gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient",
has_doc,
edit_gradient
),
+1 -1
View File
@@ -42,7 +42,7 @@ use data::{fmt_value, parse_csv, to_csv};
use generate::generate;
#[cfg(test)]
use series::default_series_color;
pub(crate) use series::{capture_label_styles, capture_series_paints, paint_targets};
pub(crate) use series::{capture_label_styles, capture_series_opacity, capture_series_paints, paint_targets};
#[cfg(test)]
mod tests;
+5 -4
View File
@@ -5,7 +5,7 @@ use super::labels::{
FILLED_LINE_BUDGET, Gen, Role, SHADOW_BUDGET, SHADOW_OPACITY, blank_label, label_size, label_width, polyline, recolour_text, runs, shadow_of,
};
use super::markers::{MARKER_BUDGET, marker_cost, marker_designs};
use super::series::series_marks;
use super::series::{series_marks, with_series_opacity};
use super::{
Arc, BezPath, Color, Document, GraphKind, GraphSpec, Justify, Node, NodeKind, Paint, PathData, Point, Rect, TickLength, ValueAxisSide, shapes,
};
@@ -244,7 +244,8 @@ impl<'a> Plot<'a> {
if marker_cost(g, &designs) > MARKER_BUDGET {
designs.clear();
}
let nser = g.rows.iter().map(Vec::len).max().unwrap_or(0).max(1);
// The same dimensions `GraphSpec::cells` reads: raw rows can be longer than the grid they are read through.
let nser = g.rows.iter().map(Vec::len).max().unwrap_or(0).clamp(1, vectorcraft_doc::MAX_GRAPH_SERIES);
let kinds: Vec<GraphKind> = (0..nser).map(|s| g.series_kind(s)).collect();
Plot {
g,
@@ -253,7 +254,7 @@ impl<'a> Plot<'a> {
designs,
r: g.rect,
nser,
ncat: g.rows.len().max(1),
ncat: g.rows.len().clamp(1, vectorcraft_doc::MAX_GRAPH_CATEGORIES),
vs: label_size(&g.label_styles, Role::Value),
cs: label_size(&g.label_styles, Role::Category),
ls: label_size(&g.label_styles, Role::Legend),
@@ -1001,7 +1002,7 @@ impl<'a> Plot<'a> {
}
}
let name = g.series.get(s).cloned().filter(|n| !n.is_empty()).unwrap_or_else(|| format!("Series {}", s + 1));
let grp = self.b.series(&name, s, items);
let grp = self.b.series(&name, s, with_series_opacity(g, s, items));
self.b.out.push(grp);
}
self.b.out.append(&mut self.on_top);
+71 -1
View File
@@ -1,5 +1,5 @@
use super::labels::{Role, label_style};
use super::{CharStyle, Color, Document, GraphKind, GraphSpec, HashMap, Node, NodeId, NodeKind, Paint, Result, Session, Value, bad};
use super::{Arc, CharStyle, Color, Document, GraphKind, GraphSpec, HashMap, Node, NodeId, NodeKind, Paint, Result, Session, Value, bad};
// ---------- generation ----------
@@ -25,6 +25,31 @@ pub(super) fn series_marks(g: &GraphSpec, i: usize, series_fill: bool, stroke: P
(fill, stroke, width)
}
/// The paths directly inside series `i`'s group (`items`) with the series' kept fill and stroke opacity on their
/// topmost fill and stroke. Other art, such as a graph design, keeps its own opacity. A value read from a file is
/// held to 0..1, and one that is not a number is left out.
pub(super) fn with_series_opacity(g: &GraphSpec, i: usize, mut items: Vec<Arc<Node>>) -> Vec<Arc<Node>> {
let Some(slot) = g.series_paints.get(i) else { return items };
let kept = |o: Option<f32>| o.filter(|o| o.is_finite()).map(|o| o.clamp(0.0, 1.0));
let (fill, stroke) = (kept(slot.fill_opacity), kept(slot.stroke_opacity));
if fill.is_none() && stroke.is_none() {
return items;
}
for item in &mut items {
if !matches!(item.kind, NodeKind::Path { .. }) {
continue;
}
let ap = &mut Arc::make_mut(item).appearance;
if let (Some(o), Some(f)) = (fill, ap.fill_mut()) {
f.opacity = o;
}
if let (Some(o), Some(st)) = (stroke, ap.stroke_mut()) {
st.opacity = o;
}
}
items
}
/// Where a node inside a graph's generated series art belongs: the graph, the series group and
/// the series index stored on that group.
#[derive(Clone, Copy)]
@@ -119,6 +144,51 @@ pub(crate) fn capture_series_paints(doc: &mut Document, ids: &[NodeId], fill: bo
changed
}
/// Copy the opacity of the topmost fill (`true`) or stroke (`false`) of generated series art just edited (`edited`:
/// each object with the kind of row) into that series' fill or stroke opacity; art left without a row of that kind
/// keeps none. Called inside the same document edit, so both undo together. Returns whether a series' kept opacity
/// changed.
pub(crate) fn capture_series_opacity(doc: &mut Document, edited: &[(NodeId, bool)]) -> bool {
if edited.is_empty() {
return false;
}
let members = series_members(doc);
if members.is_empty() {
return false;
}
let captures: Vec<_> = edited
.iter()
.filter_map(|(id, fill)| {
// Only the paths the graph draws again, not the copy of a graph design.
let r = members.get(id).filter(|r| doc.parent_of(*id) == Some(r.group))?;
let node = doc.node(*id).filter(|n| matches!(n.kind, NodeKind::Path { .. }))?;
let opacity = node.appearance.items.iter().rev().find(|it| it.is_fill() == *fill).map_or(1.0, vectorcraft_doc::AppearanceItem::opacity);
Some((r.graph, r.index, *fill, (opacity < 1.0).then_some(opacity)))
})
.collect();
let mut changed = false;
for (graph, index, fill, kept) in captures {
let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue };
// A fully opaque row on a series the graph keeps nothing for leaves the graph as it is.
if kept.is_none() && spec.series_paints.len() <= index {
continue;
}
let was = spec.series_paints.clone();
// `index` is below the graph's series count (`series_members`).
if spec.series_paints.len() <= index {
spec.series_paints.resize(index + 1, vectorcraft_doc::SeriesPaint::default());
}
let Some(slot) = spec.series_paints.get_mut(index) else { continue };
if fill {
slot.fill_opacity = kept;
} else {
slot.stroke_opacity = kept;
}
changed |= spec.series_paints != was;
}
changed
}
/// Graph Data › Transpose row/column: categories become series and series categories.
pub(super) fn transpose(g: &mut GraphSpec) {
let cells = g.cells();
+233
View File
@@ -289,6 +289,239 @@ fn painting_one_bar_sets_the_colour_used_by_the_whole_series_on_rebuild() {
assert!(group(node, "2024").children().unwrap().iter().all(|n| n.appearance.fill_paint().color() == Some(green)));
}
/// An opacity set on the fill or stroke item of one series mark is kept by the graph: every path of that series has
/// it after the graph is drawn again, the other series stay opaque, 100% forgets it, and undo takes it back.
#[test]
fn an_item_opacity_on_a_series_mark_survives_regeneration() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let id = graph(&mut s, "column");
let opacities = |s: &Session, index: u32| -> Vec<(f32, f32)> {
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
let marks = series(&n, index).children().unwrap().to_vec();
marks.iter().map(|m| (m.appearance.fill().unwrap().opacity, m.appearance.stroke().unwrap().opacity)).collect()
};
let bar = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id;
s.execute("transparency.set", &json!({"ids": [bar.0], "item": 0, "opacity": 40})).unwrap();
s.execute("transparency.set", &json!({"ids": [bar.0], "item": 1, "opacity": 60})).unwrap();
let kept = spec(&s, id).series_paints[0].clone();
assert_eq!((kept.fill_opacity, kept.stroke_opacity), (Some(0.4), Some(0.6)));
let restored: GraphSpec = serde_json::from_value(serde_json::to_value(spec(&s, id)).unwrap()).unwrap();
assert_eq!(restored, spec(&s, id));
s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4]]})).unwrap();
assert!(opacities(&s, 0).iter().all(|o| *o == (0.4, 0.6)), "{:?}", opacities(&s, 0));
assert!(opacities(&s, 1).iter().all(|o| *o == (1.0, 1.0)), "{:?}", opacities(&s, 1));
// Back to 100%: the graph keeps no opacity for the fill.
let bar = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id;
s.execute("transparency.set", &json!({"ids": [bar.0], "item": 0, "opacity": 100})).unwrap();
assert_eq!(spec(&s, id).series_paints[0].fill_opacity, None);
s.execute("graph.setType", &json!({"type": "bar"})).unwrap();
assert!(opacities(&s, 0).iter().all(|o| *o == (1.0, 0.6)), "{:?}", opacities(&s, 0));
// Undo goes back through the type change, the 100% and the data edit, then takes the stroke opacity away with its
// edit.
for _ in 0..4 {
s.execute("edit.undo", &json!({})).unwrap();
}
let kept = spec(&s, id).series_paints[0].clone();
assert_eq!((kept.fill_opacity, kept.stroke_opacity), (Some(0.4), None));
}
/// Clear Appearance and Reduce to Basic Appearance on a series mark take its fill and stroke opacity away, and the
/// graph keeps none, so the series stays opaque when it is drawn again.
#[test]
fn clearing_a_series_marks_appearance_forgets_its_kept_opacity() {
for cmd in ["appearance.clear", "appearance.reduceToBasic"] {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let id = graph(&mut s, "column");
let bar = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id;
s.execute("transparency.set", &json!({"ids": [bar.0], "item": 0, "opacity": 40})).unwrap();
s.execute("transparency.set", &json!({"ids": [bar.0], "item": 1, "opacity": 60})).unwrap();
s.execute(cmd, &json!({"ids": [bar.0]})).unwrap();
let kept = spec(&s, id).series_paints[0].clone();
assert_eq!((kept.fill_opacity, kept.stroke_opacity), (None, None), "{cmd}");
s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4]]})).unwrap();
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
assert!(series(&n, 0).children().unwrap().iter().all(|m| m.appearance.fill().unwrap().opacity == 1.0), "{cmd}");
}
}
/// Removing the fill whose opacity the graph keeps takes the kept opacity away; an edit that leaves a mark opaque
/// (a blend mode alone) keeps nothing for its series.
#[test]
fn removing_a_series_marks_fill_forgets_its_kept_opacity() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let id = graph(&mut s, "column");
let bar = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id;
s.execute("transparency.set", &json!({"ids": [bar.0], "item": 0, "blend": "multiply"})).unwrap();
assert!(spec(&s, id).series_paints.is_empty());
s.execute("transparency.set", &json!({"ids": [bar.0], "item": 0, "opacity": 40})).unwrap();
assert_eq!(spec(&s, id).series_paints[0].fill_opacity, Some(0.4));
s.execute("appearance.removeItem", &json!({"ids": [bar.0], "index": 0})).unwrap();
assert_eq!(spec(&s, id).series_paints[0].fill_opacity, None);
// An opaque fill added over the kept one takes it away too.
s.execute("edit.undo", &json!({})).unwrap();
s.execute("appearance.addFill", &json!({"ids": [bar.0]})).unwrap();
assert_eq!(spec(&s, id).series_paints[0].fill_opacity, None);
}
/// An opacity set on a row added to a graph design's copy inside a series is not kept for the series: the graph draws
/// the design again from the design itself.
#[test]
fn an_opacity_on_a_design_copy_in_a_series_is_not_kept() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let id = graph(&mut s, "column");
save_design(&mut s, "Square");
s.execute("graph.column", &json!({"id": id.0, "design": "Square"})).unwrap();
let copy = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].clone();
assert!(matches!(copy.kind, NodeKind::Group { .. }));
s.execute("appearance.addFill", &json!({"ids": [copy.id.0]})).unwrap();
s.execute("transparency.set", &json!({"ids": [copy.id.0], "item": 0, "opacity": 40})).unwrap();
assert!(spec(&s, id).series_paints.first().is_none_or(|p| p.fill_opacity.is_none()));
}
/// A series' kept opacity goes on its generated marks only: a column design made of one path keeps its own opacity.
#[test]
fn a_column_design_keeps_its_own_opacity_under_a_series_opacity() {
let mut d = vectorcraft_doc::Document::new(800.0, 800.0);
let mut look = vectorcraft_doc::Appearance::basic(Paint::solid(vectorcraft_color::Color::BLACK), Paint::None, 0.0);
look.fill_mut().unwrap().opacity = 0.5;
let rect = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0));
let art = vectorcraft_doc::Node::path(d.alloc_id(), rect, look);
d.graph_designs.push(vectorcraft_doc::GraphDesign { name: "Square".into(), art: std::sync::Arc::new(art) });
let options = ColumnDesign { design: "Square".into(), column_type: ColumnType::Vertical, ..ColumnDesign::default() };
let paints = vec![vectorcraft_doc::SeriesPaint { fill_opacity: Some(0.2), ..Default::default() }];
let g = GraphSpec {
rows: vec![vec![35.0]],
axis_min: Some(0.0),
axis_max: Some(50.0),
series_columns: vec![Some(options)],
series_paints: paints,
..GraphSpec::default()
};
let out = super::generate(&mut d, &g);
let group = out.iter().find(|n| n.extras().series_index == Some(0)).unwrap();
let mut fills = vec![];
group.walk(&mut |n| {
if matches!(n.kind, NodeKind::Path { .. }) {
fills.push(n.appearance.fill().unwrap().opacity);
}
});
assert!(!fills.is_empty() && fills.iter().all(|o| *o == 0.5), "{fills:?}");
}
/// An opacity set on an item that the graph does not draw again (a second fill added to a mark) is not kept.
#[test]
fn an_opacity_on_an_added_item_of_a_series_mark_is_not_kept() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let id = graph(&mut s, "column");
let bar = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id;
s.execute("appearance.addFill", &json!({"ids": [bar.0]})).unwrap();
let items = s.doc().unwrap().doc.node(bar).unwrap().appearance.items.clone();
let lower = items.iter().position(vectorcraft_doc::AppearanceItem::is_fill).unwrap();
assert!(items.iter().rposition(vectorcraft_doc::AppearanceItem::is_fill).unwrap() != lower);
s.execute("transparency.set", &json!({"ids": [bar.0], "item": lower, "opacity": 40})).unwrap();
assert!(spec(&s, id).series_paints.first().is_none_or(|p| p.fill_opacity.is_none()));
}
/// The fill positions (lowest, topmost) in a mark's appearance stack.
fn fill_rows(s: &Session, mark: NodeId) -> (usize, usize) {
let items = s.doc().unwrap().doc.node(mark).unwrap().appearance.items.clone();
let lower = items.iter().position(vectorcraft_doc::AppearanceItem::is_fill).unwrap();
let upper = items.iter().rposition(vectorcraft_doc::AppearanceItem::is_fill).unwrap();
assert!(lower < upper);
(lower, upper)
}
/// Moving a translucent fill to the top of a series mark's stack, or placing a copy of it there, makes the graph keep
/// its opacity.
#[test]
fn moving_or_duplicating_a_series_marks_fill_to_the_top_keeps_its_opacity() {
for cmd in ["appearance.moveItem", "appearance.duplicateItem"] {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let id = graph(&mut s, "column");
let bar = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id;
s.execute("appearance.addFill", &json!({"ids": [bar.0]})).unwrap();
let (lower, upper) = fill_rows(&s, bar);
s.execute("transparency.set", &json!({"ids": [bar.0], "item": lower, "opacity": 40})).unwrap();
assert!(spec(&s, id).series_paints.first().is_none_or(|p| p.fill_opacity.is_none()), "{cmd}");
let p = if cmd == "appearance.moveItem" {
json!({"ids": [bar.0], "from": lower, "to": upper})
} else {
json!({"ids": [bar.0], "index": lower, "to": upper + 1})
};
s.execute(cmd, &p).unwrap();
let top = fill_rows(&s, bar).1;
assert_eq!(s.doc().unwrap().doc.node(bar).unwrap().appearance.items[top].opacity(), 0.4, "{cmd}");
assert_eq!(spec(&s, id).series_paints[0].fill_opacity, Some(0.4), "{cmd}");
}
}
/// Moving or copying a translucent mark's appearance onto a mark of another series (the Layers panel's target
/// circle, or the Eyedropper) makes the graph keep the opacity for that series; a move leaves the source series with
/// none.
#[test]
fn moving_or_copying_an_appearance_onto_a_series_mark_keeps_its_opacity() {
for (cmd, source_keeps) in [("move", None), ("copy", Some(0.4)), ("eyedropper", Some(0.4))] {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let id = graph(&mut s, "column");
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
let (from, to) = (series(&n, 0).children().unwrap()[0].id, series(&n, 1).children().unwrap()[0].id);
s.execute("transparency.set", &json!({"ids": [from.0], "item": 0, "opacity": 40})).unwrap();
match cmd {
"eyedropper" => s.execute("appearance.copyFrom", &json!({"source": from.0, "ids": [to.0]})).unwrap(),
_ => s.execute("appearance.transfer", &json!({"source": from.0, "target": to.0, "copy": cmd == "copy"})).unwrap(),
};
let paints = spec(&s, id).series_paints;
assert_eq!(paints.get(1).and_then(|p| p.fill_opacity), Some(0.4), "{cmd}");
assert_eq!(paints[0].fill_opacity, source_keeps, "{cmd}");
}
}
/// A line graph keeps a stroke opacity set on a series' line, and puts it on the line drawn again.
#[test]
fn a_stroke_opacity_on_a_series_line_survives_regeneration() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let id = graph(&mut s, "line");
let lines = |s: &Session| -> Vec<vectorcraft_doc::Node> {
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
let marks = series(&n, 0).children().unwrap().to_vec();
marks.iter().filter(|m| m.appearance.stroke().is_some_and(|st| st.width > 0.0)).map(|m| (**m).clone()).collect()
};
let line = lines(&s).first().unwrap().clone();
let row = line.appearance.items.iter().rposition(|it| !it.is_fill()).unwrap();
s.execute("transparency.set", &json!({"ids": [line.id.0], "item": row, "opacity": 60})).unwrap();
assert_eq!(spec(&s, id).series_paints[0].stroke_opacity, Some(0.6));
s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4], [2, 5]]})).unwrap();
let after = lines(&s);
assert!(!after.is_empty() && after.iter().all(|m| m.appearance.stroke().unwrap().opacity == 0.6));
}
/// A kept opacity read from a file outside 0..1 is held to that range, and one that is not a number is left out.
#[test]
fn a_kept_series_opacity_from_a_file_is_held_to_its_range() {
let mut d = vectorcraft_doc::Document::new(800.0, 800.0);
let paints = vec![vectorcraft_doc::SeriesPaint { fill_opacity: Some(-1.0), stroke_opacity: Some(f32::NAN), ..Default::default() }];
let paints = [paints, vec![vectorcraft_doc::SeriesPaint { fill_opacity: Some(40.0), ..Default::default() }]].concat();
let g = GraphSpec { rows: vec![vec![35.0, 20.0]], axis_min: Some(0.0), axis_max: Some(50.0), series_paints: paints, ..GraphSpec::default() };
let out = super::generate(&mut d, &g);
for (index, want) in [(0, 0.0), (1, 1.0)] {
let group = out.iter().find(|n| n.extras().series_index == Some(index)).unwrap();
let marks: Vec<_> = group.children().unwrap().iter().filter(|n| matches!(n.kind, NodeKind::Path { .. })).collect();
assert!(!marks.is_empty());
for m in marks {
assert_eq!(m.appearance.fill().unwrap().opacity, want);
assert!(m.appearance.stroke().is_none_or(|st| st.opacity == 1.0));
}
}
}
/// A series index read from a file past the graph's series is not a series: painting its art
/// paints the art alone and stores nothing (no allocation sized by the file).
#[test]
+1 -1
View File
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Vector Halftone…",
["Object"],
None,
"{shape?: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\" (circle), frequency?: lines per inch 1–300 (20), angle?: deg (45; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode?: \"mono\"|\"cmyk\" (mono), color?: mono dot colour (\"#000000\"), invert?: bool (dots for light tones), clip?: true (clip the dots to the art's outline), keepOriginal?: false} the selection as vector halftone dots sized by its tone, a group of one path per screen (CMYK screens multiply), as one undo step → {id, dots, warning? (an image in the art couldn't be decoded, as object.rasterize says)}",
"{shape?: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\" (circle), frequency?: lines per inch 1–300 (20), angle?: deg (45; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode?: \"mono\"|\"cmyk\" (mono), color?: mono dot colour (\"#000000\"; #rrggbbaa and #rgba are refused), invert?: bool (dots for light tones), clip?: true (clip the dots to the art's outline), keepOriginal?: false} the selection as vector halftone dots sized by its tone, a group of one path per screen (CMYK screens multiply), as one undo step → {id, dots, warning? (an image in the art couldn't be decoded, as object.rasterize says)}",
has_selection,
halftone
)]
+12 -5
View File
@@ -83,7 +83,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Layer Options…",
["Window", "Layers"],
None,
"{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name} Layer Options; rows that are not layers take name, visible and locked. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. One undo step",
"{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. One undo step",
has_doc,
set_props
),
@@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New Artboard",
["Window", "Artboards"],
None,
"{x?, y?, width?, height?, name?, color?: color (its background color, as artboard.setProps takes it; default: none), showCenterMark?: bool, showCrossHairs?: bool, showVideoSafeAreas?: bool (as artboard.setProps takes them; default false), videoRulerPixelAspectRatio?: number 0.1–10 (as artboard.setProps takes it; default 1)} (default place: right of the last)",
"{x?, y?, width?, height?, name?, color?: color (its background color, as artboard.setProps takes it, #rrggbbaa and #rgba refused; default: none), showCenterMark?: bool, showCrossHairs?: bool, showVideoSafeAreas?: bool (as artboard.setProps takes them; default false), videoRulerPixelAspectRatio?: number 0.1–10 (as artboard.setProps takes it; default 1)} (default place: right of the last)",
has_doc,
artboard_new
),
@@ -155,7 +155,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Artboard Options…",
["Window", "Artboards"],
None,
"{index | artboards: [{index, name?, color?, locked?, showCenterMark?, showCrossHairs?, showVideoSafeAreas?, videoRulerPixelAspectRatio?, x?, y?, width?, height?}…] (several artboards in one undo step, each with its own fields; the art inside each before any of them changes goes with it, and an object inside several goes with the first listed that moves or scales its art), name?, color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take: the background color the canvas draws the artboard's paper in, multiplied with the Simulate Colored Paper color while that is on; exports and print leave it out) | null (no background color), locked?: bool (the Artboards panel's lock column: a locked artboard keeps its rectangle (a new x, y, width or height is an error unless locked is false), can't be moved, deleted or cut, and Rearrange and Fit to Artwork Bounds leave it as it is; the art on it (each object of a layer or sublayer whose bounds with strokes overlap it, a group as one object) acts as locked art until it is unlocked: clicks, marquees, select.set, select.all and the tools pass over it (art drawn or pasted onto it stays selected and editable until a selection leaves it out or it is moved off the locked artboards), it is deselected, and when another artboard moves or scales it stays unless lockedAndHidden), showCenterMark?: bool (Artboard Options' Show Center Mark: the canvas draws a mark at the artboard's center), showCrossHairs?: bool (Show Cross Hairs: the canvas draws a line from the middle of each side through the center), showVideoSafeAreas?: bool (Show Video Safe Areas: the canvas draws the action-safe area 3.5% and the title-safe area 5% in from each edge, as EBU R 95 sets them; the three are screen-only, as the artboard's edges are: exports and print leave them out), videoRulerPixelAspectRatio?: number 0.1–10 (Video Ruler Pixel Aspect Ratio: the width of one video pixel over its height, which View › Rulers › Show Video Rulers counts the artboard in; default 1, square pixels), x?, y?, width?, height?, moveArt?: bool (default false; a position-only change moves the contained art with its artboard), scaleArt?: bool (Scale Artwork with Artboard: resized, the artboard takes the art fully inside it (locked and hidden art only with lockedAndHidden?: bool, default prefs moveLockedWithArtboard) and its guides from its old rectangle onto the new one, each side by its own ratio; strokes/corners/patterns as object.scale), strokes?: bool, corners?: bool, patterns?: bool (the three as object.scale, for art that moves or scales with the artboard), lockedAndHidden?: bool (locked and hidden art moves along; default: the preference; recorded in the journal so a replay matches)} → null, or with scaleArt {scaled: the art scaled}",
"{index | artboards: [{index, name?, color?, locked?, showCenterMark?, showCrossHairs?, showVideoSafeAreas?, videoRulerPixelAspectRatio?, x?, y?, width?, height?}…] (several artboards in one undo step, each with its own fields; the art inside each before any of them changes goes with it, and an object inside several goes with the first listed that moves or scales its art), name?, color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused: the background color the canvas draws the artboard's paper in, multiplied with the Simulate Colored Paper color while that is on; exports and print leave it out) | null (no background color), locked?: bool (the Artboards panel's lock column: a locked artboard keeps its rectangle (a new x, y, width or height is an error unless locked is false), can't be moved, deleted or cut, and Rearrange and Fit to Artwork Bounds leave it as it is; the art on it (each object of a layer or sublayer whose bounds with strokes overlap it, a group as one object) acts as locked art until it is unlocked: clicks, marquees, select.set, select.all and the tools pass over it (art drawn or pasted onto it stays selected and editable until a selection leaves it out or it is moved off the locked artboards), it is deselected, and when another artboard moves or scales it stays unless lockedAndHidden), showCenterMark?: bool (Artboard Options' Show Center Mark: the canvas draws a mark at the artboard's center), showCrossHairs?: bool (Show Cross Hairs: the canvas draws a line from the middle of each side through the center), showVideoSafeAreas?: bool (Show Video Safe Areas: the canvas draws the action-safe area 3.5% and the title-safe area 5% in from each edge, as EBU R 95 sets them; the three are screen-only, as the artboard's edges are: exports and print leave them out), videoRulerPixelAspectRatio?: number 0.1–10 (Video Ruler Pixel Aspect Ratio: the width of one video pixel over its height, which View › Rulers › Show Video Rulers counts the artboard in; default 1, square pixels), x?, y?, width?, height?, moveArt?: bool (default false; a position-only change moves the contained art with its artboard), scaleArt?: bool (Scale Artwork with Artboard: resized, the artboard takes the art fully inside it (locked and hidden art only with lockedAndHidden?: bool, default prefs moveLockedWithArtboard) and its guides from its old rectangle onto the new one, each side by its own ratio; strokes/corners/patterns as object.scale), strokes?: bool, corners?: bool, patterns?: bool (the three as object.scale, for art that moves or scales with the artboard), lockedAndHidden?: bool (locked and hidden art moves along; default: the preference; recorded in the journal so a replay matches)} → null, or with scaleArt {scaled: the art scaled}",
has_doc,
artboard_set
),
@@ -297,7 +297,8 @@ pub(crate) fn make_layer(d: &mut Document, name: Option<&str>) -> Node {
NewLayers::of(d).make(d, name)
}
/// A layer colour: a preset index (0–26), `#rrggbb` or a preset's name (any case).
/// A layer colour: a preset index (0–26), `#rrggbb` or a preset's name (any case). A hex color
/// with an alpha part (`#rrggbbaa` or `#rgba`) is an error.
pub(super) fn layer_color_param(v: &Value) -> std::result::Result<LayerColor, String> {
match v {
Value::Number(n) => match n.as_u64() {
@@ -308,7 +309,13 @@ pub(super) fn layer_color_param(v: &Value) -> std::result::Result<LayerColor, St
if let Some(i) = LAYER_COLORS.iter().position(|(name, _)| name.eq_ignore_ascii_case(s.trim())) {
return Ok(LayerColor::Preset(i as u8));
}
let c = vectorcraft_color::Color::from_hex(s).ok_or_else(|| format!("`{s}` is not a colour (#rrggbb or a preset name)"))?;
let refused = || format!("`{s}` is not a colour (#rrggbb or a preset name)");
// `Color::from_hex` reads `#rrggbbaa` as `#rrggbb`, dropping the alpha.
let digits = s.trim();
if digits.strip_prefix('#').unwrap_or(digits).len() == 8 {
return Err(refused());
}
let c = vectorcraft_color::Color::from_hex(s).ok_or_else(refused)?;
let [r, g, b, _] = c.to_rgba8(1.0);
Ok(LayerColor::Custom([r, g, b]))
}
+1 -1
View File
@@ -643,7 +643,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), 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), 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)}",
has_doc,
add
),
+1 -1
View File
@@ -20,7 +20,7 @@ use super::edit::selected_roots;
use super::expand::gradient_sampler;
use super::pathops::Beside;
use super::{
CommandSpec, EngineError, Result, Session, always, bad, check_numbers, check_switches, cmd, color_value, f64_or, f64_req, finite_numbers,
CommandSpec, EngineError, Result, Session, always, bad, check_numbers, check_switches, cmd, color_param, f64_or, f64_req, finite_numbers,
has_doc, has_multi, has_selection, id_param, named_ids, number_or, ok, str_param, switch_or,
};
+2 -2
View File
@@ -245,7 +245,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Set Mesh Point Color",
[],
None,
"{id, index | points: [index…] | items: [{id, index | points}…], color?, keepModel?: bool (as paint.setFill), opacity?: 0..1} colour and/or opacity of gradient mesh points (one undo step; an index out of range changes nothing)",
"{id, index | points: [index…] | items: [{id, index | points}…], color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1} colour and/or opacity of gradient mesh points (one undo step; an index out of range changes nothing)",
has_doc,
mesh_set_color
),
@@ -272,7 +272,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add Mesh Line",
[],
None,
"{id, x, y, color?, keepModel?: bool (as paint.setFill), tolerance?: pt (0)} add a row and a column through (x, y) to a gradient mesh (new point in `color`) or a mesh envelope; a point outside within `tolerance` of the edge adds them through the nearest point of the edge → {index}",
"{id, x, y, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), tolerance?: pt (0)} add a row and a column through (x, y) to a gradient mesh (new point in `color`) or a mesh envelope; a point outside within `tolerance` of the edge adds them through the nearest point of the edge → {index}",
has_doc,
mesh_add_line
),
+3 -3
View File
@@ -4,7 +4,7 @@ use super::common::{fix_ids, ids_json, is_mesh, replace_with, roots_param, selec
use super::envelope::{outline_of, rows_cols};
use super::{
Color, Document, EngineError, EnvelopeKind, GradientMesh, MeshAppearance, Node, NodeId, NodeKind, Paint, Point, Result, Session, Value, bad,
check_numbers, color_value, f64_or, f64_req, finite_numbers, gradient_sampler, id_param, json, live, ok, str_param,
check_numbers, color_param, f64_or, f64_req, finite_numbers, gradient_sampler, id_param, json, live, ok, str_param,
};
// ---------- Gradient mesh ----------
@@ -232,7 +232,7 @@ pub(super) fn mesh_set_color(s: &mut Session, p: &Value) -> Result<Value> {
check_numbers(p, &["opacity"], C)?;
crate::cmd::paint::check_keep_model(p, C)?;
let items = point_items(p, C)?;
let color = p.get("color").and_then(color_value).map(|c| crate::cmd::paint::new_color(s, p, c));
let color = color_param(p, "color", C)?.map(|c| crate::cmd::paint::new_color(s, p, c));
let opacity = p.get("opacity").and_then(Value::as_f64);
if color.is_none() && opacity.is_none() {
return Err(bad(C, "missing `color` or `opacity`"));
@@ -283,7 +283,7 @@ pub(super) fn mesh_add_line(s: &mut Session, p: &Value) -> Result<Value> {
crate::cmd::paint::check_keep_model(p, C)?;
check_numbers(p, &["tolerance"], C)?;
let tol = f64_or(p, "tolerance", 0.0).max(0.0);
let color = p.get("color").and_then(color_value).map(|c| crate::cmd::paint::new_color(s, p, c));
let color = color_param(p, "color", C)?.map(|c| crate::cmd::paint::new_color(s, p, c));
let index = with_mesh(s, p, C, "Add Mesh Line", true, |m| {
let i = m.add_lines_at(q, tol).ok_or_else(|| bad(C, "point is outside the mesh"))?;
if let Some(c) = color {
+21 -3
View File
@@ -115,7 +115,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Rasterize…",
["Object"],
None,
"{ppi?, background?: transparent|white|black|\"#rrggbb\", antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline)} replace the selection with an embedded image (PNG; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}",
"{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline)} replace the selection with an embedded image (PNG; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}",
has_selection,
rasterize
),
@@ -347,7 +347,7 @@ fn other_layers(s: &mut Session, lock: bool) -> Result<Value> {
}
/// Returns the objects [`super::select::walk_selectable`] visits that are not among the selected objects `roots` and
/// hold none of them. A selected layer's objects count as selected. The walk goes into a plain group, but not a Shaper
/// hold none of them. A selected layer and its objects count as selected. The walk goes into a plain group, but not a Shaper
/// group, that holds a selected object. With `lock`, it also goes into a clip group or compound path that holds one,
/// and includes guide paths while `guides_locked`. Without `lock`, guide paths and the objects that hold one are left
/// out while `guides_locked`; a clip group, Shaper group, compound path and every other object that holds a selected
@@ -360,14 +360,32 @@ fn unselected(
guides_locked: bool,
lock: bool,
) -> Vec<NodeId> {
/// Pushes the visible guide paths in `n`, `n` included, locked ones too.
fn shown_guides(n: &vectorcraft_doc::Node, out: &mut Vec<NodeId>) {
if !n.visible {
return;
}
if matches!(n.kind, NodeKind::Path { guide: true, .. }) {
out.push(n.id);
}
for c in n.children().into_iter().flatten() {
shown_guides(c, out);
}
}
let mut roots: HashSet<NodeId> = roots.iter().copied().collect();
roots.extend(selection.iter().filter_map(|id| d.node(*id)).filter(|n| n.is_layer()).flat_map(|l| l.layer_art(true)));
let layers = || selection.iter().filter_map(|id| d.node(*id)).filter(|n| n.is_layer());
roots.extend(layers().map(|l| l.id));
roots.extend(layers().flat_map(|l| l.layer_art(true)));
let mut kept: Vec<NodeId> = roots.iter().copied().collect();
if guides_locked && !lock {
super::select::walk_selectable(d, iso, |n| {
if matches!(n.kind, NodeKind::Path { guide: true, .. }) {
kept.push(n.id);
}
// The walk skips locked objects, so the guide paths in them are looked for here.
for c in n.children().into_iter().flatten().filter(|c| c.locked) {
shown_guides(c, &mut kept);
}
true
});
}
+22 -15
View File
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Fill",
[],
None,
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|freeform, method?: classic|perceptual (as paint.editGradient; default classic), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg, start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits), dither?: bool (linear and radial fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear or radial `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid colour recolours only the gradient mesh point last clicked with the Mesh tool or Direct Selection; while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white) → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}",
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|freeform, method?: classic|perceptual (as paint.editGradient; default classic), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg, start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits), dither?: bool (linear and radial fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear or radial `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid colour recolours only the gradient mesh point last clicked with the Mesh tool or Direct Selection; while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white) → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}",
has_doc,
|s, p| set_paint(s, p, true)
),
@@ -433,29 +433,36 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
&& let Some((id, a, b)) = super::textedit::editing_range(s)?
&& a != b
{
// After Select All in threaded text, every frame's text takes it.
let story = 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();
// When the type comes out as it was, the document and its undo history stay as they are.
let before = s.doc()?.doc.clone();
super::overprint::edit_counted(s, if fill { "Fill Color" } else { "Stroke Color" }, |d| {
let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(id)) };
let (xf, lb) = (t.xf, t.local_bounds());
vectorcraft_text::edit::style_range(&mut t.runs, a, b, |st| {
if fill {
st.fill = place_run_paint(&paint, p, xf, lb);
} else {
if !paint.is_none() {
run_stroke_weight(st);
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)) };
let (xf, lb) = (t.xf, t.local_bounds());
vectorcraft_text::edit::style_range(&mut t.runs, a, b, |st| {
if fill {
st.fill = place_run_paint(&paint, p, xf, lb);
} else {
if !paint.is_none() {
run_stroke_weight(st);
}
st.stroke = place_run_paint(&paint, p, xf, vectorcraft_doc::appearance::stroke_paint_bounds(lb, st.stroke_width));
}
st.stroke = place_run_paint(&paint, p, xf, vectorcraft_doc::appearance::stroke_paint_bounds(lb, st.stroke_width));
}
});
super::typecmd::refresh_bounds(t);
Ok(super::appearance::count_changed(d, &before, &[id]))
});
super::typecmd::refresh_bounds(t);
}
Ok(super::appearance::count_changed(d, &before, &ids))
})?;
if focus {
s.fill_active = fill;
}
s.remember_paint(&paint);
return Ok(json!({"objects": 1}));
return Ok(json!({"objects": ids.len()}));
}
// Resolve the requested targets before mutating defaults or the active proxy.
let item = item_target(s, p, cmd)?.of_kind(s, fill);
+19 -6
View File
@@ -303,16 +303,30 @@ fn is_effect_color(v: &Value) -> bool {
pub(crate) fn check_effect_color(id: &str, effect: &str, params: &Value) -> Result<()> {
let key = "color";
let Some(v) = params.get(key) else { return Ok(()) };
if effect.starts_with(vectorcraft_plugins::effect::PREFIX) {
return Ok(());
}
let takes_color = vectorcraft_render::effects::effect_info(effect).is_some_and(|info| info.defaults.get(key).is_some_and(Value::is_string));
if takes_color && !is_effect_color(v) {
if effect_takes_color(effect) && !is_effect_color(v) {
return Err(bad(id, format!("`{key}` must be a #rrggbb color")));
}
Ok(())
}
/// Does built-in effect `effect` have a `color` parameter (one whose default is a string)? Plug-in
/// effects have none here.
pub(crate) fn effect_takes_color(effect: &str) -> bool {
!effect.starts_with(vectorcraft_plugins::effect::PREFIX)
&& vectorcraft_render::effects::effect_info(effect).is_some_and(|info| info.defaults.get("color").is_some_and(Value::is_string))
}
/// The color that built-in effect `effect` draws with `params`: their `color`, else the effect's
/// default color. `None` when the effect has no `color` parameter ([`effect_takes_color`]) or
/// `params` hold a `color` it can't read ([`is_effect_color`]).
pub(crate) fn effect_color(effect: &str, params: &Value) -> Option<vectorcraft_color::Color> {
if !effect_takes_color(effect) || params.get("color").is_some_and(|v| !is_effect_color(v)) {
return None;
}
let merged = vectorcraft_render::effects::merged_params(effect, params);
Some(vectorcraft_render::effects::color_param(&merged, vectorcraft_color::Color::BLACK))
}
/// The `channel` in `params` of Levels or Curves (`effect`), as command `id` was given it: a
/// parameter error naming the channels unless the effect reads it
/// ([`vectorcraft_render::effects::is_channel`]); the effect draws any other value as RGB.
@@ -439,7 +453,6 @@ pub const UNCHECKED: &[&str] = &[
"shape.flare",
"shape.polarGrid",
"shape.rectangularGrid",
"stroke.set",
"stroke.setAdvanced",
"swatch.edit",
"swatch.library.load",
+24 -7
View File
@@ -112,7 +112,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Convert Anchor Points",
[],
None,
"{to: \"corner\"|\"smooth\"} convert the direct-selected anchors (all anchors of fully selected paths, every point of a selected blend's spine) as one undo step: corner retracts both handles, smooth pulls handles in line with the neighbours (smooth anchors keep theirs)",
"{to: \"corner\"|\"smooth\"} convert the direct-selected anchors (all anchors of fully selected paths, every point of a selected blend's spine; a spine from Replace Spine changes only its handles, its points and the keys' spread along it staying as they are) as one undo step: corner retracts both handles, smooth pulls handles in line with the neighbours (smooth anchors keep theirs)",
has_selection,
convert_anchors
),
@@ -1155,11 +1155,7 @@ fn convert_anchors(s: &mut Session, p: &Value) -> Result<Value> {
}
}
}
for id in &blends {
let Some(NodeKind::Blend { children, spec }) = d.node_mut(*id).map(|n| &mut n.kind) else { continue };
let Some((mut path, anchors)) = vectorcraft_doc::live::pin_spine(children, spec) else { continue };
let pinned = path.clone();
let Some(sp) = path.subpaths.first_mut() else { continue };
let convert = |sp: &mut SubPath| {
for ai in 0..sp.anchors.len() {
if smooth {
sp.smooth_anchor(ai);
@@ -1167,6 +1163,21 @@ fn convert_anchors(s: &mut Session, p: &Value) -> Result<Value> {
a.retract();
}
}
};
for id in &blends {
let Some(NodeKind::Blend { children, spec }) = d.node_mut(*id).map(|n| &mut n.kind) else { continue };
// A spine from Replace Spine keeps its points and its keys spread along it: only the
// handles change, and the keys are not pinned to points.
if vectorcraft_doc::live::blend_spine(children, spec).is_some_and(|(_, anchors)| anchors.is_none()) {
if let Some(sp) = spec.spine.as_mut().and_then(|p| p.subpaths.first_mut()) {
convert(sp);
}
continue;
}
let Some((mut path, anchors)) = vectorcraft_doc::live::pin_spine(children, spec) else { continue };
let pinned = path.clone();
let Some(sp) = path.subpaths.first_mut() else { continue };
convert(sp);
// A spine the conversion leaves as it was stays as the blend has it.
if path != pinned {
spec.key_anchors = anchors.iter().map(|a| u32::try_from(*a).unwrap_or(u32::MAX)).collect();
@@ -1178,7 +1189,9 @@ fn convert_anchors(s: &mut Session, p: &Value) -> Result<Value> {
ok()
}
pub(crate) fn delete_anchors(s: &mut Session, _: &Value) -> Result<Value> {
pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> {
// `guides: true` (Cut, #3226): the selected ruler guides go in the same undo step.
let with_guides = p.get("guides").and_then(Value::as_bool).unwrap_or(false);
let st = s.doc()?;
let sel = st.selection.anchors.clone();
let segments = st.selection.segments.clone();
@@ -1186,6 +1199,10 @@ pub(crate) fn delete_anchors(s: &mut Session, _: &Value) -> Result<Value> {
// also catches part of another path must still delete those whole objects.
let whole = st.selection.whole();
s.edit("Clear", |d, selection| {
if with_guides {
let gone = selection.guides.clone();
d.retain_guides(selection, |i, _| !gone.contains(&i));
}
let targets: BTreeSet<NodeId> = whole.into_iter().filter(|id| d.node(*id).is_some_and(|n| !n.is_layer())).collect();
let whole_ids: Vec<NodeId> = targets
.iter()
+2 -1
View File
@@ -338,8 +338,9 @@ pub(crate) fn full_documents(d: &Document) -> (Cow<'_, Document>, Vec<String>) {
Cow::Owned(doc) => doc,
};
let mut need: Vec<PlacedDocument> = vec![];
let mut seen = std::collections::HashSet::new();
doc.visit_placed(|_, p| {
if doc.images.get(&p.key).is_some_and(ImageBlob::is_proxy) && !need.iter().any(|n| n.key == p.key) {
if doc.images.get(&p.key).is_some_and(ImageBlob::is_proxy) && seen.insert(p.key.clone()) {
need.push(p.clone());
}
});
+2 -2
View File
@@ -185,7 +185,7 @@ impl FilterRun {
if let Some(data) = out.document_data {
d.set_plugin_data(&m.id, data);
}
sel.set(ids.iter().copied());
sel.set(ids.iter().copied().filter(|&id| d.node(id).is_some_and(objects::selectable)));
Ok(ids)
})?;
Ok(json!({"plugin": m.id, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()}))
@@ -432,7 +432,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Run Plug-in",
[],
None,
"{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [..] (default: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths are left out): it may change, delete or add objects, as one undo step; the result is selected. With nothing selected it gets no objects (generators add theirs to the current layer) → {plugin, ids}",
"{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [..] (default: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths are left out): it may change, delete or add objects, as one undo step; the result is selected, except the objects it locked or made guides. With nothing selected it gets no objects (generators add theirs to the current layer) → {plugin, ids}",
has_doc,
run
),
+4 -3
View File
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Recolor Artwork",
["Edit", "Edit Colors"],
None,
"{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex)], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null, exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour] (what `group` is rewritten with; default: the rows' new colours, in order, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model)}",
"{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex)], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour] (what `group` is rewritten with; default: the rows' new colours, in order, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model)}",
has_doc,
apply
),
@@ -255,13 +255,14 @@ enum Match {
}
impl Match {
/// A colour key, a hex (`#rrggbb`) or a colour value.
/// A colour key, a hex (`#rrggbb`) or a colour value. `None` for a hex color with an alpha
/// part (`#rrggbbaa` or `#rgba`).
fn of(v: &Value) -> Option<Self> {
if let Some(s) = v.as_str() {
if let Some(k) = ColorKey::parse(s) {
return Some(Match::Key(k));
}
return Color::from_hex(s).map(|c| Match::Hex(c.to_hex()));
return Color::from_hex(s).filter(|_| !super::hex_with_alpha(s)).map(|c| Match::Hex(c.to_hex()));
}
color_value(v).map(|c| Match::Key(ColorKey::of(&c)))
}
+57 -18
View File
@@ -20,7 +20,7 @@ pub fn specs() -> Vec<CommandSpec> {
"All",
["Select"],
Some("Cmd+A"),
"{} → {count}; while the Type tool edits text, all of that text instead → {editing, start, end} (byte offsets)",
"{} → {count}; while the Type tool edits text, all of that text instead → {editing, start, end} (byte offsets); in a frame of threaded text, the whole story: the tool edits the thread's first frame that holds text (selected when it was not) with the text of every frame selected → {editing, start, end, story: [id…] (the frames in thread order)}",
has_doc,
all
),
@@ -98,7 +98,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Select by Color",
[],
None,
"{fill?: colour, stroke?: colour (as paint.setFill's color; at least one)} select the objects whose fill (and stroke) reads as that colour in #rrggbb, as document.inspect reports colours, whatever its swatch or tint; with both, the objects that match both. No object needs to be selected first; Select > Reselect repeats it → {count}",
"{fill?: colour, stroke?: colour (as paint.setFill's color, #rrggbbaa and #rgba refused; at least one)} select the objects whose fill (and stroke) reads as that colour in #rrggbb, as document.inspect reports colours, whatever its swatch or tint; with both, the objects that match both. No object needs to be selected first; Select > Reselect repeats it → {count}",
has_doc,
select_color
),
@@ -107,7 +107,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Fill Color",
["Select", "Same"],
None,
"{} the objects filled with the first selected object's fill colour (any tint of its global or spot swatch, the same tint with prefs selectSameTintPercent); a member path of a compound path selected first compares as its compound path, except in isolation mode inside that compound path; from a Live Paint face, the faces of its Live Paint group only, and from any other object, no Live Paint face",
"{} the objects filled with the first selected object's fill colour (any tint of its global or spot swatch, the same tint with prefs selectSameTintPercent); a member path of a compound path selected first compares as its compound path, except in isolation mode inside that compound path; from a Live Paint face, the faces of its Live Paint group only, and from any other object, no Live Paint face; every select.same command that compares with the first selected object passes over a selected object that is hidden or locked, on a template layer or outside the isolated group",
has_selection,
|s, _| {
let tint = s.prefs.select_same_tint_percent;
@@ -267,10 +267,41 @@ pub(crate) fn is_selectable(d: &Document, iso: Option<NodeId>, locks: &LockedArt
}
}
/// The first selected object, in selection order, that [`is_selectable`] accepts.
pub(crate) fn first_selectable(st: &DocState) -> Option<&Node> {
let locks = st.doc.locked_artboards();
st.selection.objects.iter().find(|id| is_selectable(&st.doc, st.isolation, &locks, **id)).and_then(|id| st.doc.node(*id))
}
fn all(s: &mut Session, _: &Value) -> Result<Value> {
// While the Type tool edits text, Select All takes all of that text and leaves the art
// selection as it is (Illustrator: text cursor in a text object).
if s.tool_wants_text() {
// In a frame of threaded text, the whole story: the tool edits its first frame that holds
// text with every frame's text selected, and that frame is selected when it was not.
let editing = s.tool_options()["editing"].as_u64().map(NodeId);
let story = match editing {
Some(id) => super::threads::story_of(&s.doc()?.doc, id),
None => vec![],
};
if let Some(&first) = story.first() {
let d = &s.doc()?.doc;
let holds_text = |f: &NodeId| matches!(d.node(*f).map(|n| &n.kind), Some(NodeKind::Text(t)) if t.runs.iter().any(|r| !r.text.is_empty()));
let first = story.iter().copied().find(holds_text).unwrap_or(first);
super::textedit::editing_range(s)?;
let ids: Vec<u64> = story.iter().map(|id| id.0).collect();
s.set_tool_option("selectAll", &json!({ "story": ids, "editing": first.0 }));
let st = s.doc()?;
let selected = std::iter::successors(Some(first), |c| st.doc.parent_of(*c)).any(|c| st.selection.contains(c));
if !selected {
s.select(|_, sel| sel.set([first]))?;
}
let end = match s.doc()?.doc.node(first).map(|n| &n.kind) {
Some(NodeKind::Text(t)) => t.plain_text().len(),
_ => 0,
};
return Ok(json!({ "editing": first.0, "start": 0, "end": end, "story": ids }));
}
s.set_tool_option("selectAll", &json!(true));
let editing = s.tool_options()["editing"].clone();
let id = editing.as_u64().map(NodeId);
@@ -290,21 +321,19 @@ fn all_on_artboard(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.doc()?;
let i = p.get("artboard").and_then(Value::as_u64).map_or(0, index);
let r = st.doc.artboards.get(i).map(|a| a.rect).ok_or_else(|| bad("select.allOnArtboard", "no such artboard"))?;
// Symbol instances are measured by their art.
let symbols = st.doc.symbol_boxes();
let ids: Vec<NodeId> = selectable(&st.doc, st.isolation)
.into_iter()
.filter(|id| {
st.doc
.node(*id)
.and_then(|n| n.geometric_bounds_with(&symbols))
.is_some_and(|b| b.intersect(r).area() > 0.0 || vectorcraft_doc::artboard_holds(r, b.center()))
})
.collect();
let ids: Vec<NodeId> =
selectable(&st.doc, st.isolation).into_iter().filter(|id| st.doc.node(*id).is_some_and(|n| on_artboard(n, &symbols, r))).collect();
s.select(|_, sel| sel.set(ids.iter().copied()))?;
ok()
}
/// Is `n` on the artboard at `r`, as All on Active Artboard takes it: its geometric bounds (a
/// symbol instance's measured by its art) overlap the artboard, or its center is on it.
pub(crate) fn on_artboard(n: &Node, symbols: &vectorcraft_doc::SymbolBoxes, r: vectorcraft_geom::Rect) -> bool {
n.geometric_bounds_with(symbols).is_some_and(|b| b.intersect(r).area() > 0.0 || vectorcraft_doc::artboard_holds(r, b.center()))
}
fn none(s: &mut Session, _: &Value) -> Result<Value> {
s.select(|_, sel| sel.clear())?;
ok()
@@ -686,12 +715,14 @@ fn paint_reported(d: &Document, n: &Node) -> bool {
}
/// The object Select > Same compares the others with, and whether isolation mode is inside a
/// compound path. The object is the first selected one, or its compound path when it is a member
/// of one; in isolation mode inside a compound path it is the member path itself.
/// compound path. The object is the first selected one that [`is_selectable`] accepts (none that is
/// hidden, locked, on a hidden, locked or template layer, or outside the isolated group), or its
/// compound path when it is a member of one; in isolation mode inside a compound path it is the
/// member path itself.
fn same_reference<'a>(st: &'a DocState, cmd: &str) -> Result<(&'a Node, bool)> {
let compound = |n: &Node| matches!(n.kind, NodeKind::Compound { .. });
let members = st.isolation.and_then(|i| st.doc.ancestry(i)).is_some_and(|a| a.iter().any(|i| st.doc.node(*i).is_some_and(compound)));
let first = st.selection.objects.first().and_then(|id| st.doc.node(*id)).ok_or_else(|| bad(cmd, "nothing selected"))?;
let first = first_selectable(st).ok_or_else(|| bad(cmd, "nothing selected"))?;
let refn = match st.doc.parent_of(first.id).and_then(|p| st.doc.node(p)) {
Some(p) if !members && compound(p) => p,
_ => first,
@@ -786,8 +817,16 @@ fn same_attribute(s: &mut Session, p: &Value) -> Result<Value> {
fn same_layers(s: &mut Session, _: &Value) -> Result<Value> {
let st = s.doc()?;
// The layers or sublayers the selected objects are on (art in their sublayers too).
let layers: BTreeSet<NodeId> = st.selection.objects.iter().filter_map(|id| st.doc.layer_containing(*id)).collect();
// The layers or sublayers the selected objects are on (art in their sublayers too). A selected
// object that `is_selectable` does not accept adds no layer.
let locks = st.doc.locked_artboards();
let layers: BTreeSet<NodeId> = st
.selection
.objects
.iter()
.filter(|id| is_selectable(&st.doc, st.isolation, &locks, **id))
.filter_map(|id| st.doc.layer_containing(*id))
.collect();
let mut on = BTreeSet::new();
for l in layers.iter().filter_map(|l| st.doc.node(*l)) {
l.walk(&mut |n| {
+2 -1
View File
@@ -99,7 +99,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Slice Options…",
["Object", "Slice"],
None,
"{kind?: \"image\"|\"noImage\"|\"htmlText\" (object slices of type only), name?, url?, target?, message?, alt?: (image), text?: cell text; HTML allowed (noImage), background?: \"\"|\"matte\"|\"#rrggbb\", hAlign?: \"default\"|\"left\"|\"center\"|\"right\", vAlign?: \"default\"|\"top\"|\"middle\"|\"baseline\"|\"bottom\"} set the selected slices' options as one undo step; no options: read them → the first slice's {kind, name, url, target, message, alt, text, background, hAlign, vAlign, htmlText: whether HTML Text applies}",
"{kind?: \"image\"|\"noImage\"|\"htmlText\" (object slices of type only), name?, url?, target?, message?, alt?: (image), text?: cell text; HTML allowed (noImage), background?: \"\"|\"matte\"|\"#rrggbb\" (#rrggbbaa and #rgba are refused), hAlign?: \"default\"|\"left\"|\"center\"|\"right\", vAlign?: \"default\"|\"top\"|\"middle\"|\"baseline\"|\"bottom\"} set the selected slices' options as one undo step; no options: read them → the first slice's {kind, name, url, target, message, alt, text, background, hAlign, vAlign, htmlText: whether HTML Text applies}",
slices_targeted,
options
),
@@ -513,6 +513,7 @@ impl Edits {
"" | "none" => Ok(String::new()),
"matte" => Ok("matte".to_string()),
_ => vectorcraft_color::Color::from_hex(&b)
.filter(|_| !super::hex_with_alpha(&b))
.map(|c| c.to_hex())
.ok_or_else(|| bad(C, "`background` must be \"\", \"matte\" or #rrggbb")),
})
+1 -1
View File
@@ -20,7 +20,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Stroke Options",
["Window", "Stroke"],
None,
"{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\"} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does) → {objects: how many objects took the stroke options}",
"{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does) → {objects: how many objects took the stroke options}",
has_doc,
stroke_set
),
+6 -5
View File
@@ -20,7 +20,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New Swatch",
["Window", "Swatches"],
None,
"{name?, color? | colors?: [colour] (one swatch each, in one undo step) | swatch? | gradient? | pattern?: name (default: the current fill), tint?: 0..100 (% of the global or spot `swatch`, or of the one the current fill links to), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour; lab: CIE L*a*b*, how spot colours are usually defined), global?, spot? (a spot colour, always global), group?: colour group name (solid colours only; default: ungrouped), none?: true (the None paint), paint?: paint.setFill params, keepModel?: bool (as paint.setFill)} save a colour, gradient or pattern as a swatch. A tint of a global or spot colour (below 100%, without mode, global or spot) becomes a tint swatch, \"Name 40%\", linked to its base: it follows edits to the base and applies as that tint of it. Names are unique (\"Sky 2\"); a colour's default name is its values (\"C=10 M=20 Y=30 K=0\", \"R=255 G=128 B=0\", \"Gray K=40\", \"L=55 a=60 b=40\") → {name, names: [every new swatch]}",
"{name?, color? | colors?: [colour] (one swatch each, in one undo step; #rrggbbaa and #rgba are refused) | swatch? | gradient? | pattern?: name (default: the current fill), tint?: 0..100 (% of the global or spot `swatch`, or of the one the current fill links to), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour; lab: CIE L*a*b*, how spot colours are usually defined), global?, spot? (a spot colour, always global), group?: colour group name (solid colours only; default: ungrouped), none?: true (the None paint), paint?: paint.setFill params, keepModel?: bool (as paint.setFill)} save a colour, gradient or pattern as a swatch. A tint of a global or spot colour (below 100%, without mode, global or spot) becomes a tint swatch, \"Name 40%\", linked to its base: it follows edits to the base and applies as that tint of it. Names are unique (\"Sky 2\"); a colour's default name is its values (\"C=10 M=20 Y=30 K=0\", \"R=255 G=128 B=0\", \"Gray K=40\", \"L=55 a=60 b=40\") → {name, names: [every new swatch]}",
has_doc,
swatch_new
),
@@ -38,7 +38,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New Color Group",
["Window", "Swatches"],
None,
"{name?, swatches?: [names] (solid colours move into the group; gradients, patterns and None stay), colors?: [colour] (added as new swatches), keepModel?: bool (as paint.setFill), fromArtwork?: false (add the unique colours of the selected art: fills, strokes, text, gradient stops and mesh points; a colour linked to a global swatch moves that swatch into the group), toGlobal?: true (with fromArtwork: the new swatches are global and the selected art's matching unlinked colours link to them), includeTints?: false (with fromArtwork: tints of global swatches also get swatches of their own)} → {name, swatches: [names in the group], linked: paints linked}",
"{name?, swatches?: [names] (solid colours move into the group; gradients, patterns and None stay), colors?: [colour] (added as new swatches; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), fromArtwork?: false (add the unique colours of the selected art: fills, strokes, text, gradient stops and mesh points; a colour linked to a global swatch moves that swatch into the group), toGlobal?: true (with fromArtwork: the new swatches are global and the selected art's matching unlinked colours link to them), includeTints?: false (with fromArtwork: tints of global swatches also get swatches of their own)} → {name, swatches: [names in the group], linked: paints linked}",
has_doc,
swatch_new_group
),
@@ -49,7 +49,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Swatch Options",
["Window", "Swatches"],
None,
"{name, newName?, color? (e.g. {l, a, b} for a Lab colour), keepModel?: bool (as paint.setFill; the swatch's own color and a color given with mode keep their model), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour), global?, spot? (spot colours are always global), paint?: paint.setFill params ({color}, {gradient}, {swatch} or {pattern}) replacing the swatch's colour; gradient or pattern with one of the same kind} edit a swatch in any colour group, as one undo step. Fills, strokes, text, gradient stops and tint swatches linked to a global swatch take its new colour (at their own tint) and name; turning Global off unlinks them (they keep their colour). Colour, mode and spot apply to solid colours only; a tint swatch only takes a new name (edit its base) → {name, relinked: paints changed}",
"{name, newName?, color? (e.g. {l, a, b} for a Lab colour; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill; the swatch's own color and a color given with mode keep their model), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour), global?, spot? (spot colours are always global), paint?: paint.setFill params ({color}, {gradient}, {swatch} or {pattern}) replacing the swatch's colour; gradient or pattern with one of the same kind} edit a swatch in any colour group, as one undo step. Fills, strokes, text, gradient stops and tint swatches linked to a global swatch take its new colour (at their own tint) and name; turning Global off unlinks them (they keep their colour). Colour, mode and spot apply to solid colours only; a tint swatch only takes a new name (edit its base) → {name, relinked: paints changed}",
has_doc,
swatch_edit
),
@@ -130,7 +130,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Edit Color Group",
["Window", "Swatches"],
None,
"{group: colour group, colors: [colour] (hex, key, {c,m,y,k} or {l,a,b}; the group's swatches take them in order, extra colours become new swatches, swatches past the end are removed; built-in swatches can't change; a color the swatch already has keeps its model), keepModel?: bool (as paint.setFill), rename?: new group name} rewrite a colour group as one undo step; art linked to its global swatches takes their new colours (and keeps its colour, unlinked, when its swatch goes) → {name, swatches: [names], relinked}",
"{group: colour group, colors: [colour] (hex, key, {c,m,y,k} or {l,a,b}; #rrggbbaa and #rgba are refused; the group's swatches take them in order, extra colours become new swatches, swatches past the end are removed; built-in swatches can't change; a color the swatch already has keeps its model), keepModel?: bool (as paint.setFill), rename?: new group name} rewrite a colour group as one undo step; art linked to its global swatches takes their new colours (and keeps its colour, unlinked, when its swatch goes) → {name, swatches: [names], relinked}",
has_doc,
swatch_edit_group
),
@@ -316,7 +316,8 @@ fn swatch_new_group(s: &mut Session, p: &Value) -> Result<Value> {
let colors: Vec<Color> = p
.get("colors")
.and_then(Value::as_array)
.map(|a| a.iter().filter_map(color_value).map(|c| super::paint::new_color(s, p, c)).collect())
.map(|a| a.iter().map(|v| color_value(v).map(|c| super::paint::new_color(s, p, c)).ok_or_else(|| bad(C, format!("bad color {v}")))).collect())
.transpose()?
.unwrap_or_default();
let from_art = bool_or(p, "fromArtwork", false);
let to_global = from_art && bool_or(p, "toGlobal", true);
+35 -4
View File
@@ -13,6 +13,7 @@ use serde_json::{Value, json};
use vectorcraft_color::libraries::{BuiltinLibrary, GRADIENT_LIBRARIES, SWATCH_LIBRARIES, builtin_library};
use vectorcraft_color::palette_io::{self, PaletteFormat};
use vectorcraft_color::recolor::Palette;
use vectorcraft_color::swatch::REGISTRATION;
use vectorcraft_color::{Paint, Swatch, SwatchGroup, SwatchLibrary, default_swatches};
use vectorcraft_doc::pattern::pattern_paint;
@@ -587,8 +588,9 @@ fn copy_to_user(s: &mut Session, p: &Value) -> Result<Value> {
/// ungrouped): a group's name brings the group, a swatch's name the swatch alone; no names, all.
fn picked<'a>(lib: &'a SwatchLibrary, names: &[String], cmd: &str) -> Result<Vec<(Option<&'a str>, &'a Swatch)>> {
let mut out: Vec<(Option<&str>, &Swatch)> = vec![];
let mut seen: HashSet<&str> = HashSet::new();
let mut push = |g: Option<&'a str>, w: &'a Swatch| {
if !out.iter().any(|(_, x)| x.name == w.name) {
if seen.insert(w.name.as_str()) {
out.push((g, w));
}
};
@@ -606,6 +608,23 @@ fn picked<'a>(lib: &'a SwatchLibrary, names: &[String], cmd: &str) -> Result<Vec
Ok(out)
}
/// Every name a swatch or colour group of `d` uses (they share one namespace, with the registration swatch).
fn taken_names(d: &vectorcraft_doc::Document) -> HashSet<String> {
let names = d.swatches_iter().map(|w| &w.name).chain(d.swatch_groups.iter().map(|g| &g.name));
names.cloned().chain([REGISTRATION.to_string()]).collect()
}
/// [`vectorcraft_doc::Document::free_swatch_name`] against `taken`, which takes the name returned.
fn free_in(taken: &mut HashSet<String>, base: &str) -> String {
let name = if taken.contains(base) {
(2..).map(|i| format!("{base} {i}")).find(|n| !taken.contains(n)).unwrap_or_else(|| base.to_string())
} else {
base.to_string()
};
taken.insert(name.clone());
name
}
fn add(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "swatch.library.add";
let (info, lib) = library_param(s, p, C)?;
@@ -621,11 +640,21 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
// same pattern) are reused, not added again.
let patterns = patternlib::library_doc(&info.id);
let d = &s.doc()?.doc;
// The document's swatches by name (the first of a name wins, as in `Document::swatch`), looked
// up once so that a large palette takes linear time.
let mut by_name: std::collections::HashMap<&str, &Swatch> = std::collections::HashMap::new();
for w in d.swatches_iter() {
by_name.entry(w.name.as_str()).or_insert(w);
}
let there = |w: &Swatch| match (&w.paint, &patterns) {
(Paint::Pattern { pattern, .. }, Some(src)) => {
patternlib::existing_pattern(d, src, pattern).and_then(|target| patternlib::pattern_swatch(d, &target))
}
_ => d.swatch(&w.name).is_some_and(|x| x.paint == w.paint).then(|| w.name.clone()),
_ => match by_name.get(w.name.as_str()) {
Some(x) => x.paint == w.paint,
None => w.name == REGISTRATION && d.swatch(&w.name).is_some_and(|x| x.paint == w.paint),
}
.then(|| w.name.clone()),
};
// Library name → the name of the document's swatch.
let mut existing: Vec<(String, String)> = vec![];
@@ -647,6 +676,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
// already had, or one made here.
let before = d.swatch_groups.len();
let mut placed: Vec<(&str, usize)> = vec![];
let mut taken = taken_names(d);
for (group, w) in fresh {
if let (Paint::Pattern { pattern, .. }, Some(src)) = (&w.paint, &patterns) {
// The pattern comes with its swatch; a pattern the document has without one
@@ -661,9 +691,10 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
}
};
out.push((w.name.clone(), name));
taken = taken_names(d);
continue;
}
let name = d.free_swatch_name(&w.name);
let name = free_in(&mut taken, &w.name);
let sw = Swatch { name: name.clone(), ..(*w).clone() };
match group {
Some(g) => {
@@ -671,7 +702,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
let i = match found.or_else(|| d.swatch_groups.iter().take(before).position(|x| x.name == *g)) {
Some(i) => i,
None => {
let name = d.free_swatch_name(g);
let name = free_in(&mut taken, g);
d.swatch_groups.push(SwatchGroup { name, swatches: vec![] });
d.swatch_groups.len() - 1
}
+39
View File
@@ -69,6 +69,18 @@ fn apply(s: &mut Session, p: &Value, stops: Vec<TabStop>, label: &str) -> Result
let ids = text_targets(s, p, "text.tabs.set")?;
let range = TextRange::parse(p, "text.tabs.set")?;
let n = stops.len();
// Every targeted paragraph already holds these stops: no edit and no undo step.
let doc = &s.doc()?.doc;
let unchanged = ids.iter().all(|id| match doc.node(*id).map(|node| &node.kind) {
Some(NodeKind::Text(t)) => match para_span(range, t) {
None => t.para_styles().all(|pa| pa.tabs == stops),
Some(mut r) => r.all(|i| t.para_at(i).tabs == stops),
},
_ => true,
});
if unchanged {
return Ok(json!({ "stops": n }));
}
s.edit(label, |d, _| {
for id in &ids {
if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) {
@@ -114,6 +126,33 @@ mod tests {
assert_eq!(s.execute("text.tabs.get", &json!({})).unwrap()["stops"], json!([]));
}
/// Setting the stops every targeted paragraph already holds records no undo step. When one
/// targeted paragraph holds other stops, the command still sets them all.
#[test]
fn setting_the_same_stops_records_no_undo_step() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
s.execute("text.create", &json!({"x": 10, "y": 20, "text": "a\tb\nc\td"})).unwrap();
let stops = json!({"stops": [{"position": 0}, {"position": 20, "leader": "."}]});
s.execute("text.tabs.set", &stops).unwrap();
let undo = |s: &Session| s.active().unwrap().history.undo.len();
let before = undo(&s);
s.execute("text.tabs.set", &stops).unwrap();
s.execute("text.tabs.set", &json!({"stops": [{"position": 20, "leader": "."}, {"position": 0}]})).unwrap();
assert_eq!(undo(&s), before);
s.execute("text.tabs.clear", &json!({})).unwrap();
s.execute("text.tabs.clear", &json!({})).unwrap();
assert_eq!(undo(&s), before + 1);
// The second paragraph (bytes 4 on) takes other stops; setting the first paragraph's stops
// on both paragraphs changes the second.
s.execute("text.tabs.set", &stops).unwrap();
s.execute("text.tabs.set", &json!({"stops": [{"position": 50}], "start": 4, "end": 4})).unwrap();
let before = undo(&s);
s.execute("text.tabs.set", &stops).unwrap();
assert_eq!(undo(&s), before + 1);
assert_eq!(s.execute("text.tabs.get", &json!({"start": 4})).unwrap()["stops"][1]["position"], json!(20.0));
}
/// #1877: a leader set the way the Tabs panel sets it fills the tab's gap with its dots.
#[test]
fn tab_leader_fills_the_gap_with_its_characters() {
+312 -39
View File
@@ -7,6 +7,7 @@ use vectorcraft_doc::{Appearance, CharStyle, Node, NodeId, NodeKind, TextKind, T
use vectorcraft_geom::{Affine, Point, Vec2};
use vectorcraft_text::edit;
use super::menucmds::whole_or;
use super::stroke::StrokeChange;
use super::typecmd::refresh_bounds;
use super::{
@@ -21,7 +22,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Edit Text",
[],
None,
"{id, start: byte, end: byte, insert?: string, runs?: [{text, style}]} replace bytes start..end of the plain text (inserted text takes the replaced text's style unless styled `runs` are given) → {id, caret}",
"{id, start: byte, end: byte, insert?: string, runs?: [{text, style}], clear?: [id…] (other type objects whose whole text goes in the same edit, as when typing replaces a threaded story that Select All selected)} replace bytes start..end of the plain text (inserted text takes the replaced text's style unless styled `runs` are given) → {id, caret}",
has_doc,
edit_range
),
@@ -39,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Character",
[],
None,
"{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\", keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], featureChanges?: [\"tnum\", \"-onum\", …] (OpenType features turned on, or with - off, on top of each character's own; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}",
"{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], featureChanges?: [\"tnum\", \"-onum\", …] (OpenType features turned on, or with - off, on top of each character's own; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}",
has_doc,
set_range_style
),
@@ -52,12 +53,30 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
touch_type
),
cmd!(
"text.setGlyphAlternate",
"Glyphs",
[],
None,
"{id, start: byte (a character of it), gid: glyph id|null} draw that one character with another glyph of its font as one undo step, what a double-click in the Glyphs panel's Show › Alternates for Current Selection does: gid is one of the glyphs text.glyphAlternates lists for it; its own default glyph, or null, puts the default glyph back. The text keeps the character, and its other attributes do not change. The choice is saved with the character's style and names the face it was made in (PostScript name and version): set in another font or version, or after the font goes missing, the character takes its default glyph; typed characters take their default glyphs. Choosing the glyph the character already draws is not an edit. An error when the character's font is not available, the glyph is not one of its alternates, or the character's style does not draw it (All Caps, Small Caps, another numeral system) → {id, start, end (the character's bytes), gid (the glyph drawn)}",
has_doc,
set_glyph_alternate
),
cmd!(
query "text.glyphAlternates",
"Glyphs",
[],
None,
"{id, start: byte (a character of it)} the alternate glyphs of that character in its font, what the Glyphs panel's Show › Alternates for Current Selection lists: from the font's OpenType GSUB table, the glyphs that single and alternate substitutions put in place of the character's default glyph, `aalt` first, then `salt`, `ss01` to `ss20`, `swsh`, `cv01` to `cv99`, `hist`, `jalt`, `nalt`, `ornm` and `titl`, each glyph once, the default glyph only when `aalt` lists it → {char, font: family, style: style, default: glyph id, chosen: glyph id (the glyph drawn now), alternates: [{gid, feature}]} (empty when the font has none for it; an error when the character's font is not available)",
has_doc,
glyph_alternates
),
cmd!(
query "text.getRange",
"Get Text Range",
[],
None,
"{id, start?, end?, effective?: bool = false} → {text, runs: [{text, style}], length}; effective uses document-point size/leading/baseline shift and transformed horizontal scale; default returns stored local styles for rich-text copying",
"{id, start?, end?, effective?: bool = false, story?: bool = false (the whole text of the threaded story `id` is a frame of, its frames in thread order; no `start` or `end`)} → {text, runs: [{text, style}], length}; effective uses document-point size/leading/baseline shift and transformed horizontal scale; default returns stored local styles for rich-text copying",
has_doc,
get_range
),
@@ -233,12 +252,21 @@ fn byte_param(p: &Value, k: &str) -> Option<usize> {
p.get(k).and_then(Value::as_u64).map(index)
}
/// The byte offset that `p` gives for `k`, or `default` when `p` leaves it out or gives null. Any
/// other value that is not a whole number of at least 0, such as `"2"`, `-1` or `1.5`, is an error.
fn offset_or(p: &Value, k: &str, default: usize, cmd: &str) -> Result<usize> {
match p.get(k) {
None | Some(Value::Null) => Ok(default),
Some(_) => Ok(index(whole_or(p, k, 0, cmd)?)),
}
}
/// The bytes `start..end` of `p` in text of `len` bytes, clamped and ordered (without them, all of
/// it). A `start` or `end` that is not a number or null, such as `"2"`, is an error.
/// it). A `start` or `end` that is not a whole number of at least 0 or null, such as `"2"`, `-1`
/// or `1.5`, is an error.
fn range_of(p: &Value, len: usize, cmd: &str) -> Result<(usize, usize)> {
check_numbers(p, &["start", "end"], cmd)?;
let a = byte_param(p, "start").unwrap_or(0).min(len);
let b = byte_param(p, "end").unwrap_or(len).min(len);
let a = offset_or(p, "start", 0, cmd)?.min(len);
let b = offset_or(p, "end", len, cmd)?.min(len);
Ok((a.min(b), a.max(b)))
}
@@ -253,7 +281,16 @@ fn edit_range(s: &mut Session, p: &Value) -> Result<Value> {
Some(v) => Some(serde_json::from_value(v.clone()).map_err(|e| bad(C, format!("bad `runs`: {e}")))?),
};
let insert = str_param(p, "insert").unwrap_or("").to_string();
let clear = clear_param(s, p, id, C)?;
let caret = s.edit("Typing", |d, _| {
for other in &clear {
let t = text_mut(d, *other).ok_or(EngineError::NoNode(*other))?;
let len = edit::runs_len(&t.runs);
t.splice_paras(0, len, "");
edit::replace_range(&mut t.runs, 0, len, "");
t.ruby_after_replace(0, len, 0);
refresh_bounds(t);
}
let t = text_mut(d, id).ok_or(EngineError::NoNode(id))?;
// Paragraph styles follow the edit: a split paragraph's new one continues its style, a
// merge keeps the first paragraph's.
@@ -274,13 +311,36 @@ fn edit_range(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"id": id.0, "caret": caret}))
}
/// The `clear` param of `text.editRange`: other type objects whose text the edit removes, each
/// once. An error when it is not a list of ids of type objects other than `id`.
fn clear_param(s: &Session, p: &Value, id: NodeId, c: &str) -> Result<Vec<NodeId>> {
let ids = match p.get("clear") {
None | Some(Value::Null) => return Ok(vec![]),
Some(Value::Array(ids)) => ids,
Some(v) => return Err(bad(c, format!("`clear` must be a list of type object ids, not {v}"))),
};
let mut out = vec![];
for v in ids {
let other = v.as_u64().map(NodeId).ok_or_else(|| bad(c, format!("`clear` must be a list of type object ids, not {v}")))?;
if other == id {
return Err(bad(c, "`clear` must not list `id`"));
}
if !matches!(s.doc()?.doc.node(other).map(|n| &n.kind), Some(NodeKind::Text(_))) {
return Err(bad(c, format!("`clear` must list type objects; {} is not one", other.0)));
}
if !out.contains(&other) {
out.push(other);
}
}
Ok(out)
}
fn start_list(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "text.startList";
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?;
check_numbers(p, &["at"], C)?;
let t = text_ref(s, id)?;
let len = edit::runs_len(&t.runs);
let at = byte_param(p, "at").unwrap_or(len).min(len);
let at = offset_or(p, "at", len, C)?.min(len);
let Some((start, list)) = t.typed_list_at(at) else {
return Ok(json!({"id": id.0, "started": false, "caret": at}));
};
@@ -306,6 +366,9 @@ fn start_list(s: &mut Session, p: &Value) -> Result<Value> {
fn get_range(s: &mut Session, p: &Value) -> Result<Value> {
let id = id_param(p, "id").ok_or_else(|| bad("text.getRange", "missing `id`"))?;
if switch_or(p, "story", false, "text.getRange")? {
return get_story(s, p, id);
}
let t = text_ref(s, id)?;
let len = edit::runs_len(&t.runs);
let (a, b) = range_of(p, len, "text.getRange")?;
@@ -319,6 +382,31 @@ fn get_range(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"text": text, "runs": runs, "length": len}))
}
/// `text.getRange {id, story: true}`: the whole text of the story `id` is a frame of, its thread's
/// frames in order (`id` alone when it is in no thread).
fn get_story(s: &mut Session, p: &Value, id: NodeId) -> Result<Value> {
const C: &str = "text.getRange";
if ["start", "end"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) {
return Err(bad(C, "`story` takes the whole story: give no `start` or `end`"));
}
let effective = switch_or(p, "effective", false, C)?;
let story = super::threads::story_of(&s.doc()?.doc, id);
let frames = if story.is_empty() { vec![id] } else { story };
let mut runs = vec![];
for f in frames {
let t = text_ref(s, f)?;
for mut run in edit::slice_runs(&t.runs, 0, edit::runs_len(&t.runs)) {
if effective {
run.style = t.effective_char_style(&run.style).ok_or_else(|| bad(C, "text transform is collapsed or unrepresentable"))?;
}
runs.push(run);
}
}
let text: String = runs.iter().map(|r| r.text.as_str()).collect();
let len = text.len();
Ok(json!({"text": text, "runs": runs, "length": len}))
}
/// Keep `st`'s font style when its family has it, else take the family's closest one: a family
/// whose styles are numbered (W3, W6) has no Regular (#4128). A family that isn't installed keeps
/// the style as it is.
@@ -351,6 +439,8 @@ pub(crate) struct CharChange {
stroke: Option<Paint>,
/// Weight (`strokeWidth`), cap, join, miter limit and dashes of the character stroke.
stroke_opts: StrokeChange,
/// Document points per text-space point for a stroke edit.
stroke_scale: Option<f64>,
underline: Option<bool>,
strikethrough: Option<bool>,
all_caps: Option<bool>,
@@ -641,6 +731,7 @@ impl CharChange {
fill: paint_param(p, "fill", cmd)?,
stroke: paint_param(p, "stroke", cmd)?,
stroke_opts,
stroke_scale: None,
underline: flag("underline"),
strikethrough: flag("strikethrough"),
all_caps: flag("allCaps"),
@@ -723,6 +814,7 @@ impl CharChange {
self.tcy_up_down = self.tcy_up_down.map(|v| local_type_value(t, v, (-1296.0, 1296.0), false, cmd)).transpose()?;
self.tcy_left_right = self.tcy_left_right.map(|v| local_type_value(t, v, (-1296.0, 1296.0), false, cmd)).transpose()?;
self.h_scale = self.h_scale.map(|v| local_type_value(t, v, (1.0, 10000.0), true, cmd)).transpose()?;
self.stroke_scale = Some(vectorcraft_doc::Scaling::factor(t.xf).filter(|k| k.is_finite() && *k > 1e-12).unwrap_or(1.0));
Ok(())
}
@@ -809,10 +901,13 @@ impl CharChange {
st.fill = v.clone();
}
if let Some(v) = &self.stroke {
if !v.is_none() {
super::gradient::run_stroke_weight(st);
}
st.stroke = v.clone();
}
if !self.stroke_opts.is_empty() {
self.stroke_opts.apply_char(st);
self.stroke_opts.apply_char_scaled(st, self.stroke_scale.unwrap_or(1.0));
}
if let Some(v) = self.underline {
st.underline = v;
@@ -853,8 +948,8 @@ impl CharChange {
/// Type › Enable Missing Glyph Protection: after a font change, the characters of `runs` their new
/// font has no glyph for, but their font `before` the change had, keep that font: its family,
/// style, version and Variable Font settings.
pub(crate) fn protect_missing_glyphs(before: &[TextRun], runs: &mut Vec<TextRun>) {
/// style, version and Variable Font settings. Returns the byte ranges that kept their font, in order.
pub(crate) fn protect_missing_glyphs(before: &[TextRun], runs: &mut Vec<TextRun>) -> Vec<(usize, usize)> {
fn chars(runs: &[TextRun]) -> impl Iterator<Item = (usize, char, &CharStyle)> {
runs.iter()
.scan(0, |at, r| {
@@ -886,6 +981,7 @@ pub(crate) fn protect_missing_glyphs(before: &[TextRun], runs: &mut Vec<TextRun>
_ => keep.push((at, end, old)),
}
}
let kept = keep.iter().map(|(a, b, _)| (*a, *b)).collect();
for (a, b, old) in keep {
edit::style_range(runs, a, b, |st| {
st.font_family.clone_from(&old.font_family);
@@ -894,6 +990,30 @@ pub(crate) fn protect_missing_glyphs(before: &[TextRun], runs: &mut Vec<TextRun>
st.font_axes.clone_from(&old.font_axes);
});
}
kept
}
/// The runs of `runs` from byte `a` to `b`, leaving out the ranges `kept` (in order) that Missing
/// Glyph Protection gave their earlier font: the characters a font command set its font on.
pub(crate) fn unprotected_runs(runs: &[TextRun], a: usize, b: usize, kept: &[(usize, usize)]) -> Vec<TextRun> {
let mut out = vec![];
let mut at = a;
for &(k0, k1) in kept {
if k1 <= at {
continue;
}
if k0 >= b {
break;
}
if k0 > at {
out.extend(edit::slice_runs(runs, at, k0));
}
at = k1;
}
if at < b {
out.extend(edit::slice_runs(runs, at, b));
}
out
}
fn set_range_style(s: &mut Session, p: &Value) -> Result<Value> {
@@ -906,37 +1026,54 @@ fn set_range_style(s: &mut Session, p: &Value) -> Result<Value> {
_ => return Err(bad(C, "missing `id`: give one, or select one type object")),
},
};
let mut change = CharChange::parse(p, C, &s.doc()?.doc.setup)?;
super::paint::check_keep_model(p, C)?;
change.store_colors(s, p);
if change.is_empty() {
return Err(bad(C, "nothing to change"));
let story = switch_or(p, "story", false, C)?;
if story && ["start", "end"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) {
return Err(bad(C, "`story` styles the whole story: give no `start` or `end`"));
}
let protect = s.prefs.missing_glyph_protection && (change.font.is_some() || change.style.is_some());
let t = text_ref(s, id)?;
change.localize(&t, C)?;
let (a, b) = range_of(p, edit::runs_len(&t.runs), C)?;
let frames = match super::threads::story_of(&s.doc()?.doc, id) {
all if story && !all.is_empty() => all,
_ => vec![id],
};
// Each frame's change (sizes are in its own text space) and range.
let mut parts = Vec::with_capacity(frames.len());
for f in frames {
let mut change = CharChange::parse(p, C, &s.doc()?.doc.setup)?;
super::paint::check_keep_model(p, C)?;
change.store_colors(s, p);
if change.is_empty() {
return Err(bad(C, "nothing to change"));
}
let t = text_ref(s, f)?;
change.localize(&t, C)?;
let (a, b) = if story { (0, edit::runs_len(&t.runs)) } else { range_of(p, edit::runs_len(&t.runs), C)? };
parts.push((f, change, a, b));
}
let sets_font = parts.first().is_some_and(|(_, change, _, _)| change.font.is_some() || change.style.is_some());
let protect = s.prefs.missing_glyph_protection && sets_font;
// The fonts the styled characters are set in, for the warning.
let mut set = std::collections::BTreeSet::new();
let sets_font = change.font.is_some() || change.style.is_some();
let n = s.edit("Character", |d, _| {
let t = text_mut(d, id).ok_or(EngineError::NoNode(id))?;
if a == b && !t.plain_text().is_empty() {
// An empty range inside text styles nothing (Illustrator keeps it for the next typing).
return Ok(t.runs.len());
let mut n = 0;
for (f, change, a, b) in &parts {
let (a, b) = (*a, *b);
let t = text_mut(d, *f).ok_or(EngineError::NoNode(*f))?;
if a == b && !t.plain_text().is_empty() {
// An empty range inside text styles nothing (Illustrator keeps it for the next typing).
n = if *f == id { t.runs.len() } else { n };
continue;
}
let before = protect.then(|| t.runs.clone());
edit::style_range(&mut t.runs, a, b, |st| change.apply(st));
let kept = before.map(|before| protect_missing_glyphs(&before, &mut t.runs)).unwrap_or_default();
if sets_font {
// Empty text has one run, which the empty range styles. Characters that kept their font aren't the command's.
let styled = if a == b { t.runs.clone() } else { unprotected_runs(&t.runs, a, b, &kept) };
set.extend(styled.iter().map(|r| super::fonts::font_of(&r.style)));
}
refresh_bounds(t);
n = if *f == id { t.runs.len() } else { n };
}
let before = protect.then(|| t.runs.clone());
edit::style_range(&mut t.runs, a, b, |st| change.apply(st));
if let Some(before) = before {
protect_missing_glyphs(&before, &mut t.runs);
}
if sets_font {
// Empty text has one run, which the empty range styles.
let styled = if a == b { t.runs.clone() } else { edit::slice_runs(&t.runs, a, b) };
set.extend(styled.iter().map(|r| super::fonts::font_of(&r.style)));
}
refresh_bounds(t);
Ok(t.runs.len())
Ok(n)
})?;
let mut out = json!({"id": id.0, "runs": n});
if let Some(w) = super::fonts::set_font_warning(set) {
@@ -989,6 +1126,126 @@ pub fn effective_kerning(db: &vectorcraft_text::FontDb, t: &TextObject, lay: &ve
if em > 0.0 { drawn_gap(original).zip(drawn_gap(&base)).map_or(0.0, |(a, b)| (a - b) * 1000.0 / em) } else { 0.0 }
}
/// The character at byte `start` of `p` in text object `t`, its bytes and its font's face. An error
/// when there is no character there, it is an inline graphic, or its font is not available.
fn glyph_target(t: &TextObject, p: &Value, c: &str) -> Result<(char, std::ops::Range<usize>, std::sync::Arc<vectorcraft_text::FontFace>)> {
check_numbers(p, &["start"], c)?;
let start = byte_param(p, "start").ok_or_else(|| bad(c, "missing `start` (the byte offset of a character)"))?;
let mut at = 0;
for run in &t.runs {
let end = at + run.text.len();
if (at..end).contains(&start) {
let ch = run.text.get(start - at..).and_then(|s| s.chars().next()).ok_or_else(|| bad(c, format!("no character at byte {start}")))?;
if run.inline.is_some() {
return Err(bad(c, "an inline graphic has no glyphs"));
}
let db = vectorcraft_text::FontDb::global();
let face = db.style_face(&run.style).filter(|_| db.has_family(&run.style.font_family));
let face = face.ok_or_else(|| bad(c, format!("the font {} is not available", run.style.font_family)))?;
return Ok((ch, start..start + ch.len_utf8(), face));
}
at = end;
}
Err(bad(c, format!("no character at byte {start}")))
}
fn set_glyph_alternate(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "text.setGlyphAlternate";
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?;
let gid = match p.get("gid") {
None => return Err(bad(C, "missing `gid` (a glyph id, or null for the default glyph)")),
Some(Value::Null) => None,
Some(v) => Some(v.as_u64().and_then(|g| u32::try_from(g).ok()).ok_or_else(|| bad(C, format!("`gid` must be a glyph id, not {v}")))?),
};
let t = text_ref(s, id)?;
let (ch, bytes, face) = glyph_target(&t, p, C)?;
let default = face.glyph_for(ch);
let holder = t
.runs
.iter()
.scan(0, |at, r| {
let start = *at;
*at += r.text.len();
Some((start..*at, r))
})
.find(|(bytes_of_run, _)| bytes_of_run.contains(&bytes.start));
let styled =
holder.as_ref().is_some_and(|(_, r)| r.style.all_caps || (r.style.small_caps.is_some() && ch.is_lowercase()) || r.style.digits.map(ch) != ch);
// The glyph the character is drawn with when it holds no choice, drawn alone in its face: a
// feature of its style (`salt`, a stylistic set) can draw another glyph than the default one.
// The default glyph is then kept as a choice, so that it is drawn. A character that is not laid
// out (overflowing text) is shaped alone in its style.
let alone_in_face = |lay: &vectorcraft_text::TextLayout| {
let found = lay.glyphs.iter().find(|g| g.byte <= bytes.start && bytes.start < g.byte.saturating_add(g.len));
found.map(|g| (g.byte == bytes.start && g.len == bytes.len() && g.font_id == face.id()).then_some(g.gid))
};
let unchosen = match holder.as_ref().filter(|_| !styled) {
None => None,
Some((_, run)) => {
let mut probe = t.clone();
edit::style_range(&mut probe.runs, bytes.start, bytes.end, |st| st.glyph_alternate = None);
let db = vectorcraft_text::FontDb::global();
alone_in_face(&vectorcraft_text::layout(db, &probe)).unwrap_or_else(|| {
let st = CharStyle { glyph_alternate: None, ..run.style.clone() };
let single = TextObject::point(Point::ZERO, &ch.to_string(), st);
let lay = vectorcraft_text::layout(db, &single);
lay.glyphs.iter().find(|g| g.byte == 0 && g.len == bytes.len() && g.font_id == face.id()).map(|g| g.gid)
})
}
};
let substituted = unchosen.is_some_and(|g| g != default);
let choice = match gid.filter(|g| *g != default || substituted) {
None => None,
Some(g) if g == default || face.alternates(ch).iter().any(|a| a.gid == g) => Some(face.choice(ch, g)),
Some(g) => return Err(bad(C, format!("glyph {g} is not an alternate of {ch} in {} {}", face.family, face.style))),
};
let drawn = choice.as_ref().map_or(unchosen.unwrap_or(default), |c| c.gid);
// The run holding the character. The request changes nothing when the choice is the one the
// character's run holds and that run holds the character alone; otherwise the edit splits the
// run, so that the following text does not take the character into a ligature.
let held = holder.as_ref().filter(|(bytes_of_run, _)| bytes_of_run.start == bytes.start).and_then(|(_, r)| r.style.glyph_alternate.clone());
let alone = holder.as_ref().is_some_and(|(bytes_of_run, _)| *bytes_of_run == bytes);
// A choice that the character's style keeps from being drawn (All Caps, Small Caps, another
// numeral system) is an error, not an edit that leaves the page as it was. The style decides
// for a character outside its frame too; one that is laid out is checked in the layout.
if let Some(c) = &choice {
let shown = || {
let mut probe = t.clone();
edit::style_range(&mut probe.runs, bytes.start, bytes.end, |st| st.glyph_alternate = Some(c.clone()));
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &probe);
lay.glyphs.iter().find(|g| g.byte <= bytes.start && bytes.start < g.byte.saturating_add(g.len)).map(|g| g.gid)
};
if styled || shown().is_some_and(|g| g != c.gid) {
return Err(bad(
C,
format!("glyph {} is not drawn for {ch} with the character's style (such as All Caps, Small Caps or a numeral system)", c.gid),
));
}
}
if held == choice && (choice.is_none() || alone) {
return Ok(json!({"id": id.0, "start": bytes.start, "end": bytes.end, "gid": drawn}));
}
s.edit("Glyphs", |d, _| {
let t = text_mut(d, id).ok_or(EngineError::NoNode(id))?;
edit::style_range(&mut t.runs, bytes.start, bytes.end, |st| st.glyph_alternate = choice.clone());
refresh_bounds(t);
Ok(())
})?;
Ok(json!({"id": id.0, "start": bytes.start, "end": bytes.end, "gid": drawn}))
}
fn glyph_alternates(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "text.glyphAlternates";
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?;
let t = text_ref(s, id)?;
let (ch, bytes, face) = glyph_target(&t, p, C)?;
let default = face.glyph_for(ch);
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t);
let chosen = lay.glyphs.iter().find(|g| g.byte <= bytes.start && bytes.start < g.byte.saturating_add(g.len)).map_or(default, |g| g.gid);
let alternates: Vec<Value> = face.alternates(ch).iter().map(|a| json!({"gid": a.gid, "feature": String::from_utf8_lossy(&a.feature)})).collect();
Ok(json!({"char": ch.to_string(), "font": face.family, "style": face.style, "default": default, "chosen": chosen, "alternates": alternates}))
}
fn touch_type(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "text.touchType";
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?;
@@ -1234,6 +1491,7 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result<Value> {
super::paint::check_keep_model(p, C)?;
check_numbers(p, &["size"], C)?;
check_switches(p, &["vertical", "placeholder"], C)?;
super::color_param(p, "color", C)?;
let style = super::create::new_type_style(s, p);
let text = str_param(p, "text").unwrap_or("").to_string();
let start = match point_param(p, "at") {
@@ -1310,8 +1568,20 @@ pub(crate) fn editing_range(s: &mut Session) -> Result<Option<(NodeId, usize, us
Ok(Some((id, at("start"), at("end"))))
}
/// The frames of the story whose whole text the Type tool has selected after Select All in a
/// frame of threaded text, in thread order; empty when its selection is in one type object.
pub(crate) fn editing_story(s: &Session) -> Vec<NodeId> {
let o = s.tool_options();
let Some(id) = o.get("editing").and_then(Value::as_u64).map(NodeId) else { return vec![] };
if !o.get("story").and_then(Value::as_array).is_some_and(|ids| !ids.is_empty()) {
return vec![];
}
s.active().map(|st| super::threads::story_of(&st.doc, id)).unwrap_or_default()
}
/// The text ranges a type shortcut changes: the range of `id`, else all the text of the type
/// objects in `ids`, else the text the Type tool has selected, else all the text of every selected
/// objects in `ids`, else the text the Type tool has selected (all the text of every frame of the
/// story after Select All in threaded text, [`editing_story`]), else all the text of every selected
/// type object. At a caret, `at_caret` gives the range from the plain text and the caret's byte
/// (None: nothing changes there). Each range comes with whether it came from a caret.
pub(crate) fn type_ranges(
@@ -1329,7 +1599,10 @@ pub(crate) fn type_ranges(
Some(id) => vec![(id, Some(range_of(p, edit::runs_len(&text_ref(s, id)?.runs), c)?))],
None => {
let editing = editing_range(s)?.filter(|_| p.get("ids").filter(|v| !v.is_null()).is_none());
let story = if editing.is_some() { editing_story(s) } else { vec![] };
match editing {
// Select All in threaded text: every frame's text.
Some(_) if !story.is_empty() => story.into_iter().map(|id| (id, None)).collect(),
Some((id, a, b)) => vec![(id, Some((a.min(b), a.max(b))))],
None => super::typecmd::text_targets(s, p, c)?.into_iter().map(|id| (id, None)).collect(),
}
+36 -11
View File
@@ -51,14 +51,14 @@ const fn spec(id: &'static str, label: &'static str, menu: &'static [&'static st
}
macro_rules! style_cmds {
($kind:expr, $p:literal, $menu:literal, $what:literal) => {
($kind:expr, $p:literal, $menu:literal, $what:literal, $bounds:literal) => {
vec![
spec(concat!($p, ".list"), concat!($what, " Styles"), &[], "{} → {styles: [{name, attrs, uses}]}", |s, _| list(s, $kind), false),
spec(
concat!($p, ".new"),
concat!("New ", $what, " Style"),
&["Window", "Type", $menu],
"{name? (trimmed, as rename trims `to`), attrs?: {…} (default: selected text), id?, start?: byte, end?: byte} → {name}; a nonempty character range samples its first selected character; start alone keeps insertion affinity; paragraph styles sample start",
concat!("{name? (trimmed, as rename trims `to`), attrs?: {…} (default: selected text), id?, start?: byte, end?: byte} → {name}; a nonempty character range samples its first selected character; start alone keeps insertion affinity; paragraph styles sample start", $bounds),
|s, p| new(s, p, $kind),
true,
),
@@ -82,7 +82,7 @@ macro_rules! style_cmds {
concat!($p, ".setAttrs"),
concat!($what, " Style Options"),
&[],
"{name, attrs: {…}} replace the style's attributes; users keep their overrides",
concat!("{name, attrs: {…}} replace the style's attributes; users keep their overrides", $bounds),
|s, p| set_attrs(s, p, $kind),
true,
),
@@ -116,16 +116,22 @@ macro_rules! style_cmds {
}
pub fn specs() -> Vec<CommandSpec> {
let mut v = style_cmds!(Kind::Char, "charStyle", "Character Styles", "Character");
let mut v = style_cmds!(
Kind::Char,
"charStyle",
"Character Styles",
"Character",
"; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt"
);
v.push(spec(
"charStyle.edit",
"Edit Character Style",
&[],
"{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides",
"{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt",
|s, p| edit_style(s, p, Kind::Char),
true,
));
v.extend(style_cmds!(Kind::Para, "paraStyle", "Paragraph Styles", "Paragraph"));
v.extend(style_cmds!(Kind::Para, "paraStyle", "Paragraph Styles", "Paragraph", ""));
v
}
@@ -155,6 +161,8 @@ fn to_attrs<T: Serialize>(v: &T) -> Map<String, Value> {
/// from a style instead leaves the text's own value alone.
pub fn char_attrs(v: &CharStyle) -> Map<String, Value> {
let mut m = to_attrs(v);
// A chosen glyph belongs to one character, not to a reusable character style.
m.remove("glyphAlternate");
for (k, x) in [
("font_version", json!(v.font_version)),
("fontAxes", json!(v.font_axes)),
@@ -270,11 +278,9 @@ fn restyle<T: Serialize + DeserializeOwned + Clone>(
new: &Map<String, Value>,
base: &Map<String, Value>,
) -> T {
let Some(full) = to_map(cur) else { return cur.clone() };
let mut m = attrs(cur);
if let Some(name) = full.get("style_name") {
m.insert("style_name".into(), name.clone());
}
// Starts from every key `cur` writes, so values no style sets (a glyph choice) are kept.
let Some(mut m) = to_map(cur) else { return cur.clone() };
m.extend(attrs(cur));
for (k, v) in new {
if old.get(k).is_none_or(|o| m.get(k) == Some(o)) {
m.insert(k.clone(), v.clone());
@@ -492,8 +498,27 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma
let c = kind.cmd(verb);
let full = match kind {
Kind::Char => {
if m.contains_key("glyphAlternate") {
return Err(bad(&c, "`glyphAlternate` belongs to one character, not to a character style (text.setGlyphAlternate sets it)"));
}
let mut st = with_attrs(&CharStyle::default(), m, &c)?;
let changed = |key: &str| m.contains_key(key) && kept.and_then(|k| k.get(key)) != m.get(key);
for (key, value, lo, hi) in
[("size", st.size, 0.1, 1296.0), ("h_scale", st.h_scale, 1.0, 10000.0), ("v_scale", st.v_scale, 1.0, 10000.0)]
{
if changed(key) && !(lo..=hi).contains(&value) {
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
}
}
if changed("leading") && st.leading.is_some_and(|value| !(0.1..=5000.0).contains(&value)) {
return Err(bad(&c, "`leading` must be from 0.1 to 5000, or null for Auto"));
}
let shift_max = 1296.0;
for (key, value) in [("baseline_shift", st.baseline_shift), ("tcyUpDown", st.tcy_up_down), ("tcyLeftRight", st.tcy_left_right)] {
if changed(key) && !(-shift_max..=shift_max).contains(&value) {
return Err(bad(&c, format!("`{key}` must be from {} to {shift_max}", -shift_max)));
}
}
// A language of the list, stored as its tag (as text.setFormat takes it).
if let Some(l) = &st.language
&& kept.and_then(|k| k.get("language")) != m.get("language")
+106 -3
View File
@@ -1,5 +1,42 @@
use super::*;
#[test]
fn captured_character_style_excludes_a_one_character_glyph_choice() {
let style = CharStyle {
glyph_alternate: Some(vectorcraft_doc::GlyphChoice { ch: 'a', gid: 42, font: "Test-Regular".into(), version: "1".into() }),
..Default::default()
};
assert!(!char_attrs(&style).contains_key("glyphAlternate"));
assert!(style.glyph_alternate.is_some(), "the selected text keeps its direct glyph choice");
}
#[test]
fn character_style_edit_keeps_a_linked_runs_glyph_choice() {
let (mut s, id) = session_with_text("Styled");
s.execute("charStyle.new", &json!({"name": "Body", "attrs": {"size": 24}})).unwrap();
s.execute("charStyle.apply", &json!({"name": "Body", "id": id})).unwrap();
let choice = vectorcraft_doc::GlyphChoice { ch: 'S', gid: 42, font: "Test-Regular".into(), version: "1".into() };
if let Some(NodeKind::Text(t)) = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(NodeId(id)).map(|n| &mut n.kind) {
t.runs[0].style.glyph_alternate = Some(choice.clone());
}
s.execute("charStyle.edit", &json!({"name": "Body", "to": "Body", "attrs": {"size": 18}})).unwrap();
let run = &runs(&s, id)[0];
assert_eq!((run.style.style_name.as_deref(), run.style.size), (Some("Body"), 18.0));
assert_eq!(run.style.glyph_alternate, Some(choice), "the style edit keeps the run's own glyph choice");
}
/// A glyph choice given to a character style is an error, not a value the style drops.
#[test]
fn character_style_attributes_refuse_a_glyph_choice() {
let (mut s, _) = session_with_text("Styled");
let choice = json!({"ch": "S", "gid": 42, "font": "Test-Regular", "version": "1"});
let err = s.execute("charStyle.new", &json!({"name": "Body", "attrs": {"size": 24, "glyphAlternate": choice}})).unwrap_err();
assert!(err.to_string().contains("glyphAlternate"), "{err}");
s.execute("charStyle.new", &json!({"name": "Body", "attrs": {"size": 24}})).unwrap();
let err = s.execute("charStyle.edit", &json!({"name": "Body", "to": "Body", "attrs": {"glyphAlternate": choice}})).unwrap_err();
assert!(err.to_string().contains("glyphAlternate"), "{err}");
}
fn session_with_text(text: &str) -> (Session, u64) {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
@@ -335,6 +372,69 @@ fn character_style_color_and_features_are_checked() {
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
}
#[test]
fn character_style_dimensions_are_checked_before_a_definition_changes() {
let (mut s, _) = session_with_text("Text");
s.execute("charStyle.new", &json!({"name": "Body", "attrs": {"size": 24.0}})).unwrap();
let before = s.doc().unwrap().doc.clone();
let undo = s.doc().unwrap().history.undo.len();
for attrs in [
json!({"size": 0.0}),
json!({"size": 1296.1}),
json!({"leading": 0.0}),
json!({"leading": 5000.1}),
json!({"h_scale": 0.0}),
json!({"h_scale": 0.9}),
json!({"h_scale": 10000.1}),
json!({"v_scale": 0.0}),
json!({"v_scale": 0.9}),
json!({"v_scale": 10000.1}),
json!({"baseline_shift": -1296.1}),
json!({"baseline_shift": 1296.1}),
json!({"tcyUpDown": 1296.1}),
json!({"tcyLeftRight": -1296.1}),
] {
let key = attrs.as_object().unwrap().keys().next().unwrap();
for cmd in ["charStyle.edit", "charStyle.setAttrs", "charStyle.new"] {
let params = match cmd {
"charStyle.edit" => json!({"name": "Body", "to": "Body", "attrs": attrs}),
"charStyle.new" => json!({"name": "Other", "attrs": attrs}),
_ => json!({"name": "Body", "attrs": attrs}),
};
let error = s.execute(cmd, &params).unwrap_err().to_string();
assert!(error.contains(&format!("`{key}`")), "{cmd} {attrs}: {error}");
}
}
assert_eq!(s.doc().unwrap().doc, before);
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
s.execute(
"charStyle.setAttrs",
&json!({"name": "Body", "attrs": {
"size": 1296.0, "leading": 5000.0,
"h_scale": 1.0, "v_scale": 10000.0,
"baseline_shift": -1296.0,
"tcyUpDown": 1296.0, "tcyLeftRight": -1296.0
}}),
)
.unwrap();
}
#[test]
fn text_style_rejects_doubly_signed_feature_tags() {
let (mut s, id) = session_with_text("Text");
let before = runs(&s, id);
let undo = s.doc().unwrap().history.undo.len();
for cmd in ["text.setStyle", "text.setRangeStyle"] {
for tag in ["--liga", "+-dnom", "-+ss01", "++liga"] {
let error = s.execute(cmd, &json!({"id": id, "start": 0, "end": 4, "features": [tag]})).unwrap_err().to_string();
assert!(error.contains(&format!("`{tag}`")), "{cmd}: {error}");
}
}
assert_eq!(runs(&s, id), before);
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
}
#[test]
fn style_paints_count_as_swatch_uses_and_gradient_stops_are_checked() {
let (mut s, _) = session_with_text("Text");
@@ -761,7 +861,8 @@ fn para_style_redefined_to_the_defaults_updates_its_paragraphs() {
}
/// The same for character styles: Auto kerning and the Roman baseline alignment, which the
/// run's JSON leaves out, are captured and reach the style's users.
/// run's JSON leaves out, are captured and reach the style's users. A glyph choice belongs to
/// one character, so it is not a reusable style attribute.
#[test]
fn char_style_redefined_to_the_defaults_updates_its_text() {
use vectorcraft_doc::CharAlign;
@@ -779,9 +880,11 @@ fn char_style_redefined_to_the_defaults_updates_its_text() {
s.execute("text.setFormat", &json!({"ids": [source], "kerning": "auto", "charAlign": "romanBaseline"})).unwrap();
s.execute("charStyle.redefine", &json!({"name": "Body", "id": source})).unwrap();
assert_eq!((kerning(&s), aligns(&s)), ([None, None, Some(60.0)], [CharAlign::RomanBaseline; 3]));
assert_eq!(defined(&s, 0), settable::<CharStyle>(), "Redefine captures every attribute");
let mut reusable = settable::<CharStyle>();
reusable.remove("glyphAlternate");
assert_eq!(defined(&s, 0), reusable, "Redefine captures every reusable attribute");
s.execute("charStyle.new", &json!({"name": "Copy", "id": local})).unwrap();
assert_eq!(defined(&s, 1), settable::<CharStyle>(), "New captures every attribute");
assert_eq!(defined(&s, 1), reusable, "New captures every reusable attribute");
s.execute("charStyle.setAttrs", &json!({"name": "Body", "attrs": {"kerning": 10, "charAlign": "emBoxTop"}})).unwrap();
assert_eq!((kerning(&s), aligns(&s)), ([Some(10.0), Some(10.0), Some(60.0)], [CharAlign::EmBoxTop; 3]));
s.execute("charStyle.setAttrs", &json!({"name": "Body", "attrs": {"charAlign": "romanBaseline"}})).unwrap();
+8
View File
@@ -276,6 +276,14 @@ pub(crate) fn mark_continued(doc: &mut Document) {
}
}
/// The frames of the thread that `id` is a frame of, in thread order, each area type or type on a
/// path; empty when `id` is in no thread or the thread has fewer than two such frames.
pub(crate) fn story_of(d: &Document, id: NodeId) -> Vec<NodeId> {
let Some(thread) = d.text_threads.iter().find(|t| t.contains(&id)) else { return vec![] };
let frames: Vec<NodeId> = thread.iter().copied().filter(|f| text_of(d, *f).is_some()).collect();
if frames.len() >= 2 && frames.contains(&id) { frames } else { vec![] }
}
/// `ids` followed by the other frames of the threads they are in, each once, in thread order.
pub(crate) fn with_threads(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
let mut out = ids.to_vec();
+68 -40
View File
@@ -87,7 +87,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Area Type Options…",
["Type"],
None,
"{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt (between rows and columns), rowGutter?: pt|null (between rows when it differs from gutter, which is then between columns; gutter given alone sets both; the reply gives the rows' gutter either way), inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|fixed, firstBaselineMin?: pt, verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText, fitMinPercent?: 10..100, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options; width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit (none given: query) → the first object's options, plus overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)",
"{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt (between rows and columns), rowGutter?: pt|null (between rows when it differs from gutter, which is then between columns; gutter given alone sets both; the reply gives the rows' gutter either way), inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|fixed, firstBaselineMin?: pt, verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText, fitMinPercent?: 10..100, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options (each frame takes the options given over its own and keeps the rest; fit resolves against each frame's own; options that change nothing add no undo step); width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit (none given: query) → the first object's options, plus overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)",
has_selection,
area_options
),
@@ -123,7 +123,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Character",
[],
None,
"{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt, leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour|\"none\", stroke?: colour|\"none\" (characters without a stroke weight get 1 pt), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt (the character stroke's weight, in document points as stroke.set), features?: [\"dlig\", \"-liga\", …] OpenType, featureChanges?: [\"tnum\", \"-onum\", …] (OpenType features turned on, or with - off, on top of each character's own; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}",
"{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt, leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour|\"none\", stroke?: colour|\"none\" (characters without a stroke weight get 1 pt; #rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt (the character stroke's weight, in document points as stroke.set), features?: [\"dlig\", \"-liga\", …] OpenType, featureChanges?: [\"tnum\", \"-onum\", …] (OpenType features turned on, or with - off, on top of each character's own; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}",
has_doc,
set_style
),
@@ -874,16 +874,16 @@ fn set_style(s: &mut Session, p: &Value) -> Result<Value> {
st.features = super::textedit::change_features(&st.features, c);
}
});
if let Some(before) = before {
super::textedit::protect_missing_glyphs(&before, &mut t.runs);
}
let kept = before.map(|before| super::textedit::protect_missing_glyphs(&before, &mut t.runs)).unwrap_or_default();
if font.is_some() || style.is_some() {
// All the text: every run, the one run of empty text included.
// All the text: every run, the one run of empty text included. Characters that kept their font aren't the
// command's.
let styled = match range {
None => t.runs.clone(),
None if kept.is_empty() => t.runs.clone(),
None => super::textedit::unprotected_runs(&t.runs, 0, vectorcraft_text::edit::runs_len(&t.runs), &kept),
Some(r) => {
let (a, b) = r.bytes(t);
vectorcraft_text::edit::slice_runs(&t.runs, a, b)
super::textedit::unprotected_runs(&t.runs, a, b, &kept)
}
};
set.extend(styled.iter().map(|r| super::fonts::font_of(&r.style)));
@@ -1080,46 +1080,74 @@ fn area_options(s: &mut Session, p: &Value) -> Result<Value> {
let t = area_text(s.doc()?.doc.node(first)).ok_or_else(|| bad(C, "select area type (text in a frame)"))?;
area_options_json(t)
};
// Checked once up front (its errors don't depend on the frame); each frame resolves `fit`
// against its own setting below.
let cur = area_text(s.doc()?.doc.node(first)).map(|t| t.area.clone()).unwrap_or_default();
let fit = fit_param(p, cur.fit, C)?;
let mut v = serde_json::to_value(&cur).map_err(|e| EngineError::Other(e.to_string()))?;
fit_param(p, cur.fit, C)?;
let fit_given = p.get("fit").is_some_and(|v| !v.is_null()) || p.get("fitMinPercent").is_some_and(|v| !v.is_null());
let size = |k: &str| p.get(k).and_then(Value::as_f64).filter(|x| x.is_finite()).map(|x| x.clamp(1.0, 100_000.0));
let (w, mut h) = (size("width"), size("height"));
let mut changed = w.is_some() || h.is_some() || fit.is_some();
if let (Some(o), Some(src)) = (v.as_object_mut(), p.as_object()) {
for (k, val) in src.iter().filter(|(k, _)| AREA_KEYS.contains(&k.as_str())) {
o.insert(k.clone(), val.clone());
changed = true;
}
}
if !changed {
let (w, h) = (size("width"), size("height"));
let given: Vec<(&String, &Value)> = p.as_object().into_iter().flatten().filter(|(k, _)| AREA_KEYS.contains(&k.as_str())).collect();
if w.is_none() && h.is_none() && !fit_given && given.is_empty() {
return options(s);
}
let mut opts: vectorcraft_doc::AreaOptions = serde_json::from_value(v).map_err(|e| bad(C, e.to_string()))?;
opts.rows = opts.rows.clamp(1, vectorcraft_doc::AreaOptions::MAX_ROWS_COLUMNS);
opts.columns = opts.columns.clamp(1, vectorcraft_doc::AreaOptions::MAX_ROWS_COLUMNS);
let finite = |x: f64| if x.is_finite() { x } else { 0.0 };
opts.gutter = finite(opts.gutter).clamp(0.0, 10_000.0);
// A gutter given alone is the rows' and the columns'.
if p.get("gutter").is_some() && p.get("rowGutter").is_none() {
opts.row_gutter = None;
}
opts.row_gutter = opts.row_gutter.map(|g| finite(g).clamp(0.0, 10_000.0)).filter(|g| *g != opts.gutter);
opts.inset = finite(opts.inset).clamp(0.0, 10_000.0);
opts.first_baseline_min = finite(opts.first_baseline_min).clamp(0.0, 10_000.0);
opts.fit = fit.unwrap_or(cur.fit);
if opts.fit == AreaFit::AutoHeight {
// Each area type takes the options given over its own (#3759): setting one option on several
// frames leaves their other options as they were.
let merged = |own: &vectorcraft_doc::AreaOptions| -> Result<vectorcraft_doc::AreaOptions> {
let mut v = serde_json::to_value(own).map_err(|e| EngineError::Other(e.to_string()))?;
if let Some(o) = v.as_object_mut() {
for (k, val) in &given {
o.insert((*k).clone(), (*val).clone());
}
}
let mut opts: vectorcraft_doc::AreaOptions = serde_json::from_value(v).map_err(|e| bad(C, e.to_string()))?;
opts.rows = opts.rows.clamp(1, vectorcraft_doc::AreaOptions::MAX_ROWS_COLUMNS);
opts.columns = opts.columns.clamp(1, vectorcraft_doc::AreaOptions::MAX_ROWS_COLUMNS);
let finite = |x: f64| if x.is_finite() { x } else { 0.0 };
opts.gutter = finite(opts.gutter).clamp(0.0, 10_000.0);
// A gutter given alone is the rows' and the columns'.
if p.get("gutter").is_some() && p.get("rowGutter").is_none() {
opts.row_gutter = None;
}
opts.row_gutter = opts.row_gutter.map(|g| finite(g).clamp(0.0, 10_000.0)).filter(|g| *g != opts.gutter);
opts.inset = finite(opts.inset).clamp(0.0, 10_000.0);
opts.first_baseline_min = finite(opts.first_baseline_min).clamp(0.0, 10_000.0);
// Each frame's fit from its own (`fitMinPercent` alone changes only Shrink Text frames).
opts.fit = fit_param(p, own.fit, C)?.unwrap_or(own.fit);
Ok(opts)
};
let d = &s.doc()?.doc;
let planned: Vec<(NodeId, vectorcraft_doc::AreaOptions)> = ids
.iter()
.filter_map(|id| area_text(d.node(*id)).map(|t| (*id, &t.area)))
.map(|(id, own)| merged(own).map(|o| (id, o)))
.collect::<Result<_>>()?;
let apply = |t: &mut TextObject, opts: &vectorcraft_doc::AreaOptions| {
t.area = opts.clone();
// Auto Size sets the height (Illustrator's dialog turns the Height field off).
h = None;
let h = if opts.fit == AreaFit::AutoHeight { None } else { h };
// A resized frame has laid its text out again; otherwise the new options do here.
if !size_area(t, w, h) {
refresh_bounds(t);
}
};
// Options that change nothing (the vertical alignment already set, `fitMinPercent` on frames
// without Shrink Text) add no undo step and keep redo, frame sizes and Auto Size included.
let unchanged = planned.iter().all(|(id, opts)| match d.node(*id).map(|n| &n.kind) {
Some(NodeKind::Text(t)) => {
let mut after = t.clone();
apply(&mut after, opts);
after == *t
}
_ => true,
});
if unchanged {
return options(s);
}
s.edit("Area Type Options", |d, _| {
for id in &ids {
for (id, opts) in &planned {
if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) {
t.area = opts.clone();
// A resized frame has laid its text out again; otherwise the new options do here.
if !size_area(t, w, h) {
refresh_bounds(t);
}
apply(t, opts);
}
}
Ok(())
@@ -1762,3 +1762,46 @@ fn area_options_set_a_gutter_between_rows_of_its_own() {
s.execute("text.areaOptions", &json!({"rowGutter": null})).unwrap();
assert_eq!(area(&s).row_gutter, None);
}
/// #3759: an option given for several area types goes onto each one's own options: the others
/// stay as each had them, not copied from the first.
#[test]
fn area_options_for_several_frames_change_only_what_is_given() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let make = |s: &mut Session, x: f64| {
s.execute("text.create", &json!({"x": x, "y": 10, "text": "A", "area": {"width": 100, "height": 100}})).unwrap()["id"].as_u64().unwrap()
};
let (a, b) = (make(&mut s, 10.0), make(&mut s, 200.0));
s.execute("text.areaOptions", &json!({"ids": [a], "columns": 3, "gutter": 6})).unwrap();
s.execute("text.areaOptions", &json!({"ids": [b], "inset": 4})).unwrap();
s.execute("text.areaOptions", &json!({"ids": [a, b], "verticalAlign": "bottom"})).unwrap();
let area = |s: &Session, id: u64| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
NodeKind::Text(t) => t.area.clone(),
k => panic!("{k:?}"),
};
let (oa, ob) = (area(&s, a), area(&s, b));
assert_eq!((oa.vertical_align, ob.vertical_align), (vectorcraft_doc::VerticalAlign::Bottom, vectorcraft_doc::VerticalAlign::Bottom));
assert_eq!((oa.columns, oa.gutter, oa.inset), (3, 6.0, 0.0));
assert_eq!((ob.columns, ob.inset), (1, 4.0), "b keeps its own options");
}
/// `fitMinPercent` alone changes only the frames that shrink text to fit, each from its own
/// setting (#3759).
#[test]
fn fit_min_percent_for_several_frames_keeps_each_frames_fit() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let make = |s: &mut Session, x: f64| {
s.execute("text.create", &json!({"x": x, "y": 10, "text": "A", "area": {"width": 100, "height": 100}})).unwrap()["id"].as_u64().unwrap()
};
let (plain, shrink) = (make(&mut s, 10.0), make(&mut s, 200.0));
s.execute("text.areaOptions", &json!({"ids": [shrink], "fit": "shrinkText"})).unwrap();
s.execute("text.areaOptions", &json!({"ids": [plain, shrink], "fitMinPercent": 30})).unwrap();
let fit = |s: &Session, id: u64| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
NodeKind::Text(t) => t.area.fit,
k => panic!("{k:?}"),
};
assert_eq!(fit(&s, plain), vectorcraft_doc::AreaFit::None, "the plain frame doesn't start shrinking");
assert_eq!(fit(&s, shrink), vectorcraft_doc::AreaFit::ShrinkText { min_percent: 30.0 });
}
+6 -3
View File
@@ -21,7 +21,7 @@ use vectorcraft_render::encode::quantize::{self, Dither, Indexed, PaletteOptions
use vectorcraft_render::encode::web::{self, ColorSort};
use vectorcraft_render::encode::{gif, jpeg, png};
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, f64_or, has_doc, str_param, unique_name};
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, f64_or, has_doc, str_param, unique_name_from};
const C: &str = "document.exportForWeb";
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Save for Web",
[],
None,
"{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity} (colours as the preview's colors[].source), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/<slice name>.<ext>), output?: images (default)|html (an HTML page placing the image or slices, <stem>.html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself",
"{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/<slice name>.<ext>), output?: images (default)|html (an HTML page placing the image or slices, <stem>.html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself",
has_doc,
export
),
@@ -329,6 +329,7 @@ impl ColorTable {
list.iter()
.map(|h| {
vectorcraft_color::Color::from_hex(h)
.filter(|_| !super::hex_with_alpha(h))
.map(|c| {
let [r, g, b, _] = c.to_rgba8(1.0);
[r, g, b]
@@ -866,6 +867,8 @@ pub fn export_files(doc: &Document, selected: &[NodeId], s: &WebSettings, stem:
placed.push((None, Some(name)));
} else {
let mut taken = HashSet::new();
// Per base, where the suffix search resumes, so many slices of one name don't each count up from 2.
let mut next = std::collections::HashMap::new();
for c in &cells {
let kind = c.area.id.and_then(|id| doc.slice_options(id)).map(|o| o.kind).unwrap_or_default();
if kind != SliceKind::Image {
@@ -875,7 +878,7 @@ pub fn export_files(doc: &Document, selected: &[NodeId], s: &WebSettings, stem:
let base: String = doc.slice_name(c.area).chars().map(|ch| if ch.is_alphanumeric() || "-_.".contains(ch) { ch } else { '-' }).collect();
// A slice named after a Windows device (`aux`, `NUL`…) gets a `-` after the device name.
let file = |base: &str| super::fileio::safe_file_name(&format!("{base}.{ext}"));
let base = unique_name(&base, |n| taken.contains(&file(n).to_lowercase()));
let base = unique_name_from(&base, &mut next, |n| taken.contains(&file(n).to_lowercase()));
taken.insert(file(&base).to_lowercase());
let name = format!("{IMAGES}/{}", file(&base));
let [x0, y0, x1, y1] = c.px;
+1 -1
View File
@@ -30,7 +30,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Sample Color",
[],
None,
"{color, stroke?: bool (default: whichever proxy is active), ids?, stop?: index, clearStroke?: bool} sample a color into the active fill/stroke (and the selection; `ids: []` changes only the paint default); `clearStroke: true` requires `stroke: false`, `ids: []` and no `stop`, and clears the default stroke after sampling an image into the fill; with `stop`, recolor that stop of the gradient behind the proxy instead (paint.editGradient); in a CMYK document an RGB color is stored as CMYK through the color settings, as paint.setFill stores it",
"{color (#rrggbbaa and #rgba are refused), stroke?: bool (default: whichever proxy is active), ids?, stop?: index, clearStroke?: bool} sample a color into the active fill/stroke (and the selection; `ids: []` changes only the paint default); `clearStroke: true` requires `stroke: false`, `ids: []` and no `stop`, and clears the default stroke after sampling an image into the fill; with `stop`, recolor that stop of the gradient behind the proxy instead (paint.editGradient); in a CMYK document an RGB color is stored as CMYK through the color settings, as paint.setFill stores it",
has_doc,
sample_color
),