Merge origin/main into feat/cutover-remaining-codecs

This commit is contained in:
FredApps
2026-11-16 01:57:11 +01:00
229 changed files with 13142 additions and 1517 deletions
+19 -2
View File
@@ -446,7 +446,7 @@ pub(crate) fn rows_per_target(d: &Document, of: Option<NodeId>, ids: &[NodeId],
}
/// Whether the `target` param asks for the contents of groups and layers (see the module docs).
fn targets_contents(p: &Value) -> Result<bool> {
pub(crate) fn targets_contents(p: &Value) -> Result<bool> {
match p.get("target") {
None | Some(Value::Null) => Ok(false),
Some(v) => match v.as_str() {
@@ -508,6 +508,20 @@ pub(crate) fn drop_design_art(d: &Document, mut ids: Vec<NodeId>) -> Vec<NodeId>
ids
}
/// [`drop_design_art`] for an edit of the `item` rows of `ids` (`fill`: fill rows): an explicit `item` that a design's
/// art has no row of that kind for is still an error of `cmd`, as on any other object.
pub(crate) fn drop_design_art_rows(s: &Session, ids: Vec<NodeId>, item: ItemTarget, fill: bool, cmd: &str) -> Result<Vec<NodeId>> {
let d = &s.doc()?.doc;
for (id, it) in ids.iter().zip(item.per_target(s, &ids)) {
if let (Some(it), Some(n)) = (it, d.node(*id))
&& super::graph::is_design_art(d, *id)
{
it.resolve(&n.appearance, fill, cmd)?;
}
}
Ok(drop_design_art(d, ids))
}
/// The outermost art of graph designs drawn in graph series inside `roots`: the objects directly in a series group that
/// [`super::graph::is_design_art`] accepts.
pub(crate) fn design_art_in(d: &Document, roots: &[NodeId]) -> Vec<NodeId> {
@@ -720,7 +734,10 @@ pub(crate) fn edits_stroke(s: &Session, p: &Value, item: ItemTarget, default: bo
let holder = match reference_of(s, p, item, cmd)? {
Some(of) => Some(of),
None => {
let ids = drop_design_art(d, appearance_targets(s, p)?);
let all = appearance_targets(s, p)?;
// The art of a graph design is left out, unless it is all there is: the item is then a row of that art.
let kept = drop_design_art(d, all.clone());
let ids = if kept.is_empty() { all } else { kept };
ids.get(item.anchor(s, &ids)).copied()
}
};
+3 -3
View File
@@ -190,7 +190,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Symbols",
[],
None,
"{} → {symbols: [{name, instances, size: [w,h], registration: 0..8, exportType: movieClip|graphic, nineSlice, type: static|dynamic}], current}",
"{} → {symbols: [{name, instances, size: [w,h], registration: 0..8, exportType: movieClip|graphic, nineSlice, type: static|dynamic, alignToPixelGrid: bool}], current}",
has_doc,
symbol_list
),
@@ -199,7 +199,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New Symbol…",
[],
None,
"{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type)} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions → {name, id, registration, exportType, nineSlice, type}",
"{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type), alignToPixelGrid?: bool (default false; Symbol Options › Align to Pixel Grid)} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions; alignToPixelGrid keeps the symbol's instances on the pixel grid as symbol.options describes → {name, id, registration, exportType, nineSlice, type, alignToPixelGrid}",
has_selection,
symbol_new
),
@@ -208,7 +208,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Symbol Options…",
[],
None,
"{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic} rename a symbol (its instances and the graphics mapped onto 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions in from each edge, each -16..16, with left + right < 1 and top + bottom < 1) and Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes); default name: current → {name, registration, exportType, nineSlice, type}",
"{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic, alignToPixelGrid?: bool} rename a symbol (its instances and the graphics mapped onto 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions in from each edge, each -16..16, with left + right < 1 and top + bottom < 1), Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes) and Align to Pixel Grid (on: the horizontal and vertical straight segments of the paths in the symbol's art snap to whole points, or half points for an odd centered stroke, at the symbol's natural size, its stroke weights become whole points, and every instance placed at that size, reflected across one axis or not, moves to whole points and goes back to them after each move; a scaled, rotated (a half turn included) or sheared instance, and an instance in another symbol's art, is left where it is; the art snaps again after it is edited); alignToPixelGrid alone with the value the symbol already has changes nothing and adds no undo step; default name: current → {name, registration, exportType, nineSlice, type, alignToPixelGrid}",
has_doc,
symbol_options
),
+42 -9
View File
@@ -69,6 +69,15 @@ fn nine_slice_param(p: &Value, cmd: &str, current: Option<SymbolNineSlice>) -> R
})
}
/// `alignToPixelGrid` (Symbol Options › Align to Pixel Grid): `None` when it is not given; any
/// value other than true or false, null included, is an error.
fn pixel_grid_param(p: &Value, cmd: &str) -> Result<Option<bool>> {
match p.get("alignToPixelGrid") {
None => Ok(None),
Some(v) => v.as_bool().map(Some).ok_or_else(|| bad(cmd, "alignToPixelGrid must be true or false")),
}
}
fn nine_slice_json(d: &Document, name: &str) -> Value {
d.symbol_nine_slice(name).map_or(Value::Null, SymbolNineSlice::to_value)
}
@@ -187,6 +196,7 @@ pub(super) fn symbol_list(s: &mut Session, _: &Value) -> Result<Value> {
"exportType": d.symbol_export_type(&sym.name).id(),
"nineSlice": nine_slice_json(d, &sym.name),
"type": type_id(sym.dynamic),
"alignToPixelGrid": d.symbol_pixel_aligned(&sym.name),
})
})
.collect();
@@ -239,6 +249,7 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result<Value> {
let export = export_type_param(p, C)?.unwrap_or_default();
let nine = nine_slice_param(p, C, None)?.flatten();
let dynamic = type_param(p, C)?.unwrap_or(false);
let pixel = pixel_grid_param(p, C)?.unwrap_or(false);
// Keep the art where it was: the geometric centre stays at `c`, whatever the registration is.
let place = place_xf(c + reg.offset_from_center(size.0, size.1), size, reg);
let id = s.edit("New Symbol", |d, sel| {
@@ -249,6 +260,7 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result<Value> {
d.set_symbol_registration(&name, reg);
d.set_symbol_export_type(&name, export);
d.set_symbol_nine_slice(&name, nine);
d.set_symbol_pixel_aligned(&name, pixel);
let id = instance_in_place(d, &ids, &name, place)?;
sel.set([id]);
Ok(id)
@@ -260,6 +272,7 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result<Value> {
"exportType": export.id(),
"nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value),
"type": type_id(dynamic),
"alignToPixelGrid": pixel,
}))
}
@@ -270,9 +283,15 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> {
let reg = registration_param(p, C)?;
let nine = nine_slice_param(p, C, s.doc()?.doc.symbol_nine_slice(&name))?;
let dynamic = type_param(p, C)?;
let pixel = pixel_grid_param(p, C)?;
let new_name = str_param(p, "newName").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string);
if new_name.is_none() && export.is_none() && reg.is_none() && nine.is_none() && dynamic.is_none() {
return Err(bad(C, "pass newName, registration, exportType, nineSlice and/or type"));
match pixel {
None => return Err(bad(C, "pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid")),
// Align to Pixel Grid alone, already as asked: nothing changes and no undo step is added.
Some(on) if on == s.doc()?.doc.symbol_pixel_aligned(&name) => return Ok(options_json(&s.doc()?.doc, &name)),
Some(_) => {}
}
}
if let Some(ref n) = new_name
&& n != &name
@@ -324,6 +343,7 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> {
d.rename_symbol_registration(&name, n);
d.rename_symbol_export_type(&name, n);
d.rename_symbol_nine_slice(&name, n);
d.rename_symbol_pixel_aligned(&name, n);
if d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str) == Some(name.as_str()) {
d.unknown.insert(CURRENT_SYMBOL.into(), json!(n));
}
@@ -352,16 +372,26 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> {
sym.dynamic = dynamic;
fit_overrides(d, &instances_of(d, Some(&final_name)));
}
// Turning it on snaps the art and the instances at actual size when the edit ends
// (`object::refresh_pixel_aligned`).
if let Some(on) = pixel {
d.set_symbol_pixel_aligned(&final_name, on);
}
Ok(())
})?;
let d = &s.doc()?.doc;
Ok(json!({
"name": final_name,
"registration": d.symbol_registration(&final_name).0,
"exportType": d.symbol_export_type(&final_name).id(),
"nineSlice": nine_slice_json(d, &final_name),
"type": type_id(d.symbols.iter().any(|x| x.name == final_name && x.dynamic)),
}))
Ok(options_json(&s.doc()?.doc, &final_name))
}
/// What `symbol.options` answers for symbol `name`.
fn options_json(d: &Document, name: &str) -> Value {
json!({
"name": name,
"registration": d.symbol_registration(name).0,
"exportType": d.symbol_export_type(name).id(),
"nineSlice": nine_slice_json(d, name),
"type": type_id(d.symbols.iter().any(|x| x.name == name && x.dynamic)),
"alignToPixelGrid": d.symbol_pixel_aligned(name),
})
}
fn resolve_symbol(d: &Document, p: &Value, cmd: &str) -> Result<String> {
@@ -702,6 +732,7 @@ pub(super) fn symbol_delete(s: &mut Session, p: &Value) -> Result<Value> {
d.set_symbol_registration(name, SymbolRegistration::CENTER);
d.clear_symbol_export_type(name);
d.set_symbol_nine_slice(name, None);
d.set_symbol_pixel_aligned(name, false);
if d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str) == Some(name.as_str()) {
d.unknown.remove(CURRENT_SYMBOL);
}
@@ -725,6 +756,7 @@ pub(super) fn symbol_duplicate(s: &mut Session, p: &Value) -> Result<Value> {
let reg = d.symbol_registration(&name);
let export = d.symbol_export_type(&name);
let nine = d.symbol_nine_slice(&name);
let pixel = d.symbol_pixel_aligned(&name);
s.edit("Duplicate Symbol", |d, _| {
let art = d.reid(&sym.art);
d.symbols.push(Symbol { dynamic: sym.dynamic, name: new.clone(), art: Arc::new(art) });
@@ -732,6 +764,7 @@ pub(super) fn symbol_duplicate(s: &mut Session, p: &Value) -> Result<Value> {
d.set_symbol_registration(&new, reg);
d.set_symbol_export_type(&new, export);
d.set_symbol_nine_slice(&new, nine);
d.set_symbol_pixel_aligned(&new, pixel);
Ok(())
})?;
Ok(json!({ "name": new, "registration": reg.0, "exportType": export.id(), "nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value) }))
+2 -2
View File
@@ -126,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Live Paint Bucket (Stroke)",
[],
None,
"{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), scope?: \"one\" (default: the edge alone) | \"connected\" (a double-click: also each edge joined to it, end to end, through edges that draw with stroke paint match) | \"samePaint\" (a triple-click: also every edge of the group that draws with stroke paint match), match?: paint (as the document stores it; scope connected or samePaint only; default: the stroke paint the edge draws with; an edge draws with the paint of its topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully transparent or has no such stroke), through?: [id…] (scope connected only; at most 4096 edges counted as drawing with stroke paint match whatever they draw with, such as the edge a double-click's first click painted), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point, skipping hidden edges: each edge reached has its strokes replaced by one stroke with the paint and width, shown, fully opaque and blending normally, in the place of its topmost stroke and with the dashes, caps and arrowheads of its topmost shown stroke (a new stroke above the fills when it has none; none leaves one stroke of none), and its fills stay as they are; when every edge it reaches already has only that one stroke (at any width for none), nothing changes (no undo step, and the recent colors stay as they are) → {group, edge, count (edges reached)}",
"{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), scope?: \"one\" (default: the edge alone) | \"connected\" (a double-click: also each edge joined to it, end to end, through edges that draw with stroke paint match) | \"samePaint\" (a triple-click: also every edge of the group that draws with stroke paint match), match?: paint (as the document stores it; scope connected or samePaint only; default: the stroke paint the edge draws with; an edge draws with the paint of its topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully transparent or has no such stroke), through?: [id…] (scope connected only; at most 4096 of the group's edges, each given once, counted as drawing with stroke paint match whatever they draw with, such as another edge a double-click's clicks painted; any other id is an error), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point, skipping hidden edges: each edge reached has its strokes replaced by one stroke with the paint and width, shown, fully opaque and blending normally, in the place of its topmost stroke and with the dashes, caps and arrowheads of its topmost shown stroke (a new stroke above the fills when it has none; none leaves one stroke of none), and its fills stay as they are; when every edge it reaches already has only that one stroke (at any width for none), nothing changes (no undo step, and the recent colors stay as they are) → {group, edge, count (edges reached)}",
has_doc,
lp_stroke_edge
),
@@ -144,7 +144,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Make",
["Object", "Image Trace"],
None,
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\" (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\" group under the paths holds 1.5 px strokes along the edges two filled paths share, in the color of the lower path, so that no light hairline shows along those edges; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}",
has_selection_or_ids,
|s, p| trace_make(s, p, false)
),
@@ -580,6 +580,12 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
let (eid, count, changed) = {
let d = &s.doc()?.doc;
let n = d.node(g).filter(|n| is_live_paint(n)).ok_or_else(|| bad(C, format!("{g} is not a Live Paint group")))?;
// Each id in `through` is an edge of the group, given once.
let group_edges: std::collections::HashSet<NodeId> = b::edges(n).iter().map(|e| e.id).collect();
let mut seen = std::collections::HashSet::new();
if let Some(id) = through.iter().find(|id| !group_edges.contains(id) || !seen.insert(**id)) {
return Err(bad(C, format!("through: {id} is not an edge of {g}, or is given twice")));
}
let start = b::visible_edge_near(n, pt, tol).ok_or_else(|| EngineError::Other("no Live Paint edge near that point".into()))?;
let eid = start.id;
let like = like.unwrap_or_else(|| b::lp_stroke_paint(start));
+8 -1
View File
@@ -766,6 +766,8 @@ pub struct SymbolOptions {
pub export_type: SymbolExportType,
/// 9-slice guides (`None`: 9-slice scaling off).
pub nine_slice: Option<SymbolNineSlice>,
/// Align to Pixel Grid.
pub pixel_aligned: bool,
}
impl SymbolOptions {
@@ -776,6 +778,7 @@ impl SymbolOptions {
registration: d.symbol_registration(name),
export_type: d.symbol_export_type(name),
nine_slice: d.symbol_nine_slice(name),
pixel_aligned: d.symbol_pixel_aligned(name),
}
}
@@ -785,6 +788,7 @@ impl SymbolOptions {
d.set_symbol_registration(name, self.registration);
d.set_symbol_export_type(name, self.export_type);
d.set_symbol_nine_slice(name, self.nine_slice);
d.set_symbol_pixel_aligned(name, self.pixel_aligned);
}
}
@@ -1035,10 +1039,13 @@ impl Imported {
self.relink.renames.entry(r).or_default().insert(from.to_string(), to.clone());
}
}
/// Point a pasted copy at the document's resources.
/// Point a pasted copy at the document's resources. A pie's legend labels in wedges that now show a color of the
/// other darkness take the contrast a redraw sets there.
pub(crate) fn apply(&self, n: &mut Node) {
if self.relinks {
let shades = super::super::graph::wedge_shades(n);
self.relink.node(n);
super::super::graph::follow_wedge_shades(n, &shades);
}
}
}
+12 -1
View File
@@ -221,6 +221,8 @@ pub(crate) struct Recolor<'a> {
patterns: HashMap<String, Option<String>>,
new_images: Vec<(String, ImageBlob)>,
new_patterns: Vec<PatternDef>,
/// Objects inside the recolored ones that keep their colors, with everything inside them.
skip: HashSet<NodeId>,
changed: usize,
}
@@ -236,6 +238,7 @@ impl<'a> Recolor<'a> {
patterns: HashMap::new(),
new_images: vec![],
new_patterns: vec![],
skip: HashSet::new(),
changed: 0,
}
}
@@ -254,7 +257,7 @@ impl<'a> Recolor<'a> {
/// A pass that maps colors as this one does, with nothing recolored yet.
fn again(&self) -> Self {
Self { links: self.links, gray_images: self.gray_images, remake: self.remake, ..Self::new(self.scope, self.f) }
Self { links: self.links, gray_images: self.gray_images, remake: self.remake, skip: self.skip.clone(), ..Self::new(self.scope, self.f) }
}
/// The entries of `objects` (ids, each with a flag) whose object this pass would change, other
@@ -440,12 +443,20 @@ impl ColorVisitor for Visit<'_, '_> {
fn image(&mut self, key: &str) -> Option<String> {
self.pass.image(self.d, key)
}
fn enters(&mut self, n: &Node) -> bool {
!self.pass.skip.contains(&n.id)
}
}
pub(crate) fn recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color) -> Result<Value> {
run_pass(s, p, cmd, label, Recolor::new(Scope::of(p, cmd)?, f))
}
/// [`recolor`] that leaves the objects `skip` inside the recolored ones, and everything inside them, as they are.
pub(crate) fn recolor_except(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color, skip: HashSet<NodeId>) -> Result<Value> {
run_pass(s, p, cmd, label, Recolor { skip, ..Recolor::new(Scope::of(p, cmd)?, f) })
}
/// [`recolor`] where `f` gives gray colors, so embedded images are stored with one gray channel.
fn recolor_gray(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color) -> Result<Value> {
run_pass(s, p, cmd, label, Recolor { gray_images: true, ..Recolor::new(Scope::of(p, cmd)?, f) })
+21 -3
View File
@@ -26,7 +26,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Ellipse",
[],
None,
"{x, y, width, height, rotation?: deg clockwise about the centre (0: upright)} → {id}",
"{x, y, width, height, rotation?: deg clockwise about the centre (0: upright), anchors=4 (2–1000: smooth anchors spaced evenly by angle; any count but 4 draws a plain path, not a live ellipse)} → {id}",
has_doc,
ellipse
),
@@ -362,10 +362,28 @@ fn rectangle(s: &mut Session, p: &Value) -> Result<Value> {
add_art_turned(s, label, path_kind(live.to_path(), Some(live)), f64_or(p, "rotation", 0.0))
}
/// The most anchors `shape.ellipse` draws, as many as a polygon's sides.
const MAX_ELLIPSE_ANCHORS: u64 = 1000;
fn ellipse(s: &mut Session, p: &Value) -> Result<Value> {
let r = rect_of(p, "shape.ellipse")?;
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: rect_transform(r, p, "shape.ellipse")? };
add_art_turned(s, "Ellipse", path_kind(live.to_path(), Some(live)), f64_or(p, "rotation", 0.0))
// One message for every number that is not a whole count in range (a fraction, a negative,
// 0, 1, too many); a value that is not a number gets `number_or`'s.
let (key, min, max) = ("anchors", 2, MAX_ELLIPSE_ANCHORS);
let n = number_or(p, key, 4.0, "shape.ellipse")?;
if n.fract() != 0.0 || !(min as f64..=max as f64).contains(&n) {
return Err(bad("shape.ellipse", format!("`{key}` must be a whole number between {min} and {max} (got {n})")));
}
let x = n as u64;
let xf = rect_transform(r, p, "shape.ellipse")?;
let rotation = f64_or(p, "rotation", 0.0);
if x != 4 {
// Another count is a plain path: a live ellipse always has 4 anchors.
let path = shapes::ellipse_with_anchors(Rect::new(0.0, 0.0, r.width(), r.height()), x as u32).transformed(xf);
return add_art_turned(s, "Ellipse", path_kind(path, None), rotation);
}
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf };
add_art_turned(s, "Ellipse", path_kind(live.to_path(), Some(live)), rotation)
}
/// The whole-number count `p` gives for `key` (`5` or `5.0`), or `default` when it is left out or
+6 -7
View File
@@ -631,13 +631,12 @@ impl LiquifyStroke {
}
let msg = (!ids.is_empty()).then(|| {
let n = ids.len();
format!(
"{} left {n} object{} under the brush as {} ({}): it reshapes paths only",
self.prm.kind.label(),
if n == 1 { "" } else { "s" },
if n == 1 { "it was" } else { "they were" },
kinds.join(", ")
)
let (tool, kinds) = (self.prm.kind.label(), kinds.join(", "));
if n == 1 {
format!("{tool} left {n} object under the brush as it was ({kinds}): it reshapes paths only")
} else {
format!("{tool} left {n} objects under the brush as they were ({kinds}): it reshapes paths only")
}
});
(ids, msg)
}
+27
View File
@@ -270,6 +270,33 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
super::fileinfo::file_info
),
cmd!(
"file.info.saveTemplate",
"Save Metadata Template…",
[],
None,
"{name?: save into the metadata templates folder as <name>.xmp (a name with characters file systems reject, a dot at either end, or a device name is an error (spaces at either end are dropped); the same name replaces that template), path?: save to this file instead (not both), fields?: {File Info fields as file.info takes them} save these instead of the document's (default: the document's File Info)} write the File Info as an XMP metadata template: title (only one of its own, not Untitled-N), author, authorTitle, description, keywords, rating (1–5), copyrightStatus, copyrightNotice and copyrightUrl, each where it has a value; the dates are left out → {name, path} (with name), {path} (with path), or {data: the XMP text} with neither",
has_doc,
super::fileinfo::save_template
),
cmd!(
"file.info.applyTemplate",
"Import Metadata Template…",
[],
None,
"{path?: an XMP file, name?: a template of the metadata templates folder by the name or file file.info.templates lists, data?: XMP text (exactly one of the three; at most 8 MB), mode: \"replace\" (clear the author, authorTitle, description, keywords, rating, copyright status, notice and URL, then take the template's; the title stays unless the template has one) | \"keep\" (keep the File Info, and take each field the template has) | \"append\" (keep the File Info, add the template's keywords, and take its other fields only where the File Info has none: a title only over an Untitled-N one, a rating only over 0, a copyright status only over unknown), apply?: true (false: change nothing and return the merged File Info), base?: {File Info fields as file.info takes them} merged into instead of the document's} merge a metadata template into the File Info in one undo step, none when nothing changes; a template value file.info would refuse is left out; a missing file, a file larger than 8 MB or one that is not XMP is an error → the File Info as file.info reports it, with changed: true|false (with apply: false, the merged File Info without changed)",
has_doc,
super::fileinfo::apply_template
),
cmd!(
query "file.info.templates",
"Metadata Templates",
[],
None,
"{create?: false (true: make the folder when it is missing)} the metadata templates in the metadata templates folder next to the preferences, sorted by name, at most 1,000 → {templates: [{name, file: the file name, path}], folder?: the folder (left out for a request that may not read it, in runs without preferences and on the web, where the list is empty)}",
super::always,
super::fileinfo::templates
),
]
}
+1 -1
View File
@@ -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: the tip's long axis counter-clockwise from level), roundness?: % (100, kept within 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0 or more, default 0)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An unknown mode, or a variation below 0 or past its range, is an error and erases nothing",
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation ° clockwise, as path.freehand), size?: pt (10), angle?: ° (0: the tip's long axis counter-clockwise from level), roundness?: % (100, kept within 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0 or more, default 0)} 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 unknown mode, or a variation below 0 or past its range, is 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
),
+76 -6
View File
@@ -3,9 +3,10 @@ use super::common::{
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, Result, Session,
Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, Paint, ParamCurve, PathData, Point, Rect, Result, Session,
SubPath, Value, Vec2, bad, eraser_area, eraser_tip, f64_or, fill_contains, json, number_or, object_param, po,
};
use kurbo::{CubicBez, Line, PathSeg};
use vectorcraft_brush::{Brush, BrushKind, Calligraphic, Variation};
use vectorcraft_doc::StrokeLayer;
use vectorcraft_tools::draw2::MIN_BRUSH_SIZE;
@@ -46,8 +47,8 @@ pub(in super::super) fn components(pd: &PathData) -> Vec<PathData> {
/// The pieces of `sp` where `remove(point)` is false. `None` when nothing is removed. Each segment
/// is sampled at least every `step` pt (and at least 24 times), so a removed stretch at least
/// `step` long is found.
fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool) -> Option<Vec<SubPath>> {
/// `step` long is found, and also at the parameters `extra` gives for it.
fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool, extra: &dyn Fn(CubicBez) -> Vec<f64>) -> Option<Vec<SubPath>> {
let nseg = sp.segment_count();
if nseg == 0 {
return sp.anchors.first().filter(|a| remove(a.p)).map(|_| vec![]);
@@ -64,6 +65,13 @@ fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool) -> Optio
let edge = (c.p1 - c.p0).hypot().max((c.p2 - c.p1).hypot()).max((c.p3 - c.p2).hypot());
let wanted = (3.0 * edge / step).ceil();
let samples = if wanted.is_finite() && wanted > K as f64 { (wanted as usize).min(MAX_SAMPLES) } else { K };
let mut ts: Vec<f64> = (1..=samples).map(|k| k as f64 / samples as f64).collect();
let more = extra(c);
if !more.is_empty() {
ts.extend(more.into_iter().filter(|t| t.is_finite() && *t > 0.0 && *t < 1.0));
ts.sort_by(f64::total_cmp);
ts.dedup();
}
let mut prev_t = 0.0;
let mut prev_rm = remove(c.eval(0.0));
let mut start = if prev_rm { None } else { Some(0.0) };
@@ -73,8 +81,7 @@ fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool) -> Optio
runs.push(std::mem::take(&mut cur));
}
}
for k in 1..=samples {
let t = k as f64 / samples as f64;
for t in ts {
let rm = remove(c.eval(t));
if rm != prev_rm {
let (mut lo, mut hi) = (prev_t, t);
@@ -146,10 +153,15 @@ fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool) -> Optio
/// every `step` pt (`f64::INFINITY` for the fixed sampling). Returns the new geometry per output
/// object (one object per piece when the path had a single subpath), or None if unchanged.
pub(in super::super) fn erase_outline(pd: &PathData, step: f64, remove: &dyn Fn(Point) -> bool) -> Option<Vec<PathData>> {
erase_outline_at(pd, step, remove, &|_| vec![])
}
/// [`erase_outline`], also sampling each segment at the parameters `extra` gives for it.
fn erase_outline_at(pd: &PathData, step: f64, remove: &dyn Fn(Point) -> bool, extra: &dyn Fn(CubicBez) -> Vec<f64>) -> Option<Vec<PathData>> {
let mut changed = false;
let mut subs = vec![];
for sp in &pd.subpaths {
match cut_subpath(sp, step, remove) {
match cut_subpath(sp, step, remove, extra) {
Some(pieces) => {
changed = true;
subs.extend(pieces);
@@ -274,6 +286,12 @@ pub(super) fn knife(s: &mut Session, p: &Value) -> Result<Value> {
pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "path.eraseRegion";
if let Some(rect) = p.get("rect").filter(|v| !v.is_null()) {
if p.get("points").is_some_and(|v| !v.is_null()) {
return Err(bad(C, "give `points` or `rect`, not both"));
}
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) {
@@ -325,6 +343,58 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result<Value> {
apply_plan(s, "Eraser", plan)
}
/// `path.eraseRegion`'s `rect: [x, y, width, height]`: four finite numbers, with a width and a
/// height above 0.
fn marquee_param(v: &Value, cmd: &str) -> Result<Rect> {
const SHAPE: &str = "rect is [x, y, width, height] in points, with a width and a height above 0";
let n: Vec<f64> = match v.as_array() {
Some(a) if a.len() == 4 => a.iter().map(Value::as_f64).collect::<Option<_>>().ok_or_else(|| bad(cmd, SHAPE))?,
_ => return Err(bad(cmd, SHAPE)),
};
let [x, y, w, h] = [n[0], n[1], n[2], n[3]];
if !(n.iter().all(|v| v.is_finite()) && w > 0.0 && h > 0.0 && (x + w).is_finite() && (y + h).is_finite()) {
return Err(bad(cmd, SHAPE));
}
Ok(Rect::new(x, y, x + w, y + h))
}
/// `path.eraseRegion` with a marquee: everything inside `r` is erased from the paths (selected, or
/// all). Closed paths lose the rectangle's area, and open paths are cut where they cross its edges.
fn erase_rect(s: &mut Session, r: Rect) -> Result<Value> {
let region =
PathData::single(SubPath::polyline(&[Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)], true));
let inside = |q: Point| q.x >= r.x0 && q.x <= r.x1 && q.y >= r.y0 && q.y <= r.y1;
// An open path is sampled at least every half of the rectangle's shorter side, and also where
// each segment crosses the rectangle's edges and halfway between those crossings, so a stretch
// inside the rectangle is found however long the segment is.
let step = r.width().min(r.height()) / 2.0;
let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)];
let crossings = |c: CubicBez| {
let mut ts: Vec<f64> = (0..4)
.flat_map(|k| PathSeg::Cubic(c).intersect_line(Line::new(corners[k], corners[(k + 1) % 4])))
.map(|x| x.segment_t)
.filter(|t| t.is_finite() && *t > 0.0 && *t < 1.0)
.collect();
ts.sort_by(f64::total_cmp);
let mids: Vec<f64> = [0.0].iter().chain(&ts).zip(ts.iter().chain(&[1.0])).map(|(a, b)| 0.5 * (a + b)).collect();
ts.extend(mids);
ts
};
let st = s.doc()?;
let mut plan: Vec<(NodeId, Vec<PathData>)> = vec![];
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, r)? {
if pd.is_closed() {
if po::area(&po::boolean(&pd, rule, &region, FillRule::NonZero, BoolOp::Intersect), FillRule::NonZero) <= 1e-6 {
continue;
}
plan.push((id, components(&po::boolean(&pd, rule, &region, FillRule::NonZero, BoolOp::Difference))));
} else if let Some(pieces) = erase_outline_at(&pd, step, &inside, &crossings) {
plan.push((id, pieces));
}
}
apply_plan(s, "Eraser", plan)
}
/// The variation modes `path.eraseRegion` takes for each of `angleMode`, `roundnessMode` and
/// `sizeMode`.
const ERASER_MODES: &str = "\"fixed\", \"random\", \"pressure\", \"tilt\", \"bearing\" or \"rotation\"";
+64 -13
View File
@@ -117,11 +117,10 @@ fn smooth_corners(anchors: &[Anchor], closed: bool, reach: f64) -> Vec<bool> {
// eighth of the way round a closed path. Over that much of a circle the path turns by 45°, so a
// loop shorter than the reach is not all corners, while a square's or a triangle's corners still are.
let mut spans = [reach, 2.0 * reach];
// The lengths along the path ahead and back, measured once when an anchor needs them.
let (mut ahead, mut back) = (None, None);
if closed {
let mut total = 0.0;
for i in 0..n {
total += walk(anchors, closed, (i, true), [f64::INFINITY; 2], reach, 1).1;
}
let total = ahead.get_or_insert_with(|| walk_blocks(anchors, closed, true, reach)).first().map_or(0.0, |lens| lens.iter().take(n).sum());
if !(total.is_finite() && total > 0.0) {
return corners;
}
@@ -137,8 +136,10 @@ fn smooth_corners(anchors: &[Anchor], closed: bool, reach: f64) -> Vec<bool> {
if !turn_between(arrive, leave).is_some_and(|t| t > SMOOTH_CORNER_DEG) {
continue;
}
let [Some(back_near), Some(back_far)] = walk(anchors, closed, (i, false), spans, reach, MAX_CORNER_WALK).0 else { continue };
let [Some(ahead_near), Some(ahead_far)] = walk(anchors, closed, (i, true), spans, reach, MAX_CORNER_WALK).0 else { continue };
let back = back.get_or_insert_with(|| walk_blocks(anchors, closed, false, reach));
let [Some(back_near), Some(back_far)] = spans.map(|r| point_along(anchors, closed, (i, false), r, back, reach)) else { continue };
let ahead = ahead.get_or_insert_with(|| walk_blocks(anchors, closed, true, reach));
let [Some(ahead_near), Some(ahead_far)] = spans.map(|r| point_along(anchors, closed, (i, true), r, ahead, reach)) else { continue };
*flag = [(back_near, ahead_near, spans[0]), (back_far, ahead_far, spans[1])]
.into_iter()
.all(|(back, ahead, r)| r <= 0.0 || turn_between(a.p - back, ahead - a.p).is_some_and(|t| t > SMOOTH_CORNER_DEG));
@@ -146,9 +147,54 @@ fn smooth_corners(anchors: &[Anchor], closed: bool, reach: f64) -> Vec<bool> {
corners
}
/// Most segments [`walk`] passes from an anchor before it stops, which bounds the work for each
/// anchor on a path of very many very short segments.
const MAX_CORNER_WALK: usize = 256;
/// The lengths [`walk`] measures along the segments of `anchors`, in the order a walk ahead
/// (`forward`) or back passes them, twice round, starting at the first anchor ahead or the last
/// anchor back, and added up in blocks: element `l` holds the lengths of each run of 2^`l`
/// segments that starts at a multiple of 2^`l`. Each block adds up only its own segments, so a short
/// stretch keeps its length next to very long ones. The segment past an open path's end has no
/// length.
fn walk_blocks(anchors: &[Anchor], closed: bool, forward: bool, reach: f64) -> Vec<Vec<f64>> {
let n = anchors.len();
let lens: Vec<f64> =
(0..n).map(|k| walk(anchors, closed, (if forward { k } else { n - 1 - k }, forward), [f64::INFINITY; 2], reach, 1).1).collect();
let mut blocks = vec![(0..2 * n).map(|k| lens[k % n]).collect::<Vec<f64>>()];
while let Some(last) = blocks.last().filter(|b| b.len() > 1) {
let next = last.as_chunks::<2>().0.iter().map(|[a, b]| a + b).collect();
blocks.push(next);
}
blocks
}
/// The point `dist` along the path `anchors` from anchor `from.0`, ahead when `from.1` and back
/// otherwise, as [`walk`] finds it: an open path's end for a distance beyond the end, and `None`
/// when a length is not a number or is too large to add. The walk skips whole blocks of `blocks`
/// ([`walk_blocks`] in the same direction) that end no more than `dist` along the path, so a path of
/// very many short segments is not walked one segment at a time from each anchor.
fn point_along(anchors: &[Anchor], closed: bool, from: (usize, bool), dist: f64, blocks: &[Vec<f64>], reach: f64) -> Option<Point> {
let (n, (i, forward)) = (anchors.len(), from);
let start = if forward { i } else { n - 1 - i };
let end = start
+ if closed {
n
} else if forward {
n - 1 - i
} else {
i
};
let (mut pos, mut gone) = (start, 0.0);
// The largest block that starts at `pos`, stays within the walk and ends within `dist`, until
// none does; a block whose length is not a number is never skipped.
while let Some((size, len)) = blocks.iter().enumerate().rev().find_map(|(l, lens)| {
let size = 1usize << l;
let len = lens.get(pos >> l).copied()?;
(pos % size == 0 && pos + size <= end && gone + len <= dist).then_some((size, len))
}) {
pos += size;
gone += len;
}
let at = if forward { pos % n } else { n - 1 - pos % n };
walk(anchors, closed, (at, forward), [(dist - gone).max(0.0); 2], reach, n).0[0]
}
/// A walk along the path `anchors` from anchor `from.0`, ahead when `from.1` and back otherwise,
/// past no more than `segments` segments, measured along the lines between each curved segment's
@@ -1099,11 +1145,12 @@ mod tests {
}
/// A 90° bump 400 pt high cut into 1 pt segments, between two long straight segments: with a reach
/// of 10 pt its top is a corner, and with a reach of 1,000 pt, where the walk passes more segments
/// than it measures before it gets that far, its top is not one, as the path turns by about 51°
/// over that reach.
/// of 10 pt, and of 300 pt, where twice the reach passes the bump's 566 segments on each side, its
/// top is a corner, and with a reach of 1,000 pt its top is not one, as the path turns by about 51°
/// over that reach. The turns into and between 1 pt segments that follow two segments 1e16 pt long
/// are corners too.
#[test]
fn a_corner_is_not_kept_where_the_reach_is_not_measured() {
fn a_bump_of_many_short_segments_is_a_corner_where_it_turns_over_the_reach() {
let side = 400.0 * std::f64::consts::SQRT_2;
let steps = side.ceil() as usize;
let mut pts = vec![(-3000.0, 0.0)];
@@ -1120,6 +1167,10 @@ mod tests {
let top = steps + 1;
assert_eq!(anchors[top].p, Point::new(0.0, 400.0));
assert!(smooth_corners(&anchors, false, 10.0)[top]);
assert!(smooth_corners(&anchors, false, 300.0)[top]);
let long = polyline(&[(0.0, 0.0), (1e16, 0.0), (0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 2.0)]);
let corners = smooth_corners(&long, false, 0.5);
assert!(corners[2] && corners[3] && corners[4], "{corners:?}");
assert!(!smooth_corners(&anchors, false, 1000.0)[top]);
}
+1 -1
View File
@@ -179,7 +179,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Paste",
["Edit"],
Some("Cmd+V"),
"{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}",
"{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch; legend labels in a pie's wedges that it turns dark or light take a redraw's contrast, unless their fill is their own) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}",
has_clipboard,
|s, p| paste(s, p, PasteMode::Offset)
),
+56 -27
View File
@@ -978,15 +978,18 @@ fn raster_image(d: &mut Document, n: &Node) -> Option<(Node, bool)> {
/// Expand the pieces of `m`, art evaluated from the object of the same id (its pieces share that
/// id): those made from its own fills and strokes, or with `all` every member. The other members
/// that repeat an id ([`repeats_an_id`]) and hold a random Transform effect ([`has_seeded`]) are
/// expanded as well ([`expand_in_place`]). Then the members get ids of their own. Random in a
/// Transform effect takes its seed from the id, and the canvas draws the pieces with the ids they
/// have before that. Returns what each of those other members' expansions lists, by the member's
/// new id.
/// expanded as well ([`expand_in_place`]), except the objects `skip` lists. Then the members get ids
/// of their own. Random in a Transform effect takes its seed from the id, and the canvas draws the
/// pieces with the ids they have before that. `kept` gets the new id of each object in them that
/// had an id `skip` lists before. Returns what each of those other members' expansions lists, by
/// the member's new id.
fn expand_pieces(
d: &mut Document,
m: &mut Node,
all: bool,
brushes: &[vectorcraft_brush::Brush],
skip: &[NodeId],
kept: &mut Vec<NodeId>,
stroke_art: effects::StrokeArt,
) -> std::collections::HashMap<NodeId, Vec<Listed>> {
let id = m.id;
@@ -1002,9 +1005,23 @@ fn expand_pieces(
if all || c.id == id {
effects::expand_art(d, c, stroke_art);
} else if has_seeded(c) && repeats_an_id(c, &seen) {
listed = Some(expand_in_place(d, c, brushes));
listed = Some(expand_in_place(d, c, brushes, skip));
}
let mut was = vec![];
if !skip.is_empty() {
c.walk(&mut |n| was.push(n.id));
}
fresh_ids_listed(d, c, &mut seen, listed.as_deref_mut().unwrap_or_default());
if !was.is_empty() {
// A copy of an object `skip` lists is left as it is too.
let mut at = 0;
c.walk(&mut |n| {
if was.get(at).is_some_and(|old| *old != n.id && skip.contains(old)) {
kept.push(n.id);
}
at += 1;
});
}
if let Some(listed) = listed {
expanded.insert(c.id, listed);
}
@@ -1058,9 +1075,9 @@ fn repeats_an_id(n: &Node, seen: &std::collections::HashSet<NodeId>) -> bool {
type Listed = (NodeId, usize);
/// [`expanded_node`] of `c` in place. Returns what the expansion lists, by places in the walk of `c`.
fn expand_in_place(d: &mut Document, c: &mut Node, brushes: &[vectorcraft_brush::Brush]) -> Vec<Listed> {
fn expand_in_place(d: &mut Document, c: &mut Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId]) -> Vec<Listed> {
let mut listed = vec![];
if let Some(e) = expanded_node(d, c.clone(), brushes, &mut listed) {
if let Some(e) = expanded_node(d, c.clone(), brushes, skip, &mut listed) {
*c = e;
}
listed
@@ -1084,9 +1101,16 @@ fn fresh_ids_listed(d: &mut Document, c: &mut Node, seen: &mut std::collections:
/// geometry effects are baked, raster effects become an embedded image, and the object keeps its
/// transparency.
pub(crate) fn expand_node(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush::Brush], out: &mut Vec<NodeId>) {
expand_node_except(d, id, brushes, &[], out);
}
/// [`expand_node`], leaving the objects `skip` lists, and what they hold, as they are. A geometry
/// effect of a group or layer around one still reshapes it with the rest of its members, and the
/// copies of it that such an effect makes are left as they are too.
fn expand_node_except(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], out: &mut Vec<NodeId>) {
let Some(n) = d.node(id).cloned() else { return };
let mut listed = vec![];
let m = expanded_node(d, n, brushes, &mut listed);
let m = expanded_node(d, n, brushes, skip, &mut listed);
out.extend(listed.into_iter().map(|(id, _)| id));
if let Some(mut m) = m {
// Art made from type takes its emoji's pixels into the document.
@@ -1099,10 +1123,10 @@ pub(crate) fn expand_node(d: &mut Document, id: NodeId, brushes: &[vectorcraft_b
/// [`expand_node`] of `n`, which need not be in `d`: `n` with its appearance expanded, `None` when
/// it has nothing to expand. `out` gets the objects whose appearance expands, by places in the walk
/// of the expanded `n`, `n`'s first when its own does.
fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Brush], out: &mut Vec<Listed>) -> Option<Node> {
/// of the expanded `n`, `n`'s first when its own does. The objects `skip` lists are not expanded.
fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], out: &mut Vec<Listed>) -> Option<Node> {
let id = n.id;
if !expandable(&n) {
if skip.contains(&id) || !expandable(&n) {
return None;
}
// Colour adjustments: the colours inside become the adjusted ones (an embedded image a
@@ -1139,7 +1163,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
for (i, c) in m.children_mut().into_iter().flatten().enumerate() {
let c = Arc::make_mut(c);
if i == 0 {
expanded = expand_in_place(d, c, brushes);
expanded = expand_in_place(d, c, brushes, skip);
fresh_ids_listed(d, c, &mut seen, &mut expanded);
} else {
effects::fresh_ids(d, c, &mut seen);
@@ -1169,6 +1193,8 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|d: &mut Document, path: &PathData, rule: FillRule, st: &StrokeLayer| super::pathops::outlined_stroke(d, brushes, path, rule, st);
// Members of a group or layer that `expand_pieces` expanded, by id, with what their expansion lists.
let mut members = std::collections::HashMap::new();
// New ids of the copies of objects `skip` lists among those members.
let mut kept = vec![];
let expanded = match image {
// Blur, feather and inner glow change the object itself: it becomes the image (a layer
// keeps it as its only member).
@@ -1180,7 +1206,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
} else if container {
// A group's or layer's own fills and strokes become art among its members.
effects::evaluate_container(Some(&*d), &v).map(|mut m| {
members = expand_pieces(d, &mut m, false, brushes, &mut stroke_art);
members = expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art);
m
})
} else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
@@ -1201,7 +1227,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
effects::expand_outlined(Some(&*d), &v, symbol.as_ref()).map(|mut m| {
let mut budget = vectorcraft_doc::MAX_SYMBOL_NODES;
expand_nested_instances(d, &mut m, 1, &mut budget);
expand_pieces(d, &mut m, true, brushes, &mut stroke_art);
expand_pieces(d, &mut m, true, brushes, skip, &mut kept, &mut stroke_art);
m
})
};
@@ -1223,6 +1249,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
}
}
if container {
let skip = if kept.is_empty() { std::borrow::Cow::Borrowed(skip) } else { std::borrow::Cow::Owned([skip, &kept].concat()) };
// The place of each member in the walk of `n`: after `n` and the members before it.
let mut at = 1;
for c in n.children_mut().into_iter().flatten() {
@@ -1235,7 +1262,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
match members.remove(&c.id) {
Some(listed) => out.extend(listed),
None => {
if let Some(e) = expanded_node(d, (**c).clone(), brushes, out) {
if let Some(e) = expanded_node(d, (**c).clone(), brushes, &skip, out) {
*c = Arc::new(e);
changed = true;
}
@@ -1280,9 +1307,20 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
// geometry it hasn't changed.
if vectorcraft_plugins::safe_mode::active() {
// A dimension selected with the art it measures is left as it is, and so is the art of a graph design in a
// series.
// series, unless an effect of a group around it, the selected graph or series group or one inside it, draws it
// with that group: an effect of the group's own, or a raster effect of one of its fills or strokes (the group
// then becomes an image of all of it).
let mut d = super::dimension::without_kept(&s.doc()?.doc, &roots);
let designs = super::appearance::design_art_in(&d, &roots);
let draws_members = |g: &Node| g.appearance.effects.iter().any(|e| e.visible) || !rasterfx::raster_fx(g).is_empty();
let designs: Vec<NodeId> = super::appearance::design_art_in(&d, &roots)
.into_iter()
.filter(|art| {
!d.ancestry(*art).is_some_and(|up| {
let from = up.iter().position(|a| roots.contains(a)).unwrap_or(up.len());
up.get(from..up.len().saturating_sub(1)).is_some_and(|around| around.iter().filter_map(|a| d.node(*a)).any(draws_members))
})
})
.collect();
if !designs.is_empty() {
let view = d.to_mut();
for id in designs {
@@ -1313,16 +1351,7 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
let mut out = vec![];
let threaded = super::threads::frames(d);
for id in &roots {
expand_node(d, *id, &brushes, &mut out);
}
for id in &designs {
if let (Some(was), Some(slot)) = (before.node(*id), d.node_mut(*id)) {
*slot = was.clone();
}
}
if !designs.is_empty() {
// A mark that expands into a group stays listed: only what lies in the restored art is left out.
out.retain(|id| d.node(*id).is_some() && !d.ancestry(*id).is_some_and(|up| up.iter().any(|a| designs.contains(a))));
expand_node_except(d, *id, &brushes, &designs, &mut out);
}
super::dimension::put_back(d, lifted);
// A dimension whose source was replaced stays where it was, no longer linked.
+321 -13
View File
@@ -3,14 +3,28 @@
//! title is the one the file the document was opened from gave itself ([`DocMetadata::title`]),
//! else the document's name. The SVG (with `metadata`), PDF and PNG writers carry it, and a PDF or
//! `.ai` opens with the File Info it gives ([`read_pdf`]).
//!
//! Metadata templates: `file.info.saveTemplate` writes the File Info as an XMP file
//! ([`vectorcraft_pdf::metadata_template`]), `file.info.applyTemplate` merges one into the File
//! Info, and `file.info.templates` lists those in the metadata templates folder.
use serde_json::{Map, Value, json};
use vectorcraft_doc::metadata::{MAX_RATING, iso8601};
use vectorcraft_doc::{ColorMode, CopyrightStatus, DocMetadata, Document};
use super::{Result, Session, bad};
use super::{Result, Session, bad, switch_or, text_param};
const C: &str = "file.info";
const SAVE: &str = "file.info.saveTemplate";
const APPLY: &str = "file.info.applyTemplate";
const LIST: &str = "file.info.templates";
/// The extension of a metadata template file.
const TEMPLATE_EXT: &str = "xmp";
/// The most templates `file.info.templates` lists.
const MAX_LISTED: usize = 1000;
/// The largest metadata template `file.info.saveTemplate` writes and `file.info.applyTemplate`
/// reads, in bytes (8 MB). The largest template File Info's fields can give is under 4 MB.
const MAX_TEMPLATE_FILE: usize = vectorcraft_pdf::MAX_TEMPLATE_BYTES;
/// Longest text field, in characters.
const MAX_TEXT: usize = 65_536;
/// Longest keyword, in characters.
@@ -21,9 +35,13 @@ const READ_ONLY: [&str; 6] = ["created", "modified", "colorMode", "units", "artb
/// What `file.info` reports (and takes back).
pub(crate) fn info_json(d: &Document) -> Value {
let m = &d.metadata;
info_json_with(d, d.info_title(), &d.metadata)
}
/// [`info_json`] with the title `title` and the metadata `m` in place of the document's.
fn info_json_with(d: &Document, title: &str, m: &DocMetadata) -> Value {
json!({
"title": d.info_title(),
"title": title,
"author": m.author,
"authorTitle": m.author_title,
"description": m.description,
@@ -48,11 +66,25 @@ pub(crate) fn file_info(s: &mut Session, p: &Value) -> Result<Value> {
Value::Object(o) => o,
_ => return Err(bad(C, "params must be an object")),
};
let (title, m) = edited(s, Some(o))?;
commit(s, title, m)?;
Ok(info_json(&s.doc()?.doc))
}
/// The active document's File Info title and metadata with `fields` (as `file.info` takes them)
/// applied.
fn edited(s: &Session, fields: Option<&Map<String, Value>>) -> Result<(String, DocMetadata)> {
let d = &s.doc()?.doc;
let (mut title, mut m) = (d.info_title().to_string(), d.metadata.clone());
for (k, v) in o {
for (k, v) in fields.into_iter().flatten() {
apply(&mut title, &mut m, k, v)?;
}
Ok((title, m))
}
/// Make `title` and `m` the active document's File Info in one undo step; nothing is recorded when
/// they are what it has. Whether anything changed.
fn commit(s: &mut Session, title: String, mut m: DocMetadata) -> Result<bool> {
let d = &s.doc()?.doc;
// A title File Info changes becomes the document's own, as it always has (the tab and Save As
// offer it where the document has no file), and replaces the one its file gave.
@@ -60,16 +92,290 @@ pub(crate) fn file_info(s: &mut Session, p: &Value) -> Result<Value> {
if retitled {
m.title = None;
}
if retitled || m != d.metadata {
s.edit("File Info", |d, _| {
if retitled {
d.title = title;
}
d.metadata = m;
Ok(())
})?;
if !retitled && m == d.metadata {
return Ok(false);
}
Ok(info_json(&s.doc()?.doc))
s.edit("File Info", |d, _| {
if retitled {
d.title = title;
}
d.metadata = m;
Ok(())
})?;
Ok(true)
}
/// The optional object `p` gives for `key`.
fn fields_param<'a>(p: &'a Value, key: &str, c: &str) -> Result<Option<&'a Map<String, Value>>> {
match p.get(key) {
None | Some(Value::Null) => Ok(None),
Some(Value::Object(o)) => Ok(Some(o)),
Some(_) => Err(bad(c, format!("`{key}` must be an object"))),
}
}
impl Session {
/// Have `file.info.saveTemplate`, `file.info.applyTemplate` and `file.info.templates` keep the
/// metadata templates in the folder `dir`, which a save makes when it is missing.
pub fn attach_metadata_templates_dir(&mut self, dir: std::path::PathBuf) {
self.metadata_templates_dir = Some(dir);
}
/// The metadata templates folder ([`Session::attach_metadata_templates_dir`]); none on the web,
/// which has no folders.
pub fn metadata_templates_dir(&self) -> Option<&std::path::Path> {
self.metadata_templates_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32"))
}
}
/// The metadata template of the File Info `title` and `m`: each field that has a value, the title
/// only where it is one of its own ([`super::fileio::is_own_title`]), the rating only from 1 up.
fn template_of(title: &str, m: &DocMetadata) -> vectorcraft_pdf::FileInfo {
let text = |s: &str| (!s.trim().is_empty()).then(|| s.to_string());
vectorcraft_pdf::FileInfo {
title: super::fileio::is_own_title(title).then(|| title.to_string()),
author: text(&m.author),
author_title: text(&m.author_title),
description: text(&m.description),
keywords: (!m.keywords.is_empty()).then(|| m.keywords.clone()),
rating: (m.rating > 0).then_some(m.rating),
copyright_notice: text(&m.copyright_notice),
copyright_url: text(&m.copyright_url),
copyrighted: match m.copyright_status {
CopyrightStatus::Copyrighted => Some(true),
CopyrightStatus::PublicDomain => Some(false),
CopyrightStatus::Unknown => None,
},
..Default::default()
}
}
/// The path of the template `name` in the folder `dir`: `name` made a safe file name, with
/// [`TEMPLATE_EXT`].
fn template_path(dir: &std::path::Path, name: &str, c: &str) -> Result<String> {
let name = name.trim();
if name.is_empty() {
return Err(bad(c, "the template name can't be empty"));
}
Ok(dir.join(super::swatchlib::library_file_name(name, TEMPLATE_EXT)).to_string_lossy().into_owned())
}
/// The error for a template over [`MAX_TEMPLATE_FILE`].
fn too_big(c: &str) -> crate::EngineError {
bad(c, format!("the file is larger than {} MB", MAX_TEMPLATE_FILE >> 20))
}
/// File Info › Save Metadata Template: `file.info.saveTemplate {name?, path?, fields?}`.
pub(crate) fn save_template(s: &mut Session, p: &Value) -> Result<Value> {
let name = text_param(p, "name", SAVE)?;
let path = text_param(p, "path", SAVE)?;
let (title, m) = edited(s, fields_param(p, "fields", SAVE)?)?;
let xmp = vectorcraft_pdf::metadata_template(&template_of(&title, &m));
if xmp.len() > MAX_TEMPLATE_FILE {
return Err(too_big(SAVE));
}
match (name, path) {
(Some(_), Some(_)) => Err(bad(SAVE, "give `name` or `path`, not both")),
(Some(name), None) => {
let dir = s.metadata_templates_dir().ok_or_else(|| bad(SAVE, "no metadata templates folder here"))?.to_path_buf();
let path = template_path(&dir, name, SAVE)?;
// The name is the file name as it is, so two names never share a file.
let listed = std::path::Path::new(&path).file_stem().map(|s| s.to_string_lossy().into_owned());
if listed.as_deref() != Some(name.trim()) {
return Err(bad(SAVE, "the template name isn't usable as a file name"));
}
// Only a file in the folder itself is replaced: a link there is not followed.
if std::fs::symlink_metadata(&path).is_ok_and(|m| !m.is_file()) {
return Err(crate::EngineError::Other(format!("{path}: not a file")));
}
let dir = dir.to_string_lossy().into_owned();
// The app's own folder, under a name checked above: no root applies.
crate::file_access::unconfined(|| super::fileio::create_dir(&dir).and_then(|()| super::fileio::write_file(&path, xmp.as_bytes())))?;
Ok(json!({ "name": listed, "path": super::fileio::shown_path(&path) }))
}
(None, Some(path)) => {
super::fileio::write_file(path, xmp.as_bytes())?;
Ok(json!({ "path": path }))
}
(None, None) => Ok(json!({ "data": xmp })),
}
}
/// How `file.info.applyTemplate` merges a template's fields into the File Info.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Merge {
/// Clear the fields a template can hold, then take the template's.
Replace,
/// Keep the fields, and take each one the template gives.
Keep,
/// Keep the fields: add the template's keywords, and take its other fields only where the File
/// Info has none.
Append,
}
/// File Info › Import: `file.info.applyTemplate {path?|name?|data?, mode, apply?, base?}`.
pub(crate) fn apply_template(s: &mut Session, p: &Value) -> Result<Value> {
let mode = match text_param(p, "mode", APPLY)? {
Some("replace") => Merge::Replace,
Some("keep") => Merge::Keep,
Some("append") => Merge::Append,
_ => return Err(bad(APPLY, "mode must be replace, keep or append")),
};
let apply = switch_or(p, "apply", true, APPLY)?;
let base = fields_param(p, "base", APPLY)?;
let bytes = template_bytes(s, p)?;
let t = vectorcraft_pdf::read_template(&bytes).ok_or_else(|| bad(APPLY, "the file is not an XMP metadata template"))?;
let (mut title, mut m) = edited(s, base)?;
merge(&mut title, &mut m, t, mode);
if !apply {
return Ok(info_json_with(&s.doc()?.doc, &title, &m));
}
let changed = commit(s, title, m)?;
let mut out = info_json(&s.doc()?.doc);
out["changed"] = json!(changed);
Ok(out)
}
/// The bytes of the template `p` names: `path`, `name` (in the metadata templates folder) or
/// `data`, exactly one, at most [`MAX_TEMPLATE_FILE`] long.
fn template_bytes(s: &Session, p: &Value) -> Result<Vec<u8>> {
let given = [text_param(p, "path", APPLY)?, text_param(p, "name", APPLY)?, text_param(p, "data", APPLY)?];
// At most one byte past the limit is read, so a huge file is never read whole.
let read = |path: &str| super::fileio::read_file_head(path, MAX_TEMPLATE_FILE + 1);
let bytes = match given {
[Some(path), None, None] => read(path)?,
[None, Some(name), None] => {
let dir = s.metadata_templates_dir().ok_or_else(|| bad(APPLY, "no metadata templates folder here"))?;
let mut path = template_path(dir, name, APPLY)?;
// A template `file.info.templates` lists: by its `file` first, then by its `name` with
// the extension in lowercase, then in other letter case. Only files in the folder itself
// are listed: a link there is not followed.
let name = name.trim();
let own = format!("{name}.{TEMPLATE_EXT}");
let listed = template_files(dir)
.filter(|f| f == name || f.rsplit_once('.').is_some_and(|(stem, _)| stem == name))
.min_by_key(|f| (f != name, *f != own));
if let Some(file) = listed {
path = dir.join(file).to_string_lossy().into_owned();
} else if std::path::Path::new(&path).file_stem().map(|s| s.to_string_lossy()).as_deref() != Some(name) {
// A name that is not a file name as it is never opens another template.
return Err(bad(APPLY, "the template name isn't usable as a file name"));
}
let plain_file = |path: &str| std::fs::symlink_metadata(path).is_ok_and(|m| m.is_file());
if std::fs::symlink_metadata(&path).is_ok() && !plain_file(&path) {
return Err(crate::EngineError::Other(format!("{path}: not a file")));
}
// The app's own folder: no root applies.
crate::file_access::unconfined(|| read(&path))?
}
[None, None, Some(data)] if data.len() > MAX_TEMPLATE_FILE => return Err(too_big(APPLY)),
[None, None, Some(data)] => data.as_bytes().to_vec(),
_ => return Err(bad(APPLY, "give one of `path`, `name` and `data`")),
};
if bytes.len() > MAX_TEMPLATE_FILE {
return Err(too_big(APPLY));
}
Ok(bytes)
}
/// Merge the template `t` into the File Info `title` and `m` as `mode` says. Each field goes in as
/// `file.info` would take it; a value it would refuse is left out.
fn merge(title: &mut String, m: &mut DocMetadata, t: vectorcraft_pdf::FileInfo, mode: Merge) {
if mode == Merge::Replace {
// The title is never cleared: a document always has one.
m.author.clear();
m.author_title.clear();
m.description.clear();
m.keywords.clear();
m.rating = 0;
m.copyright_status = CopyrightStatus::Unknown;
m.copyright_notice.clear();
m.copyright_url.clear();
}
let status = t.copyrighted.map(|c| if c { CopyrightStatus::Copyrighted } else { CopyrightStatus::PublicDomain });
let fields = [
("title", t.title.map(Value::from)),
("author", t.author.map(Value::from)),
("authorTitle", t.author_title.map(Value::from)),
("description", t.description.map(Value::from)),
("keywords", t.keywords.map(Value::from)),
("rating", t.rating.map(Value::from)),
("copyrightStatus", status.map(|s| Value::from(s.id()))),
("copyrightNotice", t.copyright_notice.map(Value::from)),
("copyrightUrl", t.copyright_url.map(Value::from)),
];
for (k, v) in fields {
let Some(mut v) = v else { continue };
if mode == Merge::Append {
let empty = match k {
"title" => !super::fileio::is_own_title(title),
"author" => m.author.is_empty(),
"authorTitle" => m.author_title.is_empty(),
"description" => m.description.is_empty(),
"rating" => m.rating == 0,
"copyrightStatus" => m.copyright_status == CopyrightStatus::Unknown,
"copyrightNotice" => m.copyright_notice.is_empty(),
"copyrightUrl" => m.copyright_url.is_empty(),
_ => true,
};
if !empty {
continue;
}
if k == "keywords" {
let mut all: Vec<Value> = m.keywords.iter().cloned().map(Value::from).collect();
all.extend(v.as_array().cloned().unwrap_or_default());
v = Value::from(all);
}
}
// `apply` changes the field only when it takes the value.
let _ = apply(title, m, k, &v);
}
}
/// The file names of the templates in the folder `dir`: its files with a name before the
/// [`TEMPLATE_EXT`] extension, in any case. The app's own folder, read directly; a folder not made
/// yet holds none.
fn template_files(dir: &std::path::Path) -> impl Iterator<Item = String> {
std::fs::read_dir(dir)
.into_iter()
.flatten()
.flatten()
.filter(|e| e.file_type().is_ok_and(|t| t.is_file()))
.map(|e| e.file_name().to_string_lossy().into_owned())
.filter(|file| file.rsplit_once('.').is_some_and(|(stem, ext)| ext.eq_ignore_ascii_case(TEMPLATE_EXT) && !stem.is_empty()))
}
/// `file.info.templates {create?}`: the metadata templates in the folder, by name.
pub(crate) fn templates(s: &mut Session, p: &Value) -> Result<Value> {
let create = switch_or(p, "create", false, LIST)?;
let Some(dir) = s.metadata_templates_dir().map(|d| d.to_string_lossy().into_owned()) else {
return Ok(json!({ "templates": [] }));
};
if create {
// The app's own folder: no root applies.
crate::file_access::unconfined(|| super::fileio::create_dir(&dir))?;
}
// The first [`MAX_LISTED`] by name, with no more than that many held at once.
let mut files = std::collections::BTreeSet::new();
for file in template_files(std::path::Path::new(&dir)) {
files.insert(file);
if files.len() > MAX_LISTED {
files.pop_last();
}
}
let list: Vec<Value> = files
.iter()
.filter_map(|file| {
let (stem, _) = file.rsplit_once('.')?;
let path = std::path::Path::new(&dir).join(file).to_string_lossy().into_owned();
Some(json!({ "name": stem, "file": file, "path": super::fileio::shown_path(&path) }))
})
.collect();
let mut out = json!({ "templates": list });
if super::fileio::shown_path(&dir) == dir.as_str() {
out["folder"] = json!(dir);
}
Ok(out)
}
/// The File Info a PDF or PDF-compatible `.ai` gives ([`vectorcraft_pdf::file_info`]) into `m`: each
@@ -79,8 +385,10 @@ pub(crate) fn read_pdf(m: &mut DocMetadata, f: vectorcraft_pdf::FileInfo) {
let status = f.copyrighted.map(|c| if c { CopyrightStatus::Copyrighted } else { CopyrightStatus::PublicDomain });
let fields = [
("author", f.author.map(Value::from)),
("authorTitle", f.author_title.map(Value::from)),
("description", f.description.map(Value::from)),
("keywords", f.keywords.map(Value::from)),
("rating", f.rating.map(Value::from)),
("copyrightStatus", status.map(|s| Value::from(s.id()))),
("copyrightNotice", f.copyright_notice.map(Value::from)),
("copyrightUrl", f.copyright_url.map(Value::from)),
+1 -1
View File
@@ -39,7 +39,7 @@ pub mod jxlread;
mod legacy_ai;
mod load;
mod mesh3d;
pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, size_note};
pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, png_clip, size_note};
mod heifread;
mod hpgl;
mod jp2read;
+18 -10
View File
@@ -149,7 +149,9 @@ pub(crate) const IMAGE_OUTSIDE: &str = "a linked image file is outside the read
/// file with SVG Options › Images set to Link, and with Embed when the document holds no pixels for
/// the image, for the images of the art each file draws (with chosen artboards, the art over each
/// one; hidden layers and objects only with `hiddenLayers`, template layers and the opacity-mask
/// and symbol editing layers never) and of the symbols, patterns and brushes that art uses; with
/// and symbol editing layers never, opacity masks not with SVG Tiny 1.2, and objects with effects
/// SVG has no filters for as the images the file draws of them), of the art the file draws for each
/// placed document, and of the symbols, patterns and brushes that art uses; with
/// Preserve Editing Capabilities, the native document the file carries names every linked file, the relative paths kept of them
/// and each data set's image. The error names no file or folder.
pub fn check_linked_images(cmd: &str, format: &str, st: &crate::DocState, d: &vectorcraft_doc::Document, p: &Value) -> Result<()> {
@@ -162,21 +164,27 @@ pub(crate) fn check_images_in(cmd: &str, format: &str, d: &vectorcraft_doc::Docu
if !matches!(format, "svg" | "svgz") || crate::file_access::current().is_none() {
return Ok(());
}
// Options that don't read as the encoder's choices count as Link, Preserve Editing and hidden
// layers kept: the encoder refuses them anyway.
let (link, preserve, hidden) = match super::svg::options_map(p) {
// Options that don't read as the encoder's choices count as Link, Preserve Editing, hidden
// layers kept and SVG 1.1: the encoder refuses them anyway.
let (link, preserve, hidden, tiny) = match super::svg::options_map(p) {
Ok(m) => {
let on = |k: &str| m.get(k).is_some_and(|v| v.as_bool() != Some(false));
(m.get("images").is_some_and(|v| v.as_str() != Some("embed")), on("preserveEditing"), on("hiddenLayers"))
let tiny = m.get("profile").and_then(Value::as_str) == Some("tiny12");
(m.get("images").is_some_and(|v| v.as_str() != Some("embed")), on("preserveEditing"), on("hiddenLayers"), tiny)
}
Err(_) => (true, true, true),
Err(_) => (true, true, true, false),
};
// The opacity-mask and symbol editing layers are never written.
let d = &*d.without_edit_modes();
let names = |d: &vectorcraft_doc::Document| crate::cmd::links::svg_names_hidden_image(d, base, link, hidden);
if preserve && crate::cmd::links::names_hidden_file(d, base)
|| names(d) && super::svg::drawn(d, p).is_none_or(|files| files.iter().any(|f| names(f)))
{
let names = |d: &vectorcraft_doc::Document| crate::cmd::links::svg_names_hidden_image(d, base, link, hidden, tiny);
// The SVG draws the objects with effects it has no filters for as images of them, as the
// encoder and the clipboard prepare them.
let drawing_names = || {
let flat = crate::cmd::rasterfx::flatten_pixel_effects_for(d, !tiny);
let d = flat.as_ref().unwrap_or(d);
names(d) && super::svg::drawn(d, p).is_none_or(|files| files.iter().any(|f| names(f)))
};
if preserve && crate::cmd::links::names_hidden_file(d, base) || names(d) && drawing_names() {
return Err(bad(cmd, IMAGE_OUTSIDE));
}
Ok(())
File diff suppressed because one or more lines are too long
+9 -3
View File
@@ -199,8 +199,12 @@ fn selected_part(n: &Arc<Node>, keep: &HashSet<NodeId>, holders: &HashSet<NodeId
/// out, at any depth of layers, sublayers and groups that don't clip, unless what the renderer
/// draws for them, their effects included ([`vectorcraft_render::effect_bounds`]), reaches it.
/// Objects that reach it stay whole (the file's bounds clip them), as DXF's crop leaves them.
/// Symbol instances are measured by their art, and the box of one whose art holds brushed strokes
/// grows by as far as their brush art can paint ([`SymbolBoxes::with_brush_art`]). An object that
/// Both boxes grow by the room brush art can paint past the brushed strokes of the object and of
/// the objects in it ([`vectorcraft_brush::reach_within`]: a clipping group or layer by its clipping
/// path's, a compound path by its own strokes'), so a brushed path just off `rect` stays when its
/// brush art reaches it. Symbol instances are measured by their art, and the box of one whose art
/// holds brushed strokes grows by as far as their brush art can paint
/// ([`SymbolBoxes::with_brush_art`]). An object that
/// holds a symbol instance also stays when what the canvas paints for it reaches `rect`
/// ([`vectorcraft_render::painted_bounds`]: the effects in the symbols' art and its own effects). A
/// clipping layer keeps every object, its clipping path among them. An artboard's file then holds
@@ -233,7 +237,9 @@ pub(super) fn art_over(doc: &Document, rect: vectorcraft_geom::Rect, renderer: &
let mut holds_instance = false;
n.walk(&mut |c| holds_instance |= matches!(c.kind, NodeKind::SymbolInstance { .. }));
let painted = || holds_instance && vectorcraft_render::painted_bounds(doc, n).is_some_and(over);
(n.visual_bounds_with(symbols).is_none_or(over) || renderer.effect_bounds(symbols, n).is_some_and(over) || painted()).then(|| n.clone())
let reach = vectorcraft_brush::reach_within(n);
let brushed = |b: vectorcraft_geom::Rect| over(if reach > 0.0 { b.inflate(reach, reach) } else { b });
(n.visual_bounds_with(symbols).is_none_or(brushed) || renderer.effect_bounds(symbols, n).is_some_and(brushed) || painted()).then(|| n.clone())
}
let symbols = doc.symbol_boxes().with_brush_art();
let mut d = doc.clone();
+48 -6
View File
@@ -73,8 +73,10 @@ pub struct RasterImage {
pub height: u32,
/// The resolution the file declares (see [`super::ppi::resolution`]).
pub ppi: Option<(f64, f64)>,
/// A DCS file's clipping path, in the image's pixel space ([`crate::cmd::place::dcs`]).
pub clip: Option<vectorcraft_geom::PathData>,
/// The clipping path its file draws it through, in the image's pixel space, with its fill rule:
/// a DCS file's (nonzero, [`crate::cmd::place::dcs`]), or a PSD or PSB file's (even-odd,
/// [`psdread::clipping_path`]).
pub clip: Option<(vectorcraft_geom::PathData, vectorcraft_geom::FillRule)>,
}
pub(super) fn err(e: impl std::fmt::Display) -> EngineError {
@@ -949,7 +951,8 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option<String> {
/// or TIFF keeps its inks, at the 8 or 16 bits the file has, and its CMYK ICC profile as a CMYK
/// TIFF ([`vectorcraft_doc::cmyk::turned_cmyk`]). An image the decoder reads and that is stored as
/// PNG keeps its gray or RGB samples at 8 or 16 bits, and the gray or RGB ICC profile they are in;
/// other samples become 8-bit RGBA.
/// other samples become 8-bit RGBA. A Photoshop document's PNG keeps the clipping path the file
/// names ([`png_with_clip`]).
pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
let ppi = super::ppi::resolution(bytes);
if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) {
@@ -957,7 +960,8 @@ pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
}
if psdread::is_psd(bytes) {
let cms = vectorcraft_color::cms::active();
return as_png(psdread::decode(bytes, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)).map_err(err)?, None, ppi);
let img = as_png(psdread::decode(bytes, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)).map_err(err)?, None, ppi)?;
return Ok(png_with_clip(img, psdread::clipping_path(bytes)));
}
if jxlread::is_jxl(bytes) {
let (img, icc, orientation) = jxlread::decode(bytes, MAX_RASTER_ALLOC).map_err(err)?;
@@ -1125,10 +1129,48 @@ fn stored(bytes: Vec<u8>, mime: &'static str, (width, height): (u32, u32), ppi:
Ok(RasterImage { key: blob.content_key(), blob, width, height, ppi, clip: None })
}
/// The keyword of the PNG text chunk holding the clipping path of the file a PNG was made from
/// ([`png_with_clip`]).
const CLIP_KEYWORD: &str = "VectorCraft clip";
/// Longest clipping path a PNG keeps (bytes of its JSON).
const MAX_PNG_CLIP: usize = 16 << 20;
/// `img`, a PNG made from a PSD or PSB file, with `clip`, the clipping path that file names in the
/// image's pixel space (even-odd): the image keeps it, and its PNG keeps it in a text chunk, so the
/// Links commands know a clip group of that path as the file's ([`png_clip`]). A path whose JSON is
/// longer than [`MAX_PNG_CLIP`] is left out, and the image comes in unclipped.
fn png_with_clip(mut img: RasterImage, clip: Option<vectorcraft_geom::PathData>) -> RasterImage {
let Some(clip) = clip else { return img };
let Some(json) = serde_json::to_string(&clip).ok().filter(|j| j.len() <= MAX_PNG_CLIP) else { return img };
let png = vectorcraft_render::encode::png::with_text(img.blob.bytes.to_vec(), &[(CLIP_KEYWORD, json.into())]);
img.blob = ImageBlob::new("image/png", png);
img.key = img.blob.content_key();
img.clip = Some((clip, vectorcraft_geom::FillRule::EvenOdd));
img
}
/// The clipping path a PNG made from a PSD or PSB file keeps ([`png_with_clip`]), in its pixel
/// space; `None` for other images, and for a text chunk longer than [`MAX_PNG_CLIP`] or a path
/// past [`vectorcraft_geom::path::MAX_READ_ANCHORS`]. Reads only the chunks before the image data.
pub(crate) fn png_clip(png: &[u8]) -> Option<vectorcraft_geom::PathData> {
if !png.starts_with(b"\x89PNG\r\n\x1a\n") {
return None;
}
let keyword = [CLIP_KEYWORD.as_bytes(), &[0]].concat();
let json = super::ppi::png_chunks(png)
.take_while(|(ty, _)| *ty != b"IDAT")
.find_map(|(ty, data)| data.strip_prefix(keyword.as_slice()).filter(|_| ty == b"tEXt"))?;
if json.len() > MAX_PNG_CLIP {
return None;
}
vectorcraft_geom::path::with_anchor_budget(vectorcraft_geom::path::MAX_READ_ANCHORS, || serde_json::from_slice(json).ok())
}
/// An image as a document of its physical size at the resolution it declares (as Place sizes it;
/// 72 ppi, 1 px = 1 pt, when it declares none), the image named after the file.
pub(super) fn raster_doc(name: &str, bytes: &[u8]) -> Result<Document> {
let RasterImage { key, blob, width, height, ppi, .. } = raster_image(bytes)?;
let RasterImage { key, blob, width, height, ppi, clip } = raster_image(bytes)?;
let (sx, sy) = crate::cmd::place::pt_per_px(ppi);
let mut d = Document::new(width as f64 * sx, height as f64 * sy);
let layer = d.layers[0].id;
@@ -1138,7 +1180,7 @@ pub(super) fn raster_doc(name: &str, bytes: &[u8]) -> Result<Document> {
id,
NodeKind::Image(Box::new(ImageObject { key: key.clone(), width, height, xf, link: None, placement: Default::default(), pixels: None })),
);
let mut n = file_clipped(&mut d, n, psdread::clipping_path(bytes));
let mut n = file_clipped(&mut d, n, clip.map(|(path, _)| path));
n.name = Some(name.to_string());
d.images.insert(key, blob);
d.insert(Some(layer), 0, n).map_err(err)?;
File diff suppressed because one or more lines are too long
+44 -6
View File
@@ -87,8 +87,9 @@ fn version_6(r: &mut Reader<'_>, budget: &mut usize) -> Result<Vec<PsdSlice>, St
if count > MAX_SLICES {
return Err(format!("the file has {count} slices, more than the {MAX_SLICES} read"));
}
let one_after_another = records_one_after_another(Reader::new(r.rest()), count, *budget);
let mut out = vec![];
for _ in 0..count {
for i in 0..count {
// The ID and group ID.
r.take(8)?;
let origin = r.u32()?;
@@ -116,9 +117,10 @@ fn version_6(r: &mut Reader<'_>, budget: &mut usize) -> Result<Vec<PsdSlice>, St
format!("#{red:02x}{green:02x}{blue:02x}")
};
// Photoshop 7 and later may follow a record with a descriptor (version 16); a record that
// doesn't start one is the next slice. A descriptor read that uses up the budget is an
// error.
if r.rest().starts_with(&16u32.to_be_bytes()) {
// doesn't start one is the next slice. When the records follow one another, only the
// last one may be followed by a descriptor. A descriptor read that uses up the budget is
// an error.
if (!one_after_another || i + 1 == count) && r.rest().starts_with(&16u32.to_be_bytes()) {
let mut ahead = Reader::new(r.rest());
ahead.u32()?;
match descriptor(&mut ahead, 0, budget) {
@@ -139,6 +141,37 @@ fn version_6(r: &mut Reader<'_>, budget: &mut usize) -> Result<Vec<PsdSlice>, St
Ok(out)
}
/// Whether `r` holds `count` version 6 records one after another, followed by nothing or by one
/// descriptor (version 16) that reads within `budget`, as ag-psd writes them. A record whose ID is
/// 16 then isn't taken for a descriptor. Otherwise each record may be followed by a descriptor.
fn records_one_after_another(mut r: Reader<'_>, count: usize, mut budget: usize) -> bool {
if !(0..count).all(|_| skip_record(&mut r).is_ok()) {
return false;
}
r.rest().is_empty() || (r.rest().starts_with(&16u32.to_be_bytes()) && r.u32().is_ok() && descriptor(&mut r, 0, &mut budget).is_ok())
}
/// Reads past the version 6 record `r` starts with, in the layout [`version_6`] reads. Its strings
/// are checked and read past without being decoded.
fn skip_record(r: &mut Reader<'_>) -> Result<(), String> {
// The ID and group ID.
r.take(8)?;
if r.u32()? == 1 {
r.take(4)?;
}
units(r)?;
// The type and the rectangle.
r.take(20)?;
for _ in 0..4 {
units(r)?;
}
r.take(1)?;
units(r)?;
// The alignments and the background color.
r.take(12)?;
Ok(())
}
/// Versions 7 and 8: the descriptor's `slices` list, each slice an object.
fn from_descriptor(d: &[(String, Value)]) -> Result<Vec<PsdSlice>, String> {
let Some(Value::List(list)) = field(d, "slices") else { return Err("the slices' descriptor has no list of slices".into()) };
@@ -221,12 +254,17 @@ fn text_len(n: usize) -> Result<usize, String> {
/// A Unicode string: a count of UTF-16 units, then the units; trailing NULs dropped.
fn unicode(r: &mut Reader<'_>) -> Result<String, String> {
let n = text_len(r.u32()? as usize)?;
let bytes = r.take(n.checked_mul(2).ok_or(TRUNCATED)?)?;
let bytes = units(r)?;
let units: Vec<u16> = bytes.as_chunks::<2>().0.iter().map(|u| u16::from_be_bytes(*u)).collect();
Ok(String::from_utf16_lossy(&units).trim_end_matches('\0').to_string())
}
/// A Unicode string's units, as bytes: a count of UTF-16 units, then the units.
fn units<'a>(r: &mut Reader<'a>) -> Result<&'a [u8], String> {
let n = text_len(r.u32()? as usize)?;
r.take(n.checked_mul(2).ok_or(TRUNCATED)?)
}
/// A descriptor's value, as far as the slices need it.
#[derive(Clone, Debug, PartialEq)]
enum Value {
@@ -431,6 +431,98 @@ fn a_plain_image_replacing_a_clipped_psd_keeps_its_rotation() {
assert!(after.iter().zip(before).all(|(a, b)| (a - b).abs() < 1e-9), "{after:?} != {before:?}");
}
/// A square saved as "Square" and the clipping path naming it.
fn square_resources() -> Vec<u8> {
let square = saved_path(false, &[(true, &[[0.25, 0.25], [0.75, 0.25], [0.75, 0.75], [0.25, 0.75]])]);
[resource(2000, b"Square", &square), clipping_name(b"Square")].concat()
}
/// `bytes` written as `name` in `dir`, by its path.
fn write_file(dir: &std::path::Path, name: &str, bytes: &[u8]) -> String {
let p = dir.join(name);
std::fs::write(&p, bytes).unwrap();
p.to_string_lossy().into_owned()
}
/// links.relink and links.update put a linked PSD file's image in the clip group of the clipping
/// path its new file names, take that clip group's clipping path away when the new file names
/// none, and give it back when a later file names one again.
#[test]
fn relink_and_update_follow_the_clipping_path_of_a_linked_psd() {
let dir = vectorcraft_testkit::TempDir::new("psd-relink-clip");
let cut = write_file(&dir, "cut.psd", &red_psd(&triangle_resources()));
let square = write_file(&dir, "square.psd", &red_psd(&square_resources()));
let plain = write_file(&dir, "plain.psd", &red_psd(&[]));
let triangle = vec![[50.0, 0.0], [100.0, 50.0], [0.0, 50.0]];
let squared = vec![[25.0, 12.5], [75.0, 12.5], [75.0, 37.5], [25.0, 37.5]];
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
let r = s.execute("file.place", &json!({"path": cut, "at": [50, 25]})).unwrap();
let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), r["image"].as_u64().unwrap());
assert_eq!(clip_group(&s.doc().unwrap().doc, group), (triangle.clone(), true, NodeId(image)));
s.execute("links.relink", &json!({"ids": [image], "path": square})).unwrap();
assert_eq!(clip_group(&s.doc().unwrap().doc, group), (squared.clone(), true, NodeId(image)), "the new file's clipping path");
s.execute("links.relink", &json!({"ids": [image], "path": plain})).unwrap();
let d = &s.doc().unwrap().doc;
match d.node(group).map(|n| &n.kind) {
Some(NodeKind::Group { children, clip: false }) => assert_eq!(children.iter().map(|c| c.id.0).collect::<Vec<_>>(), [image]),
other => panic!("a plain group of the image: {other:?}"),
}
s.execute("links.relink", &json!({"ids": [image], "path": cut})).unwrap();
assert_eq!(clip_group(&s.doc().unwrap().doc, group), (triangle.clone(), true, NodeId(image)), "clipped again");
// The file is saved again with another clipping path.
std::fs::write(&cut, red_psd(&square_resources())).unwrap();
s.execute("links.update", &json!({"ids": [image]})).unwrap();
assert_eq!(clip_group(&s.doc().unwrap().doc, group), (squared, true, NodeId(image)), "links.update reads the clipping path again");
}
/// The PNG a PSD file's merged image is kept as holds the clipping path the file names, and only a
/// text chunk within the size limit that reads as a path gives one back.
#[test]
fn the_kept_png_holds_the_clipping_path_within_bounds() {
let img = raster_image(&red_psd(&triangle_resources())).unwrap();
let (path, rule) = img.clip.clone().expect("the file's clipping path");
assert_eq!(rule, vectorcraft_geom::FillRule::EvenOdd);
assert_eq!(super::load::png_clip(&img.blob.bytes), Some(path));
let plain = raster_image(&red_psd(&[])).unwrap();
assert!(plain.clip.is_none() && super::load::png_clip(&plain.blob.bytes).is_none());
let with = |text: String| vectorcraft_render::encode::png::with_text(plain.blob.bytes.to_vec(), &[("VectorCraft clip", text.into())]);
assert_eq!(super::load::png_clip(&with("not a path".into())), None);
assert_eq!(super::load::png_clip(&with(" ".repeat((16 << 20) + 1))), None, "a chunk past the limit is not read");
}
/// A plain image relinked to a PSD file that names a clipping path goes into a clip group of that
/// path, under the even-odd rule; a clipping mask made in the document stays around it.
#[test]
fn a_plain_image_relinked_to_a_clipped_psd_is_clipped_by_its_path() {
let dir = vectorcraft_testkit::TempDir::new("psd-relink-plain");
let plain = write_file(&dir, "plain.psd", &red_psd(&[]));
let cut = write_file(&dir, "cut.psd", &red_psd(&triangle_resources()));
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
let r = s.execute("file.place", &json!({"path": plain, "at": [50, 25]})).unwrap();
let image = NodeId(r["ids"][0].as_u64().unwrap());
s.execute("links.relink", &json!({"ids": [image.0], "path": cut})).unwrap();
let d = &s.doc().unwrap().doc;
let group = d.parent_of(image).expect("a clip group");
assert_eq!(clip_group(d, group), (vec![[50.0, 0.0], [100.0, 50.0], [0.0, 50.0]], true, image));
// The clipping path's fill rule changed in the document makes it the document's own mask: a
// relink keeps it and puts the file's clip group inside it.
let clip = match d.node(group).map(|n| &n.kind) {
Some(NodeKind::Group { children, .. }) => children[0].id,
other => panic!("{other:?}"),
};
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
if let Some(vectorcraft_doc::Node { kind: NodeKind::Path { rule, .. }, .. }) = doc.node_mut(clip) {
*rule = vectorcraft_geom::FillRule::NonZero;
}
s.execute("links.relink", &json!({"ids": [image.0], "path": cut})).unwrap();
let d = &s.doc().unwrap().doc;
let inner = d.parent_of(image).unwrap();
assert_eq!(d.parent_of(inner), Some(group), "the document's mask holds the file's clip group");
assert!(clip_group(d, inner).1, "the file's clip group is even-odd");
}
#[test]
fn a_fill_that_starts_with_all_pixels_puts_the_image_around_the_path() {
let hole = saved_path(true, &[(true, &[[0.25, 0.25], [0.75, 0.25], [0.75, 0.75], [0.25, 0.75]])]);
@@ -262,6 +262,32 @@ fn photoshop_7_descriptors_after_version_6_records_are_read_past() {
assert_eq!(names, ["a", "b"]);
}
#[test]
fn a_version_6_record_whose_id_is_16_is_a_slice_not_a_descriptor() {
// The 16th record has ID 16, group ID 0, origin 2, no name and the Image type: its first 18
// bytes also read as a descriptor of version 16 with no items.
let records: Vec<S> = (1..=17).map(|id| if id == 16 { user("", [1, 1, 4, 4]) } else { user("a", [0, 0, 5, 5]) }).collect();
let descriptor_after = [16u32.to_be_bytes().to_vec(), descriptor(&[("topOutset", D::Long(0))])].concat();
for trailing in [vec![], descriptor_after] {
let (s, r) = open(&with_resource(&psd(false), 1050, &v6(&records, &trailing)), json!({}));
assert!(warnings(&r).is_empty(), "{r}");
let got = slices(&s);
assert_eq!(got.len(), 17, "{got:?}");
assert_eq!((got[15].0, got[15].1.name.as_str()), (Rect::new(1.0, 1.0, 4.0, 4.0), ""));
assert_eq!(got[16].1.name, "a");
}
// A descriptor after each record whose class ID is four zero bytes, with no items, followed by
// records with no strings: the records don't also read one after another.
let empty = [ustr(""), 0u32.to_be_bytes().to_vec(), vec![0; 4], 0u32.to_be_bytes().to_vec()].concat();
let trailing = [16u32.to_be_bytes().to_vec(), empty].concat();
for rect in [[0, 0, 0, 0], [0, 0, 5, 5]] {
let (s, r) = open(&with_resource(&psd(false), 1050, &v6(&[user("", rect), user("", rect), user("", rect)], &trailing)), json!({}));
let w = warnings(&r);
assert!(!w.iter().any(|w| w.starts_with("the slices can't be read")), "{w:?}");
assert_eq!(slices(&s).len(), if rect[2] > 0 { 3 } else { 0 }, "{w:?}");
}
}
#[test]
fn version_6_descriptors_share_one_budget_of_values() {
// Each record's descriptor holds 2,501 values, well under the 200,000 one descriptor may hold;
@@ -1,7 +1,10 @@
//! SVG encodings, profiles and embedded fonts through the engine: the options reach the file,
//! files in each encoding open again, and `document.serialize` reads them as text.
use std::sync::Arc;
use serde_json::json;
use vectorcraft_doc::Document;
use super::*;
@@ -109,6 +112,106 @@ fn a_chosen_artboard_s_svg_keeps_an_object_whose_shadow_reaches_it() {
assert_eq!(paths(&mut s), 1, "its shadow reaches 10 pt onto the artboard");
}
/// A 100 × 100 document whose 3 pt. Round brush paints with a 20 pt nib, and the left edge of its
/// artboard.
fn nib_doc() -> (Document, f64) {
let mut d = Document::new(100.0, 100.0);
let mut lib = vectorcraft_brush::library(&d);
let Some(vectorcraft_brush::BrushKind::Calligraphic(c)) = lib.iter_mut().find(|b| b.name == "3 pt. Round").map(|b| &mut b.kind) else {
panic!("the 3 pt. Round brush")
};
c.size = 20.0;
vectorcraft_brush::store(&mut d, &lib);
let x0 = d.artboards[0].rect.x0;
(d, x0)
}
/// A line from (`x`, 40) to (`x`, 60) with a 1 pt stroke in `paint`, painted by the 20 pt nib of
/// [`nib_doc`] when `brushed`: the nib paints 10 pt either side of the line.
fn nib_line(d: &mut Document, x: f64, paint: vectorcraft_color::Paint, brushed: bool) -> vectorcraft_doc::Node {
let mut look = vectorcraft_doc::Appearance::basic(vectorcraft_color::Paint::None, paint, 1.0);
if brushed {
look.stroke_mut().unwrap().brush = Some("3 pt. Round".into());
}
let line = vectorcraft_geom::shapes::line((x, 40.0).into(), (x, 60.0).into());
vectorcraft_doc::Node::path(d.alloc_id(), line, look)
}
fn black() -> vectorcraft_color::Paint {
vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK)
}
/// A brushed path just left of a chosen artboard, whose brush art paints onto it, is in that
/// artboard's SVG and SVGZ; a brushed path too far off for its brush art to reach it is not.
#[test]
fn a_chosen_artboard_s_svg_keeps_brush_art_reaching_in() {
let (mut d, x0) = nib_doc();
let layer = d.layers[0].id;
let near = nib_line(&mut d, x0 - 5.0, black(), true);
let far = nib_line(&mut d, x0 - 200.0, black(), true);
let (near, far) = (d.insert(Some(layer), 0, near).unwrap(), d.insert(Some(layer), 0, far).unwrap());
let kept = export::art_over(&d, d.artboards[0].rect, &mut vectorcraft_render::Renderer::new());
assert!(kept.node(near).is_some(), "the nib paints 5 pt onto the artboard");
assert!(kept.node(far).is_none(), "the nib paints 190 pt short of the artboard");
let mut s = Session::new();
s.add_document(d, None);
let svg = s.execute("document.serialize", &json!({"format": "svg", "artboard": 0})).unwrap();
let svg = svg["text"].as_str().unwrap().to_string();
assert!(vectorcraft_testkit::svg_shapes(&svg) > 0, "{svg}");
let svgz = s.execute("document.serialize", &json!({"format": "svgz", "artboard": 0})).unwrap();
let svgz = vectorcraft_format::base64_decode(svgz["dataBase64"].as_str().unwrap()).unwrap();
assert_eq!(vectorcraft_svg::text_of(&svgz).unwrap(), svg, "the SVGZ is the SVG gzipped");
}
/// The room for brush art also keeps a brushed path in a plain group on a sublayer. A brushed
/// stroke without a paint draws no brush art, a clipping group's clip keeps its members' brush art
/// inside it, and a compound path is painted with its own appearance, not its paths': those stay
/// out when only brush art could reach the artboard.
#[test]
fn a_chosen_artboard_s_svg_keeps_nested_brush_art_but_not_unpainted_or_clipped_art() {
use vectorcraft_doc::{LayerColor, Node, NodeKind};
let (mut d, x0) = nib_doc();
let layer = d.layers[0].id;
let x = x0 - 5.0;
// A brushed line in a plain group on a sublayer.
let line = nib_line(&mut d, x, black(), true);
let nested = line.id;
let group = Node::new(d.alloc_id(), NodeKind::Group { children: vec![Arc::new(line)], clip: false });
let mut sublayer = Node::layer(d.alloc_id(), "Sublayer", LayerColor::Preset(1));
sublayer.children_mut().unwrap().push(Arc::new(group));
d.insert(Some(layer), 0, sublayer).unwrap();
// A brushed stroke without a paint.
let unpainted = nib_line(&mut d, x, vectorcraft_color::Paint::None, true);
let unpainted = d.insert(Some(layer), 0, unpainted).unwrap();
// A clipping group whose clip, far left of the artboard, holds a brushed line just off it.
let mut clip = Node::path(
d.alloc_id(),
vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(x0 - 100.0, 40.0, x0 - 90.0, 60.0)),
vectorcraft_doc::Appearance::basic(vectorcraft_color::Paint::None, vectorcraft_color::Paint::None, 0.0),
);
if let NodeKind::Path { clipping, .. } = &mut clip.kind {
*clipping = true;
}
let member = nib_line(&mut d, x, black(), true);
let clipped = Node::new(d.alloc_id(), NodeKind::Group { children: vec![Arc::new(clip), Arc::new(member)], clip: true });
let clipped = d.insert(Some(layer), 0, clipped).unwrap();
// Compound paths of a brushed line: plain itself, then brushed itself.
let mut compounds = vec![];
for own in [false, true] {
let member = nib_line(&mut d, x, black(), true);
let mut compound =
Node::new(d.alloc_id(), NodeKind::Compound { children: vec![Arc::new(member)], rule: vectorcraft_geom::FillRule::NonZero });
compound.appearance = nib_line(&mut d, x, black(), own).appearance;
compounds.push(d.insert(Some(layer), 0, compound).unwrap());
}
let kept = export::art_over(&d, d.artboards[0].rect, &mut vectorcraft_render::Renderer::new());
assert!(kept.node(nested).is_some(), "the brushed line in the group on the sublayer");
assert!(kept.node(unpainted).is_none(), "a brushed stroke without a paint");
assert!(kept.node(clipped).is_none(), "a clipping group whose clip misses the artboard");
assert!(kept.node(compounds[0]).is_none(), "a compound path that is not brushed itself");
assert!(kept.node(compounds[1]).is_some(), "a compound path that is brushed itself");
}
/// #3544: an SVG of one artboard on its own (an `artboard` or `range`, Export for Screens, an asset)
/// has the artboard's (or asset's) name as `<title>`; Save's SVG and Export for Screens' Full
/// Document keep the document's.
+246 -41
View File
@@ -187,9 +187,12 @@ impl Sets {
/// horizontal extent, would otherwise compare every pair). An open box inside a later box of
/// its group, ending no further right, is closed early, and a box inside an open box of its group,
/// ending no further right, isn't opened: whatever overlaps it overlaps that box. An open box that
/// a later box of its group overlaps, starting lower and ending no further right or lower, keeps
/// only its part above the later box's top, so boxes staggered right and down each meet only the
/// one before. Fails only when cancelled ([`vectorcraft_doc::cancel`]).
/// a later box of its group overlaps and ends no further right than keeps only the part the later
/// box doesn't cover: its part above the later box's top when the later box starts lower and ends
/// no higher than it, and its part below the later box's bottom when the later box starts no lower
/// and ends higher than it. The open box's top then moves down in the tree, so boxes staggered right
/// and down, or right and up, each meet only the one before. Fails only when cancelled
/// ([`vectorcraft_doc::cancel`]).
pub(super) fn overlapping(bounds: &[Option<Rect>]) -> Result<Vec<Vec<usize>>, Cancelled> {
Ok(sweep(bounds, None)?.groups())
}
@@ -208,27 +211,25 @@ fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets,
};
let boxes: Vec<(usize, Rect)> = bounds.iter().enumerate().filter_map(|(i, b)| b.filter(finite).map(|b| (i, b))).collect();
let n = boxes.len();
// Each box's place in the tree: by top (then index).
let mut by_top: Vec<usize> = (0..n).collect();
by_top.sort_by(|&a, &b| boxes[a].1.y0.total_cmp(&boxes[b].1.y0).then(a.cmp(&b)));
let tops: Vec<f64> = by_top.iter().map(|&k| boxes[k].1.y0).collect();
let mut leaf = vec![0usize; n];
for (pos, &k) in by_top.iter().enumerate() {
leaf[k] = pos;
}
// The lowest bottom of the open boxes below each node (−∞: none open), in the tree of the
// boxes without transparency (every box without `see_through`) and the see-through boxes'.
let size = n.next_power_of_two().max(1);
let mut low = [vec![f64::NEG_INFINITY; 2 * size], if see_through.is_some() { vec![f64::NEG_INFINITY; 2 * size] } else { vec![] }];
let tree = |k: usize| usize::from(see_through.is_some_and(|s| s[boxes[k].0]));
let set = |low: &mut [f64], pos: usize, v: f64| {
let mut i = pos + size;
low[i] = v;
while i > 1 {
i /= 2;
low[i] = low[2 * i].max(low[2 * i + 1]);
}
// The places an open box's top can be at in the tree: a box's top, or just below a box's
// bottom, where a later box cuts it short (`-0.0` as `0.0`).
let mut places: Vec<f64> = boxes.iter().flat_map(|(_, b)| [b.y0 + 0.0, b.y1.next_up() + 0.0]).collect();
places.sort_by(f64::total_cmp);
places.dedup_by(|a, b| a.total_cmp(b).is_eq());
let place = |y: f64| {
let y = y + 0.0;
let p = places.partition_point(|t| t.total_cmp(&y).is_lt());
places.get(p).is_some_and(|t| t.total_cmp(&y).is_eq()).then_some(p)
};
// Each box's part still open, from its top to its bottom, and the place of its top while it
// is open.
let mut top: Vec<f64> = boxes.iter().map(|(_, b)| b.y0).collect();
let mut bottom: Vec<f64> = boxes.iter().map(|(_, b)| b.y1).collect();
let mut open: Vec<Option<usize>> = vec![None; n];
// The tree of the open boxes without transparency (every box without `see_through`) and the
// see-through boxes'.
let mut trees = [Open::new(places.len()), Open::new(if see_through.is_some() { places.len() } else { 0 })];
let tree = |k: usize| usize::from(see_through.is_some_and(|s| s[boxes[k].0]));
let mut by_left: Vec<usize> = (0..n).collect();
by_left.sort_by(|&a, &b| boxes[a].1.x0.total_cmp(&boxes[b].1.x0));
let mut by_right: Vec<usize> = (0..n).collect();
@@ -243,7 +244,9 @@ fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets,
while let Some(&c) = by_right.get(closing)
&& boxes[c].1.x1 < b.x0
{
set(&mut low[tree(c)], leaf[c], f64::NEG_INFINITY);
if let Some(p) = open[c].take() {
trees[tree(c)].take(p, c, &bottom);
}
closing += 1;
}
// The open boxes it joins with their top at most this bottom and their bottom at least
@@ -255,21 +258,32 @@ fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets,
Some(_) if shadows => &[0, 1],
Some(_) => &[1],
};
let below = tops.partition_point(|t| *t <= b.y1);
let below = places.partition_point(|t| *t <= b.y1);
met.clear();
for &t in looks {
let tr = &trees[t];
stack.clear();
stack.push((1, 0, size));
stack.push((1, 0, tr.size));
while let Some((node, lo, hi)) = stack.pop() {
work += 1;
if work.is_multiple_of(4096) {
vectorcraft_doc::cancel::check()?;
}
if lo >= below || low[t][node] < b.y0 {
if lo >= below || tr.low[node] < b.y0 {
continue;
}
if hi - lo == 1 {
met.push(by_top[lo]);
// The boxes with their top here, lowest bottom first.
for &(_, o) in tr.at[lo].iter().rev() {
if bottom[o] < b.y0 {
break;
}
work += 1;
if work.is_multiple_of(4096) {
vectorcraft_doc::cancel::check()?;
}
met.push(o);
}
continue;
}
let mid = (lo + hi) / 2;
@@ -288,30 +302,91 @@ fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets,
let ob = boxes[o].1;
see_through.is_none_or(|s| s[boxes[o].0]) && b.x1 <= ob.x1 && ob.y0 <= b.y0 && b.y1 <= ob.y1
});
// Whatever overlaps a box inside this one overlaps this one, and joins it when this one is
// see-through. Likewise, whatever later overlaps the part of an open box at or below this
// one's top, when that box ends no further right or lower than this one, overlaps this
// one: the open box then keeps only the part above this one's top.
let cut = b.y0.next_down();
// Whatever overlaps the open part of a box inside this one overlaps this one, and joins it
// when this one is see-through. Likewise, whatever later overlaps the part of an open box
// this one covers, when that box ends no further right than this one, overlaps this one:
// the open box then keeps only the part above this one's top, when this one reaches its
// bottom, or only the part below this one's bottom, when this one reaches its top.
for &o in &met {
sets.join(boxes[k].0, boxes[o].0);
let ob = boxes[o].1;
if !shadows || Some(o) == holder || b.x1 < ob.x1 || b.y1 < ob.y1 {
let Some(p) = open[o] else { continue };
if !shadows || Some(o) == holder || b.x1 < boxes[o].1.x1 {
continue;
}
if b.y0 <= ob.y0 {
set(&mut low[tree(o)], leaf[o], f64::NEG_INFINITY);
} else if holder.is_none() && cut < low[tree(o)][leaf[o] + size] {
set(&mut low[tree(o)], leaf[o], cut);
let (t, u) = (top[o], bottom[o]);
let tr = &mut trees[tree(o)];
if b.y0 <= t && u <= b.y1 {
tr.take(p, o, &bottom);
open[o] = None;
continue;
}
if holder.is_some() || (b.y1 < u && t < b.y0) {
continue;
}
let (t, u) = if u <= b.y1 { (t, b.y0.next_down()) } else { (b.y1.next_up(), u) };
// Every top it can get has a place; one without stays as it is.
let Some(q) = place(t) else { continue };
tr.take(p, o, &bottom);
(top[o], bottom[o]) = (t, u);
open[o] = (t <= u).then_some(q);
if t <= u {
tr.put(q, o, &bottom);
}
}
if holder.is_none() {
set(&mut low[tree(k)], leaf[k], b.y1);
if holder.is_none()
&& let Some(p) = place(b.y0)
{
open[k] = Some(p);
trees[tree(k)].put(p, k, &bottom);
}
}
Ok(sets)
}
/// The open boxes of [`sweep`] by the place of their tops, in a tree that knows the lowest bottom
/// below each of its branches.
struct Open {
size: usize,
/// The lowest bottom of the open boxes below each node (−∞: none open).
low: Vec<f64>,
/// The open boxes at each place, by bottom ([`order`]) and then index.
at: Vec<BTreeSet<(i64, usize)>>,
}
impl Open {
fn new(places: usize) -> Self {
let size = places.next_power_of_two().max(1);
Self { size, low: vec![f64::NEG_INFINITY; 2 * size], at: vec![BTreeSet::new(); places] }
}
/// Opens box `k` at place `p`, with its bottom `bottom[k]`.
fn put(&mut self, p: usize, k: usize, bottom: &[f64]) {
self.at[p].insert((order(bottom[k]), k));
self.fix(p, bottom);
}
/// Closes box `k` at place `p`, while its bottom is still `bottom[k]`.
fn take(&mut self, p: usize, k: usize, bottom: &[f64]) {
self.at[p].remove(&(order(bottom[k]), k));
self.fix(p, bottom);
}
fn fix(&mut self, p: usize, bottom: &[f64]) {
let mut i = p + self.size;
self.low[i] = self.at[p].last().map_or(f64::NEG_INFINITY, |&(_, k)| bottom[k]);
while i > 1 {
i /= 2;
self.low[i] = self.low[2 * i].max(self.low[2 * i + 1]);
}
}
}
/// `v` as an integer in the same order as [`f64::total_cmp`].
fn order(v: f64) -> i64 {
let b = v.to_bits() as i64;
b ^ (((b >> 63) as u64) >> 1) as i64
}
/// Boxes in blocks of nearby ones, each block with the box around it, to find the boxes a box
/// touches.
struct Blocks {
@@ -777,6 +852,136 @@ mod tests {
assert_eq!(sets.groups(), vec![(0..n).collect::<Vec<_>>()]);
}
/// `n` boxes of one size, each a little right of and above the one before, all overlapping and
/// none inside another.
fn staggered_up(n: usize) -> Vec<Option<Rect>> {
let w = 2.0 * n as f64;
(0..n).map(|i| Some(Rect::new(i as f64, -(i as f64), w + i as f64, w - i as f64))).collect()
}
/// Each box of a stagger right and up meets only the box before it, which keeps only its part
/// below the new box's bottom, not every box still open; so does each box of a stagger left and
/// down, which the sweep meets right and up.
#[test]
fn boxes_staggered_up_meet_only_the_box_before() {
let n = 512;
let bounds = staggered_up(n);
let all = vec![(0..n).collect::<Vec<_>>()];
let mut sets = sweep(&bounds, None).unwrap();
assert_eq!(sets.meets, n - 1);
assert_eq!(sets.groups(), every_pair(&bounds));
assert_eq!(sets.groups(), all);
let mut sets = sweep(&bounds, Some(&vec![true; n])).unwrap();
assert_eq!(sets.meets, n - 1);
assert_eq!(sets.groups(), all);
let mut reversed = bounds.clone();
reversed.reverse();
let mut sets = sweep(&reversed, None).unwrap();
assert_eq!(sets.meets, n - 1);
assert_eq!(sets.groups(), all);
let mut sets = sweep(&reversed, Some(&vec![true; n])).unwrap();
assert_eq!(sets.meets, n - 1);
assert_eq!(sets.groups(), all);
}
/// An open box cut short from above keeps the part a later box would meet without meeting the
/// box that cut it: a part below that box, a part further right, or any part when that box is
/// opaque or held; a box cut from above and from below keeps its middle.
#[test]
fn a_box_is_cut_short_from_above_only_where_the_later_box_covers_it() {
let k = Rect::new(5.0, -5.0, 15.0, 10.0);
let cases = [
// Below `k`: the last box overlaps only the bottom of the first.
("below", vec![Some(Rect::new(0.0, 0.0, 10.0, 20.0)), Some(k), Some(Rect::new(8.0, 15.0, 9.0, 25.0))], vec![true, true, false]),
// Further right than `k`: `k` cuts nothing and the last box overlaps the first.
("right", vec![Some(Rect::new(0.0, 0.0, 20.0, 20.0)), Some(k), Some(Rect::new(17.0, 2.0, 25.0, 4.0))], vec![true, true, false]),
// Just below `k`'s bottom, and touching it.
(
"edge",
vec![Some(Rect::new(0.0, 0.0, 10.0, 20.0)), Some(k), Some(Rect::new(8.0, 10.0, 9.0, 12.0)), Some(Rect::new(8.0, 10.5, 9.0, 12.0))],
vec![false, true, false, false],
),
// An opaque `k` doesn't join the opaque last box, which joins the see-through first one.
("opaque", vec![Some(Rect::new(0.0, 0.0, 10.0, 10.0)), Some(k), Some(Rect::new(6.0, -10.0, 7.0, 2.0))], vec![true, false, false]),
// A see-through `k` held by a see-through box around it isn't opened and cuts nothing short.
(
"held",
vec![
Some(Rect::new(0.0, -6.0, 30.0, 28.0)),
Some(Rect::new(1.0, 0.0, 10.0, 20.0)),
Some(k),
Some(Rect::new(6.0, 11.0, 7.0, 13.0)),
Some(Rect::new(6.0, 4.0, 7.0, 6.0)),
],
vec![true, false, true, false, false],
),
// Cut from above, then from below: a later box inside what is left joins the first.
(
"middle",
vec![
Some(Rect::new(0.0, 0.0, 10.0, 30.0)),
Some(Rect::new(2.0, -5.0, 12.0, 10.0)),
Some(Rect::new(3.0, 20.0, 13.0, 40.0)),
Some(Rect::new(5.0, 15.0, 6.0, 16.0)),
Some(Rect::new(5.0, 9.0, 6.0, 10.0)),
Some(Rect::new(5.0, 20.0, 6.0, 20.0)),
],
vec![false, true, true, false, false, false],
),
// Signed zeros, a point and a box that isn't finite.
(
"zeros",
vec![
Some(Rect::new(-0.0, -0.0, 4.0, 8.0)),
Some(Rect::new(0.0, -2.0, 6.0, -0.0)),
Some(Rect::new(1.0, 0.0, 1.0, 0.0)),
Some(Rect::new(2.0, f64::NEG_INFINITY, 3.0, 1.0)),
Some(Rect::new(3.0, f64::MAX, 3.0, f64::MAX)),
Some(Rect::new(3.5, 0.0, 3.5, 0.0)),
],
vec![false, true, false, true, true, false],
),
];
for (what, bounds, see) in cases {
assert_eq!(overlapping(&bounds).unwrap(), every_pair(&bounds), "{what}");
let mut sets = sweep(&bounds, Some(&see)).unwrap();
assert_eq!(sets.groups(), every_pair_joining(&bounds, |i, j| see[i] || see[j]), "{what}, with transparency");
let mut sets = sweep(&bounds, Some(&vec![true; bounds.len()])).unwrap();
assert_eq!(sets.groups(), every_pair(&bounds), "{what}, all see-through");
}
}
/// Boxes stepping right and alternately up and down, so that open boxes are cut short from
/// above and from below, of mixed sizes, some see-through, group as comparing every pair groups
/// them.
#[test]
fn boxes_stepping_up_and_down_group_as_comparing_every_pair() {
let mut seed = 0x6a09_e667_f3bc_c908u64;
let mut next = |m: f64| {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
(seed % 1000) as f64 / 1000.0 * m
};
for round in 0..40 {
let n = 10 + round * 3;
let mut y = 0.0;
let bounds: Vec<Option<Rect>> = (0..n)
.map(|i| {
let up = if (i / (1 + round % 3)) % 2 == 0 { -1.0 } else { 1.0 };
y += up * (next(4.0).floor() + 1.0);
let x = i as f64 + next(2.0).floor();
let (w, h) = (next(12.0).floor() + 4.0, next(16.0).floor() + 2.0);
Some(Rect::new(x, y, x + w, y + h))
})
.collect();
assert_eq!(overlapping(&bounds).unwrap(), every_pair(&bounds), "round {round}");
let see: Vec<bool> = (0..n).map(|_| next(1.0) < if round % 2 == 0 { 0.5 } else { 0.9 }).collect();
let mut sets = sweep(&bounds, Some(&see)).unwrap();
assert_eq!(sets.groups(), every_pair_joining(&bounds, |i, j| see[i] || see[j]), "round {round}, with transparency");
}
}
/// An open box keeps the part a later box would meet without meeting the box that cut it short:
/// a part lower than that box, a part further right, or any part when that box is opaque.
#[test]
+47
View File
@@ -53,6 +53,15 @@ pub fn specs() -> Vec<CommandSpec> {
always,
font_list
),
cmd!(
query "text.glyphCategories",
"Glyph Categories",
[],
None,
"{family, style?} the OpenType categories of the font's glyphs, what the Glyphs panel's Show menu lists after Alternates for Current Selection: from the font's GSUB table, the glyphs that the single, alternate, multiple and ligature substitutions of each kind's features give, each glyph once by id, in this order: `ligatures` (liga, dlig, hlig), `swashes` (swsh, cswh), `stylisticAlternates` (salt), `ss01` to `ss20`, `smallCaps` (smcp, c2sc), `ornaments` (ornm), `fractions` (frac, afrc, numr, dnom) and `figures` (lnum, onum, pnum, tnum); a kind without glyphs is left out; contextual lookups are not followed → {family, style, categories: [{id, name?: a stylistic set's name in the font, glyphs: [glyph id]}]} (style omitted: the family's first style; an error when the family or style isn't available)",
always,
glyph_categories
),
cmd!(
"text.rescanFonts",
"Refresh Font List",
@@ -1137,6 +1146,44 @@ fn font_list(_: &mut Session, p: &Value) -> Result<Value> {
}
}
/// `text.glyphCategories`: the OpenType categories of a font's glyphs
/// ([`vectorcraft_text::FontFace::glyph_categories`]).
fn glyph_categories(_: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "text.glyphCategories";
let text = |key: &str| match p.get(key) {
None | Some(Value::Null) => Ok(None),
Some(Value::String(s)) => Ok(Some(s.as_str())),
Some(_) => Err(bad(C, format!("`{key}` must be a string"))),
};
let family = text("family")?.ok_or_else(|| bad(C, "missing `family`"))?;
let db = vectorcraft_text::FontDb::global();
if !db.has_family(family) {
return Err(bad(C, format!("font family `{family}` is not available")));
}
let styles = db.styles(family);
let style = match text("style")? {
Some(style) => styles
.iter()
.find(|s| s.eq_ignore_ascii_case(style))
.cloned()
.ok_or_else(|| bad(C, format!("style `{style}` of `{family}` is not available")))?,
None => styles.first().cloned().unwrap_or_else(|| "Regular".into()),
};
let face = db.face(family, &style).ok_or_else(|| bad(C, format!("style `{style}` of `{family}` is not available")))?;
let categories: Vec<Value> = face
.glyph_categories()
.iter()
.map(|c| {
let mut v = json!({"id": c.kind.id(), "glyphs": c.glyphs});
if let Some(name) = &c.name {
v["name"] = json!(name);
}
v
})
.collect();
Ok(json!({"family": face.family, "style": face.style, "categories": categories}))
}
pub(crate) fn rescan(s: &mut Session, _: &Value) -> Result<Value> {
let db = vectorcraft_text::FontDb::global();
#[cfg(not(target_arch = "wasm32"))]
+11 -5
View File
@@ -534,7 +534,7 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
// Objects were given or selected, even when all of them are graph design art left out below: the stroke mode is then
// not one for new art.
let selected = !ids.is_empty();
let ids = super::appearance::drop_design_art(&s.doc()?.doc, ids);
let ids = super::appearance::drop_design_art_rows(s, ids, item, !stroke, C)?;
// How the gradient lies on a stroke (the panel's Stroke buttons).
let mode = match str_param(p, "strokeMode") {
None => None,
@@ -558,7 +558,7 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
_ => None,
});
let for_default = match p.get("aspect").and_then(Value::as_f64) {
Some(a) if a < 0.0 && !ids.is_empty() && default_kind != Some(GradientKind::Conic) => {
Some(a) if a < 0.0 && selected && default_kind != Some(GradientKind::Conic) => {
let mut q = p.clone();
q["aspect"] = json!(-a);
std::borrow::Cow::Owned(q)
@@ -568,7 +568,7 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
// A spread for selected gradients leaves a freeform default (which has no ends) as it is.
let spreads = matches!(spread_param(p), Ok(Some(sp)) if !sp.is_pad());
let for_default = match for_default {
q if spreads && !ids.is_empty() && default_kind == Some(GradientKind::Freeform) => {
q if spreads && selected && default_kind == Some(GradientKind::Freeform) => {
let mut q = q.into_owned();
if let Some(o) = q.as_object_mut() {
o.remove("spread");
@@ -579,8 +579,14 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
};
let new_default = apply_gradient_edit_in_model(&default_paint, &with_stored_stops(&for_default, &default_paint, &stored), None, &|_| true, model)
.map_err(|e| bad(C, e))?;
let freeform = str_param(p, "kind").and_then(GradientKind::parse) == Some(GradientKind::Freeform);
let of = super::appearance::reference_of(s, p, item, C)?;
// Only design art was given or selected: nothing changes, the defaults and the remembered paint included.
if selected && ids.is_empty() {
// An aligned `item` of the art alone is still checked: a row the art lacks, or that no other object has, is an error.
edit_items(s, &ids, item, of, C, "Gradient", !stroke, |_, _| Ok(()))?;
return Ok(json!({"ids": []}));
}
let freeform = str_param(p, "kind").and_then(GradientKind::parse) == Some(GradientKind::Freeform);
let shown_at = super::appearance::first_edited(s, item, of, &ids);
// The objects returned: with a design's art, those with a row equal to the art's.
let edited = edit_items(s, &ids, item, of, C, "Gradient", !stroke, |n, index| {
@@ -770,7 +776,7 @@ fn set_gradient_geom(s: &mut Session, p: &Value) -> Result<Value> {
if targets.is_empty() {
return Err(EngineError::Other("nothing selected".into()));
}
let targets = super::appearance::drop_design_art(&s.doc()?.doc, targets);
let targets = super::appearance::drop_design_art_rows(s, targets, item, !stroke, C)?;
let model = super::paint::new_color_model(s, &Value::Null);
let of = super::appearance::reference_of(s, p, item, C)?;
// The objects returned: with a design's art, those with a row equal to the art's.
+3 -3
View File
@@ -49,9 +49,9 @@ use generate::generate;
use series::default_series_color;
pub(crate) use series::{
LabelTextChange, capture_label_anti_alias, capture_label_changes, capture_label_object_opacity, capture_label_paragraphs, capture_label_rows,
capture_label_styles, capture_label_text, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, is_design_art,
label_object_opacity_differs, labels_in, paint_targets, plain_labels, series_group_marks, series_group_marks_where, series_groups_among,
series_marks_in, series_object_opacity_differs, shown_paint,
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,
series_groups_among, series_marks_in, series_object_opacity_differs, shown_paint, wedge_shades,
};
#[cfg(test)]
+63
View File
@@ -1,4 +1,5 @@
use vectorcraft_color::BlendMode;
use vectorcraft_doc::swatches::walk_with_masks;
use vectorcraft_geom::Shape;
use super::axis::radar_axis;
@@ -767,6 +768,68 @@ fn set_legend_fills(n: &mut Node, on_dark: &HashMap<NodeId, bool>) {
}
}
/// Whether each wedge shows a dark fill, for each pie in `n` (`n` itself or one inside it, opacity-mask art included)
/// with Legends in Wedges whose legend labels' fill is not their own, so a redraw sets it by its wedge. Read before a
/// paste links the pie's colors to the document's swatches, for [`follow_wedge_shades`].
pub(crate) fn wedge_shades(n: &Node) -> HashMap<NodeId, Vec<bool>> {
let mut out = HashMap::new();
walk_with_masks(n, &mut |m| {
if let Some(g) = m.extras().graph.as_deref()
&& g.kind == GraphKind::Pie
&& g.legend
&& g.pie_legend_in_wedges
&& !g.label_styles.legend_fill_is_own()
{
out.insert(m.id, pie_wedges(m).iter().map(|w| w.dark).collect());
}
});
out
}
/// Give the legend labels of each pie in `n` that [`wedge_shades`] read as `was` the contrast a redraw sets, where a
/// wedge now shows a fill of the other darkness: white on a dark wedge, black on a light one. Pies whose wedges all kept
/// their darkness keep their labels as they are.
pub(crate) fn follow_wedge_shades(n: &mut Node, was: &HashMap<NodeId, Vec<bool>>) {
let mut changed = vec![];
walk_with_masks(n, &mut |m| {
if let Some(before) = was.get(&m.id)
&& pie_wedges(m).iter().map(|w| w.dark).ne(before.iter().copied())
{
changed.push(m.id);
}
});
if !changed.is_empty() {
restore_contrast(n, &changed);
}
}
/// Set the legend labels of the pies `ids` in `n` (`n` itself or ones inside it, opacity-mask art included) as a redraw
/// sets them on their wedges.
fn restore_contrast(n: &mut Node, ids: &[NodeId]) {
if ids.contains(&n.id) {
let on_dark = match n.extras().graph.as_deref() {
Some(g) => redrawn_on_dark(n, g).unwrap_or_else(|| legend_on_dark(n, g)),
None => HashMap::new(),
};
set_legend_fills(n, &on_dark);
}
let holds = |c: &Node| {
let mut found = false;
walk_with_masks(c, &mut |m| found |= ids.contains(&m.id));
found
};
if n.extras().mask.as_ref().is_some_and(|m| holds(&m.art))
&& let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut())
{
restore_contrast(Arc::make_mut(&mut m.art), ids);
}
for c in n.children_mut().into_iter().flatten() {
if holds(c) {
restore_contrast(Arc::make_mut(c), ids);
}
}
}
/// The legend labels of graph `n`: the type in its Legend group, as [`own_labels`] finds them.
fn legend_labels(n: &Node) -> Vec<&Node> {
legend_in(n.children().map_or(&[], |c| c.as_slice()))
+258 -1
View File
@@ -454,7 +454,7 @@ fn an_edit_of_a_graph_designs_art_is_lost_when_the_graph_is_drawn_again() {
/// it, and edit the other objects they are given.
#[test]
fn paint_commands_leave_a_graph_designs_art_out() {
let (mut s, _, copy, art, mark) = design_art();
let (mut s, graph, copy, art, mark) = design_art();
let fill = top_row(&s, art, true);
let commands = [
("stroke.set", json!({"weight": 5})),
@@ -466,6 +466,7 @@ fn paint_commands_leave_a_graph_designs_art_out() {
("paint.swap", json!({})),
("paint.default", json!({})),
("paint.invert", json!({"item": fill, "stroke": false})),
("paint.invert", json!({})),
];
let (copy_was, art_was) = (look(&s, copy), look(&s, art));
for (cmd, p) in &commands {
@@ -489,6 +490,11 @@ fn paint_commands_leave_a_graph_designs_art_out() {
s.execute("select.set", &json!({"ids": [art.0]})).unwrap();
s.execute("stroke.set", &json!({"weight": 5})).unwrap();
assert_eq!(look(&s, art), art_was);
// Given the whole graph, Invert recolors the marks and leaves the art.
let mark_was = look(&s, mark);
s.execute("paint.invert", &json!({"ids": [graph.0]})).unwrap();
assert_eq!(look(&s, art), art_was);
assert_ne!(look(&s, mark), mark_was);
// A freeform gradient point is refused on the art alone.
refused_on_design_art(&mut s, "paint.freeform.addPoint", json!({"ids": [art.0], "at": [0, 0]}));
}
@@ -517,6 +523,182 @@ fn stroke_edits_of_selected_design_art_leave_the_new_art_stroke() {
assert_eq!(s.new_art_stroke().gradient_mode, mode, "paint.editGradient");
}
/// With only the art of a graph design given or selected, the gradient, swap, default and recolor commands leave the
/// paint for new art and the remembered colors as they are.
#[test]
fn paint_edits_of_design_art_alone_leave_the_defaults() {
let (mut s, _, _, art, _) = design_art();
let fill = top_row(&s, art, true);
s.execute("select.set", &json!({"ids": []})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
s.execute("stroke.set", &json!({"weight": 3})).unwrap();
let defaults = |s: &Session| format!("{:?}", (&s.paint, s.last_solid, &s.last_gradient, &s.recent_colors));
let commands = [
("paint.editGradient", json!({"kind": "linear"})),
("paint.editGradient", json!({"kind": "radial", "stroke": true})),
("paint.swap", json!({})),
("paint.default", json!({})),
("paint.invert", json!({"item": fill, "stroke": false})),
("paint.complement", json!({"item": fill, "stroke": false})),
("paint.invert", json!({})),
("paint.complement", json!({"stroke": true})),
("stroke.set", json!({"weight": 7})),
("stroke.weightUp", json!({})),
];
for (cmd, p) in &commands {
let was = defaults(&s);
let mut q = p.clone();
q["ids"] = json!([art.0]);
s.execute(cmd, &q).unwrap();
assert_eq!(defaults(&s), was, "{cmd}, given");
// Selecting the art makes the defaults take its paint.
s.execute("select.set", &json!({"ids": [art.0]})).unwrap();
let was = defaults(&s);
s.execute(cmd, p).unwrap();
assert_eq!(defaults(&s), was, "{cmd}, selected");
s.execute("select.set", &json!({"ids": []})).unwrap();
}
// A bad `item`, `aligned` or `target` is still an error with only design art given.
for bad in [
json!({"ids": [art.0], "item": "top"}),
json!({"ids": [art.0], "item": fill, "aligned": "yes"}),
json!({"ids": [art.0], "item": fill, "target": "nowhere"}),
json!({"ids": [art.0], "target": "nowhere"}),
] {
assert!(s.execute("paint.invert", &bad).is_err(), "{bad}");
assert!(s.execute("paint.complement", &bad).is_err(), "{bad}");
}
// So is an `item` the art has no row for, in each command that leaves the art out.
let steps = s.doc().unwrap().history.undo.len();
for (cmd, p) in [
("paint.invert", json!({})),
("stroke.set", json!({"weight": 2})),
("stroke.weightUp", json!({})),
("stroke.setAdvanced", json!({"swapArrows": true})),
("paint.editGradient", json!({"kind": "linear"})),
("paint.setGradientGeom", json!({"start": [0, 0], "end": [50, 50]})),
("object.setOverprint", json!({"fill": true})),
] {
let mut q = p.clone();
q["ids"] = json!([art.0]);
q["item"] = json!(99);
assert!(s.execute(cmd, &q).is_err(), "{cmd}");
}
// The art's stroke row named without `stroke` is a stroke row: the gradient commands succeed and change nothing.
let stroke_row = top_row(&s, art, false);
for p in [json!({"kind": "linear"}), json!({"start": [0, 0], "end": [50, 50]})] {
let cmd = if p.get("kind").is_some() { "paint.editGradient" } else { "paint.setGradientGeom" };
let mut q = p.clone();
q["ids"] = json!([art.0]);
q["item"] = json!(stroke_row);
s.execute(cmd, &q).unwrap();
}
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
// With nothing selected, the swap still swaps the defaults.
let was = defaults(&s);
s.execute("paint.swap", &json!({})).unwrap();
assert_ne!(defaults(&s), was);
}
/// A spread or a negative aspect for the art of a graph design alone changes nothing, whatever kind of gradient the
/// default fill is; a bad value is still an error.
#[test]
fn gradient_edits_of_design_art_alone_skip_the_default_kind_checks() {
let (mut s, _, _, art, _) = design_art();
for (default, p) in [("freeform", json!({"spread": "repeat"})), ("linear", json!({"aspect": -50}))] {
s.execute("select.set", &json!({"ids": []})).unwrap();
s.execute("paint.editGradient", &json!({"kind": default})).unwrap();
let (was, art_was, steps) = (format!("{:?}", s.paint), look(&s, art), s.doc().unwrap().history.undo.len());
let mut q = p.clone();
q["ids"] = json!([art.0]);
s.execute("paint.editGradient", &q).unwrap_or_else(|e| panic!("{q}: {e}"));
assert_eq!(format!("{:?}", s.paint), was, "{default}");
assert_eq!(look(&s, art), art_was, "{default}");
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{default}");
}
assert!(s.execute("paint.editGradient", &json!({"ids": [art.0], "spread": "sideways"})).is_err());
}
/// Invert given a group around a graph recolors the group's own fill and the series marks, and leaves the art of a
/// graph design as it is. With `target: "contents"` the group's own fill stays as it is.
#[test]
fn invert_of_a_group_recolors_its_own_fill_and_leaves_design_art() {
let (mut s, graph, _, art, mark) = design_art();
s.execute("select.set", &json!({"ids": [graph.0]})).unwrap();
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("appearance.addFill", &json!({"ids": [group.0]})).unwrap();
let row = top_row(&s, group, true);
s.execute("paint.setFill", &json!({"ids": [group.0], "item": row, "color": "#ff0000"})).unwrap();
let own = |s: &Session| format!("{:?}", s.doc().unwrap().doc.node(group).unwrap().appearance.items);
let (own_was, art_was, mark_was) = (own(&s), look(&s, art), look(&s, mark));
s.execute("paint.invert", &json!({"ids": [group.0]})).unwrap();
assert_ne!(own(&s), own_was, "the group's own fill");
assert_ne!(look(&s, mark), mark_was);
assert_eq!(look(&s, art), art_was);
// The color remembered is the group's own new fill, which the Fill proxy shows.
let Some(Paint::Solid { color, .. }) = s.doc().unwrap().doc.node(group).unwrap().proxy_paint_only(false, None).cloned() else {
panic!("the group's fill is not a solid color")
};
assert_eq!((s.last_solid, s.recent_colors.first().copied()), (color, Some(color)));
let (own_was, mark_was) = (own(&s), look(&s, mark));
s.execute("paint.invert", &json!({"ids": [group.0], "target": "contents"})).unwrap();
assert_eq!(own(&s), own_was, "target: contents");
assert_ne!(look(&s, mark), mark_was);
assert_eq!(look(&s, art), art_was);
}
/// Invert and Complement given a series group that holds only a graph design's art recolor the group's own fill and
/// remember that color, as the last color and the newest recent color. With several such groups the color remembered
/// is that of the first group whose fill changed.
#[test]
fn recoloring_a_group_of_design_art_alone_remembers_its_own_fill() {
// A fill of its own for `group`, painted `hex` (the color of a rectangle painted with it).
let paint_own = |s: &mut Session, group: NodeId, hex: &str| {
s.execute("appearance.addFill", &json!({"ids": [group.0]})).unwrap();
let t = NodeId(s.execute("shape.rectangle", &json!({"x": 700, "y": 700, "width": 5, "height": 5})).unwrap()["id"].as_u64().unwrap());
s.execute("paint.setFill", &json!({"ids": [t.0], "color": hex})).unwrap();
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let paint = d.node(t).unwrap().proxy_paint_only(false, None).unwrap().clone();
d.node_mut(group).unwrap().appearance.fill_at_mut(None).unwrap().paint = paint;
};
// Series 0's group with its own fill painted `hex`.
let painted_series = |hex: &str| {
let (mut s, graph, _, art, _) = design_art();
let group = series(s.doc().unwrap().doc.node(graph).unwrap(), 0).id;
paint_own(&mut s, group, hex);
(s, group, art)
};
for cmd in ["paint.invert", "paint.complement"] {
let (mut s, group, art) = painted_series("#ff0000");
let fill = |s: &Session| s.doc().unwrap().doc.node(group).unwrap().proxy_paint_only(false, None).unwrap().clone();
let (art_was, fill_was) = (look(&s, art), fill(&s));
s.execute(cmd, &json!({"ids": [group.0]})).unwrap();
assert_eq!(look(&s, art), art_was, "{cmd}");
assert_ne!(fill(&s), fill_was, "{cmd}: the group's fill is recolored");
let Paint::Solid { color, .. } = fill(&s) else { panic!("{cmd}: the group's fill is not a solid color") };
assert_eq!((s.last_solid, s.recent_colors.first().copied()), (color, Some(color)), "{cmd}");
}
// A gray fill is its own complement: nothing changes, and the remembered colors stay as they were.
let (mut s, group, _) = painted_series("#808080");
s.execute("select.set", &json!({"ids": []})).unwrap();
s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap();
let remembered = |s: &Session| format!("{:?}", (s.last_solid, &s.recent_colors));
let was = remembered(&s);
assert_eq!(s.execute("paint.complement", &json!({"ids": [group.0]})).unwrap()["changed"], json!(0));
assert_eq!(remembered(&s), was);
// Both series groups hold only the design's art: a gray one first and a red one, given together.
let (mut s, graph, _, _, _) = design_art();
s.execute("graph.column", &json!({"id": graph.0, "seriesIndexes": [1], "design": "Square"})).unwrap();
let groups = [0, 1].map(|i| series(s.doc().unwrap().doc.node(graph).unwrap(), i).id);
paint_own(&mut s, groups[0], "#808080");
paint_own(&mut s, groups[1], "#ff0000");
s.execute("paint.complement", &json!({"ids": [groups[0].0, groups[1].0]})).unwrap();
let Some(Paint::Solid { color, .. }) = s.doc().unwrap().doc.node(groups[1]).unwrap().proxy_paint_only(false, None).cloned() else {
panic!("the red group's fill is not a solid color")
};
assert_eq!((s.last_solid, s.recent_colors.first().copied()), (color, Some(color)));
}
/// `transparency.set` without `item` refuses the art of a graph design in a series, and given it with other objects
/// sets only theirs.
#[test]
@@ -596,6 +778,81 @@ fn expand_appearance_leaves_a_graph_designs_art() {
assert!(s.doc().unwrap().doc.node(NodeId(other)).is_none_or(|m| m.appearance.effects.is_empty()));
}
/// `effect` with `params`, as `effect.apply` gives it to an object.
fn an_effect(s: &mut Session, effect: &str, params: serde_json::Value) -> vectorcraft_doc::Effect {
let r = s.execute("shape.rectangle", &json!({"x": 700, "y": 20, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("effect.apply", &json!({"effect": effect, "ids": [r], "params": params})).unwrap();
s.doc().unwrap().doc.node(NodeId(r)).unwrap().appearance.effects[0].clone()
}
/// Expand Appearance of a graph neither lists the art of a design in a series whose own effect it leaves, nor adds an
/// image of that effect to the document.
#[test]
fn expand_appearance_lists_no_design_art_and_rasterizes_none() {
let (mut s, id, copy, _, mark) = design_art();
let shadow = an_effect(&mut s, "stylize.dropShadow", json!({}));
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(copy).unwrap().appearance.effects.push(shadow);
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [mark.0]})).unwrap();
let copy_was = look(&s, copy);
let images = |s: &Session| s.doc().unwrap().doc.images.len();
let before = images(&s);
s.execute("select.set", &json!({"ids": [mark.0]})).unwrap();
s.execute("effect.expandAppearance", &json!({})).unwrap();
let per_mark = images(&s) - before;
s.execute("edit.undo", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
let expanded = s.execute("effect.expandAppearance", &json!({})).unwrap();
assert_eq!(expanded["ids"], json!([mark.0]));
assert_eq!(look(&s, copy), copy_was);
assert_eq!(images(&s) - before, per_mark, "only the mark's shadow becomes an image");
}
/// A geometry effect of a series group that Expand Appearance bakes moves the art of a design in that series with the
/// marks.
#[test]
fn expand_appearance_moves_design_art_with_its_series_groups_effect() {
let (mut s, id, copy, _, _) = design_art();
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
let group = series(&n, 0).id;
let shift = an_effect(&mut s, "distort.transform", json!({"moveH": 50}));
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(group).unwrap().appearance.effects.push(shift);
let left = |s: &Session| {
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
series(&n, 0).children().unwrap()[0].geometric_bounds().unwrap().x0
};
let was = left(&s);
assert_eq!(series(&n, 0).children().unwrap()[0].id, copy);
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("effect.expandAppearance", &json!({})).unwrap();
assert!((left(&s) - was - 50.0).abs() < 1e-6, "{} then {}", was, left(&s));
}
/// The copies that a Transform effect of a series group makes of a design's art keep their own effects when Expand
/// Appearance bakes the series group's effect, as the art they copy does.
#[test]
fn expand_appearance_leaves_the_effects_of_design_art_copies() {
let (mut s, id, copy, _, _) = design_art();
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
let group = series(&n, 0).id;
let shadow = an_effect(&mut s, "stylize.dropShadow", json!({}));
let copies = an_effect(&mut s, "distort.transform", json!({"moveH": 50, "copies": 2}));
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
doc.node_mut(copy).unwrap().appearance.effects.push(shadow);
doc.node_mut(group).unwrap().appearance.effects.push(copies);
let shadows = |s: &Session| {
let mut count = 0;
s.doc().unwrap().doc.node(id).unwrap().walk(&mut |m| count += m.appearance.effects.iter().filter(|e| e.id == "stylize.dropShadow").count());
count
};
let images = |s: &Session| s.doc().unwrap().doc.images.len();
let before = images(&s);
assert_eq!(shadows(&s), 1);
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("effect.expandAppearance", &json!({})).unwrap();
assert_eq!(shadows(&s), 3, "the art and its two copies keep their shadows");
assert_eq!(images(&s), before, "no shadow becomes an image");
}
/// The commands that give rows, effects or graphic styles refuse the art of a graph design inside a series, given by
/// id (the design's copy or a path inside it) or selected: the graph draws that art again from the design.
#[test]
+135 -82
View File
@@ -698,6 +698,20 @@ fn clip_shape((frame, room): Clip) -> PathData {
shapes::rectangle(Rect::new(0.0, 0.0, room.0, room.1)).transformed(frame)
}
/// The clipping path an image's file draws it through, with the fill rule its clip group takes:
/// a DCS file's (nonzero) or a PSD or PSB file's (even-odd).
type FileClip = (PathData, FillRule);
/// The clipping path the file of image content `blob` draws it through, in its pixel space, as it
/// was kept when the file was read: a DCS file's ([`ImageBlob::separated_clip`]) or a PSD or PSB
/// file's ([`fileio::png_clip`]).
fn file_clip(blob: &ImageBlob) -> Option<FileClip> {
if let Some(path) = blob.separated_clip() {
return Some((path, FillRule::NonZero));
}
(blob.mime == "image/png").then(|| fileio::png_clip(&blob.bytes)).flatten().map(|path| (path, FillRule::EvenOdd))
}
/// What happens to the clip of an object a link update remakes.
enum ClipTo {
/// It stays as it is.
@@ -705,25 +719,25 @@ enum ClipTo {
/// It is clipped to this path (Placement Options' clip): the clipping path of the clip group
/// holding just it changes, else it goes into a new clip group.
Path(PathData),
/// It is clipped to this path, the clipping path its DCS file draws it through: as [`ClipTo::Path`],
/// except that a plain group holding just it (as [`ClipTo::Off`] leaves one) becomes a clip group
/// again.
File(PathData),
/// It is clipped to this path, the clipping path its file draws it through, under its fill
/// rule: as [`ClipTo::Path`], except that a plain group holding just it (as [`ClipTo::Off`]
/// leaves one) becomes a clip group again.
File(FileClip),
/// It goes into a new clip group of this path, inside the clip group that holds it.
Nest(PathData),
/// Placement Options clip it to `placement` while its DCS file draws it through `file`: it is
Nest(FileClip),
/// Placement Options clip it to `placement` while its file draws it through `file`: it is
/// clipped to `file` as [`ClipTo::File`] clips it, and the clip group holding it is clipped to
/// `placement` as [`ClipTo::Path`] clips an object. With no `file` (the new file lacks the
/// clipping path of the clip group holding it), that group stays as [`ClipTo::Off`] leaves it,
/// clipped to `placement`.
Both { file: Option<PathData>, placement: PathData },
/// Placement Options clip it to `placement` while its DCS file draws it through `file`, and the
Both { file: Option<FileClip>, placement: PathData },
/// Placement Options clip it to `placement` while its file draws it through `file`, and the
/// clip group holding just it is not its old file's: that clip group's clipping path becomes
/// `placement`, and it goes into a new clip group of `file` inside it.
BothInside { file: PathData, placement: PathData },
/// The clipping path of the clip group holding just it goes (a DCS file's clipping path that
/// its new file lacks): the group stays as a plain group of it, with its id, name, visibility
/// and transparency.
BothInside { file: FileClip, placement: PathData },
/// The clipping path of the clip group holding just it goes (its old file's clipping path,
/// which its new file lacks): the group stays as a plain group of it, with its id, name,
/// visibility and transparency.
Off,
}
@@ -756,25 +770,25 @@ fn same_path(a: &PathData, b: &PathData) -> bool {
}
/// The clip an image placed with `old_xf` takes when it shows `img`, read from a file, placed with
/// `new_xf`: Placement Options' clip `clip` when they clip it, and the clipping path a DCS file
/// draws `img` through, the file's clip group inside the placement's. When neither clips it, a clip
/// group holding just it whose clipping path `held` is its old DCS file's (`old_clip`, in the old
/// pixels, under the nonzero rule its clip groups get) goes.
/// `new_xf`: Placement Options' clip `clip` when they clip it, and the clipping path the file
/// (DCS, PSD or PSB) draws `img` through, the file's clip group inside the placement's. When
/// neither clips it, a clip group holding just it whose clipping path `held` is its old file's
/// (`old_clip`, in the old pixels, under the fill rule its clip groups get) goes.
fn clip_to(
old_xf: Affine,
old_clip: Option<&PathData>,
old_clip: Option<&FileClip>,
clip: Option<Clip>,
img: &RasterImage,
new_xf: Affine,
held: Option<(&PathData, FillRule)>,
) -> ClipTo {
// Whether the clip group holding just the image is the old DCS file's: a clipping path whose
// fill rule was changed in the document is not.
// Whether the clip group holding just the image is the old file's: a clipping path whose fill
// rule was changed in the document is not.
let file_held = match (old_clip, held) {
(Some(old), Some((held, rule))) => rule == FillRule::NonZero && same_path(&old.transformed(old_xf), held),
(Some((old, old_rule)), Some((held, rule))) => rule == *old_rule && same_path(&old.transformed(old_xf), held),
_ => false,
};
let file = img.clip.as_ref().map(|path| path.transformed(new_xf));
let file = img.clip.as_ref().map(|(path, rule)| (path.transformed(new_xf), *rule));
if let Some(clip) = clip {
let placement = clip_shape(clip);
return match file {
@@ -831,7 +845,7 @@ impl Nested<'_> {
fn root(&mut self, n: &mut Arc<Node>) {
if !(self.pick)(n) {
if let Some(placement) = self.update(n, true) {
*n = Arc::new(self.clip_group(Arc::clone(n), placement));
*n = Arc::new(self.clip_group(Arc::clone(n), (placement, FillRule::NonZero)));
}
return;
}
@@ -839,7 +853,8 @@ impl Nested<'_> {
let mut new = Arc::new(new);
let _ = self.update(&mut new, true);
*n = match clip {
ClipTo::Path(path) | ClipTo::File(path) | ClipTo::Nest(path) => Arc::new(self.clip_group(new, path)),
ClipTo::Path(path) => Arc::new(self.clip_group(new, (path, FillRule::NonZero))),
ClipTo::File(file) | ClipTo::Nest(file) => Arc::new(self.clip_group(new, file)),
ClipTo::Both { file, placement } => self.clip_both(new, file, placement),
ClipTo::BothInside { file, placement } => self.clip_both(new, Some(file), placement),
ClipTo::Keep | ClipTo::Off => new,
@@ -848,8 +863,8 @@ impl Nested<'_> {
/// `n` (outside the layer tree when `nested`) with the picked objects under it remade; it stays
/// the same node when none is there, and only the nodes on the way to one are copied. The
/// result is Placement Options' clip that `n` itself, now the clip group of a DCS file's
/// clipping path holding a picked object (or the plain group [`ClipTo::Off`] leaves), takes:
/// result is Placement Options' clip that `n` itself, now the clip group of a file's clipping
/// path holding a picked object (or the plain group [`ClipTo::Off`] leaves), takes:
/// the clipping path of the clip group holding just `n` becomes it, else `n` goes into a new
/// clip group of it.
#[must_use]
@@ -880,8 +895,8 @@ impl Nested<'_> {
match (self.update(&mut new, nested), clip_path) {
(None, _) if Arc::ptr_eq(&new, c) => {}
(None, _) => slots.push((i, new)),
(Some(placement), Some(path)) if i == 1 => slots.extend([(0, with_clip(path, placement)), (1, new)]),
(Some(placement), _) => slots.push((i, Arc::new(self.clip_group(new, placement)))),
(Some(placement), Some(path)) if i == 1 => slots.extend([(0, with_clip(path, placement, None)), (1, new)]),
(Some(placement), _) => slots.push((i, Arc::new(self.clip_group(new, (placement, FillRule::NonZero))))),
}
continue;
}
@@ -894,17 +909,22 @@ impl Nested<'_> {
let _ = self.update(&mut new, true);
match (clip, clip_path) {
(ClipTo::Keep, _) => slots.push((i, new)),
(ClipTo::Path(clip) | ClipTo::File(clip), Some(path)) if i == 1 => slots.extend([(0, with_clip(path, clip)), (1, new)]),
(ClipTo::Path(clip), Some(path)) if i == 1 => slots.extend([(0, with_clip(path, clip, None)), (1, new)]),
(ClipTo::File((clip, rule)), Some(path)) if i == 1 => slots.extend([(0, with_clip(path, clip, Some(rule))), (1, new)]),
(ClipTo::File(clip), None) if plain => reclipped = Some((clip, new)),
(ClipTo::Path(clip) | ClipTo::File(clip) | ClipTo::Nest(clip), _) => {
(ClipTo::Path(clip), _) => {
let group = self.clip_group(new, (clip, FillRule::NonZero));
slots.push((i, Arc::new(group)));
}
(ClipTo::File(clip) | ClipTo::Nest(clip), _) => {
let group = self.clip_group(new, clip);
slots.push((i, Arc::new(group)));
}
(ClipTo::Off, Some(_)) if i == 1 => declipped = Some(new),
(ClipTo::Off, _) => slots.push((i, new)),
// The file's clip group stays `n`, and the placement's clip goes around it.
(ClipTo::Both { file: Some(file), placement }, Some(path)) if i == 1 => {
slots.extend([(0, with_clip(path, file)), (1, new)]);
(ClipTo::Both { file: Some((file, rule)), placement }, Some(path)) if i == 1 => {
slots.extend([(0, with_clip(path, file, Some(rule))), (1, new)]);
around = Some(placement);
}
(ClipTo::Both { file: Some(file), placement }, None) if plain => {
@@ -917,7 +937,7 @@ impl Nested<'_> {
}
(ClipTo::BothInside { file, placement }, Some(path)) if i == 1 => {
let group = self.clip_group(new, file);
slots.extend([(0, with_clip(path, placement)), (1, Arc::new(group))]);
slots.extend([(0, with_clip(path, placement, None)), (1, Arc::new(group))]);
}
(ClipTo::Both { file, placement }, _) => slots.push((i, self.clip_both(new, file, placement))),
(ClipTo::BothInside { file, placement }, _) => slots.push((i, self.clip_both(new, Some(file), placement))),
@@ -958,27 +978,28 @@ impl Nested<'_> {
/// A clip group of `placement` holding `object`, inside a clip group of `file` when there is a
/// `file` ([`ClipTo::Both`] for an object no clip group holds yet).
fn clip_both(&mut self, object: Arc<Node>, file: Option<PathData>, placement: PathData) -> Arc<Node> {
fn clip_both(&mut self, object: Arc<Node>, file: Option<FileClip>, placement: PathData) -> Arc<Node> {
let object = match file {
Some(file) => Arc::new(self.clip_group(object, file)),
None => object,
};
Arc::new(self.clip_group(object, placement))
Arc::new(self.clip_group(object, (placement, FillRule::NonZero)))
}
/// A clip group of `object` clipped to `clip`, as [`clip_image_to`] makes one in the layers.
fn clip_group(&mut self, object: Arc<Node>, clip: PathData) -> Node {
/// A clip group of `object` clipped to `clip` under its fill rule, as [`new_clip_group`] makes
/// one in the layers.
fn clip_group(&mut self, object: Arc<Node>, clip: FileClip) -> Node {
let path = self.clipping_path(clip);
let group_id = NodeId(self.next);
self.next += 1;
Node::new(group_id, NodeKind::Group { children: vec![Arc::new(path), object], clip: true })
}
/// A clipping path of `clip`, with the next node id.
fn clipping_path(&mut self, clip: PathData) -> Node {
/// A clipping path of `clip` under its fill rule, with the next node id.
fn clipping_path(&mut self, (clip, rule): FileClip) -> Node {
let id = NodeId(self.next);
self.next += 1;
clipping_path(id, clip)
clipping_path(id, clip, rule)
}
}
@@ -1082,9 +1103,9 @@ fn placed_xf(xf: Affine, old: (f64, f64), old_pt: (f64, f64), new: (f64, f64), n
(frame * at * Affine::scale_non_uniform(size.0 / nw, size.1 / nh), (o.clip && over).then_some((frame, room)))
}
/// The clipping path of the clip group of `d` holding just object `id` becomes `path`; false when
/// no such clip group holds it.
fn set_clip_path(d: &mut Document, id: NodeId, path: PathData) -> bool {
/// The clipping path of the clip group of `d` holding just object `id` becomes `path`, under fill
/// rule `rule` when one is given; false when no such clip group holds it.
fn set_clip_path(d: &mut Document, id: NodeId, path: PathData, rule: Option<FillRule>) -> bool {
let clip_path = d.parent_of(id).and_then(|p| match &d.node(p)?.kind {
NodeKind::Group { children, clip: true } => match &children[..] {
[c, im] if im.id == id && matches!(c.kind, NodeKind::Path { clipping: true, .. }) => Some(c.id),
@@ -1093,8 +1114,9 @@ fn set_clip_path(d: &mut Document, id: NodeId, path: PathData) -> bool {
_ => None,
});
let Some(c) = clip_path else { return false };
if let Some(Node { kind: NodeKind::Path { path: p, .. }, .. }) = d.node_mut(c) {
if let Some(Node { kind: NodeKind::Path { path: p, rule: r, .. }, .. }) = d.node_mut(c) {
*p = path;
*r = rule.unwrap_or(*r);
}
true
}
@@ -1108,25 +1130,25 @@ fn clip_image(d: &mut Document, id: NodeId, clip: Clip) -> Result<()> {
/// Clip object `id` of `d` to `path`: the clipping path of the clip group holding just it changes,
/// else it goes into a new clip group.
fn clip_image_to(d: &mut Document, id: NodeId, path: PathData) -> Result<()> {
if set_clip_path(d, id, path.clone()) {
if set_clip_path(d, id, path.clone(), None) {
return Ok(());
}
new_clip_group(d, id, path)
new_clip_group(d, id, (path, FillRule::NonZero))
}
/// Clip object `id` of `d` to `path`, the clipping path its DCS file draws it through: the clipping
/// path of the clip group holding just it changes, a plain group holding just it (as [`unclip`]
/// leaves one) becomes a clip group again, else it goes into a new clip group.
fn clip_file_to(d: &mut Document, id: NodeId, path: PathData) -> Result<()> {
if set_clip_path(d, id, path.clone()) {
/// Clip object `id` of `d` to `path`, the clipping path its file draws it through, under its fill
/// rule: the clipping path of the clip group holding just it changes, a plain group holding just it
/// (as [`unclip`] leaves one) becomes a clip group again, else it goes into a new clip group.
fn clip_file_to(d: &mut Document, id: NodeId, (path, rule): FileClip) -> Result<()> {
if set_clip_path(d, id, path.clone(), Some(rule)) {
return Ok(());
}
let plain = d.parent_of(id).filter(|g| match d.node(*g).map(|n| &n.kind) {
Some(NodeKind::Group { children, clip: false }) => matches!(&children[..], [o] if o.id == id),
_ => false,
});
let Some(g) = plain else { return new_clip_group(d, id, path) };
let clip = clipping_path(d.alloc_id(), path);
let Some(g) = plain else { return new_clip_group(d, id, (path, rule)) };
let clip = clipping_path(d.alloc_id(), path, rule);
d.insert(Some(g), 0, clip)?;
if let Some(Node { kind: NodeKind::Group { clip, .. }, .. }) = d.node_mut(g) {
*clip = true;
@@ -1134,30 +1156,33 @@ fn clip_file_to(d: &mut Document, id: NodeId, path: PathData) -> Result<()> {
Ok(())
}
/// Clipping path `path` (a node) with its path changed to `clip`.
fn with_clip(path: &Node, clip: PathData) -> Arc<Node> {
/// Clipping path `path` (a node) with its path changed to `clip`, and its fill rule to `rule` when
/// one is given.
fn with_clip(path: &Node, clip: PathData, rule: Option<FillRule>) -> Arc<Node> {
let mut path = Node::clone(path);
if let NodeKind::Path { path: p, .. } = &mut path.kind {
if let NodeKind::Path { path: p, rule: r, .. } = &mut path.kind {
*p = clip;
*r = rule.unwrap_or(*r);
}
Arc::new(path)
}
/// A clipping path `id` of `path`, unpainted.
fn clipping_path(id: NodeId, path: PathData) -> Node {
/// A clipping path `id` of `path` under fill rule `rule`, unpainted.
fn clipping_path(id: NodeId, path: PathData, rule: FillRule) -> Node {
let none = vectorcraft_color::Paint::None;
let mut clip = Node::path(id, path, Appearance::basic(none.clone(), none, 0.0));
if let NodeKind::Path { clipping, .. } = &mut clip.kind {
if let NodeKind::Path { clipping, rule: r, .. } = &mut clip.kind {
*clipping = true;
*r = rule;
}
clip
}
/// Put object `id` of `d` into a new clip group of `path`, where it is.
fn new_clip_group(d: &mut Document, id: NodeId, path: PathData) -> Result<()> {
/// Put object `id` of `d` into a new clip group of `path`, under its fill rule, where it is.
fn new_clip_group(d: &mut Document, id: NodeId, (path, rule): FileClip) -> Result<()> {
let (par, index, _) = d.position(id).ok_or(EngineError::NoNode(id))?;
let image = d.remove(id)?;
let clip = clipping_path(d.alloc_id(), path);
let clip = clipping_path(d.alloc_id(), path, rule);
let group = Node::new(d.alloc_id(), NodeKind::Group { children: vec![std::sync::Arc::new(clip), image], clip: true });
d.insert(par, index, group)?;
Ok(())
@@ -1186,15 +1211,15 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio
let nested = nested_ids(d, ids);
if also.is_some() || !nested.is_empty() {
let pick = |n: &Node| matches!(n.kind, NodeKind::Image(_)) && (nested.contains(&n.id) || also.is_some_and(|also| shows(n, also, false)));
// The resolution of each content the images picked show, and the clipping path its DCS file
// The resolution of each content the images picked show, and the clipping path its file
// drew it through, looked up once each.
let mut old: BTreeMap<String, ((f64, f64), Option<PathData>)> = BTreeMap::new();
let mut old: BTreeMap<String, ((f64, f64), Option<FileClip>)> = BTreeMap::new();
d.visit_stored(|n, _| {
if let NodeKind::Image(im) = &n.kind
&& pick(n)
&& !old.contains_key(&im.key)
{
old.insert(im.key.clone(), (file_pt(d, &im.key), d.images.get(&im.key).and_then(ImageBlob::separated_clip)));
old.insert(im.key.clone(), (file_pt(d, &im.key), d.images.get(&im.key).and_then(file_clip)));
}
});
let mut make = |n: &Node, held: Option<(&PathData, FillRule)>| {
@@ -1220,8 +1245,9 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio
let o = PlacementOptions { preserve: force.unwrap_or(im.placement.preserve), ..im.placement };
let size = |w: u32, h: u32| (w as f64, h as f64);
let (xf, clip) = placed_xf(im.xf, size(im.width, im.height), file_pt(d, &im.key), size(img.width, img.height), new_pt, o);
// Placement Options' clip, else a DCS file's clipping path, read again with its plates.
let old_clip = d.images.get(&im.key).and_then(ImageBlob::separated_clip);
// Placement Options' clip, else the clipping path of a DCS file (read again with its
// plates) or of a PSD or PSB file.
let old_clip = d.images.get(&im.key).and_then(file_clip);
clips.push((*id, clip_to(im.xf, old_clip.as_ref(), clip, &img, xf, clip_path_of(d, *id))));
if let Some(n) = d.node_mut(*id)
&& let NodeKind::Image(im) = &mut n.kind
@@ -1235,8 +1261,8 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio
clips.into_iter().try_for_each(|(id, clip)| match clip {
ClipTo::Keep => Ok(()),
ClipTo::Path(path) => clip_image_to(d, id, path),
ClipTo::File(path) => clip_file_to(d, id, path),
ClipTo::Nest(path) => new_clip_group(d, id, path),
ClipTo::File(file) => clip_file_to(d, id, file),
ClipTo::Nest(file) => new_clip_group(d, id, file),
ClipTo::Off => unclip(d, id),
ClipTo::Both { file, placement } => {
match file {
@@ -1314,27 +1340,54 @@ pub(crate) fn file_hidden(path: &str, doc_path: Option<&str>) -> bool {
/// gray or missing names none: the SVG writes gray pixels colorized and leaves out an image
/// without pixels. The images of the art the SVG writes (opacity masks included) and of the
/// symbols, patterns and brushes that art uses, as Copy follows them, are checked: the SVG writes
/// no other resource. Hidden layers and objects are written only with
/// SVG Options › hidden layers kept (`hidden`), and template layers never ([`svg_written`]).
/// Always `false` without read roots in force.
pub(crate) fn svg_names_hidden_image(d: &Document, base: LinkBase, link: bool, hidden: bool) -> bool {
if crate::file_access::current().is_none() || !names_hidden_image(d, base, link) {
/// no other resource. A placed document's images are those of the art the SVG draws for it. Hidden
/// layers and objects are written only with SVG Options › hidden layers kept (`hidden`), in the
/// layers and in the symbols, patterns and graph designs alike, and template layers never. SVG Tiny
/// 1.2 (`tiny`) writes no opacity masks ([`svg_written`]). Always `false` without read roots in
/// force.
pub(crate) fn svg_names_hidden_image(d: &Document, base: LinkBase, link: bool, hidden: bool, tiny: bool) -> bool {
if crate::file_access::current().is_none() {
return false;
}
let art = d.layers.iter().filter_map(|l| svg_written(l, hidden)).collect();
names_hidden_image(&super::clipboard::Clipboard::gather(d, art).to_document(), base, link)
if !d.has_placed() && !names_hidden_image(d, base, link) {
return false;
}
// The writer draws placed documents' art with the pixels their files hold.
let placed = d.with_placed_art();
let d = &*placed;
let art = d.layers.iter().filter_map(|l| svg_written(d, l, hidden, tiny)).collect();
let mut out = super::clipboard::Clipboard::gather(d, art).to_document();
let written = |n: &std::sync::Arc<Node>| {
let empty = || Node::new(n.id, NodeKind::Group { children: vec![], clip: false });
std::sync::Arc::new(svg_written(d, n, hidden, tiny).unwrap_or_else(empty))
};
for s in &mut out.symbols {
s.art = written(&s.art);
}
for g in &mut out.graph_designs {
g.art = written(&g.art);
}
for p in &mut out.patterns {
p.art = p.art.iter().filter_map(|n| svg_written(d, n, hidden, tiny)).map(std::sync::Arc::new).collect();
}
names_hidden_image(&out, base, link)
}
/// `n` as the SVG writer writes it, or `None` when it writes none of it: a hidden layer or object
/// is left out unless `hidden`, a template layer's art always, and a disabled opacity mask's art.
/// Only layers and groups lose members; other objects keep theirs as they are.
fn svg_written(n: &Node, hidden: bool) -> Option<Node> {
/// `n` (an object of `d`) as the SVG writer writes it, or `None` when it writes none of it: a
/// hidden layer or object is left out unless `hidden`, a template layer's art always, a disabled
/// opacity mask's art, and with SVG Tiny 1.2 (`tiny`) every opacity mask's art. A placed document
/// is the art the writer draws for it. Only layers and groups lose members; other objects keep
/// theirs as they are.
fn svg_written(d: &Document, n: &Node, hidden: bool, tiny: bool) -> Option<Node> {
if !(n.visible || hidden) {
return None;
}
if matches!(n.kind, NodeKind::PlacedDocument(_)) {
return svg_written(d, &vectorcraft_render::effects::expand_live_deep(Some(d), n), hidden, tiny);
}
let mut n = n.clone();
let mask = n.extras().mask.as_deref().filter(|m| !m.disabled).and_then(|m| {
let art = svg_written(&m.art, hidden)?;
let mask = n.extras().mask.as_deref().filter(|m| !m.disabled && !tiny).and_then(|m| {
let art = svg_written(d, &m.art, hidden, tiny)?;
Some(Box::new(vectorcraft_doc::OpacityMask { art: std::sync::Arc::new(art), ..m.clone() }))
});
if n.extras().mask.is_some() {
@@ -1343,7 +1396,7 @@ fn svg_written(n: &Node, hidden: bool) -> Option<Node> {
match &mut n.kind {
NodeKind::Layer { template: true, children, .. } => children.clear(),
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => {
*children = children.iter().filter_map(|c| svg_written(c, hidden)).map(std::sync::Arc::new).collect();
*children = children.iter().filter_map(|c| svg_written(d, c, hidden, tiny)).map(std::sync::Arc::new).collect();
}
_ => {}
}
+1 -1
View File
@@ -38,7 +38,7 @@ pub use commands::specs;
pub(super) use compound::{as_clipping_path, make_clipping_path, release_clip};
pub(crate) use pixelgrid::{
align_new_object, can_align, keep_aligned_in, keep_compound_aligned, keep_pixel_aligned, refresh as refresh_pixel_aligned, resnap,
snap_if_aligned,
snap_if_aligned, snap_symbol_art,
};
pub(super) use shape::recut;
pub(crate) use transform::{apply_transform, preview_copies, scaling, transform_node, transform_patterns, transforms_objects};
+241 -2
View File
@@ -1,6 +1,9 @@
//! Transform panel › Align to Pixel Grid: an object's pixel-aligned property, and the snapping that
//! keeps the horizontal and vertical segments of a pixel-aligned object on the pixel grid
//! (<https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/pixel-preview-mode-for-web-graphics.html>).
//! (<https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/pixel-preview-mode-for-web-graphics.html>),
//! and Symbol Options › Align to Pixel Grid, which keeps a symbol's instances on the pixel grid.
use std::collections::HashMap;
use vectorcraft_doc::{AppearanceItem, LiveShape, StrokeAlign};
@@ -150,10 +153,234 @@ pub(crate) fn refresh(before: &Document, doc: &mut Document) {
keep_pixel_aligned(n, Scaling::default());
}
}
refresh_symbols(before, doc);
}
/// How far the linear part of an instance's transform may be from its symbol's natural size, as a
/// fraction of that size, for the instance to count as placed at actual size.
const ACTUAL_SIZE_TOLERANCE: f64 = 1e-9;
/// After any edit: Symbol Options › Align to Pixel Grid. The art of a pixel-aligned symbol snaps to
/// the pixel grid at the symbol's natural size ([`snap_symbol_art`]) when the symbol becomes
/// pixel-aligned, when its art or natural size changes, and when symbol editing mode for it ends
/// (while it is edited, the art snaps as the editing layer is written back to it). Every instance
/// of such a symbol then goes to whole points ([`snap_instance`]), and so does each instance of a
/// pixel-aligned symbol in an object the edit changed or added, the art of opacity masks included.
/// An instance in another symbol's art is placed by that symbol's instances and is left as it is.
/// A document without pixel-aligned symbols is not walked.
fn refresh_symbols(before: &Document, doc: &mut Document) {
let aligned = doc.pixel_aligned_symbols();
if aligned.is_empty() {
return;
}
let was = before.pixel_aligned_symbols();
let edited_before = before.symbol_edit.as_ref().map(|e| e.symbol.as_str());
let mut every = false;
for name in &aligned {
let art_before = before.symbols.iter().find(|s| &s.name == name).map(|s| &s.art);
let art_now = doc.symbols.iter().find(|s| &s.name == name).map(|s| &s.art);
let art_changed = match (art_before, art_now) {
(Some(b), Some(a)) => !Arc::ptr_eq(b, a),
_ => true,
};
let size_changed = before.symbol_natural_xf(name) != doc.symbol_natural_xf(name);
if !was.contains(name) || edited_before == Some(name.as_str()) || art_changed || size_changed {
snap_symbol_art(doc, name);
every = true;
}
}
let natural: HashMap<String, Affine> = aligned.iter().map(|name| (name.clone(), doc.symbol_natural_xf(name))).collect();
if every {
for layer in doc.layers.iter_mut() {
if holds_instance(layer, &natural) {
snap_instances_in(Arc::make_mut(layer), &natural);
}
}
return;
}
let (mut ids, mut masked) = (vec![], vec![]);
changed_instances(&before.layers, &doc.layers, &natural, &mut ids, &mut masked);
for id in ids {
if let Some(n) = doc.node_mut(id) {
snap_instance(n, &natural);
}
}
for id in masked {
if let Some(m) = doc.node_mut(id).and_then(|n| n.extras_if_any()).and_then(|e| e.mask.as_mut()) {
snap_instances_in(Arc::make_mut(&mut m.art), &natural);
}
}
}
/// Among the objects of `after` that differ from their counterparts in `before` (or are new), in
/// groups too: the instances of the symbols in `natural` (`ids`), and the objects whose opacity
/// mask art holds such instances (`masked`).
fn changed_instances(before: &[Arc<Node>], after: &[Arc<Node>], natural: &HashMap<String, Affine>, ids: &mut Vec<NodeId>, masked: &mut Vec<NodeId>) {
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
for (i, a) in after.iter().enumerate() {
let b = match before.get(i) {
Some(b) if b.id == a.id => Some(b),
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
};
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
continue;
}
if a.extras().mask.as_ref().is_some_and(|m| holds_instance(&m.art, natural)) {
masked.push(a.id);
}
if let NodeKind::SymbolInstance { symbol, .. } = &a.kind {
if natural.contains_key(symbol) {
ids.push(a.id);
}
} else if let Some(children) = a.children() {
changed_instances(b.and_then(|b| b.children()).map_or(&[], Vec::as_slice), children, natural, ids, masked);
}
}
}
/// Whether `n`, an object in it or the art of an opacity mask in it is an instance of a symbol in
/// `natural`.
fn holds_instance(n: &Node, natural: &HashMap<String, Affine>) -> bool {
matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if natural.contains_key(symbol))
|| n.extras().mask.as_ref().is_some_and(|m| holds_instance(&m.art, natural))
|| n.children().is_some_and(|ch| ch.iter().any(|c| holds_instance(c, natural)))
}
/// [`snap_instance`] on every instance of a symbol in `natural` in `n`, the art of its opacity
/// masks included. Only what holds such an instance is copied for editing.
fn snap_instances_in(n: &mut Node, natural: &HashMap<String, Affine>) {
snap_instance(n, natural);
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut())
&& holds_instance(&m.art, natural)
{
snap_instances_in(Arc::make_mut(&mut m.art), natural);
}
if let Some(children) = n.children_mut() {
for c in children.iter_mut() {
if holds_instance(c, natural) {
snap_instances_in(Arc::make_mut(c), natural);
}
}
}
}
/// Snap the art of pixel-aligned symbol `name` to the pixel grid as it is drawn at the symbol's
/// natural size: each path and compound path in it snaps as a pixel-aligned object does
/// ([`snap_object`]), measured from the symbol's origin. The art is stored again only when
/// something in it moved, and the answer says whether it did.
pub(crate) fn snap_symbol_art(doc: &mut Document, name: &str) -> bool {
let natural = doc.symbol_natural_xf(name);
let det = natural.determinant();
if !det.is_finite() || det.abs() < 1e-18 {
return false;
}
let Some(sym) = doc.symbols.iter_mut().find(|s| s.name == name) else { return false };
// Instances draw the art's strokes at their stored width, and the art of unlinked opacity
// masks, which `Node::transform` leaves alone, at the natural size too.
let mut art = (*sym.art).clone();
art.transform(natural, false);
transform_unlinked_masks(&mut art, natural);
if !snap_art(&mut art) {
return false;
}
let inverse = natural.inverse();
art.transform(inverse, false);
transform_unlinked_masks(&mut art, inverse);
sym.art = Arc::new(art);
true
}
/// Transform the art of every unlinked opacity mask in `n` by `xf`, in the art of other masks
/// too. Only what holds such a mask is copied for editing.
fn transform_unlinked_masks(n: &mut Node, xf: Affine) {
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut())
&& holds_unlinked_mask(&m.art, !m.linked)
{
let linked = m.linked;
let art = Arc::make_mut(&mut m.art);
if !linked {
art.transform(xf, false);
}
transform_unlinked_masks(art, xf);
}
if let Some(children) = n.children_mut() {
for c in children.iter_mut() {
if holds_unlinked_mask(c, false) {
transform_unlinked_masks(Arc::make_mut(c), xf);
}
}
}
}
/// Whether `n` is the art of an unlinked mask (`unlinked`), or it or an object in it, in the art of
/// its masks too, has an unlinked opacity mask.
fn holds_unlinked_mask(n: &Node, unlinked: bool) -> bool {
unlinked
|| n.extras().mask.as_ref().is_some_and(|m| holds_unlinked_mask(&m.art, !m.linked))
|| n.children().is_some_and(|ch| ch.iter().any(|c| holds_unlinked_mask(c, false)))
}
/// Snap every path and compound path in `n` ([`can_align`]) with [`snap_object`], the art of
/// opacity masks included (those of a compound path's paths too). Returns whether anything
/// changed.
fn snap_art(n: &mut Node) -> bool {
let mut moved = false;
if can_align(n) {
let was = n.clone();
snap_object(n, Scaling::default());
moved = *n != was;
if let Some(children) = n.children_mut() {
for c in children.iter_mut() {
if c.extras().mask.is_some() {
moved |= snap_mask(Arc::make_mut(c));
}
}
}
} else if let Some(children) = n.children_mut() {
for c in children.iter_mut() {
moved |= snap_art(Arc::make_mut(c));
}
}
// After the object itself, which a linked mask follows.
snap_mask(n) || moved
}
/// [`snap_art`] on the art of `n`'s opacity mask. Returns whether anything changed.
fn snap_mask(n: &mut Node) -> bool {
let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) else { return false };
let mut art = (*m.art).clone();
if !snap_art(&mut art) {
return false;
}
m.art = Arc::new(art);
true
}
/// Move symbol instance `n` to whole points when its transform places its symbol's art at the
/// symbol's natural size (`natural`, by symbol name), reflected across one axis or not. A scaled,
/// rotated (a half turn included) or sheared instance stays where it is.
fn snap_instance(n: &mut Node, natural: &HashMap<String, Affine>) {
let NodeKind::SymbolInstance { symbol, xf } = &mut n.kind else { return };
let Some(nat) = natural.get(symbol.as_str()) else { return };
let [a, b, c, d, e, f] = xf.as_coeffs();
let [na, _, _, nd, _, _] = nat.as_coeffs();
let near = |v: f64, to: f64| (v.abs() - to.abs()).abs() <= ACTUAL_SIZE_TOLERANCE * to.abs().max(1.0);
let actual =
near(a, na) && near(d, nd) && b.abs() <= ACTUAL_SIZE_TOLERANCE * na.abs().max(1.0) && c.abs() <= ACTUAL_SIZE_TOLERANCE * nd.abs().max(1.0);
// Flipped along both axes is a half turn, which counts as rotated.
let half_turn = a * na < 0.0 && d * nd < 0.0;
if !actual || half_turn || !e.is_finite() || !f.is_finite() {
return;
}
let (x, y) = (e.round(), f.round());
if x != e || y != f {
*xf = Affine::new([a, b, c, d, x, y]);
}
}
/// After a pass that moved what objects `ids` hold (Objects on Path placing its members): snap the
/// pixel-aligned objects in them to the pixel grid again.
/// pixel-aligned objects and the instances of pixel-aligned symbols in them to the pixel grid
/// again.
pub(crate) fn keep_aligned_in(doc: &mut Document, ids: &[NodeId]) {
for id in ids {
if doc.node(*id).is_some_and(holds_aligned)
@@ -162,6 +389,18 @@ pub(crate) fn keep_aligned_in(doc: &mut Document, ids: &[NodeId]) {
keep_pixel_aligned(n, Scaling::default());
}
}
let aligned = doc.pixel_aligned_symbols();
if aligned.is_empty() {
return;
}
let natural: HashMap<String, Affine> = aligned.iter().map(|name| (name.clone(), doc.symbol_natural_xf(name))).collect();
for id in ids {
if doc.node(*id).is_some_and(|n| holds_instance(n, &natural))
&& let Some(n) = doc.node_mut(*id)
{
snap_instances_in(n, &natural);
}
}
}
/// The objects of `after` that differ from their counterparts in `before` (or are new) and are
+9 -10
View File
@@ -126,14 +126,18 @@ fn kinds(p: &Value, cmd: &str, keys: [&str; 2]) -> Result<Vec<(bool, bool)>> {
.collect()
}
/// Each kind's item target and objects: (fill?, item, ids).
fn aims(s: &Session, p: &Value, cmd: &str, kinds: impl IntoIterator<Item = bool>) -> Result<Vec<(bool, ItemTarget, Vec<NodeId>)>> {
/// Each kind's item target and objects: (fill?, item, ids). With `edit`, the art of graph designs drawn in graph series
/// is left out, and an explicit item that the art left out has no row of that kind for is an error, as when the edit
/// resolves it on the other objects. Without it, the art is read with the other objects.
fn aims(s: &Session, p: &Value, cmd: &str, kinds: impl IntoIterator<Item = bool>, edit: bool) -> Result<Vec<(bool, ItemTarget, Vec<NodeId>)>> {
let item = item_target(s, p, cmd)?;
kinds
.into_iter()
.map(|fill| {
let it = item.of_kind(s, fill);
Ok((fill, it, it.targets(s, p)?))
let ids = it.targets(s, p)?;
let ids = if edit { super::appearance::drop_design_art_rows(s, ids, it, fill, cmd)? } else { ids };
Ok((fill, it, ids))
})
.collect()
}
@@ -159,12 +163,7 @@ pub(super) type OverprintJob = ((bool, ItemTarget, Vec<NodeId>), bool);
/// `object.setOverprint` aims, leaving out the art of graph designs drawn in graph series.
pub(super) fn overprint_jobs(s: &Session, p: &Value, cmd: &str, keys: [&str; 2]) -> Result<Vec<OverprintJob>> {
let kinds = kinds(p, cmd, keys)?;
let d = &s.doc()?.doc;
Ok(aims(s, p, cmd, kinds.iter().map(|k| k.0))?
.into_iter()
.map(|(fill, it, ids)| (fill, it, super::appearance::drop_design_art(d, ids)))
.zip(kinds.iter().map(|k| k.1))
.collect())
Ok(aims(s, p, cmd, kinds.iter().map(|k| k.0), true)?.into_iter().zip(kinds.iter().map(|k| k.1)).collect())
}
/// Apply `jobs` to `d`, adding the objects changed to `changed`.
@@ -203,7 +202,7 @@ fn attributes(s: &Session, p: &Value) -> Result<AttributesInfo> {
let d = &s.doc()?.doc;
let mut info = AttributesInfo { ids: targets(s, p)?, recent_urls: s.recent_urls.clone(), ..Default::default() };
super::attributes::fill_info(d, &mut info);
for (fill, item, ids) in aims(s, p, C, [true, false])? {
for (fill, item, ids) in aims(s, p, C, [true, false], false)? {
let mut all =
ids.iter().filter_map(|id| d.node(*id)).filter_map(|n| Some(flags(n, fill, item.resolve(&n.appearance, fill, C).ok()?))).flatten();
let same = all.next().and_then(|first| all.all(|b| b == first).then_some(first));
+82 -7
View File
@@ -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) 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 (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)
),
@@ -982,7 +982,13 @@ pub(super) fn restore_unpainted_stroke(ap: &mut Appearance, index: Option<usize>
}
fn swap(s: &mut Session, p: &Value) -> Result<Value> {
let ids = super::appearance::drop_design_art(&s.doc()?.doc, paint_targets(s, p)?);
let targets = paint_targets(s, p)?;
let given = !targets.is_empty();
let ids = super::appearance::drop_design_art(&s.doc()?.doc, targets);
// Only design art was given or selected: nothing changes, the defaults included.
if given && ids.is_empty() {
return ok();
}
if !ids.is_empty() {
// When every object comes out as it was, the document and its undo history stay as they are.
let before = s.doc()?.doc.clone();
@@ -1017,7 +1023,13 @@ fn swap(s: &mut Session, p: &Value) -> Result<Value> {
}
fn default_paint(s: &mut Session, p: &Value) -> Result<Value> {
let ids = super::appearance::drop_design_art(&s.doc()?.doc, paint_targets(s, p)?);
let targets = paint_targets(s, p)?;
let given = !targets.is_empty();
let ids = super::appearance::drop_design_art(&s.doc()?.doc, targets);
// Only design art was given or selected: nothing changes, the defaults included.
if given && ids.is_empty() {
return ok();
}
if !ids.is_empty() {
// When every object comes out as it was, the document and its undo history stay as they are.
let before = s.doc()?.doc.clone();
@@ -1086,10 +1098,26 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(
return Ok(json!({ "changed": changed as usize }));
}
let item = item_target(s, p, cmd)?.of_kind(s, !stroke);
// Read before the check below, so that a bad param (such as `target` or `aligned`, or an explicit `item` the art has
// no row for) is still an error.
let targets = super::appearance::drop_design_art_rows(s, item.targets(s, p)?, item, !stroke, cmd)?;
let of = match item {
ItemTarget::Item { .. } => super::appearance::reference_of(s, p, item, cmd)?,
ItemTarget::Top => None,
};
// Read before the check below too: `targets` reads no `target` for the topmost fill or stroke.
let contents = super::appearance::targets_contents(p)?;
let ids = super::appearance::drop_design_art(&s.doc()?.doc, ids);
// Only design art was given or selected: nothing changes, the defaults and remembered colors included.
if ids.is_empty() {
return Ok(json!({ "changed": 0 }));
}
let (r, shown_at) = match item {
ItemTarget::Item { .. } => {
let targets = super::appearance::drop_design_art(&s.doc()?.doc, item.targets(s, p)?);
let of = super::appearance::reference_of(s, p, item, cmd)?;
// Only design art was given or selected: nothing changes, the remembered colors included.
if targets.is_empty() {
return Ok(json!({ "changed": 0 }));
}
// The row shown is the one edited in the first object that has it: an aligned row maps to each object's equal row.
let shown_at = super::appearance::first_edited(s, item, of, &targets).and_then(|(id, it)| match it {
ItemTarget::Item { index, .. } => Some((id, Some(index))),
@@ -1105,9 +1133,56 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(
(json!({ "changed": changed }), shown_at)
}
// The proxy recolors its paints, including a colorized image's fill, without changing image pixels or pattern tiles.
// A given group's own fills and strokes change with the objects inside it, except with `target: "contents"`; other
// objects change as their paint targets do (a compound path's member stands for the compound path). Design art
// inside a given graph or series group is left out.
ItemTarget::Top => {
let q = json!({"fill": !stroke, "stroke": stroke, "includeImages": false, "includePatterns": false, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()});
(super::colorcmds::recolor(s, &q, cmd, label, f)?, leaf_targets(s, &ids)?.first().map(|id| (*id, None)))
let mut roots = vec![];
for id in &ids {
let n = s.doc()?.doc.node(*id);
let group =
!contents && n.is_some_and(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && !n.is_compound_shape());
if group {
roots.push(*id);
} else {
roots.extend(leaf_targets(s, &[*id])?);
}
}
let d = &s.doc()?.doc;
let mut seen = std::collections::HashSet::new();
roots.retain(|id| seen.insert(*id));
let roots = super::appearance::drop_design_art(d, roots);
if roots.is_empty() {
return Ok(json!({ "changed": 0 }));
}
let art = super::appearance::design_art_in(d, &roots).into_iter().collect();
// The fill or stroke the proxy shows of each group among the roots, before the edit.
let own = |d: &Document, id: NodeId| {
d.node(id)
.filter(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }))
.and_then(|n| n.proxy_paint_only(stroke, None))
.cloned()
};
let own_before: std::collections::HashMap<NodeId, Paint> = roots.iter().filter_map(|id| Some((*id, own(d, *id)?))).collect();
let q = json!({"fill": !stroke, "stroke": stroke, "includeImages": false, "includePatterns": false, "ids": roots.iter().map(|i| i.0).collect::<Vec<_>>()});
let r = super::colorcmds::recolor_except(s, &q, cmd, label, f, art)?;
// As the proxy shows a group: its own fill or stroke when the edit changed it, else the first object inside it
// that is not design art (which keeps its paint). The first object given that has either shows it.
let d = &s.doc()?.doc;
let mut shown_at = None;
for id in &ids {
if let Some(was) = own_before.get(id)
&& own(d, *id).as_ref() != Some(was)
{
shown_at = Some((*id, None));
break;
}
if let Some(leaf) = super::appearance::drop_design_art(d, leaf_targets(s, &[*id])?).first() {
shown_at = Some((*leaf, None));
break;
}
}
(r, shown_at)
}
};
// The paint remembered is one the edit recolored: a graph design's art that the item edit leaves out gives none.
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1
View File
@@ -104,6 +104,7 @@ pub(crate) fn read(bytes: &[u8], path: Option<&str>) -> Result<DcsArt> {
};
let blob = ImageBlob::separated_tiff_clipped(&p.separated, p.ppi, &files, clip.as_ref())
.ok_or_else(|| EngineError::Other("the plates can't be kept".into()))?;
let clip = clip.map(|path| (path, vectorcraft_geom::FillRule::NonZero));
let img = RasterImage { key: blob.content_key(), blob, width: p.separated.width, height: p.separated.height, ppi: p.ppi, clip };
let spots = p.separated.spots().map(|s| (s.name.clone(), s.cmyk)).collect();
Ok(DcsArt { img, xf: p.xf, page: p.page, clip: p.clip, spots, warnings: p.warnings })
@@ -624,6 +624,7 @@ pub(super) const ALLOWED: &[&str] = &[
"text.fonts",
"text.getRange",
"text.glyphAlternates",
"text.glyphCategories",
"text.insertInline",
"text.missingFonts",
"text.replaceFont",
+7 -4
View File
@@ -52,7 +52,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Randomize Colors",
[],
None,
"{map: rows as recolor.apply, order?: true (shuffle the new colours among the rows that aren't excluded), saturationBrightness?: false (random saturation and brightness, hue kept), seed?: 0} → {map: the rows with their new colours as keys}",
"{map: rows as recolor.apply (an excluded row, or a row whose from is empty, keeps its new color), order?: true (shuffle the new colours among the rows that aren't excluded and hold current colors), saturationBrightness?: false (random saturation and brightness, hue kept), seed?: 0} → {map: the rows with their new colours as keys}",
always,
randomize
),
@@ -1746,8 +1746,11 @@ fn randomize(_: &mut Session, p: &Value) -> Result<Value> {
let mut rng = Rng::new(super::menucmds::whole_or(p, "seed", 0, C)?);
let (order, saturation_brightness) = (switch_or(p, "order", true, C)?, switch_or(p, "saturationBrightness", false, C)?);
// Each new color with its row's tint and model: a tint moves with its color, and goes when
// the color changes; a model moves with its color.
let mut news: Vec<(Color, f32, Option<ModelRule>)> = rows.iter().filter_map(|r| r.new_color().map(|c| (c, r.tint, r.model))).collect();
// the color changes; a model moves with its color. A row with no current colors recolors
// nothing, so it keeps its new color and takes no other row's.
let takes = |r: &Row| !r.from.is_empty() && r.new_color().is_some();
let mut news: Vec<(Color, f32, Option<ModelRule>)> =
rows.iter().filter(|r| takes(r)).filter_map(|r| r.new_color().map(|c| (c, r.tint, r.model))).collect();
if order {
rng.shuffle(&mut news);
}
@@ -1765,7 +1768,7 @@ fn randomize(_: &mut Session, p: &Value) -> Result<Value> {
.iter()
.map(|r| {
let (to, tint, model) =
if r.new_color().is_some() { news.next().map_or((None, 1.0, None), |(c, t, m)| (Some(c), t, m)) } else { (r.to, r.tint, r.model) };
if takes(r) { news.next().map_or((None, 1.0, None), |(c, t, m)| (Some(c), t, m)) } else { (r.to, r.tint, r.model) };
let mut row = json!({"from": r.from.iter().map(Match::to_json).collect::<Vec<_>>(), "to": to.as_ref().map(key_str)});
if r.exclude {
row["exclude"] = json!(true);
+9 -4
View File
@@ -234,8 +234,11 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result<Value> {
let item = item_target(s, p, C)?.of_kind(s, false);
let mut ids = if item == ItemTarget::Top { own_stroke_or_leaves(s, p)? } else { item.targets(s, p)? };
let new_art = no_targets(&ids, p);
let given = !ids.is_empty();
// The art of a graph design in a series keeps the design's stroke.
ids = super::appearance::drop_design_art(&s.doc()?.doc, ids);
ids = super::appearance::drop_design_art_rows(s, ids, item, false, C)?;
// With only design art, the weight for new art stays as it is too.
let only_design_art = given && ids.is_empty();
if item == ItemTarget::Top {
// Images and symbol instances take no stroke from the panel.
let d = &s.doc()?.doc;
@@ -329,7 +332,9 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result<Value> {
})?;
// Commit the new-art template only after the complete request is validated
// and the selected artwork edit has succeeded.
if let Some(w) = change.weight {
if let Some(w) = change.weight
&& !only_design_art
{
s.paint.stroke_width = w;
}
if new_art && let Some(st) = s.new_art_stroke_mut() {
@@ -372,7 +377,7 @@ fn stroke_step(s: &mut Session, p: &Value, up: bool) -> Result<Value> {
}
return Ok(json!({"objects": 0}));
}
let ids = super::appearance::drop_design_art(&s.doc()?.doc, ids);
let ids = super::appearance::drop_design_art_rows(s, ids, item, false, c)?;
let label = if up { "Stroke Weight Up" } else { "Stroke Weight Down" };
edit_items(s, &ids, item, None, c, label, false, |n, index| {
if index.is_none()
@@ -517,7 +522,7 @@ fn stroke_advanced(s: &mut Session, p: &Value) -> Result<Value> {
let ids = item.targets(s, p)?;
let new_art = no_targets(&ids, p);
// The art of a graph design in a series keeps the design's stroke.
let ids = super::appearance::drop_design_art(&s.doc()?.doc, ids);
let ids = super::appearance::drop_design_art_rows(s, ids, item, false, C)?;
let arrows_and_profile = |st: &mut StrokeLayer| {
if let Some(sc) = scale {
st.arrow_scale = sc;
+18
View File
@@ -529,6 +529,24 @@ pub(crate) fn sync(before: &Document, d: &mut Document) -> Result<()> {
};
d.symbols[index].art = Arc::new(new_art);
follow_objects(d, &se.symbol, (&old, old_group), (&art, group));
// A pixel-aligned symbol stores its art on the pixel grid while it is edited too, and the
// editing layer shows the snapped art.
if d.symbol_pixel_aligned(&se.symbol) && super::object::snap_symbol_art(d, &se.symbol) {
let stored = &d.symbols[index].art;
let snapped: Vec<Arc<Node>> = if group { stored.children().map(|c| c.to_vec()).unwrap_or_default() } else { vec![stored.clone()] };
let mut snapped = snapped.into_iter().map(|n| {
let mut n = (*n).clone();
n.transform(se.xf, false);
Arc::new(n)
});
if let Some(ch) = d.node_mut(se.layer).and_then(Node::children_mut) {
for c in ch.iter_mut().filter(|c| !c.is_ruler_guide()) {
if let Some(n) = snapped.next() {
*c = n;
}
}
}
}
if let Some(e) = d.symbol_edit.as_mut() {
e.changed = true;
e.group = group;
+2 -1
View File
@@ -499,12 +499,13 @@ fn instance(name: &str) -> Node {
}
/// Symbol `from`'s Symbol Options in `src` (natural size, registration, export type, 9-slice
/// guides) given to symbol `to` of `d`.
/// guides, Align to Pixel Grid) given to symbol `to` of `d`.
fn copy_options(src: &Document, from: &str, d: &mut Document, to: &str) {
set_natural_size(d, to, Some(natural_size(src, from)));
d.set_symbol_registration(to, src.symbol_registration(from));
d.set_symbol_export_type(to, src.symbol_export_type(from));
d.set_symbol_nine_slice(to, src.symbol_nine_slice(from));
d.set_symbol_pixel_aligned(to, src.symbol_pixel_aligned(from));
}
fn builtin_info(b: &BuiltinSymbolLibrary) -> LibraryInfo {
File diff suppressed because one or more lines are too long
+26
View File
@@ -11,6 +11,7 @@
//! visibility, `@` for image, no prefix for text). `variable.loadLibrary` replaces the variables and data sets with the
//! variables and data sets of a variable library, the XML file of the reference app's Save
//! Variable Library, and `variable.saveLibrary` writes the variables and data sets as one.
//! `variable.import` (the panel's Import…) runs one of the two readers by the file's extension.
//! Agents reach every command through `run_command`, like all engine commands.
use std::collections::{BTreeMap, BTreeSet};
@@ -865,6 +866,22 @@ fn dataset_step(s: &mut Session, cmd: &str, forward: bool) -> Result<Value> {
apply_dataset(s, &name)
}
/// The Variables panel's Import…: a data source file read by its extension, a CSV, TSV or TXT
/// file as `dataset.import` reads it and an XML file as `variable.loadLibrary` reads it. The
/// result is that command's, with `format` set to `csv` or `xml`.
fn variable_import(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "variable.import";
let path = str_param(p, "path").ok_or_else(|| bad(C, "missing `path`"))?;
let ext = std::path::Path::new(path).extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase);
let (format, mut out) = match ext.as_deref() {
Some("csv" | "tsv" | "txt") => ("csv", dataset_import(s, &json!({"path": path}))?),
Some("xml") => ("xml", load_library(s, &json!({"path": path}))?),
_ => return Err(bad(C, "Import reads a data source file ending in .csv, .tsv, .txt or .xml")),
};
out["format"] = json!(format);
Ok(out)
}
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
@@ -1057,6 +1074,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
dataset_import
),
cmd!(
"variable.import",
"Import…",
["Window", "Variables"],
None,
"{path} import a data source file, chosen by its extension (any case): a .csv, .tsv or .txt file is read as dataset.import reads it, and an .xml file as variable.loadLibrary reads it, with their refusals and undo steps; any other extension, or none, is refused before the file is read → the result of that command with `format`: `csv` or `xml`",
has_doc,
variable_import
),
cmd!(
query "dataset.export",
"Export Data Sets…",
+3
View File
@@ -179,6 +179,9 @@ pub struct Session {
/// The Scripts folder, whose scripts File › Scripts lists; `None`: no folder
/// ([`Session::attach_scripts_dir`]).
scripts_dir: Option<std::path::PathBuf>,
/// The folder of File Info's metadata templates; `None`: no folder
/// ([`Session::attach_metadata_templates_dir`]).
metadata_templates_dir: Option<std::path::PathBuf>,
/// The folder of the New Document profiles `file.new` starts documents from; `None`: none,
/// every document starts with the defaults ([`Session::attach_new_doc_profiles`]).
new_doc_profile_dir: Option<std::path::PathBuf>,
+5 -1
View File
@@ -2012,7 +2012,11 @@ impl Session {
Ok(Ok(Progress::Done(_))) if job.host.dialogs.unused() > 0 => {
let n = job.host.dialogs.unused();
let kind = LimitKind::Host;
let message = format!("`answers` has {n} answer{} the script did not use", if n == 1 { "" } else { "s" });
let message = if n == 1 {
format!("`answers` has {n} answer the script did not use")
} else {
format!("`answers` has {n} answers the script did not use")
};
Some(self.script_failed(job, &RunError { kind: RunErrorKind::Limit(kind), message, line: 0, column: 0 }))
}
Ok(Ok(Progress::Done(_))) => {
+1
View File
@@ -93,6 +93,7 @@ impl Session {
color_settings_file: None,
plugin_dir: None,
scripts_dir: None,
metadata_templates_dir: None,
new_doc_profile_dir: None,
plugin_output: None,
plugin_install_approval: None,
+79
View File
@@ -3310,6 +3310,85 @@ fn flare_ring_seed_moves_only_the_rings() {
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
}
/// `shape.ellipse` without `anchors`, or with 4, draws the live ellipse it always drew.
#[test]
fn ellipse_with_four_anchors_is_the_live_ellipse() {
let mut s = session();
let draw = |s: &mut Session, extra: Option<u64>| {
let mut p = json!({"x": 40, "y": 30, "width": 120, "height": 80});
if let Some(n) = extra {
p["anchors"] = json!(n);
}
let id = NodeId(s.execute("shape.ellipse", &p).unwrap()["id"].as_u64().unwrap());
s.doc().unwrap().doc.node(id).unwrap().clone()
};
let (plain, four) = (draw(&mut s, None), draw(&mut s, Some(4)));
for n in [&plain, &four] {
assert!(matches!(n.live_shape(), Some(vectorcraft_doc::LiveShape::Ellipse { .. })), "{:?}", n.live_shape());
assert_eq!(n.path_data().unwrap().anchor_count(), 4);
}
assert_eq!(plain.path_data(), four.path_data());
assert_eq!(plain.live_shape(), four.live_shape());
}
/// Any other count draws a closed plain path of that many smooth anchors on the ellipse, its
/// bounds the typed size, as one undo step.
#[test]
fn ellipse_anchors_draw_that_many_anchors_on_the_ellipse() {
let mut s = session();
let (x, y, w, h) = (40.0, 30.0, 120.0, 80.0);
let (c, rx, ry) = (Point::new(x + w / 2.0, y + h / 2.0), w / 2.0, h / 2.0);
for n in [2u64, 3, 5, 6, 8] {
let undo = s.doc().unwrap().history.undo.len();
let id = NodeId(s.execute("shape.ellipse", &json!({"x": x, "y": y, "width": w, "height": h, "anchors": n})).unwrap()["id"].as_u64().unwrap());
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "{n}: one undo step");
let node = s.doc().unwrap().doc.node(id).unwrap();
assert!(node.live_shape().is_none(), "{n}: a plain path");
let path = node.path_data().unwrap();
assert_eq!(path.subpaths.len(), 1);
let sp = &path.subpaths[0];
assert!(sp.closed, "{n}");
assert_eq!(sp.anchors.len() as u64, n);
for a in &sp.anchors {
assert_eq!(a.kind, vectorcraft_geom::AnchorKind::Smooth, "{n}");
let on = ((a.p.x - c.x) / rx).powi(2) + ((a.p.y - c.y) / ry).powi(2);
assert!((on - 1.0).abs() < 0.01, "{n}: {:?} is off the ellipse ({on})", a.p);
}
let b = path.bounds().unwrap();
for (got, want) in [(b.x0, x), (b.y0, y), (b.x1, x + w), (b.y1, y + h)] {
assert!((got - want).abs() < 1e-6, "{n}: bounds {b:?}");
}
}
// The first anchor is the left one, and they run clockwise on screen, as the live ellipse's do.
let id = NodeId(s.execute("shape.ellipse", &json!({"x": x, "y": y, "width": w, "height": h, "anchors": 8})).unwrap()["id"].as_u64().unwrap());
let sp = s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].clone();
assert!(sp.anchors[0].p.distance(Point::new(x, c.y)) < 1e-6, "{:?}", sp.anchors[0].p);
assert!(sp.anchors[2].p.distance(Point::new(c.x, y)) < 1e-6, "{:?}", sp.anchors[2].p);
}
/// An `anchors` that is not a whole number from 2 to 1000 is refused, and nothing is drawn.
#[test]
fn ellipse_refuses_a_bad_anchor_count() {
let mut s = session();
let undo = s.doc().unwrap().history.undo.len();
let range = |got: &str| format!("`anchors` must be a whole number between 2 and 1000 (got {got})");
for (bad, want) in [
(json!(0), range("0")),
(json!(1), range("1")),
(json!(2.5), range("2.5")),
(json!(-3), range("-3")),
(json!(1001), range("1001")),
(json!("x"), "`anchors` must be a number, not \"x\"".to_string()),
(json!("6"), "`anchors` must be a number, not \"6\"".to_string()),
(json!(true), "`anchors` must be a number, not true".to_string()),
] {
let e = s.execute("shape.ellipse", &json!({"x": 0, "y": 0, "width": 50, "height": 50, "anchors": bad})).unwrap_err().to_string();
assert!(e.contains(&want), "{bad}: {e}");
}
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
assert!(s.doc().unwrap().doc.layers[0].children().unwrap().is_empty());
}
/// Through the session, Ctrl/Cmd in the Flare tool's center drag keeps the center's size while the
/// drag sizes the halo, and the flare drawn keeps both.
#[test]
+38 -1
View File
@@ -4272,15 +4272,26 @@ fn live_paint_bucket_double_click_across_a_junction_paints_the_joined_edges() {
s.pointer(&PointerEvent::new(kind, x, 50.0).with_mods(shift), v).unwrap();
}
assert_eq!(middle.iter().map(|e| node(&s, *e).appearance.stroke_paint()).collect::<Vec<_>>(), [green.clone(), green.clone(), green]);
// `through` takes edge ids, with scope "connected" only.
// `through` takes the group's edge ids, each once, with scope "connected" only; a face's id, an
// unknown id or an edge given twice is refused and changes nothing.
let face = vectorcraft_tools::builder::faces(&node(&s, g)).first().map(|f| f.id).unwrap();
let before = s.doc().unwrap().doc.clone();
let depth = s.doc().unwrap().history.undo.len();
for p in [
json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": "x"}),
json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": [-1]}),
json!({"group": g.0, "point": [15, 50], "scope": "samePaint", "through": []}),
json!({"group": g.0, "point": [15, 50], "through": []}),
json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": [face.0]}),
json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": [999_999_999]}),
json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": [middle[1].0, middle[1].0]}),
] {
assert!(s.execute("livePaint.strokeEdge", &p).is_err(), "{p}");
}
assert_eq!(s.doc().unwrap().doc, before);
assert_eq!(s.doc().unwrap().history.undo.len(), depth);
let r = s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": [middle[1].0]})).unwrap();
assert_eq!(r["count"], 3, "an edge of the group is taken");
}
/// A double-click whose second press lands on the next joined edge and is released back on the
@@ -4318,6 +4329,32 @@ fn live_paint_bucket_double_click_released_back_on_the_first_edge_paints_the_joi
assert_eq!(middle.iter().map(|e| node(&s, *e).appearance.stroke_paint()).collect::<Vec<_>>(), [green.clone(), green.clone(), green]);
}
/// With Paint Fills and Paint Strokes both on, a double-click on an edge after a click that filled
/// a face whose fill was the edge's stroke paint paints the joined edges: the face is not sent as
/// an edge to join through.
#[test]
fn live_paint_bucket_edge_double_click_after_filling_a_face_paints_the_joined_edges() {
let mut s = session();
let g = live_squares(&mut s, &[0.0, 50.0]);
let [a, b] = faces_at(&s, g, &[(25.0, 25.0), (75.0, 25.0)])[..] else { panic!("two faces") };
let black = Paint::solid(Color::rgb(0.0, 0.0, 0.0));
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 101.0, 51.0));
paint_parts(&mut s, &all, &black, &[(a, black.clone()), (b, black.clone())]);
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.set_tool_option("paintStrokes", &json!(true));
s.paint.fill = green.clone();
s.paint.stroke = green.clone();
for (kind, x) in [(PointerKind::Down, 25.0), (PointerKind::Up, 25.0), (PointerKind::Down, 50.0), (PointerKind::Up, 50.0)] {
s.pointer(&PointerEvent::new(kind, x, 25.0), v).unwrap();
}
assert_eq!(fill_of(&s, a), green, "the first click fills the face");
s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 50.0, 25.0), v).unwrap();
assert!(all.iter().all(|e| node(&s, *e).appearance.stroke_paint() == green), "every joined edge is painted");
assert_eq!(fill_of(&s, b), black);
}
/// A triple-click whose second press holds Cmd (it goes to the selection tool Cmd lends) matches
/// the fill the face had before the first click: the lent press counts as one that paints nothing.
#[test]
+78
View File
@@ -768,6 +768,84 @@ fn a_legend_fill_of_its_own_stays_behind_when_pasted_without_formatting() {
assert_eq!(label(&s, p, "North").1, Paint::solid(Color::WHITE), "still white when the pie is drawn again");
}
/// A pie pasted into a document whose swatch of the same name is another color takes that color on its linked wedges
/// (Merge), and its legend labels in those wedges take the contrast a redraw gives them there: white on a wedge that
/// turned dark. Pasting with Add, which keeps the copied color, keeps the labels as they were.
#[test]
fn pie_legend_labels_follow_wedges_that_take_the_documents_swatch() {
let mut s = session();
let csv = ",North,South\nP,1,1";
s.execute("swatch.new", &json!({"name": "Brand", "color": "#ffff66", "global": true})).unwrap();
let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "csv": csv})).unwrap());
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap();
/// The fill of the legend label of graph `id` that says `name`.
fn label(s: &Session, id: NodeId, name: &str) -> Paint {
let mut out = None;
node(s, id).walk(&mut |n| {
if let NodeKind::Text(t) = &n.kind
&& t.plain_text() == name
{
out = Some(t.first_style().fill.clone());
}
});
out.unwrap()
}
// The North wedge, black when drawn, takes the light Brand swatch, and a redraw sets its label black.
let mut wedges = vec![];
for c in node(&s, g).children().unwrap().iter().filter(|c| c.extras().series_index == Some(0)) {
c.walk(&mut |m| {
if matches!(m.kind, NodeKind::Path { .. }) {
wedges.push(m.id.0);
}
});
}
assert!(!wedges.is_empty());
s.execute("paint.setFill", &json!({"ids": wedges, "swatch": "Brand"})).unwrap();
s.execute("graph.setData", &json!({"id": g.0, "csv": csv})).unwrap();
assert_eq!(label(&s, g, "North"), Paint::solid(Color::BLACK), "black on the light wedge");
assert_eq!(label(&s, g, "South"), Paint::solid(Color::BLACK));
copy(&mut s, &[g]);
for (cmd, choice, north) in [
("edit.pasteWithoutFormatting", "merge", Color::WHITE),
("edit.paste", "merge", Color::WHITE),
("edit.pasteWithoutFormatting", "add", Color::BLACK),
("edit.paste", "add", Color::BLACK),
] {
new_doc(&mut s);
s.execute("swatch.new", &json!({"name": "Brand", "color": "#202020", "global": true})).unwrap();
let p = ids_of(&s.execute(cmd, &json!({"swatchConflict": choice})).unwrap())[0];
assert_eq!(label(&s, p, "North"), Paint::solid(north), "{cmd} {choice}");
assert_eq!(label(&s, p, "South"), Paint::solid(Color::BLACK), "{cmd} {choice}");
s.execute("graph.setData", &json!({"id": p.0, "csv": csv})).unwrap();
assert_eq!(label(&s, p, "North"), Paint::solid(north), "{cmd} {choice}: as a redraw sets it");
}
// A copy of the pie in the opacity mask of a rectangle follows the same way.
s.execute("document.activate", &json!({"index": 0})).unwrap();
let r = rect(&mut s, 10.0, 10.0, 300.0, 300.0);
let art = {
let d = doc_mut(&mut s);
let pie = d.node(g).unwrap().clone();
d.reid(&pie)
};
doc_mut(&mut s).node_mut(r).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(art, true)));
copy(&mut s, &[r]);
new_doc(&mut s);
s.execute("swatch.new", &json!({"name": "Brand", "color": "#202020", "global": true})).unwrap();
let p = ids_of(&s.execute("edit.paste", &json!({"swatchConflict": "merge"})).unwrap())[0];
let mask = node(&s, p).extras().mask.as_deref().unwrap().art.clone();
let mut north = None;
mask.walk(&mut |n| {
if let NodeKind::Text(t) = &n.kind
&& t.plain_text() == "North"
{
north = Some(t.first_style().fill.clone());
}
});
assert_eq!(north, Some(Paint::solid(Color::WHITE)), "in an opacity mask");
}
/// A two-line legend label in a narrow dark wedge, whose text sits off the wedge's middle line, stays white when its graph
/// is pasted without formatting.
#[test]
+19
View File
@@ -253,6 +253,25 @@ fn constrain_angle_turns_shapes_made_by_a_click() {
}
}
/// An ellipse of another anchor count made by a click turns along the Constrain Angle like the
/// live ellipse: it keeps its anchors and its box runs along the turned axes from the click.
#[test]
fn constrain_angle_turns_an_ellipse_of_six_anchors_made_by_a_click() {
let mut s = new_doc();
set_angle(&mut s, 90.0);
let p = json!({"x": 10, "y": 200, "width": 100, "height": 50, "anchors": 6});
let p = constrain_click(&s, "shape.ellipse", p.clone(), corner(&p));
assert_eq!(p["anchors"], json!(6));
let id = NodeId(s.execute("shape.ellipse", &p).unwrap()["id"].as_u64().unwrap());
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
assert!(n.live_shape().is_none());
assert_eq!(n.path_data().unwrap().anchor_count(), 6);
let b = bounds(&s, id);
for (got, want) in [(b.x0, 10.0), (b.y0, 100.0), (b.x1, 60.0), (b.y1, 200.0)] {
assert!(close(got, want), "{b:?}");
}
}
/// The Line Segment tool's Shift steps of 45° count from the Constrain Angle.
#[test]
fn constrain_angle_steps_the_line_segment_tool() {
+20
View File
@@ -265,6 +265,26 @@ fn liquify_without_selection_hits_paths_under_the_brush() {
assert!(path(&s, b).bounds().unwrap().width() < 100.0);
}
/// The warning about objects under the brush that Liquify leaves as they are names their count
/// with the matching noun and verb.
#[test]
fn liquify_warns_about_one_or_several_skipped_objects() {
let mut s = session();
let text =
|s: &mut Session, x: i32| s.execute("text.create", &json!({"x": x, "y": 460, "text": "Hi", "size": 24})).unwrap()["id"].as_u64().unwrap();
let pucker = json!({"tool": "pucker", "points": [[550, 450]], "diameter": 150, "intensity": 1});
let first = text(&mut s, 520);
s.execute("select.set", &json!({"ids": []})).unwrap();
let r = s.execute("object.liquify", &pucker).unwrap();
assert_eq!(r["skipped"], json!([first]));
assert_eq!(r["warning"], "Pucker left 1 object under the brush as it was (type): it reshapes paths only");
let second = text(&mut s, 560);
s.execute("select.set", &json!({"ids": []})).unwrap();
let r = s.execute("object.liquify", &pucker).unwrap();
assert_eq!(r["skipped"], json!([first, second]));
assert_eq!(r["warning"], "Pucker left 2 objects under the brush as they were (type): it reshapes paths only");
}
/// With nothing selected, a stroke leaves the art on a locked artboard as it is.
#[test]
fn liquify_without_selection_leaves_the_art_on_a_locked_artboard() {
+111
View File
@@ -1337,6 +1337,84 @@ fn eraser_removes_small_shape_entirely() {
assert!(paths(&s).is_empty());
}
/// `path.eraseRegion {rect}` (the Eraser's Alt-drag marquee) erases everything inside the
/// rectangle: a closed shape loses its area, an open path is cut where it crosses the edges, a
/// shape wholly inside goes, and only the selected paths take part when something is selected. One
/// undo step puts everything back, and a rectangle that touches nothing adds no undo step.
#[test]
fn erase_region_rect_erases_everything_inside_it() {
let filled = |s: &Session, x: f64, y: f64| {
paths(s).iter().any(|(_, pd)| pd.is_closed() && vectorcraft_geom::hit::fill_contains(&pd.to_bezpath(), FillRule::NonZero, Point::new(x, y)))
};
let mut s = session();
rect(&mut s, 100.0, 100.0, 200.0, 200.0);
rect(&mut s, 180.0, 140.0, 10.0, 10.0);
line(&mut s, 50.0, 150.0, 350.0, 150.0);
s.execute("select.none", &json!({})).unwrap();
let undo = undo_steps(&s);
let r = s.execute("path.eraseRegion", &json!({"rect": [150, 120, 100, 60]})).unwrap();
assert!(!r["ids"].as_array().unwrap().is_empty(), "{r}");
assert_eq!(undo_steps(&s), undo + 1);
assert!(!filled(&s, 200.0, 150.0) && !filled(&s, 185.0, 145.0), "the area inside is erased, the small square with it");
assert!(filled(&s, 120.0, 150.0) && filled(&s, 200.0, 250.0) && filled(&s, 200.0, 110.0), "the rest stays filled");
let ps = paths(&s);
assert_eq!(ps.iter().filter(|(_, pd)| pd.is_closed()).count(), 1, "the square keeps the rectangle as a hole: {ps:?}");
let open: Vec<f64> = ps.iter().filter(|(_, pd)| !pd.is_closed()).map(|(_, pd)| pd.length()).collect();
assert_eq!(open.len(), 2, "the line is cut in two: {open:?}");
assert!(open.iter().all(|l| (l - 100.0).abs() < 0.01), "{open:?}");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(paths(&s).len(), 3);
assert!(filled(&s, 200.0, 160.0) && filled(&s, 185.0, 145.0));
// A rectangle away from the art erases nothing and adds no undo step.
let undo = undo_steps(&s);
assert_eq!(s.execute("path.eraseRegion", &json!({"rect": [500, 500, 10, 10]})).unwrap(), json!({"ids": []}));
assert_eq!(undo_steps(&s), undo);
// With the line selected, only the line is erased.
let ln = paths(&s).into_iter().find(|(_, pd)| !pd.is_closed()).unwrap().0;
s.execute("select.set", &json!({"ids": [ln.0]})).unwrap();
let closed: Vec<PathData> = paths(&s).into_iter().filter(|(_, pd)| pd.is_closed()).map(|(_, pd)| pd).collect();
s.execute("path.eraseRegion", &json!({"rect": [90, 100, 30, 100]})).unwrap();
let after: Vec<PathData> = paths(&s).into_iter().filter(|(_, pd)| pd.is_closed()).map(|(_, pd)| pd).collect();
assert_eq!(after, closed, "the unselected squares are unchanged");
let open: Vec<f64> = paths(&s).iter().filter(|(_, pd)| !pd.is_closed()).map(|(_, pd)| pd.length()).collect();
assert_eq!(open.len(), 2);
assert!((open.iter().sum::<f64>() - 270.0).abs() < 0.01, "{open:?}");
}
/// A narrow `path.eraseRegion {rect}` across a long open path cuts it, wherever the rectangle
/// falls between the samples the path's length would give.
#[test]
fn erase_region_rect_cuts_a_long_line_with_a_narrow_rectangle() {
let mut s = session();
line(&mut s, 0.0, 100.0, 10000.0, 100.0);
s.execute("select.none", &json!({})).unwrap();
s.execute("path.eraseRegion", &json!({"rect": [5000.3, 90, 1, 20]})).unwrap();
let mut open: Vec<f64> = paths(&s).iter().map(|(_, pd)| pd.length()).collect();
open.sort_by(f64::total_cmp);
assert_eq!(open.len(), 2, "{open:?}");
assert!((open[0] - 4998.7).abs() < 0.01 && (open[1] - 5000.3).abs() < 0.01, "{open:?}");
}
/// `path.eraseRegion` refuses a `rect` that is not four finite numbers with a width and a height
/// above 0, and `rect` given with `points`, and changes nothing.
#[test]
fn erase_region_rect_refuses_bad_values() {
let mut s = session();
rect(&mut s, 0.0, 0.0, 100.0, 100.0);
let shape = "rect is [x, y, width, height] in points, with a width and a height above 0";
for p in [
json!({"rect": [10, 10, 0, 20]}),
json!({"rect": [10, 10, 20, -5]}),
json!({"rect": [10, 10, 20]}),
json!({"rect": [10, "10", 20, 20]}),
json!({"rect": [1e308, 0, 1e308, 20]}),
json!({"rect": {"x": 10, "y": 10, "width": 20, "height": 20}}),
] {
refuses_with(&mut s, "path.eraseRegion", &p, shape);
}
refuses_with(&mut s, "path.eraseRegion", &json!({"rect": [10, 10, 20, 20], "points": [[0, 0]]}), "give `points` or `rect`, not both");
}
/// #4495: the Eraser cuts a compound path as one shape: its hole stays empty, the erased area is
/// empty, and the rest stays filled, with either fill rule. A notch inside the ring keeps one
/// compound path; a drag through the whole ring leaves compound paths whose holes stay holes.
@@ -2326,6 +2404,39 @@ fn smoothing_keeps_a_corner_between_curves() {
}
}
/// A Smooth drag over a corner of a path cut into very many short segments keeps it, however many
/// segments twice the reach spans: an open path's 90° corner with legs of 2,000 segments 0.05 pt
/// long at the default reach, and a corner of a 200 pt square cut into 0.25 pt segments with a 40 pt
/// reach.
#[test]
fn smoothing_keeps_corners_on_a_path_of_many_short_segments() {
let mut s = session();
let (id, v, drag) = smooth_corner_path(&mut s, 90.0, 2000);
smooth_pass(&mut s, &drag);
let at = smooth_turn_at(&path(&s, id).subpaths[0], v);
assert!(at.is_some_and(|t| (t - 90.0).abs() < 0.01), "the open path's corner is kept: {at:?}");
let mut s = session();
let ends = [Point::new(200.0, 200.0), Point::new(400.0, 200.0), Point::new(400.0, 400.0), Point::new(200.0, 400.0)];
let mut anchors = vec![];
for k in 0..4 {
let (a, b) = (ends[k], ends[(k + 1) % 4]);
anchors.extend((0..800).map(|j| {
let p = a.lerp(b, f64::from(j) / 800.0);
json!({"x": p.x, "y": p.y})
}));
}
let id = smooth_test_path(&mut s, &anchors, true);
let v = ends[1];
let mut drag: Vec<Point> = (0..8).map(|k| v - kurbo::Vec2::new(40.0 - 5.0 * f64::from(k), 0.0)).collect();
drag.extend((0..=8).map(|k| v + kurbo::Vec2::new(0.0, 5.0 * f64::from(k))));
let pts: Vec<_> = drag.iter().map(|p| json!([p.x, p.y])).collect();
s.execute("path.smoothRegion", &json!({"points": pts, "radius": 40, "fidelity": 2.5})).unwrap();
let sp = &path(&s, id).subpaths[0];
let at = smooth_turn_at(sp, v);
assert!(sp.closed && at.is_some_and(|t| (t - 90.0).abs() < 0.01), "the square's corner is kept: {at:?}");
}
/// A corner at the first anchor of the stretch a drag smooths, just out of its reach, keeps its
/// place and its turn.
#[test]
+230
View File
@@ -601,3 +601,233 @@ fn an_untitled_document_saved_to_a_file_exports_titled_after_it() {
}
let _ = std::fs::remove_dir_all(dir);
}
/// A session whose metadata templates folder is `dir/Metadata Templates`, with a document titled
/// Poster.
fn template_session(dir: &std::path::Path) -> Session {
let mut s = session();
s.attach_metadata_templates_dir(dir.join("Metadata Templates"));
s
}
#[test]
fn a_saved_metadata_template_is_listed_and_applies_to_another_document() {
let dir = vectorcraft_testkit::TempDir::new("fileinfo-template");
let mut s = template_session(&dir);
assert_eq!(s.execute("file.info.templates", &json!({})).unwrap()["templates"], json!([]), "no folder yet");
s.execute("file.info", &info()).unwrap();
let r = s.execute("file.info.saveTemplate", &json!({"name": " Studio "})).unwrap();
assert_eq!(r["name"], "Studio");
let path = dir.join("Metadata Templates").join("Studio.xmp");
assert!(path.is_file(), "saved into the folder: {r}");
let listed = s.execute("file.info.templates", &json!({})).unwrap();
assert_eq!(listed["templates"][0]["name"], "Studio");
assert_eq!(listed["templates"].as_array().map(Vec::len), Some(1));
// A name that isn't a usable file name as it is is refused, so `a/b` and `a?b` never share a file.
for name in ["a/b", "a?b", "CON", "Studio.", "x\u{1}"] {
assert!(s.execute("file.info.saveTemplate", &json!({"name": name})).is_err(), "{name}");
}
assert_eq!(s.execute("file.info.templates", &json!({})).unwrap()["templates"].as_array().map(Vec::len), Some(1));
// Saving is not an edit of the document.
assert_eq!(s.doc().unwrap().history.undo.len(), 1);
// Into a new document, by name, in one undo step.
s.execute("file.new", &json!({"width": 100, "height": 80})).unwrap();
let r = s.execute("file.info.applyTemplate", &json!({"name": "Studio", "mode": "keep"})).unwrap();
assert_eq!(r["changed"], true);
let m = &s.doc().unwrap().doc.metadata;
assert_eq!((m.author.as_str(), m.author_title.as_str(), m.rating), ("Ada Lovelace", "Designer", 4));
assert_eq!(m.keywords, ["fair", "Poster", "print"]);
assert_eq!((m.copyright_status, m.copyright_notice.as_str()), (CopyrightStatus::Copyrighted, "(c) 2026 Ada"));
assert_eq!(m.description, "A poster\nfor the fair");
assert_eq!(r["title"], "Poster", "the template carries the title of its own");
assert_eq!(s.doc().unwrap().history.undo.len(), 1);
// Applied again, nothing changes and nothing is recorded.
let r = s.execute("file.info.applyTemplate", &json!({"path": path.to_str().unwrap(), "mode": "keep"})).unwrap();
assert_eq!(r["changed"], false);
assert_eq!(s.doc().unwrap().history.undo.len(), 1);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc.metadata.author, "");
// The same name replaces the template.
s.execute("file.info.saveTemplate", &json!({"name": "Studio", "fields": {"author": "Grace"}})).unwrap();
let back = vectorcraft_pdf::read_template(&std::fs::read(&path).unwrap()).unwrap();
assert_eq!(back.author.as_deref(), Some("Grace"));
assert_eq!(back.title, None, "an Untitled-N title is not written");
}
#[test]
fn a_metadata_template_merges_in_three_modes() {
let mut s = session();
s.execute("file.info", &json!({"author": "Ada", "keywords": ["fair"], "rating": 2, "copyrightUrl": "https://example.com/a"})).unwrap();
let template = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo {
author: Some("Grace".into()),
description: Some("From the template".into()),
keywords: Some(vec!["print".into(), "Fair".into()]),
rating: Some(5),
copyrighted: Some(false),
..Default::default()
});
let merged =
|s: &mut Session, mode: &str| s.execute("file.info.applyTemplate", &json!({"data": template, "mode": mode, "apply": false})).unwrap();
// Clear and replace: the fields the template lacks are cleared; the title stays.
let r = merged(&mut s, "replace");
assert_eq!((r["author"].as_str(), r["description"].as_str(), r["rating"].as_u64()), (Some("Grace"), Some("From the template"), Some(5)));
assert_eq!(
(r["keywords"].clone(), r["copyrightUrl"].as_str(), r["copyrightStatus"].as_str()),
(json!(["print", "Fair"]), Some(""), Some("publicDomain"))
);
assert_eq!(r["title"], "Poster");
// Keep and replace: the template's fields replace those it has; the others stay.
let r = merged(&mut s, "keep");
assert_eq!((r["author"].as_str(), r["rating"].as_u64(), r["copyrightUrl"].as_str()), (Some("Grace"), Some(5), Some("https://example.com/a")));
assert_eq!(r["keywords"], json!(["print", "Fair"]));
// Keep and append: keywords are added (each once), and only empty fields are filled.
let r = merged(&mut s, "append");
assert_eq!((r["author"].as_str(), r["rating"].as_u64(), r["description"].as_str()), (Some("Ada"), Some(2), Some("From the template")));
assert_eq!((r["keywords"].clone(), r["copyrightStatus"].as_str()), (json!(["fair", "print"]), Some("publicDomain")));
// `apply: false` changed nothing; `base` merges into the given fields instead.
assert_eq!(s.doc().unwrap().history.undo.len(), 1);
assert_eq!(s.doc().unwrap().doc.metadata.author, "Ada");
let r = s.execute("file.info.applyTemplate", &json!({"data": template, "mode": "append", "apply": false, "base": {"author": ""}})).unwrap();
assert_eq!(r["author"], "Grace");
// Applied: one undo step.
s.execute("file.info.applyTemplate", &json!({"data": template, "mode": "replace"})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), 2);
assert_eq!(s.doc().unwrap().doc.metadata.copyright_url, "");
}
#[test]
fn metadata_template_errors() {
let dir = vectorcraft_testkit::TempDir::new("fileinfo-template-errors");
let mut s = template_session(&dir);
let xmp = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo { author: Some("Ada".into()), ..Default::default() });
let not_xmp = dir.join("note.xmp");
std::fs::write(&not_xmp, "<note>not metadata</note>").unwrap();
let big = dir.join("big.xmp");
std::fs::write(&big, vec![b' '; vectorcraft_pdf::MAX_TEMPLATE_BYTES + 1]).unwrap();
let e = s.execute("file.info.applyTemplate", &json!({"path": big.to_str().unwrap(), "mode": "keep"})).unwrap_err();
assert!(e.to_string().contains("larger than 8 MB"), "{e}");
let e = s.execute("file.info.applyTemplate", &json!({"data": " ".repeat(vectorcraft_pdf::MAX_TEMPLATE_BYTES + 1), "mode": "keep"})).unwrap_err();
assert!(e.to_string().contains("larger than 8 MB"), "{e}");
for bad in [
json!({"data": xmp, "mode": "merge"}),
json!({"data": xmp}),
json!({"data": xmp, "mode": 3}),
json!({"mode": "keep"}),
json!({"data": xmp, "path": not_xmp.to_str().unwrap(), "mode": "keep"}),
json!({"path": dir.join("missing.xmp").to_str().unwrap(), "mode": "keep"}),
json!({"path": not_xmp.to_str().unwrap(), "mode": "keep"}),
json!({"path": big.to_str().unwrap(), "mode": "keep"}),
json!({"name": "missing", "mode": "keep"}),
json!({"data": "Ada Lovelace", "mode": "keep"}),
json!({"data": xmp, "mode": "keep", "apply": "yes"}),
json!({"data": xmp, "mode": "keep", "base": [1]}),
json!({"data": xmp, "mode": "keep", "base": {"rating": 9}}),
] {
assert!(s.execute("file.info.applyTemplate", &bad).is_err(), "{bad}");
}
for bad in [json!({"name": "a", "path": "b.xmp"}), json!({"name": " "}), json!({"fields": {"rating": 9}}), json!({"fields": "x"})] {
assert!(s.execute("file.info.saveTemplate", &bad).is_err(), "{bad}");
}
assert_eq!(s.doc().unwrap().history.undo.len(), 0);
assert!(!dir.join("Metadata Templates").exists(), "no failed save made the folder");
// A link in the folder is not followed, by its name or its file name.
#[cfg(unix)]
{
let outside = dir.join("outside.xmp");
std::fs::write(&outside, &xmp).unwrap();
std::fs::create_dir_all(dir.join("Metadata Templates")).unwrap();
std::os::unix::fs::symlink(&outside, dir.join("Metadata Templates").join("Linked.xmp")).unwrap();
for name in ["Linked", "Linked.xmp"] {
assert!(s.execute("file.info.applyTemplate", &json!({"name": name, "mode": "keep"})).is_err(), "{name}");
}
let e = s.execute("file.info.applyTemplate", &json!({"name": "Linked", "mode": "keep"})).unwrap_err();
assert!(e.to_string().contains("not a file"), "{e}");
assert_eq!(s.execute("file.info.templates", &json!({})).unwrap()["templates"], json!([]));
// A save by that name leaves the linked file as it was.
let e = s.execute("file.info.saveTemplate", &json!({"name": "Linked", "fields": {"author": "Grace"}})).unwrap_err();
assert!(e.to_string().contains("not a file"), "{e}");
assert_eq!(std::fs::read_to_string(&outside).unwrap(), xmp);
std::fs::remove_dir_all(dir.join("Metadata Templates")).unwrap();
}
// Without a folder (runs without preferences), a name is an error, the data comes back, and
// the list is empty.
let mut s = session();
assert!(s.execute("file.info.saveTemplate", &json!({"name": "Studio"})).is_err());
let data = s.execute("file.info.saveTemplate", &json!({"fields": {"author": "Ada"}})).unwrap()["data"].as_str().unwrap().to_string();
assert_eq!(vectorcraft_pdf::read_template(data.as_bytes()).unwrap().author.as_deref(), Some("Ada"));
assert_eq!(s.execute("file.info.templates", &json!({"create": true})).unwrap(), json!({"templates": []}));
}
#[test]
fn the_templates_folder_lists_only_xmp_files_and_can_be_made() {
let dir = vectorcraft_testkit::TempDir::new("fileinfo-template-list");
let mut s = template_session(&dir);
let r = s.execute("file.info.templates", &json!({"create": true})).unwrap();
let folder = dir.join("Metadata Templates");
assert!(folder.is_dir());
assert_eq!(r["folder"], folder.to_str().unwrap());
for f in ["b.XMP", "a.xmp", "notes.txt", ".xmp"] {
std::fs::write(folder.join(f), "x").unwrap();
}
std::fs::create_dir(folder.join("c.xmp")).unwrap();
// Other files, however many, leave the templates listed.
for i in 0..1000 {
std::fs::write(folder.join(format!("{i:04}.txt")), "").unwrap();
}
let names: Vec<String> = s.execute("file.info.templates", &json!({})).unwrap()["templates"]
.as_array()
.unwrap()
.iter()
.map(|t| t["name"].as_str().unwrap().to_string())
.collect();
assert_eq!(names, ["a", "b"]);
// A listed name opens whatever the case of its extension.
let xmp = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo { author: Some("Grace".into()), ..Default::default() });
std::fs::write(folder.join("b.XMP"), xmp).unwrap();
let r = s.execute("file.info.applyTemplate", &json!({"name": "b", "mode": "keep"})).unwrap();
assert_eq!(r["author"], "Grace");
// Its listed file name opens it too.
let listed = s.execute("file.info.templates", &json!({})).unwrap();
assert_eq!(listed["templates"][1]["file"], "b.XMP");
let r = s.execute("file.info.applyTemplate", &json!({"name": "b.XMP", "mode": "replace", "apply": false})).unwrap();
assert_eq!(r["author"], "Grace");
// A listed file name is taken before the name with `.xmp` added.
let ada = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo { author: Some("Ada".into()), ..Default::default() });
std::fs::write(folder.join("b.XMP.xmp"), ada).unwrap();
let r = s.execute("file.info.applyTemplate", &json!({"name": "b.XMP", "mode": "replace", "apply": false})).unwrap();
assert_eq!(r["author"], "Grace");
let r = s.execute("file.info.applyTemplate", &json!({"name": "b.XMP.xmp", "mode": "replace", "apply": false})).unwrap();
assert_eq!(r["author"], "Ada");
// A name that is not a file name never opens the template its safe form names.
let grace = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo { author: Some("Grace".into()), ..Default::default() });
std::fs::write(folder.join("a-b.xmp"), grace).unwrap();
let r = s.execute("file.info.applyTemplate", &json!({"name": "a-b", "mode": "replace", "apply": false})).unwrap();
assert_eq!(r["author"], "Grace");
for name in ["a/b", "a\\b", "a:b"] {
let e = s.execute("file.info.applyTemplate", &json!({"name": name, "mode": "replace", "apply": false})).unwrap_err();
assert!(e.to_string().contains("isn't usable as a file name"), "{name}: {e}");
}
}
#[test]
fn the_largest_file_info_saves_a_template_that_imports() {
let mut s = session();
let text = "\"&".repeat(32_768);
let keywords: Vec<String> = (0..1000).map(|i| format!("{i:04}{}", "\"".repeat(252))).collect();
let fields = json!({
"author": text, "authorTitle": text, "description": text, "copyrightNotice": text,
"copyrightUrl": format!("https://example.com/{}", "&".repeat(2000)), "keywords": keywords, "rating": 5, "copyrightStatus": "copyrighted",
});
let data = s.execute("file.info.saveTemplate", &json!({"fields": fields})).unwrap()["data"].as_str().unwrap().to_string();
assert!(data.len() > 1 << 20, "{} bytes", data.len());
let r = s.execute("file.info.applyTemplate", &json!({"data": data, "mode": "replace"})).unwrap();
assert_eq!((r["author"].as_str(), r["keywords"].as_array().map(Vec::len)), (Some(text.as_str()), Some(1000)));
}
#[test]
fn a_pdf_opens_with_the_rating_and_author_title_its_packet_gives() {
let mut m = DocMetadata::default();
let f = vectorcraft_pdf::FileInfo { author_title: Some("Editor".into()), rating: Some(3), ..Default::default() };
crate::cmd::fileinfo::read_pdf(&mut m, f);
assert_eq!((m.author_title.as_str(), m.rating), ("Editor", 3));
}
+35
View File
@@ -49,6 +49,41 @@ fn refreshing_the_font_list_redraws_type_without_editing_the_document() {
assert!(!d.is_dirty(), "nothing to save");
}
/// `text.glyphCategories` lists the kinds of glyph a font's OpenType features give, with a
/// stylistic set's name, and refuses a font that isn't available and params that aren't strings.
#[test]
fn glyph_categories_list_the_glyphs_of_each_kind_of_feature() {
use vectorcraft_text::test_fonts::{CATEGORIES_FAMILY, categories_font, source_sans_gid};
FontDb::global().add_font(categories_font().expect("the test font builds"));
let mut s = Session::new();
let g = |c| u32::from(source_sans_gid(c).expect("a glyph"));
let mut figures = vec![g('7'), g('8')];
figures.sort_unstable();
let r = s.execute("text.glyphCategories", &json!({"family": CATEGORIES_FAMILY})).unwrap();
assert_eq!(r["family"], CATEGORIES_FAMILY);
assert_eq!(r["style"], "Regular");
assert_eq!(
r["categories"],
json!([
{"id": "ligatures", "glyphs": [g('L')]},
{"id": "ss02", "name": "Round Dots", "glyphs": [g('G')]},
{"id": "smallCaps", "glyphs": [g('B')]},
{"id": "figures", "glyphs": figures},
])
);
assert_eq!(s.execute("text.glyphCategories", &json!({"family": CATEGORIES_FAMILY, "style": "regular"})).unwrap(), r);
for (p, says) in [
(json!({}), "missing `family`"),
(json!({"family": 3}), "`family` must be a string"),
(json!({"family": "No Such Font"}), "is not available"),
(json!({"family": CATEGORIES_FAMILY, "style": "Black"}), "is not available"),
(json!({"family": CATEGORIES_FAMILY, "style": true}), "`style` must be a string"),
] {
let e = s.execute("text.glyphCategories", &p).unwrap_err().to_string();
assert!(e.contains(says), "{p}: {e}");
}
}
/// Refreshing the font list while a background save writes the file leaves the document saved
/// once the file is written.
#[test]
+3 -2
View File
@@ -377,14 +377,15 @@ fn annotator_gestures_edit_the_gradient_as_single_undo_steps() {
assert_eq!(stops.len(), 3);
assert!((stops[1].offset - 0.3).abs() < 1e-6);
assert_eq!(s.selected_stop(), Some(1));
// Dragging the end handle changes only the end, as one undo step.
// Dragging the end handle changes only the length (the end stays on the bar's line), as one
// undo step.
let undo = s.doc().unwrap().history.undo.len();
gesture(
&mut s,
&[(PointerKind::Down, 200.0, 150.0), (PointerKind::Drag, 210.0, 160.0), (PointerKind::Drag, 220.0, 170.0), (PointerKind::Up, 220.0, 170.0)],
);
let g = fill_geom(&s, id);
assert_eq!((g.start, g.end), (Point::new(100.0, 150.0), Point::new(220.0, 170.0)));
assert_eq!((g.start, g.end), (Point::new(100.0, 150.0), Point::new(220.0, 150.0)));
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
s.execute("edit.undo", &json!({})).unwrap();
// The selected stop takes Delete ahead of edit.clear; the object stays.
+138
View File
@@ -2289,3 +2289,141 @@ fn confined_preserve_editing_svg_refuses_a_brush_library_entry_it_cannot_read()
confine(roots.as_ref(), || s.execute("document.serialize", &json!({"format": "svg"}))).unwrap();
}
}
/// A confined caller's SVG of a placed document whose art links an image: the file draws that art
/// and names the image's file, so a file outside the read roots refuses it and one inside them is
/// written. Any output that names no file is written.
#[test]
fn confined_svg_output_checks_the_images_of_placed_documents() {
use crate::file_access::{AutomationRoots, confine};
let away = Folder::new("svg-placed-away");
let home = Folder::new("svg-placed-home");
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
for (photo, outside) in [(away.file("photo.png"), true), (home.file("photo.png"), false)] {
write(&photo, &png(60, 30, RED));
let src = home.file("src.vectorcraft");
let mut inner = session();
place(&mut inner, &photo);
save(&mut inner, &src);
let mut s = session();
place(&mut s, &src);
let link = json!({"format": "svg", "images": "link"});
assert!(svg_text(&s.execute("document.serialize", &link).unwrap()).contains(&photo), "the file names the placed art's image");
for format in ["svg", "svgz"] {
for images in ["link", "embed"] {
let p = json!({"format": format, "images": images});
// Embed writes the pixels the placed file holds.
let names = svg_text(&s.execute("document.serialize", &p).unwrap()).contains(&photo);
assert_eq!(names, images == "link", "{p}");
match confine(roots.as_ref(), || s.execute("document.serialize", &p)) {
Ok(r) => assert!(!outside || !svg_text(&r).contains(&photo), "{p}: {}", svg_text(&r)),
Err(e) => {
assert!(outside && names, "{p}: {e}");
assert!(e.to_string().contains("a linked image file is outside the read roots"), "{p}: {e}");
}
}
}
}
if outside {
let e = confine(roots.as_ref(), || s.execute("document.serialize", &link)).unwrap_err().to_string();
assert!(e.contains("a linked image file is outside the read roots") && !e.contains("photo.png"), "{e}");
}
}
}
/// A confined caller's SVG of a symbol holding a visible rectangle and a hidden linked image outside
/// the read roots: the file leaves the hidden image out of the symbol and is written, unless hidden
/// layers are kept, which writes the image and refuses the file.
#[test]
fn confined_svg_output_leaves_hidden_symbol_art_unchecked() {
use crate::file_access::{AutomationRoots, confine};
let away = Folder::new("svg-symbol-hidden-away");
let home = Folder::new("svg-symbol-hidden-home");
let photo = away.file("photo.png");
write(&photo, &png(60, 30, RED));
let mut s = session();
let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap()["id"].clone();
let a = place(&mut s, &photo);
s.execute("object.hide", &json!({"ids": [a.0]})).unwrap();
s.execute("select.set", &json!({"ids": [r, a.0]})).unwrap();
s.execute("symbol.new", &json!({"name": "Mixed"})).unwrap();
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
for format in ["svg", "svgz"] {
let p = json!({"format": format, "images": "link"});
assert!(!svg_text(&s.execute("document.serialize", &p).unwrap()).contains(&photo), "{p}");
let text = svg_text(&confine(roots.as_ref(), || s.execute("document.serialize", &p)).unwrap());
assert!(!text.contains(&photo), "{p}: {text}");
let kept = json!({"format": format, "images": "link", "hiddenLayers": true});
assert!(svg_text(&s.execute("document.serialize", &kept).unwrap()).contains(&photo), "{kept}");
let e = confine(roots.as_ref(), || s.execute("document.serialize", &kept)).unwrap_err().to_string();
assert!(e.contains("a linked image file is outside the read roots"), "{kept}: {e}");
}
}
/// A confined caller's SVG Tiny 1.2 of an object whose opacity mask is a linked image outside the
/// read roots: the Tiny file leaves the mask out and is written; SVG 1.1 writes the mask and is
/// refused.
#[test]
fn confined_svg_tiny_output_leaves_opacity_mask_images_unchecked() {
use crate::file_access::{AutomationRoots, confine};
let away = Folder::new("svg-tiny-mask-away");
let home = Folder::new("svg-tiny-mask-home");
let photo = away.file("photo.png");
write(&photo, &png(60, 30, RED));
let mut s = session();
let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap()["id"].clone();
let a = place(&mut s, &photo);
s.execute("select.set", &json!({"ids": [r, a.0]})).unwrap();
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
for format in ["svg", "svgz"] {
let tiny = json!({"format": format, "images": "link", "profile": "tiny12"});
assert!(!svg_text(&s.execute("document.serialize", &tiny).unwrap()).contains(&photo), "{tiny}");
let text = svg_text(&confine(roots.as_ref(), || s.execute("document.serialize", &tiny)).unwrap());
assert!(!text.contains(&photo), "{tiny}: {text}");
let full = json!({"format": format, "images": "link"});
assert!(svg_text(&s.execute("document.serialize", &full).unwrap()).contains(&photo), "{full}");
let e = confine(roots.as_ref(), || s.execute("document.serialize", &full)).unwrap_err().to_string();
assert!(e.contains("a linked image file is outside the read roots"), "{full}: {e}");
}
}
/// A confined caller's SVG of a linked image outside the read roots, without pixels in the
/// document, under Radial Blur: the file and the clipboard draw the rendered image in its place,
/// name no file, and are written.
#[test]
fn confined_svg_output_checks_the_images_drawn_for_pixel_effects() {
use crate::file_access::{AutomationRoots, confine};
let away = Folder::new("svg-flat-away");
let home = Folder::new("svg-flat-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("effect.apply", &json!({"effect": "blur.radial", "ids": [a.0], "params": {"amount": 30, "quality": "draft"}})).unwrap();
without_pixels(&mut s, a);
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 clip =
|s: &mut Session| confine(roots.as_ref(), || s.execute("clipboard.exportSvg", &json!({}))).unwrap()["svg"].as_str().unwrap().to_string();
assert!(!clip(&mut s).contains(&photo));
assert!(confine(roots.as_ref(), || s.clipboard_svg()).is_some_and(|svg| !svg.contains(&photo)));
for format in ["svg", "svgz"] {
for images in ["link", "embed"] {
let p = json!({"format": format, "images": images});
let text = svg_text(&confine(roots.as_ref(), || s.execute("document.serialize", &p)).unwrap());
assert!(!text.contains(&photo), "{p}: {text}");
}
}
// Without the effect, the image names its file.
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
s.execute("effect.remove", &json!({"index": 0})).unwrap();
assert!(s.doc().unwrap().doc.node(a).unwrap().appearance.effects.is_empty());
let e = confine(roots.as_ref(), || s.execute("document.serialize", &json!({"format": "svg"}))).unwrap_err().to_string();
assert!(e.contains("a linked image file is outside the read roots"), "{e}");
}
+13
View File
@@ -706,3 +706,16 @@ fn a_marker_designs_art_in_a_series_keeps_its_paint() {
s.execute("addon.color.fillToStroke", &json!({"ids": [series.id.0]})).unwrap();
assert_eq!(design_strokes(&s), before, "the design's art keeps its paint");
}
/// Invert given a member of a compound path inverts the compound path's fill, which the member stands for.
#[test]
fn invert_of_a_compound_member_inverts_the_compound_path() {
let mut s = session();
let (a, b) = (rect(&mut s), rect(&mut s));
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let comp = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("paint.setFill", &json!({"ids": [comp.0], "color": "#ff0000"})).unwrap();
let member = node(&s, comp).children().into_iter().flatten().next().unwrap().id;
s.execute("paint.invert", &json!({"ids": [member.0]})).unwrap();
assert_eq!(node(&s, comp).appearance.fill_paint().color().unwrap().to_hex(), "#00ffff");
}
+16
View File
@@ -399,6 +399,22 @@ fn click_to_size_dialogs_draw_on_the_active_plane_in_plane_units() {
assert!(crate::perspective_click(&s, "shape.rectangle", &json!({}), at).is_none());
}
/// The Ellipse dialog's anchor count reaches the ellipse drawn on the active plane.
#[test]
fn an_ellipse_of_six_anchors_made_by_a_click_draws_on_the_active_plane() {
let (mut s, _) = persp_session();
s.execute("perspective.grid.show", &json!({"visible": true})).unwrap();
s.execute("perspective.plane.set", &json!({"plane": "right"})).unwrap();
let at = Point::new(470.0, 300.0);
let p = json!({"x": at.x, "y": at.y, "width": 50, "height": 30, "anchors": 6});
let (cmd, p) = crate::perspective_click(&s, "shape.ellipse", &p, at).unwrap();
let n = undo_len(&s);
let id = NodeId(s.execute(&cmd, &p).unwrap()["id"].as_u64().unwrap());
assert_eq!(undo_len(&s), n + 1);
assert_eq!(attached(&s, id).map(|a| a.0), Some(Plane::Right));
assert_eq!(node(&s, id).path_data().unwrap().anchor_count(), 6);
}
#[test]
fn the_canvas_draws_type_in_perspective_foreshortened() {
let (mut s, rect) = persp_session();
+301
View File
@@ -1158,3 +1158,304 @@ fn not_aligned_to_pixel_grid_takes_a_compound_path_by_its_own_property() {
assert!(!aligned(&s, off));
assert_eq!(not_aligned(&mut s, &[compound]), vec![other]);
}
/// The anchors of the paths in the art of symbol instance `inst`, where its transform places them.
fn placed_points(s: &Session, inst: u64) -> Vec<(f64, f64)> {
let d = &s.doc().unwrap().doc;
let NodeKind::SymbolInstance { symbol, xf } = &d.node(NodeId(inst)).unwrap().kind else { panic!("{inst} is not a symbol instance") };
let art = &d.symbols.iter().find(|x| &x.name == symbol).unwrap().art;
let mut out = vec![];
art.walk(&mut |n| {
if let Some(p) = n.path_data() {
out.extend(p.anchors().map(|(_, _, a)| {
let q = *xf * a.p;
(q.x, q.y)
}));
}
});
out
}
/// The transform of symbol instance `inst`.
fn instance_xf(s: &Session, inst: u64) -> vectorcraft_geom::Affine {
match &s.doc().unwrap().doc.node(NodeId(inst)).unwrap().kind {
NodeKind::SymbolInstance { xf, .. } => *xf,
_ => panic!("{inst} is not a symbol instance"),
}
}
/// Symbol Options › Align to Pixel Grid on a new symbol: the instance that replaces the selection
/// draws its art's edges on whole points, and goes back to them after a move by a fraction of a
/// point; a symbol made without it keeps the art where it was drawn.
#[test]
fn a_pixel_aligned_symbol_keeps_its_instance_on_whole_points() {
let mut s = new_doc();
path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0);
let r = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap();
assert_eq!(r["alignToPixelGrid"], true);
let inst = r["id"].as_u64().unwrap();
let pts = placed_points(&s, inst);
assert_eq!(pts.len(), 4);
assert!(whole(&pts), "{pts:?}");
s.execute("object.move", &json!({"dx": 0.3, "dy": 0.45})).unwrap();
let pts = placed_points(&s, inst);
assert!(whole(&pts), "{pts:?}");
let list = s.execute("symbol.list", &json!({})).unwrap();
assert_eq!(list["symbols"][0]["alignToPixelGrid"], true);
path(&mut s, "M100.3 20.6 L140.7 20.6 L140.7 30.3 L100.3 30.3 Z", 2.0);
let plain = s.execute("symbol.new", &json!({"name": "Plain"})).unwrap();
assert_eq!(plain["alignToPixelGrid"], false);
let pts = placed_points(&s, plain["id"].as_u64().unwrap());
assert!(!whole(&pts), "{pts:?}");
}
/// A centered stroke of odd weight puts the art's edges on half points, so the stroke's own edges
/// fall on the grid.
#[test]
fn a_pixel_aligned_symbol_with_an_odd_stroke_goes_to_half_points() {
let mut s = new_doc();
path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 1.0);
let inst = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap();
let pts = placed_points(&s, inst);
assert!(halves(&pts), "{pts:?}");
}
/// Turning it on in Symbol Options snaps the instances placed at actual size and leaves a scaled
/// one where it is; instances placed later land on whole points; asking again for the value the
/// symbol has adds no undo step; a duplicate and a rename keep it, a delete clears it, and a value
/// that is not true or false is refused.
#[test]
fn symbol_options_align_to_pixel_grid_snaps_instances_at_actual_size() {
let mut s = new_doc();
path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0);
let a = s.execute("symbol.new", &json!({"name": "Px"})).unwrap()["id"].as_u64().unwrap();
let b = s.execute("symbol.place", &json!({"name": "Px", "x": 100.3, "y": 200.7})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [b]})).unwrap();
s.execute("object.scale", &json!({"sx": 150, "sy": 150})).unwrap();
let scaled = instance_xf(&s, b);
assert!(!whole(&placed_points(&s, a)));
let r = s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap();
assert_eq!(r["alignToPixelGrid"], true);
let pts = placed_points(&s, a);
assert!(whole(&pts), "{pts:?}");
assert_eq!(instance_xf(&s, b), scaled);
let c = s.execute("symbol.place", &json!({"name": "Px", "x": 50.3, "y": 60.6})).unwrap()["id"].as_u64().unwrap();
let pts = placed_points(&s, c);
assert!(whole(&pts), "{pts:?}");
let steps = undo_len(&s);
s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap();
assert_eq!(undo_len(&s), steps);
assert_eq!(s.execute("symbol.duplicate", &json!({"name": "Px"})).unwrap()["name"], "Px copy");
assert!(s.doc().unwrap().doc.symbol_pixel_aligned("Px copy"));
s.execute("symbol.options", &json!({"name": "Px", "newName": "Grid"})).unwrap();
assert!(s.doc().unwrap().doc.symbol_pixel_aligned("Grid"));
assert!(!s.doc().unwrap().doc.symbol_pixel_aligned("Px"));
s.execute("symbol.delete", &json!({"names": ["Grid", "Px copy"]})).unwrap();
assert!(s.doc().unwrap().doc.unknown.get(vectorcraft_doc::SYMBOL_PIXEL_ALIGNED).is_none());
path(&mut s, "M10 10 L20 10 L20 20 L10 20 Z", 1.0);
assert!(s.execute("symbol.new", &json!({"alignToPixelGrid": "yes"})).is_err());
assert!(s.execute("symbol.new", &json!({"alignToPixelGrid": null})).is_err());
s.execute("symbol.new", &json!({"name": "Q"})).unwrap();
assert!(s.execute("symbol.options", &json!({"name": "Q", "alignToPixelGrid": 1})).is_err());
assert!(s.execute("symbol.options", &json!({"name": "Q", "alignToPixelGrid": null})).is_err());
}
/// An instance reflected across one axis goes back to whole points after a move; one turned a half
/// turn counts as rotated and moves by exactly the amount asked.
#[test]
fn a_reflected_instance_snaps_and_a_half_turned_one_does_not() {
let mut s = new_doc();
path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0);
let inst = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap();
s.execute("object.reflect", &json!({"axis": "vertical"})).unwrap();
s.execute("object.move", &json!({"dx": 0.3, "dy": 0.45})).unwrap();
let [.., e, f] = instance_xf(&s, inst).as_coeffs();
assert!(whole(&[(e, f)]), "{e} {f}");
s.execute("object.reflect", &json!({"axis": "vertical"})).unwrap();
s.execute("object.rotate", &json!({"angle": 180})).unwrap();
let [.., e0, f0] = instance_xf(&s, inst).as_coeffs();
s.execute("object.move", &json!({"dx": 0.3, "dy": 0.45})).unwrap();
let [.., e1, f1] = instance_xf(&s, inst).as_coeffs();
assert!((e1 - e0 - 0.3).abs() < 1e-9 && (f1 - f0 - 0.45).abs() < 1e-9, "{e0} {f0} -> {e1} {f1}");
}
/// An instance of a pixel-aligned symbol attached to a path goes back to whole points each time the
/// path places it.
#[test]
fn an_instance_on_a_path_stays_on_whole_points() {
let mut s = new_doc();
path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0);
let inst = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap();
let spine = s.execute("path.create", &json!({"d": "M 0.3 100.4 L 300.3 100.4"})).unwrap()["id"].as_u64().unwrap();
s.execute("object.objectsOnPath.attach", &json!({"path": spine, "ids": [inst]})).unwrap();
let pts = placed_points(&s, inst);
assert!(whole(&pts), "attached: {pts:?}");
let anchors = json!([{"x": 0.6, "y": 120.7}, {"x": 300.6, "y": 120.7}]);
s.execute("path.setAnchors", &json!({"id": spine, "subpaths": [{"anchors": anchors, "closed": false}]})).unwrap();
let pts = placed_points(&s, inst);
assert!(whole(&pts), "path edited: {pts:?}");
}
/// A path in the art of an opacity mask in a pixel-aligned symbol's art snaps with the rest of
/// the art.
#[test]
fn mask_art_in_a_pixel_aligned_symbol_snaps() {
let mut s = new_doc();
let r = path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0);
let m = path(&mut s, "M12.3 22.6 L30.7 22.6 L30.7 28.3 L12.3 28.3 Z", 2.0);
{
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let art = d.remove(NodeId(m)).unwrap();
d.node_mut(NodeId(r)).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), true)));
}
s.execute("select.set", &json!({"ids": [r]})).unwrap();
let inst = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap();
let d = &s.doc().unwrap().doc;
let xf = instance_xf(&s, inst);
let art = &d.symbols.iter().find(|x| x.name == "Px").unwrap().art;
let mut pts = vec![];
art.walk(&mut |n| {
if let Some(mask) = n.extras().mask.as_ref() {
mask.art.walk(&mut |c| {
if let Some(p) = c.path_data() {
pts.extend(p.anchors().map(|(_, _, a)| {
let q = xf * a.p;
(q.x, q.y)
}));
}
});
}
});
assert_eq!(pts.len(), 4);
assert!(whole(&pts), "{pts:?}");
}
/// A path in the art of an unlinked opacity mask in a pixel-aligned symbol's art snaps as the mask
/// is drawn at the symbol's natural size.
#[test]
fn unlinked_mask_art_in_a_pixel_aligned_symbol_snaps_at_natural_size() {
let mut s = new_doc();
let r = path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0);
let m = path(&mut s, "M12.3 22.6 L30.7 22.6 L30.7 28.3 L12.3 28.3 Z", 2.0);
{
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let art = d.remove(NodeId(m)).unwrap();
d.node_mut(NodeId(r)).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), false)));
}
s.execute("select.set", &json!({"ids": [r]})).unwrap();
let inst = s.execute("symbol.new", &json!({"name": "Px"})).unwrap()["id"].as_u64().unwrap();
assert_ne!(s.doc().unwrap().doc.symbol_natural_xf("Px"), vectorcraft_geom::Affine::IDENTITY);
{
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let sym = d.symbols.iter_mut().find(|x| x.name == "Px").unwrap();
std::sync::Arc::make_mut(&mut sym.art).extras_mut().mask.as_mut().unwrap().linked = false;
}
s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap();
let d = &s.doc().unwrap().doc;
let xf = instance_xf(&s, inst);
let art = &d.symbols.iter().find(|x| x.name == "Px").unwrap().art;
let mut pts = vec![];
art.walk(&mut |n| {
if let Some(mask) = n.extras().mask.as_ref() {
mask.art.walk(&mut |c| {
if let Some(p) = c.path_data() {
pts.extend(p.anchors().map(|(_, _, a)| {
let q = xf * a.p;
(q.x, q.y)
}));
}
});
}
});
assert_eq!(pts.len(), 4);
assert!(whole(&pts), "{pts:?}");
}
/// A path in the art of an opacity mask on a path of a compound path in a pixel-aligned symbol's
/// art snaps with the rest of the art.
#[test]
fn mask_art_on_a_compound_paths_path_in_a_pixel_aligned_symbol_snaps() {
let mut s = new_doc();
let a = path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0);
let b = path(&mut s, "M50.3 20.6 L60.7 20.6 L60.7 30.3 L50.3 30.3 Z", 2.0);
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
let m = path(&mut s, "M12.3 22.6 L30.7 22.6 L30.7 28.3 L12.3 28.3 Z", 2.0);
{
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let art = d.remove(NodeId(m)).unwrap();
let first = d.node(NodeId(c)).unwrap().children().unwrap()[0].id;
d.node_mut(first).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), true)));
}
s.execute("select.set", &json!({"ids": [c]})).unwrap();
let inst = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap();
let d = &s.doc().unwrap().doc;
let xf = instance_xf(&s, inst);
let art = &d.symbols.iter().find(|x| x.name == "Px").unwrap().art;
let mut pts = vec![];
art.walk(&mut |n| {
if let Some(mask) = n.extras().mask.as_ref() {
mask.art.walk(&mut |c| {
if let Some(p) = c.path_data() {
pts.extend(p.anchors().map(|(_, _, a)| {
let q = xf * a.p;
(q.x, q.y)
}));
}
});
}
});
assert_eq!(pts.len(), 4);
assert!(whole(&pts), "{pts:?}");
}
/// An instance in the art of an object's opacity mask goes to whole points when its symbol is made
/// pixel-aligned.
#[test]
fn an_instance_in_an_opacity_mask_snaps_with_its_symbol() {
let mut s = new_doc();
path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0);
s.execute("symbol.new", &json!({"name": "Px"})).unwrap();
let b = s.execute("symbol.place", &json!({"name": "Px", "x": 100.3, "y": 200.7})).unwrap()["id"].as_u64().unwrap();
let r = path(&mut s, "M80 180 L160 180 L160 240 L80 240 Z", 1.0);
{
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let inst = d.remove(NodeId(b)).unwrap();
d.node_mut(NodeId(r)).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*inst).clone(), true)));
}
s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap();
let d = &s.doc().unwrap().doc;
let mask = d.node(NodeId(r)).unwrap().extras().mask.clone().unwrap();
let NodeKind::SymbolInstance { xf, .. } = &mask.art.kind else { panic!("the mask art is not the instance") };
let [.., e, f] = xf.as_coeffs();
assert!(whole(&[(e, f)]), "{e} {f}");
}
/// While a pixel-aligned symbol is edited, the art written back from the editing layer is stored
/// on the pixel grid, so its instances stay on it.
#[test]
fn art_edited_in_symbol_editing_mode_stays_on_the_pixel_grid() {
let mut s = new_doc();
path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0);
let inst = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap();
s.execute("symbol.edit", &json!({"ids": [inst]})).unwrap();
let st = s.doc().unwrap();
let layer = st.doc.symbol_edit.as_ref().unwrap().layer;
let part = st.doc.node(layer).unwrap().children().unwrap()[0].id.0;
s.execute("select.set", &json!({"ids": [part]})).unwrap();
s.execute("object.move", &json!({"dx": 0.3, "dy": 0.45})).unwrap();
assert!(s.doc().unwrap().doc.symbol_edit.is_some());
let pts = placed_points(&s, inst);
assert!(whole(&pts), "{pts:?}");
// The editing layer shows the art as it is stored.
let shown = points(&s, part);
assert!(whole(&shown), "{shown:?}");
s.execute("symbol.exitEditing", &json!({})).unwrap();
let pts = placed_points(&s, inst);
assert!(whole(&pts), "{pts:?}");
}
+29
View File
@@ -1252,6 +1252,35 @@ fn the_place_queue_skips_an_image_whose_pixels_cant_be_read() {
assert_eq!(b.place_queue_read(read).unwrap(), r);
}
/// An encrypted PDF stays in the place cursor's queue, read with the session or apart from it, at
/// a letter page's size with `needsPassword`, so that a click in the app can ask for its password;
/// headless, a click on it places nothing.
#[test]
fn the_place_queue_keeps_an_encrypted_pdf() {
use vectorcraft_testkit::pdf::{PdfPage, pdf};
let locked = pdf(&[PdfPage::new(100.0, 50.0, "0 g 0 0 10 10 re f")], Some("pw"));
let p = json!({"files": [file("locked.pdf", &locked), file("a.png", &png(40, 20, [9, 9, 9, 255], None))], "thumbnail": 8});
let (mut a, mut b) = (session(), session());
let r = a.execute("file.place.queue", &p).unwrap();
assert_eq!((&r["count"], &r["skipped"]), (&json!(2), &json!([])), "{r}");
assert_eq!(r["files"][0], json!({"name": "locked.pdf", "format": "pdf", "width": 612.0, "height": 792.0, "needsPassword": true}));
assert!(r["files"][1].get("needsPassword").is_none());
let read = b.prepare_place_queue(&p).unwrap().read().unwrap();
assert_eq!(b.place_queue_read(read).unwrap(), r);
let view = ViewInfo::default();
assert_eq!(a.tool_options()["name"], "locked.pdf");
let _ = a.pointer(&PointerEvent::new(PointerKind::Down, 10.0, 10.0), view);
let _ = a.pointer(&PointerEvent::new(PointerKind::Up, 10.0, 10.0), view);
assert_eq!((top_children(&a).len(), a.doc().unwrap().history.undo.len()), (0, 0), "nothing placed without the password");
// An encrypted PDF with a bad option is refused for the option, not kept.
let e = a.execute("file.place.queue", &json!({"files": [file("locked.pdf", &locked)], "page": 0})).unwrap_err().to_string();
assert!(e.contains("page must be a whole number from 1"), "{e}");
// A PDF that can't be read for another reason is still skipped.
let broken = file("broken.pdf", b"%PDF-1.7\nnot a PDF body\n");
let r = a.execute("file.place.queue", &json!({"files": [broken, file("b.png", &png(4, 4, [0; 4], None))]})).unwrap();
assert_eq!((&r["count"], &r["skipped"][0]["name"]), (&json!(1), &json!("broken.pdf")), "{r}");
}
/// The place queue's thumbnail of an image is drawn from the pixels its check decoded, so each
/// image is decoded once.
#[test]
+21
View File
@@ -380,6 +380,27 @@ fn randomize_shuffles_new_colours_and_skips_excluded_rows() {
assert!((hue(&sb["map"][0]["to"]) - 0.0).abs() < 1.0 && (hue(&sb["map"][1]["to"]) - 120.0).abs() < 1.0, "hue kept");
}
/// A row with no current colors (New Row) keeps its new color through Randomize, and its color
/// goes to no row that holds current colors: the other rows shuffle their own colors only.
#[test]
fn randomize_leaves_an_empty_row_out() {
let mut s = session();
let map = json!([
{"from": [], "to": "rgb 0 255 0"},
{"from": ["rgb 255 0 0"], "to": "rgb 255 0 0"},
{"from": ["rgb 0 0 255"], "to": "rgb 0 0 255"},
]);
for seed in 0..16 {
let r = run(&mut s, "recolor.randomize", json!({"map": map, "seed": seed}));
assert_eq!(r["map"][0], map[0], "seed {seed}: the empty row keeps its color");
let mut tos: Vec<String> = [1, 2].iter().map(|i| r["map"][*i]["to"].as_str().unwrap().to_string()).collect();
tos.sort();
assert_eq!(tos, ["rgb 0 0 255", "rgb 255 0 0"], "seed {seed}: a permutation of the filled rows' colors");
}
let sb = run(&mut s, "recolor.randomize", json!({"map": map, "order": false, "saturationBrightness": true, "seed": 3}));
assert_eq!(sb["map"][0], map[0], "the empty row keeps its saturation and brightness");
}
#[test]
fn edit_group_rewrites_in_order_as_one_undo_step() {
let mut s = session();
+12
View File
@@ -120,6 +120,18 @@ fn missing_or_mismatched_answer_rolls_back() {
assert_eq!(s.script_report().unwrap()["dialogs"][0]["answer"], "missing");
}
/// The error about answers left over names their count with the matching noun.
#[test]
fn unused_answers_are_counted_in_the_singular_and_the_plural() {
let mut s = one_doc();
let ok = json!({"kind": "alert", "value": "ok"});
for (extra, says) in [(1, "`answers` has 1 answer the script did not use"), (2, "`answers` has 2 answers the script did not use")] {
let given = Value::Array(vec![ok.clone(); extra + 1]);
let e = headless(&mut s, "alert('x');", given).unwrap_err().to_string();
assert!(e.contains(says), "{e}");
}
}
#[test]
fn invalid_answers_are_rejected_before_run() {
let mut s = one_doc();
+63
View File
@@ -2420,6 +2420,69 @@ fn a_variable_library_defines_text_variables_and_data_sets() {
assert_eq!(s.doc().unwrap().doc.variables.datasets.len(), 2);
}
/// The Variables panel's Import… reads a data source by its extension, in any case: a .csv, .tsv
/// or .txt file as Import Data Sets… reads it, and an .xml file as Load Variable Library… reads it.
/// Any other extension, or none, is refused before the file is read.
#[test]
fn variable_import_reads_a_data_source_by_its_extension() {
let dir = Folder::new("vars-import");
let mut s = session();
let t = text(&mut s, "Alice");
s.execute("variable.define", &json!({"name": "Name", "kind": "text"})).unwrap();
s.execute("variable.bind", &json!({"variable": "Name", "ids": [t.0]})).unwrap();
for name in ["rows.csv", "rows.TSV", "rows.txt"] {
let path = dir.file(name);
write(&path, b"Name\nAnn\nBob\n");
let r = s.execute("variable.import", &json!({"path": path})).unwrap();
assert_eq!((r["format"].clone(), r["names"].clone()), (json!("csv"), json!(["Data Set 1", "Data Set 2"])), "{name}");
}
s.execute("dataset.select", &json!({"name": "Data Set 2"})).unwrap();
assert_eq!(plain(&s, t), "Bob");
let xml = r#"<variableSets><variableSet><variables><variable varName="Name" trait="textcontent"/></variables><sampleDataSets><sampleDataSet dataSetName="Row 1"><Name><p>Charlie</p></Name></sampleDataSet></sampleDataSets></variableSet></variableSets>"#;
let path = dir.file("library.Xml");
write(&path, xml.as_bytes());
let r = s.execute("variable.import", &json!({"path": path})).unwrap();
assert_eq!((r["format"].clone(), r["names"].clone(), r["deleted"].clone()), (json!("xml"), json!(["Row 1"]), json!([])));
// The library declares the bound text variable, so its binding stays.
s.execute("dataset.select", &json!({"name": "Row 1"})).unwrap();
assert_eq!(plain(&s, t), "Charlie");
// The extension picks the reader: CSV text in an .xml file goes to the library reader, which
// refuses it, and a library in a .csv file goes to the CSV reader.
let csv_in_xml = dir.file("rows.xml");
write(&csv_in_xml, b"Name\nAnn\n");
let e = s.execute("variable.import", &json!({"path": csv_in_xml})).unwrap_err().to_string();
assert!(e.contains("variable.loadLibrary"), "{e}");
let xml_in_csv = dir.file("library.csv");
write(&xml_in_csv, xml.as_bytes());
let e = s.execute("variable.import", &json!({"path": xml_in_csv})).unwrap_err().to_string();
assert!(e.contains("dataset.import"), "{e}");
// Other extensions, or none, are refused before the file is read, so a missing file gives the
// same error; the data sets stay as they were.
let refused = "Import reads a data source file ending in .csv, .tsv, .txt or .xml";
for (name, exists) in [("rows.json", true), ("rows", true), ("rows.csv.bak", true), ("missing.ai", false)] {
let path = dir.file(name);
if exists {
write(&path, b"Name\nAnn\n");
}
let e = s.execute("variable.import", &json!({"path": path})).unwrap_err().to_string();
assert!(e.contains(refused), "{name}: {e}");
}
let names: Vec<String> = s.doc().unwrap().doc.variables.datasets.iter().map(|d| d.name.clone()).collect();
assert_eq!(names, ["Row 1"]);
// `path` is required, and the command takes no other parameter.
for bad in [json!({}), json!({"path": 3})] {
let e = s.execute("variable.import", &bad).unwrap_err().to_string();
assert!(e.contains("missing `path`"), "{bad}: {e}");
}
let e = s.execute("variable.import", &json!({"path": dir.file("rows.csv"), "csv": "Name\nX\n"})).unwrap_err().to_string();
assert!(e.contains("unknown parameter `csv`"), "{e}");
}
/// Load Variable Library replaces the document's variables and data sets: every variable goes with
/// its bindings and values, a variable of another kind with a library variable's name included,
/// and every data set goes, the active one included. A text variable the library also declares
+1 -1
View File
@@ -255,7 +255,7 @@ impl Session {
}
// The Selection and Group Selection tools act on the instance whole.
self.select_whole_instance(id);
// The tool lent to does not see the press: it counts as a press elsewhere for the clicks a
// The lending tool does not see the press: it counts as a press elsewhere for the clicks a
// double-click or triple-click compares.
self.tool.press_elsewhere();
let lent = self.make_tool(id);