mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-26 23:58:03 +00:00
Merge main into fix/create-outlines-gradient-layout-bounds
This commit is contained in:
@@ -892,6 +892,10 @@ pub use buildcmds::live_paint_gaps;
|
||||
/// Control bar enable it when it changes one).
|
||||
pub use brushsym::reset_transformation_changes;
|
||||
|
||||
/// The byte order of UTF-16 text without a byte-order mark, by Import Data Sets' rule (the Graph
|
||||
/// Data window reads files by it too).
|
||||
pub use variablecmds::utf16_order_without_mark;
|
||||
|
||||
/// 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")];
|
||||
|
||||
@@ -21,6 +21,7 @@ use vectorcraft_geom::{Affine, Point, Rect};
|
||||
use vectorcraft_render::effects;
|
||||
|
||||
use super::super::appearance::series_children_in_paint_order;
|
||||
use super::super::colorcmds::edit_if_changed;
|
||||
use super::super::edit::selected_roots;
|
||||
use super::super::graph::capture_series_object_opacity;
|
||||
use super::super::menucmds::whole_or;
|
||||
@@ -92,7 +93,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Randomize Opacity",
|
||||
["Object", "Plug-ins", "Arrange Tools"],
|
||||
None,
|
||||
"{min?: % 0..100 (30), max?: % 0..100 (100; not less than min), seed?: whole number (0; the same seed, objects and range give the same opacities), ids?: [id…] (default: the selection)} give each selected object (the top-level ones) its own opacity, picked at random and evenly from min to max, as one undo step; it is the object's opacity, as the Transparency panel sets it. On paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw (docs/mcp.md) → {count}",
|
||||
"{min?: % 0..100 (30), max?: % 0..100 (100; not less than min), seed?: whole number (0; the same seed, objects and range give the same opacities), ids?: [id…] (default: the selection)} give each selected object (the top-level ones) its own opacity, picked at random and evenly from min to max, as one undo step (none when no opacity changes); it is the object's opacity, as the Transparency panel sets it. On paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw (docs/mcp.md) → {count}",
|
||||
has_selection,
|
||||
randomize_opacity
|
||||
),
|
||||
@@ -397,7 +398,8 @@ fn randomize_opacity(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Ok(json!({ "count": 0 }));
|
||||
}
|
||||
let (lo, hi) = ((min / 100.0) as f32, (max / 100.0) as f32);
|
||||
s.edit("Randomize Opacity", |d, _| {
|
||||
// A run that gives every object the opacity it has records no undo step.
|
||||
edit_if_changed(s, "Randomize Opacity", |_, d| {
|
||||
let mut changed = vec![];
|
||||
for id in &ids {
|
||||
let o = rng.range(lo, hi);
|
||||
@@ -409,7 +411,7 @@ fn randomize_opacity(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
keep_series_opacity(d, &changed);
|
||||
Ok(())
|
||||
Ok(((), !changed.is_empty()))
|
||||
})?;
|
||||
Ok(json!({ "count": ids.len() }))
|
||||
}
|
||||
@@ -516,16 +518,18 @@ fn sort(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let wanted: Vec<(&Sorted, f64)> = rank.iter().filter_map(|i| items.get(*i)).zip(values).collect();
|
||||
if apply == "opacity" {
|
||||
if wanted.iter().all(|(o, v)| (o.opacity - v).abs() < 1e-6) {
|
||||
// The opacity each object is given, as stored; an object whose stored opacity it already is has not changed.
|
||||
let given: Vec<(NodeId, f32)> = wanted.iter().map(|(o, v)| (o.id, (v / 100.0) as f32)).collect();
|
||||
let changed: Vec<NodeId> = given.iter().filter(|(id, a)| d.node(*id).is_some_and(|n| n.opacity != *a)).map(|(id, _)| *id).collect();
|
||||
if changed.is_empty() {
|
||||
return Ok(count);
|
||||
}
|
||||
s.edit("Sort Objects", |d, _| {
|
||||
for (o, v) in &wanted {
|
||||
if let Some(n) = d.node_mut(o.id) {
|
||||
n.opacity = (v / 100.0) as f32;
|
||||
for (id, a) in &given {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
n.opacity = *a;
|
||||
}
|
||||
}
|
||||
let changed: Vec<NodeId> = wanted.iter().filter(|(o, v)| (o.opacity - v).abs() >= 1e-6).map(|(o, _)| o.id).collect();
|
||||
keep_series_opacity(d, &changed);
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
@@ -393,6 +393,25 @@ fn randomize_opacity_takes_ids_and_leaves_the_rest() {
|
||||
assert_eq!((opacity(&s, g), opacity(&s, a), opacity(&s, b)), (0.2, 1.0, 1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn randomize_opacity_records_no_undo_step_when_no_opacity_changes() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 5.0, 5.0);
|
||||
let b = rect(&mut s, 10.0, 0.0, 5.0, 5.0);
|
||||
select(&mut s, &[a, b]);
|
||||
let n = steps(&s);
|
||||
// Every object already has the one opacity the range allows.
|
||||
let r = s.execute("addon.arrange.randomizeOpacity", &json!({"min": 100, "max": 100})).unwrap();
|
||||
assert_eq!(r["count"], json!(2));
|
||||
assert_eq!(steps(&s), n);
|
||||
assert_eq!((opacity(&s, a), opacity(&s, b)), (1.0, 1.0));
|
||||
s.execute("addon.arrange.randomizeOpacity", &json!({"min": 40, "max": 40})).unwrap();
|
||||
assert_eq!(steps(&s), n + 1);
|
||||
s.execute("addon.arrange.randomizeOpacity", &json!({"min": 40, "max": 40})).unwrap();
|
||||
assert_eq!(steps(&s), n + 1, "the same opacities again");
|
||||
assert_eq!((opacity(&s, a), opacity(&s, b)), (0.4, 0.4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn randomize_opacity_refuses_bad_params() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -45,7 +45,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Break Text",
|
||||
["Object", "Plug-ins", "Artwork Cleanup"],
|
||||
None,
|
||||
"{by?: \"lines\"|\"paragraphs\"|\"words\"|\"glyphs\" (lines), ids?: [id…] (default: the selection)} each horizontal point or area type object becomes point type objects, one per line, paragraph, word or glyph, each where its characters were and with their character styles, as one undo step; spaces between pieces go, a paragraph's lines stay lines (a wrapped line ends in a line break), justified lines close up, and a paragraph broken out whole keeps its bullet (not its number; other pieces have no list markers). Type on a path, vertical type, threaded type and area type whose text doesn't fit stay as they are → {ids (the pieces, selected), skipped}",
|
||||
"{by?: \"lines\"|\"paragraphs\"|\"words\"|\"glyphs\" (lines), ids?: [id…] (default: the selection; the type they name is taken locked or hidden too)} each horizontal point or area type object becomes point type objects, one per line, paragraph, word or glyph, each where its characters were and with their character styles, as one undo step; spaces between pieces go, a paragraph's lines stay lines (a wrapped line ends in a line break), justified lines close up, and a paragraph broken out whole keeps its bullet (not its number; other pieces have no list markers). Type on a path, vertical type, threaded type and area type whose text doesn't fit stay as they are → {ids (the pieces, selected), skipped}",
|
||||
has_selection,
|
||||
break_text
|
||||
),
|
||||
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Combine Point Text",
|
||||
["Object", "Plug-ins", "Artwork Cleanup"],
|
||||
None,
|
||||
"{ids?: [id…] (default: the selection)} merge one-line horizontal point type into as few objects as it can, every glyph staying where it was: pieces turned and sheared alike whose baselines line up (within 0.4 em; the difference becomes baseline shift) join left to right, a space goes between pieces at least half a space apart, and tracking on the character before each piece keeps the spacing; each object keeps its character styles, and the leftmost piece of each run its place and paint, as one undo step → {ids (the objects made, selected), combined (pieces merged into them)}",
|
||||
"{ids?: [id…] (default: the selection; the type they name is taken locked or hidden too)} merge one-line horizontal point type into as few objects as it can, every glyph staying where it was: pieces turned and sheared alike, as visible and as locked (their groups and layers included), whose baselines line up (within 0.4 em; the difference becomes baseline shift) join left to right, a space goes between pieces at least half a space apart, and tracking on the character before each piece keeps the spacing; each object keeps its character styles, and the leftmost piece of each run its place and paint, as one undo step → {ids (the objects made, selected), combined (pieces merged into them)}",
|
||||
has_selection,
|
||||
combine_text
|
||||
),
|
||||
@@ -63,7 +63,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Join Point Text",
|
||||
["Object", "Plug-ins", "Artwork Cleanup"],
|
||||
None,
|
||||
"{ids?: [id…] (default: the selection)} join one-line horizontal point type into one point type object, as one undo step: pieces turned and sheared like the top-left one are read as lines (baselines within 0.4 em of each other), top to bottom, each line's pieces left to right with a space between them; each line becomes a paragraph, left aligned, and keeps the distance between baselines as its leading. The text keeps its character styles; the object takes the top-left piece's place and paint, and the other pieces go → {id (selected), joined (pieces merged into it), lines}",
|
||||
"{ids?: [id…] (default: the selection; the type they name is taken locked or hidden too)} join one-line horizontal point type into one point type object, as one undo step: pieces turned and sheared like the top-left one, and as visible and as locked (their groups and layers included), are read as lines (baselines within 0.4 em of each other), top to bottom, each line's pieces left to right with a space between them; each line becomes a paragraph, left aligned, and keeps the distance between baselines as its leading. The text keeps its character styles; the object takes the top-left piece's place and paint, and the other pieces go → {id (selected), joined (pieces merged into it), lines}",
|
||||
has_selection,
|
||||
join_text
|
||||
),
|
||||
@@ -72,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Remove Breaks",
|
||||
["Object", "Plug-ins", "Artwork Cleanup"],
|
||||
None,
|
||||
"{kind: \"line\"|\"paragraph\", ids?: [id…]} remove the forced line breaks (line) or paragraph returns (paragraph) in the characters selected with a Type tool (after Select All in a frame of threaded text, in the text of every frame of the story), else in all the text of the selected type, as one undo step; a break between two words becomes a space, the frames of a threaded story selected all together being read as one text → {ids, removed}",
|
||||
"{kind: \"line\"|\"paragraph\", ids?: [id…] (the type they name is taken locked or hidden too)} remove the forced line breaks (line) or paragraph returns (paragraph) in the characters selected with a Type tool (after Select All in a frame of threaded text, in the text of every frame of the story), else in all the text of the selected type, as one undo step; a break between two words becomes a space, the frames of a threaded story selected all together being read as one text → {ids, removed}",
|
||||
has_selection,
|
||||
remove_breaks
|
||||
),
|
||||
@@ -90,7 +90,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Set Alignment, Keep Position",
|
||||
["Object", "Plug-ins", "Artwork Cleanup"],
|
||||
None,
|
||||
"{align: \"left\"|\"center\"|\"right\", ids?: [id…] (default: the selection)} align every paragraph of each horizontal point type object so, moving the object so its longest line stays where it is (one line: the text doesn't move), as one undo step → {ids (the objects changed)}",
|
||||
"{align: \"left\"|\"center\"|\"right\", ids?: [id…] (default: the selection; the type they name is taken locked or hidden too)} align every paragraph of each horizontal point type object so, moving the object so its longest line stays where it is (one line: the text doesn't move), as one undo step → {ids (the objects changed)}",
|
||||
has_selection,
|
||||
align_in_place
|
||||
),
|
||||
@@ -99,7 +99,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reset Text Transform",
|
||||
["Object", "Plug-ins", "Artwork Cleanup"],
|
||||
None,
|
||||
"{scale?: bool (false: the horizontal scale stays; true: it goes too, the object's and every character's), ids?: [id…] (default: the selection)} take the rotation, shear and reflection off each point type object, its size and the centre of its text staying, as one undo step → {ids (the objects changed)}",
|
||||
"{scale?: bool (false: the horizontal scale stays; true: it goes too, the object's and every character's), ids?: [id…] (default: the selection; the type they name is taken locked or hidden too)} take the rotation, shear and reflection off each point type object, its size and the centre of its text staying, as one undo step → {ids (the objects changed)}",
|
||||
has_selection,
|
||||
reset_transform
|
||||
),
|
||||
@@ -123,8 +123,17 @@ fn editing_text(s: &Session) -> std::result::Result<(), String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The type objects under `roots` (inside groups and layers, not live art) that can be edited.
|
||||
fn texts_under(d: &Document, roots: &[NodeId]) -> Result<Vec<NodeId>> {
|
||||
/// The type objects a command acts on: those under the objects `ids` names, locked and hidden ones
|
||||
/// included, else those under the selection that can be edited ([`texts_under`]).
|
||||
fn target_texts(s: &Session, p: &Value, command: &str) -> Result<Vec<NodeId>> {
|
||||
let named = p.get("ids").is_some_and(|v| !v.is_null());
|
||||
texts_under(&s.doc()?.doc, &checked_ids_or_selection(s, p, command)?, named)
|
||||
}
|
||||
|
||||
/// The type objects under `roots` (inside groups and layers, not live art). 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 texts_under(d: &Document, roots: &[NodeId], named: bool) -> Result<Vec<NodeId>> {
|
||||
fn visit(n: &Node, out: &mut Vec<NodeId>) {
|
||||
match &n.kind {
|
||||
NodeKind::Text(_) => out.push(n.id),
|
||||
@@ -134,8 +143,13 @@ fn texts_under(d: &Document, roots: &[NodeId]) -> Result<Vec<NodeId>> {
|
||||
}
|
||||
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));
|
||||
if named {
|
||||
let locks = d.locked_artboards();
|
||||
out.retain(|id| !locks.holds_id(*id));
|
||||
} else {
|
||||
let editable = d.editable();
|
||||
out.retain(|id| editable(*id));
|
||||
}
|
||||
out.dedup();
|
||||
if out.len() > MAX_TEXTS {
|
||||
return Err(EngineError::Other("Too many type objects to change at once".into()));
|
||||
@@ -376,7 +390,9 @@ fn replace_with_pieces(s: &mut Session, label: &str, items: Vec<(NodeId, Node, V
|
||||
places.push((id, nodes));
|
||||
}
|
||||
d.insert_beside(places, true)?;
|
||||
sel.set(made.iter().copied());
|
||||
// Pieces of locked or hidden type stay unselected.
|
||||
let editable = d.editable();
|
||||
sel.set(made.iter().copied().filter(|id| editable(*id)));
|
||||
Ok(made.iter().map(|i| i.0).collect())
|
||||
})
|
||||
}
|
||||
@@ -396,7 +412,7 @@ fn break_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let d = &s.doc()?.doc;
|
||||
let (mut items, mut skipped, mut count) = (vec![], vec![], 0);
|
||||
let ids = texts_under(d, &checked_ids_or_selection(s, p, C)?)?;
|
||||
let ids = target_texts(s, p, C)?;
|
||||
let threads = thread_index(d);
|
||||
for id in ids {
|
||||
let (Some(src), Some(node)) = (Source::of(d, id, threads.contains_key(&id)), d.node(id)) else {
|
||||
@@ -450,6 +466,9 @@ fn split_text(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
struct Piece {
|
||||
id: NodeId,
|
||||
t: TextObject,
|
||||
/// Whether the object and every group and layer above it are visible, and whether they are all
|
||||
/// unlocked.
|
||||
state: (bool, bool),
|
||||
/// The object's turn and shear (`xf` without its move).
|
||||
turn: [f64; 4],
|
||||
/// Where its first character's glyph starts on its baseline, in that frame.
|
||||
@@ -487,13 +506,19 @@ impl Piece {
|
||||
if !(at.x.is_finite() && at.y.is_finite() && size > 0.0) {
|
||||
return None;
|
||||
}
|
||||
Some((Self { id, t, turn: [a, b, c, dd], at, end: at.x + end, size, pens }, node))
|
||||
let state = d.ancestry(id)?.iter().filter_map(|i| d.node(*i)).fold((true, true), |(v, u), n| (v && n.visible, u && !n.locked));
|
||||
Some((Self { id, t, state, turn: [a, b, c, dd], at, end: at.x + end, size, pens }, node))
|
||||
}
|
||||
|
||||
/// Whether `o` is turned and sheared alike.
|
||||
fn turned_like(&self, o: &Piece) -> bool {
|
||||
self.turn.iter().zip(&o.turn).all(|(x, y)| (x - y).abs() <= 1e-6 * x.abs().max(y.abs()).max(1.0))
|
||||
}
|
||||
|
||||
/// Whether `o` is turned and sheared alike and has the same `state`.
|
||||
fn joins(&self, o: &Piece) -> bool {
|
||||
self.turned_like(o) && self.state == o.state
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether two objects look alike apart from their text (paint, opacity, blending, effects).
|
||||
@@ -595,15 +620,14 @@ fn merge(chain: &[&Piece]) -> std::result::Result<TextObject, usize> {
|
||||
fn combine_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.cleanup.combineText";
|
||||
let d = &s.doc()?.doc;
|
||||
let mut pieces: Vec<(Piece, &Node)> =
|
||||
texts_under(d, &checked_ids_or_selection(s, p, C)?)?.into_iter().filter_map(|id| Piece::of(d, id)).collect();
|
||||
// Lines: pieces turned alike and looking alike, by baseline, then left to right.
|
||||
let mut pieces: Vec<(Piece, &Node)> = target_texts(s, p, C)?.into_iter().filter_map(|id| Piece::of(d, id)).collect();
|
||||
// Lines: pieces turned alike, as visible and as locked and looking alike, by baseline, then left
|
||||
// to right.
|
||||
pieces.sort_by(|x, y| x.0.at.y.total_cmp(&y.0.at.y).then(x.0.at.x.total_cmp(&y.0.at.x)));
|
||||
let mut lines: Vec<Vec<(&Piece, &Node)>> = vec![];
|
||||
for (piece, node) in &pieces {
|
||||
let fits = |l: &Vec<(&Piece, &Node)>| {
|
||||
l.first()
|
||||
.is_some_and(|(f, n)| f.turned_like(piece) && same_look(n, node) && (f.at.y - piece.at.y).abs() <= SAME_LINE * f.size.min(piece.size))
|
||||
l.first().is_some_and(|(f, n)| f.joins(piece) && same_look(n, node) && (f.at.y - piece.at.y).abs() <= SAME_LINE * f.size.min(piece.size))
|
||||
};
|
||||
match lines.iter_mut().find(|l| fits(l)) {
|
||||
Some(l) => l.push((piece, node)),
|
||||
@@ -672,7 +696,8 @@ fn combine_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
gone.extend(others);
|
||||
}
|
||||
d.remove_many(&gone)?;
|
||||
sel.set(ids.iter().map(|i| NodeId(*i)));
|
||||
let editable = d.editable();
|
||||
sel.set(ids.iter().map(|i| NodeId(*i)).filter(|id| editable(*id)));
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "ids": ids, "combined": combined }))
|
||||
@@ -681,15 +706,15 @@ fn combine_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn join_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.cleanup.joinText";
|
||||
let d = &s.doc()?.doc;
|
||||
let pieces: Vec<Piece> =
|
||||
texts_under(d, &checked_ids_or_selection(s, p, C)?)?.into_iter().filter_map(|id| Piece::of(d, id).map(|p| p.0)).collect();
|
||||
// The piece top-left on the page sets the turn; the others turned like it are read in that frame.
|
||||
let pieces: Vec<Piece> = target_texts(s, p, C)?.into_iter().filter_map(|id| Piece::of(d, id).map(|p| p.0)).collect();
|
||||
// The piece top-left on the page sets the turn; the others turned like it, and as visible and as
|
||||
// locked, are read in that frame.
|
||||
let on_page = |p: &Piece| Affine::new([p.turn[0], p.turn[1], p.turn[2], p.turn[3], 0.0, 0.0]) * p.at;
|
||||
let first = pieces.iter().min_by(|x, y| {
|
||||
let (a, b) = (on_page(x), on_page(y));
|
||||
a.y.total_cmp(&b.y).then(a.x.total_cmp(&b.x))
|
||||
});
|
||||
let mut kept: Vec<&Piece> = first.map(|f| pieces.iter().filter(|p| p.turned_like(f)).collect()).unwrap_or_default();
|
||||
let mut kept: Vec<&Piece> = first.map(|f| pieces.iter().filter(|p| f.joins(p)).collect()).unwrap_or_default();
|
||||
kept.sort_by(|x, y| x.at.y.total_cmp(&y.at.y).then(x.at.x.total_cmp(&y.at.x)));
|
||||
// Lines, top to bottom, by baseline; each line's pieces left to right.
|
||||
let mut lines: Vec<Vec<&Piece>> = vec![];
|
||||
@@ -751,7 +776,7 @@ fn join_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
n.kind = NodeKind::Text(Box::new(m));
|
||||
}
|
||||
d.remove_many(&gone)?;
|
||||
sel.set([id]);
|
||||
sel.set([id].into_iter().filter(|id| d.is_editable(*id)));
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "id": id.0, "joined": joined, "lines": count }))
|
||||
@@ -797,8 +822,8 @@ fn apply_cuts(t: &mut TextObject, cuts: &[(usize, bool)], brk: char) -> usize {
|
||||
|
||||
/// The breaks `brk` in the text of the frames of `story`, read as one text: a break at the end or
|
||||
/// start of a frame between words of the frames on either side becomes a space. Each editable frame
|
||||
/// comes with its own breaks, at its own bytes.
|
||||
fn story_cuts(d: &Document, story: &[NodeId], brk: char) -> Vec<(NodeId, Vec<(usize, bool)>)> {
|
||||
/// (each frame when `all`) comes with its own breaks, at its own bytes.
|
||||
fn story_cuts(d: &Document, story: &[NodeId], brk: char, all: bool) -> Vec<(NodeId, Vec<(usize, bool)>)> {
|
||||
let texts: Vec<(NodeId, String)> = story.iter().filter_map(|id| Some((*id, text_of(d, *id)?.plain_text()))).collect();
|
||||
let joined: String = texts.iter().map(|(_, t)| t.as_str()).collect();
|
||||
// The breaks in story order, handed to the frames in one pass.
|
||||
@@ -811,7 +836,7 @@ fn story_cuts(d: &Document, story: &[NodeId], brk: char) -> Vec<(NodeId, Vec<(us
|
||||
while let Some((at, space)) = cuts.next_if(|(at, _)| *at < end) {
|
||||
own.push((at - start, space));
|
||||
}
|
||||
if d.is_editable(id) {
|
||||
if all || d.is_editable(id) {
|
||||
out.push((id, own));
|
||||
}
|
||||
start = end;
|
||||
@@ -834,31 +859,38 @@ fn remove_breaks(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let d = &s.doc()?.doc;
|
||||
// Each type object with the breaks that go from it.
|
||||
let targets: Vec<(NodeId, Vec<(usize, bool)>)> = match editing {
|
||||
Some(_) if !story.is_empty() => story_cuts(d, &story, brk),
|
||||
Some(_) if !story.is_empty() => story_cuts(d, &story, brk, false),
|
||||
Some((id, a, b)) => vec![(id, a.min(b), a.max(b))]
|
||||
.into_iter()
|
||||
.filter(|(id, ..)| d.is_editable(*id))
|
||||
.filter_map(|(id, a, b)| Some((id, break_cuts(&text_of(d, id)?.plain_text(), a, b, brk))))
|
||||
.collect(),
|
||||
None => {
|
||||
let ids = texts_under(d, &checked_ids_or_selection(s, p, C)?)?;
|
||||
let ids = target_texts(s, p, C)?;
|
||||
// A threaded story whose frames are all among them is read as one text, once.
|
||||
let named: std::collections::HashSet<NodeId> = ids.iter().copied().collect();
|
||||
let threads = thread_index(d);
|
||||
let mut done = std::collections::HashSet::new();
|
||||
// The threads already found not to be a story whose frames are all among them: their
|
||||
// other frames are read one at a time without going through the thread again.
|
||||
let mut partial = std::collections::HashSet::new();
|
||||
let mut out: Vec<(NodeId, Vec<(usize, bool)>)> = vec![];
|
||||
for &id in &ids {
|
||||
if !done.insert(id) {
|
||||
continue;
|
||||
}
|
||||
let story = match threads.get(&id).and_then(|&i| d.text_threads.get(i)) {
|
||||
Some(thread) => crate::cmd::threads::story_in(d, thread, id),
|
||||
let thread = threads.get(&id).copied();
|
||||
let story = match thread.filter(|i| !partial.contains(i)).and_then(|i| d.text_threads.get(i)) {
|
||||
Some(frames) => crate::cmd::threads::story_in(d, frames, id),
|
||||
None => vec![],
|
||||
};
|
||||
if !story.is_empty() && story.iter().all(|f| named.contains(f)) {
|
||||
done.extend(story.iter().copied());
|
||||
out.extend(story_cuts(d, &story, brk));
|
||||
// Every frame is among them, so each one keeps its breaks.
|
||||
out.extend(story_cuts(d, &story, brk, true));
|
||||
} else if let Some(t) = text_of(d, id) {
|
||||
// `id` is type, so the story of its thread is the same for each of its frames.
|
||||
partial.extend(thread);
|
||||
out.push((id, break_cuts(&t.plain_text(), 0, usize::MAX, brk)));
|
||||
}
|
||||
}
|
||||
@@ -891,10 +923,8 @@ fn remove_breaks(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// Horizontal point type among the objects `p` names.
|
||||
fn point_texts(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
|
||||
let d = &s.doc()?.doc;
|
||||
let ids: Vec<NodeId> = texts_under(d, &checked_ids_or_selection(s, p, cmd)?)?
|
||||
.into_iter()
|
||||
.filter(|id| text_of(d, *id).is_some_and(|t| matches!(t.kind, TextKind::Point)))
|
||||
.collect();
|
||||
let ids: Vec<NodeId> =
|
||||
target_texts(s, p, cmd)?.into_iter().filter(|id| text_of(d, *id).is_some_and(|t| matches!(t.kind, TextKind::Point))).collect();
|
||||
if ids.is_empty() {
|
||||
return Err(EngineError::Other("Select point type".into()));
|
||||
}
|
||||
|
||||
@@ -379,6 +379,228 @@ fn remove_breaks_reads_the_threads_once() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove Breaks reads each named frame of a story that is not all named on its own, in the order
|
||||
/// named and each once, as one undo step, and goes through that story's frames once for all of them.
|
||||
#[test]
|
||||
fn remove_breaks_goes_through_a_partly_named_story_once() {
|
||||
for (kind, brk) in [("line", '\u{2028}'), ("paragraph", '\n')] {
|
||||
let mut s = session();
|
||||
let a = text(&mut s, json!({"x": 10, "y": 20, "text": "a\u{2028}b\n".repeat(40), "size": 12, "area": {"width": 150, "height": 60}}));
|
||||
let mut roots = vec![a];
|
||||
for i in 0..4 {
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 100 + 70 * i, "width": 150, "height": 60})).unwrap();
|
||||
roots.push(NodeId(r["id"].as_u64().unwrap()));
|
||||
}
|
||||
select(&mut s, &roots);
|
||||
s.execute("text.thread.create", &json!({})).unwrap();
|
||||
let f = s.doc().unwrap().doc.text_threads[0].clone();
|
||||
assert_eq!(f.len(), 5);
|
||||
let named = [f[4], f[1], f[3]];
|
||||
let breaks: Vec<usize> = named.iter().map(|id| obj(&s, *id).plain_text().matches(brk).count()).collect();
|
||||
assert!(breaks.iter().all(|n| *n > 0), "{kind}: each named frame holds breaks: {breaks:?}");
|
||||
let before = doc_json(&s);
|
||||
let steps = undo_steps(&s);
|
||||
let builds = crate::cmd::threads::story_builds();
|
||||
let r = s.execute("addon.cleanup.removeBreaks", &json!({"kind": kind, "ids": [f[4].0, f[1].0, f[4].0, f[3].0]})).unwrap();
|
||||
assert_eq!(crate::cmd::threads::story_builds() - builds, 1, "{kind}: the story's frames are gone through once");
|
||||
assert_eq!(r["removed"].as_u64(), Some(breaks.iter().sum::<usize>() as u64), "{kind}");
|
||||
assert_eq!(ids(&r), named, "{kind}");
|
||||
assert_eq!(undo_steps(&s), steps + 1, "{kind}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(doc_json(&s), before, "{kind}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Lock `id` (`locked`), else hide it, as an undo step of its own.
|
||||
fn lock_or_hide(s: &mut Session, id: NodeId, locked: bool) {
|
||||
s.edit("Lock or Hide", |d, _| {
|
||||
let n = d.node_mut(id).unwrap();
|
||||
if locked {
|
||||
n.locked = true;
|
||||
} else {
|
||||
n.visible = false;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// Remove Breaks takes the locked and hidden type that `ids` names, and the locked member of a
|
||||
/// group it names, as one undo step; from the selection it takes only type that can be edited, and
|
||||
/// nothing changed makes no undo step.
|
||||
#[test]
|
||||
fn remove_breaks_named_locked_and_hidden_type() {
|
||||
let mut s = session();
|
||||
let locked = text(&mut s, json!({"x": 40, "y": 60, "text": "a\nb", "size": 12}));
|
||||
let hidden = text(&mut s, json!({"x": 40, "y": 120, "text": "c\nd", "size": 12}));
|
||||
let grouped = text(&mut s, json!({"x": 40, "y": 180, "text": "e\nf", "size": 12}));
|
||||
let free = text(&mut s, json!({"x": 40, "y": 240, "text": "g\nh", "size": 12}));
|
||||
select(&mut s, &[grouped, free]);
|
||||
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
lock_or_hide(&mut s, locked, true);
|
||||
lock_or_hide(&mut s, hidden, false);
|
||||
lock_or_hide(&mut s, grouped, true);
|
||||
select(&mut s, &[locked, hidden]);
|
||||
let steps = undo_steps(&s);
|
||||
assert_eq!(other(s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph"}))), "No paragraph breaks to remove");
|
||||
assert_eq!(undo_steps(&s), steps, "the selected locked and hidden type stays as it is");
|
||||
let r = s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph", "ids": [locked.0, hidden.0, group.0]})).unwrap();
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
assert_eq!(r["removed"], 4);
|
||||
for (id, now) in [(locked, "a b"), (hidden, "c d"), (grouped, "e f"), (free, "g h")] {
|
||||
assert_eq!(obj(&s, id).plain_text(), now);
|
||||
}
|
||||
assert_eq!(other(s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph", "ids": [locked.0]}))), "No paragraph breaks to remove");
|
||||
assert_eq!(undo_steps(&s), steps + 1, "nothing changed, no undo step");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(obj(&s, locked).plain_text(), "a\nb");
|
||||
}
|
||||
|
||||
/// A threaded story whose frames `ids` all names is read as one text even when a frame is locked.
|
||||
#[test]
|
||||
fn remove_breaks_named_story_with_a_locked_frame() {
|
||||
let mut s = session();
|
||||
let (a, b) = threaded(&mut s, "one\ntwo");
|
||||
lock_or_hide(&mut s, a, true);
|
||||
let r = s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph", "ids": [a.0, b.0]})).unwrap();
|
||||
assert_eq!(r["removed"], 1);
|
||||
assert_eq!(obj(&s, a).plain_text(), "one two");
|
||||
}
|
||||
|
||||
/// Type on a locked artboard stays as it is even when `ids` names it, with no undo step.
|
||||
#[test]
|
||||
fn remove_breaks_named_type_on_a_locked_artboard() {
|
||||
let mut s = session();
|
||||
let on_board = text(&mut s, json!({"x": 40, "y": 60, "text": "a\nb", "size": 12}));
|
||||
s.edit("Lock Artboard", |d, _| {
|
||||
d.artboards[0].locked = true;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph", "ids": [on_board.0]}));
|
||||
assert_eq!(other(r), "No paragraph breaks to remove");
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
assert_eq!(obj(&s, on_board).plain_text(), "a\nb");
|
||||
}
|
||||
|
||||
/// Break Text, Combine and Join Point Text, Set Alignment, Keep Position and Reset Text Transform
|
||||
/// act on the locked and hidden type that `ids` names (type in a locked layer included), each as
|
||||
/// one undo step, and leave it as it is when it is only selected.
|
||||
#[test]
|
||||
fn named_locked_and_hidden_type() {
|
||||
let mut s = session();
|
||||
let words = text(&mut s, json!({"x": 40, "y": 100, "text": "Two words", "size": 14}));
|
||||
lock_or_hide(&mut s, words, true);
|
||||
select(&mut s, &[words]);
|
||||
assert!(s.execute("addon.cleanup.breakText", &json!({"by": "words"})).is_err());
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cleanup.breakText", &json!({"by": "words", "ids": [words.0]})).unwrap();
|
||||
assert_eq!((ids(&r).len(), undo_steps(&s)), (2, steps + 1));
|
||||
assert!(s.doc().unwrap().selection.objects.is_empty(), "the locked pieces stay unselected");
|
||||
|
||||
let mut s = session();
|
||||
let a = text(&mut s, json!({"x": 50, "y": 100, "text": "Left", "size": 20}));
|
||||
let b = text(&mut s, json!({"x": 110, "y": 100, "text": "Right", "size": 20}));
|
||||
lock_or_hide(&mut s, a, false);
|
||||
lock_or_hide(&mut s, b, false);
|
||||
select(&mut s, &[a, b]);
|
||||
assert!(s.execute("addon.cleanup.combineText", &json!({})).is_err());
|
||||
let r = s.execute("addon.cleanup.combineText", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
assert_eq!(ids(&r), [a]);
|
||||
assert_eq!(obj(&s, a).plain_text(), "Left Right");
|
||||
assert!(s.doc().unwrap().selection.objects.is_empty(), "the hidden object stays unselected");
|
||||
|
||||
let mut s = session();
|
||||
let first = text(&mut s, json!({"x": 50, "y": 100, "text": "First", "size": 20}));
|
||||
let second = text(&mut s, json!({"x": 50, "y": 130, "text": "Second", "size": 20}));
|
||||
let layer = s.doc().unwrap().doc.layers[0].id;
|
||||
lock_or_hide(&mut s, layer, true);
|
||||
select(&mut s, &[first, second]);
|
||||
assert!(s.execute("addon.cleanup.joinText", &json!({})).is_err());
|
||||
let r = s.execute("addon.cleanup.joinText", &json!({"ids": [first.0, second.0]})).unwrap();
|
||||
assert_eq!(r["id"].as_u64(), Some(first.0));
|
||||
assert_eq!(obj(&s, first).plain_text(), "First\nSecond");
|
||||
assert!(s.doc().unwrap().selection.objects.is_empty(), "the object in the locked layer stays unselected");
|
||||
|
||||
let mut s = session();
|
||||
let lines = text(&mut s, json!({"x": 50, "y": 100, "text": "a\nlonger line", "size": 20}));
|
||||
lock_or_hide(&mut s, lines, false);
|
||||
select(&mut s, &[lines]);
|
||||
assert!(s.execute("addon.cleanup.alignInPlace", &json!({"align": "center"})).is_err());
|
||||
s.execute("addon.cleanup.alignInPlace", &json!({"align": "center", "ids": [lines.0]})).unwrap();
|
||||
assert!(obj(&s, lines).para_styles().all(|p| p.justify == Justify::Center));
|
||||
|
||||
let mut s = session();
|
||||
let turned = text(&mut s, json!({"x": 300, "y": 200, "text": "Turned", "size": 18, "rotation": 30}));
|
||||
lock_or_hide(&mut s, turned, true);
|
||||
select(&mut s, &[turned]);
|
||||
assert!(s.execute("addon.cleanup.resetTextTransform", &json!({})).is_err());
|
||||
let steps = undo_steps(&s);
|
||||
s.execute("addon.cleanup.resetTextTransform", &json!({"ids": [turned.0]})).unwrap();
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
let [_, b, c, _, _, _] = obj(&s, turned).xf.as_coeffs();
|
||||
assert!(b.abs() < 1e-9 && c.abs() < 1e-9, "the rotation is gone");
|
||||
}
|
||||
|
||||
/// Combine Point Text joins named pieces only with pieces as visible and as locked, a group's lock
|
||||
/// included: a visible piece and a hidden one beside it, or a free piece and one in a locked group,
|
||||
/// stay as they are, with no undo step.
|
||||
#[test]
|
||||
fn combine_keeps_hidden_and_locked_pieces_apart() {
|
||||
let mut s = session();
|
||||
let a = text(&mut s, json!({"x": 50, "y": 100, "text": "Left", "size": 20}));
|
||||
let b = text(&mut s, json!({"x": 110, "y": 100, "text": "Right", "size": 20}));
|
||||
lock_or_hide(&mut s, b, false);
|
||||
let steps = undo_steps(&s);
|
||||
assert!(s.execute("addon.cleanup.combineText", &json!({"ids": [a.0, b.0]})).is_err());
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
assert_eq!((obj(&s, a).plain_text(), obj(&s, b).plain_text()), ("Left".into(), "Right".into()));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.is_visible(a) && !d.is_visible(b), "the visible text stays shown and the hidden text stays hidden");
|
||||
|
||||
let mut s = session();
|
||||
let a = text(&mut s, json!({"x": 50, "y": 100, "text": "Left", "size": 20}));
|
||||
let b = text(&mut s, json!({"x": 110, "y": 100, "text": "Right", "size": 20}));
|
||||
select(&mut s, &[b]);
|
||||
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
lock_or_hide(&mut s, group, true);
|
||||
let steps = undo_steps(&s);
|
||||
assert!(s.execute("addon.cleanup.combineText", &json!({"ids": [a.0, group.0]})).is_err());
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
assert_eq!((obj(&s, a).plain_text(), obj(&s, b).plain_text()), ("Left".into(), "Right".into()));
|
||||
}
|
||||
|
||||
/// Join Point Text joins only the named pieces as visible and as locked as the top-left one: a
|
||||
/// hidden piece between two visible lines stays as it is, hidden, and a hidden top-left piece
|
||||
/// with only a visible one below it joins nothing, with no undo step.
|
||||
#[test]
|
||||
fn join_keeps_a_hidden_piece_apart() {
|
||||
let mut s = session();
|
||||
let first = text(&mut s, json!({"x": 50, "y": 100, "text": "First", "size": 20}));
|
||||
let hidden = text(&mut s, json!({"x": 50, "y": 130, "text": "Hidden", "size": 20}));
|
||||
let third = text(&mut s, json!({"x": 50, "y": 160, "text": "Third", "size": 20}));
|
||||
lock_or_hide(&mut s, hidden, false);
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cleanup.joinText", &json!({"ids": [first.0, hidden.0, third.0]})).unwrap();
|
||||
assert_eq!((r["id"].as_u64(), r["joined"].as_u64(), undo_steps(&s)), (Some(first.0), Some(2), steps + 1));
|
||||
assert_eq!(obj(&s, first).plain_text(), "First\nThird");
|
||||
assert_eq!(obj(&s, hidden).plain_text(), "Hidden");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.is_visible(first) && !d.is_visible(hidden), "the visible text stays shown and the hidden text stays hidden");
|
||||
assert!(d.node(third).is_none());
|
||||
|
||||
let mut s = session();
|
||||
let top = text(&mut s, json!({"x": 50, "y": 100, "text": "Top", "size": 20}));
|
||||
let below = text(&mut s, json!({"x": 50, "y": 130, "text": "Below", "size": 20}));
|
||||
lock_or_hide(&mut s, top, false);
|
||||
let steps = undo_steps(&s);
|
||||
assert!(s.execute("addon.cleanup.joinText", &json!({"ids": [top.0, below.0]})).is_err());
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
assert_eq!((obj(&s, top).plain_text(), obj(&s, below).plain_text()), ("Top".into(), "Below".into()));
|
||||
assert!(s.doc().unwrap().doc.is_visible(below));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_at_the_cursor_and_around_a_selection() {
|
||||
for (anchor, caret, want) in [(6, 6, &["Split", "here please"][..]), (6, 10, &["Split", "here", "please"][..])] {
|
||||
|
||||
@@ -43,7 +43,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Apply as Filter",
|
||||
["Object", "Plug-ins", "Color Effects"],
|
||||
None,
|
||||
"{effect: a colour adjustment's effect id (adjust.brightnessContrast, adjust.curves, adjust.hueSaturation, adjust.levels, adjust.shiftToColor, adjust.temperatureTint, addon.color.exposure, addon.color.desaturate, addon.color.duotone or addon.color.invert), params?: {…} (as effect.apply; missing keys take the dialog defaults), fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?: [id…] (default: the selection)} recolour the objects and everything inside them as the live effect would draw them, but in their colours, as edit.colors.invert does (fills, strokes, type, gradient meshes, embedded images and pattern tiles), as one undo step (none when nothing changes); their effects stay. Duotone links a colour to its one tone's swatch as the live effect does. On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke (docs/mcp.md) → {changed}",
|
||||
"{effect: a colour adjustment's effect id (adjust.brightnessContrast, adjust.curves, adjust.hueSaturation, adjust.levels, adjust.shiftToColor, adjust.temperatureTint, addon.color.exposure, addon.color.desaturate, addon.color.duotone or addon.color.invert), params?: {…} (as effect.apply; missing keys take the dialog defaults), fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?: [id…] (default: the selection)} recolour the objects and everything inside them as the live effect would draw them, but in their colours, as edit.colors.invert does (fills, strokes, type, gradient meshes, embedded images and pattern tiles), as one undo step (none when nothing changes); their effects stay. Duotone links a colour to its one tone's swatch as the live effect does. 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}",
|
||||
has_selection,
|
||||
filter
|
||||
),
|
||||
@@ -52,7 +52,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Print Ink Fixes",
|
||||
["Object", "Plug-ins", "Color Effects"],
|
||||
None,
|
||||
"{scope?: \"selection\" (the selection, or `ids`; by default, the document while nothing is selected) | \"document\" (every layer), inkLimit?: total ink % 1..400 (0 or left out: off), excludePureBlack?: true (black-only and grey colours keep their ink), removeWhiteOverprint?: false (white fills and strokes stop overprinting), overprintBlack?: black % 1..100 (black-only and grey fills and strokes this dark or darker overprint, as edit.colors.overprintBlack; 0 or left out: off), textOnly?: false (Overprint Black on type only), fill?: true, stroke?: true, ids?: [id…]} prepare a CMYK document's inks for print as one undo step: CMYK colours (solid, gradient stops, gradient meshes) with more total ink than inkLimit are scaled down to it (colours of spot swatches and Registration stay), white overprint is removed and black overprint set. Refused in RGB documents (File › Document Color Mode › CMYK Color first). On a path directly in a graph series, the graph also stores a paint the ink limit changes on the topmost visible fill or stroke (docs/mcp.md) → {changed, inkLimited: paints and meshes scaled, whiteOverprintRemoved: objects, blackOverprinted: objects}",
|
||||
"{scope?: \"selection\" (the selection, or `ids`; by default, the document while nothing is selected) | \"document\" (every layer), inkLimit?: total ink % 1..400 (0 or left out: off), excludePureBlack?: true (black-only and grey colours keep their ink), removeWhiteOverprint?: false (white fills and strokes stop overprinting), overprintBlack?: black % 1..100 (black-only and grey fills and strokes this dark or darker overprint, as edit.colors.overprintBlack; 0 or left out: off), textOnly?: false (Overprint Black on type only), fill?: true, stroke?: true, ids?: [id…]} prepare a CMYK document's inks for print as one undo step: CMYK colours (solid, gradient stops, gradient meshes) with more total ink than inkLimit are scaled down to it (colours of spot swatches and Registration stay), white overprint is removed and black overprint set. Refused in RGB documents (File › Document Color Mode › CMYK Color first). On a path directly in a graph series, the graph also stores a paint the ink limit changes on the topmost visible fill or stroke, and on a graph label the new paint of its characters and rows for every label of its kind (docs/mcp.md) → {changed, inkLimited: paints and meshes scaled, whiteOverprintRemoved: objects, blackOverprinted: objects}",
|
||||
has_doc,
|
||||
print_fixes::run
|
||||
),
|
||||
@@ -70,7 +70,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Apply Nearest Swatch",
|
||||
["Object", "Plug-ins", "Color Effects"],
|
||||
None,
|
||||
"{library?: as addon.color.nearestSwatch (default: \"document\"), fill?: true, stroke?: true, ids?: [id…] (default: the selection)} give each solid colour and gradient stop of the selected objects' fills and strokes (their type's and those of the objects inside them; gradient meshes too) the colour of its nearest swatch in the library, as addon.color.nearestSwatch finds it, as one undo step (none when nothing changes): a global or spot swatch's colour links to it. A library's swatches the colours take are added to the document's first, as swatch.library.add adds them (a spot colour stays spot); images and patterns keep their colours. On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke (docs/mcp.md) → {changed: paints changed, swatches: [the document swatches the colours took], added: [swatches added to the document]}",
|
||||
"{library?: as addon.color.nearestSwatch (default: \"document\"), fill?: true, stroke?: true, ids?: [id…] (default: the selection)} give each solid colour and gradient stop of the selected objects' fills and strokes (their type's and those of the objects inside them; gradient meshes too) the colour of its nearest swatch in the library, as addon.color.nearestSwatch finds it, as one undo step (none when nothing changes): a global or spot swatch's colour links to it. A library's swatches the colours take are added to the document's first, as swatch.library.add adds them (a spot colour stays spot); images and patterns keep their colours. 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: paints changed, swatches: [the document swatches the colours took], added: [swatches added to the document]}",
|
||||
has_selection,
|
||||
nearest::apply
|
||||
),
|
||||
|
||||
@@ -320,7 +320,8 @@ fn fresh(doc: &Document, n: &Node, cmd: &str) -> Option<Result<(ColorMask, Optio
|
||||
|
||||
/// After an edit from `before` (`None`: everything is new, as after a document's links are read):
|
||||
/// the color masks of images in `doc`'s art ([`Document::art_roots`]: layers, symbols, graph
|
||||
/// designs, patterns and the original of the pattern being edited, opacity mask art included)
|
||||
/// designs, patterns, the original of the pattern being edited and the art of the stored brushes
|
||||
/// while it is set on the document, opacity mask art included)
|
||||
/// whose own pixels were replaced are made again for the new pixels ([`Refresh::made`]). Only the
|
||||
/// art that changed since `before` is looked at.
|
||||
pub(crate) fn refresh(before: Option<&Document>, doc: &mut Document) {
|
||||
|
||||
@@ -529,9 +529,11 @@ fn require_targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
|
||||
|
||||
/// One undo step (`label`) running `f` on each of `ids` with the item a fill (`fill`) or stroke
|
||||
/// edit aimed at `item` changes there (`None`: the topmost one; text then edits its characters).
|
||||
/// What the edit changes on the topmost visible fill and stroke of graph series marks is stored on
|
||||
/// their graphs in the same step ([`capture_series_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.
|
||||
/// What the edit changes on the topmost visible fill and stroke of graph series marks, and on the
|
||||
/// rows and characters of graph labels, is stored on their graphs in the same step
|
||||
/// ([`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.
|
||||
pub(crate) fn edit_items(
|
||||
s: &mut Session,
|
||||
ids: &[NodeId],
|
||||
@@ -541,7 +543,12 @@ pub(crate) fn edit_items(
|
||||
fill: bool,
|
||||
f: impl FnMut(&mut Node, Option<usize>) -> Result<()>,
|
||||
) -> Result<()> {
|
||||
edit_items_then(s, ids, item, cmd, label, fill, f, |before, d, edited| Ok(capture_series_changes(before, d, edited)))
|
||||
edit_items_then(s, ids, item, 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);
|
||||
Ok(series || labels)
|
||||
})
|
||||
}
|
||||
|
||||
/// [`edit_items`], then `after` on the document as it was before the edit, the edited document and
|
||||
|
||||
@@ -6,8 +6,8 @@ use vectorcraft_doc::Scaling;
|
||||
use vectorcraft_geom::{Rect, Vec2};
|
||||
|
||||
use super::object::choice;
|
||||
use super::panelcmds::{artboard_index, artboards_art, locked_and_hidden, named_or_selected, note_artboards};
|
||||
use super::{Affine, CommandSpec, NodeId, Result, Session, bad, check_switches, cmd, has_doc, switch_or};
|
||||
use super::panelcmds::{artboard_at, artboards_art, locked_and_hidden, named_or_selected, note_artboards, on_board};
|
||||
use super::{Affine, CommandSpec, NodeId, Result, Session, bad, check_switches, cmd, has_doc, index, switch_or};
|
||||
use crate::EngineError;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -63,13 +63,7 @@ fn boards(s: &mut Session, p: &Value, cmd: &str) -> Result<Boards> {
|
||||
check_switches(p, &["patterns"], cmd)?;
|
||||
let to_artboard = choice(p, cmd, "to", &["selection", "artboard"])? == Some("artboard");
|
||||
let indices = named_or_selected(s, p, cmd)?;
|
||||
let given = |key: &str| -> Result<Option<usize>> {
|
||||
match p.get(key).filter(|v| !v.is_null()) {
|
||||
Some(v) => artboard_index(&s.doc()?.doc, &json!({ "index": v }), cmd).map(Some),
|
||||
None => Ok(None),
|
||||
}
|
||||
};
|
||||
let (named, recorded) = (given("artboard")?, given("activeArtboard")?);
|
||||
let (named, recorded) = (artboard_at(&s.doc()?.doc, p, "artboard", cmd)?, artboard_at(&s.doc()?.doc, p, "activeArtboard", cmd)?);
|
||||
let move_art = switch_or(p, "moveArt", s.tool_options_of("artboard")["moveArt"].as_bool().unwrap_or(true), cmd)?;
|
||||
let locked_art = locked_and_hidden(s, p, move_art, cmd)?;
|
||||
note_artboards(s, p, &indices);
|
||||
@@ -78,8 +72,8 @@ fn boards(s: &mut Session, p: &Value, cmd: &str) -> Result<Boards> {
|
||||
(false, _) => None,
|
||||
(true, Some(i)) => Some(i),
|
||||
(true, None) => {
|
||||
let active = s.tool_options_of("artboard")["active"].clone();
|
||||
Some(artboard_index(&s.doc()?.doc, &json!({ "index": active }), cmd)?)
|
||||
let active = s.tool_options_of("artboard")["active"].as_u64().map(index);
|
||||
Some(active.map_or_else(|| Err(EngineError::Other("no such artboard".into())), |i| on_board(&s.doc()?.doc, i))?)
|
||||
}
|
||||
};
|
||||
if let Some(i) = reference.filter(|_| named.is_none()) {
|
||||
|
||||
@@ -180,7 +180,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Paintbrush",
|
||||
[],
|
||||
None,
|
||||
"{…params as path.freehand, brush} paint a freehand stroke with a brush → {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, or a `style` other than \"pencil\" or \"brush\", is an error and nothing is drawn → {id}",
|
||||
has_doc,
|
||||
brush_freehand
|
||||
),
|
||||
|
||||
@@ -729,8 +729,21 @@ 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.
|
||||
pub(super) fn brush_freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = str_param(p, "brush").map(str::to_string).filter(|n| s.doc().is_ok_and(|st| brush::find(&st.doc, n).is_some()));
|
||||
const C: &str = "brush.freehand";
|
||||
let name = match crate::cmd::text_param(p, "brush", C)? {
|
||||
None => None,
|
||||
Some(n) if brush::find(&s.doc()?.doc, n).is_some() => Some(n.to_string()),
|
||||
Some(n) => return Err(bad(C, format!("no brush named `{n}`"))),
|
||||
};
|
||||
match p.get("style") {
|
||||
None | Some(Value::Null) => {}
|
||||
Some(v) if matches!(v.as_str(), Some("pencil" | "brush")) => {}
|
||||
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) };
|
||||
|
||||
@@ -99,7 +99,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Expand",
|
||||
["Object", "Live Paint"],
|
||||
None,
|
||||
"{id?, ids?: [id…] (instead of id)} turn Live Paint groups into plain groups of their painted faces and edges → {ids}",
|
||||
"{id?, ids?: [id…] (instead of id)} turn Live Paint groups into plain groups of the faces and edges that draw, with all their fill and stroke rows: a shown face or edge with an opacity above 0 and a shown fill or stroke row that has paint and an opacity above 0 (a stroke also a weight above 0), whichever row is on top → {ids}",
|
||||
has_selection_or_ids,
|
||||
lp_expand
|
||||
),
|
||||
@@ -135,7 +135,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Live Paint Info",
|
||||
[],
|
||||
None,
|
||||
"{group, id?: object id (default: the selection)} → {faces: [{id, fill, bounds}], edges: [{id, stroke, width}], sources, gapOptions: {detect, size: \"small\"|\"medium\"|\"large\"|pt, points, color: #rrggbb} (as livePaint.gapOptions sets them), gaps: [[x0,y0,x1,y1]…] (as livePaint.gapOptions returns them)}",
|
||||
"{group?|id?: Live Paint group id (one required; id is read when group is left out)} → {faces: [{id, fill (top fill), bounds, appearance: [row…]}], edges: [{id, stroke (top stroke), width (top stroke's), appearance: [row…]}], where a row is {index (in the part's fill and stroke stack, bottom first), kind: \"fill\"|\"stroke\", paint, opacity: 0..1, visible, width?: pt (strokes only), drawn (the part is shown with opacity above 0, and the row is shown, has paint and opacity above 0, a stroke also width above 0)}, sources, gapOptions: {detect, size: \"small\"|\"medium\"|\"large\"|pt, points, color: #rrggbb} (as livePaint.gapOptions sets them), gaps: [[x0,y0,x1,y1]…] (as livePaint.gapOptions returns them)}",
|
||||
has_doc,
|
||||
lp_info
|
||||
),
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
use super::{
|
||||
Appearance, Arc, Beside, Document, EDGE_NAME, EngineError, FACE_NAME, GapOptions, GapSize, LIVE_PAINT_NAME, Node, NodeId, Paint, PathData, Point,
|
||||
Rect, Result, SOURCES_NAME, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite, ids_json, is_live_paint,
|
||||
json, number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids, source_nodes, source_shapes, switch_or,
|
||||
Appearance, AppearanceItem, Arc, Beside, Document, EDGE_NAME, EngineError, FACE_NAME, GapOptions, GapSize, LIVE_PAINT_NAME, Node, NodeId,
|
||||
PathData, Point, Rect, Result, SOURCES_NAME, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite, ids_json,
|
||||
is_live_paint, json, number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids, source_nodes, source_shapes,
|
||||
switch_or,
|
||||
};
|
||||
|
||||
/// `options` as stored on a Live Paint group: none for the defaults.
|
||||
@@ -84,6 +85,35 @@ pub(super) fn lp_make(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "id": id.0, "faces": faces, "edges": edges }))
|
||||
}
|
||||
|
||||
/// What Merge carries from a face or edge to the part it makes again in its place, another path:
|
||||
/// the appearance, visibility, opacity and blending mode. Gradients fitted to the old outline keep
|
||||
/// that fit, and the strokes' pen pressure, tilt, bearing and rotation stay behind.
|
||||
struct Carried {
|
||||
appearance: Appearance,
|
||||
visible: bool,
|
||||
opacity: f32,
|
||||
blend: vectorcraft_color::BlendMode,
|
||||
}
|
||||
|
||||
impl Carried {
|
||||
fn of(n: &Node) -> Self {
|
||||
let mut appearance = (*n.appearance).clone().without_pressure();
|
||||
if appearance.has_unplaced_gradient()
|
||||
&& let Some(bounds) = n.geometric_bounds()
|
||||
{
|
||||
appearance.pin_gradients(bounds);
|
||||
}
|
||||
Self { appearance, visible: n.visible, opacity: n.opacity, blend: n.blend }
|
||||
}
|
||||
|
||||
fn onto(self, n: &mut Node) {
|
||||
n.appearance = self.appearance.into();
|
||||
n.visible = self.visible;
|
||||
n.opacity = self.opacity;
|
||||
n.blend = self.blend;
|
||||
}
|
||||
}
|
||||
|
||||
/// Add the other `roots` (back → front) to the first Live Paint group among them, which keeps its
|
||||
/// id, the paint of its faces and edges, and its own properties apart from the Gap Options, which
|
||||
/// are merged; returns (group, faces, edges).
|
||||
@@ -95,18 +125,16 @@ fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result
|
||||
.ok_or_else(|| EngineError::Other("Live Paint Merge: select a Live Paint group and the paths to add".into()))?;
|
||||
check_live_paint_takes(d, roots)?;
|
||||
let old = d.node(target).cloned().ok_or(EngineError::NoNode(target))?;
|
||||
// Paint to carry over: (point inside face, fill) and (point on edge, stroke).
|
||||
let keep_faces: Vec<(Point, Paint)> = b::faces(&old)
|
||||
.iter()
|
||||
.filter(|f| !f.appearance.fill_paint().is_none())
|
||||
.filter_map(|f| Some((po::interior_point(f.path_data()?)?, f.appearance.fill_paint())))
|
||||
.collect();
|
||||
let keep_edges: Vec<(Point, Appearance)> = b::edges(&old)
|
||||
// Paint to carry over: (point inside face, paint) for faces that draw, and (point on edge,
|
||||
// paint) for every edge.
|
||||
let keep_faces: Vec<(Point, Carried)> =
|
||||
b::faces(&old).iter().filter(|f| draws(f)).filter_map(|f| Some((po::interior_point(f.path_data()?)?, Carried::of(f)))).collect();
|
||||
let keep_edges: Vec<(Point, Carried)> = b::edges(&old)
|
||||
.iter()
|
||||
.filter_map(|e| {
|
||||
let pd = e.path_data()?;
|
||||
let sp = pd.subpaths.first().filter(|sp| sp.segment_count() > 0)?;
|
||||
Some((kurbo::ParamCurve::eval(&sp.segment(0), 0.5), (*e.appearance).clone()))
|
||||
Some((kurbo::ParamCurve::eval(&sp.segment(0), 0.5), Carried::of(e)))
|
||||
})
|
||||
.collect();
|
||||
let mut sources = source_nodes(&old);
|
||||
@@ -126,20 +154,20 @@ fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result
|
||||
*ch = children;
|
||||
}
|
||||
g.extras_mut().live_paint_gaps = stored_gap_options(options);
|
||||
for (pt, paint) in keep_faces {
|
||||
for (pt, carried) in keep_faces {
|
||||
if let Some(fid) = face_at(&g, pt).map(|f| f.id)
|
||||
&& let Some(ch) = g.children_mut()
|
||||
&& let Some(f) = ch.iter_mut().find(|c| c.id == fid)
|
||||
{
|
||||
Arc::make_mut(f).appearance.set_fill(paint);
|
||||
carried.onto(Arc::make_mut(f));
|
||||
}
|
||||
}
|
||||
for (pt, app) in keep_edges {
|
||||
for (pt, carried) in keep_edges {
|
||||
if let Some(eid) = edge_near(&g, pt, 0.5).map(|e| e.id)
|
||||
&& let Some(ch) = g.children_mut()
|
||||
&& let Some(e) = ch.iter_mut().find(|c| c.id == eid)
|
||||
{
|
||||
Arc::make_mut(e).appearance = app.into();
|
||||
carried.onto(Arc::make_mut(e));
|
||||
}
|
||||
}
|
||||
let mut merged = Beside::replacing(d, roots);
|
||||
@@ -191,6 +219,13 @@ pub(super) fn lp_release(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "ids": ids_json(&ids) }))
|
||||
}
|
||||
|
||||
/// Does face or edge `n` draw on the canvas: it is shown, its opacity is above 0, and a fill or
|
||||
/// stroke row of its appearance draws (see [`Appearance::has_drawn_fill`] and
|
||||
/// [`Appearance::has_drawn_stroke`])?
|
||||
fn draws(n: &Node) -> bool {
|
||||
n.visible && n.opacity > 0.0 && (n.appearance.has_drawn_fill() || n.appearance.has_drawn_stroke())
|
||||
}
|
||||
|
||||
pub(super) fn lp_expand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let targets = live_targets(s, p)?;
|
||||
s.edit("Expand Live Paint", |d, sel| {
|
||||
@@ -205,8 +240,7 @@ pub(super) fn lp_expand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(ch) = n.children_mut() {
|
||||
ch.retain(|c| match c.name.as_deref() {
|
||||
Some(SOURCES_NAME) => false,
|
||||
Some(FACE_NAME) => !c.appearance.fill_paint().is_none(),
|
||||
Some(EDGE_NAME) => !c.appearance.stroke_paint().is_none() && c.appearance.stroke_width() > 0.0,
|
||||
Some(FACE_NAME | EDGE_NAME) => draws(c),
|
||||
_ => true,
|
||||
});
|
||||
}
|
||||
@@ -491,6 +525,37 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "group": g.0, "edge": edge.0 }))
|
||||
}
|
||||
|
||||
/// Every fill and stroke row of face or edge `n`, bottom first, as `livePaint.info` lists them. A
|
||||
/// row is `drawn` when the part is shown with an opacity above 0 and the row is shown, has paint
|
||||
/// and has an opacity above 0 (a stroke also a weight above 0): the rule of [`draws`], row by row.
|
||||
fn appearance_rows(n: &Node) -> Vec<Value> {
|
||||
let part_shown = n.visible && n.opacity > 0.0;
|
||||
n.appearance
|
||||
.items
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, item)| {
|
||||
let shown = part_shown && item.visible() && !item.paint().is_none() && item.opacity() > 0.0;
|
||||
let mut row = json!({
|
||||
"index": i,
|
||||
"kind": item.kind_name(),
|
||||
"paint": item.paint().label(),
|
||||
"opacity": item.opacity(),
|
||||
"visible": item.visible(),
|
||||
});
|
||||
let drawn = match item {
|
||||
AppearanceItem::Fill(_) => shown,
|
||||
AppearanceItem::Stroke(st) => {
|
||||
row["width"] = json!(st.width);
|
||||
shown && st.width > 0.0
|
||||
}
|
||||
};
|
||||
row["drawn"] = json!(drawn);
|
||||
row
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(super) fn lp_info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let g = match object_param(p, "group", "livePaint.info")? {
|
||||
Some(g) => g,
|
||||
@@ -502,12 +567,24 @@ pub(super) fn lp_info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.iter()
|
||||
.map(|f| {
|
||||
let bb = f.geometric_bounds().unwrap_or(Rect::ZERO);
|
||||
json!({ "id": f.id.0, "fill": f.appearance.fill_paint().label(), "bounds": [bb.x0, bb.y0, bb.x1, bb.y1] })
|
||||
json!({
|
||||
"id": f.id.0,
|
||||
"fill": f.appearance.fill_paint().label(),
|
||||
"bounds": [bb.x0, bb.y0, bb.x1, bb.y1],
|
||||
"appearance": appearance_rows(f),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let edges: Vec<Value> = b::edges(n)
|
||||
.iter()
|
||||
.map(|e| json!({ "id": e.id.0, "stroke": e.appearance.stroke_paint().label(), "width": e.appearance.stroke_width() }))
|
||||
.map(|e| {
|
||||
json!({
|
||||
"id": e.id.0,
|
||||
"stroke": e.appearance.stroke_paint().label(),
|
||||
"width": e.appearance.stroke_width(),
|
||||
"appearance": appearance_rows(e),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let sources = b::sources(n).and_then(|g| g.children()).map(|c| c.len()).unwrap_or(0);
|
||||
let options = n.gap_options();
|
||||
|
||||
@@ -526,12 +526,15 @@ fn color_groups(cmd: &str, d: &mut Document, items: Vec<Arc<Node>>) -> Result<Ve
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// What a trace depends on: 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.
|
||||
/// 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.
|
||||
#[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,
|
||||
target: NodeId,
|
||||
image: Box<ImageObject>,
|
||||
/// The settings traced with, as JSON.
|
||||
@@ -600,7 +603,7 @@ 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 { target, image, params: traced_with, swatches: params.swatches.clone(), bytes };
|
||||
let inputs = TraceInputs { doc: s.doc()?.uid, target, image, params: traced_with, swatches: params.swatches.clone(), bytes };
|
||||
Ok(Prepared { inputs, trace: params, view, params_json, preset_label, library })
|
||||
}
|
||||
|
||||
@@ -612,8 +615,9 @@ pub struct Traced {
|
||||
}
|
||||
|
||||
impl Traced {
|
||||
/// Hand it to the next run of its command with the same inputs ([`TraceRun::params`]), which
|
||||
/// applies it as one undo step instead of tracing again. Any other trace drops it.
|
||||
/// 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.
|
||||
pub fn hand_in(self, s: &mut Session) {
|
||||
s.trace_hand_off = Some(self);
|
||||
}
|
||||
@@ -686,7 +690,7 @@ impl TraceRun {
|
||||
}
|
||||
|
||||
/// Does it still apply: would the command trace the same object, image, pixels and settings
|
||||
/// now?
|
||||
/// now, in the document it was prepared in?
|
||||
pub fn current(&self, s: &Session) -> bool {
|
||||
prepare(s, self.command, &self.params).is_ok_and(|now| now.inputs == self.prepared.inputs)
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Invert Colors",
|
||||
["Edit", "Edit Colors"],
|
||||
None,
|
||||
"{fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?} replace each colour by its RGB inverse (keeps the colour model) in fills, strokes, text, gradient meshes (with fills), colorized image fills (their pixels stay unchanged), other embedded images (a recoloured copy) and pattern tiles (a new pattern swatch; the original stays), 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 (docs/mcp.md) → {changed, notChanged: {locked, hidden} (when the selection is everything select.all takes: the locked and hidden objects it left out whose colors would have changed; an object both hidden and locked counts as hidden), warning?: set when notChanged counts any object}",
|
||||
"{fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?} replace each colour by its RGB inverse (keeps the colour model) in fills, strokes, text, gradient meshes (with fills), colorized image fills (their pixels stay unchanged), other embedded images (a recoloured copy) and pattern tiles (a new pattern swatch; the original stays), 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, notChanged: {locked, hidden} (when the selection is everything select.all takes: the locked and hidden objects it left out whose colors would have changed; an object both hidden and locked counts as hidden), warning?: set when notChanged counts any object}",
|
||||
has_selection,
|
||||
|s, p| recolor(s, p, "edit.colors.invert", "Invert Colors", &invert)
|
||||
),
|
||||
@@ -513,14 +513,16 @@ pub(crate) fn edit_if_changed<T>(s: &mut Session, label: &str, f: impl FnOnce(&D
|
||||
}
|
||||
|
||||
/// Run `recolor` on `d` (it returns how many objects it changed) over `roots`, then store on their graphs what it changed
|
||||
/// on the graph series marks among `roots` and inside them, so the marks keep their new paint when the graph is drawn
|
||||
/// again.
|
||||
/// on the graph series marks and graph labels among `roots` and inside them, so the marks and every label of a kind keep
|
||||
/// their new paint when the graph is drawn again.
|
||||
pub(crate) fn keeping_series_paint(d: &mut Document, roots: &[NodeId], recolor: impl FnOnce(&mut Document) -> Result<usize>) -> Result<usize> {
|
||||
let marks = super::graph::series_marks_in(d, roots);
|
||||
let before = (!marks.is_empty()).then(|| d.clone());
|
||||
let labels = super::graph::labels_in(d, roots);
|
||||
let before = (!marks.is_empty() || !labels.is_empty()).then(|| d.clone());
|
||||
let n = recolor(d)?;
|
||||
if let Some(before) = before.filter(|_| n > 0) {
|
||||
super::appearance::capture_series_changes(&before, d, &marks);
|
||||
super::graph::capture_label_changes(&before, d, &labels, true);
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
@@ -9,7 +9,8 @@
|
||||
//! ([`use_front_profiles`]): when they are assigned, when the working settings change, and when the
|
||||
//! document comes to the front or its assignment comes back (an open, a switch, a close, a revert,
|
||||
//! an undo or a rollback, [`Session::sync_front_profiles`]); the working spaces stay as Edit → Color
|
||||
//! Settings set them.
|
||||
//! Settings set them. A document drawn while another is in front draws through its own profiles
|
||||
//! ([`doc_cms`]).
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
@@ -236,6 +237,9 @@ fn load_profile(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} else if proof_targets(&info.name) {
|
||||
// A new file of the CMYK profile View → Proof Setup targets: redraw.
|
||||
touch_all(s);
|
||||
} else {
|
||||
// Documents behind the front one draw through their own profiles: those assigned it redraw.
|
||||
touch_assigned(s, &info.name);
|
||||
}
|
||||
Ok(json!({"name": info.name, "kind": info.kind, "remembered": remembered}))
|
||||
}
|
||||
@@ -266,9 +270,21 @@ fn remove_profile(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if proof_targets(&info.name) {
|
||||
touch_all(s);
|
||||
}
|
||||
// Documents behind the front one draw through their own profiles: those assigned it redraw.
|
||||
touch_assigned(s, &info.name);
|
||||
Ok(json!({"removed": info.name}))
|
||||
}
|
||||
|
||||
/// Redraw the open documents assigned the profile `name`.
|
||||
fn touch_assigned(s: &mut Session, name: &str) {
|
||||
for d in &mut s.docs {
|
||||
let (rgb, cmyk) = doc_profiles(&d.doc);
|
||||
if [rgb, cmyk].iter().any(|n| n.as_deref() == Some(name)) {
|
||||
d.revision += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether View → Proof Setup targets the CMYK profile `name`.
|
||||
fn proof_targets(name: &str) -> bool {
|
||||
matches!(proof::view().setup.target, ProofTarget::Cmyk(t) if t == name)
|
||||
@@ -285,6 +301,14 @@ pub fn doc_profiles(d: &vectorcraft_doc::Document) -> (Option<String>, Option<St
|
||||
(get(&d.color_profiles.rgb), get(&d.color_profiles.cmyk))
|
||||
}
|
||||
|
||||
/// The color-management context the document draws through: the working settings with its
|
||||
/// assigned profiles in place of the working spaces, whether or not it is in front
|
||||
/// ([`cms::for_document`]).
|
||||
pub fn doc_cms(d: &vectorcraft_doc::Document) -> Arc<cms::Cms> {
|
||||
let (rgb, cmyk) = doc_profiles(d);
|
||||
cms::for_document(rgb.as_deref(), cmyk.as_deref())
|
||||
}
|
||||
|
||||
fn assign_profile(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "edit.assignProfile";
|
||||
let (mut rgb, mut cmyk) = doc_profiles(&s.doc()?.doc);
|
||||
@@ -662,8 +686,15 @@ fn map_graph_colors(g: &mut vectorcraft_doc::GraphSpec, f: &mut dyn FnMut(&Color
|
||||
}
|
||||
}
|
||||
let styles = &mut g.label_styles;
|
||||
for st in [&mut styles.values, &mut styles.categories, &mut styles.legend].into_iter().flatten() {
|
||||
map_paint_colors(&mut st.fill, f);
|
||||
// A legend fill of the labels' own stays theirs when `f` makes it black. The default black legend fill stays black,
|
||||
// so the labels on dark pie wedges are still drawn white.
|
||||
styles.mark_own_legend_fill();
|
||||
let own = styles.legend_fill_is_own();
|
||||
for (st, fill) in [(&mut styles.values, true), (&mut styles.categories, true), (&mut styles.legend, own)] {
|
||||
let Some(st) = st else { continue };
|
||||
if fill {
|
||||
map_paint_colors(&mut st.fill, f);
|
||||
}
|
||||
map_paint_colors(&mut st.stroke, f);
|
||||
}
|
||||
for r in [&mut styles.values_rows, &mut styles.categories_rows, &mut styles.legend_rows].into_iter().flatten() {
|
||||
|
||||
@@ -478,6 +478,75 @@ fn an_opened_file_measures_its_type_in_its_own_composite_fonts() {
|
||||
assert_eq!(actual.cached_bounds, Some(expected));
|
||||
}
|
||||
|
||||
/// The label of dimension `id` in `doc`.
|
||||
fn label(doc: &vectorcraft_doc::Document, id: u64) -> vectorcraft_doc::TextObject {
|
||||
let node = doc.node(NodeId(id)).unwrap();
|
||||
node.children().unwrap().iter().find_map(|n| if let NodeKind::Text(t) = &n.kind { Some((**t).clone()) } else { None }).unwrap()
|
||||
}
|
||||
|
||||
/// The center of label `t`'s measured box on the page.
|
||||
fn label_center(t: &vectorcraft_doc::TextObject) -> vectorcraft_geom::Point {
|
||||
t.xf * t.cached_bounds.unwrap().center()
|
||||
}
|
||||
|
||||
/// Whether every character of label `t` is filled in CMYK.
|
||||
fn label_in_cmyk(t: &vectorcraft_doc::TextObject) -> bool {
|
||||
!t.runs.is_empty() && t.runs.iter().all(|r| matches!(r.style.fill.color(), Some(vectorcraft_color::Color::Cmyk { .. })))
|
||||
}
|
||||
|
||||
/// The native file of a CMYK document whose composite font `name` sets Roman at full size, with a
|
||||
/// dimension whose label is set in it and whose label's characters are saved in RGB, so opening
|
||||
/// the file draws the dimension again → (the file, the dimension's id, the center of its label as
|
||||
/// drawn in the document's own composite font).
|
||||
fn dimension_file(name: &str) -> (Vec<u8>, u64, vectorcraft_geom::Point) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400, "colorMode": "cmyk"})).unwrap();
|
||||
let mut full = font(name);
|
||||
full["parts"]["roman"]["size"] = json!(100);
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [full]})).unwrap();
|
||||
let line = s.execute("shape.line", &json!({"x1": 100, "y1": 100, "x2": 172, "y2": 100})).unwrap()["id"].as_u64().unwrap();
|
||||
let id = s
|
||||
.execute(
|
||||
"dimension.create",
|
||||
&json!({"source": {"kind": "segment", "edge": {"node": line, "subpath": 0, "segment": 0}},
|
||||
"options": {"units": "in", "precision": 2, "fontFamily": name, "fontSize": 20}}),
|
||||
)
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
let mut doc = (*s.doc().unwrap().doc).clone();
|
||||
let drawn = label(&doc, id);
|
||||
assert!(label_in_cmyk(&drawn));
|
||||
let center = label_center(&drawn);
|
||||
let mut label_id = None;
|
||||
doc.node(NodeId(id)).unwrap().walk(&mut |n| {
|
||||
if matches!(n.kind, NodeKind::Text(_)) {
|
||||
label_id = Some(n.id);
|
||||
}
|
||||
});
|
||||
if let Some(NodeKind::Text(t)) = doc.node_mut(label_id.unwrap()).map(|n| &mut n.kind) {
|
||||
for r in &mut t.runs {
|
||||
r.style.fill = vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb8(0, 0, 0));
|
||||
}
|
||||
}
|
||||
(vectorcraft_format::save_file(&doc), id, center)
|
||||
}
|
||||
|
||||
/// A file whose dimensions are drawn again when it opens (their art is not in the document's color
|
||||
/// mode) draws their labels in its own composite fonts, not in those of the front document, which
|
||||
/// defines the label's font name with Roman at half size: each label stays centered on its anchor.
|
||||
#[test]
|
||||
fn an_opened_file_draws_its_dimension_labels_in_its_own_composite_fonts() {
|
||||
let (bytes, id, center) = dimension_file("CF Dimension");
|
||||
let mut s = session();
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Dimension")]})).unwrap();
|
||||
let file = crate::cmd::fileio::read_for_open("dimension.vectorcraft", &bytes, None, &json!({}), false, false).unwrap();
|
||||
crate::cmd::fileio::open_read(&mut s, file).unwrap();
|
||||
let opened = label(&s.doc().unwrap().doc, id);
|
||||
assert!(label_in_cmyk(&opened));
|
||||
assert!((label_center(&opened) - center).hypot() < 1e-6, "{:?} vs {center:?}", label_center(&opened));
|
||||
}
|
||||
|
||||
/// Threaded type read from a file flows through its frames in the file's own composite fonts, when
|
||||
/// no open document defines them.
|
||||
#[test]
|
||||
@@ -536,6 +605,40 @@ fn a_document_replaced_in_the_back_is_measured_when_the_front_one_closes() {
|
||||
assert_eq!(actual.cached_bounds, Some(expected));
|
||||
}
|
||||
|
||||
/// A document replaced in front (File › Revert) whose dimensions are drawn again draws their labels
|
||||
/// in its new composite fonts, not in those it had before.
|
||||
#[test]
|
||||
fn a_document_replaced_in_front_draws_its_dimension_labels_in_its_own_composite_fonts() {
|
||||
let (bytes, id, center) = dimension_file("CF Reverted");
|
||||
let mut s = session();
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Reverted")]})).unwrap();
|
||||
assert!(s.replace_document(0, vectorcraft_format::load(&bytes).unwrap()));
|
||||
let replaced = label(&s.doc().unwrap().doc, id);
|
||||
assert!(label_in_cmyk(&replaced));
|
||||
assert!((label_center(&replaced) - center).hypot() < 1e-6, "{:?} vs {center:?}", label_center(&replaced));
|
||||
}
|
||||
|
||||
/// A document replaced in the back draws its dimension labels in its own composite fonts, while the
|
||||
/// front document keeps its definition of the same name registered; the labels stay where they are
|
||||
/// when the document comes to the front.
|
||||
#[test]
|
||||
fn a_document_replaced_in_the_back_draws_its_dimension_labels_in_its_own_composite_fonts() {
|
||||
let (bytes, id, center) = dimension_file("CF Back Dimension");
|
||||
let mut s = session();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Back Dimension")]})).unwrap();
|
||||
assert!(s.replace_document(0, vectorcraft_format::load(&bytes).unwrap()));
|
||||
assert_eq!(s.active_index(), Some(1));
|
||||
let front = vectorcraft_text::FontDb::global().composite_font("CF Back Dimension").unwrap();
|
||||
assert_eq!(front.parts.get(vectorcraft_doc::CharClass::Roman).size, 50.0);
|
||||
let replaced = label(&s.documents()[0].doc, id);
|
||||
assert!(label_in_cmyk(&replaced));
|
||||
assert!((label_center(&replaced) - center).hypot() < 1e-6, "{:?} vs {center:?}", label_center(&replaced));
|
||||
assert!(s.set_active(0));
|
||||
let shown = label(&s.doc().unwrap().doc, id);
|
||||
assert!((label_center(&shown) - center).hypot() < 1e-6, "{:?} vs {center:?}", label_center(&shown));
|
||||
}
|
||||
|
||||
/// The type of document `index` with id `id`, wherever its tab is.
|
||||
fn text_in(s: &Session, index: usize, id: u64) -> vectorcraft_doc::TextObject {
|
||||
match &s.documents()[index].doc.node(NodeId(id)).unwrap().kind {
|
||||
@@ -568,10 +671,11 @@ fn a_document_replaced_in_the_back_is_measured_before_it_comes_to_the_front() {
|
||||
}
|
||||
|
||||
/// Type a document replaced in the back sets in a composite font that only the front document
|
||||
/// defines is measured in that font while the front one is registered, and again, as missing, when
|
||||
/// the replaced document comes to the front.
|
||||
/// defines is measured as missing, though the front one is registered, also when the replaced
|
||||
/// document defines no composite font, and still as missing when it comes to the front.
|
||||
#[test]
|
||||
fn a_document_replaced_in_the_back_measures_a_font_it_lacks_again_in_front() {
|
||||
fn a_document_replaced_in_the_back_measures_a_font_it_lacks_as_missing() {
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
let mut s = session();
|
||||
let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab12", "size": 20, "font": "CF Lacked"})).unwrap()["id"].as_u64().unwrap();
|
||||
let bytes = vectorcraft_format::save_file(&s.doc().unwrap().doc);
|
||||
@@ -579,8 +683,16 @@ fn a_document_replaced_in_the_back_measures_a_font_it_lacks_again_in_front() {
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Lacked")]})).unwrap();
|
||||
assert!(s.replace_document(0, vectorcraft_format::load(&bytes).unwrap()));
|
||||
let back = text_in(&s, 0, id);
|
||||
let expected = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &back).bounds;
|
||||
assert_eq!(back.cached_bounds, Some(expected));
|
||||
assert!(s.documents()[0].doc.composite_fonts.is_empty());
|
||||
let in_front = vectorcraft_text::layout(db, &back).bounds;
|
||||
// The same type set in a family nothing defines.
|
||||
let mut nowhere = back.clone();
|
||||
for r in &mut nowhere.runs {
|
||||
r.style.font_family = "No Such Family CF Lacked".into();
|
||||
}
|
||||
let missing = vectorcraft_text::layout(db, &nowhere).bounds;
|
||||
assert!((in_front.width() - missing.width()).abs() > 1e-6, "the front document's font draws otherwise");
|
||||
assert_eq!(back.cached_bounds, Some(missing));
|
||||
assert!(s.set_active(0));
|
||||
assert!(vectorcraft_text::FontDb::global().composite_font("CF Lacked").is_none());
|
||||
let actual = text(&s, id);
|
||||
|
||||
@@ -495,7 +495,8 @@ pub(crate) fn refresh(before: &Document, doc: &mut Document) -> Result<bool> {
|
||||
|
||||
/// Redraw the dimensions of an opened document whose art isn't in its colour mode: files saved
|
||||
/// before dimensions followed the colour mode have RGB dimensions in CMYK documents. A dimension
|
||||
/// that can't be redrawn keeps the art it has.
|
||||
/// that can't be redrawn keeps the art it has. The labels are measured in the document's own
|
||||
/// composite fonts, also when another document's definitions of the same names are registered.
|
||||
pub(crate) fn conform(doc: &mut Document) {
|
||||
if !doc.dimensions {
|
||||
return;
|
||||
@@ -521,6 +522,10 @@ pub(crate) fn conform(doc: &mut Document) {
|
||||
}
|
||||
}
|
||||
});
|
||||
if stale.is_empty() {
|
||||
return;
|
||||
}
|
||||
let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts);
|
||||
for (id, d) in stale {
|
||||
// An error leaves this dimension as it was; the others are still redrawn.
|
||||
let _ = replace(doc, id, d);
|
||||
|
||||
@@ -26,7 +26,7 @@ pub use perspective::perspective_click;
|
||||
use perspective::{
|
||||
attach, edit_text, grid_set, grid_show, persp_draw, persp_move, persp_nudge, persp_transform, plane_match, plane_move, plane_set, release,
|
||||
};
|
||||
pub(crate) use perspective::{finish_edit_text, grid_of, perspective_rewrite, silent, store_grid, transform_again};
|
||||
pub(crate) use perspective::{finish_edit_text, grid_kept, grid_of, perspective_rewrite, silent, store_grid, transform_again};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -107,7 +107,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Perspective Grid Preset",
|
||||
[],
|
||||
None,
|
||||
"{kind: 1|2|3 (its normal view) | name: a preset (see perspective.presets.list)} reset the grid to the preset fitted to the first artboard (and show it; attached objects stay attached)",
|
||||
"{kind: 1|2|3 (its normal view) | name: a preset (see perspective.presets.list)} reset the grid to the preset fitted to the first artboard (and show it; attached objects stay attached). No undo step when the document already holds that grid; when only whether it shows or its active plane differs, those are set without one",
|
||||
has_doc,
|
||||
super::perspgrid::grid_preset
|
||||
),
|
||||
|
||||
@@ -18,7 +18,7 @@ pub(crate) fn store_grid(d: &mut Document, g: &PerspectiveGrid) {
|
||||
|
||||
/// Whether `d` holds `g` as [`store_grid`] writes it (with `attached` cleared): then storing `g`
|
||||
/// leaves `d` as it is.
|
||||
fn grid_kept(d: &Document, g: &PerspectiveGrid) -> bool {
|
||||
pub(crate) fn grid_kept(d: &Document, g: &PerspectiveGrid) -> bool {
|
||||
let mut g = g.clone();
|
||||
g.attached.clear();
|
||||
serde_json::to_value(&g).is_ok_and(|v| d.unknown.get(persp::DOC_KEY) == Some(&v))
|
||||
|
||||
@@ -344,44 +344,9 @@ fn spot_swatches(d: &Document) -> HashSet<&str> {
|
||||
first.into_iter().filter(|&(name, spot)| spot && name != vectorcraft_color::swatch::REGISTRATION).map(|(name, _)| name).collect()
|
||||
}
|
||||
|
||||
/// Which of gradient `g`'s stops color some part of it that draws, by the stretches
|
||||
/// [`vectorcraft_color::Gradient::sample`] mixes in, for stops in any order: the pair of stop `k`
|
||||
/// and stop `k + 1` covers the offsets above every offset of stops `0..=k` up to stop `k + 1`'s,
|
||||
/// and both its stops count when that stretch has positive width and either stop is above opacity
|
||||
/// 0. The first stop also counts when it is above opacity 0, since it colors the offsets up to its
|
||||
/// own, and so does the last stop, since it colors the offsets above every stop's. Any other stop,
|
||||
/// opaque or not, counts only through a pair: a stop out of order whose pairs have no width
|
||||
/// (another stop before it reaches past both ends) colors nothing. A freeform gradient draws from
|
||||
/// its points, so each of its stops counts while any stop is above opacity 0.
|
||||
fn drawn_stops(g: &vectorcraft_color::Gradient) -> Vec<bool> {
|
||||
let stops = &g.stops;
|
||||
if g.kind == vectorcraft_color::GradientKind::Freeform {
|
||||
let any = stops.iter().any(|s| s.opacity > 0.0);
|
||||
return vec![any; stops.len()];
|
||||
}
|
||||
let mut drawn = vec![false; stops.len()];
|
||||
if let (Some(first), Some(d)) = (stops.first(), drawn.first_mut()) {
|
||||
*d = first.opacity > 0.0;
|
||||
}
|
||||
if let (Some(last), Some(d)) = (stops.last(), drawn.last_mut()) {
|
||||
*d |= last.opacity > 0.0;
|
||||
}
|
||||
// `f32::max` skips a NaN offset, which the sampler never picks either.
|
||||
let mut reach = f32::NEG_INFINITY;
|
||||
for k in 0..stops.len().saturating_sub(1) {
|
||||
reach = reach.max(stops[k].offset);
|
||||
let (a, b) = (&stops[k], &stops[k + 1]);
|
||||
if b.offset > reach && (a.opacity > 0.0 || b.opacity > 0.0) {
|
||||
drawn[k] = true;
|
||||
drawn[k + 1] = true;
|
||||
}
|
||||
}
|
||||
drawn
|
||||
}
|
||||
|
||||
/// The spot colors paint `p` prints (`spots`: [`spot_swatches`]): the spot swatch a solid color is
|
||||
/// linked to, or those a gradient's drawn stops ([`drawn_stops`]) are linked to, each once, in the
|
||||
/// order of the stops. A link at a tint of 0 prints no ink, a stop that colors only parts of a
|
||||
/// linked to, or those a gradient's drawn stops ([`vectorcraft_color::Gradient::drawn_stops`]) are
|
||||
/// linked to, each once, in the order of the stops. A link at a tint of 0 prints no ink, a stop that colors only parts of a
|
||||
/// gradient at an opacity of 0 prints none, and a color that only looks like a spot color is not
|
||||
/// linked to one.
|
||||
fn spot_labels(spots: &HashSet<&str>, p: &Paint) -> Vec<String> {
|
||||
@@ -398,7 +363,7 @@ fn spot_labels(spots: &HashSet<&str>, p: &Paint) -> Vec<String> {
|
||||
match p {
|
||||
Paint::Solid { swatch, tint, .. } => add(swatch, *tint),
|
||||
Paint::Gradient(g) => {
|
||||
let drawn = drawn_stops(&g.gradient);
|
||||
let drawn = g.gradient.drawn_stops();
|
||||
g.gradient.stops.iter().zip(drawn).filter(|&(_, d)| d).for_each(|(s, _)| add(&s.swatch, s.tint));
|
||||
}
|
||||
_ => {}
|
||||
@@ -1662,39 +1627,6 @@ mod tests {
|
||||
assert!(!["Far", "Edge", "Seam"].iter().any(|n| text.contains(n)), "{text}");
|
||||
}
|
||||
|
||||
/// A gradient's stops print where they color a stretch that draws, for stops in any order: the
|
||||
/// sampler mixes stop `k` with stop `k + 1` above every offset of the stops before it, so an
|
||||
/// out-of-order stop's pair can have no width.
|
||||
#[test]
|
||||
fn drawn_stops_follow_the_sampled_stretches() {
|
||||
use vectorcraft_color::{Color, Gradient, GradientKind, GradientStop};
|
||||
let stop = |offset: f32, opacity: f32| GradientStop { opacity, ..GradientStop::new(offset, Color::BLACK) };
|
||||
let g = |stops: Vec<GradientStop>| Gradient::new(GradientKind::Linear, stops);
|
||||
// In order: the clear stop next to the opaque one, not the one after it.
|
||||
assert_eq!(drawn_stops(&g(vec![stop(0.0, 1.0), stop(0.5, 0.0), stop(1.0, 0.0)])), vec![true, true, false]);
|
||||
// Out of order: the pair (0.8, 0.3) has no width, so the clear stop at 0.3 mixes only with
|
||||
// the clear stop at 0.8 before it, and the pair (0.3, 1.0) is sampled above 0.8.
|
||||
assert_eq!(drawn_stops(&g(vec![stop(0.0, 0.0), stop(0.8, 0.0), stop(0.3, 0.0), stop(1.0, 1.0)])), vec![false, false, true, true]);
|
||||
// An opaque stop out of order: the pairs (0, 0.8) and (0.7, 1) cover every offset, so the
|
||||
// pairs next to the stop at 0.3 have no width and it colors nothing.
|
||||
let out_of_order = |o: f32| g(vec![stop(0.0, 0.0), stop(0.8, o), stop(0.3, 1.0), stop(0.7, 0.0), stop(1.0, 0.0)]);
|
||||
assert_eq!(drawn_stops(&out_of_order(0.0)), vec![false; 5]);
|
||||
// With the stop at 0.8 opaque, the pairs next to it with width are drawn.
|
||||
assert_eq!(drawn_stops(&out_of_order(1.0)), vec![true, true, false, false, false]);
|
||||
// The last stop colors the offsets above every stop's, even when it is out of order.
|
||||
assert_eq!(drawn_stops(&g(vec![stop(0.0, 0.0), stop(0.6, 0.0), stop(0.5, 1.0)])), vec![false, false, true]);
|
||||
// The first stop colors the offsets up to its own.
|
||||
assert_eq!(drawn_stops(&g(vec![stop(0.0, 1.0), stop(0.0, 0.0), stop(1.0, 0.0)])), vec![true, false, false]);
|
||||
// One stop, every stop clear, and no stops at all.
|
||||
assert_eq!(drawn_stops(&g(vec![stop(0.5, 1.0)])), vec![true]);
|
||||
assert_eq!(drawn_stops(&g(vec![stop(0.0, 0.0), stop(1.0, 0.0)])), vec![false, false]);
|
||||
assert!(drawn_stops(&g(vec![])).is_empty());
|
||||
// A freeform gradient draws from its points: its stops count while any is above opacity 0.
|
||||
let mut free = g(vec![stop(0.0, 1.0), stop(0.5, 0.0), stop(1.0, 0.0)]);
|
||||
free.kind = GradientKind::Freeform;
|
||||
assert_eq!(drawn_stops(&free), vec![true, true, true]);
|
||||
}
|
||||
|
||||
/// Brushes, Spot Color Objects, Pattern Objects and Gradient Objects leave out a hidden object,
|
||||
/// an object at an opacity of 0 and the objects inside a hidden layer or a group at an opacity of
|
||||
/// 0, with Selection Only too: their fills, strokes, characters and colorized pixels paint no
|
||||
|
||||
@@ -11,7 +11,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Pencil",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end; with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it",
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it",
|
||||
has_doc,
|
||||
freehand
|
||||
),
|
||||
@@ -110,7 +110,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Smooth",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…], radius?: pt (12), fidelity?: pt (2.5; kept within 0.000078125 and about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom)} smooth selected paths near the drag → {ids, before, after}",
|
||||
"{points: [[x,y]…], radius?: pt (12), fidelity?: pt (2.5; kept within 0.000078125 and about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom)} smooth selected paths near the drag, keeping a corner where the path turns by more than 57.5° at the anchor and over radius and twice radius on either side → {ids, before, after}",
|
||||
has_selection,
|
||||
smooth_region
|
||||
),
|
||||
|
||||
@@ -217,11 +217,18 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
// An extending stroke that ends within four Fidelities of the path's other end closes it:
|
||||
// at least 6 pt and at most 400 pt, whatever the Fidelity it is fitted at.
|
||||
// `closed`, when given, says whether the stroke closes the path: the Pencil and the
|
||||
// Paintbrush send it, by their Close Paths When Ends Are Within and Alt at the release.
|
||||
// Left out, an extending stroke that ends within four Fidelities of the path's other end
|
||||
// closes it: at least 6 pt and at most 400 pt, whatever the Fidelity it is fitted at.
|
||||
let close_tol = (tol * 4.0).clamp(6.0, 400.0);
|
||||
let closing = connect.is_none() && sp.anchors.len() >= 2 && pts.last().is_some_and(|p| p.distance(first) <= close_tol);
|
||||
if closing && let Some(l) = pts.last_mut() {
|
||||
let near_first = pts.last().is_some_and(|p| p.distance(first) <= close_tol);
|
||||
let wants_close = if p.get("closed").is_some_and(|v| !v.is_null()) { closed } else { near_first };
|
||||
let closing = connect.is_none() && sp.anchors.len() >= 2 && wants_close;
|
||||
// A stroke ending near the other end ends on it; one ending farther away closes with a
|
||||
// straight segment back to it.
|
||||
let ends_on_first = closing && near_first;
|
||||
if ends_on_first && let Some(l) = pts.last_mut() {
|
||||
*l = first;
|
||||
}
|
||||
if let Some((_, _, y, _)) = &connect
|
||||
@@ -238,13 +245,23 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
add.remove(0);
|
||||
}
|
||||
sp.anchors.extend(add);
|
||||
if closing
|
||||
if ends_on_first
|
||||
&& sp.anchors.len() > 2
|
||||
&& let Some(l) = sp.anchors.pop()
|
||||
&& let Some(a0) = sp.anchors.first_mut()
|
||||
{
|
||||
a0.h_in = l.h_in;
|
||||
sp.closed = true;
|
||||
} else if closing && !ends_on_first && sp.anchors.len() > 2 {
|
||||
// Closed from away from the other end: a straight segment back to it, whatever
|
||||
// handles the open ends carried.
|
||||
sp.closed = true;
|
||||
if let Some(l) = sp.anchors.last_mut() {
|
||||
l.h_out = l.p;
|
||||
}
|
||||
if let Some(f) = sp.anchors.first_mut() {
|
||||
f.h_in = f.p;
|
||||
}
|
||||
}
|
||||
for a in &mut sp.anchors {
|
||||
*a = Anchor::with_handles(a.p, a.h_in, a.h_out);
|
||||
|
||||
@@ -13,9 +13,237 @@ use super::{
|
||||
/// of path within the reach on either side of it. VectorCraft's own value.
|
||||
const SMOOTH_SPREAD: f64 = 1.0 / 3.0;
|
||||
|
||||
/// The degrees by which a path must turn at an anchor, and over the tool's reach and twice its reach
|
||||
/// on either side of it, for the Smooth tool to keep the anchor as a corner ([`smooth_corners`]): a
|
||||
/// turn of more than 57.5°, an angle inside the corner of less than 122.5°. VectorCraft's own value,
|
||||
/// the same on every drag and at any Fidelity.
|
||||
const SMOOTH_CORNER_DEG: f64 = 57.5;
|
||||
|
||||
/// Most pieces a curved segment is cut into evenly, and most more pieces near each of its ends, to
|
||||
/// measure lengths along it in [`smooth_corners`].
|
||||
const CORNER_PIECES: usize = 64;
|
||||
|
||||
/// The control polygon's length of `c`, which is at least its length.
|
||||
fn polygon_len(c: CubicBez) -> f64 {
|
||||
c.p0.distance(c.p1) + c.p1.distance(c.p2) + c.p2.distance(c.p3)
|
||||
}
|
||||
|
||||
/// The places (0 to 1, in order, without 0 and with 1) on the curved segment `c` that
|
||||
/// [`smooth_corners`] measures it at: up to [`CORNER_PIECES`] evenly spaced, and near each end, over
|
||||
/// a stretch at least three times `reach` long where the segment is that long, up to as many more
|
||||
/// that are no more than `reach` / 8 apart along the control polygon, and as many again in each
|
||||
/// stretch twice as long after it until the pieces reach three times `reach`. The turns over `reach` and
|
||||
/// twice `reach` from an anchor are then measured along the curve however long the segment is.
|
||||
fn corner_places(c: CubicBez, reach: f64) -> Vec<f64> {
|
||||
let piece = reach / 8.0;
|
||||
let pieces = |len: f64| if piece > 0.0 { (len / piece).ceil().clamp(1.0, CORNER_PIECES as f64) as usize } else { 1 };
|
||||
let k = pieces(polygon_len(c)).max(4);
|
||||
let mut places: Vec<f64> = (1..=k).map(|j| j as f64 / k as f64).collect();
|
||||
if piece > 0.0 {
|
||||
for from_start in [true, false] {
|
||||
// The stretch from the end: halved until its control polygon is at most six reaches long.
|
||||
let first = 1.0 / k as f64;
|
||||
let mut t = first;
|
||||
let part = |t: f64| if from_start { c.subsegment(0.0..t) } else { c.subsegment(1.0 - t..1.0) };
|
||||
for _ in 0..60 {
|
||||
if polygon_len(part(t)) <= 6.0 * reach {
|
||||
break;
|
||||
}
|
||||
t /= 2.0;
|
||||
}
|
||||
let side = |u: f64| if from_start { u } else { 1.0 - u };
|
||||
let m = pieces(polygon_len(part(t)));
|
||||
let mut fine: Vec<f64> = (1..=m).map(|j| t * j as f64 / m as f64).collect();
|
||||
// Then the stretches twice as long in turn, cut as finely, up to the first even place, until
|
||||
// the pieces reach three reaches from the end, so twice the reach is measured along the curve
|
||||
// where a handle that does not reach out makes the curve start more slowly than its polygon.
|
||||
let mut covered = 0.0;
|
||||
let mut at = c.eval(side(0.0));
|
||||
for u in &fine {
|
||||
let q = c.eval(side(*u));
|
||||
covered += at.distance(q);
|
||||
at = q;
|
||||
}
|
||||
let (mut from, mut levels) = (t, 0);
|
||||
while covered < 3.0 * reach && from < first && levels < 60 {
|
||||
let to = (2.0 * from).min(first);
|
||||
let piece_len = polygon_len(if from_start { c.subsegment(from..to) } else { c.subsegment(1.0 - to..1.0 - from) });
|
||||
let m = pieces(piece_len);
|
||||
for j in 1..=m {
|
||||
let u = from + (to - from) * j as f64 / m as f64;
|
||||
let q = c.eval(side(u));
|
||||
covered += at.distance(q);
|
||||
at = q;
|
||||
fine.push(u);
|
||||
}
|
||||
(from, levels) = (to, levels + 1);
|
||||
}
|
||||
places.extend(fine.into_iter().map(side));
|
||||
}
|
||||
}
|
||||
places.retain(|u| *u > 0.0 && *u <= 1.0);
|
||||
places.sort_by(f64::total_cmp);
|
||||
places.dedup();
|
||||
places
|
||||
}
|
||||
|
||||
/// The degrees between the directions `u` and `v`, `None` when either has no length or is not a
|
||||
/// number.
|
||||
fn turn_between(u: kurbo::Vec2, v: kurbo::Vec2) -> Option<f64> {
|
||||
let (lu, lv) = (u.hypot(), v.hypot());
|
||||
if !(lu.is_finite() && lv.is_finite() && lu > 1e-12 && lv > 1e-12) {
|
||||
return None;
|
||||
}
|
||||
let deg = u.cross(v).atan2(u.dot(v)).abs().to_degrees();
|
||||
deg.is_finite().then_some(deg)
|
||||
}
|
||||
|
||||
/// Which anchors of `anchors` (a closed path when `closed`) the Smooth tool keeps as corners: those
|
||||
/// where the path turns by more than [`SMOOTH_CORNER_DEG`] at the anchor itself, between the
|
||||
/// direction it arrives along and the one it leaves along, and also over `reach` and over twice
|
||||
/// `reach` on either side of it, between the direction from the point that far back along the path
|
||||
/// to the anchor and the direction from the anchor to the point that far ahead. The points are taken
|
||||
/// no farther than the ends of an open path, and no more than an eighth of the way round a closed
|
||||
/// one. A jag or a bump smaller than the reach turns sharply at its anchor but not over twice the
|
||||
/// reach, and an anchor in the middle of a tight curve turns over the reach but not at the anchor, so
|
||||
/// neither is kept. An open path's first and last anchors are never corners.
|
||||
fn smooth_corners(anchors: &[Anchor], closed: bool, reach: f64) -> Vec<bool> {
|
||||
let n = anchors.len();
|
||||
let mut corners = vec![false; n];
|
||||
if n < 2 || (n < 3 && !closed) {
|
||||
return corners;
|
||||
}
|
||||
// The distances on either side the turn is measured over: one reach and two, no more than an
|
||||
// eighth of the way round a closed path. Over that much of a circle the path turns by 45°, so a
|
||||
// loop shorter than the reach is not all corners, while a square's or a triangle's corners still are.
|
||||
let mut spans = [reach, 2.0 * reach];
|
||||
if closed {
|
||||
let mut total = 0.0;
|
||||
for i in 0..n {
|
||||
total += walk(anchors, closed, (i, true), [f64::INFINITY; 2], reach, 1).1;
|
||||
}
|
||||
if !(total.is_finite() && total > 0.0) {
|
||||
return corners;
|
||||
}
|
||||
spans = spans.map(|r| r.min(total / 8.0));
|
||||
}
|
||||
for (i, flag) in corners.iter_mut().enumerate() {
|
||||
if !closed && (i == 0 || i == n - 1) {
|
||||
continue;
|
||||
}
|
||||
let (prev, a, next) = (anchors[(i + n - 1) % n], anchors[i], anchors[(i + 1) % n]);
|
||||
let arrive = [a.p - a.h_in, a.p - prev.h_out, a.p - prev.p].into_iter().find(|d| d.hypot() > 1e-12).unwrap_or_default();
|
||||
let leave = [a.h_out - a.p, next.h_in - a.p, next.p - a.p].into_iter().find(|d| d.hypot() > 1e-12).unwrap_or_default();
|
||||
if !turn_between(arrive, leave).is_some_and(|t| t > SMOOTH_CORNER_DEG) {
|
||||
continue;
|
||||
}
|
||||
let [Some(back_near), Some(back_far)] = walk(anchors, closed, (i, false), spans, reach, MAX_CORNER_WALK).0 else { continue };
|
||||
let [Some(ahead_near), Some(ahead_far)] = walk(anchors, closed, (i, true), spans, reach, MAX_CORNER_WALK).0 else { continue };
|
||||
*flag = [(back_near, ahead_near, spans[0]), (back_far, ahead_far, spans[1])]
|
||||
.into_iter()
|
||||
.all(|(back, ahead, r)| r <= 0.0 || turn_between(a.p - back, ahead - a.p).is_some_and(|t| t > SMOOTH_CORNER_DEG));
|
||||
}
|
||||
corners
|
||||
}
|
||||
|
||||
/// Most segments [`walk`] passes from an anchor before it stops, which bounds the work for each
|
||||
/// anchor on a path of very many very short segments.
|
||||
const MAX_CORNER_WALK: usize = 256;
|
||||
|
||||
/// A walk along the path `anchors` from anchor `from.0`, ahead when `from.1` and back otherwise,
|
||||
/// past no more than `segments` segments, measured along the lines between each curved segment's
|
||||
/// points at [`corner_places`]. It gives the points at the distances `to` (in order, the nearer
|
||||
/// first), an open path's end for one beyond the end, and `None` for one it did not reach within
|
||||
/// `segments` segments, and the length it walked. Both points are `None` when it meets a length that
|
||||
/// is not a number or is too large to add, and the length is then infinite.
|
||||
fn walk(anchors: &[Anchor], closed: bool, from: (usize, bool), to: [f64; 2], reach: f64, segments: usize) -> ([Option<Point>; 2], f64) {
|
||||
let (n, forward) = (anchors.len(), from.1);
|
||||
let Some(mut here) = anchors.get(from.0).map(|a| a.p) else { return ([None; 2], 0.0) };
|
||||
let (mut at, mut gone) = (from.0, 0.0);
|
||||
let mut found: [Option<Point>; 2] = [None; 2];
|
||||
let mut at_end = false;
|
||||
'segments: for _ in 0..segments {
|
||||
let next = match (forward, closed) {
|
||||
(true, _) if at + 1 < n => at + 1,
|
||||
(true, true) => 0,
|
||||
(false, _) if at > 0 => at - 1,
|
||||
(false, true) => n - 1,
|
||||
_ => {
|
||||
at_end = true;
|
||||
break;
|
||||
}
|
||||
};
|
||||
let (a, b) = (anchors[at], anchors[next]);
|
||||
let c = if forward { CubicBez::new(a.p, a.h_out, b.h_in, b.p) } else { CubicBez::new(a.p, a.h_in, b.h_out, b.p) };
|
||||
let places = if c.p1 == c.p0 && c.p2 == c.p3 { vec![1.0] } else { corner_places(c, reach) };
|
||||
for u in places {
|
||||
let q = if u >= 1.0 { c.p3 } else { c.eval(u) };
|
||||
let d = here.distance(q);
|
||||
if !(d.is_finite() && (gone + d).is_finite()) {
|
||||
return ([None; 2], f64::INFINITY);
|
||||
}
|
||||
for (slot, &dist) in found.iter_mut().zip(&to) {
|
||||
if slot.is_none() && gone + d >= dist {
|
||||
let t = if d > 0.0 { ((dist - gone) / d).clamp(0.0, 1.0) } else { 1.0 };
|
||||
*slot = Some(here.lerp(q, t));
|
||||
}
|
||||
}
|
||||
gone += d;
|
||||
here = q;
|
||||
if found.iter().all(Option::is_some) {
|
||||
break 'segments;
|
||||
}
|
||||
}
|
||||
at = next;
|
||||
}
|
||||
// An open path that ends after the last segment walked ends there too.
|
||||
if !closed && at == if forward { n - 1 } else { 0 } {
|
||||
at_end = true;
|
||||
}
|
||||
(found.map(|p| p.or(at_end.then_some(here))), gone)
|
||||
}
|
||||
|
||||
/// Whether `a` and `b` are the same anchors, to within a rounding error.
|
||||
fn same_anchors(a: &[Anchor], b: &[Anchor]) -> bool {
|
||||
let near = |p: Point, q: Point| p.distance(q) <= 1e-9;
|
||||
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| near(x.p, y.p) && near(x.h_in, y.h_in) && near(x.h_out, y.h_out))
|
||||
}
|
||||
|
||||
/// [`refit_run`] of the open run `anchors` cut at its anchors marked in `corners`: each part between
|
||||
/// two corners is smoothed and refitted on its own, so each corner keeps its place and the direction
|
||||
/// the path arrives and leaves along. `free` applies to the run's first and last anchors only.
|
||||
fn refit_split(anchors: &[Anchor], corners: &[bool], tol: f64, sigma: f64, free: [bool; 2]) -> Vec<Anchor> {
|
||||
let last = anchors.len().saturating_sub(1);
|
||||
let mut cuts: Vec<usize> = (1..last).filter(|&i| corners.get(i).copied().unwrap_or(false)).collect();
|
||||
if cuts.is_empty() {
|
||||
return refit_run(anchors, tol, sigma, free);
|
||||
}
|
||||
cuts.insert(0, 0);
|
||||
cuts.push(last);
|
||||
let mut out: Vec<Anchor> = Vec::with_capacity(anchors.len());
|
||||
for w in cuts.windows(2) {
|
||||
let (a, b) = (w[0], w[1]);
|
||||
let part = refit_run(&anchors[a..=b], tol, sigma, [free[0] && a == 0, free[1] && b == last]);
|
||||
match out.pop() {
|
||||
// The corner ends one part and starts the next: it keeps its place, and takes the handle
|
||||
// in from the part before and the handle out from the part after.
|
||||
Some(end) => {
|
||||
let mut rest = part.into_iter();
|
||||
if let Some(start) = rest.next() {
|
||||
out.push(Anchor::with_handles(anchors[a].p, end.h_in, start.h_out));
|
||||
}
|
||||
out.extend(rest);
|
||||
}
|
||||
None => out.extend(part),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The options the Smooth tool refits with: the path smoothed along its length by a Gaussian of
|
||||
/// spread `sigma` (none at 0), then refitted within `tol` of that and within twice the distance the
|
||||
/// smoothing moved it, keeping a corner only where the path turns back on itself. `free` says whether
|
||||
/// smoothing moved it. The tool cuts the path at its corners first ([`smooth_corners`]), so within a
|
||||
/// part the refit keeps a corner only where the path turns back on itself. `free` says whether
|
||||
/// the start and the end of the stretch refitted are ends of an open path, whose direction then
|
||||
/// follows the smoothed path within the reach rather than the first or last segment.
|
||||
fn refit_options(tol: f64, sigma: f64, free: [bool; 2]) -> SimplifyOptions {
|
||||
@@ -49,6 +277,84 @@ fn refit_run(anchors: &[Anchor], tol: f64, sigma: f64, free: [bool; 2]) -> Vec<A
|
||||
out
|
||||
}
|
||||
|
||||
/// Distance (points) from an anchor within which a smoothed closed path starts at that anchor
|
||||
/// instead of at a new one split in beside it.
|
||||
const START_SNAP: f64 = 1e-3;
|
||||
|
||||
/// Distance (points) within which two points of a smoothed closed path count as equally near its
|
||||
/// old start.
|
||||
const START_TIE: f64 = 1e-6;
|
||||
|
||||
/// Where `p` lies along the closed `orig` from its first anchor: the segment index and parameter of
|
||||
/// the point of `orig` nearest `p`, the first such point in its order. Sorts after every finite place
|
||||
/// when there is none.
|
||||
fn place_along(orig: &SubPath, p: Point) -> (usize, f64) {
|
||||
let mut best: Option<(f64, usize, f64)> = None;
|
||||
for j in 0..orig.anchors.len() {
|
||||
let hit = orig.segment(j).nearest(p, 1e-9);
|
||||
if hit.distance_sq.is_finite() && hit.t.is_finite() && best.is_none_or(|(d, ..)| hit.distance_sq < d) {
|
||||
best = Some((hit.distance_sq, j, hit.t));
|
||||
}
|
||||
}
|
||||
best.map_or((usize::MAX, f64::INFINITY), |(_, j, t)| (j, t))
|
||||
}
|
||||
|
||||
/// The closed `sp` started at the point on it nearest `start`: at the anchor there, or at a new
|
||||
/// anchor split into the segment there, which leaves the outline as it is. Of points equally near
|
||||
/// `start`, the one earliest along `orig` (the path before smoothing) from its first anchor is used,
|
||||
/// then the first in `sp`'s order. An open `sp`, or one with no segment or no finite nearest point,
|
||||
/// is returned as it is.
|
||||
fn start_nearest(mut sp: SubPath, start: Point, orig: &SubPath) -> SubPath {
|
||||
let n = sp.anchors.len();
|
||||
if !sp.closed || n < 2 {
|
||||
return sp;
|
||||
}
|
||||
// (distance, place along `orig` once a tie needs it, segment of `sp`, parameter)
|
||||
type Best = (f64, Option<(usize, f64)>, usize, f64);
|
||||
let mut best: Option<Best> = None;
|
||||
for i in 0..n {
|
||||
let c = sp.segment(i);
|
||||
let hit = c.nearest(start, 1e-9);
|
||||
if !hit.distance_sq.is_finite() || !hit.t.is_finite() {
|
||||
continue;
|
||||
}
|
||||
let d = hit.distance_sq.sqrt();
|
||||
match &mut best {
|
||||
None => best = Some((d, None, i, hit.t)),
|
||||
Some((bd, bplace, bi, bt)) if (d - *bd).abs() <= START_TIE => {
|
||||
let held = *bplace.get_or_insert_with(|| place_along(orig, sp.segment(*bi).eval(*bt)));
|
||||
let place = place_along(orig, c.eval(hit.t));
|
||||
if place.0 < held.0 || (place.0 == held.0 && place.1 < held.1) {
|
||||
best = Some((d, Some(place), i, hit.t));
|
||||
}
|
||||
}
|
||||
Some((bd, ..)) if d < *bd => best = Some((d, None, i, hit.t)),
|
||||
Some(_) => {}
|
||||
}
|
||||
}
|
||||
let Some((_, _, i, t)) = best else { return sp };
|
||||
let c = sp.segment(i);
|
||||
let at = c.eval(t);
|
||||
let first = if at.distance(c.p0) <= START_SNAP {
|
||||
i
|
||||
} else if at.distance(c.p3) <= START_SNAP {
|
||||
(i + 1) % n
|
||||
} else {
|
||||
let mid = if sp.segment_is_line(i) {
|
||||
Anchor::corner(at)
|
||||
} else {
|
||||
let (l, r) = (c.subsegment(0.0..t), c.subsegment(t..1.0));
|
||||
sp.anchors[i].h_out = l.p1;
|
||||
sp.anchors[(i + 1) % n].h_in = r.p2;
|
||||
Anchor::with_handles(at, l.p2, r.p1)
|
||||
};
|
||||
sp.anchors.insert(i + 1, mid);
|
||||
i + 1
|
||||
};
|
||||
sp.anchors.rotate_left(first);
|
||||
sp
|
||||
}
|
||||
|
||||
/// Pieces of curve that one Smooth drag measures against the drag while it searches the segments
|
||||
/// under it ([`reach_samples`]), shared equally by the curved segments that come within its reach,
|
||||
/// each of which gets at least one: enough to search 300,000 pt of curve within the default reach
|
||||
@@ -226,6 +532,9 @@ fn mark_reached(sp: &SubPath, pts: &[Point], radius: f64, share: usize) -> (SubP
|
||||
(out, marked)
|
||||
}
|
||||
|
||||
/// `sp` with the anchors in the drag's reach smoothed and refitted, `None` when none are in reach.
|
||||
/// A closed path whose first anchor is in reach starts at the point of the refitted path nearest
|
||||
/// that anchor's place (VectorCraft's own rule).
|
||||
fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f64, sigma: f64) -> Option<SubPath> {
|
||||
if sp.anchors.len() < 2 {
|
||||
return None;
|
||||
@@ -238,10 +547,33 @@ fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f
|
||||
return None;
|
||||
}
|
||||
if sp.closed {
|
||||
let start = sp.anchors[0].p;
|
||||
let Some(k) = marked.iter().position(|m| !m) else {
|
||||
// Everything is in range: smooth the whole closed path, across its start too.
|
||||
let f = po::simplify_with(&PathData::single(sp.clone()), &refit_options(tol, sigma, [false; 2]));
|
||||
return f.subpaths.into_iter().next();
|
||||
let corners = smooth_corners(&sp.anchors, 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.
|
||||
let f = po::simplify_with(&PathData::single(sp.clone()), &refit_options(tol, sigma, [false; 2]));
|
||||
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();
|
||||
open.rotate_left(c);
|
||||
let mut cut = corners;
|
||||
cut.rotate_left(c);
|
||||
open.push(open[0]);
|
||||
cut.push(true);
|
||||
let mut res = refit_split(&open, &cut, tol, sigma, [false; 2]);
|
||||
if same_anchors(&res, &open) {
|
||||
return None;
|
||||
}
|
||||
let l = res.pop()?;
|
||||
if let Some(r0) = res.first_mut() {
|
||||
*r0 = Anchor::with_handles(r0.p, l.h_in, r0.h_out);
|
||||
}
|
||||
// The path starts where it did when the refit keeps an anchor there, and otherwise at its
|
||||
// point nearest there.
|
||||
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();
|
||||
@@ -251,14 +583,20 @@ fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f
|
||||
open.anchors.push(open.anchors[0]);
|
||||
m.push(false);
|
||||
open.closed = false;
|
||||
let mut res = smooth_open(&open.anchors, &m, near, tol, sigma, false);
|
||||
let mut res = smooth_open(&open.anchors, &m, near, tol, sigma, radius, false);
|
||||
if same_anchors(&res, &open.anchors) {
|
||||
return None;
|
||||
}
|
||||
let l = res.pop()?;
|
||||
if let Some(r0) = res.first_mut() {
|
||||
r0.h_in = l.h_in;
|
||||
}
|
||||
return Some(SubPath::new(res, true));
|
||||
// With k = 0 the first anchor is out of reach and still starts the result.
|
||||
let res = SubPath::new(res, true);
|
||||
return Some(if k == 0 { res } else { start_nearest(res, start, sp) });
|
||||
}
|
||||
Some(SubPath::new(smooth_open(&sp.anchors, &marked, near, tol, sigma, true), false))
|
||||
let res = smooth_open(&sp.anchors, &marked, near, tol, sigma, radius, true);
|
||||
(!same_anchors(&res, &sp.anchors)).then(|| SubPath::new(res, false))
|
||||
}
|
||||
|
||||
/// The segment `c`, which ends in the drag's reach (`near`) and starts outside it, split where it
|
||||
@@ -292,8 +630,10 @@ fn split_at_reach(c: CubicBez, near: &dyn Fn(Point) -> bool) -> Option<(CubicBez
|
||||
/// drag's reach (`near`): a short drag smooths what is under it, and the rest of a long segment next
|
||||
/// to it stays as it was (#1512). With `open`, `anchors` are an open path, and the curve at its first
|
||||
/// or last anchor turns with the smoothing when a run's refit reaches that anchor; a run's other ends,
|
||||
/// and those of the open run a closed path is cut into, keep their direction.
|
||||
fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool, tol: f64, sigma: f64, open: bool) -> Vec<Anchor> {
|
||||
/// and those of the open run a closed path is cut into, keep their direction. Each run keeps its
|
||||
/// corners ([`smooth_corners`] within `radius`, the tool's reach, measured within the run), and a run
|
||||
/// whose refit changes nothing stays as it was.
|
||||
fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool, tol: f64, sigma: f64, radius: f64, open: bool) -> Vec<Anchor> {
|
||||
let n = anchors.len();
|
||||
let mut runs = vec![];
|
||||
let mut i = 0;
|
||||
@@ -334,7 +674,11 @@ fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool
|
||||
*outer = Anchor::with_handles(far.p3, far.p2, reach.p1);
|
||||
}
|
||||
let free = [open && lo == 0 && head.is_none(), open && hi == n - 1 && tail.is_none()];
|
||||
let new = refit_run(&piece, tol, sigma, free);
|
||||
let corners = smooth_corners(&piece, false, radius);
|
||||
let new = refit_split(&piece, &corners, tol, sigma, free);
|
||||
if same_anchors(&new, &piece) {
|
||||
continue;
|
||||
}
|
||||
out.splice(lo..=hi, head.into_iter().chain(new).chain(tail));
|
||||
}
|
||||
out
|
||||
@@ -621,6 +965,89 @@ pub(super) fn join_scrub(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A closed ring of four smooth anchors round (100, 100) with radius 50.
|
||||
fn ring() -> SubPath {
|
||||
let k = 0.5523 * 50.0;
|
||||
let a = |x: f64, y: f64, dx: f64, dy: f64| Anchor::with_handles(Point::new(x, y), Point::new(x - dx, y - dy), Point::new(x + dx, y + dy));
|
||||
SubPath::new(vec![a(150.0, 100.0, 0.0, k), a(100.0, 150.0, -k, 0.0), a(50.0, 100.0, 0.0, -k), a(100.0, 50.0, k, 0.0)], true)
|
||||
}
|
||||
|
||||
/// A start between two anchors of a curve splits that curve there into two that trace it, and the
|
||||
/// new anchor comes first.
|
||||
#[test]
|
||||
fn start_nearest_splits_a_curve_where_it_passes_the_start() {
|
||||
let sp = ring();
|
||||
let old = sp.segment(0);
|
||||
let start = old.eval(0.3) + (old.eval(0.3) - Point::new(100.0, 100.0)) * 0.1;
|
||||
let out = start_nearest(sp.clone(), start, &sp);
|
||||
assert!(out.closed && out.anchors.len() == 5, "{out:?}");
|
||||
let t = old.nearest(start, 1e-9).t;
|
||||
assert!(out.anchors[0].p.distance(old.eval(t)) < 1e-9, "{out:?}");
|
||||
let (head, rest) = (out.segment(4), out.segment(0));
|
||||
for k in 0..=8 {
|
||||
let u = f64::from(k) / 8.0;
|
||||
assert!(head.eval(u).distance(old.eval(t * u)) < 1e-9);
|
||||
assert!(rest.eval(u).distance(old.eval(t + (1.0 - t) * u)) < 1e-9);
|
||||
}
|
||||
for i in 1..4 {
|
||||
assert_eq!(out.segment(i), sp.segment(i), "segment {i} stays");
|
||||
}
|
||||
}
|
||||
|
||||
/// A start within [`START_SNAP`] of an anchor starts the ring at that anchor, with no anchor added.
|
||||
#[test]
|
||||
fn start_nearest_starts_at_an_anchor_near_the_start() {
|
||||
let sp = ring();
|
||||
let out = start_nearest(sp.clone(), Point::new(50.0, 100.0 + START_SNAP / 2.0), &sp);
|
||||
let mut want = sp.anchors.clone();
|
||||
want.rotate_left(2);
|
||||
assert_eq!(out.anchors, want);
|
||||
}
|
||||
|
||||
/// A start on a straight side of a triangle adds a corner point there without handles, and the
|
||||
/// sides stay straight.
|
||||
#[test]
|
||||
fn start_nearest_splits_a_line_with_a_corner_point() {
|
||||
let sp = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(50.0, 80.0)], true);
|
||||
let out = start_nearest(sp.clone(), Point::new(40.0, -5.0), &sp);
|
||||
let want: Vec<Point> = [(40.0, 0.0), (100.0, 0.0), (50.0, 80.0), (0.0, 0.0)].map(|(x, y)| Point::new(x, y)).to_vec();
|
||||
assert!(out.anchors.len() == 4 && out.anchors.iter().zip(&want).all(|(a, w)| a.p.distance(*w) < 1e-9), "{out:?}");
|
||||
assert!((0..4).all(|i| out.segment_is_line(i)), "{out:?}");
|
||||
}
|
||||
|
||||
/// A ring whose last anchor lies on its first keeps its first anchor first, and gets no third
|
||||
/// anchor at that place.
|
||||
#[test]
|
||||
fn start_nearest_keeps_the_first_of_two_anchors_on_one_place() {
|
||||
let p = [(0.0, 0.0), (100.0, 0.0), (50.0, 80.0), (0.0, 0.0)].map(|(x, y)| Point::new(x, y));
|
||||
let sp = SubPath::polyline(&p, true);
|
||||
assert_eq!(start_nearest(sp.clone(), p[0], &sp), sp);
|
||||
}
|
||||
|
||||
/// Of points equally near the start, the one earliest along the path before smoothing from its
|
||||
/// first anchor comes first, whatever the smoothed path's order. The center of a square is equally
|
||||
/// near the middle of each side. The square before smoothing starts at (-50, -50), so the middle
|
||||
/// of its first side, (0, -50), comes first, though the smoothed copy starts at (50, 50).
|
||||
#[test]
|
||||
fn start_nearest_breaks_a_tie_by_the_order_before_smoothing() {
|
||||
let p = [(-50.0, -50.0), (50.0, -50.0), (50.0, 50.0), (-50.0, 50.0)].map(|(x, y)| Point::new(x, y));
|
||||
let orig = SubPath::polyline(&p, true);
|
||||
let mut sp = orig.clone();
|
||||
sp.anchors.rotate_left(2);
|
||||
let out = start_nearest(sp, Point::new(0.0, 0.0), &orig);
|
||||
assert!(out.closed && out.anchors.len() == 5, "{out:?}");
|
||||
assert!(out.anchors[0].p.distance(Point::new(0.0, -50.0)) < 1e-9, "{out:?}");
|
||||
assert!(out.anchors[1].p.distance(p[1]) < 1e-9, "{out:?}");
|
||||
}
|
||||
|
||||
/// An open path, and a start that is not a number, leave the path as it is.
|
||||
#[test]
|
||||
fn start_nearest_leaves_an_open_path_or_a_start_without_a_place() {
|
||||
let open = SubPath { closed: false, ..ring() };
|
||||
assert_eq!(start_nearest(open.clone(), Point::new(100.0, 50.0), &ring()), open);
|
||||
assert_eq!(start_nearest(ring(), Point::new(f64::NAN, 0.0), &ring()), ring());
|
||||
}
|
||||
|
||||
/// Searching a curve 1,000,000 pt long under a drag of 1,000 points along it measures no more
|
||||
/// pieces than the budget it is given, and a search with none left gives one sample.
|
||||
#[test]
|
||||
@@ -649,4 +1076,123 @@ mod tests {
|
||||
assert_eq!(drag_stretches(&one), vec![0]);
|
||||
assert!((dist_to_stretches(&one, &[0], Point::new(13.0, 14.0)) - 5.0).abs() < 1e-12);
|
||||
}
|
||||
|
||||
fn polyline(pts: &[(f64, f64)]) -> Vec<Anchor> {
|
||||
pts.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect()
|
||||
}
|
||||
|
||||
/// Anchors on one point, anchors that are not numbers or are too far out to measure, and a
|
||||
/// zigzag of 100,001 anchors 1 pt high give no corner and do not fail; a square's four anchors
|
||||
/// are its corners, and an open path's ends never are.
|
||||
#[test]
|
||||
fn corners_are_found_only_where_the_path_turns_at_and_around_an_anchor() {
|
||||
assert_eq!(smooth_corners(&polyline(&[(5.0, 5.0); 4]), false, 12.0), vec![false; 4]);
|
||||
assert_eq!(smooth_corners(&polyline(&[(0.0, 0.0), (f64::NAN, 1.0), (10.0, 0.0)]), false, 12.0), vec![false; 3]);
|
||||
assert_eq!(smooth_corners(&polyline(&[(0.0, 0.0), (1e308, 0.0), (1e308, 1e308), (-1e308, 0.0)]), true, 12.0), vec![false; 4]);
|
||||
let zigzag: Vec<(f64, f64)> = (0..=100_000).map(|i| (f64::from(i), f64::from(i % 2))).collect();
|
||||
assert!(!smooth_corners(&polyline(&zigzag), false, 12.0).contains(&true));
|
||||
let square = polyline(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]);
|
||||
assert_eq!(smooth_corners(&square, true, 12.0), vec![true; 4]);
|
||||
assert_eq!(smooth_corners(&square, false, 12.0), vec![false, true, true, false]);
|
||||
assert_eq!(smooth_corners(&square, false, 0.0), vec![false, true, true, false], "with no reach the turn at the anchor decides");
|
||||
assert_eq!(smooth_corners(&square[..2], false, 12.0), vec![false; 2]);
|
||||
}
|
||||
|
||||
/// A 90° bump 400 pt high cut into 1 pt segments, between two long straight segments: with a reach
|
||||
/// of 10 pt its top is a corner, and with a reach of 1,000 pt, where the walk passes more segments
|
||||
/// than it measures before it gets that far, its top is not one, as the path turns by about 51°
|
||||
/// over that reach.
|
||||
#[test]
|
||||
fn a_corner_is_not_kept_where_the_reach_is_not_measured() {
|
||||
let side = 400.0 * std::f64::consts::SQRT_2;
|
||||
let steps = side.ceil() as usize;
|
||||
let mut pts = vec![(-3000.0, 0.0)];
|
||||
pts.extend((0..steps).map(|j| {
|
||||
let f = j as f64 / steps as f64;
|
||||
(-400.0 + 400.0 * f, 400.0 * f)
|
||||
}));
|
||||
pts.extend((0..=steps).map(|j| {
|
||||
let f = j as f64 / steps as f64;
|
||||
(400.0 * f, 400.0 - 400.0 * f)
|
||||
}));
|
||||
pts.push((3000.0, 0.0));
|
||||
let anchors = polyline(&pts);
|
||||
let top = steps + 1;
|
||||
assert_eq!(anchors[top].p, Point::new(0.0, 400.0));
|
||||
assert!(smooth_corners(&anchors, false, 10.0)[top]);
|
||||
assert!(!smooth_corners(&anchors, false, 1000.0)[top]);
|
||||
}
|
||||
|
||||
/// A 60° corner between two curved segments 1,000 pt long is found at a reach of 2 pt as it is
|
||||
/// when each segment is cut into a thousand pieces: the turns over the reach are measured along the
|
||||
/// curve near the anchor, not along a chord much longer than the reach.
|
||||
#[test]
|
||||
fn a_corner_between_long_curves_is_measured_along_them() {
|
||||
// The curves arrive along x and leave at 60° to it, each bending away from the other.
|
||||
let d = kurbo::Vec2::from_angle(-60f64.to_radians());
|
||||
let side = kurbo::Vec2::new(-d.y, d.x) * 1000.0;
|
||||
let v = Point::new(0.0, 0.0);
|
||||
let a = Anchor::with_handles(Point::new(-1000.0, 1000.0), Point::new(-1000.0, 1000.0), Point::new(-300.0, 1000.0));
|
||||
let b = Anchor::with_handles(v, Point::new(-300.0, 0.0), v + d * 300.0);
|
||||
let end = v + d * 1000.0 + side;
|
||||
let c = Anchor::with_handles(end, v + d * 300.0 + side, end);
|
||||
let long = [a, b, c];
|
||||
let fine: Vec<Anchor> = {
|
||||
let sp = SubPath::new(long.to_vec(), false);
|
||||
let mut pts = vec![];
|
||||
for i in 0..2 {
|
||||
let s = sp.segment(i);
|
||||
for j in 0..1000 {
|
||||
let p = s.subsegment(f64::from(j) / 1000.0..f64::from(j + 1) / 1000.0);
|
||||
if j == 0 && i == 0 {
|
||||
pts.push(Anchor::with_handles(p.p0, p.p0, p.p1));
|
||||
} else if let Some(last) = pts.last_mut() {
|
||||
*last = Anchor::with_handles(last.p, last.h_in, p.p1);
|
||||
}
|
||||
pts.push(Anchor::with_handles(p.p3, p.p2, p.p3));
|
||||
}
|
||||
}
|
||||
pts
|
||||
};
|
||||
let at_v = |anchors: &[Anchor]| {
|
||||
let corners = smooth_corners(anchors, false, 2.0);
|
||||
anchors.iter().zip(corners).find(|(x, _)| x.p == v).map(|(_, c)| c)
|
||||
};
|
||||
assert_eq!(at_v(&fine), Some(true), "cut finely, the anchor is a corner");
|
||||
assert_eq!(at_v(&long), Some(true));
|
||||
}
|
||||
|
||||
/// A line that meets a curve leaving with no handle, turning by 58° at the anchor and by about
|
||||
/// 57.53° over twice a reach of 0.02 pt: the anchor is a corner, measured either way along the path,
|
||||
/// as the stretch measured finely near the anchor covers twice the reach along the curve.
|
||||
#[test]
|
||||
fn a_corner_next_to_a_curve_without_a_handle_is_kept() {
|
||||
let at = 58f64.to_radians();
|
||||
let prev = Anchor::corner(Point::new(-100.0 * at.cos(), -100.0 * at.sin()));
|
||||
let v = Point::new(0.0, 0.0);
|
||||
let a = Anchor::with_handles(v, v, v);
|
||||
let end = Point::new(600.0, 600.0);
|
||||
let next = Anchor::with_handles(end, Point::new(200.0, 0.0), end);
|
||||
assert_eq!(smooth_corners(&[prev, a, next], false, 0.02), vec![false, true, false]);
|
||||
let back = |x: Anchor| Anchor::with_handles(x.p, x.h_out, x.h_in);
|
||||
assert_eq!(smooth_corners(&[back(next), back(a), back(prev)], false, 0.02), vec![false, true, false]);
|
||||
}
|
||||
|
||||
/// A jagged closed path whose length is less than twice the reach: its jags are not corners,
|
||||
/// while a triangle that small keeps its three.
|
||||
#[test]
|
||||
fn a_small_jagged_loop_has_no_corners() {
|
||||
let ring: Vec<(f64, f64)> = (0..16)
|
||||
.map(|i| {
|
||||
let (a, r) = (f64::from(i) / 16.0 * std::f64::consts::TAU, if i % 2 == 0 { 3.0 } else { 2.0 });
|
||||
(r * a.cos(), r * a.sin())
|
||||
})
|
||||
.collect();
|
||||
let jags = polyline(&ring);
|
||||
let sp = SubPath::new(jags.clone(), true);
|
||||
assert!(subpath_len(&sp) < 24.0);
|
||||
assert!(smooth_corners(&jags, true, 1e-6).iter().all(|c| *c), "each jag turns sharply at its anchor");
|
||||
assert_eq!(smooth_corners(&jags, true, 12.0), vec![false; 16]);
|
||||
assert_eq!(smooth_corners(&polyline(&[(0.0, 0.0), (6.0, 0.0), (3.0, 5.196)]), true, 12.0), vec![true; 3]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -808,11 +808,11 @@ fn new_document_from_state(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let created = date_param(p, "created", C)?;
|
||||
let st = s.doc()?;
|
||||
// The row as the panel lists it now: keeping an edit in progress below changes the rows.
|
||||
let chosen = match p.get("index") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(v) => {
|
||||
let state = v.as_u64().and_then(|row| st.history.state(&st.doc, index(row)));
|
||||
Some(state.ok_or_else(|| bad(C, format!("no history state {v}")))?.clone())
|
||||
let chosen = match super::index_opt(p, "index", C)? {
|
||||
None => None,
|
||||
Some(row) => {
|
||||
let v = &p["index"];
|
||||
Some(st.history.state(&st.doc, row).ok_or_else(|| bad(C, format!("no history state {v}")))?.clone())
|
||||
}
|
||||
};
|
||||
settle_interaction(s)?;
|
||||
@@ -1276,23 +1276,28 @@ pub(crate) fn place_clip(s: &mut Session, clip: &Clipboard, center: vectorcraft_
|
||||
/// The artboards Paste in Place, in Front or in Back puts a copy on, in artboard order: `artboard`
|
||||
/// (the active one, #693), else `artboards`, else, while the Artboard tool is chosen with several
|
||||
/// artboards selected, those (noted in the journal as `artboards`, so a replay pastes on the same
|
||||
/// ones); `None` when none is named. A named index that is not an artboard of the document, a
|
||||
/// repeated one or an empty list is an error.
|
||||
/// ones); `None` when none is named. A named value that is not a whole number (null included), a
|
||||
/// named index that is not an artboard of the document, a repeated one or an empty list is an
|
||||
/// error; every value is checked for its form before any is checked against the artboards.
|
||||
fn paste_targets(s: &mut Session, p: &Value, cmd: &str) -> Result<Option<Vec<usize>>> {
|
||||
let n = s.doc()?.doc.artboards.len();
|
||||
let one = |v: &Value| v.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|i| *i < n);
|
||||
let single = match p.get("artboard") {
|
||||
Some(v) => Some(one(v).ok_or_else(|| bad(cmd, "`artboard` must be the index of an artboard of the document"))?),
|
||||
None => None,
|
||||
};
|
||||
let listed = match p.get("artboards") {
|
||||
let single = p.get("artboard").map(|v| v.as_u64().map(index).ok_or_else(|| bad(cmd, "`artboard` must be a whole number"))).transpose()?;
|
||||
let entries = match p.get("artboards") {
|
||||
Some(v) => {
|
||||
let list = v.as_array().filter(|a| !a.is_empty()).ok_or_else(|| bad(cmd, "`artboards` must be a list of artboard indices"))?;
|
||||
let mut all = list
|
||||
.iter()
|
||||
.map(one)
|
||||
.collect::<Option<Vec<usize>>>()
|
||||
.ok_or_else(|| bad(cmd, "`artboards` names an artboard the document does not have"))?;
|
||||
let all = list.iter().map(|i| i.as_u64().map(index)).collect::<Option<Vec<usize>>>();
|
||||
Some(all.ok_or_else(|| bad(cmd, "`artboards` must contain whole numbers"))?)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
if single.is_some_and(|i| i >= n) {
|
||||
return Err(bad(cmd, "`artboard` must be the index of an artboard of the document"));
|
||||
}
|
||||
let listed = match entries {
|
||||
Some(mut all) => {
|
||||
if all.iter().any(|i| *i >= n) {
|
||||
return Err(bad(cmd, "`artboards` names an artboard the document does not have"));
|
||||
}
|
||||
all.sort_unstable();
|
||||
if all.windows(2).any(|w| w[0] == w[1]) {
|
||||
return Err(bad(cmd, "`artboards` names an artboard twice"));
|
||||
|
||||
@@ -66,11 +66,14 @@ use serde_json::{Value, json};
|
||||
|
||||
pub use action_batch::batch_overwrites_one_file;
|
||||
pub use dxf::{UNSUPPORTED, Unsupported, unsupported};
|
||||
pub use encode::{ARTBOARD_PARAMS, ArtboardPick, Encoded, Note, NoteKind, encode, encode_all, encode_with_notes, encode_with_warnings, note_texts};
|
||||
pub use encode::{
|
||||
ARTBOARD_PARAMS, ArtboardPick, Encoded, Note, NoteKind, encode, encode_all, encode_with_notes, encode_with_warnings, export_art_bounds,
|
||||
note_texts,
|
||||
};
|
||||
pub(crate) use encode::{anti_alias, background, with_single_artboard};
|
||||
pub(crate) use export::with_artboard_fills;
|
||||
pub(crate) use export::{EXPORT_PARAMS, export_crop, isolated};
|
||||
pub use export::{export_doc, export_source, unused_option_notes};
|
||||
pub use export::{export_doc, export_source, selection_doc, unused_option_notes};
|
||||
use load::err;
|
||||
pub(crate) use load::import_svg;
|
||||
pub(crate) use load::is_placeholder;
|
||||
|
||||
@@ -12,6 +12,8 @@ use serde_json::json;
|
||||
use super::super::{Result, Session, bad};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::super::{check_switches, find_command, switch_or, text_param};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use crate::EngineError;
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(super) fn action_batch(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
@@ -58,6 +60,10 @@ pub(super) fn action_batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if id == "command.batch" || id == "action.batch" {
|
||||
return Err(bad(C, "batches cannot nest"));
|
||||
}
|
||||
// `command.batch` refuses the batch when it reaches this step, which would fail every file or data set it plays.
|
||||
if id == "prefs.import" {
|
||||
return Err(bad(C, format!("commands[{i}]: `prefs.import` runs on its own, not as a batch step")));
|
||||
}
|
||||
if find_command(id).is_none() {
|
||||
return Err(bad(
|
||||
C,
|
||||
@@ -213,7 +219,7 @@ fn batch_folder(s: &mut Session, cmd: &str, p: &Value, override_open: bool, run:
|
||||
// open, so its artboard files count ([`dataset_output_paths`]). No output takes the name of a
|
||||
// source file in the destination folder, other than that file's own output, or of a subfolder
|
||||
// of the destination folder that holds source files.
|
||||
let steps = filter_steps(run.steps, override_open, false);
|
||||
let (steps, places) = filter_steps(run.steps, override_open, false);
|
||||
let run = Run { steps: &steps, ..*run };
|
||||
let in_dest: Vec<Option<(String, bool)>> = files.iter().map(|path| name_in_folder(path, run.dest_folder)).collect();
|
||||
let mut picker =
|
||||
@@ -228,7 +234,7 @@ fn batch_folder(s: &mut Session, cmd: &str, p: &Value, override_open: bool, run:
|
||||
let outputs = dataset_output_extensions(&run, doc, &ext);
|
||||
picker.pick(&base, |stem| output_names(run.dest_folder, stem, &outputs, doc), own.as_deref())
|
||||
};
|
||||
match process_one_file(s, &run, path, &ext, pick) {
|
||||
match process_one_file(s, &run, &places, path, &ext, pick) {
|
||||
Ok(row) => processed.push(row),
|
||||
Err(e) => {
|
||||
failed += 1;
|
||||
@@ -266,12 +272,12 @@ fn batch_datasets(s: &mut Session, cmd: &str, run: &Run<'_>) -> Result<Value> {
|
||||
}
|
||||
let doc_stem = st.path.as_deref().and_then(|p| std::path::Path::new(p).file_stem().and_then(|s| s.to_str())).unwrap_or("Untitled").to_string();
|
||||
let stems = dataset_stems(&names, &doc_stem, run.dataset_file_naming, run, &st.doc)?;
|
||||
let steps = filter_steps(run.steps, true, false);
|
||||
let (steps, places) = filter_steps(run.steps, true, false);
|
||||
let run = Run { steps: &steps, ..*run };
|
||||
let mut processed = Vec::new();
|
||||
let mut failed = 0usize;
|
||||
for (name, stem) in names.iter().zip(&stems) {
|
||||
match process_one_dataset(s, &run, name, stem) {
|
||||
match process_one_dataset(s, &run, &places, name, stem) {
|
||||
Ok(row) => processed.push(row),
|
||||
Err(e) => {
|
||||
failed += 1;
|
||||
@@ -347,11 +353,13 @@ impl StemPicker {
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop Open (and optionally Close) steps when the batch supplies the file itself.
|
||||
/// Drop Open (and optionally Close) steps when the batch supplies the file itself → the steps that
|
||||
/// stay, and the index of each in `cmds`.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn filter_steps(cmds: &[Value], drop_open: bool, drop_close: bool) -> Vec<Value> {
|
||||
fn filter_steps(cmds: &[Value], drop_open: bool, drop_close: bool) -> (Vec<Value>, Vec<usize>) {
|
||||
cmds.iter()
|
||||
.filter(|c| {
|
||||
.enumerate()
|
||||
.filter(|(_, c)| {
|
||||
let id = c.get("command").and_then(Value::as_str).unwrap_or("");
|
||||
if drop_open && matches!(id, "document.open" | "file.open") {
|
||||
return false;
|
||||
@@ -361,14 +369,44 @@ fn filter_steps(cmds: &[Value], drop_open: bool, drop_close: bool) -> Vec<Value>
|
||||
}
|
||||
true
|
||||
})
|
||||
.cloned()
|
||||
.collect()
|
||||
.map(|(i, c)| (c.clone(), i))
|
||||
.unzip()
|
||||
}
|
||||
|
||||
/// Plays `commands`, the steps of `run` with their paths rewritten, as one `command.batch`. When a
|
||||
/// step fails, the error names it by its place in the caller's `commands`, from 1, counting the Open
|
||||
/// steps the batch skipped (`places` gives the index there of each step of `run`):
|
||||
/// ``action step 3 (`object.move`) failed: …``. Any other error, such as one about the whole batch,
|
||||
/// stays as it is.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn play_steps(s: &mut Session, run: &Run<'_>, places: &[usize], commands: Vec<Value>) -> Result<Value> {
|
||||
s.execute("command.batch", &json!({"label": run.label, "commands": commands})).map_err(|e| {
|
||||
let text = e.to_string();
|
||||
let Some((n, id, reason)) = batch_step_failure(&text) else { return e };
|
||||
let same = run.steps.get(n).and_then(|c| c.get("command")).and_then(Value::as_str) == Some(id);
|
||||
match places.get(n) {
|
||||
Some(place) if same => EngineError::Other(format!("action step {} (`{id}`) failed: {reason}", place + 1)),
|
||||
_ => e,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The step number, command id and reason in the error `command.batch` gives when one of its steps
|
||||
/// fails (``batch step 2 (`object.move`) failed: …``); none for any other error.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn batch_step_failure(e: &str) -> Option<(usize, &str, &str)> {
|
||||
let rest = e.strip_prefix("batch step ")?;
|
||||
let digits = rest.find(|c: char| !c.is_ascii_digit())?;
|
||||
let n = rest[..digits].parse().ok()?;
|
||||
let (id, reason) = rest[digits..].strip_prefix(" (`")?.split_once("`) failed: ")?;
|
||||
Some((n, id, reason))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn process_one_file(
|
||||
s: &mut Session,
|
||||
run: &Run<'_>,
|
||||
places: &[usize],
|
||||
path: &str,
|
||||
ext: &str,
|
||||
stem_for: impl FnOnce(&vectorcraft_doc::Document) -> String,
|
||||
@@ -376,17 +414,17 @@ fn process_one_file(
|
||||
s.execute("document.open", &json!({"path": path}))?;
|
||||
let stem = stem_for(&s.doc()?.doc);
|
||||
let rewritten = rewrite_paths(run.steps, run.override_save, run.override_export, run.dest_folder, &stem, ext);
|
||||
let batch = s.execute("command.batch", &json!({"label": run.label, "commands": rewritten}))?;
|
||||
let batch = play_steps(s, run, places, rewritten)?;
|
||||
// Folder sources open a file per pass: close after Save and Close / Folder.
|
||||
finish_destination(s, run, &stem, ext, path, true)?;
|
||||
Ok(json!({"path": path, "result": batch}))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn process_one_dataset(s: &mut Session, run: &Run<'_>, name: &str, stem: &str) -> Result<Value> {
|
||||
fn process_one_dataset(s: &mut Session, run: &Run<'_>, places: &[usize], name: &str, stem: &str) -> Result<Value> {
|
||||
s.execute("dataset.select", &json!({"name": name}))?;
|
||||
let rewritten = rewrite_paths(run.steps, run.override_save, run.override_export, run.dest_folder, stem, "vectorcraft");
|
||||
let batch = s.execute("command.batch", &json!({"label": run.label, "commands": rewritten}))?;
|
||||
let batch = play_steps(s, run, places, rewritten)?;
|
||||
// Data sets share one open document: write each row out but leave it open for the next.
|
||||
finish_destination(s, run, stem, "vectorcraft", "", false)?;
|
||||
Ok(json!({"dataset": name, "result": batch}))
|
||||
@@ -1454,7 +1492,8 @@ mod tests {
|
||||
assert_eq!((r["failed"].as_u64(), r["processed"].as_array().map(Vec::len)), (Some(rows), Some(rows as usize)), "{r}");
|
||||
for row in r["processed"].as_array().unwrap() {
|
||||
let e = row["error"].as_str().unwrap_or_default();
|
||||
let want = format!("batch step 0 (`document.save`) failed: automation path rejected: outside the write root {root}: doc.vectorcraft");
|
||||
let want =
|
||||
format!("action step 1 (`document.save`) failed: automation path rejected: outside the write root {root}: doc.vectorcraft");
|
||||
assert_eq!(e, want, "{r}");
|
||||
}
|
||||
assert!(!r.to_string().contains(&hidden), "{r}");
|
||||
@@ -2224,4 +2263,144 @@ mod tests {
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
/// The steps of the step-number tests: an Open the batch skips, a step that works, and one that
|
||||
/// fails (an Align with nothing selected).
|
||||
fn open_then_failing_align() -> Value {
|
||||
json!([
|
||||
{"command": "document.open", "params": {"path": "/no/such/file.svg"}},
|
||||
{"command": "object.unlockAll", "params": {}},
|
||||
{"command": "object.align", "params": {}}
|
||||
])
|
||||
}
|
||||
|
||||
/// The step a source's error names, after `action step ` and before ` failed: `.
|
||||
fn named_step(r: &Value, row: usize) -> String {
|
||||
let e = r["processed"][row]["error"].as_str().unwrap_or_default();
|
||||
assert!(!e.contains("batch step"), "{r}");
|
||||
e.strip_prefix("action step ").and_then(|e| e.split_once(" failed: ")).map(|(step, _)| step.to_string()).unwrap_or_else(|| e.to_string())
|
||||
}
|
||||
|
||||
/// A failed step of a folder batch is named by its place in the `commands` sent, from 1, with the
|
||||
/// Open step that Override Open skips counted; the reason follows unchanged.
|
||||
#[test]
|
||||
fn a_folder_batch_error_names_the_step_in_the_commands_sent() {
|
||||
let src = tmp("step-number-src");
|
||||
write_svg(&src, "a.svg", "#f00");
|
||||
write_svg(&src, "b.svg", "#0f0");
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 80})).unwrap();
|
||||
// `command.batch` itself still numbers its steps from 0.
|
||||
let reason = s
|
||||
.execute(
|
||||
"command.batch",
|
||||
&json!({"commands": [{"command": "object.unlockAll", "params": {}}, {"command": "object.align", "params": {}}]}),
|
||||
)
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
let reason = reason.strip_prefix("batch step 1 (`object.align`) failed: ").unwrap_or_else(|| panic!("{reason}")).to_string();
|
||||
for (stop, rows) in [(true, 1), (false, 2)] {
|
||||
let r = s
|
||||
.execute("action.batch", &json!({"folder": src.to_string_lossy(), "stopOnError": stop, "commands": open_then_failing_align()}))
|
||||
.unwrap();
|
||||
assert_eq!(r["failed"], rows, "{r}");
|
||||
for row in 0..rows {
|
||||
assert_eq!(r["processed"][row]["error"], format!("action step 3 (`object.align`) failed: {reason}"), "{r}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// With Override Open off, a recorded Open step runs, and its failure is named as the first step.
|
||||
#[test]
|
||||
fn a_recorded_open_that_fails_is_the_first_step() {
|
||||
let src = tmp("step-number-open-src");
|
||||
write_svg(&src, "a.svg", "#f00");
|
||||
let mut s = Session::new();
|
||||
let r = s
|
||||
.execute("action.batch", &json!({"folder": src.to_string_lossy(), "overrideOpen": false, "commands": open_then_failing_align()}))
|
||||
.unwrap();
|
||||
assert_eq!(named_step(&r, 0), "1 (`document.open`)", "{r}");
|
||||
}
|
||||
|
||||
/// A data set batch, which always skips Open steps, names a failed step by its place in the
|
||||
/// `commands` sent for every data set it fails on.
|
||||
#[test]
|
||||
fn a_data_set_batch_error_names_the_step_in_the_commands_sent() {
|
||||
let mut s = with_data_sets(&["Alpha", "Beta"]);
|
||||
for (stop, rows) in [(true, 1), (false, 2)] {
|
||||
let r = s.execute("action.batch", &json!({"source": "datasets", "stopOnError": stop, "commands": open_then_failing_align()})).unwrap();
|
||||
assert_eq!(r["failed"], rows, "{r}");
|
||||
for row in 0..rows {
|
||||
assert_eq!(named_step(&r, row), "3 (`object.align`)", "{r}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A recorded export that Override Export points into the destination folder keeps its place in
|
||||
/// the `commands` sent when it fails.
|
||||
#[test]
|
||||
fn a_redirected_export_that_fails_keeps_its_place() {
|
||||
let src = tmp("step-number-export-src");
|
||||
write_svg(&src, "a.svg", "#f00");
|
||||
let dest = tmp("step-number-export-out");
|
||||
// A file where the export's folder goes, so the export cannot write its files.
|
||||
std::fs::write(dest.join("a"), "taken").unwrap();
|
||||
let mut s = Session::new();
|
||||
let r = s
|
||||
.execute(
|
||||
"action.batch",
|
||||
&json!({
|
||||
"folder": src.to_string_lossy(),
|
||||
"destinationFolder": dest.to_string_lossy(),
|
||||
"commands": [
|
||||
{"command": "document.open", "params": {"path": "/no/such/file.svg"}},
|
||||
{"command": "object.unlockAll", "params": {}},
|
||||
{"command": "document.exportForScreens", "params": {"formats": [{"format": "svg"}]}}
|
||||
]
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r["failed"], 1, "{r}");
|
||||
assert_eq!(named_step(&r, 0), "3 (`document.exportForScreens`)", "{r}");
|
||||
}
|
||||
|
||||
/// A source file that does not open, which the batch opens itself, gives the open's own error
|
||||
/// with no step number.
|
||||
#[test]
|
||||
fn a_source_that_does_not_open_names_no_step() {
|
||||
let src = tmp("step-number-bad-src");
|
||||
std::fs::write(src.join("a.svg"), "not an svg").unwrap();
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("action.batch", &json!({"folder": src.to_string_lossy(), "commands": open_then_failing_align()})).unwrap();
|
||||
assert_eq!(r["failed"], 1, "{r}");
|
||||
let e = r["processed"][0]["error"].as_str().unwrap_or_default();
|
||||
assert!(!e.is_empty() && !e.contains("action step") && !e.contains("batch step"), "{r}");
|
||||
}
|
||||
|
||||
/// A `prefs.import` step, which `command.batch` does not run, is refused before any file opens.
|
||||
#[test]
|
||||
fn a_prefs_import_step_is_refused_before_any_file_opens() {
|
||||
let src = tmp("step-number-prefs-src");
|
||||
write_svg(&src, "a.svg", "#f00");
|
||||
let mut s = Session::new();
|
||||
let p = json!({"folder": src.to_string_lossy(), "commands": [{"command": "object.unlockAll"}, {"command": "prefs.import", "params": {}}]});
|
||||
let e = s.execute("action.batch", &p).unwrap_err().to_string();
|
||||
assert!(e.contains("commands[1]: `prefs.import` runs on its own, not as a batch step"), "{e}");
|
||||
assert!(s.active().is_none(), "no file was opened");
|
||||
}
|
||||
|
||||
/// Only the error `command.batch` gives for a failed step is read as one.
|
||||
#[test]
|
||||
fn batch_step_failure_reads_only_a_step_error() {
|
||||
assert_eq!(batch_step_failure("batch step 12 (`object.move`) failed: no selection"), Some((12, "object.move", "no selection")));
|
||||
for e in [
|
||||
"batch step (`object.move`) failed: no selection",
|
||||
"batch step 99999999999999999999999 (`object.move`) failed: x",
|
||||
"batch step 1 `object.move` failed: x",
|
||||
"invalid parameters for `command.batch`: batches cannot nest",
|
||||
"batch step 1",
|
||||
] {
|
||||
assert_eq!(batch_step_failure(e), None, "{e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -2,11 +2,13 @@
|
||||
//! (unknown keys are ignored, so one params object can carry the options of several formats).
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde_json::Value;
|
||||
use vectorcraft_doc::{Artboard, Document};
|
||||
use vectorcraft_doc::{Artboard, Document, Node, NodeKind};
|
||||
use vectorcraft_geom::Rect;
|
||||
use vectorcraft_render::AntiAlias;
|
||||
use vectorcraft_render::encode::jpeg::{self, JpegOptions};
|
||||
@@ -419,13 +421,15 @@ pub(super) fn use_artboards(cmd: &str, p: &Value) -> Result<Option<bool>> {
|
||||
|
||||
/// With `useArtboards: false` in `p`: `doc` without its opacity-mask or symbol editing layer and
|
||||
/// with one artboard, the bounds of its visible art, and `p` without the artboard choice. `None`
|
||||
/// when `useArtboards` is absent, null or true. A document with no visible art is refused.
|
||||
pub(super) fn art_page(cmd: &str, doc: &Document, p: &Value) -> Result<Option<(Document, Value)>> {
|
||||
/// when `useArtboards` is absent, null or true. The objects that `left_out` picks (layers or
|
||||
/// objects the format leaves out, see [`hidden_nodes`]) are not measured, and a document with no
|
||||
/// other visible art is refused.
|
||||
pub(super) fn art_page(cmd: &str, doc: &Document, p: &Value, left_out: impl Fn(&Node) -> bool) -> Result<Option<(Document, Value)>> {
|
||||
if use_artboards(cmd, p)? != Some(false) {
|
||||
return Ok(None);
|
||||
}
|
||||
let doc = &*doc.without_edit_modes();
|
||||
let bounds = vectorcraft_render::encode::art_bounds(doc).ok_or_else(|| bad(cmd, "nothing to export: the document has no visible art"))?;
|
||||
let bounds = bounds_without(doc, &left_out).ok_or_else(|| bad(cmd, "nothing to export: the document has no visible art"))?;
|
||||
let mut q = super::export::without_artboards(p);
|
||||
if let Some(o) = q.as_object_mut() {
|
||||
o.remove("useArtboards");
|
||||
@@ -433,6 +437,107 @@ pub(super) fn art_page(cmd: &str, doc: &Document, p: &Value) -> Result<Option<(D
|
||||
Ok(Some((single_artboard(doc, bounds, "Art"), q)))
|
||||
}
|
||||
|
||||
/// The bounds of the visible art of `doc` that a `format` file of the art's bounds draws, as
|
||||
/// [`art_page`] measures it with that format's default options: for HP-GL without what a plot
|
||||
/// leaves out ([`vectorcraft_cad::hpgl::write::plots_nothing`]), for other formats all of it (the
|
||||
/// non-printing layers a PDF leaves out depend on options chosen after the save panel). `None`
|
||||
/// when there is none, which such an export refuses.
|
||||
pub fn export_art_bounds(doc: &Document, format: &str) -> Option<Rect> {
|
||||
let doc = &*doc.without_edit_modes();
|
||||
bounds_without(doc, &|n| format == "hpgl" && vectorcraft_cad::hpgl::write::plots_nothing(doc, n))
|
||||
}
|
||||
|
||||
/// The bounds of the visible art of `doc` with the objects that `left_out` picks hidden
|
||||
/// ([`hidden_nodes`]) and the ones in the art of the symbols that instances show taken out
|
||||
/// ([`without_nodes`]: symbol art is measured with its hidden objects). An instance of a symbol
|
||||
/// whose art is all picked or hidden is hidden too. The art of a dynamic symbol is measured whole:
|
||||
/// an instance can paint its objects, and finds them by their places in the art.
|
||||
fn bounds_without(doc: &Document, left_out: &dyn Fn(&Node) -> bool) -> Option<Rect> {
|
||||
// The symbols instances show (the first of each name) that aren't dynamic.
|
||||
let mut names = HashSet::new();
|
||||
let shown: Vec<(usize, &vectorcraft_doc::Symbol)> =
|
||||
doc.symbols.iter().enumerate().filter(|(_, s)| names.insert(s.name.as_str())).filter(|(_, s)| !s.dynamic).collect();
|
||||
// The symbols whose art `left_out` leaves nothing of, those that only hold instances of such
|
||||
// symbols included.
|
||||
let mut empty: HashSet<&str> = HashSet::new();
|
||||
while let Some((_, s)) = shown.iter().find(|(_, s)| !empty.contains(s.name.as_str()) && all_left_out(&s.art, left_out, &empty)) {
|
||||
empty.insert(&s.name);
|
||||
}
|
||||
let left_out =
|
||||
&|n: &Node| left_out(n) || matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if empty.contains(symbol.as_str()) && !has_effects(n));
|
||||
let layers = hidden_nodes(&doc.layers, left_out);
|
||||
let symbols: Vec<(usize, Arc<Node>)> = shown
|
||||
.iter()
|
||||
.filter(|(_, s)| !empty.contains(s.name.as_str()))
|
||||
.filter_map(|(i, s)| without_nodes(&s.art, left_out).map(|art| (*i, art)))
|
||||
.collect();
|
||||
if layers.is_none() && symbols.is_empty() {
|
||||
return vectorcraft_render::encode::art_bounds(doc);
|
||||
}
|
||||
let mut d = doc.clone();
|
||||
if let Some(layers) = layers {
|
||||
d.layers = layers;
|
||||
}
|
||||
for (i, art) in symbols {
|
||||
if let Some(s) = d.symbols.get_mut(i) {
|
||||
s.art = art;
|
||||
}
|
||||
}
|
||||
vectorcraft_render::encode::art_bounds(&d)
|
||||
}
|
||||
|
||||
/// Whether `n` is hidden, picked by `left_out`, an instance of one of the `empty` symbols, or a
|
||||
/// layer or a group holding only such objects (its clipping path among them when it clips). A
|
||||
/// Shaper group, or a layer, group or instance with effects, fills or strokes of its own, is none
|
||||
/// of these unless it is hidden or picked.
|
||||
fn all_left_out(n: &Node, left_out: &dyn Fn(&Node) -> bool, empty: &HashSet<&str>) -> bool {
|
||||
!n.visible
|
||||
|| left_out(n)
|
||||
|| !has_effects(n)
|
||||
&& n.extras().shaper.is_none()
|
||||
&& match &n.kind {
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().all(|c| all_left_out(c, left_out, empty)),
|
||||
NodeKind::SymbolInstance { symbol, .. } => empty.contains(symbol.as_str()),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `n` has a visible effect, fill or stroke of its own, which the objects it holds can
|
||||
/// take part in.
|
||||
fn has_effects(n: &Node) -> bool {
|
||||
n.appearance.effects.iter().any(|e| e.visible) || n.appearance.items.iter().any(|i| i.visible())
|
||||
}
|
||||
|
||||
/// `n` without the objects that `left_out` picks in it, when it is a layer or a group, and in the
|
||||
/// layers and groups in it at any depth; `None` when it picks none of them. A clipping layer or
|
||||
/// group keeps its clipping path, its first object, and a Shaper group and a layer or group with
|
||||
/// effects, fills or strokes of its own keep all they hold.
|
||||
fn without_nodes(n: &Arc<Node>, left_out: &dyn Fn(&Node) -> bool) -> Option<Arc<Node>> {
|
||||
let (NodeKind::Layer { children, clip, .. } | NodeKind::Group { children, clip }) = &n.kind else { return None };
|
||||
if has_effects(n) || n.extras().shaper.is_some() {
|
||||
return None;
|
||||
}
|
||||
let mut changed = false;
|
||||
let kept: Vec<Arc<Node>> = children
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, c)| {
|
||||
if left_out(c) && !(*clip && i == 0) {
|
||||
changed = true;
|
||||
return None;
|
||||
}
|
||||
Some(without_nodes(c, left_out).inspect(|_| changed = true).unwrap_or_else(|| c.clone()))
|
||||
})
|
||||
.collect();
|
||||
changed.then(|| {
|
||||
let mut new = (**n).clone();
|
||||
if let NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } = &mut new.kind {
|
||||
*children = kept;
|
||||
}
|
||||
Arc::new(new)
|
||||
})
|
||||
}
|
||||
|
||||
/// The `rect` param of a raster export: `[x, y, width, height]` in points, y down. `None` when
|
||||
/// absent; an error when it is not four finite numbers with a positive size, when the format isn't
|
||||
/// a raster one, or when it comes with an artboard choice (`rect` is the area, so those would
|
||||
@@ -481,6 +586,35 @@ pub(crate) fn with_single_artboard(mut d: Document, rect: Rect, name: &str) -> D
|
||||
d
|
||||
}
|
||||
|
||||
/// `nodes` with the visible objects that `left_out` picks hidden, in layers, sublayers and groups
|
||||
/// that don't clip, at any depth (what an object it picks holds is not looked at); `None` when it
|
||||
/// picks none of them. Clipping layers are looked in too, as their sublayers can be picked.
|
||||
pub(super) fn hidden_nodes(nodes: &[Arc<Node>], left_out: &dyn Fn(&Node) -> bool) -> Option<Vec<Arc<Node>>> {
|
||||
let mut out: Option<Vec<Arc<Node>>> = None;
|
||||
for (i, l) in nodes.iter().enumerate() {
|
||||
let new = if left_out(l) {
|
||||
l.visible.then(|| {
|
||||
let mut n = (**l).clone();
|
||||
n.visible = false;
|
||||
Arc::new(n)
|
||||
})
|
||||
} else {
|
||||
let (NodeKind::Layer { children, .. } | NodeKind::Group { children, clip: false }) = &l.kind else { continue };
|
||||
hidden_nodes(children, left_out).map(|c| {
|
||||
let mut n = (**l).clone();
|
||||
if let NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } = &mut n.kind {
|
||||
*children = c;
|
||||
}
|
||||
Arc::new(n)
|
||||
})
|
||||
};
|
||||
if let Some(slot) = new.and_then(|new| Some((out.get_or_insert_with(|| nodes.to_vec()).get_mut(i)?, new))) {
|
||||
*slot.0 = slot.1;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn boards<T>(r: std::result::Result<T, String>) -> Result<T> {
|
||||
r.map_err(|e| bad(C, e))
|
||||
}
|
||||
@@ -636,8 +770,9 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
{
|
||||
return Ok(enc);
|
||||
}
|
||||
let left_out = |n: &Node| f.id == "hpgl" && vectorcraft_cad::hpgl::write::plots_nothing(doc, n);
|
||||
if use_artboards == Some(false)
|
||||
&& let Some((art, q)) = art_page(C, doc, p)?
|
||||
&& let Some((art, q)) = art_page(C, doc, p, left_out)?
|
||||
{
|
||||
return encode_files(&art, f, &q);
|
||||
}
|
||||
|
||||
@@ -295,8 +295,14 @@ fn source<'a>(s: &'a mut Session, f: &Format, p: &Value, cmd: &str) -> Result<(C
|
||||
/// ([`isolated`]), with one artboard: their crop. With `text`, the objects alone on one layer, so a
|
||||
/// text export holds the type of the selected objects and not that of a clipping path around them.
|
||||
fn selection(s: &mut Session, cmd: &str, text: bool) -> Result<(Document, vectorcraft_geom::Rect)> {
|
||||
let ids = selected_artwork(s)?;
|
||||
let doc = &s.doc()?.doc;
|
||||
selection_doc(s.doc()?, cmd, text)
|
||||
}
|
||||
|
||||
/// The document an Export Selection of `st` writes and its crop, as `document.exportSelection`
|
||||
/// writes it ([`selection`]); `cmd` names the command in the error when nothing selected draws.
|
||||
pub fn selection_doc(st: &DocState, cmd: &str, text: bool) -> Result<(Document, vectorcraft_geom::Rect)> {
|
||||
let ids = artwork_of(st);
|
||||
let doc = &st.doc;
|
||||
let (mut d, bounds) = isolated(doc, &ids, "Selection").ok_or_else(|| bad(cmd, "select something to export"))?;
|
||||
if text {
|
||||
let mut layer = Node::layer(d.alloc_id(), "Selection", vectorcraft_doc::LayerColor::Preset(0));
|
||||
@@ -312,12 +318,16 @@ fn selection(s: &mut Session, cmd: &str, text: bool) -> Result<(Document, vector
|
||||
/// layers are guides and are left out. With an object of a dynamic symbol instance's art selected,
|
||||
/// the instance is exported whole.
|
||||
pub(crate) fn selected_artwork(s: &Session) -> Result<Vec<NodeId>> {
|
||||
let st = s.doc()?;
|
||||
Ok(artwork_of(s.doc()?))
|
||||
}
|
||||
|
||||
/// [`selected_artwork`] of document `st`.
|
||||
fn artwork_of(st: &DocState) -> Vec<NodeId> {
|
||||
let ids = edit::roots_of(&st.doc, st.selection.in_paint_order(&st.doc));
|
||||
let is_template = |id| st.doc.node(id).is_some_and(|l| matches!(l.kind, NodeKind::Layer { template: true, .. }));
|
||||
// On a template layer or sublayer, at any depth.
|
||||
let on_template = |id| st.doc.ancestry(id).is_some_and(|a| a.into_iter().any(is_template));
|
||||
Ok(ids.into_iter().filter(|id| !on_template(*id)).collect())
|
||||
ids.into_iter().filter(|id| !on_template(*id)).collect()
|
||||
}
|
||||
|
||||
/// The crop of an export of objects `ids` of `doc` alone ([`isolated`]): the bounds the renderer
|
||||
|
||||
@@ -550,9 +550,10 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
// Optical Margin Alignment setting and writing direction. When that changes the direction of a
|
||||
// frame of a restored document, the story flows through that frame's thread again. Threaded
|
||||
// frames keep their size: Auto Size is off for them. The story is laid out in the document's
|
||||
// own composite fonts.
|
||||
// own composite fonts, and type naming one the document does not define flows as in a missing
|
||||
// font, also when the document defines none.
|
||||
let fonts = if doc.text_threads.is_empty() { Default::default() } else { doc.composite_fonts.clone() };
|
||||
let lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&fonts);
|
||||
let lent = vectorcraft_text::FontDb::global().lend_document_composite_fonts(&fonts);
|
||||
if !doc.text_threads.is_empty() && !restored {
|
||||
crate::cmd::threads::reflow(&Document::new(1.0, 1.0), &mut doc);
|
||||
} else if !doc.text_threads.is_empty() {
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -757,8 +757,9 @@ pub const AI_EDITING_NEEDS_THE_ARTBOARDS: &str =
|
||||
pub const ART_PAGE_NEEDS_PDF: &str = "pdfCompatible: false needs the artboards to keep the editable artwork when useArtboards is false";
|
||||
|
||||
/// With `useArtboards: false` in `p`: the PDF-compatible `.ai` file of one page, the bounds of
|
||||
/// `doc`'s visible art ([`super::encode::art_page`]). It carries neither the native document nor
|
||||
/// the editing copy for other apps, and its notes end with [`AI_EDITING_NEEDS_THE_ARTBOARDS`].
|
||||
/// `doc`'s visible art on the layers its pages draw ([`super::pdf::art_page`]). It carries neither
|
||||
/// the native document nor the editing copy for other apps, and its notes end with
|
||||
/// [`AI_EDITING_NEEDS_THE_ARTBOARDS`].
|
||||
/// `pdfCompatible: false` is refused. `None` when `p` asks for the artboards or for a legacy
|
||||
/// version 7 `.ai` file.
|
||||
pub(super) fn encode_ai_art_page(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result<Option<Encoded>> {
|
||||
@@ -768,7 +769,7 @@ pub(super) fn encode_ai_art_page(cmd: &str, f: &Format, doc: &Document, p: &Valu
|
||||
if !bool_or(p, "pdfCompatible", true) {
|
||||
return Err(bad(cmd, ART_PAGE_NEEDS_PDF));
|
||||
}
|
||||
let Some((art, q)) = super::encode::art_page(cmd, doc, p)? else { return Ok(None) };
|
||||
let Some((art, q)) = super::pdf::art_page(cmd, doc, &ai_pdf_params(p, false))? else { return Ok(None) };
|
||||
let mut enc = encode_ai_pages(cmd, f, &art, &q, false)?;
|
||||
enc.setting_notes.push(AI_EDITING_NEEDS_THE_ARTBOARDS.to_string());
|
||||
Ok(Some(enc))
|
||||
@@ -784,9 +785,10 @@ pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Res
|
||||
encode_ai_pages(cmd, f, doc, p, true)
|
||||
}
|
||||
|
||||
/// [`encode_ai`] of a `.ai` file with or without PDF content, carrying the native document and
|
||||
/// the editing copy for other apps when `editing` is true, and neither otherwise.
|
||||
fn encode_ai_pages(cmd: &str, f: &Format, doc: &Document, p: &Value, editing: bool) -> Result<Encoded> {
|
||||
/// `p` with the PDF options a `.ai` file is written with: Preserve Editing when `editing` is true,
|
||||
/// layers unless a standard decides, long pages with a `UserUnit`, and `compress` as
|
||||
/// `compression.compressText`.
|
||||
fn ai_pdf_params(p: &Value, editing: bool) -> Value {
|
||||
let mut params = if p.is_object() { p.clone() } else { json!({}) };
|
||||
if let Some(o) = params.as_object_mut() {
|
||||
o.insert("preserveEditing".into(), json!(editing));
|
||||
@@ -805,6 +807,13 @@ fn encode_ai_pages(cmd: &str, f: &Format, doc: &Document, p: &Value, editing: bo
|
||||
}
|
||||
}
|
||||
}
|
||||
params
|
||||
}
|
||||
|
||||
/// [`encode_ai`] of a `.ai` file with or without PDF content, carrying the native document and
|
||||
/// the editing copy for other apps when `editing` is true, and neither otherwise.
|
||||
fn encode_ai_pages(cmd: &str, f: &Format, doc: &Document, p: &Value, editing: bool) -> Result<Encoded> {
|
||||
let params = ai_pdf_params(p, editing);
|
||||
let pdf_compatible = bool_or(¶ms, "pdfCompatible", true);
|
||||
let f = &if pdf_compatible { *f } else { without_pdf(f) };
|
||||
let native_options = super::native::ai_options(cmd, f, doc, ¶ms)?;
|
||||
|
||||
@@ -186,6 +186,22 @@ fn planar_tiffs_read_as_their_chunky_versions() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A 16-bit CMYK TIFF with alpha places with its alpha rounded from 16 bits, planar as chunky.
|
||||
#[test]
|
||||
fn a_16_bit_cmyk_tiff_with_alpha_places_at_16_bits() {
|
||||
let none = vec![0u16; 6];
|
||||
let cyan = vec![129u16, 0, 300, 0, 128, 65535];
|
||||
let alpha = vec![65535u16, 129, 386, 0, 256, 65535];
|
||||
for extra in [1u16, 2] {
|
||||
let channels = [cyan.clone(), none.clone(), none.clone(), none.clone(), alpha.clone()];
|
||||
let chunky = kept(&format!("extra samples {extra}, chunky"), &hand_tiff(5, 16, &[extra], false, &channels));
|
||||
let planar = kept(&format!("extra samples {extra}, planar"), &hand_tiff(5, 16, &[extra], true, &channels));
|
||||
assert_eq!(planar, chunky, "extra samples {extra}: planar reads as chunky");
|
||||
let alphas: Vec<u8> = chunky.1.iter().skip(3).step_by(4).copied().collect();
|
||||
assert_eq!(alphas, [255, 1, 2, 0, 1, 255], "extra samples {extra}: the alpha, rounded from 16 bits");
|
||||
}
|
||||
}
|
||||
|
||||
/// A planar TIFF whose header claims more strips than the decoder can count (here 2^31 + 1 rows
|
||||
/// a strip each, times 5 planes) is refused as too large to draw, without a panic.
|
||||
#[test]
|
||||
|
||||
@@ -424,8 +424,8 @@ fn a_graphic_style_library_in_a_ai_file_without_layers_loads_its_styles() {
|
||||
/BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n{xa}0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n;\n"
|
||||
)
|
||||
};
|
||||
// Styles of one paint (`/SimpleStyle`): a red 2 pt stroke and no fill, and a gradient fill,
|
||||
// which isn't read, so it is left out rather than listed with no paint.
|
||||
// Styles of one paint (`/SimpleStyle`): a red 2 pt stroke and no fill, and a fill with a gradient
|
||||
// the file doesn't define, which is left out rather than listed with no paint.
|
||||
let one_paint = |name: &str, paint: &str| format!("/KnownStyle :\n({name}) /Name ,\n/SimpleStyle :\n{paint}/Paint ;\n/Def ;\n");
|
||||
let styles = format!(
|
||||
"%AI9_BeginArtStyles\n{}{}{}{}{}%AI9_EndArtStyles\n\
|
||||
@@ -465,6 +465,64 @@ fn a_graphic_style_library_in_a_ai_file_without_layers_loads_its_styles() {
|
||||
assert_eq!(styles, [("Red", 1), ("Green", 2), ("Blue", 3), ("Red outline", 4)], "{r}");
|
||||
}
|
||||
|
||||
/// A `.ai` graphic style library's styles that paint with one of the file's gradients by name (a
|
||||
/// fill style's, and the fill or stroke of a style of one paint) load with that gradient at the
|
||||
/// style's angle, fitted to the bounds of each object the style is applied to; one naming a gradient
|
||||
/// the file doesn't define is left out.
|
||||
#[test]
|
||||
fn graphic_styles_in_a_ai_library_that_paint_with_a_named_gradient_load_with_it() {
|
||||
let gradient =
|
||||
"%AI5_BeginGradient: (Sky)\n(Sky) 0 2 Bd\n[\n%_0 0 0 0 0 1 0 2 1 6 50 0 Bs\n%_0 0 0 0 1 1 1 2 1 6 50 100 Bs\nBD\n%AI5_EndGradient\n";
|
||||
let band = "/KnownStyle :\n(Sky band) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\
|
||||
/BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n\
|
||||
0 Bb\n2 (Sky) 0 0 45 100 1 0 0 1 0 0 Bg\n0 BB\n0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n;\n";
|
||||
let one_paint = |name: &str, paint: &str| format!("/KnownStyle :\n({name}) /Name ,\n/SimpleStyle :\n{paint}/Paint ;\n/Def ;\n");
|
||||
let styles = format!(
|
||||
"%AI9_BeginArtStyles\n{band}{}{}{}%AI9_EndArtStyles\n\
|
||||
%AI9_BeginArtStyleList\n(Sky band)\n(Sky fill)\n(Sky outline)\n(Dusk fill)\n%AI9_EndArtStyleList\n",
|
||||
one_paint("Sky fill", "0 O\n0 Bb\n2 (Sky) 0 0 0 100 1 0 0 1 0 0 Bg\n0 BB\n0 1 Xd\n"),
|
||||
one_paint("Sky outline", "0 R\n0 J 0 j 2 w 10 M []0 d\n1 Bb\n2 (Sky) 0 0 90 100 1 0 0 1 0 0 1 Bg\n0 BB\n1 0 Xd\n"),
|
||||
one_paint("Dusk fill", "0 O\n0 Bb\n2 (Dusk) 0 0 0 100 1 0 0 1 0 0 Bg\n0 BB\n0 1 Xd\n")
|
||||
);
|
||||
// A palette with the gradient's swatch, so the document opened from the file shows its gradient.
|
||||
let palette = INKS_PALETTE.replace("0 0 Pb\n", "0 0 Pb\nBb\n2 (Sky) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\n(Sky)\nPc\n");
|
||||
let data = ai::editing_data(200.0, 100.0, &format!("{gradient}{palette}{styles}"));
|
||||
let file = ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f");
|
||||
let mut s = Session::new();
|
||||
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&file), "name": "skies.ai"});
|
||||
let r = s.execute("graphicStyle.loadLibrary", &p).unwrap();
|
||||
let library = r["library"].clone();
|
||||
let lib = s.execute("graphicStyle.library", &json!({"library": library})).unwrap();
|
||||
let names: Vec<&str> = lib["styles"].as_array().unwrap().iter().map(|g| g["name"].as_str().unwrap()).collect();
|
||||
assert_eq!(names, ["Sky band", "Sky fill", "Sky outline"], "{lib}");
|
||||
// The file's gradient, as the document opened from it has its swatch.
|
||||
open(&mut s, "skies.ai", &file, json!({})).unwrap();
|
||||
let sky = match s.doc().unwrap().doc.swatch("Sky").map(|w| w.paint.clone()) {
|
||||
Some(vectorcraft_color::Paint::Gradient(g)) => g.gradient,
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
// Applied to a small and a large rectangle, each gradient is fitted to the rectangle it paints.
|
||||
s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap();
|
||||
for (style, (x, size)) in [("Sky band", (10, 20)), ("Sky fill", (40, 200)), ("Sky outline", (10, 120))] {
|
||||
let rect = json!({"x": x, "y": x, "width": size, "height": size / 2});
|
||||
let id = NodeId(s.execute("shape.rectangle", &rect).unwrap()["id"].as_u64().unwrap());
|
||||
let r = s.execute("graphicStyle.addFromLibrary", &json!({"library": library, "names": [style], "apply": true, "ids": [id.0]})).unwrap();
|
||||
assert_eq!(r["added"], json!([style]), "{r}");
|
||||
let look = &s.doc().unwrap().doc.node(id).unwrap().appearance;
|
||||
let (paint, angle, stroked) = match style {
|
||||
"Sky outline" => (look.stroke().map(|st| &st.paint), 90.0, true),
|
||||
"Sky band" => (look.fill().map(|f| &f.paint), 45.0, false),
|
||||
_ => (look.fill().map(|f| &f.paint), 0.0, false),
|
||||
};
|
||||
let Some(vectorcraft_color::Paint::Gradient(g)) = paint else { panic!("{style}: {look:?}") };
|
||||
assert_eq!((&g.gradient, g.geom, g.angle), (&sky, None, angle), "{style}");
|
||||
assert_eq!(look.stroke().is_some(), stroked, "{style}: {look:?}");
|
||||
if stroked {
|
||||
assert!(look.fill().is_none() && look.stroke().is_some_and(|st| st.width == 2.0), "{look:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A `.ai` symbol library (symbols and their list, no layers) opens with its symbols, and Other
|
||||
/// Library… in the Symbols panel lists them in the list's order.
|
||||
#[test]
|
||||
|
||||
@@ -170,6 +170,113 @@ fn a_plot_reads_back_as_its_art() {
|
||||
assert!((board.height() - (30.0 + pen)).abs() < 0.1, "{board:?}");
|
||||
}
|
||||
|
||||
/// A plot of the art's bounds is measured on the art it plots: art on a non-printing layer, on a
|
||||
/// layer at 0% opacity or at 0% opacity in a group, a placed image and a path that paints nothing
|
||||
/// don't move its origin, a clipping layer is measured as clipped, and a document whose only
|
||||
/// visible art is such art is refused.
|
||||
#[test]
|
||||
fn a_plot_of_the_arts_bounds_leaves_out_the_layers_it_does_not_plot() {
|
||||
let mut s = two_boards();
|
||||
let plot = |s: &mut Session| s.execute("document.export", &json!({"format": "hpgl", "useArtboards": false})).map(|v| bytes(&v));
|
||||
let alone = plot(&mut s).unwrap();
|
||||
let printing = s.doc().unwrap().doc.layers[0].id;
|
||||
for props in [json!({"printable": false}), json!({})] {
|
||||
let layer = s.execute("layer.new", &json!({})).unwrap()["id"].clone();
|
||||
if props.as_object().unwrap().is_empty() {
|
||||
s.execute("transparency.set", &json!({"ids": [layer], "opacity": 0})).unwrap();
|
||||
} else {
|
||||
let mut p = props.clone();
|
||||
p["id"] = layer.clone();
|
||||
s.execute("layer.setProps", &p).unwrap();
|
||||
}
|
||||
s.execute("shape.rectangle", &json!({"x": -300, "y": 500, "width": 20, "height": 20})).unwrap();
|
||||
assert_eq!(plot(&mut s).unwrap(), alone, "{props}");
|
||||
}
|
||||
// An object at 0% opacity in a group, on a layer that plots.
|
||||
s.execute("layer.new", &json!({})).unwrap();
|
||||
let far = s.execute("shape.rectangle", &json!({"x": -500, "y": 700, "width": 20, "height": 20})).unwrap()["id"].clone();
|
||||
s.execute("object.group", &json!({"ids": [far]})).unwrap();
|
||||
s.execute("transparency.set", &json!({"ids": [far], "opacity": 0})).unwrap();
|
||||
assert_eq!(plot(&mut s).unwrap(), alone, "0% opacity in a group");
|
||||
// A placed image and a path whose fill and stroke paint nothing.
|
||||
let mut png = vec![];
|
||||
image::DynamicImage::new_rgb8(4, 4).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
s.execute("file.place", &json!({"name": "far.png", "dataBase64": b64(&png), "at": [-600, 800]})).unwrap();
|
||||
assert_eq!(plot(&mut s).unwrap(), alone, "a placed image");
|
||||
let bare = s.execute("shape.rectangle", &json!({"x": 500, "y": -400, "width": 20, "height": 20})).unwrap()["id"].clone();
|
||||
s.execute("paint.setStroke", &json!({"ids": [bare], "none": true})).unwrap();
|
||||
assert_eq!(plot(&mut s).unwrap(), alone, "a path that paints nothing");
|
||||
|
||||
// A clipping layer's clipping path, which loses its paint, still clips the art measured: a
|
||||
// large square clipped to the first square draws nothing more.
|
||||
let clipping = s.execute("layer.new", &json!({})).unwrap()["id"].clone();
|
||||
s.execute("shape.rectangle", &json!({"x": -300, "y": -300, "width": 800, "height": 800})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap();
|
||||
s.execute("layer.clippingMask.toggle", &json!({"id": clipping})).unwrap();
|
||||
assert_eq!(plot(&mut s).unwrap(), alone, "a clipping layer");
|
||||
|
||||
s.execute("layer.setProps", &json!({"id": clipping, "visible": false})).unwrap();
|
||||
s.execute("layer.setProps", &json!({"id": printing, "visible": false})).unwrap();
|
||||
let e = plot(&mut s).unwrap_err().to_string();
|
||||
assert!(e.contains("no visible art"), "{e}");
|
||||
}
|
||||
|
||||
/// A placed image in a symbol's art doesn't move a plot of the art's bounds either, and a
|
||||
/// document whose only other visible art is an instance of that symbol is refused.
|
||||
#[test]
|
||||
fn a_plot_of_the_arts_bounds_leaves_out_images_in_symbol_art() {
|
||||
let mut s = two_boards();
|
||||
let plot = |s: &mut Session| s.execute("document.export", &json!({"format": "hpgl", "useArtboards": false})).map(|v| bytes(&v));
|
||||
let alone = plot(&mut s).unwrap();
|
||||
let printing = s.doc().unwrap().doc.layers[0].id;
|
||||
s.execute("layer.new", &json!({})).unwrap();
|
||||
let mut png = vec![];
|
||||
image::DynamicImage::new_rgb8(4, 4).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
s.execute("file.place", &json!({"name": "far.png", "dataBase64": b64(&png), "at": [-600, 800]})).unwrap();
|
||||
s.execute("symbol.new", &json!({"name": "Far"})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.symbols.iter().any(|sym| sym.name == "Far"));
|
||||
assert_eq!(plot(&mut s).unwrap(), alone, "an image in symbol art");
|
||||
|
||||
s.execute("layer.setProps", &json!({"id": printing, "visible": false})).unwrap();
|
||||
let e = plot(&mut s).unwrap_err().to_string();
|
||||
assert!(e.contains("no visible art"), "{e}");
|
||||
|
||||
// A symbol of a square and an image is measured by its square.
|
||||
let bounds = |s: &Session| super::export_art_bounds(&s.doc().unwrap().doc, "hpgl").unwrap();
|
||||
let square = s.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 20, "height": 20})).unwrap()["id"].clone();
|
||||
let before = bounds(&s);
|
||||
let image = s.execute("file.place", &json!({"name": "near.png", "dataBase64": b64(&png), "at": [400, 600]})).unwrap()["ids"][0].clone();
|
||||
s.execute("symbol.new", &json!({"name": "Both", "ids": [square, image]})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.symbols.len(), 2);
|
||||
let after = bounds(&s);
|
||||
for (a, b) in [(before.x0, after.x0), (before.y0, after.y0), (before.x1, after.x1), (before.y1, after.y1)] {
|
||||
assert!((a - b).abs() < 1e-6, "{before:?} {after:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// 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]
|
||||
fn a_plot_of_the_arts_bounds_measures_images_by_their_halftone_dots() {
|
||||
let mut s = two_boards();
|
||||
let plot = |s: &mut Session| s.execute("document.export", &json!({"format": "hpgl", "useArtboards": false})).map(|v| bytes(&v));
|
||||
let printing = s.doc().unwrap().doc.layers[0].id;
|
||||
s.execute("layer.new", &json!({})).unwrap();
|
||||
let mut png = vec![];
|
||||
image::DynamicImage::new_rgb8(100, 100).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
s.execute("file.place", &json!({"name": "dots.png", "dataBase64": b64(&png), "at": [300, 300]})).unwrap();
|
||||
s.execute("layer.setProps", &json!({"id": printing, "visible": false})).unwrap();
|
||||
|
||||
// At 300 lines per inch a 100 pt image takes more cells than the effect makes.
|
||||
s.execute("effect.apply", &json!({"effect": "addon.color.halftone", "params": {"frequency": 300}})).unwrap();
|
||||
let e = plot(&mut s).unwrap_err().to_string();
|
||||
assert!(e.contains("no visible art"), "{e}");
|
||||
|
||||
s.execute("effect.apply", &json!({"effect": "addon.color.halftone", "params": {"frequency": 20}})).unwrap();
|
||||
let out = String::from_utf8(plot(&mut s).unwrap()).unwrap();
|
||||
assert!(out.contains("PD"), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_options_are_checked() {
|
||||
let mut s = two_boards();
|
||||
|
||||
@@ -103,6 +103,48 @@ fn use_artboards_false_writes_one_page_of_the_arts_bounds() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A page of the art's bounds is measured on the layers the PDF draws: a non-printing layer that
|
||||
/// the PDF leaves out doesn't make it larger, unless `includeNonPrinting` or `createLayers` keeps
|
||||
/// the layer. A `.ai` file of the art's bounds, which keeps layers by default, measures it unless
|
||||
/// `createLayers` is off. A document whose only visible art doesn't print is refused.
|
||||
#[test]
|
||||
fn a_page_of_the_arts_bounds_leaves_out_non_printing_layers() {
|
||||
let mut s = session(1);
|
||||
let printing = s.doc().unwrap().doc.layers[0].id;
|
||||
let notes = s.execute("layer.new", &json!({})).unwrap()["id"].clone();
|
||||
s.execute("layer.setProps", &json!({"id": notes, "printable": false})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 20, "height": 20})).unwrap();
|
||||
let size = |bytes: &[u8]| vectorcraft_pdf::import(bytes).unwrap().artboards[0].rect.size();
|
||||
let printed = size(&b64(&export(&mut s, json!({"useArtboards": false}))));
|
||||
assert!(printed.width < 50.0 && printed.height < 40.0, "{printed:?}");
|
||||
let through_export = s.execute("document.export", &as_export(&json!({"useArtboards": false}))).unwrap();
|
||||
assert_eq!(size(&b64(&through_export)), printed);
|
||||
let ai = |s: &mut Session, extra: Value| {
|
||||
let mut p = json!({"format": "ai", "useArtboards": false});
|
||||
p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
|
||||
size(&b64(&s.execute("document.export", &p).unwrap_or_else(|e| panic!("{p}: {e}"))))
|
||||
};
|
||||
assert_eq!(ai(&mut s, json!({"createLayers": false})), printed);
|
||||
let kept = [
|
||||
size(&b64(&export(&mut s, json!({"useArtboards": false, "includeNonPrinting": true})))),
|
||||
size(&b64(&export(&mut s, json!({"useArtboards": false, "createLayers": true})))),
|
||||
ai(&mut s, json!({})),
|
||||
];
|
||||
for all in kept {
|
||||
assert!(all.width > 200.0 && all.height > 200.0, "{all:?}");
|
||||
}
|
||||
|
||||
// Only the non-printing layer shows: the PDF would draw nothing.
|
||||
s.execute("layer.setProps", &json!({"id": printing, "visible": false})).unwrap();
|
||||
for p in [json!({"useArtboards": false}), json!({"useArtboards": false, "includeNonPrinting": false})] {
|
||||
let e = s.execute("document.exportPdf", &p).unwrap_err().to_string();
|
||||
assert!(e.contains("no visible art"), "{p}: {e}");
|
||||
}
|
||||
let e = s.execute("document.export", &json!({"format": "ai", "useArtboards": false, "createLayers": false})).unwrap_err().to_string();
|
||||
assert!(e.contains("no visible art"), "{e}");
|
||||
assert!(size(&b64(&export(&mut s, json!({"useArtboards": false, "includeNonPrinting": true})))).width < 25.0);
|
||||
}
|
||||
|
||||
/// In a PDF without a standard, the warning for a page longer than 14,400 pt written with a
|
||||
/// `UserUnit` above 1 names "Write pages longer than 200 in at full size in points": at PDF 1.5
|
||||
/// (written as 1.6) and later, through `document.exportPdf`, `document.export`, a page of the
|
||||
|
||||
@@ -352,20 +352,8 @@ fn svg_darkness_preserves_source_model_and_gradient_appearance() {
|
||||
|
||||
#[test]
|
||||
fn svg_darkness_uses_rendered_shadow_in_non_srgb_working_space() {
|
||||
const CHILD: &str = "VECTORCRAFT_TEST_SHADOW_RGB_PROFILE";
|
||||
if std::env::var_os(CHILD).is_none() {
|
||||
// Color settings are process-wide: exercise this profile in a separate test process.
|
||||
let output = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--exact", "cmd::fileio::tests_svg::svg_darkness_uses_rendered_shadow_in_non_srgb_working_space", "--nocapture"])
|
||||
.env(CHILD, "1")
|
||||
.output()
|
||||
.unwrap();
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(
|
||||
output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"),
|
||||
"isolated color profile test failed:\n{stdout}\n{}",
|
||||
String::from_utf8_lossy(&output.stderr),
|
||||
);
|
||||
// Color settings are process-wide: exercise this profile in a separate test process.
|
||||
if !crate::tests::in_own_process("cmd::fileio::tests_svg::svg_darkness_uses_rendered_shadow_in_non_srgb_working_space") {
|
||||
return;
|
||||
}
|
||||
use vectorcraft_color::{Color, Paint, cms};
|
||||
|
||||
@@ -184,15 +184,17 @@ impl Sets {
|
||||
/// boxes it overlaps, not every open one (many objects stacked in a column, sharing their
|
||||
/// horizontal extent, would otherwise compare every pair). An open box inside a later box of
|
||||
/// its group, ending no further right, is closed early, and a box inside an open box of its group,
|
||||
/// ending no further right, isn't opened: whatever overlaps it overlaps that box. Fails only when
|
||||
/// cancelled ([`vectorcraft_doc::cancel`]).
|
||||
/// ending no further right, isn't opened: whatever overlaps it overlaps that box. An open box that
|
||||
/// a later box of its group overlaps, starting lower and ending no further right or lower, keeps
|
||||
/// only its part above the later box's top, so boxes staggered right and down each meet only the
|
||||
/// one before. Fails only when cancelled ([`vectorcraft_doc::cancel`]).
|
||||
pub(super) fn overlapping(bounds: &[Option<Rect>]) -> Result<Vec<Vec<usize>>, Cancelled> {
|
||||
Ok(sweep(bounds, None)?.groups())
|
||||
}
|
||||
|
||||
/// [`overlapping`]'s sweep. With `see_through`, two boxes are joined only when one of them is
|
||||
/// see-through, and an open box is closed early, or a box isn't opened, only inside a see-through
|
||||
/// box. The open
|
||||
/// see-through, an open box is closed early, or a box isn't opened, only inside a see-through box,
|
||||
/// and an open box is cut short only by a see-through box that is opened. The open
|
||||
/// see-through boxes and the open boxes without transparency are then in trees of their own, and
|
||||
/// a box without transparency meets only the see-through ones.
|
||||
fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets, Cancelled> {
|
||||
@@ -285,12 +287,20 @@ fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets,
|
||||
see_through.is_none_or(|s| s[boxes[o].0]) && b.x1 <= ob.x1 && ob.y0 <= b.y0 && b.y1 <= ob.y1
|
||||
});
|
||||
// Whatever overlaps a box inside this one overlaps this one, and joins it when this one is
|
||||
// see-through.
|
||||
// see-through. Likewise, whatever later overlaps the part of an open box at or below this
|
||||
// one's top, when that box ends no further right or lower than this one, overlaps this
|
||||
// one: the open box then keeps only the part above this one's top.
|
||||
let cut = b.y0.next_down();
|
||||
for &o in &met {
|
||||
sets.join(boxes[k].0, boxes[o].0);
|
||||
let ob = boxes[o].1;
|
||||
if shadows && Some(o) != holder && ob.x1 <= b.x1 && b.y0 <= ob.y0 && ob.y1 <= b.y1 {
|
||||
if !shadows || Some(o) == holder || b.x1 < ob.x1 || b.y1 < ob.y1 {
|
||||
continue;
|
||||
}
|
||||
if b.y0 <= ob.y0 {
|
||||
set(&mut low[tree(o)], leaf[o], f64::NEG_INFINITY);
|
||||
} else if holder.is_none() && cut < low[tree(o)][leaf[o] + size] {
|
||||
set(&mut low[tree(o)], leaf[o], cut);
|
||||
}
|
||||
}
|
||||
if holder.is_none() {
|
||||
@@ -428,8 +438,10 @@ mod tests {
|
||||
every_pair_joining(bounds, |_, _| true)
|
||||
}
|
||||
|
||||
/// The groups of `bounds` comparing every pair, joining overlapping pairs that `joins`.
|
||||
/// The groups of `bounds` comparing every pair, joining overlapping pairs that `joins`. A box
|
||||
/// that isn't finite ([`finite`]) overlaps none.
|
||||
fn every_pair_joining(bounds: &[Option<Rect>], joins: impl Fn(usize, usize) -> bool) -> Vec<Vec<usize>> {
|
||||
let bounds: Vec<Option<Rect>> = bounds.iter().map(|b| b.filter(finite)).collect();
|
||||
let n = bounds.len();
|
||||
let mut group: Vec<usize> = (0..n).collect();
|
||||
let hit = |a: &Rect, b: &Rect| a.x0 <= b.x1 && b.x0 <= a.x1 && a.y0 <= b.y1 && b.y0 <= a.y1;
|
||||
@@ -731,9 +743,9 @@ mod tests {
|
||||
];
|
||||
let see = [false, true, true, false];
|
||||
let mut sets = sweep(&bounds, Some(&see)).unwrap();
|
||||
// The second box meets the first; the third meets the second; the fourth meets the second
|
||||
// and the third.
|
||||
assert_eq!(sets.meets, 4);
|
||||
// The second box meets the first; the third meets the second, which keeps only its part
|
||||
// above the third's top; the fourth meets the third.
|
||||
assert_eq!(sets.meets, 3);
|
||||
assert_eq!(sets.groups(), vec![vec![0, 1, 2, 3]]);
|
||||
// Opaque boxes alone meet nothing.
|
||||
let mut sets = sweep(&bounds, Some(&[false; 4])).unwrap();
|
||||
@@ -741,6 +753,86 @@ mod tests {
|
||||
assert_eq!(sets.groups().len(), 4);
|
||||
}
|
||||
|
||||
/// `n` boxes of one size, each a little right of and below the one before, all overlapping and
|
||||
/// none inside another.
|
||||
fn staggered(n: usize) -> Vec<Option<Rect>> {
|
||||
let w = 2.0 * n as f64;
|
||||
(0..n).map(|i| Some(Rect::new(i as f64, i as f64, w + i as f64, w + i as f64))).collect()
|
||||
}
|
||||
|
||||
/// Each box of a stagger right and down meets only the box before it, which keeps only its
|
||||
/// part above the new box's top, not every box still open.
|
||||
#[test]
|
||||
fn staggered_boxes_meet_only_the_box_before() {
|
||||
let n = 512;
|
||||
let bounds = staggered(n);
|
||||
let mut sets = sweep(&bounds, None).unwrap();
|
||||
assert_eq!(sets.meets, n - 1);
|
||||
assert_eq!(sets.groups(), vec![(0..n).collect::<Vec<_>>()]);
|
||||
// See-through boxes do the same with transparency.
|
||||
let mut sets = sweep(&bounds, Some(&vec![true; n])).unwrap();
|
||||
assert_eq!(sets.meets, n - 1);
|
||||
assert_eq!(sets.groups(), vec![(0..n).collect::<Vec<_>>()]);
|
||||
}
|
||||
|
||||
/// An open box keeps the part a later box would meet without meeting the box that cut it short:
|
||||
/// a part lower than that box, a part further right, or any part when that box is opaque.
|
||||
#[test]
|
||||
fn a_box_is_cut_short_only_where_the_later_box_covers_it() {
|
||||
let k = Rect::new(5.0, 5.0, 15.0, 15.0);
|
||||
// Lower than `k`: the last box overlaps only the bottom of the first.
|
||||
let lower = [Some(Rect::new(0.0, 0.0, 10.0, 20.0)), Some(k), Some(Rect::new(8.0, 17.0, 9.0, 25.0))];
|
||||
assert_eq!(overlapping(&lower).unwrap(), vec![vec![0, 1, 2]]);
|
||||
// Further right than `k`: the last box starts right of it and overlaps the first.
|
||||
let right = [Some(Rect::new(0.0, 0.0, 20.0, 10.0)), Some(k), Some(Rect::new(17.0, 7.0, 25.0, 9.0))];
|
||||
assert_eq!(overlapping(&right).unwrap(), vec![vec![0, 1, 2]]);
|
||||
// An opaque `k` doesn't join the opaque last box, which joins the see-through first one.
|
||||
let opaque = [Some(Rect::new(0.0, 0.0, 10.0, 10.0)), Some(k), Some(Rect::new(6.0, 8.0, 7.0, 20.0))];
|
||||
let mut sets = sweep(&opaque, Some(&[true, false, false])).unwrap();
|
||||
assert_eq!(sets.groups(), vec![vec![0, 1, 2]]);
|
||||
// A see-through `k` held by a see-through box around it isn't opened and cuts nothing short.
|
||||
let held = [Some(Rect::new(0.0, 2.0, 30.0, 30.0)), Some(Rect::new(1.0, 0.0, 10.0, 10.0)), Some(k), Some(Rect::new(6.0, 8.0, 7.0, 20.0))];
|
||||
let see = [true, false, true, false];
|
||||
let mut sets = sweep(&held, Some(&see)).unwrap();
|
||||
assert_eq!(sets.groups(), vec![vec![0, 1, 2, 3]]);
|
||||
assert_eq!(sets.groups(), every_pair_joining(&held, |i, j| see[i] || see[j]));
|
||||
}
|
||||
|
||||
/// Staggers in all four directions, of mixed sizes (empty ones included) with gaps and shared
|
||||
/// edges, in either order, with signed zeros and boxes that aren't finite, some see-through,
|
||||
/// group as comparing every pair groups them.
|
||||
#[test]
|
||||
fn staggered_boxes_group_as_comparing_every_pair() {
|
||||
let mut seed = 0x3c6e_f372_fe94_f82bu64;
|
||||
let mut next = |m: f64| {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 7;
|
||||
seed ^= seed << 17;
|
||||
(seed % 1000) as f64 / 1000.0 * m
|
||||
};
|
||||
for round in 0..48 {
|
||||
let n = 8 + round * 2;
|
||||
let (sx, sy) = (if round % 2 == 0 { 1.0 } else { -1.0 }, if round / 2 % 2 == 0 { 1.0 } else { -1.0 });
|
||||
let mut bounds: Vec<Option<Rect>> = (0..n)
|
||||
.map(|i| {
|
||||
let step = next(4.0).floor();
|
||||
let (x, y) = (sx * (i as f64 * 2.0 + step), sy * (i as f64 * 2.0 + next(4.0).floor()));
|
||||
let (w, h) = (next(8.0).floor() * 2.0, next(8.0).floor() * 2.0);
|
||||
Some(Rect::new(x, y, x + w, y + h))
|
||||
})
|
||||
.collect();
|
||||
bounds[0] = Some(Rect::new(-0.0, -0.0, 0.0, 6.0));
|
||||
bounds[n / 2] = Some(Rect::new(0.0, sy * 6.0, f64::INFINITY, sy * 6.0 + 4.0));
|
||||
if round / 4 % 2 == 1 {
|
||||
bounds.reverse();
|
||||
}
|
||||
assert_eq!(overlapping(&bounds).unwrap(), every_pair(&bounds), "round {round}");
|
||||
let see: Vec<bool> = (0..n).map(|_| next(1.0) < 0.5).collect();
|
||||
let mut sets = sweep(&bounds, Some(&see)).unwrap();
|
||||
assert_eq!(sets.groups(), every_pair_joining(&bounds, |i, j| see[i] || see[j]), "round {round}, with transparency");
|
||||
}
|
||||
}
|
||||
|
||||
/// An opaque box between a member and its group's top that paints over the member joins, and
|
||||
/// so on along a chain; one under the member stays, but for one within the fringe.
|
||||
#[test]
|
||||
|
||||
@@ -797,22 +797,47 @@ fn place_of(d: &Document, roots: &[NodeId]) -> Option<NodeId> {
|
||||
}
|
||||
|
||||
/// The ruler guides of each of `roots` that is a sublayer (in its sublayers too), with the layer
|
||||
/// that holds it, in order. Other objects hold none.
|
||||
/// that holds it, in order. Other objects hold none. Each root, and each child of it and of its
|
||||
/// sublayers, is looked at once.
|
||||
fn held_guides(d: &Document, roots: impl IntoIterator<Item = NodeId>) -> Vec<(NodeId, Node)> {
|
||||
let mut out = vec![];
|
||||
for id in roots {
|
||||
let (Some(n), Some(parent)) = (d.node(id), d.parent_of(id)) else { continue };
|
||||
if n.holds_ruler_guides() {
|
||||
n.walk(&mut |c| {
|
||||
if c.is_ruler_guide() {
|
||||
out.push((parent, c.clone()));
|
||||
}
|
||||
});
|
||||
guide_seen(n);
|
||||
if n.is_layer() {
|
||||
guides_of(n, parent, &mut out);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Push each ruler guide of `layer` and of its sublayers onto `out` in paint order, with `parent`.
|
||||
fn guides_of(layer: &Node, parent: NodeId, out: &mut Vec<(NodeId, Node)>) {
|
||||
for c in layer.children().into_iter().flatten() {
|
||||
guide_seen(c);
|
||||
if c.is_ruler_guide() {
|
||||
out.push((parent, Node::clone(c)));
|
||||
} else if c.is_layer() {
|
||||
guides_of(c, parent, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// The nodes that [`held_guides`] has looked at on this thread, in order.
|
||||
static GUIDES_SEEN: std::cell::RefCell<Vec<NodeId>> = const { std::cell::RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
/// Note that [`held_guides`] looked at `n`.
|
||||
#[cfg(test)]
|
||||
fn guide_seen(n: &Node) {
|
||||
GUIDES_SEEN.with(|s| s.borrow_mut().push(n.id));
|
||||
}
|
||||
|
||||
#[cfg(not(test))]
|
||||
fn guide_seen(_: &Node) {}
|
||||
|
||||
/// An image of `r` (in a clip group when it is clipped).
|
||||
fn raster_node(d: &mut Document, r: Raster) -> Node {
|
||||
let key = unique_key(d, "flattened");
|
||||
@@ -922,6 +947,53 @@ mod tests {
|
||||
assert_eq!(flat.children(Some(layer)).and_then(|c| c.last()).map(|c| c.id), Some(g));
|
||||
}
|
||||
|
||||
/// The guides of a sublayer and of its sublayers are gathered in paint order with the layer
|
||||
/// that holds it, looking at the sublayer and each child of it and of its sublayers once.
|
||||
/// Other roots give none.
|
||||
#[test]
|
||||
fn held_guides_look_at_each_node_once() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let layer = s.doc().unwrap().doc.layers[0].id;
|
||||
let sublayer =
|
||||
|s: &mut Session, parent: NodeId| NodeId(s.execute("layer.newSublayer", &json!({"parent": parent.0})).unwrap()["id"].as_u64().unwrap());
|
||||
let rect = |s: &mut Session, on: NodeId| {
|
||||
s.execute("layer.setCurrent", &json!({"id": on.0})).unwrap();
|
||||
NodeId(s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap())
|
||||
};
|
||||
let sub = sublayer(&mut s, layer);
|
||||
let deep = sublayer(&mut s, sub);
|
||||
let empty = sublayer(&mut s, layer);
|
||||
let (a, b, c) = (rect(&mut s, sub), rect(&mut s, deep), rect(&mut s, empty));
|
||||
let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let mut guide = |on: NodeId, pos: f64| {
|
||||
let g = Node::new(d.alloc_id(), NodeKind::RulerGuide { vertical: true, pos, artboard: None });
|
||||
d.insert(Some(on), usize::MAX, g).unwrap()
|
||||
};
|
||||
let (g1, g2, g3) = (guide(sub, 1.0), guide(deep, 2.0), guide(sub, 3.0));
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let ids = |n: &Node| {
|
||||
let mut v = vec![];
|
||||
n.walk(&mut |c| v.push(c.id));
|
||||
v
|
||||
};
|
||||
assert_eq!(ids(doc.node(sub).unwrap()), vec![sub, deep, b, g2, a, g1, g3]);
|
||||
let run = |roots: &[NodeId]| {
|
||||
GUIDES_SEEN.with(|v| v.borrow_mut().clear());
|
||||
let got: Vec<_> = held_guides(doc, roots.iter().copied()).into_iter().map(|(p, g)| (p, g.id)).collect();
|
||||
(got, GUIDES_SEEN.with(|v| v.take()))
|
||||
};
|
||||
// Every node of the sublayer is looked at once, and the guides keep their paint order.
|
||||
assert_eq!(run(&[sub]), (vec![(layer, g2), (layer, g1), (layer, g3)], vec![sub, deep, b, g2, a, g1, g3]));
|
||||
// A sublayer that holds none gives none; a path holds none; a missing root and a top-level
|
||||
// layer, which has no parent, are skipped.
|
||||
assert_eq!(run(&[empty]), (vec![], vec![empty, c]));
|
||||
assert_eq!(run(&[a]), (vec![], vec![a]));
|
||||
assert_eq!(run(&[NodeId(u64::MAX), layer]), (vec![], vec![]));
|
||||
// A deeper sublayer gives its guides to the sublayer that holds it.
|
||||
assert_eq!(run(&[deep, deep]).0, vec![(sub, g2), (sub, g2)]);
|
||||
}
|
||||
|
||||
/// In a file without transparency with Clip Complex Regions on, art under a group's opaque
|
||||
/// image within one of its pixels joins the group, also where a long image is made at a lower
|
||||
/// resolution and its pixels are wider than at the preset's.
|
||||
|
||||
@@ -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 → {index}",
|
||||
"{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. 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
|
||||
),
|
||||
|
||||
@@ -6,20 +6,34 @@
|
||||
//! (<https://helpx.adobe.com/ph_fil/illustrator/how-to/global-editing-sensei.html>), in our words:
|
||||
//!
|
||||
//! - With one object selected, Start Global Edit finds the objects that repeat its shape: the
|
||||
//! same outline, wherever it lies and at whatever size. Two options narrow the match: Appearance
|
||||
//! (the same fill and stroke too) and Size (the same width and height too). The search covers
|
||||
//! every artboard and the canvas around them by default; it can be limited to a range of
|
||||
//! artboards (`1, 3-5`) and can leave out the objects that lie on no artboard. Images, type,
|
||||
//! masks, linked files and selections of more than one object are not supported.
|
||||
//! same outline, wherever it lies, at whatever size and at whatever angle. Two options narrow
|
||||
//! the match: Appearance (the same fill and stroke too) and Size (the same width and height
|
||||
//! too). The search covers every artboard and the canvas around them by default; it can be
|
||||
//! limited to a range of artboards (`1, 3-5`) and can leave out the objects that lie on no
|
||||
//! artboard. Images, type, masks, linked files and selections of more than one object are not
|
||||
//! supported.
|
||||
//! - The help page "Edit groups with similar objects"
|
||||
//! (<https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-groups-with-similar-objects.html>):
|
||||
//! with a group selected, Start Global Edit finds the groups like it, and an edit made to an
|
||||
//! object inside one of them is made to the matching object in each of the others. Here a group
|
||||
//! is like another when it holds as many objects, in the same order, each like the one at its
|
||||
//! place (paths, compound paths, symbol instances and groups of them, clipping paths included),
|
||||
//! and they lie the same way relative to each other: the group as a whole is moved or scaled.
|
||||
//! With Appearance on, each of those objects must have the same fill and stroke too; with Size,
|
||||
//! the groups the same width and height.
|
||||
//! and they lie the same way relative to each other: the group as a whole is moved, scaled or
|
||||
//! rotated. With Appearance on, each of those objects must have the same fill and stroke too;
|
||||
//! with Size, the groups the same width and height.
|
||||
//! - The how-to "Design a modern geometric logo"
|
||||
//! (<https://helpx.adobe.com/vn_vi/illustrator/how-to/modern-logo-design.html>) makes rotated
|
||||
//! copies of a group of shapes around a point, then starts Global Edit on one object and edits
|
||||
//! every copy of it at once. Here a rotated copy is found as a moved or scaled one is, and an
|
||||
//! edit reaches it turned by its own angle: an anchor moved to the right on the selected object
|
||||
//! moves downward on a copy turned a quarter turn clockwise. The rules below for rotated copies
|
||||
//! are VectorCraft's own. The angle is the one that lays each anchor and handle of the selected
|
||||
//! object on the copy's of the same order, so a square whose anchors were turned a quarter turn
|
||||
//! is a copy turned a quarter turn. A copy is the same shape when, laid so, every anchor and
|
||||
//! handle lies within a millionth of the larger side of the copy's box of its own ([`SAME`]).
|
||||
//! A reflected copy is another shape. With Size, a rotated copy has the same size when it is the
|
||||
//! selected object rotated without scaling: its width and height are compared as they were
|
||||
//! before the rotation.
|
||||
//! - Selecting one of the repeated objects with the Selection tool highlights the similar objects
|
||||
//! at once, before Global Edit starts. Here they are the objects Start Global Edit would take
|
||||
//! with the current Global Edit Options ([`similar`]).
|
||||
@@ -29,15 +43,16 @@
|
||||
//!
|
||||
//! Here the found objects ([`GlobalEdit::members`]) stay highlighted while the selection keeps the
|
||||
//! object that was selected, so that the Transform panel and the bounding box measure that object
|
||||
//! and not the whole set. Each member keeps the transform (a move and a uniform scale) that maps
|
||||
//! the first object's outline onto its own. After every edit ([`propagate`], run inside
|
||||
//! [`Session::edit`], so the whole change is one undo step), the first selected member the edit
|
||||
//! changed is the model: what changed about it is given to every other member, and nothing else,
|
||||
//! so members found by shape alone keep their own fills and strokes where the edit didn't touch
|
||||
//! them:
|
||||
//! and not the whole set. Each member keeps the transform (a move, a uniform scale and, for a
|
||||
//! rotated copy, a turn) that maps the first object's outline onto its own. After every edit
|
||||
//! ([`propagate`], run inside [`Session::edit`], so the whole change is one undo step), the first
|
||||
//! selected member the edit changed is the model: what changed about it is given to every other
|
||||
//! member, and nothing else, so members found by shape alone keep their own fills and strokes
|
||||
//! where the edit didn't touch them:
|
||||
//!
|
||||
//! - its outline (and anchors), placed through that transform, so in proportion to each member's
|
||||
//! size. Only geometry is placed so: no stroke weight is scaled to a member's size;
|
||||
//! size and turned by its angle. Only geometry is placed so: no stroke weight is scaled to a
|
||||
//! member's size;
|
||||
//! - its opacity, blending, knockout and the object's effects, each when it changed;
|
||||
//! - of its fills and strokes, each setting that changed (paint, weight, opacity, blending,
|
||||
//! effects, caps, dashes, arrowheads …), as it is: it goes to the member's fill or stroke of the
|
||||
@@ -74,12 +89,12 @@
|
||||
//! and later edits leave it as it is.
|
||||
//! The object the edit started from can't be left out (a Shift-click on it selects it or
|
||||
//! deselects it as before), Global Edit ends when fewer than two members are left, and leaving
|
||||
//! one out is not an undo step. Rotated copies are not covered.
|
||||
//! one out is not an undo step.
|
||||
|
||||
use serde::Serialize;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind, Scaling, Shared, StrokeLayer};
|
||||
use vectorcraft_geom::{Affine, BezPath, PathData, Point, Rect, Shape};
|
||||
use vectorcraft_geom::{Affine, BezPath, PathData, Point, Rect, Shape, Vec2};
|
||||
|
||||
use super::wand::{fill_of, stroke_of};
|
||||
use super::{CommandSpec, Result, Session, bad, bool_or, checked_id, cmd, has_doc};
|
||||
@@ -98,7 +113,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Start Global Edit",
|
||||
["Select"],
|
||||
None,
|
||||
"{appearance?: bool, size?: bool, artboards?: \"all\" | range such as \"1, 3-5\", includeCanvas?: bool} (each defaults to the Global Edit Options) while Global Edit is off: start it on the one selected object (a path, compound path, symbol instance or group of them), with the objects of the same shape (for a group: the groups holding objects like its own, at the same places) (and, with `appearance`, the same fill and stroke; with `size`, the same width and height) on the artboards given (and, with `includeCanvas`, off every artboard), at most 10000 → {active: true, count, ids}; while on: stop it (Escape does the same) → {active: false}",
|
||||
"{appearance?: bool, size?: bool, artboards?: \"all\" | range such as \"1, 3-5\", includeCanvas?: bool} (each defaults to the Global Edit Options) while Global Edit is off: start it on the one selected object (a path, compound path, symbol instance or group of them), with the objects of the same shape, moved, scaled or rotated copies of it and not reflected ones (for a group: the groups holding objects like its own, at the same places) (and, with `appearance`, the same fill and stroke; with `size`, the same width and height, for a rotated copy before its rotation) on the artboards given (and, with `includeCanvas`, off every artboard), at most 10000 → {active: true, count, ids}; while on: stop it (Escape does the same) → {active: false}",
|
||||
can_toggle,
|
||||
toggle
|
||||
),
|
||||
@@ -181,7 +196,8 @@ pub type Outlines = Vec<(BezPath, [u8; 3])>;
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct GlobalEdit {
|
||||
/// The objects edited together, the one selected at the start first, each with the transform
|
||||
/// (a move and a uniform scale) that maps that first object's outline onto its own.
|
||||
/// (a move, a uniform scale and, for a turned copy, a turn) that maps that first object's
|
||||
/// outline onto its own.
|
||||
pub members: Vec<(NodeId, Affine)>,
|
||||
/// [`highlights`] as of a document revision: the canvas asks every frame.
|
||||
outlines: std::cell::RefCell<Option<(u64, Outlines)>>,
|
||||
@@ -257,14 +273,60 @@ impl Form {
|
||||
}
|
||||
}
|
||||
|
||||
fn same(&self, o: &Form) -> bool {
|
||||
self.tag == o.tag
|
||||
&& self.symbols == o.symbols
|
||||
&& self.points.len() == o.points.len()
|
||||
&& self.points.iter().zip(&o.points).all(|(a, b)| a.distance(*b) < 1e-6)
|
||||
/// The transform that lays this form's object on `o`'s, point for point in order, and whether
|
||||
/// it turns the object: a move and a uniform scale when the two lie the same way, otherwise a
|
||||
/// turn too. `None` when `o` is another shape, a reflected copy included.
|
||||
fn onto(&self, o: &Form) -> Option<(Affine, bool)> {
|
||||
if self.tag != o.tag || self.symbols != o.symbols || self.points.len() != o.points.len() {
|
||||
return None;
|
||||
}
|
||||
let near = |xf: Affine| self.points.iter().zip(&o.points).all(|(a, b)| (xf * *a).distance(*b) < SAME);
|
||||
let back = self.frame.inverse();
|
||||
if near(Affine::IDENTITY) {
|
||||
return Some((o.frame * back, false));
|
||||
}
|
||||
let turn = self.turn_onto(o)?;
|
||||
near(turn).then(|| (o.frame * turn * back, true))
|
||||
}
|
||||
|
||||
/// The turn, uniform scale and move (both forms in their unit boxes) that best lays this
|
||||
/// form's points on `o`'s in order, by least squares. A turn within [`SQUARE`] of a quarter
|
||||
/// turn is that quarter turn exactly.
|
||||
fn turn_onto(&self, o: &Form) -> Option<Affine> {
|
||||
let n = self.points.len() as f64;
|
||||
let middle = |f: &Form| f.points.iter().fold(Vec2::ZERO, |s, p| s + p.to_vec2()) / n;
|
||||
let (from, to) = (middle(self), middle(o));
|
||||
// With the points as complex numbers about their middles, the fit is `Σ conj(p) q / Σ |p|²`.
|
||||
let (mut re, mut im, mut spread) = (0.0, 0.0, 0.0);
|
||||
for (a, b) in self.points.iter().zip(&o.points) {
|
||||
let (p, q) = (a.to_vec2() - from, b.to_vec2() - to);
|
||||
re += p.dot(q);
|
||||
im += p.cross(q);
|
||||
spread += p.hypot2();
|
||||
}
|
||||
let len = re.hypot(im);
|
||||
let scale = len / spread;
|
||||
if !(scale.is_finite() && scale > 0.0) {
|
||||
return None;
|
||||
}
|
||||
let (mut cos, mut sin) = (re / len, im / len);
|
||||
if cos.abs() < SQUARE {
|
||||
(cos, sin) = (0.0, sin.signum());
|
||||
} else if sin.abs() < SQUARE {
|
||||
(cos, sin) = (cos.signum(), 0.0);
|
||||
}
|
||||
let (a, b) = (scale * cos, scale * sin);
|
||||
Some(Affine::translate(to) * Affine::new([a, b, -b, a, 0.0, 0.0]) * Affine::translate(-from))
|
||||
}
|
||||
}
|
||||
|
||||
/// How far apart two forms' points may lie, each form in its unit box, for the forms to be the
|
||||
/// same. For a turned copy this bounds the angle too: a copy turned and then changed by more than
|
||||
/// a millionth of its larger side is another shape.
|
||||
const SAME: f64 = 1e-6;
|
||||
/// A turn whose sine or cosine is below this is taken as a whole number of quarter turns.
|
||||
const SQUARE: f64 = 1e-9;
|
||||
|
||||
/// Global Edit supports paths, compound paths, symbol instances and groups of them; not images,
|
||||
/// type, linked files, objects with an opacity mask, clipping paths or guides (the help page lists
|
||||
/// images, text, masks and links as unsupported).
|
||||
@@ -395,8 +457,16 @@ fn matches(s: &Session, o: &Options) -> Result<Vec<(NodeId, Affine)>> {
|
||||
}
|
||||
boards.as_ref().is_none_or(|rs| rs.iter().any(|r| on(*r, b)))
|
||||
};
|
||||
// A copy that lies the same way has the size of the selected object when their boxes are as
|
||||
// wide and as high; a turned copy, when the transform that lays the object on it doesn't scale.
|
||||
let same_size = |n: &Node, xf: Affine, turned: bool| {
|
||||
if turned {
|
||||
close(xf.determinant().abs().sqrt(), 1.0)
|
||||
} else {
|
||||
matches!((key_size, size(n)), (Some((w, h)), Some((w2, h2))) if close(w, w2) && close(h, h2))
|
||||
}
|
||||
};
|
||||
let mut out = vec![(*id, Affine::IDENTITY)];
|
||||
let back = form.frame.inverse();
|
||||
super::select::walk_selectable(d, st.isolation, |n| {
|
||||
if n.id == *id || out.len() >= MAX_MEMBERS {
|
||||
return false;
|
||||
@@ -413,12 +483,12 @@ fn matches(s: &Session, o: &Options) -> Result<Vec<(NodeId, Affine)>> {
|
||||
};
|
||||
// The object count first: it turns most objects down before their form is made.
|
||||
if n.children().map(Vec::len) == count
|
||||
&& let Some(f) = Form::of(n).filter(|f| f.same(&form) && supported(n))
|
||||
&& (!o.size || matches!((key_size, size(n)), (Some((w, h)), Some((w2, h2))) if close(w, w2) && close(h, h2)))
|
||||
&& let Some((xf, turned)) = Form::of(n).and_then(|f| form.onto(&f)).filter(|_| supported(n))
|
||||
&& (!o.size || same_size(n, xf, turned))
|
||||
&& (!o.appearance || same_look(key, n))
|
||||
&& in_scope(n)
|
||||
{
|
||||
out.push((n.id, f.frame * back));
|
||||
out.push((n.id, xf));
|
||||
// A group taken is taken whole, as compound paths, symbol instances and the others are.
|
||||
return false;
|
||||
}
|
||||
@@ -464,7 +534,7 @@ fn toggle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let o = s.global_edit_options.with(p, &s.doc()?.doc, C)?;
|
||||
let members = matches(s, &o)?;
|
||||
if members.len() < 2 {
|
||||
return Err(bad(C, "no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again"));
|
||||
return Err(bad(C, "no similar objects found (reflected copies are not matched); change the Global Edit Options and try again"));
|
||||
}
|
||||
let ids: Vec<u64> = members.iter().map(|(id, _)| id.0).collect();
|
||||
let st = s.doc_mut()?;
|
||||
@@ -1027,6 +1097,38 @@ mod tests {
|
||||
assert!(taken > 100 && checked - taken > 100 && asked > 200, "{taken} of {checked}, {asked} selected");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_form_is_laid_on_a_turned_copy_and_on_no_reflected_or_unmeasurable_one() {
|
||||
let mut d = Document::new(800.0, 600.0);
|
||||
let mut path = |points: &[(f64, f64)]| {
|
||||
let anchors = points.iter().map(|(x, y)| Anchor::corner(Point::new(*x, *y))).collect();
|
||||
Node::path(d.alloc_id(), PathData::new(vec![SubPath::new(anchors, true)]), Appearance::default())
|
||||
};
|
||||
let form = Form::of(&path(&[(0.0, 0.0), (30.0, 0.0), (30.0, 70.0)])).unwrap();
|
||||
let mut onto = |points: &[(f64, f64)]| Form::of(&path(points)).and_then(|f| form.onto(&f));
|
||||
let near = |xf: Affine, want: [f64; 6]| xf.as_coeffs().iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-9);
|
||||
// The same way at twice the size: a move and a scale, no turn.
|
||||
let (xf, turned) = onto(&[(100.0, 0.0), (160.0, 0.0), (160.0, 140.0)]).unwrap();
|
||||
assert!(!turned && near(xf, [2.0, 0.0, 0.0, 2.0, 100.0, 0.0]), "{xf:?}");
|
||||
// A quarter turn, (x, y) → (−y, x), moved by (100, 0); and a turn by 30° at half the size.
|
||||
let (xf, turned) = onto(&[(100.0, 0.0), (100.0, 30.0), (30.0, 30.0)]).unwrap();
|
||||
assert!(turned && near(xf, [0.0, 1.0, -1.0, 0.0, 100.0, 0.0]), "{xf:?}");
|
||||
let by = Affine::rotate(30f64.to_radians()) * Affine::scale(0.5);
|
||||
let at = |x: f64, y: f64| {
|
||||
let p = by * Point::new(x, y);
|
||||
(p.x, p.y)
|
||||
};
|
||||
let (xf, turned) = onto(&[at(0.0, 0.0), at(30.0, 0.0), at(30.0, 70.0)]).unwrap();
|
||||
assert!(turned && near(xf, by.as_coeffs()), "{xf:?}");
|
||||
// A reflected copy, a copy with an anchor a thousandth of its size away, and points that
|
||||
// are not numbers or not finite.
|
||||
assert!(onto(&[(0.0, 0.0), (-30.0, 0.0), (-30.0, 70.0)]).is_none());
|
||||
assert!(onto(&[at(0.0, 0.0), at(30.0, 0.0), at(30.0, 70.07)]).is_none());
|
||||
assert!(onto(&[(f64::NAN, 0.0), (30.0, 0.0), (30.0, 70.0)]).is_none());
|
||||
assert!(onto(&[(0.0, 0.0), (f64::INFINITY, 0.0), (30.0, 70.0)]).is_none());
|
||||
assert!(onto(&[(0.0, 0.0), (30.0, 0.0)]).is_none(), "another count of anchors");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn support_of_empty_degenerate_and_deep_objects_is_decided_as_building_the_form_decides() {
|
||||
let mut d = Document::new(800.0, 600.0);
|
||||
|
||||
@@ -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",
|
||||
"{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",
|
||||
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, with the gradient 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), 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
|
||||
),
|
||||
|
||||
@@ -45,10 +45,10 @@ use generate::generate;
|
||||
#[cfg(test)]
|
||||
use series::default_series_color;
|
||||
pub(crate) use series::{
|
||||
LabelTextChange, capture_label_anti_alias, 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, paint_targets, series_group_marks, series_group_marks_where, series_marks_in, series_object_opacity_differs,
|
||||
shown_paint,
|
||||
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_marks_in,
|
||||
series_object_opacity_differs, shown_paint,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -6,7 +6,7 @@ use super::labels::{
|
||||
recolour_text, runs, shadow_of,
|
||||
};
|
||||
use super::markers::{MARKER_BUDGET, marker_cost, marker_designs};
|
||||
use super::series::{series_marks, with_series_gradients, with_series_opacity};
|
||||
use super::series::{picks_legend_fill, series_marks, with_series_gradients, with_series_opacity};
|
||||
use super::{
|
||||
Arc, BezPath, Color, Document, GraphKind, GraphSpec, Justify, Node, NodeKind, Paint, PathData, Point, Rect, TickLength, ValueAxisSide, shapes,
|
||||
};
|
||||
@@ -397,8 +397,7 @@ impl<'a> Plot<'a> {
|
||||
let at = ring.centre + dir(mid) * (ring.hole + (ring.rad - ring.hole) * 0.62);
|
||||
let t = self.b.label(Role::Legend, Point::new(at.x, at.y + self.ls * 0.35), &label, Justify::Center, true);
|
||||
// White on a dark wedge, unless the legend labels were given a colour of their own.
|
||||
let own_colour = self.g.label_styles.legend.as_ref().is_some_and(|st| st.fill != Paint::solid(Color::BLACK));
|
||||
self.wedge_labels.push(if dark && !own_colour { recolour_text(&t, Color::WHITE) } else { t });
|
||||
self.wedge_labels.push(if dark && picks_legend_fill(self.g) { recolour_text(&t, Color::WHITE) } else { t });
|
||||
}
|
||||
|
||||
/// The pie's category name.
|
||||
|
||||
@@ -626,16 +626,37 @@ pub(crate) fn capture_label_anti_alias(doc: &mut Document, ids: &[NodeId], metho
|
||||
pub(crate) fn capture_label_styles(doc: &mut Document, ids: &[NodeId], change: &dyn Fn(&mut CharStyle)) -> bool {
|
||||
let mut changed = false;
|
||||
for (graph, role) in label_kinds(doc, ids) {
|
||||
let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue };
|
||||
let mut style = label_style(&spec.label_styles, role);
|
||||
change(&mut style);
|
||||
let slot = match role {
|
||||
Role::Value => &mut spec.label_styles.values,
|
||||
Role::Category => &mut spec.label_styles.categories,
|
||||
Role::Legend => &mut spec.label_styles.legend,
|
||||
};
|
||||
changed |= slot.as_ref() != Some(&style);
|
||||
*slot = Some(style);
|
||||
changed |= store_label_style(doc, graph, role, change);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// Apply `change` to the style graph `graph` keeps for its labels of kind `role` (or the default one). A `change` that
|
||||
/// sets the fill of legend labels marks it as set on them, so a black one stays black on dark pie wedges. Returns whether
|
||||
/// the kept style or that mark changed.
|
||||
fn store_label_style(doc: &mut Document, graph: NodeId, role: Role, change: &dyn Fn(&mut CharStyle)) -> bool {
|
||||
let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { return false };
|
||||
let mut style = label_style(&spec.label_styles, role);
|
||||
// The kept fill can already be the one `change` sets (black, the default): `change` sets the fill when it gives one
|
||||
// of two different fills something else.
|
||||
let sets_fill = role == Role::Legend
|
||||
&& [Paint::None, Paint::solid(Color::BLACK)].into_iter().any(|fill| {
|
||||
let mut probe = CharStyle { fill: fill.clone(), ..style.clone() };
|
||||
change(&mut probe);
|
||||
probe.fill != fill
|
||||
});
|
||||
change(&mut style);
|
||||
let styles = &mut spec.label_styles;
|
||||
let slot = match role {
|
||||
Role::Value => &mut styles.values,
|
||||
Role::Category => &mut styles.categories,
|
||||
Role::Legend => &mut styles.legend,
|
||||
};
|
||||
let mut changed = slot.as_ref() != Some(&style);
|
||||
*slot = Some(style);
|
||||
if sets_fill && !styles.legend_fill_set {
|
||||
styles.legend_fill_set = true;
|
||||
changed = true;
|
||||
}
|
||||
changed
|
||||
}
|
||||
@@ -807,6 +828,141 @@ pub(crate) fn capture_label_text(
|
||||
Ok(changed)
|
||||
}
|
||||
|
||||
/// The character fill and stroke attributes a kind of graph label keeps when a recolor, or a stroke or gradient edit
|
||||
/// aimed at the characters, changes them on its labels ([`capture_label_changes`]). Each entry copies one attribute
|
||||
/// from the first style to the second and returns whether they differed.
|
||||
const RUN_PAINT: [fn(&CharStyle, &mut CharStyle) -> bool; 8] = [
|
||||
|a, b| keep(&a.fill, &mut b.fill),
|
||||
|a, b| keep(&a.stroke, &mut b.stroke),
|
||||
|a, b| keep(&a.stroke_width, &mut b.stroke_width),
|
||||
|a, b| keep(&a.stroke_cap, &mut b.stroke_cap),
|
||||
|a, b| keep(&a.stroke_join, &mut b.stroke_join),
|
||||
|a, b| keep(&a.stroke_miter_limit, &mut b.stroke_miter_limit),
|
||||
|a, b| keep(&a.stroke_dash, &mut b.stroke_dash),
|
||||
|a, b| keep(&a.stroke_align, &mut b.stroke_align),
|
||||
];
|
||||
|
||||
/// Copy `from` to `to`. Returns whether they differed.
|
||||
fn keep<T: Clone + PartialEq>(from: &T, to: &mut T) -> bool {
|
||||
let differs = from != to;
|
||||
if differs {
|
||||
to.clone_from(from);
|
||||
}
|
||||
differs
|
||||
}
|
||||
|
||||
/// The [`RUN_PAINT`] attributes an edit changed on the characters of graph label `now` (`was`: the label before the
|
||||
/// edit), as the label's style and the indexes of the changed entries. An attribute counts only when every character
|
||||
/// of the label shows it alike, and the fill only when `fill` is set. A placed gradient is kept without its placement,
|
||||
/// so it fits each label it lands on. The stroke weight and dashes are kept as the label shows them: the graph draws its
|
||||
/// labels again without the label's own scale.
|
||||
fn run_paint_change(was: &Node, now: &Node, fill: bool) -> Option<(CharStyle, Vec<usize>)> {
|
||||
let (NodeKind::Text(was), NodeKind::Text(now)) = (&was.kind, &now.kind) else { return None };
|
||||
let first_now = &now.runs.first()?.style;
|
||||
// Changed: some character showed something else before the edit, whichever run it is in.
|
||||
let changed: Vec<usize> = RUN_PAINT
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(i, copy)| {
|
||||
(fill || *i != 0)
|
||||
&& now.runs.iter().all(|r| !copy(first_now, &mut r.style.clone()))
|
||||
&& was.runs.iter().any(|r| copy(first_now, &mut r.style.clone()))
|
||||
})
|
||||
.map(|(i, _)| i)
|
||||
.collect();
|
||||
if changed.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let unplaced = crate::cmd::gradient::unplaced;
|
||||
let mut style = first_now.clone();
|
||||
(style.fill, style.stroke) = (unplaced(&style.fill), unplaced(&style.stroke));
|
||||
// Character strokes are drawn in text space, scaled by the type's transform.
|
||||
if let Some(k) = vectorcraft_doc::Scaling::factor(now.xf).filter(|k| k.is_finite() && *k > 1e-12) {
|
||||
let mut st = style.stroke_layer();
|
||||
crate::inspect::scale_layer(&mut st, k);
|
||||
style.set_stroke_layer(&st);
|
||||
}
|
||||
Some((style, changed))
|
||||
}
|
||||
|
||||
/// Does graph `g` pick the fill of its legend labels itself, white on a dark wedge and black on the others: a pie with
|
||||
/// Legends in Wedges whose legend labels keep no fill of their own ([`GraphSpec::picks_legend_fill`])?
|
||||
pub(super) fn picks_legend_fill(g: &GraphSpec) -> bool {
|
||||
g.picks_legend_fill()
|
||||
}
|
||||
|
||||
/// The graph labels among `roots` and inside them, for an edit that reaches graph labels without naming them.
|
||||
pub(crate) fn labels_in(doc: &Document, roots: &[NodeId]) -> Vec<NodeId> {
|
||||
let mut texts = Vec::new();
|
||||
for id in roots {
|
||||
let Some(root) = doc.node(*id) else { continue };
|
||||
root.walk(&mut |n| {
|
||||
if matches!(n.kind, NodeKind::Text(_)) {
|
||||
texts.push(n.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
// Graph labels are type: without type among `roots`, the graph's labels are not looked up.
|
||||
if texts.is_empty() {
|
||||
return texts;
|
||||
}
|
||||
let labels = graph_labels(doc);
|
||||
texts.retain(|id| labels.contains_key(id));
|
||||
// Nested roots (a graph and one of its labels) reach a label twice.
|
||||
texts.sort_unstable();
|
||||
texts.dedup();
|
||||
texts
|
||||
}
|
||||
|
||||
/// Keep for every label of their kind what an edit changed on graph labels `ids` (`before`: the document before the
|
||||
/// edit): with `rows`, the object rows ([`capture_label_rows`]) of the labels whose rows changed, and the character fill
|
||||
/// and stroke attributes ([`RUN_PAINT`]) that changed on all of a label's characters, on the kind's kept style. The
|
||||
/// frontmost label of a kind sets what that kind keeps, whatever order `ids` are in. On a graph that colors its legend
|
||||
/// labels itself ([`picks_legend_fill`]), their fill is kept only when the legend labels among `ids` end up with one
|
||||
/// fill. Called inside the same edit, so they undo together. Returns whether what a graph keeps changed.
|
||||
pub(crate) fn capture_label_changes(before: &Document, doc: &mut Document, ids: &[NodeId], rows: bool) -> bool {
|
||||
if !ids.iter().any(|id| doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Text(_)))) {
|
||||
return false;
|
||||
}
|
||||
let labels = graph_labels(doc);
|
||||
let mut picked: Vec<NodeId> = ids.iter().copied().filter(|id| labels.contains_key(id)).collect();
|
||||
// A later label's capture replaces an earlier one's: take them in paint order, each once.
|
||||
picked.sort_by_cached_key(|id| doc.index_path(*id));
|
||||
picked.dedup();
|
||||
let picks_fill = |graph: NodeId| doc.node(graph).and_then(|n| n.extras().graph.as_deref()).is_some_and(picks_legend_fill);
|
||||
// On a pie that colors its legend labels black or white by their wedge, a recolor of the whole pie flips them both
|
||||
// ways: their fill is kept only when every legend label the edit reached ends up with the same one.
|
||||
let mut wedge_fills: HashMap<NodeId, Vec<Paint>> = HashMap::new();
|
||||
for id in &picked {
|
||||
let (Some(&(graph, Role::Legend)), Some(NodeKind::Text(t))) = (labels.get(id), doc.node(*id).map(|n| &n.kind)) else { continue };
|
||||
if picks_fill(graph) {
|
||||
wedge_fills.entry(graph).or_default().extend(t.runs.iter().map(|r| r.style.fill.clone()));
|
||||
}
|
||||
}
|
||||
let one_fill = |graph: NodeId| wedge_fills.get(&graph).is_none_or(|f| f.windows(2).all(|w| w[0] == w[1]));
|
||||
let mut changed_rows = Vec::new();
|
||||
let mut characters = Vec::new();
|
||||
for (id, kind) in picked.iter().filter_map(|id| Some((*id, *labels.get(id)?))) {
|
||||
let (Some(was), Some(now)) = (before.node(id), doc.node(id)) else { continue };
|
||||
if rows && label_rows(was) != label_rows(now) {
|
||||
changed_rows.push(id);
|
||||
}
|
||||
let fill = kind.1 != Role::Legend || one_fill(kind.0);
|
||||
characters.extend(run_paint_change(was, now, fill).map(|change| (kind, change)));
|
||||
}
|
||||
let mut changed = capture_label_rows(doc, &changed_rows);
|
||||
for ((graph, role), (style, entries)) in &characters {
|
||||
changed |= store_label_style(doc, *graph, *role, &|st| {
|
||||
for i in entries {
|
||||
if let Some(copy) = RUN_PAINT.get(*i) {
|
||||
copy(style, st);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// The graphs and kinds of label among `ids`, each once.
|
||||
fn label_kinds(doc: &Document, ids: &[NodeId]) -> Vec<(NodeId, Role)> {
|
||||
if ids.is_empty() {
|
||||
|
||||
@@ -508,6 +508,89 @@ fn paint_targets_leave_a_graph_designs_copy_out() {
|
||||
assert_eq!(super::paint_targets(d, &[copy, art, mark]), [mark]);
|
||||
}
|
||||
|
||||
/// The art of a marker design in series 1 of a line graph: the design's copy and a path inside it.
|
||||
fn marker_design_art() -> (Session, NodeId, NodeId) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut s, "Pill");
|
||||
let id = graph(&mut s, "line");
|
||||
s.execute("graph.marker", &json!({"id": id.0, "seriesIndexes": [1], "design": "Pill"})).unwrap();
|
||||
let marker = series(s.doc().unwrap().doc.node(id).unwrap(), 1).children().unwrap()[1].clone();
|
||||
assert!(matches!(marker.kind, NodeKind::Group { .. }), "the design's art");
|
||||
let mut art = vec![];
|
||||
marker.walk(&mut |m| {
|
||||
if matches!(m.kind, NodeKind::Path { .. }) {
|
||||
art.push(m.id);
|
||||
}
|
||||
});
|
||||
(s, marker.id, art[0])
|
||||
}
|
||||
|
||||
/// The ids `graphicStyle.list` reports as linked to style `name`.
|
||||
fn linked_to(s: &mut Session, name: &str) -> Vec<u64> {
|
||||
let list = s.execute("graphicStyle.list", &json!({})).unwrap();
|
||||
let style = list["styles"].as_array().unwrap().iter().find(|g| g["name"] == name).unwrap().clone();
|
||||
let mut ids: Vec<u64> = style["linked"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
|
||||
ids.sort_unstable();
|
||||
ids
|
||||
}
|
||||
|
||||
/// Graphic styles and the art of a column or marker design in a series (the design's copy and a path inside it):
|
||||
/// `graphicStyle.new` makes a style from the art without linking it; `graphicStyle.redefine` leaves the art's look as
|
||||
/// it was and unlinks it, whether the art is linked (as in a document saved before) or the source, while the other
|
||||
/// linked objects follow the new look.
|
||||
#[test]
|
||||
fn graphic_styles_leave_a_graph_designs_art_unlinked() {
|
||||
let make = |marker: bool| {
|
||||
if marker {
|
||||
marker_design_art()
|
||||
} else {
|
||||
let (s, _, copy, art, _) = design_art();
|
||||
(s, copy, art)
|
||||
}
|
||||
};
|
||||
let rows = |s: &Session, id: NodeId| s.doc().unwrap().doc.node(id).unwrap().appearance.clone();
|
||||
let link = |s: &Session, id: NodeId| s.doc().unwrap().doc.node(id).unwrap().extras().graphic_style;
|
||||
let link_directly = |s: &mut Session, ids: &[NodeId], style: u32| {
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
for id in ids {
|
||||
d.node_mut(*id).unwrap().extras_mut().graphic_style = Some(style);
|
||||
}
|
||||
};
|
||||
let rect = |s: &mut Session| {
|
||||
NodeId(s.execute("shape.rectangle", &json!({"x": 700, "y": 700, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap())
|
||||
};
|
||||
for marker in [false, true] {
|
||||
for source in [0, 1] {
|
||||
let at = format!("marker {marker}, source {source}");
|
||||
// New: the style is made from the art, which stays unlinked.
|
||||
let (mut s, copy, art) = make(marker);
|
||||
let source = [copy, art][source];
|
||||
s.execute("graphicStyle.new", &json!({"id": source.0, "name": "Art"})).unwrap();
|
||||
assert_eq!(link(&s, source), None, "{at}");
|
||||
assert_eq!(linked_to(&mut s, "Art"), Vec::<u64>::new(), "{at}");
|
||||
// Redefine from another object: linked art keeps its look and is unlinked; a linked rectangle follows.
|
||||
let follower = rect(&mut s);
|
||||
s.execute("graphicStyle.apply", &json!({"name": "Art", "ids": [follower.0]})).unwrap();
|
||||
let style = link(&s, follower).unwrap();
|
||||
link_directly(&mut s, &[copy, art], style);
|
||||
let (copy_was, art_was) = (rows(&s, copy), rows(&s, art));
|
||||
let (blue_rect, blue) = blue_style(&mut s, "Blue", false);
|
||||
s.execute("graphicStyle.redefine", &json!({"name": "Art", "id": blue_rect.0})).unwrap();
|
||||
assert_eq!((rows(&s, copy), rows(&s, art)), (copy_was.clone(), art_was.clone()), "{at}");
|
||||
assert_eq!((link(&s, copy), link(&s, art)), (None, None), "{at}");
|
||||
assert_eq!(rows(&s, follower).fill_paint(), blue, "{at}");
|
||||
assert_eq!(linked_to(&mut s, "Art"), [follower.0.min(blue_rect.0), follower.0.max(blue_rect.0)], "{at}");
|
||||
// Redefine from the art itself: the art is unlinked and the linked rectangle takes the art's look.
|
||||
link_directly(&mut s, &[copy, art], style);
|
||||
s.execute("graphicStyle.redefine", &json!({"name": "Art", "id": source.0})).unwrap();
|
||||
assert_eq!((rows(&s, copy), rows(&s, art)), (copy_was, art_was), "{at}");
|
||||
assert_eq!((link(&s, copy), link(&s, art)), (None, None), "{at}");
|
||||
assert_eq!(linked_to(&mut s, "Art"), [follower.0.min(blue_rect.0), follower.0.max(blue_rect.0)], "{at}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The art of a marker design in a series is refused too.
|
||||
#[test]
|
||||
fn effect_commands_refuse_a_marker_designs_art() {
|
||||
@@ -757,6 +840,24 @@ fn an_opacity_sort_objects_stores_the_frontmost_mark_it_changes() {
|
||||
assert_eq!(spec(&s, id).series_paints[0].opacity, Some(0.6));
|
||||
}
|
||||
|
||||
/// A Sort Objects that gives series marks the opacities they already have changes nothing: the value the graph stores
|
||||
/// stays and no undo step is made, even when the evenly stepped percentage differs from a mark's in the last digits.
|
||||
#[test]
|
||||
fn an_opacity_sort_objects_that_changes_no_mark_keeps_the_stored_opacity() {
|
||||
let (mut s, id, _, marks) = column_marks();
|
||||
s.execute("object.setProps", &json!({"id": marks[1].0, "opacity": 65})).unwrap();
|
||||
s.execute("object.setProps", &json!({"id": marks[0].0, "opacity": 30})).unwrap();
|
||||
assert_eq!(spec(&s, id).series_paints[0].opacity, Some(0.3));
|
||||
// From left to right the columns have 30%, 65% and 100%, the values an even step from 30% to 100% gives them.
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let ids = [marks[0].0, marks[1].0, marks[2].0];
|
||||
s.execute("addon.arrange.sort", &json!({"ids": ids, "by": "x", "apply": "opacity", "distribute": true})).unwrap();
|
||||
let opacities: Vec<f32> = marks[..3].iter().map(|m| s.doc().unwrap().doc.node(*m).unwrap().opacity).collect();
|
||||
assert_eq!(opacities, [0.3, 0.65, 1.0]);
|
||||
assert_eq!(spec(&s, id).series_paints[0].opacity, Some(0.3));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step");
|
||||
}
|
||||
|
||||
/// An object opacity, blend mode, fill, stroke and weight that Global Edit gives a mark of another series from the mark
|
||||
/// that was edited are stored on the graph for that series in the same undo step, and every mark of the series has them
|
||||
/// when the graph is drawn again.
|
||||
@@ -5991,6 +6092,247 @@ fn a_graphic_style_on_a_label_is_kept_for_its_kind() {
|
||||
assert!(rows_of(&looks, "0").0.iter().any(|(fill, hex, _, _)| *fill && hex == "#0080ff"), "{looks:?}");
|
||||
}
|
||||
|
||||
/// The character style of the first run of label `text` in group `grp`.
|
||||
fn label_run_style(s: &Session, id: NodeId, grp: &str, text: &str) -> CharStyle {
|
||||
let NodeKind::Text(t) = label_node(s, id, grp, text).kind else { panic!("{text} is not type") };
|
||||
t.runs[0].style.clone()
|
||||
}
|
||||
|
||||
/// A recolor of the whole graph (Invert or Complement on the proxy, an Edit Colors command, a color filter or Recolor
|
||||
/// Artwork) is kept for the characters and the rows of every kind of label when the graph is drawn again, and undo takes
|
||||
/// it back with its edit.
|
||||
#[test]
|
||||
fn recoloring_a_graph_keeps_its_labels_paint_for_every_kind() {
|
||||
let cases = [
|
||||
("paint.invert", json!({})),
|
||||
("paint.complement", json!({})),
|
||||
("edit.colors.invert", json!({})),
|
||||
("edit.colors.toGrayscale", json!({})),
|
||||
("addon.color.filter", json!({"effect": "addon.color.invert"})),
|
||||
("recolor.apply", json!({"map": {"#3366cc": "#00ff00", "#ff8000": "#8000ff"}})),
|
||||
];
|
||||
every_case(cases, |(cmd, params)| {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
// Characters of every label in a color that every case changes, and an orange fill row on the category labels.
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#3366cc"})).unwrap();
|
||||
let c = text_id(&s, id, "Axes", "Q2");
|
||||
s.execute("appearance.addFill", &json!({"ids": [c.0]})).unwrap();
|
||||
s.execute("appearance.setItem", &json!({"ids": [c.0], "index": 0, "color": "#ff8000"})).unwrap();
|
||||
let was = spec(&s, id).label_styles;
|
||||
let mut p = params.clone();
|
||||
if *cmd == "recolor.apply" {
|
||||
// Recolor Artwork works on the selection.
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
} else {
|
||||
p["ids"] = json!([id.0]);
|
||||
}
|
||||
s.execute(cmd, &p).unwrap();
|
||||
let hex = |p: &Paint| p.color().map(|c| c.to_hex()).unwrap_or_default();
|
||||
let characters = hex(&label_run_style(&s, id, "Axes", "4").fill);
|
||||
assert_ne!(characters, "#3366cc", "{cmd} recolors the characters");
|
||||
let row = label_node(&s, id, "Axes", "Q2").appearance.items[0].paint().clone();
|
||||
assert_ne!(hex(&row), "#ff8000", "{cmd} recolors the row");
|
||||
let looks = label_looks(&mut s, id);
|
||||
for t in ["0", "Q1", "2024"] {
|
||||
assert!(looks.iter().any(|(x, _, fill)| x == t && *fill == characters), "{cmd}: {t}: {looks:?}");
|
||||
}
|
||||
let rows = redrawn_label_rows(&mut s, id);
|
||||
assert_eq!(rows_of(&rows, "Q1").0.first().map(|r| r.1.clone()), Some(hex(&row)), "{cmd}: {rows:?}");
|
||||
// Undo takes back the recolor and what the graph keeps (the two redraws are undone first).
|
||||
for _ in 0..3 {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
assert_eq!(spec(&s, id).label_styles, was, "{cmd}");
|
||||
});
|
||||
}
|
||||
|
||||
/// A recolor of one label changes what the graph keeps for that kind of label only.
|
||||
#[test]
|
||||
fn recoloring_one_label_keeps_its_paint_for_its_kind_only() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let v = text_id(&s, id, "Axes", "4");
|
||||
s.execute("edit.colors.invert", &json!({"ids": [v.0]})).unwrap();
|
||||
let looks = label_looks(&mut s, id);
|
||||
assert!(looks.iter().any(|(t, _, fill)| t == "0" && fill == "#ffffff"), "{looks:?}");
|
||||
assert!(looks.iter().any(|(t, _, fill)| t == "Q1" && fill == "#000000"), "{looks:?}");
|
||||
assert!(looks.iter().any(|(t, _, fill)| t == "2024" && fill == "#000000"), "{looks:?}");
|
||||
let g = spec(&s, id).label_styles;
|
||||
assert!(g.categories.is_none() && g.legend.is_none(), "{g:?}");
|
||||
}
|
||||
|
||||
/// A recolor that leaves a label's first characters as they were and gives the rest the same fill is kept for its kind.
|
||||
#[test]
|
||||
fn a_recolor_that_evens_out_a_labels_characters_is_kept_for_its_kind() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let q2 = text_id(&s, id, "Axes", "Q2");
|
||||
s.select_tool("type", crate::ViewInfo::default()).unwrap();
|
||||
for (start, end, hex) in [(0, 1, "#ff0000"), (1, 2, "#0000ff")] {
|
||||
s.set_tool_option("textSelection", &json!({"id": q2.0, "start": start, "end": end}));
|
||||
s.execute("paint.setFill", &json!({"color": hex})).unwrap();
|
||||
}
|
||||
s.select_tool("selection", crate::ViewInfo::default()).unwrap();
|
||||
assert_eq!(spec(&s, id).label_styles.categories, None, "part of a label's text is not kept");
|
||||
s.execute("select.set", &json!({"ids": [q2.0]})).unwrap();
|
||||
s.execute("recolor.apply", &json!({"map": {"#0000ff": "#ff0000"}})).unwrap();
|
||||
let looks = label_looks(&mut s, id);
|
||||
assert!(looks.iter().any(|(t, _, fill)| t == "Q1" && fill == "#ff0000"), "{looks:?}");
|
||||
assert!(looks.iter().any(|(t, _, fill)| t == "0" && fill == "#000000"), "{looks:?}");
|
||||
}
|
||||
|
||||
/// Stroke options set with `stroke.set` and a gradient made with `paint.editGradient` and placed with
|
||||
/// `paint.setGradientGeom` on a label's characters are kept for every label of its kind, the gradient without its
|
||||
/// placement.
|
||||
#[test]
|
||||
fn stroke_and_gradient_edits_on_a_labels_characters_are_kept_for_its_kind() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let category = label_run_style(&s, id, "Axes", "Q1");
|
||||
let v = text_id(&s, id, "Axes", "4");
|
||||
s.execute("paint.setStroke", &json!({"ids": [v.0], "color": "#ff0000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"ids": [v.0], "weight": 3, "cap": "round"})).unwrap();
|
||||
s.execute("paint.editGradient", &json!({"ids": [v.0], "kind": "linear", "stroke": false})).unwrap();
|
||||
let placement = json!({"ids": [v.0], "stroke": false, "start": [100, 100], "end": [200, 100], "aspect": 50});
|
||||
s.execute("paint.setGradientGeom", &placement).unwrap();
|
||||
let fill = label_run_style(&s, id, "Axes", "4").fill;
|
||||
assert!(matches!(&fill, Paint::Gradient(g) if g.geom.is_some()), "the edited label's gradient is placed: {fill:?}");
|
||||
label_looks(&mut s, id);
|
||||
let st = label_run_style(&s, id, "Axes", "0");
|
||||
assert_eq!((st.stroke_width, st.stroke_cap), (3.0, vectorcraft_doc::LineCap::Round));
|
||||
assert!(matches!(&st.fill, Paint::Gradient(g) if g.geom.is_none()), "{:?}", st.fill);
|
||||
assert_eq!(label_run_style(&s, id, "Axes", "Q1"), category, "the category labels are left as they were");
|
||||
}
|
||||
|
||||
/// `stroke.set`, `stroke.weightUp` and `stroke.weightDown` given the whole graph are kept for every kind of label.
|
||||
#[test]
|
||||
fn stroke_weights_set_on_the_whole_graph_are_kept_for_its_labels() {
|
||||
let cases = [("stroke.set", json!({"weight": 2}), 2.0), ("stroke.weightUp", json!({}), 2.0), ("stroke.weightDown", json!({}), 0.75)];
|
||||
every_case(cases, |(cmd, params, weight)| {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("paint.setStroke", &json!({"ids": [id.0], "color": "#ff0000"})).unwrap();
|
||||
let mut p = params.clone();
|
||||
p["ids"] = json!([id.0]);
|
||||
s.execute(cmd, &p).unwrap();
|
||||
assert_eq!(label_run_style(&s, id, "Axes", "4").stroke_width, *weight, "{cmd}");
|
||||
label_looks(&mut s, id);
|
||||
for (grp, t) in [("Axes", "0"), ("Axes", "Q1"), ("Legend", "2024")] {
|
||||
assert_eq!(label_run_style(&s, id, grp, t).stroke_width, *weight, "{cmd}: {t}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// A stroke weight set on a scaled label is kept as the label shows it, since the graph draws its labels unscaled.
|
||||
#[test]
|
||||
fn a_stroke_weight_on_a_scaled_label_is_kept_as_it_shows() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let v = text_id(&s, id, "Axes", "4");
|
||||
s.execute("select.set", &json!({"ids": [v.0]})).unwrap();
|
||||
s.execute("object.scale", &json!({"sx": 200, "sy": 200})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [v.0], "color": "#ff0000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"ids": [v.0], "weight": 3})).unwrap();
|
||||
assert_eq!(label_run_style(&s, id, "Axes", "4").stroke_width, 1.5, "drawn at twice its size");
|
||||
label_looks(&mut s, id);
|
||||
assert_eq!(label_run_style(&s, id, "Axes", "0").stroke_width, 3.0);
|
||||
}
|
||||
|
||||
/// When the characters of two labels of one kind are recolored differently, the frontmost one sets what the kind
|
||||
/// keeps, whatever order `ids` are in.
|
||||
#[test]
|
||||
fn the_frontmost_label_of_a_kind_sets_what_its_recolor_keeps() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
// Legend labels: the axes tell value and category labels apart by their order, so these are moved instead.
|
||||
let (a, b) = (text_id(&s, id, "Legend", "2024"), text_id(&s, id, "Legend", "2025"));
|
||||
s.execute("paint.setFill", &json!({"ids": [a.0], "color": "#ff0000"})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [b.0], "color": "#0000ff"})).unwrap();
|
||||
// The label made first goes in front, so neither the order of `ids` nor the order the labels were made in decides.
|
||||
let (front, back) = if a < b { (a, b) } else { (b, a) };
|
||||
s.execute("select.set", &json!({"ids": [front.0]})).unwrap();
|
||||
s.execute("object.arrange.bringToFront", &json!({})).unwrap();
|
||||
let path = |n: NodeId| s.doc().unwrap().doc.index_path(n);
|
||||
assert!(path(front) > path(back), "{:?} {:?}", path(front), path(back));
|
||||
let front_fill = if front == a { "#00ffff" } else { "#ffff00" };
|
||||
s.execute("edit.colors.invert", &json!({"ids": [front.0, back.0]})).unwrap();
|
||||
let kept = spec(&s, id).label_styles.legend.unwrap().fill;
|
||||
assert_eq!(kept.color().map(|c| c.to_hex()).as_deref(), Some(front_fill));
|
||||
}
|
||||
|
||||
/// Apply Nearest Swatch and the ink limit of Print Ink Fixes on a label are kept for its kind.
|
||||
#[test]
|
||||
fn nearest_swatch_and_ink_limit_on_a_label_are_kept_for_its_kind() {
|
||||
let cases = [
|
||||
("addon.color.applyNearestSwatch", json!({"library": "web-safe-216"})),
|
||||
("addon.color.printFixes", json!({"scope": "selection", "inkLimit": 200})),
|
||||
];
|
||||
every_case(cases, |(cmd, params)| {
|
||||
let mut s = Session::new();
|
||||
// Print Ink Fixes works on CMYK documents.
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800, "colorMode": "cmyk"})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let v = text_id(&s, id, "Axes", "4");
|
||||
s.execute("paint.setFill", &json!({"ids": [v.0], "color": {"c": 90, "m": 80, "y": 70, "k": 60}})).unwrap();
|
||||
let was = label_run_style(&s, id, "Axes", "4").fill;
|
||||
let mut p = params.clone();
|
||||
p["ids"] = json!([v.0]);
|
||||
s.execute(cmd, &p).unwrap();
|
||||
let now = label_run_style(&s, id, "Axes", "4").fill;
|
||||
assert_ne!(now, was, "{cmd} changes the fill");
|
||||
label_looks(&mut s, id);
|
||||
assert_eq!(label_run_style(&s, id, "Axes", "0").fill, now, "{cmd}");
|
||||
});
|
||||
}
|
||||
|
||||
/// Swap Fill and Stroke and Default Fill and Stroke on a label are kept for its kind.
|
||||
#[test]
|
||||
fn swap_and_default_fill_and_stroke_on_a_label_are_kept_for_its_kind() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let v = text_id(&s, id, "Axes", "4");
|
||||
s.execute("paint.setStroke", &json!({"ids": [v.0], "color": "#ff0000"})).unwrap();
|
||||
s.execute("paint.swap", &json!({"ids": [v.0]})).unwrap();
|
||||
let swapped = label_run_style(&s, id, "Axes", "4");
|
||||
label_looks(&mut s, id);
|
||||
let st = label_run_style(&s, id, "Axes", "0");
|
||||
assert_eq!((&st.fill, &st.stroke), (&swapped.fill, &swapped.stroke));
|
||||
assert_eq!(st.fill.color().map(|c| c.to_hex()).as_deref(), Some("#ff0000"));
|
||||
s.execute("paint.default", &json!({"ids": [text_id(&s, id, "Axes", "4").0]})).unwrap();
|
||||
label_looks(&mut s, id);
|
||||
let st = label_run_style(&s, id, "Axes", "0");
|
||||
assert_eq!((st.fill.color().map(|c| c.to_hex()).as_deref(), st.stroke.is_none()), (Some("#000000"), true));
|
||||
}
|
||||
|
||||
/// On a pie with Legends in Wedges, a recolor of the whole graph leaves the legend labels to the graph's black or white.
|
||||
#[test]
|
||||
fn a_recolor_leaves_wedge_legend_labels_their_contrast() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = make(&mut s, "pie", ",a,b\nP1,1,2");
|
||||
s.execute("graph.setType", &json!({"id": id.0, "pieLegend": "wedges"})).unwrap();
|
||||
s.execute("edit.colors.invert", &json!({"ids": [id.0]})).unwrap();
|
||||
assert_eq!(spec(&s, id).label_styles.legend, None);
|
||||
s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2]]})).unwrap();
|
||||
// The first series' black wedge is white now, so its label is black.
|
||||
let NodeKind::Text(t) = label_node(&s, id, "Legend", "a").kind else { panic!("a is not type") };
|
||||
assert_eq!(t.runs[0].style.fill.color().map(|c| c.to_hex()).as_deref(), Some("#000000"));
|
||||
// A recolor of one legend label gives the kind that label's fill.
|
||||
s.execute("edit.colors.invert", &json!({"ids": [text_id(&s, id, "Legend", "a").0]})).unwrap();
|
||||
let kept = spec(&s, id).label_styles.legend.map(|st| st.fill);
|
||||
assert_eq!(kept.and_then(|f| f.color()).map(|c| c.to_hex()).as_deref(), Some("#ffffff"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pie_names_and_wedge_labels_keep_their_style() {
|
||||
let mut s = Session::new();
|
||||
@@ -6019,6 +6361,93 @@ fn pie_names_and_wedge_labels_keep_their_style() {
|
||||
assert_eq!(fills, ["#00ff00", "#00ff00"], "the kept fill, also on the dark wedge");
|
||||
}
|
||||
|
||||
/// On a pie with Legends in Wedges, a black fill given to the white legend label on the dark wedge is kept for every
|
||||
/// legend label: the graph draws it black on the dark wedge again, also after a native save and open.
|
||||
#[test]
|
||||
fn a_black_fill_set_on_a_wedge_legend_label_stays_black_on_dark_wedges() {
|
||||
let cases = [("paint.setFill", json!({"color": "#000000"})), ("text.setStyle", json!({"fill": "#000000"})), ("edit.colors.invert", json!({}))];
|
||||
every_case(cases, |(cmd, params)| {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = make(&mut s, "pie", ",a,b\nP1,1,2");
|
||||
s.execute("graph.setType", &json!({"id": id.0, "pieLegend": "wedges"})).unwrap();
|
||||
let legend_fill = |s: &Session, text: &str| {
|
||||
let NodeKind::Text(t) = label_node(s, id, "Legend", text).kind else { panic!("{text} is not type") };
|
||||
t.runs[0].style.fill.color().map(|c| c.to_hex()).unwrap_or_default()
|
||||
};
|
||||
assert_eq!(legend_fill(&s, "a"), "#ffffff", "white on the black wedge");
|
||||
let mut p = params.clone();
|
||||
p["ids"] = json!([text_id(&s, id, "Legend", "a").0]);
|
||||
s.execute(cmd, &p).unwrap();
|
||||
assert!(spec(&s, id).label_styles.legend_fill_set, "{cmd}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(!spec(&s, id).label_styles.legend_fill_set, "{cmd}: undone");
|
||||
assert_eq!(legend_fill(&s, "a"), "#ffffff", "{cmd}: white again after the undo");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert!(spec(&s, id).label_styles.legend_fill_set, "{cmd}: redone");
|
||||
s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2]]})).unwrap();
|
||||
assert_eq!((legend_fill(&s, "a"), legend_fill(&s, "b")), ("#000000".into(), "#000000".into()), "{cmd}: black on both wedges");
|
||||
let dir = vectorcraft_testkit::TempDir::new("graph-wedge-legend");
|
||||
let path = dir.join("pie.vectorcraft");
|
||||
s.execute("document.save", &json!({"path": path})).unwrap();
|
||||
s.execute("document.open", &json!({"path": path})).unwrap();
|
||||
assert!(spec(&s, id).label_styles.legend_fill_set, "{cmd}: kept through save and open");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.setData", &json!({"id": id.0, "rows": [[2, 1]]})).unwrap();
|
||||
assert_eq!(legend_fill(&s, "a"), "#000000", "{cmd}: still black after open");
|
||||
});
|
||||
}
|
||||
|
||||
/// A size given to the legend labels of a pie with Legends in Wedges keeps the default black fill with it. A color mode
|
||||
/// change leaves that fill black, so the legend label on the dark wedge is still drawn white. A legend fill that is not
|
||||
/// black, in a file saved without the mark, is marked as set by the change.
|
||||
#[test]
|
||||
fn a_color_mode_change_keeps_the_default_wedge_legend_fill() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = make(&mut s, "pie", ",a,b\nP1,1,2");
|
||||
s.execute("graph.setType", &json!({"id": id.0, "pieLegend": "wedges"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("text.setStyle", &json!({"size": 11})).unwrap();
|
||||
s.execute("file.documentColorMode", &json!({"mode": "cmyk"})).unwrap();
|
||||
let styles = spec(&s, id).label_styles;
|
||||
assert!(!styles.legend_fill_set && !styles.legend_fill_is_own(), "{styles:?}");
|
||||
s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2]]})).unwrap();
|
||||
let NodeKind::Text(t) = label_node(&s, id, "Legend", "a").kind else { panic!("a is not type") };
|
||||
assert_eq!(t.runs[0].style.fill.color().map(|c| c.to_hex()), Some("#ffffff".into()), "white on the black wedge");
|
||||
let red = Paint::solid(vectorcraft_color::Color::from_hex("#ff0000").unwrap());
|
||||
let styles = vectorcraft_doc::LabelStyles { legend: Some(vectorcraft_doc::CharStyle { fill: red, ..Default::default() }), ..Default::default() };
|
||||
assert!(!styles.legend_fill_set && styles.legend_fill_is_own(), "{styles:?}");
|
||||
s.edit("legacy", |d, _| {
|
||||
d.node_mut(id).unwrap().extras_mut().graph.as_deref_mut().unwrap().label_styles = styles;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("file.documentColorMode", &json!({"mode": "rgb"})).unwrap();
|
||||
assert!(spec(&s, id).label_styles.legend_fill_set, "the converted red is still the labels' own");
|
||||
}
|
||||
|
||||
/// The default black legend fill of a graph that keeps its legend beside the marks stays the default through a color
|
||||
/// mode change, so turning on Legends in Wedges later still draws the labels on dark wedges white.
|
||||
#[test]
|
||||
fn a_color_mode_change_keeps_the_default_legend_fill_of_other_graphs() {
|
||||
// A pie made here keeps its legend beside the pies.
|
||||
for kind in ["column", "pie"] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = make(&mut s, kind, ",a,b\nP1,1,2");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("text.setStyle", &json!({"size": 11})).unwrap();
|
||||
let black = Paint::solid(vectorcraft_color::Color::BLACK);
|
||||
let before = spec(&s, id).label_styles;
|
||||
assert_eq!(before.legend.as_ref().map(|st| st.fill.clone()), Some(black.clone()), "{kind}: {before:?}");
|
||||
s.execute("file.documentColorMode", &json!({"mode": "cmyk"})).unwrap();
|
||||
let after = spec(&s, id).label_styles;
|
||||
assert_eq!(after.legend.as_ref().map(|st| st.fill.clone()), Some(black), "{kind}: {after:?}");
|
||||
assert!(!after.legend_fill_set && !after.legend_fill_is_own(), "{kind}: still the default: {after:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn labels_are_told_apart_by_where_they_come_not_by_their_text() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -470,8 +470,8 @@ impl Library {
|
||||
}
|
||||
}
|
||||
|
||||
/// Make `g` a library gradient: no placement, freeform points or swatch links (a linked stop keeps
|
||||
/// the color it shows), the angle its placement showed (a finite one), and stops in order with
|
||||
/// Make `g` a library gradient: no placement, freeform points, swatch links or process plates (a
|
||||
/// linked stop keeps the color it shows), the angle its placement showed (a finite one), and stops in order with
|
||||
/// offsets, opacities and midpoints in range. False when it has fewer than 2 or more than
|
||||
/// [`MAX_STOPS`] stops.
|
||||
fn clean_gradient(g: &mut GradientPaint) -> bool {
|
||||
@@ -490,8 +490,8 @@ fn clean_gradient(g: &mut GradientPaint) -> bool {
|
||||
st.offset = within(st.offset, 0.0, 1.0, 0.0);
|
||||
st.opacity = within(st.opacity, 0.0, 1.0, 1.0);
|
||||
st.midpoint = within(st.midpoint, 0.13, 0.87, 0.5);
|
||||
st.swatch = None;
|
||||
st.tint = 1.0;
|
||||
let color = st.color;
|
||||
st.set_color(color, None);
|
||||
}
|
||||
g.gradient.stops.sort_by(|a, b| a.offset.total_cmp(&b.offset));
|
||||
true
|
||||
@@ -1488,29 +1488,15 @@ fn add_to_char_styles(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
/// Unlink a library character style's `fill` and `stroke` colors (solid, and each gradient stop)
|
||||
/// from swatches that are not global or spot swatches of `doc`: an unlinked color keeps the color
|
||||
/// it shows at full tint, as [`clean_gradient`] keeps a library gradient's stops. A link to a
|
||||
/// it shows at full tint, and an unlinked stop has no process plates, as [`clean_gradient`] keeps
|
||||
/// a library gradient's stops. A link to a
|
||||
/// global or spot swatch `doc` has stays, and takes that swatch's color.
|
||||
fn unlink_missing_swatches(doc: &vectorcraft_doc::Document, attrs: &mut Map<String, Value>) {
|
||||
let keep = |name: &str| doc.global_color(name).is_some();
|
||||
for key in ["fill", "stroke"] {
|
||||
let Some(mut paint) = attrs.get(key).and_then(|v| serde_json::from_value::<Paint>(v.clone()).ok()) else { continue };
|
||||
let mut changed = false;
|
||||
let mut unlink = |swatch: &mut Option<String>, tint: &mut f32| {
|
||||
if swatch.as_deref().is_some_and(|n| !keep(n)) {
|
||||
*swatch = None;
|
||||
*tint = 1.0;
|
||||
changed = true;
|
||||
}
|
||||
};
|
||||
match &mut paint {
|
||||
Paint::Solid { swatch, tint, .. } => unlink(swatch, tint),
|
||||
Paint::Gradient(g) => {
|
||||
for st in &mut g.gradient.stops {
|
||||
unlink(&mut st.swatch, &mut st.tint);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
// `map_links` gives an unlinked color full tint, and an unlinked stop no process plates.
|
||||
let changed = paint.map_links(&mut |_, swatch, _| swatch.take_if(|n| !keep(n.as_str())).is_some());
|
||||
if changed && let Ok(v) = serde_json::to_value(&paint) {
|
||||
attrs.insert(key.to_string(), v);
|
||||
}
|
||||
|
||||
@@ -144,9 +144,10 @@ fn find(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(_) => {
|
||||
// Images and placed documents in opacity-mask art and in the art of symbols, graph
|
||||
// designs and patterns are named by their ids too (`links.list`).
|
||||
// designs, patterns and stored brushes are named by their ids too (`links.list`).
|
||||
let ids = ids_param(p, "ids", C)?.unwrap_or_default();
|
||||
let kind = |id: &NodeId| st.doc.stored_node(*id).map(|(n, _)| &n.kind);
|
||||
let doc = super::links::with_brush_art(&st.doc);
|
||||
let kind = |id: &NodeId| doc.stored_node(*id).map(|(n, _)| &n.kind);
|
||||
if let Some(value) = ids.iter().find(|id| kind(id).is_none()).map(|id| id.0) {
|
||||
return Err(bad(C, format!("no such object id {value}")));
|
||||
}
|
||||
|
||||
+257
-96
@@ -27,6 +27,7 @@ use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_brush::stored_art::StoredArt;
|
||||
use vectorcraft_doc::links::{Align, Preserve, hash_bytes};
|
||||
use vectorcraft_doc::{
|
||||
Appearance, DataValue, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeId, NodeKind, PageBox, PlacedDocument, PlacementOptions,
|
||||
@@ -44,7 +45,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Check Links",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [image or placed document ids] (default: every linked image and placed document, in the layers and in opacity-mask art, symbols, graph designs and patterns)} where each linked file is and whether it changed since it was read → {links: [{name, path?, status: ok|modified|missing, ids, found?: path (found away from its path: relative to the document, or by name in its folder), preview: true (showing the low-resolution preview, not the file), refused?: why the path is not followed (another computer, a device or a URL: it counts as missing)}], missing, modified}; under automation read roots, path and found are left out when the file they name is outside the roots",
|
||||
"{ids?: [image or placed document ids] (default: every linked image and placed document, in the layers and in opacity-mask art, symbols, graph designs, patterns and the art of stored brushes)} where each linked file is and whether it changed since it was read → {links: [{name, path?, status: ok|modified|missing, ids, found?: path (found away from its path: relative to the document, or by name in its folder), preview: true (showing the low-resolution preview, not the file), refused?: why the path is not followed (another computer, a device or a URL: it counts as missing)}], missing, modified}; under automation read roots, path and found are left out when the file they name is outside the roots",
|
||||
has_doc,
|
||||
check
|
||||
),
|
||||
@@ -53,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Update Links",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. Images and placed documents inside symbols, graph designs, patterns and opacity masks have ids of their own, as links.list gives them; those that show the same content as one read again are read again too. One undo step → {updated: [ids], missing: [ids], warnings?: [a DCS file's spot plate whose ink a swatch of the document already names, as file.place warns]}",
|
||||
"{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. Images and placed documents inside symbols, graph designs, patterns, opacity masks and the art of stored brushes have ids of their own, as links.list gives them; those that show the same content as one read again are read again too. One undo step → {updated: [ids], missing: [ids], warnings?: [a DCS file's spot plate whose ink a swatch of the document already names, as file.place warns]}",
|
||||
has_doc,
|
||||
update
|
||||
),
|
||||
@@ -71,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Relink",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, scope?: selected (default: ids) | all (ids and every other object linked to the same file as one of them, in the layers, opacity-mask art, symbols, graph designs and patterns) | missingInFolder (with path: ids, then every other missing link whose file name is in path's folder, each to the file of its name there; names not there are in notFound; with copy, only images are looked for) | each (with paths), paths?: [{ids, path}] (with scope each, in place of ids, path and folder: each link to its own file; an id in two entries is an error), copy?: false (with path or paths, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used; an error for a DCS file that reads plate files of its own), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy; to is the file name alone when the document's folder is outside the automation read roots), warnings?: (as links.update's)}",
|
||||
"{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, scope?: selected (default: ids) | all (ids and every other object linked to the same file as one of them, in the layers, opacity-mask art, symbols, graph designs, patterns and the art of stored brushes) | missingInFolder (with path: ids, then every other missing link whose file name is in path's folder, each to the file of its name there; names not there are in notFound; with copy, only images are looked for) | each (with paths), paths?: [{ids, path}] (with scope each, in place of ids, path and folder: each link to its own file; an id in two entries is an error), copy?: false (with path or paths, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used; an error for a DCS file that reads plate files of its own), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy; to is the file name alone when the document's folder is outside the automation read roots), warnings?: (as links.update's)}",
|
||||
has_doc,
|
||||
relink
|
||||
),
|
||||
@@ -80,7 +81,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Links",
|
||||
[],
|
||||
None,
|
||||
"{show?: all (default)|missing|modified|embedded, sort?: name|kind (file format)|status (missing, modified, ok, embedded); default: stacking order; top first, dcsTransparency?: false (Show DCS Transparency Interactions: mark the images placed from DCS files that are transparent, themselves or a group or layer holding them, or that overlap a visible object with its own transparency; it looks at every object, so it takes longer)} every image object and placed document the document stores, as the Links panel lists them: those in the layers, then those in opacity-mask art and in the art of symbols, graph designs and patterns (one row per stored object, never one per symbol instance or pattern tile) → {links: [{id, name, linked, status: ok|modified|missing|embedded, format (DCS for an image placed from a DCS file), pixelWidth, pixelHeight, path?, found?: path (found away from its path), page?, preview?: true (showing the saved preview), note?: said of an image past the decode allowance (shown at reduced size, or too large to draw), document?: true (a placed document: pageWidth and pageHeight in pt instead of pixels), dcsTransparency?: true (with dcsTransparency), owner?: {kind: layers|symbol|graphDesign|pattern, name? (of the symbol, graph design or pattern), maskOf?: id (in the opacity-mask art of that object)} (an object outside the layer tree)}], missing, modified, embedded}; under automation read roots, path and found are left out when the file they name is outside the roots",
|
||||
"{show?: all (default)|missing|modified|embedded, sort?: name|kind (file format)|status (missing, modified, ok, embedded); default: stacking order; top first, dcsTransparency?: false (Show DCS Transparency Interactions: mark the images placed from DCS files that are transparent, themselves or a group or layer holding them, or that overlap a visible object with its own transparency; it looks at every object, so it takes longer)} every image object and placed document the document stores, as the Links panel lists them: those in the layers, then those in opacity-mask art and in the art of symbols, graph designs, patterns and stored brushes (one row per stored object, never one per symbol instance, pattern tile or brushed stroke) → {links: [{id, name, linked, status: ok|modified|missing|embedded, format (DCS for an image placed from a DCS file), pixelWidth, pixelHeight, path?, found?: path (found away from its path), page?, preview?: true (showing the saved preview), note?: said of an image past the decode allowance (shown at reduced size, or too large to draw), document?: true (a placed document: pageWidth and pageHeight in pt instead of pixels), dcsTransparency?: true (with dcsTransparency), owner?: {kind: layers|symbol|graphDesign|pattern|brush, name? (of the symbol, graph design, pattern or brush), index? (a brush's place in the Brushes panel, from 0), tile?: side|outerCorner|innerCorner|start|end (a pattern brush's tile), maskOf?: id (in the opacity-mask art of that object)} (an object outside the layer tree)}], missing, modified, embedded}; under automation read roots, path and found are left out when the file they name is outside the roots",
|
||||
has_doc,
|
||||
list
|
||||
),
|
||||
@@ -89,7 +90,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Go To Link",
|
||||
[],
|
||||
None,
|
||||
"{id?} select image or placed document `id` (default: the first selected one); the Links panel scrolls it into view → {id, bounds: [x0, y0, x1, y1], onCanvas: true}; one in opacity-mask art or in the art of a symbol, graph design or pattern has no place of its own on the canvas: the selection is cleared → {id, onCanvas: false, owner} (owner as links.list gives it)",
|
||||
"{id?} select image or placed document `id` (default: the first selected one); the Links panel scrolls it into view → {id, bounds: [x0, y0, x1, y1], onCanvas: true}; one in opacity-mask art or in the art of a symbol, graph design, pattern or stored brush has no place of its own on the canvas: the selection is cleared → {id, onCanvas: false, owner} (owner as links.list gives it)",
|
||||
has_doc,
|
||||
go_to
|
||||
),
|
||||
@@ -198,6 +199,8 @@ pub(crate) fn linked_groups(d: &Document) -> Vec<(String, Vec<u64>)> {
|
||||
/// visited before it has (art being edited on a layer and its definition) counts once, by its
|
||||
/// first place; without `ids` its content is still grouped.
|
||||
fn groups(d: &Document, ids: Option<&[NodeId]>) -> Vec<Group> {
|
||||
let view = with_brush_art(d);
|
||||
let d = &*view;
|
||||
let mut out: Vec<Group> = vec![];
|
||||
let mut index: BTreeMap<(String, String, bool), usize> = BTreeMap::new();
|
||||
// Looked up for every linked node: a set, not the list (which may repeat an id many times).
|
||||
@@ -234,13 +237,52 @@ fn stored(d: &Document, id: NodeId) -> Option<&Node> {
|
||||
d.stored_node(id).map(|(n, _)| &**n)
|
||||
}
|
||||
|
||||
/// `d` with the art of its stored brushes set on it ([`vectorcraft_brush::stored_art`]), so that
|
||||
/// the images and placed documents in that art are visited and found by their ids as stored art;
|
||||
/// `d` itself when no stored brush's art holds one or the art is set on it already.
|
||||
pub(crate) fn with_brush_art(d: &Document) -> Cow<'_, Document> {
|
||||
if !d.mounted_art.is_empty() {
|
||||
return Cow::Borrowed(d);
|
||||
}
|
||||
let art = StoredArt::read(d);
|
||||
if art.is_empty() {
|
||||
return Cow::Borrowed(d);
|
||||
}
|
||||
let mut d = d.clone();
|
||||
art.mount(&mut d);
|
||||
Cow::Owned(d)
|
||||
}
|
||||
|
||||
/// `f` run on `d` with the art of its stored brushes set on it as [`with_brush_art`] sets it; the
|
||||
/// brushes whose art `f` changed are then written back into the library, the color masks of its
|
||||
/// images made for their pixels first. The ids it gives that art are the ones [`with_brush_art`]
|
||||
/// gives it in the same document.
|
||||
pub(crate) fn editing_brush_art<T>(d: &mut Document, f: impl FnOnce(&mut Document) -> T) -> T {
|
||||
if !d.mounted_art.is_empty() {
|
||||
return f(d);
|
||||
}
|
||||
let art = StoredArt::read(d);
|
||||
if art.is_empty() {
|
||||
return f(d);
|
||||
}
|
||||
art.mount(d);
|
||||
let before: Vec<Arc<Node>> = d.mounted_art.iter().map(|(n, _)| n.clone()).collect();
|
||||
let out = f(d);
|
||||
if d.mounted_art.len() != before.len() || d.mounted_art.iter().zip(&before).any(|((n, _), b)| !Arc::ptr_eq(n, b)) {
|
||||
super::refresh_color_masks(None, d);
|
||||
}
|
||||
art.write_back(d);
|
||||
out
|
||||
}
|
||||
|
||||
/// Of `ids`, the objects of `d` outside the layer tree (where [`Document::node`] finds none).
|
||||
fn nested_ids(d: &Document, ids: &[NodeId]) -> std::collections::HashSet<NodeId> {
|
||||
ids.iter().copied().filter(|id| d.node(*id).is_none()).collect()
|
||||
}
|
||||
|
||||
/// `links.list`'s `owner` of an object stored at `place` of `d`, when it is not in the layer tree
|
||||
/// itself: `{kind: layers|symbol|graphDesign|pattern, name?, maskOf?}`.
|
||||
/// itself: `{kind: layers|symbol|graphDesign|pattern, name?, maskOf?}`, or for one in the art of a
|
||||
/// stored brush, `{kind: brush, name, index, tile?, maskOf?}`.
|
||||
fn owner_json(d: &Document, place: StoredPlace) -> Option<Value> {
|
||||
if place.in_layers() {
|
||||
return None;
|
||||
@@ -250,6 +292,7 @@ fn owner_json(d: &Document, place: StoredPlace) -> Option<Value> {
|
||||
StoredRoot::Symbol(i) => json!({ "kind": "symbol", "name": d.symbols.get(i).map(|s| s.name.as_str()) }),
|
||||
StoredRoot::GraphDesign(i) => json!({ "kind": "graphDesign", "name": d.graph_designs.get(i).map(|g| g.name.as_str()) }),
|
||||
StoredRoot::Pattern { pattern, .. } => json!({ "kind": "pattern", "name": d.patterns.get(pattern).map(|p| p.name.as_str()) }),
|
||||
StoredRoot::Mounted(i) => d.mounted_art.get(i).map_or_else(|| json!({}), |(_, owner)| owner.clone()),
|
||||
};
|
||||
if let Some(m) = place.mask_of {
|
||||
owner["maskOf"] = json!(m.0);
|
||||
@@ -479,7 +522,8 @@ pub(crate) fn linked_files(d: &Document, base: LinkBase) -> Vec<LinkedFile> {
|
||||
/// again (Preferences › Use Low Resolution Proxy for Linked EPS keeps the preview on screen only).
|
||||
pub(crate) fn full_linked_images<'a>(d: &'a Document, base: LinkBase) -> (Cow<'a, Document>, Vec<String>) {
|
||||
let mut keys = BTreeSet::new();
|
||||
d.visit_images(|_, im| {
|
||||
// The art of the stored brushes draws its images too.
|
||||
with_brush_art(d).visit_images(|_, im| {
|
||||
if im.link.is_some() && d.images.get(&im.key).is_some_and(ImageBlob::is_proxy) {
|
||||
keys.insert(im.key.clone());
|
||||
}
|
||||
@@ -667,6 +711,16 @@ enum ClipTo {
|
||||
File(PathData),
|
||||
/// It goes into a new clip group of this path, inside the clip group that holds it.
|
||||
Nest(PathData),
|
||||
/// Placement Options clip it to `placement` while its DCS file draws it through `file`: it is
|
||||
/// clipped to `file` as [`ClipTo::File`] clips it, and the clip group holding it is clipped to
|
||||
/// `placement` as [`ClipTo::Path`] clips an object. With no `file` (the new file lacks the
|
||||
/// clipping path of the clip group holding it), that group stays as [`ClipTo::Off`] leaves it,
|
||||
/// clipped to `placement`.
|
||||
Both { file: Option<PathData>, placement: PathData },
|
||||
/// Placement Options clip it to `placement` while its DCS file draws it through `file`, and the
|
||||
/// clip group holding just it is not its old file's: that clip group's clipping path becomes
|
||||
/// `placement`, and it goes into a new clip group of `file` inside it.
|
||||
BothInside { file: PathData, placement: PathData },
|
||||
/// The clipping path of the clip group holding just it goes (a DCS file's clipping path that
|
||||
/// its new file lacks): the group stays as a plain group of it, with its id, name, visibility
|
||||
/// and transparency.
|
||||
@@ -702,10 +756,10 @@ fn same_path(a: &PathData, b: &PathData) -> bool {
|
||||
}
|
||||
|
||||
/// The clip an image placed with `old_xf` takes when it shows `img`, read from a file, placed with
|
||||
/// `new_xf`: Placement Options' clip `clip` when they clip it, else the clipping path a DCS file
|
||||
/// draws `img` through. When neither clips it, a clip group holding just it whose clipping path
|
||||
/// `held` is its old DCS file's (`old_clip`, in the old pixels, under the nonzero rule its clip
|
||||
/// groups get) goes.
|
||||
/// `new_xf`: Placement Options' clip `clip` when they clip it, and the clipping path a DCS file
|
||||
/// draws `img` through, the file's clip group inside the placement's. When neither clips it, a clip
|
||||
/// group holding just it whose clipping path `held` is its old DCS file's (`old_clip`, in the old
|
||||
/// pixels, under the nonzero rule its clip groups get) goes.
|
||||
fn clip_to(
|
||||
old_xf: Affine,
|
||||
old_clip: Option<&PathData>,
|
||||
@@ -714,16 +768,22 @@ fn clip_to(
|
||||
new_xf: Affine,
|
||||
held: Option<(&PathData, FillRule)>,
|
||||
) -> ClipTo {
|
||||
if let Some(clip) = clip {
|
||||
return ClipTo::Path(clip_shape(clip));
|
||||
}
|
||||
// Whether the clip group holding just the image is the old DCS file's: a clipping path whose
|
||||
// fill rule was changed in the document is not.
|
||||
let file_held = match (old_clip, held) {
|
||||
(Some(old), Some((held, rule))) => rule == FillRule::NonZero && same_path(&old.transformed(old_xf), held),
|
||||
_ => false,
|
||||
};
|
||||
match img.clip.as_ref().map(|path| path.transformed(new_xf)) {
|
||||
let file = img.clip.as_ref().map(|path| path.transformed(new_xf));
|
||||
if let Some(clip) = clip {
|
||||
let placement = clip_shape(clip);
|
||||
return match file {
|
||||
Some(file) if held.is_some() && !file_held => ClipTo::BothInside { file, placement },
|
||||
file if file.is_some() || file_held => ClipTo::Both { file, placement },
|
||||
_ => ClipTo::Path(placement),
|
||||
};
|
||||
}
|
||||
match file {
|
||||
// A clipping mask made in the document stays, with the file's clip group inside it.
|
||||
Some(path) if held.is_some() && !file_held => ClipTo::Nest(path),
|
||||
Some(path) => ClipTo::File(path),
|
||||
@@ -747,17 +807,18 @@ struct Nested<'a> {
|
||||
|
||||
impl Nested<'_> {
|
||||
/// Every root of `d`: the layers (whose own objects are left alone), then the art of symbols,
|
||||
/// graph designs and patterns.
|
||||
/// graph designs and patterns, then [`Document::mounted_art`].
|
||||
fn run(mut self, d: &mut Document) {
|
||||
let first = d.peek_next_id();
|
||||
self.next = first;
|
||||
for l in d.layers.iter_mut() {
|
||||
self.update(l, false);
|
||||
// Nothing is picked in the layers themselves, so no layer is clipped.
|
||||
let _ = self.update(l, false);
|
||||
}
|
||||
for root in d.symbols.iter_mut().map(|s| &mut s.art).chain(d.graph_designs.iter_mut().map(|g| &mut g.art)) {
|
||||
self.root(root);
|
||||
}
|
||||
for root in d.patterns.iter_mut().flat_map(|p| &mut p.art) {
|
||||
for root in d.patterns.iter_mut().flat_map(|p| &mut p.art).chain(d.mounted_art.iter_mut().map(|(n, _)| n)) {
|
||||
self.root(root);
|
||||
}
|
||||
for _ in first..self.next {
|
||||
@@ -769,20 +830,30 @@ impl Nested<'_> {
|
||||
/// mask art).
|
||||
fn root(&mut self, n: &mut Arc<Node>) {
|
||||
if !(self.pick)(n) {
|
||||
return self.update(n, true);
|
||||
if let Some(placement) = self.update(n, true) {
|
||||
*n = Arc::new(self.clip_group(Arc::clone(n), placement));
|
||||
}
|
||||
return;
|
||||
}
|
||||
let (new, clip) = (self.make)(n, None);
|
||||
let mut new = Arc::new(new);
|
||||
self.update(&mut new, true);
|
||||
let _ = self.update(&mut new, true);
|
||||
*n = match clip {
|
||||
ClipTo::Path(path) | ClipTo::File(path) | ClipTo::Nest(path) => Arc::new(self.clip_group(new, path)),
|
||||
ClipTo::Both { file, placement } => self.clip_both(new, file, placement),
|
||||
ClipTo::BothInside { file, placement } => self.clip_both(new, Some(file), placement),
|
||||
ClipTo::Keep | ClipTo::Off => new,
|
||||
};
|
||||
}
|
||||
|
||||
/// `n` (outside the layer tree when `nested`) with the picked objects under it remade; it stays
|
||||
/// the same node when none is there, and only the nodes on the way to one are copied.
|
||||
fn update(&mut self, n: &mut Arc<Node>, nested: bool) {
|
||||
/// the same node when none is there, and only the nodes on the way to one are copied. The
|
||||
/// result is Placement Options' clip that `n` itself, now the clip group of a DCS file's
|
||||
/// clipping path holding a picked object (or the plain group [`ClipTo::Off`] leaves), takes:
|
||||
/// the clipping path of the clip group holding just `n` becomes it, else `n` goes into a new
|
||||
/// clip group of it.
|
||||
#[must_use]
|
||||
fn update(&mut self, n: &mut Arc<Node>, nested: bool) -> Option<PathData> {
|
||||
let mask = n.extras().mask.as_ref().and_then(|m| {
|
||||
let mut art = Arc::clone(&m.art);
|
||||
self.root(&mut art);
|
||||
@@ -794,6 +865,8 @@ impl Nested<'_> {
|
||||
// The clipping path and object of a plain group holding just the object, which becomes a
|
||||
// clip group again.
|
||||
let mut reclipped = None;
|
||||
// Placement Options' clip for `n` itself.
|
||||
let mut around = None;
|
||||
if let Some(children) = n.children() {
|
||||
// A clip group holding just the object: its clipping path changes.
|
||||
let clip_path = match (&n.kind, &children[..]) {
|
||||
@@ -804,9 +877,11 @@ impl Nested<'_> {
|
||||
for (i, c) in children.iter().enumerate() {
|
||||
if !(nested && (self.pick)(c)) {
|
||||
let mut new = Arc::clone(c);
|
||||
self.update(&mut new, nested);
|
||||
if !Arc::ptr_eq(&new, c) {
|
||||
slots.push((i, new));
|
||||
match (self.update(&mut new, nested), clip_path) {
|
||||
(None, _) if Arc::ptr_eq(&new, c) => {}
|
||||
(None, _) => slots.push((i, new)),
|
||||
(Some(placement), Some(path)) if i == 1 => slots.extend([(0, with_clip(path, placement)), (1, new)]),
|
||||
(Some(placement), _) => slots.push((i, Arc::new(self.clip_group(new, placement)))),
|
||||
}
|
||||
continue;
|
||||
}
|
||||
@@ -816,16 +891,10 @@ impl Nested<'_> {
|
||||
});
|
||||
let (new, clip) = (self.make)(c, held);
|
||||
let mut new = Arc::new(new);
|
||||
self.update(&mut new, true);
|
||||
let _ = self.update(&mut new, true);
|
||||
match (clip, clip_path) {
|
||||
(ClipTo::Keep, _) => slots.push((i, new)),
|
||||
(ClipTo::Path(clip) | ClipTo::File(clip), Some(path)) if i == 1 => {
|
||||
let mut path = Node::clone(path);
|
||||
if let NodeKind::Path { path: p, .. } = &mut path.kind {
|
||||
*p = clip;
|
||||
}
|
||||
slots.extend([(0, Arc::new(path)), (1, new)]);
|
||||
}
|
||||
(ClipTo::Path(clip) | ClipTo::File(clip), Some(path)) if i == 1 => slots.extend([(0, with_clip(path, clip)), (1, new)]),
|
||||
(ClipTo::File(clip), None) if plain => reclipped = Some((clip, new)),
|
||||
(ClipTo::Path(clip) | ClipTo::File(clip) | ClipTo::Nest(clip), _) => {
|
||||
let group = self.clip_group(new, clip);
|
||||
@@ -833,11 +902,30 @@ impl Nested<'_> {
|
||||
}
|
||||
(ClipTo::Off, Some(_)) if i == 1 => declipped = Some(new),
|
||||
(ClipTo::Off, _) => slots.push((i, new)),
|
||||
// The file's clip group stays `n`, and the placement's clip goes around it.
|
||||
(ClipTo::Both { file: Some(file), placement }, Some(path)) if i == 1 => {
|
||||
slots.extend([(0, with_clip(path, file)), (1, new)]);
|
||||
around = Some(placement);
|
||||
}
|
||||
(ClipTo::Both { file: Some(file), placement }, None) if plain => {
|
||||
reclipped = Some((file, new));
|
||||
around = Some(placement);
|
||||
}
|
||||
(ClipTo::Both { file: None, placement }, Some(_)) if i == 1 => {
|
||||
declipped = Some(new);
|
||||
around = Some(placement);
|
||||
}
|
||||
(ClipTo::BothInside { file, placement }, Some(path)) if i == 1 => {
|
||||
let group = self.clip_group(new, file);
|
||||
slots.extend([(0, with_clip(path, placement)), (1, Arc::new(group))]);
|
||||
}
|
||||
(ClipTo::Both { file, placement }, _) => slots.push((i, self.clip_both(new, file, placement))),
|
||||
(ClipTo::BothInside { file, placement }, _) => slots.push((i, self.clip_both(new, Some(file), placement))),
|
||||
}
|
||||
}
|
||||
}
|
||||
if mask.is_none() && slots.is_empty() && declipped.is_none() && reclipped.is_none() {
|
||||
return;
|
||||
return None;
|
||||
}
|
||||
let reclipped = reclipped.map(|(clip, object)| (Arc::new(self.clipping_path(clip)), object));
|
||||
let n = Arc::make_mut(n);
|
||||
@@ -849,14 +937,14 @@ impl Nested<'_> {
|
||||
if let NodeKind::Group { children, clip } = &mut n.kind {
|
||||
(*children, *clip) = (vec![path, object], true);
|
||||
}
|
||||
return;
|
||||
return around;
|
||||
}
|
||||
// A clip group that stays as a plain group of just the object.
|
||||
if let Some(object) = declipped {
|
||||
if let NodeKind::Group { children, clip } = &mut n.kind {
|
||||
(*children, *clip) = (vec![object], false);
|
||||
}
|
||||
return;
|
||||
return around;
|
||||
}
|
||||
if let Some(children) = n.children_mut() {
|
||||
for (i, c) in slots {
|
||||
@@ -865,6 +953,17 @@ impl Nested<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
around
|
||||
}
|
||||
|
||||
/// A clip group of `placement` holding `object`, inside a clip group of `file` when there is a
|
||||
/// `file` ([`ClipTo::Both`] for an object no clip group holds yet).
|
||||
fn clip_both(&mut self, object: Arc<Node>, file: Option<PathData>, placement: PathData) -> Arc<Node> {
|
||||
let object = match file {
|
||||
Some(file) => Arc::new(self.clip_group(object, file)),
|
||||
None => object,
|
||||
};
|
||||
Arc::new(self.clip_group(object, placement))
|
||||
}
|
||||
|
||||
/// A clip group of `object` clipped to `clip`, as [`clip_image_to`] makes one in the layers.
|
||||
@@ -1035,6 +1134,15 @@ fn clip_file_to(d: &mut Document, id: NodeId, path: PathData) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Clipping path `path` (a node) with its path changed to `clip`.
|
||||
fn with_clip(path: &Node, clip: PathData) -> Arc<Node> {
|
||||
let mut path = Node::clone(path);
|
||||
if let NodeKind::Path { path: p, .. } = &mut path.kind {
|
||||
*p = clip;
|
||||
}
|
||||
Arc::new(path)
|
||||
}
|
||||
|
||||
/// A clipping path `id` of `path`, unpainted.
|
||||
fn clipping_path(id: NodeId, path: PathData) -> Node {
|
||||
let none = vectorcraft_color::Paint::None;
|
||||
@@ -1130,6 +1238,19 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio
|
||||
ClipTo::File(path) => clip_file_to(d, id, path),
|
||||
ClipTo::Nest(path) => new_clip_group(d, id, path),
|
||||
ClipTo::Off => unclip(d, id),
|
||||
ClipTo::Both { file, placement } => {
|
||||
match file {
|
||||
Some(file) => clip_file_to(d, id, file)?,
|
||||
None => unclip(d, id)?,
|
||||
}
|
||||
// The file's clip group (or the plain group left of it) takes the placement's clip.
|
||||
let group = d.parent_of(id).ok_or(EngineError::NoNode(id))?;
|
||||
clip_image_to(d, group, placement)
|
||||
}
|
||||
ClipTo::BothInside { file, placement } => {
|
||||
clip_image_to(d, id, placement)?;
|
||||
new_clip_group(d, id, file)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1229,8 +1350,14 @@ impl Resolved {
|
||||
/// found away from their path take the new path. A link nothing is known of whose image, or placed
|
||||
/// document, shows a preview (a file another app wrote kept only that) was never read: its file is
|
||||
/// read now, into the object's bounds, which isn't a change to report. A placed document whose
|
||||
/// file's bytes are gone isn't showing a preview. Nothing here is an undo step.
|
||||
/// file's bytes are gone isn't showing a preview. Links in the art of the stored brushes count too,
|
||||
/// and that art keeps the ids they are listed by. Nothing here is an undo step.
|
||||
pub fn resolve(d: &mut Document, base: LinkBase, update: bool, low_res_proxy_eps: bool) -> Resolved {
|
||||
editing_brush_art(d, |d| resolve_links(d, base, update, low_res_proxy_eps))
|
||||
}
|
||||
|
||||
/// [`resolve`] in the art `d` stores.
|
||||
fn resolve_links(d: &mut Document, base: LinkBase, update: bool, low_res_proxy_eps: bool) -> Resolved {
|
||||
let mut out = Resolved::default();
|
||||
// The image (with its preview) and hash of each file read for a preview here, by path: images
|
||||
// of other keys linking to the same file share them, rather than each reading, decoding and
|
||||
@@ -1381,8 +1508,8 @@ fn set_links(d: &mut Document, ids: &[NodeId], link: &LinkInfo) {
|
||||
}
|
||||
|
||||
/// Placed documents of the document saved at `path` (document `saved` of `s`) in the other open
|
||||
/// documents, in the layers, symbols, graph designs, patterns and opacity masks: read again from
|
||||
/// the new file, each as one Update Links step of its document.
|
||||
/// documents, in the layers, symbols, graph designs, patterns, opacity masks and the art of the
|
||||
/// stored brushes: read again from the new file, each as one Update Links step of its document.
|
||||
pub(crate) fn refresh_placed(s: &mut Session, saved: u64, path: &str) {
|
||||
let path = absolute_path(path);
|
||||
let targets: Vec<usize> = s
|
||||
@@ -1392,7 +1519,7 @@ pub(crate) fn refresh_placed(s: &mut Session, saved: u64, path: &str) {
|
||||
.filter(|(_, st)| st.uid != saved)
|
||||
.filter(|(_, st)| {
|
||||
let mut placed = false;
|
||||
st.doc.visit_placed(|_, p| placed |= p.link.path == path);
|
||||
with_brush_art(&st.doc).visit_placed(|_, p| placed |= p.link.path == path);
|
||||
placed
|
||||
})
|
||||
.map(|(i, _)| i)
|
||||
@@ -1449,7 +1576,7 @@ fn link_target(link: &LinkInfo, base: LinkBase) -> PathBuf {
|
||||
/// `d` (looking from `base`) as saved to `dest`: the links' paths relative to its folder written
|
||||
/// in; `None` when they are already. A link whose file is not at its path is written relative to
|
||||
/// where its file is found, else to the place its relative path names. Links in the layers,
|
||||
/// symbols, graph designs, patterns and opacity masks are all set.
|
||||
/// symbols, graph designs, patterns, opacity masks and the art of the stored brushes are all set.
|
||||
pub fn with_relative_paths(d: &Document, base: LinkBase, dest: &str) -> Option<Document> {
|
||||
let dest = absolute_path(dest);
|
||||
let dir = Path::new(&dest).parent()?;
|
||||
@@ -1458,23 +1585,29 @@ pub fn with_relative_paths(d: &Document, base: LinkBase, dest: &str) -> Option<D
|
||||
let mut look = |l: &LinkInfo| {
|
||||
wanted.entry((l.path.clone(), l.relative.clone())).or_insert_with(|| relative_path(&link_target(l, base), dir));
|
||||
};
|
||||
d.visit_images(|_, im| im.link.iter().for_each(&mut look));
|
||||
d.visit_placed(|_, p| look(&p.link));
|
||||
let view = with_brush_art(d);
|
||||
view.visit_images(|_, im| im.link.iter().for_each(&mut look));
|
||||
view.visit_placed(|_, p| look(&p.link));
|
||||
wanted.retain(|(_, stored), rel| rel != stored);
|
||||
if wanted.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let key = |l: &LinkInfo| (l.path.clone(), l.relative.clone());
|
||||
let mut d = d.clone();
|
||||
d.update_links_where(|l| wanted.contains_key(&key(l)), |l| l.relative = wanted.get(&key(l)).cloned().flatten());
|
||||
editing_brush_art(&mut d, |d| d.update_links_where(|l| wanted.contains_key(&key(l)), |l| l.relative = wanted.get(&key(l)).cloned().flatten()));
|
||||
Some(d)
|
||||
}
|
||||
|
||||
/// Sets each link of `d`, a copy of a document looking from `base`, to the path where that
|
||||
/// document finds its file, and its relative path to it as that document's links have them, so
|
||||
/// the copy finds the same files. Links in the layers, symbols, graph designs, patterns and opacity
|
||||
/// masks are all set.
|
||||
/// the copy finds the same files. Links in the layers, symbols, graph designs, patterns, opacity
|
||||
/// masks and the art of the stored brushes are all set.
|
||||
pub(crate) fn with_found_paths(d: &mut Document, base: LinkBase) {
|
||||
editing_brush_art(d, |d| set_found_paths(d, base));
|
||||
}
|
||||
|
||||
/// [`with_found_paths`] in the art `d` stores.
|
||||
fn set_found_paths(d: &mut Document, base: LinkBase) {
|
||||
// The new path and relative path of each link by what `locate` reads of it: its path, relative
|
||||
// path and name.
|
||||
type PathAndRelative = (String, Option<String>);
|
||||
@@ -1629,7 +1762,9 @@ fn update_where(s: &mut Session, ids: Option<Vec<NodeId>>, path: Option<&str>) -
|
||||
let updated: Vec<u64> = reads.iter().flat_map(|(g, _)| ids_json(&g.ids)).collect();
|
||||
let warnings = spot_swatch_notes(&st.doc, reads.iter().map(|(_, read)| read));
|
||||
if !reads.is_empty() {
|
||||
s.edit("Update Links", |d, _| reads.into_iter().try_for_each(|(g, read)| install_read(d, &g.ids, read, None, Some(&g))))?;
|
||||
s.edit("Update Links", |d, _| {
|
||||
editing_brush_art(d, |d| reads.into_iter().try_for_each(|(g, read)| install_read(d, &g.ids, read, None, Some(&g))))
|
||||
})?;
|
||||
}
|
||||
let mut out = json!({ "updated": updated, "missing": missing });
|
||||
if !warnings.is_empty() {
|
||||
@@ -1756,9 +1891,10 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(Path::new(&doc).parent().map(Path::to_path_buf).ok_or_else(no_folder)?)
|
||||
}
|
||||
};
|
||||
let doc = with_brush_art(&st.doc);
|
||||
// An image or a placed document, with its link.
|
||||
let image = |id: &NodeId| {
|
||||
stored(&st.doc, *id).and_then(|n| match &n.kind {
|
||||
stored(&doc, *id).and_then(|n| match &n.kind {
|
||||
NodeKind::Image(im) => Some(im.link.as_ref()),
|
||||
NodeKind::PlacedDocument(p) => Some(Some(&p.link)),
|
||||
_ => None,
|
||||
@@ -1788,7 +1924,7 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let paths: BTreeSet<&str> = ids.iter().filter_map(|id| image(id).flatten()).map(|l| l.path.as_str()).collect();
|
||||
let mut given: BTreeSet<NodeId> = ids.iter().copied().collect();
|
||||
let mut more = vec![];
|
||||
st.doc.visit_stored(|n, _| {
|
||||
doc.visit_stored(|n, _| {
|
||||
if let Some((l, _, _)) = linked(n)
|
||||
&& paths.contains(l.path.as_str())
|
||||
&& n.id.0 != 0
|
||||
@@ -1799,7 +1935,7 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
});
|
||||
ids.extend(more);
|
||||
}
|
||||
if copy_to.is_some() && ids.iter().any(|id| matches!(stored(&st.doc, *id).map(|n| &n.kind), Some(NodeKind::PlacedDocument(_)))) {
|
||||
if copy_to.is_some() && ids.iter().any(|id| matches!(stored(&doc, *id).map(|n| &n.kind), Some(NodeKind::PlacedDocument(_)))) {
|
||||
return Err(bad(C, "copy takes images only: relink placed documents where their files are"));
|
||||
}
|
||||
// (ids, the file) per file to read.
|
||||
@@ -1835,7 +1971,7 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut images = vec![];
|
||||
let mut documents: Vec<((u32, bool, PageBox), Vec<NodeId>)> = vec![];
|
||||
for id in ids {
|
||||
match stored(&st.doc, id).map(|n| &n.kind) {
|
||||
match stored(&doc, id).map(|n| &n.kind) {
|
||||
Some(NodeKind::PlacedDocument(pl)) => {
|
||||
let k = (pl.page(), pl.bounding, pl.page_box);
|
||||
match documents.iter_mut().find(|(e, _)| *e == k) {
|
||||
@@ -1886,9 +2022,10 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
let relinked: Vec<u64> = reads.iter().flat_map(|(ids, _)| ids_json(ids)).collect();
|
||||
drop(doc);
|
||||
let warnings = spot_swatch_notes(&s.doc()?.doc, reads.iter().map(|(_, read)| read));
|
||||
if !reads.is_empty() {
|
||||
s.edit("Relink", |d, _| reads.into_iter().try_for_each(|(ids, read)| install_read(d, &ids, read, preserve, None)))?;
|
||||
s.edit("Relink", |d, _| editing_brush_art(d, |d| reads.into_iter().try_for_each(|(ids, read)| install_read(d, &ids, read, preserve, None))))?;
|
||||
}
|
||||
not_found.sort();
|
||||
not_found.dedup();
|
||||
@@ -1998,14 +2135,15 @@ fn selected_images(st: &crate::DocState, keep: impl Fn(&ImageObject) -> bool) ->
|
||||
st.selection.objects.iter().copied().filter(|id| image_of(&st.doc, *id).is_some_and(&keep)).collect()
|
||||
}
|
||||
|
||||
/// `id`, else the first selected image.
|
||||
fn image_param(st: &crate::DocState, p: &Value, cmd: &str) -> Result<NodeId> {
|
||||
/// `id` (looked up in `doc`, the document of `st` as [`with_brush_art`] gives it), else the first
|
||||
/// selected image.
|
||||
fn image_param(st: &crate::DocState, doc: &Document, p: &Value, cmd: &str) -> Result<NodeId> {
|
||||
let id = object_param(p, "id", cmd)?
|
||||
.or_else(|| selected_images(st, |_| true).first().copied())
|
||||
.ok_or_else(|| bad(cmd, "select an image, or pass id"))?;
|
||||
match image_of(&st.doc, id) {
|
||||
match image_of(doc, id) {
|
||||
Some(_) => Ok(id),
|
||||
None if stored(&st.doc, id).is_none() => Err(crate::EngineError::NoNode(id)),
|
||||
None if stored(doc, id).is_none() => Err(crate::EngineError::NoNode(id)),
|
||||
None => Err(bad(cmd, format!("object {} is not an image", id.0))),
|
||||
}
|
||||
}
|
||||
@@ -2028,13 +2166,14 @@ fn placement_of(d: &Document, id: NodeId) -> Option<PlacementOptions> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `id`, else the first selected image or placed document.
|
||||
fn linked_param(st: &crate::DocState, p: &Value, cmd: &str) -> Result<NodeId> {
|
||||
let first = || st.selection.objects.iter().copied().find(|id| placement_of(&st.doc, *id).is_some());
|
||||
/// `id` (looked up in `doc`, the document of `st` as [`with_brush_art`] gives it), else the first
|
||||
/// selected image or placed document.
|
||||
fn linked_param(st: &crate::DocState, doc: &Document, p: &Value, cmd: &str) -> Result<NodeId> {
|
||||
let first = || st.selection.objects.iter().copied().find(|id| placement_of(doc, *id).is_some());
|
||||
let id = object_param(p, "id", cmd)?.or_else(first).ok_or_else(|| bad(cmd, "select an image, or pass id"))?;
|
||||
match placement_of(&st.doc, id) {
|
||||
match placement_of(doc, id) {
|
||||
Some(_) => Ok(id),
|
||||
None if stored(&st.doc, id).is_none() => Err(crate::EngineError::NoNode(id)),
|
||||
None if stored(doc, id).is_none() => Err(crate::EngineError::NoNode(id)),
|
||||
None => Err(bad(cmd, format!("object {} is not an image or a linked file", id.0))),
|
||||
}
|
||||
}
|
||||
@@ -2141,10 +2280,12 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let interactions = if switch_or(p, "dcsTransparency", false, C)? { dcs_transparency(&st.doc) } else { BTreeSet::new() };
|
||||
let statuses = statuses(st);
|
||||
// The layer tree's objects, top first as the Layers panel lists them, then the others in the
|
||||
// order they are stored (opacity-mask art, symbols, graph designs, patterns), each once.
|
||||
// order they are stored (opacity-mask art, symbols, graph designs, patterns, the art of the
|
||||
// stored brushes), each once.
|
||||
let doc = with_brush_art(&st.doc);
|
||||
let (mut objects, mut nested) = (vec![], vec![]);
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
st.doc.visit_stored(|n, place| {
|
||||
doc.visit_stored(|n, place| {
|
||||
if matches!(n.kind, NodeKind::Image(_) | NodeKind::PlacedDocument(_)) && n.id.0 != 0 && seen.insert(n.id) {
|
||||
if place.in_layers() { objects.push((n, place)) } else { nested.push((n, place)) }
|
||||
}
|
||||
@@ -2196,7 +2337,7 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if preview {
|
||||
row["preview"] = json!(true);
|
||||
}
|
||||
if let Some(owner) = owner_json(&st.doc, place) {
|
||||
if let Some(owner) = owner_json(&doc, place) {
|
||||
row["owner"] = owner;
|
||||
}
|
||||
if interactions.contains(&n.id) {
|
||||
@@ -2218,10 +2359,13 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn go_to(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let id = linked_param(st, p, "links.goTo")?;
|
||||
// An object in mask art or a definition has no place of its own on the canvas: the selection
|
||||
// is cleared, and the reply names what holds it.
|
||||
if let Some(owner) = st.doc.stored_node(id).and_then(|(_, place)| owner_json(&st.doc, place)) {
|
||||
let doc = with_brush_art(&st.doc);
|
||||
let id = linked_param(st, &doc, p, "links.goTo")?;
|
||||
// An object in mask art, a definition or a stored brush's art has no place of its own on the
|
||||
// canvas: the selection is cleared, and the reply names what holds it.
|
||||
let owner = doc.stored_node(id).and_then(|(_, place)| owner_json(&doc, place));
|
||||
drop(doc);
|
||||
if let Some(owner) = owner {
|
||||
s.select(|_, sel| sel.set([]))?;
|
||||
return Ok(json!({ "id": id.0, "onCanvas": false, "owner": owner }));
|
||||
}
|
||||
@@ -2233,7 +2377,8 @@ fn go_to(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn embed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "links.embed";
|
||||
let st = s.doc()?;
|
||||
let kind = |id: &NodeId| stored(&st.doc, *id).map(|n| &n.kind);
|
||||
let doc = with_brush_art(&st.doc);
|
||||
let kind = |id: &NodeId| stored(&doc, *id).map(|n| &n.kind);
|
||||
let linked = |id: &NodeId| match kind(id) {
|
||||
Some(NodeKind::Image(im)) => im.link.is_some(),
|
||||
Some(NodeKind::PlacedDocument(_)) => true,
|
||||
@@ -2285,17 +2430,20 @@ fn embed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
_ => missing.extend(g.ids),
|
||||
}
|
||||
}
|
||||
drop(doc);
|
||||
if !done.is_empty() || !documents.is_empty() {
|
||||
s.edit("Embed", |d, _| {
|
||||
for (ids, read) in reads {
|
||||
install(d, &ids, read, Some(Preserve::Bounds), None)?;
|
||||
}
|
||||
for id in &done {
|
||||
if let Some(Node { kind: NodeKind::Image(im), .. }) = d.stored_node_mut(*id) {
|
||||
im.link = None;
|
||||
editing_brush_art(d, |d| {
|
||||
for (ids, read) in reads {
|
||||
install(d, &ids, read, Some(Preserve::Bounds), None)?;
|
||||
}
|
||||
}
|
||||
documents.iter().try_for_each(|id| super::place::document::expand(d, *id, C))
|
||||
for id in &done {
|
||||
if let Some(Node { kind: NodeKind::Image(im), .. }) = d.stored_node_mut(*id) {
|
||||
im.link = None;
|
||||
}
|
||||
}
|
||||
documents.iter().try_for_each(|id| super::place::document::expand(d, *id, C))
|
||||
})
|
||||
})?;
|
||||
}
|
||||
done.extend(documents);
|
||||
@@ -2318,9 +2466,10 @@ fn convert_image(bytes: &[u8], ext: &str) -> std::result::Result<Vec<u8>, String
|
||||
fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "links.unembed";
|
||||
let st = s.doc()?;
|
||||
let id = image_param(st, p, C)?;
|
||||
let n = stored(&st.doc, id).ok_or(crate::EngineError::NoNode(id))?;
|
||||
let im = image_of(&st.doc, id).ok_or_else(|| bad(C, format!("object {} is not an image", id.0)))?;
|
||||
let doc = with_brush_art(&st.doc);
|
||||
let id = image_param(st, &doc, p, C)?;
|
||||
let n = stored(&doc, id).ok_or(crate::EngineError::NoNode(id))?;
|
||||
let im = image_of(&doc, id).ok_or_else(|| bad(C, format!("object {} is not an image", id.0)))?;
|
||||
if im.link.is_some() {
|
||||
return Err(bad(C, format!("image {} is linked already", id.0)));
|
||||
}
|
||||
@@ -2345,7 +2494,8 @@ fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let img = linked_image(&bytes, Some(&path))?;
|
||||
write_file(&path, &bytes)?;
|
||||
let read = (link_info(&path, &bytes), img);
|
||||
s.edit("Unembed", |d, _| install(d, &[id], read, Some(Preserve::Bounds), None))?;
|
||||
drop(doc);
|
||||
s.edit("Unembed", |d, _| editing_brush_art(d, |d| install(d, &[id], read, Some(Preserve::Bounds), None)))?;
|
||||
Ok(json!({ "id": id.0, "path": path }))
|
||||
}
|
||||
|
||||
@@ -2403,9 +2553,10 @@ fn scale_rotation(xf: Affine, (px, py): (f64, f64)) -> (Value, Value) {
|
||||
(json!([a.hypot(b) / px * 100.0, c.hypot(d) / py * 100.0]), json!((-b).atan2(a).to_degrees() + 0.0))
|
||||
}
|
||||
|
||||
/// Link Info of placed document `id`.
|
||||
fn placed_info(st: &crate::DocState, id: NodeId) -> Result<Value> {
|
||||
let n = stored(&st.doc, id).ok_or(crate::EngineError::NoNode(id))?;
|
||||
/// Link Info of placed document `id` (looked up in `doc`, the document of `st` as
|
||||
/// [`with_brush_art`] gives it).
|
||||
fn placed_info(st: &crate::DocState, doc: &Document, id: NodeId) -> Result<Value> {
|
||||
let n = stored(doc, id).ok_or(crate::EngineError::NoNode(id))?;
|
||||
let NodeKind::PlacedDocument(pl) = &n.kind else { return Err(bad("links.info", format!("object {} is not a placed document", id.0))) };
|
||||
let size = n.geometric_bounds().unwrap_or_default();
|
||||
let (scale, rotation) = scale_rotation(pl.xf, (1.0, 1.0));
|
||||
@@ -2430,13 +2581,19 @@ fn placed_info(st: &crate::DocState, id: NodeId) -> Result<Value> {
|
||||
|
||||
fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "links.info";
|
||||
let id = linked_param(s.doc()?, p, C)?;
|
||||
if image_of(&s.doc()?.doc, id).is_none() {
|
||||
return placed_info(s.doc()?, id);
|
||||
}
|
||||
let id = {
|
||||
let st = s.doc()?;
|
||||
let doc = with_brush_art(&st.doc);
|
||||
let id = linked_param(st, &doc, p, C)?;
|
||||
if image_of(&doc, id).is_none() {
|
||||
return placed_info(st, &doc, id);
|
||||
}
|
||||
id
|
||||
};
|
||||
let mut out = super::place::image_info(s, &json!({ "id": id.0 }))?;
|
||||
let st = s.doc()?;
|
||||
let im = image_of(&st.doc, id).ok_or_else(|| bad(C, format!("object {} is not an image", id.0)))?;
|
||||
let doc = with_brush_art(&st.doc);
|
||||
let im = image_of(&doc, id).ok_or_else(|| bad(C, format!("object {} is not an image", id.0)))?;
|
||||
let (px, py) = file_pt(&st.doc, &im.key);
|
||||
out["effectivePpi"] = out["ppi"].take();
|
||||
out["ppi"] = json!([72.0 / px, 72.0 / py]);
|
||||
@@ -2453,9 +2610,10 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn placement_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "links.placementOptions";
|
||||
let st = s.doc()?;
|
||||
let doc = with_brush_art(&st.doc);
|
||||
let ids =
|
||||
ids_param(p, "ids", C)?.unwrap_or_else(|| st.selection.objects.iter().copied().filter(|id| placement_of(&st.doc, *id).is_some()).collect());
|
||||
if let Some(id) = ids.iter().find(|id| placement_of(&st.doc, **id).is_none()) {
|
||||
ids_param(p, "ids", C)?.unwrap_or_else(|| st.selection.objects.iter().copied().filter(|id| placement_of(&doc, *id).is_some()).collect());
|
||||
if let Some(id) = ids.iter().find(|id| placement_of(&doc, **id).is_none()) {
|
||||
return Err(bad(C, format!("object {} is not an image or a linked file", id.0)));
|
||||
}
|
||||
if ids.is_empty() {
|
||||
@@ -2474,7 +2632,8 @@ fn placement_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(v) => Some(v.as_bool().ok_or_else(|| bad(C, "clip must be true or false"))?),
|
||||
};
|
||||
let first = ids.first().and_then(|id| placement_of(&st.doc, *id)).unwrap_or_default();
|
||||
let first = ids.first().and_then(|id| placement_of(&doc, *id)).unwrap_or_default();
|
||||
drop(doc);
|
||||
if preserve.is_none() && align.is_none() && clip.is_none() {
|
||||
return Ok(json!({ "placement": placement_json(first) }));
|
||||
}
|
||||
@@ -2484,11 +2643,13 @@ fn placement_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
o.clip = clip.unwrap_or(o.clip);
|
||||
};
|
||||
s.edit("Placement Options", |d, _| {
|
||||
for id in &ids {
|
||||
if let Some(o) = d.stored_node_mut(*id).and_then(placement_mut) {
|
||||
set(o);
|
||||
editing_brush_art(d, |d| {
|
||||
for id in &ids {
|
||||
if let Some(o) = d.stored_node_mut(*id).and_then(placement_mut) {
|
||||
set(o);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
})?;
|
||||
let mut shown = first;
|
||||
|
||||
@@ -149,9 +149,22 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let angle = |k: &str| Ok::<_, EngineError>(number(k, |_| true, "an angle in degrees")?.map(|a| a.rem_euclid(360.0)));
|
||||
let length = |k: &str| number(k, |x| x > 0.0 && x <= crate::MAX_COORD, "a length in points above 0");
|
||||
let radius = number("radius", |r| r >= 0.0, "a radius of 0 or more")?;
|
||||
// Saved steps ([`Session::replay`]) can hold values a direct call refuses, recorded before these
|
||||
// checks: a negative radius is 0, a whole side count of 0 or more is brought into 3 to 1000, and
|
||||
// a fractional or negative one is ignored. A whole number written as 5.0 counts as 5, as in a
|
||||
// direct call.
|
||||
let replaying = s.replaying();
|
||||
let radius = if replaying {
|
||||
number("radius", |_| true, "a number")?.map(|r| r.max(0.0))
|
||||
} else {
|
||||
number("radius", |r| r >= 0.0, "a radius of 0 or more")?
|
||||
};
|
||||
// A polygon's side count: a whole number from 3 to 1000.
|
||||
let sides = number("sides", |n| n.fract() == 0.0 && (3.0..=1000.0).contains(&n), "a whole number from 3 to 1000")?.map(|n| n as u64);
|
||||
let sides = if replaying {
|
||||
number("sides", |_| true, "a number")?.filter(|n| n.fract() == 0.0 && *n >= 0.0).map(|n| n.min(1000.0) as u64)
|
||||
} else {
|
||||
number("sides", |n| n.fract() == 0.0 && (3.0..=1000.0).contains(&n), "a whole number from 3 to 1000")?.map(|n| n as u64)
|
||||
};
|
||||
// An ellipse's pie (Ellipse Properties: Pie Start and End Angle, degrees; Invert Pie swaps them).
|
||||
let (pie_start, pie_end) = (angle("pieStart")?, angle("pieEnd")?);
|
||||
let invert = p.get("invertPie").and_then(Value::as_bool) == Some(true);
|
||||
|
||||
@@ -472,7 +472,7 @@ impl Session {
|
||||
pub fn transparency_info(&self) -> TransparencyInfo {
|
||||
match (self.active(), transparency_targets(self, &Value::Null)) {
|
||||
(Some(st), Ok(ids)) => {
|
||||
let points = super::paint::picked_mesh_points_of(self, &ids);
|
||||
let points = self.mesh_points_picked();
|
||||
TransparencyInfo::of(&st.doc, ids).with_mesh_points(&st.doc, points)
|
||||
}
|
||||
_ => TransparencyInfo::default(),
|
||||
@@ -483,7 +483,8 @@ impl Session {
|
||||
fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let ids = transparency_targets(s, p)?;
|
||||
let points = super::paint::picked_mesh_points_of(s, &ids);
|
||||
// The points `transparency.set` with the same `ids` (or none) fades.
|
||||
let points = if p.get("ids").is_none() && p.get("id").is_none() { s.mesh_points_picked() } else { super::paint::picked_mesh_points_of(s, &ids) };
|
||||
let i = TransparencyInfo::of(&st.doc, ids).with_mesh_points(&st.doc, points);
|
||||
Ok(json!({
|
||||
"ids": i.ids.iter().map(|id| id.0).collect::<Vec<_>>(),
|
||||
|
||||
@@ -229,7 +229,7 @@ impl<'a> Collector<'a> {
|
||||
Some((d, base)) => super::links::linked_files(d, base),
|
||||
None => super::links::linked_files(doc, LinkBase::file(Some(source))),
|
||||
};
|
||||
doc.visit_placed(|_, p| {
|
||||
super::links::with_brush_art(doc).visit_placed(|_, p| {
|
||||
let page = (p.link.page.unwrap_or(1), p.bounding, p.page_box);
|
||||
let pages = placed.entry(p.link.path.clone()).or_default();
|
||||
if !pages.contains(&page) {
|
||||
@@ -389,16 +389,20 @@ impl<'a> Collector<'a> {
|
||||
}
|
||||
if self.opts.relink {
|
||||
// The child files have already been rewritten; the hash and size of each
|
||||
// target must reflect the *packaged* bytes rather than the original.
|
||||
doc.update_links(|link: &mut LinkInfo| {
|
||||
if let Some(copy) = local.get(&link.path) {
|
||||
let relative = relative_in_package(destination, ©.name);
|
||||
link.path = self.root.as_ref().map_or_else(|| copy.name.clone(), |r| r.join(©.name).to_string_lossy().into_owned());
|
||||
link.relative = Some(relative);
|
||||
link.size = copy.size;
|
||||
link.hash = copy.hash.clone();
|
||||
link.modified = None;
|
||||
}
|
||||
// target must reflect the *packaged* bytes rather than the original. The links in the
|
||||
// art of the stored brushes are written back into the brush library.
|
||||
let root = &self.root;
|
||||
super::links::editing_brush_art(doc, |doc| {
|
||||
doc.update_links(|link: &mut LinkInfo| {
|
||||
if let Some(copy) = local.get(&link.path) {
|
||||
let relative = relative_in_package(destination, ©.name);
|
||||
link.path = root.as_ref().map_or_else(|| copy.name.clone(), |r| r.join(©.name).to_string_lossy().into_owned());
|
||||
link.relative = Some(relative);
|
||||
link.size = copy.size;
|
||||
link.hash = copy.hash.clone();
|
||||
link.modified = None;
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
if let Some(s) = self.sections.get_mut(section) {
|
||||
|
||||
@@ -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 colour recolours only the gradient mesh point last clicked with the Mesh tool or Direct Selection; while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; 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), 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)
|
||||
),
|
||||
@@ -39,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Swap Fill and Stroke",
|
||||
[],
|
||||
Some("Shift+X"),
|
||||
"{ids?|id?} swap the fill and stroke of the selection (type too) and of the defaults. On a path directly in a graph series, the graph also stores the swapped paints and the stroke weight (exceptions: docs/mcp.md)",
|
||||
"{ids?|id?} swap the fill and stroke of the selection (type too) and of the defaults. On a path directly in a graph series, the graph also stores the swapped paints and the stroke weight, and on a graph label the swapped paints of its characters for every label of its kind (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
swap
|
||||
),
|
||||
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Default Fill and Stroke",
|
||||
[],
|
||||
Some("D"),
|
||||
"{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults; type gets black fill and no stroke. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
"{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults; type gets black fill and no stroke. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters for every label of its kind (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
default_paint
|
||||
),
|
||||
@@ -81,7 +81,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Transparency",
|
||||
["Window", "Transparency"],
|
||||
None,
|
||||
"{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, item?: appearance item index|null, 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)} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects; a gradient mesh point last clicked with the Mesh tool or Direct Selection takes the opacity itself). With an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, opacity and blend change that object for this instance only (isolate, knockout, knockoutShape, aligned and target are refused). On a path directly in a graph series (for a fill or stroke item, a series group's id stands for those paths), the graph also stores the opacity and blend mode of the object and of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores the label's object opacity and blend mode for every label of its kind, and with `item` its topmost visible fill and stroke rows too",
|
||||
"{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, item?: appearance item index|null, 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)} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects; when every target is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso, those points take the opacity themselves). With an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, opacity and blend change that object for this instance only (isolate, knockout, knockoutShape, aligned and target are refused). On a path directly in a graph series (for a fill or stroke item, a series group's id stands for those paths), the graph also stores the opacity and blend mode of the object and of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores the label's object opacity and blend mode for every label of its kind, and with `item` its topmost visible fill and stroke rows too",
|
||||
has_doc,
|
||||
transparency
|
||||
),
|
||||
@@ -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 (docs/mcp.md); no undo step when no color changes → {changed}",
|
||||
"{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}",
|
||||
has_doc,
|
||||
|s, p| proxy_recolor(s, p, "paint.invert", "Invert", &super::colorcmds::invert)
|
||||
),
|
||||
@@ -154,7 +154,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
|
||||
"Fill and Stroke",
|
||||
[],
|
||||
None,
|
||||
"{} → {fill, stroke: the paints the Fill/Stroke proxies show (the Appearance panel's active item for the proxy of its kind, else the first selected object's, a group's first painted object's, type: its first run's; else the defaults for new art), fillActive, fillMixed, strokeMixed: the selected objects' (or a selected group's contents') fills (strokes) differ, shown as a \"?\" proxy}",
|
||||
"{} → {fill, stroke: the paints the Fill/Stroke proxies show (the Appearance panel's active item for the proxy of its kind, else the first selected object's, a group's first painted object's, type: its first run's; else the defaults for new art; when that object is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso and no fill item is active, the fill is its first picked point's color), fillActive, fillMixed, strokeMixed: the selected objects' (or a selected group's contents') fills (strokes) differ, shown as a \"?\" proxy (a gradient mesh with points picked counts with their colors)}",
|
||||
always,
|
||||
proxies
|
||||
),
|
||||
@@ -179,9 +179,13 @@ impl Session {
|
||||
/// The fill and stroke the Fill/Stroke proxies show: the Appearance panel's active item (in the
|
||||
/// first selected object's own stack) for the proxy of its kind, else the first selected
|
||||
/// object's (a group's first painted object's; type: its first run's), else the defaults for
|
||||
/// new art.
|
||||
/// new art. When the object whose fill the proxy shows is a gradient mesh with points picked
|
||||
/// ([`Session::fill_mesh_points`]), the fill is its first picked point's color, which a solid
|
||||
/// fill color changes.
|
||||
pub fn proxy_paints(&self) -> (Paint, Paint) {
|
||||
let points = self.fill_mesh_points();
|
||||
let show = |stroke: bool| match self.proxy_source(stroke) {
|
||||
Some((n, None)) if !stroke && let Some(c) = picked_colors(&n, &points).first() => Paint::solid(*c),
|
||||
Some((n, item)) => proxy_paint(&n, stroke, item),
|
||||
None if stroke => self.paint.stroke.clone(),
|
||||
None => self.paint.fill.clone(),
|
||||
@@ -273,6 +277,13 @@ impl DocState {
|
||||
/// each selected object's own stack is compared. One walk of the document, so callers that ask
|
||||
/// every frame cache it by revision.
|
||||
pub fn proxy_mixed(&self, item: Option<usize>) -> (bool, bool) {
|
||||
self.proxy_mixed_with(item, &[])
|
||||
}
|
||||
|
||||
/// [`DocState::proxy_mixed`] with the gradient mesh points a solid fill color recolors
|
||||
/// (`points`, see [`Session::fill_mesh_points`]): a mesh among them counts with the colors of
|
||||
/// its picked points instead of its fill.
|
||||
fn proxy_mixed_with(&self, item: Option<usize>, points: &[(NodeId, Vec<usize>)]) -> (bool, bool) {
|
||||
if self.selection.is_empty() {
|
||||
return (false, false);
|
||||
}
|
||||
@@ -291,7 +302,10 @@ impl DocState {
|
||||
let differ = |stroke: bool| {
|
||||
let item = first.and_then(|f| f.appearance.item_of_kind(item, !stroke));
|
||||
let set = if item.is_some() { &selected } else { &nodes };
|
||||
let mut paints = set.iter().map(|n| proxy_paint(n, stroke, item));
|
||||
let mut paints = set.iter().flat_map(|n| match picked_colors(n, if stroke || item.is_some() { &[] } else { points }) {
|
||||
c if c.is_empty() => vec![proxy_paint(n, stroke, item)],
|
||||
c => c.into_iter().map(Paint::solid).collect(),
|
||||
});
|
||||
let Some(p0) = paints.next() else { return false };
|
||||
paints.any(|p| !same_in_proxy(&p0, &p))
|
||||
};
|
||||
@@ -313,8 +327,9 @@ impl DocState {
|
||||
|
||||
impl Session {
|
||||
/// [`DocState::proxy_mixed`] of the active document for the Appearance panel's active item.
|
||||
/// A gradient mesh with points picked ([`Session::fill_mesh_points`]) counts with their colors.
|
||||
pub fn proxy_mixed(&self) -> (bool, bool) {
|
||||
self.active().map_or((false, false), |st| st.proxy_mixed(self.appearance_item()))
|
||||
self.active().map_or((false, false), |st| st.proxy_mixed_with(self.appearance_item(), &self.fill_mesh_points()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -539,8 +554,8 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
|
||||
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 };
|
||||
// The gradient mesh points picked with the Mesh tool or Direct Selection: a solid fill
|
||||
// recolours just those points of their meshes.
|
||||
// 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![] };
|
||||
// Without `item`, unless the Appearance panel's active fill item takes the paint.
|
||||
let colorized = if fill && p.get("item").is_none() && item == ItemTarget::Top {
|
||||
@@ -871,6 +886,55 @@ pub(crate) fn picked_mesh_points_of(s: &Session, ids: &[NodeId]) -> Option<Vec<(
|
||||
(!ids.is_empty() && ids.iter().all(|id| v.iter().any(|(m, _)| m == id))).then_some(v)
|
||||
}
|
||||
|
||||
/// The colors of the picked points of `n` (see [`picked_mesh_points`]) when it is a gradient mesh
|
||||
/// among `points`, in the order they were picked; empty otherwise.
|
||||
fn picked_colors(n: &Node, points: &[(NodeId, Vec<usize>)]) -> Vec<Color> {
|
||||
match (&n.kind, points.iter().find(|(id, _)| *id == n.id)) {
|
||||
(NodeKind::Mesh(m), Some((_, v))) => v.iter().filter_map(|i| m.points.get(*i)).map(|q| q.color).collect(),
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The picked gradient mesh points that a solid fill color (`paint.setFill` without `ids` or
|
||||
/// `item`) recolors instead of their meshes' fills, each mesh with its points: the targets are
|
||||
/// resolved as [`set_paint`] resolves them, so this is empty while the Appearance panel's
|
||||
/// active item is a fill row or an object of a symbol instance is selected, and a mesh with
|
||||
/// points picked counts even when other objects are selected with it.
|
||||
pub fn fill_mesh_points(&self) -> Vec<(NodeId, Vec<usize>)> {
|
||||
let Some(st) = self.active() else { return vec![] };
|
||||
// Only gradient meshes have points to pick: a selection with no mesh and no container that
|
||||
// could hold one skips reading the tool's options.
|
||||
let may_hold_mesh = |id: &NodeId| st.doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Mesh(_)) || n.is_container());
|
||||
if st.selection.symbol_part.is_some() || !st.selection.subjects().iter().any(may_hold_mesh) {
|
||||
return vec![];
|
||||
}
|
||||
let Ok(item) = item_target(self, &Value::Null, "paint.setFill").map(|t| t.of_kind(self, true)) else { return vec![] };
|
||||
if item != ItemTarget::Top {
|
||||
return vec![];
|
||||
}
|
||||
let Ok(selected) = item.targets(self, &Value::Null) else { return vec![] };
|
||||
picked_mesh_points(self, &super::graph::paint_targets(&st.doc, &selected))
|
||||
}
|
||||
|
||||
/// The picked gradient mesh points that the Transparency panel's opacity (`transparency.set`
|
||||
/// without `ids` or `item`) fades instead of their objects: `None` unless every target is a
|
||||
/// gradient mesh with points picked, and while the Appearance panel's active item takes the
|
||||
/// opacity (outside opacity mask editing).
|
||||
pub fn mesh_points_picked(&self) -> Option<Vec<(NodeId, Vec<usize>)>> {
|
||||
let st = self.active()?;
|
||||
let ids = super::opacitymask::transparency_targets(self, &Value::Null).ok()?;
|
||||
// Only gradient meshes have points to pick: other targets skip reading the tool's options.
|
||||
if ids.is_empty() || !ids.iter().all(|id| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Mesh(_)))) {
|
||||
return None;
|
||||
}
|
||||
if st.doc.mask_edit.is_none() && self.appearance_item().is_some() {
|
||||
return None;
|
||||
}
|
||||
picked_mesh_points_of(self, &ids)
|
||||
}
|
||||
}
|
||||
|
||||
/// A type run's stroke; a painted stroke on a run without one gets 1 pt.
|
||||
pub(super) fn set_run_stroke(style: &mut CharStyle, paint: Paint) {
|
||||
if !paint.is_none() {
|
||||
@@ -925,7 +989,8 @@ fn swap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// The swap writes the paint of the topmost fill and stroke, not their opacity.
|
||||
let kept = super::appearance::capture_series_writes(&before, d, &ids, (true, true), (false, false), true, false);
|
||||
Ok(super::appearance::count_changed(d, &before, &ids) + usize::from(kept))
|
||||
let labels = super::graph::capture_label_changes(&before, d, &ids, false);
|
||||
Ok(super::appearance::count_changed(d, &before, &ids) + usize::from(kept || labels))
|
||||
})?;
|
||||
}
|
||||
if s.paint.stroke.is_none() && !s.paint.fill.is_none() && s.paint.stroke_width == 0.0 {
|
||||
@@ -954,7 +1019,8 @@ fn default_paint(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
let kept = super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false, false);
|
||||
Ok(super::appearance::count_changed(d, &before, &ids) + usize::from(kept))
|
||||
let labels = super::graph::capture_label_changes(&before, d, &ids, false);
|
||||
Ok(super::appearance::count_changed(d, &before, &ids) + usize::from(kept || labels))
|
||||
})?;
|
||||
}
|
||||
super::newart::reset(s);
|
||||
@@ -1084,8 +1150,8 @@ fn transparency(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
q.remove("item");
|
||||
q.remove("id");
|
||||
q.insert("ids".into(), json!(ids.iter().map(|id| id.0).collect::<Vec<_>>()));
|
||||
// The gradient mesh points picked with the Mesh tool or Direct Selection take the opacity
|
||||
// themselves, so only the mesh around them fades (#4206, #4170, #4208).
|
||||
// The gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take the
|
||||
// opacity themselves, so only the mesh around them fades (#4206, #4170, #4208).
|
||||
if matches!(item, ItemTarget::Top)
|
||||
&& let Some(o) = q.get("opacity").and_then(Value::as_f64)
|
||||
&& let Some(points) = picked_mesh_points_of(s, &ids)
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -77,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reverse Path Direction",
|
||||
["Object", "Path"],
|
||||
None,
|
||||
"{ids?|id?, subpath?: usize (reverse only this subpath of each path, 0 included; default: every subpath), reversed?: bool (true: every subpath runs counter-clockwise on screen, false: clockwise, the Attributes panel's Reverse Path Direction On / Off; omitted: flip each path; with subpath, the direction is not read: that subpath is flipped)} the paths in ids or the selection (groups and compound paths: the paths inside), as one undo step → {changed: paths}",
|
||||
"{ids?|id?, subpath?: usize (reverse only this subpath of each path, 0 included; default: every subpath), reversed?: bool (true: every subpath runs counter-clockwise on screen, false: clockwise, the Attributes panel's Reverse Path Direction On / Off; omitted: flip each path; with subpath, the direction is not read: that subpath is flipped)} the paths in ids or the selection (groups and compound paths: the paths inside), as one undo step; when every subpath of a path turns alike, its strokes' width profiles (sides swapped) and pen pressure, tilt, bearing and rotation turn with it, so they draw as before → {changed: paths}",
|
||||
has_selected_path,
|
||||
reverse
|
||||
),
|
||||
@@ -315,13 +315,13 @@ fn set_handle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let pos = Point::new(f64_req(p, "x", "path.setHandle")?, f64_req(p, "y", "path.setHandle")?);
|
||||
let independent = switch_or(p, "independent", false, "path.setHandle")?;
|
||||
// A handle already there, on an anchor already of the kind it would get, changes nothing and
|
||||
// records no undo step.
|
||||
if let Some(a) = anchor_of(s, id, si, ai)? {
|
||||
let mut b = a;
|
||||
b.set_handle(out, pos, independent);
|
||||
if b == a {
|
||||
return ok();
|
||||
}
|
||||
// records no undo step. The handle is compared directly: `set_handle` would recompute the
|
||||
// other handle of a smooth anchor, which need not give back the same value.
|
||||
if let Some(a) = anchor_of(s, id, si, ai)?
|
||||
&& (if out { a.h_out } else { a.h_in }) == pos
|
||||
&& !(independent && a.kind != AnchorKind::Corner)
|
||||
{
|
||||
return ok();
|
||||
}
|
||||
s.edit("Reshape", |d, _| {
|
||||
let path = path_mut(d, id)?;
|
||||
@@ -462,22 +462,24 @@ fn reverse(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut changed = 0;
|
||||
for id in &ids {
|
||||
let path = path_mut(d, *id)?;
|
||||
if let Some(si) = subpath {
|
||||
if let Some(sp) = path.subpaths.get_mut(si) {
|
||||
let flip: Vec<bool> = match subpath {
|
||||
Some(si) => (0..path.subpaths.len()).map(|i| i == si).collect(),
|
||||
None => path.subpaths.iter().map(|sp| want.is_none_or(|ccw| (sp.signed_area() < 0.0) != ccw)).collect(),
|
||||
};
|
||||
if !flip.contains(&true) {
|
||||
continue;
|
||||
}
|
||||
// The stroke's width profile and pen recordings turn with the path, read before it turns.
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
vectorcraft_doc::blend::reverse_stroke_records(n, &flip);
|
||||
}
|
||||
let path = path_mut(d, *id)?;
|
||||
for (sp, f) in path.subpaths.iter_mut().zip(flip) {
|
||||
if f {
|
||||
sp.reverse();
|
||||
changed += 1;
|
||||
}
|
||||
} else {
|
||||
let flip: Vec<bool> = path.subpaths.iter().map(|sp| want.is_none_or(|ccw| (sp.signed_area() < 0.0) != ccw)).collect();
|
||||
if flip.contains(&true) {
|
||||
for (sp, f) in path.subpaths.iter_mut().zip(flip) {
|
||||
if f {
|
||||
sp.reverse();
|
||||
}
|
||||
}
|
||||
changed += 1;
|
||||
}
|
||||
}
|
||||
changed += 1;
|
||||
}
|
||||
Ok(changed)
|
||||
})?;
|
||||
|
||||
@@ -19,7 +19,7 @@ use vectorcraft_tools::distort::perspective::widget::{WidgetCorner, WidgetPlace}
|
||||
use vectorcraft_tools::distort::perspective::{GridDefinition, PerspectiveGrid};
|
||||
use vectorcraft_tools::{PointerEvent, PointerKind, ToolKey};
|
||||
|
||||
use super::distortcmds::{grid_of, silent, store_grid};
|
||||
use super::distortcmds::{grid_kept, grid_of, silent, store_grid};
|
||||
use super::{CommandSpec, EngineError, Result, Session, always, bad, bool_or, cmd, has_doc, str_param, switch_or, unique_name};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -261,10 +261,21 @@ pub(crate) fn grid_preset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let g = s.perspective_preset_grid(&name, ab).ok_or_else(|| bad(C, format!("no perspective grid preset named `{name}`")))?;
|
||||
// The objects stay attached and the view options stay as they were.
|
||||
let g = PerspectiveGrid { attached: old.attached, locked: old.locked, lock_station: old.lock_station, snap: old.snap, rulers: old.rulers, ..g };
|
||||
s.edit("Perspective Grid Preset", |d, _| {
|
||||
store_grid(d, &g);
|
||||
Ok(())
|
||||
})?;
|
||||
// When the document holds this grid already, apart from whether it shows and its active plane,
|
||||
// the preset only sets those two, without an undo step (as perspective.grid.show and
|
||||
// perspective.plane.set do).
|
||||
let view = PerspectiveGrid { visible: old.visible, plane: old.plane, ..g.clone() };
|
||||
if !grid_kept(&s.doc()?.doc, &view) {
|
||||
s.edit("Perspective Grid Preset", |d, _| {
|
||||
store_grid(d, &g);
|
||||
Ok(())
|
||||
})?;
|
||||
} else if (old.visible, old.plane) != (g.visible, g.plane) {
|
||||
silent(s, |cur| {
|
||||
cur.visible = g.visible;
|
||||
cur.plane = g.plane;
|
||||
})?;
|
||||
}
|
||||
Ok(g.definition_json())
|
||||
}
|
||||
|
||||
|
||||
@@ -75,7 +75,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Place…",
|
||||
["File"],
|
||||
Some("Cmd+Shift+P"),
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file placed in a clip group, which the Links commands take}. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed",
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file placed in a clip group, which the Links commands take}. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed",
|
||||
has_doc,
|
||||
place
|
||||
),
|
||||
@@ -962,8 +962,10 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
(None, [id]) => *id,
|
||||
_ => return Err(bad(C, "select one image or pass id")),
|
||||
};
|
||||
// An image in opacity-mask art or a definition's art is found by its id too (`links.list`).
|
||||
let n = st.doc.stored_node(id).map(|(n, _)| &**n).ok_or(EngineError::NoNode(id))?;
|
||||
// An image in opacity-mask art, a definition's art or a stored brush's art is found by its id
|
||||
// too (`links.list`).
|
||||
let doc = super::links::with_brush_art(&st.doc);
|
||||
let n = doc.stored_node(id).map(|(n, _)| &**n).ok_or(EngineError::NoNode(id))?;
|
||||
let NodeKind::Image(im) = &n.kind else { return Err(bad(C, format!("object {} is not an image", id.0))) };
|
||||
// Effective resolution: 72 pt per inch over the points one pixel spans along each axis.
|
||||
let [a, b, c, d, ..] = im.xf.as_coeffs();
|
||||
|
||||
@@ -330,7 +330,8 @@ pub(crate) fn node(d: &mut Document, s: &Source, link: LinkInfo, bounding: bool)
|
||||
}
|
||||
|
||||
/// `d` for output: linked images and placed documents that keep only their previews get their
|
||||
/// files back, else output as their previews, with a warning.
|
||||
/// files back, else output as their previews, with a warning. The art of the stored brushes counts
|
||||
/// too.
|
||||
pub(crate) fn full_documents(d: &Document) -> (Cow<'_, Document>, Vec<String>) {
|
||||
let (d, mut warnings) = super::super::links::full_linked_images(d, Default::default());
|
||||
let doc = match &d {
|
||||
@@ -339,7 +340,7 @@ pub(crate) fn full_documents(d: &Document) -> (Cow<'_, Document>, Vec<String>) {
|
||||
};
|
||||
let mut need: Vec<PlacedDocument> = vec![];
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
doc.visit_placed(|_, p| {
|
||||
super::super::links::with_brush_art(doc).visit_placed(|_, p| {
|
||||
if doc.images.get(&p.key).is_some_and(ImageBlob::is_proxy) && seen.insert(p.key.clone()) {
|
||||
need.push(p.clone());
|
||||
}
|
||||
@@ -370,7 +371,7 @@ pub(crate) fn full_documents(d: &Document) -> (Cow<'_, Document>, Vec<String>) {
|
||||
"{n} placed documents output as their previews: their files can't be found, or changed since they were read (relink or update them)"
|
||||
),
|
||||
});
|
||||
out.placed_as_previews(&previews);
|
||||
super::super::links::editing_brush_art(&mut out, |out| out.placed_as_previews(&previews));
|
||||
}
|
||||
(Cow::Owned(out), warnings)
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use super::super::utf16_order_without_mark;
|
||||
use super::{Point, Rect, Result, bad, bool_or, fileio, shapes, str_param};
|
||||
|
||||
/// Text files as `file.place` reports them (not a format `document.open` reads).
|
||||
@@ -76,8 +77,10 @@ pub(super) fn import(bytes: &[u8], o: TextOptions, cmd: &str) -> Result<String>
|
||||
Ok(clean(&decode(bytes, o), o))
|
||||
}
|
||||
|
||||
/// `bytes` as text: Unicode (UTF-8, or UTF-16 with a byte-order mark; bytes that aren't UTF-8 are
|
||||
/// read as the platform's 8-bit set), or the platform's 8-bit character set.
|
||||
/// `bytes` as text: Unicode (UTF-8, or UTF-16 with a byte-order mark, or without one when the
|
||||
/// file has an even length, reads as valid UTF-16 with no NUL character in the byte order
|
||||
/// [`utf16_order_without_mark`] gives; bytes that aren't UTF-8 are read as the platform's 8-bit
|
||||
/// set), or the platform's 8-bit character set.
|
||||
fn decode(bytes: &[u8], o: TextOptions) -> String {
|
||||
let eight_bit = |b: &[u8]| -> String { b.iter().map(|&c| if o.mac { mac_roman(c) } else { windows_1252(c) }).collect() };
|
||||
if o.ansi {
|
||||
@@ -91,7 +94,17 @@ fn decode(bytes: &[u8], o: TextOptions) -> String {
|
||||
[0xEF, 0xBB, 0xBF, rest @ ..] => String::from_utf8_lossy(rest).into_owned(),
|
||||
[0xFF, 0xFE, rest @ ..] => utf16(rest, true),
|
||||
[0xFE, 0xFF, rest @ ..] => utf16(rest, false),
|
||||
_ => std::str::from_utf8(bytes).map_or_else(|_| eight_bit(bytes), str::to_string),
|
||||
_ => {
|
||||
let without_mark = (bytes.len().is_multiple_of(2) && bytes.contains(&0))
|
||||
.then(|| utf16_order_without_mark(bytes))
|
||||
.flatten()
|
||||
.and_then(|le| {
|
||||
let units = bytes.as_chunks::<2>().0.iter().map(|&c| if le { u16::from_le_bytes(c) } else { u16::from_be_bytes(c) });
|
||||
char::decode_utf16(units).collect::<std::result::Result<String, _>>().ok()
|
||||
})
|
||||
.filter(|text| !text.contains('\0'));
|
||||
without_mark.unwrap_or_else(|| std::str::from_utf8(bytes).map_or_else(|_| eight_bit(bytes), str::to_string))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -51,6 +51,7 @@ use vectorcraft_doc::{Effect, Node};
|
||||
use vectorcraft_plugins::{Budget, Command, Kind, Plugin, effect, export, objects, registry, safe_mode};
|
||||
|
||||
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, cmd, has_doc, ids_param, str_param, switch_or};
|
||||
use crate::store::StoreTurn;
|
||||
|
||||
use vectorcraft_plugins::permissions::{self, Grant, GrantToken, Permission};
|
||||
|
||||
@@ -683,6 +684,9 @@ thread_local! {
|
||||
/// Tests: runs once in the next `plugin.install` on this thread after it installs and before it
|
||||
/// writes the store.
|
||||
pub(crate) static BEFORE_STORE: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
|
||||
/// Tests: runs once on this thread when [`keep_installed`] has written the module to the store
|
||||
/// and before it writes the grant.
|
||||
pub(crate) static BEFORE_GRANT_STORED: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
|
||||
/// Tests: runs once on this thread when [`hold_plugin_changes`] finds the lock held and waits.
|
||||
pub(crate) static WHILE_WAITING: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
|
||||
}
|
||||
@@ -718,7 +722,9 @@ pub(crate) fn hold_plugin_changes() -> std::sync::MutexGuard<'static, ()> {
|
||||
/// the next start → its `plugin.list` entry. A refused install changes neither the plug-in store
|
||||
/// nor the plug-ins and grants of the process. A module that lists no permissions ends any grant
|
||||
/// held for its id. A `plugin.remove` in another session waits until the install has written the
|
||||
/// store.
|
||||
/// store. With a plug-in store, all of it happens in a turn on the store ([`StoreTurn`]), so another
|
||||
/// process using the same folder changes it before or after; when the store can't be locked, nothing
|
||||
/// is installed.
|
||||
fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "plugin.install";
|
||||
// One use: spent whatever this install does.
|
||||
@@ -736,8 +742,11 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
{
|
||||
return Err(bad(C, "the module doesn't have the SHA-256 `hash` gives: nothing was installed"));
|
||||
}
|
||||
// A removal in another session waits until the store holds what this install wrote.
|
||||
// A removal in another session waits until the store holds what this install wrote, and so
|
||||
// does a change of the store by another process.
|
||||
let _held = hold_plugin_changes();
|
||||
let turn =
|
||||
s.plugin_store_turn().map_err(|e| EngineError::Other(format!("{C}: {}: {e}: nothing was installed", crate::store::STORE_NOT_LOCKED)))?;
|
||||
// The grant the checks below count on, the approval included. The install checks it again,
|
||||
// with the plug-in installed under the id, before anything is stored: another session may
|
||||
// change either in between.
|
||||
@@ -844,41 +853,12 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// The plug-in gets the settings and cache kept for its id. A module without permissions takes
|
||||
// the id over, so nothing the user approved for the id applies any more.
|
||||
let installed = registry::install_checked(plugin, update, check, || s.attach_plugin_storage(&id), err)?;
|
||||
let installed = registry::install_checked(plugin, update, check, || s.attach_plugin_storage(&turn, &id), err)?;
|
||||
#[cfg(test)]
|
||||
if let Some(between) = BEFORE_STORE.take() {
|
||||
between();
|
||||
}
|
||||
// Installed plug-ins stay installed after a restart (#2541). The module is written first and its
|
||||
// grant only once it is there; when the grant can't be written, the store gets the module it
|
||||
// held back. A failed write of that module is only logged: the store then holds the new module,
|
||||
// which the grant doesn't cover. A write that reports a failure may still have put the old
|
||||
// module back, so the store is read again to tell which module it holds. A stored module that
|
||||
// can't be read back isn't replaced by one that needs a grant.
|
||||
let previous = s.stored_plugin_bytes(&id);
|
||||
let mut stored = (previous.is_ok() || !asks) && s.store_plugin(&id, &bytes);
|
||||
let holds_new = |s: &Session| s.stored_plugin_bytes(&id).is_ok_and(|held| held.as_deref() == Some(&bytes[..]));
|
||||
if asks {
|
||||
if stored && !s.store_grant(&id, Some(g)) {
|
||||
stored = !s.put_back_plugin(&id, previous.ok().flatten().as_deref()) && holds_new(s);
|
||||
}
|
||||
} else {
|
||||
// When the write failed, the old stored module stays in the folder and needs its grant at
|
||||
// the next launch. A grant that can't be removed still approves the old bytes, so the store
|
||||
// gets the module it held back. When that module can't be read or written back, or there
|
||||
// was none, no module goes with the grant, and the grant stops counting for every session in
|
||||
// the process attached to the folder. A grants file that is too large or doesn't hold a list
|
||||
// approves nothing, and the new module stays; one that can't be opened or read may approve
|
||||
// the old bytes once it reads again.
|
||||
let writes = s.grant_writes();
|
||||
if stored && !s.store_grant(&id, None) && s.holds_plugin_grant(&id) {
|
||||
let back = previous.as_ref().is_ok_and(|held| s.put_back_plugin(&id, held.as_deref()));
|
||||
stored = !back && holds_new(s);
|
||||
if !back || matches!(previous, Ok(None)) {
|
||||
s.ignore_stored_grant(&id, writes);
|
||||
}
|
||||
}
|
||||
}
|
||||
let stored = keep_installed(s, &turn, &id, &bytes, asks.then_some(g));
|
||||
// Installing a disabled plug-in again (an updated version) turns it on for the next launch too,
|
||||
// also when it is disabled by its stored file alone (it stopped a launch while loading). When
|
||||
// the new version could not replace the stored file, the old one stays disabled.
|
||||
@@ -891,8 +871,9 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
s.store_disabled_plugins();
|
||||
s.store_disabled_plugins_in(&turn);
|
||||
}
|
||||
drop(turn);
|
||||
let mut v = describe_installed(&installed);
|
||||
if !unknown.is_empty() {
|
||||
v["unknownCommands"] = json!(unknown);
|
||||
@@ -900,6 +881,53 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// Keeps the plug-in `id` that `plugin.install` installed, its module `bytes`, in the plug-in store,
|
||||
/// in `turn`, with `grant` when its module lists permissions (`None`: it lists none, and the grant
|
||||
/// held for the id is removed) → whether the store now holds the new module (`false` without a
|
||||
/// store).
|
||||
///
|
||||
/// Installed plug-ins stay installed after a restart (#2541). The module is written first and its
|
||||
/// grant only once it is there; when the grant can't be written, the store gets the module it held
|
||||
/// back. A failed write of that module is only logged: the store then holds the new module, which
|
||||
/// the grant doesn't cover. A write that reports a failure may still have put the old module back,
|
||||
/// so the store is read again to tell which module it holds. A stored module that can't be read back
|
||||
/// isn't replaced by one that needs a grant.
|
||||
pub(crate) fn keep_installed(s: &Session, turn: &StoreTurn, id: &str, bytes: &[u8], grant: Option<Grant>) -> bool {
|
||||
let asks = grant.is_some();
|
||||
let previous = s.stored_plugin_bytes(id);
|
||||
let mut stored = (previous.is_ok() || !asks) && s.store_plugin(turn, id, bytes);
|
||||
#[cfg(test)]
|
||||
if let Some(between) = BEFORE_GRANT_STORED.take() {
|
||||
between();
|
||||
}
|
||||
let holds_new = |s: &Session| s.stored_plugin_bytes(id).is_ok_and(|held| held.as_deref() == Some(bytes));
|
||||
match grant {
|
||||
Some(g) => {
|
||||
if stored && !s.store_grant_in(turn, id, Some(g)) {
|
||||
stored = !s.put_back_plugin(turn, id, previous.ok().flatten().as_deref()) && holds_new(s);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
// When the write failed, the old stored module stays in the folder and needs its grant
|
||||
// at the next launch. A grant that can't be removed still approves the old bytes, so the
|
||||
// store gets the module it held back. When that module can't be read or written back, or
|
||||
// there was none, no module goes with the grant, and the grant stops counting for every
|
||||
// session in the process attached to the folder. A grants file that is too large or
|
||||
// doesn't hold a list approves nothing, and the new module stays; one that can't be
|
||||
// opened or read may approve the old bytes once it reads again.
|
||||
let writes = s.grant_writes();
|
||||
if stored && !s.store_grant_in(turn, id, None) && s.holds_plugin_grant(id) {
|
||||
let back = previous.as_ref().is_ok_and(|held| s.put_back_plugin(turn, id, held.as_deref()));
|
||||
stored = !back && holds_new(s);
|
||||
if !back || matches!(previous, Ok(None)) {
|
||||
s.ignore_stored_grant(id, writes);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
stored
|
||||
}
|
||||
|
||||
/// `plugin.inspect`: what installing the module would install, without installing it, whether that
|
||||
/// needs the user to grant its permissions first (`needsApproval`) and whether it would take
|
||||
/// another module's place (`needsReplace`).
|
||||
@@ -992,15 +1020,17 @@ fn load_folder(s: &Session, folder: &str) -> Value {
|
||||
None if crate::file_access::current().is_none() => Ok(()),
|
||||
None => Err(format!("automation path rejected: {} isn't valid text", f.display())),
|
||||
};
|
||||
// A `plugin.install` in another session finishes writing the store first.
|
||||
// A `plugin.install` in another session or process finishes writing the store first. When the
|
||||
// store can't be locked, the folder still loads, and the store isn't written.
|
||||
let _held = hold_plugin_changes();
|
||||
let turn = s.plugin_store_turn().unwrap_or_else(|_| StoreTurn::unheld());
|
||||
match registry::load_folder_where(std::path::Path::new(folder), allow, s.plugin_folder_approver()) {
|
||||
Ok(r) => {
|
||||
for id in &r.loaded {
|
||||
s.attach_plugin_storage(id);
|
||||
s.attach_plugin_storage(&turn, id);
|
||||
}
|
||||
if r.disabled_changed {
|
||||
s.store_disabled_plugins();
|
||||
s.store_disabled_plugins_in(&turn);
|
||||
}
|
||||
json!({"folder": folder, "loaded": r.loaded, "failed": r.failed.iter().map(|(f, e)| json!({"file": f, "error": e})).collect::<Vec<_>>()})
|
||||
}
|
||||
@@ -1140,6 +1170,9 @@ fn set_enabled(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
(None, None) => return Err(bad(C, "give `id` or `file` (see plugin.safeMode)")),
|
||||
};
|
||||
let items: Vec<&safe_mode::Item> = std::iter::once(&item).chain(stored.as_ref()).collect();
|
||||
// The list is changed and saved in one turn on the plug-in store, so that an install in another
|
||||
// process doesn't change the store in between.
|
||||
let turn = s.plugin_store_turn().ok();
|
||||
if enabled && !safe_mode::disabled().iter().any(|i| items.iter().any(|item| i.same(item))) {
|
||||
return Err(bad(C, "that plug-in isn't disabled (see plugin.safeMode)"));
|
||||
}
|
||||
@@ -1149,7 +1182,7 @@ fn set_enabled(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// Without a plug-in folder (a session confined to automation roots), or when the list there
|
||||
// can't take the change, the change stays in this process and goes with the next change that saves.
|
||||
let saved = !changed || s.store_disabled_plugins();
|
||||
let saved = !changed || turn.as_ref().is_some_and(|turn| s.store_disabled_plugins_in(turn));
|
||||
Ok(json!({"changed": changed, "saved": saved, "disabled": safe_mode::disabled().iter().map(shown_item).collect::<Vec<_>>()}))
|
||||
}
|
||||
|
||||
@@ -1164,31 +1197,35 @@ fn info(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = str_param(p, "id").ok_or_else(|| bad("plugin.remove", "missing `id`"))?;
|
||||
// An install in another session finishes its store writes first.
|
||||
// An install in another session or process finishes its store writes first. When the store
|
||||
// can't be locked, nothing is removed.
|
||||
let _held = hold_plugin_changes();
|
||||
let turn = s
|
||||
.plugin_store_turn()
|
||||
.map_err(|e| EngineError::Other(format!("plugin.remove: {}: {e}: nothing was removed", crate::store::STORE_NOT_LOCKED)))?;
|
||||
let installed = registry::get(id).is_some();
|
||||
// Settings and cache the store keeps for an id that isn't installed are deleted too.
|
||||
let stored = !installed && vectorcraft_plugins::manifest::valid_id(id) && s.has_plugin_storage(id);
|
||||
// Installed again, it asks again. A grant that can't be removed still approves the module, and
|
||||
// so may a grants file that can't be opened or read. One that is too large or doesn't hold a
|
||||
// list approves nothing and doesn't stop the removal.
|
||||
let forget = || s.store_grant(id, None) || !s.holds_plugin_grant(id);
|
||||
let forget = || s.store_grant_in(&turn, id, None) || !s.holds_plugin_grant(id);
|
||||
// Its settings and cache are moved aside and its grant removed before anything is deleted: when
|
||||
// either can't be done, the plug-in stays installed, as it was, and a second `plugin.remove`
|
||||
// tries again.
|
||||
let failed = if installed || stored {
|
||||
s.remove_plugin_storage(id, forget).err().map(|e| e.to_string())
|
||||
s.remove_plugin_storage(&turn, id, forget).err().map(|e| e.to_string())
|
||||
} else {
|
||||
(!forget()).then(|| crate::store::GRANT_NOT_REMOVED.to_string())
|
||||
};
|
||||
if let Some(e) = failed {
|
||||
if installed {
|
||||
s.attach_plugin_storage(id);
|
||||
s.attach_plugin_storage(&turn, id);
|
||||
}
|
||||
return Err(EngineError::Other(e));
|
||||
}
|
||||
registry::revoke(id);
|
||||
s.unstore_plugin(id);
|
||||
s.unstore_plugin(&turn, id);
|
||||
if !stored && (!installed || !registry::remove(id)) {
|
||||
return Err(err(vectorcraft_plugins::Error::NotFound(id.into())));
|
||||
}
|
||||
@@ -1248,7 +1285,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Install Plug-in",
|
||||
[],
|
||||
None,
|
||||
"{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a WebAssembly plug-in for this session (a module whose commandAllowlist names a command no plug-in may call, such as one that reads or writes files, is refused) → its plugin.list entry, plus unknownCommands?: [id] (commandAllowlist ids no command has; a call of one fails)",
|
||||
"{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a WebAssembly plug-in for this session (with a plug-in store, the install waits while another window or process changes the store and writes the module and its grant before that window or process changes it again; when the store's disabled.lock can't be locked, nothing is installed) (a module whose commandAllowlist names a command no plug-in may call, such as one that reads or writes files, is refused) → its plugin.list entry, plus unknownCommands?: [id] (commandAllowlist ids no command has; a call of one fails)",
|
||||
always,
|
||||
install
|
||||
),
|
||||
@@ -1266,7 +1303,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Remove Plug-in",
|
||||
[],
|
||||
None,
|
||||
"{id} uninstall a plug-in (its live effects then leave the geometry as it is) and delete the settings and cache it kept (when their folder can't be moved aside, or its grant can't be removed from the plug-in store, the command fails and the plug-in stays installed; when the settings can't be moved back either, the error names the folder they stay in, and the next load, install or removal of the plug-in moves them back); for an id that isn't installed, deletes the settings and cache the plug-in store still keeps for it → {removed}",
|
||||
"{id} uninstall a plug-in (its live effects then leave the geometry as it is) and delete the settings and cache it kept (when their folder can't be moved aside, or its grant can't be removed from the plug-in store, the command fails and the plug-in stays installed; when the settings can't be moved back either, the error names the folder they stay in, and the next load, install or removal of the plug-in moves them back); for an id that isn't installed, deletes the settings and cache the plug-in store still keeps for it; it waits while another window or process changes the plug-in store, and when the store's disabled.lock can't be locked, the command fails and nothing is removed → {removed}",
|
||||
always,
|
||||
remove
|
||||
),
|
||||
|
||||
@@ -217,6 +217,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[
|
||||
p!("recentFontsCount", "Type", "Options", "Number of Recent Fonts", int(1, 15)),
|
||||
p!("missingGlyphProtection", "Type", "Options", "Enable Missing Glyph Protection", bool),
|
||||
p!("highlightAlternateGlyphs", "Type", "Options", "Highlight Alternate Glyphs", bool),
|
||||
p!("showCharacterAlternates", "Type", "Options", "Show Character Alternates", bool),
|
||||
p!("highlightSubstitutedFonts", "Type", "Options", "Highlight Substituted Fonts", bool),
|
||||
p!("placeholderText", "Type", "Options", "Fill New Type Objects With Placeholder Text", bool),
|
||||
p!("typedLists", "Type", "Options", "Start Lists From Typed Markers", bool),
|
||||
|
||||
@@ -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 (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)], 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}",
|
||||
has_doc,
|
||||
apply
|
||||
),
|
||||
|
||||
@@ -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 → {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)} 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
|
||||
),
|
||||
@@ -31,7 +31,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Stroke Weight Up",
|
||||
[],
|
||||
Some("Cmd+Alt+."),
|
||||
"{ids?|id?} raise each selected stroke's weight by one step of Units › Stroke (a quarter unit below one unit, then whole units; up to 1000 pt), each from its own weight: the selected objects' active or top stroke, type's stroked characters; objects without a stroke are left alone. With nothing selected (and no ids), the weight of the next object drawn. On a path directly in a graph series, the graph also stores the new weight of the topmost visible stroke (docs/mcp.md) → {objects}",
|
||||
"{ids?|id?} raise each selected stroke's weight by one step of Units › Stroke (a quarter unit below one unit, then whole units; up to 1000 pt), each from its own weight: the selected objects' active or top stroke, type's stroked characters; objects without a stroke are left alone. With nothing selected (and no ids), the weight of the next object drawn. On a path directly in a graph series, the graph also stores the new weight of the topmost visible stroke, and on a graph label the new weight of its characters' stroke or its stroke row for every label of its kind (docs/mcp.md) → {objects}",
|
||||
has_doc,
|
||||
|s, p| stroke_step(s, p, true)
|
||||
),
|
||||
|
||||
@@ -40,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New Graphic Style",
|
||||
["Window", "Graphic Styles"],
|
||||
None,
|
||||
"{name?, id?} a style from object `id` or the first selected object: its appearance, opacity, blend mode, isolate and knockout (a group without fills or strokes of its own lends its topmost object's, type its characters'; a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own stands for the topmost path directly in it; placed gradients are kept relative to its bounds); links the object. Names are made unique → {name}",
|
||||
"{name?, id?} a style from object `id` or the first selected object: its appearance, opacity, blend mode, isolate and knockout (a group without fills or strokes of its own lends its topmost object's, type its characters'; a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own stands for the topmost path directly in it; placed gradients are kept relative to its bounds); links the object, unless it is the art of a graph design in a series. Names are made unique → {name}",
|
||||
has_doc,
|
||||
style_new
|
||||
),
|
||||
@@ -68,7 +68,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Redefine Graphic Style",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{name?, id?} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object (a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own: the topmost path directly in it); the objects still linked to it update, and that object becomes linked. A linked graph series group passes the style to the paths directly in it, other than the source and paths linked to the style whose look was edited, and is left cleared (as appearance.clear) and unlinked. On a linked path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, the graph stores the label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind → {name}",
|
||||
"{name?, id?} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object (a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own: the topmost path directly in it); the objects still linked to it update, and that object becomes linked. The art of a graph design in a series keeps its look and is unlinked, as the source or as a linked object. A linked graph series group passes the style to the paths directly in it, other than the source and paths linked to the style whose look was edited, and is left cleared (as appearance.clear) and unlinked. On a linked path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, the graph stores the label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind → {name}",
|
||||
has_doc,
|
||||
style_redefine
|
||||
),
|
||||
@@ -392,8 +392,10 @@ fn style_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None => d.new_graphic_style_name(),
|
||||
};
|
||||
let g = GraphicStyle { id: d.next_graphic_style_id(), ..GraphicStyle::of(name.clone(), captured(n), n) };
|
||||
// The art of a graph design in a series is not linked: the graph draws it again from the design.
|
||||
let link = (!super::graph::is_design_art(d, src)).then_some(g.id);
|
||||
s.edit("New Graphic Style", |d, _| {
|
||||
set_link(d, &[src], Some(g.id));
|
||||
set_link(d, &[src], link);
|
||||
d.graphic_styles.push(g);
|
||||
Ok(())
|
||||
})?;
|
||||
@@ -491,10 +493,12 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.edit_named("Redefine Graphic Style “{name}”", &name, false, |d, _| {
|
||||
let id = d.graphic_style_id(i);
|
||||
let old = std::mem::replace(&mut d.graphic_styles[i], GraphicStyle { name: name.clone(), id, ..look });
|
||||
// Objects still linked follow the new definition; edited ones are unlinked (they keep
|
||||
// their look), and the source keeps its own.
|
||||
// Objects still linked follow the new definition; edited ones are unlinked (they keep their look), and the
|
||||
// source keeps its own. The art of a graph design in a series is unlinked and keeps its look too, as the
|
||||
// source or as a linked object: the graph draws it again from the design.
|
||||
let linked = objects_where(d, |n| n.extras().graphic_style == Some(id) && n.id != src);
|
||||
let (follow, edited): (Vec<NodeId>, Vec<NodeId>) = linked.into_iter().partition(|nid| d.node(*nid).is_some_and(|n| in_sync(n, &old)));
|
||||
let (follow, edited): (Vec<NodeId>, Vec<NodeId>) =
|
||||
linked.into_iter().partition(|nid| !super::graph::is_design_art(d, *nid) && d.node(*nid).is_some_and(|n| in_sync(n, &old)));
|
||||
set_link(d, &edited, None);
|
||||
// A linked graph series group passes the style to the paths directly inside it, so the graph stores it, and
|
||||
// goes back to the empty appearance the graph draws it with. The source and the edited paths keep their look.
|
||||
@@ -509,7 +513,8 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
super::appearance::capture_series_writes(&before, d, &follow_marks, (true, true), (true, true), false, true);
|
||||
super::graph::capture_label_rows(d, &follow_marks);
|
||||
set_link(d, &[src], Some(id));
|
||||
let link = (!super::graph::is_design_art(d, src)).then_some(id);
|
||||
set_link(d, &[src], link);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "name": name }))
|
||||
|
||||
@@ -62,7 +62,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Other Library…",
|
||||
["Window", "Graphic Style Libraries"],
|
||||
None,
|
||||
"{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcstyles library, or the graphic styles of any document VectorCraft opens (see document.formats), for the library panel (Window → Graphic Style Libraries lists it until the app quits; a file of the user library folder, or a file with the same extension and bytes as one there, opens as that User Defined library) → {library: id, name, count}",
|
||||
"{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcstyles library, or the graphic styles of any document VectorCraft opens (see document.formats), for the library panel (Window → Graphic Style Libraries lists it until the app quits; a file of the user library folder, or a file with the same extension and bytes as one there, opens as that User Defined library; a .ai or EPS style painting with one of the file's gradients by name takes it at the style's angle, fitted to each object it is applied to, VectorCraft's own placement) → {library: id, name, count}",
|
||||
always,
|
||||
load
|
||||
),
|
||||
|
||||
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New Swatch",
|
||||
["Window", "Swatches"],
|
||||
None,
|
||||
"{name?, color? | colors?: [colour] (one swatch each, in one undo step; #rrggbbaa and #rgba are refused) | swatch? | gradient? | pattern?: name (default: the current fill), tint?: 0..100 (% of the global or spot `swatch`, or of the one the current fill links to), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour; lab: CIE L*a*b*, how spot colours are usually defined), global?, spot? (a spot colour, always global), group?: colour group name (solid colours only; default: ungrouped), none?: true (the None paint), paint?: paint.setFill params, keepModel?: bool (as paint.setFill)} save a colour, gradient or pattern as a swatch. A tint of a global or spot colour (below 100%, without mode, global or spot) becomes a tint swatch, \"Name 40%\", linked to its base: it follows edits to the base and applies as that tint of it. A gradient swatch holds no link to the swatch its gradient came from, and a pattern swatch holds the pattern untransformed. Names are unique (\"Sky 2\"); a colour's default name is its values (\"C=10 M=20 Y=30 K=0\", \"R=255 G=128 B=0\", \"Gray K=40\", \"L=55 a=60 b=40\") → {name, names: [every new swatch]}",
|
||||
"{name?, color? | colors?: [colour] (one swatch each, in one undo step; #rrggbbaa and #rgba are refused) | swatch? | gradient? | pattern?: name (default: the current fill), tint?: 0..100 (% of the global or spot `swatch`, or of the one the current fill links to), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour; lab: CIE L*a*b*, how spot colours are usually defined), global?, spot? (a spot colour, always global), group?: colour group name (solid colours only; default: ungrouped), none?: true (the None paint), paint?: paint.setFill params, keepModel?: bool (as paint.setFill)} save a colour, gradient or pattern as a swatch. A tint of a global or spot colour (below 100%, without mode, global or spot) becomes a tint swatch, \"Name 40%\", linked to its base: it follows edits to the base and applies as that tint of it. A gradient swatch keeps the gradient's aspect (with or without start/end) and holds no link to the swatch its gradient came from, and a pattern swatch holds the pattern untransformed. Names are unique (\"Sky 2\"); a colour's default name is its values (\"C=10 M=20 Y=30 K=0\", \"R=255 G=128 B=0\", \"Gray K=40\", \"L=55 a=60 b=40\") → {name, names: [every new swatch]}",
|
||||
has_doc,
|
||||
swatch_new
|
||||
),
|
||||
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Swatch Options",
|
||||
["Window", "Swatches"],
|
||||
None,
|
||||
"{name, newName?, color? (e.g. {l, a, b} for a Lab colour; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill; the swatch's own color and a color given with mode keep their model), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour), global?, spot? (spot colours are always global), paint?: paint.setFill params ({color}, {gradient}, {swatch} or {pattern}) replacing the swatch's colour; gradient or pattern with one of the same kind} edit a swatch in any colour group, as one undo step. Fills, strokes, text, gradient stops and tint swatches linked to a global swatch take its new colour (at their own tint) and name; turning Global off unlinks them (they keep their colour). Colour, mode and spot apply to solid colours only; a tint swatch only takes a new name (edit its base) → {name, relinked: paints changed}",
|
||||
"{name, newName?, color? (e.g. {l, a, b} for a Lab colour; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill; the swatch's own color and a color given with mode keep their model), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour), global?, spot? (spot colours are always global), paint?: paint.setFill params ({color}, {gradient} or {swatch}) or {pattern: name} replacing the swatch's colour; gradient or pattern with one of the same kind (stored as swatch.new stores it: a gradient keeps its aspect with or without start/end and holds no swatch link; a pattern is untransformed)} edit a swatch in any colour group, as one undo step. Fills, strokes, text, gradient stops and tint swatches linked to a global swatch take its new colour (at their own tint) and name; turning Global off unlinks them (they keep their colour). Colour, mode and spot apply to solid colours only; a tint swatch only takes a new name (edit its base) → {name, relinked: paints changed}",
|
||||
has_doc,
|
||||
swatch_edit
|
||||
),
|
||||
@@ -187,11 +187,7 @@ fn swatch_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})),
|
||||
Paint::None => Err(bad(C, "a swatch needs a colour, gradient or pattern")),
|
||||
_ if spot || mode.is_some() || group.is_some() => Err(bad(C, "spot, mode and group apply to solid colours only")),
|
||||
// The swatch holds the gradient itself, not a link to the swatch it may have come from.
|
||||
// It keeps `geom`, which holds the aspect the swatch is applied with.
|
||||
Paint::Gradient(g) => Ok(Paint::Gradient(Box::new(vectorcraft_color::GradientPaint { swatch: None, ..*g }))),
|
||||
// The swatch holds the pattern untransformed, not the placement of the art it came from.
|
||||
Paint::Pattern { pattern, .. } => Ok(pattern_paint(&pattern)),
|
||||
paint @ (Paint::Gradient(_) | Paint::Pattern { .. }) => Ok(stored_paint(paint, p)),
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
// A name applies to a single new swatch.
|
||||
@@ -220,6 +216,27 @@ fn swatch_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "name": names[0], "names": names }))
|
||||
}
|
||||
|
||||
/// A gradient or pattern `paint`, parsed from the paint params `p`, as a new or edited swatch
|
||||
/// stores it.
|
||||
fn stored_paint(paint: Paint, p: &Value) -> Paint {
|
||||
match paint {
|
||||
// A gradient given an `aspect` but no vector is placed on a box so that the swatch keeps
|
||||
// the aspect, as `paint.setFill` places it on each object.
|
||||
Paint::Gradient(ref g) if g.geom.is_none() && g.freeform.is_none() => {
|
||||
match super::gradient::place_paint(&paint, p, Some(vectorcraft_geom::Rect::new(0.0, 0.0, 100.0, 100.0))) {
|
||||
Paint::Gradient(g) => Paint::Gradient(Box::new(vectorcraft_color::GradientPaint { swatch: None, ..*g })),
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
// The swatch holds the gradient itself, not a link to the swatch it may have come from.
|
||||
// It keeps `geom`, which holds the aspect the swatch is applied with.
|
||||
Paint::Gradient(g) => Paint::Gradient(Box::new(vectorcraft_color::GradientPaint { swatch: None, ..*g })),
|
||||
// The swatch holds the pattern untransformed, not the placement of the art it came from.
|
||||
Paint::Pattern { pattern, .. } => pattern_paint(&pattern),
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
/// The `names` list and `name` parameters, without repeats; at least one is required.
|
||||
pub(super) fn names_param(p: &Value, cmd: &str) -> Result<Vec<String>> {
|
||||
let mut seen: HashSet<String> = HashSet::new();
|
||||
@@ -866,12 +883,21 @@ fn swatch_edit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// A replacement paint of the swatch's kind (a dropped colour or edited gradient).
|
||||
let paint = match p.get("paint").filter(|v| !v.is_null()) {
|
||||
Some(v) => match (if given("mode") { paint_from(s, &keeping_model(v))? } else { paint_from(s, v)? }, &sw.paint) {
|
||||
Some(v) => match (
|
||||
// A pattern by name, as `swatch.new` takes it.
|
||||
match str_param(v, "pattern") {
|
||||
Some(pat) if d.pattern(pat).is_some() => Some(pattern_paint(pat)),
|
||||
Some(pat) => return Err(bad(C, format!("no pattern `{pat}`"))),
|
||||
None if given("mode") => paint_from(s, &keeping_model(v))?,
|
||||
None => paint_from(s, v)?,
|
||||
},
|
||||
&sw.paint,
|
||||
) {
|
||||
(Some(Paint::Solid { color, .. }), Paint::Solid { .. }) => Some(Paint::solid(color)),
|
||||
(Some(Paint::Gradient(g)), Paint::Gradient(_)) => {
|
||||
Some(Paint::Gradient(Box::new(vectorcraft_color::GradientPaint { geom: None, swatch: None, ..*g })))
|
||||
// Stored as `swatch.new` stores it.
|
||||
(Some(new @ Paint::Gradient(_)), Paint::Gradient(_)) | (Some(new @ Paint::Pattern { .. }), Paint::Pattern { .. }) => {
|
||||
Some(stored_paint(new, v))
|
||||
}
|
||||
(Some(new @ Paint::Pattern { .. }), Paint::Pattern { .. }) => Some(new),
|
||||
_ => return Err(bad(C, format!("`{name}` takes a paint of its own kind (colour, gradient or pattern)"))),
|
||||
},
|
||||
None => None,
|
||||
|
||||
@@ -13,7 +13,7 @@ use std::sync::{Arc, LazyLock};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, Symbol, SymbolNineSlice};
|
||||
use vectorcraft_geom::{Affine, Point, Rect, shapes};
|
||||
use vectorcraft_geom::{Affine, Anchor, AnchorKind, PathData, Point, Rect, SubPath, shapes};
|
||||
|
||||
use super::brushsym::{CURRENT_SYMBOL, natural_size, normalize, place_xf, set_natural_size};
|
||||
use super::clipboard::Clipboard;
|
||||
@@ -160,6 +160,7 @@ pub const BUILTIN: &[BuiltinSymbolLibrary] = &[
|
||||
BuiltinSymbolLibrary { id: "map-markers", name: "Map Markers", make: map_markers },
|
||||
BuiltinSymbolLibrary { id: "inventory-icons", name: "Inventory Icons", make: inventory_icons },
|
||||
BuiltinSymbolLibrary { id: "skill-icons", name: "Skill Icons", make: skill_icons },
|
||||
BuiltinSymbolLibrary { id: "weather-icons", name: "Weather Icons", make: weather_icons },
|
||||
];
|
||||
|
||||
/// Built-in library `id`, made once.
|
||||
@@ -358,6 +359,140 @@ fn skill_icons() -> SymbolLibrary {
|
||||
SymbolLibrary { name: "Skill Icons".into(), doc }
|
||||
}
|
||||
|
||||
/// Weather Icons: sun, moon, cloud, rain, thunder and snow for weather/status art (original, no 9-slice).
|
||||
fn weather_icons() -> SymbolLibrary {
|
||||
// 1. Sun: Central circular disk with radial rays.
|
||||
let mut sun_subpaths = Vec::new();
|
||||
sun_subpaths.extend(shapes::ellipse(Rect::new(-8.5, -8.5, 8.5, 8.5)).subpaths);
|
||||
for i in 0..8 {
|
||||
let angle = (i as f64) * std::f64::consts::PI / 4.0;
|
||||
let (sin, cos) = angle.sin_cos();
|
||||
let r_in = 11.5;
|
||||
let r_out = 18.5;
|
||||
let w = 1.5;
|
||||
let p1 = Point::new(r_in * cos - w * sin, r_in * sin + w * cos);
|
||||
let tip = Point::new(r_out * cos, r_out * sin);
|
||||
let p2 = Point::new(r_in * cos + w * sin, r_in * sin - w * cos);
|
||||
sun_subpaths.push(SubPath::polyline(&[p1, tip, p2], true));
|
||||
}
|
||||
let sun = PathData::new(sun_subpaths);
|
||||
|
||||
// 2. Moon: Crescent moon shape.
|
||||
let moon_anchors = vec![
|
||||
Anchor { p: Point::new(3.0, -17.0), h_in: Point::new(-2.0, -10.0), h_out: Point::new(-8.0, -17.0), kind: AnchorKind::Corner },
|
||||
Anchor { p: Point::new(-16.0, 0.0), h_in: Point::new(-16.0, -9.0), h_out: Point::new(-16.0, 9.0), kind: AnchorKind::Smooth },
|
||||
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 });
|
||||
|
||||
// Helper for cloud contour
|
||||
let cloud_subpath = |offset_y: f64, scale: f64| -> SubPath {
|
||||
let mut pts = Vec::new();
|
||||
let base_y = 8.0 * scale + offset_y;
|
||||
pts.push(Point::new(9.0 * scale, base_y));
|
||||
pts.push(Point::new(-9.0 * scale, base_y));
|
||||
|
||||
let c1 = Point::new(-9.0 * scale, 2.0 * scale + offset_y);
|
||||
let r1 = 6.0 * scale;
|
||||
let steps_lobe = 8;
|
||||
for i in 1..=steps_lobe {
|
||||
let a = std::f64::consts::FRAC_PI_2 + (i as f64) * std::f64::consts::PI / (steps_lobe as f64);
|
||||
pts.push(Point::new(c1.x + r1 * a.cos(), c1.y + r1 * a.sin()));
|
||||
}
|
||||
|
||||
let c2 = Point::new(0.0, -3.0 * scale + offset_y);
|
||||
let r2 = 9.0 * scale;
|
||||
let a_start = -2.973;
|
||||
let a_end = -0.169;
|
||||
let steps_top = 10;
|
||||
for i in 1..=steps_top {
|
||||
let a = a_start + (i as f64) * (a_end - a_start) / (steps_top as f64);
|
||||
pts.push(Point::new(c2.x + r2 * a.cos(), c2.y + r2 * a.sin()));
|
||||
}
|
||||
|
||||
let c3 = Point::new(9.0 * scale, 2.0 * scale + offset_y);
|
||||
let r3 = 6.0 * scale;
|
||||
for i in 1..steps_lobe {
|
||||
let a = -std::f64::consts::FRAC_PI_2 + (i as f64) * std::f64::consts::PI / (steps_lobe as f64);
|
||||
pts.push(Point::new(c3.x + r3 * a.cos(), c3.y + r3 * a.sin()));
|
||||
}
|
||||
|
||||
SubPath::polyline(&pts, true)
|
||||
};
|
||||
|
||||
// 3. Cloud: Merged circular lobes with a flat base.
|
||||
let cloud = PathData::single(cloud_subpath(0.0, 1.0));
|
||||
|
||||
// 4. Rain: Cloud outline with angled falling droplet/dash lines.
|
||||
let mut rain_subpaths = vec![cloud_subpath(-4.0, 0.9)];
|
||||
let drops = [(-6.0, 6.0), (0.0, 8.0), (6.0, 6.0)];
|
||||
for &(x0, y0) in &drops {
|
||||
let (dx, dy) = (-2.0, 6.0);
|
||||
let w = 1.0;
|
||||
let d = [Point::new(x0 + w, y0), Point::new(x0 + dx + w, y0 + dy), Point::new(x0 + dx - w, y0 + dy), Point::new(x0 - w, y0)];
|
||||
rain_subpaths.push(SubPath::polyline(&d, true));
|
||||
}
|
||||
let rain = PathData::new(rain_subpaths);
|
||||
|
||||
// 5. Thunder: Angular zigzag lightning bolt polygon.
|
||||
let bolt = [(3.0, -18.0), (-8.0, -1.0), (-1.0, -1.0), (-5.0, 18.0), (8.0, 1.0), (1.0, 1.0)];
|
||||
let bolt_pts: Vec<Point> = bolt.iter().map(|&(x, y)| Point::new(x, y)).collect();
|
||||
let thunder = PathData::single(SubPath::polyline(&bolt_pts, true));
|
||||
|
||||
// 6. Snow: Symmetrical snowflake with hexagonal cross and branching ticks.
|
||||
let mut snow_pts = Vec::new();
|
||||
let r_hub = 3.5;
|
||||
for k in 0..6 {
|
||||
let angle = (k as f64) * std::f64::consts::PI / 3.0;
|
||||
let (u_sin, u_cos) = angle.sin_cos();
|
||||
let u = Point::new(u_cos, u_sin);
|
||||
let v = Point::new(-u_sin, u_cos);
|
||||
let to_pt = |du: f64, dv: f64| Point::new(du * u.x + dv * v.x, du * u.y + dv * v.y);
|
||||
|
||||
let valley_angle = angle - std::f64::consts::PI / 6.0;
|
||||
snow_pts.push(Point::new(r_hub * valley_angle.cos(), r_hub * valley_angle.sin()));
|
||||
|
||||
snow_pts.push(to_pt(5.0, -1.0));
|
||||
snow_pts.push(to_pt(8.5, -1.0));
|
||||
snow_pts.push(to_pt(10.0, -3.0));
|
||||
snow_pts.push(to_pt(11.5, -1.0));
|
||||
snow_pts.push(to_pt(15.5, -1.0));
|
||||
snow_pts.push(to_pt(15.5, -2.5));
|
||||
|
||||
snow_pts.push(to_pt(18.0, 0.0));
|
||||
|
||||
snow_pts.push(to_pt(15.5, 2.5));
|
||||
snow_pts.push(to_pt(15.5, 1.0));
|
||||
snow_pts.push(to_pt(11.5, 1.0));
|
||||
snow_pts.push(to_pt(10.0, 3.0));
|
||||
snow_pts.push(to_pt(8.5, 1.0));
|
||||
snow_pts.push(to_pt(5.0, 1.0));
|
||||
}
|
||||
let snow = PathData::single(SubPath::polyline(&snow_pts, true));
|
||||
|
||||
let icons = [
|
||||
("Sun", sun, "#f39c12"),
|
||||
("Moon", moon, "#5c6bc0"),
|
||||
("Cloud", cloud, "#78909c"),
|
||||
("Rain", rain, "#3498db"),
|
||||
("Thunder", thunder, "#f1c40f"),
|
||||
("Snow", snow, "#29b6f6"),
|
||||
];
|
||||
let mut doc = Document::new(100.0, 100.0);
|
||||
for (name, path, hex) in icons {
|
||||
let fill = Color::from_hex(hex).unwrap_or(Color::BLACK);
|
||||
let edge = fill.lerp(&Color::BLACK, 0.35);
|
||||
let id = doc.alloc_id();
|
||||
let art = Node::path(id, path, Appearance::basic(Paint::solid(fill), Paint::solid(edge), 1.25));
|
||||
let Ok((art, size, _)) = normalize(art) else { continue };
|
||||
doc.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(art) });
|
||||
set_natural_size(&mut doc, name, Some(size));
|
||||
}
|
||||
doc.title = "Weather Icons".into();
|
||||
SymbolLibrary { name: "Weather Icons".into(), doc }
|
||||
}
|
||||
|
||||
/// An instance of symbol `name` (what the resource gathering follows).
|
||||
fn instance(name: &str) -> Node {
|
||||
Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY })
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -222,6 +222,7 @@ pub fn char_attrs(v: &CharStyle) -> Map<String, Value> {
|
||||
("warichuAlign", json!(v.warichu_align)),
|
||||
("akiLeft", json!(v.aki_left)),
|
||||
("akiRight", json!(v.aki_right)),
|
||||
("tsume", json!(v.tsume)),
|
||||
("standardVerticalRoman", json!(v.standard_vertical_roman)),
|
||||
("noBreak", json!(v.no_break)),
|
||||
("digits", json!(v.digits)),
|
||||
@@ -578,6 +579,10 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma
|
||||
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
|
||||
}
|
||||
}
|
||||
let (key, lo, hi) = ("tsume", 0.0, vectorcraft_doc::text::MAX_TSUME);
|
||||
if changed(key) && !(lo..=hi).contains(&st.tsume) {
|
||||
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
|
||||
}
|
||||
let lines = vectorcraft_doc::text::WARICHU_LINES;
|
||||
if changed("warichuLines") && !lines.contains(&st.warichu_lines) {
|
||||
return Err(bad(&c, format!("`warichuLines` must be a whole number from {} to {}", lines.start(), lines.end())));
|
||||
@@ -1075,12 +1080,12 @@ fn unused(s: &mut Session, kind: Kind) -> Result<Value> {
|
||||
|
||||
/// The styles of `kind` in `src` that load, with their source names so that art in the file keeps
|
||||
/// referring to them: not the Normal style, and not one whose attributes don't read, whose sizes,
|
||||
/// scales, leading, shifts, Insert Aki, Warichu Settings or stroke width are out of the range `charStyle.new` takes, whose
|
||||
/// scales, leading, shifts, Insert Aki, Tsume, Warichu Settings or stroke width are out of the range `charStyle.new` takes, whose
|
||||
/// indents, spacing, Hyphenation or Justification options or tab stops are out of the range
|
||||
/// `paraStyle.new` takes, or whose name is empty, which are skipped. → (the styles, the names in
|
||||
/// `src` of those skipped)
|
||||
fn loadable(src: &Document, kind: Kind) -> (Vec<TextStyleDef>, Vec<String>) {
|
||||
const RANGED: [&str; 21] = [
|
||||
const RANGED: [&str; 22] = [
|
||||
"size",
|
||||
"h_scale",
|
||||
"v_scale",
|
||||
@@ -1088,6 +1093,7 @@ fn loadable(src: &Document, kind: Kind) -> (Vec<TextStyleDef>, Vec<String>) {
|
||||
"baseline_shift",
|
||||
"akiLeft",
|
||||
"akiRight",
|
||||
"tsume",
|
||||
"tcyUpDown",
|
||||
"tcyLeftRight",
|
||||
"warichuLines",
|
||||
|
||||
@@ -397,6 +397,8 @@ fn character_style_dimensions_are_checked_before_a_definition_changes() {
|
||||
json!({"tcyLeftRight": -1296.1}),
|
||||
json!({"akiLeft": -0.1}),
|
||||
json!({"akiRight": 1000.1}),
|
||||
json!({"tsume": -0.1}),
|
||||
json!({"tsume": 100.1}),
|
||||
] {
|
||||
let key = attrs.as_object().unwrap().keys().next().unwrap();
|
||||
for cmd in ["charStyle.edit", "charStyle.setAttrs", "charStyle.new"] {
|
||||
@@ -419,7 +421,8 @@ fn character_style_dimensions_are_checked_before_a_definition_changes() {
|
||||
"h_scale": 1.0, "v_scale": 10000.0,
|
||||
"baseline_shift": -1296.0,
|
||||
"tcyUpDown": 1296.0, "tcyLeftRight": -1296.0,
|
||||
"akiLeft": 0.0, "akiRight": 1000.0
|
||||
"akiLeft": 0.0, "akiRight": 1000.0,
|
||||
"tsume": 100.0
|
||||
}}),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
@@ -400,6 +400,8 @@ thread_local! {
|
||||
/// Tests: how many times [`story_of`] and [`ThreadIndex::of`] went through the document's
|
||||
/// threads on this thread.
|
||||
static THREAD_SCANS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// Tests: how many times [`story_in`] went through a thread's frames on this thread.
|
||||
static STORY_BUILDS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Tests: how many times [`story_of`] and [`ThreadIndex::of`] have gone through the document's
|
||||
@@ -409,6 +411,12 @@ pub(crate) fn thread_scans() -> usize {
|
||||
THREAD_SCANS.with(std::cell::Cell::get)
|
||||
}
|
||||
|
||||
/// Tests: how many times [`story_in`] has gone through a thread's frames on this thread.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn story_builds() -> usize {
|
||||
STORY_BUILDS.with(std::cell::Cell::get)
|
||||
}
|
||||
|
||||
/// The frames of the thread that `id` is a frame of, in thread order, each area type or type on a
|
||||
/// path; empty when `id` is in no thread or the thread has fewer than two such frames.
|
||||
pub(crate) fn story_of(d: &Document, id: NodeId) -> Vec<NodeId> {
|
||||
@@ -420,6 +428,8 @@ pub(crate) fn story_of(d: &Document, id: NodeId) -> Vec<NodeId> {
|
||||
|
||||
/// [`story_of`] for `id` in `thread`, the first of the document's threads that lists it.
|
||||
pub(crate) fn story_in(d: &Document, thread: &[NodeId], id: NodeId) -> Vec<NodeId> {
|
||||
#[cfg(test)]
|
||||
STORY_BUILDS.with(|c| c.set(c.get() + 1));
|
||||
let frames: Vec<NodeId> = thread.iter().copied().filter(|f| text_of(d, *f).is_some()).collect();
|
||||
if frames.len() >= 2 && frames.contains(&id) { frames } else { vec![] }
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Vertical",
|
||||
["Type", "Orientation"],
|
||||
None,
|
||||
"{ids?|id?} set vertical writing for the selected type and every frame of its threads → {vertical, ids}",
|
||||
"{ids?|id?} set vertical writing for the selected type and every frame of its threads; no undo step when every object is already vertical → {vertical, ids}",
|
||||
has_selection,
|
||||
|s, p| orientation(s, p, true)
|
||||
),
|
||||
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Horizontal",
|
||||
["Type", "Orientation"],
|
||||
None,
|
||||
"{ids?|id?} set horizontal writing for the selected type and every frame of its threads → {vertical, ids}",
|
||||
"{ids?|id?} set horizontal writing for the selected type and every frame of its threads; no undo step when every object is already horizontal → {vertical, ids}",
|
||||
has_selection,
|
||||
|s, p| orientation(s, p, false)
|
||||
),
|
||||
@@ -59,7 +59,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Optical Margin Alignment",
|
||||
["Type"],
|
||||
None,
|
||||
"{ids?|id?, on?: bool} turn Optical Margin Alignment on or off for the selected type and every frame of its threads (on omitted: the opposite of the first object's setting): in every paragraph of point and area type, quotation marks, hyphens, full stops and commas at a line's start or end hang wholly outside the margin there; asterisks, tildes, ellipses, en and em dashes, colons and semicolons hang by half; and A, V, W, Y, v, w and y hang by a tenth of their advance; a left-aligned line hangs at its left margin, a right-aligned line hangs at its right margin, and centered and justified lines hang at both; Auto aligns a right-to-left line at its right; type on a path hangs at the start bracket when its line is placed there, hangs at the end bracket when the line is placed there, and hangs at both when it is centered → {on, ids}",
|
||||
"{ids?|id?, on?: bool} turn Optical Margin Alignment on or off for the selected type and every frame of its threads (on omitted: the opposite of the first object's setting): in every paragraph of point and area type, quotation marks, hyphens, full stops and commas at a line's start or end hang wholly outside the margin there; asterisks, tildes, ellipses, en and em dashes, colons and semicolons hang by half; and A, V, W, Y, v, w and y hang by a tenth of their advance; a left-aligned line hangs at its left margin, a right-aligned line hangs at its right margin, and centered and justified lines hang at both; Auto aligns a right-to-left line at its right; type on a path hangs at the start bracket when its line is placed there, hangs at the end bracket when the line is placed there, and hangs at both when it is centered; no undo step when every object already has the setting → {on, ids}",
|
||||
has_selection,
|
||||
optical_margin_alignment
|
||||
),
|
||||
@@ -68,7 +68,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"System Layout",
|
||||
[],
|
||||
None,
|
||||
"{on?: bool} turn System Layout on or off for the document (on omitted: the opposite of the document's setting) and every text object in it. On, each character that takes any space advances by a whole number of points, at least one, so small type does not run together; a character with no width stays at none. Off (the default, and what a document from before it reads as), spacing uses fractions of a point. New point, area and path type inherits the document's setting → {on}",
|
||||
"{on?: bool} turn System Layout on or off for the document (on omitted: the opposite of the document's setting) and every text object in it. On, each character that takes any space advances by a whole number of points, at least one, so small type does not run together; a character with no width stays at none. Off (the default, and what a document from before it reads as), spacing uses fractions of a point. New point, area and path type inherits the document's setting. No undo step when the document and every text object already have the setting → {on}",
|
||||
has_doc,
|
||||
system_layout
|
||||
),
|
||||
@@ -77,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Fractional Widths",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?, on?: bool} turn Fractional Widths on or off for the selected type and every frame of its threads (on omitted: the opposite of the first object's setting). On (the default, and what a document from before it reads as), spacing between characters uses fractions of a point. Off, each character that takes any space advances by a whole number of points, at least one, so small type does not run together; a character with no width stays at none. The setting is the whole type object, not a range of characters → {on, ids}",
|
||||
"{ids?|id?, on?: bool} turn Fractional Widths on or off for the selected type and every frame of its threads (on omitted: the opposite of the first object's setting). On (the default, and what a document from before it reads as), spacing between characters uses fractions of a point. Off, each character that takes any space advances by a whole number of points, at least one, so small type does not run together; a character with no width stays at none. The setting is the whole type object, not a range of characters. No undo step when every object already has the setting → {on, ids}",
|
||||
has_selection,
|
||||
fractional_widths
|
||||
),
|
||||
@@ -86,7 +86,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Set Text",
|
||||
[],
|
||||
None,
|
||||
"{id?|ids?, text} replace the contents of text objects (keeps the first run's style) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits)}",
|
||||
"{id?|ids?, text} replace the contents of text objects (keeps the first run's style); no undo step when no object changes (each already has the text in one style, every paragraph with the first one's attributes, and no ruby) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits)}",
|
||||
has_doc,
|
||||
set_text
|
||||
),
|
||||
@@ -104,7 +104,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reshape Type Area",
|
||||
[],
|
||||
None,
|
||||
"{id, anchors: [[subpath, anchor]…], dx, dy} or {items: [{id, anchors}…], dx, dy} move anchors of area type's frame (the type area) by dx, dy points, with their handles; the text reflows at its size, through its thread too (what Direct Selection does dragging a frame corner or edge, or the frame anchors its marquee selected, and the arrow keys nudging those); with items, every listed frame moves in one step",
|
||||
"{id, anchors: [[subpath, anchor]…], dx, dy} or {items: [{id, anchors}…], dx, dy} move anchors of area type's frame (the type area) by dx, dy points, with their handles; the text reflows at its size, through its thread too (what Direct Selection does dragging a frame corner or edge, or the frame anchors its marquee selected, and the arrow keys nudging those); with items, every listed frame moves in one step; no undo step when no frame changes (dx and dy both 0)",
|
||||
has_doc,
|
||||
reshape_area
|
||||
),
|
||||
@@ -113,7 +113,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reshape Type Path",
|
||||
[],
|
||||
None,
|
||||
"{id, anchors: [[subpath, anchor]…], dx, dy} move anchors of type on a path's path by dx, dy points, with their handles; the start and end brackets keep their fractions of the path and the text reflows along it (what Direct Selection does dragging an anchor of the path)",
|
||||
"{id, anchors: [[subpath, anchor]…], dx, dy} move anchors of type on a path's path by dx, dy points, with their handles; the start and end brackets keep their fractions of the path and the text reflows along it (what Direct Selection does dragging an anchor of the path); no undo step when the path does not change (dx and dy both 0)",
|
||||
has_doc,
|
||||
reshape_path
|
||||
),
|
||||
@@ -122,7 +122,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Type Path Handle",
|
||||
[],
|
||||
None,
|
||||
"{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool} move a direction handle of an anchor of type on a path's path to (x, y), as path.setHandle moves a path's (independent: that side only, the anchor becomes a corner); the start and end brackets keep their fractions of the path and the text reflows along it (what Direct Selection does dragging a handle of the path)",
|
||||
"{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool} move a direction handle of an anchor of type on a path's path to (x, y), as path.setHandle moves a path's (independent: that side only, the anchor becomes a corner); the start and end brackets keep their fractions of the path and the text reflows along it (what Direct Selection does dragging a handle of the path); no undo step when the handle is already there and the path does not change",
|
||||
has_doc,
|
||||
set_path_handle
|
||||
),
|
||||
@@ -131,7 +131,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Fit Headline",
|
||||
["Type"],
|
||||
None,
|
||||
"{ids?|id?} track the first line of area type so it fills the frame width → {tracking}",
|
||||
"{ids?|id?} track the first line of area type so it fills the frame width; no undo step when the first line already has that tracking → {tracking}",
|
||||
has_selection,
|
||||
fit_headline
|
||||
),
|
||||
@@ -140,7 +140,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Character",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour|\"none\", stroke?: colour|\"none\" (characters without a stroke weight get 1 pt; #rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt (the character stroke's weight, in document points as stroke.set), features?: [\"dlig\", \"-liga\", \"salt=2\", …] OpenType (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}",
|
||||
"{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour|\"none\", stroke?: colour|\"none\" (characters without a stroke weight get 1 pt; #rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt (the character stroke's weight, in document points as stroke.set), features?: [\"dlig\", \"-liga\", \"salt=2\", …] OpenType (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text; no undo step when no character, paragraph or graph label style changes) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}",
|
||||
has_doc,
|
||||
set_style
|
||||
),
|
||||
@@ -149,7 +149,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Ruby…",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?, start?: byte, end?: byte, text?: reading, position?: above|below (vertical type: right|left), align?: start|center|end, size?: 1–100 (percent of the base text's size, default 50), overhang?: bool (default true), remove?: bool} set the ruby (furigana) over the selected text's bytes in `start..end` (without them: all its text): the reading over the base characters, above them in horizontal type and right of them in vertical type; `remove` takes the ruby off the range instead → {ids, ruby: [{start, end, text, position, align, sizePercent, overhang}…] (the first object's ruby)}",
|
||||
"{ids?|id?, start?: byte, end?: byte, text?: reading, position?: above|below (vertical type: right|left), align?: start|center|end, size?: 1–100 (percent of the base text's size, default 50), overhang?: bool (default true), remove?: bool} set the ruby (furigana) over the selected text's bytes in `start..end` (without them: all its text): the reading over the base characters, above them in horizontal type and right of them in vertical type; `remove` takes the ruby off the range instead; no undo step when the ruby does not change (the same reading and options again, or `remove` where there is none) → {ids, ruby: [{start, end, text, position, align, sizePercent, overhang}…] (the first object's ruby)}",
|
||||
has_selection,
|
||||
ruby
|
||||
),
|
||||
@@ -157,24 +157,30 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}
|
||||
|
||||
/// Type › Type Orientation: set vertical or horizontal writing on every selected text object and
|
||||
/// every frame of their threads, in one undo step.
|
||||
/// every frame of their threads, in one undo step (none when nothing changes).
|
||||
fn orientation(s: &mut Session, p: &Value, vertical: bool) -> Result<Value> {
|
||||
let ids = super::threads::with_threads(&s.doc()?.doc, &text_targets(s, p, "Text Orientation")?);
|
||||
s.edit("Text Orientation", |d, _| {
|
||||
// When every object already has the orientation, the document and its undo history stay as they are.
|
||||
super::colorcmds::edit_if_changed(s, "Text Orientation", |_, d| {
|
||||
let mut changed = false;
|
||||
for id in &ids {
|
||||
let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else {
|
||||
return Err(EngineError::NoNode(*id));
|
||||
};
|
||||
t.vertical = vertical;
|
||||
refresh_bounds(t);
|
||||
if t.vertical != vertical {
|
||||
t.vertical = vertical;
|
||||
refresh_bounds(t);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
Ok(((), changed))
|
||||
})?;
|
||||
Ok(json!({"vertical": vertical, "ids": ids.iter().map(|id| id.0).collect::<Vec<_>>()}))
|
||||
}
|
||||
|
||||
/// Type › Optical Margin Alignment: set `on` (without it, the opposite of the first object's
|
||||
/// setting) on every selected text object and every frame of their threads, in one undo step.
|
||||
/// setting) on every selected text object and every frame of their threads, in one undo step
|
||||
/// (none when nothing changes).
|
||||
fn optical_margin_alignment(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = super::threads::with_threads(&s.doc()?.doc, &text_targets(s, p, "Optical Margin Alignment")?);
|
||||
let first = ids.first().and_then(|id| match s.doc().ok()?.doc.node(*id).map(|n| &n.kind) {
|
||||
@@ -182,29 +188,38 @@ fn optical_margin_alignment(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
_ => None,
|
||||
});
|
||||
let on = switch_or(p, "on", !first.unwrap_or(false), "type.opticalMarginAlignment")?;
|
||||
s.edit("Optical Margin Alignment", |d, _| {
|
||||
// When every object already has the setting, the document and its undo history stay as they are.
|
||||
super::colorcmds::edit_if_changed(s, "Optical Margin Alignment", |_, d| {
|
||||
let mut changed = false;
|
||||
for id in &ids {
|
||||
let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else {
|
||||
return Err(EngineError::NoNode(*id));
|
||||
};
|
||||
t.optical_margin = on;
|
||||
refresh_bounds(t);
|
||||
if t.optical_margin != on {
|
||||
t.optical_margin = on;
|
||||
refresh_bounds(t);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
Ok(((), changed))
|
||||
})?;
|
||||
Ok(json!({"on": on, "ids": ids.iter().map(|id| id.0).collect::<Vec<_>>()}))
|
||||
}
|
||||
|
||||
/// Character panel menu › System Layout: set `on` (without it, the opposite of the document's
|
||||
/// setting) on the document and every text object, in one undo step. Off is the default.
|
||||
/// setting) on the document and every text object, in one undo step (none when nothing changes).
|
||||
/// Off is the default.
|
||||
fn system_layout(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let current = s.doc()?.doc.setup.system_layout;
|
||||
let on = switch_or(p, "on", !current, "type.systemLayout")?;
|
||||
s.edit("System Layout", |d, _| {
|
||||
// When the document and every text object already have the setting, the document and its undo
|
||||
// history stay as they are.
|
||||
super::colorcmds::edit_if_changed(s, "System Layout", |_, d| {
|
||||
let mut changed = d.setup.system_layout != on;
|
||||
d.setup.system_layout = on;
|
||||
let mut ids = vec![];
|
||||
d.walk(|n| {
|
||||
if matches!(n.kind, NodeKind::Text(_)) {
|
||||
if matches!(&n.kind, NodeKind::Text(t) if t.system_layout != on) {
|
||||
ids.push(n.id);
|
||||
}
|
||||
});
|
||||
@@ -214,15 +229,16 @@ fn system_layout(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
t.system_layout = on;
|
||||
refresh_bounds(t);
|
||||
changed = true;
|
||||
}
|
||||
Ok(())
|
||||
Ok(((), changed))
|
||||
})?;
|
||||
Ok(json!({ "on": on }))
|
||||
}
|
||||
|
||||
/// Character panel menu › Fractional Widths: set `on` (without it, the opposite of the first
|
||||
/// object's setting) on every selected text object and every frame of their threads, in one undo
|
||||
/// step. On is the default.
|
||||
/// step (none when nothing changes). On is the default.
|
||||
fn fractional_widths(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = super::threads::with_threads(&s.doc()?.doc, &text_targets(s, p, "Fractional Widths")?);
|
||||
let first = ids.first().and_then(|id| match s.doc().ok()?.doc.node(*id).map(|n| &n.kind) {
|
||||
@@ -230,22 +246,27 @@ fn fractional_widths(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
_ => None,
|
||||
});
|
||||
let on = switch_or(p, "on", !first.unwrap_or(true), "type.fractionalWidths")?;
|
||||
s.edit("Fractional Widths", |d, _| {
|
||||
// When every object already has the setting, the document and its undo history stay as they are.
|
||||
super::colorcmds::edit_if_changed(s, "Fractional Widths", |_, d| {
|
||||
let mut changed = false;
|
||||
for id in &ids {
|
||||
let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else {
|
||||
return Err(EngineError::NoNode(*id));
|
||||
};
|
||||
t.fractional_widths = on;
|
||||
refresh_bounds(t);
|
||||
if t.fractional_widths != on {
|
||||
t.fractional_widths = on;
|
||||
refresh_bounds(t);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
Ok(((), changed))
|
||||
})?;
|
||||
Ok(json!({"on": on, "ids": ids.iter().map(|id| id.0).collect::<Vec<_>>()}))
|
||||
}
|
||||
|
||||
/// Type › Ruby: set or remove the ruby (furigana) over a byte range of the selected type in one
|
||||
/// undo step. Without `start`/`end` the range is all the text; a new reading replaces the ruby
|
||||
/// over the range. The reply lists the first object's ruby (start/end in bytes of its plain text).
|
||||
/// undo step (none when nothing changes). Without `start`/`end` the range is all the text; a new
|
||||
/// reading replaces the ruby over the range. The reply lists the first object's ruby (start/end in bytes of its plain text).
|
||||
fn ruby(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "type.ruby";
|
||||
let ids = text_targets(s, p, C)?;
|
||||
@@ -272,7 +293,8 @@ fn ruby(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let overhang = switch_or(p, "overhang", true, C)?;
|
||||
let mut first: Option<Value> = None;
|
||||
s.edit("Ruby", |d, _| {
|
||||
// The same reading again, or a removal where there is no ruby, is no undo step.
|
||||
edit_if_nodes_changed(s, "Ruby", &ids, |d| {
|
||||
for id in &ids {
|
||||
let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else {
|
||||
return Err(EngineError::NoNode(*id));
|
||||
@@ -299,7 +321,7 @@ fn ruby(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
first = Some(serde_json::to_value(&t.ruby).unwrap_or(Value::Null));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
Ok(((), false))
|
||||
})?;
|
||||
Ok(json!({"ids": ids.iter().map(|id| id.0).collect::<Vec<_>>(), "ruby": first.unwrap_or(Value::Null)}))
|
||||
}
|
||||
@@ -737,6 +759,19 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }))
|
||||
}
|
||||
|
||||
/// [`Session::edit`] for a type command that may set what the type already has: `f` runs on a
|
||||
/// copy of the document, and it becomes an undo step only when one of the objects `ids` differs
|
||||
/// afterwards or `f` returns true for a change of its own elsewhere (a graph's kept label styles).
|
||||
/// When nothing changed, the document, its undo and redo steps and its saved state stay as they
|
||||
/// were. Only the objects are compared, not the whole document, whose embedded images can be large.
|
||||
fn edit_if_nodes_changed<T>(s: &mut Session, label: &str, ids: &[NodeId], f: impl FnOnce(&mut Document) -> Result<(T, bool)>) -> Result<T> {
|
||||
super::colorcmds::edit_if_changed(s, label, |before, d| {
|
||||
let (v, other) = f(d)?;
|
||||
let changed = other || ids.iter().any(|id| before.node(*id) != d.node(*id));
|
||||
Ok((v, changed))
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn text_targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
|
||||
let ids = targets(s, p)?;
|
||||
let t = text_ids(&s.doc()?.doc, &ids);
|
||||
@@ -831,7 +866,8 @@ pub(crate) fn style_chars(t: &mut TextObject, range: Option<TextRange>, mut f: i
|
||||
fn set_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let text = str_param(p, "text").ok_or_else(|| bad("text.setText", "missing `text`"))?.to_string();
|
||||
let ids = text_targets(s, p, "text.setText")?;
|
||||
s.edit("Typing", |d, _| {
|
||||
// The text the type already has is no undo step.
|
||||
edit_if_nodes_changed(s, "Typing", &ids, |d| {
|
||||
for id in &ids {
|
||||
let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue };
|
||||
let style = t.first_style();
|
||||
@@ -842,7 +878,7 @@ fn set_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
t.ruby.clear();
|
||||
refresh_bounds(t);
|
||||
}
|
||||
Ok(())
|
||||
Ok(((), false))
|
||||
})?;
|
||||
Ok(with_overflow(s, &ids, json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() })))
|
||||
}
|
||||
@@ -915,7 +951,8 @@ fn set_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let protect = s.prefs.missing_glyph_protection && (font.is_some() || style.is_some());
|
||||
// The fonts the styled characters are set in, for the warning.
|
||||
let mut set = std::collections::BTreeSet::new();
|
||||
s.edit("Character", |d, _| {
|
||||
// Attributes the characters already have are no undo step.
|
||||
edit_if_nodes_changed(s, "Character", &ids, |d| {
|
||||
for id in &ids {
|
||||
let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue };
|
||||
let size = size.map(|v| local_type_value(t, v, (0.1, 1296.0), false, C)).transpose()?;
|
||||
@@ -990,8 +1027,9 @@ fn set_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// Graph labels keep a change made to all of their text through the graph being drawn again (sizes as given,
|
||||
// not in a scaled label's own units).
|
||||
let mut labels_changed = false;
|
||||
if range.is_none() {
|
||||
super::graph::capture_label_styles(d, &ids, &|st| {
|
||||
labels_changed = super::graph::capture_label_styles(d, &ids, &|st| {
|
||||
if let Some(f) = &font {
|
||||
st.font_family = f.clone();
|
||||
st.font_version = None;
|
||||
@@ -1034,7 +1072,7 @@ fn set_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
Ok(((), labels_changed))
|
||||
})?;
|
||||
let mut out = with_overflow(s, &ids, json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }));
|
||||
if let Some(w) = super::fonts::set_font_warning(set) {
|
||||
@@ -1332,14 +1370,16 @@ fn reshape_area(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
items.push((id, refs));
|
||||
}
|
||||
let d = Vec2::new(f64_req(p, "dx", C)?, f64_req(p, "dy", C)?);
|
||||
s.edit("Reshape Type Area", |doc, _| {
|
||||
// Anchors moved by no distance are no undo step.
|
||||
let ids: Vec<NodeId> = items.iter().map(|(id, _)| *id).collect();
|
||||
edit_if_nodes_changed(s, "Reshape Type Area", &ids, |doc| {
|
||||
for (id, refs) in &items {
|
||||
let Some(NodeKind::Text(t)) = doc.node_mut(*id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(*id)) };
|
||||
if !reshape_area_with(t, |t| t.move_area_anchors(refs, d)) {
|
||||
return Err(bad(C, "no such frame anchor, or the frame would reach past the canvas"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
Ok(((), false))
|
||||
})?;
|
||||
ok()
|
||||
}
|
||||
@@ -1359,7 +1399,8 @@ fn reshape_path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !on_path || node.is_some_and(|n| n.extras().perspective.is_some()) {
|
||||
return Err(bad(C, "not type on a path outside perspective"));
|
||||
}
|
||||
s.edit("Reshape Type Path", |doc, _| {
|
||||
// Anchors moved by no distance are no undo step.
|
||||
edit_if_nodes_changed(s, "Reshape Type Path", &[id], |doc| {
|
||||
let Some(NodeKind::Text(t)) = doc.node_mut(id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(id)) };
|
||||
let before = t.kind.clone();
|
||||
let within = |t: &TextObject| {
|
||||
@@ -1370,7 +1411,7 @@ fn reshape_path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "no such path anchor, or the path would reach past the canvas"));
|
||||
}
|
||||
refresh_bounds(t);
|
||||
Ok(())
|
||||
Ok(((), false))
|
||||
})?;
|
||||
ok()
|
||||
}
|
||||
@@ -1388,7 +1429,8 @@ fn set_path_handle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !on_path || node.is_some_and(|n| n.extras().perspective.is_some()) {
|
||||
return Err(bad(C, "not type on a path outside perspective"));
|
||||
}
|
||||
s.edit("Reshape Type Path", |doc, _| {
|
||||
// A handle moved to where it is is no undo step.
|
||||
edit_if_nodes_changed(s, "Reshape Type Path", &[id], |doc| {
|
||||
let Some(NodeKind::Text(t)) = doc.node_mut(id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(id)) };
|
||||
let before = t.kind.clone();
|
||||
let within = |t: &TextObject| {
|
||||
@@ -1399,7 +1441,7 @@ fn set_path_handle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "no such path anchor, or the path would reach past the canvas"));
|
||||
}
|
||||
refresh_bounds(t);
|
||||
Ok(())
|
||||
Ok(((), false))
|
||||
})?;
|
||||
ok()
|
||||
}
|
||||
@@ -1410,6 +1452,8 @@ mod block;
|
||||
pub(crate) use block::needed_room;
|
||||
#[cfg(test)]
|
||||
mod block_tests;
|
||||
#[cfg(test)]
|
||||
mod noop_tests;
|
||||
|
||||
/// Width of the first line and of the space it can fill, with `tracking` on the first paragraph.
|
||||
/// The third value is where the first line ends in the plain text.
|
||||
@@ -1451,7 +1495,9 @@ fn fit_headline(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
plans.push((*id, (lo * 10.0).floor() / 10.0));
|
||||
}
|
||||
let first = plans.first().map(|p| p.1).ok_or_else(|| bad(C, "select area type whose first line can fit its frame"))?;
|
||||
s.edit("Fit Headline", |d, _| {
|
||||
// A headline that already has its fitted tracking is no undo step.
|
||||
let fitted: Vec<NodeId> = plans.iter().map(|(id, _)| *id).collect();
|
||||
edit_if_nodes_changed(s, "Fit Headline", &fitted, |d| {
|
||||
for (id, tr) in &plans {
|
||||
if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) {
|
||||
let end = t.plain_text().find('\n').unwrap_or(usize::MAX).min(vectorcraft_text::edit::runs_len(&t.runs));
|
||||
@@ -1459,7 +1505,7 @@ fn fit_headline(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
refresh_bounds(t);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
Ok(((), false))
|
||||
})?;
|
||||
Ok(json!({ "tracking": first }))
|
||||
}
|
||||
|
||||
@@ -199,8 +199,11 @@ fn optical_margin_alignment_is_set_per_object_and_saved_only_when_on() {
|
||||
assert!(left(&s) < inside - 5.0, "{} {inside}", left(&s));
|
||||
assert_eq!(serde_json::to_value(text(&s)).unwrap()["opticalMarginAlignment"], true);
|
||||
// `on` sets it; without `on` it toggles.
|
||||
// Setting the value the type already has: no undo step.
|
||||
let n = s.doc().unwrap().history.undo.len();
|
||||
assert_eq!(s.execute("type.opticalMarginAlignment", &json!({"on": true})).unwrap()["on"], true);
|
||||
assert!(text(&s).optical_margin);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), n);
|
||||
assert_eq!(s.execute("type.opticalMarginAlignment", &json!({})).unwrap()["on"], false);
|
||||
assert!(!text(&s).optical_margin);
|
||||
assert_eq!(left(&s), inside);
|
||||
@@ -247,6 +250,10 @@ fn system_layout_sets_the_document_and_every_text_object() {
|
||||
assert!(fractional.iter().zip(&whole).any(|(a, b)| (a - b).abs() > 0.05), "{fractional:?} {whole:?}");
|
||||
assert_eq!(serde_json::to_value(setup(&s)).unwrap()["systemLayout"], true);
|
||||
assert_eq!(serde_json::to_value(text(&s, id)).unwrap()["systemLayout"], true);
|
||||
// Setting the value the document and its type already have: no undo step.
|
||||
let n = s.doc().unwrap().history.undo.len();
|
||||
assert_eq!(s.execute("type.systemLayout", &json!({"on": true})).unwrap()["on"], true);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), n);
|
||||
// New type inherits the document's setting.
|
||||
let made = s.execute("text.create", &json!({"x": 10, "y": 120, "text": "Z"})).unwrap()["id"].as_u64().unwrap();
|
||||
assert!(text(&s, made).system_layout);
|
||||
@@ -305,6 +312,10 @@ fn fractional_widths_is_set_per_object_and_saved_only_when_off() {
|
||||
assert!(text(&s).fractional_widths);
|
||||
assert_eq!(s.execute("type.fractionalWidths", &json!({"on": false})).unwrap()["on"], false);
|
||||
assert!(!text(&s).fractional_widths);
|
||||
// Setting the value the type already has: no undo step.
|
||||
let n = s.doc().unwrap().history.undo.len();
|
||||
assert_eq!(s.execute("type.fractionalWidths", &json!({"on": false})).unwrap()["on"], false);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), n);
|
||||
// One undo step.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(text(&s).fractional_widths);
|
||||
@@ -1821,6 +1832,61 @@ fn insert_aki_is_a_character_attribute_set_one_side_at_a_time() {
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step for a refused call");
|
||||
}
|
||||
|
||||
/// Tsume (Character panel, East Asian options): a character attribute in percent, 0 by default
|
||||
/// and saved only when not 0. Both commands set it in one undo step, a call that gives the value
|
||||
/// the text already has records none, and a value that is not a number or lies outside 0 to 100 is
|
||||
/// refused, naming the key, before anything changes; a character style captured from the
|
||||
/// characters carries it.
|
||||
#[test]
|
||||
fn tsume_is_a_character_attribute() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "(日本)"})).unwrap()["id"].as_u64().unwrap();
|
||||
let runs = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => t.runs.clone(),
|
||||
_ => panic!("text"),
|
||||
};
|
||||
let tsume = |s: &Session| runs(s).iter().map(|r| (r.text.clone(), r.style.tsume)).collect::<Vec<_>>();
|
||||
let saved = serde_json::to_value(&runs(&s)[0].style).unwrap();
|
||||
assert!(saved.get("tsume").is_none());
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"tsume": 50})).unwrap();
|
||||
assert_eq!(tsume(&s), [("(日本)".to_string(), 50.0)]);
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("text.setFormat", &json!({"tsume": 50})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step without a change");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(tsume(&s), [("(日本)".to_string(), 0.0)], "one undo step");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(tsume(&s), [("(日本)".to_string(), 50.0)]);
|
||||
|
||||
let paren = "(".len();
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": paren, "tsume": 100})).unwrap();
|
||||
assert_eq!(tsume(&s), [("(".to_string(), 100.0), ("日本)".to_string(), 50.0)]);
|
||||
let saved = serde_json::to_value(&runs(&s)[0].style).unwrap();
|
||||
assert_eq!(saved["tsume"], json!(100.0));
|
||||
let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
|
||||
let NodeKind::Text(t) = &back.node(NodeId(id)).unwrap().kind else { panic!("text") };
|
||||
let reopened: Vec<_> = t.runs.iter().map(|r| (r.text.clone(), r.style.tsume)).collect();
|
||||
assert_eq!(reopened, tsume(&s));
|
||||
let attrs = super::super::textstyles::char_attrs(&runs(&s)[0].style);
|
||||
assert_eq!(attrs["tsume"], json!(100.0));
|
||||
|
||||
let before = tsume(&s);
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
for (cmd, p, want) in [
|
||||
("text.setFormat", json!({"tsume": "50"}), "`tsume` must be a number"),
|
||||
("text.setFormat", json!({"tsume": -1}), "`tsume` must be from 0 to 100"),
|
||||
("text.setRangeStyle", json!({"id": id, "tsume": true}), "`tsume` must be a number"),
|
||||
("text.setRangeStyle", json!({"id": id, "start": 0, "end": paren, "tsume": 100.5}), "`tsume` must be from 0 to 100"),
|
||||
] {
|
||||
let e = s.execute(cmd, &p).unwrap_err();
|
||||
assert!(matches!(&e, EngineError::BadParams { msg, .. } if msg == want), "{cmd} {p}: {e}");
|
||||
}
|
||||
assert_eq!(tsume(&s), before);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step for a refused call");
|
||||
}
|
||||
|
||||
/// Standard Vertical Roman Alignment (Character panel menu, East Asian options): a character
|
||||
/// attribute, off by default and saved only when on. Documents written before it read as off; a
|
||||
/// character style captured from the characters carries it.
|
||||
@@ -2276,8 +2342,17 @@ fn vertical_point_type_keeps_its_anchor_on_the_column_centre_line() {
|
||||
let tall = bounds(&s);
|
||||
assert!(tall.height() > tall.width(), "{tall:?}");
|
||||
assert!((tall.center().x - 100.0).abs() < 6.0, "the anchor stays on the column's centre line: {tall:?}");
|
||||
// Vertical type set vertical again: no undo step.
|
||||
let n = s.doc().unwrap().history.undo.len();
|
||||
s.execute("type.orientation.vertical", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), n);
|
||||
assert_eq!(bounds(&s), tall);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(bounds(&s), wide);
|
||||
// Horizontal type set horizontal: no undo step either.
|
||||
let n = s.doc().unwrap().history.undo.len();
|
||||
s.execute("type.orientation.horizontal", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), n);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
use super::*;
|
||||
|
||||
/// The document and the number of undo steps, to compare before and after a command that sets
|
||||
/// what the type already has.
|
||||
fn state(s: &Session) -> (std::sync::Arc<Document>, usize) {
|
||||
let st = s.doc().unwrap();
|
||||
(st.doc.clone(), st.history.undo.len())
|
||||
}
|
||||
|
||||
/// Assert that `cmd` with `p` leaves the document and its undo history as they were.
|
||||
fn records_nothing(s: &mut Session, cmd: &str, p: Value) {
|
||||
let before = state(s);
|
||||
s.execute(cmd, &p).unwrap();
|
||||
let after = state(s);
|
||||
assert!(*after.0 == *before.0, "{cmd} {p} changed the document");
|
||||
assert_eq!(after.1, before.1, "{cmd} {p} recorded an undo step");
|
||||
}
|
||||
|
||||
/// Assert that `cmd` with `p` changes the document in exactly one undo step.
|
||||
fn records_one_step(s: &mut Session, cmd: &str, p: Value) {
|
||||
let before = state(s);
|
||||
s.execute(cmd, &p).unwrap();
|
||||
let after = state(s);
|
||||
assert!(*after.0 != *before.0, "{cmd} {p} left the document as it was");
|
||||
assert_eq!(after.1, before.1 + 1, "{cmd} {p} did not record one undo step");
|
||||
}
|
||||
|
||||
fn session_with(text: &str, area: Option<Value>) -> (Session, u64) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
|
||||
let mut p = json!({"x": 10, "y": 20, "text": text, "size": 24});
|
||||
if let Some(a) = area {
|
||||
p["area"] = a;
|
||||
}
|
||||
let id = s.execute("text.create", &p).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
(s, id)
|
||||
}
|
||||
|
||||
/// Ruby set again with the same reading and options, or removed where there is none, records no
|
||||
/// undo step; a step that does change the ruby still undoes in one.
|
||||
#[test]
|
||||
fn ruby_that_changes_nothing_records_no_undo_step() {
|
||||
let (mut s, id) = session_with("漢字です", None);
|
||||
records_nothing(&mut s, "type.ruby", json!({"remove": true}));
|
||||
let p = json!({"text": "かんじ", "start": 0, "end": 6, "position": "below", "size": 60});
|
||||
records_one_step(&mut s, "type.ruby", p.clone());
|
||||
records_nothing(&mut s, "type.ruby", p);
|
||||
s.execute("type.ruby", &json!({"remove": true})).unwrap();
|
||||
records_nothing(&mut s, "type.ruby", json!({"remove": true, "start": 0, "end": 6}));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let NodeKind::Text(t) = &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind else { panic!("text") };
|
||||
assert_eq!(t.ruby.len(), 1, "undo brings the ruby back");
|
||||
}
|
||||
|
||||
/// `text.setStyle` (the Character panel) given the attributes the characters already have
|
||||
/// records no undo step, with a range too.
|
||||
#[test]
|
||||
fn character_attributes_already_set_record_no_undo_step() {
|
||||
let (mut s, _) = session_with("Headline", None);
|
||||
records_nothing(&mut s, "text.setStyle", json!({"size": 24}));
|
||||
s.execute("text.setStyle", &json!({"tracking": 50, "fill": "#ff0000"})).unwrap();
|
||||
records_nothing(&mut s, "text.setStyle", json!({"tracking": 50, "fill": "#ff0000"}));
|
||||
records_nothing(&mut s, "text.setStyle", json!({"tracking": 50, "start": 0, "end": 4}));
|
||||
s.execute("text.setStyle", &json!({"justify": "center"})).unwrap();
|
||||
records_nothing(&mut s, "text.setStyle", json!({"justify": "center"}));
|
||||
records_one_step(&mut s, "text.setStyle", json!({"tracking": 80, "start": 0, "end": 4}));
|
||||
}
|
||||
|
||||
/// `text.setStyle` on a graph label that leaves the label's own text as it is but changes the
|
||||
/// style its kind of label keeps still records one undo step; given again, it records none.
|
||||
#[test]
|
||||
fn a_kept_graph_label_style_change_alone_records_one_undo_step() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let csv = ",2024,2025\nQ1,3,2\nQ2,5,4";
|
||||
let graph = NodeId(
|
||||
s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let legend = doc.node(graph).unwrap().children().unwrap().iter().find(|c| c.name.as_deref() == Some("Legend")).unwrap();
|
||||
let (label, size) = legend
|
||||
.children()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find_map(|c| match &c.kind {
|
||||
NodeKind::Text(t) if t.plain_text() == "2025" => Some((c.id, t.runs[0].style.size)),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
let kept = |s: &Session| s.doc().unwrap().doc.node(graph).unwrap().extras().graph.as_deref().unwrap().label_styles.legend.clone();
|
||||
assert!(kept(&s).is_none());
|
||||
let p = json!({"ids": [label.0], "size": size});
|
||||
let before = state(&s);
|
||||
s.execute("text.setStyle", &p).unwrap();
|
||||
let after = state(&s);
|
||||
assert!(after.0.node(label) == before.0.node(label), "the label's own text changed");
|
||||
assert!(kept(&s).is_some(), "the legend keeps the style");
|
||||
assert_eq!(after.1, before.1 + 1, "the kept style change recorded no undo step");
|
||||
records_nothing(&mut s, "text.setStyle", p);
|
||||
}
|
||||
|
||||
/// `text.setText` with the text the type already has records no undo step; new text records one.
|
||||
#[test]
|
||||
fn the_same_text_records_no_undo_step() {
|
||||
let (mut s, _) = session_with("Same words", None);
|
||||
records_nothing(&mut s, "text.setText", json!({"text": "Same words"}));
|
||||
records_one_step(&mut s, "text.setText", json!({"text": "Other words"}));
|
||||
}
|
||||
|
||||
/// Fit Headline run again on a headline it already fitted records no undo step; the first run
|
||||
/// records one.
|
||||
#[test]
|
||||
fn fit_headline_again_records_no_undo_step() {
|
||||
let (mut s, _) = session_with("HEADLINE\nbody text", Some(json!({"width": 300, "height": 120})));
|
||||
let start = state(&s);
|
||||
let tracking = s.execute("text.fitHeadline", &json!({})).unwrap()["tracking"].clone();
|
||||
let fitted = state(&s);
|
||||
assert!(*fitted.0 != *start.0 && fitted.1 == start.1 + 1, "the first Fit Headline did not record one undo step");
|
||||
let before = state(&s);
|
||||
assert_eq!(s.execute("text.fitHeadline", &json!({})).unwrap()["tracking"], tracking);
|
||||
let after = state(&s);
|
||||
assert!(*after.0 == *before.0 && after.1 == before.1, "a second Fit Headline recorded an undo step");
|
||||
}
|
||||
|
||||
/// Reshaping area type or type on a path by no distance, or moving a path handle to where it is,
|
||||
/// records no undo step; a reshape that moves something records one.
|
||||
#[test]
|
||||
fn reshaping_type_by_nothing_records_no_undo_step() {
|
||||
let (mut s, id) = session_with("Boxed words", Some(json!({"width": 200, "height": 100})));
|
||||
records_nothing(&mut s, "text.reshapeArea", json!({"id": id, "anchors": [[0, 2]], "dx": 0, "dy": 0}));
|
||||
records_one_step(&mut s, "text.reshapeArea", json!({"id": id, "anchors": [[0, 2]], "dx": 20, "dy": 10}));
|
||||
let path =
|
||||
s.execute("path.create", &json!({"anchors": [{"x": 100, "y": 300, "in": [50, 300], "out": [150, 300]}, {"x": 400, "y": 300}]})).unwrap();
|
||||
let on_path = s.execute("text.createInPath", &json!({"path": path["id"], "mode": "onPath", "text": "Along the curve"})).unwrap()["id"].clone();
|
||||
records_nothing(&mut s, "text.reshapePath", json!({"id": on_path, "anchors": [[0, 1]], "dx": 0, "dy": 0}));
|
||||
records_one_step(&mut s, "text.reshapePath", json!({"id": on_path, "anchors": [[0, 1]], "dx": 0, "dy": 20}));
|
||||
let handle = json!({"id": on_path, "anchor": 0, "which": "out", "x": 100, "y": 250});
|
||||
records_one_step(&mut s, "text.setPathHandle", handle.clone());
|
||||
records_nothing(&mut s, "text.setPathHandle", handle);
|
||||
}
|
||||
@@ -26,6 +26,7 @@ use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids
|
||||
mod csv;
|
||||
mod library;
|
||||
|
||||
pub use csv::utf16_order_without_mark;
|
||||
use csv::{MAX_GRAPH_CSV, dataset_export, dataset_import};
|
||||
pub(crate) use library::{give_svg_library, svg_library};
|
||||
use library::{load_library, save_library};
|
||||
|
||||
@@ -59,25 +59,35 @@ fn utf16(bytes: &[u8], le: bool) -> Option<String> {
|
||||
char::decode_utf16(units).collect::<std::result::Result<String, _>>().ok().filter(|_| odd.is_empty())
|
||||
}
|
||||
|
||||
/// `bytes`, which hold NUL bytes and no byte-order mark, as UTF-16, or `None`. At least half of
|
||||
/// the two-byte units must hold a NUL byte, as characters from U+0001 to U+00FF do; a file with
|
||||
/// fewer, such as UTF-8 or Windows-1252 text with stray NUL bytes, is refused. The byte order is
|
||||
/// the one that reads a line break (`\n` or `\r`). The other order reads one only from U+0A00 or
|
||||
/// U+0D00, so a file that reads one in both orders is refused. A file that reads none in either
|
||||
/// order has no data rows, and is read little-endian so that the import reports that. The text
|
||||
/// must be valid UTF-16 in that order and hold no NUL character.
|
||||
fn utf16_without_mark(bytes: &[u8]) -> Option<String> {
|
||||
let (units, odd) = bytes.as_chunks::<2>();
|
||||
if !odd.is_empty() || units.iter().filter(|c| c.contains(&0)).count() * 2 < units.len() {
|
||||
/// The byte order of `bytes`, which hold NUL bytes and no byte-order mark, read as UTF-16:
|
||||
/// `Some(true)` for little-endian, or `None` when they don't read as UTF-16. At least half of the
|
||||
/// two-byte units must hold a NUL byte, as characters from U+0001 to U+00FF do; a file with fewer,
|
||||
/// such as UTF-8 or Windows-1252 text with stray NUL bytes, is refused. The byte order is the one
|
||||
/// that reads a line break (`\n` or `\r`). The other order reads one only from U+0A00 or U+0D00,
|
||||
/// so a file that reads one in both orders is refused. A file that reads none in either order (one
|
||||
/// line) is big-endian when more of its units start with a NUL byte than end with one, as
|
||||
/// characters from U+0001 to U+00FF do in that order, and little-endian otherwise. An odd last
|
||||
/// byte is left out of the count.
|
||||
pub fn utf16_order_without_mark(bytes: &[u8]) -> Option<bool> {
|
||||
let units = bytes.as_chunks::<2>().0;
|
||||
if units.iter().filter(|c| c.contains(&0)).count() * 2 < units.len() {
|
||||
return None;
|
||||
}
|
||||
let is_line_break = |u: u16| matches!(u, 0x0A | 0x0D);
|
||||
let lines_le = units.iter().any(|&c| is_line_break(u16::from_le_bytes(c)));
|
||||
let lines_be = units.iter().any(|&c| is_line_break(u16::from_be_bytes(c)));
|
||||
if lines_le && lines_be {
|
||||
return None;
|
||||
match (lines_le, lines_be) {
|
||||
(true, true) => None,
|
||||
(false, false) => Some(units.iter().filter(|c| c[0] == 0).count() <= units.iter().filter(|c| c[1] == 0).count()),
|
||||
(_, lines_be) => Some(!lines_be),
|
||||
}
|
||||
utf16(bytes, !lines_be).filter(|text| !text.contains('\0'))
|
||||
}
|
||||
|
||||
/// `bytes`, which hold NUL bytes and no byte-order mark, as UTF-16 in the byte order
|
||||
/// [`utf16_order_without_mark`] gives, or `None`. The file must have an even length, and the text
|
||||
/// must be valid UTF-16 in that order and hold no NUL character.
|
||||
fn utf16_without_mark(bytes: &[u8]) -> Option<String> {
|
||||
utf16(bytes, utf16_order_without_mark(bytes)?).filter(|text| !text.contains('\0'))
|
||||
}
|
||||
|
||||
/// A row of a datasets CSV: the file line it starts on, its cells, and for each cell whether it was quoted.
|
||||
|
||||
@@ -111,6 +111,9 @@ pub struct Prefs {
|
||||
pub recent_fonts_count: u32,
|
||||
pub missing_glyph_protection: bool,
|
||||
pub highlight_alternate_glyphs: bool,
|
||||
/// Type › Show Character Alternates: with a Type tool and one character selected, the canvas
|
||||
/// shows that character's alternate glyphs beside it (on by default).
|
||||
pub show_character_alternates: bool,
|
||||
/// Type › Highlight Substituted Fonts: on screen, text drawn in a substitute for a missing
|
||||
/// font is highlighted, in every document (on by default).
|
||||
pub highlight_substituted_fonts: bool,
|
||||
@@ -442,6 +445,7 @@ impl Default for Prefs {
|
||||
recent_fonts_count: 10,
|
||||
missing_glyph_protection: true,
|
||||
highlight_alternate_glyphs: false,
|
||||
show_character_alternates: true,
|
||||
highlight_substituted_fonts: true,
|
||||
placeholder_text: true,
|
||||
typed_lists: true,
|
||||
|
||||
@@ -415,14 +415,16 @@ impl Session {
|
||||
|
||||
/// Measure the type not measured yet in open document `index`, which is in the back, in its own
|
||||
/// composite fonts, lent for the measuring, so its type has the bounds it will have when the
|
||||
/// document comes to the front. The front document stays the one whose composite fonts are
|
||||
/// registered. The names of the document's composite fonts its type was measured in are kept,
|
||||
/// so its coming to the front does not measure that type again.
|
||||
/// document comes to the front: type naming a composite font the document does not define is
|
||||
/// measured as in a missing font, also when the front document defines one of that name, and
|
||||
/// also when the document defines none. The front document stays the one whose composite fonts
|
||||
/// are registered. The names of the document's composite fonts its type was measured in are
|
||||
/// kept, so its coming to the front does not measure that type again.
|
||||
fn measure_back_document(&mut self, index: usize) {
|
||||
let Some(st) = self.docs.get(index) else { return };
|
||||
let fonts = st.doc.composite_fonts.clone();
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
let lent = db.lend_composite_fonts(&fonts);
|
||||
let lent = db.lend_document_composite_fonts(&fonts);
|
||||
// A name another loan holds with a different definition is not lent: type set in it is
|
||||
// measured again when the document comes to the front.
|
||||
let own: HashSet<String> =
|
||||
|
||||
+180
-53
@@ -17,9 +17,8 @@
|
||||
//! * **Plug-ins**: the module of each plug-in `plugin.install` installs, as a `.wasm` file named
|
||||
//! after its id (as Illustrator keeps plug-ins in its Plug-ins folder); `plugin.remove` deletes it.
|
||||
//! Attaching the folder installs them again, except in Safe Mode and except the ones the user
|
||||
//! disabled, which `disabled.json` in the same folder lists (`plugin.setEnabled`; a window locks
|
||||
//! `disabled.lock` while it writes the list). The Additional Plug-ins Folder preference is not
|
||||
//! copied: it is loaded from where it is. `grants.json` holds what the user granted the plug-ins
|
||||
//! disabled, which `disabled.json` in the same folder lists (`plugin.setEnabled`). The Additional
|
||||
//! Plug-ins Folder preference is not copied: it is loaded from where it is. `grants.json` holds what the user granted the plug-ins
|
||||
//! stored there that list permissions (id, module hash, permissions); a stored plug-in whose
|
||||
//! permissions it doesn't grant is skipped with a log record, and stays in the folder.
|
||||
//! * **Plug-in settings and caches**: `storage/id-<id>/` in the plug-in store, the id written as
|
||||
@@ -27,6 +26,11 @@
|
||||
//! keeps with the `settings` and `cache` permissions ([`PluginStorage`]): `settings.json` and a
|
||||
//! `cache` folder with one file per entry. The host names every file; a plug-in only names keys.
|
||||
//! Replacing a plug-in keeps them, and `plugin.remove` deletes them.
|
||||
//! * **Turns on the plug-in store**: a window or process locks `disabled.lock` in the plug-in folder
|
||||
//! ([`StoreTurn`]) while it reads and changes the stored plug-ins, `grants.json`, `disabled.json`
|
||||
//! and the plug-ins' settings and caches, so that two of them using one folder change it one after
|
||||
//! the other: an install's module and grant are written in one turn, and a grant written for one
|
||||
//! plug-in doesn't undo another one's.
|
||||
//!
|
||||
//! The files are untrusted input like any other: sizes and counts are capped, a file that does not
|
||||
//! parse is skipped with a log record, and every write is atomic.
|
||||
@@ -62,12 +66,15 @@ pub const MAX_PLUGIN_STORE: u64 = 512 << 20;
|
||||
const PLUGIN_EXT: &str = "wasm";
|
||||
/// The file in the plug-in folder that lists the plug-ins the user disabled.
|
||||
pub const DISABLED_FILE: &str = "disabled.json";
|
||||
/// The file in the plug-in folder that a window locks while it reads and writes [`DISABLED_FILE`].
|
||||
/// The file in the plug-in folder that a window locks while it reads and changes the plug-in store
|
||||
/// ([`StoreTurn`]), [`DISABLED_FILE`] included.
|
||||
pub const DISABLED_LOCK: &str = "disabled.lock";
|
||||
/// The file in the plug-in store that holds the permissions the user granted.
|
||||
const GRANTS_FILE: &str = "grants.json";
|
||||
/// The error of a `plugin.remove` that can't remove the plug-in's grant from [`GRANTS_FILE`].
|
||||
pub(crate) const GRANT_NOT_REMOVED: &str = "the plug-in's grant can't be removed from the plug-in store";
|
||||
/// The error of a change to the plug-in store that can't take its turn ([`StoreTurn`]).
|
||||
pub(crate) const STORE_NOT_LOCKED: &str = "the plug-in store can't be locked";
|
||||
/// The largest grants file read.
|
||||
const MAX_GRANTS_FILE: u64 = 1 << 20;
|
||||
/// The folder in the plug-in store that holds each plug-in's settings and cache.
|
||||
@@ -84,7 +91,7 @@ const CACHE_EXT: &str = "bin";
|
||||
/// A write to a folder that holds more is refused as full.
|
||||
pub(crate) const MAX_CACHE_SCAN: usize = storage::MAX_CACHE_ENTRIES * 2;
|
||||
/// Held while a plug-in's settings or cache change, so two runs can't pass a cap together or lose
|
||||
/// each other's settings.
|
||||
/// each other's settings. Taken after the plug-in store's turn ([`StoreTurn`]), never before it.
|
||||
static PLUGIN_DATA_LOCK: Mutex<()> = Mutex::new(());
|
||||
/// The state of each plug-in folder's storage, shared by every storage made for the folder until
|
||||
/// the plug-in is removed, which closes it and drops it.
|
||||
@@ -99,7 +106,7 @@ const MAX_GRANT_WRITES_KEPT: usize = 256;
|
||||
struct IgnoredGrants {
|
||||
/// The grants that should be gone but could not be removed: no session in the process counts
|
||||
/// them ([`Session::ignore_stored_grant`]) until one writes the store's grants for the id
|
||||
/// ([`Session::store_grant`]).
|
||||
/// ([`Session::store_grant_in`]).
|
||||
ignored: BTreeSet<(PathBuf, String)>,
|
||||
/// The latest grant writes of the process, at most [`MAX_GRANT_WRITES_KEPT`], each with the
|
||||
/// count of writes it made ([`IgnoredGrants::writes`]).
|
||||
@@ -217,23 +224,53 @@ fn write_atomic(_: &Path, _: &[u8]) -> std::io::Result<()> {
|
||||
Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "no file system"))
|
||||
}
|
||||
|
||||
/// [`DISABLED_LOCK`] in `dir`, locked until the file is dropped, waiting while another window holds
|
||||
/// it; `None` when it can't be opened or locked.
|
||||
/// [`DISABLED_LOCK`] in the plug-in store `dir`, locked until the file is dropped, waiting while
|
||||
/// another window or process holds it, or another handle in this process. The file is opened for
|
||||
/// reading and writing (a handle that only appends can't be locked on Windows) and is never
|
||||
/// replaced or removed, so that every window locks the same file.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn lock_disabled(dir: &Path) -> Option<std::fs::File> {
|
||||
let opened = std::fs::create_dir_all(dir)
|
||||
.and_then(|()| std::fs::File::options().create(true).truncate(false).read(true).write(true).open(dir.join(DISABLED_LOCK)));
|
||||
let file = opened.and_then(|f| f.lock().map(|()| f));
|
||||
if let Err(e) = &file {
|
||||
log::warn!("can't lock {}: {e}", dir.join(DISABLED_LOCK).display());
|
||||
fn lock_store(dir: &Path) -> std::io::Result<std::fs::File> {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let file = std::fs::File::options().create(true).truncate(false).read(true).write(true).open(dir.join(DISABLED_LOCK))?;
|
||||
match file.try_lock() {
|
||||
Ok(()) => return Ok(file),
|
||||
Err(std::fs::TryLockError::WouldBlock) => {}
|
||||
Err(std::fs::TryLockError::Error(e)) => return Err(e),
|
||||
}
|
||||
file.ok()
|
||||
#[cfg(test)]
|
||||
if let Some(waiting) = WHILE_STORE_LOCKED.take() {
|
||||
waiting();
|
||||
}
|
||||
file.lock()?;
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
/// The browser has no folders to keep anything in.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn lock_disabled(_: &Path) -> Option<std::fs::File> {
|
||||
None
|
||||
fn lock_store(_: &Path) -> std::io::Result<std::fs::File> {
|
||||
Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "no file system"))
|
||||
}
|
||||
|
||||
/// A turn on a plug-in store ([`Session::plugin_store_turn`]): while it is held, no other window or
|
||||
/// process that takes one reads and changes the store's plug-ins, grants, disabled list, settings
|
||||
/// or caches. Dropping it ends the turn. A turn is taken once per operation and handed to the
|
||||
/// functions it calls, since a second lock of the same file by the same thread waits for ever.
|
||||
pub(crate) struct StoreTurn {
|
||||
/// [`DISABLED_LOCK`], locked; `None` without a store, and for a load that goes ahead without
|
||||
/// a turn ([`Session::plugin_store_turn_for_load`]), which then writes nothing to the store.
|
||||
lock: Option<std::fs::File>,
|
||||
}
|
||||
|
||||
impl StoreTurn {
|
||||
/// A turn that isn't held, for a load that goes ahead without one: it writes nothing.
|
||||
pub(crate) fn unheld() -> Self {
|
||||
StoreTurn { lock: None }
|
||||
}
|
||||
|
||||
/// Whether the store may be written in this turn.
|
||||
fn held(&self) -> bool {
|
||||
self.lock.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -252,6 +289,15 @@ thread_local! {
|
||||
/// Tests: writing the `.delete` file beside a folder about to be deleted ([`delete_aside`])
|
||||
/// fails on this thread, as on a full volume.
|
||||
pub(crate) static MARKER_WRITE_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
/// Tests: runs once on this thread when locking the plug-in store ([`lock_store`]) finds it
|
||||
/// locked and waits.
|
||||
pub(crate) static WHILE_STORE_LOCKED: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
|
||||
/// Tests: runs once on this thread when a grant write has read `grants.json` and before it
|
||||
/// writes the file.
|
||||
pub(crate) static AFTER_GRANTS_READ: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
|
||||
/// Tests: runs once on this thread when a change of a plug-in's settings has read them and
|
||||
/// before it writes them.
|
||||
pub(crate) static AFTER_SETTINGS_READ: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Remove `dir/file` → whether it is gone; a file that isn't there is what was wanted.
|
||||
@@ -401,11 +447,14 @@ impl Session {
|
||||
/// Keep the plug-ins this session installs in `dir`, take the disabled plug-ins saved there
|
||||
/// ([`DISABLED_FILE`]), and install the stored ones ([`Session::load_stored_plugins`]).
|
||||
pub fn attach_plugin_store(&mut self, dir: PathBuf) {
|
||||
let disabled =
|
||||
read_capped(&dir.join(DISABLED_FILE), safe_mode::MAX_DISABLED_FILE_BYTES).map(|b| safe_mode::parse_disabled_file(&b)).unwrap_or_default();
|
||||
safe_mode::set_disabled(disabled);
|
||||
let path = dir.join(DISABLED_FILE);
|
||||
self.plugin_dir = Some(dir);
|
||||
self.load_stored_plugins();
|
||||
// A `plugin.install` in another session or process writes the store before this reads it.
|
||||
let _held = crate::cmd::plugin::hold_plugin_changes();
|
||||
let turn = self.plugin_store_turn_for_load();
|
||||
let disabled = read_capped(&path, safe_mode::MAX_DISABLED_FILE_BYTES).map(|b| safe_mode::parse_disabled_file(&b)).unwrap_or_default();
|
||||
safe_mode::set_disabled(disabled);
|
||||
self.load_stored_plugins_in(&turn);
|
||||
}
|
||||
|
||||
/// Install the plug-ins kept in the plug-in folder: none in Safe Mode, and none the user
|
||||
@@ -415,14 +464,25 @@ impl Session {
|
||||
/// stays in the folder with its grant. A grant for an id whose stored module lists no
|
||||
/// permissions is forgotten; one that can't be removed from the grants file doesn't count for
|
||||
/// any session in the process attached to the folder until the file can be written for the id
|
||||
/// ([`Session::ignore_stored_grant`]).
|
||||
/// ([`Session::ignore_stored_grant`]). The folder is read and changed in one turn on it
|
||||
/// ([`Session::plugin_store_turn_for_load`]).
|
||||
pub fn load_stored_plugins(&mut self) {
|
||||
if self.plugin_dir.is_none() || safe_mode::active() {
|
||||
return;
|
||||
}
|
||||
// A `plugin.install` in another session or process writes the store before this reads it.
|
||||
let _held = crate::cmd::plugin::hold_plugin_changes();
|
||||
let turn = self.plugin_store_turn_for_load();
|
||||
self.load_stored_plugins_in(&turn);
|
||||
}
|
||||
|
||||
/// [`Session::load_stored_plugins`] in `turn`, while [`crate::cmd::plugin::hold_plugin_changes`]
|
||||
/// is held.
|
||||
fn load_stored_plugins_in(&mut self, turn: &StoreTurn) {
|
||||
let Some(dir) = self.plugin_dir.clone() else { return };
|
||||
if safe_mode::active() {
|
||||
return;
|
||||
}
|
||||
// A `plugin.install` in another session writes the store before this reads it.
|
||||
let _held = crate::cmd::plugin::hold_plugin_changes();
|
||||
let grants = self.counted_grants(&dir);
|
||||
let limits = vectorcraft_plugins::Limits::default();
|
||||
let mut left = MAX_PLUGIN_STORE;
|
||||
@@ -454,7 +514,7 @@ impl Session {
|
||||
Some(g) => {
|
||||
asks_nothing.remove(&m.id);
|
||||
vectorcraft_plugins::registry::grant(GrantToken::from_engine_grants_file(g.clone()));
|
||||
vectorcraft_plugins::registry::set_storage(&m.id, plugin_storage(Some(&dir), &m.id));
|
||||
vectorcraft_plugins::registry::set_storage(&m.id, plugin_storage(Some(&dir), &m.id, turn));
|
||||
if let Err(e) = vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string())) {
|
||||
log::warn!("skipping the stored plug-in {}: {e}", path.display());
|
||||
}
|
||||
@@ -466,7 +526,7 @@ impl Session {
|
||||
}
|
||||
Ok(plugin) => {
|
||||
asks_nothing.insert(plugin.id().to_string());
|
||||
vectorcraft_plugins::registry::set_storage(plugin.id(), plugin_storage(Some(&dir), plugin.id()));
|
||||
vectorcraft_plugins::registry::set_storage(plugin.id(), plugin_storage(Some(&dir), plugin.id(), turn));
|
||||
if let Err(e) = vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string())) {
|
||||
log::warn!("skipping the stored plug-in {}: {e}", path.display());
|
||||
}
|
||||
@@ -483,13 +543,34 @@ impl Session {
|
||||
};
|
||||
if named {
|
||||
let writes = self.grant_writes();
|
||||
if !self.store_grant(id, None) && self.holds_plugin_grant(id) {
|
||||
if !self.store_grant_in(turn, id, None) && self.holds_plugin_grant(id) {
|
||||
self.ignore_stored_grant(id, writes);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Take a turn on the attached plug-in store ([`StoreTurn`]), waiting while another window or
|
||||
/// process holds one; without a store, a turn that writes nothing. An error, with a log record,
|
||||
/// when the lock file can't be made, opened or locked. Taken after
|
||||
/// [`crate::cmd::plugin::hold_plugin_changes`] when both are needed, and never by a thread that
|
||||
/// holds a turn already.
|
||||
pub(crate) fn plugin_store_turn(&self) -> std::io::Result<StoreTurn> {
|
||||
let Some(dir) = self.plugin_dir.as_deref() else { return Ok(StoreTurn::unheld()) };
|
||||
lock_store(dir)
|
||||
.map(|file| StoreTurn { lock: Some(file) })
|
||||
.inspect_err(|e| log::warn!("can't lock {}: {e}", dir.join(DISABLED_LOCK).display()))
|
||||
}
|
||||
|
||||
/// [`Session::plugin_store_turn`] for a load, which goes ahead without the turn when the store
|
||||
/// folder isn't there (nothing is stored) or can't be locked, and then writes nothing to it.
|
||||
pub(crate) fn plugin_store_turn_for_load(&self) -> StoreTurn {
|
||||
match self.plugin_dir.as_deref() {
|
||||
Some(dir) if dir.is_dir() => self.plugin_store_turn().unwrap_or_else(|_| StoreTurn::unheld()),
|
||||
_ => StoreTurn::unheld(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Write the disabled plug-ins saved for the next launch to the plug-in folder → whether they
|
||||
/// went there, every change included (`false` without a folder, and when a plug-in turned off
|
||||
/// found the file's list full: [`safe_mode::Merged::complete`]). The changes this launch made are applied to the list
|
||||
@@ -499,8 +580,15 @@ impl Session {
|
||||
/// a file that can't be read (too large, say) or that a later version wrote
|
||||
/// ([`safe_mode::read_disabled_file`]): it is kept as it is.
|
||||
pub fn store_disabled_plugins(&self) -> bool {
|
||||
self.plugin_store_turn().is_ok_and(|turn| self.store_disabled_plugins_in(&turn))
|
||||
}
|
||||
|
||||
/// [`Session::store_disabled_plugins`] in `turn`; `false` when it isn't held.
|
||||
pub(crate) fn store_disabled_plugins_in(&self, turn: &StoreTurn) -> bool {
|
||||
let Some(dir) = self.plugin_dir.as_deref() else { return false };
|
||||
let Some(_turn) = lock_disabled(dir) else { return false };
|
||||
if !turn.held() {
|
||||
return false;
|
||||
}
|
||||
let path = dir.join(DISABLED_FILE);
|
||||
let theirs = match read_capped(&path, safe_mode::MAX_DISABLED_FILE_BYTES) {
|
||||
Ok(bytes) => match safe_mode::read_disabled_file(&bytes) {
|
||||
@@ -580,10 +668,10 @@ impl Session {
|
||||
grants
|
||||
}
|
||||
|
||||
/// Write the module `bytes` of the plug-in `id` to the store → whether they went there (`false`
|
||||
/// without a folder).
|
||||
pub(crate) fn store_plugin(&self, id: &str, bytes: &[u8]) -> bool {
|
||||
self.plugin_dir.as_deref().is_some_and(|dir| put(dir, &format!("{}.{PLUGIN_EXT}", file_stem(id)), bytes))
|
||||
/// Write the module `bytes` of the plug-in `id` to the store in `turn` → whether they went there
|
||||
/// (`false` without a folder, and when `turn` isn't held).
|
||||
pub(crate) fn store_plugin(&self, turn: &StoreTurn, id: &str, bytes: &[u8]) -> bool {
|
||||
turn.held() && self.plugin_dir.as_deref().is_some_and(|dir| put(dir, &format!("{}.{PLUGIN_EXT}", file_stem(id)), bytes))
|
||||
}
|
||||
|
||||
/// The module the store holds for the plug-in `id`: `None` without a folder or such a file, and
|
||||
@@ -601,14 +689,15 @@ impl Session {
|
||||
/// Return the store's module for the plug-in `id` to `previous`, the bytes it held before a
|
||||
/// write ([`Session::stored_plugin_bytes`]): with `None`, the file is removed. → whether the
|
||||
/// write reported success; a write that reports a failure may still have put `previous` back.
|
||||
pub(crate) fn put_back_plugin(&self, id: &str, previous: Option<&[u8]>) -> bool {
|
||||
/// In `turn`, the one the write was made in.
|
||||
pub(crate) fn put_back_plugin(&self, turn: &StoreTurn, id: &str, previous: Option<&[u8]>) -> bool {
|
||||
#[cfg(test)]
|
||||
if PUT_BACK_FAILS.get() {
|
||||
return false;
|
||||
}
|
||||
let back = match previous {
|
||||
Some(bytes) => self.store_plugin(id, bytes),
|
||||
None => self.unstore_plugin(id),
|
||||
Some(bytes) => self.store_plugin(turn, id, bytes),
|
||||
None => self.unstore_plugin(turn, id),
|
||||
};
|
||||
#[cfg(test)]
|
||||
if PUT_BACK_FAILS_AFTER_WRITE.get() {
|
||||
@@ -623,15 +712,23 @@ impl Session {
|
||||
self.plugin_dir.as_ref().map(|dir| dir.join(format!("{}.{PLUGIN_EXT}", file_stem(id))).display().to_string())
|
||||
}
|
||||
|
||||
/// Tests: [`Session::store_grant_in`] in a turn of its own ([`Session::plugin_store_turn`]);
|
||||
/// `false` when it can't be taken.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn store_grant(&self, id: &str, grant: Option<vectorcraft_plugins::permissions::Grant>) -> bool {
|
||||
self.plugin_store_turn().is_ok_and(|turn| self.store_grant_in(&turn, id, grant))
|
||||
}
|
||||
|
||||
/// Record in the store what the user granted plug-in `id` (`None`: nothing), leaving the store's
|
||||
/// other grants as they are; with none left, remove the file. Entries this version can't use
|
||||
/// are written back as they were, except one for `id`. A grants file that is too large, can't
|
||||
/// be read or doesn't hold a list is left as it is, with a log record, and nothing is recorded;
|
||||
/// so is one whose new content would be larger than `MAX_GRANTS_FILE`. → whether the store now
|
||||
/// holds what was asked (`false` without a folder). When it does, the grant kept for `id` counts
|
||||
/// again, for every session in the process attached to the store ([`Session::ignore_stored_grant`]).
|
||||
pub(crate) fn store_grant(&self, id: &str, grant: Option<vectorcraft_plugins::permissions::Grant>) -> bool {
|
||||
let done = self.write_grant(id, grant);
|
||||
/// so is one whose new content would be larger than `MAX_GRANTS_FILE`. The file is read and
|
||||
/// written in `turn`. → whether the store now holds what was asked (`false` without a folder,
|
||||
/// and when `turn` isn't held). When it does, the grant kept for `id` counts again, for every
|
||||
/// session in the process attached to the store ([`Session::ignore_stored_grant`]).
|
||||
pub(crate) fn store_grant_in(&self, turn: &StoreTurn, id: &str, grant: Option<vectorcraft_plugins::permissions::Grant>) -> bool {
|
||||
let done = turn.held() && self.write_grant(id, grant);
|
||||
if done && let Some(key) = self.plugin_dir.as_deref().map(plugin_store_key) {
|
||||
let mut shared = IGNORED_PLUGIN_GRANTS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let entry = (key, id.to_string());
|
||||
@@ -648,7 +745,7 @@ impl Session {
|
||||
done
|
||||
}
|
||||
|
||||
/// How many grant writes the sessions of the process have made ([`Session::store_grant`]).
|
||||
/// How many grant writes the sessions of the process have made ([`Session::store_grant_in`]).
|
||||
/// Taken before a write that may fail, for [`Session::ignore_stored_grant`].
|
||||
pub(crate) fn grant_writes(&self) -> u64 {
|
||||
IGNORED_PLUGIN_GRANTS.lock().unwrap_or_else(|e| e.into_inner()).writes
|
||||
@@ -661,7 +758,7 @@ impl Session {
|
||||
}
|
||||
|
||||
/// Stop counting the attached store's grant for the plug-in `id`, in every session in the
|
||||
/// process attached to the same folder, until [`Session::store_grant`] next succeeds for it in
|
||||
/// process attached to the same folder, until [`Session::store_grant_in`] next succeeds for it in
|
||||
/// one of them: for a grant that should be gone and could not be removed, which would otherwise
|
||||
/// approve the bytes it covers. `writes` is [`Session::grant_writes`] from before the failed
|
||||
/// write: when a session has written the store's grants for `id` since, the file holds what that
|
||||
@@ -687,6 +784,10 @@ impl Session {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
#[cfg(test)]
|
||||
if let Some(between) = AFTER_GRANTS_READ.take() {
|
||||
between();
|
||||
}
|
||||
let others = file.other.len();
|
||||
file.other.retain(|entry| entry.get("id").and_then(serde_json::Value::as_str) != Some(id));
|
||||
let changed = match grant {
|
||||
@@ -724,16 +825,17 @@ impl Session {
|
||||
})
|
||||
}
|
||||
|
||||
/// Remove the plug-in `id` from the store → whether its file is gone (`false` without a folder).
|
||||
pub(crate) fn unstore_plugin(&self, id: &str) -> bool {
|
||||
self.plugin_dir.as_deref().is_some_and(|dir| take(dir, &format!("{}.{PLUGIN_EXT}", file_stem(id))))
|
||||
/// Remove the plug-in `id` from the store in `turn` → whether its file is gone (`false` without a
|
||||
/// folder, and when `turn` isn't held).
|
||||
pub(crate) fn unstore_plugin(&self, turn: &StoreTurn, id: &str) -> bool {
|
||||
turn.held() && self.plugin_dir.as_deref().is_some_and(|dir| take(dir, &format!("{}.{PLUGIN_EXT}", file_stem(id))))
|
||||
}
|
||||
|
||||
/// Keep the settings and cache of plug-in `id` in the attached plug-in store from now on; without
|
||||
/// one, nowhere (its storage calls then fail as unavailable). Settings and cache that a removal
|
||||
/// kept are moved back first ([`plugin_storage`]).
|
||||
pub(crate) fn attach_plugin_storage(&self, id: &str) {
|
||||
vectorcraft_plugins::registry::set_storage(id, plugin_storage(self.plugin_dir.as_deref(), id));
|
||||
/// kept are moved back first, in `turn` ([`plugin_storage`]).
|
||||
pub(crate) fn attach_plugin_storage(&self, turn: &StoreTurn, id: &str) {
|
||||
vectorcraft_plugins::registry::set_storage(id, plugin_storage(self.plugin_dir.as_deref(), id, turn));
|
||||
}
|
||||
|
||||
/// Does the attached plug-in store have a folder of settings and cache for plug-in `id`, or one
|
||||
@@ -757,9 +859,13 @@ impl Session {
|
||||
/// that rename fails too, the error also names both paths and the reason, and the next attach or
|
||||
/// removal for the id moves the folder back. Once `forget` returns `true`, the folder and the
|
||||
/// kept settings are deleted ([`delete_aside`]); what that deletion leaves stays, with a log
|
||||
/// record, and a later call for the id tries to delete it again.
|
||||
pub(crate) fn remove_plugin_storage(&self, id: &str, forget: impl FnOnce() -> bool) -> Result<(), StorageError> {
|
||||
/// record, and a later call for the id tries to delete it again. All of it happens in `turn`;
|
||||
/// with a store and a turn that isn't held, nothing changes and this fails.
|
||||
pub(crate) fn remove_plugin_storage(&self, turn: &StoreTurn, id: &str, forget: impl FnOnce() -> bool) -> Result<(), StorageError> {
|
||||
let not_forgotten = || StorageError::Io(GRANT_NOT_REMOVED.to_string());
|
||||
if self.plugin_dir.is_some() && !turn.held() {
|
||||
return Err(StorageError::Io(STORE_NOT_LOCKED.to_string()));
|
||||
}
|
||||
vectorcraft_plugins::registry::set_storage(id, None);
|
||||
let Some(dir) = &self.plugin_dir else {
|
||||
return if forget() { Ok(()) } else { Err(not_forgotten()) };
|
||||
@@ -943,13 +1049,16 @@ fn restore_removed(path: &Path) -> std::io::Result<()> {
|
||||
/// Where plug-in `id` keeps its settings and cache in the plug-in store `dir`. Settings and cache
|
||||
/// that a removal kept are moved back first ([`restore_removed`]); when that fails, the failure is
|
||||
/// logged and there is no storage (its calls fail as unavailable), so that nothing the plug-in
|
||||
/// writes takes their place. A later attach or load tries again.
|
||||
fn plugin_storage(dir: Option<&Path>, id: &str) -> Option<Arc<dyn Storage>> {
|
||||
/// writes takes their place. A later attach or load tries again. They are moved in `turn`; when it
|
||||
/// isn't held, they stay where they are, as when moving them fails.
|
||||
fn plugin_storage(dir: Option<&Path>, id: &str, turn: &StoreTurn) -> Option<Arc<dyn Storage>> {
|
||||
let dir = dir?;
|
||||
let data = plugin_data_dir(dir, id);
|
||||
if !is_link(&dir.join(PLUGIN_DATA_DIR)) {
|
||||
let _held = PLUGIN_DATA_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Err(e) = restore_removed(&data) {
|
||||
let kept_aside = || std::fs::symlink_metadata(&data).is_err() && aside_paths(&data).iter().any(|a| is_kept(a));
|
||||
let restored = if turn.held() || !kept_aside() { restore_removed(&data) } else { Err(std::io::Error::other(STORE_NOT_LOCKED)) };
|
||||
if let Err(e) = restored {
|
||||
log::warn!("can't move the settings and cache of {} back: {e}", data.display());
|
||||
return None;
|
||||
}
|
||||
@@ -1088,6 +1197,12 @@ impl PluginStorage {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A turn on the plug-in store ([`lock_store`]), taken before [`PLUGIN_DATA_LOCK`], so that a
|
||||
/// window or process changing the same settings or cache waits for this change.
|
||||
fn turn(&self) -> Result<std::fs::File, StorageError> {
|
||||
lock_store(&self.root).map_err(|e| StorageError::Io(format!("{STORE_NOT_LOCKED}: {e}")))
|
||||
}
|
||||
|
||||
fn kept(&self) -> MutexGuard<'_, Kept> {
|
||||
self.state.kept.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
@@ -1212,6 +1327,8 @@ impl PluginStorage {
|
||||
|
||||
impl Storage for PluginStorage {
|
||||
fn setting(&self, key: &str, meter: &mut Meter) -> Result<Option<Vec<u8>>, StorageError> {
|
||||
// Reading may move a settings file that doesn't read aside.
|
||||
let _turn = self.turn()?;
|
||||
let _held = PLUGIN_DATA_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
self.open()?;
|
||||
let mut kept = self.kept();
|
||||
@@ -1219,10 +1336,15 @@ impl Storage for PluginStorage {
|
||||
}
|
||||
|
||||
fn set_setting(&self, key: &str, value: &[u8], meter: &mut Meter) -> Result<(), StorageError> {
|
||||
let _turn = self.turn()?;
|
||||
let _held = PLUGIN_DATA_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
self.open()?;
|
||||
let mut kept = self.kept();
|
||||
let settings = &mut self.read_settings(&mut kept.settings, meter)?.values;
|
||||
#[cfg(test)]
|
||||
if let Some(between) = AFTER_SETTINGS_READ.take() {
|
||||
between();
|
||||
}
|
||||
if value.len() > storage::MAX_SETTING_BYTES || (!settings.contains_key(key) && settings.len() >= storage::MAX_SETTINGS) {
|
||||
return Err(StorageError::Full);
|
||||
}
|
||||
@@ -1234,6 +1356,7 @@ impl Storage for PluginStorage {
|
||||
}
|
||||
|
||||
fn delete_setting(&self, key: &str, meter: &mut Meter) -> Result<bool, StorageError> {
|
||||
let _turn = self.turn()?;
|
||||
let _held = PLUGIN_DATA_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
self.open()?;
|
||||
let mut kept = self.kept();
|
||||
@@ -1258,6 +1381,8 @@ impl Storage for PluginStorage {
|
||||
}
|
||||
|
||||
fn set_cache_entry(&self, name: &str, value: &[u8], meter: &mut Meter) -> Result<(), StorageError> {
|
||||
// The cache's size and count are added up and the entry written in one turn.
|
||||
let _turn = self.turn()?;
|
||||
let _held = PLUGIN_DATA_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
self.open()?;
|
||||
let path = self.entry_path(name);
|
||||
@@ -1281,6 +1406,7 @@ impl Storage for PluginStorage {
|
||||
}
|
||||
|
||||
fn remove_cache_entry(&self, name: &str) -> Result<bool, StorageError> {
|
||||
let _turn = self.turn()?;
|
||||
let _held = PLUGIN_DATA_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
self.open()?;
|
||||
let path = self.entry_path(name);
|
||||
@@ -1296,6 +1422,7 @@ impl Storage for PluginStorage {
|
||||
}
|
||||
|
||||
fn clear_cache(&self) -> Result<u64, StorageError> {
|
||||
let _turn = self.turn()?;
|
||||
let _held = PLUGIN_DATA_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
self.open()?;
|
||||
let dir = self.cache_dir();
|
||||
|
||||
@@ -241,6 +241,25 @@ pub(crate) fn key_guide(s: &Session) -> Option<usize> {
|
||||
st.selection.key_guide.and_then(|k| crate::cmd::guide_indexes(&st.doc, &[k]).first().copied())
|
||||
}
|
||||
|
||||
/// Runs the unit test `path` (`tests::newdoc::...`) again in a child process of the test binary
|
||||
/// → whether this is that child. For a test that changes process-wide state the tests running
|
||||
/// beside it read, such as the active color settings.
|
||||
pub(crate) fn in_own_process(path: &str) -> bool {
|
||||
const CHILD: &str = "VECTORCRAFT_TEST_OWN_PROCESS";
|
||||
if std::env::var_os(CHILD).is_some() {
|
||||
return true;
|
||||
}
|
||||
let output =
|
||||
std::process::Command::new(std::env::current_exe().unwrap()).args(["--exact", path, "--nocapture"]).env(CHILD, "1").output().unwrap();
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(
|
||||
output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"),
|
||||
"{path} failed in its own process:\n{stdout}\n{}",
|
||||
String::from_utf8_lossy(&output.stderr),
|
||||
);
|
||||
false
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_and_undo_redo() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -8,7 +8,7 @@ use std::sync::Arc;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId};
|
||||
use vectorcraft_geom::path::measured_segments;
|
||||
use vectorcraft_geom::{Anchor, PathData, Point, SubPath};
|
||||
use vectorcraft_geom::{Anchor, AnchorKind, PathData, Point, SubPath, Vec2};
|
||||
|
||||
use crate::*;
|
||||
|
||||
@@ -109,3 +109,29 @@ fn an_anchor_edit_that_changes_nothing_records_no_undo_step() {
|
||||
s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 5, "x": a.p.x + 1.0, "y": a.p.y})).unwrap();
|
||||
assert_eq!(undo_steps(&s), 1);
|
||||
}
|
||||
|
||||
/// `path.setHandle` to where the handle already is, on a smooth anchor whose other handle is not in
|
||||
/// line with it, leaves both handles as they are and records no undo step. With `independent` it
|
||||
/// makes the anchor a corner, which records one.
|
||||
#[test]
|
||||
fn a_handle_already_in_place_on_a_smooth_anchor_records_no_undo_step() {
|
||||
let (mut s, id) = long_path(100);
|
||||
let p = anchor(&s, id, 5).p;
|
||||
let smooth = Anchor { p, h_in: p + Vec2::new(-3.0, 0.0), h_out: p + Vec2::new(0.0, 4.0), kind: AnchorKind::Smooth };
|
||||
let path = Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().path_data_mut().unwrap();
|
||||
path.subpaths[0].anchors[5] = smooth;
|
||||
for which in ["out", "in"] {
|
||||
let h = if which == "out" { smooth.h_out } else { smooth.h_in };
|
||||
s.execute("path.setHandle", &json!({"id": id.0, "anchor": 5, "which": which, "x": h.x, "y": h.y})).unwrap();
|
||||
assert_eq!(undo_steps(&s), 0, "path.setHandle on the {which} handle recorded an undo step");
|
||||
assert_eq!(anchor(&s, id, 5), smooth, "path.setHandle on the {which} handle changed the anchor");
|
||||
}
|
||||
s.execute("path.setHandle", &json!({"id": id.0, "anchor": 5, "which": "out", "x": smooth.h_out.x, "y": smooth.h_out.y, "independent": true}))
|
||||
.unwrap();
|
||||
assert_eq!(undo_steps(&s), 1);
|
||||
assert_eq!(anchor(&s, id, 5).kind, AnchorKind::Corner);
|
||||
// On a corner, the same independent request changes nothing.
|
||||
s.execute("path.setHandle", &json!({"id": id.0, "anchor": 5, "which": "out", "x": smooth.h_out.x, "y": smooth.h_out.y, "independent": true}))
|
||||
.unwrap();
|
||||
assert_eq!(undo_steps(&s), 1);
|
||||
}
|
||||
|
||||
@@ -163,6 +163,61 @@ fn reverse_path_direction_on_and_off_set_the_winding() {
|
||||
assert!(s.execute("path.reverse", &json!({})).is_err(), "nothing to reverse");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reverse_path_direction_turns_the_width_profile_and_pen_records_with_the_path() {
|
||||
use vectorcraft_doc::{AngleProfile, PressureProfile, WidthProfile};
|
||||
let mut s = session();
|
||||
let open =
|
||||
NodeId(run(&mut s, "path.create", json!({"anchors": [{"x": 0, "y": 50}, {"x": 40, "y": 50}, {"x": 100, "y": 50}]}))["id"].as_u64().unwrap());
|
||||
let closed = rect(&mut s, 10.0);
|
||||
let profile = WidthProfile { points: vec![(0.0, 0.2, 0.6), (0.3, 1.0, 0.4), (1.0, 0.5, 0.9)] };
|
||||
let pressure = PressureProfile { points: vec![(0.0, 0.1), (0.25, 0.9), (1.0, 0.4)] };
|
||||
let bearing = AngleProfile { points: vec![(0.0, 10.0), (0.6, 80.0), (1.0, 170.0)] };
|
||||
s.edit("set", |d, _| {
|
||||
for id in [open, closed] {
|
||||
let st = d.node_mut(id).unwrap().appearance.stroke_mut().unwrap();
|
||||
st.profile = Some(profile.clone());
|
||||
st.pressure = Some(pressure.clone());
|
||||
st.tilt = Some(pressure.clone());
|
||||
st.bearing = Some(bearing.clone());
|
||||
st.rotation = Some(bearing.clone());
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
// (anchor point, its fraction of the path's length) for each anchor.
|
||||
let along = |s: &Session, id: NodeId| {
|
||||
let sp = s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].clone();
|
||||
let pos = sp.anchor_arc_positions();
|
||||
let total = *pos.last().unwrap();
|
||||
sp.anchors.iter().zip(pos).map(|(a, at)| (a.p, at / total)).collect::<Vec<_>>()
|
||||
};
|
||||
let before = [along(&s, open), along(&s, closed)];
|
||||
run(&mut s, "select.set", json!({"ids": [open.0, closed.0]}));
|
||||
assert_eq!(run(&mut s, "path.reverse", json!({}))["changed"], 2);
|
||||
for ((id, before), closed) in [open, closed].into_iter().zip(before).zip([false, true]) {
|
||||
let after = along(&s, id);
|
||||
let st = s.doc().unwrap().doc.node(id).unwrap().appearance.stroke().unwrap().clone();
|
||||
// Each anchor keeps the widths it had (its sides swapped, as the path runs the other way)
|
||||
// and what the pen recorded there. (A closed path's start is where its profile steps.) A
|
||||
// closed path now starts part way along a span of the width profile, which is resampled
|
||||
// there, so its smooth curve moves a little.
|
||||
let near = if closed { 0.02 } else { 1e-6 };
|
||||
for (p, t) in before.iter().filter(|(_, t)| !closed || *t > 0.0) {
|
||||
let u = after.iter().find(|(q, _)| q.distance(*p) < 1e-9).unwrap().1;
|
||||
let (l, r) = profile.at(*t);
|
||||
let (l2, r2) = st.profile.as_ref().unwrap().at(u);
|
||||
assert!((l - r2).abs() < near && (r - l2).abs() < near, "{id:?} at {p:?}: {:?} then {:?}", (l, r), (l2, r2));
|
||||
for got in [&st.pressure, &st.tilt] {
|
||||
assert!((pressure.at(*t) - got.as_ref().unwrap().at(u)).abs() < 1e-6, "{id:?} pressure at {p:?}");
|
||||
}
|
||||
for got in [&st.bearing, &st.rotation] {
|
||||
assert!((bearing.at(*t) - got.as_ref().unwrap().at(u)).abs() < 1e-6, "{id:?} bearing at {p:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attributes_survive_a_native_round_trip() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -963,6 +963,69 @@ fn brush_freehand_paints_with_a_brush_in_one_step() {
|
||||
assert_eq!(brush_of(&s, id).as_deref(), Some("Charcoal"));
|
||||
}
|
||||
|
||||
/// `brush.freehand` refuses a `brush` that is not a string or names no brush in the document,
|
||||
/// and a `style` other than "pencil" or "brush", before it draws: the document, the selection
|
||||
/// and the undo history stay as they were. A `brush` left out or null draws the plain path.
|
||||
#[test]
|
||||
fn brush_freehand_refuses_a_brush_or_style_it_cannot_use() {
|
||||
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]]);
|
||||
for (extra, words) in [
|
||||
(json!({"brush": "Nope"}), "no brush named `Nope`"),
|
||||
(json!({"brush": ""}), "no brush named ``"),
|
||||
(json!({"brush": 5}), "`brush` must be a string"),
|
||||
(json!({"brush": {"name": "Charcoal"}}), "`brush` must be a string"),
|
||||
(json!({"brush": true}), "`brush` must be a string"),
|
||||
(json!({"brush": "Charcoal", "style": "marker"}), "`style` must be \"pencil\" or \"brush\", not \"marker\""),
|
||||
(json!({"brush": "Charcoal", "style": 1}), "`style` must be \"pencil\" or \"brush\", not 1"),
|
||||
] {
|
||||
let mut p = extra.clone();
|
||||
p["points"] = points.clone();
|
||||
let (before, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
|
||||
let e = s.execute("brush.freehand", &p).expect_err(&format!("{extra} is refused"));
|
||||
assert!(e.to_string().contains(words), "{extra}: {e}");
|
||||
assert!(*s.doc().unwrap().doc == *before, "{extra} leaves the document");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [a], "{extra} leaves the selection");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{extra} records no undo step");
|
||||
}
|
||||
for extra in [json!({}), json!({"brush": null, "style": null})] {
|
||||
let mut p = extra.clone();
|
||||
p["points"] = points.clone();
|
||||
let id = NodeId(s.execute("brush.freehand", &p).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(brush_of(&s, id), None, "{extra} draws the plain path");
|
||||
}
|
||||
for style in ["pencil", "brush"] {
|
||||
let r = s.execute("brush.freehand", &json!({"points": points, "style": style, "brush": "Charcoal"})).unwrap();
|
||||
assert!(r["id"].is_u64(), "{style}: {r}");
|
||||
}
|
||||
}
|
||||
|
||||
/// 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]
|
||||
fn paintbrush_tool_skips_a_deleted_brush() {
|
||||
let mut s = session();
|
||||
s.execute("brush.setCurrent", &json!({"name": "Arrow"})).unwrap();
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("paintbrush", v).unwrap();
|
||||
s.set_tool_option("brush", &json!("Dots"));
|
||||
s.execute("brush.delete", &json!({"name": "Dots"})).unwrap();
|
||||
let stroke = |s: &mut Session, y: f64| {
|
||||
for (k, x) in [(PointerKind::Down, 10.0), (PointerKind::Drag, 50.0), (PointerKind::Drag, 90.0), (PointerKind::Up, 130.0)] {
|
||||
s.pointer(&PointerEvent::new(k, x, y), v).unwrap();
|
||||
}
|
||||
s.doc().unwrap().selection.objects[0]
|
||||
};
|
||||
let id = stroke(&mut s, 10.0);
|
||||
assert_eq!(brush_of(&s, id).as_deref(), Some("Arrow"));
|
||||
s.execute("brush.delete", &json!({"name": "Arrow"})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.unknown.get("currentBrush"), None);
|
||||
let id = stroke(&mut s, 110.0);
|
||||
assert_eq!(brush_of(&s, id), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paintbrush_tool_uses_the_current_brush() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -2947,6 +2947,262 @@ fn live_paint_release_and_expand() {
|
||||
assert!((area(&s, a) - 10000.0).abs() < 1.0);
|
||||
}
|
||||
|
||||
/// Set the appearance rows of the face of Live Paint group `g` at `face` (or the edge nearest
|
||||
/// `edge`) to `items`, and give it `opacity`; returns that child's id.
|
||||
fn set_live_part(s: &mut Session, g: NodeId, face: Option<(f64, f64)>, edge: Option<(f64, f64)>, items: Vec<AppearanceItem>, opacity: f32) -> NodeId {
|
||||
use vectorcraft_tools::builder::{edge_near, face_at};
|
||||
let n = node(s, g);
|
||||
let part = match (face, edge) {
|
||||
(Some((x, y)), _) => face_at(&n, Point::new(x, y)),
|
||||
(_, Some((x, y))) => edge_near(&n, Point::new(x, y), 0.5),
|
||||
_ => None,
|
||||
};
|
||||
let id = part.unwrap().id;
|
||||
s.edit("t", |d, _| {
|
||||
let c = d.node_mut(id).unwrap();
|
||||
c.appearance.items = items;
|
||||
c.opacity = opacity;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
/// Expand keeps a face or edge when a fill or stroke row draws it, whatever row is on top: a
|
||||
/// painted lower row under an unpainted top row is kept, and a part whose only painted row is
|
||||
/// hidden, transparent or 0 pt wide, or whose own opacity is 0, is dropped.
|
||||
#[test]
|
||||
fn live_paint_expand_keeps_the_faces_and_edges_that_draw() {
|
||||
use vectorcraft_doc::{FillLayer, StrokeLayer};
|
||||
let fill = |p: Paint| AppearanceItem::Fill(FillLayer::new(p));
|
||||
let stroke = |p: Paint, w: f64| AppearanceItem::Stroke(StrokeLayer::new(p, w));
|
||||
let red = || Paint::solid(Color::rgb(1.0, 0.0, 0.0));
|
||||
let hidden = |mut i: AppearanceItem| {
|
||||
match &mut i {
|
||||
AppearanceItem::Fill(f) => f.visible = false,
|
||||
AppearanceItem::Stroke(st) => st.visible = false,
|
||||
}
|
||||
i
|
||||
};
|
||||
let clear = |mut i: AppearanceItem| {
|
||||
match &mut i {
|
||||
AppearanceItem::Fill(f) => f.opacity = 0.0,
|
||||
AppearanceItem::Stroke(st) => st.opacity = 0.0,
|
||||
}
|
||||
i
|
||||
};
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
let lower_fill = set_live_part(&mut s, g, Some((25.0, 50.0)), None, vec![fill(red()), fill(Paint::None)], 1.0);
|
||||
let hidden_fill = set_live_part(&mut s, g, Some((125.0, 50.0)), None, vec![hidden(fill(red()))], 1.0);
|
||||
let clear_fill = set_live_part(&mut s, g, Some((75.0, 50.0)), None, vec![clear(fill(red()))], 1.0);
|
||||
let lower_stroke = set_live_part(&mut s, g, None, Some((0.0, 50.0)), vec![stroke(red(), 2.0), stroke(Paint::None, 1.0)], 1.0);
|
||||
let hidden_stroke = set_live_part(&mut s, g, None, Some((150.0, 50.0)), vec![hidden(stroke(red(), 2.0))], 1.0);
|
||||
let thin_stroke = set_live_part(&mut s, g, None, Some((100.0, 50.0)), vec![stroke(red(), 0.0)], 1.0);
|
||||
let clear_stroke = set_live_part(&mut s, g, None, Some((50.0, 50.0)), vec![clear(stroke(red(), 2.0))], 1.0);
|
||||
let clear_edge = set_live_part(&mut s, g, None, Some((75.0, 0.0)), vec![stroke(red(), 2.0)], 0.0);
|
||||
let parts = [lower_fill, hidden_fill, clear_fill, lower_stroke, hidden_stroke, thin_stroke, clear_stroke, clear_edge];
|
||||
assert_eq!(parts.iter().collect::<std::collections::HashSet<_>>().len(), parts.len());
|
||||
let before = node(&s, g);
|
||||
s.execute("livePaint.expand", &json!({})).unwrap();
|
||||
let n = node(&s, g);
|
||||
let kept: Vec<NodeId> = n.children().unwrap().iter().map(|c| c.id).collect();
|
||||
let has = |id: NodeId| kept.contains(&id);
|
||||
assert!(has(lower_fill) && has(lower_stroke), "a painted lower row draws: {kept:?}");
|
||||
for id in [hidden_fill, clear_fill, hidden_stroke, thin_stroke, clear_stroke, clear_edge] {
|
||||
assert!(!has(id), "{id:?} draws nothing: {kept:?}");
|
||||
}
|
||||
// The kept parts keep every row.
|
||||
let rows = |n: &Node, id: NodeId| n.children().unwrap().iter().find(|c| c.id == id).unwrap().appearance.items.clone();
|
||||
assert_eq!(rows(&n, lower_fill), rows(&before, lower_fill));
|
||||
assert_eq!(rows(&n, lower_stroke), rows(&before, lower_stroke));
|
||||
}
|
||||
|
||||
/// `livePaint.info` lists every fill and stroke row of each face and edge, bottom first, and says
|
||||
/// which rows draw by Expand's rule, while `fill`, `stroke` and `width` stay the top rows.
|
||||
#[test]
|
||||
fn live_paint_info_lists_every_appearance_row() {
|
||||
use vectorcraft_doc::{FillLayer, StrokeLayer};
|
||||
let fill = |p: Paint| AppearanceItem::Fill(FillLayer::new(p));
|
||||
let stroke = |p: Paint, w: f64| AppearanceItem::Stroke(StrokeLayer::new(p, w));
|
||||
let red = || Paint::solid(Color::rgb(1.0, 0.0, 0.0));
|
||||
let blue = || Paint::solid(Color::rgb(0.0, 0.0, 1.0));
|
||||
let green = || Paint::solid(Color::rgb(0.0, 1.0, 0.0));
|
||||
let hidden = |mut i: AppearanceItem| {
|
||||
match &mut i {
|
||||
AppearanceItem::Fill(f) => f.visible = false,
|
||||
AppearanceItem::Stroke(st) => st.visible = false,
|
||||
}
|
||||
i
|
||||
};
|
||||
let faded = |mut i: AppearanceItem, o: f32| {
|
||||
match &mut i {
|
||||
AppearanceItem::Fill(f) => f.opacity = o,
|
||||
AppearanceItem::Stroke(st) => st.opacity = o,
|
||||
}
|
||||
i
|
||||
};
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
// A drawn lower fill and a half-opaque stroke under an unpainted top fill.
|
||||
let lower = set_live_part(&mut s, g, Some((25.0, 50.0)), None, vec![fill(red()), faded(stroke(blue(), 2.0), 0.5), fill(Paint::None)], 1.0);
|
||||
let quiet = set_live_part(&mut s, g, Some((125.0, 50.0)), None, vec![hidden(fill(red())), faded(fill(red()), 0.0)], 1.0);
|
||||
let bare = set_live_part(&mut s, g, Some((75.0, 50.0)), None, vec![], 1.0);
|
||||
// Two strokes with a fill between them.
|
||||
let two = set_live_part(&mut s, g, None, Some((0.0, 50.0)), vec![stroke(red(), 4.0), fill(green()), stroke(blue(), 2.0)], 1.0);
|
||||
let thin = set_live_part(&mut s, g, None, Some((100.0, 50.0)), vec![stroke(red(), 0.0)], 1.0);
|
||||
let clear_edge = set_live_part(&mut s, g, None, Some((75.0, 0.0)), vec![stroke(red(), 2.0)], 0.0);
|
||||
let hidden_edge = set_live_part(&mut s, g, None, Some((150.0, 50.0)), vec![stroke(red(), 2.0)], 1.0);
|
||||
s.edit("t", |d, _| {
|
||||
d.node_mut(hidden_edge).unwrap().visible = false;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let parts = [lower, quiet, bare, two, thin, clear_edge, hidden_edge];
|
||||
assert_eq!(parts.iter().collect::<std::collections::HashSet<_>>().len(), parts.len());
|
||||
|
||||
let info = s.execute("livePaint.info", &json!({"group": g.0})).unwrap();
|
||||
let part = |key: &str, id: NodeId| info[key].as_array().unwrap().iter().find(|p| p["id"] == id.0).unwrap().clone();
|
||||
let fill_row = |i: usize, p: Paint, o: f64, v: bool, drawn: bool| json!({"index": i, "kind": "fill", "paint": p.label(), "opacity": o, "visible": v, "drawn": drawn});
|
||||
let stroke_row = |i: usize, p: Paint, o: f64, v: bool, w: f64, drawn: bool| json!({"index": i, "kind": "stroke", "paint": p.label(), "opacity": o, "visible": v, "width": w, "drawn": drawn});
|
||||
|
||||
let f = part("faces", lower);
|
||||
assert_eq!(f["fill"], json!(Paint::None.label()), "fill stays the top fill");
|
||||
assert!(f["bounds"].is_array());
|
||||
assert_eq!(
|
||||
f["appearance"],
|
||||
json!([fill_row(0, red(), 1.0, true, true), stroke_row(1, blue(), 0.5, true, 2.0, true), fill_row(2, Paint::None, 1.0, true, false)])
|
||||
);
|
||||
assert_eq!(part("faces", quiet)["appearance"], json!([fill_row(0, red(), 1.0, false, false), fill_row(1, red(), 0.0, true, false)]));
|
||||
assert_eq!(part("faces", bare)["appearance"], json!([]));
|
||||
|
||||
let e = part("edges", two);
|
||||
assert_eq!((e["stroke"].clone(), e["width"].clone()), (json!(blue().label()), json!(2.0)), "stroke and width stay the top stroke's");
|
||||
assert_eq!(
|
||||
e["appearance"],
|
||||
json!([stroke_row(0, red(), 1.0, true, 4.0, true), fill_row(1, green(), 1.0, true, true), stroke_row(2, blue(), 1.0, true, 2.0, true)])
|
||||
);
|
||||
assert_eq!(part("edges", thin)["appearance"], json!([stroke_row(0, red(), 1.0, true, 0.0, false)]));
|
||||
for id in [clear_edge, hidden_edge] {
|
||||
assert_eq!(part("edges", id)["appearance"], json!([stroke_row(0, red(), 1.0, true, 2.0, false)]), "a part that is not shown draws no row");
|
||||
}
|
||||
}
|
||||
|
||||
/// Merge carries a face's whole appearance when one of its rows draws, and carries nothing from a
|
||||
/// face that draws nothing.
|
||||
#[test]
|
||||
fn live_paint_merge_carries_the_faces_that_draw() {
|
||||
use vectorcraft_doc::FillLayer;
|
||||
use vectorcraft_tools::builder::face_at;
|
||||
let fill = |p: Paint| AppearanceItem::Fill(FillLayer::new(p));
|
||||
let green = || Paint::solid(Color::rgb(0.0, 1.0, 0.0));
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
let rows = vec![fill(green()), fill(Paint::None)];
|
||||
set_live_part(&mut s, g, Some((25.0, 50.0)), None, rows.clone(), 1.0);
|
||||
let mut only_hidden = fill(green());
|
||||
if let AppearanceItem::Fill(f) = &mut only_hidden {
|
||||
f.visible = false;
|
||||
}
|
||||
set_live_part(&mut s, g, Some((125.0, 50.0)), None, vec![only_hidden], 1.0);
|
||||
let c = rect(&mut s, 120.0, 120.0, 100.0, 20.0);
|
||||
s.execute("livePaint.merge", &json!({"ids": [g.0, c.0]})).unwrap();
|
||||
let n = node(&s, g);
|
||||
assert_eq!(face_at(&n, Point::new(25.0, 50.0)).unwrap().appearance.items, rows, "the drawn lower fill is carried");
|
||||
let b = face_at(&n, Point::new(125.0, 50.0)).unwrap();
|
||||
assert_eq!(b.appearance.fill_paint(), Paint::solid(Color::rgb(0.0, 0.0, 1.0)), "the face takes its source's fill again");
|
||||
assert!(b.appearance.has_drawn_fill());
|
||||
}
|
||||
|
||||
/// Merge rebuilds the faces and edges as other paths, so the appearance it carries to them leaves
|
||||
/// the strokes' pen pressure behind and keeps the rest.
|
||||
#[test]
|
||||
fn live_paint_merge_leaves_pen_pressure_behind() {
|
||||
use vectorcraft_doc::{FillLayer, PressureProfile, StrokeLayer};
|
||||
use vectorcraft_tools::builder::{edge_near, face_at};
|
||||
let pressed = || {
|
||||
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 3.0);
|
||||
st.pressure = PressureProfile::from_samples([(0.0, 0.2), (0.5, 1.0), (1.0, 0.2)]);
|
||||
assert!(st.pressure.is_some());
|
||||
st
|
||||
};
|
||||
let green = AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0))));
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
set_live_part(&mut s, g, Some((75.0, 50.0)), None, vec![green.clone(), AppearanceItem::Stroke(pressed())], 1.0);
|
||||
set_live_part(&mut s, g, None, Some((0.0, 50.0)), vec![AppearanceItem::Stroke(pressed())], 1.0);
|
||||
let c = rect(&mut s, 120.0, 120.0, 100.0, 20.0);
|
||||
s.execute("livePaint.merge", &json!({"ids": [g.0, c.0]})).unwrap();
|
||||
let n = node(&s, g);
|
||||
let mut plain = pressed();
|
||||
plain.pressure = None;
|
||||
let face = &face_at(&n, Point::new(75.0, 50.0)).unwrap().appearance.items;
|
||||
assert_eq!(face, &vec![green, AppearanceItem::Stroke(plain.clone())]);
|
||||
assert_eq!(edge_near(&n, Point::new(0.0, 50.0), 0.5).unwrap().appearance.items, vec![AppearanceItem::Stroke(plain)]);
|
||||
}
|
||||
|
||||
/// The gradients Merge carries to the rebuilt faces and edges keep their fit on the old outline,
|
||||
/// lower rows included.
|
||||
#[test]
|
||||
fn live_paint_merge_keeps_the_fit_of_carried_gradients() {
|
||||
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop};
|
||||
use vectorcraft_doc::{FillLayer, StrokeLayer};
|
||||
use vectorcraft_tools::builder::{edge_near, face_at};
|
||||
let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)];
|
||||
let unplaced = GradientPaint::new(Gradient::new(GradientKind::Linear, stops));
|
||||
let gradient = || Paint::Gradient(Box::new(unplaced.clone()));
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
let rows = vec![AppearanceItem::Fill(FillLayer::new(gradient())), AppearanceItem::Fill(FillLayer::new(Paint::None))];
|
||||
let face = set_live_part(&mut s, g, Some((25.0, 50.0)), None, rows, 1.0);
|
||||
let edge = set_live_part(&mut s, g, None, Some((0.0, 50.0)), vec![AppearanceItem::Stroke(StrokeLayer::new(gradient(), 2.0))], 1.0);
|
||||
let before = node(&s, g);
|
||||
let old = |id: NodeId| before.children().unwrap().iter().find(|c| c.id == id).unwrap().clone();
|
||||
let (old_face, old_edge) = (old(face), old(edge));
|
||||
let c = rect(&mut s, 120.0, 120.0, 100.0, 20.0);
|
||||
s.execute("livePaint.merge", &json!({"ids": [g.0, c.0]})).unwrap();
|
||||
let n = node(&s, g);
|
||||
let geom = |items: &[AppearanceItem]| match items[0].paint() {
|
||||
Paint::Gradient(gp) => gp.geom,
|
||||
p => panic!("a gradient, not {p:?}"),
|
||||
};
|
||||
let face_bounds = old_face.geometric_bounds().unwrap();
|
||||
let new_face = face_at(&n, Point::new(25.0, 50.0)).unwrap();
|
||||
assert_eq!(geom(&new_face.appearance.items), Some(unplaced.resolve(face_bounds)), "the lower-row fill keeps its fit");
|
||||
let AppearanceItem::Stroke(st) = &old_edge.appearance.items[0] else { panic!("a stroke") };
|
||||
let edge_box = st.paint_bounds(old_edge.geometric_bounds().unwrap());
|
||||
let new_edge = edge_near(&n, Point::new(0.0, 50.0), 0.5).unwrap();
|
||||
assert_eq!(geom(&new_edge.appearance.items), Some(unplaced.resolve(edge_box)), "the stroke keeps its fit");
|
||||
}
|
||||
|
||||
/// Merge carries a face's or edge's visibility, opacity and blending mode to the rebuilt part with
|
||||
/// its appearance: a half-transparent face drawn by a stroke alone stays half transparent, and a
|
||||
/// hidden edge stays hidden.
|
||||
#[test]
|
||||
fn live_paint_merge_keeps_the_visibility_opacity_and_blending_of_carried_parts() {
|
||||
use vectorcraft_color::BlendMode;
|
||||
use vectorcraft_doc::StrokeLayer;
|
||||
use vectorcraft_tools::builder::{edge_near, face_at};
|
||||
let stroke = || AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), 2.0));
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
let face = set_live_part(&mut s, g, Some((25.0, 50.0)), None, vec![stroke()], 0.5);
|
||||
let edge = set_live_part(&mut s, g, None, Some((0.0, 50.0)), vec![stroke()], 1.0);
|
||||
s.edit("t", |d, _| {
|
||||
d.node_mut(face).unwrap().blend = BlendMode::Multiply;
|
||||
d.node_mut(edge).unwrap().visible = false;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let c = rect(&mut s, 120.0, 120.0, 100.0, 20.0);
|
||||
s.execute("livePaint.merge", &json!({"ids": [g.0, c.0]})).unwrap();
|
||||
let n = node(&s, g);
|
||||
let f = face_at(&n, Point::new(25.0, 50.0)).unwrap();
|
||||
assert_eq!((f.appearance.items.clone(), f.opacity, f.blend, f.visible), (vec![stroke()], 0.5, BlendMode::Multiply, true));
|
||||
let e = edge_near(&n, Point::new(0.0, 50.0), 0.5).unwrap();
|
||||
assert_eq!((e.appearance.items.clone(), e.visible), (vec![stroke()], false), "the hidden edge stays hidden");
|
||||
}
|
||||
|
||||
fn live_group_only(s: &mut Session) -> NodeId {
|
||||
let r = s.execute("livePaint.make", &json!({})).unwrap();
|
||||
NodeId(r["id"].as_u64().unwrap())
|
||||
@@ -3692,6 +3948,37 @@ fn live_paint_bucket_alt_shift_gradient_samples_active_stroke_only() {
|
||||
assert!(matches!(node(&s, src).appearance.fill_paint(), Paint::Gradient(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn live_paint_selection_double_click_selects_the_faces_no_stroked_edge_parts() {
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
// The edge between the middle and right faces draws no stroke.
|
||||
s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": [100.0, 50.0], "none": true})).unwrap();
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("livePaintSelection", v).unwrap();
|
||||
let gn = node(&s, g);
|
||||
let face = |x: f64| vectorcraft_tools::builder::face_at(&gn, Point::new(x, 50.0)).unwrap().id;
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let double_click = |s: &mut Session, x: f64, m: Mods| {
|
||||
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] {
|
||||
s.pointer(&PointerEvent::new(kind, x, 50.0).with_mods(m), v).unwrap();
|
||||
}
|
||||
let mut ids = s.doc().unwrap().selection.objects.clone();
|
||||
ids.sort();
|
||||
ids
|
||||
};
|
||||
let sorted = |mut ids: Vec<NodeId>| {
|
||||
ids.sort();
|
||||
ids
|
||||
};
|
||||
assert_eq!(double_click(&mut s, 125.0, Mods::default()), sorted(vec![face(75.0), face(125.0)]));
|
||||
// The stroked edge at x = 50 parts the left face from the others.
|
||||
assert_eq!(double_click(&mut s, 25.0, Mods::default()), vec![face(25.0)]);
|
||||
// Shift-double-click adds the faces reached to the selection.
|
||||
assert_eq!(double_click(&mut s, 75.0, Mods { shift: true, ..Default::default() }), sorted(vec![face(25.0), face(75.0), face(125.0)]));
|
||||
assert_eq!(s.doc().unwrap().doc, before, "selecting changes no paint");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn live_paint_selection_marquee_selects_what_it_touches() {
|
||||
let mut s = session();
|
||||
@@ -4229,6 +4516,41 @@ fn a_trace_run_hands_its_trace_to_the_command() {
|
||||
assert!((bb.center().x - 160.0).abs() < 1.5, "traced where the image is now: {bb:?}");
|
||||
}
|
||||
|
||||
/// A trace made in one document applies only there: in another document with the same image,
|
||||
/// object and settings, the run no longer applies, and both trace commands drop the trace handed
|
||||
/// in and trace that document's own image, as one undo step.
|
||||
#[test]
|
||||
fn a_trace_run_applies_only_in_its_own_document() {
|
||||
let p = json!({"params": {"ignoreWhite": true}});
|
||||
for command in ["imageTrace.make", "imageTrace.makeAndExpand"] {
|
||||
let mut direct = session();
|
||||
image_doc(&mut direct);
|
||||
let want = direct.execute(command, &p).unwrap();
|
||||
let mut s = session();
|
||||
let img = image_doc(&mut s);
|
||||
let a = s.active_index().unwrap();
|
||||
let copy = (*s.doc().unwrap().doc).clone();
|
||||
let run = cmd::TraceRun::prepare(&s, command, &p).unwrap();
|
||||
let traced = run.run(&|_, _| true).unwrap();
|
||||
let b = s.add_document(copy, None);
|
||||
assert_ne!(s.documents()[a].uid, s.documents()[b].uid);
|
||||
assert!(!run.current(&s), "{command}: another document");
|
||||
assert!(s.set_active(a));
|
||||
assert!(run.current(&s), "{command}: its own document");
|
||||
assert!(s.set_active(b));
|
||||
traced.hand_in(&mut s);
|
||||
let got = s.execute(run.command(), run.params()).unwrap();
|
||||
assert!(s.trace_hand_off.is_none(), "{command}: dropped");
|
||||
assert_eq!(got, want, "{command}");
|
||||
let g = NodeId(got["id"].as_u64().unwrap());
|
||||
assert_eq!(node(&s, g), node(&direct, g), "{command}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(matches!(node(&s, img).kind, NodeKind::Image(_)), "{command}: one undo step");
|
||||
assert!(s.set_active(a));
|
||||
assert!(matches!(node(&s, img).kind, NodeKind::Image(_)), "{command}: the first document is untouched");
|
||||
}
|
||||
}
|
||||
|
||||
/// A plug-in run that calls Image Trace and then fails leaves a trace handed in for the command in
|
||||
/// place, as it leaves the document.
|
||||
#[test]
|
||||
|
||||
@@ -1034,14 +1034,39 @@ fn in_place_pastes_put_a_copy_on_each_artboard_named() {
|
||||
// `artboard` wins over `artboards`.
|
||||
let ids = ids_of(&s.execute(cmd, &json!({"artboard": 2, "artboards": [0, 3]})).unwrap());
|
||||
assert_eq!(doc(&s).bounds_of(&ids, false).unwrap().origin(), Point::new(boards[2].x0 + 10.0, boards[2].y0 + 5.0), "{cmd}");
|
||||
// A list that is empty, names an artboard the document lacks or names one twice, or isn't a
|
||||
// list: an error, and nothing pasted.
|
||||
let before = doc(&s).clone();
|
||||
for bad in [json!([]), json!([0, 4]), json!([1, 1]), json!([0, -1]), json!(2), json!("0,1")] {
|
||||
assert!(s.execute(cmd, &json!({"artboards": bad})).is_err(), "{cmd} with artboards {bad}");
|
||||
// A list that is empty, names an artboard the document lacks or names one twice, holds a
|
||||
// value that is not a whole number, or isn't a list, and an `artboard` that is not a whole
|
||||
// number or not an artboard: an error naming the fault, and nothing pasted. Both keys are
|
||||
// checked when both are given.
|
||||
let (before, undo) = (doc(&s).clone(), s.doc().unwrap().history.undo.len());
|
||||
let (not_list, missing, not_whole) = (
|
||||
"`artboards` must be a list of artboard indices",
|
||||
"`artboards` names an artboard the document does not have",
|
||||
"`artboards` must contain whole numbers",
|
||||
);
|
||||
let cases = [
|
||||
(json!({"artboards": []}), not_list),
|
||||
(json!({"artboards": 2}), not_list),
|
||||
(json!({"artboards": "0,1"}), not_list),
|
||||
(json!({"artboards": [0, 4]}), missing),
|
||||
(json!({"artboards": [1, 1]}), "`artboards` names an artboard twice"),
|
||||
(json!({"artboards": [0, -1]}), not_whole),
|
||||
(json!({"artboards": [0, 1.5]}), not_whole),
|
||||
(json!({"artboards": [4, "1"]}), not_whole),
|
||||
(json!({"artboard": 1, "artboards": [7]}), missing),
|
||||
(json!({"artboard": 1, "artboards": ["1"]}), not_whole),
|
||||
(json!({"artboard": 4}), "`artboard` must be the index of an artboard of the document"),
|
||||
(json!({"artboard": -1}), "`artboard` must be a whole number"),
|
||||
(json!({"artboard": 1.5}), "`artboard` must be a whole number"),
|
||||
(json!({"artboard": "1"}), "`artboard` must be a whole number"),
|
||||
(json!({"artboard": null}), "`artboard` must be a whole number"),
|
||||
(json!({"artboard": "1", "artboards": [9]}), "`artboard` must be a whole number"),
|
||||
];
|
||||
for (p, want) in cases {
|
||||
let e = s.execute(cmd, &p).unwrap_err().to_string();
|
||||
assert_eq!(e, format!("invalid parameters for `{cmd}`: {want}"), "{cmd} {p}");
|
||||
}
|
||||
assert!(s.execute(cmd, &json!({"artboard": 1, "artboards": [7]})).is_err(), "{cmd}: a bad list with `artboard`");
|
||||
assert_eq!(doc(&s), &before, "{cmd}");
|
||||
assert_eq!((doc(&s), s.doc().unwrap().history.undo.len()), (&before, undo), "{cmd}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -16,7 +16,10 @@ use crate::*;
|
||||
/// Every test here reads or changes the process-wide proof view or colour settings: one at a time.
|
||||
/// Tests that switch the Color Settings away from the defaults live in `tests/color_settings.rs`
|
||||
/// (their own process): every colour shown or rendered goes through them, so no lock could cover
|
||||
/// all the tests that would see the change.
|
||||
/// all the tests that would see the change. A unit test that assigns its front document a profile
|
||||
/// other than the working space changes the active settings the same way until another document
|
||||
/// comes to the front: it starts with `crate::tests::in_own_process`, which runs it again in a
|
||||
/// child process.
|
||||
pub(crate) static GLOBAL: Mutex<()> = Mutex::new(());
|
||||
|
||||
fn session() -> Session {
|
||||
@@ -184,6 +187,26 @@ fn rgb_cmyk_converts_each_gradient_stop() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Each point of a freeform gradient converts on its own, as gradient stops do.
|
||||
#[test]
|
||||
fn rgb_cmyk_converts_each_freeform_point() {
|
||||
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 10.0, 10.0, 50.0, 50.0, json!("#000000"));
|
||||
let stops = json!([{"offset": 0, "color": Color::rgb(0.912_345, 0.1, 0.2)}, {"offset": 1, "color": Color::rgb(0.3, 0.4, 0.654_321)}]);
|
||||
let points = json!([{"at": [20, 20], "color": Color::rgb(0.2, 0.876_543, 0.3)}, {"at": [50, 50], "color": Color::rgb(0.6, 0.111_111, 0.9)}]);
|
||||
let gradient = json!({"kind": "freeform", "stops": stops, "freeform": {"points": points}});
|
||||
s.execute("paint.setFill", &json!({"ids": [id.0], "gradient": gradient})).unwrap();
|
||||
let points = |s: &Session| match fill_of(s, id) {
|
||||
Paint::Gradient(g) => g.freeform.map(|f| f.points.iter().map(|p| p.color).collect::<Vec<_>>()).unwrap_or_default(),
|
||||
p => panic!("not a gradient: {p:?}"),
|
||||
};
|
||||
let old = points(&s);
|
||||
assert!(!old.is_empty(), "the freeform fill has points");
|
||||
s.execute("object.convertDocumentColorMode", &json!({"mode": "cmyk"})).unwrap();
|
||||
assert_eq!(points(&s), old.into_iter().map(to_cmyk).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
/// A pattern's tile art converts, and the art filled with the pattern keeps it.
|
||||
#[test]
|
||||
fn rgb_cmyk_converts_a_pattern_tile() {
|
||||
|
||||
@@ -490,6 +490,118 @@ fn a_clipping_mask_of_ones_own_stays_when_the_link_is_updated() {
|
||||
assert_eq!(mask_width(&s), Some(4.0), "the mask's path is kept");
|
||||
}
|
||||
|
||||
/// [`two_plates`] on a 20 × 20 pt page, its composite drawn through the left half of it (same
|
||||
/// length, so the plates stay where the header says).
|
||||
fn two_plates_square() -> Vec<u8> {
|
||||
let text = String::from_utf8(two_plates()).unwrap();
|
||||
let text = text.replace("0 0 20 10", "0 0 20 20").replace("20 10 scale", "20 20 scale");
|
||||
text.replacen("10 10 lineto 0 10 lineto", "10 20 lineto 0 20 lineto", 1).into_bytes()
|
||||
}
|
||||
|
||||
/// The bounds (width, height) of the clipping path of clip group `g`.
|
||||
fn clip_size(doc: &Document, g: NodeId) -> (f64, f64) {
|
||||
let NodeKind::Group { children, clip: true } = &doc.node(g).unwrap().kind else { panic!("a clip group: {:?}", doc.node(g).unwrap().kind) };
|
||||
let b = children[0].geometric_bounds().expect("a clipping path");
|
||||
(b.width(), b.height())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placement_options_clip_a_dcs_image_inside_its_files_clipping_path() {
|
||||
let dir = temp_dir("placement-clip");
|
||||
let path = write(&dir, "pic.eps", &two_plates());
|
||||
let square = write(&dir, "square.eps", &two_plates_square());
|
||||
let mut s = session();
|
||||
let r = s.execute("file.place", &json!({ "path": path, "at": [100, 100] })).unwrap();
|
||||
let id = image_of(&s, &r["ids"][0]).id;
|
||||
s.execute("links.placementOptions", &json!({"ids": [id.0], "preserve": "fill", "clip": true})).unwrap();
|
||||
let depth = |doc: &Document| std::iter::successors(Some(id), |n| doc.parent_of(*n)).count();
|
||||
let mut first = None;
|
||||
// The square file fills the 20 × 10 pt placement and is cut to it; the file's own clipping
|
||||
// path, the left half of its page, still clips the image inside that, on every relink.
|
||||
for _ in 0..2 {
|
||||
s.execute("links.relink", &json!({ "ids": [id.0], "path": square })).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let file = doc.parent_of(id).expect("the file's clip group");
|
||||
let (w, h) = clip_size(doc, file);
|
||||
assert!((w - 10.0).abs() < 1e-6 && (h - 20.0).abs() < 1e-6, "the file's clipping path: {w} × {h}");
|
||||
let placement = doc.parent_of(file).expect("the placement's clip group");
|
||||
let (w, h) = clip_size(doc, placement);
|
||||
assert!((w - 20.0).abs() < 1e-6 && (h - 10.0).abs() < 1e-6, "the placement's clip: {w} × {h}");
|
||||
assert_eq!(*first.get_or_insert(depth(doc)), depth(doc), "no group is added on a later relink");
|
||||
}
|
||||
// An update of the file keeps both.
|
||||
s.execute("links.update", &json!({ "ids": [id.0] })).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert_eq!(first, Some(depth(doc)));
|
||||
let file = doc.parent_of(id).unwrap();
|
||||
assert!((clip_size(doc, file).0 - 10.0).abs() < 1e-6, "the file's clipping path");
|
||||
assert!((clip_size(doc, doc.parent_of(file).unwrap()).1 - 10.0).abs() < 1e-6, "the placement's clip");
|
||||
// The file loses its clipping path and gains it again: the same two groups, no more.
|
||||
let unclipped = String::from_utf8(two_plates_square()).unwrap().replacen("closepath clip newpath", "closepath newpath ", 1);
|
||||
for _ in 0..2 {
|
||||
std::fs::write(&square, unclipped.as_bytes()).unwrap();
|
||||
s.execute("links.update", &json!({ "ids": [id.0] })).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert_eq!(first, Some(depth(doc)), "the file's group stays, without its clip");
|
||||
let plain = doc.parent_of(id).unwrap();
|
||||
assert!(!matches!(doc.node(plain).unwrap().kind, NodeKind::Group { clip: true, .. }), "the file's group is not clipped");
|
||||
assert!((clip_size(doc, doc.parent_of(plain).unwrap()).1 - 10.0).abs() < 1e-6, "the placement's clip stays");
|
||||
std::fs::write(&square, two_plates_square()).unwrap();
|
||||
s.execute("links.update", &json!({ "ids": [id.0] })).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert_eq!(first, Some(depth(doc)), "the file's clip group again, at the same depth");
|
||||
let file = doc.parent_of(id).unwrap();
|
||||
assert!((clip_size(doc, file).0 - 10.0).abs() < 1e-6, "the file's clipping path again");
|
||||
assert!((clip_size(doc, doc.parent_of(file).unwrap()).1 - 10.0).abs() < 1e-6, "the placement's clip");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placement_options_clip_a_dcs_image_in_a_symbol_inside_its_files_clipping_path() {
|
||||
let dir = temp_dir("placement-clip-symbol");
|
||||
let path = write(&dir, "pic.eps", &two_plates());
|
||||
let square = write(&dir, "square.eps", &two_plates_square());
|
||||
let mut s = session();
|
||||
let r = s.execute("file.place", &json!({ "path": path, "at": [100, 100] })).unwrap();
|
||||
s.execute("symbol.new", &json!({ "name": "Pic", "ids": [r["ids"][0]] })).unwrap();
|
||||
let list = s.execute("links.list", &json!({})).unwrap();
|
||||
let row = list["links"].as_array().unwrap().iter().find(|r| r["owner"]["kind"] == "symbol").cloned().expect("the symbol's image");
|
||||
let id = row["id"].as_u64().unwrap();
|
||||
s.execute("links.placementOptions", &json!({"ids": [id], "preserve": "fill", "clip": true})).unwrap();
|
||||
// The clip groups around the symbol's image, innermost first.
|
||||
let clips = |s: &Session| {
|
||||
fn find(n: &Node, id: u64, around: &mut Vec<(f64, f64)>) -> bool {
|
||||
if n.id.0 == id {
|
||||
return true;
|
||||
}
|
||||
let Some(children) = n.children() else { return false };
|
||||
if !children.iter().any(|c| find(c, id, around)) {
|
||||
return false;
|
||||
}
|
||||
if let NodeKind::Group { clip: true, .. } = n.kind
|
||||
&& let Some(b) = children[0].geometric_bounds()
|
||||
{
|
||||
around.push((b.width(), b.height()));
|
||||
}
|
||||
true
|
||||
}
|
||||
let mut around = vec![];
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert!(find(&doc.symbols.iter().find(|w| w.name == "Pic").expect("the symbol").art, id, &mut around));
|
||||
around
|
||||
};
|
||||
for _ in 0..2 {
|
||||
s.execute("links.relink", &json!({ "ids": [id], "path": square })).unwrap();
|
||||
let around = clips(&s);
|
||||
assert_eq!(around.len(), 2, "the file's clip group inside the placement's: {around:?}");
|
||||
// In the symbol's own units: the file's path as wide as the placement is tall, half as
|
||||
// wide as it is tall, and the placement twice as wide as it is tall.
|
||||
let ((fw, fh), (pw, ph)) = (around[0], around[1]);
|
||||
assert!((fh - 2.0 * fw).abs() < 1e-6 && (fw - ph).abs() < 1e-6, "the file's clipping path: {around:?}");
|
||||
assert!((pw - 2.0 * ph).abs() < 1e-6, "the placement's clip: {around:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dcs_file_takes_the_place_parameters_an_eps_file_takes() {
|
||||
let dir = temp_dir("params");
|
||||
|
||||
@@ -1651,6 +1651,97 @@ fn smoothing_a_whole_closed_path_smooths_a_bump_at_its_start() {
|
||||
assert!(start <= far + 0.5, "the bump at the start stays {start} pt high, the far one {far} pt");
|
||||
}
|
||||
|
||||
/// Checks that the closed path `p` starts at its point nearest `old`, within `reach` of it: its first
|
||||
/// anchor is no farther from `old` than any other point along the path, and its outline starts there.
|
||||
fn assert_starts_nearest(p: &PathData, old: Point, reach: f64) {
|
||||
let sp = &p.subpaths[0];
|
||||
assert!(sp.closed, "the path stays closed");
|
||||
let first = sp.anchors[0].p;
|
||||
let nearest = smooth_test_samples(p).iter().map(|q| q.distance(old)).fold(f64::INFINITY, f64::min);
|
||||
let d = first.distance(old);
|
||||
assert!(d <= nearest + 1e-6 && d <= reach, "the path starts {d} pt from its old start, its nearest point is {nearest} pt away: {sp:?}");
|
||||
let mut bp = kurbo::BezPath::new();
|
||||
sp.to_bezpath_into(&mut bp);
|
||||
assert_eq!(bp.elements().first(), Some(&kurbo::PathEl::MoveTo(first)));
|
||||
}
|
||||
|
||||
/// A drag over a closed path's first anchor and the anchors either side of it smooths the bump there,
|
||||
/// and the path starts at the point of the smoothed path nearest the old first anchor. The anchors out
|
||||
/// of reach keep their places, and undo brings the path back.
|
||||
#[test]
|
||||
fn smoothing_over_a_closed_paths_first_anchor_keeps_its_start() {
|
||||
let mut s = session();
|
||||
let (c, r) = (Point::new(300.0, 300.0), 100.0);
|
||||
let at = |deg: f64, rr: f64| c + rr * kurbo::Vec2::from_angle(deg.to_radians());
|
||||
let anchors: Vec<_> = (0..12)
|
||||
.map(|i| {
|
||||
let q = at(30.0 * f64::from(i), if i == 0 { r + 8.0 } else { r });
|
||||
json!({"x": q.x, "y": q.y})
|
||||
})
|
||||
.collect();
|
||||
let id = smooth_test_path(&mut s, &anchors, true);
|
||||
let before = path(&s, id);
|
||||
let old = before.subpaths[0].anchors[0].p;
|
||||
// Along the circle from -40° to 40°, over anchors 11, 0 and 1.
|
||||
let drag: Vec<Point> = (-20..=20).map(|k| at(2.0 * f64::from(k), r)).collect();
|
||||
smooth_pass(&mut s, &drag);
|
||||
let after = path(&s, id);
|
||||
assert_ne!(after, before, "the bump is smoothed");
|
||||
assert_starts_nearest(&after, old, 12.0);
|
||||
let kept = &after.subpaths[0].anchors;
|
||||
for a in &before.subpaths[0].anchors[2..=10] {
|
||||
assert!(kept.iter().any(|k| k.p == a.p), "{:?} is out of reach and stays: {kept:?}", a.p);
|
||||
}
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(path(&s, id), before);
|
||||
}
|
||||
|
||||
/// A drag over the whole of a closed path with a spike that turns back on itself, which the refit
|
||||
/// keeps as a corner, leaves the path starting at its point nearest the old first anchor.
|
||||
#[test]
|
||||
fn smoothing_a_whole_closed_path_with_a_spike_keeps_its_start() {
|
||||
let mut s = session();
|
||||
let mut seed = 5u64;
|
||||
let (c, r) = (Point::new(300.0, 300.0), 80.0);
|
||||
let at = |a: f64, rr: f64| c + rr * kurbo::Vec2::from_angle(a);
|
||||
use std::f64::consts::{PI, TAU};
|
||||
let mut pts: Vec<Point> = (0..64).map(|i| at(f64::from(i) / 64.0 * TAU, r + 2.5 * smooth_noise(&mut seed))).collect();
|
||||
// Out from the anchor at 180° to a tip 40 pt beyond the circle and back.
|
||||
pts.splice(33..33, [at(PI, r + 40.0), at(PI + 0.002, r)]);
|
||||
let anchors: Vec<_> = pts.iter().map(|q| json!({"x": q.x, "y": q.y})).collect();
|
||||
let id = smooth_test_path(&mut s, &anchors, true);
|
||||
let before = path(&s, id);
|
||||
let mut drag: Vec<Point> = (0..=128).map(|i| at(f64::from(i) / 128.0 * TAU, r)).collect();
|
||||
drag.splice(65..65, (0..=16).chain((0..=16).rev()).map(|k| at(PI, r + 2.5 * f64::from(k))));
|
||||
smooth_pass(&mut s, &drag);
|
||||
let after = path(&s, id);
|
||||
assert_ne!(after, before, "the path is smoothed");
|
||||
assert_starts_nearest(&after, pts[0], 12.0);
|
||||
}
|
||||
|
||||
/// A drag that reaches a closed path but not its first anchor leaves that anchor first, where it was.
|
||||
#[test]
|
||||
fn smoothing_a_closed_path_away_from_its_first_anchor_keeps_it_first() {
|
||||
let mut s = session();
|
||||
let (c, r) = (Point::new(300.0, 300.0), 100.0);
|
||||
let at = |deg: f64, rr: f64| c + rr * kurbo::Vec2::from_angle(deg.to_radians());
|
||||
let anchors: Vec<_> = (0..12)
|
||||
.map(|i| {
|
||||
let q = at(30.0 * f64::from(i), if i == 6 { r + 8.0 } else { r });
|
||||
json!({"x": q.x, "y": q.y})
|
||||
})
|
||||
.collect();
|
||||
let id = smooth_test_path(&mut s, &anchors, true);
|
||||
let before = path(&s, id);
|
||||
// Along the circle from 140° to 220°, over anchors 5, 6 and 7.
|
||||
let drag: Vec<Point> = (70..=110).map(|k| at(2.0 * f64::from(k), r)).collect();
|
||||
smooth_pass(&mut s, &drag);
|
||||
let after = path(&s, id);
|
||||
assert_ne!(after, before, "the bump is smoothed");
|
||||
assert!(after.subpaths[0].closed);
|
||||
assert_eq!(after.subpaths[0].anchors[0], before.subpaths[0].anchors[0]);
|
||||
}
|
||||
|
||||
/// A straight line along y = 200 from x = 100 to 400, one anchor every 5 pt, whose second and
|
||||
/// second-to-last anchors are 1.5 pt off the line: its first and last segments leave and arrive at
|
||||
/// 16.7° to it.
|
||||
@@ -1932,6 +2023,260 @@ fn smoothing_leaves_paths_out_of_reach_and_straight_segments_alone() {
|
||||
assert_eq!(path(&s, line), before);
|
||||
}
|
||||
|
||||
/// The turn, in degrees, of `sp` at each of its anchors: round a closed path, and 0 at an open
|
||||
/// path's first and last anchors.
|
||||
fn smooth_anchor_turns(sp: &vectorcraft_geom::SubPath) -> Vec<f64> {
|
||||
let (n, segs) = (sp.anchors.len(), sp.segment_count());
|
||||
(0..n)
|
||||
.map(|i| {
|
||||
if segs == 0 || !sp.closed && (i == 0 || i == n - 1) {
|
||||
return 0.0;
|
||||
}
|
||||
let (a, b) = (sp.segment((i + segs - 1) % segs), sp.segment(i % segs));
|
||||
let tin = [a.p3 - a.p2, a.p3 - a.p1, a.p3 - a.p0].into_iter().find(|d| d.hypot() > 1e-9).unwrap_or_default();
|
||||
let tout = [b.p1 - b.p0, b.p2 - b.p0, b.p3 - b.p0].into_iter().find(|d| d.hypot() > 1e-9).unwrap_or_default();
|
||||
tin.cross(tout).atan2(tin.dot(tout)).abs().to_degrees()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The turn of `sp` at its anchor on `at`, `None` when no anchor is there.
|
||||
fn smooth_turn_at(sp: &vectorcraft_geom::SubPath, at: Point) -> Option<f64> {
|
||||
let i = sp.anchors.iter().position(|a| a.p.distance(at) < 1e-9)?;
|
||||
smooth_anchor_turns(sp).get(i).copied()
|
||||
}
|
||||
|
||||
/// An open polyline with a corner at (300, 300) whose angle inside is `inside` degrees: a 100 pt
|
||||
/// leg along y = 300 from the left, then a 100 pt leg turning by 180 - `inside` degrees, each leg cut
|
||||
/// into `per_leg` segments. Returns the path, the corner, and a drag along the path from 40 pt
|
||||
/// before the corner to 40 pt after it.
|
||||
fn smooth_corner_path(s: &mut Session, inside: f64, per_leg: usize) -> (NodeId, Point, Vec<Point>) {
|
||||
let v = Point::new(300.0, 300.0);
|
||||
let d = kurbo::Vec2::from_angle(-(180.0 - inside).to_radians());
|
||||
let back = kurbo::Vec2::new(-100.0, 0.0);
|
||||
let legs = per_leg as f64;
|
||||
let mut pts: Vec<Point> = (0..per_leg).map(|k| v + back * (1.0 - k as f64 / legs)).collect();
|
||||
pts.extend((0..=per_leg).map(|k| v + d * (100.0 * k as f64 / legs)));
|
||||
let anchors: Vec<_> = pts.iter().map(|p| json!({"x": p.x, "y": p.y})).collect();
|
||||
let id = smooth_test_path(s, &anchors, false);
|
||||
let mut drag: Vec<Point> = (0..8).map(|k| v - kurbo::Vec2::new(40.0 - 5.0 * f64::from(k), 0.0)).collect();
|
||||
drag.extend((0..=8).map(|k| v + d * (5.0 * f64::from(k))));
|
||||
(id, v, drag)
|
||||
}
|
||||
|
||||
/// A Smooth drag over a corner keeps it where the path turns there by more than 57.5° (an angle
|
||||
/// inside the corner under 122.5°), whether each leg is one segment or ten and at any Fidelity. A
|
||||
/// wider corner is not kept: when the drag changes the path, no anchor is left turning as sharply
|
||||
/// there, and a leg of ten segments at the default Fidelity always rounds it.
|
||||
#[test]
|
||||
fn the_smooth_tool_keeps_corners_sharper_than_its_threshold() {
|
||||
let mut wrong = vec![];
|
||||
for inside in [30.0f64, 60.0, 90.0, 120.0, 122.4, 122.6, 125.0, 135.0, 150.0, 170.0] {
|
||||
let kept = inside < 122.5;
|
||||
for per_leg in [1, 10] {
|
||||
for fidelity in [0.5, 2.5, 10.0] {
|
||||
let mut s = session();
|
||||
let (id, v, drag) = smooth_corner_path(&mut s, inside, per_leg);
|
||||
let before = path(&s, id);
|
||||
let pts: Vec<_> = drag.iter().map(|p| json!([p.x, p.y])).collect();
|
||||
s.execute("path.smoothRegion", &json!({"points": pts, "radius": 12, "fidelity": fidelity})).unwrap();
|
||||
let p = path(&s, id);
|
||||
let turn = 180.0 - inside;
|
||||
let at = smooth_turn_at(&p.subpaths[0], v);
|
||||
let changed = p != before;
|
||||
let rounded = changed && at.is_none_or(|t| t < turn - 1.0);
|
||||
let right = if kept { at.is_some_and(|t| (t - turn).abs() < 0.01) } else { rounded || !changed && per_leg == 1 };
|
||||
let most = smooth_anchor_turns(&p.subpaths[0]).into_iter().fold(0.0, f64::max);
|
||||
if !right || !kept && most > 57.5 || !kept && per_leg == 10 && fidelity == 2.5 && !rounded {
|
||||
wrong.push(format!(
|
||||
"{inside}° inside, {per_leg} segments a leg, Fidelity {fidelity}: turn {at:?}, changed {changed}, sharpest {most}°"
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(wrong.is_empty(), "{wrong:#?}");
|
||||
}
|
||||
|
||||
/// Three Smooth drags over a 90° and a 120° corner leave the corner where it was and as sharp, while
|
||||
/// the first one smooths a wobble on the same leg.
|
||||
#[test]
|
||||
fn smooth_drags_again_and_again_keep_a_corner_in_place() {
|
||||
for inside in [90.0f64, 120.0] {
|
||||
let mut s = session();
|
||||
let v = Point::new(300.0, 300.0);
|
||||
let d = kurbo::Vec2::from_angle(-(180.0 - inside).to_radians());
|
||||
let mut anchors: Vec<_> = (0..=18).map(|k| json!({"x": 180.0 + 5.0 * f64::from(k), "y": if k % 2 == 1 { 301.5 } else { 300.0 }})).collect();
|
||||
anchors.push(json!({"x": v.x, "y": v.y}));
|
||||
let c = v + d * 100.0;
|
||||
anchors.push(json!({"x": c.x, "y": c.y}));
|
||||
let id = smooth_test_path(&mut s, &anchors, false);
|
||||
let mut drag = smooth_drag_along(300.0, 175.0, 300.0);
|
||||
drag.extend((1..=8).map(|k| v + d * (5.0 * f64::from(k))));
|
||||
let mut before = path(&s, id);
|
||||
for pass in 1..=3 {
|
||||
smooth_pass(&mut s, &drag);
|
||||
let p = path(&s, id);
|
||||
let at = smooth_turn_at(&p.subpaths[0], v);
|
||||
assert!(at.is_some_and(|t| (t - (180.0 - inside)).abs() < 0.01), "{inside}°, pass {pass}: {at:?}");
|
||||
if pass == 1 {
|
||||
assert!(p.anchor_count() < before.anchor_count(), "{inside}°: the wobble is smoothed: {} anchors", p.anchor_count());
|
||||
assert!(total_turning(&p) < total_turning(&before), "{inside}°: the path turns less");
|
||||
}
|
||||
before = p;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A Smooth drag along a line with 1 pt jags, each turning by 90°, smooths them all: none is kept
|
||||
/// as a corner, since the line hardly turns over the tool's reach.
|
||||
#[test]
|
||||
fn smoothing_keeps_no_small_jag_as_a_corner() {
|
||||
let mut s = session();
|
||||
let anchors: Vec<_> = (0..=200).map(|i| json!({"x": 100.0 + f64::from(i), "y": if i % 2 == 1 { 201.0 } else { 200.0 }})).collect();
|
||||
let id = smooth_test_path(&mut s, &anchors, false);
|
||||
assert!(smooth_anchor_turns(&path(&s, id).subpaths[0]).iter().skip(1).take(199).all(|t| (t - 90.0).abs() < 1e-6));
|
||||
smooth_pass(&mut s, &smooth_drag_along(200.5, 90.0, 310.0));
|
||||
let p = path(&s, id);
|
||||
let sp = &p.subpaths[0];
|
||||
assert!(sp.anchors.len() < 50, "the jags are smoothed: {} anchors", sp.anchors.len());
|
||||
let most = smooth_anchor_turns(sp).into_iter().fold(0.0, f64::max);
|
||||
assert!(most <= 57.5, "a jag is kept, turning {most}°");
|
||||
}
|
||||
|
||||
/// A closed path with 90° corners at (200, 200), where it starts, and at (400, 200), 75° ones at
|
||||
/// (400, 400) and (200, 400), a 30° bend at (300, 426.79), and a top side jagged by 1 pt. With
|
||||
/// `from_bend` the path starts at the bend instead.
|
||||
fn smooth_house(s: &mut Session, from_bend: bool) -> (NodeId, [Point; 4], Point) {
|
||||
let corners = [Point::new(200.0, 200.0), Point::new(400.0, 200.0), Point::new(400.0, 400.0), Point::new(200.0, 400.0)];
|
||||
let bend = Point::new(300.0, 400.0 + 100.0 / 75f64.to_radians().tan());
|
||||
let mut anchors = vec![json!({"x": 200.0, "y": 200.0})];
|
||||
anchors.extend((1..40).map(|k| json!({"x": 200.0 + 5.0 * f64::from(k), "y": if k % 2 == 1 { 201.0 } else { 200.0 }})));
|
||||
for p in [corners[1], corners[2], bend, corners[3]] {
|
||||
anchors.push(json!({"x": p.x, "y": p.y}));
|
||||
}
|
||||
if from_bend {
|
||||
let at_bend = anchors.len() - 2;
|
||||
anchors.rotate_left(at_bend);
|
||||
}
|
||||
(smooth_test_path(s, &anchors, true), corners, bend)
|
||||
}
|
||||
|
||||
/// A Smooth drag round the whole of a closed path, and one along its top side only, keep its corners,
|
||||
/// the one where the path starts included, and smooth the jags; the path still starts where it did,
|
||||
/// at a corner or at the bend, which the refit keeps, and the bend out of the second drag's reach
|
||||
/// stays as it was.
|
||||
#[test]
|
||||
fn smoothing_a_closed_path_keeps_its_corners() {
|
||||
let turns: Vec<f64> = {
|
||||
let mut s = session();
|
||||
let (id, corners, _) = smooth_house(&mut s, false);
|
||||
corners.iter().map(|c| smooth_turn_at(&path(&s, id).subpaths[0], *c).unwrap()).collect()
|
||||
};
|
||||
for from_bend in [false, true] {
|
||||
let mut s = session();
|
||||
let (id, corners, bend) = smooth_house(&mut s, from_bend);
|
||||
let before = path(&s, id);
|
||||
let mut ring: Vec<Point> = vec![];
|
||||
for (a, b) in [(corners[0], corners[1]), (corners[1], corners[2]), (corners[2], bend), (bend, corners[3]), (corners[3], corners[0])] {
|
||||
let n = (a.distance(b) / 5.0).ceil();
|
||||
ring.extend((0..n as usize).map(|k| a.lerp(b, k as f64 / n)));
|
||||
}
|
||||
ring.push(corners[0]);
|
||||
smooth_pass(&mut s, &ring);
|
||||
let p = path(&s, id);
|
||||
let sp = &p.subpaths[0];
|
||||
assert!(sp.closed && sp.anchors.len() < before.subpaths[0].anchors.len(), "{} anchors", sp.anchors.len());
|
||||
assert_eq!(sp.anchors[0].p, before.subpaths[0].anchors[0].p, "the path still starts where it did");
|
||||
for (c, t) in corners.iter().zip(&turns) {
|
||||
let at = smooth_turn_at(sp, *c);
|
||||
assert!(at.is_some_and(|a| (a - t).abs() < 0.01), "the corner at {c:?} turning {t}° is kept: {at:?}");
|
||||
}
|
||||
}
|
||||
|
||||
let mut s = session();
|
||||
let (id, corners, bend) = smooth_house(&mut s, false);
|
||||
let before = path(&s, id);
|
||||
smooth_pass(&mut s, &smooth_drag_along(200.0, 190.0, 410.0));
|
||||
let p = path(&s, id);
|
||||
let sp = &p.subpaths[0];
|
||||
assert!(sp.closed && sp.anchors.len() < before.subpaths[0].anchors.len(), "the top is smoothed: {} anchors", sp.anchors.len());
|
||||
for (c, t) in corners.iter().zip(&turns) {
|
||||
let at = smooth_turn_at(sp, *c);
|
||||
assert!(at.is_some_and(|a| (a - t).abs() < 0.01), "part of the path: the corner at {c:?} turning {t}° is kept: {at:?}");
|
||||
}
|
||||
assert!(smooth_turn_at(sp, bend).is_some_and(|t| (t - 30.0).abs() < 0.01), "the bend out of reach stays");
|
||||
}
|
||||
|
||||
/// A Smooth drag over an anchor whose curved legs meet at a corner keeps the corner, taking the turn
|
||||
/// from the directions the curves arrive and leave along, a handle of no length included.
|
||||
#[test]
|
||||
fn smoothing_keeps_a_corner_between_curves() {
|
||||
use kurbo::ParamCurve;
|
||||
let v = Point::new(200.0, 300.0);
|
||||
let with_in = json!({"x": 200.0, "y": 300.0, "in": [170.0, 270.0], "out": [230.0, 270.0]});
|
||||
let no_in = json!({"x": 200.0, "y": 300.0, "out": [230.0, 270.0]});
|
||||
for (corner, first_out) in [(with_in, [130.0, 260.0]), (no_in, [170.0, 230.0])] {
|
||||
let mut s = session();
|
||||
let anchors = [json!({"x": 100.0, "y": 300.0, "out": first_out}), corner, json!({"x": 300.0, "y": 300.0, "in": [270.0, 260.0]})];
|
||||
let id = smooth_test_path(&mut s, &anchors, false);
|
||||
let before = path(&s, id);
|
||||
let turn = smooth_turn_at(&before.subpaths[0], v).unwrap();
|
||||
assert!(turn > 80.0, "{turn}");
|
||||
let (a, b) = (before.subpaths[0].segment(0), before.subpaths[0].segment(1));
|
||||
let mut drag: Vec<Point> = (0..=10).map(|k| a.eval(0.6 + 0.04 * f64::from(k))).collect();
|
||||
drag.extend((1..=10).map(|k| b.eval(0.04 * f64::from(k))));
|
||||
smooth_pass(&mut s, &drag);
|
||||
let at = smooth_turn_at(&path(&s, id).subpaths[0], v);
|
||||
assert!(at.is_some_and(|t| (t - turn).abs() < 0.01), "the corner turning {turn}° is kept: {at:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A corner at the first anchor of the stretch a drag smooths, just out of its reach, keeps its
|
||||
/// place and its turn.
|
||||
#[test]
|
||||
fn a_corner_at_the_end_of_the_smoothed_stretch_stays() {
|
||||
let mut s = session();
|
||||
let mut anchors = vec![json!({"x": 100.0, "y": 300.0}), json!({"x": 200.0, "y": 300.0})];
|
||||
anchors.extend((1..=20).map(|k| json!({"x": if k % 2 == 1 { 201.0 } else { 200.0 }, "y": 300.0 - 5.0 * f64::from(k)})));
|
||||
let id = smooth_test_path(&mut s, &anchors, false);
|
||||
let before = path(&s, id);
|
||||
let turn = smooth_turn_at(&before.subpaths[0], Point::new(200.0, 300.0)).unwrap();
|
||||
let drag: Vec<Point> = (0..=19).map(|k| Point::new(200.0, 287.0 - 5.0 * f64::from(k))).collect();
|
||||
smooth_pass(&mut s, &drag);
|
||||
let p = path(&s, id);
|
||||
let sp = &p.subpaths[0];
|
||||
assert_ne!(p, before, "the jagged leg is smoothed");
|
||||
assert_eq!(sp.anchors[0], before.subpaths[0].anchors[0]);
|
||||
let at = smooth_turn_at(sp, Point::new(200.0, 300.0));
|
||||
assert!(at.is_some_and(|t| (t - turn).abs() < 0.01), "the corner turning {turn}° stays: {at:?}");
|
||||
}
|
||||
|
||||
/// A Smooth drag over corners it keeps, with nothing else to smooth, changes nothing and adds no
|
||||
/// undo step: an open path's corner and a square's four corners.
|
||||
#[test]
|
||||
fn a_smooth_drag_that_only_meets_corners_adds_no_undo_step() {
|
||||
let mut s = session();
|
||||
let (id, v, drag) = smooth_corner_path(&mut s, 90.0, 1);
|
||||
let before = path(&s, id);
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
assert_eq!(smooth_pass_ids(&mut s, &drag), json!([]), "a corner at {v:?}");
|
||||
assert_eq!(path(&s, id), before);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
|
||||
let square = [(100.0, 100.0), (200.0, 100.0), (200.0, 200.0), (100.0, 200.0)].map(|(x, y)| json!({"x": x, "y": y}));
|
||||
let id = smooth_test_path(&mut s, &square, true);
|
||||
let before = path(&s, id);
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let mut ring = smooth_drag_along(100.0, 100.0, 200.0);
|
||||
ring.extend((1..=20).map(|k| Point::new(200.0, 100.0 + 5.0 * f64::from(k))));
|
||||
ring.extend(smooth_drag_along(200.0, 100.0, 200.0).into_iter().rev().skip(1));
|
||||
ring.extend((1..=20).map(|k| Point::new(100.0, 200.0 - 5.0 * f64::from(k))));
|
||||
assert_eq!(smooth_pass_ids(&mut s, &ring), json!([]), "a square");
|
||||
assert_eq!(path(&s, id), before);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn join_tool_joins_two_lines() {
|
||||
let mut s = session();
|
||||
@@ -5178,6 +5523,47 @@ fn pencil_extend_closes_within_400_pt_at_any_fidelity() {
|
||||
}
|
||||
}
|
||||
|
||||
/// `closed`, when given, decides whether a stroke continuing an open path closes it (the tools
|
||||
/// send it by Close Paths When Ends Are Within): false leaves it open even ending on the other end;
|
||||
/// true closes one ending 50 pt away with a straight segment back, the stroke's end kept, and one
|
||||
/// ending 2 pt away on the other end itself.
|
||||
#[test]
|
||||
fn pencil_extend_closes_as_closed_says() {
|
||||
let mut s = session();
|
||||
for (end, closed, ends_on_start) in [([0i32, 0], false, false), ([0, 50], true, false), ([0, 2], true, true)] {
|
||||
let l = line(&mut s, 0.0, 0.0, 200.0, 0.0);
|
||||
let points = json!([[200, 0], [200, 100], [100, 150], end]);
|
||||
let p = json!({"points": points, "fidelity": 1.5, "closed": closed, "extend": {"id": l.0}, "keepSelected": false});
|
||||
s.execute("path.freehand", &p).unwrap();
|
||||
let pd = path(&s, l);
|
||||
let sp = &pd.subpaths[0];
|
||||
assert_eq!(sp.closed, closed, "ending at {end:?}");
|
||||
if closed {
|
||||
let stroke_end = Point::new(f64::from(end[0]), f64::from(end[1]));
|
||||
let kept = sp.anchors.iter().any(|a| a.p.distance(stroke_end) < 1e-6);
|
||||
assert_eq!(kept, !ends_on_start, "ending at {end:?}: {:?}", sp.anchors);
|
||||
let on_start = sp.anchors.iter().filter(|a| a.p.distance(Point::new(0.0, 0.0)) < 1e-6).count();
|
||||
assert_eq!((sp.anchors[0].p, on_start), (Point::new(0.0, 0.0), 1), "ending at {end:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A continued path closed from away from its other end closes with a straight segment, even when
|
||||
/// that end carries a handle the open path didn't use.
|
||||
#[test]
|
||||
fn pencil_extend_closes_far_away_with_a_straight_segment() {
|
||||
let mut s = session();
|
||||
let anchors = json!([{"x": 0, "y": 0, "in": [-40, 30]}, {"x": 200, "y": 0}]);
|
||||
let l = NodeId(s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap());
|
||||
let points = json!([[200, 0], [200, 100], [100, 150], [0, 50]]);
|
||||
let p = json!({"points": points, "fidelity": 1.5, "closed": true, "extend": {"id": l.0}, "keepSelected": false});
|
||||
s.execute("path.freehand", &p).unwrap();
|
||||
let sp = path(&s, l).subpaths[0].clone();
|
||||
assert!(sp.closed);
|
||||
let (first, last) = (sp.anchors[0], sp.anchors[sp.anchors.len() - 1]);
|
||||
assert_eq!((first.h_in, last.h_out), (first.p, last.p), "the closing segment has no handles: {:?}", sp.anchors);
|
||||
}
|
||||
|
||||
/// At Fidelity 0.01 short, one-point and repeated-point strokes still draw or are refused, never
|
||||
/// crash, and what they draw has finite anchors.
|
||||
#[test]
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Node, NodeKind};
|
||||
use vectorcraft_geom::{Affine, PathData, Rect};
|
||||
use vectorcraft_geom::{Affine, PathData, Point, Rect};
|
||||
|
||||
use crate::*;
|
||||
|
||||
@@ -320,16 +320,16 @@ fn global_edit_needs_one_supported_object() {
|
||||
let t = NodeId(s.execute("text.create", &json!({"x": 50, "y": 500, "text": "Hi"})).unwrap()["id"].as_u64().unwrap());
|
||||
sel(&mut s, &[t]);
|
||||
assert!(matches!(s.execute("select.globalEdit", &json!({})), Err(EngineError::Disabled(..))), "type");
|
||||
let lone = rect(&mut s, 0.0, 500.0, 30.0, 70.0);
|
||||
// A copy turned a quarter turn (70 × 30) is not taken: rotated copies are not matched, and the
|
||||
// message says so.
|
||||
let turned = rect(&mut s, 200.0, 500.0, 30.0, 70.0);
|
||||
sel(&mut s, &[turned]);
|
||||
s.execute("object.rotate", &json!({"angle": 90})).unwrap();
|
||||
// A reflected copy is not taken, and the message says so.
|
||||
let lone = kite(&mut s, 0.0, 500.0, 1.0);
|
||||
let mirrored = kite(&mut s, 200.0, 500.0, 1.0);
|
||||
sel(&mut s, &[mirrored]);
|
||||
s.execute("object.reflect", &json!({"axis": "vertical"})).unwrap();
|
||||
sel(&mut s, &[lone]);
|
||||
let e = s.execute("select.globalEdit", &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("no similar objects") && e.contains("rotated"), "{e}");
|
||||
assert!(e.contains("no similar objects") && e.contains("reflected copies are not matched") && !e.contains("rotated"), "{e}");
|
||||
assert!(s.doc().unwrap().global_edit.is_none());
|
||||
assert!(crate::cmd::globaledit::highlights(&s).is_empty(), "and it is not highlighted");
|
||||
// A group holding type is not offered, though another such group exists.
|
||||
let group = |s: &mut Session, x: f64| {
|
||||
let p = rect(s, x, 100.0, 10.0, 10.0);
|
||||
@@ -851,3 +851,159 @@ fn groups_nested_as_deep_as_a_document_allows_are_edited_together() {
|
||||
s.execute("paint.setFill", &json!({"color": "#12ab34"})).unwrap();
|
||||
assert_eq!(fill(&s, other_inner), "#12ab34");
|
||||
}
|
||||
|
||||
/// A four-sided path with no symmetry, `k` times the size, its box's top left near (`x`, `y`): a
|
||||
/// 30 × 70 rectangle whose first anchor is moved.
|
||||
fn kite(s: &mut Session, x: f64, y: f64, k: f64) -> NodeId {
|
||||
let id = rect(s, x, y, 30.0 * k, 70.0 * k);
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0]]})).unwrap();
|
||||
s.execute("path.moveAnchors", &json!({"dx": 10.0 * k, "dy": -20.0 * k})).unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
/// Rotate `id` by `deg` (counter-clockwise) about the centre of its box → that rotation.
|
||||
fn rotate(s: &mut Session, id: NodeId, deg: f64) -> Affine {
|
||||
let c = bounds(s, id).center();
|
||||
sel(s, &[id]);
|
||||
s.execute("object.rotate", &json!({"angle": deg})).unwrap();
|
||||
Affine::rotate_about(-deg.to_radians(), c)
|
||||
}
|
||||
|
||||
/// A kite at the origin side of the page, a copy of it turned a quarter turn, and a copy at half
|
||||
/// the size turned by 30° → the three and the transforms that lay the first on the other two.
|
||||
fn turned_kites(s: &mut Session) -> ([NodeId; 3], [Affine; 2]) {
|
||||
let a = kite(s, 0.0, 100.0, 1.0);
|
||||
let (b, c) = (kite(s, 200.0, 100.0, 1.0), kite(s, 400.0, 100.0, 0.5));
|
||||
let quarter = rotate(s, b, 90.0) * Affine::translate((200.0, 0.0));
|
||||
let small = rotate(s, c, 30.0) * Affine::translate((400.0, 100.0)) * Affine::scale(0.5) * Affine::translate((0.0, -100.0));
|
||||
assert!(placed(s, a, b, quarter) && placed(s, a, c, small), "the copies as made");
|
||||
([a, b, c], [quarter, small])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn start_global_edit_takes_rotated_copies_and_an_edit_reaches_each_turned_by_its_angle() {
|
||||
let mut s = session();
|
||||
let ([a, b, c], [quarter, small]) = turned_kites(&mut s);
|
||||
sel(&mut s, &[a]);
|
||||
assert_eq!(crate::cmd::globaledit::highlights(&s).len(), 2, "both are highlighted before the start");
|
||||
assert_eq!(s.execute("select.globalEditOptions", &json!({})).unwrap()["count"], 3);
|
||||
assert_eq!(start(&mut s, a, json!({})), [a, b, c]);
|
||||
let before = (*s.doc().unwrap().doc).clone();
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
// An anchor moved on the selected kite moves on each copy along the copy's own directions.
|
||||
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]]})).unwrap();
|
||||
s.execute("path.moveAnchors", &json!({"dx": 12, "dy": 5})).unwrap();
|
||||
assert!(placed(&s, a, b, quarter), "the quarter-turned copy");
|
||||
assert!(placed(&s, a, c, small), "the smaller copy turned by 30°");
|
||||
assert!(!placed(&s, a, b, Affine::translate((200.0, 0.0))), "the copy is still turned");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step");
|
||||
crate::tests_large_edits::undo_gives_back(&mut s, &before);
|
||||
// A move of the whole kite to the right moves the quarter-turned copy up (counter-clockwise).
|
||||
sel(&mut s, &[a]);
|
||||
let was = bounds(&s, b);
|
||||
s.execute("object.move", &json!({"dx": 10, "dy": 0})).unwrap();
|
||||
let now = bounds(&s, b);
|
||||
assert!((now.x0 - was.x0).abs() < 1e-6 && (now.y0 - (was.y0 - 10.0)).abs() < 1e-6, "{was:?} → {now:?}");
|
||||
assert!(placed(&s, a, b, quarter) && placed(&s, a, c, small), "each copy lies on the kite as before");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rotated_copy_leads_an_edit_as_any_other_member_does() {
|
||||
let mut s = session();
|
||||
let ([a, b, c], [quarter, small]) = turned_kites(&mut s);
|
||||
// Started on the turned copy, and edited from the smaller one.
|
||||
assert_eq!(start(&mut s, b, json!({})), [b, a, c]);
|
||||
s.execute("select.anchors", &json!({"id": c.0, "anchors": [[0, 2]]})).unwrap();
|
||||
s.execute("path.moveAnchors", &json!({"dx": 3, "dy": -4})).unwrap();
|
||||
assert!(placed(&s, a, b, quarter) && placed(&s, a, c, small));
|
||||
// A fill reaches the turned copies as it is.
|
||||
s.execute("paint.setFill", &json!({"color": "#12ab34"})).unwrap();
|
||||
assert_eq!((fill(&s, a), fill(&s, b)), ("#12ab34".to_string(), "#12ab34".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn size_takes_a_rotated_copy_of_the_same_size_and_other_shapes_stay_out() {
|
||||
let mut s = session();
|
||||
let ([a, b, c], _) = turned_kites(&mut s);
|
||||
// A quarter-turned copy is 70 × 30 by its box: it has the size of the 30 × 70 kite all the same.
|
||||
assert_eq!(start(&mut s, a, json!({"size": true})), [a, b], "not the half-size copy {c}");
|
||||
s.execute("select.globalEdit", &json!({})).unwrap();
|
||||
// A copy turned and then stretched, and one whose anchor was moved, are other shapes.
|
||||
let stretched = kite(&mut s, 0.0, 300.0, 1.0);
|
||||
rotate(&mut s, stretched, 30.0);
|
||||
s.execute("object.scale", &json!({"sx": 150, "sy": 100})).unwrap();
|
||||
let bent = kite(&mut s, 200.0, 300.0, 1.0);
|
||||
rotate(&mut s, bent, 45.0);
|
||||
s.execute("select.anchors", &json!({"id": bent.0, "anchors": [[0, 2]]})).unwrap();
|
||||
s.execute("path.moveAnchors", &json!({"dx": 1, "dy": 0})).unwrap();
|
||||
// A copy turned by half a turn and by a full turn in two steps.
|
||||
let half = kite(&mut s, 400.0, 300.0, 1.0);
|
||||
rotate(&mut s, half, 180.0);
|
||||
let full = kite(&mut s, 600.0, 300.0, 1.0);
|
||||
rotate(&mut s, full, 135.0);
|
||||
rotate(&mut s, full, 225.0);
|
||||
assert_eq!(start(&mut s, a, json!({})), [a, b, c, half, full], "not the stretched {stretched} nor the bent {bent}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_square_whose_anchors_were_turned_is_a_rotated_copy() {
|
||||
let mut s = session();
|
||||
let [a, b, ..] = squares(&mut s);
|
||||
let turn = rotate(&mut s, b, 90.0) * Affine::translate((300.0, 0.0));
|
||||
assert_eq!(start(&mut s, a, json!({})).len(), 3, "the turned square is still taken, with the small one");
|
||||
// The first anchor of the turned square lies at another corner, and that is the one that moves.
|
||||
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0]]})).unwrap();
|
||||
s.execute("path.moveAnchors", &json!({"dx": 10, "dy": 30})).unwrap();
|
||||
assert!(placed(&s, a, b, turn));
|
||||
assert!(!placed(&s, a, b, Affine::translate((300.0, 0.0))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotated_groups_are_like_the_group_and_an_edit_inside_one_reaches_the_others_turned() {
|
||||
let mut s = session();
|
||||
let (g, [sq, dot, _]) = card(&mut s, 0.0, 1.0);
|
||||
let (copy, [csq, cdot, cbar]) = card(&mut s, 300.0, 1.0);
|
||||
let turn = rotate(&mut s, copy, 90.0) * Affine::translate((300.0, 0.0));
|
||||
// The same three objects, each turned in place: not the group turned as a whole.
|
||||
let (apart, objects) = card(&mut s, 500.0, 1.0);
|
||||
for id in objects {
|
||||
rotate(&mut s, id, 90.0);
|
||||
}
|
||||
assert_eq!(start(&mut s, g, json!({})), [g, copy], "not the group {apart} whose objects were turned one by one");
|
||||
sel(&mut s, &[dot]);
|
||||
s.execute("paint.setFill", &json!({"color": "#12ab34"})).unwrap();
|
||||
assert_eq!(fill(&s, cdot), "#12ab34");
|
||||
sel(&mut s, &[sq]);
|
||||
s.execute("object.setBounds", &json!({"height": 20, "reference": 0})).unwrap();
|
||||
assert!(placed(&s, sq, csq, turn), "the square in the turned group is halved along the group's own direction");
|
||||
assert_eq!(kids(&s, copy), [csq, cdot, cbar], "each object keeps its id");
|
||||
s.execute("select.globalEdit", &json!({})).unwrap();
|
||||
// An object inside one group takes the object at its place in the turned group, as the
|
||||
// objects of rotated copies of a group are edited together.
|
||||
assert_eq!(start(&mut s, sq, json!({})), [sq, csq]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rotated_symbol_instance_is_taken_and_a_reflected_one_is_not() {
|
||||
let mut s = session();
|
||||
let r = rect(&mut s, 0.0, 0.0, 40.0, 40.0);
|
||||
let first = NodeId(s.execute("symbol.new", &json!({"ids": [r.0], "name": "Tile"})).unwrap()["id"].as_u64().unwrap());
|
||||
let place =
|
||||
|s: &mut Session, x: f64| NodeId(s.execute("symbol.place", &json!({"name": "Tile", "x": x, "y": 300})).unwrap()["id"].as_u64().unwrap());
|
||||
let (turned, mirrored) = (place(&mut s, 200.0), place(&mut s, 400.0));
|
||||
sel(&mut s, &[turned]);
|
||||
s.execute("object.rotate", &json!({"angle": 30, "origin": [220, 320]})).unwrap();
|
||||
sel(&mut s, &[mirrored]);
|
||||
s.execute("object.reflect", &json!({"axis": "vertical", "origin": [420, 320]})).unwrap();
|
||||
assert_eq!(start(&mut s, first, json!({})), [first, turned], "not the reflected instance {mirrored}");
|
||||
let xf = |s: &Session, id: NodeId| match node(s, id).kind {
|
||||
NodeKind::SymbolInstance { xf, .. } => xf,
|
||||
_ => panic!("not an instance"),
|
||||
};
|
||||
let was = xf(&s, turned);
|
||||
s.execute("object.move", &json!({"dx": 10, "dy": 0})).unwrap();
|
||||
// The instance turned by 30° counter-clockwise moves along its own direction.
|
||||
let moved = Affine::rotate((-30f64).to_radians()) * Point::new(10.0, 0.0);
|
||||
let (now, want) = (xf(&s, turned).as_coeffs(), (Affine::translate(moved.to_vec2()) * was).as_coeffs());
|
||||
assert!(now.iter().zip(want).all(|(p, q)| (p - q).abs() < 1e-6), "{now:?} vs {want:?}");
|
||||
}
|
||||
|
||||
@@ -79,18 +79,29 @@ fn the_source_stays_as_it_is() {
|
||||
assert!(s.doc().unwrap().is_dirty(), "the new document is unsaved");
|
||||
}
|
||||
|
||||
/// An index that names no state, or is not a whole number, is an error and changes nothing: no
|
||||
/// document, no step and no Untitled number is used up.
|
||||
/// An index that names no state (`no history state N`), or is not a whole number ("`index` must be
|
||||
/// a whole number"), is an error and changes nothing: no document, no step and no Untitled number
|
||||
/// is used up.
|
||||
#[test]
|
||||
fn a_bad_index_is_an_error_and_changes_nothing() {
|
||||
let mut s = three_rectangles_one_undone();
|
||||
let source = s.doc().unwrap().doc.clone();
|
||||
let untitled = s.peek_untitled();
|
||||
let bad: [Value; 8] = [json!(4), json!(99), json!(-1), json!(1.5), json!("1"), json!(true), json!([1]), json!(u64::MAX)];
|
||||
for index in bad {
|
||||
let bad: [(Value, bool); 8] = [
|
||||
(json!(4), true),
|
||||
(json!(99), true),
|
||||
(json!(u64::MAX), true),
|
||||
(json!(-1), false),
|
||||
(json!(1.5), false),
|
||||
(json!("1"), false),
|
||||
(json!(true), false),
|
||||
(json!([1]), false),
|
||||
];
|
||||
for (index, whole) in bad {
|
||||
let e = s.execute(CMD, &json!({ "index": index })).unwrap_err();
|
||||
assert!(matches!(e, EngineError::BadParams { .. }), "{index}: {e}");
|
||||
assert!(e.to_string().contains(&format!("no history state {index}")), "{e}");
|
||||
let want = if whole { format!("no history state {index}") } else { "`index` must be a whole number".to_string() };
|
||||
assert_eq!(e.to_string(), format!("invalid parameters for `{CMD}`: {want}"), "{index}");
|
||||
assert_eq!(s.documents().len(), 1, "{index}");
|
||||
assert_eq!(steps(&s), (2, 1), "{index}");
|
||||
assert!(Arc::ptr_eq(&s.doc().unwrap().doc, &source), "{index}");
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
//! Inline graphics in text: `text.insertInline`, editing over them, undo, following their symbol.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::text::INLINE_CHAR;
|
||||
use vectorcraft_doc::{Node, NodeId, NodeKind, TextObject};
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
|
||||
|
||||
use crate::*;
|
||||
@@ -325,6 +329,143 @@ fn a_symbol_that_shows_itself_inline_is_an_empty_slot() {
|
||||
assert_eq!(d.inline_art_bounds("Loop"), None);
|
||||
}
|
||||
|
||||
/// A rectangle `r` filled black, without a stroke.
|
||||
fn filled_rect(d: &mut vectorcraft_doc::Document, r: Rect) -> Arc<Node> {
|
||||
let look = vectorcraft_doc::Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0);
|
||||
Arc::new(Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(r), look))
|
||||
}
|
||||
|
||||
/// An instance of symbol `name` placed by `xf`.
|
||||
fn symbol_instance(d: &mut vectorcraft_doc::Document, name: &str, xf: Affine) -> Arc<Node> {
|
||||
Arc::new(Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: name.into(), xf }))
|
||||
}
|
||||
|
||||
/// Gives symbol `name` the art `art` in a group, adding the symbol when there is none of that name.
|
||||
fn set_symbol_art(d: &mut vectorcraft_doc::Document, name: &str, art: Vec<Arc<Node>>) {
|
||||
let art = Arc::new(Node::group(d.alloc_id(), art));
|
||||
match d.symbols.iter_mut().find(|x| x.name == name) {
|
||||
Some(x) => x.art = art,
|
||||
None => d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: name.into(), art }),
|
||||
}
|
||||
}
|
||||
|
||||
/// An inline graphic of a symbol whose art holds an instance of another symbol is sized by that
|
||||
/// symbol's art, and follows it when it changes, through undo, redo and a saved copy.
|
||||
#[test]
|
||||
fn an_inline_graphic_follows_the_art_of_a_symbol_nested_in_its_symbol() {
|
||||
let mut s = session();
|
||||
s.edit("Symbols", |d, _| {
|
||||
let far = filled_rect(d, Rect::new(100.0, 0.0, 160.0, 20.0));
|
||||
set_symbol_art(d, "Far", vec![far]);
|
||||
let inner = symbol_instance(d, "Far", Affine::IDENTITY);
|
||||
set_symbol_art(d, "Holder", vec![inner]);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let id = text(&mut s, "ab");
|
||||
let w0 = obj(&s, id).bounds().unwrap().width();
|
||||
s.execute("text.insertInline", &json!({"id": id.0, "at": 1, "symbol": "Holder", "scale": 1})).unwrap();
|
||||
let wide = Some(Rect::new(100.0, 0.0, 160.0, 20.0));
|
||||
let t = obj(&s, id);
|
||||
assert_eq!(inline_bounds(&t), wide);
|
||||
// 20 pt tall at 20 pt type and 3 times as wide: the text grows by 60 pt.
|
||||
let w1 = t.bounds().unwrap().width();
|
||||
assert!((w1 - w0 - 60.0).abs() < 1.5, "{w0} → {w1}");
|
||||
// Far redefined as a 10 × 40 rectangle: the graphic is 20 pt tall and 5 pt wide.
|
||||
s.edit("Redefine Far", |d, _| {
|
||||
let tall = filled_rect(d, Rect::new(0.0, 0.0, 10.0, 40.0));
|
||||
set_symbol_art(d, "Far", vec![tall]);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let tall = Some(Rect::new(0.0, 0.0, 10.0, 40.0));
|
||||
let t = obj(&s, id);
|
||||
assert_eq!(inline_bounds(&t), tall);
|
||||
assert_eq!(s.doc().unwrap().doc.symbol_art_bounds("Holder"), tall);
|
||||
let w2 = t.bounds().unwrap().width();
|
||||
assert!((w2 - w0 - 5.0).abs() < 1.5, "{w0} → {w2}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(inline_bounds(&obj(&s, id)), wide);
|
||||
assert!((obj(&s, id).bounds().unwrap().width() - w1).abs() < 1e-6);
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(inline_bounds(&obj(&s, id)), tall);
|
||||
// Opening a saved copy measures it the same way.
|
||||
let doc = (*s.doc().unwrap().doc).clone();
|
||||
let mut back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap();
|
||||
back.title = "copy".into();
|
||||
let mut s2 = Session::new();
|
||||
s2.add_document(back, None);
|
||||
assert_eq!(inline_bounds(&obj(&s2, id)), tall);
|
||||
assert!((obj(&s2, id).bounds().unwrap().width() - w2).abs() < 1e-6);
|
||||
}
|
||||
|
||||
/// Symbol C shows Holder inline, Holder holds an instance of B, and B shows A inline: with the
|
||||
/// symbols listed C, Holder, B, A, a change to A reaches C through B's and Holder's new sizes.
|
||||
#[test]
|
||||
fn symbols_are_resolved_after_the_symbols_their_instances_show() {
|
||||
let mut s = session();
|
||||
circle_symbol(&mut s, "A", 10.0);
|
||||
let t = text(&mut s, "z");
|
||||
s.execute("text.insertInline", &json!({"id": t.0, "at": 0, "symbol": "A"})).unwrap();
|
||||
s.execute("symbol.new", &json!({"name": "B", "ids": [t.0]})).unwrap();
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
s.edit("Holder", |d, _| {
|
||||
let inner = symbol_instance(d, "B", Affine::IDENTITY);
|
||||
set_symbol_art(d, "Holder", vec![inner]);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let t = text(&mut s, "z");
|
||||
s.execute("text.insertInline", &json!({"id": t.0, "at": 0, "symbol": "Holder"})).unwrap();
|
||||
s.execute("symbol.new", &json!({"name": "C", "ids": [t.0]})).unwrap();
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
s.edit("Reverse the symbols", |d, _| {
|
||||
d.symbols.reverse();
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let h0 = s.doc().unwrap().doc.symbol_art_bounds("Holder");
|
||||
redefine_as_wide_ellipse(&mut s, "A");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_ne!(d.symbol_art_bounds("Holder"), h0);
|
||||
assert_eq!(inline_bounds(&art_text(&s, "C")), d.symbol_art_bounds("Holder"));
|
||||
}
|
||||
|
||||
/// Symbol A holds an instance of B, and B's type shows A inline: the size of each would depend on
|
||||
/// itself, so both are empty slots, and stay so through later edits.
|
||||
#[test]
|
||||
fn a_symbol_that_shows_itself_through_an_instance_is_an_empty_slot() {
|
||||
let mut s = session();
|
||||
circle_symbol(&mut s, "A", 10.0);
|
||||
let t = text(&mut s, "ab");
|
||||
s.execute("text.insertInline", &json!({"id": t.0, "at": 1, "symbol": "A"})).unwrap();
|
||||
s.execute("symbol.new", &json!({"name": "B", "ids": [t.0]})).unwrap();
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
s.edit("A holds B", |d, _| {
|
||||
let inner = symbol_instance(d, "B", Affine::IDENTITY);
|
||||
set_symbol_art(d, "A", vec![inner]);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let line = text(&mut s, "x");
|
||||
s.execute("text.insertInline", &json!({"id": line.0, "at": 0, "symbol": "A"})).unwrap();
|
||||
for _ in 0..2 {
|
||||
for name in ["A", "B"] {
|
||||
assert_eq!(s.doc().unwrap().doc.inline_art_bounds(name), None, "{name}");
|
||||
}
|
||||
assert_eq!(inline_bounds(&art_text(&s, "B")), None);
|
||||
assert_eq!(inline_bounds(&obj(&s, line)), None);
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
|
||||
}
|
||||
let _ = s.execute("document.serialize", &json!({"format": "png"})).unwrap();
|
||||
// Redefined without the instance, A is on no cycle.
|
||||
redefine_as_wide_ellipse(&mut s, "A");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.inline_art_bounds("A").is_some());
|
||||
assert_eq!(inline_bounds(&art_text(&s, "B")), d.symbol_art_bounds("A"));
|
||||
assert_eq!(inline_bounds(&obj(&s, line)), d.symbol_art_bounds("A"));
|
||||
}
|
||||
|
||||
/// A list paragraph that starts with an inline graphic draws its bullet before the graphic, and
|
||||
/// live SVG text writes the bullet.
|
||||
#[test]
|
||||
|
||||
@@ -611,15 +611,18 @@ fn edit_copy_and_cut_read_the_recorded_artboards() {
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert!(matches!(s.execute(id, &json!({})), Err(crate::EngineError::Disabled(..))), "{id}");
|
||||
let before = documents(&s);
|
||||
for bad in [
|
||||
json!({"selectedArtboards": [9]}),
|
||||
json!({"selectedArtboards": []}),
|
||||
json!({"selectedArtboards": "1"}),
|
||||
json!({"selectedArtboards": null}),
|
||||
json!({"selectedArtboards": [1], "art": "yes"}),
|
||||
for (bad, want) in [
|
||||
(json!({"selectedArtboards": [9]}), "no such artboard"),
|
||||
(json!({"selectedArtboards": []}), "`selectedArtboards` must be a non-empty list of artboard indices"),
|
||||
(json!({"selectedArtboards": "1"}), "`selectedArtboards` must be a list of artboard indices"),
|
||||
(json!({"selectedArtboards": null}), "`selectedArtboards` must be a list of artboard indices"),
|
||||
(json!({"selectedArtboards": [1, "0"]}), "`selectedArtboards` must contain whole numbers"),
|
||||
(json!({"selectedArtboards": [1, -1]}), "`selectedArtboards` must contain whole numbers"),
|
||||
(json!({"selectedArtboards": [1], "art": "yes"}), "`art` must be true or false"),
|
||||
] {
|
||||
let err = s.execute(id, &bad).unwrap_err().to_string();
|
||||
assert!(err.contains(id) || err.contains("no such artboard"), "{id} {bad}: {err}");
|
||||
assert!(err.ends_with(want), "{id} {bad}: {err}");
|
||||
assert!(err.contains(id) || want == "no such artboard", "{id} {bad}: {err}");
|
||||
assert_eq!(documents(&s), before, "{id} {bad}");
|
||||
assert!(s.clipboard.artboards.is_empty(), "{id} {bad}");
|
||||
}
|
||||
|
||||
@@ -733,6 +733,38 @@ fn a_library_character_style_linked_to_a_missing_swatch_is_added_unlinked() {
|
||||
assert_eq!((r["style"].as_str(), r["existing"].as_bool()), (Some("Accent"), Some(true)));
|
||||
}
|
||||
|
||||
/// A gradient stop linked to a spot swatch with process plates, as a library file can hold one.
|
||||
fn plated_stops() -> Value {
|
||||
let ink = vectorcraft_color::Color::cmyk(0.0, 0.5, 0.0, 0.0);
|
||||
json!([
|
||||
{"offset": 0, "color": vectorcraft_color::Color::WHITE},
|
||||
{"offset": 1, "color": ink, "swatch": "Brand", "tint": 0.5, "plates": [0.3, 0, 0, 0]}
|
||||
])
|
||||
}
|
||||
|
||||
/// Library gradients and the gradient stops of library character styles lose their links to
|
||||
/// swatches the document does not have together with the process plates those links print with.
|
||||
#[test]
|
||||
fn library_stops_unlinked_from_their_swatch_keep_no_process_plates() {
|
||||
let data = json!({
|
||||
"name": "Plated",
|
||||
"gradients": [{"name": "Glow", "gradient": {"gradient": {"kind": "Linear", "stops": plated_stops()}, "angle": 0}}],
|
||||
"charStyles": [{"name": "Accent", "attrs": {"fill": {"type": "gradient", "gradient": {"kind": "Linear", "stops": plated_stops()}}}}]
|
||||
});
|
||||
let mut s = session();
|
||||
let lib = run(&mut s, "library.import", json!({"data": data.to_string()}))["id"].as_str().unwrap().to_string();
|
||||
let a = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 20}))["id"].clone();
|
||||
run(&mut s, "select.set", json!({"ids": [a]}));
|
||||
run(&mut s, "library.use", json!({"library": lib, "kind": "fillGradient", "item": "Glow"}));
|
||||
let st = gradient(&paint_of(&s, &a, false)).gradient.stops[1].clone();
|
||||
assert_eq!((st.swatch.as_deref(), st.tint, st.plates), (None, 1.0, None), "{st:?}");
|
||||
run(&mut s, "library.addToCharacterStyles", json!({"library": lib, "item": "Accent"}));
|
||||
let style = s.doc().unwrap().doc.char_styles.iter().find(|c| c.name == "Accent").map(|c| c.attrs["fill"].clone()).unwrap();
|
||||
let fill = serde_json::from_value::<vectorcraft_color::Paint>(style).unwrap();
|
||||
let st = gradient(&fill).gradient.stops[1].clone();
|
||||
assert_eq!((st.swatch.as_deref(), st.tint, st.plates), (None, 1.0, None), "{st:?}");
|
||||
}
|
||||
|
||||
/// A library style is compared with the document's in the form the document stores it in, so a
|
||||
/// style whose file writes a size as a whole number is reused, by Add to Character Styles and by a
|
||||
/// click alike.
|
||||
|
||||
@@ -213,6 +213,24 @@ fn spot_stops_with_process_plates_export_both_in_device_n_shadings() {
|
||||
assert_eq!(gradient(&s, id).gradient.stops[1].plates, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_a_spot_swatch_takes_the_process_plates_of_the_stops_it_unlinks() {
|
||||
let (mut s, id) = setup();
|
||||
let plated = json!({"stops": [{"offset": 0, "color": "#ffffff"}, {"offset": 1, "swatch": "Ink", "tint": 50, "plates": [0.3, 0, 0, 0]}]});
|
||||
run(&mut s, "paint.editGradient", plated.clone());
|
||||
run(&mut s, "swatch.new", json!({"name": "Glow", "gradient": plated}));
|
||||
let linked = gradient(&s, id).gradient.stops[1].clone();
|
||||
assert_eq!((linked.swatch.as_deref(), linked.plates), (Some("Ink"), Some([0.3, 0.0, 0.0, 0.0])));
|
||||
run(&mut s, "swatch.delete", json!({"name": "Ink"}));
|
||||
// The art's stop and the gradient swatch's stop keep the color they show, unlinked and without plates.
|
||||
let Paint::Gradient(sw) = doc(&s).swatch("Glow").unwrap().paint.clone() else { panic!("a gradient swatch") };
|
||||
for st in [&gradient(&s, id).gradient.stops[1], &sw.gradient.stops[1]] {
|
||||
assert_eq!((st.color, st.swatch.as_deref(), st.tint, st.plates), (linked.color, None, 1.0, None), "{st:?}");
|
||||
}
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(gradient(&s, id).gradient.stops[1], linked, "undo brings back the link and the plates");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn radial_spot_gradients_mixed_with_other_inks_export_as_device_n_shadings() {
|
||||
let (mut s, _) = setup();
|
||||
|
||||
@@ -768,6 +768,223 @@ fn nested_objects_that_repeat_ids_open_with_ids_of_their_own() {
|
||||
assert!(image(&s, layer_image).link.is_some(), "the image in the layers stays linked");
|
||||
}
|
||||
|
||||
/// The files of the linked images that the stored brushes of [`brush_links`] are made of: a scatter
|
||||
/// brush's, an art brush's and a pattern brush's side tile.
|
||||
const BRUSHED: [(&str, &str, &str); 3] = [("scatter.png", "scatter", "Specks"), ("art.png", "art", "Band"), ("side.png", "pattern", "Frame")];
|
||||
|
||||
/// A document whose stored brushes are made of [`BRUSHED`]'s linked images in `dir`. The art
|
||||
/// brush's image is still in the layers too, so its brush art repeats that object's id; the other
|
||||
/// two images were cleared from the layers.
|
||||
fn brush_links(dir: &Folder) -> (Session, NodeId) {
|
||||
for (i, (name, ..)) in (0u8..).zip(BRUSHED) {
|
||||
write(&dir.file(name), &png(20, 10, [30 + 60 * i, 120, 90]));
|
||||
}
|
||||
let mut s = session();
|
||||
let mut kept = NodeId(0);
|
||||
for (name, kind, brush) in BRUSHED {
|
||||
let id = place(&mut s, &dir.file(name));
|
||||
s.execute("brush.new", &json!({"type": kind, "name": brush, "ids": [id.0]})).unwrap();
|
||||
if kind == "art" {
|
||||
kept = id;
|
||||
} else {
|
||||
s.execute("edit.clear", &json!({"ids": [id.0]})).unwrap();
|
||||
}
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
(s, kept)
|
||||
}
|
||||
|
||||
/// The image in the art of stored brush `name`, as the document stores it.
|
||||
fn brush_image(s: &Session, name: &str) -> ImageObject {
|
||||
let b = vectorcraft_brush::find(&s.doc().unwrap().doc, name).unwrap_or_else(|| panic!("no brush {name}"));
|
||||
let mut found = None;
|
||||
b.art()[0].walk(&mut |n| {
|
||||
if let (None, NodeKind::Image(im)) = (&found, &n.kind) {
|
||||
found = Some((**im).clone());
|
||||
}
|
||||
});
|
||||
found.unwrap_or_else(|| panic!("no image in brush {name}"))
|
||||
}
|
||||
|
||||
/// The id of the image in the art of stored brush `name`, as the document stores it.
|
||||
fn brush_image_id(s: &Session, name: &str) -> u64 {
|
||||
let b = vectorcraft_brush::find(&s.doc().unwrap().doc, name).unwrap();
|
||||
let mut found = None;
|
||||
b.art()[0].walk(&mut |n| {
|
||||
if found.is_none() && matches!(n.kind, NodeKind::Image(_)) {
|
||||
found = Some(n.id.0);
|
||||
}
|
||||
});
|
||||
found.unwrap()
|
||||
}
|
||||
|
||||
/// Images in the art of stored brushes are listed after the others, one row per image in each brush tile,
|
||||
/// each with an id no other object has (the layer tree keeps its own), the brush named as what holds it; Check
|
||||
/// Links and the missing filter count them, and the ids stay the same from one list to the next.
|
||||
#[test]
|
||||
fn links_in_stored_brush_art_are_listed_and_checked_with_ids() {
|
||||
let dir = Folder::new("brush-ids");
|
||||
let (mut s, kept) = brush_links(&dir);
|
||||
let list = s.execute("links.list", &json!({})).unwrap();
|
||||
let rows = list["links"].as_array().unwrap();
|
||||
let owners: Vec<(&str, &Value)> = rows.iter().map(|r| (r["name"].as_str().unwrap(), &r["owner"])).collect();
|
||||
let library = vectorcraft_brush::library(&s.doc().unwrap().doc);
|
||||
let index = |name: &str| library.iter().position(|b| b.name == name).unwrap();
|
||||
assert_eq!(
|
||||
owners,
|
||||
[
|
||||
("art.png", &Value::Null),
|
||||
("scatter.png", &json!({"kind": "brush", "name": "Specks", "index": index("Specks")})),
|
||||
("art.png", &json!({"kind": "brush", "name": "Band", "index": index("Band")})),
|
||||
("side.png", &json!({"kind": "brush", "name": "Frame", "index": index("Frame"), "tile": "side"})),
|
||||
],
|
||||
"{list}"
|
||||
);
|
||||
assert_eq!(rows[0]["id"], json!(kept.0), "the layer tree keeps its ids: {list}");
|
||||
let ids: std::collections::BTreeSet<u64> = rows.iter().map(|r| r["id"].as_u64().unwrap()).collect();
|
||||
assert_eq!(ids.len(), 4, "{list}");
|
||||
assert!(!ids.contains(&0), "{list}");
|
||||
assert!(rows.iter().all(|r| r["status"] == "ok" && r["linked"] == true), "{list}");
|
||||
assert_eq!(s.execute("links.list", &json!({})).unwrap(), list, "the same ids each time");
|
||||
let other = super::rect(&mut s, 0.0, 0.0, 5.0, 5.0);
|
||||
s.execute("edit.clear", &json!({"ids": [other.0]})).unwrap();
|
||||
assert_eq!(s.execute("links.list", &json!({})).unwrap(), list, "the same ids after other objects are made");
|
||||
let check = s.execute("links.check", &json!({})).unwrap();
|
||||
assert_eq!(check["links"].as_array().unwrap().len(), 3, "{check}");
|
||||
std::fs::remove_file(dir.file("side.png")).unwrap();
|
||||
let check = s.execute("links.check", &json!({})).unwrap();
|
||||
assert_eq!(check["missing"].as_u64(), Some(1), "{check}");
|
||||
let missing = s.execute("links.list", &json!({"show": "missing"})).unwrap();
|
||||
assert_eq!(missing["links"][0]["id"], rows[3]["id"], "{missing}");
|
||||
}
|
||||
|
||||
/// Every links command takes the id of an image in a stored brush's art and acts on that brush's art,
|
||||
/// never on the image in the layers whose id the art repeated: Link Info, Go To (which clears the
|
||||
/// selection and names the brush), Placement Options, Relink, Update and Embed. The ids each change
|
||||
/// gives the art are kept in the library, so the next list names the same rows.
|
||||
#[test]
|
||||
fn links_commands_act_on_images_in_stored_brush_art_by_id() {
|
||||
let dir = Folder::new("brush-act");
|
||||
let (mut s, kept) = brush_links(&dir);
|
||||
let band = row_id_owned(&mut s, "art.png", "brush");
|
||||
assert_ne!(band, kept.0);
|
||||
let info = s.execute("links.info", &json!({"id": band})).unwrap();
|
||||
assert_eq!((info["fileName"].as_str(), info["status"].as_str(), info["id"].as_u64()), (Some("art.png"), Some("ok"), Some(band)), "{info}");
|
||||
s.execute("select.set", &json!({"ids": [kept.0]})).unwrap();
|
||||
let go = s.execute("links.goTo", &json!({"id": band})).unwrap();
|
||||
assert_eq!(
|
||||
(go["onCanvas"].clone(), go["owner"]["kind"].clone(), go["owner"]["name"].clone()),
|
||||
(json!(false), json!("brush"), json!("Band")),
|
||||
"{go}"
|
||||
);
|
||||
assert!(s.doc().unwrap().selection.objects.is_empty(), "nothing on the canvas is selected");
|
||||
s.execute("links.placementOptions", &json!({"ids": [band], "preserve": "fit"})).unwrap();
|
||||
assert_eq!(s.execute("links.placementOptions", &json!({"ids": [band]})).unwrap()["placement"]["preserve"], "fit");
|
||||
assert_eq!(brush_image(&s, "Band").placement.preserve, vectorcraft_doc::links::Preserve::Fit);
|
||||
assert_eq!(brush_image_id(&s, "Band"), band, "the brush keeps the id it is listed by");
|
||||
assert_ne!(image(&s, kept).placement.preserve, vectorcraft_doc::links::Preserve::Fit, "the image in the layers is left as it was");
|
||||
// Relink: the brush's image shows the new file; the image in the layers keeps its file.
|
||||
let other = dir.file("other.png");
|
||||
write(&other, &png(40, 20, BLUE));
|
||||
let r = s.execute("links.relink", &json!({"ids": [band], "path": other})).unwrap();
|
||||
assert_eq!(r["relinked"], json!([band]), "{r}");
|
||||
assert_eq!(brush_image(&s, "Band").link.unwrap().path, other);
|
||||
assert_eq!(image(&s, kept).link.unwrap().path, dir.file("art.png"));
|
||||
assert_eq!(row_id_owned(&mut s, "other.png", "brush"), band, "{}", s.execute("links.list", &json!({})).unwrap());
|
||||
// Update: a changed file is read again for the scatter brush's image.
|
||||
let dots = row_id_owned(&mut s, "scatter.png", "brush");
|
||||
let changed = png(30, 30, RED);
|
||||
write(&dir.file("scatter.png"), &changed);
|
||||
let r = s.execute("links.update", &json!({"ids": [dots]})).unwrap();
|
||||
assert_eq!(r["updated"], json!([dots]), "{r}");
|
||||
assert_eq!(brush_image(&s, "Specks").link.unwrap().size, Some(changed.len() as u64));
|
||||
// Embed: the pattern brush's side tile keeps its pixels and no longer links.
|
||||
let frame = row_id_owned(&mut s, "side.png", "brush");
|
||||
let r = s.execute("links.embed", &json!({"ids": [frame]})).unwrap();
|
||||
assert_eq!(r["embedded"], json!([frame]), "{r}");
|
||||
assert!(brush_image(&s, "Frame").link.is_none());
|
||||
let embedded = s.execute("links.list", &json!({"show": "embedded"})).unwrap();
|
||||
assert_eq!(embedded["links"][0]["id"], json!(frame), "{embedded}");
|
||||
// Relink All Instances takes the image in the layers and the brush's image of the same file.
|
||||
let r = s.execute("links.relink", &json!({"ids": [kept.0], "path": dir.file("scatter.png"), "scope": "all"})).unwrap();
|
||||
assert_eq!(r["relinked"], json!([kept.0]), "{r}");
|
||||
let r = s.execute("links.relink", &json!({"ids": [dots], "path": other, "scope": "all"})).unwrap();
|
||||
let mut relinked: Vec<u64> = r["relinked"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
|
||||
relinked.sort();
|
||||
let mut both = vec![kept.0, dots];
|
||||
both.sort();
|
||||
assert_eq!(relinked, both, "{r}");
|
||||
assert_eq!(image(&s, kept).link.unwrap().path, other);
|
||||
// One undo step puts the brushes back as they were.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(brush_image(&s, "Specks").link.unwrap().path, dir.file("scatter.png"));
|
||||
}
|
||||
|
||||
/// The id of the `links.list` row of file `name` whose owner is of `kind`.
|
||||
fn row_id_owned(s: &mut Session, name: &str, kind: &str) -> u64 {
|
||||
let list = s.execute("links.list", &json!({})).unwrap();
|
||||
let row = list["links"].as_array().unwrap().iter().find(|r| r["name"] == name && r["owner"]["kind"] == kind);
|
||||
row.unwrap_or_else(|| panic!("{name} in {kind}: {list}"))["id"].as_u64().unwrap()
|
||||
}
|
||||
|
||||
/// A document saved with links in its stored brushes opens with them reported by the ids the list
|
||||
/// gives them, and a library entry that does not read as a brush is kept as it was.
|
||||
#[test]
|
||||
fn links_in_stored_brush_art_open_by_id_and_unreadable_entries_stay() {
|
||||
let dir = Folder::new("brush-open");
|
||||
let (mut s, _) = brush_links(&dir);
|
||||
let odd = json!({"name": "Odd", "type": "unknown", "art": {"id": 3}});
|
||||
s.edit("Odd brush", |d, _| {
|
||||
if let Some(list) = d.unknown.get_mut(vectorcraft_brush::DOC_KEY).and_then(Value::as_array_mut) {
|
||||
list.push(odd.clone());
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let path = dir.file("poster.vectorcraft");
|
||||
save(&mut s, &path);
|
||||
std::fs::remove_file(dir.file("scatter.png")).unwrap();
|
||||
let r = open(&mut s, &path);
|
||||
let dots = row_id_owned(&mut s, "scatter.png", "brush");
|
||||
assert_eq!(r["missingLinks"][0]["ids"], json!([dots]), "{r}");
|
||||
assert_eq!(brush_image_id(&s, "Specks"), dots, "the library keeps the ids opening gave");
|
||||
let band = row_id_owned(&mut s, "art.png", "brush");
|
||||
s.execute("links.embed", &json!({"ids": [band]})).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let stored = doc.unknown[vectorcraft_brush::DOC_KEY].as_array().unwrap();
|
||||
assert_eq!(stored.last(), Some(&odd), "the unreadable entry is left as it was");
|
||||
assert!(doc.mounted_art.is_empty());
|
||||
}
|
||||
|
||||
/// The Color Mask of an image in a stored brush's art is made again for the new pixels when Update
|
||||
/// reads the image's changed file.
|
||||
#[test]
|
||||
fn updating_an_image_in_stored_brush_art_makes_its_color_mask_again() {
|
||||
let dir = Folder::new("brush-mask");
|
||||
let path = dir.file("logo.png");
|
||||
write(&path, &png(12, 10, RED));
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &path);
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
let hide_white = json!({"background": "colors", "colors": "#ffffff", "contiguous": false, "tolerance": 0, "softness": 0});
|
||||
s.execute("addon.image.colorMask", &hide_white).unwrap();
|
||||
s.execute("brush.new", &json!({"type": "scatter", "name": "Masked", "ids": [id.0]})).unwrap();
|
||||
s.execute("edit.clear", &json!({"ids": [id.0]})).unwrap();
|
||||
write(&path, &png(14, 10, BLUE));
|
||||
let row = row_id_owned(&mut s, "logo.png", "brush");
|
||||
let r = s.execute("links.update", &json!({"ids": [row]})).unwrap();
|
||||
assert_eq!(r["updated"], json!([row]), "{r}");
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let brush = vectorcraft_brush::find(doc, "Masked").unwrap();
|
||||
let mut masks = vec![];
|
||||
brush.art()[0].walk(&mut |n| {
|
||||
if let (NodeKind::Image(im), Some(m)) = (&n.kind, Document::color_mask_of(n)) {
|
||||
masks.push((m.made_for(im), doc.images.contains_key(&m.key)));
|
||||
}
|
||||
});
|
||||
assert_eq!(masks, [(true, true)], "the mask is made for the new pixels");
|
||||
}
|
||||
|
||||
/// An image that Placement Options clip, alone in a group the user made, goes into a new clip group
|
||||
/// inside that group when its file grows, in the layers and in a symbol's art; the user's group
|
||||
/// stays a plain group.
|
||||
|
||||
@@ -126,6 +126,30 @@ fn bad_sides_radii_and_keys_are_errors() {
|
||||
assert_eq!(corners(&s, id).0, [0.0; 4]);
|
||||
}
|
||||
|
||||
/// Saved steps play as they did before `sides` and `radius` were checked: a negative radius
|
||||
/// removes the rounding, a whole side count outside 3 to 1000 is brought into that range, and a
|
||||
/// fractional or negative side count is ignored.
|
||||
#[test]
|
||||
fn saved_steps_with_out_of_range_sides_or_radius_still_play() {
|
||||
let (mut s, id) = session();
|
||||
let poly = NodeId(s.execute("shape.polygon", &json!({"cx": 200, "cy": 200, "radius": 80, "sides": 6})).unwrap()["id"].as_u64().unwrap());
|
||||
let replay = |s: &mut Session, p: Value| s.replay("object.setLiveShape", &p).unwrap_or_else(|e| panic!("{p}: {e}"));
|
||||
run(&mut s, json!({"id": id.0, "radius": 6}));
|
||||
replay(&mut s, json!({"id": id.0, "radius": -4}));
|
||||
assert_eq!(corners(&s, id).0, [0.0; 4]);
|
||||
let sides = |s: &Session| match node_path(s, poly).1 {
|
||||
Some(LiveShape::Polygon { sides, .. }) => sides,
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
for (n, want) in [(json!(2), 3), (json!(1001), 1000), (json!(2.5), 1000), (json!(-1), 1000), (json!(5.0), 5)] {
|
||||
replay(&mut s, json!({"ids": [poly.0], "sides": n}));
|
||||
assert_eq!(sides(&s), want, "{n}");
|
||||
}
|
||||
// A direct call still refuses them.
|
||||
assert!(s.execute("object.setLiveShape", &json!({"id": id.0, "radius": -4})).is_err());
|
||||
assert!(s.execute("object.setLiveShape", &json!({"ids": [poly.0], "sides": 2})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_selected_corners_round_alone_and_stay_selected() {
|
||||
let (mut s, id) = session();
|
||||
|
||||
@@ -1979,9 +1979,10 @@ fn fit_to_artwork_bounds_fits_each_artboard_to_its_own_art() {
|
||||
assert_eq!(boards(&s), [Rect::new(100.0, 100.0, 1050.0, 280.0), was[1], was[2]], "the first artboard by default");
|
||||
}
|
||||
|
||||
/// Artboard Options and Fit to Selected Art fail with `no such artboard` on an `index` that names
|
||||
/// no artboard (past the last, negative, fractional, a string or null), and the artboards stay as
|
||||
/// they were. Artboard Options needs an `index`; Fit to Selected Art without one fits the first
|
||||
/// Artboard Options and Fit to Selected Art fail with `no such artboard` on a whole-number `index`
|
||||
/// past the last artboard, with "`index` must be a whole number" on one that is negative,
|
||||
/// fractional or a string, and with `missing index` on a null one, and the artboards stay as they
|
||||
/// were. Artboard Options needs an `index`; Fit to Selected Art without one fits the first
|
||||
/// artboard.
|
||||
#[test]
|
||||
fn artboard_options_and_fit_to_selected_art_refuse_an_index_that_names_no_artboard() {
|
||||
@@ -1992,9 +1993,16 @@ fn artboard_options_and_fit_to_selected_art_refuse_an_index_that_names_no_artboa
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
let boards = |s: &Session| s.doc().unwrap().doc.artboards.iter().map(|a| a.rect).collect::<Vec<_>>();
|
||||
let (was, n) = (boards(&s), undo_len(&s));
|
||||
for index in [json!(99), json!(-1), json!(1.5), json!("1"), Value::Null] {
|
||||
for (index, error) in [
|
||||
(json!(99), None),
|
||||
(json!(-1), Some("`index` must be a whole number")),
|
||||
(json!(1.5), Some("`index` must be a whole number")),
|
||||
(json!("1"), Some("`index` must be a whole number")),
|
||||
(Value::Null, Some("missing index")),
|
||||
] {
|
||||
for (cmd, p) in [("artboard.setProps", json!({"index": index, "width": 300})), ("artboard.fitToSelection", json!({"index": index}))] {
|
||||
assert_eq!(s.execute(cmd, &p).unwrap_err().to_string(), "no such artboard", "{cmd} {p}");
|
||||
let want = error.map_or_else(|| "no such artboard".to_string(), |e| format!("invalid parameters for `{cmd}`: {e}"));
|
||||
assert_eq!(s.execute(cmd, &p).unwrap_err().to_string(), want, "{cmd} {p}");
|
||||
}
|
||||
}
|
||||
let e = s.execute("artboard.setProps", &json!({"width": 300})).unwrap_err().to_string();
|
||||
|
||||
@@ -683,6 +683,9 @@ fn the_new_document_links_from_the_profile_file() {
|
||||
/// is a warning.
|
||||
#[test]
|
||||
fn a_profile_brings_the_color_profile_its_file_carries() {
|
||||
if !super::in_own_process("tests::newdoc::a_profile_brings_the_color_profile_its_file_carries") {
|
||||
return;
|
||||
}
|
||||
use vectorcraft_color::cms;
|
||||
let (mut s, dir) = with_profiles("icc");
|
||||
let builtin = cms::profiles().into_iter().find(|p| p.kind == cms::ProfileKind::Rgb && p.builtin && p.name != cms::SRGB).unwrap();
|
||||
|
||||
@@ -257,6 +257,27 @@ fn shadows_under_a_groups_or_an_objects_transform_expand_appearance_as_the_canva
|
||||
}
|
||||
}
|
||||
|
||||
/// Each copy of a Transform effect draws the drop shadow listed before the effect under itself,
|
||||
/// scaled with it, and Expand Appearance keeps those shadows: the square (20..40) has its shadow
|
||||
/// 20 pt to its right, and its copy scaled 200 % and moved 80 pt down (10..50 across, 90..130
|
||||
/// down) has its own 40 pt to its right.
|
||||
#[test]
|
||||
fn each_copys_shadow_expands_as_the_canvas_draws_it() {
|
||||
let mut s = session();
|
||||
run(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 20, "height": 20}));
|
||||
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
|
||||
run(&mut s, "paint.setStroke", json!({"none": true}));
|
||||
let shadow = json!({"x": 20, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"});
|
||||
run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "params": shadow}));
|
||||
run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": {"scaleH": 200, "scaleV": 200, "moveV": 80, "copies": 1}}));
|
||||
let before = render(&s);
|
||||
assert_eq!(before.pixel(70, 110), [0, 255, 0, 255], "the copy's shadow");
|
||||
run(&mut s, "effect.expandAppearance", json!({}));
|
||||
let after = render(&s);
|
||||
let diff = differing(&before, &after, 64);
|
||||
assert_eq!(diff, 0, "{diff} pixels differ");
|
||||
}
|
||||
|
||||
/// A group's Transform effect runs after its member's own Offset Path in Expand Appearance as on
|
||||
/// the canvas: the 100 pt square offset to 120 pt and scaled by half expands 60 pt wide.
|
||||
#[test]
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user