M2: reconcile fill-only Eraser fix with main (#6582)

This commit is contained in:
yoriswind committed 2026-11-15 11:46:32 -08:00
commit 63dc751bca
266 files changed
+17716 -1000

No files matched your search

+77 -17
View File
@@ -9,8 +9,9 @@
//! text. Each action is an `/action-N` block with a hexadecimal `/name`; each step is an `/event-N`
//! block inside one, with its `/internalName` in parentheses, the `/localizedName` it is shown with
//! as hexadecimal text, and `/isOn` 0 when it is left out of playback; each value a step was
//! recorded with is a `/parameter-N` block inside it, which is counted, and whose hexadecimal
//! `/value` is checked against its byte count. The set's `/actionCount`, an action's `/eventCount`
//! recorded with is a `/parameter-N` block inside it, which is counted, whose `/key` (a number),
//! `/type` (text in parentheses) and `/value` (a number, text in parentheses or hexadecimal text) are
//! kept, and whose hexadecimal `/value` is checked against its byte count. The set's `/actionCount`, an action's `/eventCount`
//! and a step's `/parameterCount` give how many actions, steps and recorded values follow.
//! The layout follows the README of Inventsable's Redesigning-Illustrator-Actions-in-Scripting
//! (https://github.com/Inventsable/Redesigning-Illustrator-Actions-in-Scripting), the forum post
@@ -40,6 +41,8 @@ const MAX_STEPS: usize = 10_000;
/// The most steps read in the set: a small text can hold hundreds of thousands of empty steps, and
/// the answer holds an object for each.
const MAX_SET_STEPS: usize = 100_000;
/// The most recorded values kept in the set; the others are counted but not kept.
const MAX_VALUES: usize = 100_000;
/// The longest name kept (bytes).
const MAX_NAME: usize = 1024;
/// The most tokens listed as unread.
@@ -56,7 +59,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Read Action Set File",
[],
None,
"{path? | data?: the file's text | dataBase64?, name?: the file's name (default: the path's)} read an action set another app saved as text (.aia, starting \"/version\") without changing anything → {set: the set's /name (else the file's name without its extension, else empty), version, actions: [{name, steps: [{name: the step's /internalName, label: its /localizedName, or null when it has none or it is blank, on: false when /isOn is 0, params: how many /parameter blocks it has, line}]}], unread: [{line, text}] (tokens that aren't read, at most 1000), truncated: true when a cap stopped the reading (8 MiB, 16 open blocks, 1,000 actions, 10,000 steps in an action, 100,000 steps in the set; names past 1,024 bytes are cut), when the text ends inside a block or a value or after a field's name, when /actionCount, /eventCount or a step's /parameterCount differs from the actions, steps or recorded values read (a negative count, one too large for a number and one that isn't a number always differ), or when a hexadecimal name, label or recorded /value isn't as many bytes as its count says}. Give exactly one of path, data and dataBase64. Text that doesn't start with /version and a number is an error",
"{path? | data?: the file's text | dataBase64?, name?: the file's name (default: the path's)} read an action set another app saved as text (.aia, starting \"/version\") without changing anything → {set: the set's /name (else the file's name without its extension, else empty), version, actions: [{name, steps: [{name: the step's /internalName, label: its /localizedName, or null when it has none or it is blank, on: false when /isOn is 0, params: how many /parameter blocks it has, values: [{key: the block's /key, or null, type: its /type, or null, value: its /value when it is a number, or text that is UTF-8 (else null), bytes?: the text's length in bytes}] (the first 100,000 recorded values in the set), line}]}], unread: [{line, text}] (tokens that aren't read, at most 1000), truncated: true when a cap stopped the reading (8 MiB, 16 open blocks, 1,000 actions, 10,000 steps in an action, 100,000 steps in the set; names past 1,024 bytes are cut), when the text ends inside a block or a value or after a field's name, when /actionCount, /eventCount or a step's /parameterCount differs from the actions, steps or recorded values read (a negative count, one too large for a number and one that isn't a number always differ), or when a hexadecimal name, label or recorded /value isn't as many bytes as its count says}. Give exactly one of path, data and dataBase64. Text that doesn't start with /version and a number is an error",
always,
read
)]
@@ -73,12 +76,33 @@ pub struct AiaStep {
pub on: Option<i64>,
/// How many `/parameter-N` blocks it has.
pub params: usize,
/// Its `/parameter-N` blocks, in order, while the set keeps at most [`MAX_VALUES`].
pub values: Vec<AiaValue>,
/// Its `/parameterCount`, if it has one.
pub declared: Option<i64>,
/// The line its block opens on (from 1).
pub line: usize,
}
/// A value a step was recorded with: a `/parameter-N` block.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct AiaValue {
/// Its `/key`, if it has one that fits an `i64`.
pub key: Option<i64>,
/// Its `/type`, read as UTF-8 with replacement characters, if it has one.
pub kind: Option<String>,
/// Its `/value`, if it is a number that fits an `i64` or text.
pub value: Option<AiaData>,
}
/// A recorded `/value` that is kept.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum AiaData {
Int(i64),
/// The bytes of text in parentheses or of hexadecimal text.
Text(Vec<u8>),
}
/// An action: an `/action-N` block.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct AiaAction {
@@ -106,6 +130,8 @@ pub struct AiaSet {
pub truncated: bool,
/// How many steps were read in all the actions.
steps: usize,
/// How many recorded values were kept in all the steps.
values: usize,
}
/// A token of the text.
@@ -252,7 +278,8 @@ fn hex_bytes(digits: &[u8]) -> Option<Vec<u8>> {
enum Kind {
Action,
Step,
Param,
/// A recorded value, and whether it is kept.
Param(bool),
/// A block that isn't read, or one past a cap.
Other,
}
@@ -315,12 +342,18 @@ fn open_block(set: &mut AiaSet, stack: &[Kind], name: &[u8], line: usize) -> Kin
}
},
Some(Kind::Step) if numbered(name, b"parameter-") => {
let mut kept = false;
if let Some(s) = set.actions.last_mut().and_then(|a| a.steps.last_mut()) {
s.params += 1;
if set.values < MAX_VALUES {
s.values.push(AiaValue::default());
set.values += 1;
kept = true;
}
}
Kind::Param
Kind::Param(kept)
}
Some(Kind::Param | Kind::Other) => Kind::Other,
Some(Kind::Param(_) | Kind::Other) => Kind::Other,
_ => {
unread(set, line, format!("/{} {{", String::from_utf8_lossy(name)));
Kind::Other
@@ -355,12 +388,23 @@ fn set_hex(set: &mut AiaSet, kind: Option<&Kind>, name: Option<&[u8]>, bytes: Op
}
}
/// Mark `set` truncated when the hexadecimal `/value` on `line` isn't as many bytes as its count
/// says.
fn check_value(set: &mut AiaSet, bytes: Option<Vec<u8>>, line: usize) {
if bytes.is_none() {
/// Set the field `name` of the recorded value open on `line` to `token`: its `/key`, `/type` or
/// `/value`, when the value is `kept`. A hexadecimal `/value` that isn't as many bytes as its count
/// says marks `set` truncated, kept or not.
fn set_param(set: &mut AiaSet, kept: bool, name: Option<&[u8]>, token: Token, line: usize) {
if name == Some(b"value".as_slice()) && matches!(token, Token::Hex(None)) {
set.truncated = true;
unread(set, line, BAD_HEX);
return;
}
let value = set.actions.last_mut().and_then(|a| a.steps.last_mut()).and_then(|s| s.values.last_mut());
let Some(v) = value.filter(|_| kept) else { return };
match (name, token) {
(Some(b"key"), Token::Int(key)) => v.key = key,
(Some(b"type"), Token::Text(t)) => v.kind = Some(String::from_utf8_lossy(&t).into_owned()),
(Some(b"value"), Token::Int(Some(n))) => v.value = Some(AiaData::Int(n)),
(Some(b"value"), Token::Text(t) | Token::Hex(Some(t))) => v.value = Some(AiaData::Text(t)),
_ => {}
}
}
@@ -448,13 +492,13 @@ pub fn read_aia(bytes: &[u8]) -> std::result::Result<AiaSet, String> {
unread(&mut set, line, "}");
}
}
Token::Hex(bytes) if matches!(stack.last(), Some(Kind::Param)) => {
if field(&mut pending).as_deref() == Some(b"value".as_slice()) {
check_value(&mut set, bytes, line);
}
_ if matches!(stack.last(), Some(Kind::Param(_))) => {
let kept = matches!(stack.last(), Some(Kind::Param(true)));
let name = field(&mut pending);
set_param(&mut set, kept, name.as_deref(), token, line);
}
// The other values inside a recorded value, or a block that isn't read.
_ if matches!(stack.last(), Some(Kind::Param | Kind::Other)) => {
// The values inside a block that isn't read.
_ if matches!(stack.last(), Some(Kind::Other)) => {
pending = None;
}
Token::Hex(bytes) => {
@@ -521,6 +565,21 @@ pub fn read_aia(bytes: &[u8]) -> std::result::Result<AiaSet, String> {
Ok(set)
}
/// A recorded value in `actionSet.read`'s answer: `{key, type, value, bytes?}`, the value a number,
/// text that is UTF-8 (else null) with its length in bytes, or null.
fn value_json(v: &AiaValue) -> Value {
let mut out = json!({ "key": v.key, "type": v.kind, "value": null });
match &v.value {
Some(AiaData::Int(n)) => out["value"] = json!(n),
Some(AiaData::Text(t)) => {
out["value"] = json!(std::str::from_utf8(t).ok());
out["bytes"] = json!(t.len());
}
None => {}
}
out
}
fn read(_: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "actionSet.read";
let (path, data, b64) = (text_param(p, "path", C)?, text_param(p, "data", C)?, text_param(p, "dataBase64", C)?);
@@ -544,7 +603,8 @@ fn read(_: &mut Session, p: &Value) -> Result<Value> {
.iter()
.map(|s| {
let label = s.label.clone().filter(|l| !l.trim().is_empty());
json!({ "name": s.name, "label": label, "on": s.on != Some(0), "params": s.params, "line": s.line })
let values: Vec<Value> = s.values.iter().map(value_json).collect();
json!({ "name": s.name, "label": label, "on": s.on != Some(0), "params": s.params, "values": values, "line": s.line })
})
.collect();
json!({ "name": a.name, "steps": steps })
+3
View File
@@ -8,6 +8,7 @@ mod contour;
mod cutting;
mod document;
mod image;
mod packaging;
mod pathtools;
mod pen;
mod select;
@@ -15,6 +16,7 @@ mod shapes;
mod typetools;
pub(crate) use image::{DecodedImages, refresh_color_masks};
pub(crate) use packaging::{role_swatch_edited, role_swatches_merged};
use super::CommandSpec;
@@ -27,6 +29,7 @@ pub fn specs() -> Vec<CommandSpec> {
v.extend(cutting::specs());
v.extend(document::specs());
v.extend(image::specs());
v.extend(packaging::specs());
v.extend(pathtools::specs());
v.extend(pen::specs());
v.extend(select::specs());
+18
View File
@@ -0,0 +1,18 @@
//! Packaging Tools (`addon.packaging.*`), a built-in add-on for the dielines of boxes and other
//! folded packaging. A path is a fold line when its top stroke is painted with the swatch of a line
//! role: Cut, Crease, Partial Cut or Perforation ([`roles`]). The document's role table maps each
//! role to its swatch, so every format that keeps the stroke's swatch keeps the role. Its submenu
//! (Object › Plug-ins › Packaging Tools) and its Fold Lines panel are the UI's.
mod roles;
pub(crate) use roles::{role_swatch_edited, role_swatches_merged};
use super::super::CommandSpec;
pub fn specs() -> Vec<CommandSpec> {
roles::specs()
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,454 @@
//! Fold line roles (`addon.packaging.setRole`, `addon.packaging.roles`,
//! `addon.packaging.setRoleSwatch`). A path, compound path or live shape has a role when its top
//! stroke is painted with the swatch the document's role table gives that role, at any tint. The
//! table lives in [`Document::unknown`] under [`ROLES_KEY`], `{cut, crease, partialCut,
//! perforation}` each naming a swatch; a role it leaves out, or names with something other than a
//! string, takes its default swatch, named after the role.
use serde_json::{Map, Value, json};
use vectorcraft_color::swatch::REGISTRATION;
use vectorcraft_color::{Color, Paint, Swatch};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use super::super::super::overprint::edit_counted;
use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, switch_or, text_param};
use crate::{Result, Session};
/// Document unknown key: the role table, `{role id: swatch name}`.
pub(crate) const ROLES_KEY: &str = "packagingRoles";
const SET_ROLE: &str = "addon.packaging.setRole";
const ROLES: &str = "addon.packaging.roles";
const SET_ROLE_SWATCH: &str = "addon.packaging.setRoleSwatch";
/// What a fold line does when the blank is cut and folded.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Role {
/// Separates the material.
Cut,
/// A fold.
Crease,
/// A fold cut part way through the board.
PartialCut,
/// A fold along a line of cuts.
Perforation,
}
impl Role {
pub(crate) const ALL: [Role; 4] = [Role::Cut, Role::Crease, Role::PartialCut, Role::Perforation];
/// The role's id in params and in the role table.
pub(crate) fn id(self) -> &'static str {
match self {
Role::Cut => "cut",
Role::Crease => "crease",
Role::PartialCut => "partialCut",
Role::Perforation => "perforation",
}
}
/// The role's name, which is also its default swatch's name.
pub(crate) fn name(self) -> &'static str {
match self {
Role::Cut => "Cut",
Role::Crease => "Crease",
Role::PartialCut => "Partial Cut",
Role::Perforation => "Perforation",
}
}
pub(crate) fn from_id(id: &str) -> Option<Role> {
Role::ALL.into_iter().find(|r| r.id() == id)
}
/// The color a missing role swatch is made with (VectorCraft's own values): Cut 100% magenta,
/// Crease 100% cyan, Partial Cut 100% yellow, Perforation 50% magenta and 50% cyan.
fn color(self) -> Color {
match self {
Role::Cut => Color::cmyk(0.0, 1.0, 0.0, 0.0),
Role::Crease => Color::cmyk(1.0, 0.0, 0.0, 0.0),
Role::PartialCut => Color::cmyk(0.0, 0.0, 1.0, 0.0),
Role::Perforation => Color::cmyk(0.5, 0.5, 0.0, 0.0),
}
}
fn index(self) -> usize {
Role::ALL.iter().position(|r| *r == self).unwrap_or(0)
}
}
/// The swatch each role is carried by, in [`Role::ALL`] order.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct RoleTable([String; 4]);
impl RoleTable {
/// The document's role table, with each missing or damaged entry at its default. When a damaged
/// table names one swatch for two roles, the later role takes its default name instead, or
/// "Crease 2" and so on when an earlier role has that.
pub(crate) fn of(d: &Document) -> RoleTable {
let stored = d.unknown.get(ROLES_KEY).and_then(Value::as_object);
let mut names: Vec<String> = Vec::with_capacity(Role::ALL.len());
for r in Role::ALL {
let name = match stored.and_then(|m| m.get(r.id())).and_then(Value::as_str) {
Some(name) if !name.is_empty() && !names.iter().any(|n| n == name) => name.to_string(),
_ => {
let base = r.name();
std::iter::once(base.to_string())
.chain((2..).map(|i| format!("{base} {i}")))
.find(|n| !names.contains(n))
.unwrap_or_else(|| base.to_string())
}
};
names.push(name);
}
RoleTable(Role::ALL.map(|r| names.get(r.index()).cloned().unwrap_or_else(|| r.name().to_string())))
}
/// The swatch of `role`.
pub(crate) fn swatch(&self, role: Role) -> &str {
self.0.get(role.index()).map_or("", String::as_str)
}
/// The role swatch `name` carries.
pub(crate) fn role_of_swatch(&self, name: &str) -> Option<Role> {
Role::ALL.into_iter().find(|r| self.swatch(*r) == name)
}
/// The role of object `n`: the role of the swatch its top stroke is painted with.
pub(crate) fn role_of(&self, n: &Node) -> Option<Role> {
if !can_carry(n) {
return None;
}
match &n.appearance.stroke()?.paint {
Paint::Solid { swatch: Some(name), .. } => self.role_of_swatch(name),
_ => None,
}
}
fn to_value(&self) -> Value {
Value::Object(Role::ALL.into_iter().map(|r| (r.id().to_string(), json!(self.swatch(r)))).collect::<Map<_, _>>())
}
}
/// Swatch `from` of `d` is now named `to`, and `global` says whether it is still a global color.
/// A role it carried keeps it under the new name, as the strokes linked to it do; when it stopped
/// being global, which unlinks those strokes, the role moves to a new name that `setRole` makes a
/// swatch for. Another role that named `to` without such a swatch moves to a new name too, so no
/// two roles share a swatch.
pub(crate) fn role_swatch_edited(d: &mut Document, from: &str, to: &str, global: bool) {
let before = RoleTable::of(d);
let mut table = before.clone();
for r in Role::ALL {
let name = table.swatch(r).to_string();
let moved = if name == from && global {
Some(to.to_string())
} else if name == from || (name == to && from != to) {
Some(free_role_name(d, &table, r))
} else {
None
};
if let (Some(new), Some(slot)) = (moved, table.0.get_mut(r.index())) {
*slot = new;
}
}
if table != before {
d.unknown.insert(ROLES_KEY.to_string(), table.to_value());
}
}
/// Swatches `merged` of `d` were merged into swatch `kept`, and `linked` says whether their strokes
/// now link to it (it is a global color). When `kept` carries no role, it takes the role of the
/// first merged swatch that carried one, so the lines of that role keep it; a merged swatch's other
/// role keeps its name, which the next `setRole` makes a swatch for.
pub(crate) fn role_swatches_merged(d: &mut Document, merged: &[String], kept: &str, linked: bool) {
let mut table = RoleTable::of(d);
if !linked || table.role_of_swatch(kept).is_some() {
return;
}
let Some(role) = merged.iter().find_map(|m| table.role_of_swatch(m)) else { return };
if let Some(slot) = table.0.get_mut(role.index()) {
*slot = kept.to_string();
}
d.unknown.insert(ROLES_KEY.to_string(), table.to_value());
}
/// A name for `role`'s swatch that no swatch, color group or other role of `table` uses: the
/// role's name, else "Cut 2", "Cut 3"… The document holds finitely many names, so the search
/// always ends at a free one.
fn free_role_name(d: &Document, table: &RoleTable, role: Role) -> String {
let free = |n: &str| !d.swatch_name_taken(n) && Role::ALL.into_iter().all(|r| r == role || table.swatch(r) != n);
let base = role.name();
if free(base) {
return base.to_string();
}
(2usize..).map(|i| format!("{base} {i}")).find(|n| free(n)).unwrap_or_else(|| base.to_string())
}
/// Whether `n` can carry a role: a path (a live shape too) that is neither a clipping path nor a
/// guide, or a compound path.
fn can_carry(n: &Node) -> bool {
match &n.kind {
NodeKind::Path { clipping, guide, .. } => !clipping && !guide,
NodeKind::Compound { .. } => true,
_ => false,
}
}
/// The objects under the outermost objects `roots` that can carry a role, through groups and clip
/// groups, each once, and
/// how many of `roots` and their members can't (text, images, symbol instances and other objects).
/// With `editable`, objects that are locked or hidden, are in a locked or hidden group or layer, or
/// are on a locked artboard are left out and counted as skipped.
fn role_targets(d: &Document, roots: &[NodeId], editable: bool) -> (Vec<NodeId>, usize) {
fn walk(n: &Node, out: &mut Vec<NodeId>, skipped: &mut usize) {
match &n.kind {
NodeKind::Group { children, .. } => {
for c in children {
// A group's clipping path draws no stroke: it is skipped.
if matches!(c.kind, NodeKind::Path { clipping: true, .. }) {
*skipped += 1;
} else {
walk(c, out, skipped);
}
}
}
_ if can_carry(n) => out.push(n.id),
_ => *skipped += 1,
}
}
let (mut out, mut skipped) = (vec![], 0);
// A path of a compound path is painted with the compound's appearance: the compound takes the
// role. `roots` come from `checked_ids_or_selection`, which keeps only outermost objects, so a
// group and its member are never both roots.
let mut seen = std::collections::HashSet::new();
let compound_of = |id: NodeId| d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })));
for n in roots.iter().map(|id| compound_of(*id).unwrap_or(*id)).filter(|id| seen.insert(*id)).filter_map(|id| d.node(id)) {
walk(n, &mut out, &mut skipped);
}
if editable {
// Named directly or not, a locked or hidden object, or one in a locked or hidden group or
// layer or on a locked artboard, stays as it is.
let ok = d.editable();
let before = out.len();
out.retain(|id| ok(*id));
skipped += before - out.len();
}
(out, skipped)
}
/// Every object of the document that can carry a role, through layers and groups.
fn document_targets(d: &Document) -> Vec<NodeId> {
fn walk(n: &Node, out: &mut Vec<NodeId>) {
match &n.kind {
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, out)),
_ if can_carry(n) => out.push(n.id),
_ => {}
}
}
let mut out = vec![];
d.layers.iter().for_each(|l| walk(l, &mut out));
out
}
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"addon.packaging.setRole",
"Make Fold Line",
["Object", "Plug-ins", "Packaging Tools"],
None,
"{role: cut|crease|partialCut|perforation|none, ids?: [id…] (default: the selection), overprint?: bool (true)} give each path, compound path and live shape among the objects (through groups and clip groups; objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and counted as skipped, even when named in ids) a fold line role: its top stroke is painted with the role's swatch (addon.packaging.roles) at 100% and shown, a path without a stroke gets a 1 pt stroke, and the stroke overprints, or with overprint: false does not. A missing role swatch is made as a global spot swatch (Cut 100% magenta, Crease 100% cyan, Partial Cut 100% yellow, Perforation 50% magenta and 50% cyan, in the document's color mode; named \"Cut 2\" and so on, in the role table too, when a color group or a swatch that can't carry a role, such as a process color that is not global, has the name). none takes the role away: a role stroke keeps the color it shows, no longer linked to the swatch, and stops overprinting. Text, images, symbol instances and other objects are skipped and counted. One undo step, none when nothing changes → {ids (the objects that can carry a role), changed, skipped}",
has_selection,
set_role
),
cmd!(
query "addon.packaging.roles",
"Fold Lines",
[],
None,
"{ids?: [id…] (default: the selection)} the fold line roles → {roles: [{role: cut|crease|partialCut|perforation, name, swatch (the swatch that carries it), exists (the document has the swatch), count}], scope: ids|selection|document, selected (objects given or selected)}; count is how many of the paths, compound paths and live shapes among the objects (through groups, locked and hidden members included, each object once) have the role, or among every object of the document while nothing is selected and ids is left out",
has_doc,
roles
),
cmd!(
"addon.packaging.setRoleSwatch",
"Role Swatches…",
["Object", "Plug-ins", "Packaging Tools"],
None,
"{role: cut|crease|partialCut|perforation, swatch: a global or spot color swatch's name} make the swatch carry the role, in the document's role table, as one undo step (none when it already does). Objects stroked with the role's old swatch keep their color and no longer have the role. Refused: a missing swatch, a gradient or pattern swatch, a process color that is not global, a tint swatch, [None], [Registration], and a swatch another role has → {role, swatch, changed}",
has_doc,
set_role_swatch
),
]
}
/// The role `p` gives: `Some(None)` for `none` when `none` is allowed.
fn role_param(p: &Value, cmd: &str, none: bool) -> Result<Option<Role>> {
let id = text_param(p, "role", cmd)?.ok_or_else(|| bad(cmd, "missing `role`"))?;
match Role::from_id(id) {
Some(r) => Ok(Some(r)),
None if none && id == "none" => Ok(None),
None if none => Err(bad(cmd, format!("unknown role `{id}`: cut, crease, partialCut, perforation or none"))),
None => Err(bad(cmd, format!("unknown role `{id}`: cut, crease, partialCut or perforation"))),
}
}
/// Why swatch `name` of `d` can't carry a role, if it can't.
fn unfit_swatch(d: &Document, name: &str) -> Option<String> {
if name == REGISTRATION || name == "[None]" {
return Some(format!("`{name}` can't carry a role"));
}
let Some(sw) = d.swatch(name) else { return Some(format!("no swatch `{name}`")) };
match &sw.paint {
Paint::Solid { swatch: Some(_), .. } => Some(format!("`{name}` is a tint swatch: pick its base or another global or spot color")),
Paint::Solid { .. } if sw.global => None,
Paint::Solid { .. } => Some(format!("`{name}` is a process color: pick a global or spot color")),
_ => Some(format!("`{name}` isn't a color swatch")),
}
}
/// `role`'s swatch in `d`, made as a global spot swatch in the document's color mode when `d`
/// lacks it → its paint at 100%. When a color group or a swatch that can't carry a role (a process
/// color that is not global, a tint, a gradient) has the swatch's name, the swatch is made under a
/// free name, which the role table then gives the role.
fn role_paint(d: &mut Document, role: Role) -> Result<Paint> {
let mut table = RoleTable::of(d);
let current = table.swatch(role);
let taken = match d.swatch(current) {
Some(_) => unfit_swatch(d, current).is_some(),
None => d.swatch_name_taken(current),
};
if taken {
let free = free_role_name(d, &table, role);
if let Some(slot) = table.0.get_mut(role.index()) {
*slot = free;
}
d.unknown.insert(ROLES_KEY.to_string(), table.to_value());
}
let name = table.swatch(role);
if d.swatch(name).is_none() {
let model = d.color_mode.model();
let color = role.color();
let color = if color.model() == model {
color
} else {
let cms = vectorcraft_color::cms::active();
cms.convert(&color, model, cms.settings().intent)
};
d.swatches.push(Swatch { name: name.to_string(), paint: Paint::solid(color), global: true, spot: true });
}
if let Some(why) = unfit_swatch(d, name) {
return Err(bad(SET_ROLE, format!("{why} (the {} role's swatch; addon.packaging.setRoleSwatch picks another)", role.name())));
}
d.tint_paint(name, 1.0).ok_or_else(|| bad(SET_ROLE, format!("`{name}` isn't a global or spot color")))
}
/// Gives object `id` of `d` `role`'s `paint` (`None`: takes its role away) → whether it changed.
fn give_role(d: &mut Document, table: &RoleTable, id: NodeId, paint: Option<&Paint>, overprint: bool) -> bool {
let Some(n) = d.node_mut(id) else { return false };
let had = table.role_of(n);
let mut a = (*n.appearance).clone();
match paint {
Some(paint) => {
a.set_stroke(paint.clone());
if let Some(st) = a.stroke_mut() {
if st.width <= 0.0 {
st.width = 1.0;
}
// A hidden stroke would carry the role without drawing or printing the line.
st.visible = true;
st.overprint = overprint;
}
}
None => {
if had.is_none() {
return false;
}
if let Some(st) = a.stroke_mut() {
if let Paint::Solid { color, .. } = st.paint {
st.paint = Paint::solid(color);
}
st.overprint = false;
}
}
}
if a == *n.appearance {
return false;
}
n.appearance = vectorcraft_doc::Shared::new(a);
true
}
fn set_role(s: &mut Session, p: &Value) -> Result<Value> {
let role = role_param(p, SET_ROLE, true)?;
let overprint = switch_or(p, "overprint", true, SET_ROLE)?;
let roots = checked_ids_or_selection(s, p, SET_ROLE)?;
let (ids, skipped) = role_targets(&s.doc()?.doc, &roots, true);
if ids.is_empty() {
return Err(bad(SET_ROLE, "select a path that is neither locked nor hidden: text, images and symbol instances can't have a fold line role"));
}
let label = role.map_or("Remove Fold Line Role", |_| "Make Fold Line");
let mut changed = 0;
edit_counted(s, label, |d| {
let before = (d.swatches.len(), d.unknown.get(ROLES_KEY).cloned());
let paint = role.map(|r| role_paint(d, r)).transpose()?;
// A role swatch made again (its strokes may still name it) is a change of its own.
let made = (d.swatches.len(), d.unknown.get(ROLES_KEY).cloned()) != before;
let table = RoleTable::of(d);
changed = ids.iter().filter(|id| give_role(d, &table, **id, paint.as_ref(), overprint)).count();
Ok(changed + usize::from(made))
})?;
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "changed": changed, "skipped": skipped }))
}
fn roles(s: &mut Session, p: &Value) -> Result<Value> {
let given = p.get("ids").is_some_and(|v| !v.is_null());
let roots = checked_ids_or_selection(s, p, ROLES)?;
let d = &s.doc()?.doc;
let (scope, ids) = match (given, roots.is_empty()) {
(true, _) => ("ids", role_targets(d, &roots, false).0),
(false, false) => ("selection", role_targets(d, &roots, false).0),
(false, true) => ("document", document_targets(d)),
};
let table = RoleTable::of(d);
let mut counts = [0usize; 4];
for r in ids.iter().filter_map(|id| d.node(*id)).filter_map(|n| table.role_of(n)) {
if let Some(c) = counts.get_mut(r.index()) {
*c += 1;
}
}
let rows: Vec<Value> = Role::ALL
.into_iter()
.zip(counts)
.map(|(r, count)| {
let swatch = table.swatch(r);
json!({ "role": r.id(), "name": r.name(), "swatch": swatch, "exists": d.swatch(swatch).is_some(), "count": count })
})
.collect();
Ok(json!({ "roles": rows, "scope": scope, "selected": roots.len() }))
}
fn set_role_swatch(s: &mut Session, p: &Value) -> Result<Value> {
let Some(role) = role_param(p, SET_ROLE_SWATCH, false)? else { return Err(bad(SET_ROLE_SWATCH, "missing `role`")) };
let name = text_param(p, "swatch", SET_ROLE_SWATCH)?.ok_or_else(|| bad(SET_ROLE_SWATCH, "missing `swatch`"))?;
let d = &s.doc()?.doc;
if let Some(why) = unfit_swatch(d, name) {
return Err(bad(SET_ROLE_SWATCH, why));
}
let mut table = RoleTable::of(d);
if let Some(other) = Role::ALL.into_iter().find(|r| *r != role && table.swatch(*r) == name) {
return Err(bad(SET_ROLE_SWATCH, format!("`{name}` already carries the {} role", other.name())));
}
if let Some(slot) = table.0.get_mut(role.index()) {
*slot = name.to_string();
}
let value = table.to_value();
let changed = RoleTable::of(d) != table;
if changed {
s.edit("Role Swatches", |d, _| {
d.unknown.insert(ROLES_KEY.to_string(), value);
Ok(())
})?;
}
Ok(json!({ "role": role.id(), "swatch": name, "changed": changed }))
}
@@ -0,0 +1,540 @@
//! Tests for Packaging Tools: fold line roles, their swatches and the role table.
use std::collections::BTreeSet;
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{AppearanceItem, Node, NodeKind};
use crate::*;
fn session(mode: &str) -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 400, "colorMode": mode})).unwrap();
s
}
fn id_of(v: &Value) -> NodeId {
NodeId(v["id"].as_u64().unwrap())
}
fn rect(s: &mut Session, x: f64) -> NodeId {
id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": 20, "width": 40, "height": 40})).unwrap())
}
fn node(s: &Session, id: NodeId) -> Node {
s.doc().unwrap().doc.node(id).cloned().unwrap()
}
fn steps(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
fn set_role(s: &mut Session, p: Value) -> Value {
s.execute("addon.packaging.setRole", &p).unwrap()
}
fn err(s: &mut Session, cmd: &str, p: Value) -> String {
s.execute(cmd, &p).unwrap_err().to_string()
}
fn b64(v: &Value) -> Vec<u8> {
vectorcraft_format::base64_decode(v["dataBase64"].as_str().expect("dataBase64")).unwrap()
}
/// The `roles` query's counts, in role order.
fn counts(s: &mut Session, p: Value) -> Vec<u64> {
let r = s.execute("addon.packaging.roles", &p).unwrap();
r["roles"].as_array().unwrap().iter().map(|r| r["count"].as_u64().unwrap()).collect()
}
#[test]
fn set_role_makes_the_spot_swatch_and_links_the_top_stroke() {
let mut s = session("cmyk");
let a = rect(&mut s, 20.0);
assert!(s.doc().unwrap().doc.swatch("Cut").is_none());
let before = steps(&s);
let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(0)));
assert_eq!(steps(&s), before + 1, "one undo step");
let d = &s.doc().unwrap().doc;
let sw = d.swatch("Cut").unwrap();
assert!(sw.global && sw.spot, "{sw:?}");
assert_eq!(sw.paint, Paint::solid(Color::cmyk(0.0, 1.0, 0.0, 0.0)), "100% magenta in a CMYK document");
let st = node(&s, a).appearance.stroke().cloned().unwrap();
assert!(matches!(&st.paint, Paint::Solid { swatch: Some(n), tint, .. } if n == "Cut" && *tint == 1.0), "{:?}", st.paint);
assert!(st.overprint, "role strokes overprint by default");
// Again: nothing changes, and no undo step is recorded.
let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
assert_eq!(r["changed"].as_u64(), Some(0));
assert_eq!(steps(&s), before + 1);
// Undo takes the swatch away with the role.
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.swatch("Cut").is_none());
}
#[test]
fn each_role_gets_its_own_swatch_color_in_the_document_s_mode() {
let mut s = session("rgb");
for (i, role) in ["cut", "crease", "partialCut", "perforation"].into_iter().enumerate() {
let id = rect(&mut s, 20.0 + 60.0 * i as f64);
set_role(&mut s, json!({"role": role, "ids": [id.0]}));
}
let d = &s.doc().unwrap().doc;
let colors: Vec<Color> = ["Cut", "Crease", "Partial Cut", "Perforation"].iter().map(|n| d.swatch(n).unwrap().paint.color().unwrap()).collect();
assert!(colors.iter().all(|c| matches!(c, Color::Rgb { .. })), "an RGB document's swatches are RGB: {colors:?}");
assert_eq!(colors.iter().map(|c| c.to_hex()).collect::<BTreeSet<_>>().len(), 4, "four colors: {colors:?}");
}
#[test]
fn a_path_without_a_stroke_gets_one_and_overprint_can_be_left_off() {
let mut s = session("cmyk");
let a = rect(&mut s, 20.0);
s.edit("strip", |d, _| {
let n = d.node_mut(a).unwrap();
n.appearance.items.retain(AppearanceItem::is_fill);
Ok(())
})
.unwrap();
assert!(node(&s, a).appearance.stroke().is_none());
set_role(&mut s, json!({"role": "crease", "ids": [a.0], "overprint": false}));
let st = node(&s, a).appearance.stroke().cloned().unwrap();
assert_eq!(st.width, 1.0, "a 1 pt stroke");
assert!(!st.overprint);
assert!(matches!(&st.paint, Paint::Solid { swatch: Some(n), .. } if n == "Crease"));
assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut", "ids": [a.0], "overprint": "yes"})).contains("overprint"));
}
#[test]
fn none_takes_the_role_away_and_keeps_the_color() {
let mut s = session("cmyk");
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0));
set_role(&mut s, json!({"role": "perforation", "ids": [a.0]}));
let shown = node(&s, a).appearance.stroke().unwrap().paint.color().unwrap();
let before = steps(&s);
let r = set_role(&mut s, json!({"role": "none", "ids": [a.0, b.0]}));
assert_eq!(r["changed"].as_u64(), Some(1), "the plain rectangle has no role to take away");
assert_eq!(steps(&s), before + 1);
let st = node(&s, a).appearance.stroke().cloned().unwrap();
assert_eq!(st.paint, Paint::solid(shown));
assert!(!st.overprint);
assert_eq!(counts(&mut s, json!({"ids": [a.0, b.0]})), [0, 0, 0, 0]);
// Nothing left with a role: no undo step.
set_role(&mut s, json!({"role": "none", "ids": [a.0, b.0]}));
assert_eq!(steps(&s), before + 1);
}
#[test]
fn bad_roles_and_targets_are_refused() {
let mut s = session("cmyk");
let a = rect(&mut s, 20.0);
assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "fold", "ids": [a.0]})).contains("unknown role"));
assert!(err(&mut s, "addon.packaging.setRole", json!({"ids": [a.0]})).contains("role"));
assert!(err(&mut s, "addon.packaging.setRole", json!({"role": 3, "ids": [a.0]})).contains("role"));
s.execute("select.none", &json!({})).unwrap();
assert!(s.execute("addon.packaging.setRole", &json!({"role": "cut"})).is_err(), "nothing selected");
let t = id_of(&s.execute("text.create", &json!({"x": 20, "y": 200, "text": "Lid", "size": 20})).unwrap());
let before = steps(&s);
assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut", "ids": [t.0]})).contains("select a path"));
assert_eq!(steps(&s), before);
assert!(s.doc().unwrap().doc.swatch("Cut").is_none(), "a refused run makes no swatch");
// Text beside a path is skipped and counted.
let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0, t.0]}));
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(1)));
}
#[test]
fn groups_are_walked_and_their_locked_and_hidden_members_left_out() {
let mut s = session("cmyk");
let (a, b, c) = (rect(&mut s, 20.0), rect(&mut s, 100.0), rect(&mut s, 180.0));
s.execute("select.set", &json!({"ids": [a.0, b.0, c.0]})).unwrap();
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
s.edit("lock", |d, _| {
d.node_mut(b).unwrap().locked = true;
d.node_mut(c).unwrap().visible = false;
Ok(())
})
.unwrap();
let r = set_role(&mut s, json!({"role": "crease", "ids": [g.0]}));
assert_eq!(r["ids"], json!([a.0]));
assert_eq!(r["skipped"].as_u64(), Some(2), "the locked and the hidden member");
assert_eq!(counts(&mut s, json!({"ids": [g.0]})), [0, 1, 0, 0]);
// Named directly, a locked or hidden path is left out too.
let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0, b.0, c.0]}));
assert_eq!((r["ids"].clone(), r["skipped"].as_u64()), (json!([a.0]), Some(2)));
let before = steps(&s);
assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut", "ids": [b.0]})).contains("locked"));
assert_eq!(steps(&s), before);
assert_eq!(counts(&mut s, json!({"ids": [b.0, c.0]})), [0, 0, 0, 0]);
}
#[test]
fn a_clip_group_s_clipping_path_is_skipped_and_counted() {
let mut s = session("cmyk");
let (art, mask) = (rect(&mut s, 20.0), rect(&mut s, 30.0));
s.execute("select.set", &json!({"ids": [art.0, mask.0]})).unwrap();
let g = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap());
let r = set_role(&mut s, json!({"role": "cut", "ids": [g.0]}));
assert_eq!((r["ids"].clone(), r["skipped"].as_u64()), (json!([art.0]), Some(1)), "the clipping path is left out and counted");
}
#[test]
fn a_group_and_its_member_count_once_and_locked_lines_count_in_every_scope() {
let mut s = session("cmyk");
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0));
set_role(&mut s, json!({"role": "cut", "ids": [b.0]}));
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
let r = set_role(&mut s, json!({"role": "crease", "ids": [g.0, a.0]}));
assert_eq!(r["ids"], json!([a.0, b.0]), "each path once");
assert_eq!(counts(&mut s, json!({"ids": [g.0, a.0]})), [0, 2, 0, 0]);
set_role(&mut s, json!({"role": "cut", "ids": [b.0]}));
s.edit("lock", |d, _| {
d.node_mut(b).unwrap().locked = true;
Ok(())
})
.unwrap();
// A locked line keeps its role and is counted, whether its group is selected or not.
assert_eq!(counts(&mut s, json!({"ids": [g.0]})), [1, 1, 0, 0]);
s.execute("select.none", &json!({})).unwrap();
assert_eq!(counts(&mut s, json!({})), [1, 1, 0, 0]);
}
#[test]
fn a_process_swatch_named_like_a_role_swatch_keeps_its_name() {
let mut s = session("cmyk");
let a = rect(&mut s, 20.0);
s.execute("swatch.new", &json!({"name": "Cut", "color": "#ff0000"})).unwrap();
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
let d = &s.doc().unwrap().doc;
assert_eq!(d.unknown.get("packagingRoles").unwrap()["cut"], json!("Cut 2"));
assert!(d.swatch("Cut 2").is_some_and(|w| w.spot), "the role swatch is made beside it");
assert!(d.swatch("Cut").is_some_and(|w| !w.global), "the process swatch is left as it was");
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0]);
}
#[test]
fn the_free_role_swatch_name_is_searched_past_ten_thousand() {
let mut s = session("cmyk");
let a = rect(&mut s, 20.0);
let taken = std::iter::once("Cut".to_string()).chain((2..10_000).map(|i| format!("Cut {i}"))).chain(["Cut 10004".to_string()]);
let process = |name: String| vectorcraft_color::Swatch { name, paint: Paint::solid(Color::rgb(1.0, 0.0, 0.0)), global: false, spot: false };
Arc::make_mut(&mut s.doc_mut().unwrap().doc).swatches.extend(taken.map(process));
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
let d = &s.doc().unwrap().doc;
assert_eq!(d.unknown.get("packagingRoles").unwrap()["cut"], json!("Cut 10000"));
assert!(d.swatch("Cut 10000").is_some_and(|w| w.spot), "the role swatch is made under the first free name");
assert!(d.swatch("Cut 10004").is_some_and(|w| !w.global), "a taken name is left as it was");
}
#[test]
fn a_merged_role_swatch_hands_its_role_to_the_kept_swatch() {
let mut s = session("cmyk");
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0));
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
set_role(&mut s, json!({"role": "crease", "ids": [b.0]}));
s.execute("swatch.new", &json!({"name": "Die", "color": {"model": "cmyk", "c": 0, "m": 0.8, "y": 0.2, "k": 0}, "spot": true})).unwrap();
s.execute("swatch.merge", &json!({"names": ["Die", "Cut"]})).unwrap();
assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["cut"], json!("Die"));
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0], "the cut line is still a cut line");
// A kept swatch that already carries a role keeps it; the merged role's lines take it.
s.execute("swatch.merge", &json!({"names": ["Crease", "Die"]})).unwrap();
let table = s.doc().unwrap().doc.unknown.get("packagingRoles").cloned().unwrap();
assert_eq!((&table["cut"], &table["crease"]), (&json!("Die"), &json!("Crease")), "{table}");
assert_eq!(counts(&mut s, json!({"ids": [a.0, b.0]})), [0, 2, 0, 0]);
// The next Make Cut Line makes the Cut role's swatch again.
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
assert!(s.doc().unwrap().doc.swatch("Die").is_some_and(|w| w.spot));
assert_eq!(counts(&mut s, json!({"ids": [a.0, b.0]})), [1, 1, 0, 0]);
}
#[test]
fn a_global_process_swatch_can_carry_a_role() {
let mut s = session("cmyk");
let a = rect(&mut s, 20.0);
s.execute("swatch.new", &json!({"name": "Die", "color": {"model": "cmyk", "c": 0, "m": 0.8, "y": 0.2, "k": 0}, "global": true})).unwrap();
s.execute("addon.packaging.setRoleSwatch", &json!({"role": "partialCut", "swatch": "Die"})).unwrap();
set_role(&mut s, json!({"role": "partialCut", "ids": [a.0]}));
assert!(matches!(&node(&s, a).appearance.stroke().unwrap().paint, Paint::Solid { swatch: Some(n), .. } if n == "Die"));
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 0, 1, 0]);
}
#[test]
fn roles_counts_the_selection_or_the_whole_document() {
let mut s = session("cmyk");
let (a, b, c) = (rect(&mut s, 20.0), rect(&mut s, 100.0), rect(&mut s, 180.0));
set_role(&mut s, json!({"role": "cut", "ids": [a.0, b.0]}));
set_role(&mut s, json!({"role": "partialCut", "ids": [c.0]}));
s.execute("select.set", &json!({"ids": [a.0, c.0]})).unwrap();
let r = s.execute("addon.packaging.roles", &json!({})).unwrap();
assert_eq!((r["scope"].as_str(), r["selected"].as_u64()), (Some("selection"), Some(2)));
assert_eq!(counts(&mut s, json!({})), [1, 0, 1, 0]);
s.execute("select.none", &json!({})).unwrap();
let r = s.execute("addon.packaging.roles", &json!({})).unwrap();
assert_eq!((r["scope"].as_str(), r["selected"].as_u64()), (Some("document"), Some(0)));
assert_eq!(counts(&mut s, json!({})), [2, 0, 1, 0]);
let rows = r["roles"].as_array().unwrap();
assert_eq!(rows[0], json!({"role": "cut", "name": "Cut", "swatch": "Cut", "exists": true, "count": 2}));
assert_eq!(rows[1]["exists"], json!(false), "no Crease swatch yet");
}
#[test]
fn role_swatches_maps_a_role_to_another_swatch() {
let mut s = session("cmyk");
let a = rect(&mut s, 20.0);
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
s.execute("swatch.new", &json!({"name": "Die", "color": {"model": "cmyk", "c": 0, "m": 0.8, "y": 0.2, "k": 0}, "spot": true})).unwrap();
let before = steps(&s);
let r = s.execute("addon.packaging.setRoleSwatch", &json!({"role": "cut", "swatch": "Die"})).unwrap();
assert_eq!(r["changed"], json!(true));
assert_eq!(steps(&s), before + 1);
assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["cut"], json!("Die"));
// The old swatch's objects keep their color and lose the role.
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 0, 0, 0]);
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
assert!(matches!(&node(&s, a).appearance.stroke().unwrap().paint, Paint::Solid { swatch: Some(n), .. } if n == "Die"));
// The same mapping again changes nothing.
let steps_now = steps(&s);
let r = s.execute("addon.packaging.setRoleSwatch", &json!({"role": "cut", "swatch": "Die"})).unwrap();
assert_eq!((r["changed"].clone(), steps(&s)), (json!(false), steps_now));
}
#[test]
fn a_renamed_role_swatch_keeps_its_role() {
let mut s = session("cmyk");
let a = rect(&mut s, 20.0);
set_role(&mut s, json!({"role": "crease", "ids": [a.0]}));
s.execute("swatch.edit", &json!({"name": "Crease", "newName": "Score"})).unwrap();
assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["crease"], json!("Score"));
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 1, 0, 0]);
// A swatch that carries no role leaves the table alone.
s.execute("swatch.new", &json!({"name": "Ink", "color": {"model": "cmyk", "c": 0, "m": 1, "y": 1, "k": 0}, "spot": true})).unwrap();
s.execute("swatch.edit", &json!({"name": "Ink", "newName": "Red Ink"})).unwrap();
let table = s.doc().unwrap().doc.unknown.get("packagingRoles").cloned().unwrap();
assert_eq!(table, json!({"cut": "Cut", "crease": "Score", "partialCut": "Partial Cut", "perforation": "Perforation"}));
// Undo puts the old name back in the table with the swatch.
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.unknown.get("packagingRoles").is_none());
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 1, 0, 0]);
}
#[test]
fn a_role_swatch_renamed_to_another_role_s_name_leaves_each_role_its_own_swatch() {
let mut s = session("cmyk");
let a = rect(&mut s, 20.0);
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
// No Crease swatch exists yet, so the name is free for the Cut swatch.
s.execute("swatch.edit", &json!({"name": "Cut", "newName": "Crease"})).unwrap();
let table = s.doc().unwrap().doc.unknown.get("packagingRoles").cloned().unwrap();
assert_eq!((&table["cut"], &table["crease"]), (&json!("Crease"), &json!("Crease 2")), "{table}");
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0], "the line is still a cut line");
}
#[test]
fn a_role_swatch_that_stops_being_global_hands_its_role_to_a_new_swatch() {
let mut s = session("cmyk");
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0));
set_role(&mut s, json!({"role": "perforation", "ids": [a.0]}));
s.execute("swatch.edit", &json!({"name": "Perforation", "spot": false, "global": false})).unwrap();
assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["perforation"], json!("Perforation 2"));
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 0, 0, 0], "the unlinked stroke has no role");
set_role(&mut s, json!({"role": "perforation", "ids": [b.0]}));
assert!(s.doc().unwrap().doc.swatch("Perforation 2").is_some_and(|w| w.spot));
assert_eq!(counts(&mut s, json!({"ids": [b.0]})), [0, 0, 0, 1]);
}
#[test]
fn a_color_group_named_like_a_role_swatch_keeps_its_name() {
let mut s = session("cmyk");
let a = rect(&mut s, 20.0);
s.execute("swatch.newGroup", &json!({"name": "Cut", "colors": ["#ff0000"]})).unwrap();
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
let d = &s.doc().unwrap().doc;
assert_eq!(d.unknown.get("packagingRoles").unwrap()["cut"], json!("Cut 2"));
assert!(d.swatch("Cut 2").is_some_and(|w| w.spot) && d.swatch("Cut").is_none());
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0]);
}
#[test]
fn set_role_makes_a_deleted_role_swatch_again_for_strokes_that_still_name_it() {
let mut s = session("cmyk");
let a = rect(&mut s, 20.0);
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
s.execute("swatch.delete", &json!({"name": "Cut", "unlink": false})).unwrap();
assert!(s.doc().unwrap().doc.swatch("Cut").is_none());
let before = steps(&s);
let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
assert_eq!(r["changed"].as_u64(), Some(0), "the stroke already names the swatch");
assert!(s.doc().unwrap().doc.swatch("Cut").is_some_and(|w| w.spot), "the swatch is back");
assert_eq!(steps(&s), before + 1, "as one undo step");
}
#[test]
fn a_hidden_stroke_is_shown_when_it_takes_a_role() {
let mut s = session("cmyk");
let a = rect(&mut s, 20.0);
s.edit("hide", |d, _| {
if let Some(AppearanceItem::Stroke(st)) = d.node_mut(a).unwrap().appearance.items.iter_mut().find(|i| !i.is_fill()) {
st.visible = false;
}
Ok(())
})
.unwrap();
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
assert!(node(&s, a).appearance.stroke().unwrap().visible);
}
#[test]
fn role_swatches_refuses_swatches_that_cannot_carry_a_role() {
let mut s = session("cmyk");
let ramp = json!({"type": "linear", "stops": [{"offset": 0, "color": "#000000"}, {"offset": 1, "color": "#ffffff"}]});
s.execute("swatch.new", &json!({"name": "Ramp", "gradient": ramp})).unwrap();
s.execute("swatch.new", &json!({"name": "Plain", "color": "#336699"})).unwrap();
s.execute("swatch.new", &json!({"name": "Ink", "color": {"model": "cmyk", "c": 0, "m": 1, "y": 1, "k": 0}, "spot": true})).unwrap();
s.execute("swatch.new", &json!({"name": "Ink Tint", "swatch": "Ink", "tint": 0.5})).unwrap();
s.execute("swatch.new", &json!({"name": "Crease", "color": {"model": "cmyk", "c": 1, "m": 0, "y": 0, "k": 0}, "spot": true})).unwrap();
let before = steps(&s);
for (swatch, says) in [
("Nope", "no swatch"),
("Ramp", "isn't a color swatch"),
("Plain", "process color"),
("Ink Tint", "tint swatch"),
("[None]", "can't carry a role"),
("[Registration]", "can't carry a role"),
("Crease", "already carries the Crease role"),
] {
let e = err(&mut s, "addon.packaging.setRoleSwatch", json!({"role": "cut", "swatch": swatch}));
assert!(e.contains(says), "{swatch}: {e}");
}
assert!(err(&mut s, "addon.packaging.setRoleSwatch", json!({"role": "none", "swatch": "Ink"})).contains("unknown role"));
assert!(err(&mut s, "addon.packaging.setRoleSwatch", json!({"role": "cut"})).contains("swatch"));
assert_eq!(steps(&s), before, "no refusal records an undo step");
}
#[test]
fn a_damaged_role_table_reads_as_the_defaults() {
let mut s = session("cmyk");
s.edit("damage", |d, _| {
d.unknown.insert("packagingRoles".into(), json!({"cut": 5, "crease": "", "partialCut": null, "extra": "x"}));
Ok(())
})
.unwrap();
let r = s.execute("addon.packaging.roles", &json!({})).unwrap();
let swatches: Vec<&str> = r["roles"].as_array().unwrap().iter().map(|r| r["swatch"].as_str().unwrap()).collect();
assert_eq!(swatches, ["Cut", "Crease", "Partial Cut", "Perforation"]);
s.edit("not an object", |d, _| {
d.unknown.insert("packagingRoles".into(), json!("Cut"));
Ok(())
})
.unwrap();
let a = rect(&mut s, 20.0);
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0]);
// One swatch named for two roles: the later role takes its own default.
s.edit("duplicate", |d, _| {
d.unknown.insert("packagingRoles".into(), json!({"cut": "Crease", "crease": "Crease", "partialCut": "Cut"}));
Ok(())
})
.unwrap();
let r = s.execute("addon.packaging.roles", &json!({})).unwrap();
let swatches: Vec<&str> = r["roles"].as_array().unwrap().iter().map(|r| r["swatch"].as_str().unwrap()).collect();
assert_eq!(swatches, ["Crease", "Crease 2", "Cut", "Perforation"]);
let b = rect(&mut s, 100.0);
set_role(&mut s, json!({"role": "crease", "ids": [b.0]}));
assert_eq!(counts(&mut s, json!({"ids": [b.0]})), [0, 1, 0, 0], "the crease line is a crease line");
}
#[test]
fn native_save_and_open_keep_the_role_table_and_the_roles() {
let mut s = session("cmyk");
let a = rect(&mut s, 20.0);
s.execute("swatch.new", &json!({"name": "Die", "color": {"model": "cmyk", "c": 0, "m": 0.8, "y": 0.2, "k": 0}, "spot": true})).unwrap();
s.execute("addon.packaging.setRoleSwatch", &json!({"role": "cut", "swatch": "Die"})).unwrap();
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
let saved = s.execute("document.export", &json!({"format": "vectorcraft"})).unwrap();
s.execute("document.open", &json!({"name": "box.vectorcraft", "dataBase64": saved["dataBase64"]})).unwrap();
assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["cut"], json!("Die"));
s.execute("select.none", &json!({})).unwrap();
assert_eq!(counts(&mut s, json!({})), [1, 0, 0, 0]);
}
/// A document with one rectangle of each of Cut and Crease.
fn two_roles() -> Session {
let mut s = session("cmyk");
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0));
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
set_role(&mut s, json!({"role": "crease", "ids": [b.0]}));
s
}
fn export(s: &mut Session, format: &str) -> String {
String::from_utf8_lossy(&b64(&s.execute("document.export", &json!({"format": format})).unwrap())).into_owned()
}
#[test]
fn pdf_prints_each_role_on_its_swatch_s_separation_and_overprints_it() {
let mut s = two_roles();
let c = rect(&mut s, 180.0);
set_role(&mut s, json!({"role": "partialCut", "ids": [c.0]}));
let bytes = vectorcraft_pdf::export(
&s.doc().unwrap().doc,
&vectorcraft_pdf::PdfOptions { created: Some(0), ..vectorcraft_pdf::PdfOptions::uncompressed() },
)
.unwrap();
let pdf = String::from_utf8_lossy(&bytes);
assert!(pdf.contains("/Separation/Cut"), "the Cut line prints on the Cut plate");
assert!(pdf.contains("/Separation/Crease"));
assert!(pdf.contains("/Separation/Partial#20Cut"), "a name with a space");
assert!(pdf.contains("/OP true"), "the role strokes overprint");
// Without overprint, nothing in the file overprints.
let mut plain = session("cmyk");
let (a, b) = (rect(&mut plain, 20.0), rect(&mut plain, 100.0));
set_role(&mut plain, json!({"role": "cut", "ids": [a.0], "overprint": false}));
set_role(&mut plain, json!({"role": "crease", "ids": [b.0], "overprint": false}));
let bytes = vectorcraft_pdf::export(
&plain.doc().unwrap().doc,
&vectorcraft_pdf::PdfOptions { created: Some(0), ..vectorcraft_pdf::PdfOptions::uncompressed() },
)
.unwrap();
assert!(!String::from_utf8_lossy(&bytes).contains("/OP true"));
assert!(!export(&mut s, "pdf").is_empty());
}
#[test]
fn svg_dxf_and_hpgl_keep_the_default_role_swatches_apart() {
let mut s = two_roles();
let svg = export(&mut s, "svg");
let strokes: BTreeSet<&str> = svg.split("stroke=\"").skip(1).filter_map(|t| t.split('"').next()).filter(|c| c.starts_with('#')).collect();
let strokes = if strokes.is_empty() {
svg.split("stroke:").skip(1).filter_map(|t| t.split([';', '"', '}']).next()).filter(|c| c.starts_with('#')).collect()
} else {
strokes
};
assert_eq!(strokes.len(), 2, "two stroke colors: {svg}");
let dxf = export(&mut s, "dxf");
let lines: Vec<&str> = dxf.lines().map(str::trim).collect();
// The rectangles' white fills come out as true colors too.
let colors: BTreeSet<&str> = lines.windows(2).filter(|w| w[0] == "420" && w[1] != "16777215").map(|w| w[1]).collect();
assert_eq!(colors.len(), 2, "two stroke true colors: {colors:?}");
let plot = s.execute("document.export", &json!({"format": "hpgl", "hpglVersion": "hpgl2"})).unwrap();
let plot = String::from_utf8_lossy(&b64(&plot)).into_owned();
assert!(plot.contains("SP1") && plot.contains("SP2"), "a pen per role swatch color: {plot}");
}
#[test]
fn compound_paths_carry_a_role() {
let mut s = session("cmyk");
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 30.0));
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let c = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap());
assert!(matches!(node(&s, c).kind, NodeKind::Compound { .. }));
let r = set_role(&mut s, json!({"role": "cut", "ids": [c.0]}));
assert_eq!(r["ids"], json!([c.0]));
assert_eq!(counts(&mut s, json!({"ids": [c.0]})), [1, 0, 0, 0]);
// A member named by id gives its compound the role.
let r = set_role(&mut s, json!({"role": "crease", "ids": [a.0, b.0]}));
assert_eq!((r["ids"].clone(), r["changed"].as_u64()), (json!([c.0]), Some(1)));
assert_eq!(counts(&mut s, json!({"ids": [c.0]})), [0, 1, 0, 0]);
}
@@ -1225,7 +1225,7 @@ fn expand_dashes_keeps_the_fill_below_and_follows_aligned_corners() {
let mut centred = 0;
for id in ids(&r) {
let sp = path(&s, id).subpaths[0].clone();
if let [a, b, c] = sp.anchors.as_slice()
if let [a, b, c] = &*sp.anchors.to_vec()
&& corners.iter().any(|k| b.p.distance(*k) < 1e-6)
{
assert!((a.p.distance(b.p) - 5.0).abs() < 1e-6 && (c.p.distance(b.p) - 5.0).abs() < 1e-6, "{sp:?}");
+6 -6
View File
@@ -14,8 +14,9 @@ use vectorcraft_doc::{LockedArtboards, Node, NodeId, NodeKind};
use vectorcraft_geom::Point;
use super::super::links::{Status, statuses};
use super::super::panelcmds::listed_artboards;
use super::super::select::{is_selectable, on_artboard, selectable};
use super::super::{CommandSpec, bad, checked_ids_param, cmd, has_doc, point_indices, switch_or, text_param};
use super::super::{CommandSpec, bad, checked_ids_param, cmd, has_doc, switch_or, text_param};
use crate::{DocState, Result, Session};
/// How Select by Artboards relates an object to the chosen artboards (`relation`).
@@ -33,7 +34,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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}",
"{artboards: [index…] (0-based whole numbers, 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
),
@@ -58,13 +59,12 @@ fn by_artboards(s: &mut Session, p: &Value) -> Result<Value> {
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() {
if listed.as_array().is_some_and(Vec::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 rects: Vec<_> =
listed_artboards(&st.doc, listed, "artboards", C)?.into_iter().filter_map(|i| st.doc.artboards.get(i)).map(|a| a.rect).collect();
let symbols = st.doc.symbol_boxes();
let ids: Vec<NodeId> = selectable(&st.doc, st.isolation)
.into_iter()
@@ -108,6 +108,35 @@ fn bad_params_are_errors_and_leave_the_selection() {
}
}
/// A malformed `artboards` entry is refused as one, naming the parameter, before any entry is
/// looked up; a value that is not a list, an empty list, a left-out list and a whole number past
/// the last artboard each have their own error.
#[test]
fn artboard_errors_say_what_is_wrong() {
let mut s = three_boards();
let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
let entries = "invalid parameters for `addon.select.byArtboards`: `artboards` must contain whole numbers";
let not_a_list = "invalid parameters for `addon.select.byArtboards`: `artboards` must be a list of artboard indices";
for (p, want) in [
(json!({"artboards": ["1"]}), entries),
(json!({"artboards": [-1]}), entries),
(json!({"artboards": [1.5]}), entries),
(json!({"artboards": [true]}), entries),
(json!({"artboards": [9, "1"]}), entries),
(json!({"artboards": "0"}), not_a_list),
(json!({"artboards": null}), not_a_list),
(json!({"artboards": []}), "invalid parameters for `addon.select.byArtboards`: choose at least one artboard"),
(json!({}), "invalid parameters for `addon.select.byArtboards`: missing `artboards`"),
(json!({"artboards": [9]}), "no such artboard"),
(json!({"artboards": [0, 9]}), "no such artboard"),
] {
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
assert_eq!(s.execute(C, &p).unwrap_err().to_string(), want, "{p}");
assert_eq!(s.doc().unwrap().selection.objects, vec![a], "{p}");
}
assert_eq!(pick(&mut s, json!({"artboards": [0, 0]})), vec![a]);
}
#[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
+1 -1
View File
@@ -126,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Live Paint Bucket (Stroke)",
[],
None,
"{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), scope?: \"one\" (default: the edge alone) | \"connected\" (a double-click: also each edge joined to it, end to end, through edges that draw with stroke paint match) | \"samePaint\" (a triple-click: also every edge of the group that draws with stroke paint match), match?: paint (as the document stores it; scope connected or samePaint only; default: the stroke paint the edge draws with; an edge draws with the paint of its topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully transparent or has no such stroke), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point, skipping hidden edges: each edge reached has its strokes replaced by one stroke with the paint and width, shown, fully opaque and blending normally, in the place of its topmost stroke and with the dashes, caps and arrowheads of its topmost shown stroke (a new stroke above the fills when it has none; none leaves one stroke of none), and its fills stay as they are; when every edge it reaches already has only that one stroke (at any width for none), nothing changes (no undo step, and the recent colors stay as they are) → {group, edge, count (edges reached)}",
"{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), scope?: \"one\" (default: the edge alone) | \"connected\" (a double-click: also each edge joined to it, end to end, through edges that draw with stroke paint match) | \"samePaint\" (a triple-click: also every edge of the group that draws with stroke paint match), match?: paint (as the document stores it; scope connected or samePaint only; default: the stroke paint the edge draws with; an edge draws with the paint of its topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully transparent or has no such stroke), through?: [id…] (scope connected only; at most 4096 edges counted as drawing with stroke paint match whatever they draw with, such as the edge a double-click's first click painted), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point, skipping hidden edges: each edge reached has its strokes replaced by one stroke with the paint and width, shown, fully opaque and blending normally, in the place of its topmost stroke and with the dashes, caps and arrowheads of its topmost shown stroke (a new stroke above the fills when it has none; none leaves one stroke of none), and its fills stay as they are; when every edge it reaches already has only that one stroke (at any width for none), nothing changes (no undo step, and the recent colors stay as they are) → {group, edge, count (edges reached)}",
has_doc,
lp_stroke_edge
),
+11 -1
View File
@@ -567,6 +567,16 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
let tol = number_or(p, "tolerance", 4.0, C)?.clamp(0.0, 1000.0);
let scope = scope_param(p, C)?;
let like = match_param(p, C, scope != LpScope::One, "\"connected\" or \"samePaint\"")?;
let through: Vec<NodeId> = match p.get("through") {
None => vec![],
Some(_) if scope != LpScope::Connected => return Err(bad(C, "through applies to scope \"connected\"")),
Some(v) => {
let ids = v.as_array().filter(|ids| ids.len() <= 4096).ok_or_else(|| bad(C, "through must be an array of at most 4096 edge ids"))?;
ids.iter()
.map(|id| id.as_u64().map(NodeId).ok_or_else(|| bad(C, "through must be an array of at most 4096 edge ids")))
.collect::<Result<_>>()?
}
};
let (eid, count, changed) = {
let d = &s.doc()?.doc;
let n = d.node(g).filter(|n| is_live_paint(n)).ok_or_else(|| bad(C, format!("{g} is not a Live Paint group")))?;
@@ -575,7 +585,7 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
let like = like.unwrap_or_else(|| b::lp_stroke_paint(start));
let targets = match scope {
LpScope::One => vec![eid],
LpScope::Connected => b::connected_edges(n, eid, &like),
LpScope::Connected => b::connected_edges_through(n, eid, &like, &through),
LpScope::SamePaint => std::iter::once(eid)
.chain(b::edges(n).into_iter().filter(|e| e.visible && e.id != eid && b::lp_stroke_paint(e) == like).map(|e| e.id))
.collect(),
+30 -7
View File
@@ -12,6 +12,7 @@ use super::{
thread_local! {
static BOX_TESTS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
static CANDIDATE_VISITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
static TRACES_ON_THIS_THREAD: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
// ---------- Image Trace ----------
@@ -548,15 +549,20 @@ fn color_groups(cmd: &str, d: &mut Document, items: Vec<Arc<Node>>) -> Result<Ve
Ok(seams.into_iter().chain(groups).collect())
}
/// What a trace depends on: the document it is made in, the object traced (an image, or an Image
/// Trace object traced again), its image, the image's encoded bytes, and the settings it is traced
/// with. The tracer makes the same paths of the same inputs, so a trace made away from the command
/// ([`TraceRun`]) stands in for the command's own in the same document.
/// What a trace depends on: the document it is made in and the content it was reverted to, the
/// object traced (an image, or an Image Trace object traced again), its image, the image's encoded
/// bytes, and the settings it is traced with. The tracer makes the same paths of the same inputs,
/// so a trace made away from the command ([`TraceRun`]) stands in for the command's own in the same
/// document until File › Revert replaces its content.
#[derive(Clone, Debug, PartialEq)]
struct TraceInputs {
/// The [`DocState::uid`](crate::DocState::uid) of the document traced in. A trace made in one
/// document never stands in for one in another, however alike their images and settings.
doc: u64,
/// The document's [`DocState::reverts`](crate::DocState::reverts) when the trace was prepared.
/// A trace prepared before File › Revert never stands in for one after it, even when the
/// restored image, pixels, object and settings are the same.
reverts: u64,
target: NodeId,
image: Box<ImageObject>,
/// The settings traced with, as JSON.
@@ -625,7 +631,8 @@ fn prepare(s: &Session, c: &str, p: &Value) -> Result<Prepared> {
let bytes = Arc::clone(&blob.bytes);
let library = trace_library(c, s, &mut params)?;
let traced_with = serde_json::to_value(&params).map_err(|e| EngineError::Other(e.to_string()))?;
let inputs = TraceInputs { doc: s.doc()?.uid, target, image, params: traced_with, swatches: params.swatches.clone(), bytes };
let st = s.doc()?;
let inputs = TraceInputs { doc: st.uid, reverts: st.reverts, target, image, params: traced_with, swatches: params.swatches.clone(), bytes };
Ok(Prepared { inputs, trace: params, view, params_json, preset_label, library })
}
@@ -641,7 +648,8 @@ pub struct Traced {
impl Traced {
/// Hand it to the next run of its command with the same inputs ([`TraceRun::params`]) in the
/// document it was made in, which applies it as one undo step instead of tracing again. Any
/// other trace drops it, a trace in another document included.
/// other trace drops it and traces again, a trace in another document included, and so does
/// the command after File › Revert replaced the document's content.
pub fn hand_in(self, s: &mut Session) {
s.trace_hand_off = Some(self);
}
@@ -650,6 +658,8 @@ impl Traced {
/// Decode the image bytes of `inputs` and trace them with `params`, telling `steps` how far it has
/// got ([`tr::trace_watched`]); [`EngineError::Cancelled`] once `steps` answers `false`.
fn trace_now(inputs: &TraceInputs, params: &tr::TraceParams, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result<Traced> {
#[cfg(test)]
TRACES_ON_THIS_THREAD.with(|n| n.set(n.get() + 1));
// An image over the tracer's size is traced scaled down (the paths are scaled back).
let raster = tr::Raster::decode_to_fit(&inputs.bytes).map_err(|e| EngineError::Other(e.to_string()))?;
if !steps(0, 0) {
@@ -725,17 +735,30 @@ impl TraceRun {
}
/// Does it still apply: would the command trace the same object, image, pixels and settings
/// now, in the document it was prepared in?
/// now, in the document it was prepared in, with no File › Revert since?
pub fn current(&self, s: &Session) -> bool {
prepare(s, self.command, &self.params).is_ok_and(|now| now.inputs == self.prepared.inputs)
}
/// Has File › Revert replaced the content of the document it was prepared in since then? False
/// when that document is no longer open.
pub fn reverted(&self, s: &Session) -> bool {
let TraceInputs { doc, reverts, .. } = self.prepared.inputs;
s.documents().iter().any(|st| st.uid == doc && st.reverts != reverts)
}
/// Decode and trace the image, telling `steps` how far it has got → what it traced, or why it
/// failed or stopped ([`EngineError::Cancelled`] once `steps` answers `false`). It touches no
/// document, so it can run on any thread.
pub fn run(&self, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result<Traced> {
trace_now(&self.prepared.inputs, &self.prepared.trace, steps)
}
/// How many images this thread has decoded and traced so far.
#[cfg(test)]
pub(crate) fn traces_on_this_thread() -> usize {
TRACES_ON_THIS_THREAD.with(std::cell::Cell::get)
}
}
pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Value> {
+29 -1
View File
@@ -595,6 +595,8 @@ struct Relink {
styles: BTreeMap<u32, u32>,
/// Swatch (its name in the document) → the colour linked colours show at 100 %.
colors: BTreeMap<String, Color>,
/// Leave graphic style links as they are ([`Clipboard::show_merged_colors`]).
keep_styles: bool,
}
impl Relink {
@@ -674,7 +676,9 @@ impl Relink {
/// Relink a node tree (the mirror of [`node_refs`]).
fn node(&self, n: &mut Node) {
self.appearance(&mut n.appearance);
n.extras_mut().graphic_style = n.extras().graphic_style.and_then(|id| self.styles.get(&id).copied());
if !self.keep_styles {
n.extras_mut().graphic_style = n.extras().graphic_style.and_then(|id| self.styles.get(&id).copied());
}
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) {
self.node(Arc::make_mut(&mut m.art));
}
@@ -1109,6 +1113,30 @@ impl Clipboard {
self.import_used(d, &self.used(), choices, same_doc)
}
/// Give the objects' colors linked to a global or spot swatch whose conflict with `d`
/// `choices` merge the color that swatch has in `d`, as pasting into `d` gives them (Paste
/// without Formatting sets its pie legend labels' contrast from the wedge colors before it
/// pastes). Nothing changes for the document the objects came from (`same_doc`).
pub(crate) fn show_merged_colors(&mut self, d: &Document, choices: &SwatchChoices, same_doc: bool) {
if same_doc {
return;
}
let used = self.used();
let colors: BTreeMap<String, Color> = self
.conflicts(d, &used)
.into_iter()
.filter(|(w, _)| choices.of(&w.name) == SwatchChoice::Merge)
.filter_map(|(w, _)| d.global_color(&w.name).map(|c| (w.name.clone(), c)))
.collect();
if colors.is_empty() {
return;
}
let relink = Relink { colors, keep_styles: true, ..Default::default() };
for n in &mut self.nodes {
relink.node(n);
}
}
/// [`Self::import_into`] for the resources `used` names. Each style, symbol, pattern and brush
/// comes after the styles, symbols, patterns and brushes it uses ([`use_order`]), so that it is
/// compared and relinked with their names here, and each loop of definitions that use each
+2 -1
View File
@@ -356,7 +356,8 @@ fn mirror_open(sp: &SubPath, axis: &Axis, m: Affine) -> Vec<SubPath> {
if !end_on {
run.reverse();
}
let Some((last, body)) = run.anchors.split_last() else { return vec![] };
let run = run.anchors.into_vec();
let Some((last, body)) = run.split_last() else { return vec![] };
let q = axis.project(last.p);
let mut anchors = body.to_vec();
anchors.push(Anchor::with_handles(q, last.h_in, m * last.h_in));
+3 -9
View File
@@ -10,6 +10,7 @@ use vectorcraft_doc::{CharStyle, Guide, Node, NodeId, NodeKind, SavedSelection,
use vectorcraft_geom::Vec2;
use super::edit::selected_roots;
use super::panelcmds::artboard_at;
use super::pathops::Beside;
use super::select::{first_selectable, is_selectable, selectable_ids, walk_selectable};
use super::{
@@ -201,7 +202,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add Guide",
[],
None,
"{vertical: bool, pos: pt (x for vertical, y for horizontal), artboard?: index (an artboard guide: it runs across that artboard only and moves, is copied and is deleted with it; default a canvas guide, across the whole canvas), layer?: id (the layer it is on, shown, hidden, locked and deleted with it; default the current layer)} → {index}",
"{vertical: bool, pos: pt (x for vertical, y for horizontal), artboard?: index (0-based whole number; an artboard guide: it runs across that artboard only and moves, is copied and is deleted with it; default, or null, a canvas guide, across the whole canvas), layer?: id (the layer it is on, shown, hidden, locked and deleted with it; default the current layer)} → {index}",
has_doc,
guide_add
),
@@ -767,15 +768,8 @@ fn clear_guides(s: &mut Session, _: &Value) -> Result<Value> {
fn guide_add(s: &mut Session, p: &Value) -> Result<Value> {
let pos = f64_req(p, "pos", "guide.add")?;
let vertical = switch_or(p, "vertical", false, "guide.add")?;
let artboard = match p.get("artboard").filter(|v| !v.is_null()) {
Some(v) => {
let boards = &s.doc()?.doc.artboards;
let ab = v.as_u64().and_then(|i| boards.get(usize::try_from(i).ok()?)).ok_or_else(|| EngineError::Other("no such artboard".into()))?;
Some(ab.id)
}
None => None,
};
let st = s.doc()?;
let artboard = artboard_at(&st.doc, p, "artboard", "guide.add")?.and_then(|i| st.doc.artboards.get(i)).map(|a| a.id);
let layer = match id_param(p, "layer") {
Some(l) if st.doc.node(l).is_some_and(Node::is_layer) => Some(l),
Some(_) => return Err(bad("guide.add", "layer must name a layer or sublayer")),
+14 -8
View File
@@ -46,7 +46,7 @@ fn fit_freehand(pts: &[Point], tol: f64, closed: bool) -> SubPath {
let sp = vectorcraft_tools::draw2::catmull_rom(&marked, false);
if sp.anchors.len() < 3 {
// Two anchors closed would run back over the line itself.
return SubPath::new(sp.anchors, closed && n > 2);
return SubPath::of(sp.anchors, closed && n > 2);
}
let fitted = po::simplify_with(
&PathData::single(sp.clone()),
@@ -62,7 +62,7 @@ fn fit_freehand(pts: &[Point], tol: f64, closed: bool) -> SubPath {
f.h_in = f.p;
}
}
SubPath::new(anchors, closed)
SubPath::of(anchors, closed)
}
/// The path of a freehand stroke: fitted at `tol` ([`fit_freehand`]), or with no `tol` the points
@@ -133,13 +133,13 @@ fn redraw_section(pd: &PathData, pts: &[Point], tol: Option<f64>, within: f64) -
*s0 = s1.p;
let (Some(e0), Some(e1)) = (stroke.last_mut(), sp.anchors.get(end)) else { return None };
*e0 = e1.p;
let fit = stroke_subpath(&stroke, tol, false).anchors;
let fit = stroke_subpath(&stroke, tol, false).anchors.into_vec();
let (Some(f0), Some(f1)) = (fit.first().copied(), fit.last().copied()) else { return None };
let inner = fit.get(1..fit.len().saturating_sub(1)).unwrap_or_default();
let (before, after): (Vec<Anchor>, Vec<Anchor>) = if sp.closed {
((0..=(start + n - end) % n).filter_map(|k| sp.anchors.get((end + k) % n).copied()).collect(), vec![])
} else {
(sp.anchors.get(..=start)?.to_vec(), sp.anchors.get(end..)?.to_vec())
(sp.anchors.get_range(..=start)?, sp.anchors.get_range(end..)?)
};
let mut anchors = before;
if let Some(a) = anchors.last_mut() {
@@ -227,12 +227,18 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s
let Some(p0) = pts.first_mut() else { return Err(bad(C, "needs points")) };
*p0 = end;
if pts.len() < 2 {
// No stroke to add: the brush alone changes, when it is not the path's already.
// No stroke to add: the brush alone changes, when it is not the path's already, and the
// path is selected or deselected as a longer continuation leaves it.
if let Some(name) = brush_name
&& s.doc()?.doc.node(target).and_then(|n| n.appearance.stroke()).is_some_and(|st| st.brush.as_deref() != Some(name))
{
s.edit("Paintbrush", |d, _| {
s.edit("Paintbrush", |d, sel| {
set_brush(d, target, name);
if keep_selected {
sel.set([id]);
} else {
sel.remove(id);
}
Ok(())
})?;
}
@@ -316,12 +322,12 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s
// outgoing handle.
let mut other_len = 0.0;
if let Some((_, _, y, _)) = &connect
&& let Some((y0, rest)) = y.anchors.split_first()
&& let Some(y0) = y.anchors.first()
{
if let Some(last) = sp.anchors.last_mut() {
*last = Anchor::with_handles(y0.p, last.h_in + (y0.p - last.p), y0.h_out);
}
sp.anchors.extend_from_slice(rest);
sp.anchors.extend(y.anchors.iter().skip(1));
other_len = subpath_len(y);
}
// What the pen recorded along the path (in the direction it is continued in), followed by
+11 -11
View File
@@ -274,7 +274,7 @@ fn refit_run(anchors: &[Anchor], tol: f64, sigma: f64, free: [bool; 2]) -> Vec<A
for a in &mut out {
*a = Anchor::with_handles(a.p, a.h_in, a.h_out);
}
out
out.into_vec()
}
/// Distance (points) from an anchor within which a smoothed closed path starts at that anchor
@@ -549,7 +549,7 @@ fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f
if sp.closed {
let start = sp.anchors[0].p;
let Some(k) = marked.iter().position(|m| !m) else {
let corners = smooth_corners(&sp.anchors, true, radius);
let corners = smooth_corners(&sp.anchors.contiguous(), true, radius);
let Some(c) = corners.iter().position(|c| *c) else {
// Everything is in range and nothing is a corner: smooth the whole closed path,
// across its start too.
@@ -557,7 +557,7 @@ fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f
return f.subpaths.into_iter().next().map(|r| start_nearest(r, start, sp));
};
// Cut the path open at a corner, which then ends the last part as well as starting the first.
let mut open = sp.anchors.clone();
let mut open = sp.anchors.to_vec();
open.rotate_left(c);
let mut cut = corners;
cut.rotate_left(c);
@@ -576,15 +576,14 @@ fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f
return Some(start_nearest(SubPath::new(res, true), start, sp));
};
// Rotate so an untouched anchor comes first, duplicate it at the end and treat as open.
let mut open = sp.clone();
open.anchors.rotate_left(k);
let mut open = sp.anchors.to_vec();
open.rotate_left(k);
let mut m = marked.clone();
m.rotate_left(k);
open.anchors.push(open.anchors[0]);
open.push(open[0]);
m.push(false);
open.closed = false;
let mut res = smooth_open(&open.anchors, &m, near, tol, sigma, radius, false);
if same_anchors(&res, &open.anchors) {
let mut res = smooth_open(&open, &m, near, tol, sigma, radius, false);
if same_anchors(&res, &open) {
return None;
}
let l = res.pop()?;
@@ -595,8 +594,9 @@ fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f
let res = SubPath::new(res, true);
return Some(if k == 0 { res } else { start_nearest(res, start, sp) });
}
let res = smooth_open(&sp.anchors, &marked, near, tol, sigma, radius, true);
(!same_anchors(&res, &sp.anchors)).then(|| SubPath::new(res, false))
let anchors = sp.anchors.contiguous();
let res = smooth_open(&anchors, &marked, near, tol, sigma, radius, true);
(!same_anchors(&res, &anchors)).then(|| SubPath::new(res, false))
}
/// The segment `c`, which ends in the drag's reach (`near`) and starts outside it, split where it
+8 -2
View File
@@ -367,7 +367,8 @@ fn edit_effects(
/// [`edit_effects`] for several effects of one list (`indices`): `f` gets each target's list and
/// the positions of `indices` there, ascending; with `aligned`, a position a target doesn't share
/// is left out of it, and a target sharing none of them is left out.
/// is left out of it, and a target sharing none of them is left out. A position no target has is
/// an error with `none`, and nothing changes.
#[allow(clippy::too_many_arguments)]
fn edit_effects_at(
s: &mut Session,
@@ -396,7 +397,12 @@ fn edit_effects_at(
// Each target's list and the positions in it, in the order the targets first come up.
let mut targets: Vec<(NodeId, Option<usize>, Vec<usize>)> = vec![];
for &index in indices {
for (id, at, i) in effect_targets(s, p, item, index, cmd)? {
let found = effect_targets(s, p, item, index, cmd)?;
// An aligned effect of a design's art that no other object has is refused, as it is given alone.
if found.is_empty() {
return Err(EngineError::Other(none.into()));
}
for (id, at, i) in found {
match targets.iter_mut().find(|t| t.0 == id && t.1 == at) {
Some(t) => t.2.push(i),
None => targets.push((id, at, vec![i])),
+8 -5
View File
@@ -265,18 +265,21 @@ fn gradient_expands(d: &Document, l: &Node) -> bool {
/// Whether type `t` has a gradient fill that Fill expands once Object has outlined it: one of the
/// paths `type.createOutlines` makes of its glyphs, ruby glyphs and underline and strikethrough
/// bars, each painted as its run with its unplaced gradients fitted to the layout's bounds, has one
/// bars, each painted as its run with its unplaced gradients fitted to the layout's bounds, or the
/// path filled with its run's stroke under a transform that is not a similarity, has one
/// ([`gradient_expands`] on that path). Inline graphics and color glyphs become other art. Leaves
/// the document as it is and stops at the first such path.
fn text_gradient_expands(d: &Document, t: &TextObject) -> bool {
if !t.runs.iter().any(|r| matches!(r.style.fill, Paint::Gradient(_))) {
let gradient =
|st: &vectorcraft_doc::CharStyle| matches!(st.fill, Paint::Gradient(_)) || (st.has_stroke() && matches!(st.stroke, Paint::Gradient(_)));
if !t.runs.iter().any(|r| gradient(&r.style)) {
return false;
}
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
let first = t.first_style();
let expands = |run: usize, outline: &BezPath| {
let style = t.runs.get(run).map_or(&first, |r| &r.style);
if !matches!(style.fill, Paint::Gradient(_)) {
if !gradient(style) {
return false;
}
let path = PathData::from_bezpath(outline);
@@ -284,8 +287,8 @@ fn text_gradient_expands(d: &Document, t: &TextObject) -> bool {
return false;
}
let mut piece = Node::path(NodeId(u64::MAX), path, Appearance::default());
vectorcraft_render::effects::paint_type_piece(&mut piece, style, lay.bounds, t.xf);
gradient_expands(d, &piece)
let stroke = vectorcraft_render::effects::paint_type_piece(&mut piece, style, lay.bounds, t.xf);
gradient_expands(d, &piece) || stroke.is_some_and(|s| gradient_expands(d, &s))
};
let inline = |gi: usize| lay.inlines.iter().find(|i| i.glyph == gi).is_some_and(|i| t.runs.get(i.run).is_some_and(|r| r.inline.is_some()));
lay.glyphs.iter().enumerate().any(|(gi, g)| !inline(gi) && g.image.is_none() && g.colour.is_none() && expands(g.run, &g.outline))
+6
View File
@@ -54,6 +54,7 @@ pub mod ppi;
pub mod progress;
mod psdlayers;
pub mod psdread;
mod psdslices;
mod pxrread;
mod save;
mod screens;
@@ -93,6 +94,9 @@ pub(crate) use native::preview_png;
pub use native::with_compression_pref;
pub(crate) use pdfimport::opened_page_document;
pub use pdfimport::{LoadOptions, page_document};
pub(crate) use psdlayers::import_active as psd_layers;
pub use psdlayers::{PsdInfo, info as psd_info};
pub(crate) use psdslices::over as psd_slices;
pub(crate) use save::job_for;
pub(crate) use save::save as save_document;
pub use save::{
@@ -240,6 +244,8 @@ mod tests_psd;
mod tests_psdlayers;
#[cfg(test)]
mod tests_psdread;
#[cfg(test)]
mod tests_psdslices;
#[cfg(test)]
mod tests_heifread;
+11 -2
View File
@@ -1,6 +1,6 @@
use super::access::file_list;
use super::formats::formats;
use super::{CommandSpec, action_batch, always, batch, cmd, export, has_doc, has_selection, load, pdfimport, save, screens};
use super::{CommandSpec, action_batch, always, batch, cmd, export, has_doc, has_selection, load, pdfimport, psdlayers, save, screens};
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -9,7 +9,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Open Document",
[],
None,
"{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), importer?: \"plugin.<id>\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), PICT .pct/.pic/.p Line truncated
"{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), importer?: \"plugin.<id>\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size Line truncated
always,
load::open
),
@@ -139,6 +139,15 @@ pub fn specs() -> Vec<CommandSpec> {
always,
pdfimport::pdf_info
),
cmd!(
query "document.psdInfo",
"PSD Info",
[],
None,
"{path} or {name?, dataBase64} what a PSD or PSB file holds, read from its header, slices and layer records without decoding pixels → {format: psd|psb, width, height (the canvas, px), layers (group markers not counted), hiddenLayers (the hidden ones among them), groups, slices (those importSlices brings in; 0 when the file has none or they can't be read)}; a file without layer records, or whose layer records can't be read, has layers: 0 and opens and places as its merged image; a file that is not a PSD or PSB file is an error",
always,
psdlayers::psd_info
),
cmd!(
"document.exportForOffice",
"Save for Office Documents…",
+17 -8
View File
@@ -528,17 +528,26 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
}
// A PSD or PSB file's layers become layers (`layers`, default on); without layers, or with
// `layers: false`, its merged image opens. Layers that can't be read leave the merged image.
"psd" | "psb" if opts.layers => {
let cms = vectorcraft_color::cms::active();
match super::psdlayers::import(bytes, opts.hidden_layers, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)) {
Ok(Some((doc, warnings))) => (doc, warnings, false),
Ok(None) => (raster_doc(&title, bytes)?, vec![], false),
Err(e) => (raster_doc(&title, bytes)?, vec![format!("the layers can't be read ({e}): the file opened as its merged image")], false),
}
}
"psd" | "psb" if opts.layers => match super::psdlayers::import_active(bytes, opts.hidden_layers) {
Ok(Some((doc, warnings))) => (doc, warnings, false),
Ok(None) => (raster_doc(&title, bytes)?, vec![], false),
Err(e) => (raster_doc(&title, bytes)?, vec![format!("the layers can't be read ({e}): the file opened as its merged image")], false),
},
_ if format.raster => (raster_doc(&title, bytes)?, vec![], false),
_ => return Err(err(format!("{} files can't be opened yet", format.label))),
};
// A PSD or PSB file's slices become user slices over its canvas (`importSlices`, default on),
// whether its layers or its merged image came in.
if matches!(format.id, "psd" | "psb")
&& opts.import_slices
&& let Some(canvas) = doc.artboards.first().map(|a| a.rect)
{
let (slices, notes) = super::psd_slices(bytes, canvas);
for (rect, options) in slices {
crate::cmd::slices::add_slice(&mut doc, rect, options);
}
warnings.extend(notes);
}
// A PDF, `.ai` or `.ait` read from its pages or its editing copy, not restored from the document
// it carries, opens with the File Info it gives (a PostScript `.ai` gives none).
if matches!(format.id, "pdf" | "ai" | "ait")
+1 -1
View File
@@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export PDF",
[],
None,
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destinatio Line truncated
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destinatio Line truncated
has_doc,
export_pdf
),
+9 -1
View File
@@ -36,6 +36,8 @@ pub struct LoadOptions {
pub layers: bool,
/// A PSD or PSB file's hidden layers come in, hidden (`hiddenLayers`; else they are left out).
pub hidden_layers: bool,
/// A PSD or PSB file's slices become user slices (`importSlices`; else they are left out).
pub import_slices: bool,
/// How a DXF drawing comes in (the `dxf` param, see [`super::dxfimport`]).
pub dxf: vectorcraft_cad::ImportOptions,
/// An Illustrator EPS or `.ai` that carries the editing copy of its art opens from it (its
@@ -67,6 +69,7 @@ impl Default for LoadOptions {
text_as: TextAs::default(),
layers: true,
hidden_layers: false,
import_slices: true,
dxf: Default::default(),
editing_data: true,
trust_editing_data: false,
@@ -81,7 +84,7 @@ impl LoadOptions {
/// From command params: `pages` (`"2-3, 5"`, a page number or `"all"`), `page` (one page, when
/// `pages` isn't given), `cropTo` (or `crop`), `password`, `colorMode` (`rgb` | `cmyk`) with `grays`,
/// `textAs` (`text` | `outlines`), `layers` (true | false), `hiddenLayers` (true | false),
/// `editingData` (true | false | `always`),
/// `importSlices` (true | false), `editingData` (true | false | `always`),
/// `legacyNameEncoding` (one of [`vectorcraft_eps::NameEncoding::LABELS`]), `linkPages` (true |
/// false) and `dxf` (the DXF import options).
pub fn from_params(cmd: &str, p: &Value) -> Result<Self> {
@@ -111,6 +114,10 @@ impl LoadOptions {
None => false,
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "hiddenLayers must be true or false"))?,
};
let import_slices = match p.get("importSlices").filter(|v| !v.is_null()) {
None => true,
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "importSlices must be true or false"))?,
};
let (editing_data, trust_editing_data) = match p.get("editingData").filter(|v| !v.is_null()) {
None => (true, false),
Some(Value::String(s)) if s.eq_ignore_ascii_case("always") => (true, true),
@@ -137,6 +144,7 @@ impl LoadOptions {
text_as,
layers,
hidden_layers,
import_slices,
dxf,
editing_data,
trust_editing_data,
+64
View File
@@ -43,6 +43,7 @@ use std::cell::Cell;
use std::sync::Arc;
use image::RgbaImage;
use serde_json::{Value, json};
use vectorcraft_color::BlendMode;
use vectorcraft_color::blend::{blend_rgb, composite};
use vectorcraft_color::cms::{Lab, lab::lab_to_srgb};
@@ -51,6 +52,7 @@ use vectorcraft_geom::Affine;
use super::load::{RasterImage, as_png};
use super::psdread::{Header, Reader, byte, header, layer_channel, layer_info, long_key, row_bytes, sample, to_rgb};
use crate::cmd::Session;
use crate::cmd::place::text::mac_roman;
/// Most layer groups inside one another.
@@ -1527,3 +1529,65 @@ pub(super) fn import(
doc.limit_depth_noting(&mut warnings);
Ok(Some((doc, warnings)))
}
/// [`import`] within the memory allowed for one image, CMYK converted with the active color
/// settings: what `document.open` and `file.place` read a PSD or PSB file's layers with.
pub(crate) fn import_active(bytes: &[u8], hidden: bool) -> Result<Option<(Document, Vec<String>)>, String> {
let cms = vectorcraft_color::cms::active();
import(bytes, hidden, super::MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false))
}
/// What a PSD or PSB file holds (`document.psdInfo`, the PSD Import Options dialog).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PsdInfo {
/// The large document format.
pub psb: bool,
/// The canvas, in pixels.
pub width: u32,
pub height: u32,
/// The layers, group markers left out.
pub layers: usize,
/// The layers among them that are hidden.
pub hidden: usize,
/// The layer groups.
pub groups: usize,
/// The slices that come in with `importSlices` (those generated automatically, and those
/// outside the canvas, left out).
pub slices: usize,
}
/// What PSD or PSB file `bytes` holds, read from its header, its slices and its layer records
/// without decoding any pixels. A file without layer records, or whose layer records can't be read, has no layers: it
/// opens and places as its merged image.
pub fn info(bytes: &[u8]) -> Result<PsdInfo, String> {
let mut r = Reader::new(bytes);
let h = header(&mut r)?;
let records = layer_info(h.layers, h.psb).filter(|info| info.len() > 2).and_then(|info| records(info, h.psb).ok()).unwrap_or_default();
let layers = records.iter().filter(|r| r.divider == 0);
Ok(PsdInfo {
psb: h.psb,
width: h.width,
height: h.height,
layers: layers.clone().count(),
hidden: layers.filter(|r| r.hidden).count(),
groups: records.iter().filter(|r| matches!(r.divider, 1 | 2)).count(),
slices: super::psdslices::count(bytes),
})
}
const INFO: &str = "document.psdInfo";
/// `document.psdInfo`.
pub(super) fn psd_info(_: &mut Session, p: &Value) -> crate::cmd::Result<Value> {
let bytes = super::source(p, INFO)?.bytes;
let i = info(&bytes).map_err(super::load::err)?;
Ok(json!({
"format": if i.psb { "psb" } else { "psd" },
"width": i.width,
"height": i.height,
"layers": i.layers,
"hiddenLayers": i.hidden,
"groups": i.groups,
"slices": i.slices,
}))
}
+42 -17
View File
@@ -105,7 +105,7 @@ pub(super) struct Header<'a> {
/// Colour mode data: an indexed image's palette (256 reds, then greens, then blues).
palette: &'a [u8],
/// The image resources.
resources: &'a [u8],
pub(super) resources: &'a [u8],
/// The layer and mask information.
pub(super) layers: &'a [u8],
}
@@ -172,25 +172,50 @@ pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> {
/// The image resource blocks of `resources`, in file order: each one's id, name (the bytes of its
/// Pascal string) and data. Stops at the first block that is cut short. With `signed`, only the
/// blocks whose signature is `8BIM` are given.
fn resources(resources: &[u8], signed: bool) -> impl Iterator<Item = (u16, &[u8], &[u8])> {
pub(super) fn resources(resources: &[u8], signed: bool) -> impl Iterator<Item = (u16, &[u8], &[u8])> {
let mut r = Reader::new(resources);
std::iter::from_fn(move || {
if r.rest().is_empty() {
return None;
std::iter::from_fn(move || if r.rest().is_empty() { None } else { block(&mut r).ok() })
.filter(move |(ours, ..)| *ours || !signed)
.map(|(_, id, name, data)| (id, name, data))
}
/// The data of the first `8BIM` image resource block `id` of `resources`. `None` when there is
/// none before the blocks end or before a block that is cut short ahead of it. An error when
/// that block itself is cut short.
pub(super) fn resource(resources: &[u8], id: u16) -> Result<Option<&[u8]>, String> {
let mut r = Reader::new(resources);
while !r.rest().is_empty() {
match block(&mut r) {
Ok((true, i, _, data)) if i == id => return Ok(Some(data)),
Ok(_) => {}
Err(Some((true, i))) if i == id => return Err(TRUNCATED.into()),
Err(_) => return Ok(None),
}
let ours = r.take(4).ok()? == b"8BIM";
let id = r.u16().ok()?;
}
Ok(None)
}
/// An image resource block: whether its signature is `8BIM`, its id, its name (the bytes of its
/// Pascal string) and its data.
type Block<'a> = (bool, u16, &'a [u8], &'a [u8]);
/// The image resource block that `r` starts with. When it is cut short, the error gives whether
/// its signature is `8BIM` and its id, when those were read.
fn block<'a>(r: &mut Reader<'a>) -> Result<Block<'a>, Option<(bool, u16)>> {
let ours = r.take(4).map_err(|_| None)? == b"8BIM";
let id = r.u16().map_err(|_| None)?;
let mut rest = || -> Result<(&'a [u8], &'a [u8]), String> {
// A Pascal string padded to an even size, length byte included.
let len = usize::from(r.u8().ok()?);
let name = r.take(len).ok()?;
r.take((len + 1) % 2).ok()?;
let size = usize::try_from(r.u32().ok()?).ok()?;
let data = r.take(size).ok()?;
r.take(size % 2).ok()?;
Some((ours, id, name, data))
})
.filter(move |(ours, ..)| *ours || !signed)
.map(|(_, id, name, data)| (id, name, data))
let len = usize::from(r.u8()?);
let name = r.take(len)?;
r.take((len + 1) % 2)?;
let size = usize::try_from(r.u32()?).map_err(|_| TRUNCATED.to_string())?;
let data = r.take(size)?;
r.take(size % 2)?;
Ok((name, data))
};
let (name, data) = rest().map_err(|_| Some((ours, id)))?;
Ok((ours, id, name, data))
}
/// The resource naming the document's clipping path.
+408
View File
@@ -0,0 +1,408 @@
//! The slices a Photoshop document (PSD or PSB) stores, for `document.open` and `file.place`
//! with `importSlices`: image resource 1050, read from the "Slices resource format" of Adobe's
//! public Photoshop File Formats Specification
//! (<https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/>). Version 6 stores the slices
//! as records; versions 7 and 8 store them in a descriptor. The descriptor's keys, and the meaning
//! of the origin, type and background values, are read as the MIT-licensed ag-psd reads them
//! (<https://github.com/Agamnentzar/ag-psd>, `src/imageResources.ts` and `src/descriptor.ts`),
//! which agrees with psd.rb (<https://github.com/layervault/psd.rb>,
//! `lib/psd/resources/slices.rb`) on the keys both read.
//!
//! A slice the file marks as generated automatically is left out: the document lays out its own
//! auto slices around the others. A slice that follows a layer comes in as a user slice over the
//! rectangle the file stores for it. Each slice keeps its name, its type (Image or No Image), its
//! link, target, message, alternative text, cell text and background color; text alignment isn't
//! read. The file is untrusted: every read is checked, and the slice count, the strings and the
//! descriptor's nesting and item count are capped.
use vectorcraft_doc::{SliceKind, SliceOptions};
use vectorcraft_geom::Rect;
use super::psdread::{Reader, TRUNCATED, header, resource};
/// The image resource that holds the slices.
const SLICES: u16 = 1050;
/// The most slices one file brings in.
const MAX_SLICES: usize = 10_000;
/// The deepest descriptor objects and lists nest.
const MAX_DEPTH: usize = 16;
/// The most values the descriptors of one slices resource hold together, nested ones included.
const MAX_VALUES: usize = 200_000;
/// The error of descriptors that hold more than [`MAX_VALUES`].
const TOO_MANY_VALUES: &str = "the slices' descriptor holds too many values";
/// One slice as the file stores it.
#[derive(Clone, Debug, PartialEq)]
struct PsdSlice {
/// Left, top, right and bottom, in the canvas's pixels.
rect: [i64; 4],
options: SliceOptions,
}
/// The slices a file stores, those generated automatically left out, and its canvas.
struct Stored {
slices: Vec<PsdSlice>,
/// The canvas's width and height, in pixels.
size: (u32, u32),
}
/// The slices PSD or PSB file `bytes` stores. `None` when it stores none (no `8BIM` resource 1050
/// before the image resources end, or before a block that is cut short ahead of it). An error when
/// the file isn't a PSD or PSB file, resource 1050 is cut short, or its slices can't be read.
fn read(bytes: &[u8]) -> Result<Option<Stored>, String> {
let mut r = Reader::new(bytes);
let h = header(&mut r)?;
let Some(data) = resource(h.resources, SLICES)? else { return Ok(None) };
Ok(Some(Stored { slices: decode(data)?, size: (h.width, h.height) }))
}
/// The slices of resource 1050's `data`.
fn decode(data: &[u8]) -> Result<Vec<PsdSlice>, String> {
let mut r = Reader::new(data);
// The values every descriptor of the resource may hold together.
let mut budget = MAX_VALUES;
match r.u32()? {
6 => version_6(&mut r, &mut budget),
7 | 8 => {
if r.u32()? != 16 {
return Err("the slices' descriptor has a version other than 16".into());
}
let d = descriptor(&mut r, 0, &mut budget)?;
from_descriptor(&d)
}
v => Err(format!("the slices are stored in version {v}, which isn't read")),
}
}
/// Version 6: the bounds of all the slices, the group's name, the count, then each slice's record.
/// The descriptors that follow the records spend one `budget` of values between them.
fn version_6(r: &mut Reader<'_>, budget: &mut usize) -> Result<Vec<PsdSlice>, String> {
r.take(16)?;
unicode(r)?;
let count = r.u32()? as usize;
if count > MAX_SLICES {
return Err(format!("the file has {count} slices, more than the {MAX_SLICES} read"));
}
let mut out = vec![];
for _ in 0..count {
// The ID and group ID.
r.take(8)?;
let origin = r.u32()?;
// A slice that follows a layer gives the layer's ID.
if origin == 1 {
r.take(4)?;
}
let name = unicode(r)?;
let kind = if r.u32()? == 0 { SliceKind::NoImage } else { SliceKind::Image };
let mut rect = [0i64; 4];
for v in &mut rect {
*v = i64::from(r.u32()? as i32);
}
let (url, target, message, alt) = (unicode(r)?, unicode(r)?, unicode(r)?, unicode(r)?);
let html = r.u8()? != 0;
let cell = unicode(r)?;
// The horizontal and vertical alignment.
r.take(8)?;
let [a, red, green, blue] = r.array::<4>()?;
let background = if a == 0 && red == 0 && green == 0 && blue == 0 {
String::new()
} else if a == 0 {
"matte".into()
} else {
format!("#{red:02x}{green:02x}{blue:02x}")
};
// Photoshop 7 and later may follow a record with a descriptor (version 16); a record that
// doesn't start one is the next slice. A descriptor read that uses up the budget is an
// error.
if r.rest().starts_with(&16u32.to_be_bytes()) {
let mut ahead = Reader::new(r.rest());
ahead.u32()?;
match descriptor(&mut ahead, 0, budget) {
Ok(_) => {
let used = r.rest().len() - ahead.rest().len();
r.take(used)?;
}
Err(e) if e == TOO_MANY_VALUES => return Err(e),
Err(_) => {}
}
}
// Origin 0 is a slice generated automatically.
if origin != 0 {
let options = SliceOptions { kind, name, url, target, message, alt, text: cell_text(cell, html), background, ..Default::default() };
out.push(PsdSlice { rect, options: for_kind(options) });
}
}
Ok(out)
}
/// Versions 7 and 8: the descriptor's `slices` list, each slice an object.
fn from_descriptor(d: &[(String, Value)]) -> Result<Vec<PsdSlice>, String> {
let Some(Value::List(list)) = field(d, "slices") else { return Err("the slices' descriptor has no list of slices".into()) };
if list.len() > MAX_SLICES {
return Err(format!("the file has {} slices, more than the {MAX_SLICES} read", list.len()));
}
let mut out = vec![];
for s in list {
let Value::Object(s) = s else { return Err("the slices' descriptor lists something other than a slice".into()) };
if matches!(field(s, "origin"), Some(Value::Enum(_, v)) if v == "autoGenerated") {
continue;
}
let Some(Value::Object(b)) = field(s, "bounds") else { return Err("a slice in the slices' descriptor has no bounds".into()) };
let edge = |k: &str| number(field(b, k)).ok_or_else(|| "a slice's bounds in the slices' descriptor aren't numbers".to_string());
let rect = [edge("Left")?, edge("Top ")?, edge("Rght")?, edge("Btom")?];
let text = |k: &str| match field(s, k) {
Some(Value::Text(t)) => t.clone(),
_ => String::new(),
};
let kind = if matches!(field(s, "Type"), Some(Value::Enum(_, v)) if v == "noImage") { SliceKind::NoImage } else { SliceKind::Image };
let html = matches!(field(s, "cellTextIsHTML"), Some(Value::Bool(true)));
let background = match field(s, "bgColorType") {
Some(Value::Enum(_, v)) if v == "matte" => "matte".into(),
Some(Value::Enum(_, v)) if v == "Clr " => match field(s, "bgColor") {
Some(Value::Object(c)) => {
let channel = |k: &str| number(field(c, k)).map(|v| v.clamp(0, 255));
match (channel("Rd "), channel("Grn "), channel("Bl ")) {
(Some(r), Some(g), Some(b)) => format!("#{r:02x}{g:02x}{b:02x}"),
_ => String::new(),
}
}
_ => String::new(),
},
_ => String::new(),
};
let options = SliceOptions {
kind,
name: text("Nm "),
url: text("url"),
target: text("null"),
message: text("Msge"),
alt: text("altTag"),
text: cell_text(text("cellText"), html),
background,
..Default::default()
};
out.push(PsdSlice { rect, options: for_kind(options) });
}
Ok(out)
}
/// `o` with only the options of its slice type: an Image slice's cell text isn't shown, and a No
/// Image slice has no link, target, message or alternative text.
fn for_kind(mut o: SliceOptions) -> SliceOptions {
if o.kind == SliceKind::Image {
o.text.clear();
} else {
for s in [&mut o.url, &mut o.target, &mut o.message, &mut o.alt] {
s.clear();
}
}
o
}
/// A cell's text as the HTML a No Image slice shows: plain text has `&`, `<` and `>` escaped.
fn cell_text(text: String, html: bool) -> String {
if html { text } else { text.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;") }
}
/// The longest text one string, key or class ID holds (UTF-16 units or bytes).
const MAX_TEXT: usize = 65_536;
/// An error unless `n`, the length a string or ID declares, is at most [`MAX_TEXT`].
fn text_len(n: usize) -> Result<usize, String> {
if n > MAX_TEXT {
return Err(format!("a text in the slices has more than the {MAX_TEXT} characters read"));
}
Ok(n)
}
/// A Unicode string: a count of UTF-16 units, then the units; trailing NULs dropped.
fn unicode(r: &mut Reader<'_>) -> Result<String, String> {
let n = text_len(r.u32()? as usize)?;
let bytes = r.take(n.checked_mul(2).ok_or(TRUNCATED)?)?;
let units: Vec<u16> = bytes.as_chunks::<2>().0.iter().map(|u| u16::from_be_bytes(*u)).collect();
Ok(String::from_utf16_lossy(&units).trim_end_matches('\0').to_string())
}
/// A descriptor's value, as far as the slices need it.
#[derive(Clone, Debug, PartialEq)]
enum Value {
Long(i32),
Double(f64),
Bool(bool),
Text(String),
/// An enumeration's type and value.
Enum(String, String),
Object(Vec<(String, Value)>),
List(Vec<Value>),
/// A value of another type, read past.
Other,
}
/// The value with key `key`.
fn field<'a>(d: &'a [(String, Value)], key: &str) -> Option<&'a Value> {
d.iter().find(|(k, _)| k == key).map(|(_, v)| v)
}
/// A whole number: a long, or a finite double rounded.
fn number(v: Option<&Value>) -> Option<i64> {
match v? {
Value::Long(n) => Some(i64::from(*n)),
Value::Double(d) if d.is_finite() && d.abs() < 1e12 => Some(d.round() as i64),
_ => None,
}
}
/// A key or class ID: a length, then that many characters, or four when the length is 0.
fn id(r: &mut Reader<'_>) -> Result<String, String> {
let n = text_len(r.u32()? as usize)?;
let b = r.take(if n == 0 { 4 } else { n })?;
Ok(String::from_utf8_lossy(b).into_owned())
}
/// A class: its Unicode name, then its ID.
fn class(r: &mut Reader<'_>) -> Result<(), String> {
unicode(r)?;
id(r)?;
Ok(())
}
/// A descriptor: its class, the count of its items, then each item's key, type and value.
fn descriptor(r: &mut Reader<'_>, depth: usize, budget: &mut usize) -> Result<Vec<(String, Value)>, String> {
if depth > MAX_DEPTH {
return Err("the slices' descriptor nests too deep".into());
}
class(r)?;
let count = r.u32()? as usize;
let mut out = vec![];
for _ in 0..count {
let key = id(r)?;
let kind = r.array::<4>()?;
out.push((key, value(r, &kind, depth, budget)?));
}
Ok(out)
}
/// A value of type `kind`.
fn value(r: &mut Reader<'_>, kind: &[u8; 4], depth: usize, budget: &mut usize) -> Result<Value, String> {
*budget = budget.checked_sub(1).ok_or(TOO_MANY_VALUES)?;
Ok(match kind {
b"long" => Value::Long(r.u32()? as i32),
b"doub" => Value::Double(f64::from_be_bytes(r.array()?)),
b"UntF" => {
r.take(4)?;
Value::Double(f64::from_be_bytes(r.array()?))
}
b"UnFl" => {
r.take(4)?;
Value::Double(f64::from(f32::from_be_bytes(r.array()?)))
}
b"bool" => Value::Bool(r.u8()? != 0),
b"TEXT" => Value::Text(unicode(r)?),
b"enum" => Value::Enum(id(r)?, id(r)?),
b"Objc" | b"GlbO" => Value::Object(descriptor(r, depth + 1, budget)?),
b"VlLs" => {
if depth >= MAX_DEPTH {
return Err("the slices' descriptor nests too deep".into());
}
let count = r.u32()? as usize;
let mut items = vec![];
for _ in 0..count {
let kind = r.array::<4>()?;
items.push(value(r, &kind, depth + 1, budget)?);
}
Value::List(items)
}
b"comp" => {
r.take(8)?;
Value::Other
}
b"type" | b"GlbC" => {
class(r)?;
Value::Other
}
b"tdta" | b"alis" => {
let n = r.u32()? as usize;
r.take(n)?;
Value::Other
}
b"obj " => {
let count = r.u32()? as usize;
for _ in 0..count {
*budget = budget.checked_sub(1).ok_or(TOO_MANY_VALUES)?;
match &r.array::<4>()? {
b"prop" => {
class(r)?;
id(r)?;
}
b"Clss" => class(r)?,
b"Enmr" => {
class(r)?;
id(r)?;
id(r)?;
}
b"rele" => {
class(r)?;
r.take(4)?;
}
b"Idnt" | b"indx" => {
r.take(4)?;
}
b"name" => {
class(r)?;
unicode(r)?;
}
k => return Err(format!("the slices' descriptor has a reference of an unknown kind ({})", String::from_utf8_lossy(k))),
}
}
Value::Other
}
k => return Err(format!("the slices' descriptor has a value of an unknown type ({})", String::from_utf8_lossy(k))),
})
}
/// The slices of PSD or PSB file `bytes` laid over `canvas`, the box its canvas takes (points),
/// each clipped to the canvas, with warnings: for slices that lie wholly outside it or have no
/// size, and for slices that can't be read (the file comes in without them). Empty, without a
/// warning, when the file stores no slices.
pub(crate) fn over(bytes: &[u8], canvas: Rect) -> (Vec<(Rect, SliceOptions)>, Vec<String>) {
match read(bytes) {
Ok(None) => (vec![], vec![]),
Ok(Some(s)) => laid_over(&s.slices, s.size, canvas),
Err(e) => (vec![], vec![format!("the slices can't be read ({e}) and were left out")]),
}
}
/// `slices` of a canvas of `size` pixels laid over `canvas` (points).
fn laid_over(slices: &[PsdSlice], (w, h): (u32, u32), canvas: Rect) -> (Vec<(Rect, SliceOptions)>, Vec<String>) {
let (sx, sy) = (canvas.width() / f64::from(w.max(1)), canvas.height() / f64::from(h.max(1)));
let mut out = vec![];
for s in slices {
let [l, t, r, b] = s.rect;
let (l, r) = (l.clamp(0, i64::from(w)), r.clamp(0, i64::from(w)));
let (t, b) = (t.clamp(0, i64::from(h)), b.clamp(0, i64::from(h)));
if l < r && t < b {
let x = |v: i64| canvas.x0 + v as f64 * sx;
let y = |v: i64| canvas.y0 + v as f64 * sy;
out.push((Rect::new(x(l), y(t), x(r), y(b)), s.options.clone()));
}
}
let warnings = match slices.len() - out.len() {
0 => vec![],
1 => vec!["1 slice lies outside the canvas or has no size and was left out".to_string()],
n => vec![format!("{n} slices lie outside the canvas or have no size and were left out")],
};
(out, warnings)
}
/// How many slices of PSD or PSB file `bytes` come in (`document.psdInfo`): 0 when it stores none
/// or they can't be read.
pub(crate) fn count(bytes: &[u8]) -> usize {
match read(bytes) {
Ok(Some(Stored { slices, size: (w, h) })) => laid_over(&slices, (w, h), Rect::new(0.0, 0.0, f64::from(w), f64::from(h))).0.len(),
_ => 0,
}
}
@@ -38,3 +38,19 @@ fn export_pdf_converts_colours_writes_the_output_intent_and_real_text() {
let bad = s.execute("document.exportPdf", &json!({"output": {"conversion": "destination", "destination": "Missing"}}));
assert!(matches!(bad, Err(crate::EngineError::BadParams { .. })), "{bad:?}");
}
/// Over a saved preset whose Profiles setting is `none`, `"default"` leaves the setting unset,
/// while `null` keeps the preset's value; an unknown value is a bad parameter.
#[test]
fn profiles_default_unsets_a_presets_profiles_setting() {
use vectorcraft_pdf::{PdfPreset, PdfSettings, ProfileInclusion};
let mut settings = PdfSettings::default();
settings.output.profiles = Some(ProfileInclusion::None);
let saved = [PdfPreset { name: "No profiles".into(), description: String::new(), settings }];
let resolve = |output: Value| pdf::resolve("document.exportPdf", &json!({"preset": "No profiles", "output": output}), &saved);
assert_eq!(resolve(json!({"profiles": "default"})).unwrap().output.profiles, None);
assert_eq!(resolve(json!({"profiles": null})).unwrap().output.profiles, Some(ProfileInclusion::None));
assert_eq!(resolve(json!({"profiles": "all"})).unwrap().output.profiles, Some(ProfileInclusion::All));
let bad = resolve(json!({"profiles": "sometimes"}));
assert!(matches!(bad, Err(crate::EngineError::BadParams { .. })), "{bad:?}");
}
+187 -1
View File
@@ -1,7 +1,8 @@
//! Opening PSD and PSB files with their layers as layers (`document.open`'s `layers` and
//! `hiddenLayers`): names, visibility, opacity, blend modes, groups, layer masks, clipped layers
//! and blend modes VectorCraft lacks merged, 16-bit and PSB files, VectorCraft's own PSD export
//! read back, and damaged files read without a panic.
//! read back, and damaged files read without a panic. Placing them with their layers as objects
//! (`file.place`'s `layers` and `hiddenLayers`), and `document.psdInfo`.
use serde_json::{Value, json};
use vectorcraft_color::BlendMode;
@@ -967,10 +968,12 @@ fn damaged_layers_never_panic() {
let mut f = good.clone();
f[i] = v;
let _ = psdlayers::import(&f, true, 1 << 30, cms);
let _ = psdlayers::info(&f);
}
}
for n in 0..good.len() {
let _ = psdlayers::import(&good[..n], true, 1 << 30, cms);
let _ = psdlayers::info(&good[..n]);
}
// A layer past the memory allowed is refused, not read.
assert!(psdlayers::import(&good, true, 64, cms).unwrap_err().contains("too large"));
@@ -1015,3 +1018,186 @@ fn merges_keep_pass_through_groups_blending_with_what_is_below() {
assert!(px.iter().zip([75, 150, 38, 255]).all(|(&a, b)| a.abs_diff(b) <= 1), "{px:?}");
}
}
/// `file.place` of `f` with `p` into a new 100 × 100 pt document, centred on (50, 50).
fn place(f: &[u8], p: Value) -> (Session, crate::cmd::Result<Value>) {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
let r = s.execute("file.place", &merge(json!({"name": "layers.psd", "dataBase64": vectorcraft_format::base64_encode(f), "at": [50, 50]}), p));
(s, r)
}
/// The one object `file.place` placed.
fn placed(s: &Session, r: &Value) -> Node {
let id = vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap());
s.doc().unwrap().doc.node(id).unwrap().clone()
}
#[test]
fn placing_with_layers_embeds_the_layers_as_one_group() {
let f = file(8, 8, &stack(), 8, false, false);
let (mut s, r) = place(&f, json!({"layers": true}));
let r = r.unwrap();
assert_eq!((&r["format"], &r["linked"], &r["warnings"]), (&json!("psd"), &json!(false), &json!([HIDDEN_1])), "{r}");
let g = placed(&s, &r);
assert!(matches!(g.kind, NodeKind::Group { clip: false, .. }), "one group, unclipped: its layers lie on the canvas");
assert_eq!(name(&g), "layers.psd");
let kids = g.children().unwrap();
assert_eq!(kids.iter().map(|c| name(c)).collect::<Vec<_>>(), ["Bottom", "Folder", "Screens", "Faded"], "bottom first");
// A layer is its image, where the merged image would put it: the 8 pt canvas centred on (50, 50).
let ((x, y), px) = pixels_of(&s, &kids[0]);
assert_eq!(((x, y), px.dimensions(), px.get_pixel(3, 3).0), ((46.0, 46.0), (8, 8), [255, 0, 0, 255]));
// A group is a group of its layers; a pass-through group isn't isolated, another mode's is.
let folder = &kids[1];
assert!(matches!(folder.kind, NodeKind::Group { .. }) && !folder.isolate && folder.blend == BlendMode::Normal);
let inner = folder.children().unwrap();
assert_eq!(inner.iter().map(|c| name(c)).collect::<Vec<_>>(), ["Inner A"], "the hidden layer is left out");
assert!(matches!(inner[0].kind, NodeKind::Image(_)) && inner[0].blend == BlendMode::Multiply && (inner[0].opacity - 128.0 / 255.0).abs() < 1e-6);
let screens = &kids[2];
assert!(screens.isolate && screens.blend == BlendMode::Screen);
let ((x, y), px) = pixels_of(&s, &screens.children().unwrap()[0]);
assert_eq!(((x, y), px.get_pixel(0, 0).0), ((48.0, 48.0), [10, 20, 30, 128]));
assert!((kids[3].opacity - 102.0 / 255.0).abs() < 1e-6, "fill opacity: {}", kids[3].opacity);
// One undo step.
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.layers.iter().all(|l| l.children().is_none_or(Vec::is_empty)));
// Hidden layers come in hidden when asked for.
let (s, r) = place(&f, json!({"layers": true, "hiddenLayers": true}));
let r = r.unwrap();
assert_eq!(r["warnings"], json!([]), "{r}");
let g = placed(&s, &r);
let inner: Vec<(&str, bool)> = g.children().unwrap()[1].children().unwrap().iter().map(|c| (name(c), c.visible)).collect();
assert_eq!(inner, [("Inner A", true), ("Inner B", false)]);
// Without `layers`, the merged image, in the same box.
let (s, r) = place(&f, json!({}));
let r = r.unwrap();
let flat = placed(&s, &r);
let ((x, y), px) = pixels_of(&s, &flat);
assert_eq!(((x, y), px.dimensions(), px.get_pixel(0, 0).0), ((46.0, 46.0), (8, 8), [128, 128, 128, 255]), "{r}");
}
#[test]
fn placed_layers_keep_their_masks_and_are_clipped_to_the_canvas() {
let mut masked = layer("Masked", [0, 0, 8, 8], [255, 255, 255, 255]);
masked.mask = Some(([2, 2, 4, 4], 0, 0, vec![255, 128, 0, 255]));
let (s, r) = place(&file(8, 8, &[masked], 8, false, false), json!({"layers": true}));
let g = placed(&s, &r.unwrap());
let kids = g.children().unwrap();
assert!(matches!(kids[0].kind, NodeKind::Image(_)), "the layer is its image");
let m = kids[0].extras().mask.as_deref().expect("the layer mask as the image's opacity mask");
let ((x, y), px) = pixels_of(&s, &m.art);
assert_eq!(((x, y), px.dimensions(), m.clip), ((48.0, 48.0), (2, 2), true), "the mask moves with its layer");
// A layer that reaches past the canvas: the group is clipped to the canvas, as the merged
// image shows only the canvas.
let over = layer("Over", [-2, -2, 6, 6], [0, 255, 0, 255]);
let (s, r) = place(&file(8, 8, &[layer("Bottom", [0, 0, 8, 8], [255, 0, 0, 255]), over], 8, false, false), json!({"layers": true}));
let r = r.unwrap();
let g = placed(&s, &r);
assert!(matches!(g.kind, NodeKind::Group { clip: true, .. }), "{r}");
let kids = g.children().unwrap();
let b = kids[0].geometric_bounds_with(&s.doc().unwrap().doc.symbol_boxes()).unwrap();
assert!(matches!(kids[0].kind, NodeKind::Path { clipping: true, .. }));
assert_eq!((b.x0, b.y0, b.x1, b.y1), (46.0, 46.0, 54.0, 54.0), "the clipping path is the canvas");
assert_eq!(kids[1..].iter().map(|c| name(c)).collect::<Vec<_>>(), ["Bottom", "Over"]);
assert_eq!(pixels_of(&s, &kids[2]).0, (44.0, 44.0));
// A hidden layer that reaches past the canvas clips the group too, so showing it later draws
// only the canvas. Left out, it doesn't.
let mut hidden = layer("Hidden", [-2, -2, 6, 6], [0, 255, 0, 255]);
hidden.hidden = true;
let f = file(8, 8, &[layer("Bottom", [0, 0, 8, 8], [255, 0, 0, 255]), hidden], 8, false, false);
let (s, r) = place(&f, json!({"layers": true, "hiddenLayers": true}));
let r = r.unwrap();
let g = placed(&s, &r);
assert!(matches!(g.kind, NodeKind::Group { clip: true, .. }), "{r}");
assert_eq!(g.children().unwrap()[1..].iter().map(|c| (name(c), c.visible)).collect::<Vec<_>>(), [("Bottom", true), ("Hidden", false)]);
let (s, r) = place(&f, json!({"layers": true}));
assert!(matches!(placed(&s, &r.unwrap()).kind, NodeKind::Group { clip: false, .. }));
}
#[test]
fn placing_with_layers_never_links_and_refuses_values_it_cant_use() {
let f = file(8, 8, &stack(), 8, false, false);
let dir = std::env::temp_dir().join(format!("vc-psd-place-layers-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("layers.psd");
std::fs::write(&path, &f).unwrap();
let from_path = |p: Value| {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
let r = s.execute("file.place", &merge(json!({"path": path.to_str().unwrap()}), p));
(s, r)
};
// From a path, `layers` embeds: `link` is then false unless given, and `link: true` is refused.
let (s, r) = from_path(json!({"layers": true}));
let r = r.unwrap();
assert_eq!(r["linked"], json!(false), "{r}");
assert!(matches!(placed(&s, &r).kind, NodeKind::Group { .. }));
let (s, r) = from_path(json!({"layers": true, "link": true}));
assert!(r.unwrap_err().to_string().contains("a linked PSD file is placed as its flat image"));
assert!(s.doc().unwrap().doc.layers.iter().all(|l| l.children().is_none_or(Vec::is_empty)), "nothing is placed");
// Without `layers` the file is linked as before.
let (s, r) = from_path(json!({}));
let r = r.unwrap();
assert_eq!(r["linked"], json!(true), "{r}");
assert!(matches!(placed(&s, &r).kind, NodeKind::Image(_)));
// A file without layers is embedded as its merged image, without a warning.
let flat = {
let mut f = file(2, 2, &[layer("x", [0, 0, 2, 2], [9, 9, 9, 255])], 8, false, false);
let at = 26 + 8;
let len = u32::from_be_bytes(f[at..at + 4].try_into().unwrap()) as usize;
f.splice(at..at + 4 + len, 0u32.to_be_bytes());
f
};
std::fs::write(&path, &flat).unwrap();
let (s, r) = from_path(json!({"layers": true}));
let r = r.unwrap();
assert_eq!((&r["linked"], &r["warnings"]), (&json!(false), &json!([])), "{r}");
assert!(matches!(placed(&s, &r).kind, NodeKind::Image(_)));
// Layers that are all left out: the merged image, with the importer's warnings.
let mut gone = layer("Gone", [0, 0, 2, 2], [9, 9, 9, 255]);
gone.hidden = true;
let (s, r) = place(&file(2, 2, &[gone], 8, false, false), json!({"layers": true}));
let r = r.unwrap();
assert_eq!((&r["linked"], r["warnings"].as_array().map(Vec::len)), (&json!(false), Some(1)), "{r}");
assert!(matches!(placed(&s, &r).kind, NodeKind::Image(_)));
// Layers that can't be read: the merged image, with a warning.
let mut cut = file(4, 4, &[layer("x", [0, 0, 4, 4], [9, 9, 9, 255])], 8, false, false);
let at = cut.windows(4).position(|w| w == [0, 0, 0, 18]).unwrap();
cut[at..at + 4].copy_from_slice(&1000u32.to_be_bytes());
let (s, r) = place(&cut, json!({"layers": true}));
let r = r.unwrap();
assert!(r["warnings"][0].as_str().unwrap().starts_with("the layers can't be read"), "{r}");
assert!(matches!(placed(&s, &r).kind, NodeKind::Image(_)));
// Values the command can't use are errors, and nothing is placed.
for (p, why) in [
(json!({"hiddenLayers": true}), "hiddenLayers applies to a PSD file placed with layers: true"),
(json!({"layers": true, "link": true}), "a linked PSD file is placed as its flat image"),
(json!({"layers": "yes"}), "layers must be true or false"),
(json!({"layers": true, "hiddenLayers": 1}), "hiddenLayers must be true or false"),
] {
let (s, r) = place(&f, p.clone());
assert!(r.unwrap_err().to_string().contains(why), "{p}");
assert!(s.doc().unwrap().doc.layers.iter().all(|l| l.children().is_none_or(Vec::is_empty)), "{p}");
}
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let q = s.execute("file.place.queue", &json!({"paths": [path.to_str().unwrap()], "layers": "yes"}));
assert!(q.unwrap_err().to_string().contains("`layers` must be true or false"));
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn psd_info_counts_the_layers_without_opening_the_file() {
let mut s = Session::new();
let info = |s: &mut Session, f: &[u8]| s.execute("document.psdInfo", &json!({"dataBase64": vectorcraft_format::base64_encode(f)}));
let r = info(&mut s, &file(8, 8, &stack(), 8, false, false)).unwrap();
assert_eq!(r, json!({"format": "psd", "width": 8, "height": 8, "layers": 5, "hiddenLayers": 1, "groups": 2, "slices": 0}));
let r = info(&mut s, &file(4, 2, &[layer("x", [0, 0, 2, 2], [9, 9, 9, 255])], 16, true, true)).unwrap();
assert_eq!((&r["format"], &r["width"], &r["height"], &r["layers"]), (&json!("psb"), &json!(4), &json!(2), &json!(1)), "{r}");
// Layer records that can't be read count as no layers: the file opens as its merged image.
let mut cut = file(4, 4, &[layer("x", [0, 0, 4, 4], [9, 9, 9, 255])], 8, false, false);
let at = cut.windows(4).position(|w| w == [0, 0, 0, 18]).unwrap();
cut[at..at + 4].copy_from_slice(&1000u32.to_be_bytes());
assert_eq!(info(&mut s, &cut).unwrap()["layers"], json!(0));
assert!(info(&mut s, b"not a psd").unwrap_err().to_string().contains("not a PSD file"));
}
@@ -0,0 +1,482 @@
//! A PSD or PSB file's slices (image resource 1050) opened and placed as user slices
//! (`document.open`'s and `file.place`'s `importSlices`): version 6 records and version 7 and 8
//! descriptors, built from the Photoshop File Formats Specification's "Slices resource format";
//! their options, slices outside the canvas, damaged or unknown slice data, placing scaled and
//! moved in one undo step, linked files, and `document.psdInfo`'s count.
use serde_json::{Value, json};
use vectorcraft_doc::{SliceKind, SliceOptions};
use vectorcraft_geom::Rect;
use crate::Session;
/// A Unicode string: a count of UTF-16 units, then the units.
fn ustr(s: &str) -> Vec<u8> {
let units: Vec<u16> = s.encode_utf16().collect();
let mut b = (units.len() as u32).to_be_bytes().to_vec();
b.extend(units.iter().flat_map(|u| u.to_be_bytes()));
b
}
/// One version 6 slice record.
#[derive(Clone)]
struct S {
/// 0: generated automatically, 1: follows a layer, 2: made by the user.
origin: u32,
name: &'static str,
/// 0: No Image, 1: Image.
kind: u32,
/// Left, top, right, bottom (px).
rect: [i32; 4],
url: &'static str,
target: &'static str,
message: &'static str,
alt: &'static str,
html: bool,
cell: &'static str,
/// Alpha, red, green, blue.
argb: [u8; 4],
}
fn user(name: &'static str, rect: [i32; 4]) -> S {
S { origin: 2, name, kind: 1, rect, url: "", target: "", message: "", alt: "", html: false, cell: "", argb: [0; 4] }
}
/// Resource 1050 in version 6, each record followed by `trailing` (a Photoshop 7 descriptor, or
/// nothing).
fn v6(slices: &[S], trailing: &[u8]) -> Vec<u8> {
let mut b = 6u32.to_be_bytes().to_vec();
b.extend([0u8; 16]);
b.extend(ustr("group"));
b.extend((slices.len() as u32).to_be_bytes());
for (i, s) in slices.iter().enumerate() {
b.extend((i as u32 + 1).to_be_bytes());
b.extend(0u32.to_be_bytes());
b.extend(s.origin.to_be_bytes());
if s.origin == 1 {
b.extend(7u32.to_be_bytes());
}
b.extend(ustr(s.name));
b.extend(s.kind.to_be_bytes());
for v in s.rect {
b.extend(v.to_be_bytes());
}
for t in [s.url, s.target, s.message, s.alt] {
b.extend(ustr(t));
}
b.push(u8::from(s.html));
b.extend(ustr(s.cell));
b.extend([0u8; 8]);
b.extend(s.argb);
b.extend(trailing);
}
b
}
/// A descriptor value.
enum D {
Long(i32),
Doub(f64),
Bool(bool),
Text(&'static str),
Enum(&'static str, &'static str),
Obj(Vec<(&'static str, D)>),
List(Vec<D>),
}
/// A key or class ID: a four-character one with length 0, else its length and characters.
fn key(k: &str) -> Vec<u8> {
let mut b = if k.len() == 4 { 0u32 } else { k.len() as u32 }.to_be_bytes().to_vec();
b.extend(k.as_bytes());
b
}
/// A descriptor: an empty class name, the class ID, the count, then each item.
fn descriptor(items: &[(&str, D)]) -> Vec<u8> {
let mut b = ustr("");
b.extend(key("null"));
b.extend((items.len() as u32).to_be_bytes());
for (k, v) in items {
b.extend(key(k));
b.extend(value(v));
}
b
}
/// A value's type, then the value.
fn value(v: &D) -> Vec<u8> {
let mut b = vec![];
match v {
D::Long(n) => {
b.extend(b"long");
b.extend(n.to_be_bytes());
}
D::Doub(d) => {
b.extend(b"doub");
b.extend(d.to_be_bytes());
}
D::Bool(on) => {
b.extend(b"bool");
b.push(u8::from(*on));
}
D::Text(t) => {
b.extend(b"TEXT");
b.extend(ustr(t));
}
D::Enum(t, e) => {
b.extend(b"enum");
b.extend(key(t));
b.extend(key(e));
}
D::Obj(items) => {
b.extend(b"Objc");
b.extend(descriptor(items));
}
D::List(items) => {
b.extend(b"VlLs");
b.extend((items.len() as u32).to_be_bytes());
for i in items {
b.extend(value(i));
}
}
}
b
}
/// A bounds object: top, left, bottom and right.
fn bounds(l: i32, t: i32, r: i32, b: i32) -> D {
D::Obj(vec![("Top ", D::Long(t)), ("Left", D::Long(l)), ("Btom", D::Long(b)), ("Rght", D::Long(r))])
}
/// Resource 1050 in `version` 7 or 8 holding `slices`.
fn v7(version: u32, slices: Vec<D>) -> Vec<u8> {
let mut b = version.to_be_bytes().to_vec();
b.extend(16u32.to_be_bytes());
b.extend(descriptor(&[("bounds", bounds(0, 0, 20, 20)), ("baseName", D::Text("poster")), ("slices", D::List(slices))]));
b
}
/// A 20 × 20 px PSD file written by `document.export`, with its layers (two) or flat.
fn psd(layers: bool) -> Vec<u8> {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 20, "height": 20})).unwrap();
s.execute("paint.setFill", &json!({ "color": "#ff0000" })).unwrap();
s.execute("shape.rectangle", &json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap();
s.execute("layer.new", &json!({ "name": "Top" })).unwrap();
s.execute("shape.rectangle", &json!({"x": 8, "y": 8, "width": 10, "height": 10})).unwrap();
let r = s.execute("document.export", &json!({"format": "psd", "layers": layers})).unwrap();
vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap()
}
/// `psd` with image resource `id` holding `data` added to its image resources.
fn with_resource(psd: &[u8], id: u16, data: &[u8]) -> Vec<u8> {
let u32_at = |at: usize| u32::from_be_bytes(psd[at..at + 4].try_into().unwrap()) as usize;
let colors = 26 + 4 + u32_at(26);
let len = u32_at(colors);
let mut block = b"8BIM".to_vec();
block.extend(id.to_be_bytes());
block.extend([0, 0]);
block.extend((data.len() as u32).to_be_bytes());
block.extend(data);
block.resize(block.len().next_multiple_of(2), 0);
let mut out = psd[..colors].to_vec();
out.extend(((len + block.len()) as u32).to_be_bytes());
out.extend(&psd[colors + 4..colors + 4 + len]);
out.extend(block);
out.extend(&psd[colors + 4 + len..]);
out
}
fn b64(f: &[u8]) -> String {
vectorcraft_format::base64_encode(f)
}
fn open(f: &[u8], extra: Value) -> (Session, Value) {
let mut s = Session::new();
let mut p = json!({"name": "poster.psd", "dataBase64": b64(f)});
for (k, v) in extra.as_object().unwrap() {
p[k] = v.clone();
}
let r = s.execute("document.open", &p).unwrap();
(s, r)
}
/// The document's user slices: rectangle and options.
fn slices(s: &Session) -> Vec<(Rect, SliceOptions)> {
s.doc().unwrap().doc.slices.iter().map(|x| (x.rect, x.options.clone())).collect()
}
fn warnings(r: &Value) -> Vec<String> {
r["warnings"].as_array().map(|a| a.iter().filter_map(|w| w.as_str().map(str::to_string)).collect()).unwrap_or_default()
}
#[test]
fn version_6_slices_open_as_user_slices_with_their_options() {
let linked = S { origin: 1, url: "https://example.com/", target: "_blank", message: "Go", alt: "Logo", ..user("logo", [2, 4, 10, 8]) };
let plain = S { kind: 0, cell: "a < b & c", argb: [0, 0, 0, 0], ..user("note", [10, 10, 20, 20]) };
let html = S { kind: 0, html: true, cell: "<b>Hi</b>", argb: [255, 0x12, 0x34, 0x56], ..user("", [0, 12, 6, 18]) };
let matte = S { argb: [0, 1, 2, 3], cell: "ignored", ..user("matte", [12, 0, 18, 6]) };
let auto = S { origin: 0, ..user("auto", [0, 0, 20, 2]) };
let data = v6(&[linked, plain, html, matte, auto], &[]);
for layers in [true, false] {
let f = with_resource(&psd(layers), 1050, &data);
// Either conversion brings the slices in; the automatic one stays out.
for p in [json!({}), json!({"layers": false})] {
let (s, r) = open(&f, p);
assert!(warnings(&r).is_empty(), "{r}");
let got = slices(&s);
assert_eq!(got.len(), 4, "{got:?}");
assert_eq!(got[0].0, Rect::new(2.0, 4.0, 10.0, 8.0));
assert_eq!(
got[0].1,
SliceOptions {
kind: SliceKind::Image,
name: "logo".into(),
url: "https://example.com/".into(),
target: "_blank".into(),
message: "Go".into(),
alt: "Logo".into(),
..Default::default()
}
);
// Plain cell text is escaped as the HTML a No Image cell shows; HTML stays as it is.
assert_eq!((got[1].1.kind, got[1].1.text.as_str(), got[1].1.background.as_str()), (SliceKind::NoImage, "a &lt; b &amp; c", ""));
assert_eq!((got[2].1.text.as_str(), got[2].1.background.as_str(), got[2].1.name.as_str()), ("<b>Hi</b>", "#123456", ""));
// An Image slice's cell text isn't kept; a background with no alpha is the matte.
assert_eq!((got[3].1.text.as_str(), got[3].1.background.as_str()), ("", "matte"));
// Web output lays them out with auto slices around them.
let layout = s.doc().unwrap().doc.slice_layout();
assert_eq!(layout.iter().filter(|a| a.source == vectorcraft_doc::SliceSource::User).count(), 4);
assert!(layout.iter().any(|a| a.source == vectorcraft_doc::SliceSource::Auto));
}
}
}
#[test]
fn photoshop_7_descriptors_after_version_6_records_are_read_past() {
let trailing = [16u32.to_be_bytes().to_vec(), descriptor(&[("topOutset", D::Long(0))])].concat();
let f = with_resource(&psd(false), 1050, &v6(&[user("a", [0, 0, 5, 5]), user("b", [5, 5, 10, 10])], &trailing));
let (s, r) = open(&f, json!({}));
assert!(warnings(&r).is_empty(), "{r}");
let names: Vec<String> = slices(&s).into_iter().map(|(_, o)| o.name).collect();
assert_eq!(names, ["a", "b"]);
}
#[test]
fn version_6_descriptors_share_one_budget_of_values() {
// Each record's descriptor holds 2,501 values, well under the 200,000 one descriptor may hold;
// 100 of them hold 250,100 together.
let list = D::List((0..2_500).map(D::Long).collect());
let trailing = [16u32.to_be_bytes().to_vec(), descriptor(&[("many", list)])].concat();
let records: Vec<S> = (0..100).map(|_| user("a", [0, 0, 5, 5])).collect();
// Alone, one such descriptor is read past.
let (s, r) = open(&with_resource(&psd(false), 1050, &v6(&records[..1], &trailing)), json!({}));
assert!(warnings(&r).is_empty(), "{r}");
assert_eq!(slices(&s).len(), 1);
// Together they are refused, and the file opens without slices.
let (s, r) = open(&with_resource(&psd(false), 1050, &v6(&records, &trailing)), json!({}));
let w = warnings(&r);
assert!(w.iter().any(|w| w.starts_with("the slices can't be read (") && w.contains("too many values")), "{w:?}");
assert!(slices(&s).is_empty());
}
#[test]
fn version_7_and_8_descriptors_open_as_user_slices() {
let slice = |origin: &'static str, kind: &'static str, l: i32, t: i32, r: i32, b: i32| {
D::Obj(vec![
("sliceID", D::Long(1)),
("groupID", D::Long(0)),
("origin", D::Enum("ESliceOrigin", origin)),
("Type", D::Enum("ESliceType", kind)),
("bounds", bounds(l, t, r, b)),
("Nm ", D::Text("cell")),
("url", D::Text("https://example.com/")),
("null", D::Text("_top")),
("Msge", D::Text("msg")),
("altTag", D::Text("alt")),
("cellTextIsHTML", D::Bool(false)),
("cellText", D::Text("x>y")),
("bgColorType", D::Enum("ESliceBGColorType", "Clr ")),
("bgColor", D::Obj(vec![("Rd ", D::Doub(255.0)), ("Grn ", D::Doub(128.0)), ("Bl ", D::Long(0))])),
])
};
for version in [7, 8] {
let data = v7(
version,
vec![slice("userGenerated", "Img ", 1, 2, 9, 10), slice("autoGenerated", "Img ", 0, 0, 20, 1), slice("layer", "noImage", 10, 10, 15, 15)],
);
let (s, r) = open(&with_resource(&psd(true), 1050, &data), json!({}));
assert!(warnings(&r).is_empty(), "{r}");
let got = slices(&s);
assert_eq!(got.len(), 2, "{got:?}");
assert_eq!(got[0].0, Rect::new(1.0, 2.0, 9.0, 10.0));
assert_eq!(
got[0].1,
SliceOptions {
name: "cell".into(),
url: "https://example.com/".into(),
target: "_top".into(),
message: "msg".into(),
alt: "alt".into(),
background: "#ff8000".into(),
..Default::default()
}
);
assert_eq!((got[1].1.kind, got[1].1.text.as_str(), got[1].1.url.as_str()), (SliceKind::NoImage, "x&gt;y", ""));
}
}
#[test]
fn import_slices_false_leaves_them_out_and_must_be_a_switch() {
let f = with_resource(&psd(true), 1050, &v6(&[user("a", [0, 0, 5, 5])], &[]));
let (s, _) = open(&f, json!({"importSlices": false}));
assert!(slices(&s).is_empty());
let mut s = Session::new();
let e = s.execute("document.open", &json!({"name": "poster.psd", "dataBase64": b64(&f), "importSlices": "yes"})).unwrap_err();
assert!(e.to_string().contains("importSlices must be true or false"), "{e}");
}
#[test]
fn slices_that_cant_be_read_warn_and_the_file_still_opens() {
let good = v6(&[user("a", [0, 0, 5, 5])], &[]);
let mut bad_descriptor = v7(7, vec![]);
bad_descriptor[4..8].copy_from_slice(&15u32.to_be_bytes());
let cases: Vec<(Vec<u8>, &str)> = vec![
(good[..good.len() - 3].to_vec(), "cut short"),
([9u32.to_be_bytes().to_vec(), good[4..].to_vec()].concat(), "version 9"),
(bad_descriptor, "version other than 16"),
// The count follows the version, the bounds and the group's name.
([&good[..34], &u32::MAX.to_be_bytes()[..], &good[38..]].concat(), "more than the 10000 read"),
(v7(8, vec![D::Long(3)]), "other than a slice"),
// A whole record whose name is longer than a slice's text may be.
(v6(&[user("a".repeat(65_537).leak(), [0, 0, 5, 5])], &[]), "more than the 65536 characters read"),
];
for (data, why) in cases {
for layers in [true, false] {
let (s, r) = open(&with_resource(&psd(layers), 1050, &data), json!({}));
let w = warnings(&r);
assert!(w.iter().any(|w| w.starts_with("the slices can't be read (") && w.contains(why)), "{why}: {w:?}");
assert!(slices(&s).is_empty());
// The art still came in.
assert!(s.doc().unwrap().doc.art_bounds().is_some(), "{why}");
}
}
// A name of the longest length read comes in.
let longest = v6(&[user("a".repeat(65_536).leak(), [0, 0, 5, 5])], &[]);
let (s, r) = open(&with_resource(&psd(false), 1050, &longest), json!({}));
assert!(warnings(&r).is_empty(), "{r}");
assert_eq!(slices(&s).first().map(|(_, o)| o.name.len()), Some(65_536));
// A file without slices opens without a word about them.
let (s, r) = open(&psd(true), json!({}));
assert!(warnings(&r).is_empty() && slices(&s).is_empty(), "{r}");
}
#[test]
fn a_slices_resource_cut_short_warns_and_the_file_still_opens() {
let good = v6(&[user("a", [0, 0, 5, 5])], &[]);
// Image resource `id`, the last of the image resources, declares 10 bytes more than they hold.
let cut = |layers: bool, id: u16, data: &[u8]| {
let mut f = with_resource(&psd(layers), id, data);
let sig = [&b"8BIM"[..], &id.to_be_bytes()].concat();
let at = f.windows(6).rposition(|w| w == sig.as_slice()).unwrap() + 8;
f[at..at + 4].copy_from_slice(&(data.len() as u32 + 10).to_be_bytes());
f
};
for layers in [true, false] {
let (s, r) = open(&cut(layers, 1050, &good), json!({}));
let w = warnings(&r);
assert!(w.iter().any(|w| w.starts_with("the slices can't be read (") && w.contains("cut short")), "{w:?}");
assert!(slices(&s).is_empty());
assert!(s.doc().unwrap().doc.art_bounds().is_some());
// Another resource cut short says nothing about slices.
let (s, r) = open(&cut(layers, 1051, &[0, 1]), json!({}));
assert!(warnings(&r).is_empty() && slices(&s).is_empty(), "{r}");
}
}
#[test]
fn slices_are_clipped_to_the_canvas_and_those_outside_it_are_left_out() {
let data = v6(&[user("over", [-5, -5, 5, 30]), user("out", [25, 0, 30, 5]), user("empty", [4, 4, 4, 9]), user("in", [1, 1, 2, 2])], &[]);
let (s, r) = open(&with_resource(&psd(false), 1050, &data), json!({}));
assert_eq!(warnings(&r), ["2 slices lie outside the canvas or have no size and were left out"]);
let got: Vec<(Rect, String)> = slices(&s).into_iter().map(|(r, o)| (r, o.name)).collect();
assert_eq!(got, [(Rect::new(0.0, 0.0, 5.0, 20.0), "over".to_string()), (Rect::new(1.0, 1.0, 2.0, 2.0), "in".to_string())]);
}
#[test]
fn placed_embedded_files_bring_their_slices_with_the_art_in_one_undo_step() {
let data = v6(&[user("a", [0, 0, 10, 10]), user("b", [10, 10, 20, 20])], &[]);
for layers in [false, true] {
let f = with_resource(&psd(layers), 1050, &data);
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
// Fitted into a 40 pt square at (100, 60): twice the size.
let r = s.execute("file.place", &json!({"name": "poster.psd", "dataBase64": b64(&f), "rect": [100, 60, 40, 40], "layers": layers})).unwrap();
assert_eq!(r["slices"].as_array().map(Vec::len), Some(2), "{r}");
let got: Vec<Rect> = slices(&s).into_iter().map(|(r, _)| r).collect();
assert_eq!(got, [Rect::new(100.0, 60.0, 120.0, 80.0), Rect::new(120.0, 80.0, 140.0, 100.0)]);
// The placed art stays selected, and one undo takes the art and the slices away.
assert_eq!(s.doc().unwrap().selection.objects.len(), 1);
s.execute("edit.undo", &json!({})).unwrap();
assert!(slices(&s).is_empty());
assert!(s.doc().unwrap().doc.art_bounds().is_none());
// Centered on `at` at 100%.
s.execute("file.place", &json!({"name": "poster.psd", "dataBase64": b64(&f), "at": [100, 100], "layers": layers})).unwrap();
assert_eq!(slices(&s)[0].0, Rect::new(90.0, 90.0, 100.0, 100.0));
// `importSlices: false` places the art alone.
let r = s.execute("file.place", &json!({"name": "poster.psd", "dataBase64": b64(&f), "importSlices": false, "layers": layers})).unwrap();
assert!(r.get("slices").is_none());
assert_eq!(slices(&s).len(), 2);
}
}
#[test]
fn linked_files_are_placed_without_their_slices() {
let dir = std::env::temp_dir().join(format!("vc-psd-slices-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("poster.psd");
std::fs::write(&path, with_resource(&psd(false), 1050, &v6(&[user("a", [0, 0, 5, 5])], &[]))).unwrap();
let path = path.to_string_lossy().into_owned();
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
let r = s.execute("file.place", &json!({ "path": path })).unwrap();
assert_eq!((&r["linked"], r.get("slices")), (&json!(true), None));
assert!(slices(&s).is_empty());
let e = s.execute("file.place", &json!({ "path": path, "importSlices": true })).unwrap_err();
assert!(e.to_string().contains("importSlices: a linked PSD file is placed as its flat image"), "{e}");
// Embedded from its path, they come in.
let r = s.execute("file.place", &json!({ "path": path, "link": false })).unwrap();
assert_eq!((&r["linked"], r["slices"].as_array().map(Vec::len)), (&json!(false), Some(1)));
// file.place.info counts what a place would bring in.
let info = s.execute("file.place.info", &json!({ "path": path, "link": false })).unwrap();
assert_eq!(info["slices"], json!(1));
let info = s.execute("file.place.info", &json!({ "path": path })).unwrap();
assert_eq!(info["slices"], json!(0));
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn psd_info_counts_the_slices_that_come_in() {
let mut s = Session::new();
let info = |s: &mut Session, f: &[u8]| s.execute("document.psdInfo", &json!({"dataBase64": b64(f)})).unwrap();
let data = v6(&[user("a", [0, 0, 5, 5]), S { origin: 0, ..user("auto", [5, 5, 20, 20]) }, user("out", [30, 30, 40, 40])], &[]);
assert_eq!(info(&mut s, &with_resource(&psd(false), 1050, &data))["slices"], json!(1));
assert_eq!(info(&mut s, &with_resource(&psd(true), 1050, &data[..data.len() - 4]))["slices"], json!(0));
assert_eq!(info(&mut s, &psd(true))["slices"], json!(0));
}
#[test]
fn damaged_slices_never_panic() {
let data = v7(8, vec![D::Obj(vec![("origin", D::Enum("ESliceOrigin", "userGenerated")), ("bounds", bounds(0, 0, 5, 5))])]);
let base = with_resource(&psd(false), 1050, &data);
let start = base.windows(data.len()).position(|w| w == data).unwrap();
for at in (start - 12..start + data.len()).step_by(3) {
for v in [0u8, 0x7f, 0xff] {
let mut f = base.clone();
f[at] = v;
let mut s = Session::new();
let _ = s.execute("document.open", &json!({"name": "poster.psd", "dataBase64": b64(&f)}));
let _ = s.execute("document.psdInfo", &json!({"dataBase64": b64(&f)}));
}
}
}
+40 -5
View File
@@ -10,9 +10,10 @@ use vectorcraft_color::Paint;
use vectorcraft_doc::{AppearanceItem, Document, Node, NodeId, NodeKind, TextKind, TextObject, TextRun};
use vectorcraft_geom::Rect;
use super::panelcmds::listed_artboards;
use super::select::on_artboard;
use super::typecmd::refresh_bounds;
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, index, str_param};
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, str_param};
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -39,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Select Text by Font",
[],
None,
"{family, style?, scope?: \"document\" (default) | {artboards: [index, …] (0-based)} | {layers: [id, …] (layers or sublayers)}} select the text objects using the font, the instances of the symbols whose art uses it, the text whose inline graphics draw such a symbol, the objects painted with a pattern whose art uses it (by a visible fill or stroke whose opacity is above 0, a stroke wider than 0) and the objects whose opacity mask uses it (in type that is not hidden or locked in that art), that are not hidden or locked, in a hidden or locked group or layer, or on a locked artboard; a pattern swatch that nothing paints, or a layer's mask, selects nothing; with scope, only those on one of the artboards (as All on Active Artboard takes them: their bounds overlap it or their center is on it) or in one of the layers → {count}",
"{family, style?, scope?: \"document\" (default) | {artboards: [index, …] (0-based whole numbers)} | {layers: [id, …] (layers or sublayers)}} select the text objects using the font, the instances of the symbols whose art uses it, the text whose inline graphics draw such a symbol, the objects painted with a pattern whose art uses it (by a visible fill or stroke whose opacity is above 0, a stroke wider than 0) and the objects whose opacity mask uses it (in type that is not hidden or locked in that art), that are not hidden or locked, in a hidden or locked group or layer, or on a locked artboard; a pattern swatch that nothing paints, or a layer's mask, selects nothing; with scope, only those on one of the artboards (as All on Active Artboard takes them: their bounds overlap it or their center is on it) or in one of the layers → {count}",
has_doc,
select_font
),
@@ -1080,9 +1081,9 @@ impl FontScope {
Some(_) => Err(bad(C, format!("`scope.{key}` must be a non-empty array"))),
}
};
if let Some(a) = list("artboards")? {
let rect = |v: &Value| v.as_u64().and_then(|i| d.artboards.get(index(i))).map(|b| b.rect);
return a.iter().map(|v| rect(v).ok_or_else(|| bad(C, format!("no such artboard {v}")))).collect::<Result<_>>().map(Self::Artboards);
if let (Some(v), Some(_)) = (scope.get("artboards"), list("artboards")?) {
let indices = listed_artboards(d, v, "scope.artboards", C)?;
return Ok(Self::Artboards(indices.into_iter().filter_map(|i| d.artboards.get(i)).map(|b| b.rect).collect()));
}
if let Some(a) = list("layers")? {
let layer = |v: &Value| v.as_u64().map(NodeId).filter(|id| d.node(*id).is_some_and(Node::is_layer));
@@ -1292,6 +1293,40 @@ mod tests {
}
}
/// Select Text by Font refuses a `scope.artboards` entry that is not a whole number, naming the
/// parameter, before it looks at the artboards, and leaves the selection as it was; a whole
/// number past the last artboard is `no such artboard`.
#[test]
fn select_font_refuses_artboards_that_are_not_whole_numbers() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
s.execute("artboard.new", &json!({"x": 300, "y": 0, "width": 200, "height": 200})).unwrap();
let text = |s: &mut Session, x: i32| {
NodeId(s.execute("text.create", &json!({"x": x, "y": 50, "text": "Serif", "font": "Source Serif 4"})).unwrap()["id"].as_u64().unwrap())
};
let first = text(&mut s, 10);
let second = text(&mut s, 350);
let run =
|s: &mut Session, artboards: Value| s.execute("select.font", &json!({"family": "Source Serif 4", "scope": {"artboards": artboards}}));
let malformed = "invalid parameters for `select.font`: `scope.artboards` must contain whole numbers";
for (artboards, want) in [
(json!(["1"]), malformed),
(json!([-1]), malformed),
(json!([1.5]), malformed),
(json!([true]), malformed),
(json!([null]), malformed),
(json!([9, "1"]), malformed),
(json!([9]), "no such artboard"),
(json!([1, 9]), "no such artboard"),
] {
s.execute("select.set", &json!({"ids": [first.0]})).unwrap();
assert_eq!(run(&mut s, artboards.clone()).unwrap_err().to_string(), want, "{artboards}");
assert_eq!(s.doc().unwrap().selection.objects, [first], "{artboards}");
}
run(&mut s, json!([1, 1])).unwrap();
assert_eq!(s.doc().unwrap().selection.objects, [second]);
}
/// Select Text by Font with a layer scope takes the text in the layers, their sublayers
/// included, and still leaves out hidden and locked text.
#[test]
+36
View File
@@ -1109,6 +1109,42 @@ fn aligned_effect_indices_past_the_end_of_a_graph_designs_art_are_refused() {
assert!(rows(&s, mark).effects.is_empty());
}
/// With a graph design's art given first and `aligned: true`, `effect.remove` and `effect.duplicate` with `indices` are an
/// error and change nothing when one of the art's effects is one no other object has, as with that index given alone.
#[test]
fn aligned_effect_indices_of_a_graph_designs_art_that_no_object_has_are_refused() {
let rows = |s: &Session, id: NodeId| (*s.doc().unwrap().doc.node(id).unwrap().appearance).clone();
let (mut s, _, art, mark) = aligned_design_art();
// The art has a shadow and a roughen, the mark the shadow only.
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [mark.0], "item": null})).unwrap();
s.execute("effect.apply", &json!({"effect": "distort.roughen", "ids": [mark.0], "item": null})).unwrap();
s.edit("Effects", |d, _| {
let effects = d.node(mark).unwrap().appearance.effects.clone();
d.node_mut(art).unwrap().appearance.effects = effects;
d.node_mut(mark).unwrap().appearance.effects.pop();
Ok(())
})
.unwrap();
let (art_was, mark_was) = (rows(&s, art), rows(&s, mark));
let steps = s.doc().unwrap().history.undo.len();
for cmd in ["effect.remove", "effect.duplicate"] {
assert!(s.execute(cmd, &json!({"ids": [art.0, mark.0], "item": null, "index": 1, "aligned": true})).is_err(), "{cmd}");
let e = s.execute(cmd, &json!({"ids": [art.0, mark.0], "item": null, "indices": [0, 1], "aligned": true})).unwrap_err();
assert!(e.to_string().contains("no effects at indices 0, 1"), "{cmd}: {e}");
assert_eq!((rows(&s, art), rows(&s, mark)), (art_was.clone(), mark_was.clone()), "{cmd}");
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{cmd}");
}
// With the roughen on the mark too, both of its effects are removed.
s.edit("Roughen", |d, _| {
let roughen = d.node(art).unwrap().appearance.effects[1].clone();
d.node_mut(mark).unwrap().appearance.effects.push(roughen);
Ok(())
})
.unwrap();
s.execute("effect.remove", &json!({"ids": [art.0, mark.0], "item": null, "indices": [0, 1], "aligned": true})).unwrap();
assert!(rows(&s, mark).effects.is_empty());
}
/// A blur on a series group makes the whole group an image, which draws the design's art with the series' other art:
/// Expand Appearance does not put the art back beside the image.
#[test]
+16 -9
View File
@@ -555,9 +555,15 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
let ids = super::graph::paint_targets(&s.doc()?.doc, &selected);
let of = super::appearance::reference_of(s, p, item, cmd)?;
let paint = if span {
// With a design's art, the gradient spans only the objects with a row equal to the art's, which take it.
let spanned: Vec<NodeId> = ids.iter().zip(item.per_target_of(s, of, &ids)).filter_map(|(id, it)| it.map(|_| *id)).collect();
placed_across(&s.doc()?.doc, &spanned, paint, p, fill)
// With a design's art, the gradient spans only the objects with a row equal to the art's, which take it. Each
// object's box is that of the row it edits.
let d = &s.doc()?.doc;
let mut spanned = Vec::with_capacity(ids.len());
for (id, it) in ids.iter().zip(item.per_target_of(s, of, &ids)) {
let (Some(it), Some(n)) = (it, d.node(*id)) else { continue };
spanned.push((*id, it.resolve(&n.appearance, fill, cmd)?));
}
placed_across(d, &spanned, paint, p, fill)
} else {
paint
};
@@ -730,14 +736,15 @@ fn spans_targets(p: &Value, paint: &Paint) -> std::result::Result<bool, String>
Ok(true)
}
/// `paint` placed once on the union of the bounds of `ids` (each one's fill box, or the box its
/// stroke paints), at the gradient's angle and aspect: every target gets the same vector in
/// document coordinates, so the ramp runs on across them (#2127).
fn placed_across(d: &Document, ids: &[NodeId], paint: Paint, p: &Value, fill: bool) -> Paint {
/// `paint` placed once on the union of the bounds of `ids` (each one's fill box, or the box the
/// stroke it edits paints: the row given with it, `None` for the topmost), at the gradient's angle
/// and aspect: every target gets the same vector in document coordinates, so the ramp runs on
/// across them (#2127).
fn placed_across(d: &Document, ids: &[(NodeId, Option<usize>)], paint: Paint, p: &Value, fill: bool) -> Paint {
let union = ids
.iter()
.filter_map(|id| d.node(*id))
.filter_map(|n| item_paint_bounds(n, None, fill).or_else(|| n.geometric_bounds()))
.filter_map(|(id, index)| Some((d.node(*id)?, *index)))
.filter_map(|(n, index)| item_paint_bounds(n, index, fill).or_else(|| n.geometric_bounds()))
.filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()))
.reduce(|a, b| a.union(b));
let (Some(union), Paint::Gradient(g)) = (union, &paint) else { return paint };
+11 -3
View File
@@ -67,7 +67,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Character / Paragraph",
[],
None,
"{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"yakumonoHankaku\"|\"gyomatsuYakumonoHankaku\"|\"gyomatsuYakumonoZenkaku\"|\"yakumonoZenkaku\"|\"lineEndHalf\" (Mojikumi Set: Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tent Line truncated
"{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"yakumonoHankaku\"|\"gyomatsuYakumonoHankaku\"|\"gyomatsuYakumonoZenkaku\"|\"yakumonoZenkaku\"|\"lineEndHalf\" (Mojikumi Set: Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tent Line truncated
has_doc,
set_format
),
@@ -255,7 +255,7 @@ pub(crate) fn artboard_indices(d: &vectorcraft_doc::Document, p: &Value, cmd: &s
/// list of artboard indices", and a list with an entry that is not a whole number is "`{key}` must
/// contain whole numbers"; a whole number past the last artboard is `no such artboard`. Every entry
/// is checked for its form before any is checked against the artboards.
fn listed_artboards(d: &vectorcraft_doc::Document, v: &Value, key: &str, cmd: &str) -> Result<Vec<usize>> {
pub(crate) fn listed_artboards(d: &vectorcraft_doc::Document, v: &Value, key: &str, cmd: &str) -> Result<Vec<usize>> {
let entries = v.as_array().ok_or_else(|| bad(cmd, format!("`{key}` must be a list of artboard indices")))?;
if entries.is_empty() {
return Err(bad(cmd, format!("`{key}` must be a non-empty list of artboard indices")));
@@ -614,6 +614,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
"akiLeft",
"akiRight",
"tsume",
"diacriticHorizontal",
"diacriticVertical",
"standardVerticalRoman",
"noBreak",
"digits",
@@ -645,7 +647,9 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
Some(v) => Some(match v.as_str() {
Some("singleLine") => Composer::SingleLine,
Some("everyLine") => Composer::EveryLine,
_ => return Err(bad(C, "composer must be \"singleLine\" or \"everyLine\"")),
Some("standardSingleLine") => Composer::StandardSingleLine,
Some("standardEveryLine") => Composer::StandardEveryLine,
_ => return Err(bad(C, "composer must be \"singleLine\", \"everyLine\", \"standardSingleLine\" or \"standardEveryLine\"")),
}),
};
let (position, small_caps) = super::docsetup::script_params(p, &s.doc()?.doc.setup, C)?;
@@ -661,6 +665,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
let aki_left = super::textedit::aki_param(p, "akiLeft", C)?;
let aki_right = super::textedit::aki_param(p, "akiRight", C)?;
let tsume = super::textedit::tsume_param(p, C)?;
let diacritic_horizontal = super::textedit::diacritic_param(p, "diacriticHorizontal", C)?;
let diacritic_vertical = super::textedit::diacritic_param(p, "diacriticVertical", C)?;
let warichu_lines = super::textedit::warichu_lines_param(p, C)?;
let warichu_gap = super::textedit::warichu_number_param(p, "warichuGap", C)?;
let warichu_scale = super::textedit::warichu_number_param(p, "warichuScale", C)?;
@@ -851,6 +857,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(v) = tsume {
st.tsume = v;
}
st.diacritic_horizontal = diacritic_horizontal.unwrap_or(st.diacritic_horizontal);
st.diacritic_vertical = diacritic_vertical.unwrap_or(st.diacritic_vertical);
if let Some(v) = flag("standardVerticalRoman") {
st.standard_vertical_roman = v;
}
+6
View File
@@ -369,6 +369,12 @@ pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()>
{
return Err(bad(id, "`origin` must be [x, y] in points"));
}
if effect == vectorcraft_render::effects::SVG_FILTER
&& let Some(axes) = given.get("axes")
&& vectorcraft_render::effects::svg_filter::valid_axes(axes).is_none()
{
return Err(bad(id, "`axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0"));
}
// Its name is the filter's id.
if effect == vectorcraft_render::effects::SVG_FILTER && given.contains_key("name") && !given.contains_key("xml") {
return Err(bad(id, "an SVG filter is named by its id: give `xml` with `name`"));
+19 -15
View File
@@ -5,7 +5,7 @@ use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Scaling, Selection};
use vectorcraft_geom::{Anchor, AnchorKind, PathData, Point, SubPath, Vec2};
use vectorcraft_geom::{Anchor, AnchorKind, Anchors, PathData, Point, SubPath, Vec2};
use super::create::anchor_from_json;
use super::draw2::usize_opt;
@@ -544,10 +544,12 @@ fn merge_coincident(sp: &mut SubPath, picked: impl Fn(usize) -> bool, join_kind:
&& before > 2
&& picked(0)
&& picked(before - 1)
&& let [first, .., last] = sp.anchors.as_mut_slice()
&& same(first, last)
&& let (Some(&first), Some(&last)) = (sp.anchors.first(), sp.anchors.last())
&& same(&first, &last)
{
first.h_in = last.h_in;
if let Some(first) = sp.anchors.first_mut() {
first.h_in = last.h_in;
}
sp.anchors.pop();
if let Some(smooth) = join_kind {
join_point(sp, 0, smooth);
@@ -565,10 +567,12 @@ fn merge_coincident(sp: &mut SubPath, picked: impl Fn(usize) -> bool, join_kind:
for i in (1..len).rev() {
if picked(i - 1)
&& picked(i)
&& let Some([a, b]) = anchors.get_mut(i - 1..=i)
&& same(a, b)
&& let (Some(&a), Some(&b)) = (anchors.get(i - 1), anchors.get(i))
&& same(&a, &b)
{
a.h_out = b.h_out;
if let Some(a) = anchors.get_mut(i - 1) {
a.h_out = b.h_out;
}
if let Some(slot) = gone.get_mut(i) {
*slot = true;
}
@@ -603,7 +607,7 @@ fn merge_coincident(sp: &mut SubPath, picked: impl Fn(usize) -> bool, join_kind:
}
/// [`join_point`] on anchor `ai` of `anchors` with its neighbors given by index.
fn join_point_between(anchors: &mut [Anchor], ai: usize, prev: Option<usize>, next: Option<usize>, smooth: bool) {
fn join_point_between(anchors: &mut Anchors, ai: usize, prev: Option<usize>, next: Option<usize>, smooth: bool) {
let at = |j: Option<usize>| j.and_then(|j| anchors.get(j)).map(|a| a.p);
let (prev, next) = (at(prev), at(next));
if let Some(a) = anchors.get_mut(ai) {
@@ -1565,7 +1569,7 @@ enum Stretch {
/// anchor, so the two handles of a smooth anchor stay in line with it. That share is below 0 or
/// above 1 for a handle long enough beside the span. A closed subpath with no anchor that stays
/// moves whole when it has a focal point.
fn stretch_weights(anchors: &[Anchor], closed: bool, roles: &[Stretch]) -> Vec<[f64; 3]> {
fn stretch_weights(anchors: &Anchors, closed: bool, roles: &[Stretch]) -> Vec<[f64; 3]> {
let n = anchors.len();
let mut shares = vec![[0.0; 3]; n];
let role = |i: usize| match roles.get(i) {
@@ -1891,10 +1895,10 @@ mod tests {
&& before > 2
&& picked(0)
&& picked(before - 1)
&& let [first, .., last] = sp.anchors.as_mut_slice()
&& same(first, last)
&& let (Some(&first), Some(&last)) = (sp.anchors.first(), sp.anchors.last())
&& same(&first, &last)
{
first.h_in = last.h_in;
sp.anchors[0].h_in = last.h_in;
sp.anchors.pop();
if let Some(smooth) = join_kind {
join_point(sp, 0, smooth);
@@ -1903,10 +1907,10 @@ mod tests {
for i in (1..sp.anchors.len()).rev() {
if picked(i - 1)
&& picked(i)
&& let Some([a, b]) = sp.anchors.get_mut(i - 1..=i)
&& same(a, b)
&& let (Some(&a), Some(&b)) = (sp.anchors.get(i - 1), sp.anchors.get(i))
&& same(&a, &b)
{
a.h_out = b.h_out;
sp.anchors[i - 1].h_out = b.h_out;
sp.anchors.remove(i);
if let Some(smooth) = join_kind {
join_point(sp, i - 1, smooth);
+150 -16
View File
@@ -4,6 +4,10 @@
//! - A raster image becomes one image at 100% of its physical size: its pixels at the resolution
//! the file declares ([`fileio::ppi`]; 72 ppi when it declares none), linked to its file with
//! `link` ([`super::links`]).
//! - A PSD or PSB file placed with `layers` becomes one group of its layers as objects, embedded
//! ([`fileio::psd_layers`]); otherwise it is an image like any other, its merged image. An
//! embedded one brings its slices in as user slices, placed with its art (`importSlices`,
//! [`fileio::psd_slices`]).
//! - An SVG becomes one group of its art; so does a DXF drawing, read with the DXF options
//! (`dxf`, [`fileio::dxfimport`]), and an HP-GL plot file (`vectorcraft_cad::hpgl`).
//! - An EMF, WMF or PICT picture becomes one group, clipped to its frame (`crop: "crop"`) or
@@ -45,7 +49,7 @@ use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::Paint;
use vectorcraft_doc::{Appearance, Document, ImageObject, LinkInfo, Node, NodeId, NodeKind, PageBox, Scaling, SymbolBoxes};
use vectorcraft_doc::{Appearance, Document, ImageObject, LinkInfo, Node, NodeId, NodeKind, PageBox, Scaling, SliceOptions, SymbolBoxes};
use vectorcraft_geom::{Affine, Point, Rect, shapes};
use vectorcraft_pdf::CropTo;
@@ -75,7 +79,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Place…",
["File"],
Some("Cmd+Shift+P"),
"{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf and a PDF with several pages or a password and no page ask for those options first; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed",
"{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives Line truncated
has_doc,
place
),
@@ -84,7 +88,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Placed File Info",
[],
None,
"{path | name | dataBase64 (a file's path, or its name with its bytes), page?, crop?, password?, thumbnail?: px, link?: bool, dxf?: {…} (both as file.place)} what file.place would place, without placing it → {name, format, width, height (pt at 100%), pixelWidth?, pixelHeight?, ppi?: [x, y], colorMode?: RGB|Grayscale|CMYK (raster images), plates?: [ink names] (a DCS file), warnings, thumbnailBase64?: PNG of at most `thumbnail` (≤ 512) px on its longer side}",
"{path | name | dataBase64 (a file's path, or its name with its bytes), page?, crop?, password?, thumbnail?: px, link?: bool, dxf?: {…}, layers?, hiddenLayers?, importSlices? (all as file.place)} what file.place would place, without placing it → {name, format, width, height (pt at 100%), pixelWidth?, pixelHeight?, ppi?: [x, y], colorMode?: RGB|Grayscale|CMYK (raster images), plates?: [ink names] (a DCS file), slices?: the user slices a PSD or PSB file would bring in, warnings, thumbnailBase64?: PNG of at most `thumbnail` (≤ 512) px on its longer side}",
always,
info
),
@@ -102,7 +106,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Load Place Cursor",
[],
None,
"{paths?: [path…], files?: [{name, dataBase64}…], link?, template?, page?, crop?, text?, dxf?, thumbnail?: px} load the place cursor (the `place` tool) with up to 100 files (as file.place reads them): a click places the current file at 100% with its top-left corner there, a drag places it at the dragged size (aspect kept), ←/→ and ↑/↓ cycle the files, Esc discards the current one; each placement is a file.place, and the previous tool returns after the last → {count, files: [{name, format, width, height, thumbnailBase64?}], skipped: [{name, error}]}",
"{paths?: [path…], files?: [{name, dataBase64}…], link?, template?, page?, crop?, text?, dxf?, layers?, hiddenLayers?, importSlices?, thumbnail?: px} load the place cursor (the `place` tool) with up to 100 files (as file.place reads them): a click places the current file at 100% with its top-left corner there, a drag places it at the dragged size (aspect kept), ←/→ and ↑/↓ cycle the files, Esc discards the current one; each placement is a file.place, and the previous tool returns after the last → {count, files: [{name, format, width, height, thumbnailBase64?}], skipped: [{name, error}]}",
has_doc,
queue
),
@@ -148,16 +152,33 @@ struct Loaded {
board: Option<Rect>,
}
/// A PSD or PSB file's slices, embedded with `importSlices`: their rectangles over the natural box
/// of its art, and their options.
type Slices = Vec<(Rect, SliceOptions)>;
/// Points per pixel of a raster image at the resolution it declares (72 ppi when none).
pub(crate) fn pt_per_px(ppi: Option<(f64, f64)>) -> (f64, f64) {
let (x, y) = ppi.unwrap_or((72.0, 72.0));
(72.0 / x, 72.0 / y)
}
/// [`load_sliced`] without the slices.
fn load(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool) -> Result<Loaded> {
load_into(p, cmd, board, link_pdf, &mut vec![])
}
/// [`load_into`], with the slices of a PSD or PSB file that `importSlices` brings in.
fn load_sliced(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool) -> Result<(Loaded, Slices)> {
let mut slices = vec![];
let l = load_into(p, cmd, board, link_pdf, &mut slices)?;
Ok((l, slices))
}
/// The file `p` names, read into placeable art; a DXF drawing's Fit to Artboard fills `board`
/// (unless the params name their own box). A PDF/.ai page read from a path is placed linked with
/// Link when `link_pdf` (false for the queries, which read it embedded).
fn load(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool) -> Result<Loaded> {
/// Link when `link_pdf` (false for the queries, which read it embedded). A PSD or PSB file's slices
/// go to `slices`.
fn load_into(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool, slices_out: &mut Slices) -> Result<Loaded> {
let src = fileio::source(p, cmd)?;
let name = fileio::file_name(src.name);
// An Affinity file is recognised by its signature, whatever its name says.
@@ -237,12 +258,52 @@ fn load(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool) -> Result<Loa
let art = Art::Vector { src: Box::new(a.doc), nodes: a.nodes, clip: a.clip };
return Ok(Loaded { name, format, art, natural: a.frame, warnings: a.warnings, link: None, board: None });
}
// A PSD or PSB file placed with `layers`: its layers as objects, never linked. One without
// layers, or whose layers can't be read, is embedded as its merged image.
let (mut embed, mut unread) = (false, vec![]);
let mut slices_from = None;
if matches!(format.id, "psd" | "psb") {
let layers = switch_or(p, "layers", false, cmd)?;
if switch_or(p, "hiddenLayers", false, cmd)? && !layers {
return Err(bad(cmd, "hiddenLayers applies to a PSD file placed with layers: true"));
}
// Slices come in with an embedded file (default on); a linked file shows its flat image.
let linked = !layers && src.path.is_some() && bool_or(p, "link", true);
let slices = switch_or(p, "importSlices", !linked, cmd)?;
if slices && linked {
return Err(bad(cmd, "importSlices: a linked PSD file is placed as its flat image; give link: false to embed it with its slices"));
}
if slices {
slices_from = Some(&src.bytes[..]);
}
if layers {
// Layers are embedded: a link shows the file's flat image.
if switch_or(p, "link", false, cmd)? {
return Err(bad(cmd, "layers: a linked PSD file is placed as its flat image; leave link out or give link: false"));
}
embed = true;
match fileio::psd_layers(&src.bytes, opts.hidden_layers) {
Ok(Some((doc, mut warnings))) => match psd_groups(doc) {
Some((art, natural)) => {
*slices_out = psd_slices(slices_from, natural, &mut warnings);
return Ok(Loaded { name, format, art, natural, warnings, link: None, board: None });
}
// No layer has art: the merged image, embedded.
None => unread = warnings,
},
// No layers: the merged image, embedded.
Ok(None) => {}
Err(e) => unread.push(format!("the layers can't be read ({e}): the file was placed as its merged image")),
}
}
}
if format.raster {
let img = fileio::raster_image(&src.bytes)?;
let (sx, sy) = pt_per_px(img.ppi);
let natural = Rect::new(0.0, 0.0, img.width as f64 * sx, img.height as f64 * sy);
let link = src.path.map(|path| super::links::link_info(path, &src.bytes));
let warnings = fileio::size_note(&img.blob.bytes).into_iter().collect();
let link = src.path.filter(|_| !embed).map(|path| super::links::link_info(path, &src.bytes));
let mut warnings: Vec<String> = unread.into_iter().chain(fileio::size_note(&img.blob.bytes)).collect();
*slices_out = psd_slices(slices_from, natural, &mut warnings);
let clip = fileio::psdread::clipping_path(&src.bytes);
return Ok(Loaded { name, format, art: Art::Image(img, clip), natural, warnings, link, board: None });
}
@@ -303,6 +364,56 @@ fn load(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool) -> Result<Loa
Ok(Loaded { name, format, art: Art::Vector { src: Box::new(doc), nodes, clip }, natural, warnings, link: None, board })
}
/// A PSD or PSB file's layers, read as `document.open` reads them into `doc`, as art to place: an
/// image for each layer and a group for each layer group, bottom first, with the layer's name,
/// visibility, opacity, blend mode and opacity mask. The art's natural box is the file's canvas,
/// where the merged image would lie, and the art is clipped to the canvas when layers reach past it.
/// None when no layer brought any art in.
fn psd_groups(mut doc: Document) -> Option<(Art, Rect)> {
let canvas = doc.artboards.first()?.rect;
let nodes = psd_objects(&std::mem::take(&mut doc.layers));
// Hidden layers count too: showing one later must not draw past the canvas.
let symbols = doc.symbol_boxes();
let reached = nodes.iter().fold(None, |acc, n| vectorcraft_geom::union_opt(acc, reach(&symbols, n)))?;
let past = reached.union(canvas) != canvas;
Some((Art::Vector { src: Box::new(doc), nodes, clip: past.then_some(canvas) }, canvas))
}
/// The slices of the PSD or PSB file `bytes` (none without it) laid over `canvas`, the natural box
/// of its art; their warnings go to `warnings`.
fn psd_slices(bytes: Option<&[u8]>, canvas: Rect, warnings: &mut Vec<String>) -> Slices {
let Some(bytes) = bytes else { return vec![] };
let (slices, notes) = fileio::psd_slices(bytes, canvas);
warnings.extend(notes);
slices
}
/// The bounds of `n` and every object inside it, hidden ones included.
fn reach(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
match n.children() {
Some(kids) => kids.iter().fold(None, |acc, k| vectorcraft_geom::union_opt(acc, reach(symbols, k))),
None => n.geometric_bounds_with(symbols),
}
}
/// The layers a PSD import made as objects: a layer of sublayers as a group of them, and a layer
/// holding one image as that image, each with the layer's name, visibility, opacity, blend mode,
/// isolation and opacity mask.
fn psd_objects(layers: &[Arc<Node>]) -> Vec<Node> {
layers
.iter()
.map(|l| {
let mut n = (**l).clone();
let NodeKind::Layer { children, .. } = &l.kind else { return n };
n.kind = match &children[..] {
[c] if matches!(c.kind, NodeKind::Image(_)) => c.kind.clone(),
_ => NodeKind::Group { children: psd_objects(children).into_iter().map(Arc::new).collect(), clip: false },
};
n
})
.collect()
}
/// Page `page` (1-based) of the PDF/.ai/.ait file `src` (`bytes`, read from `path` when there is
/// one) as art to place: clipped to the box `opts.crop` names, or (`bounding`) the bounds of its
/// art; read with `opts.password`. Only the page placed is read. A .ai saved without PDF
@@ -548,6 +659,7 @@ pub struct PlaceJob {
pub struct PlaceRead {
job: PlaceJob,
loaded: Loaded,
slices: Slices,
}
impl PlaceJob {
@@ -562,7 +674,7 @@ impl PlaceJob {
/// the renderers' image store for the first frame that draws them
/// ([`super::links::readable_and_kept`]).
pub fn read(self) -> Result<PlaceRead> {
let mut loaded = load(&self.params, PLACE, self.target, true)?;
let (mut loaded, slices) = load_sliced(&self.params, PLACE, self.target, true)?;
let linked = loaded.link.is_some() && bool_or(&self.params, "link", true);
match &mut loaded.art {
Art::Image(img, _) => {
@@ -572,7 +684,7 @@ impl PlaceJob {
Art::Dcs(a) => a.img.blob = super::links::readable(a.img.blob.clone(), false, true)?,
_ => {}
}
Ok(PlaceRead { job: self, loaded })
Ok(PlaceRead { job: self, loaded, slices })
}
}
@@ -653,7 +765,7 @@ fn prepare(s: &Session, p: &Value) -> Result<PlaceJob> {
/// Place the file `read` holds in the active document.
fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
let PlaceRead { job: PlaceJob { params, old, target: read_for, .. }, mut loaded } = read;
let PlaceRead { job: PlaceJob { params, old, target: read_for, .. }, mut loaded, slices: read_slices } = read;
let p = &params;
let template = bool_or(p, "template", false);
let at = at_param(p)?;
@@ -699,7 +811,22 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
if let Art::Dcs(a) = &loaded.art {
warnings.extend(dcs::swatch_notes(&st.doc, &a.spots));
}
let (id, size) = s.edit("Place", |d, sel| {
// A PSD file's slices move and scale with its art; one that would leave the canvas is left out.
let read_count = read_slices.len();
let slices: Slices = read_slices
.into_iter()
.filter_map(|(r, o)| {
let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x0, r.y1), Point::new(r.x1, r.y1)].map(|c| m * c);
let placed = corners.iter().skip(1).fold(Rect::from_points(corners[0], corners[0]), |acc, c| acc.union_pt(*c));
super::slices::slice_rect_ok(placed).then_some((placed, o))
})
.collect();
match read_count - slices.len() {
0 => {}
1 => warnings.push("1 slice would lie outside the canvas and was left out".into()),
n => warnings.push(format!("{n} slices would lie outside the canvas and were left out")),
}
let (id, size, slice_ids) = s.edit("Place", |d, sel| {
let node = transformed(build(d, loaded, link), m);
let size = node.geometric_bounds_with(&d.symbol_boxes()).unwrap_or_default();
let (into, index) = match old {
@@ -712,15 +839,19 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
None => (parent, usize::MAX),
};
let id = d.insert(into, index, node)?;
let slice_ids: Vec<u64> = slices.into_iter().map(|(r, o)| super::slices::add_slice(d, r, o).0).collect();
// Template art is locked: nothing to select.
if template {
sel.clear()
} else {
sel.set([id])
}
Ok((id, size))
Ok((id, size, slice_ids))
})?;
let mut out = json!({ "ids": [id.0], "name": name, "format": format, "linked": linked, "width": size.width(), "height": size.height(), "warnings": warnings });
if !slice_ids.is_empty() {
out["slices"] = json!(slice_ids);
}
// A DCS, PSD or PSB file clipped by its clipping path: its image, which the Links commands
// take.
if file_clipped {
@@ -824,7 +955,7 @@ fn read_queue(doc: u64, p: Value, queued: Vec<Value>) -> Result<QueueRead> {
let thumbnail = p.get("thumbnail").and_then(Value::as_f64);
let (mut entries, mut files, mut skipped) = (vec![], vec![], vec![]);
for mut q in queued {
for k in ["link", "template", "page", "crop", "text", "dxf"] {
for k in ["link", "template", "page", "crop", "text", "dxf", "layers", "hiddenLayers", "importSlices"] {
if let Some(v) = p.get(k) {
q[k] = v.clone();
}
@@ -870,7 +1001,7 @@ impl Session {
/// desktop the Place dialog's OK with several files does this off the UI thread).
pub fn prepare_place_queue(&self, params: &Value) -> Result<QueueJob> {
has_doc(self).map_err(|why| EngineError::Disabled(QUEUE.into(), why))?;
check_switches(params, &["link", "template"], QUEUE)?;
check_switches(params, &["link", "template", "layers", "hiddenLayers", "importSlices"], QUEUE)?;
check_numbers(params, &["thumbnail"], QUEUE)?;
let files = queued_files(params)?;
Ok(QueueJob { doc: self.doc()?.uid, params: params.clone(), files })
@@ -948,7 +1079,7 @@ pub fn read_info(p: &Value) -> Result<Value> {
check_switches(p, &["link"], "file.place.info")?;
check_numbers(p, &["thumbnail"], "file.place.info")?;
// A PDF/.ai page linked or not has the same size and art.
let mut l = load(p, "file.place.info", None, false)?;
let (mut l, slices) = load_sliced(p, "file.place.info", None, false)?;
let natural = l.natural;
let mut out = json!({
"name": l.name,
@@ -957,6 +1088,9 @@ pub fn read_info(p: &Value) -> Result<Value> {
"height": natural.height(),
"warnings": std::mem::take(&mut l.warnings),
});
if matches!(l.format.id, "psd" | "psb") {
out["slices"] = json!(slices.len());
}
if let Art::Image(img, _) = &l.art {
let (x, y) = img.ppi.unwrap_or((72.0, 72.0));
out["pixelWidth"] = json!(img.width);
@@ -40,6 +40,9 @@ pub(super) const ALLOWED: &[&str] = &[
"addon.image.colorMask",
"addon.image.removeBackground",
"addon.image.removeColorMask",
"addon.packaging.roles",
"addon.packaging.setRole",
"addon.packaging.setRoleSwatch",
"addon.pathtools.addPoints",
"addon.pathtools.close",
"addon.pathtools.corner",
+3 -1
View File
@@ -486,7 +486,9 @@ fn imaged(n: &Node, which: Which) -> bool {
let live = filters
&& pixels == 1
&& effects::svg_filter::writes_live(&n.appearance.effects)
&& fx.iter().any(|f| matches!(f, RasterFx::Pixel(effects::PixelFx::Svg(s)) if s.in_points() && (!s.measured() || fx.len() == 1) && s.writes_as_svg11()));
&& fx
.iter()
.any(|f| matches!(f, RasterFx::Pixel(effects::PixelFx::Svg(s)) if (!s.measured() || fx.len() == 1) && s.writes_as_svg11() && s.opens_again()));
(pixels > 0 && !live)
|| (fx.iter().any(|f| matches!(f, RasterFx::DropShadow { darkness: Some(_), .. })) && (cmyk || !simple_rgb_shadow_source(n, &fx)))
}
+6 -5
View File
@@ -8,9 +8,10 @@ use vectorcraft_doc::{Document, LockedArtboards, Node, NodeId, NodeKind};
use vectorcraft_tools::builder::is_live_paint;
use super::object::can_align;
use super::panelcmds::artboard_at;
use super::wand::{fill_of, stroke_of};
use super::{
CommandSpec, Result, Session, bad, bool_or, checked_id, checked_ids_param, cmd, color_value, has_doc, has_selection, index, ok, str_param,
CommandSpec, Result, Session, bad, bool_or, checked_id, checked_ids_param, cmd, color_value, has_doc, has_selection, index_opt, ok, str_param,
switch_or, text_param,
};
use crate::DocState;
@@ -31,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
"All on Active Artboard",
["Select"],
Some("Cmd+Alt+A"),
"{artboard?: index (0-based; the app passes the active one; default: the first)}",
"{artboard?: index (0-based whole number; the app passes the active one; default, or null: the first)}",
has_doc,
all_on_artboard
),
@@ -229,7 +230,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Appearance Attribute",
["Select", "Same"],
None,
"{item?: appearance item index} the objects sharing an appearance attribute of the first selected object: its fill or stroke `item` (default: the Appearance panel's active item), else its first effect, else its topmost fill (compound paths as select.same.fillColor)",
"{item?: appearance item index (0-based whole number; default, or null: the Appearance panel's active item)} the objects sharing an appearance attribute of the first selected object: its fill or stroke `item` (default: the Appearance panel's active item), else its first effect, else its topmost fill (compound paths as select.same.fillColor)",
has_selection,
same_attribute
),
@@ -428,7 +429,7 @@ fn all(s: &mut Session, _: &Value) -> Result<Value> {
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 i = artboard_at(&st.doc, p, "artboard", "select.allOnArtboard")?.unwrap_or(0);
let r = st.doc.artboards.get(i).map(|a| a.rect).ok_or_else(|| bad("select.allOnArtboard", "no such artboard"))?;
let symbols = st.doc.symbol_boxes();
let ids: Vec<NodeId> =
@@ -1217,10 +1218,10 @@ enum Attribute {
fn same_attribute(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "select.same.appearanceAttribute";
let item = index_opt(p, "item", cmd)?.or(s.appearance_item());
let st = s.doc()?;
let (refn, _) = same_reference(st, cmd)?;
let ap = &refn.appearance;
let item = p.get("item").and_then(Value::as_u64).map(index).or(s.appearance_item());
let attr = match (item.and_then(|i| ap.items.get(i)), ap.effects.first()) {
(Some(it), _) => Attribute::Item(it.clone()),
(None, Some(e)) => Attribute::Effect(e.clone()),
+33 -4
View File
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Swatch Options",
["Window", "Swatches"],
None,
"{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} or {swatch}) or {pattern: name} replacing the swatch's colour; gradient or pattern with one of the same kind (stored as swatch.new stores it: a gradient keeps its aspect with or without start/end and holds no swatch link; a pattern is untransformed)} 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} or {swatch}) or {pattern: name} replacing the swatch's colour; gradient or pattern with one of the same kind (stored as swatch.new stores it: a gradient keeps its aspect with or without start/end and holds no swatch link; a pattern is untransformed)} 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). A fold line role the swatch carries (addon.packaging.roles) stays with it under its new name, and moves to a new swatch name when Global is turned off. 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
),
@@ -93,7 +93,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Merge Swatches",
["Window", "Swatches"],
None,
"{names: [two or more solid-colour swatches], name?: the merged swatch's name (one swatch kept)} keep the first (its name and colour) and delete the others; paints linked to them take its colour and link to it (or unlink when it isn't global), as one undo step → {name, merged: [deleted names], relinked}",
"{names: [two or more solid-colour swatches], name?: the merged swatch's name (one swatch kept)} keep the first (its name and colour) and delete the others; paints linked to them take its colour and link to it (or unlink when it isn't global), and gradient stops linked to them drop their process plates, as one undo step. When the kept swatch is global and carries no fold line role (addon.packaging.roles), it takes the role of the first merged swatch that carried one → {name, merged: [deleted names], relinked}",
has_doc,
swatch_merge
),
@@ -688,6 +688,11 @@ impl Relink {
/// batch, and a canceled batch preview, put back the paints the batch started with. A change is
/// recorded with the step just made, so Undo and Redo put these paints back with the document.
pub(super) fn map_default_paints(s: &mut Session, f: &mut LinkFn) -> Result<()> {
map_default_paints_by(s, &mut |p| p.map_links(f))
}
/// [`map_default_paints`] with `f` applied to each whole paint; `f` returns true when it changed it.
fn map_default_paints_by(s: &mut Session, f: &mut dyn FnMut(&mut Paint) -> bool) -> Result<()> {
if s.in_interaction() && s.batch_stash.is_none() {
return Ok(());
}
@@ -699,7 +704,7 @@ pub(super) fn map_default_paints(s: &mut Session, f: &mut LinkFn) -> Result<()>
});
let mut changed = false;
for p in [&mut pd.fill, &mut pd.stroke].into_iter().chain(template) {
changed |= p.map_links(f);
changed |= f(p);
}
if changed {
super::colormgmt::record_new_art_colors(s, start)?;
@@ -932,6 +937,8 @@ fn swatch_edit(s: &mut Session, p: &Value) -> Result<Value> {
}
}
let relinked = map_swatch_links(d, &mut |c, l, t| relink.apply(c, l, t));
// A fold line role carried by the swatch follows its new name, as the strokes do.
super::addons::role_swatch_edited(d, &name, &to, global);
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))?;
Ok(relinked)
})?;
@@ -1124,17 +1131,39 @@ fn swatch_merge(s: &mut Session, p: &Value) -> Result<Value> {
*l = link.clone();
true
};
// A stop linked to a merged swatch loses its process plates, which printed with that ink.
let mut unplate = |p: &Paint| {
let mut q = p.clone();
drop_stop_plates(&mut q, &merged_names).then_some(q)
};
let colorized_ok = super::paint::check_colorized(d).is_ok();
let relinked = s.edit("Merge Swatches", |d, _| {
take_swatches(d, merged, |_| true);
map_all_paints(d, &mut unplate);
let relinked = map_swatch_links(d, &mut relink);
// The lines of a merged role swatch link to the kept swatch, which takes that role.
super::addons::role_swatches_merged(d, merged, keep, link.is_some());
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))?;
Ok(relinked)
})?;
map_default_paints(s, &mut relink)?;
map_default_paints_by(s, &mut |p| {
let unplated = drop_stop_plates(p, &merged_names);
p.map_links(&mut relink) | unplated
})?;
Ok(json!({"name": keep, "merged": merged, "relinked": relinked}))
}
/// Clear the process plates of `p`'s gradient stops linked to a swatch in `names`. True when any
/// stop had plates.
fn drop_stop_plates(p: &mut Paint, names: &HashSet<&str>) -> bool {
let Paint::Gradient(g) = p else { return false };
g.gradient
.stops
.iter_mut()
.filter(|st| st.swatch.as_deref().is_some_and(|l| names.contains(l)))
.fold(false, |ch, st| st.plates.take().is_some() | ch)
}
fn swatch_ungroup(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "swatch.ungroup";
let name = str_param(p, "name").ok_or_else(|| bad(C, "missing `name`"))?.to_string();
+1 -1
View File
@@ -384,7 +384,7 @@ fn weather_icons() -> SymbolLibrary {
Anchor { p: Point::new(5.0, 16.0), h_in: Point::new(-6.0, 16.0), h_out: Point::new(0.0, 8.0), kind: AnchorKind::Corner },
Anchor { p: Point::new(-4.0, -1.0), h_in: Point::new(-4.0, 6.0), h_out: Point::new(-4.0, -8.0), kind: AnchorKind::Smooth },
];
let moon = PathData::single(SubPath { anchors: moon_anchors, closed: true });
let moon = PathData::single(SubPath::new(moon_anchors, true));
// Helper for cloud contour
let cloud_subpath = |offset_y: f64, scale: f64| -> SubPath {
+26 -2
View File
@@ -40,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Character",
[],
None,
"{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 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\" (the space after each character), kerningBefore?: 1/1000 em -1000..10000 (the space before a character that starts a line by itself: the first character of the text, of a paragraph or after a forced line break; no effect elsewhere; 0 by default), baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), 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\", \"salt=2\", …] (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only; the range is shaped with its word, so a letter's alternate keeps it joined to its neighbours), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; 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; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), warichu?: bool (Character panel menu › Warichu, with Show East Asian Options: the characters are set at warichuScale percent of their size and stacked on warichuLines lines inside their line, one above the other in horizontal type and side by side in vertical type, the first line above or to the right; a stretch of them is one block with the settings of its first character that stays whole on one line and may run past its end; type on a path sets them at their own size), warichuLines?: 1..6 (default 2), warichuGap?: pt 0..100 (the space between the lines, default 0), warichuScale?: % 10..100 (default 50), warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Warichu Settings: how the lines line up along the block, which is as long as its longest line; the justify values spread every line but the last, which is set left, centered or right, or spread with justifyAll; auto, the default, sets them as justifyLeft; left and right are top and bottom in vertical type; none of them turns warichu on), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options: space before and after each character in reading order, on its left and right in left-to-right type, on its right and left in right-to-left type, above and below it in vertical type; a ligature or a letter with its marks takes the values of its first character; line wrapping counts it, alignment keeps it at a line's ends and justification does not stretch or narrow it; 0 by default; a value that is not a number or is outside the range is refused, naming the key), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options: the share of the blank space on each side of each character's ink, inside its own width, that is taken away in horizontal type, the glyph keeping its shape; 100 sets the ink edge to edge; a character without ink, such as a space, keeps its width; a ligature or a letter with its marks takes Line truncated
"{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 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\" (the space after each character), kerningBefore?: 1/1000 em -1000..10000 (the space before a character that starts a line by itself: the first character of the text, of a paragraph or after a forced line break; no effect elsewhere; 0 by default), baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), 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\", \"salt=2\", …] (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only; the range is shaped with its word, so a letter's alternate keeps it joined to its neighbours), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; 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; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), warichu?: bool (Character panel menu › Warichu, with Show East Asian Options: the characters are set at warichuScale percent of their size and stacked on warichuLines lines inside their line, one above the other in horizontal type and side by side in vertical type, the first line above or to the right; a stretch of them is one block with the settings of its first character that stays whole on one line and may run past its end; type on a path sets them at their own size), warichuLines?: 1..6 (default 2), warichuGap?: pt 0..100 (the space between the lines, default 0), warichuScale?: % 10..100 (default 50), warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Warichu Settings: how the lines line up along the block, which is as long as its longest line; the justify values spread every line but the last, which is set left, centered or right, or spread with justifyAll; auto, the default, sets them as justifyLeft; left and right are top and bottom in vertical type; none of them turns warichu on), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options: space before and after each character in reading order, on its left and right in left-to-right type, on its right and left in right-to-left type, above and below it in vertical type; a ligature or a letter with its marks takes the values of its first character; line wrapping counts it, alignment keeps it at a line's ends and justification does not stretch or narrow it; 0 by default; a value that is not a number or is outside the range is refused, naming the key), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options: the share of the blank space on each side of each character's ink, inside its own width, that is taken away in horizontal type, the glyph keeping its shape; 100 sets the ink edge to edge; a character without ink, such as a space, keeps its width; a ligature or a letter with its marks takes Line truncated
has_doc,
set_range_style
),
@@ -470,6 +470,9 @@ pub(crate) struct CharChange {
aki_right: Option<f64>,
/// Tsume, in percent.
tsume: Option<f64>,
/// Adjust Horizontal and Vertical Diacritic Position, in 1/1000 em.
diacritic_horizontal: Option<f64>,
diacritic_vertical: Option<f64>,
standard_vertical_roman: Option<bool>,
no_break: Option<bool>,
digits: Option<vectorcraft_doc::Digits>,
@@ -548,6 +551,16 @@ pub(crate) fn aki_param(p: &Value, key: &str, cmd: &str) -> Result<Option<f64>>
if (lo..=hi).contains(&v) { Ok(Some(v)) } else { Err(bad(cmd, format!("`{key}` must be from {lo} to {hi}"))) }
}
/// `diacriticHorizontal` or `diacriticVertical` (Adjust Horizontal and Vertical Diacritic
/// Position): a number of thousandths of an em within
/// [`vectorcraft_doc::text::MAX_DIACRITIC_POSITION`] either way. Any other value is an error.
pub(crate) fn diacritic_param(p: &Value, key: &str, cmd: &str) -> Result<Option<f64>> {
let Some(v) = p.get(key).filter(|v| !v.is_null()) else { return Ok(None) };
let v = v.as_f64().filter(|v| v.is_finite()).ok_or_else(|| bad(cmd, format!("`{key}` must be a number")))?;
let (lo, hi) = (-vectorcraft_doc::text::MAX_DIACRITIC_POSITION, vectorcraft_doc::text::MAX_DIACRITIC_POSITION);
if (lo..=hi).contains(&v) { Ok(Some(v)) } else { Err(bad(cmd, format!("`{key}` must be from {lo} to {hi}"))) }
}
/// `tsume` (Tsume): a percentage from 0 to [`vectorcraft_doc::text::MAX_TSUME`]. Any other value is
/// an error.
pub(crate) fn tsume_param(p: &Value, cmd: &str) -> Result<Option<f64>> {
@@ -852,6 +865,8 @@ impl CharChange {
aki_left: aki_param(p, "akiLeft", cmd)?,
aki_right: aki_param(p, "akiRight", cmd)?,
tsume: tsume_param(p, cmd)?,
diacritic_horizontal: diacritic_param(p, "diacriticHorizontal", cmd)?,
diacritic_vertical: diacritic_param(p, "diacriticVertical", cmd)?,
standard_vertical_roman: flag("standardVerticalRoman"),
no_break: flag("noBreak"),
digits: digits_param(p, cmd)?,
@@ -918,6 +933,8 @@ impl CharChange {
&& self.aki_left.is_none()
&& self.aki_right.is_none()
&& self.tsume.is_none()
&& self.diacritic_horizontal.is_none()
&& self.diacritic_vertical.is_none()
&& self.standard_vertical_roman.is_none()
&& self.no_break.is_none()
&& self.digits.is_none()
@@ -963,7 +980,8 @@ impl CharChange {
}
}
/// The character alignment, direction and East Asian settings of [`Self::apply`].
/// The character alignment, direction, diacritic positions and East Asian settings of
/// [`Self::apply`].
fn apply_cjk(&self, st: &mut CharStyle) {
if let Some(v) = self.char_align {
st.char_align = v;
@@ -1010,6 +1028,12 @@ impl CharChange {
if let Some(v) = self.tsume {
st.tsume = v;
}
if let Some(v) = self.diacritic_horizontal {
st.diacritic_horizontal = v;
}
if let Some(v) = self.diacritic_vertical {
st.diacritic_vertical = v;
}
if let Some(v) = self.standard_vertical_roman {
st.standard_vertical_roman = v;
}
+13 -2
View File
@@ -223,6 +223,8 @@ pub fn char_attrs(v: &CharStyle) -> Map<String, Value> {
("akiLeft", json!(v.aki_left)),
("akiRight", json!(v.aki_right)),
("tsume", json!(v.tsume)),
("diacriticHorizontal", json!(v.diacritic_horizontal)),
("diacriticVertical", json!(v.diacritic_vertical)),
("standardVerticalRoman", json!(v.standard_vertical_roman)),
("noBreak", json!(v.no_break)),
("digits", json!(v.digits)),
@@ -584,6 +586,13 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma
if changed(key) && !(lo..=hi).contains(&st.tsume) {
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
}
let hi = vectorcraft_doc::text::MAX_DIACRITIC_POSITION;
let lo = -hi;
for (key, value) in [("diacriticHorizontal", st.diacritic_horizontal), ("diacriticVertical", st.diacritic_vertical)] {
if changed(key) && !(lo..=hi).contains(&value) {
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
}
}
let lines = vectorcraft_doc::text::WARICHU_LINES;
if changed("warichuLines") && !lines.contains(&st.warichu_lines) {
return Err(bad(&c, format!("`warichuLines` must be a whole number from {} to {}", lines.start(), lines.end())));
@@ -1081,12 +1090,12 @@ fn unused(s: &mut Session, kind: Kind) -> Result<Value> {
/// The styles of `kind` in `src` that load, with their source names so that art in the file keeps
/// referring to them: not the Normal style, and not one whose attributes don't read, whose sizes,
/// scales, leading, shifts, Insert Aki, Tsume, Warichu Settings or stroke width are out of the range `charStyle.new` takes, whose
/// scales, leading, shifts, Insert Aki, Tsume, diacritic positions, Warichu Settings or stroke width are out of the range `charStyle.new` takes, whose
/// indents, spacing, Hyphenation or Justification options or tab stops are out of the range
/// `paraStyle.new` takes, or whose name is empty, which are skipped. → (the styles, the names in
/// `src` of those skipped)
fn loadable(src: &Document, kind: Kind) -> (Vec<TextStyleDef>, Vec<String>) {
const RANGED: [&str; 22] = [
const RANGED: [&str; 24] = [
"size",
"h_scale",
"v_scale",
@@ -1095,6 +1104,8 @@ fn loadable(src: &Document, kind: Kind) -> (Vec<TextStyleDef>, Vec<String>) {
"akiLeft",
"akiRight",
"tsume",
"diacriticHorizontal",
"diacriticVertical",
"tcyUpDown",
"tcyLeftRight",
"warichuLines",
+28 -1
View File
@@ -399,6 +399,8 @@ fn character_style_dimensions_are_checked_before_a_definition_changes() {
json!({"akiRight": 1000.1}),
json!({"tsume": -0.1}),
json!({"tsume": 100.1}),
json!({"diacriticHorizontal": -1000.1}),
json!({"diacriticVertical": 1000.1}),
] {
let key = attrs.as_object().unwrap().keys().next().unwrap();
for cmd in ["charStyle.edit", "charStyle.setAttrs", "charStyle.new"] {
@@ -422,7 +424,8 @@ fn character_style_dimensions_are_checked_before_a_definition_changes() {
"baseline_shift": -1296.0,
"tcyUpDown": 1296.0, "tcyLeftRight": -1296.0,
"akiLeft": 0.0, "akiRight": 1000.0,
"tsume": 100.0
"tsume": 100.0,
"diacriticHorizontal": -1000.0, "diacriticVertical": 1000.0
}}),
)
.unwrap();
@@ -1652,6 +1655,30 @@ fn paragraph_style_options_edit_applies_to_users_and_is_one_saved_undo_step() {
}
}
/// A paragraph style can hold a Standard composer: it applies to its paragraphs, redefining and
/// resetting treat it like any attribute, and the style and the paragraphs keep it through a save.
#[test]
fn paragraph_styles_keep_a_standard_composer_through_a_save() {
use vectorcraft_doc::Composer;
let (mut s, id) = session_with_text("One\nTwo");
s.execute("paraStyle.new", &json!({"name": "Legacy", "attrs": {"composer": "standardSingleLine"}})).unwrap();
s.execute("paraStyle.apply", &json!({"name": "Legacy", "id": id, "start": 0, "end": 0})).unwrap();
assert_eq!(paras(&s, id).iter().map(|p| p.composer).collect::<Vec<_>>(), [Composer::StandardSingleLine, Composer::EveryLine]);
let doc = s.doc().unwrap().doc.clone();
let saved = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap();
let style = saved.para_styles.iter().find(|d| d.name == "Legacy").unwrap();
assert_eq!(style.attrs["composer"], json!("standardSingleLine"));
let mut composers = vec![];
saved.walk(|n| {
if let vectorcraft_doc::NodeKind::Text(t) = &n.kind {
composers.extend(t.paragraph_styles().iter().map(|p| p.composer));
}
});
assert_eq!(composers, [Composer::StandardSingleLine, Composer::EveryLine]);
s.execute("paraStyle.setAttrs", &json!({"name": "Legacy", "attrs": {"composer": "standardEveryLine"}})).unwrap();
assert_eq!(paras(&s, id)[0].composer, Composer::StandardEveryLine, "an edited style reaches its paragraphs");
}
/// A changed paragraph attribute outside the range `text.setFormat` keeps it to is an error for
/// `paraStyle.edit`, `paraStyle.setAttrs` and `paraStyle.new`, with no change to the document; the
/// ends of each range are accepted, and an out-of-range value the style already has can be kept.
+18 -14
View File
@@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Create Outlines",
["Type"],
Some("Cmd+Shift+O"),
"{} convert the selected text to groups of compound paths (one per glyph); the type object's own fills and strokes (not its characters') go on paths of its whole outline, below or above the glyphs as its Characters row places them; the group keeps the object's transparency, opacity mask and effects, once; a frame of threaded text leaves its thread with the text it shows; a dimension whose label is outlined becomes a plain group of its art → {ids}",
"{} convert the selected text to groups of compound paths (one per glyph); on type scaled unevenly, sheared or flattened, each glyph's stroke becomes a filled path over it, shaped as the canvas strokes it; the type object's own fills and strokes (not its characters') go on paths of its whole outline, below or above the glyphs as its Characters row places them; the group keeps the object's transparency, opacity mask and effects, once; a frame of threaded text leaves its thread with the text it shows; a dimension whose label is outlined becomes a plain group of its art → {ids}",
has_selection,
create_outlines
),
@@ -619,16 +619,25 @@ fn scale_text_attributes(s: &mut Session, p: &Value) -> Result<Value> {
/// A path (or compound path) of `outline`, a piece of type `t`'s outline in text space, painted as
/// run `run` and placed in the document as the canvas paints it ([`paint_type_piece`]: unplaced
/// gradients fitted to `bounds`, the layout's bounds, stroke weights scaled by the type's
/// transform); `None` when the piece has no path.
fn type_piece(d: &mut Document, t: &TextObject, bounds: kurbo::Rect, run: usize, outline: &kurbo::BezPath) -> Option<Node> {
/// transform), followed by a path (or compound path) filled with the run's stroke when the type's
/// transform is not a similarity; empty when the piece has no path.
fn type_piece(d: &mut Document, t: &TextObject, bounds: kurbo::Rect, run: usize, outline: &kurbo::BezPath) -> Vec<Node> {
let path = PathData::from_bezpath(outline);
if path.is_empty() {
return None;
return vec![];
}
let st = t.runs.get(run).map(|r| r.style.clone()).unwrap_or_else(|| t.first_style());
let mut node = shape_node(d, path, None);
vectorcraft_render::effects::paint_type_piece(&mut node, &st, bounds, t.xf);
Some(node)
let stroke = vectorcraft_render::effects::paint_type_piece(&mut node, &st, bounds, t.xf);
let mut out = vec![node];
if let Some(s) = stroke
&& let Some(path) = s.path_data()
{
let mut filled = shape_node(d, path.clone(), None);
filled.appearance = s.appearance.clone();
out.push(filled);
}
out
}
fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> {
@@ -675,9 +684,7 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> {
children.push(Arc::new(d.reid(&art)));
break 'glyph;
}
if let Some(node) = type_piece(d, t, lay.bounds, g.run, &g.outline) {
children.push(Arc::new(node));
}
children.extend(type_piece(d, t, lay.bounds, g.run, &g.outline).into_iter().map(Arc::new));
}
run_end.insert(g.run, children.len());
}
@@ -686,10 +693,9 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> {
// nothing there either).
let mut ruby: Vec<(usize, Arc<Node>)> = vec![];
for g in &lay.ruby {
let Some(node) = type_piece(d, t, lay.bounds, g.run, &g.outline) else { continue };
// After the glyphs of its run and of the runs before it.
let at = run_end.range(..=g.run).map(|(_, end)| *end).max().unwrap_or(0);
ruby.push((at, Arc::new(node)));
ruby.extend(type_piece(d, t, lay.bounds, g.run, &g.outline).into_iter().map(|node| (at, Arc::new(node))));
}
ruby.sort_by_key(|(at, _)| *at);
let mut ruby = ruby.into_iter().peekable();
@@ -711,9 +717,7 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> {
// Underline and strikethrough bars become paths of their run's paint too (#847).
for (run, bar) in vectorcraft_text::decorations(&lay, vectorcraft_text::FontDb::global(), t) {
all.extend(bar.iter());
if let Some(node) = type_piece(d, t, lay.bounds, run, &bar) {
children.push(Arc::new(node));
}
children.extend(type_piece(d, t, lay.bounds, run, &bar).into_iter().map(Arc::new));
}
// The object's own fills and strokes (not its characters') paint the whole outline:
// those below the Characters row under the characters, the others over them, with
@@ -1921,6 +1921,66 @@ fn tsume_is_a_character_attribute() {
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step for a refused call");
}
/// Adjust Horizontal and Vertical Diacritic Position (Character panel, Middle Eastern options):
/// character attributes in thousandths of an em, 0 by default and saved only when not 0. Both
/// commands set them in one undo step, setting one leaves the other, a call that gives the values
/// the text already has records none, and a value that is not a number or lies outside -1000 to
/// 1000 is refused, naming the key, before anything changes; the native file and a character style
/// captured from the characters carry them.
#[test]
fn diacritic_positions_are_character_attributes() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "بَب"})).unwrap()["id"].as_u64().unwrap();
let runs = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
NodeKind::Text(t) => t.runs.clone(),
_ => panic!("text"),
};
let moved = |s: &Session| runs(s).iter().map(|r| (r.text.clone(), r.style.diacritic_horizontal, r.style.diacritic_vertical)).collect::<Vec<_>>();
let saved = serde_json::to_value(&runs(&s)[0].style).unwrap();
assert!(saved.get("diacriticHorizontal").is_none() && saved.get("diacriticVertical").is_none());
s.execute("select.set", &json!({"ids": [id]})).unwrap();
s.execute("text.setFormat", &json!({"diacriticHorizontal": -150})).unwrap();
s.execute("text.setFormat", &json!({"diacriticVertical": 250})).unwrap();
assert_eq!(moved(&s), [("بَب".to_string(), -150.0, 250.0)], "setting one leaves the other");
let undo = s.doc().unwrap().history.undo.len();
s.execute("text.setFormat", &json!({"diacriticHorizontal": -150, "diacriticVertical": 250})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step without a change");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(moved(&s), [("بَب".to_string(), -150.0, 0.0)], "one undo step");
s.execute("edit.redo", &json!({})).unwrap();
let mark = "بَ".len();
s.execute("text.setRangeStyle", &json!({"id": id, "start": "ب".len(), "end": mark, "diacriticVertical": -1000})).unwrap();
assert_eq!(moved(&s), [("ب".to_string(), -150.0, 250.0), ("\u{064E}".to_string(), -150.0, -1000.0), ("ب".to_string(), -150.0, 250.0)]);
let saved = serde_json::to_value(&runs(&s)[1].style).unwrap();
assert_eq!((saved["diacriticHorizontal"].clone(), saved["diacriticVertical"].clone()), (json!(-150.0), json!(-1000.0)));
let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
let NodeKind::Text(t) = &back.node(NodeId(id)).unwrap().kind else { panic!("text") };
let reopened: Vec<_> = t.runs.iter().map(|r| (r.text.clone(), r.style.diacritic_horizontal, r.style.diacritic_vertical)).collect();
assert_eq!(reopened, moved(&s));
let attrs = super::super::textstyles::char_attrs(&runs(&s)[1].style);
assert_eq!((attrs["diacriticHorizontal"].clone(), attrs["diacriticVertical"].clone()), (json!(-150.0), json!(-1000.0)));
let before = moved(&s);
let undo = s.doc().unwrap().history.undo.len();
for (cmd, p, want) in [
("text.setFormat", json!({"diacriticHorizontal": "50"}), "`diacriticHorizontal` must be a number"),
("text.setFormat", json!({"diacriticVertical": 1000.5}), "`diacriticVertical` must be from -1000 to 1000"),
("text.setRangeStyle", json!({"id": id, "diacriticVertical": true}), "`diacriticVertical` must be a number"),
(
"text.setRangeStyle",
json!({"id": id, "start": 0, "end": mark, "diacriticHorizontal": -1001}),
"`diacriticHorizontal` must be from -1000 to 1000",
),
] {
let e = s.execute(cmd, &p).unwrap_err();
assert!(matches!(&e, EngineError::BadParams { msg, .. } if msg == want), "{cmd} {p}: {e}");
}
assert_eq!(moved(&s), before);
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step for a refused call");
}
/// Standard Vertical Roman Alignment (Character panel menu, East Asian options): a character
/// attribute, off by default and saved only when on. Documents written before it read as off; a
/// character style captured from the characters carries it.
+7
View File
@@ -1783,6 +1783,13 @@ fn strip_formatting(n: &mut vectorcraft_doc::Node) {
fn paste_plain(s: &mut Session, p: &Value) -> Result<Value> {
let saved = s.clipboard.nodes.clone();
// Pasted colors linked to a swatch merged with the document's show its color, so a pasted pie's legend labels take
// the contrast of the wedges as pasted. A `swatchConflict` the paste refuses is left to its error.
if let (Ok(choices), Ok(st)) = (super::clipboard::SwatchChoices::parse("edit.pasteWithoutFormatting", p), s.doc()) {
let same_doc = s.clipboard.source_doc == Some(st.uid);
let d = std::sync::Arc::clone(&st.doc);
s.clipboard.show_merged_colors(&d, &choices, same_doc);
}
for n in &mut s.clipboard.nodes {
strip_formatting(n);
}
+17 -2
View File
@@ -59,8 +59,23 @@ fn rect_in_range(r: vectorcraft_geom::Rect) -> bool {
/// margin passes without being measured: its curves stay inside their control points. Any other
/// object, and a path with a point outside that margin, is measured.
pub(crate) fn objects_in_range(d: &Document, ids: &[NodeId]) -> bool {
let paths = d.index_paths(ids.iter().copied());
ids.iter().all(|id| paths.get(id).and_then(|p| d.node_at(p)).is_none_or(|n| points_in_range(n) || n.geometric_bounds().is_none_or(rect_in_range)))
if ids.is_empty() {
return true;
}
let node_ok = |n: &vectorcraft_doc::Node| points_in_range(n) || n.geometric_bounds().is_none_or(rect_in_range);
// A cached document or a few ids: look each one up. Otherwise one walk of the tree, with no
// path vectors allocated.
if d.has_lookup_cache() || ids.len() <= 16 {
return ids.iter().all(|id| d.node(*id).is_none_or(node_ok));
}
let want: std::collections::HashSet<NodeId> = ids.iter().copied().collect();
let mut ok = true;
d.walk(|n| {
if ok && want.contains(&n.id) && !node_ok(n) {
ok = false;
}
});
ok
}
/// Coordinates at most this far from 0 keep a curve's measured bounds within [`MAX_COORD`]
+4 -4
View File
@@ -2133,7 +2133,7 @@ mod pen_interactions {
gesture(&mut s, &[(400.0, 500.0)], Mods::default(), v);
let extended = path(&s, id);
assert_eq!(extended.anchor_count(), 3);
assert_eq!(extended.subpaths[0].anchors[..2], reversed.subpaths[0].anchors);
assert_eq!(extended.subpaths[0].anchors.to_vec()[..2], reversed.subpaths[0].anchors);
assert!(!s.in_interaction() && !s.tool_busy());
assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 1);
}
@@ -2168,7 +2168,7 @@ mod pen_interactions {
gesture(&mut s, &[(300.0, 400.0)], Mods::default(), v);
let extended = path(&s, id);
assert_eq!(extended.anchor_count(), 3);
assert_eq!(extended.subpaths[0].anchors[..2], converted.subpaths[0].anchors);
assert_eq!(extended.subpaths[0].anchors.to_vec()[..2], converted.subpaths[0].anchors);
assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 1);
}
@@ -2227,7 +2227,7 @@ mod pen_interactions {
}
let extended = path(&s, id);
assert_eq!(extended.anchor_count(), 3);
assert_eq!(extended.subpaths[0].anchors[..2], before.subpaths[0].anchors);
assert_eq!(extended.subpaths[0].anchors.to_vec()[..2], before.subpaths[0].anchors);
let a = extended.subpaths[0].anchors[2];
assert_eq!(a.p, Point::new(320.0, 450.0));
assert_eq!(a.h_in, Point::new(290.0, 430.0), "Alt freezes the incoming handle and Space translates it");
@@ -3381,7 +3381,7 @@ fn reshape_open_path(s: &mut Session, anchors: Value) -> NodeId {
/// The anchors of the path's first subpath.
fn reshape_anchors(s: &Session, id: NodeId) -> Vec<vectorcraft_geom::Anchor> {
s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].anchors.clone()
s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].anchors.to_vec()
}
/// The share of the drag an anchor takes at `u` of the way from an end to the grabbed point.
+57 -3
View File
@@ -3,7 +3,7 @@
use serde_json::json;
use crate::cmd::actionset::{AiaStep, read_aia};
use crate::cmd::actionset::{AiaData, AiaStep, AiaValue, read_aia};
use crate::*;
/// `text` as a bracketed hexadecimal value.
@@ -37,7 +37,12 @@ fn a_set_reads_its_actions_and_steps() {
let names: Vec<&str> = set.actions.iter().map(|a| a.name.as_str()).collect();
assert_eq!(names, ["First", "二番目"]);
let step = |a: usize, s: usize| set.actions[a].steps[s].clone();
let join = AiaStep { name: "sample_join".into(), label: Some("Join".into()), on: Some(1), params: 3, declared: Some(3), line: 9 };
let values = vec![
AiaValue { key: Some(1), kind: Some("unit real".into()), value: None },
AiaValue { key: None, kind: Some("ustring".into()), value: Some(AiaData::Text(b"a } brace".to_vec())) },
AiaValue { key: None, kind: Some("raw".into()), value: None },
];
let join = AiaStep { name: "sample_join".into(), label: Some("Join".into()), on: Some(1), params: 3, values, declared: Some(3), line: 9 };
assert_eq!(step(0, 0), join);
assert_eq!((step(1, 0).name.as_str(), step(1, 0).label.clone(), step(1, 0).on), ("sample)one", None, Some(0)));
assert_eq!((step(1, 1).label.as_deref(), step(1, 1).on, step(1, 1).line), (Some("Second Step"), None, 39));
@@ -60,6 +65,55 @@ fn recorded_values_are_counted_and_checked() {
assert!(set(&[value("one"), "/value [ 1 zz ]".to_string()]).truncated, "a second value that isn't hexadecimal");
}
/// `actionSet.read` answers with each recorded value's key, type and value: a number, text in
/// parentheses or hexadecimal text that is UTF-8 with its length in bytes, and null for text that
/// isn't UTF-8 and for other values. Fields may come in any order, and a value with the wrong byte
/// count still marks the set truncated.
#[test]
fn recorded_values_come_back_with_their_keys_and_types() {
let mut s = Session::new();
let text = format!(
"/version 3 /action-1 {{ /event-1 {{ /internalName (sample_values) /parameterCount 6 \
/parameter-1 {{ /key 1952807028 /type (ustring) /value {note} }} \
/parameter-2 {{ /value 1 /type (boolean) /key 2003792484 }} \
/parameter-3 {{ /type (ustring) /value [ 2 c328 ] /key 7 }} \
/parameter-4 {{ /key 99999999999999999999 /type (real) /value 4.5 }} \
/parameter-5 {{ /key 3 /type (text) /value (plain) }} \
/parameter-6 {{ }} }} }}",
note = hex("Größe ✓")
);
let r = s.execute("actionSet.read", &json!({ "data": text })).unwrap();
assert_eq!(r["truncated"], false);
assert_eq!(
r["actions"][0]["steps"][0]["values"],
json!([
{"key": 1952807028, "type": "ustring", "value": "Größe ✓", "bytes": 11},
{"key": 2003792484, "type": "boolean", "value": 1},
{"key": 7, "type": "ustring", "value": null, "bytes": 2},
{"key": null, "type": "real", "value": null},
{"key": 3, "type": "text", "value": "plain", "bytes": 5},
{"key": null, "type": null, "value": null},
])
);
let bad = "/version 3 /action-1 { /event-1 { /parameter-1 { /key 1 /type (ustring) /value [ 3 4142 ] } } }";
assert_eq!(s.execute("actionSet.read", &json!({ "data": bad })).unwrap()["truncated"], true);
}
/// At most 100,000 recorded values are kept in a set: the others are still counted, so a step's
/// `values` can be shorter than its `params`.
#[test]
fn recorded_values_past_the_cap_are_counted_but_not_kept() {
let step = format!("/event-1 {{ {} }} ", "/parameter-1 { /key 1 /value 0 } ".repeat(1000));
let action = format!("/action-1 {{ {} }} ", step.repeat(50));
let set = read_aia(format!("/version 3 {}", action.repeat(3)).as_bytes()).unwrap();
assert!(!set.truncated);
let steps = || set.actions.iter().flat_map(|a| &a.steps);
assert_eq!(steps().map(|s| s.params).sum::<usize>(), 150_000);
assert_eq!(steps().map(|s| s.values.len()).sum::<usize>(), 100_000);
assert_eq!(set.actions[2].steps[0].values.len(), 0);
assert_eq!(set.actions[1].steps[49].values[999], AiaValue { key: Some(1), kind: None, value: Some(AiaData::Int(0)) });
}
/// `actionSet.read` takes exactly one of `path`, `data` and `dataBase64`, and text for the text
/// params; any other value is an error.
#[test]
@@ -97,7 +151,7 @@ fn read_command_answers_with_the_set() {
let text = sample().replacen(&format!("/name {}", hex("Prep Sätze")), "", 1);
let r = s.execute("actionSet.read", &json!({ "data": text, "name": "/sets/Mine.aia" })).unwrap();
assert_eq!(r["set"], "Mine");
assert_eq!(r["actions"][1]["steps"][0], json!({"name": "sample)one", "label": null, "on": false, "params": 0, "line": 34}));
assert_eq!(r["actions"][1]["steps"][0], json!({"name": "sample)one", "label": null, "on": false, "params": 0, "values": [], "line": 34}));
assert_eq!(r["actions"][0]["steps"][0]["on"], true);
assert_eq!(r["actions"][0]["steps"][0]["label"], "Join");
let blank = format!("/version 3 /action-1 {{ /event-1 {{ /internalName (x) /localizedName {} }} }}", hex(" "));
+43 -2
View File
@@ -1,6 +1,7 @@
//! An edit of one anchor of a long selected path does not measure the path's segments
//! ([`vectorcraft_geom::path::measured_segments`]) to check that it stays within the canvas, and
//! an edit that leaves the anchor as it was records no undo step.
//! ([`vectorcraft_geom::path::measured_segments`]) to check that it stays within the canvas, its
//! undo step keeps the chunk of anchors it changed rather than a copy of every anchor, and an edit
//! that leaves the anchor as it was records no undo step.
use std::collections::BTreeSet;
use std::sync::Arc;
@@ -74,6 +75,46 @@ fn one_anchor_edit_of_a_long_path_measures_few_segments() {
}
}
/// Most bytes the undo step of one anchor edit may keep, however many anchors the path has: about
/// one chunk of anchors and the node, with room for the chunk tables of 200,000 anchors.
const MOST_STEP_BYTES: usize = 48 * 1024;
#[test]
fn one_anchor_edit_of_a_long_path_keeps_one_chunk_in_its_undo_step() {
for n in [10_000, 200_000] {
let (mut s, id) = long_path(n);
let original = s.doc().unwrap().doc.clone();
let edits = [
("path.moveAnchor", json!({"id": id.0, "anchor": 5, "x": 3, "y": 50})),
("path.setHandle", json!({"id": id.0, "anchor": 5, "which": "out", "x": 4, "y": 40})),
("path.moveAnchors", json!({"dx": 1, "dy": 0})),
("object.nudge", json!({"dx": 1, "dy": 0})),
];
let mut docs = vec![];
for (cmd, p) in &edits {
s.execute(cmd, p).unwrap();
let step = s.doc().unwrap().history.undo.last().unwrap().bytes;
assert!(step <= MOST_STEP_BYTES, "{cmd} on {n} anchors kept {step} bytes in its undo step");
docs.push(s.doc().unwrap().doc.clone());
}
assert_eq!(anchor(&s, id, 5).p, Point::new(5.0, 50.0));
assert_eq!(anchor(&s, id, 5).h_out, Point::new(6.0, 40.0));
assert_eq!(anchor(&s, id, n - 1), original.node(id).unwrap().path_data().unwrap().subpaths[0].anchors[n - 1]);
// Undo gives back each version exactly, and redo the edits, each step as small.
for k in (0..edits.len()).rev() {
s.execute("edit.undo", &json!({})).unwrap();
let expected = if k == 0 { &original } else { &docs[k - 1] };
assert!(s.doc().unwrap().doc == *expected, "undo of {} on {n} anchors", edits[k].0);
let redo = s.doc().unwrap().history.redo.last().unwrap().bytes;
assert!(redo <= MOST_STEP_BYTES, "redo of {} on {n} anchors keeps {redo} bytes", edits[k].0);
}
for (k, doc) in docs.iter().enumerate() {
s.execute("edit.redo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc == *doc, "redo of {} on {n} anchors", edits[k].0);
}
}
}
/// A handle past the canvas is measured: the edit stands while the curve stays within the canvas,
/// and is refused once the curve leaves it.
#[test]
+34
View File
@@ -1037,6 +1037,40 @@ fn brush_freehand_direct_call_has_one_undo_step() {
assert_eq!(s.doc().unwrap().history.undo.last().map(|e| e.label.as_str()), Some("Paintbrush"), "a stroke with a brush is a Paintbrush step");
}
/// A `brush.freehand` call that continues a path by one point changes only the path's brush, and
/// applies `keepSelected` as a longer continuation does: off, the path is deselected while the
/// rest of the selection stays; on, the path is selected. A call that leaves the brush as it is
/// changes neither the selection nor the undo history.
#[test]
fn brush_freehand_continued_by_one_point_follows_keep_selected() {
let mut s = session();
let r = s.execute("brush.freehand", &json!({"points": [[10, 10], [60, 40], [120, 10]], "style": "brush", "brush": "Charcoal"})).unwrap();
let p = NodeId(r["id"].as_u64().unwrap());
let a = rect(&mut s, 200.0, 200.0, 10.0, 10.0);
let extend = json!({"id": p.0, "end": "end"});
select(&mut s, &[p, a]);
let off = json!({"points": [[120, 10]], "extend": extend, "brush": "Dots", "keepSelected": false});
assert_eq!(s.execute("brush.freehand", &off).unwrap()["id"], json!(p.0));
assert_eq!(brush_of(&s, p).as_deref(), Some("Dots"));
assert_eq!(selected(&s), [a], "Keep selected off: the path is deselected and the rest stays");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(brush_of(&s, p).as_deref(), Some("Charcoal"), "one Undo takes back the brush");
assert_eq!(selected(&s), [p, a], "Undo gives back the earlier selection");
select(&mut s, &[a]);
let on = json!({"points": [[120, 10]], "extend": extend, "brush": "Dots"});
s.execute("brush.freehand", &on).unwrap();
assert_eq!(brush_of(&s, p).as_deref(), Some("Dots"));
assert_eq!(selected(&s), [p], "Keep selected on: the continued path is selected");
select(&mut s, &[a]);
let undo = s.doc().unwrap().history.undo.len();
s.execute("brush.freehand", &on).unwrap();
assert_eq!(selected(&s), [a], "the same brush again: the selection stays");
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "the same brush again: no undo step");
}
/// `brush.freehand` refuses a brush for a path with no stroke (a continued path, a redrawn one
/// and a new filled pencil path while the stroke is None) instead of reporting it painted: the
/// document, the selection and the undo history stay as they were. Without a brush the path is
+421
View File
@@ -3908,6 +3908,266 @@ fn live_paint_bucket_triple_click_fills_every_face_of_the_same_fill() {
assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), green, red.clone(), red]);
}
/// A triple-click whose first click is released across an edge, in the face it then clicks twice,
/// matches that face's fill from before the first click: the release painted it too.
#[test]
fn live_paint_bucket_triple_click_after_a_release_across_an_edge_matches_the_fill_before() {
let mut s = session();
let g = live_squares(&mut s, &[0.0, 50.0, 100.0, 150.0]);
let [a, b, c, d] = faces_at(&s, g, &[(25.0, 25.0), (75.0, 25.0), (125.0, 25.0), (175.0, 25.0)])[..] else { panic!("four faces") };
let (red, blue) = (Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 201.0, 51.0));
paint_parts(&mut s, &all, &Paint::solid(Color::rgb(0.0, 0.0, 0.0)), &[(a, red.clone()), (b, red.clone()), (c, blue.clone()), (d, red.clone())]);
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.paint.fill = green.clone();
s.pointer(&PointerEvent::new(PointerKind::Down, 45.0, 25.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 55.0, 25.0), v).unwrap();
assert_eq!([a, b].map(|f| fill_of(&s, f)), [green.clone(), green.clone()], "the release across x = 50 fills both faces");
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick, PointerKind::Down, PointerKind::Up, PointerKind::TripleClick] {
s.pointer(&PointerEvent::new(kind, 55.0, 25.0), v).unwrap();
}
assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), green.clone(), blue, green]);
}
/// A triple-click whose third press lands in another face and is released in the face its first
/// two clicks painted still matches that face's fill from before the first click.
#[test]
fn live_paint_bucket_triple_click_released_from_another_face_matches_the_fill_before() {
let mut s = session();
let g = live_squares(&mut s, &[0.0, 50.0, 100.0, 150.0]);
let [a, b, c, d] = faces_at(&s, g, &[(25.0, 25.0), (75.0, 25.0), (125.0, 25.0), (175.0, 25.0)])[..] else { panic!("four faces") };
let (red, blue) = (Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 201.0, 51.0));
paint_parts(&mut s, &all, &Paint::solid(Color::rgb(0.0, 0.0, 0.0)), &[(a, red.clone()), (b, red.clone()), (c, blue.clone()), (d, red.clone())]);
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.paint.fill = green.clone();
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] {
s.pointer(&PointerEvent::new(kind, 55.0, 25.0), v).unwrap();
}
s.pointer(&PointerEvent::new(PointerKind::Down, 45.0, 25.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 55.0, 25.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::TripleClick, 55.0, 25.0), v).unwrap();
assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), green.clone(), blue, green]);
}
/// A triple-click whose first click makes the Live Paint group and is released across an edge, in
/// the face it then clicks twice, matches the fill that face was made with.
#[test]
fn live_paint_bucket_triple_click_after_making_the_group_across_an_edge_matches_the_made_fill() {
let mut s = session();
let ids: Vec<NodeId> = [0.0, 50.0, 200.0, 300.0].iter().map(|&x| rect(&mut s, x, 0.0, 50.0, 50.0)).collect();
let (red, blue) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0));
for (id, c) in ids.iter().zip([red, red, blue, red]) {
set_fill(&mut s, *id, c);
}
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.paint.fill = green.clone();
s.pointer(&PointerEvent::new(PointerKind::Down, 45.0, 25.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 55.0, 25.0), v).unwrap();
let g = vectorcraft_tools::builder::live_paint_at(&s.doc().unwrap().doc, Point::new(25.0, 25.0)).expect("the click made a group");
let faces = faces_at(&s, g, &[(25.0, 25.0), (75.0, 25.0), (225.0, 25.0), (325.0, 25.0)]);
assert_eq!(faces[..2].iter().map(|f| fill_of(&s, *f)).collect::<Vec<_>>(), [green.clone(), green.clone()], "the release fills both faces");
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick, PointerKind::Down, PointerKind::Up, PointerKind::TripleClick] {
s.pointer(&PointerEvent::new(kind, 55.0, 25.0), v).unwrap();
}
assert_eq!(faces.iter().map(|f| fill_of(&s, *f)).collect::<Vec<_>>(), [green.clone(), green.clone(), Paint::solid(blue), green]);
}
/// When the first click makes the Live Paint group and is released in a face covered by a source
/// path with no fill in front of a filled one, the face was made with the filled source's fill, as
/// Make gives it, so the triple-click there matches that fill and not none.
#[test]
fn live_paint_bucket_triple_click_after_making_the_group_under_an_unfilled_path_matches_the_made_fill() {
let mut s = session();
let red = Color::rgb(1.0, 0.0, 0.0);
let (a, b, d) = (rect(&mut s, 0.0, 0.0, 50.0, 50.0), rect(&mut s, 50.0, 0.0, 50.0, 50.0), rect(&mut s, 200.0, 0.0, 50.0, 50.0));
for id in [a, b, d] {
set_fill(&mut s, id, red);
}
let (c, e) = (rect(&mut s, 60.0, 10.0, 30.0, 30.0), rect(&mut s, 300.0, 0.0, 50.0, 50.0));
s.edit("t", |doc, _| {
for id in [c, e] {
doc.node_mut(id).unwrap().appearance.set_fill(Paint::None);
}
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [a.0, b.0, d.0, c.0, e.0]})).unwrap();
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.paint.fill = green.clone();
s.pointer(&PointerEvent::new(PointerKind::Down, 45.0, 25.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 75.0, 25.0), v).unwrap();
let g = vectorcraft_tools::builder::live_paint_at(&s.doc().unwrap().doc, Point::new(25.0, 25.0)).expect("the click made a group");
let faces = faces_at(&s, g, &[(75.0, 25.0), (225.0, 25.0), (325.0, 25.0)]);
assert_eq!(fill_of(&s, faces[0]), green, "the release fills the face under the unfilled path");
assert_eq!([faces[1], faces[2]].map(|f| fill_of(&s, f)), [Paint::solid(red), Paint::None], "Make gave the far faces red and none");
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick, PointerKind::Down, PointerKind::Up, PointerKind::TripleClick] {
s.pointer(&PointerEvent::new(kind, 75.0, 25.0), v).unwrap();
}
assert_eq!([faces[1], faces[2]].map(|f| fill_of(&s, f)), [green, Paint::None], "the triple-click matches the red the face was made with");
}
/// A triple-click whose first click adds paths to a selected Live Paint group and is released in a
/// face of that group matches the face's fill, not the edge around it.
#[test]
fn live_paint_bucket_triple_click_after_merging_across_an_edge_matches_the_face_fill() {
let mut s = session();
let g = live_squares(&mut s, &[0.0]);
let [a] = faces_at(&s, g, &[(25.0, 25.0)])[..] else { panic!("one face") };
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 51.0, 51.0));
paint_parts(&mut s, &all, &Paint::solid(Color::rgb(0.0, 0.0, 0.0)), &[(a, red.clone())]);
let (next, far) = (rect(&mut s, 50.0, 0.0, 50.0, 50.0), rect(&mut s, 200.0, 0.0, 50.0, 50.0));
set_fill(&mut s, next, Color::rgb(0.0, 0.0, 1.0));
set_fill(&mut s, far, Color::rgb(1.0, 0.0, 0.0));
s.execute("select.set", &json!({"ids": [g.0, next.0, far.0]})).unwrap();
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.paint.fill = green.clone();
s.pointer(&PointerEvent::new(PointerKind::Down, 55.0, 25.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 45.0, 25.0), v).unwrap();
let g = vectorcraft_tools::builder::live_paint_at(&s.doc().unwrap().doc, Point::new(25.0, 25.0)).expect("the click merged the paths");
let faces = faces_at(&s, g, &[(25.0, 25.0), (225.0, 25.0)]);
assert_eq!(fill_of(&s, faces[0]), green, "the release fills the group's face");
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick, PointerKind::Down, PointerKind::Up, PointerKind::TripleClick] {
s.pointer(&PointerEvent::new(kind, 45.0, 25.0), v).unwrap();
}
assert_eq!(fill_of(&s, faces[1]), green, "the far face had the red the face had");
}
/// When the first click merges two selected Live Paint groups, a face of the group in front takes
/// its source path's fill, so a triple-click there after a release across an edge matches that fill
/// and not the paint the face had before the merge.
#[test]
fn live_paint_bucket_triple_click_after_merging_two_groups_matches_the_merged_fill() {
let mut s = session();
let back = live_squares(&mut s, &[0.0]);
let source = rect(&mut s, 100.0, 0.0, 50.0, 50.0);
set_fill(&mut s, source, Color::rgb(1.0, 0.0, 0.0));
s.execute("select.set", &json!({"ids": [source.0]})).unwrap();
let front = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
let [f] = faces_at(&s, front, &[(125.0, 25.0)])[..] else { panic!("one face") };
let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0));
paint_parts(&mut s, &[], &Paint::None, &[(f, blue.clone())]);
let (next, far) = (rect(&mut s, 150.0, 0.0, 50.0, 50.0), rect(&mut s, 300.0, 0.0, 50.0, 50.0));
set_fill(&mut s, next, Color::rgb(1.0, 1.0, 0.0));
set_fill(&mut s, far, Color::rgb(1.0, 0.0, 0.0));
s.execute("select.set", &json!({"ids": [back.0, front.0, next.0, far.0]})).unwrap();
let merged = NodeId(s.execute("livePaint.merge", &json!({})).unwrap()["id"].as_u64().unwrap());
let [m] = faces_at(&s, merged, &[(125.0, 25.0)])[..] else { panic!("one face") };
assert_eq!(fill_of(&s, m), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), "Merge gives the front group's face its source's fill");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [back.0, front.0, next.0, far.0]})).unwrap();
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.paint.fill = green.clone();
s.pointer(&PointerEvent::new(PointerKind::Down, 155.0, 25.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 145.0, 25.0), v).unwrap();
let g = vectorcraft_tools::builder::live_paint_at(&s.doc().unwrap().doc, Point::new(125.0, 25.0)).expect("the click merged the groups");
let faces = faces_at(&s, g, &[(125.0, 25.0), (325.0, 25.0)]);
assert_eq!(fill_of(&s, faces[0]), green, "the release fills the front group's face");
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick, PointerKind::Down, PointerKind::Up, PointerKind::TripleClick] {
s.pointer(&PointerEvent::new(kind, 145.0, 25.0), v).unwrap();
}
assert_eq!(fill_of(&s, faces[1]), green, "the far face had the red the merge gave the face");
}
/// When the first click merges paths into a selected Live Paint group whose face has an unplaced
/// gradient, Merge fixes the gradient to the face's fit, so a triple-click there after a release
/// across an edge matches the fixed gradient: a far face whose source has that same fixed gradient
/// takes the bucket's paint.
#[test]
fn live_paint_bucket_triple_click_after_merging_matches_the_fixed_gradient() {
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop};
let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)];
let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))));
let mut s = session();
let g = live_squares(&mut s, &[0.0]);
let [f] = faces_at(&s, g, &[(25.0, 25.0)])[..] else { panic!("one face") };
paint_parts(&mut s, &[], &Paint::None, &[(f, gradient.clone())]);
let (next, far) = (rect(&mut s, 50.0, 0.0, 50.0, 50.0), rect(&mut s, 200.0, 0.0, 50.0, 50.0));
set_fill(&mut s, next, Color::rgb(1.0, 1.0, 0.0));
s.execute("select.set", &json!({"ids": [g.0, next.0]})).unwrap();
let merged = NodeId(s.execute("livePaint.merge", &json!({})).unwrap()["id"].as_u64().unwrap());
let [m] = faces_at(&s, merged, &[(25.0, 25.0)])[..] else { panic!("one face") };
let fixed = fill_of(&s, m);
assert_ne!(fixed, gradient, "Merge fixes the face's gradient to its fit");
s.execute("edit.undo", &json!({})).unwrap();
s.edit("t", |d, _| {
d.node_mut(far).unwrap().appearance.set_fill(fixed.clone());
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [g.0, next.0, far.0]})).unwrap();
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
s.paint.fill = green.clone();
s.pointer(&PointerEvent::new(PointerKind::Down, 55.0, 25.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 45.0, 25.0), v).unwrap();
let g = vectorcraft_tools::builder::live_paint_at(&s.doc().unwrap().doc, Point::new(45.0, 25.0)).expect("the click merged the paths");
let [far_face] = faces_at(&s, g, &[(225.0, 25.0)])[..] else { panic!("the far face") };
assert_eq!(fill_of(&s, far_face), fixed, "the far face keeps its source's fixed gradient");
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick, PointerKind::Down, PointerKind::Up, PointerKind::TripleClick] {
s.pointer(&PointerEvent::new(kind, 45.0, 25.0), v).unwrap();
}
assert_eq!(fill_of(&s, far_face), green, "the far face had the fixed gradient the merge gave the face");
}
/// When the first click merges a line that splits a painted face of the selected Live Paint group,
/// Merge keeps the face's paint in one part only and the other part takes its source path's fill;
/// a triple-click in that other part after a release across an edge matches the source's fill.
#[test]
fn live_paint_bucket_triple_click_after_a_merge_splits_a_face_matches_the_part_fill() {
let mut s = session();
let source = rect(&mut s, 0.0, 0.0, 50.0, 50.0);
set_fill(&mut s, source, Color::rgb(1.0, 0.0, 0.0));
s.execute("select.set", &json!({"ids": [source.0]})).unwrap();
let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
let [f] = faces_at(&s, g, &[(25.0, 25.0)])[..] else { panic!("one face") };
paint_parts(&mut s, &[], &Paint::None, &[(f, Paint::solid(Color::rgb(0.0, 0.0, 1.0)))]);
let line = NodeId(s.execute("shape.line", &json!({"x1": 40, "y1": -10, "x2": 40, "y2": 60})).unwrap()["id"].as_u64().unwrap());
let next = rect(&mut s, 50.0, 0.0, 50.0, 50.0);
set_fill(&mut s, next, Color::rgb(1.0, 1.0, 0.0));
let (red_far, blue_far) = (rect(&mut s, 200.0, 0.0, 50.0, 50.0), rect(&mut s, 300.0, 0.0, 50.0, 50.0));
set_fill(&mut s, red_far, Color::rgb(1.0, 0.0, 0.0));
set_fill(&mut s, blue_far, Color::rgb(0.0, 0.0, 1.0));
let ids = json!({"ids": [g.0, line.0, next.0, red_far.0, blue_far.0]});
s.execute("select.set", &ids).unwrap();
let merged = NodeId(s.execute("livePaint.merge", &json!({})).unwrap()["id"].as_u64().unwrap());
let parts = faces_at(&s, merged, &[(20.0, 25.0), (45.0, 25.0)]);
assert_eq!(
parts.iter().map(|p| fill_of(&s, *p)).collect::<Vec<_>>(),
[Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0))],
"Merge keeps the paint in the part that holds the face's inside point"
);
s.execute("edit.undo", &json!({})).unwrap();
s.execute("select.set", &ids).unwrap();
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.paint.fill = green.clone();
s.pointer(&PointerEvent::new(PointerKind::Down, 55.0, 25.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 45.0, 25.0), v).unwrap();
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick, PointerKind::Down, PointerKind::Up, PointerKind::TripleClick] {
s.pointer(&PointerEvent::new(kind, 45.0, 25.0), v).unwrap();
}
let g = vectorcraft_tools::builder::live_paint_at(&s.doc().unwrap().doc, Point::new(45.0, 25.0)).expect("the click merged the paths");
let far = faces_at(&s, g, &[(225.0, 25.0), (325.0, 25.0)]);
assert_eq!(far.iter().map(|p| fill_of(&s, *p)).collect::<Vec<_>>(), [green, Paint::solid(Color::rgb(0.0, 0.0, 1.0))]);
}
/// A triple-click whose first click makes the Live Paint group from the selected paths matches the
/// fill the face was made with.
#[test]
@@ -3978,6 +4238,116 @@ fn live_paint_bucket_double_and_triple_click_paint_joined_and_same_stroke_edges(
assert_eq!(node(&s, apart[0]).appearance.stroke_paint(), black);
}
/// A double-click whose two clicks land on two joined edges paints every edge joined to them that
/// had their stroke: the edge the first click painted still joins the others.
#[test]
fn live_paint_bucket_double_click_across_a_junction_paints_the_joined_edges() {
// A square with a line across its middle, cut at x = 30 and x = 70 by two lines from the top: the
// middle line's three edges join end to end.
let mut s = session();
let mut ids = vec![rect(&mut s, 0.0, 0.0, 100.0, 100.0).0];
for anchors in [
json!([{"x": 0, "y": 50}, {"x": 100, "y": 50}]),
json!([{"x": 30, "y": 0}, {"x": 30, "y": 70}]),
json!([{"x": 70, "y": 0}, {"x": 70, "y": 70}]),
] {
ids.push(s.execute("path.create", &json!({ "anchors": anchors })).unwrap()["id"].as_u64().unwrap());
}
s.execute("select.set", &json!({"ids": ids})).unwrap();
let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
let (black, red) = (Paint::solid(Color::rgb(0.0, 0.0, 0.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)));
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 101.0, 101.0));
paint_parts(&mut s, &all, &red, &[]);
let middle = edges_in(&s, g, Rect::new(-1.0, 49.0, 101.0, 51.0));
assert_eq!(middle.len(), 3, "the middle line's three edges");
paint_parts(&mut s, &middle, &black, &[]);
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.paint.stroke = green.clone();
let shift = Mods { shift: true, ..Default::default() };
for (kind, x) in
[(PointerKind::Down, 50.0), (PointerKind::Up, 50.0), (PointerKind::Down, 85.0), (PointerKind::Up, 85.0), (PointerKind::DoubleClick, 85.0)]
{
s.pointer(&PointerEvent::new(kind, x, 50.0).with_mods(shift), v).unwrap();
}
assert_eq!(middle.iter().map(|e| node(&s, *e).appearance.stroke_paint()).collect::<Vec<_>>(), [green.clone(), green.clone(), green]);
// `through` takes edge ids, with scope "connected" only.
for p in [
json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": "x"}),
json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": [-1]}),
json!({"group": g.0, "point": [15, 50], "scope": "samePaint", "through": []}),
json!({"group": g.0, "point": [15, 50], "through": []}),
] {
assert!(s.execute("livePaint.strokeEdge", &p).is_err(), "{p}");
}
}
/// A double-click whose second press lands on the next joined edge and is released back on the
/// edge the first click painted (at the end of the line) matches that edge's stroke paint from
/// before the first click, and the edge the second press painted still joins the edge past it.
#[test]
fn live_paint_bucket_double_click_released_back_on_the_first_edge_paints_the_joined_edges() {
let mut s = session();
let mut ids = vec![rect(&mut s, 0.0, 0.0, 100.0, 100.0).0];
for anchors in [
json!([{"x": 0, "y": 50}, {"x": 100, "y": 50}]),
json!([{"x": 30, "y": 0}, {"x": 30, "y": 70}]),
json!([{"x": 70, "y": 0}, {"x": 70, "y": 70}]),
] {
ids.push(s.execute("path.create", &json!({ "anchors": anchors })).unwrap()["id"].as_u64().unwrap());
}
s.execute("select.set", &json!({"ids": ids})).unwrap();
let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
let (black, red) = (Paint::solid(Color::rgb(0.0, 0.0, 0.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)));
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 101.0, 101.0));
paint_parts(&mut s, &all, &red, &[]);
let middle = edges_in(&s, g, Rect::new(-1.0, 49.0, 101.0, 51.0));
assert_eq!(middle.len(), 3, "the middle line's three edges");
paint_parts(&mut s, &middle, &black, &[]);
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.paint.stroke = green.clone();
let shift = Mods { shift: true, ..Default::default() };
for (kind, x) in
[(PointerKind::Down, 15.0), (PointerKind::Up, 15.0), (PointerKind::Down, 50.0), (PointerKind::Up, 15.0), (PointerKind::DoubleClick, 15.0)]
{
s.pointer(&PointerEvent::new(kind, x, 50.0).with_mods(shift), v).unwrap();
}
assert_eq!(middle.iter().map(|e| node(&s, *e).appearance.stroke_paint()).collect::<Vec<_>>(), [green.clone(), green.clone(), green]);
}
/// A triple-click whose second press holds Cmd (it goes to the selection tool Cmd lends) matches
/// the fill the face had before the first click: the lent press counts as one that paints nothing.
#[test]
fn live_paint_bucket_triple_click_with_a_cmd_press_between_matches_the_fill_before() {
let mut s = session();
let g = live_squares(&mut s, &[0.0, 50.0, 100.0, 150.0]);
let [a, b, c, d] = faces_at(&s, g, &[(25.0, 25.0), (75.0, 25.0), (125.0, 25.0), (175.0, 25.0)])[..] else { panic!("four faces") };
let (red, blue) = (Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 201.0, 51.0));
paint_parts(&mut s, &all, &Paint::solid(Color::rgb(0.0, 0.0, 0.0)), &[(a, red.clone()), (b, red.clone()), (c, blue.clone()), (d, red.clone())]);
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.paint.fill = green.clone();
let cmd = Mods { cmd: true, ..Default::default() };
for (kind, m) in [
(PointerKind::Down, Mods::default()),
(PointerKind::Up, Mods::default()),
(PointerKind::Down, cmd),
(PointerKind::Up, cmd),
(PointerKind::Down, Mods::default()),
(PointerKind::Up, Mods::default()),
(PointerKind::TripleClick, Mods::default()),
] {
s.pointer(&PointerEvent::new(kind, 25.0, 25.0).with_mods(m), v).unwrap();
}
assert_eq!(s.tool_id(), "livePaintBucket");
assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), green.clone(), blue, green]);
}
/// A `scope` that is not one of the three, a `match` that is not a paint or is given with a scope
/// that compares none, and a scope with a drag's points are refused; nothing changes.
#[test]
@@ -5688,6 +6058,57 @@ fn a_trace_run_applies_only_in_its_own_document() {
}
}
/// A trace prepared before File › Revert doesn't apply after it, even when the document keeps its
/// uid and the restored image, object and settings are the same: both trace commands drop the
/// trace handed in and trace the restored image again, as one undo step. Reverting another
/// document, or a revert that fails, leaves the run current, and a trace prepared after the revert
/// applies as usual.
#[test]
fn a_trace_run_prepared_before_a_revert_does_not_apply_after_it() {
let p = json!({"params": {"ignoreWhite": true}});
for command in ["imageTrace.make", "imageTrace.makeAndExpand"] {
let mut direct = session();
image_doc(&mut direct);
let want = direct.execute(command, &p).unwrap();
let mut s = session();
let img = image_doc(&mut s);
let a = s.active_index().unwrap();
let copy = (*s.doc().unwrap().doc).clone();
let run = cmd::TraceRun::prepare(&s, command, &p).unwrap();
let traced = run.run(&|_, _| true).unwrap();
let b = s.add_document(copy.clone(), None);
assert!(s.replace_document(b, copy.clone()));
assert!(s.set_active(a));
assert!(run.current(&s) && !run.reverted(&s), "{command}: another document reverted");
assert!(!s.replace_document(s.documents().len(), copy.clone()));
assert!(run.current(&s) && !run.reverted(&s), "{command}: a revert that failed");
let (uid, reverts) = (s.doc().unwrap().uid, s.doc().unwrap().reverts);
assert!(s.replace_document(a, copy));
assert_eq!(s.doc().unwrap().uid, uid, "{command}: the tab keeps its uid");
assert_eq!(s.doc().unwrap().reverts, reverts + 1, "{command}");
assert!(!run.current(&s), "{command}: reverted");
assert!(run.reverted(&s), "{command}");
traced.hand_in(&mut s);
let traces = cmd::TraceRun::traces_on_this_thread();
let got = s.execute(run.command(), run.params()).unwrap();
assert_eq!(cmd::TraceRun::traces_on_this_thread(), traces + 1, "{command}: traced again");
assert!(s.trace_hand_off.is_none(), "{command}: dropped");
assert_eq!(got, want, "{command}");
let g = NodeId(got["id"].as_u64().unwrap());
assert_eq!(node(&s, g), node(&direct, g), "{command}");
s.execute("edit.undo", &json!({})).unwrap();
assert!(matches!(node(&s, img).kind, NodeKind::Image(_)), "{command}: one undo step");
// A trace prepared after the revert is handed in and applied without tracing again.
let after = cmd::TraceRun::prepare(&s, command, run.params()).unwrap();
let traced = after.run(&|_, _| true).unwrap();
assert!(after.current(&s) && !after.reverted(&s), "{command}: prepared after the revert");
traced.hand_in(&mut s);
let traces = cmd::TraceRun::traces_on_this_thread();
s.execute(after.command(), after.params()).unwrap();
assert_eq!(cmd::TraceRun::traces_on_this_thread(), traces, "{command}: the trace handed in applied");
}
}
/// A plug-in run that calls Image Trace and then fails leaves a trace handed in for the command in
/// place, as it leaves the document.
#[test]
+71
View File
@@ -188,6 +188,77 @@ fn align_stroke_reaches_the_characters_stroke() {
assert!(aligns.contains(&StrokeAlign::Inside) && aligns.contains(&StrokeAlign::Outside), "{aligns:?}");
}
/// The bounds of type `t`'s glyph outlines in text space.
fn glyph_bounds(t: &TextObject) -> kurbo::Rect {
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
let mut all = kurbo::BezPath::new();
for g in &lay.glyphs {
all.extend(g.outline.iter());
}
kurbo::Shape::bounding_box(&all)
}
/// Create Outlines on type scaled 300% across and 100% down: the canvas strokes the characters in
/// text space and then scales them, so the outlined stroke is filled art three times as thick
/// across upright stems as across level bars, not a live stroke of one mean weight.
#[test]
fn create_outlines_keeps_the_character_strokes_thickness_under_an_uneven_scale() {
let mut s = session();
let id = stroked_text(&mut s);
run(&mut s, "stroke.set", json!({"weight": 4, "join": "round", "cap": "round"}));
run(&mut s, "object.scale", json!({"ids": [id.0], "sx": 300, "sy": 100}));
let t = text(&s, id);
let [a, b, c, d, ..] = t.xf.as_coeffs();
assert!((a - 3.0).abs() < 1e-9 && b.abs() < 1e-9 && c.abs() < 1e-9 && (d - 1.0).abs() < 1e-9, "{:?}", t.xf);
let w = t.runs[0].style.stroke_width;
let gb = glyph_bounds(&t);
run(&mut s, "select.set", json!({ "ids": [id.0] }));
let g = run(&mut s, "type.createOutlines", json!({}))["ids"][0].as_u64().unwrap();
let doc = &s.doc().unwrap().doc;
let group = doc.node(NodeId(g)).unwrap();
let mut strokes: Option<kurbo::Rect> = None;
for c in group.children().unwrap() {
assert!(c.appearance.stroke().is_none(), "no live stroke of one weight is left");
if c.appearance.fill_paint() == Paint::solid(Color::rgb8(255, 0, 0)) {
let cb = c.geometric_bounds().unwrap();
strokes = Some(strokes.map_or(cb, |s| s.union(cb)));
}
}
// Round joins and caps reach half the weight past the glyphs in text space, then scale.
let want = t.xf.transform_rect_bbox(gb.inflate(w / 2.0, w / 2.0));
let got = strokes.expect("filled character strokes");
assert!((got.width() - want.width()).abs() < 0.1 && (got.height() - want.height()).abs() < 0.1, "{got:?} for {want:?}");
assert!((got.height() - (gb.height() + w)).abs() < 0.1, "level bars keep the weight: {got:?}");
}
/// Under a uniform scale and a rotation the outlined characters keep a live stroke, its weight
/// and dashes scaled with them.
#[test]
fn create_outlines_keeps_a_live_character_stroke_under_a_uniform_scale_and_rotation() {
let mut s = session();
let id = stroked_text(&mut s);
run(&mut s, "stroke.set", json!({"weight": 4, "dash": [6, 2]}));
run(&mut s, "object.scale", json!({"ids": [id.0], "sx": 200, "sy": 200}));
run(&mut s, "object.rotate", json!({"angle": 30}));
let t = text(&s, id);
let k = t.xf.determinant().abs().sqrt();
assert!((k - 2.0).abs() < 1e-9, "{:?}", t.xf);
let st = t.runs[0].style.clone();
let dash = st.stroke_dash.as_ref().unwrap().pattern.clone();
let glyphs = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).glyphs.len();
run(&mut s, "select.set", json!({ "ids": [id.0] }));
let g = run(&mut s, "type.createOutlines", json!({}))["ids"][0].as_u64().unwrap();
let doc = &s.doc().unwrap().doc;
let pieces = doc.node(NodeId(g)).unwrap().children().unwrap().to_vec();
assert_eq!(pieces.len(), glyphs, "one path for each glyph, no filled strokes");
for p in &pieces {
let ps = p.appearance.stroke().expect("a live stroke");
assert!((ps.width - st.stroke_width * k).abs() < 1e-6, "{} for {}", ps.width, st.stroke_width * k);
let got = &ps.dash.as_ref().unwrap().pattern;
assert!(got.iter().zip(&dash).all(|(g, d)| (g - d * k).abs() < 1e-6), "{got:?} for {dash:?}");
}
}
/// Copying type's appearance onto a path keeps its characters' stroke alignment (the Eyedropper's
/// own stroke attributes have none, on paths as on type).
#[test]
+62
View File
@@ -1034,6 +1034,68 @@ fn a_repainted_wedge_sets_its_label_color_when_pasted_without_formatting() {
assert_eq!(pasted, labels(&s, p), "copied as {before:?}");
}
/// Wedges linked to a global swatch that the destination document gives a dark color, merged on Paste without
/// Formatting, give their legend labels white characters, as a redraw does; added under a new name, they keep the
/// copied light color and black labels.
#[test]
fn wedges_merged_into_a_dark_swatch_give_white_labels_when_pasted_without_formatting() {
let csv = ",North,South\nP,1,1";
fn labels(s: &Session, id: NodeId) -> Vec<(String, Paint)> {
let mut out = vec![];
node(s, id).walk(&mut |n| {
if let NodeKind::Text(t) = &n.kind
&& ["North", "South"].contains(&t.plain_text().as_str())
{
out.push((t.plain_text(), t.first_style().fill.clone()));
}
});
out
}
let both = |c: Color| vec![("North".to_string(), Paint::solid(c)), ("South".to_string(), Paint::solid(c))];
for (conflict, expected) in [("merge", Color::WHITE), ("add", Color::BLACK)] {
let mut s = session();
let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "csv": csv})).unwrap());
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap();
s.execute("swatch.new", &json!({"name": "Ink", "color": "#ffffff", "global": true})).unwrap();
let mut wedges = vec![];
node(&s, g).walk(&mut |m| {
if let NodeKind::Path { .. } = m.kind {
wedges.push(m.id.0);
}
});
s.execute("paint.setFill", &json!({"ids": wedges, "swatch": "Ink"})).unwrap();
s.execute("graph.setData", &json!({"id": g.0, "csv": csv})).unwrap();
assert_eq!(labels(&s, g), both(Color::BLACK), "light wedges have black labels");
copy(&mut s, &[g]);
new_doc(&mut s);
s.execute("swatch.new", &json!({"name": "Ink", "color": "#000000", "global": true})).unwrap();
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({"swatchConflict": conflict})).unwrap())[0];
let pasted = labels(&s, p);
assert_eq!(pasted, both(expected), "{conflict}");
s.execute("graph.setData", &json!({"id": p.0, "csv": csv})).unwrap();
assert_eq!(pasted, labels(&s, p), "{conflict}: as a redraw sets them");
}
}
/// An object linked to a graphic style and to a swatch merged with the document's keeps its graphic style link when
/// pasted without formatting, and its color shows the document's swatch.
#[test]
fn a_merged_swatch_keeps_graphic_style_links_when_pasted_without_formatting() {
let mut s = session();
let r = swatched_rect(&mut s, "Ink", "#ffffff");
sel(&mut s, &[r]);
s.execute("graphicStyle.new", &json!({"name": "Sun"})).unwrap();
copy(&mut s, &[r]);
new_doc(&mut s);
s.execute("swatch.new", &json!({"name": "Ink", "color": "#000000", "global": true})).unwrap();
let v = s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap();
assert_eq!(v["merged"], 1);
let p = ids_of(&v)[0];
let style = node(&s, p).extras().graphic_style.and_then(|id| doc(&s).graphic_style_by_id(id)).map(|g| g.name.clone());
assert_eq!(style.as_deref(), Some("Sun"));
assert_eq!(fill(&s, p), linked(hex("#000000"), "Ink", 1.0));
}
/// When one pie's wedge of a series is repainted and another pie's wedge of that series is not, each pasted legend label
/// takes the contrast of the wedge it is in.
#[test]
+1 -1
View File
@@ -40,7 +40,7 @@ fn close(a: f64, b: f64) -> bool {
fn segment_angles(p: &PathData) -> Vec<f64> {
p.subpaths
.iter()
.flat_map(|sp| sp.anchors.windows(2).map(|w| w[1].p - w[0].p))
.flat_map(|sp| sp.anchors.iter().zip(sp.anchors.iter().skip(1)).map(|(a, b)| b.p - a.p))
.filter(|v| v.hypot() > 1e-9)
.map(|v| (-v.y).atan2(v.x).to_degrees().rem_euclid(90.0))
.collect()
+5 -5
View File
@@ -890,7 +890,7 @@ fn curvature_rubber_band_is_the_path_the_click_makes() {
s.pointer(&PointerEvent::new(PointerKind::Up, 450.0, 400.0), v).unwrap();
let made = path(&s, id).subpaths[0].clone();
assert_eq!(made.anchors.len(), 4);
let tail = vectorcraft_geom::SubPath::new(made.anchors[1..].to_vec(), false);
let tail = vectorcraft_geom::SubPath::new(made.anchors.to_vec()[1..].to_vec(), false);
assert_eq!(preview, bez(&tail));
}
@@ -1218,7 +1218,7 @@ fn scissors_cut_ellipse_end_drags_alone() {
s.pointer(&PointerEvent::new(PointerKind::Up, cut.x + 8.0, cut.y + 8.0).with_mods(m), v).unwrap();
assert_eq!(undo_steps(&s), undo + 1);
let after = path(&s, id);
let (old, new) = (&sp.anchors, &after.subpaths[0].anchors);
let (old, new) = (&sp.anchors.to_vec(), &after.subpaths[0].anchors.to_vec());
assert_eq!(new.len(), old.len());
assert_eq!(new[1..], old[1..], "only the dragged end moves (at anchor: {at_anchor}, {m:?})");
let d = Point::new(cut.x + 8.0, cut.y + 8.0) - cut;
@@ -1572,7 +1572,7 @@ fn a_short_smooth_drag_leaves_the_rest_of_long_segments_alone() {
drag(&mut s, "smooth", &[(195.0, 194.0), (205.0, 194.0)], Mods::default());
let p = path(&s, id);
assert_ne!(p, before, "the bump is smoothed");
let a = &p.subpaths[0].anchors;
let a = &p.subpaths[0].anchors.to_vec();
let (first, second, last) = (a[0], a[1], a[a.len() - 1]);
assert!(first.p == Point::new(50.0, 200.0) && !first.has_out() && !second.has_in(), "the left side is a line still: {first:?} {second:?}");
assert!(last.p == Point::new(350.0, 200.0) && !last.has_in() && !a[a.len() - 2].has_out(), "and the right one: {last:?}");
@@ -1783,7 +1783,7 @@ fn smoothing_over_a_closed_paths_first_anchor_keeps_its_start() {
assert_ne!(after, before, "the bump is smoothed");
assert_starts_nearest(&after, old, 12.0);
let kept = &after.subpaths[0].anchors;
for a in &before.subpaths[0].anchors[2..=10] {
for a in &before.subpaths[0].anchors.to_vec()[2..=10] {
assert!(kept.iter().any(|k| k.p == a.p), "{:?} is out of reach and stays: {kept:?}", a.p);
}
s.execute("edit.undo", &json!({})).unwrap();
@@ -3885,7 +3885,7 @@ fn pen_cmd_selected_anchors_are_what_copy_and_cut_take() {
assert!(left.is_empty());
assert!(s.doc().unwrap().selection.objects.is_empty());
assert_eq!(s.clipboard.nodes.len(), 1);
assert_eq!(s.clipboard.nodes[0].path_data().unwrap().subpaths[0].anchors, original.subpaths[0].anchors[1..3]);
assert_eq!(s.clipboard.nodes[0].path_data().unwrap().subpaths[0].anchors, original.subpaths[0].anchors.to_vec()[1..3]);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(paths(&s), vec![(id, original.clone())]);
assert_eq!(s.doc().unwrap().selection, picked);
+22
View File
@@ -119,6 +119,28 @@ fn strokes_span_the_targets_too() {
assert!(ga.start.x < 0.0 && ga.end.x > 400.0, "the stroke's box, half its weight out: {ga:?}");
}
#[test]
fn a_lower_stroke_row_spans_the_box_that_row_paints() {
let mut s = session();
let a = rect(&mut s, 0.0, 50.0, 100.0, 100.0);
let b = rect(&mut s, 300.0, 50.0, 100.0, 100.0);
// [Fill, Stroke 40 pt, Stroke 1 pt] on both.
s.execute("appearance.addStroke", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("stroke.set", &json!({"ids": [a.0, b.0], "item": 1, "weight": 40})).unwrap();
for aligned in [false, true] {
s.execute("paint.setStroke", &json!({"ids": [a.0, b.0], "item": 1, "aligned": aligned, "gradient": black_to_white(), "span": "selection"}))
.unwrap();
for id in [a, b] {
let Paint::Gradient(g) = &s.doc().unwrap().doc.node(id).unwrap().appearance.stroke_at(Some(1)).unwrap().paint else {
panic!("expected a gradient on stroke row 1")
};
// The 40 pt row reaches 20 pt past the union 0..400, not the 1 pt topmost stroke's 0.5 pt.
let geom = g.geom.expect("placed in document coordinates");
assert!(near(geom.start, Point::new(-20.0, 100.0)) && near(geom.end, Point::new(420.0, 100.0)), "aligned {aligned}, {id:?}: {geom:?}");
}
}
}
#[test]
fn the_new_art_default_stays_unplaced() {
let mut s = session();
+69
View File
@@ -231,6 +231,75 @@ fn deleting_a_spot_swatch_takes_the_process_plates_of_the_stops_it_unlinks() {
assert_eq!(gradient(&s, id).gradient.stops[1], linked, "undo brings back the link and the plates");
}
/// The stops of the gradients the merge test puts in place: the art's fill, gradient swatch "Glow",
/// graphic style "Style", the art of brush "Brush" and the fill new art takes.
fn merge_test_stops(s: &Session, id: NodeId) -> Vec<(&'static str, Vec<GradientStop>)> {
let d = doc(s);
let stops = |p: Paint| match p {
Paint::Gradient(g) => g.gradient.stops,
p => panic!("not a gradient: {p:?}"),
};
let style = d.graphic_style("Style").unwrap().appearance.items.iter().find_map(|it| match it {
vectorcraft_doc::AppearanceItem::Fill(f) => Some(f.paint.clone()),
vectorcraft_doc::AppearanceItem::Stroke(_) => None,
});
let mut brush = None;
for n in vectorcraft_brush::find(d, "Brush").unwrap().art() {
n.walk(&mut |m| {
if brush.is_none() && matches!(m.appearance.fill_paint(), Paint::Gradient(_)) {
brush = Some(m.appearance.fill_paint());
}
});
}
vec![
("art", stops(d.node(id).unwrap().appearance.fill_paint())),
("gradient swatch", stops(d.swatch("Glow").unwrap().paint.clone())),
("graphic style", stops(style.unwrap())),
("brush art", stops(brush.unwrap())),
("new art", stops(s.paint.fill.clone())),
]
}
#[test]
fn merging_swatches_takes_the_process_plates_of_the_stops_it_relinks() {
// Kept swatch "Keep": spot, global process, and process that isn't global.
for (spot, global) in [(true, true), (false, true), (false, false)] {
let (mut s, id) = setup();
run(&mut s, "swatch.new", json!({"name": "Keep", "color": "#00ff00", "spot": spot, "global": global}));
run(&mut s, "swatch.new", json!({"name": "Other", "color": {"c": 1, "m": 0, "y": 0, "k": 0}, "spot": true}));
// Ink at 50 % over a 30 % cyan plate, and Other over its own 20 % magenta plate, which the
// merge leaves alone.
let plated = json!({"stops": [
{"offset": 0, "swatch": "Ink", "tint": 50, "plates": [0.3, 0, 0, 0]},
{"offset": 1, "swatch": "Other", "plates": [0, 0.2, 0, 0]},
]});
run(&mut s, "paint.editGradient", plated.clone());
run(&mut s, "swatch.new", json!({"name": "Glow", "gradient": plated}));
run(&mut s, "graphicStyle.new", json!({"name": "Style"}));
run(&mut s, "brush.new", json!({"type": "art", "name": "Brush"}));
s.paint.fill = doc(&s).node(id).unwrap().appearance.fill_paint();
let before = merge_test_stops(&s, id);
let kept = doc(&s).linked_color(doc(&s).swatch("Keep").unwrap().paint.color().unwrap(), spot);
assert!(before.iter().all(|(_, st)| st[0].plates == Some([0.3, 0.0, 0.0, 0.0])), "{before:?}");
run(&mut s, "swatch.merge", json!({"names": ["Keep", "Ink"]}));
let after = merge_test_stops(&s, id);
// The stop shows its tint of the kept color, unlinked when the kept swatch isn't global.
let (link, tint, color) = if global { (Some("Keep"), 0.5, kept.tinted(0.5)) } else { (None, 1.0, kept.tinted(0.5)) };
for (place, st) in &after {
let what = format!("spot {spot}, global {global}, {place}: {st:?}");
assert_eq!((st[0].swatch.as_deref(), st[0].tint, st[0].plates), (link, tint, None), "{what}");
assert_eq!(st[0].color, color, "{what}");
assert_eq!((st[1].swatch.as_deref(), st[1].plates), (Some("Other"), Some([0.0, 0.2, 0.0, 0.0])), "{what}");
}
run(&mut s, "edit.undo", json!({}));
assert_eq!(merge_test_stops(&s, id), before, "undo brings back the links and the plates");
run(&mut s, "edit.redo", json!({}));
assert_eq!(merge_test_stops(&s, id), after, "redo merges again");
}
}
#[test]
fn radial_spot_gradients_mixed_with_other_inks_export_as_device_n_shadings() {
let (mut s, _) = setup();
+47
View File
@@ -3299,6 +3299,32 @@ fn select_all_on_artboard_refuses_an_artboard_past_u32() {
assert!(selected(&s).is_empty());
}
/// All on Active Artboard refuses an `artboard` that is not a whole number, naming the parameter,
/// and leaves the selection as it was; a whole number past the last artboard is `no such
/// artboard`. Left out or null, it takes the first artboard.
#[test]
fn select_all_on_artboard_refuses_an_artboard_that_is_not_a_whole_number() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 2, "artboardLayout": {"layout": "row", "spacing": 0}})).unwrap();
let (first, second) = (rect(&mut s, 10.0, 10.0, 20.0, 20.0), rect(&mut s, 110.0, 10.0, 20.0, 20.0));
for bad in [json!("1"), json!(-1), json!(1.5), json!(true), json!([1]), json!({})] {
s.execute("select.none", &json!({})).unwrap();
let err = s.execute("select.allOnArtboard", &json!({"artboard": bad})).unwrap_err().to_string();
assert_eq!(err, "invalid parameters for `select.allOnArtboard`: `artboard` must be a whole number", "{bad}");
assert!(selected(&s).is_empty(), "{bad}");
}
s.execute("select.none", &json!({})).unwrap();
assert_eq!(s.execute("select.allOnArtboard", &json!({"artboard": 9})).unwrap_err().to_string(), "no such artboard");
assert!(selected(&s).is_empty());
for p in [json!({}), json!({"artboard": null}), json!({"artboard": 0})] {
s.execute("select.none", &json!({})).unwrap();
s.execute("select.allOnArtboard", &p).unwrap();
assert_eq!(selected(&s), vec![first], "{p}");
}
s.execute("select.allOnArtboard", &json!({"artboard": 1})).unwrap();
assert_eq!(selected(&s), vec![second]);
}
#[test]
fn save_and_recall_selection() {
let mut s = session();
@@ -4605,6 +4631,27 @@ fn artboard_guides_go_with_their_artboard() {
assert_eq!((guides(&s).len(), selected_guides(&s)), (3, vec![0, 1]));
}
/// `guide.add` refuses an `artboard` that is not a whole number, naming the parameter, and adds no
/// guide; a whole number past the last artboard is `no such artboard`. Null makes a canvas guide,
/// and a whole number an artboard guide.
#[test]
fn guide_add_refuses_an_artboard_that_is_not_a_whole_number() {
let mut s = session();
s.execute("artboard.new", &json!({"x": 900, "y": 0, "width": 400, "height": 300})).unwrap();
let add = |s: &mut Session, artboard: Value| s.execute("guide.add", &json!({"vertical": true, "pos": 10, "artboard": artboard}));
for bad in [json!("1"), json!(-1), json!(1.5), json!(true), json!([1]), json!({})] {
let err = add(&mut s, bad.clone()).unwrap_err().to_string();
assert_eq!(err, "invalid parameters for `guide.add`: `artboard` must be a whole number", "{bad}");
}
assert_eq!(add(&mut s, json!(9)).unwrap_err().to_string(), "no such artboard");
assert!(s.doc().unwrap().doc.ruler_guides().is_empty());
add(&mut s, Value::Null).unwrap();
add(&mut s, json!(1)).unwrap();
let d = &s.doc().unwrap().doc;
let boards: Vec<_> = d.ruler_guides().iter().map(|g| g.artboard).collect();
assert_eq!(boards, [None, Some(d.artboards[1].id)]);
}
/// #451: a guide dragged out of a ruler snaps (to the art's corners, side midpoints and anchors,
/// the artboards' edges and centres) and is made in one undo step where it is released over the
/// canvas; with the Artboard tool it is an artboard guide of the active artboard.
+23
View File
@@ -717,6 +717,29 @@ fn type_reports_a_gradient_when_any_glyph_expands() {
assert_eq!(gradients_and_type(&s), (1, 0), "the large glyph keeps its gradient");
}
/// Type scaled unevenly outlines its characters' stroke as a filled path, so a gradient on that
/// stroke becomes a gradient fill: the query reports it, and Expand turns it into art.
#[test]
fn type_reports_a_stroke_gradient_its_uneven_scale_turns_into_a_fill() {
let mut s = session();
let t = run(&mut s, "text.create", json!({"x": 50, "y": 100, "text": "Hi", "size": 48}))["id"].as_u64().unwrap();
run(&mut s, "select.set", json!({"ids": [t]}));
run(
&mut s,
"paint.setStroke",
json!({"gradient": {"kind": "linear", "spread": "repeat", "repeats": 100, "start": [50, 100], "end": [70, 100],
"stops": [{"offset": 0, "color": "#ffff00"}, {"offset": 1, "color": "#004080"}]}}),
);
run(&mut s, "stroke.set", json!({"weight": 4}));
let info = run(&mut s, "object.expand.info", json!({}));
assert_eq!(info["gradient"], json!(false), "a live stroke's gradient is not a fill");
run(&mut s, "object.scale", json!({"ids": [t], "sx": 300, "sy": 100}));
let info = run(&mut s, "object.expand.info", json!({}));
assert_eq!((info["gradient"].clone(), info["fill"].clone()), (json!(true), json!(true)));
run(&mut s, "object.expand", json!({}));
assert_eq!(gradients_and_type(&s), (0, 0), "the filled strokes' gradients became art");
}
/// The same rule for type in the art of a symbol instance that Object expands. The symbol's art
/// is the type scaled down (its "i" about 2.5 pt wide), so its glyphs need more runs than are
/// written with 0.002 pt runs (over a 0.2 pt vector).
+29
View File
@@ -1722,6 +1722,35 @@ fn text_set_format() {
assert_eq!(t.para.composer, vectorcraft_doc::Composer::EveryLine);
}
/// `text.setFormat {composer}` takes the two Middle Eastern & South Asian and the two Standard
/// composers, each per paragraph and one undo step; any other value is refused and names them all.
#[test]
fn text_set_format_takes_the_four_composers() {
use vectorcraft_doc::Composer;
let mut s = session();
let r = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "One\nTwo"})).unwrap();
let id = NodeId(r["id"].as_u64().unwrap());
let composers = |s: &Session| {
let NodeKind::Text(t) = node(s, id).kind else { panic!() };
[t.para_at(0).composer, t.para_at(1).composer]
};
assert_eq!(composers(&s), [Composer::EveryLine; 2], "new type is ME&SA Every-line");
for (value, want) in [
("singleLine", Composer::SingleLine),
("standardSingleLine", Composer::StandardSingleLine),
("standardEveryLine", Composer::StandardEveryLine),
("everyLine", Composer::EveryLine),
] {
s.execute("text.setFormat", &json!({"ids": [id.0], "composer": value, "start": 4, "end": 4})).unwrap();
assert_eq!(composers(&s), [Composer::EveryLine, want], "{value}: only the second paragraph");
}
s.execute("text.setFormat", &json!({"ids": [id.0], "composer": "standardEveryLine"})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(composers(&s), [Composer::EveryLine; 2], "one undo step");
let e = s.execute("text.setFormat", &json!({"ids": [id.0], "composer": "standard"})).unwrap_err().to_string();
assert!(e.contains("standardSingleLine") && e.contains("standardEveryLine"), "{e}");
}
#[test]
fn stroke_advanced_scale_swap_flip() {
let mut s = session();
+2 -1
View File
@@ -704,10 +704,11 @@ fn effect_params_are_the_effects_own() {
fn an_effect_parameter_without_a_default_is_held_to_its_type() {
use crate::cmd::params::undefaulted_type;
use vectorcraft_render::effects::effect_catalog;
// Read by checks of their own: a stored texture or a texture to load, an SVG filter, a Warp's
// Read by checks of their own: a stored texture or a texture to load, an SVG filter and its axes, a Warp's
// map and the style of Crop Marks.
let own_check = |effect: &str, key: &str| match key {
"textureImage" | "name" | "xml" => true,
"axes" => effect == "svg.filter",
"version" => effect.starts_with("warp."),
"style" => effect == "cropMarks",
_ => false,
+10 -10
View File
@@ -73,8 +73,8 @@ fn simplify_refits_only_the_run_between_direct_selected_anchors() {
assert_eq!(out["after"].as_u64(), Some(len as u64));
assert!(len < 101 - 30, "{len}");
let end = len - 41;
assert_eq!(sp.anchors[..20], original.anchors[..20], "the anchors before the run");
assert_eq!(sp.anchors[end + 1..], original.anchors[61..], "the anchors after the run");
assert_eq!(sp.anchors.to_vec()[..20], original.anchors.to_vec()[..20], "the anchors before the run");
assert_eq!(sp.anchors.to_vec()[end + 1..], original.anchors.to_vec()[61..], "the anchors after the run");
assert_eq!((sp.anchors[20].p, sp.anchors[20].h_in), (original.anchors[20].p, original.anchors[20].h_in));
assert_eq!((sp.anchors[end].p, sp.anchors[end].h_out), (original.anchors[60].p, original.anchors[60].h_out));
for i in 0..20 {
@@ -100,7 +100,7 @@ fn separate_runs_on_one_path_simplify_independently_in_one_step() {
let id = wave(&mut s);
select_anchors(&mut s, id, ranges);
s.execute("object.path.simplify", &json!({"tolerance": 1})).unwrap();
path_of(&s, id).subpaths[0].anchors.clone()
path_of(&s, id).subpaths[0].anchors.to_vec()
};
let (first, second) = (alone(&[(10, 30)]), alone(&[(60, 80)]));
let mut s = session();
@@ -110,13 +110,13 @@ fn separate_runs_on_one_path_simplify_independently_in_one_step() {
let undo = undo_len(&s);
s.execute("object.path.simplify", &json!({"tolerance": 1})).unwrap();
assert_eq!(undo_len(&s), undo + 1, "one undo step");
let both = path_of(&s, id).subpaths[0].anchors.clone();
let both = path_of(&s, id).subpaths[0].anchors.to_vec();
// Where old anchor 30 is in the first result, and old anchor 80 in the second.
let (a30, a80) = (first.len() - 71, second.len() - 21);
assert!(a30 < 30 && a80 < 80, "both runs lose anchors");
let mid = a30 + 30;
assert_eq!(both[..=a30], first[..=a30]);
assert_eq!(both[a30 + 1..mid], original.anchors[31..60], "the anchors between the runs");
assert_eq!(both[a30 + 1..mid], original.anchors.to_vec()[31..60], "the anchors between the runs");
assert_eq!(both[mid..], second[60..]);
let sel: BTreeSet<_> = (10..=a30).chain(mid..=mid + a80 - 60).map(|i| (0, i)).collect();
assert_eq!(s.doc().unwrap().selection.anchors.get(&id), Some(&sel));
@@ -138,7 +138,7 @@ fn a_run_across_the_start_of_a_closed_path_simplifies_as_one() {
assert!(sp.closed);
assert!(sp.anchors.len() < 80 - 10, "{}", sp.anchors.len());
assert!(!sp.anchors.iter().any(|a| a.p == original.anchors[0].p), "anchor 0 was inside the run");
assert_eq!(sp.anchors[1..60], original.anchors[11..70]);
assert_eq!(sp.anchors.to_vec()[1..60], original.anchors.to_vec()[11..70]);
assert_eq!((sp.anchors[0].p, sp.anchors[0].h_out), (original.anchors[10].p, original.anchors[10].h_out));
assert_eq!((sp.anchors[60].p, sp.anchors[60].h_in), (original.anchors[70].p, original.anchors[70].h_in));
for i in 0..60 {
@@ -162,8 +162,8 @@ fn picked_segments_simplify_and_stay_picked() {
s.execute("object.path.simplify", &json!({"tolerance": 1})).unwrap();
let sp = path_of(&s, id).subpaths[0].clone();
let end = sp.anchors.len() - 41;
assert_eq!(sp.anchors[..20], original.anchors[..20]);
assert_eq!(sp.anchors[end + 1..], original.anchors[61..]);
assert_eq!(sp.anchors.to_vec()[..20], original.anchors.to_vec()[..20]);
assert_eq!(sp.anchors.to_vec()[end + 1..], original.anchors.to_vec()[61..]);
let sel = &s.doc().unwrap().selection;
assert_eq!(sel.segments.get(&id), Some(&(20..end).map(|i| (0, i)).collect()));
assert_eq!(sel.anchors.get(&id), Some(&(20..=end).map(|i| (0, i)).collect()));
@@ -200,8 +200,8 @@ fn slider_preview_and_auto_simplify_only_the_run() {
let previewed = path_of(&s, id);
let sp = &previewed.subpaths[0];
assert!(sp.anchors.len() < 101, "{p}");
assert_eq!(sp.anchors[..20], original.anchors[..20], "{p}");
assert_eq!(sp.anchors[sp.anchors.len() - 40..], original.anchors[61..], "{p}");
assert_eq!(sp.anchors.to_vec()[..20], original.anchors.to_vec()[..20], "{p}");
assert_eq!(sp.anchors.to_vec()[sp.anchors.len() - 40..], original.anchors.to_vec()[61..], "{p}");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("object.path.simplify", &p).unwrap();
assert_eq!(path_of(&s, id), previewed, "{p}");
+2 -2
View File
@@ -93,7 +93,7 @@ fn more_smoothing_removes_the_jags_and_keeps_the_shape() {
// Within the tolerance (2.5 % of 300 pt at most) plus the jag the refit smooths away.
assert!(farthest(&before, &after) <= 7.5 + 1.5, "level {level}: {}", farthest(&before, &after));
// The end points of an open path stay put.
let (a, b) = (&before.subpaths[0].anchors, &after.subpaths[0].anchors);
let (a, b) = (&before.subpaths[0].anchors.to_vec(), &after.subpaths[0].anchors.to_vec());
assert_eq!((a[0].p, a[a.len() - 1].p), (b[0].p, b[b.len() - 1].p));
assert!(!after.subpaths[0].closed);
s.execute("edit.undo", &json!({})).unwrap();
@@ -206,7 +206,7 @@ fn direct_selected_anchors_smooth_only_their_section() {
s.execute("select.anchors", &json!({"id": id.0, "anchors": anchors})).unwrap();
s.execute("object.path.smooth", &json!({"level": 100})).unwrap();
let after = path_of(&s, id);
let (a, b) = (&before.subpaths[0].anchors, &after.subpaths[0].anchors);
let (a, b) = (&before.subpaths[0].anchors.to_vec(), &after.subpaths[0].anchors.to_vec());
assert!(b.len() < a.len(), "{} → {}", a.len(), b.len());
// Anchors 0..=10 and 30..=40 are untouched, the section between them refitted.
assert_eq!(a[..=10].iter().map(|x| x.p).collect::<Vec<_>>(), b[..=10].iter().map(|x| x.p).collect::<Vec<_>>());
+20
View File
@@ -325,6 +325,26 @@ fn select_same_appearance_attribute() {
run(&mut s, "select.set", json!({"ids": [a.0]}));
run(&mut s, "select.same.appearanceAttribute", json!({"item": (1u64 << 32) + 1}));
assert_eq!(s.doc().unwrap().selection.objects, vec![a, b]);
// Null is the default: the shared effect.
run(&mut s, "select.set", json!({"ids": [a.0]}));
run(&mut s, "select.same.appearanceAttribute", json!({"item": null}));
assert_eq!(s.doc().unwrap().selection.objects, vec![a, b]);
}
/// Select > Same > Appearance Attribute refuses an `item` that is not a whole number and leaves
/// the selection as it was.
#[test]
fn select_same_appearance_attribute_refuses_an_item_that_is_not_a_whole_number() {
let mut s = session();
let a = rect(&mut s, 10.0);
run(&mut s, "effect.apply", json!({"effect": "distort.roughen"}));
rect(&mut s, 100.0);
run(&mut s, "select.set", json!({"ids": [a.0]}));
for item in [json!("1"), json!(-1), json!(1.5), json!(true), json!([1])] {
let e = s.execute("select.same.appearanceAttribute", &json!({"item": item})).unwrap_err().to_string();
assert_eq!(e, "invalid parameters for `select.same.appearanceAttribute`: `item` must be a whole number", "{item}");
assert_eq!(s.doc().unwrap().selection.objects, vec![a], "{item}");
}
}
/// With a member path of a compound path selected first, Select > Same > Graphic Style and
+37
View File
@@ -551,6 +551,26 @@ fn svg_export_keeps_a_measured_region_only_on_the_object_alone() {
assert!(after.contains("<image") && !after.contains("<feOffset dx=\"3\""), "{after}");
}
/// SVG export keeps a filter live only in a user space SVG import stores again: `scale` 1000 with
/// `axes` that double it scales the user space 2000 times, past what import holds, so the object is
/// written as an image instead of a filter that would be left out when the file is opened.
#[test]
fn svg_export_writes_an_image_for_a_user_space_import_cannot_store() {
let hue = r#"<filter id="Hue"><feColorMatrix type="hueRotate" values="90"/></filter>"#;
for (scale, axes, live) in [(2.0, json!([2, 0, 0, 2]), true), (1000.0, json!([2, 0, 0, 2]), false)] {
let mut s = session();
let a = rect(&mut s, 10.0);
run(&mut s, "effect.apply", json!({"effect": "svg.filter", "ids": [a.0], "params": {"xml": hue, "scale": scale, "axes": axes}}));
let out = svg(&mut s);
assert_eq!((out.contains("<feColorMatrix"), out.contains("<image")), (live, !live), "scale {scale}: {out}");
let (back, warnings) = vectorcraft_svg::import_with_report(&out).unwrap();
assert!(warnings.is_empty(), "scale {scale}: {warnings:?}");
let mut kept = 0;
back.walk(|n| kept += n.appearance.effects.iter().filter(|e| e.id == "svg.filter").count());
assert_eq!(kept, usize::from(live), "scale {scale}: {out}");
}
}
/// SVG export writes a filter rebuilt from its filter elements and filter attributes, not the XML
/// the effect holds.
#[test]
@@ -575,6 +595,23 @@ fn moving_the_object_moves_the_filters_origin() {
assert_eq!(p["origin"], json!([8.0, 2.0]));
}
/// `axes` turns or skews the filter's user space; a move moves only its origin. Axes the effect
/// can't measure are refused.
#[test]
fn axes_turn_the_filters_user_space_and_bad_axes_are_refused() {
let mut s = session();
let a = rect(&mut s, 10.0);
run(&mut s, "effect.apply", json!({"effect": "svg.filter", "ids": [a.0], "params": {"xml": SHIFT, "axes": [0, 1, -1, 0]}}));
run(&mut s, "object.move", json!({"ids": [a.0], "dx": 5, "dy": -2}));
let p = &s.doc().unwrap().doc.node(a).unwrap().appearance.effects[0].params;
assert_eq!((&p["axes"], &p["origin"]), (&json!([0, 1, -1, 0]), &json!([5.0, -2.0])));
for axes in [json!([0, 0, 0, 0]), json!([1, 0, 0]), json!([1, 0, 0, "1"]), json!([1001, 0, 0, 1]), json!(null), json!("x")] {
let e = err(&mut s, "effect.apply", json!({"effect": "svg.filter", "ids": [a.0], "params": {"xml": SHIFT, "axes": axes}}));
assert!(e.contains("`axes` must be [a, b, c, d]"), "{axes}: {e}");
}
assert!(err(&mut s, "effect.setParams", json!({"ids": [a.0], "index": 0, "params": {"axes": [0.01, 0, 0, 0.01]}})).contains("`axes` must be"));
}
#[test]
fn filters_survive_a_native_round_trip() {
let mut s = session();
+1 -1
View File
@@ -286,7 +286,7 @@ fn legacy_spiral_decay_preferences_report_the_ratio_drawn_after_reopening() {
assert_eq!(d.selection.objects.len(), 1);
let id = d.selection.objects[0];
let path = d.doc.node(id).unwrap().path_data().unwrap().clone();
let anchors = &path.subpaths[0].anchors;
let anchors = &path.subpaths[0].anchors.to_vec();
assert_eq!(anchors.len(), 5);
assert!(!path.is_closed());
let center = Point::new(200.0, 200.0);
+9
View File
@@ -255,6 +255,9 @@ impl Session {
}
// The Selection and Group Selection tools act on the instance whole.
self.select_whole_instance(id);
// The tool lent to does not see the press: it counts as a press elsewhere for the clicks a
// double-click or triple-click compares.
self.tool.press_elsewhere();
let lent = self.make_tool(id);
self.selection_at_lend = self.active().map(|d| (d.uid, d.selection.clone()));
self.lender = Some(std::mem::replace(&mut self.tool, lent));
@@ -1086,6 +1089,12 @@ impl Session {
self.with_tool_cx(view, |t, cx| t.hover_ended(cx));
}
/// A press on the canvas went to the view tools and not to the active tool
/// ([`vectorcraft_tools::Tool::press_elsewhere`]).
pub fn tool_press_elsewhere(&mut self) {
self.tool.press_elsewhere();
}
/// Whether the active tool's hover depends on what lies under a still pointer
/// ([`vectorcraft_tools::Tool::wants_rehover`]).
pub fn tool_wants_rehover(&self) -> bool {
+7
View File
@@ -993,6 +993,13 @@ fn structured_junk() {
("addon.document.symbolsFromLayers", json!({"layers": "x", "replace": 3})),
("addon.document.symbolsFromLayers", json!({"layers": [1e308, -1, null, u64::MAX], "replace": true})),
("addon.document.symbolsFromLayers", json!({"layers": [], "replace": true})),
// Packaging Tools add-on.
("addon.packaging.setRole", json!({"role": "cut", "ids": [u64::MAX], "overprint": "no"})),
("addon.packaging.setRole", json!({"role": ["crease"], "ids": "all"})),
("addon.packaging.setRole", json!({"role": "none", "overprint": null})),
("addon.packaging.roles", json!({"ids": [-1, 1e300]})),
("addon.packaging.setRoleSwatch", json!({"role": "perforation", "swatch": "[Registration]"})),
("addon.packaging.setRoleSwatch", json!({"role": "cut", "swatch": 5})),
// Smart Pen add-on.
("addon.pen.append", json!({"id": 2, "x": 1e308, "y": 0, "in": [1e308, -1e308]})),
("addon.pen.append", json!({"id": 2, "subpath": u64::MAX, "x": 0, "y": 0, "segment": "curved"})),
+11
View File
@@ -1672,6 +1672,9 @@ fn action_set(bytes: &[u8]) -> Result<(), TestCaseError> {
prop_assert!(actions.iter().all(|a| a["steps"].as_array().map_or(0, Vec::len) <= 10_000));
prop_assert!(actions.iter().map(|a| a["steps"].as_array().map_or(0, Vec::len)).sum::<usize>() <= 100_000);
prop_assert!(r["unread"].as_array().map_or(0, Vec::len) <= 1000);
let steps = || actions.iter().flat_map(|a| a["steps"].as_array().cloned().unwrap_or_default());
prop_assert!(steps().all(|s| s["values"].as_array().map_or(0, Vec::len) as u64 <= s["params"].as_u64().unwrap_or(0)));
prop_assert!(steps().map(|s| s["values"].as_array().map_or(0, Vec::len)).sum::<usize>() <= 100_000);
}
Ok(())
}
@@ -1690,6 +1693,8 @@ fn arb_aia_token() -> impl Strategy<Value = Vec<u8>> {
"/localizedName",
"/isOn",
"/value",
"/key",
"/type",
"/x",
"/version",
])
@@ -1699,6 +1704,7 @@ fn arb_aia_token() -> impl Strategy<Value = Vec<u8>> {
"[a-z ()\\\\]{0,12}".prop_map(|t| format!("({t})").into_bytes()),
prop::sample::select(vec!["(", ")", "\\", "[ 2 4142 ]", "[ 3 41 4", "[ 1 zz ]", "[", "]", "< 2 0a0b >", "<", ">", "2.5"])
.prop_map(|t| t.as_bytes().to_vec()),
prop::sample::select(vec!["[ 2 c328 ]", "(ustring)", "(boolean)"]).prop_map(|t| t.as_bytes().to_vec()),
prop::sample::select(vec!["{", "}", "\r\n", "\r", "\n"]).prop_map(|t| t.as_bytes().to_vec()),
prop::sample::select(vec![vec![0u8], vec![0xFF, 0xFE], vec![0xC3]]),
]
@@ -1835,6 +1841,7 @@ proptest! {
/// Mutated copies of the PSD and PSB samples never crash opening them with their layers, hidden
/// ones too: the PSD's layer records, channel lengths and data, and the PSB's layer count.
/// (Masks, clipping and groups are covered by `tests_psdlayers::damaged_layers_never_panic`.)
/// Neither does `document.psdInfo`, nor placing them with their layers as objects.
#[test]
fn mutated_layered_psds_open_without_panics(which in 6usize..8, cut in 0usize..1_000_000, edits in prop::collection::vec((0usize..1_000_000, any::<u8>()), 0..12)) {
let (name, mut bytes) = raster_samples().swap_remove(which);
@@ -1849,6 +1856,10 @@ proptest! {
let mut s = vectorcraft_engine::Session::new();
let p = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&bytes), "hiddenLayers": true});
let _ = no_panic(s.execute("document.open", &p));
let _ = no_panic(s.execute("document.psdInfo", &p));
let _ = no_panic(s.execute("file.new", &json!({})));
let p = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&bytes), "layers": true, "hiddenLayers": true});
let _ = no_panic(s.execute("file.place", &p));
});
prop_assert!(r.is_ok(), "{name}: panicked: {:?}", r.err());
}