mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-17 04:25:18 +00:00
Merge main into fix/erase-region-params-refused
This commit is contained in:
@@ -235,11 +235,7 @@ pub fn has_multi(s: &Session) -> std::result::Result<(), String> {
|
||||
/// editing and symbol editing mode isolate their own layer, which does not count here; an object
|
||||
/// isolated inside them counts.
|
||||
pub(crate) fn ordinary_isolation(st: &crate::DocState) -> Option<vectorcraft_doc::NodeId> {
|
||||
st.isolation.filter(|l| {
|
||||
!st.doc.pattern_edit.as_ref().is_some_and(|e| e.layer == *l)
|
||||
&& !st.doc.mask_edit.as_ref().is_some_and(|e| e.layer == *l)
|
||||
&& !st.doc.symbol_edit.as_ref().is_some_and(|e| e.layer == *l)
|
||||
})
|
||||
vectorcraft_tools::ordinary_isolation(&st.doc, st.isolation)
|
||||
}
|
||||
/// Objects are selected ([`has_selection`]), and in isolation mode ([`ordinary_isolation`]) at
|
||||
/// least one of them is inside the isolated object: Object › Lock's and Object › Hide's items.
|
||||
|
||||
@@ -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, and on a graph label the new paint of its characters and rows for every label of its kind (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, and on a graph's axis line, tick mark or radar ring its rows for every line 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, 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}",
|
||||
"{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, and on a graph's axis line, tick mark or radar ring its rows for every line 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, 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]}",
|
||||
"{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, and on a graph's axis line, tick mark or radar ring its rows for every line 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
|
||||
),
|
||||
@@ -79,7 +79,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Apply Fill to Stroke",
|
||||
["Object", "Plug-ins", "Color Effects"],
|
||||
None,
|
||||
"{ids?|id?, skipNone?: bool} each target's top stroke takes its own top fill, as it is (a colour in its model, a global or spot colour linked at its tint, a gradient or pattern with its placement, None); a stroke given paint at width 0 gets 1 pt, as Swap Fill and Stroke does. Type: each run's stroke takes its own fill, and while the Type tool has characters selected (no ids), only those. A graph's labels keep the paint when the graph is drawn again. On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row (exceptions: docs/mcp.md). skipNone: leave alone a target whose fill is None. A target whose stroke already has that paint is left as it is, and when nothing changes no undo step is recorded. The default stroke takes the default fill the same way → {objects}",
|
||||
"{ids?|id?, skipNone?: bool} each target's top stroke takes its own top fill, as it is (a colour in its model, a global or spot colour linked at its tint, a gradient or pattern with its placement, None); a stroke given paint at width 0 gets 1 pt, as Swap Fill and Stroke does. Type: each run's stroke takes its own fill, and while the Type tool has characters selected (no ids), only those. A graph's labels keep the paint when the graph is drawn again, and its axis lines, tick marks and radar rings keep their new rows for every line of their kind. On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row (exceptions: docs/mcp.md). skipNone: leave alone a target whose fill is None. A target whose stroke already has that paint is left as it is, and when nothing changes no undo step is recorded. The default stroke takes the default fill the same way → {objects}",
|
||||
has_doc,
|
||||
|s, p| copy_paint(s, p, true)
|
||||
),
|
||||
@@ -259,7 +259,10 @@ fn copy_paint(s: &mut Session, p: &Value, to_stroke: bool) -> Result<Value> {
|
||||
// The graph keeps the paint its series marks and labels now have.
|
||||
let series = super::super::appearance::capture_series_paint_writes(&before, d, &ids, &written);
|
||||
let labels = super::super::graph::capture_label_styles(d, &ids, ©_run);
|
||||
Ok(objects + usize::from(series || labels))
|
||||
let painted: Vec<NodeId> = written.iter().map(|(id, _)| *id).collect();
|
||||
// A line keeps the paint written to it, also when it already showed it, and the rest stays as its kind keeps it.
|
||||
let lines = super::super::graph::capture_line_changes(&before, d, &painted) | super::super::graph::capture_line_paint_writes(d, &written);
|
||||
Ok(objects + usize::from(series || labels || lines))
|
||||
})?;
|
||||
}
|
||||
// The defaults for new art change the same way, as Swap Fill and Stroke changes them.
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! anchor edits, Split / Add Points at Crossings, Slide Anchor Along Path, the Corner Tool's corners
|
||||
//! ([`corners`]), the Parametric Shape Tool's shapes ([`shape`]), the Shared Edge Merge Tool's
|
||||
//! merges with Keep Shared Points Together ([`shared_edge`]), Divide into Dashes, Expand Dashes
|
||||
//! into Paths and Trim at Crossings ([`trim`]).
|
||||
//! into Paths, Trim at Crossings ([`trim`]) and Tangent Circle ([`tangent_circle`]).
|
||||
//! Its tools, panels and submenu (Object › Plug-ins › Path Precision Tools) are the tools crate's
|
||||
//! and the UI's.
|
||||
|
||||
@@ -12,6 +12,7 @@ mod corners;
|
||||
mod effect_tests;
|
||||
mod shape;
|
||||
mod shared_edge;
|
||||
mod tangent_circle;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
mod trim;
|
||||
@@ -180,6 +181,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
v.extend(corners::specs());
|
||||
v.extend(shared_edge::specs());
|
||||
v.extend(trim::specs());
|
||||
v.extend(tangent_circle::specs());
|
||||
v
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
//! Tangent Circle: draw the circles that touch two paths or compound paths at a given radius, or
|
||||
//! that touch three of them. The geometry is the pathops crate's
|
||||
//! ([`tangent_circles`](vectorcraft_pathops::addons::pathtools::tangent_circles)).
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, LiveShape, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Affine, FillRule, PathData};
|
||||
use vectorcraft_pathops::addons::pathtools::{self as pt, TangentCircleError};
|
||||
|
||||
use super::super::super::{CommandSpec, bad, checked_ids_or_selection, checked_ids_param, cmd, has_selection, index_opt, number_or};
|
||||
use crate::{Result, Session};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
/// The command.
|
||||
pub(crate) const COMMAND: &str = "addon.pathtools.tangentCircle";
|
||||
/// The undo step's name.
|
||||
const LABEL: &str = "Tangent Circle";
|
||||
/// The radius the command takes with two shapes (pt).
|
||||
const RADIUS: std::ops::RangeInclusive<f64> = 0.01..=1e6;
|
||||
|
||||
pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"addon.pathtools.tangentCircle",
|
||||
"Tangent Circle",
|
||||
["Object", "Plug-ins", "Path Precision Tools"],
|
||||
None,
|
||||
"{ids?: [id…] (two or three paths or compound paths; default: the selection), radius?: pt 0.01..1000000 (needed with two shapes; three shapes set the radius themselves and take none), circle?: 0..64 (0: every circle found; n: only the nth, the circles listed by radius, then top to bottom, then left to right)} draw the circles that touch two shapes and have the radius, or that touch three shapes. A circle touches a shape when it meets the shape's outline without crossing it, the whole outline lying outside the circle or inside it: it is tangent to the outline at a smooth point and passes through a corner or an open end; the members of a compound path count as one outline. With three shapes, circles up to 64 times the diagonal of the box around the shapes' anchors and handles are found. Each circle is a new ellipse with the current paint on top of the current layer, or of the isolated group (inside an isolated compound path they join it); the circles are selected; one undo step. Locked and hidden shapes given by `ids` are read and left as they are. No circle is an error, and so are more than 64 (shapes touched along a whole curve, such as two concentric circles), an object named twice, shapes at one point or too small for the radius, and more than 2000 segments in all; the document is then unchanged → {ids, found (how many circles touch the shapes)}",
|
||||
has_selection,
|
||||
tangent_circle
|
||||
)]
|
||||
}
|
||||
|
||||
/// The paths of path or compound path `id`: itself, or its members.
|
||||
fn paths_of(d: &Document, id: NodeId) -> Result<Vec<&PathData>> {
|
||||
let value = id.0;
|
||||
let n = d.node(id).ok_or_else(|| bad(COMMAND, format!("no such object id {value}")))?;
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, .. } => Ok(vec![path]),
|
||||
NodeKind::Compound { children, .. } => Ok(children.iter().filter_map(|c| c.path_data()).collect()),
|
||||
_ => Err(bad(COMMAND, format!("object {value} is not a path or compound path"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The outlines of `ids`, each path's or compound path's subpaths together; counted before they
|
||||
/// are copied.
|
||||
fn outlines(d: &Document, ids: &[NodeId]) -> Result<Vec<PathData>> {
|
||||
let parts = ids.iter().map(|id| paths_of(d, *id)).collect::<Result<Vec<_>>>()?;
|
||||
let segments: usize = parts.iter().flatten().map(|p| pt::tangent_circle_segments(p)).sum();
|
||||
if segments > pt::MAX_TANGENT_CIRCLE_SEGMENTS {
|
||||
return Err(bad(COMMAND, TOO_COMPLEX));
|
||||
}
|
||||
Ok(parts.iter().map(|paths| PathData::new(paths.iter().flat_map(|p| p.subpaths.iter().cloned()).collect())).collect())
|
||||
}
|
||||
|
||||
const TOO_COMPLEX: &str = "the shapes are too complex: at most 2000 segments in all";
|
||||
|
||||
fn tangent_circle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// A repeated id is refused before the ids inside another given one are dropped.
|
||||
if p.get("ids").is_some_and(|v| !v.is_null()) {
|
||||
let mut seen = HashSet::new();
|
||||
if checked_ids_param(s, p, "ids", COMMAND)?.iter().any(|id| !seen.insert(*id)) {
|
||||
return Err(bad(COMMAND, "`ids` names an object twice"));
|
||||
}
|
||||
}
|
||||
let ids = checked_ids_or_selection(s, p, COMMAND)?;
|
||||
let d = &s.doc()?.doc;
|
||||
if !(2..=3).contains(&ids.len()) {
|
||||
return Err(bad(COMMAND, "select two or three paths or compound paths"));
|
||||
}
|
||||
let outlines = outlines(d, &ids)?;
|
||||
if outlines.iter().any(|o| o.subpaths.iter().all(|sp| sp.anchors.is_empty())) {
|
||||
return Err(bad(COMMAND, "a shape has no outline"));
|
||||
}
|
||||
let given_radius = p.get("radius").is_some_and(|v| !v.is_null());
|
||||
let radius = number_or(p, "radius", 0.0, COMMAND)?;
|
||||
let radius = match (ids.len(), given_radius) {
|
||||
(2, true) if RADIUS.contains(&radius) => Some(radius),
|
||||
(2, true) => return Err(bad(COMMAND, "`radius` must be from 0.01 to 1000000 pt")),
|
||||
(2, false) => return Err(bad(COMMAND, "two shapes need a `radius`")),
|
||||
(_, true) => return Err(bad(COMMAND, "three shapes set the radius themselves: leave `radius` out")),
|
||||
(_, false) => None,
|
||||
};
|
||||
let pick = index_opt(p, "circle", COMMAND)?.unwrap_or(0);
|
||||
if pick > pt::MAX_TANGENT_CIRCLES {
|
||||
return Err(bad(COMMAND, "`circle` must be from 0 to 64"));
|
||||
}
|
||||
let refs: Vec<&PathData> = outlines.iter().collect();
|
||||
let found = pt::tangent_circles(&refs, radius).map_err(|e| match e {
|
||||
// Every outline has points (checked above): all at one place, or too small for the radius.
|
||||
TangentCircleError::BadInput => bad(COMMAND, "these shapes are too small to measure"),
|
||||
// The segments were counted above: the search itself went past its limits.
|
||||
TangentCircleError::TooComplex => bad(COMMAND, "these shapes take too long to search"),
|
||||
TangentCircleError::TooMany => bad(COMMAND, "more than 64 circles touch these shapes: they may touch along a whole curve"),
|
||||
})?;
|
||||
if found.is_empty() {
|
||||
return Err(bad(COMMAND, "no circle touches these shapes"));
|
||||
}
|
||||
let chosen: Vec<pt::Circle> = match pick {
|
||||
0 => found.clone(),
|
||||
n => match found.get(n - 1) {
|
||||
Some(c) => vec![*c],
|
||||
None => {
|
||||
let found = found.len();
|
||||
return Err(bad(COMMAND, format!("`circle` is past the last circle found ({found})")));
|
||||
}
|
||||
},
|
||||
};
|
||||
// Path art: inside an isolated compound path, the circles join it and take its appearance.
|
||||
let parent = s.doc()?.target_parent_for_path()?;
|
||||
let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
|
||||
let ids = s.edit(LABEL, |d, sel| {
|
||||
let mut ids = vec![];
|
||||
for c in &chosen {
|
||||
let (r, at) = (c.radius, c.center);
|
||||
let live = LiveShape::Ellipse { w: 2.0 * r, h: 2.0 * r, pie: (0.0, 360.0), xf: Affine::translate((at.x - r, at.y - r)) };
|
||||
let kind = NodeKind::Path { path: live.to_path(), rule: FillRule::NonZero, live: Some(Box::new(live)), clipping: false, guide: false };
|
||||
let mut n = Node::new(d.alloc_id(), kind);
|
||||
look.apply(d, &mut n);
|
||||
ids.push(n.id);
|
||||
d.insert(parent, usize::MAX, n)?;
|
||||
}
|
||||
sel.set(ids.iter().copied());
|
||||
Ok(ids)
|
||||
})?;
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "found": found.len() }))
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
//! Tangent Circle: circles drawn for two shapes and a radius or three shapes, one undo step, the
|
||||
//! current paint, compound paths, one circle picked, and the errors that leave the document as it was.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{LiveShape, NodeId, NodeKind};
|
||||
use vectorcraft_geom::Point;
|
||||
|
||||
use super::COMMAND;
|
||||
use crate::Session;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn ellipse(s: &mut Session, x: f64, y: f64, w: f64, h: f64, rotation: f64) -> u64 {
|
||||
let id = s.execute("shape.ellipse", &json!({"x": x, "y": y, "width": w, "height": h, "rotation": rotation})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
fn circle(s: &mut Session, cx: f64, cy: f64, r: f64) -> u64 {
|
||||
ellipse(s, cx - r, cy - r, 2.0 * r, 2.0 * r, 0.0)
|
||||
}
|
||||
|
||||
fn undo_steps(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn count(s: &Session) -> usize {
|
||||
s.doc().unwrap().doc.layers[0].children().unwrap().len()
|
||||
}
|
||||
|
||||
/// The circle path `id` is: (center, radius) from its live ellipse.
|
||||
fn drawn(s: &Session, id: &Value) -> (Point, f64) {
|
||||
let n = s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap();
|
||||
let NodeKind::Path { live: Some(live), .. } = &n.kind else { panic!("not a live shape") };
|
||||
let LiveShape::Ellipse { w, h, xf, .. } = live.as_ref() else { panic!("not an ellipse") };
|
||||
assert!((w - h).abs() < 1e-9);
|
||||
(*xf * Point::new(w / 2.0, h / 2.0), w / 2.0)
|
||||
}
|
||||
|
||||
fn refused(s: &mut Session, p: Value) -> String {
|
||||
let (steps, objects) = (undo_steps(s), count(s));
|
||||
let e = s.execute(COMMAND, &p).unwrap_err().to_string();
|
||||
assert_eq!((undo_steps(s), count(s)), (steps, objects), "{p} changed the document");
|
||||
e
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_circles_and_a_radius_draw_every_circle_as_one_step() {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 100.0, 100.0, 10.0);
|
||||
let b = circle(&mut s, 130.0, 100.0, 10.0);
|
||||
s.execute("paint.setFill", &json!({"color": "#12ab34"})).unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute(COMMAND, &json!({"ids": [a, b], "radius": 20})).unwrap();
|
||||
assert_eq!(r["found"], 6);
|
||||
let ids = r["ids"].as_array().unwrap().clone();
|
||||
assert_eq!(ids.len(), 6);
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
assert_eq!(count(&s), 8);
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!(st.selection.objects.len(), 6);
|
||||
let fill = st.doc.node(NodeId(ids[0].as_u64().unwrap())).unwrap().appearance.fill_paint();
|
||||
assert_eq!(fill, s.paint.fill);
|
||||
// Outside both: 30 from each center, at x = 115.
|
||||
let h = (900.0f64 - 225.0).sqrt();
|
||||
let centers: Vec<(Point, f64)> = ids.iter().map(|id| drawn(&s, id)).collect();
|
||||
for want in [Point::new(115.0, 100.0 - h), Point::new(115.0, 100.0 + h)] {
|
||||
// Within the Bézier circles' own error (0.0273% of the radius) of the ideal answer.
|
||||
assert!(centers.iter().any(|(c, r)| (*c - want).hypot() < 0.02 && (r - 20.0).abs() < 1e-9), "{centers:?}");
|
||||
}
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(count(&s), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_circles_and_one_picked() {
|
||||
let mut s = session();
|
||||
let ids = [circle(&mut s, 100.0, 100.0, 10.0), circle(&mut s, 180.0, 100.0, 10.0), circle(&mut s, 100.0, 160.0, 10.0)];
|
||||
s.execute("select.set", &json!({"ids": ids})).unwrap();
|
||||
// The selection: all eight, smallest first; the first is the one outside all three, about the
|
||||
// circumcenter (140, 130), 50 from each center.
|
||||
let r = s.execute(COMMAND, &json!({"circle": 1})).unwrap();
|
||||
assert_eq!(r["found"], 8);
|
||||
let one = r["ids"].as_array().unwrap();
|
||||
assert_eq!(one.len(), 1);
|
||||
let (c, radius) = drawn(&s, &one[0]);
|
||||
assert!((c - Point::new(140.0, 130.0)).hypot() < 0.05 && (radius - 40.0).abs() < 0.05, "{c:?} {radius}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": ids})).unwrap();
|
||||
assert_eq!(s.execute(COMMAND, &json!({})).unwrap()["ids"].as_array().unwrap().len(), 8);
|
||||
assert!(refused(&mut s, json!({"ids": ids, "circle": 9})).contains("past the last circle found (8)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compound_rotated_and_locked_shapes() {
|
||||
let mut s = session();
|
||||
// A ring as a compound path, and an ellipse turned 30° inside its hole.
|
||||
let outer = circle(&mut s, 200.0, 150.0, 80.0);
|
||||
let inner = circle(&mut s, 200.0, 150.0, 60.0);
|
||||
s.execute("select.set", &json!({"ids": [outer, inner]})).unwrap();
|
||||
let ring = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
let oval = ellipse(&mut s, 180.0, 140.0, 40.0, 20.0, 30.0);
|
||||
s.execute("select.set", &json!({"ids": [oval]})).unwrap();
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [ring]})).unwrap();
|
||||
s.execute("object.hide", &json!({})).unwrap();
|
||||
let r = s.execute(COMMAND, &json!({"ids": [ring, oval], "radius": 22})).unwrap();
|
||||
let ids = r["ids"].as_array().unwrap();
|
||||
// In the hole, 38 from the center, and 22 from the oval (reaching 42 along its long axis and
|
||||
// 32 along its short one): two by each end of the oval.
|
||||
assert_eq!(ids.len(), 4, "{r}");
|
||||
for id in ids {
|
||||
let (c, radius) = drawn(&s, id);
|
||||
assert!(((c - Point::new(200.0, 150.0)).hypot() - (60.0 - radius)).abs() < 0.05, "{c:?}");
|
||||
}
|
||||
// The locked oval and the hidden ring were read and left as they were.
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.node(NodeId(oval)).unwrap().locked);
|
||||
assert!(!d.node(NodeId(ring)).unwrap().visible);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn circles_go_into_an_isolated_group() {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 100.0, 100.0, 10.0);
|
||||
let b = circle(&mut s, 130.0, 100.0, 10.0);
|
||||
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
|
||||
let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.isolate", &json!({"id": group})).unwrap();
|
||||
let r = s.execute(COMMAND, &json!({"ids": [a, b], "radius": 5})).unwrap();
|
||||
let id = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.parent_of(id), Some(NodeId(group)));
|
||||
// On top of the group's art.
|
||||
assert_eq!(d.node(NodeId(group)).unwrap().children().unwrap().last().map(|n| n.id), Some(id));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn circles_join_an_isolated_compound_path() {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 100.0, 100.0, 10.0);
|
||||
let b = circle(&mut s, 130.0, 100.0, 10.0);
|
||||
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
|
||||
let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.isolate", &json!({"id": compound})).unwrap();
|
||||
let members: Vec<u64> = s.doc().unwrap().doc.node(NodeId(compound)).unwrap().children().unwrap().iter().map(|c| c.id.0).collect();
|
||||
let r = s.execute(COMMAND, &json!({"ids": members, "radius": 5})).unwrap();
|
||||
let id = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(NodeId(compound)));
|
||||
// A compound path and one of its own members are taken as the compound path alone: one shape.
|
||||
let e = refused(&mut s, json!({"ids": [compound, members[0]], "radius": 5}));
|
||||
assert!(e.contains("two or three"), "{e}");
|
||||
// A repeated member is refused even though the compound path holds it.
|
||||
let other = circle(&mut s, 300.0, 100.0, 10.0);
|
||||
let e = refused(&mut s, json!({"ids": [compound, members[0], members[0], other], "radius": 5}));
|
||||
assert!(e.contains("twice"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn errors_leave_the_document_unchanged() {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 50.0, 50.0, 10.0);
|
||||
let b = circle(&mut s, 250.0, 50.0, 10.0);
|
||||
let c = circle(&mut s, 150.0, 200.0, 10.0);
|
||||
assert!(refused(&mut s, json!({"ids": [a, b], "radius": 5})).contains("no circle touches"));
|
||||
assert!(refused(&mut s, json!({"ids": [a, b]})).contains("need a `radius`"));
|
||||
assert!(refused(&mut s, json!({"ids": [a, b, c], "radius": 5})).contains("leave `radius` out"));
|
||||
assert!(refused(&mut s, json!({"ids": [a, b], "radius": 0})).contains("0.01"));
|
||||
assert!(refused(&mut s, json!({"ids": [a, b], "radius": "5 mm"})).contains("must be a number"));
|
||||
assert!(refused(&mut s, json!({"ids": [a], "radius": 5})).contains("two or three"));
|
||||
assert!(refused(&mut s, json!({"ids": [a, a], "radius": 5})).contains("twice"));
|
||||
let e = refused(&mut s, json!({"ids": [a, a as f64], "radius": 5}));
|
||||
assert!(e.contains("not a non-negative integer"), "{e}");
|
||||
// Two lone anchors at one place.
|
||||
let dot = |s: &mut Session| s.execute("path.create", &json!({"anchors": [{"x": 5, "y": 5}]})).unwrap()["id"].as_u64().unwrap();
|
||||
let (p, q) = (dot(&mut s), dot(&mut s));
|
||||
assert!(refused(&mut s, json!({"ids": [p, q], "radius": 5})).contains("too small to measure"));
|
||||
assert!(refused(&mut s, json!({"ids": [a, b], "radius": 200, "circle": 65})).contains("from 0 to 64"));
|
||||
assert!(refused(&mut s, json!({"ids": [a, b], "radius": 200, "circle": -1})).contains("whole number"));
|
||||
let t = s.execute("text.create", &json!({"x": 10, "y": 280, "text": "Hi"})).unwrap()["id"].as_u64().unwrap();
|
||||
assert!(refused(&mut s, json!({"ids": [a, t], "radius": 5})).contains("not a path"));
|
||||
let anchors: Vec<Value> = (0..2002).map(|i| json!({"x": i as f64 * 0.1, "y": 250.0 + (i % 2) as f64})).collect();
|
||||
let zigzag = s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap();
|
||||
assert!(refused(&mut s, json!({"ids": [a, zigzag], "radius": 5})).contains("at most 2000 segments"));
|
||||
// Concentric circles touched all the way round.
|
||||
let inner = circle(&mut s, 50.0, 50.0, 40.0);
|
||||
assert!(refused(&mut s, json!({"ids": [a, inner], "radius": 15})).contains("whole curve"));
|
||||
}
|
||||
@@ -1,15 +1,13 @@
|
||||
//! Trim at Crossings: remove the stretch of a path between the places where other paths, or the
|
||||
//! path itself, cross it. The command takes the stretch at a point, every stretch a rectangle
|
||||
//! touches, or every stretch a line through some points crosses. It works on every path that can
|
||||
//! be edited, selected or not.
|
||||
|
||||
use std::collections::HashSet;
|
||||
//! be edited, selected or not. What it removes is worked out by
|
||||
//! [`vectorcraft_tools::addons::trim::plan`], which the tool also uses to show it beforehand.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, NodeId, NodeKind};
|
||||
use vectorcraft_geom::kurbo::{Line, PathSeg};
|
||||
use vectorcraft_geom::{PathData, Point, Rect, SubPath, hit};
|
||||
use vectorcraft_pathops::addons::pathtools as pt;
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Point, Rect};
|
||||
use vectorcraft_tools::addons::trim::plan::{self, Limits, Pick, Stretches};
|
||||
|
||||
use super::super::super::draw2::replace_with_pieces;
|
||||
use super::super::super::pathops::Beside;
|
||||
@@ -41,16 +39,6 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
)]
|
||||
}
|
||||
|
||||
/// What picks the stretches to remove.
|
||||
enum Pick {
|
||||
/// The stretch of the nearest path within the tolerance of the point.
|
||||
At(Point, f64),
|
||||
/// Every stretch the rectangle touches.
|
||||
Rect(Rect),
|
||||
/// Every stretch the line through the points crosses.
|
||||
Line(Vec<Point>, Rect),
|
||||
}
|
||||
|
||||
fn pick(p: &Value) -> Result<Pick> {
|
||||
const C: &str = "addon.pathtools.trim";
|
||||
let given = |key: &str| p.get(key).filter(|v| !v.is_null());
|
||||
@@ -89,194 +77,15 @@ fn pick(p: &Value) -> Result<Pick> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A path that takes part: its id, geometry and control-point box.
|
||||
type Part<'a> = (NodeId, &'a PathData, Rect);
|
||||
|
||||
/// The paths that take part, bottom to top: the ones that can be edited, without guides and
|
||||
/// clipping paths. The clipping path of a clip group or a clipped layer is left out whole, the
|
||||
/// members of a compound clipping path included.
|
||||
fn parts(d: &Document) -> Vec<Part<'_>> {
|
||||
let editable = d.editable();
|
||||
let mut masks = HashSet::new();
|
||||
d.walk(|n| {
|
||||
if n.clips()
|
||||
&& let Some(first) = n.children().and_then(|c| c.first())
|
||||
{
|
||||
first.walk(&mut |m| {
|
||||
masks.insert(m.id);
|
||||
});
|
||||
}
|
||||
});
|
||||
let mut out = vec![];
|
||||
d.walk(|n| {
|
||||
if let NodeKind::Path { path, guide: false, clipping: false, .. } = &n.kind
|
||||
&& !masks.contains(&n.id)
|
||||
&& let Some(b) = path.control_bounds()
|
||||
&& editable(n.id)
|
||||
{
|
||||
out.push((n.id, path, b));
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// Most box tests one command makes between a line's pieces and the paths' segments.
|
||||
const MAX_LINE_TESTS: usize = 60_000_000;
|
||||
/// Most tests one command makes between the boxes of the paths to trim and of the other paths.
|
||||
const MAX_BOX_TESTS: usize = 50_000_000;
|
||||
|
||||
/// Does the line through `pts` cross `sp`? Each piece of the line compared costs one of `budget`;
|
||||
/// `None` once it is spent.
|
||||
fn crossed_by_line(sp: &SubPath, pts: &[Point], budget: &mut usize) -> Option<bool> {
|
||||
let segs: Vec<_> = (0..sp.segment_count())
|
||||
.map(|i| {
|
||||
let c = sp.segment(i);
|
||||
(c, Rect::from_points(c.p0, c.p1).union_pt(c.p2).union_pt(c.p3).inflate(1e-9, 1e-9))
|
||||
})
|
||||
.collect();
|
||||
let Some(reach) = segs.iter().map(|s| s.1).reduce(|a, b| a.union(b)) else { return Some(false) };
|
||||
for w in pts.windows(2) {
|
||||
let [a, b] = w else { continue };
|
||||
let piece = Rect::from_points(*a, *b);
|
||||
*budget = budget.checked_sub(1)?;
|
||||
if !reach.overlaps(piece) {
|
||||
continue;
|
||||
}
|
||||
for (c, r) in &segs {
|
||||
*budget = budget.checked_sub(1)?;
|
||||
if r.overlaps(piece) && !PathSeg::Cubic(*c).intersect_line(Line::new(*a, *b)).is_empty() {
|
||||
return Some(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(false)
|
||||
}
|
||||
|
||||
/// Does the rectangle or line of `pick` touch the outline of `piece`? Never for `Pick::At`.
|
||||
fn touches(piece: &SubPath, pick: &Pick, budget: &mut usize) -> Result<bool> {
|
||||
match pick {
|
||||
Pick::At(..) => Ok(false),
|
||||
Pick::Rect(r) => Ok(hit::intersects_rect(&PathData::single(piece.clone()), *r)),
|
||||
Pick::Line(pts, _) => crossed_by_line(piece, pts, budget)
|
||||
.ok_or_else(|| bad("addon.pathtools.trim", "the line is too long, or the paths it passes too many, to check")),
|
||||
}
|
||||
}
|
||||
|
||||
/// `path` without the stretches `pick` takes (`on`: the place of `Pick::At` on it): its subpaths
|
||||
/// then, and how many stretches went. `None` when none does. A rectangle or a line that touches no
|
||||
/// part of `path` leaves it out before its crossings are looked for.
|
||||
fn trimmed(
|
||||
path: &PathData,
|
||||
others: &[&PathData],
|
||||
pick: &Pick,
|
||||
on: Option<pt::Place>,
|
||||
budget: &mut usize,
|
||||
work: &mut pt::Work,
|
||||
) -> Result<Option<(Vec<SubPath>, usize)>> {
|
||||
const C: &str = "addon.pathtools.trim";
|
||||
let reached = match pick {
|
||||
Pick::At(..) => true,
|
||||
Pick::Rect(r) => hit::intersects_rect(path, *r),
|
||||
Pick::Line(..) => {
|
||||
let mut any = false;
|
||||
for sp in &path.subpaths {
|
||||
if touches(sp, pick, budget)? {
|
||||
any = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
any
|
||||
}
|
||||
};
|
||||
if !reached {
|
||||
return Ok(None);
|
||||
}
|
||||
let places =
|
||||
pt::crossings_on_within(path, others, work).ok_or_else(|| bad(C, "the paths are too many or too tangled to find where they cross"))?;
|
||||
let mut subs = vec![];
|
||||
let mut removed = 0;
|
||||
for (si, sp) in path.subpaths.iter().enumerate() {
|
||||
// The places come in subpath order: this subpath's are one run of them.
|
||||
let run = places.partition_point(|p| p.0 < si)..places.partition_point(|p| p.0 <= si);
|
||||
let here: Vec<(usize, f64)> = places.get(run).unwrap_or_default().iter().map(|&(_, seg, t)| (seg, t)).collect();
|
||||
let spans = pt::spans(sp, &here);
|
||||
let marks: Vec<bool> = match pick {
|
||||
Pick::At(..) => {
|
||||
let at = on.filter(|(s, ..)| *s == si).and_then(|(_, seg, t)| pt::span_at(sp, &spans, seg, t));
|
||||
(0..spans.len()).map(|i| Some(i) == at).collect()
|
||||
}
|
||||
_ => spans.iter().map(|s| touches(&pt::slice(sp, *s), pick, budget)).collect::<Result<_>>()?,
|
||||
};
|
||||
match pt::without_spans(sp, &spans, &marks) {
|
||||
Some(pieces) => {
|
||||
removed += marks.iter().filter(|m| **m).count();
|
||||
subs.extend(pieces);
|
||||
}
|
||||
None => subs.push(sp.clone()),
|
||||
}
|
||||
}
|
||||
Ok((removed > 0).then_some((subs, removed)))
|
||||
}
|
||||
|
||||
fn trim(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.pathtools.trim";
|
||||
let pick = pick(p)?;
|
||||
let st = s.doc()?;
|
||||
let d = &st.doc;
|
||||
let parts = parts(d);
|
||||
// In isolation mode only the isolated object's paths are trimmed; paths outside it still cross them.
|
||||
let root = crate::cmd::ordinary_isolation(st);
|
||||
let in_scope = |id: NodeId| root.is_none_or(|r| id == r || crate::cmd::inside_isolation(d, r, id));
|
||||
// The paths to trim, each with the place `at` falls on.
|
||||
let targets: Vec<(usize, Option<pt::Place>)> = match &pick {
|
||||
Pick::At(at, tolerance) => {
|
||||
let mut best: Option<(usize, pt::Place, f64)> = None;
|
||||
for (i, (id, path, b)) in parts.iter().enumerate() {
|
||||
if !in_scope(*id) {
|
||||
continue;
|
||||
}
|
||||
let b = b.inflate(*tolerance, *tolerance);
|
||||
if !(b.x0 <= at.x && at.x <= b.x1 && b.y0 <= at.y && at.y <= b.y1) {
|
||||
continue;
|
||||
}
|
||||
// Of paths equally near, the one on top.
|
||||
if let Some((si, seg, t, _, dist)) = path.nearest(*at)
|
||||
&& dist <= *tolerance
|
||||
&& best.is_none_or(|b| dist <= b.2)
|
||||
{
|
||||
best = Some((i, (si, seg, t), dist));
|
||||
}
|
||||
}
|
||||
best.map(|(i, on, _)| (i, Some(on))).into_iter().collect()
|
||||
}
|
||||
Pick::Rect(r) | Pick::Line(_, r) => {
|
||||
parts.iter().enumerate().filter(|(_, (id, _, b))| in_scope(*id) && b.overlaps(*r)).map(|(i, _)| (i, None)).collect()
|
||||
}
|
||||
};
|
||||
// Each path to trim has its box tested against every other path's.
|
||||
if targets.len().saturating_mul(parts.len()) > MAX_BOX_TESTS {
|
||||
return Err(bad(C, "the rectangle or line reaches too many paths to check"));
|
||||
}
|
||||
let mut plan: Vec<(NodeId, Vec<PathData>)> = vec![];
|
||||
let mut removed = 0;
|
||||
let mut budget = MAX_LINE_TESTS;
|
||||
// One budget of crossing work for every path the command trims.
|
||||
let mut work = pt::Work::default();
|
||||
for (i, on) in targets {
|
||||
let Some((id, path, b)) = parts.get(i) else { continue };
|
||||
let reach = b.inflate(1e-3, 1e-3);
|
||||
let others: Vec<&PathData> =
|
||||
parts.iter().enumerate().filter(|(j, (_, _, ob))| *j != i && reach.overlaps(*ob)).map(|(_, (_, o, _))| *o).collect();
|
||||
let Some((subs, n)) = trimmed(path, &others, &pick, on, &mut budget, &mut work)? else { continue };
|
||||
removed += n;
|
||||
// A path of one subpath becomes a path per piece; the pieces of one with more stay its subpaths.
|
||||
let pieces = match (path.subpaths.len(), subs.is_empty()) {
|
||||
(_, true) => vec![],
|
||||
(1, false) => subs.into_iter().map(PathData::single).collect(),
|
||||
_ => vec![PathData::new(subs)],
|
||||
};
|
||||
plan.push((*id, pieces));
|
||||
}
|
||||
let trimmed = plan::plan(&st.doc, root, &pick, Limits::COMMAND, &mut Stretches::default()).map_err(|e| bad(C, e.message()))?;
|
||||
let removed: usize = trimmed.iter().map(|t| t.count).sum();
|
||||
let plan: Vec<(NodeId, Vec<_>)> = trimmed.into_iter().map(|t| (t.id, t.pieces)).collect();
|
||||
if plan.is_empty() {
|
||||
return Ok(json!({ "ids": [], "removed": 0 }));
|
||||
}
|
||||
|
||||
@@ -480,6 +480,129 @@ fn the_tool_trims_on_release_as_one_step_and_escape_drops_a_drag() {
|
||||
assert_eq!(steps(&s), n + 2);
|
||||
}
|
||||
|
||||
/// The ends of each red path the tool shows.
|
||||
fn highlighted(s: &mut Session, view: crate::ViewInfo) -> Vec<(Point, Point)> {
|
||||
use vectorcraft_geom::kurbo::ParamCurve;
|
||||
s.overlays(view)
|
||||
.into_iter()
|
||||
.filter_map(|o| match o {
|
||||
vectorcraft_tools::Overlay::Path { path, color, .. } if color == vectorcraft_tools::builder::HIGHLIGHT_RED => {
|
||||
let segs: Vec<_> = path.segments().collect();
|
||||
Some((segs.first()?.start(), segs.last()?.end()))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hovering_with_the_tool_shows_the_stretch_its_click_removes() {
|
||||
use vectorcraft_tools::{PointerEvent, PointerKind};
|
||||
let mut s = session();
|
||||
let (h, _, _) = across_and_uprights(&mut s);
|
||||
let hidden = line(&mut s, &[(0.0, 200.0), (300.0, 200.0)], false);
|
||||
set_flags(&mut s, hidden, false, false);
|
||||
let view = crate::ViewInfo { smart_guides: false, ..crate::ViewInfo::default() };
|
||||
s.select_tool("trimAtCrossings", view).unwrap();
|
||||
let n = steps(&s);
|
||||
// Over the middle of the line across: the stretch between the uprights, and nothing changes.
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, 150.0, 101.0), view).unwrap();
|
||||
let shown = highlighted(&mut s, view);
|
||||
assert!(matches!(shown.as_slice(), [(a, b)] if near(*a, 100.0, 100.0) && near(*b, 200.0, 100.0)), "{shown:?}");
|
||||
assert_eq!(steps(&s), n);
|
||||
// Over the hidden path and over empty canvas: nothing.
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, 150.0, 200.0), view).unwrap();
|
||||
assert!(highlighted(&mut s, view).is_empty());
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, 150.0, 250.0), view).unwrap();
|
||||
assert!(highlighted(&mut s, view).is_empty());
|
||||
// A click where the stretch was shown removes exactly it: the line keeps 0 to 100 and 200 to 300.
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, 150.0, 101.0), view).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 150.0, 101.0), view).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 150.0, 101.0), view).unwrap();
|
||||
assert_eq!(steps(&s), n + 1);
|
||||
assert!(near(ends(&s, h).0, 0.0, 100.0) && near(ends(&s, h).1, 100.0, 100.0));
|
||||
let rest = stack(&s).into_iter().find(|id| *id != h && path(&s, *id).subpaths.len() == 1 && near(ends(&s, *id).0, 200.0, 100.0));
|
||||
assert!(rest.is_some_and(|id| near(ends(&s, id).1, 300.0, 100.0)));
|
||||
assert!(highlighted(&mut s, view).is_empty(), "the edit drops the highlight");
|
||||
}
|
||||
|
||||
/// The red paths the tool shows.
|
||||
fn red(s: &mut Session, view: crate::ViewInfo) -> Vec<vectorcraft_geom::BezPath> {
|
||||
s.overlays(view)
|
||||
.into_iter()
|
||||
.filter_map(|o| match o {
|
||||
vectorcraft_tools::Overlay::Path { path, color, .. } if color == vectorcraft_tools::builder::HIGHLIGHT_RED => Some(path),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The length of every path in the first layer.
|
||||
fn total_length(s: &Session) -> f64 {
|
||||
use vectorcraft_geom::kurbo::ParamCurveArclen;
|
||||
stack(s).into_iter().flat_map(|id| path(s, id).to_bezpath().segments().collect::<Vec<_>>()).map(|seg| seg.arclen(1e-9)).sum()
|
||||
}
|
||||
|
||||
/// `act` removes exactly the red paths shown before it: the paths lose their length, and nothing
|
||||
/// is left on the middle of any of them.
|
||||
fn removes_what_was_shown(s: &mut Session, view: crate::ViewInfo, act: &dyn Fn(&mut Session)) {
|
||||
use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveArclen};
|
||||
let shown = red(s, view);
|
||||
assert!(!shown.is_empty());
|
||||
let shown_length: f64 = shown.iter().flat_map(|p| p.segments().collect::<Vec<_>>()).map(|seg| seg.arclen(1e-9)).sum();
|
||||
let before = total_length(s);
|
||||
act(s);
|
||||
assert!((before - total_length(s) - shown_length).abs() < 1e-3, "{before} - {} != {shown_length}", total_length(s));
|
||||
for p in &shown {
|
||||
let segs: Vec<_> = p.segments().collect();
|
||||
let mid = segs[segs.len() / 2].eval(if segs.len() % 2 == 1 { 0.5 } else { 0.0 });
|
||||
let left = stack(s).into_iter().filter_map(|id| path(s, id).nearest(mid)).map(|n| n.4).fold(f64::INFINITY, f64::min);
|
||||
assert!(left > 0.5, "a path is left at {mid:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_the_tool_shows_before_a_click_or_a_release_is_what_the_command_removes() {
|
||||
use vectorcraft_tools::{Mods, PointerEvent, PointerKind};
|
||||
let view = crate::ViewInfo { smart_guides: false, ..crate::ViewInfo::default() };
|
||||
let ev = |kind, x, y| PointerEvent::new(kind, x, y);
|
||||
let alt = Mods { alt: true, ..Mods::default() };
|
||||
let setup = || {
|
||||
let mut s = session();
|
||||
s.execute("shape.ellipse", &json!({"x": 100, "y": 50, "width": 200, "height": 100})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
line(&mut s, &[(50.0, 100.0), (350.0, 100.0)], false);
|
||||
// A Z whose first and last sides cross.
|
||||
line(&mut s, &[(0.0, 160.0), (100.0, 260.0), (100.0, 160.0), (0.0, 260.0)], false);
|
||||
s.select_tool("trimAtCrossings", view).unwrap();
|
||||
s
|
||||
};
|
||||
// A click on the ellipse's top, on the line inside it and on the Z's loop.
|
||||
for (x, y) in [(200.0, 51.0), (200.0, 101.0), (101.0, 210.0)] {
|
||||
let mut s = setup();
|
||||
s.pointer(&ev(PointerKind::Move, x, y), view).unwrap();
|
||||
removes_what_was_shown(&mut s, view, &|s| {
|
||||
s.pointer(&ev(PointerKind::Down, x, y), view).unwrap();
|
||||
s.pointer(&ev(PointerKind::Up, x, y), view).unwrap();
|
||||
});
|
||||
}
|
||||
// A rectangle over the ellipse's left side and the line.
|
||||
let mut s = setup();
|
||||
s.pointer(&ev(PointerKind::Down, 90.0, 90.0), view).unwrap();
|
||||
s.pointer(&ev(PointerKind::Drag, 120.0, 110.0), view).unwrap();
|
||||
removes_what_was_shown(&mut s, view, &|s| {
|
||||
s.pointer(&ev(PointerKind::Up, 120.0, 110.0), view).unwrap();
|
||||
});
|
||||
// An Alt line through the ellipse's bottom and the Z's tail.
|
||||
let mut s = setup();
|
||||
s.pointer(&ev(PointerKind::Down, 200.0, 140.0).with_mods(alt), view).unwrap();
|
||||
s.pointer(&ev(PointerKind::Drag, 200.0, 170.0).with_mods(alt), view).unwrap();
|
||||
s.pointer(&ev(PointerKind::Drag, 10.0, 250.0).with_mods(alt), view).unwrap();
|
||||
removes_what_was_shown(&mut s, view, &|s| {
|
||||
s.pointer(&ev(PointerKind::Up, 10.0, 250.0).with_mods(alt), view).unwrap();
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_too_long_to_check_against_the_paths_is_refused() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add New Fill",
|
||||
["Window", "Appearance"],
|
||||
Some("Cmd+/"),
|
||||
"{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
"{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the row it adds when that row becomes the line's topmost visible row of its kind)",
|
||||
has_doc,
|
||||
|s, p| add_item(s, p, true)
|
||||
),
|
||||
@@ -57,7 +57,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add New Stroke",
|
||||
["Window", "Appearance"],
|
||||
Some("Cmd+Alt+/"),
|
||||
"{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
"{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the row it adds when that row becomes the line's topmost visible row of its kind)",
|
||||
has_doc,
|
||||
|s, p| add_item(s, p, false)
|
||||
),
|
||||
@@ -66,7 +66,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Clear Appearance",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own) and reset its opacity and blend mode. On a path directly in a graph series (a series group's id stands for those paths and the group), 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, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
"{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own) and reset its opacity and blend mode. On a path directly in a graph series (a series group's id stands for those paths and the group), 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, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind",
|
||||
has_doc,
|
||||
clear_appearance
|
||||
),
|
||||
@@ -75,7 +75,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reduce to Basic Appearance",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
"{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes)",
|
||||
has_doc,
|
||||
reduce_basic
|
||||
),
|
||||
@@ -84,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Appearance Item",
|
||||
[],
|
||||
None,
|
||||
"{index: paint-order item index, ids?|id? (default: the selection), target?: \"object\"|\"contents\", opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), tint?: 0..100, keepModel?: bool (both as paint.setFill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} edit one fill/stroke of each target object's own appearance stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
"{index: paint-order item index, ids?|id? (default: the selection), target?: \"object\"|\"contents\", opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), tint?: 0..100, keepModel?: bool (both as paint.setFill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} edit one fill/stroke of each target object's own appearance stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels; when their rows differ, `index` needs `aligned` and is a row of the backmost one), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the paint, weight, opacity and blend mode it writes to the line's topmost visible row)",
|
||||
has_doc,
|
||||
set_item
|
||||
),
|
||||
@@ -93,7 +93,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Remove Item",
|
||||
[],
|
||||
None,
|
||||
"{index | indices: [..] (paint-order item indices), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} remove those fills/strokes from each target object's own stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
"{index | indices: [..] (paint-order item indices), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} remove those fills/strokes from each target object's own stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels; when their rows differ, the indices need `aligned` and are rows of the backmost one), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes)",
|
||||
has_doc,
|
||||
remove_item
|
||||
),
|
||||
@@ -111,7 +111,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Duplicate Item",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{index | indices: [..] (paint-order item indices), to?: paint-order index of the copy (with several, of the lowest copy: they land together in their order; default: each right above its item; not with aligned rows of a mixed selection), contents?: count (with `to`: how many items paint below the Contents (Characters) row afterwards; default: it stays between the same items), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} copy fills/strokes with their effects, as Alt-dragging rows places them. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
"{index | indices: [..] (paint-order item indices), to?: paint-order index of the copy (with several, of the lowest copy: they land together in their order; default: each right above its item; not with aligned rows of a mixed selection), contents?: count (with `to`: how many items paint below the Contents (Characters) row afterwards; default: it stays between the same items), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} copy fills/strokes with their effects, as Alt-dragging rows places them. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels; when their rows differ, the indices need `aligned` and are rows of the backmost one), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes)",
|
||||
has_doc,
|
||||
duplicate_item
|
||||
),
|
||||
@@ -120,7 +120,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reorder Appearance Item",
|
||||
[],
|
||||
None,
|
||||
"{from: paint-order item index | \"contents\", indices?: [..] (several items instead of from: they move as one block in their order, the lowest landing at `to`; a block landing next to the Contents row keeps its lowest item's side), to, contents?: count, ids?|id?, target?, aligned?: bool (refused when the targets' appearances differ, or differ from that of a graph design's art given first)} move fill/stroke `from` to paint-order index `to`; on a group, layer or type the Contents (Characters) row stays between the same items (a moved item landing next to it keeps its side) unless `contents` says how many items paint below it afterwards. from \"contents\": move that row so `to` items paint below the members (characters) and the rest above. On a path directly in a graph series (a series group's id stands for those paths, except with from \"contents\", which moves the group's own row), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind → {index: where the item landed | contents: the row's slot}",
|
||||
"{from: paint-order item index | \"contents\", indices?: [..] (several items instead of from: they move as one block in their order, the lowest landing at `to`; a block landing next to the Contents row keeps its lowest item's side), to, contents?: count, ids?|id?, target?, aligned?: bool (refused when the targets' appearances differ, or differ from that of a graph design's art given first)} move fill/stroke `from` to paint-order index `to`; on a group, layer or type the Contents (Characters) row stays between the same items (a moved item landing next to it keeps its side) unless `contents` says how many items paint below it afterwards. from \"contents\": move that row so `to` items paint below the members (characters) and the rest above. On a path directly in a graph series (a series group's id stands for those paths, except with from \"contents\", which moves the group's own row), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels; moving rows of such a group whose members' rows differ is an error), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes) → {index: where the item landed | contents: the row's slot}",
|
||||
has_doc,
|
||||
move_item
|
||||
),
|
||||
@@ -129,7 +129,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Eyedropper",
|
||||
[],
|
||||
None,
|
||||
"{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. 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 the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode, and with `append` its topmost visible fill and stroke rows → {ids}",
|
||||
"{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. 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 the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode when transparency is applied, and with `append` its topmost visible fill and stroke rows of the kinds it adds; on a graph's axis line, tick mark or radar ring, its topmost visible fill and stroke rows, and when transparency is applied its object opacity and blend mode, for every line of its kind (a pick of some attributes without `append`: what it changes, and the paint, stroke weight and row transparency it applies to the topmost visible rows; with `append`: only the kinds of row it adds) → {ids}",
|
||||
has_doc,
|
||||
copy_from
|
||||
),
|
||||
@@ -147,7 +147,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Show All Hidden Attributes",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{ids?|id?, target?} make every hidden fill, stroke and effect (the object's and each item's) of each selected object visible again; errors when nothing is hidden. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind → {ids}",
|
||||
"{ids?|id?, target?} make every hidden fill, stroke and effect (the object's and each item's) of each selected object visible again; errors when nothing is hidden. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes) → {ids}",
|
||||
has_doc,
|
||||
show_all_hidden
|
||||
),
|
||||
@@ -165,7 +165,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Appearance",
|
||||
[],
|
||||
None,
|
||||
"{source: id, target: id, copy?: bool} give `target` (a layer, group or object) the appearance (fills, strokes, effects) and transparency (opacity, blend mode, isolation, knockout) of `source`, as dragging a target circle onto another in the Layers panel does; the source is left with a cleared appearance (as appearance.clear) unless `copy` (Alt-drag). Opacity masks stay; placed gradients keep their place relative to each object's bounds. On a path directly in a graph series (a series group's id stands for those paths; as `source`, when the group has no effect, opacity, blend mode, isolation, knockout or style link of its own, the topmost one is read and a move clears them all; as `target` each takes the appearance and the group is cleared, a `source` among them keeps its look, and a `source` that is the group's only path is an error), 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, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind → {source, target}",
|
||||
"{source: id, target: id, copy?: bool} give `target` (a layer, group or object) the appearance (fills, strokes, effects) and transparency (opacity, blend mode, isolation, knockout) of `source`, as dragging a target circle onto another in the Layers panel does; the source is left with a cleared appearance (as appearance.clear) unless `copy` (Alt-drag). Opacity masks stay; placed gradients keep their place relative to each object's bounds. On a path directly in a graph series (a series group's id stands for those paths; as `source`, when the group has no effect, opacity, blend mode, isolation, knockout or style link of its own, the topmost one is read and a move clears them all; as `target` each takes the appearance and the group is cleared, a `source` among them keeps its look, and a `source` that is the group's only path is an error), 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, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {source, target}",
|
||||
has_doc,
|
||||
transfer
|
||||
),
|
||||
@@ -538,7 +538,8 @@ pub(crate) fn design_art_in(d: &Document, roots: &[NodeId]) -> Vec<NodeId> {
|
||||
}
|
||||
|
||||
/// `ids` with each graph series group that has no fill or stroke row of its own replaced by the paths directly inside
|
||||
/// it ([`super::graph::series_group_marks`]). A series group with rows, as a document saved earlier can hold, stays:
|
||||
/// it, and each such Axes or Legend group of a graph by the lines and labels directly inside it
|
||||
/// ([`super::graph::series_group_marks`]). A series group with rows, as a document saved earlier can hold, stays:
|
||||
/// the Appearance panel lists those rows and edits them by index.
|
||||
pub(crate) fn rowless_series_marks(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
super::graph::series_group_marks_where(d, ids, |group| group.appearance.items.is_empty())
|
||||
@@ -559,8 +560,9 @@ fn holds_no_look(group: &Node) -> bool {
|
||||
}
|
||||
|
||||
/// The objects whose appearance a command reads for `id`: a graph series group that holds nothing of its own
|
||||
/// ([`holds_no_look`]) gives the paths directly inside it, backmost first. A series group with an effect, an opacity or
|
||||
/// another attribute of its own is read itself, with that attribute.
|
||||
/// ([`holds_no_look`]) gives the paths directly inside it, backmost first, and such an Axes or Legend group of a graph
|
||||
/// the lines and labels directly inside it. A series group with an effect, an opacity or another attribute of its own is
|
||||
/// read itself, with that attribute.
|
||||
fn look_holders(d: &Document, id: NodeId) -> Vec<NodeId> {
|
||||
super::graph::series_group_marks_where(d, &[id], holds_no_look)
|
||||
}
|
||||
@@ -626,11 +628,48 @@ fn require_targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
/// Refuse a row index given a graph's Axes or Legend group that stands for lines and labels whose stacks differ
|
||||
/// ([`rowless_series_marks`]), unless the index is `aligned`, a row of the backmost one's stack: the same index names a
|
||||
/// different row in each of them.
|
||||
pub(crate) fn check_part_rows(s: &Session, p: &Value, aligned: bool, cmd: &str) -> Result<()> {
|
||||
if aligned {
|
||||
return Ok(());
|
||||
}
|
||||
let d = &s.doc()?.doc;
|
||||
for id in appearance_targets(s, p)? {
|
||||
let Some(n) = d.node(id).filter(|n| n.appearance.items.is_empty()) else { continue };
|
||||
if let Some(members) = super::graph::graph_part_members(d, n)
|
||||
&& appearances_differ(d, &members)
|
||||
{
|
||||
return Err(bad(
|
||||
cmd,
|
||||
format!("the lines and labels in graph group {} have different appearance rows: pass `aligned: true` or their ids", id.0),
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether row `index` of `n` is the topmost visible row of its kind, the row a graph keeps for a label or line.
|
||||
fn is_top_shown(n: &Node, index: usize) -> bool {
|
||||
let items = &n.appearance.items;
|
||||
items.get(index).is_some_and(|it| items.iter().rposition(|o| o.is_fill() == it.is_fill() && o.visible()) == Some(index))
|
||||
}
|
||||
|
||||
/// `ids` without the objects whose topmost visible fill and stroke rows ([`super::graph::label_rows`]) an edit left as
|
||||
/// they were (`before`: the document before it), unless `wrote` says the edit wrote one of those rows. An edit of a
|
||||
/// hidden row of a graph label or line then leaves what the graph keeps for its kind as it is.
|
||||
fn shown_rows_edited(before: &Document, d: &Document, ids: Vec<NodeId>, wrote: impl Fn(NodeId) -> bool) -> Vec<NodeId> {
|
||||
let shown = |doc: &Document, id: NodeId| doc.node(id).map(super::graph::label_rows);
|
||||
ids.into_iter().filter(|id| wrote(*id) || shown(before, *id) != shown(d, *id)).collect()
|
||||
}
|
||||
|
||||
/// 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, 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
|
||||
/// ([`capture_series_changes`], [`super::graph::capture_label_changes`]), and so are the rows of
|
||||
/// the graph lines it reaches ([`super::graph::capture_line_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.
|
||||
///
|
||||
@@ -652,7 +691,7 @@ pub(crate) fn edit_items(
|
||||
edit_items_then(s, ids, item, of, cmd, label, fill, f, |before, d, edited| {
|
||||
let series = capture_series_changes(before, d, edited);
|
||||
// The rows `f` edited are kept by `edit_items_then`.
|
||||
let labels = super::graph::capture_label_changes(before, d, edited, false);
|
||||
let labels = super::graph::capture_label_changes(before, d, edited, false, None);
|
||||
Ok(series || labels)
|
||||
})
|
||||
}
|
||||
@@ -670,6 +709,45 @@ pub(crate) fn edit_items_then(
|
||||
cmd: &str,
|
||||
label: &str,
|
||||
fill: bool,
|
||||
f: impl FnMut(&mut Node, Option<usize>) -> Result<()>,
|
||||
after: impl FnMut(&vectorcraft_doc::Document, &mut vectorcraft_doc::Document, &[NodeId]) -> Result<bool>,
|
||||
) -> Result<Vec<NodeId>> {
|
||||
edit_items_writing_then(s, ids, item, of, cmd, label, fill, super::graph::RowWrites::NONE, f, after)
|
||||
}
|
||||
|
||||
/// [`edit_items`] for an edit that writes the attributes `writes` says to the row of each target it edits: a graph line
|
||||
/// keeps them for its kind when that row is its topmost visible one, also when the line already showed them
|
||||
/// ([`super::graph::capture_line_row_writes`]).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn edit_items_writing(
|
||||
s: &mut Session,
|
||||
ids: &[NodeId],
|
||||
item: ItemTarget,
|
||||
of: Option<NodeId>,
|
||||
cmd: &str,
|
||||
label: &str,
|
||||
fill: bool,
|
||||
writes: super::graph::RowWrites,
|
||||
f: impl FnMut(&mut Node, Option<usize>) -> Result<()>,
|
||||
) -> Result<Vec<NodeId>> {
|
||||
edit_items_writing_then(s, ids, item, of, cmd, label, fill, writes, f, |before, d, edited| {
|
||||
let series = capture_series_changes(before, d, edited);
|
||||
let labels = super::graph::capture_label_changes(before, d, edited, false, None);
|
||||
Ok(series || labels)
|
||||
})
|
||||
}
|
||||
|
||||
/// [`edit_items_then`] with the attributes `writes` says, as [`edit_items_writing`] keeps them.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn edit_items_writing_then(
|
||||
s: &mut Session,
|
||||
ids: &[NodeId],
|
||||
item: ItemTarget,
|
||||
of: Option<NodeId>,
|
||||
cmd: &str,
|
||||
label: &str,
|
||||
fill: bool,
|
||||
writes: super::graph::RowWrites,
|
||||
mut f: impl FnMut(&mut Node, Option<usize>) -> Result<()>,
|
||||
mut after: impl FnMut(&vectorcraft_doc::Document, &mut vectorcraft_doc::Document, &[NodeId]) -> Result<bool>,
|
||||
) -> Result<Vec<NodeId>> {
|
||||
@@ -693,6 +771,10 @@ pub(crate) fn edit_items_then(
|
||||
let mut edited = Vec::new();
|
||||
// The objects whose rows `f` edited: on type, no row means its characters.
|
||||
let mut rows = Vec::new();
|
||||
// The objects where `f` wrote the topmost visible row of its kind.
|
||||
let mut wrote = Vec::new();
|
||||
// The row of each object `f` wrote: its index, else the topmost row of the kind.
|
||||
let mut written = Vec::new();
|
||||
for (id, item) in ids.iter().zip(&per) {
|
||||
let Some(item) = item else { continue };
|
||||
let Some(n) = d.node_mut(*id) else { continue };
|
||||
@@ -702,10 +784,22 @@ pub(crate) fn edit_items_then(
|
||||
if index.is_some() {
|
||||
rows.push(*id);
|
||||
}
|
||||
if index.is_none_or(|i| is_top_shown(n, i)) {
|
||||
wrote.push(*id);
|
||||
}
|
||||
written.extend(index.or_else(|| n.appearance.items.iter().rposition(|it| it.is_fill() == fill)).map(|at| (*id, at)));
|
||||
}
|
||||
let more = after(&before, d, &edited)?;
|
||||
let labels = super::graph::capture_label_rows(d, &rows);
|
||||
Ok(count_changed(d, &before, &edited) + usize::from(more || labels))
|
||||
// A graph line keeps only the attributes of its rows that the edit changed, and those it wrote (`writes`): the
|
||||
// others stay as its kind keeps them, which the line may not show yet.
|
||||
rows.retain(|id| !super::graph::is_graph_line(d, *id));
|
||||
let labels = super::graph::capture_label_rows(d, &shown_rows_edited(&before, d, rows, |id| wrote.contains(&id)));
|
||||
let mut lines = super::graph::capture_line_changes(&before, d, &edited);
|
||||
if writes != super::graph::RowWrites::NONE {
|
||||
let (on_fill, on_stroke) = if fill { (writes, super::graph::RowWrites::NONE) } else { (super::graph::RowWrites::NONE, writes) };
|
||||
lines |= super::graph::capture_line_row_writes(d, &written, on_fill, on_stroke);
|
||||
}
|
||||
Ok(count_changed(d, &before, &edited) + usize::from(more || labels || lines))
|
||||
})?;
|
||||
Ok(aimed)
|
||||
}
|
||||
@@ -716,6 +810,17 @@ pub(crate) fn first_edited(s: &Session, item: ItemTarget, of: Option<NodeId>, id
|
||||
ids.iter().zip(item.per_target_of(s, of, ids)).find_map(|(id, it)| Some((*id, it?)))
|
||||
}
|
||||
|
||||
/// Keep the object rows of the graph labels among `ids` for every label of their kind
|
||||
/// ([`super::graph::capture_label_rows`]), and of the graph lines among them only the attributes the edit changed
|
||||
/// ([`super::graph::capture_line_changes`]): a line's other attributes stay as its kind keeps them, which the line may
|
||||
/// not show yet. Returns whether what a graph keeps changed.
|
||||
fn capture_row_edits(before: &vectorcraft_doc::Document, d: &mut vectorcraft_doc::Document, ids: &[NodeId]) -> bool {
|
||||
let labels: Vec<NodeId> = ids.iter().copied().filter(|id| !super::graph::is_graph_line(d, *id)).collect();
|
||||
let labels = super::graph::capture_label_rows(d, &labels);
|
||||
let lines = super::graph::capture_line_changes(before, d, ids);
|
||||
labels || lines
|
||||
}
|
||||
|
||||
/// How many of `ids` differ in `d` from `before`.
|
||||
pub(crate) fn count_changed(d: &vectorcraft_doc::Document, before: &vectorcraft_doc::Document, ids: &[NodeId]) -> usize {
|
||||
ids.iter().filter(|id| d.node(**id) != before.node(**id)).count()
|
||||
@@ -854,10 +959,13 @@ fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids));
|
||||
let lines: Vec<NodeId> = added.iter().map(|(id, _)| *id).collect();
|
||||
let mut rows = top_paint_changed(&before, d, &ids);
|
||||
rows.extend(painted_rows(d, added));
|
||||
super::graph::capture_series_top_paints(d, &rows);
|
||||
super::graph::capture_label_rows(d, &ids);
|
||||
capture_row_edits(&before, d, &ids);
|
||||
// A graph line keeps the row it got for its kind, also when it showed that row's paint, weight and transparency.
|
||||
super::graph::capture_line_kind_rows(d, &lines, (fill, !fill), false);
|
||||
Ok(())
|
||||
})?;
|
||||
// A fill added above the active row becomes the active row; otherwise the rows above the new
|
||||
@@ -1046,7 +1154,7 @@ fn transfer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut targets: Vec<NodeId> = marks.iter().copied().filter(|id| !within.contains(id)).collect();
|
||||
if targets.is_empty() {
|
||||
if stands {
|
||||
return Err(bad(C, "`source` is the only path in series group `target`"));
|
||||
return Err(bad(C, "`source` is the only path, line or label that graph group `target` stands for"));
|
||||
}
|
||||
targets.push(target);
|
||||
}
|
||||
@@ -1091,8 +1199,9 @@ fn transfer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
rows.extend(painted_rows(d, both_kinds(&targets)));
|
||||
let painted = super::graph::capture_series_top_paints(d, &rows);
|
||||
let object = super::graph::capture_series_object_opacity(d, &changed);
|
||||
// The targets last: on two labels of one kind, the target's rows are the ones the kind keeps.
|
||||
let labels = super::graph::capture_label_rows(d, &changed);
|
||||
// The targets last: on two labels of one kind, the target's rows are the ones the kind keeps. Graph lines are
|
||||
// taken in paint order, so the targets are captured again on their own, after a cleared source in front of them.
|
||||
let labels = super::graph::capture_label_rows(d, &changed) | super::graph::capture_label_rows(d, &targets);
|
||||
let all: Vec<NodeId> = from.iter().chain(&targets).chain(&group).copied().collect();
|
||||
Ok(count_changed(d, &before, &all) + usize::from(kept || painted || object || labels || forgot))
|
||||
})?;
|
||||
@@ -1150,7 +1259,7 @@ fn reduce_basic(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let kept = super::graph::capture_series_opacity(d, &both_kinds(&ids));
|
||||
let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &ids));
|
||||
let labels = super::graph::capture_label_rows(d, &ids);
|
||||
let labels = capture_row_edits(&before, d, &ids);
|
||||
Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || labels))
|
||||
})?;
|
||||
s.active_appearance_item = None;
|
||||
@@ -1167,6 +1276,7 @@ fn set_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if ids.is_empty() {
|
||||
return Err(bad("appearance.setItem", "select objects or give ids"));
|
||||
}
|
||||
check_part_rows(s, p, aligned(p, "appearance.setItem")?, "appearance.setItem")?;
|
||||
let blend = str_param(p, "blend").and_then(BlendMode::parse);
|
||||
// When every object comes out as it was (for example, when none has item `index`), the document
|
||||
// and its undo history stay as they are.
|
||||
@@ -1175,6 +1285,9 @@ fn set_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let per = rows_per_target(&before, of, &ids, &[idx], aligned(p, "appearance.setItem")?);
|
||||
super::overprint::edit_counted(s, "Appearance", |d| {
|
||||
let mut edited = Vec::new();
|
||||
// The targets that have the row: an aligned row leaves out the members of a graph's Axes or Legend group that
|
||||
// lack it, and the graph keeps the rows of the labels and lines it reached only.
|
||||
let mut reached = Vec::new();
|
||||
for (id, at) in ids.iter().zip(&per) {
|
||||
let Some(&idx) = at.first() else { continue };
|
||||
let Some(n) = d.node_mut(*id) else { continue };
|
||||
@@ -1185,6 +1298,7 @@ fn set_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let bounds = n.geometric_bounds();
|
||||
let Some(item) = n.appearance.items.get_mut(idx) else { continue };
|
||||
reached.push(*id);
|
||||
let (pp, op, bl, vis, bounds) = match item {
|
||||
AppearanceItem::Fill(f) => (&mut f.paint, &mut f.opacity, &mut f.blend, &mut f.visible, bounds),
|
||||
AppearanceItem::Stroke(st) => {
|
||||
@@ -1227,8 +1341,19 @@ fn set_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut rows = top_paint_changed(&before, d, &ids);
|
||||
rows.extend(painted_rows(d, written));
|
||||
let painted = super::graph::capture_series_top_paints(d, &rows);
|
||||
let labels = super::graph::capture_label_rows(d, &ids);
|
||||
Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || labels))
|
||||
let reached = shown_rows_edited(&before, d, reached, |id| edited.iter().any(|(e, _)| *e == id));
|
||||
let labels = capture_row_edits(&before, d, &reached);
|
||||
// A graph line keeps what was written to its topmost visible row, also when it already showed it.
|
||||
let tops: Vec<(NodeId, usize)> = ids.iter().zip(&per).filter_map(|(id, at)| Some((*id, *at.first()?))).collect();
|
||||
// Only the values the edit applied: a null weight or opacity leaves the row as it is.
|
||||
let writes = super::graph::RowWrites {
|
||||
paint: paint.is_some(),
|
||||
weight: p.get("weight").and_then(Value::as_f64).is_some(),
|
||||
opacity: p.get("opacity").and_then(Value::as_f64).is_some(),
|
||||
blend: blend.is_some(),
|
||||
};
|
||||
let lines = super::graph::capture_line_row_writes(d, &tops, super::graph::RowWrites { weight: false, ..writes }, writes);
|
||||
Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || labels || lines))
|
||||
})?;
|
||||
if let Some(pa) = &paint {
|
||||
s.remember_paint(pa);
|
||||
@@ -1256,14 +1381,20 @@ pub(super) fn item_indices(p: &Value, cmd: &str) -> Result<Vec<usize>> {
|
||||
fn remove_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let idx = item_indices(p, "appearance.removeItem")?;
|
||||
let ids = require_targets(s, p, "appearance.removeItem")?;
|
||||
check_part_rows(s, p, aligned(p, "appearance.removeItem")?, "appearance.removeItem")?;
|
||||
// When no object has an item at any of the indices, the document and its undo history stay as
|
||||
// they are.
|
||||
let before = s.doc()?.doc.clone();
|
||||
let of = design_reference(s, p, "appearance.removeItem")?;
|
||||
let per = rows_per_target(&before, of, &ids, &idx, aligned(p, "appearance.removeItem")?);
|
||||
super::overprint::edit_counted(s, "Remove Item", |d| {
|
||||
// The targets that had a row to remove, as in `set_item`.
|
||||
let mut reached = Vec::new();
|
||||
for (id, idx) in ids.iter().zip(&per) {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
if idx.iter().any(|i| *i < n.appearance.items.len()) {
|
||||
reached.push(*id);
|
||||
}
|
||||
let mut idx = idx.clone();
|
||||
idx.sort_unstable();
|
||||
// From the top down, so the lower indices stay valid.
|
||||
@@ -1275,7 +1406,7 @@ fn remove_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let kept = super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids));
|
||||
let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &ids));
|
||||
let labels = super::graph::capture_label_rows(d, &ids);
|
||||
let labels = capture_row_edits(&before, d, &shown_rows_edited(&before, d, reached, |_| false));
|
||||
Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || labels))
|
||||
})?;
|
||||
// The rows removed from the active row's object, which need not come first in `ids`.
|
||||
@@ -1295,6 +1426,7 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "`contents` goes with `to`"));
|
||||
}
|
||||
let ids = require_targets(s, p, C)?;
|
||||
check_part_rows(s, p, aligned(p, C)?, C)?;
|
||||
// Where the first target's copy landed, and where it landed on the active row's object (the
|
||||
// first selected one, not always the first target): copies placed at `to` land at a different
|
||||
// index on stacks of other lengths.
|
||||
@@ -1319,6 +1451,8 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Copies that became the topmost visible row of their kind: the series stores their paint even when the object
|
||||
// showed it.
|
||||
let mut added = Vec::new();
|
||||
// The targets that took a copy, as in `set_item`.
|
||||
let mut reached = Vec::new();
|
||||
for (id, idx) in ids.iter().zip(&per) {
|
||||
let Some(n) = d.node_mut(*id) else { continue };
|
||||
let has_contents = n.contents_label().is_some();
|
||||
@@ -1343,6 +1477,7 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
ap.set_contents_at(c);
|
||||
}
|
||||
any = true;
|
||||
reached.push(*id);
|
||||
continue;
|
||||
}
|
||||
let mut idx = idx.clone();
|
||||
@@ -1357,6 +1492,9 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
added.push((*id, kind));
|
||||
}
|
||||
any = true;
|
||||
if reached.last() != Some(id) {
|
||||
reached.push(*id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1365,9 +1503,10 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids));
|
||||
let mut rows = top_paint_changed(&before, d, &ids);
|
||||
let top_copies: Vec<NodeId> = added.iter().map(|(id, _)| *id).collect();
|
||||
rows.extend(painted_rows(d, added));
|
||||
super::graph::capture_series_top_paints(d, &rows);
|
||||
super::graph::capture_label_rows(d, &ids);
|
||||
capture_row_edits(&before, d, &shown_rows_edited(&before, d, reached, |id| top_copies.contains(&id)));
|
||||
Ok(())
|
||||
})?;
|
||||
// Rows at or above each copy move up by one (by the block, for copies placed at `to`).
|
||||
@@ -1407,7 +1546,7 @@ fn show_all_hidden(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &shown));
|
||||
super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &shown));
|
||||
super::graph::capture_label_rows(d, &shown);
|
||||
capture_row_edits(&before, d, &shown);
|
||||
Ok(shown)
|
||||
})?;
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }))
|
||||
@@ -1431,6 +1570,7 @@ fn move_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return move_contents(s, &ids, to);
|
||||
}
|
||||
let ids = require_targets(s, p, C)?;
|
||||
check_part_rows(s, p, aligned, C)?;
|
||||
// Where an aligned row would go in each of several different stacks isn't one place.
|
||||
if aligned && appearances_differ(&s.doc()?.doc, &with_reference(design_reference(s, p, C)?, &ids)) {
|
||||
return Err(bad(C, "rows of objects whose appearances differ can't be reordered together"));
|
||||
@@ -1457,7 +1597,7 @@ fn move_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let kept = super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids));
|
||||
let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &ids));
|
||||
let labels = super::graph::capture_label_rows(d, &ids);
|
||||
let labels = super::graph::capture_label_changes(&before, d, &ids, true, None);
|
||||
Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || labels))
|
||||
})?;
|
||||
// The moved row stays the active one; the rows it passed shift by one.
|
||||
@@ -1503,7 +1643,7 @@ fn move_items(s: &mut Session, p: &Value, ids: &[NodeId], to: usize) -> Result<V
|
||||
}
|
||||
let kept = super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, ids));
|
||||
let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, ids));
|
||||
let labels = super::graph::capture_label_rows(d, ids);
|
||||
let labels = super::graph::capture_label_changes(&before, d, ids, true, None);
|
||||
Ok(count_changed(d, &before, ids) + usize::from(kept || painted || labels))
|
||||
})?;
|
||||
let m = idx.len();
|
||||
@@ -1536,8 +1676,8 @@ fn move_contents(s: &mut Session, ids: &[NodeId], to: usize) -> Result<Value> {
|
||||
slot.get_or_insert(n.appearance.contents_at());
|
||||
}
|
||||
slot.ok_or_else(|| bad("appearance.moveItem", "only groups, layers, type and images have a Contents (Characters) row"))?;
|
||||
// A graph label's kind keeps where its rows paint relative to the characters.
|
||||
let labels = super::graph::capture_label_rows(d, ids);
|
||||
// A graph label's kind keeps where its rows paint relative to the characters, from the labels the move changed.
|
||||
let labels = capture_row_edits(&before, d, &shown_rows_edited(&before, d, ids.to_vec(), |_| false));
|
||||
Ok(count_changed(d, &before, ids) + usize::from(labels))
|
||||
})?;
|
||||
Ok(json!({ "contents": slot }))
|
||||
@@ -1804,15 +1944,45 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let object = super::graph::capture_series_object_opacity(d, &objects);
|
||||
// Graph labels keep their new rows, characters and paragraphs per kind of label.
|
||||
// On type, only `append` adds rows and a transparency pick changes the object's opacity and blend mode; the other
|
||||
// attributes go to the characters.
|
||||
// attributes go to the characters. Without a transparency pick, the object opacity and blend mode a kind keeps stay,
|
||||
// also when the label or line picked onto still shows other ones until the graph is drawn again. `append` keeps
|
||||
// only the kinds of row it added; a row of the other kind stays as the kind keeps it.
|
||||
let transparency = attrs.appearance.transparency;
|
||||
let rows = if append {
|
||||
super::graph::capture_label_rows(d, &targets)
|
||||
super::graph::capture_label_kind_rows(d, &targets, paints, transparency)
|
||||
} else {
|
||||
attrs.appearance.transparency && super::graph::capture_label_object_opacity(d, &targets)
|
||||
transparency && super::graph::capture_label_object_opacity(d, &targets)
|
||||
};
|
||||
// `append` adds rows and leaves the characters as they were.
|
||||
let text = !append && super::graph::capture_label_text(d, &targets, kept_text, kept_para)?;
|
||||
Ok(count_changed(d, &before, &targets) + usize::from(kept || painted || object || rows || text))
|
||||
// A graph line is a path: a whole pick and `append` write its rows. A pick of some attributes keeps those it
|
||||
// changed, and the rest stay as its kind keeps them, which the line may not show yet. Row attributes the graph
|
||||
// does not keep (overprint, caps, joins, miter limit, dashes) leave what its kind keeps as it is.
|
||||
let lines = match (rows_written, transparency) {
|
||||
_ if append => super::graph::capture_line_kind_rows(d, &targets, paints, transparency),
|
||||
(true, true) => super::graph::capture_line_rows(d, &targets),
|
||||
(true, false) => super::graph::capture_line_fill_stroke_rows(d, &targets),
|
||||
(false, _) => {
|
||||
// The topmost row of each kind, which the pick wrote: what it wrote is kept also when the line showed it.
|
||||
let tops: Vec<(NodeId, usize)> = targets
|
||||
.iter()
|
||||
.filter_map(|id| d.node(*id).map(|n| (*id, &n.appearance.items)))
|
||||
.flat_map(|(id, items)| {
|
||||
[true, false].into_iter().filter_map(move |kind| items.iter().rposition(|it| it.is_fill() == kind).map(|at| (id, at)))
|
||||
})
|
||||
.collect();
|
||||
// A transparency pick applies the row's opacity and blend mode together.
|
||||
let on_fill = super::graph::RowWrites { paint: fill.color, weight: false, opacity: opacities.0, blend: opacities.0 };
|
||||
let on_stroke = super::graph::RowWrites {
|
||||
paint: stroke.color,
|
||||
weight: stroke.weight && source_has(false),
|
||||
opacity: opacities.1,
|
||||
blend: opacities.1,
|
||||
};
|
||||
super::graph::capture_line_changes(&before, d, &targets) | super::graph::capture_line_row_writes(d, &tops, on_fill, on_stroke)
|
||||
}
|
||||
};
|
||||
Ok(count_changed(d, &before, &targets) + usize::from(kept || painted || object || rows || text || lines))
|
||||
})?;
|
||||
Ok(finish(s, &targets))
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ use std::collections::HashSet;
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::{ExportAsset, NodeId};
|
||||
|
||||
use super::edit::{roots_of, selected_roots};
|
||||
use super::edit::{refuse_symbol_part, roots_of, selected_roots};
|
||||
use super::fileio::{
|
||||
DEFAULT_FORMAT_3D, FORMATS_3D, SCREEN_SETTINGS_KEYS, check_screen_settings, create_dir, export_crop, export_screens, mesh_file_names, mesh_files,
|
||||
safe_file_name, store_screen_settings, with_screen_export_preset, write_file,
|
||||
@@ -62,7 +62,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export 3D Object",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [id…] (default: the selected objects), format?: usda|usdz|gltf|obj (default usda)} collect each object with an Extrude & Bevel, Revolve, Inflate or Rotate effect as a 3D asset of Window › Asset Export, named after the object (else Asset 1, Asset 2…): assets.export3D writes it as a mesh file. An object already collected as a 3D asset keeps it; an object without such an effect is refused → {assets: [asset id…] (in order), added: n}",
|
||||
"{ids?: [id…] (default: the selected objects), format?: usda|usdz|gltf|obj (default usda)} collect each object with an Extrude & Bevel, Revolve, Inflate or Rotate effect as a 3D asset of Window › Asset Export, named after the object (else Asset 1, Asset 2…): assets.export3D writes it as a mesh file. An object already collected as a 3D asset keeps it; an object in ids without such an effect is refused. Without ids, the selected objects without one (on a group or layer, one on its fill or stroke draws nothing and does not count), and a selected object inside another selected object that has one, are left out; refused when none is left → {assets: [asset id…] (in order), added: n}",
|
||||
has_doc,
|
||||
add_3d
|
||||
),
|
||||
@@ -203,10 +203,36 @@ fn three_d_asset_ids(d: &vectorcraft_doc::Document, p: &Value, key: &str, cmd: &
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
/// The selected objects `assets.add3D` collects without `ids`: those with a 3D effect it exports
|
||||
/// ([`vectorcraft_render::effects::exports_three_d`]; a path of a compound path counts as the
|
||||
/// compound path), layers included, in tree order, dropping
|
||||
/// each one inside another of them (that one's asset holds it). Refused while an object of a
|
||||
/// dynamic symbol instance's art is selected, as [`selected_roots`] is.
|
||||
fn selected_3d_roots(s: &Session) -> Result<Vec<NodeId>> {
|
||||
refuse_symbol_part(s)?;
|
||||
let st = s.doc()?;
|
||||
// A path of a compound path stands for the compound path, which holds the paint and effects.
|
||||
let found = st
|
||||
.selection
|
||||
.objects
|
||||
.iter()
|
||||
.map(|id| super::path::compound_or_self(&st.doc, *id))
|
||||
.filter(|id| st.doc.node(*id).is_some_and(vectorcraft_render::effects::exports_three_d));
|
||||
let mut paths: Vec<(Vec<usize>, NodeId)> = st.doc.index_paths(found).into_iter().map(|(id, path)| (path, id)).collect();
|
||||
paths.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
let mut kept: Vec<(Vec<usize>, NodeId)> = Vec::with_capacity(paths.len());
|
||||
for (path, id) in paths {
|
||||
if !kept.last().is_some_and(|(outer, _)| path.starts_with(outer)) {
|
||||
kept.push((path, id));
|
||||
}
|
||||
}
|
||||
Ok(kept.into_iter().map(|(_, id)| id).collect())
|
||||
}
|
||||
|
||||
fn add_3d(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "assets.add3D";
|
||||
let format = format_3d_param(p, C, Some(DEFAULT_FORMAT_3D))?;
|
||||
let ids = if p.get("ids").is_some_and(|v| !v.is_null()) { checked_ids_param(s, p, "ids", C)? } else { selected_roots(s)? };
|
||||
let ids = if p.get("ids").is_some_and(|v| !v.is_null()) { checked_ids_param(s, p, "ids", C)? } else { selected_3d_roots(s)? };
|
||||
if ids.is_empty() {
|
||||
return Err(bad(C, "select an object with a 3D effect (or give its ids)"));
|
||||
}
|
||||
|
||||
@@ -144,7 +144,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Make",
|
||||
["Object", "Image Trace"],
|
||||
None,
|
||||
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px (an area smaller than this joins the color it shares the longest border with; when that color is far from its own and the area is 2 px or more, or a single pixel whose longest border is not tied between colors, it joins the neighboring color nearest its pixels among those sharing at least a tenth of that border), method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" group under the paths holds 1.5 px strokes along the edges two filled paths share, in the color of the lower path, so that no light hairline shows along those edges; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}",
|
||||
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px (an area smaller than this joins the color it shares the longest border with; when that color is far from its own and the area is 2 px or more, or a single pixel whose longest border is not tied between colors, it joins the neighboring color nearest its pixels among those sharing at least a tenth of that border), method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" clip group under the paths holds strokes along the edges two filled paths share, 1.5 image pixels wide (VectorCraft's own width), in the color of the lower path (on an image stretched more one way than another, each stroke's outline in image pixels as a filled path), clipped to the image's box within the traced paths' box; paths that became live shapes get none; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}",
|
||||
has_selection_or_ids,
|
||||
|s, p| trace_make(s, p, false)
|
||||
),
|
||||
|
||||
@@ -23,20 +23,30 @@ fn is_trace_group(n: &Node) -> bool {
|
||||
&& n.children().is_some_and(|c| c.first().is_some_and(|i| matches!(i.kind, NodeKind::Image(_))))
|
||||
}
|
||||
|
||||
/// The name of the group that holds an Abutting trace's seam fills (see [`tr::TraceResult::seams`]).
|
||||
/// The name of the clip group that holds an Abutting trace's seam fills (see [`tr::seam_fills`]).
|
||||
const SEAM_FILLS_NAME: &str = "Seam Fills";
|
||||
|
||||
/// Whether `n` can be a trace's seam fills group: a group named as one, or a group of stroked paths
|
||||
/// without fills, so that it is still found after it is renamed or its strokes are edited. (Auto
|
||||
/// Grouping groups hold filled paths.)
|
||||
/// Whether `n` can be a trace's seam fills group: a clip group named as one, or a clip group whose
|
||||
/// members after the clipping path are all stroked paths without fills, or all filled paths
|
||||
/// without strokes (the strokes' outlines, on a stretched image), so that it is still found after
|
||||
/// it is renamed or its strokes are edited. (Auto Grouping groups are not clip groups.) Traces made
|
||||
/// before the seam fills were clipped hold a group without a clip: one named as seam fills, or one
|
||||
/// of stroked paths without fills. (Auto Grouping groups hold filled paths.)
|
||||
fn is_seam_fills(n: &Node) -> bool {
|
||||
let stroke_only = |m: &Arc<Node>| {
|
||||
matches!(m.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
|
||||
&& m.appearance.fill_paint() == Paint::None
|
||||
&& m.appearance.stroke_paint() != Paint::None
|
||||
};
|
||||
matches!(n.kind, NodeKind::Group { clip: false, .. })
|
||||
&& (n.name.as_deref() == Some(SEAM_FILLS_NAME) || n.children().is_some_and(|c| !c.is_empty() && c.iter().all(stroke_only)))
|
||||
let path = |m: &Arc<Node>| matches!(m.kind, NodeKind::Path { .. } | NodeKind::Compound { .. });
|
||||
let stroke_only = |m: &Arc<Node>| path(m) && m.appearance.fill_paint() == Paint::None && m.appearance.stroke_paint() != Paint::None;
|
||||
let fill_only = |m: &Arc<Node>| path(m) && m.appearance.fill_paint() != Paint::None && m.appearance.stroke_paint() == Paint::None;
|
||||
let named = n.name.as_deref() == Some(SEAM_FILLS_NAME);
|
||||
match &n.kind {
|
||||
NodeKind::Group { clip: true, children } => {
|
||||
named
|
||||
|| children
|
||||
.split_first()
|
||||
.is_some_and(|(_, members)| !members.is_empty() && (members.iter().all(stroke_only) || members.iter().all(fill_only)))
|
||||
}
|
||||
NodeKind::Group { clip: false, children } => named || (!children.is_empty() && children.iter().all(stroke_only)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
const LIVE_PATHFINDER_BY_COLOR: &str = "byColor can't regroup a trace with a live Pathfinder effect: expand without byColor";
|
||||
@@ -411,7 +421,8 @@ fn by_color_param(cmd: &str, p: &Value) -> Result<bool> {
|
||||
/// starts another group of that paint, which keeps the stacking order of those items. Items
|
||||
/// farther apart can still share antialiased pixels at small view or raster-export scales, so
|
||||
/// their edge pixels may change. The seam fills' group, when it is the lowest item, stays as it is,
|
||||
/// under every other group. Any other group among `items` (Auto Grouping) is refused.
|
||||
/// under every other group; above another item it is refused. Any other group among `items` (Auto
|
||||
/// Grouping) is refused.
|
||||
fn color_groups(cmd: &str, d: &mut Document, items: Vec<Arc<Node>>) -> Result<Vec<Arc<Node>>> {
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::ops::Bound::{Excluded, Unbounded};
|
||||
@@ -465,6 +476,9 @@ fn color_groups(cmd: &str, d: &mut Document, items: Vec<Arc<Node>>) -> Result<Ve
|
||||
let mut large: BTreeMap<usize, Vec<Rect>> = BTreeMap::new();
|
||||
let mut all_boxes: BTreeMap<usize, Vec<Rect>> = BTreeMap::new();
|
||||
for (item, bounds) in items {
|
||||
if is_seam_fills(&item) {
|
||||
return Err(bad(cmd, "byColor needs the seam fills' group under every path: move it to the bottom or delete it"));
|
||||
}
|
||||
if matches!(item.kind, NodeKind::Group { .. }) {
|
||||
return Err(bad(cmd, "byColor can't split Auto Grouping groups: trace without Auto Grouping"));
|
||||
}
|
||||
@@ -637,12 +651,12 @@ fn prepare(s: &Session, c: &str, p: &Value) -> Result<Prepared> {
|
||||
}
|
||||
|
||||
/// What a trace made of an image: the size in pixels it was decoded at, the paths, and their seam
|
||||
/// fills ([`seams_within`]).
|
||||
/// fills, if any ([`seams_within`]).
|
||||
pub struct Traced {
|
||||
inputs: TraceInputs,
|
||||
raster: (u32, u32),
|
||||
res: tr::TraceResult,
|
||||
seams: Vec<tr::TracedPath>,
|
||||
seams: Option<tr::SeamFills>,
|
||||
}
|
||||
|
||||
impl Traced {
|
||||
@@ -669,18 +683,127 @@ fn trace_now(inputs: &TraceInputs, params: &tr::TraceParams, steps: &(dyn Fn(u64
|
||||
tr::TraceError::Cancelled => EngineError::Cancelled,
|
||||
e => EngineError::Other(e.to_string()),
|
||||
})?;
|
||||
let seams = seams_within(&res, params, MAX_TRACE_ANCHORS);
|
||||
Ok(Traced { inputs: inputs.clone(), raster: (raster.width, raster.height), res, seams })
|
||||
if !steps(0, 0) {
|
||||
return Err(EngineError::Cancelled);
|
||||
}
|
||||
let size = (raster.width, raster.height);
|
||||
let outlined = seam_unit(inputs.image.xf, raster_xf(&inputs.image, size)).is_none();
|
||||
let seams = seams_within(&res, params, size, MAX_TRACE_ANCHORS, outlined, steps)?;
|
||||
Ok(Traced { inputs: inputs.clone(), raster: size, res, seams })
|
||||
}
|
||||
|
||||
/// The seam fills of `res`, traced with `params` ([`tr::seam_fills`]), while the paths and the seam
|
||||
/// fills together stay within `max` anchors: the seam fills have at most as many anchors as the
|
||||
/// paths, so a trace whose paths have more than half of `max` gets none.
|
||||
fn seams_within(res: &tr::TraceResult, params: &tr::TraceParams, max: usize) -> Vec<tr::TracedPath> {
|
||||
if res.anchor_count() > max / 2 {
|
||||
return vec![];
|
||||
/// Pixel space of a `size` raster decoded from `img` → the image object's pixel space → document.
|
||||
fn raster_xf(img: &ImageObject, size: (u32, u32)) -> vectorcraft_geom::Affine {
|
||||
let sx = img.width.max(1) as f64 / size.0.max(1) as f64;
|
||||
let sy = img.height.max(1) as f64 / size.1.max(1) as f64;
|
||||
img.xf * vectorcraft_geom::Affine::scale_non_uniform(sx, sy)
|
||||
}
|
||||
|
||||
/// Whether `xf` scales every direction alike (turning and mirroring allowed): its axes keep equal
|
||||
/// lengths and stay at right angles.
|
||||
fn scales_alike(xf: vectorcraft_geom::Affine) -> bool {
|
||||
let [a, b, c, d, _, _] = xf.as_coeffs();
|
||||
let (across, down) = (a * a + b * b, c * c + d * d);
|
||||
let t = across + down;
|
||||
t.is_finite() && t > 0.0 && (across - down).abs() <= 1e-9 * t && (a * c + b * d).abs() <= 1e-9 * t
|
||||
}
|
||||
|
||||
/// The smallest length that `xf` scales a unit vector to (its smaller singular value): the
|
||||
/// difference of the lengths of its turning part and its stretching part.
|
||||
fn least_scale(xf: vectorcraft_geom::Affine) -> f64 {
|
||||
let [a, b, c, d, _, _] = xf.as_coeffs();
|
||||
let turning = ((a + d) / 2.0).hypot((b - c) / 2.0);
|
||||
let stretching = ((a - d) / 2.0).hypot((b + c) / 2.0);
|
||||
(turning - stretching).abs()
|
||||
}
|
||||
|
||||
/// Document units per raster pixel for the seam fills' strokes when the image object's transform
|
||||
/// `img_xf` scales every direction alike: the smaller scale of the raster-to-document transform
|
||||
/// `xf`, so that a stroke 1.5 pixels wide covers at most 0.75 pixels on each side of its edge at
|
||||
/// any angle. (A raster decoded scaled down to fit can be scaled a little differently across and
|
||||
/// down, as each side is rounded.) `None` when `img_xf` stretches one direction more than another
|
||||
/// or is degenerate, where a stroke of any one width would cover more pixels across some edges
|
||||
/// than across others.
|
||||
fn seam_unit(img_xf: vectorcraft_geom::Affine, xf: vectorcraft_geom::Affine) -> Option<f64> {
|
||||
let least = least_scale(xf);
|
||||
(scales_alike(img_xf) && least.is_finite() && least > 0.0).then_some(least)
|
||||
}
|
||||
|
||||
/// The seam fills of `res`, traced with `params` from a `size` raster ([`tr::seam_fills`]), while
|
||||
/// the paths, the seam fills and their clip together stay within `max` anchors. With `outlined`,
|
||||
/// each stroke is replaced by a filled path, its outline in raster pixels ([`outline_seams`]),
|
||||
/// for an image stretched more one way than another ([`seam_unit`]). The strokes have at most as
|
||||
/// many anchors as the paths and the clip at most [`SEAM_CLIP_ANCHORS`], so a trace whose paths
|
||||
/// have more than half of `max` less four gets none. Outlines, which have more anchors, are
|
||||
/// counted as each is made, and none is made when [`SEAM_OUTLINE_ANCHORS`] times the strokes'
|
||||
/// anchors would not fit, or once those made so far no longer fit. [`EngineError::Cancelled`]
|
||||
/// once `steps` answers `false`.
|
||||
fn seams_within(
|
||||
res: &tr::TraceResult,
|
||||
params: &tr::TraceParams,
|
||||
size: (u32, u32),
|
||||
max: usize,
|
||||
outlined: bool,
|
||||
steps: &(dyn Fn(u64, u64) -> bool + Sync),
|
||||
) -> Result<Option<tr::SeamFills>> {
|
||||
if res.anchor_count().saturating_mul(2).saturating_add(SEAM_CLIP_ANCHORS) > max {
|
||||
return Ok(None);
|
||||
}
|
||||
let Some(mut seams) = tr::seam_fills(&res.paths, params, size) else { return Ok(None) };
|
||||
if outlined {
|
||||
let strokes = seams.strokes.iter().map(|tp| tp.path.anchor_count()).sum::<usize>();
|
||||
let estimate = strokes.saturating_mul(SEAM_OUTLINE_ANCHORS).saturating_add(SEAM_CLIP_ANCHORS);
|
||||
if res.anchor_count().saturating_add(estimate) > max {
|
||||
return Ok(None);
|
||||
}
|
||||
let budget = max.saturating_sub(res.anchor_count()).saturating_sub(SEAM_CLIP_ANCHORS);
|
||||
if !outline_seams(&mut seams.strokes, budget, steps)? {
|
||||
return Ok(None);
|
||||
}
|
||||
seams.strokes.retain(|tp| !tp.path.is_empty());
|
||||
if seams.strokes.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
Ok(Some(seams))
|
||||
}
|
||||
|
||||
/// The most anchors the seam fills' clip has: the image's box cut to the box of the traced paths
|
||||
/// ([`within_box`]), four corners and at most four more where the image is turned.
|
||||
const SEAM_CLIP_ANCHORS: usize = 8;
|
||||
|
||||
/// How many seam strokes [`outline_seams`] outlines between asking whether to go on.
|
||||
const SEAM_OUTLINE_STEP: usize = 64;
|
||||
|
||||
/// Outline each of `strokes` ([`outlined_seam`]) while the outlines' anchors stay within `budget`,
|
||||
/// asking `steps` every [`SEAM_OUTLINE_STEP`] strokes whether to go on → whether every outline
|
||||
/// fits (it stops at the first that does not), or [`EngineError::Cancelled`] once `steps`
|
||||
/// answers `false`.
|
||||
fn outline_seams(strokes: &mut [tr::TracedPath], budget: usize, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result<bool> {
|
||||
let mut total = 0usize;
|
||||
for (i, tp) in strokes.iter_mut().enumerate() {
|
||||
if i % SEAM_OUTLINE_STEP == 0 && !steps(0, 0) {
|
||||
return Err(EngineError::Cancelled);
|
||||
}
|
||||
outlined_seam(tp);
|
||||
total = total.saturating_add(tp.path.anchor_count());
|
||||
if total > budget {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// About how many anchors a seam stroke's outline ([`outlined_seam`]) has for each anchor of the
|
||||
/// stroke: both sides of each segment and a round join at each anchor. Curves can take more.
|
||||
const SEAM_OUTLINE_ANCHORS: usize = 6;
|
||||
|
||||
/// Replace a seam stroke `tp` by the area it covers, as a filled path in the same raster pixels:
|
||||
/// butt caps and round joins, as the strokes have.
|
||||
fn outlined_seam(tp: &mut tr::TracedPath) {
|
||||
if let Some(width) = tp.stroke.take() {
|
||||
tp.path = vectorcraft_pathops::outline_stroke(&tp.path, width, vectorcraft_pathops::Cap::Butt, vectorcraft_pathops::Join::Round, 4.0);
|
||||
}
|
||||
tr::seam_fills(&res.paths, params)
|
||||
}
|
||||
|
||||
/// An Image Trace made away from its command, off the UI thread (#3098). [`TraceRun::prepare`]
|
||||
@@ -780,19 +903,12 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
let TraceInputs { target, image: img, .. } = inputs;
|
||||
let mut warnings = keep_warnings(&trace, &res);
|
||||
warnings.extend(trace_warnings((img.width, img.height), raster, res.worked_at));
|
||||
// Pixel space of the decoded raster → the image object's pixel space → document.
|
||||
let sx = img.width.max(1) as f64 / raster.0.max(1) as f64;
|
||||
let sy = img.height.max(1) as f64 / raster.1.max(1) as f64;
|
||||
let xf = img.xf * vectorcraft_geom::Affine::scale_non_uniform(sx, sy);
|
||||
let xf = raster_xf(&img, raster);
|
||||
// Document units per raster pixel (stroke widths).
|
||||
let unit = xf.determinant().abs().sqrt();
|
||||
// Seam fills: document units per raster pixel along the direction the image is stretched most,
|
||||
// so that a stroke covers its pixels across an edge at any angle.
|
||||
let seam_unit = {
|
||||
let [a, b, c, d, _, _] = xf.as_coeffs();
|
||||
let (t, det) = (a * a + b * b + c * c + d * d, a * d - b * c);
|
||||
((t + (t * t - 4.0 * det * det).max(0.0).sqrt()) / 2.0).sqrt()
|
||||
};
|
||||
// Seam fills: strokes when the image is scaled alike in every direction; on an image stretched
|
||||
// more one way, the trace outlined them in raster pixels ([`seams_within`]).
|
||||
let seam_unit = seam_unit(img.xf, xf);
|
||||
let (npaths, anchors, colors) = (res.paths.len(), res.anchor_count(), res.palette.len());
|
||||
let label = if expand { "Image Trace (Make and Expand)" } else { "Image Trace" };
|
||||
// A library color fills with the swatch's displayed color (its model kept), unlinked.
|
||||
@@ -824,29 +940,41 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
// Gradients: a path the tracer found to be a linear gradient is filled with it.
|
||||
tp.gradient.as_ref().map_or(solid, |g| traced_gradient(g, xf))
|
||||
};
|
||||
// Abutting: the seam fills, in a group of their own under every path.
|
||||
let seams: Vec<Arc<Node>> = seam_fills
|
||||
// Abutting: the seam fills, in a clip group of their own under every path, clipped to the
|
||||
// image's box within the traced paths' box: strokes, or on an image stretched more one
|
||||
// way, their outlines filled.
|
||||
let strokes: Vec<Arc<Node>> = seam_fills
|
||||
.iter()
|
||||
.flat_map(|f| &f.strokes)
|
||||
.filter_map(|tp| {
|
||||
let width = tp.stroke?;
|
||||
let mut n = shape_node(d, tp.path.transformed(xf), None);
|
||||
n.appearance = Appearance {
|
||||
items: vec![AppearanceItem::Stroke(StrokeLayer {
|
||||
cap: LineCap::Butt,
|
||||
join: LineJoin::Round,
|
||||
..StrokeLayer::new(paint_of(tp), width * seam_unit)
|
||||
})],
|
||||
..Default::default()
|
||||
let outline = match (tp.stroke, seam_unit) {
|
||||
(Some(width), Some(u)) => {
|
||||
let mut n = shape_node(d, tp.path.transformed(xf), None);
|
||||
n.appearance = Appearance {
|
||||
items: vec![AppearanceItem::Stroke(StrokeLayer {
|
||||
cap: LineCap::Butt,
|
||||
join: LineJoin::Round,
|
||||
..StrokeLayer::new(paint_of(tp), width * u)
|
||||
})],
|
||||
..Default::default()
|
||||
}
|
||||
.into();
|
||||
return Some(Arc::new(n));
|
||||
}
|
||||
// The trace leaves strokes only for an image scaled alike in every direction,
|
||||
// with these same inputs; a stroke is left out here rather than outlined
|
||||
// outside the anchor limit.
|
||||
(Some(_), None) => return None,
|
||||
(None, _) => tp.path.clone(),
|
||||
};
|
||||
if outline.is_empty() {
|
||||
return None;
|
||||
}
|
||||
.into();
|
||||
let mut n = shape_node(d, outline.transformed(xf), None);
|
||||
n.appearance = fill_only(paint_of(tp)).into();
|
||||
Some(Arc::new(n))
|
||||
})
|
||||
.collect();
|
||||
if !seams.is_empty() {
|
||||
let mut g = Node::group(d.alloc_id(), seams);
|
||||
g.name = Some(SEAM_FILLS_NAME.into());
|
||||
children.push(Arc::new(g));
|
||||
}
|
||||
let mut traced = Vec::with_capacity(res.paths.len());
|
||||
for tp in res.paths {
|
||||
let paint = paint_of(&tp);
|
||||
@@ -873,6 +1001,23 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
};
|
||||
traced.push(n);
|
||||
}
|
||||
// The seam fills' clip is the image's box cut to the box of the traced paths, so the group
|
||||
// stays within the box the paths measure.
|
||||
let art = traced.iter().filter_map(Node::geometric_bounds).reduce(|a, b| a.union(b));
|
||||
if let (Some(f), Some(art)) = (seam_fills.as_ref().filter(|_| !strokes.is_empty()), art) {
|
||||
let corners: Vec<Point> = f.clip.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| xf * a.p)).collect();
|
||||
let inside = within_box(&corners, art);
|
||||
if inside.len() >= 3 {
|
||||
let mut clip = shape_node(d, vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&inside, true)), None);
|
||||
if let NodeKind::Path { clipping, .. } = &mut clip.kind {
|
||||
*clipping = true;
|
||||
}
|
||||
let members = std::iter::once(Arc::new(clip)).chain(strokes).collect();
|
||||
let mut g = Node::new(d.alloc_id(), NodeKind::Group { children: members, clip: true });
|
||||
g.name = Some(SEAM_FILLS_NAME.into());
|
||||
children.push(Arc::new(g));
|
||||
}
|
||||
}
|
||||
children.extend(grouped(d, traced, &res.parents));
|
||||
if group_by_color {
|
||||
children = color_groups(c, d, children)?;
|
||||
@@ -894,6 +1039,28 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
Ok(json!({ "id": id.0, "paths": npaths, "anchors": anchors, "colors": colors, "warnings": warnings }))
|
||||
}
|
||||
|
||||
/// The part of the convex polygon `poly` inside `r`, as a polygon with at most four more corners
|
||||
/// than `poly` (each side of `r` cuts at most one corner off and adds two); empty when none of it
|
||||
/// is inside.
|
||||
fn within_box(poly: &[Point], r: Rect) -> Vec<Point> {
|
||||
let sides: [&dyn Fn(Point) -> f64; 4] = [&|p| p.x - r.x0, &|p| r.x1 - p.x, &|p| p.y - r.y0, &|p| r.y1 - p.y];
|
||||
let mut out = poly.to_vec();
|
||||
for side in sides {
|
||||
let corners = std::mem::take(&mut out);
|
||||
for (k, &p) in corners.iter().enumerate() {
|
||||
let Some(&q) = corners.get((k + 1) % corners.len()) else { continue };
|
||||
let (dp, dq) = (side(p), side(q));
|
||||
if dp >= 0.0 {
|
||||
out.push(p);
|
||||
}
|
||||
if (dp > 0.0 && dq < 0.0) || (dp < 0.0 && dq > 0.0) {
|
||||
out.push(p + (q - p) * (dp / (dp - dq)));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Images larger than this on a side are traced, but more slowly: the trace says so.
|
||||
pub const LARGE_TRACE_SIDE: u32 = 1500;
|
||||
|
||||
@@ -1193,7 +1360,7 @@ mod color_group_tests {
|
||||
|
||||
#[cfg(test)]
|
||||
mod trace_limit_tests {
|
||||
use super::{MAX_TRACE_ANCHORS, keep_warnings, seams_within, trace_warnings};
|
||||
use super::{MAX_TRACE_ANCHORS, SEAM_CLIP_ANCHORS, SEAM_OUTLINE_ANCHORS, keep_warnings, outline_seams, seams_within, trace_warnings};
|
||||
use vectorcraft_trace as tr;
|
||||
|
||||
#[test]
|
||||
@@ -1206,13 +1373,89 @@ mod trace_limit_tests {
|
||||
});
|
||||
let params = tr::TraceParams { mode: tr::Mode::Color, colors: 2, method: tr::Method::Abutting, ..tr::TraceParams::default() };
|
||||
let res = tr::trace(&img, ¶ms);
|
||||
let all = tr::seam_fills(&res.paths, ¶ms);
|
||||
assert!(!all.is_empty(), "{res:?}");
|
||||
let all = tr::seam_fills(&res.paths, ¶ms, (24, 16));
|
||||
assert!(all.is_some(), "{res:?}");
|
||||
let anchors = res.anchor_count();
|
||||
// Twice the paths' anchors leaves room for any seam fills.
|
||||
assert_eq!(seams_within(&res, ¶ms, 2 * anchors), all);
|
||||
assert!(anchors + all.as_ref().map_or(0, tr::SeamFills::anchor_count) <= 2 * anchors + SEAM_CLIP_ANCHORS);
|
||||
let go = |_: u64, _: u64| true;
|
||||
// Twice the paths' anchors and the clip's eight at most leave room for any seam fills.
|
||||
assert_eq!(seams_within(&res, ¶ms, (24, 16), 2 * anchors + SEAM_CLIP_ANCHORS, false, &go).unwrap(), all);
|
||||
// One anchor short of that: none.
|
||||
assert_eq!(seams_within(&res, ¶ms, 2 * anchors - 1), []);
|
||||
assert_eq!(seams_within(&res, ¶ms, (24, 16), 2 * anchors + SEAM_CLIP_ANCHORS - 1, false, &go).unwrap(), None);
|
||||
// Outlined, the seam fills are filled paths, within SEAM_OUTLINE_ANCHORS of the strokes'
|
||||
// anchors each.
|
||||
let strokes = |f: &tr::SeamFills| f.strokes.iter().map(|tp| tp.path.anchor_count()).sum::<usize>();
|
||||
let outlined = seams_within(&res, ¶ms, (24, 16), MAX_TRACE_ANCHORS, true, &go).unwrap().unwrap();
|
||||
assert!(outlined.strokes.iter().all(|tp| tp.stroke.is_none() && !tp.path.is_empty()), "{outlined:?}");
|
||||
let n = strokes(all.as_ref().unwrap());
|
||||
assert!(strokes(&outlined) <= SEAM_OUTLINE_ANCHORS * n, "{} outline anchors, {n} stroke anchors", strokes(&outlined));
|
||||
// A staircase edge: the outline's round joins give it more anchors than the paths have. The
|
||||
// outlines are made only when SEAM_OUTLINE_ANCHORS times the strokes' anchors fit.
|
||||
let img = tr::Raster::from_fn(32, 32, |x, y| if x < y / 4 * 4 + 4 { [200, 40, 50, 255] } else { [30, 90, 200, 255] });
|
||||
let params = tr::TraceParams { corners: 100.0, ..params };
|
||||
let res = tr::trace(&img, ¶ms);
|
||||
let anchors = res.anchor_count();
|
||||
let all = tr::seam_fills(&res.paths, ¶ms, (32, 32)).unwrap();
|
||||
let n = strokes(&all);
|
||||
let outlined = seams_within(&res, ¶ms, (32, 32), MAX_TRACE_ANCHORS, true, &go).unwrap().unwrap();
|
||||
assert!(strokes(&outlined) > anchors, "{} outline anchors, {anchors} in the paths", strokes(&outlined));
|
||||
assert!(strokes(&outlined) <= SEAM_OUTLINE_ANCHORS * n, "{} outline anchors, {n} stroke anchors", strokes(&outlined));
|
||||
let fits = anchors + SEAM_OUTLINE_ANCHORS * n + SEAM_CLIP_ANCHORS;
|
||||
assert!(fits > 2 * anchors + SEAM_CLIP_ANCHORS, "{fits}, {anchors} in the paths");
|
||||
assert_eq!(seams_within(&res, ¶ms, (32, 32), fits, true, &go).unwrap(), Some(outlined.clone()));
|
||||
assert_eq!(seams_within(&res, ¶ms, (32, 32), fits - 1, true, &go).unwrap(), None);
|
||||
assert_eq!(seams_within(&res, ¶ms, (32, 32), fits - 1, false, &go).unwrap(), Some(all.clone()));
|
||||
// The outlines are counted as each is made: they stop at the first one past the budget, so
|
||||
// outlines with more anchors than the estimate allows are refused too.
|
||||
let need = strokes(&outlined);
|
||||
assert!(outline_seams(&mut all.strokes.clone(), need, &go).unwrap());
|
||||
assert!(!outline_seams(&mut all.strokes.clone(), need - 1, &go).unwrap());
|
||||
// Canceled while outlining: the run stops.
|
||||
let stop = |_: u64, _: u64| false;
|
||||
assert!(matches!(seams_within(&res, ¶ms, (32, 32), MAX_TRACE_ANCHORS, true, &stop), Err(super::EngineError::Cancelled)));
|
||||
assert!(matches!(outline_seams(&mut all.strokes.clone(), need, &stop), Err(super::EngineError::Cancelled)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn within_box_cuts_a_turned_box_to_a_box() {
|
||||
use vectorcraft_geom::{Point, Rect};
|
||||
// A square turned by 45° in a smaller box: each side cuts a corner off, 8 corners.
|
||||
let diamond = [Point::new(0.0, -10.0), Point::new(10.0, 0.0), Point::new(0.0, 10.0), Point::new(-10.0, 0.0)];
|
||||
let cut = super::within_box(&diamond, Rect::new(-6.0, -6.0, 6.0, 6.0));
|
||||
assert_eq!(cut.len(), 8, "{cut:?}");
|
||||
assert!(cut.iter().all(|p| p.x.abs() <= 6.0 + 1e-12 && p.y.abs() <= 6.0 + 1e-12 && p.x.abs() + p.y.abs() <= 10.0 + 1e-12), "{cut:?}");
|
||||
// A corner on a side is kept once.
|
||||
let square = [Point::new(0.0, 0.0), Point::new(4.0, 0.0), Point::new(4.0, 4.0), Point::new(0.0, 4.0)];
|
||||
assert_eq!(super::within_box(&square, Rect::new(0.0, 0.0, 4.0, 4.0)), square.to_vec());
|
||||
assert_eq!(super::within_box(&square, Rect::new(1.0, 0.0, 4.0, 4.0)).len(), 4);
|
||||
assert!(super::within_box(&square, Rect::new(5.0, 5.0, 6.0, 6.0)).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seams_are_strokes_only_where_the_image_is_scaled_alike_every_way() {
|
||||
use super::seam_unit;
|
||||
use vectorcraft_geom::Affine;
|
||||
assert_eq!(seam_unit(Affine::scale(2.0), Affine::scale(2.0)), Some(2.0));
|
||||
assert_eq!(seam_unit(Affine::new([-2.0, 0.0, 0.0, 2.0, 5.0, 7.0]), Affine::new([-2.0, 0.0, 0.0, 2.0, 5.0, 7.0])), Some(2.0));
|
||||
// Turned and scaled alike at any angle, rounding included.
|
||||
for k in [0.5, 1.0, 3.0, 17.0] {
|
||||
for i in 0..2000 {
|
||||
let xf = Affine::rotate(f64::from(i) * std::f64::consts::TAU / 2000.0) * Affine::scale(k);
|
||||
let unit = seam_unit(xf, xf);
|
||||
assert!(unit.is_some_and(|u| (u - k).abs() < 1e-9 * k), "{unit:?} at step {i}, scale {k}");
|
||||
}
|
||||
}
|
||||
let xf = Affine::rotate(0.0496) * Affine::scale(0.5);
|
||||
assert!(seam_unit(xf, xf).is_some());
|
||||
// A raster decoded scaled down to fit (10000 × 7000 pixels as 9791 × 6853) of an image placed
|
||||
// at 2×: strokes, at the smaller scale.
|
||||
let (sx, sy) = (10000.0 / 9791.0, 7000.0 / 6853.0);
|
||||
let unit = seam_unit(Affine::scale(2.0), Affine::scale(2.0) * Affine::scale_non_uniform(sx, sy)).unwrap();
|
||||
assert!((unit - 2.0 * f64::min(sx, sy)).abs() < 1e-12, "{unit}");
|
||||
assert_eq!(seam_unit(Affine::scale_non_uniform(20.0, 1.0), Affine::scale_non_uniform(20.0, 1.0)), None);
|
||||
assert_eq!(seam_unit(Affine::skew(0.5, 0.0), Affine::skew(0.5, 0.0)), None);
|
||||
assert_eq!(seam_unit(Affine::scale_non_uniform(1.0, 0.0), Affine::scale_non_uniform(1.0, 0.0)), None);
|
||||
assert_eq!(seam_unit(Affine::scale(0.0), Affine::scale(0.0)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -173,7 +173,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Clipboard Formats",
|
||||
[],
|
||||
None,
|
||||
"{} → {flavours: [mime…]} what Copy offers other apps for the current clipboard, best first, by the Clipboard Handling preferences: text/plain (a type-only copy's text, else the SVG markup with copyAsSvg when the images it embeds total at most 1 MiB), image/svg+xml (copyAsSvg), application/pdf (copyAsPdf), image/png (always; PDF and PNG only for objects with an area); the app publishes them on Copy and Cut",
|
||||
"{} → {flavours: [mime…]} what Copy offers other apps for the current clipboard, best first, by the Clipboard Handling preferences: text/plain (a type-only copy's text, else the SVG markup with copyAsSvg when the images it embeds total at most 1 MiB), image/svg+xml (copyAsSvg), application/pdf (copyAsPdf), image/png (always; PDF and PNG only for objects with an area); under read roots, SVG and its markup as text are left out when clipboard.exportSvg would refuse; the app publishes them on Copy and Cut",
|
||||
always,
|
||||
flavours
|
||||
),
|
||||
@@ -369,13 +369,20 @@ impl Session {
|
||||
|
||||
/// The MIME types of [`Self::clipboard_flavours`], without making them.
|
||||
pub fn clipboard_flavour_types(&self) -> Vec<&'static str> {
|
||||
self.clipboard.flavour_types(self.prefs.copy_as_svg, self.prefs.copy_as_pdf)
|
||||
self.clipboard.flavour_types(self.clipboard_svg_offered(), self.prefs.copy_as_pdf)
|
||||
}
|
||||
|
||||
/// What Copy offers other apps, best first (see `clipboard.flavours`): [`Clipboard::flavours`]
|
||||
/// by the Clipboard Handling preferences.
|
||||
/// by the Clipboard Handling preferences, without the SVG (and the SVG markup as text) that
|
||||
/// [`Self::clipboard_svg_refused`] withholds from the caller asking now.
|
||||
pub fn clipboard_flavours(&self) -> Vec<Flavour> {
|
||||
self.clipboard.flavours(self.prefs.copy_as_svg, self.prefs.copy_as_pdf)
|
||||
self.clipboard.flavours(self.clipboard_svg_offered(), self.prefs.copy_as_pdf)
|
||||
}
|
||||
|
||||
/// Does Copy offer the SVG: Include SVG Code is on and the SVG is not withheld from the caller
|
||||
/// asking now.
|
||||
fn clipboard_svg_offered(&self) -> bool {
|
||||
self.prefs.copy_as_svg && !self.clipboard_svg_refused()
|
||||
}
|
||||
|
||||
/// Replace the clipboard with `clip`, centred on `p`'s `center` (default: the first
|
||||
|
||||
@@ -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, 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}",
|
||||
"{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, and on a graph's axis line, tick mark or radar ring its rows for every line 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)
|
||||
),
|
||||
@@ -533,7 +533,7 @@ pub(crate) fn keeping_series_paint(d: &mut Document, roots: &[NodeId], recolor:
|
||||
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);
|
||||
super::graph::capture_label_changes(&before, d, &labels, true, Some(roots));
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
@@ -803,8 +803,8 @@ fn map_effect_colors(a: &mut vectorcraft_doc::Appearance, f: &mut dyn FnMut(&Col
|
||||
}
|
||||
}
|
||||
|
||||
/// `f` applied to the series paints and the label styles that graph `g` keeps, which its marks and
|
||||
/// labels take each time it is drawn again.
|
||||
/// `f` applied to the series paints, the label styles and the line rows that graph `g` keeps, which
|
||||
/// its marks, labels and lines take each time it is drawn again.
|
||||
fn map_graph_colors(g: &mut vectorcraft_doc::GraphSpec, f: &mut dyn FnMut(&Color, proof::Link) -> Color) {
|
||||
for p in g.series_paints.iter_mut() {
|
||||
for paint in [&mut p.fill, &mut p.stroke].into_iter().flatten() {
|
||||
@@ -823,7 +823,10 @@ fn map_graph_colors(g: &mut vectorcraft_doc::GraphSpec, f: &mut dyn FnMut(&Color
|
||||
}
|
||||
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() {
|
||||
for r in [&mut styles.values_rows, &mut styles.categories_rows, &mut styles.legend_rows, &mut styles.axis_rows, &mut styles.ring_rows]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
for paint in [&mut r.paint.fill, &mut r.paint.stroke].into_iter().flatten() {
|
||||
map_paint_colors(paint, f);
|
||||
}
|
||||
|
||||
@@ -881,7 +881,8 @@ pub(crate) fn new_area_fit(s: &Session, p: &Value, c: &str, t: &mut TextObject)
|
||||
|
||||
/// The character style new type gets: `size`, `font`, `style` and `color` from `p` (an RGB
|
||||
/// `color` in a CMYK document as [`super::paint::new_color`] stores it), else the defaults,
|
||||
/// filled with the current fill unless that is None or white (black then), in the document's
|
||||
/// filled as `[Normal Character Style]` is (black unless redefined; never the current fill,
|
||||
/// #7975), in the document's
|
||||
/// language. A `size` outside [`super::typecmd::TYPE_SIZES`] is an error.
|
||||
pub(crate) fn new_type_style(s: &Session, p: &Value, cmd: &str) -> Result<CharStyle> {
|
||||
let mut style = CharStyle::default();
|
||||
@@ -899,8 +900,7 @@ pub(crate) fn new_type_style(s: &Session, p: &Value, cmd: &str) -> Result<CharSt
|
||||
}
|
||||
style.fill = match p.get("color").and_then(color_value) {
|
||||
Some(c) => vectorcraft_color::Paint::solid(super::paint::new_color(s, p, c)),
|
||||
None if !s.paint.fill.is_none() && s.paint.fill != vectorcraft_color::Paint::solid(vectorcraft_color::Color::WHITE) => s.paint.fill.clone(),
|
||||
None => vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK),
|
||||
None => s.doc().map_or_else(|_| CharStyle::default().fill, |d| super::textstyles::normal_char_fill(&d.doc)),
|
||||
};
|
||||
// In the language Document Setup chose, else Preferences › Hyphenation › Default Language; none
|
||||
// for the default. Type already in a document keeps its own.
|
||||
|
||||
@@ -857,14 +857,12 @@ mod tests {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
|
||||
s.execute(
|
||||
"paint.setFill",
|
||||
&json!({"gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]}}),
|
||||
)
|
||||
.unwrap();
|
||||
let gradient = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]});
|
||||
s.execute("paint.setFill", &json!({"gradient": gradient})).unwrap();
|
||||
let t = s.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi"})).unwrap()["id"].clone();
|
||||
// New type starts black (#7975); filled with the gradient, its characters make it a gradient object too.
|
||||
s.execute("paint.setFill", &json!({"gradient": gradient, "ids": [t]})).unwrap();
|
||||
let i = s.execute("document.info", &json!({})).unwrap();
|
||||
// The type's characters take the current gradient fill, so it is a gradient object too.
|
||||
assert_eq!(
|
||||
(i["objects"]["paths"].as_u64(), i["objects"]["textObjects"].as_u64(), i["objects"]["gradients"].as_u64()),
|
||||
(Some(1), Some(1), Some(2))
|
||||
|
||||
@@ -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, 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",
|
||||
"{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, 0..360: 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. A pressure, tilt or rotation outside its range, or a point array of more than six numbers, is an error), 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
|
||||
),
|
||||
@@ -83,7 +83,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Knife",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…]} cut closed shapes (selected, or all when nothing is selected) along the polyline → {ids}",
|
||||
"{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the cut)} cut closed shapes (selected, or all when nothing is selected) along the polyline → {ids}",
|
||||
has_doc,
|
||||
knife
|
||||
),
|
||||
@@ -92,7 +92,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Eraser",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation ° clockwise, as path.freehand), size?: pt (10), angle?: ° (0, −180–180: the tip's long axis counter-clockwise from level), roundness?: % (100, 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0 or more, default 0)} or {rect: [x, y, width, height] (pt; the Eraser's Alt-drag marquee)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An angle or roundness outside its range, an unknown mode, or a variation below 0 or past its range is refused with an error and erases nothing. `rect` in place of `points` erases everything inside the rectangle: closed paths lose its area, and open paths are cut where they cross its edges; the tip's size, angle, roundness and variations do not apply. A width or height of 0 or less, a value that is not a finite number, or `points` and `rect` together is an error. When nothing is erased, no undo step is added",
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation 0..360° clockwise; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), angle?: ° (0, −180–180: the tip's long axis counter-clockwise from level), roundness?: % (100, 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0–1000, default 0)} or {rect: [x, y, width, height] (pt; the Eraser's Alt-drag marquee)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An angle or roundness outside its range, an unknown mode, or a variation below 0 or past its range is refused with an error and erases nothing. `rect` in place of `points` erases everything inside the rectangle: closed paths lose its area, and open paths are cut where they cross its edges; the tip's size, angle, roundness and variations do not apply. A width or height of 0 or less, a value that is not a finite number, or `points` and `rect` together is an error. When nothing is erased, no undo step is added",
|
||||
has_doc,
|
||||
erase_region
|
||||
),
|
||||
@@ -101,7 +101,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Path Eraser",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…], width?: pt (8)} erase the parts of selected paths under the drag → {ids}",
|
||||
"{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change what is erased), width?: pt (8)} erase the parts of selected paths under the drag → {ids}",
|
||||
has_selection,
|
||||
erase_segments
|
||||
),
|
||||
@@ -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, 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}",
|
||||
"{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the smoothing), 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
|
||||
),
|
||||
@@ -119,7 +119,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Join",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…], tolerance?: pt (12)} join the open-path endpoints scrubbed over, or trim two crossing open paths whose overhanging ends are scrubbed and join them at the crossing → {id}",
|
||||
"{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the join), tolerance?: pt (12)} join the open-path endpoints scrubbed over, or trim two crossing open paths whose overhanging ends are scrubbed and join them at the crossing → {id}",
|
||||
has_doc,
|
||||
join_scrub
|
||||
),
|
||||
@@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Blob Brush",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1), size?: pt (10), sizeMode?: \"fixed\" (default) | \"pressure\" (Blob Brush Tool Options' Size set to Pressure: the brush is size − sizeVariation wide at the lightest pen pressure and size + sizeVariation at the heaviest, at least 0.1 pt; a stroke without pressure keeps the size), sizeVariation?: pt (0), angle?: ° (0, kept within −180–180: the tip's long axis counter-clockwise from horizontal, kept on the page along the stroke), roundness?: % (100, kept within 0–100: the tip's short axis in percent of its long one, 100 round; 0 is drawn as 0.1), fidelity?: pt (0.01–100; the brush follows the stroke fitted at this tolerance as path.freehand fits a Pencil stroke, and a higher value gives a smoother shape; without it the brush follows every point), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with the topmost touching same-color blob and the touching ones next to it in stacking order in its group or layer → {id}",
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), sizeMode?: \"fixed\" (default) | \"pressure\" (Blob Brush Tool Options' Size set to Pressure: the brush is size − sizeVariation wide at the lightest pen pressure and size + sizeVariation at the heaviest, at least 0.1 pt; a stroke without pressure keeps the size), sizeVariation?: pt (0; from 0 to 1000, checked with Fixed too), angle?: ° (0, kept within −180–180: the tip's long axis counter-clockwise from horizontal, kept on the page along the stroke), roundness?: % (100, kept within 0–100: the tip's short axis in percent of its long one, 100 round; 0 is drawn as 0.1), fidelity?: pt (0.01–100; the brush follows the stroke fitted at this tolerance as path.freehand fits a Pencil stroke, and a higher value gives a smoother shape; without it the brush follows every point), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with the topmost touching same-color blob and the touching ones next to it in stacking order in its group or layer → {id}",
|
||||
has_doc,
|
||||
blob
|
||||
),
|
||||
|
||||
@@ -28,6 +28,27 @@ pub(super) struct Sample {
|
||||
/// x and y.
|
||||
const PEN_KEYS: [&str; 4] = ["pressure", "tiltX", "tiltY", "rotation"];
|
||||
|
||||
/// The range each of [`PEN_KEYS`] takes: pressure 0..1, each tilt −90..90 degrees and rotation
|
||||
/// 0..360 degrees (360 is the same direction as 0).
|
||||
const PEN_RANGES: [(f64, f64); PEN_KEYS.len()] = [(0.0, 1.0), (-90.0, 90.0), (-90.0, 90.0), (0.0, 360.0)];
|
||||
|
||||
/// Blob Brush and Eraser Tool Options' Size, in points.
|
||||
pub(super) const SIZES: (f64, f64) = (0.1, 1000.0);
|
||||
|
||||
/// Blob Brush and Eraser Tool Options' Size Variation, in points.
|
||||
pub(super) const SIZE_VARIATIONS: (f64, f64) = (0.0, 1000.0);
|
||||
|
||||
/// `v`, or an error naming `key` when it is outside `lo..=hi` (or not a number at all, NaN).
|
||||
fn within(v: f64, key: &str, (lo, hi): (f64, f64), cmd: &str) -> Result<f64> {
|
||||
if (lo..=hi).contains(&v) { Ok(v) } else { Err(bad(cmd, format!("`{key}` must be from {lo} to {hi}"))) }
|
||||
}
|
||||
|
||||
/// The number `p` gives for `key`, `default` when it leaves it out or gives null, as [`number_or`]
|
||||
/// reads it, or an error naming `key` when the number is outside `range`.
|
||||
pub(super) fn ranged(p: &Value, key: &str, default: f64, range: (f64, f64), cmd: &str) -> Result<f64> {
|
||||
within(number_or(p, key, default, cmd)?, key, range, cmd)
|
||||
}
|
||||
|
||||
/// The point `[x, y, …]` or `{x, y, …}` that `v` holds, or an error when its x or y is not a finite
|
||||
/// number.
|
||||
pub(super) fn point_entry(v: &Value, cmd: &str) -> Result<Point> {
|
||||
@@ -42,27 +63,36 @@ pub(super) fn point_entry(v: &Value, cmd: &str) -> Result<Point> {
|
||||
/// [`points_param`] with what a pen read at each point, as far as it is given:
|
||||
/// `[[x,y,pressure,tiltX,tiltY,rotation]…]` or `[{x,y,pressure,tiltX,tiltY,rotation}…]`. Pressure
|
||||
/// is 0..1; tilt in degrees, each −90..90 (one of the two without the other is 0); rotation in
|
||||
/// degrees clockwise. A point whose x or y is not a number, or whose pressure, tilt or rotation is
|
||||
/// neither a number nor null, is an error.
|
||||
/// degrees clockwise, 0..360. A point whose x or y is not a number, whose pressure, tilt or
|
||||
/// rotation is neither a number nor null or is outside its range, or an array of more than six
|
||||
/// numbers, is an error.
|
||||
pub(super) fn samples_param(p: &Value, key: &str, cmd: &str) -> Result<Vec<Sample>> {
|
||||
let a = p.get(key).and_then(Value::as_array).ok_or_else(|| bad(cmd, format!("missing array `{key}`")))?;
|
||||
let pts: Vec<Sample> = a
|
||||
.iter()
|
||||
.map(|v| {
|
||||
.enumerate()
|
||||
.map(|(at, v)| {
|
||||
const MAX_ITEMS: usize = 2 + PEN_KEYS.len();
|
||||
if let Value::Array(xy) = v
|
||||
&& xy.len() > MAX_ITEMS
|
||||
{
|
||||
let key = format!("{key}[{at}]");
|
||||
return Err(bad(cmd, format!("`{key}` must be an array of at most {MAX_ITEMS} entries")));
|
||||
}
|
||||
let mut pen = [None; 4];
|
||||
for (i, (key, slot)) in PEN_KEYS.iter().zip(&mut pen).enumerate() {
|
||||
for (i, ((key, range), slot)) in PEN_KEYS.iter().zip(PEN_RANGES).zip(&mut pen).enumerate() {
|
||||
let given = match v {
|
||||
Value::Array(xy) => xy.get(i + 2),
|
||||
_ => v.get(*key),
|
||||
};
|
||||
*slot = match given {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(n @ Value::Number(_)) => n.as_f64(),
|
||||
Some(n @ Value::Number(_)) => n.as_f64().map(|x| within(x, key, range, cmd)).transpose()?,
|
||||
Some(v) => return Err(bad(cmd, format!("`{key}` must be a number, not {v}"))),
|
||||
};
|
||||
}
|
||||
let [pressure, tx, ty, rotation] = pen;
|
||||
let tilt = (tx.is_some() || ty.is_some()).then(|| [tx, ty].map(|t| t.unwrap_or(0.0).clamp(-90.0, 90.0)));
|
||||
let tilt = (tx.is_some() || ty.is_some()).then(|| [tx, ty].map(|t| t.unwrap_or(0.0)));
|
||||
Ok(Sample { pt: point_entry(v, cmd)?, pressure, tilt, rotation })
|
||||
})
|
||||
.collect::<Result<_>>()?;
|
||||
@@ -186,18 +216,14 @@ impl PenRecord {
|
||||
}
|
||||
|
||||
/// Blob Brush and Eraser Tool Options' Size set to Pressure (`sizeMode: "pressure"`, with
|
||||
/// `sizeVariation` in points): the stroke's pen pressure along it and the variation, `None` for
|
||||
/// Fixed (the default), no variation or a stroke without pressure (a mouse), which keeps the size.
|
||||
/// `sizeVariation` in points, 0..1000): the stroke's pen pressure along it and the variation, `None`
|
||||
/// for Fixed (the default), no variation or a stroke without pressure (a mouse), which keeps the
|
||||
/// size. A `sizeVariation` outside its range is an error with Fixed too.
|
||||
pub(super) fn size_pressure(p: &Value, samples: &[Sample], cmd: &str) -> Result<Option<(PressureProfile, f64)>> {
|
||||
let variation = ranged(p, "sizeVariation", 0.0, SIZE_VARIATIONS, cmd)?;
|
||||
match p.get("sizeMode").filter(|v| !v.is_null()).map(|v| v.as_str().ok_or(v)) {
|
||||
None | Some(Ok("fixed")) => Ok(None),
|
||||
Some(Ok("pressure")) => {
|
||||
let variation = number_or(p, "sizeVariation", 0.0, cmd)?;
|
||||
if !(variation.is_finite() && variation >= 0.0) {
|
||||
return Err(bad(cmd, "sizeVariation must be 0 or more"));
|
||||
}
|
||||
Ok(stroke_pressure(samples).filter(|_| variation > 0.0).map(|prof| (prof, variation)))
|
||||
}
|
||||
Some(Ok("pressure")) => Ok(stroke_pressure(samples).filter(|_| variation > 0.0).map(|prof| (prof, variation))),
|
||||
Some(Ok(other)) => Err(bad(cmd, format!("sizeMode is \"fixed\" or \"pressure\", not `{other}`"))),
|
||||
Some(Err(other)) => Err(bad(cmd, format!("sizeMode is \"fixed\" or \"pressure\", not {other}"))),
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::common::{
|
||||
PenRecord, Sample, dist_to_polyline, fill_targets, ids_json, path_mut, path_of, points_param, poly_bounds, pressure_region, replace_with_pieces,
|
||||
samples_param, sibling_with, size_pressure, target_paths, usize_opt,
|
||||
PenRecord, SIZE_VARIATIONS, SIZES, Sample, dist_to_polyline, fill_targets, ids_json, path_mut, path_of, points_param, poly_bounds,
|
||||
pressure_region, ranged, replace_with_pieces, samples_param, sibling_with, size_pressure, target_paths, usize_opt,
|
||||
};
|
||||
use super::{
|
||||
Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, Paint, ParamCurve, PathData, Point, Rect, Result, Session,
|
||||
@@ -296,10 +296,7 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return erase_rect(s, marquee_param(rect, C)?);
|
||||
}
|
||||
let samples = samples_param(p, "points", C)?;
|
||||
let size = number_or(p, "size", 10.0, C)?;
|
||||
if !(size.is_finite() && size > 0.0) {
|
||||
return Err(bad(C, "size must be positive"));
|
||||
}
|
||||
let size = ranged(p, "size", 10.0, SIZES, C)?;
|
||||
let angle = number_or(p, "angle", 0.0, C)?;
|
||||
if !(-180.0..=180.0).contains(&angle) {
|
||||
return Err(bad(C, "`angle` must be from -180 to 180 degrees"));
|
||||
@@ -410,12 +407,13 @@ const ERASER_MODES: &str = "\"fixed\", \"random\", \"pressure\", \"tilt\", \"bea
|
||||
|
||||
/// Eraser Tool Options' Angle, Roundness and Size variations: for each of angle (`angleMode` with
|
||||
/// `angleVariation` in degrees, at most 180), roundness (`roundnessMode` with `roundnessVariation`
|
||||
/// in percent, at most 100) and size (`sizeMode` with `sizeVariation` in points), its mode and how
|
||||
/// far it varies either way. A mode left out or null is Fixed, and a variation left out or null
|
||||
/// is 0; any other mode, or a variation that is negative or past its most, is refused.
|
||||
/// in percent, at most 100) and size (`sizeMode` with `sizeVariation` in points, at most 1000), its
|
||||
/// mode and how far it varies either way. A mode left out or null is Fixed, and a variation left
|
||||
/// out or null is 0; any other mode, or a variation that is negative or past its most, is refused,
|
||||
/// in every mode.
|
||||
fn eraser_variations(p: &Value, cmd: &str) -> Result<[(Variation, f64); 3]> {
|
||||
const KEYS: [(&str, &str, f64); 3] =
|
||||
[("angleMode", "angleVariation", 180.0), ("roundnessMode", "roundnessVariation", 100.0), ("sizeMode", "sizeVariation", f64::INFINITY)];
|
||||
[("angleMode", "angleVariation", 180.0), ("roundnessMode", "roundnessVariation", 100.0), ("sizeMode", "sizeVariation", SIZE_VARIATIONS.1)];
|
||||
let mut out = [(Variation::Fixed, 0.0); 3];
|
||||
for (slot, (mode_key, var_key, most)) in out.iter_mut().zip(KEYS) {
|
||||
let mode = match p.get(mode_key).filter(|v| !v.is_null()) {
|
||||
@@ -428,7 +426,11 @@ fn eraser_variations(p: &Value, cmd: &str) -> Result<[(Variation, f64); 3]> {
|
||||
return Err(bad(cmd, format!("{var_key} must be 0 or more")));
|
||||
}
|
||||
if variation > most {
|
||||
return Err(bad(cmd, format!("{var_key} must be at most {most}")));
|
||||
// Size Variation is refused as path.blob refuses it.
|
||||
return Err(match var_key {
|
||||
"sizeVariation" => bad(cmd, format!("`{var_key}` must be from {} to {most}", SIZE_VARIATIONS.0)),
|
||||
_ => bad(cmd, format!("{var_key} must be at most {most}")),
|
||||
});
|
||||
}
|
||||
*slot = (mode, variation);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::common::{
|
||||
PenRecord, Sample, brush_region, path_kind, path_mut, path_of, poly_bounds, pressure_region, samples_param, size_pressure, stroke_paint,
|
||||
subpath_len, target_paths, within_input_bound,
|
||||
PenRecord, SIZES, Sample, brush_region, path_kind, path_mut, path_of, poly_bounds, pressure_region, ranged, samples_param, size_pressure,
|
||||
stroke_paint, subpath_len, target_paths, within_input_bound,
|
||||
};
|
||||
use super::{
|
||||
Anchor, Appearance, BTreeSet, BoolOp, Cap, Color, Document, EngineError, FillRule, Join, NewArt, Node, NodeId, NodeKind, Paint, PathData, Point,
|
||||
@@ -486,10 +486,7 @@ fn adjacent_to_topmost(doc: &Document, touched: &[NodeId], paint: &Paint) -> Vec
|
||||
pub(super) fn blob(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "path.blob";
|
||||
let samples = samples_param(p, "points", C)?;
|
||||
let size = number_or(p, "size", 10.0, C)?;
|
||||
if !(size.is_finite() && size > 0.0) {
|
||||
return Err(bad(C, "size must be positive"));
|
||||
}
|
||||
let size = ranged(p, "size", 10.0, SIZES, C)?;
|
||||
let angle = number_or(p, "angle", 0.0, C)?;
|
||||
let roundness = number_or(p, "roundness", 100.0, C)?;
|
||||
if !angle.is_finite() || !roundness.is_finite() {
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -268,6 +268,8 @@ struct RasterOptions {
|
||||
/// PSD: Write Layers.
|
||||
layers: Option<bool>,
|
||||
max_editability: Option<bool>,
|
||||
/// PSD: Preserve Text Editability (with layers).
|
||||
preserve_text: Option<bool>,
|
||||
hidden_layers: Option<bool>,
|
||||
/// Appearance of Black › Printing / Exporting (`prefs.blackOutput`); agents can set it here too.
|
||||
rich_black: Option<bool>,
|
||||
@@ -350,6 +352,7 @@ impl RasterOptions {
|
||||
color_model,
|
||||
layers: self.layers.unwrap_or(true),
|
||||
max_editability: self.max_editability.unwrap_or(false),
|
||||
preserve_text: self.preserve_text.unwrap_or(false),
|
||||
hidden_layers: self.hidden_layers.unwrap_or(false),
|
||||
embed_icc,
|
||||
},
|
||||
@@ -374,6 +377,7 @@ fn check_options(format: RasterFormat, o: &RasterExportOptions) -> Result<()> {
|
||||
let r = match format {
|
||||
RasterFormat::Bmp if model == jpeg::ColorModel::Cmyk => Err("BMP files are RGB or grayscale: colorModel rgb or gray".to_string()),
|
||||
RasterFormat::Tga if model != jpeg::ColorModel::Rgb => Err("Targa files are RGB: colorModel rgb".to_string()),
|
||||
RasterFormat::Psd if o.psd.preserve_text && !o.psd.layers => Err("preserveText writes type layers: it needs layers: true".to_string()),
|
||||
RasterFormat::Bmp => o.bmp.check(),
|
||||
RasterFormat::Tga => o.tga.check(),
|
||||
_ => Ok(()),
|
||||
|
||||
@@ -318,6 +318,13 @@ const MAX_EDITABILITY: FormatOption = FormatOption {
|
||||
description: "with layers: layers and sublayers become groups and every object a layer of its own, named as the Layers panel names it (text by its text); clipping, masked or knockout layers stay one layer",
|
||||
};
|
||||
|
||||
const PRESERVE_TEXT: FormatOption = FormatOption {
|
||||
name: "preserveText",
|
||||
ty: "boolean",
|
||||
default: "false",
|
||||
description: "with layers: horizontal and vertical point type in solid colors, with left-to-right paragraphs that set only their alignment, without strokes, effects or an appearance of its own, becomes editable type layers (with their pixels); a layer holding such type becomes a group of its type layers and pixel layers of the art between them, unless other art in it blends in a mode other than normal; refused with layers: false",
|
||||
};
|
||||
|
||||
const PSD_HIDDEN_LAYERS: FormatOption = FormatOption {
|
||||
name: "hiddenLayers",
|
||||
ty: "boolean",
|
||||
@@ -339,6 +346,7 @@ const PSD_OPTIONS: &[FormatOption] = &[
|
||||
ANTI_ALIAS,
|
||||
COLOR_MODEL,
|
||||
PSD_LAYERS,
|
||||
PRESERVE_TEXT,
|
||||
MAX_EDITABILITY,
|
||||
PSD_HIDDEN_LAYERS,
|
||||
EMBED_ICC,
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -69,6 +69,23 @@ fn psd_writes_layers_groups_and_text_named_after_it() {
|
||||
assert!(s.execute("document.export", &json!({"format": "psd", "colorModel": "lab"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserve_text_writes_point_type_as_type_layers_and_needs_layers() {
|
||||
let mut s = session();
|
||||
let file = export(&mut s, json!({"preserveText": true}));
|
||||
let (_, count, names) = layers(&file);
|
||||
assert_eq!((count, names), (-4, vec!["Layer 1".into(), "</Layer group>".into(), "Hello".into(), "Words".into()]), "Words becomes a group");
|
||||
assert_eq!(file.windows(8).filter(|w| w == b"8BIMTySh").count(), 1, "one type layer");
|
||||
assert_eq!(export(&mut s, json!({"preserveText": false})), export(&mut s, json!({})));
|
||||
// Without layers there are no type layers to write.
|
||||
let err = s.execute("document.export", &json!({"format": "psd", "layers": false, "preserveText": true})).unwrap_err().to_string();
|
||||
assert!(err.contains("preserveText") && err.contains("layers: true"), "{err}");
|
||||
assert!(s.execute("document.export", &json!({"format": "psd", "preserveText": "yes"})).is_err());
|
||||
// Other formats don't take it.
|
||||
let r = s.execute("document.export", &json!({"format": "png", "preserveText": true})).unwrap();
|
||||
assert!(r["warnings"].to_string().contains("preserveText"), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn psd_is_listed_with_its_options_and_writes_one_file_per_artboard() {
|
||||
let mut s = Session::new();
|
||||
@@ -79,7 +96,7 @@ fn psd_is_listed_with_its_options_and_writes_one_file_per_artboard() {
|
||||
(psd["label"].as_str(), psd["write"].as_bool(), psd["read"].as_bool(), psd["raster"].as_bool()),
|
||||
(Some("PSD"), Some(true), Some(true), Some(true))
|
||||
);
|
||||
for k in ["colorModel", "layers", "maxEditability", "hiddenLayers", "embedIcc", "ppi", "antiAlias", "background"] {
|
||||
for k in ["colorModel", "layers", "preserveText", "maxEditability", "hiddenLayers", "embedIcc", "ppi", "antiAlias", "background"] {
|
||||
assert!(psd["options"].get(k).is_some(), "psd takes {k}");
|
||||
}
|
||||
let r = s.execute("document.export", &json!({"format": "psd", "useArtboards": true})).unwrap();
|
||||
|
||||
@@ -501,8 +501,13 @@ fn damaged_slices_never_panic() {
|
||||
let mut f = base.clone();
|
||||
f[at] = v;
|
||||
let mut s = Session::new();
|
||||
let _ = s.execute("document.open", &json!({"name": "poster.psd", "dataBase64": b64(&f)}));
|
||||
let _ = s.execute("document.psdInfo", &json!({"dataBase64": b64(&f)}));
|
||||
// The engine's guard reports a panic as an internal error.
|
||||
for r in [
|
||||
s.execute("document.open", &json!({"name": "poster.psd", "dataBase64": b64(&f)})),
|
||||
s.execute("document.psdInfo", &json!({"dataBase64": b64(&f)})),
|
||||
] {
|
||||
assert!(!matches!(r, Err(crate::EngineError::Internal { .. })), "byte {at} set to {v}: {r:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ use vectorcraft_render::effects;
|
||||
|
||||
use super::edit::roots_of;
|
||||
use super::menucmds::{MAX_PIXELS, isolated_doc, unique_key};
|
||||
use super::pathops::{node_path, outline_strokes, outline_strokes_under, separate, shape_node};
|
||||
use super::pathops::{leaves, node_path, outline_strokes, separate, shape_node};
|
||||
use super::{CommandSpec, EngineError, Result, Session, always, bad, bool_or, cmd, has_doc, str_param, targets, unique_name};
|
||||
|
||||
mod analysis;
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use super::analysis::{Scratch, finite, flatten_groups, has_effects, masked, outlined_text, overlapping, painted, reach};
|
||||
use super::compose::{Builder, CLEAR, Composer, Elem, Fill, Kind, Px, WHITE};
|
||||
use super::options::FlattenOptions;
|
||||
use super::{
|
||||
Affine, Appearance, AppearanceItem, Arc, BlendMode, Color, ColorMode, Document, EngineError, FillLayer, FillRule, ImageBlob, ImageObject, Inks,
|
||||
MAX_PIXELS, Node, NodeId, NodeKind, Paint, PathData, Rect, Result, composite, effects, isolated_doc, outline_strokes_under, planes_cmyk, po,
|
||||
MAX_PIXELS, Node, NodeId, NodeKind, Paint, PathData, Rect, Result, composite, effects, isolated_doc, leaves, outline_strokes, planes_cmyk, po,
|
||||
separate, shape_node, shapes, unique_key,
|
||||
};
|
||||
|
||||
@@ -14,6 +16,8 @@ pub(super) struct Plan {
|
||||
pub(super) flat: Vec<Flat>,
|
||||
/// Objects without transparency (they stay, but for the outline options).
|
||||
pub(super) kept: Vec<NodeId>,
|
||||
/// What the outline and overprint options do to each of `kept`, in its order.
|
||||
pub(super) work: Vec<Kept>,
|
||||
/// The objects with transparency of their own.
|
||||
pub(super) transparent: Vec<NodeId>,
|
||||
}
|
||||
@@ -112,7 +116,12 @@ pub(super) fn plan(src: &Document, roots: &[NodeId], o: &FlattenOptions, render:
|
||||
let reaches: Vec<Option<Rect>> = plain.iter().zip(&clipped).map(|(n, c)| reach(n).zip(reach(c)).map(|(a, b)| a.intersect(b))).collect();
|
||||
let see_through: Vec<bool> = plain.iter().map(|n| o.shows_transparency(&baked, n) || o.draws_see_through_image(n)).collect();
|
||||
let cmyk = src.color_mode == ColorMode::Cmyk;
|
||||
let mut out = Plan { flat: vec![], kept: vec![], transparent: roots.iter().zip(&see_through).filter(|(_, t)| **t).map(|(id, _)| *id).collect() };
|
||||
let mut out = Plan {
|
||||
flat: vec![],
|
||||
kept: vec![],
|
||||
work: vec![],
|
||||
transparent: roots.iter().zip(&see_through).filter(|(_, t)| **t).map(|(id, _)| *id).collect(),
|
||||
};
|
||||
// Baking above stopped early when cancelled; each group is a place to stop (a plan changes nothing).
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
let mut queue = groups(src, roots, &plain, &reaches, &see_through, o)?;
|
||||
@@ -193,9 +202,101 @@ pub(super) fn plan(src: &Document, roots: &[NodeId], o: &FlattenOptions, render:
|
||||
};
|
||||
out.flat.push(Flat { roots: ids, regions, area, raster, lines });
|
||||
}
|
||||
out.work = out.kept.iter().map(|id| Kept::of(src, *id, o)).collect();
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// What the outline and overprint options do to one object without transparency, found in one
|
||||
/// walk of it.
|
||||
pub(super) struct Kept {
|
||||
pub(super) id: NodeId,
|
||||
/// Whether the options change it.
|
||||
pub(super) changes: bool,
|
||||
/// The type the text option outlines and the stroked paths the stroke option outlines, those
|
||||
/// that show and are not pieces of a compound path: what the Flattener Preview highlights.
|
||||
pub(super) shown_text: Vec<NodeId>,
|
||||
pub(super) shown_strokes: Vec<NodeId>,
|
||||
/// In paint order: the type the text option outlines and the leaf shapes ([`leaves`]) other
|
||||
/// than type that the stroke option outlines.
|
||||
steps: Vec<Step>,
|
||||
/// The objects with overprints, each with the type or leaf shape that holds it (itself
|
||||
/// included) when a step replaces that.
|
||||
overprinted: Vec<(NodeId, Option<NodeId>)>,
|
||||
}
|
||||
|
||||
/// One object [`apply`] outlines.
|
||||
enum Step {
|
||||
/// Type; `leaf`: only groups and layers hold it, so its outlines are leaf shapes for the
|
||||
/// stroke option.
|
||||
Text { id: NodeId, leaf: bool },
|
||||
/// A leaf shape other than type.
|
||||
Leaf(NodeId),
|
||||
}
|
||||
|
||||
/// Where [`Kept::visit`] is in the object it walks.
|
||||
#[derive(Clone, Copy)]
|
||||
struct At {
|
||||
/// Neither the node nor what holds it is hidden, and it is not a piece of a compound path.
|
||||
shown: bool,
|
||||
/// Only groups and layers hold the node.
|
||||
leaf: bool,
|
||||
/// The type or leaf shape holding the node that a step replaces.
|
||||
holder: Option<NodeId>,
|
||||
}
|
||||
|
||||
impl Kept {
|
||||
/// What the options `o` do to `root` of `d`: nothing when `d` doesn't hold it.
|
||||
fn of(d: &Document, root: NodeId, o: &FlattenOptions) -> Kept {
|
||||
let mut k = Kept { id: root, changes: false, shown_text: vec![], shown_strokes: vec![], steps: vec![], overprinted: vec![] };
|
||||
if let Some(n) = d.node(root) {
|
||||
k.visit(n, o, At { shown: true, leaf: true, holder: None });
|
||||
}
|
||||
k
|
||||
}
|
||||
|
||||
/// Note what the options `o` do to `n` and to everything under it.
|
||||
fn visit(&mut self, n: &Node, o: &FlattenOptions, at: At) {
|
||||
kept_seen(n);
|
||||
let shown = at.shown && n.visible;
|
||||
let mut holder = at.holder;
|
||||
if matches!(n.kind, NodeKind::Text(_)) {
|
||||
if o.text_to_outlines {
|
||||
self.changes = true;
|
||||
if shown {
|
||||
self.shown_text.push(n.id);
|
||||
}
|
||||
self.steps.push(Step::Text { id: n.id, leaf: at.leaf });
|
||||
holder = Some(n.id);
|
||||
}
|
||||
} else {
|
||||
if o.strokes_to_outlines && stroked(n) {
|
||||
self.changes = true;
|
||||
if shown {
|
||||
self.shown_strokes.push(n.id);
|
||||
}
|
||||
}
|
||||
if o.strokes_to_outlines && at.leaf && matches!(n.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. })
|
||||
{
|
||||
self.steps.push(Step::Leaf(n.id));
|
||||
holder = Some(n.id);
|
||||
}
|
||||
}
|
||||
if !o.preserve_overprints && overprints(n) {
|
||||
self.changes = true;
|
||||
self.overprinted.push((n.id, holder));
|
||||
}
|
||||
let Some(children) = n.children() else { return };
|
||||
let inside = At {
|
||||
shown: shown && !matches!(n.kind, NodeKind::Compound { .. }),
|
||||
leaf: at.leaf && matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }),
|
||||
holder,
|
||||
};
|
||||
for c in children {
|
||||
self.visit(c, o, inside);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `roots` of `src` (`plain`: as plain art; `reaches`: where each can paint, clipped) in the
|
||||
/// groups that flatten together ([`flatten_groups`]), each in paint order, by their first object.
|
||||
/// Objects that overlap (as [`overlapping`] groups them) stay in one group when one of them is
|
||||
@@ -668,7 +769,7 @@ pub(crate) fn flatten_expanded(doc: &Document, o: &FlattenOptions) -> Result<Opt
|
||||
roots.extend(children.iter().skip(usize::from(l.clips())).filter(|c| c.visible && !c.is_ruler_guide()).map(|c| c.id));
|
||||
}
|
||||
let plan = plan(doc, &roots, o, true)?;
|
||||
if plan.flat.is_empty() && !plan.kept.iter().any(|id| doc.node(*id).is_some_and(|n| kept_work(n, o))) {
|
||||
if plan.flat.is_empty() && !plan.work.iter().any(|k| k.changes) {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut d = doc.clone();
|
||||
@@ -753,19 +854,8 @@ pub(super) fn apply(d: &mut Document, sel: &mut vectorcraft_doc::Selection, plan
|
||||
d.insert(Some(layer), usize::MAX, guide)?;
|
||||
}
|
||||
let brushes = if o.strokes_to_outlines { vectorcraft_brush::library(d) } else { vec![] };
|
||||
for mut id in plan.kept {
|
||||
if o.text_to_outlines {
|
||||
id = outline_texts_under(d, id)?;
|
||||
}
|
||||
if o.strokes_to_outlines {
|
||||
id = outline_strokes_under(d, &brushes, id)?.0;
|
||||
}
|
||||
if !o.preserve_overprints
|
||||
&& let Some(n) = d.node_mut(id)
|
||||
{
|
||||
drop_overprints(n);
|
||||
}
|
||||
ids.push(id);
|
||||
for k in plan.work {
|
||||
ids.push(outline_kept(d, &brushes, k, o)?);
|
||||
}
|
||||
ids.sort_by_key(|id| d.index_path(*id));
|
||||
sel.set(ids.iter().copied());
|
||||
@@ -838,6 +928,21 @@ fn guide_seen(n: &Node) {
|
||||
#[cfg(not(test))]
|
||||
fn guide_seen(_: &Node) {}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// The nodes that [`Kept::of`] has looked at on this thread, in order.
|
||||
static KEPT_SEEN: std::cell::RefCell<Vec<NodeId>> = const { std::cell::RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
/// Note that [`Kept::of`] looked at `n`.
|
||||
#[cfg(test)]
|
||||
fn kept_seen(n: &Node) {
|
||||
KEPT_SEEN.with(|s| s.borrow_mut().push(n.id));
|
||||
}
|
||||
|
||||
#[cfg(not(test))]
|
||||
fn kept_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");
|
||||
@@ -858,38 +963,65 @@ fn raster_node(d: &mut Document, r: Raster) -> Node {
|
||||
crate::cmd::rasterfx::clip_group(d, path, FillRule::NonZero, image)
|
||||
}
|
||||
|
||||
/// Replace the type under `root` by its outlines: → the id now standing for `root`.
|
||||
fn outline_texts_under(d: &mut Document, root: NodeId) -> Result<NodeId> {
|
||||
let mut texts = vec![];
|
||||
if let Some(n) = d.node(root) {
|
||||
n.walk(&mut |c| {
|
||||
if matches!(c.kind, NodeKind::Text(_)) {
|
||||
texts.push(c.clone());
|
||||
/// Do what [`Kept`] `k` found to its object of `d` (`brushes`: the document's brushes, for the
|
||||
/// stroke option): its type outlined, then the strokes of its leaf shapes, the outlines of its
|
||||
/// type included, then its overprints dropped. → the id now standing for the object.
|
||||
fn outline_kept(d: &mut Document, brushes: &[vectorcraft_brush::Brush], k: Kept, o: &FlattenOptions) -> Result<NodeId> {
|
||||
let mut root = k.id;
|
||||
let mut replaced = HashSet::new();
|
||||
let dropping = !o.preserve_overprints;
|
||||
// Each replacement loses its overprints before it goes in: no new object is looked up.
|
||||
let mut put = |d: &mut Document, old: NodeId, mut new: Node, root: &mut NodeId| -> Result<()> {
|
||||
if dropping {
|
||||
drop_overprints(&mut new);
|
||||
}
|
||||
let nid = new.id;
|
||||
*d.node_mut(old).ok_or(EngineError::NoNode(old))? = new;
|
||||
replaced.insert(old);
|
||||
if old == *root {
|
||||
*root = nid;
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
// The leaf shapes of each outlined type that only groups and layers hold, by step.
|
||||
let mut outlined: Vec<Vec<Node>> = Vec::with_capacity(k.steps.len());
|
||||
for step in &k.steps {
|
||||
let mut lv = vec![];
|
||||
if let Step::Text { id, leaf } = *step
|
||||
&& let Some(out) = d.node(id).and_then(outlined_text)
|
||||
{
|
||||
let out = d.reid(&out);
|
||||
if leaf && o.strokes_to_outlines {
|
||||
leaves(&out, &mut lv);
|
||||
}
|
||||
});
|
||||
put(d, id, out, &mut root)?;
|
||||
}
|
||||
outlined.push(lv);
|
||||
}
|
||||
let mut out = root;
|
||||
for t in texts {
|
||||
let Some(o) = outlined_text(&t) else { continue };
|
||||
let o = d.reid(&o);
|
||||
let nid = o.id;
|
||||
*d.node_mut(t.id).ok_or(EngineError::NoNode(t.id))? = o;
|
||||
if t.id == root {
|
||||
out = nid;
|
||||
if o.strokes_to_outlines {
|
||||
for (step, lv) in k.steps.iter().zip(outlined) {
|
||||
let shapes = match *step {
|
||||
Step::Leaf(id) => d.node(id).cloned().into_iter().collect(),
|
||||
Step::Text { .. } => lv,
|
||||
};
|
||||
for l in shapes.iter().filter(|l| !matches!(l.kind, NodeKind::Text(_))) {
|
||||
if let Some(new) = outline_strokes(d, brushes, l) {
|
||||
put(d, l.id, new, &mut root)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Whether the outline and overprint options change `n`, an object without transparency.
|
||||
pub(super) fn kept_work(n: &Node, o: &FlattenOptions) -> bool {
|
||||
let mut any = false;
|
||||
n.walk(&mut |c| {
|
||||
any |= (o.text_to_outlines && matches!(c.kind, NodeKind::Text(_)))
|
||||
|| (o.strokes_to_outlines && stroked(c))
|
||||
|| (!o.preserve_overprints && overprints(c));
|
||||
});
|
||||
any
|
||||
if dropping {
|
||||
for (id, holder) in k.overprinted {
|
||||
if holder.is_some_and(|h| replaced.contains(&h)) {
|
||||
continue;
|
||||
}
|
||||
if let Some(n) = d.node_mut(id) {
|
||||
drop_own_overprints(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(root)
|
||||
}
|
||||
|
||||
/// Whether `n` is a path with a visible stroke (outlining turns it into a fill).
|
||||
@@ -898,12 +1030,8 @@ pub(super) fn stroked(n: &Node) -> bool {
|
||||
&& n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.visible && !s.paint.is_none() && s.width > 0.0))
|
||||
}
|
||||
|
||||
fn overprints(n: &Node) -> bool {
|
||||
n.appearance.items.iter().any(AppearanceItem::overprint)
|
||||
|| matches!(&n.kind, NodeKind::Text(t) if t.runs.iter().any(|r| r.style.overprint_fill || r.style.overprint_stroke))
|
||||
}
|
||||
|
||||
fn drop_overprints(n: &mut Node) {
|
||||
/// Drop the overprints of `n` itself.
|
||||
fn drop_own_overprints(n: &mut Node) {
|
||||
if overprints(n) {
|
||||
for i in &mut n.appearance.items {
|
||||
*i.overprint_mut() = false;
|
||||
@@ -914,6 +1042,16 @@ fn drop_overprints(n: &mut Node) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn overprints(n: &Node) -> bool {
|
||||
n.appearance.items.iter().any(AppearanceItem::overprint)
|
||||
|| matches!(&n.kind, NodeKind::Text(t) if t.runs.iter().any(|r| r.style.overprint_fill || r.style.overprint_stroke))
|
||||
}
|
||||
|
||||
/// Drop the overprints of `n` and of everything under it.
|
||||
fn drop_overprints(n: &mut Node) {
|
||||
drop_own_overprints(n);
|
||||
if let Some(ch) = n.children_mut() {
|
||||
for c in ch {
|
||||
drop_overprints(Arc::make_mut(c));
|
||||
@@ -994,6 +1132,208 @@ mod tests {
|
||||
assert_eq!(run(&[deep, deep]).0, vec![(sub, g2), (sub, g2)]);
|
||||
}
|
||||
|
||||
/// The objects [`kept_session`] makes.
|
||||
struct KeptArt {
|
||||
/// Each group with its stroked rectangle (its fill overprints) and its stroked type.
|
||||
groups: Vec<(NodeId, NodeId, NodeId)>,
|
||||
/// A stroked rectangle and stroked type with an overprint, on their own.
|
||||
rect: NodeId,
|
||||
text: NodeId,
|
||||
/// A stroked compound path and its pieces.
|
||||
compound: NodeId,
|
||||
pieces: Vec<NodeId>,
|
||||
/// A group holding an unstroked rectangle and a hidden stroked rectangle.
|
||||
hidden_group: NodeId,
|
||||
hidden: NodeId,
|
||||
/// An unstroked rectangle.
|
||||
plain: NodeId,
|
||||
}
|
||||
|
||||
/// A document without transparency: `n` groups, then the other objects of [`KeptArt`].
|
||||
fn kept_session(n: usize) -> (Session, KeptArt) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let id = |v: serde_json::Value| NodeId(v["id"].as_u64().unwrap());
|
||||
let rect = |s: &mut Session, x: f64| id(s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap());
|
||||
let text = |s: &mut Session, x: f64| {
|
||||
let t = id(s.execute("text.create", &json!({"x": x, "y": 80, "text": "Hi", "size": 24})).unwrap());
|
||||
s.execute("paint.setStroke", &json!({"color": "#000000", "ids": [t.0]})).unwrap();
|
||||
t
|
||||
};
|
||||
let select = |s: &mut Session, ids: &[NodeId]| {
|
||||
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
};
|
||||
let overprint = |s: &mut Session, on: NodeId| {
|
||||
s.execute("attributes.set", &json!({"ids": [on.0], "overprintFill": true})).unwrap();
|
||||
};
|
||||
let unstroked = |s: &mut Session, on: NodeId| {
|
||||
s.execute("paint.setStroke", &json!({"none": true, "ids": [on.0]})).unwrap();
|
||||
};
|
||||
let mut groups = vec![];
|
||||
for i in 0..n {
|
||||
let x = (i % 10) as f64 * 30.0;
|
||||
let (r, t) = (rect(&mut s, x), text(&mut s, x));
|
||||
overprint(&mut s, r);
|
||||
select(&mut s, &[r, t]);
|
||||
groups.push((id(s.execute("object.group", &json!({})).unwrap()), r, t));
|
||||
}
|
||||
let (r, t) = (rect(&mut s, 0.0), text(&mut s, 100.0));
|
||||
overprint(&mut s, t);
|
||||
let (a, b) = (rect(&mut s, 200.0), rect(&mut s, 210.0));
|
||||
select(&mut s, &[a, b]);
|
||||
let compound = id(s.execute("object.compoundPath.make", &json!({})).unwrap());
|
||||
s.execute("paint.setStroke", &json!({"color": "#000000", "ids": [compound.0]})).unwrap();
|
||||
let pieces = s.doc().unwrap().doc.node(compound).unwrap().children().unwrap().iter().map(|c| c.id).collect();
|
||||
let (shown, hidden) = (rect(&mut s, 300.0), rect(&mut s, 310.0));
|
||||
unstroked(&mut s, shown);
|
||||
select(&mut s, &[shown, hidden]);
|
||||
let hidden_group = id(s.execute("object.group", &json!({})).unwrap());
|
||||
s.execute("object.hide", &json!({"ids": [hidden.0]})).unwrap();
|
||||
let plain = rect(&mut s, 350.0);
|
||||
unstroked(&mut s, plain);
|
||||
(s, KeptArt { groups, rect: r, text: t, compound, pieces, hidden_group, hidden, plain })
|
||||
}
|
||||
|
||||
/// Every option on: type and strokes outlined, overprints dropped.
|
||||
fn outlining() -> FlattenOptions {
|
||||
FlattenOptions { text_to_outlines: true, strokes_to_outlines: true, preserve_overprints: false, ..FlattenOptions::default() }
|
||||
}
|
||||
|
||||
/// The top-level objects of `d`'s first layer, in paint order.
|
||||
fn top_level(d: &Document) -> Vec<NodeId> {
|
||||
d.layers[0].children().unwrap().iter().map(|c| c.id).collect()
|
||||
}
|
||||
|
||||
fn sorted(mut ids: Vec<NodeId>) -> Vec<NodeId> {
|
||||
ids.sort();
|
||||
ids
|
||||
}
|
||||
|
||||
/// The nodes [`Kept::of`] looked at while `f` ran, sorted.
|
||||
fn kept_seen_by(f: impl FnOnce()) -> Vec<NodeId> {
|
||||
KEPT_SEEN.with(|v| v.borrow_mut().clear());
|
||||
f();
|
||||
sorted(KEPT_SEEN.with(|v| v.take()))
|
||||
}
|
||||
|
||||
/// The Flattener Preview, `object.flattenTransparency` and flattening a whole document each look
|
||||
/// at every node of the objects without transparency once, with type and strokes outlined and
|
||||
/// overprints dropped, an object they leave as it is included.
|
||||
#[test]
|
||||
fn kept_objects_are_looked_at_once() {
|
||||
let (mut s, _) = kept_session(100);
|
||||
let o = outlining();
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let roots = top_level(&doc);
|
||||
let mut nodes = vec![];
|
||||
for r in &roots {
|
||||
doc.node(*r).unwrap().walk(&mut |c| nodes.push(c.id));
|
||||
}
|
||||
nodes.sort();
|
||||
assert_eq!(nodes.len(), 309);
|
||||
let preview = kept_seen_by(|| drop(super::super::report::report(&doc, &roots, &o).unwrap()));
|
||||
assert!(preview == nodes, "the preview looked at {} nodes of {}", preview.len(), nodes.len());
|
||||
let whole = kept_seen_by(|| drop(flatten_document(&doc, &o).unwrap().unwrap()));
|
||||
assert!(whole == nodes, "flattening the document looked at {} nodes of {}", whole.len(), nodes.len());
|
||||
let ids: Vec<u64> = roots.iter().map(|r| r.0).collect();
|
||||
let command = kept_seen_by(|| {
|
||||
s.execute(
|
||||
"object.flattenTransparency",
|
||||
&json!({"ids": ids, "textToOutlines": true, "strokesToOutlines": true, "preserveOverprints": false}),
|
||||
)
|
||||
.unwrap();
|
||||
});
|
||||
assert!(command == nodes, "object.flattenTransparency looked at {} nodes of {}", command.len(), nodes.len());
|
||||
}
|
||||
|
||||
/// [`apply`]'s outlining of `kept` (objects of `d` without transparency) with `o`, done as a
|
||||
/// walk of each object for each option: → the ids standing for them, in paint order.
|
||||
fn outlined_walk_by_walk(d: &mut Document, kept: &[NodeId], o: &FlattenOptions) -> Vec<NodeId> {
|
||||
let brushes = if o.strokes_to_outlines { vectorcraft_brush::library(d) } else { vec![] };
|
||||
let mut ids = vec![];
|
||||
for &root in kept {
|
||||
let mut id = root;
|
||||
if o.text_to_outlines {
|
||||
let mut texts = vec![];
|
||||
d.node(id).unwrap().walk(&mut |c| {
|
||||
if matches!(c.kind, NodeKind::Text(_)) {
|
||||
texts.push(c.clone());
|
||||
}
|
||||
});
|
||||
for t in texts {
|
||||
let Some(out) = outlined_text(&t) else { continue };
|
||||
let out = d.reid(&out);
|
||||
if t.id == root {
|
||||
id = out.id;
|
||||
}
|
||||
*d.node_mut(t.id).unwrap() = out;
|
||||
}
|
||||
}
|
||||
if o.strokes_to_outlines {
|
||||
id = crate::cmd::pathops::outline_strokes_under(d, &brushes, id).unwrap().0;
|
||||
}
|
||||
if !o.preserve_overprints {
|
||||
drop_overprints(d.node_mut(id).unwrap());
|
||||
}
|
||||
ids.push(id);
|
||||
}
|
||||
ids.sort_by_key(|id| d.index_path(*id));
|
||||
ids
|
||||
}
|
||||
|
||||
/// With each mix of the text, stroke and overprint options, the objects without transparency
|
||||
/// end as a walk of each of them for each option leaves them: the same art, ids and selection.
|
||||
#[test]
|
||||
fn kept_objects_change_as_a_walk_per_option_changes_them() {
|
||||
let (s, _) = kept_session(3);
|
||||
let doc = Document::clone(&s.doc().unwrap().doc);
|
||||
let roots = top_level(&doc);
|
||||
for bits in 0..8u8 {
|
||||
let o = FlattenOptions {
|
||||
text_to_outlines: bits & 1 != 0,
|
||||
strokes_to_outlines: bits & 2 != 0,
|
||||
preserve_overprints: bits & 4 != 0,
|
||||
..FlattenOptions::default()
|
||||
};
|
||||
let p = plan(&doc, &roots, &o, true).unwrap();
|
||||
assert!(p.flat.is_empty(), "{o:?}");
|
||||
// In the order the plan's groups come in.
|
||||
let kept = p.kept.clone();
|
||||
assert_eq!(sorted(kept.clone()), sorted(roots.clone()), "{o:?}");
|
||||
let mut once = doc.clone();
|
||||
let mut sel = vectorcraft_doc::Selection::default();
|
||||
let (ids, ..) = apply(&mut once, &mut sel, p, &o).unwrap();
|
||||
let mut walked = doc.clone();
|
||||
let want = outlined_walk_by_walk(&mut walked, &kept, &o);
|
||||
assert_eq!(ids, want, "{o:?}");
|
||||
assert!(once == walked, "{o:?}");
|
||||
assert_eq!(once == doc, bits == 4, "{o:?}: only with every option off does nothing change");
|
||||
}
|
||||
}
|
||||
|
||||
/// The Flattener Preview lists the kept objects the options change, and of those the type and
|
||||
/// the stroked paths that show and are not pieces of a compound path.
|
||||
#[test]
|
||||
fn the_preview_lists_what_the_options_change_in_kept_objects() {
|
||||
let (s, a) = kept_session(2);
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let roots = top_level(doc);
|
||||
let r = super::super::report::report(doc, &roots, &outlining()).unwrap();
|
||||
let (g, rects, texts): (Vec<_>, Vec<_>, Vec<_>) =
|
||||
(a.groups.iter().map(|g| g.0).collect(), a.groups.iter().map(|g| g.1).collect(), a.groups.iter().map(|g| g.2).collect());
|
||||
assert_eq!(r.affected, [g.clone(), vec![a.rect, a.text, a.compound, a.hidden_group]].concat());
|
||||
// Both lists come in the order the plan's groups do.
|
||||
assert_eq!(sorted(r.text.clone()), sorted([texts, vec![a.text]].concat()));
|
||||
assert_eq!(sorted(r.strokes.clone()), sorted([rects, vec![a.rect, a.compound]].concat()));
|
||||
assert!(!r.strokes.contains(&a.hidden) && !r.strokes.iter().any(|id| a.pieces.contains(id)) && !r.affected.contains(&a.plain));
|
||||
// Dropping overprints alone changes the objects that overprint.
|
||||
let o = FlattenOptions { preserve_overprints: false, ..FlattenOptions::default() };
|
||||
let r = super::super::report::report(doc, &roots, &o).unwrap();
|
||||
assert_eq!((r.affected, r.text, r.strokes), ([g, vec![a.text]].concat(), vec![], vec![]));
|
||||
// With every option off, nothing.
|
||||
assert!(super::super::report::report(doc, &roots, &FlattenOptions::default()).unwrap().affected.is_empty());
|
||||
}
|
||||
|
||||
/// 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.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::analysis::draws_image;
|
||||
use super::apply::{apply, kept_work, plan};
|
||||
use super::apply::{apply, plan};
|
||||
use super::presets::{FlattenerPreset, saved_preset};
|
||||
use super::report::target_roots;
|
||||
use super::{BTreeSet, Deserialize, Document, EngineError, Node, NodeKind, Paint, Result, Serialize, Session, Value, bad, json, str_param};
|
||||
@@ -194,7 +194,7 @@ pub(super) fn flatten(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let plan = plan(&src, &roots, &o, true)?;
|
||||
let warning = crate::cmd::rasterfx::undecoded_warning(failed);
|
||||
let options = serde_json::to_value(&o).unwrap_or_default();
|
||||
if plan.flat.is_empty() && !plan.kept.iter().any(|id| src.node(*id).is_some_and(|n| kept_work(n, &o))) {
|
||||
if plan.flat.is_empty() && !plan.work.iter().any(|k| k.changes) {
|
||||
return Ok(json!({ "ids": roots.iter().map(|i| i.0).collect::<Vec<_>>(), "rasterized": 0, "vector": 0, "options": options }));
|
||||
}
|
||||
let (ids, vector, rasterized) = s.edit("Flatten Transparency", |d, sel| {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::apply::{kept_work, opaque, plan, stroked};
|
||||
use super::apply::{opaque, plan, stroked};
|
||||
use super::options::FlattenOptions;
|
||||
use super::{
|
||||
Appearance, Color, Deserialize, Document, Node, NodeId, NodeKind, Paint, PathData, Rect, Result, Serialize, Session, Value, bad, isolated_doc,
|
||||
@@ -263,15 +263,10 @@ pub fn report(doc: &Document, roots: &[NodeId], o: &FlattenOptions) -> Result<Fl
|
||||
r.rasterized.push(a.outline());
|
||||
}
|
||||
}
|
||||
for root in plan.kept.iter().filter_map(|id| doc.node(*id)).filter(|n| kept_work(n, o)) {
|
||||
r.affected.push(root.id);
|
||||
visit(root, &mut |n| {
|
||||
if o.text_to_outlines && matches!(n.kind, NodeKind::Text(_)) {
|
||||
r.text.push(n.id);
|
||||
} else if o.strokes_to_outlines && stroked(n) {
|
||||
r.strokes.push(n.id);
|
||||
}
|
||||
});
|
||||
for k in plan.work.iter().filter(|k| k.changes) {
|
||||
r.affected.push(k.id);
|
||||
r.text.extend(&k.shown_text);
|
||||
r.strokes.extend(&k.shown_strokes);
|
||||
}
|
||||
r.affected.sort_by_key(|id| doc.index_path(*id));
|
||||
Ok(r)
|
||||
|
||||
@@ -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), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind; the points on a label's characters are not stored → {index}",
|
||||
"{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its points); the points on a label's characters are not stored → {index}",
|
||||
has_doc,
|
||||
add_point
|
||||
),
|
||||
|
||||
@@ -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), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters their gradient without its placement, fitted to each label",
|
||||
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), 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), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\", index?: appearance item index (as item)} set the gradient vector, aspect ratio and focal point (solid paints become the default gradient; type objects set it on their runs, in text space). On a path directly in a graph series, the graph also stores the gradient with its placement relative to the path's box when it is on the topmost visible fill or stroke, and every path of the series takes it at the same place on its own box (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters their gradient without the placement this command sets, fitted to each label",
|
||||
"{start?: [x,y], end?: [x,y] (document coordinates; both or neither: omitted, the vector stays), aspect?: % (radial, conic and diamond: the extent's height / width across the vector, a negative one mirroring a conic's sweep and an error for the other kinds; default: kept), focal?: [x,y] (document coordinates) | null (radial: the focal point, where the first stop sits, pulled inside the extent ellipse; null centres it; default: it keeps its place in the ellipse; an error on a conic or diamond gradient), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (alias: index; omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\", index?: appearance item index (as item)} set the gradient vector, aspect ratio and focal point (solid paints become the default gradient; type objects set it on their runs, in text space). On a path directly in a graph series, the graph also stores the gradient with its placement relative to the path's box when it is on the topmost visible fill or stroke, and every path of the series takes it at the same place on its own box (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without the placement this command sets, fitted to each label",
|
||||
has_doc,
|
||||
set_gradient_geom
|
||||
),
|
||||
|
||||
@@ -48,9 +48,11 @@ use generate::generate;
|
||||
#[cfg(test)]
|
||||
use series::default_series_color;
|
||||
pub(crate) use series::{
|
||||
LabelTextChange, capture_label_anti_alias, capture_label_changes, capture_label_object_opacity, capture_label_paragraphs, capture_label_rows,
|
||||
capture_label_styles, capture_label_text, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, follow_wedge_shades,
|
||||
is_design_art, label_object_opacity_differs, labels_in, paint_targets, plain_labels, series_group_marks, series_group_marks_where,
|
||||
LabelTextChange, RowWrites, capture_label_anti_alias, capture_label_changes, capture_label_kind_rows, capture_label_object_opacity,
|
||||
capture_label_paragraphs, capture_label_rows, capture_label_styles, capture_label_styles_given, capture_label_text, capture_line_changes,
|
||||
capture_line_fill_stroke_rows, capture_line_kind_rows, capture_line_paint_writes, capture_line_row_writes, capture_line_rows,
|
||||
capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, follow_wedge_shades, graph_part_members, is_design_art,
|
||||
is_graph_line, label_object_opacity_differs, label_rows, labels_in, paint_targets, plain_labels, series_group_marks, series_group_marks_where,
|
||||
series_groups_among, series_marks_in, series_object_opacity_differs, shown_paint, wedge_shades,
|
||||
};
|
||||
|
||||
|
||||
@@ -393,6 +393,16 @@ impl<'a> Plot<'a> {
|
||||
series_marks(self.g, i, series_fill, stroke, width)
|
||||
}
|
||||
|
||||
/// The stroke paint and width series `s`'s filled marks and its legend swatch get when the series keeps no stroke
|
||||
/// of its own: a white line between stacked segments, area bands and pie wedges, none on other marks.
|
||||
fn mark_stroke(&self, s: usize) -> (Paint, f64) {
|
||||
match self.kind(s) {
|
||||
GraphKind::StackedColumn | GraphKind::StackedBar | GraphKind::Area => (Paint::solid(Color::WHITE), 0.25),
|
||||
GraphKind::Pie => (Paint::solid(Color::WHITE), 0.5),
|
||||
_ => (Paint::None, 0.0),
|
||||
}
|
||||
}
|
||||
|
||||
fn series_label(&self, i: usize) -> String {
|
||||
self.g.series.get(i).cloned().unwrap_or_default()
|
||||
}
|
||||
@@ -471,7 +481,8 @@ impl<'a> Plot<'a> {
|
||||
}
|
||||
let sweep = v / total * std::f64::consts::TAU;
|
||||
let bp = wedge_path(ring, a0, sweep);
|
||||
let (fill, stroke, sw) = self.mark(s, true, Paint::solid(Color::WHITE), 0.5);
|
||||
let (stroke, width) = self.mark_stroke(s);
|
||||
let (fill, stroke, sw) = self.mark(s, true, stroke, width);
|
||||
let dark = is_dark(&fill);
|
||||
let n = self.b.path(PathData::from_bezpath(&bp), fill, stroke, sw);
|
||||
self.push_shadowed(s, n);
|
||||
@@ -532,7 +543,7 @@ impl<'a> Plot<'a> {
|
||||
}
|
||||
for v in tick_values(lo, hi, step).into_iter().skip(1) {
|
||||
let ring: Vec<Point> = (0..ncat).map(|c| at(c, v)).collect();
|
||||
axes.push(self.b.path(polyline(&ring, true), Paint::None, Paint::solid(Color::rgb(0.6, 0.6, 0.6)), 0.25));
|
||||
axes.push(self.b.ring(polyline(&ring, true)));
|
||||
}
|
||||
let ax = self.b.group("Axes", axes);
|
||||
self.b.out.push(ax);
|
||||
@@ -887,7 +898,8 @@ impl<'a> Plot<'a> {
|
||||
let Some(base) = (if v >= 0.0 { pos.get_mut(ax) } else { neg.get_mut(ax) }) else { continue };
|
||||
let (v0, v1) = (geo.vpos(ax, *base), geo.vpos(ax, *base + v));
|
||||
*base += v;
|
||||
let paint = self.mark(s, true, Paint::solid(Color::WHITE), 0.25);
|
||||
let (stroke, width) = self.mark_stroke(s);
|
||||
let paint = self.mark(s, true, stroke, width);
|
||||
let rect = bar_rect(geo.horizontal, a, w, v0, v1);
|
||||
// A segment of 0 has no area to shade.
|
||||
let n = self.bar_node(Bar { s, rect, value: v, down: v1 < v0, per_unit: geo.per_unit(ax) }, paint, v != 0.0);
|
||||
@@ -907,7 +919,8 @@ impl<'a> Plot<'a> {
|
||||
let at = |c: usize, v: &[f64]| Point::new(geo.cat_mid(c), geo.vpos(a, v.get(c).copied().unwrap_or(0.0)));
|
||||
let mut pts: Vec<Point> = (0..ncat).map(|c| at(c, &above)).collect();
|
||||
pts.extend((0..ncat).rev().map(|c| at(c, below)));
|
||||
let (fill, stroke, w) = self.mark(s, true, Paint::solid(Color::WHITE), 0.25);
|
||||
let (stroke, width) = self.mark_stroke(s);
|
||||
let (fill, stroke, w) = self.mark(s, true, stroke, width);
|
||||
let n = self.b.path(polyline(&pts, true), fill, stroke, w);
|
||||
self.push_series(s, n);
|
||||
*below = above;
|
||||
@@ -951,10 +964,11 @@ impl<'a> Plot<'a> {
|
||||
}
|
||||
|
||||
/// The swatch of series `s` at `(x, y)`: series drawn with markers show their marker design in the legend, and
|
||||
/// series drawn with a column design that design.
|
||||
/// series drawn with a column design that design. A default swatch has the stroke of its series' marks.
|
||||
fn legend_swatch(&mut self, s: usize, (x, y): (f64, f64)) {
|
||||
let marked = matches!(self.g.kind, GraphKind::Scatter | GraphKind::Radar) || self.kind(s) == GraphKind::Line;
|
||||
let paint = self.mark(s, true, Paint::None, 0.0);
|
||||
let (stroke, width) = self.mark_stroke(s);
|
||||
let paint = self.mark(s, true, stroke, width);
|
||||
let column = nth(self.column_looks, s).filter(|_| self.columnar(s));
|
||||
let swatch = self.b.swatch(column, nth(&self.designs, s).filter(|_| marked), Rect::new(x, y, x + 8.0, y + 8.0), paint);
|
||||
self.push_series(s, swatch);
|
||||
|
||||
@@ -82,9 +82,49 @@ fn kept_rows(styles: &vectorcraft_doc::LabelStyles, role: Role) -> Option<&vecto
|
||||
}
|
||||
}
|
||||
|
||||
/// Give label `n` the object rows `kept` keeps: a fill row and a stroke row for the kept paints, in their kept order and
|
||||
/// place relative to the characters, and the object opacity and blend mode. An opacity read from a file is held to 0..1
|
||||
/// and a weight to 0..1000 pt; one that is not a number is left out (a stroke then takes 1 pt).
|
||||
/// What a graph line is, for the rows it keeps: an axis line or tick mark, or a ring of a radar graph.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
pub(crate) enum Line {
|
||||
Axis,
|
||||
Ring,
|
||||
}
|
||||
|
||||
impl Line {
|
||||
/// The stroke and weight the graph draws lines of this kind with when they keep no rows. They have no fill.
|
||||
fn default_stroke(self) -> (Paint, f64) {
|
||||
match self {
|
||||
Line::Axis => (Paint::solid(Color::BLACK), 0.5),
|
||||
Line::Ring => (Paint::solid(Color::rgb(0.6, 0.6, 0.6)), 0.25),
|
||||
}
|
||||
}
|
||||
|
||||
/// The rows ([`super::series::label_rows`]) a line of this kind shows as the graph draws it with no kept rows.
|
||||
pub(super) fn default_rows(self) -> vectorcraft_doc::LabelRows {
|
||||
let (stroke, width) = self.default_stroke();
|
||||
let paint = vectorcraft_doc::SeriesPaint { fill: Some(Paint::None), stroke: Some(stroke), stroke_width: Some(width), ..Default::default() };
|
||||
vectorcraft_doc::LabelRows { paint, ..Default::default() }
|
||||
}
|
||||
}
|
||||
|
||||
/// The rows lines of kind `line` keep, if any.
|
||||
pub(super) fn kept_line_rows(styles: &vectorcraft_doc::LabelStyles, line: Line) -> Option<&vectorcraft_doc::LabelRows> {
|
||||
match line {
|
||||
Line::Axis => styles.axis_rows.as_ref(),
|
||||
Line::Ring => styles.ring_rows.as_ref(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The slot of `styles` that holds the rows lines of kind `line` keep.
|
||||
pub(super) fn line_slot(styles: &mut vectorcraft_doc::LabelStyles, line: Line) -> &mut Option<vectorcraft_doc::LabelRows> {
|
||||
match line {
|
||||
Line::Axis => &mut styles.axis_rows,
|
||||
Line::Ring => &mut styles.ring_rows,
|
||||
}
|
||||
}
|
||||
|
||||
/// Give label or graph line `n` the object rows `kept` keeps: a fill row and a stroke row for the kept paints, in their
|
||||
/// kept order and place relative to the contents, and the object opacity and blend mode. An opacity read from a file is
|
||||
/// held to 0..1 and a weight to 0..1000 pt; one that is not a number is left out (a stroke then takes 1 pt).
|
||||
fn apply_label_rows(n: &mut Node, kept: &vectorcraft_doc::LabelRows) {
|
||||
use vectorcraft_doc::{AppearanceItem, FillLayer, StrokeLayer};
|
||||
let rows = &kept.paint;
|
||||
@@ -124,7 +164,20 @@ impl Gen<'_> {
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to(a);
|
||||
bp.line_to(b);
|
||||
self.path(PathData::from_bezpath(&bp), Paint::None, Paint::solid(Color::BLACK), 0.5)
|
||||
self.kept_line(Line::Axis, PathData::from_bezpath(&bp))
|
||||
}
|
||||
/// A ring of a radar graph through `pd`.
|
||||
pub(super) fn ring(&mut self, pd: PathData) -> Arc<Node> {
|
||||
self.kept_line(Line::Ring, pd)
|
||||
}
|
||||
/// A graph line of kind `line` through `pd`, with the rows lines of its kind keep, else its default stroke.
|
||||
fn kept_line(&mut self, line: Line, pd: PathData) -> Arc<Node> {
|
||||
let (stroke, width) = line.default_stroke();
|
||||
let mut n = Node::path(self.d.alloc_id(), pd, Appearance::basic(Paint::None, stroke, width));
|
||||
if let Some(rows) = kept_line_rows(self.styles, line) {
|
||||
apply_label_rows(&mut n, rows);
|
||||
}
|
||||
Arc::new(n)
|
||||
}
|
||||
pub(super) fn text(&mut self, role: Role, at: Point, s: &str, justify: Justify) -> Arc<Node> {
|
||||
let t = self.text_object(role, at, s, justify);
|
||||
|
||||
@@ -4,7 +4,7 @@ use vectorcraft_geom::Shape;
|
||||
|
||||
use super::axis::radar_axis;
|
||||
use super::generate::is_dark;
|
||||
use super::labels::{Role, filled_lines_on, label_para, label_size, label_style};
|
||||
use super::labels::{Line, Role, filled_lines_on, kept_line_rows, label_para, label_size, label_style, line_slot};
|
||||
use super::{
|
||||
Affine, Arc, CharStyle, Color, Document, GraphKind, GraphSpec, HashMap, Node, NodeId, NodeKind, Paint, Rect, Result, Session, Value, bad,
|
||||
refresh_bounds,
|
||||
@@ -155,13 +155,32 @@ pub(crate) fn paint_targets(doc: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
}
|
||||
|
||||
/// `ids` with each graph series group replaced by the paths directly inside it, as [`paint_targets`] reads a series
|
||||
/// group: the graph draws its series groups again with no rows of their own. A series group with no such path, other
|
||||
/// ids and the art of a graph design pass through, and the order of `ids` is kept.
|
||||
/// group: the graph draws its series groups again with no rows of their own. A graph's Axes group is replaced by the
|
||||
/// lines and labels directly inside it, and its Legend group by the labels directly inside it, which the graph keeps
|
||||
/// rows for ([`capture_label_rows`]). A group with no such member, other ids and the art of a graph design pass
|
||||
/// through, and the order of `ids` is kept.
|
||||
pub(crate) fn series_group_marks(doc: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
series_group_marks_where(doc, ids, |_| true)
|
||||
}
|
||||
|
||||
/// [`series_group_marks`] for the series groups `stands` accepts; the others pass through.
|
||||
/// The lines and labels directly in `n` when it is the Axes group of a graph, or the labels directly in it when it is
|
||||
/// the graph's Legend group, in paint order. `None` for any other object.
|
||||
pub(crate) fn graph_part_members(doc: &Document, n: &Node) -> Option<Vec<NodeId>> {
|
||||
if !matches!(n.kind, NodeKind::Group { .. }) || n.extras().series_index.is_some() {
|
||||
return None;
|
||||
}
|
||||
let axes = match n.name.as_deref() {
|
||||
Some("Axes") => true,
|
||||
Some("Legend") => false,
|
||||
_ => return None,
|
||||
};
|
||||
let spec = doc.parent_of(n.id).and_then(|parent| doc.node(parent)).and_then(|parent| parent.extras().graph.as_deref())?;
|
||||
let member = |c: &Node| matches!(c.kind, NodeKind::Text(_)) || (axes && line_in(spec, n, c).is_some());
|
||||
Some(n.children().into_iter().flatten().filter(|c| member(c)).map(|c| c.id).collect())
|
||||
}
|
||||
|
||||
/// [`series_group_marks`] for the series groups, Axes groups and Legend groups `stands` accepts; the others pass
|
||||
/// through.
|
||||
pub(crate) fn series_group_marks_where(doc: &Document, ids: &[NodeId], stands: impl Fn(&Node) -> bool) -> Vec<NodeId> {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut out = Vec::new();
|
||||
@@ -172,6 +191,10 @@ pub(crate) fn series_group_marks_where(doc: &Document, ids: &[NodeId], stands: i
|
||||
group.children().into_iter().flatten().filter(|m| matches!(m.kind, NodeKind::Path { .. })).map(|m| m.id).collect();
|
||||
if marks.is_empty() { out.push(*id) } else { out.extend(marks) }
|
||||
}
|
||||
Some(part) if stands(part) => match graph_part_members(doc, part) {
|
||||
Some(members) if !members.is_empty() => out.extend(members),
|
||||
_ => out.push(*id),
|
||||
},
|
||||
_ => out.push(*id),
|
||||
}
|
||||
}
|
||||
@@ -1185,21 +1208,34 @@ pub(crate) fn capture_label_anti_alias(doc: &mut Document, ids: &[NodeId], metho
|
||||
/// Keep a formatting change made to graph labels `ids` (Character or Appearance, on the whole graph or on labels
|
||||
/// picked with Group Selection) for every label of their kind: `change` is applied to the kind's kept style (or
|
||||
/// the default one), so the labels look the same when the graph is drawn again. Called inside the same edit, so
|
||||
/// they undo together. Returns whether a kept style changed.
|
||||
/// they undo together. A kind that keeps no style and that `change` leaves at the default style keeps none, unless
|
||||
/// `change` sets the legend fill. Returns whether a kept style changed.
|
||||
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) {
|
||||
changed |= store_label_style(doc, graph, role, change);
|
||||
changed |= store_label_style(doc, graph, role, change, true);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// [`capture_label_styles`], except that a kind that keeps no style keeps the default style when `change` leaves it
|
||||
/// unchanged, for a command that gives character attributes (a size equal to the labels' own, for example).
|
||||
pub(crate) fn capture_label_styles_given(doc: &mut Document, ids: &[NodeId], change: &dyn Fn(&mut CharStyle)) -> bool {
|
||||
let mut changed = false;
|
||||
for (graph, role) in label_kinds(doc, ids) {
|
||||
changed |= store_label_style(doc, graph, role, change, false);
|
||||
}
|
||||
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 {
|
||||
/// the kept style or that mark changed. With `unless_default`, a kind that keeps no style and that `change` leaves at
|
||||
/// the default style keeps none, unless `change` sets the legend fill.
|
||||
fn store_label_style(doc: &mut Document, graph: NodeId, role: Role, change: &dyn Fn(&mut CharStyle), unless_default: bool) -> 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);
|
||||
let was = label_style(&spec.label_styles, role);
|
||||
let mut style = was.clone();
|
||||
// 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
|
||||
@@ -1215,6 +1251,9 @@ fn store_label_style(doc: &mut Document, graph: NodeId, role: Role, change: &dyn
|
||||
Role::Category => &mut styles.categories,
|
||||
Role::Legend => &mut styles.legend,
|
||||
};
|
||||
if unless_default && slot.is_none() && style == was && !(sets_fill && !styles.legend_fill_set) {
|
||||
return false;
|
||||
}
|
||||
let mut changed = slot.as_ref() != Some(&style);
|
||||
*slot = Some(style);
|
||||
if sets_fill && !styles.legend_fill_set {
|
||||
@@ -1277,37 +1316,356 @@ pub(crate) fn label_rows(n: &Node) -> Option<vectorcraft_doc::LabelRows> {
|
||||
(rows != vectorcraft_doc::LabelRows::default()).then_some(rows)
|
||||
}
|
||||
|
||||
/// The graph and kind of graph line `id`: a path directly in a graph's Axes group. Looked up through its parents, with no
|
||||
/// pass over the document.
|
||||
fn graph_line(doc: &Document, id: NodeId) -> Option<(NodeId, Line)> {
|
||||
let line = doc.node(id)?;
|
||||
if !matches!(line.kind, NodeKind::Path { .. }) {
|
||||
return None;
|
||||
}
|
||||
let path = doc.ancestry(id)?;
|
||||
let [.., graph, axes, _] = path.as_slice() else { return None };
|
||||
let spec = doc.node(*graph)?.extras().graph.as_deref()?;
|
||||
Some((*graph, line_in(spec, doc.node(*axes)?, line)?))
|
||||
}
|
||||
|
||||
/// The kind of graph line `line` is when `axes` is the Axes group of a graph drawn from `spec` and `line` a path directly
|
||||
/// in it. A radar graph's rings are its closed paths; its spokes, open, are axis lines.
|
||||
fn line_in(spec: &GraphSpec, axes: &Node, line: &Node) -> Option<Line> {
|
||||
if axes.name.as_deref() != Some("Axes") || axes.extras().series_index.is_some() || !matches!(axes.kind, NodeKind::Group { .. }) {
|
||||
return None;
|
||||
}
|
||||
let NodeKind::Path { path, .. } = &line.kind else { return None };
|
||||
Some(if spec.kind == GraphKind::Radar && path.is_closed() { Line::Ring } else { Line::Axis })
|
||||
}
|
||||
|
||||
/// The graph lines among `ids`, each with its graph and kind, from the back to the front and each once: a later line's
|
||||
/// capture replaces an earlier one's, so the frontmost line of a kind sets what the kind keeps.
|
||||
fn lines_of(doc: &Document, ids: &[NodeId]) -> Vec<(NodeId, NodeId, Line)> {
|
||||
let mut out: Vec<(NodeId, NodeId, Line)> = ids.iter().filter_map(|id| graph_line(doc, *id).map(|(g, line)| (*id, g, line))).collect();
|
||||
out.sort_by_cached_key(|(id, ..)| doc.index_path(*id));
|
||||
out.dedup_by_key(|(id, ..)| *id);
|
||||
out
|
||||
}
|
||||
|
||||
/// Which of the object rows ([`label_rows`]) a graph label or line shows its kind keeps after an edit.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Keep {
|
||||
/// All of them.
|
||||
All,
|
||||
/// Only the object opacity and blend mode; the fill and stroke rows stay as the kind keeps them.
|
||||
Object,
|
||||
/// The fill and stroke rows; the object opacity and blend mode stay as the kind keeps them.
|
||||
Rows,
|
||||
/// The fill row with `fill`, the stroke row with `stroke`, and the object opacity and blend mode with `object`; the
|
||||
/// others stay as the kind keeps them. Each row keeps its place relative to the characters; a row taken from the
|
||||
/// label or line paints above a kept row on the same side of them, unless the label or line shows it below its own row
|
||||
/// of that kind.
|
||||
Kinds { fill: bool, stroke: bool, object: bool },
|
||||
}
|
||||
|
||||
/// The kinds (true: fill) of the rows in `rows` from the bottom up, each with whether it paints below the characters.
|
||||
fn row_places(rows: &vectorcraft_doc::LabelRows) -> Vec<(bool, bool)> {
|
||||
let order = if rows.stroke_under { [false, true] } else { [true, false] };
|
||||
let has = |fill: bool| if fill { rows.paint.fill.is_some() } else { rows.paint.stroke.is_some() };
|
||||
let below = usize::from(rows.below.unwrap_or(0));
|
||||
order.into_iter().filter(|k| has(*k)).enumerate().map(|(i, k)| (k, i < below)).collect()
|
||||
}
|
||||
|
||||
/// Where the rows paint when the row of kind `taken` (true: fill) comes from `shown` and the row of the other kind from
|
||||
/// `kept`, each keeping its place relative to the characters: `below` and `stroke_under` of [`vectorcraft_doc::LabelRows`].
|
||||
fn merged_places(kept: &vectorcraft_doc::LabelRows, shown: &vectorcraft_doc::LabelRows, taken: bool) -> (Option<u8>, bool) {
|
||||
let in_shown = row_places(shown);
|
||||
let t = in_shown.iter().copied().find(|p| p.0 == taken);
|
||||
let o = row_places(kept).into_iter().find(|p| p.0 != taken);
|
||||
let order = match (t, o) {
|
||||
(Some(t), Some(o)) => {
|
||||
// Rows on different sides of the characters: the one below them is lower. On the same side: as the label or
|
||||
// line shows them, else the taken row on top.
|
||||
let at = |kind: bool| in_shown.iter().position(|p| p.0 == kind);
|
||||
let o_first = if t.1 != o.1 {
|
||||
o.1
|
||||
} else {
|
||||
match (at(!taken), at(taken)) {
|
||||
(Some(o_at), Some(t_at)) => o_at < t_at,
|
||||
_ => true,
|
||||
}
|
||||
};
|
||||
if o_first { vec![o, t] } else { vec![t, o] }
|
||||
}
|
||||
(t, o) => t.into_iter().chain(o).collect(),
|
||||
};
|
||||
let below = order.iter().filter(|p| p.1).fold(0u8, |k, _| k + 1);
|
||||
((below > 0).then_some(below), order.len() == 2 && !order[0].0)
|
||||
}
|
||||
|
||||
/// `shown` with the parts of the rows `kept` keeps that `keep` leaves as they are.
|
||||
fn keep_rows(kept: vectorcraft_doc::LabelRows, shown: vectorcraft_doc::LabelRows, keep: Keep) -> vectorcraft_doc::LabelRows {
|
||||
match keep {
|
||||
Keep::All => shown,
|
||||
Keep::Object => {
|
||||
let mut kept = kept;
|
||||
(kept.paint.opacity, kept.paint.blend) = (shown.paint.opacity, shown.paint.blend);
|
||||
kept
|
||||
}
|
||||
Keep::Rows => {
|
||||
let mut shown = shown;
|
||||
(shown.paint.opacity, shown.paint.blend) = (kept.paint.opacity, kept.paint.blend);
|
||||
shown
|
||||
}
|
||||
Keep::Kinds { fill, stroke, object } => {
|
||||
let places = match (fill, stroke) {
|
||||
(true, true) => (shown.below, shown.stroke_under),
|
||||
(false, false) => (kept.below, kept.stroke_under),
|
||||
(taken, _) => merged_places(&kept, &shown, taken),
|
||||
};
|
||||
let mut rows = shown;
|
||||
(rows.below, rows.stroke_under) = places;
|
||||
let (r, k) = (&mut rows.paint, kept.paint);
|
||||
if !object {
|
||||
(r.opacity, r.blend) = (k.opacity, k.blend);
|
||||
}
|
||||
if !fill {
|
||||
(r.fill, r.fill_opacity, r.fill_blend, r.fill_unit_box) = (k.fill, k.fill_opacity, k.fill_blend, k.fill_unit_box);
|
||||
}
|
||||
if !stroke {
|
||||
(r.stroke, r.stroke_width, r.stroke_opacity, r.stroke_blend, r.stroke_unit_box) =
|
||||
(k.stroke, k.stroke_width, k.stroke_opacity, k.stroke_blend, k.stroke_unit_box);
|
||||
}
|
||||
rows
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What lines of kind `line` keep (`slot`) after line `n` shows its rows ([`label_rows`]), of which `keep` says what is
|
||||
/// taken from the line: `None` when that is how the graph draws them with no kept rows.
|
||||
fn line_rows_after(slot: Option<&vectorcraft_doc::LabelRows>, line: Line, n: &Node, keep: Keep) -> Option<vectorcraft_doc::LabelRows> {
|
||||
let shown = label_rows(n).unwrap_or_default();
|
||||
let rows = keep_rows(slot.cloned().unwrap_or_else(|| line.default_rows()), shown, keep);
|
||||
(rows != line.default_rows()).then_some(rows)
|
||||
}
|
||||
|
||||
/// Keep the object rows ([`label_rows`]) of the graph lines among `ids` for every line of their kind (axis lines and tick
|
||||
/// marks, or a radar graph's rings), the part of them `keep` says, even when a line already showed them. Returns whether
|
||||
/// kept rows changed.
|
||||
fn store_line_rows(doc: &mut Document, ids: &[NodeId], keep: Keep) -> bool {
|
||||
let mut changed = false;
|
||||
for (id, graph, line) in lines_of(doc, ids) {
|
||||
let Some(spec) = doc.node(graph).and_then(|n| n.extras().graph.as_deref()) else { continue };
|
||||
let Some(n) = doc.node(id) else { continue };
|
||||
let kept = line_rows_after(kept_line_rows(&spec.label_styles, line), line, n, keep);
|
||||
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 slot = line_slot(&mut spec.label_styles, line);
|
||||
changed |= *slot != kept;
|
||||
*slot = kept;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// Keep the object rows of graph lines `ids` for every line of their kind, as [`capture_label_rows`] keeps a label's,
|
||||
/// for an edit that wrote their fill or stroke. Lines of a kind that the edit reached differently take the frontmost
|
||||
/// one's rows. Called inside the same edit, so they undo together. Returns whether kept rows changed.
|
||||
pub(crate) fn capture_line_rows(doc: &mut Document, ids: &[NodeId]) -> bool {
|
||||
store_line_rows(doc, ids, Keep::All)
|
||||
}
|
||||
|
||||
/// [`capture_line_rows`] for an edit that wrote the fill and stroke rows of graph lines `ids` and left their object
|
||||
/// opacity and blend mode alone: those stay as the kind keeps them, also when a line still shows other ones until the
|
||||
/// graph is drawn again.
|
||||
pub(crate) fn capture_line_fill_stroke_rows(doc: &mut Document, ids: &[NodeId]) -> bool {
|
||||
store_line_rows(doc, ids, Keep::Rows)
|
||||
}
|
||||
|
||||
/// Keep, for every line of their kind, the attributes of the object rows ([`label_rows`]) that an edit changed on the
|
||||
/// graph lines among `ids` (`before`: the document before the edit). The attributes the edit left alone stay as the kind
|
||||
/// keeps them, also when a line still shows other ones until the graph is drawn again. Lines of a kind that the edit
|
||||
/// changed differently take the frontmost one's attributes. Called inside the same edit, so they undo together. Returns
|
||||
/// whether kept rows changed.
|
||||
pub(crate) fn capture_line_changes(before: &Document, doc: &mut Document, ids: &[NodeId]) -> bool {
|
||||
let mut changed = false;
|
||||
for (id, graph, line) in lines_of(doc, ids) {
|
||||
let old = before.node(id).and_then(label_rows).unwrap_or_default();
|
||||
let new = doc.node(id).and_then(label_rows).unwrap_or_default();
|
||||
if old == new {
|
||||
continue;
|
||||
}
|
||||
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 slot = line_slot(&mut spec.label_styles, line);
|
||||
let mut rows = slot.clone().unwrap_or_else(|| line.default_rows());
|
||||
merge_row_edits(&mut rows, &old, &new);
|
||||
let kept = (rows != line.default_rows()).then_some(rows);
|
||||
changed |= *slot != kept;
|
||||
*slot = kept;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// Keep, for every line of their kind, the paint an edit wrote to row `at` of graph line `id` for each `(id, at)` in
|
||||
/// `written` when that row is the line's topmost visible fill or stroke, also when the line already showed that paint:
|
||||
/// the paint replaces the one its kind keeps from another line. The other attributes stay as the kind keeps them. Lines
|
||||
/// of a kind take the frontmost one's paint. Called inside the same edit, so they undo together. Returns whether kept
|
||||
/// rows changed.
|
||||
pub(crate) fn capture_line_paint_writes(doc: &mut Document, written: &[(NodeId, usize)]) -> bool {
|
||||
let paint = RowWrites { paint: true, ..RowWrites::NONE };
|
||||
capture_line_row_writes(doc, written, paint, paint)
|
||||
}
|
||||
|
||||
/// Which attributes of a fill or stroke row an edit wrote, for [`capture_line_row_writes`].
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
pub(crate) struct RowWrites {
|
||||
/// The paint.
|
||||
pub paint: bool,
|
||||
/// The weight (a stroke row only).
|
||||
pub weight: bool,
|
||||
/// The row's opacity.
|
||||
pub opacity: bool,
|
||||
/// The row's blend mode.
|
||||
pub blend: bool,
|
||||
}
|
||||
|
||||
impl RowWrites {
|
||||
/// No attribute.
|
||||
pub const NONE: RowWrites = RowWrites { paint: false, weight: false, opacity: false, blend: false };
|
||||
}
|
||||
|
||||
/// [`capture_line_paint_writes`] for the attributes `fill` says of a written fill row and `stroke` says of a written
|
||||
/// stroke row: each is kept for every line of the kind as the line shows it, also when the line already showed it, in
|
||||
/// place of what its kind keeps from another line.
|
||||
pub(crate) fn capture_line_row_writes(doc: &mut Document, written: &[(NodeId, usize)], fill: RowWrites, stroke: RowWrites) -> bool {
|
||||
let ids: Vec<NodeId> = written.iter().map(|(id, _)| *id).collect();
|
||||
let mut changed = false;
|
||||
for (id, graph, line) in lines_of(doc, &ids) {
|
||||
let Some(n) = doc.node(id) else { continue };
|
||||
let items = &n.appearance.items;
|
||||
let wrote = |kind: bool| items.iter().rposition(|it| it.is_fill() == kind && it.visible()).is_some_and(|at| written.contains(&(id, at)));
|
||||
let on_fill = if wrote(true) { fill } else { RowWrites::NONE };
|
||||
let on_stroke = if wrote(false) { stroke } else { RowWrites::NONE };
|
||||
if on_fill == RowWrites::NONE && on_stroke == RowWrites::NONE {
|
||||
continue;
|
||||
}
|
||||
let shown = label_rows(n).unwrap_or_default().paint;
|
||||
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 slot = line_slot(&mut spec.label_styles, line);
|
||||
let mut rows = slot.clone().unwrap_or_else(|| line.default_rows());
|
||||
let k = &mut rows.paint;
|
||||
if on_fill.paint {
|
||||
k.fill = shown.fill;
|
||||
}
|
||||
if on_fill.opacity {
|
||||
k.fill_opacity = shown.fill_opacity;
|
||||
}
|
||||
if on_fill.blend {
|
||||
k.fill_blend = shown.fill_blend;
|
||||
}
|
||||
if on_stroke.paint {
|
||||
k.stroke = shown.stroke;
|
||||
}
|
||||
if on_stroke.weight {
|
||||
k.stroke_width = shown.stroke_width;
|
||||
}
|
||||
if on_stroke.opacity {
|
||||
k.stroke_opacity = shown.stroke_opacity;
|
||||
}
|
||||
if on_stroke.blend {
|
||||
k.stroke_blend = shown.stroke_blend;
|
||||
}
|
||||
let kept = (rows != line.default_rows()).then_some(rows);
|
||||
changed |= *slot != kept;
|
||||
*slot = kept;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// Is `id` a graph line: a path directly in a graph's Axes group?
|
||||
pub(crate) fn is_graph_line(doc: &Document, id: NodeId) -> bool {
|
||||
graph_line(doc, id).is_some()
|
||||
}
|
||||
|
||||
/// Set each attribute of `rows` that differs between `old` and `new` as `new` has it.
|
||||
fn merge_row_edits(rows: &mut vectorcraft_doc::LabelRows, old: &vectorcraft_doc::LabelRows, new: &vectorcraft_doc::LabelRows) {
|
||||
fn take<T: PartialEq + Clone>(kept: &mut T, old: &T, new: &T) {
|
||||
if old != new {
|
||||
*kept = new.clone();
|
||||
}
|
||||
}
|
||||
let (k, o, n) = (&mut rows.paint, &old.paint, &new.paint);
|
||||
take(&mut k.fill, &o.fill, &n.fill);
|
||||
take(&mut k.stroke, &o.stroke, &n.stroke);
|
||||
take(&mut k.stroke_width, &o.stroke_width, &n.stroke_width);
|
||||
take(&mut k.fill_opacity, &o.fill_opacity, &n.fill_opacity);
|
||||
take(&mut k.stroke_opacity, &o.stroke_opacity, &n.stroke_opacity);
|
||||
take(&mut k.fill_blend, &o.fill_blend, &n.fill_blend);
|
||||
take(&mut k.stroke_blend, &o.stroke_blend, &n.stroke_blend);
|
||||
take(&mut k.opacity, &o.opacity, &n.opacity);
|
||||
take(&mut k.blend, &o.blend, &n.blend);
|
||||
take(&mut rows.below, &old.below, &new.below);
|
||||
take(&mut rows.stroke_under, &old.stroke_under, &new.stroke_under);
|
||||
}
|
||||
|
||||
/// Would [`store_line_rows`] with [`Keep::Object`] change what a graph keeps for the lines among `ids`? Reads the
|
||||
/// document without copying it.
|
||||
fn line_object_opacity_differs(doc: &Document, ids: &[NodeId]) -> bool {
|
||||
let mut kept: Vec<(NodeId, Line, Option<vectorcraft_doc::LabelRows>)> = vec![];
|
||||
for (id, graph, line) in lines_of(doc, ids) {
|
||||
let (Some(spec), Some(n)) = (doc.node(graph).and_then(|n| n.extras().graph.as_deref()), doc.node(id)) else { continue };
|
||||
let slot = match kept.iter().position(|(g, l, _)| *g == graph && *l == line) {
|
||||
Some(i) => kept.swap_remove(i).2,
|
||||
None => kept_line_rows(&spec.label_styles, line).cloned(),
|
||||
};
|
||||
kept.push((graph, line, line_rows_after(slot.as_ref(), line, n, Keep::Object)));
|
||||
}
|
||||
kept.into_iter().any(|(graph, line, rows)| {
|
||||
doc.node(graph).and_then(|n| n.extras().graph.as_deref()).is_some_and(|spec| kept_line_rows(&spec.label_styles, line) != rows.as_ref())
|
||||
})
|
||||
}
|
||||
|
||||
/// Keep the object rows ([`label_rows`]) of graph labels `ids` for every label of their kind, as
|
||||
/// [`capture_label_styles`] keeps a character format, even when a label already showed them: the last label of a kind
|
||||
/// in the order of `ids` sets what that kind keeps. Objects other than type are left out before the graph's labels are
|
||||
/// looked up. Called inside the same edit, so they undo together. Returns whether kept rows changed.
|
||||
/// looked up. The graph lines among `ids` keep their rows for every line of their kind too ([`capture_line_rows`]).
|
||||
/// Called inside the same edit, so they undo together. Returns whether kept rows changed.
|
||||
pub(crate) fn capture_label_rows(doc: &mut Document, ids: &[NodeId]) -> bool {
|
||||
store_label_rows(doc, ids, false)
|
||||
store_label_rows(doc, ids, Keep::All)
|
||||
}
|
||||
|
||||
/// Keep the object opacity and blend mode of graph labels `ids` for every label of their kind, as [`capture_label_rows`]
|
||||
/// keeps them, and leave the kept fill and stroke rows as they are. Returns whether what the graph keeps changed.
|
||||
/// Keep the object opacity and blend mode of graph labels and graph lines `ids` for every label or line of their kind, as
|
||||
/// [`capture_label_rows`] keeps them, and leave the kept fill and stroke rows as they are. Returns whether what the graph
|
||||
/// keeps changed.
|
||||
pub(crate) fn capture_label_object_opacity(doc: &mut Document, ids: &[NodeId]) -> bool {
|
||||
store_label_rows(doc, ids, true)
|
||||
store_label_rows(doc, ids, Keep::Object)
|
||||
}
|
||||
|
||||
/// Keep, for every label or line of their kind, the fill row (with `fill`) and the stroke row (with `stroke`) that graph
|
||||
/// labels and graph lines `ids` show, and with `object` their object opacity and blend mode, as [`capture_label_rows`]
|
||||
/// keeps them, for an edit that wrote only those: a row of the other kind stays as the kind keeps it, also when a label or
|
||||
/// line still shows its own one until the graph is drawn again. Returns whether what the graph keeps changed.
|
||||
pub(crate) fn capture_label_kind_rows(doc: &mut Document, ids: &[NodeId], (fill, stroke): (bool, bool), object: bool) -> bool {
|
||||
store_label_rows(doc, ids, Keep::Kinds { fill, stroke, object })
|
||||
}
|
||||
|
||||
/// [`capture_label_kind_rows`] for the graph lines among `ids` alone.
|
||||
pub(crate) fn capture_line_kind_rows(doc: &mut Document, ids: &[NodeId], (fill, stroke): (bool, bool), object: bool) -> bool {
|
||||
store_line_rows(doc, ids, Keep::Kinds { fill, stroke, object })
|
||||
}
|
||||
|
||||
/// Would [`capture_label_object_opacity`] change what a graph keeps for labels `ids`? Reads the document without copying
|
||||
/// it.
|
||||
pub(crate) fn label_object_opacity_differs(doc: &Document, ids: &[NodeId]) -> bool {
|
||||
label_rows_of(doc, ids).into_iter().any(|(graph, role, rows)| {
|
||||
let Some(spec) = doc.node(graph).and_then(|n| n.extras().graph.as_deref()) else { return false };
|
||||
let slot = match role {
|
||||
Role::Value => &spec.label_styles.values_rows,
|
||||
Role::Category => &spec.label_styles.categories_rows,
|
||||
Role::Legend => &spec.label_styles.legend_rows,
|
||||
};
|
||||
*slot != kept_label_rows(slot, rows, true)
|
||||
})
|
||||
line_object_opacity_differs(doc, ids)
|
||||
|| label_rows_of(doc, ids).into_iter().any(|(graph, role, rows)| {
|
||||
let Some(spec) = doc.node(graph).and_then(|n| n.extras().graph.as_deref()) else { return false };
|
||||
let slot = match role {
|
||||
Role::Value => &spec.label_styles.values_rows,
|
||||
Role::Category => &spec.label_styles.categories_rows,
|
||||
Role::Legend => &spec.label_styles.legend_rows,
|
||||
};
|
||||
*slot != kept_label_rows(slot, rows, Keep::Object)
|
||||
})
|
||||
}
|
||||
|
||||
/// [`capture_label_rows`], or with `object_only` [`capture_label_object_opacity`].
|
||||
fn store_label_rows(doc: &mut Document, ids: &[NodeId], object_only: bool) -> bool {
|
||||
let mut changed = false;
|
||||
/// [`capture_label_rows`], [`capture_label_object_opacity`] or [`capture_label_kind_rows`], as `keep` says.
|
||||
fn store_label_rows(doc: &mut Document, ids: &[NodeId], keep: Keep) -> bool {
|
||||
let mut changed = store_line_rows(doc, ids, keep);
|
||||
for (graph, role, rows) in label_rows_of(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 slot = match role {
|
||||
@@ -1315,26 +1673,23 @@ fn store_label_rows(doc: &mut Document, ids: &[NodeId], object_only: bool) -> bo
|
||||
Role::Category => &mut spec.label_styles.categories_rows,
|
||||
Role::Legend => &mut spec.label_styles.legend_rows,
|
||||
};
|
||||
let kept = kept_label_rows(slot, rows, object_only);
|
||||
let kept = kept_label_rows(slot, rows, keep);
|
||||
changed |= *slot != kept;
|
||||
*slot = kept;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// What a kind keeps after a label of it shows `rows`: those rows, or with `object_only` what `slot` keeps with the
|
||||
/// label's object opacity and blend mode.
|
||||
/// What a kind keeps (`slot`) after a label of it shows `rows`, of which `keep` says what is taken from the label.
|
||||
fn kept_label_rows(
|
||||
slot: &Option<vectorcraft_doc::LabelRows>,
|
||||
rows: Option<vectorcraft_doc::LabelRows>,
|
||||
object_only: bool,
|
||||
keep: Keep,
|
||||
) -> Option<vectorcraft_doc::LabelRows> {
|
||||
if !object_only {
|
||||
if keep == Keep::All {
|
||||
return rows;
|
||||
}
|
||||
let mut kept = slot.clone().unwrap_or_default();
|
||||
let shown = rows.unwrap_or_default();
|
||||
(kept.paint.opacity, kept.paint.blend) = (shown.paint.opacity, shown.paint.blend);
|
||||
let kept = keep_rows(slot.clone().unwrap_or_default(), rows.unwrap_or_default(), keep);
|
||||
(kept != vectorcraft_doc::LabelRows::default()).then_some(kept)
|
||||
}
|
||||
|
||||
@@ -1454,23 +1809,38 @@ 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.
|
||||
/// The graph labels and graph lines among `roots` and inside them, for an edit that reaches them without naming them.
|
||||
pub(crate) fn labels_in(doc: &Document, roots: &[NodeId]) -> Vec<NodeId> {
|
||||
let mut texts = Vec::new();
|
||||
let mut lines = Vec::new();
|
||||
for id in roots {
|
||||
// A root that is a line, or the Axes group: found through its parents.
|
||||
if graph_line(doc, *id).is_some() {
|
||||
lines.push(*id);
|
||||
}
|
||||
let Some(root) = doc.node(*id) else { continue };
|
||||
if let Some(parent) = doc.parent_of(*id).and_then(|p| doc.node(p))
|
||||
&& let Some(spec) = parent.extras().graph.as_deref()
|
||||
{
|
||||
lines.extend(root.children().into_iter().flatten().filter(|c| line_in(spec, root, c).is_some()).map(|c| c.id));
|
||||
}
|
||||
root.walk(&mut |n| {
|
||||
if matches!(n.kind, NodeKind::Text(_)) {
|
||||
texts.push(n.id);
|
||||
}
|
||||
if let Some(spec) = n.extras().graph.as_deref() {
|
||||
for axes in n.children().into_iter().flatten() {
|
||||
lines.extend(axes.children().into_iter().flatten().filter(|c| line_in(spec, axes, c).is_some()).map(|c| c.id));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
// Graph labels are type: without type among `roots`, the graph's labels are not looked up.
|
||||
if texts.is_empty() {
|
||||
return texts;
|
||||
if !texts.is_empty() {
|
||||
let labels = graph_labels(doc);
|
||||
texts.retain(|id| labels.contains_key(id));
|
||||
}
|
||||
let labels = graph_labels(doc);
|
||||
texts.retain(|id| labels.contains_key(id));
|
||||
texts.extend(lines.into_iter().filter(|id| doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. }))));
|
||||
// Nested roots (a graph and one of its labels) reach a label twice.
|
||||
texts.sort_unstable();
|
||||
texts.dedup();
|
||||
@@ -1482,10 +1852,14 @@ pub(crate) fn labels_in(doc: &Document, roots: &[NodeId]) -> Vec<NodeId> {
|
||||
/// 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 {
|
||||
/// fill and the edit named them: with `named`, only a legend label among `named` (an edit that reached the others
|
||||
/// through the graph or a group leaves them the graph's black or white); without it, every label in `ids`. The graph
|
||||
/// lines among `ids` whose rows changed keep what changed for every line of their kind ([`capture_line_changes`]), with or without
|
||||
/// `rows`. 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, named: Option<&[NodeId]>) -> bool {
|
||||
let lines = capture_line_changes(before, doc, ids);
|
||||
if !ids.iter().any(|id| doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Text(_)))) {
|
||||
return false;
|
||||
return lines;
|
||||
}
|
||||
let labels = graph_labels(doc);
|
||||
let mut picked: Vec<NodeId> = ids.iter().copied().filter(|id| labels.contains_key(id)).collect();
|
||||
@@ -1510,18 +1884,25 @@ pub(crate) fn capture_label_changes(before: &Document, doc: &mut Document, ids:
|
||||
if rows && label_rows(was) != label_rows(now) {
|
||||
changed_rows.push(id);
|
||||
}
|
||||
let fill = kind.1 != Role::Legend || one_fill(kind.0);
|
||||
let aimed = !wedge_fills.contains_key(&kind.0) || named.is_none_or(|n| n.contains(&id));
|
||||
let fill = kind.1 != Role::Legend || (one_fill(kind.0) && aimed);
|
||||
characters.extend(run_paint_change(was, now, fill).map(|change| (kind, change)));
|
||||
}
|
||||
let mut changed = capture_label_rows(doc, &changed_rows);
|
||||
let mut changed = capture_label_rows(doc, &changed_rows) | lines;
|
||||
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 |= store_label_style(
|
||||
doc,
|
||||
*graph,
|
||||
*role,
|
||||
&|st| {
|
||||
for i in entries {
|
||||
if let Some(copy) = RUN_PAINT.get(*i) {
|
||||
copy(style, st);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
true,
|
||||
);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -251,7 +251,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Object Properties",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?, name?, visible?, locked? (visible: false or locked: true deselects every selected object hidden or locked after the call, the key object included), opacity?: 0..100, blend?: \"Multiply\"…, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, data?: {key: \"value\" | null (removes it)} (the object's own data, SVG data-* attributes: {pivot: \"100,180\"} is data-pivot; document.node → attrs.data)}. On a path directly in a graph series, the graph also stores the object's opacity and blend mode, and on a series group the group's opacity, blend mode, isolate, knockout and knockoutShape (exceptions: docs/mcp.md); on a graph label, the graph stores the label's opacity and blend mode for every label of its kind",
|
||||
"{ids?|id?, name?, visible?, locked? (visible: false or locked: true deselects every selected object hidden or locked after the call, the key object included), opacity?: 0..100, blend?: \"Multiply\"…, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, data?: {key: \"value\" | null (removes it)} (the object's own data, SVG data-* attributes: {pivot: \"100,180\"} is data-pivot; document.node → attrs.data)}. On a path directly in a graph series, the graph also stores the object's opacity and blend mode, and on a series group the group's opacity, blend mode, isolate, knockout and knockoutShape (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's opacity and blend mode for every label or line of its kind",
|
||||
has_doc,
|
||||
set_props
|
||||
),
|
||||
|
||||
@@ -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), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}",
|
||||
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind → {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, and on a graph label the swapped paints of its characters for every label of its kind (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, and on a graph's axis line, tick mark or radar ring its rows for every line 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, and on a graph label the black fill and no stroke of its characters for every label of its kind (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, and on a graph's axis line, tick mark or radar ring its rows for every line 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; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} 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, and on a series group without an item, the group's own opacity, blend mode, isolate, knockout and knockoutShape (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; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} 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, and on a series group without an item, the group's own opacity, blend mode, isolate, knockout and knockoutShape (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (for a fill or stroke item, a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels; when their rows differ, `item` needs `aligned` and is a row of the backmost one), the graph stores that object's opacity and blend mode for every label or line 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, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents and, except with target \"contents\", their own fills and strokes; a compound path's member stands for its compound path) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind (docs/mcp.md); no undo step when no color changes → {changed}",
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents and, except with target \"contents\", their own fills and strokes; a compound path's member stands for its compound path) 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, and on a graph's axis line, tick mark or radar ring its rows for every line 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)
|
||||
),
|
||||
@@ -655,6 +655,8 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
|
||||
},
|
||||
|before, d, changed| {
|
||||
let series = super::appearance::capture_series_paint_writes(before, d, changed, &written.borrow());
|
||||
// A graph line keeps the paint written to it, also when it already showed it.
|
||||
let lines = super::graph::capture_line_paint_writes(d, &written.borrow());
|
||||
let labels = super::graph::capture_label_styles(d, &characters.borrow(), &|st| {
|
||||
if fill {
|
||||
st.fill = unplaced(&paint);
|
||||
@@ -665,7 +667,7 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
|
||||
st.stroke = unplaced(&paint);
|
||||
}
|
||||
});
|
||||
Ok(series || labels)
|
||||
Ok(series || lines || labels)
|
||||
},
|
||||
)?;
|
||||
// Rejected edits leave the next shape's appearance and active proxy untouched.
|
||||
@@ -1011,7 +1013,7 @@ 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);
|
||||
let labels = super::graph::capture_label_changes(&before, d, &ids, false);
|
||||
let labels = super::graph::capture_label_changes(&before, d, &ids, false, None);
|
||||
Ok(super::appearance::count_changed(d, &before, &ids) + usize::from(kept || labels))
|
||||
})?;
|
||||
}
|
||||
@@ -1047,8 +1049,15 @@ 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);
|
||||
let labels = super::graph::capture_label_changes(&before, d, &ids, false);
|
||||
Ok(super::appearance::count_changed(d, &before, &ids) + usize::from(kept || labels))
|
||||
// The graph keeps the default paint for every label of a kind it reached, and the default fill and stroke rows
|
||||
// for every line of a kind it reached, also when one already showed them; the object opacity a line kind keeps
|
||||
// stays.
|
||||
let labels = super::graph::capture_label_styles(d, &ids, &|st| {
|
||||
st.fill = Paint::solid(Color::BLACK);
|
||||
st.stroke = Paint::None;
|
||||
});
|
||||
let lines = super::graph::capture_line_fill_stroke_rows(d, &ids);
|
||||
Ok(super::appearance::count_changed(d, &before, &ids) + usize::from(kept || labels || lines))
|
||||
})?;
|
||||
}
|
||||
super::newart::reset(s);
|
||||
@@ -1269,6 +1278,9 @@ fn transparency(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
// Opacity and blend belong to the targeted fill/stroke; isolate/knockout/knockoutShape stay object-level.
|
||||
let item_ids = if editing_mask { ids } else { row_targets(s, p, C)? };
|
||||
if !editing_mask {
|
||||
super::appearance::check_part_rows(s, p, aligned || !explicit, C)?;
|
||||
}
|
||||
// The art of a graph design whose stack an explicit aligned item is a row of goes first: appearance.setItem leaves
|
||||
// it as it is and matches the other objects' rows against it.
|
||||
let of = if editing_mask || !explicit { None } else { super::appearance::design_reference(s, p, C)? };
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -318,7 +318,7 @@ pub(crate) fn style_of(n: &Node) -> Style {
|
||||
|
||||
/// Leaf shapes (paths, compound paths, text) of a subtree in paint order; guides and clipping
|
||||
/// paths are skipped.
|
||||
fn leaves(n: &Node, out: &mut Vec<Node>) {
|
||||
pub(crate) fn leaves(n: &Node, out: &mut Vec<Node>) {
|
||||
each_leaf(n, &mut |l| out.push(l.clone()));
|
||||
}
|
||||
|
||||
|
||||
@@ -63,6 +63,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"addon.pathtools.shape.set",
|
||||
"addon.pathtools.slideAnchor",
|
||||
"addon.pathtools.smooth",
|
||||
"addon.pathtools.tangentCircle",
|
||||
"addon.pathtools.trim",
|
||||
"addon.pen.append",
|
||||
"addon.pen.close",
|
||||
|
||||
@@ -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); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour] (what `group` is rewritten with; default: the rows' new colours, in order, excluded and empty rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}",
|
||||
"{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour] (what `group` is rewritten with; default: the rows' new colours, in order, excluded and empty rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line 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; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take → {objects: how many objects took the stroke options}",
|
||||
"{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path}} (a custom head with its art, as document.inspect reports one; refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads → {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, 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}",
|
||||
"{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, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {objects}",
|
||||
has_doc,
|
||||
|s, p| stroke_step(s, p, true)
|
||||
),
|
||||
@@ -307,8 +307,10 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
};
|
||||
let of = super::appearance::reference_of(s, p, item, C)?;
|
||||
// The objects counted: with a design's art, those with a row equal to the art's.
|
||||
let ids = edit_items(s, &ids, item, of, C, "Stroke", false, |n, index| {
|
||||
// The objects counted: with a design's art, those with a row equal to the art's. A graph line keeps the weight
|
||||
// given to it, also when it already showed it.
|
||||
let writes = super::graph::RowWrites { weight: change.weight.is_some(), ..super::graph::RowWrites::NONE };
|
||||
let ids = super::appearance::edit_items_writing(s, &ids, item, of, C, "Stroke", false, writes, |n, index| {
|
||||
if index.is_none()
|
||||
&& let NodeKind::Text(t) = &mut n.kind
|
||||
{
|
||||
|
||||
@@ -31,7 +31,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Apply Graphic Style",
|
||||
["Window", "Graphic Styles"],
|
||||
None,
|
||||
"{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (with `add`: of the kinds of row the style shows) and, without `add`, the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: 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. With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}",
|
||||
"{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (with `add`: of the kinds of row the style shows) and, without `add`, the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows (with `add`: of the kinds of row the style shows) and, without `add`, its object opacity and blend mode for every label or line of its kind. With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}",
|
||||
has_doc,
|
||||
style_apply
|
||||
),
|
||||
@@ -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, unless it is the art of a graph design in a series. 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, and a graph's Axes or Legend group with none of these for its topmost line or label; 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. 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}",
|
||||
"{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; a graph's Axes or Legend group: its topmost line or label); 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, a linked Axes group to its lines and labels and a linked Legend group to its labels, 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, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {name}",
|
||||
has_doc,
|
||||
style_redefine
|
||||
),
|
||||
@@ -77,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Break Link to Graphic Style",
|
||||
["Window", "Graphic Styles"],
|
||||
None,
|
||||
"{ids?|id?, target?: \"object\"|\"contents\"} unlink the objects (default: the selection) from their graphic style; they keep their look. A graph series group's id stands for the group and the paths directly in it",
|
||||
"{ids?|id?, target?: \"object\"|\"contents\"} unlink the objects (default: the selection) from their graphic style; they keep their look. A graph series group's id stands for the group and the paths directly in it, a graph's Axes group for the group and its lines and labels, and its Legend group for the group and its labels",
|
||||
has_doc,
|
||||
style_break_link
|
||||
),
|
||||
@@ -364,6 +364,9 @@ fn style_apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let shows = |kind: bool| g.appearance.items.iter().any(|it| it.is_fill() == kind && it.visible());
|
||||
let kinds = (shows(true), shows(false));
|
||||
super::appearance::capture_series_writes(&before, d, &ids, kinds, kinds, false, false);
|
||||
// A label or graph line keeps its new rows of those kinds for its kind. The other kind, the object opacity and
|
||||
// the blend mode stay as the kind keeps them.
|
||||
super::graph::capture_label_kind_rows(d, &ids, kinds, false);
|
||||
} else {
|
||||
d.graphic_style_id(i);
|
||||
let g = d.graphic_styles[i].clone();
|
||||
@@ -373,9 +376,9 @@ fn style_apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
super::appearance::clear_stood_for(d, &groups);
|
||||
super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false, true);
|
||||
// A label or graph line keeps its new rows for its kind.
|
||||
super::graph::capture_label_rows(d, &ids);
|
||||
}
|
||||
// A label keeps its new rows for its kind of label.
|
||||
super::graph::capture_label_rows(d, &ids);
|
||||
Ok(())
|
||||
})?;
|
||||
ok()
|
||||
|
||||
@@ -1830,6 +1830,7 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
para: super::create::new_type_para(),
|
||||
paras: Vec::new(),
|
||||
first_para_continues: false,
|
||||
first_para_lead: None,
|
||||
area: Default::default(),
|
||||
path_effect: Default::default(),
|
||||
path_align: Default::default(),
|
||||
@@ -2136,6 +2137,7 @@ fn headline_tracking(t: &TextObject, target: f64) -> Option<f64> {
|
||||
para: Default::default(),
|
||||
paras: Vec::new(),
|
||||
first_para_continues: false,
|
||||
first_para_lead: None,
|
||||
area: Default::default(),
|
||||
path_effect: Default::default(),
|
||||
path_align: Default::default(),
|
||||
|
||||
@@ -255,6 +255,7 @@ pub fn para_attrs(v: &ParaStyle) -> Map<String, Value> {
|
||||
("kinsoku", json!(v.kinsoku)),
|
||||
("kinsoku_type", json!(v.kinsoku_type)),
|
||||
("bunri_kinshi", json!(v.bunri_kinshi)),
|
||||
("kurikaeshi_moji_shori", json!(v.kurikaeshi_moji_shori)),
|
||||
("roman_hanging", json!(v.roman_hanging)),
|
||||
("kashida", json!(v.kashida)),
|
||||
("korean_line_break_anywhere", json!(v.korean_line_break_anywhere)),
|
||||
@@ -515,6 +516,16 @@ pub(crate) fn style_attrs(d: &Document, para: bool, name: &str) -> Option<Map<St
|
||||
if para { Kind::Para } else { Kind::Char }.attrs(d, name)
|
||||
}
|
||||
|
||||
/// The fill of `[Normal Character Style]` in `d`: black, or the fill a redefinition gave it. New
|
||||
/// type starts in that style ([Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html):
|
||||
/// every character is in it by default; [FAQs on fonts](https://helpx.adobe.com/illustrator/using/fonts-faq.html):
|
||||
/// new type's defaults are changed by editing it), so it takes this fill, not the current fill
|
||||
/// left from the last shape (#7975).
|
||||
pub(crate) fn normal_char_fill(d: &Document) -> vectorcraft_color::Paint {
|
||||
let normal = Kind::Char.attrs(d, NORMAL_CHAR).unwrap_or_default();
|
||||
with_attrs(&CharStyle::default(), &normal, "text.create").map_or_else(|_| CharStyle::default().fill, |st| st.fill)
|
||||
}
|
||||
|
||||
/// `attrs` in the form `charStyle.new` (`para`: `paraStyle.new`) stores them in `d`, or `None`
|
||||
/// when they don't pass its checks.
|
||||
pub(crate) fn stored_style_attrs(d: &Document, para: bool, attrs: &Map<String, Value>) -> Option<Map<String, Value>> {
|
||||
|
||||
@@ -225,7 +225,9 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) {
|
||||
.collect();
|
||||
let refs: Vec<&TextObject> = frames.iter().collect();
|
||||
let parts = vectorcraft_text::thread::distribute(vectorcraft_text::FontDb::global(), &refs, &story, ¶s);
|
||||
for (id, part) in live.iter().zip(parts) {
|
||||
let texts: Vec<String> = parts.iter().map(|p| p.runs.iter().map(|r| r.text.as_str()).collect()).collect();
|
||||
let leads = first_para_leads(&texts, &parts.iter().map(|p| p.continues).collect::<Vec<_>>());
|
||||
for ((id, part), lead) in live.iter().zip(parts).zip(leads) {
|
||||
if let Some(NodeKind::Text(t)) = doc.node_mut(*id).map(|n| &mut n.kind) {
|
||||
let mut next = (**t).clone();
|
||||
next.runs = part.runs;
|
||||
@@ -241,6 +243,7 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) {
|
||||
|| part.list_count != t.list_count
|
||||
|| part.list_level_counts != t.list_level_counts
|
||||
|| continues != t.first_para_continues
|
||||
|| lead != t.first_para_lead
|
||||
{
|
||||
t.runs = next.runs;
|
||||
t.para = next.para;
|
||||
@@ -250,6 +253,7 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) {
|
||||
t.list_count = part.list_count;
|
||||
t.list_level_counts = part.list_level_counts;
|
||||
t.first_para_continues = continues;
|
||||
t.first_para_lead = lead;
|
||||
refresh_bounds(t);
|
||||
}
|
||||
}
|
||||
@@ -384,17 +388,42 @@ pub(crate) fn mark_continued(doc: &mut Document) {
|
||||
let live: Vec<NodeId> = thread.into_iter().filter(|id| text_of(doc, *id).is_some()).collect();
|
||||
let frames: Vec<&TextObject> = live.iter().filter_map(|id| text_of(doc, *id)).collect();
|
||||
let marks = vectorcraft_text::thread::continued(&frames);
|
||||
for (id, on) in live.iter().zip(marks) {
|
||||
let texts: Vec<String> = frames.iter().map(|t| t.plain_text()).collect();
|
||||
let leads = first_para_leads(&texts, &marks);
|
||||
for ((id, on), lead) in live.iter().zip(marks).zip(leads) {
|
||||
if let Some(NodeKind::Text(t)) = doc.node_mut(*id).map(|n| &mut n.kind)
|
||||
&& t.first_para_continues != on
|
||||
&& (t.first_para_continues != on || t.first_para_lead != lead)
|
||||
{
|
||||
t.first_para_continues = on;
|
||||
t.first_para_lead = lead;
|
||||
refresh_bounds(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`TextObject::first_para_lead`] for each frame of a thread, from the frames' plain `texts` and
|
||||
/// whether each one's first paragraph `continues` from the frame before: the last character of
|
||||
/// that paragraph in the frames before that a repeat mark could stand for, or None. One pass over
|
||||
/// the frames: each frame's lead is carried forward to the next.
|
||||
fn first_para_leads(texts: &[String], continues: &[bool]) -> Vec<Option<char>> {
|
||||
// The lead the next frame takes when its first paragraph continues from this one.
|
||||
let mut carry = None;
|
||||
texts
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(k, text)| {
|
||||
#[cfg(test)]
|
||||
LEAD_SCANS.with(|c| c.set(c.get() + 1));
|
||||
let lead = carry.filter(|_| continues.get(k) == Some(&true));
|
||||
let tail = text.rsplit('\n').next().unwrap_or(text);
|
||||
// A paragraph break in this frame ends the paragraph the lead came from.
|
||||
carry = vectorcraft_text::repeat_base(tail).or(lead.filter(|_| tail.len() == text.len()));
|
||||
lead
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Tests: how many times [`story_of`] and [`ThreadIndex::of`] went through the document's
|
||||
@@ -402,6 +431,8 @@ thread_local! {
|
||||
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 frame texts [`first_para_leads`] went through on this thread.
|
||||
static LEAD_SCANS: 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
|
||||
@@ -417,6 +448,12 @@ pub(crate) fn story_builds() -> usize {
|
||||
STORY_BUILDS.with(std::cell::Cell::get)
|
||||
}
|
||||
|
||||
/// Tests: how many frame texts [`first_para_leads`] has gone through on this thread.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn lead_scans() -> usize {
|
||||
LEAD_SCANS.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> {
|
||||
|
||||
@@ -2226,3 +2226,57 @@ fn paragraph_indents_check_every_entry_and_skip_a_change_that_changes_nothing()
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
assert_eq!(text_of(&s.doc().unwrap().doc, NodeId(c)).unwrap().para_at(1).left_indent, 30.0);
|
||||
}
|
||||
|
||||
/// Kurikaeshi Moji Shori: a frame whose first paragraph continues carries the last character of
|
||||
/// that paragraph in the frames before that a repeat mark can stand for, looking past frames that
|
||||
/// hold only repeat marks and stopping at the paragraph's start; a frame that starts a paragraph
|
||||
/// carries none. Flowing the story and opening a file both set it.
|
||||
#[test]
|
||||
fn a_continued_frame_carries_the_character_a_repeat_mark_stands_for() {
|
||||
let leads = |texts: &[&str], continues: &[bool]| first_para_leads(&texts.iter().map(|t| t.to_string()).collect::<Vec<_>>(), continues);
|
||||
assert_eq!(leads(&["時", "々す"], &[false, true]), [None, Some('時')]);
|
||||
assert_eq!(leads(&["時", "々", "々"], &[false, true, true]), [None, Some('時'), Some('時')]);
|
||||
assert_eq!(leads(&["時\nか\u{3099}", "ゝ"], &[false, true]), [None, Some('か')]);
|
||||
assert_eq!(leads(&["時\n々", "々"], &[false, true]), [None, None]);
|
||||
assert_eq!(leads(&["時\n", "々"], &[false, false]), [None, None]);
|
||||
assert_eq!(leads(&[], &[]), Vec::<Option<char>>::new());
|
||||
// Opening a file marks the frames as they were saved.
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 300})).unwrap();
|
||||
let mut ids = Vec::new();
|
||||
for (x, text) in [(10, "日時"), (200, "々す")] {
|
||||
let id =
|
||||
s.execute("text.create", &json!({"x": x, "y": 10, "text": text, "area": {"width": 150, "height": 60}})).unwrap()["id"].as_u64().unwrap();
|
||||
ids.push(NodeId(id));
|
||||
}
|
||||
let mut d = (*s.doc().unwrap().doc).clone();
|
||||
d.text_threads = vec![ids.clone()];
|
||||
mark_continued(&mut d);
|
||||
let tb = text_of(&d, ids[1]).unwrap();
|
||||
assert!(tb.first_para_continues);
|
||||
assert_eq!(tb.first_para_lead, Some('時'));
|
||||
// Flowing the story through the frames sets it from the text each frame now holds.
|
||||
reflow(&d.clone(), &mut d);
|
||||
let (ta, tb) = (text_of(&d, ids[0]).unwrap(), text_of(&d, ids[1]).unwrap());
|
||||
assert_eq!([ta.plain_text(), tb.plain_text()].concat(), "日時々す");
|
||||
assert!(tb.first_para_continues);
|
||||
assert_eq!(tb.first_para_lead, vectorcraft_text::repeat_base(&ta.plain_text()));
|
||||
}
|
||||
|
||||
/// Kurikaeshi Moji Shori: the leads of a thread whose frames hold only repeat marks come from one
|
||||
/// pass over the frames, each frame's text gone through once, not once for every frame after it.
|
||||
#[test]
|
||||
fn continued_frame_leads_go_through_each_frame_once() {
|
||||
let n = 2000;
|
||||
let mut texts = vec!["時".to_string()];
|
||||
texts.extend(std::iter::repeat_n("々\u{2028}".to_string(), n - 1));
|
||||
let continues: Vec<bool> = (0..n).map(|k| k > 0).collect();
|
||||
let before = lead_scans();
|
||||
let leads = first_para_leads(&texts, &continues);
|
||||
assert!(lead_scans() - before <= n, "{} frame texts gone through for {n} frames", lead_scans() - before);
|
||||
assert_eq!(leads.first(), Some(&None));
|
||||
assert!(leads.iter().skip(1).all(|l| *l == Some('時')));
|
||||
// A paragraph break stops the carry, and a frame that starts a paragraph carries nothing.
|
||||
let leads = first_para_leads(&["時".into(), "々\nす".into(), "々".into(), "日".into(), "々".into()], &[false, true, true, false, true]);
|
||||
assert_eq!(leads, [None, Some('時'), Some('す'), None, Some('日')]);
|
||||
}
|
||||
|
||||
@@ -1038,7 +1038,17 @@ fn set_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// not in a scaled label's own units).
|
||||
let mut labels_changed = false;
|
||||
if range.is_none() {
|
||||
labels_changed = super::graph::capture_label_styles(d, &ids, &|st| {
|
||||
let gives_character = font.is_some()
|
||||
|| style.is_some()
|
||||
|| size.is_some()
|
||||
|| leading.is_some()
|
||||
|| tracking.is_some()
|
||||
|| fill.is_some()
|
||||
|| stroke.is_some()
|
||||
|| !stroke_weight.is_empty()
|
||||
|| features.is_some()
|
||||
|| feature_changes.as_ref().is_some_and(|c| !c.is_empty());
|
||||
let change = |st: &mut vectorcraft_doc::CharStyle| {
|
||||
if let Some(f) = &font {
|
||||
st.font_family = f.clone();
|
||||
st.font_version = None;
|
||||
@@ -1079,7 +1089,13 @@ fn set_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(c) = &feature_changes {
|
||||
st.features = super::textedit::change_features(&st.features, c);
|
||||
}
|
||||
});
|
||||
};
|
||||
// A command that gives character attributes keeps the style even when they equal the labels' own.
|
||||
labels_changed = if gives_character {
|
||||
super::graph::capture_label_styles_given(d, &ids, &change)
|
||||
} else {
|
||||
super::graph::capture_label_styles(d, &ids, &change)
|
||||
};
|
||||
}
|
||||
Ok(((), labels_changed))
|
||||
})?;
|
||||
|
||||
@@ -504,6 +504,62 @@ fn bunri_kinshi_is_set_per_paragraph_and_saved_only_when_on() {
|
||||
assert!(!text(&s).para_at(0).bunri_kinshi && !text(&s).para_at(1).bunri_kinshi);
|
||||
}
|
||||
|
||||
/// Paragraph panel menu › Kurikaeshi Moji Shori: off for new type and for a paragraph saved before
|
||||
/// it, and saved only when on; `text.setFormat {kurikaeshiMojiShori}` sets it per paragraph in one
|
||||
/// undo step, records nothing when the paragraphs already have the value, refuses a value that is
|
||||
/// not true or false, and paragraph styles carry it. The text keeps its repeat marks.
|
||||
#[test]
|
||||
fn kurikaeshi_moji_shori_is_set_per_paragraph_and_saved_only_when_on() {
|
||||
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": 10, "size": 20, "text": "時々\nすゝ"})).unwrap()["id"].as_u64().unwrap();
|
||||
let text = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => (**t).clone(),
|
||||
_ => panic!("text"),
|
||||
};
|
||||
assert!(!text(&s).para_at(0).kurikaeshi_moji_shori, "new type has it off");
|
||||
assert!(serde_json::to_value(text(&s).para_at(0)).unwrap().get("kurikaeshi_moji_shori").is_none());
|
||||
let old: vectorcraft_doc::ParaStyle = serde_json::from_value(json!({"justify": "Left"})).unwrap();
|
||||
assert!(!old.kurikaeshi_moji_shori, "saved before the option: off");
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
// Only the second paragraph.
|
||||
let second = "時々\n".len();
|
||||
s.execute("text.setFormat", &json!({"kurikaeshiMojiShori": true, "start": second, "end": second})).unwrap();
|
||||
assert!(!text(&s).para_at(0).kurikaeshi_moji_shori && text(&s).para_at(1).kurikaeshi_moji_shori);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1);
|
||||
assert_eq!(text(&s).plain_text(), "時々\nすゝ", "the text keeps its marks");
|
||||
// The same value again records nothing.
|
||||
s.execute("text.setFormat", &json!({"kurikaeshiMojiShori": true, "start": second, "end": second})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1);
|
||||
let saved = serde_json::to_value(text(&s).para_at(1)).unwrap();
|
||||
assert_eq!(saved["kurikaeshi_moji_shori"], true);
|
||||
let back: vectorcraft_doc::ParaStyle = serde_json::from_value(saved).unwrap();
|
||||
assert!(back.kurikaeshi_moji_shori);
|
||||
let reopened = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
|
||||
let Some(NodeKind::Text(back)) = reopened.node(NodeId(id)).map(|n| &n.kind) else { panic!("text") };
|
||||
assert!(!back.para_at(0).kurikaeshi_moji_shori && back.para_at(1).kurikaeshi_moji_shori, "the file keeps it per paragraph");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(!text(&s).para_at(1).kurikaeshi_moji_shori);
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert!(text(&s).para_at(1).kurikaeshi_moji_shori);
|
||||
for bad in [json!("yes"), json!(1)] {
|
||||
assert!(s.execute("text.setFormat", &json!({"ids": [id], "kurikaeshiMojiShori": bad, "kinsoku": "none"})).is_err(), "{bad}");
|
||||
}
|
||||
assert!(s.execute("text.setRangeStyle", &json!({"id": id, "kurikaeshiMojiShori": false})).is_err());
|
||||
assert!(
|
||||
text(&s).para_at(1).kurikaeshi_moji_shori && text(&s).para_at(1).kinsoku != vectorcraft_doc::Kinsoku::None,
|
||||
"a refused call changes nothing"
|
||||
);
|
||||
// A paragraph style carries it.
|
||||
s.execute("paraStyle.new", &json!({"name": "Repeats", "attrs": {"kurikaeshi_moji_shori": true}})).unwrap();
|
||||
s.execute("paraStyle.apply", &json!({"name": "Repeats", "id": id})).unwrap();
|
||||
assert!(text(&s).para_at(0).kurikaeshi_moji_shori && text(&s).para_at(1).kurikaeshi_moji_shori);
|
||||
s.execute("paraStyle.new", &json!({"name": "Marks", "attrs": {"kurikaeshi_moji_shori": false}})).unwrap();
|
||||
s.execute("paraStyle.apply", &json!({"name": "Marks", "id": id})).unwrap();
|
||||
assert!(!text(&s).para_at(0).kurikaeshi_moji_shori && !text(&s).para_at(1).kurikaeshi_moji_shori);
|
||||
}
|
||||
|
||||
/// Paragraph panel › Insert Kashidas: `text.setFormat {kashida}` sets it per paragraph in one
|
||||
/// undo step, the paragraph is saved with it only when it is not None and opens with it, an
|
||||
/// unknown value changes nothing, and paragraph styles carry it.
|
||||
|
||||
@@ -102,6 +102,34 @@ fn a_kept_graph_label_style_change_alone_records_one_undo_step() {
|
||||
records_nothing(&mut s, "text.setStyle", p);
|
||||
}
|
||||
|
||||
/// `text.setStyle` on a graph label with only `justify`, which the label already has, records no undo step and keeps no
|
||||
/// character style for its kind of label.
|
||||
#[test]
|
||||
fn a_justify_only_style_change_on_a_graph_label_records_nothing() {
|
||||
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 = legend
|
||||
.children()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find_map(|c| match &c.kind {
|
||||
NodeKind::Text(t) if t.plain_text() == "2025" => Some(c.id),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
records_nothing(&mut s, "text.setStyle", json!({"ids": [label.0], "justify": "left"}));
|
||||
let kept = s.doc().unwrap().doc.node(graph).unwrap().extras().graph.as_deref().unwrap().label_styles.legend.clone();
|
||||
assert!(kept.is_none(), "the legend keeps a style");
|
||||
}
|
||||
|
||||
/// `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() {
|
||||
|
||||
@@ -26,6 +26,9 @@ impl Session {
|
||||
vectorcraft_doc::hit::set_image_paint(vectorcraft_render::effects::image_paint);
|
||||
// Clicks inside a clip group fall in the region its clipping path's effects give it.
|
||||
vectorcraft_doc::hit::set_clip_region(vectorcraft_render::effects::reshaped_clip_outline);
|
||||
// Clicks and marquees find paths, compound paths, groups and layers where their geometry
|
||||
// effects draw them.
|
||||
vectorcraft_doc::hit::set_drawn_art(vectorcraft_render::effects::preview::drawn_art);
|
||||
// Clicks find a blend's steps and an envelope's distorted art where the canvas draws them,
|
||||
// evaluated again when the fonts, the hyphenation exceptions or the plug-ins change.
|
||||
vectorcraft_doc::hit::set_live_art(vectorcraft_render::effects::expand_live, || {
|
||||
|
||||
@@ -89,6 +89,45 @@ fn export_3d_object_refuses_objects_without_a_3d_effect_and_bad_formats() {
|
||||
assert_eq!(r["added"], 1);
|
||||
}
|
||||
|
||||
/// Without `ids`, the selected objects without a 3D effect, a group whose 3D effect is on its fill
|
||||
/// (it draws nothing to export) and a 3D object inside another selected one are left out; a
|
||||
/// selection with none left is refused.
|
||||
#[test]
|
||||
fn export_3d_object_leaves_flat_objects_in_the_selection_out() {
|
||||
let mut s = session();
|
||||
let plain = run(&mut s, "shape.rectangle", json!({"x": 10.0, "y": 100.0, "width": 40.0, "height": 30.0}))["id"].as_u64().unwrap();
|
||||
let filled = run(&mut s, "shape.rectangle", json!({"x": 10.0, "y": 200.0, "width": 40.0, "height": 30.0}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "select.set", json!({"ids": [filled]}));
|
||||
let group = run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "select.set", json!({"ids": [group]}));
|
||||
run(&mut s, "appearance.addFill", json!({}));
|
||||
run(&mut s, "effect.apply", json!({"effect": "threeD.extrude"}));
|
||||
// `effect.apply` puts a group's 3D effect on the group itself; a file can hold one on its fill.
|
||||
s.edit("fill", |d, _| {
|
||||
let n = d.node_mut(vectorcraft_doc::NodeId(group)).unwrap();
|
||||
let fx = n.appearance.effects.remove(0);
|
||||
n.appearance.items[0].effects_mut().push(fx);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
run(&mut s, "select.set", json!({"ids": [plain, group]}));
|
||||
let before = undo_len(&s);
|
||||
assert!(s.execute("assets.add3D", &json!({})).is_err(), "no object with a 3D effect to export");
|
||||
assert_eq!(undo_len(&s), before);
|
||||
let inner = extruded(&mut s, 100.0, "Inner");
|
||||
let other = run(&mut s, "shape.rectangle", json!({"x": 200.0, "y": 10.0, "width": 40.0, "height": 30.0}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "select.set", json!({"ids": [inner, other]}));
|
||||
let outer = run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "select.set", json!({"ids": [outer]}));
|
||||
run(&mut s, "effect.apply", json!({"effect": "threeD.extrude"}));
|
||||
run(&mut s, "select.set", json!({"ids": [plain, group, inner, outer]}));
|
||||
let r = run(&mut s, "assets.add3D", json!({}));
|
||||
assert_eq!(r["added"], 1, "{r}");
|
||||
let nodes: Vec<Value> = run(&mut s, "assets.list", json!({}))["assets"].as_array().unwrap().iter().map(|a| a["nodes"].clone()).collect();
|
||||
assert_eq!(nodes, [json!([outer])]);
|
||||
assert!(s.execute("assets.add3D", &json!({"ids": [plain, outer]})).is_err(), "ids are still refused");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_format_is_set_per_asset_and_only_a_change_is_an_undo_step() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -5847,9 +5847,10 @@ fn add_image(s: &mut Session, r: &vectorcraft_trace::Raster, xf: Affine) -> Node
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// The traced paths of an Image Trace object: its children but the image and the seam fills.
|
||||
/// The traced paths of an Image Trace object: its children but the image and the seam fills'
|
||||
/// clip group (a trace makes no other clip group).
|
||||
fn traced_paths(n: &Node) -> Vec<Arc<Node>> {
|
||||
n.children().unwrap().iter().filter(|c| !matches!(c.kind, NodeKind::Image(_)) && c.name.as_deref() != Some("Seam Fills")).cloned().collect()
|
||||
n.children().unwrap().iter().filter(|c| !matches!(c.kind, NodeKind::Image(_) | NodeKind::Group { clip: true, .. })).cloned().collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -6550,7 +6551,12 @@ fn image_trace_abutting_seam_fills_sit_under_the_paths() {
|
||||
assert!(matches!(kids[0].kind, NodeKind::Image(_)));
|
||||
let group = seams(&n).unwrap();
|
||||
assert!(Arc::ptr_eq(&group, &kids[1]), "the seam fills come under the paths");
|
||||
let strokes = group.children().unwrap();
|
||||
assert!(matches!(group.kind, NodeKind::Group { clip: true, .. }), "{group:?}");
|
||||
// The two paths cover the image, so the strokes are clipped to its box.
|
||||
let (clip, strokes) = group.children().unwrap().split_first().unwrap();
|
||||
assert!(matches!(clip.kind, NodeKind::Path { clipping: true, .. }), "{clip:?}");
|
||||
let cb = outline(clip).0.bounds().unwrap();
|
||||
assert!([cb.x0, cb.y0, cb.x1 - 80.0, cb.y1 - 40.0].iter().all(|v| v.abs() < 1e-9), "{cb:?}");
|
||||
assert_eq!(strokes.len(), 1);
|
||||
assert_eq!(strokes[0].appearance.fill_paint(), Paint::None);
|
||||
let AppearanceItem::Stroke(layer) = &strokes[0].appearance.items[0] else { panic!("{:?}", strokes[0].appearance) };
|
||||
@@ -6568,6 +6574,14 @@ fn image_trace_abutting_seam_fills_sit_under_the_paths() {
|
||||
assert_eq!(names.len(), 3, "{names:?}");
|
||||
assert_eq!(names[0], "Edges", "{names:?}");
|
||||
assert_eq!(n.children().unwrap()[0].id, group.id);
|
||||
// Above a path, the seam fills' group is refused by name, not as an Auto Grouping group.
|
||||
let (mut s, _, r) = made("abutting", "imageTrace.make", false);
|
||||
let g = NodeId(r["id"].as_u64().unwrap());
|
||||
let kids = node(&s, g).children().unwrap().clone();
|
||||
s.execute("object.arrange.bringToFront", &json!({"ids": [kids[1].id.0]})).unwrap();
|
||||
assert_eq!(node(&s, g).children().unwrap().last().map(|c| c.id), Some(kids[1].id));
|
||||
let e = s.execute("imageTrace.expand", &json!({"id": g.0, "byColor": true})).unwrap_err().to_string();
|
||||
assert!(e.contains("seam fills") && !e.contains("Auto Grouping"), "{e}");
|
||||
let (mut s, img, _) = made("abutting", "imageTrace.make", false);
|
||||
assert_eq!(ids(&s.execute("imageTrace.release", &json!({})).unwrap()), vec![img]);
|
||||
// Make and Expand by color too.
|
||||
@@ -6577,13 +6591,126 @@ fn image_trace_abutting_seam_fills_sit_under_the_paths() {
|
||||
// Overlapping paths are stacked: no seam fills.
|
||||
let (s, _, r) = made("overlapping", "imageTrace.make", false);
|
||||
assert!(seams(&node(&s, NodeId(r["id"].as_u64().unwrap()))).is_none());
|
||||
// An image stretched 3× across and squeezed to half height: 1.5 pixels at the larger scale.
|
||||
}
|
||||
|
||||
/// With white left out, the seam fills are clipped to the image's box within the traced paths'
|
||||
/// box, so the expanded trace measures as its paths do, also on a turned image.
|
||||
#[test]
|
||||
fn image_trace_seam_fills_stay_within_the_traced_paths_box() {
|
||||
let seams = |n: &Node| n.children().unwrap().iter().find(|c| c.name.as_deref() == Some("Seam Fills")).cloned();
|
||||
let band = vectorcraft_trace::Raster::from_fn(24, 16, |x, y| match ((4..12).contains(&y), x < 12) {
|
||||
(false, _) => [255; 4],
|
||||
(true, true) => [200, 30, 30, 255],
|
||||
(true, false) => [30, 30, 200, 255],
|
||||
});
|
||||
for xf in [Affine::IDENTITY, Affine::translate((100.0, 100.0)) * Affine::rotate(0.5)] {
|
||||
let mut s = session();
|
||||
add_image(&mut s, &band, xf);
|
||||
let r = s
|
||||
.execute(
|
||||
"imageTrace.makeAndExpand",
|
||||
&json!({"params": {"mode": "color", "palette": "limited", "colors": 3, "method": "abutting", "ignoreWhite": true}}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r["paths"], 2, "{r}");
|
||||
let n = node(&s, NodeId(r["id"].as_u64().unwrap()));
|
||||
let group = seams(&n).unwrap();
|
||||
let clip = &group.children().unwrap()[0];
|
||||
assert!(matches!(clip.kind, NodeKind::Path { clipping: true, .. }), "{clip:?}");
|
||||
let cb = outline(clip).0.bounds().unwrap();
|
||||
let paths = n.children().unwrap()[1..].iter().filter_map(|c| c.geometric_bounds()).reduce(|a, b| a.union(b)).unwrap();
|
||||
assert_eq!(n.geometric_bounds(), Some(paths), "{xf:?}");
|
||||
assert!(cb.x0 >= paths.x0 - 1e-9 && cb.y0 >= paths.y0 - 1e-9 && cb.x1 <= paths.x1 + 1e-9 && cb.y1 <= paths.y1 + 1e-9, "{xf:?}: {cb:?}");
|
||||
if xf == Affine::IDENTITY {
|
||||
assert!([cb.x0, cb.y0 - 4.0, cb.x1 - 24.0, cb.y1 - 12.0].iter().all(|v| v.abs() < 1e-9), "{cb:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// On an image stretched more one way than another, the seam fills are the strokes' outlines in
|
||||
/// image pixels, filled: on an image stretched 20× across, the one along a horizontal edge covers
|
||||
/// 0.75 image pixels on each side of it, as on an image scaled alike both ways, and does not reach
|
||||
/// across the transparent rows above the edge.
|
||||
#[test]
|
||||
fn image_trace_seam_fills_on_a_stretched_image_stay_near_their_edge() {
|
||||
// Red beside blue, the edge between them anti-aliased, on an image stretched 3× across and
|
||||
// squeezed to half height: the outline is 1.5 pixels (4.5 points) across the vertical edge.
|
||||
let art = vectorcraft_trace::Raster::from_fn(40, 20, |x, _| {
|
||||
let share = (16.4 - f64::from(x)).clamp(0.0, 1.0);
|
||||
let mix = |a: f64, b: f64| (a * share + b * (1.0 - share)).round() as u8;
|
||||
[mix(200.0, 30.0), mix(40.0, 90.0), mix(50.0, 200.0), 255]
|
||||
});
|
||||
let mut s = session();
|
||||
add_image(&mut s, &art, Affine::scale_non_uniform(3.0, 0.5));
|
||||
let r = s.execute("imageTrace.make", &json!({"params": {"mode": "color", "palette": "limited", "colors": 2, "method": "abutting"}})).unwrap();
|
||||
let group = seams(&node(&s, NodeId(r["id"].as_u64().unwrap()))).unwrap();
|
||||
let AppearanceItem::Stroke(layer) = &group.children().unwrap()[0].appearance.items[0] else { panic!("{group:?}") };
|
||||
assert!((layer.width - 4.5).abs() < 1e-9, "{}", layer.width);
|
||||
let n = node(&s, NodeId(r["id"].as_u64().unwrap()));
|
||||
let kids = n.children().unwrap();
|
||||
assert_eq!(kids[1].name.as_deref(), Some("Seam Fills"));
|
||||
let fill = &kids[1].children().unwrap()[1];
|
||||
assert_eq!(fill.appearance.stroke_paint(), Paint::None, "{:?}", fill.appearance);
|
||||
assert_eq!(fill.appearance.fill_paint(), kids[2].appearance.fill_paint(), "the lower path's color");
|
||||
let bb = outline(fill).0.bounds().unwrap();
|
||||
assert!((bb.width() - 4.5).abs() < 0.05 && bb.y0.abs() < 1e-6 && (bb.y1 - 10.0).abs() < 1e-6, "{bb:?}");
|
||||
// Rows 0 to 5 transparent, 5 to 10 red, 10 to 20 blue.
|
||||
let art = vectorcraft_trace::Raster::from_fn(40, 20, |_, y| match y {
|
||||
0..5 => [0, 0, 0, 0],
|
||||
5..10 => [200, 30, 30, 255],
|
||||
_ => [30, 30, 200, 255],
|
||||
});
|
||||
let mut s = session();
|
||||
add_image(&mut s, &art, Affine::scale_non_uniform(20.0, 1.0));
|
||||
let r = s.execute("imageTrace.make", &json!({"params": {"mode": "color", "palette": "limited", "colors": 2, "method": "abutting"}})).unwrap();
|
||||
let n = node(&s, NodeId(r["id"].as_u64().unwrap()));
|
||||
let group = n.children().unwrap().iter().find(|c| c.name.as_deref() == Some("Seam Fills")).cloned().unwrap();
|
||||
let (_, members) = group.children().unwrap().split_first().unwrap();
|
||||
assert!(!members.is_empty(), "{group:?}");
|
||||
for m in members {
|
||||
// What the member covers: its outline, grown by half its stroke's width.
|
||||
let half = m.appearance.items.iter().fold(0.0_f64, |w, it| match it {
|
||||
AppearanceItem::Stroke(l) => w.max(l.width / 2.0),
|
||||
_ => w,
|
||||
});
|
||||
let bb = outline(m).0.bounds().unwrap();
|
||||
let (y0, y1) = (bb.y0 - half, bb.y1 + half);
|
||||
assert!(y0 > 9.25 - 1e-6 && y1 < 10.75 + 1e-6, "covers y {y0} to {y1}: {m:?}");
|
||||
}
|
||||
// Renamed, the group of filled outlines is still the seam fills: Expand by color keeps it under
|
||||
// every color's group.
|
||||
s.execute("layer.setProps", &json!({"id": group.id.0, "name": "Edges"})).unwrap();
|
||||
s.execute("imageTrace.expand", &json!({"id": n.id.0, "byColor": true})).unwrap();
|
||||
assert_eq!(node(&s, n.id).children().unwrap()[0].id, group.id);
|
||||
}
|
||||
|
||||
/// A trace made before the seam fills were clipped holds them in a group without a clip: Expand by
|
||||
/// color keeps that group under every color's group too, named or renamed.
|
||||
#[test]
|
||||
fn image_trace_expand_by_color_keeps_unclipped_seam_fills() {
|
||||
let art = vectorcraft_trace::Raster::from_fn(40, 20, |x, _| {
|
||||
let share = (16.4 - f64::from(x)).clamp(0.0, 1.0);
|
||||
let mix = |a: f64, b: f64| (a * share + b * (1.0 - share)).round() as u8;
|
||||
[mix(200.0, 30.0), mix(40.0, 90.0), mix(50.0, 200.0), 255]
|
||||
});
|
||||
for name in [Some("Seam Fills"), None] {
|
||||
let mut s = session();
|
||||
add_image(&mut s, &art, Affine::scale(2.0));
|
||||
let r = s.execute("imageTrace.make", &json!({"params": {"mode": "color", "palette": "limited", "colors": 2, "method": "abutting"}})).unwrap();
|
||||
let g = NodeId(r["id"].as_u64().unwrap());
|
||||
// The seam fills as such a trace holds them: the strokes alone, in a plain group.
|
||||
let seams = node(&s, g).children().unwrap()[1].clone();
|
||||
let NodeKind::Group { clip: true, children } = &seams.kind else { panic!("{seams:?}") };
|
||||
let mut legacy = Node::group(seams.id, children[1..].to_vec());
|
||||
legacy.name = name.map(Into::into);
|
||||
s.edit("legacy", |d, _| {
|
||||
let NodeKind::Group { children, .. } = &mut d.node_mut(g).unwrap().kind else { panic!("trace group") };
|
||||
children[1] = Arc::new(legacy);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("imageTrace.expand", &json!({"id": g.0, "byColor": true})).unwrap();
|
||||
let kids = node(&s, g).children().unwrap().clone();
|
||||
assert_eq!(kids.len(), 3, "{name:?}: {kids:?}");
|
||||
assert_eq!(kids[0].id, seams.id, "{name:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Expand by color: each color's paths in a group of their own, named by the color, the groups
|
||||
@@ -7646,6 +7773,51 @@ fn image_trace_views_draw_on_screen_only_and_expand_to_the_result() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Outline views draw the traced paths' outlines and leave out an Abutting trace's seam fills
|
||||
/// (their clipping box and strokes, or on a stretched image the strokes' filled outlines), renamed
|
||||
/// too.
|
||||
#[test]
|
||||
fn image_trace_outline_view_leaves_out_the_seam_fills() {
|
||||
// Red beside blue in the middle of a transparent 60 × 40 image, placed at 50, 50 and scaled 2×,
|
||||
// or 2× across and 2.5× down.
|
||||
let art = vectorcraft_trace::Raster::from_fn(60, 40, |x, y| match ((10..50).contains(&x) && (10..30).contains(&y), x < 30) {
|
||||
(false, _) => [0, 0, 0, 0],
|
||||
(true, true) => [200, 30, 30, 255],
|
||||
(true, false) => [30, 30, 200, 255],
|
||||
});
|
||||
for (scale, stretched) in [(Affine::scale(2.0), false), (Affine::scale_non_uniform(2.0, 2.5), true)] {
|
||||
let mut s = session();
|
||||
add_image(&mut s, &art, Affine::translate((50.0, 50.0)) * scale);
|
||||
let r = s.execute("imageTrace.make", &json!({"params": {"mode": "color", "palette": "limited", "colors": 2, "method": "abutting"}})).unwrap();
|
||||
let g = NodeId(r["id"].as_u64().unwrap());
|
||||
let seams =
|
||||
node(&s, g).children().unwrap().iter().find(|c| matches!(c.kind, NodeKind::Group { clip: true, .. })).cloned().expect("seam fills");
|
||||
// Strokes, or on the stretched image their outlines, filled.
|
||||
let members = &seams.children().unwrap()[1..];
|
||||
assert!(!members.is_empty());
|
||||
for m in members {
|
||||
let (fill, stroke) = (m.appearance.fill_paint(), m.appearance.stroke_paint());
|
||||
assert_eq!((fill != Paint::None, stroke != Paint::None), (stretched, !stretched), "{scale:?}: {fill:?}, {stroke:?}");
|
||||
}
|
||||
s.execute("imageTrace.setView", &json!({"id": g.0, "view": "outlines"})).unwrap();
|
||||
let screen = render_doc(&s, true);
|
||||
// The image's top edge (y = 50), away from the art: nothing drawn.
|
||||
for x in [60, 110, 160] {
|
||||
assert!(screen.pixel(x, 50)[0] > 245 && screen.pixel(x, 51)[0] > 245, "{scale:?}, x = {x}: {:?}", screen.pixel(x, 50));
|
||||
}
|
||||
// The art's left edge (x = 70) is outlined.
|
||||
assert!((68..=72).any(|x| screen.pixel(x, 90)[0] < 128), "{scale:?}");
|
||||
// Beside the red and blue paths' shared edge (x = 110), inside the seam band (1.5 units
|
||||
// each side on the stretched image) but off the traced outlines (x = 109 and 110): nothing.
|
||||
for x in [108, 111] {
|
||||
assert!(screen.pixel(x, 100)[0] > 245, "{scale:?}, x = {x}: {:?}", screen.pixel(x, 100));
|
||||
}
|
||||
// Renamed, the group is still left out: the view draws as it did.
|
||||
s.execute("layer.setProps", &json!({"id": seams.id.0, "name": "Edges"})).unwrap();
|
||||
assert!(render_doc(&s, true).pixels == screen.pixels, "{scale:?}: renamed seam fills drawn");
|
||||
}
|
||||
}
|
||||
|
||||
/// #569: merging the regions of a rosette of unfilled ellipses (each off the centre, petals
|
||||
/// overlapping) merges every region the drags touch into one shape whose outline is only the
|
||||
/// merged area's border: no edge between merged regions stays in, as a stray line or a spur.
|
||||
|
||||
@@ -512,3 +512,21 @@ fn keep_plain_text_preference_drops_pasted_formatting() {
|
||||
assert_eq!(paste_copied_range(false), 40.0, "Keep Formatting");
|
||||
assert_eq!(paste_copied_range(true), 10.0, "Keep Plain Text");
|
||||
}
|
||||
|
||||
/// #7975: pasted plain text is new type, filled as [Normal Character Style] is, not with the
|
||||
/// current fill.
|
||||
#[test]
|
||||
fn pasted_plain_text_takes_the_normal_character_style_fill() {
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
let mut s = session();
|
||||
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
|
||||
run(&mut s, "clipboard.importText", json!({"text": "Plain"}));
|
||||
run(&mut s, "edit.paste", json!({"center": [200, 150]}));
|
||||
assert_eq!(text_of(&pasted(&s)[0]).runs[0].style.fill, Paint::solid(Color::BLACK));
|
||||
let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0));
|
||||
let attrs = crate::cmd::textstyles::char_attrs(&vectorcraft_doc::CharStyle { fill: blue.clone(), ..Default::default() });
|
||||
run(&mut s, "charStyle.setAttrs", json!({"name": "[Normal Character Style]", "attrs": {"fill": attrs["fill"]}}));
|
||||
run(&mut s, "clipboard.importText", json!({"text": "Plain"}));
|
||||
run(&mut s, "edit.paste", json!({"center": [200, 150]}));
|
||||
assert_eq!(text_of(&pasted(&s)[0]).runs[0].style.fill, blue);
|
||||
}
|
||||
|
||||
@@ -677,16 +677,16 @@ fn the_eraser_tip_varies_with_its_modes() {
|
||||
assert!((upright - 195.0).abs() < 0.3, "the upright tip left {upright} pt of the line");
|
||||
let level_tip = left_of_line(json!([]));
|
||||
assert!((level_tip - 180.0).abs() < 0.3, "the level tip left {level_tip} pt of the line");
|
||||
// A 1500 pt tip on Tilt erases 1500 pt across with a mouse, as it does on Fixed.
|
||||
// A 1000 pt tip on Tilt erases 1000 pt across with a mouse, as it does on Fixed.
|
||||
let mut s = session();
|
||||
rect(&mut s, 0.0, 0.0, 4000.0, 4000.0);
|
||||
let big = json!({"points": [[1000, 2000], [3000, 2000]], "size": 1500, "sizeMode": "tilt", "sizeVariation": 10});
|
||||
let big = json!({"points": [[1000, 2000], [3000, 2000]], "size": 1000, "sizeMode": "tilt", "sizeVariation": 10});
|
||||
s.execute("path.eraseRegion", &big).unwrap();
|
||||
let filled =
|
||||
|x: f64, y: f64| paths(&s).iter().any(|(_, pd)| vectorcraft_geom::hit::fill_contains(&pd.to_bezpath(), FillRule::NonZero, Point::new(x, y)));
|
||||
assert_eq!((filled(2000.0, 2740.0), filled(2000.0, 2760.0)), (false, true), "a 1500 pt tip");
|
||||
assert_eq!((filled(2000.0, 2490.0), filled(2000.0, 2510.0)), (false, true), "a 1000 pt tip");
|
||||
// A Size Variation kept while Size is Fixed leaves the size alone.
|
||||
let kept = with(&on_rotation, json!({"sizeMode": "fixed", "sizeVariation": 1000000}));
|
||||
let kept = with(&on_rotation, json!({"sizeMode": "fixed", "sizeVariation": 1000}));
|
||||
assert_eq!(erased(kept, json!([]), &probes), [true, false], "Size on Fixed with a Variation");
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
@@ -2949,6 +2949,116 @@ fn drawing_commands_refuse_a_point_or_pressure_given_as_text() {
|
||||
s.execute("path.eraseRegion", &sized).unwrap();
|
||||
}
|
||||
|
||||
/// The drawing tools' commands refuse a pen pressure outside 0 to 1, a tiltX or tiltY outside -90
|
||||
/// to 90 and a rotation outside 0 to 360, naming the key, and a point array of more than six
|
||||
/// numbers, naming the point; the document, the selection and the undo history stay as they were.
|
||||
/// The ends of each range, null, one tilt axis alone and a mouse point `[x, y]` still draw.
|
||||
#[test]
|
||||
fn pen_values_outside_their_ranges_are_refused() {
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 100.0, 100.0, 100.0, 100.0);
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
let good = [json!([90, 150]), json!([150, 150]), json!([210, 150])];
|
||||
let cmds = [
|
||||
"path.freehand",
|
||||
"brush.freehand",
|
||||
"path.knife",
|
||||
"path.eraseRegion",
|
||||
"path.eraseSegments",
|
||||
"path.smoothRegion",
|
||||
"path.joinScrub",
|
||||
"path.blob",
|
||||
];
|
||||
let pressure = "`pressure` must be from 0 to 1";
|
||||
let tilt_x = "`tiltX` must be from -90 to 90";
|
||||
let tilt_y = "`tiltY` must be from -90 to 90";
|
||||
let rotation = "`rotation` must be from 0 to 360";
|
||||
let entries = "`points[3]` must be an array of at most 6 entries";
|
||||
for cmd in cmds {
|
||||
for (bad, want) in [
|
||||
(json!([150, 150, -0.01]), pressure),
|
||||
(json!([150, 150, 1.5]), pressure),
|
||||
(json!({"x": 150, "y": 150, "pressure": 1e300}), pressure),
|
||||
(json!([150, 150, 0.5, -90.5]), tilt_x),
|
||||
(json!([150, 150, 0.5, 91, 0]), tilt_x),
|
||||
(json!({"x": 150, "y": 150, "tiltX": -1e300}), tilt_x),
|
||||
(json!([150, 150, null, 0, -1e300]), tilt_y),
|
||||
(json!({"x": 150, "y": 150, "tiltY": 90.01}), tilt_y),
|
||||
(json!([150, 150, null, null, null, -1]), rotation),
|
||||
(json!({"x": 150, "y": 150, "rotation": 360.5}), rotation),
|
||||
(json!([150, 150, null, null, null, 720]), rotation),
|
||||
(json!([150, 150, 0.5, 0, 0, 0, 1]), entries),
|
||||
(json!([150, 150, null, null, null, null, null]), entries),
|
||||
] {
|
||||
let points: Vec<_> = good.iter().cloned().chain([bad]).collect();
|
||||
let sel = s.doc().unwrap().selection.clone();
|
||||
refuses_with(&mut s, cmd, &json!({"points": points}), want);
|
||||
assert_eq!(s.doc().unwrap().selection, sel, "{cmd} {points:?} changed the selection");
|
||||
}
|
||||
}
|
||||
for (row, cmd) in ["path.freehand", "brush.freehand", "path.blob", "path.eraseRegion"].into_iter().enumerate() {
|
||||
let y = 300.0 + 50.0 * row as f64;
|
||||
let points = json!([
|
||||
[100, y, 0, -90, 90, 0],
|
||||
[150, y, 1, 90, -90, 360],
|
||||
[200, y, 0.5, null, 30],
|
||||
{"x": 250, "y": y, "tiltX": -45, "pressure": null},
|
||||
[300, y],
|
||||
{"x": 350, "y": y, "rotation": 359.99},
|
||||
]);
|
||||
s.execute(cmd, &json!({"points": points})).unwrap_or_else(|e| panic!("{cmd}: {e}"));
|
||||
let mouse = json!([[100, y + 20.0], [200, y + 20.0], [300, y + 25.0]]);
|
||||
s.execute(cmd, &json!({"points": mouse})).unwrap_or_else(|e| panic!("{cmd} with mouse points: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// `path.blob` and `path.eraseRegion` refuse a `size` outside 0.1 to 1000 pt and a `sizeVariation`
|
||||
/// outside 0 to 1000 pt, in every `sizeMode` each takes and with it left out, and a `sizeVariation`
|
||||
/// that is not a number with Fixed too; nothing changes. The ends of each range and null still draw.
|
||||
#[test]
|
||||
fn blob_and_eraser_size_and_variation_outside_their_ranges_are_refused() {
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 100.0, 100.0, 100.0, 100.0);
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
let stroke = json!({"points": [[90, 150, 0.2, 30, 0, 45], [150, 150, 0.6, 0, 30, 90], [210, 150, 1, -30, 0, 180]]});
|
||||
let size = "`size` must be from 0.1 to 1000";
|
||||
let variation = "`sizeVariation` must be from 0 to 1000";
|
||||
let blob_modes = [json!(null), json!("fixed"), json!("pressure")];
|
||||
let eraser_modes = [json!(null), json!("fixed"), json!("random"), json!("pressure"), json!("tilt"), json!("bearing"), json!("rotation")];
|
||||
// The Eraser keeps its own message for a negative Size Variation.
|
||||
for (cmd, modes, negative) in
|
||||
[("path.blob", &blob_modes[..], variation), ("path.eraseRegion", &eraser_modes[..], "sizeVariation must be 0 or more")]
|
||||
{
|
||||
for x in [json!(0.09), json!(0), json!(-1), json!(1000.5), json!(1e300)] {
|
||||
let sel = s.doc().unwrap().selection.clone();
|
||||
refuses_with(&mut s, cmd, &with(&stroke, json!({"size": x})), size);
|
||||
assert_eq!(s.doc().unwrap().selection, sel, "{cmd} size {x} changed the selection");
|
||||
}
|
||||
for mode in modes {
|
||||
for (x, want) in [(json!(-0.5), negative), (json!(1000.01), variation), (json!(1e300), variation)] {
|
||||
let sel = s.doc().unwrap().selection.clone();
|
||||
refuses_with(&mut s, cmd, &with(&stroke, json!({"sizeMode": mode, "sizeVariation": x})), want);
|
||||
assert_eq!(s.doc().unwrap().selection, sel, "{cmd} {mode} sizeVariation {x} changed the selection");
|
||||
}
|
||||
let text = json!({"sizeMode": mode, "sizeVariation": "8"});
|
||||
refuses_with(&mut s, cmd, &with(&stroke, text), "`sizeVariation` must be a number, not \"8\"");
|
||||
}
|
||||
}
|
||||
for (row, (cmd, modes)) in [("path.blob", &blob_modes[..]), ("path.eraseRegion", &eraser_modes[..])].into_iter().enumerate() {
|
||||
let y = 300.0 + 100.0 * row as f64;
|
||||
let at = |p: serde_json::Value| with(&json!({"points": [[100, y, 0.2, 30, 0, 0], [200, y, 0.6, 0, 30, 90], [300, y, 1, -30, 0, 360]]}), p);
|
||||
for extra in [json!({"size": 0.1}), json!({"size": 1000}), json!({"size": null, "sizeVariation": null, "sizeMode": null})] {
|
||||
s.execute(cmd, &at(extra.clone())).unwrap_or_else(|e| panic!("{cmd} {extra}: {e}"));
|
||||
}
|
||||
for mode in modes {
|
||||
for x in [0, 1000] {
|
||||
let extra = json!({"sizeMode": mode, "sizeVariation": x});
|
||||
s.execute(cmd, &at(extra.clone())).unwrap_or_else(|e| panic!("{cmd} {extra}: {e}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The Eraser, Path Eraser, Smooth, Join and Blob Brush commands refuse a size, angle, roundness,
|
||||
/// width, radius, fidelity or tolerance given as text or as another value that is not a number, and change
|
||||
/// nothing; null is read as the key left out.
|
||||
|
||||
@@ -2117,6 +2117,35 @@ fn confined_clipboard_svg_refuses_a_linked_image_file_outside_the_read_roots() {
|
||||
assert!(svg.contains(&format!("xlink:href=\"{photo}\"")), "{svg}");
|
||||
}
|
||||
|
||||
/// `clipboard.flavours` and the session's flavors leave out the SVG, and its markup as text, that
|
||||
/// `clipboard.exportSvg` withholds from a confined caller; the PNG is still listed. The SVG is listed
|
||||
/// while its image's pixels are held, and for a caller with no read roots.
|
||||
#[test]
|
||||
fn confined_clipboard_flavours_leave_out_a_withheld_svg() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let away = Folder::new("clip-flavours-away");
|
||||
let home = Folder::new("clip-flavours-home");
|
||||
let photo = away.file("photo.png");
|
||||
write(&photo, &png(60, 30, RED));
|
||||
let mut s = session();
|
||||
let a = place(&mut s, &photo);
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
|
||||
let (text, svg, png) = ("text/plain", "image/svg+xml", "image/png");
|
||||
let listed = |s: &mut Session| confine(roots.as_ref(), || s.execute("clipboard.flavours", &json!({}))).unwrap()["flavours"].clone();
|
||||
assert_eq!(listed(&mut s), json!([text, svg, png]));
|
||||
|
||||
without_pixels(&mut s, a);
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
assert_eq!(listed(&mut s), json!([png]));
|
||||
let made = confine(roots.as_ref(), || s.clipboard_flavours());
|
||||
assert!(made.iter().all(|f| f.mime != svg && f.mime != text), "{:?}", made.iter().map(|f| f.mime).collect::<Vec<_>>());
|
||||
assert_eq!(confine(roots.as_ref(), || s.clipboard_flavour_types()), [png]);
|
||||
assert_eq!(s.execute("clipboard.flavours", &json!({})).unwrap()["flavours"], json!([text, svg, png]));
|
||||
}
|
||||
|
||||
/// A confined caller's SVG with Preserve Editing Capabilities is refused while the stored brush
|
||||
/// library holds an entry that does not read as a brush, or is not a list: the native document
|
||||
/// carries it as it is, and its links cannot be checked. Without Preserve Editing the SVG is written.
|
||||
|
||||
@@ -278,6 +278,35 @@ fn each_copys_shadow_expands_as_the_canvas_draws_it() {
|
||||
assert_eq!(diff, 0, "{diff} pixels differ");
|
||||
}
|
||||
|
||||
/// Each copy of type's Transform effect draws the drop shadow listed before the effect under
|
||||
/// itself, scaled with it, and Expand Appearance keeps those shadows: the type's copy, scaled 200 %
|
||||
/// and moved 80 pt down, has its shadow 40 pt to the right of its letters rather than the type's
|
||||
/// own 20 pt.
|
||||
#[test]
|
||||
fn each_copys_shadow_on_type_expands_as_the_canvas_draws_it() {
|
||||
let mut s = session();
|
||||
let t = run(&mut s, "text.create", json!({"x": 20, "y": 60, "text": "I", "size": 40}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "select.set", json!({"ids": [t]}));
|
||||
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
|
||||
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);
|
||||
if !(0..100u32).any(|y| (0..200u32).any(|x| before.pixel(x, y) == [255, 0, 0, 255])) {
|
||||
eprintln!("skipped: built without a font that draws the type");
|
||||
return;
|
||||
}
|
||||
// The rightmost red pixel of the copy, below the type, and 38 pt right of it the copy's shadow.
|
||||
let red =
|
||||
(100..200u32).flat_map(|y| (0..200u32).map(move |x| (x, y))).filter(|&(x, y)| before.pixel(x, y) == [255, 0, 0, 255]).max_by_key(|p| p.0);
|
||||
let (x, y) = red.expect("the copy");
|
||||
assert_eq!(before.pixel(x + 38, y), [0, 255, 0, 255], "the copy's shadow, 40 pt to the right of ({x}, {y})");
|
||||
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]
|
||||
|
||||
@@ -276,3 +276,61 @@ fn overprint_black_covers_type_gradients_spots_and_groups() {
|
||||
s.execute("edit.colors.overprintBlack", &json!({"includeCmyBlacks": true, "includeSpotBlacks": true})).unwrap();
|
||||
assert!(fill(&s, g) && fill(&s, spot));
|
||||
}
|
||||
|
||||
/// The plate `plate` of `doc`, drawn as Separations Preview draws one plate, as one gray value per
|
||||
/// pixel (0 full ink, 255 none).
|
||||
fn plate(doc: &Document, plate: &str) -> Vec<u8> {
|
||||
let mut r = Renderer::new();
|
||||
r.threads = 0;
|
||||
let seps = vectorcraft_render::proof::ProofSetup { separations: Some(vec![plate.into()]), ..Default::default() };
|
||||
let opts = RenderOptions { background: Some([255, 255, 255, 255]), proof: Some(seps), ..Default::default() };
|
||||
let image = r.render(doc, 100, 100, Affine::IDENTITY, &opts);
|
||||
(0..100 * 100).map(|i| image.pixel(i % 100, i / 100)[0]).collect()
|
||||
}
|
||||
|
||||
/// 3D (Classic) with the shading color Black Overprint puts the shading on the black plate, shows
|
||||
/// it as the cyan darkened, and writes it to PDF as overprinting fills.
|
||||
#[test]
|
||||
fn classic_3d_black_overprint_shades_on_the_black_plate() {
|
||||
let doc = |params: Value| {
|
||||
let mut s = session();
|
||||
rect(&mut s, [30.0, 30.0, 40.0, 40.0], cyan_ink(), None, 0.0);
|
||||
s.execute("effect.apply", &json!({"effect": "threeD.classicExtrude", "item": null, "params": params})).unwrap();
|
||||
s
|
||||
};
|
||||
let over = doc(json!({"surface": "diffuse", "depth": 20, "shadingColor": "blackOverprint"}));
|
||||
let flat = doc(json!({"surface": "none", "depth": 20, "shadingColor": "blackOverprint"}));
|
||||
let black = doc(json!({"surface": "diffuse", "depth": 20}));
|
||||
let (over_doc, flat_doc) = (&over.doc().unwrap().doc, &flat.doc().unwrap().doc);
|
||||
let inked = |p: &[u8]| p.iter().filter(|v| **v < 250).count();
|
||||
assert!(inked(&plate(over_doc, "Cyan")) > 1000, "the solid is drawn");
|
||||
assert!(inked(&plate(over_doc, "Black")) > 100, "the shading is on the black plate");
|
||||
assert_eq!(inked(&plate(flat_doc, "Black")), 0, "No Shading adds no black");
|
||||
// On screen a shaded face is the cyan darkened, not gray: the black multiplies the cyan.
|
||||
let image = |d: &Document| {
|
||||
let mut r = Renderer::new();
|
||||
r.threads = 0;
|
||||
let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() };
|
||||
r.render(d, 100, 100, Affine::IDENTITY, &opts)
|
||||
};
|
||||
let (shaded, unshaded) = (image(over_doc), image(flat_doc));
|
||||
let mut darker = 0;
|
||||
for (x, y) in (0..100u32).flat_map(|y| (0..100u32).map(move |x| (x, y))) {
|
||||
let (s, u) = (shaded.pixel(x, y), unshaded.pixel(x, y));
|
||||
// Inside the solid (no white mixed in at an antialiased edge) where the shading darkens it.
|
||||
if u[0] < 30 && (s[1] as i32) + 20 < u[1] as i32 {
|
||||
darker += 1;
|
||||
assert!(s[2] as i32 > s[0] as i32 + 20, "a shaded face keeps its cyan at ({x}, {y}): {s:?}");
|
||||
}
|
||||
}
|
||||
assert!(darker > 100, "the faces turned from the light are darker");
|
||||
|
||||
let pdf_overprints = |s: &mut Session| {
|
||||
let v = s.execute("document.exportPdf", &json!({"compression": {"compressText": false}, "preserveEditing": false})).unwrap();
|
||||
let bytes = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap();
|
||||
String::from_utf8_lossy(&bytes).matches("/OP true/op true/OPM 1").count()
|
||||
};
|
||||
let (mut over, mut black) = (over, black);
|
||||
assert!(pdf_overprints(&mut over) > 0, "the black is written overprinting");
|
||||
assert_eq!(pdf_overprints(&mut black), 0);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Clicks, hovers and marquees with the selection tools leave out the area that raster effects
|
||||
//! (drop shadows, glows, blurs) paint beyond an object: there they reach the object under the
|
||||
//! effect, or nothing.
|
||||
//! effect, or nothing. Clicks and marquees take art where its geometry effects draw it.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::NodeId;
|
||||
@@ -391,3 +391,107 @@ fn group_selection_hover_over_a_drop_shadow_marks_nothing() {
|
||||
}
|
||||
assert_eq!(press(&mut s, "groupSelection", (110.0, 50.0), (110.0, 50.0), Mods::default()), [b]);
|
||||
}
|
||||
|
||||
/// A rectangle that a Transform effect moves 100 pt to the right is selected by a click and by a
|
||||
/// marquee where it is drawn, and not at its own place, which it no longer paints. The same holds
|
||||
/// for a group whose own Transform effect moves it.
|
||||
#[test]
|
||||
fn a_click_and_a_marquee_select_art_where_its_transform_effect_draws_it() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 20.0, 20.0, 40.0, 40.0, "#ff0000");
|
||||
run(&mut s, "effect.apply", json!({"effect": "distort.transform", "ids": [a.0], "params": {"moveH": 100}, "item": null}));
|
||||
assert_eq!(pixel(&s, 140, 40), [255, 0, 0, 255], "drawn where it moved");
|
||||
assert_eq!(pixel(&s, 40, 40), WHITE, "not drawn at its own place");
|
||||
run(&mut s, "select.none", json!({}));
|
||||
assert!(click(&mut s, 40.0, 40.0).is_empty());
|
||||
assert_eq!(click(&mut s, 140.0, 40.0), [a]);
|
||||
assert_eq!(press(&mut s, "selection", (110.0, 10.0), (130.0, 30.0), Mods::default()), [a], "a marquee across its drawn corner");
|
||||
run(&mut s, "select.none", json!({}));
|
||||
assert!(press(&mut s, "selection", (10.0, 10.0), (30.0, 30.0), Mods::default()).is_empty(), "a marquee across its own corner");
|
||||
|
||||
let mut s = session();
|
||||
let b = rect(&mut s, 20.0, 120.0, 40.0, 40.0, "#0000ff");
|
||||
run(&mut s, "select.set", json!({"ids": [b.0]}));
|
||||
let g = id_of(&run(&mut s, "object.group", json!({})));
|
||||
run(&mut s, "effect.apply", json!({"effect": "distort.transform", "ids": [g.0], "params": {"moveH": 100}, "item": null}));
|
||||
assert_eq!(pixel(&s, 140, 140), BLUE, "the group drawn where it moved");
|
||||
run(&mut s, "select.none", json!({}));
|
||||
assert!(click(&mut s, 40.0, 140.0).is_empty());
|
||||
assert_eq!(click(&mut s, 140.0, 140.0), [g]);
|
||||
assert_eq!(press(&mut s, "selection", (110.0, 110.0), (130.0, 130.0), Mods::default()), [g]);
|
||||
run(&mut s, "select.none", json!({}));
|
||||
assert!(press(&mut s, "selection", (10.0, 110.0), (30.0, 130.0), Mods::default()).is_empty());
|
||||
}
|
||||
|
||||
/// A group's own fill paints its member's shape before the member's own Transform effect moves the
|
||||
/// member: a click there selects the group, and a click on the moved member selects it too. A
|
||||
/// Direct Selection marquee takes the group there and the member where it moved.
|
||||
#[test]
|
||||
fn a_click_selects_a_group_where_its_own_fill_paints_a_moved_member() {
|
||||
let mut s = session();
|
||||
let b = rect(&mut s, 20.0, 120.0, 40.0, 40.0, "#0000ff");
|
||||
run(&mut s, "select.set", json!({"ids": [b.0]}));
|
||||
let g = id_of(&run(&mut s, "object.group", json!({})));
|
||||
run(&mut s, "appearance.addFill", json!({}));
|
||||
run(&mut s, "appearance.setActiveItem", json!({"index": 0}));
|
||||
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
|
||||
run(&mut s, "effect.apply", json!({"effect": "distort.transform", "ids": [b.0], "params": {"moveH": 100}, "item": null}));
|
||||
assert_eq!(pixel(&s, 40, 140), [255, 0, 0, 255], "the group's fill at the member's own place");
|
||||
assert_eq!(pixel(&s, 140, 140), BLUE, "the member where it moved");
|
||||
run(&mut s, "select.none", json!({}));
|
||||
assert_eq!(click(&mut s, 40.0, 140.0), [g]);
|
||||
run(&mut s, "select.none", json!({}));
|
||||
assert_eq!(click(&mut s, 140.0, 140.0), [g]);
|
||||
// A marquee across the edge of the group's fill takes the group, and one across the moved
|
||||
// member's edge takes the member.
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert_eq!(vectorcraft_doc::hit::marquee(doc, Rect::new(10.0, 130.0, 30.0, 150.0), None, true), [g]);
|
||||
assert_eq!(vectorcraft_doc::hit::marquee(doc, Rect::new(110.0, 130.0, 130.0, 150.0), None, true), [b]);
|
||||
}
|
||||
|
||||
/// An inner group's own fill paints its member's shape before the member's own Transform effect
|
||||
/// moves the member, and so does an outer group's own fill around it: a Direct Selection marquee
|
||||
/// across the edge of those fills takes both groups, and one across the moved member takes it.
|
||||
#[test]
|
||||
fn a_marquee_takes_an_inner_groups_own_fill_inside_a_painted_group() {
|
||||
let mut s = session();
|
||||
let b = rect(&mut s, 20.0, 120.0, 40.0, 40.0, "#0000ff");
|
||||
run(&mut s, "select.set", json!({"ids": [b.0]}));
|
||||
let g = id_of(&run(&mut s, "object.group", json!({})));
|
||||
run(&mut s, "appearance.addFill", json!({}));
|
||||
run(&mut s, "appearance.setActiveItem", json!({"index": 0}));
|
||||
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
|
||||
run(&mut s, "effect.apply", json!({"effect": "distort.transform", "ids": [b.0], "params": {"moveV": -100}, "item": null}));
|
||||
run(&mut s, "select.set", json!({"ids": [g.0]}));
|
||||
let o = id_of(&run(&mut s, "object.group", json!({})));
|
||||
run(&mut s, "appearance.addFill", json!({}));
|
||||
run(&mut s, "appearance.setActiveItem", json!({"index": 0}));
|
||||
run(&mut s, "paint.setFill", json!({"color": "#00ff00"}));
|
||||
assert_eq!(pixel(&s, 40, 140), [0, 255, 0, 255], "the outer group's fill at the member's own place");
|
||||
assert_eq!(pixel(&s, 40, 40), BLUE, "the member where it moved");
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert_eq!(vectorcraft_doc::hit::marquee(doc, Rect::new(10.0, 130.0, 30.0, 150.0), None, true), [o, g]);
|
||||
assert_eq!(vectorcraft_doc::hit::marquee(doc, Rect::new(10.0, 30.0, 30.0, 50.0), None, true), [b]);
|
||||
}
|
||||
|
||||
/// A group's own fill paints its member's shape before the member's own Transform effect moves
|
||||
/// the member, and so does its layer's own fill around it: a Direct Selection marquee across the
|
||||
/// edge of the group's fill takes the group, and one across the moved member takes it.
|
||||
#[test]
|
||||
fn a_marquee_takes_a_groups_own_fill_inside_a_painted_layer() {
|
||||
let mut s = session();
|
||||
let b = rect(&mut s, 20.0, 120.0, 40.0, 40.0, "#0000ff");
|
||||
run(&mut s, "select.set", json!({"ids": [b.0]}));
|
||||
let g = id_of(&run(&mut s, "object.group", json!({})));
|
||||
run(&mut s, "appearance.addFill", json!({}));
|
||||
run(&mut s, "appearance.setActiveItem", json!({"index": 0}));
|
||||
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
|
||||
run(&mut s, "effect.apply", json!({"effect": "distort.transform", "ids": [b.0], "params": {"moveV": -100}, "item": null}));
|
||||
let l = s.doc().unwrap().doc.layers[0].id;
|
||||
run(&mut s, "appearance.addFill", json!({"ids": [l.0]}));
|
||||
assert!(!s.doc().unwrap().doc.layers[0].appearance.items.is_empty(), "the layer has a fill of its own");
|
||||
assert_eq!(pixel(&s, 40, 40), BLUE, "the member where it moved");
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert_eq!(vectorcraft_doc::hit::marquee(doc, Rect::new(10.0, 130.0, 30.0, 150.0), None, true), [g]);
|
||||
assert_eq!(vectorcraft_doc::hit::marquee(doc, Rect::new(10.0, 30.0, 30.0, 50.0), None, true), [b]);
|
||||
}
|
||||
|
||||
@@ -262,8 +262,8 @@ fn document_color_mode_converts_effect_colors() {
|
||||
assert_eq!((object(&s), style(&s)), before);
|
||||
}
|
||||
|
||||
/// Document Color Mode converts the series paints and label styles a graph keeps, so a graph drawn
|
||||
/// again after the switch paints its series and labels in the new mode.
|
||||
/// Document Color Mode converts the series paints, label styles and line rows a graph keeps, so a
|
||||
/// graph drawn again after the switch paints its series, labels and lines in the new mode.
|
||||
#[test]
|
||||
fn document_color_mode_converts_the_paints_a_graph_keeps() {
|
||||
let mut s = session();
|
||||
@@ -284,22 +284,26 @@ fn document_color_mode_converts_the_paints_a_graph_keeps() {
|
||||
}
|
||||
// A fill row on the label, which the graph keeps with the label's rows.
|
||||
run(&mut s, "appearance.addFill", json!({"ids": [label.0]}));
|
||||
// A stroke on an axis line, which the graph keeps for its axis lines and tick marks.
|
||||
let line = part(&s, "Axes").children().unwrap().iter().find(|c| matches!(c.kind, vectorcraft_doc::NodeKind::Path { .. })).unwrap().id;
|
||||
run(&mut s, "paint.setStroke", json!({"color": "#ff0000", "ids": [line.0]}));
|
||||
let kept = |s: &Session| -> Vec<Color> {
|
||||
let g = doc(s).node(id).unwrap().extras().graph.as_deref().unwrap().clone();
|
||||
let rows = [&g.label_styles.values_rows, &g.label_styles.categories_rows, &g.label_styles.legend_rows];
|
||||
let rows: Vec<Color> = rows.into_iter().flatten().filter_map(|r| r.paint.fill.as_ref()?.color()).collect();
|
||||
let lines = g.label_styles.axis_rows.iter().filter_map(|r| r.paint.stroke.as_ref()?.color());
|
||||
let labels = [g.label_styles.values, g.label_styles.categories, g.label_styles.legend];
|
||||
let labels = labels.into_iter().flatten().map(|st| st.fill.color().unwrap());
|
||||
g.series_paints.iter().filter_map(|p| p.fill.as_ref()?.color()).chain(labels).chain(rows).collect()
|
||||
g.series_paints.iter().filter_map(|p| p.fill.as_ref()?.color()).chain(labels).chain(rows).chain(lines).collect()
|
||||
};
|
||||
let before = kept(&s);
|
||||
assert_eq!(before, [Color::rgb(1.0, 0.0, 0.0); 3]);
|
||||
assert_eq!(before, [Color::rgb(1.0, 0.0, 0.0); 4]);
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
|
||||
run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"}));
|
||||
let cmyk = first_fill(doc(&s).node(red).unwrap());
|
||||
assert!(matches!(cmyk, Color::Cmyk { .. }), "{cmyk:?}");
|
||||
assert_eq!(kept(&s), [cmyk; 3]);
|
||||
assert_eq!(kept(&s), [cmyk; 4]);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
// Drawn again from new data, the series keeps the converted color.
|
||||
run(&mut s, "graph.setData", json!({"id": id.0, "rows": [[2, 3], [4, 5]]}));
|
||||
|
||||
@@ -4027,3 +4027,35 @@ fn apply_fill_to_stroke_with_characters_selected_changes_only_them() {
|
||||
let labels = undo_labels(&s);
|
||||
assert_eq!((labels.len(), labels.last().map(String::as_str)), (steps + 1, Some("Apply Fill to Stroke")));
|
||||
}
|
||||
|
||||
/// Redefines `[Normal Character Style]` with `fill` (`charStyle.setAttrs`).
|
||||
fn set_normal_fill(s: &mut Session, fill: vectorcraft_color::Paint) {
|
||||
let attrs = crate::cmd::textstyles::char_attrs(&CharStyle { fill, ..CharStyle::default() });
|
||||
s.execute("charStyle.setAttrs", &json!({"name": "[Normal Character Style]", "attrs": {"fill": attrs["fill"]}})).unwrap();
|
||||
}
|
||||
|
||||
/// #7975: type the Type tool starts is filled as [Normal Character Style] is, black unless it was
|
||||
/// redefined, not with the current fill a shape left behind.
|
||||
#[test]
|
||||
fn new_type_takes_the_normal_character_style_fill_not_the_current_fill() {
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
let mut s = session();
|
||||
let v = ViewInfo::default();
|
||||
s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 60, "height": 60})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
assert_eq!(s.paint.fill, Paint::solid(Color::rgb(1.0, 0.0, 0.0)), "the current fill is red");
|
||||
s.select_tool("type", v).unwrap();
|
||||
click(&mut s, 200.0, 200.0);
|
||||
s.tool_text("Black", v).unwrap();
|
||||
let id = s.doc().unwrap().selection.objects[0];
|
||||
assert_eq!(obj(&s, id).runs[0].style.fill, Paint::solid(Color::BLACK));
|
||||
// A redefined [Normal Character Style] gives new type its fill.
|
||||
let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0));
|
||||
set_normal_fill(&mut s, blue.clone());
|
||||
let made = s.execute("text.create", &json!({"x": 100, "y": 300, "text": "Blue"})).unwrap();
|
||||
assert_eq!(obj(&s, NodeId(made["id"].as_u64().unwrap())).runs[0].style.fill, blue);
|
||||
// A color given to the command still wins.
|
||||
let made = s.execute("text.create", &json!({"x": 100, "y": 400, "text": "Green", "color": "#00ff00"})).unwrap();
|
||||
assert_eq!(obj(&s, NodeId(made["id"].as_u64().unwrap())).runs[0].style.fill, Paint::solid(Color::rgb(0.0, 1.0, 0.0)));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user