mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-26 01:26:39 +00:00
Merge main into fix/graph-series-group-appearance
This commit is contained in:
@@ -778,6 +778,8 @@ pub(crate) fn unique_name_from(base: &str, next: &mut std::collections::HashMap<
|
||||
pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000;
|
||||
|
||||
pub(crate) use addons::{DecodedImages, refresh_color_masks};
|
||||
/// Document Info's category titles and the Objects category's count labels.
|
||||
pub use docinfo::{CATEGORIES, OBJECT_LABELS};
|
||||
pub use docmenu::guide_indexes;
|
||||
pub(crate) use edit::{settle_interaction, typing_in_progress};
|
||||
pub(crate) use object::bounds_rewrite;
|
||||
|
||||
@@ -527,8 +527,9 @@ fn color_groups(cmd: &str, d: &mut Document, items: Vec<Arc<Node>>) -> Result<Ve
|
||||
}
|
||||
|
||||
/// What a trace depends on: the object traced (an image, or an Image Trace object traced again),
|
||||
/// its image, and the settings it is traced with. The tracer makes the same paths of the same
|
||||
/// inputs, so a trace made away from the command ([`TraceRun`]) stands in for the command's own.
|
||||
/// its image, the image's encoded bytes, and the settings it is traced with. The tracer makes the
|
||||
/// same paths of the same inputs, so a trace made away from the command ([`TraceRun`]) stands in
|
||||
/// for the command's own.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
struct TraceInputs {
|
||||
target: NodeId,
|
||||
@@ -538,6 +539,9 @@ struct TraceInputs {
|
||||
/// Document Library: the library's colours, which the JSON leaves out
|
||||
/// ([`tr::TraceParams::swatches`]).
|
||||
swatches: Vec<[u8; 3]>,
|
||||
/// The encoded image the tracer decodes: the blob under the image's key, shared with the
|
||||
/// document. Two blobs are equal when they are the same allocation or hold the same bytes.
|
||||
bytes: Arc<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// What `imageTrace.make` and `imageTrace.makeAndExpand` take from the session before they trace.
|
||||
@@ -549,7 +553,6 @@ struct Prepared {
|
||||
params_json: Value,
|
||||
preset_label: String,
|
||||
library: Vec<([u8; 3], Paint)>,
|
||||
bytes: Arc<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// What command `c` with params `p` traces, and how, from the session: everything but the trace.
|
||||
@@ -597,8 +600,8 @@ fn prepare(s: &Session, c: &str, p: &Value) -> Result<Prepared> {
|
||||
let bytes = Arc::clone(&blob.bytes);
|
||||
let library = trace_library(c, s, &mut params)?;
|
||||
let traced_with = serde_json::to_value(¶ms).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
let inputs = TraceInputs { target, image, params: traced_with, swatches: params.swatches.clone() };
|
||||
Ok(Prepared { inputs, trace: params, view, params_json, preset_label, library, bytes })
|
||||
let inputs = TraceInputs { target, image, params: traced_with, swatches: params.swatches.clone(), bytes };
|
||||
Ok(Prepared { inputs, trace: params, view, params_json, preset_label, library })
|
||||
}
|
||||
|
||||
/// What a trace made of an image: the size in pixels it was decoded at, and the paths.
|
||||
@@ -616,11 +619,11 @@ impl Traced {
|
||||
}
|
||||
}
|
||||
|
||||
/// Decode the image `bytes` and trace it with `params`, telling `steps` how far it has got
|
||||
/// ([`tr::trace_watched`]); [`EngineError::Cancelled`] once `steps` answers `false`.
|
||||
fn trace_now(inputs: &TraceInputs, params: &tr::TraceParams, bytes: &[u8], steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result<Traced> {
|
||||
/// Decode the image bytes of `inputs` and trace them with `params`, telling `steps` how far it has
|
||||
/// got ([`tr::trace_watched`]); [`EngineError::Cancelled`] once `steps` answers `false`.
|
||||
fn trace_now(inputs: &TraceInputs, params: &tr::TraceParams, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result<Traced> {
|
||||
// An image over the tracer's size is traced scaled down (the paths are scaled back).
|
||||
let raster = tr::Raster::decode_to_fit(bytes).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
let raster = tr::Raster::decode_to_fit(&inputs.bytes).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
if !steps(0, 0) {
|
||||
return Err(EngineError::Cancelled);
|
||||
}
|
||||
@@ -682,7 +685,8 @@ impl TraceRun {
|
||||
(self.prepared.inputs.image.width, self.prepared.inputs.image.height)
|
||||
}
|
||||
|
||||
/// Does it still apply: would the command trace the same object, image and settings now?
|
||||
/// Does it still apply: would the command trace the same object, image, pixels and settings
|
||||
/// now?
|
||||
pub fn current(&self, s: &Session) -> bool {
|
||||
prepare(s, self.command, &self.params).is_ok_and(|now| now.inputs == self.prepared.inputs)
|
||||
}
|
||||
@@ -691,13 +695,13 @@ impl TraceRun {
|
||||
/// failed or stopped ([`EngineError::Cancelled`] once `steps` answers `false`). It touches no
|
||||
/// document, so it can run on any thread.
|
||||
pub fn run(&self, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result<Traced> {
|
||||
trace_now(&self.prepared.inputs, &self.prepared.trace, &self.prepared.bytes, steps)
|
||||
trace_now(&self.prepared.inputs, &self.prepared.trace, steps)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Value> {
|
||||
let c = if expand { "imageTrace.makeAndExpand" } else { "imageTrace.make" };
|
||||
let Prepared { inputs, trace, view, params_json, preset_label, library, bytes } = prepare(s, c, p)?;
|
||||
let Prepared { inputs, trace, view, params_json, preset_label, library } = prepare(s, c, p)?;
|
||||
let group_by_color = expand && by_color_param(c, p)?;
|
||||
// A saved preset's settings join the journal entry, so a replay traces as this run did after
|
||||
// the preset is changed, renamed or deleted.
|
||||
@@ -709,7 +713,7 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
// A trace handed in for these very inputs ([`TraceRun`]), else one made now.
|
||||
let Traced { raster, res, .. } = match s.trace_hand_off.take() {
|
||||
Some(traced) if traced.inputs == inputs => traced,
|
||||
_ => trace_now(&inputs, &trace, &bytes, &|_, _| true)?,
|
||||
_ => trace_now(&inputs, &trace, &|_, _| true)?,
|
||||
};
|
||||
let TraceInputs { target, image: img, .. } = inputs;
|
||||
let mut warnings = keep_warnings(&trace, &res);
|
||||
|
||||
@@ -143,17 +143,13 @@ pub(crate) fn subpath_selected_segments(
|
||||
let has_explicit_segs = seg_refs.is_some_and(|segments| !segments.is_empty());
|
||||
if has_explicit_segs {
|
||||
if let Some(segments) = seg_refs {
|
||||
for &(s, seg) in segments {
|
||||
if s == si && seg < seg_count {
|
||||
selected_segs.insert(seg);
|
||||
}
|
||||
}
|
||||
selected_segs.extend(super::path::subpath_refs(segments, si).filter(|&seg| seg < seg_count));
|
||||
}
|
||||
return selected_segs;
|
||||
}
|
||||
|
||||
if let Some(anchors) = anchor_refs {
|
||||
let sub_anchors: BTreeSet<usize> = anchors.iter().filter_map(|&(s, a)| (s == si && a < n).then_some(a)).collect();
|
||||
let sub_anchors: BTreeSet<usize> = super::path::subpath_refs(anchors, si).filter(|&a| a < n).collect();
|
||||
if !sub_anchors.is_empty() {
|
||||
for i in 0..seg_count {
|
||||
let next = (i + 1) % n;
|
||||
|
||||
@@ -52,7 +52,7 @@ pub const CATEGORIES: [(&str, &str); 13] = [
|
||||
];
|
||||
|
||||
/// The object counts of `document.info` and their labels.
|
||||
const OBJECT_LABELS: [(&str, &str); 19] = [
|
||||
pub const OBJECT_LABELS: [(&str, &str); 19] = [
|
||||
("paths", "Paths"),
|
||||
("compoundPaths", "Compound Paths"),
|
||||
("groups", "Groups"),
|
||||
|
||||
@@ -116,8 +116,11 @@ pub(super) fn remove_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(EngineError::Other("no such anchor".into()));
|
||||
}
|
||||
let mut emptied = Beside::replacing(d, &[id]);
|
||||
let removed = remove_anchors_of(d, sel, &mut emptied, id, [(si, ai)], curvature)?;
|
||||
let removed = remove_anchors_of(d, sel, &mut emptied, id, vec![(si, ai)], curvature)?;
|
||||
emptied.finish(d)?;
|
||||
if removed {
|
||||
sel.remove(id);
|
||||
}
|
||||
Ok(removed)
|
||||
})?;
|
||||
Ok(json!({ "removedObject": removed }))
|
||||
@@ -136,14 +139,14 @@ pub(super) fn remove_anchors(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
return Err(bad("path.removeAnchors", "direct-select anchor points of a path"));
|
||||
}
|
||||
let removed = s.edit("Remove Anchor Points", |d, sel| {
|
||||
let mut removed = 0;
|
||||
let mut gone = Vec::new();
|
||||
let mut emptied = Beside::replacing(d, &jobs.iter().map(|(id, _)| *id).collect::<Vec<_>>());
|
||||
for (id, anchors) in jobs {
|
||||
let shape: Vec<(usize, bool)> =
|
||||
d.node(id).and_then(Node::path_data).map(|p| p.subpaths.iter().map(|sp| (sp.anchors.len(), sp.closed)).collect()).unwrap_or_default();
|
||||
let next = following_anchors(&shape, &anchors);
|
||||
if remove_anchors_of(d, sel, &mut emptied, id, anchors, false)? {
|
||||
removed += 1;
|
||||
gone.push(id);
|
||||
} else if !next.is_empty() {
|
||||
// The next anchor along is selected, so the next Remove Anchor Points goes on from
|
||||
// there without picking it first (#2241).
|
||||
@@ -151,7 +154,8 @@ pub(super) fn remove_anchors(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
emptied.finish(d)?;
|
||||
Ok(removed)
|
||||
sel.remove_all(gone.iter().copied());
|
||||
Ok(gone.len())
|
||||
})?;
|
||||
Ok(json!({ "removedObjects": removed }))
|
||||
}
|
||||
@@ -160,19 +164,32 @@ pub(super) fn remove_anchors(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
/// path whose subpaths have `shape` (anchor count, closed): in each subpath, the anchor after its
|
||||
/// last removed one, round the end of a closed subpath, or the one before it at an open subpath's
|
||||
/// end. Indexes are those after the removal, without the subpaths left with fewer than two anchors.
|
||||
/// `removed` is in ascending order without repeats, as a selection holds it, and each subpath reads
|
||||
/// only its own pairs.
|
||||
fn following_anchors(shape: &[(usize, bool)], removed: &[(usize, usize)]) -> BTreeSet<(usize, usize)> {
|
||||
let mut next = BTreeSet::new();
|
||||
let mut kept = 0;
|
||||
let mut rest = removed;
|
||||
for (si, &(n, closed)) in shape.iter().enumerate() {
|
||||
let gone: BTreeSet<usize> = removed.iter().filter(|&&(s, a)| s == si && a < n).map(|&(_, a)| a).collect();
|
||||
let (mine, after) = rest.split_at(rest.iter().take_while(|&&(s, _)| s == si).count());
|
||||
rest = after;
|
||||
let gone = &mine[..mine.partition_point(|&(_, a)| a < n)];
|
||||
if n - gone.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
if let Some(&last) = gone.last() {
|
||||
let wrap = if closed { 0..last } else { 0..0 };
|
||||
let after = (last + 1..n).chain(wrap).find(|a| !gone.contains(a));
|
||||
if let Some(a) = after.or_else(|| (0..last).rev().find(|a| !gone.contains(a))) {
|
||||
next.insert((kept, a - gone.range(..a).count()));
|
||||
if let Some(&(_, last)) = gone.last() {
|
||||
// Anchors past `last` are all left. Below it, the first one left (round a closed
|
||||
// subpath's end) is past the removed run from 0, and the last one left is below the
|
||||
// removed run down from `last`.
|
||||
let a = if last + 1 < n {
|
||||
Some(last + 1)
|
||||
} else if closed {
|
||||
Some(gone.iter().zip(0..).take_while(|&(&(_, g), k)| g == k).count())
|
||||
} else {
|
||||
last.checked_sub(gone.iter().rev().zip((0..=last).rev()).take_while(|&(&(_, g), k)| g == k).count())
|
||||
};
|
||||
if let Some(a) = a {
|
||||
next.insert((kept, a - gone.partition_point(|&(_, g)| g < a)));
|
||||
}
|
||||
}
|
||||
kept += 1;
|
||||
@@ -183,34 +200,37 @@ fn following_anchors(shape: &[(usize, bool)], removed: &[(usize, usize)]) -> BTr
|
||||
/// Remove `anchors` (subpath, anchor) of path `id` without opening it, refitting the curve round
|
||||
/// each one, or with `curvature` re-curving it as the Curvature tool curves its points
|
||||
/// ([`vectorcraft_tools::draw2::curvature_remove`]). A subpath left with one anchor is removed,
|
||||
/// and a path left with no subpath is removed through `emptied`. True when the path went.
|
||||
/// and a path left with no subpath is removed through `emptied`; the caller then takes it out of
|
||||
/// the selection. True when the path went.
|
||||
fn remove_anchors_of(
|
||||
d: &mut Document,
|
||||
sel: &mut Selection,
|
||||
emptied: &mut Beside,
|
||||
id: NodeId,
|
||||
anchors: impl IntoIterator<Item = (usize, usize)>,
|
||||
mut anchors: Vec<(usize, usize)>,
|
||||
curvature: bool,
|
||||
) -> Result<bool> {
|
||||
let mut anchors: Vec<(usize, usize)> = anchors.into_iter().collect();
|
||||
// The last first, so the indexes still to come stay valid.
|
||||
anchors.sort_unstable_by(|a, b| b.cmp(a));
|
||||
anchors.dedup();
|
||||
let path = path_mut(d, id)?;
|
||||
for (si, ai) in anchors {
|
||||
if let Some(sp) = path.subpaths.get_mut(si) {
|
||||
if curvature {
|
||||
let mut rest = &anchors[..];
|
||||
while let Some(&(si, _)) = rest.first() {
|
||||
let (mine, after) = rest.split_at(rest.iter().take_while(|&&(s, _)| s == si).count());
|
||||
rest = after;
|
||||
let Some(sp) = path.subpaths.get_mut(si) else { continue };
|
||||
if curvature {
|
||||
for &(_, ai) in mine {
|
||||
vectorcraft_tools::draw2::curvature_remove(sp, ai);
|
||||
} else {
|
||||
po::remove_anchor(sp, ai);
|
||||
}
|
||||
} else {
|
||||
po::remove_anchors(sp, &mine.iter().map(|&(_, ai)| ai).collect::<Vec<_>>());
|
||||
}
|
||||
}
|
||||
path.subpaths.retain(|sp| sp.anchors.len() >= 2);
|
||||
let gone = path.is_empty();
|
||||
if gone {
|
||||
emptied.put(d, id, vec![])?;
|
||||
sel.remove(id);
|
||||
} else {
|
||||
sel.anchors.remove(&id);
|
||||
sel.segments.remove(&id);
|
||||
@@ -277,3 +297,47 @@ pub(super) fn reshape_segment(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})?;
|
||||
ok()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// [`following_anchors`] by its definition: for each subpath, a search of the anchors after
|
||||
/// its last removed one, round a closed end, then before it.
|
||||
fn following_by_search(shape: &[(usize, bool)], removed: &[(usize, usize)]) -> BTreeSet<(usize, usize)> {
|
||||
let mut next = BTreeSet::new();
|
||||
let mut kept = 0;
|
||||
for (si, &(n, closed)) in shape.iter().enumerate() {
|
||||
let gone: BTreeSet<usize> = removed.iter().filter(|&&(s, a)| s == si && a < n).map(|&(_, a)| a).collect();
|
||||
if n - gone.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
if let Some(&last) = gone.last() {
|
||||
let wrap = if closed { 0..last } else { 0..0 };
|
||||
let after = (last + 1..n).chain(wrap).find(|a| !gone.contains(a));
|
||||
if let Some(a) = after.or_else(|| (0..last).rev().find(|a| !gone.contains(a))) {
|
||||
next.insert((kept, a - gone.range(..a).count()));
|
||||
}
|
||||
}
|
||||
kept += 1;
|
||||
}
|
||||
next
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn following_anchors_matches_a_search_along_each_subpath() {
|
||||
let mut seed = 0x2545_f491_4f6c_dd1d_u64;
|
||||
let mut rnd = |m: u64| {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 7;
|
||||
seed ^= seed << 17;
|
||||
(seed % m) as usize
|
||||
};
|
||||
for case in 0..2000 {
|
||||
let shape: Vec<(usize, bool)> = (0..rnd(5) + 1).map(|_| (rnd(9), rnd(2) == 0)).collect();
|
||||
let removed: BTreeSet<(usize, usize)> = (0..rnd(14)).map(|_| (rnd(shape.len() as u64 + 1), rnd(11))).collect();
|
||||
let removed: Vec<_> = removed.into_iter().collect();
|
||||
assert_eq!(following_anchors(&shape, &removed), following_by_search(&shape, &removed), "case {case}: {shape:?} removing {removed:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1096,7 +1096,7 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
|
||||
subpaths.extend(super::path::without_segments(sp, &cuts));
|
||||
} else {
|
||||
// Picked anchors leave the path with their connections, as Clear removes them.
|
||||
let gone: BTreeSet<usize> = anchor_refs.into_iter().flatten().filter_map(|&(s, a)| (s == si).then_some(a)).collect();
|
||||
let gone: BTreeSet<usize> = anchor_refs.into_iter().flat_map(|refs| super::path::subpath_refs(refs, si)).collect();
|
||||
subpaths.extend(super::path::without_anchors(sp, &gone));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,8 +78,11 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// `artboard`, as the Artboards panel shows it in the document the step runs in: past that
|
||||
/// document's last artboard, the last one; a Paste in Place, in Front or in Back step that names
|
||||
/// `artboards` keeps them, and one that names neither, while the Artboard tool is chosen with
|
||||
/// several artboards selected, pastes on those. A step that resizes the active artboard
|
||||
/// ([`crate::FIT_ACTIVE_ARTBOARD`]) and names no `index` gets that artboard as its `index`.
|
||||
/// several artboards selected, pastes on those. A Fit to Artwork Bounds step that names neither
|
||||
/// `index` nor `indices`, while the Artboard tool is chosen with several artboards selected when the
|
||||
/// step runs, gets those as its `indices`, which its journal entry records. Otherwise a step that
|
||||
/// resizes the active artboard ([`crate::FIT_ACTIVE_ARTBOARD`]) and names no `index` (nor
|
||||
/// `indices`, for Fit to Artwork Bounds) gets that artboard as its `index`.
|
||||
/// `grouped` gets each step's undo groups, as [`Session::batch_steps`] keeps them.
|
||||
fn run_steps(
|
||||
s: &mut Session,
|
||||
@@ -110,9 +113,22 @@ fn run_steps(
|
||||
// Artboard tool is chosen with several artboards selected, pastes on those.
|
||||
let names_artboards = id.starts_with("edit.pasteIn")
|
||||
&& (params.get("artboards").is_some() || (params.get("artboard").is_none() && !crate::cmd::edit::artboard_tool_picks(s).is_empty()));
|
||||
// A Fit to Artwork Bounds step that names neither `index` nor `indices`, while the Artboard
|
||||
// tool is chosen with several artboards selected, fits those, as the command does on its own.
|
||||
let fit_picks = if id == "artboard.fitToArt" && params.get("index").is_none() && params.get("indices").is_none() {
|
||||
crate::cmd::edit::artboard_tool_picks(s)
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
if !fit_picks.is_empty()
|
||||
&& let Some(o) = params.as_object_mut()
|
||||
{
|
||||
o.insert("indices".into(), json!(fit_picks));
|
||||
}
|
||||
if let Some(a) = artboard
|
||||
&& let Some(key) = key
|
||||
&& params.get(key).is_none()
|
||||
&& !(id == "artboard.fitToArt" && params.get("indices").is_some())
|
||||
&& !names_artboards
|
||||
&& let Some(last) = s.active().and_then(|d| d.doc.artboards.len().checked_sub(1))
|
||||
&& let Some(o) = params.as_object_mut()
|
||||
@@ -129,8 +145,9 @@ fn run_steps(
|
||||
}
|
||||
grouped.push(step_groups(s, start, &held));
|
||||
// The step's journal entry records what it took from the preferences or the clock (a
|
||||
// save's date, a new document's), as a command of its own would.
|
||||
if noted != params
|
||||
// save's date, a new document's), as a command of its own would, and the artboards a Fit to
|
||||
// Artwork Bounds step took from the Artboard tool.
|
||||
if (noted != params || !fit_picks.is_empty())
|
||||
&& let Some(c) = c.as_object_mut()
|
||||
{
|
||||
c.insert("params".into(), noted);
|
||||
|
||||
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Batch",
|
||||
[],
|
||||
None,
|
||||
"{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing, select.allOnArtboard or symbol.edit step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included",
|
||||
"{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing, select.allOnArtboard or symbol.edit step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer; an artboard.fitToArt step that names neither index nor indices, while the Artboard tool is chosen with several artboards selected when the step runs, gets those as indices instead, and the journal records them)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included",
|
||||
has_doc,
|
||||
batch::batch
|
||||
),
|
||||
|
||||
@@ -868,7 +868,7 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option<String> {
|
||||
/// A TIFF with more strips or tiles than the decoder can count
|
||||
/// ([`vectorcraft_doc::cmyk::oversized_tiff`]) is refused as too large to draw. JPEG XL images are
|
||||
/// read with [`jxlread`] and stored as PNG, with the ICC profile their colors are left in.
|
||||
/// A PNG, JPEG, GIF, WebP or TIFF whose orientation ([`exif_orientation`]) turns or flips it is
|
||||
/// A PNG, JPEG, GIF, WebP or TIFF whose orientation ([`vectorcraft_doc::cmyk::exif_orientation`]) turns or flips it is
|
||||
/// stored as it is shown, with its resolution's axes swapped when it turns a quarter; a CMYK JPEG
|
||||
/// or TIFF keeps its inks, 8 bits each, as a CMYK TIFF ([`vectorcraft_doc::cmyk::turned_cmyk`]).
|
||||
pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
|
||||
@@ -909,7 +909,7 @@ pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
|
||||
let f = image_format(kind).ok_or_else(|| err(format!("{kind:?} images can't be opened (see document.formats)")))?;
|
||||
// A photo whose EXIF orientation turns or flips it (a camera held upright) is stored as it is
|
||||
// seen, so it places the way it was taken (#4284); the others keep their own bytes.
|
||||
let orientation = matches!(f.id, "png" | "jpg" | "gif" | "webp" | "tiff").then(|| exif_orientation(bytes)).flatten();
|
||||
let orientation = matches!(f.id, "png" | "jpg" | "gif" | "webp" | "tiff").then(|| vectorcraft_doc::cmyk::exif_orientation(bytes)).flatten();
|
||||
let turned = orientation.is_some();
|
||||
// The resolution describes the stored pixels; a quarter turn swaps its axes.
|
||||
let quarter = orientation.is_some_and(|o| o.to_exif() >= 5);
|
||||
@@ -957,18 +957,6 @@ pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
|
||||
as_png(img, None, shown_ppi)
|
||||
}
|
||||
|
||||
/// The EXIF orientation of encoded image `bytes` when it turns or flips the pixels; `None` when
|
||||
/// it leaves them as stored, or the image has none. A TIFF the image decoder can't open (one with
|
||||
/// extra samples) has its Orientation tag read from its first image
|
||||
/// ([`vectorcraft_doc::cmyk::tiff_orientation`]).
|
||||
pub(crate) fn exif_orientation(bytes: &[u8]) -> Option<image::metadata::Orientation> {
|
||||
use image::ImageDecoder as _;
|
||||
use image::metadata::Orientation;
|
||||
let decoded = || image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?.into_decoder().ok()?.orientation().ok();
|
||||
let tagged = || vectorcraft_doc::cmyk::tiff_orientation(bytes).and_then(|v| Orientation::from_exif(u8::try_from(v).ok()?));
|
||||
decoded().or_else(tagged).filter(|o| *o != Orientation::NoTransforms)
|
||||
}
|
||||
|
||||
/// `img` stored as a PNG that keeps the file's resolution and carries `icc`, the ICC profile its
|
||||
/// colors are in.
|
||||
pub(super) fn as_png(img: image::RgbaImage, icc: Option<Vec<u8>>, ppi: Option<(f64, f64)>) -> Result<RasterImage> {
|
||||
|
||||
+216
-11
@@ -481,6 +481,12 @@ fn join_point(sp: &mut SubPath, ai: usize, smooth: bool) {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Anchors that [`merge_coincident`] moved to a lower index of their vector on this thread.
|
||||
static ANCHOR_MOVES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Merge each run of `picked` neighbours of `sp` that lie on one another into one anchor, which
|
||||
/// keeps the first one's incoming handle and the last one's outgoing handle. Returns how many
|
||||
/// anchors went.
|
||||
@@ -501,23 +507,68 @@ fn merge_coincident(sp: &mut SubPath, picked: impl Fn(usize) -> bool, join_kind:
|
||||
join_point(sp, 0, smooth);
|
||||
}
|
||||
}
|
||||
// Back to front, so the indices `picked` knows stay true for the anchors still to visit.
|
||||
for i in (1..sp.anchors.len()).rev() {
|
||||
// Back to front, so the indices `picked` knows stay true for the anchors still to visit. A
|
||||
// merged anchor is only marked here; the marked anchors are removed in one pass at the end.
|
||||
let closed = sp.closed;
|
||||
let anchors = &mut sp.anchors;
|
||||
let len = anchors.len();
|
||||
let mut gone = vec![false; len];
|
||||
// The anchor after `i` that is still on the path, and the last one still on it.
|
||||
let mut next = None;
|
||||
let mut last = len.saturating_sub(1);
|
||||
for i in (1..len).rev() {
|
||||
if picked(i - 1)
|
||||
&& picked(i)
|
||||
&& let Some([a, b]) = sp.anchors.get_mut(i - 1..=i)
|
||||
&& let Some([a, b]) = anchors.get_mut(i - 1..=i)
|
||||
&& same(a, b)
|
||||
{
|
||||
a.h_out = b.h_out;
|
||||
sp.anchors.remove(i);
|
||||
if let Some(smooth) = join_kind {
|
||||
join_point(sp, i - 1, smooth);
|
||||
if let Some(slot) = gone.get_mut(i) {
|
||||
*slot = true;
|
||||
}
|
||||
if next.is_none() {
|
||||
last = i - 1;
|
||||
}
|
||||
if let Some(smooth) = join_kind {
|
||||
// The neighbors the anchor has on the path as it now stands, as `join_point` sees them.
|
||||
let prev = if i > 1 { Some(i - 2) } else { closed.then_some(last) };
|
||||
let after = next.or(closed.then_some(0));
|
||||
join_point_between(anchors, i - 1, prev, after, smooth);
|
||||
}
|
||||
} else {
|
||||
next = Some(i);
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
if let Some(first) = gone.iter().position(|&g| g) {
|
||||
// `retain` moves each anchor it keeps after the first one it drops.
|
||||
let dropped = gone.iter().filter(|&&g| g).count();
|
||||
ANCHOR_MOVES.set(ANCHOR_MOVES.get() + (len - first - dropped));
|
||||
}
|
||||
if gone.contains(&true) {
|
||||
let mut k = 0;
|
||||
anchors.retain(|_| {
|
||||
let keep = !gone.get(k).copied().unwrap_or(false);
|
||||
k += 1;
|
||||
keep
|
||||
});
|
||||
}
|
||||
before - sp.anchors.len()
|
||||
}
|
||||
|
||||
/// [`join_point`] on anchor `ai` of `anchors` with its neighbors given by index.
|
||||
fn join_point_between(anchors: &mut [Anchor], ai: usize, prev: Option<usize>, next: Option<usize>, smooth: bool) {
|
||||
let at = |j: Option<usize>| j.and_then(|j| anchors.get(j)).map(|a| a.p);
|
||||
let (prev, next) = (at(prev), at(next));
|
||||
if let Some(a) = anchors.get_mut(ai) {
|
||||
if smooth {
|
||||
a.smooth_between(prev, next);
|
||||
} else {
|
||||
a.retract();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Close subpath `si` of path `id`, merging coincident endpoints if present.
|
||||
fn close_subpath_in_node(d: &mut Document, id: NodeId, si: usize, join_kind: Option<bool>) -> Result<()> {
|
||||
let path = path_mut(d, id)?;
|
||||
@@ -751,8 +802,19 @@ pub(super) fn join(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut merged = vec![];
|
||||
for (id, picked) in &st.selection.anchors {
|
||||
let Some(mut path) = st.doc.node(*id).and_then(|n| n.path_data()).cloned() else { continue };
|
||||
let n: usize =
|
||||
path.subpaths.iter_mut().enumerate().map(|(si, sp)| merge_coincident(sp, |ai| picked.contains(&(si, ai)), join_kind)).sum();
|
||||
// One flag per anchor; references past the end of a subpath or to a missing one pick nothing.
|
||||
let mut masks: Vec<Vec<bool>> = path.subpaths.iter().map(|sp| vec![false; sp.anchors.len()]).collect();
|
||||
for &(si, ai) in picked {
|
||||
if let Some(flag) = masks.get_mut(si).and_then(|m| m.get_mut(ai)) {
|
||||
*flag = true;
|
||||
}
|
||||
}
|
||||
let n: usize = path
|
||||
.subpaths
|
||||
.iter_mut()
|
||||
.zip(&masks)
|
||||
.map(|(sp, mask)| merge_coincident(sp, |ai| mask.get(ai).copied().unwrap_or(false), join_kind))
|
||||
.sum();
|
||||
if n > 0 {
|
||||
merged.push((*id, path));
|
||||
}
|
||||
@@ -1276,7 +1338,7 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.flat_map(|(si, sp)| {
|
||||
let cuts = refs.iter().filter_map(|&(s, seg)| (s == si).then_some(seg)).collect();
|
||||
let cuts = subpath_refs(refs, si).collect();
|
||||
without_segments(sp, &cuts)
|
||||
})
|
||||
.filter(|s| s.anchors.len() >= 2)
|
||||
@@ -1288,7 +1350,7 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.flat_map(|(si, sp)| {
|
||||
let gone = set.iter().filter_map(|&(s, ai)| (s == si).then_some(ai)).collect();
|
||||
let gone = subpath_refs(set, si).collect();
|
||||
without_anchors(sp, &gone)
|
||||
})
|
||||
.filter(|s| s.anchors.len() >= 2)
|
||||
@@ -1314,6 +1376,12 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
/// The anchor or segment indexes in `refs` that belong to subpath `si`, in index order.
|
||||
/// `refs` is ordered by subpath first, so this reads only that subpath's entries.
|
||||
pub(super) fn subpath_refs(refs: &BTreeSet<(usize, usize)>, si: usize) -> impl Iterator<Item = usize> + '_ {
|
||||
refs.range((si, 0)..=(si, usize::MAX)).map(|&(_, i)| i)
|
||||
}
|
||||
|
||||
/// Retain path `id` from `d` without copying its geometry before deletion takes its subpaths.
|
||||
/// The shared snapshot supplies the original path classification and, only if needed, gradient
|
||||
/// bounds after the working node's geometry has moved. Returns `NoNode` for a missing/non-path ID.
|
||||
@@ -1722,7 +1790,7 @@ fn cut_at_anchors(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let Some(pd) = st.doc.node(*id).and_then(|n| n.path_data()) else { continue };
|
||||
let (mut subs, mut starts) = (vec![], vec![]);
|
||||
for (si, sp) in pd.subpaths.iter().enumerate() {
|
||||
let at: BTreeSet<usize> = set.iter().filter(|(s, _)| *s == si).map(|(_, a)| *a).collect();
|
||||
let at: BTreeSet<usize> = subpath_refs(set, si).collect();
|
||||
let pieces = sp.cut_at(&at);
|
||||
// The pieces that start at a cut: every piece of an opened closed subpath, all but the
|
||||
// first of an open one.
|
||||
@@ -1763,3 +1831,140 @@ fn cut_at_anchors(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
})?;
|
||||
Ok(super::draw2::ids_json(&ids))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// `merge_coincident` removing each merged anchor from the vector straight away, kept as the
|
||||
/// reference the one-pass version must match.
|
||||
fn merge_coincident_by_removal(sp: &mut SubPath, picked: impl Fn(usize) -> bool, join_kind: Option<bool>) -> usize {
|
||||
let same = |a: &Anchor, b: &Anchor| a.p.distance(b.p) < 1e-6;
|
||||
let before = sp.anchors.len();
|
||||
if sp.closed
|
||||
&& before > 2
|
||||
&& picked(0)
|
||||
&& picked(before - 1)
|
||||
&& let [first, .., last] = sp.anchors.as_mut_slice()
|
||||
&& same(first, last)
|
||||
{
|
||||
first.h_in = last.h_in;
|
||||
sp.anchors.pop();
|
||||
if let Some(smooth) = join_kind {
|
||||
join_point(sp, 0, smooth);
|
||||
}
|
||||
}
|
||||
for i in (1..sp.anchors.len()).rev() {
|
||||
if picked(i - 1)
|
||||
&& picked(i)
|
||||
&& let Some([a, b]) = sp.anchors.get_mut(i - 1..=i)
|
||||
&& same(a, b)
|
||||
{
|
||||
a.h_out = b.h_out;
|
||||
sp.anchors.remove(i);
|
||||
if let Some(smooth) = join_kind {
|
||||
join_point(sp, i - 1, smooth);
|
||||
}
|
||||
}
|
||||
}
|
||||
before - sp.anchors.len()
|
||||
}
|
||||
|
||||
/// Every field of every anchor, bit for bit.
|
||||
fn bits(sp: &SubPath) -> (Vec<[u64; 6]>, Vec<AnchorKind>, bool) {
|
||||
let b = |p: Point| [p.x.to_bits(), p.y.to_bits()];
|
||||
let fields = sp.anchors.iter().map(|a| [b(a.p), b(a.h_in), b(a.h_out)].concat().try_into().unwrap()).collect();
|
||||
(fields, sp.anchors.iter().map(|a| a.kind).collect(), sp.closed)
|
||||
}
|
||||
|
||||
/// A small linear congruential generator, so the cases are the same on every run.
|
||||
struct Lcg(u64);
|
||||
impl Lcg {
|
||||
fn below(&mut self, n: u64) -> u64 {
|
||||
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
|
||||
(self.0 >> 33) % n
|
||||
}
|
||||
}
|
||||
|
||||
fn same_as_removal(sp: &SubPath, picked: &dyn Fn(usize) -> bool, join_kind: Option<bool>) {
|
||||
let (mut ours, mut theirs) = (sp.clone(), sp.clone());
|
||||
let n = merge_coincident(&mut ours, picked, join_kind);
|
||||
let m = merge_coincident_by_removal(&mut theirs, picked, join_kind);
|
||||
assert_eq!(n, m, "{sp:?} {join_kind:?}");
|
||||
assert_eq!(bits(&ours), bits(&theirs), "{sp:?} {join_kind:?}");
|
||||
}
|
||||
|
||||
/// Short paths with points on, near and just past the merge distance, selections with stale
|
||||
/// indices, every anchor kind and every join kind give the same anchors, bit for bit, as
|
||||
/// removing each merged anchor straight away.
|
||||
#[test]
|
||||
fn merging_coincident_anchors_matches_removing_them_one_by_one() {
|
||||
let spots = [(0.0, 0.0), (0.0, 0.0), (0.0, 0.0), (5e-7, 0.0), (0.0, 1.5e-6), (10.0, 0.0), (5.0, 5.0), (10.0, 0.0)];
|
||||
let mut rng = Lcg(7);
|
||||
for _ in 0..30_000 {
|
||||
let n = rng.below(9) as usize;
|
||||
let anchors = (0..n)
|
||||
.map(|_| {
|
||||
let (x, y) = spots[rng.below(spots.len() as u64) as usize];
|
||||
let p = Point::new(x, y);
|
||||
let handle = |rng: &mut Lcg| match rng.below(3) {
|
||||
0 => p,
|
||||
_ => p + Vec2::new(rng.below(7) as f64 - 3.0, rng.below(7) as f64 - 3.0),
|
||||
};
|
||||
let (h_in, h_out) = (handle(&mut rng), handle(&mut rng));
|
||||
let kind = if rng.below(2) == 0 { AnchorKind::Corner } else { AnchorKind::Smooth };
|
||||
Anchor { p, h_in, h_out, kind }
|
||||
})
|
||||
.collect();
|
||||
let sp = SubPath::new(anchors, rng.below(2) == 0);
|
||||
let picks: Vec<bool> = (0..n + 2).map(|_| rng.below(4) != 0).collect();
|
||||
let join_kind = [None, Some(false), Some(true)][rng.below(3) as usize];
|
||||
same_as_removal(&sp, &|i| picks.get(i).copied().unwrap_or(false), join_kind);
|
||||
}
|
||||
}
|
||||
|
||||
/// A smooth join of three anchors on one another takes the outgoing handle the middle anchor
|
||||
/// was given when it joined the right one: an already smooth left anchor keeps that handle.
|
||||
#[test]
|
||||
fn a_smooth_join_of_three_anchors_keeps_the_handle_the_middle_one_got() {
|
||||
let o = Point::ZERO;
|
||||
let left = Anchor { p: o, h_in: Point::new(-2.0, 0.0), h_out: o, kind: AnchorKind::Smooth };
|
||||
let right = Anchor { p: o, h_in: o, h_out: Point::new(0.0, 5.0), kind: AnchorKind::Corner };
|
||||
let mut sp = SubPath::new(vec![left, Anchor::corner(o), right, Anchor::corner(Point::new(10.0, 0.0))], false);
|
||||
assert_eq!(merge_coincident(&mut sp, |i| i < 3, Some(true)), 2);
|
||||
let a = sp.anchors[0];
|
||||
assert_eq!((a.h_in, a.h_out, a.kind), (Point::new(-2.0, 0.0), Point::new(10.0 / 3.0, 0.0), AnchorKind::Smooth));
|
||||
assert_eq!(sp.anchors.len(), 2);
|
||||
}
|
||||
|
||||
/// One long run of selected anchors on one another, open or closed, becomes one anchor.
|
||||
#[test]
|
||||
fn a_long_run_of_anchors_on_one_another_becomes_one() {
|
||||
for closed in [false, true] {
|
||||
for join_kind in [None, Some(false), Some(true)] {
|
||||
let anchors = (0..50_000).map(|i| Anchor::smooth(Point::ZERO, Point::new(1.0, i as f64))).collect();
|
||||
let sp = SubPath::new(anchors, closed);
|
||||
same_as_removal(&sp, &|_| true, join_kind);
|
||||
let mut ours = sp.clone();
|
||||
assert_eq!(merge_coincident(&mut ours, |_| true, join_kind), 49_999);
|
||||
assert_eq!((ours.anchors.len(), ours.closed), (1, closed));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A long selected run at the start of a path followed by as many anchors that stay: each
|
||||
/// anchor after the run moves once, not once per merged anchor.
|
||||
#[test]
|
||||
fn a_long_run_before_many_other_anchors_merges_in_one_pass() {
|
||||
let run = 300_000;
|
||||
let anchors = (0..run).map(|_| Anchor::corner(Point::ZERO)).chain((1..=run).map(|i| Anchor::corner(Point::new(i as f64, 1.0)))).collect();
|
||||
let mut sp = SubPath::new(anchors, false);
|
||||
ANCHOR_MOVES.set(0);
|
||||
assert_eq!(merge_coincident(&mut sp, |i| i < run, Some(false)), run - 1);
|
||||
assert_eq!(ANCHOR_MOVES.get(), run);
|
||||
assert_eq!(sp.anchors.len(), run + 1);
|
||||
assert_eq!(sp.anchors[0].p, Point::ZERO);
|
||||
assert_eq!(sp.anchors[1].p, Point::new(1.0, 1.0));
|
||||
assert_eq!(sp.anchors[run].p, Point::new(run as f64, 1.0));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,7 +19,9 @@ pub const ON_ACTIVE_ARTBOARD: [&str; 8] = [
|
||||
/// The commands that resize the artboards the app passes (Object › Artboards): the app passes the
|
||||
/// selected artboards to Fit to Artwork Bounds as its `indices`, and the active artboard to Fit to
|
||||
/// Selected Art as its `index`. A `command.batch` given `artboard` passes it on, as `index`, to
|
||||
/// each of their steps that names none.
|
||||
/// each of their steps that names none; a Fit to Artwork Bounds step that names neither `index` nor
|
||||
/// `indices`, while the Artboard tool is chosen with several artboards selected, gets those as its
|
||||
/// `indices` instead.
|
||||
pub const FIT_ACTIVE_ARTBOARD: [&str; 2] = ["artboard.fitToArt", "artboard.fitToSelection"];
|
||||
|
||||
/// `(command, param)` pairs the journal records only so a replay reproduces the original run
|
||||
|
||||
@@ -3788,6 +3788,103 @@ fn a_trace_run_needs_the_library_colours_it_traced_with() {
|
||||
assert!(!run.current(&s), "{name} changed");
|
||||
}
|
||||
|
||||
/// `image_doc`'s image with its disc 20 px to the left: the same size, other pixels.
|
||||
fn moved_disc_png() -> Vec<u8> {
|
||||
vectorcraft_trace::Raster::from_fn(100, 100, |x, y| {
|
||||
let (dx, dy) = (x as f64 + 0.5 - 30.0, y as f64 + 0.5 - 50.0);
|
||||
if dx * dx + dy * dy <= 900.0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] }
|
||||
})
|
||||
.encode_png()
|
||||
}
|
||||
|
||||
/// Puts `bytes` under the image key `key`, or takes the key's image data away (`None`).
|
||||
fn set_image_data(s: &mut Session, key: &str, bytes: Option<Vec<u8>>) {
|
||||
s.edit("image data", |d, _| {
|
||||
match bytes {
|
||||
Some(b) => d.images.insert(key.into(), ImageBlob::new("image/png", b)),
|
||||
None => d.images.remove(key),
|
||||
};
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// The middle of the first traced path of the Image Trace object the reply `r` names, in x.
|
||||
fn traced_center_x(s: &Session, r: &Value) -> f64 {
|
||||
outline(&traced_paths(&node(s, NodeId(r["id"].as_u64().unwrap())))[0]).0.bounds().unwrap().center().x
|
||||
}
|
||||
|
||||
/// A trace made away from its command no longer applies once the pixels under its image's key
|
||||
/// change, though the object, its image record and the settings stay as they were; both commands
|
||||
/// then trace the pixels there now. The same bytes in another allocation still apply.
|
||||
#[test]
|
||||
fn a_trace_run_needs_the_pixels_it_traced() {
|
||||
let p = json!({"params": {"ignoreWhite": true}});
|
||||
for command in ["imageTrace.make", "imageTrace.makeAndExpand"] {
|
||||
let mut s = session();
|
||||
image_doc(&mut s);
|
||||
let run = cmd::TraceRun::prepare(&s, command, &p).unwrap();
|
||||
let traced = run.run(&|_, _| true).unwrap();
|
||||
// The same bytes, allocated anew: still current.
|
||||
let same = s.doc().unwrap().doc.images["img1"].bytes.to_vec();
|
||||
set_image_data(&mut s, "img1", Some(same));
|
||||
assert!(run.current(&s), "{command}: equal bytes");
|
||||
// Other pixels under the same key: no longer current, and the hand-off is dropped.
|
||||
set_image_data(&mut s, "img1", Some(moved_disc_png()));
|
||||
assert!(!run.current(&s), "{command}: other pixels");
|
||||
traced.hand_in(&mut s);
|
||||
let r = s.execute(command, run.params()).unwrap();
|
||||
assert!(s.trace_hand_off.is_none(), "{command}: dropped");
|
||||
// The disc is now at image x 30, which the ×2 placement at 50 puts at 110.
|
||||
let x = traced_center_x(&s, &r);
|
||||
assert!((x - 110.0).abs() < 1.5, "{command}: traced the pixels there now, at {x}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Image data that is missing or empty: a run made before it went no longer applies, the run's
|
||||
/// command gives the error it gives without a run, and nothing panics.
|
||||
#[test]
|
||||
fn a_trace_run_of_missing_or_empty_image_data() {
|
||||
let p = json!({"params": {"ignoreWhite": true}});
|
||||
let mut s = session();
|
||||
image_doc(&mut s);
|
||||
let run = cmd::TraceRun::prepare(&s, "imageTrace.make", &p).unwrap();
|
||||
let traced = run.run(&|_, _| true).unwrap();
|
||||
set_image_data(&mut s, "img1", None);
|
||||
assert!(!run.current(&s), "missing");
|
||||
traced.hand_in(&mut s);
|
||||
let e = s.execute(run.command(), run.params()).unwrap_err().to_string();
|
||||
assert!(e.contains("image data `img1` is missing"), "{e}");
|
||||
set_image_data(&mut s, "img1", Some(vec![]));
|
||||
assert!(!run.current(&s), "empty");
|
||||
let empty = cmd::TraceRun::prepare(&s, "imageTrace.make", &p).unwrap();
|
||||
assert!(empty.current(&s), "two empty blobs are equal");
|
||||
assert!(matches!(empty.run(&|_, _| true), Err(EngineError::Other(_))));
|
||||
assert!(matches!(s.execute(run.command(), run.params()), Err(EngineError::Other(_))));
|
||||
}
|
||||
|
||||
/// Tracing an Image Trace object again follows the same rule: once the pixels of the image it
|
||||
/// holds change, a run made before no longer applies, and the command traces the pixels there now.
|
||||
#[test]
|
||||
fn a_trace_run_of_an_image_trace_object_needs_its_pixels() {
|
||||
let p = json!({"params": {"ignoreWhite": true}});
|
||||
let mut s = session();
|
||||
image_doc(&mut s);
|
||||
let g = s.execute("imageTrace.make", &p).unwrap()["id"].as_u64().unwrap();
|
||||
let again = json!({"id": g, "params": {"ignoreWhite": true}});
|
||||
let run = cmd::TraceRun::prepare(&s, "imageTrace.make", &again).unwrap();
|
||||
assert_eq!(run.target(), NodeId(g));
|
||||
let traced = run.run(&|_, _| true).unwrap();
|
||||
assert!(run.current(&s));
|
||||
set_image_data(&mut s, "img1", Some(moved_disc_png()));
|
||||
assert!(!run.current(&s));
|
||||
traced.hand_in(&mut s);
|
||||
let r = s.execute(run.command(), run.params()).unwrap();
|
||||
assert!(s.trace_hand_off.is_none(), "dropped");
|
||||
let x = traced_center_x(&s, &r);
|
||||
assert!((x - 110.0).abs() < 1.5, "traced the pixels there now, at {x}");
|
||||
}
|
||||
|
||||
/// Shapes: the disc of the test image comes out as a live ellipse where the image lies, the same
|
||||
/// circle as its traced path; without the option it is a plain path.
|
||||
#[test]
|
||||
|
||||
@@ -1367,6 +1367,37 @@ fn smooth_tool_reduces_jagged_path() {
|
||||
assert_eq!(p.subpaths[0].anchors[0].p, Point::new(100.0, 200.0));
|
||||
}
|
||||
|
||||
/// A drag of the Smooth tool along a line jagged by up to 6 pt leaves no corner between a curve and
|
||||
/// a line: every anchor between the path's ends turns by at most 1°.
|
||||
#[test]
|
||||
fn smooth_tool_leaves_no_corner_where_a_curve_meets_a_line() {
|
||||
let mut s = session();
|
||||
let mut seed = 7u64;
|
||||
let anchors: Vec<_> = (0..=60)
|
||||
.map(|i| {
|
||||
seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
|
||||
let noise = ((seed >> 11) as f64 / (1u64 << 53) as f64) * 2.0 - 1.0;
|
||||
json!({"x": 100.0 + f64::from(i) * 5.0, "y": 200.0 + 6.0 * noise})
|
||||
})
|
||||
.collect();
|
||||
let r = s.execute("path.create", &json!({"anchors": anchors})).unwrap();
|
||||
let id = NodeId(r["id"].as_u64().unwrap());
|
||||
let drag_points: Vec<(f64, f64)> = (0..=64).map(|i| (90.0 + f64::from(i) * 5.0, 200.0)).collect();
|
||||
drag(&mut s, "smooth", &drag_points, Mods::default());
|
||||
let p = path(&s, id);
|
||||
let sp = &p.subpaths[0];
|
||||
assert!(sp.anchors.len() < 61, "the path is smoothed: {}", sp.anchors.len());
|
||||
let dir = |v: kurbo::Vec2, w: kurbo::Vec2, chord: kurbo::Vec2| [v, w, chord].into_iter().find(|d| d.hypot() > 1e-9).unwrap_or(chord);
|
||||
for i in 1..sp.segment_count() {
|
||||
let (prev, next) = (sp.segment(i - 1), sp.segment(i));
|
||||
let arrive = dir(prev.p3 - prev.p2, prev.p3 - prev.p1, prev.p3 - prev.p0);
|
||||
let leave = dir(next.p1 - next.p0, next.p2 - next.p0, next.p3 - next.p0);
|
||||
let turn = arrive.cross(leave).atan2(arrive.dot(leave)).abs().to_degrees();
|
||||
let kinds = (sp.segment_is_line(i - 1), sp.segment_is_line(i));
|
||||
assert!(turn <= 1.0, "anchor {i} turns {turn}° (lines before and after: {kinds:?}): {:?}", sp.anchors[i]);
|
||||
}
|
||||
}
|
||||
|
||||
/// Smoothing a path with direct-selected anchors leaves the path selected whole: the selection no
|
||||
/// longer names anchors by indices into the anchors the smooth replaced. A selected path the drag
|
||||
/// does not reach keeps its anchors selected, and undo brings the old selection back.
|
||||
@@ -2718,6 +2749,49 @@ fn remove_anchor_points_selects_one_next_anchor_per_subpath_and_per_path() {
|
||||
assert_eq!(selected_anchors(&s, other), [(0, 0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_anchor_points_on_many_paths_and_subpaths_matches_removing_one_at_a_time() {
|
||||
// Many anchors over many subpaths and paths, curved and straight, open and closed: each
|
||||
// subpath ends as removing its anchors one at a time, the last first, leaves it. Paths left
|
||||
// with nothing go, the rest stay selected in order, and one undo step brings all back.
|
||||
let mut s = session();
|
||||
let curvy = "M0 0 C10 20 30 20 40 0 C50 -20 70 -20 80 0 C90 20 110 20 120 0 C130 -20 150 -20 160 0 Z \
|
||||
M0 100 L40 120 C60 140 80 80 100 100 L140 90 L180 110 L220 100";
|
||||
let ids: Vec<NodeId> = (0..4).map(|i| path_from(&mut s, if i == 2 { "M0 0 L10 0 L20 5" } else { curvy })).collect();
|
||||
let picks: [&[(usize, usize)]; 4] =
|
||||
[&[(0, 0), (0, 2), (0, 3), (1, 1), (1, 2), (1, 5)], &[(0, 1), (1, 0), (1, 6)], &[(0, 0), (0, 1)], &[(0, 3), (1, 3), (1, 4)]];
|
||||
for (k, (&id, &anchors)) in ids.iter().zip(&picks).enumerate() {
|
||||
let mode = if k == 0 { "set" } else { "add" };
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": anchors, "mode": mode})).unwrap();
|
||||
}
|
||||
let before: Vec<PathData> = ids.iter().map(|&id| path(&s, id)).collect();
|
||||
assert_eq!(s.execute("path.removeAnchors", &json!({})).unwrap()["removedObjects"], 1);
|
||||
for (k, &id) in ids.iter().enumerate() {
|
||||
let mut want = before[k].clone();
|
||||
let mut order = picks[k].to_vec();
|
||||
order.sort_unstable_by(|a, b| b.cmp(a));
|
||||
for (si, ai) in order {
|
||||
vectorcraft_pathops::remove_anchor(&mut want.subpaths[si], ai);
|
||||
}
|
||||
want.subpaths.retain(|sp| sp.anchors.len() >= 2);
|
||||
if want.subpaths.is_empty() {
|
||||
assert!(s.doc().unwrap().doc.node(id).is_none(), "path {k} goes");
|
||||
} else {
|
||||
assert_eq!(path(&s, id).subpaths, want.subpaths, "path {k}");
|
||||
}
|
||||
}
|
||||
let kept = [ids[0], ids[1], ids[3]];
|
||||
assert_eq!(s.doc().unwrap().selection.objects, kept);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
for (k, &id) in ids.iter().enumerate() {
|
||||
assert_eq!(path(&s, id), before[k]);
|
||||
assert_eq!(selected_anchors(&s, id), picks[k]);
|
||||
}
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(ids[2]).is_none());
|
||||
assert_eq!(s.doc().unwrap().selection.objects, kept);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_anchor_point_tool_and_delete_still_select_the_remainder_whole() {
|
||||
// Only Remove Anchor Points moves the selection on. The Delete Anchor Point tool leaves the
|
||||
|
||||
@@ -192,6 +192,87 @@ fn fit_steps_take_the_batchs_artboard_and_actions_leave_out_their_index() {
|
||||
assert_eq!(action, [fit("artboard.fitToArt"), fit("artboard.fitToArt"), fit("artboard.fitToSelection")]);
|
||||
}
|
||||
|
||||
/// A document of three artboards with art of its own on each → its artboards before any fit.
|
||||
fn three_artboards_with_art(s: &mut Session) -> Vec<vectorcraft_geom::Rect> {
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 3, "created": null})).unwrap();
|
||||
for (x, h) in [(10, 30), (130, 20), (250, 40)] {
|
||||
s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": h})).unwrap();
|
||||
}
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.doc().unwrap().doc.artboards.iter().map(|a| a.rect).collect()
|
||||
}
|
||||
|
||||
/// The artboards of [`three_artboards_with_art`], each fitted to its art.
|
||||
fn three_fitted_artboards() -> [vectorcraft_geom::Rect; 3] {
|
||||
let rect = vectorcraft_geom::Rect::new;
|
||||
[rect(10.0, 10.0, 30.0, 40.0), rect(130.0, 10.0, 150.0, 30.0), rect(250.0, 10.0, 270.0, 50.0)]
|
||||
}
|
||||
|
||||
/// A Fit to Artwork Bounds step that names neither `index` nor `indices`, while the Artboard tool
|
||||
/// is chosen with several artboards selected, fits each of those (not the batch's artboard), as the
|
||||
/// command does on its own; a step's own `index` or `indices` wins, and with one artboard or none
|
||||
/// selected the step takes the batch's artboard.
|
||||
#[test]
|
||||
fn a_batch_fit_step_uses_the_artboard_tool_selection() {
|
||||
let fitted = three_fitted_artboards();
|
||||
let boards = |s: &Session| s.doc().unwrap().doc.artboards.iter().map(|a| a.rect).collect::<Vec<_>>();
|
||||
let fit = |params: Value| json!({"artboard": 1, "commands": [{"command": "artboard.fitToArt", "params": params}]});
|
||||
let session = |picks: &Value| {
|
||||
let mut s = Session::new();
|
||||
let was = three_artboards_with_art(&mut s);
|
||||
s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap();
|
||||
s.set_tool_option("selected", picks);
|
||||
(s, was)
|
||||
};
|
||||
let (mut s, was) = session(&json!([2, 0]));
|
||||
s.execute("command.batch", &fit(json!({}))).unwrap();
|
||||
assert_eq!(boards(&s), [fitted[0], was[1], fitted[2]], "artboards 1 and 3, the selected ones, and not the batch's artboard 2");
|
||||
let (mut s, was) = session(&json!([2, 0]));
|
||||
s.execute("command.batch", &fit(json!({"index": 1}))).unwrap();
|
||||
assert_eq!(boards(&s), [was[0], fitted[1], was[2]], "a step's own index");
|
||||
let (mut s, was) = session(&json!([2, 0]));
|
||||
s.execute("command.batch", &fit(json!({"indices": [1, 2]}))).unwrap();
|
||||
assert_eq!(boards(&s), [was[0], fitted[1], fitted[2]], "a step's own indices");
|
||||
for picks in [json!([2]), json!([])] {
|
||||
let (mut s, was) = session(&picks);
|
||||
s.execute("command.batch", &fit(json!({}))).unwrap();
|
||||
assert_eq!(boards(&s), [was[0], fitted[1], was[2]], "the batch's artboard with {picks} selected");
|
||||
}
|
||||
}
|
||||
|
||||
/// The journal records the artboards a batch's Fit to Artwork Bounds step took from the Artboard
|
||||
/// tool, so a replay in a new session fits the same ones; an action leaves them out and fits the
|
||||
/// artboards selected when it plays.
|
||||
#[test]
|
||||
fn a_batch_fit_selection_replays_but_an_action_uses_the_current_selection() {
|
||||
let fitted = three_fitted_artboards();
|
||||
let boards = |s: &Session| s.doc().unwrap().doc.artboards.iter().map(|a| a.rect).collect::<Vec<_>>();
|
||||
let mut s = Session::new();
|
||||
let was = three_artboards_with_art(&mut s);
|
||||
s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap();
|
||||
s.set_tool_option("selected", &json!([0, 2]));
|
||||
let start = s.journal.len();
|
||||
let steps = json!([{"command": "artboard.fitToArt", "params": {}}]);
|
||||
s.execute("command.batch", &json!({"artboard": 1, "commands": steps})).unwrap();
|
||||
assert_eq!(boards(&s), [fitted[0], was[1], fitted[2]]);
|
||||
let (id, p) = s.journal.last().unwrap().clone();
|
||||
assert_eq!((id.as_str(), &p["commands"][0]["params"]), ("command.batch", &json!({"indices": [0, 2]})));
|
||||
let r = replayed(&s);
|
||||
assert_ne!(r.tool_id(), "artboard", "the new session's tool selects no artboards");
|
||||
assert_eq!(boards(&r), boards(&s), "the replay fits the recorded artboards");
|
||||
let action = s.journal_for_action(start);
|
||||
assert_eq!(action, [("command.batch".to_string(), json!({"commands": steps}))]);
|
||||
// Played on a fresh copy of the document with other artboards selected.
|
||||
let mut a = Session::new();
|
||||
three_artboards_with_art(&mut a);
|
||||
a.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap();
|
||||
a.set_tool_option("selected", &json!([1, 2]));
|
||||
a.execute("command.batch", &json!({"artboard": 0, "commands": action[0].1["commands"]})).unwrap();
|
||||
assert_eq!(boards(&a), [was[0], fitted[1], fitted[2]], "the action fits the artboards selected when it plays");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_save_records_its_date_and_replays_it() {
|
||||
let path = vectorcraft_testkit::temp_dir("journal-save").join("a.vectorcraft").to_string_lossy().into_owned();
|
||||
|
||||
@@ -753,6 +753,9 @@ fn precise_cursors_replace_every_pen_state() {
|
||||
Cursor::ShapeBuilderErase,
|
||||
Cursor::AnchorPoint,
|
||||
Cursor::Curvature,
|
||||
Cursor::LivePaintBucket,
|
||||
Cursor::LivePaintBucketFace,
|
||||
Cursor::LivePaintBucketEdge,
|
||||
] {
|
||||
assert_eq!(c.precise(), Cursor::Crosshair, "{c:?}");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user