mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-19 20:19:44 +00:00
Merge main into feat/editable-flares
This commit is contained in:
@@ -44,6 +44,7 @@ pub(crate) mod graph;
|
||||
mod halftone;
|
||||
pub mod help;
|
||||
pub mod importmatches;
|
||||
mod info;
|
||||
pub(crate) mod inline;
|
||||
mod interactivity;
|
||||
mod intertwine;
|
||||
@@ -345,6 +346,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(docmenu::specs());
|
||||
v.extend(variablecmds::specs());
|
||||
v.extend(docinfo::specs());
|
||||
v.extend(info::specs());
|
||||
v.extend(panelcmds::specs());
|
||||
v.extend(artboardalign::specs());
|
||||
v.extend(buildcmds::specs());
|
||||
@@ -829,6 +831,7 @@ pub(crate) use edit::{settle_interaction, typing_in_progress};
|
||||
pub(crate) use object::bounds_rewrite;
|
||||
pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned};
|
||||
pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location_keys};
|
||||
pub use select::SIMILAR;
|
||||
pub(crate) use vectorcraft_doc::range::parse_range;
|
||||
|
||||
/// A date param in Unix seconds that defaults to the clock: `None` when absent (now, see
|
||||
@@ -897,6 +900,9 @@ pub use brushsym::reset_transformation_changes;
|
||||
/// Data window reads files by it too).
|
||||
pub use variablecmds::utf16_order_without_mark;
|
||||
|
||||
/// The Variables panel's sort (`variable.sort`) and its rows in that order.
|
||||
pub use variablecmds::{VariableSort, VariableSortKey, variable_order};
|
||||
|
||||
/// Command ids kept only so older scripts keep working: `(alias, the command it duplicates)`.
|
||||
/// They run as before but the command palette leaves them out (it lists the command once).
|
||||
pub const ALIASES: &[(&str, &str)] = &[("object.convertDocumentColorMode", "file.documentColorMode")];
|
||||
|
||||
@@ -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 })
|
||||
|
||||
@@ -9,7 +9,7 @@ mod tests;
|
||||
mod text;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
use vectorcraft_doc::{Document, LockedArtboards, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{PathData, SubPath};
|
||||
use vectorcraft_pathops::addons as po;
|
||||
|
||||
@@ -37,7 +37,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Simplify Anchors (Keep Shape)…",
|
||||
["Object", "Plug-ins", "Artwork Cleanup"],
|
||||
None,
|
||||
"{tolerance?: 1..100 (20; higher removes more anchors and lets the outline move further from where it was, up to tolerance × 0.02 pt), protectCorners?: bool (false; anchors where the path turns by more than 30° stay), ids?: [id…] (default: the selection)} remove the anchors each path under the objects can do without, refitting the handles beside each so the outline keeps its shape, as one undo step; open ends stay, and locked and hidden paths are left out → {ids, before, after} anchor counts",
|
||||
"{tolerance?: 1..100 (20; higher removes more anchors and lets the outline move further from where it was, up to tolerance × 0.02 pt), protectCorners?: bool (false; anchors where the path turns by more than 30° stay), ids?: [id…] (default: the selection)} remove the anchors each path under the objects can do without, refitting the handles beside each so the outline keeps its shape, as one undo step when a path changes; open ends stay; from the selection, locked and hidden paths are left out, and named by `ids`, the paths of the objects, groups and layers it names are taken even when locked or hidden, but not those on a locked artboard; a changed path loses its selected anchors and segments → {ids, before, after} anchor counts",
|
||||
has_selection,
|
||||
simplify
|
||||
),
|
||||
@@ -73,7 +73,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Deep Ungroup…",
|
||||
["Object", "Plug-ins", "Artwork Cleanup"],
|
||||
None,
|
||||
"{includeClipGroups?: bool (false: clipping groups, and the art inside them, stay as they are; true: they are ungrouped too and their clipping paths become plain paths), ids?: [id…] (default: the selection)} ungroup every level of the groups among the objects, as one undo step; each object keeps the opacity of the groups it was in; locked and hidden groups stay whole, and locked and hidden objects stay locked or hidden and are not selected → {ids (the objects selected: those left, or with no group to take apart the selection as it was), ungrouped (groups)}",
|
||||
"{includeClipGroups?: bool (false: clipping groups, and the art inside them, stay as they are; true: they are ungrouped too and their clipping paths become plain paths), ids?: [id…] (default: the selection)} ungroup every level of the groups among the objects, as one undo step when a group goes; each object keeps the opacity of the groups it was in; from the selection, locked and hidden groups stay whole; named by `ids`, the groups it names and the groups in the groups and layers it names are ungrouped even when locked or hidden (a named layer stays), but not those on a locked artboard, and their objects become hidden or locked when a group was; locked and hidden objects stay locked or hidden and are not selected → {ids (the objects selected: those left, or with no group to take apart the selection as it was), ungrouped (groups)}",
|
||||
has_selection,
|
||||
deep_ungroup
|
||||
),
|
||||
@@ -82,7 +82,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Rejoin Path Pieces…",
|
||||
["Object", "Plug-ins", "Artwork Cleanup"],
|
||||
None,
|
||||
"{gap?: pt 0..6 (0.1), ids?: [id…] (default: the selection)} weld the open paths under the objects whose ends lie within the gap of each other back into paths: an end joins one other end, the one the path turns least to go on into, pieces may run either way, and a chain whose ends meet closes; each path takes the place and paint of its topmost piece, as one undo step → {ids, joined (paths made), removed (pieces merged into them)}",
|
||||
"{gap?: pt 0..6 (0.1), ids?: [id…] (default: the selection)} weld the open paths under the objects whose ends lie within the gap of each other back into paths: an end joins one other end, the one the path turns least to go on into, pieces may run either way, and a chain whose ends meet closes; each path takes the place and paint of its topmost piece, as one undo step when a path is made; from the selection, locked and hidden paths are left out, and named by `ids`, they are taken, but not those on a locked artboard; only pieces alike in being hidden (by themselves or a group or layer above them) and in being locked join; locked and hidden paths made are not selected → {ids, joined (paths made), removed (pieces merged into them)}",
|
||||
has_selection,
|
||||
rejoin
|
||||
),
|
||||
@@ -91,9 +91,28 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
v
|
||||
}
|
||||
|
||||
/// The paths (not guides) under `roots`, compound path members included; locked and hidden
|
||||
/// paths, and those in locked or hidden groups, stay out.
|
||||
fn paths_under(d: &Document, roots: &[NodeId]) -> Vec<NodeId> {
|
||||
/// Whether a request names its objects with `ids` (present and not null) rather than taking the
|
||||
/// selection.
|
||||
fn named(p: &Value) -> bool {
|
||||
p.get("ids").is_some_and(|v| !v.is_null())
|
||||
}
|
||||
|
||||
/// Keep the items of `items` whose object (`id`) a command acts on: when `named`, every one not on
|
||||
/// a locked artboard, locked and hidden ones (and ones in a locked or hidden group or layer)
|
||||
/// included; else only those that can be edited.
|
||||
fn retain_targets<T>(d: &Document, items: &mut Vec<T>, named: bool, id: impl Fn(&T) -> NodeId) {
|
||||
if named {
|
||||
let locks = d.locked_artboards();
|
||||
items.retain(|t| !locks.holds_id(id(t)));
|
||||
} else {
|
||||
let editable = d.editable();
|
||||
items.retain(|t| editable(id(t)));
|
||||
}
|
||||
}
|
||||
|
||||
/// The paths (not guides) under `roots`, compound path members included, that a command acts on
|
||||
/// ([`retain_targets`]).
|
||||
fn paths_under(d: &Document, roots: &[NodeId], named: bool) -> Vec<NodeId> {
|
||||
let mut out = vec![];
|
||||
for n in roots.iter().filter_map(|id| d.node(*id)) {
|
||||
n.walk(&mut |c| {
|
||||
@@ -102,8 +121,7 @@ fn paths_under(d: &Document, roots: &[NodeId]) -> Vec<NodeId> {
|
||||
}
|
||||
});
|
||||
}
|
||||
let editable = d.editable();
|
||||
out.retain(|id| editable(*id));
|
||||
retain_targets(d, &mut out, named, |id| *id);
|
||||
out
|
||||
}
|
||||
|
||||
@@ -116,7 +134,7 @@ fn simplify(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let protect = switch_or(p, "protectCorners", false, C)?;
|
||||
let roots = checked_ids_or_selection(s, p, C)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let ids = paths_under(d, &roots);
|
||||
let ids = paths_under(d, &roots, named(p));
|
||||
let paths: Vec<(NodeId, &PathData)> = ids.iter().filter_map(|id| Some((*id, d.node(*id)?.path_data()?))).collect();
|
||||
let before: usize = paths.iter().map(|(_, p)| p.anchor_count()).sum();
|
||||
if before > MAX_ANCHORS {
|
||||
@@ -258,10 +276,11 @@ fn ungroupable(n: &Node, clips: bool) -> bool {
|
||||
}
|
||||
|
||||
/// `n` with every level of grouping Deep Ungroup takes apart removed, into `out`; `count` counts
|
||||
/// the groups. Members take on the opacity of the groups they were in, and a clipping path
|
||||
/// becomes a plain path. A locked or hidden group stays whole.
|
||||
fn flatten(n: Node, clips: bool, out: &mut Vec<Node>, count: &mut usize) {
|
||||
if !ungroupable(&n, clips) || n.locked || !n.visible {
|
||||
/// the groups. Members take on the opacity of the groups they were in, are hidden when one of them
|
||||
/// was hidden and locked when one of them was locked, and a clipping path becomes a plain path. A
|
||||
/// locked or hidden group stays whole unless `named`.
|
||||
fn flatten(n: Node, clips: bool, named: bool, out: &mut Vec<Node>, count: &mut usize) {
|
||||
if !ungroupable(&n, clips) || (!named && (n.locked || !n.visible)) {
|
||||
out.push(n);
|
||||
return;
|
||||
}
|
||||
@@ -276,26 +295,57 @@ fn flatten(n: Node, clips: bool, out: &mut Vec<Node>, count: &mut usize) {
|
||||
*clipping = false;
|
||||
}
|
||||
c.opacity *= n.opacity;
|
||||
flatten(c, clips, out, count);
|
||||
c.visible &= n.visible;
|
||||
c.locked |= n.locked;
|
||||
flatten(c, clips, named, out, count);
|
||||
}
|
||||
}
|
||||
|
||||
/// The outermost groups Deep Ungroup takes apart in layer `n`, its sublayers included, in paint
|
||||
/// order, leaving out those on a locked artboard.
|
||||
fn groups_in_layer(d: &Document, n: &Node, clips: bool, out: &mut Vec<NodeId>) {
|
||||
let locks = d.locked_artboards();
|
||||
fn visit(n: &Node, clips: bool, locks: &LockedArtboards, out: &mut Vec<NodeId>) {
|
||||
for c in n.children().into_iter().flatten() {
|
||||
if c.is_layer() {
|
||||
visit(c, clips, locks, out);
|
||||
} else if ungroupable(c, clips) && !locks.holds_id(c.id) {
|
||||
out.push(c.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
visit(n, clips, &locks, out);
|
||||
}
|
||||
|
||||
fn deep_ungroup(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.cleanup.deepUngroup";
|
||||
let clips = switch_or(p, "includeClipGroups", false, C)?;
|
||||
let roots = checked_ids_or_selection(s, p, C)?;
|
||||
let named = named(p);
|
||||
let mut roots = checked_ids_or_selection(s, p, C)?;
|
||||
let d = &s.doc()?.doc;
|
||||
// Locked and hidden objects, and those in locked or hidden groups, stay as they are.
|
||||
let roots: Vec<NodeId> = {
|
||||
let editable = d.editable();
|
||||
roots.into_iter().filter(|id| editable(*id)).collect()
|
||||
};
|
||||
// From the selection, locked and hidden objects, and those in locked or hidden groups, stay as
|
||||
// they are; named, only those on a locked artboard do.
|
||||
retain_targets(d, &mut roots, named, |id| *id);
|
||||
// A named layer stays: the groups in it, and in its sublayers, are taken apart.
|
||||
let mut groups = vec![];
|
||||
for id in roots {
|
||||
match d.node(id) {
|
||||
Some(n) if named && n.is_layer() => {
|
||||
let at = groups.len();
|
||||
groups_in_layer(d, n, clips, &mut groups);
|
||||
if groups.len() == at {
|
||||
groups.push(id);
|
||||
}
|
||||
}
|
||||
_ => groups.push(id),
|
||||
}
|
||||
}
|
||||
let (mut items, mut selected, mut count) = (vec![], vec![], 0);
|
||||
for id in &roots {
|
||||
for id in &groups {
|
||||
match d.node(*id).filter(|n| ungroupable(n, clips)) {
|
||||
Some(n) => {
|
||||
let mut out = vec![];
|
||||
flatten(n.clone(), clips, &mut out, &mut count);
|
||||
flatten(n.clone(), clips, named, &mut out, &mut count);
|
||||
selected.extend(out.iter().map(|n| n.id));
|
||||
items.push((*id, out));
|
||||
}
|
||||
@@ -304,7 +354,7 @@ fn deep_ungroup(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// With no group to take apart, the document, the selection and the undo history stay as they
|
||||
// are, and the reply lists the selection.
|
||||
if items.is_empty() {
|
||||
if count == 0 {
|
||||
selected = s.doc()?.selection.objects.to_vec();
|
||||
} else {
|
||||
selected = s.edit("Deep Ungroup", move |d, sel| {
|
||||
@@ -319,26 +369,39 @@ fn deep_ungroup(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "ids": selected.iter().map(|i| i.0).collect::<Vec<_>>(), "ungrouped": count }))
|
||||
}
|
||||
|
||||
/// One path Rejoin Path Pieces takes: its id, its subpath, and whether it and every group and layer
|
||||
/// above it are visible, and whether they are all unlocked.
|
||||
type Piece = (NodeId, SubPath, (bool, bool));
|
||||
|
||||
/// The open single-subpath paths under `roots` that Rejoin Path Pieces takes, in paint order
|
||||
/// (compound path members, clipping paths and guides stay out).
|
||||
fn pieces(d: &Document, roots: &[NodeId]) -> Vec<(NodeId, SubPath)> {
|
||||
fn visit(n: &Node, out: &mut Vec<(NodeId, SubPath)>) {
|
||||
/// (compound path members, clipping paths and guides stay out; [`retain_targets`]).
|
||||
fn pieces(d: &Document, roots: &[NodeId], named: bool) -> Vec<Piece> {
|
||||
fn visit(n: &Node, above: (bool, bool), out: &mut Vec<Piece>) {
|
||||
let state = (above.0 && n.visible, above.1 && !n.locked);
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, guide: false, clipping: false, .. } => {
|
||||
if let [sp] = path.subpaths.as_slice()
|
||||
&& !sp.closed
|
||||
{
|
||||
out.push((n.id, sp.clone()));
|
||||
out.push((n.id, sp.clone(), state));
|
||||
}
|
||||
}
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => children.iter().for_each(|c| visit(c, out)),
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => children.iter().for_each(|c| visit(c, state, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
roots.iter().filter_map(|id| d.node(*id)).for_each(|n| visit(n, &mut out));
|
||||
let editable = d.editable();
|
||||
out.retain(|(id, _)| editable(*id));
|
||||
for (id, n) in roots.iter().filter_map(|id| Some((*id, d.node(*id)?))) {
|
||||
// The groups and layers above the root, and their state.
|
||||
let above = d.ancestry(id).unwrap_or_default();
|
||||
let above = above.split_last().map_or(&[][..], |(_, up)| up);
|
||||
if above.last().and_then(|i| d.node(*i)).is_some_and(|parent| matches!(parent.kind, NodeKind::Compound { .. })) {
|
||||
continue;
|
||||
}
|
||||
let state = above.iter().filter_map(|i| d.node(*i)).fold((true, true), |(v, u), a| (v && a.visible, u && !a.locked));
|
||||
visit(n, state, &mut out);
|
||||
}
|
||||
retain_targets(d, &mut out, named, |piece| piece.0);
|
||||
out
|
||||
}
|
||||
|
||||
@@ -349,18 +412,26 @@ fn rejoin(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "`gap` must be from 0 to 6 pt"));
|
||||
}
|
||||
let roots = checked_ids_or_selection(s, p, C)?;
|
||||
let found = pieces(&s.doc()?.doc, &roots);
|
||||
let found = pieces(&s.doc()?.doc, &roots, named(p));
|
||||
if found.len() > MAX_OBJECTS {
|
||||
return Err(EngineError::Other("Rejoin Path Pieces: too many paths to rejoin at once".into()));
|
||||
}
|
||||
let subpaths: Vec<SubPath> = found.iter().map(|(_, sp)| sp.clone()).collect();
|
||||
// Each chain becomes its topmost piece (the last in paint order); the others go.
|
||||
// Only pieces alike in being shown and in being unlocked join, so that a joined path neither
|
||||
// shows hidden art nor hides shown art, nor locks or unlocks a piece.
|
||||
let (mut kept, mut gone) = (vec![], vec![]);
|
||||
for j in po::rejoin(&subpaths, gap) {
|
||||
let ids: Vec<NodeId> = j.members.iter().filter_map(|&m| found.get(m).map(|f| f.0)).collect();
|
||||
let Some(&top) = j.members.iter().max().and_then(|&m| found.get(m).map(|f| &f.0)) else { continue };
|
||||
gone.extend(ids.into_iter().filter(|id| *id != top));
|
||||
kept.push((top, j.path));
|
||||
for state in [(true, true), (true, false), (false, true), (false, false)] {
|
||||
let part: Vec<&Piece> = found.iter().filter(|f| f.2 == state).collect();
|
||||
if part.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let subpaths: Vec<SubPath> = part.iter().map(|f| f.1.clone()).collect();
|
||||
// Each chain becomes its topmost piece (the last in paint order); the others go.
|
||||
for j in po::rejoin(&subpaths, gap) {
|
||||
let ids: Vec<NodeId> = j.members.iter().filter_map(|&m| part.get(m).map(|f| f.0)).collect();
|
||||
let Some(top) = j.members.iter().max().and_then(|&m| part.get(m).map(|f| f.0)) else { continue };
|
||||
gone.extend(ids.into_iter().filter(|id| *id != top));
|
||||
kept.push((top, j.path));
|
||||
}
|
||||
}
|
||||
if !kept.is_empty() {
|
||||
let ids: Vec<NodeId> = kept.iter().map(|k| k.0).collect();
|
||||
@@ -369,7 +440,9 @@ fn rejoin(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
set_path(d, *id, PathData::single(sp.clone()));
|
||||
}
|
||||
d.remove_many(&gone)?;
|
||||
sel.set(ids);
|
||||
// Locked and hidden paths, and those in locked or hidden groups, are not selected.
|
||||
let editable = d.editable();
|
||||
sel.set(ids.into_iter().filter(|id| editable(*id)));
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Node, NodeId, NodeKind};
|
||||
use vectorcraft_doc::{Appearance, LayerColor, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{FillRule, Rect};
|
||||
|
||||
use crate::Session;
|
||||
@@ -123,18 +123,100 @@ fn simplify_leaves_locked_and_hidden_paths_alone() {
|
||||
assert_eq!(r["before"], 16);
|
||||
assert!(anchors(&s, ids[0]) < 16);
|
||||
assert_eq!((anchors(&s, ids[1]), anchors(&s, ids[2])), (16, 16));
|
||||
// Named by `ids`, or in a locked group, a path stays too, with no undo step.
|
||||
let steps = undo_steps(&s);
|
||||
s.execute("addon.cleanup.simplify", &json!({"ids": [ids[1].0, ids[2].0]})).unwrap();
|
||||
assert_eq!((anchors(&s, ids[1]), anchors(&s, ids[2])), (16, 16));
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
// In a selected locked group, a path stays too, with no undo step.
|
||||
change(&mut s, ids[1], |n| n.locked = false);
|
||||
change(&mut s, g, |n| n.locked = true);
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cleanup.simplify", &json!({"ids": [g.0]})).unwrap();
|
||||
let r = s.execute("addon.cleanup.simplify", &json!({})).unwrap();
|
||||
assert_eq!((r["before"].as_u64(), r["after"].as_u64()), (Some(0), Some(0)));
|
||||
assert_eq!(anchors(&s, ids[1]), 16);
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
// Named by `ids`, the locked group's paths, its hidden one included, are simplified.
|
||||
let r = s.execute("addon.cleanup.simplify", &json!({"ids": [g.0]})).unwrap();
|
||||
assert_eq!(r["ids"], json!([ids[0].0, ids[1].0, ids[2].0]));
|
||||
assert!(anchors(&s, ids[1]) < 16 && anchors(&s, ids[2]) < 16);
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
}
|
||||
|
||||
/// A path of 16 anchors at (`x`, `y`): an ellipse with anchors added twice.
|
||||
fn ellipse16(s: &mut Session, x: f64, y: f64) -> NodeId {
|
||||
let e = id_of(&s.execute("shape.ellipse", &json!({"x": x, "y": y, "width": 50, "height": 50})).unwrap());
|
||||
select(s, &[e]);
|
||||
s.execute("object.path.addAnchorPoints", &json!({})).unwrap();
|
||||
s.execute("object.path.addAnchorPoints", &json!({})).unwrap();
|
||||
e
|
||||
}
|
||||
|
||||
/// Simplify Anchors takes the locked and hidden paths `ids` names, those in the locked or hidden
|
||||
/// groups and layers it names (their locked and hidden members too) and a hidden compound path's
|
||||
/// member, as one undo step, without selecting them; from the selection it leaves them alone, and a
|
||||
/// path on a locked artboard stays even when named.
|
||||
#[test]
|
||||
fn simplify_named_locked_and_hidden_paths() {
|
||||
let mut s = session();
|
||||
let locked = ellipse16(&mut s, 10.0, 10.0);
|
||||
let hidden = ellipse16(&mut s, 70.0, 10.0);
|
||||
change(&mut s, locked, |n| n.locked = true);
|
||||
change(&mut s, hidden, |n| n.visible = false);
|
||||
// A locked group with a hidden member, and a hidden group with a locked member.
|
||||
let in_locked = ellipse16(&mut s, 130.0, 10.0);
|
||||
let locked_group = wrap(&mut s, in_locked, |c| NodeKind::Group { children: c, clip: false });
|
||||
change(&mut s, locked_group, |n| n.locked = true);
|
||||
change(&mut s, in_locked, |n| n.visible = false);
|
||||
let in_hidden = ellipse16(&mut s, 190.0, 10.0);
|
||||
let hidden_group = wrap(&mut s, in_hidden, |c| NodeKind::Group { children: c, clip: false });
|
||||
change(&mut s, hidden_group, |n| n.visible = false);
|
||||
change(&mut s, in_hidden, |n| n.locked = true);
|
||||
// A member of a hidden compound path.
|
||||
let member = ellipse16(&mut s, 250.0, 10.0);
|
||||
let compound = wrap(&mut s, member, |c| NodeKind::Compound { children: c, rule: FillRule::NonZero });
|
||||
change(&mut s, compound, |n| n.visible = false);
|
||||
// A path in a locked layer, named itself.
|
||||
let layer = id_of(&s.execute("layer.new", &json!({})).unwrap());
|
||||
let in_layer = ellipse16(&mut s, 10.0, 100.0);
|
||||
let on_board = ellipse16(&mut s, 10.0, 200.0);
|
||||
change(&mut s, layer, |n| n.locked = true);
|
||||
let all = [locked, hidden, in_locked, in_hidden, member, in_layer];
|
||||
select(&mut s, &[locked, hidden, locked_group, hidden_group, compound]);
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cleanup.simplify", &json!({})).unwrap();
|
||||
assert_eq!(r["ids"], json!([]), "from the selection, none is taken");
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
assert!(all.iter().all(|id| anchors(&s, *id) == 16));
|
||||
select(&mut s, &[]);
|
||||
s.edit("Select Anchors", |_, sel| {
|
||||
sel.anchors.insert(locked, [(0, 1)].into());
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cleanup.simplify", &json!({"ids": [locked.0, hidden.0, locked_group.0, hidden_group.0, member.0, in_layer.0]})).unwrap();
|
||||
assert_eq!(r["ids"], json!(all.iter().map(|i| i.0).collect::<Vec<_>>()));
|
||||
assert_eq!(r["before"], 16 * 6);
|
||||
assert_eq!(r["after"].as_u64(), Some(all.iter().map(|id| anchors(&s, *id) as u64).sum::<u64>()));
|
||||
assert!(all.iter().all(|id| anchors(&s, *id) < 16), "{r}");
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
let sel = &s.doc().unwrap().selection;
|
||||
assert!(sel.objects.is_empty() && sel.anchors.is_empty(), "nothing is selected, and the changed path's anchors are not");
|
||||
let n = node(&s, in_hidden).unwrap();
|
||||
assert!(n.locked && n.visible && !node(&s, hidden_group).unwrap().visible);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(all.iter().all(|id| anchors(&s, *id) == 16));
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert!(all.iter().all(|id| anchors(&s, *id) < 16));
|
||||
// Nothing left to remove: no undo step.
|
||||
let steps = undo_steps(&s);
|
||||
s.execute("addon.cleanup.simplify", &json!({"ids": [locked.0]})).unwrap();
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
// On a locked artboard, a named path stays as it is.
|
||||
s.edit("Lock Artboard", |d, _| {
|
||||
d.artboards[0].locked = true;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cleanup.simplify", &json!({"ids": [on_board.0]})).unwrap();
|
||||
assert_eq!((r["ids"].clone(), anchors(&s, on_board), undo_steps(&s)), (json!([]), 16, steps));
|
||||
}
|
||||
|
||||
/// Each kind: what makes the issue in a fresh document (beside a clean rectangle).
|
||||
@@ -610,14 +692,15 @@ fn deep_ungroup_keeps_hidden_art_hidden_and_locked_art_locked() {
|
||||
assert!(!d.node(hidden).unwrap().visible && d.node(b).unwrap().visible);
|
||||
assert!(d.node(locked).unwrap().locked && d.node(e).unwrap().locked);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [a]);
|
||||
// Named by `ids`, a locked group stays as it is, with no undo step.
|
||||
// Named by `ids`, a locked group is taken apart as one undo step; its member becomes locked
|
||||
// and is not selected.
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cleanup.deepUngroup", &json!({"ids": [locked.0]})).unwrap();
|
||||
assert_eq!(r["ungrouped"], 0);
|
||||
assert!(node(&s, locked).is_some());
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
assert_eq!(r["ungrouped"], 1);
|
||||
assert!(node(&s, locked).is_none() && node(&s, c).unwrap().locked);
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
assert_eq!(r["ids"], json!([]));
|
||||
// With nothing ungrouped, the selection stays and the reply lists it.
|
||||
assert_eq!(r["ids"], json!([a.0]));
|
||||
let f = rect(&mut s, 130.0, 10.0, 20.0, 20.0);
|
||||
select(&mut s, &[a]);
|
||||
let r = s.execute("addon.cleanup.deepUngroup", &json!({"ids": [f.0]})).unwrap();
|
||||
@@ -625,6 +708,108 @@ fn deep_ungroup_keeps_hidden_art_hidden_and_locked_art_locked() {
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [a]);
|
||||
}
|
||||
|
||||
/// Put `ids` inside a new container that `kind` makes of its members.
|
||||
fn wrap_all(s: &mut Session, ids: &[NodeId], kind: fn(Vec<std::sync::Arc<Node>>) -> NodeKind) -> NodeId {
|
||||
s.edit("t", |d, _| {
|
||||
let w = d.alloc_id();
|
||||
Ok(d.wrap(ids, |c| Node::new(w, kind(c)))?)
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn plain_group(c: Vec<std::sync::Arc<Node>>) -> NodeKind {
|
||||
NodeKind::Group { children: c, clip: false }
|
||||
}
|
||||
|
||||
fn sublayer(c: Vec<std::sync::Arc<Node>>) -> NodeKind {
|
||||
NodeKind::Layer { color: LayerColor::Preset(0), template: false, printable: true, children: c, clip: false, preview: true, dim_images: None }
|
||||
}
|
||||
|
||||
/// Named by `ids`, Deep Ungroup takes apart locked and hidden groups, those nested in a group it
|
||||
/// names and those in a layer it names (its sublayers included, the layer staying), as one undo
|
||||
/// step; their members become locked or hidden as the groups were, keep the groups' opacity and are
|
||||
/// not selected. From the selection those groups stay whole, as do a clipping group and a group on a
|
||||
/// locked artboard even when named.
|
||||
#[test]
|
||||
fn deep_ungroup_named_locked_and_hidden_groups() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
|
||||
let b = rect(&mut s, 40.0, 10.0, 20.0, 20.0);
|
||||
let locked = wrap_all(&mut s, &[a], plain_group);
|
||||
let hidden = wrap_all(&mut s, &[b], plain_group);
|
||||
change(&mut s, locked, |n| n.locked = true);
|
||||
change(&mut s, hidden, |n| {
|
||||
n.visible = false;
|
||||
n.opacity = 0.5;
|
||||
});
|
||||
select(&mut s, &[locked, hidden]);
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cleanup.deepUngroup", &json!({})).unwrap();
|
||||
assert_eq!((r["ungrouped"].clone(), undo_steps(&s)), (json!(0), steps), "from the selection, they stay whole");
|
||||
assert!(node(&s, locked).is_some() && node(&s, hidden).is_some());
|
||||
let r = s.execute("addon.cleanup.deepUngroup", &json!({"ids": [locked.0, hidden.0]})).unwrap();
|
||||
assert_eq!((r["ungrouped"].clone(), r["ids"].clone()), (json!(2), json!([])));
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
assert!(node(&s, locked).is_none() && node(&s, hidden).is_none());
|
||||
let (na, nb) = (node(&s, a).unwrap(), node(&s, b).unwrap());
|
||||
assert!(na.locked && na.visible && !nb.visible && !nb.locked);
|
||||
assert_eq!(nb.opacity, 0.5);
|
||||
assert!(s.doc().unwrap().selection.objects.is_empty());
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(node(&s, locked).is_some() && !node(&s, a).unwrap().locked && node(&s, b).unwrap().visible);
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert!(node(&s, locked).is_none() && node(&s, a).unwrap().locked);
|
||||
// Locked and hidden groups nested in a named group that can be edited.
|
||||
let c = rect(&mut s, 70.0, 10.0, 20.0, 20.0);
|
||||
let e = rect(&mut s, 100.0, 10.0, 20.0, 20.0);
|
||||
let f = rect(&mut s, 130.0, 10.0, 20.0, 20.0);
|
||||
let inner_locked = wrap_all(&mut s, &[e], plain_group);
|
||||
let inner_hidden = wrap_all(&mut s, &[f], plain_group);
|
||||
change(&mut s, inner_locked, |n| n.locked = true);
|
||||
change(&mut s, inner_hidden, |n| n.visible = false);
|
||||
let outer = wrap_all(&mut s, &[c, inner_locked, inner_hidden], plain_group);
|
||||
let r = s.execute("addon.cleanup.deepUngroup", &json!({"ids": [outer.0]})).unwrap();
|
||||
assert_eq!((r["ungrouped"].clone(), r["ids"].clone()), (json!(3), json!([c.0])));
|
||||
assert!(node(&s, e).unwrap().locked && !node(&s, f).unwrap().visible);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [c]);
|
||||
// In a named layer and its sublayer; the layers and a clipping group stay.
|
||||
let layer = id_of(&s.execute("layer.new", &json!({})).unwrap());
|
||||
let g = rect(&mut s, 10.0, 100.0, 20.0, 20.0);
|
||||
let h = rect(&mut s, 40.0, 100.0, 20.0, 20.0);
|
||||
let layer_locked = wrap_all(&mut s, &[g], plain_group);
|
||||
change(&mut s, layer_locked, |n| n.locked = true);
|
||||
let layer_hidden = wrap_all(&mut s, &[h], plain_group);
|
||||
change(&mut s, layer_hidden, |n| n.visible = false);
|
||||
let sub = wrap_all(&mut s, &[layer_hidden], sublayer);
|
||||
let clipped = rect(&mut s, 100.0, 100.0, 10.0, 10.0);
|
||||
let clip = rect(&mut s, 95.0, 95.0, 30.0, 30.0);
|
||||
select(&mut s, &[clipped, clip]);
|
||||
s.execute("object.clippingMask.make", &json!({})).unwrap();
|
||||
let clip_group = s.doc().unwrap().selection.objects[0];
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cleanup.deepUngroup", &json!({"ids": [layer.0]})).unwrap();
|
||||
assert_eq!((r["ungrouped"].clone(), undo_steps(&s)), (json!(2), steps + 1));
|
||||
assert!(node(&s, layer_locked).is_none() && node(&s, layer_hidden).is_none());
|
||||
assert!(node(&s, layer).is_some() && node(&s, clip_group).is_some());
|
||||
assert!(node(&s, g).unwrap().locked && !node(&s, h).unwrap().visible);
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(h), Some(sub));
|
||||
// On a locked artboard, a named group stays whole, with the selection as it was.
|
||||
let k = rect(&mut s, 10.0, 200.0, 20.0, 20.0);
|
||||
let on_board = wrap_all(&mut s, &[k], plain_group);
|
||||
let off_board = rect(&mut s, 500.0, 10.0, 20.0, 20.0);
|
||||
s.edit("Lock Artboard", |d, _| {
|
||||
d.artboards[0].locked = true;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
select(&mut s, &[off_board]);
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cleanup.deepUngroup", &json!({"ids": [on_board.0]})).unwrap();
|
||||
assert_eq!((r["ungrouped"].clone(), r["ids"].clone(), undo_steps(&s)), (json!(0), json!([off_board.0]), steps));
|
||||
assert!(node(&s, on_board).is_some());
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [off_board]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejoin_joins_pieces_within_the_gap_only() {
|
||||
let mut s = session();
|
||||
@@ -646,3 +831,74 @@ fn rejoin_joins_pieces_within_the_gap_only() {
|
||||
assert!(s.execute("addon.cleanup.rejoin", &bad).is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Named by `ids`, Rejoin Path Pieces takes locked and hidden pieces (in a locked group or layer
|
||||
/// too) and joins only pieces alike in being hidden and in being locked, whichever is topmost, as one
|
||||
/// undo step; a locked or hidden path it makes is not selected. From the selection it takes only
|
||||
/// pieces that can be edited, and compound path members and pieces on a locked artboard stay out.
|
||||
#[test]
|
||||
fn rejoin_named_locked_and_hidden_pieces() {
|
||||
let mut s = session();
|
||||
let a = line(&mut s, &[(10.0, 10.0), (50.0, 10.0)]);
|
||||
let b = line(&mut s, &[(50.05, 10.0), (90.0, 10.0)]);
|
||||
let g = wrap_all(&mut s, &[a, b], plain_group);
|
||||
change(&mut s, g, |n| n.locked = true);
|
||||
select(&mut s, &[g]);
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cleanup.rejoin", &json!({})).unwrap();
|
||||
assert_eq!((r["joined"].clone(), undo_steps(&s)), (json!(0), steps), "from the selection, none is taken");
|
||||
let r = s.execute("addon.cleanup.rejoin", &json!({"ids": [g.0]})).unwrap();
|
||||
assert_eq!((r["joined"].clone(), r["removed"].clone(), r["ids"].clone()), (json!(1), json!(1), json!([b.0])));
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
assert!(node(&s, a).is_none() && anchors(&s, b) == 3);
|
||||
assert!(s.doc().unwrap().selection.objects.is_empty(), "the locked path is not selected");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(node(&s, a).is_some() && anchors(&s, b) == 2);
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert!(node(&s, a).is_none() && anchors(&s, b) == 3);
|
||||
// A shown piece and two hidden ones, the hidden on top: only the hidden pair joins.
|
||||
let c = line(&mut s, &[(10.0, 40.0), (50.0, 40.0)]);
|
||||
let e = line(&mut s, &[(50.05, 40.0), (90.0, 40.0)]);
|
||||
let h = line(&mut s, &[(90.05, 40.0), (130.0, 40.0)]);
|
||||
change(&mut s, e, |n| n.visible = false);
|
||||
change(&mut s, h, |n| n.visible = false);
|
||||
let r = s.execute("addon.cleanup.rejoin", &json!({"ids": [c.0, e.0, h.0]})).unwrap();
|
||||
assert_eq!((r["joined"].clone(), r["removed"].clone(), r["ids"].clone()), (json!(1), json!(1), json!([h.0])));
|
||||
assert!(node(&s, e).is_none() && anchors(&s, c) == 2 && anchors(&s, h) == 3);
|
||||
assert!(!node(&s, h).unwrap().visible && node(&s, c).unwrap().visible);
|
||||
assert!(s.doc().unwrap().selection.objects.is_empty(), "the hidden path is not selected");
|
||||
// An unlocked piece under a locked one, and a hidden piece under a shown one: none joins.
|
||||
let k = line(&mut s, &[(10.0, 70.0), (50.0, 70.0)]);
|
||||
let m = line(&mut s, &[(50.05, 70.0), (90.0, 70.0)]);
|
||||
let n = line(&mut s, &[(10.0, 100.0), (50.0, 100.0)]);
|
||||
let o = line(&mut s, &[(50.05, 100.0), (90.0, 100.0)]);
|
||||
change(&mut s, m, |x| x.locked = true);
|
||||
change(&mut s, n, |x| x.visible = false);
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cleanup.rejoin", &json!({"ids": [k.0, m.0, n.0, o.0]})).unwrap();
|
||||
assert_eq!((r["joined"].clone(), r["removed"].clone(), undo_steps(&s)), (json!(0), json!(0), steps));
|
||||
assert!([k, m, n, o].iter().all(|id| anchors(&s, *id) == 2));
|
||||
// Named pieces in a locked layer join; members of a compound path stay out.
|
||||
let layer = id_of(&s.execute("layer.new", &json!({})).unwrap());
|
||||
let p = line(&mut s, &[(10.0, 130.0), (50.0, 130.0)]);
|
||||
let q = line(&mut s, &[(50.05, 130.0), (90.0, 130.0)]);
|
||||
let u = line(&mut s, &[(10.0, 160.0), (50.0, 160.0)]);
|
||||
let v = line(&mut s, &[(50.05, 160.0), (90.0, 160.0)]);
|
||||
wrap_all(&mut s, &[u, v], |c| NodeKind::Compound { children: c, rule: FillRule::NonZero });
|
||||
let w = line(&mut s, &[(10.0, 200.0), (50.0, 200.0)]);
|
||||
let x = line(&mut s, &[(50.05, 200.0), (90.0, 200.0)]);
|
||||
change(&mut s, layer, |l| l.locked = true);
|
||||
let r = s.execute("addon.cleanup.rejoin", &json!({"ids": [p.0, q.0, u.0, v.0]})).unwrap();
|
||||
assert_eq!((r["joined"].clone(), r["ids"].clone()), (json!(1), json!([q.0])));
|
||||
assert!(node(&s, p).is_none() && anchors(&s, u) == 2 && anchors(&s, v) == 2);
|
||||
// On a locked artboard, named pieces stay as they are.
|
||||
s.edit("Lock Artboard", |d, _| {
|
||||
d.artboards[0].locked = true;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cleanup.rejoin", &json!({"ids": [w.0, x.0]})).unwrap();
|
||||
assert_eq!((r["joined"].clone(), undo_steps(&s)), (json!(0), steps));
|
||||
assert!(node(&s, w).is_some() && node(&s, x).is_some());
|
||||
}
|
||||
|
||||
@@ -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:?}");
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -422,6 +422,15 @@ pub(crate) fn design_reference(s: &Session, p: &Value, cmd: &str) -> Result<Opti
|
||||
Ok(ids.first().copied().filter(|id| super::graph::is_design_art(d, *id)))
|
||||
}
|
||||
|
||||
/// The [`design_reference`] of an edit aimed at `item`: none for the Appearance panel's active row, which is a row of the
|
||||
/// first selected object's stack.
|
||||
pub(crate) fn reference_of(s: &Session, p: &Value, item: ItemTarget, cmd: &str) -> Result<Option<NodeId>> {
|
||||
if matches!(item, ItemTarget::Item { explicit: false, .. }) {
|
||||
return Ok(None);
|
||||
}
|
||||
design_reference(s, p, cmd)
|
||||
}
|
||||
|
||||
/// `ids` after `of` (see [`design_reference`]), when there is one.
|
||||
pub(crate) fn with_reference(of: Option<NodeId>, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
of.into_iter().chain(ids.iter().copied()).collect()
|
||||
@@ -610,16 +619,23 @@ fn require_targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
|
||||
/// ([`capture_series_changes`], [`super::graph::capture_label_changes`]). Nothing targeted is not
|
||||
/// an edit, and when `f` leaves every target as it was, the document and its undo history stay as
|
||||
/// they are.
|
||||
///
|
||||
/// With `of` (see [`reference_of`]), an explicit aligned `item` is a row of the stack of `of`, which
|
||||
/// is not among `ids`: it must be there and of the edited kind, each target edits the row equal to
|
||||
/// it, a target without one is left as it is, and no target with one is an error. Returns the
|
||||
/// targets `f` was aimed at, in the order of `ids`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn edit_items(
|
||||
s: &mut Session,
|
||||
ids: &[NodeId],
|
||||
item: ItemTarget,
|
||||
of: Option<NodeId>,
|
||||
cmd: &str,
|
||||
label: &str,
|
||||
fill: bool,
|
||||
f: impl FnMut(&mut Node, Option<usize>) -> Result<()>,
|
||||
) -> Result<()> {
|
||||
edit_items_then(s, ids, item, cmd, label, fill, f, |before, d, edited| {
|
||||
) -> Result<Vec<NodeId>> {
|
||||
edit_items_then(s, ids, item, of, cmd, label, fill, f, |before, d, edited| {
|
||||
let series = capture_series_changes(before, d, edited);
|
||||
// The rows `f` edited are kept by `edit_items_then`.
|
||||
let labels = super::graph::capture_label_changes(before, d, edited, false);
|
||||
@@ -636,17 +652,29 @@ pub(crate) fn edit_items_then(
|
||||
s: &mut Session,
|
||||
ids: &[NodeId],
|
||||
item: ItemTarget,
|
||||
of: Option<NodeId>,
|
||||
cmd: &str,
|
||||
label: &str,
|
||||
fill: bool,
|
||||
mut f: impl FnMut(&mut Node, Option<usize>) -> Result<()>,
|
||||
mut after: impl FnMut(&vectorcraft_doc::Document, &mut vectorcraft_doc::Document, &[NodeId]) -> Result<bool>,
|
||||
) -> Result<()> {
|
||||
if ids.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
) -> Result<Vec<NodeId>> {
|
||||
let art = of.and_then(|of| s.doc().ok()?.doc.node(of).map(|n| n.appearance.clone()));
|
||||
let per = match (item, art) {
|
||||
// Checked even when the art is the only object given, which leaves `ids` empty.
|
||||
(ItemTarget::Item { index, explicit: true, aligned: true }, Some(art)) => {
|
||||
item.resolve(&art, fill, cmd)?;
|
||||
let per = item.per_target_of(s, of, ids);
|
||||
if per.iter().all(Option::is_none) {
|
||||
return Err(bad(cmd, format!("no appearance item {index}")));
|
||||
}
|
||||
per
|
||||
}
|
||||
_ if ids.is_empty() => return Ok(Vec::new()),
|
||||
_ => item.per_target(s, ids),
|
||||
};
|
||||
let aimed: Vec<NodeId> = ids.iter().zip(&per).filter(|(_, item)| item.is_some()).map(|(id, _)| *id).collect();
|
||||
let before = s.doc()?.doc.clone();
|
||||
let per = item.per_target(s, ids);
|
||||
super::overprint::edit_counted(s, label, |d| {
|
||||
let mut edited = Vec::new();
|
||||
// The objects whose rows `f` edited: on type, no row means its characters.
|
||||
@@ -665,7 +693,13 @@ pub(crate) fn edit_items_then(
|
||||
let labels = super::graph::capture_label_rows(d, &rows);
|
||||
Ok(count_changed(d, &before, &edited) + usize::from(more || labels))
|
||||
})?;
|
||||
Ok(())
|
||||
Ok(aimed)
|
||||
}
|
||||
|
||||
/// The first of `ids` that [`edit_items`] aimed at `item` with `of` changes, and the item it changes there. Read it
|
||||
/// before the edit: once edited, a row that was equal to a row of the art of `of` no longer is.
|
||||
pub(crate) fn first_edited(s: &Session, item: ItemTarget, of: Option<NodeId>, ids: &[NodeId]) -> Option<(NodeId, ItemTarget)> {
|
||||
ids.iter().zip(item.per_target_of(s, of, ids)).find_map(|(id, it)| Some((*id, it?)))
|
||||
}
|
||||
|
||||
/// How many of `ids` differ in `d` from `before`.
|
||||
@@ -674,8 +708,8 @@ pub(crate) fn count_changed(d: &vectorcraft_doc::Document, before: &vectorcraft_
|
||||
}
|
||||
|
||||
/// Whether an edit aimed at `item` changes a stroke: the `stroke` param, else the kind of the
|
||||
/// targeted item (on the object whose row it is, see [`ItemTarget::anchor`]), else `default`. A `stroke` other than true, false or
|
||||
/// null is an error of command `cmd`.
|
||||
/// targeted item (on the object whose row it is, see [`ItemTarget::anchor`] and [`reference_of`]), else `default`. A `stroke` other than
|
||||
/// true, false or null is an error of command `cmd`.
|
||||
pub(crate) fn edits_stroke(s: &Session, p: &Value, item: ItemTarget, default: bool, cmd: &str) -> Result<bool> {
|
||||
check_switches(p, &["stroke"], cmd)?;
|
||||
if let Some(b) = p.get("stroke").and_then(Value::as_bool) {
|
||||
@@ -683,8 +717,14 @@ pub(crate) fn edits_stroke(s: &Session, p: &Value, item: ItemTarget, default: bo
|
||||
}
|
||||
let ItemTarget::Item { index, .. } = item else { return Ok(default) };
|
||||
let d = &s.doc()?.doc;
|
||||
let ids = drop_design_art(d, appearance_targets(s, p)?);
|
||||
Ok(ids.get(item.anchor(s, &ids)).and_then(|id| d.node(*id)?.appearance.items.get(index)).map_or(default, |it| !it.is_fill()))
|
||||
let holder = match reference_of(s, p, item, cmd)? {
|
||||
Some(of) => Some(of),
|
||||
None => {
|
||||
let ids = drop_design_art(d, appearance_targets(s, p)?);
|
||||
ids.get(item.anchor(s, &ids)).copied()
|
||||
}
|
||||
};
|
||||
Ok(holder.and_then(|id| d.node(id)?.appearance.items.get(index)).map_or(default, |it| !it.is_fill()))
|
||||
}
|
||||
|
||||
/// The whole number of 0 or more that `key` holds, read with [`u64_req`] and [`index`].
|
||||
|
||||
@@ -19,8 +19,8 @@ use super::edit::{outermost, selected_roots};
|
||||
use super::pathops::{remove_each, separate};
|
||||
use super::swatch::{anchor, names_param};
|
||||
use super::{
|
||||
CommandSpec, Result, Session, bad, check_numbers, cmd, color_param, find_command, has_doc, has_selection, id_param, named_ids, number_or, ok,
|
||||
str_param, switch_or,
|
||||
CommandSpec, Result, Session, bad, check_numbers, cmd, color_param, find_command, has_doc, has_selection, named_ids, number_or, ok, str_param,
|
||||
switch_or,
|
||||
};
|
||||
use crate::EngineError;
|
||||
|
||||
@@ -180,7 +180,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Paintbrush",
|
||||
[],
|
||||
None,
|
||||
"{…params as path.freehand, brush?: name} paint a freehand stroke with a brush; without `brush` (or with null) the plain path is drawn; a `brush` that names no brush in the document, or a `style` other than \"pencil\" or \"brush\", is an error and nothing is drawn → {id}",
|
||||
"{…params as path.freehand, brush?: name} paint a freehand stroke with a brush; without `brush` (or with null) the plain path is drawn; a `brush` that names no brush in the document, a `style` other than \"pencil\" or \"brush\", a `brush` for a path with no stroke (a continued or redrawn path without one, or a new filled \"pencil\" path while the stroke is None) and an unknown key are errors and nothing is drawn; the path and its brush are one undo step → {id}",
|
||||
has_doc,
|
||||
brush_freehand
|
||||
),
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
use super::{
|
||||
AppearanceItem, Arc, BTreeSet, Bristle, Brush, BrushKind, Color, Document, EngineError, Node, NodeId, NodeKind, Paint, Result, Session, Value,
|
||||
anchor, bad, brush, check_numbers, find_command, id_param, ids_json, json, name_param, names_param, ok, roots, selection_art, set_unknown,
|
||||
str_param,
|
||||
anchor, bad, brush, check_numbers, find_command, ids_json, json, name_param, names_param, ok, roots, selection_art, set_unknown, str_param,
|
||||
};
|
||||
|
||||
// ---------- brushes ----------
|
||||
@@ -729,9 +728,10 @@ pub(super) fn expand_brush(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "ids": ids_json(&out) }))
|
||||
}
|
||||
|
||||
/// Paints a `path.freehand` stroke with the brush `brush` names. A `brush` left out or null draws
|
||||
/// the plain path; a `brush` that is not a string or names no brush in the document, and a `style`
|
||||
/// other than "pencil" or "brush", is an error before anything is drawn.
|
||||
/// Paints a `path.freehand` stroke with the brush `brush` names, in one undo step with the path.
|
||||
/// A `brush` left out or null draws the plain path; a `brush` that is not a string or names no
|
||||
/// brush in the document, a `style` other than "pencil" or "brush", and a `brush` for a path with
|
||||
/// no stroke are errors before anything is drawn.
|
||||
pub(super) fn brush_freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "brush.freehand";
|
||||
let name = match crate::cmd::text_param(p, "brush", C)? {
|
||||
@@ -745,13 +745,6 @@ pub(super) fn brush_freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(v) => return Err(bad(C, format!("`style` must be \"pencil\" or \"brush\", not {v}"))),
|
||||
}
|
||||
let spec = find_command("path.freehand").ok_or_else(|| EngineError::UnknownCommand("path.freehand".into()))?;
|
||||
let r = crate::cmd::run_checked(s, spec, p)?;
|
||||
let (Some(name), Some(id)) = (name, id_param(&r, "id")) else { return Ok(r) };
|
||||
s.edit("Paintbrush", |d, _| {
|
||||
if let Some(st) = d.node_mut(id).and_then(|n| n.appearance.stroke_mut()) {
|
||||
st.brush = Some(name.clone());
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(r)
|
||||
let checked = crate::schemas::check(spec, p, s.replaying())?;
|
||||
crate::cmd::draw2::freehand_brushed(s, checked.as_ref().unwrap_or(p), name.as_deref())
|
||||
}
|
||||
|
||||
@@ -117,7 +117,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Live Paint Bucket",
|
||||
[],
|
||||
None,
|
||||
"{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], points?: [[x,y]…] (a drag polyline starting at point; 1 to 4096 finite canvas points; fills every crossed face of the same group), continuation?: [[[x,y]…]…] (further path chunks of 1 to 4096 finite canvas points each; each starts at the preceding chunk's last point; requires points), scope?: \"one\" (default: the face alone) | \"connected\" (a double-click: also each face reached across edges that are hidden or draw no stroke, as a flood from the face; a stroked edge, a hidden face or a Gap Detection gap stops it) | \"samePaint\" (a triple-click: also every face of the group whose fill is match; \"connected\" and \"samePaint\" are refused with points), match?: paint (as the document stores it, the `fill` of a face's appearance; scope samePaint only; default: the face's fill), color?|swatch?|gradient?|none? (default: current fill; a color in #rrggbbaa or #rgba is refused), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces; when every face it reaches already has the paint, nothing changes (no undo step, and the recent colors stay as they are) → {group, face, count (faces reached)}",
|
||||
"{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], points?: [[x,y]…] (a drag polyline starting at point; 1 to 4096 finite canvas points; fills every crossed face of the same group), continuation?: [[[x,y]…]…] (further path chunks of 1 to 4096 finite canvas points each; each starts at the preceding chunk's last point; requires points), scope?: \"one\" (default: the face alone) | \"connected\" (a double-click: also each face reached across edges that are hidden or draw no stroke, as a flood from the face; a stroked edge, a hidden face or a Gap Detection gap stops it) | \"samePaint\" (a triple-click: also every face of the group whose fill is match; \"connected\" and \"samePaint\" are refused with points), match?: paint (as the document stores it, the `fill` of a face's appearance; scope samePaint only; default: the face's fill), color?|swatch?|gradient?|none? (default: current fill; a color in #rrggbbaa or #rgba is refused), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces: each face reached has its fills replaced by one fill with the paint, shown, fully opaque and blending normally, in the place of its topmost fill (none leaves one fill of none), and its strokes and its own opacity stay as they are; when every face it reaches already has only that one fill, nothing changes (no undo step, and the recent colors stay as they are) → {group, face, count (faces reached)}",
|
||||
has_doc,
|
||||
lp_fill
|
||||
),
|
||||
@@ -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 takes the paint and width in its topmost stroke that is shown, or in a new stroke above the others when it has none; when every edge it reaches already has the paint and the width there, 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), 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
|
||||
),
|
||||
@@ -144,7 +144,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Make",
|
||||
["Object", "Image Trace"],
|
||||
None,
|
||||
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\", ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}",
|
||||
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" group under the paths holds 1.5 px strokes along the edges two filled paths share, in the color of the lower path, so that no light hairline shows along those edges; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}",
|
||||
has_selection_or_ids,
|
||||
|s, p| trace_make(s, p, false)
|
||||
),
|
||||
|
||||
@@ -525,16 +525,17 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(gid) => {
|
||||
let (fid, targets) = targets_in(&s.doc()?.doc, gid)?;
|
||||
let count = targets.len();
|
||||
// Faces that already have the paint stay as they are: when every face has it, nothing
|
||||
// changes and no undo step is recorded.
|
||||
// Faces that already have only the fill the bucket would leave ([`bucket_keeps`]) stay as
|
||||
// they are: when every face does, nothing changes and no undo step is recorded.
|
||||
let d = &s.doc()?.doc;
|
||||
let unpainted: Vec<NodeId> = targets.into_iter().filter(|t| d.node(*t).is_none_or(|f| f.appearance.fill_paint() != paint)).collect();
|
||||
let unpainted: Vec<NodeId> =
|
||||
targets.into_iter().filter(|t| d.node(*t).is_none_or(|f| !bucket_keeps(&f.appearance, true, &paint, 0.0))).collect();
|
||||
if unpainted.is_empty() {
|
||||
return Ok(json!({ "group": gid.0, "face": fid.0, "count": count }));
|
||||
}
|
||||
s.edit("Live Paint Bucket", |d, _| {
|
||||
for target in unpainted {
|
||||
d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance.set_fill(paint.clone());
|
||||
bucket_paint(&mut d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance, true, &paint, 0.0);
|
||||
}
|
||||
Ok((gid, fid, count))
|
||||
})?
|
||||
@@ -544,7 +545,7 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (fid, targets) = targets_in(d, gid)?;
|
||||
let count = targets.len();
|
||||
for target in targets {
|
||||
d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance.set_fill(paint.clone());
|
||||
bucket_paint(&mut d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance, true, &paint, 0.0);
|
||||
}
|
||||
Ok((gid, fid, count))
|
||||
})?,
|
||||
@@ -580,18 +581,10 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.collect(),
|
||||
};
|
||||
let count = targets.len();
|
||||
// An edge whose shown stroke already has the paint and the width (or that has no shown stroke
|
||||
// and gets none) stays as it is; when every edge does, nothing changes and no undo step is
|
||||
// recorded.
|
||||
let changed: Vec<NodeId> = targets
|
||||
.into_iter()
|
||||
.filter(|t| {
|
||||
d.node(*t).is_none_or(|e| match shown_stroke(e) {
|
||||
Some(st) => !(st.paint == paint && st.width == width),
|
||||
None => !paint.is_none(),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
// An edge that already has only the stroke the bucket would leave ([`bucket_keeps`]) stays
|
||||
// as it is; when every edge does, nothing changes and no undo step is recorded.
|
||||
let changed: Vec<NodeId> =
|
||||
targets.into_iter().filter(|t| d.node(*t).is_none_or(|e| !bucket_keeps(&e.appearance, false, &paint, width))).collect();
|
||||
(eid, count, changed)
|
||||
};
|
||||
if changed.is_empty() {
|
||||
@@ -599,14 +592,7 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
s.edit("Live Paint Bucket", |d, _| {
|
||||
for target in &changed {
|
||||
let e = d.node_mut(*target).ok_or(EngineError::NoNode(*target))?;
|
||||
match shown_stroke_mut(e) {
|
||||
Some(st) => {
|
||||
st.paint = paint.clone();
|
||||
st.width = width;
|
||||
}
|
||||
None => e.appearance.items.push(super::AppearanceItem::Stroke(super::StrokeLayer::new(paint.clone(), width))),
|
||||
}
|
||||
bucket_paint(&mut d.node_mut(*target).ok_or(EngineError::NoNode(*target))?.appearance, false, &paint, width);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
@@ -614,22 +600,76 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "group": g.0, "edge": eid.0, "count": count }))
|
||||
}
|
||||
|
||||
/// The stroke `livePaint.strokeEdge` paints on Live Paint edge `e`: its topmost stroke that is
|
||||
/// shown. None when it has no stroke or every stroke is hidden; the command then adds a stroke
|
||||
/// above the others.
|
||||
fn shown_stroke(e: &Node) -> Option<&super::StrokeLayer> {
|
||||
e.appearance.items.iter().rev().find_map(|i| match i {
|
||||
super::AppearanceItem::Stroke(s) if s.visible => Some(s),
|
||||
_ => None,
|
||||
})
|
||||
/// Whether the Live Paint Bucket leaves appearance `a` as it is when it paints its fills (`fill`)
|
||||
/// or strokes with `paint` (a stroke at `width`): it has exactly one row of that kind, shown, fully
|
||||
/// opaque, blending normally and with the paint (a stroke also with the width, unless the paint is
|
||||
/// none), or it has no row of that kind and the paint is none.
|
||||
fn bucket_keeps(a: &Appearance, fill: bool, paint: &super::Paint, width: f64) -> bool {
|
||||
let mut rows = a.items.iter().filter(|i| i.is_fill() == fill);
|
||||
match (rows.next(), rows.next()) {
|
||||
(None, _) => paint.is_none(),
|
||||
(Some(row), None) => {
|
||||
row.visible()
|
||||
&& row.opacity() == 1.0
|
||||
&& row.blend() == vectorcraft_color::BlendMode::Normal
|
||||
&& row.paint() == paint
|
||||
&& match row {
|
||||
AppearanceItem::Fill(_) => true,
|
||||
AppearanceItem::Stroke(st) => paint.is_none() || st.width == width,
|
||||
}
|
||||
}
|
||||
(Some(_), Some(_)) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// [`shown_stroke`], to change.
|
||||
fn shown_stroke_mut(e: &mut Node) -> Option<&mut super::StrokeLayer> {
|
||||
e.appearance.items.iter_mut().rev().find_map(|i| match i {
|
||||
super::AppearanceItem::Stroke(s) if s.visible => Some(s),
|
||||
_ => None,
|
||||
})
|
||||
/// Paint the fills (`fill`) or strokes of appearance `a` with `paint` (a stroke at `width`), as the
|
||||
/// Live Paint Bucket does: every row of that kind is replaced by one row, shown, fully opaque and
|
||||
/// blending normally, in the place of the topmost row of that kind. The new row keeps the other
|
||||
/// settings (a stroke's dashes, caps and arrowheads, a row's effects) of the topmost row of that
|
||||
/// kind that is shown, or of the topmost one when every row is hidden. Rows of the other kind stay
|
||||
/// as they are. With no row of that kind, a fill is added below the strokes and a stroke above the
|
||||
/// fills.
|
||||
fn bucket_paint(a: &mut Appearance, fill: bool, paint: &super::Paint, width: f64) {
|
||||
let of_kind = |i: &AppearanceItem| i.is_fill() == fill;
|
||||
let Some(top) = a.items.iter().rposition(of_kind) else {
|
||||
if fill {
|
||||
a.set_fill(paint.clone());
|
||||
} else {
|
||||
a.items.push(AppearanceItem::Stroke(super::StrokeLayer::new(paint.clone(), width)));
|
||||
}
|
||||
return;
|
||||
};
|
||||
let base = a.items.iter().rposition(|i| of_kind(i) && i.visible()).unwrap_or(top);
|
||||
let Some(mut row) = a.items.get(base).cloned() else { return };
|
||||
match &mut row {
|
||||
AppearanceItem::Fill(f) => {
|
||||
f.paint = paint.clone();
|
||||
f.opacity = 1.0;
|
||||
f.blend = vectorcraft_color::BlendMode::Normal;
|
||||
f.visible = true;
|
||||
}
|
||||
AppearanceItem::Stroke(st) => {
|
||||
st.paint = paint.clone();
|
||||
st.width = width;
|
||||
st.opacity = 1.0;
|
||||
st.blend = vectorcraft_color::BlendMode::Normal;
|
||||
st.visible = true;
|
||||
}
|
||||
}
|
||||
let mut row = Some(row);
|
||||
a.items = std::mem::take(&mut a.items)
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, item)| {
|
||||
if i == top {
|
||||
row.take()
|
||||
} else if of_kind(&item) {
|
||||
None
|
||||
} else {
|
||||
Some(item)
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
|
||||
/// Every fill and stroke row of face or edge `n`, bottom first, as `livePaint.info` lists them. A
|
||||
|
||||
@@ -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 ----------
|
||||
@@ -22,6 +23,22 @@ fn is_trace_group(n: &Node) -> bool {
|
||||
&& n.children().is_some_and(|c| c.first().is_some_and(|i| matches!(i.kind, NodeKind::Image(_))))
|
||||
}
|
||||
|
||||
/// The name of the group that holds an Abutting trace's seam fills (see [`tr::TraceResult::seams`]).
|
||||
const SEAM_FILLS_NAME: &str = "Seam Fills";
|
||||
|
||||
/// Whether `n` can be a trace's seam fills group: a group named as one, or a group of stroked paths
|
||||
/// without fills, so that it is still found after it is renamed or its strokes are edited. (Auto
|
||||
/// Grouping groups hold filled paths.)
|
||||
fn is_seam_fills(n: &Node) -> bool {
|
||||
let stroke_only = |m: &Arc<Node>| {
|
||||
matches!(m.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
|
||||
&& m.appearance.fill_paint() == Paint::None
|
||||
&& m.appearance.stroke_paint() != Paint::None
|
||||
};
|
||||
matches!(n.kind, NodeKind::Group { clip: false, .. })
|
||||
&& (n.name.as_deref() == Some(SEAM_FILLS_NAME) || n.children().is_some_and(|c| !c.is_empty() && c.iter().all(stroke_only)))
|
||||
}
|
||||
|
||||
const LIVE_PATHFINDER_BY_COLOR: &str = "byColor can't regroup a trace with a live Pathfinder effect: expand without byColor";
|
||||
|
||||
/// The `view` param ([`TraceView`] id), if given.
|
||||
@@ -393,11 +410,15 @@ fn by_color_param(cmd: &str, p: &Value) -> Result<bool> {
|
||||
/// (by the boxes of everything they paint, effects included, within one point); otherwise it
|
||||
/// starts another group of that paint, which keeps the stacking order of those items. Items
|
||||
/// farther apart can still share antialiased pixels at small view or raster-export scales, so
|
||||
/// their edge pixels may change. A group among `items` (Auto Grouping) is refused.
|
||||
/// their edge pixels may change. The seam fills' group, when it is the lowest item, stays as it is,
|
||||
/// under every other group. Any other group among `items` (Auto Grouping) is refused.
|
||||
fn color_groups(cmd: &str, d: &mut Document, items: Vec<Arc<Node>>) -> Result<Vec<Arc<Node>>> {
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::ops::Bound::{Excluded, Unbounded};
|
||||
use vectorcraft_color::tint_percent;
|
||||
// The seam fills come first, under every path: kept there, they move under nothing.
|
||||
let mut items = items;
|
||||
let seams: Vec<Arc<Node>> = if items.first().is_some_and(|n| is_seam_fills(n)) { items.drain(..1).collect() } else { vec![] };
|
||||
// Grouped by the paint: unlinked (its #rrggbb), linked (the swatch and its exact tint), a
|
||||
// gradient, or another paint (its label). The name is apart from it: a swatch may be named as
|
||||
// a color's `#rrggbb` or as "Gradients".
|
||||
@@ -517,25 +538,31 @@ fn color_groups(cmd: &str, d: &mut Document, items: Vec<Arc<Node>>) -> Result<Ve
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(groups
|
||||
let groups: Vec<Arc<Node>> = groups
|
||||
.into_iter()
|
||||
.map(|run| {
|
||||
let mut g = Node::group(d.alloc_id(), run.members);
|
||||
g.name = Some(run.name);
|
||||
Arc::new(g)
|
||||
})
|
||||
.collect())
|
||||
.collect();
|
||||
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.
|
||||
@@ -604,21 +631,25 @@ fn prepare(s: &Session, c: &str, p: &Value) -> Result<Prepared> {
|
||||
let bytes = Arc::clone(&blob.bytes);
|
||||
let library = trace_library(c, s, &mut params)?;
|
||||
let traced_with = serde_json::to_value(¶ms).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
let inputs = TraceInputs { 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 })
|
||||
}
|
||||
|
||||
/// What a trace made of an image: the size in pixels it was decoded at, and the paths.
|
||||
/// What a trace made of an image: the size in pixels it was decoded at, the paths, and their seam
|
||||
/// fills ([`seams_within`]).
|
||||
pub struct Traced {
|
||||
inputs: TraceInputs,
|
||||
raster: (u32, u32),
|
||||
res: tr::TraceResult,
|
||||
seams: Vec<tr::TracedPath>,
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
@@ -627,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) {
|
||||
@@ -636,7 +669,18 @@ fn trace_now(inputs: &TraceInputs, params: &tr::TraceParams, steps: &(dyn Fn(u64
|
||||
tr::TraceError::Cancelled => EngineError::Cancelled,
|
||||
e => EngineError::Other(e.to_string()),
|
||||
})?;
|
||||
Ok(Traced { inputs: inputs.clone(), raster: (raster.width, raster.height), res })
|
||||
let seams = seams_within(&res, params, MAX_TRACE_ANCHORS);
|
||||
Ok(Traced { inputs: inputs.clone(), raster: (raster.width, raster.height), res, seams })
|
||||
}
|
||||
|
||||
/// The seam fills of `res`, traced with `params` ([`tr::seam_fills`]), while the paths and the seam
|
||||
/// fills together stay within `max` anchors: the seam fills have at most as many anchors as the
|
||||
/// paths, so a trace whose paths have more than half of `max` gets none.
|
||||
fn seams_within(res: &tr::TraceResult, params: &tr::TraceParams, max: usize) -> Vec<tr::TracedPath> {
|
||||
if res.anchor_count() > max / 2 {
|
||||
return vec![];
|
||||
}
|
||||
tr::seam_fills(&res.paths, params)
|
||||
}
|
||||
|
||||
/// An Image Trace made away from its command, off the UI thread (#3098). [`TraceRun::prepare`]
|
||||
@@ -691,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> {
|
||||
@@ -716,7 +773,7 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
s.note_journal("savedPreset", recorded);
|
||||
}
|
||||
// A trace handed in for these very inputs ([`TraceRun`]), else one made now.
|
||||
let Traced { raster, res, .. } = match s.trace_hand_off.take() {
|
||||
let Traced { raster, res, seams: seam_fills, .. } = match s.trace_hand_off.take() {
|
||||
Some(traced) if traced.inputs == inputs => traced,
|
||||
_ => trace_now(&inputs, &trace, &|_, _| true)?,
|
||||
};
|
||||
@@ -729,6 +786,13 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
let xf = img.xf * vectorcraft_geom::Affine::scale_non_uniform(sx, sy);
|
||||
// Document units per raster pixel (stroke widths).
|
||||
let unit = xf.determinant().abs().sqrt();
|
||||
// Seam fills: document units per raster pixel along the direction the image is stretched most,
|
||||
// so that a stroke covers its pixels across an edge at any angle.
|
||||
let seam_unit = {
|
||||
let [a, b, c, d, _, _] = xf.as_coeffs();
|
||||
let (t, det) = (a * a + b * b + c * c + d * d, a * d - b * c);
|
||||
((t + (t * t - 4.0 * det * det).max(0.0).sqrt()) / 2.0).sqrt()
|
||||
};
|
||||
let (npaths, anchors, colors) = (res.paths.len(), res.anchor_count(), res.palette.len());
|
||||
let label = if expand { "Image Trace (Make and Expand)" } else { "Image Trace" };
|
||||
// A library color fills with the swatch's displayed color (its model kept), unlinked.
|
||||
@@ -754,8 +818,38 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
hidden.visible = false;
|
||||
children.push(Arc::new(hidden));
|
||||
}
|
||||
let paint_of = |tp: &tr::TracedPath| {
|
||||
let solid =
|
||||
by_color.get(&tp.color).map_or_else(|| Paint::solid(Color::rgb8(tp.color[0], tp.color[1], tp.color[2])), |paint| (*paint).clone());
|
||||
// Gradients: a path the tracer found to be a linear gradient is filled with it.
|
||||
tp.gradient.as_ref().map_or(solid, |g| traced_gradient(g, xf))
|
||||
};
|
||||
// Abutting: the seam fills, in a group of their own under every path.
|
||||
let seams: Vec<Arc<Node>> = seam_fills
|
||||
.iter()
|
||||
.filter_map(|tp| {
|
||||
let width = tp.stroke?;
|
||||
let mut n = shape_node(d, tp.path.transformed(xf), None);
|
||||
n.appearance = Appearance {
|
||||
items: vec![AppearanceItem::Stroke(StrokeLayer {
|
||||
cap: LineCap::Butt,
|
||||
join: LineJoin::Round,
|
||||
..StrokeLayer::new(paint_of(tp), width * seam_unit)
|
||||
})],
|
||||
..Default::default()
|
||||
}
|
||||
.into();
|
||||
Some(Arc::new(n))
|
||||
})
|
||||
.collect();
|
||||
if !seams.is_empty() {
|
||||
let mut g = Node::group(d.alloc_id(), seams);
|
||||
g.name = Some(SEAM_FILLS_NAME.into());
|
||||
children.push(Arc::new(g));
|
||||
}
|
||||
let mut traced = Vec::with_capacity(res.paths.len());
|
||||
for tp in res.paths {
|
||||
let paint = paint_of(&tp);
|
||||
let path = tp.path.transformed(xf);
|
||||
let mut n = shape_node(d, path, None);
|
||||
// Shapes: a path the tracer found to be a shape is that live shape.
|
||||
@@ -764,10 +858,6 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
*path = shape.to_path();
|
||||
*live = Some(Box::new(shape));
|
||||
}
|
||||
let solid =
|
||||
by_color.get(&tp.color).map_or_else(|| Paint::solid(Color::rgb8(tp.color[0], tp.color[1], tp.color[2])), |paint| (*paint).clone());
|
||||
// Gradients: a path the tracer found to be a linear gradient is filled with it.
|
||||
let paint = tp.gradient.as_ref().map_or(solid, |g| traced_gradient(g, xf));
|
||||
n.appearance = match tp.stroke {
|
||||
// Traced lines: round corners, and ends round or square as the tracer found them.
|
||||
Some(width) => Appearance {
|
||||
@@ -1103,9 +1193,28 @@ mod color_group_tests {
|
||||
|
||||
#[cfg(test)]
|
||||
mod trace_limit_tests {
|
||||
use super::{MAX_TRACE_ANCHORS, keep_warnings, trace_warnings};
|
||||
use super::{MAX_TRACE_ANCHORS, keep_warnings, seams_within, trace_warnings};
|
||||
use vectorcraft_trace as tr;
|
||||
|
||||
#[test]
|
||||
fn seam_fills_count_against_the_anchor_limit() {
|
||||
// Two colors side by side, the edge between them anti-aliased: one seam fill along it.
|
||||
let img = tr::Raster::from_fn(24, 16, |x, _| {
|
||||
let share = (10.4 - f64::from(x)).clamp(0.0, 1.0);
|
||||
let mix = |a: f64, b: f64| (a * share + b * (1.0 - share)).round() as u8;
|
||||
[mix(200.0, 30.0), mix(40.0, 90.0), mix(50.0, 200.0), 255]
|
||||
});
|
||||
let params = tr::TraceParams { mode: tr::Mode::Color, colors: 2, method: tr::Method::Abutting, ..tr::TraceParams::default() };
|
||||
let res = tr::trace(&img, ¶ms);
|
||||
let all = tr::seam_fills(&res.paths, ¶ms);
|
||||
assert!(!all.is_empty(), "{res:?}");
|
||||
let anchors = res.anchor_count();
|
||||
// Twice the paths' anchors leaves room for any seam fills.
|
||||
assert_eq!(seams_within(&res, ¶ms, 2 * anchors), all);
|
||||
// One anchor short of that: none.
|
||||
assert_eq!(seams_within(&res, ¶ms, 2 * anchors - 1), []);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keep_warnings_name_matched_colors_that_produce_no_paths() {
|
||||
let params = tr::TraceParams { keep_colors: vec!["#ff0000".into()], ..tr::TraceParams::default() };
|
||||
|
||||
@@ -32,7 +32,7 @@ use crate::DocState;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let mut v = vec![
|
||||
cmd!(query "clipboard.exportSvg", "Clipboard as SVG", [], None, "{} → {svg} the copied objects as standalone SVG (null when the clipboard is empty)", always, export_svg),
|
||||
cmd!(query "clipboard.exportSvg", "Clipboard as SVG", [], None, "{} → {svg} the copied objects as standalone SVG (null when the clipboard is empty). Under automation read roots it is refused while the SVG would name a linked image's file outside them (an image whose pixels the clipboard doesn't hold; a relative path is followed from the document the objects came from while it is open)", always, export_svg),
|
||||
cmd!(
|
||||
query "clipboard.importSvg",
|
||||
"Load SVG into Clipboard",
|
||||
@@ -435,14 +435,37 @@ impl Clipboard {
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The internal clipboard as standalone SVG (`None` when it is empty).
|
||||
/// The internal clipboard as standalone SVG (`None` when it is empty, and when the SVG would name
|
||||
/// a linked image's file the caller asking now may not be shown: [`Self::clipboard_svg_refused`]).
|
||||
pub fn clipboard_svg(&self) -> Option<String> {
|
||||
if self.clipboard_svg_refused() {
|
||||
return None;
|
||||
}
|
||||
self.clipboard.svg()
|
||||
}
|
||||
|
||||
/// Would the internal clipboard's SVG name a linked image's file outside the read roots in
|
||||
/// force? It names the file of an image whose pixels the clipboard doesn't hold. A relative
|
||||
/// path is followed from the document the objects came from while it is open; otherwise it
|
||||
/// counts as outside.
|
||||
pub fn clipboard_svg_refused(&self) -> bool {
|
||||
self.check_clipboard_svg("clipboard.exportSvg").is_err()
|
||||
}
|
||||
|
||||
/// [`Self::clipboard_svg_refused`] as `cmd`'s error, which names no file or folder.
|
||||
fn check_clipboard_svg(&self, cmd: &str) -> Result<()> {
|
||||
if crate::file_access::current().is_none() || !self.clipboard.has_art() {
|
||||
return Ok(());
|
||||
}
|
||||
let from = self.docs.iter().find(|d| Some(d.uid) == self.clipboard.source_doc);
|
||||
let base = from.map_or_else(super::links::LinkBase::default, super::links::LinkBase::of);
|
||||
super::fileio::check_images_in(cmd, "svg", &self.clipboard.to_document(), base, &json!({}))
|
||||
}
|
||||
}
|
||||
|
||||
fn export_svg(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({ "svg": s.clipboard_svg() }))
|
||||
s.check_clipboard_svg("clipboard.exportSvg")?;
|
||||
Ok(json!({ "svg": s.clipboard.svg() }))
|
||||
}
|
||||
|
||||
fn import_svg(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -16,7 +16,7 @@ use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::cms::{self, ColorSettings, Intent, Model, ProofTarget};
|
||||
use vectorcraft_color::cms::{self, ColorSettings, Intent, Model, Policy, ProofTarget};
|
||||
use vectorcraft_color::recolor::Neutral;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::ColorMode;
|
||||
@@ -37,7 +37,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Color Settings…",
|
||||
["Edit"],
|
||||
Some("Cmd+Shift+K"),
|
||||
"{rgb?: profile, cmyk?: profile, intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool} set the working spaces → {rgb, cmyk, intent, bpc, profiles: [{name, kind, builtin}]}. The desktop app and vectorcraft-cli keep them in `Color Settings.json` next to the preferences and use them again at the next start (not with VECTORCRAFT_NO_PREFS); saved settings naming a profile that is gone leave the defaults",
|
||||
"{rgb?: profile, cmyk?: profile, intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool, rgbPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\", cmykPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\"|\"preserveNumbers\"} set the working spaces and the color management policies → {rgb, cmyk, intent, bpc, rgbPolicy, cmykPolicy, profiles: [{name, kind, builtin}]}. A policy decides what opening a document (document.open, file.newFromTemplate, file.revert) does with an RGB or CMYK profile it is tagged with that is not the working space: preserveEmbedded (default) keeps it; off and preserveNumbers take it off and keep the color numbers; convert converts the colors of that model into the working space with the intent and bpc and takes it off. The open reply's warnings name each profile taken off or converted, and a document a policy changed opens with unsaved changes. The desktop app and vectorcraft-cli keep them in `Color Settings.json` next to the preferences and use them again at the next start (not with VECTORCRAFT_NO_PREFS); saved settings naming a profile that is gone leave the defaults",
|
||||
always,
|
||||
color_settings
|
||||
),
|
||||
@@ -64,7 +64,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Assign Profile…",
|
||||
["Edit"],
|
||||
None,
|
||||
"{rgb?: profile|null, cmyk?: profile|null} tag the document with profiles (color numbers are kept; null: the working space). Colors then show and convert through the profiles assigned; the working spaces stay as edit.colorSettings set them → {rgb, cmyk}",
|
||||
"{rgb?: profile|null, cmyk?: profile|null} tag the document with profiles (color numbers are kept; null: no profile, Don't Color Manage This Document, so colors show through the working space; the working space's name: that profile stays assigned when the working space changes). Colors then show and convert through the profiles assigned; the working spaces stay as edit.colorSettings set them → {rgb, cmyk}",
|
||||
has_doc,
|
||||
assign_profile
|
||||
),
|
||||
@@ -163,12 +163,26 @@ fn on_param(p: &Value, key: &str, cmd: &str) -> Result<Option<bool>> {
|
||||
switch_or(p, key, false, cmd).map(Some)
|
||||
}
|
||||
|
||||
/// The policy `p` gives for `key`, one of `allowed`, or `None` when `p` leaves it out.
|
||||
fn policy_param(p: &Value, key: &str, allowed: &[Policy], cmd: &str) -> Result<Option<Policy>> {
|
||||
let Some(v) = text_param(p, key, cmd)? else { return Ok(None) };
|
||||
match Policy::parse(v).filter(|x| allowed.contains(x)) {
|
||||
Some(x) => Ok(Some(x)),
|
||||
None => {
|
||||
let ids: Vec<&str> = allowed.iter().map(Policy::id).collect();
|
||||
Err(bad(cmd, format!("`{key}` must be one of {}", ids.join(", "))))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn settings_json(st: &ColorSettings) -> Value {
|
||||
json!({
|
||||
"rgb": st.rgb,
|
||||
"cmyk": st.cmyk,
|
||||
"intent": st.intent.id(),
|
||||
"bpc": st.bpc,
|
||||
"rgbPolicy": st.rgb_policy.id(),
|
||||
"cmykPolicy": st.cmyk_policy.id(),
|
||||
"profiles": cms::profiles().iter().map(|p| json!({"name": p.name, "kind": p.kind, "builtin": p.builtin})).collect::<Vec<_>>(),
|
||||
})
|
||||
}
|
||||
@@ -205,6 +219,12 @@ fn color_settings(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
st.intent = i;
|
||||
}
|
||||
st.bpc = switch_or(p, "bpc", st.bpc, C)?;
|
||||
if let Some(v) = policy_param(p, "rgbPolicy", &Policy::RGB, C)? {
|
||||
st.rgb_policy = v;
|
||||
}
|
||||
if let Some(v) = policy_param(p, "cmykPolicy", &Policy::CMYK, C)? {
|
||||
st.cmyk_policy = v;
|
||||
}
|
||||
if st != before {
|
||||
cms::set_active(&st).map_err(|e| bad(C, e.to_string()))?;
|
||||
// Saved for the next start when the app attached a settings file (#6335).
|
||||
@@ -530,7 +550,12 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode,
|
||||
if !convert {
|
||||
return 0;
|
||||
}
|
||||
let conv = mode_converter(mode, intent, grays);
|
||||
convert_colors(d, &mode_converter(mode, intent, grays))
|
||||
}
|
||||
|
||||
/// Every color of `d` that [`set_color_mode`] converts, converted with `conv` → how many colors of
|
||||
/// the art changed, as [`set_color_mode`] counts them.
|
||||
fn convert_colors(d: &mut vectorcraft_doc::Document, conv: &dyn Fn(&Color) -> Color) -> usize {
|
||||
for sw in d.swatches_iter_mut() {
|
||||
match &mut sw.paint {
|
||||
Paint::Solid { color, .. } => *color = conv(color),
|
||||
@@ -538,6 +563,11 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode,
|
||||
for st in &mut g.gradient.stops {
|
||||
st.color = conv(&st.color);
|
||||
}
|
||||
if let Some(freeform) = &mut g.freeform {
|
||||
for point in &mut freeform.points {
|
||||
point.color = conv(&point.color);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -621,6 +651,102 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode,
|
||||
in_art
|
||||
}
|
||||
|
||||
/// Apply the color management policies of Edit → Color Settings to `d`, a document being opened:
|
||||
/// each RGB or CMYK profile it is tagged with that is not the working space of its model is kept
|
||||
/// (Preserve Embedded Profiles), taken off with the color numbers kept (Off, Preserve Numbers), or
|
||||
/// taken off after the colors of that model were converted from it into the working space with the
|
||||
/// working intent (Convert to Working Space). A profile that is not available here is taken off
|
||||
/// by Off and Preserve Numbers and kept by Convert to Working Space, which has nothing to convert
|
||||
/// from. → a note for each profile, and whether `d` changed.
|
||||
pub(crate) fn apply_open_policies(d: &mut vectorcraft_doc::Document) -> (Vec<String>, bool) {
|
||||
let working = cms::working_settings();
|
||||
let (rgb, cmyk) = doc_profiles(d);
|
||||
let mut notes = Vec::new();
|
||||
// What each model's policy does with its profile: `None` keeps it; `Some` takes it off, after
|
||||
// converting the colors from the profile it holds.
|
||||
let mut decide = |label: &str, tag: Option<String>, working: &str, policy: Policy, kind: cms::ProfileKind| -> Option<Option<String>> {
|
||||
let tag = tag.filter(|t| t != working)?;
|
||||
let available = cms::profile(&tag).is_some_and(|p| p.kind == kind);
|
||||
match policy {
|
||||
Policy::PreserveEmbedded => None,
|
||||
Policy::Off | Policy::PreserveNumbers => {
|
||||
notes.push(format!(
|
||||
"the {label} profile “{tag}” the file is tagged with was not used: Color Settings' {label} policy is {}",
|
||||
policy.label()
|
||||
));
|
||||
Some(None)
|
||||
}
|
||||
Policy::Convert if available => {
|
||||
notes.push(format!(
|
||||
"the {label} colors were converted from the profile “{tag}” the file is tagged with into the working space “{working}”"
|
||||
));
|
||||
Some(Some(tag))
|
||||
}
|
||||
Policy::Convert => {
|
||||
notes.push(format!("the {label} profile “{tag}” the file is tagged with is not available, so its colors were not converted"));
|
||||
None
|
||||
}
|
||||
}
|
||||
};
|
||||
let rgb_do = decide("RGB", rgb, &working.rgb, working.rgb_policy, cms::ProfileKind::Rgb);
|
||||
let cmyk_do = decide("CMYK", cmyk, &working.cmyk, working.cmyk_policy, cms::ProfileKind::Cmyk);
|
||||
if rgb_do.is_none() && cmyk_do.is_none() {
|
||||
return (notes, false);
|
||||
}
|
||||
let (from_rgb, from_cmyk) = (rgb_do.clone().flatten(), cmyk_do.clone().flatten());
|
||||
if from_rgb.is_some() || from_cmyk.is_some() {
|
||||
let source = cms::for_document(from_rgb.as_deref(), from_cmyk.as_deref());
|
||||
let dest = cms::working();
|
||||
let intent = working.intent;
|
||||
let (rgb_on, cmyk_on) = (from_rgb.is_some(), from_cmyk.is_some());
|
||||
let conv = |c: &Color| match c {
|
||||
Color::Rgb { .. } if rgb_on => source.convert_into(&dest, c, intent),
|
||||
Color::Cmyk { .. } if cmyk_on => source.convert_into(&dest, c, intent),
|
||||
_ => *c,
|
||||
};
|
||||
convert_colors(d, &conv);
|
||||
convert_setting_colors(d, &conv);
|
||||
}
|
||||
if rgb_do.is_some() {
|
||||
d.color_profiles.rgb = None;
|
||||
}
|
||||
if cmyk_do.is_some() {
|
||||
d.color_profiles.cmyk = None;
|
||||
}
|
||||
(notes, true)
|
||||
}
|
||||
|
||||
/// The colors of `d` outside its art that [`convert_colors`] leaves, converted with `conv`: each
|
||||
/// artboard's background, the transparency grid and simulated paper colors of Document Setup, and
|
||||
/// the fill and stroke of the character and paragraph styles.
|
||||
fn convert_setting_colors(d: &mut vectorcraft_doc::Document, conv: &dyn Fn(&Color) -> Color) {
|
||||
for c in d.artboards.iter_mut().filter_map(|a| a.color.as_mut()) {
|
||||
*c = conv(c);
|
||||
}
|
||||
for c in &mut d.setup.grid_colors {
|
||||
*c = conv(c);
|
||||
}
|
||||
// A tint of a global swatch is the converted swatch's color at its tint, which
|
||||
// [`convert_colors`] already gave it.
|
||||
let bases = global_bases(d);
|
||||
let mut f = |c: &Color, link: proof::Link| mode_color(c, link, &bases, conv);
|
||||
for styles in [&mut d.char_styles, &mut d.para_styles] {
|
||||
if !styles.iter().any(|s| s.attrs.contains_key("fill") || s.attrs.contains_key("stroke")) {
|
||||
continue;
|
||||
}
|
||||
for def in styles.iter_mut() {
|
||||
for key in ["fill", "stroke"] {
|
||||
let Some(value) = def.attrs.get_mut(key) else { continue };
|
||||
let Ok(mut paint) = serde_json::from_value::<Paint>(value.clone()) else { continue };
|
||||
map_paint_colors(&mut paint, &mut f);
|
||||
if let Ok(v) = serde_json::to_value(&paint) {
|
||||
*value = v;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`proof::map_node_colors`] over `n`'s subtree, then [`map_more_colors`].
|
||||
fn map_art_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof::Link) -> Color) {
|
||||
proof::map_node_colors(n, f);
|
||||
|
||||
@@ -1,15 +1,18 @@
|
||||
//! Type › Composite Fonts…: the document's composite fonts ([`vectorcraft_doc::CompositeFont`]),
|
||||
//! which set each class of character (Kanji, Kana, Punctuation, Symbols, Roman, Numerals) in a
|
||||
//! font of its own. Type names a composite font as its family, and the font menus list them first.
|
||||
//! The font database holds the active document's composite fonts ([`sync`]); a file exported here
|
||||
//! carries them to another document.
|
||||
//! font of its own, and the characters of each custom character set in the set's font. Type names
|
||||
//! a composite font as its family, and the font menus list them first. The font database holds the
|
||||
//! active document's composite fonts ([`sync`]); a file exported here carries them to another
|
||||
//! document.
|
||||
//!
|
||||
//! Behavior reference (public documentation):
|
||||
//! <https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=347>.
|
||||
//! <https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=347>,
|
||||
//! custom character sets:
|
||||
//! <https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=348>.
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::text::{COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX};
|
||||
use vectorcraft_doc::{CharClass, CompositeFont, CompositePart, CompositeParts};
|
||||
use vectorcraft_doc::text::{COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, CUSTOM_CHARS_MAX, CUSTOM_SETS_MAX};
|
||||
use vectorcraft_doc::{CharClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet};
|
||||
use vectorcraft_text::FontDb;
|
||||
|
||||
use super::fileio::{read_file_head, write_file};
|
||||
@@ -26,6 +29,10 @@ const MAX_FILE_BYTES: usize = 4 << 20;
|
||||
/// The keys a part may give.
|
||||
const PART_KEYS: [&str; 7] = ["font", "style", "size", "baseline", "hScale", "vScale", "scaleAtCenter"];
|
||||
|
||||
/// The keys a custom character set may give: its name and characters, then its part's values
|
||||
/// (a set is never scaled at the center).
|
||||
const SET_KEYS: [&str; 8] = ["name", "characters", "font", "style", "size", "baseline", "hScale", "vScale"];
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
@@ -33,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Composite Fonts",
|
||||
[],
|
||||
None,
|
||||
"{} the active document's composite fonts → {fonts: [{name, parts: {kanji, kana, punctuation, symbols, roman, numerals: {font, style, size: % of the type size, baseline: % of the type size (positive raises), hScale: %, vScale: %, scaleAtCenter?: bool}}}]}",
|
||||
"{} the active document's composite fonts → {fonts: [{name, parts: {kanji, kana, punctuation, symbols, roman, numerals: {font, style, size: % of the type size, baseline: % of the type size (positive raises), hScale: %, vScale: %, scaleAtCenter?: bool}}, custom?: [{name, characters, font, style, size, baseline, hScale, vScale}]}]}",
|
||||
has_doc,
|
||||
list
|
||||
),
|
||||
@@ -42,7 +49,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Composite Fonts…",
|
||||
["Type"],
|
||||
None,
|
||||
"{fonts: [{name, parts: {kanji: {font, style?: \"Regular\", size?: % 10..400 = 100, baseline?: % -100..100 = 0}, kana?, punctuation?, symbols?, roman?, numerals?: {font, style?, size?, baseline?, hScale?, vScale?: % 10..400 = 100, scaleAtCenter?: bool = false}}}]} replace the active document's composite fonts (Type › Composite Fonts…'s OK), as one undo step, none when nothing changes. A composite font sets each class of character in its part's font: kanji (the base: ideographs, full-width letters and digits and anything no other class takes), kana (hiragana and katakana, both widths), punctuation (East Asian and full-width punctuation, quotes and dashes), symbols (arrows, math, shapes and other symbols), roman (half-width letters, their punctuation and spaces) and numerals (the digits 0 to 9); a part left out is the kanji part. size and baseline are percent of the type's size, hScale and vScale scale kana, roman and numerals only, and scaleAtCenter (kana only) scales them from the em box's center instead of the baseline. Names are trimmed, unique in any case, at most 255 characters, and may not name an installed font; a part's font may not be a composite font; at most 256. Type set in a composite font names it as its family (text.setStyle {font: name}), and the font menus list composite fonts first. A font taken out stays named by its type, which then shows as missing → {fonts}",
|
||||
"{fonts: [{name, parts: {kanji: {font, style?: \"Regular\", size?: % 10..400 = 100, baseline?: % -100..100 = 0}, kana?, punctuation?, symbols?, roman?, numerals?: {font, style?, size?, baseline?, hScale?, vScale?: % 10..400 = 100, scaleAtCenter?: bool = false}}, custom?: [{name, characters?: string = \"\", font?, style?, size?, baseline?, hScale?, vScale?}]}]} replace the active document's composite fonts (Type › Composite Fonts…'s OK), as one undo step, none when nothing changes. A composite font sets each class of character in its part's font: kanji (the base: ideographs, full-width letters and digits and anything no other class takes), kana (hiragana and katakana, both widths), punctuation (East Asian and full-width punctuation, quotes and dashes), symbols (arrows, math, shapes and other symbols), roman (half-width letters, their punctuation and spaces) and numerals (the digits 0 to 9); a part left out is the kanji part. size and baseline are percent of the type's size, hScale and vScale scale kana, roman and numerals only, and scaleAtCenter (kana only) scales them from the em box's center instead of the baseline. custom lists custom character sets: each sets the characters it lists in its own font, style, size, baseline and scales (values left out are the kanji part's), ahead of their class; a character two sets list is set by the later one. A set's name is trimmed and unique in the font in any case; its characters are each listed once, at most 8192, none a control character or past U+FFFF; at most 64 sets. Names are trimmed, unique in any case, at most 255 characters, and may not name an installed font; a part's font may not be a composite font; at most 256. Type set in a composite font names it as its family (text.setStyle {font: name}), and the font menus list composite fonts first. A font taken out stays named by its type, which then shows as missing → {fonts}",
|
||||
has_doc,
|
||||
set
|
||||
),
|
||||
@@ -51,7 +58,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Composite Fonts",
|
||||
[],
|
||||
None,
|
||||
"{path?: .vccomposite file, names?: [name] (default: all), fonts?: [{name, parts}] (as type.compositeFonts.set takes them)} write the active document's composite fonts (all, or those named, any case), or the fonts given, to a file type.compositeFonts.import reads; without path the file's text comes back as data → {path, count} | {data, count}",
|
||||
"{path?: .vccomposite file, names?: [name] (default: all), fonts?: [{name, parts}] (as type.compositeFonts.set takes them)} write the active document's composite fonts (all, or those named, any case), or the fonts given, to a file type.compositeFonts.import reads (a file over 4 MB is refused); without path the file's text comes back as data → {path, count} | {data, count}",
|
||||
has_doc,
|
||||
export
|
||||
),
|
||||
@@ -121,8 +128,8 @@ fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
/// copy of the Kanji part, and keys or values a part can't take refused.
|
||||
fn parse_font(v: &Value, c: &str) -> Result<CompositeFont> {
|
||||
let o = v.as_object().ok_or_else(|| bad(c, "each font must be {name, parts}"))?;
|
||||
if let Some(k) = o.keys().find(|k| !["name", "parts"].contains(&k.as_str())) {
|
||||
return Err(bad(c, format!("unknown key `{k}`; a font takes name and parts")));
|
||||
if let Some(k) = o.keys().find(|k| !["name", "parts", "custom"].contains(&k.as_str())) {
|
||||
return Err(bad(c, format!("unknown key `{k}`; a font takes name, parts and custom")));
|
||||
}
|
||||
let raw = o.get("name").and_then(Value::as_str).ok_or_else(|| bad(c, "each font needs a name"))?;
|
||||
let name = CompositeFont::clean_name(raw)
|
||||
@@ -140,7 +147,17 @@ fn parse_font(v: &Value, c: &str) -> Result<CompositeFont> {
|
||||
serde_json::from_value(p.clone()).map(Some).map_err(|e| bad(c, format!("`{name}`: {}: {e}", class.key())))
|
||||
};
|
||||
let kanji = part(CharClass::Kanji)?.ok_or_else(|| bad(c, format!("`{name}`: give the kanji part")))?;
|
||||
let mut f = CompositeFont { name: name.clone(), parts: CompositeParts::all(kanji) };
|
||||
let custom = match o.get("custom") {
|
||||
None => Vec::new(),
|
||||
Some(Value::Array(sets)) => {
|
||||
if sets.len() > CUSTOM_SETS_MAX {
|
||||
return Err(bad(c, format!("`{name}`: a composite font keeps at most {CUSTOM_SETS_MAX} character sets")));
|
||||
}
|
||||
sets.iter().map(|s| parse_set(s, &name, &kanji, c)).collect::<Result<Vec<_>>>()?
|
||||
}
|
||||
Some(_) => return Err(bad(c, format!("`{name}`: custom must be a list of character sets"))),
|
||||
};
|
||||
let mut f = CompositeFont { name: name.clone(), parts: CompositeParts::all(kanji), custom };
|
||||
for class in CharClass::ALL.into_iter().skip(1) {
|
||||
if let Some(p) = part(class)? {
|
||||
*f.parts.get_mut(class) = p;
|
||||
@@ -150,6 +167,38 @@ fn parse_font(v: &Value, c: &str) -> Result<CompositeFont> {
|
||||
Ok(f)
|
||||
}
|
||||
|
||||
/// Custom character set `v` of composite font `font` from command parameters or a file: its name
|
||||
/// trimmed, the part values it leaves out those of `kanji`, and keys or values it can't take
|
||||
/// refused. [`CompositeFont::check`] checks its characters and values.
|
||||
fn parse_set(v: &Value, font: &str, kanji: &CompositePart, c: &str) -> Result<CustomCharSet> {
|
||||
let o = v.as_object().ok_or_else(|| bad(c, format!("`{font}`: each character set must be {{name, characters, font…}}")))?;
|
||||
if let Some(k) = o.keys().find(|k| !SET_KEYS.contains(&k.as_str())) {
|
||||
return Err(bad(c, format!("`{font}`: unknown key `{k}` in a character set")));
|
||||
}
|
||||
let raw = o.get("name").and_then(Value::as_str).ok_or_else(|| bad(c, format!("`{font}`: each character set needs a name")))?;
|
||||
let name = CompositeFont::clean_name(raw)
|
||||
.ok_or_else(|| bad(c, format!("`{raw}` can't name a character set (1 to {COMPOSITE_NAME_MAX} characters, no control characters)")))?;
|
||||
let characters = match o.get("characters") {
|
||||
None => String::new(),
|
||||
Some(Value::String(s)) => s.clone(),
|
||||
Some(_) => return Err(bad(c, format!("`{font}`: `{name}`: characters must be a string"))),
|
||||
};
|
||||
// Checked here as well as by `check`, so a huge list is refused before it is copied again.
|
||||
if characters.chars().nth(CUSTOM_CHARS_MAX).is_some() {
|
||||
return Err(bad(c, format!("`{font}`: `{name}`: a character set keeps at most {CUSTOM_CHARS_MAX} characters")));
|
||||
}
|
||||
let mut part = serde_json::to_value(kanji).map_err(|e| bad(c, e.to_string()))?;
|
||||
if let Some(p) = part.as_object_mut() {
|
||||
for k in &SET_KEYS[2..] {
|
||||
if let Some(given) = o.get(*k) {
|
||||
p.insert(k.to_string(), given.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
let part: CompositePart = serde_json::from_value(part).map_err(|e| bad(c, format!("`{font}`: `{name}`: {e}")))?;
|
||||
Ok(CustomCharSet { name, characters, part })
|
||||
}
|
||||
|
||||
/// Error unless `fonts` can stand together in a document: names unique in any case, none naming
|
||||
/// an installed font, no part set in a composite font, and at most [`COMPOSITE_FONTS_MAX`].
|
||||
fn check_set(fonts: &[CompositeFont], c: &str) -> Result<()> {
|
||||
@@ -167,10 +216,10 @@ fn check_set(fonts: &[CompositeFont], c: &str) -> Result<()> {
|
||||
}
|
||||
}
|
||||
for f in fonts {
|
||||
for class in CharClass::ALL {
|
||||
let font = &f.parts.get(class).font;
|
||||
let classes = CharClass::ALL.into_iter().map(|class| (class.key(), &f.parts.get(class).font));
|
||||
for (part, font) in classes.chain(f.custom.iter().map(|s| (s.name.as_str(), &s.part.font))) {
|
||||
if names.contains(&font.to_lowercase()) || db.composite_font(font).is_some() {
|
||||
return Err(bad(c, format!("`{}`: {} is set in `{font}`, a composite font", f.name, class.key())));
|
||||
return Err(bad(c, format!("`{}`: {} is set in `{font}`, a composite font", f.name, part)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -260,6 +309,9 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut file = Map::new();
|
||||
file.insert("compositeFonts".into(), json!(fonts));
|
||||
let text = serde_json::to_string_pretty(&file).map_err(|e| bad(C, e.to_string()))?;
|
||||
if text.len() > MAX_FILE_BYTES {
|
||||
return Err(bad(C, "the composite fonts make a file larger than 4 MB, which Import can't read; export fewer of them"));
|
||||
}
|
||||
match path {
|
||||
Some(path) => {
|
||||
write_file(path, text.as_bytes())?;
|
||||
|
||||
@@ -856,3 +856,127 @@ fn composite_fonts_export_and_import() {
|
||||
assert!(s.execute("type.compositeFonts.export", &json!({"path": " "})).is_err());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// `font(name)` with two custom character sets: "Marks" (x and A) in Inter at 150%, and "A only"
|
||||
/// (A) in Source Sans 3, which sets A since it comes later.
|
||||
fn font_with_sets(name: &str) -> Value {
|
||||
let mut v = font(name);
|
||||
v["custom"] = json!([
|
||||
{"name": " Marks ", "characters": "xA", "font": "Inter", "size": 150, "hScale": 90},
|
||||
{"name": "A only", "characters": "A"},
|
||||
]);
|
||||
v
|
||||
}
|
||||
|
||||
/// Custom character sets are set with the font as one undo step, take values they leave out from
|
||||
/// the Kanji part, set the characters they list ahead of their class (the later set winning), are
|
||||
/// saved with the document, and measure type again when they change.
|
||||
#[test]
|
||||
fn custom_character_sets_set_their_characters() {
|
||||
let mut s = session();
|
||||
let before = steps(&s);
|
||||
let r = s.execute("type.compositeFonts.set", &json!({"fonts": [font_with_sets("CF Sets")]})).unwrap();
|
||||
assert_eq!(r["fonts"][0]["custom"][0]["name"], "Marks");
|
||||
assert_eq!(steps(&s), before + 1);
|
||||
let f = s.doc().unwrap().doc.composite_fonts[0].clone();
|
||||
assert_eq!(f.custom.len(), 2);
|
||||
assert_eq!((f.custom[0].part.font.as_str(), f.custom[0].part.size, f.custom[0].part.h_scale), ("Inter", 150.0, 90.0));
|
||||
assert_eq!((f.custom[1].part.font.as_str(), f.custom[1].part.size), ("Source Sans 3", 100.0));
|
||||
// The same sets again change nothing.
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [font_with_sets("CF Sets")]})).unwrap();
|
||||
assert_eq!(steps(&s), before + 1);
|
||||
let back = vectorcraft_format::load(&vectorcraft_format::save_file(&s.doc().unwrap().doc)).unwrap();
|
||||
assert_eq!(*back.composite_fonts, *s.doc().unwrap().doc.composite_fonts);
|
||||
|
||||
let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "xAB", "size": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("text.setStyle", &json!({"ids": [id], "font": "CF Sets"})).unwrap();
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
let face = |family: &str| db.face(family, "Regular").unwrap().id();
|
||||
let lay = vectorcraft_text::layout(db, &text(&s, id));
|
||||
let fonts: Vec<u32> = lay.glyphs.iter().map(|g| g.font_id).collect();
|
||||
assert_eq!(fonts, [face("Inter"), face("Source Sans 3"), face("JetBrains Mono")]);
|
||||
// Taking x out of Marks sets it in its class's font again, measured in the same step.
|
||||
let wide = text(&s, id).cached_bounds.unwrap().width();
|
||||
let mut fewer = font_with_sets("CF Sets");
|
||||
fewer["custom"][0]["characters"] = json!("A");
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [fewer]})).unwrap();
|
||||
assert!(text(&s, id).cached_bounds.unwrap().width() < wide - 1.0);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!((text(&s, id).cached_bounds.unwrap().width() - wide).abs() < 1e-6);
|
||||
}
|
||||
|
||||
/// Bad custom character sets are refused with an error and no undo step.
|
||||
#[test]
|
||||
fn bad_custom_character_sets_are_refused() {
|
||||
let mut s = session();
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [font_with_sets("CF Sets Base")]})).unwrap();
|
||||
let before = steps(&s);
|
||||
let with = |f: &dyn Fn(&mut Value)| {
|
||||
let mut v = font_with_sets("CF Sets Refused");
|
||||
f(&mut v);
|
||||
json!({"fonts": [v]})
|
||||
};
|
||||
let many: String = (0x4E00u32..).filter_map(char::from_u32).take(8193).collect();
|
||||
let sets: Vec<Value> = (0..65).map(|i| json!({"name": format!("S{i}")})).collect();
|
||||
for bad in [
|
||||
with(&|v| v["custom"] = json!("Marks")),
|
||||
with(&|v| v["custom"] = Value::Null),
|
||||
with(&|v| v["custom"][0]["characters"] = Value::Null),
|
||||
with(&|v| v["custom"][0] = json!("Marks")),
|
||||
with(&|v| v["custom"][0]["name"] = json!(" ")),
|
||||
with(&|v| {
|
||||
v["custom"][0].as_object_mut().unwrap().remove("name");
|
||||
}),
|
||||
with(&|v| v["custom"][1]["name"] = json!("marks")),
|
||||
with(&|v| v["custom"][0]["characters"] = json!(["※"])),
|
||||
with(&|v| v["custom"][0]["characters"] = json!("※※")),
|
||||
with(&|v| v["custom"][0]["characters"] = json!("A\n")),
|
||||
with(&|v| v["custom"][0]["characters"] = json!("😀")),
|
||||
with(&|v| v["custom"][0]["characters"] = json!(many.clone())),
|
||||
with(&|v| v["custom"] = json!(sets.clone())),
|
||||
with(&|v| v["custom"][0]["size"] = json!(5)),
|
||||
with(&|v| v["custom"][0]["size"] = json!("50")),
|
||||
with(&|v| v["custom"][0]["scaleAtCenter"] = json!(true)),
|
||||
with(&|v| v["custom"][0]["scaleAtCenter"] = json!(false)),
|
||||
with(&|v| v["custom"][0]["font"] = json!("")),
|
||||
with(&|v| v["custom"][0]["font"] = json!("CF Sets Base")),
|
||||
with(&|v| v["custom"][0]["width"] = json!(3)),
|
||||
] {
|
||||
let e = s.execute("type.compositeFonts.set", &bad);
|
||||
assert!(e.is_err(), "accepted {bad}");
|
||||
assert_eq!(names(&s), ["CF Sets Base"]);
|
||||
assert_eq!(steps(&s), before);
|
||||
}
|
||||
// A set without characters is kept: it sets nothing.
|
||||
let ok = with(&|v| v["custom"][0]["characters"] = json!(""));
|
||||
s.execute("type.compositeFonts.set", &ok).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.composite_fonts[0].custom[0].characters, "");
|
||||
}
|
||||
|
||||
/// Export writes the custom character sets and Import reads them back; a file whose set is bad is
|
||||
/// refused.
|
||||
#[test]
|
||||
fn custom_character_sets_export_and_import() {
|
||||
let mut s = session();
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [font_with_sets("CF Sets IO")]})).unwrap();
|
||||
let data = s.execute("type.compositeFonts.export", &json!({})).unwrap();
|
||||
let mut t = session();
|
||||
t.execute("type.compositeFonts.import", &json!({"data": data["data"]})).unwrap();
|
||||
assert_eq!(*t.doc().unwrap().doc.composite_fonts, *s.doc().unwrap().doc.composite_fonts);
|
||||
let text = data["data"].as_str().unwrap().replace("\"A only\"", "\"marks\"");
|
||||
let mut u = session();
|
||||
assert!(u.execute("type.compositeFonts.import", &json!({"data": text})).is_err());
|
||||
assert!(names(&u).is_empty());
|
||||
// Fonts whose file would be larger than Import reads are refused.
|
||||
let full: String = (0x4E00u32..).filter_map(char::from_u32).take(8192).collect();
|
||||
let sets: Vec<Value> = (0..64).map(|i| json!({"name": format!("S{i}"), "characters": full})).collect();
|
||||
let big: Vec<Value> = (0..3)
|
||||
.map(|i| {
|
||||
let mut f = font(&format!("CF Sets Big {i}"));
|
||||
f["custom"] = json!(sets);
|
||||
f
|
||||
})
|
||||
.collect();
|
||||
let e = s.execute("type.compositeFonts.export", &json!({"fonts": big})).unwrap_err();
|
||||
assert!(e.to_string().contains("4 MB"), "{e}");
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Flare",
|
||||
[],
|
||||
None,
|
||||
"{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg counter-clockwise from 3 o'clock: where the rings run from the centre), seed?} → {id}",
|
||||
"{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg counter-clockwise from 3 o'clock: where the rings run from the centre), seed?, ringSeed? (whole number below 2^53: places the rings along the path anew, keeping their count and sizes)} → {id}",
|
||||
has_doc,
|
||||
super::flare::flare
|
||||
),
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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")),
|
||||
|
||||
@@ -33,3 +33,4 @@ mod smooth;
|
||||
pub use commands::specs;
|
||||
pub(super) use common::{ids_json, replace_with_pieces, usize_opt};
|
||||
pub(super) use cut::{components, erase_outline};
|
||||
pub(super) use freehand::freehand_brushed;
|
||||
|
||||
@@ -92,7 +92,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Eraser",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1), size?: pt (10), sizeMode?: \"fixed\" (default) | \"pressure\" (Eraser Tool Options' Size set to Pressure: the tip is size − sizeVariation across where the pen presses lightest and size + sizeVariation where it presses hardest, as path.blob), sizeVariation?: pt (0), angle?: ° (0: the tip's long axis counter-clockwise from level), roundness?: % (100, kept within 1–100)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one",
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation ° clockwise, as path.freehand), size?: pt (10), angle?: ° (0: the tip's long axis counter-clockwise from level), roundness?: % (100, kept within 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0 or more, default 0)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An unknown mode, or a variation below 0 or past its range, is an error and erases nothing",
|
||||
has_doc,
|
||||
erase_region
|
||||
),
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
use super::common::{
|
||||
dist_to_polyline, fill_targets, ids_json, path_mut, path_of, points_param, poly_bounds, pressure_region, replace_with_pieces, samples_param,
|
||||
sibling_with, size_pressure, target_paths, usize_opt,
|
||||
PenRecord, Sample, dist_to_polyline, fill_targets, ids_json, path_mut, path_of, points_param, poly_bounds, pressure_region, replace_with_pieces,
|
||||
samples_param, sibling_with, size_pressure, target_paths, usize_opt,
|
||||
};
|
||||
use super::{
|
||||
Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, ParamCurve, PathData, Point, Result, Session, SubPath,
|
||||
Value, bad, eraser_area, eraser_tip, f64_or, fill_contains, json, number_or, object_param, po,
|
||||
Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, Paint, ParamCurve, PathData, Point, Result, Session,
|
||||
SubPath, Value, Vec2, bad, eraser_area, eraser_tip, f64_or, fill_contains, json, number_or, object_param, po,
|
||||
};
|
||||
use vectorcraft_brush::{Brush, BrushKind, Calligraphic, Variation};
|
||||
use vectorcraft_doc::StrokeLayer;
|
||||
use vectorcraft_tools::draw2::MIN_BRUSH_SIZE;
|
||||
|
||||
/// Split a filled path into connected pieces (each outer contour with its holes).
|
||||
pub(in super::super) fn components(pd: &PathData) -> Vec<PathData> {
|
||||
@@ -278,7 +281,11 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let angle = number_or(p, "angle", 0.0, C)?;
|
||||
let roundness = number_or(p, "roundness", 100.0, C)?;
|
||||
let pressure = size_pressure(p, &samples, C)?;
|
||||
let vary = eraser_variations(p, C)?;
|
||||
if varies_beyond_size_pressure(&vary) {
|
||||
return erase_varied(s, &samples, [angle, roundness, size], vary);
|
||||
}
|
||||
let pressure = if vary[2].0 == Variation::Pressure { size_pressure(p, &samples, C)? } else { None };
|
||||
let pts: Vec<Point> = samples.into_iter().map(|s| s.pt).collect();
|
||||
let r = size / 2.0;
|
||||
// The tip's short axis (its narrowest with Pressure): an open path is sampled at least every half of it.
|
||||
@@ -318,6 +325,101 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
apply_plan(s, "Eraser", plan)
|
||||
}
|
||||
|
||||
/// The variation modes `path.eraseRegion` takes for each of `angleMode`, `roundnessMode` and
|
||||
/// `sizeMode`.
|
||||
const ERASER_MODES: &str = "\"fixed\", \"random\", \"pressure\", \"tilt\", \"bearing\" or \"rotation\"";
|
||||
|
||||
/// Eraser Tool Options' Angle, Roundness and Size variations: for each of angle (`angleMode` with
|
||||
/// `angleVariation` in degrees, at most 180), roundness (`roundnessMode` with `roundnessVariation`
|
||||
/// in percent, at most 100) and size (`sizeMode` with `sizeVariation` in points), its mode and how
|
||||
/// far it varies either way. A mode left out or null is Fixed, and a variation left out or null
|
||||
/// is 0; any other mode, or a variation that is negative or past its most, is refused.
|
||||
fn eraser_variations(p: &Value, cmd: &str) -> Result<[(Variation, f64); 3]> {
|
||||
const KEYS: [(&str, &str, f64); 3] =
|
||||
[("angleMode", "angleVariation", 180.0), ("roundnessMode", "roundnessVariation", 100.0), ("sizeMode", "sizeVariation", f64::INFINITY)];
|
||||
let mut out = [(Variation::Fixed, 0.0); 3];
|
||||
for (slot, (mode_key, var_key, most)) in out.iter_mut().zip(KEYS) {
|
||||
let mode = match p.get(mode_key).filter(|v| !v.is_null()) {
|
||||
None => Variation::Fixed,
|
||||
Some(Value::String(id)) => Variation::parse(id).ok_or_else(|| bad(cmd, format!("{mode_key} is one of {ERASER_MODES}, not `{id}`")))?,
|
||||
Some(other) => return Err(bad(cmd, format!("{mode_key} is one of {ERASER_MODES}, not {other}"))),
|
||||
};
|
||||
let variation = number_or(p, var_key, 0.0, cmd)?;
|
||||
if !(variation.is_finite() && variation >= 0.0) {
|
||||
return Err(bad(cmd, format!("{var_key} must be 0 or more")));
|
||||
}
|
||||
if variation > most {
|
||||
return Err(bad(cmd, format!("{var_key} must be at most {most}")));
|
||||
}
|
||||
*slot = (mode, variation);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Does any of the Eraser's Angle, Roundness and Size vary with something other than Size on
|
||||
/// Pressure? A mode whose variation is 0 does not vary.
|
||||
fn varies_beyond_size_pressure(vary: &[(Variation, f64); 3]) -> bool {
|
||||
vary.iter().enumerate().any(|(i, (mode, v))| *v > 0.0 && *mode != Variation::Fixed && !(i == 2 && *mode == Variation::Pressure))
|
||||
}
|
||||
|
||||
/// `path.eraseRegion` with its tip varying along the drag ([`eraser_variations`]): the area the
|
||||
/// tip covers is swept as a Calligraphic brush nib of the same angle, roundness, size, modes and
|
||||
/// variations, with what the pen recorded along the drag. Random draws one value for the drag
|
||||
/// and the pen modes follow the pen at each point; a drag without that recording (a mouse) takes
|
||||
/// the value itself. `tip`: the angle, roundness and size.
|
||||
fn erase_varied(s: &mut Session, samples: &[Sample], tip: [f64; 3], vary: [(Variation, f64); 3]) -> Result<Value> {
|
||||
let [angle, roundness, size] = tip;
|
||||
let mut pts: Vec<Point> = samples.iter().map(|s| s.pt).collect();
|
||||
// A press without a drag is a dab: a sweep needs some length.
|
||||
if let [only] = pts[..] {
|
||||
pts.push(only + Vec2::new(0.01, 0.0));
|
||||
}
|
||||
// A nib's size is kept within 1296 pt and the stroke's width scales it: a larger tip is swept
|
||||
// at a fraction of its size on a stroke as many times wider.
|
||||
let [(am, av), (rm, rv), (sm, sv)] = vary;
|
||||
let sv = if sm == Variation::Fixed { 0.0 } else { sv };
|
||||
let scale = ((size + sv) / Calligraphic::RANGES[2].1).max(1.0);
|
||||
let nib = Calligraphic {
|
||||
angle,
|
||||
roundness: roundness.clamp(1.0, 100.0),
|
||||
size: size / scale,
|
||||
variation: [av, rv, sv / scale],
|
||||
modes: Some([am, rm, sm]),
|
||||
};
|
||||
let brush = Brush { name: "Eraser".into(), kind: BrushKind::Calligraphic(nib) };
|
||||
let mut stroke = StrokeLayer::new(Paint::None, scale);
|
||||
PenRecord::of_samples(samples).write(&mut stroke);
|
||||
let spine = SubPath::polyline(&pts, false);
|
||||
let st = s.doc()?;
|
||||
let pieces = vectorcraft_brush::stroke_pieces(&st.doc, &brush, &PathData::single(spine).to_bezpath(), &stroke);
|
||||
let areas: Vec<PathData> = pieces.iter().filter_map(|n| n.path_data().cloned()).collect();
|
||||
if areas.is_empty() {
|
||||
return Ok(json!({ "ids": [] }));
|
||||
}
|
||||
let region =
|
||||
po::try_unite_all(&areas.iter().map(|a| (a, FillRule::NonZero)).collect::<Vec<_>>()).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
let bp = region.to_bezpath();
|
||||
// The narrowest the tip gets across: an open path is sampled at least every half of it.
|
||||
let low = |i: usize| match vary[i] {
|
||||
(Variation::Fixed, _) => tip[i],
|
||||
(_, v) => tip[i] - v,
|
||||
};
|
||||
let short = low(2).max(MIN_BRUSH_SIZE) * low(1).clamp(1.0, 100.0) / 100.0;
|
||||
let reach = (size + sv) / 2.0;
|
||||
let mut plan: Vec<(NodeId, Vec<PathData>)> = vec![];
|
||||
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, reach))? {
|
||||
if pd.is_closed() {
|
||||
if po::area(&po::boolean(&pd, rule, ®ion, FillRule::NonZero, BoolOp::Intersect), FillRule::NonZero) <= 1e-6 {
|
||||
continue;
|
||||
}
|
||||
plan.push((id, components(&po::boolean(&pd, rule, ®ion, FillRule::NonZero, BoolOp::Difference))));
|
||||
} else if let Some(pieces) = erase_outline(&pd, short / 2.0, &|q| fill_contains(&bp, FillRule::NonZero, q)) {
|
||||
plan.push((id, pieces));
|
||||
}
|
||||
}
|
||||
apply_plan(s, "Eraser", plan)
|
||||
}
|
||||
|
||||
fn apply_plan(s: &mut Session, label: &str, plan: Vec<(NodeId, Vec<PathData>)>) -> Result<Value> {
|
||||
if plan.is_empty() {
|
||||
return Ok(json!({ "ids": [] }));
|
||||
|
||||
@@ -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() {
|
||||
@@ -157,6 +157,34 @@ fn redraw_section(pd: &PathData, pts: &[Point], tol: Option<f64>, within: f64) -
|
||||
}
|
||||
|
||||
pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
freehand_brushed(s, p, None)
|
||||
}
|
||||
|
||||
/// The object a brush on path `id` paints: the compound path a member path is in, else the path.
|
||||
fn brush_target(d: &Document, id: NodeId) -> NodeId {
|
||||
d.parent_of(id).filter(|p| d.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))).unwrap_or(id)
|
||||
}
|
||||
|
||||
/// Whether `ap` has a stroke a brush can paint: a stroke whose paint is not None.
|
||||
fn can_brush(ap: &Appearance) -> bool {
|
||||
ap.stroke().is_some_and(|st| !st.paint.is_none())
|
||||
}
|
||||
|
||||
fn no_stroke(name: &str) -> EngineError {
|
||||
bad("brush.freehand", format!("cannot apply brush `{name}`: path has no stroke"))
|
||||
}
|
||||
|
||||
/// Sets brush `name` on the stroke of object `id` of `d`.
|
||||
fn set_brush(d: &mut Document, id: NodeId, name: &str) {
|
||||
if let Some(st) = d.node_mut(id).and_then(|n| n.appearance.stroke_mut()) {
|
||||
st.brush = Some(name.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
/// `path.freehand`, with the stroke painted with brush `brush_name` (one `brush.freehand` has
|
||||
/// checked) in the same undo step as the path. A path without a stroke is an error before
|
||||
/// anything changes.
|
||||
pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&str>) -> Result<Value> {
|
||||
const C: &str = "path.freehand";
|
||||
let samples = samples_param(p, "points", C)?;
|
||||
if samples.iter().any(|q| !within_input_bound(q.pt)) {
|
||||
@@ -173,6 +201,8 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let fit_tol = switch_or(p, "fit", true, C)?.then_some(tol);
|
||||
let closed = switch_or(p, "closed", false, C)?;
|
||||
let brush = str_param(p, "style") == Some("brush");
|
||||
// The undo step's name: a stroke painted with a brush is a Paintbrush stroke, whatever its style.
|
||||
let label = if brush || brush_name.is_some() { "Paintbrush" } else { "Pencil" };
|
||||
let keep_selected = switch_or(p, "keepSelected", true, C)?;
|
||||
let filled = switch_or(p, "fill", false, C)?;
|
||||
if let Some(ext) = p.get("extend").filter(|v| !v.is_null()) {
|
||||
@@ -180,6 +210,12 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let at_start = str_param(ext, "end") == Some("start");
|
||||
let (pd, _) = path_of(&s.doc()?.doc, id)?;
|
||||
let si = pd.subpaths.iter().rposition(|s| !s.closed && !s.anchors.is_empty()).ok_or_else(|| bad(C, "path has no open end"))?;
|
||||
let target = brush_target(&s.doc()?.doc, id);
|
||||
if let Some(name) = brush_name
|
||||
&& !s.doc()?.doc.node(target).is_some_and(|n| can_brush(&n.appearance))
|
||||
{
|
||||
return Err(no_stroke(name));
|
||||
}
|
||||
let mut sp = pd.subpaths[si].clone();
|
||||
let old_len = subpath_len(&sp);
|
||||
if at_start {
|
||||
@@ -191,6 +227,15 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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.
|
||||
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, _| {
|
||||
set_brush(d, target, name);
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
return Ok(json!({ "id": id.0 }));
|
||||
}
|
||||
// A stroke that ends on an open end of another path connects the two: (that path, its last
|
||||
@@ -271,12 +316,12 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// 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
|
||||
@@ -290,7 +335,7 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let drawn = old.extended(old_len, &pen, drawn_len - old_len);
|
||||
if connect.is_some() { drawn.extended(drawn_len, &other, other_len) } else { drawn }
|
||||
});
|
||||
s.edit(if brush { "Paintbrush" } else { "Pencil" }, |d, sel| {
|
||||
s.edit(label, |d, sel| {
|
||||
let reverse = at_start && !sp.closed;
|
||||
if reverse {
|
||||
sp.reverse();
|
||||
@@ -326,6 +371,9 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
{
|
||||
if reverse { joined.reversed() } else { joined }.write(st);
|
||||
}
|
||||
if let Some(name) = brush_name {
|
||||
set_brush(d, target, name);
|
||||
}
|
||||
if keep_selected {
|
||||
sel.set([id]);
|
||||
} else {
|
||||
@@ -346,11 +394,19 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// were, measured along the old path; fit them to the new length if strokes drawn with a
|
||||
// pen get redrawn.
|
||||
if let Some((si, sp)) = redraw_section(&pd, &pts, fit_tol, within) {
|
||||
s.edit(if brush { "Paintbrush" } else { "Pencil" }, |d, sel| {
|
||||
// A member path of a compound path is redrawn in it: the compound path is what is
|
||||
// selected, and what a brush paints.
|
||||
let whole = brush_target(&s.doc()?.doc, id);
|
||||
if let Some(name) = brush_name
|
||||
&& !s.doc()?.doc.node(whole).is_some_and(|n| can_brush(&n.appearance))
|
||||
{
|
||||
return Err(no_stroke(name));
|
||||
}
|
||||
s.edit(label, |d, sel| {
|
||||
*path_mut(d, id)?.subpaths.get_mut(si).ok_or_else(|| bad(C, "no such subpath"))? = sp;
|
||||
// A member path of a compound path is redrawn in it: the compound path is what is
|
||||
// selected.
|
||||
let whole = d.parent_of(id).filter(|p| d.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))).unwrap_or(id);
|
||||
if let Some(name) = brush_name {
|
||||
set_brush(d, whole, name);
|
||||
}
|
||||
if keep_selected {
|
||||
sel.set([whole]);
|
||||
} else {
|
||||
@@ -373,7 +429,15 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(st) = look.appearance.stroke_mut() {
|
||||
pen.write(st);
|
||||
}
|
||||
let out = insert_look(s, if brush { "Paintbrush" } else { "Pencil" }, path_kind(PathData::single(sp)), look, None, keep_selected)?;
|
||||
if let Some(name) = brush_name {
|
||||
if !can_brush(&look.appearance) {
|
||||
return Err(no_stroke(name));
|
||||
}
|
||||
if let Some(st) = look.appearance.stroke_mut() {
|
||||
st.brush = Some(name.to_string());
|
||||
}
|
||||
}
|
||||
let out = insert_look(s, label, path_kind(PathData::single(sp)), look, None, keep_selected)?;
|
||||
if !keep_selected {
|
||||
// A new stroke with Keep selected off leaves nothing selected: Illustrator starts the stroke
|
||||
// by dropping the earlier selection, it does not keep it (#5752).
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -14,7 +14,8 @@ use vectorcraft_geom::{FillRule, PathData};
|
||||
use vectorcraft_render::effects;
|
||||
|
||||
use super::appearance::{
|
||||
ItemTarget, aligned, appearance_targets, design_reference, edit_targets, index_param, item_indices, item_target, item_target_at, with_reference,
|
||||
ItemTarget, aligned, appearance_targets, design_reference, edit_targets, index_param, item_indices, item_target, item_target_at, reference_of,
|
||||
with_reference,
|
||||
};
|
||||
use super::expand::has_seeded;
|
||||
use super::rasterfx;
|
||||
@@ -336,15 +337,6 @@ pub(crate) fn effect_targets(s: &Session, p: &Value, item: ItemTarget, index: us
|
||||
/// have.
|
||||
const APPENDED: usize = usize::MAX;
|
||||
|
||||
/// The [`design_reference`] of an effect edit aimed at `item`: none for the Appearance panel's active row, which is a
|
||||
/// row of the first selected object's stack.
|
||||
fn reference_of(s: &Session, p: &Value, item: ItemTarget, cmd: &str) -> Result<Option<NodeId>> {
|
||||
if matches!(item, ItemTarget::Item { explicit: false, .. }) {
|
||||
return Ok(None);
|
||||
}
|
||||
design_reference(s, p, cmd)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn edit_effects(
|
||||
s: &mut Session,
|
||||
|
||||
@@ -146,7 +146,11 @@ fn text(k: &str, v: &Value, multiline: bool) -> Result<String> {
|
||||
return Err(bad(C, format!("{k} is too long (at most {MAX_TEXT} characters)")));
|
||||
}
|
||||
if s.chars().any(|c| c.is_control() && !(multiline && matches!(c, '\n' | '\r' | '\t'))) {
|
||||
return Err(bad(C, format!("{k} has control characters{}", if multiline { "" } else { " or line breaks" })));
|
||||
return Err(if multiline {
|
||||
bad(C, format!("{k} has control characters"))
|
||||
} else {
|
||||
bad(C, format!("{k} has control characters or line breaks"))
|
||||
});
|
||||
}
|
||||
Ok(s.to_string())
|
||||
}
|
||||
|
||||
@@ -54,6 +54,7 @@ pub mod ppi;
|
||||
pub mod progress;
|
||||
mod psdlayers;
|
||||
pub mod psdread;
|
||||
mod psdslices;
|
||||
mod pxrread;
|
||||
mod save;
|
||||
mod screens;
|
||||
@@ -91,7 +92,11 @@ pub(crate) use mesh3d::{mesh_file_names, mesh_files};
|
||||
pub use naming::{NameParts as FileNameParts, parse_date as parse_file_date, render as render_file_name};
|
||||
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::{
|
||||
@@ -124,9 +129,10 @@ mod commands;
|
||||
mod export_names;
|
||||
mod formats;
|
||||
|
||||
pub(crate) use access::check_images_in;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) use access::list_dir;
|
||||
pub use access::{check_linked_scripts, write_file_with, write_save_file, write_save_file_with};
|
||||
pub use access::{check_linked_images, check_linked_scripts, write_file_with, write_save_file, write_save_file_with};
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod tests_readonly;
|
||||
@@ -238,6 +244,8 @@ mod tests_psd;
|
||||
mod tests_psdlayers;
|
||||
#[cfg(test)]
|
||||
mod tests_psdread;
|
||||
#[cfg(test)]
|
||||
mod tests_psdslices;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests_heifread;
|
||||
|
||||
@@ -139,6 +139,49 @@ pub fn check_linked_scripts(cmd: &str, format: &str, st: &crate::DocState) -> Re
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The error for an SVG that would name a linked image's file outside the read roots.
|
||||
pub(crate) const IMAGE_OUTSIDE: &str = "a linked image file is outside the read roots";
|
||||
|
||||
/// `cmd` may write `d`, the document an output of `st` writes (all of it, or the objects it
|
||||
/// exports), in format `format` (a format id) with options `p`: any format but SVG and SVGZ, and
|
||||
/// those too unless read roots are in force and the file would name a linked image's file outside
|
||||
/// them (a relative path taken from `st`'s folder; a URL is not checked). An `<image>` names the
|
||||
/// file with SVG Options › Images set to Link, and with Embed when the document holds no pixels for
|
||||
/// the image, for the images of the art each file draws (with chosen artboards, the art over each
|
||||
/// one; hidden layers and objects only with `hiddenLayers`, template layers and the opacity-mask
|
||||
/// and symbol editing layers never) and of the symbols, patterns and brushes that art uses; with
|
||||
/// Preserve Editing Capabilities, the native document the file carries names every linked file, the relative paths kept of them
|
||||
/// and each data set's image. The error names no file or folder.
|
||||
pub fn check_linked_images(cmd: &str, format: &str, st: &crate::DocState, d: &vectorcraft_doc::Document, p: &Value) -> Result<()> {
|
||||
check_images_in(cmd, format, d, crate::cmd::links::LinkBase::of(st), p)
|
||||
}
|
||||
|
||||
/// [`check_linked_images`] for `d`, a document whose links are looked for from `base` (the
|
||||
/// objects on the clipboard, looked for from the document they came from).
|
||||
pub(crate) fn check_images_in(cmd: &str, format: &str, d: &vectorcraft_doc::Document, base: crate::cmd::links::LinkBase, p: &Value) -> Result<()> {
|
||||
if !matches!(format, "svg" | "svgz") || crate::file_access::current().is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
// Options that don't read as the encoder's choices count as Link, Preserve Editing and hidden
|
||||
// layers kept: the encoder refuses them anyway.
|
||||
let (link, preserve, hidden) = match super::svg::options_map(p) {
|
||||
Ok(m) => {
|
||||
let on = |k: &str| m.get(k).is_some_and(|v| v.as_bool() != Some(false));
|
||||
(m.get("images").is_some_and(|v| v.as_str() != Some("embed")), on("preserveEditing"), on("hiddenLayers"))
|
||||
}
|
||||
Err(_) => (true, true, true),
|
||||
};
|
||||
// The opacity-mask and symbol editing layers are never written.
|
||||
let d = &*d.without_edit_modes();
|
||||
let names = |d: &vectorcraft_doc::Document| crate::cmd::links::svg_names_hidden_image(d, base, link, hidden);
|
||||
if preserve && crate::cmd::links::names_hidden_file(d, base)
|
||||
|| names(d) && super::svg::drawn(d, p).is_none_or(|files| files.iter().any(|f| names(f)))
|
||||
{
|
||||
return Err(bad(cmd, IMAGE_OUTSIDE));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `path` checked for writing against the automation roots in force.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn may_write(path: &str) -> Result<()> {
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -8,7 +8,7 @@ use std::sync::Arc;
|
||||
use serde::Deserialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde_json::Value;
|
||||
use vectorcraft_doc::{Artboard, Document, Node, NodeKind, SymbolOverride};
|
||||
use vectorcraft_doc::{Artboard, Document, Node, NodeKind, SYMBOL_SIZES, SymbolOverride};
|
||||
use vectorcraft_geom::Rect;
|
||||
use vectorcraft_render::AntiAlias;
|
||||
use vectorcraft_render::encode::jpeg::{self, JpegOptions};
|
||||
@@ -454,7 +454,12 @@ pub fn export_art_bounds(doc: &Document, format: &str) -> Option<Rect> {
|
||||
/// make the same appearance changes to its art are measured on a copy of the symbol of their own,
|
||||
/// in which each object is judged with those changes ([`as_drawn`]); the objects taken out of
|
||||
/// a dynamic symbol's art leave empty groups in their places, by which instances find the objects
|
||||
/// they change.
|
||||
/// they change. Each copy keeps its symbol's 9-slice guides and natural size. An instance whose art
|
||||
/// goes through 9-slice guides at any depth is measured as its art placed through them
|
||||
/// ([`placed_instances`]), with the objects `left_out` picks hidden after placing: the guides cut
|
||||
/// the box of the whole art. Where an instance stays one, the art of a symbol with 9-slice guides,
|
||||
/// and of the symbols whose instances are in that art at any depth ([`sliced_art`]), is measured
|
||||
/// whole.
|
||||
fn bounds_without(doc: &Document, left_out: &dyn Fn(&Node) -> bool) -> Option<Rect> {
|
||||
// The symbols instances show (the first of each name).
|
||||
let mut names = HashSet::new();
|
||||
@@ -492,12 +497,15 @@ fn bounds_without(doc: &Document, left_out: &dyn Fn(&Node) -> bool) -> Option<Re
|
||||
let Some(s) = d.symbols.get(*i).cloned() else { continue };
|
||||
for (k, c) in sets.get(s.name.as_str()).into_iter().flatten().flatten().enumerate() {
|
||||
copies.push((d.symbols.len(), c.as_slice()));
|
||||
d.symbols.push(vectorcraft_doc::Symbol { name: format!("{}\u{0}{k}", s.name), ..s.clone() });
|
||||
let name = format!("{}\u{0}{k}", s.name);
|
||||
copy_placement(&mut d, &s.name, &name);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { name, ..s.clone() });
|
||||
}
|
||||
}
|
||||
d
|
||||
});
|
||||
let src = remapped_doc.as_ref().unwrap_or(doc);
|
||||
let whole = sliced_art(src);
|
||||
// The symbols to measure with the changes their instances make (`None` for a static symbol),
|
||||
// without the dynamic symbols measured whole.
|
||||
let entries: Vec<(usize, Option<&[&SymbolOverride]>)> = shown
|
||||
@@ -517,11 +525,25 @@ fn bounds_without(doc: &Document, left_out: &dyn Fn(&Node) -> bool) -> Option<Re
|
||||
}
|
||||
let left_out =
|
||||
&|n: &Node| left_out(n) || matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if empty.contains(symbol.as_str()) && !has_effects(n));
|
||||
// The instances whose art goes through 9-slice guides, at any depth, are measured as their art
|
||||
// placed by those guides without the objects `left_out` picks, and without a clip group that
|
||||
// holds only such objects.
|
||||
let layers = hidden_nodes(&src.layers, left_out);
|
||||
let placing = holding(src, &whole);
|
||||
let layers = if placing.is_empty() {
|
||||
layers
|
||||
} else {
|
||||
let picked = &|n: &Node| {
|
||||
left_out(n) || matches!(n.kind, NodeKind::Group { clip: true, .. }) && all_left_out(n, left_out, &empty, None, &mut Vec::new())
|
||||
};
|
||||
let mut budget = 0;
|
||||
let from = layers.as_deref().unwrap_or(&src.layers);
|
||||
Some(from.iter().map(|l| placed_instances(src, l, &placing, picked, &mut budget, 0).unwrap_or_else(|| l.clone())).collect())
|
||||
};
|
||||
let symbols: Vec<(usize, Arc<Node>)> = entries
|
||||
.iter()
|
||||
.filter_map(|(i, c)| {
|
||||
let s = src.symbols.get(*i).filter(|s| !empty.contains(s.name.as_str()))?;
|
||||
let s = src.symbols.get(*i).filter(|s| !empty.contains(s.name.as_str()) && !whole.contains(s.name.as_str()))?;
|
||||
without_nodes(&s.art, left_out, *c, &mut Vec::new()).map(|art| (*i, art))
|
||||
})
|
||||
.collect();
|
||||
@@ -540,6 +562,135 @@ fn bounds_without(doc: &Document, left_out: &dyn Fn(&Node) -> bool) -> Option<Re
|
||||
vectorcraft_render::encode::art_bounds(&d)
|
||||
}
|
||||
|
||||
/// Give symbol `to` of `d` the 9-slice guides and the natural size that symbol `from` has.
|
||||
fn copy_placement(d: &mut Document, from: &str, to: &str) {
|
||||
if let Some(guides) = d.symbol_nine_slice(from) {
|
||||
d.set_symbol_nine_slice(to, Some(guides));
|
||||
}
|
||||
if let Some(size) = d.unknown.get(SYMBOL_SIZES).and_then(|m| m.get(from)).cloned()
|
||||
&& let Some(sizes) = d.unknown.get_mut(SYMBOL_SIZES).and_then(Value::as_object_mut)
|
||||
{
|
||||
sizes.insert(to.to_string(), size);
|
||||
}
|
||||
}
|
||||
|
||||
/// The names of the symbols of `doc` with 9-slice guides, and of the symbols whose instances are in
|
||||
/// the art of those at any depth.
|
||||
fn sliced_art(doc: &Document) -> HashSet<&str> {
|
||||
let mut arts: HashMap<&str, &Arc<Node>> = HashMap::new();
|
||||
for s in &doc.symbols {
|
||||
arts.entry(s.name.as_str()).or_insert(&s.art);
|
||||
}
|
||||
let mut todo: Vec<&str> = arts.keys().copied().filter(|name| doc.symbol_nine_slice(name).is_some()).collect();
|
||||
let mut found = HashSet::new();
|
||||
while let Some(name) = todo.pop() {
|
||||
if !found.insert(name) {
|
||||
continue;
|
||||
}
|
||||
if let Some(&art) = arts.get(name) {
|
||||
art.walk(&mut |n| {
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind {
|
||||
todo.push(symbol.as_str());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// The names of the symbols of `doc` in `sliced`, and of the symbols whose art holds an instance of
|
||||
/// one of those at any depth.
|
||||
fn holding<'a>(doc: &'a Document, sliced: &HashSet<&'a str>) -> HashSet<&'a str> {
|
||||
let mut held_by: HashMap<&str, Vec<&str>> = HashMap::new();
|
||||
let mut seen = HashSet::new();
|
||||
for s in doc.symbols.iter().filter(|s| seen.insert(s.name.as_str())) {
|
||||
s.art.walk(&mut |n| {
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind {
|
||||
held_by.entry(symbol.as_str()).or_default().push(s.name.as_str());
|
||||
}
|
||||
});
|
||||
}
|
||||
let mut found = HashSet::new();
|
||||
let mut todo: Vec<&str> = sliced.iter().copied().collect();
|
||||
while let Some(name) = todo.pop() {
|
||||
if found.insert(name) {
|
||||
todo.extend(held_by.get(name).into_iter().flatten().copied());
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// The most instances deep [`placed_instances`] places symbol art.
|
||||
const MAX_PLACED_DEPTH: usize = 32;
|
||||
|
||||
/// `n` with each instance of the `placing` symbols in it, and in its layers and groups at any depth,
|
||||
/// made a group with the instance's appearance that holds the instance's art (with its changes and
|
||||
/// stain) as `doc` places it, through the symbol's 9-slice guides when it has them, without the
|
||||
/// objects `picked` picks ([`without_nodes`]; hidden when it picks the whole art); `None` when `n`
|
||||
/// holds no such instance, or is hidden. An instance on a perspective grid, one
|
||||
/// [`MAX_PLACED_DEPTH`] instances deep, one in another kind of object (a blend, for example), and
|
||||
/// one whose art would take the objects placed in all (`budget`) past
|
||||
/// [`vectorcraft_doc::MAX_SYMBOL_NODES`] stay instances.
|
||||
/// Their symbols' art is measured whole, as taking objects out of it would change the box the
|
||||
/// guides cut, and the page can come out larger than the plot.
|
||||
fn placed_instances(
|
||||
doc: &Document,
|
||||
n: &Arc<Node>,
|
||||
placing: &HashSet<&str>,
|
||||
picked: &dyn Fn(&Node) -> bool,
|
||||
budget: &mut u64,
|
||||
depth: usize,
|
||||
) -> Option<Arc<Node>> {
|
||||
// Hidden art is not plotted, and placing it would take from the budget of the art that is.
|
||||
if !n.visible {
|
||||
return None;
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::SymbolInstance { symbol, xf } => {
|
||||
if !placing.contains(symbol.as_str()) || depth >= MAX_PLACED_DEPTH || n.projection().is_some() {
|
||||
return None;
|
||||
}
|
||||
let sym = doc.symbols.iter().find(|s| s.name == *symbol)?;
|
||||
let art = vectorcraft_doc::symbol_overrides::instance_art(&sym.art, n);
|
||||
let most = doc.symbol_slice_map(symbol, *xf).map_or(art.count_with_masks() as u64, |m| m.most_placed(&art, doc));
|
||||
if budget.saturating_add(most) > vectorcraft_doc::MAX_SYMBOL_NODES {
|
||||
return None;
|
||||
}
|
||||
let art = Arc::new(doc.place_symbol_art(symbol, &art, *xf)?);
|
||||
*budget = budget.saturating_add(art.count_with_masks() as u64);
|
||||
let art = placed_instances(doc, &art, placing, picked, budget, depth + 1).unwrap_or(art);
|
||||
let art = if picked(&art) {
|
||||
let mut hidden = (*art).clone();
|
||||
hidden.visible = false;
|
||||
Arc::new(hidden)
|
||||
} else {
|
||||
without_nodes(&art, picked, None, &mut Vec::new()).unwrap_or(art)
|
||||
};
|
||||
let mut g = (**n).clone();
|
||||
g.kind = NodeKind::Group { children: vec![art], clip: false };
|
||||
Some(Arc::new(g))
|
||||
}
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => {
|
||||
let mut out: Option<Vec<Arc<Node>>> = None;
|
||||
for (i, c) in children.iter().enumerate() {
|
||||
if let Some(new) = placed_instances(doc, c, placing, picked, budget, depth)
|
||||
&& let Some(slot) = out.get_or_insert_with(|| children.clone()).get_mut(i)
|
||||
{
|
||||
*slot = new;
|
||||
}
|
||||
}
|
||||
out.map(|c| {
|
||||
let mut m = (**n).clone();
|
||||
if let Some(children) = m.children_mut() {
|
||||
*children = c;
|
||||
}
|
||||
Arc::new(m)
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The appearance changes instance `n` makes to its symbol's art, without those that change nothing.
|
||||
fn own_changes(n: &Node) -> Vec<&SymbolOverride> {
|
||||
n.extras().symbol_overrides.iter().filter(|o| !o.is_empty()).collect()
|
||||
@@ -600,9 +751,10 @@ fn all_left_out(n: &Node, left_out: &dyn Fn(&Node) -> bool, empty: &HashSet<&str
|
||||
|
||||
/// Add the sets of appearance changes that the instances in `n` and its subtree make to the art of
|
||||
/// the symbols `sets` names, each set once, and those of the instances in the art of the symbols the
|
||||
/// instances show (`walked`, the symbols already looked in). The instances that `left_out` picks or
|
||||
/// that are in an object it picks are left out, and with `hidden` (in a layer) the hidden ones and
|
||||
/// those in a hidden object. A symbol with more than [`MAX_ART_COPIES`] sets gets `None`.
|
||||
/// instances show (`walked`, the symbols already looked in). With `hidden` (in a layer), the
|
||||
/// instances that are hidden or that `left_out` picks, and those in such an object, are left out.
|
||||
/// In symbol art every instance counts, since an instance of the symbol can change the objects
|
||||
/// that hold it. A symbol with more than [`MAX_ART_COPIES`] sets gets `None`.
|
||||
fn drawn_changes<'a>(
|
||||
doc: &'a Document,
|
||||
n: &'a Node,
|
||||
@@ -611,7 +763,7 @@ fn drawn_changes<'a>(
|
||||
walked: &mut HashSet<&'a str>,
|
||||
sets: &mut HashMap<&'a str, Option<Vec<Vec<&'a SymbolOverride>>>>,
|
||||
) {
|
||||
if hidden && !n.visible || left_out(n) {
|
||||
if hidden && (!n.visible || left_out(n)) {
|
||||
return;
|
||||
}
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind {
|
||||
|
||||
@@ -12,8 +12,8 @@ use crate::DocState;
|
||||
use super::super::{Result, Session, bad, check_switches, edit, number_or, switch_or, text_param};
|
||||
use super::encode::single_artboard;
|
||||
use super::{
|
||||
ARTBOARD_PARAMS, Format, check_linked_scripts, default_name, encode_all, encode_with_warnings, merge, with_black_output, writable, write_encoded,
|
||||
write_or_return,
|
||||
ARTBOARD_PARAMS, Format, check_images_in, check_linked_scripts, default_name, encode_all, encode_with_warnings, merge, with_black_output,
|
||||
writable, write_encoded, write_or_return,
|
||||
};
|
||||
|
||||
/// The keys the export commands take for every format, beside the path, the format and the
|
||||
@@ -287,6 +287,8 @@ fn source<'a>(s: &'a mut Session, f: &Format, p: &Value, cmd: &str) -> Result<(C
|
||||
}
|
||||
let st = s.doc()?;
|
||||
let doc = export_doc(st, f, p)?;
|
||||
// The objects written (all, or with selectedOnly the selected ones) are checked.
|
||||
check_images_in(cmd, f.id, &doc, crate::cmd::links::LinkBase::of(st), p)?;
|
||||
let display_doc_title = super::has_own_title(&doc);
|
||||
Ok((super::titled_for_export(&doc, st.path.as_deref(), f.id).map_or(doc, Cow::Owned), display_doc_title))
|
||||
}
|
||||
@@ -372,6 +374,8 @@ pub(super) fn export_selection(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let expanded = expand_presets(s, C, p)?;
|
||||
let p = with_black_output(s, &expanded);
|
||||
let (d, bounds) = selection(s, C, f.id == "txt")?;
|
||||
// The selected objects' links are looked for from the document they are in.
|
||||
check_images_in(C, f.id, &d, crate::cmd::links::LinkBase::of(s.doc()?), &without_artboards(&p))?;
|
||||
// The encoder's warnings (options accepted but not applied, features approximated or left
|
||||
// out), as document.export reports them.
|
||||
let (bytes, mut warnings) = encode_with_warnings(&d, f.id, &without_artboards(&p))?;
|
||||
|
||||
@@ -393,8 +393,10 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
return Err(err(format!("can't open `{}`: {}", file_name(name), crate::cmd::place::dcs::LINK_ONLY)));
|
||||
}
|
||||
let editing = vectorcraft_eps::has_native(bytes).then_some((true, || vectorcraft_eps::native(bytes)));
|
||||
// A `.ai` keeps the artboard its header gives; an EPS comes in on its page.
|
||||
let import = if matches!(format.id, "ai" | "ait") { vectorcraft_eps::import_ai } else { vectorcraft_eps::import_names };
|
||||
restore_or_import(editing, || {
|
||||
let r = vectorcraft_eps::import_names(bytes, opts.editing_data, opts.trust_editing_data, opts.legacy_names)
|
||||
let r = import(bytes, opts.editing_data, opts.trust_editing_data, opts.legacy_names)
|
||||
.map_err(|e| err(format!("can't open `{}`: {e}", file_name(name))))?;
|
||||
Ok((r.document, r.warnings))
|
||||
})?
|
||||
@@ -526,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")
|
||||
@@ -658,6 +669,17 @@ pub struct ReadFile {
|
||||
path: Option<String>,
|
||||
/// What became of its linked files.
|
||||
links: Resolved,
|
||||
/// Whether the color management policies changed the document ([`apply_policies`]).
|
||||
policy_changed: bool,
|
||||
}
|
||||
|
||||
/// Edit › Color Settings: the color management policies keep, take off or convert from the
|
||||
/// profiles the document `loaded` holds is tagged with, and their notes go to its warnings →
|
||||
/// whether they changed the document.
|
||||
fn apply_policies(loaded: &mut Loaded) -> bool {
|
||||
let (notes, changed) = crate::cmd::colormgmt::apply_open_policies(&mut loaded.doc);
|
||||
loaded.warnings.extend(notes);
|
||||
changed
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -678,17 +700,35 @@ impl ReadFile {
|
||||
/// ([`super::importer`]).
|
||||
pub fn read_for_open(name: &str, bytes: &[u8], path: Option<String>, p: &Value, update_links: bool, low_res_proxy_eps: bool) -> Result<ReadFile> {
|
||||
let opts = LoadOptions::from_params("document.open", p)?;
|
||||
let mut loaded = if opts.link_pages {
|
||||
linked_pages(name, bytes, path.as_deref(), &opts)?
|
||||
let (mut loaded, policy_changed) = if opts.link_pages {
|
||||
let mut loaded = linked_pages(name, bytes, path.as_deref(), &opts)?;
|
||||
let changed = apply_policies(&mut loaded);
|
||||
(loaded, changed)
|
||||
} else {
|
||||
match super::importer::pick(name, bytes, p)? {
|
||||
Some(plugin) => super::importer::load(name, bytes, &plugin, p)?,
|
||||
None => load_with(name, bytes, &opts)?,
|
||||
Some(plugin) => {
|
||||
let mut loaded = super::importer::load(name, bytes, &plugin, p)?;
|
||||
let changed = apply_policies(&mut loaded);
|
||||
(loaded, changed)
|
||||
}
|
||||
None => {
|
||||
// The color mode `p` asks for converts the colors after the policies did, through
|
||||
// the profiles the document keeps.
|
||||
let mut loaded = load_with(name, bytes, &LoadOptions { color_mode: None, ..opts.clone() })?;
|
||||
let changed = apply_policies(&mut loaded);
|
||||
if let Some(mode) = opts.color_mode.filter(|m| *m != loaded.doc.color_mode) {
|
||||
let doc = &mut loaded.doc;
|
||||
vectorcraft_color::cms::with_active(super::super::colormgmt::doc_cms(doc), || {
|
||||
super::super::colormgmt::set_color_mode(doc, mode, true, None, opts.grays);
|
||||
});
|
||||
}
|
||||
(loaded, changed)
|
||||
}
|
||||
}
|
||||
};
|
||||
let links = crate::cmd::links::resolve(&mut loaded.doc, crate::cmd::links::LinkBase::file(path.as_deref()), update_links, low_res_proxy_eps);
|
||||
Session::refresh_text_bounds(&mut loaded.doc);
|
||||
Ok(ReadFile { loaded, opts, path, links })
|
||||
Ok(ReadFile { loaded, opts, path, links, policy_changed })
|
||||
}
|
||||
|
||||
/// The PDF `name` (`bytes`, read from `path`) opened with `linkPages`: its pages as placed documents
|
||||
@@ -703,7 +743,7 @@ fn linked_pages(name: &str, bytes: &[u8], path: Option<&str>, opts: &LoadOptions
|
||||
/// The second half of [`open_bytes_with`]: open a file [`read_for_open`] read as the new active
|
||||
/// document → `document.open`'s result.
|
||||
pub fn open_read(s: &mut Session, file: ReadFile) -> Result<Value> {
|
||||
open_loaded(s, file.loaded, file.links, file.path, &file.opts, false)
|
||||
open_loaded(s, file.loaded, file.links, file.path, &file.opts, false, file.policy_changed)
|
||||
}
|
||||
|
||||
/// File → New from Template: any readable file (at `path`, if it is one: its links are looked for
|
||||
@@ -715,14 +755,24 @@ pub fn open_template(s: &mut Session, name: &str, bytes: &[u8], path: Option<&st
|
||||
"only this Affinity file's embedded preview could be read: use File › Open to see it with its warning, or export SVG or PDF from Affinity first",
|
||||
));
|
||||
}
|
||||
let policy_changed = apply_policies(&mut loaded);
|
||||
let base = crate::cmd::links::LinkBase::file(path);
|
||||
let links = crate::cmd::links::resolve(&mut loaded.doc, base, s.prefs.update_links == "automatically", s.prefs.low_res_proxy_eps);
|
||||
open_loaded(s, loaded, links, path.map(str::to_string), &LoadOptions::default(), true)
|
||||
open_loaded(s, loaded, links, path.map(str::to_string), &LoadOptions::default(), true, policy_changed)
|
||||
}
|
||||
|
||||
/// Make a loaded file the new active document; `links` is what became of its linked files, and
|
||||
/// `opts` are the options it was read with.
|
||||
fn open_loaded(s: &mut Session, loaded: Loaded, links: Resolved, path: Option<String>, opts: &LoadOptions, as_template: bool) -> Result<Value> {
|
||||
/// Make a loaded file the new active document; `links` is what became of its linked files, `opts`
|
||||
/// are the options it was read with, and `policy_changed` says whether the color management
|
||||
/// policies changed it (it then opens with unsaved changes).
|
||||
fn open_loaded(
|
||||
s: &mut Session,
|
||||
loaded: Loaded,
|
||||
links: Resolved,
|
||||
path: Option<String>,
|
||||
opts: &LoadOptions,
|
||||
as_template: bool,
|
||||
policy_changed: bool,
|
||||
) -> Result<Value> {
|
||||
let Loaded { mut doc, format, warnings, restored, converted, native_pdf_compatible, .. } =
|
||||
loaded.with_grid_prefs(&s.prefs).with_unit_prefs(&s.prefs);
|
||||
// EPS now has an ordinary Save path. Its preview, partial-program and damaged-editing
|
||||
@@ -763,6 +813,9 @@ fn open_loaded(s: &mut Session, loaded: Loaded, links: Resolved, path: Option<St
|
||||
let converted = saves_back && converted && s.prefs.append_converted;
|
||||
let index = s.add_document(doc, path);
|
||||
let st = s.doc_mut()?;
|
||||
if policy_changed {
|
||||
st.mark_unsaved();
|
||||
}
|
||||
if let Some(pdf) = native_pdf_compatible {
|
||||
st.save_options.insert("pdfCompatible".into(), json!(pdf));
|
||||
}
|
||||
|
||||
@@ -236,15 +236,13 @@ pub(super) fn encode_to(cmd: &str, f: &Format, doc: &Document, p: &Value, w: imp
|
||||
}
|
||||
|
||||
/// `doc` with its path geometry rounded to `decimals` places, as [`vectorcraft_format::save_to`]
|
||||
/// writes it for `version`: placed documents become groups of their art for older versions.
|
||||
/// writes it for `version`: placed documents, those in the stored brushes' art included, become
|
||||
/// groups of their art for older versions.
|
||||
fn rounded(doc: &Document, version: u32, decimals: u8) -> Document {
|
||||
let mut d = if version < vectorcraft_format::VERSION && doc.has_placed() {
|
||||
let mut d = doc.with_placed_art().into_owned();
|
||||
d.placed_as_groups();
|
||||
d
|
||||
} else {
|
||||
doc.clone()
|
||||
};
|
||||
let mut d = doc.clone();
|
||||
if version < vectorcraft_format::VERSION {
|
||||
vectorcraft_format::placed_as_groups(&mut d);
|
||||
}
|
||||
d.round_geometry(decimals.min(vectorcraft_format::MAX_PRECISION));
|
||||
d
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -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,
|
||||
@@ -205,7 +213,7 @@ pub fn page_document(bytes: &[u8], page: usize, o: &LoadOptions) -> Result<(Docu
|
||||
}
|
||||
|
||||
/// [`page_document`] of `opened`, the PDF `bytes` already read.
|
||||
fn opened_page_document(bytes: &[u8], opened: &vectorcraft_pdf::Opened, page: usize, o: &LoadOptions) -> Result<(Document, Vec<String>)> {
|
||||
pub(crate) fn opened_page_document(bytes: &[u8], opened: &vectorcraft_pdf::Opened, page: usize, o: &LoadOptions) -> Result<(Document, Vec<String>)> {
|
||||
vectorcraft_pdf::import_opened(bytes, opened, &page_options(page, o)).map(|r| (r.document, r.warnings)).map_err(err)
|
||||
}
|
||||
|
||||
@@ -217,8 +225,11 @@ fn page_options(page: usize, o: &LoadOptions) -> ImportOptions {
|
||||
/// `document.open` with `linkPages`: the pages `o` picks of the PDF (or PDF-compatible `.ai` or
|
||||
/// `.ait`) `name`, read from `path`, as a document holding one placed document per page, linked to
|
||||
/// that page of the file as File › Place with Link places one ([`document::source`]). Each page
|
||||
/// gets an artboard of its `o.crop` box (its art's bounds for `bounding`), in a row from the left
|
||||
/// with the gap a PDF's artboards open with, and a layer named after the page. The document opens
|
||||
/// gets an artboard of its `o.crop` box (its art's bounds for `bounding`, a blank page's crop box;
|
||||
/// a PDF-compatible `.ai` asked for its crop box gets its trim box, as it opens), in a row from the
|
||||
/// left with the gap a PDF's artboards open with, and a layer named after the page. On its trim box,
|
||||
/// a page shows its bleed box round the artboard, and the document's bleed is the pages' bleed (the
|
||||
/// widest on each side); the artboards are then the gap apart plus the bleed on both sides. The document opens
|
||||
/// in CMYK when most of the pages read in CMYK, unless `o.color_mode` names a mode. Refused without a
|
||||
/// path, for any other file, with a password (a linked page is read again without one), with
|
||||
/// `textAs: outlines` (a linked page shows the file's own type) and for a file over
|
||||
@@ -239,12 +250,16 @@ pub(super) fn linked_pages(name: &str, bytes: &[u8], path: Option<&str>, o: &Loa
|
||||
if bytes.len() > document::MAX_FILE {
|
||||
return Err(bad(C, format!("linkPages: `{file}` is over {} MB", document::MAX_FILE >> 20)));
|
||||
}
|
||||
let count = vectorcraft_pdf::open_pdf(bytes, None).map_err(err)?.page_count();
|
||||
// The file is read once: every page is read from it.
|
||||
let opened = vectorcraft_pdf::open_pdf(bytes, None).map_err(err)?;
|
||||
let count = opened.page_count();
|
||||
let picked = match &o.pages {
|
||||
None => (0..count).collect(),
|
||||
Some(range) => parse_range(range, count).map_err(|e| err(format!("pages: {e}")))?,
|
||||
};
|
||||
let bounding = o.crop == CropTo::Bounding;
|
||||
// A PDF-compatible `.ai` asked for its crop box opens on its trim boxes ([`LoadOptions::import_options`]).
|
||||
let crop = if o.crop == CropTo::Crop && opened.has_illustrator_data() { CropTo::Trim } else { o.crop };
|
||||
let mut doc = Document::new(1.0, 1.0);
|
||||
let board = doc.artboards.first().cloned().ok_or_else(|| err("a new document has no artboard"))?;
|
||||
doc.artboards.clear();
|
||||
@@ -253,14 +268,55 @@ pub(super) fn linked_pages(name: &str, bytes: &[u8], path: Option<&str>, o: &Loa
|
||||
let gap = ImportOptions::default().artboard_gap;
|
||||
// Every page's object keeps the same one copy of the file.
|
||||
let shared = Arc::new(bytes.to_vec());
|
||||
let (mut x, mut warnings, mut cmyk_pages) = (0.0, Vec::<String>::new(), 0);
|
||||
for (i, &index) in picked.iter().enumerate() {
|
||||
// The file is hashed once for all its pages.
|
||||
let hash = link.hash.clone().unwrap_or_else(|| vectorcraft_doc::links::hash_bytes(bytes));
|
||||
let (mut warnings, mut cmyk_pages) = (Vec::<String>::new(), 0);
|
||||
// Each page as read, with its bleed (top, bottom, left, right). The pages are laid out once
|
||||
// the document's bleed is known.
|
||||
let mut read_pages = Vec::with_capacity(picked.len());
|
||||
for &index in &picked {
|
||||
let page = index as u32 + 1;
|
||||
let s = document::shared_source(name, &shared, Some(path), page, bounding, document::page_box(o.crop), C)?;
|
||||
let file_once = document::SharedFile { bytes: &shared, hash: &hash, opened: &opened };
|
||||
// On its trim box, a page shows its bleed box, the artboard on the trim box inside it, so
|
||||
// the art in the bleed shows and prints as bleed.
|
||||
let bleed = if crop == CropTo::Trim { opened.page_bleed(index) } else { None };
|
||||
let page_box = if bleed.is_some() { vectorcraft_doc::PageBox::Bleed } else { document::page_box(crop) };
|
||||
let read = |bounding| document::shared_source(name, file_once, Some(path), page, bounding, page_box, C);
|
||||
// A blank page has no art's bounds: it keeps its crop box, as opening it as art does.
|
||||
let (mut s, bounding) = match read(bounding) {
|
||||
Err(e) if bounding && e.to_string().contains("has no art to place") => (read(false)?, false),
|
||||
s => (s?, bounding),
|
||||
};
|
||||
// A page that is only a placeholder (a `.ai` saved without PDF compatibility) shows the
|
||||
// file's editing data, not a page of the file.
|
||||
if s.editing_data {
|
||||
return Err(bad(C, format!("linkPages: `{file}` isn't a PDF or a PDF-compatible .ai file")));
|
||||
}
|
||||
cmyk_pages += usize::from(s.color_mode == ColorMode::Cmyk);
|
||||
// The document's bleed is the widest of the pages' on each side.
|
||||
let sides = bleed.unwrap_or_default();
|
||||
for (side, b) in doc.setup.bleed.iter_mut().zip(sides) {
|
||||
*side = side.max(b.min(vectorcraft_doc::setup::MAX_BLEED));
|
||||
}
|
||||
for w in std::mem::take(&mut s.warnings) {
|
||||
if !warnings.contains(&w) {
|
||||
warnings.push(w);
|
||||
}
|
||||
}
|
||||
read_pages.push((page, s, bounding, sides));
|
||||
}
|
||||
// Each artboard is the gap from the one before plus the bleed on both sides of it: the
|
||||
// document's bleed, which export adds round every artboard, or a page's own bleed box where it
|
||||
// reaches farther. Neither page then shows or exports the other's art.
|
||||
let [_, _, doc_left, doc_right] = doc.setup.bleed;
|
||||
let mut x = 0.0;
|
||||
for (i, (page, s, bounding, [top, bottom, left, right])) in read_pages.into_iter().enumerate() {
|
||||
if i > 0 {
|
||||
x += doc_left.max(left);
|
||||
}
|
||||
let mut node = document::node(&mut doc, &s, LinkInfo { page: Some(page), ..link.clone() }, bounding);
|
||||
if let NodeKind::PlacedDocument(p) = &mut node.kind {
|
||||
p.xf = Affine::translate((x, 0.0));
|
||||
p.xf = Affine::translate((x - left, -top));
|
||||
}
|
||||
node.name = Some(file.clone());
|
||||
let mut layer = Node::layer(doc.alloc_id(), &format!("Page {page}"), LayerColor::Preset((i % 27) as u8));
|
||||
@@ -268,14 +324,9 @@ pub(super) fn linked_pages(name: &str, bytes: &[u8], path: Option<&str>, o: &Loa
|
||||
children.push(Arc::new(node));
|
||||
}
|
||||
doc.layers.push(Arc::new(layer));
|
||||
let rect = Rect::new(x, 0.0, x + s.frame.width(), s.frame.height());
|
||||
let rect = Rect::new(x, 0.0, x + s.frame.width() - left - right, s.frame.height() - top - bottom);
|
||||
doc.artboards.push(Artboard { id: i as u32 + 1, name: format!("Artboard {}", i + 1), rect, ..board.clone() });
|
||||
x = rect.x1 + gap;
|
||||
for w in s.warnings {
|
||||
if !warnings.contains(&w) {
|
||||
warnings.push(w);
|
||||
}
|
||||
}
|
||||
x = rect.x1 + doc_right.max(right) + gap;
|
||||
}
|
||||
// Pages painted mostly in CMYK read as CMYK documents, as opening them as art does: the
|
||||
// document opens in CMYK (with the CMYK default swatches) when most of its pages do.
|
||||
|
||||
@@ -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,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -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,7 +172,7 @@ 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() {
|
||||
|
||||
@@ -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, resources};
|
||||
|
||||
/// 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 are cut short). An error when the file isn't a PSD or PSB
|
||||
/// file, 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)) = resources(h.resources, true).find(|(id, _, _)| *id == 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('&', "&").replace('<', "<").replace('>', ">") }
|
||||
}
|
||||
|
||||
/// 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,
|
||||
}
|
||||
}
|
||||
@@ -891,6 +891,13 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option<i
|
||||
let cmd = plan.mode.command();
|
||||
super::check_linked_scripts(cmd, plan.format.id, st)?;
|
||||
let mut own = doc_to_save(st, plan.format);
|
||||
let mut params = plan.options.clone();
|
||||
if is_svg(plan.format) {
|
||||
// A save keeps hidden layers (not displayed) unless told otherwise; exports leave them out.
|
||||
params.entry("hiddenLayers").or_insert(Value::Bool(true));
|
||||
}
|
||||
let params = Value::Object(params);
|
||||
super::check_linked_images(cmd, plan.format.id, st, &own, ¶ms)?;
|
||||
// The file the document is saved as (else its own) titles it if New's name is all it has.
|
||||
let file = plan.path.as_deref().filter(|_| plan.retargets()).or(st.path.as_deref());
|
||||
if let Some(d) = super::titled_for_export(&own, file, plan.format.id) {
|
||||
@@ -905,12 +912,7 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option<i
|
||||
let base = crate::cmd::links::LinkBase::of(st);
|
||||
let relative = plan.path.as_deref().filter(|_| is_native(plan.format)).and_then(|p| crate::cmd::links::with_relative_paths(&own, base, p));
|
||||
let doc = relative.map_or(own, Arc::new);
|
||||
let mut params = plan.options.clone();
|
||||
if is_svg(plan.format) {
|
||||
// A save keeps hidden layers (not displayed) unless told otherwise; exports leave them out.
|
||||
params.entry("hiddenLayers").or_insert(Value::Bool(true));
|
||||
}
|
||||
let mut params = Value::Object(params);
|
||||
let mut params = params;
|
||||
if matches!(plan.format.id, "vectorcraft" | "template") {
|
||||
// Not remembered with the options: the preference decides each time it isn't given.
|
||||
params = with_compression_pref(&s.prefs, ¶ms);
|
||||
@@ -1237,14 +1239,23 @@ fn revert(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let bytes = read_file(&path).map_err(|e| super::access::naming_in_error(e, &path))?;
|
||||
let Loaded { mut doc, native_pdf_compatible, .. } = load(&path, &bytes)?.with_grid_prefs(&s.prefs).with_unit_prefs(&s.prefs);
|
||||
doc.template = false;
|
||||
// The color management policies apply as when the file is opened.
|
||||
let (notes, policy_changed) = crate::cmd::colormgmt::apply_open_policies(&mut doc);
|
||||
// Back to the saved file: its recovery copy has nothing left to recover.
|
||||
let uid = s.doc()?.uid;
|
||||
crate::cmd::recovery::forget(s, uid);
|
||||
s.replace_document(index, doc);
|
||||
if policy_changed {
|
||||
s.doc_mut()?.mark_unsaved();
|
||||
}
|
||||
if let Some(pdf) = native_pdf_compatible {
|
||||
s.doc_mut()?.save_options.insert("pdfCompatible".into(), json!(pdf));
|
||||
}
|
||||
Ok(json!({ "path": path }))
|
||||
let mut reply = json!({ "path": path });
|
||||
if !notes.is_empty() {
|
||||
reply["warnings"] = json!(notes);
|
||||
}
|
||||
Ok(reply)
|
||||
}
|
||||
|
||||
/// `file.formatOptions`: a writable format's options with the values Save would use.
|
||||
@@ -1307,7 +1318,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"Save Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel",
|
||||
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel",
|
||||
has_doc,
|
||||
|s, p| save(s, SaveMode::Save, p)
|
||||
),
|
||||
@@ -1343,7 +1354,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"New from Template…",
|
||||
["File"],
|
||||
Some("Cmd+Shift+N"),
|
||||
"{path} or {name, dataBase64}: open a template (or any readable file) as a new untitled document → {index, title, format, warnings}",
|
||||
"{path} or {name, dataBase64}: open a template (or any readable file) as a new untitled document; the color management policies of edit.colorSettings apply as at document.open → {index, title, format, warnings (with the policies' notes)}",
|
||||
always,
|
||||
super::load::new_from_template
|
||||
),
|
||||
@@ -1352,7 +1363,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"Revert",
|
||||
["File"],
|
||||
Some("F12"),
|
||||
"{confirmed?: bool (the app's own: it asks first, then runs the command with it)} discard the changes: reload the saved file into the same tab (history cleared; the tab keeps its place and view). Saved, modified documents only; if the file can't be read the document is left as it is → {path}. The app asks first (a confirm dialog) unless confirmed: true",
|
||||
"{confirmed?: bool (the app's own: it asks first, then runs the command with it)} discard the changes: reload the saved file into the same tab (history cleared; the tab keeps its place and view). Saved, modified documents only; if the file can't be read the document is left as it is → {path, warnings?: the notes of the color management policies of edit.colorSettings, which apply as at document.open}. The app asks first (a confirm dialog) unless confirmed: true",
|
||||
can_revert,
|
||||
revert
|
||||
),
|
||||
|
||||
@@ -1125,6 +1125,13 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result<Value>
|
||||
};
|
||||
let crop = rows.iter().any(|r| r.format.id != "pdf");
|
||||
let items = items(&doc, &o, selection, &selected, &naming.filename, crop, true)?;
|
||||
// The file each item writes for each SVG row, before the folder is made or any row is written.
|
||||
let base = crate::cmd::links::LinkBase::of(s.doc()?);
|
||||
for r in rows.iter().filter(|r| matches!(r.format.id, "svg" | "svgz")) {
|
||||
for item in &items {
|
||||
super::check_images_in(C, r.format.id, &item.doc, base, &r.options_for(item.region, item.artboard)?)?;
|
||||
}
|
||||
}
|
||||
// Appearance of Black › Printing / Exporting for RGB raster rows.
|
||||
// Include Artboard Fill off: the encoders leave the background colors out.
|
||||
let fill = if o.include_artboard_fill == Some(false) { json!({ "includeArtboardFill": false }) } else { json!({}) };
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
//! params' top level or from an `svg` object (which wins), and the files an SVG export writes
|
||||
//! (one per artboard, plus the images it links to).
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Map, Value};
|
||||
use vectorcraft_doc::Document;
|
||||
@@ -155,6 +157,18 @@ fn plan(doc: &Document, p: &Value) -> Result<(ExportOptions, Vec<Option<usize>>,
|
||||
Ok((opts, named.unwrap_or_else(|| vec![0]).into_iter().map(Some).collect(), chosen))
|
||||
}
|
||||
|
||||
/// The art the SVG files of `doc` with options `p` draw, as [`encode`] picks it: with chosen
|
||||
/// artboards, the art over each one; else all of `doc`. `None` when the options don't read.
|
||||
pub(super) fn drawn<'a>(doc: &'a Document, p: &Value) -> Option<Vec<Cow<'a, Document>>> {
|
||||
let (_, boards, chosen) = plan(doc, p).ok()?;
|
||||
if !chosen {
|
||||
return Some(vec![Cow::Borrowed(doc)]);
|
||||
}
|
||||
let mut renderer = vectorcraft_render::Renderer::new();
|
||||
let rects: Vec<_> = boards.iter().flatten().filter_map(|b| doc.artboards.get(*b)).map(|a| a.rect).collect();
|
||||
Some(rects.into_iter().map(|r| Cow::Owned(super::export::art_over(doc, r, &mut renderer))).collect())
|
||||
}
|
||||
|
||||
/// What a save of `doc` as SVG (format `label`) with options `p` loses of several artboards: the
|
||||
/// file is one artboard and reopens as one, unless it carries the native document (Preserve
|
||||
/// Editing Capabilities).
|
||||
|
||||
@@ -202,6 +202,25 @@ fn a_16_bit_cmyk_tiff_with_alpha_places_at_16_bits() {
|
||||
}
|
||||
}
|
||||
|
||||
/// An opaque 16-bit CMYK TIFF's inks are rounded to the nearest 8-bit level, chunky and planar, and
|
||||
/// the stored image keeps its 16-bit samples.
|
||||
#[test]
|
||||
fn an_opaque_16_bit_cmyk_tiffs_inks_are_rounded_to_8_bits() {
|
||||
let c = vec![0u16, 200, 0x80FF, 0x8100, 65535, 32896];
|
||||
let m = vec![511u16, 65535, 0, 128, 129, 0];
|
||||
let none = vec![0u16; 6];
|
||||
let channels = [c, m, none.clone(), none];
|
||||
let want: Vec<u8> = [[0, 2, 0, 0], [1, 255, 0, 0], [128, 0, 0, 0], [128, 0, 0, 0], [255, 1, 0, 0], [128, 0, 0, 0]].concat();
|
||||
let chunky_bytes = hand_tiff(5, 16, &[], false, &channels);
|
||||
let chunky = raster_image(&chunky_bytes).unwrap();
|
||||
assert_eq!(chunky.blob.cmyk().map(|i| i.data), Some(want.clone()), "chunky: the inks");
|
||||
assert_eq!(*chunky.blob.bytes, chunky_bytes, "chunky: the file is stored as it is");
|
||||
let planar = raster_image(&hand_tiff(5, 16, &[], true, &channels)).unwrap();
|
||||
assert_eq!(planar.blob.cmyk().map(|i| i.data), Some(want), "planar: the inks");
|
||||
let stored = image::load_from_memory(&planar.blob.bytes).unwrap();
|
||||
assert_eq!(stored.color(), image::ColorType::Rgb16, "planar: the stored image keeps 16-bit samples");
|
||||
}
|
||||
|
||||
/// A CMYK or grayscale TIFF whose alpha follows another extra sample opens and places with that
|
||||
/// alpha, at 8 and 16 bits, chunky and planar; a CMYK one is not kept as inks. A CMYK one with two
|
||||
/// more samples than its ExtraSamples values count does too.
|
||||
|
||||
@@ -966,7 +966,7 @@ fn an_ai_file_opens_its_variable_library() {
|
||||
{"name": "v_file", "kind": "image", "bindings": 0},
|
||||
{"name": "v_graph", "kind": "graph", "bindings": 0},
|
||||
{"name": "v_unbound", "kind": "unknown", "bindings": 0},
|
||||
], "locked": true})
|
||||
], "locked": true, "sort": {"by": "none", "descending": false}})
|
||||
);
|
||||
let r = s.execute("dataset.list", &json!({})).unwrap();
|
||||
assert_eq!(r["active"], "ds_two", "{r}");
|
||||
@@ -1160,6 +1160,91 @@ fn an_ai_file_saved_without_its_pdf_part_places_from_its_editing_data() {
|
||||
assert!(e.contains("placeholder"), "{e}");
|
||||
}
|
||||
|
||||
/// `document.open` with `linkPages` refuses a `.ai` saved without PDF compatibility, whose page is
|
||||
/// only a placeholder, and opens a PDF-compatible one.
|
||||
#[test]
|
||||
fn link_pages_refuses_an_ai_file_saved_without_its_pdf_part() {
|
||||
let d = std::env::temp_dir().join(format!("vc-ailinkpages-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
let file = |name: &str, page: &str| {
|
||||
let path = d.join(name);
|
||||
std::fs::write(&path, ai::ai(&compressed(&ai::sample_data()), page)).unwrap();
|
||||
path.to_string_lossy().to_string()
|
||||
};
|
||||
let (plain, compatible) = (file("plain.ai", PLACEHOLDER), file("compatible.ai", "0 g 10 10 40 40 re f"));
|
||||
let mut s = Session::new();
|
||||
let e = s.execute("document.open", &json!({"path": plain, "linkPages": true})).unwrap_err().to_string();
|
||||
assert!(e.contains("isn't a PDF or a PDF-compatible .ai file"), "{e}");
|
||||
assert!(s.documents().is_empty(), "nothing opened");
|
||||
s.execute("document.open", &json!({"path": compatible, "linkPages": true})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.has_placed());
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// `document.open` with `linkPages` opens a PDF-compatible `.ai` asked for its crop box on its trim
|
||||
/// box, as it opens as art, showing its bleed box round the artboard, which is the document's bleed.
|
||||
#[test]
|
||||
fn link_pages_open_an_ai_file_on_its_trim_box_with_its_bleed() {
|
||||
let d = std::env::temp_dir().join(format!("vc-ailinkpagestrim-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
let path = d.join("trimmed.ai");
|
||||
let boxes = "/TrimBox [10 10 190 90] /BleedBox [4 2 196 98]";
|
||||
std::fs::write(&path, ai::ai_with(&compressed(&ai::sample_data()), "0 g 10 10 40 40 re f", boxes)).unwrap();
|
||||
let path = path.to_string_lossy().to_string();
|
||||
let mut s = Session::new();
|
||||
s.execute("document.open", &json!({"path": path, "linkPages": true})).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let board = doc.artboards[0].rect;
|
||||
assert_eq!((board.width(), board.height()), (180.0, 80.0), "the trim box");
|
||||
assert_eq!(doc.setup.bleed, [8.0, 8.0, 6.0, 6.0], "top, bottom, left, right");
|
||||
// The page shows its bleed box, so the art in the bleed is kept.
|
||||
let placed = doc.layers[0].children().unwrap()[0].clone();
|
||||
let NodeKind::PlacedDocument(p) = &placed.kind else { panic!("{:?}", placed.kind) };
|
||||
assert_eq!((p.width, p.height, p.page_box), (192.0, 96.0, vectorcraft_doc::PageBox::Bleed));
|
||||
assert_eq!(p.xf.translation(), vectorcraft_geom::Vec2::new(-6.0, -8.0), "the trim box on the artboard");
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn link_pages_on_their_trim_boxes_keep_the_bleed_between_the_artboards() {
|
||||
// Two 100 pt trim boxes: the first with 60 pt of bleed on each side, the second with 80 pt on
|
||||
// its left, more than the largest document bleed (72 pt).
|
||||
let entries = format!("/PieceInfo << /Illustrator << /Private << /AIPrivateData1 {} 0 R /NumBlock 1 >> >> >>", first_extra(2));
|
||||
let first = PdfPage {
|
||||
bleed: Some([0.0, 0.0, 220.0, 220.0]),
|
||||
trim: Some([60.0, 60.0, 160.0, 160.0]),
|
||||
entries,
|
||||
..PdfPage::new(220.0, 220.0, "0 g 0 0 220 220 re f")
|
||||
};
|
||||
let second = PdfPage {
|
||||
bleed: Some([0.0, 0.0, 240.0, 220.0]),
|
||||
trim: Some([80.0, 60.0, 180.0, 160.0]),
|
||||
..PdfPage::new(240.0, 220.0, "0 g 0 0 240 220 re f")
|
||||
};
|
||||
let d = std::env::temp_dir().join(format!("vc-ailinkpagesgap-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
let path = d.join("pages.ai");
|
||||
std::fs::write(&path, pdf_with(&[first, second], &["<< /Length 4 >>\nstream\ndata\nendstream"], None)).unwrap();
|
||||
let path = path.to_string_lossy().to_string();
|
||||
let mut s = Session::new();
|
||||
s.execute("document.open", &json!({"path": path, "linkPages": true})).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert_eq!(doc.setup.bleed, [60.0, 60.0, 72.0, 60.0], "top, bottom, left, right");
|
||||
// The first page's bleed ends at 160; the second's starts 36 pt later, 80 pt left of its trim box.
|
||||
let boards: Vec<(f64, f64)> = doc.artboards.iter().map(|a| (a.rect.x0, a.rect.x1)).collect();
|
||||
assert_eq!(boards, [(0.0, 100.0), (276.0, 376.0)]);
|
||||
let shown: Vec<f64> = doc
|
||||
.layers
|
||||
.iter()
|
||||
.map(|l| match &l.children().unwrap()[0].kind {
|
||||
NodeKind::PlacedDocument(p) => p.xf.translation().x,
|
||||
k => panic!("{k:?}"),
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(shown, [-60.0, 196.0], "each page's bleed box round its artboard");
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// A page of text alone, as text-only art has in its PDF part: no path is painted.
|
||||
const TEXT_ART: &str = "BT /F1 36 Tf 10 40 Td (Text only) Tj ET";
|
||||
|
||||
|
||||
@@ -277,3 +277,17 @@ fn ps_and_epsf_files_open_and_place() {
|
||||
let e = writable_format(None, Some("out.ps")).unwrap_err();
|
||||
assert_eq!(e, "PostScript files can be opened but not written (see document.formats)");
|
||||
}
|
||||
|
||||
/// A program in the legacy `.ai` format with a template box and no art size (version 3) opens as a
|
||||
/// `.ai` or `.ait` on a US Letter artboard around the box's center, and as an EPS on its bounding
|
||||
/// box.
|
||||
#[test]
|
||||
fn a_legacy_ai_program_opens_on_its_artboard_and_an_eps_on_its_page() {
|
||||
let program = b"%!PS-Adobe-2.0 EPSF-1.2\n%%Creator: a script\n%%BoundingBox: 10 10 30 30\n%AI3_TemplateBox: 100 100 100 100\n\
|
||||
%%EndComments\n%%BeginProlog\n/m {moveto} def /L {lineto} def /f {closepath fill} def /k {setcmykcolor} def\n\
|
||||
%%EndProlog\n%%BeginSetup\n%%EndSetup\n0 0 0 1 k\n10 10 m\n30 10 L\n30 30 L\n10 30 L\nf\n%%PageTrailer\nshowpage\n%%Trailer\n%%EOF\n";
|
||||
for (name, size) in [("old.ai", (612.0, 792.0)), ("old.ait", (612.0, 792.0)), ("old.eps", (20.0, 20.0))] {
|
||||
let r = load(name, program).unwrap_or_else(|e| panic!("{name}: {e}"));
|
||||
assert_eq!(r.doc.artboards[0].rect.size(), vectorcraft_geom::Size::new(size.0, size.1), "{name}: {:?}", r.warnings);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -338,6 +338,152 @@ fn a_plot_of_the_arts_bounds_leaves_out_images_in_dynamic_symbol_art() {
|
||||
assert!(e.contains("no visible art"), "{e}");
|
||||
}
|
||||
|
||||
/// A rectangle filled black, or one that paints nothing.
|
||||
fn plot_rect(d: &mut vectorcraft_doc::Document, r: vectorcraft_geom::Rect, painted: bool) -> std::sync::Arc<vectorcraft_doc::Node> {
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
let fill = if painted { Paint::solid(Color::BLACK) } else { Paint::None };
|
||||
let appearance = vectorcraft_doc::Appearance::basic(fill, Paint::None, 0.0);
|
||||
std::sync::Arc::new(vectorcraft_doc::Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(r), appearance))
|
||||
}
|
||||
|
||||
/// An instance of symbol `symbol` placed by `xf`.
|
||||
fn plot_instance(d: &mut vectorcraft_doc::Document, symbol: &str, xf: vectorcraft_geom::Affine) -> vectorcraft_doc::Node {
|
||||
vectorcraft_doc::Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: symbol.into(), xf })
|
||||
}
|
||||
|
||||
/// Symbol `name` holding `art` in a group.
|
||||
fn plot_symbol(d: &mut vectorcraft_doc::Document, name: &str, art: Vec<std::sync::Arc<vectorcraft_doc::Node>>, dynamic: bool) {
|
||||
let group = vectorcraft_doc::Node::group(d.alloc_id(), art);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic, name: name.into(), art: std::sync::Arc::new(group) });
|
||||
}
|
||||
|
||||
/// Puts `n` on the first layer of `d`.
|
||||
fn plot_on_layer(d: &mut vectorcraft_doc::Document, n: vectorcraft_doc::Node) {
|
||||
std::sync::Arc::make_mut(&mut d.layers[0]).children_mut().unwrap().push(std::sync::Arc::new(n));
|
||||
}
|
||||
|
||||
/// The art of a symbol with 9-slice guides, static or dynamic, is placed whole and measured
|
||||
/// without what the plot leaves out: a frame that paints nothing sets where the guides place the
|
||||
/// painted art inside it, and is not measured itself.
|
||||
#[test]
|
||||
fn a_plot_of_the_arts_bounds_places_9_slice_symbol_art_by_all_of_it() {
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
// Static and dynamic, and with the instance's fill staining the art.
|
||||
for (dynamic, stained) in [(false, false), (true, false), (false, true)] {
|
||||
let mut d = vectorcraft_doc::Document::new(400.0, 400.0);
|
||||
let frame = plot_rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), false);
|
||||
let square = plot_rect(&mut d, Rect::new(40.0, 40.0, 60.0, 60.0), true);
|
||||
plot_symbol(&mut d, "Panel", vec![frame, square], dynamic);
|
||||
d.set_symbol_nine_slice("Panel", Some(vectorcraft_doc::SymbolNineSlice::default()));
|
||||
let mut wide = plot_instance(&mut d, "Panel", Affine::scale_non_uniform(2.0, 1.0));
|
||||
if stained {
|
||||
let red = vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0));
|
||||
wide.appearance = vectorcraft_doc::Appearance::basic(red, vectorcraft_color::Paint::None, 0.0).into();
|
||||
}
|
||||
plot_on_layer(&mut d, wide);
|
||||
// Scaled 2 times across, the middle column maps x to 3x - 50: the square draws from x 70
|
||||
// to 130.
|
||||
let b = super::export_art_bounds(&d, "hpgl").unwrap();
|
||||
let exact = [(b.x0, 70.0), (b.y0, 40.0), (b.x1, 130.0), (b.y1, 60.0)].iter().all(|(a, e)| (a - e).abs() < 1e-6);
|
||||
assert!(exact, "dynamic: {dynamic}, stained: {stained}, {b:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// In art placed through 9-slice guides, a group with a fill of its own keeps the path it paints,
|
||||
/// which paints nothing by itself.
|
||||
#[test]
|
||||
fn a_plot_of_the_arts_bounds_keeps_what_a_group_paints_in_9_slice_symbol_art() {
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
let mut d = vectorcraft_doc::Document::new(400.0, 400.0);
|
||||
let frame = plot_rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), false);
|
||||
let bare = plot_rect(&mut d, Rect::new(40.0, 40.0, 60.0, 60.0), false);
|
||||
let mut group = vectorcraft_doc::Node::group(d.alloc_id(), vec![bare]);
|
||||
let black = vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK);
|
||||
group.appearance = vectorcraft_doc::Appearance::basic(black, vectorcraft_color::Paint::None, 0.0).into();
|
||||
plot_symbol(&mut d, "Panel", vec![frame, std::sync::Arc::new(group)], false);
|
||||
d.set_symbol_nine_slice("Panel", Some(vectorcraft_doc::SymbolNineSlice::default()));
|
||||
let wide = plot_instance(&mut d, "Panel", Affine::scale_non_uniform(2.0, 1.0));
|
||||
plot_on_layer(&mut d, wide);
|
||||
let b = super::export_art_bounds(&d, "hpgl").expect("the group's path is plotted");
|
||||
let exact = [(b.x0, 70.0), (b.y0, 40.0), (b.x1, 130.0), (b.y1, 60.0)].iter().all(|(a, e)| (a - e).abs() < 1e-6);
|
||||
assert!(exact, "{b:?}");
|
||||
}
|
||||
|
||||
/// A symbol without guides in the art of a symbol with 9-slice guides is measured without what the
|
||||
/// plot leaves out, in the placed art and in an instance of its own.
|
||||
#[test]
|
||||
fn a_plot_of_the_arts_bounds_leaves_out_unplotted_art_of_symbols_in_9_slice_art() {
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
let mut d = vectorcraft_doc::Document::new(400.0, 400.0);
|
||||
let far = plot_rect(&mut d, Rect::new(45.0, -500.0, 55.0, -480.0), false);
|
||||
let dot = plot_rect(&mut d, Rect::new(45.0, 45.0, 55.0, 55.0), true);
|
||||
plot_symbol(&mut d, "Dot", vec![far, dot], false);
|
||||
let frame = plot_rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), false);
|
||||
let inner = std::sync::Arc::new(plot_instance(&mut d, "Dot", Affine::IDENTITY));
|
||||
plot_symbol(&mut d, "Panel", vec![frame, inner], false);
|
||||
d.set_symbol_nine_slice("Panel", Some(vectorcraft_doc::SymbolNineSlice::default()));
|
||||
let wide = plot_instance(&mut d, "Panel", Affine::scale_non_uniform(2.0, 1.0));
|
||||
plot_on_layer(&mut d, wide);
|
||||
let near = |b: Rect, e: [f64; 4]| [b.x0, b.y0, b.x1, b.y1].iter().zip(e).all(|(a, e)| (a - e).abs() < 1e-6);
|
||||
// The dot's box is in the middle column, which maps x to 3x - 50.
|
||||
let b = super::export_art_bounds(&d, "hpgl").unwrap();
|
||||
assert!(near(b, [85.0, 45.0, 115.0, 55.0]), "{b:?}");
|
||||
let own = plot_instance(&mut d, "Dot", Affine::translate((200.0, 0.0)));
|
||||
plot_on_layer(&mut d, own);
|
||||
let b = super::export_art_bounds(&d, "hpgl").unwrap();
|
||||
assert!(near(b, [85.0, 45.0, 255.0, 55.0]), "{b:?}");
|
||||
}
|
||||
|
||||
/// The copy of a dynamic symbol that an instance's changes are measured on keeps the symbol's
|
||||
/// 9-slice guides.
|
||||
#[test]
|
||||
fn a_plot_of_the_arts_bounds_measures_changed_9_slice_instances_by_their_guides() {
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
let mut d = vectorcraft_doc::Document::new(400.0, 400.0);
|
||||
let bar = plot_rect(&mut d, Rect::new(10.0, 40.0, 70.0, 60.0), true);
|
||||
plot_symbol(&mut d, "Bar", vec![bar], false);
|
||||
let frame = plot_rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), false);
|
||||
let inner = std::sync::Arc::new(plot_instance(&mut d, "Bar", Affine::IDENTITY));
|
||||
plot_symbol(&mut d, "Panel", vec![frame, inner], true);
|
||||
d.set_symbol_nine_slice("Panel", Some(vectorcraft_doc::SymbolNineSlice::default()));
|
||||
let mut wide = plot_instance(&mut d, "Panel", Affine::scale_non_uniform(2.0, 1.0));
|
||||
wide.extras_mut().symbol_overrides =
|
||||
vec![vectorcraft_doc::SymbolOverride { path: vec![0], fill: Some(vectorcraft_color::Paint::None), ..Default::default() }];
|
||||
plot_on_layer(&mut d, wide);
|
||||
// The bar crosses the left guide and is placed by the middle column's map, x to 3x - 50: it
|
||||
// draws from x -20 to 160.
|
||||
let b = super::export_art_bounds(&d, "hpgl").unwrap();
|
||||
let exact = |b: Rect| [(b.x0, -20.0), (b.y0, 40.0), (b.x1, 160.0), (b.y1, 60.0)].iter().all(|(a, e)| (a - e).abs() < 1e-6);
|
||||
assert!(exact(b), "{b:?}");
|
||||
// The same instance in the art of a symbol without guides.
|
||||
let wide = std::sync::Arc::make_mut(&mut d.layers[0]).children_mut().unwrap().pop().unwrap();
|
||||
plot_symbol(&mut d, "Holder", vec![wide], false);
|
||||
let holder = plot_instance(&mut d, "Holder", Affine::IDENTITY);
|
||||
plot_on_layer(&mut d, holder);
|
||||
let b = super::export_art_bounds(&d, "hpgl").unwrap();
|
||||
assert!(exact(b), "{b:?}");
|
||||
}
|
||||
|
||||
/// An instance in a dynamic symbol's art, in a group at 0% opacity that an instance of the symbol
|
||||
/// brings back to full opacity, is measured with the paint it gives its own symbol's art.
|
||||
#[test]
|
||||
fn a_plot_of_the_arts_bounds_measures_instances_that_an_instance_brings_back() {
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
let mut d = vectorcraft_doc::Document::new(400.0, 400.0);
|
||||
let bare = plot_rect(&mut d, Rect::new(300.0, 300.0, 320.0, 320.0), false);
|
||||
plot_symbol(&mut d, "Inner", vec![bare], true);
|
||||
let mut inner = plot_instance(&mut d, "Inner", Affine::IDENTITY);
|
||||
let black = vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK);
|
||||
inner.extras_mut().symbol_overrides = vec![vectorcraft_doc::SymbolOverride { path: vec![0], fill: Some(black), ..Default::default() }];
|
||||
plot_symbol(&mut d, "Outer", vec![std::sync::Arc::new(inner)], true);
|
||||
std::sync::Arc::make_mut(&mut d.symbols[1].art).opacity = 0.0;
|
||||
let mut outer = plot_instance(&mut d, "Outer", Affine::IDENTITY);
|
||||
outer.extras_mut().symbol_overrides = vec![vectorcraft_doc::SymbolOverride { path: vec![], opacity: Some(1.0), ..Default::default() }];
|
||||
plot_on_layer(&mut d, outer);
|
||||
let b = super::export_art_bounds(&d, "hpgl").expect("the painted rectangle is plotted");
|
||||
assert!((b.x0 - 300.0).abs() < 1e-6 && (b.x1 - 320.0).abs() < 1e-6, "{b:?}");
|
||||
}
|
||||
|
||||
/// A placed image with a Vector Halftone effect is measured when the effect makes dots, and left
|
||||
/// out when it would take more cells than the effect makes.
|
||||
#[test]
|
||||
|
||||
@@ -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"));
|
||||
}
|
||||
|
||||
@@ -386,10 +386,32 @@ fn replacing_a_clipped_psd_keeps_its_scale() {
|
||||
assert_eq!((r["width"].as_f64(), r["height"].as_f64()), (Some(200.0), Some(100.0)), "{r}");
|
||||
let (anchors, _, _) = clip_group(&s.doc().unwrap().doc, NodeId(r["ids"][0].as_u64().unwrap()));
|
||||
assert_eq!(anchors, [[200.0, 150.0], [300.0, 250.0], [100.0, 250.0]]);
|
||||
// Other art replacing the clip group takes its centre only, as before.
|
||||
// A plain image replacing the clip group keeps its scale too.
|
||||
let plain = vectorcraft_format::base64_encode(&red_psd(&[]));
|
||||
let r = s.execute("file.place", &json!({"name": "plain.psd", "dataBase64": plain, "replace": true})).unwrap();
|
||||
assert_eq!((r["width"].as_f64(), r["height"].as_f64()), (Some(100.0), Some(50.0)), "{r}");
|
||||
assert_eq!((r["width"].as_f64(), r["height"].as_f64()), (Some(200.0), Some(100.0)), "{r}");
|
||||
}
|
||||
|
||||
/// A plain image replacing a clipped PSD file takes the clipped image's scale and rotation.
|
||||
#[test]
|
||||
fn a_plain_image_replacing_a_clipped_psd_keeps_its_rotation() {
|
||||
let data = vectorcraft_format::base64_encode(&red_psd(&triangle_resources()));
|
||||
let plain = vectorcraft_format::base64_encode(&red_psd(&[]));
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let r = s.execute("file.place", &json!({"name": "cut.psd", "dataBase64": data, "at": [200, 200]})).unwrap();
|
||||
let group = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
s.execute("object.scale", &json!({"sx": 200, "sy": 150})).unwrap();
|
||||
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
|
||||
let xf = |s: &Session, id: NodeId| match s.doc().unwrap().doc.node(id).map(|n| &n.kind) {
|
||||
Some(NodeKind::Image(im)) => im.xf.as_coeffs(),
|
||||
other => panic!("not an image: {other:?}"),
|
||||
};
|
||||
let (_, _, image) = clip_group(&s.doc().unwrap().doc, group);
|
||||
let before = xf(&s, image);
|
||||
let r = s.execute("file.place", &json!({"name": "plain.psd", "dataBase64": plain, "replace": true})).unwrap();
|
||||
let after = xf(&s, NodeId(r["ids"][0].as_u64().unwrap()));
|
||||
assert!(after.iter().zip(before).all(|(a, b)| (a - b).abs() < 1e-9), "{after:?} != {before:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,459 @@
|
||||
//! 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 < b & 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>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 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)}));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -38,12 +38,22 @@ fn count_or(p: &Value, key: &str, default: u64, cmd: &str) -> Result<u64> {
|
||||
|
||||
/// `shape.flare`'s params `p` with every setting given: the defaults filled in, the counts at most
|
||||
/// 50 and the rings' end point as `x2`, `y2` (from `pathLength` and `direction` when `p` gives no
|
||||
/// end point).
|
||||
/// end point), with `ringSeed` when `p` gives one.
|
||||
fn settings_of(p: &Value, cmd: &str) -> Result<Value> {
|
||||
let c = Point::new(f64_req(p, "cx", cmd)?, f64_req(p, "cy", cmd)?);
|
||||
let mut numbers: Vec<&str> = SETTINGS.iter().map(|(key, _)| *key).collect();
|
||||
numbers.extend(["x2", "y2", "direction", "pathLength", "seed"]);
|
||||
numbers.extend(["x2", "y2", "direction", "pathLength", "seed", "ringSeed"]);
|
||||
check_numbers(p, &numbers, cmd)?;
|
||||
let seed_of = |key: &str| match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => v.as_u64().map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be a whole number of at least 0, not {v}"))),
|
||||
};
|
||||
let seed = seed_of("seed")?.unwrap_or(DEFAULT_SEED);
|
||||
// Each `ringSeed` below 2^53 (what a JSON number holds exactly) places the rings anew.
|
||||
let ring_seed = match seed_of("ringSeed")? {
|
||||
Some(r) if r >= 1 << 53 => return Err(bad(cmd, format!("`ringSeed` must be below 2^53, not {r}"))),
|
||||
r => r,
|
||||
};
|
||||
let rays = count_or(p, "rays", 15, cmd)?.min(50);
|
||||
let rings = count_or(p, "rings", 10, cmd)?.min(50);
|
||||
let end = match (p.get("x2").and_then(Value::as_f64), p.get("y2").and_then(Value::as_f64)) {
|
||||
@@ -53,8 +63,10 @@ fn settings_of(p: &Value, cmd: &str) -> Result<Value> {
|
||||
c + Vec2::new(a.cos(), -a.sin()) * f64_or(p, "pathLength", 300.0)
|
||||
}
|
||||
};
|
||||
let seed = p.get("seed").and_then(Value::as_u64).unwrap_or(DEFAULT_SEED);
|
||||
let mut v = json!({ "cx": c.x, "cy": c.y, "x2": end.x, "y2": end.y, "rays": rays, "rings": rings, "seed": seed });
|
||||
if let Some(r) = ring_seed {
|
||||
v["ringSeed"] = json!(r);
|
||||
}
|
||||
for (key, default) in SETTINGS {
|
||||
v[key] = json!(f64_or(p, key, default));
|
||||
}
|
||||
|
||||
@@ -51,7 +51,7 @@ mod options;
|
||||
mod presets;
|
||||
mod report;
|
||||
|
||||
pub(crate) use analysis::{outlined_text, see_through_images};
|
||||
pub(crate) use analysis::{carry, outlined_text, see_through_images};
|
||||
pub(crate) use apply::{expand_transparent_tile_images, flatten_document, flatten_expanded, has_transparent_tile_images};
|
||||
#[cfg(test)]
|
||||
pub(crate) use apply::{with_clips_ignored, with_every_region};
|
||||
|
||||
@@ -56,7 +56,7 @@ pub(crate) fn outlined_text(n: &Node) -> Option<Node> {
|
||||
}
|
||||
|
||||
/// `to` (art made from `from`) with `from`'s name, transparency, opacity mask and effects.
|
||||
fn carry(from: &Node, mut to: Node) -> Node {
|
||||
pub(crate) fn carry(from: &Node, mut to: Node) -> Node {
|
||||
to.name = from.name.clone();
|
||||
to.opacity = from.opacity;
|
||||
to.blend = from.blend;
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add Freeform Point",
|
||||
[],
|
||||
None,
|
||||
"{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind; the points on a label's characters are not stored → {index}",
|
||||
"{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind; the points on a label's characters are not stored → {index}",
|
||||
has_doc,
|
||||
add_point
|
||||
),
|
||||
@@ -28,7 +28,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Edit Freeform Point",
|
||||
[],
|
||||
None,
|
||||
"{index? (default: the selected point), at?: [x,y] (document coordinates), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient → {index}",
|
||||
"{index? (default: the selected point), at?: [x,y] (document coordinates), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient → {index}",
|
||||
has_doc,
|
||||
set_point
|
||||
),
|
||||
@@ -37,7 +37,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Delete Freeform Point",
|
||||
[],
|
||||
None,
|
||||
"{index? (default: the selected point), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} remove a point (never the last one); lines through it close up around it and lines left with one point go → {index}",
|
||||
"{index? (default: the selected point), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} remove a point (never the last one); lines through it close up around it and lines left with one point go → {index}",
|
||||
has_doc,
|
||||
delete_point
|
||||
),
|
||||
@@ -46,7 +46,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add Freeform Line",
|
||||
[],
|
||||
None,
|
||||
"{points: [index, …] (at least two), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} join points with a smooth line through them, in order → {line}",
|
||||
"{points: [index, …] (at least two), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} join points with a smooth line through them, in order → {line}",
|
||||
has_doc,
|
||||
add_line
|
||||
),
|
||||
@@ -55,7 +55,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Split Freeform Line",
|
||||
[],
|
||||
None,
|
||||
"{line: line index, segment: the segment from the line's point `segment` to the next, t?: 0..1 along it (default 0.5), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} add a point on a line there (colour, opacity and spread between the segment's ends) and select it → {index}",
|
||||
"{line: line index, segment: the segment from the line's point `segment` to the next, t?: 0..1 along it (default 0.5), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point on a line there (colour, opacity and spread between the segment's ends) and select it → {index}",
|
||||
has_doc,
|
||||
split_line
|
||||
),
|
||||
@@ -201,7 +201,9 @@ fn edit<R>(s: &mut Session, p: &Value, cmd: &str, mut f: impl FnMut(&mut Freefor
|
||||
first.get_or_insert(r);
|
||||
Ok(())
|
||||
};
|
||||
edit_items(s, &ids, item, cmd, "Gradient", !stroke, |n, index| {
|
||||
let of = super::appearance::reference_of(s, p, item, cmd)?;
|
||||
let shown_at = super::appearance::first_edited(s, item, of, &ids);
|
||||
edit_items(s, &ids, item, of, cmd, "Gradient", !stroke, |n, index| {
|
||||
if index.is_none()
|
||||
&& let NodeKind::Text(t) = &mut n.kind
|
||||
{
|
||||
@@ -222,7 +224,9 @@ fn edit<R>(s: &mut Session, p: &Value, cmd: &str, mut f: impl FnMut(&mut Freefor
|
||||
})?;
|
||||
let r = first.ok_or_else(|| bad(cmd, NOT_FREEFORM))?;
|
||||
// The edited gradient is the last one used (`paint.lastGradient`).
|
||||
let shown = s.doc()?.doc.node(ids[0]).map(|n| super::paint::proxy_paint(n, stroke, item.resolve(&n.appearance, !stroke, cmd).ok().flatten()));
|
||||
let shown = shown_at.and_then(|(id, item)| {
|
||||
s.doc().ok()?.doc.node(id).map(|n| super::paint::proxy_paint(n, stroke, item.resolve(&n.appearance, !stroke, cmd).ok().flatten()))
|
||||
});
|
||||
if let Some(p) = shown {
|
||||
s.remember_paint(&p);
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Gradient",
|
||||
["Window", "Gradient"],
|
||||
None,
|
||||
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters their gradient without its placement, fitted to each label",
|
||||
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters their gradient without its placement, fitted to each label",
|
||||
has_doc,
|
||||
edit_gradient
|
||||
),
|
||||
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Gradient Vector",
|
||||
[],
|
||||
None,
|
||||
"{start?: [x,y], end?: [x,y] (document coordinates; both or neither: omitted, the vector stays), aspect?: % (radial, conic and diamond: the extent's height / width across the vector, a negative one mirroring a conic's sweep and an error for the other kinds; default: kept), focal?: [x,y] (document coordinates) | null (radial: the focal point, where the first stop sits, pulled inside the extent ellipse; null centres it; default: it keeps its place in the ellipse; an error on a conic or diamond gradient), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (alias: index; omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\", index?: appearance item index (as item)} set the gradient vector, aspect ratio and focal point (solid paints become the default gradient; type objects set it on their runs, in text space). On a path directly in a graph series, the graph also stores the gradient with its placement relative to the path's box when it is on the topmost visible fill or stroke, and every path of the series takes it at the same place on its own box (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters their gradient without the placement this command sets, fitted to each label",
|
||||
"{start?: [x,y], end?: [x,y] (document coordinates; both or neither: omitted, the vector stays), aspect?: % (radial, conic and diamond: the extent's height / width across the vector, a negative one mirroring a conic's sweep and an error for the other kinds; default: kept), focal?: [x,y] (document coordinates) | null (radial: the focal point, where the first stop sits, pulled inside the extent ellipse; null centres it; default: it keeps its place in the ellipse; an error on a conic or diamond gradient), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (alias: index; omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\", index?: appearance item index (as item)} set the gradient vector, aspect ratio and focal point (solid paints become the default gradient; type objects set it on their runs, in text space). On a path directly in a graph series, the graph also stores the gradient with its placement relative to the path's box when it is on the topmost visible fill or stroke, and every path of the series takes it at the same place on its own box (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters their gradient without the placement this command sets, fitted to each label",
|
||||
has_doc,
|
||||
set_gradient_geom
|
||||
),
|
||||
@@ -580,7 +580,10 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let new_default = apply_gradient_edit_in_model(&default_paint, &with_stored_stops(&for_default, &default_paint, &stored), None, &|_| true, model)
|
||||
.map_err(|e| bad(C, e))?;
|
||||
let freeform = str_param(p, "kind").and_then(GradientKind::parse) == Some(GradientKind::Freeform);
|
||||
edit_items(s, &ids, item, C, "Gradient", !stroke, |n, index| {
|
||||
let of = super::appearance::reference_of(s, p, item, C)?;
|
||||
let shown_at = super::appearance::first_edited(s, item, of, &ids);
|
||||
// The objects returned: with a design's art, those with a row equal to the art's.
|
||||
let edited = edit_items(s, &ids, item, of, C, "Gradient", !stroke, |n, index| {
|
||||
if index.is_none()
|
||||
&& let NodeKind::Text(t) = &mut n.kind
|
||||
{
|
||||
@@ -616,9 +619,12 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
st.gradient_mode = m;
|
||||
}
|
||||
// The last gradient is the one the first object now shows (the defaults' without objects).
|
||||
let shown = match ids.first() {
|
||||
Some(id) => s.doc()?.doc.node(*id).map(|n| super::paint::proxy_paint(n, stroke, item.resolve(&n.appearance, !stroke, C).ok().flatten())),
|
||||
None => Some(new_default.clone()),
|
||||
let shown = match shown_at {
|
||||
Some((id, item)) => {
|
||||
s.doc()?.doc.node(id).map(|n| super::paint::proxy_paint(n, stroke, item.resolve(&n.appearance, !stroke, C).ok().flatten()))
|
||||
}
|
||||
None if ids.is_empty() => Some(new_default.clone()),
|
||||
None => None,
|
||||
};
|
||||
if let Some(shown) = shown {
|
||||
s.remember_paint(&shown);
|
||||
@@ -628,7 +634,7 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} else {
|
||||
s.paint.fill = new_default;
|
||||
}
|
||||
Ok(json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()}))
|
||||
Ok(json!({"ids": edited.iter().map(|i| i.0).collect::<Vec<_>>()}))
|
||||
}
|
||||
|
||||
/// A painted stroke on a type run without a weight gets 1 pt.
|
||||
@@ -766,7 +772,9 @@ fn set_gradient_geom(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let targets = super::appearance::drop_design_art(&s.doc()?.doc, targets);
|
||||
let model = super::paint::new_color_model(s, &Value::Null);
|
||||
edit_items(s, &targets, item, C, "Gradient", !stroke, |n, index| {
|
||||
let of = super::appearance::reference_of(s, p, item, C)?;
|
||||
// The objects returned: with a design's art, those with a row equal to the art's.
|
||||
let targets = edit_items(s, &targets, item, of, C, "Gradient", !stroke, |n, index| {
|
||||
if index.is_none()
|
||||
&& let NodeKind::Text(t) = &mut n.kind
|
||||
{
|
||||
|
||||
@@ -40,7 +40,9 @@ pub use commands::specs;
|
||||
pub(crate) use data::{apply_csv, parse_csv};
|
||||
#[cfg(test)]
|
||||
use data::{fmt_value, to_csv};
|
||||
pub(crate) use edit::{graphs_holding, keep_placed};
|
||||
pub use edit::{GraphTypeSubject, graph_type_subject};
|
||||
pub(crate) use edit::{edit_graph_art, graphs_holding, keep_placed};
|
||||
pub use generate::calculated_axes;
|
||||
#[cfg(test)]
|
||||
use generate::generate;
|
||||
#[cfg(test)]
|
||||
@@ -48,8 +50,8 @@ use series::default_series_color;
|
||||
pub(crate) use series::{
|
||||
LabelTextChange, capture_label_anti_alias, capture_label_changes, capture_label_object_opacity, capture_label_paragraphs, capture_label_rows,
|
||||
capture_label_styles, capture_label_text, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, is_design_art,
|
||||
label_object_opacity_differs, labels_in, paint_targets, series_group_marks, series_group_marks_where, series_groups_among, series_marks_in,
|
||||
series_object_opacity_differs, shown_paint,
|
||||
label_object_opacity_differs, labels_in, paint_targets, plain_labels, series_group_marks, series_group_marks_where, series_groups_among,
|
||||
series_marks_in, series_object_opacity_differs, shown_paint,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -2,7 +2,7 @@ use vectorcraft_doc::graph::graph_art_without_type as art_bounds;
|
||||
|
||||
use super::axis::{MAX_TICK_MARKS, count_given, one_line};
|
||||
use super::data::apply_data;
|
||||
use super::generate::{children_bounds, generate};
|
||||
use super::generate::{calculated_axes, children_bounds, generate};
|
||||
use super::series::{picked_series, reselect_series};
|
||||
use super::{
|
||||
Affine, Document, EngineError, GraphKind, GraphSpec, Node, NodeId, Rect, Result, Session, TickLength, Value, ValueAxisSide, bad, f64_req, json,
|
||||
@@ -88,6 +88,23 @@ pub(crate) fn keep_placed(d: &mut Document, graphs: &[(NodeId, Option<Rect>, Opt
|
||||
}
|
||||
}
|
||||
|
||||
/// Let `edit` change the art of graph node `n` (a copy outside any document) without the next redraw reading the
|
||||
/// change as a move or scale: the plot rect first takes any move or scale of the art since it was generated, as a
|
||||
/// redraw measures it, and the bounds the graph keeps become those of the changed art (also for a graph that had none,
|
||||
/// so a later move is followed).
|
||||
pub(crate) fn edit_graph_art(n: &mut Node, edit: impl FnOnce(&mut Node)) {
|
||||
let moved = measured(n).and_then(|(placed, now)| n.extras().graph.as_deref().and_then(|g| carried(g.rect, placed, now)));
|
||||
if let (Some(rect), Some(g)) = (moved, n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) {
|
||||
g.rect = rect;
|
||||
}
|
||||
edit(n);
|
||||
let children = n.children();
|
||||
let (whole, art) = (children.and_then(|c| children_bounds(c)), children.and_then(|c| art_bounds(c)));
|
||||
if let Some(g) = n.extras_if_any().and_then(|e| e.graph.as_deref_mut()) {
|
||||
(g.placed, g.placed_art) = (whole, art);
|
||||
}
|
||||
}
|
||||
|
||||
/// Regenerate graph `id` from `spec` (adjusting the plot rect for any move/scale since the last
|
||||
/// generation, which is recorded in the spec's `placed_art` bounds, or `placed` in graphs saved without them).
|
||||
pub(super) fn regenerate(d: &mut Document, id: NodeId, mut spec: GraphSpec) -> Result<()> {
|
||||
@@ -169,6 +186,28 @@ pub(super) fn spec_of(s: &Session, id: NodeId) -> Result<GraphSpec> {
|
||||
s.doc()?.doc.node(id).and_then(|n| n.extras().graph.as_deref().cloned()).ok_or(EngineError::NoNode(id))
|
||||
}
|
||||
|
||||
/// What `graph.setType` without `id` or `seriesIndexes` acts on, for the Graph Type dialog.
|
||||
pub struct GraphTypeSubject {
|
||||
/// The selected graph, or the graph that holds the selection.
|
||||
pub id: NodeId,
|
||||
/// The series picked in it with Group Selection, in order; empty when the type goes to the whole graph.
|
||||
pub series: Vec<usize>,
|
||||
/// The least value, the greatest and the number of divisions each value axis is drawn with while its tick values
|
||||
/// are calculated: the left (or only) axis, then the right axis' own scale (the left one's without Separate Scales).
|
||||
pub calculated: [(f64, f64, usize); 2],
|
||||
}
|
||||
|
||||
/// The graph and series that `graph.setType {}` reads its options from, as [`GraphTypeSubject`]. An error without a
|
||||
/// selected graph, as the command gives.
|
||||
pub fn graph_type_subject(s: &Session) -> Result<GraphTypeSubject> {
|
||||
const C: &str = "graph.setType";
|
||||
let p = json!({});
|
||||
let id = target(s, &p, C)?;
|
||||
let spec = spec_of(s, id)?;
|
||||
let count = spec.rows.iter().map(Vec::len).max().unwrap_or(0).min(vectorcraft_doc::MAX_GRAPH_SERIES);
|
||||
Ok(GraphTypeSubject { id, series: picked_series(s, &p, id, count, C)?, calculated: calculated_axes(&spec) })
|
||||
}
|
||||
|
||||
fn query_type_options(spec: &GraphSpec, count: usize, picked: &[usize]) -> Value {
|
||||
// With series picked, the type and value axis they share, so the dialog's OK keeps them.
|
||||
let kinds: Vec<GraphKind> = picked.iter().map(|i| spec.series_kind(*i)).collect();
|
||||
|
||||
@@ -38,6 +38,101 @@ fn nth<T>(list: &[Option<T>], s: usize) -> Option<&T> {
|
||||
list.get(s).and_then(Option::as_ref)
|
||||
}
|
||||
|
||||
/// The data a value range is read from: each series' type, the cells (a blank is `None`), which series use the right
|
||||
/// axis' own scale, and the number of categories.
|
||||
struct Values<'a> {
|
||||
kinds: &'a [GraphKind],
|
||||
cells: &'a [Vec<Option<f64>>],
|
||||
on_right: &'a [bool],
|
||||
ncat: usize,
|
||||
}
|
||||
|
||||
impl Values<'_> {
|
||||
fn cell(&self, c: usize, s: usize) -> Option<f64> {
|
||||
self.cells.get(c).and_then(|r| r.get(s)).copied().flatten()
|
||||
}
|
||||
|
||||
fn axis(&self, s: usize) -> usize {
|
||||
usize::from(self.on_right.get(s).copied().unwrap_or(false))
|
||||
}
|
||||
|
||||
/// The value range per axis (stacked graphs stack positives and negatives separately), and a scatter's x range.
|
||||
fn range(&self, scatter: bool) -> ([f64; 2], [f64; 2], f64, f64) {
|
||||
let (mut lo, mut hi) = ([0.0f64; 2], [0.0f64; 2]);
|
||||
let (mut xlo, mut xhi) = (f64::MAX, f64::MIN);
|
||||
for c in 0..self.ncat {
|
||||
if !scatter {
|
||||
for (a, (lo, hi)) in lo.iter_mut().zip(hi.iter_mut()).enumerate() {
|
||||
self.extend(c, a, (lo, hi));
|
||||
}
|
||||
} else {
|
||||
for s in (0..self.kinds.len()).step_by(2) {
|
||||
if let (Some(y), Some(x)) = (self.cell(c, s), self.cell(c, s + 1)) {
|
||||
hi[0] = hi[0].max(y);
|
||||
lo[0] = lo[0].min(y);
|
||||
xlo = xlo.min(x);
|
||||
xhi = xhi.max(x);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
(lo, hi, xlo, xhi)
|
||||
}
|
||||
|
||||
/// Widen the range of axis `a` by category `c`'s values.
|
||||
fn extend(&self, c: usize, a: usize, (lo, hi): (&mut f64, &mut f64)) {
|
||||
let val = |s: usize| self.cell(c, s).unwrap_or(0.0);
|
||||
let on = |s: &usize, kinds: &[GraphKind]| self.axis(*s) == a && self.kinds.get(*s).is_some_and(|k| kinds.contains(k));
|
||||
// Stacked columns (or bars) stack together, and so do areas; other series count one value each.
|
||||
for stack in [[GraphKind::StackedColumn, GraphKind::StackedBar], [GraphKind::Area, GraphKind::Area]] {
|
||||
let members = || (0..self.kinds.len()).filter(|s| on(s, &stack));
|
||||
*hi = hi.max(members().map(|s| val(s).max(0.0)).sum());
|
||||
*lo = lo.min(members().map(|s| val(s).min(0.0)).sum());
|
||||
}
|
||||
let single = |s: &usize| on(s, &[GraphKind::Column, GraphKind::Bar, GraphKind::Line]);
|
||||
for v in (0..self.kinds.len()).filter(single).filter_map(|s| self.cell(c, s)) {
|
||||
*hi = hi.max(v);
|
||||
*lo = lo.min(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The tick values `g`'s value axes are drawn with while they are calculated from the data (Graph Type › Tick Values
|
||||
/// without Override Calculated Values): the least value, the greatest and the number of divisions of the left (or
|
||||
/// only) axis, then of the right axis' own scale, which is the left one's unless Separate Scales gives the series on
|
||||
/// the right axis a scale of their own. A pie graph has no value axis and gives the axis of a graph without data. A
|
||||
/// single bound the graph has (only a minimum or only a maximum) is calculated with, as the axis is drawn.
|
||||
pub fn calculated_axes(g: &GraphSpec) -> [(f64, f64, usize); 2] {
|
||||
// Adding 0 makes a negative zero, which a nice axis around 0 can start at, a plain 0.
|
||||
let divisions = |(lo, hi, step): (f64, f64, f64)| (lo + 0.0, hi + 0.0, ((hi - lo) / step).round().clamp(1.0, 100.0) as usize);
|
||||
// The bounds the axis is calculated with: all but a pair that overrides the calculation.
|
||||
let partial = |min: Option<f64>, max: Option<f64>| match (min, max) {
|
||||
(Some(a), Some(b)) if b > a && (b - a).is_finite() => (None, None),
|
||||
bounds => bounds,
|
||||
};
|
||||
let (min, max) = partial(g.axis_min, g.axis_max);
|
||||
if g.kind == GraphKind::Radar {
|
||||
let top = g.rows.iter().flatten().copied().fold(0.0, f64::max);
|
||||
return [divisions(value_axis(g.ticks, min, max, 0.0, top)); 2];
|
||||
}
|
||||
let nser = g.rows.iter().map(Vec::len).max().unwrap_or(0).clamp(1, vectorcraft_doc::MAX_GRAPH_SERIES);
|
||||
let kinds: Vec<GraphKind> = (0..nser).map(|s| g.series_kind(s)).collect();
|
||||
let (scatter, horizontal) = (g.kind == GraphKind::Scatter, matches!(g.kind, GraphKind::Bar | GraphKind::StackedBar));
|
||||
let separate = g.separate_scales && g.value_axis == ValueAxisSide::Both && !horizontal && !scatter;
|
||||
let on_right: Vec<bool> = (0..nser).map(|s| separate && g.right_series.contains(&s)).collect();
|
||||
let cells = if g.kind == GraphKind::Pie { vec![] } else { g.cells() };
|
||||
let ncat = g.rows.len().clamp(1, vectorcraft_doc::MAX_GRAPH_CATEGORIES);
|
||||
let (lo, hi, ..) = Values { kinds: &kinds, cells: &cells, on_right: &on_right, ncat }.range(scatter);
|
||||
let left = divisions(value_axis(g.ticks, min, max, lo[0], hi[0]));
|
||||
let used = |right: bool| on_right.contains(&right);
|
||||
if !used(true) {
|
||||
return [left; 2];
|
||||
}
|
||||
let (right_min, right_max) = partial(g.right_axis_min, g.right_axis_max);
|
||||
let right = divisions(value_axis(g.right_ticks, right_min, right_max, lo[1], hi[1]));
|
||||
if used(false) { [left, right] } else { [right; 2] }
|
||||
}
|
||||
|
||||
/// One graph being generated: its data, the nodes drawn so far and what the legend and shadows still need.
|
||||
struct Plot<'a> {
|
||||
g: &'a GraphSpec,
|
||||
@@ -198,7 +293,7 @@ fn bar_rect(horizontal: bool, a: f64, w: f64, v0: f64, v1: f64) -> Rect {
|
||||
}
|
||||
|
||||
/// White text on a dark wedge.
|
||||
fn is_dark(fill: &Paint) -> bool {
|
||||
pub(super) fn is_dark(fill: &Paint) -> bool {
|
||||
fill.color().is_some_and(|c| {
|
||||
let [r, g, b] = c.to_rgb();
|
||||
0.2126 * r + 0.7152 * g + 0.0722 * b < 0.5
|
||||
@@ -526,41 +621,7 @@ impl<'a> Plot<'a> {
|
||||
|
||||
/// The value range per axis (stacked graphs stack positives and negatives separately), and a scatter's x range.
|
||||
fn value_range(&self, geo: &Geo, scatter: bool) -> ([f64; 2], [f64; 2], f64, f64) {
|
||||
let (mut lo, mut hi) = ([0.0f64; 2], [0.0f64; 2]);
|
||||
let (mut xlo, mut xhi) = (f64::MAX, f64::MIN);
|
||||
for c in 0..self.ncat {
|
||||
if !scatter {
|
||||
for (a, (lo, hi)) in lo.iter_mut().zip(hi.iter_mut()).enumerate() {
|
||||
self.extend_range(geo, c, a, (lo, hi));
|
||||
}
|
||||
} else {
|
||||
for s in (0..self.nser).step_by(2) {
|
||||
if let (Some(y), Some(x)) = (self.cell(c, s), self.cell(c, s + 1)) {
|
||||
hi[0] = hi[0].max(y);
|
||||
lo[0] = lo[0].min(y);
|
||||
xlo = xlo.min(x);
|
||||
xhi = xhi.max(x);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
(lo, hi, xlo, xhi)
|
||||
}
|
||||
|
||||
/// Widen the range of axis `a` by category `c`'s values.
|
||||
fn extend_range(&self, geo: &Geo, c: usize, a: usize, (lo, hi): (&mut f64, &mut f64)) {
|
||||
let nser = self.nser;
|
||||
// Stacked columns (or bars) stack together, and so do areas; other series count one value each.
|
||||
for stack in [[GraphKind::StackedColumn, GraphKind::StackedBar], [GraphKind::Area, GraphKind::Area]] {
|
||||
let members = || (0..nser).filter(|s| geo.axis(*s) == a && stack.contains(&self.kind(*s)));
|
||||
*hi = hi.max(members().map(|s| self.val(c, s).max(0.0)).sum());
|
||||
*lo = lo.min(members().map(|s| self.val(c, s).min(0.0)).sum());
|
||||
}
|
||||
let single = |s: &usize| geo.axis(*s) == a && matches!(self.kind(*s), GraphKind::Column | GraphKind::Bar | GraphKind::Line);
|
||||
for v in (0..nser).filter(single).filter_map(|s| self.cell(c, s)) {
|
||||
*hi = hi.max(v);
|
||||
*lo = lo.min(v);
|
||||
}
|
||||
Values { kinds: &self.kinds, cells: &self.cells, on_right: &geo.on_right, ncat: self.ncat }.range(scatter)
|
||||
}
|
||||
|
||||
/// The value axes with ticks and labels, the legend's start after them, and the axis lines.
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
use vectorcraft_color::BlendMode;
|
||||
use vectorcraft_geom::Shape;
|
||||
|
||||
use super::axis::radar_axis;
|
||||
use super::labels::{Role, filled_lines_on, label_para, label_style};
|
||||
use super::{Arc, CharStyle, Color, Document, GraphKind, GraphSpec, HashMap, Node, NodeId, NodeKind, Paint, Rect, Result, Session, Value, bad};
|
||||
use super::generate::is_dark;
|
||||
use super::labels::{Role, filled_lines_on, label_para, label_size, label_style};
|
||||
use super::{
|
||||
Affine, Arc, CharStyle, Color, Document, GraphKind, GraphSpec, HashMap, Node, NodeId, NodeKind, Paint, Rect, Result, Session, Value, bad,
|
||||
refresh_bounds,
|
||||
};
|
||||
|
||||
// ---------- generation ----------
|
||||
|
||||
@@ -639,35 +644,460 @@ fn graph_labels(doc: &Document) -> HashMap<NodeId, (NodeId, Role)> {
|
||||
let mut out = HashMap::new();
|
||||
doc.walk(|n| {
|
||||
let Some(g) = n.extras().graph.as_deref() else { return };
|
||||
for c in n.children().into_iter().flatten() {
|
||||
match (&c.kind, c.name.as_deref(), c.extras().series_index) {
|
||||
(NodeKind::Text(_), _, _) if g.kind == GraphKind::Pie => {
|
||||
out.insert(c.id, (n.id, Role::Category));
|
||||
}
|
||||
(NodeKind::Group { .. }, Some("Legend"), None) => {
|
||||
for t in c.children().into_iter().flatten().filter(|t| matches!(t.kind, NodeKind::Text(_))) {
|
||||
out.insert(t.id, (n.id, Role::Legend));
|
||||
}
|
||||
}
|
||||
(NodeKind::Group { .. }, Some("Axes"), None) => {
|
||||
let texts: Vec<NodeId> =
|
||||
c.children().into_iter().flatten().filter(|t| matches!(t.kind, NodeKind::Text(_))).map(|t| t.id).collect();
|
||||
let cats = match g.kind {
|
||||
GraphKind::Scatter => 0,
|
||||
GraphKind::Radar => texts.len(),
|
||||
_ => g.categories.iter().take(g.rows.len().max(1)).filter(|c| !c.is_empty()).count().min(texts.len()),
|
||||
};
|
||||
for (i, t) in texts.iter().enumerate() {
|
||||
out.insert(*t, (n.id, if i + cats >= texts.len() { Role::Category } else { Role::Value }));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
for (id, role) in own_labels(n, g) {
|
||||
out.insert(id, (n.id, role));
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// The generated labels of graph `n` (with spec `g`) and what each shows, as [`graph_labels`] finds them.
|
||||
fn own_labels(n: &Node, g: &GraphSpec) -> Vec<(NodeId, Role)> {
|
||||
let mut out = vec![];
|
||||
for c in n.children().into_iter().flatten() {
|
||||
match (&c.kind, c.name.as_deref(), c.extras().series_index) {
|
||||
(NodeKind::Text(_), _, _) if g.kind == GraphKind::Pie => {
|
||||
out.push((c.id, Role::Category));
|
||||
}
|
||||
(NodeKind::Group { .. }, Some("Legend"), None) => {
|
||||
for t in c.children().into_iter().flatten().filter(|t| matches!(t.kind, NodeKind::Text(_))) {
|
||||
out.push((t.id, Role::Legend));
|
||||
}
|
||||
}
|
||||
(NodeKind::Group { .. }, Some("Axes"), None) => {
|
||||
let texts: Vec<NodeId> = c.children().into_iter().flatten().filter(|t| matches!(t.kind, NodeKind::Text(_))).map(|t| t.id).collect();
|
||||
let cats = match g.kind {
|
||||
GraphKind::Scatter => 0,
|
||||
GraphKind::Radar => texts.len(),
|
||||
_ => g.categories.iter().take(g.rows.len().max(1)).filter(|c| !c.is_empty()).count().min(texts.len()),
|
||||
};
|
||||
for (i, t) in texts.iter().enumerate() {
|
||||
out.push((*t, if i + cats >= texts.len() { Role::Category } else { Role::Value }));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Set the labels of graph node `n` (a copy outside any document) in a new graph's label formats: the character and
|
||||
/// paragraph formats the graph keeps for them are dropped, with the mark that its legend labels' fill is their own, and
|
||||
/// each label takes its kind's default character style, unscaled (keeping its rotation), and default paragraph
|
||||
/// attributes, keeping its alignment and where it starts. A pie's legend label on a dark wedge is white, as a redraw
|
||||
/// sets it. Every other object in the graph goes to `other`. The rest of the graph's art, and what its labels say, stay
|
||||
/// as they are.
|
||||
pub(crate) fn plain_labels(n: &mut Node, other: &dyn Fn(&mut Node)) {
|
||||
fn plain(l: &mut vectorcraft_doc::LabelStyles) {
|
||||
(l.values, l.categories, l.legend) = (None, None, None);
|
||||
(l.values_para, l.categories_para, l.legend_para) = (None, None, None);
|
||||
l.legend_fill_set = false;
|
||||
}
|
||||
// Which legend labels a redraw sets on a dark wedge, read while the labels are as the graph drew them.
|
||||
let on_dark = match n.extras().graph.as_deref() {
|
||||
Some(g) if g.kind == GraphKind::Pie && g.legend && g.pie_legend_in_wedges => {
|
||||
let mut redraw = g.clone();
|
||||
plain(&mut redraw.label_styles);
|
||||
redrawn_on_dark(n, &redraw).unwrap_or_else(|| legend_on_dark(n, g))
|
||||
}
|
||||
_ => HashMap::new(),
|
||||
};
|
||||
let Some(g) = n.extras_if_any().and_then(|e| e.graph.as_deref_mut()) else { return };
|
||||
plain(&mut g.label_styles);
|
||||
let Some(g) = n.extras().graph.as_deref() else { return };
|
||||
let roles: HashMap<NodeId, Role> = own_labels(n, g).into_iter().collect();
|
||||
struct Plain<'a> {
|
||||
roles: HashMap<NodeId, Role>,
|
||||
other: &'a dyn Fn(&mut Node),
|
||||
}
|
||||
fn visit(c: &mut Node, p: &Plain) {
|
||||
let role = p.roles.get(&c.id).copied();
|
||||
if let (Some(role), NodeKind::Text(t)) = (role, &mut c.kind) {
|
||||
let plain = vectorcraft_doc::LabelStyles::default();
|
||||
let justify = t.para_at(0).justify;
|
||||
let text = t.plain_text();
|
||||
t.runs = vec![vectorcraft_doc::TextRun { text, style: label_style(&plain, role), inline: None }];
|
||||
let mut para = label_para(&plain, role);
|
||||
para.justify = justify;
|
||||
t.set_all_paras(para);
|
||||
// The label loses its scale and keeps its rotation (and a reflection), so it stays turned with the
|
||||
// rest of a rotated graph's art.
|
||||
let [a, b, c, d, _, _] = t.xf.as_coeffs();
|
||||
let flip = if a * d - b * c < 0.0 { Affine::scale_non_uniform(1.0, -1.0) } else { Affine::IDENTITY };
|
||||
t.xf = Affine::translate(t.xf.translation()) * Affine::rotate(b.atan2(a)) * flip;
|
||||
refresh_bounds(t);
|
||||
return;
|
||||
}
|
||||
// The Axes and Legend groups, and any other group of the graph's own, are looked through.
|
||||
if role.is_none() && matches!(c.kind, NodeKind::Group { .. }) && c.extras().graph.is_none() {
|
||||
for k in c.children_mut().into_iter().flatten() {
|
||||
visit(Arc::make_mut(k), p);
|
||||
}
|
||||
return;
|
||||
}
|
||||
(p.other)(c);
|
||||
}
|
||||
let p = Plain { roles, other };
|
||||
for c in n.children_mut().into_iter().flatten() {
|
||||
visit(Arc::make_mut(c), &p);
|
||||
}
|
||||
set_legend_fills(n, &on_dark);
|
||||
}
|
||||
|
||||
/// Give each legend label of graph `n` in `on_dark` white characters (`true`) or black ones.
|
||||
fn set_legend_fills(n: &mut Node, on_dark: &HashMap<NodeId, bool>) {
|
||||
if on_dark.is_empty() {
|
||||
return;
|
||||
}
|
||||
// The legend labels are in the graph's Legend group.
|
||||
for c in n.children_mut().into_iter().flatten() {
|
||||
if !c.children().into_iter().flatten().any(|t| on_dark.contains_key(&t.id)) {
|
||||
continue;
|
||||
}
|
||||
for t in Arc::make_mut(c).children_mut().into_iter().flatten() {
|
||||
let Some(dark) = on_dark.get(&t.id) else { continue };
|
||||
let fill = Paint::solid(if *dark { Color::WHITE } else { Color::BLACK });
|
||||
if matches!(&t.kind, NodeKind::Text(text) if text.runs.iter().all(|r| r.style.fill == fill)) {
|
||||
continue;
|
||||
}
|
||||
if let NodeKind::Text(text) = &mut Arc::make_mut(t).kind {
|
||||
text.runs.iter_mut().for_each(|r| r.style.fill = fill.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The legend labels of graph `n`: the type in its Legend group, as [`own_labels`] finds them.
|
||||
fn legend_labels(n: &Node) -> Vec<&Node> {
|
||||
legend_in(n.children().map_or(&[], |c| c.as_slice()))
|
||||
}
|
||||
|
||||
/// The type in the Legend group among a graph's `children`.
|
||||
fn legend_in(children: &[Arc<Node>]) -> Vec<&Node> {
|
||||
children
|
||||
.iter()
|
||||
.filter(|c| matches!(c.kind, NodeKind::Group { .. }) && c.name.as_deref() == Some("Legend") && c.extras().series_index.is_none())
|
||||
.flat_map(|c| c.children().into_iter().flatten())
|
||||
.map(|t| t.as_ref())
|
||||
.filter(|t| matches!(t.kind, NodeKind::Text(_)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A pie wedge: its series, its outline and whether the fill it shows is dark.
|
||||
struct Wedge {
|
||||
series: u32,
|
||||
bounds: vectorcraft_geom::Rect,
|
||||
path: vectorcraft_geom::BezPath,
|
||||
dark: bool,
|
||||
}
|
||||
|
||||
/// The wedges of pie `n` (the paths of its series groups), in paint order.
|
||||
fn pie_wedges(n: &Node) -> Vec<Wedge> {
|
||||
wedges_in(n.children().map_or(&[], |c| c.as_slice()))
|
||||
}
|
||||
|
||||
/// The wedges among a pie's `children`, as [`pie_wedges`] finds them.
|
||||
fn wedges_in(children: &[Arc<Node>]) -> Vec<Wedge> {
|
||||
let mut wedges = vec![];
|
||||
for c in children {
|
||||
let Some(series) = c.extras().series_index else { continue };
|
||||
c.walk(&mut |m| {
|
||||
if let NodeKind::Path { path, .. } = &m.kind {
|
||||
let path = path.to_bezpath();
|
||||
wedges.push(Wedge { series, bounds: path.bounding_box(), path, dark: is_dark(&shown_paint(m, true).0) });
|
||||
}
|
||||
});
|
||||
}
|
||||
wedges
|
||||
}
|
||||
|
||||
/// The text of the label of each series of graph `g` in its wedges, with the series that show it (several when series
|
||||
/// share a name).
|
||||
fn series_by_label(g: &GraphSpec) -> HashMap<String, Vec<u32>> {
|
||||
let mut names: HashMap<String, Vec<u32>> = HashMap::new();
|
||||
for (s, name) in g.series.iter().enumerate() {
|
||||
if let Ok(s) = u32::try_from(s) {
|
||||
names.entry(name.replace('|', "\n")).or_default().push(s);
|
||||
}
|
||||
}
|
||||
names
|
||||
}
|
||||
|
||||
/// The legend labels of pie `n`, each with whether a redraw from spec `g` sets it on a dark wedge, by the fill each wedge
|
||||
/// of `n` shows now. The pie is drawn again apart from any document, which places each label in its wedge as `g` sets
|
||||
/// it and tells each label's series. Each redrawn wedge takes the fill of the wedge of `n` of its series with the same
|
||||
/// bounds, and each legend label of `n` is the nearest redrawn one with the same text, places measured in the bounds of
|
||||
/// all the wedges. `None` when a wedge or a label has no counterpart of its own, or a wedge out of its place in paint
|
||||
/// order has several (art or labels added, removed, edited or restyled since the pie was drawn).
|
||||
fn redrawn_on_dark(n: &Node, g: &GraphSpec) -> Option<HashMap<NodeId, bool>> {
|
||||
use vectorcraft_geom::kurbo::ParamCurveNearest;
|
||||
// Each series name that shows a label is drawn with a mark and its index after it, which moves no line, so each
|
||||
// redrawn label tells its series.
|
||||
const MARK: char = '\u{1f}';
|
||||
let mut marked = g.clone();
|
||||
for (s, name) in marked.series.iter_mut().enumerate() {
|
||||
if !super::labels::blank_label(name) {
|
||||
name.push(MARK);
|
||||
name.push_str(&s.to_string());
|
||||
}
|
||||
}
|
||||
let legend = legend_labels(n);
|
||||
let mut scratch = Document::new(1.0, 1.0);
|
||||
let art = super::generate::generate(&mut scratch, &marked);
|
||||
let redrawn = legend_in(&art);
|
||||
let now = pie_wedges(n);
|
||||
let mut wedges = wedges_in(&art);
|
||||
if redrawn.len() != legend.len() || wedges.len() != now.len() {
|
||||
return None;
|
||||
}
|
||||
// Places are measured in the bounds of all the wedges, since the pie may have been moved or resized since it was drawn.
|
||||
let frame = |ws: &[Wedge]| ws.iter().map(|w| w.bounds).reduce(|a, b| a.union(b));
|
||||
let (Some(was), Some(is)) = (frame(&wedges), frame(&now)) else { return None };
|
||||
let at = |f: vectorcraft_geom::Rect, p: vectorcraft_geom::Point| ((p.x - f.x0) / f.width().max(1e-9), (p.y - f.y0) / f.height().max(1e-9));
|
||||
let corners = |f: vectorcraft_geom::Rect, w: &Wedge| {
|
||||
let (a, b) = (at(f, vectorcraft_geom::Point::new(w.bounds.x0, w.bounds.y0)), at(f, vectorcraft_geom::Point::new(w.bounds.x1, w.bounds.y1)));
|
||||
[a.0, a.1, b.0, b.1]
|
||||
};
|
||||
// A wedge and a redrawn one are the same wedge when they show the same series with the same bounds. Wedges are
|
||||
// compared this many times in all, labels included; past it, nothing is matched.
|
||||
let mut budget: usize = 1 << 20;
|
||||
let mut copied_wedges: HashMap<u32, Vec<(usize, [f64; 4])>> = HashMap::new();
|
||||
for (k, w) in now.iter().enumerate() {
|
||||
copied_wedges.entry(w.series).or_default().push((k, corners(is, w)));
|
||||
}
|
||||
// The wedge in the same place in paint order when its bounds are the same, else the one of the series whose bounds
|
||||
// are nearest, when they are the same to within 0.001 of the whole; each copied wedge is matched once.
|
||||
let off = |c: &[f64; 4], d: &[f64; 4]| c.iter().zip(d).map(|(p, q)| (p - q).abs()).fold(0.0, f64::max);
|
||||
let mut used = vec![false; now.len()];
|
||||
let mut fills = Vec::with_capacity(wedges.len());
|
||||
for (i, r) in wedges.iter().enumerate() {
|
||||
let c = corners(was, r);
|
||||
let k = match now.get(i) {
|
||||
Some(w) if w.series == r.series && off(&c, &corners(is, w)) <= 1e-7 => i,
|
||||
_ => {
|
||||
let group = copied_wedges.get(&r.series)?;
|
||||
if budget < group.len() {
|
||||
return None;
|
||||
}
|
||||
budget -= group.len();
|
||||
let (k, d) = group.iter().map(|(k, d)| (*k, off(&c, d))).min_by(|a, b| a.1.total_cmp(&b.1))?;
|
||||
if d > 1e-3 {
|
||||
return None;
|
||||
}
|
||||
k
|
||||
}
|
||||
};
|
||||
if std::mem::replace(used.get_mut(k)?, true) {
|
||||
return None;
|
||||
}
|
||||
fills.push(now.get(k)?.dark);
|
||||
}
|
||||
for (r, dark) in wedges.iter_mut().zip(fills) {
|
||||
r.dark = dark;
|
||||
}
|
||||
// Each label's words and origin, in the frame of its pie's wedges.
|
||||
let place = |labels: &[&Node], f| {
|
||||
labels
|
||||
.iter()
|
||||
.map(|t| match &t.kind {
|
||||
NodeKind::Text(text) => Some((text.plain_text(), at(f, text.xf * vectorcraft_geom::Point::ORIGIN))),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Option<Vec<_>>>()
|
||||
};
|
||||
let (Some(copied), Some(mut drawn)) = (place(&legend, is), place(&redrawn, was)) else { return None };
|
||||
// The series of each redrawn label, and its words without the mark.
|
||||
let mut series = Vec::with_capacity(drawn.len());
|
||||
for (words, _) in &mut drawn {
|
||||
let (said, s) = words.rsplit_once(MARK)?;
|
||||
let s: usize = s.parse().ok()?;
|
||||
let name = g.series.get(s)?;
|
||||
if *said != name.replace('|', "\n") {
|
||||
return None;
|
||||
}
|
||||
series.push((s, name.as_str()));
|
||||
words.truncate(said.len());
|
||||
}
|
||||
// Each label is the nearest redrawn label that says the same, and no two labels are the same redrawn one.
|
||||
let mut same: HashMap<&str, Vec<usize>> = HashMap::new();
|
||||
for (j, (words, _)) in drawn.iter().enumerate() {
|
||||
same.entry(words.as_str()).or_default().push(j);
|
||||
}
|
||||
let mut taken = vec![false; drawn.len()];
|
||||
let mut matched = Vec::with_capacity(copied.len());
|
||||
for (words, p) in &copied {
|
||||
let group = same.get(words.as_str())?;
|
||||
if budget < group.len() {
|
||||
return None;
|
||||
}
|
||||
budget -= group.len();
|
||||
let away = |j: &usize| drawn.get(*j).map_or(f64::INFINITY, |(_, q)| (p.0 - q.0).powi(2) + (p.1 - q.1).powi(2));
|
||||
let j = *group.iter().min_by(|a, b| away(a).total_cmp(&away(b)))?;
|
||||
if std::mem::replace(taken.get_mut(j)?, true) {
|
||||
return None;
|
||||
}
|
||||
matched.push(j);
|
||||
}
|
||||
let mut by_series: HashMap<u32, Vec<&Wedge>> = HashMap::new();
|
||||
for w in &wedges {
|
||||
by_series.entry(w.series).or_default().push(w);
|
||||
}
|
||||
// A redraw puts the middle of a label's lines (its series name split at `|` and line breaks, at the default leading)
|
||||
// 0.35 of the label size below a point inside its wedge, at the label's origin across. The label is on the nearest
|
||||
// wedge of its series to that point, the one holding it. When the wedges of the series are all dark or all light, the
|
||||
// place does not matter.
|
||||
let uniform: HashMap<u32, Option<bool>> =
|
||||
by_series.iter().map(|(s, ws)| (*s, ws.first().map(|w| w.dark).filter(|d| ws.iter().all(|w| w.dark == *d)))).collect();
|
||||
let ls = label_size(&g.label_styles, Role::Legend);
|
||||
let mut out = HashMap::new();
|
||||
for (t, j) in legend.iter().zip(matched) {
|
||||
let (Some(r), Some((s, name))) = (redrawn.get(j), series.get(j).copied()) else { return None };
|
||||
let s = u32::try_from(s).ok()?;
|
||||
if let Some(Some(dark)) = uniform.get(&s) {
|
||||
out.insert(t.id, *dark);
|
||||
continue;
|
||||
}
|
||||
let NodeKind::Text(text) = &r.kind else { return None };
|
||||
let middle = name.split(['|', '\n']).count().saturating_sub(1) as f64 * ls * 1.2 / 2.0;
|
||||
let point = text.xf * vectorcraft_geom::Point::new(0.0, middle - ls * 0.35);
|
||||
let named = by_series.get(&s)?;
|
||||
if budget < named.len() {
|
||||
return None;
|
||||
}
|
||||
budget -= named.len();
|
||||
// The nearest wedge, measured exactly only while its bounds are nearer than the nearest one found so far.
|
||||
let to_box = |b: vectorcraft_geom::Rect| {
|
||||
let (dx, dy) = ((b.x0 - point.x).max(point.x - b.x1).max(0.0), (b.y0 - point.y).max(point.y - b.y1).max(0.0));
|
||||
dx * dx + dy * dy
|
||||
};
|
||||
let away = |w: &Wedge| {
|
||||
if w.path.contains(point) { 0.0 } else { w.path.segments().map(|seg| seg.nearest(point, 1e-3).distance_sq).fold(f64::INFINITY, f64::min) }
|
||||
};
|
||||
let mut by_box: Vec<(f64, &Wedge)> = named.iter().map(|w| (to_box(w.bounds), *w)).collect();
|
||||
by_box.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let mut best: Option<(f64, bool)> = None;
|
||||
for (near, w) in by_box {
|
||||
if best.is_some_and(|b| near >= b.0) {
|
||||
break;
|
||||
}
|
||||
let d = away(w);
|
||||
if best.is_none_or(|b| d < b.0) {
|
||||
best = Some((d, w.dark));
|
||||
}
|
||||
}
|
||||
out.insert(t.id, best?.1);
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// The legend labels of graph `n` (a pie with Legends in Wedges, its labels where it drew them), each with whether a
|
||||
/// redraw sets it on a dark wedge, by the fill each wedge shows now. A label is placed by the point a redraw centers it
|
||||
/// on, which lies inside its wedge: the wedge holding it of the series the label names (the nearest one when none holds
|
||||
/// it), or of any series when the label names none. When the wedges of the series a label names are all dark or all
|
||||
/// light, the label's place does not matter.
|
||||
fn legend_on_dark(n: &Node, g: &GraphSpec) -> HashMap<NodeId, bool> {
|
||||
wedge_contrast(&legend_labels(n), &pie_wedges(n), g)
|
||||
}
|
||||
|
||||
/// The point a redraw centers legend label `text` of series `name` on, in a pie of spec `g` whose legend labels are
|
||||
/// `ls` points: 0.35 of the label size above where a redraw (`label` in `labels.rs`) puts the middle of the label's
|
||||
/// lines, at the label's origin across. The lines are those of the series name, split at `|` and line breaks, at the
|
||||
/// default leading; with kept paragraph attributes, a redraw puts the middle of the first and last baselines there
|
||||
/// instead, when each of those lines that holds characters has one baseline and the first and last hold characters.
|
||||
fn label_anchor(text: &vectorcraft_doc::TextObject, name: &str, g: &GraphSpec, ls: f64) -> vectorcraft_geom::Point {
|
||||
let lines: Vec<&str> = name.split(['|', '\n']).collect();
|
||||
let ys: Vec<f64> = text.baselines().map(|(a, _)| a.y).collect();
|
||||
let set = lines.iter().filter(|l| !l.is_empty()).count();
|
||||
let ends_set = lines.first().is_some_and(|l| !l.is_empty()) && lines.last().is_some_and(|l| !l.is_empty());
|
||||
let middle = match (ys.first(), ys.last()) {
|
||||
(Some(first), Some(last)) if g.label_styles.legend_para.is_some() && ends_set && ys.len() == set => (first + last) / 2.0,
|
||||
_ => lines.len().saturating_sub(1) as f64 * ls * 1.2 / 2.0,
|
||||
};
|
||||
text.xf * vectorcraft_geom::Point::new(0.0, middle - ls * 0.35)
|
||||
}
|
||||
|
||||
/// [`legend_on_dark`] for legend labels `legend` of a pie of spec `g` with wedges `wedges`.
|
||||
fn wedge_contrast(legend: &[&Node], wedges: &[Wedge], g: &GraphSpec) -> HashMap<NodeId, bool> {
|
||||
use vectorcraft_geom::kurbo::ParamCurveNearest;
|
||||
let mut out = HashMap::new();
|
||||
if legend.is_empty() {
|
||||
return out;
|
||||
}
|
||||
let mut by_series: HashMap<u32, Vec<&Wedge>> = HashMap::new();
|
||||
for w in wedges {
|
||||
by_series.entry(w.series).or_default().push(w);
|
||||
}
|
||||
// For each label text, the wedges of the series that show it, and how many of them are dark.
|
||||
let named_wedges: HashMap<String, (Vec<&Wedge>, usize)> = series_by_label(g)
|
||||
.into_iter()
|
||||
.map(|(name, series)| {
|
||||
let named: Vec<&Wedge> = series.iter().filter_map(|s| by_series.get(s)).flatten().copied().collect();
|
||||
let darks = named.iter().filter(|w| w.dark).count();
|
||||
(name, (named, darks))
|
||||
})
|
||||
.collect();
|
||||
let none = (vec![], 0);
|
||||
// For each label text, the first series name that shows it (names that differ only in `|` against a line break of
|
||||
// their own show the same text, and nothing in the label tells them apart).
|
||||
let mut series_names: HashMap<String, &str> = HashMap::new();
|
||||
for name in &g.series {
|
||||
series_names.entry(name.replace('|', "\n")).or_insert(name.as_str());
|
||||
}
|
||||
let ls = label_size(&g.label_styles, Role::Legend);
|
||||
// The search for the nearest wedge looks at this many wedges in all; past it, a label takes the contrast most of the
|
||||
// wedges of its series show.
|
||||
let mut budget: usize = 1 << 20;
|
||||
for t in legend {
|
||||
let NodeKind::Text(text) = &t.kind else { continue };
|
||||
let id = t.id;
|
||||
let words = text.plain_text();
|
||||
let (named, darks) = named_wedges.get(&words).unwrap_or(&none);
|
||||
let darks = *darks;
|
||||
if (darks == 0 || darks == named.len())
|
||||
&& let Some(w) = named.first()
|
||||
{
|
||||
out.insert(id, w.dark);
|
||||
continue;
|
||||
}
|
||||
let name = series_names.get(&words).map_or_else(|| words.replace('\n', "|"), |s| (*s).to_owned());
|
||||
let at = label_anchor(text, &name, g, ls);
|
||||
if named.is_empty() {
|
||||
let cost = wedges.len();
|
||||
let dark = budget >= cost && wedges.iter().any(|w| w.dark && w.bounds.contains(at) && w.path.contains(at));
|
||||
budget = budget.saturating_sub(cost);
|
||||
out.insert(id, dark);
|
||||
continue;
|
||||
}
|
||||
if budget < named.len() {
|
||||
out.insert(id, darks * 2 > named.len());
|
||||
continue;
|
||||
}
|
||||
budget -= named.len();
|
||||
// The nearest wedge, measured exactly only while its bounds are nearer than the nearest one found so far.
|
||||
let to_box = |r: vectorcraft_geom::Rect| {
|
||||
let (dx, dy) = ((r.x0 - at.x).max(at.x - r.x1).max(0.0), (r.y0 - at.y).max(at.y - r.y1).max(0.0));
|
||||
dx * dx + dy * dy
|
||||
};
|
||||
let away = |w: &Wedge| {
|
||||
if w.path.contains(at) { 0.0 } else { w.path.segments().map(|s| s.nearest(at, 1e-3).distance_sq).fold(f64::INFINITY, f64::min) }
|
||||
};
|
||||
let mut by_box: Vec<(f64, &Wedge)> = named.iter().map(|w| (to_box(w.bounds), *w)).collect();
|
||||
by_box.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let mut best = (f64::INFINITY, darks * 2 > named.len());
|
||||
for (near, w) in by_box {
|
||||
if near >= best.0 {
|
||||
break;
|
||||
}
|
||||
let d = away(w);
|
||||
if d < best.0 {
|
||||
best = (d, w.dark);
|
||||
}
|
||||
}
|
||||
out.insert(id, best.1);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Keep the anti-aliasing method `method` given to graph labels `ids` for every label of their kind, as
|
||||
/// [`capture_label_styles`] keeps a formatting change. Returns whether a kept method changed.
|
||||
pub(crate) fn capture_label_anti_alias(doc: &mut Document, ids: &[NodeId], method: vectorcraft_doc::text::TypeAntiAlias) -> bool {
|
||||
|
||||
@@ -869,6 +869,188 @@ fn aligned_rows_of_a_graph_designs_art_and_a_different_stack_are_not_moved() {
|
||||
assert_eq!(paints, [art_was.items[1].paint().clone(), art_was.items[0].paint().clone(), art_was.items[1].paint().clone()]);
|
||||
}
|
||||
|
||||
/// An `item` given with `aligned: true` and the art of a graph design in a series first is a row of the art's stack in the
|
||||
/// paint and stroke commands: each other object edits the row equal to it, and a row the art does not have as a fill or
|
||||
/// stroke as edited, or that no other object has, is an error that leaves the document and its undo history as they are.
|
||||
#[test]
|
||||
fn aligned_paint_rows_of_a_graph_designs_art_edit_the_equal_rows_of_the_other_objects() {
|
||||
let rows = |s: &Session, id: NodeId| (*s.doc().unwrap().doc.node(id).unwrap().appearance).clone();
|
||||
let green = Paint::solid(vectorcraft_color::Color::rgb(0.0, 1.0, 0.0));
|
||||
// The art's row 1 is the blue fill the mark has as row 0, and its row 2 the black stroke the mark has as row 1.
|
||||
let (mut s, _, art, mark) = aligned_design_art();
|
||||
let black = rows(&s, mark).items[1].clone();
|
||||
s.edit("Stroke", |d, _| {
|
||||
d.node_mut(art).unwrap().appearance.items.push(black.clone());
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let (art_was, mark_was) = (rows(&s, art), rows(&s, mark));
|
||||
let fill = |s: &mut Session, cmd: &str, p: serde_json::Value| {
|
||||
s.execute(cmd, &p).unwrap();
|
||||
let now = rows(s, mark);
|
||||
assert_eq!(rows(s, art), art_was, "{cmd}");
|
||||
assert_ne!(now.items[0], mark_was.items[0], "{cmd} edits the mark's blue fill");
|
||||
assert_eq!(now.items[1], mark_was.items[1], "{cmd} leaves the mark's stroke");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(rows(s, mark), mark_was, "{cmd} is one undo step");
|
||||
now
|
||||
};
|
||||
let ids = [art.0, mark.0];
|
||||
let now = fill(&mut s, "paint.setFill", json!({"ids": ids, "item": 1, "aligned": true, "color": "#00ff00"}));
|
||||
assert_eq!(now.items[0].paint(), &green);
|
||||
let now = fill(&mut s, "paint.invert", json!({"ids": ids, "item": 1, "aligned": true}));
|
||||
assert_eq!(Some(s.last_solid), now.items[0].paint().color(), "the inverted color is the last color, not the art's");
|
||||
let now = fill(&mut s, "paint.lastColor", json!({"ids": ids, "item": 1, "aligned": true, "stroke": false}));
|
||||
assert_eq!(Some(s.last_solid), now.items[0].paint().color());
|
||||
// Without `aligned`, the art is left out and the item is a row of the mark.
|
||||
let now = fill(&mut s, "paint.invert", json!({"ids": ids, "item": 0}));
|
||||
assert_eq!(Some(s.last_solid), now.items[0].paint().color(), "the mark's inverted color is the last color, not the art's");
|
||||
s.last_solid = vectorcraft_color::Color::rgb(0.5, 0.5, 0.5);
|
||||
let now = fill(&mut s, "paint.complement", json!({"ids": ids, "item": 0}));
|
||||
assert_eq!(Some(s.last_solid), now.items[0].paint().color(), "the mark's complement is the last color, not the art's");
|
||||
let now = fill(&mut s, "paint.editGradient", json!({"ids": ids, "item": 1, "aligned": true, "kind": "linear"}));
|
||||
let Paint::Gradient(g) = now.items[0].paint() else { panic!("{:?}", now.items[0].paint()) };
|
||||
assert_eq!(&s.last_gradient, &**g, "the mark's new gradient is the last gradient");
|
||||
let now = fill(&mut s, "paint.lastGradient", json!({"ids": ids, "item": 1, "aligned": true, "stroke": false}));
|
||||
assert!(matches!(now.items[0].paint(), Paint::Gradient(_)));
|
||||
|
||||
let stroke = |s: &mut Session, cmd: &str, p: serde_json::Value| {
|
||||
s.execute(cmd, &p).unwrap();
|
||||
let now = rows(s, mark);
|
||||
assert_eq!(rows(s, art), art_was, "{cmd}");
|
||||
assert_eq!(now.items[0], mark_was.items[0], "{cmd} leaves the mark's fill");
|
||||
assert_ne!(now.items[1], mark_was.items[1], "{cmd} edits the mark's stroke");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(rows(s, mark), mark_was, "{cmd} is one undo step");
|
||||
now
|
||||
};
|
||||
let now = stroke(&mut s, "paint.setStroke", json!({"ids": ids, "item": 2, "aligned": true, "color": "#00ff00"}));
|
||||
assert_eq!(now.items[1].paint(), &green);
|
||||
let now = stroke(&mut s, "stroke.set", json!({"ids": ids, "item": 2, "aligned": true, "weight": 5}));
|
||||
assert_eq!(now.stroke_at(Some(1)).unwrap().width, 5.0);
|
||||
let now = stroke(&mut s, "stroke.setAdvanced", json!({"ids": ids, "item": 2, "aligned": true, "arrowScale": [200, 200]}));
|
||||
assert_eq!(now.stroke_at(Some(1)).unwrap().arrow_scale, (200.0, 200.0));
|
||||
// Without `stroke`, the kind of the art's row is edited.
|
||||
let now = stroke(&mut s, "paint.editGradient", json!({"ids": ids, "item": 2, "aligned": true, "kind": "linear"}));
|
||||
assert!(matches!(now.items[1].paint(), Paint::Gradient(_)));
|
||||
fill(&mut s, "paint.complement", json!({"ids": ids, "item": 1, "aligned": true, "stroke": false}));
|
||||
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
for (cmd, p, said) in [
|
||||
("stroke.set", json!({"ids": ids, "item": 1, "aligned": true, "weight": 5}), "appearance item 1 is not a stroke"),
|
||||
("paint.setFill", json!({"ids": ids, "item": 2, "aligned": true, "color": "#00ff00"}), "appearance item 2 is not a fill"),
|
||||
("paint.setFill", json!({"ids": ids, "item": 0, "aligned": true, "color": "#00ff00"}), "no appearance item 0"),
|
||||
("paint.setFill", json!({"ids": ids, "item": 9, "aligned": true, "color": "#00ff00"}), "no appearance item 9"),
|
||||
// The art alone: no other object has the row.
|
||||
("paint.setFill", json!({"ids": [art.0], "item": 9, "aligned": true, "color": "#00ff00"}), "no appearance item 9"),
|
||||
("paint.setFill", json!({"ids": [art.0], "item": 1, "aligned": true, "color": "#00ff00"}), "no appearance item 1"),
|
||||
("stroke.set", json!({"ids": [art.0], "item": 1, "aligned": true, "weight": 5}), "appearance item 1 is not a stroke"),
|
||||
("paint.editGradient", json!({"ids": [art.0], "item": 1, "aligned": true, "kind": "linear"}), "no appearance item 1"),
|
||||
// The weight steps take no row: they step each object's active or top stroke.
|
||||
("stroke.weightUp", json!({"ids": ids, "item": 2}), "unknown parameter `item`"),
|
||||
("stroke.weightUp", json!({"ids": ids, "aligned": true}), "unknown parameter `aligned`"),
|
||||
("stroke.weightDown", json!({"ids": ids, "item": 2}), "unknown parameter `item`"),
|
||||
("stroke.weightDown", json!({"ids": ids, "aligned": true}), "unknown parameter `aligned`"),
|
||||
] {
|
||||
let defaults = format!("{:?}", (&s.paint.fill, &s.paint.stroke, &s.last_gradient));
|
||||
let e = s.execute(cmd, &p).unwrap_err().to_string();
|
||||
assert!(e.contains(said), "{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}");
|
||||
assert_eq!(format!("{:?}", (&s.paint.fill, &s.paint.stroke, &s.last_gradient)), defaults, "{cmd}");
|
||||
}
|
||||
|
||||
// An object with no row equal to the art's is left out of what the commands report as edited.
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
|
||||
let rect = *s.doc().unwrap().selection.subjects().first().unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [rect.0], "color": "#ff00ff"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#ff00ff"})).unwrap();
|
||||
let rect_was = rows(&s, rect);
|
||||
let ids = [art.0, mark.0, rect.0];
|
||||
for (cmd, p, key, said) in [
|
||||
("paint.setFill", json!({"ids": ids, "item": 1, "aligned": true, "color": "#00ff00"}), "objects", json!(1)),
|
||||
("stroke.set", json!({"ids": ids, "item": 2, "aligned": true, "weight": 5}), "objects", json!(1)),
|
||||
("paint.editGradient", json!({"ids": ids, "item": 1, "aligned": true, "kind": "linear"}), "ids", json!([mark.0])),
|
||||
("paint.setGradientGeom", json!({"ids": ids, "item": 1, "aligned": true, "start": [0, 0], "end": [10, 40]}), "ids", json!([mark.0])),
|
||||
] {
|
||||
if cmd == "paint.setGradientGeom" {
|
||||
s.execute("paint.editGradient", &json!({"ids": [mark.0], "item": 0, "kind": "linear"})).unwrap();
|
||||
let gradient = rows(&s, mark).items[0].clone();
|
||||
s.edit("Gradient", |d, _| {
|
||||
d.node_mut(art).unwrap().appearance.items[1] = gradient.clone();
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
let r = s.execute(cmd, &p).unwrap();
|
||||
assert_eq!(r[key], said, "{cmd}: {r}");
|
||||
assert_eq!(rows(&s, rect), rect_was, "{cmd}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
|
||||
// A gradient spanning the selection spans only the objects that take it: a distant object without an equal row does
|
||||
// not move it.
|
||||
s.execute("shape.rectangle", &json!({"x": 5000, "y": 5000, "width": 10, "height": 10})).unwrap();
|
||||
let far = *s.doc().unwrap().selection.subjects().first().unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [far.0], "color": "#ff00ff"})).unwrap();
|
||||
let far_was = rows(&s, far);
|
||||
let gradient = json!({"stops": [{"offset": 0, "color": "#000000"}, {"offset": 1, "color": "#ffffff"}]});
|
||||
let mut placed = Vec::new();
|
||||
for ids in [vec![art.0, mark.0], vec![art.0, mark.0, far.0]] {
|
||||
s.execute("paint.setFill", &json!({"ids": ids, "item": 1, "aligned": true, "gradient": gradient, "span": "selection"})).unwrap();
|
||||
placed.push(rows(&s, mark).items[0].clone());
|
||||
assert_eq!(rows(&s, far), far_was);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
assert!(matches!(placed[0].paint(), Paint::Gradient(_)));
|
||||
assert_eq!(placed[1], placed[0]);
|
||||
}
|
||||
|
||||
/// The gradient and freeform gradient commands read an `item` given with `aligned: true` and the art of a graph design in
|
||||
/// a series first as a row of the art's stack, as the paint commands do.
|
||||
#[test]
|
||||
fn aligned_gradient_rows_of_a_graph_designs_art_edit_the_equal_rows_of_the_other_objects() {
|
||||
let rows = |s: &Session, id: NodeId| (*s.doc().unwrap().doc.node(id).unwrap().appearance).clone();
|
||||
for kind in ["linear", "freeform"] {
|
||||
let (mut s, _, art, mark) = aligned_design_art();
|
||||
// The mark's fill and the art's equal row become the same gradient.
|
||||
s.execute("paint.editGradient", &json!({"ids": [mark.0], "item": 0, "kind": kind})).unwrap();
|
||||
let gradient = rows(&s, mark).items[0].clone();
|
||||
// A yellow fill above the mark's gradient is the mark's row 1, as the gradient is the art's row 1.
|
||||
let mut yellow = gradient.clone();
|
||||
*yellow.paint_mut() = Paint::solid(vectorcraft_color::Color::rgb(1.0, 1.0, 0.0));
|
||||
s.edit("Gradient", |d, _| {
|
||||
d.node_mut(art).unwrap().appearance.items[1] = gradient.clone();
|
||||
d.node_mut(mark).unwrap().appearance.items.insert(1, yellow.clone());
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let ids = [art.0, mark.0];
|
||||
let edits = if kind == "linear" {
|
||||
vec![
|
||||
("paint.setGradientGeom", json!({"ids": ids, "item": 1, "aligned": true, "start": [0, 0], "end": [10, 40]})),
|
||||
("paint.editGradient", json!({"ids": ids, "item": 1, "aligned": true, "kind": "radial"})),
|
||||
]
|
||||
} else {
|
||||
vec![("paint.freeform.addPoint", json!({"ids": ids, "item": 1, "aligned": true, "at": [5, 5]}))]
|
||||
};
|
||||
for (cmd, p) in edits {
|
||||
let (art_was, mark_was) = (rows(&s, art), rows(&s, mark));
|
||||
s.execute(cmd, &p).unwrap();
|
||||
let now = rows(&s, mark);
|
||||
assert_eq!(rows(&s, art), art_was, "{cmd}");
|
||||
assert_ne!(now.items[0], mark_was.items[0], "{cmd} edits the mark's gradient fill");
|
||||
assert_eq!(now.items[1..], mark_was.items[1..], "{cmd}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// The edited gradient is the last gradient (paint.setGradientGeom does not set it).
|
||||
if cmd != "paint.setGradientGeom" {
|
||||
let Paint::Gradient(g) = now.items[0].paint() else { panic!("{cmd}") };
|
||||
assert_eq!(&s.last_gradient, &**g, "{cmd}: the mark's edited gradient is the last gradient");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The Contents row of a graph design's copy and of a group whose stack differs is not moved with `aligned: true`, as
|
||||
/// the rows are not.
|
||||
#[test]
|
||||
@@ -4488,6 +4670,58 @@ fn group_selected_series_go_on_the_chosen_axis() {
|
||||
assert!(spec(&s, id).right_series.is_empty());
|
||||
}
|
||||
|
||||
/// The Graph Type dialog's subject: the selected graph, the series picked in it, and the tick values each value axis
|
||||
/// is drawn with while they are calculated, which are the ones the graph's value labels show.
|
||||
#[test]
|
||||
fn graph_type_subject_gives_the_picked_series_and_the_calculated_tick_values() {
|
||||
let mut s = Session::new();
|
||||
assert!(super::graph_type_subject(&s).is_err(), "no document");
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
assert!(super::graph_type_subject(&s).is_err(), "no graph selected");
|
||||
// Q1 3, 2; Q2 5, 4; Q3 -1, 6.
|
||||
let id = graph(&mut s, "column");
|
||||
let subject = super::graph_type_subject(&s).unwrap();
|
||||
assert_eq!((subject.id, subject.series), (id, vec![]));
|
||||
assert_eq!(subject.calculated, [(-2.0, 6.0, 4); 2]);
|
||||
let shown = |s: &Session| value_labels(s, id).into_iter().map(|(t, _)| t).collect::<Vec<_>>();
|
||||
assert_eq!(shown(&s), ["-2", "0", "2", "4", "6"]);
|
||||
// Overriding with them draws the same axis, and the calculated values stay the data's.
|
||||
s.execute("graph.setType", &json!({"axisMin": -2, "axisMax": 6, "ticks": 4})).unwrap();
|
||||
assert_eq!(shown(&s), ["-2", "0", "2", "4", "6"]);
|
||||
s.execute("graph.setType", &json!({"axisMin": 0, "axisMax": 100, "ticks": 0})).unwrap();
|
||||
assert_eq!(super::graph_type_subject(&s).unwrap().calculated[0], (-2.0, 6.0, 4));
|
||||
// A single bound is calculated with, as the axis is drawn.
|
||||
s.execute("graph.setType", &json!({"axisMin": -10, "axisMax": null})).unwrap();
|
||||
let (lo, hi, _) = super::graph_type_subject(&s).unwrap().calculated[0];
|
||||
let labels = shown(&s);
|
||||
assert!(lo <= -10.0, "{lo}");
|
||||
assert_eq!((labels.first().and_then(|t| t.parse::<f64>().ok()), labels.last().and_then(|t| t.parse::<f64>().ok())), (Some(lo), Some(hi)));
|
||||
s.execute("graph.setType", &json!({"axisMin": null, "axisMax": null})).unwrap();
|
||||
// Stacked columns stack their positive and their negative values: Q2 reaches 9, Q3 from -1 to 6.
|
||||
s.execute("graph.setType", &json!({"type": "stackedColumn"})).unwrap();
|
||||
assert_eq!(super::graph_type_subject(&s).unwrap().calculated[0], (-2.0, 10.0, 6));
|
||||
assert_eq!(shown(&s), ["-2", "0", "2", "4", "6", "8", "10"]);
|
||||
// A radar graph's axis starts at 0, and a pie graph has none.
|
||||
s.execute("graph.setType", &json!({"type": "radar"})).unwrap();
|
||||
assert_eq!(super::graph_type_subject(&s).unwrap().calculated, [(0.0, 6.0, 3); 2]);
|
||||
s.execute("graph.setType", &json!({"type": "pie"})).unwrap();
|
||||
assert_eq!(super::graph_type_subject(&s).unwrap().calculated, [(0.0, 1.0, 5); 2]);
|
||||
// Series picked with Group Selection.
|
||||
s.execute("graph.setType", &json!({"type": "column"})).unwrap();
|
||||
let picked = series(s.doc().unwrap().doc.node(id).unwrap(), 1).id;
|
||||
s.execute("select.set", &json!({"ids": [picked.0]})).unwrap();
|
||||
let subject = super::graph_type_subject(&s).unwrap();
|
||||
assert_eq!((subject.id, subject.series), (id, vec![1]));
|
||||
// Separate Scales: the right axis has the tick values of its own series.
|
||||
let mut s = Session::new();
|
||||
let id = two_scale_graph(&mut s);
|
||||
assert_eq!(super::graph_type_subject(&s).unwrap().calculated, [(0.0, 1000.0, 5); 2]);
|
||||
s.execute("graph.setType", &json!({"seriesIndexes": [1], "valueAxis": "right"})).unwrap();
|
||||
s.execute("graph.setType", &json!({"valueAxis": "both", "separateScales": true})).unwrap();
|
||||
assert_eq!(super::graph_type_subject(&s).unwrap().calculated, [(0.0, 10.0, 5), (0.0, 1000.0, 5)]);
|
||||
assert_eq!(spec(&s, id).right_series, [1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bar_graphs_keep_their_value_axis_along_the_bottom() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
//! Window › Info (`info.readout`): the selection's size and the active tool's readout, as the Info
|
||||
//! panel shows them.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_render::effects;
|
||||
|
||||
use super::{CommandSpec, Result, Session, always, cmd};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
query "info.readout",
|
||||
"Info",
|
||||
[],
|
||||
None,
|
||||
"{} → {tool: the active tool's id, width?, height?: the sides of the selection's bounding box in pt (the box around the anchors selected with Direct Selection, when there are some), measured as prefs usePreviewBounds says; left out with nothing selected, readout?: what the Info panel shows for the tool in use: {kind: \"drag\", dx, dy, distance, angle} while the Selection, Direct Selection or Group Selection tool moves the selection or the Gradient tool draws a gradient vector on the art; {kind: \"scale\", width, height} (percent) during a Scale tool drag; {kind: \"rotate\", center: [x, y], angle: deg counter-clockwise, as object.rotate takes it} and {kind: \"reflect\", center, angle: the axis in deg counter-clockwise from horizontal, as object.reflect takes it} during a Rotate or Reflect tool drag; {kind: \"shear\", center, axis: 0 for a horizontal shear and 90 for a vertical one, angle: deg, as object.shear takes it} during a Shear tool drag; {kind: \"brush\", brush: name|null} while the Paintbrush is the tool; left out for any other tool and between drags. Lengths are in pt, a drag's angle is in deg counter-clockwise from the x axis, and center is the center of the selection's bounding box as the drag has carried it, in document coordinates}",
|
||||
always,
|
||||
readout
|
||||
)]
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The sides of the selection's bounding box as the Info panel shows them: of the box around
|
||||
/// the anchors selected with Direct Selection when there are some, else of the bounding box
|
||||
/// rotated with rotated objects ([`Session::transform_box`]), measured as Use Preview Bounds
|
||||
/// says. None with nothing selected.
|
||||
pub fn info_size(&self) -> Option<(f64, f64)> {
|
||||
let st = self.active()?;
|
||||
let anchors = effects::preview::anchor_bounds_with(&st.selection, &st.doc, self.bounds_measure());
|
||||
let r = anchors.or_else(|| self.transform_box(&st.selection.objects).map(|b| b.rect))?;
|
||||
Some((r.width(), r.height()))
|
||||
}
|
||||
}
|
||||
|
||||
fn readout(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let mut out = json!({ "tool": s.tool_id() });
|
||||
if let Some((w, h)) = s.info_size() {
|
||||
out["width"] = json!(w);
|
||||
out["height"] = json!(h);
|
||||
}
|
||||
if let Some(r) = s.tool_readout() {
|
||||
out["readout"] = r.to_json();
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
use vectorcraft_tools::{PointerEvent, PointerKind};
|
||||
|
||||
use crate::{Session, ViewInfo};
|
||||
|
||||
fn view() -> ViewInfo {
|
||||
ViewInfo { smart_guides: false, snap_to_point: false, ..Default::default() }
|
||||
}
|
||||
|
||||
/// A 100 by 60 rectangle at (50, 50), selected, with a 10 pt stroke.
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 60})).unwrap()["id"].clone();
|
||||
s.execute("select.set", &json!({ "ids": [id] })).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 10})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn tool(s: &mut Session, id: &str) {
|
||||
s.select_tool(id, view()).unwrap();
|
||||
}
|
||||
|
||||
fn pointer(s: &mut Session, kind: PointerKind, x: f64, y: f64) {
|
||||
s.pointer(&PointerEvent::new(kind, x, y), view()).unwrap();
|
||||
}
|
||||
|
||||
fn info(s: &mut Session) -> serde_json::Value {
|
||||
s.execute("info.readout", &json!({})).unwrap()
|
||||
}
|
||||
|
||||
fn near(v: &serde_json::Value, want: f64) -> bool {
|
||||
v.as_f64().is_some_and(|v| (v - want).abs() < 1e-6)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_size_follows_use_preview_bounds() {
|
||||
let mut s = session();
|
||||
let i = info(&mut s);
|
||||
assert!(near(&i["width"], 100.0) && near(&i["height"], 60.0), "{i}");
|
||||
assert!(i.get("readout").is_none(), "{i}");
|
||||
s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap();
|
||||
let i = info(&mut s);
|
||||
assert!(near(&i["width"], 110.0) && near(&i["height"], 70.0), "{i}");
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let i = info(&mut s);
|
||||
assert!(i.get("width").is_none() && i.get("height").is_none(), "{i}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_move_reads_how_far_it_has_gone_until_the_release() {
|
||||
let mut s = session();
|
||||
tool(&mut s, "selection");
|
||||
pointer(&mut s, PointerKind::Down, 100.0, 80.0);
|
||||
assert!(info(&mut s).get("readout").is_none());
|
||||
pointer(&mut s, PointerKind::Drag, 130.0, 40.0);
|
||||
let i = info(&mut s);
|
||||
let r = &i["readout"];
|
||||
assert_eq!(r["kind"], "drag", "{i}");
|
||||
assert!(near(&r["dx"], 30.0) && near(&r["dy"], -40.0) && near(&r["distance"], 50.0), "{i}");
|
||||
assert!(near(&r["angle"], 53.13010235415598), "{i}");
|
||||
pointer(&mut s, PointerKind::Up, 130.0, 40.0);
|
||||
let i = info(&mut s);
|
||||
assert!(i.get("readout").is_none(), "{i}");
|
||||
assert!(near(&i["width"], 100.0), "{i}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_transform_tool_reads_its_drag() {
|
||||
for (id, check) in [
|
||||
("scale", (|r| r["kind"] == "scale" && near(&r["width"], 200.0) && near(&r["height"], 200.0)) as fn(&serde_json::Value) -> bool),
|
||||
("rotate", |r| r["kind"] == "rotate" && near(&r["center"][0], 100.0) && near(&r["center"][1], 80.0) && near(&r["angle"], -90.0)),
|
||||
("reflect", |r| r["kind"] == "reflect" && near(&r["center"][0], 100.0) && near(&r["angle"], 0.0)),
|
||||
("shear", |r| {
|
||||
r["kind"] == "shear"
|
||||
&& near(&r["center"][0], 100.0)
|
||||
&& near(&r["center"][1], 80.0)
|
||||
&& near(&r["axis"], 0.0)
|
||||
&& near(&r["angle"], 45.0)
|
||||
}),
|
||||
] {
|
||||
let mut s = session();
|
||||
tool(&mut s, id);
|
||||
// The reference point is the box's center (100, 80).
|
||||
let from = if id == "shear" { (100.0, 60.0) } else { (120.0, 100.0) };
|
||||
pointer(&mut s, PointerKind::Down, from.0, from.1);
|
||||
let to = match id {
|
||||
"scale" => (140.0, 120.0),
|
||||
"rotate" => (80.0, 100.0),
|
||||
"reflect" => (160.0, 80.0),
|
||||
_ => (120.0, 60.0),
|
||||
};
|
||||
pointer(&mut s, PointerKind::Drag, to.0, to.1);
|
||||
let i = info(&mut s);
|
||||
assert_eq!(i["tool"], id);
|
||||
assert!(check(&i["readout"]), "{id}: {i}");
|
||||
pointer(&mut s, PointerKind::Up, to.0, to.1);
|
||||
assert!(info(&mut s).get("readout").is_none(), "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_paintbrush_reads_its_brush() {
|
||||
let mut s = session();
|
||||
tool(&mut s, "paintbrush");
|
||||
let i = info(&mut s);
|
||||
assert_eq!(i["readout"], json!({"kind": "brush", "brush": null}), "{i}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_parameter_is_refused() {
|
||||
let mut s = session();
|
||||
let e = s.execute("info.readout", &json!({"tool": "scale"})).unwrap_err().to_string();
|
||||
assert!(e.contains("tool"), "{e}");
|
||||
}
|
||||
}
|
||||
@@ -1298,7 +1298,112 @@ pub(crate) fn path_shown(path: &str, doc_path: Option<&str>) -> bool {
|
||||
/// alone in a reply to the caller asking now? Only a path [`path_shown`] does not allow; a URL is
|
||||
/// always shown as it is.
|
||||
pub(crate) fn script_hidden(f: &str, doc_path: Option<&str>) -> bool {
|
||||
!path_shown(f, doc_path) && !matches!(fileio::document_path(f, doc_path), Err(craft_docpath::Refused::Url))
|
||||
file_hidden(f, doc_path)
|
||||
}
|
||||
|
||||
/// Is the file `path` (a link of the document saved at `doc_path`) one the caller asking now may
|
||||
/// not be shown? Only a path [`path_shown`] does not allow; a URL is not a file and is shown as it is.
|
||||
pub(crate) fn file_hidden(path: &str, doc_path: Option<&str>) -> bool {
|
||||
!path_shown(path, doc_path) && !matches!(fileio::document_path(path, doc_path), Err(craft_docpath::Refused::Url))
|
||||
}
|
||||
|
||||
/// Does an SVG of `d` (a document whose links are looked for from `base`) written for the caller
|
||||
/// asking now name the file of a linked image that [`file_hidden`] keeps from it? An `<image>`
|
||||
/// names its image's file with SVG Options › Images set to Link (`link`), and with Embed when the
|
||||
/// document holds no pixels for the image. An image with a solid colorize paint whose pixels are
|
||||
/// gray or missing names none: the SVG writes gray pixels colorized and leaves out an image
|
||||
/// without pixels. The images of the art the SVG writes (opacity masks included) and of the
|
||||
/// symbols, patterns and brushes that art uses, as Copy follows them, are checked: the SVG writes
|
||||
/// no other resource. Hidden layers and objects are written only with
|
||||
/// SVG Options › hidden layers kept (`hidden`), and template layers never ([`svg_written`]).
|
||||
/// Always `false` without read roots in force.
|
||||
pub(crate) fn svg_names_hidden_image(d: &Document, base: LinkBase, link: bool, hidden: bool) -> bool {
|
||||
if crate::file_access::current().is_none() || !names_hidden_image(d, base, link) {
|
||||
return false;
|
||||
}
|
||||
let art = d.layers.iter().filter_map(|l| svg_written(l, hidden)).collect();
|
||||
names_hidden_image(&super::clipboard::Clipboard::gather(d, art).to_document(), base, link)
|
||||
}
|
||||
|
||||
/// `n` as the SVG writer writes it, or `None` when it writes none of it: a hidden layer or object
|
||||
/// is left out unless `hidden`, a template layer's art always, and a disabled opacity mask's art.
|
||||
/// Only layers and groups lose members; other objects keep theirs as they are.
|
||||
fn svg_written(n: &Node, hidden: bool) -> Option<Node> {
|
||||
if !(n.visible || hidden) {
|
||||
return None;
|
||||
}
|
||||
let mut n = n.clone();
|
||||
let mask = n.extras().mask.as_deref().filter(|m| !m.disabled).and_then(|m| {
|
||||
let art = svg_written(&m.art, hidden)?;
|
||||
Some(Box::new(vectorcraft_doc::OpacityMask { art: std::sync::Arc::new(art), ..m.clone() }))
|
||||
});
|
||||
if n.extras().mask.is_some() {
|
||||
n.extras_mut().mask = mask;
|
||||
}
|
||||
match &mut n.kind {
|
||||
NodeKind::Layer { template: true, children, .. } => children.clear(),
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => {
|
||||
*children = children.iter().filter_map(|c| svg_written(c, hidden)).map(std::sync::Arc::new).collect();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Some(n)
|
||||
}
|
||||
|
||||
/// [`svg_names_hidden_image`] for every image of `d`: in the layers, symbols, graph designs,
|
||||
/// patterns, opacity masks and the art of the stored brushes, used or not.
|
||||
fn names_hidden_image(d: &Document, base: LinkBase, link: bool) -> bool {
|
||||
let d = with_brush_art(d);
|
||||
let mut hidden = false;
|
||||
d.visit_images(|n, im| {
|
||||
if hidden {
|
||||
return;
|
||||
}
|
||||
let shown = d.shown_image(n, im);
|
||||
let Some(l) = &shown.link else { return };
|
||||
let blob = d.image_blob(&shown).filter(|b| !b.bytes.is_empty());
|
||||
// The SVG writes an image with a solid colorize paint as colorized pixels when they are
|
||||
// gray, and leaves it out when the document holds none of them.
|
||||
if matches!(n.extras().colorize.as_deref(), Some(vectorcraft_color::Paint::Solid { .. })) && blob.is_none_or(|b| b.gray_source().is_some()) {
|
||||
return;
|
||||
}
|
||||
let named = link || blob.is_none();
|
||||
hidden = named && file_hidden(&l.path, base.doc);
|
||||
});
|
||||
hidden
|
||||
}
|
||||
|
||||
/// Does the native document an SVG of `d` (a document whose links are looked for from `base`)
|
||||
/// carries with Preserve Editing Capabilities name a file that the caller asking now may not be
|
||||
/// shown: the file of a linked image or placed document ([`file_hidden`]), the relative path kept
|
||||
/// of one, which is followed from the file the document was read from and from the document's own
|
||||
/// folder, or a data set's image? Links in the layers, symbols, graph designs, patterns, the pattern
|
||||
/// being edited as it was before, opacity masks and the art of the stored brushes are all checked,
|
||||
/// as [`with_hidden_paths_named`] checks them. A stored brush library that is not a list, or holds
|
||||
/// an entry that does not read as a brush, counts as naming one: the native document carries it as
|
||||
/// it is, and its links cannot be checked. Always `false` without read roots in force.
|
||||
pub(crate) fn names_hidden_file(d: &Document, base: LinkBase) -> bool {
|
||||
if crate::file_access::current().is_none() {
|
||||
return false;
|
||||
}
|
||||
let unread = |list: &Vec<Value>| list.iter().any(|raw| vectorcraft_brush::Brush::from_json(raw.clone()).is_err());
|
||||
if d.unknown.get(vectorcraft_brush::DOC_KEY).is_some_and(|v| v.as_array().is_none_or(unread)) {
|
||||
return true;
|
||||
}
|
||||
let relative_hidden = |r: &str| [base.relative, base.doc].into_iter().any(|from| !path_shown(r, from));
|
||||
let hidden = |l: &LinkInfo| file_hidden(&l.path, base.doc) || l.relative.as_deref().is_some_and(relative_hidden);
|
||||
let image_hidden = |v: &DataValue| matches!(v, DataValue::Image(path) if file_hidden(path, base.doc));
|
||||
if d.variables.datasets.iter().any(|set| set.values.values().any(image_hidden)) {
|
||||
return true;
|
||||
}
|
||||
let mut d = with_brush_art(d);
|
||||
if let Some(original) = d.pattern_edit.as_ref().and_then(|e| e.original.clone()) {
|
||||
d.to_mut().patterns.push(original);
|
||||
}
|
||||
let mut found = false;
|
||||
d.visit_images(|_, im| found |= im.link.as_ref().is_some_and(hidden));
|
||||
d.visit_placed(|_, p| found |= hidden(&p.link));
|
||||
found
|
||||
}
|
||||
|
||||
/// The linked JavaScript file `f` of the open document `st` as a reply to the caller asking now
|
||||
|
||||
@@ -292,8 +292,22 @@ fn guide_moves(s: &Session, p: &Value, r: Rect, h: Option<&str>, v: Option<&str>
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// The key anchor ([`vectorcraft_doc::Selection::key_anchor`]) when Align and Distribute act on the
|
||||
/// selected anchor points and align to the key ([`align_to`]): the path and the point.
|
||||
fn key_anchor(s: &Session, p: &Value) -> Option<(NodeId, (usize, usize))> {
|
||||
(align_to(s, p) == Some("key")).then(|| s.doc().ok()?.selection.key_anchor).flatten()
|
||||
}
|
||||
|
||||
/// Where the key anchor of [`key_anchor`] is.
|
||||
fn key_anchor_point(s: &Session, p: &Value) -> Option<Point> {
|
||||
key_anchor(s, p)?;
|
||||
let st = s.doc().ok()?;
|
||||
st.selection.key_anchor_point(&st.doc)
|
||||
}
|
||||
|
||||
/// [`align`] of the selected anchor points (whole paths among them give all theirs): each point
|
||||
/// moves to the edge or centre of the points' bounds, or of the artboard with Align To Artboard.
|
||||
/// moves to the edge or centre of the points' bounds, of the artboard with Align To Artboard, or to
|
||||
/// the key anchor when aligning to it.
|
||||
fn align_anchors(s: &mut Session, p: &Value, ids: &[NodeId], (h, v): (Option<&str>, Option<&str>)) -> Result<Value> {
|
||||
let targets = crate::cmd::path::anchor_targets(s)?;
|
||||
let d = &s.doc()?.doc;
|
||||
@@ -304,9 +318,10 @@ fn align_anchors(s: &mut Session, p: &Value, ids: &[NodeId], (h, v): (Option<&st
|
||||
let Some(bounds) = pts.iter().skip(1).fold(pts.first().map(|q| Rect::from_points(*q, *q)), |b, q| b.map(|b| b.union_pt(*q))) else {
|
||||
return ok();
|
||||
};
|
||||
// shortcut: no key anchor yet, so Align To Key Object aligns to the points' bounds as Selection does
|
||||
// (or to a key guide).
|
||||
let (r, along_x, along_y) = align_reference(s, p, ids, Measure::default(), Some(bounds))?;
|
||||
// Aligning to the key, the points go to the key anchor, which stays where it is. Without one,
|
||||
// a key object aligns them to their bounds as Selection does (a key guide lines them up on it).
|
||||
let own = key_anchor_point(s, p).map_or(bounds, |k| Rect::from_points(k, k));
|
||||
let (r, along_x, along_y) = align_reference(s, p, ids, Measure::default(), Some(own))?;
|
||||
let (h, v) = (h.filter(|_| along_x), v.filter(|_| along_y));
|
||||
let target = |q: Point| {
|
||||
let x = match h {
|
||||
@@ -410,9 +425,10 @@ fn apply_spaced(s: &mut Session, label: &str, p: &Value, ids: &[NodeId], horiz:
|
||||
|
||||
/// [`distribute`] and [`distribute_spacing`] of the selected anchor points (whole paths among them
|
||||
/// give all theirs): the points between the first and the last along the axis are spaced evenly,
|
||||
/// or `gap` apart from the first. A point has no size, so every Distribute option of an axis
|
||||
/// gives the same result.
|
||||
fn distribute_anchors(s: &mut Session, label: &str, horiz: bool, gap: Option<f64>) -> Result<Value> {
|
||||
/// or `gap` apart from the first. With a gap and a key anchor `key` among them, the key anchor stays
|
||||
/// where it is and the others are placed `gap` apart outward from it, in their order along the
|
||||
/// axis. A point has no size, so every Distribute option of an axis gives the same result.
|
||||
fn distribute_anchors(s: &mut Session, label: &str, horiz: bool, gap: Option<f64>, key: Option<(NodeId, (usize, usize))>) -> Result<Value> {
|
||||
let targets = crate::cmd::path::anchor_targets(s)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let along = |q: Point| if horiz { q.x } else { q.y };
|
||||
@@ -431,8 +447,11 @@ fn distribute_anchors(s: &mut Session, label: &str, horiz: bool, gap: Option<f64
|
||||
return ok();
|
||||
}
|
||||
let step = gap.unwrap_or((last - first) / (pts.len() - 1) as f64);
|
||||
// The point the spacing starts from: the key anchor with a gap, else the first point.
|
||||
let (from, at_from) =
|
||||
gap.and(key).and_then(|(kid, (ksi, kai))| pts.iter().position(|q| (q.0, q.1, q.2) == (kid, ksi, kai))).map_or((0, first), |k| (k, pts[k].3));
|
||||
let moves: Vec<(NodeId, usize, usize, f64)> =
|
||||
pts.iter().enumerate().map(|(i, &(id, si, ai, at))| (id, si, ai, first + step * i as f64 - at)).collect();
|
||||
pts.iter().enumerate().map(|(i, &(id, si, ai, at))| (id, si, ai, at_from + step * (i as f64 - from as f64) - at)).collect();
|
||||
if moves.iter().all(|m| m.3.abs() <= 1e-9) {
|
||||
return ok();
|
||||
}
|
||||
@@ -466,11 +485,13 @@ pub(super) fn distribute(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let m = measure(s, p, "object.distribute")?;
|
||||
let board = distribute_to(s, p, &ids, m, "object.distribute")?;
|
||||
let spacing = spacing(p, "object.distribute")?;
|
||||
// Anchor points selected with Direct Selection are distributed themselves, as Align aligns them.
|
||||
// Anchor points selected with Direct Selection are distributed themselves, as Align aligns them;
|
||||
// with a key anchor, a spacing places them from it.
|
||||
if !s.doc()?.selection.anchors.is_empty() {
|
||||
let key = key_anchor(s, p);
|
||||
return match direction(p, "object.distribute")? {
|
||||
(None, None) => Err(bad("object.distribute", "give horizontal or vertical")),
|
||||
(h, _) => distribute_anchors(s, "Distribute", h.is_some(), None),
|
||||
(h, _) => distribute_anchors(s, "Distribute", h.is_some(), spacing.filter(|_| key.is_some()), key),
|
||||
};
|
||||
}
|
||||
let (horiz, key): (bool, fn(&Rect, bool) -> f64) = match direction(p, "object.distribute")? {
|
||||
@@ -543,7 +564,8 @@ pub(super) fn distribute_spacing(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let board = distribute_to(s, p, &ids, m, "object.distributeSpacing")?;
|
||||
let spacing = spacing(p, "object.distributeSpacing")?;
|
||||
if !s.doc()?.selection.anchors.is_empty() {
|
||||
return distribute_anchors(s, "Distribute Spacing", horiz, spacing);
|
||||
let key = key_anchor(s, p);
|
||||
return distribute_anchors(s, "Distribute Spacing", horiz, spacing, key);
|
||||
}
|
||||
// The selected guides across the axis are spaced with the objects, as items with no size (#1597).
|
||||
let mut items = spaced_items(s, &ids, m, horiz)?;
|
||||
|
||||
@@ -260,7 +260,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Align",
|
||||
["Window", "Align"],
|
||||
None,
|
||||
"{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", to?: \"selection\"|\"artboard\"|\"key\" (default: the key object when the selection has one, select.key, else the selection; a key guide, select.key {guide}, stays put and the objects line up on its line: a vertical guide sets where left, center and right go and vertical alignment leaves them, a horizontal one the other way round; aligning to the key, the other selected ruler guides move too: a vertical guide to the key's left edge, center or right edge, a horizontal one to its top, center or bottom; aligning to the artboard moves selected guides to its edges too (#3463), and with only guides selected aligning to the selection moves them to their collective bounds), artboard?: index (0-based; with to: \"artboard\", the artboard to align to; the app passes the active one; default: the artboard under the center of the selection, else the first), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} With anchor points selected (Direct Selection), the points align instead: to their own bounds, or to the artboard (#1180)",
|
||||
"{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", to?: \"selection\"|\"artboard\"|\"key\" (default: the key object when the selection has one, select.key, else the selection; a key guide, select.key {guide}, stays put and the objects line up on its line: a vertical guide sets where left, center and right go and vertical alignment leaves them, a horizontal one the other way round; aligning to the key, the other selected ruler guides move too: a vertical guide to the key's left edge, center or right edge, a horizontal one to its top, center or bottom; aligning to the artboard moves selected guides to its edges too (#3463), and with only guides selected aligning to the selection moves them to their collective bounds), artboard?: index (0-based; with to: \"artboard\", the artboard to align to; the app passes the active one; default: the artboard under the center of the selection, else the first), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} With anchor points selected (Direct Selection), the points align instead: to their own bounds, to the artboard (#1180), or, aligning to the key with a key anchor (select.key {id, anchor}, the last point a Shift-click added), to the key anchor, which stays put",
|
||||
has_selection_or_guides,
|
||||
align
|
||||
),
|
||||
@@ -269,7 +269,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Distribute",
|
||||
["Window", "Align"],
|
||||
None,
|
||||
"{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", spacing?: pt (used with a key, select.key: the key object, or the key guide, select.key {guide}, stays put and the lines are placed this far apart, outward from its line, in their order on that line; 0 puts them all on its line; a key guide along the axis leaves everything where it is; not used without a key or with anchor points selected), to?: \"selection\"|\"artboard\"|\"key\" (default: the key while there is one, else the selection; \"key\" without spacing distributes as \"selection\" does; not used with anchor points selected, or with spacing and a key object; with a key guide, \"selection\" or \"artboard\" distributes without it as the key), artboard?: index (0-based; with to: \"artboard\", the artboard to distribute across; the app passes the active one; default: as object.align's), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} space the selected objects' left edges, centers or right edges (top edges, centers or bottom edges) in their order on that line, with the selected ruler guides across the axis (vertical ones for horizontal; #1597): a guide has no size, so its edges and center are its line, and guides along the axis stay. Without spacing and a key they are spaced evenly, the first and last stay put, and fewer than three don't move; with spacing and a key, see spacing (two are enough); with to: \"artboard\", the first one's left (top) edge goes to the artboard's left (top) edge, the last one's right (bottom) edge goes to the artboard's right (bottom) edge, and two are enough. With anchor points selected (Direct Selection), the points are spaced evenly between the first and the last along the axis instead (#1636)",
|
||||
"{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", spacing?: pt (used with a key, select.key: the key object, or the key guide, select.key {guide}, stays put and the lines are placed this far apart, outward from its line, in their order on that line; 0 puts them all on its line; a key guide along the axis leaves everything where it is; not used without a key, or with anchor points selected and no key anchor), to?: \"selection\"|\"artboard\"|\"key\" (default: the key while there is one, else the selection; \"key\" without spacing distributes as \"selection\" does; with anchor points selected, with \"selection\" or \"artboard\" the key anchor is not the key and all the points are spaced as without one; not used with spacing and a key object; with a key guide, \"selection\" or \"artboard\" distributes without it as the key), artboard?: index (0-based; with to: \"artboard\", the artboard to distribute across; the app passes the active one; default: as object.align's), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} space the selected objects' left edges, centers or right edges (top edges, centers or bottom edges) in their order on that line, with the selected ruler guides across the axis (vertical ones for horizontal; #1597): a guide has no size, so its edges and center are its line, and guides along the axis stay. Without spacing and a key they are spaced evenly, the first and last stay put, and fewer than three don't move; with spacing and a key, see spacing (two are enough); with to: \"artboard\", the first one's left (top) edge goes to the artboard's left (top) edge, the last one's right (bottom) edge goes to the artboard's right (bottom) edge, and two are enough. With anchor points selected (Direct Selection), the points are spaced evenly between the first and the last along the axis instead (#1636); with spacing and a key anchor (select.key {id, anchor}), the key anchor stays put and the others are placed spacing apart, outward from it, in their order along the axis",
|
||||
can_distribute,
|
||||
distribute
|
||||
),
|
||||
@@ -278,7 +278,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Distribute Spacing",
|
||||
["Window", "Align"],
|
||||
None,
|
||||
"{axis?: \"horizontal\"|\"vertical\" (default: \"horizontal\"), spacing?: pt (the key object, select.key, or the key guide, select.key {guide}, stays put and the others are spaced from it; a key guide along the axis leaves everything where it is), to?: \"selection\"|\"artboard\"|\"key\" (used without spacing and without anchor points selected, and with a key guide; default: the key while there is one, else the selection; \"key\" without spacing spaces as \"selection\" does), artboard?: index (0-based; with to: \"artboard\", the artboard to space across; the app passes the active one; default: as object.align's), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} without spacing, make the gaps between the selected objects equal, in the order of their left (top) edges, with the selected ruler guides across the axis as items with no size (#1597; guides along the axis stay): the first item's left (top) edge and the last one's right (bottom) edge stay put, or with to: \"artboard\" go to the artboard's left (top) and right (bottom) edges. With anchor points selected (Direct Selection), the points are spaced evenly along the axis instead, or `spacing` apart from the first (#1636)",
|
||||
"{axis?: \"horizontal\"|\"vertical\" (default: \"horizontal\"), spacing?: pt (the key object, select.key, or the key guide, select.key {guide}, stays put and the others are spaced from it; a key guide along the axis leaves everything where it is), to?: \"selection\"|\"artboard\"|\"key\" (used without spacing, and with a key guide; with anchor points selected, with \"selection\" or \"artboard\" the key anchor is not the key and all the points are spaced as without one; default: the key while there is one, else the selection; \"key\" without spacing spaces as \"selection\" does), artboard?: index (0-based; with to: \"artboard\", the artboard to space across; the app passes the active one; default: as object.align's), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} without spacing, make the gaps between the selected objects equal, in the order of their left (top) edges, with the selected ruler guides across the axis as items with no size (#1597; guides along the axis stay): the first item's left (top) edge and the last one's right (bottom) edge stay put, or with to: \"artboard\" go to the artboard's left (top) and right (bottom) edges. With anchor points selected (Direct Selection), the points are spaced evenly along the axis instead, or `spacing` apart from the first (#1636), or with a key anchor (select.key {id, anchor}) `spacing` apart outward from the key anchor, which stays put",
|
||||
can_distribute,
|
||||
distribute_spacing
|
||||
),
|
||||
|
||||
@@ -158,6 +158,9 @@ fn apply_transform_moving_guides(
|
||||
}
|
||||
None => ids.clone(),
|
||||
};
|
||||
// Pattern editing with Move Tile with Art: the tile art's bounds before a move.
|
||||
let moves_only = c[0] == 1.0 && c[1] == 0.0 && c[2] == 0.0 && c[3] == 1.0;
|
||||
let tile_art = if objects && !copy && moves_only { crate::cmd::patterncmds::tile_art_bounds(d) } else { None };
|
||||
// Transforms don't move nodes in the tree, so reuse the paths found for the no-copy
|
||||
// case; copies and a settled typing session need paths from the edited document.
|
||||
let paths = if reindex { d.index_paths(targets.iter().copied()) } else { paths };
|
||||
@@ -172,6 +175,10 @@ fn apply_transform_moving_guides(
|
||||
for id in &targets {
|
||||
super::pixelgrid::keep_compound_aligned(d, *id, sc);
|
||||
}
|
||||
// Moving all of the tile art moves the tile as far.
|
||||
if let Some(before) = tile_art {
|
||||
crate::cmd::patterncmds::move_tile_with_art(d, &targets, before);
|
||||
}
|
||||
}
|
||||
if with_guides && (delta.x != 0.0 || delta.y != 0.0) {
|
||||
for i in sel.guides.clone() {
|
||||
|
||||
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Fill",
|
||||
[],
|
||||
None,
|
||||
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}",
|
||||
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}",
|
||||
has_doc,
|
||||
|s, p| set_paint(s, p, true)
|
||||
),
|
||||
@@ -30,7 +30,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Stroke",
|
||||
[],
|
||||
None,
|
||||
"{…as paint.setFill, item?: the stroke item to set} same as paint.setFill, for the stroke; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, as paint.setFill",
|
||||
"{…as paint.setFill, item?: the stroke item to set, aligned?: bool (as paint.setFill)} same as paint.setFill, for the stroke; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, as paint.setFill",
|
||||
has_doc,
|
||||
|s, p| { set_paint(s, p, false) }
|
||||
),
|
||||
@@ -96,7 +96,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
|
||||
"Invert",
|
||||
[],
|
||||
None,
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind (docs/mcp.md); no undo step when no color changes → {changed}",
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind (docs/mcp.md); no undo step when no color changes → {changed}",
|
||||
has_doc,
|
||||
|s, p| proxy_recolor(s, p, "paint.invert", "Invert", &super::colorcmds::invert)
|
||||
),
|
||||
@@ -105,7 +105,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
|
||||
"Complement",
|
||||
[],
|
||||
None,
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} replace the active proxy's colours by their complements ((highest + lowest) − each component, over RGB or CMY; grey unchanged) keeping each colour's model; honours the Appearance panel's active item and a selected object of a dynamic symbol instance as paint.invert does; with nothing selected, the default; no undo step when no color changes → {changed}",
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} replace the active proxy's colours by their complements ((highest + lowest) − each component, over RGB or CMY; grey unchanged) keeping each colour's model; honours the Appearance panel's active item and a selected object of a dynamic symbol instance as paint.invert does; with nothing selected, the default; no undo step when no color changes → {changed}",
|
||||
has_doc,
|
||||
|s, p| proxy_recolor(s, p, "paint.complement", "Complement", &|c: Color| c.complement_keep_model())
|
||||
),
|
||||
@@ -114,7 +114,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
|
||||
"Apply Last Color",
|
||||
[],
|
||||
Some(","),
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} apply the last solid colour used (paint.recent lastColor) to the active proxy of the selection and the default → {objects} (as paint.setFill)",
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last solid colour used (paint.recent lastColor) to the active proxy of the selection and the default → {objects} (as paint.setFill)",
|
||||
has_doc,
|
||||
|s, p| {
|
||||
let paint = Paint::solid(s.last_solid);
|
||||
@@ -126,7 +126,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
|
||||
"Apply Last Gradient",
|
||||
[],
|
||||
Some("."),
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} apply the last gradient used (paint.recent lastGradient), fitted to each object, to the active proxy of the selection and the default → {objects} (as paint.setFill)",
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last gradient used (paint.recent lastGradient), fitted to each object, to the active proxy of the selection and the default → {objects} (as paint.setFill)",
|
||||
has_doc,
|
||||
|s, p| {
|
||||
let paint = super::gradient::unplaced(&Paint::Gradient(Box::new(s.last_gradient.clone())));
|
||||
@@ -553,7 +553,14 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
|
||||
let item = item_target(s, p, cmd)?.of_kind(s, fill);
|
||||
let selected = item.targets(s, p)?;
|
||||
let ids = super::graph::paint_targets(&s.doc()?.doc, &selected);
|
||||
let paint = if span { placed_across(&s.doc()?.doc, &ids, paint, p, fill) } else { paint };
|
||||
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)
|
||||
} else {
|
||||
paint
|
||||
};
|
||||
// The gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso: a solid
|
||||
// fill recolors just those points of their meshes (the proxies show them: `fill_mesh_points`).
|
||||
let mesh_points = if fill && matches!(paint, Paint::Solid { .. }) { picked_mesh_points(s, &ids) } else { vec![] };
|
||||
@@ -570,10 +577,12 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
|
||||
// The type objects whose characters took the paint (no row targeted): only those change what a graph's labels keep
|
||||
// for their characters; a row edit is kept with the label's rows.
|
||||
let characters = std::cell::RefCell::new(Vec::new());
|
||||
edit_items_then(
|
||||
// The objects counted: with a design's art, those with a row equal to the art's.
|
||||
let ids = edit_items_then(
|
||||
s,
|
||||
&ids,
|
||||
item,
|
||||
of,
|
||||
cmd,
|
||||
label,
|
||||
fill,
|
||||
@@ -1070,30 +1079,32 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(
|
||||
return Ok(json!({ "changed": changed as usize }));
|
||||
}
|
||||
let item = item_target(s, p, cmd)?.of_kind(s, !stroke);
|
||||
let (r, shown_item, edited) = match item {
|
||||
ItemTarget::Item { index, .. } => {
|
||||
let ids = super::appearance::drop_design_art(&s.doc()?.doc, item.targets(s, p)?);
|
||||
let (r, shown_at) = match item {
|
||||
ItemTarget::Item { .. } => {
|
||||
let targets = super::appearance::drop_design_art(&s.doc()?.doc, item.targets(s, p)?);
|
||||
let of = super::appearance::reference_of(s, p, item, cmd)?;
|
||||
// The row shown is the one edited in the first object that has it: an aligned row maps to each object's equal row.
|
||||
let shown_at = super::appearance::first_edited(s, item, of, &targets).and_then(|(id, it)| match it {
|
||||
ItemTarget::Item { index, .. } => Some((id, Some(index))),
|
||||
ItemTarget::Top => None,
|
||||
});
|
||||
let mut changed = 0;
|
||||
edit_items(s, &ids, item, cmd, label, !stroke, |n, i| {
|
||||
edit_items(s, &targets, item, of, cmd, label, !stroke, |n, i| {
|
||||
let paint =
|
||||
if stroke { n.appearance.stroke_at_mut(i).map(|l| &mut l.paint) } else { n.appearance.fill_at_mut(i).map(|l| &mut l.paint) };
|
||||
changed += paint.is_some_and(|paint| super::colorcmds::map_paint(paint, f)) as usize;
|
||||
Ok(())
|
||||
})?;
|
||||
(json!({ "changed": changed }), Some(index), Some(ids))
|
||||
(json!({ "changed": changed }), shown_at)
|
||||
}
|
||||
// The proxy recolors its paints, including a colorized image's fill, without changing image pixels or pattern tiles.
|
||||
ItemTarget::Top => {
|
||||
let q = json!({"fill": !stroke, "stroke": stroke, "includeImages": false, "includePatterns": false, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()});
|
||||
(super::colorcmds::recolor(s, &q, cmd, label, f)?, None, None)
|
||||
(super::colorcmds::recolor(s, &q, cmd, label, f)?, leaf_targets(s, &ids)?.first().map(|id| (*id, None)))
|
||||
}
|
||||
};
|
||||
// The paint remembered is one the edit recolored: a graph design's art that the item edit leaves out gives none.
|
||||
let shown_ids = match edited {
|
||||
Some(ids) => ids,
|
||||
None => leaf_targets(s, &ids)?,
|
||||
};
|
||||
if let Some(shown) = shown_ids.first().and_then(|id| s.doc().ok()?.doc.node(*id).map(|n| proxy_paint(n, stroke, shown_item))) {
|
||||
if let Some(shown) = shown_at.and_then(|(id, at)| s.doc().ok()?.doc.node(id).map(|n| proxy_paint(n, stroke, at))) {
|
||||
s.remember_paint(&shown);
|
||||
}
|
||||
Ok(r)
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -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`"));
|
||||
@@ -529,7 +535,6 @@ pub const UNCHECKED: &[&str] = &[
|
||||
"assets.settings.set",
|
||||
"attributes.info",
|
||||
"attributes.set",
|
||||
"brush.freehand",
|
||||
"css.export",
|
||||
"css.generate",
|
||||
"css.selection",
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -78,7 +78,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Pattern Options",
|
||||
["Window", "Pattern Options"],
|
||||
None,
|
||||
"{name? (default: the pattern being edited), newName? (trimmed; blank: the name is kept), tileType?, brickOffset?, width?, height?, hSpacing?, vSpacing?, sizeTileToArt?: bool, overlap?: {h: left|right, v: top|bottom}, copies?: 3|5|7|9, dimCopies?: %, showTileEdge?: bool, showSwatchBounds?: bool (outline the part of the tiling the swatch repeats, dashed)}",
|
||||
"{name? (default: the pattern being edited), newName? (trimmed; blank: the name is kept), tileType?, brickOffset?, width?, height?, hSpacing?, vSpacing?, sizeTileToArt?: bool, moveTileWithArt?: bool (in pattern editing mode, a move of all of the tile art moves the tile with it; off for a new pattern), overlap?: {h: left|right, v: top|bottom}, copies?: 3|5|7|9, dimCopies?: %, showTileEdge?: bool, showSwatchBounds?: bool (outline the part of the tiling the swatch repeats, dashed)}",
|
||||
has_doc,
|
||||
pattern_options
|
||||
),
|
||||
@@ -530,7 +530,7 @@ fn pattern_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cur = s.doc()?.doc.pattern(&name).cloned().ok_or_else(|| bad(C, format!("no pattern `{name}`")))?;
|
||||
let tt = tile_type_param(p, C, cur.tile_type)?;
|
||||
check_numbers(p, &["width", "height", "hSpacing", "vSpacing", "copies", "dimCopies"], C)?;
|
||||
check_switches(p, &["sizeTileToArt", "showTileEdge", "showSwatchBounds"], C)?;
|
||||
check_switches(p, &["sizeTileToArt", "moveTileWithArt", "showTileEdge", "showSwatchBounds"], C)?;
|
||||
let num = |k: &str| p.get(k).and_then(Value::as_f64);
|
||||
for k in ["width", "height"] {
|
||||
if num(k).is_some_and(|v| !(v.is_finite() && v > 0.0)) {
|
||||
@@ -560,11 +560,11 @@ fn pattern_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let edit_layer = editing(s).filter(|e| e.pattern == name).map(|e| e.layer);
|
||||
let out_name = new_name.clone().unwrap_or(name.clone());
|
||||
s.edit("Pattern Options", |d, _| {
|
||||
// While editing, the tile art is the edit layer's.
|
||||
let live_art: Option<Vec<Arc<Node>>> =
|
||||
edit_layer.and_then(|l| d.node(l)).and_then(|l| l.children()).map(|ch| ch.iter().filter(|c| !c.is_ruler_guide()).cloned().collect());
|
||||
let def = d.pattern_mut(&name).ok_or_else(|| EngineError::Other("pattern missing".into()))?;
|
||||
// While editing, the tile art is the edit layer's.
|
||||
let live_art = |d: &Document| -> Option<Vec<Arc<Node>>> {
|
||||
edit_layer.and_then(|l| d.node(l)).and_then(|l| l.children()).map(|ch| ch.iter().filter(|c| !c.is_ruler_guide()).cloned().collect())
|
||||
};
|
||||
let apply = |def: &mut PatternDef, live_art: Option<Vec<Arc<Node>>>| {
|
||||
def.tile_type = tt;
|
||||
def.overlap = overlap;
|
||||
if let Some(v) = num("hSpacing") {
|
||||
@@ -576,6 +576,9 @@ fn pattern_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(v) = p.get("sizeTileToArt").and_then(Value::as_bool) {
|
||||
def.size_tile_to_art = v;
|
||||
}
|
||||
if let Some(v) = p.get("moveTileWithArt").and_then(Value::as_bool) {
|
||||
def.move_tile_with_art = v;
|
||||
}
|
||||
if let Some(v) = num("copies") {
|
||||
def.copies = (v as u32).clamp(1, 15) | 1;
|
||||
}
|
||||
@@ -590,13 +593,24 @@ fn pattern_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
if def.size_tile_to_art {
|
||||
let saved = std::mem::take(&mut def.art);
|
||||
def.art = live_art.clone().unwrap_or_else(|| saved.clone());
|
||||
def.art = live_art.unwrap_or_else(|| saved.clone());
|
||||
def.fit_tile_to_art();
|
||||
def.art = saved;
|
||||
} else if num("width").is_some() || num("height").is_some() {
|
||||
let c = def.tile.center();
|
||||
def.tile = Rect::from_center_size(c, (num("width").unwrap_or(def.tile.width()), num("height").unwrap_or(def.tile.height())));
|
||||
}
|
||||
};
|
||||
// Options that change nothing leave the document and its undo history as they are.
|
||||
let mut next = cur.clone();
|
||||
apply(&mut next, live_art(&s.doc()?.doc));
|
||||
if next == cur && new_name.is_none() {
|
||||
return Ok(json!({ "name": out_name }));
|
||||
}
|
||||
s.edit("Pattern Options", |d, _| {
|
||||
let live = live_art(d);
|
||||
let def = d.pattern_mut(&name).ok_or_else(|| EngineError::Other("pattern missing".into()))?;
|
||||
apply(def, live);
|
||||
if let Some(nn) = &new_name {
|
||||
def.name = nn.clone();
|
||||
rename_pattern_uses(d, &name, nn);
|
||||
@@ -609,6 +623,47 @@ fn pattern_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "name": out_name }))
|
||||
}
|
||||
|
||||
/// The tile art's objects (the editing layer's, ruler guides aside) while `d` edits a pattern that
|
||||
/// has Move Tile with Art on, with the pattern's name.
|
||||
fn moving_tile_art(d: &Document) -> Option<(String, Vec<Arc<Node>>)> {
|
||||
let pe = d.pattern_edit.as_ref()?;
|
||||
if !d.pattern(&pe.pattern).is_some_and(|p| p.move_tile_with_art) {
|
||||
return None;
|
||||
}
|
||||
let art = d.node(pe.layer)?.children()?.iter().filter(|c| !c.is_ruler_guide()).cloned().collect();
|
||||
Some((pe.pattern.clone(), art))
|
||||
}
|
||||
|
||||
/// Before a move: the bounds of the tile art for [`move_tile_with_art`], `None` unless `d` edits a
|
||||
/// pattern with Move Tile with Art on.
|
||||
pub(crate) fn tile_art_bounds(d: &Document) -> Option<Rect> {
|
||||
moving_tile_art(d).and_then(|(_, art)| vectorcraft_doc::live::nodes_bounds(&art))
|
||||
}
|
||||
|
||||
/// Move Tile with Art: after a move of `moved` that takes every object of the tile art (a group
|
||||
/// counting when all of its objects moved), the tile moves by as much as the art did, measured from
|
||||
/// its bounds `before` the move (objects aligned to the pixel grid snap back to it). A move of only
|
||||
/// some of the art leaves the tile where it is.
|
||||
pub(crate) fn move_tile_with_art(d: &mut Document, moved: &[NodeId], before: Rect) {
|
||||
let Some((name, art)) = moving_tile_art(d) else { return };
|
||||
let moved: std::collections::HashSet<NodeId> = moved.iter().copied().collect();
|
||||
// An object moves whole when it moved, or when every object in it did (a group whose members
|
||||
// were selected and moved one by one).
|
||||
fn whole(n: &Node, moved: &std::collections::HashSet<NodeId>) -> bool {
|
||||
moved.contains(&n.id) || n.children().is_some_and(|ch| !ch.is_empty() && ch.iter().all(|c| whole(c, moved)))
|
||||
}
|
||||
if art.is_empty() || !art.iter().all(|c| whole(c, &moved)) {
|
||||
return;
|
||||
}
|
||||
let Some(after) = vectorcraft_doc::live::nodes_bounds(&art) else { return };
|
||||
let by = after.origin() - before.origin();
|
||||
if (by.x != 0.0 || by.y != 0.0)
|
||||
&& let Some(def) = d.pattern_mut(&name)
|
||||
{
|
||||
def.tile = def.tile + by;
|
||||
}
|
||||
}
|
||||
|
||||
/// Side `side` of the `overlap` object `o` gives `cmd`: true for the second of `names`, false for the
|
||||
/// first, `current` when `o` leaves it out or gives null. Any other value is an error.
|
||||
fn overlap_side(o: &Value, side: &str, names: [&str; 2], current: bool, cmd: &str) -> Result<bool> {
|
||||
@@ -680,6 +735,7 @@ fn pattern_list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
"hSpacing": p.h_spacing,
|
||||
"vSpacing": p.v_spacing,
|
||||
"sizeTileToArt": p.size_tile_to_art,
|
||||
"moveTileWithArt": p.move_tile_with_art,
|
||||
"overlap": {"h": if p.overlap.right_in_front { "right" } else { "left" }, "v": if p.overlap.bottom_in_front { "bottom" } else { "top" }},
|
||||
"copies": p.copies,
|
||||
"dimCopies": p.dim_copies,
|
||||
|
||||
+169
-29
File diff suppressed because one or more lines are too long
@@ -100,6 +100,9 @@ pub(crate) struct DocumentArt {
|
||||
/// What is shown: the artboard, or the art's bounds.
|
||||
pub frame: Rect,
|
||||
pub warnings: Vec<String>,
|
||||
/// Whether a PDF or `.ai` page was read from the file's editing data (its page only a
|
||||
/// placeholder, or its PDF part unreadable) instead of from the page.
|
||||
pub editing_data: bool,
|
||||
}
|
||||
|
||||
/// Artboard `page` (1-based) of the VectorCraft document `name` (`bytes`, read from `path` when
|
||||
@@ -114,6 +117,21 @@ pub(crate) fn document_art(
|
||||
bounding: bool,
|
||||
page_box: PageBox,
|
||||
cmd: &str,
|
||||
) -> Result<DocumentArt> {
|
||||
opened_document_art(name, (bytes, None), path, page, bounding, page_box, cmd)
|
||||
}
|
||||
|
||||
/// [`document_art`] of `bytes` and, for a PDF already read, `opened`: the PDF `bytes` as
|
||||
/// [`vectorcraft_pdf::open_pdf`] read it without a password, so its page is read without reading
|
||||
/// the file again.
|
||||
fn opened_document_art(
|
||||
name: &str,
|
||||
(bytes, opened): (&[u8], Option<&vectorcraft_pdf::Opened>),
|
||||
path: Option<&str>,
|
||||
page: u32,
|
||||
bounding: bool,
|
||||
page_box: PageBox,
|
||||
cmd: &str,
|
||||
) -> Result<DocumentArt> {
|
||||
let file = fileio::file_name(name);
|
||||
let pdf = is_pdf(name, bytes);
|
||||
@@ -125,7 +143,7 @@ pub(crate) fn document_art(
|
||||
}
|
||||
if pdf {
|
||||
let o = fileio::LoadOptions { crop: crop_to(page_box), ..Default::default() };
|
||||
return super::pdf_art(name, bytes, path, page as usize, o, bounding, cmd);
|
||||
return super::pdf_art(name, (bytes, opened), path, page as usize, o, bounding, cmd);
|
||||
}
|
||||
let mut l = fileio::load(name, bytes)?;
|
||||
// Its linked images show their files; its placed documents stay as they are, unless their
|
||||
@@ -145,7 +163,7 @@ pub(crate) fn document_art(
|
||||
let nodes = super::on_artboard(&symbols, &layers, board);
|
||||
let frame = if bounding { super::shown_bounds(&symbols, &nodes) } else { Some(board) };
|
||||
let frame = frame.filter(|r| r.width() > 0.0 || r.height() > 0.0).ok_or_else(|| bad(cmd, format!("`{file}` has no art to place")))?;
|
||||
Ok(DocumentArt { doc: l.doc, nodes, clip: (!bounding).then_some(board), frame, warnings: l.warnings })
|
||||
Ok(DocumentArt { doc: l.doc, nodes, clip: (!bounding).then_some(board), frame, warnings: l.warnings, editing_data: false })
|
||||
}
|
||||
|
||||
/// The most placed documents read inside one another while their links are resolved.
|
||||
@@ -223,6 +241,8 @@ pub(crate) struct Source {
|
||||
pub warnings: Vec<String>,
|
||||
/// The colour mode the file's art was read in (a PDF page painted mostly in CMYK reads in CMYK).
|
||||
pub color_mode: ColorMode,
|
||||
/// [`DocumentArt::editing_data`].
|
||||
pub editing_data: bool,
|
||||
}
|
||||
|
||||
/// The VectorCraft document `name` (`bytes`, from `path` when there is one) read for showing
|
||||
@@ -232,33 +252,48 @@ pub(crate) fn source(name: &str, bytes: &[u8], path: Option<&str>, page: u32, bo
|
||||
read_source(name, bytes, None, path, (page, bounding, page_box), cmd)
|
||||
}
|
||||
|
||||
/// [`source`] of the file whose bytes `bytes` holds, kept by the blob without a copy of its own:
|
||||
/// several pages of one file read this way share one copy of it.
|
||||
/// A PDF (or PDF-compatible `.ai`) whose pages are read for placing linked, read once for them all.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct SharedFile<'a> {
|
||||
/// The file's bytes, which every page's blob keeps without a copy of its own.
|
||||
pub bytes: &'a Arc<Vec<u8>>,
|
||||
/// The bytes' hash ([`hash_bytes`]).
|
||||
pub hash: &'a str,
|
||||
/// The bytes as [`vectorcraft_pdf::open_pdf`] read them, without a password.
|
||||
pub opened: &'a vectorcraft_pdf::Opened,
|
||||
}
|
||||
|
||||
/// [`source`] of page `page` of `file`: several pages of one file read this way share one copy of
|
||||
/// it, and the file is hashed and read once for them all.
|
||||
pub(crate) fn shared_source(
|
||||
name: &str,
|
||||
bytes: &Arc<Vec<u8>>,
|
||||
file: SharedFile<'_>,
|
||||
path: Option<&str>,
|
||||
page: u32,
|
||||
bounding: bool,
|
||||
page_box: PageBox,
|
||||
cmd: &str,
|
||||
) -> Result<Source> {
|
||||
read_source(name, bytes, Some(bytes), path, (page, bounding, page_box), cmd)
|
||||
read_source(name, file.bytes, Some(file), path, (page, bounding, page_box), cmd)
|
||||
}
|
||||
|
||||
/// [`source`], the blob keeping `shared` when given (else a copy of `bytes`); `shown` is the page
|
||||
/// (or artboard), whether the art's bounds are shown, and the page's box.
|
||||
/// [`source`], the blob keeping `shared`'s bytes when given (else a copy of `bytes`), its hash
|
||||
/// used for the key (else `bytes` hashed) and its pages read from what was read of it; `shown` is
|
||||
/// the page (or artboard), whether the art's bounds are shown, and the page's box.
|
||||
fn read_source(
|
||||
name: &str,
|
||||
bytes: &[u8],
|
||||
shared: Option<&Arc<Vec<u8>>>,
|
||||
shared: Option<SharedFile<'_>>,
|
||||
path: Option<&str>,
|
||||
shown: (u32, bool, PageBox),
|
||||
cmd: &str,
|
||||
) -> Result<Source> {
|
||||
let (page, bounding, page_box) = shown;
|
||||
let hash = shared.map_or_else(|| hash_bytes(bytes), |f| f.hash.to_string());
|
||||
let opened = shared.map(|f| f.opened);
|
||||
let shared = shared.map(|f| f.bytes);
|
||||
// The same document placed the same way is read once (placing it again is free).
|
||||
let key = key_for(&hash_bytes(bytes), page, bounding, page_box);
|
||||
let key = key_for(&hash, page, bounding, page_box);
|
||||
// Resolving its links depends on where the file is and on what the caller may read, so a hit
|
||||
// needs the same path, and nothing is shared with or from a confined (automation) caller.
|
||||
let confined = crate::file_access::current().is_some();
|
||||
@@ -269,7 +304,7 @@ fn read_source(
|
||||
}
|
||||
return Ok(s);
|
||||
}
|
||||
let a = document_art(name, bytes, path, page, bounding, page_box, cmd)?;
|
||||
let a = opened_document_art(name, (bytes, opened), path, page, bounding, page_box, cmd)?;
|
||||
let bytes = shared.cloned().unwrap_or_else(|| Arc::new(bytes.to_vec()));
|
||||
let mut blob = ImageBlob { mime: mime(name, &bytes).into(), bytes, proxy: None };
|
||||
let shown = PlacedDocument {
|
||||
@@ -284,10 +319,10 @@ fn read_source(
|
||||
};
|
||||
let art = group(a.nodes, a.clip);
|
||||
blob.proxy = preview(&a.doc, &art, a.frame).map(Arc::new);
|
||||
let color_mode = a.doc.color_mode;
|
||||
let (color_mode, editing_data) = (a.doc.color_mode, a.editing_data);
|
||||
// Drawing it needn't read it again.
|
||||
vectorcraft_doc::placed_document::prime(&shown, blob.bytes.clone(), (a.doc, art, a.frame));
|
||||
let s = Source { blob, key, page_box, frame: a.frame, warnings: a.warnings, color_mode };
|
||||
let s = Source { blob, key, page_box, frame: a.frame, warnings: a.warnings, color_mode, editing_data };
|
||||
if !confined {
|
||||
let mut m = lock_memo();
|
||||
if m.len() >= MEMO_SIZE {
|
||||
|
||||
@@ -540,6 +540,7 @@ struct Saved {
|
||||
recent_colors: Vec<vectorcraft_color::Color>,
|
||||
recent_urls: Vec<String>,
|
||||
global_edit_options: super::globaledit::Options,
|
||||
select_similar: &'static str,
|
||||
envelope_defaults: Option<(vectorcraft_doc::live::EnvelopeOptions, f64)>,
|
||||
}
|
||||
|
||||
@@ -564,6 +565,7 @@ impl Saved {
|
||||
recent_colors: s.recent_colors.clone(),
|
||||
recent_urls: s.recent_urls.clone(),
|
||||
global_edit_options: s.global_edit_options.clone(),
|
||||
select_similar: s.select_similar,
|
||||
envelope_defaults: s.envelope_defaults,
|
||||
}
|
||||
}
|
||||
@@ -587,6 +589,7 @@ impl Saved {
|
||||
s.recent_colors = self.recent_colors;
|
||||
s.recent_urls = self.recent_urls;
|
||||
s.global_edit_options = self.global_edit_options;
|
||||
s.select_similar = self.select_similar;
|
||||
s.envelope_defaults = self.envelope_defaults;
|
||||
s.pending_paint = None;
|
||||
}
|
||||
|
||||
@@ -206,6 +206,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"imageTrace.makeAndExpand",
|
||||
"imageTrace.release",
|
||||
"imageTrace.setView",
|
||||
"info.readout",
|
||||
"layer.clippingMask.toggle",
|
||||
"layer.collectInNew",
|
||||
"layer.delete",
|
||||
@@ -536,6 +537,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"select.same.textStrokeColor",
|
||||
"select.segments",
|
||||
"select.set",
|
||||
"select.similar",
|
||||
"select.storedPath",
|
||||
"select.toggle",
|
||||
"select.update",
|
||||
@@ -692,6 +694,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"variable.makeTextDynamic",
|
||||
"variable.makeVisibilityDynamic",
|
||||
"variable.rename",
|
||||
"variable.sort",
|
||||
"variable.unbind",
|
||||
];
|
||||
|
||||
|
||||
@@ -334,10 +334,19 @@ pub(crate) fn raster_image(d: &mut Document, n: &Node, below: bool, members: boo
|
||||
|
||||
/// The image Object › Rasterize makes of `n` with the options of `n`'s Effect › Rasterize, when
|
||||
/// that is its only visible raster effect and is its own (not a fill's or a stroke's): made of `n`
|
||||
/// without that effect and without its transparency, which stays on the object. `None` otherwise,
|
||||
/// or when the image can't be made.
|
||||
/// without that effect and without its transparency, which stays on the object. When Transform
|
||||
/// effects after the Rasterize effect move its image ([`vectorcraft_render::rasterize_stage`]),
|
||||
/// the image is made of the art before them and moved by them, as the canvas draws it. `None`
|
||||
/// otherwise, when those Transform effects flatten the image, or when the image can't be made.
|
||||
fn rasterize_effect_image(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
let [RasterFx::Rasterize(r)] = raster_fx(n)[..] else { return None };
|
||||
let staged = vectorcraft_render::rasterize_stage(d, n);
|
||||
if let Some((_, map)) = &staged
|
||||
&& !(map.determinant().is_finite() && map.determinant().abs() > 1e-12)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let n = staged.as_ref().map_or(n, |(stage, _)| stage);
|
||||
let at = n.appearance.effects.iter().position(|e| e.visible && e.id == effects::RASTERIZE)?;
|
||||
let p = json!({
|
||||
"ppi": r.ppi.unwrap_or(d.raster_effects_ppi),
|
||||
@@ -354,7 +363,11 @@ fn rasterize_effect_image(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
// shortcut: expanded Rasterize effects stay RGB, as the object keeps its own opacity mask and the
|
||||
// image's transparency would need one too; upgrade when CMYK images carry alpha.
|
||||
let image = super::menucmds::rasterize_art(d, vec![whole], &p, "object.rasterize", false).ok()?;
|
||||
Some(image.into_node(d))
|
||||
let mut image = image.into_node(d);
|
||||
if let Some((_, map)) = staged {
|
||||
image.transform(map, false);
|
||||
}
|
||||
Some(image)
|
||||
}
|
||||
|
||||
/// `v` (an object without its raster effects) replaced by `image` of the object with them: the
|
||||
@@ -473,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)))
|
||||
}
|
||||
@@ -589,6 +604,112 @@ fn walk_all(out: &mut Document, nodes: &[Arc<Node>], report: &mut FlattenReport)
|
||||
.then(|| nodes.iter().map(|n| walk(out, n, report).map(Arc::new).unwrap_or_else(|| n.clone())).collect())
|
||||
}
|
||||
|
||||
/// `n` as an image when its Rasterize image moves with the Transform effects after it
|
||||
/// ([`vectorcraft_render::rasterize_stage`]): the image is made of the art before those Transform
|
||||
/// effects and moved by them, as the canvas draws it, which baking the geometry effects first would
|
||||
/// lose. A map that flattens the image leaves an empty group, as the canvas draws nothing. Inside
|
||||
/// groups, layers and opacity masks, the members are looked at the same way. `None` when nothing in
|
||||
/// `n` changes; hidden objects and template layers stay as they are.
|
||||
fn staged(out: &mut Document, n: &Node, report: &mut FlattenReport) -> Option<Node> {
|
||||
if !n.visible || matches!(n.kind, NodeKind::Layer { template: true, .. }) {
|
||||
return None;
|
||||
}
|
||||
if let Some((_, map)) = vectorcraft_render::rasterize_stage(out, n) {
|
||||
let mut v = n.clone();
|
||||
strip_raster(&mut v, false);
|
||||
let det = map.determinant();
|
||||
if !(det.is_finite() && det.abs() > 1e-12) {
|
||||
v.appearance = Default::default();
|
||||
v.kind = NodeKind::Group { children: vec![], clip: false };
|
||||
return Some(v);
|
||||
}
|
||||
let image = raster_image(out, n, false, false)?;
|
||||
report.record(n, &image);
|
||||
let mut m = replace_with_image(v, image);
|
||||
staged_mask(out, &mut m, report);
|
||||
return Some(m);
|
||||
}
|
||||
let mut m = n.clone();
|
||||
let mut changed = staged_mask(out, &mut m, report);
|
||||
if is_container(n)
|
||||
&& let Some(ch) = staged_all(out, n.children()?, report)
|
||||
&& let Some(slot) = m.children_mut()
|
||||
{
|
||||
*slot = ch;
|
||||
changed = true;
|
||||
}
|
||||
changed.then_some(m)
|
||||
}
|
||||
|
||||
/// The art of `n`'s opacity mask with [`staged`] applied; `true` when it changed.
|
||||
fn staged_mask(out: &mut Document, n: &mut Node, report: &mut FlattenReport) -> bool {
|
||||
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut())
|
||||
&& let Some(art) = staged(out, &m.art, report)
|
||||
{
|
||||
m.art = Arc::new(art);
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Does `n`, or anything inside it or its opacity mask, list a Rasterize effect whose image the
|
||||
/// Transform effects after it move ([`effects::rasterize_stage`])?
|
||||
fn holds_stage(n: &Node) -> bool {
|
||||
effects::rasterize_stage(&n.appearance.effects).is_some()
|
||||
|| n.extras().mask.as_ref().is_some_and(|m| holds_stage(&m.art))
|
||||
|| n.children().is_some_and(|ch| ch.iter().any(|c| holds_stage(c)))
|
||||
}
|
||||
|
||||
/// A copy of `doc` with [`staged`] applied in its layers, symbol definitions and pattern tiles,
|
||||
/// `None` when nothing changes.
|
||||
fn staged_document(doc: &Document, report: &mut FlattenReport) -> Option<Document> {
|
||||
let holds = doc.layers.iter().any(|n| holds_stage(n))
|
||||
|| doc.symbols.iter().any(|s| holds_stage(&s.art))
|
||||
|| doc.patterns.iter().any(|p| p.art.iter().any(|n| holds_stage(n)));
|
||||
if !holds {
|
||||
return None;
|
||||
}
|
||||
let mut out = doc.clone();
|
||||
let mut changed = false;
|
||||
if let Some(layers) = staged_all(&mut out, &doc.layers, report) {
|
||||
out.layers = layers;
|
||||
changed = true;
|
||||
}
|
||||
for i in 0..out.symbols.len() {
|
||||
if let Some(art) = out.symbols.get(i).map(|s| s.art.clone()).and_then(|a| staged(&mut out, &a, report))
|
||||
&& let Some(s) = out.symbols.get_mut(i)
|
||||
{
|
||||
s.art = Arc::new(art);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
for i in 0..out.patterns.len() {
|
||||
if let Some(art) = out.patterns.get(i).map(|p| p.art.clone()).and_then(|a| staged_all(&mut out, &a, report))
|
||||
&& let Some(p) = out.patterns.get_mut(i)
|
||||
{
|
||||
p.art = art;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
changed.then_some(out)
|
||||
}
|
||||
|
||||
/// `nodes` with [`staged`] applied, `None` when none changes.
|
||||
fn staged_all(out: &mut Document, nodes: &[Arc<Node>], report: &mut FlattenReport) -> Option<Vec<Arc<Node>>> {
|
||||
let mut changed = false;
|
||||
let all = nodes
|
||||
.iter()
|
||||
.map(|n| match staged(out, n, report) {
|
||||
Some(m) => {
|
||||
changed = true;
|
||||
Arc::new(m)
|
||||
}
|
||||
None => n.clone(),
|
||||
})
|
||||
.collect();
|
||||
changed.then_some(all)
|
||||
}
|
||||
|
||||
/// A copy of `doc` with raster effects turned into images at the document's raster effects
|
||||
/// resolution, or `None` when there are none: on every kind of object (paths, groups and layers,
|
||||
/// type, images, symbol instances, live objects) and on single fills and strokes, in the layers,
|
||||
@@ -616,6 +737,9 @@ fn flatten(doc: &Document, report: &mut FlattenReport) -> Option<Document> {
|
||||
if !any(&doc.layers) && !doc.symbols.iter().any(|s| needs(&s.art, which)) && !doc.patterns.iter().any(|p| any(&p.art)) {
|
||||
return None;
|
||||
}
|
||||
// Rasterize images that Transform effects after them move, before those effects are baked.
|
||||
let pre = staged_document(doc, report);
|
||||
let doc = pre.as_ref().unwrap_or(doc);
|
||||
// Geometry effects first, so the vector objects kept above shadows are final.
|
||||
let baked = effects::bake_document(doc);
|
||||
let src = baked.as_ref().unwrap_or(doc);
|
||||
|
||||
@@ -34,7 +34,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Recolor Artwork",
|
||||
["Edit", "Edit Colors"],
|
||||
None,
|
||||
"{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex)], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour] (what `group` is rewritten with; default: the rows' new colours, in order, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}",
|
||||
"{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour] (what `group` is rewritten with; default: the rows' new colours, in order, excluded and empty rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}",
|
||||
has_doc,
|
||||
apply
|
||||
),
|
||||
@@ -1614,8 +1614,11 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(k) => super::swatchlib::library_swatches(s, k).unwrap_or_default(),
|
||||
None => vec![],
|
||||
};
|
||||
let row_swatches: Vec<Option<Swatch>> =
|
||||
rows.iter().map(|r| r.new_color().and_then(|c| lib_swatches.iter().find(|w| w.paint.color() == Some(c)).cloned())).collect();
|
||||
// A row with no current colors recolors nothing, so its swatch does not join the document.
|
||||
let row_swatches: Vec<Option<Swatch>> = rows
|
||||
.iter()
|
||||
.map(|r| r.new_color().filter(|_| !r.from.is_empty()).and_then(|c| lib_swatches.iter().find(|w| w.paint.color() == Some(c)).cloned()))
|
||||
.collect();
|
||||
// While an object of a dynamic symbol instance's art is selected, the selection is refused, as
|
||||
// `selected_roots` refuses it.
|
||||
super::edit::refuse_symbol_part(s)?;
|
||||
@@ -1657,7 +1660,8 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.ok_or_else(|| bad(C, format!("bad colour {v} in groupColors")))
|
||||
})
|
||||
.collect::<Result<_>>()?,
|
||||
None => rows.iter().filter_map(Row::new_color).map(|c| mapped_adjust.apply(c)).collect(),
|
||||
// A row with no current colors gives the group no color.
|
||||
None => rows.iter().filter(|r| !r.from.is_empty()).filter_map(Row::new_color).map(|c| mapped_adjust.apply(c)).collect(),
|
||||
};
|
||||
let rename = text_param(p, "rename", C)?;
|
||||
let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok();
|
||||
|
||||
@@ -999,8 +999,9 @@ impl RecoveryJob {
|
||||
pub fn write(&self) -> std::result::Result<Value, String> {
|
||||
let store = self.store.as_ref();
|
||||
let doc = self.save.doc();
|
||||
// A linked image keeps its preview, as a save writes it.
|
||||
let linked = doc.linked_only_images();
|
||||
// A linked image keeps its preview, as a save writes it (the images in the stored brushes'
|
||||
// art counted too).
|
||||
let linked = super::links::with_brush_art(doc).linked_only_images();
|
||||
let mut lean = Document::clone(doc);
|
||||
let blobs = std::mem::take(&mut lean.images);
|
||||
let enc = self.save.encode_doc(&lean).map_err(|e| e.to_string())?;
|
||||
|
||||
File diff suppressed because one or more lines are too long
+126
-10
@@ -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
|
||||
),
|
||||
@@ -81,11 +82,19 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Cancel Key Object",
|
||||
[],
|
||||
None,
|
||||
"{id?: a selected top-level object (not a layer, a compound-path member or an object inside another selected object); one of two or more or the only one with ruler guides selected (the Selection tool: a click on one object of a selection of several, or of one with guides; on the key again: no id), guide?: index (a selected ruler guide, guide.list, with one or more objects selected: the Selection tool's click on a selected guide; Align lines the objects up on it and the guide stays put)} the key object Align aligns to and Distribute Spacing spaces from; without `id` or `guide` it cancels the key, as does a selection that holds only the key and objects inside it (one object, or a group key and its own members) and no ruler guide, or a key guide with no object selected or taken out of the selection; any other id or guide is an error that leaves the key as it was → {key, guide?} (the resulting key object, or null; guide: the key guide, left out without one)",
|
||||
"{id?: a selected top-level object (not a layer, a compound-path member or an object inside another selected object); one of two or more or the only one with ruler guides selected (the Selection tool: a click on one object of a selection of several, or of one with guides; on the key again: no id), guide?: index (a selected ruler guide, guide.list, with one or more objects selected: the Selection tool's click on a selected guide; Align lines the objects up on it and the guide stays put), anchor?: [subpath, anchor] with `id` the path (an anchor point selected with Direct Selection beside at least one other point becomes the key anchor: Align and Distribute move the other points relative to it and it stays put; select.anchors add or toggle of one point makes it the key anchor, as a Shift-click does)} the key object Align aligns to and Distribute Spacing spaces from; without `id` or `guide` it cancels the key, as does a selection that holds only the key and objects inside it (one object, or a group key and its own members) and no ruler guide, or a key guide with no object selected or taken out of the selection, or a key anchor that is deselected, deleted or left as the only selected point; any other id, guide or anchor is an error that leaves the key as it was → {key, guide?, keyAnchor?} (the resulting key object, or null; guide: the key guide, left out without one; keyAnchor: {id, anchor}, left out without one)",
|
||||
has_doc,
|
||||
key
|
||||
),
|
||||
cmd!("select.anchors", "Select Anchors", [], None, "{id, anchors: [[subpath, anchor]…], mode: \"set\"|\"add\"|\"toggle\"}", has_doc, anchors),
|
||||
cmd!(
|
||||
"select.anchors",
|
||||
"Select Anchors",
|
||||
[],
|
||||
None,
|
||||
"{id, anchors: [[subpath, anchor]…], mode: \"set\"|\"add\"|\"toggle\"}; add or toggle that selects one point makes it the key anchor while another point is selected too (see select.key)",
|
||||
has_doc,
|
||||
anchors
|
||||
),
|
||||
cmd!(
|
||||
"select.segments",
|
||||
"Select Segments",
|
||||
@@ -221,13 +230,73 @@ 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
|
||||
),
|
||||
cmd!(
|
||||
"select.similar",
|
||||
"Select Similar Objects",
|
||||
[],
|
||||
None,
|
||||
"{by?: \"all\"|\"fillColor\"|\"fillAndStroke\"|\"strokeColor\"|\"strokeWeight\"|\"opacity\"|\"blendingMode\"|\"appearance\"|\"graphicStyle\"|\"shapeType\"|\"symbolInstance\"} the Control bar's Select Similar Objects button and its menu: selects the objects like the first selected object by `by`, running the select.same command of that name; `all` selects the objects with its fill and stroke colours, stroke weight, opacity and blending mode (tints, compound paths and Live Paint faces as select.same.fillColor). A `by` given is kept for the session once the selection is made; without it, the kept one (`all` until one is given). Any other `by` is an error that keeps the selection and the kept attribute → {count, by}",
|
||||
has_selection,
|
||||
similar
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// The attributes Select Similar Objects (`select.similar`) selects by, in its menu's order, each
|
||||
/// with the Select › Same command it runs; `all` compares the fill and stroke colours, the stroke
|
||||
/// weight, the opacity and the blending mode at once, with no command of its own.
|
||||
pub const SIMILAR: [(&str, Option<&str>); 11] = [
|
||||
("all", None),
|
||||
("fillColor", Some("select.same.fillColor")),
|
||||
("fillAndStroke", Some("select.same.fillAndStroke")),
|
||||
("strokeColor", Some("select.same.strokeColor")),
|
||||
("strokeWeight", Some("select.same.strokeWeight")),
|
||||
("opacity", Some("select.same.opacity")),
|
||||
("blendingMode", Some("select.same.blendingMode")),
|
||||
("appearance", Some("select.same.appearance")),
|
||||
("graphicStyle", Some("select.same.graphicStyle")),
|
||||
("shapeType", Some("select.same.shapeType")),
|
||||
("symbolInstance", Some("select.same.symbolInstance")),
|
||||
];
|
||||
|
||||
fn similar(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "select.similar";
|
||||
let by = match text_param(p, "by", C)? {
|
||||
Some(name) => *SIMILAR.iter().find(|(n, _)| *n == name).ok_or_else(|| {
|
||||
let names: Vec<&str> = SIMILAR.iter().map(|(n, _)| *n).collect();
|
||||
bad(C, format!("unknown `by` \"{name}\": expected one of {}", names.join(", ")))
|
||||
})?,
|
||||
None => *SIMILAR.iter().find(|(n, _)| *n == s.select_similar).unwrap_or(&SIMILAR[0]),
|
||||
};
|
||||
let mut r = match by.1 {
|
||||
Some(same_cmd) => s.execute(same_cmd, &json!({}))?,
|
||||
None => {
|
||||
let tint = s.prefs.select_same_tint_percent;
|
||||
let r = same_fill(s, C, |a, b| {
|
||||
same_paint(&fill_of(a), &fill_of(b), tint)
|
||||
&& same_paint(&stroke_of(a).0, &stroke_of(b).0, tint)
|
||||
&& (stroke_weight(a) - stroke_weight(b)).abs() < 1e-9
|
||||
&& (a.opacity - b.opacity).abs() < 1e-6
|
||||
&& a.blend == b.blend
|
||||
})?;
|
||||
// Select › Reselect repeats `all`, whichever attribute is kept by then.
|
||||
if let Some(last) = s.doc_mut()?.last_selection_cmd.as_mut() {
|
||||
last.1 = json!({ "by": by.0 });
|
||||
}
|
||||
r
|
||||
}
|
||||
};
|
||||
s.select_similar = by.0;
|
||||
// A recorded action or the journal repeats the attribute used, not the one kept by then.
|
||||
s.note_journal("by", json!(by.0));
|
||||
r["by"] = json!(by.0);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// Selectable objects: children of visible, unlocked layers (or of the isolation container).
|
||||
/// The objects Select All takes: those of the isolated container, else of every layer (looking
|
||||
/// through sublayers, which are not objects). In isolation mode there are none while the isolated
|
||||
@@ -360,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> =
|
||||
@@ -610,6 +679,9 @@ fn key(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
if let Some(v) = p.get("anchor").filter(|v| !v.is_null()) {
|
||||
return key_anchor(s, id, guide, v);
|
||||
}
|
||||
if let Some(g) = guide {
|
||||
let sel = &s.doc()?.selection;
|
||||
if id.is_some() {
|
||||
@@ -624,6 +696,7 @@ fn key(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
s.select(|_, sel| {
|
||||
sel.key = None;
|
||||
sel.key_anchor = None;
|
||||
sel.key_guide = Some(gid);
|
||||
})?;
|
||||
return key_result(s);
|
||||
@@ -640,17 +713,52 @@ fn key(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.select(|_, sel| {
|
||||
sel.key = id;
|
||||
sel.key_guide = None;
|
||||
sel.key_anchor = None;
|
||||
})?;
|
||||
key_result(s)
|
||||
}
|
||||
|
||||
/// `{key}`, with `guide` when a guide is the key.
|
||||
/// `select.key {id, anchor: [subpath, anchor]}`: anchor point `anchor` of path `id`, selected with
|
||||
/// Direct Selection beside at least one other point, becomes the key anchor
|
||||
/// ([`vectorcraft_doc::Selection::key_anchor`]).
|
||||
fn key_anchor(s: &mut Session, id: Option<NodeId>, guide: Option<usize>, v: &Value) -> Result<Value> {
|
||||
const C: &str = "select.key";
|
||||
let r = match checked_refs(Some(&Value::Array(vec![v.clone()])), C)?.as_slice() {
|
||||
[r] => *r,
|
||||
_ => return Err(bad(C, "`anchor` must be a [subpath, anchor] pair")),
|
||||
};
|
||||
if guide.is_some() {
|
||||
return Err(bad(C, "give `anchor` or `guide`, not both"));
|
||||
}
|
||||
let id = id.ok_or_else(|| bad(C, "`anchor` needs `id`, the path the point is on"))?;
|
||||
let st = s.doc()?;
|
||||
let sel = &st.selection;
|
||||
let on_path = st.doc.node(id).and_then(|n| n.path_data()).is_some_and(|p| p.subpaths.get(r.0).is_some_and(|sp| r.1 < sp.anchors.len()));
|
||||
if !on_path || sel.segments.contains_key(&id) || !sel.anchors.get(&id).is_some_and(|set| set.contains(&r)) {
|
||||
return Err(bad(C, format!("anchor [{}, {}] of object {id} is not a selected anchor point", r.0, r.1)));
|
||||
}
|
||||
// Check the new key on a copy first, so a request that fails leaves the key as it was.
|
||||
let mut trial = sel.clone();
|
||||
trial.key_anchor = Some((id, r));
|
||||
trial.prune(&st.doc);
|
||||
if trial.key_anchor.is_none() {
|
||||
return Err(bad(C, "select another anchor point to align to the key anchor"));
|
||||
}
|
||||
s.select(|_, sel| sel.key_anchor = Some((id, r)))?;
|
||||
key_result(s)
|
||||
}
|
||||
|
||||
/// `{key}`, with `guide` when a guide is the key and `keyAnchor` (`{id, anchor}`) when an anchor
|
||||
/// point is.
|
||||
fn key_result(s: &Session) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let mut out = json!({ "key": st.selection.key });
|
||||
if let Some(g) = st.selection.key_guide.and_then(|id| super::docmenu::guide_indexes(&st.doc, &[id]).first().copied()) {
|
||||
out["guide"] = json!(g);
|
||||
}
|
||||
if let Some((id, (si, ai))) = st.selection.key_anchor {
|
||||
out["keyAnchor"] = json!({ "id": id.0, "anchor": [si, ai] });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
@@ -783,15 +891,23 @@ fn anchors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if whole && let Some(path) = d.node(id).and_then(|n| n.path_data()) {
|
||||
e.extend(path.anchors().map(|(s, i, _)| (s, i)));
|
||||
}
|
||||
// One point that add or toggle selects becomes the key anchor (a Shift-click with Direct
|
||||
// Selection); `prune` drops it unless another point is selected too.
|
||||
let single = refs.len() == 1;
|
||||
let mut newest = None;
|
||||
for r in refs {
|
||||
if mode == "toggle" && e.contains(&r) {
|
||||
e.remove(&r);
|
||||
} else {
|
||||
e.insert(r);
|
||||
} else if e.insert(r) && single {
|
||||
newest = Some(r);
|
||||
}
|
||||
}
|
||||
if e.is_empty() {
|
||||
sel.remove(id);
|
||||
} else if mode != "set"
|
||||
&& let Some(r) = newest
|
||||
{
|
||||
sel.key_anchor = Some((id, r));
|
||||
}
|
||||
})?;
|
||||
ok()
|
||||
@@ -1102,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()),
|
||||
|
||||
@@ -22,7 +22,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Stroke Options",
|
||||
["Window", "Stroke"],
|
||||
None,
|
||||
"{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path}} (a custom head with its art, as document.inspect reports one; refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take → {objects: how many objects took the stroke options}",
|
||||
"{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path}} (a custom head with its art, as document.inspect reports one; refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take → {objects: how many objects took the stroke options}",
|
||||
has_doc,
|
||||
stroke_set
|
||||
),
|
||||
@@ -49,7 +49,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Stroke Options",
|
||||
[],
|
||||
None,
|
||||
"{arrowScale?: [start %, end %], swapArrows?: bool, flipProfile?: \"along\"|\"across\", brush?: name|null, item?: stroke item index|null, ids?|id?, target?: \"object\"|\"contents\"} Stroke panel extras (with nothing selected, all but brush set up the next object drawn)",
|
||||
"{arrowScale?: [start %, end %], swapArrows?: bool, flipProfile?: \"along\"|\"across\", brush?: name|null, item?: stroke item index|null, aligned?: bool (as stroke.set), ids?|id?, target?: \"object\"|\"contents\"} Stroke panel extras (with nothing selected, all but brush set up the next object drawn)",
|
||||
has_doc,
|
||||
stroke_advanced
|
||||
),
|
||||
@@ -303,7 +303,9 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
st.profile = pr.clone();
|
||||
}
|
||||
};
|
||||
edit_items(s, &ids, item, C, "Stroke", false, |n, index| {
|
||||
let of = super::appearance::reference_of(s, p, item, C)?;
|
||||
// The objects counted: with a design's art, those with a row equal to the art's.
|
||||
let ids = edit_items(s, &ids, item, of, C, "Stroke", false, |n, index| {
|
||||
if index.is_none()
|
||||
&& let NodeKind::Text(t) = &mut n.kind
|
||||
{
|
||||
@@ -372,7 +374,7 @@ fn stroke_step(s: &mut Session, p: &Value, up: bool) -> Result<Value> {
|
||||
}
|
||||
let ids = super::appearance::drop_design_art(&s.doc()?.doc, ids);
|
||||
let label = if up { "Stroke Weight Up" } else { "Stroke Weight Down" };
|
||||
edit_items(s, &ids, item, c, label, false, |n, index| {
|
||||
edit_items(s, &ids, item, None, c, label, false, |n, index| {
|
||||
if index.is_none()
|
||||
&& let NodeKind::Text(t) = &mut n.kind
|
||||
{
|
||||
@@ -535,7 +537,8 @@ fn stroke_advanced(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
{
|
||||
arrows_and_profile(st);
|
||||
}
|
||||
edit_items(s, &ids, item, C, "Stroke", false, |n, index| {
|
||||
let of = super::appearance::reference_of(s, p, item, C)?;
|
||||
edit_items(s, &ids, item, of, C, "Stroke", false, |n, index| {
|
||||
let Some(st) = n.appearance.stroke_at_mut(index) else { return Ok(()) };
|
||||
arrows_and_profile(st);
|
||||
if let Some(b) = &brush {
|
||||
|
||||
@@ -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 → {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)?;
|
||||
@@ -1124,17 +1129,37 @@ 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);
|
||||
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();
|
||||
|
||||
@@ -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 {
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -1652,6 +1652,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.
|
||||
|
||||
@@ -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; 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); 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
|
||||
),
|
||||
@@ -739,11 +739,13 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
if children.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// The group takes the object's name, transparency, opacity mask and effects, which
|
||||
// apply to the type as a whole: once, not to each glyph. It is marked as type's
|
||||
// outlines, so geometry effects move its placed gradients with the whole outline, as
|
||||
// they do on the type.
|
||||
let gid = d.alloc_id();
|
||||
let mut g = Node::group(gid, children);
|
||||
g.opacity = n.opacity;
|
||||
g.blend = n.blend;
|
||||
g.name = n.name.clone();
|
||||
let mut g = super::flatten::carry(&n, Node::group(gid, children));
|
||||
g.extras_mut().type_outlines = true;
|
||||
d.insert(par, idx, g)?;
|
||||
out.push(gid);
|
||||
if roots.contains(&tid) {
|
||||
|
||||
@@ -2008,6 +2008,38 @@ fn glyph_form_is_one_character_attribute_saved_only_when_set() {
|
||||
assert!(runs(&s).iter().all(|r| r.style.glyph_form == GlyphForm::Default));
|
||||
}
|
||||
|
||||
/// A glyph choice (`text.setGlyphAlternate`) would keep drawing its own glyph over a glyph form,
|
||||
/// so setting a form other than "default" takes it away, in `text.setRangeStyle` and in
|
||||
/// `text.setFormat`; "default" (Revert To Default Forms) and calls without `glyphForm` keep it.
|
||||
#[test]
|
||||
fn a_glyph_form_takes_away_the_characters_glyph_choice() {
|
||||
use vectorcraft_doc::{GlyphChoice, GlyphForm};
|
||||
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 choice = GlyphChoice { ch: '唖', gid: 42, font: "Test-Regular".into(), version: "1".into() };
|
||||
if let Some(NodeKind::Text(t)) = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(NodeId(id)).map(|n| &mut n.kind) {
|
||||
vectorcraft_text::edit::style_range(&mut t.runs, 3, 6, |st| st.glyph_alternate = Some(choice.clone()));
|
||||
}
|
||||
let state = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.glyph_form, r.style.glyph_alternate.is_some())).collect::<Vec<_>>(),
|
||||
_ => panic!("text"),
|
||||
};
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "size": 30})).unwrap();
|
||||
assert_eq!(state(&s), [("亜".into(), GlyphForm::Default, false), ("唖".into(), GlyphForm::Default, true)], "no glyphForm: kept");
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "glyphForm": "default"})).unwrap();
|
||||
assert_eq!(state(&s)[1], ("唖".into(), GlyphForm::Default, true), "default: kept");
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "start": 3, "end": 6, "glyphForm": "jis78"})).unwrap();
|
||||
assert_eq!(state(&s), [("亜".into(), GlyphForm::Default, false), ("唖".into(), GlyphForm::Jis78, false)]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(state(&s)[1], ("唖".into(), GlyphForm::Default, true), "one undo step brings both back");
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"glyphForm": "default"})).unwrap();
|
||||
assert!(state(&s).iter().any(|r| r.2), "default: kept");
|
||||
s.execute("text.setFormat", &json!({"glyphForm": "traditional"})).unwrap();
|
||||
assert!(state(&s).iter().all(|r| r.1 == GlyphForm::Traditional && !r.2), "{:?}", state(&s));
|
||||
}
|
||||
|
||||
/// No Break is a character attribute, saved only when on.
|
||||
#[test]
|
||||
fn no_break_is_a_character_attribute_saved_only_when_on() {
|
||||
|
||||
@@ -138,7 +138,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Paste without Formatting",
|
||||
["Edit"],
|
||||
Some("Cmd+Alt+V"),
|
||||
"{center?, dx?, dy?, swatchConflict?} paste as edit.paste; pasted text takes the default character style (one run) and leaves its character and paragraph styles behind, as do the labels of pasted graphs → {ids, added, merged, renamed}",
|
||||
"{center?, dx?, dy?, swatchConflict?} paste as edit.paste; pasted text takes the default character style (one run) and leaves its character and paragraph styles behind, as do the labels of pasted graphs, which take a new graph's label character style and paragraph attributes (keeping their alignment); a pasted graph no longer keeps its labels' character and paragraph formats, so a later redraw sets them the same way → {ids, added, merged, renamed}",
|
||||
has_clipboard,
|
||||
paste_plain
|
||||
),
|
||||
@@ -1767,15 +1767,12 @@ fn strip_formatting(n: &mut vectorcraft_doc::Node) {
|
||||
t.set_all_paras(Default::default());
|
||||
refresh_bounds(t);
|
||||
}
|
||||
// A graph keeps the names of its labels' character and paragraph styles for each redraw.
|
||||
if let Some(g) = n.extras_if_any().and_then(|e| e.graph.as_deref_mut()) {
|
||||
let l = &mut g.label_styles;
|
||||
for st in [&mut l.values, &mut l.categories, &mut l.legend].into_iter().flatten() {
|
||||
st.style_name = None;
|
||||
}
|
||||
for pa in [&mut l.values_para, &mut l.categories_para, &mut l.legend_para].into_iter().flatten() {
|
||||
pa.style_name = None;
|
||||
}
|
||||
// A graph keeps its labels' character and paragraph formats for each redraw: they go with the
|
||||
// labels' own formatting, and the labels are set in a new graph's label formats. The graph's generated
|
||||
// bounds follow its changed labels, so the next redraw does not read them as a move.
|
||||
if n.extras().graph.is_some() {
|
||||
super::graph::edit_graph_art(n, |n| super::graph::plain_labels(n, &strip_formatting));
|
||||
return;
|
||||
}
|
||||
if let Some(ch) = n.children_mut() {
|
||||
for c in ch.iter_mut() {
|
||||
|
||||
@@ -245,39 +245,92 @@ fn define(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"name": name, "kind": kind.label()}))
|
||||
}
|
||||
|
||||
/// Whether the object `id`, bound to the variable `name`, can stay bound to it once the variable
|
||||
/// is of `kind`: a text variable drives type that holds no other text variable, an image variable
|
||||
/// drives an image object, a graph variable drives a graph root, and a visibility variable drives
|
||||
/// any object. Locks and hidden layers don't count, as they don't unbind anything else either.
|
||||
fn keeps_binding(doc: &Document, id: NodeId, name: &str, kind: VariableKind) -> bool {
|
||||
let Some(n) = doc.node(id) else { return false };
|
||||
match kind {
|
||||
VariableKind::Text => {
|
||||
matches!(n.kind, NodeKind::Text(_))
|
||||
&& !doc.variables.bindings.get(&id).is_some_and(|bound| {
|
||||
doc.variables.variables.iter().any(|v| v.kind == VariableKind::Text && v.name != name && bound.contains(&v.name))
|
||||
})
|
||||
}
|
||||
VariableKind::Visibility => true,
|
||||
VariableKind::Image => matches!(n.kind, NodeKind::Image(_)),
|
||||
VariableKind::Graph => n.extras().graph.is_some(),
|
||||
VariableKind::Unknown => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Variable Options: rename a variable (`newName`), change its kind (`kind`), or both, in one undo
|
||||
/// step, carrying its bindings and its values in every data set to the new name. A kind change
|
||||
/// unbinds the objects that can't hold the new kind ([`keeps_binding`]) and drops the variable's
|
||||
/// value in every data set. A call that changes nothing adds no undo step.
|
||||
fn rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "variable.rename";
|
||||
let from = var_name(p, C)?;
|
||||
let to = named(p.get("newName").and_then(Value::as_str), "newName", C)?;
|
||||
let st = s.doc()?;
|
||||
if st.doc.variables.variable(&from).is_none() {
|
||||
return Err(bad(C, format!("no variable named `{from}`")));
|
||||
// An omitted key is no change; a null, like any other value that isn't a name or a kind, is refused.
|
||||
let to = match p.get("newName") {
|
||||
None => None,
|
||||
Some(v) => Some(named(v.as_str(), "newName", C)?),
|
||||
};
|
||||
let kind = match p.get("kind") {
|
||||
None => None,
|
||||
Some(v) => Some(v.as_str().and_then(VariableKind::parse).ok_or_else(|| bad(C, "`kind` must be `text`, `visibility`, `image` or `graph`"))?),
|
||||
};
|
||||
if to.is_none() && kind.is_none() {
|
||||
return Err(bad(C, "missing `newName` or `kind`"));
|
||||
}
|
||||
if st.doc.variables.variable(&to).is_some() {
|
||||
let doc = &s.doc()?.doc;
|
||||
let Some(old) = doc.variables.variable(&from) else {
|
||||
return Err(bad(C, format!("no variable named `{from}`")));
|
||||
};
|
||||
let to = to.unwrap_or_else(|| from.clone());
|
||||
if to != from && doc.variables.variable(&to).is_some() {
|
||||
return Err(bad(C, format!("variable `{to}` already exists")));
|
||||
}
|
||||
s.edit("Rename Variable", |d, _| {
|
||||
let v = d.variables.variables.iter_mut().find(|v| v.name == from).ok_or_else(|| bad(C, format!("no variable named `{from}`")))?;
|
||||
let kind = kind.unwrap_or(old.kind);
|
||||
let retyped = kind != old.kind;
|
||||
let unbound: Vec<NodeId> =
|
||||
if retyped { doc.variables.objects_of(&from).into_iter().filter(|id| !keeps_binding(doc, *id, &from, kind)).collect() } else { Vec::new() };
|
||||
let label = if retyped { "Variable Options" } else { "Rename Variable" };
|
||||
let dropped = edit_variables(s, label, |vars| {
|
||||
let v = vars.variables.iter_mut().find(|v| v.name == from).ok_or_else(|| bad(C, format!("no variable named `{from}`")))?;
|
||||
v.name = to.clone();
|
||||
for bound in d.variables.bindings.values_mut() {
|
||||
v.kind = kind;
|
||||
for id in &unbound {
|
||||
vars.unbind(*id, &from);
|
||||
}
|
||||
for bound in vars.bindings.values_mut() {
|
||||
if bound.remove(&from) {
|
||||
bound.insert(to.clone());
|
||||
}
|
||||
}
|
||||
for ds in &mut d.variables.datasets {
|
||||
if let Some(value) = ds.values.remove(&from) {
|
||||
ds.values.insert(to.clone(), value);
|
||||
let mut dropped = 0;
|
||||
for ds in &mut vars.datasets {
|
||||
match ds.values.remove(&from) {
|
||||
// A rename alone carries every value, one that doesn't fit the kind included; a kind
|
||||
// change drops them all, as none was given for the new kind.
|
||||
Some(value) if !retyped => {
|
||||
ds.values.insert(to.clone(), value);
|
||||
}
|
||||
Some(_) => dropped += 1,
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
Ok(dropped)
|
||||
})?;
|
||||
// The highlight names a variable, so it follows the rename rather than going stale.
|
||||
// The highlight names a variable, so it follows the rename rather than going stale. A call
|
||||
// that leaves the name as it was leaves the revision alone too.
|
||||
let st = s.doc_mut()?;
|
||||
if st.variables_highlight.as_deref() == Some(from.as_str()) {
|
||||
if to != from && st.variables_highlight.as_deref() == Some(from.as_str()) {
|
||||
st.variables_highlight = Some(to.clone());
|
||||
st.revision += 1;
|
||||
}
|
||||
st.revision += 1;
|
||||
Ok(json!({"from": from, "name": to}))
|
||||
Ok(json!({"from": from, "name": to, "kind": kind.label(), "unbound": unbound.iter().map(|i| i.0).collect::<Vec<_>>(), "droppedValues": dropped}))
|
||||
}
|
||||
|
||||
/// Make Text / Visibility / Image / Graph Dynamic: define a variable of that kind and bind the
|
||||
@@ -330,18 +383,19 @@ fn delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn list(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
let xml_id = s.prefs.identify_objects_by == "xmlId";
|
||||
let st = s.doc()?;
|
||||
let variables: Vec<Value> = st
|
||||
.doc
|
||||
.variables
|
||||
.variables
|
||||
.iter()
|
||||
let vars = &st.doc.variables.variables;
|
||||
let variables: Vec<Value> = variable_order(st, xml_id)
|
||||
.into_iter()
|
||||
.filter_map(|i| vars.get(i))
|
||||
.map(|v| {
|
||||
let bindings = st.doc.variables.objects_of(&v.name).len();
|
||||
json!({"name": v.name, "kind": v.kind.label(), "bindings": bindings})
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({"variables": variables, "locked": st.doc.variables.locked}))
|
||||
let sort = json!({"by": st.variables_sort.by.id(), "descending": st.variables_sort.descending});
|
||||
Ok(json!({"variables": variables, "locked": st.doc.variables.locked, "sort": sort}))
|
||||
}
|
||||
|
||||
/// Lock Variables: without `locked` it toggles. Setting the state the document already has
|
||||
@@ -417,6 +471,120 @@ fn highlight(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"variable": name}))
|
||||
}
|
||||
|
||||
/// The column the Variables panel sorts its list by (`variable.sort`).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum VariableSortKey {
|
||||
/// The order the variables were defined in.
|
||||
#[default]
|
||||
Defined,
|
||||
/// The Variables column: the variable's name.
|
||||
Name,
|
||||
/// The Objects column: the name of the object the variable is bound to.
|
||||
Object,
|
||||
/// The type column: text, image, graph, visibility, then variables of unknown kind.
|
||||
Type,
|
||||
}
|
||||
|
||||
impl VariableSortKey {
|
||||
/// The values `variable.sort` takes for `by`, in the order of [`Self::id`].
|
||||
const IDS: [&'static str; 4] = ["name", "object", "type", "none"];
|
||||
|
||||
/// The value `variable.sort` takes for `by` and `variable.list` reports.
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
Self::Name => "name",
|
||||
Self::Object => "object",
|
||||
Self::Type => "type",
|
||||
Self::Defined => "none",
|
||||
}
|
||||
}
|
||||
|
||||
fn parse(s: &str) -> Option<Self> {
|
||||
match s {
|
||||
"name" => Some(Self::Name),
|
||||
"object" => Some(Self::Object),
|
||||
"type" => Some(Self::Type),
|
||||
"none" => Some(Self::Defined),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How the Variables panel orders its list: a column, and whether the order is reversed. Panel
|
||||
/// state, not saved and not an undo step.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct VariableSort {
|
||||
pub by: VariableSortKey,
|
||||
pub descending: bool,
|
||||
}
|
||||
|
||||
/// The place of a variable's kind in the order the type column sorts by.
|
||||
fn kind_rank(kind: VariableKind) -> u8 {
|
||||
match kind {
|
||||
VariableKind::Text => 0,
|
||||
VariableKind::Image => 1,
|
||||
VariableKind::Graph => 2,
|
||||
VariableKind::Visibility => 3,
|
||||
VariableKind::Unknown => 4,
|
||||
}
|
||||
}
|
||||
|
||||
/// The Variables panel's rows in its sort order, as indices into the document's variables.
|
||||
/// Names compare without regard to case. Sorted by object, a variable bound to nothing comes
|
||||
/// first and one bound to several objects comes after those bound to one; `xml_id` names objects
|
||||
/// by their XML ids, as the panel does with Identify Objects By set to XML ID. Ties go by name.
|
||||
pub fn variable_order(st: &crate::DocState, xml_id: bool) -> Vec<usize> {
|
||||
let vars = &st.doc.variables.variables;
|
||||
let sort = st.variables_sort;
|
||||
let mut order: Vec<usize> = (0..vars.len()).collect();
|
||||
if sort.by != VariableSortKey::Defined {
|
||||
order.sort_by_cached_key(|&i| {
|
||||
let v = &vars[i];
|
||||
let (rank, label) = match sort.by {
|
||||
VariableSortKey::Object => match st.doc.variables.objects_of(&v.name).as_slice() {
|
||||
[] => (0, String::new()),
|
||||
[one] => (1, st.doc.node(*one).map(|n| n.identify_label(xml_id)).unwrap_or_default()),
|
||||
_ => (2, String::new()),
|
||||
},
|
||||
VariableSortKey::Type => (kind_rank(v.kind), String::new()),
|
||||
VariableSortKey::Name | VariableSortKey::Defined => (0, String::new()),
|
||||
};
|
||||
(rank, label.to_lowercase(), label, v.name.to_lowercase(), v.name.clone())
|
||||
});
|
||||
}
|
||||
if sort.descending {
|
||||
order.reverse();
|
||||
}
|
||||
order
|
||||
}
|
||||
|
||||
/// Sort the Variables panel's list. Panel state, like `variable.highlight`: not saved and not an
|
||||
/// undo step. Setting the order the panel already has changes nothing.
|
||||
fn sort(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "variable.sort";
|
||||
let key = "by";
|
||||
let by = match p.get(key) {
|
||||
None => return Err(bad(C, format!("missing `{key}`"))),
|
||||
Some(v) => v
|
||||
.as_str()
|
||||
.and_then(VariableSortKey::parse)
|
||||
.ok_or_else(|| bad(C, format!("`{key}` must be one of {}", VariableSortKey::IDS.join(", "))))?,
|
||||
};
|
||||
// A `descending` that is given must be true or false: null is refused, not read as omitted.
|
||||
let key = "descending";
|
||||
let descending = match p.get(key) {
|
||||
None => false,
|
||||
Some(v) => v.as_bool().ok_or_else(|| bad(C, format!("`{key}` must be true or false")))?,
|
||||
};
|
||||
let sort = VariableSort { by, descending };
|
||||
let st = s.doc_mut()?;
|
||||
if st.variables_sort != sort {
|
||||
st.variables_sort = sort;
|
||||
st.revision += 1;
|
||||
}
|
||||
Ok(json!({"by": by.id(), "descending": descending}))
|
||||
}
|
||||
|
||||
fn dataset_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "dataset.new";
|
||||
let name = var_name(p, C)?;
|
||||
@@ -722,11 +890,19 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Rename Variable",
|
||||
["Window", "Variables"],
|
||||
None,
|
||||
"{name, newName} rename a variable, with its bindings and its values in every dataset; refused while the variables are locked",
|
||||
"{name, newName?, kind?: text|visibility|image|graph} Variable Options: rename a variable, with its bindings and its values in every dataset, change its kind, or both, in one undo step (none when the name and the kind are the ones it has). A kind change unbinds every object that can't hold the new kind (a text variable keeps type that has no other text variable, an image variable keeps image objects, a graph variable keeps graph roots, a visibility variable keeps every object) and drops the variable's values in every dataset; locked and hidden objects keep their binding when they can hold it. Needs `newName` or `kind`, and a null or empty one is refused; refused while the variables are locked → {from, name, kind, unbound: [id…], droppedValues}",
|
||||
variables_unlocked,
|
||||
rename
|
||||
),
|
||||
cmd!(query "variable.list", "List Variables", [], None, "{} → variables with kinds and binding counts, and whether they are locked → {variables, locked}", has_doc, list),
|
||||
cmd!(
|
||||
query "variable.list",
|
||||
"List Variables",
|
||||
[],
|
||||
None,
|
||||
"{} → variables with kinds and binding counts in the Variables panel's order, whether they are locked, and the panel's sort (as variable.sort sets it) → {variables, locked, sort: {by, descending}}",
|
||||
has_doc,
|
||||
list
|
||||
),
|
||||
cmd!(
|
||||
"variable.makeTextDynamic",
|
||||
"Make Text Dynamic",
|
||||
@@ -799,6 +975,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
highlight
|
||||
),
|
||||
cmd!(
|
||||
"variable.sort",
|
||||
"Sort Variables",
|
||||
[],
|
||||
None,
|
||||
"{by: name|object|type|none, descending?: bool} sort the Variables panel's list (a click on a column header) by variable name, by the name of the bound object, or by type (text, image, graph, visibility, then unknown); `none` is the order the variables were defined in, and `descending` reverses the order. Names compare without regard to case; by object, unbound variables come first and variables bound to several objects last, and ties go by name. Panel state: not saved and not an undo step; variable.list reports it → {by, descending}",
|
||||
has_doc,
|
||||
sort
|
||||
),
|
||||
cmd!("dataset.new", "New Data Set…", ["Window", "Variables"], None, "{name, values?: {variable: value}} add a dataset", has_doc, dataset_new),
|
||||
cmd!(
|
||||
"dataset.set",
|
||||
|
||||
@@ -29,6 +29,9 @@ pub struct DocState {
|
||||
/// Bound Object act on. Panel state, not art selection: not saved, not undoable
|
||||
/// (`variable.highlight`). A name, so renaming a variable moves the highlight with it.
|
||||
pub variables_highlight: Option<String>,
|
||||
/// The order of the Variables panel's list: the column it is sorted by, and whether it is
|
||||
/// reversed. Panel state: not saved, not undoable (`variable.sort`).
|
||||
pub variables_sort: cmd::VariableSort,
|
||||
/// Isolation mode container.
|
||||
pub isolation: Option<NodeId>,
|
||||
/// Select › Start Global Edit: the objects edited together until Stop Global Edit or Escape
|
||||
@@ -316,6 +319,7 @@ impl DocState {
|
||||
active_layer,
|
||||
layer_rows: vec![],
|
||||
variables_highlight: None,
|
||||
variables_sort: Default::default(),
|
||||
isolation: None,
|
||||
global_edit: None,
|
||||
similar_outlines: Default::default(),
|
||||
|
||||
@@ -399,6 +399,12 @@ impl ScriptScope {
|
||||
Self { roots: std::fs::canonicalize(dir).ok().into_iter().collect() }
|
||||
}
|
||||
|
||||
/// The scope of a script run from a file in the folder whose real path, with its links already
|
||||
/// followed, is `real`: that folder, which is not looked up again.
|
||||
pub(crate) fn of_real_folder(real: PathBuf) -> Self {
|
||||
Self { roots: vec![real] }
|
||||
}
|
||||
|
||||
/// Is `path` refused by its name alone: a `..` component, a NUL, a Windows device name or
|
||||
/// stream, or a computer on the network?
|
||||
fn refused_by_name(path: &Path) -> bool {
|
||||
|
||||
@@ -308,6 +308,8 @@ fn document_base(s: &Session) -> Value {
|
||||
"key": st.selection.key.map(|k| k.0),
|
||||
// The ruler guide that is the key instead (`select.key {guide}`): an index into `guide.list`.
|
||||
"keyGuide": st.selection.key_guide.and_then(|id| crate::cmd::guide_indexes(d, &[id]).first().copied()),
|
||||
// The anchor point that is the key instead (`select.key {id, anchor}`): {id, anchor}.
|
||||
"keyAnchor": st.selection.key_anchor.map(|(id, (si, ai))| json!({"id": id.0, "anchor": [si, ai]})),
|
||||
"history": st.history.undo.iter().map(|h| h.label.clone()).collect::<Vec<_>>(),
|
||||
"redo": st.history.redo.iter().rev().map(|h| h.label.clone()).collect::<Vec<_>>(),
|
||||
"objects": d.node_count(),
|
||||
|
||||
@@ -30,6 +30,7 @@ pub use cmd::clipboard::{Clipboard, SourceLayer};
|
||||
pub use cmd::create::constrain_click;
|
||||
pub use cmd::distortcmds::perspective_click;
|
||||
pub use cmd::flare::flare_settings;
|
||||
pub use cmd::graph::{GraphTypeSubject, calculated_axes as graph_calculated_axes, graph_type_subject};
|
||||
pub use cmd::params::{check_keys, check_params};
|
||||
pub use cmd::pathops::auto_simplify_level;
|
||||
pub use cmd::rasterfx::{export_pdf, flatten_raster_effects};
|
||||
@@ -245,6 +246,8 @@ pub struct Session {
|
||||
/// keyboard: those files, and the files they link to, are read under these roots, so a queue
|
||||
/// an agent loaded never reads beyond what it was given.
|
||||
pub(crate) place_queue_roots: Option<std::sync::Arc<file_access::AutomationRoots>>,
|
||||
/// How many times the place cursor has been loaded ([`Session::place_queue_loads`]).
|
||||
pub(crate) place_queue_loads: u64,
|
||||
/// While [`Session::import_image_read`] runs `clipboard.importImage`: the image read for it,
|
||||
/// which the command loads instead of reading `dataBase64`; `None` otherwise.
|
||||
pub(crate) image_hand_off: Option<cmd::clipboard::ImageRead>,
|
||||
@@ -345,6 +348,9 @@ pub struct Session {
|
||||
/// The Global Edit Options Start Global Edit matches with (`select.globalEditOptions`); not
|
||||
/// saved.
|
||||
pub global_edit_options: cmd::globaledit::Options,
|
||||
/// The attribute Select Similar Objects selects by (`select.similar`), one of
|
||||
/// [`cmd::SIMILAR`]; not saved.
|
||||
pub select_similar: &'static str,
|
||||
/// Set while [`Session::tool_typed_text`] passes keyboard input to the active tool
|
||||
/// ([`vectorcraft_tools::ToolContext::typed_from_keyboard`]).
|
||||
keyboard_text: bool,
|
||||
|
||||
@@ -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`]
|
||||
|
||||
@@ -295,12 +295,14 @@ fn display(path: &Path) -> Arc<str> {
|
||||
|
||||
impl Files {
|
||||
/// The files of a run of the script at `path` (`None` for a script given as text), with the
|
||||
/// `JSINCLUDE` folders `jsinclude`.
|
||||
pub(crate) fn new(path: Option<&str>, jsinclude: Vec<PathBuf>) -> Self {
|
||||
let real = path.and_then(|p| std::fs::canonicalize(p).ok());
|
||||
/// `JSINCLUDE` folders `jsinclude`. `checked` is the script's real path when the read of its text
|
||||
/// found it, which the run's folder then comes from; without it, `path` is looked up.
|
||||
pub(crate) fn new(path: Option<&str>, checked: Option<PathBuf>, jsinclude: Vec<PathBuf>) -> Self {
|
||||
let scope_of_checked = checked.as_deref().and_then(Path::parent).map(|d| ScriptScope::of_real_folder(d.to_path_buf()));
|
||||
let real = checked.or_else(|| path.and_then(|p| std::fs::canonicalize(p).ok()));
|
||||
let dir = real.as_deref().and_then(folder_of);
|
||||
Self {
|
||||
scope: dir.as_deref().map(ScriptScope::of_folder).unwrap_or_default(),
|
||||
scope: scope_of_checked.or_else(|| dir.as_deref().map(ScriptScope::of_folder)).unwrap_or_default(),
|
||||
jsinclude,
|
||||
include_path: Vec::new(),
|
||||
files: 0,
|
||||
|
||||
@@ -163,6 +163,9 @@ pub(crate) struct Request {
|
||||
pub name_given: bool,
|
||||
/// The file the script was read from, which its included files are read beside.
|
||||
pub file: Option<String>,
|
||||
/// The real path of `file` as the read of `source` found it, which the included files are then
|
||||
/// read beside instead of looking `file` up again.
|
||||
pub checked_real: Option<std::path::PathBuf>,
|
||||
pub source: String,
|
||||
pub args: Map<String, Value>,
|
||||
pub fuel: u64,
|
||||
@@ -429,7 +432,7 @@ struct World {
|
||||
}
|
||||
|
||||
/// The choices outside the documents that a script's commands can change: the preferences, the
|
||||
/// global edit options, the recent URLs, the chosen gradient stop, freeform point and appearance
|
||||
/// global edit options, the Select Similar Objects attribute, the recent URLs, the chosen gradient stop, freeform point and appearance
|
||||
/// item, the Eyedropper's sample, the envelope defaults and the Caps Lock state.
|
||||
#[derive(Clone)]
|
||||
struct Choices {
|
||||
@@ -437,6 +440,7 @@ struct Choices {
|
||||
caps_lock: bool,
|
||||
eyedropper_sample: Option<Arc<vectorcraft_doc::Node>>,
|
||||
global_edit_options: cmd::globaledit::Options,
|
||||
select_similar: &'static str,
|
||||
recent_urls: Vec<String>,
|
||||
gradient_stop: Option<(usize, cmd::gradient::StopOwner)>,
|
||||
freeform_point: Option<(usize, cmd::gradient::StopOwner)>,
|
||||
@@ -451,6 +455,7 @@ impl Choices {
|
||||
caps_lock: s.caps_lock,
|
||||
eyedropper_sample: s.eyedropper_sample.clone(),
|
||||
global_edit_options: s.global_edit_options.clone(),
|
||||
select_similar: s.select_similar,
|
||||
recent_urls: s.recent_urls.clone(),
|
||||
gradient_stop: s.gradient_stop,
|
||||
freeform_point: s.freeform_point,
|
||||
@@ -464,6 +469,7 @@ impl Choices {
|
||||
s.caps_lock = self.caps_lock;
|
||||
s.eyedropper_sample = self.eyedropper_sample;
|
||||
s.global_edit_options = self.global_edit_options;
|
||||
s.select_similar = self.select_similar;
|
||||
s.recent_urls = self.recent_urls;
|
||||
s.gradient_stop = self.gradient_stop;
|
||||
s.freeform_point = self.freeform_point;
|
||||
@@ -477,6 +483,7 @@ impl Choices {
|
||||
swap(&mut self.caps_lock, &mut s.caps_lock);
|
||||
swap(&mut self.eyedropper_sample, &mut s.eyedropper_sample);
|
||||
swap(&mut self.global_edit_options, &mut s.global_edit_options);
|
||||
swap(&mut self.select_similar, &mut s.select_similar);
|
||||
swap(&mut self.recent_urls, &mut s.recent_urls);
|
||||
swap(&mut self.gradient_stop, &mut s.gradient_stop);
|
||||
swap(&mut self.freeform_point, &mut s.freeform_point);
|
||||
@@ -1814,7 +1821,7 @@ impl Session {
|
||||
self.script_high_water.retain(|uid, _| open.contains(uid));
|
||||
self.script_stop.clear();
|
||||
self.script_report = None;
|
||||
let mut files = include::Files::new(request.file.as_deref(), include::Files::jsinclude_env());
|
||||
let mut files = include::Files::new(request.file.as_deref(), request.checked_real, include::Files::jsinclude_env());
|
||||
let expanded = files.expand_script(&request.source);
|
||||
let name = match &expanded {
|
||||
Ok(include::Expanded { name: Some(name), .. }) if !request.name_given => name.clone(),
|
||||
|
||||
@@ -113,6 +113,7 @@ impl Session {
|
||||
place_hand_off: None,
|
||||
queue_hand_off: None,
|
||||
place_queue_roots: None,
|
||||
place_queue_loads: 0,
|
||||
image_hand_off: None,
|
||||
trace_hand_off: None,
|
||||
place_cursor_requests: false,
|
||||
@@ -141,6 +142,7 @@ impl Session {
|
||||
link_stamps: Default::default(),
|
||||
link_scan: None,
|
||||
global_edit_options: Default::default(),
|
||||
select_similar: crate::cmd::SIMILAR[0].0,
|
||||
keyboard_text: false,
|
||||
script_key: None,
|
||||
script_engines: crate::script::EnginesKey::new(),
|
||||
|
||||
@@ -86,6 +86,7 @@ mod inline;
|
||||
mod interactivity;
|
||||
mod intertwine;
|
||||
mod journal;
|
||||
mod keyanchor;
|
||||
mod keyguide;
|
||||
mod knockout;
|
||||
mod labspots;
|
||||
@@ -1544,6 +1545,7 @@ fn shape_commands_refuse_a_number_or_boolean_given_as_text() {
|
||||
("shape.flare", json!({"cx": 100, "cy": 100, "x2": "300", "y2": 300}), "x2"),
|
||||
("shape.flare", with(&flare, "direction", json!("45")), "direction"),
|
||||
("shape.flare", with(&flare, "seed", json!("7")), "seed"),
|
||||
("shape.flare", with(&flare, "ringSeed", json!("7")), "ringSeed"),
|
||||
("shape.spiral", with(&spiral, "decay", json!("80")), "decay"),
|
||||
("shape.spiral", with(&spiral, "segments", json!("10")), "segments"),
|
||||
]
|
||||
@@ -2131,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);
|
||||
}
|
||||
@@ -2166,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);
|
||||
}
|
||||
|
||||
@@ -2225,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");
|
||||
@@ -3390,6 +3392,70 @@ fn edit_flare_keeps_its_parts_pixel_alignment() {
|
||||
assert!(aligned(&s, off).iter().all(|a| !*a));
|
||||
}
|
||||
|
||||
/// `shape.flare`'s `ringSeed` places the rings along the path anew and keeps their count and
|
||||
/// sizes and the other parts; the same `ringSeed` draws the same flare, neighboring ones differ,
|
||||
/// and a seed that is not a whole number of at least 0 (for `ringSeed`, below 2^53) is refused.
|
||||
#[test]
|
||||
fn flare_ring_seed_moves_only_the_rings() {
|
||||
let mut s = session();
|
||||
let parts = |s: &mut Session, ring_seed: Option<u64>| {
|
||||
let mut p = json!({"cx": 200, "cy": 200, "diameter": 60, "rays": 9, "rings": 6, "x2": 400, "y2": 300, "seed": 3});
|
||||
if let Some(r) = ring_seed {
|
||||
p["ringSeed"] = json!(r);
|
||||
}
|
||||
let id = NodeId(s.execute("shape.flare", &p).unwrap()["id"].as_u64().unwrap());
|
||||
let NodeKind::Group { children, .. } = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("flare is a group") };
|
||||
children.iter().map(|c| (c.name.clone(), c.geometric_bounds().unwrap())).collect::<Vec<_>>()
|
||||
};
|
||||
let plain = parts(&mut s, None);
|
||||
let placed = parts(&mut s, Some(11));
|
||||
assert_eq!(placed, parts(&mut s, Some(11)));
|
||||
assert_eq!(plain.len(), placed.len());
|
||||
let mut moved = 0;
|
||||
for ((name, a), (_, b)) in plain.iter().zip(&placed) {
|
||||
if name.as_deref() == Some("Ring") {
|
||||
assert!((a.width() - b.width()).abs() < 1e-9, "a ring keeps its size");
|
||||
moved += usize::from(a.center().distance(b.center()) > 1e-6);
|
||||
} else {
|
||||
assert_eq!(a, b, "{name:?}");
|
||||
}
|
||||
}
|
||||
assert_eq!(moved, 6, "every ring moves");
|
||||
assert_ne!(parts(&mut s, Some(0)), parts(&mut s, Some(1)), "neighboring seeds place the rings differently");
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
for bad in [json!(-1), json!(2.5), json!(true), json!(1u64 << 53)] {
|
||||
assert!(s.execute("shape.flare", &json!({"cx": 0, "cy": 0, "ringSeed": bad})).is_err(), "{bad}");
|
||||
}
|
||||
for bad in [json!(-1), json!(2.5), json!(true)] {
|
||||
assert!(s.execute("shape.flare", &json!({"cx": 0, "cy": 0, "seed": bad})).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
}
|
||||
|
||||
/// Through the session, Ctrl/Cmd in the Flare tool's center drag keeps the center's size while the
|
||||
/// drag sizes the halo, and the flare drawn keeps both.
|
||||
#[test]
|
||||
fn flare_tool_ctrl_keeps_the_center_while_the_drag_sizes_the_halo() {
|
||||
let mut s = session();
|
||||
let v = ViewInfo::default();
|
||||
let cmd = vectorcraft_tools::Mods { cmd: true, ..Default::default() };
|
||||
s.select_tool("flare", v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 240.0, 200.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 200.0).with_mods(cmd), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 200.0).with_mods(cmd), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 500.0, 400.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 500.0, 400.0), v).unwrap();
|
||||
let st = s.doc().unwrap();
|
||||
let g = st.doc.node(st.selection.objects[0]).unwrap();
|
||||
let NodeKind::Group { children, .. } = &g.kind else { panic!("flare is a group") };
|
||||
let width = |name: &str| children.iter().find(|c| c.name.as_deref() == Some(name)).unwrap().geometric_bounds().unwrap().width();
|
||||
// The center as the key found it (80); the halo as a 160-point center with 20 % growth would
|
||||
// have it: 80 × 1.2 × 1.6 = 153.6 radius.
|
||||
assert!((width("Center") - 80.0).abs() < 0.5, "{}", width("Center"));
|
||||
assert!((width("Halo") - 2.0 * 153.6).abs() < 0.5, "{}", width("Halo"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reshape_moves_the_grabbed_point_and_its_neighbourhood() {
|
||||
let mut s = session();
|
||||
@@ -3437,7 +3503,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.
|
||||
|
||||
@@ -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(" "));
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -1002,6 +1002,105 @@ fn brush_freehand_refuses_a_brush_or_style_it_cannot_use() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A `brush.freehand` call outside an interaction draws the path and paints it with the brush in
|
||||
/// one undo step: one Undo removes the path and gives back the earlier selection, and one Redo
|
||||
/// brings back the brushed path. Continuing a path with a brush is one step too.
|
||||
#[test]
|
||||
fn brush_freehand_direct_call_has_one_undo_step() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[a]);
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let r = s.execute("brush.freehand", &json!({"points": [[10, 10], [60, 40], [120, 10]], "style": "brush", "brush": "Charcoal"})).unwrap();
|
||||
let id = NodeId(r["id"].as_u64().unwrap());
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step");
|
||||
assert_eq!(brush_of(&s, id).as_deref(), Some("Charcoal"));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(*s.doc().unwrap().doc == *before, "one Undo removes the brushed path");
|
||||
assert_eq!(selected(&s), [a], "Undo gives back the earlier selection");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(brush_of(&s, id).as_deref(), Some("Charcoal"), "Redo brings back the brush");
|
||||
assert_eq!(selected(&s), [id]);
|
||||
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let p = json!({"points": [[120, 10], [160, 60], [200, 10]], "extend": {"id": id.0, "end": "end"}, "brush": "Dots"});
|
||||
assert_eq!(s.execute("brush.freehand", &p).unwrap()["id"], json!(id.0));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "continuing is one undo step");
|
||||
assert_eq!(brush_of(&s, id).as_deref(), Some("Dots"));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(brush_of(&s, id).as_deref(), Some("Charcoal"), "one Undo takes back the stroke and its brush");
|
||||
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("brush.freehand", &json!({"points": [[10, 100], [60, 140], [120, 100]], "style": "pencil", "brush": "Charcoal"})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
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");
|
||||
}
|
||||
|
||||
/// `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
|
||||
/// drawn as `path.freehand` draws it.
|
||||
#[test]
|
||||
fn brush_freehand_refuses_a_brush_on_a_path_without_a_stroke() {
|
||||
let mut s = session();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
let drawn = json!([[10, 10], [60, 20], [90, 80], [20, 90]]);
|
||||
let p = NodeId(s.execute("path.freehand", &json!({"points": drawn, "fill": true})).unwrap()["id"].as_u64().unwrap());
|
||||
assert!(node(&s, p).appearance.stroke_paint().is_none(), "the path has no stroke");
|
||||
// The redraw below replaces a section of the path rather than drawing a new one.
|
||||
let redraw = json!({"points": [[10, 10], [40, 30], [60, 20]], "redraw": {"id": p.0}});
|
||||
assert_eq!(s.execute("path.freehand", &redraw).unwrap()["id"], json!(p.0));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
select(&mut s, &[p]);
|
||||
let extend = json!({"id": p.0, "end": "end"});
|
||||
for (what, mut params) in [
|
||||
("continued", json!({"points": [[20, 90], [0, 120], [-10, 150]], "extend": extend})),
|
||||
("continued by one point", json!({"points": [[20, 90]], "extend": extend})),
|
||||
("redrawn", redraw.clone()),
|
||||
("new filled pencil", json!({"points": [[100, 100], [150, 120], [180, 180]], "style": "pencil", "fill": true})),
|
||||
] {
|
||||
params["brush"] = json!("Charcoal");
|
||||
let (before, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
|
||||
let e = s.execute("brush.freehand", ¶ms).expect_err(&format!("{what}: refused"));
|
||||
assert_eq!(e.to_string(), "invalid parameters for `brush.freehand`: cannot apply brush `Charcoal`: path has no stroke", "{what}");
|
||||
assert!(*s.doc().unwrap().doc == *before, "{what}: the document stays");
|
||||
assert_eq!(selected(&s), [p], "{what}: the selection stays");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{what}: no undo step");
|
||||
}
|
||||
let r = s.execute("brush.freehand", &json!({"points": [[20, 90], [0, 120], [-10, 150]], "extend": extend, "brush": null})).unwrap();
|
||||
assert_eq!(r["id"], json!(p.0));
|
||||
assert_eq!(brush_of(&s, p), None, "without a brush the path is continued as it is");
|
||||
}
|
||||
|
||||
/// `brush.freehand` takes the keys of `path.freehand` and `brush`, and refuses any other key with
|
||||
/// the nearest key it takes, before it draws.
|
||||
#[test]
|
||||
fn brush_freehand_refuses_unknown_keys() {
|
||||
let spec = crate::cmd::find_command("brush.freehand").unwrap();
|
||||
let mut keys = crate::cmd::params::accepted_keys(spec.params).expect("the description names every key");
|
||||
keys.sort_unstable();
|
||||
assert_eq!(keys, ["brush", "closed", "connect", "extend", "fidelity", "fill", "fit", "keepSelected", "points", "redraw", "style"]);
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[a]);
|
||||
let points = json!([[10, 10], [60, 40], [120, 10]]);
|
||||
let (before, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
|
||||
let e = s.execute("brush.freehand", &json!({"points": points, "brsuh": "Charcoal"})).expect_err("a misspelled key is refused");
|
||||
assert!(e.to_string().contains("unknown parameter `brsuh`; did you mean `brush`?"), "{e}");
|
||||
assert!(*s.doc().unwrap().doc == *before, "the document stays");
|
||||
assert_eq!(selected(&s), [a], "the selection stays");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step");
|
||||
let every = json!({
|
||||
"points": points, "fidelity": 2.0, "fit": true, "closed": false, "style": "brush", "fill": false, "keepSelected": true,
|
||||
"extend": null, "connect": null, "redraw": null, "brush": "Charcoal"
|
||||
});
|
||||
let id = NodeId(s.execute("brush.freehand", &every).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(brush_of(&s, id).as_deref(), Some("Charcoal"));
|
||||
}
|
||||
|
||||
/// The Paintbrush skips a brush deleted after it was chosen: a deleted tool brush gives way to
|
||||
/// the document's current brush, and with neither the stroke is drawn without a brush.
|
||||
#[test]
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user