mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-17 00:54:44 +00:00
Merge main into feat/graph-type-dialog
This commit is contained in:
@@ -1008,6 +1008,33 @@ pub fn has_brush(n: &Node) -> bool {
|
||||
n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.brush.is_some() && s.visible))
|
||||
}
|
||||
|
||||
/// How far brush art can paint past the visual box of `n`: `16 × w + 8`, where `w` is the widest
|
||||
/// stroke of `n` (at least 1), when `n` has a visible brushed stroke with a paint; 0 when it has
|
||||
/// none, as a brushed stroke without a paint draws no brush art. This is the room the renderer and
|
||||
/// the exports leave for brush art when they cull.
|
||||
pub fn reach(n: &Node) -> f64 {
|
||||
let paints = |i: &AppearanceItem| matches!(i, AppearanceItem::Stroke(s) if s.visible && s.brush.is_some() && !s.paint.is_none());
|
||||
if !n.appearance.items.iter().any(paints) {
|
||||
return 0.0;
|
||||
}
|
||||
let w = n.appearance.items.iter().filter_map(|i| if let AppearanceItem::Stroke(s) = i { Some(s.width) } else { None }).fold(1.0, f64::max);
|
||||
16.0 * w + 8.0
|
||||
}
|
||||
|
||||
/// The largest [`reach`] of `n` and of the objects in it: the members of its groups, layers and
|
||||
/// live objects. Of a group or layer with a clipping path only the clipping path counts, as the
|
||||
/// clip keeps its members' brush art inside it. A compound path counts its own strokes only, as
|
||||
/// it is painted with its own appearance and not its paths'. Symbol art is not looked into
|
||||
/// ([`vectorcraft_doc::SymbolBoxes::with_brush_art`] measures it).
|
||||
pub fn reach_within(n: &Node) -> f64 {
|
||||
let members = match &n.kind {
|
||||
NodeKind::Group { children, clip: true } | NodeKind::Layer { children, clip: true, .. } => children.get(..1).unwrap_or_default(),
|
||||
NodeKind::Compound { .. } => &[],
|
||||
_ => n.children().map_or(&[][..], |c| &c[..]),
|
||||
};
|
||||
members.iter().map(|c| reach_within(c)).fold(reach(n), f64::max)
|
||||
}
|
||||
|
||||
/// Expand a brushed path: a group of [the path with its fills and unbrushed strokes (if any
|
||||
/// paint remains), the brush art…]. Ids are 0 (the caller re-ids). `None` if not brushed.
|
||||
pub fn expand(doc: &Document, n: &Node) -> Option<Node> {
|
||||
|
||||
+12
-8
@@ -840,15 +840,19 @@ fn reorient_strokes(n: &mut Node, o: Orient) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Turn the strokes of path `n` for Reverse Path Direction, before its subpaths flagged in
|
||||
/// `reversed` are reversed with [`SubPath::reverse`] (a closed one then starts at its last
|
||||
/// anchor): each stroke's width profile (sides swapped), pen pressure, tilt, bearing and rotation
|
||||
/// then run the new way, so the stroke draws as it did. A stroke reads one profile along every
|
||||
/// subpath, so it turns only when all of them turn alike. Arrowheads stay at the path's start and
|
||||
/// end.
|
||||
/// Turn the strokes of path or compound path `n` for Reverse Path Direction, before its subpaths
|
||||
/// flagged in `reversed` are reversed with [`SubPath::reverse`] (a closed one then starts at its
|
||||
/// last anchor): each stroke's width profile (sides swapped), pen pressure, tilt, bearing and
|
||||
/// rotation then run the new way, so the stroke draws as it did. A compound path's subpaths are
|
||||
/// its members' subpaths in order. A stroke reads one profile along every subpath, so it turns
|
||||
/// only when all of them turn alike. Arrowheads stay at the path's start and end.
|
||||
pub fn reverse_stroke_records(n: &mut Node, reversed: &[bool]) {
|
||||
let NodeKind::Path { path, .. } = &n.kind else { return };
|
||||
let mut turns = path.subpaths.iter().enumerate().map(|(i, sp)| {
|
||||
let subpaths: Vec<&SubPath> = match &n.kind {
|
||||
NodeKind::Path { path, .. } => path.subpaths.iter().collect(),
|
||||
NodeKind::Compound { children, .. } => children.iter().filter_map(|c| c.path_data()).flat_map(|pd| &pd.subpaths).collect(),
|
||||
_ => return,
|
||||
};
|
||||
let mut turns = subpaths.into_iter().enumerate().map(|(i, sp)| {
|
||||
let mut o = Orient::of(sp);
|
||||
if reversed.get(i).copied().unwrap_or(false) {
|
||||
if sp.closed {
|
||||
|
||||
+1097
-77
File diff suppressed because it is too large
Load Diff
+38
-27
@@ -543,7 +543,7 @@ pub struct GraphSpec {
|
||||
/// Bounds of the art when it was last generated (detects moves/scales of the graph group).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub placed: Option<Rect>,
|
||||
/// Bounds of the art other than type when it was last generated ([`art_bounds`]). Moves and scales of the graph
|
||||
/// Bounds of the art other than type when it was last generated ([`graph_art_without_type`]). Moves and scales of the graph
|
||||
/// group are measured on these when present; graphs saved without them are measured on [`Self::placed`].
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub placed_art: Option<Rect>,
|
||||
@@ -562,6 +562,43 @@ fn edge_to_edge_before_the_option() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// The geometric bounds of a graph's art `children` leaving out their type: the plot, axes, tick marks and legend
|
||||
/// swatches without the labels. None when there is nothing else. [`GraphSpec::placed_art`] keeps these.
|
||||
pub fn graph_art_without_type(children: &[std::sync::Arc<crate::Node>]) -> Option<Rect> {
|
||||
children.iter().filter_map(|c| without_type(c).0).reduce(|a, b| a.union(b))
|
||||
}
|
||||
|
||||
/// The geometric bounds of `n` leaving out the type in it, and whether its own geometric bounds depend on that type. A
|
||||
/// group without such type gives its own bounds, and a clipping group whose clip does not depend on type gives the
|
||||
/// bounds of its clip. Objects other than groups, layers and compound paths, blends, envelopes and repeats among them,
|
||||
/// give their own bounds.
|
||||
fn without_type(n: &crate::Node) -> (Option<Rect>, bool) {
|
||||
use crate::NodeKind::{Compound, Group, Layer, Text};
|
||||
if matches!(n.kind, Text(_)) {
|
||||
return (None, true);
|
||||
}
|
||||
let children: &[std::sync::Arc<crate::Node>] = match &n.kind {
|
||||
Group { clip: true, children } | Layer { clip: true, children, .. } => children,
|
||||
Group { .. } | Layer { .. } | Compound { .. } => n.editing_children(),
|
||||
_ => return (n.geometric_bounds(), false),
|
||||
};
|
||||
let mut bounds: Option<Rect> = None;
|
||||
let mut had_type = false;
|
||||
let mut clip_has_type = false;
|
||||
let hidden_layer_member = |c: &crate::Node| !c.visible && matches!(n.kind, Layer { clip: false, .. });
|
||||
for (i, c) in children.iter().enumerate().filter(|(_, c)| !hidden_layer_member(c)) {
|
||||
let (b, t) = without_type(c);
|
||||
had_type |= t;
|
||||
clip_has_type |= i == 0 && t;
|
||||
bounds = match (bounds, b) {
|
||||
(Some(a), Some(b)) => Some(a.union(b)),
|
||||
(a, b) => a.or(b),
|
||||
};
|
||||
}
|
||||
let clip = matches!(n.kind, Group { clip: true, .. } | Layer { clip: true, .. });
|
||||
if had_type && (!clip || clip_has_type) { (bounds, true) } else { (n.geometric_bounds(), false) }
|
||||
}
|
||||
|
||||
impl GraphSpec {
|
||||
/// The type series `s` is drawn as: its own type when it combines with the graph's, else the graph's.
|
||||
pub fn series_kind(&self, s: usize) -> GraphKind {
|
||||
@@ -630,32 +667,6 @@ impl GraphSpec {
|
||||
}
|
||||
}
|
||||
|
||||
/// The geometric bounds of a graph's art `children` leaving out their type: the plot, axes, tick marks and legend
|
||||
/// swatches without the labels. None when there is nothing else. [`GraphSpec::placed_art`] keeps these.
|
||||
pub fn art_bounds(children: &[std::sync::Arc<crate::Node>]) -> Option<Rect> {
|
||||
children.iter().filter_map(|c| art_bounds_of(c).0).reduce(|a, b| a.union(b))
|
||||
}
|
||||
|
||||
/// The geometric bounds of `n` leaving out the type in it, and whether there was type to leave out. A group without type
|
||||
/// gives its own bounds, so a clipping group gives the bounds of its clip.
|
||||
fn art_bounds_of(n: &crate::Node) -> (Option<Rect>, bool) {
|
||||
if matches!(n.kind, crate::NodeKind::Text(_)) {
|
||||
return (None, true);
|
||||
}
|
||||
let Some(children) = n.children() else { return (n.geometric_bounds(), false) };
|
||||
let mut bounds: Option<Rect> = None;
|
||||
let mut had_type = false;
|
||||
for c in children {
|
||||
let (b, t) = art_bounds_of(c);
|
||||
had_type |= t;
|
||||
bounds = match (bounds, b) {
|
||||
(Some(a), Some(b)) => Some(a.union(b)),
|
||||
(a, b) => a.or(b),
|
||||
};
|
||||
}
|
||||
if had_type { (bounds, true) } else { (n.geometric_bounds(), false) }
|
||||
}
|
||||
|
||||
impl Default for GraphSpec {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
|
||||
+376
-88
@@ -1,7 +1,7 @@
|
||||
//! Hit testing over the document tree.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashSet;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::rc::Rc;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
@@ -279,13 +279,16 @@ pub fn selected_hidden_at(doc: &Document, p: Point, opt: HitOptions, selected: &
|
||||
return false;
|
||||
}
|
||||
// How a click reaches it, if one does.
|
||||
let start = opt;
|
||||
let Some(opt) = path_options(&nodes, &chain, opt) else { return false };
|
||||
// Hidden by a mask: one of the containers around it clips, and not to `p`.
|
||||
let masked = nodes
|
||||
.iter()
|
||||
.rev()
|
||||
.skip(1)
|
||||
.any(|n| n.clips() && n.children().and_then(|c| c.first()).is_some_and(|clip| clip.id != id && !clip_contains(clip, p)));
|
||||
// Hidden by a mask: one of the containers around it clips, and not to `p`. A container
|
||||
// tests its clipping path in outline from the first layer with Preview off down to it, as
|
||||
// a click going down to it does ([`path_options`]).
|
||||
let below = start.scope.and_then(|s| chain.iter().position(|a| *a == s)).map_or(0, |i| i + 1);
|
||||
let masked = nodes.iter().enumerate().rev().skip(1).any(|(k, n)| {
|
||||
let outline = start.outline || nodes.get(below..=k).is_some_and(|ns| ns.iter().any(|n| previews_off(n)));
|
||||
n.clips() && n.children().and_then(|c| c.first()).is_some_and(|clip| clip.id != id && !clip_contains(clip, p, outline))
|
||||
});
|
||||
// A click may reach it there ([`may_hit`]: not a guide while guides are locked or
|
||||
// hidden, nor a Shaper group's hidden part), and its own art is what a click would hit
|
||||
// in it: a group's hidden, locked or masked contents don't count.
|
||||
@@ -359,6 +362,7 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeI
|
||||
/// measured by their art ([`Node::geometric_bounds_with`]).
|
||||
fn objects_at_layer(layer: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, tops: &mut Vec<NodeId>, seen: &mut HashSet<NodeId>) -> bool {
|
||||
let Some(children) = layer.children() else { return true };
|
||||
let opt = if matches!(layer.kind, NodeKind::Layer { preview: false, .. }) { HitOptions { outline: true, ..opt } } else { opt };
|
||||
if layer.clips()
|
||||
&& let Some(clip) = children.first()
|
||||
{
|
||||
@@ -366,11 +370,10 @@ fn objects_at_layer(layer: &Node, p: Point, opt: HitOptions, symbols: &SymbolBox
|
||||
if clip_outline_hit(layer, clip, p, opt, symbols, true).is_some() && seen.insert(clip.id) {
|
||||
tops.push(clip.id);
|
||||
}
|
||||
if !clip_contains(clip, p) {
|
||||
if !clip_contains(clip, p, opt.outline) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
let opt = if matches!(layer.kind, NodeKind::Layer { preview: false, .. }) { HitOptions { outline: true, ..opt } } else { opt };
|
||||
for (i, c) in children.iter().enumerate().rev() {
|
||||
if !may_hit(layer, i, c, p, opt, symbols, true) || seen.contains(&c.id) {
|
||||
continue;
|
||||
@@ -452,7 +455,7 @@ pub fn locked_objects_at(doc: &Document, p: Point, opt: HitOptions) -> Vec<NodeI
|
||||
/// whole, and an unlocked layer, group, blend or envelope in Edit Contents is searched inside.
|
||||
fn locked_children(parent: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, out: &mut Vec<NodeId>) {
|
||||
let Some(children) = parent.children() else { return };
|
||||
if parent.clips() && !edits_inside(parent, opt.scope) && children.first().is_some_and(|clip| !clip_contains(clip, p)) {
|
||||
if parent.clips() && !edits_inside(parent, opt.scope) && children.first().is_some_and(|clip| !clip_contains(clip, p, opt.outline)) {
|
||||
return;
|
||||
}
|
||||
for i in hit_order(parent, children, p) {
|
||||
@@ -561,14 +564,170 @@ fn edits_contents(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::Envelope { editing: true, .. })
|
||||
}
|
||||
|
||||
/// Is `p` inside the region `clip` clips to ([`Node::clip_shapes`])? Text counts by its frame:
|
||||
/// glyph outlines need the font engine, above this crate.
|
||||
fn clip_contains(clip: &Node, p: Point) -> bool {
|
||||
clip_regions(clip).iter().any(|(bp, rule)| fill_contains(bp, *rule, p))
|
||||
/// Is `p` inside the region `clip` clips to ([`clip_areas`])? In outline mode ([`HitOptions::outline`])
|
||||
/// the canvas draws no effects, so the plain shapes of `clip` ([`clip_regions`]) count.
|
||||
fn clip_contains(clip: &Node, p: Point, outline: bool) -> bool {
|
||||
let areas = if outline { clip_regions(clip) } else { clip_areas(clip) };
|
||||
areas.iter().any(|(bp, rule)| fill_contains(bp, *rule, p))
|
||||
}
|
||||
|
||||
/// The regions `clip` clips to ([`Node::clip_shapes`]), text counted by its frame as in
|
||||
/// [`clip_contains`].
|
||||
/// The region of a clip group's clipping path as the canvas clips by it, with the live geometry
|
||||
/// effects of the clipping path and of what it clips by applied, as one path and fill rule
|
||||
/// (`Some(None)` when nothing is left to clip by). `None` when nothing in the clipping path has a
|
||||
/// live geometry effect: its plain shapes ([`clip_regions`]) count then. Effects are evaluated
|
||||
/// above this crate, so the engine registers one with [`set_clip_region`].
|
||||
pub type ClipRegion = fn(&Node) -> Option<Option<(BezPath, FillRule)>>;
|
||||
|
||||
static CLIP_REGION: OnceLock<ClipRegion> = OnceLock::new();
|
||||
|
||||
/// Register how the region of a clipping path with live effects is found (the first registration
|
||||
/// stays).
|
||||
pub fn set_clip_region(f: ClipRegion) {
|
||||
// Already set: the same engine, registered by another session.
|
||||
let _ = CLIP_REGION.set(f);
|
||||
}
|
||||
|
||||
/// Does `clip`, or anything it holds, have a visible effect of its own or on a fill or stroke? Only
|
||||
/// then can the registered [`ClipRegion`] find a geometry effect in it.
|
||||
fn has_effects(clip: &Node) -> bool {
|
||||
let mut found = false;
|
||||
clip.walk(&mut |n| {
|
||||
let visible = |e: &crate::Effect| e.visible;
|
||||
found |= n.appearance.effects.iter().any(visible) || n.appearance.items.iter().any(|i| i.effects().iter().any(visible));
|
||||
});
|
||||
found
|
||||
}
|
||||
|
||||
/// A clipping path's region evaluated by [`clip_region`] on this thread: the clipping path and the
|
||||
/// [`LiveInputs`] as they were, the region (`None` without geometry effects) and the number of its
|
||||
/// path elements.
|
||||
struct EvaluatedClip {
|
||||
clip: Node,
|
||||
inputs: u64,
|
||||
region: Option<Rc<Option<(BezPath, FillRule)>>>,
|
||||
size: usize,
|
||||
}
|
||||
|
||||
/// How many regions [`clip_region`] keeps on each thread: every click and every hover over a clip
|
||||
/// group whose clipping path has live effects asks for its region, and clip groups can be nested.
|
||||
const CLIPS_KEPT: usize = 16;
|
||||
|
||||
thread_local! {
|
||||
/// The regions [`clip_region`] keeps, the latest first.
|
||||
static CLIPS: RefCell<Vec<EvaluatedClip>> = const { RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many regions [`clip_region`] evaluated on this thread.
|
||||
static CLIPS_EVALUATED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The region clipping path `clip` clips to with its live geometry effects applied
|
||||
/// ([`set_clip_region`]), or `None` when it has none or nothing is registered; its plain shapes
|
||||
/// ([`clip_regions`]) are the region then. The region is evaluated again when `clip` or the
|
||||
/// [`LiveInputs`] have changed since.
|
||||
fn clip_region(clip: &Node) -> Option<Rc<Option<(BezPath, FillRule)>>> {
|
||||
let f = CLIP_REGION.get()?;
|
||||
if !has_effects(clip) {
|
||||
return None;
|
||||
}
|
||||
let inputs = live_inputs();
|
||||
let kept = CLIPS.with_borrow_mut(|kept| {
|
||||
let i = kept.iter().position(|e| e.inputs == inputs && e.clip == *clip)?;
|
||||
let e = kept.remove(i);
|
||||
let region = e.region.clone();
|
||||
kept.insert(0, e);
|
||||
Some(region)
|
||||
});
|
||||
if let Some(region) = kept {
|
||||
return region;
|
||||
}
|
||||
#[cfg(test)]
|
||||
CLIPS_EVALUATED.with(|c| c.set(c.get() + 1));
|
||||
let region = f(clip).map(Rc::new);
|
||||
let elements = region.as_deref().and_then(Option::as_ref).map_or(0, |(bp, _)| bp.elements().len());
|
||||
let size = elements.saturating_add(art_size(std::slice::from_ref(clip)));
|
||||
if size <= LIVE_KEPT_SIZE {
|
||||
let e = EvaluatedClip { clip: clip.clone(), inputs, region: region.clone(), size };
|
||||
CLIPS.with_borrow_mut(|kept| {
|
||||
kept.insert(0, e);
|
||||
kept.truncate(CLIPS_KEPT);
|
||||
let mut total = 0usize;
|
||||
kept.retain(|e| {
|
||||
total = total.saturating_add(e.size);
|
||||
total <= LIVE_KEPT_SIZE
|
||||
});
|
||||
});
|
||||
}
|
||||
region
|
||||
}
|
||||
|
||||
/// The box of a clipping path's region found by [`reshaped_clip_box`]: the clipping path and the
|
||||
/// [`LiveInputs`] as they were, the box and the [`art_size`] of the clipping path.
|
||||
struct ClipBox {
|
||||
clip: Node,
|
||||
inputs: u64,
|
||||
rect: Option<Rect>,
|
||||
size: usize,
|
||||
}
|
||||
|
||||
/// How many boxes [`reshaped_clip_box`] keeps on each thread. Every pointer move measures every clip
|
||||
/// group it passes, so the boxes of all of a document's clip groups with live effects are kept, not
|
||||
/// only the latest few as with the regions.
|
||||
const CLIP_BOXES_KEPT: usize = 4096;
|
||||
|
||||
thread_local! {
|
||||
/// The boxes [`reshaped_clip_box`] keeps, by clipping path, and the sum of their sizes.
|
||||
static CLIP_BOXES: RefCell<(HashMap<NodeId, ClipBox>, usize)> = RefCell::new((HashMap::new(), 0));
|
||||
}
|
||||
|
||||
/// The box of the region `clip` clips to with its live geometry effects applied ([`clip_region`]),
|
||||
/// `None` when it has none or no region. The box is kept until `clip` or the [`LiveInputs`] change.
|
||||
/// When the boxes kept are full, a new box replaces as many others as it needs room for, so the
|
||||
/// pointer moving over more clip groups than fit still finds most of their boxes.
|
||||
pub(crate) fn reshaped_clip_box(clip: &Node) -> Option<Rect> {
|
||||
use vectorcraft_geom::kurbo::Shape;
|
||||
CLIP_REGION.get()?;
|
||||
if !has_effects(clip) {
|
||||
return None;
|
||||
}
|
||||
let inputs = live_inputs();
|
||||
let kept = CLIP_BOXES.with_borrow(|(boxes, _)| boxes.get(&clip.id).filter(|b| b.inputs == inputs && b.clip == *clip).map(|b| b.rect));
|
||||
if let Some(rect) = kept {
|
||||
return rect;
|
||||
}
|
||||
let rect = clip_region(clip).and_then(|r| r.as_ref().as_ref().filter(|(bp, _)| !bp.elements().is_empty()).map(|(bp, _)| bp.bounding_box()));
|
||||
let size = art_size(std::slice::from_ref(clip));
|
||||
if size <= LIVE_KEPT_SIZE {
|
||||
CLIP_BOXES.with_borrow_mut(|(boxes, total)| {
|
||||
if let Some(old) = boxes.remove(&clip.id) {
|
||||
*total = total.saturating_sub(old.size);
|
||||
}
|
||||
while boxes.len() >= CLIP_BOXES_KEPT || total.saturating_add(size) > LIVE_KEPT_SIZE {
|
||||
let Some(other) = boxes.keys().next().copied() else { break };
|
||||
if let Some(old) = boxes.remove(&other) {
|
||||
*total = total.saturating_sub(old.size);
|
||||
}
|
||||
}
|
||||
boxes.insert(clip.id, ClipBox { clip: clip.clone(), inputs, rect, size });
|
||||
*total = total.saturating_add(size);
|
||||
});
|
||||
}
|
||||
rect
|
||||
}
|
||||
|
||||
/// The regions a click inside a clip group must fall in: those `clip` clips to with its live
|
||||
/// effects applied, as the canvas clips ([`clip_region`]), else its plain shapes ([`clip_regions`]).
|
||||
fn clip_areas(clip: &Node) -> Vec<(BezPath, FillRule)> {
|
||||
match clip_region(clip) {
|
||||
Some(region) => region.as_ref().iter().cloned().collect(),
|
||||
None => clip_regions(clip),
|
||||
}
|
||||
}
|
||||
|
||||
/// The regions `clip` clips to by its plain shapes ([`Node::clip_shapes`]), without its live
|
||||
/// effects. Text counts by its frame: glyph outlines need the font engine, above this crate.
|
||||
pub fn clip_regions(clip: &Node) -> Vec<(vectorcraft_geom::BezPath, vectorcraft_geom::FillRule)> {
|
||||
let frame = |n: &Node| {
|
||||
let b = n.geometric_bounds()?;
|
||||
@@ -698,7 +857,7 @@ fn hit_children(
|
||||
// Elsewhere a clip group (or a layer with a clipping mask) only hits inside it, except for
|
||||
// the selection tools in isolation mode within it.
|
||||
let edited = opt.clip_outlines && editable_only && edits_inside(parent, opt.scope);
|
||||
if !edited && !clip_contains(clip, p) {
|
||||
if !edited && !clip_contains(clip, p, opt.outline) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
@@ -960,7 +1119,7 @@ fn hit_any(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option
|
||||
match &n.kind {
|
||||
// A clip group only hits inside its clipping path.
|
||||
NodeKind::Group { children, clip } => {
|
||||
if *clip && children.first().is_some_and(|c| !clip_contains(c, p)) {
|
||||
if *clip && children.first().is_some_and(|c| !clip_contains(c, p, opt.outline)) {
|
||||
return None;
|
||||
}
|
||||
children.iter().rev().find_map(|c| hit_any(c, p, opt, symbols))
|
||||
@@ -1048,7 +1207,9 @@ fn moved(n: &Node, xf: vectorcraft_geom::Affine) -> Node {
|
||||
/// group's original shapes, which the canvas does not draw, and guide paths with
|
||||
/// [`HitOptions::skip_guides`]. Nothing is picked in art that placing through the symbol's 9-slice
|
||||
/// guides could make more than [`crate::MAX_SYMBOL_NODES`] objects of, which the canvas does not
|
||||
/// draw. `None` when `inst` is not a symbol instance or no editable object of its art is under `p`.
|
||||
/// draw. Art in a layer of the symbol whose Preview is off, and the art of an instance below such a
|
||||
/// layer, is tested in outline ([`HitOptions::outline`]), as the canvas draws it. `None` when `inst` is not a symbol instance or
|
||||
/// no editable object of its art is under `p`.
|
||||
pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> Option<Vec<u32>> {
|
||||
struct Find<'a> {
|
||||
art: &'a InstanceArt<'a>,
|
||||
@@ -1057,35 +1218,34 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) ->
|
||||
symbols: &'a SymbolBoxes<'a>,
|
||||
}
|
||||
impl Find<'_> {
|
||||
fn hit(&self, n: &Node, whole: Option<vectorcraft_geom::Affine>) -> bool {
|
||||
self.art.place(n, whole).is_some_and(|n| hit_any(&n, self.p, self.opt, self.symbols).is_some())
|
||||
fn hit(&self, n: &Node, whole: Option<vectorcraft_geom::Affine>, opt: HitOptions) -> bool {
|
||||
self.art.place(n, whole).is_some_and(|n| hit_any(&n, self.p, opt, self.symbols).is_some())
|
||||
}
|
||||
fn skips_guide(&self, n: &Node) -> bool {
|
||||
self.opt.skip_guides && matches!(n.kind, NodeKind::Path { guide: true, .. })
|
||||
}
|
||||
fn find(&self, n: &Node, path: &mut Vec<u32>, whole: Option<vectorcraft_geom::Affine>) -> bool {
|
||||
/// `outline`: the view is in Outline, or a layer around `n` has Preview off.
|
||||
fn find(&self, n: &Node, path: &mut Vec<u32>, whole: Option<vectorcraft_geom::Affine>, outline: bool) -> bool {
|
||||
if !n.visible || n.locked || n.is_template() || self.skips_guide(n) {
|
||||
return false;
|
||||
}
|
||||
let (NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }) = &n.kind else { return self.hit(n, whole) };
|
||||
let outline = outline || previews_off(n);
|
||||
let opt = HitOptions { outline, ..self.opt };
|
||||
let (NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }) = &n.kind else { return self.hit(n, whole, opt) };
|
||||
if path.len() >= crate::symbol_overrides::MAX_PATH_DEPTH {
|
||||
return self.hit(n, whole);
|
||||
return self.hit(n, whole, opt);
|
||||
}
|
||||
let whole = self.art.whole(n, whole);
|
||||
if n.clips()
|
||||
&& let Some(first) = children.first()
|
||||
{
|
||||
let Some(clip) = self.art.place_unclipped(first, whole) else { return false };
|
||||
if self.opt.clip_outlines
|
||||
&& first.visible
|
||||
&& !first.locked
|
||||
&& !self.skips_guide(first)
|
||||
&& clip_outline(&clip, self.p, self.opt).is_some()
|
||||
if self.opt.clip_outlines && first.visible && !first.locked && !self.skips_guide(first) && clip_outline(&clip, self.p, opt).is_some()
|
||||
{
|
||||
path.push(0);
|
||||
return true;
|
||||
}
|
||||
if !clip_contains(&clip, self.p) {
|
||||
if !clip_contains(&clip, self.p, outline) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1096,7 +1256,7 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) ->
|
||||
}
|
||||
let Ok(i) = u32::try_from(i) else { continue };
|
||||
path.push(i);
|
||||
if self.find(c, path, whole) {
|
||||
if self.find(c, path, whole, outline) {
|
||||
return true;
|
||||
}
|
||||
path.pop();
|
||||
@@ -1107,7 +1267,17 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) ->
|
||||
let art = InstanceArt::of(doc, inst)?;
|
||||
let symbols = doc.symbol_boxes();
|
||||
let mut path = vec![];
|
||||
Find { art: &art, p, opt, symbols: &symbols }.find(&art.art, &mut path, None).then_some(path)
|
||||
let outline = opt.outline || below_preview_off(doc, inst, opt.scope);
|
||||
Find { art: &art, p, opt, symbols: &symbols }.find(&art.art, &mut path, None, outline).then_some(path)
|
||||
}
|
||||
|
||||
/// Is `n` below a layer whose Preview is off, so that the canvas draws it in outline? As for clicks
|
||||
/// ([`path_options`]), the Preview of the isolated container `scope` and of the layers around it
|
||||
/// does not count.
|
||||
fn below_preview_off(doc: &Document, n: &Node, scope: Option<NodeId>) -> bool {
|
||||
let Some(chain) = doc.ancestry(n.id) else { return false };
|
||||
let below = scope.and_then(|s| chain.iter().position(|a| *a == s)).map_or(0, |i| i + 1);
|
||||
chain.iter().skip(below).any(|a| doc.node(*a).is_some_and(previews_off))
|
||||
}
|
||||
|
||||
/// The outlines of the object at `path` in symbol instance `inst`'s art (see [`symbol_part_at`]),
|
||||
@@ -1116,11 +1286,23 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) ->
|
||||
/// group per cell) they are cut to the bounds of the group's clip path, which is not outlined. An
|
||||
/// object inside a clip group or a clipping layer of the art, other than its clipping path, is cut
|
||||
/// to the bounds of that clipping path as well, which contain the region where [`symbol_part_at`]
|
||||
/// picks it.
|
||||
/// picks it: the bounds of the region its live geometry effects give it ([`clip_region`]) when it
|
||||
/// has any.
|
||||
/// `None` for art past the 9-slice object limit that [`symbol_part_at`] applies.
|
||||
pub fn symbol_part_outline(doc: &Document, inst: &Node, path: &[u32]) -> Option<BezPath> {
|
||||
symbol_part_outline_in_view(doc, inst, path, HitOptions::default())
|
||||
}
|
||||
|
||||
/// [`symbol_part_outline`] in the view the canvas shows, for the clicks of `opt`: in Outline view
|
||||
/// ([`HitOptions::outline`]) and below a layer whose Preview is off, in the art or around the
|
||||
/// instance (the isolated container [`HitOptions::scope`] and the layers around it apart), the
|
||||
/// outlines are cut to the bounds of the plain clipping paths, without their live effects, as
|
||||
/// [`symbol_part_at`] counts them. The outline is empty when the effects of a clipping path around
|
||||
/// the object leave no region.
|
||||
pub fn symbol_part_outline_in_view(doc: &Document, inst: &Node, path: &[u32], opt: HitOptions) -> Option<BezPath> {
|
||||
let art = InstanceArt::of(doc, inst)?;
|
||||
let part = crate::symbol_overrides::part(&art.art, path)?;
|
||||
let mut outline = opt.outline || below_preview_off(doc, inst, opt.scope);
|
||||
let mut out = BezPath::new();
|
||||
let mut limit = None;
|
||||
let mut whole = None;
|
||||
@@ -1128,24 +1310,40 @@ pub fn symbol_part_outline(doc: &Document, inst: &Node, path: &[u32]) -> Option<
|
||||
for &i in path {
|
||||
let children = n.children()?;
|
||||
whole = art.whole(n, whole);
|
||||
outline = outline || previews_off(n);
|
||||
if i != 0
|
||||
&& n.clips()
|
||||
&& let Some(first) = children.first()
|
||||
&& let Some(clip) = art.place_unclipped(first, whole)?.geometric_bounds()
|
||||
{
|
||||
match meet(Some(clip), limit) {
|
||||
Some(r) => limit = Some(r),
|
||||
None => return Some(out),
|
||||
}
|
||||
let Some(within) = limit_within(&art.place_unclipped(first, whole)?, limit, outline) else { return Some(out) };
|
||||
limit = within;
|
||||
}
|
||||
n = children.get(usize::try_from(i).ok()?)?;
|
||||
}
|
||||
outline_within(&art.place(part, whole)?, limit, &mut out);
|
||||
outline_within(&art.place(part, whole)?, limit, outline, &mut out);
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// [`symbol_part_outline`] for placed object `n`, cut to `limit` when there is one.
|
||||
fn outline_within(n: &Node, limit: Option<Rect>, out: &mut BezPath) {
|
||||
/// `limit` cut to the box that the art clipped by `clip` is drawn in: the bounds of the region the
|
||||
/// live geometry effects of `clip` give it ([`clip_region`]), or the bounds of `clip` when it has no
|
||||
/// such effects and with `outline`, where the canvas draws no effects. `None` when none of that art
|
||||
/// is drawn: the effects leave no region, or the box is outside `limit`.
|
||||
fn limit_within(clip: &Node, limit: Option<Rect>, outline: bool) -> Option<Option<Rect>> {
|
||||
use vectorcraft_geom::kurbo::Shape;
|
||||
let region = if outline { None } else { clip_region(clip) };
|
||||
let bounds = match region.as_deref() {
|
||||
Some(Some((bp, _))) if !bp.elements().is_empty() => Some(bp.bounding_box()),
|
||||
Some(_) => return None,
|
||||
None => clip.geometric_bounds(),
|
||||
};
|
||||
match bounds {
|
||||
Some(b) => meet(Some(b), limit).map(Some),
|
||||
None => Some(limit),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`symbol_part_outline_in_view`] for placed object `n`, cut to `limit` when there is one.
|
||||
fn outline_within(n: &Node, limit: Option<Rect>, outline: bool, out: &mut BezPath) {
|
||||
use vectorcraft_geom::kurbo::Shape;
|
||||
if let Some(pd) = n.path_data() {
|
||||
match limit {
|
||||
@@ -1159,20 +1357,15 @@ fn outline_within(n: &Node, limit: Option<Rect>, out: &mut BezPath) {
|
||||
out.extend(b.to_path(0.1));
|
||||
}
|
||||
let Some(children) = n.children() else { return };
|
||||
let outline = outline || previews_off(n);
|
||||
if n.clips()
|
||||
&& let Some((first, rest)) = children.split_first()
|
||||
{
|
||||
let inner = match first.geometric_bounds() {
|
||||
Some(c) => match meet(Some(c), limit) {
|
||||
Some(r) => Some(r),
|
||||
None => return,
|
||||
},
|
||||
None => limit,
|
||||
};
|
||||
rest.iter().for_each(|c| outline_within(c, inner, out));
|
||||
let Some(inner) = limit_within(first, limit, outline) else { return };
|
||||
rest.iter().for_each(|c| outline_within(c, inner, outline, out));
|
||||
return;
|
||||
}
|
||||
children.iter().for_each(|c| outline_within(c, limit, out));
|
||||
children.iter().for_each(|c| outline_within(c, limit, outline, out));
|
||||
}
|
||||
|
||||
/// The overlap of `a` and `b` (`a` alone without `b`), `None` when they do not overlap.
|
||||
@@ -1248,31 +1441,48 @@ pub fn compound_part_at(n: &Node, p: Point, tol: f64) -> Option<NodeId> {
|
||||
/// or of the parent of the single object isolated, does not limit the marquee, as it does not limit
|
||||
/// the selection tools' clicks.
|
||||
pub fn marquee(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool) -> Vec<NodeId> {
|
||||
marquee_with(doc, r, scope, leaves, false)
|
||||
marquee_with(doc, r, scope, leaves, false, false)
|
||||
}
|
||||
|
||||
/// [`marquee`] in the view the canvas shows: with `outline` (Outline view), and below a layer
|
||||
/// whose Preview is off, a clipping path counts by its plain shapes, without its live effects, as
|
||||
/// the clicks of [`HitOptions::outline`] do.
|
||||
pub fn marquee_in_view(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, outline: bool) -> Vec<NodeId> {
|
||||
marquee_with(doc, r, scope, leaves, false, outline)
|
||||
}
|
||||
|
||||
/// Candidates for whole-object enclosure by a loop bounded by `r`. Eligibility and group
|
||||
/// traversal follow [`marquee`]; compounds contribute the complete path they paint.
|
||||
pub fn enclosure_candidates(doc: &Document, r: Rect, scope: Option<NodeId>) -> Vec<NodeId> {
|
||||
marquee_with(doc, r, scope, true, true)
|
||||
/// traversal follow [`marquee_in_view`]; compounds contribute the complete path they paint.
|
||||
pub fn enclosure_candidates(doc: &Document, r: Rect, scope: Option<NodeId>, outline: bool) -> Vec<NodeId> {
|
||||
marquee_with(doc, r, scope, true, true, outline)
|
||||
}
|
||||
|
||||
fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, whole_compounds: bool) -> Vec<NodeId> {
|
||||
/// Is `n` a layer whose Preview is off (its art is drawn and clicked in outline)?
|
||||
fn previews_off(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::Layer { preview: false, .. })
|
||||
}
|
||||
|
||||
fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, whole_compounds: bool, outline: bool) -> Vec<NodeId> {
|
||||
let mut out = Vec::new();
|
||||
// `tops` pairs each object with the part of `r` in which the marquee can touch it.
|
||||
let tops: Vec<(&std::sync::Arc<Node>, Rect)> = match scope.and_then(|s| doc.node(s)) {
|
||||
// The objects the marquee may touch ([`Top`]).
|
||||
let tops: Vec<Top> = match scope.and_then(|s| doc.node(s)) {
|
||||
// Isolated art whose layer, or a group around it, was locked or hidden afterwards: the
|
||||
// marquee touches none of it, as clicks don't (#5309).
|
||||
Some(s) if !doc.is_editable(s.id) => vec![],
|
||||
Some(s) => match s.children() {
|
||||
Some(c) => c.iter().enumerate().filter(|(i, c)| !c.is_ruler_guide() && !shaper_hides(s, *i, scope)).map(|(_, c)| (c, r)).collect(),
|
||||
Some(c) => c
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(i, c)| !c.is_ruler_guide() && !shaper_hides(s, *i, scope))
|
||||
.map(|(_, c)| (c, Some(r), outline, None))
|
||||
.collect(),
|
||||
// A single object isolated: only it.
|
||||
None => doc
|
||||
.parent_of(s.id)
|
||||
.and_then(|p| doc.node(p))
|
||||
.and_then(|p| p.children())
|
||||
.into_iter()
|
||||
.flat_map(|c| c.iter().filter(|c| c.id == s.id).map(|c| (c, r)))
|
||||
.flat_map(|c| c.iter().filter(|c| c.id == s.id).map(|c| (c, Some(r), outline, None)))
|
||||
.collect(),
|
||||
},
|
||||
// The objects of the layers, looking through sublayers (hidden, locked and template ones
|
||||
@@ -1281,42 +1491,88 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
.layers
|
||||
.iter()
|
||||
.filter(|l| l.visible && !l.locked && !l.is_template() && doc.pattern_edit.as_ref().is_none_or(|e| e.layer == l.id))
|
||||
.flat_map(|l| layer_objects(l, r))
|
||||
.flat_map(|l| layer_objects(l, r, outline))
|
||||
.collect(),
|
||||
};
|
||||
/// The objects of layer `l`, each with the part of `r` that the clipping masks of `l` and of
|
||||
/// the sublayers it is in leave.
|
||||
fn layer_objects(l: &Node, r: Rect) -> Vec<(&std::sync::Arc<Node>, Rect)> {
|
||||
/// the sublayers it is in leave, whether it is in outline, and for the clipping mask of `l`,
|
||||
/// `r` for its edge test. The clipping mask itself counts by its own geometry within its plain
|
||||
/// shapes ([`mask_marquee`]).
|
||||
fn layer_objects(l: &Node, r: Rect, outline: bool) -> Vec<Top<'_>> {
|
||||
let mut out = vec![];
|
||||
let Some(r) = marquee_in(l, r) else { return out };
|
||||
for c in l.children().into_iter().flatten() {
|
||||
let outline = outline || previews_off(l);
|
||||
let inner = marquee_in_parent(l, r, outline);
|
||||
for (i, c) in l.children().into_iter().flatten().enumerate() {
|
||||
if c.is_layer() {
|
||||
if c.visible && !c.locked && !c.is_template() {
|
||||
out.extend(layer_objects(c, r));
|
||||
if let Some(inner) = inner
|
||||
&& c.visible
|
||||
&& !c.locked
|
||||
&& !c.is_template()
|
||||
{
|
||||
out.extend(layer_objects(c, inner, outline));
|
||||
}
|
||||
} else if !c.is_ruler_guide() {
|
||||
out.push((c, r));
|
||||
if i == 0 && l.clips() {
|
||||
out.push((c, mask_marquee(l, r), outline, Some(r)));
|
||||
} else if inner.is_some() {
|
||||
out.push((c, inner, outline, None));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
/// The part of `r` in which the marquee can touch the clipping path of `parent` by its own
|
||||
/// geometry: within the bounds of its plain shapes ([`marquee_in`]), where clicks find its
|
||||
/// outline too ([`clip_outline_hit`]), whatever its live effects do to the region it clips to.
|
||||
fn mask_marquee(parent: &Node, r: Rect) -> Option<Rect> {
|
||||
marquee_in_parent(parent, r, true)
|
||||
}
|
||||
/// Does the marquee `r` touch `clip`, the clipping path of a clip group or of a layer with a
|
||||
/// clipping mask, on the edge of the region its live effects give it ([`clip_region`]), where
|
||||
/// the clip shows? Never in outline, nor without live effects: its own geometry counts then.
|
||||
fn clip_edge_touches(clip: &Node, r: Rect, outline: bool) -> bool {
|
||||
if outline {
|
||||
return false;
|
||||
}
|
||||
clip_region(clip).is_some_and(|region| {
|
||||
region.as_ref().as_ref().is_some_and(|(bp, _)| {
|
||||
// The edge of the region is its outline with each open subpath closed, as `fill_contains` fills it.
|
||||
let mut edge = PathData::from_bezpath(bp);
|
||||
edge.subpaths.iter_mut().for_each(|sp| sp.closed = true);
|
||||
vectorcraft_geom::hit::intersects_rect(&edge, r)
|
||||
})
|
||||
})
|
||||
}
|
||||
/// Is `n` collected whole by [`collect_leaves`], not by its members?
|
||||
fn is_leaf(n: &Node) -> bool {
|
||||
!matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Intertwine { .. })
|
||||
}
|
||||
/// Does the marquee `r` touch `n`? It skips the children of a Shaper Group that clicks skip
|
||||
/// ([`shaper_hides`]). An Intertwine group is touched by its members, and a repeat is touched
|
||||
/// by the copies it draws, as clicks hit them. Objects of every other kind except paths,
|
||||
/// compound paths, layers and groups are touched by their box.
|
||||
fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, whole_compounds: bool) -> bool {
|
||||
/// compound paths, layers and groups are touched by their box. A clipping path is touched by
|
||||
/// its own geometry ([`mask_marquee`]) and on the edge of its region ([`clip_edge_touches`]).
|
||||
fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, whole_compounds: bool, outline: bool) -> bool {
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, .. } => vectorcraft_geom::hit::intersects_rect(path, r),
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => {
|
||||
marquee_in(n, r).is_some_and(|r| {
|
||||
children.iter().enumerate().any(|(i, c)| c.visible && !shaper_hides(n, i, scope) && touches(c, s, r, scope, whole_compounds))
|
||||
let outline = outline || previews_off(n);
|
||||
let inner = marquee_in_parent(n, r, outline);
|
||||
children.iter().enumerate().any(|(i, c)| {
|
||||
c.visible
|
||||
&& !shaper_hides(n, i, scope)
|
||||
&& if i == 0 && n.clips() {
|
||||
mask_marquee(n, r).is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline)) || clip_edge_touches(c, r, outline)
|
||||
} else {
|
||||
inner.is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline))
|
||||
}
|
||||
})
|
||||
}
|
||||
NodeKind::Compound { children, .. } if whole_compounds => {
|
||||
children.iter().filter_map(|c| c.path_data()).any(|path| vectorcraft_geom::hit::intersects_rect(path, r))
|
||||
}
|
||||
NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, whole_compounds)),
|
||||
NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, whole_compounds)),
|
||||
NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, whole_compounds, outline)),
|
||||
NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, whole_compounds, outline)),
|
||||
// A box with no width or no height (an instance of a symbol that draws a straight
|
||||
// line) is touched where the marquee crosses it.
|
||||
_ => n.geometric_bounds_with(s).is_some_and(|b| {
|
||||
@@ -1325,18 +1581,30 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
}),
|
||||
}
|
||||
}
|
||||
fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, whole_compounds: bool, out: &mut Vec<NodeId>) {
|
||||
fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, whole_compounds: bool, outline: bool, out: &mut Vec<NodeId>) {
|
||||
match &n.kind {
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => {
|
||||
let Some(r) = marquee_in(n, r) else { return };
|
||||
let outline = outline || previews_off(n);
|
||||
let inner = marquee_in_parent(n, r, outline);
|
||||
for (i, c) in children.iter().enumerate() {
|
||||
if c.visible && !c.locked && !shaper_hides(n, i, scope) {
|
||||
collect_leaves(c, s, r, scope, whole_compounds, out);
|
||||
if !c.visible || c.locked || shaper_hides(n, i, scope) {
|
||||
continue;
|
||||
}
|
||||
if i == 0 && n.clips() {
|
||||
let before = out.len();
|
||||
if let Some(r) = mask_marquee(n, r) {
|
||||
collect_leaves(c, s, r, scope, whole_compounds, outline, out);
|
||||
}
|
||||
if out.len() == before && is_leaf(c) && clip_edge_touches(c, r, outline) {
|
||||
out.push(c.id);
|
||||
}
|
||||
} else if let Some(r) = inner {
|
||||
collect_leaves(c, s, r, scope, whole_compounds, outline, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if touches(n, s, r, scope, whole_compounds) {
|
||||
if touches(n, s, r, scope, whole_compounds, outline) {
|
||||
out.push(n.id);
|
||||
}
|
||||
}
|
||||
@@ -1344,36 +1612,56 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
}
|
||||
let symbols = doc.symbol_boxes();
|
||||
let locks = doc.locked_artboards();
|
||||
for (t, r) in tops {
|
||||
for (t, r, outline, edge) in tops {
|
||||
if !t.visible || t.locked || locks.holds_id(t.id) {
|
||||
continue;
|
||||
}
|
||||
if leaves {
|
||||
collect_leaves(t, &symbols, r, scope, whole_compounds, &mut out);
|
||||
} else if touches(t, &symbols, r, scope, whole_compounds) {
|
||||
let before = out.len();
|
||||
if let Some(r) = r {
|
||||
collect_leaves(t, &symbols, r, scope, whole_compounds, outline, &mut out);
|
||||
}
|
||||
if edge.is_some_and(|e| out.len() == before && is_leaf(t) && clip_edge_touches(t, e, outline)) {
|
||||
out.push(t.id);
|
||||
}
|
||||
} else if r.is_some_and(|r| touches(t, &symbols, r, scope, whole_compounds, outline))
|
||||
|| edge.is_some_and(|e| clip_edge_touches(t, e, outline))
|
||||
{
|
||||
out.push(t.id);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// An object a marquee may touch ([`marquee_with`]): the object, the part of the marquee in which
|
||||
/// it can be touched (`None` when nowhere), whether it is in outline, and for the clipping mask of a
|
||||
/// layer, the marquee whose edge test it also takes (`clip_edge_touches`).
|
||||
type Top<'a> = (&'a std::sync::Arc<Node>, Option<Rect>, bool, Option<Rect>);
|
||||
|
||||
/// The part of a marquee `r` in which it can touch the children of `parent`. For a clip group or a
|
||||
/// layer with a clipping mask, this is what [`marquee_in_clip`] returns for its clipping path (None
|
||||
/// when the marquee misses it); otherwise it is all of `r`.
|
||||
/// layer with a clipping mask, this is what [`marquee_in_clip`] returns for the plain shapes of its
|
||||
/// clipping path ([`clip_regions`]; None when the marquee misses them); otherwise it is all of `r`.
|
||||
pub fn marquee_in(parent: &Node, r: Rect) -> Option<Rect> {
|
||||
marquee_in_parent(parent, r, true)
|
||||
}
|
||||
|
||||
/// The part of a marquee `r` in which it can touch the children of `parent`, by the region its
|
||||
/// clipping path clips to ([`clip_areas`]), or by that path's plain shapes with `outline`
|
||||
/// ([`marquee_in_view`]).
|
||||
fn marquee_in_parent(parent: &Node, r: Rect, outline: bool) -> Option<Rect> {
|
||||
match parent.children().and_then(|c| c.first()) {
|
||||
Some(clip) if parent.clips() => marquee_in_clip(clip, r),
|
||||
Some(clip) if parent.clips() => marquee_in_clip(clip, r, outline),
|
||||
_ => Some(r),
|
||||
}
|
||||
}
|
||||
|
||||
/// The part of a marquee `r` in which it can touch the art that `clip` clips (the clipping path of
|
||||
/// a clip group or of a layer with a clipping mask): `r` cut to the bounds of the regions `clip`
|
||||
/// clips to ([`clip_regions`]), or `None` when `r` meets none of those regions. Within those
|
||||
/// bounds, art outside a region that is not a rectangle still counts.
|
||||
fn marquee_in_clip(clip: &Node, r: Rect) -> Option<Rect> {
|
||||
/// clips to ([`clip_areas`], its plain shapes with `outline`), or `None` when `r` meets none of
|
||||
/// those regions. Within those bounds, art outside a region that is not a rectangle still counts.
|
||||
fn marquee_in_clip(clip: &Node, r: Rect, outline: bool) -> Option<Rect> {
|
||||
use vectorcraft_geom::kurbo::Shape;
|
||||
let regions = clip_regions(clip);
|
||||
let regions = if outline { clip_regions(clip) } else { clip_areas(clip) };
|
||||
// The edge of a region is its outline with each open subpath closed, as `fill_contains` fills it.
|
||||
let meets = |(bp, rule): &(vectorcraft_geom::BezPath, vectorcraft_geom::FillRule)| {
|
||||
let mut edge = vectorcraft_geom::PathData::from_bezpath(bp);
|
||||
|
||||
@@ -110,6 +110,252 @@ fn half_clipped(d: &mut Document) -> (Node, Node) {
|
||||
(mask, art)
|
||||
}
|
||||
|
||||
/// A stand-in for the engine's [`ClipRegion`]: with an effect named `test.move` in the clipping
|
||||
/// path, its first shape moved 100 pt right; with one named `test.empty`, no region left to clip
|
||||
/// by; without either, no geometry effect.
|
||||
fn moved_clip_region(clip: &Node) -> Option<Option<(BezPath, FillRule)>> {
|
||||
let (mut moves, mut empty) = (false, false);
|
||||
clip.walk(&mut |n| {
|
||||
moves |= n.appearance.effects.iter().any(|e| e.visible && e.id == "test.move");
|
||||
empty |= n.appearance.effects.iter().any(|e| e.visible && e.id == "test.empty");
|
||||
});
|
||||
if empty {
|
||||
return Some(None);
|
||||
}
|
||||
if !moves {
|
||||
return None;
|
||||
}
|
||||
Some(clip_regions(clip).into_iter().next().map(|(mut bp, rule)| {
|
||||
bp.apply_affine(vectorcraft_geom::Affine::translate((100.0, 0.0)));
|
||||
(bp, rule)
|
||||
}))
|
||||
}
|
||||
|
||||
/// A visible effect named `test.move`, which [`moved_clip_region`] reads as moving the region.
|
||||
fn test_move() -> crate::Effect {
|
||||
crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true }
|
||||
}
|
||||
|
||||
/// Clicks inside a clip group whose clipping path has a live effect fall in the region the
|
||||
/// registered [`ClipRegion`] gives it. The pointer moving over it evaluates the region once, and
|
||||
/// again after the clipping path changes; a clipping path without effects is not evaluated.
|
||||
#[test]
|
||||
fn clicks_in_a_clip_group_evaluate_its_clipping_paths_region_once_until_it_changes() {
|
||||
set_clip_region(moved_clip_region);
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (mut mask, art) = half_clipped(&mut d);
|
||||
mask.appearance.effects.push(crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true });
|
||||
let (g, mask_id, art_id) = (d.alloc_id(), mask.id, art.id);
|
||||
let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]);
|
||||
clip.set_clips(true);
|
||||
d.insert(Some(l), 0, clip).unwrap();
|
||||
let evaluated = || CLIPS_EVALUATED.with(std::cell::Cell::get);
|
||||
let before = evaluated();
|
||||
let leaf = |d: &Document, x: f64| hit_test(d, Point::new(x, 50.0), HitOptions::default()).map(|h| h.leaf);
|
||||
for x in [148.0, 150.0, 152.0] {
|
||||
assert_eq!(leaf(&d, x), Some(art_id), "in the moved region");
|
||||
}
|
||||
assert_eq!(leaf(&d, 50.0), None, "the clipping path's own place");
|
||||
assert_eq!(evaluated(), before + 1);
|
||||
// Outline mode draws no effects: the art's edge shows within the clipping path's own shape.
|
||||
let outline = HitOptions { outline: true, ..HitOptions::default() };
|
||||
assert_eq!(hit_test(&d, Point::new(50.0, 0.5), outline).map(|h| h.leaf), Some(art_id), "outline mode");
|
||||
// So with a marquee across the art's left edge: in the view, only in Outline view. The
|
||||
// clipping path's own left edge lies there too, and counts in both.
|
||||
let edge = Rect::new(-5.0, 40.0, 5.0, 60.0);
|
||||
assert_eq!(marquee_in_view(&d, edge, None, true, false), [mask_id]);
|
||||
assert_eq!(marquee_in_view(&d, edge, None, true, true), [mask_id, art_id]);
|
||||
// `marquee_in` measures by the plain shapes, as its callers clip by them.
|
||||
assert!(marquee_in(d.node(g).unwrap(), edge).is_some());
|
||||
// Hidden, the effect no longer moves the region.
|
||||
d.node_mut(mask_id).unwrap().appearance.effects[0].visible = false;
|
||||
assert_eq!(leaf(&d, 50.0), Some(art_id));
|
||||
assert_eq!(leaf(&d, 150.0), None);
|
||||
assert_eq!(evaluated(), before + 1);
|
||||
// Shown again and widened, the region is evaluated again.
|
||||
let mask = d.node_mut(mask_id).unwrap();
|
||||
mask.appearance.effects[0].visible = true;
|
||||
if let NodeKind::Path { path, .. } = &mut mask.kind {
|
||||
*path = shapes::rectangle(Rect::new(0.0, 0.0, 90.0, 100.0));
|
||||
}
|
||||
assert_eq!(leaf(&d, 180.0), Some(art_id));
|
||||
assert_eq!(leaf(&d, 195.0), None);
|
||||
assert_eq!(evaluated(), before + 2);
|
||||
}
|
||||
|
||||
/// A marquee around a clipping path that an effect moved into the middle of large art touches the
|
||||
/// clipping path on the edge of its moved region, in a clip group and in a clipping layer.
|
||||
#[test]
|
||||
fn a_marquee_touches_a_moved_clipping_path_on_its_region() {
|
||||
set_clip_region(moved_clip_region);
|
||||
let parts = |d: &mut Document| {
|
||||
let mut mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(20.0, 20.0, 60.0, 60.0)), Appearance::default());
|
||||
mask.appearance.effects.push(crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true });
|
||||
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 300.0, 300.0)), Appearance::default_art());
|
||||
(mask, art)
|
||||
};
|
||||
// Around the moved region (120..160) and the clipping path's own place, inside the art.
|
||||
let around = Rect::new(10.0, 10.0, 170.0, 70.0);
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
let l = d.layers[0].id;
|
||||
let (mask, art) = parts(&mut d);
|
||||
let (g, mask_id) = (d.alloc_id(), mask.id);
|
||||
let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]);
|
||||
clip.set_clips(true);
|
||||
d.insert(Some(l), 0, clip).unwrap();
|
||||
assert_eq!(marquee(&d, around, None, false), [g]);
|
||||
assert_eq!(marquee(&d, around, None, true), [mask_id]);
|
||||
// Only over the clipping path's own place, the marquee misses the region but touches the
|
||||
// clipping path's anchors, which a click on its outline also finds.
|
||||
let own = Rect::new(10.0, 10.0, 70.0, 70.0);
|
||||
assert_eq!(marquee(&d, own, None, false), [g]);
|
||||
assert_eq!(marquee(&d, own, None, true), [mask_id]);
|
||||
// Away from both, nothing.
|
||||
assert!(marquee(&d, Rect::new(70.0, 10.0, 110.0, 70.0), None, true).is_empty());
|
||||
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
let top = d.layers[0].id;
|
||||
let (mask, art) = parts(&mut d);
|
||||
let mask_id = mask.id;
|
||||
let mut sublayer = (*d.layers[0]).clone();
|
||||
sublayer.id = d.alloc_id();
|
||||
if let NodeKind::Layer { children, clip, .. } = &mut sublayer.kind {
|
||||
(*children, *clip) = (vec![Arc::new(mask), Arc::new(art)], true);
|
||||
}
|
||||
d.insert(Some(top), 0, sublayer).unwrap();
|
||||
assert_eq!(marquee(&d, around, None, false), [mask_id]);
|
||||
}
|
||||
|
||||
/// A clipping layer whose Preview is off draws its art in outline: clicks, the objects at a point
|
||||
/// and marquees count its clipping path by its plain shape, without the effect that moves it.
|
||||
#[test]
|
||||
fn a_clipping_layer_with_preview_off_counts_its_plain_clipping_path() {
|
||||
set_clip_region(moved_clip_region);
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let top = d.layers[0].id;
|
||||
let (mut mask, art) = half_clipped(&mut d);
|
||||
mask.appearance.effects.push(crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true });
|
||||
let art_id = art.id;
|
||||
let mut sublayer = (*d.layers[0]).clone();
|
||||
sublayer.id = d.alloc_id();
|
||||
if let NodeKind::Layer { children, clip, preview, .. } = &mut sublayer.kind {
|
||||
(*children, *clip, *preview) = (vec![Arc::new(mask), Arc::new(art)], true, false);
|
||||
}
|
||||
d.insert(Some(top), 0, sublayer).unwrap();
|
||||
// The art's top edge, within the clipping path's own shape.
|
||||
let p = Point::new(50.0, 0.5);
|
||||
assert_eq!(hit_test(&d, p, HitOptions::default()).map(|h| h.leaf), Some(art_id));
|
||||
assert_eq!(objects_at(&d, p, HitOptions::default(), None).first(), Some(&art_id));
|
||||
assert!(marquee(&d, Rect::new(45.0, -5.0, 55.0, 5.0), None, true).contains(&art_id));
|
||||
}
|
||||
|
||||
/// The pointer moving over empty canvas past more clip groups with live effects than the regions
|
||||
/// kept measures each group's box once: the boxes are kept for every clip group.
|
||||
#[test]
|
||||
fn hovers_past_many_clip_groups_evaluate_each_clipping_path_once() {
|
||||
set_clip_region(moved_clip_region);
|
||||
let mut d = Document::new(1000.0, 1000.0);
|
||||
let l = d.layers[0].id;
|
||||
for i in 0..(2 * CLIPS_KEPT) {
|
||||
let x = 20.0 * i as f64;
|
||||
let mut mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0)), Appearance::default());
|
||||
mask.appearance.effects.push(crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true });
|
||||
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, 0.0, x + 20.0, 10.0)), Appearance::default_art());
|
||||
let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(art)]);
|
||||
clip.set_clips(true);
|
||||
d.insert(Some(l), 0, clip).unwrap();
|
||||
}
|
||||
let evaluated = || CLIPS_EVALUATED.with(std::cell::Cell::get);
|
||||
let empty = Point::new(500.0, 500.0);
|
||||
assert!(hit_test(&d, empty, HitOptions::default()).is_none());
|
||||
let first = evaluated();
|
||||
for _ in 0..3 {
|
||||
assert!(hit_test(&d, empty, HitOptions::default()).is_none());
|
||||
}
|
||||
assert_eq!(evaluated(), first);
|
||||
}
|
||||
|
||||
/// With more clip groups with live effects than the boxes kept, a new box replaces only as many
|
||||
/// others as it needs room for: the next hover finds most of the boxes and evaluates few regions.
|
||||
#[test]
|
||||
fn hovers_past_more_clip_groups_than_the_boxes_kept_evaluate_few_again() {
|
||||
set_clip_region(moved_clip_region);
|
||||
let mut d = Document::new(1000.0, 1000.0);
|
||||
let l = d.layers[0].id;
|
||||
let groups = CLIP_BOXES_KEPT + 64;
|
||||
let mut members = Vec::with_capacity(groups);
|
||||
for i in 0..groups {
|
||||
let x = (i % 100) as f64 * 5.0;
|
||||
let y = (i / 100) as f64 * 5.0;
|
||||
let mut mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 2.0, y + 2.0)), Appearance::default());
|
||||
mask.appearance.effects.push(test_move());
|
||||
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 4.0, y + 2.0)), Appearance::default_art());
|
||||
let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(art)]);
|
||||
clip.set_clips(true);
|
||||
members.push(Arc::new(clip));
|
||||
}
|
||||
if let Some(children) = d.node_mut(l).and_then(|n| n.children_mut()) {
|
||||
*children = members;
|
||||
}
|
||||
let evaluated = || CLIPS_EVALUATED.with(std::cell::Cell::get);
|
||||
let empty = Point::new(900.0, 900.0);
|
||||
assert!(hit_test(&d, empty, HitOptions::default()).is_none());
|
||||
let first = evaluated();
|
||||
assert!(hit_test(&d, empty, HitOptions::default()).is_none());
|
||||
let again = evaluated() - first;
|
||||
assert!(again < groups / 8, "{again} of {groups} regions evaluated again");
|
||||
}
|
||||
|
||||
/// Every test of a clip group by its clipping path follows the region a live effect moved it to:
|
||||
/// the selected art hidden by the mask, a click into a group holding the clip group, the locked
|
||||
/// objects under the pointer, and, below a clipping layer whose Preview is on, art on a sublayer
|
||||
/// whose Preview is off, which is clicked in outline while the layer above clips by its region.
|
||||
#[test]
|
||||
fn every_clip_test_follows_the_moved_region() {
|
||||
set_clip_region(moved_clip_region);
|
||||
let (moved, own) = (Point::new(150.0, 50.0), Point::new(50.0, 50.0));
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (mut mask, art) = half_clipped(&mut d);
|
||||
mask.appearance.effects.push(test_move());
|
||||
let (g, art_id) = (d.alloc_id(), art.id);
|
||||
let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]);
|
||||
clip.set_clips(true);
|
||||
let outer = Node::group(d.alloc_id(), vec![Arc::new(clip)]);
|
||||
d.insert(Some(l), 0, outer.clone()).unwrap();
|
||||
let opt = HitOptions::default();
|
||||
assert_eq!(selected_hidden_at(&d, own, opt, &[art_id]), Some(art_id), "hidden at the clipping path's own place");
|
||||
assert_eq!(selected_hidden_at(&d, moved, opt, &[art_id]), None, "shown in the moved region");
|
||||
let symbols = d.symbol_boxes();
|
||||
assert_eq!(hit_any(&outer, moved, opt, &symbols), Some(HitKind::Fill));
|
||||
assert_eq!(hit_any(&outer, own, opt, &symbols), None);
|
||||
d.node_mut(art_id).unwrap().locked = true;
|
||||
assert_eq!(locked_objects_at(&d, moved, opt), [art_id]);
|
||||
assert!(locked_objects_at(&d, own, opt).is_empty());
|
||||
|
||||
// A clipping layer holding the mask and a sublayer whose Preview is off, with the art.
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let top = d.layers[0].id;
|
||||
let (mut mask, art) = half_clipped(&mut d);
|
||||
mask.appearance.effects.push(test_move());
|
||||
let art_id = art.id;
|
||||
let mut sublayer = (*d.layers[0]).clone();
|
||||
sublayer.id = d.alloc_id();
|
||||
if let NodeKind::Layer { children, preview, .. } = &mut sublayer.kind {
|
||||
(*children, *preview) = (vec![Arc::new(art)], false);
|
||||
}
|
||||
d.insert(Some(top), 0, sublayer).unwrap();
|
||||
d.insert(Some(top), 0, mask).unwrap();
|
||||
d.node_mut(top).unwrap().set_clips(true);
|
||||
// The art's top edge, at the clipping path's own place and in the moved region.
|
||||
let (own, moved) = (Point::new(50.0, 0.5), Point::new(150.0, 0.5));
|
||||
assert!(hit_test(&d, own, opt).is_none());
|
||||
assert_eq!(hit_test(&d, moved, opt).map(|h| h.leaf), Some(art_id));
|
||||
assert_eq!(selected_hidden_at(&d, own, opt, &[art_id]), Some(art_id));
|
||||
assert_eq!(selected_hidden_at(&d, moved, opt, &[art_id]), None);
|
||||
}
|
||||
|
||||
/// The art a mask hides counts only for a selected object: there a click hits nothing, and the
|
||||
/// selection tools grab the selection by that art. Not where the art shows (the click hits it),
|
||||
/// beyond the art, for the clip group selected as a whole, nor for art a click can't hit (locked,
|
||||
@@ -1549,6 +1795,63 @@ fn an_object_a_clipping_layer_in_symbol_art_hides_is_not_picked_there() {
|
||||
assert!((b.x1 - 100.0).abs() < 1e-6, "the layer's outline is cut to the mask: {b:?}");
|
||||
}
|
||||
|
||||
/// In a dynamic symbol's art, an object in a clipping layer whose clipping path has a live effect
|
||||
/// is picked and outlined in the region the effect gives the clipping path. In Outline view, and
|
||||
/// when Preview is off for the layer in the art or for the layer the instance is on, the plain
|
||||
/// clipping path counts, as the canvas draws it. An effect that leaves no region leaves no outline.
|
||||
#[test]
|
||||
fn a_symbol_part_follows_the_region_its_clipping_layers_effects_give_it() {
|
||||
set_clip_region(moved_clip_region);
|
||||
// The instance of a symbol whose art is a clipping layer; `preview` is the Preview of that
|
||||
// layer and of the document layer the instance is on.
|
||||
let instance = |effect: &str, preview: [bool; 2]| {
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
if let NodeKind::Layer { preview: p, .. } = &mut Arc::make_mut(&mut d.layers[0]).kind {
|
||||
*p = preview[1];
|
||||
}
|
||||
let l = d.layers[0].id;
|
||||
let (mut mask, art) = half_clipped(&mut d);
|
||||
mask.appearance.effects.push(crate::Effect { id: effect.into(), ..test_move() });
|
||||
let mut layer = Node::layer(d.alloc_id(), "Masked", crate::LayerColor::Preset(2));
|
||||
if let NodeKind::Layer { children, preview: p, .. } = &mut layer.kind {
|
||||
(*children, *p) = (vec![Arc::new(mask), Arc::new(art)], preview[0]);
|
||||
}
|
||||
layer.set_clips(true);
|
||||
let root = Node::group(d.alloc_id(), vec![Arc::new(layer)]);
|
||||
d.symbols.push(crate::Symbol { dynamic: true, name: "Clipped".into(), art: Arc::new(root) });
|
||||
let inst = d.alloc_id();
|
||||
d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Clipped".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap();
|
||||
(d, inst)
|
||||
};
|
||||
let outline_box = |d: &Document, inst: NodeId, opt: HitOptions| {
|
||||
let o = symbol_part_outline_in_view(d, d.node(inst).unwrap(), &[0, 1], opt).unwrap();
|
||||
vectorcraft_geom::kurbo::Shape::bounding_box(&o)
|
||||
};
|
||||
let opt = HitOptions::default();
|
||||
let (d, inst) = instance("test.move", [true, true]);
|
||||
let n = d.node(inst).unwrap();
|
||||
assert_eq!(symbol_part_at(&d, n, Point::new(150.0, 50.0), opt), Some(vec![0, 1]), "in the moved region");
|
||||
assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 50.0), opt), None, "where the clipping path was");
|
||||
let b = outline_box(&d, inst, opt);
|
||||
assert!((b.x0 - 100.0).abs() < 1e-6 && (b.x1 - 200.0).abs() < 1e-6, "the outline is cut to the moved region: {b:?}");
|
||||
let b = outline_box(&d, inst, HitOptions { outline: true, ..opt });
|
||||
assert!(b.x0.abs() < 1e-6 && (b.x1 - 100.0).abs() < 1e-6, "in Outline view, to the plain clipping path: {b:?}");
|
||||
// With Preview off, the art's top edge counts within the plain clipping path.
|
||||
for (preview, what) in [([false, true], "the layer in the art"), ([true, false], "the layer the instance is on")] {
|
||||
let (d, inst) = instance("test.move", preview);
|
||||
let n = d.node(inst).unwrap();
|
||||
assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 0.5), opt), Some(vec![0, 1]), "on the edge the canvas draws, Preview off for {what}");
|
||||
assert_eq!(symbol_part_at(&d, n, Point::new(150.0, 0.5), opt), None, "past the plain clipping path, Preview off for {what}");
|
||||
let b = outline_box(&d, inst, opt);
|
||||
assert!(b.x0.abs() < 1e-6 && (b.x1 - 100.0).abs() < 1e-6, "Preview off for {what}: the plain clipping path: {b:?}");
|
||||
}
|
||||
// An effect that leaves the clipping path no region hides the art: no pick and no outline.
|
||||
let (d, inst) = instance("test.empty", [true, true]);
|
||||
let n = d.node(inst).unwrap();
|
||||
assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 50.0), opt), None);
|
||||
assert!(symbol_part_outline(&d, n, &[0, 1]).unwrap().elements().is_empty(), "nothing is drawn, so nothing is outlined");
|
||||
}
|
||||
|
||||
/// In a dynamic symbol's art that placing through its 9-slice guides could make more than
|
||||
/// [`crate::MAX_SYMBOL_NODES`] objects of, Direct Selection picks and outlines nothing, as the
|
||||
/// canvas draws nothing of it. At the art's natural size the same art is picked.
|
||||
|
||||
@@ -119,6 +119,7 @@ pub use slices::{CellAlign, CellVAlign, Slice, SliceArea, SliceKind, SliceOption
|
||||
pub use style_libs::StyleLibrary;
|
||||
pub use text::FontHeightReference;
|
||||
pub use text::GlyphChoice;
|
||||
pub use text::GlyphForm;
|
||||
pub use text::WarichuAlign;
|
||||
pub use text::{
|
||||
AreaFit, AreaOptions, Burasagari, CharAlign, CharPosition, CharStyle, Composer, Digits, FirstBaseline, HyphenationOptions, InlineArt,
|
||||
|
||||
@@ -211,7 +211,9 @@ impl Node {
|
||||
|
||||
/// A quick box round everything the object can paint, for culling clicks: paths and compound
|
||||
/// paths grow their geometric bounds by the farthest their strokes can reach from any path
|
||||
/// ([`Appearance::outset`]) instead of measuring along their shape. An image's box takes in
|
||||
/// ([`Appearance::outset`]) instead of measuring along their shape. A clip group's or a
|
||||
/// clipping layer's box takes in the region that the live geometry effects of its clipping
|
||||
/// path give it ([`crate::hit::set_clip_region`]). An image's box takes in
|
||||
/// the shapes its own fills and strokes paint ([`crate::hit::set_image_paint`]). Groups, layers
|
||||
/// without a clipping mask and Intertwine groups take in their members' boxes, grown by their
|
||||
/// own strokes. Symbol instances are measured as in [`Node::visual_bounds`]. A blend's box
|
||||
@@ -261,6 +263,11 @@ impl Node {
|
||||
NodeKind::Blend { children, spec } => {
|
||||
vectorcraft_geom::union_opt(self.visual(symbols), crate::blend::rail_reach(children, spec, symbols))
|
||||
}
|
||||
// The live geometry effects of a clipping path can move or grow the region it clips to
|
||||
// past its plain shape ([`crate::hit::set_clip_region`]).
|
||||
NodeKind::Layer { children, clip: true, .. } | NodeKind::Group { children, clip: true } => {
|
||||
vectorcraft_geom::union_opt(self.visual(symbols), children.first().and_then(|c| crate::hit::reshaped_clip_box(c)))
|
||||
}
|
||||
_ => self.visual(symbols),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,6 +79,21 @@ fn odd_text_reads_as_nothing_without_panicking() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Text from a command or a file can be any length: a sum of thousands of terms reads as nothing
|
||||
/// instead of exhausting the stack. Up to 128 `+ - * /` signs read; 129 read as nothing.
|
||||
#[test]
|
||||
fn a_very_long_expression_reads_as_nothing() {
|
||||
let sum = |terms: usize| format!("1{}", "+1".repeat(terms - 1));
|
||||
assert_eq!(Unit::Points.parse(&sum(129)), Some(129.0));
|
||||
assert_eq!(Unit::Points.parse(&format!("10{} mm", "*1".repeat(128))), Some(Unit::Millimeters.to_pt(10.0)));
|
||||
// Long text with no signs still reads.
|
||||
assert_eq!(Unit::Points.parse(&format!("{}5", " ".repeat(2_000))), Some(5.0));
|
||||
for text in [sum(200_000), format!("1{}", "*1".repeat(200_000)), sum(130), format!("10{} mm", "*1".repeat(129))] {
|
||||
assert_eq!(Unit::Points.parse(&text), None, "{} bytes", text.len());
|
||||
assert_eq!(crate::parse_number(&text), None, "{} bytes", text.len());
|
||||
}
|
||||
}
|
||||
|
||||
proptest! {
|
||||
/// Field text made of digits, operators, `%`, spaces and unit letters reads as a finite value
|
||||
/// or as nothing and does not panic.
|
||||
|
||||
@@ -18,8 +18,8 @@ mod wrap;
|
||||
pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextFlow, TextWrap, VerticalAlign, WrapShape};
|
||||
use char_style::yes;
|
||||
pub use char_style::{
|
||||
CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, MAX_AKI, MAX_TSUME, MAX_WARICHU_GAP, ScriptMetrics, WARICHU_LINES,
|
||||
WARICHU_SCALE, WarichuAlign,
|
||||
CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, GlyphForm, MAX_AKI, MAX_TSUME, MAX_WARICHU_GAP, ScriptMetrics,
|
||||
WARICHU_LINES, WARICHU_SCALE, WarichuAlign,
|
||||
};
|
||||
pub use composite::{
|
||||
COMPOSITE_BASELINE, COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, COMPOSITE_SCALE, COMPOSITE_SIZE, CharClass, CompositeFont, CompositePart,
|
||||
|
||||
@@ -205,6 +205,99 @@ pub struct CharStyle {
|
||||
/// default glyph otherwise. Saved only when set.
|
||||
#[serde(default, rename = "glyphAlternate", skip_serializing_if = "Option::is_none")]
|
||||
pub glyph_alternate: Option<GlyphChoice>,
|
||||
/// The East Asian glyph form these characters are drawn in (Glyphs panel menu, with Show East
|
||||
/// Asian Options): one OpenType feature of the font, such as JIS 78 forms (`jp78`), or the
|
||||
/// font's default glyphs. The text keeps its characters. Saved only when set.
|
||||
/// <https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html>
|
||||
#[serde(default, rename = "glyphForm", skip_serializing_if = "crate::skip::is_default")]
|
||||
pub glyph_form: GlyphForm,
|
||||
}
|
||||
|
||||
/// The East Asian glyph form characters are drawn in ([`CharStyle::glyph_form`]): the font's
|
||||
/// default glyphs, or the glyphs one OpenType feature substitutes. One form at a time.
|
||||
/// <https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist>
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum GlyphForm {
|
||||
/// The font's default glyphs.
|
||||
#[default]
|
||||
Default,
|
||||
/// Traditional forms (`trad`).
|
||||
Traditional,
|
||||
/// Expert forms (`expt`).
|
||||
Expert,
|
||||
/// JIS 2004 forms (`jp04`).
|
||||
Jis04,
|
||||
/// JIS 90 forms (`jp90`).
|
||||
Jis90,
|
||||
/// JIS 78 forms (`jp78`).
|
||||
Jis78,
|
||||
/// JIS 83 forms (`jp83`).
|
||||
Jis83,
|
||||
/// Monospaced full-width forms (`fwid`).
|
||||
FullWidth,
|
||||
/// Monospaced half-width forms (`hwid`).
|
||||
HalfWidth,
|
||||
/// Monospaced third-width forms (`twid`).
|
||||
ThirdWidth,
|
||||
/// Monospaced quarter-width forms (`qwid`).
|
||||
QuarterWidth,
|
||||
}
|
||||
|
||||
impl GlyphForm {
|
||||
/// Every form, in menu order, the default last.
|
||||
pub const ALL: [GlyphForm; 11] = [
|
||||
GlyphForm::Traditional,
|
||||
GlyphForm::Expert,
|
||||
GlyphForm::Jis04,
|
||||
GlyphForm::Jis90,
|
||||
GlyphForm::Jis78,
|
||||
GlyphForm::Jis83,
|
||||
GlyphForm::FullWidth,
|
||||
GlyphForm::HalfWidth,
|
||||
GlyphForm::ThirdWidth,
|
||||
GlyphForm::QuarterWidth,
|
||||
GlyphForm::Default,
|
||||
];
|
||||
|
||||
/// The name files and commands give this form (as it is saved).
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
GlyphForm::Default => "default",
|
||||
GlyphForm::Traditional => "traditional",
|
||||
GlyphForm::Expert => "expert",
|
||||
GlyphForm::Jis04 => "jis04",
|
||||
GlyphForm::Jis90 => "jis90",
|
||||
GlyphForm::Jis78 => "jis78",
|
||||
GlyphForm::Jis83 => "jis83",
|
||||
GlyphForm::FullWidth => "fullWidth",
|
||||
GlyphForm::HalfWidth => "halfWidth",
|
||||
GlyphForm::ThirdWidth => "thirdWidth",
|
||||
GlyphForm::QuarterWidth => "quarterWidth",
|
||||
}
|
||||
}
|
||||
|
||||
/// The form [`GlyphForm::id`] names; `None` for any other name.
|
||||
pub fn from_id(id: &str) -> Option<GlyphForm> {
|
||||
GlyphForm::ALL.into_iter().find(|f| f.id() == id)
|
||||
}
|
||||
|
||||
/// The OpenType feature that draws this form; `None` for the default glyphs.
|
||||
pub fn feature(self) -> Option<&'static [u8; 4]> {
|
||||
Some(match self {
|
||||
GlyphForm::Default => return None,
|
||||
GlyphForm::Traditional => b"trad",
|
||||
GlyphForm::Expert => b"expt",
|
||||
GlyphForm::Jis04 => b"jp04",
|
||||
GlyphForm::Jis90 => b"jp90",
|
||||
GlyphForm::Jis78 => b"jp78",
|
||||
GlyphForm::Jis83 => b"jp83",
|
||||
GlyphForm::FullWidth => b"fwid",
|
||||
GlyphForm::HalfWidth => b"hwid",
|
||||
GlyphForm::ThirdWidth => b"twid",
|
||||
GlyphForm::QuarterWidth => b"qwid",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A glyph chosen for one character ([`CharStyle::glyph_alternate`]): the glyph id and the face it
|
||||
@@ -586,6 +679,7 @@ impl Default for CharStyle {
|
||||
no_break: false,
|
||||
language: None,
|
||||
glyph_alternate: None,
|
||||
glyph_form: GlyphForm::Default,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,7 +156,12 @@ impl Unit {
|
||||
/// before it (`3cm*50%` is 1.5 cm, `3cm/50%` is 6 cm). After `+` or `-`, it adds or takes away
|
||||
/// that share of everything before it (`50pt+25%` is 62.5 pt, `100pt+20pt-50%` is 60 pt). A
|
||||
/// percentage on its own (`50%`) reads as nothing.
|
||||
///
|
||||
/// Text with more than 128 `+ - * /` signs reads as nothing.
|
||||
pub fn parse(self, s: &str) -> Option<f64> {
|
||||
if s.chars().filter(|c| matches!(c, '+' | '-' | '*' | '/')).count() > MAX_MEASURE_OPERATORS {
|
||||
return None;
|
||||
}
|
||||
parse_measure(s, self).filter(|v| v.is_finite())
|
||||
}
|
||||
/// The value naming this unit in the Units preferences (`points`, `millimeters`,
|
||||
@@ -207,6 +212,9 @@ impl Unit {
|
||||
}
|
||||
}
|
||||
|
||||
/// The most `+ - * /` signs [`Unit::parse`] reads in one text.
|
||||
const MAX_MEASURE_OPERATORS: usize = 128;
|
||||
|
||||
fn parse_measure(s: &str, default: Unit) -> Option<f64> {
|
||||
let s = s.trim();
|
||||
// Simple arithmetic on the right (Illustrator fields accept "10+5", "100/2", "3in*2").
|
||||
|
||||
+56
-15
@@ -199,8 +199,19 @@ fn placed_fits(baked: &Node, spent: u64, dropped: u64) -> Option<u64> {
|
||||
}
|
||||
|
||||
/// The names of the symbols of `d` whose art needs baking ([`needs_bake`]), and of those whose art
|
||||
/// holds an instance of one of them at any depth.
|
||||
/// holds an instance of one of them at any depth, in the art of enabled opacity masks too.
|
||||
fn drawn_symbols(d: &Document) -> HashSet<String> {
|
||||
fn used(n: &Node, names: &mut Vec<String>) {
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind {
|
||||
names.push(symbol.clone());
|
||||
}
|
||||
if let Some(m) = n.extras().mask.as_ref().filter(|m| !m.disabled) {
|
||||
used(&m.art, names);
|
||||
}
|
||||
for c in n.children().into_iter().flatten() {
|
||||
used(c, names);
|
||||
}
|
||||
}
|
||||
let mut out: HashSet<String> = d.symbols.iter().filter(|s| needs_bake(&s.art)).map(|s| s.name.clone()).collect();
|
||||
if out.is_empty() {
|
||||
return out;
|
||||
@@ -211,11 +222,7 @@ fn drawn_symbols(d: &Document) -> HashSet<String> {
|
||||
.filter(|s| !out.contains(&s.name))
|
||||
.map(|s| {
|
||||
let mut names = vec![];
|
||||
s.art.walk(&mut |c| {
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &c.kind {
|
||||
names.push(symbol.clone());
|
||||
}
|
||||
});
|
||||
used(&s.art, &mut names);
|
||||
(s.name.as_str(), names)
|
||||
})
|
||||
.collect();
|
||||
@@ -233,14 +240,22 @@ fn drawn_symbols(d: &Document) -> HashSet<String> {
|
||||
}
|
||||
|
||||
/// Does `n`'s subtree hold an instance of a symbol that [`bake_document_placing_symbols`] replaces
|
||||
/// by its placed art? False outside it, and for objects the export does not write ([`unwritten`]).
|
||||
/// by its placed art, in the art of its enabled opacity masks too? False outside it, and for
|
||||
/// objects the export does not write ([`unwritten`]).
|
||||
fn holds_placed_symbol(n: &Node) -> bool {
|
||||
fn walk(n: &Node, symbols: &HashSet<String>) -> bool {
|
||||
placed_symbol_in(n, true)
|
||||
}
|
||||
|
||||
/// [`holds_placed_symbol`], with the art of `n`'s own opacity mask left out unless `own_mask`
|
||||
/// (the art of the masks inside `n` is always looked into).
|
||||
fn placed_symbol_in(n: &Node, own_mask: bool) -> bool {
|
||||
fn walk(n: &Node, symbols: &HashSet<String>, own_mask: bool) -> bool {
|
||||
!unwritten(n)
|
||||
&& (matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if symbols.contains(symbol))
|
||||
|| n.children().is_some_and(|ch| ch.iter().any(|c| walk(c, symbols))))
|
||||
|| (own_mask && !n.is_ruler_guide() && n.extras().mask.as_ref().is_some_and(|m| !m.disabled && walk(&m.art, symbols, true)))
|
||||
|| n.children().is_some_and(|ch| ch.iter().any(|c| walk(c, symbols, true))))
|
||||
}
|
||||
!UNWRITTEN.with(|c| c.get()) && PLACING.with(|p| p.borrow().as_ref().is_some_and(|p| walk(n, &p.symbols)))
|
||||
!UNWRITTEN.with(|c| c.get()) && PLACING.with(|p| p.borrow().as_ref().is_some_and(|p| walk(n, &p.symbols, own_mask)))
|
||||
}
|
||||
|
||||
/// Symbol instance `n`, while [`bake_document_placing_symbols`] bakes and its symbol is one it
|
||||
@@ -278,8 +293,29 @@ fn placed_symbol_art(d: &Document, n: &Node) -> Option<(Node, u64)> {
|
||||
Some((g, most))
|
||||
}
|
||||
|
||||
/// `n` with its geometry effects evaluated (`None` = unchanged).
|
||||
/// `n` with its geometry effects evaluated (`None` = unchanged), and the art of its enabled opacity
|
||||
/// mask baked one level deeper when it holds instances that [`bake_document_placing_symbols`]
|
||||
/// places ([`holds_placed_symbol`]), so the mask masks with the art the instances draw. The art is
|
||||
/// baked only while the object baked from `n` still carries `n`'s mask art; art already baked
|
||||
/// with `n`'s recolored or placed form is not baked again. A ruler guide's mask stays as it is.
|
||||
fn bake_node(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
let out = bake_object(d, n);
|
||||
let Some(mask) = n.extras().mask.as_ref().filter(|m| !m.disabled && !n.is_ruler_guide() && !unwritten(n) && holds_placed_symbol(&m.art)) else {
|
||||
return out;
|
||||
};
|
||||
let changed = out.is_some();
|
||||
let mut out = out.unwrap_or_else(|| n.clone());
|
||||
let Some(slot) = out.extras_if_any().and_then(|e| e.mask.as_mut()).filter(|s| Arc::ptr_eq(&s.art, &mask.art)) else {
|
||||
return changed.then_some(out);
|
||||
};
|
||||
let Some(art) = one_deeper(|| bake_node(d, &mask.art)) else { return changed.then_some(out) };
|
||||
slot.art = Arc::new(art);
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// `n` with its geometry effects evaluated (`None` = unchanged); its opacity mask is left to
|
||||
/// [`bake_node`].
|
||||
fn bake_object(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
// Inside an object the export leaves out, effects are baked but no instance is placed.
|
||||
if !UNWRITTEN.with(|c| c.get()) && unwritten(n) {
|
||||
UNWRITTEN.with(|c| c.set(true));
|
||||
@@ -289,7 +325,8 @@ fn bake_node(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
}
|
||||
// A cancelled export leaves the rest of the document as it is: the caller drops the result.
|
||||
// A ruler guide draws nothing and stays as it is, last in its layer.
|
||||
if n.is_ruler_guide() || !(needs_bake(n) || holds_placed_symbol(n)) || vectorcraft_doc::cancel::is_cancelled() {
|
||||
// An object whose own mask's art alone holds placed instances stays as it is here.
|
||||
if n.is_ruler_guide() || !(needs_bake(n) || placed_symbol_in(n, false)) || vectorcraft_doc::cancel::is_cancelled() {
|
||||
return None;
|
||||
}
|
||||
// Colour adjustments: the object recoloured (inside it too), then baked as it is.
|
||||
@@ -476,14 +513,18 @@ fn clip_group_with_type_clip(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
|
||||
/// `m`, art evaluated from an object, with its children baked and then given ids of their own (the
|
||||
/// pieces copied from the source keep the source's ids until then). The pieces are baked with the
|
||||
/// ids the renderer draws them with: Random in a Transform effect takes its seed from the id.
|
||||
/// ids the renderer draws them with: Random in a Transform effect takes its seed from the id. When
|
||||
/// `m` clips, its clipping path, unless it is type, first takes the geometry effects in it as the
|
||||
/// canvas clips by it ([`crate::clip::with_clip_effects_applied`]).
|
||||
fn bake_pieces(d: &mut Document, mut m: Node) -> Node {
|
||||
let mut seen = std::collections::HashSet::from([m.id]);
|
||||
let clip = usize::from(m.clips() && !m.children().and_then(|ch| ch.first()).is_some_and(|c| matches!(c.kind, NodeKind::Text(_))));
|
||||
let children = m.children().cloned().unwrap_or_default();
|
||||
let children = children
|
||||
.into_iter()
|
||||
.map(|c| {
|
||||
let c = Arc::unwrap_or_clone(c);
|
||||
.enumerate()
|
||||
.map(|(i, c)| {
|
||||
let c = (i < clip).then(|| crate::clip::with_clip_effects_applied(&c)).flatten().unwrap_or_else(|| Arc::unwrap_or_clone(c));
|
||||
let mut c = one_deeper(|| bake_node(d, &c)).unwrap_or(c);
|
||||
fresh_ids(d, &mut c, &mut seen);
|
||||
Arc::new(c)
|
||||
|
||||
@@ -1169,6 +1169,74 @@ fn placing_symbols_reaches_the_art_of_nested_instances() {
|
||||
assert!(near_rect(bounds(&out, 900), Rect::new(110.0, 140.0, 120.0, 150.0)), "{:?}", bounds(&out, 900));
|
||||
}
|
||||
|
||||
/// A 10 pt square with id `id`, masked by `art` (the mask enabled unless `disabled`).
|
||||
fn masked_square(id: u64, art: Node, disabled: bool) -> Node {
|
||||
let mut n = Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art());
|
||||
let mut mask = vectorcraft_doc::OpacityMask::new(art, false);
|
||||
mask.disabled = disabled;
|
||||
n.extras_mut().mask = Some(Box::new(mask));
|
||||
n
|
||||
}
|
||||
|
||||
/// Whether the art of `n`'s opacity mask is still a symbol instance, and its bounds when it is not.
|
||||
fn mask_art(n: &Node) -> (bool, Option<Rect>) {
|
||||
let art = &n.extras().mask.as_ref().unwrap_or_else(|| panic!("node {:?} has a mask", n.id)).art;
|
||||
(matches!(art.kind, NodeKind::SymbolInstance { .. }), art.geometric_bounds())
|
||||
}
|
||||
|
||||
/// An instance in the art of an enabled opacity mask is placed and baked like any other, so the
|
||||
/// mask masks with the art the instance draws, and the masked object stays as it is (a clipping
|
||||
/// path stays one); one in a disabled mask, in the mask of an object the export leaves out, or in
|
||||
/// a ruler guide's mask, stays as it is.
|
||||
#[test]
|
||||
fn placing_symbols_reaches_instances_in_opacity_masks() {
|
||||
use vectorcraft_geom::Affine;
|
||||
let mut d = doc_with(masked_square(700, instance(900, "S", Affine::IDENTITY), false));
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 1, masked_square(701, instance(901, "S", Affine::IDENTITY), true)).unwrap();
|
||||
let mut hidden = masked_square(702, instance(902, "S", Affine::IDENTITY), false);
|
||||
hidden.visible = false;
|
||||
d.insert(Some(layer), 2, hidden).unwrap();
|
||||
let mut clipping = masked_square(703, instance(903, "S", Affine::IDENTITY), false);
|
||||
if let NodeKind::Path { clipping: c, .. } = &mut clipping.kind {
|
||||
*c = true;
|
||||
}
|
||||
d.insert(Some(layer), 3, Node::group(NodeId(704), vec![Arc::new(clipping)])).unwrap();
|
||||
let mut guide = Node::new(NodeId(705), NodeKind::RulerGuide { vertical: false, pos: 5.0, artboard: None });
|
||||
guide.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(instance(905, "S", Affine::IDENTITY), false)));
|
||||
d.insert(Some(layer), 4, guide).unwrap();
|
||||
add_symbol(&mut d, "S", moved_square(800));
|
||||
let out = bake_document_placing_symbols(&d, true, ALL).unwrap();
|
||||
for id in [700, 703] {
|
||||
let (still, b) = mask_art(out.node(NodeId(id)).unwrap());
|
||||
assert!(!still && b.is_some_and(|b| near_rect(b, Rect::new(110.0, 40.0, 120.0, 50.0))), "{id}: {b:?}");
|
||||
}
|
||||
assert!(matches!(out.node(NodeId(703)).unwrap().kind, NodeKind::Path { clipping: true, .. }), "the clipping path stays one");
|
||||
assert!(mask_art(out.node(NodeId(701)).unwrap()).0, "a disabled mask's instance stays");
|
||||
assert!(mask_art(out.node(NodeId(702)).unwrap()).0, "a hidden object's mask's instance stays");
|
||||
assert!(mask_art(out.node(NodeId(705)).unwrap()).0, "a ruler guide's mask's instance stays");
|
||||
}
|
||||
|
||||
/// A symbol whose art holds an instance only in an opacity mask's art is placed too, and the
|
||||
/// instance in its mask is placed with it.
|
||||
#[test]
|
||||
fn placing_symbols_reaches_instances_in_the_masks_of_symbol_art() {
|
||||
use vectorcraft_geom::Affine;
|
||||
let mut d = doc_with(instance(900, "Outer", Affine::IDENTITY));
|
||||
add_symbol(&mut d, "Inner", moved_square(800));
|
||||
add_symbol(&mut d, "Outer", masked_square(803, instance(802, "Inner", Affine::IDENTITY), false));
|
||||
let out = bake_document_placing_symbols(&d, true, ALL).unwrap();
|
||||
assert!(!is_instance(&out, 900), "the outer instance is placed");
|
||||
let mut found = None;
|
||||
out.node(NodeId(900)).unwrap().walk(&mut |n| {
|
||||
if n.id == NodeId(803) {
|
||||
found = Some(mask_art(n));
|
||||
}
|
||||
});
|
||||
let (still, b) = found.unwrap_or_else(|| panic!("the masked square is in the placed art"));
|
||||
assert!(!still && b.is_some_and(|b| near_rect(b, Rect::new(110.0, 40.0, 120.0, 50.0))), "{b:?}");
|
||||
}
|
||||
|
||||
/// A symbol whose art holds an instance of itself is placed until the depth limit, and the export
|
||||
/// ends.
|
||||
#[test]
|
||||
|
||||
@@ -417,7 +417,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
"artistic.roughPastels",
|
||||
"Rough Pastels…",
|
||||
ARTISTIC,
|
||||
"{strokeLength: 0..40 (6; longer pastel strokes), strokeDetail: 1..20 (10; bristle texture along the strokes), texture: \"brick\"|\"burlap\"|\"canvas\"|\"sandstone\" (\"canvas\"), scaling: % 50..200 (100), relief: 0..50 (4), lightDirection: \"bottom\"|\"bottomLeft\"|\"left\"|\"topLeft\"|\"top\"|\"topRight\"|\"right\"|\"bottomRight\" (\"top\"), invert: bool (false)} repaints the object in soft diagonal pastel strokes over a textured surface, keeping its coverage. Slider ranges follow the documented controls; numeric defaults are chosen for VectorCraft and are not verified against proprietary defaults.",
|
||||
"{strokeLength: 0..40 (6; longer pastel strokes), strokeDetail: 1..20 (10; bristle texture along the strokes), texture: \"brick\"|\"burlap\"|\"canvas\"|\"sandstone\"|\"loaded\" (\"canvas\"; \"loaded\" draws the image in textureImage and draws Canvas when there is none; the others are surfaces made in code), textureImage?: {path} | {name?, dataBase64} | string (Load Texture…: an image file that File › Place reads, within the renderer's pixel allowance, stored as its gray levels in a grayscale PNG in base64; a file sets texture to \"loaded\" unless texture is given, and the stored string, as effect.list gives it, is kept as it is), scaling: % 50..200 (100), relief: 0..50 (4), lightDirection: \"bottom\"|\"bottomLeft\"|\"left\"|\"topLeft\"|\"top\"|\"topRight\"|\"right\"|\"bottomRight\" (\"top\"), invert: bool (false)} repaints the object in soft diagonal pastel strokes over a textured surface, keeping its coverage. A loaded texture lies one image pixel per point at 100 %, centered on the object's center and repeated; each pixel's luma is the surface's height, from 0 for black to 1 pt for white, and a transparent pixel counts as middle gray. Slider ranges follow the documented controls; numeric defaults are chosen for VectorCraft and are not verified against proprietary defaults.",
|
||||
json!({
|
||||
"strokeLength": 6.0,
|
||||
"strokeDetail": 10.0,
|
||||
@@ -468,8 +468,8 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
"blur.radial",
|
||||
"Radial Blur…",
|
||||
BLUR,
|
||||
"{amount: 1..100 (10; spin: an arc of `amount`°, zoom: the content scaled by up to about ±amount/2 %), method: \"spin\"|\"zoom\" (\"spin\"), quality: \"draft\"|\"good\"|\"best\" (\"good\"; 16, 64 or 256 samples)} blurs around the object's centre",
|
||||
json!({"amount": 10.0, "method": "spin", "quality": "good"}),
|
||||
"{amount: 1..100 (10; spin: an arc of `amount`°, zoom: the content scaled by up to about ±amount/2 %), method: \"spin\"|\"zoom\" (\"spin\"), quality: \"draft\"|\"good\"|\"best\" (\"good\"; 16, 64 or 256 samples), centerX: 0..1 (0.5; the Blur Center across the object's bounds, 0 their left edge), centerY: 0..1 (0.5; the Blur Center down the object's bounds, 0 their top edge)} blurs around the Blur Center, which moves and scales with the object. A centerX or centerY outside 0..1 is refused",
|
||||
json!({"amount": 10.0, "method": "spin", "quality": "good", "centerX": 0.5, "centerY": 0.5}),
|
||||
),
|
||||
r(
|
||||
"blur.smart",
|
||||
|
||||
@@ -12,10 +12,14 @@ use vectorcraft_geom::{BezPath, FillRule, PathData};
|
||||
/// fills and strokes: the region is then the union of the paths they give, as an export bakes them.
|
||||
/// `None` when there is nothing to clip by (the clipped art is then hidden).
|
||||
pub fn clip_outline(clip: &Node) -> Option<(BezPath, FillRule)> {
|
||||
match clip_effects_applied(clip, true, || true) {
|
||||
Some(m) => m.clip_outline(Some(&outline_text), &unite),
|
||||
None => clip.clip_outline(Some(&outline_text), &unite),
|
||||
}
|
||||
reshaped_clip_outline(clip).unwrap_or_else(|| clip.clip_outline(Some(&outline_text), &unite))
|
||||
}
|
||||
|
||||
/// [`clip_outline`] of a clipping path that a live geometry effect reshapes; `None` when nothing
|
||||
/// `clip` clips by has a geometry effect of its own or on a fill or stroke. A hidden member of a
|
||||
/// group or layer does not clip, so its effects are not counted.
|
||||
pub fn reshaped_clip_outline(clip: &Node) -> Option<Option<(BezPath, FillRule)>> {
|
||||
clip_effects_applied(clip, true, || true).map(|m| m.clip_outline(Some(&outline_text), &unite))
|
||||
}
|
||||
|
||||
/// `n`, the clipping path of a clip group, with the live geometry effects of everything it clips by
|
||||
|
||||
@@ -72,7 +72,7 @@ pub use bake::{
|
||||
StrokeArt, WrittenLayers, bake_appearance, bake_document, bake_document_placing_symbols, bake_type_appearance, expand_art, expand_leaf,
|
||||
fresh_ids, needs_bake,
|
||||
};
|
||||
pub use clip::{WarpSeams, clip_outline, knockout_silhouette, warp_pieces_translucent};
|
||||
pub use clip::{WarpSeams, clip_outline, knockout_silhouette, reshaped_clip_outline, warp_pieces_translucent};
|
||||
pub use group::{
|
||||
OutlineHook, PATHFINDER_EFFECTS, compound_shape_area, compound_shape_art, evaluate_container, has_container_appearance, has_pathfinder,
|
||||
is_pathfinder, member_leaves, member_shapes, paints, pathfinder_children, shape_art,
|
||||
|
||||
+22
-16
@@ -30,7 +30,7 @@ mod texture;
|
||||
mod video;
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_geom::{Affine, Point, Rect};
|
||||
use vectorcraft_geom::{Affine, Point, Rect, Vec2};
|
||||
|
||||
use crate::util::{flag, num, text};
|
||||
|
||||
@@ -155,12 +155,14 @@ pub enum PixelFx {
|
||||
/// `texture_coverage` (0..40) says.
|
||||
Underpainting { brush_size: f64, texture_coverage: f64, texture: Texture, scaling: f64, relief: f64, light: Light, invert: bool },
|
||||
/// Artistic › Rough Pastels: diagonal pastel strokes `length` (0..40) long, bristle detail
|
||||
/// (1..20), then a [`Texture`] surface scaled by `scaling` (0.5..2), in relief as strong as
|
||||
/// `relief` (0..50) and lit from `light`; `invert` turns the surface's heights over.
|
||||
/// (1..20), then a [`Texture`] surface (a loaded one included) scaled by `scaling` (0.5..2), in
|
||||
/// relief as strong as `relief` (0..50) and lit from `light`; `invert` turns the surface's
|
||||
/// heights over.
|
||||
RoughPastels { length: f64, detail: f64, texture: Texture, scaling: f64, relief: f64, light: Light, invert: bool },
|
||||
/// Blur › Radial Blur around the object's centre: along arcs (spin, an arc of `amount`°) or
|
||||
/// along rays (zoom, the content scaled by up to about ±`amount`/2 %), averaging 2^`passes` samples.
|
||||
RadialBlur { amount: f64, zoom: bool, passes: u32 },
|
||||
/// Blur › Radial Blur around its Blur Center, `center` (0..1 across and down the object's
|
||||
/// bounds; (0.5, 0.5) the object's centre): along arcs (spin, an arc of `amount`°) or along
|
||||
/// rays (zoom, the content scaled by up to about ±`amount`/2 %), averaging 2^`passes` samples.
|
||||
RadialBlur { amount: f64, zoom: bool, passes: u32, center: [f64; 2] },
|
||||
/// Blur › Smart Blur (Normal mode): each pixel averaged with the neighbours within `radius`
|
||||
/// whose colour differs from its own by no more than `threshold` levels, over a grid of
|
||||
/// `samples` × `samples` neighbours at most.
|
||||
@@ -314,9 +316,12 @@ pub struct PixelSpace {
|
||||
pub to_doc: Affine,
|
||||
/// The size of a pixel in document units.
|
||||
pub px: f64,
|
||||
/// The object's centre (document coordinates): where Radial Blur blurs around, and where the
|
||||
/// Pixelate filters' patterns are anchored (so they move with the object).
|
||||
/// The object's centre (document coordinates): where Radial Blur blurs around by default, and
|
||||
/// where the Pixelate filters' patterns are anchored (so they move with the object).
|
||||
pub center: Point,
|
||||
/// The width and height of the object's bounds (document units), centred on `center`: Radial
|
||||
/// Blur's Blur Center lies at a share of them.
|
||||
pub size: Vec2,
|
||||
/// What the colour channels hold.
|
||||
pub channels: Channels,
|
||||
/// The height of a line of the document's raster grid (document units: 72 / Document Raster
|
||||
@@ -381,7 +386,7 @@ pub(crate) fn parse(id: &str, p: &Value) -> Option<PixelFx> {
|
||||
"artistic.roughPastels" => PixelFx::RoughPastels {
|
||||
length: num(p, "strokeLength", 6.0).clamp(0.0, 40.0),
|
||||
detail: num(p, "strokeDetail", 10.0).clamp(1.0, 20.0),
|
||||
texture: Texture::parse(text(p, "texture", "canvas")),
|
||||
texture: Texture::parse_with(text(p, "texture", "canvas"), p.get(TEXTURE_IMAGE).and_then(Value::as_str)),
|
||||
scaling: num(p, "scaling", 100.0).clamp(50.0, 200.0) / 100.0,
|
||||
relief: num(p, "relief", 4.0).clamp(0.0, 50.0),
|
||||
light: Light::parse(text(p, "lightDirection", "top")),
|
||||
@@ -421,6 +426,7 @@ pub(crate) fn parse(id: &str, p: &Value) -> Option<PixelFx> {
|
||||
amount: num(p, "amount", 10.0).clamp(1.0, 100.0),
|
||||
zoom: text(p, "method", "spin").eq_ignore_ascii_case("zoom"),
|
||||
passes: quality([("draft", 4), ("good", 6), ("best", 8)], 6),
|
||||
center: [num(p, "centerX", 0.5).clamp(0.0, 1.0), num(p, "centerY", 0.5).clamp(0.0, 1.0)],
|
||||
},
|
||||
"blur.smart" => PixelFx::SmartBlur {
|
||||
radius: num(p, "radius", 3.0).clamp(0.1, 100.0),
|
||||
@@ -608,13 +614,13 @@ pub(crate) fn parse(id: &str, p: &Value) -> Option<PixelFx> {
|
||||
impl PixelFx {
|
||||
/// How far beyond `bounds` (the content's, document units) the effect can paint.
|
||||
pub fn outset(&self, bounds: Rect) -> f64 {
|
||||
// From the centre to the farthest corner, and to the nearest side.
|
||||
let far = 0.5 * bounds.width().hypot(bounds.height());
|
||||
let near = 0.5 * bounds.width().min(bounds.height());
|
||||
match *self {
|
||||
// A rotated corner reaches the circle through the corners.
|
||||
PixelFx::RadialBlur { zoom: false, .. } => (far - near).max(0.0),
|
||||
PixelFx::RadialBlur { amount, zoom: true, .. } => far * (blur::zoom_extent(amount).exp() - 1.0),
|
||||
// A rotated corner reaches the circle about the Blur Center through the farthest corner.
|
||||
PixelFx::RadialBlur { zoom: false, center, .. } => {
|
||||
let (far, near) = blur::center_reach(bounds, center);
|
||||
(far - near).max(0.0)
|
||||
}
|
||||
PixelFx::RadialBlur { amount, zoom: true, center, .. } => blur::center_reach(bounds, center).0 * (blur::zoom_extent(amount).exp() - 1.0),
|
||||
PixelFx::SmartBlur { radius, .. } => radius,
|
||||
PixelFx::AccentedEdges { .. } => 0.0,
|
||||
// Strokes reach out of the object as far as they reach into it.
|
||||
@@ -786,7 +792,7 @@ impl PixelFx {
|
||||
PixelFx::RoughPastels { length, detail, ref texture, scaling, relief, light, invert } => {
|
||||
artistic::rough_pastels(px, w, h, space, length, detail, texture, scaling, relief, light, invert)
|
||||
}
|
||||
PixelFx::RadialBlur { amount, zoom, passes } => blur::radial(px, w, h, space, amount, zoom, passes),
|
||||
PixelFx::RadialBlur { amount, zoom, passes, center } => blur::radial(px, w, h, space, amount, zoom, passes, center),
|
||||
PixelFx::SmartBlur { radius, threshold, samples, mode: SmartBlurMode::Normal } => {
|
||||
blur::smart(px, w, h, to_px(radius), threshold, samples)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Blur › Radial Blur and Smart Blur (Normal, Edge Only and Overlay Edge).
|
||||
|
||||
use vectorcraft_geom::{Affine, Point, Vec2};
|
||||
use vectorcraft_geom::{Affine, Point, Rect, Vec2};
|
||||
|
||||
use super::{PixelSpace, Px16, box_blur, pick, to8, to16};
|
||||
|
||||
@@ -29,13 +29,31 @@ fn bilinear(buf: &[Px16], w: usize, h: usize, x: f64, y: f64) -> [f32; 4] {
|
||||
std::array::from_fn(|i| a[i] * wa + b[i] * wb + c[i] * wc + d[i] * wd)
|
||||
}
|
||||
|
||||
/// Radial Blur: the average of the content turned (spin) or scaled (zoom) about the centre over
|
||||
/// evenly spaced steps spanning `amount`. Each pass averages the previous result with itself
|
||||
/// turned both ways by half the last step, so `passes` passes average 2^`passes` samples at two
|
||||
/// lookups a pixel each.
|
||||
pub(super) fn radial(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, amount: f64, zoom: bool, passes: u32) {
|
||||
/// How far Radial Blur's Blur Center `center` (0..1 across and down `bounds`) lies from the
|
||||
/// farthest corner of `bounds`, and from its nearest side.
|
||||
pub(super) fn center_reach(bounds: Rect, center: [f64; 2]) -> (f64, f64) {
|
||||
// The share of the width (height) on the far side of the center, doubled: 1 at the middle.
|
||||
let far = |f: f64| 1.0 + (2.0 * f - 1.0).abs();
|
||||
let (w, h) = (bounds.width(), bounds.height());
|
||||
let near = ((2.0 - far(center[0])) * w).min((2.0 - far(center[1])) * h);
|
||||
(0.5 * (far(center[0]) * w).hypot(far(center[1]) * h), 0.5 * near)
|
||||
}
|
||||
|
||||
/// Where Radial Blur's Blur Center `center` (0..1 across and down the object's bounds) lies in the
|
||||
/// document: the object's centre at (0.5, 0.5).
|
||||
pub(super) fn blur_center(space: &PixelSpace, center: [f64; 2]) -> Point {
|
||||
let shift = Vec2::new((center[0] - 0.5) * space.size.x, (center[1] - 0.5) * space.size.y);
|
||||
if shift.x.is_finite() && shift.y.is_finite() { space.center + shift } else { space.center }
|
||||
}
|
||||
|
||||
/// Radial Blur: the average of the content turned (spin) or scaled (zoom) about the Blur Center
|
||||
/// (`center`, [`blur_center`]) over evenly spaced steps spanning `amount`. Each pass averages the
|
||||
/// previous result with itself turned both ways by half the last step, so `passes` passes average
|
||||
/// 2^`passes` samples at two lookups a pixel each.
|
||||
#[allow(clippy::too_many_arguments)] // the effect's four options
|
||||
pub(super) fn radial(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, amount: f64, zoom: bool, passes: u32, center: [f64; 2]) {
|
||||
// The centre in pixel index coordinates (pixel centres at whole numbers).
|
||||
let c = space.to_doc.inverse() * space.center - Vec2::new(0.5, 0.5);
|
||||
let c = space.to_doc.inverse() * blur_center(space, center) - Vec2::new(0.5, 0.5);
|
||||
if !(c.x.is_finite() && c.y.is_finite()) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ fn space(w: usize, h: usize) -> PixelSpace {
|
||||
to_doc: Affine::IDENTITY,
|
||||
px: 1.0,
|
||||
center: Point::new(w / 2.0, h / 2.0),
|
||||
size: vectorcraft_geom::Vec2::new(w, h),
|
||||
channels: Channels::Rgb,
|
||||
line: 1.0,
|
||||
extent: 0.5 * w.hypot(h),
|
||||
@@ -479,12 +480,16 @@ fn film_grain_leaves_invalid_coordinate_spaces_alone() {
|
||||
|
||||
#[test]
|
||||
fn params_take_defaults_and_stay_in_range() {
|
||||
assert_eq!(fx("blur.radial", json!({})), PixelFx::RadialBlur { amount: 10.0, zoom: false, passes: 6 });
|
||||
assert_eq!(fx("blur.radial", json!({})), PixelFx::RadialBlur { amount: 10.0, zoom: false, passes: 6, center: [0.5, 0.5] });
|
||||
assert_eq!(
|
||||
fx("blur.radial", json!({"amount": 1e308, "method": "ZOOM", "quality": "best"})),
|
||||
PixelFx::RadialBlur { amount: 100.0, zoom: true, passes: 8 }
|
||||
fx("blur.radial", json!({"amount": 1e308, "method": "ZOOM", "quality": "best", "centerX": 0.25, "centerY": 1})),
|
||||
PixelFx::RadialBlur { amount: 100.0, zoom: true, passes: 8, center: [0.25, 1.0] }
|
||||
);
|
||||
// A saved center outside the bounds (the commands refuse one) draws at the nearest edge.
|
||||
assert_eq!(
|
||||
fx("blur.radial", json!({"amount": -5, "quality": "nonsense", "centerX": -3, "centerY": 7})),
|
||||
PixelFx::RadialBlur { amount: 1.0, zoom: false, passes: 6, center: [0.0, 1.0] }
|
||||
);
|
||||
assert_eq!(fx("blur.radial", json!({"amount": -5, "quality": "nonsense"})), PixelFx::RadialBlur { amount: 1.0, zoom: false, passes: 6 });
|
||||
assert_eq!(fx("blur.smart", json!({})), PixelFx::SmartBlur { radius: 3.0, threshold: 25.0, samples: 7, mode: SmartBlurMode::Normal });
|
||||
assert_eq!(
|
||||
fx("blur.smart", json!({"radius": "1e999", "threshold": -1, "quality": "low", "blurMode": "EDGEONLY"})),
|
||||
@@ -519,6 +524,11 @@ fn outsets_follow_the_object() {
|
||||
let far = 0.5 * 100f64.hypot(50.0);
|
||||
assert!((spin.outset(b) - (far - 25.0)).abs() < 1e-9);
|
||||
assert!(fx("blur.radial", json!({"method": "zoom", "amount": 100})).outset(b) > 0.4 * far);
|
||||
// About a corner the spin reaches the circle through the opposite corner, the whole diagonal out.
|
||||
let corner = fx("blur.radial", json!({"centerX": 0, "centerY": 0}));
|
||||
assert!((corner.outset(b) - 100f64.hypot(50.0)).abs() < 1e-9, "{}", corner.outset(b));
|
||||
let zoom = |center: f64| fx("blur.radial", json!({"method": "zoom", "amount": 100, "centerX": center, "centerY": center})).outset(b);
|
||||
assert!((zoom(1.0) - 2.0 * zoom(0.5)).abs() < 1e-9, "a zoom about a corner reaches twice as far");
|
||||
assert_eq!(fx("blur.smart", json!({"radius": 4})).outset(b), 4.0);
|
||||
assert_eq!(fx("blur.smart", json!({"radius": 4})).reach(1.0), Some(4.0));
|
||||
// The edge modes also read the copy blurred over a wide radius's samples.
|
||||
@@ -633,6 +643,40 @@ fn spin_blur_smears_along_arcs_and_keeps_the_centre() {
|
||||
assert_eq!(at(&z, w, 32, 16)[3], 0, "not across it");
|
||||
}
|
||||
|
||||
/// The Blur Center moves the point the blur turns about: a dot on it stays sharp, a dot on the
|
||||
/// object's centre then spreads, and the center follows the object when it moves or is scaled.
|
||||
#[test]
|
||||
fn radial_blur_turns_about_its_blur_center() {
|
||||
let (w, h) = (41, 41);
|
||||
// A dot on pixel (10, 30), whose centre (10.5, 30.5) is the Blur Center below, and one on the
|
||||
// object's centre.
|
||||
let src = image(w, h, |x, y| if (x == 10 && y == 30) || (x == 20 && y == 20) { grey(255) } else { [0, 0, 0, 0] });
|
||||
let blur = |p: serde_json::Value, s: &PixelSpace, src: &[u8]| {
|
||||
let mut d = src.to_vec();
|
||||
fx("blur.radial", p).apply(&mut d, w, h, s);
|
||||
d
|
||||
};
|
||||
let off = json!({"amount": 60, "quality": "best", "centerX": 10.5 / 41.0, "centerY": 30.5 / 41.0});
|
||||
let d = blur(off.clone(), &space(w, h), &src);
|
||||
assert!(at(&d, w, 10, 30)[3] > 100, "the dot on the Blur Center barely moves: {:?}", at(&d, w, 10, 30));
|
||||
assert!(at(&d, w, 20, 20)[3] < 100, "the dot on the object's centre spreads: {:?}", at(&d, w, 20, 20));
|
||||
// The default center is the object's centre, the same as no center at all.
|
||||
assert_eq!(blur(json!({"amount": 60, "centerX": 0.5, "centerY": 0.5}), &space(w, h), &src), blur(json!({"amount": 60}), &space(w, h), &src));
|
||||
// Moved 7 pt right and 3 pt down, the object draws the same pixels.
|
||||
let moved =
|
||||
PixelSpace { to_doc: Affine::translate((7.0, 3.0)), center: space(w, h).center + vectorcraft_geom::Vec2::new(7.0, 3.0), ..space(w, h) };
|
||||
assert_eq!(blur(off.clone(), &moved, &src), d, "the center moves with the object");
|
||||
// Drawn at twice the size (two points a pixel), the center lies on the same pixels.
|
||||
let big = PixelSpace {
|
||||
to_doc: Affine::scale(2.0),
|
||||
px: 2.0,
|
||||
center: Point::new(41.0, 41.0),
|
||||
size: vectorcraft_geom::Vec2::new(82.0, 82.0),
|
||||
..space(w, h)
|
||||
};
|
||||
assert_eq!(blur(off, &big, &src), d, "the center scales with the object");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smart_blur_smooths_noise_and_keeps_edges() {
|
||||
let (w, h) = (40, 20);
|
||||
@@ -862,6 +906,7 @@ fn lengths_are_document_units() {
|
||||
to_doc: Affine::scale(1.0 / scale as f64),
|
||||
px: 1.0 / scale as f64,
|
||||
center: Point::ZERO,
|
||||
size: vectorcraft_geom::Vec2::ZERO,
|
||||
channels: Channels::Rgb,
|
||||
line: 1.0,
|
||||
extent: 0.0,
|
||||
@@ -916,7 +961,15 @@ fn linear_light_blur_mixes_light_not_values() {
|
||||
fn pixel_timings() {
|
||||
let (w, h) = (2000, 2000);
|
||||
let src = image(w, h, |x, y| [(x % 256) as u8, (y % 256) as u8, ((x ^ y) % 256) as u8, 255]);
|
||||
let s = PixelSpace { to_doc: Affine::IDENTITY, px: 1.0, center: Point::new(1000.0, 1000.0), channels: Channels::Rgb, line: 1.0, extent: 0.0 };
|
||||
let s = PixelSpace {
|
||||
to_doc: Affine::IDENTITY,
|
||||
px: 1.0,
|
||||
center: Point::new(1000.0, 1000.0),
|
||||
size: vectorcraft_geom::Vec2::new(2000.0, 2000.0),
|
||||
channels: Channels::Rgb,
|
||||
line: 1.0,
|
||||
extent: 0.0,
|
||||
};
|
||||
let cases = [
|
||||
("blur.radial", json!({"quality": "draft"})),
|
||||
("blur.radial", json!({"quality": "good"})),
|
||||
@@ -1494,6 +1547,42 @@ fn texturizer_draws_a_loaded_texture_as_relief() {
|
||||
assert_eq!(fx("texture.texturizer", json!({"texture": "LOADED", "textureImage": "not a texture"})), fx("texture.texturizer", json!({})));
|
||||
}
|
||||
|
||||
/// Rough Pastels draws a loaded texture as its surface, and Scaling, Relief, Light Direction and
|
||||
/// Invert act on it as on the built-in ones.
|
||||
#[test]
|
||||
fn rough_pastels_draws_a_loaded_texture_as_its_surface() {
|
||||
let w = 64;
|
||||
let mid = grey(150);
|
||||
let rings = stored(12, 10, |x, y| {
|
||||
let v = ((x as f64 - 5.5).hypot(y as f64 - 4.5) * 0.9).sin().abs();
|
||||
let g = (v * 255.0).round() as u8;
|
||||
[g, g, g, 255]
|
||||
});
|
||||
let run = |mut p: serde_json::Value| {
|
||||
p["strokeLength"] = json!(0);
|
||||
let mut d = flat(w, mid);
|
||||
fx("artistic.roughPastels", p).apply(&mut d, w, w, &space(w, w));
|
||||
d
|
||||
};
|
||||
let relief = run(json!({"texture": "loaded", "textureImage": rings, "relief": 20}));
|
||||
assert_ne!(relief, flat(w, mid));
|
||||
for (_, builtin) in TEXTURES {
|
||||
assert_ne!(relief, run(json!({"texture": builtin, "relief": 20})), "{builtin}");
|
||||
}
|
||||
for (key, value) in [("invert", json!(true)), ("scaling", json!(200)), ("lightDirection", json!("bottomRight")), ("relief", json!(5))] {
|
||||
let mut p = json!({"texture": "loaded", "textureImage": rings, "relief": 20});
|
||||
p[key] = value;
|
||||
assert_ne!(run(p), relief, "{key}");
|
||||
}
|
||||
assert_eq!(run(json!({"texture": "loaded", "textureImage": rings, "relief": 0})), flat(w, mid));
|
||||
let parsed = fx("artistic.roughPastels", json!({"texture": "Loaded", "textureImage": rings}));
|
||||
assert!(matches!(parsed, PixelFx::RoughPastels { texture: Texture::Loaded(_), .. }), "{parsed:?}");
|
||||
// Without a stored texture, or with one that isn't, Loaded draws Canvas.
|
||||
for p in [json!({"texture": "loaded"}), json!({"texture": "loaded", "textureImage": "not a texture"})] {
|
||||
assert_eq!(fx("artistic.roughPastels", p), fx("artistic.roughPastels", json!({})));
|
||||
}
|
||||
}
|
||||
|
||||
/// The Texture filters' patterns lie in document space around the object's centre: the same at
|
||||
/// twice the resolution, and moving with the object.
|
||||
#[test]
|
||||
|
||||
@@ -14,6 +14,7 @@ fn space(w: usize, h: usize) -> PixelSpace {
|
||||
to_doc: Affine::IDENTITY,
|
||||
px: 1.0,
|
||||
center: Point::new(w / 2.0, h / 2.0),
|
||||
size: vectorcraft_geom::Vec2::new(w, h),
|
||||
channels: Channels::Rgb,
|
||||
line: 1.0,
|
||||
extent: 0.5 * w.hypot(h),
|
||||
|
||||
@@ -14,6 +14,7 @@ fn space(w: usize, h: usize) -> PixelSpace {
|
||||
to_doc: Affine::IDENTITY,
|
||||
px: 1.0,
|
||||
center: Point::new(w / 2.0, h / 2.0),
|
||||
size: vectorcraft_geom::Vec2::new(w, h),
|
||||
channels: Channels::Rgb,
|
||||
line: 1.0,
|
||||
extent: 0.5 * w.hypot(h),
|
||||
|
||||
@@ -1115,6 +1115,44 @@ fn the_check_builds_the_profile_of_a_shape_with_no_fill() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A filled shape is checked about the bounds the effect draws its solid about, which take in the
|
||||
/// strokes beside it. A shape of many small curves is too complex for Extrude & Bevel about the
|
||||
/// shapes' own bounds, where its curves are sampled more finely, and passes about the bounds of a
|
||||
/// wide stroke in its group, as its solid draws there.
|
||||
#[test]
|
||||
fn the_check_builds_a_filled_shape_about_the_bounds_its_solid_draws_about() {
|
||||
// 900 curves about (100, 100), each bulging 1 pt out from a side of a polygon 80 pt across.
|
||||
let corners = 900;
|
||||
let center = Point::new(100.0, 100.0);
|
||||
let corner = |k: usize| {
|
||||
let (s, c) = (k as f64 * std::f64::consts::TAU / corners as f64).sin_cos();
|
||||
Point::new(center.x + 40.0 * c, center.y + 40.0 * s)
|
||||
};
|
||||
let mut b = BezPath::new();
|
||||
b.move_to(corner(0));
|
||||
for k in 0..corners {
|
||||
let (p0, p3) = (corner(k), corner(k + 1));
|
||||
let out = p0.midpoint(p3) - center;
|
||||
let out = out / out.hypot();
|
||||
b.curve_to(p0 + (p3 - p0) / 3.0 + out, p0 + (p3 - p0) * (2.0 / 3.0) + out, p3);
|
||||
}
|
||||
b.close_path();
|
||||
let filled = Node::path(NodeId(1), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(RED), Paint::None, 0.0));
|
||||
let mut line = BezPath::new();
|
||||
line.move_to((80.0, 100.0));
|
||||
line.line_to((120.0, 100.0));
|
||||
let mut wide = Node::path(NodeId(2), PathData::from_bezpath(&line), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 2000.0));
|
||||
wide.appearance.items.retain(|i| matches!(i, AppearanceItem::Stroke(_)));
|
||||
let p = json!({"bevel": "rounded", "bevelRepeat": 6});
|
||||
let (path, rule) = profile(&filled).unwrap();
|
||||
let own = path.bounds().unwrap().union(wide.path_data().unwrap().bounds().unwrap());
|
||||
assert_eq!(facets(EXTRUDE, &path, rule, own, &p).map(|_| ()), Err(vectorcraft_three_d::TOO_COMPLEX_SOLID.to_string()), "about its own bounds");
|
||||
let mut g = Node::group(NodeId(9999), vec![Arc::new(filled), Arc::new(wide)]);
|
||||
assert_eq!(validate_solid(&g, EXTRUDE, &p), Ok(()));
|
||||
g.appearance.effects.push(fx(EXTRUDE, p));
|
||||
assert!(solid_art(&g).is_some(), "the solid draws");
|
||||
}
|
||||
|
||||
/// A convex polygon of `corners` corners about (20,000, 20,000), filled red, with no stroke.
|
||||
fn polygon_node(id: u64, corners: usize) -> Node {
|
||||
let points: Vec<Point> = (0..corners)
|
||||
|
||||
@@ -16,6 +16,7 @@ use vectorcraft_geom::{Affine, Rect, Vec2};
|
||||
use crate::pixel::PixelSpace;
|
||||
use crate::util::{num, text};
|
||||
|
||||
pub mod defaults;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
//! The default SVG filters: the filters Effect › SVG Filters and Apply SVG Filter list in every
|
||||
//! document. The set, the names and the values are VectorCraft's own, written with the filter
|
||||
//! primitives of SVG 1.1 (<https://www.w3.org/TR/SVG11/filters.html>). A default is not part of a
|
||||
//! document until it is applied or edited there: the document then holds a copy under the
|
||||
//! default's name, and that copy stands in the default's place in the lists. Every default computes
|
||||
//! in sRGB (`color-interpolation-filters="sRGB"`), so art a filter passes through keeps its colors.
|
||||
|
||||
use vectorcraft_doc::SvgFilter;
|
||||
|
||||
/// A default SVG filter: its name (the `<filter>` element's `id`) and the element's XML.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct DefaultFilter {
|
||||
pub name: &'static str,
|
||||
pub xml: &'static str,
|
||||
}
|
||||
|
||||
/// The default filters, in the order the lists show them.
|
||||
pub const DEFAULT_FILTERS: [DefaultFilter; 14] = [
|
||||
DefaultFilter {
|
||||
name: "Soft Blur",
|
||||
xml: r#"<filter id="Soft Blur" x="-20%" y="-20%" width="140%" height="140%" color-interpolation-filters="sRGB"><feGaussianBlur stdDeviation="2"/></filter>"#,
|
||||
},
|
||||
DefaultFilter {
|
||||
name: "Heavy Blur",
|
||||
xml: r#"<filter id="Heavy Blur" x="-50%" y="-50%" width="200%" height="200%" color-interpolation-filters="sRGB"><feGaussianBlur stdDeviation="6"/></filter>"#,
|
||||
},
|
||||
DefaultFilter {
|
||||
name: "Soft Shadow",
|
||||
xml: r#"<filter id="Soft Shadow" x="-30%" y="-30%" width="170%" height="170%" color-interpolation-filters="sRGB"><feGaussianBlur in="SourceAlpha" stdDeviation="3"/><feOffset dx="4" dy="4"/><feComponentTransfer><feFuncA type="linear" slope="0.5"/></feComponentTransfer><feMerge><feMergeNode/><feMergeNode in="SourceGraphic"/></feMerge></filter>"#,
|
||||
},
|
||||
DefaultFilter {
|
||||
name: "Hard Shadow",
|
||||
xml: r#"<filter id="Hard Shadow" x="-20%" y="-20%" width="150%" height="150%" color-interpolation-filters="sRGB"><feOffset in="SourceAlpha" dx="3" dy="3"/><feComponentTransfer><feFuncA type="linear" slope="0.6"/></feComponentTransfer><feMerge><feMergeNode/><feMergeNode in="SourceGraphic"/></feMerge></filter>"#,
|
||||
},
|
||||
DefaultFilter {
|
||||
name: "Glow",
|
||||
xml: r##"<filter id="Glow" x="-40%" y="-40%" width="180%" height="180%" color-interpolation-filters="sRGB"><feGaussianBlur in="SourceAlpha" stdDeviation="4" result="spread"/><feFlood flood-color="#ffd24a"/><feComposite in2="spread" operator="in"/><feMerge><feMergeNode/><feMergeNode in="SourceGraphic"/></feMerge></filter>"##,
|
||||
},
|
||||
DefaultFilter {
|
||||
name: "Bevel",
|
||||
xml: r##"<filter id="Bevel" color-interpolation-filters="sRGB"><feGaussianBlur in="SourceAlpha" stdDeviation="2" result="height"/><feSpecularLighting in="height" surfaceScale="4" specularConstant="0.8" specularExponent="16" lighting-color="#ffffff" result="light"><feDistantLight azimuth="225" elevation="45"/></feSpecularLighting><feComposite in="light" in2="SourceAlpha" operator="in" result="lit"/><feComposite in="SourceGraphic" in2="lit" operator="arithmetic" k1="0" k2="1" k3="1" k4="0"/></filter>"##,
|
||||
},
|
||||
DefaultFilter {
|
||||
name: "Emboss",
|
||||
xml: r#"<filter id="Emboss" color-interpolation-filters="sRGB"><feConvolveMatrix order="3" kernelMatrix="-2 -1 0 -1 1 1 0 1 2" preserveAlpha="true"/></filter>"#,
|
||||
},
|
||||
DefaultFilter {
|
||||
name: "Thicken",
|
||||
xml: r#"<filter id="Thicken" x="-20%" y="-20%" width="140%" height="140%" color-interpolation-filters="sRGB"><feMorphology operator="dilate" radius="1.5"/></filter>"#,
|
||||
},
|
||||
DefaultFilter {
|
||||
name: "Thin",
|
||||
xml: r#"<filter id="Thin" color-interpolation-filters="sRGB"><feMorphology operator="erode" radius="1.5"/></filter>"#,
|
||||
},
|
||||
DefaultFilter {
|
||||
name: "Rough Edges",
|
||||
xml: r#"<filter id="Rough Edges" x="-20%" y="-20%" width="140%" height="140%" color-interpolation-filters="sRGB"><feTurbulence type="turbulence" baseFrequency="0.05" numOctaves="2" result="waves"/><feDisplacementMap in="SourceGraphic" in2="waves" scale="6" xChannelSelector="R" yChannelSelector="G"/></filter>"#,
|
||||
},
|
||||
DefaultFilter {
|
||||
name: "Grain",
|
||||
xml: r#"<filter id="Grain" color-interpolation-filters="sRGB"><feTurbulence type="fractalNoise" baseFrequency="0.9" numOctaves="2"/><feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.35 0"/><feComposite in2="SourceAlpha" operator="in" result="specks"/><feMerge><feMergeNode in="SourceGraphic"/><feMergeNode in="specks"/></feMerge></filter>"#,
|
||||
},
|
||||
DefaultFilter {
|
||||
name: "Grayscale",
|
||||
xml: r#"<filter id="Grayscale" color-interpolation-filters="sRGB"><feColorMatrix type="saturate" values="0"/></filter>"#,
|
||||
},
|
||||
DefaultFilter {
|
||||
name: "Invert",
|
||||
xml: r#"<filter id="Invert" color-interpolation-filters="sRGB"><feComponentTransfer><feFuncR type="table" tableValues="1 0"/><feFuncG type="table" tableValues="1 0"/><feFuncB type="table" tableValues="1 0"/></feComponentTransfer></filter>"#,
|
||||
},
|
||||
DefaultFilter {
|
||||
name: "Hue Shift",
|
||||
xml: r#"<filter id="Hue Shift" color-interpolation-filters="sRGB"><feColorMatrix type="hueRotate" values="180"/></filter>"#,
|
||||
},
|
||||
];
|
||||
|
||||
/// The default filter named `name`.
|
||||
pub fn default_filter(name: &str) -> Option<DefaultFilter> {
|
||||
DEFAULT_FILTERS.iter().copied().find(|f| f.name == name)
|
||||
}
|
||||
|
||||
impl DefaultFilter {
|
||||
/// The filter as a document holds it once it is applied or edited there.
|
||||
pub fn to_filter(self) -> SvgFilter {
|
||||
SvgFilter { name: self.name.to_string(), xml: self.xml.to_string() }
|
||||
}
|
||||
}
|
||||
|
||||
/// A filter of the lists ([`listed`]), and whether it is a default the document does not hold.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Listed {
|
||||
pub filter: SvgFilter,
|
||||
/// A default the document has no filter named for: applying or editing it adds a copy.
|
||||
pub default: bool,
|
||||
}
|
||||
|
||||
/// The filters Effect › SVG Filters and Apply SVG Filter list for a document that holds `held`,
|
||||
/// and how many of them come first as the defaults: each default in [`DEFAULT_FILTERS`]' order (the
|
||||
/// document's filter of that name in its place), then the document's other filters in their order.
|
||||
pub fn listed(held: &[SvgFilter]) -> (Vec<Listed>, usize) {
|
||||
let mut out: Vec<Listed> = DEFAULT_FILTERS
|
||||
.iter()
|
||||
.map(|d| match held.iter().find(|f| f.name == d.name) {
|
||||
Some(f) => Listed { filter: f.clone(), default: false },
|
||||
None => Listed { filter: d.to_filter(), default: true },
|
||||
})
|
||||
.collect();
|
||||
let defaults = out.len();
|
||||
out.extend(held.iter().filter(|f| default_filter(&f.name).is_none()).map(|f| Listed { filter: f.clone(), default: false }));
|
||||
(out, defaults)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::Effect;
|
||||
use vectorcraft_geom::{Affine, Point};
|
||||
|
||||
use super::*;
|
||||
use crate::pixel::{Channels, PixelSpace};
|
||||
use crate::svg_filter::{SVG_FILTER, SvgFilterFx, check, with_id};
|
||||
use crate::{PixelFx, RasterFx, raster_effects};
|
||||
|
||||
/// A `w` × `w` raster whose pixels are one point wide.
|
||||
fn space(w: usize) -> PixelSpace {
|
||||
let wd = w as f64;
|
||||
PixelSpace {
|
||||
to_doc: Affine::scale(1.0),
|
||||
px: 1.0,
|
||||
center: Point::new(wd / 2.0, wd / 2.0),
|
||||
size: vectorcraft_geom::Vec2::new(wd, wd),
|
||||
channels: Channels::Rgb,
|
||||
line: 1.0,
|
||||
extent: 0.5 * wd.hypot(wd),
|
||||
}
|
||||
}
|
||||
|
||||
/// The default named `name` as the renderer reads it.
|
||||
fn fx(name: &str) -> SvgFilterFx {
|
||||
let d = default_filter(name).unwrap_or_else(|| panic!("no default {name}"));
|
||||
let e = Effect { id: SVG_FILTER.into(), params: json!({"name": d.name, "xml": d.xml}), visible: true };
|
||||
match raster_effects(&[e]).first() {
|
||||
Some(RasterFx::Pixel(PixelFx::Svg(f))) => f.clone(),
|
||||
other => panic!("{name}: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A 40 × 40 raster with an opaque square of `rgb` from 10 to 30, run through default `name`.
|
||||
fn run(name: &str, rgb: [u8; 3]) -> Vec<u8> {
|
||||
let mut data: Vec<u8> = (0..40usize)
|
||||
.flat_map(|y| (0..40usize).map(move |x| (x, y)))
|
||||
.flat_map(|(x, y)| if (10..30).contains(&x) && (10..30).contains(&y) { [rgb[0], rgb[1], rgb[2], 255] } else { [0; 4] })
|
||||
.collect();
|
||||
fx(name).apply(&mut data, 40, 40, &space(40));
|
||||
data
|
||||
}
|
||||
|
||||
fn at(d: &[u8], x: usize, y: usize) -> [u8; 4] {
|
||||
let i = (y * 40 + x) * 4;
|
||||
[d[i], d[i + 1], d[i + 2], d[i + 3]]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_default_is_a_filter_the_check_takes_under_its_own_name() {
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
for d in DEFAULT_FILTERS {
|
||||
assert_eq!(check(d.xml), Ok(d.name.to_string()), "{}", d.name);
|
||||
assert!(seen.insert(d.name), "{} is listed twice", d.name);
|
||||
assert_eq!(d.name, d.name.trim());
|
||||
// Edit SVG Filter keeps the name by writing it as the id: a default's code comes back as it is.
|
||||
assert_eq!(with_id(d.xml, d.name).as_deref(), Some(d.xml), "{}", d.name);
|
||||
assert_eq!(default_filter(d.name), Some(d));
|
||||
assert!(d.xml.contains(r#" color-interpolation-filters="sRGB""#), "{} computes in sRGB", d.name);
|
||||
}
|
||||
assert!(DEFAULT_FILTERS.len() <= SvgFilter::MAX);
|
||||
assert_eq!(default_filter("soft blur"), None, "names match exactly");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_default_draws_and_is_written_to_svg_as_a_filter() {
|
||||
let plain = {
|
||||
let mut d = vec![0u8; 40 * 40 * 4];
|
||||
for y in 10..30 {
|
||||
for x in 10..30 {
|
||||
d[(y * 40 + x) * 4..(y * 40 + x) * 4 + 4].copy_from_slice(&[200, 60, 20, 255]);
|
||||
}
|
||||
}
|
||||
d
|
||||
};
|
||||
for d in DEFAULT_FILTERS {
|
||||
assert_ne!(run(d.name, [200, 60, 20]), plain, "{} changes what is drawn", d.name);
|
||||
assert!(fx(d.name).writes_as_svg11(), "{} is written as SVG 1.1", d.name);
|
||||
}
|
||||
}
|
||||
|
||||
/// The color defaults against SVG 1.1's own arithmetic, in sRGB as each filter asks.
|
||||
#[test]
|
||||
fn the_color_defaults_compute_what_svg_1_1_defines() {
|
||||
let near = |got: [u8; 4], want: [u8; 4]| got.iter().zip(want).all(|(g, w)| g.abs_diff(w) <= 1);
|
||||
// feComponentTransfer, type="table" with values 1 0: C' = 1 - C (§15.11).
|
||||
let inv = at(&run("Invert", [200, 60, 20]), 20, 20);
|
||||
assert!(near(inv, [55, 195, 235, 255]), "{inv:?}");
|
||||
// feColorMatrix type="saturate" values="0": every channel is 0.213 R + 0.715 G + 0.072 B (§15.10).
|
||||
let grey = at(&run("Grayscale", [200, 60, 20]), 20, 20);
|
||||
let l = (0.213 * 200.0 + 0.715 * 60.0 + 0.072 * 20.0f64).round() as u8;
|
||||
assert!(near(grey, [l, l, l, 255]), "{grey:?} for {l}");
|
||||
// feColorMatrix type="hueRotate" values="180" (§15.10): cos = -1 and sin = 0 leave
|
||||
// R' = (2·0.213 - 1) R + 2·0.715 G + 2·0.072 B, and likewise for G' and B'.
|
||||
let hue = at(&run("Hue Shift", [200, 60, 20]), 20, 20);
|
||||
let lum2 = 2.0 * (0.213 * 200.0 + 0.715 * 60.0 + 0.072 * 20.0f64);
|
||||
let turned = [lum2 - 200.0, lum2 - 60.0, lum2 - 20.0].map(|v| v.round().clamp(0.0, 255.0) as u8);
|
||||
assert!(near(hue, [turned[0], turned[1], turned[2], 255]), "{hue:?} for {turned:?}");
|
||||
}
|
||||
|
||||
/// The shape defaults against what their primitives define: an offset copy of the alpha behind
|
||||
/// the art (feOffset, §15.21), and a shape grown or shrunk by its radius (feMorphology, §15.20).
|
||||
#[test]
|
||||
fn the_shape_defaults_move_and_resize_the_alpha() {
|
||||
let shadow = run("Hard Shadow", [200, 60, 20]);
|
||||
assert_eq!(at(&shadow, 20, 20), [200, 60, 20, 255], "the art is on top");
|
||||
// Right of and below the art by up to 3: black at 60% alpha (premultiplied 153).
|
||||
assert_eq!(at(&shadow, 31, 31), [0, 0, 0, 153]);
|
||||
assert_eq!(at(&shadow, 34, 34)[3], 0, "past the offset");
|
||||
assert_eq!(at(&shadow, 8, 8)[3], 0, "nothing up and left");
|
||||
let thick = run("Thicken", [200, 60, 20]);
|
||||
assert_eq!((at(&thick, 9, 20)[3], at(&thick, 7, 20)[3]), (255, 0), "grown by its radius");
|
||||
let thin = run("Thin", [200, 60, 20]);
|
||||
assert_eq!((at(&thin, 10, 20)[3], at(&thin, 13, 20)[3]), (0, 255), "shrunk by its radius");
|
||||
let soft = run("Soft Shadow", [200, 60, 20]);
|
||||
assert_eq!(at(&soft, 20, 20), [200, 60, 20, 255]);
|
||||
let below = at(&soft, 33, 33);
|
||||
assert!(below[3] > 0 && below[3] < 128 && below[0] == 0, "a blurred, half-strength shadow: {below:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_lists_show_the_defaults_first_with_the_documents_copy_in_place() {
|
||||
let (all, defaults) = listed(&[]);
|
||||
assert_eq!((all.len(), defaults), (DEFAULT_FILTERS.len(), DEFAULT_FILTERS.len()));
|
||||
assert!(all.iter().all(|l| l.default));
|
||||
let mine = SvgFilter { name: "Mine".into(), xml: "<filter id=\"Mine\"><feOffset/></filter>".into() };
|
||||
let glow = SvgFilter { name: "Glow".into(), xml: "<filter id=\"Glow\"><feOffset dx=\"1\"/></filter>".into() };
|
||||
let (all, defaults) = listed(&[mine.clone(), glow.clone()]);
|
||||
assert_eq!((all.len(), defaults), (DEFAULT_FILTERS.len() + 1, DEFAULT_FILTERS.len()));
|
||||
let at = DEFAULT_FILTERS.iter().position(|d| d.name == "Glow").unwrap();
|
||||
assert_eq!(all[at], Listed { filter: glow, default: false }, "the document's Glow where the default was");
|
||||
assert_eq!(all.last(), Some(&Listed { filter: mine, default: false }));
|
||||
assert_eq!(all.iter().filter(|l| l.default).count(), DEFAULT_FILTERS.len() - 1);
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,15 @@ use crate::{PixelFx, RasterFx, raster_effects};
|
||||
/// resolution whose pixels are `line` points wide.
|
||||
fn space(w: usize, h: usize, px: f64, line: f64) -> PixelSpace {
|
||||
let (wd, hd) = (w as f64 * px, h as f64 * px);
|
||||
PixelSpace { to_doc: Affine::scale(px), px, center: Point::new(wd / 2.0, hd / 2.0), channels: Channels::Rgb, line, extent: 0.5 * wd.hypot(hd) }
|
||||
PixelSpace {
|
||||
to_doc: Affine::scale(px),
|
||||
px,
|
||||
center: Point::new(wd / 2.0, hd / 2.0),
|
||||
size: vectorcraft_geom::Vec2::new(wd, hd),
|
||||
channels: Channels::Rgb,
|
||||
line,
|
||||
extent: 0.5 * wd.hypot(hd),
|
||||
}
|
||||
}
|
||||
|
||||
/// `w` × `h` premultiplied pixels: `f(x, y)` each.
|
||||
|
||||
@@ -1850,6 +1850,7 @@ fn rasterize_compose_leaves_the_raster_alone_when_the_sizes_do_not_fit() {
|
||||
to_doc: Affine::IDENTITY,
|
||||
px: 1.0,
|
||||
center: Point::new(1.0, 1.0),
|
||||
size: vectorcraft_geom::Vec2::new(2.0, 2.0),
|
||||
channels: pixel::Channels::Rgb,
|
||||
line: 1.0,
|
||||
extent: std::f64::consts::SQRT_2,
|
||||
|
||||
@@ -172,6 +172,48 @@ fn the_clipping_paths_effects_apply_before_the_clip_groups() {
|
||||
assert!((b.x0 - want.x0).abs() < 0.5 && (b.x1 - want.x1).abs() < 0.5, "exported: {b:?} against {want:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clip_group_with_a_fill_or_stroke_of_its_own_clips_as_the_canvas_does() {
|
||||
// A clip group with a fill or a stroke of its own and no effects: the export turns its paint
|
||||
// into art and still clips by the outline the canvas clips by, Transform copies included.
|
||||
let items = [
|
||||
vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(Color::BLACK))),
|
||||
vectorcraft_doc::AppearanceItem::Stroke(vectorcraft_doc::StrokeLayer::new(Paint::solid(Color::BLACK), 2.0)),
|
||||
];
|
||||
let copies = || fx("distort.transform", json!({"moveH": 60, "copies": 1}));
|
||||
let roughen = fx("distort.roughen", json!({"size": 10, "detail": 10, "relative": false}));
|
||||
// A ring: a compound path of two squares with effects `own`, its hole with effects `hole_fx`.
|
||||
let ring = |hole_fx: Vec<Effect>, own: Vec<Effect>| {
|
||||
let outer = Node::path(NodeId(3), shapes::rectangle(Rect::new(50.0, 50.0, 150.0, 150.0)), Appearance::default());
|
||||
let mut hole = Node::path(NodeId(4), shapes::rectangle(Rect::new(75.0, 75.0, 125.0, 125.0)), Appearance::default());
|
||||
hole.appearance.effects = hole_fx;
|
||||
let mut c =
|
||||
Node::new(NodeId(2), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(hole)], rule: vectorcraft_geom::FillRule::EvenOdd });
|
||||
c.appearance.effects = own;
|
||||
c
|
||||
};
|
||||
let clips = [
|
||||
("copies", clipping_path(2, vec![copies()])),
|
||||
("roughen", clipping_path(2, vec![roughen])),
|
||||
("a compound path's copies", ring(vec![], vec![copies()])),
|
||||
("a compound path member's copies", ring(vec![copies()], vec![])),
|
||||
];
|
||||
for item in &items {
|
||||
for (what, clip) in &clips {
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
let layer = d.layers[0].id;
|
||||
let live = clip_outline(clip).unwrap();
|
||||
let mut group = clip_group(1, clip.clone());
|
||||
group.appearance.items.push(item.clone());
|
||||
d.insert(Some(layer), 0, group).unwrap();
|
||||
let exported = clip_outline(&baked_clip(&d)).unwrap();
|
||||
assert_eq!(live, exported, "{what} with {item:?}: the canvas clips by the outline the export writes");
|
||||
}
|
||||
}
|
||||
let b = bounds(&clips[0].1);
|
||||
assert!((b.x0 - 50.0).abs() < 1e-6 && (b.x1 - 210.0).abs() < 1e-6, "the clip covers both copies: {b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_effects_apply_before_the_clip_groups() {
|
||||
// The clip group grows its clipping path by 10 (Offset Path). Inside the clipping path a
|
||||
|
||||
@@ -531,8 +531,13 @@ fn an_anchor_edit_makes_it_a_plain_path_and_transforms_keep_it_editable() {
|
||||
s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "count": 6})).unwrap();
|
||||
assert_eq!((path(&s, id).anchor_count(), steps(&s)), (12, n + 1));
|
||||
assert!((shape_of(&s, id).unwrap().rotation + 30.0).abs() < 1e-6, "the turn stays");
|
||||
// Stretched across its own axes (it is turned): skewed, so no longer.
|
||||
// Stretched along its turned bounding box: still the shape, wider along its own axis.
|
||||
s.execute("object.scale", &json!({"sx": 150, "sy": 100, "origin": [220, 140]})).unwrap();
|
||||
let r = shape_of(&s, id).unwrap();
|
||||
assert!((r.width - 300.0).abs() < 1e-6 && (r.height - 200.0).abs() < 1e-6 && (r.rotation + 30.0).abs() < 1e-6, "{r:?}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// Stretched across the page's axes (it is turned): skewed, so no longer.
|
||||
s.execute("object.scale", &json!({"sx": 150, "sy": 100, "origin": [220, 140], "basis": "page"})).unwrap();
|
||||
assert_eq!(shape_of(&s, id), None);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(shape_of(&s, id).is_some(), "undo brings it back");
|
||||
|
||||
@@ -14,7 +14,7 @@ use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_color::{BlendMode, Color, Paint};
|
||||
use vectorcraft_doc::appearance::{AppearanceItem, FillLayer, LineCap, LineJoin, StrokeLayer};
|
||||
use vectorcraft_doc::{Appearance, Document, GapOptions, GapSize, LiveShape, Node, NodeId, NodeKind, Selection, TraceView};
|
||||
use vectorcraft_geom::{FillRule, PathData, Point, Rect, SubPath};
|
||||
@@ -72,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Make",
|
||||
["Object", "Live Paint"],
|
||||
Some("Cmd+Alt+X"),
|
||||
"{ids?|id?} build a Live Paint group from the selected paths (paths, compound paths and groups of them; type, images and other objects are refused, nothing changes); each covered face starts with its front-most covering source's fill; with a Live Paint group among them, add the others to it as livePaint.merge does; a Live Paint group alone has nothing to add, so it is selected and nothing changes (no undo step) → {id, faces, edges}",
|
||||
"{ids?|id?} build a Live Paint group from the selected paths (paths, compound paths and groups of them; type, images and other objects are refused, nothing changes); each covered face starts with the fill rows that draw (shown, with paint and an opacity above 0) of its front-most covering source that has one and an opacity above 0, and each edge with the stroke rows that draw (also a weight above 0) of its source, in order with their settings and with that source's opacity and blending mode (on a path cut into several edges, dashes go on along the path with the lengths set, without the fit of dashes aligned to corners and path ends, arrowheads stay at its own ends, and a width profile or brush stays only on an edge that runs the whole path); a face or edge given no such row has one unpainted row; with a Live Paint group among them, add the others to it as livePaint.merge does; a Live Paint group alone has nothing to add, so it is selected and nothing changes (no undo step) → {id, faces, edges}",
|
||||
has_selection_or_ids,
|
||||
lp_make
|
||||
),
|
||||
@@ -117,7 +117,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Live Paint Bucket",
|
||||
[],
|
||||
None,
|
||||
"{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], points?: [[x,y]…] (a drag polyline starting at point; 1 to 4096 finite canvas points; fills every crossed face of the same group), continuation?: [[[x,y]…]…] (further path chunks of 1 to 4096 finite canvas points each; each starts at the preceding chunk's last point; requires points), color?|swatch?|gradient?|none? (default: current fill; a color in #rrggbbaa or #rgba is refused), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces; when every face it reaches already has the paint, nothing changes (no undo step, and the recent colors stay as they are) → {group, face}",
|
||||
"{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], points?: [[x,y]…] (a drag polyline starting at point; 1 to 4096 finite canvas points; fills every crossed face of the same group), continuation?: [[[x,y]…]…] (further path chunks of 1 to 4096 finite canvas points each; each starts at the preceding chunk's last point; requires points), scope?: \"one\" (default: the face alone) | \"connected\" (a double-click: also each face reached across edges that are hidden or draw no stroke, as a flood from the face; a stroked edge, a hidden face or a Gap Detection gap stops it) | \"samePaint\" (a triple-click: also every face of the group whose fill is match; \"connected\" and \"samePaint\" are refused with points), match?: paint (as the document stores it, the `fill` of a face's appearance; scope samePaint only; default: the face's fill), color?|swatch?|gradient?|none? (default: current fill; a color in #rrggbbaa or #rgba is refused), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces; when every face it reaches already has the paint, nothing changes (no undo step, and the recent colors stay as they are) → {group, face, count (faces reached)}",
|
||||
has_doc,
|
||||
lp_fill
|
||||
),
|
||||
@@ -126,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Live Paint Bucket (Stroke)",
|
||||
[],
|
||||
None,
|
||||
"{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point; when it already has the paint and the width, nothing changes (no undo step, and the recent colors stay as they are) → {group, edge}",
|
||||
"{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), scope?: \"one\" (default: the edge alone) | \"connected\" (a double-click: also each edge joined to it, end to end, through edges that draw with stroke paint match) | \"samePaint\" (a triple-click: also every edge of the group that draws with stroke paint match), match?: paint (as the document stores it; scope connected or samePaint only; default: the stroke paint the edge draws with; an edge draws with the paint of its topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully transparent or has no such stroke), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point, skipping hidden edges: each edge reached takes the paint and width in its topmost stroke that is shown, or in a new stroke above the others when it has none; when every edge it reaches already has the paint and the width there, nothing changes (no undo step, and the recent colors stay as they are) → {group, edge, count (edges reached)}",
|
||||
has_doc,
|
||||
lp_stroke_edge
|
||||
),
|
||||
@@ -414,22 +414,274 @@ fn source_nodes(n: &Node) -> Vec<Arc<Node>> {
|
||||
if is_live_paint(n) { b::sources(n).and_then(|g| g.children().cloned()).unwrap_or_default() } else { vec![Arc::new(n.clone())] }
|
||||
}
|
||||
|
||||
/// Does appearance row `i` draw: it is shown, has paint and an opacity above 0, and a stroke also
|
||||
/// has a weight above 0?
|
||||
fn row_draws(i: &AppearanceItem) -> bool {
|
||||
match i {
|
||||
AppearanceItem::Fill(f) => f.visible && !f.paint.is_none() && f.opacity > 0.0,
|
||||
AppearanceItem::Stroke(s) => s.visible && !s.paint.is_none() && s.opacity > 0.0 && s.width > 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// What a source path gives the faces and edges made from it.
|
||||
struct SourceStyle {
|
||||
/// The fill rows that draw, in paint order (none when the path's opacity is 0).
|
||||
fills: Vec<AppearanceItem>,
|
||||
/// The stroke rows that draw, in paint order (none when the path's opacity is 0).
|
||||
strokes: Vec<AppearanceItem>,
|
||||
/// The top stroke's weight, for an edge given no stroke that draws.
|
||||
width: f64,
|
||||
opacity: f32,
|
||||
blend: BlendMode,
|
||||
}
|
||||
|
||||
impl SourceStyle {
|
||||
/// The style of source path `n`: its rows keep their order and settings, gradients fitted to
|
||||
/// its bounds keep that fit, and the strokes' pen pressure, tilt, bearing and rotation stay
|
||||
/// with the path.
|
||||
fn of(n: &Node) -> Self {
|
||||
let mut a = (*n.appearance).clone().without_pressure();
|
||||
if a.has_unplaced_gradient()
|
||||
&& let Some(bounds) = n.geometric_bounds()
|
||||
{
|
||||
a.pin_gradients(bounds);
|
||||
}
|
||||
let width = a.stroke().map_or(1.0, |s| s.width);
|
||||
let (mut fills, mut strokes) = (vec![], vec![]);
|
||||
if n.opacity > 0.0 {
|
||||
for i in a.items.into_iter().filter(row_draws) {
|
||||
if i.is_fill() { fills.push(i) } else { strokes.push(i) }
|
||||
}
|
||||
}
|
||||
Self { fills, strokes, width, opacity: n.opacity, blend: n.blend }
|
||||
}
|
||||
|
||||
/// Give part `n` the rows `rows` of this source with its opacity and blending mode; with no
|
||||
/// rows, `n` keeps the unpainted row it has.
|
||||
fn paint(&self, n: &mut Node, rows: &[AppearanceItem]) {
|
||||
if rows.is_empty() {
|
||||
return;
|
||||
}
|
||||
n.appearance = Appearance { items: rows.to_vec(), ..Default::default() }.into();
|
||||
n.opacity = self.opacity;
|
||||
n.blend = self.blend;
|
||||
}
|
||||
}
|
||||
|
||||
/// How far, in points, a place on an edge may be from its source path and still be on it.
|
||||
const ON_SOURCE: f64 = 0.05;
|
||||
|
||||
/// Does stroke row `i` have settings that depend on where along its path a piece of it lies or
|
||||
/// which way it runs: dashes, arrowheads, a width profile, a brush, or a gradient along or across
|
||||
/// the stroke?
|
||||
fn depends_on_place(i: &AppearanceItem) -> bool {
|
||||
matches!(i, AppearanceItem::Stroke(s) if s.dash.is_some() || s.start_arrow.is_some() || s.end_arrow.is_some() || s.profile.is_some() || s.brush.is_some() || s.gradient_mode != vectorcraft_doc::StrokeGradientMode::Within)
|
||||
}
|
||||
|
||||
/// One subpath's segments with the length along it where each starts, then its whole length, and
|
||||
/// a grid of square cells listing the segments whose bounds, grown by [`ON_SOURCE`], reach into
|
||||
/// each cell, so finding the segments near a point does not look at every segment.
|
||||
struct Track {
|
||||
segs: Vec<kurbo::PathSeg>,
|
||||
at: Vec<f64>,
|
||||
closed: bool,
|
||||
cell: f64,
|
||||
grid: HashMap<(i64, i64), Vec<usize>>,
|
||||
/// Segments that reach into more than [`Track::MAX_CELLS`] cells, or that come after the grid
|
||||
/// holds [`Track::CELLS_PER_SEGMENT`] entries per segment, looked at for every point.
|
||||
wide: Vec<usize>,
|
||||
}
|
||||
|
||||
impl Track {
|
||||
const ACCURACY: f64 = 1e-4;
|
||||
const MAX_CELLS: i64 = 4096;
|
||||
const CELLS_PER_SEGMENT: usize = 16;
|
||||
|
||||
fn new(sp: &SubPath) -> Self {
|
||||
use kurbo::{ParamCurveArclen, Shape as _};
|
||||
let mut bp = kurbo::BezPath::new();
|
||||
sp.to_bezpath_into(&mut bp);
|
||||
let segs: Vec<kurbo::PathSeg> = bp.segments().collect();
|
||||
let mut at = Vec::with_capacity(segs.len() + 1);
|
||||
let mut len = 0.0;
|
||||
for s in &segs {
|
||||
at.push(len);
|
||||
len += s.arclen(Self::ACCURACY);
|
||||
}
|
||||
at.push(len);
|
||||
let boxes: Vec<kurbo::Rect> = segs.iter().map(|s| s.bounding_box().inflate(ON_SOURCE, ON_SOURCE)).collect();
|
||||
// Cells about as wide as an average segment's bounds.
|
||||
let mean = boxes.iter().map(|b| b.width().max(b.height())).sum::<f64>() / boxes.len().max(1) as f64;
|
||||
let cell = if mean.is_finite() { mean.max(4.0 * ON_SOURCE) } else { 4.0 * ON_SOURCE };
|
||||
let mut grid: HashMap<(i64, i64), Vec<usize>> = HashMap::new();
|
||||
let mut wide = vec![];
|
||||
// The grid holds at most this many entries in all.
|
||||
let mut budget = boxes.len().saturating_mul(Self::CELLS_PER_SEGMENT);
|
||||
for (k, b) in boxes.iter().enumerate() {
|
||||
let (x0, y0) = Self::cell_of(Point::new(b.x0, b.y0), cell);
|
||||
let (x1, y1) = Self::cell_of(Point::new(b.x1, b.y1), cell);
|
||||
let cells = x1.saturating_sub(x0).saturating_add(1).saturating_mul(y1.saturating_sub(y0).saturating_add(1));
|
||||
let Some(cells) = usize::try_from(cells).ok().filter(|&c| cells <= Self::MAX_CELLS && c <= budget) else {
|
||||
wide.push(k);
|
||||
continue;
|
||||
};
|
||||
budget -= cells;
|
||||
for x in x0..=x1 {
|
||||
for y in y0..=y1 {
|
||||
grid.entry((x, y)).or_default().push(k);
|
||||
}
|
||||
}
|
||||
}
|
||||
Self { segs, at, closed: sp.closed, cell, grid, wide }
|
||||
}
|
||||
|
||||
fn cell_of(p: Point, cell: f64) -> (i64, i64) {
|
||||
((p.x / cell).floor() as i64, (p.y / cell).floor() as i64)
|
||||
}
|
||||
|
||||
fn len(&self) -> f64 {
|
||||
self.at.last().copied().unwrap_or(0.0)
|
||||
}
|
||||
|
||||
/// The lengths along the subpath to each of its segments' places nearest `p` that are within
|
||||
/// [`ON_SOURCE`] of it (more than one where the subpath passes `p` again).
|
||||
fn places(&self, p: Point) -> Vec<f64> {
|
||||
use kurbo::{ParamCurve, ParamCurveArclen, ParamCurveNearest};
|
||||
let near = self.grid.get(&Self::cell_of(p, self.cell)).map(Vec::as_slice).unwrap_or_default();
|
||||
let mut out = vec![];
|
||||
for &k in near.iter().chain(&self.wide) {
|
||||
let Some(s) = self.segs.get(k) else { continue };
|
||||
let n = s.nearest(p, 1e-9);
|
||||
if n.distance_sq <= ON_SOURCE * ON_SOURCE {
|
||||
out.push(self.at.get(k).copied().unwrap_or(0.0) + s.subsegment(0.0..n.t).arclen(Self::ACCURACY));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The signed length from `a` to `b` along the subpath (the shorter way round a closed one).
|
||||
fn step(&self, a: f64, b: f64) -> f64 {
|
||||
let (d, len) = (b - a, self.len());
|
||||
if self.closed && len > 0.0 { d - len * (d / len).round() } else { d }
|
||||
}
|
||||
|
||||
/// Of `places`, the one nearest along the subpath to `target`.
|
||||
fn nearest(&self, places: &[f64], target: f64) -> Option<f64> {
|
||||
places.iter().copied().min_by(|x, y| self.step(*x, target).abs().total_cmp(&self.step(*y, target).abs()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Where edge `edge` runs along its source path, whose subpaths' tracks are `tracks`: the length
|
||||
/// along the source subpath to the edge's start, whether the edge starts at that subpath's start and
|
||||
/// ends at its end (an open subpath), and whether it runs the whole subpath. The middle of the
|
||||
/// edge's first segment places it, and its ends are taken where they lie that far along the source,
|
||||
/// so a path that passes a point twice is told apart. An edge that runs against the direction of its
|
||||
/// source is reversed first, and a closed edge as long as its closed source is started at the anchor
|
||||
/// where its source starts (one with no anchor there, or a shorter loop cut from a source that
|
||||
/// crosses itself, does not count as running the whole subpath). `None` when the edge is
|
||||
/// not a single piece found on the source.
|
||||
fn edge_run(tracks: &[Track], edge: &mut PathData) -> Option<(f64, bool, bool, bool)> {
|
||||
use kurbo::{ParamCurve, ParamCurveArclen};
|
||||
let [sp] = edge.subpaths.as_slice() else { return None };
|
||||
if sp.segment_count() == 0 {
|
||||
return None;
|
||||
}
|
||||
let (a, z) = (sp.anchors.first()?.p, if sp.closed { sp.anchors.first()?.p } else { sp.anchors.last()?.p });
|
||||
let first = sp.segment(0);
|
||||
let mid = first.eval(0.5);
|
||||
let half = first.subsegment(0.0..0.5).arclen(Track::ACCURACY);
|
||||
let length = sp.anchor_arc_positions().last().copied().unwrap_or(0.0);
|
||||
let edge_closed = sp.closed;
|
||||
// (how far off the fit is, track, start, end, runs forward) for the subpath that fits best.
|
||||
let mut found: Option<(f64, &Track, f64, f64, bool)> = None;
|
||||
for track in tracks {
|
||||
// The start lies half the first segment before its middle along the source, or after it
|
||||
// when the edge runs the other way: take the place and way that fit best.
|
||||
let starts_at = track.places(a);
|
||||
let mut best: Option<(f64, f64, bool)> = None;
|
||||
for pm in track.places(mid) {
|
||||
for forward in [true, false] {
|
||||
let Some(pa) = track.nearest(&starts_at, if forward { pm - half } else { pm + half }) else { continue };
|
||||
let miss = (if forward { track.step(pa, pm) } else { track.step(pm, pa) } - half).abs();
|
||||
if best.is_none_or(|(m, _, _)| miss < m) {
|
||||
best = Some((miss, pa, forward));
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some((miss, pa, forward)) = best else { continue };
|
||||
let target = if forward { pa + length } else { pa - length };
|
||||
let Some(pz) = track.nearest(&track.places(z), target) else { continue };
|
||||
let miss = miss + track.step(pz, target).abs();
|
||||
if found.is_none_or(|(m, ..)| miss < m) {
|
||||
found = Some((miss, track, pa, pz, forward));
|
||||
}
|
||||
}
|
||||
let (_, track, pa, pz, forward) = found?;
|
||||
let (from, to) = if forward { (pa, pz) } else { (pz, pa) };
|
||||
if !forward {
|
||||
edge.reverse();
|
||||
}
|
||||
let open = !track.closed;
|
||||
let starts = open && from <= ON_SOURCE;
|
||||
let ends = open && to >= track.len() - ON_SOURCE;
|
||||
if open {
|
||||
return Some((from, starts, ends, starts && ends));
|
||||
}
|
||||
// A closed edge runs the whole closed subpath, from the anchor the planar map starts it at.
|
||||
// Start it at the anchor where the source starts, so settings that follow the path begin there.
|
||||
let start = track.segs.first().map(|s| s.start())?;
|
||||
let moved = edge_closed
|
||||
&& (length - track.len()).abs() <= ON_SOURCE.max(track.len() * 1e-4)
|
||||
&& edge.subpaths.first_mut().is_some_and(|sp| match sp.anchors.iter().position(|a| a.p.distance(start) <= ON_SOURCE) {
|
||||
Some(k) => {
|
||||
sp.anchors.rotate_left(k);
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
});
|
||||
Some((if moved { 0.0 } else { from }, false, false, moved))
|
||||
}
|
||||
|
||||
/// Fit stroke row `row` of a source path to an edge cut from it, which runs as [`edge_run`] says
|
||||
/// (`None`: not known): its dashes go on from where the edge starts along the source, with the
|
||||
/// lengths set and without the fit of dashes aligned to corners and path ends, its arrowheads stay only at the source's own ends, and its width profile and brush, which spread
|
||||
/// over the whole path, stay only on an edge that runs the whole path.
|
||||
fn fit_to_edge(row: &mut AppearanceItem, run: Option<(f64, bool, bool, bool)>) {
|
||||
let AppearanceItem::Stroke(s) = row else { return };
|
||||
let (from, starts, ends, whole) = run.unwrap_or((0.0, false, false, false));
|
||||
if !whole {
|
||||
if let Some(d) = &mut s.dash
|
||||
&& run.is_some()
|
||||
{
|
||||
d.offset += from;
|
||||
d.align_corners = false;
|
||||
}
|
||||
s.profile = None;
|
||||
s.brush = None;
|
||||
}
|
||||
if !starts {
|
||||
s.start_arrow = None;
|
||||
}
|
||||
if !ends {
|
||||
s.end_arrow = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// The planar map's inputs from `sources` (paths and compound paths, back → front), with the
|
||||
/// fill, stroke and stroke width of each.
|
||||
fn source_shapes(sources: &[Arc<Node>]) -> (Vec<po::Shape>, Vec<(Paint, Paint, f64)>) {
|
||||
/// style of each.
|
||||
fn source_shapes(sources: &[Arc<Node>]) -> (Vec<po::Shape>, Vec<SourceStyle>) {
|
||||
let mut lv = vec![];
|
||||
for n in sources {
|
||||
b::leaf_shapes(n, &mut lv);
|
||||
}
|
||||
let mut shapes = vec![];
|
||||
let mut styles: Vec<(Paint, Paint, f64)> = vec![];
|
||||
let mut styles: Vec<SourceStyle> = vec![];
|
||||
for l in lv {
|
||||
if let Some((path, rule)) = b::node_outline(l)
|
||||
&& !path.is_empty()
|
||||
{
|
||||
shapes.push(po::Shape::new(path, rule, styles.len() as u64));
|
||||
let a = &l.appearance;
|
||||
styles.push((a.fill_paint(), a.stroke_paint(), a.stroke().map(|s| s.width).unwrap_or(1.0)));
|
||||
styles.push(SourceStyle::of(l));
|
||||
}
|
||||
}
|
||||
(shapes, styles)
|
||||
@@ -462,17 +714,35 @@ fn build_children(d: &mut Document, sources: Vec<Arc<Node>>, max_gap: Option<f64
|
||||
let nfaces = regs.len();
|
||||
for r in regs {
|
||||
let id = d.alloc_id();
|
||||
let fill = r.top().and_then(|t| styles.get(t)).map_or(Paint::None, |s| s.0.clone());
|
||||
let mut n = Node::path(id, r.path, fill_only(fill));
|
||||
let mut n = Node::path(id, r.path, fill_only(Paint::None));
|
||||
n.name = Some(FACE_NAME.into());
|
||||
// The front-most covering source with a fill that draws gives the face its fill rows.
|
||||
if let Some(s) = r.sources.iter().rev().filter_map(|&t| styles.get(t)).find(|s| !s.fills.is_empty()) {
|
||||
s.paint(&mut n, &s.fills);
|
||||
}
|
||||
children.push(Arc::new(n));
|
||||
}
|
||||
let nedges = edges.len();
|
||||
// The tracks of the sources whose edges need them, measured once each.
|
||||
let mut tracks: HashMap<usize, Vec<Track>> = HashMap::new();
|
||||
for e in edges {
|
||||
let Some((_, stroke, w)) = styles.get(e.key as usize) else { continue };
|
||||
let key = e.key as usize;
|
||||
let Some(s) = styles.get(key) else { continue };
|
||||
let mut path = e.path;
|
||||
let mut rows = s.strokes.clone();
|
||||
if rows.iter().any(depends_on_place) {
|
||||
let source = tracks
|
||||
.entry(key)
|
||||
.or_insert_with(|| shapes.get(key).map(|src| src.path.subpaths.iter().map(Track::new).collect()).unwrap_or_default());
|
||||
let run = edge_run(source, &mut path);
|
||||
for r in &mut rows {
|
||||
fit_to_edge(r, run);
|
||||
}
|
||||
}
|
||||
let id = d.alloc_id();
|
||||
let mut n = Node::path(id, e.path, stroke_only(stroke.clone(), *w));
|
||||
let mut n = Node::path(id, path, stroke_only(Paint::None, s.width));
|
||||
n.name = Some(EDGE_NAME.into());
|
||||
s.paint(&mut n, &rows);
|
||||
children.push(Arc::new(n));
|
||||
}
|
||||
Ok((children, nfaces, nedges))
|
||||
@@ -481,8 +751,9 @@ fn build_children(d: &mut Document, sources: Vec<Arc<Node>>, max_gap: Option<f64
|
||||
/// Give the faces and edges of `g`, a Live Paint group made again from the sources of `old`, the
|
||||
/// look of `old`'s face or edge where they lie: each face takes everything but the outline (its
|
||||
/// appearance, none included, its transparency and the rest) of the old face its inside point is
|
||||
/// in, and each edge that of the old edge its middle lies on. Faces and edges where `old` had none
|
||||
/// keep the paint of their sources.
|
||||
/// in, and each edge that of the old edge its middle lies on, with the old edge's stroke rows fitted
|
||||
/// to the part of it the new edge runs, as [`fit_to_edge`] fits a source's rows. Faces and edges
|
||||
/// where `old` had none keep the paint of their sources.
|
||||
fn repaint_from(g: &mut Node, old: &Node) {
|
||||
/// How far an edge's middle may be from the old edge it lies on.
|
||||
const ON_EDGE: f64 = 1e-3;
|
||||
@@ -505,7 +776,30 @@ fn repaint_from(g: &mut Node, old: &Node) {
|
||||
n.id = c.id;
|
||||
n.kind = c.kind.clone();
|
||||
n.bbox_angle = c.bbox_angle;
|
||||
// An edge cut from the old one takes the old edge's dashes, arrowheads, width profile
|
||||
// and brush as they fall on its part of the old edge.
|
||||
if c.name.as_deref() == Some(EDGE_NAME)
|
||||
&& let Some(old_path) = was.path_data()
|
||||
{
|
||||
fit_to_old_edge(&mut n, old_path);
|
||||
}
|
||||
*c = Arc::new(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Fit the stroke rows of edge `n`, which it took from an old edge whose outline is `old`, to the
|
||||
/// part of the old edge that `n` runs, as [`fit_to_edge`] fits a source's rows to an edge cut from
|
||||
/// it; `n` is reversed when it runs against the old edge.
|
||||
fn fit_to_old_edge(n: &mut Node, old: &PathData) {
|
||||
if !n.appearance.items.iter().any(depends_on_place) {
|
||||
return;
|
||||
}
|
||||
let tracks: Vec<Track> = old.subpaths.iter().map(Track::new).collect();
|
||||
let run = n.path_data_mut().and_then(|path| edge_run(&tracks, path));
|
||||
let mut a = (*n.appearance).clone();
|
||||
for r in &mut a.items {
|
||||
fit_to_edge(r, run);
|
||||
}
|
||||
n.appearance = a.into();
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use super::{
|
||||
Appearance, AppearanceItem, Arc, Beside, Document, EDGE_NAME, EngineError, FACE_NAME, GapOptions, GapSize, LIVE_PAINT_NAME, Node, NodeId,
|
||||
PathData, Point, Rect, Result, SOURCES_NAME, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite, ids_json,
|
||||
is_live_paint, json, number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids, source_nodes, source_shapes,
|
||||
switch_or,
|
||||
PathData, Point, Rect, Result, SOURCES_NAME, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite,
|
||||
fit_to_old_edge, ids_json, is_live_paint, json, number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids,
|
||||
source_nodes, source_shapes, switch_or,
|
||||
};
|
||||
|
||||
/// `options` as stored on a Live Paint group: none for the defaults.
|
||||
@@ -85,6 +85,9 @@ pub(super) fn lp_make(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "id": id.0, "faces": faces, "edges": edges }))
|
||||
}
|
||||
|
||||
/// How far, in points, the middle of an edge Merge makes may be from the old edge it lies on.
|
||||
const ON_OLD_EDGE: f64 = 1e-3;
|
||||
|
||||
/// What Merge carries from a face or edge to the part it makes again in its place, another path:
|
||||
/// the appearance, visibility, opacity and blending mode. Gradients fitted to the old outline keep
|
||||
/// that fit, and the strokes' pen pressure, tilt, bearing and rotation stay behind.
|
||||
@@ -125,18 +128,11 @@ fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result
|
||||
.ok_or_else(|| EngineError::Other("Live Paint Merge: select a Live Paint group and the paths to add".into()))?;
|
||||
check_live_paint_takes(d, roots)?;
|
||||
let old = d.node(target).cloned().ok_or(EngineError::NoNode(target))?;
|
||||
// Paint to carry over: (point inside face, paint) for faces that draw, and (point on edge,
|
||||
// paint) for every edge.
|
||||
// Paint to carry over: (point inside face, paint) for faces that draw; edges are matched to the
|
||||
// old edges below.
|
||||
let keep_faces: Vec<(Point, Carried)> =
|
||||
b::faces(&old).iter().filter(|f| draws(f)).filter_map(|f| Some((po::interior_point(f.path_data()?)?, Carried::of(f)))).collect();
|
||||
let keep_edges: Vec<(Point, Carried)> = b::edges(&old)
|
||||
.iter()
|
||||
.filter_map(|e| {
|
||||
let pd = e.path_data()?;
|
||||
let sp = pd.subpaths.first().filter(|sp| sp.segment_count() > 0)?;
|
||||
Some((kurbo::ParamCurve::eval(&sp.segment(0), 0.5), Carried::of(e)))
|
||||
})
|
||||
.collect();
|
||||
let old_parts = old.clone();
|
||||
let mut sources = source_nodes(&old);
|
||||
for r in roots {
|
||||
if *r != target {
|
||||
@@ -162,12 +158,24 @@ fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result
|
||||
carried.onto(Arc::make_mut(f));
|
||||
}
|
||||
}
|
||||
for (pt, carried) in keep_edges {
|
||||
if let Some(eid) = edge_near(&g, pt, 0.5).map(|e| e.id)
|
||||
&& let Some(ch) = g.children_mut()
|
||||
&& let Some(e) = ch.iter_mut().find(|c| c.id == eid)
|
||||
{
|
||||
carried.onto(Arc::make_mut(e));
|
||||
// Each edge whose middle lies on an old edge, every piece of an edge an added path cuts
|
||||
// included, takes the old edge's paint, with its rows fitted to its part of the old edge.
|
||||
if let Some(ch) = g.children_mut() {
|
||||
for c in ch.iter_mut().filter(|c| c.name.as_deref() == Some(EDGE_NAME)) {
|
||||
let Some(mid) = c
|
||||
.path_data()
|
||||
.and_then(|pd| pd.subpaths.first())
|
||||
.filter(|sp| sp.segment_count() > 0)
|
||||
.map(|sp| kurbo::ParamCurve::eval(&sp.segment(0), 0.5))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let Some(was) = edge_near(&old_parts, mid, ON_OLD_EDGE) else { continue };
|
||||
let e = Arc::make_mut(c);
|
||||
Carried::of(was).onto(e);
|
||||
if let Some(outline) = was.path_data() {
|
||||
fit_to_old_edge(e, outline);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut merged = Beside::replacing(d, roots);
|
||||
@@ -363,9 +371,52 @@ pub(super) fn lp_gap_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "ids": ids_json(&targets), "faces": faces, "gaps": gaps_json(&gaps), "closed": closed }))
|
||||
}
|
||||
|
||||
/// Which parts a Live Paint Bucket click paints besides the one under the pointer.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum LpScope {
|
||||
/// The part under the pointer alone (a click).
|
||||
One,
|
||||
/// A face and the faces reached from it across edges that draw no stroke ([`b::flood_faces`]),
|
||||
/// or an edge and the edges joined to it end to end that draw with the same stroke paint
|
||||
/// ([`b::connected_edges`], [`b::lp_stroke_paint`]) (a double-click).
|
||||
Connected,
|
||||
/// Every face with the same fill, or every edge that draws with the same stroke paint, in the
|
||||
/// group (a triple-click).
|
||||
SamePaint,
|
||||
}
|
||||
|
||||
/// The `scope` of `livePaint.fill` and `livePaint.strokeEdge`: `one` when left out or null.
|
||||
fn scope_param(p: &Value, c: &str) -> Result<LpScope> {
|
||||
match p.get("scope").filter(|v| !v.is_null()) {
|
||||
None => Ok(LpScope::One),
|
||||
Some(v) => match v.as_str() {
|
||||
Some("one") => Ok(LpScope::One),
|
||||
Some("connected") => Ok(LpScope::Connected),
|
||||
Some("samePaint") => Ok(LpScope::SamePaint),
|
||||
_ => Err(bad(c, "scope must be \"one\", \"connected\" or \"samePaint\"")),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The `match` of `livePaint.fill` and `livePaint.strokeEdge`: a paint as the document stores it,
|
||||
/// None when left out or null. With `allowed` false (a scope that compares no paints) a `match` is
|
||||
/// an error naming `scopes`, the scopes it applies to.
|
||||
fn match_param(p: &Value, c: &str, allowed: bool, scopes: &str) -> Result<Option<super::Paint>> {
|
||||
let Some(v) = p.get("match").filter(|v| !v.is_null()) else { return Ok(None) };
|
||||
if !allowed {
|
||||
return Err(bad(c, format!("match applies only with scope {scopes}")));
|
||||
}
|
||||
serde_json::from_value::<super::Paint>(v.clone()).map(Some).map_err(|_| bad(c, "match must be a paint as the document stores it"))
|
||||
}
|
||||
|
||||
pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "livePaint.fill";
|
||||
let pt = point_param(p, "point").filter(|q| finite(*q)).ok_or_else(|| bad(C, "missing point [x,y]"))?;
|
||||
let scope = scope_param(p, C)?;
|
||||
let like = match_param(p, C, scope == LpScope::SamePaint, "\"samePaint\"")?;
|
||||
if scope != LpScope::One && p.get("points").is_some() {
|
||||
return Err(bad(C, "scope applies to a click: leave out points"));
|
||||
}
|
||||
let parse_chunk = |input: &Value, start: Point| -> Result<Vec<Point>> {
|
||||
let values = input
|
||||
.as_array()
|
||||
@@ -400,7 +451,8 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let group = object_param(p, "group", C)?;
|
||||
let roots = if group.is_none() { root_ids(s, p)? } else { vec![] };
|
||||
// The faces the click or drag paints in Live Paint group `gid`: the visible face at the point,
|
||||
// and every visible face the drag crosses; → (the face at the point, the faces).
|
||||
// the faces its scope adds, and every visible face the drag crosses; → (the face at the point,
|
||||
// the faces).
|
||||
let targets_in = |d: &Document, gid: NodeId| -> Result<(NodeId, std::collections::BTreeSet<NodeId>)> {
|
||||
let fid = d
|
||||
.node(gid)
|
||||
@@ -408,6 +460,18 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.map(|f| f.id)
|
||||
.ok_or_else(|| EngineError::Other("no Live Paint face at that point".into()))?;
|
||||
let mut targets = std::collections::BTreeSet::from([fid]);
|
||||
if scope != LpScope::One {
|
||||
let n = d.node(gid).ok_or(EngineError::NoNode(gid))?;
|
||||
if scope == LpScope::Connected {
|
||||
targets.extend(b::flood_faces(n, fid));
|
||||
} else {
|
||||
let like = match &like {
|
||||
Some(m) => m.clone(),
|
||||
None => d.node(fid).ok_or(EngineError::NoNode(fid))?.appearance.fill_paint(),
|
||||
};
|
||||
targets.extend(b::faces(n).into_iter().filter(|f| f.visible && f.appearance.fill_paint() == like).map(|f| f.id));
|
||||
}
|
||||
}
|
||||
if let Some(points) = points {
|
||||
let n = d.node(gid).ok_or(EngineError::NoNode(gid))?;
|
||||
// Use the existing region-crossing probes, so even a face narrower than the distance
|
||||
@@ -457,34 +521,36 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
};
|
||||
let (g, face) = match live {
|
||||
let (g, face, count) = match live {
|
||||
Some(gid) => {
|
||||
let (fid, targets) = targets_in(&s.doc()?.doc, gid)?;
|
||||
let count = targets.len();
|
||||
// Faces that already have the paint stay as they are: when every face has it, nothing
|
||||
// changes and no undo step is recorded.
|
||||
let d = &s.doc()?.doc;
|
||||
let unpainted: Vec<NodeId> = targets.into_iter().filter(|t| d.node(*t).is_none_or(|f| f.appearance.fill_paint() != paint)).collect();
|
||||
if unpainted.is_empty() {
|
||||
return Ok(json!({ "group": gid.0, "face": fid.0 }));
|
||||
return Ok(json!({ "group": gid.0, "face": fid.0, "count": count }));
|
||||
}
|
||||
s.edit("Live Paint Bucket", |d, _| {
|
||||
for target in unpainted {
|
||||
d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance.set_fill(paint.clone());
|
||||
}
|
||||
Ok((gid, fid))
|
||||
Ok((gid, fid, count))
|
||||
})?
|
||||
}
|
||||
None => s.edit("Live Paint Bucket", |d, sel| {
|
||||
let gid = make_live(d, sel, &roots)?.0;
|
||||
let (fid, targets) = targets_in(d, gid)?;
|
||||
let count = targets.len();
|
||||
for target in targets {
|
||||
d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance.set_fill(paint.clone());
|
||||
}
|
||||
Ok((gid, fid))
|
||||
Ok((gid, fid, count))
|
||||
})?,
|
||||
};
|
||||
s.remember_paint(&paint);
|
||||
Ok(json!({ "group": g.0, "face": face.0 }))
|
||||
Ok(json!({ "group": g.0, "face": face.0, "count": count }))
|
||||
}
|
||||
|
||||
pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -498,31 +564,72 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "width out of range"));
|
||||
}
|
||||
let tol = number_or(p, "tolerance", 4.0, C)?.clamp(0.0, 1000.0);
|
||||
let (eid, unchanged) = {
|
||||
let scope = scope_param(p, C)?;
|
||||
let like = match_param(p, C, scope != LpScope::One, "\"connected\" or \"samePaint\"")?;
|
||||
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")))?;
|
||||
let e = b::visible_edge_near(n, pt, tol).ok_or_else(|| EngineError::Other("no Live Paint edge near that point".into()))?;
|
||||
// An edge that already has the paint and the width (or has no stroke and gets none) stays as
|
||||
// it is, and no undo step is recorded.
|
||||
let unchanged = match e.appearance.stroke() {
|
||||
Some(st) => st.paint == paint && st.width == width,
|
||||
None => paint.is_none(),
|
||||
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));
|
||||
let targets = match scope {
|
||||
LpScope::One => vec![eid],
|
||||
LpScope::Connected => b::connected_edges(n, eid, &like),
|
||||
LpScope::SamePaint => std::iter::once(eid)
|
||||
.chain(b::edges(n).into_iter().filter(|e| e.visible && e.id != eid && b::lp_stroke_paint(e) == like).map(|e| e.id))
|
||||
.collect(),
|
||||
};
|
||||
(e.id, unchanged)
|
||||
let count = targets.len();
|
||||
// An edge whose shown stroke already has the paint and the width (or that has no shown stroke
|
||||
// and gets none) stays as it is; when every edge does, nothing changes and no undo step is
|
||||
// recorded.
|
||||
let changed: Vec<NodeId> = targets
|
||||
.into_iter()
|
||||
.filter(|t| {
|
||||
d.node(*t).is_none_or(|e| match shown_stroke(e) {
|
||||
Some(st) => !(st.paint == paint && st.width == width),
|
||||
None => !paint.is_none(),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
(eid, count, changed)
|
||||
};
|
||||
if unchanged {
|
||||
return Ok(json!({ "group": g.0, "edge": eid.0 }));
|
||||
if changed.is_empty() {
|
||||
return Ok(json!({ "group": g.0, "edge": eid.0, "count": count }));
|
||||
}
|
||||
let edge = s.edit("Live Paint Bucket", |d, _| {
|
||||
let e = d.node_mut(eid).ok_or(EngineError::NoNode(eid))?;
|
||||
e.appearance.set_stroke(paint.clone());
|
||||
if let Some(st) = e.appearance.stroke_mut() {
|
||||
st.width = width;
|
||||
s.edit("Live Paint Bucket", |d, _| {
|
||||
for target in &changed {
|
||||
let e = d.node_mut(*target).ok_or(EngineError::NoNode(*target))?;
|
||||
match shown_stroke_mut(e) {
|
||||
Some(st) => {
|
||||
st.paint = paint.clone();
|
||||
st.width = width;
|
||||
}
|
||||
None => e.appearance.items.push(super::AppearanceItem::Stroke(super::StrokeLayer::new(paint.clone(), width))),
|
||||
}
|
||||
}
|
||||
Ok(eid)
|
||||
Ok(())
|
||||
})?;
|
||||
s.remember_paint(&paint);
|
||||
Ok(json!({ "group": g.0, "edge": edge.0 }))
|
||||
Ok(json!({ "group": g.0, "edge": eid.0, "count": count }))
|
||||
}
|
||||
|
||||
/// The stroke `livePaint.strokeEdge` paints on Live Paint edge `e`: its topmost stroke that is
|
||||
/// shown. None when it has no stroke or every stroke is hidden; the command then adds a stroke
|
||||
/// above the others.
|
||||
fn shown_stroke(e: &Node) -> Option<&super::StrokeLayer> {
|
||||
e.appearance.items.iter().rev().find_map(|i| match i {
|
||||
super::AppearanceItem::Stroke(s) if s.visible => Some(s),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// [`shown_stroke`], to change.
|
||||
fn shown_stroke_mut(e: &mut Node) -> Option<&mut super::StrokeLayer> {
|
||||
e.appearance.items.iter_mut().rev().find_map(|i| match i {
|
||||
super::AppearanceItem::Stroke(s) if s.visible => Some(s),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Every fill and stroke row of face or edge `n`, bottom first, as `livePaint.info` lists them. A
|
||||
|
||||
@@ -288,9 +288,10 @@ fn trace_library(c: &str, s: &Session, params: &mut tr::TraceParams) -> Result<V
|
||||
/// The most anchor points an Image Trace may make, a guard for memory: a trace past it is refused
|
||||
/// with advice instead (#525). A trace keeps about 90 bytes an anchor in the document (measured on
|
||||
/// code-drawn photos of 2000 × 2000 to 6000 × 4000 pixels), so 8,000,000 anchors are about
|
||||
/// 0.7 GB, with a peak of about 1 GB while tracing: a 4000 × 3000 photo at High Fidelity Photo
|
||||
/// makes about 1.9 million, and even at Paths 100, Noise 1 and every tone about 7.9 million. On the
|
||||
/// web, where a page has at most 4 GB of memory, the limit stays at 2,000,000.
|
||||
/// 0.7 GB, with a peak of about 1 GB while tracing: a 4000 × 3000 photo at Limited 64 colors,
|
||||
/// Paths 90, Corners 25 and Noise 4 makes about 1.9 million, and even at Paths 100, Noise 1 and
|
||||
/// every tone about 7.9 million. On the web, where a page has at most 4 GB of memory, the limit
|
||||
/// stays at 2,000,000.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub const MAX_TRACE_ANCHORS: usize = 8_000_000;
|
||||
|
||||
@@ -1139,7 +1140,7 @@ mod trace_limit_tests {
|
||||
assert_eq!(w, ["Flat Logo traced the image at 946 × 710 pixels, averaged down from 16000 × 12000."]);
|
||||
}
|
||||
|
||||
// A 4000 × 3000 photo at High Fidelity Photo makes about 1.9 million anchors, which must fit;
|
||||
// the limit still guards memory (about 90 bytes an anchor). Checked when the tests build.
|
||||
// A 4000 × 3000 photo at Limited 64 colors, Paths 90, Corners 25 and Noise 4 makes about
|
||||
// 1.9 million anchors, which must fit; the limit still guards memory (about 90 bytes an anchor). Checked when the tests build.
|
||||
const _: () = assert!(MAX_TRACE_ANCHORS >= 2_000_000 && MAX_TRACE_ANCHORS <= 16_000_000);
|
||||
}
|
||||
|
||||
@@ -104,9 +104,14 @@ fn plane_param(g: &PerspectiveGrid, p: &Value, cmd: &str) -> Result<Plane> {
|
||||
Ok(plane)
|
||||
}
|
||||
|
||||
/// The objects a perspective command acts on: the outermost of `ids` (each once, in the order first
|
||||
/// given), else the selection's roots.
|
||||
pub(super) fn roots(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
match named_ids(p)? {
|
||||
Some(v) => Ok(outermost(&s.doc()?.doc, v)),
|
||||
Some(v) => {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
Ok(outermost(&s.doc()?.doc, v.into_iter().filter(|id| seen.insert(*id)).collect()))
|
||||
}
|
||||
None => selected_roots(s),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -427,6 +427,7 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
super::params::check_effect_color(C, id, ¶ms)?;
|
||||
super::params::check_effect_channel(C, id, ¶ms)?;
|
||||
super::params::check_effect_center(C, id, ¶ms)?;
|
||||
// Crop Marks take their style from the preferences when applied.
|
||||
if id == effects::CROP_MARKS && params.get("style").is_none() {
|
||||
params["style"] = json!(s.crop_mark_style().id());
|
||||
@@ -718,7 +719,7 @@ fn lighting_preset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// sets its Warp style (`warpStyle`), its 3D type (`threeDType`) or visibility (`visible`), as one
|
||||
/// undo step. They are checked as `effect.apply` checks them, and a visible 3D effect must still
|
||||
/// fit; a hidden one has its given values checked. → `{ids}`.
|
||||
fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "effect.setParams";
|
||||
let index = index_param(p, "index", C)?;
|
||||
let mut params = p.get("params").cloned().unwrap_or(Value::Null);
|
||||
@@ -740,6 +741,7 @@ fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for effect in &edited {
|
||||
super::params::check_effect_color(C, effect, ¶ms)?;
|
||||
super::params::check_effect_channel(C, effect, ¶ms)?;
|
||||
super::params::check_effect_center(C, effect, ¶ms)?;
|
||||
}
|
||||
if edited.iter().any(|e| texture_load_effect(e)) {
|
||||
load_texture(&mut params, C)?;
|
||||
@@ -833,11 +835,13 @@ fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const GLASS: &str = "distort.glass";
|
||||
/// Effect › Texture › Texturizer.
|
||||
const TEXTURIZER: &str = "texture.texturizer";
|
||||
/// Effect › Artistic › Rough Pastels.
|
||||
const ROUGH_PASTELS: &str = "artistic.roughPastels";
|
||||
|
||||
/// Does effect `id` have Load Texture: a `textureImage` that `effect.apply` reads from an image
|
||||
/// file (Glass, Texturizer)?
|
||||
/// file (Glass, Texturizer, Rough Pastels)?
|
||||
pub(crate) fn texture_load_effect(id: &str) -> bool {
|
||||
id == GLASS || id == TEXTURIZER
|
||||
id == GLASS || id == TEXTURIZER || id == ROUGH_PASTELS
|
||||
}
|
||||
|
||||
/// Glass's `textureImage` in `params` as Glass stores it: an image file (`{path}`, or `{name?,
|
||||
|
||||
@@ -1016,3 +1016,69 @@ fn a_3d_shadow_is_one_undo_step_saved_exported_and_expanded() {
|
||||
});
|
||||
assert_eq!(shadows, 1);
|
||||
}
|
||||
|
||||
/// Radial Blur's Blur Center: stored as given, drawn about that point of the object's bounds, and
|
||||
/// a value outside 0 to 1 (or not a number) is refused with nothing changed and no undo step.
|
||||
#[test]
|
||||
fn radial_blur_center_is_stored_drawn_and_checked() {
|
||||
let (mut s, id) = session_with_rect();
|
||||
let draw = |s: &Session| {
|
||||
vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()).pixels
|
||||
};
|
||||
s.execute("effect.apply", &json!({"effect": "blur.radial", "params": {"amount": 40}})).unwrap();
|
||||
assert_eq!(node(&s, id).appearance.effects[0].params["centerX"], json!(0.5), "the default center is stored");
|
||||
let middle = draw(&s);
|
||||
s.execute("effect.setParams", &json!({"index": 0, "params": {"centerX": 0.5, "centerY": 0.5}})).unwrap();
|
||||
assert_eq!(draw(&s), middle, "the default center draws as before");
|
||||
s.execute("effect.setParams", &json!({"index": 0, "params": {"centerX": 0, "centerY": 1}})).unwrap();
|
||||
let params = node(&s, id).appearance.effects[0].params.clone();
|
||||
assert_eq!((params["centerX"].clone(), params["centerY"].clone()), (json!(0), json!(1)));
|
||||
let corner = draw(&s);
|
||||
assert_ne!(corner, middle, "the blur turns about the bottom-left corner");
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
for (cmd, params) in [
|
||||
("effect.setParams", json!({"index": 0, "params": {"centerX": 1.5}})),
|
||||
("effect.setParams", json!({"index": 0, "params": {"centerY": -0.01}})),
|
||||
("effect.setParams", json!({"index": 0, "params": {"centerX": "0.5"}})),
|
||||
("effect.apply", json!({"effect": "blur.radial", "params": {"centerY": 2}})),
|
||||
] {
|
||||
let e = s.execute(cmd, ¶ms).unwrap_err().to_string();
|
||||
assert!(e.contains("must be a number"), "{cmd} {params}: {e}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{cmd} {params}");
|
||||
assert_eq!(node(&s, id).appearance.effects.len(), 1, "{cmd} {params}");
|
||||
assert_eq!(draw(&s), corner, "{cmd} {params}");
|
||||
}
|
||||
// A replayed journal is checked too: the refusal is the command's own.
|
||||
let e = s.replay("effect.setParams", &json!({"index": 0, "params": {"centerX": 7}})).unwrap_err().to_string();
|
||||
assert!(e.contains("`centerX` must be a number from 0 to 1"), "{e}");
|
||||
// Moving the object moves the blur with it.
|
||||
s.execute("object.move", &json!({"ids": [id.0], "dx": 40, "dy": 20})).unwrap();
|
||||
let moved = draw(&s);
|
||||
let at = |px: &[u8], x: usize, y: usize| px[(y * 300 + x) * 4..][..4].to_vec();
|
||||
for (x, y) in [(95, 150), (150, 205), (205, 95), (120, 120)] {
|
||||
assert_eq!(at(&moved, x + 40, y + 20), at(&corner, x, y), "({x}, {y})");
|
||||
}
|
||||
}
|
||||
|
||||
/// A Rasterize with transparent room around the art, before another Rasterize, splits the stack,
|
||||
/// and the part after the split paints around content the room spreads. The Blur Center still
|
||||
/// lies in the object's own bounds, so the blur draws as it does without the room.
|
||||
#[test]
|
||||
fn radial_blur_center_stays_in_the_object_when_the_stack_splits() {
|
||||
let draw = |room: bool| {
|
||||
let (mut s, _) = session_with_rect();
|
||||
let mut stack = vec![("rasterize", json!({})), ("blur.radial", json!({"amount": 60, "centerX": 0, "centerY": 0}))];
|
||||
if room {
|
||||
stack.insert(0, ("rasterize", json!({"addAround": 40})));
|
||||
}
|
||||
for (effect, params) in stack {
|
||||
s.execute("effect.apply", &json!({"effect": effect, "params": params})).unwrap();
|
||||
}
|
||||
vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()).pixels
|
||||
};
|
||||
let (plain, split) = (draw(false), draw(true));
|
||||
let alpha = |px: &[u8]| px.iter().skip(3).step_by(4).map(|a| u64::from(*a)).sum::<u64>();
|
||||
assert!(alpha(&plain) > 0, "the blurred art draws");
|
||||
let differ = (0..300 * 300).filter(|i| plain[i * 4 + 3].abs_diff(split[i * 4 + 3]) > 8).count();
|
||||
assert!(differ < 50, "{differ} pixels' coverage moved with the room around the art");
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ pub mod jxlread;
|
||||
mod legacy_ai;
|
||||
mod load;
|
||||
mod mesh3d;
|
||||
pub(crate) use load::{MAX_RASTER_ALLOC, size_note};
|
||||
pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, size_note};
|
||||
mod heifread;
|
||||
mod hpgl;
|
||||
mod jp2read;
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
//! (unknown keys are ignored, so one params object can carry the options of several formats).
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashSet;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde_json::Value;
|
||||
use vectorcraft_doc::{Artboard, Document, Node, NodeKind};
|
||||
use vectorcraft_doc::{Artboard, Document, Node, NodeKind, SymbolOverride};
|
||||
use vectorcraft_geom::Rect;
|
||||
use vectorcraft_render::AntiAlias;
|
||||
use vectorcraft_render::encode::jpeg::{self, JpegOptions};
|
||||
@@ -450,31 +450,85 @@ pub fn export_art_bounds(doc: &Document, format: &str) -> Option<Rect> {
|
||||
/// The bounds of the visible art of `doc` with the objects that `left_out` picks hidden
|
||||
/// ([`hidden_nodes`]) and the ones in the art of the symbols that instances show taken out
|
||||
/// ([`without_nodes`]: symbol art is measured with its hidden objects). An instance of a symbol
|
||||
/// whose art is all picked or hidden is hidden too. The art of a dynamic symbol is measured whole:
|
||||
/// an instance can paint its objects, and finds them by their places in the art.
|
||||
/// whose art is all picked or hidden is hidden too. The drawn instances of a dynamic symbol that
|
||||
/// make the same appearance changes to its art are measured on a copy of the symbol of their own,
|
||||
/// in which each object is judged with those changes ([`as_drawn`]); the objects taken out of
|
||||
/// a dynamic symbol's art leave empty groups in their places, by which instances find the objects
|
||||
/// they change.
|
||||
fn bounds_without(doc: &Document, left_out: &dyn Fn(&Node) -> bool) -> Option<Rect> {
|
||||
// The symbols instances show (the first of each name) that aren't dynamic.
|
||||
// The symbols instances show (the first of each name).
|
||||
let mut names = HashSet::new();
|
||||
let shown: Vec<(usize, &vectorcraft_doc::Symbol)> =
|
||||
doc.symbols.iter().enumerate().filter(|(_, s)| names.insert(s.name.as_str())).filter(|(_, s)| !s.dynamic).collect();
|
||||
let shown: Vec<usize> = doc.symbols.iter().enumerate().filter(|(_, s)| names.insert(s.name.as_str())).map(|(i, _)| i).collect();
|
||||
// The sets of appearance changes the drawn instances of each dynamic symbol make to its art;
|
||||
// `None` for a symbol with more than `MAX_ART_COPIES`, which is measured whole.
|
||||
let mut sets: HashMap<&str, Option<Vec<Vec<&SymbolOverride>>>> =
|
||||
shown.iter().filter_map(|i| doc.symbols.get(*i)).filter(|s| s.dynamic).map(|s| (s.name.as_str(), Some(Vec::new()))).collect();
|
||||
if !sets.is_empty() {
|
||||
let mut walked = HashSet::new();
|
||||
for l in &doc.layers {
|
||||
drawn_changes(doc, l, left_out, true, &mut walked, &mut sets);
|
||||
}
|
||||
}
|
||||
// Each set of changes gets a copy of its symbol, appended after the symbols, which the instances
|
||||
// that make those changes show instead.
|
||||
let variant = |symbol: &str, n: &Node| -> Option<String> {
|
||||
let k = sets.get(symbol)?.as_ref()?.iter().position(|c| *c == own_changes(n))?;
|
||||
Some(format!("{symbol}\u{0}{k}"))
|
||||
};
|
||||
let mut copies: Vec<(usize, &[&SymbolOverride])> = Vec::new();
|
||||
let remapped_doc = sets.values().flatten().any(|v| !v.is_empty()).then(|| {
|
||||
let mut d = doc.clone();
|
||||
for l in &mut d.layers {
|
||||
if let Some(n) = remapped(l, &variant) {
|
||||
*l = n;
|
||||
}
|
||||
}
|
||||
for s in &mut d.symbols {
|
||||
if let Some(n) = remapped(&s.art, &variant) {
|
||||
s.art = n;
|
||||
}
|
||||
}
|
||||
for i in &shown {
|
||||
let Some(s) = d.symbols.get(*i).cloned() else { continue };
|
||||
for (k, c) in sets.get(s.name.as_str()).into_iter().flatten().flatten().enumerate() {
|
||||
copies.push((d.symbols.len(), c.as_slice()));
|
||||
d.symbols.push(vectorcraft_doc::Symbol { name: format!("{}\u{0}{k}", s.name), ..s.clone() });
|
||||
}
|
||||
}
|
||||
d
|
||||
});
|
||||
let src = remapped_doc.as_ref().unwrap_or(doc);
|
||||
// The symbols to measure with the changes their instances make (`None` for a static symbol),
|
||||
// without the dynamic symbols measured whole.
|
||||
let entries: Vec<(usize, Option<&[&SymbolOverride]>)> = shown
|
||||
.iter()
|
||||
.filter_map(|i| src.symbols.get(*i).map(|s| (*i, s)))
|
||||
.filter(|(_, s)| !s.dynamic || sets.get(s.name.as_str()).is_some_and(Option::is_some))
|
||||
.map(|(i, s)| (i, s.dynamic.then_some(&[][..])))
|
||||
.chain(copies.iter().map(|(i, c)| (*i, Some(*c))))
|
||||
.collect();
|
||||
// The symbols whose art `left_out` leaves nothing of, those that only hold instances of such
|
||||
// symbols included.
|
||||
let mut empty: HashSet<&str> = HashSet::new();
|
||||
while let Some((_, s)) = shown.iter().find(|(_, s)| !empty.contains(s.name.as_str()) && all_left_out(&s.art, left_out, &empty)) {
|
||||
while let Some(s) = entries.iter().find_map(|(i, c)| {
|
||||
src.symbols.get(*i).filter(|s| !empty.contains(s.name.as_str()) && all_left_out(&s.art, left_out, &empty, *c, &mut Vec::new()))
|
||||
}) {
|
||||
empty.insert(&s.name);
|
||||
}
|
||||
let left_out =
|
||||
&|n: &Node| left_out(n) || matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if empty.contains(symbol.as_str()) && !has_effects(n));
|
||||
let layers = hidden_nodes(&doc.layers, left_out);
|
||||
let symbols: Vec<(usize, Arc<Node>)> = shown
|
||||
let layers = hidden_nodes(&src.layers, left_out);
|
||||
let symbols: Vec<(usize, Arc<Node>)> = entries
|
||||
.iter()
|
||||
.filter(|(_, s)| !empty.contains(s.name.as_str()))
|
||||
.filter_map(|(i, s)| without_nodes(&s.art, left_out).map(|art| (*i, art)))
|
||||
.filter_map(|(i, c)| {
|
||||
let s = src.symbols.get(*i).filter(|s| !empty.contains(s.name.as_str()))?;
|
||||
without_nodes(&s.art, left_out, *c, &mut Vec::new()).map(|art| (*i, art))
|
||||
})
|
||||
.collect();
|
||||
if layers.is_none() && symbols.is_empty() {
|
||||
return vectorcraft_render::encode::art_bounds(doc);
|
||||
return vectorcraft_render::encode::art_bounds(src);
|
||||
}
|
||||
let mut d = doc.clone();
|
||||
let mut d = remapped_doc.unwrap_or_else(|| doc.clone());
|
||||
if let Some(layers) = layers {
|
||||
d.layers = layers;
|
||||
}
|
||||
@@ -486,22 +540,126 @@ fn bounds_without(doc: &Document, left_out: &dyn Fn(&Node) -> bool) -> Option<Re
|
||||
vectorcraft_render::encode::art_bounds(&d)
|
||||
}
|
||||
|
||||
/// The appearance changes instance `n` makes to its symbol's art, without those that change nothing.
|
||||
fn own_changes(n: &Node) -> Vec<&SymbolOverride> {
|
||||
n.extras().symbol_overrides.iter().filter(|o| !o.is_empty()).collect()
|
||||
}
|
||||
|
||||
/// `n` with each instance at any depth that `variant` gives another symbol (from the instance's
|
||||
/// symbol and the instance) made an instance of that symbol; `None` when none is.
|
||||
fn remapped(n: &Arc<Node>, variant: &dyn Fn(&str, &Node) -> Option<String>) -> Option<Arc<Node>> {
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind {
|
||||
let name = variant(symbol, n)?;
|
||||
let mut m = (**n).clone();
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &mut m.kind {
|
||||
*symbol = name;
|
||||
}
|
||||
return Some(Arc::new(m));
|
||||
}
|
||||
let children = n.children()?;
|
||||
let mut out: Option<Vec<Arc<Node>>> = None;
|
||||
for (i, c) in children.iter().enumerate() {
|
||||
if let Some(new) = remapped(c, variant)
|
||||
&& let Some(slot) = out.get_or_insert_with(|| children.clone()).get_mut(i)
|
||||
{
|
||||
*slot = new;
|
||||
}
|
||||
}
|
||||
out.map(|c| {
|
||||
let mut m = (**n).clone();
|
||||
if let Some(children) = m.children_mut() {
|
||||
*children = c;
|
||||
}
|
||||
Arc::new(m)
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `n` is hidden, picked by `left_out`, an instance of one of the `empty` symbols, or a
|
||||
/// layer or a group holding only such objects (its clipping path among them when it clips). A
|
||||
/// Shaper group, or a layer, group or instance with effects, fills or strokes of its own, is none
|
||||
/// of these unless it is hidden or picked.
|
||||
fn all_left_out(n: &Node, left_out: &dyn Fn(&Node) -> bool, empty: &HashSet<&str>) -> bool {
|
||||
/// of these unless it is hidden or picked. In the art of a dynamic symbol (`changed`, the changes
|
||||
/// an instance makes to it; `n` is at place `at`), each object is judged with those changes
|
||||
/// ([`as_drawn`]).
|
||||
fn all_left_out(n: &Node, left_out: &dyn Fn(&Node) -> bool, empty: &HashSet<&str>, changed: Option<&[&SymbolOverride]>, at: &mut Vec<u32>) -> bool {
|
||||
let m = as_drawn(n, changed, at);
|
||||
!n.visible
|
||||
|| left_out(n)
|
||||
|| !has_effects(n)
|
||||
|| left_out(&m)
|
||||
|| !has_effects(&m)
|
||||
&& n.extras().shaper.is_none()
|
||||
&& match &n.kind {
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().all(|c| all_left_out(c, left_out, empty)),
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().enumerate().all(|(i, c)| {
|
||||
at.push(i as u32);
|
||||
let out = all_left_out(c, left_out, empty, changed, at);
|
||||
at.pop();
|
||||
out
|
||||
}),
|
||||
NodeKind::SymbolInstance { symbol, .. } => empty.contains(symbol.as_str()),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Add the sets of appearance changes that the instances in `n` and its subtree make to the art of
|
||||
/// the symbols `sets` names, each set once, and those of the instances in the art of the symbols the
|
||||
/// instances show (`walked`, the symbols already looked in). The instances that `left_out` picks or
|
||||
/// that are in an object it picks are left out, and with `hidden` (in a layer) the hidden ones and
|
||||
/// those in a hidden object. A symbol with more than [`MAX_ART_COPIES`] sets gets `None`.
|
||||
fn drawn_changes<'a>(
|
||||
doc: &'a Document,
|
||||
n: &'a Node,
|
||||
left_out: &dyn Fn(&Node) -> bool,
|
||||
hidden: bool,
|
||||
walked: &mut HashSet<&'a str>,
|
||||
sets: &mut HashMap<&'a str, Option<Vec<Vec<&'a SymbolOverride>>>>,
|
||||
) {
|
||||
if hidden && !n.visible || left_out(n) {
|
||||
return;
|
||||
}
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind {
|
||||
let changes = own_changes(n);
|
||||
if let Some(entry) = sets.get_mut(symbol.as_str())
|
||||
&& !changes.is_empty()
|
||||
{
|
||||
let full = match entry {
|
||||
Some(list) if !list.contains(&changes) && list.len() < MAX_ART_COPIES => {
|
||||
list.push(changes);
|
||||
false
|
||||
}
|
||||
Some(list) => !list.contains(&changes),
|
||||
None => false,
|
||||
};
|
||||
if full {
|
||||
*entry = None;
|
||||
}
|
||||
}
|
||||
if walked.insert(symbol.as_str())
|
||||
&& let Some(s) = doc.symbols.iter().find(|s| s.name == *symbol)
|
||||
{
|
||||
drawn_changes(doc, &s.art, left_out, false, walked, sets);
|
||||
}
|
||||
}
|
||||
for c in n.children().into_iter().flatten() {
|
||||
drawn_changes(doc, c, left_out, hidden, walked, sets);
|
||||
}
|
||||
}
|
||||
|
||||
/// The most copies of one dynamic symbol's art [`bounds_without`] measures, one for each set of
|
||||
/// appearance changes its instances make; a symbol whose instances make more sets is measured whole.
|
||||
const MAX_ART_COPIES: usize = 64;
|
||||
|
||||
/// `n`, the object at place `at` of a symbol's art, with the appearance changes `changed` that an
|
||||
/// instance makes to it applied in their order; `n` itself for the art of a symbol that is not
|
||||
/// dynamic (`changed` is `None`) and when no change names `at`.
|
||||
fn as_drawn<'a>(n: &'a Node, changed: Option<&[&SymbolOverride]>, at: &[u32]) -> Cow<'a, Node> {
|
||||
let here: Vec<SymbolOverride> =
|
||||
changed.into_iter().flatten().filter(|o| o.path == at).map(|o| SymbolOverride { path: Vec::new(), ..(*o).clone() }).collect();
|
||||
if here.is_empty() {
|
||||
return Cow::Borrowed(n);
|
||||
}
|
||||
let mut m = n.clone();
|
||||
vectorcraft_doc::symbol_overrides::apply(&mut m, &here);
|
||||
Cow::Owned(m)
|
||||
}
|
||||
|
||||
/// Whether `n` has a visible effect, fill or stroke of its own, which the objects it holds can
|
||||
/// take part in.
|
||||
fn has_effects(n: &Node) -> bool {
|
||||
@@ -511,25 +669,32 @@ fn has_effects(n: &Node) -> bool {
|
||||
/// `n` without the objects that `left_out` picks in it, when it is a layer or a group, and in the
|
||||
/// layers and groups in it at any depth; `None` when it picks none of them. A clipping layer or
|
||||
/// group keeps its clipping path, its first object, and a Shaper group and a layer or group with
|
||||
/// effects, fills or strokes of its own keep all they hold.
|
||||
fn without_nodes(n: &Arc<Node>, left_out: &dyn Fn(&Node) -> bool) -> Option<Arc<Node>> {
|
||||
/// effects, fills or strokes of its own keep all they hold. In the art of a dynamic symbol
|
||||
/// (`changed`, the changes an instance makes to it, as for [`all_left_out`]; `n` is at place
|
||||
/// `at`), each object is judged with those changes ([`as_drawn`]), and an object taken out leaves
|
||||
/// an empty group in its place.
|
||||
fn without_nodes(n: &Arc<Node>, left_out: &dyn Fn(&Node) -> bool, changed: Option<&[&SymbolOverride]>, at: &mut Vec<u32>) -> Option<Arc<Node>> {
|
||||
let (NodeKind::Layer { children, clip, .. } | NodeKind::Group { children, clip }) = &n.kind else { return None };
|
||||
if has_effects(n) || n.extras().shaper.is_some() {
|
||||
if has_effects(&as_drawn(n, changed, at)) || n.extras().shaper.is_some() {
|
||||
return None;
|
||||
}
|
||||
let mut changed = false;
|
||||
let mut taken = false;
|
||||
let kept: Vec<Arc<Node>> = children
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, c)| {
|
||||
if left_out(c) && !(*clip && i == 0) {
|
||||
changed = true;
|
||||
return None;
|
||||
}
|
||||
Some(without_nodes(c, left_out).inspect(|_| changed = true).unwrap_or_else(|| c.clone()))
|
||||
at.push(i as u32);
|
||||
let out = if left_out(&as_drawn(c, changed, at)) && !(*clip && i == 0) {
|
||||
taken = true;
|
||||
changed.map(|_| Arc::new(Node::group(c.id, Vec::new())))
|
||||
} else {
|
||||
Some(without_nodes(c, left_out, changed, at).inspect(|_| taken = true).unwrap_or_else(|| c.clone()))
|
||||
};
|
||||
at.pop();
|
||||
out
|
||||
})
|
||||
.collect();
|
||||
changed.then(|| {
|
||||
taken.then(|| {
|
||||
let mut new = (**n).clone();
|
||||
if let NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } = &mut new.kind {
|
||||
*children = kept;
|
||||
|
||||
@@ -864,7 +864,9 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option<String> {
|
||||
/// they are, with their ink amounts ([`ImageBlob::cmyk`]), except that ones storing one plane per
|
||||
/// ink are written again with their inks together ([`vectorcraft_doc::cmyk::stored_cmyk_tiff`]);
|
||||
/// CMYK TIFFs with an alpha channel, which the decoder can't read, become RGBA in the active color
|
||||
/// settings' CMYK, as do CMYK Photoshop documents, whose merged image is read ([`psdread`]).
|
||||
/// settings' CMYK, whichever of their extra channels is the alpha
|
||||
/// ([`vectorcraft_doc::cmyk::extra_samples_tiff_rgba`]), as do CMYK Photoshop documents, whose
|
||||
/// merged image is read ([`psdread`]).
|
||||
/// 1-bit TIFFs compressed with CCITT Group 3, which the decoder can't read either, become RGBA
|
||||
/// too ([`vectorcraft_doc::cmyk::group3_tiff_rgba`]).
|
||||
/// Grayscale TIFFs with an alpha channel or other extra channels, which the decoder can't read
|
||||
@@ -1072,16 +1074,32 @@ pub(super) fn raster_doc(name: &str, bytes: &[u8]) -> Result<Document> {
|
||||
let layer = d.layers[0].id;
|
||||
let id = d.alloc_id();
|
||||
let xf = Affine::scale_non_uniform(sx, sy);
|
||||
let mut n = Node::new(
|
||||
let n = Node::new(
|
||||
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));
|
||||
n.name = Some(name.to_string());
|
||||
d.images.insert(key, blob);
|
||||
d.insert(Some(layer), 0, n).map_err(err)?;
|
||||
Ok(d)
|
||||
}
|
||||
|
||||
/// Image `image` of `d` clipped by `clip`, the clipping path its file names in the image's pixel
|
||||
/// space (a PSD or PSB file's, [`psdread::clipping_path`]): a clip group of that path (even-odd,
|
||||
/// with no paint) and the image. Without one the image stays as it is.
|
||||
pub(crate) fn file_clipped(d: &mut Document, image: Node, clip: Option<vectorcraft_geom::PathData>) -> Node {
|
||||
let (Some(mut path), NodeKind::Image(im)) = (clip, &image.kind) else { return image };
|
||||
path.transform(im.xf);
|
||||
let none = vectorcraft_color::Paint::None;
|
||||
let mut clip = Node::path(d.alloc_id(), path, vectorcraft_doc::Appearance::basic(none.clone(), none, 0.0));
|
||||
if let NodeKind::Path { clipping, rule, .. } = &mut clip.kind {
|
||||
*clipping = true;
|
||||
*rule = vectorcraft_geom::FillRule::EvenOdd;
|
||||
}
|
||||
Node::new(d.alloc_id(), NodeKind::Group { children: vec![std::sync::Arc::new(clip), std::sync::Arc::new(image)], clip: true })
|
||||
}
|
||||
|
||||
/// Does this import note say that the file has something the document doesn't?
|
||||
fn is_loss(note: &str) -> bool {
|
||||
note == vectorcraft_pdf::OFF_ARTBOARD_NOTE || vectorcraft_eps::is_loss(note)
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
//! File › Place (#918): the merged image, the flattened picture every PSD carries after its layers,
|
||||
//! as a linked PSD shows. Written from Adobe's public "Photoshop File Formats Specification"
|
||||
//! (<https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/>). File › Open reads the
|
||||
//! layers with [`super::psdlayers`], which shares this reader.
|
||||
//! layers with [`super::psdlayers`], which shares this reader. The clipping path a document names
|
||||
//! ([`clipping_path`]) clips its merged image where it opens or is placed.
|
||||
//!
|
||||
//! Every mode Photoshop saves a merged image in is read: Bitmap, Grayscale, Duotone (as its
|
||||
//! grayscale data), Indexed, RGB, CMYK and Lab, at 1, 8, 16 and 32 bits per channel, stored raw,
|
||||
@@ -14,6 +15,7 @@
|
||||
use std::io::Read;
|
||||
|
||||
use vectorcraft_color::cms::{Lab, lab::lab_to_srgb};
|
||||
use vectorcraft_geom::{Anchor, AnchorKind, PathData, Point, SubPath};
|
||||
|
||||
/// Photoshop's colour modes (the header's numbers), as far as the merged image is concerned.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -154,30 +156,113 @@ pub(super) fn header<'a>(r: &mut Reader<'a>) -> Result<Header<'a>, String> {
|
||||
pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> {
|
||||
let mut r = Reader::new(bytes);
|
||||
let h = header(&mut r).ok()?;
|
||||
let mut r = Reader::new(h.resources);
|
||||
while !r.rest().is_empty() {
|
||||
r.take(4).ok()?;
|
||||
let (_, _, data) = resources(h.resources, false).find(|(id, _, _)| *id == 0x03ed)?;
|
||||
let mut d = Reader::new(data);
|
||||
// Fixed 16.16 values, each with its unit (1: per inch, 2: per centimetre) and the unit the
|
||||
// size is shown in.
|
||||
let mut axis = || -> Option<f64> {
|
||||
let v = f64::from(d.u32().ok()?) / 65536.0;
|
||||
let unit = d.u16().ok()?;
|
||||
d.u16().ok()?;
|
||||
Some(if unit == 2 { v * 2.54 } else { v })
|
||||
};
|
||||
Some((axis()?, axis()?))
|
||||
}
|
||||
|
||||
/// The image resource blocks of `resources`, in file order: each one's id, name (the bytes of its
|
||||
/// Pascal string) and data. Stops at the first block that is cut short. With `signed`, only the
|
||||
/// blocks whose signature is `8BIM` are given.
|
||||
fn resources(resources: &[u8], signed: bool) -> impl Iterator<Item = (u16, &[u8], &[u8])> {
|
||||
let mut r = Reader::new(resources);
|
||||
std::iter::from_fn(move || {
|
||||
if r.rest().is_empty() {
|
||||
return None;
|
||||
}
|
||||
let ours = r.take(4).ok()? == b"8BIM";
|
||||
let id = r.u16().ok()?;
|
||||
// A Pascal string padded to an even size, length byte included.
|
||||
let name = usize::from(r.u8().ok()?);
|
||||
r.take(name + (name + 1) % 2).ok()?;
|
||||
let len = usize::from(r.u8().ok()?);
|
||||
let name = r.take(len).ok()?;
|
||||
r.take((len + 1) % 2).ok()?;
|
||||
let size = usize::try_from(r.u32().ok()?).ok()?;
|
||||
let data = r.take(size).ok()?;
|
||||
r.take(size % 2).ok()?;
|
||||
if id == 0x03ed {
|
||||
let mut d = Reader::new(data);
|
||||
// Fixed 16.16 values, each with its unit (1: per inch, 2: per centimetre) and the
|
||||
// unit the size is shown in.
|
||||
let mut axis = || -> Option<f64> {
|
||||
let v = f64::from(d.u32().ok()?) / 65536.0;
|
||||
let unit = d.u16().ok()?;
|
||||
d.u16().ok()?;
|
||||
Some(if unit == 2 { v * 2.54 } else { v })
|
||||
};
|
||||
return Some((axis()?, axis()?));
|
||||
Some((ours, id, name, data))
|
||||
})
|
||||
.filter(move |(ours, ..)| *ours || !signed)
|
||||
.map(|(_, id, name, data)| (id, name, data))
|
||||
}
|
||||
|
||||
/// The resource naming the document's clipping path.
|
||||
const CLIPPING_PATH_NAME: u16 = 2999;
|
||||
|
||||
/// The saved paths' resource ids.
|
||||
const SAVED_PATHS: std::ops::RangeInclusive<u16> = 2000..=2997;
|
||||
|
||||
/// The clipping path a PSD or PSB file names, in its pixel space (x across its width, y down
|
||||
/// its height): the saved path (resources 2000 to 2997) whose name the clipping path resource
|
||||
/// (2999) gives, both `8BIM` resources. `None` when the document names none, names a path it doesn't have, or that path
|
||||
/// has no anchors or more records than [`vectorcraft_geom::path::MAX_READ_ANCHORS`]. Saved paths
|
||||
/// use the even-odd rule. A path whose initial fill record says the fill starts with all pixels
|
||||
/// begins with a subpath around the whole image, so its subpaths cut holes in it.
|
||||
pub fn clipping_path(bytes: &[u8]) -> Option<PathData> {
|
||||
let mut r = Reader::new(bytes);
|
||||
let h = header(&mut r).ok()?;
|
||||
let (_, _, named) = resources(h.resources, true).find(|(id, _, _)| *id == CLIPPING_PATH_NAME)?;
|
||||
// A Pascal string, then the flatness and a fill rule, which the specification says is ignored.
|
||||
let len = usize::from(*named.first()?);
|
||||
let name = named.get(1..1 + len)?;
|
||||
let (_, _, data) = resources(h.resources, true).find(|(id, n, _)| SAVED_PATHS.contains(id) && *n == name)?;
|
||||
// A path of more records than a document may hold anchors is left out before it is built.
|
||||
if data.len() / PATH_RECORD > vectorcraft_geom::path::MAX_READ_ANCHORS {
|
||||
return None;
|
||||
}
|
||||
let path = saved_path(data, f64::from(h.width), f64::from(h.height));
|
||||
(!path.is_empty()).then_some(path)
|
||||
}
|
||||
|
||||
/// One record of a saved path: a selector, then 24 bytes.
|
||||
const PATH_RECORD: usize = 26;
|
||||
|
||||
/// The saved path of path records `data`, scaled to an image `width` × `height` pixels. Knot
|
||||
/// records come after their subpath's length record; one that comes before any, or past the knots
|
||||
/// a length record counts, is left out, as is a last record cut short.
|
||||
fn saved_path(data: &[u8], width: f64, height: f64) -> PathData {
|
||||
// A path point: a vertical, then a horizontal signed 8.24 fixed-point fraction of the image's
|
||||
// height and width.
|
||||
let fixed = |b: [u8; 4]| f64::from(i32::from_be_bytes(b)) / f64::from(1 << 24);
|
||||
let point = |[v0, v1, v2, v3, h0, h1, h2, h3]: [u8; 8]| Point::new(fixed([h0, h1, h2, h3]) * width, fixed([v0, v1, v2, v3]) * height);
|
||||
let mut subpaths: Vec<SubPath> = vec![];
|
||||
let mut all_pixels = false;
|
||||
// The knots the current subpath still takes.
|
||||
let mut left = 0usize;
|
||||
let (records, _) = data.as_chunks::<PATH_RECORD>();
|
||||
for &[s0, s1, ref body @ ..] in records {
|
||||
let [c0, c1, ..] = *body;
|
||||
let (points, _) = body.as_chunks::<8>();
|
||||
let [a, b, c] = [0, 1, 2].map(|i| points.get(i).copied().map_or(Point::ZERO, point));
|
||||
match u16::from_be_bytes([s0, s1]) {
|
||||
sel @ (0 | 3) => {
|
||||
left = usize::from(u16::from_be_bytes([c0, c1]));
|
||||
// Anchors are added as knots come: a count can claim more than follow.
|
||||
subpaths.push(SubPath::new(vec![], sel == 0));
|
||||
}
|
||||
sel @ (1 | 2 | 4 | 5) if left > 0 => {
|
||||
let Some(sp) = subpaths.last_mut() else { continue };
|
||||
left -= 1;
|
||||
let kind = if matches!(sel, 1 | 4) { AnchorKind::Smooth } else { AnchorKind::Corner };
|
||||
sp.anchors.push(Anchor { h_in: a, p: b, h_out: c, kind });
|
||||
}
|
||||
8 => all_pixels = [c0, c1] == [0, 1],
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
None
|
||||
subpaths.retain(|s| !s.anchors.is_empty());
|
||||
if all_pixels && !subpaths.is_empty() {
|
||||
let all = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, width, height));
|
||||
subpaths.splice(0..0, all.subpaths);
|
||||
}
|
||||
PathData::new(subpaths)
|
||||
}
|
||||
|
||||
/// Does the merged image keep its transparency in the first extra channel? Yes when the layer
|
||||
|
||||
@@ -202,6 +202,41 @@ fn a_16_bit_cmyk_tiff_with_alpha_places_at_16_bits() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A CMYK or grayscale TIFF whose alpha follows another extra sample opens and places with that
|
||||
/// alpha, at 8 and 16 bits, chunky and planar; a CMYK one is not kept as inks. A CMYK one with two
|
||||
/// more samples than its ExtraSamples values count does too.
|
||||
#[test]
|
||||
fn a_tiff_with_alpha_after_another_extra_sample_places_with_its_alpha() {
|
||||
let none = vec![0u16; 6];
|
||||
let full = vec![255u16; 6];
|
||||
let other = vec![9u16, 8, 7, 6, 5, 4];
|
||||
let alpha = vec![255u16, 128, 0, 255, 64, 1];
|
||||
let inks = [full.clone(), none.clone(), none.clone(), none.clone()];
|
||||
let cases = [
|
||||
("CMYK", 5, vec![full.clone(), none.clone(), none.clone(), none.clone(), other.clone(), alpha.clone()]),
|
||||
("CMYK, two more samples", 5, [&inks[..], &[other.clone(), alpha.clone(), other.clone(), full.clone()]].concat()),
|
||||
("gray", 1, vec![full.clone(), other.clone(), alpha.clone()]),
|
||||
];
|
||||
for (what, photometric, channels) in cases {
|
||||
for bits in [8, 16] {
|
||||
let wide: Vec<Vec<u16>> = channels.iter().map(|ch| ch.iter().map(|v| if bits == 16 { v * 257 } else { *v }).collect()).collect();
|
||||
for planar in [false, true] {
|
||||
let what = format!("{what}, {bits} bits, planar {planar}");
|
||||
let file = hand_tiff(photometric, bits, &[0, 2], planar, &wide);
|
||||
let (inks, rgba) = kept(&what, &file);
|
||||
assert_eq!(inks, None, "{what}: shown as RGB with its alpha");
|
||||
let alphas: Vec<u8> = rgba.iter().skip(3).step_by(4).copied().collect();
|
||||
assert_eq!(alphas, [255, 128, 0, 255, 64, 1], "{what}: the alpha is the second extra sample");
|
||||
let mut s = session(100.0, 100.0, 1);
|
||||
s.execute("file.place", &json!({"name": "a.tif", "dataBase64": vectorcraft_format::base64_encode(&file)})).unwrap();
|
||||
let blob = &s.doc().unwrap().doc.images[&image_of(&s).key];
|
||||
let placed = image::load_from_memory(&blob.bytes).unwrap().to_rgba8().into_raw();
|
||||
assert_eq!(placed, rgba, "{what}: Place reads it as Open does");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A planar TIFF whose header claims more strips than the decoder can count (here 2^31 + 1 rows
|
||||
/// a strip each, times 5 planes) is refused as too large to draw, without a panic.
|
||||
#[test]
|
||||
|
||||
@@ -254,6 +254,90 @@ fn a_plot_of_the_arts_bounds_leaves_out_images_in_symbol_art() {
|
||||
}
|
||||
}
|
||||
|
||||
/// In the art of a dynamic symbol a placed image and a path that paints nothing are left out as
|
||||
/// well, until an instance paints the path, and a document whose only other visible art is an
|
||||
/// instance of a dynamic symbol of an image is refused.
|
||||
#[test]
|
||||
fn a_plot_of_the_arts_bounds_leaves_out_images_in_dynamic_symbol_art() {
|
||||
let mut s = two_boards();
|
||||
let plot = |s: &mut Session| s.execute("document.export", &json!({"format": "hpgl", "useArtboards": false})).map(|v| bytes(&v));
|
||||
let bounds = |s: &Session| super::export_art_bounds(&s.doc().unwrap().doc, "hpgl").unwrap();
|
||||
let same = |a: vectorcraft_geom::Rect, b: vectorcraft_geom::Rect| {
|
||||
[(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(a, b)| (a - b).abs() < 1e-6)
|
||||
};
|
||||
let printing = s.doc().unwrap().doc.layers[0].id;
|
||||
s.execute("layer.new", &json!({})).unwrap();
|
||||
let mut png = vec![];
|
||||
image::DynamicImage::new_rgb8(4, 4).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
let image = s.execute("file.place", &json!({"name": "far.png", "dataBase64": b64(&png), "at": [-600, 800]})).unwrap()["ids"][0].clone();
|
||||
let square = s.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 20, "height": 20})).unwrap()["id"].clone();
|
||||
let bare = s.execute("shape.rectangle", &json!({"x": 500, "y": -400, "width": 20, "height": 20})).unwrap()["id"].clone();
|
||||
s.execute("paint.setStroke", &json!({"ids": [bare], "none": true})).unwrap();
|
||||
let before = bounds(&s);
|
||||
let inst = s.execute("symbol.new", &json!({"name": "Mixed", "ids": [image, square, bare], "type": "dynamic"})).unwrap()["id"].clone();
|
||||
let after = bounds(&s);
|
||||
assert!(same(before, after), "{before:?} {after:?}");
|
||||
|
||||
// A change of the path's blending mode leaves it painting nothing; once the instance paints the
|
||||
// path, the path is measured.
|
||||
let art = s.doc().unwrap().doc.symbols[0].art.clone();
|
||||
let x0 = |c: &std::sync::Arc<vectorcraft_doc::Node>| c.visual_bounds().map_or(f64::MIN, |b| b.x0);
|
||||
let at = (0..art.children().unwrap().len()).max_by(|a, b| x0(&art.children().unwrap()[*a]).total_cmp(&x0(&art.children().unwrap()[*b]))).unwrap();
|
||||
s.execute("symbol.instance.setAppearance", &json!({"id": inst, "path": [at], "blend": "multiply"})).unwrap();
|
||||
let blended = bounds(&s);
|
||||
assert!(same(before, blended), "{before:?} {blended:?}");
|
||||
s.execute("symbol.instance.setAppearance", &json!({"id": inst, "path": [at], "stroke": "#000000"})).unwrap();
|
||||
let painted = bounds(&s);
|
||||
assert!(painted.x1 > 500.0 && painted.y0 < -390.0, "{painted:?}");
|
||||
// A later change to the same object, as a file can hold, takes the paint off again.
|
||||
{
|
||||
let id = vectorcraft_doc::NodeId(inst.as_u64().unwrap());
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let n = d.node_mut(id).unwrap();
|
||||
let mut overrides = n.extras().symbol_overrides.clone();
|
||||
overrides.push(vectorcraft_doc::SymbolOverride { path: vec![at as u32], opacity: Some(0.0), ..Default::default() });
|
||||
n.extras_mut().symbol_overrides = overrides.clone();
|
||||
let taken_off = bounds(&s);
|
||||
assert!(same(before, taken_off), "{before:?} {taken_off:?}");
|
||||
overrides.pop();
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
d.node_mut(id).unwrap().extras_mut().symbol_overrides = overrides;
|
||||
}
|
||||
// Another instance, far above, that doesn't paint the path is measured without it, whether or
|
||||
// not the first one paints it.
|
||||
let other = s.execute("symbol.place", &json!({"name": "Mixed", "x": 0, "y": -5000})).unwrap()["id"].clone();
|
||||
let with_paint = bounds(&s);
|
||||
s.execute("symbol.instance.reset", &json!({"ids": [inst]})).unwrap();
|
||||
let without_paint = bounds(&s);
|
||||
assert!((with_paint.y0 - without_paint.y0).abs() < 1e-6, "{with_paint:?} {without_paint:?}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let undone = bounds(&s);
|
||||
assert!(same(undone, with_paint), "{undone:?} {with_paint:?}");
|
||||
s.execute("select.set", &json!({"ids": [other]})).unwrap();
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
|
||||
s.execute("select.set", &json!({"ids": [inst]})).unwrap();
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
s.execute("layer.setProps", &json!({"id": printing, "visible": false})).unwrap();
|
||||
let image = s.execute("file.place", &json!({"name": "far.png", "dataBase64": b64(&png), "at": [-600, 800]})).unwrap()["ids"][0].clone();
|
||||
s.execute("symbol.new", &json!({"name": "Image", "ids": [image], "type": "dynamic"})).unwrap();
|
||||
let e = plot(&mut s).unwrap_err().to_string();
|
||||
assert!(e.contains("no visible art"), "{e}");
|
||||
|
||||
// An instance that brings a group at 0% opacity back to full opacity still draws nothing when
|
||||
// the group holds only an image.
|
||||
let image = s.execute("file.place", &json!({"name": "far.png", "dataBase64": b64(&png), "at": [-600, 800]})).unwrap()["ids"][0].clone();
|
||||
let group = s.execute("object.group", &json!({"ids": [image]})).unwrap()["id"].clone();
|
||||
s.execute("transparency.set", &json!({"ids": [group], "opacity": 0})).unwrap();
|
||||
let inst = s.execute("symbol.new", &json!({"name": "Clear", "ids": [group], "type": "dynamic"})).unwrap()["id"].clone();
|
||||
let id = vectorcraft_doc::NodeId(inst.as_u64().unwrap());
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
d.node_mut(id).unwrap().extras_mut().symbol_overrides =
|
||||
[vec![], vec![0]].into_iter().map(|path| vectorcraft_doc::SymbolOverride { path, opacity: Some(1.0), ..Default::default() }).collect();
|
||||
let e = plot(&mut s).unwrap_err().to_string();
|
||||
assert!(e.contains("no visible art"), "{e}");
|
||||
}
|
||||
|
||||
/// A placed image with a Vector Halftone effect is measured when the effect makes dots, and left
|
||||
/// out when it would take more cells than the effect makes.
|
||||
#[test]
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
//! Reading Photoshop documents (#918): the merged image of every colour mode, depth and
|
||||
//! compression, PSB files, transparency, the resolution, and damaged files refused without a panic.
|
||||
//! compression, PSB files, transparency, the resolution, the clipping path, and damaged files
|
||||
//! refused without a panic.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, NodeId, NodeKind};
|
||||
|
||||
use super::psdread::{decode, is_psd, resolution};
|
||||
use super::psdread::{clipping_path, decode, is_psd, resolution};
|
||||
use super::*;
|
||||
|
||||
/// A Photoshop document built from its parts: `version` 1 (PSD) or 2 (PSB), the header's fields,
|
||||
@@ -260,6 +262,199 @@ fn pdd_files_open_and_place() {
|
||||
assert!(format_for_name("x.pdd").is_none() && writable_format(None, Some("x.pdd")).is_err(), "an export to .pdd is refused as before");
|
||||
}
|
||||
|
||||
/// An image resource block: `8BIM`, `id`, `name` as a Pascal string padded to an even size, then
|
||||
/// `data` padded to an even size.
|
||||
fn resource(id: u16, name: &[u8], data: &[u8]) -> Vec<u8> {
|
||||
let mut r = b"8BIM".to_vec();
|
||||
r.extend(id.to_be_bytes());
|
||||
r.push(name.len() as u8);
|
||||
r.extend(name);
|
||||
if name.len().is_multiple_of(2) {
|
||||
r.push(0);
|
||||
}
|
||||
r.extend((data.len() as u32).to_be_bytes());
|
||||
r.extend(data);
|
||||
if !data.len().is_multiple_of(2) {
|
||||
r.push(0);
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
/// A path point record's 8 bytes: `[x, y]` as fractions of the image's width and height, stored
|
||||
/// vertical first as signed 8.24 fixed-point numbers.
|
||||
fn point([x, y]: [f64; 2]) -> Vec<u8> {
|
||||
[y, x].iter().flat_map(|v| ((v * f64::from(1 << 24)).round() as i32).to_be_bytes()).collect()
|
||||
}
|
||||
|
||||
/// A saved path's records: the fill rule record, an initial fill record saying whether the fill
|
||||
/// starts with all pixels, then each subpath (closed or not) of corner knots without handles.
|
||||
fn saved_path(all_pixels: bool, subpaths: &[(bool, &[[f64; 2]])]) -> Vec<u8> {
|
||||
let record = |selector: u16, body: Vec<u8>| {
|
||||
let mut r = selector.to_be_bytes().to_vec();
|
||||
r.extend(body);
|
||||
r.resize(26, 0);
|
||||
r
|
||||
};
|
||||
let mut d = record(6, vec![]);
|
||||
d.extend(record(8, vec![0, u8::from(all_pixels)]));
|
||||
for (closed, knots) in subpaths {
|
||||
d.extend(record(if *closed { 0 } else { 3 }, (knots.len() as u16).to_be_bytes().to_vec()));
|
||||
for k in *knots {
|
||||
d.extend(record(if *closed { 2 } else { 5 }, [point(*k), point(*k), point(*k)].concat()));
|
||||
}
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
/// The clipping path resource (2999) naming the saved path `name`, with a flatness of 0 and the
|
||||
/// fill rule left as it is.
|
||||
fn clipping_name(name: &[u8]) -> Vec<u8> {
|
||||
let mut d = vec![name.len() as u8];
|
||||
d.extend(name);
|
||||
d.extend([0; 6]);
|
||||
resource(2999, b"", &d)
|
||||
}
|
||||
|
||||
/// A 100 × 50 pixel red RGB document with `resources`, flat or with a layer count of 0.
|
||||
fn red_psd(resources: &[u8]) -> Vec<u8> {
|
||||
psd(1, 3, (100, 50), 8, 3, &[], resources, &[], &raw(&[&[255; 5000], &[0; 5000], &[0; 5000]]))
|
||||
}
|
||||
|
||||
/// The triangle saved as "Outline", another path saved as "Other", and the clipping path naming
|
||||
/// "Outline".
|
||||
fn triangle_resources() -> Vec<u8> {
|
||||
let other = saved_path(false, &[(true, &[[0.0, 0.0], [0.1, 0.0], [0.1, 0.1]])]);
|
||||
let outline = saved_path(false, &[(true, &[[0.5, 0.0], [1.0, 1.0], [0.0, 1.0]])]);
|
||||
[resource(2000, b"Other", &other), resource(2001, b"Outline", &outline), clipping_name(b"Outline")].concat()
|
||||
}
|
||||
|
||||
/// The clip group a PSD file comes in as: its clipping path's anchors (pt), whether that path
|
||||
/// uses the even-odd rule, and the image it clips.
|
||||
fn clip_group(d: &Document, id: NodeId) -> (Vec<[f64; 2]>, bool, NodeId) {
|
||||
let Some(NodeKind::Group { children, clip: true }) = d.node(id).map(|n| &n.kind) else { panic!("not a clip group: {:?}", d.node(id)) };
|
||||
let [path, image] = &children[..] else { panic!("{} children", children.len()) };
|
||||
let NodeKind::Path { path: p, rule, clipping: true, .. } = &path.kind else { panic!("not a clipping path") };
|
||||
assert!(matches!(image.kind, NodeKind::Image(_)));
|
||||
let anchors = p.anchors().map(|(_, _, a)| [a.p.x, a.p.y]).collect();
|
||||
(anchors, *rule == vectorcraft_geom::FillRule::EvenOdd, image.id)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_clipping_path_clips_the_merged_image_on_place_and_open() {
|
||||
let f = red_psd(&triangle_resources());
|
||||
let triangle = vec![[50.0, 0.0], [100.0, 50.0], [0.0, 50.0]];
|
||||
let data = vectorcraft_format::base64_encode(&f);
|
||||
// Place: one clip group of the named path, not the other, at 100 % (72 ppi: a pixel a point).
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
|
||||
let r = s.execute("file.place", &json!({"name": "cut.psd", "dataBase64": data, "at": [50, 25]})).unwrap();
|
||||
let id = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
let (anchors, even_odd, image) = clip_group(&s.doc().unwrap().doc, id);
|
||||
assert_eq!((anchors, even_odd), (triangle.clone(), true));
|
||||
assert_eq!(r["image"], image.0, "{r}");
|
||||
assert_eq!((r["width"].as_f64(), r["height"].as_f64()), (Some(100.0), Some(50.0)));
|
||||
// Open with layers off, and a flat file opened with layers on, as its merged image.
|
||||
for params in [json!({"layers": false}), json!({})] {
|
||||
s.execute("document.open", &merge(json!({"name": "cut.psd", "dataBase64": data}), params.clone())).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let top = d.layers[0].children().unwrap();
|
||||
assert_eq!(top.len(), 1, "{params}");
|
||||
assert_eq!(top[0].name.as_deref(), Some("cut.psd"), "{params}");
|
||||
let group = top[0].id;
|
||||
let (anchors, even_odd, _) = clip_group(d, group);
|
||||
assert_eq!((anchors, even_odd), (triangle.clone(), true), "{params}");
|
||||
// The corner outside the triangle draws nothing; its middle draws red.
|
||||
let png = image::load_from_memory(&exported(&mut s, json!({"format": "png"}))).unwrap().to_rgba8();
|
||||
assert_eq!((png.get_pixel(2, 2).0[3], png.get_pixel(50, 40).0), (0, [255, 0, 0, 255]), "{params}");
|
||||
// The clipping path is an ordinary path: releasing the clipping mask leaves the image whole.
|
||||
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
|
||||
s.execute("object.clippingMask.release", &json!({})).unwrap();
|
||||
let png = image::load_from_memory(&exported(&mut s, json!({"format": "png"}))).unwrap().to_rgba8();
|
||||
assert_eq!(png.get_pixel(2, 2).0, [255, 0, 0, 255], "{params}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace keeps a clipped PSD file's scale, as it keeps an image's.
|
||||
#[test]
|
||||
fn replacing_a_clipped_psd_keeps_its_scale() {
|
||||
let data = vectorcraft_format::base64_encode(&red_psd(&triangle_resources()));
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
s.execute("file.place", &json!({"name": "cut.psd", "dataBase64": data, "at": [200, 200]})).unwrap();
|
||||
s.execute("object.scale", &json!({"sx": 200, "sy": 200})).unwrap();
|
||||
let r = s.execute("file.place", &json!({"name": "cut.psd", "dataBase64": data, "replace": true})).unwrap();
|
||||
assert_eq!((r["width"].as_f64(), r["height"].as_f64()), (Some(200.0), Some(100.0)), "{r}");
|
||||
let (anchors, _, _) = clip_group(&s.doc().unwrap().doc, NodeId(r["ids"][0].as_u64().unwrap()));
|
||||
assert_eq!(anchors, [[200.0, 150.0], [300.0, 250.0], [100.0, 250.0]]);
|
||||
// Other art replacing the clip group takes its centre only, as before.
|
||||
let plain = vectorcraft_format::base64_encode(&red_psd(&[]));
|
||||
let r = s.execute("file.place", &json!({"name": "plain.psd", "dataBase64": plain, "replace": true})).unwrap();
|
||||
assert_eq!((r["width"].as_f64(), r["height"].as_f64()), (Some(100.0), Some(50.0)), "{r}");
|
||||
}
|
||||
|
||||
#[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]])]);
|
||||
let f = red_psd(&[resource(2000, b"Hole", &hole), clipping_name(b"Hole")].concat());
|
||||
let path = clipping_path(&f).unwrap();
|
||||
let starts: Vec<_> = path.subpaths.iter().map(|s| (s.anchors[0].p.x, s.anchors[0].p.y, s.closed)).collect();
|
||||
assert_eq!(starts, [(0.0, 0.0, true), (25.0, 12.5, true)], "the image's edges, then the hole");
|
||||
let mut s = Session::new();
|
||||
s.execute("document.open", &json!({"name": "hole.psd", "dataBase64": vectorcraft_format::base64_encode(&f), "layers": false})).unwrap();
|
||||
let png = image::load_from_memory(&exported(&mut s, json!({"format": "png"}))).unwrap().to_rgba8();
|
||||
assert_eq!((png.get_pixel(2, 2).0, png.get_pixel(50, 25).0[3]), ([255, 0, 0, 255], 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_naming_no_clipping_path_or_a_missing_one_place_a_plain_image() {
|
||||
let other = saved_path(false, &[(true, &[[0.0, 0.0], [1.0, 0.0], [1.0, 1.0]])]);
|
||||
let empty = saved_path(false, &[]);
|
||||
for (resources, what) in [
|
||||
(resource(2000, b"Other", &other), "saved paths, none named"),
|
||||
([resource(2000, b"Other", &other), clipping_name(b"Gone")].concat(), "a name no path has"),
|
||||
([resource(2000, b"Empty", &empty), clipping_name(b"Empty")].concat(), "a path with no knots"),
|
||||
([resource(3000, b"Other", &other), clipping_name(b"Other")].concat(), "a resource outside the saved paths"),
|
||||
([resource(2000, b"Other", &other), [&b"MeSa"[..], &clipping_name(b"Other")[4..]].concat()].concat(), "a block not signed 8BIM"),
|
||||
(vec![], "no resources"),
|
||||
] {
|
||||
let f = red_psd(&resources);
|
||||
assert!(clipping_path(&f).is_none(), "{what}");
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let r = s.execute("file.place", &json!({"name": "a.psd", "dataBase64": vectorcraft_format::base64_encode(&f)})).unwrap();
|
||||
let id = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
assert!(matches!(s.doc().unwrap().doc.node(id).map(|n| &n.kind), Some(NodeKind::Image(_))), "{what}");
|
||||
assert!(r.get("image").is_none(), "{what}: {r}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn damaged_clipping_paths_are_read_without_a_panic() {
|
||||
let good = red_psd(&triangle_resources());
|
||||
assert!(clipping_path(&good).is_some());
|
||||
// The header, the empty colour mode data, then the resources' length and the resources.
|
||||
let start = 26 + 4;
|
||||
let end = start + 4 + triangle_resources().len();
|
||||
for n in 0..end + 2 {
|
||||
let _ = clipping_path(&good[..n]);
|
||||
}
|
||||
for i in start..end {
|
||||
for v in [0, 1, 0x7f, 0x80, 0xff] {
|
||||
let mut f = good.clone();
|
||||
f[i] = v;
|
||||
let _ = clipping_path(&f);
|
||||
}
|
||||
}
|
||||
// Knots before any length record, and more knots than a length record counts, are left out.
|
||||
let mut extra = saved_path(false, &[(true, &[[0.0, 0.0], [1.0, 0.0], [1.0, 1.0]])]);
|
||||
extra[26 * 2 + 3] = 2;
|
||||
let mut stray = 2u16.to_be_bytes().to_vec();
|
||||
stray.resize(26, 0);
|
||||
extra.splice(26..26, stray);
|
||||
let path = clipping_path(&red_psd(&[resource(2000, b"P", &extra), clipping_name(b"P")].concat())).unwrap();
|
||||
assert_eq!(path.subpaths.iter().map(|s| s.anchors.len()).collect::<Vec<_>>(), [2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn damaged_and_unsupported_files_are_refused_without_a_panic() {
|
||||
let good = psd(2, 4, (3, 2), 8, 3, &[], &[], &layer_count(-1, true), &raw(&[&[1; 6], &[2; 6], &[3; 6], &[4; 6]]));
|
||||
|
||||
@@ -37,9 +37,9 @@ use axis::{nice_axis, tick_values};
|
||||
#[cfg(test)]
|
||||
use columns::{fill_totals, total_text};
|
||||
pub use commands::specs;
|
||||
pub(crate) use data::apply_csv;
|
||||
pub(crate) use data::{apply_csv, parse_csv};
|
||||
#[cfg(test)]
|
||||
use data::{fmt_value, parse_csv, to_csv};
|
||||
use data::{fmt_value, to_csv};
|
||||
pub use edit::{GraphTypeSubject, graph_type_subject};
|
||||
pub(crate) use edit::{graphs_holding, keep_placed};
|
||||
pub use generate::calculated_axes;
|
||||
|
||||
@@ -42,7 +42,7 @@ fn cell(c: &str) -> Cell {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn parse_csv(csv: &str) -> (Vec<String>, Vec<String>, Vec<Vec<Option<f64>>>) {
|
||||
pub(crate) fn parse_csv(csv: &str) -> (Vec<String>, Vec<String>, Vec<Vec<Option<f64>>>) {
|
||||
let csv = csv.strip_prefix('\u{feff}').unwrap_or(csv);
|
||||
// Records end at line breaks outside quotes; a record is tab-separated if it has a tab outside quotes.
|
||||
let rows: Vec<Vec<Cell>> = split_unquoted(csv, '\n')
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use vectorcraft_doc::graph::art_bounds;
|
||||
use vectorcraft_doc::graph::graph_art_without_type as art_bounds;
|
||||
|
||||
use super::axis::{MAX_TICK_MARKS, count_given, one_line};
|
||||
use super::data::apply_data;
|
||||
@@ -21,12 +21,16 @@ fn bound_param(p: &Value, key: &str, cmd: &str) -> Result<Option<Option<f64>>> {
|
||||
|
||||
/// The bounds a redraw of graph `n` measures a move or scale on, as kept at the last generation and as they are now:
|
||||
/// those of its art without type ([`GraphSpec::placed_art`]), or those of all its art when the graph keeps no such
|
||||
/// bounds with a width and a height, or has no art without type now.
|
||||
/// bounds with a width and a height. `None` when the art measured has no width or no height now, or the graph keeps
|
||||
/// bounds of its art without type and has no such art now.
|
||||
fn measured(n: &Node) -> Option<(Rect, Rect)> {
|
||||
let kept = n.extras().graph.as_deref()?;
|
||||
let c = n.children()?;
|
||||
let art = kept.placed_art.filter(|p| p.width() > 1e-9 && p.height() > 1e-9).zip(art_bounds(c));
|
||||
art.or_else(|| kept.placed.zip(children_bounds(c)))
|
||||
let solid = |r: &Rect| r.width() > 1e-9 && r.height() > 1e-9;
|
||||
match kept.placed_art.filter(solid) {
|
||||
Some(placed) => art_bounds(c).filter(solid).map(|now| (placed, now)),
|
||||
None => kept.placed.zip(children_bounds(c).filter(solid)),
|
||||
}
|
||||
}
|
||||
|
||||
/// `r` carried by the change from bounds `from` to bounds `to`: each edge stays at the same place relative to them.
|
||||
@@ -39,14 +43,28 @@ fn carried(r: Rect, from: Rect, to: Rect) -> Option<Rect> {
|
||||
Some(Rect::new(to.x0 + (r.x0 - from.x0) * sx, to.y0 + (r.y0 - from.y0) * sy, to.x0 + (r.x1 - from.x0) * sx, to.y0 + (r.y1 - from.y0) * sy))
|
||||
}
|
||||
|
||||
/// The graphs holding objects `ids`, each with the bounds of its art without type and of all its art. Give them to
|
||||
/// [`keep_placed`] after an edit that changes a graph's art without moving the graph.
|
||||
/// The graphs holding objects `ids`, that are among them or that are inside them, each with the bounds of its art
|
||||
/// without type and of all its art. Give them to [`keep_placed`] after an edit that changes a graph's art without
|
||||
/// moving the graph.
|
||||
pub(crate) fn graphs_holding(d: &Document, ids: &[NodeId]) -> Vec<(NodeId, Option<Rect>, Option<Rect>)> {
|
||||
let mut out: Vec<(NodeId, Option<Rect>, Option<Rect>)> = vec![];
|
||||
let is_graph = |n: &Node| n.extras().graph.is_some();
|
||||
let mut found: Vec<NodeId> = vec![];
|
||||
for id in ids {
|
||||
let Some(chain) = d.ancestry(*id) else { continue };
|
||||
let holder = chain.iter().rev().skip(1).copied().find(|a| d.node(*a).is_some_and(|n| n.extras().graph.is_some()));
|
||||
let Some(gid) = holder.filter(|g| !out.iter().any(|(o, ..)| o == g)) else { continue };
|
||||
found.extend(chain.iter().rev().copied().find(|a| d.node(*a).is_some_and(is_graph)));
|
||||
if let Some(n) = d.node(*id) {
|
||||
n.walk(&mut |c| {
|
||||
if is_graph(c) {
|
||||
found.push(c.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
let mut out: Vec<(NodeId, Option<Rect>, Option<Rect>)> = vec![];
|
||||
for gid in found {
|
||||
if out.iter().any(|(o, ..)| *o == gid) {
|
||||
continue;
|
||||
}
|
||||
let children = d.node(gid).and_then(Node::children);
|
||||
out.push((gid, children.and_then(|c| art_bounds(c)), children.and_then(|c| children_bounds(c))));
|
||||
}
|
||||
|
||||
@@ -149,20 +149,22 @@ impl Gen<'_> {
|
||||
refresh_bounds(&mut t);
|
||||
t
|
||||
}
|
||||
/// A category or series label: a `|` in it starts a new line (Add graph labels). `middle`: the lines are centred
|
||||
/// on `at` (labels beside an axis or in a wedge) instead of running down from it.
|
||||
/// A category or series label: a `|` in it starts a new line (Add graph labels), as does a line break a quoted CSV
|
||||
/// cell keeps. `middle`: the lines are centred on `at` (labels beside an axis or in a wedge) instead of running down
|
||||
/// from it.
|
||||
pub(super) fn label(&mut self, role: Role, at: Point, s: &str, justify: Justify, middle: bool) -> Arc<Node> {
|
||||
let lines = s.split('|').count();
|
||||
let text = s.replace('|', "\n");
|
||||
let lines = text.split('\n').count();
|
||||
// Default leading puts the first and last baselines this far above and below `at`.
|
||||
let half = (lines - 1) as f64 * label_size(self.styles, role) * 1.2 / 2.0;
|
||||
let start = if middle { Point::new(at.x, at.y - half) } else { at };
|
||||
let mut t = self.text_object(role, start, &s.replace('|', "\n"), justify);
|
||||
let mut t = self.text_object(role, start, &text, justify);
|
||||
// Kept leading or paragraph spacing moves the lines: put the middle of the first and last baselines on `at`. An
|
||||
// empty line has no baseline: an empty first or last line leaves the label where the default leading puts it.
|
||||
if middle && kept_para(self.styles, role).is_some() {
|
||||
let ys: Vec<f64> = t.baselines().map(|(a, _)| a.y).collect();
|
||||
let ends_set = s.split('|').next().is_some_and(|l| !l.is_empty()) && s.split('|').next_back().is_some_and(|l| !l.is_empty());
|
||||
let set = s.split('|').filter(|l| !l.is_empty()).count();
|
||||
let ends_set = text.split('\n').next().is_some_and(|l| !l.is_empty()) && text.split('\n').next_back().is_some_and(|l| !l.is_empty());
|
||||
let set = text.split('\n').filter(|l| !l.is_empty()).count();
|
||||
if let (Some(first), Some(last), true) = (ys.first(), ys.last(), ends_set && ys.len() == set) {
|
||||
t.xf = Affine::translate((0.0, half - (first + last) / 2.0)) * t.xf;
|
||||
}
|
||||
|
||||
@@ -6029,6 +6029,141 @@ fn outlining_a_graphs_labels_leaves_the_plot_in_place() {
|
||||
let moved = spec(&s, id).rect;
|
||||
assert!((moved.x0 - (rect.x0 + 30.0)).abs() < 1e-6 && (moved.y0 - (rect.y0 + 15.0)).abs() < 1e-6, "{moved:?}");
|
||||
assert!((moved.width() - rect.width()).abs() < 1e-6 && (moved.height() - rect.height()).abs() < 1e-6, "{moved:?}");
|
||||
// A scale of the graph made before outlining is still followed.
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("object.scale", &json!({"sx": 150, "sy": 50, "origin": [moved.x0, moved.y0]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [text_id(&s, id, "Axes", "Q3").0]})).unwrap();
|
||||
s.execute("type.createOutlines", &json!({})).unwrap();
|
||||
s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap();
|
||||
let scaled = spec(&s, id).rect;
|
||||
assert!((scaled.x0 - moved.x0).abs() < 1e-6 && (scaled.y0 - moved.y0).abs() < 1e-6, "{scaled:?}");
|
||||
assert!((scaled.width() - 1.5 * rect.width()).abs() < 1e-6 && (scaled.height() - 0.5 * rect.height()).abs() < 1e-6, "{scaled:?}");
|
||||
}
|
||||
|
||||
/// Outline Stroke on a graph's strokes leaves the plot where it is when the graph is drawn again, and a move of the
|
||||
/// graph made before it is still followed.
|
||||
#[test]
|
||||
fn outlining_a_graphs_strokes_leaves_the_plot_in_place() {
|
||||
let csv = ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6";
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let rect = spec(&s, id).rect;
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("object.move", &json!({"dx": 20, "dy": 10})).unwrap();
|
||||
s.execute("object.path.outlineStroke", &json!({})).unwrap();
|
||||
s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap();
|
||||
let moved = spec(&s, id).rect;
|
||||
assert!((moved.x0 - (rect.x0 + 20.0)).abs() < 1e-6 && (moved.y0 - (rect.y0 + 10.0)).abs() < 1e-6, "{moved:?}");
|
||||
assert!((moved.width() - rect.width()).abs() < 1e-6 && (moved.height() - rect.height()).abs() < 1e-6, "{moved:?}");
|
||||
}
|
||||
|
||||
/// A graph left with only its labels, or with its labels and one vertical line, leaves the plot where it is when it is
|
||||
/// drawn again after a label edit.
|
||||
#[test]
|
||||
fn a_graph_left_with_only_its_labels_leaves_the_plot_in_place() {
|
||||
for keep_a_line in [false, true] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let rect = spec(&s, id).rect;
|
||||
let (mut art, mut line) = (vec![], None);
|
||||
s.doc().unwrap().doc.node(id).unwrap().walk(&mut |n| {
|
||||
if n.children().is_none() && !matches!(n.kind, NodeKind::Text(_)) {
|
||||
let vertical = n.geometric_bounds().is_some_and(|b| b.width() < 1e-9 && b.height() > 1.0);
|
||||
if keep_a_line && vertical && line.is_none() {
|
||||
line = n.geometric_bounds();
|
||||
} else {
|
||||
art.push(n.id.0);
|
||||
}
|
||||
}
|
||||
});
|
||||
assert!(!art.is_empty() && line.is_some() == keep_a_line);
|
||||
s.execute("select.set", &json!({"ids": art})).unwrap();
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
let left = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
assert_eq!(vectorcraft_doc::graph::graph_art_without_type(left.children().unwrap()), line, "{:#?}", left.children());
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("text.setStyle", &json!({"size": 20})).unwrap();
|
||||
s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap();
|
||||
assert_eq!(spec(&s, id).rect, rect, "keeping a line: {keep_a_line}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A graph saved without the bounds of its art without type, left with one vertical line, keeps its plot's size when
|
||||
/// it is drawn again.
|
||||
#[test]
|
||||
fn a_graph_saved_with_only_its_whole_bounds_and_left_with_a_line_keeps_its_plot() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let rect = spec(&s, id).rect;
|
||||
let mut old = spec(&s, id);
|
||||
old.placed_art = None;
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().extras_mut().graph = Some(Box::new(old));
|
||||
let (mut art, mut line) = (vec![], None);
|
||||
s.doc().unwrap().doc.node(id).unwrap().walk(&mut |n| {
|
||||
if n.children().is_none() {
|
||||
let vertical = !matches!(n.kind, NodeKind::Text(_)) && n.geometric_bounds().is_some_and(|b| b.width() < 1e-9 && b.height() > 1.0);
|
||||
if vertical && line.is_none() {
|
||||
line = Some(n.id);
|
||||
} else {
|
||||
art.push(n.id.0);
|
||||
}
|
||||
}
|
||||
});
|
||||
assert!(line.is_some());
|
||||
s.execute("select.set", &json!({"ids": art})).unwrap();
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap();
|
||||
assert_eq!(spec(&s, id).rect, rect);
|
||||
}
|
||||
|
||||
/// The bounds a graph measures moves on take a clipping group holding type at the bounds of its clip, so art outside the
|
||||
/// clip does not change them; a clipping group whose clip is type is measured on its other art.
|
||||
#[test]
|
||||
fn a_clipping_group_holding_type_is_measured_on_its_clip() {
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_doc::graph::graph_art_without_type as measure;
|
||||
use vectorcraft_geom::Affine;
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
let label: Arc<vectorcraft_doc::Node> =
|
||||
group(&n, "Legend").children().unwrap().iter().find(|c| matches!(c.kind, NodeKind::Text(_))).unwrap().clone();
|
||||
let mut paths = vec![];
|
||||
n.walk(&mut |c| {
|
||||
if matches!(c.kind, NodeKind::Path { .. }) {
|
||||
paths.push(c.clone());
|
||||
}
|
||||
});
|
||||
let (clip, art) = (Arc::new(paths[0].clone()), paths[1].clone());
|
||||
let clipped = |dx: f64, first: Arc<vectorcraft_doc::Node>, second: Arc<vectorcraft_doc::Node>| {
|
||||
let mut far = art.clone();
|
||||
far.transform(Affine::translate((dx, 0.0)), false);
|
||||
let mut g = vectorcraft_doc::Node::group(NodeId(999_999), vec![first, second, Arc::new(far)]);
|
||||
if let NodeKind::Group { clip, .. } = &mut g.kind {
|
||||
*clip = true;
|
||||
}
|
||||
measure(&[Arc::new(g)])
|
||||
};
|
||||
assert_eq!(clipped(500.0, clip.clone(), label.clone()), clip.geometric_bounds());
|
||||
assert_eq!(clipped(500.0, clip.clone(), label.clone()), clipped(900.0, clip.clone(), label.clone()));
|
||||
// A clip that is type leaves the other art to measure.
|
||||
assert_ne!(clipped(500.0, label.clone(), clip.clone()), clipped(900.0, label.clone(), clip.clone()));
|
||||
// A clip that is a clipping group holding type in its clipped art is measured on its own clip.
|
||||
let mut inner = vectorcraft_doc::Node::group(NodeId(999_998), vec![clip.clone(), label.clone()]);
|
||||
if let NodeKind::Group { clip, .. } = &mut inner.kind {
|
||||
*clip = true;
|
||||
}
|
||||
let inner = Arc::new(inner);
|
||||
assert_eq!(clipped(500.0, inner.clone(), label.clone()), clip.geometric_bounds());
|
||||
assert_eq!(clipped(500.0, inner.clone(), label.clone()), clipped(900.0, inner.clone(), label.clone()));
|
||||
// A blend holding type is measured whole, as it is drawn.
|
||||
let blend = vectorcraft_doc::Node::new(NodeId(999_997), NodeKind::Blend { children: vec![clip.clone(), label.clone()], spec: Box::default() });
|
||||
assert_eq!(measure(&[Arc::new(blend.clone())]), blend.geometric_bounds());
|
||||
}
|
||||
|
||||
/// A graph whose kept bounds of its art without type have no width follows a move with the bounds of all of its art.
|
||||
@@ -7059,6 +7194,43 @@ fn a_centered_label_with_an_empty_middle_line_and_kept_leading_stays_centered()
|
||||
assert!((after - before).abs() < 0.01, "the three-line category label keeps its middle: {before} {after}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_centered_label_with_a_line_break_in_its_text_is_set_as_with_a_bar() {
|
||||
// A quoted CSV cell keeps its line breaks, so they reach the label as well as the `|` it is written with.
|
||||
for (bar, quoted, text) in [("Q|1", "\"Q\n1\"", "Q\n1"), ("Q|||1", "\"Q\n||1\"", "Q\n\n\n1")] {
|
||||
let label_middle = |s: &Session, id: NodeId| {
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
let label =
|
||||
group(&n, "Axes").children().unwrap().iter().find(|c| matches!(&c.kind, NodeKind::Text(t) if t.plain_text() == text)).unwrap();
|
||||
let b = label.geometric_bounds().unwrap();
|
||||
(b.y0 + b.y1) / 2.0
|
||||
};
|
||||
let drawn = |cat: &str, leading: bool| {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let csv = format!(",2024,2025\n{cat},3,2\nQ2,5,4\nQ3,-1,6");
|
||||
let id = NodeId(
|
||||
s.execute("graph.create", &json!({"type": "bar", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
if leading {
|
||||
let l = text_id(&s, id, "Axes", text);
|
||||
s.execute("select.set", &json!({"ids": [l.0]})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"autoLeading": 400})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap();
|
||||
}
|
||||
label_middle(&s, id)
|
||||
};
|
||||
for leading in [false, true] {
|
||||
let (by_bar, by_break) = (drawn(bar, leading), drawn(quoted, leading));
|
||||
assert!((by_bar - by_break).abs() < 0.01, "{text:?} sits where {bar:?} does (kept leading: {leading}): {by_bar} {by_break}");
|
||||
}
|
||||
assert!((drawn(quoted, true) - drawn(quoted, false)).abs() < 0.01, "{text:?} keeps its middle with kept leading");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_legend_across_top_measures_its_labels_with_system_layout() {
|
||||
let mut s = Session::new();
|
||||
@@ -7252,8 +7424,8 @@ fn graph_commands_refuse_params_of_the_wrong_type() {
|
||||
}
|
||||
|
||||
/// A `.ai` in PostScript form whose graph's records read whole (version 7 specification, appendix A)
|
||||
/// opens as a graph whose data can be edited: Graph Data redraws it on its plot. Saving it as `.ai`
|
||||
/// says its data and settings aren't written, in either form.
|
||||
/// opens as a graph whose data can be edited: Graph Data redraws it on its plot. Saving it as `.ai`,
|
||||
/// in either form, writes its records, and the file opens again with the graph's new data.
|
||||
#[test]
|
||||
fn a_graph_opened_from_ai_keeps_its_data_for_editing() {
|
||||
let graph = "%_Gs\n%_100 200 300 100 Gb\n%_5 0 0 14 0 1 0 0 6 44 Gy\n%_10 2 0 0 90 80 0 Gd\n\
|
||||
@@ -7310,10 +7482,60 @@ fn a_graph_opened_from_ai_keeps_its_data_for_editing() {
|
||||
}
|
||||
let r = s.execute("file.saveAs", &p).unwrap();
|
||||
let notes = r["warnings"].as_array().cloned().unwrap_or_default();
|
||||
assert!(notes.iter().any(|w| w.as_str().is_some_and(|w| w.starts_with("graphs are written as their art"))), "{name}: {r}");
|
||||
assert!(!notes.iter().any(|w| w.as_str().is_some_and(|w| w.starts_with("graphs are written as their art"))), "{name}: {r}");
|
||||
let mut again = Session::new();
|
||||
again.execute("document.open", &json!({"path": dir.join(name)})).unwrap();
|
||||
let mut graphs = vec![];
|
||||
again.doc().unwrap().doc.walk(|n| graphs.extend(n.extras().graph.as_deref().cloned()));
|
||||
assert_eq!(graphs.len(), 1, "{name}");
|
||||
let g = &graphs[0];
|
||||
assert_eq!(
|
||||
(g.series.as_slice(), g.categories.as_slice(), g.rows.as_slice()),
|
||||
(&after.series[..], &after.categories[..], &after.rows[..]),
|
||||
"{name}"
|
||||
);
|
||||
assert_eq!(g.kind, after.kind, "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A graph the graph tools draw, of each type, saved as `.ai` in either form, opens again as the same
|
||||
/// graph exactly when the save gives no warning about graphs; a column graph does.
|
||||
#[test]
|
||||
fn a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns() {
|
||||
let dir = vectorcraft_testkit::temp_dir("graph-ai-save");
|
||||
let mut live = vec![];
|
||||
for ty in ["column", "stackedColumn", "bar", "stackedBar", "line", "area", "scatter", "pie", "radar"] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let csv = ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,1,6";
|
||||
let id = s.execute("graph.create", &json!({"type": ty, "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
let written = spec(&s, NodeId(id));
|
||||
for (name, version) in [("v7.ai", Some("7")), ("pdf.ai", None)] {
|
||||
let path = dir.join(format!("{ty}-{name}"));
|
||||
let mut p = json!({"path": path, "format": "ai"});
|
||||
if let Some(v) = version {
|
||||
p["aiVersion"] = json!(v);
|
||||
}
|
||||
let r = s.execute("file.saveAs", &p).unwrap();
|
||||
let notes = r["warnings"].as_array().cloned().unwrap_or_default();
|
||||
let warned = notes.iter().any(|w| w.as_str().is_some_and(|w| w.starts_with("graphs are written as their art")));
|
||||
let mut again = Session::new();
|
||||
again.execute("document.open", &json!({"path": path})).unwrap();
|
||||
let mut graphs = vec![];
|
||||
again.doc().unwrap().doc.walk(|n| graphs.extend(n.extras().graph.as_deref().cloned()));
|
||||
assert_eq!(graphs.len(), usize::from(!warned), "{ty} {name}: {r}");
|
||||
if let Some(g) = graphs.first() {
|
||||
assert_eq!((g.kind, g.cells()), (written.kind, written.cells()), "{ty} {name}");
|
||||
assert_eq!((g.series.as_slice(), g.categories.as_slice()), (&written.series[..], &written.categories[..]), "{ty} {name}");
|
||||
live.push(format!("{ty} {name}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(live.contains(&"column v7.ai".to_string()) && live.contains(&"column pdf.ai".to_string()), "{live:?}");
|
||||
}
|
||||
|
||||
/// A graph opened from a `.ai` keeps the bounds of its art without type, so moving one of its labels on its own
|
||||
/// leaves the plot where it is at the first redraw.
|
||||
#[test]
|
||||
@@ -7346,9 +7568,17 @@ fn a_graph_opened_from_ai_measures_moves_without_its_labels() {
|
||||
assert_eq!((graphs.len(), labels.len()), (1, 1));
|
||||
let (id, label) = (graphs[0], labels[0]);
|
||||
let before = spec(&s, id);
|
||||
assert!(before.placed_art.is_some());
|
||||
s.execute("select.set", &json!({"ids": [label.0]})).unwrap();
|
||||
s.execute("text.setStyle", &json!({"size": 30})).unwrap();
|
||||
s.execute("object.move", &json!({"dx": 80, "dy": -40})).unwrap();
|
||||
s.execute("graph.setData", &json!({"id": id.0, "csv": ",East\nQ1,8\nQ2,2"})).unwrap();
|
||||
assert_eq!(spec(&s, id).rect, before.rect);
|
||||
let rect = spec(&s, id).rect;
|
||||
assert_eq!(rect, before.rect, "after restyling and moving a label");
|
||||
// A move of the whole opened graph is still followed.
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("object.move", &json!({"dx": 15, "dy": 25})).unwrap();
|
||||
s.execute("graph.setData", &json!({"id": id.0, "csv": ",East\nQ1,8\nQ2,2"})).unwrap();
|
||||
let moved = spec(&s, id).rect;
|
||||
assert!((moved.x0 - (rect.x0 + 15.0)).abs() < 1e-6 && (moved.y0 - (rect.y0 + 25.0)).abs() < 1e-6, "{moved:?}");
|
||||
assert!((moved.width() - rect.width()).abs() < 1e-6 && (moved.height() - rect.height()).abs() < 1e-6, "{moved:?}");
|
||||
}
|
||||
|
||||
@@ -43,7 +43,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Scale…",
|
||||
["Object", "Transform"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection), sx: %, sy?: %, origin?: [x,y], copy?, strokes?: bool (Scale Strokes & Effects: stroke weights, dashes and effect distances scale; off keeps them, type strokes included), corners?: bool (Scale Corners: live corner radii scale), objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)} (strokes/corners default to the preferences). With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
|
||||
"{ids?: [id…] (selected first; default: the selection), sx: % (along the bounding box's width), sy?: % (along its height), origin?: [x,y] (a page point), basis?: \"box\"|\"page\" (box, the default: sx and sy follow the bounding box, turned with rotated objects until Reset Bounding Box; page: the page's axes; a saved step without basis, recorded before it, plays along the page's axes), copy?, strokes?: bool (Scale Strokes & Effects: stroke weights, dashes and effect distances scale; off keeps them, type strokes included), corners?: bool (Scale Corners: live corner radii scale), objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)} (strokes/corners default to the preferences). With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
|
||||
has_selection,
|
||||
scale
|
||||
),
|
||||
@@ -52,7 +52,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reflect…",
|
||||
["Object", "Transform"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection), axis: \"vertical\"|\"horizontal\"|deg (the mirror line, counter-clockwise from horizontal; 0: horizontal; omitted: vertical), origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
|
||||
"{ids?: [id…] (selected first; default: the selection), axis: \"vertical\"|\"horizontal\"|deg (the mirror line, counter-clockwise from horizontal; 0: horizontal; omitted: vertical; vertical and horizontal are the bounding box's own axes, deg a line on the page), origin?, basis?: \"box\"|\"page\" (for a named axis; box, the default: the bounding box's axes, turned with rotated objects until Reset Bounding Box; page: the page's axes; a saved step without basis, recorded before it, plays along the page's axes), copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
|
||||
has_selection,
|
||||
reflect
|
||||
),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::align::choice;
|
||||
use super::{
|
||||
Affine, Arc, Document, EngineError, LastTransform, Node, NodeId, NodeKind, Point, Result, Scaling, Session, Value, Vec2, bad, bool_or,
|
||||
check_numbers, check_switches, duplicate_in, effects, f64_or, f64_req, ids_param, json, matrix_param, ok, outermost, point_param,
|
||||
Affine, Arc, Document, EngineError, LastTransform, Node, NodeId, NodeKind, OrientedBox, Point, Rect, Result, Scaling, Session, Value, Vec2, bad,
|
||||
bool_or, check_numbers, check_switches, duplicate_in, effects, f64_or, f64_req, ids_param, json, matrix_param, ok, outermost, point_param,
|
||||
selected_roots_to_transform,
|
||||
};
|
||||
|
||||
@@ -358,26 +358,52 @@ pub(super) fn scale(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if sx == 0.0 || sy == 0.0 {
|
||||
return Err(bad("object.scale", "scale must be non-zero"));
|
||||
}
|
||||
apply_transform(s, "Scale", ids, about(o, Affine::scale_non_uniform(sx, sy)), p, true)
|
||||
let frame = basis_frame(s, p, "object.scale", &ids)?;
|
||||
apply_transform(s, "Scale", ids, about(o, frame.conjugate(Affine::scale_non_uniform(sx, sy))), p, true)
|
||||
}
|
||||
|
||||
/// The frame that `object.scale` and a named `object.reflect` act in, from the `basis` param:
|
||||
/// `"box"` (the default) is the bounding box of `ids`, turned with rotated objects until Reset
|
||||
/// Bounding Box ([`Document::bbox_angle`]); `"page"` is the page's axes. Anchors selected with
|
||||
/// Direct Selection (with no copy and Transform Objects on) transform along the page's axes, as
|
||||
/// their own box does. The basis joins the journal entry, so a replay acts in the same frame. A
|
||||
/// saved step without `basis` ([`Session::replay`]) was recorded before Scale and Reflect followed
|
||||
/// the box, so it acts along the page's axes, as it did when it was recorded.
|
||||
fn basis_frame(s: &mut Session, p: &Value, cmd: &str, ids: &[NodeId]) -> Result<OrientedBox> {
|
||||
let basis = choice(p, cmd, "basis", &["box", "page"])?;
|
||||
let page = basis == Some("page") || (basis.is_none() && s.replaying());
|
||||
let st = s.doc()?;
|
||||
let anchors = !bool_or(p, "copy", false)
|
||||
&& transforms_objects(p)
|
||||
&& effects::preview::anchor_bounds_with(&st.selection, &st.doc, s.bounds_measure()).is_some();
|
||||
let angle = if page || anchors { 0.0 } else { st.doc.bbox_angle(ids) };
|
||||
s.note_journal("basis", json!(if page { "page" } else { "box" }));
|
||||
Ok(OrientedBox { angle, rect: Rect::ZERO })
|
||||
}
|
||||
|
||||
pub(super) fn reflect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_switches(p, &TRANSFORM_SWITCHES, "object.reflect")?;
|
||||
let ids = selected_roots_to_transform(s)?;
|
||||
let o = origin_of(s, p, &ids)?;
|
||||
let m = match p.get("axis") {
|
||||
Some(Value::String(a)) if a == "horizontal" => Affine::scale_non_uniform(1.0, -1.0),
|
||||
Some(Value::Number(n)) => {
|
||||
let t = -n.as_f64().unwrap_or(90.0).to_radians();
|
||||
Affine::rotate(t) * Affine::scale_non_uniform(1.0, -1.0) * Affine::rotate(-t)
|
||||
}
|
||||
None | Some(Value::Null) => Affine::scale_non_uniform(-1.0, 1.0),
|
||||
Some(Value::String(a)) if a == "vertical" => Affine::scale_non_uniform(-1.0, 1.0),
|
||||
// A named axis is the bounding box's own (see [`basis_frame`]); an angle is a line on the page.
|
||||
let named = match p.get("axis") {
|
||||
Some(Value::String(a)) if a == "horizontal" => Some(Affine::scale_non_uniform(1.0, -1.0)),
|
||||
Some(Value::Number(_)) => None,
|
||||
None | Some(Value::Null) => Some(Affine::scale_non_uniform(-1.0, 1.0)),
|
||||
Some(Value::String(a)) if a == "vertical" => Some(Affine::scale_non_uniform(-1.0, 1.0)),
|
||||
Some(v) => {
|
||||
let given = v.as_str().map_or_else(|| v.to_string(), str::to_string);
|
||||
return Err(bad("object.reflect", format!("axis must be \"vertical\", \"horizontal\" or an angle in degrees, not `{given}`")));
|
||||
}
|
||||
};
|
||||
let m = match named {
|
||||
Some(m) => basis_frame(s, p, "object.reflect", &ids)?.conjugate(m),
|
||||
None => {
|
||||
choice(p, "object.reflect", "basis", &["box", "page"])?;
|
||||
let t = -p.get("axis").and_then(Value::as_f64).unwrap_or(90.0).to_radians();
|
||||
Affine::rotate(t) * Affine::scale_non_uniform(1.0, -1.0) * Affine::rotate(-t)
|
||||
}
|
||||
};
|
||||
apply_transform(s, "Reflect", ids, about(o, m), p, true)
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -382,7 +382,8 @@ pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()>
|
||||
return Err(bad(id, format!("`version` must be 0 or {newest}")));
|
||||
}
|
||||
check_effect_color(id, effect, params)?;
|
||||
check_effect_channel(id, effect, params)
|
||||
check_effect_channel(id, effect, params)?;
|
||||
check_effect_center(id, effect, params)
|
||||
}
|
||||
|
||||
/// The type of the values in `params` of effect `effect`, as command `id` was given them: a key
|
||||
@@ -423,9 +424,9 @@ fn check_effect_types(id: &str, effect: &str, params: &Value) -> Result<()> {
|
||||
/// A value of the type effect `effect` reads for `key`, a parameter its params description names
|
||||
/// without a dialog default: the earlier 3D Perspective and light (`perspective`, `lightAzimuth`,
|
||||
/// `lightElevation`) and Scribble `variation` are numbers, an Outline Stroke's `width` is a number
|
||||
/// and a Gaussian Blur's `linear` is true or false. A Glass or Texturizer `textureImage`, an SVG
|
||||
/// filter's `name` and `xml`, a Warp's `version` and the `style` of Crop Marks have checks of their
|
||||
/// own; they aren't listed.
|
||||
/// and a Gaussian Blur's `linear` is true or false. A Glass, Texturizer or Rough Pastels
|
||||
/// `textureImage`, an SVG filter's `name` and `xml`, a Warp's `version` and the `style` of Crop
|
||||
/// Marks have checks of their own; they aren't listed.
|
||||
pub(crate) fn undefaulted_type(effect: &str, key: &str) -> Option<Value> {
|
||||
use vectorcraft_render::effects;
|
||||
let number = || Some(Value::from(0.0));
|
||||
@@ -500,6 +501,22 @@ pub(crate) fn check_effect_channel(id: &str, effect: &str, params: &Value) -> Re
|
||||
Err(bad(id, format!("`{key}` must be one of {}", vectorcraft_render::effects::CHANNELS.join(", "))))
|
||||
}
|
||||
|
||||
/// The Blur Center (`centerX`, `centerY`) in `params` of Radial Blur (`effect`), as command `id`
|
||||
/// was given it: a parameter error unless each is a number from 0 to 1 (a share of the object's
|
||||
/// bounds). `effect.apply` and `effect.setParams` run this themselves before they edit, as they
|
||||
/// run [`check_effect_channel`].
|
||||
pub(crate) fn check_effect_center(id: &str, effect: &str, params: &Value) -> Result<()> {
|
||||
if effect != "blur.radial" {
|
||||
return Ok(());
|
||||
}
|
||||
for key in ["centerX", "centerY"] {
|
||||
if params.get(key).is_some_and(|v| !v.as_f64().is_some_and(|x| (0.0..=1.0).contains(&x))) {
|
||||
return Err(bad(id, format!("`{key}` must be a number from 0 to 1")));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Commands whose params aren't checked yet (#1442): they read keys in ways the audit of the
|
||||
/// descriptions couldn't follow (a list of keys in a loop, a whole object read as settings), so
|
||||
/// their descriptions aren't proven to name every key they take. Sorted; take a command out once
|
||||
|
||||
@@ -77,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reverse Path Direction",
|
||||
["Object", "Path"],
|
||||
None,
|
||||
"{ids?|id?, subpath?: usize (reverse only this subpath of each path, 0 included; default: every subpath), reversed?: bool (true: every subpath runs counter-clockwise on screen, false: clockwise, the Attributes panel's Reverse Path Direction On / Off; omitted: flip each path; with subpath, the direction is not read: that subpath is flipped)} the paths in ids or the selection (groups and compound paths: the paths inside), as one undo step; when every subpath of a path turns alike, its strokes' width profiles (sides swapped) and pen pressure, tilt, bearing and rotation turn with it, so they draw as before → {changed: paths}",
|
||||
"{ids?|id?, subpath?: usize (reverse only this subpath of each path, 0 included; default: every subpath), reversed?: bool (true: every subpath runs counter-clockwise on screen, false: clockwise, the Attributes panel's Reverse Path Direction On / Off; omitted: flip each path; with subpath, the direction is not read: that subpath is flipped)} the paths in ids or the selection (groups and compound paths: the paths inside), as one undo step; when every subpath of a path or compound path turns alike, its strokes' width profiles (sides swapped) and pen pressure, tilt, bearing and rotation turn with it, so they draw as before → {changed: paths}",
|
||||
has_selected_path,
|
||||
reverse
|
||||
),
|
||||
@@ -458,14 +458,33 @@ fn reverse(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if ids.is_empty() {
|
||||
return Err(bad(C, "select paths"));
|
||||
}
|
||||
let flip_of = |path: &PathData| -> Vec<bool> {
|
||||
match subpath {
|
||||
Some(si) => (0..path.subpaths.len()).map(|i| i == si).collect(),
|
||||
None => path.subpaths.iter().map(|sp| want.is_none_or(|ccw| (sp.signed_area() < 0.0) != ccw)).collect(),
|
||||
}
|
||||
};
|
||||
let changed = super::overprint::edit_counted(s, "Reverse Path Direction", |d| {
|
||||
// A compound path's own strokes run along its members' subpaths in order, so they turn
|
||||
// with them, read before any member turns.
|
||||
let compounds: BTreeSet<NodeId> = ids.iter().map(|id| compound_or_self(d, *id)).filter(|c| ids.binary_search(c).is_err()).collect();
|
||||
for c in compounds {
|
||||
let Some(NodeKind::Compound { children, .. }) = d.node(c).map(|n| &n.kind) else { continue };
|
||||
let flip: Vec<bool> = children
|
||||
.iter()
|
||||
.filter_map(|m| m.path_data().map(|pd| if ids.binary_search(&m.id).is_ok() { flip_of(pd) } else { vec![false; pd.subpaths.len()] }))
|
||||
.flatten()
|
||||
.collect();
|
||||
if flip.contains(&true)
|
||||
&& let Some(n) = d.node_mut(c)
|
||||
{
|
||||
vectorcraft_doc::blend::reverse_stroke_records(n, &flip);
|
||||
}
|
||||
}
|
||||
let mut changed = 0;
|
||||
for id in &ids {
|
||||
let path = path_mut(d, *id)?;
|
||||
let flip: Vec<bool> = match subpath {
|
||||
Some(si) => (0..path.subpaths.len()).map(|i| i == si).collect(),
|
||||
None => path.subpaths.iter().map(|sp| want.is_none_or(|ccw| (sp.signed_area() < 0.0) != ccw)).collect(),
|
||||
};
|
||||
let flip = flip_of(path);
|
||||
if !flip.contains(&true) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -1188,6 +1188,8 @@ fn outline_stroke(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let roots = selected_roots(s)?;
|
||||
let ids = s.edit("Outline Stroke", |d, sel| {
|
||||
let before = d.clone();
|
||||
// Outlining the strokes in a graph does not move or scale its plot at the next redraw.
|
||||
let graphs = super::graph::graphs_holding(d, &roots);
|
||||
// A dimension selected with the art it measures keeps its own lines: it is out of the
|
||||
// document while the art is outlined.
|
||||
let lifted = super::dimension::lift(d, &roots);
|
||||
@@ -1207,6 +1209,7 @@ fn outline_stroke(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
if changed == 0 || (kept && d.layers == before.layers) {
|
||||
return Err(EngineError::Other("Outline Stroke: no stroked paths selected".into()));
|
||||
}
|
||||
super::graph::keep_placed(d, &graphs);
|
||||
sel.set(new_sel.iter().copied());
|
||||
Ok(new_sel)
|
||||
})?;
|
||||
|
||||
@@ -75,7 +75,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Place…",
|
||||
["File"],
|
||||
Some("Cmd+Shift+P"),
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file placed in a clip group, which the Links commands take}. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed",
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed",
|
||||
has_doc,
|
||||
place
|
||||
),
|
||||
@@ -113,7 +113,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
|
||||
/// A file's art at its natural size, before it joins a document.
|
||||
enum Art {
|
||||
Image(RasterImage),
|
||||
/// An image, with the clipping path its file names, in its pixel space (a PSD or PSB file's,
|
||||
/// [`fileio::psdread::clipping_path`]).
|
||||
Image(RasterImage, Option<vectorcraft_geom::PathData>),
|
||||
/// A text file's, an RTF file's or a Word document's text, placed as area type filling the
|
||||
/// natural box.
|
||||
Text(text::Story),
|
||||
@@ -241,7 +243,8 @@ fn load(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool) -> Result<Loa
|
||||
let natural = Rect::new(0.0, 0.0, img.width as f64 * sx, img.height as f64 * sy);
|
||||
let link = src.path.map(|path| super::links::link_info(path, &src.bytes));
|
||||
let warnings = fileio::size_note(&img.blob.bytes).into_iter().collect();
|
||||
return Ok(Loaded { name, format, art: Art::Image(img), natural, warnings, link, board: None });
|
||||
let clip = fileio::psdread::clipping_path(&src.bytes);
|
||||
return Ok(Loaded { name, format, art: Art::Image(img, clip), natural, warnings, link, board: None });
|
||||
}
|
||||
if pdf {
|
||||
// Linked: placed like a VectorCraft document, read again with the page's box only. A page
|
||||
@@ -411,7 +414,7 @@ fn art_of<'a>(nodes: impl Iterator<Item = &'a Arc<Node>>) -> Vec<Node> {
|
||||
/// The art as one object of `d` (its resources added), at its natural size and position.
|
||||
fn build(d: &mut Document, l: Loaded, link: Option<LinkInfo>) -> Node {
|
||||
let mut node = match l.art {
|
||||
Art::Image(img) => {
|
||||
Art::Image(img, clip) => {
|
||||
let (sx, sy) = pt_per_px(img.ppi);
|
||||
super::links::store_image(d, &img.key, img.blob, link.is_some());
|
||||
let im = ImageObject {
|
||||
@@ -423,7 +426,8 @@ fn build(d: &mut Document, l: Loaded, link: Option<LinkInfo>) -> Node {
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
Node::new(d.alloc_id(), NodeKind::Image(Box::new(im)))
|
||||
let image = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im)));
|
||||
fileio::file_clipped(d, image, clip)
|
||||
}
|
||||
Art::Dcs(a) => {
|
||||
let a = *a;
|
||||
@@ -485,9 +489,23 @@ fn at_param(p: &Value) -> Result<Option<Point>> {
|
||||
|
||||
/// The transform that puts new art with the natural box `natural` where `old` is: an image's scale
|
||||
/// and rotation relative to its 100% size (its resolution's) and its centre are kept (with
|
||||
/// `image_xf`); other objects keep their centre.
|
||||
fn replace_xf(d: &Document, old: &Node, natural: Rect, image_xf: bool) -> Affine {
|
||||
if image_xf && let NodeKind::Image(im) = &old.kind {
|
||||
/// `image_xf`), also for an image alone in a clip group when the new art is an image clipped by
|
||||
/// its file's clipping path (`clipped`); other objects keep their centre.
|
||||
fn replace_xf(d: &Document, old: &Node, natural: Rect, image_xf: bool, clipped: bool) -> Affine {
|
||||
// An image alone in a clip group (as a PSD or PSB file's clipping path places it,
|
||||
// [`fileio::file_clipped`]) is measured as the image when the new art brings its own clip
|
||||
// group; a DCS file's plates are not.
|
||||
let image = match &old.kind {
|
||||
NodeKind::Group { children, clip: true } if clipped => match &children[..] {
|
||||
[path, image] if matches!(path.kind, NodeKind::Path { clipping: true, .. }) => match &image.kind {
|
||||
NodeKind::Image(im) if d.images.get(&im.key).is_none_or(|b| b.separated().is_none()) => image,
|
||||
_ => old,
|
||||
},
|
||||
_ => old,
|
||||
},
|
||||
_ => old,
|
||||
};
|
||||
if image_xf && let NodeKind::Image(im) = &image.kind {
|
||||
let (sx, sy) = pt_per_px(d.images.get(&im.key).and_then(|b| fileio::ppi::resolution(&b.bytes)));
|
||||
let full = Affine::scale_non_uniform(sx, sy);
|
||||
let centre = full * Point::new(im.width as f64 / 2.0, im.height as f64 / 2.0);
|
||||
@@ -541,7 +559,7 @@ impl PlaceJob {
|
||||
let mut loaded = load(&self.params, PLACE, self.target, true)?;
|
||||
let linked = loaded.link.is_some() && bool_or(&self.params, "link", true);
|
||||
match &mut loaded.art {
|
||||
Art::Image(img) => {
|
||||
Art::Image(img, _) => {
|
||||
let unread = super::links::kept_unread(&img.blob.bytes);
|
||||
img.blob = super::links::readable_and_kept(img.blob.clone(), unread, linked)?;
|
||||
}
|
||||
@@ -657,7 +675,7 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
|
||||
}
|
||||
let natural = loaded.natural;
|
||||
let m = match (old_node, rect) {
|
||||
(Some(o), _) => replace_xf(&st.doc, o, natural, !is_text),
|
||||
(Some(o), _) => replace_xf(&st.doc, o, natural, !is_text, matches!(loaded.art, Art::Image(_, Some(_)))),
|
||||
(None, Some(r)) => fit(natural, r),
|
||||
// Its artboard's bottom-left corner on the target's.
|
||||
(None, None) if let (Some(src), Some(to)) = (loaded.board, target) => Affine::translate((to.x0 - src.x0, to.y1 - src.y1)),
|
||||
@@ -671,7 +689,7 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
|
||||
let link = loaded.link.take().filter(|_| bool_or(p, "link", true));
|
||||
let linked = link.is_some();
|
||||
let (name, format, mut warnings) = (loaded.name.clone(), loaded.format.id, std::mem::take(&mut loaded.warnings));
|
||||
let dcs_clipped = matches!(&loaded.art, Art::Dcs(a) if a.clip.is_some());
|
||||
let file_clipped = matches!(&loaded.art, Art::Dcs(a) if a.clip.is_some()) || matches!(&loaded.art, Art::Image(_, Some(_)));
|
||||
if let Art::Dcs(a) = &loaded.art {
|
||||
warnings.extend(dcs::swatch_notes(&st.doc, &a.spots));
|
||||
}
|
||||
@@ -697,8 +715,9 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
|
||||
Ok((id, size))
|
||||
})?;
|
||||
let mut out = json!({ "ids": [id.0], "name": name, "format": format, "linked": linked, "width": size.width(), "height": size.height(), "warnings": warnings });
|
||||
// A DCS file clipped by its clipping path: its image, which the Links commands take.
|
||||
if dcs_clipped {
|
||||
// A DCS, PSD or PSB file clipped by its clipping path: its image, which the Links commands
|
||||
// take.
|
||||
if file_clipped {
|
||||
let image = s.doc()?.doc.node(id).and_then(|n| match &n.kind {
|
||||
NodeKind::Group { children, clip: true } => children.get(1).filter(|c| matches!(c.kind, NodeKind::Image(_))).map(|c| c.id),
|
||||
_ => None,
|
||||
@@ -810,7 +829,7 @@ fn read_queue(doc: u64, p: Value, queued: Vec<Value>) -> Result<QueueRead> {
|
||||
let checked = load(&q, QUEUE, None, false).and_then(|mut l| {
|
||||
let linked = l.link.is_some() && bool_or(&q, "link", true);
|
||||
match &mut l.art {
|
||||
Art::Image(img) => {
|
||||
Art::Image(img, _) => {
|
||||
let unread = super::links::kept_unread(&img.blob.bytes);
|
||||
let check = if thumbnail.is_some() { super::links::readable_and_kept } else { super::links::readable };
|
||||
img.blob = check(img.blob.clone(), unread, linked)?;
|
||||
@@ -932,7 +951,7 @@ pub fn read_info(p: &Value) -> Result<Value> {
|
||||
"height": natural.height(),
|
||||
"warnings": std::mem::take(&mut l.warnings),
|
||||
});
|
||||
if let Art::Image(img) = &l.art {
|
||||
if let Art::Image(img, _) = &l.art {
|
||||
let (x, y) = img.ppi.unwrap_or((72.0, 72.0));
|
||||
out["pixelWidth"] = json!(img.width);
|
||||
out["pixelHeight"] = json!(img.height);
|
||||
|
||||
@@ -538,8 +538,8 @@ pub(crate) fn run_command(s: &mut Session, id: &str, p: &Value) -> Result<Value>
|
||||
/// live-effect plug-in) with parameters it takes, filled in to their defaults. A record the object
|
||||
/// already had stays as it was. An object takes one 3D effect (its fills' and strokes' own
|
||||
/// counted), which must fit it, and the `textureImage` of an effect with Load Texture (Glass,
|
||||
/// Texturizer) comes as the effect stores it, never as a file to read: a plug-in can't have the
|
||||
/// host read one.
|
||||
/// Texturizer, Rough Pastels) comes as the effect stores it, never as a file to read: a plug-in
|
||||
/// can't have the host read one.
|
||||
fn admit_effects(fx: &[Effect], n: &Node) -> std::result::Result<Vec<Effect>, String> {
|
||||
admit_effects_for("plugin.run", fx, n)
|
||||
}
|
||||
|
||||
@@ -3,9 +3,14 @@
|
||||
//! applied effect names the document's filter: editing the filter changes what every object that
|
||||
//! uses it draws, and deleting it leaves their effects in place, drawing nothing, until a filter of
|
||||
//! that name exists again. Each effect holds the definition it draws with, kept in step here.
|
||||
//!
|
||||
//! The default filters ([`svg_filter::defaults`]) are listed for every document. Applying or
|
||||
//! editing one adds a copy to the document under the default's name, and from then on that copy is
|
||||
//! the filter of that name. Deleting the copy lists the default again.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Appearance, Document, SvgFilter};
|
||||
use vectorcraft_render::effects::svg_filter::defaults::{DEFAULT_FILTERS, default_filter};
|
||||
use vectorcraft_render::effects::{self, svg_filter};
|
||||
|
||||
use super::fileio::{absolute_path, read_file_head};
|
||||
@@ -21,7 +26,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"SVG Filters",
|
||||
[],
|
||||
None,
|
||||
"{} → {filters: [{name, xml}…]} the SVG filters the document holds, in the SVG Filters submenu's order",
|
||||
"{} → {filters: [{name, xml}…], defaults: [{name, xml, inDocument}…]} filters: the SVG filters the document holds, in the order they were added; defaults: the default filters every document lists (VectorCraft's own set), with inDocument true when the document holds a filter of that name, which then stands in the default's place. The SVG Filters submenu and Apply SVG Filter list the defaults first, then the document's other filters",
|
||||
has_doc,
|
||||
list
|
||||
),
|
||||
@@ -30,7 +35,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New SVG Filter",
|
||||
[],
|
||||
None,
|
||||
"{xml: one SVG <filter> element (its id is its name; 1..64 primitives; at most 64 KB), replace?: the name of the filter it replaces and keeps (Edit SVG Filter)} add an SVG filter to the document, after the others, or replace one, as one undo step; every object whose svg.filter effect names it draws with the new definition; a name another filter has is refused and a document holds at most 64 filters → {name, filters}",
|
||||
"{xml: one SVG <filter> element (its id is its name; 1..64 primitives; at most 64 KB), replace?: the name of the filter it replaces and keeps (Edit SVG Filter)} add an SVG filter to the document, after the others, or replace one, as one undo step; every object whose svg.filter effect names it draws with the new definition; a name another filter of the document has is refused and a document holds at most 64 filters; replace with the name of a default filter the document does not hold adds the edited copy to the document under that name, and code equal to the default's adds nothing; a new filter may take a default's name, and then stands in its place → {name, filters}",
|
||||
has_doc,
|
||||
define
|
||||
),
|
||||
@@ -39,7 +44,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Delete SVG Filter",
|
||||
[],
|
||||
None,
|
||||
"{name} remove an SVG filter from the document, as one undo step; objects whose svg.filter effect names it keep the effect, which draws nothing until a filter of that name is defined or imported again → {filters}",
|
||||
"{name} remove an SVG filter from the document, as one undo step; objects whose svg.filter effect names it keep the effect, which draws nothing until a filter of that name is defined or imported again, or the default of that name is applied; a default filter the document holds no copy of is refused (the defaults are not deleted), and deleting the document's copy of one lists the default again → {filters}",
|
||||
has_doc,
|
||||
delete
|
||||
),
|
||||
@@ -57,7 +62,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Apply SVG Filter",
|
||||
[],
|
||||
None,
|
||||
"{name, ids?|id?, item?} apply the document's SVG filter `name` (svgFilter.list) to ids or the selection as a live svg.filter effect, as one undo step, like effect.apply → {ids, index, item}",
|
||||
"{name, ids?|id?, item?, index?} apply the document's SVG filter `name`, or the default filter of that name when the document holds none (svgFilter.list), to ids or the selection as a live svg.filter effect, as one undo step, like effect.apply → {ids, index, item}; with index, the filter takes the place of the applied svg.filter effect at index of item, like effect.setParams → {ids}; a default is copied into the document in the same undo step, which is refused when the document already holds 64 filters",
|
||||
has_doc,
|
||||
apply
|
||||
),
|
||||
@@ -69,7 +74,10 @@ fn filters_json(d: &Document) -> Value {
|
||||
}
|
||||
|
||||
fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({ "filters": filters_json(&s.doc()?.doc) }))
|
||||
let d = &s.doc()?.doc;
|
||||
let held = |name: &str| d.svg_filters.iter().any(|f| f.name == name);
|
||||
let defaults: Vec<Value> = DEFAULT_FILTERS.iter().map(|f| json!({ "name": f.name, "xml": f.xml, "inDocument": held(f.name) })).collect();
|
||||
Ok(json!({ "filters": filters_json(d), "defaults": defaults }))
|
||||
}
|
||||
|
||||
/// `p`'s `name`, trimmed and not empty.
|
||||
@@ -132,10 +140,12 @@ fn define(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
svg_filter::check(&xml).map_err(|e| bad(C, e))?;
|
||||
let filters = &s.doc()?.doc.svg_filters;
|
||||
let at = match &replace {
|
||||
Some(r) => Some(filters.iter().position(|f| f.name == *r).ok_or_else(|| bad(C, format!("the document has no SVG filter named {r:?}")))?),
|
||||
None => None,
|
||||
};
|
||||
let at = replace.as_ref().and_then(|r| filters.iter().position(|f| f.name == *r));
|
||||
// A default the document does not hold: its edited copy is added under the default's name.
|
||||
let default = replace.as_ref().filter(|_| at.is_none()).and_then(|r| default_filter(r));
|
||||
if let Some(r) = replace.as_ref().filter(|_| at.is_none() && default.is_none()) {
|
||||
return Err(bad(C, format!("the document has no SVG filter named {r:?}")));
|
||||
}
|
||||
// An edited filter keeps its name, whatever id its new code gives it.
|
||||
let xml = match &replace {
|
||||
Some(r) => svg_filter::with_id(&xml, r).ok_or_else(|| bad(C, "give one <filter> element"))?,
|
||||
@@ -145,22 +155,28 @@ fn define(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if filters.iter().enumerate().any(|(i, f)| f.name == name && Some(i) != at) {
|
||||
return Err(bad(C, format!("the document already has an SVG filter named {name:?}")));
|
||||
}
|
||||
let new = SvgFilter { name: name.clone(), xml };
|
||||
// Nothing to record when the filter, and every object that uses it, is already as given: a
|
||||
// default saved with its own code stays out of the document.
|
||||
let as_given = match default {
|
||||
Some(d) => d.to_filter() == new,
|
||||
None => at.and_then(|i| filters.get(i)) == Some(&new),
|
||||
};
|
||||
if as_given && !out_of_step(&s.doc()?.doc, &new.name, &new.xml) {
|
||||
return Ok(json!({ "name": name, "filters": filters_json(&s.doc()?.doc) }));
|
||||
}
|
||||
if at.is_none() && filters.len() >= SvgFilter::MAX {
|
||||
return Err(bad(C, format!("a document holds at most {} SVG filters", SvgFilter::MAX)));
|
||||
}
|
||||
let new = SvgFilter { name: name.clone(), xml };
|
||||
// Nothing to record when the filter, and every object that uses it, is already as given.
|
||||
if at.and_then(|i| filters.get(i)) != Some(&new) || out_of_step(&s.doc()?.doc, &new.name, &new.xml) {
|
||||
let label = if at.is_some() { "Edit SVG Filter" } else { "New SVG Filter" };
|
||||
s.edit(label, |d, _| {
|
||||
update_users(d, &new.name, &new.xml);
|
||||
match at.and_then(|i| d.svg_filters.get_mut(i)) {
|
||||
Some(f) => *f = new,
|
||||
None => d.svg_filters.push(new),
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
let label = if replace.is_some() { "Edit SVG Filter" } else { "New SVG Filter" };
|
||||
s.edit(label, |d, _| {
|
||||
update_users(d, &new.name, &new.xml);
|
||||
match at.and_then(|i| d.svg_filters.get_mut(i)) {
|
||||
Some(f) => *f = new,
|
||||
None => d.svg_filters.push(new),
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "name": name, "filters": filters_json(&s.doc()?.doc) }))
|
||||
}
|
||||
|
||||
@@ -168,6 +184,9 @@ fn delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "svgFilter.delete";
|
||||
let name = name_param(p, C)?;
|
||||
if !s.doc()?.doc.svg_filters.iter().any(|f| f.name == name) {
|
||||
if default_filter(&name).is_some() {
|
||||
return Err(bad(C, format!("{name:?} is a default SVG filter, and the document holds no copy of it to delete")));
|
||||
}
|
||||
return Err(bad(C, format!("the document has no SVG filter named {name:?}")));
|
||||
}
|
||||
s.edit("Delete SVG Filter", |d, _| {
|
||||
@@ -222,13 +241,79 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "svgFilter.apply";
|
||||
let name = name_param(p, C)?;
|
||||
let f = s.doc()?.doc.svg_filters.iter().find(|f| f.name == name).cloned();
|
||||
let f = f.ok_or_else(|| bad(C, format!("the document has no SVG filter named {name:?}")))?;
|
||||
let mut q = json!({ "effect": effects::SVG_FILTER, "params": { "name": f.name, "xml": f.xml } });
|
||||
let filters = &s.doc()?.doc.svg_filters;
|
||||
// The document's filter of that name, or the default of that name, which the document then takes.
|
||||
let (f, copied) = match (filters.iter().find(|f| f.name == name), default_filter(&name)) {
|
||||
(Some(f), _) => (f.clone(), false),
|
||||
(None, Some(_)) if filters.len() >= SvgFilter::MAX => {
|
||||
return Err(bad(C, format!("a document holds at most {} SVG filters, and applying a default filter adds it", SvgFilter::MAX)));
|
||||
}
|
||||
(None, Some(d)) => (d.to_filter(), true),
|
||||
(None, None) => return Err(bad(C, format!("the document has no SVG filter named {name:?}"))),
|
||||
};
|
||||
// A given `index`, null included, is checked as an index: only a missing one adds an effect.
|
||||
let replaces = p.get("index").is_some();
|
||||
let mut q = match replaces {
|
||||
true => json!({ "index": p["index"], "params": { "name": f.name, "xml": f.xml } }),
|
||||
false => json!({ "effect": effects::SVG_FILTER, "params": { "name": f.name, "xml": f.xml } }),
|
||||
};
|
||||
for key in ["ids", "id", "item"] {
|
||||
if let Some(v) = p.get(key) {
|
||||
q[key] = v.clone();
|
||||
}
|
||||
}
|
||||
super::effectcmd::apply(s, &q)
|
||||
if !copied {
|
||||
return apply_as_given(s, p, &q, replaces, None);
|
||||
}
|
||||
// The effect and the copy are two edits joined into one step. The history keeps room for both
|
||||
// until they are joined, so the application lets one old step go at most, as any edit does.
|
||||
let limit = s.doc()?.history.limit;
|
||||
if let Some(st) = s.active_mut() {
|
||||
st.history.limit = limit.saturating_add(2);
|
||||
}
|
||||
let out = apply_as_given(s, p, &q, replaces, Some(f));
|
||||
if let Some(st) = s.active_mut() {
|
||||
st.history.limit = limit;
|
||||
st.history.trim();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// [`apply`] once the filter is known: the effect added (`q`) or put in the applied filter's place
|
||||
/// (`replaces`), and `copy`, a default's copy, added to the document in the same undo step.
|
||||
fn apply_as_given(s: &mut Session, p: &Value, q: &Value, replaces: bool, copy: Option<SvgFilter>) -> Result<Value> {
|
||||
const C: &str = "svgFilter.apply";
|
||||
let newest = s.doc()?.history.step().0;
|
||||
let out = if replaces {
|
||||
super::appearance::index_param(p, "index", C)?;
|
||||
// Only an applied SVG filter gives its place: another effect would take the filter's
|
||||
// parameters as its own.
|
||||
let edited = super::effectcmd::set_params_effects(s, q);
|
||||
if edited.is_empty() || edited.iter().any(|e| e != effects::SVG_FILTER) {
|
||||
return Err(bad(C, "`index` must be the index of an applied SVG filter"));
|
||||
}
|
||||
super::effectcmd::set_params(s, q)?
|
||||
} else {
|
||||
super::effectcmd::apply(s, q)?
|
||||
};
|
||||
if let Some(f) = copy {
|
||||
// The copy joins the step that applied it, under that step's name. That step is found by
|
||||
// its document, not its place: in an undo group both edits join the group's one step.
|
||||
let h = &s.doc()?.history;
|
||||
let applied = h.undo.last().filter(|_| h.step().0 != newest).map(|step| (step.label.clone(), step.doc.clone()));
|
||||
let label = applied.as_ref().map_or_else(|| "SVG Filter".to_string(), |(l, _)| l.clone());
|
||||
s.edit(&label, |d, _| {
|
||||
update_users(d, &f.name, &f.xml);
|
||||
d.svg_filters.push(f);
|
||||
Ok(())
|
||||
})?;
|
||||
let undo = &s.doc()?.history.undo;
|
||||
let below = undo.len().checked_sub(2);
|
||||
if let (Some(at), Some((_, doc))) = (below, &applied)
|
||||
&& undo.get(at).is_some_and(|e| std::sync::Arc::ptr_eq(&e.doc, doc))
|
||||
{
|
||||
super::menucmds::squash(s, at, &label);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -228,6 +228,7 @@ pub fn char_attrs(v: &CharStyle) -> Map<String, Value> {
|
||||
("digits", json!(v.digits)),
|
||||
("fontHeightReference", json!(v.font_height_reference)),
|
||||
("language", json!(v.language)),
|
||||
("glyphForm", json!(v.glyph_form)),
|
||||
] {
|
||||
m.insert(k.into(), x);
|
||||
}
|
||||
|
||||
@@ -140,7 +140,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Character",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour|\"none\", stroke?: colour|\"none\" (characters without a stroke weight get 1 pt; #rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt (the character stroke's weight, in document points as stroke.set), features?: [\"dlig\", \"-liga\", \"salt=2\", …] OpenType (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text; no undo step when no character, paragraph or graph label style changes) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}",
|
||||
"{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour|\"none\", stroke?: colour|\"none\" (characters without a stroke weight get 1 pt; #rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt (the character stroke's weight, in document points as stroke.set), features?: [\"dlig\", \"-liga\", \"salt=2\", …] OpenType (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text; no undo step when no character, paragraph or graph label style changes) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}",
|
||||
has_doc,
|
||||
set_style
|
||||
),
|
||||
|
||||
@@ -1589,6 +1589,40 @@ fn proportional_metrics_is_a_character_attribute_saved_only_when_on() {
|
||||
assert!(!serde_json::from_value::<vectorcraft_doc::CharStyle>(old).unwrap().proportional_metrics);
|
||||
}
|
||||
|
||||
/// H or V Style (`hkna`) and Roman Italics (`ital`, OpenType panel menu, East Asian options) are
|
||||
/// feature tags of the characters: set on a range and turned off again, kept by a character style
|
||||
/// and in a saved document, on or off only (`hkna=2` is refused and changes nothing).
|
||||
#[test]
|
||||
fn kana_style_and_roman_italics_are_character_features() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "かなAB"})).unwrap()["id"].as_u64().unwrap();
|
||||
let runs = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.features.clone())).collect::<Vec<_>>(),
|
||||
_ => panic!("text"),
|
||||
};
|
||||
// か and な are 3 bytes each.
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": 6, "features": ["hkna"]})).unwrap();
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "start": 6, "end": 8, "featureChanges": ["ital"]})).unwrap();
|
||||
assert_eq!(runs(&s), [("かな".to_string(), vec!["hkna".to_string()]), ("AB".to_string(), vec!["ital".to_string()])]);
|
||||
let saved = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
|
||||
let NodeKind::Text(t) = &saved.node(NodeId(id)).unwrap().kind else { panic!("text") };
|
||||
assert_eq!(t.runs.iter().map(|r| r.style.features.clone()).collect::<Vec<_>>(), [vec!["hkna".to_string()], vec!["ital".to_string()]]);
|
||||
let before = runs(&s);
|
||||
for bad in [json!({"id": id, "features": ["hkna=2"]}), json!({"id": id, "featureChanges": ["ital=1"]})] {
|
||||
let e = s.execute("text.setRangeStyle", &bad).unwrap_err().to_string();
|
||||
assert!(e.contains("unknown OpenType feature"), "{e}");
|
||||
}
|
||||
assert_eq!(runs(&s), before);
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "featureChanges": ["-hkna", "-ital"]})).unwrap();
|
||||
assert!(runs(&s).iter().all(|(_, f)| f.is_empty()), "{:?}", runs(&s));
|
||||
s.execute("charStyle.new", &json!({"name": "Kana", "attrs": {"features": ["hkna", "ital"]}})).unwrap();
|
||||
s.execute("charStyle.apply", &json!({"name": "Kana", "id": id})).unwrap();
|
||||
assert!(runs(&s).iter().all(|(_, f)| *f == ["hkna", "ital"]), "{:?}", runs(&s));
|
||||
let e = s.execute("charStyle.new", &json!({"name": "Bad", "attrs": {"features": ["ital=2"]}})).unwrap_err().to_string();
|
||||
assert!(e.contains("unknown OpenType feature `ital=2`"), "{e}");
|
||||
}
|
||||
|
||||
/// Tate-chu-yoko (Character panel menu, East Asian options): a character attribute, saved only
|
||||
/// when on. Documents written before it read as off.
|
||||
#[test]
|
||||
@@ -1925,6 +1959,55 @@ fn standard_vertical_roman_is_a_character_attribute_saved_only_when_on() {
|
||||
assert!(runs(&s).iter().all(|r| !r.style.standard_vertical_roman));
|
||||
}
|
||||
|
||||
/// The East Asian glyph form (Glyphs panel menu) is one character attribute, `glyphForm`: one
|
||||
/// form replaces another, "default" (Revert To Default Forms) takes it away, and it is saved
|
||||
/// only when set. A call that changes nothing records no undo step, an unknown form is refused,
|
||||
/// and character styles carry it.
|
||||
#[test]
|
||||
fn glyph_form_is_one_character_attribute_saved_only_when_set() {
|
||||
use vectorcraft_doc::GlyphForm;
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "亜唖芦"})).unwrap()["id"].as_u64().unwrap();
|
||||
let runs = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => t.runs.clone(),
|
||||
_ => panic!("text"),
|
||||
};
|
||||
let forms = |s: &Session| runs(s).iter().map(|r| (r.text.clone(), r.style.glyph_form)).collect::<Vec<_>>();
|
||||
assert!(serde_json::to_value(&runs(&s)[0].style).unwrap().get("glyphForm").is_none());
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "start": 3, "end": 6, "glyphForm": "jis78"})).unwrap();
|
||||
assert_eq!(forms(&s), [("亜".into(), GlyphForm::Default), ("唖".into(), GlyphForm::Jis78), ("芦".into(), GlyphForm::Default)]);
|
||||
assert_eq!(serde_json::to_value(&runs(&s)[1].style).unwrap()["glyphForm"], "jis78");
|
||||
// Saved and reopened as it was.
|
||||
let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
|
||||
let NodeKind::Text(t) = &back.node(NodeId(id)).unwrap().kind else { panic!("text") };
|
||||
assert_eq!(t.runs.iter().map(|r| (r.text.clone(), r.style.glyph_form)).collect::<Vec<_>>(), forms(&s));
|
||||
// Another form replaces it: one form at a time.
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"glyphForm": "fullWidth"})).unwrap();
|
||||
assert!(runs(&s).iter().all(|r| r.style.glyph_form == GlyphForm::FullWidth));
|
||||
let n = s.doc().unwrap().history.undo.len();
|
||||
s.execute("text.setFormat", &json!({"glyphForm": "fullWidth"})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), n, "nothing changed, no undo step");
|
||||
for bad in [json!("jis2004"), json!(78), json!(true), json!("Traditional")] {
|
||||
let e = s.execute("text.setFormat", &json!({"glyphForm": bad})).unwrap_err().to_string();
|
||||
assert!(e.contains("`glyphForm` must be one of \"traditional\""), "{bad}: {e}");
|
||||
assert!(s.execute("text.setRangeStyle", &json!({"id": id, "glyphForm": bad})).is_err(), "{bad}");
|
||||
}
|
||||
assert!(runs(&s).iter().all(|r| r.style.glyph_form == GlyphForm::FullWidth), "a refused call changes nothing");
|
||||
assert_eq!(super::super::textstyles::char_attrs(&runs(&s)[0].style)["glyphForm"], "fullWidth");
|
||||
s.execute("text.setFormat", &json!({"glyphForm": "default"})).unwrap();
|
||||
assert!(runs(&s).iter().all(|r| r.style.glyph_form == GlyphForm::Default));
|
||||
assert!(serde_json::to_value(&runs(&s)[0].style).unwrap().get("glyphForm").is_none());
|
||||
// A character style carries the form.
|
||||
s.execute("charStyle.new", &json!({"name": "Old forms", "attrs": {"glyphForm": "jis83"}})).unwrap();
|
||||
s.execute("charStyle.apply", &json!({"name": "Old forms", "id": id})).unwrap();
|
||||
assert!(runs(&s).iter().all(|r| r.style.glyph_form == GlyphForm::Jis83));
|
||||
assert!(s.execute("charStyle.new", &json!({"name": "Bad", "attrs": {"glyphForm": "jis2004"}})).is_err());
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(runs(&s).iter().all(|r| r.style.glyph_form == GlyphForm::Default));
|
||||
}
|
||||
|
||||
/// No Break is a character attribute, saved only when on.
|
||||
#[test]
|
||||
fn no_break_is_a_character_attribute_saved_only_when_on() {
|
||||
|
||||
@@ -9,8 +9,8 @@
|
||||
//! before an image variable); import replaces the datasets, names the rows Data Set 1, 2…,
|
||||
//! also reads tab-separated files, and reads header cells that define new variables (`#` for
|
||||
//! visibility, `@` for image, no prefix for text). `variable.loadLibrary` replaces the variables and data sets with the
|
||||
//! text variables and data sets of a variable library, the XML file of the reference app's Save
|
||||
//! Variable Library, and `variable.saveLibrary` writes the text variables and data sets as one.
|
||||
//! 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.
|
||||
//! Agents reach every command through `run_command`, like all engine commands.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
@@ -886,7 +886,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Load Variable Library…",
|
||||
["Window", "Variables"],
|
||||
None,
|
||||
"{path? | xml? | dataBase64?} replace the document's variables and data sets with a variable library's (XML: `variableSets` › `variableSet` › `variables` of `variable` elements with `varName` and `trait`, and `sampleDataSets` of `sampleDataSet` elements with `dataSetName`) in one undo step (none when the document already holds what the library gives). Every data set is deleted, and every variable of the document is deleted with its bindings and values except a text variable the library also declares, which keeps its bindings; then the library's other variables whose `trait` is `textcontent` are defined as text variables, unbound, and each data set takes a value for a variable from the `p` elements of the element named after it, one paragraph each. Variables of other kinds are left out and named in `skipped` and `warning`. Refused while the variables are locked when it would delete or define a variable → {variables, deleted, deletedDataSets, names, skipped, warning?}",
|
||||
"{path? | xml? | dataBase64?} replace the document's variables and data sets with a variable library's (XML: `variableSets` › `variableSet` › `variables` of `variable` elements with `varName` and `trait`, and `sampleDataSets` of `sampleDataSet` elements with `dataSetName`) in one undo step (none when the document already holds what the library gives). Every data set is deleted, and every variable of the document is deleted with its bindings and values except a variable the library also declares with the same kind, which keeps its bindings; then the library's other variables are defined, unbound, with the kind of their `trait`: `textcontent` text, `visibility` visibility, `fileref` image, `graphdata` graph, and any other or none unknown (no values). Each data set takes a variable's value from the element named after it: a text value from its `p` elements, one paragraph each; a visibility value from `true` or `false`; an image value from a file's absolute path or a `file:` URL (the file isn't read); a graph value from a `data` element (`propertyRow` series names, `values` › `row` with a first `value` key=\"name\" category), read as the CSV graph.setData takes. A value that doesn't fit its kind is refused. Refused while the variables are locked when it would delete or define a variable → {variables, deleted, deletedDataSets, names}",
|
||||
has_doc,
|
||||
load_library
|
||||
),
|
||||
@@ -895,7 +895,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Save Variable Library…",
|
||||
["Window", "Variables"],
|
||||
None,
|
||||
"{path?} write the document's text variables and every data set as a variable library, the XML that variable.loadLibrary reads: a `variable` element with `varName` and `trait=\"textcontent\"` per text variable, and a `sampleDataSet` element with `dataSetName` per data set, holding an element named after each text variable it has a value for, with one `p` element per line of the value. Variables of other kinds are left out with their values and named in `skipped` and `warning`. Refused without a text variable, for a text variable whose name isn't an XML name (letters, digits, `-`, `_` and `.`, starting with a letter or `_`), for a data set name or value that holds a control character, for a data set name with white space at either end, for a name longer than 255 characters or used twice, and past variable.loadLibrary's caps (256 variables, 1,000 data sets, 8 MiB). Without path → {xml, variables, datasets, skipped, warning?}; with it → {path, variables, datasets, skipped, warning?}",
|
||||
"{path?} write the document's variables and every data set as a variable library, the XML that variable.loadLibrary reads: a `variable` element with `varName` per variable, with the `trait` of its kind (`textcontent`, `visibility`, `fileref` for image, `graphdata` for graph; none for an unknown kind), and a `sampleDataSet` element with `dataSetName` per data set, holding an element named after each variable it has a value for: one `p` element per line of a text value, `true` or `false`, an image's path (a `file:///` URL for a path from a Unix root), or graph data as a `data` element. Refused without a variable, for a variable whose name isn't an XML name (letters, digits, `-`, `_` and `.`, starting with a letter or `_`; not asked of an unknown kind), for a name or value that holds a control character, for a name with white space at either end, for a name longer than 255 characters or used twice, for an image value that isn't a file's absolute path, and past variable.loadLibrary's caps (256 variables, 1,000 data sets, 8 MiB). Without path → {xml, variables, datasets}; with it → {path, variables, datasets}",
|
||||
has_doc,
|
||||
save_library
|
||||
),
|
||||
|
||||
@@ -1,18 +1,29 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use std::fmt::Write as _;
|
||||
|
||||
use vectorcraft_doc::{GraphSpec, MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES};
|
||||
|
||||
use super::{
|
||||
BTreeMap, BTreeSet, DataSet, DataValue, Document, EngineError, MAX_NAME, NodeId, NodeKind, Result, Session, Value, Variable, VariableKind,
|
||||
Variables, absolute_path, bad, json, named, read_file_head, str_param, variables_unlocked, write_file,
|
||||
BTreeMap, BTreeSet, DataSet, DataValue, Document, EngineError, MAX_GRAPH_CSV, MAX_NAME, NodeId, NodeKind, Result, Session, Value, Variable,
|
||||
VariableKind, Variables, absolute_path, bad, json, named, read_file_head, str_param, variables_unlocked, write_file,
|
||||
};
|
||||
|
||||
/// The namespace of a variable library's elements, the default namespace of its data sets' values,
|
||||
/// and the `category` of its text variables.
|
||||
/// and the `category` of its visibility and image variables.
|
||||
const NS_VARIABLES: &str = "http://ns.adobe.com/Variables/1.0/"; // brand-ok: the namespace variable libraries use
|
||||
|
||||
const NS_CUSTOM: &str = "http://ns.adobe.com/GenericCustomNamespace/1.0/"; // brand-ok: the namespace variable libraries use
|
||||
|
||||
/// The `category` of a library's text variables.
|
||||
const NS_FLOWS: &str = "http://ns.adobe.com/Flows/1.0/"; // brand-ok: the namespace variable libraries use
|
||||
|
||||
/// The `category` of a library's graph variables.
|
||||
const NS_GRAPHS: &str = "http://ns.adobe.com/Graphs/1.0/"; // brand-ok: the namespace variable libraries use
|
||||
|
||||
/// The white space XML puts round a value: a value's text is read without it at either end.
|
||||
const XML_SPACE: [char; 4] = [' ', '\t', '\n', '\r'];
|
||||
|
||||
/// Caps on a variable library (paths and MCP payloads are untrusted): its size, its XML nodes, how
|
||||
/// deep its elements nest, and the entities, variables and data sets it declares.
|
||||
const MAX_LIBRARY_BYTES: usize = 8 << 20;
|
||||
@@ -170,16 +181,47 @@ fn without_doctype(xml: &str, cmd: &str) -> Result<String> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// A variable library as Load Variable Library reads it: the names of its text variables in the
|
||||
/// order it declares them, the name and `trait` of each variable of another kind, its data sets
|
||||
/// with their text values, and the element id each text variable's `docRef` names.
|
||||
/// One variable a library declares: its name, its kind, and its `trait` as the library spells it
|
||||
/// (`None` when it has none).
|
||||
struct LibraryVariable {
|
||||
name: String,
|
||||
kind: VariableKind,
|
||||
trait_name: Option<String>,
|
||||
}
|
||||
|
||||
/// A variable library as Load Variable Library reads it: its variables in the order it declares
|
||||
/// them, its data sets with their values, and the element id each text variable's `docRef` names.
|
||||
pub(crate) struct Library {
|
||||
text: Vec<String>,
|
||||
other: Vec<(String, String)>,
|
||||
variables: Vec<LibraryVariable>,
|
||||
datasets: Vec<DataSet>,
|
||||
refs: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
/// The kind of a library variable whose `trait` is `t`: `textcontent` is text, `visibility` is
|
||||
/// visibility, `fileref` (a linked file) is image and `graphdata` is graph. A variable without a
|
||||
/// `trait`, or with one VectorCraft doesn't know, is of unknown kind.
|
||||
fn trait_kind(t: Option<&str>) -> VariableKind {
|
||||
match t {
|
||||
Some("textcontent") => VariableKind::Text,
|
||||
Some("visibility") => VariableKind::Visibility,
|
||||
Some("fileref") => VariableKind::Image,
|
||||
Some("graphdata") => VariableKind::Graph,
|
||||
_ => VariableKind::Unknown,
|
||||
}
|
||||
}
|
||||
|
||||
/// The `trait` and the `category` reference a library declares a variable of `kind` with, or `None`
|
||||
/// for a variable of unknown kind, which is declared with neither.
|
||||
fn kind_trait(kind: VariableKind) -> Option<(&'static str, &'static str)> {
|
||||
match kind {
|
||||
VariableKind::Text => Some(("textcontent", "&ns_flows;")),
|
||||
VariableKind::Visibility => Some(("visibility", "&ns_vars;")),
|
||||
VariableKind::Image => Some(("fileref", "&ns_vars;")),
|
||||
VariableKind::Graph => Some(("graphdata", "&ns_graphs;")),
|
||||
VariableKind::Unknown => None,
|
||||
}
|
||||
}
|
||||
|
||||
impl Library {
|
||||
/// The element ids the text variables' `docRef`s name.
|
||||
pub(crate) fn elements(&self) -> std::collections::HashSet<String> {
|
||||
@@ -190,13 +232,13 @@ impl Library {
|
||||
/// Read a variable library: XML whose `variableSets` element holds `variableSet` elements, each
|
||||
/// with a `variables` element of `variable` elements (`varName`, `trait`) and a `sampleDataSets`
|
||||
/// element of `sampleDataSet` elements (`dataSetName`). Elements are matched by their local names.
|
||||
/// A variable whose `trait` is `textcontent` is a text variable. In a data set, an element named
|
||||
/// after a text variable gives its value: the text of its `p` elements, one paragraph each, and
|
||||
/// none when it has no `p` element. Values for variables of other kinds are left out. A variable
|
||||
/// or data set declared twice, a value for a variable the library doesn't declare, and a library
|
||||
/// past the caps are refused. Entities that its document type declaration defines are read as
|
||||
/// [`without_doctype`] says.
|
||||
fn parse_library(xml: &str, cmd: &str) -> Result<Library> {
|
||||
/// A variable's kind comes from its `trait` ([`trait_kind`]). In a data set, an element named after
|
||||
/// a variable gives its value, as [`library_value`] reads it. A variable or data set declared
|
||||
/// twice, a value for a variable the library doesn't declare, a value that doesn't fit its
|
||||
/// variable's kind, and a library past the caps are refused. With `text_only`, only text values
|
||||
/// are read, and the values of the other kinds are passed over unread. Entities that its document
|
||||
/// type declaration defines are read as [`without_doctype`] says.
|
||||
fn parse_library(xml: &str, cmd: &str, text_only: bool) -> Result<Library> {
|
||||
let xml = without_doctype(xml, cmd)?;
|
||||
// roxmltree parses nested elements recursively.
|
||||
if crate::cmd::place::docx::nesting(&xml) > MAX_LIBRARY_NESTING {
|
||||
@@ -210,32 +252,29 @@ fn parse_library(xml: &str, cmd: &str) -> Result<Library> {
|
||||
return Err(bad(cmd, "the file holds no `variableSets` element"));
|
||||
};
|
||||
let sets: Vec<roxmltree::Node> = root.children().filter(|n| is(n, "variableSet")).collect();
|
||||
let (mut text, mut other, mut declared, mut refs) = (Vec::new(), Vec::new(), BTreeSet::new(), Vec::new());
|
||||
let (mut variables, mut kinds, mut refs) = (Vec::new(), BTreeMap::new(), Vec::new());
|
||||
for var in sets.iter().flat_map(|s| s.children()).filter(|n| is(n, "variables")).flat_map(|v| v.children()).filter(|n| is(n, "variable")) {
|
||||
let name = named(var.attribute("varName"), "varName", cmd)?;
|
||||
if !declared.insert(name.clone()) {
|
||||
let trait_name = var.attribute("trait").map(|t| t.chars().take(MAX_NAME).collect::<String>());
|
||||
let kind = trait_kind(trait_name.as_deref());
|
||||
if kinds.insert(name.clone(), kind).is_some() {
|
||||
return Err(bad(cmd, format!("variable `{name}` is declared twice")));
|
||||
}
|
||||
if declared.len() > MAX_LIBRARY_VARIABLES {
|
||||
if kinds.len() > MAX_LIBRARY_VARIABLES {
|
||||
return Err(bad(cmd, format!("the variable library declares more than {MAX_LIBRARY_VARIABLES} variables")));
|
||||
}
|
||||
match var.attribute("trait") {
|
||||
Some("textcontent") => {
|
||||
// `docRef="id('…')"` names the element of the variable's bound object.
|
||||
let element = var.attribute("docRef").and_then(|r| r.trim().strip_prefix("id('")?.strip_suffix("')")).filter(|e| !e.is_empty());
|
||||
if let Some(element) = element {
|
||||
refs.push((name.clone(), element.to_string()));
|
||||
}
|
||||
text.push(name);
|
||||
if kind == VariableKind::Text {
|
||||
// `docRef="id('…')"` names the element of the variable's bound object.
|
||||
let element = var.attribute("docRef").and_then(|r| r.trim().strip_prefix("id('")?.strip_suffix("')")).filter(|e| !e.is_empty());
|
||||
if let Some(element) = element {
|
||||
refs.push((name.clone(), element.to_string()));
|
||||
}
|
||||
Some(t) => other.push((name, t.chars().take(MAX_NAME).collect())),
|
||||
None => return Err(bad(cmd, format!("variable `{name}` has no `trait`"))),
|
||||
}
|
||||
variables.push(LibraryVariable { name, kind, trait_name });
|
||||
}
|
||||
if declared.is_empty() {
|
||||
if variables.is_empty() {
|
||||
return Err(bad(cmd, "the variable library declares no variables"));
|
||||
}
|
||||
let text_names: BTreeSet<&str> = text.iter().map(String::as_str).collect();
|
||||
let (mut datasets, mut seen) = (Vec::new(), BTreeSet::new());
|
||||
for row in
|
||||
sets.iter().flat_map(|s| s.children()).filter(|n| is(n, "sampleDataSets")).flat_map(|d| d.children()).filter(|n| is(n, "sampleDataSet"))
|
||||
@@ -250,27 +289,197 @@ fn parse_library(xml: &str, cmd: &str) -> Result<Library> {
|
||||
let (mut values, mut held) = (BTreeMap::new(), BTreeSet::new());
|
||||
for el in row.children().filter(roxmltree::Node::is_element) {
|
||||
let var = el.tag_name().name();
|
||||
if !declared.contains(var) {
|
||||
let Some(kind) = kinds.get(var) else {
|
||||
return Err(bad(cmd, format!("data set `{name}` holds a value for `{var}`, which the library doesn't declare")));
|
||||
}
|
||||
};
|
||||
if !held.insert(var) {
|
||||
return Err(bad(cmd, format!("data set `{name}` holds two values for `{var}`")));
|
||||
}
|
||||
if !text_names.contains(var) {
|
||||
if text_only && *kind != VariableKind::Text {
|
||||
continue;
|
||||
}
|
||||
let paras: Vec<String> = el
|
||||
.children()
|
||||
.filter(|n| is(n, "p"))
|
||||
.map(|p| p.descendants().filter(roxmltree::Node::is_text).filter_map(|t| t.text()).collect())
|
||||
.collect();
|
||||
if !paras.is_empty() {
|
||||
values.insert(var.to_string(), DataValue::Text(paras.join("\n")));
|
||||
if let Some(value) = library_value(el, *kind, &name, cmd)? {
|
||||
values.insert(var.to_string(), value);
|
||||
}
|
||||
}
|
||||
datasets.push(DataSet { name, values });
|
||||
}
|
||||
Ok(Library { text, other, datasets, refs })
|
||||
Ok(Library { variables, datasets, refs })
|
||||
}
|
||||
|
||||
/// The value a data set's element `el` gives a variable of `kind`, or `None` when it gives none.
|
||||
/// A text value is the text of its `p` elements, one paragraph each, and none without a `p`
|
||||
/// element. A visibility value is `true` or `false`, in any case. An image value is the absolute
|
||||
/// path of a file, or a `file:` URL of one ([`library_path`]); the file isn't read. A graph value is
|
||||
/// a `data` element ([`graph_value`]). Visibility, image and graph values are read without the
|
||||
/// white space round them, and an element holding only white space gives none. A variable of
|
||||
/// unknown kind takes no value, so what its element holds is passed over. `set` names the data set
|
||||
/// in the errors.
|
||||
fn library_value(el: roxmltree::Node, kind: VariableKind, set: &str, cmd: &str) -> Result<Option<DataValue>> {
|
||||
let refused = |what: &str| bad(cmd, format!("data set `{set}` holds a value for `{}` that isn't {what}", el.tag_name().name()));
|
||||
let text = || if elements(el).next().is_some() { None } else { Some(deep_text(el)) };
|
||||
match kind {
|
||||
VariableKind::Text => {
|
||||
let paras: Vec<String> = elements(el).filter(|n| n.tag_name().name() == "p").map(deep_text).collect();
|
||||
Ok((!paras.is_empty()).then(|| DataValue::Text(paras.join("\n"))))
|
||||
}
|
||||
VariableKind::Visibility => {
|
||||
let what = "`true` or `false`";
|
||||
let text = text().ok_or_else(|| refused(what))?;
|
||||
match text.trim_matches(XML_SPACE) {
|
||||
"" => Ok(None),
|
||||
t if t.eq_ignore_ascii_case("true") => Ok(Some(DataValue::Visible(true))),
|
||||
t if t.eq_ignore_ascii_case("false") => Ok(Some(DataValue::Visible(false))),
|
||||
_ => Err(refused(what)),
|
||||
}
|
||||
}
|
||||
VariableKind::Image => {
|
||||
let what = "a file's absolute path or `file:` URL";
|
||||
let text = text().ok_or_else(|| refused(what))?;
|
||||
match text.trim_matches(XML_SPACE) {
|
||||
"" => Ok(None),
|
||||
t => library_path(t).map(|p| Some(DataValue::Image(p))).ok_or_else(|| refused(what)),
|
||||
}
|
||||
}
|
||||
VariableKind::Graph => graph_value(el, set, cmd),
|
||||
VariableKind::Unknown => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// The elements among `n`'s children.
|
||||
fn elements<'a, 'i>(n: roxmltree::Node<'a, 'i>) -> impl Iterator<Item = roxmltree::Node<'a, 'i>> {
|
||||
n.children().filter(roxmltree::Node::is_element)
|
||||
}
|
||||
|
||||
/// The text of every text node inside `n`, in order.
|
||||
fn deep_text(n: roxmltree::Node) -> String {
|
||||
n.descendants().filter(roxmltree::Node::is_text).filter_map(|t| t.text()).collect()
|
||||
}
|
||||
|
||||
/// The absolute path a library's image value `text` names: a `file:` URL's path (`file:///…`,
|
||||
/// `file://localhost/…` or `file:/…`), its `%XX` escapes decoded (a URL with a host names a share,
|
||||
/// `//host/…`), or `text` itself. `None` unless that is an absolute path: one starting with `/` or
|
||||
/// `\\`, or a drive's path from its root (`C:\…`, `C:/…`).
|
||||
fn library_path(text: &str) -> Option<String> {
|
||||
let drive = |p: &str| matches!(p.as_bytes(), [l, b':', b'\\' | b'/', ..] if l.is_ascii_alphabetic());
|
||||
let url = match (text.strip_prefix("file://"), text.strip_prefix("file:")) {
|
||||
(Some(rest), _) => Some(rest.strip_prefix("localhost").filter(|r| r.starts_with('/')).unwrap_or(rest)),
|
||||
// `file:/…` names a path without a host.
|
||||
(None, Some(rest)) if rest.starts_with('/') => Some(rest),
|
||||
_ => None,
|
||||
};
|
||||
let path = match url {
|
||||
Some(rest) => {
|
||||
if rest.starts_with('/') {
|
||||
let p = percent_decoded(rest.trim_start_matches('/'));
|
||||
if drive(&p) { p } else { format!("/{p}") }
|
||||
} else {
|
||||
format!("//{}", percent_decoded(rest))
|
||||
}
|
||||
}
|
||||
None => text.to_string(),
|
||||
};
|
||||
(path.len() > 1 && (path.starts_with('/') || path.starts_with("\\\\") || drive(&path))).then_some(path)
|
||||
}
|
||||
|
||||
/// `s` with its `%XX` escapes decoded, or as it is when the decoded bytes aren't UTF-8.
|
||||
fn percent_decoded(s: &str) -> String {
|
||||
let hex = |b: u8| char::from(b).to_digit(16);
|
||||
let (mut out, mut rest) = (Vec::with_capacity(s.len()), s.as_bytes());
|
||||
while let Some((&b, tail)) = rest.split_first() {
|
||||
match tail {
|
||||
[h, l, more @ ..] if b == b'%' && hex(*h).is_some() && hex(*l).is_some() => {
|
||||
out.push(((hex(*h).unwrap_or(0) << 4) | hex(*l).unwrap_or(0)) as u8);
|
||||
rest = more;
|
||||
}
|
||||
_ => {
|
||||
out.push(b);
|
||||
rest = tail;
|
||||
}
|
||||
}
|
||||
}
|
||||
String::from_utf8(out).unwrap_or_else(|_| s.to_string())
|
||||
}
|
||||
|
||||
/// How a library writes the image value `path`: an absolute path from the root of a Unix file
|
||||
/// system as a `file:` URL (`file:///` and the path, with `%`, `#`, `?`, spaces, controls and
|
||||
/// bytes past ASCII escaped), any other path as it is. [`library_path`] reads it back.
|
||||
fn library_file(path: &str) -> String {
|
||||
if !path.starts_with('/') || path.starts_with("//") {
|
||||
return path.to_string();
|
||||
}
|
||||
let mut url = String::from("file:///");
|
||||
for &b in path.as_bytes() {
|
||||
if matches!(b, b'%' | b'#' | b'?') || !(0x21..=0x7e).contains(&b) {
|
||||
let _ = write!(url, "%{b:02X}");
|
||||
} else {
|
||||
url.push(char::from(b));
|
||||
}
|
||||
}
|
||||
url
|
||||
}
|
||||
|
||||
/// A library's graph value: the `data` element that `el` holds, read as CSV of the kind Graph
|
||||
/// Data takes. Its `propertyRow` holds a corner cell and then the names of the series, and each
|
||||
/// `row` of its `values` holds the row's category in a first `value` whose `key` is `name`, then
|
||||
/// the row's values. The graph has categories when a row's name isn't blank or is marked
|
||||
/// `type="string"`. Labels are read as they are; a value is read without the white space round it,
|
||||
/// and one that is empty, marked `type="string"` or not a finite number is a blank. Without rows or
|
||||
/// series, or when `el` holds only white space, there is no value. Anything else in `el`, more than
|
||||
/// [`MAX_GRAPH_CATEGORIES`] rows or [`MAX_GRAPH_SERIES`] series (what a graph holds), and CSV longer
|
||||
/// than graph values hold, are refused.
|
||||
fn graph_value(el: roxmltree::Node, set: &str, cmd: &str) -> Result<Option<DataValue>> {
|
||||
let var = el.tag_name().name();
|
||||
let refused = || bad(cmd, format!("data set `{set}` holds a value for `{var}` that isn't a graph's `data` element"));
|
||||
let named = |name: &'static str| move |n: &roxmltree::Node| n.tag_name().name() == name;
|
||||
let mut children = elements(el);
|
||||
let data = match (children.next(), children.next()) {
|
||||
(None, _) if deep_text(el).trim_matches(XML_SPACE).is_empty() => return Ok(None),
|
||||
(Some(data), None) if data.tag_name().name() == "data" => data,
|
||||
_ => return Err(refused()),
|
||||
};
|
||||
// Labels keep their white space; numbers are read without it.
|
||||
let series: Vec<String> =
|
||||
elements(data).find(named("propertyRow")).map(|r| elements(r).filter(named("value")).skip(1).map(deep_text).collect()).unwrap_or_default();
|
||||
let rows: Vec<roxmltree::Node> =
|
||||
elements(data).filter(named("values")).flat_map(elements).filter(named("row")).take(MAX_GRAPH_CATEGORIES + 1).collect();
|
||||
if rows.is_empty() && series.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let too_many = || bad(cmd, format!("data set `{set}` holds a graph value for `{var}` with {}", graph_limits()));
|
||||
// A row's values after its name.
|
||||
let wide = |row: &roxmltree::Node| {
|
||||
let mut values = elements(*row).filter(named("value")).peekable();
|
||||
let _name = values.next_if(|v| v.attribute("key") == Some("name"));
|
||||
values.count() > MAX_GRAPH_SERIES
|
||||
};
|
||||
if rows.len() > MAX_GRAPH_CATEGORIES || series.len() > MAX_GRAPH_SERIES || rows.iter().any(wide) {
|
||||
return Err(too_many());
|
||||
}
|
||||
// Each row's name and the values after it. A blank name marked `type="string"` is a blank
|
||||
// category, so a graph whose categories are all blank keeps them.
|
||||
let mut labelled = false;
|
||||
let read: Vec<(Option<String>, Vec<Option<f64>>)> = rows
|
||||
.iter()
|
||||
.map(|row| {
|
||||
let mut values = elements(*row).filter(named("value")).peekable();
|
||||
let name = values.next_if(|v| v.attribute("key") == Some("name"));
|
||||
labelled |= name.is_some_and(|v| v.attribute("type") == Some("string") || !deep_text(v).is_empty());
|
||||
let name = name.map(deep_text);
|
||||
let number = |v: roxmltree::Node| deep_text(v).trim_matches(XML_SPACE).parse::<f64>().ok().filter(|n| n.is_finite());
|
||||
let numbers = values.map(|v| if v.attribute("type") == Some("string") { None } else { number(v) });
|
||||
(name, numbers.collect())
|
||||
})
|
||||
.collect();
|
||||
let categories = if labelled { read.iter().map(|(name, _)| name.clone().unwrap_or_default()).collect() } else { vec![] };
|
||||
let mut spec = GraphSpec { series, categories, ..GraphSpec::default() };
|
||||
spec.set_cells(read.into_iter().map(|(_, numbers)| numbers).collect());
|
||||
// Data set values hold graph data without the line break at its end.
|
||||
let csv = spec.to_csv().trim_end().to_string();
|
||||
if csv.len() > MAX_GRAPH_CSV {
|
||||
return Err(bad(cmd, format!("data set `{set}` holds a graph value for `{var}` longer than {MAX_GRAPH_CSV} bytes")));
|
||||
}
|
||||
Ok(Some(DataValue::Graph(csv)))
|
||||
}
|
||||
|
||||
/// The variable library an SVG carries (SVG Options › Include Variable Data), read as
|
||||
@@ -317,7 +526,8 @@ pub(crate) fn svg_library(svg: &str) -> Option<Result<Library>> {
|
||||
for (name, value) in &entities {
|
||||
element = element.replace(name.as_str(), value);
|
||||
}
|
||||
parse_library(&format!("<svg>{element}</svg>"), C)
|
||||
// The SVG keeps only the text variables, so the values of the other kinds aren't read.
|
||||
parse_library(&format!("<svg>{element}</svg>"), C, true)
|
||||
};
|
||||
Some(read())
|
||||
}
|
||||
@@ -389,12 +599,16 @@ fn variable_sets_range(svg: &str) -> Option<(usize, Option<usize>)> {
|
||||
/// the type object made of the element its `docRef` names, or the one type object among the
|
||||
/// objects a group made of it holds (`found`: the object made of each element, by id). A `docRef`
|
||||
/// that names no type object, or one another variable is bound to already, binds nothing. The art
|
||||
/// stays as the file draws it. The warning about the variables of other kinds that were left out,
|
||||
/// if any.
|
||||
/// stays as the file draws it. Variables of other kinds are left out with their values. The
|
||||
/// warning about those variables, if any.
|
||||
pub(crate) fn give_svg_library(doc: &mut Document, lib: Library, found: &HashMap<String, NodeId>) -> Option<String> {
|
||||
let (text, other): (Vec<LibraryVariable>, Vec<LibraryVariable>) = lib.variables.into_iter().partition(|v| v.kind == VariableKind::Text);
|
||||
let mut vars =
|
||||
Variables { variables: lib.text.iter().map(|n| Variable { name: n.clone(), kind: VariableKind::Text }).collect(), ..Variables::default() };
|
||||
Variables { variables: text.iter().map(|v| Variable { name: v.name.clone(), kind: VariableKind::Text }).collect(), ..Variables::default() };
|
||||
vars.datasets = lib.datasets;
|
||||
for ds in &mut vars.datasets {
|
||||
ds.values.retain(|_, v| matches!(v, DataValue::Text(_)));
|
||||
}
|
||||
// A type object written with a paint of its own, or with fills and strokes of its appearance,
|
||||
// is a group around its text (and the appearance's paths).
|
||||
let text_of = |id: NodeId| match doc.node(id).map(|n| &n.kind) {
|
||||
@@ -415,32 +629,32 @@ pub(crate) fn give_svg_library(doc: &mut Document, lib: Library, found: &HashMap
|
||||
}
|
||||
}
|
||||
doc.variables = vars.into();
|
||||
left_out_warning(lib.other.iter().map(|(_, t)| t.as_str()))
|
||||
left_out_warning(other.iter().map(|v| v.trait_name.as_deref().unwrap_or_else(|| v.kind.label())))
|
||||
}
|
||||
|
||||
/// Load Variable Library: replace the document's variables and data sets with a variable library's
|
||||
/// ([`parse_library`]) in one undo step, or none when the document already holds what the library
|
||||
/// gives. Every data set is deleted, and every variable of the document is deleted with its
|
||||
/// bindings and values, except a text variable the library also declares: it stays bound to its
|
||||
/// objects, so the library's data sets change them (#4136; a template's bound variables take a
|
||||
/// library of the same names:
|
||||
/// bindings and values, except a variable the library also declares with the same kind: it stays
|
||||
/// bound to its objects, so the library's data sets change them (#4136; a template's bound
|
||||
/// variables take a library of the same names:
|
||||
/// <https://community.adobe.com/questions-652/illustrator-error-with-csv-files-812184>). The
|
||||
/// library's other text variables are then defined, unbound, and its data sets are added. The
|
||||
/// library's variables of other kinds are left out, named in `skipped` and in a warning.
|
||||
/// library's other variables are then defined with their kinds, unbound, and its data sets are
|
||||
/// added.
|
||||
pub(super) fn load_library(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "variable.loadLibrary";
|
||||
let bytes = library_bytes(p, C)?;
|
||||
let xml = std::str::from_utf8(bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(&bytes)).map_err(|_| bad(C, "the variable library is not UTF-8"))?;
|
||||
let lib = parse_library(xml, C)?;
|
||||
let lib = parse_library(xml, C, false)?;
|
||||
let vars = &s.doc()?.doc.variables;
|
||||
let kept = |v: &Variable| v.kind == VariableKind::Text && lib.text.contains(&v.name);
|
||||
let kept = |v: &Variable| lib.variables.iter().any(|l| l.name == v.name && l.kind == v.kind);
|
||||
let deleted: Vec<String> = vars.variables.iter().filter(|v| !kept(v)).map(|v| v.name.clone()).collect();
|
||||
let deleted_sets: Vec<String> = vars.datasets.iter().map(|d| d.name.clone()).collect();
|
||||
let added: Vec<Variable> = lib
|
||||
.text
|
||||
.variables
|
||||
.iter()
|
||||
.filter(|n| !vars.variables.iter().any(|v| kept(v) && &v.name == *n))
|
||||
.map(|n| Variable { name: n.clone(), kind: VariableKind::Text })
|
||||
.filter(|l| !vars.variables.iter().any(|v| kept(v) && v.name == l.name))
|
||||
.map(|l| Variable { name: l.name.clone(), kind: l.kind })
|
||||
.collect();
|
||||
// Lock Variables refuses New Variable and Delete Variable, so the load is refused when it would
|
||||
// delete or define a variable.
|
||||
@@ -460,14 +674,8 @@ pub(super) fn load_library(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let st = s.doc_mut()?;
|
||||
st.drop_stale_variables_highlight();
|
||||
st.revision += 1;
|
||||
let skipped: Vec<Value> = lib.other.iter().map(|(name, t)| json!({"name": name, "trait": t})).collect();
|
||||
let mut out = json!({
|
||||
"variables": lib.text, "deleted": deleted, "deletedDataSets": deleted_sets, "names": names, "skipped": skipped,
|
||||
});
|
||||
if let Some(warning) = left_out_warning(lib.other.iter().map(|(_, t)| t.as_str())) {
|
||||
out["warning"] = json!(warning);
|
||||
}
|
||||
Ok(out)
|
||||
let declared: Vec<&str> = lib.variables.iter().map(|l| l.name.as_str()).collect();
|
||||
Ok(json!({"variables": declared, "deleted": deleted, "deletedDataSets": deleted_sets, "names": names}))
|
||||
}
|
||||
|
||||
/// The warning about variables that aren't text and were left out, given the kind of each: every
|
||||
@@ -533,26 +741,95 @@ fn push_escaped(out: &mut String, c: char, attribute: bool) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Save Variable Library: the document's text variables and its data sets as a variable library in
|
||||
/// the layout [`parse_library`] reads, so Load Variable Library reads back the same text variables,
|
||||
/// data set names and text values. A text value is written as one `p` element per line. Variables
|
||||
/// of other kinds are left out with their values, named in `skipped` and in a warning. A text
|
||||
/// variable whose name can't name an element ([`element_name`]), a data set name or text value that
|
||||
/// holds a character XML can't hold, a name that Load Variable Library would read differently or
|
||||
/// refuse (white space at either end of a data set name, a name longer than `MAX_NAME` characters,
|
||||
/// a name used twice), and a library past the caps Load Variable Library reads are refused. With `path` the library is written to the file; without it the reply carries it as
|
||||
/// `xml`.
|
||||
/// Add the graph value `csv` of the variable `var` to `xml` as the `data` element [`graph_value`]
|
||||
/// reads: the CSV read as Graph Data reads it, a `propertyRow` with a blank corner cell and the
|
||||
/// series names when it names series, and a `row` per category, its name in a first `value` with
|
||||
/// `key="name"` (blank without categories) and then a `value` per series, blank where the row has
|
||||
/// none. A label that isn't a number is marked `type="string"`, and so is a blank category. CSV
|
||||
/// that names series and has no rows is written as the `propertyRow` alone. Refused for CSV with
|
||||
/// neither rows nor series, which reads back as no value, for more than [`MAX_GRAPH_CATEGORIES`]
|
||||
/// rows or [`MAX_GRAPH_SERIES`] series (what a graph holds), when a label holds a character XML
|
||||
/// can't hold, and when `xml` grows past `room` bytes.
|
||||
fn push_graph(xml: &mut String, var: &str, csv: &str, room: usize) -> std::result::Result<(), GraphRefusal> {
|
||||
let (series, categories, rows) = super::super::graph::parse_csv(csv);
|
||||
if rows.is_empty() && series.is_empty() {
|
||||
return Err(GraphRefusal::Empty);
|
||||
}
|
||||
let width = rows.iter().map(Vec::len).max().unwrap_or(0).max(series.len());
|
||||
if rows.len() > MAX_GRAPH_CATEGORIES || width > MAX_GRAPH_SERIES {
|
||||
return Err(GraphRefusal::TooMany);
|
||||
}
|
||||
if !series.iter().chain(&categories).all(|l| l.chars().all(xml_char)) {
|
||||
return Err(GraphRefusal::Control);
|
||||
}
|
||||
let labelled = !categories.is_empty();
|
||||
let label = |l: &str, category: bool| {
|
||||
let text = !l.is_empty() && l.trim().parse::<f64>().is_err();
|
||||
let blank_category = category && labelled && l.is_empty();
|
||||
let key = if category { " key=\"name\"" } else { "" };
|
||||
let string = if text || blank_category { " type=\"string\"" } else { "" };
|
||||
format!("<value{key}{string}>{}</value>", escaped(l, false))
|
||||
};
|
||||
let _ = writeln!(xml, "\t\t\t\t<{var}>\n\t\t\t\t\t<data numDataColumns=\"{}\">", width + usize::from(labelled));
|
||||
if !series.is_empty() {
|
||||
let names: String = (0..width).map(|s| label(series.get(s).map(String::as_str).unwrap_or_default(), false)).collect();
|
||||
let _ = writeln!(xml, "\t\t\t\t\t\t<propertyRow key=\"name\"><value></value>{names}</propertyRow>");
|
||||
}
|
||||
xml.push_str("\t\t\t\t\t\t<values>\n");
|
||||
for (i, row) in rows.iter().enumerate() {
|
||||
let name = label(categories.get(i).map(String::as_str).unwrap_or_default(), true);
|
||||
let values: String = (0..width)
|
||||
.map(|s| match row.get(s).copied().flatten() {
|
||||
Some(v) => format!("<value>{v}</value>"),
|
||||
None => "<value></value>".to_string(),
|
||||
})
|
||||
.collect();
|
||||
let _ = writeln!(xml, "\t\t\t\t\t\t\t<row>{name}{values}</row>");
|
||||
if xml.len() > room {
|
||||
return Err(GraphRefusal::TooLarge);
|
||||
}
|
||||
}
|
||||
let _ = writeln!(xml, "\t\t\t\t\t\t</values>\n\t\t\t\t\t</data>\n\t\t\t\t</{var}>");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// What a graph holds at most, for the errors about graph data past it.
|
||||
fn graph_limits() -> String {
|
||||
format!("more than {MAX_GRAPH_CATEGORIES} rows or {MAX_GRAPH_SERIES} series, which a graph doesn't hold")
|
||||
}
|
||||
|
||||
/// Why [`push_graph`] refused a graph value.
|
||||
enum GraphRefusal {
|
||||
/// A label holds a character XML can't hold.
|
||||
Control,
|
||||
/// The data has more rows or series than a graph holds.
|
||||
TooMany,
|
||||
/// The data has neither rows nor series.
|
||||
Empty,
|
||||
/// The library grew past the room it has.
|
||||
TooLarge,
|
||||
}
|
||||
|
||||
/// Save Variable Library: the document's variables and its data sets as a variable library in the
|
||||
/// layout [`parse_library`] reads, so Load Variable Library reads back the same variables with their
|
||||
/// kinds, data set names and values. Each variable is declared with the `trait` and `category` of
|
||||
/// its kind ([`kind_trait`]), and a variable of unknown kind with neither. A text value is written
|
||||
/// as one `p` element per line, a visibility value as `true` or `false`, an image value as
|
||||
/// [`library_file`] writes its path, and a graph value as a `data` element ([`push_graph`]). A
|
||||
/// variable whose name can't name an element ([`element_name`]; a variable of unknown kind has no
|
||||
/// values, so no element is named after it), a name or value that holds a character XML can't
|
||||
/// hold, a name that Load Variable Library would read differently or refuse (white space at either
|
||||
/// end, a name longer than `MAX_NAME` characters, a name used twice), an image value that isn't a
|
||||
/// file's absolute path, and a library past the caps Load Variable Library reads are refused. With
|
||||
/// `path` the library is written to the file; without it the reply carries it as `xml`.
|
||||
pub(super) fn save_library(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "variable.saveLibrary";
|
||||
let vars = &s.doc()?.doc.variables;
|
||||
if vars.variables.is_empty() {
|
||||
return Err(bad(C, "define a variable first"));
|
||||
}
|
||||
let (text, other): (Vec<&Variable>, Vec<&Variable>) = vars.variables.iter().partition(|v| v.kind == VariableKind::Text);
|
||||
if text.is_empty() {
|
||||
return Err(bad(C, "a variable library holds text variables, and the document has none"));
|
||||
}
|
||||
if let Some(name) = text.iter().map(|v| &v.name).find(|n| !element_name(n)) {
|
||||
let all: Vec<&Variable> = vars.variables.iter().collect();
|
||||
if let Some(name) = all.iter().filter(|v| v.kind != VariableKind::Unknown).map(|v| &v.name).find(|n| !element_name(n)) {
|
||||
return Err(bad(
|
||||
C,
|
||||
format!(
|
||||
@@ -560,48 +837,62 @@ pub(super) fn save_library(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
),
|
||||
));
|
||||
}
|
||||
// Load Variable Library refuses a name longer than `MAX_NAME` characters and a name declared
|
||||
// twice.
|
||||
// Load Variable Library reads a name trimmed and refuses one longer than `MAX_NAME` characters
|
||||
// or declared twice.
|
||||
let mut declared = BTreeSet::new();
|
||||
for v in &text {
|
||||
named(Some(&v.name), "varName", C)?;
|
||||
for v in &all {
|
||||
if named(Some(&v.name), "varName", C)? != v.name || !v.name.chars().all(xml_char) {
|
||||
return Err(bad(
|
||||
C,
|
||||
format!("variable `{}` starts or ends with white space or holds a control character, which a variable library can't hold", v.name),
|
||||
));
|
||||
}
|
||||
if !declared.insert(v.name.as_str()) {
|
||||
return Err(bad(C, format!("variable `{}` is already defined", v.name)));
|
||||
}
|
||||
}
|
||||
if text.len() > MAX_LIBRARY_VARIABLES {
|
||||
if all.len() > MAX_LIBRARY_VARIABLES {
|
||||
return Err(bad(C, format!("the variable library declares more than {MAX_LIBRARY_VARIABLES} variables")));
|
||||
}
|
||||
if vars.datasets.len() > MAX_LIBRARY_DATASETS {
|
||||
return Err(bad(C, format!("the variable library declares more than {MAX_LIBRARY_DATASETS} data sets")));
|
||||
}
|
||||
fn text_value<'a>(ds: &'a DataSet, var: &str) -> Option<&'a str> {
|
||||
match ds.values.get(var) {
|
||||
Some(DataValue::Text(t)) => Some(t.as_str()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
let mut xml = format!(
|
||||
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n\
|
||||
<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\" [\n\
|
||||
\t<!ENTITY ns_vars \"{NS_VARIABLES}\">\n\
|
||||
\t<!ENTITY ns_custom \"{NS_CUSTOM}\">\n\
|
||||
\t<!ENTITY ns_flows \"{NS_FLOWS}\">\n\
|
||||
\t<!ENTITY ns_graphs \"{NS_GRAPHS}\">\n\
|
||||
]>\n\
|
||||
<svg>\n\
|
||||
<variableSets xmlns=\"&ns_vars;\">\n\
|
||||
\t<variableSet varSetName=\"binding1\" locked=\"none\">\n\
|
||||
\t\t<variables>\n"
|
||||
);
|
||||
for v in &text {
|
||||
xml += &format!("\t\t\t<variable varName=\"{}\" trait=\"textcontent\" category=\"&ns_flows;\"></variable>\n", v.name);
|
||||
for v in &all {
|
||||
let name = escaped(&v.name, true);
|
||||
match kind_trait(v.kind) {
|
||||
Some((t, category)) => xml += &format!("\t\t\t<variable varName=\"{name}\" trait=\"{t}\" category=\"{category}\"></variable>\n"),
|
||||
None => xml += &format!("\t\t\t<variable varName=\"{name}\"></variable>\n"),
|
||||
}
|
||||
}
|
||||
xml += "\t\t</variables>\n\t\t<v:sampleDataSets xmlns:v=\"&ns_vars;\" xmlns=\"&ns_custom;\">\n";
|
||||
// Load Variable Library caps the file and the text its entity references expand to: one
|
||||
// `&ns_flows;` per variable, two `&ns_vars;` and one `&ns_custom;`. The library stays within
|
||||
// the cap less what the references add.
|
||||
// Load Variable Library caps the file and the text its entity references expand to: each
|
||||
// variable's `category`, two `&ns_vars;` and one `&ns_custom;`. The library stays within the
|
||||
// cap less what the references add.
|
||||
let grows = |value: &str, reference: &str| value.len().saturating_sub(reference.len());
|
||||
let growth = text.len() * grows(NS_FLOWS, "&ns_flows;") + 2 * grows(NS_VARIABLES, "&ns_vars;") + grows(NS_CUSTOM, "&ns_custom;");
|
||||
let growth = all
|
||||
.iter()
|
||||
.filter_map(|v| kind_trait(v.kind))
|
||||
.map(|(_, category)| match category {
|
||||
"&ns_flows;" => grows(NS_FLOWS, category),
|
||||
"&ns_graphs;" => grows(NS_GRAPHS, category),
|
||||
_ => grows(NS_VARIABLES, category),
|
||||
})
|
||||
.sum::<usize>()
|
||||
+ 2 * grows(NS_VARIABLES, "&ns_vars;")
|
||||
+ grows(NS_CUSTOM, "&ns_custom;");
|
||||
let room = MAX_LIBRARY_BYTES.saturating_sub(growth);
|
||||
let too_large = || bad(C, format!("the variable library is larger than {MAX_LIBRARY_BYTES} bytes"));
|
||||
let mut seen = BTreeSet::new();
|
||||
@@ -615,25 +906,61 @@ pub(super) fn save_library(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !seen.insert(name.as_str()) {
|
||||
return Err(bad(C, format!("dataset `{name}` already exists")));
|
||||
}
|
||||
if !name.chars().all(xml_char) || text.iter().filter_map(|v| text_value(ds, &v.name)).any(|t| !t.chars().all(xml_char)) {
|
||||
return Err(bad(C, format!("data set `{name}` holds a control character, which a variable library can't hold")));
|
||||
let control = || bad(C, format!("data set `{name}` holds a control character, which a variable library can't hold"));
|
||||
let mut text_values = all.iter().filter_map(|v| match ds.values.get(&v.name) {
|
||||
Some(DataValue::Text(t)) if v.kind == VariableKind::Text => Some(t),
|
||||
_ => None,
|
||||
});
|
||||
if !name.chars().all(xml_char) || text_values.any(|t| !t.chars().all(xml_char)) {
|
||||
return Err(control());
|
||||
}
|
||||
xml += &format!("\t\t\t<v:sampleDataSet dataSetName=\"{}\">\n", escaped(name, true));
|
||||
for v in &text {
|
||||
let Some(t) = text_value(ds, &v.name) else { continue };
|
||||
xml += &format!("\t\t\t\t<{}>\n", v.name);
|
||||
for line in t.split('\n') {
|
||||
xml += "\t\t\t\t\t<p>";
|
||||
// A value can be larger than the cap, so the text stops growing once it passes it.
|
||||
for c in line.chars() {
|
||||
push_escaped(&mut xml, c, false);
|
||||
if xml.len() > room {
|
||||
return Err(too_large());
|
||||
for v in &all {
|
||||
let Some(value) = ds.values.get(&v.name).filter(|value| value.fits(v.kind)) else { continue };
|
||||
let var = &v.name;
|
||||
match value {
|
||||
DataValue::Text(t) => {
|
||||
xml += &format!("\t\t\t\t<{var}>\n");
|
||||
for line in t.split('\n') {
|
||||
xml += "\t\t\t\t\t<p>";
|
||||
// A value can be larger than the cap, so the text stops growing once it passes it.
|
||||
for c in line.chars() {
|
||||
push_escaped(&mut xml, c, false);
|
||||
if xml.len() > room {
|
||||
return Err(too_large());
|
||||
}
|
||||
}
|
||||
xml += "</p>\n";
|
||||
}
|
||||
xml += &format!("\t\t\t\t</{var}>\n");
|
||||
}
|
||||
xml += "</p>\n";
|
||||
DataValue::Visible(shown) => xml += &format!("\t\t\t\t<{var}>{shown}</{var}>\n"),
|
||||
DataValue::Image(path) => {
|
||||
// Load Variable Library reads back only a file's absolute path.
|
||||
let file = library_file(path);
|
||||
if library_path(file.trim_matches(XML_SPACE)).as_deref() != Some(path.as_str()) {
|
||||
return Err(bad(C, format!("data set `{name}` holds an image value for `{var}` that isn't a file's absolute path")));
|
||||
}
|
||||
if !file.chars().all(xml_char) {
|
||||
return Err(control());
|
||||
}
|
||||
xml += &format!("\t\t\t\t<{var}>{}</{var}>\n", escaped(&file, false));
|
||||
}
|
||||
DataValue::Graph(csv) => match push_graph(&mut xml, var, csv, room) {
|
||||
Ok(()) => {}
|
||||
Err(GraphRefusal::Control) => return Err(control()),
|
||||
Err(GraphRefusal::TooMany) => {
|
||||
return Err(bad(C, format!("data set `{name}` holds a graph value for `{var}` with {}", graph_limits())));
|
||||
}
|
||||
Err(GraphRefusal::Empty) => {
|
||||
return Err(bad(C, format!("data set `{name}` holds a graph value for `{var}` without rows or series")));
|
||||
}
|
||||
Err(GraphRefusal::TooLarge) => return Err(too_large()),
|
||||
},
|
||||
}
|
||||
if xml.len() > room {
|
||||
return Err(too_large());
|
||||
}
|
||||
xml += &format!("\t\t\t\t</{}>\n", v.name);
|
||||
}
|
||||
xml += "\t\t\t</v:sampleDataSet>\n";
|
||||
if xml.len() > room {
|
||||
@@ -644,13 +971,7 @@ pub(super) fn save_library(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if xml.len() > room {
|
||||
return Err(too_large());
|
||||
}
|
||||
let skipped: Vec<Value> = other.iter().map(|v| json!({"name": v.name, "kind": v.kind.label()})).collect();
|
||||
let mut out = json!({
|
||||
"variables": text.iter().map(|v| v.name.as_str()).collect::<Vec<_>>(), "datasets": vars.datasets.len(), "skipped": skipped,
|
||||
});
|
||||
if let Some(warning) = left_out_warning(other.iter().map(|v| v.kind.label())) {
|
||||
out["warning"] = json!(warning);
|
||||
}
|
||||
let mut out = json!({"variables": all.iter().map(|v| v.name.as_str()).collect::<Vec<_>>(), "datasets": vars.datasets.len()});
|
||||
match str_param(p, "path") {
|
||||
Some(path) => {
|
||||
let path = absolute_path(path);
|
||||
|
||||
@@ -24,6 +24,8 @@ impl Session {
|
||||
});
|
||||
// Clicks find an image's own fills and strokes where their effects draw them.
|
||||
vectorcraft_doc::hit::set_image_paint(vectorcraft_render::effects::image_paint);
|
||||
// Clicks inside a clip group fall in the region its clipping path's effects give it.
|
||||
vectorcraft_doc::hit::set_clip_region(vectorcraft_render::effects::reshaped_clip_outline);
|
||||
// Clicks find a blend's steps and an envelope's distorted art where the canvas draws them,
|
||||
// evaluated again when the fonts, the hyphenation exceptions or the plug-ins change.
|
||||
vectorcraft_doc::hit::set_live_art(vectorcraft_render::effects::expand_live, || {
|
||||
|
||||
@@ -1293,7 +1293,12 @@ fn a_transform_that_moves_nothing_records_no_undo_step() {
|
||||
for (id, p) in calls {
|
||||
assert_eq!(s.execute(id, &p).unwrap(), json!({"ids": [a.0]}), "{id} {p}");
|
||||
assert_eq!(history(&s), before, "{id} {p}");
|
||||
assert_eq!(s.journal.last().unwrap(), &(id.to_string(), p));
|
||||
// The journal adds the frame a scale acted in, so a replay acts in the same one.
|
||||
let mut recorded = p;
|
||||
if id == "object.scale" {
|
||||
recorded["basis"] = json!("box");
|
||||
}
|
||||
assert_eq!(s.journal.last().unwrap(), &(id.to_string(), recorded));
|
||||
}
|
||||
assert_eq!(
|
||||
s.doc().unwrap().last_transform,
|
||||
|
||||
@@ -218,6 +218,39 @@ fn reverse_path_direction_turns_the_width_profile_and_pen_records_with_the_path(
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reverse_path_direction_turns_a_compound_paths_own_width_profile_and_pen_records() {
|
||||
use vectorcraft_doc::{AngleProfile, PressureProfile, WidthProfile};
|
||||
let mut s = session();
|
||||
let (a, b) = (rect(&mut s, 0.0), rect(&mut s, 50.0));
|
||||
run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
|
||||
run(&mut s, "object.compoundPath.make", json!({}));
|
||||
let compound = s.doc().unwrap().selection.objects[0];
|
||||
// A lone rectangle of the same shape, whose strokes Reverse Path Direction already turns.
|
||||
let lone = rect(&mut s, 0.0);
|
||||
let profile = WidthProfile { points: vec![(0.0, 0.2, 0.6), (0.3, 1.0, 0.4), (1.0, 0.5, 0.9)] };
|
||||
let pressure = PressureProfile { points: vec![(0.0, 0.1), (0.25, 0.9), (1.0, 0.4)] };
|
||||
let bearing = AngleProfile { points: vec![(0.0, 10.0), (0.6, 80.0), (1.0, 170.0)] };
|
||||
s.edit("set", |d, _| {
|
||||
for id in [compound, lone] {
|
||||
let st = d.node_mut(id).unwrap().appearance.stroke_mut().unwrap();
|
||||
st.profile = Some(profile.clone());
|
||||
st.pressure = Some(pressure.clone());
|
||||
st.bearing = Some(bearing.clone());
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
run(&mut s, "select.set", json!({"ids": [compound.0, lone.0]}));
|
||||
assert_eq!(run(&mut s, "path.reverse", json!({}))["changed"], 3);
|
||||
let stroke = |id: NodeId| s.doc().unwrap().doc.node(id).unwrap().appearance.stroke().unwrap().clone();
|
||||
let (got, want) = (stroke(compound), stroke(lone));
|
||||
assert_ne!(want.profile.as_ref(), Some(&profile), "the lone rectangle's profile turned");
|
||||
assert_eq!(got.profile, want.profile, "both members turned alike, so the compound path's profile turns as the rectangle's does");
|
||||
assert_eq!(got.pressure, want.pressure);
|
||||
assert_eq!(got.bearing, want.bearing);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attributes_survive_a_native_round_trip() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -666,7 +666,7 @@ fn expanding_a_reflected_symbol_instance_keeps_its_box() {
|
||||
for reset in [false, true] {
|
||||
let (mut s, inst) = turned_instance(0.0);
|
||||
s.execute("object.rotate", &json!({"angle": 150})).unwrap();
|
||||
s.execute("object.reflect", &json!({"axis": "horizontal"})).unwrap();
|
||||
s.execute("object.reflect", &json!({"axis": "horizontal", "basis": "page"})).unwrap();
|
||||
assert!(near(angle(&s, inst), -170.0), "{}", angle(&s, inst));
|
||||
if reset {
|
||||
s.execute("object.resetBoundingBox", &json!({})).unwrap();
|
||||
@@ -719,10 +719,164 @@ fn page_flips_keep_an_upright_box_upright() {
|
||||
s.execute("object.reflect", &json!({"axis": "horizontal"})).unwrap();
|
||||
assert_eq!(angle(&s, a), 0.0);
|
||||
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
|
||||
// A named axis is the turned box's own: the box keeps its angle.
|
||||
s.execute("object.reflect", &json!({"axis": "vertical"})).unwrap();
|
||||
assert!(near(angle(&s, a), 30.0));
|
||||
s.execute("object.reflect", &json!({"axis": "vertical", "basis": "page"})).unwrap();
|
||||
assert!(near(angle(&s, a), -30.0));
|
||||
}
|
||||
|
||||
fn same_matrix(a: Affine, b: Affine) -> bool {
|
||||
a.as_coeffs().iter().zip(b.as_coeffs()).all(|(x, y)| near(*x, y))
|
||||
}
|
||||
|
||||
/// After a rotation, Scale and a named Reflect act along the turned bounding box until Reset
|
||||
/// Bounding Box; `basis: "page"` keeps the page's axes, and Transform Again repeats the matrix the
|
||||
/// transform applied on the page.
|
||||
#[test]
|
||||
fn scale_and_reflect_follow_the_turned_box() {
|
||||
let mut s = session();
|
||||
let a = turned_rect(&mut s);
|
||||
let page = |s: &Session, ids: &[NodeId]| s.doc().unwrap().doc.bounds_of(ids, false).unwrap();
|
||||
let c = Point::new(200.0, 200.0);
|
||||
let frame = OrientedBox { angle: 45.0, rect: Rect::ZERO };
|
||||
s.execute("object.scale", &json!({"sx": 200, "sy": 100})).unwrap();
|
||||
let b = selection_box(&s);
|
||||
assert!(near(b.angle, 45.0) && near(angle(&s, a), 45.0), "{b:?}");
|
||||
assert!(near(b.rect.width(), 200.0) && near(b.rect.height(), 50.0), "{b:?}");
|
||||
assert!(b.center().distance(c) < 1e-6, "{b:?}");
|
||||
let want = Affine::translate(c.to_vec2()) * frame.conjugate(Affine::scale_non_uniform(2.0, 1.0)) * Affine::translate(-c.to_vec2());
|
||||
let Some(LastTransform::Matrix(m, _)) = s.doc().unwrap().last_transform.clone() else { panic!("no transform to repeat") };
|
||||
assert!(same_matrix(m, want), "{m:?}");
|
||||
// The recorded step names its basis, so a replay acts in the same frame.
|
||||
let steps = s.journal_for_action(0);
|
||||
assert!(steps.iter().any(|(id, p)| id == "object.scale" && p["basis"] == "box"), "{steps:?}");
|
||||
|
||||
// Reflected across the box's vertical axis through its left side: the box keeps its angle and
|
||||
// size, and its centre moves a width to the left along the box.
|
||||
let left = b.reference_point(3);
|
||||
s.execute("object.reflect", &json!({"axis": "vertical", "origin": [left.x, left.y]})).unwrap();
|
||||
let r = selection_box(&s);
|
||||
let moved = c + (frame.to_doc() * Point::new(-200.0, 0.0)).to_vec2();
|
||||
assert!(near(r.angle, 45.0) && near(r.rect.width(), 200.0) && near(r.rect.height(), 50.0), "{r:?}");
|
||||
assert!(r.center().distance(moved) < 1e-6, "{r:?}");
|
||||
// Across its horizontal axis through its centre: the box stays where it is.
|
||||
s.execute("object.reflect", &json!({"axis": "horizontal"})).unwrap();
|
||||
assert!(selection_box(&s).center().distance(moved) < 1e-6 && near(angle(&s, a), 45.0));
|
||||
|
||||
// Unknown bases are errors and change nothing.
|
||||
let n = undo_len(&s);
|
||||
assert!(s.execute("object.scale", &json!({"sx": 50, "basis": "turned"})).is_err());
|
||||
assert!(s.execute("object.reflect", &json!({"axis": "vertical", "basis": 1})).is_err());
|
||||
assert!(s.execute("object.reflect", &json!({"axis": 30, "basis": "turned"})).is_err());
|
||||
assert_eq!(undo_len(&s), n);
|
||||
|
||||
// On the page's axes, the box no longer stands at 45°.
|
||||
s.execute("object.scale", &json!({"sx": 50, "sy": 100, "basis": "page"})).unwrap();
|
||||
assert!(!near(angle(&s, a), 45.0));
|
||||
// Transform Again repeats the page matrix after Reset Bounding Box too.
|
||||
s.execute("object.scale", &json!({"sx": 200, "sy": 100})).unwrap();
|
||||
let Some(LastTransform::Matrix(m, _)) = s.doc().unwrap().last_transform.clone() else { panic!("no transform to repeat") };
|
||||
s.execute("object.resetBoundingBox", &json!({})).unwrap();
|
||||
let before = s.doc().unwrap().doc.node(a).unwrap().clone();
|
||||
s.execute("object.transformAgain", &json!({})).unwrap();
|
||||
let mut want = before;
|
||||
want.transform(m, false);
|
||||
let (got, want) = (page(&s, &[a]), want.geometric_bounds_with(&s.doc().unwrap().doc.symbol_boxes()).unwrap());
|
||||
assert!([got.x0 - want.x0, got.y0 - want.y0, got.x1 - want.x1, got.y1 - want.y1].iter().all(|d| d.abs() < 1e-6), "{got:?} {want:?}");
|
||||
}
|
||||
|
||||
/// A saved step without `basis` was recorded before Scale and Reflect followed the turned box, so a
|
||||
/// replay of it acts along the page's axes, as it did then, and its new journal entry says so. A
|
||||
/// step recorded now names its basis and replays along the box. A call without `basis` that is not
|
||||
/// a replay acts along the box.
|
||||
#[test]
|
||||
fn saved_steps_without_a_basis_replay_on_the_page() {
|
||||
// The turned rectangle after `run` runs on it: its page bounds and its box's angle.
|
||||
let after = |run: &dyn Fn(&mut Session)| {
|
||||
let mut s = session();
|
||||
let a = turned_rect(&mut s);
|
||||
run(&mut s);
|
||||
let st = (s.doc().unwrap().doc.bounds_of(&[a], false).unwrap(), angle(&s, a));
|
||||
(st, s.journal.last().unwrap().clone())
|
||||
};
|
||||
let same = |(r, a): (Rect, f64), (q, b): (Rect, f64)| [r.x0 - q.x0, r.y0 - q.y0, r.x1 - q.x1, r.y1 - q.y1, a - b].iter().all(|d| d.abs() < 1e-6);
|
||||
for (id, p) in [("object.scale", json!({"sx": 200, "sy": 100})), ("object.reflect", json!({"axis": "vertical"}))] {
|
||||
let mut on_page = p.clone();
|
||||
on_page["basis"] = json!("page");
|
||||
let (page, _) = after(&|s| {
|
||||
s.execute(id, &on_page).unwrap();
|
||||
});
|
||||
let (old, (_, noted)) = after(&|s| {
|
||||
s.replay(id, &p).unwrap();
|
||||
});
|
||||
assert!(same(old, page), "{id}: {old:?} {page:?}");
|
||||
assert_eq!(noted["basis"], "page", "{id}");
|
||||
|
||||
let (boxed, (recorded_id, recorded)) = after(&|s| {
|
||||
s.execute(id, &p).unwrap();
|
||||
});
|
||||
assert!(!same(boxed, page) && near(boxed.1, 45.0), "{id}: {boxed:?}");
|
||||
assert_eq!(recorded["basis"], "box", "{id}");
|
||||
let (replayed, _) = after(&|s| {
|
||||
s.replay(&recorded_id, &recorded).unwrap();
|
||||
});
|
||||
assert!(same(replayed, boxed), "{id}: {replayed:?} {boxed:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Once Reset Bounding Box squares the box, and for objects standing at different angles, Scale
|
||||
/// acts along the page's axes.
|
||||
#[test]
|
||||
fn scale_follows_the_page_after_a_reset_and_for_mixed_angles() {
|
||||
let mut s = session();
|
||||
let a = turned_rect(&mut s);
|
||||
s.execute("object.resetBoundingBox", &json!({})).unwrap();
|
||||
let page = |s: &Session, ids: &[NodeId]| s.doc().unwrap().doc.bounds_of(ids, false).unwrap();
|
||||
let w = page(&s, &[a]);
|
||||
s.execute("object.scale", &json!({"sx": 200, "sy": 100})).unwrap();
|
||||
let r = page(&s, &[a]);
|
||||
assert!(near(r.width(), 2.0 * w.width()) && near(r.height(), w.height()), "{w:?} {r:?}");
|
||||
assert_eq!(angle(&s, a), 0.0);
|
||||
// A turned rectangle with an upright one: the box is square to the page.
|
||||
let b = turned_rect(&mut s);
|
||||
let u = rect(&mut s, 400.0, 100.0, 50.0, 50.0);
|
||||
sel(&mut s, &[b, u]);
|
||||
let w = page(&s, &[b, u]);
|
||||
s.execute("object.scale", &json!({"sx": 100, "sy": 200})).unwrap();
|
||||
let r = page(&s, &[b, u]);
|
||||
assert!(near(r.width(), w.width()) && near(r.height(), 2.0 * w.height()), "{w:?} {r:?}");
|
||||
}
|
||||
|
||||
/// With anchors selected, Scale and a named Reflect move the anchors along the page's axes, but
|
||||
/// with Transform Objects off they move the whole objects' pattern tiles, along the turned box.
|
||||
#[test]
|
||||
fn pattern_only_transforms_of_selected_anchors_follow_the_turned_box() {
|
||||
let c = Point::new(200.0, 200.0);
|
||||
let frame = OrientedBox { angle: 45.0, rect: Rect::ZERO };
|
||||
let about = |m: Affine| Affine::translate(c.to_vec2()) * m * Affine::translate(-c.to_vec2());
|
||||
let last = |s: &Session| match s.doc().unwrap().last_transform.clone() {
|
||||
Some(LastTransform::Matrix(m, _)) => m,
|
||||
other => panic!("no matrix to repeat: {other:?}"),
|
||||
};
|
||||
let scale = Affine::scale_non_uniform(2.0, 1.0);
|
||||
let flip = Affine::scale_non_uniform(-1.0, 1.0);
|
||||
for (cmd, p, m) in [("object.scale", json!({"sx": 200, "sy": 100}), scale), ("object.reflect", json!({"axis": "vertical"}), flip)] {
|
||||
for objects in [false, true] {
|
||||
let mut s = session();
|
||||
let a = turned_rect(&mut s);
|
||||
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0]], "mode": "set"})).unwrap();
|
||||
let mut p = p.clone();
|
||||
p["origin"] = json!([c.x, c.y]);
|
||||
p["objects"] = json!(objects);
|
||||
p["patterns"] = json!(true);
|
||||
s.execute(cmd, &p).unwrap();
|
||||
let want = if objects { about(m) } else { about(frame.conjugate(m)) };
|
||||
assert!(same_matrix(last(&s), want), "{cmd} objects {objects}: {:?}", last(&s));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn groups_type_and_multiple_selections_keep_their_angle() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_color::{BlendMode, Color, Paint};
|
||||
use vectorcraft_doc::appearance::{Effect, FillLayer, StrokeLayer};
|
||||
use vectorcraft_doc::{AppearanceItem, ImageBlob, ImageObject, LineCap, LineJoin, Node, NodeKind};
|
||||
use vectorcraft_geom::{Affine, FillRule, PathData, Point, Rect};
|
||||
use vectorcraft_testkit::pdf::{PdfPage, pdf};
|
||||
@@ -2684,6 +2685,401 @@ fn live_paint_make_and_expand_keep_abutting_compound_colors() {
|
||||
check_colors(&node(&s, group));
|
||||
}
|
||||
|
||||
/// Gives `id` the appearance rows `items` (paint order) and returns them.
|
||||
fn set_rows(s: &mut Session, id: NodeId, items: Vec<AppearanceItem>) -> Vec<AppearanceItem> {
|
||||
s.edit("t", |d, _| {
|
||||
d.node_mut(id).unwrap().appearance = vectorcraft_doc::Appearance { items: items.clone(), ..Default::default() }.into();
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
items
|
||||
}
|
||||
|
||||
/// A fill row of `p`, changed by `f`.
|
||||
fn fill_row(p: Paint, f: impl FnOnce(&mut FillLayer)) -> AppearanceItem {
|
||||
let mut l = FillLayer::new(p);
|
||||
f(&mut l);
|
||||
AppearanceItem::Fill(l)
|
||||
}
|
||||
|
||||
/// A stroke row of `p` `width` wide, changed by `f`.
|
||||
fn stroke_row(p: Paint, width: f64, f: impl FnOnce(&mut StrokeLayer)) -> AppearanceItem {
|
||||
let mut l = StrokeLayer::new(p, width);
|
||||
f(&mut l);
|
||||
AppearanceItem::Stroke(l)
|
||||
}
|
||||
|
||||
/// The faces and edges of Live Paint group `g` whose bounds lie within x `x0`..`x1`.
|
||||
fn parts_within(s: &Session, g: NodeId, x0: f64, x1: f64) -> (Vec<Node>, Vec<Node>) {
|
||||
let n = node(s, g);
|
||||
let within = |c: &&Arc<Node>| c.geometric_bounds().is_some_and(|b| b.x0 >= x0 - 1e-6 && b.x1 <= x1 + 1e-6);
|
||||
let faces = vectorcraft_tools::builder::faces(&n).into_iter().filter(within).map(|c| (**c).clone()).collect();
|
||||
let edges = vectorcraft_tools::builder::edges(&n).into_iter().filter(within).map(|c| (**c).clone()).collect();
|
||||
(faces, edges)
|
||||
}
|
||||
|
||||
/// Make gives each edge every stroke row of its source that draws, a lower one under an
|
||||
/// unpainted or hidden top row included, with the rows' settings and the source's opacity and
|
||||
/// blending mode; rows that draw nothing stay only with the stored source, which Release returns.
|
||||
#[test]
|
||||
fn live_paint_make_keeps_lower_drawn_stroke_rows() {
|
||||
let mut s = session();
|
||||
let (a, b) = two_at(&mut s, 200.0);
|
||||
let black = Paint::solid(Color::BLACK);
|
||||
let green = Paint::solid(Color::rgb(0.0, 1.0, 0.0));
|
||||
let thick = stroke_row(black.clone(), 3.0, |l| {
|
||||
l.opacity = 0.5;
|
||||
l.blend = BlendMode::Multiply;
|
||||
l.cap = LineCap::Round;
|
||||
});
|
||||
// A: the top stroke has no paint.
|
||||
let a_rows =
|
||||
set_rows(&mut s, a, vec![fill_row(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), |_| {}), thick.clone(), stroke_row(Paint::None, 1.0, |_| {})]);
|
||||
// B: the top stroke is hidden; a zero-weight and a transparent stroke draw nothing either.
|
||||
set_rows(
|
||||
&mut s,
|
||||
b,
|
||||
vec![
|
||||
stroke_row(green.clone(), 2.0, |_| {}),
|
||||
stroke_row(black.clone(), 0.0, |_| {}),
|
||||
stroke_row(black, 2.0, |l| l.opacity = 0.0),
|
||||
stroke_row(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 5.0, |l| l.visible = false),
|
||||
],
|
||||
);
|
||||
s.edit("t", |d, _| {
|
||||
let n = d.node_mut(a).unwrap();
|
||||
n.opacity = 0.75;
|
||||
n.blend = BlendMode::Screen;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let (_, a_edges) = parts_within(&s, g, 0.0, 100.0);
|
||||
let (_, b_edges) = parts_within(&s, g, 200.0, 300.0);
|
||||
assert!(!a_edges.is_empty() && !b_edges.is_empty());
|
||||
for e in &a_edges {
|
||||
assert_eq!(e.appearance.items, vec![thick.clone()], "A's edge takes the stroke that draws");
|
||||
assert_eq!((e.opacity, e.blend), (0.75, BlendMode::Screen));
|
||||
}
|
||||
for e in &b_edges {
|
||||
assert_eq!(e.appearance.items, vec![stroke_row(green.clone(), 2.0, |_| {})], "B's edge takes only its green stroke");
|
||||
assert_eq!((e.opacity, e.blend), (1.0, BlendMode::Normal));
|
||||
}
|
||||
// Release returns the sources with every row they had.
|
||||
let released = ids(&s.execute("livePaint.release", &json!({})).unwrap());
|
||||
assert!(released.contains(&a));
|
||||
assert_eq!(node(&s, a).appearance.items, a_rows);
|
||||
}
|
||||
|
||||
/// When Make cuts a dashed stroke with arrowheads, a width profile and a brush into edges, each
|
||||
/// edge's dashes go on from where it starts along the path, the arrowheads stay at the path's own
|
||||
/// ends, and the profile and brush, which spread over the whole path, are left off the pieces.
|
||||
#[test]
|
||||
fn live_paint_make_fits_dashes_and_arrowheads_to_each_edge() {
|
||||
use vectorcraft_doc::{Arrowhead, Dash};
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
let l = line(&mut s, (-20.0, 50.0), (120.0, 50.0));
|
||||
let dash = Dash { pattern: vec![10.0, 5.0], offset: 2.0, align_corners: true };
|
||||
let row = stroke_row(Paint::solid(Color::BLACK), 2.0, |st| {
|
||||
st.dash = Some(dash.clone());
|
||||
st.start_arrow = Some(Arrowhead::Triangle);
|
||||
st.end_arrow = Some(Arrowhead::Circle);
|
||||
st.brush = Some("Charcoal".into());
|
||||
});
|
||||
let rows = set_rows(&mut s, l, vec![row]);
|
||||
s.execute("select.set", &json!({"ids": [a.0, l.0]})).unwrap();
|
||||
let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let gn = node(&s, g);
|
||||
let mut pieces: Vec<(f64, f64, vectorcraft_doc::StrokeLayer)> = vectorcraft_tools::builder::edges(&gn)
|
||||
.iter()
|
||||
.filter_map(|e| {
|
||||
let st = e.appearance.stroke().filter(|st| st.dash.is_some())?.clone();
|
||||
let sp = e.path_data()?.subpaths.first()?;
|
||||
Some((sp.anchors.first()?.p.x, sp.anchors.last()?.p.x, st))
|
||||
})
|
||||
.collect();
|
||||
pieces.sort_by(|p, q| p.0.total_cmp(&q.0));
|
||||
let ends: Vec<(f64, f64)> = pieces.iter().map(|p| ((p.0 * 1e3).round() / 1e3, (p.1 * 1e3).round() / 1e3)).collect();
|
||||
assert_eq!(ends, vec![(-20.0, 0.0), (0.0, 100.0), (100.0, 120.0)], "each piece runs the way the line does");
|
||||
let offsets: Vec<f64> = pieces.iter().map(|p| (p.2.dash.as_ref().unwrap().offset * 1e3).round() / 1e3).collect();
|
||||
assert_eq!(offsets, vec![2.0, 22.0, 122.0], "the dashes go on along the line");
|
||||
assert!(pieces.iter().all(|p| !p.2.dash.as_ref().unwrap().align_corners && p.2.brush.is_none()));
|
||||
let arrows: Vec<_> = pieces.iter().map(|p| (p.2.start_arrow.clone(), p.2.end_arrow.clone())).collect();
|
||||
assert_eq!(arrows, vec![(Some(Arrowhead::Triangle), None), (None, None), (None, Some(Arrowhead::Circle))]);
|
||||
// A path that crosses itself: the pieces that start at the crossing take their place on the
|
||||
// path from where they run, not from the first time the path passes that point.
|
||||
let mut s3 = session();
|
||||
let anchors = [(0.0, 0.0), (100.0, 100.0), (100.0, 0.0), (0.0, 100.0)].map(|(x, y)| json!({"x": x, "y": y}));
|
||||
let z = NodeId(s3.execute("path.create", &json!({"anchors": anchors, "closed": false})).unwrap()["id"].as_u64().unwrap());
|
||||
set_rows(&mut s3, z, rows.clone());
|
||||
s3.execute("select.set", &json!({"ids": [z.0]})).unwrap();
|
||||
let g3 = NodeId(s3.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let mut cut: Vec<(f64, Option<Arrowhead>, Option<Arrowhead>)> = vectorcraft_tools::builder::edges(&node(&s3, g3))
|
||||
.iter()
|
||||
.filter_map(|e| {
|
||||
let st = e.appearance.stroke()?;
|
||||
Some(((st.dash.as_ref()?.offset * 1e3).round() / 1e3, st.start_arrow.clone(), st.end_arrow.clone()))
|
||||
})
|
||||
.collect();
|
||||
cut.sort_by(|p, q| p.0.total_cmp(&q.0));
|
||||
let d = 2.0 + 50.0 * 2f64.sqrt();
|
||||
let r = |v: f64| (v * 1e3).round() / 1e3;
|
||||
assert_eq!(
|
||||
cut,
|
||||
vec![(2.0, Some(Arrowhead::Triangle), None), (r(d), None, None), (r(d + 100.0 + 100.0 * 2f64.sqrt()), None, Some(Arrowhead::Circle))]
|
||||
);
|
||||
// An uncut path keeps all of it.
|
||||
let mut s2 = session();
|
||||
let l2 = line(&mut s2, (0.0, 0.0), (50.0, 0.0));
|
||||
set_rows(&mut s2, l2, rows.clone());
|
||||
s2.execute("select.set", &json!({"ids": [l2.0]})).unwrap();
|
||||
let g2 = NodeId(s2.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let edges: Vec<_> = vectorcraft_tools::builder::edges(&node(&s2, g2)).iter().map(|e| e.appearance.items.clone()).collect();
|
||||
assert_eq!(edges, vec![rows]);
|
||||
}
|
||||
|
||||
/// When Gap Options or Merge cuts an edge in two, each piece keeps the edge's dashes going on from
|
||||
/// where it starts along the edge, an arrowhead only at the end of the edge it ends at, and no brush.
|
||||
#[test]
|
||||
fn live_paint_gap_options_and_merge_fit_an_edge_look_to_each_piece() {
|
||||
use vectorcraft_doc::{Arrowhead, Dash};
|
||||
let mut s = session();
|
||||
let l = line(&mut s, (0.0, 50.0), (100.0, 50.0));
|
||||
let stub = line(&mut s, (50.0, 0.0), (50.0, 48.0));
|
||||
let row = stroke_row(Paint::solid(Color::BLACK), 2.0, |st| {
|
||||
st.dash = Some(Dash { pattern: vec![10.0, 5.0], offset: 2.0, align_corners: false });
|
||||
st.start_arrow = Some(Arrowhead::Triangle);
|
||||
st.end_arrow = Some(Arrowhead::Circle);
|
||||
st.brush = Some("Charcoal".into());
|
||||
});
|
||||
let rows = set_rows(&mut s, l, vec![row]);
|
||||
s.execute("select.set", &json!({"ids": [l.0, stub.0]})).unwrap();
|
||||
let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let dashed = |s: &Session, g: NodeId| {
|
||||
let mut out: Vec<(f64, f64, vectorcraft_doc::StrokeLayer)> = vectorcraft_tools::builder::edges(&node(s, g))
|
||||
.iter()
|
||||
.filter_map(|e| {
|
||||
let st = e.appearance.stroke().filter(|st| st.dash.is_some())?.clone();
|
||||
let sp = e.path_data()?.subpaths.first()?;
|
||||
Some(((sp.anchors.first()?.p.x * 1e3).round() / 1e3, (sp.anchors.last()?.p.x * 1e3).round() / 1e3, st))
|
||||
})
|
||||
.collect();
|
||||
out.sort_by(|p, q| p.0.total_cmp(&q.0));
|
||||
out
|
||||
};
|
||||
let before = dashed(&s, g);
|
||||
assert_eq!(before.len(), 1, "nothing cuts the line yet");
|
||||
assert_eq!(vec![AppearanceItem::Stroke(before[0].2.clone())], rows);
|
||||
let r = s.execute("livePaint.gapOptions", &json!({"id": g.0, "closeGaps": true})).unwrap();
|
||||
assert_eq!(r["closed"], json!(1));
|
||||
let pieces = dashed(&s, g);
|
||||
let ends: Vec<(f64, f64)> = pieces.iter().map(|p| (p.0, p.1)).collect();
|
||||
assert_eq!(ends, vec![(0.0, 50.0), (50.0, 100.0)], "the line is cut where the gap closes");
|
||||
let offsets: Vec<f64> = pieces.iter().map(|p| (p.2.dash.as_ref().unwrap().offset * 1e3).round() / 1e3).collect();
|
||||
assert_eq!(offsets, vec![2.0, 52.0], "the dashes go on along the line");
|
||||
let arrows: Vec<_> = pieces.iter().map(|p| (p.2.start_arrow.clone(), p.2.end_arrow.clone())).collect();
|
||||
assert_eq!(arrows, vec![(Some(Arrowhead::Triangle), None), (None, Some(Arrowhead::Circle))]);
|
||||
assert!(pieces.iter().all(|p| p.2.brush.is_none()), "a brush spreads over the whole line");
|
||||
// Merge: the piece of the edge that an added path cuts off, which takes the edge's look, gets
|
||||
// it fitted to where it lies along the edge in the same way.
|
||||
let mut s = session();
|
||||
let l = line(&mut s, (0.0, 50.0), (100.0, 50.0));
|
||||
set_rows(&mut s, l, rows.clone());
|
||||
s.execute("select.set", &json!({"ids": [l.0]})).unwrap();
|
||||
let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let cut = line(&mut s, (25.0, 0.0), (25.0, 100.0));
|
||||
s.execute("livePaint.merge", &json!({"ids": [g.0, cut.0]})).unwrap();
|
||||
let pieces = dashed(&s, g);
|
||||
let ends: Vec<(f64, f64)> = pieces.iter().map(|p| (p.0, p.1)).collect();
|
||||
assert_eq!(ends, vec![(0.0, 25.0), (25.0, 100.0)], "the added line cuts the edge");
|
||||
let offsets: Vec<f64> = pieces.iter().map(|p| (p.2.dash.as_ref().unwrap().offset * 1e3).round() / 1e3).collect();
|
||||
assert_eq!(offsets, vec![2.0, 27.0], "the dashes go on along the line");
|
||||
let arrows: Vec<_> = pieces.iter().map(|p| (p.2.start_arrow.clone(), p.2.end_arrow.clone())).collect();
|
||||
assert_eq!(arrows, vec![(Some(Arrowhead::Triangle), None), (None, Some(Arrowhead::Circle))]);
|
||||
assert!(pieces.iter().all(|p| p.2.brush.is_none()), "a brush spreads over the whole line");
|
||||
// A repainted edge that Merge cuts keeps its paint on every piece.
|
||||
let mut s = session();
|
||||
let l = line(&mut s, (0.0, 50.0), (100.0, 50.0));
|
||||
s.execute("select.set", &json!({"ids": [l.0]})).unwrap();
|
||||
let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": [50, 50], "color": "#ff0000", "width": 3})).unwrap();
|
||||
let cut = line(&mut s, (50.0, 0.0), (50.0, 100.0));
|
||||
s.execute("livePaint.merge", &json!({"ids": [g.0, cut.0]})).unwrap();
|
||||
let gn = node(&s, g);
|
||||
let red = Paint::solid(Color::from_hex("#ff0000").unwrap());
|
||||
let mut on_line: Vec<(f64, bool)> = vectorcraft_tools::builder::edges(&gn)
|
||||
.iter()
|
||||
.filter_map(|e| {
|
||||
let sp = e.path_data()?.subpaths.first()?;
|
||||
let (a, z) = (sp.anchors.first()?.p, sp.anchors.last()?.p);
|
||||
((a.y - 50.0).abs() < 1e-6 && (z.y - 50.0).abs() < 1e-6)
|
||||
.then(|| ((a.x.min(z.x) * 1e3).round() / 1e3, e.appearance.stroke().is_some_and(|st| st.paint == red)))
|
||||
})
|
||||
.collect();
|
||||
on_line.sort_by(|p, q| p.0.total_cmp(&q.0));
|
||||
assert_eq!(on_line, vec![(0.0, true), (50.0, true)], "both pieces keep the edge's paint");
|
||||
}
|
||||
|
||||
/// The edge Make builds from a closed path that nothing cuts starts at the anchor the path starts
|
||||
/// at and runs the way the path does, whichever anchor that is, so its dashes and brush lie where
|
||||
/// they do on the path, and it keeps the path's stroke row as it is.
|
||||
#[test]
|
||||
fn live_paint_make_starts_a_closed_edge_where_its_path_starts() {
|
||||
use vectorcraft_doc::Dash;
|
||||
let corners = [(50.0, 0.0), (100.0, 50.0), (50.0, 100.0), (0.0, 50.0)];
|
||||
for clockwise in [true, false] {
|
||||
for start in 0..4 {
|
||||
let mut s = session();
|
||||
let mut pts: Vec<(f64, f64)> = (0..4).map(|k| corners[(k + start) % 4]).collect();
|
||||
if !clockwise {
|
||||
pts.reverse();
|
||||
}
|
||||
let anchors: Vec<_> = pts.iter().map(|(x, y)| json!({"x": x, "y": y})).collect();
|
||||
let z = NodeId(s.execute("path.create", &json!({"anchors": anchors, "closed": true})).unwrap()["id"].as_u64().unwrap());
|
||||
let row = stroke_row(Paint::solid(Color::BLACK), 2.0, |st| {
|
||||
st.dash = Some(Dash { pattern: vec![10.0, 5.0], offset: 2.0, align_corners: false });
|
||||
st.brush = Some("Charcoal".into());
|
||||
});
|
||||
let rows = set_rows(&mut s, z, vec![row]);
|
||||
s.execute("select.set", &json!({"ids": [z.0]})).unwrap();
|
||||
let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let gn = node(&s, g);
|
||||
let edges = vectorcraft_tools::builder::edges(&gn);
|
||||
let [e] = edges.as_slice() else { panic!("one edge, got {}", edges.len()) };
|
||||
let sp = e.path_data().unwrap().subpaths.first().unwrap().clone();
|
||||
let at: Vec<(f64, f64)> = sp.anchors.iter().map(|a| ((a.p.x * 1e3).round() / 1e3, (a.p.y * 1e3).round() / 1e3)).collect();
|
||||
assert!(sp.closed);
|
||||
assert_eq!(at, pts, "clockwise {clockwise}, start {start}");
|
||||
assert_eq!(e.appearance.items, rows, "clockwise {clockwise}, start {start}");
|
||||
}
|
||||
}
|
||||
// A closed path that crosses itself is cut into loops, and the loop that holds the path's
|
||||
// first anchor is still only part of the path: it keeps no brush.
|
||||
let mut s = session();
|
||||
let anchors = [(0.0, 0.0), (100.0, 100.0), (100.0, 0.0), (0.0, 100.0)].map(|(x, y)| json!({"x": x, "y": y}));
|
||||
let z = NodeId(s.execute("path.create", &json!({"anchors": anchors, "closed": true})).unwrap()["id"].as_u64().unwrap());
|
||||
let row = stroke_row(Paint::solid(Color::BLACK), 2.0, |st| {
|
||||
st.dash = Some(Dash { pattern: vec![10.0, 5.0], offset: 2.0, align_corners: false });
|
||||
st.brush = Some("Charcoal".into());
|
||||
});
|
||||
set_rows(&mut s, z, vec![row]);
|
||||
s.execute("select.set", &json!({"ids": [z.0]})).unwrap();
|
||||
let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let gn = node(&s, g);
|
||||
let edges = vectorcraft_tools::builder::edges(&gn);
|
||||
assert!(edges.len() > 1, "the crossing cuts the path, got {} edge", edges.len());
|
||||
assert!(edges.iter().all(|e| e.appearance.stroke().is_some_and(|st| st.brush.is_none())), "no loop is the whole path");
|
||||
}
|
||||
|
||||
/// When Make cuts a stroke whose only setting that depends on direction is a gradient along or
|
||||
/// across it, each edge runs the way its source path does, so the gradient keeps its direction.
|
||||
#[test]
|
||||
fn live_paint_make_keeps_the_direction_of_gradient_strokes() {
|
||||
use vectorcraft_doc::StrokeGradientMode;
|
||||
for mode in [StrokeGradientMode::Along, StrokeGradientMode::Across] {
|
||||
for (x0, x1) in [(-20.0, 120.0), (120.0, -20.0)] {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
let l = line(&mut s, (x0, 50.0), (x1, 50.0));
|
||||
let gradient = Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(vectorcraft_color::Gradient::default())));
|
||||
set_rows(&mut s, l, vec![stroke_row(gradient, 2.0, |st| st.gradient_mode = mode)]);
|
||||
s.execute("select.set", &json!({"ids": [a.0, l.0]})).unwrap();
|
||||
let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let pieces: Vec<(f64, f64)> = vectorcraft_tools::builder::edges(&node(&s, g))
|
||||
.iter()
|
||||
.filter_map(|e| {
|
||||
e.appearance.stroke().filter(|st| st.gradient_mode == mode)?;
|
||||
let sp = e.path_data()?.subpaths.first()?;
|
||||
Some((sp.anchors.first()?.p.x, sp.anchors.last()?.p.x))
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(pieces.len(), 3, "{mode:?}, from {x0}");
|
||||
assert!(
|
||||
pieces.iter().all(|&(p, q)| (q - p).signum() == (x1 - x0).signum()),
|
||||
"{mode:?}, from {x0}: each piece runs the way the line does: {pieces:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Make gives each face every fill row of its source that draws, in order and with their
|
||||
/// opacity, blending mode, overprint and effects, and the source's gradients keep their fit on
|
||||
/// the source; Expand keeps the rows, and Undo and Redo bring the group back with them.
|
||||
#[test]
|
||||
fn live_paint_make_keeps_all_drawn_fill_rows_and_attributes() {
|
||||
let mut s = session();
|
||||
let (a, b) = two(&mut s);
|
||||
let lower = fill_row(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), |l| {
|
||||
l.opacity = 0.4;
|
||||
l.blend = BlendMode::Multiply;
|
||||
l.overprint = true;
|
||||
l.effects.push(Effect { id: "distort.roughen".into(), params: Value::Null, visible: true });
|
||||
});
|
||||
// A: two fills that draw, with a hidden one between them and an unpainted one above them.
|
||||
set_rows(
|
||||
&mut s,
|
||||
a,
|
||||
vec![
|
||||
lower.clone(),
|
||||
fill_row(Paint::solid(Color::rgb(0.0, 1.0, 0.0)), |l| l.visible = false),
|
||||
fill_row(Paint::None, |_| {}),
|
||||
stroke_row(Paint::None, 1.0, |_| {}),
|
||||
],
|
||||
);
|
||||
// The top fill (and the stroke) become a gradient fitted to A's bounds.
|
||||
let (want_fill, _) = paint_with_gradients(&mut s, a);
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let want = vec![lower, fill_row(want_fill, |_| {})];
|
||||
let rows_within = |s: &Session, x0: f64, x1: f64| parts_within(s, g, x0, x1).0.iter().map(|f| f.appearance.items.clone()).collect::<Vec<_>>();
|
||||
assert_eq!(rows_within(&s, 0.0, 50.0), vec![want.clone()], "A's face takes both fills that draw, the gradient at its fit on A");
|
||||
let blue = vec![fill_row(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), |_| {})];
|
||||
assert_eq!(rows_within(&s, 50.0, 100.0), vec![blue], "B is in front");
|
||||
s.execute("livePaint.expand", &json!({})).unwrap();
|
||||
let expanded = node(&s, g);
|
||||
assert!(!vectorcraft_tools::builder::is_live_paint(&expanded));
|
||||
let kept =
|
||||
expanded.children().unwrap().iter().filter(|c| c.geometric_bounds().is_some_and(|b| b.x1 <= 50.0 + 1e-6)).any(|c| c.appearance.items == want);
|
||||
assert!(kept, "Expand keeps both fills");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(rows_within(&s, 0.0, 50.0), vec![want.clone()]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(rows_within(&s, 0.0, 50.0), vec![want]);
|
||||
}
|
||||
|
||||
/// A face takes the fill rows of the front-most covering source whose fill draws: a source in
|
||||
/// front whose fill is hidden or transparent, or whose opacity is 0, does not hide the paint of the
|
||||
/// source behind it, and a face that no such source covers has no paint.
|
||||
#[test]
|
||||
fn live_paint_make_uses_frontmost_source_with_drawn_fill() {
|
||||
for front in ["hidden", "clear", "transparent object"] {
|
||||
let mut s = session();
|
||||
let (a, b) = two(&mut s);
|
||||
s.edit("t", |d, _| {
|
||||
let n = d.node_mut(b).unwrap();
|
||||
let mut app = (*n.appearance).clone();
|
||||
match front {
|
||||
"hidden" => app.fill_mut().unwrap().visible = false,
|
||||
"clear" => app.fill_mut().unwrap().opacity = 0.0,
|
||||
_ => n.opacity = 0.0,
|
||||
}
|
||||
n.appearance = app.into();
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let rows_within = |x0: f64, x1: f64| parts_within(&s, g, x0, x1).0.iter().map(|f| f.appearance.items.clone()).collect::<Vec<_>>();
|
||||
let red = vec![fill_row(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), |_| {})];
|
||||
assert_eq!(rows_within(50.0, 100.0), vec![red], "{front}: the overlap shows A");
|
||||
assert_eq!(rows_within(100.0, 150.0), vec![vec![fill_row(Paint::None, |_| {})]], "{front}: B alone paints nothing");
|
||||
assert_eq!(parts_within(&s, g, 100.0, 150.0).0[0].opacity, 1.0, "{front}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn live_paint_fill_assigns_the_face_under_the_point() {
|
||||
let mut s = session();
|
||||
@@ -2781,7 +3177,7 @@ fn live_paint_fill_same_paint_is_no_op() {
|
||||
let mut before = snapshot(&s);
|
||||
let click = s.execute("livePaint.fill", &json!({"group": g.0, "point": [75, 50], "color": "#00ff00"})).unwrap();
|
||||
let face = vectorcraft_tools::builder::face_at(&node(&s, g), Point::new(75.0, 50.0)).unwrap().id;
|
||||
assert_eq!(click, json!({"group": g.0, "face": face.0}), "the usual reply");
|
||||
assert_eq!(click, json!({"group": g.0, "face": face.0, "count": 1}), "the usual reply");
|
||||
assert_unchanged(&mut s, &mut before, "a click on a face with the paint");
|
||||
s.execute("livePaint.fill", &drag).unwrap();
|
||||
assert_unchanged(&mut s, &mut before, "a drag over faces with the paint");
|
||||
@@ -2850,6 +3246,42 @@ fn live_paint_stroke_edge_same_paint_and_width_is_no_op() {
|
||||
assert_eq!(history_state(&s).0, before.1.0 + 1);
|
||||
}
|
||||
|
||||
/// With `scope`, faces and edges that already have the paint (and the width) are skipped: when
|
||||
/// every face or edge the call reaches has it, nothing changes, and when some do, only the others
|
||||
/// are painted, in one undo step. `count` is every face or edge reached.
|
||||
#[test]
|
||||
fn live_paint_scoped_fill_and_stroke_skip_parts_with_the_paint() {
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 50], "points": [[25, 50], [125, 50]], "color": "#00ff00"})).unwrap();
|
||||
let edges =
|
||||
s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": [100, 50], "scope": "samePaint", "color": "#ff0000", "width": 3})).unwrap();
|
||||
redo_waiting_and_saved(&mut s, g);
|
||||
let mut before = snapshot(&s);
|
||||
let same = json!({"group": g.0, "point": [75, 50], "scope": "samePaint", "color": "#00ff00"});
|
||||
assert_eq!(s.execute("livePaint.fill", &same).unwrap()["count"], 3);
|
||||
assert_unchanged(&mut s, &mut before, "a samePaint fill where every face has the paint");
|
||||
let again = json!({"group": g.0, "point": [100, 50], "scope": "samePaint", "color": "#ff0000", "width": 3});
|
||||
assert_eq!(s.execute("livePaint.strokeEdge", &again).unwrap()["count"], edges["count"]);
|
||||
assert_unchanged(&mut s, &mut before, "a samePaint stroke where every edge has the paint and the width");
|
||||
// One face of the three without the paint: only it is filled, in one undo step.
|
||||
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
|
||||
let red = Paint::solid(Color::from_hex("#ff0000").unwrap());
|
||||
s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 50], "color": "#ff0000"})).unwrap();
|
||||
let depth = history_state(&s).0;
|
||||
let like = serde_json::to_value(&green).unwrap();
|
||||
let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 50], "scope": "samePaint", "match": like, "color": "#00ff00"})).unwrap();
|
||||
assert_eq!(r["count"], 3);
|
||||
assert_eq!(history_state(&s).0, depth + 1);
|
||||
let fill_at = |s: &Session, x: f64| vectorcraft_tools::builder::face_at(&node(s, g), Point::new(x, 50.0)).unwrap().appearance.fill_paint();
|
||||
for x in [25.0, 75.0, 125.0] {
|
||||
assert_eq!(fill_at(&s, x), green, "{x}");
|
||||
}
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(fill_at(&s, 25.0), red);
|
||||
assert_eq!((fill_at(&s, 75.0), fill_at(&s, 125.0)), (green.clone(), green));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn live_paint_gap_options_same_values_are_no_op() {
|
||||
let mut s = session();
|
||||
@@ -3012,6 +3444,472 @@ fn live_paint_fill_skips_hidden_faces() {
|
||||
assert!(!node(&s, hidden).visible);
|
||||
}
|
||||
|
||||
/// A Live Paint group of 50 pt squares side by side, 50 pt tall, with their left sides at each of
|
||||
/// `xs`.
|
||||
fn live_squares(s: &mut Session, xs: &[f64]) -> NodeId {
|
||||
let ids: Vec<u64> = xs.iter().map(|&x| rect(s, x, 0.0, 50.0, 50.0).0).collect();
|
||||
s.execute("select.set", &json!({"ids": ids})).unwrap();
|
||||
NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
/// The ids of the faces of `g` that hold `p`, in the order given.
|
||||
fn faces_at(s: &Session, g: NodeId, ps: &[(f64, f64)]) -> Vec<NodeId> {
|
||||
ps.iter().map(|&(x, y)| vectorcraft_tools::builder::face_at(&node(s, g), Point::new(x, y)).unwrap().id).collect()
|
||||
}
|
||||
|
||||
/// The edges of `g` whose bounds lie within `r`.
|
||||
fn edges_in(s: &Session, g: NodeId, r: Rect) -> Vec<NodeId> {
|
||||
let r = r.inflate(1e-6, 1e-6);
|
||||
vectorcraft_tools::builder::edges(&node(s, g))
|
||||
.iter()
|
||||
.filter(|e| e.geometric_bounds().is_some_and(|bb| r.contains(Point::new(bb.x0, bb.y0)) && r.contains(Point::new(bb.x1, bb.y1))))
|
||||
.map(|e| e.id)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Give `ids` stroke paint `paint` at weight 1 (none: no stroke), and `fill` to the faces in `faces`.
|
||||
fn paint_parts(s: &mut Session, ids: &[NodeId], paint: &Paint, faces: &[(NodeId, Paint)]) {
|
||||
s.edit("t", |d, _| {
|
||||
for id in ids {
|
||||
let n = d.node_mut(*id).unwrap();
|
||||
n.appearance.set_stroke(paint.clone());
|
||||
if let Some(st) = n.appearance.stroke_mut() {
|
||||
st.width = 1.0;
|
||||
}
|
||||
}
|
||||
for (id, fill) in faces {
|
||||
d.node_mut(*id).unwrap().appearance.set_fill(fill.clone());
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn fill_of(s: &Session, id: NodeId) -> Paint {
|
||||
node(s, id).appearance.fill_paint()
|
||||
}
|
||||
|
||||
/// A double-click on a face fills it and the faces reached across edges that draw no stroke; a
|
||||
/// stroked edge and a hidden face stop the flood.
|
||||
#[test]
|
||||
fn live_paint_bucket_double_click_floods_across_unstroked_edges() {
|
||||
let mut s = session();
|
||||
let g = live_squares(&mut s, &[0.0, 50.0, 100.0, 150.0]);
|
||||
let [a, b, c, d] = faces_at(&s, g, &[(25.0, 25.0), (75.0, 25.0), (125.0, 25.0), (175.0, 25.0)])[..] else { panic!("four faces") };
|
||||
let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 201.0, 51.0));
|
||||
paint_parts(&mut s, &all, &Paint::None, &[]);
|
||||
let stroked = edges_in(&s, g, Rect::new(150.0, 0.0, 150.0, 50.0));
|
||||
assert!(!stroked.is_empty());
|
||||
paint_parts(&mut s, &stroked, &Paint::solid(Color::rgb(0.0, 0.0, 0.0)), &[]);
|
||||
let white = fill_of(&s, d);
|
||||
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
|
||||
assert_ne!(white, green);
|
||||
let depth = s.doc().unwrap().history.undo.len();
|
||||
let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 25], "color": "#00ff00", "scope": "connected"})).unwrap();
|
||||
assert_eq!((&r["face"], &r["count"]), (&json!(a.0), &json!(3)));
|
||||
assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), green.clone(), green.clone(), white.clone()]);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), depth + 1, "one undo step");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!([a, b, c].iter().all(|f| fill_of(&s, *f) != green));
|
||||
// A hidden face is not filled and does not pass the flood on.
|
||||
s.execute("object.setProps", &json!({"ids": [b.0], "visible": false})).unwrap();
|
||||
let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 25], "color": "#00ff00", "scope": "connected"})).unwrap();
|
||||
assert_eq!(r["count"], 1);
|
||||
assert_eq!([a, b, c].map(|f| fill_of(&s, f) == green), [true, false, false]);
|
||||
while s.doc().unwrap().history.undo.len() > depth {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
// The tool: two clicks and the double-click that follows them.
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("livePaintBucket", v).unwrap();
|
||||
s.paint.fill = green.clone();
|
||||
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] {
|
||||
s.pointer(&PointerEvent::new(kind, 125.0, 25.0), v).unwrap();
|
||||
}
|
||||
assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), green.clone(), green, white]);
|
||||
}
|
||||
|
||||
/// An edge that draws no stroke (fully transparent, or with its stroke hidden) lets a flood across
|
||||
/// although it stores a stroke paint, and an edge scope compares the stroke paint each edge draws
|
||||
/// with.
|
||||
#[test]
|
||||
fn live_paint_bucket_scopes_follow_the_stroke_an_edge_draws() {
|
||||
let mut s = session();
|
||||
let g = live_squares(&mut s, &[0.0, 50.0, 100.0]);
|
||||
let black = Paint::solid(Color::rgb(0.0, 0.0, 0.0));
|
||||
let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 151.0, 51.0));
|
||||
paint_parts(&mut s, &all, &black, &[]);
|
||||
let clear = edges_in(&s, g, Rect::new(50.0, 0.0, 50.0, 50.0));
|
||||
let hidden = edges_in(&s, g, Rect::new(100.0, 0.0, 100.0, 50.0));
|
||||
assert!(!clear.is_empty() && !hidden.is_empty());
|
||||
s.edit("t", |d, _| {
|
||||
for id in &clear {
|
||||
d.node_mut(*id).unwrap().opacity = 0.0;
|
||||
}
|
||||
for id in &hidden {
|
||||
d.node_mut(*id).unwrap().appearance.stroke_mut().unwrap().visible = false;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 25], "color": "#00ff00", "scope": "connected"})).unwrap();
|
||||
assert_eq!(r["count"], 3, "the flood crosses both middle edges");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let stroke = |s: &mut Session, at: [f64; 2]| {
|
||||
let r = s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": at, "color": "#00ff00", "width": 3, "scope": "samePaint"})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
r["count"].clone()
|
||||
};
|
||||
assert_eq!(stroke(&mut s, [25.0, 0.0]), json!(all.len() - clear.len() - hidden.len()), "the edges that draw black");
|
||||
assert_eq!(stroke(&mut s, [50.0, 25.0]), json!(clear.len() + hidden.len()), "the edges that draw no stroke");
|
||||
// With the top edge between them fully transparent too, the connected scope walks from the edge
|
||||
// at x = 50 through it to the edge at x = 100, and reaches no edge that draws black.
|
||||
let top = edges_in(&s, g, Rect::new(50.0, 0.0, 100.0, 0.0));
|
||||
assert_eq!(top.len(), 1);
|
||||
s.edit("t", |d, _| {
|
||||
d.node_mut(top[0]).unwrap().opacity = 0.0;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let r =
|
||||
s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": [50, 25], "color": "#00ff00", "width": 3, "scope": "connected"})).unwrap();
|
||||
assert_eq!(r["count"], json!(clear.len() + top.len() + hidden.len()));
|
||||
}
|
||||
|
||||
/// `livePaint.strokeEdge` paints an edge's topmost stroke that is shown, so the edge then draws
|
||||
/// with the paint; an edge whose strokes are all hidden takes a new stroke above them. Painting
|
||||
/// again changes nothing.
|
||||
#[test]
|
||||
fn live_paint_stroke_edge_paints_the_shown_stroke() {
|
||||
let mut s = session();
|
||||
let g = live_squares(&mut s, &[0.0, 50.0]);
|
||||
let black = Paint::solid(Color::rgb(0.0, 0.0, 0.0));
|
||||
let red = Paint::solid(Color::rgb(1.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, &[]);
|
||||
let middle = edges_in(&s, g, Rect::new(50.0, 0.0, 50.0, 50.0));
|
||||
let left: Vec<NodeId> = edges_in(&s, g, Rect::new(0.0, 0.0, 50.0, 50.0)).into_iter().filter(|e| !middle.contains(e)).collect();
|
||||
let (&[m], &[l]) = (&middle[..], &left[..]) else { panic!("one middle edge and one other edge round the left face") };
|
||||
// The middle edge draws red under a hidden black stroke; every stroke of the left face's other
|
||||
// edge is hidden.
|
||||
s.edit("t", |d, _| {
|
||||
let n = d.node_mut(m).unwrap();
|
||||
n.appearance.items.insert(0, AppearanceItem::Stroke(vectorcraft_doc::appearance::StrokeLayer::new(red.clone(), 1.0)));
|
||||
n.appearance.stroke_mut().unwrap().visible = false;
|
||||
d.node_mut(l).unwrap().appearance.stroke_mut().unwrap().visible = false;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let drawn = |s: &Session, id: NodeId| vectorcraft_tools::builder::lp_stroke_paint(&node(s, id));
|
||||
assert_eq!(drawn(&s, m), red);
|
||||
let paint = |s: &mut Session, at: [f64; 2]| {
|
||||
s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": at, "color": "#00ff00", "width": 2})).unwrap();
|
||||
};
|
||||
for (id, at) in [(m, [50.0, 25.0]), (l, [0.0, 25.0])] {
|
||||
paint(&mut s, at);
|
||||
assert_eq!(drawn(&s, id), green, "{id}");
|
||||
let depth = history_state(&s).0;
|
||||
paint(&mut s, at);
|
||||
assert_eq!(history_state(&s).0, depth, "painting {id} again");
|
||||
}
|
||||
assert_eq!(node(&s, m).appearance.items.len(), 2, "the hidden stroke stays as it was");
|
||||
assert_eq!(node(&s, l).appearance.items.len(), 2, "a new stroke above the hidden one");
|
||||
}
|
||||
|
||||
/// With Cmd held, the Live Paint Bucket's presses go to the selection tool Cmd lends, and the
|
||||
/// double-click and triple-click that follow them paint nothing.
|
||||
#[test]
|
||||
fn live_paint_bucket_cmd_double_and_triple_click_paint_nothing() {
|
||||
let mut s = session();
|
||||
let g = live_squares(&mut s, &[0.0, 50.0, 100.0]);
|
||||
let faces = faces_at(&s, g, &[(25.0, 25.0), (75.0, 25.0), (125.0, 25.0)]);
|
||||
let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 151.0, 51.0));
|
||||
paint_parts(&mut s, &all, &Paint::None, &[]);
|
||||
let before: Vec<Paint> = faces.iter().map(|f| fill_of(&s, *f)).collect();
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("livePaintBucket", v).unwrap();
|
||||
s.paint.fill = Paint::solid(Color::from_hex("#00ff00").unwrap());
|
||||
let cmd = Mods { cmd: true, ..Default::default() };
|
||||
let (down, up) = (PointerKind::Down, PointerKind::Up);
|
||||
for kind in [down, up, down, up, PointerKind::DoubleClick, down, up, PointerKind::TripleClick] {
|
||||
s.pointer(&PointerEvent::new(kind, 75.0, 25.0).with_mods(cmd), v).unwrap();
|
||||
}
|
||||
assert_eq!(faces.iter().map(|f| fill_of(&s, *f)).collect::<Vec<_>>(), before);
|
||||
assert_eq!(s.tool_id(), "livePaintBucket");
|
||||
}
|
||||
|
||||
/// The flood crosses curved edges, and reaches a face 0.012 pt wide.
|
||||
#[test]
|
||||
fn live_paint_bucket_double_click_floods_curved_and_narrow_faces() {
|
||||
let mut s = session();
|
||||
let ids: Vec<u64> = [0.0, 60.0]
|
||||
.iter()
|
||||
.map(|&x| s.execute("shape.ellipse", &json!({"x": x, "y": 0, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap())
|
||||
.collect();
|
||||
s.execute("select.set", &json!({"ids": ids})).unwrap();
|
||||
let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 161.0, 101.0));
|
||||
paint_parts(&mut s, &all, &Paint::None, &[]);
|
||||
let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [20, 50], "color": "#00ff00", "scope": "connected"})).unwrap();
|
||||
assert_eq!(r["count"], 3, "both lunes and the lens between them");
|
||||
|
||||
let mut s = session();
|
||||
let ids = [rect(&mut s, 0.0, 0.0, 50.0, 50.0).0, rect(&mut s, 49.988, 0.0, 50.0, 50.0).0];
|
||||
s.execute("select.set", &json!({"ids": ids})).unwrap();
|
||||
let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let [a, sliver, c] = faces_at(&s, g, &[(25.0, 25.0), (49.994, 25.0), (75.0, 25.0)])[..] else { panic!("three faces") };
|
||||
assert!(a != sliver && sliver != c);
|
||||
let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 101.0, 51.0));
|
||||
paint_parts(&mut s, &all, &Paint::None, &[]);
|
||||
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
|
||||
let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 25], "color": "#00ff00", "scope": "connected"})).unwrap();
|
||||
assert_eq!(r["count"], 3);
|
||||
assert_eq!([a, sliver, c].map(|f| fill_of(&s, f)), [green.clone(), green.clone(), green]);
|
||||
}
|
||||
|
||||
/// The flood crosses a hidden edge, and an edge that a Gap Detection gap meets partway along, but
|
||||
/// not the gap.
|
||||
#[test]
|
||||
fn live_paint_bucket_double_click_floods_across_hidden_edges_and_past_gaps() {
|
||||
let mut s = session();
|
||||
let g = live_squares(&mut s, &[0.0, 50.0]);
|
||||
let black = Paint::solid(Color::rgb(0.0, 0.0, 0.0));
|
||||
let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 101.0, 51.0));
|
||||
paint_parts(&mut s, &all, &black, &[]);
|
||||
let fill = |s: &mut Session, g: NodeId, at: [f64; 2]| {
|
||||
s.execute("livePaint.fill", &json!({"group": g.0, "point": at, "color": "#00ff00", "scope": "connected"})).unwrap()["count"].clone()
|
||||
};
|
||||
assert_eq!(fill(&mut s, g, [25.0, 25.0]), 1, "a stroked edge stops the flood");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let middle = edges_in(&s, g, Rect::new(50.0, 0.0, 50.0, 50.0));
|
||||
s.execute("object.setProps", &json!({"ids": middle.iter().map(|e| e.0).collect::<Vec<_>>(), "visible": false})).unwrap();
|
||||
assert_eq!(fill(&mut s, g, [25.0, 25.0]), 2, "a hidden edge does not");
|
||||
|
||||
// Square B (100..200 by 0..100) over square C (100..200 by 100..200), and a line down the middle
|
||||
// of B that stops 2 pt short of their shared edge: Gap Detection closes it, so B is two faces
|
||||
// that each run along part of the shared edge, which is one edge segment.
|
||||
let mut s = session();
|
||||
let mut ids = vec![rect(&mut s, 100.0, 0.0, 100.0, 100.0).0, rect(&mut s, 100.0, 100.0, 100.0, 100.0).0];
|
||||
let line = s.execute("path.create", &json!({"anchors": [{"x": 150, "y": 0}, {"x": 150, "y": 98}]})).unwrap();
|
||||
ids.push(line["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": ids})).unwrap();
|
||||
let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("livePaint.gapOptions", &json!({"id": g.0, "detect": true, "size": "small"})).unwrap();
|
||||
let [b1, b2, c] = faces_at(&s, g, &[(125.0, 50.0), (175.0, 50.0), (150.0, 150.0)])[..] else { panic!("three faces") };
|
||||
assert!(b1 != b2 && b2 != c && b1 != c);
|
||||
let all = edges_in(&s, g, Rect::new(99.0, -1.0, 201.0, 201.0));
|
||||
paint_parts(&mut s, &all, &black, &[]);
|
||||
let shared = edges_in(&s, g, Rect::new(100.0, 100.0, 200.0, 100.0));
|
||||
assert!(!shared.is_empty());
|
||||
paint_parts(&mut s, &shared, &Paint::None, &[]);
|
||||
assert_eq!(fill(&mut s, g, [150.0, 150.0]), 3, "from C across the shared edge to both faces of B");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// With the line and the shared edge stroked, only the gap lies between the two faces of B.
|
||||
paint_parts(&mut s, &shared, &black, &[]);
|
||||
assert_eq!(fill(&mut s, g, [125.0, 50.0]), 1, "the flood does not pass the gap");
|
||||
|
||||
// B alone, its outline drawing no stroke and the line stroked: the two faces of B run along
|
||||
// different parts of the outline's bottom segment, on the same side, and the flood does not
|
||||
// join them there.
|
||||
let mut s = session();
|
||||
let mut ids = vec![rect(&mut s, 100.0, 0.0, 100.0, 100.0).0];
|
||||
let line = s.execute("path.create", &json!({"anchors": [{"x": 150, "y": 0}, {"x": 150, "y": 98}]})).unwrap();
|
||||
ids.push(line["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": ids})).unwrap();
|
||||
let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("livePaint.gapOptions", &json!({"id": g.0, "detect": true, "size": "small"})).unwrap();
|
||||
assert_eq!(vectorcraft_tools::builder::faces(&node(&s, g)).len(), 2);
|
||||
let all = edges_in(&s, g, Rect::new(99.0, -1.0, 201.0, 101.0));
|
||||
paint_parts(&mut s, &all, &Paint::None, &[]);
|
||||
let line = edges_in(&s, g, Rect::new(150.0, 0.0, 150.0, 98.0));
|
||||
assert!(!line.is_empty() && line.len() < all.len());
|
||||
paint_parts(&mut s, &line, &black, &[]);
|
||||
assert_eq!(fill(&mut s, g, [125.0, 50.0]), 1, "the gap parts the two faces along the bottom");
|
||||
}
|
||||
|
||||
/// The flood crosses an edge into each face along it when a face's outline runs along the edge in
|
||||
/// one segment and the edge is split where another line meets it.
|
||||
#[test]
|
||||
fn live_paint_bucket_double_click_floods_along_edges_split_at_a_junction() {
|
||||
// A square with a line across its middle, and a line from the top at x = 30 that crosses it and
|
||||
// stops 20 pt below. The bottom face's outline runs along the middle line in one segment, from
|
||||
// x = 0 to 100; the middle line's edges are split at x = 30.
|
||||
let mut s = session();
|
||||
let mut ids = vec![rect(&mut s, 0.0, 0.0, 100.0, 100.0).0];
|
||||
for anchors in [json!([{"x": 0, "y": 50}, {"x": 100, "y": 50}]), json!([{"x": 30, "y": 0}, {"x": 30, "y": 70}])] {
|
||||
ids.push(s.execute("path.create", &json!({ "anchors": anchors })).unwrap()["id"].as_u64().unwrap());
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": ids})).unwrap();
|
||||
let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let [left, right, bottom] = faces_at(&s, g, &[(15.0, 25.0), (65.0, 25.0), (65.0, 75.0)])[..] else { panic!("three faces") };
|
||||
assert!(left != right && right != bottom && left != bottom);
|
||||
let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 101.0, 101.0));
|
||||
paint_parts(&mut s, &all, &Paint::None, &[]);
|
||||
let down = edges_in(&s, g, Rect::new(30.0, 0.0, 30.0, 70.0));
|
||||
assert!(!down.is_empty() && down.len() < all.len());
|
||||
paint_parts(&mut s, &down, &Paint::solid(Color::rgb(0.0, 0.0, 0.0)), &[]);
|
||||
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
|
||||
let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [65, 75], "color": "#00ff00", "scope": "connected"})).unwrap();
|
||||
assert_eq!(r["count"], 3, "from the bottom face to both faces above the line");
|
||||
assert_eq!([left, right, bottom].map(|f| fill_of(&s, f)), [green.clone(), green.clone(), green.clone()]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [15, 25], "color": "#00ff00", "scope": "connected"})).unwrap();
|
||||
assert_eq!(r["count"], 3, "from the upper left face down to the bottom face and up again");
|
||||
}
|
||||
|
||||
/// A triple-click on a face fills every face of the group with that face's fill, joined to it or
|
||||
/// not. Through the tool, the fill compared is the face's fill before the first click.
|
||||
#[test]
|
||||
fn live_paint_bucket_triple_click_fills_every_face_of_the_same_fill() {
|
||||
let mut s = session();
|
||||
let g = live_squares(&mut s, &[0.0, 50.0, 100.0, 150.0]);
|
||||
let [a, b, c, d] = faces_at(&s, g, &[(25.0, 25.0), (75.0, 25.0), (125.0, 25.0), (175.0, 25.0)])[..] else { panic!("four faces") };
|
||||
let (red, blue) = (Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
|
||||
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
|
||||
let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 201.0, 51.0));
|
||||
paint_parts(&mut s, &all, &Paint::None, &[(a, red.clone()), (b, blue.clone()), (c, red.clone()), (d, red.clone())]);
|
||||
let stroked = edges_in(&s, g, Rect::new(100.0, 0.0, 100.0, 50.0));
|
||||
paint_parts(&mut s, &stroked, &Paint::solid(Color::rgb(0.0, 0.0, 0.0)), &[]);
|
||||
let depth = s.doc().unwrap().history.undo.len();
|
||||
let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 25], "color": "#00ff00", "scope": "samePaint"})).unwrap();
|
||||
assert_eq!(r["count"], 3);
|
||||
assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), blue.clone(), green.clone(), green.clone()]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// The tool: the first click fills the face, the double-click floods across x = 50 into B, and
|
||||
// the triple-click fills the faces that were red.
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("livePaintBucket", v).unwrap();
|
||||
s.paint.fill = green.clone();
|
||||
for kind in [
|
||||
PointerKind::Down,
|
||||
PointerKind::Up,
|
||||
PointerKind::Down,
|
||||
PointerKind::Up,
|
||||
PointerKind::DoubleClick,
|
||||
PointerKind::Down,
|
||||
PointerKind::Up,
|
||||
PointerKind::TripleClick,
|
||||
] {
|
||||
s.pointer(&PointerEvent::new(kind, 25.0, 25.0), v).unwrap();
|
||||
}
|
||||
assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), green.clone(), green.clone(), green.clone()]);
|
||||
// A match given by the caller is the fill compared.
|
||||
while s.doc().unwrap().history.undo.len() > depth {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [red.clone(), blue.clone(), red.clone(), red.clone()]);
|
||||
let r = s
|
||||
.execute(
|
||||
"livePaint.fill",
|
||||
&json!({"group": g.0, "point": [25, 25], "color": "#00ff00", "scope": "samePaint", "match": serde_json::to_value(&blue).unwrap()}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r["count"], 2);
|
||||
assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), green, red.clone(), red]);
|
||||
}
|
||||
|
||||
/// A triple-click whose first click makes the Live Paint group from the selected paths matches the
|
||||
/// fill the face was made with.
|
||||
#[test]
|
||||
fn live_paint_bucket_triple_click_after_making_the_group_matches_the_made_fill() {
|
||||
let mut s = session();
|
||||
let ids: Vec<NodeId> = [0.0, 100.0, 200.0].iter().map(|&x| rect(&mut s, x, 0.0, 50.0, 50.0)).collect();
|
||||
let (red, blue) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0));
|
||||
for (id, c) in ids.iter().zip([red, red, blue]) {
|
||||
set_fill(&mut s, *id, c);
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("livePaintBucket", v).unwrap();
|
||||
s.paint.fill = green.clone();
|
||||
for kind in [
|
||||
PointerKind::Down,
|
||||
PointerKind::Up,
|
||||
PointerKind::Down,
|
||||
PointerKind::Up,
|
||||
PointerKind::DoubleClick,
|
||||
PointerKind::Down,
|
||||
PointerKind::Up,
|
||||
PointerKind::TripleClick,
|
||||
] {
|
||||
s.pointer(&PointerEvent::new(kind, 25.0, 25.0), v).unwrap();
|
||||
}
|
||||
let g = vectorcraft_tools::builder::live_paint_at(&s.doc().unwrap().doc, Point::new(25.0, 25.0)).expect("the clicks made a group");
|
||||
let faces = faces_at(&s, g, &[(25.0, 25.0), (125.0, 25.0), (225.0, 25.0)]);
|
||||
assert_eq!(faces.iter().map(|f| fill_of(&s, *f)).collect::<Vec<_>>(), [green.clone(), green, Paint::solid(blue)]);
|
||||
}
|
||||
|
||||
/// A double-click on an edge paints the edges joined to it that have its stroke, and a
|
||||
/// triple-click every edge of the group with that stroke; an edge with another stroke is left.
|
||||
#[test]
|
||||
fn live_paint_bucket_double_and_triple_click_paint_joined_and_same_stroke_edges() {
|
||||
let mut s = session();
|
||||
let g = live_squares(&mut s, &[0.0, 50.0, 200.0]);
|
||||
let black = Paint::solid(Color::rgb(0.0, 0.0, 0.0));
|
||||
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
|
||||
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
|
||||
let joined = edges_in(&s, g, Rect::new(0.0, 0.0, 100.0, 50.0));
|
||||
let apart = edges_in(&s, g, Rect::new(200.0, 0.0, 250.0, 50.0));
|
||||
let middle = edges_in(&s, g, Rect::new(50.0, 0.0, 50.0, 50.0));
|
||||
assert!(!apart.is_empty() && !middle.is_empty());
|
||||
paint_parts(&mut s, &joined, &black, &[]);
|
||||
paint_parts(&mut s, &apart, &black, &[]);
|
||||
paint_parts(&mut s, &middle, &red, &[]);
|
||||
let stroke = |s: &Session, ids: &[NodeId]| ids.iter().map(|id| node(s, *id).appearance.stroke_paint()).collect::<Vec<_>>();
|
||||
let outer: Vec<NodeId> = joined.iter().copied().filter(|e| !middle.contains(e)).collect();
|
||||
let r =
|
||||
s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": [25, 0], "color": "#00ff00", "width": 3, "scope": "connected"})).unwrap();
|
||||
assert_eq!(r["count"], outer.len());
|
||||
assert!(stroke(&s, &outer).iter().all(|p| *p == green));
|
||||
assert!(outer.iter().all(|e| node(&s, *e).appearance.stroke_width() == 3.0));
|
||||
assert!(stroke(&s, &middle).iter().all(|p| *p == red), "another stroke is left");
|
||||
assert!(stroke(&s, &apart).iter().all(|p| *p == black), "edges not joined are left");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let r = s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": [25, 0], "color": "#00ff00", "scope": "samePaint"})).unwrap();
|
||||
assert_eq!(r["count"], outer.len() + apart.len());
|
||||
assert!(stroke(&s, &outer).iter().chain(&stroke(&s, &apart)).all(|p| *p == green));
|
||||
assert!(stroke(&s, &middle).iter().all(|p| *p == red));
|
||||
// A hidden edge is not painted.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("object.setProps", &json!({"ids": [apart[0].0], "visible": false})).unwrap();
|
||||
let r = s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": [25, 0], "color": "#00ff00", "scope": "samePaint"})).unwrap();
|
||||
assert_eq!(r["count"], outer.len() + apart.len() - 1);
|
||||
assert_eq!(node(&s, apart[0]).appearance.stroke_paint(), black);
|
||||
}
|
||||
|
||||
/// A `scope` that is not one of the three, a `match` that is not a paint or is given with a scope
|
||||
/// that compares none, and a scope with a drag's points are refused; nothing changes.
|
||||
#[test]
|
||||
fn live_paint_scope_and_match_are_checked() {
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
let none = serde_json::to_value(Paint::None).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let depth = s.doc().unwrap().history.undo.len();
|
||||
for (cmd, p) in [
|
||||
("livePaint.fill", json!({"group": g.0, "point": [75, 50], "scope": "all"})),
|
||||
("livePaint.fill", json!({"group": g.0, "point": [75, 50], "scope": 2})),
|
||||
("livePaint.fill", json!({"group": g.0, "point": [75, 50], "match": none})),
|
||||
("livePaint.fill", json!({"group": g.0, "point": [75, 50], "scope": "connected", "match": none})),
|
||||
("livePaint.fill", json!({"group": g.0, "point": [75, 50], "scope": "samePaint", "match": "red"})),
|
||||
("livePaint.fill", json!({"group": g.0, "point": [75, 50], "scope": "connected", "points": [[75, 50], [125, 50]]})),
|
||||
("livePaint.strokeEdge", json!({"group": g.0, "point": [100, 50], "scope": "Connected"})),
|
||||
("livePaint.strokeEdge", json!({"group": g.0, "point": [100, 50], "scope": "one", "match": none})),
|
||||
("livePaint.strokeEdge", json!({"group": g.0, "point": [100, 50], "scope": "samePaint", "match": {"type": "plaid"}})),
|
||||
] {
|
||||
assert!(s.execute(cmd, &p).is_err(), "{cmd} {p}");
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), depth);
|
||||
// "one" and null are a click's scope.
|
||||
for scope in [json!("one"), Value::Null] {
|
||||
let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [75, 50], "scope": scope})).unwrap();
|
||||
assert_eq!(r["count"], 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn live_paint_release_and_expand() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -119,12 +119,80 @@ fn text_on_top_clips_by_its_glyphs() {
|
||||
assert_eq!(hit(&s, (b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0), Some(art));
|
||||
assert!(b.x1 < 95.0, "{b:?}");
|
||||
assert_eq!(hit(&s, b.x1 + 3.0, (b.y0 + b.y1) / 2.0), None, "beside the text");
|
||||
// An effect that does not reshape it, such as a drop shadow, leaves clicks on its frame.
|
||||
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "params": {}, "ids": [t.0], "item": null})).unwrap();
|
||||
assert_eq!(hit(&s, (b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0), Some(art), "in the counter, with a drop shadow");
|
||||
// Release gives the text back.
|
||||
select(&mut s, &[g]);
|
||||
s.execute("object.clippingMask.release", &json!({})).unwrap();
|
||||
assert!(matches!(s.doc().unwrap().doc.node(t).unwrap().kind, NodeKind::Text(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hidden_member_of_a_clipping_group_leaves_clicks_on_the_type_frame() {
|
||||
// The clipping path is a group of an "O" and a hidden rectangle with a Transform effect. The
|
||||
// hidden rectangle does not clip, so clicks inside the clip group still count the type by its
|
||||
// frame, the counter of the "O" included.
|
||||
let mut s = session();
|
||||
let art = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap());
|
||||
let t = id_of(&s.execute("text.create", &json!({"x": 5, "y": 80, "text": "O", "size": 90})).unwrap());
|
||||
let b = s.doc().unwrap().doc.node(t).unwrap().geometric_bounds().unwrap();
|
||||
let r = id_of(&s.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 10, "height": 10})).unwrap());
|
||||
s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"moveH": 20}, "ids": [r.0], "item": null})).unwrap();
|
||||
select(&mut s, &[art, t]);
|
||||
let g = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap());
|
||||
// Make Clipping Mask takes no group on top, so the group goes in place of the type.
|
||||
let mut d = (*s.doc().unwrap().doc).clone();
|
||||
let mut rect = (*d.remove(r).unwrap()).clone();
|
||||
rect.visible = false;
|
||||
let text = d.remove(t).unwrap();
|
||||
let group = vectorcraft_doc::Node::group(d.alloc_id(), vec![text, Arc::new(rect)]);
|
||||
d.insert(Some(g), 0, group).unwrap();
|
||||
let leaf = |x: f64, y: f64| vectorcraft_doc::hit::hit_test(&d, vectorcraft_geom::Point::new(x, y), Default::default()).map(|h| h.leaf);
|
||||
let middle = ((b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0);
|
||||
assert_eq!(leaf(middle.0, middle.1), Some(art), "in the counter, inside the frame");
|
||||
assert_eq!(leaf(b.x1 + 3.0, middle.1), None, "beside the text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clicks_follow_the_region_a_clipping_paths_effects_give_it() {
|
||||
// Art from 10 to 90 pt, clipped by the artboard's left half, which a Transform effect moves
|
||||
// 50 pt right: the art shows on the right half, as clicks find it.
|
||||
let mut s = session();
|
||||
let art = id_of(&s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 80, "height": 80})).unwrap());
|
||||
let clip = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 100})).unwrap());
|
||||
select(&mut s, &[art, clip]);
|
||||
let g = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap());
|
||||
s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"moveH": 50}, "ids": [clip.0], "item": null})).unwrap();
|
||||
let r = render(&s);
|
||||
assert!(opaque(&r, 75, 50) && !opaque(&r, 25, 50), "the canvas clips by the moved region");
|
||||
assert_eq!(hit(&s, 75.0, 50.0), Some(art), "where the effect moved the clipping path");
|
||||
assert_eq!(hit(&s, 25.0, 50.0), None, "the clipping path's own place");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let at = |x: f64| vectorcraft_doc::hit::objects_at(d, vectorcraft_geom::Point::new(x, 50.0), Default::default(), None);
|
||||
assert_eq!(at(75.0), [g]);
|
||||
assert!(at(25.0).is_empty());
|
||||
// A marquee across the art's edge reaches it within the moved region only.
|
||||
let marquee = |x0: f64, x1: f64| vectorcraft_doc::hit::marquee(d, vectorcraft_geom::Rect::new(x0, 40.0, x1, 60.0), None, true);
|
||||
assert_eq!(marquee(85.0, 95.0), [art], "the right edge, in the moved region");
|
||||
assert!(marquee(5.0, 15.0).is_empty(), "the left edge, in the clipping path's own place");
|
||||
|
||||
// The same with a sublayer that clips by its first object.
|
||||
let mut d = (**d).clone();
|
||||
let members: Vec<_> = d.node(g).unwrap().children().unwrap().to_vec();
|
||||
let top = d.layers[0].id;
|
||||
d.remove(g).unwrap();
|
||||
let mut sublayer = (*d.layers[0]).clone();
|
||||
sublayer.id = d.alloc_id();
|
||||
if let NodeKind::Layer { children, clip, .. } = &mut sublayer.kind {
|
||||
(*children, *clip) = (members, true);
|
||||
}
|
||||
d.insert(Some(top), 0, sublayer).unwrap();
|
||||
let leaf = |x: f64| vectorcraft_doc::hit::hit_test(&d, vectorcraft_geom::Point::new(x, 50.0), Default::default()).map(|h| h.leaf);
|
||||
assert_eq!(leaf(75.0), Some(art));
|
||||
assert_eq!(leaf(25.0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn make_refuses_a_top_object_that_cannot_clip() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Width points, Liquify, Puppet Warp and Perspective Grid commands and tools.
|
||||
|
||||
use serde_json::json;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_geom::{PathData, Point, Rect, Shape};
|
||||
use vectorcraft_tools::distort::perspective::{PerspectiveGrid, Plane};
|
||||
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
|
||||
@@ -625,6 +625,25 @@ fn attach_projects_onto_the_plane_and_releases() {
|
||||
assert_eq!(path(&s, a).bounds().unwrap(), Rect::new(450.0, 300.0, 550.0, 400.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_repeated_id_attaches_moves_and_transforms_an_object_once() {
|
||||
let edited = |cmd: &str, ids: &[u64], extra: Value| {
|
||||
let mut s = session();
|
||||
s.execute("perspective.grid.preset", &json!({"kind": 2})).unwrap();
|
||||
let a = rect(&mut s, 450.0, 300.0, 100.0, 100.0);
|
||||
let ids: Vec<u64> = ids.iter().map(|_| a.0).collect();
|
||||
let mut p = json!({"ids": ids, "plane": "right"});
|
||||
p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
|
||||
s.execute(cmd, &p).unwrap();
|
||||
path(&s, a)
|
||||
};
|
||||
let moved = json!({"from": [480.0, 330.0], "to": [500.0, 350.0], "constrain": true});
|
||||
let scaled = json!({"matrix": [1.5, 0.0, 0.0, 1.5, 10.0, 0.0]});
|
||||
for (cmd, extra) in [("perspective.attach", json!({})), ("perspective.move", moved), ("perspective.transform", scaled)] {
|
||||
assert_eq!(edited(cmd, &[0, 0], extra.clone()), edited(cmd, &[0], extra), "{cmd}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rectangle_tool_draws_in_perspective_on_the_active_plane() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -219,9 +219,10 @@ fn rotate_reflect_and_scale_carry_unplaced_gradients() {
|
||||
s.execute("object.rotate", &json!({"angle": 90})).unwrap();
|
||||
let g = fill_geom(&s, id);
|
||||
assert!((g.end.x - g.start.x).abs() < 1e-9 && (g.length() - 100.0).abs() < 1e-9, "vertical after a 90° turn: {g:?}");
|
||||
s.execute("object.reflect", &json!({"axis": "horizontal"})).unwrap();
|
||||
s.execute("object.reflect", &json!({"axis": "horizontal", "basis": "page"})).unwrap();
|
||||
let r = fill_geom(&s, id);
|
||||
// The vertical vector is centred on the object, so the reflection swaps its ends.
|
||||
// The vertical vector is centred on the object, so the reflection across the page's
|
||||
// horizontal axis swaps its ends.
|
||||
assert!(r.start.distance(g.end) < 1e-9 && r.end.distance(g.start) < 1e-9, "{g:?} → {r:?}");
|
||||
|
||||
// A circle's radial gradient becomes an ellipse under a non-uniform scale.
|
||||
|
||||
@@ -406,7 +406,7 @@ fn a_batch_step_records_what_it_took_from_the_preferences() {
|
||||
]);
|
||||
s.execute("command.batch", &json!({ "commands": steps })).unwrap();
|
||||
let p = &s.journal.last().unwrap().1;
|
||||
assert_eq!(p["commands"][2]["params"], json!({"sx": 300, "strokes": true, "corners": false}));
|
||||
assert_eq!(p["commands"][2]["params"], json!({"sx": 300, "strokes": true, "corners": false, "basis": "box"}));
|
||||
// Replayed with other preferences, the scale still scales the stroke.
|
||||
let r = replayed(&s);
|
||||
assert!(!r.prefs.scale_strokes);
|
||||
|
||||
@@ -1700,6 +1700,7 @@ fn filters_set_effects_and_stroke_styles() {
|
||||
("test.engine.badn", json!([{"id": "plugin.test.engine.fx", "params": {"n": "two"}}]), "`n`"),
|
||||
("test.engine.file", json!([{"id": "distort.glass", "params": {"textureImage": {"path": "/etc/hosts"}}}]), "textureImage"),
|
||||
("test.engine.file2", json!([{"id": "texture.texturizer", "params": {"textureImage": {"path": "/etc/hosts"}}}]), "textureImage"),
|
||||
("test.engine.file3", json!([{"id": "artistic.roughPastels", "params": {"textureImage": {"path": "/etc/hosts"}}}]), "textureImage"),
|
||||
("test.engine.two3d", json!([{"id": "threeD.extrude"}, {"id": "threeD.extrude"}]), "one 3D effect"),
|
||||
] {
|
||||
let e = filter(&mut s, name, fx).unwrap_err().to_string();
|
||||
|
||||
@@ -143,19 +143,22 @@ fn listed_applied_edited_and_undone() {
|
||||
}
|
||||
}
|
||||
// Numbers far out of range are stored as given and read clamped; the canvas still draws.
|
||||
// Radial Blur's Blur Center is refused outside 0 to 1 instead.
|
||||
let center = |id: &str, k: &str| id == "blur.radial" && matches!(k, "centerX" | "centerY");
|
||||
for (id, _) in EFFECTS {
|
||||
let defaults = vectorcraft_render::effects::default_params(id).unwrap();
|
||||
let junk: serde_json::Map<String, Value> = defaults
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|(_, v)| v.is_number())
|
||||
.filter(|(k, v)| v.is_number() && !center(id, k))
|
||||
.enumerate()
|
||||
.map(|(i, (k, _))| (k.clone(), json!(if i % 2 == 0 { 1e308 } else { -1e308 })))
|
||||
.collect();
|
||||
assert!(!junk.is_empty(), "{id}");
|
||||
s.execute("effect.apply", &json!({"effect": id, "ids": [g], "params": junk})).unwrap();
|
||||
}
|
||||
assert!(s.execute("effect.apply", &json!({"effect": "blur.radial", "ids": [g], "params": {"centerX": 1e308}})).is_err());
|
||||
let _ = render(&s);
|
||||
let n = s.doc().unwrap().doc.node(NodeId(g)).unwrap().clone();
|
||||
assert_eq!(n.appearance.effects.len(), 3);
|
||||
@@ -320,8 +323,7 @@ fn glass_loads_a_texture_saves_it_and_draws_it() {
|
||||
assert_eq!(doc.node(NodeId(g)).unwrap().appearance.effects[0].params, glass_params(&s, g));
|
||||
assert_eq!(Renderer::new().render_region(&doc, Rect::new(0.0, 0.0, 200.0, 200.0), 1.0, true).pixels, loaded.pixels);
|
||||
// The same file by path, through Effect Options, stores the same texture.
|
||||
let dir = std::env::temp_dir().join(format!("vc-glass-texture-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let dir = vectorcraft_testkit::TempDir::new("glass-texture");
|
||||
let path = dir.join("rings.png");
|
||||
std::fs::write(&path, &png).unwrap();
|
||||
let (mut t, h) = striped();
|
||||
@@ -331,7 +333,7 @@ fn glass_loads_a_texture_saves_it_and_draws_it() {
|
||||
assert_eq!(glass_params(&t, h)["textureImage"], json!(stored));
|
||||
assert_eq!(glass_params(&t, h)["texture"], json!("loaded"));
|
||||
assert_eq!(render(&t).pixels, loaded.pixels);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
drop(dir);
|
||||
// The stored string is taken as it is (as effect.list gives it, and a graphic style copies it).
|
||||
t.execute("effect.apply", &json!({"effect": "distort.glass", "ids": [h], "params": {"textureImage": stored, "texture": "frosted"}})).unwrap();
|
||||
let second = t.doc().unwrap().doc.node(NodeId(h)).unwrap().appearance.effects[1].params.clone();
|
||||
@@ -388,6 +390,53 @@ fn texturizer_loads_a_texture_and_draws_it() {
|
||||
assert_eq!(Renderer::new().render_region(&doc, Rect::new(0.0, 0.0, 200.0, 200.0), 1.0, true).pixels, loaded.pixels);
|
||||
}
|
||||
|
||||
/// Effect › Artistic › Rough Pastels › Load Texture: an image file, given as bytes or by path, is
|
||||
/// stored with the effect and picked; it draws as the surface, a save and open keeps it, a file
|
||||
/// that isn't an image is refused without a change, and undo takes it away.
|
||||
#[test]
|
||||
fn rough_pastels_loads_a_texture_saves_it_and_draws_it() {
|
||||
let png = rings_png();
|
||||
let data = vectorcraft_format::base64_encode(&png);
|
||||
let (mut s, g) = striped();
|
||||
let file = json!({"name": "rings.png", "dataBase64": data});
|
||||
s.execute("effect.apply", &json!({"effect": "artistic.roughPastels", "ids": [g], "params": {"relief": 20, "textureImage": file}})).unwrap();
|
||||
let p = glass_params(&s, g);
|
||||
assert_eq!(p["texture"], json!("loaded"), "loading a texture picks it");
|
||||
let stored = p["textureImage"].as_str().unwrap().to_string();
|
||||
assert_eq!(vectorcraft_render::effects::pixel::texture(&stored).unwrap().size(), (12, 10));
|
||||
let loaded = render(&s);
|
||||
for (_, builtin) in vectorcraft_render::effects::pixel::TEXTURES {
|
||||
s.execute("effect.setParams", &json!({"index": 0, "ids": [g], "params": {"texture": builtin}})).unwrap();
|
||||
assert!(mean_diff(&loaded, &render(&s)) > 0.001, "{builtin}");
|
||||
}
|
||||
s.execute("effect.setParams", &json!({"index": 0, "ids": [g], "params": {"texture": "loaded"}})).unwrap();
|
||||
assert_eq!(render(&s).pixels, loaded.pixels, "the texture stayed with the effect");
|
||||
let doc = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
|
||||
assert_eq!(doc.node(NodeId(g)).unwrap().appearance.effects[0].params, glass_params(&s, g));
|
||||
assert_eq!(Renderer::new().render_region(&doc, Rect::new(0.0, 0.0, 200.0, 200.0), 1.0, true).pixels, loaded.pixels);
|
||||
// A file that isn't an image changes nothing.
|
||||
let junk = vectorcraft_format::base64_encode(b"not an image");
|
||||
let before = glass_params(&s, g);
|
||||
let e = s.execute("effect.setParams", &json!({"index": 0, "ids": [g], "params": {"textureImage": {"dataBase64": junk}}})).unwrap_err();
|
||||
assert!(e.to_string().contains("textureImage"), "{e}");
|
||||
let e = s.execute("effect.setParams", &json!({"index": 0, "ids": [g], "params": {"textureImage": 5}})).unwrap_err();
|
||||
assert!(e.to_string().contains("textureImage"), "{e}");
|
||||
assert_eq!(glass_params(&s, g), before);
|
||||
// The same file by path, through Effect Options, stores the same texture; undo takes it away.
|
||||
let dir = vectorcraft_testkit::TempDir::new("rough-pastels-texture");
|
||||
let path = dir.join("rings.png");
|
||||
std::fs::write(&path, &png).unwrap();
|
||||
let (mut t, h) = striped();
|
||||
t.execute("effect.apply", &json!({"effect": "artistic.roughPastels", "ids": [h], "params": {"relief": 20}})).unwrap();
|
||||
assert!(glass_params(&t, h).get("textureImage").is_none());
|
||||
t.execute("effect.setParams", &json!({"index": 0, "ids": [h], "params": {"textureImage": {"path": path.to_string_lossy()}}})).unwrap();
|
||||
drop(dir);
|
||||
assert_eq!((&glass_params(&t, h)["textureImage"], &glass_params(&t, h)["texture"]), (&json!(stored), &json!("loaded")));
|
||||
assert_eq!(render(&t).pixels, loaded.pixels);
|
||||
t.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(glass_params(&t, h).get("textureImage").is_none(), "undone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spin_blur_reaches_past_the_corners() {
|
||||
let (mut s, g) = striped();
|
||||
|
||||
@@ -216,7 +216,7 @@ fn the_journal_records_the_scale_options_used() {
|
||||
run(&mut s, "object.scale", json!({"sx": 150}));
|
||||
let (cmd, p) = s.journal.last().unwrap().clone();
|
||||
assert_eq!(cmd, "object.scale");
|
||||
assert_eq!(p, json!({"sx": 150, "strokes": false, "corners": true}));
|
||||
assert_eq!(p, json!({"sx": 150, "strokes": false, "corners": true, "basis": "box"}));
|
||||
// An explicit value stays; moves don't scale, so they record nothing.
|
||||
run(&mut s, "object.scale", json!({"sx": 150, "strokes": true}));
|
||||
assert_eq!(s.journal.last().unwrap().1["strokes"], json!(true));
|
||||
|
||||
@@ -715,3 +715,179 @@ fn svg_export_draws_a_filter_svg_1_1_lacks_as_an_image() {
|
||||
assert_eq!((out.contains("<image"), out.contains("<feBlend")), (image, !image), "{mode}: {out}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The `defaults` of `svgFilter.list`: each one's name and whether the document holds it.
|
||||
fn defaults(s: &mut Session) -> Vec<(String, bool)> {
|
||||
let listed = run(s, "svgFilter.list", json!({}))["defaults"].as_array().cloned().unwrap_or_default();
|
||||
listed.iter().map(|f| (f["name"].as_str().unwrap().to_string(), f["inDocument"].as_bool().unwrap())).collect()
|
||||
}
|
||||
|
||||
/// Every document lists the default filters without holding them; applying one adds the effect and
|
||||
/// the document's copy in one undo step.
|
||||
#[test]
|
||||
fn a_default_filter_is_listed_and_copied_into_the_document_when_applied() {
|
||||
use vectorcraft_render::effects::svg_filter::defaults::DEFAULT_FILTERS;
|
||||
let mut s = session();
|
||||
let listed = defaults(&mut s);
|
||||
assert_eq!(listed.len(), DEFAULT_FILTERS.len());
|
||||
assert!(listed.iter().all(|(_, held)| !held), "a new document holds none of them");
|
||||
assert!(names(&mut s).is_empty());
|
||||
let soft = DEFAULT_FILTERS.iter().find(|f| f.name == "Soft Shadow").unwrap();
|
||||
assert_eq!(run(&mut s, "svgFilter.list", json!({}))["defaults"][2], json!({"name": "Soft Shadow", "xml": soft.xml, "inDocument": false}));
|
||||
let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 50.0));
|
||||
run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
|
||||
let before = steps(&s);
|
||||
let r = run(&mut s, "svgFilter.apply", json!({"name": "Soft Shadow"}));
|
||||
assert_eq!((r["ids"].as_array().unwrap().len(), &r["index"]), (2, &json!(0)));
|
||||
assert_eq!(steps(&s), before + 1, "the effect and the copy are one step");
|
||||
assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "SVG Filter");
|
||||
assert_eq!(names(&mut s), ["Soft Shadow"]);
|
||||
assert_eq!(drawn(&s, a), json!(soft.xml));
|
||||
assert!(defaults(&mut s).contains(&("Soft Shadow".to_string(), true)));
|
||||
// Applied again, the document's copy is the filter: nothing more is added.
|
||||
run(&mut s, "svgFilter.apply", json!({"name": "Soft Shadow", "ids": [a.0]}));
|
||||
assert_eq!(names(&mut s), ["Soft Shadow"]);
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert!(names(&mut s).is_empty(), "undo takes the copy back with the effect");
|
||||
assert!(s.doc().unwrap().doc.node(a).unwrap().appearance.effects.is_empty());
|
||||
run(&mut s, "edit.redo", json!({}));
|
||||
assert_eq!((names(&mut s), drawn(&s, b)), (vec!["Soft Shadow".to_string()], json!(soft.xml)));
|
||||
// Nothing to apply it to: no copy and no step.
|
||||
let mut s = session();
|
||||
assert!(s.execute("svgFilter.apply", &json!({"name": "Glow"})).is_err(), "nothing selected");
|
||||
assert!(names(&mut s).is_empty());
|
||||
assert_eq!(steps(&s), 0);
|
||||
assert!(err(&mut s, "svgFilter.apply", json!({"name": "glow", "ids": []})).contains("no SVG filter named \"glow\""), "names match exactly");
|
||||
}
|
||||
|
||||
/// With a full history, applying a default lets one old step go, as any edit does: the copy joins
|
||||
/// the step that applied it, and one Undo takes both back.
|
||||
#[test]
|
||||
fn a_default_applied_with_a_full_history_is_still_one_step() {
|
||||
let mut s = session();
|
||||
s.active_mut().unwrap().history.limit = 3;
|
||||
let a = rect(&mut s, 10.0);
|
||||
rect(&mut s, 30.0);
|
||||
rect(&mut s, 50.0);
|
||||
assert_eq!(steps(&s), 3);
|
||||
run(&mut s, "svgFilter.apply", json!({"name": "Invert", "ids": [a.0]}));
|
||||
// The application takes one place in the history: only the oldest step went.
|
||||
assert_eq!(steps(&s), 3);
|
||||
assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "SVG Filter");
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert!(names(&mut s).is_empty(), "the copy is undone with the effect");
|
||||
assert!(s.doc().unwrap().doc.node(a).unwrap().appearance.effects.is_empty());
|
||||
}
|
||||
|
||||
/// Edit SVG Filter on a default saves the edited copy in the document under the default's name;
|
||||
/// the document's filter then stands in the default's place, and deleting it lists the default again.
|
||||
#[test]
|
||||
fn an_edited_default_is_saved_in_the_document_and_delete_restores_the_default() {
|
||||
use vectorcraft_render::effects::svg_filter::defaults::default_filter;
|
||||
let mut s = session();
|
||||
let glow = default_filter("Glow").unwrap();
|
||||
// Saved with its own code: nothing to keep, and no undo step.
|
||||
run(&mut s, "svgFilter.define", json!({"xml": glow.xml, "replace": "Glow"}));
|
||||
assert_eq!((names(&mut s).len(), steps(&s)), (0, 0));
|
||||
let edited = r#"<filter id="Renamed"><feGaussianBlur stdDeviation="9"/></filter>"#;
|
||||
assert_eq!(run(&mut s, "svgFilter.define", json!({"xml": edited, "replace": "Glow"}))["name"], "Glow");
|
||||
assert_eq!((names(&mut s), steps(&s)), (vec!["Glow".to_string()], 1));
|
||||
assert_eq!(s.doc().unwrap().history.undo[0].label, "Edit SVG Filter");
|
||||
let kept = r#"<filter id="Glow"><feGaussianBlur stdDeviation="9"/></filter>"#;
|
||||
assert_eq!(run(&mut s, "svgFilter.list", json!({}))["filters"][0]["xml"], kept, "it keeps the default's name");
|
||||
// Applying the name now applies the document's filter.
|
||||
let a = rect(&mut s, 10.0);
|
||||
run(&mut s, "svgFilter.apply", json!({"name": "Glow", "ids": [a.0]}));
|
||||
assert_eq!(drawn(&s, a), json!(kept));
|
||||
// Deleting the copy leaves the effect drawing nothing, as for any filter, and lists the default.
|
||||
run(&mut s, "svgFilter.delete", json!({"name": "Glow"}));
|
||||
assert_eq!(drawn(&s, a), json!(""));
|
||||
assert!(defaults(&mut s).contains(&("Glow".to_string(), false)));
|
||||
// The default itself is not deleted.
|
||||
let before = steps(&s);
|
||||
assert!(err(&mut s, "svgFilter.delete", json!({"name": "Glow"})).contains("is a default SVG filter"));
|
||||
assert!(err(&mut s, "svgFilter.delete", json!({"name": "Nope"})).contains("no SVG filter named"));
|
||||
assert_eq!(steps(&s), before);
|
||||
// Applied again, the default is copied back, and the object that named it draws with it.
|
||||
let b = rect(&mut s, 50.0);
|
||||
run(&mut s, "svgFilter.apply", json!({"name": "Glow", "ids": [b.0]}));
|
||||
assert_eq!((drawn(&s, a), drawn(&s, b)), (json!(glow.xml), json!(glow.xml)));
|
||||
assert_eq!(steps(&s), before + 2, "the rectangle and one step for the application");
|
||||
// A new filter may take a default's name the document does not hold.
|
||||
let mut s = session();
|
||||
run(&mut s, "svgFilter.define", json!({"xml": r#"<filter id="Invert"><feOffset dx="1"/></filter>"#}));
|
||||
assert!(defaults(&mut s).contains(&("Invert".to_string(), true)));
|
||||
// An unknown name is still refused.
|
||||
assert!(err(&mut s, "svgFilter.define", json!({"xml": SHIFT, "replace": "Nope"})).contains("no SVG filter named \"Nope\""));
|
||||
}
|
||||
|
||||
/// With `index`, the filter takes the place of an applied SVG filter, a default with its copy in
|
||||
/// the same undo step; any other effect keeps its place.
|
||||
#[test]
|
||||
fn apply_with_an_index_replaces_an_applied_filter() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 10.0);
|
||||
run(&mut s, "svgFilter.define", json!({"xml": SHIFT}));
|
||||
run(&mut s, "svgFilter.apply", json!({"name": "Shift", "ids": [a.0]}));
|
||||
run(&mut s, "effect.apply", json!({"effect": "stylize.feather", "ids": [a.0]}));
|
||||
let before = steps(&s);
|
||||
let r = run(&mut s, "svgFilter.apply", json!({"name": "Invert", "ids": [a.0], "index": 0, "item": null}));
|
||||
assert_eq!(r["ids"], json!([a.0]));
|
||||
assert_eq!(steps(&s), before + 1, "one step");
|
||||
let fx = s.doc().unwrap().doc.node(a).unwrap().appearance.effects.clone();
|
||||
assert_eq!((fx.len(), fx[0].params["name"].as_str(), fx[1].id.as_str()), (2, Some("Invert"), "stylize.feather"));
|
||||
assert_eq!(names(&mut s), ["Shift", "Invert"]);
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(names(&mut s), ["Shift"]);
|
||||
assert_eq!(s.doc().unwrap().doc.node(a).unwrap().appearance.effects[0].params["name"], "Shift");
|
||||
// Not an SVG filter, no effect there, or not an index: refused, and the default is not copied.
|
||||
let before = steps(&s);
|
||||
for (index, why) in [
|
||||
(json!(1), "applied SVG filter"),
|
||||
(json!(7), "applied SVG filter"),
|
||||
(json!("x"), "`index`"),
|
||||
(json!(-1), "`index`"),
|
||||
(json!(null), "`index`"),
|
||||
] {
|
||||
let e = err(&mut s, "svgFilter.apply", json!({"name": "Invert", "ids": [a.0], "index": index, "item": null}));
|
||||
assert!(e.contains(why), "{index}: {e}");
|
||||
}
|
||||
assert_eq!((names(&mut s), steps(&s)), (vec!["Shift".to_string()], before));
|
||||
}
|
||||
|
||||
/// A default needs room in the document: at 64 filters applying one is refused, and a filter the
|
||||
/// document holds still applies.
|
||||
#[test]
|
||||
fn a_full_document_refuses_a_default_it_does_not_hold() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 10.0);
|
||||
for i in 0..64 {
|
||||
run(&mut s, "svgFilter.define", json!({"xml": format!("<filter id=\"f{i}\"><feOffset/></filter>")}));
|
||||
}
|
||||
let before = steps(&s);
|
||||
assert!(err(&mut s, "svgFilter.apply", json!({"name": "Glow", "ids": [a.0]})).contains("at most 64 SVG filters"));
|
||||
let edited = r#"<filter id="Glow"><feOffset dx="2"/></filter>"#;
|
||||
assert!(err(&mut s, "svgFilter.define", json!({"xml": edited, "replace": "Glow"})).contains("at most 64 SVG filters"));
|
||||
assert_eq!(steps(&s), before);
|
||||
assert!(s.doc().unwrap().doc.node(a).unwrap().appearance.effects.is_empty());
|
||||
run(&mut s, "svgFilter.apply", json!({"name": "f3", "ids": [a.0]}));
|
||||
}
|
||||
|
||||
/// A default applied in one document is written to SVG as a filter and read back from the native
|
||||
/// format with the document's copy.
|
||||
#[test]
|
||||
fn an_applied_default_survives_svg_export_and_a_native_round_trip() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 10.0);
|
||||
run(&mut s, "svgFilter.apply", json!({"name": "Grayscale", "ids": [a.0]}));
|
||||
let out = svg(&mut s);
|
||||
assert!(out.contains("<feColorMatrix") && out.contains("saturate"), "{out}");
|
||||
let (back, warnings) = vectorcraft_svg::import_with_report(&out).unwrap();
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
assert!(back.any_node(|n| n.appearance.effects.iter().any(|e| e.id == "svg.filter")), "SVG import reads the filter back");
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let again = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap();
|
||||
assert_eq!(again.svg_filters, doc.svg_filters);
|
||||
assert_eq!(again.svg_filters[0].name, "Grayscale");
|
||||
}
|
||||
|
||||
@@ -2284,7 +2284,7 @@ fn a_variable_library_defines_text_variables_and_data_sets() {
|
||||
assert_eq!(r["variables"], json!(["Name", "Note"]));
|
||||
assert_eq!((r["deleted"].clone(), r["deletedDataSets"].clone()), (json!([]), json!([])));
|
||||
assert_eq!(r["names"], json!(["Row 1", "Row 2"]));
|
||||
assert_eq!((r["skipped"].clone(), r.get("warning")), (json!([]), None));
|
||||
assert_eq!((r.get("skipped"), r.get("warning")), (None, None));
|
||||
let listed = s.execute("variable.list", &json!({})).unwrap();
|
||||
assert_eq!(listed["variables"], json!([{"name": "Name", "kind": "text", "bindings": 0}, {"name": "Note", "kind": "text", "bindings": 0}]));
|
||||
let sets = s.execute("dataset.list", &json!({})).unwrap();
|
||||
@@ -2405,13 +2405,14 @@ fn an_import_or_library_load_that_changes_nothing_records_no_undo_step() {
|
||||
s.execute("variable.loadLibrary", &json!({"xml": other})).unwrap();
|
||||
assert_eq!(super::history(&s), (undo + 1, 0, true));
|
||||
|
||||
// While the variables are locked, a library without text variables still loads its data sets,
|
||||
// and loading it again changes nothing.
|
||||
// While the variables are locked, a library of the variables the document has, with their
|
||||
// kinds, still loads its data sets, and loading it again changes nothing.
|
||||
let mut s = session();
|
||||
let t = text(&mut s, "Alice");
|
||||
s.execute("variable.lock", &json!({"locked": true})).unwrap();
|
||||
let xml = library(&[("Shown", "other")], &[("B", &[])]);
|
||||
s.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap();
|
||||
s.execute("variable.lock", &json!({"locked": true})).unwrap();
|
||||
s.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap();
|
||||
super::select_with_a_step_to_redo(&mut s, &[t]);
|
||||
let before = super::history(&s);
|
||||
s.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap();
|
||||
@@ -2432,22 +2433,89 @@ fn a_refused_variable_library_deletes_nothing() {
|
||||
assert_eq!(s.doc().unwrap().doc.variables, before);
|
||||
}
|
||||
|
||||
/// A library's variables of other kinds are left out with their values, named in `skipped` and
|
||||
/// in a warning that gives each kind once with its count; its text variables load.
|
||||
/// A library of every kind, in the layout the public grammar gives: visibility (`visibility`),
|
||||
/// image (`fileref`) and graph (`graphdata`) variables beside a text variable, a variable without a
|
||||
/// `trait` and one whose `trait` VectorCraft doesn't know, with values in the forms
|
||||
/// [`a_variable_library_defines_every_kind_with_its_values`] reads.
|
||||
fn every_kind_library() -> String {
|
||||
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n\
|
||||
<!DOCTYPE svg [<!ENTITY ns_vars \"http://ns.adobe.com/Variables/1.0/\"><!ENTITY ns_custom \"http://ns.adobe.com/GenericCustomNamespace/1.0/\">]>\n\
|
||||
<svg><variableSets xmlns=\"&ns_vars;\"><variableSet varSetName=\"binding1\" locked=\"none\"><variables>\
|
||||
<variable varName=\"Name\" trait=\"textcontent\"/><variable varName=\"Shown\" trait=\"visibility\"/>\
|
||||
<variable varName=\"Photo\" trait=\"fileref\"/><variable varName=\"Chart\" trait=\"graphdata\"/>\
|
||||
<variable varName=\"Loose\"/><variable varName=\"Odd\" trait=\"somethingelse\"/></variables>\
|
||||
<v:sampleDataSets xmlns:v=\"&ns_vars;\" xmlns=\"&ns_custom;\">\
|
||||
<v:sampleDataSet dataSetName=\"A\"><Name><p>Bravo</p></Name><Shown>true</Shown>\
|
||||
<Photo>\n\t\tfile:////Users/me/Art%20Work/logo%23one.png\n\t\t</Photo>\
|
||||
<Chart><data numDataColumns=\"3\"><propertyRow key=\"name\"><value></value><value type=\"string\">North</value><value type=\"string\">South</value></propertyRow>\
|
||||
<values><row><value key=\"name\" type=\"string\">Q1</value><value>10</value><value>2.5</value></row>\
|
||||
<row><value key=\"name\">2024</value><value></value><value>-4</value></row></values></data></Chart>\
|
||||
<Loose></Loose><Odd>ignored</Odd></v:sampleDataSet>\
|
||||
<v:sampleDataSet dataSetName=\"B\"><Shown> FALSE </Shown><Photo>C:\\Art\\logo.png</Photo>\
|
||||
<Chart><data numDataColumns=\"2\"><values><row><value key=\"name\"></value><value>7</value><value>8</value></row></values></data></Chart></v:sampleDataSet>\
|
||||
<v:sampleDataSet dataSetName=\"C\"><Shown/><Photo> </Photo><Chart>\n</Chart></v:sampleDataSet>\
|
||||
</v:sampleDataSets></variableSet></variableSets></svg>\n"
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// Load Variable Library defines a library's variables of every kind, unbound, with their values:
|
||||
/// a visibility value from `true` or `false` in any case, an image value from a file's absolute
|
||||
/// path or a `file:` URL (escapes decoded, the white space round it left out, the file not read),
|
||||
/// and a graph value from a `data` element, as the CSV Graph Data takes (series from its
|
||||
/// `propertyRow`, a category from each row's `key="name"` value, blanks where a row has no
|
||||
/// number). A variable without a `trait`, or with one VectorCraft doesn't know, is defined of
|
||||
/// unknown kind, without values. An element holding only white space gives no value.
|
||||
#[test]
|
||||
fn a_variable_library_leaves_out_variables_that_are_not_text() {
|
||||
fn a_variable_library_defines_every_kind_with_its_values() {
|
||||
let mut s = session();
|
||||
let xml = library(
|
||||
&[("Shown", "kindB"), ("Name", "textcontent"), ("Photo", "kindC"), ("Other", "kindB")],
|
||||
&[("A", &[("Shown", &["true"]), ("Name", &["Bravo"]), ("Photo", &["a.png"])])],
|
||||
);
|
||||
let r = s.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap();
|
||||
assert_eq!(r["variables"], json!(["Name"]));
|
||||
assert_eq!(r["skipped"], json!([{"name": "Shown", "trait": "kindB"}, {"name": "Photo", "trait": "kindC"}, {"name": "Other", "trait": "kindB"}]));
|
||||
assert_eq!(r["warning"], "variables that aren't text were left out: kindB (2), kindC (1)");
|
||||
let r = s.execute("variable.loadLibrary", &json!({"xml": every_kind_library()})).unwrap();
|
||||
assert_eq!(r["variables"], json!(["Name", "Shown", "Photo", "Chart", "Loose", "Odd"]));
|
||||
let vars = &s.doc().unwrap().doc.variables;
|
||||
assert_eq!(vars.variables.len(), 1);
|
||||
assert_eq!(vars.dataset("A").map(|d| d.values.len()), Some(1));
|
||||
let kinds: Vec<(&str, &str)> = vars.variables.iter().map(|v| (v.name.as_str(), v.kind.label())).collect();
|
||||
assert_eq!(kinds, [("Name", "text"), ("Shown", "visibility"), ("Photo", "image"), ("Chart", "graph"), ("Loose", "unknown"), ("Odd", "unknown")]);
|
||||
assert!(vars.bindings.is_empty());
|
||||
use vectorcraft_doc::DataValue::{Graph, Image, Text, Visible};
|
||||
let a = &vars.dataset("A").unwrap().values;
|
||||
assert_eq!(a.get("Name"), Some(&Text("Bravo".into())));
|
||||
assert_eq!(a.get("Shown"), Some(&Visible(true)));
|
||||
assert_eq!(a.get("Photo"), Some(&Image("/Users/me/Art Work/logo#one.png".into())));
|
||||
assert_eq!(a.get("Chart"), Some(&Graph(",North,South\nQ1,10,2.5\n\"2024\",,-4".into())));
|
||||
assert_eq!((a.get("Loose"), a.get("Odd")), (None, None));
|
||||
let b = &vars.dataset("B").unwrap().values;
|
||||
assert_eq!((b.get("Shown"), b.get("Photo")), (Some(&Visible(false)), Some(&Image("C:\\Art\\logo.png".into()))));
|
||||
assert_eq!(b.get("Chart"), Some(&Graph(",,\n7,8".into())));
|
||||
assert!(vars.dataset("C").unwrap().values.is_empty(), "{:?}", vars.dataset("C"));
|
||||
}
|
||||
|
||||
/// A library's visibility, image and graph variables drive the art they are bound to: a variable
|
||||
/// the document already has with the same name and kind stays bound (#4136), so selecting a
|
||||
/// library's data set shows or hides the object, swaps the linked image's path and replaces the
|
||||
/// graph's data. A variable of the same name and another kind is replaced, and its bindings go.
|
||||
#[test]
|
||||
fn a_variable_library_keeps_bound_variables_of_every_kind() {
|
||||
let mut s = session();
|
||||
let r = rect(&mut s);
|
||||
let graph = s.execute("graph.create", &json!({"type": "column", "x": 10, "y": 10, "width": 120, "height": 80, "csv": ",a\nX,1"})).unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
for (name, kind, id) in [("Shown", "visibility", r.0), ("Chart", "graph", graph), ("Photo", "text", r.0)] {
|
||||
s.execute("variable.define", &json!({"name": name, "kind": kind})).unwrap();
|
||||
if kind != "text" {
|
||||
s.execute("variable.bind", &json!({"variable": name, "ids": [id]})).unwrap();
|
||||
}
|
||||
}
|
||||
let loaded = s.execute("variable.loadLibrary", &json!({"xml": every_kind_library()})).unwrap();
|
||||
assert_eq!(loaded["deleted"], json!(["Photo"]), "Photo is an image variable in the library");
|
||||
let listed = s.execute("variable.list", &json!({})).unwrap();
|
||||
let bindings: Vec<(String, u64)> =
|
||||
listed["variables"].as_array().unwrap().iter().map(|v| (v["name"].as_str().unwrap().to_string(), v["bindings"].as_u64().unwrap())).collect();
|
||||
assert_eq!(bindings.iter().find(|(n, _)| n == "Shown").map(|b| b.1), Some(1));
|
||||
assert_eq!(bindings.iter().find(|(n, _)| n == "Chart").map(|b| b.1), Some(1));
|
||||
s.execute("dataset.select", &json!({"name": "B"})).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert!(!doc.node(r).unwrap().visible, "Shown is false in B");
|
||||
let csv = doc.node(NodeId(graph)).and_then(|n| n.extras().graph.as_ref()).map(|g| g.to_csv());
|
||||
assert_eq!(csv.as_deref(), Some(",,\n7,8\n"), "B's graph data");
|
||||
}
|
||||
|
||||
/// A library that isn't one, or that breaks its grammar or the caps, is refused, and the document
|
||||
@@ -2477,12 +2545,36 @@ fn malformed_variable_libraries_are_refused() {
|
||||
"&big;".repeat(8000),
|
||||
" ".repeat(300_000)
|
||||
);
|
||||
// A library of one variable `Shown` of the trait given, and a data set holding `value`.
|
||||
let kind_value = |t: &str, value: &str| {
|
||||
format!(
|
||||
"<variableSets><variableSet><variables><variable varName=\"Shown\" trait=\"{t}\"/></variables>\
|
||||
<sampleDataSets><sampleDataSet dataSetName=\"A\">{value}</sampleDataSet></sampleDataSets></variableSet></variableSets>"
|
||||
)
|
||||
};
|
||||
// A library graph value of more rows or series than a graph holds.
|
||||
let rows_past = format!("<Shown><data><values>{}</values></data></Shown>", "<row><value>1</value></row>".repeat(10_001));
|
||||
let series_past =
|
||||
format!("<Shown><data><values><row><value key=\"name\">Q</value>{}</row></values></data></Shown>", "<value>1</value>".repeat(257));
|
||||
// 2,000 rows of 20 values of eight digits are more CSV than a graph value holds.
|
||||
let row = format!("<row>{}</row>", "<value>12345678</value>".repeat(20));
|
||||
let long_graph = format!("<Shown><data><values>{}</values></data></Shown>", row.repeat(2_000));
|
||||
let cases = [
|
||||
("not well-formed XML", "<variableSets><variableSet>".to_string()),
|
||||
("no `variableSets` element", "<svg><variables/></svg>".to_string()),
|
||||
("declares no variables", "<variableSets><variableSet><variables/></variableSet></variableSets>".to_string()),
|
||||
("is declared twice", library(&[("Name", "textcontent"), ("Name", "textcontent")], &[])),
|
||||
("has no `trait`", ok.replace(" trait=\"textcontent\"", "")),
|
||||
("for `Shown` that isn't `true` or `false`", kind_value("visibility", "<Shown>maybe</Shown>")),
|
||||
("for `Shown` that isn't `true` or `false`", kind_value("visibility", "<Shown><p>true</p></Shown>")),
|
||||
("for `Shown` that isn't a file's absolute path or `file:` URL", kind_value("fileref", "<Shown>logo.png</Shown>")),
|
||||
("for `Shown` that isn't a file's absolute path or `file:` URL", kind_value("fileref", "<Shown>C:logo.png</Shown>")),
|
||||
("for `Shown` that isn't a file's absolute path or `file:` URL", kind_value("fileref", "<Shown>file:logo.png</Shown>")),
|
||||
("for `Shown` that isn't a graph's `data` element", kind_value("graphdata", "<Shown>1,2</Shown>")),
|
||||
("for `Shown` that isn't a graph's `data` element", kind_value("graphdata", "<Shown><values/></Shown>")),
|
||||
("for `Shown` that isn't a graph's `data` element", kind_value("graphdata", "<Shown><data/><data/></Shown>")),
|
||||
("graph value for `Shown` longer than 262144 bytes", kind_value("graphdata", &long_graph)),
|
||||
("graph value for `Shown` with more than 10000 rows or 256 series", kind_value("graphdata", &rows_past)),
|
||||
("graph value for `Shown` with more than 10000 rows or 256 series", kind_value("graphdata", &series_past)),
|
||||
("missing `varName`", ok.replace("varName=\"Name\"", "varName=\" \"")),
|
||||
("missing `dataSetName`", ok.replace(" dataSetName=\"A\"", "")),
|
||||
("data set `A` is declared twice", library(&[("Name", "textcontent")], &[("A", &[]), ("A", &[])])),
|
||||
@@ -2531,51 +2623,50 @@ fn a_variable_library_expands_entities_of_plain_text() {
|
||||
assert_eq!(value, Some(vectorcraft_doc::DataValue::Text("x-y \"z\"-x&a;".into())));
|
||||
}
|
||||
|
||||
/// Save Variable Library writes what Load Variable Library reads back: the text variables in their
|
||||
/// order, every data set by name and in order, and each text value as it was, with several lines,
|
||||
/// markup characters, quotes, a carriage return and an empty value. Variables of other kinds are
|
||||
/// left out with their values, named in `skipped` and in the warning. The library is written while
|
||||
/// the variables are locked too, to a file with `path`.
|
||||
/// Save Variable Library writes what Load Variable Library reads back: the variables of every kind
|
||||
/// in their order, every data set by name and in order, and each value as it was: text with several
|
||||
/// lines, markup characters, quotes, a carriage return and an empty value; visibility values;
|
||||
/// image paths with spaces, markup characters, `%`, `#` and letters past ASCII, from a Unix root,
|
||||
/// a drive and a share; and graph data with series, categories, a numeric category and blanks. A
|
||||
/// variable of unknown kind is declared without a `trait` and loads back as one. The library is
|
||||
/// written while the variables are locked too, to a file with `path`.
|
||||
#[test]
|
||||
fn a_saved_variable_library_loads_back_the_text_variables_and_data_sets() {
|
||||
fn a_saved_variable_library_loads_back_every_variable_and_data_set() {
|
||||
let mut s = session();
|
||||
let t = text(&mut s, "Alice");
|
||||
for (name, kind) in [("Name", "text"), ("Shown", "visibility"), ("Note", "text"), ("Photo", "image"), ("Badge", "visibility")] {
|
||||
for (name, kind) in [("Name", "text"), ("Shown", "visibility"), ("Note", "text"), ("Photo", "image"), ("Chart", "graph"), ("Badge", "visibility")]
|
||||
{
|
||||
s.execute("variable.define", &json!({"name": name, "kind": kind})).unwrap();
|
||||
}
|
||||
s.execute("variable.bind", &json!({"variable": "Name", "ids": [t.0]})).unwrap();
|
||||
s.execute("dataset.new", &json!({"name": "First", "values": {"Name": "Bravo", "Note": "One\nTwo & <three>\r\n'four' \"five\"", "Shown": true}}))
|
||||
.unwrap();
|
||||
s.execute("dataset.new", &json!({"name": "Say \"hi\" & <go>\tnow", "values": {"Name": "", "Photo": "a.png"}})).unwrap();
|
||||
let chart = ",North,\"S, \"\"q\"\"\"\nQ1,10,2.5\n\"2024\",,-4";
|
||||
let first = json!({"Name": "Bravo", "Note": "One\nTwo & <three>\r\n'four' \"five\"", "Shown": true, "Photo": "/Users/me/Art & <Work> 100%/#1 ü.png", "Chart": chart});
|
||||
s.execute("dataset.new", &json!({"name": "First", "values": first})).unwrap();
|
||||
let second = json!({"Name": "", "Photo": "C:\\Art\\logo.png", "Badge": false, "Chart": ",,\n7,8"});
|
||||
s.execute("dataset.new", &json!({"name": "Say \"hi\" & <go>\tnow", "values": second})).unwrap();
|
||||
s.execute("dataset.new", &json!({"name": "Share", "values": {"Photo": "\\\\server\\share\\a.png"}})).unwrap();
|
||||
s.execute("dataset.new", &json!({"name": "Empty"})).unwrap();
|
||||
// A file can declare a variable of unknown kind, which no command defines.
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc)
|
||||
.variables
|
||||
.variables
|
||||
.push(vectorcraft_doc::Variable { name: "Loose name".into(), kind: vectorcraft_doc::VariableKind::Unknown });
|
||||
s.execute("variable.lock", &json!({"locked": true})).unwrap();
|
||||
let before = s.doc().unwrap().doc.variables.clone();
|
||||
|
||||
let saved = s.execute("variable.saveLibrary", &json!({})).unwrap();
|
||||
assert_eq!(saved["variables"], json!(["Name", "Note"]));
|
||||
assert_eq!(saved["datasets"], json!(3));
|
||||
assert_eq!(
|
||||
saved["skipped"],
|
||||
json!([{"name": "Shown", "kind": "visibility"}, {"name": "Photo", "kind": "image"}, {"name": "Badge", "kind": "visibility"}])
|
||||
);
|
||||
assert_eq!(saved["warning"], "variables that aren't text were left out: visibility (2), image (1)");
|
||||
assert_eq!(saved["variables"], json!(["Name", "Shown", "Note", "Photo", "Chart", "Badge", "Loose name"]));
|
||||
assert_eq!(saved["datasets"], json!(4));
|
||||
assert_eq!((saved.get("skipped"), saved.get("warning")), (None, None));
|
||||
assert_eq!(s.doc().unwrap().doc.variables, before, "saving changes nothing");
|
||||
|
||||
let mut other = session();
|
||||
let loaded = other.execute("variable.loadLibrary", &json!({"xml": saved["xml"]})).unwrap();
|
||||
assert_eq!((loaded["skipped"].clone(), loaded.get("warning")), (json!([]), None));
|
||||
other.execute("variable.loadLibrary", &json!({"xml": saved["xml"]})).unwrap();
|
||||
let vars = &other.doc().unwrap().doc.variables;
|
||||
assert_eq!(vars.variables.iter().map(|v| (v.name.as_str(), v.kind.label())).collect::<Vec<_>>(), [("Name", "text"), ("Note", "text")]);
|
||||
let text_only: Vec<vectorcraft_doc::DataSet> = before
|
||||
.datasets
|
||||
.iter()
|
||||
.map(|d| {
|
||||
let mut d = d.clone();
|
||||
d.values.retain(|k, _| k == "Name" || k == "Note");
|
||||
d
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(vars.datasets, text_only);
|
||||
assert_eq!(vars.variables, before.variables);
|
||||
assert_eq!(vars.datasets, before.datasets);
|
||||
// Saving the loaded library again writes the same file.
|
||||
assert_eq!(other.execute("variable.saveLibrary", &json!({})).unwrap()["xml"], saved["xml"]);
|
||||
|
||||
let dir = Folder::new("vars-save-library");
|
||||
let path = dir.file("library.xml");
|
||||
@@ -2585,19 +2676,78 @@ fn a_saved_variable_library_loads_back_the_text_variables_and_data_sets() {
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), saved["xml"].as_str().unwrap());
|
||||
let mut from_file = session();
|
||||
from_file.execute("variable.loadLibrary", &json!({"path": path})).unwrap();
|
||||
assert_eq!(from_file.doc().unwrap().doc.variables.datasets, text_only);
|
||||
assert_eq!(from_file.doc().unwrap().doc.variables.datasets, before.datasets);
|
||||
}
|
||||
|
||||
/// Graph data whose categories are all blank keeps them through a save and a load, and so does
|
||||
/// graph data of series names without rows; graph data with neither is refused. An image value
|
||||
/// written as a `file:/…` URL without a host loads as its path, graph data with more series than a
|
||||
/// graph holds is refused, and wide graph data is checked against the size cap as it is written.
|
||||
#[test]
|
||||
fn saved_graph_values_and_file_urls_load_back_at_their_edges() {
|
||||
let mut s = session();
|
||||
s.execute("variable.define", &json!({"name": "Chart", "kind": "graph"})).unwrap();
|
||||
s.execute("dataset.new", &json!({"name": "A", "values": {"Chart": ",S\n\"\",1\n\"\",2"}})).unwrap();
|
||||
let xml = s.execute("variable.saveLibrary", &json!({})).unwrap()["xml"].as_str().unwrap().to_string();
|
||||
assert!(xml.contains("<row><value key=\"name\" type=\"string\"></value><value>1</value></row>"), "{xml}");
|
||||
let mut other = session();
|
||||
other.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap();
|
||||
assert_eq!(other.doc().unwrap().doc.variables.datasets, s.doc().unwrap().doc.variables.datasets);
|
||||
// Series names without rows load back, and graph data with neither is refused.
|
||||
s.execute("dataset.set", &json!({"name": "A", "values": {"Chart": ",North,South"}})).unwrap();
|
||||
let xml = s.execute("variable.saveLibrary", &json!({})).unwrap()["xml"].clone();
|
||||
let mut other = session();
|
||||
other.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap();
|
||||
assert_eq!(other.doc().unwrap().doc.variables.datasets, s.doc().unwrap().doc.variables.datasets);
|
||||
s.execute("dataset.set", &json!({"name": "A", "values": {"Chart": ","}})).unwrap();
|
||||
let e = s.execute("variable.saveLibrary", &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("graph value for `Chart` without rows or series"), "{e}");
|
||||
|
||||
let url = "<variableSets><variableSet><variables><variable varName=\"Photo\" trait=\"fileref\"/></variables><sampleDataSets>\
|
||||
<sampleDataSet dataSetName=\"A\"><Photo>file:/tmp/logo%20one.png</Photo></sampleDataSet>\
|
||||
<sampleDataSet dataSetName=\"B\"><Photo>file:/C:/Art/logo.png</Photo></sampleDataSet></sampleDataSets></variableSet></variableSets>";
|
||||
let mut s = session();
|
||||
s.execute("variable.loadLibrary", &json!({"xml": url})).unwrap();
|
||||
let image = |set: &str| s.doc().unwrap().doc.variables.dataset(set).and_then(|d| d.values.get("Photo")).cloned();
|
||||
assert_eq!(image("A"), Some(vectorcraft_doc::DataValue::Image("/tmp/logo one.png".into())));
|
||||
assert_eq!(image("B"), Some(vectorcraft_doc::DataValue::Image("C:/Art/logo.png".into())));
|
||||
|
||||
// More series than a graph holds are refused.
|
||||
let mut s = session();
|
||||
s.execute("variable.define", &json!({"name": "Chart", "kind": "graph"})).unwrap();
|
||||
let wide = (0..257).map(|i| i.to_string()).collect::<Vec<_>>().join(",");
|
||||
s.execute("dataset.new", &json!({"name": "A", "values": {"Chart": wide}})).unwrap();
|
||||
let e = s.execute("variable.saveLibrary", &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("graph value for `Chart` with more than 10000 rows or 256 series"), "{e}");
|
||||
// One row of 256 values and 1,000 rows of one: every row is written 256 values wide.
|
||||
let mut csv = (0..256).map(|i| i.to_string()).collect::<Vec<_>>().join(",");
|
||||
for i in 0..1_000 {
|
||||
csv += &format!("\n{i}");
|
||||
}
|
||||
s.execute("dataset.set", &json!({"name": "A", "values": {"Chart": csv.clone()}})).unwrap();
|
||||
let xml = s.execute("variable.saveLibrary", &json!({})).unwrap()["xml"].as_str().unwrap().to_string();
|
||||
assert_eq!(xml.matches("<row>").count(), 1_001);
|
||||
assert!(xml.contains("<data numDataColumns=\"256\">"));
|
||||
// Rows that make the library larger than 8 MiB are refused as each is written.
|
||||
for i in 1_000..9_000 {
|
||||
csv += &format!("\n{i}");
|
||||
}
|
||||
s.execute("dataset.set", &json!({"name": "A", "values": {"Chart": csv}})).unwrap();
|
||||
let e = s.execute("variable.saveLibrary", &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("larger than 8388608 bytes"), "{e}");
|
||||
}
|
||||
|
||||
/// The library is the XML of the public grammar: a document type declaration with the namespace
|
||||
/// entities, `variableSets` › `variableSet` › `variables` with a `textcontent` variable per text
|
||||
/// variable, and `sampleDataSets` with a `sampleDataSet` per data set, holding an element per text
|
||||
/// variable it has a value for, with a `p` element per line. Markup characters, a carriage return,
|
||||
/// and a tab or quote in a data set name are escaped. A document with text variables and no data
|
||||
/// sets writes an empty `sampleDataSets`.
|
||||
/// entities, `variableSets` › `variableSet` › `variables` with a variable per variable, its `trait`
|
||||
/// and `category` those of its kind, and `sampleDataSets` with a `sampleDataSet` per data set,
|
||||
/// holding an element per variable it has a value for: a `p` element per line of a text value,
|
||||
/// `true` or `false`, a `file:` URL for an image's path from a Unix root, and a `data` element for
|
||||
/// graph data. Markup characters, a carriage return, and a tab or quote in a data set name are
|
||||
/// escaped. A document with variables and no data sets writes an empty `sampleDataSets`.
|
||||
#[test]
|
||||
fn a_saved_variable_library_has_the_library_layout() {
|
||||
let mut s = session();
|
||||
for (name, kind) in [("Name", "text"), ("Shown", "visibility"), ("Note", "text")] {
|
||||
for (name, kind) in [("Name", "text"), ("Shown", "visibility"), ("Note", "text"), ("Photo", "image"), ("Chart", "graph")] {
|
||||
s.execute("variable.define", &json!({"name": name, "kind": kind})).unwrap();
|
||||
}
|
||||
let head = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n\
|
||||
@@ -2605,13 +2755,17 @@ fn a_saved_variable_library_has_the_library_layout() {
|
||||
\t<!ENTITY ns_vars \"http://ns.adobe.com/Variables/1.0/\">\n\
|
||||
\t<!ENTITY ns_custom \"http://ns.adobe.com/GenericCustomNamespace/1.0/\">\n\
|
||||
\t<!ENTITY ns_flows \"http://ns.adobe.com/Flows/1.0/\">\n\
|
||||
\t<!ENTITY ns_graphs \"http://ns.adobe.com/Graphs/1.0/\">\n\
|
||||
]>\n\
|
||||
<svg>\n\
|
||||
<variableSets xmlns=\"&ns_vars;\">\n\
|
||||
\t<variableSet varSetName=\"binding1\" locked=\"none\">\n\
|
||||
\t\t<variables>\n\
|
||||
\t\t\t<variable varName=\"Name\" trait=\"textcontent\" category=\"&ns_flows;\"></variable>\n\
|
||||
\t\t\t<variable varName=\"Shown\" trait=\"visibility\" category=\"&ns_vars;\"></variable>\n\
|
||||
\t\t\t<variable varName=\"Note\" trait=\"textcontent\" category=\"&ns_flows;\"></variable>\n\
|
||||
\t\t\t<variable varName=\"Photo\" trait=\"fileref\" category=\"&ns_vars;\"></variable>\n\
|
||||
\t\t\t<variable varName=\"Chart\" trait=\"graphdata\" category=\"&ns_graphs;\"></variable>\n\
|
||||
\t\t</variables>\n\
|
||||
\t\t<v:sampleDataSets xmlns:v=\"&ns_vars;\" xmlns=\"&ns_custom;\">\n";
|
||||
let tail = "\t\t</v:sampleDataSets>\n\t</variableSet>\n</variableSets>\n</svg>\n";
|
||||
@@ -2619,7 +2773,8 @@ fn a_saved_variable_library_has_the_library_layout() {
|
||||
assert_eq!(empty["xml"].as_str().unwrap(), format!("{head}{tail}"));
|
||||
assert_eq!(empty["datasets"], json!(0));
|
||||
|
||||
s.execute("dataset.new", &json!({"name": "A &\t\"B\"", "values": {"Name": "x\r\ny < z", "Shown": false}})).unwrap();
|
||||
let values = json!({"Name": "x\r\ny < z", "Shown": false, "Photo": "/art/a b.png", "Chart": ",S\nQ1,1\n2,"});
|
||||
s.execute("dataset.new", &json!({"name": "A &\t\"B\"", "values": values})).unwrap();
|
||||
s.execute("dataset.new", &json!({"name": "C", "values": {"Note": ""}})).unwrap();
|
||||
let xml = s.execute("variable.saveLibrary", &json!({})).unwrap()["xml"].as_str().unwrap().to_string();
|
||||
let sets = "\t\t\t<v:sampleDataSet dataSetName=\"A &	"B"\">\n\
|
||||
@@ -2627,6 +2782,17 @@ fn a_saved_variable_library_has_the_library_layout() {
|
||||
\t\t\t\t\t<p>x </p>\n\
|
||||
\t\t\t\t\t<p>y < z</p>\n\
|
||||
\t\t\t\t</Name>\n\
|
||||
\t\t\t\t<Shown>false</Shown>\n\
|
||||
\t\t\t\t<Photo>file:////art/a%20b.png</Photo>\n\
|
||||
\t\t\t\t<Chart>\n\
|
||||
\t\t\t\t\t<data numDataColumns=\"2\">\n\
|
||||
\t\t\t\t\t\t<propertyRow key=\"name\"><value></value><value type=\"string\">S</value></propertyRow>\n\
|
||||
\t\t\t\t\t\t<values>\n\
|
||||
\t\t\t\t\t\t\t<row><value key=\"name\" type=\"string\">Q1</value><value>1</value></row>\n\
|
||||
\t\t\t\t\t\t\t<row><value key=\"name\">2</value><value></value></row>\n\
|
||||
\t\t\t\t\t\t</values>\n\
|
||||
\t\t\t\t\t</data>\n\
|
||||
\t\t\t\t</Chart>\n\
|
||||
\t\t\t</v:sampleDataSet>\n\
|
||||
\t\t\t<v:sampleDataSet dataSetName=\"C\">\n\
|
||||
\t\t\t\t<Note>\n\
|
||||
@@ -2636,10 +2802,11 @@ fn a_saved_variable_library_has_the_library_layout() {
|
||||
assert_eq!(xml, format!("{head}{sets}{tail}"));
|
||||
}
|
||||
|
||||
/// Save Variable Library refuses a document without variables or without text variables, a text
|
||||
/// variable whose name can't name an element, a data set name or text value with a character XML
|
||||
/// can't hold, a name that Load Variable Library would read differently or refuse, and a library
|
||||
/// past the caps that Load Variable Library reads. A refused save writes no file.
|
||||
/// Save Variable Library refuses a document without variables, a variable whose name can't name an
|
||||
/// element (but for a variable of unknown kind), a data set name, text value or graph label with a
|
||||
/// character XML can't hold, an image value that isn't a file's absolute path, a name that Load
|
||||
/// Variable Library would read differently or refuse, and a library past the caps that Load
|
||||
/// Variable Library reads. A refused save writes no file.
|
||||
#[test]
|
||||
fn save_variable_library_refuses_what_a_library_cant_hold() {
|
||||
let dir = Folder::new("vars-save-refused");
|
||||
@@ -2652,14 +2819,41 @@ fn save_variable_library_refuses_what_a_library_cant_hold() {
|
||||
|
||||
let mut s = session();
|
||||
refused(&mut s, "define a variable first");
|
||||
// A library without text variables is saved.
|
||||
s.execute("variable.define", &json!({"name": "Shown", "kind": "visibility"})).unwrap();
|
||||
refused(&mut s, "holds text variables, and the document has none");
|
||||
assert_eq!(s.execute("variable.saveLibrary", &json!({})).unwrap()["variables"], json!(["Shown"]));
|
||||
|
||||
for name in ["First Name", "1st", "a:b", "x/y", "-dash"] {
|
||||
for (name, kind) in [("First Name", "text"), ("1st", "visibility"), ("a:b", "image"), ("x/y", "graph"), ("-dash", "text")] {
|
||||
let mut s = session();
|
||||
s.execute("variable.define", &json!({"name": name, "kind": "text"})).unwrap();
|
||||
s.execute("variable.define", &json!({"name": name, "kind": kind})).unwrap();
|
||||
refused(&mut s, &format!("variable `{name}` can't be saved in a variable library"));
|
||||
}
|
||||
// No element is named after a variable of unknown kind, so its name can be any name.
|
||||
let mut s = session();
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc)
|
||||
.variables
|
||||
.variables
|
||||
.push(vectorcraft_doc::Variable { name: "First \"Name\" & <x>".into(), kind: vectorcraft_doc::VariableKind::Unknown });
|
||||
let xml = s.execute("variable.saveLibrary", &json!({})).unwrap()["xml"].clone();
|
||||
let mut other = session();
|
||||
other.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap();
|
||||
assert_eq!(other.doc().unwrap().doc.variables.variables, s.doc().unwrap().doc.variables.variables);
|
||||
|
||||
// An image value that isn't a file's absolute path, which Load Variable Library refuses.
|
||||
for path in ["a.png", "C:a.png", "C:\\a.png ", "/"] {
|
||||
let mut s = session();
|
||||
s.execute("variable.define", &json!({"name": "Photo", "kind": "image"})).unwrap();
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).variables.datasets.push(vectorcraft_doc::DataSet {
|
||||
name: "A".into(),
|
||||
values: [("Photo".to_string(), vectorcraft_doc::DataValue::Image(path.into()))].into(),
|
||||
});
|
||||
refused(&mut s, "data set `A` holds an image value for `Photo` that isn't a file's absolute path");
|
||||
}
|
||||
// A graph label with a character XML can't hold.
|
||||
let mut s = session();
|
||||
s.execute("variable.define", &json!({"name": "Chart", "kind": "graph"})).unwrap();
|
||||
s.execute("dataset.new", &json!({"name": "A", "values": {"Chart": ",S\u{1}\nQ1,1"}})).unwrap();
|
||||
refused(&mut s, "data set `A` holds a control character");
|
||||
for name in ["Ünïcode", "_x", "a.b-c_d", "名前"] {
|
||||
let mut s = session();
|
||||
s.execute("variable.define", &json!({"name": name, "kind": "text"})).unwrap();
|
||||
@@ -2757,10 +2951,10 @@ fn a_saved_variable_library_near_the_size_cap_loads_back() {
|
||||
|
||||
/// While the variables are locked, a library that would delete or define a variable is refused, as
|
||||
/// Delete Variable and New Variable are, and the document keeps its variables and data sets. That
|
||||
/// covers a library without text variables loaded into a document with variables, and one that
|
||||
/// adds a text variable to the document's. A library of the document's own text variables, and
|
||||
/// one without text variables loaded into a document without variables, delete and define none:
|
||||
/// they load, replacing the data sets.
|
||||
/// covers a library of other variables loaded into a document with variables, one that adds a
|
||||
/// variable to the document's, one that declares a document variable's name with another kind, and
|
||||
/// any library loaded into a document without variables. A library of the document's own variables
|
||||
/// with their kinds deletes and defines none: it loads, replacing the data sets.
|
||||
#[test]
|
||||
fn locked_variables_refuse_a_library_that_deletes_or_defines_variables() {
|
||||
let mut s = session();
|
||||
@@ -2768,7 +2962,7 @@ fn locked_variables_refuse_a_library_that_deletes_or_defines_variables() {
|
||||
s.execute("dataset.new", &json!({"name": "A", "values": {"Name": "Old"}})).unwrap();
|
||||
s.execute("variable.lock", &json!({"locked": true})).unwrap();
|
||||
let before = s.doc().unwrap().doc.variables.clone();
|
||||
for vars in [&[("Shown", "other")][..], &[("Name", "textcontent"), ("Note", "textcontent")][..]] {
|
||||
for vars in [&[("Shown", "other")][..], &[("Name", "textcontent"), ("Note", "textcontent")][..], &[("Name", "visibility")][..]] {
|
||||
let e = s.execute("variable.loadLibrary", &json!({"xml": library(vars, &[("B", &[])])})).unwrap_err();
|
||||
assert!(matches!(&e, EngineError::Disabled(cmd, why) if cmd == "variable.loadLibrary" && why == "variables are locked"), "{e}");
|
||||
assert_eq!(s.doc().unwrap().doc.variables, before);
|
||||
@@ -2780,13 +2974,13 @@ fn locked_variables_refuse_a_library_that_deletes_or_defines_variables() {
|
||||
let mut s = session();
|
||||
s.execute("dataset.new", &json!({"name": "A"})).unwrap();
|
||||
s.execute("variable.lock", &json!({"locked": true})).unwrap();
|
||||
let e = s.execute("variable.loadLibrary", &json!({"xml": library(&[("Name", "textcontent")], &[])})).unwrap_err();
|
||||
assert!(matches!(&e, EngineError::Disabled(_, why) if why == "variables are locked"), "{e}");
|
||||
let r = s.execute("variable.loadLibrary", &json!({"xml": library(&[("Shown", "other")], &[("B", &[])])})).unwrap();
|
||||
assert_eq!((r["deletedDataSets"].clone(), r["names"].clone()), (json!(["A"]), json!(["B"])));
|
||||
for vars in [&[("Name", "textcontent")][..], &[("Shown", "other")][..]] {
|
||||
let e = s.execute("variable.loadLibrary", &json!({"xml": library(vars, &[("B", &[])])})).unwrap_err();
|
||||
assert!(matches!(&e, EngineError::Disabled(_, why) if why == "variables are locked"), "{e}");
|
||||
}
|
||||
let vars = &s.doc().unwrap().doc.variables;
|
||||
assert!(vars.variables.is_empty() && vars.locked);
|
||||
assert_eq!(vars.datasets.iter().map(|d| d.name.as_str()).collect::<Vec<_>>(), ["B"]);
|
||||
assert_eq!(vars.datasets.iter().map(|d| d.name.as_str()).collect::<Vec<_>>(), ["A"]);
|
||||
}
|
||||
|
||||
/// A graph variable's data set applies its CSV as `graph.setData` does: a right-axis series the row's data no longer
|
||||
@@ -3109,6 +3303,10 @@ fn an_svg_without_readable_variable_data_opens_its_art() {
|
||||
let head = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"20\" height=\"20\">";
|
||||
let art = "<rect x=\"1\" y=\"1\" width=\"5\" height=\"5\"/></svg>";
|
||||
let untraited = format!("{head}<variableSets><variableSet><variables><variable varName=\"A\"/></variables></variableSet></variableSets>{art}");
|
||||
let relative = format!(
|
||||
"{head}<variableSets><variableSet><variables><variable varName=\"T\" trait=\"textcontent\"/><variable varName=\"A\" trait=\"fileref\"/></variables>\
|
||||
<sampleDataSets><sampleDataSet dataSetName=\"D\"><T><p>kept</p></T><A>a.png</A></sampleDataSet></sampleDataSets></variableSet></variableSets>{art}"
|
||||
);
|
||||
let refs = "&ns_big;".repeat(40_000);
|
||||
let big = "x".repeat(250);
|
||||
let growing = format!(
|
||||
@@ -3164,11 +3362,23 @@ fn an_svg_without_readable_variable_data_opens_its_art() {
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
assert_eq!(o.doc().unwrap().doc.variables.variables.len(), 1);
|
||||
|
||||
for (svg, why) in [(untraited, "variable `A` has no `trait`"), (growing, "entities expand to more than")] {
|
||||
let (o, warnings) = svg_opened(&svg, "broken.svg");
|
||||
assert!(warnings.iter().any(|w| w.as_str().is_some_and(|w| w.contains("variable data wasn't read") && w.contains(why))), "{warnings:?}");
|
||||
let d = &o.doc().unwrap().doc;
|
||||
assert!(d.variables.variables.is_empty());
|
||||
assert_eq!(vectorcraft_testkit::svg_shapes(&vectorcraft_svg::export(d, &Default::default())), 1, "the art opens");
|
||||
}
|
||||
// A variable without a `trait` is of unknown kind: the SVG leaves it out like the other kinds
|
||||
// that aren't text.
|
||||
let (o, warnings) = svg_opened(&untraited, "untraited.svg");
|
||||
assert!(warnings.contains(&json!("variables that aren't text were left out: unknown (1)")), "{warnings:?}");
|
||||
assert!(o.doc().unwrap().doc.variables.variables.is_empty());
|
||||
// The values of the other kinds aren't read, so one that Load Variable Library would refuse
|
||||
// leaves the text variables and their values as they open.
|
||||
let (o, warnings) = svg_opened(&relative, "relative.svg");
|
||||
assert!(warnings.contains(&json!("variables that aren't text were left out: fileref (1)")), "{warnings:?}");
|
||||
let vars = &o.doc().unwrap().doc.variables;
|
||||
assert_eq!(vars.variables.iter().map(|v| v.name.as_str()).collect::<Vec<_>>(), ["T"]);
|
||||
assert_eq!(vars.dataset("D").map(|d| d.values.clone()), Some([("T".to_string(), vectorcraft_doc::DataValue::Text("kept".into()))].into()));
|
||||
|
||||
let (o, warnings) = svg_opened(&growing, "broken.svg");
|
||||
let why = "entities expand to more than";
|
||||
assert!(warnings.iter().any(|w| w.as_str().is_some_and(|w| w.contains("variable data wasn't read") && w.contains(why))), "{warnings:?}");
|
||||
let d = &o.doc().unwrap().doc;
|
||||
assert!(d.variables.variables.is_empty());
|
||||
assert_eq!(vectorcraft_testkit::svg_shapes(&vectorcraft_svg::export(d, &Default::default())), 1, "the art opens");
|
||||
}
|
||||
|
||||
@@ -651,7 +651,7 @@ impl Session {
|
||||
match ev.kind {
|
||||
PointerKind::Down | PointerKind::Drag => self.pointer_held = true,
|
||||
PointerKind::Up | PointerKind::Move => self.pointer_held = false,
|
||||
PointerKind::DoubleClick => {}
|
||||
PointerKind::DoubleClick | PointerKind::TripleClick => {}
|
||||
}
|
||||
match ev.kind {
|
||||
PointerKind::Down => {
|
||||
|
||||
@@ -752,6 +752,10 @@ fn structured_junk() {
|
||||
)}),
|
||||
),
|
||||
("svgFilter.apply", json!({"name": "\u{0}", "ids": [u64::MAX]})),
|
||||
("svgFilter.apply", json!({"name": "Glow", "index": u64::MAX, "item": -1})),
|
||||
("svgFilter.apply", json!({"name": "Rough Edges", "index": [0], "ids": "x"})),
|
||||
("svgFilter.define", json!({"xml": "<filter id=\"x\"/>", "replace": "Glow"})),
|
||||
("svgFilter.delete", json!({"name": "Glow"})),
|
||||
("svgFilter.delete", json!({"name": ["a"]})),
|
||||
(
|
||||
"effect.apply",
|
||||
|
||||
@@ -664,6 +664,29 @@ proptest! {
|
||||
survive(&svg, || vectorcraft_svg::import(&svg).ok())?;
|
||||
}
|
||||
|
||||
/// Style sheets of descendant, child, sibling and `:not()` selectors over nested groups and the
|
||||
/// `<use>` copies of a rectangle inside them, in an SVG and in an SVG image it shows: the import
|
||||
/// measures their matching before its own cascade and the SVG reader run.
|
||||
#[test]
|
||||
fn svg_hostile_selectors_over_copies_never_panic(
|
||||
sheet in r#"([a-z.#:()>+* ]{1,24}\{fill:red\} ?){1,6}"#,
|
||||
depth in 1usize..12,
|
||||
copies in 0usize..4,
|
||||
) {
|
||||
let groups = format!("{}<rect id=\"r\" class=\"a\" width=\"1\" height=\"1\"/>{}", "<g class=\"a\">".repeat(depth), "</g>".repeat(depth));
|
||||
let inner = format!(
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"4\" height=\"4\"><style>{sheet}</style>{groups}{}</svg>",
|
||||
"<use href=\"#r\"/>".repeat(copies)
|
||||
);
|
||||
let image = format!(
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"4\" height=\"4\"><image href=\"data:image/svg+xml;base64,{}\" width=\"4\" height=\"4\"/></svg>",
|
||||
vectorcraft_svg::base64_encode(inner.as_bytes())
|
||||
);
|
||||
for svg in [inner, image] {
|
||||
survive(&svg, || vectorcraft_svg::import(&svg).ok())?;
|
||||
}
|
||||
}
|
||||
|
||||
/// Clip paths made of text, of `<use>` elements showing text, and of both with shapes, each with
|
||||
/// hostile attributes, clipping art that may clip by them in turn.
|
||||
#[test]
|
||||
@@ -1831,6 +1854,80 @@ proptest! {
|
||||
}
|
||||
}
|
||||
|
||||
/// A 4 × 2 pixel RGB PSD file whose clipping path resource (2999) names its saved path "P"
|
||||
/// (resource 2000): a closed subpath of a linked and two unlinked knots, an open subpath, and the
|
||||
/// initial fill record saying the fill starts with all pixels.
|
||||
fn clipped_psd() -> Vec<u8> {
|
||||
let record = |selector: u16, body: &[i32]| {
|
||||
let mut r = selector.to_be_bytes().to_vec();
|
||||
r.extend(body.iter().flat_map(|v| v.to_be_bytes()));
|
||||
r.resize(26, 0);
|
||||
r
|
||||
};
|
||||
let one = 1 << 24;
|
||||
let mut path = record(6, &[]);
|
||||
path.extend(record(8, &[1 << 16]));
|
||||
path.extend(record(0, &[3 << 16]));
|
||||
path.extend(record(1, &[0, 0, 0, one / 2, 0, one]));
|
||||
path.extend(record(2, &[one, one, one, one, one, one]));
|
||||
path.extend(record(2, &[one, 0, one, 0, one, 0]));
|
||||
path.extend(record(3, &[2 << 16]));
|
||||
path.extend(record(5, &[-one, -one, 0, 0, 2 * one, 2 * one]));
|
||||
path.extend(record(4, &[one / 4, one / 4, one / 4, one / 4, one / 4, one / 4]));
|
||||
let mut res = b"8BIM\x07\xd0\x01P".to_vec();
|
||||
res.extend((path.len() as u32).to_be_bytes());
|
||||
res.extend(path);
|
||||
res.extend(b"8BIM\x0b\xb7\0\0");
|
||||
res.extend(8u32.to_be_bytes());
|
||||
res.extend([1, b'P', 0, 0, 0, 0, 0, 0]);
|
||||
let mut f = b"8BPS\0\x01\0\0\0\0\0\0\0\x03\0\0\0\x02\0\0\0\x04\0\x08\0\x03".to_vec();
|
||||
f.extend([0; 4]);
|
||||
f.extend((res.len() as u32).to_be_bytes());
|
||||
f.extend(res);
|
||||
f.extend([0; 4]);
|
||||
f.extend([0, 0]);
|
||||
f.extend((0..24u8).map(|v| v * 10));
|
||||
f
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_clipped_psd_sample_places_in_a_clip_group() {
|
||||
let path = vectorcraft_engine::cmd::fileio::psdread::clipping_path(&clipped_psd()).unwrap();
|
||||
assert_eq!(path.subpaths.iter().map(|s| (s.anchors.len(), s.closed)).collect::<Vec<_>>(), [(4, true), (3, true), (2, false)]);
|
||||
let mut s = vectorcraft_engine::Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let r = s.execute("file.place", &json!({"name": "c.psd", "dataBase64": vectorcraft_format::base64_encode(&clipped_psd())})).unwrap();
|
||||
assert!(r["image"].is_u64(), "{r}");
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(config())]
|
||||
|
||||
/// Mutated copies of a PSD file with a clipping path (its resources: the path records, their
|
||||
/// selectors, counts and points, and the names) never crash reading the path, placing the file
|
||||
/// or opening its merged image.
|
||||
#[test]
|
||||
fn mutated_psd_clipping_paths_never_panic(cut in 0usize..1000, edits in prop::collection::vec((0usize..300, any::<u8>()), 0..12)) {
|
||||
let mut bytes = clipped_psd();
|
||||
let len = bytes.len();
|
||||
for (at, b) in edits {
|
||||
if let Some(x) = bytes.get_mut(at % len) {
|
||||
*x = b;
|
||||
}
|
||||
}
|
||||
bytes.truncate((cut % (len + 1)).max(8));
|
||||
let r = catch_quiet(|| {
|
||||
let _ = vectorcraft_engine::cmd::fileio::psdread::clipping_path(&bytes);
|
||||
let mut s = vectorcraft_engine::Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let p = json!({"name": "c.psd", "dataBase64": vectorcraft_format::base64_encode(&bytes), "thumbnail": 8});
|
||||
let _ = no_panic(s.execute("file.place", &p));
|
||||
let _ = no_panic(s.execute("document.open", &json!({"name": "c.psd", "dataBase64": vectorcraft_format::base64_encode(&bytes), "layers": false})));
|
||||
});
|
||||
prop_assert!(r.is_ok(), "panicked: {:?}", r.err());
|
||||
}
|
||||
}
|
||||
|
||||
/// 1-bit TIFFs compressed with CCITT Group 3: modified Huffman (Compression 2) in three strips, T.4
|
||||
/// (Compression 3) with two-dimensional rows, fill bits, six EOLs at the end and each byte's lowest
|
||||
/// bit first, and T.4 two-dimensional rows in 16 × 16 tiles.
|
||||
|
||||
@@ -143,6 +143,10 @@
|
||||
//! A path or compound path with a brush the reader reads live is written with an art style whose
|
||||
//! stroke is the brush's filter (`writer::brushes`). A brush is written only when the reader reads
|
||||
//! it back with its settings.
|
||||
//! - Graphs, as the reader reads them (`read/graph.rs`): a graph on the layers whose records the
|
||||
//! reader reads back as the same graph ([`crate::ai_graph`]) is written as its group between
|
||||
//! `%_Gs`, its functional records and `%_GS`, each series' group tagged `Go` right after its end;
|
||||
//! any other graph, and a graph with art left out, as its art, with a warning.
|
||||
//!
|
||||
//! Lines end in CR LF. Strings are written in UTF-8. Art space is ruler space: y up, its origin at
|
||||
//! the first artboard's top-left corner. On the canvas ([`CANVAS_SIZE`] points square, y down) the
|
||||
|
||||
@@ -4191,6 +4191,57 @@ fn standard_vertical_roman_alignment_comes_back() {
|
||||
assert_eq!(flags(&texts(&read_back(&both))[0])[2], (false, true));
|
||||
}
|
||||
|
||||
/// Insert Aki Left and Right come back on each run, in vertical and horizontal type: a run with
|
||||
/// either writes it as key 49 or 50 in 1/1000 em, a run without writes neither, and nothing is
|
||||
/// reported. Each object lays out as it did. A run that also has an attribute the text document
|
||||
/// leaves out is still reported.
|
||||
#[test]
|
||||
fn insert_aki_comes_back() {
|
||||
use vectorcraft_doc::{CharStyle, TextObject, TextRun};
|
||||
let plain = style(14.0, Color::BLACK);
|
||||
let left = CharStyle { aki_left: 250.0, ..plain.clone() };
|
||||
let both = CharStyle { aki_left: 125.5, aki_right: 500.0, ..plain.clone() };
|
||||
let mut doc = Document::new(200.0, 200.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let mut down = TextObject::point(vectorcraft_geom::Point::new(150.0, 20.0), "", plain.clone());
|
||||
down.runs = vec![TextRun::new("AB", left.clone()), TextRun::new("CD", plain.clone()), TextRun::new("EF", both.clone())];
|
||||
down.vertical = true;
|
||||
let mut across = TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), "", plain.clone());
|
||||
across.runs = vec![TextRun::new("GH", both.clone()), TextRun::new("IJ", plain.clone())];
|
||||
for t in [down, across] {
|
||||
let n = text_node(&mut doc, t);
|
||||
doc.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
}
|
||||
let out = export_ai_editing(&doc, &opts()).unwrap();
|
||||
assert!(out.warnings.is_empty(), "{:?}", out.warnings);
|
||||
let back = read_back(&doc);
|
||||
same_lines(&type_lines(&back), &type_lines(&doc));
|
||||
let texts = |d: &Document| -> Vec<TextObject> {
|
||||
d.layers[0].children().unwrap().iter().filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some((**t).clone()) } else { None }).collect()
|
||||
};
|
||||
let aki = |t: &TextObject| t.runs.iter().map(|r| (r.style.aki_left, r.style.aki_right)).collect::<Vec<_>>();
|
||||
let (written, read) = (texts(&doc), texts(&back));
|
||||
assert_eq!(read.iter().map(aki).collect::<Vec<_>>(), [vec![(250.0, 0.0), (0.0, 0.0), (125.5, 500.0)], vec![(125.5, 500.0), (0.0, 0.0)]]);
|
||||
let origins = |t: &TextObject| {
|
||||
vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).glyphs.iter().map(|g| (r3(g.origin.x), r3(g.origin.y))).collect::<Vec<_>>()
|
||||
};
|
||||
for (w, r) in written.iter().zip(&read) {
|
||||
assert_eq!(origins(r), origins(w), "vertical={}", w.vertical);
|
||||
}
|
||||
let decoded = text_document(&program(&doc));
|
||||
for (key, count) in [("/49 250.0", 1), ("/49 125.5", 2), ("/50 500.0", 2)] {
|
||||
assert_eq!(decoded.matches(key).count(), count, "{key}: {decoded}");
|
||||
}
|
||||
assert_eq!(decoded.matches("/49 ").count() + decoded.matches("/50 ").count(), 5, "{decoded}");
|
||||
// Underline is still left out, and reported.
|
||||
let mut lossy = doc.clone();
|
||||
let id = lossy.layers[0].children().unwrap()[0].id;
|
||||
if let Some(NodeKind::Text(t)) = lossy.node_mut(id).map(|n| &mut n.kind) {
|
||||
t.runs[0].style.underline = true;
|
||||
}
|
||||
assert_eq!(export_ai_editing(&lossy, &opts()).unwrap().warnings, [writer::TYPE_ATTRIBUTES]);
|
||||
}
|
||||
|
||||
/// The text document of program `text` (LF line ends), decoded, with its UTF-16 strings' zero
|
||||
/// bytes left out.
|
||||
fn text_document(text: &str) -> String {
|
||||
@@ -10856,3 +10907,73 @@ fn a_clipping_path_written_as_its_paint_keeps_one_text_wrap() {
|
||||
same_wraps(&wraps(read_back(&doc).layers[0].children().unwrap()), &[(None, 5.0, true)]);
|
||||
}
|
||||
}
|
||||
|
||||
/// A graph whose records read back whole is written with them, each series' group tagged before
|
||||
/// its name, and opens again as the same live graph, also from a PDF-compatible file's first page.
|
||||
#[test]
|
||||
fn graphs_are_written_with_their_records_and_open_live() {
|
||||
use crate::ai_graph::sample;
|
||||
for (what, doc) in sample::kept() {
|
||||
let out = export_ai_editing(&doc, &opts()).unwrap();
|
||||
assert!(!out.warnings.iter().any(|w| w == writer::GRAPHS), "{what}: {:?}", out.warnings);
|
||||
let text = program(&doc);
|
||||
assert_eq!((text.matches("%_Gs\n").count(), text.matches("%_GS\n").count()), (1, 1), "{what}: {text}");
|
||||
assert!(text.contains("U\n%_2 ") && text.contains(" 0 0 Go\n%_/ArtDictionary :\n"), "{what}: the tag comes before the series' name: {text}");
|
||||
let written = sample::graphs(&doc);
|
||||
let graphs = sample::graphs(&read_back(&doc));
|
||||
assert_eq!(graphs.len(), 1, "{what}");
|
||||
assert!(sample::same(&written[0].0, &graphs[0].0), "{what}: {:#?}\n{:#?}", written[0].0, graphs[0].0);
|
||||
assert_eq!(graphs[0].1, written[0].1, "{what}: the members and their series");
|
||||
}
|
||||
let doc = sample::document(sample::spec(vectorcraft_doc::GraphKind::Column));
|
||||
let (p, _) = private_data(&doc, &opts()).unwrap();
|
||||
let pdf =
|
||||
vectorcraft_pdf::export(&doc, &vectorcraft_pdf::PdfOptions { private_data: Some(p), ..vectorcraft_pdf::PdfOptions::uncompressed() }).unwrap();
|
||||
let (read, _) = crate::ai_alone(&vectorcraft_pdf::illustrator_data(&pdf, None).unwrap()).unwrap();
|
||||
let graphs = sample::graphs(&read);
|
||||
assert_eq!(graphs.len(), 1);
|
||||
assert!(sample::same(&sample::graphs(&doc)[0].0, &graphs[0].0));
|
||||
}
|
||||
|
||||
/// A graph whose records wouldn't read back as it is is written as its art, without records, with
|
||||
/// the warning.
|
||||
#[test]
|
||||
fn graphs_the_records_cant_keep_are_written_as_their_art() {
|
||||
use crate::ai_graph::sample;
|
||||
for (what, doc) in sample::unkept() {
|
||||
let out = export_ai_editing(&doc, &opts()).unwrap();
|
||||
assert!(out.warnings.iter().any(|w| w == writer::GRAPHS), "{what}: {:?}", out.warnings);
|
||||
let text = program(&doc);
|
||||
assert!(!text.contains("%_Gs") && !text.contains(" Go\n") && !text.contains("%_GS"), "{what}: {text}");
|
||||
let read = read_back(&doc);
|
||||
assert!(sample::graphs(&read).is_empty(), "{what}");
|
||||
let paths = |d: &Document| {
|
||||
let mut count = 0;
|
||||
d.walk(|n| count += usize::from(matches!(n.kind, NodeKind::Path { .. })));
|
||||
count
|
||||
};
|
||||
assert_eq!(paths(&read), paths(&doc), "{what}: the graph's art is kept");
|
||||
}
|
||||
}
|
||||
|
||||
/// A graph with art left out for the object limit is written as the art there is room for, without
|
||||
/// records or tags, with the warning; with room for all of it, it is written with its records.
|
||||
#[test]
|
||||
fn a_graph_with_art_left_out_is_written_without_records() {
|
||||
use crate::ai_graph::sample;
|
||||
let doc = sample::document(sample::spec(vectorcraft_doc::GraphKind::Column));
|
||||
let all = export_ai_editing(&doc, &opts()).unwrap();
|
||||
let read = crate::import::objects_read(&all.program).unwrap();
|
||||
let room = export_within(&doc, &opts(), read).unwrap();
|
||||
assert_eq!(room.program, all.program);
|
||||
for max in [0, 1, read / 2, read - 1] {
|
||||
let out = export_within(&doc, &opts(), max).unwrap();
|
||||
let text = String::from_utf8_lossy(&out.program).replace("\r\n", "\n");
|
||||
assert!(
|
||||
out.warnings.iter().any(|w| w == writer::OBJECT_LIMIT) && out.warnings.iter().any(|w| w == writer::GRAPHS),
|
||||
"{max}: {:?}",
|
||||
out.warnings
|
||||
);
|
||||
assert!(!text.contains("%_Gs") && !text.contains(" Go\n") && !text.contains("%_GS"), "{max}: {text}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -295,6 +295,13 @@ pub(super) struct Writer<'a> {
|
||||
shown: Vec<vectorcraft_geom::BezPath>,
|
||||
/// The copy of an image that the last [`Self::image`] wrote as a window, when it did.
|
||||
windowed: Option<images::Windowed>,
|
||||
/// Writing a graph's art with its records ([`Self::graph_records`]): a graph inside it is written
|
||||
/// as its art.
|
||||
in_graph: bool,
|
||||
/// The `Go` line the next object, a graph's series group, is followed by.
|
||||
series_tag: Option<String>,
|
||||
/// Where the `Go` lines of the graph being written start in [`Self::body`].
|
||||
graph_tags: Vec<usize>,
|
||||
}
|
||||
|
||||
impl<'a> Writer<'a> {
|
||||
@@ -367,6 +374,9 @@ impl<'a> Writer<'a> {
|
||||
whole_images: HashMap::new(),
|
||||
shown: vec![],
|
||||
windowed: None,
|
||||
in_graph: false,
|
||||
series_tag: None,
|
||||
graph_tags: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -642,6 +652,7 @@ impl<'a> Writer<'a> {
|
||||
|
||||
/// One object: its state before it, its transparency, and its name and opacity mask after it.
|
||||
fn node(&mut self, n: &Node) {
|
||||
let tag = self.series_tag.take();
|
||||
if let NodeKind::Layer { .. } = n.kind {
|
||||
return self.write_layer(n, &[]);
|
||||
}
|
||||
@@ -652,7 +663,8 @@ impl<'a> Writer<'a> {
|
||||
if self.in_symbol {
|
||||
self.wrote_fixed |= symbols::redrawn(n);
|
||||
}
|
||||
if n.extras().graph.is_some() && !self.in_look {
|
||||
let graph = if n.extras().graph.is_some() && !self.in_look { self.graph_records(n) } else { None };
|
||||
if n.extras().graph.is_some() && !self.in_look && graph.is_none() {
|
||||
self.warn(GRAPHS);
|
||||
}
|
||||
// On the layers or in an opacity mask's art, outside art cut to a clipping object: with its
|
||||
@@ -680,14 +692,18 @@ impl<'a> Writer<'a> {
|
||||
let start = self.body.len();
|
||||
// An image's copy written as the part that its opacity mask, among other regions, shows.
|
||||
let mut mask_window = None;
|
||||
let charged = self.charges();
|
||||
match &n.kind {
|
||||
NodeKind::Layer { .. } => {}
|
||||
NodeKind::Group { children, clip: true } => self.clip_group(children, xy),
|
||||
NodeKind::Group { children, clip: false } => {
|
||||
if self.open_group("u") {
|
||||
self.in_graph |= graph.is_some();
|
||||
for c in children {
|
||||
self.series_tag = graph.as_ref().and_then(|g| g.tags.get(&c.id).cloned());
|
||||
self.node(c);
|
||||
}
|
||||
self.in_graph &= graph.is_none();
|
||||
self.end_group("U", xy);
|
||||
}
|
||||
}
|
||||
@@ -790,6 +806,11 @@ impl<'a> Writer<'a> {
|
||||
// A group's dictionary goes between its end and its state block.
|
||||
let block = (self.block_end == self.body.len() && self.block_start >= start).then(|| self.body.split_off(self.block_start));
|
||||
self.block_end = usize::MAX;
|
||||
// A graph's series group is tagged right after its end, before its dictionary.
|
||||
if let Some(t) = tag {
|
||||
self.graph_tags.push(self.body.len());
|
||||
self.line(&t);
|
||||
}
|
||||
let mask_written = self.dictionary(n);
|
||||
if let Some(b) = block {
|
||||
self.body.push_str(&b);
|
||||
@@ -803,6 +824,41 @@ impl<'a> Writer<'a> {
|
||||
if deform {
|
||||
self.line(&envelopes::plugin_line());
|
||||
}
|
||||
if let Some(g) = graph {
|
||||
self.graph_end(g, start, charged);
|
||||
}
|
||||
}
|
||||
|
||||
/// The records of graph `n` ([`crate::ai_graph::records`]) when it is written as a graph: on the
|
||||
/// layers, outside art cut to a clipping object, symbols' art, live objects' art and another
|
||||
/// graph, and without an art style anywhere in it. `None` when it is written as its art.
|
||||
fn graph_records(&self, n: &Node) -> Option<crate::ai_graph::Records> {
|
||||
fn has_style(n: &Node, styled: &HashMap<NodeId, Arc<Node>>) -> bool {
|
||||
styled.contains_key(&n.id) || n.children().is_some_and(|c| c.iter().any(|c| has_style(c, styled)))
|
||||
}
|
||||
let placed = self.hidden == 0 && self.nest == 0 && self.drawn == 0 && self.clip.is_none() && !self.in_symbol && !self.in_graph;
|
||||
if !placed || has_style(n, &self.styled) {
|
||||
return None;
|
||||
}
|
||||
crate::ai_graph::records(n, self.to_art)
|
||||
}
|
||||
|
||||
/// The graph whose art was written from `start` on, charged from `charged`, ends: its records go
|
||||
/// before the art and `%_GS` after it, or, when art in it was left out ([`Self::take_objects`]),
|
||||
/// its `Go` lines are taken out and it stays its art, with a warning.
|
||||
fn graph_end(&mut self, records: crate::ai_graph::Records, start: usize, charged: Charges) {
|
||||
let tags = std::mem::take(&mut self.graph_tags);
|
||||
if self.body.len() > start && !self.left_out_since(charged) {
|
||||
self.body.insert_str(start, &records.head);
|
||||
self.line(crate::ai_graph::END);
|
||||
return;
|
||||
}
|
||||
for at in tags.into_iter().rev() {
|
||||
if let Some(len) = self.body.get(at..).and_then(|rest| rest.find('\n')) {
|
||||
self.body.replace_range(at..=at + len, "");
|
||||
}
|
||||
}
|
||||
self.warn(GRAPHS);
|
||||
}
|
||||
|
||||
/// Live object `n`, of transparency `xy`, as a group of its art, with `warning` when it is given.
|
||||
|
||||
@@ -20,6 +20,7 @@ use std::fmt::Write;
|
||||
|
||||
use kurbo::{ParamCurveArclen, PathSeg};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::text::MAX_AKI;
|
||||
use vectorcraft_doc::{
|
||||
AreaOptions, Burasagari, CharStyle, Document, FirstBaseline, Justify, LineCap, LineJoin, Mojikumi, Node, NodeId, NodeKind, ParaDirection,
|
||||
ParaStyle, PathAlign, PathEffect, TextKind, TextObject, VerticalAlign,
|
||||
@@ -29,7 +30,7 @@ use vectorcraft_geom::{Affine, PathData, Point};
|
||||
use crate::ps;
|
||||
|
||||
/// What the text document holds of type, and what it leaves out.
|
||||
pub(in crate::ai_editing) const TYPE_ATTRIBUTES: &str = "attributes of type other than its font, size, leading, tracking, baseline shift, horizontal and vertical scale, solid fill, solid stroke and its weight, cap, join and miter limit, capitals, small capitals at the document's size, Tate-chu-yoko, Standard Vertical Roman Alignment, paragraph alignment, indents, space before and after, hyphenation on or off and right-to-left direction (for example underline, kerning, OpenType features, swatch links of its colors, character and paragraph styles, tabs, lists, optical margin alignment, area type's inset spacing, vertical alignment and flow, a minimum first baseline with the Ascent first baseline, and type on a path's effect, alignment and spacing and an end bracket at the very end of an open path) are left out of the editing data for other apps";
|
||||
pub(in crate::ai_editing) const TYPE_ATTRIBUTES: &str = "attributes of type other than its font, size, leading, tracking, baseline shift, horizontal and vertical scale, solid fill, solid stroke and its weight, cap, join and miter limit, capitals, small capitals at the document's size, Tate-chu-yoko, Standard Vertical Roman Alignment, Insert Aki, paragraph alignment, indents, space before and after, hyphenation on or off and right-to-left direction (for example underline, kerning, OpenType features, swatch links of its colors, character and paragraph styles, tabs, lists, optical margin alignment, area type's inset spacing, vertical alignment and flow, a minimum first baseline with the Ascent first baseline, and type on a path's effect, alignment and spacing and an end bracket at the very end of an open path) are left out of the editing data for other apps";
|
||||
|
||||
/// The version of the text document's form (`/98 << /0 n >>`), as the newest files users sent have it.
|
||||
const STREAM_VERSION: u32 = 14;
|
||||
@@ -326,6 +327,12 @@ fn end_read_as_none(t: &TextObject) -> bool {
|
||||
!closed(&segs) && end < 1.0 - 1e-9 && place_on(&segs, end) >= segs.len() as f64 - 0.02
|
||||
}
|
||||
|
||||
/// Insert Aki Left or Right `v` as the text document holds it: 0 to [`MAX_AKI`] in 1/1000 em, and 0
|
||||
/// for a value that is not a number.
|
||||
fn held_aki(v: f64) -> f64 {
|
||||
if v.is_nan() { 0.0 } else { v.clamp(0.0, MAX_AKI) }
|
||||
}
|
||||
|
||||
/// Has type `t` attributes the text document leaves out ([`TYPE_ATTRIBUTES`])?
|
||||
pub(in crate::ai_editing) fn loses(t: &TextObject) -> bool {
|
||||
// Small capitals are read back at Document Setup's default size.
|
||||
@@ -360,6 +367,8 @@ pub(in crate::ai_editing) fn loses(t: &TextObject) -> bool {
|
||||
tate_chu_yoko: s.tate_chu_yoko,
|
||||
// Key 35 holds one of the two: a Tate-chu-yoko run is read back without the other.
|
||||
standard_vertical_roman: s.standard_vertical_roman && !s.tate_chu_yoko,
|
||||
aki_left: held_aki(s.aki_left),
|
||||
aki_right: held_aki(s.aki_right),
|
||||
..CharStyle::default()
|
||||
}
|
||||
};
|
||||
@@ -677,6 +686,14 @@ impl TextDoc {
|
||||
};
|
||||
d.push((12, V::Int(caps)));
|
||||
d.push((35, V::Int(baseline_direction(st))));
|
||||
// Insert Aki Left and Right in 1/1000 em, as the reader reads keys 49 and 50. No key is no
|
||||
// space added: neither the stories' character attributes nor `[Normal Character Style]` set one.
|
||||
for (key, v) in [(49, st.aki_left), (50, st.aki_right)] {
|
||||
let v = held_aki(v);
|
||||
if v > 0.0 {
|
||||
d.push((key, real(v)));
|
||||
}
|
||||
}
|
||||
let fill = solid(&st.fill).flatten();
|
||||
// A stroke of no width keeps its paint.
|
||||
let stroke = solid(&st.stroke).flatten();
|
||||
|
||||
@@ -0,0 +1,661 @@
|
||||
//! A live graph's records, which the legacy `.ai` writer ([`crate::legacy_ai`]) and the editing data
|
||||
//! writer ([`crate::ai_editing`]) both write around a graph's group (Adobe Illustrator File Format
|
||||
//! Specification, version 7.0, §17 and appendix A): `%_Gs`, the functional records on `%_` lines
|
||||
//! (`Gb`, `Gy`, `Gd`, three `Ga` … `GA` axes, `Gz`, `Gc` cells and `GC`), the drawn art in one group
|
||||
//! with each series' group followed by `%_2 column 0 0 Go`, then `%_GS`.
|
||||
//!
|
||||
//! A graph is written so only when the `.ai` reader (`import::ai::read::graph`) reads every record
|
||||
//! back as the same graph: one of the four graph types it reads (grouped and stacked column, line,
|
||||
//! area), the settings it keeps, a table it holds, and drawn art it attaches the graph to (each
|
||||
//! series' group a direct member of the graph's, of paths painted with one solid fill and one plain
|
||||
//! line, and the plot's left and bottom edges drawn as stroked lines). Any other graph is written as
|
||||
//! its art, with a warning.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::Write;
|
||||
|
||||
use kurbo::{PathSeg, Point};
|
||||
use vectorcraft_color::{BlendMode, Paint};
|
||||
use vectorcraft_doc::{
|
||||
Appearance, AppearanceItem, GraphKind, GraphSpec, LabelStyles, MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES, Node, NodeId, NodeKind, PiePosition,
|
||||
PieSort, TickLength, ValueAxisSide,
|
||||
};
|
||||
use vectorcraft_effects::stroke;
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
|
||||
use crate::ps;
|
||||
|
||||
/// Most cells of a graph's table, its label row and column included.
|
||||
const MAX_CELLS: usize = 2_600_000;
|
||||
|
||||
/// Longest cell string, in bytes (appendix A, `Gc`).
|
||||
const MAX_CELL_TEXT: usize = 255;
|
||||
|
||||
/// Most characters of the text before or after a value axis' numbers (appendix A, `Ga`, `GA`).
|
||||
const MAX_AFFIX: usize = 9;
|
||||
|
||||
/// Most tick marks per division the reader keeps.
|
||||
const MAX_TICK_MARKS: usize = 20;
|
||||
|
||||
/// Most divisions of a value axis with set values the reader keeps.
|
||||
const MAX_DIVISIONS: usize = 100;
|
||||
|
||||
/// How far an axis line may be from the plot's edge, in points.
|
||||
const EDGE: f64 = 0.01;
|
||||
|
||||
/// Most values one `Gc` takes.
|
||||
const CELLS_PER_RECORD: usize = 15;
|
||||
|
||||
/// A graph's records: what goes before its group (`%_Gs` to `%_GC`), and the `Go` line that follows
|
||||
/// each series' group, by the group's id. `%_GS` follows the group.
|
||||
pub(crate) struct Records {
|
||||
pub(crate) head: String,
|
||||
pub(crate) tags: HashMap<NodeId, String>,
|
||||
}
|
||||
|
||||
/// The line that ends a graph's records, after its group.
|
||||
pub(crate) const END: &str = "%_GS";
|
||||
|
||||
/// The records of graph `n` (a group holding [`vectorcraft_doc::NodeExtras::graph`]), its art written
|
||||
/// through `to_art`; `None` when the reader would not read them back as the same graph.
|
||||
pub(crate) fn records(n: &Node, to_art: Affine) -> Option<Records> {
|
||||
let g = n.extras().graph.as_deref()?;
|
||||
let NodeKind::Group { children, clip: false } = &n.kind else { return None };
|
||||
(n.visible && n.extras().mask.is_none() && all_shown(n)).then_some(())?;
|
||||
let ty = kind_code(g.kind)?;
|
||||
settings_kept(g).then_some(())?;
|
||||
let (left_manual, left_min, left_max, left_step) = axis(g.ticks, g.axis_min, g.axis_max)?;
|
||||
let (right_manual, right_min, right_max, right_step) = axis(g.right_ticks, g.right_axis_min, g.right_axis_max)?;
|
||||
// The table as the graph draws it: `cells` leaves out rows and series past the model's limits.
|
||||
let rows = g.rows.len();
|
||||
let width = g.rows.iter().map(Vec::len).max().unwrap_or(0);
|
||||
((1..=MAX_GRAPH_CATEGORIES).contains(&rows) && (1..=MAX_GRAPH_SERIES).contains(&width)).then_some(())?;
|
||||
let cells = g.cells();
|
||||
cells.iter().flatten().all(|v| v.is_none_or(f64::is_finite)).then_some(())?;
|
||||
cells.iter().flatten().any(Option::is_some).then_some(())?;
|
||||
let first_row = usize::from(!g.series.is_empty());
|
||||
let first_col = usize::from(!g.categories.is_empty());
|
||||
(g.series.is_empty() || g.series.len() == width).then_some(())?;
|
||||
(g.categories.is_empty() || g.categories.len() == rows).then_some(())?;
|
||||
let (total_rows, total_cols) = (rows + first_row, width + first_col);
|
||||
total_rows.checked_mul(total_cols).filter(|c| *c <= MAX_CELLS)?;
|
||||
g.series.iter().chain(&g.categories).all(|l| l.len() <= MAX_CELL_TEXT && !l.chars().any(char::is_control)).then_some(())?;
|
||||
[&g.prefix, &g.suffix, &g.right_prefix, &g.right_suffix]
|
||||
.iter()
|
||||
.all(|a| a.chars().count() <= MAX_AFFIX && !a.chars().any(char::is_control))
|
||||
.then_some(())?;
|
||||
// The plot, and the art the reader attaches the graph to.
|
||||
let r = g.rect;
|
||||
(r.is_finite() && r.width() > 0.0 && r.height() > 0.0).then_some(())?;
|
||||
let plot = to_art.transform_rect_bbox(r);
|
||||
(plot.is_finite() && plot.width() > 0.0 && plot.height() > 0.0).then_some(())?;
|
||||
let tags = series_groups(children, width, first_col, g.kind == GraphKind::Line)?;
|
||||
draws_axes(n, r).then_some(())?;
|
||||
let placed = n.geometric_bounds()?;
|
||||
(r.x0 >= placed.x0 - EDGE && r.y0 >= placed.y0 - EDGE && r.x1 <= placed.x1 + EDGE && r.y1 <= placed.y1 + EDGE).then_some(())?;
|
||||
|
||||
let mut head = String::from("%_Gs\n");
|
||||
let _ = writeln!(head, "%_{} {} {} {} Gb", real(plot.x0), real(plot.y1), real(plot.x1), real(plot.y0));
|
||||
let flag = |b: bool| u8::from(b);
|
||||
let _ = writeln!(
|
||||
head,
|
||||
"%_{ty} {} {} 14 {} {} 0 {} 6 44 Gy",
|
||||
flag(g.drop_shadow),
|
||||
flag(g.first_row_in_front),
|
||||
flag(g.mark_points),
|
||||
flag(g.connect_points),
|
||||
flag(g.legend_across_top)
|
||||
);
|
||||
let _ =
|
||||
writeln!(head, "%_10 2 {} 0 {} {} {} Gd", flag(g.first_column_in_front), real(g.column_width), real(g.cluster_width), flag(g.edge_to_edge));
|
||||
// Tick marks per division: 0 and 1 both mean one, at the labels, and the reader reads 0 as 1.
|
||||
let (category_marks, left_marks, right_marks) = (g.category_tick_marks.max(1), g.tick_marks.max(1), g.right_tick_marks.max(1));
|
||||
let _ = writeln!(head, "%_1 () Ga\n%_0 {} 0 0 0 {category_marks} {} () GA", tick(g.category_tick_length), flag(g.ticks_between_labels));
|
||||
let _ = writeln!(head, "%_2 {} Ga", ps::bytes(g.prefix.as_bytes()));
|
||||
let _ = writeln!(
|
||||
head,
|
||||
"%_{} {} {} {} {} {} 0 {} GA",
|
||||
flag(left_manual),
|
||||
tick(g.tick_length),
|
||||
real(left_min),
|
||||
real(left_max),
|
||||
real(left_step),
|
||||
left_marks,
|
||||
ps::bytes(g.suffix.as_bytes())
|
||||
);
|
||||
let _ = writeln!(head, "%_4 {} Ga", ps::bytes(g.right_prefix.as_bytes()));
|
||||
let _ = writeln!(
|
||||
head,
|
||||
"%_{} {} {} {} {} {} 0 {} GA",
|
||||
flag(right_manual),
|
||||
tick(g.right_tick_length),
|
||||
real(right_min),
|
||||
real(right_max),
|
||||
real(right_step),
|
||||
right_marks,
|
||||
ps::bytes(g.right_suffix.as_bytes())
|
||||
);
|
||||
let _ = writeln!(head, "%_{total_rows} {total_cols} {first_row} {first_col} Gz");
|
||||
let mut table = Table::new(&mut head);
|
||||
if first_row == 1 {
|
||||
if first_col == 1 {
|
||||
table.text("");
|
||||
}
|
||||
for s in &g.series {
|
||||
table.text(s);
|
||||
}
|
||||
}
|
||||
for (i, row) in cells.iter().enumerate() {
|
||||
if let Some(c) = g.categories.get(i) {
|
||||
table.text(c);
|
||||
}
|
||||
for v in row {
|
||||
match v {
|
||||
Some(v) => table.num(*v),
|
||||
None => table.text(""),
|
||||
}
|
||||
}
|
||||
}
|
||||
table.finish();
|
||||
head.push_str("%_GC\n");
|
||||
Some(Records { head, tags })
|
||||
}
|
||||
|
||||
/// The `Gc` records of a table, its cells in rows: at most [`CELLS_PER_RECORD`] values each, one
|
||||
/// string at most.
|
||||
struct Table<'a> {
|
||||
out: &'a mut String,
|
||||
values: usize,
|
||||
string: bool,
|
||||
}
|
||||
|
||||
impl<'a> Table<'a> {
|
||||
fn new(out: &'a mut String) -> Self {
|
||||
Self { out, values: 0, string: false }
|
||||
}
|
||||
|
||||
fn start(&mut self, string: bool) {
|
||||
if self.values == CELLS_PER_RECORD || (string && self.string) {
|
||||
self.finish();
|
||||
}
|
||||
self.out.push_str(if self.values == 0 { "%_" } else { " " });
|
||||
self.values += 1;
|
||||
self.string |= string;
|
||||
}
|
||||
|
||||
fn text(&mut self, t: &str) {
|
||||
self.start(true);
|
||||
self.out.push_str(&ps::bytes(t.as_bytes()));
|
||||
}
|
||||
|
||||
fn num(&mut self, v: f64) {
|
||||
self.start(false);
|
||||
self.out.push_str(&real(v));
|
||||
}
|
||||
|
||||
fn finish(&mut self) {
|
||||
if self.values > 0 {
|
||||
self.out.push_str(" Gc\n");
|
||||
}
|
||||
(self.values, self.string) = (0, false);
|
||||
}
|
||||
}
|
||||
|
||||
/// `v` as a PostScript number that reads back as the same value.
|
||||
fn real(v: f64) -> String {
|
||||
if v == 0.0 {
|
||||
"0".into()
|
||||
} else if (1e-4..1e15).contains(&v.abs()) {
|
||||
format!("{v}")
|
||||
} else {
|
||||
format!("{v:e}")
|
||||
}
|
||||
}
|
||||
|
||||
/// `graphType`: 5 grouped column, 6 stacked column, 7 line, 10 area; the reader reads no other type.
|
||||
fn kind_code(k: GraphKind) -> Option<u8> {
|
||||
match k {
|
||||
GraphKind::Column => Some(5),
|
||||
GraphKind::StackedColumn => Some(6),
|
||||
GraphKind::Line => Some(7),
|
||||
GraphKind::Area => Some(10),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `tickMarkType`: 13 none, 14 short, 15 the length of the plot.
|
||||
fn tick(t: TickLength) -> u8 {
|
||||
match t {
|
||||
TickLength::None => 13,
|
||||
TickLength::Short => 14,
|
||||
TickLength::Full => 15,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `g`'s settings are ones the records give and the reader keeps: a legend beside or across
|
||||
/// the top, every series of the graph's type, one value axis on the left, lines not filled, no graph
|
||||
/// designs, label formatting or pie settings, column and cluster widths of 1% to 1000%, and at most
|
||||
/// [`MAX_TICK_MARKS`] tick marks a division.
|
||||
fn settings_kept(g: &GraphSpec) -> bool {
|
||||
let percent = |p: f64| (1.0..=1000.0).contains(&p);
|
||||
g.legend
|
||||
&& g.series_kinds.iter().all(|k| k.is_none_or(|k| k == g.kind))
|
||||
&& g.value_axis == ValueAxisSide::Left
|
||||
&& !g.separate_scales
|
||||
&& g.right_series.is_empty()
|
||||
&& !g.filled_lines
|
||||
&& g.series_markers.iter().all(Option::is_none)
|
||||
&& g.series_columns.iter().all(Option::is_none)
|
||||
&& g.label_styles == LabelStyles::default()
|
||||
&& !g.pie_legend_in_wedges
|
||||
&& g.pie_position == PiePosition::Even
|
||||
&& g.pie_sort == PieSort::None
|
||||
&& percent(g.column_width)
|
||||
&& percent(g.cluster_width)
|
||||
&& [g.tick_marks, g.right_tick_marks, g.category_tick_marks].iter().all(|m| *m <= MAX_TICK_MARKS)
|
||||
}
|
||||
|
||||
/// A value axis' `useManualValues`, lowest and highest value and `betweenValue`: automatic (no tick
|
||||
/// count and no values), or a whole number of divisions (1 to [`MAX_DIVISIONS`]) between a lowest
|
||||
/// and a higher highest value, which the reader reads back as the same count.
|
||||
fn axis(ticks: usize, min: Option<f64>, max: Option<f64>) -> Option<(bool, f64, f64, f64)> {
|
||||
match (ticks, min, max) {
|
||||
(0, None, None) => Some((false, 0.0, 0.0, 0.0)),
|
||||
(1..=MAX_DIVISIONS, Some(lo), Some(hi)) if lo.is_finite() && hi.is_finite() && hi > lo => {
|
||||
let step = (hi - lo) / ticks as f64;
|
||||
let n = (hi - lo) / step;
|
||||
let exact = step > 0.0 && step.is_finite() && (n - n.round()).abs() <= 1e-6 * n.round().max(1.0) && n.round() == ticks as f64;
|
||||
exact.then_some((true, lo, hi, step))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `n` and everything in it is shown.
|
||||
fn all_shown(n: &Node) -> bool {
|
||||
n.visible && n.children().is_none_or(|c| c.iter().all(|c| all_shown(c)))
|
||||
}
|
||||
|
||||
/// Whether `n` is shown, fully opaque, in Normal mode, not isolated and without an opacity mask or
|
||||
/// effects: the reader keeps a series' paint only from groups and paths drawn so.
|
||||
fn as_drawn(n: &Node) -> bool {
|
||||
n.visible
|
||||
&& n.opacity == 1.0
|
||||
&& n.blend == BlendMode::Normal
|
||||
&& !n.isolate
|
||||
&& n.extras().mask.is_none()
|
||||
&& !n.appearance.effects.iter().any(|e| e.visible)
|
||||
}
|
||||
|
||||
/// The visible fill and line `p` is written with as one path object: a solid fill, and a solid
|
||||
/// plain line with its weight, each opaque, in Normal mode and without effects of its own. `None`
|
||||
/// when it has other paint, more than one of either, or isn't one path of one subpath.
|
||||
#[allow(clippy::type_complexity)]
|
||||
fn plain_paint(p: &Node) -> Option<(Option<Paint>, Option<(Paint, f64)>)> {
|
||||
let NodeKind::Path { path, guide: false, clipping: false, .. } = &p.kind else { return None };
|
||||
(path.subpaths.iter().filter(|sp| !sp.anchors.is_empty()).count() == 1).then_some(())?;
|
||||
let (mut fill, mut line) = (None, None);
|
||||
for item in &p.appearance.items {
|
||||
let drawn = match item {
|
||||
AppearanceItem::Fill(f) => f.visible && !f.paint.is_none(),
|
||||
AppearanceItem::Stroke(s) => s.visible && !s.paint.is_none() && s.width > 0.0 && s.width.is_finite(),
|
||||
};
|
||||
if !drawn {
|
||||
// The writers leave out what draws nothing; the reader reads nothing in its place.
|
||||
continue;
|
||||
}
|
||||
let plain =
|
||||
item.opacity() == 1.0 && item.blend() == BlendMode::Normal && item.effects().is_empty() && matches!(item.paint(), Paint::Solid { .. });
|
||||
plain.then_some(())?;
|
||||
match item {
|
||||
AppearanceItem::Fill(f) if fill.is_none() && line.is_none() => fill = Some(f.paint.clone()),
|
||||
AppearanceItem::Stroke(s) if line.is_none() && stroke::is_plain(s) => line = Some((s.paint.clone(), s.width)),
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
Some((fill, line))
|
||||
}
|
||||
|
||||
/// The `Go` line of each series' group among `children`: a group whose series index is one of the
|
||||
/// `series` the table has, each once, of paths [`as_drawn`] with one fill and one line alike
|
||||
/// ([`plain_paint`]), every path filled unless the graph draws lines (`line`). Its column is the
|
||||
/// table's: after the label column when there is one (`first_col`). `None` when a series has no
|
||||
/// such group.
|
||||
fn series_groups(children: &[std::sync::Arc<Node>], series: usize, first_col: usize, line: bool) -> Option<HashMap<NodeId, String>> {
|
||||
let mut tags = HashMap::new();
|
||||
let mut seen = vec![false; series];
|
||||
for c in children {
|
||||
let Some(s) = c.extras().series_index else { continue };
|
||||
let s = usize::try_from(s).ok().filter(|s| *s < series)?;
|
||||
let slot = seen.get_mut(s)?;
|
||||
(!*slot).then_some(())?;
|
||||
*slot = true;
|
||||
let NodeKind::Group { children: paths, clip: false } = &c.kind else { return None };
|
||||
(as_drawn(c) && *c.appearance == Appearance::default() && !paths.is_empty()).then_some(())?;
|
||||
let mut paints = vec![];
|
||||
for p in paths {
|
||||
as_drawn(p).then_some(())?;
|
||||
paints.push(plain_paint(p)?);
|
||||
}
|
||||
let fill = paints.iter().find_map(|(f, _)| f.clone());
|
||||
paints.iter().all(|(f, _)| f.is_none() || *f == fill).then_some(())?;
|
||||
(line || paints.iter().all(|(f, _)| f.is_some())).then_some(())?;
|
||||
let stroke = paints.first().and_then(|(_, s)| s.clone());
|
||||
paints.iter().all(|(_, s)| *s == stroke).then_some(())?;
|
||||
tags.insert(c.id, format!("%_2 {} 0 0 Go", s + first_col));
|
||||
}
|
||||
seen.iter().all(|s| *s).then_some(tags)
|
||||
}
|
||||
|
||||
/// Whether `art` draws plot `plot`'s left edge and its bottom edge (the document's y runs down) as
|
||||
/// straight lines, each a shown path of one subpath with a plain line ([`plain_paint`]) in a shown
|
||||
/// group, as the reader finds the axes.
|
||||
fn draws_axes(art: &Node, plot: Rect) -> bool {
|
||||
let near = |a: Point, b: Point| (a - b).hypot() <= EDGE;
|
||||
let on = |s: &PathSeg, a: Point, b: Point| match s {
|
||||
PathSeg::Line(l) => (near(l.p0, a) && near(l.p1, b)) || (near(l.p0, b) && near(l.p1, a)),
|
||||
_ => false,
|
||||
};
|
||||
let (top_left, bottom_left, bottom_right) = (Point::new(plot.x0, plot.y0), Point::new(plot.x0, plot.y1), Point::new(plot.x1, plot.y1));
|
||||
let (mut left, mut bottom) = (false, false);
|
||||
let mut stack = vec![art];
|
||||
while let Some(n) = stack.pop() {
|
||||
if !n.visible || n.opacity <= 0.0 || (left && bottom) {
|
||||
continue;
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Group { children, clip: false } => stack.extend(children.iter().map(|c| &**c)),
|
||||
NodeKind::Path { path, .. } if plain_paint(n).is_some_and(|(_, line)| line.is_some()) => {
|
||||
for s in path.to_bezpath().segments() {
|
||||
left |= on(&s, top_left, bottom_left);
|
||||
bottom |= on(&s, bottom_left, bottom_right);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
left && bottom
|
||||
}
|
||||
|
||||
/// Graphs built as the graph tools draw them, for the writers' tests.
|
||||
#[cfg(test)]
|
||||
pub(crate) mod sample {
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Document, GraphKind, GraphSpec, Node, PieSort, TickLength, ValueAxisSide};
|
||||
use vectorcraft_geom::{PathData, Point, Rect, shapes};
|
||||
|
||||
use super::Appearance;
|
||||
|
||||
/// A graph of kind `kind`: series East and West, categories Q1 to Q3, West blank in Q2, on the
|
||||
/// plot 100 100 300 250.
|
||||
pub(crate) fn spec(kind: GraphKind) -> GraphSpec {
|
||||
let mut g = GraphSpec {
|
||||
kind,
|
||||
rect: Rect::new(100.0, 100.0, 300.0, 250.0),
|
||||
series: vec!["East".into(), "West".into()],
|
||||
categories: vec!["Q1".into(), "Q2".into(), "Q3".into()],
|
||||
..GraphSpec::default()
|
||||
};
|
||||
g.set_cells(vec![vec![Some(5.0), Some(3.0)], vec![Some(7.0), None], vec![Some(4.0), Some(6.0)]]);
|
||||
g
|
||||
}
|
||||
|
||||
fn path(doc: &mut Document, p: PathData, fill: Paint, stroke: Paint) -> Arc<Node> {
|
||||
Arc::new(Node::path(doc.alloc_id(), p, Appearance::basic(fill, stroke, 1.0)))
|
||||
}
|
||||
|
||||
/// Graph `g` drawn as a group: a group of each series' marks (a line graph's series as an unfilled
|
||||
/// line, the others' as filled columns), its axes on the plot's left and bottom edges, and a
|
||||
/// legend of a swatch for each series; its series groups named after the series.
|
||||
pub(crate) fn graph(doc: &mut Document, g: GraphSpec) -> Node {
|
||||
let r = g.rect;
|
||||
let cells = g.cells();
|
||||
let width = cells.first().map_or(0, Vec::len);
|
||||
let mut members = vec![];
|
||||
let axes = vec![
|
||||
path(doc, shapes::line(Point::new(r.x0, r.y0), Point::new(r.x0, r.y1)), Paint::None, Paint::solid(Color::BLACK)),
|
||||
path(doc, shapes::line(Point::new(r.x0, r.y1), Point::new(r.x1, r.y1)), Paint::None, Paint::solid(Color::BLACK)),
|
||||
];
|
||||
members.push(Arc::new(Node::group(doc.alloc_id(), axes)));
|
||||
for s in 0..width {
|
||||
let gray = Paint::solid(Color::gray(0.2 + 0.3 * s as f32));
|
||||
let points: Vec<Point> = cells
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(c, row)| {
|
||||
row.get(s).copied().flatten().map(|v| Point::new(r.x0 + 20.0 + 60.0 * c as f64 + 15.0 * s as f64, r.y1 - v * 10.0))
|
||||
})
|
||||
.collect();
|
||||
let marks: Vec<Arc<Node>> = if g.kind == GraphKind::Line {
|
||||
let mut bp = kurbo::BezPath::new();
|
||||
for (i, p) in points.iter().enumerate() {
|
||||
if i == 0 { bp.move_to(*p) } else { bp.line_to(*p) }
|
||||
}
|
||||
vec![path(doc, PathData::from_bezpath(&bp), Paint::None, gray)]
|
||||
} else {
|
||||
points.iter().map(|p| path(doc, shapes::rectangle(Rect::new(p.x, p.y, p.x + 10.0, r.y1)), gray.clone(), Paint::None)).collect()
|
||||
};
|
||||
let mut series = Node::group(doc.alloc_id(), marks);
|
||||
series.name = Some(g.series.get(s).cloned().unwrap_or_else(|| format!("Series {}", s + 1)));
|
||||
series.extras_mut().series_index = Some(s as u32);
|
||||
members.push(Arc::new(series));
|
||||
}
|
||||
let swatches: Vec<Arc<Node>> = (0..width)
|
||||
.map(|s| {
|
||||
let y = r.y0 + 12.0 * s as f64;
|
||||
path(
|
||||
doc,
|
||||
shapes::rectangle(Rect::new(r.x1 + 10.0, y, r.x1 + 18.0, y + 8.0)),
|
||||
Paint::solid(Color::gray(0.2 + 0.3 * s as f32)),
|
||||
Paint::None,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
members.push(Arc::new(Node::group(doc.alloc_id(), swatches)));
|
||||
let mut n = Node::group(doc.alloc_id(), members);
|
||||
n.extras_mut().graph = Some(Box::new(g));
|
||||
n
|
||||
}
|
||||
|
||||
/// A 400 × 300 document holding `g` drawn by [`graph`] on its layer.
|
||||
pub(crate) fn document(g: GraphSpec) -> Document {
|
||||
let mut doc = Document::new(400.0, 300.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let n = graph(&mut doc, g);
|
||||
doc.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
doc
|
||||
}
|
||||
|
||||
/// Graphs whose records read back whole: each type the records give, every setting they keep
|
||||
/// changed, labels with parentheses, backslashes and non-ASCII characters, a label of 255 bytes,
|
||||
/// and a table without labels.
|
||||
pub(crate) fn kept() -> Vec<(&'static str, Document)> {
|
||||
let mut cases = vec![
|
||||
("column", document(spec(GraphKind::Column))),
|
||||
("stacked column", document(spec(GraphKind::StackedColumn))),
|
||||
("line", document(spec(GraphKind::Line))),
|
||||
("area", document(spec(GraphKind::Area))),
|
||||
];
|
||||
let mut g = spec(GraphKind::Column);
|
||||
(g.drop_shadow, g.first_row_in_front, g.first_column_in_front, g.legend_across_top) = (true, true, true, true);
|
||||
(g.mark_points, g.connect_points, g.edge_to_edge) = (false, false, true);
|
||||
(g.column_width, g.cluster_width) = (120.0, 50.0);
|
||||
(g.tick_length, g.tick_marks, g.ticks, g.axis_min, g.axis_max) = (TickLength::Full, 3, 4, Some(0.0), Some(20.0));
|
||||
(g.right_tick_length, g.right_tick_marks, g.right_ticks, g.right_axis_min, g.right_axis_max) = (TickLength::None, 2, 5, Some(1.0), Some(6.0));
|
||||
(g.category_tick_length, g.category_tick_marks, g.ticks_between_labels) = (TickLength::Short, 2, true);
|
||||
(g.prefix, g.suffix, g.right_prefix, g.right_suffix) = ("($".into(), "\\)".into(), "é".into(), " u".into());
|
||||
cases.push(("settings", document(g)));
|
||||
let mut g = spec(GraphKind::Column);
|
||||
g.series = vec!["A (1)".into(), "B\\2".into()];
|
||||
g.categories = vec![String::new(), "naïve".into(), "a".repeat(255)];
|
||||
g.set_cells(vec![vec![Some(1.0 / 3.0), Some(1e-7)], vec![None, Some(2.5)], vec![Some(12.0), None]]);
|
||||
cases.push(("labels", document(g)));
|
||||
let mut g = spec(GraphKind::Column);
|
||||
(g.series, g.categories) = (vec![], vec![]);
|
||||
cases.push(("no labels", document(g)));
|
||||
cases
|
||||
}
|
||||
|
||||
/// Graphs the records can't give as they are, which are written as their art: the five other
|
||||
/// types, settings the reader doesn't keep, a table it can't hold, and art it can't attach the
|
||||
/// graph to.
|
||||
pub(crate) fn unkept() -> Vec<(&'static str, Document)> {
|
||||
let with = |f: &dyn Fn(&mut GraphSpec)| {
|
||||
let mut g = spec(GraphKind::Column);
|
||||
f(&mut g);
|
||||
document(g)
|
||||
};
|
||||
let mut cases: Vec<(&'static str, Document)> = [GraphKind::Bar, GraphKind::StackedBar, GraphKind::Scatter, GraphKind::Pie, GraphKind::Radar]
|
||||
.into_iter()
|
||||
.map(|k| (k.id(), document(spec(k))))
|
||||
.collect();
|
||||
cases.extend([
|
||||
("no legend", with(&|g| g.legend = false)),
|
||||
("filled lines", with(&|g| (g.kind, g.filled_lines) = (GraphKind::Line, true))),
|
||||
("a series of another type", with(&|g| g.series_kinds = vec![None, Some(GraphKind::Line)])),
|
||||
("a marker design", with(&|g| g.series_markers = vec![Some("Star".into())])),
|
||||
("a column design", with(&|g| g.series_columns = vec![Some(Default::default())])),
|
||||
("label formatting", with(&|g| g.label_styles.values = Some(Default::default()))),
|
||||
("a value axis on both sides", with(&|g| g.value_axis = ValueAxisSide::Both)),
|
||||
("a series on the right axis", with(&|g| g.right_series = vec![1])),
|
||||
("pie settings", with(&|g| g.pie_sort = PieSort::All)),
|
||||
("a manual axis without its values", with(&|g| g.ticks = 4)),
|
||||
("values without a tick count", with(&|g| (g.axis_min, g.axis_max) = (Some(0.0), Some(10.0)))),
|
||||
("101 divisions", with(&|g| (g.ticks, g.axis_min, g.axis_max) = (101, Some(0.0), Some(101.0)))),
|
||||
("too many tick marks", with(&|g| g.tick_marks = 21)),
|
||||
("a column width past 1000%", with(&|g| g.column_width = 1001.0)),
|
||||
("a long prefix", with(&|g| g.prefix = "0123456789".into())),
|
||||
("a line break in a label", with(&|g| g.series[0] = "East\nside".into())),
|
||||
("a label of 256 bytes", with(&|g| g.categories[0] = "a".repeat(256))),
|
||||
("a value that isn't finite", with(&|g| g.rows[0][0] = f64::NAN)),
|
||||
("only blank cells", with(&|g| g.set_cells(vec![vec![None, None]; 3]))),
|
||||
("fewer labels than series", with(&|g| g.series.truncate(1))),
|
||||
]);
|
||||
let drawn = |what: &'static str, f: &dyn Fn(&mut Vec<Arc<Node>>)| {
|
||||
let mut doc = Document::new(400.0, 300.0);
|
||||
let mut n = graph(&mut doc, spec(GraphKind::Column));
|
||||
if let Some(c) = n.children_mut() {
|
||||
f(c);
|
||||
}
|
||||
let layer = doc.layers[0].id;
|
||||
doc.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
(what, doc)
|
||||
};
|
||||
cases.extend([
|
||||
drawn("a series without its group", &|c| {
|
||||
c.remove(2);
|
||||
}),
|
||||
drawn("no axes", &|c| {
|
||||
c.remove(0);
|
||||
}),
|
||||
drawn("a hidden legend", &|c| {
|
||||
if let Some(l) = c.last_mut() {
|
||||
Arc::make_mut(l).visible = false;
|
||||
}
|
||||
}),
|
||||
drawn("a series drawn half opaque", &|c| Arc::make_mut(&mut c[1]).opacity = 0.5),
|
||||
drawn("a series mark with a gradient", &|c| {
|
||||
let g = vectorcraft_color::Gradient::new(
|
||||
vectorcraft_color::GradientKind::Linear,
|
||||
vec![vectorcraft_color::GradientStop::new(0.0, Color::BLACK), vectorcraft_color::GradientStop::new(1.0, Color::WHITE)],
|
||||
);
|
||||
let series = Arc::make_mut(&mut c[1]);
|
||||
if let Some(marks) = series.children_mut() {
|
||||
let mark = Arc::make_mut(&mut marks[0]);
|
||||
mark.appearance = Appearance::basic(Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(g))), Paint::None, 0.0).into();
|
||||
}
|
||||
}),
|
||||
]);
|
||||
cases
|
||||
}
|
||||
|
||||
/// The graphs in `doc`, each with the series index of its members.
|
||||
pub(crate) fn graphs(doc: &Document) -> Vec<(GraphSpec, Vec<Option<u32>>)> {
|
||||
let mut out = vec![];
|
||||
doc.walk(|n| {
|
||||
if let Some(g) = n.extras().graph.as_deref() {
|
||||
out.push((g.clone(), n.children().map(|c| c.iter().map(|c| c.extras().series_index).collect()).unwrap_or_default()));
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether `read` is the graph `written` was: the same data and settings, the plot in the same
|
||||
/// place; its series' paint is the art's and its bounds are the art's as read.
|
||||
pub(crate) fn same(written: &GraphSpec, read: &GraphSpec) -> bool {
|
||||
let near = |a: Rect, b: Rect| (a.x0 - b.x0).abs() + (a.y0 - b.y0).abs() + (a.x1 - b.x1).abs() + (a.y1 - b.y1).abs() < 1e-6;
|
||||
let plain = |g: &GraphSpec| GraphSpec {
|
||||
rect: Rect::ZERO,
|
||||
rows: vec![],
|
||||
blanks: vec![],
|
||||
series_paints: vec![],
|
||||
placed: None,
|
||||
placed_art: None,
|
||||
series_kinds: vec![],
|
||||
..g.clone()
|
||||
};
|
||||
near(written.rect, read.rect) && written.cells() == read.cells() && plain(written) == plain(read)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Numbers are written so they read back the same, small and large ones included.
|
||||
#[test]
|
||||
fn numbers_read_back_as_written() {
|
||||
for v in [0.0, 1.0, -2.5, 1.0 / 3.0, 1e-7, 123_456_789_012_345_678.0, f64::MAX, f64::MIN_POSITIVE] {
|
||||
assert_eq!(real(v).parse::<f64>().ok(), Some(v), "{v}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A graph of `categories` rows of `series` values, drawn by [`sample::graph`].
|
||||
fn sized(categories: usize, series: usize) -> Node {
|
||||
let mut g = sample::spec(GraphKind::Column);
|
||||
(g.series, g.categories) = (vec![], vec![]);
|
||||
g.set_cells(vec![vec![Some(1.0); series]; categories]);
|
||||
sample::graph(&mut vectorcraft_doc::Document::new(400.0, 300.0), g)
|
||||
}
|
||||
|
||||
/// The table the reader holds: up to 10,000 categories and 256 series; past them, the graph is
|
||||
/// its art.
|
||||
#[test]
|
||||
fn tables_up_to_the_readers_limits_are_written() {
|
||||
assert!(records(&sized(MAX_GRAPH_CATEGORIES, 1), Affine::IDENTITY).is_some_and(|r| r.head.contains("%_10000 1 0 0 Gz\n")));
|
||||
assert!(records(&sized(MAX_GRAPH_CATEGORIES + 1, 1), Affine::IDENTITY).is_none());
|
||||
assert!(records(&sized(1, MAX_GRAPH_SERIES), Affine::IDENTITY).is_some_and(|r| r.tags.len() == MAX_GRAPH_SERIES));
|
||||
assert!(records(&sized(1, MAX_GRAPH_SERIES + 1), Affine::IDENTITY).is_none());
|
||||
}
|
||||
|
||||
/// Tick-mark counts of 0, which mean one tick mark as 1 does, are written as 1, the count the
|
||||
/// reader reads back.
|
||||
#[test]
|
||||
fn tick_mark_counts_of_0_are_written_as_1() {
|
||||
let mut g = sample::spec(GraphKind::Column);
|
||||
(g.tick_marks, g.right_tick_marks, g.category_tick_marks) = (0, 0, 0);
|
||||
let n = sample::graph(&mut vectorcraft_doc::Document::new(400.0, 300.0), g);
|
||||
let head = records(&n, Affine::IDENTITY).map(|r| r.head).unwrap_or_default();
|
||||
let marks: Vec<&str> = head.lines().filter(|l| l.ends_with(" GA")).map(|l| l.split(' ').nth(5).unwrap_or("")).collect();
|
||||
assert_eq!(marks, ["1", "1", "1"], "{head}");
|
||||
}
|
||||
|
||||
/// A table's cells go fifteen to a record, with one string at most in each.
|
||||
#[test]
|
||||
fn cells_go_fifteen_to_a_record_with_one_string_each() {
|
||||
let mut out = String::new();
|
||||
let mut t = Table::new(&mut out);
|
||||
t.text("a");
|
||||
t.text("b");
|
||||
for v in 0..16 {
|
||||
t.num(f64::from(v));
|
||||
}
|
||||
t.finish();
|
||||
let records: Vec<&str> = out.lines().collect();
|
||||
assert_eq!(records[0], "%_(a) Gc");
|
||||
assert_eq!(records[1], "%_(b) 0 1 2 3 4 5 6 7 8 9 10 11 12 13 Gc");
|
||||
assert_eq!(records[2], "%_14 15 Gc");
|
||||
}
|
||||
}
|
||||
@@ -631,7 +631,7 @@ impl<'a> Reader<'a> {
|
||||
let Some(paints) = series_paints(art, &tags, spec.kind == GraphKind::Line) else { return false };
|
||||
spec.series_paints = paints;
|
||||
spec.placed = Some(placed);
|
||||
spec.placed_art = art.children().and_then(|c| vectorcraft_doc::graph::art_bounds(c));
|
||||
spec.placed_art = art.children().and_then(|c| vectorcraft_doc::graph::graph_art_without_type(c));
|
||||
tag_series(art, &tags);
|
||||
art.extras_mut().graph = Some(Box::new(spec));
|
||||
true
|
||||
|
||||
@@ -10329,23 +10329,48 @@ fn a_brushed_path_with_samples_of_the_pen_keeps_its_drawn_look() {
|
||||
assert_eq!(a.len(), 1, "{a:#?}");
|
||||
assert!(matches!(a[0].kind, NodeKind::Group { .. }), "the drawn look: {a:#?}");
|
||||
assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings);
|
||||
// The samples belong to the path before them: a path after them is read as it was.
|
||||
let after = format!("{path}{RED}{}f\n", rect_path(0.0, 0.0, 10.0, 10.0));
|
||||
// The samples belong to the path before them: a path after them with the same brush and no
|
||||
// samples of its own comes in brushed.
|
||||
let after = format!("{path}{}", brushed_path());
|
||||
let a = art(&read_ok(&format!("{def}{style}{}", layer(&after))).doc);
|
||||
assert_eq!(a.len(), 2, "{a:#?}");
|
||||
assert!(matches!(a[1].kind, NodeKind::Path { .. }) && a[1].appearance.fill().is_some(), "{a:#?}");
|
||||
assert!(matches!(a[0].kind, NodeKind::Group { .. }), "the sampled path's drawn look: {a:#?}");
|
||||
assert!(matches!(a[1].kind, NodeKind::Path { .. }), "the path after the samples, brushed: {a:#?}");
|
||||
assert_eq!(a[1].appearance.stroke().and_then(|s| s.brush.as_deref()), Some("Six D"), "{a:#?}");
|
||||
// Samples with no object before them in the layer mark nothing: the path after them is read.
|
||||
let first = format!("{PEN_SAMPLES}{}", brushed_path());
|
||||
let a = art(&read_ok(&format!("{def}{style}{}", layer(&first))).doc);
|
||||
assert_eq!(a.len(), 1, "{a:#?}");
|
||||
assert!(matches!(a[0].kind, NodeKind::Path { .. }), "the path, brushed: {a:#?}");
|
||||
// A brush whose modes are Fixed and Random, one whose pen modes vary by 0, and an Art brush
|
||||
// don't follow the pen: the path comes in brushed.
|
||||
// Each setting that follows the pen keeps the drawn look on its own, with the other two fixed:
|
||||
// the diameter with the pressure or the tilt, the roundness with the bearing and the angle with
|
||||
// the barrel's rotation.
|
||||
let one_setting = [
|
||||
("the diameter with the pressure", "1 4 8 40 40 30 30 2 0 0 0", [(6.0, 2.0), (40.0, 0.0), (30.0, 0.0)], [2, 0, 0]),
|
||||
("the diameter with the tilt", "1 4 8 40 40 30 30 4 0 0 0", [(6.0, 2.0), (40.0, 0.0), (30.0, 0.0)], [4, 0, 0]),
|
||||
("the roundness with the bearing", "1 6 6 30 50 30 30 0 5 0 0", [(6.0, 0.0), (40.0, 10.0), (30.0, 0.0)], [0, 5, 0]),
|
||||
("the angle with the rotation", "1 6 6 40 40 -150 210 0 0 6 0", [(6.0, 0.0), (40.0, 0.0), (30.0, 180.0)], [0, 0, 6]),
|
||||
];
|
||||
for (why, params, settings, codes) in one_setting {
|
||||
let def = plugin_object(CALLIGRAPHIC, "Six D", params);
|
||||
let style = brushed_style("Six D", 0.5, settings, codes, 0);
|
||||
let r = read_ok(&format!("{def}{style}{}", layer(&path)));
|
||||
let a = art(&r.doc);
|
||||
assert_eq!(a.len(), 1, "{why}: {a:#?}");
|
||||
assert!(matches!(a[0].kind, NodeKind::Group { .. }), "{why}: the drawn look, {a:#?}");
|
||||
assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{why}: {:?}", r.warnings);
|
||||
}
|
||||
// A brush whose modes are Fixed and Random, one whose pen modes vary by 0, one whose only
|
||||
// varying setting is Random beside a pen setting that varies by 0, and an Art brush don't
|
||||
// follow the pen: the path comes in brushed.
|
||||
let fixed_def = plugin_object(CALLIGRAPHIC, "Six D", &SIX_D.replace(" 2 5 6 0", " 0 1 0 0"));
|
||||
let fixed = brushed_style("Six D", 0.5, SIX_D_SETTINGS, [0, 1, 0], 0);
|
||||
let even_def = plugin_object(CALLIGRAPHIC, "Six D", "1 6 6 40 40 30 30 2 5 6 0");
|
||||
let even = brushed_style("Six D", 0.5, [(6.0, 0.0), (40.0, 0.0), (30.0, 0.0)], [2, 5, 6], 0);
|
||||
for (why, def, style) in [("Fixed and Random", fixed_def, fixed), ("no variation", even_def, even)] {
|
||||
let random_def = plugin_object(CALLIGRAPHIC, "Six D", "1 4 8 40 40 30 30 1 2 0 0");
|
||||
let random = brushed_style("Six D", 0.5, [(6.0, 2.0), (40.0, 0.0), (30.0, 0.0)], [1, 2, 0], 0);
|
||||
let cases = [("Fixed and Random", fixed_def, fixed), ("no variation", even_def, even), ("Random beside an even pen setting", random_def, random)];
|
||||
for (why, def, style) in cases {
|
||||
let r = read_ok(&format!("{def}{style}{}", layer(&path)));
|
||||
let a = art(&r.doc);
|
||||
assert_eq!(a.len(), 1, "{why}: {a:#?}");
|
||||
|
||||
@@ -25,6 +25,7 @@ use std::collections::{BTreeMap, HashMap};
|
||||
|
||||
use kurbo::{BezPath, CubicBez, ParamCurve, ParamCurveArclen};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::text::MAX_AKI;
|
||||
use vectorcraft_doc::{
|
||||
Burasagari, CharStyle, HyphenationOptions, JustificationOptions, Justify, Kinsoku, KinsokuShoriType, LineCap, LineJoin, Node, NodeId, NodeKind,
|
||||
ParaDirection, ParaStyle, PathAlign, PathEffect, TabAlign, TabStop, TextKind, TextObject, TextRun,
|
||||
@@ -525,6 +526,17 @@ struct Style {
|
||||
/// Key 35 at 1 (Standard): Standard Vertical Roman Alignment, half-width characters upright in
|
||||
/// a column. Any other value, or no key in the run, its character style or the defaults, is off.
|
||||
standard_vertical_roman: bool,
|
||||
/// Keys 49 and 50, Insert Aki Left and Right ([`CharStyle::aki_left`]), in 1/1000 em.
|
||||
aki_left: f64,
|
||||
aki_right: f64,
|
||||
}
|
||||
|
||||
/// Insert Aki Left or Right as key `v` of a character style gives it, in 1/1000 em (the unit the
|
||||
/// scripting reference gives `aki left` and `aki right`), 0 to [`MAX_AKI`]. A negative value, one
|
||||
/// that is not a finite number, or no key is 0: no space added. A key the run itself carries wins
|
||||
/// over its styles' even when it is not a number, so a bad value never shows a style's.
|
||||
fn aki(v: Option<&Val>) -> f64 {
|
||||
v.and_then(Val::num).filter(|v| v.is_finite() && *v > 0.0).map_or(0.0, |v| v.min(MAX_AKI))
|
||||
}
|
||||
|
||||
/// The longest font version string read from a font record: name ID 5 strings are short (`Version
|
||||
@@ -922,6 +934,8 @@ impl Texts {
|
||||
caps: num("12").filter(|v| *v == 1.0 || *v == 2.0).map_or(0, |v| v as u8),
|
||||
tate_chu_yoko: num("35") == Some(3.0),
|
||||
standard_vertical_roman: num("35") == Some(1.0),
|
||||
aki_left: aki(pick("49")),
|
||||
aki_right: aki(pick("50")),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1549,6 +1563,9 @@ fn char_style(s: &Style, scale: f64, to_text: Affine) -> CharStyle {
|
||||
small_caps: (s.caps == 1).then(|| vectorcraft_doc::DocSetup::default().small_caps_size),
|
||||
tate_chu_yoko: s.tate_chu_yoko,
|
||||
standard_vertical_roman: s.standard_vertical_roman,
|
||||
// In ems of the type's own size, so the art's scale does not apply.
|
||||
aki_left: s.aki_left,
|
||||
aki_right: s.aki_right,
|
||||
..CharStyle::default()
|
||||
}
|
||||
}
|
||||
@@ -1922,6 +1939,48 @@ mod tests {
|
||||
assert!(texts(b"/35 3").style(None).tate_chu_yoko && !texts(b"/35 3").style(None).standard_vertical_roman);
|
||||
}
|
||||
|
||||
/// Keys 49 and 50 of a character style are Insert Aki Left and Right in 1/1000 em, each from the
|
||||
/// run, its character style and the styles that is based on, `[Normal Character Style]`, then the
|
||||
/// document's defaults. A run's own 0 wins over a style's value, a value past 1000 is 1000, and a
|
||||
/// negative value, one that is not a number or no key at all is 0.
|
||||
#[test]
|
||||
fn a_run_keeps_its_insert_aki() {
|
||||
let texts = |defaults: &[u8], normal: &[u8]| Texts {
|
||||
stories: vec![],
|
||||
fonts: vec![],
|
||||
defaults: read(defaults).unwrap(),
|
||||
para_defaults: Val::Dict(BTreeMap::new()),
|
||||
char_sheets: vec![
|
||||
read(&[&b"/0 ([Normal Character Style]) /6 << "[..], normal, b" >>"].concat()).unwrap(),
|
||||
read(b"/0 (Base) /6 << /49 125.0 >>").unwrap(),
|
||||
read(b"/0 (Spaced) /5 1 /6 << /50 500.0 >>").unwrap(),
|
||||
],
|
||||
para_sheets: vec![],
|
||||
frames: vec![],
|
||||
patterns: HashMap::new(),
|
||||
kinsoku_sets: vec![],
|
||||
};
|
||||
let aki = |defaults: &[u8], normal: &[u8], run: &[u8]| {
|
||||
let s = texts(defaults, normal).style(Some(&read(run).unwrap()));
|
||||
(s.aki_left, s.aki_right)
|
||||
};
|
||||
assert_eq!(aki(b"/0 0", b"", b"/6 << /49 250.0 /50 750.0 >>"), (250.0, 750.0), "the run's own");
|
||||
assert_eq!(aki(b"/0 0", b"", b"/5 2 /6 << >>"), (125.0, 500.0), "its style's, and the style that is based on");
|
||||
assert_eq!(aki(b"/0 0", b"", b"/5 2 /6 << /49 0.0 /50 0 >>"), (0.0, 0.0), "the run's own zero wins");
|
||||
assert_eq!(aki(b"/49 10.0 /50 20.0", b"/49 30.0", b"/6 << >>"), (30.0, 20.0), "Normal, then the document's");
|
||||
assert_eq!(aki(b"/49 10.0 /50 20.0", b"", b"/6 << >>"), (10.0, 20.0), "the document's");
|
||||
assert_eq!(aki(b"/0 0", b"", b"/6 << >>"), (0.0, 0.0), "no key");
|
||||
assert_eq!(aki(b"/0 0", b"", b"/6 << /49 1000.5 /50 1e300 >>"), (MAX_AKI, MAX_AKI), "clamped");
|
||||
for bad in [&b"-1.0"[..], b"-250", b"(125)", b"true", b"[ 125 ]", b"1e400", b"-1e400"] {
|
||||
let run = [&b"/5 2 /6 << /49 "[..], bad, b" /50 ", bad, b" >>"].concat();
|
||||
assert_eq!(aki(b"/0 0", b"", &run), (0.0, 0.0), "{}", String::from_utf8_lossy(bad));
|
||||
}
|
||||
// In ems of the type's size: the art's scale leaves it as it is.
|
||||
let s = texts(b"/0 0", b"").style(Some(&read(b"/6 << /49 250.0 /50 125.0 >>").unwrap()));
|
||||
let c = char_style(&s, 10.0, Affine::IDENTITY);
|
||||
assert_eq!((c.aki_left, c.aki_right), (250.0, 125.0));
|
||||
}
|
||||
|
||||
/// Keys 61, 62 and 64 of a character style are its stroke's cap (0 butt, 1 round, 2
|
||||
/// projecting), join (0 miter, 1 round, 2 bevel) and miter limit, from the run, its character
|
||||
/// style or the document's defaults. A value that isn't one of theirs keeps the default, a miter
|
||||
@@ -2397,6 +2456,8 @@ mod tests {
|
||||
caps: 0,
|
||||
tate_chu_yoko: false,
|
||||
standard_vertical_roman: false,
|
||||
aki_left: 0.0,
|
||||
aki_right: 0.0,
|
||||
},
|
||||
)],
|
||||
kerns: vec![],
|
||||
|
||||
@@ -43,13 +43,17 @@
|
||||
//! PostScript names in `%%DocumentFonts` and `%%IncludeFont` (§3.1) and re-encoded to
|
||||
//! Windows-1252 (`TE`, then `%AI3_BeginEncoding: _name name`, `TZ`, §3.3), the 8-bit encoding
|
||||
//! strings are in.
|
||||
//! - Graphs (§17): a graph whose records VectorCraft's reader reads back as the same graph
|
||||
//! (`crate::ai_graph`) as `%_Gs`, its functional records, its group with each series' group
|
||||
//! followed by `%_2 column 0 0 Go`, and `%_GS`.
|
||||
//!
|
||||
//! The format has one artboard, no transparency, sublayers, object names, hidden objects (only
|
||||
//! layers hide), live effects, symbols or appearances with several fills and strokes. Callers write
|
||||
//! one file per artboard and expand appearances first; what is left is written as the format can
|
||||
//! hold it, each loss a warning: transparent objects are written opaque, sublayers become groups,
|
||||
//! live objects and symbols their art, strokes a plain line can't draw their outlines, pattern
|
||||
//! fills their tiles clipped to the shape, freeform gradients their average colour, elliptical
|
||||
//! live objects and symbols their art, other graphs their art, strokes a plain line can't draw
|
||||
//! their outlines, pattern fills their tiles clipped to the shape, freeform gradients their average
|
||||
//! colour, elliptical
|
||||
//! radial gradients circular (the gradient matrix is relative to a canvas the specification
|
||||
//! doesn't size), transparent image pixels over white. Hidden objects go to a hidden layer of
|
||||
//! their own above their layer, are left out or show, as [`HiddenObjects`] says (in a hidden
|
||||
@@ -101,7 +105,7 @@ const HEX_LINE: usize = 60;
|
||||
pub const SUBLAYERS: &str = "sublayers are written as groups in their top-level layer (legacy .ai files have no sublayers)";
|
||||
pub const TYPE: &str = "type a legacy .ai can't hold as text (characters outside Windows Latin-1, vertical type, ruby, inline graphics, gradient or pattern fills) is written as outlines";
|
||||
pub const ROTATED_TYPE: &str = "type with rotated characters is written as outlines, which keep the rotation, and is no longer editable text (legacy .ai text can't rotate characters)";
|
||||
pub const TYPE_ATTRIBUTES: &str = "type attributes legacy .ai files don't have (underline, strikethrough, optical kerning, small caps, superscript and subscript, OpenType features, Variable Font settings, optical margin alignment, System Layout, fractional widths off, area type options, type on a path's effect, alignment and spacing, an end bracket short of the path's end, subpaths after the first in an area type frame or a type path, space after paragraphs, tabs, bulleted and numbered lists) are left out";
|
||||
pub const TYPE_ATTRIBUTES: &str = "type attributes legacy .ai files don't have (underline, strikethrough, optical kerning, small caps, superscript and subscript, Insert Aki, OpenType features, Variable Font settings, optical margin alignment, System Layout, fractional widths off, area type options, type on a path's effect, alignment and spacing, an end bracket short of the path's end, subpaths after the first in an area type frame or a type path, space after paragraphs, tabs, bulleted and numbered lists) are left out";
|
||||
pub const DYNAMIC_TEXT: &str = "Dynamic Text is written as the sizes the type is drawn at (legacy .ai files don't have it)";
|
||||
pub const HIDDEN: &str = "hidden objects are left out (hidden layers are kept, hidden)";
|
||||
pub const HIDDEN_LAYER: &str = "hidden objects are moved to a hidden layer above their own (legacy .ai files can hide only layers)";
|
||||
|
||||
@@ -123,6 +123,9 @@ pub(super) fn lost_attributes(t: &TextObject) -> bool {
|
||||
|| s.optical_kerning
|
||||
|| s.small_caps.is_some()
|
||||
|| s.position != CharPosition::Normal
|
||||
// Its text operators (§15.4) have no Insert Aki.
|
||||
|| s.aki_left != 0.0
|
||||
|| s.aki_right != 0.0
|
||||
|| !s.features.is_empty()
|
||||
|| !s.font_axes.is_empty()
|
||||
};
|
||||
|
||||
@@ -1435,6 +1435,41 @@ fn variable_font_settings_are_warned_as_left_out() {
|
||||
assert!(String::from_utf8(out.bytes).unwrap().contains("(H\\351llo \\2005\\r) Tx\n"), "still written as text");
|
||||
}
|
||||
|
||||
/// A legacy `.ai` text object has no Insert Aki (§15.4): type with Insert Aki Left or Right is
|
||||
/// written as text with the warning that it is left out. Written as outlines, the glyphs keep the
|
||||
/// space it adds, and nothing is reported.
|
||||
#[test]
|
||||
fn insert_aki_is_warned_as_left_out_of_text() {
|
||||
for (left, right) in [(250.0, 0.0), (0.0, 125.0)] {
|
||||
let mut doc = typed();
|
||||
let id = texts(&doc)[0].0.id;
|
||||
if let Some(NodeKind::Text(t)) = doc.node_mut(id).map(|n| &mut n.kind) {
|
||||
t.runs[0].style.aki_left = left;
|
||||
t.runs[0].style.aki_right = right;
|
||||
}
|
||||
let out = write(&doc);
|
||||
assert!(out.warnings.iter().any(|w| w == TYPE_ATTRIBUTES), "{left} {right}: {:?}", out.warnings);
|
||||
assert!(String::from_utf8(out.bytes).unwrap().contains("(H\\351llo \\2005\\r) Tx\n"), "still written as text");
|
||||
}
|
||||
let width = |aki: f64| {
|
||||
let mut st = style(20.0, red());
|
||||
st.aki_left = aki;
|
||||
st.aki_right = aki;
|
||||
let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), "HH", st);
|
||||
let mut doc = Document::new(300.0, 200.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t)));
|
||||
doc.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
let out = write_with(&doc, LegacyAiOptions { outline_text: true, ..LegacyAiOptions::default() });
|
||||
assert!(!out.warnings.iter().any(|w| w == TYPE_ATTRIBUTES), "{:?}", out.warnings);
|
||||
let back = crate::import(&out.bytes).unwrap().document;
|
||||
children(&children(&back.layers[0])[0])[0].visual_bounds().unwrap().width()
|
||||
};
|
||||
// Between the two H's: 0.5 em after the first and 0.5 em before the second, 20 pt.
|
||||
let (plain, spaced) = (width(0.0), width(500.0));
|
||||
assert!((spaced - plain - 20.0).abs() < 0.05, "{plain} {spaced}");
|
||||
}
|
||||
|
||||
/// Standard Vertical Roman Alignment is written as `Tv` and Tate-chu-yoko in horizontal type as a
|
||||
/// Kumi block recorded for later use, `TY` (§15.3.4), each where it changes: the marks read back
|
||||
/// on the same characters, a block is closed before its text object ends, and type with neither
|
||||
@@ -2122,3 +2157,64 @@ fn a_stained_instance_is_written_in_its_stained_color() {
|
||||
let text = String::from_utf8(write(&doc).bytes).unwrap();
|
||||
assert!(text.contains("0 0 1 Xa") && !text.contains("1 0 0 Xa"), "{text}");
|
||||
}
|
||||
|
||||
/// A graph whose records read back whole is written with them (§17), and opens again as the same
|
||||
/// live graph: its table, type and settings, its series' groups tagged in order, without a warning
|
||||
/// about graphs.
|
||||
#[test]
|
||||
fn graphs_are_written_with_their_records_and_open_live() {
|
||||
use crate::ai_graph::sample;
|
||||
for (what, doc) in sample::kept() {
|
||||
let out = write(&doc);
|
||||
assert!(!out.warnings.iter().any(|w| w == GRAPHS), "{what}: {:?}", out.warnings);
|
||||
let text = String::from_utf8(out.bytes.clone()).unwrap();
|
||||
assert_eq!((text.matches("%_Gs\n").count(), text.matches("%_GS\n").count()), (1, 1), "{what}: {text}");
|
||||
let read = crate::import(&out.bytes).unwrap();
|
||||
let written = sample::graphs(&doc);
|
||||
let graphs = sample::graphs(&read.document);
|
||||
assert_eq!(graphs.len(), 1, "{what}: {:?}", read.warnings);
|
||||
assert!(sample::same(&written[0].0, &graphs[0].0), "{what}: {:#?}\n{:#?}", written[0].0, graphs[0].0);
|
||||
assert_eq!(graphs[0].1, written[0].1, "{what}: the members and their series");
|
||||
}
|
||||
}
|
||||
|
||||
/// A graph inside a group is written with its records too, and opens on its own group.
|
||||
#[test]
|
||||
fn a_graph_in_a_group_is_written_with_its_records() {
|
||||
use crate::ai_graph::sample;
|
||||
let mut doc = Document::new(400.0, 300.0);
|
||||
let graph = sample::graph(&mut doc, sample::spec(vectorcraft_doc::GraphKind::Column));
|
||||
let frame = shape(&mut doc, shapes::rectangle(Rect::new(10.0, 10.0, 20.0, 20.0)), red(), Paint::None);
|
||||
let outer = Node::group(doc.alloc_id(), vec![Arc::new(frame), Arc::new(graph)]);
|
||||
let l = doc.layers[0].id;
|
||||
doc.insert(Some(l), 0, outer).unwrap();
|
||||
let out = write(&doc);
|
||||
assert!(!out.warnings.iter().any(|w| w == GRAPHS), "{:?}", out.warnings);
|
||||
let read = crate::import(&out.bytes).unwrap();
|
||||
let graphs = sample::graphs(&read.document);
|
||||
assert_eq!(graphs.len(), 1, "{:?}", read.warnings);
|
||||
assert!(sample::same(&sample::graphs(&doc)[0].0, &graphs[0].0));
|
||||
let layer = children(&read.document.layers[0]);
|
||||
assert!(layer[0].extras().graph.is_none() && layer[0].children().is_some_and(|c| c.len() == 2), "{layer:#?}");
|
||||
}
|
||||
|
||||
/// A graph whose records wouldn't read back as it is is written as its art, without records, with
|
||||
/// the warning, and opens as that art.
|
||||
#[test]
|
||||
fn graphs_the_records_cant_keep_are_written_as_their_art() {
|
||||
use crate::ai_graph::sample;
|
||||
for (what, doc) in sample::unkept() {
|
||||
let out = export_legacy_ai(&doc, &LegacyAiOptions::default()).unwrap();
|
||||
assert!(out.warnings.iter().any(|w| w == GRAPHS), "{what}: {:?}", out.warnings);
|
||||
let text = String::from_utf8_lossy(&out.bytes).into_owned();
|
||||
assert!(!text.contains("%_Gs") && !text.contains(" Go\n") && !text.contains("%_GS"), "{what}: {text}");
|
||||
let read = crate::import(&out.bytes).unwrap();
|
||||
assert!(sample::graphs(&read.document).is_empty(), "{what}");
|
||||
let paths = |d: &Document| {
|
||||
let mut count = 0;
|
||||
d.walk(|n| count += usize::from(matches!(n.kind, NodeKind::Path { .. })));
|
||||
count
|
||||
};
|
||||
assert_eq!(paths(&read.document), paths(&doc), "{what}: the graph's art is kept");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,6 +52,8 @@ pub(super) struct Writer<'a> {
|
||||
last_image: Option<(ImageBlob, Option<Arc<image::DynamicImage>>)>,
|
||||
/// The images written whole so far, by the address of their data (which each entry keeps).
|
||||
whole_images: std::collections::HashMap<usize, Arc<Vec<u8>>>,
|
||||
/// Writing a graph's art with its records: a graph inside it is written as its art.
|
||||
in_graph: bool,
|
||||
}
|
||||
|
||||
impl<'a> Writer<'a> {
|
||||
@@ -78,6 +80,7 @@ impl<'a> Writer<'a> {
|
||||
clips: vec![],
|
||||
last_image: None,
|
||||
whole_images: std::collections::HashMap::new(),
|
||||
in_graph: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -264,7 +267,12 @@ impl<'a> Writer<'a> {
|
||||
if n.name.as_deref().is_some_and(|s| !s.is_empty()) && !n.is_layer() {
|
||||
self.warn(NAMES);
|
||||
}
|
||||
if n.extras().graph.is_some() {
|
||||
// A graph on the layers keeps its data and settings when its records read back whole.
|
||||
let graph = match n.extras().graph.is_some() {
|
||||
true if self.nest == 0 && !self.in_graph => crate::ai_graph::records(n, self.to_art),
|
||||
_ => None,
|
||||
};
|
||||
if n.extras().graph.is_some() && graph.is_none() {
|
||||
self.warn(GRAPHS);
|
||||
}
|
||||
let locked = locked || n.locked;
|
||||
@@ -273,7 +281,10 @@ impl<'a> Writer<'a> {
|
||||
self.warn(SUBLAYERS);
|
||||
self.group(children, *clip, locked);
|
||||
}
|
||||
NodeKind::Group { children, clip } => self.group(children, *clip, locked),
|
||||
NodeKind::Group { children, clip } => match &graph {
|
||||
Some(records) => self.graph(children, locked, records),
|
||||
None => self.group(children, *clip, locked),
|
||||
},
|
||||
NodeKind::Path { path, rule, guide, .. } => {
|
||||
self.lock(locked);
|
||||
if *guide {
|
||||
@@ -352,6 +363,25 @@ impl<'a> Writer<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A graph's group (`u` … `U`) between its records (§17): `%_Gs` and its functional records
|
||||
/// before it, `%_GS` after it, and each series' group followed by its `Go` tag.
|
||||
fn graph(&mut self, children: &[Arc<Node>], locked: bool, records: &crate::ai_graph::Records) {
|
||||
self.lock(locked);
|
||||
self.body.push_str(&records.head);
|
||||
self.line("u");
|
||||
self.in_graph = true;
|
||||
for c in children {
|
||||
self.node(c, locked);
|
||||
if let Some(tag) = records.tags.get(&c.id) {
|
||||
self.line(tag);
|
||||
}
|
||||
}
|
||||
self.in_graph = false;
|
||||
self.lock(locked);
|
||||
self.line("U");
|
||||
self.line(crate::ai_graph::END);
|
||||
}
|
||||
|
||||
/// A clipping group: its first member's outline clips the others (`h W n`). That member's fills
|
||||
/// paint behind the art, inside the clip, and its strokes over it, outside.
|
||||
fn clip_group(&mut self, children: &[Arc<Node>], locked: bool) {
|
||||
|
||||
@@ -31,9 +31,11 @@
|
||||
//! - `ai_editing`: the editing copy of the art a PDF-compatible `.ai` file carries
|
||||
//! ([`export_ai_editing`], [`ai_private_data`]).
|
||||
//! - `ai_ops`: the path and line style operators those two write.
|
||||
//! - `ai_graph`: the records of a live graph those two write around its group.
|
||||
//! - [`dcs`]: DCS files, an EPS file with one program per printing plate, read for placing.
|
||||
|
||||
mod ai_editing;
|
||||
mod ai_graph;
|
||||
mod ai_ops;
|
||||
pub mod dcs;
|
||||
mod import;
|
||||
|
||||
@@ -489,8 +489,11 @@ impl<'a> Scene<'a> {
|
||||
self.warn(TOO_LARGE);
|
||||
return;
|
||||
}
|
||||
// Off the region, an object is still written when brush art painted along its brushed
|
||||
// strokes, or those of the objects in it, can reach the region.
|
||||
let off = |b: Rect, reach: f64| !overlaps(b.inflate(1.0 + reach, 1.0 + reach), self.o.region);
|
||||
match n.visual_bounds_with(&self.symbols) {
|
||||
Some(b) if !force && !overlaps(b.inflate(1.0, 1.0), self.o.region) => return,
|
||||
Some(b) if !force && off(b, 0.0) && off(b, vectorcraft_brush::reach_within(n)) => return,
|
||||
None if !n.is_container() => return,
|
||||
_ => {}
|
||||
}
|
||||
|
||||
@@ -1654,6 +1654,59 @@ fn an_instance_whose_brush_art_reaches_the_region_is_written() {
|
||||
assert!(page.contains("1 0 0 rg"), "{page}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_whose_brush_art_reaches_the_region_is_written() {
|
||||
// A line from (-5, 40) to (-5, 60) with a 1 pt red stroke painted by a 20 pt round nib lies
|
||||
// left of the artboard, and the nib paints 10 pt either side of it, onto the artboard: alone, in
|
||||
// a group and as a compound path. Without its brush, or 100 pt left of the artboard, where the
|
||||
// nib does not reach it, the line is left out.
|
||||
let red = |x: f64, brushed: bool| {
|
||||
let mut n = Node::path(
|
||||
vectorcraft_doc::NodeId(0),
|
||||
shapes::line((x, 40.0).into(), (x, 60.0).into()),
|
||||
Appearance::basic(Paint::None, Paint::solid(Color::rgb(1.0, 0.0, 0.0)), 1.0),
|
||||
);
|
||||
if brushed {
|
||||
n.appearance.stroke_mut().unwrap().brush = Some("3 pt. Round".into());
|
||||
}
|
||||
n
|
||||
};
|
||||
let cases: [(&str, f64, bool, bool); 5] = [
|
||||
("path", -5.0, true, true),
|
||||
("group", -5.0, true, true),
|
||||
("compound path", -5.0, true, true),
|
||||
("unbrushed path", -5.0, false, false),
|
||||
("far path", -100.0, true, false),
|
||||
];
|
||||
for (what, x, brushed, written) in cases {
|
||||
let mut d = Document::new(200.0, 200.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 line = red(x, brushed);
|
||||
let mut n = match what {
|
||||
"group" => Node::group(vectorcraft_doc::NodeId(0), vec![Arc::new(line)]),
|
||||
"compound path" => {
|
||||
let mut c = Node::new(
|
||||
vectorcraft_doc::NodeId(0),
|
||||
NodeKind::Compound { children: vec![Arc::new(red(x, false))], rule: vectorcraft_geom::FillRule::NonZero },
|
||||
);
|
||||
c.appearance = line.appearance;
|
||||
c
|
||||
}
|
||||
_ => line,
|
||||
};
|
||||
n.id = d.alloc_id();
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
let page = page_of(&d, &opts(&d));
|
||||
assert_eq!(page.contains("1 0 0 rg") || page.contains("1 0 0 RG"), written, "{what}: {page}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbol_art_effects_are_written_where_they_draw() {
|
||||
// The symbol's square at (10, 40), which a Transform effect moves 100 pt right, is drawn from
|
||||
|
||||
@@ -166,10 +166,11 @@ fn create(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Va
|
||||
/// `Object.defineProperty` (section 15.2.3.6).
|
||||
fn define_property(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let o = require_object(interp, &arg(args, 0), "defineProperty")?;
|
||||
let k = interp.to_key(&arg(args, 1))?;
|
||||
let desc = to_desc(interp, &arg(args, 2))?;
|
||||
let roots = desc_values(&desc);
|
||||
interp.rooted(&roots, |interp| interp.define_own_property(o, k, &desc, true))?;
|
||||
interp.with_key(&arg(args, 1), |interp, k| {
|
||||
let desc = to_desc(interp, &arg(args, 2))?;
|
||||
let roots = desc_values(&desc);
|
||||
interp.rooted(&roots, |interp| interp.define_own_property(o, k, &desc, true))
|
||||
})?;
|
||||
Ok(Value::Object(o))
|
||||
}
|
||||
|
||||
|
||||
+14
-4
@@ -1779,8 +1779,7 @@ impl Interp {
|
||||
return self.replace(2, v);
|
||||
}
|
||||
self.check_coercible(&base, &[])?;
|
||||
let name = self.to_key(&k)?;
|
||||
let v = self.get_value(&base, &name)?;
|
||||
let v = self.with_key(&k, |i, name| i.get_value(&base, &name))?;
|
||||
self.replace(2, v)?;
|
||||
if with_this { self.push(base) } else { Ok(()) }
|
||||
}
|
||||
@@ -1852,8 +1851,7 @@ impl Interp {
|
||||
return self.replace(2, Value::Number(if prefix { new } else { old }));
|
||||
}
|
||||
self.check_coercible(&base, &[])?;
|
||||
let name = self.to_key(&k)?;
|
||||
let r = self.inc_property(&base, name, prefix, dec)?;
|
||||
let r = self.with_key(&k, |i, name| i.inc_property(&base, name, prefix, dec))?;
|
||||
self.replace(2, r)
|
||||
}
|
||||
|
||||
@@ -2670,6 +2668,18 @@ impl Interp {
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `f` with the property name [`Self::to_key`] makes from `v`. A name converted from a
|
||||
/// value that is not a string is kept reachable while `f` runs, so a collection that a getter
|
||||
/// or setter starts still counts its units.
|
||||
pub(crate) fn with_key<T>(&mut self, v: &Value, f: impl FnOnce(&mut Self, Key) -> JsResult<T>) -> JsResult<T> {
|
||||
let name = self.to_key(v)?;
|
||||
if matches!(v, Value::String(_)) {
|
||||
return f(self, name);
|
||||
}
|
||||
let root = Value::String(Str::from_rc(name.clone()));
|
||||
self.rooted(&[root], |i| f(i, name))
|
||||
}
|
||||
|
||||
/// The code units of `s`. Flattening a rope makes a copy of its units, so for a rope that
|
||||
/// copy's bytes are reserved and added to the heap first, without taking fuel. The rope stays
|
||||
/// rooted while the copy is reserved; everything else the caller still needs must be
|
||||
|
||||
@@ -434,6 +434,32 @@ fn a_call_keeps_its_operands_while_a_string_receiver_is_boxed() {
|
||||
assert_eq!(realm.run(src), Ok(JsValue::Number(1.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_computed_key_stays_counted_while_its_getter_or_setter_runs() {
|
||||
// `o` has an accessor named by a flat string of 131,073 units. `key`'s toString returns a new
|
||||
// rope with the same units, so using `key` as a name makes a second flat copy, which must stay
|
||||
// counted while an accessor makes a third. The heap has room for one more copy, not two.
|
||||
let build = "var s = 'x'; for (var i = 0; i < 17; i++) s = s + s; function f(c) { return s + c; } \
|
||||
function copy() { var g = f('g'); g[0]; return 1; } var o = {}, name = f('k'); name[0]; \
|
||||
Object.defineProperty(o, name, { get: copy, set: copy }); \
|
||||
var key = { toString: function () { return f('k'); } }; 0";
|
||||
let realm = || {
|
||||
let mut realm = Realm::with_options(Options::default(), Limits::default());
|
||||
assert_eq!(realm.run(build), Ok(JsValue::Number(0.0)));
|
||||
let interp = realm.interp();
|
||||
interp.collect_garbage();
|
||||
let copy = crate::heap::string_bytes(131_073);
|
||||
interp.limits.heap_bytes = interp.heap.bytes + copy + copy / 2;
|
||||
interp.reset_gc_threshold();
|
||||
realm
|
||||
};
|
||||
assert_eq!(realm().run("o[name]"), Ok(JsValue::Number(1.0)), "the accessor's own copy fits");
|
||||
for read in ["o[key]", "o[key] = 1", "o[key]++", "Object.defineProperty({}, key, { get value() { return copy(); } })"] {
|
||||
let result = realm().run(read);
|
||||
assert!(matches!(result, Err(ref e) if e.kind == RunErrorKind::Limit(LimitKind::Heap)), "{read}: {result:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compiling_a_pattern_counts_against_the_heap() {
|
||||
let src = "var s = '[\\\\s\\\\S]a*'; for (var i = 0; i < 14; i++) s = s + s; new RegExp(s).source.length";
|
||||
|
||||
@@ -81,6 +81,7 @@ pub(crate) fn pointer_kind(k: &str) -> Option<PointerKind> {
|
||||
"up" => PointerKind::Up,
|
||||
"move" => PointerKind::Move,
|
||||
"doubleclick" | "dblclick" => PointerKind::DoubleClick,
|
||||
"tripleclick" => PointerKind::TripleClick,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -238,7 +239,7 @@ impl Headless {
|
||||
.map(|(e, backquote)| {
|
||||
let mods = packet_mods(e)?.unwrap_or(base);
|
||||
let kind = s(e, "kind").unwrap_or("");
|
||||
let kind = pointer_kind(kind).ok_or_else(|| format!("unknown pointer kind `{kind}` (down|drag|up|move|doubleclick)"))?;
|
||||
let kind = pointer_kind(kind).ok_or_else(|| format!("unknown pointer kind `{kind}` (down|drag|up|move|doubleclick|tripleclick)"))?;
|
||||
PointerEvent::json_check(e)?;
|
||||
if s(e, "space") == Some("screen") {
|
||||
return Err("screen-space pointer events need the desktop app; use document coordinates".to_string());
|
||||
|
||||
@@ -16,6 +16,7 @@ mod gradient;
|
||||
mod limits;
|
||||
mod links;
|
||||
mod liquify;
|
||||
mod livepaint;
|
||||
mod pen;
|
||||
mod persp;
|
||||
mod place;
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
//! The Live Paint Bucket through MCP: `pointer_gesture` sends a triple-click as `tripleclick`.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::{Backend, Headless, call_tool};
|
||||
|
||||
fn ok(h: &mut Headless, name: &str, args: Value) -> Value {
|
||||
let r = call_tool(h, name, &args);
|
||||
assert!(!r.is_error, "{name} {args}: {r:?}");
|
||||
serde_json::from_str(r.content[0]["text"].as_str().unwrap()).unwrap_or(Value::Null)
|
||||
}
|
||||
|
||||
fn run(h: &mut Headless, command: &str, params: Value) -> Value {
|
||||
ok(h, "run_command", json!({"command": command, "params": params}))
|
||||
}
|
||||
|
||||
/// The fill of each face of Live Paint group `g`, left to right.
|
||||
fn fills(h: &mut Headless, g: &Value) -> Vec<Value> {
|
||||
let info = run(h, "livePaint.info", json!({"group": g}));
|
||||
let mut faces = info["faces"].as_array().unwrap().clone();
|
||||
faces.sort_by(|a, b| a["bounds"][0].as_f64().unwrap().total_cmp(&b["bounds"][0].as_f64().unwrap()));
|
||||
faces.iter().map(|f| f["fill"].clone()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_triple_click_fills_every_face_of_the_same_fill() {
|
||||
let mut h = Headless::new();
|
||||
h.call("engine.execute", json!({"command": "file.new", "params": {"width": 300, "height": 300}})).unwrap();
|
||||
let a = run(&mut h, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}))["id"].clone();
|
||||
let b = run(&mut h, "shape.rectangle", json!({"x": 100, "y": 0, "width": 50, "height": 50}))["id"].clone();
|
||||
let g = run(&mut h, "livePaint.make", json!({"ids": [a, b]}))["id"].clone();
|
||||
for x in [25, 125] {
|
||||
run(&mut h, "livePaint.fill", json!({"group": g, "point": [x, 25], "color": "#ff0000"}));
|
||||
}
|
||||
let red = fills(&mut h, &g);
|
||||
assert_eq!(red[0], red[1]);
|
||||
// With nothing selected, the current fill changes and the group keeps its faces' fills.
|
||||
run(&mut h, "select.none", json!({}));
|
||||
run(&mut h, "paint.setFill", json!({"color": "#00ff00"}));
|
||||
assert_eq!(fills(&mut h, &g), red);
|
||||
let ev = |kind: &str| json!({"kind": kind, "x": 25, "y": 25});
|
||||
let clicks = [ev("down"), ev("up"), ev("down"), ev("up"), ev("doubleclick"), ev("down"), ev("up")];
|
||||
ok(&mut h, "pointer_gesture", json!({"tool": "livePaintBucket", "events": clicks}));
|
||||
let after_two = fills(&mut h, &g);
|
||||
assert_eq!(after_two[1], red[1], "the face apart is left by the clicks and the double-click");
|
||||
assert_ne!(after_two[0], red[0]);
|
||||
ok(&mut h, "pointer_gesture", json!({"events": [ev("tripleclick")]}));
|
||||
assert_eq!(fills(&mut h, &g), [after_two[0].clone(), after_two[0].clone()], "both faces were red");
|
||||
}
|
||||
|
||||
/// With Space held (`mods.space`), the Live Paint Bucket's clicks, double-click and triple-click
|
||||
/// paint nothing.
|
||||
#[test]
|
||||
fn clicks_with_space_held_paint_nothing() {
|
||||
let mut h = Headless::new();
|
||||
h.call("engine.execute", json!({"command": "file.new", "params": {"width": 300, "height": 300}})).unwrap();
|
||||
let a = run(&mut h, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}))["id"].clone();
|
||||
let b = run(&mut h, "shape.rectangle", json!({"x": 100, "y": 0, "width": 50, "height": 50}))["id"].clone();
|
||||
let g = run(&mut h, "livePaint.make", json!({"ids": [a, b]}))["id"].clone();
|
||||
for x in [25, 125] {
|
||||
run(&mut h, "livePaint.fill", json!({"group": g, "point": [x, 25], "color": "#ff0000"}));
|
||||
}
|
||||
run(&mut h, "select.none", json!({}));
|
||||
run(&mut h, "paint.setFill", json!({"color": "#00ff00"}));
|
||||
let red = fills(&mut h, &g);
|
||||
let ev = |kind: &str| json!({"kind": kind, "x": 25, "y": 25});
|
||||
let clicks = [ev("down"), ev("up"), ev("down"), ev("up"), ev("doubleclick"), ev("down"), ev("up"), ev("tripleclick")];
|
||||
ok(&mut h, "pointer_gesture", json!({"tool": "livePaintBucket", "mods": {"space": true}, "events": clicks}));
|
||||
assert_eq!(fills(&mut h, &g), red);
|
||||
// Without Space, the same clicks paint.
|
||||
ok(&mut h, "pointer_gesture", json!({"events": [ev("down"), ev("up")]}));
|
||||
assert_ne!(fills(&mut h, &g)[0], red[0]);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user