mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-20 01:14:23 +01:00
Merge main into #8427
# Conflicts: # docs/gaps.md # docs/target-app-parity.md
This commit is contained in:
commit
d89bcb3e64
224 files changed
+26062
-1077
No files matched your search
Generated
+15
@@ -1044,6 +1044,20 @@ name = "craft-eps"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
|
||||
|
||||
[[package]]
|
||||
name = "craft-font-catalog"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3#23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3"
|
||||
dependencies = [
|
||||
"harfrust 0.13.3",
|
||||
"kurbo 0.13.1",
|
||||
"skrifa 0.47.0",
|
||||
"thiserror 2.0.21",
|
||||
"unicode-bidi",
|
||||
"unicode-segmentation",
|
||||
"windows-registry",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
@@ -7109,6 +7123,7 @@ dependencies = [
|
||||
name = "vectorcraft-text"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-font-catalog",
|
||||
"craft-proof",
|
||||
"harfrust 0.13.3",
|
||||
"icu_segmenter",
|
||||
|
||||
@@ -154,6 +154,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-11-01: Document Tools, a built-in add-on (Object › Plug-ins › Document Tools), starts with Save a Timestamped Copy: a copy of the document named `<name>_YYYY-MM-DD_HH-MM` (UTC; `-2`, `-3`… when that name is taken) goes next to it, or into a folder picked for a document never saved, written as File › Save a Copy writes it, so the document keeps its path, title and modified state. Off on the web, which has no clock. A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-15: Common Tangents in the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the straight lines that touch two selected convex closed paths (ellipses at any rotation and scale, or convex Bézier paths) without crossing either are added as open paths with the current stroke: external, internal or all, and the line joining the centers if asked; a path inside the other has none unless the two touch, and a message says why; a dialog with Preview, one undo step (`addon.pathtools.commonTangents`, #7845). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-18: Common Tangents also takes a point (a path of one anchor) and a convex closed path: the lines from the point that touch the path, and the line from the point to the path's center if asked; a point on the outline gets the one tangent there, and a point inside gets none, with a message (#7846). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-15: With Smart Guides and Snap to Tangent on, a Line Segment drag pressed on one convex curved path and dragged near another lands on a common tangent of the two: both ends move to where the line touches the paths, each labeled "tangent" (#7845). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-15: Smooth Bridge joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): two selected circles become one closed outline joined by two concave arcs that touch both circles, so every anchor is smooth; the arcs' radius is a percentage of the smaller circle's radius (1 to 1000%, 100% by default), and Keep Originals adds the outline above the circles instead of replacing them. A dialog with Preview, one undo step (`addon.pathtools.bridge`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged.
|
||||
|
||||
+65
-41
@@ -2106,20 +2106,39 @@ pub fn compound_part_at(n: &Node, p: Point, tol: f64) -> Option<NodeId> {
|
||||
/// the members of a group or layer with geometry effects of its own, are touched where the art those
|
||||
/// effects draw lies ([`set_drawn_art`]), as clicks hit them.
|
||||
pub fn marquee(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool) -> Vec<NodeId> {
|
||||
marquee_with(doc, r, scope, leaves, false, false)
|
||||
marquee_with(doc, r, scope, leaves, false, 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)
|
||||
/// the clicks of [`HitOptions::outline`] do. With `skip_guides` (Lock Guides is on or the guides
|
||||
/// are hidden, as [`HitOptions::skip_guides`]), the paths made into guides are not touched, at the
|
||||
/// top or inside a group, so a group is not taken for a guide in it (#8538).
|
||||
pub fn marquee_in_view(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, outline: bool, skip_guides: bool) -> Vec<NodeId> {
|
||||
marquee_with(doc, r, scope, leaves, false, outline, skip_guides)
|
||||
}
|
||||
|
||||
/// Candidates for whole-object enclosure by a loop bounded by `r`. Eligibility and group
|
||||
/// 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)
|
||||
pub fn enclosure_candidates(doc: &Document, r: Rect, scope: Option<NodeId>, outline: bool, skip_guides: bool) -> Vec<NodeId> {
|
||||
marquee_with(doc, r, scope, true, true, outline, skip_guides)
|
||||
}
|
||||
|
||||
/// What a marquee ([`marquee_with`]) takes, besides where it is: whether a compound path is
|
||||
/// touched by every path it paints (`whole_compounds`, for an enclosing loop's candidates), and
|
||||
/// whether the paths made into guides are left out (`skip_guides`: Lock Guides is on or the
|
||||
/// guides are hidden, [`HitOptions::skip_guides`] for the marquee).
|
||||
#[derive(Clone, Copy)]
|
||||
struct Rules {
|
||||
whole_compounds: bool,
|
||||
skip_guides: bool,
|
||||
}
|
||||
|
||||
impl Rules {
|
||||
/// Is `n` a path made into a guide that the marquee leaves out?
|
||||
fn skips(self, n: &Node) -> bool {
|
||||
self.skip_guides && matches!(n.kind, NodeKind::Path { guide: true, .. })
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `n` a layer whose Preview is off (its art is drawn and clicked in outline)?
|
||||
@@ -2127,8 +2146,17 @@ 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> {
|
||||
fn marquee_with(
|
||||
doc: &Document,
|
||||
r: Rect,
|
||||
scope: Option<NodeId>,
|
||||
leaves: bool,
|
||||
whole_compounds: bool,
|
||||
outline: bool,
|
||||
skip_guides: bool,
|
||||
) -> Vec<NodeId> {
|
||||
let _walk = ArtWalk::open();
|
||||
let rules = Rules { whole_compounds, skip_guides };
|
||||
let mut out = Vec::new();
|
||||
// The locks first: they copy the kept art boxes that `symbols` takes, and `symbols` keeps theirs.
|
||||
let locks = doc.locked_artboards_kept();
|
||||
@@ -2142,7 +2170,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
Some(c) => {
|
||||
// In an isolated clip group, its members by their own geometry, as clicks take
|
||||
// them ([`edits_inside`]).
|
||||
let drawn = if s.clips() { None } else { touched_in_art(s, &symbols, r, whole_compounds, outline || previews_off(s)) };
|
||||
let drawn = if s.clips() { None } else { touched_in_art(s, &symbols, r, rules, outline || previews_off(s)) };
|
||||
c.iter()
|
||||
.enumerate()
|
||||
.filter(|(i, c)| !c.is_ruler_guide() && !shaper_hides(s, *i, scope))
|
||||
@@ -2164,7 +2192,7 @@ 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, &symbols, r, outline, whole_compounds, None))
|
||||
.flat_map(|l| layer_objects(l, &symbols, r, outline, rules, None))
|
||||
.collect(),
|
||||
};
|
||||
/// The objects of layer `l`, each with the part of `r` that the clipping masks of `l` and of
|
||||
@@ -2173,17 +2201,10 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
/// shapes ([`mask_marquee`]). In a layer whose own geometry effects reshape its art, each object
|
||||
/// comes with the objects that art touches ([`touched_in_art`]), `drawn` when a layer around
|
||||
/// `l` has such effects.
|
||||
fn layer_objects<'a>(
|
||||
l: &'a Node,
|
||||
s: &SymbolBoxes,
|
||||
r: Rect,
|
||||
outline: bool,
|
||||
whole_compounds: bool,
|
||||
drawn: Option<Rc<HashSet<NodeId>>>,
|
||||
) -> Vec<Top<'a>> {
|
||||
fn layer_objects<'a>(l: &'a Node, s: &SymbolBoxes, r: Rect, outline: bool, rules: Rules, drawn: Option<Rc<HashSet<NodeId>>>) -> Vec<Top<'a>> {
|
||||
let mut out = vec![];
|
||||
let outline = outline || previews_off(l);
|
||||
let drawn = drawn.or_else(|| touched_in_art(l, s, r, whole_compounds, outline));
|
||||
let drawn = drawn.or_else(|| touched_in_art(l, s, r, rules, outline));
|
||||
let inner = marquee_in_parent(l, r, outline);
|
||||
for (i, c) in l.children().into_iter().flatten().enumerate() {
|
||||
if c.is_layer() {
|
||||
@@ -2192,7 +2213,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
&& !c.locked
|
||||
&& !c.is_template()
|
||||
{
|
||||
out.extend(layer_objects(c, s, inner, outline, whole_compounds, drawn.clone()));
|
||||
out.extend(layer_objects(c, s, inner, outline, rules, drawn.clone()));
|
||||
}
|
||||
} else if !c.is_ruler_guide() {
|
||||
if drawn.is_some() {
|
||||
@@ -2209,12 +2230,12 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
/// The ids of the objects of the art that group or layer `n` draws with its own geometry
|
||||
/// effects ([`drawn_art`]) that the marquee `r` touches, as [`collect_leaves`] collects them.
|
||||
/// `None` in outline and when it has no such effects.
|
||||
fn touched_in_art(n: &Node, s: &SymbolBoxes, r: Rect, whole_compounds: bool, outline: bool) -> Option<Rc<HashSet<NodeId>>> {
|
||||
fn touched_in_art(n: &Node, s: &SymbolBoxes, r: Rect, rules: Rules, outline: bool) -> Option<Rc<HashSet<NodeId>>> {
|
||||
let art = drawn_art(s, n, outline)?;
|
||||
let _off = DrawnOff::set();
|
||||
let mut ids = vec![];
|
||||
for a in art.iter().filter(|a| a.visible) {
|
||||
collect_leaves(a, s, r, None, whole_compounds, false, &mut ids);
|
||||
collect_leaves(a, s, r, None, rules, false, &mut ids);
|
||||
}
|
||||
Some(Rc::new(ids.into_iter().collect()))
|
||||
}
|
||||
@@ -2271,12 +2292,16 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
/// instance also where its fills and strokes paint outside it ([`painted_touches`]). 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 {
|
||||
fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, rules: Rules, outline: bool) -> bool {
|
||||
// Locked or hidden guides are not touched ([`Rules::skips`]).
|
||||
if rules.skips(n) {
|
||||
return false;
|
||||
}
|
||||
// A path or compound path whose geometry effects reshape it, or a group or layer whose own
|
||||
// geometry effects reshape its members, is touched where that art is drawn ([`drawn_art`]).
|
||||
if let Some(art) = drawn_art(s, n, outline || previews_off(n)) {
|
||||
let _off = DrawnOff::set();
|
||||
return art.iter().any(|a| a.visible && touches(a, s, r, None, whole_compounds, false));
|
||||
return art.iter().any(|a| a.visible && touches(a, s, r, None, rules, false));
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, .. } => vectorcraft_geom::hit::intersects_rect(path, r),
|
||||
@@ -2287,25 +2312,26 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
c.visible
|
||||
&& !shaper_hides(n, i, scope)
|
||||
&& if i == 0 && n.clips() {
|
||||
plain(true, || mask_marquee(n, r).is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline)))
|
||||
plain(true, || mask_marquee(n, r).is_some_and(|r| touches(c, s, r, scope, rules, outline)))
|
||||
|| clip_edge_touches(c, r, outline)
|
||||
} else {
|
||||
inner.is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline))
|
||||
inner.is_some_and(|r| touches(c, s, r, scope, rules, 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, .. } if rules.whole_compounds => {
|
||||
// Guide contours left out ([`Rules::skips`]) don't make the compound a candidate.
|
||||
children.iter().filter(|c| !rules.skips(c)).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, outline)),
|
||||
NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, whole_compounds, outline)),
|
||||
NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, rules, outline)),
|
||||
NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, rules, outline)),
|
||||
// A symbol instance is touched by its box, and outside it where the live geometry
|
||||
// effects of a clipping path in its art show the art, or where the geometry effects of
|
||||
// its active fill or stroke reshape the art ([`painted_touches`]). In the art of another
|
||||
// instance walked outside that instance's box, it is touched only by its own art
|
||||
// ([`ArtOnly`]) and those shapes.
|
||||
NodeKind::SymbolInstance { .. } => {
|
||||
!ArtOnly::on() && box_touches(n, s, r) || !outline && (instance_art_touches(n, s, r, whole_compounds) || painted_touches(n, s, r))
|
||||
!ArtOnly::on() && box_touches(n, s, r) || !outline && (instance_art_touches(n, s, r, rules) || painted_touches(n, s, r))
|
||||
}
|
||||
// An image is touched by its box, and outside it where its own fills and strokes paint.
|
||||
NodeKind::Image(_) => box_touches(n, s, r) || !outline && painted_touches(n, s, r),
|
||||
@@ -2334,7 +2360,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
/// ([`SymbolBoxes::art`]), or for any art while [`ArtOnly`] is on, and only when `r` meets the
|
||||
/// instance's reach ([`Node::reach_bounds_with`]): elsewhere the art lies within the instance's
|
||||
/// box. Not once the marquee has placed as many objects of symbol art as [`ArtWalk`] allows.
|
||||
fn instance_art_touches(n: &Node, s: &SymbolBoxes, r: Rect, whole_compounds: bool) -> bool {
|
||||
fn instance_art_touches(n: &Node, s: &SymbolBoxes, r: Rect, rules: Rules) -> bool {
|
||||
let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return false };
|
||||
let meets = |b: Rect| b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1;
|
||||
if s.art(symbol).is_none_or(|a| a.reshaped.is_none() && !ArtOnly::on()) || !n.reach_bounds_with(s).is_some_and(meets) {
|
||||
@@ -2351,15 +2377,15 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
#[cfg(test)]
|
||||
ARTS_WALKED.with(|c| c.set(c.get() + 1));
|
||||
let _art_only = ArtOnly::set();
|
||||
art.place(&art.art, None).is_some_and(|placed| placed.visible && touches(&placed, s, r, None, whole_compounds, false))
|
||||
art.place(&art.art, None).is_some_and(|placed| placed.visible && touches(&placed, s, r, None, rules, false))
|
||||
}
|
||||
fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, whole_compounds: bool, outline: bool, out: &mut Vec<NodeId>) {
|
||||
fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, rules: Rules, outline: bool, out: &mut Vec<NodeId>) {
|
||||
match &n.kind {
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => {
|
||||
let outline = outline || previews_off(n);
|
||||
// The members that the art its own geometry effects draw touches, and a group whose
|
||||
// own fills and strokes that art paints, as clicks hit it ([`member_chain`]).
|
||||
if let Some(drawn) = touched_in_art(n, s, r, whole_compounds, outline) {
|
||||
if let Some(drawn) = touched_in_art(n, s, r, rules, outline) {
|
||||
if drawn.contains(&n.id) && !n.is_layer() {
|
||||
out.push(n.id);
|
||||
}
|
||||
@@ -2374,18 +2400,18 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
if i == 0 && n.clips() {
|
||||
let before = out.len();
|
||||
if let Some(r) = mask_marquee(n, r) {
|
||||
plain(true, || collect_leaves(c, s, r, scope, whole_compounds, outline, out));
|
||||
plain(true, || collect_leaves(c, s, r, scope, rules, 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);
|
||||
collect_leaves(c, s, r, scope, rules, outline, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if touches(n, s, r, scope, whole_compounds, outline) {
|
||||
if touches(n, s, r, scope, rules, outline) {
|
||||
out.push(n.id);
|
||||
}
|
||||
}
|
||||
@@ -2420,14 +2446,12 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
if leaves {
|
||||
let before = out.len();
|
||||
if let Some(r) = r {
|
||||
collect_leaves(t, &symbols, r, scope, whole_compounds, outline, &mut out);
|
||||
collect_leaves(t, &symbols, r, scope, rules, 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))
|
||||
{
|
||||
} else if r.is_some_and(|r| touches(t, &symbols, r, scope, rules, outline)) || edge.is_some_and(|e| clip_edge_touches(t, e, outline)) {
|
||||
out.push(t.id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -164,8 +164,8 @@ fn clicks_in_a_clip_group_evaluate_its_clipping_paths_region_once_until_it_chang
|
||||
// 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]);
|
||||
assert_eq!(marquee_in_view(&d, edge, None, true, false, false), [mask_id]);
|
||||
assert_eq!(marquee_in_view(&d, edge, None, true, true, false), [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.
|
||||
@@ -489,8 +489,8 @@ fn a_marquee_touches_a_paths_shifted_art_not_its_source() {
|
||||
for leaves in [false, true] {
|
||||
assert_eq!(marquee(&d, drawn, None, leaves), [a], "where it is drawn");
|
||||
assert!(marquee(&d, own, None, leaves).is_empty(), "its own place");
|
||||
assert!(marquee_in_view(&d, drawn, None, leaves, true).is_empty(), "outline: no drawn art");
|
||||
assert_eq!(marquee_in_view(&d, own, None, leaves, true), [a], "outline: its own place");
|
||||
assert!(marquee_in_view(&d, drawn, None, leaves, true, false).is_empty(), "outline: no drawn art");
|
||||
assert_eq!(marquee_in_view(&d, own, None, leaves, true, false), [a], "outline: its own place");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -870,6 +870,68 @@ fn a_selected_guide_hidden_by_a_mask_counts_only_while_guides_can_be_clicked() {
|
||||
assert_eq!(selected_hidden_at(&d, hidden, HitOptions { skip_guides: true, ..opt }, &[guide_id]), None);
|
||||
}
|
||||
|
||||
/// #8538: while guides are locked or hidden (`skip_guides`), a marquee touches no guide path, at
|
||||
/// the top of a layer or in a group (the group is not taken for it), nor in a group in a group,
|
||||
/// with leaves or without. The group's other members still take it, and with the guides unlocked
|
||||
/// the guide does.
|
||||
#[test]
|
||||
fn a_marquee_skips_guide_paths_in_groups_while_guides_are_locked() {
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let guide = |d: &mut Document, r: Rect| {
|
||||
let mut n = Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::default_art());
|
||||
if let NodeKind::Path { guide, .. } = &mut n.kind {
|
||||
*guide = true;
|
||||
}
|
||||
n
|
||||
};
|
||||
let top = guide(&mut d, Rect::new(0.0, 0.0, 20.0, 20.0));
|
||||
let inner = guide(&mut d, Rect::new(100.0, 0.0, 120.0, 20.0));
|
||||
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(200.0, 0.0, 220.0, 20.0)), Appearance::default_art());
|
||||
let (top_id, inner_id, art_id) = (top.id, inner.id, art.id);
|
||||
let (outer_id, nested_id) = (d.alloc_id(), d.alloc_id());
|
||||
let nested = Node::group(nested_id, vec![Arc::new(inner)]);
|
||||
d.insert(Some(l), 0, top).unwrap();
|
||||
d.insert(Some(l), 1, Node::group(outer_id, vec![Arc::new(nested), Arc::new(art)])).unwrap();
|
||||
let (on_top, on_inner, on_art) = (Rect::new(-5.0, 5.0, 5.0, 10.0), Rect::new(95.0, 5.0, 105.0, 10.0), Rect::new(195.0, 5.0, 205.0, 10.0));
|
||||
for leaves in [false, true] {
|
||||
let m = |r: Rect, skip: bool| marquee_in_view(&d, r, None, leaves, false, skip);
|
||||
assert!(m(on_top, true).is_empty(), "a guide at the top, leaves {leaves}");
|
||||
assert!(m(on_inner, true).is_empty(), "a guide in a group in a group, leaves {leaves}");
|
||||
assert!(m(Rect::new(0.0, 0.0, 300.0, 200.0), true).iter().all(|id| ![top_id, inner_id].contains(id)), "all, leaves {leaves}");
|
||||
assert_eq!(m(on_art, true), [if leaves { art_id } else { outer_id }], "the group's art, leaves {leaves}");
|
||||
// Unlocked: the guides are touched.
|
||||
assert_eq!(m(on_top, false), [top_id], "unlocked, leaves {leaves}");
|
||||
assert_eq!(m(on_inner, false), [if leaves { inner_id } else { outer_id }], "unlocked, leaves {leaves}");
|
||||
}
|
||||
// An enclosing loop's candidates leave them out alike.
|
||||
assert!(enclosure_candidates(&d, on_inner, None, false, true).is_empty());
|
||||
assert_eq!(enclosure_candidates(&d, on_inner, None, false, false), [inner_id]);
|
||||
}
|
||||
|
||||
/// #8538: an enclosing loop's candidates leave out a compound path whose touched contours are all
|
||||
/// locked or hidden guides, as the marquee does.
|
||||
#[test]
|
||||
fn guide_contours_do_not_make_a_compound_an_enclosure_candidate() {
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let part = |d: &mut Document, r: Rect| {
|
||||
let mut n = Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::default_art());
|
||||
if let NodeKind::Path { guide, .. } = &mut n.kind {
|
||||
*guide = true;
|
||||
}
|
||||
Arc::new(n)
|
||||
};
|
||||
let (a, b) = (part(&mut d, Rect::new(10.0, 10.0, 50.0, 50.0)), part(&mut d, Rect::new(20.0, 20.0, 40.0, 40.0)));
|
||||
let id = d.alloc_id();
|
||||
let mut compound = Node::group(id, vec![]);
|
||||
compound.kind = NodeKind::Compound { children: vec![a, b], rule: Default::default() };
|
||||
d.insert(Some(l), 0, compound).unwrap();
|
||||
let r = Rect::new(0.0, 0.0, 60.0, 60.0);
|
||||
assert!(enclosure_candidates(&d, r, None, false, true).is_empty(), "locked or hidden");
|
||||
assert_eq!(enclosure_candidates(&d, r, None, false, false), [id], "shown and unlocked");
|
||||
}
|
||||
|
||||
/// A selected path in a Shaper group's original shapes, where an outer mask hides it, counts only
|
||||
/// while those shapes can be clicked (Construction mode, with them isolated), however deep it
|
||||
/// lies in them.
|
||||
@@ -2674,7 +2736,7 @@ fn a_symbol_instance_is_hit_where_a_moved_clipping_path_in_its_art_shows_the_art
|
||||
assert_eq!(marquee(&d, edge, None, false), [g], "layer {layer}");
|
||||
assert_eq!(marquee(&d, edge, None, true), [inst], "layer {layer}");
|
||||
assert!(marquee(&d, past, None, false).is_empty());
|
||||
assert!(marquee_in_view(&d, edge, None, false, true).is_empty(), "Outline view");
|
||||
assert!(marquee_in_view(&d, edge, None, false, true, false).is_empty(), "Outline view");
|
||||
}
|
||||
// Preview off for the layer the instance is on.
|
||||
let (mut d, _, _) = build("test.move", Affine::IDENTITY, false, true, false);
|
||||
|
||||
@@ -90,6 +90,42 @@ impl Node {
|
||||
matches!(self.kind, NodeKind::RulerGuide { .. } | NodeKind::Path { guide: true, .. })
|
||||
}
|
||||
|
||||
/// This object without the paths made into guides among the members of its groups, layers,
|
||||
/// Intertwine groups and compound paths, at any depth, for measuring the art around them while
|
||||
/// Lock Guides or Hide Guides leaves them out (#8538). The clipping path of a clip group or
|
||||
/// layer and the original shapes of a Shaper group stay, guides or not, so the object keeps
|
||||
/// its structure. `None` when it holds no such guide.
|
||||
pub fn without_guides(&self) -> Option<Node> {
|
||||
let (NodeKind::Layer { children, .. }
|
||||
| NodeKind::Group { children, .. }
|
||||
| NodeKind::Intertwine { children }
|
||||
| NodeKind::Compound { children, .. }) = &self.kind
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let keep = usize::from(self.clips() || self.extras().shaper.is_some());
|
||||
let mut changed = false;
|
||||
let mut out = Vec::with_capacity(children.len());
|
||||
for (i, c) in children.iter().enumerate() {
|
||||
if i >= keep && matches!(c.kind, NodeKind::Path { guide: true, .. }) {
|
||||
changed = true;
|
||||
} else if let Some(stripped) = c.without_guides() {
|
||||
changed = true;
|
||||
out.push(Arc::new(stripped));
|
||||
} else {
|
||||
out.push(c.clone());
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
return None;
|
||||
}
|
||||
let mut n = self.clone();
|
||||
if let Some(c) = n.children_mut() {
|
||||
*c = out;
|
||||
}
|
||||
Some(n)
|
||||
}
|
||||
|
||||
/// A template layer (Layer Options → Template).
|
||||
pub fn is_template(&self) -> bool {
|
||||
matches!(self.kind, NodeKind::Layer { template: true, .. })
|
||||
|
||||
@@ -312,6 +312,36 @@ impl Carry {
|
||||
}
|
||||
}
|
||||
|
||||
/// Undo the actual maps of already placed gradients. Failure only changes this temporary
|
||||
/// appearance; callers retain the stored row unchanged when a map cannot be inverted.
|
||||
pub(crate) fn unapply_placed(&self, ap: &mut Appearance) -> Option<()> {
|
||||
for step in self.0.iter().rev() {
|
||||
for item in &mut ap.items {
|
||||
if !matches!(item.paint(), vectorcraft_doc::color::Paint::Gradient(_)) {
|
||||
continue;
|
||||
}
|
||||
let map = match *step {
|
||||
CarryStep::Affine { m, .. } => m,
|
||||
CarryStep::Boxes { from, to } => match item {
|
||||
AppearanceItem::Fill(_) => crate::reshape::box_map(from, to),
|
||||
AppearanceItem::Stroke(s) => crate::reshape::box_map(s.paint_bounds(from), s.paint_bounds(to)),
|
||||
},
|
||||
};
|
||||
if vectorcraft_doc::node::flattens(map) {
|
||||
return None;
|
||||
}
|
||||
let inverse = map.inverse();
|
||||
if !inverse.is_finite() {
|
||||
return None;
|
||||
}
|
||||
if let vectorcraft_doc::color::Paint::Gradient(g) = item.paint_mut() {
|
||||
g.transform(inverse);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
pub(crate) fn push(&mut self, more: Carry) {
|
||||
self.0.extend(more.0);
|
||||
self.1.extend(more.1);
|
||||
|
||||
+79
-25
@@ -846,23 +846,19 @@ fn take_sublayer_guides(n: &mut Node, out: &mut Vec<Arc<Node>>, is_guide: &impl
|
||||
take_held_guides(n, held, out, false, false);
|
||||
}
|
||||
|
||||
/// `n`, a group or layer, as plain art: its Pathfinder effects evaluated, its geometry effects
|
||||
/// reshaping all its members as one piece (the whole art's bounds as their reference box) after
|
||||
/// the members' own geometry and Pathfinder effects ([`members_as_drawn`]), and its
|
||||
/// own fills and strokes turned into art painting the members' geometry ([`member_shapes`]) below
|
||||
/// the members (after a clipping path) or above them, as its contents slot says. Its
|
||||
/// transparency, opacity mask and raster effects stay. `None` when it has none of these. Live
|
||||
/// objects among the members are evaluated with the symbols of `doc` (see [`member_shapes`]), and
|
||||
/// a Pathfinder operation or compound shape takes the symbol instances among its members as their
|
||||
/// symbols' art from `doc`. A Transform effect that makes copies with raster effects listed before
|
||||
/// it gives each copy those raster effects ([`copied_container`]).
|
||||
pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
struct PreparedContainer {
|
||||
m: Node,
|
||||
guides: Vec<Arc<Node>>,
|
||||
paint: bool,
|
||||
carry: crate::Carry,
|
||||
}
|
||||
|
||||
/// The existing container pass up to its own rows becoming art. Keep its carried appearance for
|
||||
/// rendering, and retain the same Carry for freezing only missing stored placements separately.
|
||||
fn prepare_container(doc: Option<&Document>, n: &Node) -> Option<PreparedContainer> {
|
||||
if !is_container(n) {
|
||||
return None;
|
||||
}
|
||||
if let Some(t) = crate::reshape::copied_container_raster_at(n) {
|
||||
return Some(copied_container(doc, n, t));
|
||||
}
|
||||
let pathfinder = has_pathfinder(n);
|
||||
let fx = crate::reshape::geometry_effects(n);
|
||||
let paint = has_own_paint(n);
|
||||
@@ -870,6 +866,7 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
return None;
|
||||
}
|
||||
let mut m = n.clone();
|
||||
let mut carry = crate::Carry::default();
|
||||
// Its ruler guides take no part: they go back above the evaluated art at the end. With effects
|
||||
// that replace or copy the art, so do its guides among the art and those in its sublayers and
|
||||
// groups, which would otherwise go with that art: they stay on `n`, in order, hidden and
|
||||
@@ -896,7 +893,7 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
let _later = crate::raster::LaterGroups::enter(&n.appearance.effects);
|
||||
members_as_drawn(doc, &mut m);
|
||||
}
|
||||
let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, &n.appearance.effects, doc);
|
||||
carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, &n.appearance.effects, doc);
|
||||
// The group's own fills and strokes paint the members as a whole: their gradients follow
|
||||
// the effects as the members' do.
|
||||
if paint && carry.moves(&m.appearance) {
|
||||
@@ -905,6 +902,27 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
}
|
||||
m.appearance.effects = crate::raster::without_geometry(&m.appearance.effects);
|
||||
m.appearance.effects.retain(|e| !is_pathfinder(&e.id));
|
||||
Some(PreparedContainer { m, guides, paint, carry })
|
||||
}
|
||||
|
||||
/// `n`, a group or layer, as plain art: its Pathfinder effects evaluated, its geometry effects
|
||||
/// reshaping all its members as one piece (the whole art's bounds as their reference box) after
|
||||
/// the members' own geometry and Pathfinder effects ([`members_as_drawn`]), and its
|
||||
/// own fills and strokes turned into art painting the members' geometry ([`member_shapes`]) below
|
||||
/// the members (after a clipping path) or above them, as its contents slot says. Its
|
||||
/// transparency, opacity mask and raster effects stay. `None` when it has none of these. Live
|
||||
/// objects among the members are evaluated with the symbols of `doc` (see [`member_shapes`]), and
|
||||
/// a Pathfinder operation or compound shape takes the symbol instances among its members as their
|
||||
/// symbols' art from `doc`. A Transform effect that makes copies with raster effects listed before
|
||||
/// it gives each copy those raster effects ([`copied_container`]).
|
||||
pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
if !is_container(n) {
|
||||
return None;
|
||||
}
|
||||
if let Some(t) = crate::reshape::copied_container_raster_at(n) {
|
||||
return Some(copied_container(doc, n, t));
|
||||
}
|
||||
let PreparedContainer { mut m, guides, paint, .. } = prepare_container(doc, n)?;
|
||||
if paint {
|
||||
// A clip group whose clipping type paints strokes is now a group of a clip group and those
|
||||
// strokes ([`crate::reshape::paint_type_clip`]): its own fills and strokes paint inside
|
||||
@@ -931,16 +949,8 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
Some(m)
|
||||
}
|
||||
|
||||
/// `n`, a group or layer whose own effects split at `t` ([`crate::reshape::copied_container_raster_at`]),
|
||||
/// as plain art: the effects before the Transform effect at `t` evaluated on its members as one
|
||||
/// piece ([`evaluate_container`]), with the raster effects among them, and that piece copied by the
|
||||
/// Transform effect, each copy a group of its own carrying those raster effects moved, turned,
|
||||
/// reflected and scaled with it ([`crate::reshape::copied_container_art`]). The art keeps the kind,
|
||||
/// transparency and opacity mask of `n` and the raster effects from `t` on, which paint once around
|
||||
/// all the copies; a clip group's or clipping layer's copies each clip, and the art itself does not.
|
||||
/// Its ruler guides, those in its sublayers and groups included, go once above the copies, hidden
|
||||
/// and locked as their containers were.
|
||||
fn copied_container(doc: Option<&Document>, n: &Node, t: usize) -> Node {
|
||||
/// The exact pre-copy source shared by rendering and stored gradient placement.
|
||||
fn copied_container_source(doc: Option<&Document>, n: &Node, t: usize) -> (Node, Vec<Arc<Node>>, Node) {
|
||||
let mut m = n.clone();
|
||||
let mut guides = vec![];
|
||||
take_sublayer_guides(&mut m, &mut guides, &Node::is_ruler_guide);
|
||||
@@ -955,6 +965,20 @@ fn copied_container(doc: Option<&Document>, n: &Node, t: usize) -> Node {
|
||||
let _later = crate::raster::LaterGroups::enter(&n.appearance.effects);
|
||||
members_as_drawn(doc, &mut source);
|
||||
}
|
||||
(m, guides, source)
|
||||
}
|
||||
|
||||
/// `n`, a group or layer whose own effects split at `t` ([`crate::reshape::copied_container_raster_at`]),
|
||||
/// as plain art: the effects before the Transform effect at `t` evaluated on its members as one
|
||||
/// piece ([`evaluate_container`]), with the raster effects among them, and that piece copied by the
|
||||
/// Transform effect, each copy a group of its own carrying those raster effects moved, turned,
|
||||
/// reflected and scaled with it ([`crate::reshape::copied_container_art`]). The art keeps the kind,
|
||||
/// transparency and opacity mask of `n` and the raster effects from `t` on, which paint once around
|
||||
/// all the copies; a clip group's or clipping layer's copies each clip, and the art itself does not.
|
||||
/// Its ruler guides, those in its sublayers and groups included, go once above the copies, hidden
|
||||
/// and locked as their containers were.
|
||||
fn copied_container(doc: Option<&Document>, n: &Node, t: usize) -> Node {
|
||||
let (mut m, guides, source) = copied_container_source(doc, n, t);
|
||||
let mut piece = evaluate_container(doc, &source).unwrap_or_else(|| {
|
||||
let mut p = source.clone();
|
||||
p.appearance.effects = crate::raster::without_geometry(&p.appearance.effects);
|
||||
@@ -988,6 +1012,36 @@ fn copied_container(doc: Option<&Document>, n: &Node, t: usize) -> Node {
|
||||
m
|
||||
}
|
||||
|
||||
/// Freeze representable fitted own paints to the box the container pass gives them, retaining
|
||||
/// every live effect and already explicit placement. Hidden-only containers the pass does not
|
||||
/// evaluate stay unchanged; this does not add a different fallback to `evaluate_container`.
|
||||
pub fn pinned_container_appearance(doc: &Document, n: &Node) -> Option<Appearance> {
|
||||
if !n.appearance.has_unplaced_gradient() {
|
||||
return None;
|
||||
}
|
||||
if let Some(t) = crate::reshape::copied_container_raster_at(n) {
|
||||
let (_, _, source) = copied_container_source(Some(doc), n, t);
|
||||
let pinned = pinned_container_appearance(doc, &source)?;
|
||||
let mut out = (*n.appearance).clone();
|
||||
out.items = pinned.items;
|
||||
return Some(out);
|
||||
}
|
||||
let PreparedContainer { m, carry, .. } = prepare_container(Some(doc), n)?;
|
||||
let bounds = m.geometric_bounds()?;
|
||||
let mut out = (*n.appearance).clone();
|
||||
let mut changed = false;
|
||||
for (item, original) in out.items.iter_mut().zip(&n.appearance.items) {
|
||||
if paints(original)
|
||||
&& matches!(original.paint(), Paint::Gradient(g) if !g.is_placed())
|
||||
&& let Some(pinned) = crate::pinned_gradient_item(original, bounds, &[&carry])
|
||||
{
|
||||
*item = pinned;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
changed.then_some(out)
|
||||
}
|
||||
|
||||
/// Replace each visible member of `n` with geometry or Pathfinder effects of its own, at every
|
||||
/// depth of its groups and layers, by the art it draws ([`evaluate_container`],
|
||||
/// [`crate::reshape::own_effects_art`]), so the geometry effects of `n` reshape what its members
|
||||
|
||||
@@ -45,6 +45,7 @@ mod lighting_presets;
|
||||
mod live;
|
||||
mod marks;
|
||||
pub mod pixel;
|
||||
mod placement;
|
||||
pub mod preview;
|
||||
mod raster;
|
||||
mod reshape;
|
||||
@@ -75,12 +76,13 @@ pub use bake::{
|
||||
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,
|
||||
is_pathfinder, member_leaves, member_shapes, paints, pathfinder_children, pinned_container_appearance, shape_art,
|
||||
};
|
||||
pub use lighting_presets::{LIGHTING_PRESETS, LightingPreset, lighting_preset_params, matching_lighting_preset};
|
||||
pub use live::{expand_live, expand_live_deep, expanded_live_group, outline_object, text_outliner};
|
||||
pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks};
|
||||
pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace};
|
||||
pub use placement::pinned_gradient_item;
|
||||
pub use raster::{
|
||||
RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, rasterize_stage, stage_maps, staged_effects,
|
||||
without_geometry,
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
//! Conservative stored placements for gradients fitted by the existing effects passes.
|
||||
|
||||
use vectorcraft_doc::color::{GradientKind, GradientPaint, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem};
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
use crate::Carry;
|
||||
|
||||
/// Freeze one fitted gradient at the evaluated row's geometric bounds, before its live effects.
|
||||
/// `carries` are the actual object and item passes, in rendering order. Only missing placement
|
||||
/// fields are returned; explicit coordinates and the row's other data stay unchanged. A map or
|
||||
/// model that cannot reproduce the original resolved row returns `None`, leaving it fitted.
|
||||
pub fn pinned_gradient_item(item: &AppearanceItem, bounds: Rect, carries: &[&Carry]) -> Option<AppearanceItem> {
|
||||
if gradient(item)?.is_placed() {
|
||||
return Some(item.clone());
|
||||
}
|
||||
if ![bounds.x0, bounds.y0, bounds.x1, bounds.y1].iter().all(|v| v.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let resolved = resolve(item, bounds, carries);
|
||||
if !finite_placement(resolved.items.first()?) {
|
||||
return None;
|
||||
}
|
||||
let mut stored = resolved.clone();
|
||||
for carry in carries.iter().rev() {
|
||||
carry.unapply_placed(&mut stored)?;
|
||||
}
|
||||
if !finite_placement(stored.items.first()?) {
|
||||
return None;
|
||||
}
|
||||
let candidate = missing_placement(item, stored.items.first()?)?;
|
||||
let replayed = resolve(&candidate, bounds, carries);
|
||||
(finite_placement(replayed.items.first()?) && replayed.approx_eq(&resolved)).then_some(candidate)
|
||||
}
|
||||
|
||||
fn gradient(item: &AppearanceItem) -> Option<&GradientPaint> {
|
||||
match item.paint() {
|
||||
Paint::Gradient(g) => Some(g),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve(item: &AppearanceItem, bounds: Rect, carries: &[&Carry]) -> Appearance {
|
||||
let mut ap = Appearance { items: vec![item.clone()], ..Default::default() };
|
||||
for carry in carries {
|
||||
carry.apply(&mut ap);
|
||||
}
|
||||
ap.pin_gradients(bounds);
|
||||
ap
|
||||
}
|
||||
|
||||
fn missing_placement(item: &AppearanceItem, placed: &AppearanceItem) -> Option<AppearanceItem> {
|
||||
let original = gradient(item)?;
|
||||
let placed = gradient(placed)?;
|
||||
let mut out = item.clone();
|
||||
let Paint::Gradient(g) = out.paint_mut() else { return None };
|
||||
if original.geom.is_none() {
|
||||
g.geom = placed.geom;
|
||||
}
|
||||
if original.gradient.kind == GradientKind::Freeform && !original.has_freeform_points() {
|
||||
let freeform = placed.freeform.as_ref()?;
|
||||
match &mut g.freeform {
|
||||
Some(f) => f.points.clone_from(&freeform.points),
|
||||
None => g.freeform = Some(freeform.clone()),
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
fn finite_placement(item: &AppearanceItem) -> bool {
|
||||
let Some(g) = gradient(item) else { return false };
|
||||
g.geom.is_none_or(|v| v.start.is_finite() && v.end.is_finite() && v.aspect.is_finite() && v.focal.is_none_or(|p| p.is_finite()))
|
||||
&& g.freeform.as_ref().is_none_or(|f| f.points.iter().all(|p| p.at.is_finite()))
|
||||
}
|
||||
@@ -3505,7 +3505,7 @@ pub(crate) fn follow_boxes(ap: &mut Appearance, from: Rect, to: Rect) {
|
||||
|
||||
/// The map that takes box `from` onto box `to` along each axis (along an axis `from` has no extent
|
||||
/// on, a move from its center to `to`'s).
|
||||
fn box_map(from: Rect, to: Rect) -> vectorcraft_geom::Affine {
|
||||
pub(crate) fn box_map(from: Rect, to: Rect) -> vectorcraft_geom::Affine {
|
||||
let axis = |a0: f64, a1: f64, b0: f64, b1: f64| {
|
||||
if (a1 - a0).abs() > 1e-12 {
|
||||
let s = (b1 - b0) / (a1 - a0);
|
||||
|
||||
@@ -99,12 +99,13 @@ pub(crate) mod symboledit;
|
||||
pub mod symbollib;
|
||||
pub(crate) mod tabs;
|
||||
mod textedit;
|
||||
mod xmlattrs;
|
||||
|
||||
pub use textedit::effective_kerning;
|
||||
mod retype;
|
||||
pub mod textstyles;
|
||||
pub(crate) mod textwrap;
|
||||
pub(crate) mod threads;
|
||||
pub mod toast;
|
||||
pub(crate) mod typecmd;
|
||||
mod typemenu;
|
||||
mod variablecmds;
|
||||
@@ -322,6 +323,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(pathops::specs());
|
||||
v.extend(compoundshape::specs());
|
||||
v.extend(typecmd::specs());
|
||||
v.extend(retype::specs());
|
||||
v.extend(menucmds::specs());
|
||||
v.extend(live::specs());
|
||||
v.extend(colorcmds::specs());
|
||||
@@ -334,6 +336,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(compositefonts::specs());
|
||||
v.extend(fontfiles::specs());
|
||||
v.extend(help::specs());
|
||||
v.extend(toast::specs());
|
||||
v.extend(threads::specs());
|
||||
v.extend(textwrap::specs());
|
||||
v.extend(graph::specs());
|
||||
@@ -876,6 +879,9 @@ pub use xform::{AppearanceAttrs, EyedropperAttrs, EyedropperOptions, FillAttrs,
|
||||
/// The shape modes of the selected compound-shape members (the Pathfinder panel lights theirs).
|
||||
pub use compoundshape::selected_member_modes;
|
||||
|
||||
/// Make Compound Shape's warning when a member is an open path that encloses no area.
|
||||
pub use compoundshape::OPEN_PATHS_ADD_NO_AREA;
|
||||
|
||||
/// Pathfinder Options (`Prefs::pathfinder`).
|
||||
pub use pathops::{PATHFINDER_PRECISION_RANGE, PathfinderOptions};
|
||||
|
||||
@@ -903,6 +909,8 @@ pub(crate) use buildcmds::TracePresetChanges;
|
||||
/// The shapes a group selected alone gives the Pathfinder panel.
|
||||
pub use pathops::shape_count;
|
||||
|
||||
/// The tile counts Create Object Mosaic would use (the dialog's Use Ratio button sets them).
|
||||
pub use menucmds::mosaic_counts;
|
||||
/// The Shape Mode commands' warning when a selected open path encloses no area.
|
||||
pub use pathops::SHAPE_MODE_OPEN_PATH_NO_AREA;
|
||||
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! Common Tangents (`addon.pathtools.commonTangents`): the straight lines that touch two selected
|
||||
//! convex closed paths (ellipses at any rotation and scale, and convex Bézier paths) without
|
||||
//! crossing into either, added as separate open paths, with the line joining their centers if
|
||||
//! asked. The geometry is `vectorcraft_pathops::addons::pathtools::common_tangents`.
|
||||
//! asked. One of the two may be a point (a path of one anchor) instead: the lines then run from it
|
||||
//! to where they touch the path. The geometry is `vectorcraft_pathops::addons::pathtools::common_tangents`.
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -30,19 +31,24 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"Common Tangents",
|
||||
["Object", "Plug-ins", "Path Precision Tools"],
|
||||
None,
|
||||
"{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), ids?: [id, id] (default: the selection)} add the common tangent lines of two convex closed paths as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is less than a billionth of the larger of their sizes and the distance between their centers. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}",
|
||||
"{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), ids?: [id, id] (default: the selection)} add the common tangent lines of two convex closed paths as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is less than a billionth of the larger of their sizes and the distance between their centers. One of the two may be a point (a path of one anchor): the lines then run from the point to where they touch the path, two when the point lies outside it (one that lies along a straight side covers the whole side), one when the point lies on its outline, that is, less than the touching tolerance from it, with the point's distance from the path's center in place of the distance between centers (centered on the point and as long as the path is wide along it, or the whole straight side the point lies on), none when it lies inside; every `tangents` value gives the same lines, counted as internal when `tangents` is \"internal\" and as external otherwise, and the centerline runs from the point to the path's center; two points are refused. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}",
|
||||
has_selection,
|
||||
common_tangents
|
||||
)]
|
||||
}
|
||||
|
||||
/// The outline of path `id` as the geometry takes it: an exact ellipse for a whole live ellipse,
|
||||
/// else the path's one closed convex subpath.
|
||||
/// The outline of path `id` as the geometry takes it: a point for a path of one anchor, an exact
|
||||
/// ellipse for a whole live ellipse, else the path's one closed convex subpath.
|
||||
fn outline_of(d: &Document, id: NodeId) -> Result<pt::Outline> {
|
||||
const C: &str = COMMON_TANGENTS;
|
||||
let n = d.node(id).ok_or(EngineError::NoNode(id))?;
|
||||
let NodeKind::Path { path, live, .. } = &n.kind else { return Err(bad(C, "select two closed paths")) };
|
||||
let [sp] = path.subpaths.as_slice() else { return Err(bad(C, "select two closed paths")) };
|
||||
if sp.anchors.len() == 1
|
||||
&& let Some(only) = sp.anchors.first()
|
||||
{
|
||||
return pt::Outline::point(only.p).map_err(refusal);
|
||||
}
|
||||
if let Some(LiveShape::Ellipse { w, h, pie, xf }) = live.as_deref() {
|
||||
let span = (pie.1 - pie.0).rem_euclid(360.0);
|
||||
if span < 1e-9 || 360.0 - span < 1e-9 {
|
||||
@@ -74,17 +80,36 @@ fn common_tangents(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ordered = d.paint_order(roots.iter().copied());
|
||||
let [first, second] = ordered.as_slice() else { return Err(bad(C, "select two closed paths")) };
|
||||
let (a, b) = (outline_of(d, *first)?, outline_of(d, *second)?);
|
||||
if a.is_point() && b.is_point() {
|
||||
return Err(bad(C, "select two closed paths"));
|
||||
}
|
||||
// A point goes first, so that each line runs from it to where it touches the path.
|
||||
let point = a.is_point() || b.is_point();
|
||||
let (a, b) = if b.is_point() { (b, a) } else { (a, b) };
|
||||
let all = pt::common_tangents(&a, &b).map_err(|_| bad(C, "the two paths have the same outline"))?;
|
||||
let external = all.iter().filter(|t| t.kind == pt::TangentKind::External).count();
|
||||
let keep = |t: &&pt::Tangent| match kinds {
|
||||
"external" => t.kind == pt::TangentKind::External,
|
||||
"internal" => t.kind == pt::TangentKind::Internal,
|
||||
_ => true,
|
||||
// A point's external and internal tangents are the same lines: every kind keeps them.
|
||||
let keep = |t: &&pt::Tangent| {
|
||||
point
|
||||
|| match kinds {
|
||||
"external" => t.kind == pt::TangentKind::External,
|
||||
"internal" => t.kind == pt::TangentKind::Internal,
|
||||
_ => true,
|
||||
}
|
||||
};
|
||||
let kept: Vec<&pt::Tangent> = all.iter().filter(keep).collect();
|
||||
let count = |kind: pt::TangentKind| kept.iter().filter(|t| t.kind == kind).count();
|
||||
let (external_kept, internal_kept) = (count(pt::TangentKind::External), count(pt::TangentKind::Internal));
|
||||
let (external_kept, internal_kept) = match (point, kinds) {
|
||||
(true, "internal") => (0, kept.len()),
|
||||
(true, _) => (kept.len(), 0),
|
||||
_ => (count(pt::TangentKind::External), count(pt::TangentKind::Internal)),
|
||||
};
|
||||
let lines: Vec<(Point, Point)> = kept.iter().map(|t| (t.from, t.to)).collect();
|
||||
if lines.is_empty() && point {
|
||||
// Written as `EngineError::Other` so that the i18n message scan finds it.
|
||||
let warning = EngineError::Other("The point lies inside the path, so it has no tangents".into());
|
||||
return Ok(json!({ "ids": [], "external": 0, "internal": 0, "centerline": null, "warning": warning.to_string() }));
|
||||
}
|
||||
if lines.is_empty() {
|
||||
// Written as `EngineError::Other` so that the i18n message scan finds them. Exactly one
|
||||
// external tangent means one path lies inside the other and touches it there; paths that
|
||||
|
||||
@@ -248,6 +248,84 @@ fn nested_and_overlapping_paths_change_nothing_and_say_why() {
|
||||
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(1), Some(0)), "{r}");
|
||||
}
|
||||
|
||||
fn point(s: &mut Session, x: f64, y: f64) -> NodeId {
|
||||
id_of(&s.execute("path.create", &json!({"anchors": [{"x": x, "y": y}]})).unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_point_and_an_ellipse_get_the_two_lines_from_the_point_and_the_centerline() {
|
||||
let mut s = session();
|
||||
// The point is drawn after the oval, so it is the upper object; the lines still start at it.
|
||||
let oval = id_of(&s.execute("shape.ellipse", &json!({"x": 260, "y": 170, "width": 80, "height": 60})).unwrap());
|
||||
let dot = point(&mut s, 100.0, 200.0);
|
||||
select(&mut s, &[oval, dot]);
|
||||
let before = steps(&s);
|
||||
let r = s.execute(C, &json!({"centerline": true})).unwrap();
|
||||
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(0)), "{r}");
|
||||
assert_eq!(steps(&s), before + 1);
|
||||
let found = lines(&s, &r);
|
||||
assert_eq!(found.len(), 3, "two tangents and the centerline");
|
||||
let (p, c) = (Point::new(100.0, 200.0), Point::new(300.0, 200.0));
|
||||
// From (-200, 0) to an ellipse with semi-axes 40 and 30 about the origin: the touching points
|
||||
// are x = -a²/200 = -8, y = ±b √(1 - x²/a²).
|
||||
let y = 30.0 * (1.0f64 - (8.0f64 / 40.0).powi(2)).sqrt();
|
||||
for sy in [1.0, -1.0] {
|
||||
let touch = c + Vec2::new(-8.0, sy * y);
|
||||
assert!(found[..2].iter().any(|(a, b)| near(*a, p) && near(*b, touch)), "{touch:?} in {found:?}");
|
||||
}
|
||||
assert_eq!(r["centerline"], r["ids"][2]);
|
||||
assert!(near(found[2].0, p) && near(found[2].1, c), "{:?}", found[2]);
|
||||
// Every `tangents` value gives the same two lines.
|
||||
for (kind, external, internal) in [("external", 2, 0), ("internal", 0, 2)] {
|
||||
let r = s.execute(C, &json!({"ids": [oval.0, dot.0], "tangents": kind})).unwrap();
|
||||
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(external), Some(internal)), "{kind}: {r}");
|
||||
assert_eq!(lines(&s, &r).len(), 2, "{kind}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_point_below_the_path_still_starts_the_lines() {
|
||||
let mut s = session();
|
||||
// The point is drawn first, so it is the lower object and needs no swap.
|
||||
let dot = point(&mut s, 100.0, 200.0);
|
||||
let round = circle(&mut s, 300.0, 200.0, 50.0);
|
||||
let r = s.execute(C, &json!({"ids": [round.0, dot.0], "centerline": true})).unwrap();
|
||||
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(0)), "{r}");
|
||||
let found = lines(&s, &r);
|
||||
assert_eq!(found.len(), 3, "two tangents and the centerline");
|
||||
let p = Point::new(100.0, 200.0);
|
||||
assert!(found.iter().all(|(a, _)| near(*a, p)), "every line starts at the point: {found:?}");
|
||||
// From 200 away to a circle of radius 50, each tangent is √(200² - 50²) long.
|
||||
let length = (200.0f64 * 200.0 - 50.0 * 50.0).sqrt();
|
||||
assert!(found[..2].iter().all(|(a, b)| (a.distance(*b) - length).abs() < 1e-6), "{found:?}");
|
||||
assert!(near(found[2].1, Point::new(300.0, 200.0)), "{:?}", found[2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_point_on_or_inside_a_path_and_two_points() {
|
||||
let mut s = session();
|
||||
let round = circle(&mut s, 200.0, 200.0, 50.0);
|
||||
// On the circle: one line, centered on the point and as long as the circle is wide.
|
||||
let on = point(&mut s, 250.0, 200.0);
|
||||
let r = s.execute(C, &json!({"ids": [round.0, on.0]})).unwrap();
|
||||
assert_eq!(r["external"].as_u64(), Some(1), "{r}");
|
||||
let (p, q) = lines(&s, &r)[0];
|
||||
assert!((p.x - 250.0).abs() < 1e-5 && (q.x - 250.0).abs() < 1e-5 && (p.distance(q) - 100.0).abs() < 1e-5, "{p:?} {q:?}");
|
||||
// Inside: nothing changes, and the warning says why.
|
||||
let inside = point(&mut s, 210.0, 190.0);
|
||||
let before = (steps(&s), s.doc().unwrap().doc.node_count());
|
||||
let r = s.execute(C, &json!({"ids": [round.0, inside.0], "centerline": true})).unwrap();
|
||||
assert_eq!(r["ids"], json!([]));
|
||||
assert!(r["warning"].as_str().unwrap().contains("point lies inside the path"), "{r}");
|
||||
assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before, "nothing changes");
|
||||
// Two points, or a point and an open path, are refused.
|
||||
let err = |s: &mut Session, p: Value| s.execute(C, &p).unwrap_err().to_string();
|
||||
assert!(err(&mut s, json!({"ids": [on.0, inside.0]})).contains("select two closed paths"));
|
||||
let open = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 50, "y": 0}, {"x": 50, "y": 50}]})).unwrap());
|
||||
assert!(err(&mut s, json!({"ids": [open.0, on.0]})).contains("open"));
|
||||
assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), (before.0 + 1, before.1 + 1), "only the open path was added");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_selections_and_params_are_refused() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -172,6 +172,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[
|
||||
BuiltinBrushLibrary { id: "art-ribbons", name: "Art Ribbons", make: art_ribbons },
|
||||
BuiltinBrushLibrary { id: "ink-and-wash", name: "Ink and Wash", make: ink_and_wash },
|
||||
BuiltinBrushLibrary { id: "calligraphic-nibs", name: "Calligraphic Nibs", make: calligraphic_nibs },
|
||||
BuiltinBrushLibrary { id: "pressure-sensitive", name: "Pressure Sensitive", make: pressure_sensitive },
|
||||
BuiltinBrushLibrary { id: "bristle-brushes", name: "Bristle Brushes", make: bristle_brushes },
|
||||
BuiltinBrushLibrary { id: "pattern-borders", name: "Pattern Borders", make: pattern_borders },
|
||||
BuiltinBrushLibrary { id: "scatter-shapes", name: "Scatter Shapes", make: scatter_shapes },
|
||||
@@ -374,6 +375,47 @@ fn bristle(name: &str, shape: BristleShape, [size, length, density, thickness, o
|
||||
Brush { name: name.into(), kind: BrushKind::Bristle(Bristle { shape, size, length, density, thickness, opacity, stiffness }) }
|
||||
}
|
||||
|
||||
/// Pressure Sensitive: four original marks whose art width or nib size responds to recorded pen
|
||||
/// pressure. Mouse paths keep the engine's neutral middle-pressure rendering.
|
||||
fn pressure_sensitive() -> BrushLibrary {
|
||||
let flex = black(band(100.0, 5.0, 48, |x| 0.5 * (x / 100.0 * std::f64::consts::TAU).sin()));
|
||||
let pulse = group(vec![
|
||||
black(band(100.0, 2.8, 64, |x| 1.4 * (x / 100.0 * 2.0 * std::f64::consts::TAU).sin())),
|
||||
black(shapes::ellipse(Rect::new(46.0, -2.2, 54.0, 2.2))),
|
||||
]);
|
||||
let art_pressure = |name: &str, art: Node, light: f64, heavy: f64| Brush {
|
||||
name: name.into(),
|
||||
kind: BrushKind::Art(ArtBrush {
|
||||
art,
|
||||
width: light,
|
||||
width_mode: Some(Variation::Pressure),
|
||||
width_max: Some(heavy),
|
||||
colorization: Colorization::Tints,
|
||||
..Default::default()
|
||||
}),
|
||||
};
|
||||
let nib_pressure = |name: &str, angle: f64, roundness: f64, size: f64, variation: f64| Brush {
|
||||
name: name.into(),
|
||||
kind: BrushKind::Calligraphic(Calligraphic {
|
||||
angle,
|
||||
roundness,
|
||||
size,
|
||||
variation: [0.0, 0.0, variation],
|
||||
modes: Some([Variation::Fixed, Variation::Fixed, Variation::Pressure]),
|
||||
}),
|
||||
};
|
||||
built(
|
||||
"Pressure Sensitive",
|
||||
Document::new(100.0, 100.0),
|
||||
vec![
|
||||
art_pressure("Flex Ribbon", flex, 35.0, 250.0),
|
||||
art_pressure("Pulse Stroke", pulse, 45.0, 280.0),
|
||||
nib_pressure("Round Flow", 0.0, 100.0, 7.0, 5.0),
|
||||
nib_pressure("Chisel Flow", 35.0, 25.0, 9.0, 7.0),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
/// Bristle Brushes: one bristle brush for each tip shape, from a fine liner to wide fans for
|
||||
/// blending and texture.
|
||||
fn bristle_brushes() -> BrushLibrary {
|
||||
|
||||
@@ -38,7 +38,7 @@ mod shape_builder;
|
||||
mod trace;
|
||||
|
||||
pub use live_paint::live_paint_gaps;
|
||||
pub(crate) use live_paint::{isolated_live_paint, merge_drawn_in_isolation};
|
||||
pub(crate) use live_paint::{LivePaintMove, check_part_name, clear_part_name, isolated_live_paints, merge_drawn_in_isolation};
|
||||
use live_paint::{lp_expand, lp_fill, lp_gap_options, lp_info, lp_make, lp_merge, lp_release, lp_stroke_edge};
|
||||
use shape_builder::{sb_merge, sb_regions};
|
||||
pub(crate) use trace::TracePresetChanges;
|
||||
|
||||
@@ -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, 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,
|
||||
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.
|
||||
@@ -74,6 +74,44 @@ fn set_parts(g: &mut Node, mut parts: Vec<Arc<Node>>, gone: &[NodeId]) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a path named `name` directly in a Live Paint group is one of its faces or edges: the
|
||||
/// name is [`FACE_NAME`] or [`EDGE_NAME`].
|
||||
fn part_name(name: Option<&str>) -> bool {
|
||||
matches!(name, Some(FACE_NAME | EDGE_NAME))
|
||||
}
|
||||
|
||||
/// Whether `n` is a path whose parent `parent` is a Live Paint group.
|
||||
fn path_in_live_paint(d: &Document, parent: Option<NodeId>, n: &Node) -> bool {
|
||||
n.path_data().is_some() && parent.and_then(|p| d.node(p)).is_some_and(is_live_paint)
|
||||
}
|
||||
|
||||
/// Clear the name of `n`, put directly in `parent`, when it is a path named like a face or an edge
|
||||
/// ([`part_name`]) and `parent` is a Live Paint group, so that the group's other children
|
||||
/// ([`others_in`]) keep it when its faces and edges are made again. Paste uses it.
|
||||
pub(crate) fn clear_part_name(d: &Document, parent: Option<NodeId>, n: &mut Node) {
|
||||
if part_name(n.name.as_deref()) && path_in_live_paint(d, parent, n) {
|
||||
n.name = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Refuse naming rows `ids` `name` when it is the name of a face or an edge ([`part_name`]) and one
|
||||
/// of them is a path directly in a Live Paint group that is not named `name` already. Checked
|
||||
/// before anything changes.
|
||||
pub(crate) fn check_part_name(d: &Document, ids: &[NodeId], name: &str) -> Result<()> {
|
||||
if !part_name(Some(name)) {
|
||||
return Ok(());
|
||||
}
|
||||
for id in ids {
|
||||
if let Some(n) = d.node(*id)
|
||||
&& n.name.as_deref() != Some(name)
|
||||
&& path_in_live_paint(d, d.parent_of(*id), n)
|
||||
{
|
||||
return Err(EngineError::Other("`Face` and `Edge` name the faces and edges of a Live Paint group: give the path another name".into()));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Select `ids` alone, without an undo step, when they are not selected that way already.
|
||||
fn select_only(s: &mut Session, ids: &[NodeId]) -> Result<()> {
|
||||
let st = s.doc()?;
|
||||
@@ -149,11 +187,16 @@ fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result
|
||||
.ok_or_else(|| EngineError::Other("Live Paint Merge: select a Live Paint group and the paths to add".into()))?;
|
||||
check_live_paint_takes(d, roots)?;
|
||||
let old = d.node(target).cloned().ok_or(EngineError::NoNode(target))?;
|
||||
// The rows that join are children of the group already when Merge runs after a drag, and a joining
|
||||
// path named like a face or an edge is not one of the group's parts.
|
||||
let mut old_parts = old.clone();
|
||||
if let Some(ch) = old_parts.children_mut() {
|
||||
ch.retain(|c| !roots.contains(&c.id));
|
||||
}
|
||||
// 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 old_parts = old.clone();
|
||||
b::faces(&old_parts).iter().filter(|f| draws(f)).filter_map(|f| Some((po::interior_point(f.path_data()?)?, Carried::of(f)))).collect();
|
||||
let mut sources = source_nodes(&old);
|
||||
// The objects drawn in the other Live Paint groups besides their parts stay in the merged group.
|
||||
let mut others = vec![];
|
||||
@@ -227,19 +270,22 @@ pub(super) fn lp_merge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "id": id.0, "faces": faces, "edges": edges }))
|
||||
}
|
||||
|
||||
/// The Live Paint group whose drawn art is added when isolation mode leaves `isolated`: the innermost
|
||||
/// Live Paint group that is `isolated` or holds it, such as a group drawn in an isolated Live Paint
|
||||
/// group and then isolated itself. None when `isolated` is not in a Live Paint group.
|
||||
pub(crate) fn isolated_live_paint(d: &Document, isolated: NodeId) -> Option<NodeId> {
|
||||
d.ancestry(isolated)?.into_iter().rev().find(|id| d.node(*id).is_some_and(is_live_paint))
|
||||
/// The Live Paint groups whose drawn art can be added when isolation mode leaves `isolated`, innermost
|
||||
/// first: every Live Paint group that is `isolated` or holds it, such as a group drawn in an isolated
|
||||
/// Live Paint group and then isolated itself, and the group it was drawn in. Empty when `isolated` is
|
||||
/// not in a Live Paint group.
|
||||
pub(crate) fn isolated_live_paints(d: &Document, isolated: NodeId) -> Vec<NodeId> {
|
||||
d.ancestry(isolated).unwrap_or_default().into_iter().rev().filter(|id| d.node(*id).is_some_and(is_live_paint)).collect()
|
||||
}
|
||||
|
||||
/// The children of Live Paint group `g` besides its parts ([`others_in`]) that Live Paint takes
|
||||
/// ([`b::live_paint_takes`]) and that are shown and unlocked with everything in them, back to
|
||||
/// front: the paths drawn in it in isolation mode.
|
||||
/// front: the paths drawn in it in isolation mode. A Live Paint group's sources group, which is
|
||||
/// always hidden, does not count.
|
||||
fn drawn_in(g: &Node) -> Vec<NodeId> {
|
||||
fn open(n: &Node) -> bool {
|
||||
n.visible && !n.locked && n.children().is_none_or(|ch| ch.iter().all(|c| open(c)))
|
||||
let src = b::sources(n).filter(|_| is_live_paint(n)).map(|s| s.id);
|
||||
n.visible && !n.locked && n.children().is_none_or(|ch| ch.iter().filter(|c| Some(c.id) != src).all(|c| open(c)))
|
||||
}
|
||||
others_in(g).filter(|c| open(c) && b::live_paint_takes(c)).map(|c| c.id).collect()
|
||||
}
|
||||
@@ -259,6 +305,189 @@ pub(crate) fn merge_drawn_in_isolation(s: &mut Session, g: NodeId) -> Result<boo
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Where a row sits for Live Paint: among the paths of a Live Paint group (in its sources group,
|
||||
/// at any depth), directly in a Live Paint group, or neither.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Spot {
|
||||
Source(NodeId),
|
||||
In(NodeId),
|
||||
Outside,
|
||||
}
|
||||
|
||||
/// The [`Spot`] of a row whose parent is `parent` (None: the top level).
|
||||
fn spot_in(d: &Document, parent: Option<NodeId>) -> Spot {
|
||||
let Some(p) = parent else { return Spot::Outside };
|
||||
for x in d.ancestry(p).unwrap_or_default().into_iter().rev() {
|
||||
let n = d.node(x);
|
||||
if n.is_some_and(is_live_paint) {
|
||||
return if x == p { Spot::In(x) } else { Spot::Outside };
|
||||
}
|
||||
if let Some(g) = d.parent_of(x)
|
||||
&& d.node(g).filter(|n| is_live_paint(n)).and_then(b::sources).is_some_and(|s| s.id == x)
|
||||
{
|
||||
return Spot::Source(g);
|
||||
}
|
||||
}
|
||||
Spot::Outside
|
||||
}
|
||||
|
||||
/// The Live Paint groups that hold Live Paint group `g` among their paths (in their sources group,
|
||||
/// at any depth), innermost first.
|
||||
fn enclosing_live_paints(d: &Document, g: NodeId) -> Vec<NodeId> {
|
||||
let mut out = vec![];
|
||||
let mut at = g;
|
||||
while let Spot::Source(o) = spot_in(d, d.parent_of(at)) {
|
||||
if out.contains(&o) {
|
||||
break;
|
||||
}
|
||||
out.push(o);
|
||||
at = o;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// What moving rows in the Layers panel (`layer.move`, `node.move`) does to Live Paint groups.
|
||||
/// Rows that go into a Live Paint group from elsewhere are added to it as `livePaint.merge` adds
|
||||
/// paths. Rows that go into or leave a group's paths (its sources group) change those paths, and
|
||||
/// the group's faces and edges are made again from them, keeping the paint of the faces and edges
|
||||
/// that stay, and so are those of every Live Paint group that holds a changed group among its
|
||||
/// paths. Rows moved within one group's paths, or among a group's own children, change no faces.
|
||||
pub(crate) struct LivePaintMove {
|
||||
/// The Live Paint group the rows go into, and for each row whether it joins the group's paths.
|
||||
join: Option<(NodeId, Vec<bool>)>,
|
||||
/// The Live Paint group the rows go among the children of, with its sources group as it is
|
||||
/// before the move.
|
||||
keep_sources: Option<(NodeId, NodeId)>,
|
||||
/// The Live Paint groups whose paths change.
|
||||
rebuild: Vec<NodeId>,
|
||||
}
|
||||
|
||||
impl LivePaintMove {
|
||||
/// Plan moving `rows` (with `copy`, copies of them) into `parent`, before anything changes.
|
||||
/// Refuses rows Live Paint can't take ([`b::live_paint_takes`]) that would go among a group's
|
||||
/// paths, with the message Make and Merge give.
|
||||
pub(crate) fn plan(d: &Document, rows: &[NodeId], parent: Option<NodeId>, copy: bool) -> Result<Self> {
|
||||
let to = spot_in(d, parent);
|
||||
let from: Vec<Spot> = rows.iter().map(|r| if copy { Spot::Outside } else { spot_in(d, d.parent_of(*r)) }).collect();
|
||||
let mut rebuild = vec![];
|
||||
for f in &from {
|
||||
if let Spot::Source(g) = *f
|
||||
&& *f != to
|
||||
&& !rebuild.contains(&g)
|
||||
{
|
||||
rebuild.push(g);
|
||||
}
|
||||
}
|
||||
if let Spot::Source(g) = to
|
||||
&& from.iter().any(|f| *f != to)
|
||||
&& !rebuild.contains(&g)
|
||||
{
|
||||
rebuild.push(g);
|
||||
}
|
||||
let entering: Vec<NodeId> = rows.iter().zip(&from).filter(|(_, f)| **f != to).map(|(r, _)| *r).collect();
|
||||
let join = match to {
|
||||
Spot::In(g) if !entering.is_empty() => Some((g, from.iter().map(|f| *f != to).collect())),
|
||||
_ => None,
|
||||
};
|
||||
if to != Spot::Outside {
|
||||
check_live_paint_takes(d, &entering)?;
|
||||
}
|
||||
let keep_sources = match to {
|
||||
Spot::In(g) => d.node(g).and_then(b::sources).map(|s| (g, s.id)),
|
||||
_ => None,
|
||||
};
|
||||
Ok(Self { join, keep_sources, rebuild })
|
||||
}
|
||||
|
||||
/// Whether rows join a Live Paint group, which makes the move a "Merge Live Paint" step.
|
||||
pub(crate) fn joins(&self) -> bool {
|
||||
self.join.is_some()
|
||||
}
|
||||
|
||||
/// After the rows were moved, now `moved` (in the order [`LivePaintMove::plan`] took them),
|
||||
/// make the faces and edges of the groups whose paths changed again, and add the rows that
|
||||
/// joined a group to it. → `moved` with the joined rows replaced by their group, once, and
|
||||
/// without the faces and edges that were made again.
|
||||
pub(crate) fn finish(self, d: &mut Document, sel: &mut Selection, moved: &[NodeId]) -> Result<Vec<NodeId>> {
|
||||
// A moved object named like the sources group may now sit before it, where a lookup by name
|
||||
// finds the object first. The group's own sources group goes back in front.
|
||||
if let Some((g, src)) = self.keep_sources {
|
||||
let ch = d.children_mut(Some(g))?;
|
||||
if let Some(at) = ch.iter().position(|c| c.id == src)
|
||||
&& ch[..at].iter().any(|c| c.name.as_deref() == Some(SOURCES_NAME))
|
||||
{
|
||||
let s = ch.remove(at);
|
||||
ch.insert(0, s);
|
||||
}
|
||||
}
|
||||
if self.join.is_none() && self.rebuild.is_empty() {
|
||||
return Ok(moved.to_vec());
|
||||
}
|
||||
// The group the rows join is made again by the merge below, from its paths as they are now
|
||||
// and with the paint of its faces and edges as they were before the move.
|
||||
let join_group = self.join.as_ref().map(|(g, _)| *g);
|
||||
// A Live Paint group among another group's paths gives that group its faces and edges, so
|
||||
// the groups holding a changed group among their paths are made again too, innermost first.
|
||||
let mut groups: Vec<NodeId> = vec![];
|
||||
for g in self.rebuild.iter().copied().chain(join_group) {
|
||||
for x in std::iter::once(g).chain(enclosing_live_paints(d, g)) {
|
||||
if !groups.contains(&x) {
|
||||
groups.push(x);
|
||||
}
|
||||
}
|
||||
}
|
||||
groups.sort_by_cached_key(|g| std::cmp::Reverse(d.ancestry(*g).map_or(0, |a| a.len())));
|
||||
let joined: Vec<NodeId> = match &self.join {
|
||||
Some((_, mask)) => moved.iter().zip(mask).filter(|(_, j)| **j).map(|(r, _)| *r).collect(),
|
||||
None => vec![],
|
||||
};
|
||||
for g in groups {
|
||||
if Some(g) == join_group {
|
||||
let roots: Vec<NodeId> = std::iter::once(g).chain(joined.iter().copied()).collect();
|
||||
merge_live(d, sel, &roots)?;
|
||||
} else if d.node(g).is_some() {
|
||||
rebuild_paths(d, g)?;
|
||||
}
|
||||
}
|
||||
let Some((g, mask)) = self.join else { return Ok(moved.iter().copied().filter(|r| d.node(*r).is_some()).collect()) };
|
||||
// `moved` holds each row once, so only the group can come twice. Faces and edges of the
|
||||
// group moved along with the joining rows were made again, so they are left out.
|
||||
let mut out = vec![];
|
||||
let mut listed = false;
|
||||
for (r, j) in moved.iter().zip(&mask) {
|
||||
if *j {
|
||||
if !listed {
|
||||
out.push(g);
|
||||
listed = true;
|
||||
}
|
||||
} else if d.node(*r).is_some() {
|
||||
out.push(*r);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
/// Make Live Paint group `g`'s faces and edges again from the paths its sources group holds now,
|
||||
/// with its Gap Options, carrying over the paint of the faces and edges that stay. With no path
|
||||
/// left, the group keeps its sources group and its other children, and has no faces or edges.
|
||||
fn rebuild_paths(d: &mut Document, g: NodeId) -> Result<()> {
|
||||
let old = d.node(g).cloned().ok_or(EngineError::NoNode(g))?;
|
||||
let sources = source_nodes(&old);
|
||||
let mut n = old.clone();
|
||||
if source_shapes(&sources).0.is_empty() {
|
||||
let src = b::sources(&old).cloned().ok_or(EngineError::NoNode(g))?;
|
||||
set_parts(&mut n, vec![src], &[]);
|
||||
} else {
|
||||
let (children, _, _) = build_children(d, sources, old.gap_options().max_gap())?;
|
||||
set_parts(&mut n, children, &[]);
|
||||
repaint_from(&mut n, &old);
|
||||
}
|
||||
let mut changed = Beside::replacing(d, &[g]);
|
||||
changed.put(d, g, vec![n])?;
|
||||
changed.finish(d)
|
||||
}
|
||||
|
||||
fn live_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
let d = &s.doc()?.doc;
|
||||
let ids = root_ids(s, p)?;
|
||||
|
||||
@@ -8,6 +8,8 @@ use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, ShapeMode};
|
||||
use vectorcraft_geom::{FillRule, PathData, SubPath};
|
||||
use vectorcraft_pathops as po;
|
||||
use vectorcraft_render::effects;
|
||||
|
||||
use super::edit::{roots_of, selected_roots};
|
||||
@@ -16,6 +18,10 @@ use super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_multi};
|
||||
|
||||
const MODE_NAMES: [&str; 4] = ["add", "subtract", "intersect", "exclude"];
|
||||
|
||||
/// Make Compound Shape's warning, which the status bar shows, when a member holds a line or another
|
||||
/// open path that encloses no area once closed, and so contributes no area to the shape.
|
||||
pub const OPEN_PATHS_ADD_NO_AREA: &str = "a line or other open path that encloses no area contributes no area to the compound shape; to include it, apply Object › Path › Outline Stroke to it first";
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
@@ -23,7 +29,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Make Compound Shape",
|
||||
["Window", "Pathfinder"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection), mode?: \"add\"|\"subtract\"|\"intersect\"|\"exclude\" (default add; Alt-clicking a Shape Mode button gives its mode)} the two or more selected objects (paths, compound paths, groups, compound shapes, type, blends, envelopes) become the members of one compound shape, each with the shape mode, in their stacking order where the frontmost was: it draws as the area they make from the backmost up (open paths closed; a blend as its steps, an envelope as its distorted art, an object with a warp or other geometry effect as it draws), painted with the appearance and transparency of the topmost member in Add, Intersect or Exclude mode (with every member in Subtract, the backmost), and the members stay editable (Direct Selection, Layers panel, isolation mode) → {id}",
|
||||
"{ids?: [id…] (selected first; default: the selection), mode?: \"add\"|\"subtract\"|\"intersect\"|\"exclude\" (default add; Alt-clicking a Shape Mode button gives its mode)} the two or more selected objects (paths, compound paths, groups, compound shapes, type, blends, envelopes) become the members of one compound shape, each with the shape mode, in their stacking order where the frontmost was: it draws as the area they make from the backmost up (open paths closed; a blend as its steps, an envelope as its distorted art, an object with a warp or other geometry effect as it draws), painted with the appearance and transparency of the topmost member in Add, Intersect or Exclude mode (with every member in Subtract, the backmost), and the members stay editable (Direct Selection, Layers panel, isolation mode) → {id, warning?: when a member is or holds a line or another open path that encloses no area once closed, and so contributes no area}",
|
||||
has_multi,
|
||||
make
|
||||
),
|
||||
@@ -157,6 +163,7 @@ fn make(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// all have `mode`, the topmost, or the backmost when they all subtract.
|
||||
let order: Vec<&Node> = if mode == ShapeMode::Subtract { members } else { members.into_iter().rev().collect() };
|
||||
let hook = |c: &Node| effects::outline_object(Some(d), c);
|
||||
let no_area = order.iter().any(|n| adds_no_area(d, n, &hook));
|
||||
let style = order.into_iter().find_map(|n| top_style(d, n, &hook));
|
||||
let id = s.edit("Make Compound Shape", |d, sel| {
|
||||
let gid = d.alloc_id();
|
||||
@@ -179,7 +186,44 @@ fn make(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
})?;
|
||||
Ok(json!({ "id": id.0 }))
|
||||
let mut out = json!({ "id": id.0 });
|
||||
if no_area {
|
||||
out["warning"] = json!(OPEN_PATHS_ADD_NO_AREA);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Member `n` holds an open path that adds no area to a compound shape: one of the paths it takes
|
||||
/// part as ([`effects::member_leaves`]), inside a group or a compound path too, has an open subpath
|
||||
/// that encloses no area once closed (a straight line, or an evenodd contour traced twice), or it
|
||||
/// has an open subpath and its subpaths, all closed, enclose no area together (open evenodd
|
||||
/// subpaths that cancel one another or a closed subpath). The area is the one the path's fill rule
|
||||
/// gives, which also keeps a self-crossing path whose signed area is zero (a bow tie) from the
|
||||
/// warning, as Divide measures it. An area that can't be measured gives no warning.
|
||||
fn adds_no_area(d: &Document, n: &Node, hook: effects::OutlineHook) -> bool {
|
||||
effects::member_leaves(Some(d), n, Some(hook)).iter().any(|leaf| {
|
||||
let (paths, rule): (Vec<&PathData>, FillRule) = match &leaf.kind {
|
||||
NodeKind::Compound { children, rule } => (children.iter().filter_map(|c| c.path_data()).collect(), *rule),
|
||||
NodeKind::Path { path, rule, .. } => (vec![path], *rule),
|
||||
_ => return false,
|
||||
};
|
||||
let subpaths: Vec<&SubPath> = paths.iter().flat_map(|p| &p.subpaths).collect();
|
||||
if subpaths.iter().all(|sp| sp.closed) {
|
||||
return false;
|
||||
}
|
||||
let closed = |sp: &SubPath| {
|
||||
let mut sp = sp.clone();
|
||||
sp.closed = true;
|
||||
sp
|
||||
};
|
||||
// An area that can't be measured counts as an area, so a failed measurement gives no warning.
|
||||
let no_area = |p: PathData| po::try_area(&p, rule).is_ok_and(|a| a <= 0.0);
|
||||
subpaths.iter().filter(|sp| !sp.closed).any(|sp| {
|
||||
// The signed-area test alone only holds for nonzero: evenodd can fill nothing where
|
||||
// the signed area is not zero (a contour traced twice).
|
||||
!(rule == FillRule::NonZero && po::encloses_area(sp)) && no_area(PathData::single(closed(sp)))
|
||||
}) || (subpaths.len() > 1 && no_area(PathData::new(subpaths.iter().map(|sp| closed(sp)).collect())))
|
||||
})
|
||||
}
|
||||
|
||||
/// The paint and transparency of the frontmost shape `n` adds to a compound shape's area, from the
|
||||
|
||||
@@ -92,7 +92,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Eraser",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation 0..360° clockwise; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), angle?: ° (0, −180–180: the tip's long axis counter-clockwise from level), roundness?: % (100, 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0–1000, default 0)} or {rect: [x, y, width, height] (pt; the Eraser's Alt-drag marquee)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An angle or roundness outside its range, an unknown mode, or a variation below 0 or past its range is refused with an error and erases nothing. `rect` in place of `points` erases everything inside the rectangle: closed paths lose its area, and open paths are cut where they cross its edges; the tip's size, angle, roundness and variations do not apply. A width or height of 0 or less, a value that is not a finite number, or `points` and `rect` together is an error. When nothing is erased, no undo step is added",
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation 0..360° clockwise; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), angle?: ° (0, −180–180: the tip's long axis counter-clockwise from level), roundness?: % (100, 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0–1000, default 0)} or {rect: [x, y, width, height] (pt; the Eraser's Alt-drag marquee)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An angle or roundness outside its range, an unknown mode, or a variation below 0 or past its range is refused with an error and erases nothing. `rect` in place of `points` erases everything inside the rectangle: closed paths and filled open paths without a visible painted stroke lose its area, and other open paths are cut where they cross its edges; the tip's size, angle, roundness and variations do not apply. A width or height of 0 or less, a value that is not a finite number, or `points` and `rect` together is an error. When nothing is erased, no undo step is added",
|
||||
has_doc,
|
||||
erase_region
|
||||
),
|
||||
|
||||
@@ -345,18 +345,46 @@ pub(super) fn target_paths(doc: &Document, sel: &Selection, area: Rect) -> Vec<N
|
||||
out
|
||||
}
|
||||
|
||||
/// Any visible non-None fill, including one below a topmost None.
|
||||
pub(super) fn has_fill(n: &Node) -> bool {
|
||||
n.appearance.items.iter().any(|item| item.is_fill() && item.visible() && !item.paint().is_none())
|
||||
}
|
||||
|
||||
/// A visible painted stroke keeps open paths on the existing outline-erasure route.
|
||||
pub(super) fn has_painted_stroke(n: &Node) -> bool {
|
||||
n.appearance.items.iter().any(
|
||||
|item| matches!(item, vectorcraft_doc::AppearanceItem::Stroke(stroke) if stroke.visible && !stroke.paint.is_none() && stroke.width > 0.0),
|
||||
)
|
||||
}
|
||||
|
||||
/// A container stroke that paints this target's open geometry. A clipping container's own
|
||||
/// paint follows its clipping outline, and a compound shape paints its combined area instead.
|
||||
/// Neither makes its descendants' implicit fill-closing edges into new stroked edges.
|
||||
pub(super) fn has_painted_ancestor_stroke(doc: &Document, id: NodeId) -> bool {
|
||||
doc.ancestry(id)
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.rev()
|
||||
.skip(1)
|
||||
.filter_map(|id| doc.node(id))
|
||||
.take_while(|node| !node.clips() && !node.is_compound_shape())
|
||||
.any(|node| matches!(node.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && has_painted_stroke(node))
|
||||
}
|
||||
|
||||
/// [`target_paths`] for the tools that cut fills, with each target's geometry and fill rule: the
|
||||
/// members of a compound path whose members are all closed paths give the compound path itself,
|
||||
/// once, so its fill (holes included) is cut as one shape under its own fill rule.
|
||||
pub(super) fn fill_targets(doc: &Document, sel: &Selection, area: Rect) -> Result<Vec<(NodeId, PathData, FillRule)>> {
|
||||
let closed_compound = |n: &Node| {
|
||||
/// With `open_fills`, an open compound with a visible fill and no painted visible stroke does too.
|
||||
pub(super) fn fill_targets(doc: &Document, sel: &Selection, area: Rect, open_fills: bool) -> Result<Vec<(NodeId, PathData, FillRule)>> {
|
||||
let area_compound = |n: &Node| {
|
||||
let filled = open_fills && has_fill(n) && !has_painted_stroke(n) && !has_painted_ancestor_stroke(doc, n.id);
|
||||
matches!(&n.kind, NodeKind::Compound { children, .. }
|
||||
if children.iter().all(|c| matches!(&c.kind, NodeKind::Path { path, .. } if path.is_closed())))
|
||||
if children.iter().all(|c| matches!(&c.kind, NodeKind::Path { path, .. } if path.is_closed() || filled)))
|
||||
};
|
||||
let editable = doc.editable();
|
||||
let mut out: Vec<(NodeId, PathData, FillRule)> = vec![];
|
||||
for id in target_paths(doc, sel, area) {
|
||||
let compound = doc.parent_of(id).and_then(|p| doc.node(p)).filter(|p| closed_compound(p) && editable(p.id));
|
||||
let compound = doc.parent_of(id).and_then(|p| doc.node(p)).filter(|p| area_compound(p) && editable(p.id));
|
||||
let target = compound.map_or(id, |c| c.id);
|
||||
if out.iter().any(|t| t.0 == target) {
|
||||
continue;
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
use super::common::{
|
||||
PenRecord, SIZE_VARIATIONS, SIZES, Sample, center_strokes, dist_to_polyline, fill_targets, ids_json, path_mut, path_of, points_param,
|
||||
poly_bounds, pressure_region, ranged, replace_with_pieces, samples_param, sibling_with, size_pressure, target_paths, usize_opt,
|
||||
PenRecord, SIZE_VARIATIONS, SIZES, Sample, center_strokes, dist_to_polyline, fill_targets, has_fill, has_painted_ancestor_stroke,
|
||||
has_painted_stroke, ids_json, path_mut, path_of, points_param, poly_bounds, pressure_region, ranged, replace_with_pieces, samples_param,
|
||||
set_geometry, sibling_with, size_pressure, target_paths, usize_opt,
|
||||
};
|
||||
use super::{
|
||||
Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, Paint, ParamCurve, PathData, Point, Rect, Result, Session,
|
||||
SubPath, Value, Vec2, bad, eraser_area, eraser_tip, f64_or, fill_contains, json, number_or, object_param, po,
|
||||
Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, Document, EngineError, FillRule, Join, NodeId, NodeKind, Paint, ParamCurve, PathData, Point,
|
||||
Rect, Result, Session, SubPath, Value, Vec2, bad, eraser_area, eraser_tip, f64_or, fill_contains, json, number_or, object_param, po,
|
||||
};
|
||||
use kurbo::{CubicBez, Line, PathSeg};
|
||||
use vectorcraft_brush::{Brush, BrushKind, Calligraphic, Variation};
|
||||
@@ -266,7 +267,7 @@ pub(super) fn knife(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let strip = po::outline_stroke(&PathData::single(SubPath::polyline(&pts, false)), KNIFE_GAP, Cap::Butt, Join::Round, 4.0);
|
||||
let mut plan: Vec<(NodeId, Vec<PathData>)> = vec![];
|
||||
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, 1.0))? {
|
||||
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, 1.0), false)? {
|
||||
if !pd.is_closed() {
|
||||
continue;
|
||||
}
|
||||
@@ -340,8 +341,9 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None => dist_to_polyline(&round, squash * q) <= r,
|
||||
};
|
||||
let mut plan: Vec<(NodeId, Vec<PathData>)> = vec![];
|
||||
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, reach))? {
|
||||
if pd.is_closed() {
|
||||
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, reach), true)? {
|
||||
if erase_as_area(&st.doc, id, &pd) {
|
||||
let pd = eraser_fill_operand(pd);
|
||||
if po::area(&po::boolean(&pd, rule, ®ion, FillRule::NonZero, BoolOp::Intersect), FillRule::NonZero) <= 1e-6 {
|
||||
continue;
|
||||
}
|
||||
@@ -353,6 +355,34 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
apply_plan(s, "Eraser", plan)
|
||||
}
|
||||
|
||||
/// Whether the target is erased as filled area rather than as an open outline.
|
||||
fn erase_as_area(doc: &Document, id: NodeId, pd: &PathData) -> bool {
|
||||
// An unaggregated compound member keeps the outline route: its own appearance does not
|
||||
// paint it. Eligible fill-only compounds were collected as one parent target above.
|
||||
let compound_member =
|
||||
doc.parent_of(id).and_then(|parent| doc.node(parent)).is_some_and(|parent| matches!(parent.kind, NodeKind::Compound { .. }));
|
||||
let filled_open =
|
||||
!compound_member && !has_painted_ancestor_stroke(doc, id) && doc.node(id).is_some_and(|node| has_fill(node) && !has_painted_stroke(node));
|
||||
pd.is_closed() || filled_open
|
||||
}
|
||||
|
||||
/// Close only Eraser's temporary fill operand, preserving an open path's straight closing edge.
|
||||
fn eraser_fill_operand(mut pd: PathData) -> PathData {
|
||||
for sp in &mut pd.subpaths {
|
||||
if !sp.closed {
|
||||
// These endpoint handles are unused by an open path. Closing it must not activate them.
|
||||
if let Some(first) = sp.anchors.first_mut() {
|
||||
first.h_in = first.p;
|
||||
}
|
||||
if let Some(last) = sp.anchors.last_mut() {
|
||||
last.h_out = last.p;
|
||||
}
|
||||
sp.closed = true;
|
||||
}
|
||||
}
|
||||
pd
|
||||
}
|
||||
|
||||
/// `path.eraseRegion`'s `rect: [x, y, width, height]`: four finite numbers, with a width and a
|
||||
/// height above 0.
|
||||
fn marquee_param(v: &Value, cmd: &str) -> Result<Rect> {
|
||||
@@ -369,7 +399,7 @@ fn marquee_param(v: &Value, cmd: &str) -> Result<Rect> {
|
||||
}
|
||||
|
||||
/// `path.eraseRegion` with a marquee: everything inside `r` is erased from the paths (selected, or
|
||||
/// all). Closed paths lose the rectangle's area, and open paths are cut where they cross its edges.
|
||||
/// all). Closed paths and fill-only open paths lose the rectangle's area; other open paths are cut where they cross its edges.
|
||||
fn erase_rect(s: &mut Session, r: Rect) -> Result<Value> {
|
||||
let region =
|
||||
PathData::single(SubPath::polyline(&[Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)], true));
|
||||
@@ -392,8 +422,9 @@ fn erase_rect(s: &mut Session, r: Rect) -> Result<Value> {
|
||||
};
|
||||
let st = s.doc()?;
|
||||
let mut plan: Vec<(NodeId, Vec<PathData>)> = vec![];
|
||||
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, r)? {
|
||||
if pd.is_closed() {
|
||||
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, r, true)? {
|
||||
if erase_as_area(&st.doc, id, &pd) {
|
||||
let pd = eraser_fill_operand(pd);
|
||||
if po::area(&po::boolean(&pd, rule, ®ion, FillRule::NonZero, BoolOp::Intersect), FillRule::NonZero) <= 1e-6 {
|
||||
continue;
|
||||
}
|
||||
@@ -492,8 +523,9 @@ fn erase_varied(s: &mut Session, samples: &[Sample], tip: [f64; 3], vary: [(Vari
|
||||
let short = low(2).max(MIN_BRUSH_SIZE) * low(1).clamp(1.0, 100.0) / 100.0;
|
||||
let reach = (size + sv) / 2.0;
|
||||
let mut plan: Vec<(NodeId, Vec<PathData>)> = vec![];
|
||||
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, reach))? {
|
||||
if pd.is_closed() {
|
||||
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, reach), true)? {
|
||||
if erase_as_area(&st.doc, id, &pd) {
|
||||
let pd = eraser_fill_operand(pd);
|
||||
if po::area(&po::boolean(&pd, rule, ®ion, FillRule::NonZero, BoolOp::Intersect), FillRule::NonZero) <= 1e-6 {
|
||||
continue;
|
||||
}
|
||||
@@ -510,10 +542,36 @@ fn apply_plan(s: &mut Session, label: &str, plan: Vec<(NodeId, Vec<PathData>)>)
|
||||
return Ok(json!({ "ids": [] }));
|
||||
}
|
||||
let ids = s.edit(label, |d, sel| {
|
||||
// Measure every original painting owner before any geometry or appearance changes.
|
||||
// This includes a Compound above a Path Eraser target and containers above live art.
|
||||
let owners: std::collections::BTreeSet<_> = plan.iter().flat_map(|(id, _)| d.ancestry(*id).unwrap_or_default()).collect();
|
||||
let pinned: Vec<_> = owners
|
||||
.into_iter()
|
||||
.filter_map(|id| {
|
||||
let node = d.node(id)?;
|
||||
if !node.appearance.has_unplaced_gradient() {
|
||||
return None;
|
||||
}
|
||||
vectorcraft_render::pinned_appearance_for_geometry_edit(d, node).map(|appearance| (id, appearance))
|
||||
})
|
||||
.collect();
|
||||
for (id, appearance) in pinned {
|
||||
if let Some(node) = d.node_mut(id) {
|
||||
node.appearance = appearance.into();
|
||||
}
|
||||
}
|
||||
let mut all = vec![];
|
||||
let mut cut = Beside::replacing(d, &plan.iter().map(|(id, _)| *id).collect::<Vec<_>>());
|
||||
for (id, pieces) in plan {
|
||||
all.extend(replace_with_pieces(d, &mut cut, id, pieces)?);
|
||||
let clipping_path = d.position(id).is_some_and(|(parent, i, _)| i == 0 && parent.and_then(|p| d.node(p)).is_some_and(|p| p.clips()));
|
||||
if clipping_path {
|
||||
// Keep every clipping contour in its original first child slot. An empty mask
|
||||
// must also stay there so the clipped artwork cannot become the new mask.
|
||||
set_geometry(d, id, PathData::new(pieces.into_iter().flat_map(|p| p.subpaths).collect()))?;
|
||||
all.push(id);
|
||||
} else {
|
||||
all.extend(replace_with_pieces(d, &mut cut, id, pieces)?);
|
||||
}
|
||||
}
|
||||
cut.finish(d)?;
|
||||
sel.set(all.iter().copied());
|
||||
|
||||
@@ -1611,6 +1611,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
}
|
||||
} else {
|
||||
super::object::keep_pixel_aligned(&mut c, sc);
|
||||
super::buildcmds::clear_part_name(d, par, &mut c);
|
||||
new_ids.push(d.insert(par, idx, c)?);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,18 @@ pub(super) const OPTIONS: &[FormatOption] = &[super::ARTBOARD, super::ARTBOARDS,
|
||||
/// Encode `doc` as `kind`: the chosen artboard (default the first), or with `use_artboards` one
|
||||
/// picture per chosen artboard (default all).
|
||||
pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>, kind: Kind) -> Result<Encoded> {
|
||||
encode_flattening(doc, p, use_artboards, kind, crate::flatten_raster_effects)
|
||||
}
|
||||
|
||||
/// [`encode`] with `flatten` turning raster effects into images. The chosen artboards are checked
|
||||
/// first, so an export that is refused does not call `flatten`.
|
||||
pub(super) fn encode_flattening(
|
||||
doc: &Document,
|
||||
p: &Value,
|
||||
use_artboards: Option<bool>,
|
||||
kind: Kind,
|
||||
flatten: impl FnOnce(&Document) -> Option<Document>,
|
||||
) -> Result<Encoded> {
|
||||
let f = super::format(kind.id()).ok_or_else(|| bad(C, "no metafile format"))?;
|
||||
let pick: ArtboardPick = super::encode::options(f, p)?;
|
||||
let n = doc.artboards.len();
|
||||
@@ -26,12 +38,16 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>, kin
|
||||
Some(true) => pick.resolve(n).map_err(|e| bad(C, e))?.unwrap_or_else(|| (0..n).collect()),
|
||||
_ => vec![pick.one(n).map_err(|e| bad(C, e))?],
|
||||
};
|
||||
if boards.is_empty() {
|
||||
return Err(bad(C, "the document has no artboard"));
|
||||
}
|
||||
let rects = boards
|
||||
.iter()
|
||||
.map(|&b| doc.artboards.get(b).map(|a| a.rect).ok_or_else(|| bad(C, format!("no artboard {}", b + 1))))
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
vectorcraft_metafile::check_regions(&rects).map_err(|e| bad(C, e))?;
|
||||
// Raster effects (shadows, glows, blurs) as images, as PDF export does.
|
||||
let flat = crate::flatten_raster_effects(doc);
|
||||
let flat = flatten(doc);
|
||||
let src = flat.as_ref().unwrap_or(doc);
|
||||
let outs = vectorcraft_metafile::export_regions(src, &rects, kind).map_err(|e| bad(C, e))?;
|
||||
let mut enc = Encoded::default();
|
||||
|
||||
@@ -95,6 +95,65 @@ fn raster_effects_are_written_as_images() {
|
||||
assert!(kinds.contains(&114), "the shadow is an image with transparency");
|
||||
}
|
||||
|
||||
/// An export refused for an empty or non-finite artboard among the chosen ones, or for no
|
||||
/// artboard, gives the same error as before and turns no raster effect into an image; an export
|
||||
/// that goes ahead does so once, and writes what `document.export` writes.
|
||||
#[test]
|
||||
fn a_refused_export_turns_no_raster_effects_into_images() {
|
||||
use vectorcraft_geom::Rect;
|
||||
use vectorcraft_metafile::Kind;
|
||||
let mut s = two_boards();
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 30, "height": 30})).unwrap()["id"].clone();
|
||||
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [id]})).unwrap();
|
||||
let doc = s.doc().unwrap().doc.as_ref().clone();
|
||||
let run = |doc: &vectorcraft_doc::Document, p: Value, kind: Kind| {
|
||||
let mut calls = 0;
|
||||
let r = super::metafile::encode_flattening(doc, &p, Some(true), kind, |d| {
|
||||
calls += 1;
|
||||
crate::flatten_raster_effects(d)
|
||||
});
|
||||
(r.map(|e| e.files).map_err(|e| e.to_string()), calls)
|
||||
};
|
||||
for kind in [Kind::Emf, Kind::Wmf] {
|
||||
let (files, calls) = run(&doc, json!({}), kind);
|
||||
assert_eq!(calls, 1, "{kind:?}");
|
||||
let files = files.unwrap();
|
||||
assert_eq!(files.len(), 2, "{kind:?}");
|
||||
let r = s.execute("document.export", &json!({"format": kind.id(), "useArtboards": true})).unwrap();
|
||||
let written: Vec<Vec<u8>> = r["files"].as_array().unwrap().iter().map(b64).collect();
|
||||
assert_eq!(files.into_iter().map(|(_, b)| b).collect::<Vec<_>>(), written, "{kind:?}");
|
||||
// The first artboard is fine; the second is empty, or has a corner that isn't finite.
|
||||
let x = doc.artboards[0].rect.x1 + 10.0;
|
||||
for empty in [Rect::new(x, 0.0, x, 100.0), Rect::new(0.0, 0.0, f64::NAN, 100.0), Rect::new(0.0, 0.0, 100.0, f64::INFINITY)] {
|
||||
let mut bad_doc = doc.clone();
|
||||
bad_doc.artboards[1].rect = empty;
|
||||
for p in [json!({}), json!({"artboards": [0, 1]}), json!({"artboards": [1]})] {
|
||||
let (files, calls) = run(&bad_doc, p.clone(), kind);
|
||||
let e = files.err().unwrap_or_default();
|
||||
assert!(e.contains("the export region is empty"), "{kind:?} {p}: {e}");
|
||||
assert_eq!(calls, 0, "{kind:?} {p}");
|
||||
}
|
||||
}
|
||||
// Reversed corners are an artboard like any other.
|
||||
let mut flipped = doc.clone();
|
||||
let r1 = flipped.artboards[1].rect;
|
||||
flipped.artboards[1].rect = Rect::new(r1.x1, r1.y1, r1.x0, r1.y0);
|
||||
let (files, calls) = run(&flipped, json!({}), kind);
|
||||
assert_eq!((files.map(|f| f.len()), calls), (Ok(2), 1), "{kind:?}");
|
||||
// No artboard to write.
|
||||
let mut none = doc.clone();
|
||||
none.artboards.clear();
|
||||
let (files, calls) = run(&none, json!({}), kind);
|
||||
let e = files.err().unwrap_or_default();
|
||||
assert!(e.contains("the document has no artboard"), "{kind:?}: {e}");
|
||||
assert_eq!(calls, 0, "{kind:?}");
|
||||
}
|
||||
// Through the command, the refusal reads as it did.
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).artboards[1].rect = Rect::new(0.0, 0.0, 0.0, 100.0);
|
||||
let e = s.execute("document.export", &json!({"format": "emf", "useArtboards": true})).unwrap_err().to_string();
|
||||
assert!(e.contains("the export region is empty"), "{e}");
|
||||
}
|
||||
|
||||
/// Two placed images whose pixel data can't be decoded are left out of an EMF or WMF, and
|
||||
/// `warnings` holds the note raster exports give, once, without naming either image's key.
|
||||
#[test]
|
||||
|
||||
@@ -19,23 +19,6 @@ use crate::DocState;
|
||||
const MAX_FONTS: usize = 1_000;
|
||||
/// The longest family or style name listed or given (bytes).
|
||||
const MAX_NAME: usize = 256;
|
||||
/// The CSS generic font families (CSS Fonts Module Level 4), which SVG and HTML files name in place
|
||||
/// of a font and no font file provides; compared in any ASCII case. The list leaves out
|
||||
/// `fangsong`, which is also the family name of a Chinese font (FangSong).
|
||||
const GENERIC_FAMILIES: &[&str] = &[
|
||||
"serif",
|
||||
"sans-serif",
|
||||
"monospace",
|
||||
"cursive",
|
||||
"fantasy",
|
||||
"system-ui",
|
||||
"ui-serif",
|
||||
"ui-sans-serif",
|
||||
"ui-monospace",
|
||||
"ui-rounded",
|
||||
"math",
|
||||
"emoji",
|
||||
];
|
||||
/// The longest folder path given (bytes).
|
||||
const MAX_PATH: usize = 4096;
|
||||
/// The most files one `text.addFontFiles` copies: as many as a search keeps.
|
||||
@@ -105,10 +88,10 @@ pub struct MissingFont {
|
||||
|
||||
/// The fonts the type of `d` uses, in its layers, symbols and patterns, opacity masks included (a composite font's parts, those
|
||||
/// its characters are drawn in, in place of its name), that aren't available as named (sorted by family and style, each once whatever version its type names; at most 1000). CSS generic families such as `sans-serif`
|
||||
/// ([`GENERIC_FAMILIES`]) and names longer than 256 bytes are left out.
|
||||
/// ([`vectorcraft_text::GENERIC_FAMILIES`]) and names longer than 256 bytes are left out.
|
||||
pub fn missing_fonts(d: &Document) -> Vec<MissingFont> {
|
||||
let db = FontDb::global();
|
||||
let generic = |family: &str| GENERIC_FAMILIES.iter().any(|g| g.eq_ignore_ascii_case(family.trim()));
|
||||
let generic = vectorcraft_text::is_generic_family;
|
||||
let mut used: Vec<(String, String)> = super::fonts::used_fonts(d).into_iter().map(|(family, style, _)| (family, style)).collect();
|
||||
// Sorted by family and style: the versions type names of one face are neighbors.
|
||||
used.dedup();
|
||||
|
||||
@@ -13,6 +13,7 @@ use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Artboard, ArtboardSide, Document, LAYER_COLORS, LayerColor, Node, NodeId, NodeKind, Scaling};
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
|
||||
use super::buildcmds::LivePaintMove;
|
||||
use super::{
|
||||
CommandSpec, Result, Session, bad, bool_or, check_numbers, check_switches, checked_id, checked_ids_param, checked_node, checked_nodes_param, cmd,
|
||||
color_value, f64_or, has_doc, has_selection, ids_param, index, object_param, ok, str_param, switch_or,
|
||||
@@ -83,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Layer Options…",
|
||||
["Window", "Layers"],
|
||||
None,
|
||||
"{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked, and `ids` may name ruler guides (their `guide.list` id), which hide or lock on their own. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. One undo step",
|
||||
"{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked, and `ids` may name ruler guides (their `guide.list` id), which hide or lock on their own. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. A path directly in a Live Paint group can't take the name Face or Edge, which name the group's faces and edges, unless it has it already. One undo step",
|
||||
has_doc,
|
||||
set_props
|
||||
),
|
||||
@@ -110,7 +111,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Rows",
|
||||
[],
|
||||
None,
|
||||
"{ids|id, target, place?: \"above\"|\"below\"|\"inside\" (default inside), copy?: bool} drag rows in the Layers panel: above or below the target row (beside it, in its layer or group), or inside a layer, group or Intertwine group (on top of its contents). Layers go only in layers or at the top level, objects in layers, groups and Intertwine groups; an object placed beside a top-level layer goes inside it. An object placed in an Intertwine group becomes a member drawn in its row's order, with no arranged areas, and one placed in a group that is a member becomes part of that member; one that is or holds an Intertwine group, a Repeat, a graph or a Live Paint group is refused. A member moved out of its Intertwine group drops its arranged areas, and a group left with one member is replaced by that member, or becomes a plain group of it when the group has an opacity, blending, appearance, mask, lock or hidden state of its own (with no member, it is removed). A row never goes into itself; a locked layer or group takes nothing. `copy` (Alt-drag) moves copies, which may also go above or below a row they copy (the target among `ids`). Every selected object left hidden or locked, such as one moved into a hidden layer or group, is deselected (the key object too). One undo step → {ids}",
|
||||
"{ids|id, target, place?: \"above\"|\"below\"|\"inside\" (default inside), copy?: bool} drag rows in the Layers panel: above or below the target row (beside it, in its layer or group), or inside a layer, group or Intertwine group (on top of its contents). Layers go only in layers or at the top level, objects in layers, groups and Intertwine groups; an object placed beside a top-level layer goes inside it. An object placed in an Intertwine group becomes a member drawn in its row's order, with no arranged areas, and one placed in a group that is a member becomes part of that member; one that is or holds an Intertwine group, a Repeat, a graph or a Live Paint group is refused. A member moved out of its Intertwine group drops its arranged areas, and a group left with one member is replaced by that member, or becomes a plain group of it when the group has an opacity, blending, appearance, mask, lock or hidden state of its own (with no member, it is removed). A row never goes into itself; a locked layer or group takes nothing. `copy` (Alt-drag) moves copies, which may also go above or below a row they copy (the target among `ids`). A row that goes into a Live Paint group from elsewhere joins its paths as livePaint.merge adds them, and the group is selected (paths, compound paths, groups of them and Live Paint groups; anything else is refused and nothing moves); a row that goes into or leaves a Live Paint group's paths makes the group's faces and edges again, keeping the paint of those that stay. Every selected object left hidden or locked, such as one moved into a hidden layer or group, is deselected (the key object too). One undo step → {ids} (a row that joined a Live Paint group is listed as the group)",
|
||||
has_doc,
|
||||
move_rows
|
||||
),
|
||||
@@ -119,7 +120,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reorder",
|
||||
[],
|
||||
None,
|
||||
"{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too)",
|
||||
"{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does",
|
||||
has_doc,
|
||||
move_node
|
||||
),
|
||||
@@ -625,12 +626,22 @@ fn highlight(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"add" | "toggle" => {}
|
||||
other => return Err(bad(C, format!("mode is set, add or toggle, not `{other}`"))),
|
||||
}
|
||||
// `rows` keeps the highlight order. With more than 8 ids, `held` holds the same rows as a set and
|
||||
// answers each lookup; with fewer, each lookup searches `rows`.
|
||||
let mut held: Option<HashSet<NodeId>> = (ids.len() > 8).then(|| rows.iter().copied().collect());
|
||||
let mut last = None;
|
||||
for id in ids {
|
||||
if mode == "toggle" && rows.contains(&id) {
|
||||
let has = held.as_ref().map_or_else(|| rows.contains(&id), |h| h.contains(&id));
|
||||
if mode == "toggle" && has {
|
||||
rows.retain(|r| *r != id);
|
||||
} else if !rows.contains(&id) {
|
||||
if let Some(h) = &mut held {
|
||||
h.remove(&id);
|
||||
}
|
||||
} else if !has {
|
||||
rows.push(id);
|
||||
if let Some(h) = &mut held {
|
||||
h.insert(id);
|
||||
}
|
||||
last = Some(id);
|
||||
}
|
||||
}
|
||||
@@ -651,6 +662,10 @@ fn set_props(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if ids.is_empty() {
|
||||
return Err(bad(C, "no rows"));
|
||||
}
|
||||
if let Some(v) = str_param(p, "name").filter(|v| !v.trim().is_empty()) {
|
||||
let name = if xml_id { vectorcraft_doc::xml_id::to_object_name(v) } else { v.to_string() };
|
||||
super::buildcmds::check_part_name(&s.doc()?.doc, &ids, &name)?;
|
||||
}
|
||||
s.edit("Layer Options", |d, sel| {
|
||||
for id in &ids {
|
||||
apply_options(d.node_mut(*id).ok_or(EngineError::NoNode(*id))?, p, xml_id);
|
||||
@@ -807,7 +822,15 @@ fn move_rows(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if parent.is_some_and(|p| locked_within(d, p)) {
|
||||
return Err(EngineError::Other("the layer or group is locked".into()));
|
||||
}
|
||||
let label = if copy { "Duplicate Rows" } else { "Move Rows" };
|
||||
// Rows that go into a Live Paint group join its paths, as Live Paint › Merge adds them.
|
||||
let live_paint = LivePaintMove::plan(d, &ids, parent, copy)?;
|
||||
let label = if live_paint.joins() {
|
||||
"Merge Live Paint"
|
||||
} else if copy {
|
||||
"Duplicate Rows"
|
||||
} else {
|
||||
"Move Rows"
|
||||
};
|
||||
// Where each moved row comes from (a copy has a new id, so it comes from nowhere), and the
|
||||
// Intertwine groups it leaves.
|
||||
let from: std::collections::HashMap<NodeId, Option<NodeId>> = ids.iter().map(|i| (*i, d.parent_of(*i))).collect();
|
||||
@@ -848,6 +871,7 @@ fn move_rows(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let placed: Vec<(NodeId, Option<NodeId>)> = out.iter().map(|o| (*o, from.get(o).copied().flatten())).collect();
|
||||
super::intertwine::settle_members(d, &placed, &left)?;
|
||||
let out = live_paint.finish(d, sel, &out)?;
|
||||
sel.prune(d);
|
||||
sel.deselect_uneditable(d);
|
||||
Ok(out)
|
||||
@@ -870,11 +894,14 @@ fn move_node(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(what) = super::intertwine::refused_in(d, parent, n) {
|
||||
return Err(bad(C, format!("{what} can't be intertwined")));
|
||||
}
|
||||
let live_paint = LivePaintMove::plan(d, &[id], parent, false)?;
|
||||
let label = if live_paint.joins() { "Merge Live Paint" } else { "Reorder" };
|
||||
let from = d.parent_of(id);
|
||||
let left = super::intertwine::groups_of(d, &[id]);
|
||||
s.edit("Reorder", |d, sel| {
|
||||
s.edit(label, |d, sel| {
|
||||
d.move_node(id, parent, index)?;
|
||||
super::intertwine::settle_members(d, &[(id, from)], &left)?;
|
||||
live_paint.finish(d, sel, &[id])?;
|
||||
sel.prune(d);
|
||||
sel.deselect_uneditable(d);
|
||||
Ok(())
|
||||
|
||||
@@ -132,7 +132,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Locate Object",
|
||||
["Window", "Layers"],
|
||||
None,
|
||||
"{id?, layersOnly?} (default: the last selected object) highlight the object's row; the Layers panel opens the layers around it and scrolls to it, also when the row was already highlighted →{id, ancestry: [layer…, id]}. layersOnly (default false; the panel sends true while Show Layers Only is on, as Locate Layer) highlights the innermost layer or sublayer holding the object instead, or a layer id itself → {id: layer, objectId, ancestry: [layer…]}",
|
||||
"{id?, layersOnly?} (default: the frontmost selected object in the stacking order) highlight the object's row; the Layers panel opens the layers around it and scrolls to it, also when the row was already highlighted → {id, ancestry: [layer…, id]}. layersOnly (default false; the panel sends true while Show Layers Only is on, as Locate Layer) highlights the innermost layer or sublayer holding the object instead, or a layer id itself → {id: layer, objectId, ancestry: [layer…]}",
|
||||
has_doc,
|
||||
locate
|
||||
),
|
||||
@@ -437,7 +437,8 @@ fn locate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = object_param(p, "id", "layer.locate")?;
|
||||
let layers_only = switch_or(p, "layersOnly", false, "layer.locate")?;
|
||||
let st = s.doc_mut()?;
|
||||
let id = id.or_else(|| st.selection.objects.last().copied()).ok_or_else(|| bad("layer.locate", "nothing selected"))?;
|
||||
// With no id, the frontmost selected object in the stacking order, whatever order it was selected in.
|
||||
let id = id.or_else(|| st.selection.in_paint_order(&st.doc).last().copied()).ok_or_else(|| bad("layer.locate", "nothing selected"))?;
|
||||
let mut ancestry = st.doc.ancestry(id).ok_or(EngineError::NoNode(id))?;
|
||||
if layers_only {
|
||||
// Locate Layer: the innermost layer or sublayer holding the object (a layer locates itself).
|
||||
|
||||
@@ -133,7 +133,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Create Object Mosaic…",
|
||||
["Object"],
|
||||
None,
|
||||
"{columns=10, rows=10 (whole numbers, kept within 1..1000), width?, height? (new size in pt; default the image's), spacingX=0, spacingY=0 (pt between tiles), gray?: bool, deleteRaster?: bool} a group of rectangles coloured by the selected image's average tile colours → {id, tiles}",
|
||||
"{columns=10, rows=10 (whole numbers, kept within 1..1000), width?, height? (new size in pt, 0.1..1000000; default the image's), percentages?: bool (width and height are percentages of the image's size, default 100), constrain?: \"width\"|\"height\"|null (Constrain Ratio: the mosaic keeps the image's proportions, the named side's size leads and the other side's is worked out from it, both growing or shrinking in proportion to keep the sizes within 0.1..1000000), useRatio?: bool|\"width\"|\"height\" (square tiles as drawn, spacing taken off: the count on the side named, or with true on the constrained side, columns by default, stays and the other is the count, 1..1000, whose tiles come closest to square), spacingX=0, spacingY=0 (pt between tiles), gray?: bool, deleteRaster?: bool} a group of rectangles colored by the selected image's average tile colors → {id, tiles, columns, rows}",
|
||||
has_image,
|
||||
object_mosaic
|
||||
),
|
||||
@@ -970,7 +970,23 @@ pub(crate) fn has_image(s: &Session) -> std::result::Result<(), String> {
|
||||
}
|
||||
}
|
||||
|
||||
fn object_mosaic(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// What `object.createObjectMosaic` makes from its params: the image, the tile counts, the tiles'
|
||||
/// placement, their size and spacing in image pixels, and the options.
|
||||
struct MosaicPlan {
|
||||
id: NodeId,
|
||||
im: ImageObject,
|
||||
cols: u32,
|
||||
rows: u32,
|
||||
xf: Affine,
|
||||
tile: (f64, f64),
|
||||
gap: (f64, f64),
|
||||
gray: bool,
|
||||
delete: bool,
|
||||
}
|
||||
|
||||
/// The mosaic `object.createObjectMosaic` would make from `p`, worked out without decoding the
|
||||
/// image or changing the document.
|
||||
fn mosaic_plan(s: &Session, p: &Value) -> Result<MosaicPlan> {
|
||||
const C: &str = "object.createObjectMosaic";
|
||||
let st = s.doc()?;
|
||||
let id = st
|
||||
@@ -980,28 +996,97 @@ fn object_mosaic(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.copied()
|
||||
.find(|id| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Image(_))))
|
||||
.ok_or_else(|| bad(C, "select an image"))?;
|
||||
let node = st.doc.node(id).cloned().ok_or(EngineError::NoNode(id))?;
|
||||
let node = st.doc.node(id).ok_or(EngineError::NoNode(id))?;
|
||||
let NodeKind::Image(im) = &node.kind else { return Err(bad(C, "select an image")) };
|
||||
let blob = st.doc.images.get(&im.key).filter(|b| !b.bytes.is_empty()).ok_or_else(|| bad(C, "the image has no embedded pixels"))?;
|
||||
let raster = vectorcraft_trace::Raster::decode(&blob.bytes).map_err(|e| bad(C, e.to_string()))?;
|
||||
let cols = whole_or(p, "columns", 10, C)?.clamp(1, 1000) as u32;
|
||||
let rows = whole_or(p, "rows", 10, C)?.clamp(1, 1000) as u32;
|
||||
if !st.doc.images.get(&im.key).is_some_and(|b| !b.bytes.is_empty()) {
|
||||
return Err(bad(C, "the image has no embedded pixels"));
|
||||
}
|
||||
let mut cols = whole_or(p, "columns", 10, C)?.clamp(1, 1000) as u32;
|
||||
let mut rows = whole_or(p, "rows", 10, C)?.clamp(1, 1000) as u32;
|
||||
let gray = switch_or(p, "gray", false, C)?;
|
||||
let colors = vectorcraft_trace::mosaic(&raster, cols, rows);
|
||||
let percentages = switch_or(p, "percentages", false, C)?;
|
||||
// A side named "width" (true) or "height" (false), as `constrain` and `useRatio` take it.
|
||||
let side = |key: &str, v: &Value, also: &str| match v.as_str() {
|
||||
Some("width") => Ok(true),
|
||||
Some("height") => Ok(false),
|
||||
_ => Err(bad(C, format!("`{key}` must be one of {}", format_args!("\"width\", \"height\"{also} or null")))),
|
||||
};
|
||||
let constrain = match p.get("constrain") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(v) => Some(side("constrain", v, "")?),
|
||||
};
|
||||
// Use Ratio's kept side: true keeps Constrain Ratio's side (the width when it is left out).
|
||||
let use_ratio = match p.get("useRatio") {
|
||||
None | Some(Value::Null | Value::Bool(false)) => None,
|
||||
Some(Value::Bool(true)) => Some(constrain.unwrap_or(true)),
|
||||
Some(v) => Some(side("useRatio", v, ", true, false")?),
|
||||
};
|
||||
// Tiles in image space, placed by the image transform (scaled to a new size if asked).
|
||||
let b = node.geometric_bounds().ok_or_else(|| bad(C, "image has no bounds"))?;
|
||||
check_numbers(p, &["width", "height", "spacingX", "spacingY"], C)?;
|
||||
let (nw, nh) = (f64_or(p, "width", b.width()).max(0.1), f64_or(p, "height", b.height()).max(0.1));
|
||||
let resize = Affine::translate(b.origin().to_vec2())
|
||||
* Affine::scale_non_uniform(nw / b.width().max(1e-9), nh / b.height().max(1e-9))
|
||||
* Affine::translate(-b.origin().to_vec2());
|
||||
let (bw, bh) = (b.width().max(1e-9), b.height().max(1e-9));
|
||||
// A size given (pt, or % of the image's) is from 0.1 to 1,000,000; one left out is the image's.
|
||||
let size = |key: &str, base: f64| -> Result<f64> {
|
||||
let Some(x) = p.get(key).and_then(Value::as_f64) else { return Ok(base) };
|
||||
let (min, max) = (0.1, 1_000_000.0);
|
||||
if !(min..=max).contains(&x) {
|
||||
return Err(bad(C, format!("`{key}` must be between {min} and {max} (got {x})")));
|
||||
}
|
||||
Ok(if percentages { base * x / 100.0 } else { x })
|
||||
};
|
||||
let (mut nw, mut nh) = (size("width", bw)?, size("height", bh)?);
|
||||
// Constrain Ratio keeps the image's proportions: the named side leads and the other follows.
|
||||
match constrain {
|
||||
Some(true) => nh = nw * bh / bw,
|
||||
Some(false) => nw = nh * bw / bh,
|
||||
None => {}
|
||||
}
|
||||
// A size under 0.1 pt grows to 0.1 pt, in proportion while Constrain Ratio keeps it. A side
|
||||
// Constrain Ratio works out above 1,000,000 pt shrinks to 1,000,000 pt, the other with it.
|
||||
let (nw, nh) = match constrain {
|
||||
Some(_) => {
|
||||
let k = (0.1 / nw.min(nh)).max(1.0).min(1_000_000.0 / nw.max(nh));
|
||||
// Proportions over 10,000,000 to 1 leave no size with both sides within the range.
|
||||
if nw.min(nh) * k < 0.1 * (1.0 - 1e-9) {
|
||||
return Err(bad(C, "the image's proportions leave no size with both sides between 0.1 and 1000000 pt"));
|
||||
}
|
||||
(nw * k, nh * k)
|
||||
}
|
||||
None => (nw.max(0.1), nh.max(0.1)),
|
||||
};
|
||||
let resize = Affine::translate(b.origin().to_vec2()) * Affine::scale_non_uniform(nw / bw, nh / bh) * Affine::translate(-b.origin().to_vec2());
|
||||
let xf = resize * im.xf;
|
||||
let (tw, th) = (im.width as f64 / cols as f64, im.height as f64 / rows as f64);
|
||||
// Spacing is in points; convert to image pixels along each axis.
|
||||
// Points per image pixel along each of the image's axes (the image may be turned).
|
||||
let ppx = (xf * Point::new(1.0, 0.0) - xf * Point::ZERO).hypot().max(1e-9);
|
||||
let ppy = (xf * Point::new(0.0, 1.0) - xf * Point::ZERO).hypot().max(1e-9);
|
||||
let (gx, gy) = ((f64_or(p, "spacingX", 0.0).max(0.0) / ppx).min(tw * 0.9), (f64_or(p, "spacingY", 0.0).max(0.0) / ppy).min(th * 0.9));
|
||||
let (sx, sy) = (f64_or(p, "spacingX", 0.0).max(0.0), f64_or(p, "spacingY", 0.0).max(0.0));
|
||||
let (iw, ih) = (im.width as f64, im.height as f64);
|
||||
// Use Ratio: square tiles as drawn, spacing taken off, from the count on the kept side,
|
||||
// measured along the image's axes.
|
||||
match use_ratio {
|
||||
Some(true) => rows = mosaic_square_count(cols, iw * ppx, ih * ppy, sx, sy),
|
||||
Some(false) => cols = mosaic_square_count(rows, ih * ppy, iw * ppx, sy, sx),
|
||||
None => {}
|
||||
}
|
||||
let (tw, th) = (iw / cols as f64, ih / rows as f64);
|
||||
// Spacing is in points; convert to image pixels along each axis.
|
||||
let gap = ((sx / ppx).min(tw * 0.9), (sy / ppy).min(th * 0.9));
|
||||
let delete = switch_or(p, "deleteRaster", false, C)?;
|
||||
Ok(MosaicPlan { id, im: im.as_ref().clone(), cols, rows, xf, tile: (tw, th), gap, gray, delete })
|
||||
}
|
||||
|
||||
/// The tile counts (columns, rows) `object.createObjectMosaic` would use with `p`, Use Ratio
|
||||
/// included, without making the mosaic (the dialog's Use Ratio button shows them).
|
||||
pub fn mosaic_counts(s: &Session, p: &Value) -> Result<(u32, u32)> {
|
||||
mosaic_plan(s, p).map(|m| (m.cols, m.rows))
|
||||
}
|
||||
|
||||
fn object_mosaic(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.createObjectMosaic";
|
||||
let MosaicPlan { id, im, cols, rows, xf, tile: (tw, th), gap: (gx, gy), gray, delete } = mosaic_plan(s, p)?;
|
||||
let blob = s.doc()?.doc.images.get(&im.key).ok_or_else(|| bad(C, "the image has no embedded pixels"))?;
|
||||
let raster = vectorcraft_trace::Raster::decode(&blob.bytes).map_err(|e| bad(C, e.to_string()))?;
|
||||
let colors = vectorcraft_trace::mosaic(&raster, cols, rows);
|
||||
let (gid, n) = s.edit("Create Object Mosaic", |d, sel| {
|
||||
let mut tiles = vec![];
|
||||
for r in 0..rows {
|
||||
@@ -1039,7 +1124,32 @@ fn object_mosaic(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
sel.set([gid]);
|
||||
Ok((gid, n))
|
||||
})?;
|
||||
Ok(json!({ "id": gid.0, "tiles": n }))
|
||||
Ok(json!({ "id": gid.0, "tiles": n, "columns": cols, "rows": rows }))
|
||||
}
|
||||
|
||||
/// The tile count along one side of an Object Mosaic whose tiles, as drawn, come closest to square
|
||||
/// (Use Ratio): `kept` tiles span `kept_len` on the other side, and this side is `other_len` long.
|
||||
/// Each tile is its cell less the gap on its side (`kept_gap`, `other_gap`), and a gap takes at
|
||||
/// most 90% of a cell, as the tiles are drawn. Within 1..1000, the smaller count on a tie; all
|
||||
/// lengths in points.
|
||||
pub(crate) fn mosaic_square_count(kept: u32, kept_len: f64, other_len: f64, kept_gap: f64, other_gap: f64) -> u32 {
|
||||
let drawn = |len: f64, n: u32, gap: f64| {
|
||||
let cell = len / n.max(1) as f64;
|
||||
cell - gap.max(0.0).min(cell * 0.9)
|
||||
};
|
||||
let side = drawn(kept_len, kept, kept_gap);
|
||||
if !(side.is_finite() && side > 0.0 && other_len.is_finite() && other_len > 0.0) {
|
||||
return 1;
|
||||
}
|
||||
// A tile on this side shrinks as the count grows: find the first count whose tile is no wider
|
||||
// than `side`, then take it or the count before it, whichever is closer.
|
||||
let (mut lo, mut hi) = (1u32, 1000u32);
|
||||
while lo < hi {
|
||||
let mid = (lo + hi) / 2;
|
||||
if drawn(other_len, mid, other_gap) > side { lo = mid + 1 } else { hi = mid }
|
||||
}
|
||||
let off = |n: u32| (drawn(other_len, n, other_gap) - side).abs();
|
||||
if lo > 1 && off(lo - 1) <= off(lo) { lo - 1 } else { lo }
|
||||
}
|
||||
|
||||
fn polygon_path(pts: &[Point]) -> PathData {
|
||||
|
||||
@@ -371,16 +371,21 @@ pub(super) fn isolate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// Leaving isolation mode in `isolated` for `next` (None: out of isolation mode) adds the paths drawn
|
||||
/// in the Live Paint group isolation put new art in to that group, as `livePaint.merge` does, in one
|
||||
/// undo step ([`crate::cmd::buildcmds::merge_drawn_in_isolation`]), unless `next` is that group or is
|
||||
/// inside it; → the group when paths were added.
|
||||
/// in each Live Paint group that is `isolated` or holds it to that group, as `livePaint.merge` does,
|
||||
/// innermost group first, one undo step per group ([`crate::cmd::buildcmds::merge_drawn_in_isolation`]).
|
||||
/// A group that `next` is or is inside is skipped, since isolation stays in it. → the outermost group
|
||||
/// that paths were added to.
|
||||
fn add_drawn_live_paint(s: &mut Session, isolated: NodeId, next: Option<NodeId>) -> Result<Option<NodeId>> {
|
||||
let d = &s.doc()?.doc;
|
||||
let Some(g) = crate::cmd::buildcmds::isolated_live_paint(d, isolated) else { return Ok(None) };
|
||||
if next.is_some_and(|n| d.ancestry(n).is_some_and(|a| a.contains(&g))) {
|
||||
return Ok(None);
|
||||
let stays = next.and_then(|n| d.ancestry(n)).unwrap_or_default();
|
||||
let left: Vec<NodeId> = crate::cmd::buildcmds::isolated_live_paints(d, isolated).into_iter().filter(|g| !stays.contains(g)).collect();
|
||||
let mut added = None;
|
||||
for g in left {
|
||||
if crate::cmd::buildcmds::merge_drawn_in_isolation(s, g)? {
|
||||
added = Some(g);
|
||||
}
|
||||
}
|
||||
Ok(crate::cmd::buildcmds::merge_drawn_in_isolation(s, g)?.then_some(g))
|
||||
Ok(added)
|
||||
}
|
||||
|
||||
pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -250,7 +250,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Exit Isolation Mode",
|
||||
[],
|
||||
None,
|
||||
"{all?: bool (default false)} leave isolation mode; from an isolated sublayer, go up one level to its parent layer instead (the next call goes up again), unless all is true or the parent layer is hidden or locked; no undo step for the move up; while a symbol is edited, a group isolated in its art goes back to the symbol's layer first, with or without all; leaving an isolated Live Paint group adds the paths, compound paths and groups of them drawn in it (shown and unlocked with everything in them) to the group as livePaint.merge does, in one undo step, and leaves type, images and other objects in it as they are; object.isolate on a level outside the group does the same",
|
||||
"{all?: bool (default false)} leave isolation mode; from an isolated sublayer, go up one level to its parent layer instead (the next call goes up again), unless all is true or the parent layer is hidden or locked; no undo step for the move up; while a symbol is edited, a group isolated in its art goes back to the symbol's layer first, with or without all; leaving an isolated Live Paint group adds the paths, compound paths and groups of them drawn in it (shown and unlocked with everything in them) to the group as livePaint.merge does, in one undo step, and leaves type, images and other objects in it as they are; object.isolate on a level outside the group does the same. Leaving a Live Paint group drawn in another isolated Live Paint group, and that group too, does this for each, innermost first, one undo step each",
|
||||
has_doc,
|
||||
exit_isolation
|
||||
),
|
||||
@@ -259,7 +259,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Object Properties",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?, name?, visible?, locked? (visible: false or locked: true deselects every selected object hidden or locked after the call, the key object included), opacity?: 0..100, blend?: \"Multiply\"…, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, data?: {key: \"value\" | null (removes it)} (the object's own data, SVG data-* attributes: {pivot: \"100,180\"} is data-pivot; document.node → attrs.data)}. On a path directly in a graph series, the graph also stores the object's opacity and blend mode, and on a series group the group's opacity, blend mode, isolate, knockout and knockoutShape (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's opacity and blend mode for every label or line of its kind",
|
||||
"{ids?|id?, name?, visible?, locked? (visible: false or locked: true deselects every selected object hidden or locked after the call, the key object included), opacity?: 0..100, blend?: \"Multiply\"…, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, data?: {key: \"value\" | null (removes it)} (the object's own data, SVG data-* attributes: {pivot: \"100,180\"} is data-pivot; document.node → attrs.data)}. On a path directly in a graph series, the graph also stores the object's opacity and blend mode, and on a series group the group's opacity, blend mode, isolate, knockout and knockoutShape (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's opacity and blend mode for every label or line of its kind. A path directly in a Live Paint group can't take the name Face or Edge, which name the group's faces and edges, unless it has it already",
|
||||
has_doc,
|
||||
set_props
|
||||
),
|
||||
|
||||
@@ -65,6 +65,9 @@ pub(super) fn set_props(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})
|
||||
};
|
||||
let d = &s.doc()?.doc;
|
||||
if let Some(v) = str_param(p, "name") {
|
||||
crate::cmd::buildcmds::check_part_name(d, &ids, v)?;
|
||||
}
|
||||
// A graph keeps the object opacity and blend mode set on a mark of a series for the whole series, and set on a label
|
||||
// for its kind of label, so a value a mark or label already has still replaces the one another left on the graph.
|
||||
let transparency = opacity.is_some() || blend.is_some();
|
||||
|
||||
@@ -171,8 +171,6 @@ fn parse(xml: &str, name: &str, cmd: &str) -> Result<El> {
|
||||
craft_xml::Error::TooDeep(_) => bad(cmd, format!("`{name}` in the Word document nests elements more than {MAX_NESTING} deep")),
|
||||
_ => bad(cmd, format!("`{name}` in the Word document is not well-formed XML: {e}")),
|
||||
})?;
|
||||
crate::cmd::xmlattrs::validate(xml.as_bytes(), opts.limits)
|
||||
.map_err(|e| bad(cmd, format!("`{name}` in the Word document is not well-formed XML: {e}")))?;
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
|
||||
@@ -88,6 +88,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"addon.type.textTweaker",
|
||||
"addon.units.convert",
|
||||
"addon.units.selectionSize",
|
||||
"app.toast",
|
||||
"appearance.addEffect",
|
||||
"appearance.addFill",
|
||||
"appearance.addStroke",
|
||||
@@ -177,6 +178,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"edit.duplicate",
|
||||
"edit.findNext",
|
||||
"edit.findReplace",
|
||||
"edit.replaceMatch",
|
||||
"effect.apply",
|
||||
"effect.deferredStatus",
|
||||
"effect.duplicate",
|
||||
@@ -689,6 +691,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"type.pathOptions",
|
||||
"type.resetHorizontalScale",
|
||||
"type.resetTracking",
|
||||
"type.retype",
|
||||
"type.ruby",
|
||||
"type.scaleTextAttributes",
|
||||
"type.size.decrease",
|
||||
|
||||
@@ -34,7 +34,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Recolor Artwork",
|
||||
["Edit", "Edit Colors"],
|
||||
None,
|
||||
"{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null | \"keep\"] (what `group` is rewritten with, a null removing the group's swatch at its place and \"keep\" leaving that swatch its colour, without the Global Adjust (past the swatches it adds nothing; refused for a swatch that is not a colour); default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}",
|
||||
"{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null | \"keep\"] (what the color swatches of `group` are rewritten with, in order: a gradient, pattern or None swatch keeps its place and paint; a null removing the color swatch at its place and \"keep\" leaving that swatch its colour, without the Global Adjust (past the color swatches it adds nothing); default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}",
|
||||
has_doc,
|
||||
apply
|
||||
),
|
||||
@@ -1680,12 +1680,18 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(Value::Array(cs)) => Some(cs),
|
||||
Some(_) => return Err(bad(C, "`groupColors` must be an array")),
|
||||
};
|
||||
// A null in groupColors removes the group's swatch at its place, and "keep" leaves the swatch
|
||||
// at its place its color, without the Global Adjust.
|
||||
let own: Vec<Option<Color>> = match group {
|
||||
Some(g) => {
|
||||
s.doc()?.doc.swatch_groups.iter().find(|x| x.name == g).map(|g| g.swatches.iter().map(|w| w.paint.color()).collect()).unwrap_or_default()
|
||||
}
|
||||
// The places of groupColors are those of the group's color swatches: a gradient, pattern or
|
||||
// None swatch keeps its place and paint. A null removes the color swatch at its place, and
|
||||
// "keep" leaves it its color, without the Global Adjust.
|
||||
let own: Vec<Color> = match group {
|
||||
Some(g) => s
|
||||
.doc()?
|
||||
.doc
|
||||
.swatch_groups
|
||||
.iter()
|
||||
.find(|x| x.name == g)
|
||||
.map(|g| g.swatches.iter().filter_map(|w| w.paint.color()).collect())
|
||||
.unwrap_or_default(),
|
||||
None => vec![],
|
||||
};
|
||||
let new: Vec<Option<Color>> = match group_colors {
|
||||
@@ -1694,12 +1700,8 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.enumerate()
|
||||
.map(|(i, v)| match v {
|
||||
Value::Null => Ok(None),
|
||||
// Past the group's swatches it adds nothing.
|
||||
Value::String(k) if k == "keep" => match own.get(i) {
|
||||
Some(Some(c)) => Ok(Some(*c)),
|
||||
Some(None) => Err(bad(C, format!("the swatch at place {i} of groupColors is not a colour to keep"))),
|
||||
None => Ok(None),
|
||||
},
|
||||
// Past the group's color swatches it adds nothing.
|
||||
Value::String(k) if k == "keep" => Ok(own.get(i).copied()),
|
||||
v => color_value(v)
|
||||
.map(|c| adjust.apply(c))
|
||||
.map(|c| Some(in_doc_model(palette.as_ref().map_or(c, |pl| pl.nearest(c)))))
|
||||
@@ -1747,6 +1749,7 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.map(|g| {
|
||||
g.swatches
|
||||
.iter()
|
||||
.filter(|w| w.paint.color().is_some())
|
||||
.zip(&new)
|
||||
.filter(|(w, _)| w.global && !w.is_reserved())
|
||||
.filter_map(|(w, c)| Some((w, (*c)?)))
|
||||
@@ -1766,7 +1769,7 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.collect();
|
||||
map.converted.set(false);
|
||||
let changed = keeping_series_paint(d, &ids, |d| Ok(Recolor::with_links(scope, &f, &lf).run(d, &ids)))?;
|
||||
let edit = group.map(|g| super::swatch::rewrite_group(d, g, &new, rename, C)).transpose()?;
|
||||
let edit = group.map(|g| super::swatch::rewrite_group(d, g, &new, true, rename, C)).transpose()?;
|
||||
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))?;
|
||||
// Rewriting the group's swatches can change the colors of art linked to them, left out or
|
||||
// not, and of the patterns it uses. Art that only loses its link keeps its colors and is
|
||||
|
||||
@@ -0,0 +1,619 @@
|
||||
//! Type › Retype (#4934), phase 1: outlined text whose glyph shapes are glyphs of a font the app
|
||||
//! has becomes live point text again, in that font and size, at the same baseline.
|
||||
//!
|
||||
//! Behaviour follows the public description of Illustrator's Retype
|
||||
//! (<https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html>,
|
||||
//! <https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html>):
|
||||
//! select outlined text and Retype finds the fonts that match it, from the fonts on the device among
|
||||
//! others, for use as live text. Illustrator ranks candidate fonts in a panel; this phase is local
|
||||
//! and exact instead, and sets the text itself, as #4934 asks. Each selected glyph shape (a path or compound
|
||||
//! path, inside groups too) is compared with the glyphs of the candidate fonts
|
||||
//! ([`vectorcraft_text::retype`]), the same up to uniform scale, rotation and translation. Matched
|
||||
//! glyphs map back to characters through the font's cmap and are rebuilt as point text, one object
|
||||
//! per line of glyphs, with the first glyph's fill and stroke. Shapes that match no font stay as
|
||||
//! they are and are reported. Near matches (another version of the font, simplified outlines,
|
||||
//! merged glyphs) and images are phase 2.
|
||||
|
||||
use std::f64::consts::{PI, TAU};
|
||||
use std::sync::Arc;
|
||||
|
||||
use kurbo::{BezPath, Point, Vec2};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Appearance, CharStyle, Document, Node, NodeId, NodeKind, TextObject};
|
||||
use vectorcraft_text::FontDb;
|
||||
use vectorcraft_text::retype::{GlyphMatch, RetypeIndex};
|
||||
|
||||
use super::edit::selected_roots;
|
||||
use super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_selected_path};
|
||||
|
||||
/// At most this many shapes are compared.
|
||||
const MAX_PIECES: usize = 2048;
|
||||
/// Groups deeper than this are not looked into.
|
||||
const MAX_DEPTH: usize = 16;
|
||||
/// Extra families named by `fonts`.
|
||||
const MAX_FONT_PARAMS: usize = 32;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"type.retype",
|
||||
"Retype",
|
||||
["Type"],
|
||||
None,
|
||||
"{fonts?: [family…]} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live point text: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation (exact matches only); matched glyphs become point text in that font and size at the same baseline, one object per line, with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line splits where its type would not draw the outlines' glyphs in their places (tracking, manual spacing, font substitutions); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts, fonts: [{family, style, size}], unmatched: [id…], truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error when no shape matches",
|
||||
has_selected_path,
|
||||
retype
|
||||
)]
|
||||
}
|
||||
|
||||
/// A shape to match: a path or compound path, in document space.
|
||||
struct Piece {
|
||||
id: NodeId,
|
||||
/// The group or layer holding it: glyphs of different groups, which may composite
|
||||
/// differently, never share a line.
|
||||
parent: Option<NodeId>,
|
||||
/// Other art (not retyped) lies between it and the shape before it, so the type after that
|
||||
/// art must stay painted after it: the line ends here.
|
||||
after_barrier: bool,
|
||||
path: BezPath,
|
||||
appearance: Appearance,
|
||||
/// The shape's own transparency, which the new type takes.
|
||||
opacity: f32,
|
||||
blend: vectorcraft_color::BlendMode,
|
||||
/// The shape has what type cannot take (its own opacity mask, more than one fill or stroke,
|
||||
/// effects, a brush, width profile or arrowheads): it stays an outline.
|
||||
keeps_outline: bool,
|
||||
}
|
||||
|
||||
/// The shapes in `n` (held by `parent`), in paint order. `barrier` is set when art that is not a
|
||||
/// shape lies before the next one; it starts set for a root that does not follow the last root.
|
||||
/// `truncated` is set when shapes past [`MAX_PIECES`] or [`MAX_DEPTH`] were left out.
|
||||
fn collect(n: &Node, parent: Option<NodeId>, depth: usize, barrier: &mut bool, truncated: &mut bool, out: &mut Vec<Piece>) {
|
||||
if out.len() >= MAX_PIECES || depth > MAX_DEPTH {
|
||||
*barrier = true;
|
||||
*truncated = true;
|
||||
return;
|
||||
}
|
||||
// Hidden and locked art is left as it is: a hidden glyph must not come back as visible type.
|
||||
if !n.visible || n.locked {
|
||||
*barrier = true;
|
||||
return;
|
||||
}
|
||||
let piece = |path: BezPath, after_barrier: bool| Piece {
|
||||
id: n.id,
|
||||
parent,
|
||||
after_barrier,
|
||||
path,
|
||||
appearance: (*n.appearance).clone(),
|
||||
opacity: n.opacity,
|
||||
blend: n.blend,
|
||||
keeps_outline: n.extras().mask.is_some() || !type_can_paint(&n.appearance),
|
||||
};
|
||||
match &n.kind {
|
||||
NodeKind::Group { children, clip: false } => {
|
||||
for c in children {
|
||||
collect(c, Some(n.id), depth + 1, barrier, truncated, out);
|
||||
}
|
||||
}
|
||||
// Only closed shapes can be glyphs: an open path stroked along a glyph's outline is not one.
|
||||
NodeKind::Path { path, clipping: false, guide: false, .. } if path.is_closed() => out.push(piece(path.to_bezpath(), std::mem::take(barrier))),
|
||||
NodeKind::Compound { children, .. } => {
|
||||
let mut path = BezPath::new();
|
||||
for c in children {
|
||||
match &c.kind {
|
||||
// A hidden or locked path keeps its whole compound as it is.
|
||||
NodeKind::Path { path: p, .. } if p.is_closed() && c.visible && !c.locked => path.extend(p.to_bezpath()),
|
||||
_ => {
|
||||
*barrier = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push(piece(path, std::mem::take(barrier)));
|
||||
}
|
||||
// Live type, images, clip groups and the rest stay, and the type after them stays after them.
|
||||
_ => *barrier = true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Can type's character style paint `ap` as it is: a basic appearance (at most one fill and one
|
||||
/// stroke, no effects, no item opacity or blend), with a plain stroke?
|
||||
fn type_can_paint(ap: &Appearance) -> bool {
|
||||
ap.is_basic() && ap.stroke().is_none_or(|s| s.start_arrow.is_none() && s.end_arrow.is_none() && s.profile.is_none() && s.brush.is_none())
|
||||
}
|
||||
|
||||
/// The faces to match against: the families in `fonts`, the document's fonts, then every loaded face.
|
||||
fn candidate_faces(db: &FontDb, d: &Document, fonts: &[String]) -> Vec<Arc<vectorcraft_text::FontFace>> {
|
||||
let mut families: Vec<String> = fonts.iter().take(MAX_FONT_PARAMS).cloned().collect();
|
||||
d.walk(|n| {
|
||||
if let NodeKind::Text(t) = &n.kind {
|
||||
for r in &t.runs {
|
||||
if !families.contains(&r.style.font_family) && families.len() < vectorcraft_text::retype::MAX_FACES {
|
||||
families.push(r.style.font_family.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
let cap = vectorcraft_text::retype::MAX_FACES;
|
||||
let mut faces = vec![];
|
||||
'families: for f in &families {
|
||||
for style in db.styles(f) {
|
||||
// No more faces are loaded than the index takes.
|
||||
if faces.len() >= cap {
|
||||
break 'families;
|
||||
}
|
||||
if let Some(face) = db.face(f, &style)
|
||||
&& !faces.iter().any(|k: &Arc<vectorcraft_text::FontFace>| k.id() == face.id())
|
||||
{
|
||||
faces.push(face);
|
||||
}
|
||||
}
|
||||
}
|
||||
for face in db.loaded_faces() {
|
||||
if faces.len() >= cap {
|
||||
break;
|
||||
}
|
||||
if !faces.iter().any(|k| k.id() == face.id()) {
|
||||
faces.push(face);
|
||||
}
|
||||
}
|
||||
faces
|
||||
}
|
||||
|
||||
/// One line of retyped glyphs.
|
||||
struct Line {
|
||||
pieces: Vec<NodeId>,
|
||||
/// What each piece matched, as `pieces`.
|
||||
matches: Vec<GlyphMatch>,
|
||||
/// Every glyph the first piece fits, while the line holds only it: the next glyph may tell
|
||||
/// which one it is (see [`join`]).
|
||||
first_cands: Vec<GlyphMatch>,
|
||||
text: String,
|
||||
face: Arc<vectorcraft_text::FontFace>,
|
||||
scale: f64,
|
||||
angle: f64,
|
||||
origin: Point,
|
||||
end: Point,
|
||||
appearance: Appearance,
|
||||
parent: Option<NodeId>,
|
||||
opacity: f32,
|
||||
blend: vectorcraft_color::BlendMode,
|
||||
}
|
||||
|
||||
impl Line {
|
||||
fn dir(&self) -> Vec2 {
|
||||
Vec2::new(self.angle.cos(), self.angle.sin())
|
||||
}
|
||||
|
||||
/// Does glyph `m` of shape `pc` continue this line (same group, paint and transparency, same
|
||||
/// font, size and turn, on its baseline, after its end)?
|
||||
fn continues(&self, pc: &Piece, m: &GlyphMatch) -> bool {
|
||||
let size = self.scale * self.face.units_per_em();
|
||||
let d = m.origin - self.origin;
|
||||
let dir = self.dir();
|
||||
let across = d.cross(dir).abs();
|
||||
pc.parent == self.parent
|
||||
&& pc.appearance == self.appearance
|
||||
&& pc.opacity == self.opacity
|
||||
&& pc.blend == self.blend
|
||||
&& m.face.id() == self.face.id()
|
||||
// One size and turn for the whole line: the type sets every glyph at the first one's.
|
||||
&& (m.scale - self.scale).abs() <= self.scale * 1e-4
|
||||
// Wrapped: type turned 180° has angles near +π and −π.
|
||||
&& ((m.angle - self.angle + PI).rem_euclid(TAU) - PI).abs() < 1e-5
|
||||
&& across < size * 0.05
|
||||
&& (m.origin - self.end).dot(dir) > -size * 0.25
|
||||
}
|
||||
|
||||
fn push(&mut self, id: NodeId, m: &GlyphMatch) {
|
||||
// A gap wider than half a space before the glyph is spaces the outlines left no shape for.
|
||||
let dir = self.dir();
|
||||
let gap = (m.origin - self.end).dot(dir);
|
||||
let space = space_advance(&self.face) * self.scale;
|
||||
if space > 0.0 && gap > space * 0.5 {
|
||||
let n = ((gap / space).round() as usize).clamp(1, 64);
|
||||
self.text.extend(std::iter::repeat_n(' ', n));
|
||||
}
|
||||
self.text.push(m.ch);
|
||||
self.pieces.push(id);
|
||||
self.matches.push(m.clone());
|
||||
self.end = m.origin + dir * (m.face.advance(m.gid) * m.scale);
|
||||
}
|
||||
|
||||
/// The line of this one's glyphs `from..to`, with its group, paint and transparency.
|
||||
fn part(&self, from: usize, to: usize) -> Option<Line> {
|
||||
let (ids, ms) = (self.pieces.get(from..to)?, self.matches.get(from..to)?);
|
||||
let (first, m) = (ids.first()?, ms.first()?);
|
||||
let dir = Vec2::new(m.angle.cos(), m.angle.sin());
|
||||
let mut l = Line {
|
||||
pieces: vec![*first],
|
||||
matches: vec![m.clone()],
|
||||
first_cands: vec![],
|
||||
text: m.ch.to_string(),
|
||||
face: m.face.clone(),
|
||||
scale: m.scale,
|
||||
angle: m.angle,
|
||||
origin: m.origin,
|
||||
end: m.origin + dir * (m.face.advance(m.gid) * m.scale),
|
||||
appearance: self.appearance.clone(),
|
||||
parent: self.parent,
|
||||
opacity: self.opacity,
|
||||
blend: self.blend,
|
||||
};
|
||||
for (id, m) in ids.iter().zip(ms).skip(1) {
|
||||
l.push(*id, m);
|
||||
}
|
||||
Some(l)
|
||||
}
|
||||
|
||||
/// The point type that sets this line.
|
||||
fn text_object(&self, system_layout: bool) -> TextObject {
|
||||
let style = CharStyle {
|
||||
font_family: self.face.family.clone(),
|
||||
font_style: self.face.style.clone(),
|
||||
// The version that matched, when two of the family and style are loaded.
|
||||
font_version: (!self.face.version.is_empty()).then(|| self.face.version.clone()),
|
||||
// Each outlined glyph was drawn on its own; a ligature would draw another shape.
|
||||
features: vec!["-liga".into()],
|
||||
size: self.scale * self.face.units_per_em(),
|
||||
fill: self.appearance.fill_paint(),
|
||||
stroke: self.appearance.stroke_paint(),
|
||||
stroke_width: self.appearance.stroke_width(),
|
||||
..Default::default()
|
||||
};
|
||||
let mut style = style;
|
||||
if let Some(st) = self.appearance.stroke() {
|
||||
style.stroke_cap = st.cap;
|
||||
style.stroke_join = st.join;
|
||||
style.stroke_miter_limit = st.miter_limit;
|
||||
style.stroke_dash = st.dash.clone();
|
||||
style.stroke_align = st.align;
|
||||
}
|
||||
let mut t = TextObject::point(self.origin, &self.text, style);
|
||||
if self.angle != 0.0 {
|
||||
t.xf *= kurbo::Affine::rotate(self.angle);
|
||||
}
|
||||
t.para = super::create::new_type_para();
|
||||
t.system_layout = system_layout;
|
||||
super::typecmd::refresh_bounds(&mut t);
|
||||
t
|
||||
}
|
||||
|
||||
/// The first of this line's glyphs its type does not draw as the outlines did: another glyph
|
||||
/// (a substitution the font makes) or the same glyph elsewhere (tracking, manual spacing,
|
||||
/// more space than whole spaces make); `None` when the type draws every glyph in its place.
|
||||
fn first_mismatch(&self, t: &TextObject) -> Option<usize> {
|
||||
let lay = vectorcraft_text::layout(FontDb::global(), t);
|
||||
let mut drawn = lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty());
|
||||
let tol = (self.scale * self.face.units_per_em() * 0.01).max(0.01);
|
||||
for (k, m) in self.matches.iter().enumerate() {
|
||||
let Some(g) = drawn.next() else { return Some(k) };
|
||||
let at = t.xf * (g.xf * Point::ORIGIN);
|
||||
if g.font_id != m.face.id() || g.gid != m.gid || at.distance(m.origin) > tol {
|
||||
return Some(k);
|
||||
}
|
||||
}
|
||||
// Ink the outlines did not have: the last glyph is where it went wrong.
|
||||
drawn.next().map(|_| self.matches.len().saturating_sub(1))
|
||||
}
|
||||
}
|
||||
|
||||
/// `lines` checked against their own layout: a line splits where its type stops drawing the
|
||||
/// outlines, and a glyph its type cannot draw even on its own stays an outline (`unmatched`).
|
||||
/// The glyphs laid out are bounded by a multiple of the number of glyphs.
|
||||
fn verified(lines: Vec<Line>, system_layout: bool, unmatched: &mut Vec<NodeId>) -> Vec<Line> {
|
||||
// Glyphs laid out in all, at most: past it, the glyphs left unchecked stay outlines.
|
||||
let mut budget = lines.iter().map(|l| l.pieces.len()).sum::<usize>().saturating_mul(16).saturating_add(256);
|
||||
let mut todo: std::collections::VecDeque<Line> = lines.into();
|
||||
let mut out = vec![];
|
||||
while let Some(l) = todo.pop_front() {
|
||||
let n = l.pieces.len();
|
||||
// The line's type is laid out over a window from its start that doubles while the type
|
||||
// draws the window's glyphs as the outlines do, so finding where it stops costs about
|
||||
// twice the glyphs before that point, not the whole rest of the line each time.
|
||||
let mut w = 8usize;
|
||||
loop {
|
||||
let e = n.min(w);
|
||||
let Some(part) = l.part(0, e) else { break };
|
||||
let Some(left) = budget.checked_sub(e) else {
|
||||
// Unchecked glyphs stay outlines.
|
||||
unmatched.extend(l.pieces.iter().copied());
|
||||
break;
|
||||
};
|
||||
budget = left;
|
||||
match part.first_mismatch(&part.text_object(system_layout)) {
|
||||
// The whole line is drawn as it was: one object.
|
||||
None if e == n => {
|
||||
out.push(part);
|
||||
break;
|
||||
}
|
||||
None => w = w.saturating_mul(2),
|
||||
// The first glyph on its own may still be drawn as it was (a contextual form
|
||||
// changed it in the line); else it stays an outline. Checked again either way.
|
||||
Some(0) if n > 1 => {
|
||||
todo.extend_front_parts(&l, [(0, 1), (1, n)]);
|
||||
break;
|
||||
}
|
||||
Some(0) => {
|
||||
unmatched.extend(l.pieces.first().copied());
|
||||
break;
|
||||
}
|
||||
// The glyphs before the mismatch, then the rest, each checked as a line of its
|
||||
// own: the type before the mismatch may draw otherwise without what follows it (a
|
||||
// font can place a glyph by the glyph after it).
|
||||
Some(k) => {
|
||||
todo.extend_front_parts(&l, [(0, k), (k, n)]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Puts parts of a line at the front of the work list, in order.
|
||||
trait FrontParts {
|
||||
fn extend_front_parts<const N: usize>(&mut self, l: &Line, ranges: [(usize, usize); N]);
|
||||
}
|
||||
|
||||
impl FrontParts for std::collections::VecDeque<Line> {
|
||||
fn extend_front_parts<const N: usize>(&mut self, l: &Line, ranges: [(usize, usize); N]) {
|
||||
for (a, b) in ranges.into_iter().rev() {
|
||||
if let Some(p) = l.part(a, b) {
|
||||
self.push_front(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn space_advance(face: &vectorcraft_text::FontFace) -> f64 {
|
||||
face.mapped_chars().iter().find(|(c, _)| *c == ' ').map(|(_, g)| face.advance(*g)).unwrap_or(0.0)
|
||||
}
|
||||
|
||||
/// Add shape `pc` to line `l` when one of its candidate glyphs `cands`, in one of its poses,
|
||||
/// continues it (one shape can be several glyphs, and a glyph that looks the same turned fits in
|
||||
/// more than one pose). A line of one shape may turn to another of that shape's candidates to take
|
||||
/// the next one: an L or a turned L half round, an I upright or upside down, and the glyph after it
|
||||
/// tells which. Whether it was added.
|
||||
fn join(l: &mut Line, pc: &Piece, cands: &[GlyphMatch]) -> bool {
|
||||
let fits = |l: &Line| cands.iter().flat_map(|c| c.poses()).find(|mp| l.continues(pc, mp));
|
||||
if let Some(mp) = fits(l) {
|
||||
l.push(pc.id, &mp);
|
||||
return true;
|
||||
}
|
||||
let (Some(id), [current]) = (l.pieces.first().copied(), l.matches.as_slice()) else { return false };
|
||||
let current = current.clone();
|
||||
let others: Vec<GlyphMatch> = l
|
||||
.first_cands
|
||||
.iter()
|
||||
.flat_map(|c| c.poses())
|
||||
.filter(|fp| !(fp.gid == current.gid && fp.face.id() == current.face.id() && fp.angle == current.angle))
|
||||
.collect();
|
||||
for fp in others {
|
||||
let mut turned = reposed(l, id, &fp);
|
||||
if let Some(mp) = fits(&turned) {
|
||||
turned.push(pc.id, &mp);
|
||||
*l = turned;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Line `l`'s group, paint and transparency with glyph `m` (shape `id`) alone on it.
|
||||
fn reposed(l: &Line, id: NodeId, m: &GlyphMatch) -> Line {
|
||||
let dir = Vec2::new(m.angle.cos(), m.angle.sin());
|
||||
Line {
|
||||
pieces: vec![id],
|
||||
matches: vec![m.clone()],
|
||||
first_cands: l.first_cands.clone(),
|
||||
text: m.ch.to_string(),
|
||||
face: m.face.clone(),
|
||||
scale: m.scale,
|
||||
angle: m.angle,
|
||||
origin: m.origin,
|
||||
end: m.origin + dir * (m.face.advance(m.gid) * m.scale),
|
||||
appearance: l.appearance.clone(),
|
||||
parent: l.parent,
|
||||
opacity: l.opacity,
|
||||
blend: l.blend,
|
||||
}
|
||||
}
|
||||
|
||||
/// A new line of shape `pc` alone, as the first of its candidate glyphs `cands` (none: `None`).
|
||||
fn new_line(pc: &Piece, cands: &[GlyphMatch]) -> Option<Line> {
|
||||
let m = cands.first()?;
|
||||
let dir = Vec2::new(m.angle.cos(), m.angle.sin());
|
||||
Some(Line {
|
||||
pieces: vec![pc.id],
|
||||
matches: vec![m.clone()],
|
||||
first_cands: cands.to_vec(),
|
||||
text: m.ch.to_string(),
|
||||
face: m.face.clone(),
|
||||
scale: m.scale,
|
||||
angle: m.angle,
|
||||
origin: m.origin,
|
||||
end: m.origin + dir * (m.face.advance(m.gid) * m.scale),
|
||||
appearance: pc.appearance.clone(),
|
||||
parent: pc.parent,
|
||||
opacity: pc.opacity,
|
||||
blend: pc.blend,
|
||||
})
|
||||
}
|
||||
|
||||
fn retype(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "type.retype";
|
||||
let fonts: Vec<String> = match p.get("fonts") {
|
||||
None | Some(Value::Null) => vec![],
|
||||
Some(Value::Array(a)) => {
|
||||
a.iter().map(|v| v.as_str().map(str::to_owned).ok_or_else(|| bad(C, "fonts must be a list of family names"))).collect::<Result<_>>()?
|
||||
}
|
||||
Some(_) => return Err(bad(C, "fonts must be a list of family names")),
|
||||
};
|
||||
let roots = selected_roots(s)?;
|
||||
let db = FontDb::global();
|
||||
let system_layout = s.doc()?.doc.setup.system_layout;
|
||||
let (lines, unmatched, truncated) = {
|
||||
let d = &s.doc()?.doc;
|
||||
let mut pieces = vec![];
|
||||
let mut truncated = false;
|
||||
let mut last: Option<(Option<NodeId>, usize)> = None;
|
||||
// Carried across roots: a selected root that yields no shape (live type, an open path) still
|
||||
// ends the line.
|
||||
let mut barrier = true;
|
||||
for r in &roots {
|
||||
let Some(n) = d.node(*r) else { continue };
|
||||
let parent = d.parent_of(*r);
|
||||
let idx = d.position(*r).map(|(_, i, _)| i);
|
||||
// A root right after the last one, in the same parent, continues its lines; unselected
|
||||
// art between two roots is a barrier.
|
||||
if !matches!((last, idx), (Some((p, i)), Some(j)) if p == parent && i + 1 == j) {
|
||||
barrier = true;
|
||||
}
|
||||
last = idx.map(|i| (parent, i));
|
||||
collect(n, parent, 0, &mut barrier, &mut truncated, &mut pieces);
|
||||
}
|
||||
if pieces.is_empty() {
|
||||
return Err(EngineError::Other("Retype: select outlined text (paths or compound paths)".into()));
|
||||
}
|
||||
// Only glyphs with a selected shape's key (segments per contour) can match one: the others are
|
||||
// not sampled.
|
||||
let wanted: std::collections::BTreeSet<u64> =
|
||||
pieces.iter().filter(|pc| !pc.keeps_outline).filter_map(|pc| vectorcraft_text::retype::shape_key(&pc.path)).collect();
|
||||
// Nothing to match (every shape stays an outline): no font is read.
|
||||
let index = if wanted.is_empty() { RetypeIndex::default() } else { RetypeIndex::build(db, candidate_faces(db, d, &fonts), &wanted) };
|
||||
let found: Vec<Vec<GlyphMatch>> = pieces.iter().map(|pc| if pc.keeps_outline { vec![] } else { index.matches(&pc.path) }).collect();
|
||||
// The face most shapes match, so a glyph several fonts share is set in the same font as
|
||||
// the glyphs around it.
|
||||
let mut votes: Vec<(u32, usize)> = vec![];
|
||||
for ms in &found {
|
||||
// Each shape votes once for each face it fits.
|
||||
let mut faces: Vec<u32> = ms.iter().map(|m| m.face.id()).collect();
|
||||
faces.sort_unstable();
|
||||
faces.dedup();
|
||||
for f in faces {
|
||||
match votes.iter_mut().find(|(v, _)| *v == f) {
|
||||
Some(v) => v.1 += 1,
|
||||
None => votes.push((f, 1)),
|
||||
}
|
||||
}
|
||||
}
|
||||
let rank = |face: u32| votes.iter().find(|(f, _)| *f == face).map_or(0, |v| v.1);
|
||||
let mut lines: Vec<Line> = vec![];
|
||||
let mut unmatched = vec![];
|
||||
// An unmatched shape between glyphs ends the line: the type after it is painted after it.
|
||||
let mut open = false;
|
||||
for (pc, ms) in pieces.iter().zip(&found) {
|
||||
if pc.after_barrier {
|
||||
open = false;
|
||||
}
|
||||
// The shape's candidates in the face most shapes fit (the first such face, as the
|
||||
// matches come upright and closest first).
|
||||
let face = ms.iter().enumerate().max_by_key(|(i, m)| (rank(m.face.id()), std::cmp::Reverse(*i))).map(|(_, m)| m.face.id());
|
||||
let cands: Vec<GlyphMatch> = ms.iter().filter(|m| Some(m.face.id()) == face).cloned().collect();
|
||||
if cands.is_empty() {
|
||||
unmatched.push(pc.id);
|
||||
open = false;
|
||||
continue;
|
||||
}
|
||||
let joined = match lines.last_mut() {
|
||||
Some(l) if open => join(l, pc, &cands),
|
||||
_ => false,
|
||||
};
|
||||
if !joined {
|
||||
lines.extend(new_line(pc, &cands));
|
||||
}
|
||||
open = true;
|
||||
}
|
||||
// A lone one-contour glyph (a period, a hyphen, a bullet) is too plain to tell from drawn
|
||||
// art (a dot, a bar): beside other shapes it stays an outline. Selected on its own, it is
|
||||
// what was asked for. Lone means alone on its baseline as the outlines lie, before the
|
||||
// layout check splits lines (tracking and manual kerning split them glyph by glyph).
|
||||
let lone_pieces: std::collections::HashSet<NodeId> =
|
||||
lines.iter().filter(|l| matches!(l.matches.as_slice(), [m] if m.contours == 1)).flat_map(|l| l.pieces.iter().copied()).collect();
|
||||
let mut lines = verified(lines, system_layout, &mut unmatched);
|
||||
if pieces.len() > 1 {
|
||||
lines.retain(|l| {
|
||||
let lone = matches!(l.pieces.as_slice(), [id] if lone_pieces.contains(id));
|
||||
if lone {
|
||||
unmatched.extend(l.pieces.iter().copied());
|
||||
}
|
||||
!lone
|
||||
});
|
||||
}
|
||||
(lines, unmatched, truncated)
|
||||
};
|
||||
if lines.is_empty() {
|
||||
return Err(EngineError::Other(format!("Retype: no selected shape matches a glyph of an available font ({} checked)", unmatched.len())));
|
||||
}
|
||||
let made = s.edit("Retype", |d, sel| {
|
||||
let mut ids = vec![];
|
||||
let mut emptied = vec![];
|
||||
for l in &lines {
|
||||
let Some(first) = l.pieces.first() else { continue };
|
||||
let (par, idx, _) = d.position(*first).ok_or(EngineError::NoNode(*first))?;
|
||||
let t = l.text_object(system_layout);
|
||||
let id = d.alloc_id();
|
||||
let mut node = Node::new(id, NodeKind::Text(Box::new(t)));
|
||||
// The glyphs' own transparency (the group's, kept, still applies over it).
|
||||
node.opacity = l.opacity;
|
||||
node.blend = l.blend;
|
||||
d.insert(par, idx, node)?;
|
||||
for pc in &l.pieces {
|
||||
if let Some((Some(parent), _, _)) = d.position(*pc) {
|
||||
emptied.push(parent);
|
||||
}
|
||||
d.remove(*pc)?;
|
||||
}
|
||||
ids.push(id);
|
||||
}
|
||||
// A group left holding only the new type (Create Outlines' group) gives way to it, unless
|
||||
// the group has transparency, effects, a mask or a name of its own, which then keep
|
||||
// applying to the type inside it. A group left empty goes.
|
||||
emptied.sort_unstable();
|
||||
emptied.dedup();
|
||||
for g in emptied {
|
||||
let Some(n) = d.node(g) else { continue };
|
||||
let NodeKind::Group { children, clip: false } = &n.kind else { continue };
|
||||
let plain = n.opacity == 1.0
|
||||
&& n.blend == vectorcraft_color::BlendMode::Normal
|
||||
&& *n.appearance == Appearance::default()
|
||||
&& n.name.is_none()
|
||||
// Its mask, Attributes note and the rest of what few objects have stay with it.
|
||||
&& {
|
||||
let mut ex = n.extras().clone();
|
||||
ex.type_outlines = false;
|
||||
ex == vectorcraft_doc::NodeExtras::default()
|
||||
}
|
||||
// Isolation and knockout change how the group composites its type.
|
||||
&& !n.isolate
|
||||
&& n.knockout == vectorcraft_doc::Knockout::default()
|
||||
&& !n.knockout_shape;
|
||||
let only_type = children.iter().all(|c| ids.contains(&c.id));
|
||||
if children.is_empty() {
|
||||
d.remove(g)?;
|
||||
} else if plain && only_type {
|
||||
let kids: Vec<Arc<Node>> = children.clone();
|
||||
let (par, idx, _) = d.position(g).ok_or(EngineError::NoNode(g))?;
|
||||
d.remove(g)?;
|
||||
for (i, k) in kids.into_iter().enumerate() {
|
||||
d.insert(par, idx + i, (*k).clone())?;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut keep: Vec<NodeId> = roots.iter().copied().filter(|r| d.node(*r).is_some()).collect();
|
||||
keep.extend(&ids);
|
||||
sel.set(keep);
|
||||
Ok(ids)
|
||||
})?;
|
||||
Ok(json!({
|
||||
"ids": made.iter().map(|i| i.0).collect::<Vec<_>>(),
|
||||
"texts": lines.iter().map(|l| l.text.clone()).collect::<Vec<_>>(),
|
||||
"fonts": lines.iter().map(|l| json!({"family": l.face.family, "style": l.face.style, "size": l.scale * l.face.units_per_em()})).collect::<Vec<_>>(),
|
||||
"unmatched": unmatched.iter().map(|i| i.0).collect::<Vec<_>>(),
|
||||
"truncated": truncated,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "retype_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,539 @@
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::{NodeId, NodeKind, TextObject};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// Point text, outlined: the id of the outlines' group.
|
||||
fn outlined(s: &mut Session, p: serde_json::Value) -> u64 {
|
||||
let id = s.execute("text.create", &p).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap()
|
||||
}
|
||||
|
||||
fn text_of(s: &Session, id: u64) -> TextObject {
|
||||
let NodeKind::Text(t) = &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind else { panic!("text object") };
|
||||
(**t).clone()
|
||||
}
|
||||
|
||||
fn near(a: f64, b: f64, tol: f64) -> bool {
|
||||
(a - b).abs() <= tol
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outlined_point_text_retypes_to_the_same_text_font_size_and_place() {
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Retype me, 42!", "size": 36, "font": "Source Sans 3", "style": "Regular"}));
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["Retype me, 42!"]), "{r}");
|
||||
assert_eq!(r["unmatched"], json!([]));
|
||||
let id = r["ids"][0].as_u64().unwrap();
|
||||
let t = text_of(&s, id);
|
||||
assert_eq!(t.plain_text(), "Retype me, 42!");
|
||||
let st = t.first_style();
|
||||
assert_eq!((st.font_family.as_str(), st.font_style.as_str()), ("Source Sans 3", "Regular"));
|
||||
assert!(near(st.size, 36.0, 0.01), "size {}", st.size);
|
||||
let o = t.xf.translation();
|
||||
assert!(near(o.x, 40.0, 0.01) && near(o.y, 100.0, 0.01), "baseline start {o:?}");
|
||||
// The outlines are gone, in one undo step that brings them back.
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.node(NodeId(g)).is_none(), "the emptied group goes");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.node(NodeId(g)).is_some() && d.node(NodeId(id)).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turned_bold_and_serif_type_keeps_its_font_and_angle() {
|
||||
let mut s = session();
|
||||
let a = outlined(&mut s, json!({"x": 100, "y": 200, "text": "Bold", "size": 24, "font": "Source Sans 3", "style": "Bold", "rotation": 30}));
|
||||
let b = outlined(&mut s, json!({"x": 300, "y": 80, "text": "Serif", "size": 18, "font": "Source Serif 4", "style": "Regular"}));
|
||||
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["Bold", "Serif"]), "{r}");
|
||||
let ids: Vec<u64> = r["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
|
||||
let bold = text_of(&s, ids[0]);
|
||||
assert_eq!(bold.first_style().font_style, "Bold");
|
||||
assert!(near(bold.first_style().size, 24.0, 0.01));
|
||||
// text.create turns as kurbo does: compare the turn the new type has with the old one's.
|
||||
let turned = kurbo::Affine::translate((100.0, 200.0)) * vectorcraft_geom::rotate_deg(30.0);
|
||||
for (x, y) in bold.xf.as_coeffs().iter().zip(turned.as_coeffs()) {
|
||||
assert!(near(*x, y, 1e-3), "{:?} vs {:?}", bold.xf, turned);
|
||||
}
|
||||
let serif = text_of(&s, ids[1]);
|
||||
assert_eq!(serif.first_style().font_family, "Source Serif 4");
|
||||
assert!(near(serif.first_style().size, 18.0, 0.01));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_drawn_shape_is_reported_and_left_alone() {
|
||||
let mut s = session();
|
||||
let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 80, "height": 40})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [rect]})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let e = s.execute("type.retype", &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("no selected shape matches"), "{e}");
|
||||
assert!(s.doc().unwrap().doc == before, "nothing changes");
|
||||
// With outlines that would match, a bad `fonts` is refused for itself, and nothing changes.
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "AB", "size": 40}));
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
for bad in [json!("Source Sans 3"), json!([1]), json!({"family": "x"})] {
|
||||
let e = s.execute("type.retype", &json!({"fonts": bad})).unwrap_err().to_string();
|
||||
assert!(e.contains("fonts must be a list of family names"), "{e}");
|
||||
}
|
||||
assert!(s.doc().unwrap().doc == before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_selection_retypes_the_glyphs_and_keeps_the_rest() {
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Mix", "size": 30}));
|
||||
let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 200, "width": 80, "height": 40})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g, rect]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["Mix"]));
|
||||
assert_eq!(r["unmatched"], json!([rect]));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(matches!(d.node(NodeId(rect)).unwrap().kind, NodeKind::Path { .. }), "the rectangle stays");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_words_keep_their_space() {
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 20, "y": 60, "text": "two words", "size": 20}));
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["two words"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn craft_fonts_glyphs_retype_too() {
|
||||
let Some(f) = vectorcraft_text::CRAFT_FONTS.iter().find(|f| f.is_japanese()) else {
|
||||
eprintln!("skipped: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout to run it)");
|
||||
return;
|
||||
};
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 20, "y": 60, "text": "漢字です", "size": 20, "font": f.family, "style": f.style}));
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({"fonts": [f.family]})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["漢字です"]), "{r}");
|
||||
assert_eq!(r["fonts"][0]["family"], json!(f.family));
|
||||
}
|
||||
|
||||
fn children_of(s: &Session, g: u64) -> Vec<u64> {
|
||||
s.doc().unwrap().doc.node(NodeId(g)).unwrap().children().unwrap().iter().map(|c| c.id.0).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shape_between_glyphs_ends_the_line_so_paint_order_holds() {
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40}));
|
||||
let rect = s.execute("shape.rectangle", &json!({"x": 30, "y": 60, "width": 80, "height": 50})).unwrap()["id"].as_u64().unwrap();
|
||||
// The rectangle goes between A and B, inside the outlines' group.
|
||||
s.edit("test", |d, _| {
|
||||
let n = d.node(NodeId(rect)).unwrap().clone();
|
||||
d.remove(NodeId(rect))?;
|
||||
d.insert(Some(NodeId(g)), 1, n)?;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["A", "B"]), "{r}");
|
||||
assert_eq!(r["unmatched"], json!([rect]));
|
||||
let ids: Vec<u64> = r["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
|
||||
assert_eq!(children_of(&s, g), vec![ids[0], rect, ids[1]], "A under the rectangle, B over it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn glyphs_of_different_groups_and_transparency_stay_apart() {
|
||||
let mut s = session();
|
||||
let a = outlined(&mut s, json!({"x": 40, "y": 100, "text": "ab", "size": 20}));
|
||||
let b = outlined(&mut s, json!({"x": 120, "y": 100, "text": "ed", "size": 20}));
|
||||
let first_d = children_of(&s, b)[1];
|
||||
s.edit("test", |d, _| {
|
||||
d.node_mut(NodeId(b)).unwrap().opacity = 0.5;
|
||||
d.node_mut(NodeId(first_d)).unwrap().opacity = 0.25;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["ab", "e", "d"]), "same baseline, other group; d has its own opacity: {r}");
|
||||
let ids: Vec<u64> = r["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.node(NodeId(a)).is_none(), "a plain group gives way to its type");
|
||||
assert_eq!(d.node(NodeId(b)).unwrap().opacity, 0.5, "the half-transparent group stays");
|
||||
assert_eq!(children_of(&s, b), vec![ids[1], ids[2]]);
|
||||
assert_eq!(s.doc().unwrap().doc.node(NodeId(ids[2])).unwrap().opacity, 0.25, "the glyph's own opacity carries over");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn live_type_between_glyphs_ends_the_line_too() {
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40}));
|
||||
let live = s.execute("text.create", &json!({"x": 30, "y": 90, "text": "x", "size": 60})).unwrap()["id"].as_u64().unwrap();
|
||||
s.edit("test", |d, _| {
|
||||
let n = d.node(NodeId(live)).unwrap().clone();
|
||||
d.remove(NodeId(live))?;
|
||||
d.insert(Some(NodeId(g)), 1, n)?;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["A", "B"]), "{r}");
|
||||
let ids: Vec<u64> = r["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
|
||||
assert_eq!(children_of(&s, g), vec![ids[0], live, ids[1]], "B stays over the live type");
|
||||
let t = text_of(&s, ids[0]);
|
||||
assert!(t.first_style().features.iter().any(|f| f == "-liga"), "glyphs drawn one by one: no ligatures");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_path_along_a_glyph_is_not_a_glyph() {
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "I", "size": 40}));
|
||||
s.edit("test", |d, _| {
|
||||
let glyph = d.node(NodeId(g)).unwrap().children().unwrap()[0].id;
|
||||
for sp in &mut d.node_mut(glyph).unwrap().path_data_mut().unwrap().subpaths {
|
||||
sp.closed = false;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
assert!(s.execute("type.retype", &json!({})).is_err(), "nothing matches");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn live_type_selected_between_loose_glyphs_still_ends_the_line() {
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40}));
|
||||
let live = s.execute("text.create", &json!({"x": 30, "y": 90, "text": "x", "size": 60})).unwrap()["id"].as_u64().unwrap();
|
||||
let (a, b) = (children_of(&s, g)[0], children_of(&s, g)[1]);
|
||||
// A, the live type and B as siblings in the layer, as Ungroup leaves them.
|
||||
s.edit("test", |d, _| {
|
||||
let (par, idx, _) = d.position(NodeId(g)).unwrap();
|
||||
let live_n = d.node(NodeId(live)).unwrap().clone();
|
||||
let (an, bn) = (d.node(NodeId(a)).unwrap().clone(), d.node(NodeId(b)).unwrap().clone());
|
||||
d.remove(NodeId(live))?;
|
||||
d.remove(NodeId(g))?;
|
||||
d.insert(par, idx, an)?;
|
||||
d.insert(par, idx + 1, live_n)?;
|
||||
d.insert(par, idx + 2, bn)?;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a, live, b]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["A", "B"]), "the selected live type between them ends the line: {r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn glyphs_selected_inside_groups_join_only_their_siblings() {
|
||||
let mut s = session();
|
||||
let g1 = outlined(&mut s, json!({"x": 40, "y": 100, "text": "ab", "size": 20}));
|
||||
let g2 = outlined(&mut s, json!({"x": 70, "y": 100, "text": "ed", "size": 20}));
|
||||
let (a, b, c) = (children_of(&s, g1)[0], children_of(&s, g1)[1], children_of(&s, g2)[0]);
|
||||
s.execute("select.set", &json!({"ids": [a, b, c]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["ab", "e"]), "a and b are siblings; e is in another group: {r}");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.node(NodeId(g2)).is_some(), "d's group stays with c's type and d in it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tracked_type_splits_where_its_spacing_cannot_be_set_again() {
|
||||
let mut s = session();
|
||||
let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": "abe", "size": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
// Less than half a space: no whole number of spaces makes up the gap (0.4 em would be two
|
||||
// spaces in this font, and the outlines cannot tell those apart from tracking).
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "start": 1, "end": 3, "tracking": 50})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
let texts: Vec<String> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect();
|
||||
assert_eq!(texts.concat(), "abe", "{r}");
|
||||
assert!(texts.len() > 1, "the tracked glyphs are set where the outlines are, not where untracked type puts them: {r}");
|
||||
assert_eq!(r["unmatched"], json!([]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_masked_glyph_stays_an_outline() {
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40}));
|
||||
let a = children_of(&s, g)[0];
|
||||
s.edit("test", |d, _| {
|
||||
let art = vectorcraft_doc::Node::path(d.alloc_id(), vectorcraft_geom::PathData::default(), Default::default());
|
||||
d.node_mut(NodeId(a)).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(art, true)));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["B"]), "{r}");
|
||||
assert_eq!(r["unmatched"], json!([a]));
|
||||
assert!(s.doc().unwrap().doc.node(NodeId(a)).unwrap().extras().mask.is_some(), "A keeps its mask");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shapes_past_the_limits_are_reported_as_left_out() {
|
||||
let mut s = session();
|
||||
let top = outlined(&mut s, json!({"x": 40, "y": 100, "text": "A", "size": 40}));
|
||||
let deep = outlined(&mut s, json!({"x": 40, "y": 200, "text": "B", "size": 40}));
|
||||
// B, deeper than Retype looks.
|
||||
s.edit("test", |d, _| {
|
||||
let (par, idx, _) = d.position(NodeId(deep)).unwrap();
|
||||
let mut n = d.node(NodeId(deep)).unwrap().clone();
|
||||
d.remove(NodeId(deep))?;
|
||||
for _ in 0..20 {
|
||||
n = vectorcraft_doc::Node::group(d.alloc_id(), vec![std::sync::Arc::new(n)]);
|
||||
}
|
||||
let wrapper = n.id.0;
|
||||
d.insert(par, idx, n)?;
|
||||
Ok(wrapper)
|
||||
})
|
||||
.map(|w| s.execute("select.set", &json!({"ids": [top, w]})).unwrap())
|
||||
.unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["A"]));
|
||||
assert_eq!(r["truncated"], json!(true), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_glyph_painted_beyond_what_type_takes_stays_an_outline() {
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40}));
|
||||
let a = children_of(&s, g)[0];
|
||||
s.edit("test", |d, _| {
|
||||
let n = d.node_mut(NodeId(a)).unwrap();
|
||||
let mut ap = (*n.appearance).clone();
|
||||
let fill = ap.items.iter().find(|i| i.is_fill()).unwrap().clone();
|
||||
ap.items.push(fill);
|
||||
n.appearance = ap.into();
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["B"]), "two fills: A stays an outline: {r}");
|
||||
assert_eq!(r["unmatched"], json!([a]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hidden_or_locked_glyph_stays_an_outline() {
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "ABD", "size": 40}));
|
||||
let k = children_of(&s, g);
|
||||
s.edit("test", |d, _| {
|
||||
d.node_mut(NodeId(k[0])).unwrap().visible = false;
|
||||
d.node_mut(NodeId(k[2])).unwrap().locked = true;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["B"]), "{r}");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(!d.node(NodeId(k[0])).unwrap().visible, "A stays a hidden outline");
|
||||
assert!(d.node(NodeId(k[2])).unwrap().locked, "D stays a locked outline");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_isolated_or_knockout_group_keeps_its_type_inside() {
|
||||
for case in ["isolate", "knockout", "knockout_shape"] {
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40}));
|
||||
s.edit("test", |d, _| {
|
||||
let n = d.node_mut(NodeId(g)).unwrap();
|
||||
match case {
|
||||
"isolate" => n.isolate = true,
|
||||
"knockout" => n.knockout = vectorcraft_doc::Knockout::On,
|
||||
_ => n.knockout_shape = true,
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
let id = r["ids"][0].as_u64().unwrap();
|
||||
assert_eq!(children_of(&s, g), vec![id], "{case}: the group stays, holding the type");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn type_turned_half_round_stays_one_object() {
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 300, "y": 200, "text": "Upside", "size": 30, "rotation": 180}));
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["Upside"]), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_drawn_dot_or_bar_beside_type_stays_art() {
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40}));
|
||||
let dot = s.execute("shape.ellipse", &json!({"x": 300, "y": 60, "width": 8, "height": 8})).unwrap()["id"].as_u64().unwrap();
|
||||
// A bar that is exactly a hyphen of the font, somewhere else: the worst case.
|
||||
let bar = outlined(&mut s, json!({"x": 200, "y": 300, "text": "-", "size": 50}));
|
||||
s.execute("select.set", &json!({"ids": [g, dot, bar]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["AB"]), "{r}");
|
||||
let un = r["unmatched"].as_array().unwrap();
|
||||
assert!(un.contains(&json!(dot)) && un.len() == 2, "the dot and the bar stay art: {r}");
|
||||
// Selected on its own, the hyphen is what was asked for.
|
||||
s.execute("select.set", &json!({"ids": [bar]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["-"]), "{r}");
|
||||
}
|
||||
|
||||
/// How long Retype takes with a large CJK face to match against (run with `--ignored
|
||||
/// --nocapture`; skips when no such face is installed). Not a pass/fail budget: it prints.
|
||||
#[test]
|
||||
#[ignore = "timing: needs an installed CJK font"]
|
||||
fn timing_with_a_large_cjk_face() {
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
let Some(family) = ["Microsoft YaHei", "Yu Gothic", "MS Gothic", "Noto Sans CJK JP", "Hiragino Sans"].into_iter().find(|f| db.has_family(f))
|
||||
else {
|
||||
eprintln!("skipped: no large CJK font installed");
|
||||
return;
|
||||
};
|
||||
let face = db.resolve(family, "Regular").map(|(f, _)| f).unwrap();
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 20, "y": 80, "text": "漢字のテスト ABC", "size": 24, "font": family, "style": face.style}));
|
||||
for run in ["cold", "warm"] {
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let t0 = std::time::Instant::now();
|
||||
let r = s.execute("type.retype", &json!({"fonts": [family]})).unwrap();
|
||||
let ms = t0.elapsed().as_secs_f64() * 1000.0;
|
||||
eprintln!("{run}: Retype with {family} ({} encoded glyphs) loaded: {ms:.0} ms → {}", face.mapped_chars().len(), r["texts"]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_compound_with_a_locked_or_hidden_part_stays_whole() {
|
||||
let mut s = session();
|
||||
// "B" outlines as a compound path of three contours.
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40}));
|
||||
let b = children_of(&s, g)[1];
|
||||
let part = children_of(&s, b)[1];
|
||||
s.edit("test", |d, _| {
|
||||
d.node_mut(NodeId(part)).unwrap().locked = true;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
assert_eq!(r["texts"], json!(["A"]), "{r}");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.node(NodeId(part)).unwrap().locked, "B's locked part, and B, stay as they are");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_with_an_attributes_note_keeps_its_type_inside() {
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40}));
|
||||
s.execute("attributes.set", &json!({"ids": [g], "note": "logo, keep"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
let id = r["ids"][0].as_u64().unwrap();
|
||||
assert_eq!(children_of(&s, g), vec![id], "the group and its note stay, holding the type");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_retypable_reads_no_font() {
|
||||
let mut s = session();
|
||||
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "A", "size": 40}));
|
||||
let a = children_of(&s, g)[0];
|
||||
s.edit("test", |d, _| {
|
||||
let art = vectorcraft_doc::Node::path(d.alloc_id(), vectorcraft_geom::PathData::default(), Default::default());
|
||||
d.node_mut(NodeId(a)).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(art, true)));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let e = s.execute("type.retype", &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("(1 checked)"), "the masked shape is reported, and no font was indexed: {e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tracked_one_contour_letters_still_become_type() {
|
||||
for text in ["LIT", "HELLO", "LIST"] {
|
||||
let mut s = session();
|
||||
let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": text, "size": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
let n = text.len() as u64;
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": n, "tracking": 50})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
let texts: Vec<String> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect();
|
||||
assert_eq!(texts.concat(), text, "split by the tracking, every letter still becomes type: {r}");
|
||||
assert!(texts.len() > 1, "the tracking splits the line: {r}");
|
||||
assert_eq!(r["unmatched"], json!([]), "{r}");
|
||||
}
|
||||
}
|
||||
|
||||
/// How long Retype takes on a few hundred CJK outlines at once (run with `--ignored --nocapture`;
|
||||
/// skips when no large CJK font is installed). Not a pass/fail budget: it prints.
|
||||
#[test]
|
||||
#[ignore = "timing: needs an installed CJK font"]
|
||||
fn timing_with_hundreds_of_cjk_outlines() {
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
let Some(family) = ["Microsoft YaHei", "Yu Gothic", "MS Gothic", "Noto Sans CJK JP", "Hiragino Sans"].into_iter().find(|f| db.has_family(f))
|
||||
else {
|
||||
eprintln!("skipped: no large CJK font installed");
|
||||
return;
|
||||
};
|
||||
let face = db.resolve(family, "Regular").map(|(f, _)| f).unwrap();
|
||||
// 300 common ideographs, ten lines of thirty.
|
||||
let chars: Vec<char> = (0x4E00u32..).filter_map(char::from_u32).filter(|c| face.covers(*c)).take(300).collect();
|
||||
let mut s = session();
|
||||
let mut groups = vec![];
|
||||
for (i, line) in chars.chunks(30).enumerate() {
|
||||
let text: String = line.iter().collect();
|
||||
groups.push(outlined(&mut s, json!({"x": 20, "y": 40 + 30 * i, "text": text, "size": 20, "font": family, "style": face.style})));
|
||||
}
|
||||
for run in ["cold", "warm"] {
|
||||
s.execute("select.set", &json!({"ids": groups})).unwrap();
|
||||
let t0 = std::time::Instant::now();
|
||||
let r = s.execute("type.retype", &json!({"fonts": [family]})).unwrap();
|
||||
let ms = t0.elapsed().as_secs_f64() * 1000.0;
|
||||
let typed: usize = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().chars().count()).sum();
|
||||
eprintln!(
|
||||
"{run}: Retype of {} {family} outlines: {ms:.0} ms → {typed} characters typed, {} unmatched",
|
||||
chars.len(),
|
||||
r["unmatched"].as_array().unwrap().len()
|
||||
);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_tracked_line_is_checked_in_time() {
|
||||
// Tracking splits the line at every glyph: the layout check must not lay out the rest of the
|
||||
// line again after each split.
|
||||
let text = "abe".repeat(150);
|
||||
let mut s = session();
|
||||
let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": text, "size": 4})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": text.len(), "tracking": 50})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let t0 = std::time::Instant::now();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
let texts: Vec<String> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect();
|
||||
assert_eq!(texts.concat(), text);
|
||||
assert_eq!(r["unmatched"], json!([]));
|
||||
eprintln!("450 tracked glyphs: {:?}, {} objects", t0.elapsed(), texts.len());
|
||||
}
|
||||
@@ -1279,40 +1279,63 @@ impl GroupEdit {
|
||||
|
||||
/// Rewrite colour group `group` with `colors`: its swatches take them in order (keeping their
|
||||
/// names, kinds and global or spot flags), a `None` removes the swatch at its place, extra colors
|
||||
/// are added as new swatches and swatches past the end are removed. Paints linked to its global
|
||||
/// are added as new swatches and swatches past the end are removed. With `colors_only`, a swatch
|
||||
/// that is not a color (a gradient, pattern or None swatch) keeps its place and paint and takes no
|
||||
/// entry of `colors`, which go to the group's color swatches in order. Paints linked to its global
|
||||
/// swatches follow (a removed swatch's are unlinked); `rename` renames the group. A built-in swatch
|
||||
/// (None, Registration) it would change or remove is refused.
|
||||
pub(super) fn rewrite_group(d: &mut Document, group: &str, colors: &[Option<Color>], rename: Option<&str>, cmd: &str) -> Result<GroupEdit> {
|
||||
pub(super) fn rewrite_group(
|
||||
d: &mut Document,
|
||||
group: &str,
|
||||
colors: &[Option<Color>],
|
||||
colors_only: bool,
|
||||
rename: Option<&str>,
|
||||
cmd: &str,
|
||||
) -> Result<GroupEdit> {
|
||||
let gi = d.swatch_groups.iter().position(|g| g.name == group).ok_or_else(|| bad(cmd, format!("no colour group `{group}`")))?;
|
||||
let name = match rename.map(str::trim).filter(|n| !n.is_empty() && *n != group) {
|
||||
Some(n) => d.free_swatch_name(n),
|
||||
None => group.to_string(),
|
||||
};
|
||||
let old = &d.swatch_groups[gi].swatches;
|
||||
// The place in `colors` of each swatch's new color; none for a swatch kept as it is.
|
||||
let mut taken = 0;
|
||||
let places: Vec<Option<usize>> = old
|
||||
.iter()
|
||||
.map(|w| {
|
||||
(!colors_only || w.paint.color().is_some()).then(|| {
|
||||
taken += 1;
|
||||
taken - 1
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let new_color = |place: Option<usize>| place.and_then(|i| colors.get(i).copied().flatten());
|
||||
if let Some(w) = old
|
||||
.iter()
|
||||
.enumerate()
|
||||
.find(|(i, w)| w.is_reserved() && colors.get(*i).copied().flatten().is_none_or(|c| w.paint.color() != Some(c)))
|
||||
.map(|x| x.1)
|
||||
.zip(&places)
|
||||
.find(|(w, place)| place.is_some() && w.is_reserved() && new_color(**place).is_none_or(|c| w.paint.color() != Some(c)))
|
||||
.map(|x| x.0)
|
||||
{
|
||||
return Err(bad(cmd, format!("`{}` can't be edited or removed", w.name)));
|
||||
}
|
||||
let colorized_ok = super::paint::check_colorized(d).is_ok();
|
||||
let mut relinks = vec![];
|
||||
let old = std::mem::take(&mut d.swatch_groups[gi].swatches);
|
||||
let old_len = old.len();
|
||||
// The swatches that stay, each with its new color.
|
||||
let mut kept: Vec<(Swatch, Color)> = vec![];
|
||||
for (i, w) in old.into_iter().enumerate() {
|
||||
match colors.get(i).copied().flatten() {
|
||||
Some(c) => kept.push((w, c)),
|
||||
None if w.global => relinks.push(Relink { from: w.name.clone(), to: w.name, color: None, keep: false }),
|
||||
None => {}
|
||||
// The swatches that stay, each with its new color (none for one kept as it is).
|
||||
let mut kept: Vec<(Swatch, Option<Color>)> = vec![];
|
||||
for (w, place) in old.into_iter().zip(places) {
|
||||
match (place, new_color(place)) {
|
||||
(None, _) => kept.push((w, None)),
|
||||
(_, Some(c)) => kept.push((w, Some(c))),
|
||||
(_, None) if w.global => relinks.push(Relink { from: w.name.clone(), to: w.name, color: None, keep: false }),
|
||||
(_, None) => {}
|
||||
}
|
||||
}
|
||||
let mut swatches = Vec::with_capacity(kept.len());
|
||||
for (mut w, c) in kept {
|
||||
if w.paint.color() != Some(c) {
|
||||
if let Some(c) = c
|
||||
&& w.paint.color() != Some(c)
|
||||
{
|
||||
// A tint swatch becomes a colour of its own.
|
||||
w.paint = Paint::solid(c);
|
||||
if w.global {
|
||||
@@ -1325,7 +1348,7 @@ pub(super) fn rewrite_group(d: &mut Document, group: &str, colors: &[Option<Colo
|
||||
let mut free = d.free_swatch_names();
|
||||
free.insert(&name);
|
||||
swatches.iter().for_each(|w| free.insert(&w.name));
|
||||
for c in colors.iter().skip(old_len).flatten() {
|
||||
for c in colors.iter().skip(taken).flatten() {
|
||||
let nm = free.take(&color_name(*c));
|
||||
swatches.push(Swatch { name: nm, paint: Paint::solid(*c), global: false, spot: false });
|
||||
}
|
||||
@@ -1379,7 +1402,7 @@ fn swatch_edit_group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
{
|
||||
return Ok(json!({"name": group, "swatches": g.swatches.iter().map(|w| w.name.clone()).collect::<Vec<_>>(), "relinked": 0}));
|
||||
}
|
||||
let e = s.edit("Edit Color Group", |d, _| rewrite_group(d, group, &colors, rename, C))?;
|
||||
let e = s.edit("Edit Color Group", |d, _| rewrite_group(d, group, &colors, false, rename, C))?;
|
||||
e.defaults(s)?;
|
||||
Ok(json!({"name": e.name, "swatches": e.swatches, "relinked": e.relinked}))
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
//! `app.toast`: a short message shown over the window that does not stop work and goes away by
|
||||
//! itself (a toast). Scripts (`vc.run`), actions (a recorded step), MCP clients and plug-ins raise
|
||||
//! one with the command, and the app's code can raise one with [`Session::toast`]. The engine
|
||||
//! queues the messages and the desktop app takes them each frame ([`Session::take_toasts`]) and
|
||||
//! shows them. A failed script run puts the documents back but keeps the messages it raised.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CommandSpec, Result, always, bad, cmd};
|
||||
use crate::Session;
|
||||
|
||||
const ID: &str = "app.toast";
|
||||
|
||||
/// The most characters a message has.
|
||||
pub const MAX_CHARS: usize = 500;
|
||||
|
||||
/// How long a message shows when `seconds` is omitted, and the shortest and longest time it may
|
||||
/// show.
|
||||
pub const DEFAULT_SECONDS: f64 = 4.0;
|
||||
pub const MIN_SECONDS: f64 = 0.5;
|
||||
pub const MAX_SECONDS: f64 = 60.0;
|
||||
|
||||
/// The most messages waiting for the app to take them: past it the oldest one goes. A session
|
||||
/// without a window (the headless MCP server, `vectorcraft-cli run`) never takes them.
|
||||
pub const MAX_QUEUED: usize = 32;
|
||||
|
||||
/// What kind of news a message is, which sets its color.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum Level {
|
||||
#[default]
|
||||
Info,
|
||||
Success,
|
||||
Warning,
|
||||
Error,
|
||||
}
|
||||
|
||||
impl Level {
|
||||
pub const ALL: [Level; 4] = [Level::Info, Level::Success, Level::Warning, Level::Error];
|
||||
|
||||
/// Its `level` value.
|
||||
pub fn param(self) -> &'static str {
|
||||
match self {
|
||||
Level::Info => "info",
|
||||
Level::Success => "success",
|
||||
Level::Warning => "warning",
|
||||
Level::Error => "error",
|
||||
}
|
||||
}
|
||||
|
||||
/// The level whose `level` value is `param`.
|
||||
pub fn from_param(param: &str) -> Option<Level> {
|
||||
Level::ALL.into_iter().find(|l| l.param() == param)
|
||||
}
|
||||
}
|
||||
|
||||
/// A message to show.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Toast {
|
||||
pub message: String,
|
||||
pub level: Level,
|
||||
/// How long it shows, in seconds.
|
||||
pub seconds: f64,
|
||||
}
|
||||
|
||||
impl Toast {
|
||||
/// A message of `level` shown for [`DEFAULT_SECONDS`].
|
||||
pub fn new(message: impl Into<String>, level: Level) -> Toast {
|
||||
Toast { message: message.into(), level, seconds: DEFAULT_SECONDS }
|
||||
}
|
||||
}
|
||||
|
||||
/// The messages waiting for the app to show them.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Queue(VecDeque<Toast>);
|
||||
|
||||
impl Session {
|
||||
/// Queue `toast` for the app to show. With [`MAX_QUEUED`] waiting, the oldest one goes. Its
|
||||
/// time is held to [`MIN_SECONDS`] to [`MAX_SECONDS`], and a time that is not a number is
|
||||
/// [`DEFAULT_SECONDS`].
|
||||
pub fn toast(&mut self, mut toast: Toast) {
|
||||
toast.seconds = if toast.seconds.is_nan() { DEFAULT_SECONDS } else { toast.seconds.clamp(MIN_SECONDS, MAX_SECONDS) };
|
||||
while self.toasts.0.len() >= MAX_QUEUED {
|
||||
self.toasts.0.pop_front();
|
||||
}
|
||||
self.toasts.0.push_back(toast);
|
||||
}
|
||||
|
||||
/// Take the messages queued since the last call, oldest first.
|
||||
pub fn take_toasts(&mut self) -> Vec<Toast> {
|
||||
self.toasts.0.drain(..).collect()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"app.toast",
|
||||
"Show Message",
|
||||
[],
|
||||
None,
|
||||
"{message: string (1 to 500 characters, not only whitespace), level?: \"info\" | \"success\" | \"warning\" | \"error\" (default \"info\"), seconds?: number 0.5 to 60 (default 4)} show `message` over the window without stopping work: it goes away after `seconds` or when clicked; messages stack at the window's bottom right, the newest lowest, at most 5 at once; edits no document; an action records it as a step → {message, level, seconds}",
|
||||
always,
|
||||
run
|
||||
)]
|
||||
}
|
||||
|
||||
fn run(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let toast = parse(p)?;
|
||||
let r = json!({"message": &toast.message, "level": toast.level.param(), "seconds": toast.seconds});
|
||||
s.toast(toast);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// The message `p` asks for; an invalid value of any key is an error.
|
||||
fn parse(p: &Value) -> Result<Toast> {
|
||||
let message = match p.get("message") {
|
||||
Some(Value::String(m)) => m,
|
||||
Some(_) => return Err(bad(ID, "`message` must be a string")),
|
||||
None => return Err(bad(ID, "`message` is required")),
|
||||
};
|
||||
if message.trim().is_empty() {
|
||||
return Err(bad(ID, "`message` must have a character other than whitespace"));
|
||||
}
|
||||
let chars = message.chars().count();
|
||||
if chars > MAX_CHARS {
|
||||
return Err(bad(ID, format!("`message` has {chars} characters; at most {MAX_CHARS} are allowed")));
|
||||
}
|
||||
let level = match p.get("level") {
|
||||
None => Level::default(),
|
||||
Some(v) => v.as_str().and_then(Level::from_param).ok_or_else(|| {
|
||||
let all: Vec<&str> = Level::ALL.iter().map(|l| l.param()).collect();
|
||||
bad(ID, format!("`level` must be one of {}", all.join(", ")))
|
||||
})?,
|
||||
};
|
||||
let seconds = match p.get("seconds") {
|
||||
None => DEFAULT_SECONDS,
|
||||
Some(v) => v
|
||||
.as_f64()
|
||||
.filter(|s| (MIN_SECONDS..=MAX_SECONDS).contains(s))
|
||||
.ok_or_else(|| bad(ID, format!("`seconds` must be a number from {MIN_SECONDS} to {MAX_SECONDS}")))?,
|
||||
};
|
||||
Ok(Toast { message: message.clone(), level, seconds })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_message_is_queued_with_its_defaults() {
|
||||
let mut s = Session::new();
|
||||
let r = s.execute(ID, &json!({"message": "Saved 3 files"})).unwrap();
|
||||
assert_eq!(r, json!({"message": "Saved 3 files", "level": "info", "seconds": 4.0}));
|
||||
assert_eq!(s.take_toasts(), vec![Toast::new("Saved 3 files", Level::Info)]);
|
||||
// Taken once.
|
||||
assert_eq!(s.take_toasts(), vec![]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn level_and_seconds_are_kept() {
|
||||
let mut s = Session::new();
|
||||
for level in Level::ALL {
|
||||
s.execute(ID, &json!({"message": "m", "level": level.param(), "seconds": 0.5})).unwrap();
|
||||
}
|
||||
s.execute(ID, &json!({"message": "long", "seconds": 60})).unwrap();
|
||||
let got: Vec<(Level, f64)> = s.take_toasts().iter().map(|t| (t.level, t.seconds)).collect();
|
||||
assert_eq!(got, vec![(Level::Info, 0.5), (Level::Success, 0.5), (Level::Warning, 0.5), (Level::Error, 0.5), (Level::Info, 60.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_values_are_errors_and_queue_nothing() {
|
||||
let mut s = Session::new();
|
||||
let long = "x".repeat(MAX_CHARS + 1);
|
||||
for p in [
|
||||
json!({}),
|
||||
json!({"message": 3}),
|
||||
json!({"message": ""}),
|
||||
json!({"message": " \n\t"}),
|
||||
json!({"message": long}),
|
||||
json!({"message": "m", "level": "loud"}),
|
||||
json!({"message": "m", "level": 1}),
|
||||
json!({"message": "m", "seconds": 0.4}),
|
||||
json!({"message": "m", "seconds": 61}),
|
||||
json!({"message": "m", "seconds": "4"}),
|
||||
json!({"message": "m", "seconds": null}),
|
||||
] {
|
||||
let e = s.execute(ID, &p).unwrap_err().to_string();
|
||||
assert!(e.contains(ID), "{p}: {e}");
|
||||
}
|
||||
assert_eq!(s.take_toasts(), vec![]);
|
||||
// The longest message is allowed, counted in characters, not bytes.
|
||||
let most = "é".repeat(MAX_CHARS);
|
||||
s.execute(ID, &json!({"message": most})).unwrap();
|
||||
assert_eq!(s.take_toasts().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_message_queued_by_the_app_shows_for_0_5_to_60_seconds() {
|
||||
let mut s = Session::new();
|
||||
for seconds in [f64::INFINITY, 1e9, f64::NEG_INFINITY, 0.0, f64::NAN, 10.0] {
|
||||
s.toast(Toast { seconds, ..Toast::new("m", Level::Info) });
|
||||
}
|
||||
let got: Vec<f64> = s.take_toasts().iter().map(|t| t.seconds).collect();
|
||||
assert_eq!(got, vec![MAX_SECONDS, MAX_SECONDS, MIN_SECONDS, MIN_SECONDS, DEFAULT_SECONDS, 10.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_oldest_waiting_message_goes_past_the_limit() {
|
||||
let mut s = Session::new();
|
||||
for i in 0..MAX_QUEUED + 2 {
|
||||
s.toast(Toast::new(format!("{i}"), Level::Info));
|
||||
}
|
||||
let left: Vec<String> = s.take_toasts().into_iter().map(|t| t.message).collect();
|
||||
assert_eq!(left.len(), MAX_QUEUED);
|
||||
assert_eq!(left.first().map(String::as_str), Some("2"));
|
||||
assert_eq!(left.last().map(String::as_str), Some("33"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_message_is_journaled_without_an_undo_step_or_a_document() {
|
||||
let mut s = Session::new();
|
||||
// No document open.
|
||||
s.execute(ID, &json!({"message": "no document"})).unwrap();
|
||||
assert_eq!(s.journal.last().unwrap(), &(ID.to_string(), json!({"message": "no document"})));
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let undo = s.active().unwrap().history.undo.len();
|
||||
let revision = s.active().unwrap().revision;
|
||||
s.execute(ID, &json!({"message": "m", "level": "success"})).unwrap();
|
||||
assert_eq!(s.journal.last().unwrap(), &(ID.to_string(), json!({"message": "m", "level": "success"})));
|
||||
assert_eq!(s.active().unwrap().history.undo.len(), undo);
|
||||
assert_eq!(s.active().unwrap().revision, revision);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_script_raises_a_message_with_vc_run() {
|
||||
let mut s = Session::new();
|
||||
let r = s
|
||||
.execute(
|
||||
"script.run",
|
||||
&json!({"source": "vc.run('app.toast', {message: 'Done: ' + (1 + 1), level: 'success'});", "name": "t.js", "answers": []}),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(r.get("error").is_none_or(Value::is_null), "{r}");
|
||||
assert_eq!(s.take_toasts(), vec![Toast::new("Done: 2", Level::Success)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_script_run_puts_the_documents_back_and_keeps_its_messages() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let art = format!("{:?}", s.active().unwrap().doc.layers);
|
||||
let e = s
|
||||
.execute(
|
||||
"script.run",
|
||||
&json!({
|
||||
"source": "vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10}); vc.run('app.toast', {message: 'Failed: no artboard'}); throw new Error('stop');",
|
||||
"name": "t.js",
|
||||
"answers": [],
|
||||
}),
|
||||
)
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(e.contains("stop"), "{e}");
|
||||
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), art, "the rectangle is put back");
|
||||
assert_eq!(s.take_toasts(), vec![Toast::new("Failed: no artboard", Level::Info)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_command_batch_raises_its_messages_in_order() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
s.execute(
|
||||
"command.batch",
|
||||
&json!({"commands": [
|
||||
{"command": "app.toast", "params": {"message": "one"}},
|
||||
{"command": "app.toast", "params": {"message": "two", "level": "warning"}},
|
||||
]}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(s.take_toasts(), vec![Toast::new("one", Level::Info), Toast::new("two", Level::Warning)]);
|
||||
}
|
||||
}
|
||||
@@ -10,8 +10,8 @@ use super::object::choice;
|
||||
use super::threads::ThreadIndex;
|
||||
use super::typecmd::{area_text, block_gaps, needed_room, refresh_bounds};
|
||||
use super::{
|
||||
CommandSpec, EngineError, Result, Session, bad, checked_ids_param, cmd, find_command, has_clipboard, has_doc, has_selection, named_ids,
|
||||
number_or, switch_or, targets, text_param,
|
||||
CommandSpec, EngineError, Result, Session, bad, checked_ids_param, cmd, find_command, has_clipboard, has_doc, has_selection, index_opt,
|
||||
named_ids, number_or, object_param, switch_or, targets, text_param,
|
||||
};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -120,7 +120,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Find and Replace…",
|
||||
["Edit"],
|
||||
None,
|
||||
"{find, replace?: \"\", matchCase?: false, wholeWord?: false, ids?} replace in every text object (or ids) → {count}. Matches never span style runs.",
|
||||
"{find, replace?: \"\", matchCase?: false, wholeWord?: false, hiddenLayers?: false, lockedLayers?: false, ids?} replace every match in the type the search reaches (or in ids, whatever their layers), as one undo step → {count (every match), replaced (the matches that did not already read as `replace`)}. The search reaches visible, unlocked type on visible, unlocked layers, off locked artboards; hiddenLayers adds the type of hidden layers and sublayers and lockedLayers that of locked ones, while a hidden or locked object or group keeps its type out. Matches never span style runs. When nothing matches, or every match already reads as `replace`, nothing changes and no undo step is recorded.",
|
||||
has_doc,
|
||||
find_replace
|
||||
),
|
||||
@@ -129,10 +129,19 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Find Next",
|
||||
["Edit"],
|
||||
None,
|
||||
"{find, matchCase?, wholeWord?} select the next text object (after the selected one, wrapping) containing `find` → {id|null}",
|
||||
"{find, matchCase?: false, wholeWord?: false, backwards?: false, hiddenLayers?: false, lockedLayers?: false, from?: {id, start, end} (a match this command returned, or the range edit.replaceMatch returned)} find the next match of `find` in the type edit.findReplace reaches and select its type object → {id, start, end (the match's bytes in the object's plain text), index (its place among all the matches, from 1), count, selected} or {id: null, count: 0}. The search visits type objects from the top of the stacking order down and each object's matches in reading order; backwards visits the objects from the bottom up and each object's matches from the last. It goes on after `from` and, past the last match, starts again at the first. Without `from` it goes on after the first selected type object, and with no type selected, or with a null `from`, it starts at the first match. A match on a hidden or locked layer is returned with selected false and the selection stays as it is. Nothing is recorded for undo.",
|
||||
has_doc,
|
||||
find_next
|
||||
),
|
||||
cmd!(
|
||||
"edit.replaceMatch",
|
||||
"Replace",
|
||||
[],
|
||||
None,
|
||||
"{find, replace?: \"\", matchCase?: false, wholeWord?: false, id, start, end} replace one match of `find`, the bytes start..end of type object id as edit.findNext returns them, with `replace`, as one undo step → {id, start, end (the replacement's bytes; pass them to edit.findNext as `from` to go on), replaced}. Bytes that are no match of `find` are refused. When the match already reads as `replace`, nothing changes, no undo step is recorded and replaced is false.",
|
||||
has_doc,
|
||||
replace_one
|
||||
),
|
||||
cmd!(
|
||||
"edit.pasteWithoutFormatting",
|
||||
"Paste without Formatting",
|
||||
@@ -1657,14 +1666,9 @@ fn is_word(c: char) -> bool {
|
||||
c.is_alphanumeric() || c == '_'
|
||||
}
|
||||
|
||||
/// Byte ranges of `needle` in `hay`.
|
||||
pub(crate) fn find_all(hay: &str, needle: &str, match_case: bool, whole_word: bool) -> Vec<(usize, usize)> {
|
||||
find_all_between(hay, needle, match_case, whole_word, None, None)
|
||||
}
|
||||
|
||||
/// [`find_all`] in run `i` of `runs`: a whole word looks past the run's ends at the characters
|
||||
/// next to it, so a change of style inside a word is not a word boundary (#5901). Matches stay
|
||||
/// inside the run.
|
||||
/// Byte ranges of `needle` in run `i` of `runs`: a whole word looks past the run's ends at the
|
||||
/// characters next to it, so a change of style inside a word is not a word boundary (#5901).
|
||||
/// Matches stay inside the run.
|
||||
fn find_in_run(runs: &[TextRun], i: usize, needle: &str, match_case: bool, whole_word: bool) -> Vec<(usize, usize)> {
|
||||
let Some(run) = runs.get(i) else { return vec![] };
|
||||
let before = runs.get(..i).and_then(|r| r.iter().rev().find_map(|r| r.text.chars().next_back()));
|
||||
@@ -1672,8 +1676,8 @@ fn find_in_run(runs: &[TextRun], i: usize, needle: &str, match_case: bool, whole
|
||||
find_all_between(&run.text, needle, match_case, whole_word, before, after)
|
||||
}
|
||||
|
||||
/// [`find_all`], with `before` and `after` the characters on either side of `hay` (none at the
|
||||
/// text's ends), which a whole word must not touch either.
|
||||
/// Byte ranges of `needle` in `hay`, with `before` and `after` the characters on either side of
|
||||
/// `hay` (none at the text's ends), which a whole word must not touch either.
|
||||
fn find_all_between(hay: &str, needle: &str, match_case: bool, whole_word: bool, before: Option<char>, after: Option<char>) -> Vec<(usize, usize)> {
|
||||
let nc: Vec<char> = needle.chars().collect();
|
||||
if nc.is_empty() {
|
||||
@@ -1705,102 +1709,234 @@ fn find_all_between(hay: &str, needle: &str, match_case: bool, whole_word: bool,
|
||||
/// The visible, unlocked type objects of visible, unlocked layers, off locked artboards, in paint
|
||||
/// order: the text Find and Replace and Check Spelling go through.
|
||||
pub(crate) fn all_texts(d: &Document) -> Vec<NodeId> {
|
||||
fn visit(n: &Node, locks: &LockedArtboards<'_>, v: &mut Vec<NodeId>) {
|
||||
if !n.visible || n.locked {
|
||||
searched_texts(d, false, false)
|
||||
}
|
||||
|
||||
/// [`all_texts`], with the type of hidden layers (`hidden_layers`) and of locked layers
|
||||
/// (`locked_layers`) as well, as Check Hidden Layers and Check Locked Layers of Find and Replace
|
||||
/// ask. The switches are about layers and sublayers: a hidden or locked object or group keeps its
|
||||
/// type out, and so does a locked artboard.
|
||||
fn searched_texts(d: &Document, hidden_layers: bool, locked_layers: bool) -> Vec<NodeId> {
|
||||
fn visit(n: &Node, locks: &LockedArtboards<'_>, layers: (bool, bool), v: &mut Vec<NodeId>) {
|
||||
let layer = matches!(n.kind, NodeKind::Layer { .. });
|
||||
if (!n.visible && !(layer && layers.0)) || (n.locked && !(layer && layers.1)) {
|
||||
return;
|
||||
}
|
||||
if matches!(n.kind, NodeKind::Text(_)) && !locks.holds_id(n.id) {
|
||||
v.push(n.id);
|
||||
}
|
||||
for c in n.children().into_iter().flatten() {
|
||||
visit(c, locks, v);
|
||||
visit(c, locks, layers, v);
|
||||
}
|
||||
}
|
||||
let mut v = vec![];
|
||||
let locks = d.locked_artboards();
|
||||
for l in &d.layers {
|
||||
visit(l, &locks, &mut v);
|
||||
visit(l, &locks, (hidden_layers, locked_layers), &mut v);
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// What Find and Replace looks for: the text, Match Case and Find Whole Word.
|
||||
struct Query {
|
||||
find: String,
|
||||
match_case: bool,
|
||||
whole_word: bool,
|
||||
}
|
||||
|
||||
impl Query {
|
||||
/// The `find`, `matchCase` and `wholeWord` params of command `c`. An empty or missing `find`
|
||||
/// is an error.
|
||||
fn of(p: &Value, c: &str) -> Result<Self> {
|
||||
let find = text_param(p, "find", c)?.filter(|f| !f.is_empty()).ok_or_else(|| bad(c, "missing `find`"))?.to_string();
|
||||
Ok(Self { find, match_case: switch_or(p, "matchCase", false, c)?, whole_word: switch_or(p, "wholeWord", false, c)? })
|
||||
}
|
||||
|
||||
/// The matches in `t`, in reading order, each as (run, start, end) with `start..end` the bytes
|
||||
/// of the match in the object's plain text. A match stays inside one style run, and an inline
|
||||
/// graphic is art, not characters to find.
|
||||
fn matches(&self, t: &TextObject) -> Vec<(usize, usize, usize)> {
|
||||
let mut hits = vec![];
|
||||
let mut base = 0;
|
||||
for (ri, r) in t.runs.iter().enumerate() {
|
||||
if r.inline.is_none() {
|
||||
hits.extend(
|
||||
find_in_run(&t.runs, ri, &self.find, self.match_case, self.whole_word).into_iter().map(|(a, b)| (ri, base + a, base + b)),
|
||||
);
|
||||
}
|
||||
base += r.text.len();
|
||||
}
|
||||
hits
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace bytes `start..end` of the plain text of `t`, which lie inside run `run`, with `rep`.
|
||||
/// The paragraph styles and the ruby follow the edit, as `text.editRange` moves them. The caller
|
||||
/// refreshes the bounds.
|
||||
fn replace_match(t: &mut TextObject, run: usize, start: usize, end: usize, rep: &str) {
|
||||
let base: usize = t.runs.iter().take(run).map(|r| r.text.len()).sum();
|
||||
let (Some(a), Some(b)) = (start.checked_sub(base), end.checked_sub(base)) else { return };
|
||||
if !t.runs.get(run).is_some_and(|r| a <= b && r.text.is_char_boundary(a) && r.text.is_char_boundary(b)) {
|
||||
return;
|
||||
}
|
||||
t.splice_paras(start, end, rep);
|
||||
if let Some(r) = t.runs.get_mut(run) {
|
||||
r.text.replace_range(a..b, rep);
|
||||
}
|
||||
t.ruby_after_replace(start, end, rep.len());
|
||||
}
|
||||
|
||||
fn find_replace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "edit.findReplace";
|
||||
let find = text_param(p, "find", C)?.filter(|f| !f.is_empty()).ok_or_else(|| bad(C, "missing `find`"))?.to_string();
|
||||
let q = Query::of(p, C)?;
|
||||
let rep = text_param(p, "replace", C)?.unwrap_or("").to_string();
|
||||
let (mc, ww) = (switch_or(p, "matchCase", false, C)?, switch_or(p, "wholeWord", false, C)?);
|
||||
let (hidden, locked) = (switch_or(p, "hiddenLayers", false, C)?, switch_or(p, "lockedLayers", false, C)?);
|
||||
let ids = match p.get("ids").filter(|v| !v.is_null()) {
|
||||
Some(_) => text_ids(&s.doc()?.doc, &checked_ids_param(s, p, "ids", C)?),
|
||||
None => all_texts(&s.doc()?.doc),
|
||||
None => searched_texts(&s.doc()?.doc, hidden, locked),
|
||||
};
|
||||
let st = s.doc()?;
|
||||
let total: usize = ids
|
||||
// Every match, and the matches that do not already read as the replacement.
|
||||
let (total, replaced) = ids
|
||||
.iter()
|
||||
.filter_map(|id| match &st.doc.node(*id)?.kind {
|
||||
NodeKind::Text(t) => Some((0..t.runs.len()).map(|i| find_in_run(&t.runs, i, &find, mc, ww).len()).sum::<usize>()),
|
||||
NodeKind::Text(t) => {
|
||||
let plain = t.plain_text();
|
||||
let hits = q.matches(t);
|
||||
Some((hits.len(), hits.iter().filter(|(_, a, b)| plain.get(*a..*b) != Some(rep.as_str())).count()))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.sum();
|
||||
if total == 0 {
|
||||
return Ok(json!({ "count": 0 }));
|
||||
.fold((0, 0), |(n, r), (hn, hr)| (n + hn, r + hr));
|
||||
if replaced == 0 {
|
||||
return Ok(json!({ "count": total, "replaced": 0 }));
|
||||
}
|
||||
super::overprint::edit_counted(s, "Replace", |d| {
|
||||
let mut changed = 0;
|
||||
for id in &ids {
|
||||
let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue };
|
||||
// Matches as (run, start, end) with offsets inside the run. Inline graphics are art, not
|
||||
// characters to rewrite.
|
||||
let mut hits = vec![];
|
||||
let mut base = 0;
|
||||
for (ri, r) in t.runs.iter().enumerate() {
|
||||
if r.inline.is_none() {
|
||||
for (a, b) in find_in_run(&t.runs, ri, &find, mc, ww) {
|
||||
if r.text.get(a..b) != Some(rep.as_str()) {
|
||||
hits.push((ri, base + a, base + b, a, b));
|
||||
}
|
||||
}
|
||||
}
|
||||
base += r.text.len();
|
||||
}
|
||||
let plain = t.plain_text();
|
||||
let hits: Vec<_> = q.matches(t).into_iter().filter(|(_, a, b)| plain.get(*a..*b) != Some(rep.as_str())).collect();
|
||||
if hits.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// Last match first, so the offsets of earlier ones stay valid. The paragraph styles follow
|
||||
// each edit, as `text.editRange` does.
|
||||
for (ri, ta, tb, a, b) in hits.into_iter().rev() {
|
||||
t.splice_paras(ta, tb, &rep);
|
||||
if let Some(r) = t.runs.get_mut(ri) {
|
||||
r.text.replace_range(a..b, &rep);
|
||||
}
|
||||
// Last match first, so the offsets of earlier ones stay valid.
|
||||
for (ri, a, b) in hits.into_iter().rev() {
|
||||
replace_match(t, ri, a, b, &rep);
|
||||
}
|
||||
changed += 1;
|
||||
refresh_bounds(t);
|
||||
}
|
||||
Ok(changed)
|
||||
})?;
|
||||
Ok(json!({ "count": total }))
|
||||
Ok(json!({ "count": total, "replaced": replaced }))
|
||||
}
|
||||
|
||||
/// A match of Find and Replace: bytes `start..end` of the plain text of type object `id`.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Match {
|
||||
id: NodeId,
|
||||
start: usize,
|
||||
end: usize,
|
||||
}
|
||||
|
||||
impl Match {
|
||||
/// The `id`, `start` and `end` that `p` gives for a match, under command `c`: an object id and
|
||||
/// two byte offsets, put in order as `text.editRange` orders its own.
|
||||
fn of(p: &Value, c: &str) -> Result<Self> {
|
||||
let whole = |key: &str| index_opt(p, key, c)?.ok_or_else(|| bad(c, format!("missing `{key}`")));
|
||||
let id = object_param(p, "id", c)?.ok_or_else(|| bad(c, "missing `id`"))?;
|
||||
let (start, end) = (whole("start")?, whole("end")?);
|
||||
Ok(Self { id, start: start.min(end), end: start.max(end) })
|
||||
}
|
||||
}
|
||||
|
||||
fn find_next(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "edit.findNext";
|
||||
let find = text_param(p, "find", C)?.filter(|f| !f.is_empty()).ok_or_else(|| bad(C, "missing `find`"))?.to_string();
|
||||
let (mc, ww) = (switch_or(p, "matchCase", false, C)?, switch_or(p, "wholeWord", false, C)?);
|
||||
let q = Query::of(p, C)?;
|
||||
let backwards = switch_or(p, "backwards", false, C)?;
|
||||
let (hidden, locked) = (switch_or(p, "hiddenLayers", false, C)?, switch_or(p, "lockedLayers", false, C)?);
|
||||
// A `from` that is no object gives no `id`, and is refused as one without it. A null `from`
|
||||
// starts at the first match, whatever is selected.
|
||||
let from = match p.get("from") {
|
||||
None => None,
|
||||
Some(Value::Null) => Some(None),
|
||||
Some(v) => Some(Some(Match::of(v, C)?)),
|
||||
};
|
||||
let st = s.doc()?;
|
||||
let all = all_texts(&st.doc);
|
||||
let cur = st.selection.objects.first().and_then(|id| all.iter().position(|x| x == id));
|
||||
let n = all.len();
|
||||
let start = cur.map(|c| c + 1).unwrap_or(0);
|
||||
let hit = (0..n).map(|k| all[(start + k) % n.max(1)]).find(|id| match st.doc.node(*id).map(|n| &n.kind) {
|
||||
Some(NodeKind::Text(t)) => !find_all(&t.plain_text(), &find, mc, ww).is_empty(),
|
||||
_ => false,
|
||||
});
|
||||
match hit {
|
||||
Some(id) => {
|
||||
s.select(|_, sel| sel.set([id]))?;
|
||||
Ok(json!({ "id": id.0 }))
|
||||
}
|
||||
None => Ok(json!({ "id": null })),
|
||||
// The objects in the order the search visits them: from the top of the stacking order down,
|
||||
// or with Search Backwards from the bottom up.
|
||||
let mut order = searched_texts(&st.doc, hidden, locked);
|
||||
if !backwards {
|
||||
order.reverse();
|
||||
}
|
||||
// Every match in that order as (object's place, match): inside an object in reading order, or
|
||||
// with Search Backwards from its end.
|
||||
let mut all: Vec<(usize, Match)> = vec![];
|
||||
for (place, id) in order.iter().enumerate() {
|
||||
let Some(NodeKind::Text(t)) = st.doc.node(*id).map(|n| &n.kind) else { continue };
|
||||
let mut hits = q.matches(t);
|
||||
if backwards {
|
||||
hits.reverse();
|
||||
}
|
||||
all.extend(hits.into_iter().map(|(_, start, end)| (place, Match { id: *id, start, end })));
|
||||
}
|
||||
if all.is_empty() {
|
||||
return Ok(json!({ "id": null, "count": 0 }));
|
||||
}
|
||||
// The search goes on from `from`, or from the whole of the first selected type object it
|
||||
// visits, so that the same call again reaches the next object. From anywhere else it starts
|
||||
// at the first match.
|
||||
let from = from.unwrap_or_else(|| {
|
||||
st.selection.objects.iter().filter(|id| order.contains(id)).find_map(|id| match &st.doc.node(*id)?.kind {
|
||||
NodeKind::Text(t) => Some(Match { id: *id, start: 0, end: t.runs.iter().map(|r| r.text.len()).sum() }),
|
||||
_ => None,
|
||||
})
|
||||
});
|
||||
let after = |(place, m): &(usize, Match), at: usize, f: &Match| {
|
||||
*place > at || (*place == at && if backwards { m.end <= f.start } else { m.start >= f.end })
|
||||
};
|
||||
let k = from
|
||||
.and_then(|f| order.iter().position(|id| *id == f.id).map(|at| (at, f)))
|
||||
.and_then(|(at, f)| all.iter().position(|hit| after(hit, at, &f)))
|
||||
.unwrap_or(0);
|
||||
let Some((_, m)) = all.get(k).copied() else { return Ok(json!({ "id": null, "count": 0 })) };
|
||||
let count = all.len();
|
||||
// Type that a selection tool can't reach (on a hidden or locked layer) is found without being
|
||||
// selected.
|
||||
let selected = all_texts(&st.doc).contains(&m.id);
|
||||
if selected && st.selection.objects != [m.id] {
|
||||
s.select(|_, sel| sel.set([m.id]))?;
|
||||
}
|
||||
let index = if backwards { count - k } else { k + 1 };
|
||||
Ok(json!({ "id": m.id.0, "start": m.start, "end": m.end, "index": index, "count": count, "selected": selected }))
|
||||
}
|
||||
|
||||
fn replace_one(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "edit.replaceMatch";
|
||||
let q = Query::of(p, C)?;
|
||||
let rep = text_param(p, "replace", C)?.unwrap_or("").to_string();
|
||||
let m = Match::of(p, C)?;
|
||||
let st = s.doc()?;
|
||||
let t = match st.doc.node(m.id).map(|n| &n.kind) {
|
||||
Some(NodeKind::Text(t)) => t,
|
||||
Some(_) => return Err(bad(C, format!("node {} is not text", m.id.0))),
|
||||
None => return Err(EngineError::NoNode(m.id)),
|
||||
};
|
||||
let Some((run, ..)) = q.matches(t).into_iter().find(|(_, a, b)| (*a, *b) == (m.start, m.end)) else {
|
||||
return Err(bad(C, format!("no match of `find` at bytes {}..{} of object {}", m.start, m.end, m.id.0)));
|
||||
};
|
||||
let end = m.start + rep.len();
|
||||
if t.plain_text().get(m.start..m.end) == Some(rep.as_str()) {
|
||||
return Ok(json!({ "id": m.id.0, "start": m.start, "end": end, "replaced": false }));
|
||||
}
|
||||
s.edit("Replace", |d, _| {
|
||||
let Some(NodeKind::Text(t)) = d.node_mut(m.id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(m.id)) };
|
||||
replace_match(t, run, m.start, m.end, &rep);
|
||||
refresh_bounds(t);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "id": m.id.0, "start": m.start, "end": end, "replaced": true }))
|
||||
}
|
||||
|
||||
// ---------- Paste without Formatting ----------
|
||||
|
||||
@@ -250,7 +250,6 @@ fn parse_library(xml: &str, cmd: &str, text_only: bool) -> Result<Library> {
|
||||
craft_xml::Error::TooDeep(_) => bad(cmd, format!("the variable library nests elements more than {MAX_LIBRARY_NESTING} deep")),
|
||||
_ => bad(cmd, format!("the variable library is not well-formed XML: {e}")),
|
||||
})?;
|
||||
crate::cmd::xmlattrs::validate(xml.as_bytes(), opts.limits).map_err(|e| bad(cmd, format!("the variable library is not well-formed XML: {e}")))?;
|
||||
let Some(root) = std::iter::once(&doc).chain(doc.descendants()).find(|n| n.is(craft_xml::Local("variableSets"))) else {
|
||||
return Err(bad(cmd, "the file holds no `variableSets` element"));
|
||||
};
|
||||
|
||||
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Save for Web",
|
||||
[],
|
||||
None,
|
||||
"{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity, deleted?: [\"#rrggbb\"…] (taken out of the table: their pixels take the nearest color left, and at least one color stays), customPalette?: [\"#rrggbb\"…] (a fixed palette used instead of the reduction's, at most `colors` entries; a new reduction without colorTable clears it and deleted)} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/<slice name>.<ext>), output?: images (default)|html (an HTML page placing the image or slices, <stem>.html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself",
|
||||
"{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity, deleted?: [\"#rrggbb\"…] (taken out of the table: their pixels take the nearest color left, and at least one color stays), customPalette?: [\"#rrggbb\"…] (a fixed palette used instead of the reduction's, at most `colors` entries, its transparent colors taking one slot together; a new reduction without colorTable clears it and deleted), shifted?: {\"#source\": \"#rrggbb\"…} (each source color is written as the color given, wherever it is in the image; kept when reducing as a locked color is, before the locked ones, while one palette slot is left for the reduction; at most 256; a source the table does not hold shifts nothing; a color shifted to itself is removed; a shifted color is not web-shifted, and a transparent one stays transparent; GIF lossy moves no pixel into or out of a shifted color)} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/<slice name>.<ext>), output?: images (default)|html (an HTML page placing the image or slices, <stem>.html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself",
|
||||
has_doc,
|
||||
export
|
||||
),
|
||||
@@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Save for Web Preview",
|
||||
[],
|
||||
None,
|
||||
"{…the settings of document.exportForWeb (preset?, format?…), slice?: n (1-based, from slice.list; default the whole image), kbps?: 56.6 (connection speed for the download time), image?: false (also the optimised file as dataBase64)} what Save writes for the whole image (or one slice) → {format, width, height, bytes (exactly the file's size), seconds (to download at kbps), kbps, colors?: [{color: \"#rrggbb\", source: \"#rrggbb\" (the colour the reduction made, as colorTable lists it), transparent, locked, webShifted, webSafe}] (gif/png8: the colour table in file order), mappedToTransparent?: [\"#rrggbb\"…], slices: images an export writes, warnings (as document.exportForWeb's), dataBase64?}",
|
||||
"{…the settings of document.exportForWeb (preset?, format?…), slice?: n (1-based, from slice.list; default the whole image), kbps?: 56.6 (connection speed for the download time), image?: false (also the optimised file as dataBase64)} what Save writes for the whole image (or one slice) → {format, width, height, bytes (exactly the file's size), seconds (to download at kbps), kbps, colors?: [{color: \"#rrggbb\", source: \"#rrggbb\" (the colour the reduction made, as colorTable lists it), transparent, locked, webShifted, shifted (by colorTable.shifted; also locked), webSafe}] (gif/png8: the colour table in file order), mappedToTransparent?: [\"#rrggbb\"…], slices: images an export writes, warnings (as document.exportForWeb's), dataBase64?}",
|
||||
has_doc,
|
||||
preview
|
||||
),
|
||||
@@ -331,8 +331,14 @@ pub struct ColorTable {
|
||||
/// A fixed palette (a Custom table) used instead of the reduction's own: the colors of the
|
||||
/// table when the first color was deleted. Empty: the reduction makes the palette.
|
||||
pub custom_palette: Vec<String>,
|
||||
/// Colors shifted by hand: each source color (`#rrggbb`) and the color it is written as. A
|
||||
/// shifted color is locked, and a source the table does not hold shifts nothing.
|
||||
pub shifted: std::collections::BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
/// A color shifted by hand: (source, color written).
|
||||
type Shift = ([u8; 3], [u8; 3]);
|
||||
|
||||
/// The most colours a colour table list holds.
|
||||
const MAX_TABLE: usize = 256;
|
||||
|
||||
@@ -352,6 +358,21 @@ impl ColorTable {
|
||||
list.iter().map(|h| Self::rgb(h).ok_or_else(|| format!("colorTable.{what}: `{h}` is not a colour such as \"#ff8800\""))).collect()
|
||||
}
|
||||
|
||||
/// The colors shifted by hand as (source, color written). An error names a value that is not a
|
||||
/// color such as `#ff8800`, two keys that name one color, or more than 256 entries.
|
||||
fn shifts(&self) -> std::result::Result<Vec<Shift>, String> {
|
||||
// One entry past the limit is enough for `colors` to refuse a longer map.
|
||||
let (keys, values): (Vec<String>, Vec<String>) = self.shifted.iter().take(MAX_TABLE + 1).map(|(k, v)| (k.clone(), v.clone())).unzip();
|
||||
let sources = Self::colors(&keys, "shifted")?;
|
||||
let to = Self::colors(&values, "shifted")?;
|
||||
for (i, (s, k)) in sources.iter().zip(&keys).enumerate() {
|
||||
if sources[..i].contains(s) {
|
||||
return Err(format!("colorTable.shifted: `{k}` names a color another key names"));
|
||||
}
|
||||
}
|
||||
Ok(sources.into_iter().zip(to).collect())
|
||||
}
|
||||
|
||||
/// `h` as RGB; `None` when it is not a color such as `#ff8800`.
|
||||
fn rgb(h: &str) -> Option<[u8; 3]> {
|
||||
vectorcraft_color::Color::from_hex(h).filter(|_| !super::hex_with_alpha(h)).map(|c| {
|
||||
@@ -487,13 +508,18 @@ impl WebSettings {
|
||||
{
|
||||
ColorTable::colors(list, what)?;
|
||||
}
|
||||
// A deleted color is no longer locked, transparent or web-shifted.
|
||||
// A deleted color is no longer locked, transparent, web-shifted or shifted.
|
||||
let deleted = ColorTable::colors(&table.deleted, "deleted")?;
|
||||
if !deleted.is_empty() {
|
||||
for list in [&mut table.locked, &mut table.transparent, &mut table.web_shift] {
|
||||
list.retain(|h| ColorTable::rgb(h).is_none_or(|c| !deleted.contains(&c)));
|
||||
}
|
||||
}
|
||||
// Shifts are kept as `#rrggbb` in lowercase; a color shifted to itself is not shifted, and
|
||||
// a color shifted by hand is not web-shifted.
|
||||
let shifts: Vec<Shift> = table.shifts()?.into_iter().filter(|(s, to)| s != to && !deleted.contains(s)).collect();
|
||||
table.web_shift.retain(|h| ColorTable::rgb(h).is_none_or(|c| !shifts.iter().any(|(s, _)| *s == c)));
|
||||
table.shifted = shifts.into_iter().map(|(s, to)| (hex(s), hex(to))).collect();
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
@@ -640,6 +666,8 @@ pub struct TableColor {
|
||||
pub transparent: bool,
|
||||
pub locked: bool,
|
||||
pub web_shifted: bool,
|
||||
/// Shifted by hand (`colorTable.shifted`): written as `color` instead of `source`.
|
||||
pub shifted: bool,
|
||||
}
|
||||
|
||||
/// An optimised image file.
|
||||
@@ -759,6 +787,11 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8
|
||||
let locked = ColorTable::colors(&table.locked, "locked")?;
|
||||
let to_clear = ColorTable::colors(&table.transparent, "transparent")?;
|
||||
let shift = ColorTable::colors(&table.web_shift, "webShift")?;
|
||||
let by_hand = table.shifts()?;
|
||||
let shifted_to = |src: &[u8; 3]| by_hand.iter().find(|(s, _)| s == src).map(|(_, to)| *to);
|
||||
// A color shifted by hand is kept when the colors are reduced, as a locked one is, and takes
|
||||
// one of the slots kept for them before the locked colors do.
|
||||
let kept: Vec<[u8; 3]> = by_hand.iter().map(|(s, _)| *s).chain(locked.iter().copied()).collect();
|
||||
let o = PaletteOptions {
|
||||
colors: s.colors,
|
||||
reduction: s.reduction,
|
||||
@@ -767,7 +800,7 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8
|
||||
transparency: s.transparency,
|
||||
matte,
|
||||
};
|
||||
let mut ix = reduced(rgba, w, h, s, &o, &locked)?;
|
||||
let mut ix = reduced(rgba, w, h, s, &o, &kept)?;
|
||||
// Map to transparent works on the colours the reduction made.
|
||||
let before = ix.palette.clone();
|
||||
let clear = ix.transparent.map(usize::from);
|
||||
@@ -781,11 +814,11 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8
|
||||
*slot = *c;
|
||||
}
|
||||
}
|
||||
// Web snap, then the colours shifted by hand (locked colours stay as they are).
|
||||
// Web shift and web snap (locked colors and colors shifted by hand stay as they are).
|
||||
let clear = ix.transparent.map(usize::from);
|
||||
for (i, c) in ix.palette.iter_mut().enumerate() {
|
||||
let src = sources.get(i).copied().unwrap_or(*c);
|
||||
if Some(i) == clear || locked.contains(&src) {
|
||||
if Some(i) == clear || shifted_to(&src).is_some() || locked.contains(&src) {
|
||||
continue;
|
||||
}
|
||||
if shift.contains(&src) {
|
||||
@@ -794,8 +827,19 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8
|
||||
*c = snapped;
|
||||
}
|
||||
}
|
||||
// Lossy compares the pixels with the colors written for them, and moves no pixel into or out of
|
||||
// a color shifted by hand.
|
||||
if s.format == WebFormat::Gif {
|
||||
web::lossy(&mut ix, rgba, s.lossy);
|
||||
let fixed: Vec<u8> = sources.iter().enumerate().filter(|(_, c)| shifted_to(c).is_some()).filter_map(|(i, _)| u8::try_from(i).ok()).collect();
|
||||
web::lossy(&mut ix, rgba, s.lossy, &fixed);
|
||||
}
|
||||
// The colors shifted by hand.
|
||||
for (i, c) in ix.palette.iter_mut().enumerate() {
|
||||
if Some(i) != clear
|
||||
&& let Some(to) = sources.get(i).and_then(shifted_to)
|
||||
{
|
||||
*c = to;
|
||||
}
|
||||
}
|
||||
let order = web::sort(&mut ix, table.sort);
|
||||
let sources: Vec<[u8; 3]> = order.iter().map(|&i| sources.get(i).copied().unwrap_or_default()).collect();
|
||||
@@ -804,12 +848,17 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8
|
||||
.iter()
|
||||
.zip(&sources)
|
||||
.enumerate()
|
||||
.map(|(i, (c, src))| TableColor {
|
||||
color: *c,
|
||||
source: *src,
|
||||
transparent: ix.transparent == u8::try_from(i).ok(),
|
||||
locked: locked.contains(src),
|
||||
web_shifted: shift.contains(src),
|
||||
.map(|(i, (c, src))| {
|
||||
let transparent = ix.transparent == u8::try_from(i).ok();
|
||||
let shifted = !transparent && shifted_to(src).is_some();
|
||||
TableColor {
|
||||
color: *c,
|
||||
source: *src,
|
||||
transparent,
|
||||
locked: locked.contains(src) || shifted,
|
||||
web_shifted: shift.contains(src) && !shifted,
|
||||
shifted,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
Ok(PaletteImage { ix, colors, mapped })
|
||||
@@ -818,7 +867,8 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8
|
||||
/// The pixels reduced to the palette `s` gives: the reduction's own (`locked` kept), or the
|
||||
/// color table's fixed one, without the deleted colors. The pixels of a deleted color take the
|
||||
/// nearest color left, with `o`'s dither. A deletion has to leave a color that is not mapped to
|
||||
/// transparent.
|
||||
/// transparent. A fixed palette keeps its colors mapped to transparent, which take one slot of
|
||||
/// `colors` together, and its first opaque colors that fit in the rest.
|
||||
fn reduced(rgba: &[u8], w: u32, h: u32, s: &WebSettings, o: &PaletteOptions, locked: &[[u8; 3]]) -> std::result::Result<Indexed, String> {
|
||||
let table = &s.color_table;
|
||||
let deleted = ColorTable::colors(&table.deleted, "deleted")?;
|
||||
@@ -847,11 +897,70 @@ fn reduced(rgba: &[u8], w: u32, h: u32, s: &WebSettings, o: &PaletteOptions, loc
|
||||
left.push(c);
|
||||
}
|
||||
}
|
||||
left.truncate(usize::from(s.colors.clamp(2, 256)) - usize::from(has_clear));
|
||||
if left.is_empty() || (removed && !opaque_left(&left)) {
|
||||
return Err(KEEP_ONE.into());
|
||||
}
|
||||
Ok(quantize::quantize_to(rgba, w, h, o, &left))
|
||||
// The colors mapped to transparent all become the one transparent entry, so together they take
|
||||
// one slot, and the opaque colors fill the rest in palette order. When no pixel takes one of
|
||||
// them and no pixel is transparent, that slot goes to the next opaque color instead.
|
||||
let kept = fixed_palette(&left, &to_clear, s.colors, has_clear, true);
|
||||
let mut ix = quantize::quantize_to(rgba, w, h, o, &kept);
|
||||
clear_dropped(&mut ix, rgba, o, &kept, &left, &to_clear);
|
||||
if !has_clear && !ix.palette.iter().any(|c| to_clear.contains(c)) && left.iter().any(|c| to_clear.contains(c)) {
|
||||
return Ok(quantize::quantize_to(rgba, w, h, o, &fixed_palette(&left, &to_clear, s.colors, has_clear, false)));
|
||||
}
|
||||
Ok(ix)
|
||||
}
|
||||
|
||||
/// The entries of the fixed palette `left` that fit in `colors`. With `clear`, the colors in
|
||||
/// `to_clear` are kept and take one slot together; without it they are left out. The list holds
|
||||
/// at most 256 entries, less one when `has_clear` (the transparent pixels' entry).
|
||||
fn fixed_palette(left: &[[u8; 3]], to_clear: &[[u8; 3]], colors: u16, has_clear: bool, clear: bool) -> Vec<[u8; 3]> {
|
||||
let any_clear = clear && left.iter().any(|c| to_clear.contains(c));
|
||||
let total = 256 - usize::from(has_clear);
|
||||
let mut room = (usize::from(colors.clamp(2, 256)) - usize::from(has_clear || any_clear)).min(total - usize::from(any_clear));
|
||||
let opaque = left.iter().filter(|c| !to_clear.contains(c)).count().min(room);
|
||||
let mut clear_room = if clear { total - opaque } else { 0 };
|
||||
left.iter()
|
||||
.copied()
|
||||
.filter(|c| {
|
||||
let slots = if to_clear.contains(c) { &mut clear_room } else { &mut room };
|
||||
let keep = *slots > 0;
|
||||
*slots = slots.saturating_sub(1);
|
||||
keep
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Makes transparent the pixels of `ix` whose nearest color is a color of `left` mapped to
|
||||
/// transparent (`to_clear`) that does not fit in the fixed palette `kept`. Such a pixel takes the
|
||||
/// transparent entry, or an entry mapped to transparent, which Map to Transparent clears later.
|
||||
fn clear_dropped(ix: &mut Indexed, rgba: &[u8], o: &PaletteOptions, kept: &[[u8; 3]], left: &[[u8; 3]], to_clear: &[[u8; 3]]) {
|
||||
let dropped: Vec<[u8; 3]> = left.iter().filter(|c| to_clear.contains(c) && !kept.contains(c)).copied().collect();
|
||||
if dropped.is_empty() {
|
||||
return;
|
||||
}
|
||||
let all: Vec<[u8; 3]> = kept.iter().chain(&dropped).copied().collect();
|
||||
let near = quantize::nearest_entries(rgba, o, &all);
|
||||
if !near.iter().any(|n| n.is_some_and(|n| n >= kept.len())) {
|
||||
return;
|
||||
}
|
||||
let entry = match ix.transparent.or_else(|| ix.palette.iter().position(|c| to_clear.contains(c)).and_then(|i| u8::try_from(i).ok())) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
// A kept color mapped to transparent that no pixel took; at most 255 entries are used then.
|
||||
let (Some(c), Ok(i)) = (kept.iter().find(|c| to_clear.contains(c)), u8::try_from(ix.palette.len())) else {
|
||||
return;
|
||||
};
|
||||
ix.palette.push(*c);
|
||||
i
|
||||
}
|
||||
};
|
||||
for (v, n) in ix.indices.iter_mut().zip(&near) {
|
||||
if n.is_some_and(|n| n >= kept.len()) {
|
||||
*v = entry;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An optimised image as straight RGBA → `(pixels, width, height)` (the dialog's preview).
|
||||
@@ -1116,7 +1225,7 @@ fn preview(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.map(|c| {
|
||||
json!({
|
||||
"color": hex(c.color), "source": hex(c.source), "transparent": c.transparent, "locked": c.locked,
|
||||
"webShifted": c.web_shifted, "webSafe": quantize::web_safe(c.color) == c.color,
|
||||
"webShifted": c.web_shifted, "shifted": c.shifted, "webSafe": quantize::web_safe(c.color) == c.color,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
//! Attribute uniqueness checks missing from the pinned shared XML reader's strict mode.
|
||||
//!
|
||||
//! Temporary consumer guard: parsing remains in craft-xml. Move this invariant into the
|
||||
//! shared strict reader and remove this second event pass when that dependency is updated.
|
||||
|
||||
/// Check names before canonical/local-name rewriting can collapse distinct attributes.
|
||||
/// The event reader and namespace scope use the same caller-supplied resource caps.
|
||||
pub(super) fn validate(xml: &[u8], limits: craft_xml::Limits) -> Result<(), String> {
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
let opts = craft_xml::Options { limits, doctype: craft_xml::Doctype::Reject, ..Default::default() }.strict();
|
||||
let mut events = opts.events(xml);
|
||||
let mut bindings: Vec<(String, String)> = Vec::new();
|
||||
let mut scopes = Vec::new();
|
||||
while let Some(event) = events.next().map_err(|e| e.to_string())? {
|
||||
match event {
|
||||
craft_xml::Event::Start { attrs, .. } => {
|
||||
scopes.push(bindings.len());
|
||||
let mut raw = BTreeSet::new();
|
||||
for (key, value) in &attrs {
|
||||
if !raw.insert(key.as_str()) {
|
||||
return Err(format!("duplicate attribute `{key}`"));
|
||||
}
|
||||
if let Some(prefix) = key.strip_prefix("xmlns:") {
|
||||
if bindings.len() >= limits.max_attrs {
|
||||
return Err("too many in-scope namespace declarations".into());
|
||||
}
|
||||
bindings.push((prefix.to_string(), value.clone()));
|
||||
}
|
||||
}
|
||||
let mut expanded = BTreeSet::new();
|
||||
for (key, _) in &attrs {
|
||||
if key == "xmlns" || key.starts_with("xmlns:") {
|
||||
continue;
|
||||
}
|
||||
// Default namespaces do not apply to attributes. Preserve undeclared
|
||||
// prefixes for standalone SVG library fragments, as the importer did.
|
||||
let name = match key.split_once(':') {
|
||||
Some(("xml", local)) => ("http://www.w3.org/XML/1998/namespace", local),
|
||||
Some((prefix, local)) => {
|
||||
bindings.iter().rev().find(|(p, _)| p == prefix).map_or(("", key.as_str()), |(_, uri)| (uri.as_str(), local))
|
||||
}
|
||||
None => ("", key.as_str()),
|
||||
};
|
||||
if !expanded.insert(name) {
|
||||
return Err(format!("duplicate expanded attribute `{key}`"));
|
||||
}
|
||||
}
|
||||
}
|
||||
craft_xml::Event::End { .. } => bindings.truncate(scopes.pop().unwrap_or(0)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -360,6 +360,8 @@ pub struct Session {
|
||||
/// Set while [`Session::tool_typed_text`] passes keyboard input to the active tool
|
||||
/// ([`vectorcraft_tools::ToolContext::typed_from_keyboard`]).
|
||||
keyboard_text: bool,
|
||||
/// The messages `app.toast` and [`Session::toast`] queued for the app to show; not saved.
|
||||
pub(crate) toasts: cmd::toast::Queue,
|
||||
}
|
||||
|
||||
impl Default for Session {
|
||||
|
||||
@@ -1559,12 +1559,14 @@ fn kind_id(kind: &RunErrorKind) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
/// `message`, with what to do about a failure that comes from a script written for another program.
|
||||
fn explained(kind: &RunErrorKind, message: &str) -> String {
|
||||
/// `e`'s message, with what to do about a failure that comes from a script written for another
|
||||
/// program. A message the script supplied itself ([`RunError::authored`]) is given as it is.
|
||||
fn explained(e: &RunError) -> String {
|
||||
const HOST_OBJECTS: &[&str] = &["app", "Window", "BridgeTalk", "activeDocument", "documents"];
|
||||
let message = &e.message;
|
||||
let names_host_object =
|
||||
message.strip_prefix("ReferenceError: ").is_some_and(|m| HOST_OBJECTS.iter().any(|o| m.split_whitespace().next() == Some(o)));
|
||||
if *kind == RunErrorKind::Thrown && names_host_object {
|
||||
if e.kind == RunErrorKind::Thrown && !e.authored && names_host_object {
|
||||
format!("{message} (scripts here use the `vc` object; objects other applications give their scripts are not available)")
|
||||
} else {
|
||||
message.to_string()
|
||||
@@ -1582,7 +1584,7 @@ fn preprocessor_error(f: include::Failure) -> (RunError, Option<Arc<str>>) {
|
||||
include::FailKind::Limit => (RunErrorKind::Limit(LimitKind::Host), f.message),
|
||||
};
|
||||
let file = (f.index > 0).then_some(f.file);
|
||||
(RunError { kind, message, line: f.line, column: f.column }, file)
|
||||
(RunError { kind, message, line: f.line, column: f.column, authored: false }, file)
|
||||
}
|
||||
|
||||
/// `e`, the error `realm` raised in the run of `host`, at the line and column of the file it is in,
|
||||
@@ -1591,20 +1593,20 @@ fn located(host: &Host, realm: &Realm, e: &RunError) -> (RunError, Option<Arc<st
|
||||
let map = |m: &include::SourceMap| {
|
||||
let (index, file, line, column) = m.locate(e.line, e.column);
|
||||
let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() };
|
||||
(RunError { kind: e.kind.clone(), message, line, column }, index, file)
|
||||
(RunError { kind: e.kind.clone(), message, line, column, authored: e.authored }, index, file)
|
||||
};
|
||||
// An error `$.evalFile` raised for a file it could not run, and no script caught, is at that
|
||||
// file's place.
|
||||
if let Some((file, line, column)) = realm.error_mark().and_then(|m| host.eval_failures.borrow().get(m as usize).cloned()) {
|
||||
let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() };
|
||||
return (RunError { kind: e.kind.clone(), message, line, column }, Some(file));
|
||||
return (RunError { kind: e.kind.clone(), message, line, column, authored: e.authored }, Some(file));
|
||||
}
|
||||
if e.line == 0 {
|
||||
return (e.clone(), None);
|
||||
}
|
||||
// An error in code from a source whose map is not at hand, such as code that `eval` compiled,
|
||||
// is given without a place.
|
||||
let unplaced = || (RunError { kind: e.kind.clone(), message: e.message.clone(), line: 0, column: 0 }, None);
|
||||
let unplaced = || (RunError { line: 0, column: 0, ..e.clone() }, None);
|
||||
match realm.error_source() {
|
||||
0 => {
|
||||
let (e, index, file) = map(&host.script_map.borrow());
|
||||
@@ -1777,6 +1779,15 @@ impl Session {
|
||||
self.script_report.as_ref().filter(|r| r["ok"] == false).map(failure_text)
|
||||
}
|
||||
|
||||
/// [`Self::script_failure_text`] split around the message when that message is text the script
|
||||
/// supplied itself (`messageOrigin` `script`): the text before it, the message and the text after
|
||||
/// it. `None` when the last run did not fail, or failed with one of the app's own errors.
|
||||
pub fn script_authored_failure(&self) -> Option<(String, &str, String)> {
|
||||
let r = self.script_report.as_ref().filter(|r| r["ok"] == false && r["messageOrigin"] == "script")?;
|
||||
let (before, after) = failure_frame(r);
|
||||
Some((before, r["message"].as_str().unwrap_or_default(), after))
|
||||
}
|
||||
|
||||
/// Has the running script used up its growth allowance, so a person must answer? A run asked
|
||||
/// to stop no longer waits: the next [`Session::script_pump`] ends it.
|
||||
pub fn script_waiting(&self) -> bool {
|
||||
@@ -1873,7 +1884,7 @@ impl Session {
|
||||
};
|
||||
drop(key);
|
||||
let kind = LimitKind::Interrupted;
|
||||
let e = RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0 };
|
||||
let e = RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0, authored: false };
|
||||
let _ = self.script_failed(job, &e);
|
||||
true
|
||||
}
|
||||
@@ -2120,14 +2131,14 @@ impl Session {
|
||||
// A stop while a dialog waits ends the run there; the interpreter cannot go on from the call.
|
||||
if job.realm.waits() {
|
||||
let kind = LimitKind::Interrupted;
|
||||
let e = RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0 };
|
||||
let e = RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0, authored: false };
|
||||
return Some(self.script_failed(job, &e));
|
||||
}
|
||||
job.host.calls_this_slice.set(0);
|
||||
let outcome = run_slice(self, &mut job);
|
||||
match outcome {
|
||||
Err(panic) => {
|
||||
let e = RunError { kind: RunErrorKind::Internal, message: panic, line: 0, column: 0 };
|
||||
let e = RunError { kind: RunErrorKind::Internal, message: panic, line: 0, column: 0, authored: false };
|
||||
Some(self.script_failed(job, &e))
|
||||
}
|
||||
Ok(Err(e)) => Some(self.script_failed(job, &e)),
|
||||
@@ -2144,7 +2155,7 @@ impl Session {
|
||||
} else {
|
||||
format!("`answers` has {n} answers the script did not use")
|
||||
};
|
||||
Some(self.script_failed(job, &RunError { kind: RunErrorKind::Limit(kind), message, line: 0, column: 0 }))
|
||||
Some(self.script_failed(job, &RunError { kind: RunErrorKind::Limit(kind), message, line: 0, column: 0, authored: false }))
|
||||
}
|
||||
Ok(Ok(Progress::Done(_))) => {
|
||||
let r = self.script_commit(job);
|
||||
@@ -2179,7 +2190,7 @@ impl Session {
|
||||
let unwritten = job.host.flush_files();
|
||||
if !unwritten.is_empty() {
|
||||
let message = format!("{UNWRITTEN_FILES}: {}", unwritten.join(", "));
|
||||
let e = RunError { kind: RunErrorKind::Thrown, message, line: 0, column: 0 };
|
||||
let e = RunError { kind: RunErrorKind::Thrown, message, line: 0, column: 0, authored: false };
|
||||
return self.script_failed(job, &e);
|
||||
}
|
||||
// The working copy goes into the session; `job.world` holds the state before the run.
|
||||
@@ -2197,7 +2208,7 @@ impl Session {
|
||||
if changed && (!crate::sanity::doc_sane(&st.doc, &st.selection) || st.doc.too_deep(None)) {
|
||||
job.world.docs = start;
|
||||
job.world.swap(self);
|
||||
let e = RunError { kind: RunErrorKind::Internal, message: INVALID_RESULT.to_string(), line: 0, column: 0 };
|
||||
let e = RunError { kind: RunErrorKind::Internal, message: INVALID_RESULT.to_string(), line: 0, column: 0, authored: false };
|
||||
return self.script_failed(job, &e);
|
||||
}
|
||||
}
|
||||
@@ -2302,7 +2313,8 @@ fn failure_report(name: &str, e: &RunError, file: Option<&str>, host: &Host, fue
|
||||
let mut report = json!({
|
||||
"ok": false,
|
||||
"kind": kind_id(&e.kind),
|
||||
"message": explained(&e.kind, &e.message),
|
||||
"message": explained(e),
|
||||
"messageOrigin": if e.authored { "script" } else { "built-in" },
|
||||
"name": name,
|
||||
"line": e.line,
|
||||
"column": e.column,
|
||||
@@ -2395,6 +2407,12 @@ fn close_run(s: &mut Session, host: &Host, report: &mut Value, ending: console::
|
||||
|
||||
/// The text of a failed run's error.
|
||||
fn failure_text(report: &Value) -> String {
|
||||
let (before, after) = failure_frame(report);
|
||||
format!("{before}{}{after}", report["message"].as_str().unwrap_or_default())
|
||||
}
|
||||
|
||||
/// The text of a failed run's error before its message and after it.
|
||||
fn failure_frame(report: &Value) -> (String, String) {
|
||||
let s = |k: &str| report[k].as_str().unwrap_or_default();
|
||||
let (line, column) = (report["line"].as_u64().unwrap_or(0), report["column"].as_u64().unwrap_or(0));
|
||||
let at = match report["file"].as_str() {
|
||||
@@ -2409,7 +2427,7 @@ fn failure_text(report: &Value) -> String {
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
format!("{}{at}: {} ({}){kept}", s("name"), s("message"), s("kind"))
|
||||
(format!("{}{at}: ", s("name")), format!(" ({}){kept}", s("kind")))
|
||||
}
|
||||
|
||||
/// A run's slice: the working copy in, the real session lent to the host functions, one measured
|
||||
|
||||
@@ -149,6 +149,7 @@ impl Session {
|
||||
global_edit_options: Default::default(),
|
||||
select_similar: crate::cmd::SIMILAR[0].0,
|
||||
keyboard_text: false,
|
||||
toasts: Default::default(),
|
||||
script_key: None,
|
||||
script_engines: crate::script::EnginesKey::new(),
|
||||
script_stop: vectorcraft_js::Interrupt::new(),
|
||||
@@ -204,8 +205,7 @@ impl Session {
|
||||
let _ = self.finish_tool_edit_later();
|
||||
// The switch goes on whatever the lent tool's last actions did, as for the deactivation.
|
||||
let _ = self.give_back_tool(view);
|
||||
let acts = self.with_tool_cx(view, |t, cx| t.deactivate(cx));
|
||||
let _ = self.apply_actions(acts);
|
||||
let _ = self.deactivate_tool(view);
|
||||
// A batch leaves its interaction open in the document it leaves, to keep or roll back with
|
||||
// the rest of the batch; anything else in progress (a drag) is cancelled.
|
||||
if self.batch_stash.is_none() {
|
||||
|
||||
@@ -4329,6 +4329,124 @@ fn object_mosaic_refuses_a_boolean_given_as_text() {
|
||||
assert_eq!((r["tiles"].clone(), images(&s)), (json!(2), 1));
|
||||
}
|
||||
|
||||
/// The size of the mosaic a call makes from the 100 × 50 pt image selected in `s`, with its column and row counts.
|
||||
fn mosaic_size(s: &mut Session, p: serde_json::Value) -> (f64, f64, serde_json::Value, serde_json::Value) {
|
||||
let image = s.doc().unwrap().selection.objects.clone();
|
||||
let r = s.execute("object.createObjectMosaic", &p).unwrap();
|
||||
let b = s.doc().unwrap().doc.node(NodeId(r["id"].as_u64().unwrap())).unwrap().geometric_bounds().unwrap();
|
||||
s.execute("select.set", &json!({ "ids": image })).unwrap();
|
||||
((b.width() * 1e6).round() / 1e6, (b.height() * 1e6).round() / 1e6, r["columns"].clone(), r["rows"].clone())
|
||||
}
|
||||
|
||||
/// Resize Using Percentages reads the new width and height as percentages of the image's size; Constrain Ratio keeps
|
||||
/// the image's proportions, the named side leading; Use Ratio makes the tiles square from the count on the
|
||||
/// constrained side (columns by default), and the call answers the counts it used.
|
||||
#[test]
|
||||
fn object_mosaic_resizes_by_percentages_constrains_the_ratio_and_squares_the_tiles() {
|
||||
let mut s = session();
|
||||
rect(&mut s, 0.0, 0.0, 100.0, 50.0);
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("object.rasterize", &json!({"ppi": 72})).unwrap();
|
||||
assert_eq!(mosaic_size(&mut s, json!({"columns": 2, "rows": 1})), (100.0, 50.0, json!(2), json!(1)));
|
||||
assert_eq!(mosaic_size(&mut s, json!({"width": 50, "height": 200, "percentages": true})), (50.0, 100.0, json!(10), json!(10)));
|
||||
// A side left out is 100% of the image's.
|
||||
assert_eq!(mosaic_size(&mut s, json!({"width": 150, "percentages": true})).0, 150.0);
|
||||
assert_eq!(mosaic_size(&mut s, json!({"width": 200, "height": 10, "constrain": "width"})), (200.0, 100.0, json!(10), json!(10)));
|
||||
assert_eq!(mosaic_size(&mut s, json!({"width": 10, "height": 25, "constrain": "height"})), (50.0, 25.0, json!(10), json!(10)));
|
||||
assert_eq!(mosaic_size(&mut s, json!({"width": 50, "constrain": "width", "percentages": true})), (50.0, 25.0, json!(10), json!(10)));
|
||||
// Square tiles: 10 columns of 10 pt over 50 pt are 5 rows; 4 rows of 12.5 pt over 100 pt are 8 columns.
|
||||
assert_eq!(mosaic_size(&mut s, json!({"columns": 10, "rows": 3, "useRatio": true})), (100.0, 50.0, json!(10), json!(5)));
|
||||
assert_eq!(mosaic_size(&mut s, json!({"columns": 3, "rows": 4, "useRatio": true, "constrain": "height"})), (100.0, 50.0, json!(8), json!(4)));
|
||||
// A side named for Use Ratio is kept without Constrain Ratio: the size stays as given.
|
||||
assert_eq!(mosaic_size(&mut s, json!({"rows": 4, "height": 100, "useRatio": "height"})), (100.0, 100.0, json!(4), json!(4)));
|
||||
// On a new size: 30 columns over 300 × 50 pt are 5 rows.
|
||||
assert_eq!(mosaic_size(&mut s, json!({"columns": 30, "width": 300, "useRatio": true})), (300.0, 50.0, json!(30), json!(5)));
|
||||
// The count is kept within 1..1000.
|
||||
assert_eq!(mosaic_size(&mut s, json!({"columns": 1, "width": 1, "height": 5000, "useRatio": true})).3, json!(1000));
|
||||
assert_eq!(mosaic_size(&mut s, json!({"columns": 1, "width": 5000, "height": 1, "useRatio": true})).3, json!(1));
|
||||
// A size under 0.1 pt grows in proportion while Constrain Ratio keeps it.
|
||||
let (w, h, ..) = mosaic_size(&mut s, json!({"width": 0.1, "constrain": "width"}));
|
||||
assert!((w - 0.2).abs() < 1e-6 && (h - 0.1).abs() < 1e-6, "{w} × {h}");
|
||||
// A side Constrain Ratio works out above 1,000,000 pt shrinks to it, in proportion: a height of
|
||||
// 1,000,000 pt over the 100 × 50 pt image would need a width of 2,000,000 pt.
|
||||
assert_eq!(mosaic_size(&mut s, json!({"height": 1e6, "constrain": "height"})), (1e6, 5e5, json!(10), json!(10)));
|
||||
// An image 20,000,000 times wider than it is tall has no such size: the call is refused.
|
||||
s.execute("object.scale", &json!({"sx": 1, "sy": 1e-7})).unwrap();
|
||||
let r = s.execute("object.createObjectMosaic", &json!({"width": 1e6, "constrain": "width"}));
|
||||
let msg = "the image's proportions leave no size with both sides between 0.1 and 1000000 pt";
|
||||
assert!(matches!(&r, Err(EngineError::BadParams { msg: m, .. }) if m == msg), "{r:?}");
|
||||
}
|
||||
|
||||
/// Use Ratio squares the tiles as drawn: with 4 pt between columns, 10 columns of 10 pt cells draw 6 pt wide, so the
|
||||
/// rows are 6 pt plus their own 4 pt apart (5 rows down 50 pt); on an image turned 90°, the tiles are measured along
|
||||
/// its own axes.
|
||||
#[test]
|
||||
fn object_mosaic_use_ratio_takes_spacing_and_turned_images_into_account() {
|
||||
let mut s = session();
|
||||
rect(&mut s, 0.0, 0.0, 100.0, 50.0);
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("object.rasterize", &json!({"ppi": 72})).unwrap();
|
||||
let image = s.doc().unwrap().selection.objects.clone();
|
||||
let counts = |s: &Session, p: serde_json::Value| crate::cmd::mosaic_counts(s, &p).unwrap();
|
||||
assert_eq!(counts(&s, json!({"columns": 10, "useRatio": true, "spacingX": 4, "spacingY": 4})), (10, 5));
|
||||
assert_eq!(counts(&s, json!({"columns": 10, "useRatio": true, "spacingX": 4})), (10, 8));
|
||||
assert_eq!(counts(&s, json!({"columns": 10, "rows": 7})), (10, 7), "without Use Ratio the counts are kept");
|
||||
let r = s.execute("object.createObjectMosaic", &json!({"columns": 10, "useRatio": true, "spacingX": 4})).unwrap();
|
||||
let g = s.doc().unwrap().doc.node(NodeId(r["id"].as_u64().unwrap())).unwrap().clone();
|
||||
let t = g.children().unwrap()[0].geometric_bounds().unwrap();
|
||||
assert!((t.width() - 6.0).abs() < 1e-6 && (t.height() - 6.25).abs() < 1e-6, "{t:?}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("select.set", &json!({ "ids": image })).unwrap();
|
||||
// Turned 90°, the image's 100 pt side runs down the page; 10 columns along it are still 5 rows across its 50.
|
||||
s.execute("object.rotate", &json!({"angle": 90})).unwrap();
|
||||
assert_eq!(counts(&s, json!({"columns": 10, "useRatio": true})), (10, 5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn object_mosaic_square_count_is_the_nearest_whole_count() {
|
||||
use crate::cmd::menucmds::mosaic_square_count;
|
||||
assert_eq!(mosaic_square_count(10, 100.0, 50.0, 0.0, 0.0), 5);
|
||||
assert_eq!(mosaic_square_count(3, 100.0, 50.0, 0.0, 0.0), 2);
|
||||
assert_eq!(mosaic_square_count(0, 100.0, 50.0, 0.0, 0.0), 1);
|
||||
assert_eq!(mosaic_square_count(10, 0.0, 50.0, 0.0, 0.0), 1);
|
||||
assert_eq!(mosaic_square_count(1000, 1.0, 1000.0, 0.0, 0.0), 1000);
|
||||
// Spacing wider than a cell leaves 10% of it, on either side.
|
||||
assert_eq!(mosaic_square_count(10, 100.0, 50.0, 50.0, 0.0), 50);
|
||||
// 10 columns of 1 pt tiles (9 pt gaps) over 100 pt; rows 100 pt apart are capped too, so 10 rows draw 1 pt.
|
||||
assert_eq!(mosaic_square_count(10, 100.0, 100.0, 9.0, 100.0), 10);
|
||||
// 15 pt tiles over 50 pt: 3 rows draw 16.7 pt and 4 rows 12.5 pt, so 3.
|
||||
assert_eq!(mosaic_square_count(1, 15.0, 50.0, 0.0, 0.0), 3);
|
||||
}
|
||||
|
||||
/// A Constrain Ratio side that is not "width" or "height", a new size of 0 or less, and Use Ratio or Resize Using
|
||||
/// Percentages given as text are errors naming the key; no mosaic is made.
|
||||
#[test]
|
||||
fn object_mosaic_refuses_a_bad_ratio_side_size_or_switch() {
|
||||
let mut s = session();
|
||||
rect(&mut s, 0.0, 0.0, 100.0, 50.0);
|
||||
s.execute("object.rasterize", &json!({"ppi": 72})).unwrap();
|
||||
let undo = |s: &Session| s.doc().unwrap().history.undo.len();
|
||||
let before = undo(&s);
|
||||
for (p, msg) in [
|
||||
(json!({"constrain": "both"}), "`constrain` must be one of \"width\", \"height\" or null"),
|
||||
(json!({"constrain": 1}), "`constrain` must be one of \"width\", \"height\" or null"),
|
||||
(json!({"width": 0}), "`width` must be between 0.1 and 1000000 (got 0)"),
|
||||
(json!({"height": -5, "percentages": true}), "`height` must be between 0.1 and 1000000 (got -5)"),
|
||||
(json!({"width": 2e6, "percentages": true}), "`width` must be between 0.1 and 1000000 (got 2000000)"),
|
||||
// A side Constrain Ratio works out is not used, but a size given for it is still checked.
|
||||
(json!({"width": 200, "height": 0, "constrain": "width"}), "`height` must be between 0.1 and 1000000 (got 0)"),
|
||||
(json!({"useRatio": "true"}), "`useRatio` must be one of \"width\", \"height\", true, false or null"),
|
||||
(json!({"useRatio": 1}), "`useRatio` must be one of \"width\", \"height\", true, false or null"),
|
||||
(json!({"percentages": 1}), "`percentages` must be true or false"),
|
||||
] {
|
||||
let r = s.execute("object.createObjectMosaic", &p);
|
||||
assert!(matches!(&r, Err(EngineError::BadParams { msg: m, .. }) if m == msg), "{p}: {r:?}");
|
||||
assert_eq!(undo(&s), before, "{p}");
|
||||
}
|
||||
let r = s.execute("object.createObjectMosaic", &json!({"constrain": null, "useRatio": null, "percentages": null})).unwrap();
|
||||
assert_eq!(r["tiles"], json!(100));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snap_to_pixel_rounds_drawing_and_moves() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -110,6 +110,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
|
||||
"art-ribbons",
|
||||
"ink-and-wash",
|
||||
"calligraphic-nibs",
|
||||
"pressure-sensitive",
|
||||
"bristle-brushes",
|
||||
"pattern-borders",
|
||||
"scatter-shapes",
|
||||
@@ -131,19 +132,19 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
|
||||
trails["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect::<Vec<_>>(),
|
||||
["Speed Line", "Dash Trail", "Burst Ray", "Zigzag"]
|
||||
);
|
||||
assert_eq!(libs[6]["count"].as_u64(), Some(4));
|
||||
assert_eq!(libs[7]["count"].as_u64(), Some(4));
|
||||
let beams = run(&mut s, "brush.library", json!({"library": "energy-beams"}));
|
||||
assert_eq!(
|
||||
beams["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect::<Vec<_>>(),
|
||||
["Laser Bolt", "Plasma Arc", "Charge Wave", "Spark Trail"]
|
||||
);
|
||||
assert_eq!(libs[7]["count"].as_u64(), Some(4));
|
||||
assert_eq!(libs[8]["count"].as_u64(), Some(4));
|
||||
let dry = run(&mut s, "brush.library", json!({"library": "Dry Media"}));
|
||||
assert_eq!(
|
||||
dry["brushes"].as_array().unwrap().iter().map(|b| (b["name"].as_str().unwrap(), b["type"].as_str().unwrap())).collect::<Vec<_>>(),
|
||||
[("Chalk Grain", "art"), ("Graphite Pencil", "art"), ("Wax Crayon", "art"), ("Charcoal Dust", "art")]
|
||||
);
|
||||
assert_eq!((libs[8]["name"].as_str(), libs[8]["count"].as_u64()), (Some("Dry Media"), Some(4)));
|
||||
assert_eq!((libs[9]["name"].as_str(), libs[9]["count"].as_u64()), (Some("Dry Media"), Some(4)));
|
||||
run(&mut s, "file.new", json!({"width": 200, "height": 200}));
|
||||
let id = run(&mut s, "shape.rectangle", json!({"x": 10, "y": 20, "width": 40, "height": 8}))["id"].as_u64().unwrap();
|
||||
let added = run(&mut s, "brush.addFromLibrary", json!({"library": "energy-beams", "name": "Laser Bolt", "apply": true, "ids": [id]}));
|
||||
@@ -154,6 +155,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
|
||||
("art-ribbons", "art"),
|
||||
("ink-and-wash", "art"),
|
||||
("calligraphic-nibs", "calligraphic"),
|
||||
("pressure-sensitive", "art"),
|
||||
("bristle-brushes", "bristle"),
|
||||
("pattern-borders", "pattern"),
|
||||
("scatter-shapes", "scatter"),
|
||||
@@ -164,7 +166,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
|
||||
let (_, lib) = cmd::brushlib::library(&s, id).unwrap();
|
||||
assert!(lib.len() >= 4, "{id}");
|
||||
for b in &lib.brushes {
|
||||
let kind = if b.name == "Brush Pen" { "calligraphic" } else { kind };
|
||||
let kind = if ["Brush Pen", "Round Flow", "Chisel Flow"].contains(&b.name.as_str()) { "calligraphic" } else { kind };
|
||||
assert_eq!(b.kind.type_id(), kind, "{}", b.name);
|
||||
let mut line = vectorcraft_geom::BezPath::new();
|
||||
line.move_to((0.0, 0.0));
|
||||
@@ -299,6 +301,52 @@ fn the_tech_circuit_library_constructs_adds_and_applies_each_brush() {
|
||||
assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pressure_sensitive_brushes_widen_with_pen_pressure_and_survive_a_saved_library() {
|
||||
let mut s = session();
|
||||
let (_, lib) = cmd::brushlib::library(&s, "Pressure Sensitive").unwrap();
|
||||
let names = ["Flex Ribbon", "Pulse Stroke", "Round Flow", "Chisel Flow"];
|
||||
assert_eq!(lib.brushes.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(), names);
|
||||
let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 40, "x2": 190, "y2": 40}))["id"].as_u64().unwrap();
|
||||
let mut curve = line_to(20.0);
|
||||
curve.curve_to((60.0, -25.0), (140.0, 25.0), (180.0, 0.0));
|
||||
for b in &lib.brushes {
|
||||
let width_at = |pressure| {
|
||||
let stroke = vectorcraft_doc::StrokeLayer {
|
||||
pressure: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, pressure), (1.0, pressure)] }),
|
||||
..black_stroke()
|
||||
};
|
||||
let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(180.0), &stroke);
|
||||
let points = anchors(&pieces.iter().collect::<Vec<_>>());
|
||||
assert!(!points.is_empty() && points.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{} at pressure {pressure}", b.name);
|
||||
let min = points.iter().map(|p| p.y).fold(f64::INFINITY, f64::min);
|
||||
let max = points.iter().map(|p| p.y).fold(f64::NEG_INFINITY, f64::max);
|
||||
max - min
|
||||
};
|
||||
let light = width_at(0.0);
|
||||
let heavy = width_at(1.0);
|
||||
for width in [light, heavy] {
|
||||
assert!(width.is_finite() && width > 0.0, "{}: light={light}, heavy={heavy}", b.name);
|
||||
}
|
||||
assert!(heavy > light * 1.3, "{}: light={light}, heavy={heavy}", b.name);
|
||||
for line in [line_to(2.0), curve.clone()] {
|
||||
let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line, &black_stroke());
|
||||
let points = anchors(&pieces.iter().collect::<Vec<_>>());
|
||||
assert!(!points.is_empty() && points.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{}", b.name);
|
||||
}
|
||||
let before = undo_len(&s);
|
||||
let added = run(&mut s, "brush.addFromLibrary", json!({"library": "pressure-sensitive", "name": b.name, "apply": true, "ids": [path]}));
|
||||
assert_eq!(strs(&added["added"]), [b.name.as_str()]);
|
||||
assert_eq!(added["applied"], json!([path]));
|
||||
assert_eq!(undo_len(&s), before + 1);
|
||||
assert_eq!(doc(&s).node(NodeId(path)).unwrap().appearance.stroke().unwrap().brush.as_deref(), Some(b.name.as_str()));
|
||||
}
|
||||
let saved = run(&mut s, "brush.saveLibrary", json!({"names": names}));
|
||||
let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap();
|
||||
let reopened = vectorcraft_format::load(&bytes).unwrap();
|
||||
assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes);
|
||||
}
|
||||
|
||||
/// Ink and Wash: a tapered ink art brush, a brush pen whose size follows the pen pressure and two
|
||||
/// translucent washes, with names of their own and a few paths of art each.
|
||||
#[test]
|
||||
|
||||
@@ -5027,6 +5027,73 @@ fn live_paint_does_not_count_art_named_like_its_parts() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A path drawn in an isolated Live Paint group can't be named Face or Edge, the names of the
|
||||
/// group's faces and edges: `object.setProps` and `layer.setProps` return an error and rename
|
||||
/// nothing, so Gap Options and a path dragged into the group keep the path. A face keeps its name.
|
||||
#[test]
|
||||
fn live_paint_refuses_part_names_for_paths_drawn_in_it() {
|
||||
use vectorcraft_tools::builder::{EDGE_NAME, FACE_NAME, faces};
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
let face = faces(&node(&s, g))[0].id;
|
||||
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
|
||||
let a = line_across(&mut s, 50.0);
|
||||
// Hidden, the path stays in the group as drawn when isolation mode ends.
|
||||
s.execute("object.setProps", &json!({"id": a.0, "visible": false})).unwrap();
|
||||
let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
|
||||
for name in [FACE_NAME, EDGE_NAME] {
|
||||
let calls = [
|
||||
("object.setProps", json!({"id": a.0, "name": name})),
|
||||
("layer.setProps", json!({"id": a.0, "name": name})),
|
||||
("layer.setProps", json!({"ids": [face.0, a.0], "name": name})),
|
||||
];
|
||||
for (c, p) in calls {
|
||||
let err = s.execute(c, &p).unwrap_err().to_string();
|
||||
assert!(err.contains("give the path another name"), "{c} {p}: {err}");
|
||||
}
|
||||
}
|
||||
assert!(s.doc().unwrap().doc == before.0, "nothing was renamed");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), before.1);
|
||||
s.execute("layer.setProps", &json!({"id": face.0, "name": FACE_NAME})).unwrap();
|
||||
s.execute("object.exitIsolation", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g), "the hidden path stays in the group");
|
||||
s.execute("livePaint.gapOptions", &json!({"ids": [g.0], "detect": true})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g), "Gap Options keeps the path");
|
||||
let b = line_to_right_face(&mut s, 30.0);
|
||||
s.execute("layer.move", &json!({"ids": [b.0], "target": g.0, "place": "inside"})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g), "a path dragged in keeps it");
|
||||
assert_eq!(faces(&node(&s, g)).len(), 5);
|
||||
}
|
||||
|
||||
/// A path pasted into an isolated Live Paint group under the name of a face or an edge loses the
|
||||
/// name, so Gap Options keeps it and it joins the group's paths when isolation mode ends.
|
||||
#[test]
|
||||
fn live_paint_paste_clears_part_names() {
|
||||
use vectorcraft_tools::builder::{EDGE_NAME, FACE_NAME, faces, sources};
|
||||
for name in [FACE_NAME, EDGE_NAME] {
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
let r = rect(&mut s, 20.0, 40.0, 60.0, 20.0);
|
||||
s.execute("object.setProps", &json!({"id": r.0, "name": name})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [r.0]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
|
||||
s.execute("edit.pasteInPlace", &json!({})).unwrap();
|
||||
let pasted = s.doc().unwrap().selection.objects.clone();
|
||||
assert_eq!(pasted.len(), 1);
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.parent_of(pasted[0]), Some(g), "{name}: the paste goes into the group");
|
||||
assert_eq!(d.node(pasted[0]).unwrap().name, None, "{name}: the paste loses the name");
|
||||
assert_eq!(d.node(r).unwrap().name.as_deref(), Some(name), "the path outside keeps its name");
|
||||
s.execute("livePaint.gapOptions", &json!({"ids": [g.0], "detect": true})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(pasted[0]), Some(g), "{name}: Gap Options keeps the paste");
|
||||
s.execute("object.exitIsolation", &json!({})).unwrap();
|
||||
let n = node(&s, g);
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(pasted[0]), Some(sources(&n).unwrap().id), "{name}: the paste joined");
|
||||
assert!(faces(&n).len() > 3);
|
||||
}
|
||||
}
|
||||
|
||||
/// With Real-time Drawing and Editing off, a rectangle still being drawn in a Live Paint group
|
||||
/// isolated in a pattern tile is drawn first when Exit Isolation Mode leaves pattern editing, and
|
||||
/// joins the group with the tile saved.
|
||||
@@ -5098,6 +5165,315 @@ fn live_paint_isolation_adds_a_drawn_group_isolated_inside_it() {
|
||||
}
|
||||
}
|
||||
|
||||
/// With Live Paint group `inner` made in isolated Live Paint group `outer` and then isolated itself,
|
||||
/// leaving both levels (`object.exitIsolation`, or `object.isolate` on the layer) adds the path drawn
|
||||
/// in `inner` to it and then `inner` and the path drawn directly in `outer` to `outer`, one undo step
|
||||
/// each. Isolating `outer` from `inner` adds only `inner`'s drawn path, and `outer` keeps its own.
|
||||
#[test]
|
||||
fn live_paint_isolation_merges_nested_live_paint_groups_it_leaves() {
|
||||
use vectorcraft_tools::builder::{faces, sources};
|
||||
for to in ["exit", "layer", "outer"] {
|
||||
let mut s = session();
|
||||
let outer = live(&mut s);
|
||||
let layer = s.doc().unwrap().doc.parent_of(outer).unwrap();
|
||||
s.execute("object.isolate", &json!({"id": outer.0})).unwrap();
|
||||
let a = line_across(&mut s, 50.0);
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(outer));
|
||||
let inner = live(&mut s);
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(inner), Some(outer), "the inner group is drawn in the outer one");
|
||||
s.execute("object.isolate", &json!({"id": inner.0})).unwrap();
|
||||
let b = line_across(&mut s, 30.0);
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(b), Some(inner));
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
match to {
|
||||
"exit" => s.execute("object.exitIsolation", &json!({})).unwrap(),
|
||||
"layer" => s.execute("object.isolate", &json!({"id": layer.0})).unwrap(),
|
||||
_ => s.execute("object.isolate", &json!({"id": outer.0})).unwrap(),
|
||||
};
|
||||
let d = &s.doc().unwrap().doc;
|
||||
if to == "outer" {
|
||||
assert_eq!(s.doc().unwrap().isolation, Some(outer));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "only the inner group's path joins");
|
||||
let n = node(&s, inner);
|
||||
assert_eq!(d.parent_of(b), Some(sources(&n).unwrap().id), "the path drawn in the inner group joined it");
|
||||
assert_eq!(d.parent_of(inner), Some(outer), "the inner group stays drawn in the outer one");
|
||||
assert_eq!(d.parent_of(a), Some(outer), "the path drawn in the outer group stays as drawn");
|
||||
continue;
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 2, "{to}: one undo step for each group");
|
||||
assert!(d.node(inner).is_none(), "{to}: the inner group joined the outer one");
|
||||
let n = node(&s, outer);
|
||||
let src = sources(&n).unwrap().id;
|
||||
assert_eq!(d.parent_of(a), Some(src), "{to}: the path drawn in the outer group joined it");
|
||||
assert!(d.ancestry(b).unwrap().contains(&src), "{to}: the path drawn in the inner group is among the outer group's paths");
|
||||
assert!(n.children().unwrap().iter().all(|c| c.id == src || c.path_data().is_some()), "{to}: only parts are left in the outer group");
|
||||
assert!(faces(&n).len() > 3, "{to}: the added paths cut the outer group's faces");
|
||||
if to == "exit" {
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![outer]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A line from left of the [`live`] group to its right face, so it cuts the two faces left of it.
|
||||
fn line_to_right_face(s: &mut Session, y: f64) -> NodeId {
|
||||
let r = s.execute("path.create", &json!({"anchors": [{"x": -10, "y": y}, {"x": 105, "y": y}]})).unwrap();
|
||||
NodeId(r["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn undo_label(s: &Session) -> Option<String> {
|
||||
s.doc().unwrap().history.undo.last().map(|e| e.label.clone())
|
||||
}
|
||||
|
||||
/// Paths dragged into a Live Paint group in the Layers panel join its paths as Live Paint › Merge
|
||||
/// adds them: they go among its sources and cut the faces they cross, a painted face they do not
|
||||
/// cross keeps its fill, and the drop is one "Merge Live Paint" undo step that selects the group.
|
||||
#[test]
|
||||
fn layers_drag_adds_paths_to_a_live_paint_group() {
|
||||
use vectorcraft_tools::builder::{face_at, faces, sources};
|
||||
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
s.execute("livePaint.fill", &json!({"group": g.0, "point": [125, 50], "color": "#00ff00"})).unwrap();
|
||||
let layer = s.doc().unwrap().doc.parent_of(g);
|
||||
let (a, b) = (line_to_right_face(&mut s, 30.0), line_to_right_face(&mut s, 70.0));
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(a), layer);
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
let r = s.execute("layer.move", &json!({"ids": [a.0, b.0], "target": g.0, "place": "inside"})).unwrap();
|
||||
assert_eq!(r["ids"], json!([g.0]), "the rows that joined are listed as the group");
|
||||
let d = s.doc().unwrap();
|
||||
assert_eq!(d.history.undo.len(), steps + 1, "both paths join in one undo step");
|
||||
assert_eq!(undo_label(&s).as_deref(), Some("Merge Live Paint"));
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![g]);
|
||||
let n = node(&s, g);
|
||||
let src = sources(&n).unwrap();
|
||||
assert_eq!(src.children().unwrap().len(), 4);
|
||||
for id in [a, b] {
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(src.id), "{id} joined the sources");
|
||||
}
|
||||
assert_eq!(faces(&n).len(), 7, "two lines cut each of the two faces they cross in three");
|
||||
assert_eq!(face_at(&n, Point::new(125.0, 50.0)).unwrap().appearance.fill_paint(), green, "the face the lines do not cross keeps its fill");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(faces(&node(&s, g)).len(), 3);
|
||||
for id in [a, b] {
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(id), layer, "Undo puts {id} back where it was");
|
||||
}
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(faces(&node(&s, g)).len(), 7);
|
||||
}
|
||||
|
||||
/// A path named like a Live Paint group's sources group joins the group when it is dragged in, in
|
||||
/// front of the sources group or behind it: the group keeps its own sources group and the path
|
||||
/// goes among its paths.
|
||||
#[test]
|
||||
fn layers_drag_of_a_path_named_like_the_sources_group_joins_a_live_paint_group() {
|
||||
use vectorcraft_tools::builder::{SOURCES_NAME, faces, sources};
|
||||
for index in [0, 99] {
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
let a = line_to_right_face(&mut s, 30.0);
|
||||
s.execute("object.setProps", &json!({"id": a.0, "name": SOURCES_NAME})).unwrap();
|
||||
s.execute("node.move", &json!({"id": a.0, "parent": g.0, "index": index})).unwrap();
|
||||
assert_eq!(undo_label(&s).as_deref(), Some("Merge Live Paint"), "index {index}");
|
||||
let n = node(&s, g);
|
||||
let src = sources(&n).unwrap();
|
||||
assert!(src.children().is_some(), "index {index}: the sources group is a group");
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(src.id), "index {index}: the path joined the sources");
|
||||
assert_eq!(faces(&n).len(), 5, "index {index}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An object drawn in a Live Paint group and named like its sources group can be moved ahead of the
|
||||
/// sources group: the group keeps its own sources group and stays a Live Paint group.
|
||||
#[test]
|
||||
fn layers_reorder_of_an_object_named_like_the_sources_group_keeps_the_live_paint_group() {
|
||||
use vectorcraft_tools::builder::{SOURCES_NAME, is_live_paint, sources};
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
let real = sources(&node(&s, g)).unwrap().id;
|
||||
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
|
||||
let a = line_across(&mut s, 50.0);
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g));
|
||||
s.execute("object.setProps", &json!({"id": a.0, "name": SOURCES_NAME})).unwrap();
|
||||
s.execute("node.move", &json!({"id": a.0, "parent": g.0, "index": 0})).unwrap();
|
||||
let n = node(&s, g);
|
||||
assert!(is_live_paint(&n));
|
||||
assert_eq!(sources(&n).unwrap().id, real);
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g), "the object stays where it was drawn");
|
||||
}
|
||||
|
||||
/// A path named `Face` that is dragged into a Live Paint group is not one of its faces: the face it
|
||||
/// covers keeps its own fill.
|
||||
#[test]
|
||||
fn layers_drag_of_a_path_named_face_does_not_repaint_the_group() {
|
||||
use vectorcraft_tools::builder::{face_at, faces};
|
||||
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 50], "color": "#00ff00"})).unwrap();
|
||||
let a = rect(&mut s, 0.0, 0.0, 50.0, 100.0);
|
||||
set_fill(&mut s, a, Color::rgb(0.0, 0.0, 1.0));
|
||||
s.execute("object.setProps", &json!({"id": a.0, "name": "Face"})).unwrap();
|
||||
s.execute("node.move", &json!({"id": a.0, "parent": g.0, "index": 99})).unwrap();
|
||||
let n = node(&s, g);
|
||||
assert_eq!(faces(&n).len(), 3);
|
||||
assert_eq!(face_at(&n, Point::new(25.0, 50.0)).unwrap().appearance.fill_paint(), green);
|
||||
}
|
||||
|
||||
/// An Alt-drag into a Live Paint group adds a copy and leaves the path where it was; a drop above
|
||||
/// one of the group's faces, and `node.move` into the group, add the path the same way.
|
||||
#[test]
|
||||
fn layers_drag_copy_and_drop_beside_a_part_add_to_a_live_paint_group() {
|
||||
use vectorcraft_tools::builder::{faces, sources};
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
let layer = s.doc().unwrap().doc.parent_of(g);
|
||||
let a = line_to_right_face(&mut s, 30.0);
|
||||
s.execute("layer.move", &json!({"ids": [a.0], "target": g.0, "copy": true})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(a), layer, "the path itself stays");
|
||||
let n = node(&s, g);
|
||||
assert_eq!(faces(&n).len(), 5);
|
||||
let src = sources(&n).unwrap().children().unwrap().clone();
|
||||
assert_eq!(src.len(), 3);
|
||||
assert!(src.iter().all(|c| c.id != a), "a copy joined");
|
||||
let (face, other_face) = (faces(&n)[0].id, faces(&n)[1].id);
|
||||
let b = line_to_right_face(&mut s, 70.0);
|
||||
// A face dragged along is made again with the others, so only the group is listed.
|
||||
let r = s.execute("layer.move", &json!({"ids": [b.0, other_face.0], "target": face.0, "place": "above"})).unwrap();
|
||||
assert_eq!(r["ids"], json!([g.0]));
|
||||
assert_eq!(s.doc().unwrap().layer_rows, vec![g]);
|
||||
let n = node(&s, g);
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(b), Some(sources(&n).unwrap().id), "a drop beside a face joins");
|
||||
assert_eq!(faces(&n).len(), 7);
|
||||
let c = line_to_right_face(&mut s, 50.0);
|
||||
s.execute("node.move", &json!({"id": c.0, "parent": g.0, "index": 0})).unwrap();
|
||||
assert_eq!(undo_label(&s).as_deref(), Some("Merge Live Paint"));
|
||||
let n = node(&s, g);
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(c), Some(sources(&n).unwrap().id), "node.move into the group joins");
|
||||
assert_eq!(faces(&n).len(), 9);
|
||||
}
|
||||
|
||||
/// Dragging type, or type with a path, into a Live Paint group is refused with Make's message and
|
||||
/// moves nothing, as Merge refuses it; a drop beside the group is an ordinary move.
|
||||
#[test]
|
||||
fn layers_drag_refuses_type_into_a_live_paint_group() {
|
||||
use vectorcraft_tools::builder::faces;
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
let layer = s.doc().unwrap().doc.parent_of(g);
|
||||
let a = line_to_right_face(&mut s, 30.0);
|
||||
let text = NodeId(s.execute("text.create", &json!({"x": 20, "y": 20, "text": "Hi"})).unwrap()["id"].as_u64().unwrap());
|
||||
let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
|
||||
for p in [json!({"ids": [a.0, text.0], "target": g.0}), json!({"ids": [text.0], "target": g.0, "copy": true})] {
|
||||
let err = s.execute("layer.move", &p).unwrap_err().to_string();
|
||||
assert!(err.contains("Live Paint takes paths and compound paths"), "{err}");
|
||||
}
|
||||
assert!(s.execute("node.move", &json!({"id": text.0, "parent": g.0, "index": 0})).is_err());
|
||||
assert!(s.doc().unwrap().doc == before.0, "nothing moved");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), before.1);
|
||||
s.execute("layer.move", &json!({"ids": [a.0, text.0], "target": g.0, "place": "above"})).unwrap();
|
||||
assert_eq!(undo_label(&s).as_deref(), Some("Move Rows"));
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(text), layer);
|
||||
assert_eq!(faces(&node(&s, g)).len(), 3);
|
||||
}
|
||||
|
||||
/// A path dragged out of a Live Paint group's sources leaves its faces and edges: the group makes
|
||||
/// them again from the paths left, and with none left it has no faces until a path joins it again.
|
||||
/// Reordering the sources, or the group's own faces, makes nothing again.
|
||||
#[test]
|
||||
fn layers_drag_out_of_a_live_paint_group_makes_its_faces_again() {
|
||||
use vectorcraft_tools::builder::{faces, sources};
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
let layer = s.doc().unwrap().doc.parent_of(g).unwrap();
|
||||
let n = node(&s, g);
|
||||
let src: Vec<NodeId> = sources(&n).unwrap().children().unwrap().iter().map(|c| c.id).collect();
|
||||
let face_ids: Vec<NodeId> = faces(&n).iter().map(|f| f.id).collect();
|
||||
s.execute("layer.move", &json!({"ids": [src[0].0], "target": src[1].0, "place": "above"})).unwrap();
|
||||
s.execute("layer.move", &json!({"ids": [face_ids[0].0], "target": face_ids[2].0, "place": "above"})).unwrap();
|
||||
let n = node(&s, g);
|
||||
assert_eq!(sources(&n).unwrap().children().unwrap().len(), 2, "a reorder keeps the sources");
|
||||
let mut now: Vec<NodeId> = faces(&n).iter().map(|f| f.id).collect();
|
||||
now.sort();
|
||||
let mut was = face_ids.clone();
|
||||
was.sort();
|
||||
assert_eq!(now, was, "and the faces");
|
||||
s.execute("layer.move", &json!({"ids": [src[0].0], "target": layer.0})).unwrap();
|
||||
assert_eq!(undo_label(&s).as_deref(), Some("Move Rows"));
|
||||
let n = node(&s, g);
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(src[0]), Some(layer));
|
||||
assert_eq!(sources(&n).unwrap().children().unwrap().len(), 1);
|
||||
assert_eq!(faces(&n).len(), 1, "one rectangle left");
|
||||
s.execute("node.move", &json!({"id": src[1].0, "parent": layer.0, "index": 0})).unwrap();
|
||||
let n = node(&s, g);
|
||||
assert!(vectorcraft_tools::builder::is_live_paint(&n), "the group stays a Live Paint group");
|
||||
assert!(sources(&n).unwrap().children().unwrap().is_empty());
|
||||
assert!(faces(&n).is_empty() && vectorcraft_tools::builder::edges(&n).is_empty());
|
||||
s.execute("layer.move", &json!({"ids": [src[0].0], "target": g.0})).unwrap();
|
||||
assert_eq!(faces(&node(&s, g)).len(), 1, "a path joins the empty group");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(faces(&node(&s, g)).len(), 1);
|
||||
}
|
||||
|
||||
/// A path dragged from a Live Paint group's sources into the group itself stays among its paths,
|
||||
/// and the faces it bounds keep their paint, also when it is the group's only path.
|
||||
#[test]
|
||||
fn layers_drag_a_source_path_into_its_own_live_paint_group_keeps_the_paint() {
|
||||
use vectorcraft_tools::builder::{face_at, faces, sources};
|
||||
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
|
||||
let blue = Paint::solid(Color::from_hex("#0000ff").unwrap());
|
||||
let mut s = session();
|
||||
let g = live(&mut s);
|
||||
let layer = s.doc().unwrap().doc.parent_of(g).unwrap();
|
||||
s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 50], "color": "#00ff00"})).unwrap();
|
||||
let src: Vec<NodeId> = sources(&node(&s, g)).unwrap().children().unwrap().iter().map(|c| c.id).collect();
|
||||
s.execute("layer.move", &json!({"ids": [src[0].0], "target": g.0, "place": "inside"})).unwrap();
|
||||
let n = node(&s, g);
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(src[0]), Some(sources(&n).unwrap().id), "the path stays among the group's paths");
|
||||
assert_eq!(faces(&n).len(), 3);
|
||||
assert_eq!(face_at(&n, Point::new(25.0, 50.0)).unwrap().appearance.fill_paint(), green, "the face it bounds keeps its fill");
|
||||
s.execute("layer.move", &json!({"ids": [src[1].0], "target": layer.0})).unwrap();
|
||||
s.execute("livePaint.fill", &json!({"group": g.0, "point": [50, 50], "color": "#0000ff"})).unwrap();
|
||||
s.execute("layer.move", &json!({"ids": [src[0].0], "target": g.0, "place": "inside"})).unwrap();
|
||||
let n = node(&s, g);
|
||||
assert_eq!(faces(&n).len(), 1);
|
||||
assert_eq!(face_at(&n, Point::new(50.0, 50.0)).unwrap().appearance.fill_paint(), blue, "the only path's face keeps its fill");
|
||||
}
|
||||
|
||||
/// A Live Paint group among another Live Paint group's paths gives it faces and edges: a path
|
||||
/// dragged into or out of the inner group's paths, or from the outer group's paths into the inner
|
||||
/// group's, makes the inner group's faces and edges again and then the outer group's.
|
||||
#[test]
|
||||
fn layers_drag_into_a_nested_live_paint_group_makes_the_outer_group_again() {
|
||||
use vectorcraft_tools::builder::{faces, sources};
|
||||
let mut s = session();
|
||||
let outer = live(&mut s);
|
||||
let inner = live(&mut s);
|
||||
let layer = s.doc().unwrap().doc.parent_of(outer).unwrap();
|
||||
let first_source = |s: &Session, g: NodeId| sources(&node(s, g)).unwrap().children().unwrap()[0].id;
|
||||
let into = |s: &mut Session, row: NodeId, g: NodeId| {
|
||||
let target = first_source(s, g);
|
||||
s.execute("layer.move", &json!({"ids": [row.0], "target": target.0, "place": "above"})).unwrap();
|
||||
};
|
||||
into(&mut s, inner, outer);
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(inner), Some(sources(&node(&s, outer)).unwrap().id));
|
||||
let plain = faces(&node(&s, outer)).len();
|
||||
let a = line_to_right_face(&mut s, 30.0);
|
||||
into(&mut s, a, inner);
|
||||
assert_eq!(faces(&node(&s, inner)).len(), 5);
|
||||
let cut = faces(&node(&s, outer)).len();
|
||||
assert!(cut > plain, "a path joining the inner group cuts the outer group's faces: {cut} faces, {plain} before");
|
||||
s.execute("layer.move", &json!({"ids": [a.0], "target": layer.0})).unwrap();
|
||||
assert_eq!(faces(&node(&s, inner)).len(), 3);
|
||||
assert_eq!(faces(&node(&s, outer)).len(), plain, "a path leaving the inner group leaves the outer group's faces");
|
||||
into(&mut s, a, outer);
|
||||
assert_eq!(faces(&node(&s, outer)).len(), cut);
|
||||
into(&mut s, a, inner);
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(sources(&node(&s, inner)).unwrap().id));
|
||||
assert_eq!(faces(&node(&s, inner)).len(), 5);
|
||||
assert_eq!(faces(&node(&s, outer)).len(), cut, "the outer group is made after the inner one");
|
||||
}
|
||||
|
||||
/// Give Live Paint group `g` a lock, hidden state, appearance, knockout, opacity mask and
|
||||
/// graphic style link, and return it as it then is.
|
||||
fn dress_live_group(s: &mut Session, g: NodeId) -> Node {
|
||||
|
||||
@@ -696,3 +696,108 @@ fn a_locked_or_hidden_layer_keeps_the_isolated_compound_shape_from_clicks() {
|
||||
assert!(selected(&s).is_empty(), "{prop}: nor by a marquee");
|
||||
}
|
||||
}
|
||||
|
||||
/// A straight line, closed as a compound shape closes open paths, encloses no area, so it
|
||||
/// contributes no area to the shape: Make Compound Shape still makes it, in any mode and at any
|
||||
/// place in the stack, and its reply carries a warning that names Outline Stroke. The shape draws
|
||||
/// the area the other members make in that mode: the square alone in Add, or on top in Subtract,
|
||||
/// and nothing in Intersect or when the line is the backmost member in Subtract. A line in a group,
|
||||
/// beside a closed path too, an open evenodd square traced twice, and open evenodd subpaths that cancel one another or a closed
|
||||
/// subpath of the same path are the same. An open path that encloses an area once closed (a bow tie
|
||||
/// whose lobes cancel in signed area included) and closed shapes alone give no warning (#7849).
|
||||
#[test]
|
||||
fn lines_that_add_no_area_are_reported() {
|
||||
use crate::cmd::OPEN_PATHS_ADD_NO_AREA;
|
||||
fn line_of(s: &mut Session) -> NodeId {
|
||||
NodeId(run(s, "shape.line", json!({"x1": 20, "y1": 50, "x2": 180, "y2": 50}))["id"].as_u64().unwrap())
|
||||
}
|
||||
fn vee_of(s: &mut Session) -> NodeId {
|
||||
let anchors = json!([{"x": 20, "y": 50}, {"x": 100, "y": 150}, {"x": 180, "y": 50}]);
|
||||
NodeId(run(s, "path.create", json!({ "anchors": anchors }))["id"].as_u64().unwrap())
|
||||
}
|
||||
fn bow_tie_of(s: &mut Session) -> NodeId {
|
||||
let anchors = json!([{"x": 20, "y": 0}, {"x": 180, "y": 100}, {"x": 180, "y": 0}, {"x": 20, "y": 100}]);
|
||||
NodeId(run(s, "path.create", json!({ "anchors": anchors }))["id"].as_u64().unwrap())
|
||||
}
|
||||
fn twice_around_of(s: &mut Session) -> NodeId {
|
||||
let d = "M20 20 L80 20 L80 80 L20 80 L20 20 L80 20 L80 80 L20 80";
|
||||
let id = NodeId(run(s, "path.create", json!({ "d": d }))["id"].as_u64().unwrap());
|
||||
run(s, "path.setFillRule", json!({"rule": "evenOdd"}));
|
||||
id
|
||||
}
|
||||
fn evenodd_of(s: &mut Session, d: &str) -> NodeId {
|
||||
let id = NodeId(run(s, "path.create", json!({ "d": d }))["id"].as_u64().unwrap());
|
||||
run(s, "path.setFillRule", json!({"rule": "evenOdd"}));
|
||||
id
|
||||
}
|
||||
fn two_open_squares_of(s: &mut Session) -> NodeId {
|
||||
evenodd_of(s, "M20 20 L80 20 L80 80 L20 80 M20 20 L80 20 L80 80 L20 80")
|
||||
}
|
||||
fn open_over_closed_of(s: &mut Session) -> NodeId {
|
||||
evenodd_of(s, "M20 20 L80 20 L80 80 L20 80 Z M20 20 L80 20 L80 80 L20 80")
|
||||
}
|
||||
fn group_of(s: &mut Session, ids: &[NodeId]) -> NodeId {
|
||||
run(s, "select.set", json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()}));
|
||||
NodeId(run(s, "object.group", json!({}))["id"].as_u64().unwrap())
|
||||
}
|
||||
type Build = fn(&mut Session) -> NodeId;
|
||||
// (case, mode, the other member, whether it goes behind the 100 pt square, warned, area drawn)
|
||||
type Case = (&'static str, &'static str, Build, bool, bool, Option<f64>);
|
||||
let cases: [Case; 13] = [
|
||||
("an open evenodd square traced twice", "add", twice_around_of, false, true, Some(10_000.0)),
|
||||
("two open evenodd squares on one another", "add", two_open_squares_of, false, true, Some(10_000.0)),
|
||||
("an open evenodd square on the same closed square", "add", open_over_closed_of, false, true, Some(10_000.0)),
|
||||
("a line", "add", line_of, false, true, Some(10_000.0)),
|
||||
("a line, subtracting", "subtract", line_of, false, true, Some(10_000.0)),
|
||||
("a line, intersecting", "intersect", line_of, false, true, Some(0.0)),
|
||||
("a line behind, subtracting", "subtract", line_of, true, true, Some(0.0)),
|
||||
(
|
||||
"a group of lines",
|
||||
"add",
|
||||
|s| {
|
||||
let ids = [line_of(s), line_of(s)];
|
||||
group_of(s, &ids)
|
||||
},
|
||||
false,
|
||||
true,
|
||||
Some(10_000.0),
|
||||
),
|
||||
(
|
||||
"a group of a line and a square",
|
||||
"add",
|
||||
|s| {
|
||||
let ids = [line_of(s), square(s, 200.0, "#00ff00")];
|
||||
group_of(s, &ids)
|
||||
},
|
||||
false,
|
||||
true,
|
||||
Some(20_000.0),
|
||||
),
|
||||
("an open path that encloses an area", "add", vee_of, false, false, None),
|
||||
("an open bow tie, whose signed area is zero", "add", bow_tie_of, false, false, None),
|
||||
("a square", "add", |s| square(s, 50.0, "#0000ff"), false, false, Some(15_000.0)),
|
||||
("a square, subtracting", "subtract", |s| square(s, 50.0, "#0000ff"), false, false, Some(5_000.0)),
|
||||
];
|
||||
for (what, mode, build, behind, warned, want) in cases {
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "file.new", json!({"width": 400, "height": 300}));
|
||||
let (back, front) = if behind {
|
||||
let other = build(&mut s);
|
||||
(other, square(&mut s, 0.0, "#ff0000"))
|
||||
} else {
|
||||
let sq = square(&mut s, 0.0, "#ff0000");
|
||||
(sq, build(&mut s))
|
||||
};
|
||||
run(&mut s, "select.set", json!({"ids": [back.0, front.0]}));
|
||||
let r = run(&mut s, "object.compoundShape.make", json!({ "mode": mode }));
|
||||
let id = NodeId(r["id"].as_u64().unwrap_or_else(|| panic!("{what}: {r}")));
|
||||
assert_eq!(node(&s, id).children().unwrap().len(), 2, "{what}: both are members");
|
||||
assert_eq!(r.get("warning").and_then(Value::as_str), warned.then_some(OPEN_PATHS_ADD_NO_AREA), "{what}: {r}");
|
||||
if let Some(want) = want {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let hook = |c: &Node| effects::outline_object(Some(d), c);
|
||||
let got = effects::compound_shape_area(None, &node(&s, id), Some(&hook)).map_or(0.0, |p| area(&p));
|
||||
assert!((got - want).abs() < 0.5, "{what}: draws {got}, not {want}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -407,7 +407,7 @@ fn image_with_shaped_fill(s: &mut Session) -> NodeId {
|
||||
/// outline with `outline`.
|
||||
fn marquee_at(s: &Session, x0: f64, x1: f64, outline: bool) -> Vec<NodeId> {
|
||||
let r = vectorcraft_geom::Rect::new(x0, 90.0, x1, 110.0);
|
||||
vectorcraft_doc::hit::marquee_in_view(&s.doc().unwrap().doc, r, None, true, outline)
|
||||
vectorcraft_doc::hit::marquee_in_view(&s.doc().unwrap().doc, r, None, true, outline, false)
|
||||
}
|
||||
|
||||
/// A marquee touches a symbol instance where the geometry effects of its fill or stroke paint its
|
||||
|
||||
@@ -377,7 +377,7 @@ fn ids_cases(d: u64) -> Vec<(&'static str, &'static str, serde_json::Value, Unse
|
||||
("addon.color.filter", "ids", json!({"effect": "addon.color.invert"}), Selected),
|
||||
("addon.color.applyNearestSwatch", "ids", json!({}), Selected),
|
||||
("edit.colors.overprintBlack", "ids", json!({}), Selected),
|
||||
("edit.findReplace", "ids", json!({"find": "A", "replace": "B"}), Gives(json!({"count": 1}))),
|
||||
("edit.findReplace", "ids", json!({"find": "A", "replace": "B"}), Gives(json!({"count": 1, "replaced": 1}))),
|
||||
("layer.highlight", "ids", json!({}), Fails("missing ids")),
|
||||
("layer.move", "ids", json!({ "target": d }), Fails("missing ids")),
|
||||
("library.add", "ids", json!({"kind": "graphic"}), Selected),
|
||||
|
||||
@@ -167,6 +167,183 @@ fn clicking_rows_at_any_depth_highlights_them_and_sets_the_current_layer() {
|
||||
assert_eq!(document_rows(&s), vec![g.0, c.0], "document.inspect lists the rows");
|
||||
}
|
||||
|
||||
/// Run `layer.highlight` with `ids` and `mode` → (the rows it returned, the current layer), after
|
||||
/// checking that the call counted one revision and left the rows it returned highlighted.
|
||||
fn highlight_rows(s: &mut Session, ids: &[NodeId], mode: &str) -> (Vec<NodeId>, Option<NodeId>) {
|
||||
let revision = s.doc().unwrap().revision;
|
||||
let r = run(s, "layer.highlight", json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "mode": mode}));
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!(st.revision, revision + 1, "{mode} {ids:?}");
|
||||
let rows: Vec<NodeId> = r["rows"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect();
|
||||
assert_eq!(rows, st.layer_rows, "{mode} {ids:?}");
|
||||
(rows, st.active_layer)
|
||||
}
|
||||
|
||||
/// `layer.highlight` keeps the rows in highlight order: `set` and `add` take a repeated id once,
|
||||
/// `toggle` takes an id listed twice off and on again (or on and off, and its layer becomes the
|
||||
/// current one), unknown ids and ids after the first 100,000 are dropped, rows highlighted twice
|
||||
/// stay as they are on `add`, and `toggle` takes every copy off.
|
||||
#[test]
|
||||
fn highlighting_rows_keeps_their_order_with_repeated_unknown_and_excess_ids() {
|
||||
let mut s = session();
|
||||
let (layer, sub, a, g, b, c) = tree(&mut s);
|
||||
let unknown = NodeId(9999);
|
||||
assert_eq!(highlight_rows(&mut s, &[a, g, a, unknown, c], "set"), (vec![a, g, c], Some(layer)));
|
||||
assert_eq!(highlight_rows(&mut s, &[g, b, a, b], "add"), (vec![a, g, c, b], Some(sub)));
|
||||
assert_eq!(highlight_rows(&mut s, &[c, c], "toggle"), (vec![a, g, b, c], Some(layer)));
|
||||
// `sub` goes on and off again; it was the last row added, so its layer is the current one.
|
||||
assert_eq!(highlight_rows(&mut s, &[sub, sub], "toggle"), (vec![a, g, b, c], Some(sub)));
|
||||
assert_eq!(highlight_rows(&mut s, &[a, unknown], "toggle"), (vec![g, b, c], Some(layer)));
|
||||
assert_eq!(highlight_rows(&mut s, &[], "add"), (vec![g, b, c], Some(layer)));
|
||||
assert_eq!(highlight_rows(&mut s, &[], "toggle"), (vec![g, b, c], Some(layer)));
|
||||
s.doc_mut().unwrap().active_layer = Some(sub);
|
||||
assert_eq!(highlight_rows(&mut s, &[], "set"), (vec![], Some(sub)), "no rows: the current layer stays");
|
||||
let mut excess = vec![unknown; 100_000];
|
||||
excess.push(a);
|
||||
assert_eq!(highlight_rows(&mut s, &excess, "set"), (vec![], Some(sub)), "only the first 100,000 ids count");
|
||||
s.doc_mut().unwrap().layer_rows = vec![a, a, g];
|
||||
assert_eq!(highlight_rows(&mut s, &[a, c], "add"), (vec![a, a, g, c], Some(layer)));
|
||||
assert_eq!(highlight_rows(&mut s, &[a], "toggle"), (vec![g, c], Some(layer)));
|
||||
// The same with more than 8 ids.
|
||||
s.doc_mut().unwrap().layer_rows = vec![a, a, g];
|
||||
assert_eq!(highlight_rows(&mut s, &[a, c, c, c, c, c, c, c, c], "add"), (vec![a, a, g, c], Some(layer)));
|
||||
s.doc_mut().unwrap().layer_rows = vec![a, a, g];
|
||||
assert_eq!(highlight_rows(&mut s, &[a, b, b, b, b, b, b, b, b], "toggle"), (vec![g], Some(sub)), "`b` goes on and off 4 times");
|
||||
assert_eq!(highlight_rows(&mut s, &[c, g, sub, g, sub, a, unknown, a, c, layer], "toggle"), (vec![g, layer], Some(layer)));
|
||||
let revision = s.doc().unwrap().revision;
|
||||
assert!(s.execute("layer.highlight", &json!({"ids": [b.0], "mode": "nope"})).is_err());
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!((st.revision, st.layer_rows.clone()), (revision, vec![g, layer]), "a bad mode changes nothing");
|
||||
}
|
||||
|
||||
/// `layer.highlight`'s rule as a search of the highlighted rows for each id in `p`. The tests
|
||||
/// compare the command with it.
|
||||
fn highlight_by_search(st: &mut DocState, p: &Value) -> Value {
|
||||
let mut ids: Vec<NodeId> = p["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect();
|
||||
ids.truncate(crate::cmd::layer::MAX_ROWS);
|
||||
let mode = p["mode"].as_str().unwrap_or("set");
|
||||
ids.retain(|id| st.doc.node(*id).is_some());
|
||||
let mut rows = st.highlighted_rows();
|
||||
if mode == "set" {
|
||||
rows.clear();
|
||||
}
|
||||
let mut last = None;
|
||||
for id in ids {
|
||||
if mode == "toggle" && rows.contains(&id) {
|
||||
rows.retain(|r| *r != id);
|
||||
} else if !rows.contains(&id) {
|
||||
rows.push(id);
|
||||
last = Some(id);
|
||||
}
|
||||
}
|
||||
if let Some(layer) = last.or(rows.last().copied()).and_then(|id| st.doc.layer_containing(id)) {
|
||||
st.active_layer = Some(layer);
|
||||
}
|
||||
st.layer_rows = rows;
|
||||
st.revision += 1;
|
||||
json!({ "rows": st.layer_rows.iter().map(|i| i.0).collect::<Vec<_>>() })
|
||||
}
|
||||
|
||||
/// Two sessions with `n` squares on a layer and a sublayer after them, and the squares' ids.
|
||||
fn highlight_pair(n: usize) -> (Session, Session, Vec<NodeId>, NodeId) {
|
||||
let make = || {
|
||||
let mut s = super::large_edits::session(n, super::large_edits::square);
|
||||
let sub = id(&run(&mut s, "layer.newSublayer", json!({"name": "Sub"})));
|
||||
(s, sub)
|
||||
};
|
||||
let ((cmd, sub), (search, other)) = (make(), make());
|
||||
assert_eq!(sub, other);
|
||||
let squares = super::large_edits::layer(&cmd, 0).into_iter().filter(|i| *i != sub).collect();
|
||||
(cmd, search, squares, sub)
|
||||
}
|
||||
|
||||
/// `p` for `layer.highlight` with `ids` and `mode`.
|
||||
fn highlight_params(ids: impl IntoIterator<Item = NodeId>, mode: &str) -> Value {
|
||||
json!({"ids": ids.into_iter().map(|i| i.0).collect::<Vec<_>>(), "mode": mode})
|
||||
}
|
||||
|
||||
/// On 3,000 rows `layer.highlight` gives what [`highlight_by_search`] gives: the same rows in the
|
||||
/// same order, the same current layer and the same returned rows, with repeated, unknown and
|
||||
/// toggled ids.
|
||||
#[test]
|
||||
fn layer_highlight_matches_a_search_of_the_rows_for_each_id() {
|
||||
let (mut cmd, mut search, sq, sub) = highlight_pair(3_000);
|
||||
let unknown = NodeId(u64::MAX);
|
||||
let steps = [
|
||||
highlight_params(sq[..2_000].iter().copied(), "set"),
|
||||
highlight_params(sq[1_000..].iter().copied().chain([sub, sq[0]]), "add"),
|
||||
highlight_params([sq[5], sq[5], sub, sq[2_999], unknown, sub, sub], "toggle"),
|
||||
highlight_params(sq[500..520].iter().chain(&sq[510..515]).copied(), "toggle"),
|
||||
highlight_params(sq.iter().rev().step_by(7).copied(), "add"),
|
||||
highlight_params(sq.iter().step_by(3).copied().chain([sub]), "toggle"),
|
||||
highlight_params(Vec::new(), "add"),
|
||||
highlight_params(sq.iter().rev().step_by(2).chain(&sq[..10]).copied(), "set"),
|
||||
highlight_params(Vec::new(), "set"),
|
||||
];
|
||||
for p in &steps {
|
||||
let r = run(&mut cmd, "layer.highlight", p.clone());
|
||||
let expected = highlight_by_search(search.doc_mut().unwrap(), p);
|
||||
let (a, b) = (cmd.doc().unwrap(), search.doc().unwrap());
|
||||
assert_eq!(r, expected, "{}", p["mode"]);
|
||||
assert_eq!((&a.layer_rows, a.active_layer, a.revision), (&b.layer_rows, b.active_layer, b.revision), "{}", p["mode"]);
|
||||
}
|
||||
}
|
||||
|
||||
/// Time `layer.highlight` against [`highlight_by_search`] on one layer of 20,000 paths: `set` of
|
||||
/// all of them, `add` of 10,000 already highlighted and `toggle` of one, 7 runs each, both checked
|
||||
/// to give the same rows and current layer.
|
||||
/// Run with `cargo test --release -p vectorcraft-engine --lib layer_highlight_timing -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore = "manual timing probe; wall-clock performance depends on machine load"]
|
||||
fn layer_highlight_timing() {
|
||||
let (mut cmd, mut search, sq, _) = highlight_pair(20_000);
|
||||
let steps = [
|
||||
("set of 20,000", highlight_params(sq.iter().copied(), "set")),
|
||||
("add of 10,000", highlight_params(sq[5_000..15_000].iter().copied(), "add")),
|
||||
("toggle of 1", highlight_params([sq[10_000]], "toggle")),
|
||||
];
|
||||
let mut ms = vec![(Vec::new(), Vec::new()); steps.len()];
|
||||
for run_no in 0..7 {
|
||||
for (i, (_, p)) in steps.iter().enumerate() {
|
||||
let mut time_cmd = || {
|
||||
let start = std::time::Instant::now();
|
||||
let r = cmd.execute("layer.highlight", p).unwrap();
|
||||
(start.elapsed().as_secs_f64() * 1000.0, r)
|
||||
};
|
||||
let mut time_search = || {
|
||||
let start = std::time::Instant::now();
|
||||
let r = highlight_by_search(search.doc_mut().unwrap(), p);
|
||||
(start.elapsed().as_secs_f64() * 1000.0, r)
|
||||
};
|
||||
// Alternate which goes first.
|
||||
let ((tc, rc), (ts, rs)) = if run_no % 2 == 0 {
|
||||
let c = time_cmd();
|
||||
(c, time_search())
|
||||
} else {
|
||||
let s = time_search();
|
||||
(time_cmd(), s)
|
||||
};
|
||||
assert_eq!(rc, rs);
|
||||
let (a, b) = (cmd.doc().unwrap(), search.doc().unwrap());
|
||||
assert_eq!((&a.layer_rows, a.active_layer), (&b.layer_rows, b.active_layer));
|
||||
ms[i].0.push(ts);
|
||||
ms[i].1.push(tc);
|
||||
}
|
||||
}
|
||||
let median = |v: &[f64]| {
|
||||
let mut v = v.to_vec();
|
||||
v.sort_by(f64::total_cmp);
|
||||
v[v.len() / 2]
|
||||
};
|
||||
for ((name, _), (search_ms, cmd_ms)) in steps.iter().zip(&ms) {
|
||||
println!(
|
||||
"{name}: search {:.3} ms, command {:.3} ms (median of 7); search runs {search_ms:.3?}, command runs {cmd_ms:.3?}",
|
||||
median(search_ms),
|
||||
median(cmd_ms)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn document_rows(s: &Session) -> Vec<u64> {
|
||||
crate::inspect::document(s)["layerRows"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect()
|
||||
}
|
||||
@@ -1102,6 +1279,43 @@ fn locate_object_highlights_its_row() {
|
||||
assert!(s.execute("layer.locate", &json!({})).is_err());
|
||||
}
|
||||
|
||||
/// With several objects selected, Locate Object finds the frontmost one in the stacking order,
|
||||
/// whatever order they were selected in; an `id` still wins.
|
||||
#[test]
|
||||
fn locate_object_finds_the_frontmost_selected_object() {
|
||||
let mut s = session();
|
||||
let (_, sub, a, g, b, c) = tree(&mut s);
|
||||
let top = id(&run(&mut s, "layer.new", json!({"top": true})));
|
||||
let d = rect(&mut s, 400.0);
|
||||
let locate = |s: &mut Session, ids: &[NodeId]| {
|
||||
run(s, "select.set", json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()}));
|
||||
assert_eq!(s.doc().unwrap().selection.objects.last(), ids.last(), "selected in this order");
|
||||
run(s, "layer.locate", json!({}))["id"].clone()
|
||||
};
|
||||
// In one sublayer, the group in front of the rectangle selected last.
|
||||
assert_eq!(locate(&mut s, &[g, a]), json!(g.0));
|
||||
assert_eq!(s.doc().unwrap().highlighted_rows(), vec![g]);
|
||||
// The sublayer sits in front of the art directly in its layer.
|
||||
assert_eq!(locate(&mut s, &[a, c]), json!(a.0));
|
||||
// A higher layer wins over everything below it.
|
||||
assert_eq!(locate(&mut s, &[d, b, c]), json!(d.0));
|
||||
assert_eq!(s.doc().unwrap().highlighted_rows(), vec![d]);
|
||||
// A group and its member: the member paints after the group it is in.
|
||||
assert_eq!(locate(&mut s, &[b, g]), json!(b.0));
|
||||
// Added one at a time, as by Shift-clicks.
|
||||
run(&mut s, "select.set", json!({"ids": [d.0]}));
|
||||
run(&mut s, "select.add", json!({"ids": [a.0]}));
|
||||
assert_eq!(run(&mut s, "layer.locate", json!({}))["id"], d.0);
|
||||
// An id still locates that object, behind the selection or not.
|
||||
assert_eq!(run(&mut s, "layer.locate", json!({"id": c.0}))["id"], c.0);
|
||||
assert_eq!(s.doc().unwrap().highlighted_rows(), vec![c]);
|
||||
// Locate Layer takes the layer of the frontmost selected object.
|
||||
run(&mut s, "select.set", json!({"ids": [d.0, a.0]}));
|
||||
assert_eq!(run(&mut s, "layer.locate", json!({"layersOnly": true})), json!({"id": top.0, "objectId": d.0, "ancestry": [top.0]}));
|
||||
run(&mut s, "select.set", json!({"ids": [a.0, c.0]}));
|
||||
assert_eq!(run(&mut s, "layer.locate", json!({"layersOnly": true}))["id"], sub.0);
|
||||
}
|
||||
|
||||
/// Locate Layer (`layersOnly`, sent while Show Layers Only is on) highlights the innermost layer
|
||||
/// or sublayer holding the object, through any groups; a layer locates itself.
|
||||
#[test]
|
||||
|
||||
@@ -2377,7 +2377,8 @@ fn find_and_replace_leaves_type_on_a_locked_artboard() {
|
||||
|
||||
/// Find and Replace that replaces each match with the text it is (`CAT` found in `cat`, ignoring
|
||||
/// case, and replaced by `cat`) records no undo step: the step to redo stays and the document stays
|
||||
/// unmodified. It still replies with the count. A replacement that changes the text is one undo step.
|
||||
/// unmodified. It still replies with the count, and with no match replaced. A replacement that
|
||||
/// changes the text is one undo step.
|
||||
#[test]
|
||||
fn find_and_replace_that_changes_nothing_records_no_undo_step() {
|
||||
let mut s = session();
|
||||
@@ -2385,9 +2386,9 @@ fn find_and_replace_that_changes_nothing_records_no_undo_step() {
|
||||
select_with_a_step_to_redo(&mut s, &[a]);
|
||||
let before = history(&s);
|
||||
assert_eq!((before.1, before.2), (1, false), "a step to redo, and nothing unsaved");
|
||||
assert_eq!(s.execute("edit.findReplace", &json!({"find": "CAT", "replace": "cat"})).unwrap(), json!({"count": 2}));
|
||||
assert_eq!(s.execute("edit.findReplace", &json!({"find": "CAT", "replace": "cat"})).unwrap(), json!({"count": 2, "replaced": 0}));
|
||||
assert_eq!((history(&s), plain(&s, a)), (before, "cat cat".to_string()));
|
||||
assert_eq!(s.execute("edit.findReplace", &json!({"find": "cat", "replace": "dog"})).unwrap(), json!({"count": 2}));
|
||||
assert_eq!(s.execute("edit.findReplace", &json!({"find": "cat", "replace": "dog"})).unwrap(), json!({"count": 2, "replaced": 2}));
|
||||
assert_eq!((history(&s), plain(&s, a)), ((before.0 + 1, 0, true), "dog dog".to_string()));
|
||||
}
|
||||
|
||||
@@ -2424,12 +2425,190 @@ fn find_next_cycles_through_text_objects() {
|
||||
let _ = text(&mut s, "banana");
|
||||
let c = text(&mut s, "pineapple");
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert_eq!(id_of(&s.execute("edit.findNext", &json!({"find": "APPLE"})).unwrap()), a);
|
||||
// From the top of the stacking order down, then round again.
|
||||
assert_eq!(id_of(&s.execute("edit.findNext", &json!({"find": "APPLE"})).unwrap()), c);
|
||||
assert_eq!(id_of(&s.execute("edit.findNext", &json!({"find": "apple"})).unwrap()), a);
|
||||
assert_eq!(id_of(&s.execute("edit.findNext", &json!({"find": "apple"})).unwrap()), c);
|
||||
// A selection that starts with a shape goes on after its first type object.
|
||||
let shape = rect(&mut s, 300.0, 300.0, 20.0, 20.0);
|
||||
sel(&mut s, &[shape, c]);
|
||||
assert_eq!(id_of(&s.execute("edit.findNext", &json!({"find": "apple"})).unwrap()), a);
|
||||
assert!(s.execute("edit.findNext", &json!({"find": "zzz"})).unwrap()["id"].is_null());
|
||||
}
|
||||
|
||||
/// The match `r` (an `edit.findNext` result) as (object, start, end, index, count).
|
||||
fn found(r: &Value) -> (u64, u64, u64, u64, u64) {
|
||||
let n = |k: &str| r[k].as_u64().unwrap_or_else(|| panic!("no `{k}` in {r}"));
|
||||
(n("id"), n("start"), n("end"), n("index"), n("count"))
|
||||
}
|
||||
|
||||
/// Find Next steps through the matches one by one when each call is given the match before it:
|
||||
/// the objects from the top of the stacking order down, each object's matches in reading order,
|
||||
/// and round again after the last. Search Backwards visits them the other way. Each match is
|
||||
/// returned with its bytes and its object is selected; nothing is recorded for undo.
|
||||
#[test]
|
||||
fn find_next_steps_through_the_matches_in_both_directions() {
|
||||
let mut s = session();
|
||||
let bottom = text(&mut s, "cat éa cat");
|
||||
let _ = text(&mut s, "dog");
|
||||
let top = text(&mut s, "a cat");
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let before = history(&s);
|
||||
let step = |s: &mut Session, from: &Value, backwards: bool| {
|
||||
let from = if from.is_null() { Value::Null } else { json!({"id": from["id"], "start": from["start"], "end": from["end"]}) };
|
||||
s.execute("edit.findNext", &json!({"find": "cat", "from": from, "backwards": backwards})).unwrap()
|
||||
};
|
||||
// "é" is two bytes, so the second match of the bottom object is at bytes 8..11.
|
||||
let forward = [(top.0, 2, 5, 1, 3), (bottom.0, 0, 3, 2, 3), (bottom.0, 8, 11, 3, 3), (top.0, 2, 5, 1, 3)];
|
||||
let mut at = Value::Null;
|
||||
for want in forward {
|
||||
at = step(&mut s, &at, false);
|
||||
assert_eq!((found(&at), selected(&s), at["selected"].clone()), (want, vec![NodeId(want.0)], json!(true)));
|
||||
}
|
||||
let backward = [(bottom.0, 8, 11, 3, 3), (bottom.0, 0, 3, 2, 3), (top.0, 2, 5, 1, 3), (bottom.0, 8, 11, 3, 3)];
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let mut at = Value::Null;
|
||||
for want in backward {
|
||||
at = step(&mut s, &at, true);
|
||||
assert_eq!((found(&at), selected(&s)), (want, vec![NodeId(want.0)]));
|
||||
}
|
||||
assert_eq!(history(&s), before, "finding is no undo step");
|
||||
// A `from` in an object the search does not visit starts at the first match.
|
||||
let r = s.execute("edit.findNext", &json!({"find": "cat", "from": {"id": 999_999, "start": 0, "end": 0}})).unwrap();
|
||||
assert_eq!(found(&r), (top.0, 2, 5, 1, 3));
|
||||
// So does a null `from`, with a type object selected.
|
||||
sel(&mut s, &[top]);
|
||||
let r = s.execute("edit.findNext", &json!({"find": "cat", "from": null})).unwrap();
|
||||
assert_eq!(found(&r), (top.0, 2, 5, 1, 3));
|
||||
// Nothing found: no match, and the selection stays.
|
||||
let r = s.execute("edit.findNext", &json!({"find": "zebra"})).unwrap();
|
||||
assert_eq!((r, selected(&s)), (json!({"id": null, "count": 0}), vec![top]));
|
||||
}
|
||||
|
||||
/// Check Hidden Layers and Check Locked Layers: Find Next and Find and Replace leave the type of
|
||||
/// a hidden layer and of a locked layer alone unless the switch for it is on. A match on such a
|
||||
/// layer is returned without being selected. A hidden or locked object keeps its type out with
|
||||
/// the switches on.
|
||||
#[test]
|
||||
fn find_and_replace_reach_hidden_and_locked_layers_only_when_asked() {
|
||||
for (prop, switch, other) in [("visible", "hiddenLayers", "lockedLayers"), ("locked", "lockedLayers", "hiddenLayers")] {
|
||||
let mut s = session();
|
||||
let open = text(&mut s, "cat one");
|
||||
let layer = id_of(&s.execute("layer.new", &json!({})).unwrap());
|
||||
let closed = text(&mut s, "cat two");
|
||||
let object = text(&mut s, "cat three");
|
||||
let off = |id: NodeId| if prop == "visible" { json!({"id": id.0, "visible": false}) } else { json!({"id": id.0, "locked": true}) };
|
||||
s.execute("object.setProps", &off(object)).unwrap();
|
||||
s.execute("layer.setProps", &off(layer)).unwrap();
|
||||
sel(&mut s, &[open]);
|
||||
// Without the switch, and with only the other one, the one reachable match is found.
|
||||
for p in [json!({"find": "cat"}), json!({"find": "cat", other: true})] {
|
||||
let r = s.execute("edit.findNext", &p).unwrap();
|
||||
assert_eq!(found(&r), (open.0, 0, 3, 1, 1), "{prop} {p}");
|
||||
}
|
||||
// With it, the layer's type is searched (it is above, so it comes first) and not selected.
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let r = s.execute("edit.findNext", &json!({"find": "cat", switch: true})).unwrap();
|
||||
assert_eq!((found(&r), r["selected"].clone(), selected(&s)), ((closed.0, 0, 3, 1, 2), json!(false), vec![]), "{prop}");
|
||||
let r = s.execute("edit.findNext", &json!({"find": "cat", switch: true, "from": {"id": closed.0, "start": 0, "end": 3}})).unwrap();
|
||||
assert_eq!((found(&r), r["selected"].clone(), selected(&s)), ((open.0, 0, 3, 2, 2), json!(true), vec![open]), "{prop}");
|
||||
// Replace All: the same reach.
|
||||
let n = undo_len(&s);
|
||||
assert_eq!(
|
||||
s.execute("edit.findReplace", &json!({"find": "cat", "replace": "dog", other: true})).unwrap(),
|
||||
json!({"count": 1, "replaced": 1}),
|
||||
"{prop}"
|
||||
);
|
||||
assert_eq!((plain(&s, open), plain(&s, closed), plain(&s, object)), ("dog one".into(), "cat two".into(), "cat three".into()), "{prop}");
|
||||
assert_eq!(
|
||||
s.execute("edit.findReplace", &json!({"find": "cat", "replace": "dog", switch: true})).unwrap(),
|
||||
json!({"count": 1, "replaced": 1}),
|
||||
"{prop}"
|
||||
);
|
||||
assert_eq!((plain(&s, closed), plain(&s, object), undo_len(&s)), ("dog two".into(), "cat three".into(), n + 2), "{prop}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace changes one match, the bytes Find Next returned, as one undo step, and returns the
|
||||
/// replacement's bytes to go on from. Bytes that are no match are refused, and a match that
|
||||
/// already reads as the replacement is left with no undo step.
|
||||
#[test]
|
||||
fn replace_match_replaces_the_one_match_found() {
|
||||
let mut s = session();
|
||||
let t = text(&mut s, "cat cat Cat");
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let first = s.execute("edit.findNext", &json!({"find": "cat"})).unwrap();
|
||||
assert_eq!(found(&first), (t.0, 0, 3, 1, 3));
|
||||
let n = undo_len(&s);
|
||||
let r = s.execute("edit.replaceMatch", &json!({"find": "cat", "replace": "horse", "id": t.0, "start": 0, "end": 3})).unwrap();
|
||||
assert_eq!(r, json!({"id": t.0, "start": 0, "end": 5, "replaced": true}));
|
||||
assert_eq!((plain(&s, t), undo_len(&s)), ("horse cat Cat".to_string(), n + 1));
|
||||
// Replace & Find: on from the replacement, so text put in is not searched again.
|
||||
let r = s.execute("edit.replaceMatch", &json!({"find": "cat", "replace": "a cat", "id": t.0, "start": 6, "end": 9})).unwrap();
|
||||
let next = s.execute("edit.findNext", &json!({"find": "cat", "from": {"id": r["id"], "start": r["start"], "end": r["end"]}})).unwrap();
|
||||
assert_eq!((plain(&s, t), found(&next)), ("horse a cat Cat".to_string(), (t.0, 12, 15, 2, 2)));
|
||||
// Match Case decides what a match is.
|
||||
let shape = rect(&mut s, 300.0, 300.0, 20.0, 20.0);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let before = (history(&s), plain(&s, t));
|
||||
for (p, want) in [
|
||||
(json!({"find": "cat", "replace": "x", "matchCase": true, "id": t.0, "start": 12, "end": 15}), "at bytes 12..15 of object"),
|
||||
(json!({"find": "cat", "replace": "x", "id": t.0, "start": 1, "end": 4}), "at bytes 1..4 of object"),
|
||||
(json!({"find": "cat", "replace": "x", "id": t.0, "start": 4, "end": 1}), "at bytes 1..4 of object"),
|
||||
(json!({"find": "cat", "replace": "x", "id": t.0, "start": 0}), "missing `end`"),
|
||||
(json!({"find": "cat", "replace": "x", "start": 0, "end": 3}), "missing `id`"),
|
||||
(json!({"find": "cat", "replace": "x", "id": t.0, "start": "0", "end": 3}), "`start` must be a whole number"),
|
||||
(json!({"find": "", "replace": "x", "id": t.0, "start": 0, "end": 3}), "missing `find`"),
|
||||
(json!({"find": "cat", "replace": 5, "id": t.0, "start": 8, "end": 11}), "`replace` must be a string"),
|
||||
(json!({"find": "cat", "replace": "x", "id": shape.0, "start": 0, "end": 3}), "is not text"),
|
||||
] {
|
||||
let r = s.execute("edit.replaceMatch", &p);
|
||||
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg.contains(want)), "{p}: {r:?}");
|
||||
assert_eq!((history(&s), plain(&s, t)), before, "{p}");
|
||||
}
|
||||
let r = s.execute("edit.replaceMatch", &json!({"find": "cat", "replace": "x", "id": 999_999, "start": 0, "end": 3}));
|
||||
assert!(matches!(r, Err(EngineError::NoNode(NodeId(999_999)))), "{r:?}");
|
||||
// A match that already reads as the replacement: nothing to undo.
|
||||
let r = s.execute("edit.replaceMatch", &json!({"find": "CAT", "replace": "Cat", "id": t.0, "start": 12, "end": 15})).unwrap();
|
||||
assert_eq!((r, history(&s)), (json!({"id": t.0, "start": 12, "end": 15, "replaced": false}), before.0));
|
||||
// Find Next refuses a `from` that is not a match.
|
||||
for (from, want) in [
|
||||
(json!(5), "missing `id`"),
|
||||
(json!({"id": t.0, "start": 2}), "missing `end`"),
|
||||
(json!({"id": "x", "start": 0, "end": 1}), "`id` must be a whole number"),
|
||||
] {
|
||||
let r = s.execute("edit.findNext", &json!({"find": "cat", "from": from}));
|
||||
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg.contains(want)), "{from}: {r:?}");
|
||||
}
|
||||
for key in ["backwards", "hiddenLayers", "lockedLayers"] {
|
||||
let r = s.execute("edit.findNext", &json!({"find": "cat", key: "yes"}));
|
||||
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if *msg == format!("`{key}` must be true or false")), "{key}: {r:?}");
|
||||
}
|
||||
for key in ["hiddenLayers", "lockedLayers"] {
|
||||
let r = s.execute("edit.findReplace", &json!({"find": "cat", key: 1}));
|
||||
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if *msg == format!("`{key}` must be true or false")), "{key}: {r:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Ruby over text after a replaced match moves with the text, for Replace and for Replace All, as
|
||||
/// it does when the text is typed.
|
||||
#[test]
|
||||
fn find_and_replace_moves_the_ruby_after_a_match() {
|
||||
for all in [false, true] {
|
||||
let mut s = session();
|
||||
let t = text(&mut s, "ab 漢字");
|
||||
sel(&mut s, &[t]);
|
||||
s.execute("type.ruby", &json!({"text": "かんじ", "start": 3, "end": 9})).unwrap();
|
||||
if all {
|
||||
s.execute("edit.findReplace", &json!({"find": "ab", "replace": "abcd"})).unwrap();
|
||||
} else {
|
||||
s.execute("edit.replaceMatch", &json!({"find": "ab", "replace": "abcd", "id": t.0, "start": 0, "end": 2})).unwrap();
|
||||
}
|
||||
let NodeKind::Text(tt) = &node(&s, t).kind else { panic!() };
|
||||
assert_eq!((tt.plain_text().as_str(), tt.ruby.first().map(|r| (r.start, r.end))), ("abcd 漢字", Some((5, 11))), "all: {all}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The Type menu's commands and Find and Replace and Find Next refuse a param of the wrong type, or
|
||||
/// `ids` that name no object, with an error naming the param, and leave the text, the selection and
|
||||
/// the undo history as they were, even when Insert Character is also given a source it would use
|
||||
|
||||
@@ -836,6 +836,49 @@ fn a_null_in_group_colors_removes_that_swatch_and_the_ones_after_it_keep_their_p
|
||||
assert_eq!(link(&s, green), ("#00ff00".into(), Some(names[2].clone())), "art linked to a swatch that stays keeps its link");
|
||||
}
|
||||
|
||||
/// A gradient or pattern swatch of the group keeps its place and its paint when `recolor.apply`
|
||||
/// rewrites the group: the group's colors, from the rows or from `groupColors`, go to its color
|
||||
/// swatches in order.
|
||||
#[test]
|
||||
fn apply_with_a_group_keeps_its_gradient_swatch() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.newGroup", json!({"name": "Brand", "colors": ["#ff0000", "#0000ff"]}));
|
||||
let fade = vectorcraft_color::Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(vectorcraft_color::Gradient::default())));
|
||||
s.edit("test", |d, _| {
|
||||
let w = vectorcraft_color::Swatch { name: "Fade".into(), paint: fade.clone(), global: false, spot: false };
|
||||
d.swatch_groups.iter_mut().find(|g| g.name == "Brand").unwrap().swatches.insert(1, w);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let group = |s: &Session| -> Vec<(String, Option<String>)> {
|
||||
let g = s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Brand").unwrap().swatches.clone();
|
||||
g.iter().map(|w| (w.name.clone(), w.paint.color().map(|c| c.to_hex()))).collect()
|
||||
};
|
||||
let names: Vec<String> = group(&s).into_iter().map(|(n, _)| n).collect();
|
||||
rect(&mut s, json!("#ff0000"));
|
||||
rect(&mut s, json!("#0000ff"));
|
||||
select_all(&mut s);
|
||||
// The rows' new colors go to the red and blue swatches; the gradient stays between them.
|
||||
let map = json!([{"from": ["#ff0000"], "to": "#00ff00"}, {"from": ["#0000ff"], "to": "#ffff00"}]);
|
||||
run(&mut s, "recolor.apply", json!({"map": map, "group": "Brand"}));
|
||||
let want = |a: &str, b: &str| vec![(names[0].clone(), Some(a.to_string())), (names[1].clone(), None), (names[2].clone(), Some(b.to_string()))];
|
||||
assert_eq!(group(&s), want("#00ff00", "#ffff00"));
|
||||
assert_eq!(gradient_at(&s, 1), fade, "the gradient swatch keeps its paint");
|
||||
// `groupColors` counts the color swatches only: "keep" is the first, and the second color is
|
||||
// the blue swatch's.
|
||||
run(&mut s, "recolor.apply", json!({"map": [], "group": "Brand", "groupColors": ["keep", "#123456"]}));
|
||||
assert_eq!(group(&s), want("#00ff00", "#123456"));
|
||||
// A null removes the color swatch at its place and leaves the gradient.
|
||||
run(&mut s, "recolor.apply", json!({"map": [], "group": "Brand", "groupColors": [null, "#123456"]}));
|
||||
assert_eq!(group(&s), [(names[1].clone(), None), (names[2].clone(), Some("#123456".into()))]);
|
||||
assert_eq!(gradient_at(&s, 0), fade);
|
||||
}
|
||||
|
||||
/// The paint of the swatch at place `i` of the group "Brand".
|
||||
fn gradient_at(s: &Session, i: usize) -> vectorcraft_color::Paint {
|
||||
s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Brand").unwrap().swatches[i].paint.clone()
|
||||
}
|
||||
|
||||
/// A row whose new color was removed keeps its art's colors: art in it linked to another swatch of
|
||||
/// the group, which the rewrite gives another color, loses the link instead of following it.
|
||||
#[test]
|
||||
|
||||
@@ -77,6 +77,31 @@ fn script_missing_include_reports_origin() {
|
||||
assert!(report["message"].as_str().unwrap().contains("include file not found: nope.jsxinc"), "{report}");
|
||||
assert_eq!(report["log"], json!([]), "nothing ran before the include was read");
|
||||
assert!(report.get("file").is_none(), "the line is the script's own");
|
||||
assert_eq!(report["messageOrigin"], "built-in");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// An error in an included file keeps where its message came from: a value the file threw is the
|
||||
/// script's own text, and an error the app raised for it, or for a file `$.evalFile` could not run, is not.
|
||||
#[test]
|
||||
fn script_include_errors_keep_their_message_origin() {
|
||||
let base = folder("origin");
|
||||
write(&base.join("main/lib.jsxinc"), "var a = 1;\n throw new RangeError('invalid array length');");
|
||||
write(&base.join("main/native.jsxinc"), "var a = 1;\n new Array(-1);");
|
||||
for (text, message, origin) in [
|
||||
("#include \"lib.jsxinc\"", "RangeError: invalid array length", "script"),
|
||||
("#include \"native.jsxinc\"", "RangeError: invalid array length", "built-in"),
|
||||
("try {\n#include \"native.jsxinc\"\n} catch (e) { throw e; }", "RangeError: invalid array length", "built-in"),
|
||||
("try {\n#include \"native.jsxinc\"\n} catch (e) { throw e.message; }", "invalid array length", "script"),
|
||||
] {
|
||||
let report = failed(&base, text);
|
||||
assert_eq!((report["message"].as_str(), report["messageOrigin"].as_str()), (Some(message), Some(origin)), "{text}: {report}");
|
||||
}
|
||||
let report = failed(&base, "#include \"lib.jsxinc\"");
|
||||
let file = report["file"].as_str().map(|f| Path::new(f).ends_with("lib.jsxinc"));
|
||||
assert_eq!((file, report["line"].as_u64(), report["column"].as_u64()), (Some(true), Some(2), Some(3)), "{report}");
|
||||
let report = failed(&base, "$.evalFile('nope.jsx');");
|
||||
assert_eq!(report["messageOrigin"], "built-in", "{report}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
|
||||
@@ -170,6 +170,58 @@ fn an_error_names_the_script_its_place_and_kind() {
|
||||
assert_eq!(s.script_report().unwrap()["line"], 1);
|
||||
}
|
||||
|
||||
/// A failed run's report keeps its message and kind and says where the message came from: text the
|
||||
/// script supplied, or one of the app's own errors. The status text and the console line read the
|
||||
/// same either way, and only the app's own errors get advice about other applications' objects.
|
||||
#[test]
|
||||
fn failed_script_report_keeps_message_and_adds_origin() {
|
||||
let mut s = two_docs();
|
||||
for (source, kind, message, origin) in [
|
||||
("throw new Error('invalid array length');", "thrown", "Error: invalid array length", "script"),
|
||||
("throw new RangeError('invalid array length');", "thrown", "RangeError: invalid array length", "script"),
|
||||
("throw 'invalid array length';", "thrown", "invalid array length", "script"),
|
||||
("throw 'ReferenceError: app is not defined';", "thrown", "ReferenceError: app is not defined", "script"),
|
||||
("try { new Array(-1); } catch (e) { throw new Error(e.message); }", "thrown", "Error: invalid array length", "script"),
|
||||
("new Array(-1);", "thrown", "RangeError: invalid array length", "built-in"),
|
||||
("try { new Array(-1); } catch (e) { throw e; }", "thrown", "RangeError: invalid array length", "built-in"),
|
||||
("vc.run();", "thrown", "TypeError: vc.run: give a command id, as a string", "built-in"),
|
||||
] {
|
||||
let e = run(&mut s, source).unwrap_err().to_string();
|
||||
let report = s.script_report().unwrap().clone();
|
||||
assert_eq!(
|
||||
(report["kind"].as_str(), report["message"].as_str(), report["messageOrigin"].as_str()),
|
||||
(Some(kind), Some(message), Some(origin)),
|
||||
"{source}"
|
||||
);
|
||||
let (line, column) = (&report["line"], &report["column"]);
|
||||
let before = format!("t.js: line {line}, column {column}: ");
|
||||
assert_eq!(e, format!("{before}{message} ({kind})"), "{source}");
|
||||
assert_eq!(s.script_failure_text().as_deref(), Some(e.as_str()));
|
||||
let authored = s.script_authored_failure();
|
||||
assert_eq!(authored, (origin == "script").then(|| (before.clone(), message, format!(" ({kind})"))), "{source}");
|
||||
let console = s.execute("script.console", &json!({})).unwrap();
|
||||
let error = console["lines"].as_array().unwrap().iter().rev().find(|l| l["kind"] == "error").map(|l| l["text"].clone());
|
||||
assert_eq!(error, Some(json!(format!("t.js:{line}:{column}: {message}"))), "{source}");
|
||||
}
|
||||
// The app's own reference error names the `vc` object; the same text a script threw does not.
|
||||
run(&mut s, "app.activeDocument;").unwrap_err();
|
||||
assert!(s.script_report().unwrap()["message"].as_str().unwrap().contains("`vc`"));
|
||||
assert_eq!(s.script_report().unwrap()["messageOrigin"], "built-in");
|
||||
// An error in code `eval` compiled keeps where its message came from.
|
||||
let e = run(&mut s, "eval(\"throw new Error('invalid array length')\");").unwrap_err().to_string();
|
||||
assert_eq!(e, "t.js: Error: invalid array length (thrown)");
|
||||
assert_eq!(s.script_authored_failure(), Some(("t.js: ".to_string(), "Error: invalid array length", " (thrown)".to_string())));
|
||||
// Syntax errors and limits are the app's own.
|
||||
run(&mut s, "var = 1;").unwrap_err();
|
||||
assert_eq!((s.script_report().unwrap()["kind"].as_str(), s.script_authored_failure()), (Some("syntax"), None));
|
||||
s.execute("script.run", &json!({"source": "while (true) {}", "name": "t.js", "maxFuel": 100_000})).unwrap_err();
|
||||
assert_eq!((s.script_report().unwrap()["messageOrigin"].as_str(), s.script_authored_failure()), (Some("built-in"), None));
|
||||
// A run that completes has no failure to split.
|
||||
run(&mut s, "throw 'x';").unwrap_err();
|
||||
run(&mut s, "1").unwrap();
|
||||
assert_eq!(s.script_authored_failure(), None);
|
||||
}
|
||||
|
||||
/// An error raised where the run has no place for it, such as in code `eval` compiled, is named
|
||||
/// with the script and its kind alone, with one colon after the script's name.
|
||||
#[test]
|
||||
|
||||
@@ -539,6 +539,196 @@ fn colour_table_delete_maps_pixels_to_the_nearest_color_left() {
|
||||
assert_eq!(sources(&preview(&mut s, json!({"preset": "No near red"}))), ["#0000ff", "#ff0000"]);
|
||||
}
|
||||
|
||||
/// The colors of a fixed palette mapped to transparent take one slot of Colors together with the
|
||||
/// transparent pixels, so the opaque colors after them still fit: their pixels stay opaque, and the
|
||||
/// pixels of the colors mapped to transparent become transparent.
|
||||
#[test]
|
||||
fn colour_table_fixed_palette_keeps_an_opaque_color() {
|
||||
// 40×10: red, a near red and blue, and 10 px with nothing (transparent).
|
||||
let mut s = session(40.0, 10.0);
|
||||
rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#ff0000");
|
||||
rect(&mut s, [10.0, 0.0, 10.0, 10.0], "#ee1100");
|
||||
rect(&mut s, [20.0, 0.0, 10.0, 10.0], "#0000ff");
|
||||
for table in [
|
||||
json!({"customPalette": ["#ff0000", "#ee1100", "#0000ff"], "deleted": ["#ee1100"], "transparent": ["#ff0000"]}),
|
||||
json!({"customPalette": ["#ff0000", "#0000ff"], "transparent": ["#ff0000"]}),
|
||||
] {
|
||||
let p = json!({"format": "png8", "dither": "none", "colors": 2, "colorTable": table});
|
||||
let v = run(&mut s, "document.exportForWeb.preview", p.clone());
|
||||
let opaque: Vec<&Value> = v["colors"].as_array().unwrap().iter().filter(|c| c["transparent"] == false).map(|c| &c["source"]).collect();
|
||||
assert_eq!((opaque, v["colors"].as_array().unwrap().len()), (vec![&json!("#0000ff")], 2), "{p}");
|
||||
let img = pixels(&one(&mut s, p.clone()));
|
||||
let alpha = |x: u32| img.get_pixel(x, 5).0[3];
|
||||
assert_eq!((alpha(5), alpha(15), img.get_pixel(25, 5).0, alpha(35)), (0, 0, [0, 0, 255, 255], 0), "{p}");
|
||||
}
|
||||
// A color mapped to transparent that no pixel takes leaves its slot to an opaque color.
|
||||
let mut u = session(20.0, 10.0);
|
||||
rect(&mut u, [0.0, 0.0, 10.0, 10.0], "#0000ff");
|
||||
rect(&mut u, [10.0, 0.0, 10.0, 10.0], "#00ff00");
|
||||
let p = json!({"format": "png8", "dither": "none", "colors": 2, "colorTable": {"customPalette": ["#0000ff", "#00ff00", "#ff0000"], "transparent": ["#ff0000"]}});
|
||||
let img = pixels(&one(&mut u, p));
|
||||
assert_eq!((img.get_pixel(5, 5).0, img.get_pixel(15, 5).0), ([0, 0, 255, 255], [0, 255, 0, 255]));
|
||||
// At 256 colors a color mapped to transparent after 255 opaque ones still keeps an entry.
|
||||
let full: Vec<String> =
|
||||
std::iter::once("#0000ff".to_string()).chain((1..255).map(|i| format!("#00{i:02x}00"))).chain(["#ff0000".to_string()]).collect();
|
||||
let p = json!({"format": "png8", "dither": "none", "colors": 256, "colorTable": {"customPalette": full, "transparent": ["#ff0000"]}});
|
||||
let img = pixels(&one(&mut s, p));
|
||||
assert_eq!((img.get_pixel(5, 5).0[3], img.get_pixel(25, 5).0, img.get_pixel(35, 5).0[3]), (0, [0, 0, 255, 255], 0));
|
||||
// With one opaque color and 255 mapped to transparent, the last of those does not fit, and its
|
||||
// pixels still become transparent rather than taking the opaque color nearest them.
|
||||
let mut d = session(30.0, 10.0);
|
||||
rect(&mut d, [0.0, 0.0, 10.0, 10.0], "#0000ff");
|
||||
rect(&mut d, [10.0, 0.0, 10.0, 10.0], "#0000ee");
|
||||
let clear: Vec<String> = (1..255).map(|i| format!("#00{i:02x}00")).chain(["#0000ee".to_string()]).collect();
|
||||
let palette: Vec<String> = std::iter::once("#0000ff".to_string()).chain(clear.iter().cloned()).collect();
|
||||
let p = json!({"format": "png8", "dither": "none", "colors": 256, "colorTable": {"customPalette": palette, "transparent": clear}});
|
||||
let img = pixels(&one(&mut d, p));
|
||||
assert_eq!((img.get_pixel(5, 5).0, img.get_pixel(15, 5).0[3], img.get_pixel(25, 5).0[3]), ([0, 0, 255, 255], 0, 0));
|
||||
// Without transparent pixels the colors mapped to transparent still take one slot together.
|
||||
let mut t = session(30.0, 10.0);
|
||||
rect(&mut t, [0.0, 0.0, 10.0, 10.0], "#ff0000");
|
||||
rect(&mut t, [10.0, 0.0, 10.0, 10.0], "#ee1100");
|
||||
rect(&mut t, [20.0, 0.0, 10.0, 10.0], "#0000ff");
|
||||
let p = json!({"format": "png8", "dither": "none", "colors": 2, "colorTable": {
|
||||
"customPalette": ["#ff0000", "#ee1100", "#0000ff", "#00ff00"], "transparent": ["#ff0000", "#ee1100"],
|
||||
}});
|
||||
let v = run(&mut t, "document.exportForWeb.preview", p.clone());
|
||||
assert_eq!(v["colors"].as_array().unwrap().len(), 2, "{v}");
|
||||
let img = pixels(&one(&mut t, p));
|
||||
assert_eq!((img.get_pixel(5, 5).0[3], img.get_pixel(15, 5).0[3], img.get_pixel(25, 5).0), (0, 0, [0, 0, 255, 255]));
|
||||
}
|
||||
|
||||
/// A color shifted by hand (`colorTable.shifted`) is written as the color picked wherever it is in
|
||||
/// the image, the other colors stay, the table shows it as shifted and locked, and the preview is
|
||||
/// the file.
|
||||
#[test]
|
||||
fn colour_table_shift_writes_the_picked_color_wherever_the_source_is() {
|
||||
let mut s = session(30.0, 10.0);
|
||||
rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#ff0000");
|
||||
rect(&mut s, [10.0, 0.0, 10.0, 10.0], "#0000ff");
|
||||
rect(&mut s, [20.0, 0.0, 10.0, 10.0], "#00ff00");
|
||||
let preview = |s: &mut Session, p: Value| run(s, "document.exportForWeb.preview", p);
|
||||
let entry = |v: &Value, source: &str| v["colors"].as_array().unwrap().iter().find(|c| c["source"] == source).cloned().unwrap_or(Value::Null);
|
||||
for format in ["gif", "png8"] {
|
||||
let p = json!({"format": format, "dither": "none", "colorTable": {"shifted": {"#0000FF": "#FF8800"}}});
|
||||
let v = preview(&mut s, p.clone());
|
||||
let c = entry(&v, "#0000ff");
|
||||
assert_eq!(
|
||||
(c["color"].as_str(), c["shifted"].as_bool(), c["locked"].as_bool(), c["webShifted"].as_bool()),
|
||||
(Some("#ff8800"), Some(true), Some(true), Some(false)),
|
||||
"{format}: {v}"
|
||||
);
|
||||
assert_eq!((entry(&v, "#ff0000")["shifted"].as_bool(), entry(&v, "#ff0000")["color"].as_str()), (Some(false), Some("#ff0000")));
|
||||
let file = one(&mut s, p);
|
||||
assert_eq!(v["bytes"].as_u64(), Some(file.len() as u64), "{format}: the preview is the file");
|
||||
let img = pixels(&file);
|
||||
assert_eq!(
|
||||
(img.get_pixel(5, 5).0, img.get_pixel(12, 2).0, img.get_pixel(18, 8).0, img.get_pixel(25, 5).0),
|
||||
([255, 0, 0, 255], [255, 136, 0, 255], [255, 136, 0, 255], [0, 255, 0, 255]),
|
||||
"{format}"
|
||||
);
|
||||
assert_eq!(distinct(&img), 3, "{format}");
|
||||
}
|
||||
// A shifted color is kept when the colors are reduced, as a locked one is.
|
||||
let two = preview(&mut s, json!({"colors": 2, "dither": "none", "colorTable": {"shifted": {"#00ff00": "#123456"}}}));
|
||||
assert_eq!(entry(&two, "#00ff00")["color"], "#123456", "{two}");
|
||||
// With one slot to keep, the shifted color takes it before a locked one.
|
||||
let p = json!({"colors": 2, "dither": "none", "colorTable": {"locked": ["#ff0000"], "shifted": {"#0000ff": "#123456"}}});
|
||||
let first = preview(&mut s, p);
|
||||
assert_eq!(entry(&first, "#0000ff")["color"], "#123456", "{first}");
|
||||
// A source the table does not hold shifts nothing, and the shift stays with the settings.
|
||||
let base = preview(&mut s, json!({"dither": "none"}));
|
||||
let absent = preview(&mut s, json!({"dither": "none", "colorTable": {"shifted": {"#123456": "#000000"}}}));
|
||||
assert_eq!(absent["colors"], base["colors"]);
|
||||
// Two colors may be shifted to one color and keep their own sources.
|
||||
let same = preview(&mut s, json!({"dither": "none", "colorTable": {"shifted": {"#ff0000": "#123456", "#0000ff": "#123456"}}}));
|
||||
assert_eq!((entry(&same, "#ff0000")["color"].as_str(), entry(&same, "#0000ff")["color"].as_str()), (Some("#123456"), Some("#123456")));
|
||||
assert_eq!(entry(&same, "#00ff00")["shifted"], false);
|
||||
// A shift by hand wins over web shift, web snap and a lock; transparency wins over it.
|
||||
let p =
|
||||
json!({"dither": "none", "webSnap": 100, "colorTable": {"shifted": {"#0000ff": "#fe0101"}, "webShift": ["#0000ff"], "locked": ["#0000ff"]}});
|
||||
let c = entry(&preview(&mut s, p), "#0000ff");
|
||||
assert_eq!((c["color"].as_str(), c["webShifted"].as_bool(), c["locked"].as_bool()), (Some("#fe0101"), Some(false), Some(true)));
|
||||
let clear = json!({"dither": "none", "colorTable": {"shifted": {"#0000ff": "#fe0101"}, "transparent": ["#0000ff"]}});
|
||||
let v = preview(&mut s, clear.clone());
|
||||
assert!(v["colors"].as_array().unwrap().iter().all(|c| c["shifted"] == false), "{v}");
|
||||
assert_eq!(pixels(&one(&mut s, clear)).get_pixel(15, 5).0[3], 0);
|
||||
// The settings keep the shifts in lowercase, drop a color shifted to itself, a deleted one and
|
||||
// the web shift of a color shifted by hand.
|
||||
let table = json!({"shifted": {"#0000FF": "#FE0101", "#FF0000": "#ff0000", "#00ff00": "#000000"}, "webShift": ["#0000ff", "#00ff00"], "deleted": ["#00ff00"]});
|
||||
let r = run(&mut s, "webExport.settings", json!({ "colorTable": table }));
|
||||
let t = &r["settings"]["colorTable"];
|
||||
assert_eq!((&t["shifted"], &t["webShift"]), (&json!({"#0000ff": "#fe0101"}), &json!([])));
|
||||
// Another reduction keeps the shifts; a saved preset keeps them.
|
||||
let r = run(&mut s, "webExport.settings", json!({"reduction": "adaptive"}));
|
||||
assert_eq!(r["settings"]["colorTable"]["shifted"], json!({"#0000ff": "#fe0101"}));
|
||||
run(&mut s, "webExport.presets.save", json!({"name": "Blue to red", "dither": "none", "colorTable": {"shifted": {"#0000ff": "#fe0101"}}}));
|
||||
assert_eq!(entry(&preview(&mut s, json!({"preset": "Blue to red"})), "#0000ff")["color"], "#fe0101");
|
||||
// Bad shifts are refused and change nothing.
|
||||
let many: serde_json::Map<String, Value> = (0..257).map(|i| (format!("#{i:06x}"), json!("#000000"))).collect();
|
||||
for bad in [
|
||||
json!({"nope": "#000000"}),
|
||||
json!({"#ff0000": "nope"}),
|
||||
json!({"#ff0000": "#ff000080"}),
|
||||
json!({"#ff000080": "#000000"}),
|
||||
json!({"#ff0000": "#000000", "#FF0000": "#ffffff"}),
|
||||
json!({"#f00": "#000000", "#ff0000": "#ffffff"}),
|
||||
Value::Object(many),
|
||||
] {
|
||||
let p = json!({"colorTable": {"shifted": bad}});
|
||||
assert!(s.execute("document.exportForWeb", &p).is_err(), "{p}");
|
||||
assert!(s.execute("document.exportForWeb.preview", &p).is_err(), "{p}");
|
||||
assert!(s.execute("webExport.settings", &p).is_err(), "{p}");
|
||||
}
|
||||
assert_eq!(run(&mut s, "webExport.settings", json!({}))["settings"]["colorTable"]["shifted"], json!({"#0000ff": "#fe0101"}));
|
||||
// Settings saved before shifts existed still read.
|
||||
let old: cmd::webexport::WebSettings = serde_json::from_value(json!({"colorTable": {"locked": ["#ff0000"]}})).unwrap();
|
||||
assert!(old.color_table.shifted.is_empty());
|
||||
}
|
||||
|
||||
/// Lossy GIF compression leaves the pixels of a color shifted by hand alone, so a color shifted near
|
||||
/// another one does not take in that color's pixels.
|
||||
#[test]
|
||||
fn lossy_does_not_spread_a_shifted_color_into_another() {
|
||||
let mut s = session(30.0, 10.0);
|
||||
rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#0000ff");
|
||||
rect(&mut s, [10.0, 0.0, 20.0, 10.0], "#c80000");
|
||||
let p = json!({"format": "gif", "dither": "none", "lossy": 100, "colorTable": {"shifted": {"#0000ff": "#be0000"}}});
|
||||
let img = pixels(&one(&mut s, p));
|
||||
assert_eq!((img.get_pixel(5, 5).0, img.get_pixel(20, 5).0, img.get_pixel(29, 5).0), ([190, 0, 0, 255], [200, 0, 0, 255], [200, 0, 0, 255]));
|
||||
}
|
||||
|
||||
/// Lossy GIF compression moves no pixel into or out of a color shifted by hand: the colors next to
|
||||
/// a shifted one keep their own pixels, and the shifted color keeps all of its pixels.
|
||||
#[test]
|
||||
fn lossy_moves_no_pixel_into_or_out_of_a_shifted_color() {
|
||||
let mut s = session(30.0, 10.0);
|
||||
rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#1414e6");
|
||||
rect(&mut s, [10.0, 0.0, 20.0, 10.0], "#0000ff");
|
||||
rect(&mut s, [20.0, 0.0, 30.0, 10.0], "#1414e6");
|
||||
let p = json!({"format": "gif", "dither": "none", "lossy": 100, "colorTable": {"shifted": {"#0000ff": "#ff0000"}}});
|
||||
let img = pixels(&one(&mut s, p));
|
||||
let near_blue = [20, 20, 230, 255];
|
||||
for x in 0..30 {
|
||||
let want = if (10..20).contains(&x) { [255, 0, 0, 255] } else { near_blue };
|
||||
assert_eq!(img.get_pixel(x, 5).0, want, "x = {x}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Lossy GIF compression compares the pixels with the colors web snap writes, so a pixel does not
|
||||
/// take a color that snaps far from it.
|
||||
#[test]
|
||||
fn lossy_compares_pixels_with_the_snapped_colors() {
|
||||
let mut s = session(20.0, 10.0);
|
||||
rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#1a1a1a");
|
||||
rect(&mut s, [10.0, 0.0, 20.0, 10.0], "#000000");
|
||||
let img = pixels(&one(&mut s, json!({"format": "gif", "dither": "none", "webSnap": 100, "lossy": 50})));
|
||||
for x in 0..20 {
|
||||
let want = if x < 10 { [51, 51, 51, 255] } else { [0, 0, 0, 255] };
|
||||
assert_eq!(img.get_pixel(x, 5).0, want, "x = {x}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn presets_and_remembered_settings() {
|
||||
let mut s = two_colours();
|
||||
|
||||
@@ -188,8 +188,7 @@ impl Session {
|
||||
.then(|| self.tool.options().get("meshPoints").cloned())
|
||||
.flatten()
|
||||
.filter(|v| v.as_array().is_some_and(|a| !a.is_empty()));
|
||||
let acts = self.with_tool_cx(view, |t, cx| t.deactivate(cx));
|
||||
self.apply_actions(acts)?;
|
||||
self.deactivate_tool(view)?;
|
||||
self.keep_tool_settings();
|
||||
self.tool = self.make_tool(id);
|
||||
if let Some(selection) = text_selection {
|
||||
@@ -205,6 +204,18 @@ impl Session {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Deactivate the tool and apply the actions it returns. In a batch, a Cancel is left out: the
|
||||
/// batch settled the tool's drag when it began, and the open interaction holds the batch's
|
||||
/// steps, which the batch keeps or rolls back as a whole.
|
||||
pub(crate) fn deactivate_tool(&mut self, view: ViewInfo) -> Result<()> {
|
||||
let mut acts = self.with_tool_cx(view, |t, cx| t.deactivate(cx));
|
||||
if self.batch_stash.is_some() {
|
||||
acts.retain(|a| !matches!(a, Action::Cancel));
|
||||
}
|
||||
self.apply_actions(acts)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The selection tools other than Direct Selection pick whole objects: with one of them chosen,
|
||||
/// an object selected in a symbol instance's art gives way to the instance. The revision
|
||||
/// changes with it, so panels that cache by revision show the instance.
|
||||
@@ -297,8 +308,7 @@ impl Session {
|
||||
// them all (#8090). Group Selection picks no mesh points, so the Eyedropper keeps its own.
|
||||
let mesh_points =
|
||||
(lender.id() == "eyedropper" && self.tool.id() != "groupSelection").then(|| self.tool.options().get("meshPoints").cloned()).flatten();
|
||||
let acts = self.with_tool_cx(view, |t, cx| t.deactivate(cx));
|
||||
let r = self.apply_actions(acts);
|
||||
let r = self.deactivate_tool(view);
|
||||
self.keep_tool_settings();
|
||||
self.tool = lender;
|
||||
if let Some(points) = mesh_points {
|
||||
@@ -311,7 +321,7 @@ impl Session {
|
||||
self.lent_selection = left;
|
||||
}
|
||||
self.after_command(None);
|
||||
r.map(drop)
|
||||
r
|
||||
}
|
||||
|
||||
/// A fresh `id` tool with the options it keeps ([`settings`]): its last values, from this
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
//! Blend edits invalidate every pixel they change, including keys aligned to a curved spine.
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::{Document, NodeId, NodeKind};
|
||||
use vectorcraft_engine::Session;
|
||||
use vectorcraft_geom::Affine;
|
||||
use vectorcraft_render::{Changed, RenderOptions, Rendered, Renderer, view_pixels};
|
||||
|
||||
const WIDTH: u32 = 720;
|
||||
const HEIGHT: u32 = 480;
|
||||
|
||||
type Retained = (Renderer, Option<(Arc<Document>, Vec<u8>)>);
|
||||
|
||||
fn live(s: &Session, blend: NodeId, keys: [NodeId; 2], curved: bool) {
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let NodeKind::Blend { children, spec } = &doc.node(blend).unwrap().kind else {
|
||||
panic!("INPUT: the fixture must remain a live blend");
|
||||
};
|
||||
assert_eq!(children.iter().map(|n| n.id).collect::<Vec<_>>(), keys.to_vec());
|
||||
assert_eq!(serde_json::to_value(spec).unwrap()["spacing"], json!({"steps": 3}));
|
||||
for key in keys {
|
||||
assert_eq!(doc.parent_of(key), Some(blend), "INPUT: key identity/parent changed");
|
||||
}
|
||||
if curved {
|
||||
let bounds = spec.spine.as_ref().expect("INPUT: Replace Spine did not set a spine").bounds().unwrap();
|
||||
assert!(!spec.no_spine && bounds.height() > 40.0 && bounds.width() > 250.0, "INPUT: a real curved spine is required");
|
||||
}
|
||||
}
|
||||
|
||||
fn fixture() -> (Session, NodeId, [NodeId; 2]) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": WIDTH, "height": HEIGHT})).unwrap();
|
||||
let mut rectangle = |x: f64, color: &str| {
|
||||
let id = NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 120.0, "width": 64.0, "height": 48.0})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("paint.setFill", &json!({"color": color})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
id
|
||||
};
|
||||
let keys = [rectangle(90.0, "#d52c38"), rectangle(430.0, "#25b453")];
|
||||
let blend = NodeId(
|
||||
s.execute("object.blend.make", &json!({"ids": [keys[0].0, keys[1].0], "steps": 3, "orientation": "path"})).unwrap()["id"].as_u64().unwrap(),
|
||||
);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![blend]);
|
||||
live(&s, blend, keys, false);
|
||||
(s, blend, keys)
|
||||
}
|
||||
|
||||
fn cpu() -> Renderer {
|
||||
let mut renderer = Renderer::new();
|
||||
renderer.threads = 0;
|
||||
renderer
|
||||
}
|
||||
|
||||
fn same_pixels(actual: &Rendered, expected: &Rendered) {
|
||||
assert_eq!((actual.width, actual.height), (WIDTH, HEIGHT));
|
||||
assert_eq!((expected.width, expected.height), (WIDTH, HEIGHT));
|
||||
assert_eq!(actual.pixels.len(), (WIDTH * HEIGHT * 4) as usize);
|
||||
assert!(actual.pixels == expected.pixels, "complete RGBA frames differ");
|
||||
}
|
||||
|
||||
fn damage_pixels(stage: &str, changed: Changed, before: &[u8], current: &[u8]) {
|
||||
let region = match changed {
|
||||
Changed::Everything => return,
|
||||
Changed::Nothing => None,
|
||||
Changed::Area(area) => view_pixels(area, Affine::IDENTITY, WIDTH, HEIGHT),
|
||||
};
|
||||
assert_eq!(before.len(), current.len());
|
||||
for (i, (old, new)) in before.as_chunks::<4>().0.iter().zip(current.as_chunks::<4>().0.iter()).enumerate() {
|
||||
let (x, y) = (i as u32 % WIDTH, i as u32 / WIDTH);
|
||||
if !region.is_some_and(|[x0, y0, x1, y1]| x >= x0 && x < x1 && y >= y0 && y < y1) {
|
||||
assert_eq!(old, new, "{stage}: pixel ({x}, {y}) changed outside {changed:?}, view pixels {region:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn frame(s: &Session, retained: &mut Retained, stage: &str) -> Rendered {
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let opts = RenderOptions { background: Some([255, 255, 255, 255]), artboards: false, ..Default::default() };
|
||||
// Ask for the edit's advertised damage before rendering the new full frame on this renderer.
|
||||
let changed = retained.1.as_ref().map(|(old, _)| retained.0.changed(old.as_ref(), doc.as_ref(), &opts));
|
||||
let actual = retained.0.render(doc.as_ref(), WIDTH, HEIGHT, Affine::IDENTITY, &opts);
|
||||
let expected = cpu().render(doc.as_ref(), WIDTH, HEIGHT, Affine::IDENTITY, &opts);
|
||||
same_pixels(&actual, &expected);
|
||||
let red = expected.pixels.as_chunks::<4>().0.iter().filter(|p| p[0] > 150 && p[1] < 100 && p[2] < 120 && p[3] == 255).count();
|
||||
let green = expected.pixels.as_chunks::<4>().0.iter().filter(|p| p[0] < 100 && p[1] > 120 && p[2] < 150 && p[3] == 255).count();
|
||||
assert!(red > 100 && green > 100, "INPUT: both original colored keys must really draw: red={red}, green={green}");
|
||||
if let (Some((_, previous)), Some(changed)) = (&retained.1, changed) {
|
||||
damage_pixels(stage, changed, previous, &expected.pixels);
|
||||
}
|
||||
retained.1 = Some((doc.clone(), expected.pixels));
|
||||
actual
|
||||
}
|
||||
|
||||
fn move_and_undo(s: &mut Session, retained: &mut Retained, blend: NodeId, keys: [NodeId; 2], curved: bool, before_frame: &Rendered) {
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![blend]);
|
||||
let before = serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap();
|
||||
s.execute("object.transform", &json!({"matrix": [1.0, 0.0, 0.0, 1.0, 37.0, 29.0]})).unwrap();
|
||||
live(s, blend, keys, curved);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![blend]);
|
||||
let moved = frame(s, retained, "moved");
|
||||
assert!(moved.pixels != before_frame.pixels, "INPUT: the fresh rendered fixture must actually move");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
live(s, blend, keys, curved);
|
||||
assert_eq!(serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap(), before);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![blend]);
|
||||
let restored = frame(s, retained, "undo-move");
|
||||
same_pixels(&restored, before_frame);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blend_5179_straight_move_undo_matches_fresh_cpu() {
|
||||
let (mut s, blend, keys) = fixture();
|
||||
let mut retained = (cpu(), None);
|
||||
let warm = frame(&s, &mut retained, "warm");
|
||||
move_and_undo(&mut s, &mut retained, blend, keys, false, &warm);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blend_5179_replace_spine_move_undo_matches_fresh_cpu() {
|
||||
let (mut s, blend, keys) = fixture();
|
||||
let path = NodeId(s.execute("path.create", &json!({"d": "M122 144 C166 330 402 288 462 144"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [blend.0, path.0]})).unwrap();
|
||||
let before = serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap();
|
||||
let nodes = s.doc().unwrap().doc.node_count();
|
||||
let mut retained = (cpu(), None);
|
||||
let warm = frame(&s, &mut retained, "before-replace");
|
||||
s.execute("object.blend.replaceSpine", &json!({})).unwrap();
|
||||
live(&s, blend, keys, true);
|
||||
assert!(s.doc().unwrap().doc.node(path).is_none(), "Replace Spine consumes the original standalone path");
|
||||
assert_eq!(s.doc().unwrap().doc.node_count(), nodes - 1);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![blend]);
|
||||
let replaced = frame(&s, &mut retained, "replaced");
|
||||
assert!(replaced.pixels != warm.pixels, "INPUT: replacing the spine must visibly change the drawn fixture");
|
||||
move_and_undo(&mut s, &mut retained, blend, keys, true, &replaced);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
live(&s, blend, keys, false);
|
||||
assert_eq!(serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap(), before);
|
||||
let restored = frame(&s, &mut retained, "undo-replace");
|
||||
same_pixels(&restored, &warm);
|
||||
}
|
||||
|
||||
// A fixed ordinary anisotropic Transform, evaluated after Align to Path turns the key.
|
||||
// 200% is the legitimate control; 400% is the single source-derived witness.
|
||||
fn rotated_transform_damage(scale_h: f64) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": WIDTH, "height": HEIGHT})).unwrap();
|
||||
let mut rectangle = |x: f64, color: &str| {
|
||||
let id = NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 200.0, "width": 8.0, "height": 80.0})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("paint.setFill", &json!({"color": color})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"scaleH": scale_h, "scaleV": 100.0, "reference": 4}})).unwrap();
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
let b = n.geometric_bounds().unwrap();
|
||||
assert!((b.width() - 8.0).abs() < 1e-8 && (b.height() - 80.0).abs() < 1e-8, "INPUT: the Transform must remain live on the narrow key");
|
||||
assert_eq!(n.appearance.effects.len(), 1);
|
||||
assert_eq!(n.appearance.effects[0].params["scaleH"], json!(scale_h));
|
||||
id
|
||||
};
|
||||
let keys = [rectangle(260.0, "#d52c38"), rectangle(460.0, "#25b453")];
|
||||
let blend = NodeId(
|
||||
s.execute("object.blend.make", &json!({"ids": [keys[0].0, keys[1].0], "steps": 3, "orientation": "path"})).unwrap()["id"].as_u64().unwrap(),
|
||||
);
|
||||
live(&s, blend, keys, false);
|
||||
let path = NodeId(s.execute("path.create", &json!({"d": "M264 160 L264 320"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [blend.0, path.0]})).unwrap();
|
||||
let before = serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap();
|
||||
let mut retained = (cpu(), None);
|
||||
let warm = frame(&s, &mut retained, "anisotropic-before-replace");
|
||||
s.execute("object.blend.replaceSpine", &json!({})).unwrap();
|
||||
live(&s, blend, keys, false);
|
||||
assert!(s.doc().unwrap().doc.node(path).is_none());
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![blend]);
|
||||
let n = s.doc().unwrap().doc.node(blend).unwrap();
|
||||
let NodeKind::Blend { spec, .. } = &n.kind else { panic!("INPUT: the fixture must remain a live blend") };
|
||||
let spine = spec.spine.as_ref().unwrap().bounds().unwrap();
|
||||
assert!(spine.width().abs() < 1e-8 && (spine.height() - 160.0).abs() < 1e-8, "INPUT: this is the fixed vertical rail");
|
||||
let expanded = vectorcraft_render::expand_live(n);
|
||||
let placed = expanded.iter().find(|n| n.id == keys[0]).unwrap();
|
||||
let b = placed.geometric_bounds().unwrap();
|
||||
assert!((b.width() - 80.0).abs() < 1e-8 && (b.height() - 8.0).abs() < 1e-8, "INPUT: Align to Path must really turn the key by 90 degrees");
|
||||
assert_eq!(placed.appearance.effects.len(), 1);
|
||||
assert_eq!(placed.appearance.effects[0].params["scaleH"], json!(scale_h));
|
||||
let replaced = frame(&s, &mut retained, &format!("rotated-transform-{scale_h}-replace"));
|
||||
assert!(replaced.pixels != warm.pixels, "INPUT: the replacement must really change the painted frame");
|
||||
move_and_undo(&mut s, &mut retained, blend, keys, false, &replaced);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap(), before);
|
||||
let restored = frame(&s, &mut retained, "anisotropic-undo-replace");
|
||||
same_pixels(&restored, &warm);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blend_5179_rotated_transform_damage_contains_painted_pixels() {
|
||||
// The control completes every render, move and history check before the witness runs.
|
||||
rotated_transform_damage(200.0);
|
||||
rotated_transform_damage(400.0);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1956,6 +1956,149 @@ fn an_anchor_beside_a_drawn_dimension_takes_the_point() {
|
||||
assert_eq!(linear_marker(&mut s, zoomed, 125.5, 358.3), (Some((pt(126.0, 358.0), 10.0)), vec!["anchor".to_string()]));
|
||||
}
|
||||
|
||||
/// The Smart Guide lines a pointer move at (`x`, `y`) shows, as their ends.
|
||||
fn guide_lines(s: &mut Session, view: ViewInfo, x: f64, y: f64) -> Vec<(vectorcraft_geom::Point, vectorcraft_geom::Point)> {
|
||||
use vectorcraft_engine::tools::Overlay;
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, x, y), view).unwrap();
|
||||
s.overlays(view).into_iter().filter_map(|o| if let Overlay::Line { a, b, .. } = o { Some((a, b)) } else { None }).collect()
|
||||
}
|
||||
|
||||
/// An edge with anchors at x 100, 200 and 300, and a dimension from 100 to 200 placed 30 points
|
||||
/// above it, with the Dimension tool active and nothing selected: the session and the dimension.
|
||||
fn level_start(view: ViewInfo) -> (Session, u64) {
|
||||
let pt = vectorcraft_geom::Point::new;
|
||||
let mut s = session();
|
||||
run(&mut s, "path.create", json!({"d": "M100 200 L200 200 L300 200 L300 300 L100 300 Z"}));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
s.select_tool("dimension", view).unwrap();
|
||||
linear_click(&mut s, view, 100.0, 200.0);
|
||||
linear_click(&mut s, view, 200.0, 200.0);
|
||||
linear_click(&mut s, view, 150.0, 170.0);
|
||||
let first = s.doc().unwrap().selection.objects[0].0;
|
||||
assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 170.0), pt(200.0, 170.0)));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
(s, first)
|
||||
}
|
||||
|
||||
/// The next dimension, from 200 to 300, placed with the pointer at `y`: where its line lies.
|
||||
fn level_next(s: &mut Session, view: ViewInfo, y: f64) -> (vectorcraft_geom::Point, vectorcraft_geom::Point) {
|
||||
linear_click(s, view, 200.0, 200.0);
|
||||
linear_click(s, view, 300.0, 200.0);
|
||||
linear_click(s, view, 250.0, y);
|
||||
let id = s.doc().unwrap().selection.objects[0].0;
|
||||
recipe(s, id).line_ends()
|
||||
}
|
||||
|
||||
/// A dimension placed next to another, with its line within the Smart Guides snapping tolerance of
|
||||
/// the level of the other's parallel line, has its line on that level. A level further off, Smart
|
||||
/// Guides off, a locked dimension or one that is not parallel leaves the line where the pointer
|
||||
/// puts it.
|
||||
#[test]
|
||||
fn a_dimension_line_placed_beside_another_lands_on_its_level() {
|
||||
let plain = ViewInfo::default();
|
||||
let off = ViewInfo { smart_guides: false, ..plain };
|
||||
let pt = vectorcraft_geom::Point::new;
|
||||
// 2.5 points below the first line's level, and 3.5 above it: on the level.
|
||||
for y in [172.5, 166.5] {
|
||||
let (mut s, _) = level_start(plain);
|
||||
assert_eq!(level_next(&mut s, plain, y), (pt(200.0, 170.0), pt(300.0, 170.0)), "pointer at y {y}");
|
||||
}
|
||||
// 10 points off: where the pointer is.
|
||||
let (mut s, _) = level_start(plain);
|
||||
assert_eq!(level_next(&mut s, plain, 180.0), (pt(200.0, 180.0), pt(300.0, 180.0)));
|
||||
// Smart Guides off: where the pointer is.
|
||||
let (mut s, _) = level_start(off);
|
||||
assert_eq!(level_next(&mut s, off, 172.5), (pt(200.0, 172.5), pt(300.0, 172.5)));
|
||||
// A locked dimension does not pull the line.
|
||||
let (mut s, first) = level_start(plain);
|
||||
run(&mut s, "select.set", json!({"ids":[first]}));
|
||||
run(&mut s, "object.lock", json!({}));
|
||||
assert_eq!(level_next(&mut s, plain, 172.5), (pt(200.0, 172.5), pt(300.0, 172.5)));
|
||||
// A dimension of the right edge has a vertical line, which is not parallel to the first: the
|
||||
// pointer 2.5 points below the first line's level places it where the pointer is.
|
||||
let (mut s, _) = level_start(plain);
|
||||
linear_click(&mut s, plain, 300.0, 200.0);
|
||||
linear_click(&mut s, plain, 300.0, 300.0);
|
||||
linear_click(&mut s, plain, 330.0, 172.5);
|
||||
let id = s.doc().unwrap().selection.objects[0].0;
|
||||
assert_eq!(recipe(&s, id).line_ends(), (pt(330.0, 200.0), pt(330.0, 300.0)));
|
||||
}
|
||||
|
||||
/// While a dimension is placed with its line on the level of another, one alignment guide runs
|
||||
/// along the level across both lines. Off the level, after a dropped press and with Alignment
|
||||
/// Guides off, no guide shows.
|
||||
#[test]
|
||||
fn a_dimension_line_on_another_level_shows_one_guide_across_both() {
|
||||
let plain = ViewInfo::default();
|
||||
let pt = vectorcraft_geom::Point::new;
|
||||
let (mut s, _) = level_start(plain);
|
||||
linear_click(&mut s, plain, 200.0, 200.0);
|
||||
linear_click(&mut s, plain, 300.0, 200.0);
|
||||
let guides = guide_lines(&mut s, plain, 250.0, 172.5);
|
||||
assert!(guides.iter().any(|(a, b)| near(*a, pt(100.0, 170.0)) && near(*b, pt(300.0, 170.0))), "{guides:?}");
|
||||
assert!(guide_lines(&mut s, plain, 250.0, 180.0).is_empty(), "no guide off the level");
|
||||
// A press on the level that the app drops cancels the preview, and its guide goes with it.
|
||||
assert!(!guide_lines(&mut s, plain, 250.0, 172.5).is_empty());
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 250.0, 172.5), plain).unwrap();
|
||||
s.drop_tool_press(plain).unwrap();
|
||||
assert!(s.overlays(plain).iter().all(|o| !matches!(o, vectorcraft_engine::tools::Overlay::Line { .. })), "{:?}", s.overlays(plain));
|
||||
// Alignment Guides off: the line still lands on the level, with no guide.
|
||||
let (mut s, _) = level_start(plain);
|
||||
run(&mut s, "prefs.set", json!({"key": "alignmentGuides", "value": false}));
|
||||
linear_click(&mut s, plain, 200.0, 200.0);
|
||||
linear_click(&mut s, plain, 300.0, 200.0);
|
||||
assert!(guide_lines(&mut s, plain, 250.0, 172.5).is_empty());
|
||||
linear_click(&mut s, plain, 250.0, 172.5);
|
||||
let id = s.doc().unwrap().selection.objects[0].0;
|
||||
assert_eq!(recipe(&s, id).line_ends(), (pt(200.0, 170.0), pt(300.0, 170.0)));
|
||||
}
|
||||
|
||||
/// A second dimension of the same two points as a dimension already drawn lands on its level too.
|
||||
/// Off every level, a pointer moved in small steps while it is placed puts the line at each step,
|
||||
/// with no pull from the preview of the dimension itself.
|
||||
#[test]
|
||||
fn a_dimension_of_the_same_points_lines_up_and_the_line_follows_the_pointer() {
|
||||
let plain = ViewInfo::default();
|
||||
let pt = vectorcraft_geom::Point::new;
|
||||
let (mut s, first) = level_start(plain);
|
||||
linear_click(&mut s, plain, 100.0, 200.0);
|
||||
linear_click(&mut s, plain, 200.0, 200.0);
|
||||
linear_click(&mut s, plain, 150.0, 172.5);
|
||||
let id = s.doc().unwrap().selection.objects[0].0;
|
||||
assert_ne!(id, first);
|
||||
assert_eq!(recipe(&s, id).line_ends(), (pt(100.0, 170.0), pt(200.0, 170.0)));
|
||||
let (mut s, _) = level_start(plain);
|
||||
linear_click(&mut s, plain, 200.0, 200.0);
|
||||
linear_click(&mut s, plain, 300.0, 200.0);
|
||||
for y in [190.0, 189.0, 188.0, 187.0, 186.0] {
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, 250.0, y), plain).unwrap();
|
||||
}
|
||||
for kind in [PointerKind::Down, PointerKind::Up] {
|
||||
s.pointer(&PointerEvent::new(kind, 250.0, 186.0), plain).unwrap();
|
||||
}
|
||||
let id = s.doc().unwrap().selection.objects[0].0;
|
||||
assert_eq!(recipe(&s, id).line_ends(), (pt(200.0, 186.0), pt(300.0, 186.0)));
|
||||
}
|
||||
|
||||
/// A dimension dragged out from a segment, with its line within the Smart Guides snapping
|
||||
/// tolerance of the level of another dimension's parallel line, lands on that level.
|
||||
#[test]
|
||||
fn a_dimension_dragged_out_beside_another_lands_on_its_level() {
|
||||
let plain = ViewInfo::default();
|
||||
let pt = vectorcraft_geom::Point::new;
|
||||
// The bottom edge dragged out to 2 points below the level of the first line, 130 points
|
||||
// above the edge: on the level.
|
||||
let (mut s, _) = level_start(plain);
|
||||
for (kind, y) in
|
||||
[(PointerKind::Move, 300.0), (PointerKind::Down, 300.0), (PointerKind::Drag, 240.0), (PointerKind::Drag, 172.0), (PointerKind::Up, 172.0)]
|
||||
{
|
||||
s.pointer(&PointerEvent::new(kind, 160.0, y), plain).unwrap();
|
||||
}
|
||||
let id = s.doc().unwrap().selection.objects[0].0;
|
||||
let (a, b) = recipe(&s, id).line_ends();
|
||||
assert!(near(a, pt(300.0, 170.0)) && near(b, pt(100.0, 170.0)) || near(a, pt(100.0, 170.0)) && near(b, pt(300.0, 170.0)), "{a:?} {b:?}");
|
||||
}
|
||||
|
||||
/// The page content streams of exported PDF `v`, inflated.
|
||||
fn pdf_content(v: &Value) -> String {
|
||||
let bytes = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap();
|
||||
|
||||
@@ -70,7 +70,7 @@ fn sheet(p: &PrintPage, job: &PrintJob) -> Result<(String, Vec<Page>), String> {
|
||||
}
|
||||
let opts = |region: Rect| EpsOptions { level: job.level, region, ..EpsOptions::default() };
|
||||
let art_opts = opts(r);
|
||||
let art = Scene::new(p.doc, &art_opts).run();
|
||||
let art = Scene::new(p.doc, &art_opts).on_plate(p.ink.is_some()).run();
|
||||
// The marks' area: the drawing space the page shows (within the tile).
|
||||
let paper = Rect::new(0.0, 0.0, w, h);
|
||||
let shown = if p.view.determinant().abs() > 1e-12 { p.view.inverse().transform_rect_bbox(paper) } else { paper };
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
//! PostScript print jobs: DSC page comments, the setup of each sheet, and a file the PostScript
|
||||
//! reader reads back.
|
||||
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId};
|
||||
use vectorcraft_geom::{Affine, Rect, shapes};
|
||||
use vectorcraft_color::{
|
||||
Color, Freeform, FreeformPoint, Gradient, GradientGeom, GradientKind, GradientPaint, GradientSpread, GradientStop, Paint, Swatch,
|
||||
};
|
||||
use vectorcraft_doc::{Appearance, CharStyle, Document, Node, NodeId, NodeKind, StrokeGradientMode, TextObject};
|
||||
use vectorcraft_geom::{Affine, Point, Rect, Vec2, shapes};
|
||||
use vectorcraft_testkit::raster::{Image, render_region};
|
||||
|
||||
use super::*;
|
||||
|
||||
@@ -110,3 +113,219 @@ fn separations_screens_flatness_negatives_and_tiles() {
|
||||
assert!(print(&[], &[], &job).is_err());
|
||||
assert!(print(&[PrintPage { size: (f64::NAN, 1.0), ..page(&d, None) }], &[0], &job).is_err());
|
||||
}
|
||||
|
||||
/// A 200 × 100 pt CMYK document with spot swatch `Ink` (100% K): a rectangle over the whole page
|
||||
/// painted `under`, when there is one, then `art`.
|
||||
fn over(under: Option<Paint>, art: &[Node]) -> Document {
|
||||
let mut d = Document::new(200.0, 100.0);
|
||||
d.color_mode = vectorcraft_doc::ColorMode::Cmyk;
|
||||
d.swatches.push(Swatch { name: "Ink".into(), paint: Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)), global: true, spot: true });
|
||||
let layer = d.layers[0].id;
|
||||
let under = under.map(|p| Node::path(NodeId(0), shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 100.0)), Appearance::basic(p, Paint::None, 0.0)));
|
||||
for mut n in under.into_iter().chain(art.iter().cloned()) {
|
||||
n.id = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
/// Ink `ink`'s plate of `d` as the print plan separates it for PostScript, and as a PostScript
|
||||
/// separation at `level` read back, both drawn at 1 px a point.
|
||||
fn plate_of(d: &Document, ink: &str, level: Level) -> (Image, Image) {
|
||||
let area = Rect::new(0.0, 0.0, 200.0, 100.0);
|
||||
let settings = serde_json::from_value(serde_json::json!({"output": {"mode": "separations"}})).unwrap();
|
||||
let plan = vectorcraft_pdf::plan(d, &vectorcraft_pdf::PrintOptions { settings, postscript: true, ..Default::default() }).unwrap();
|
||||
let i = plan.sheets.iter().find(|s| s.ink.as_ref().is_some_and(|p| p.name == ink)).and_then(|s| s.plate).unwrap();
|
||||
let plate = &plan.plates[i];
|
||||
let page = PrintPage {
|
||||
doc: plate,
|
||||
size: (200.0, 100.0),
|
||||
view: Affine::IDENTITY,
|
||||
window: None,
|
||||
place: Affine::IDENTITY,
|
||||
copies: &[],
|
||||
area,
|
||||
marks: None,
|
||||
negative: false,
|
||||
ink: Some((ink, 85.0, 15.0)),
|
||||
};
|
||||
let out = print(&[page], &[0], &PrintJob { level, ..PrintJob::default() }).unwrap();
|
||||
assert!(level == Level::Three || !text(&out).contains("shfill"), "Level 2 has no smooth shadings");
|
||||
let back = crate::import(&out.bytes).unwrap().document;
|
||||
(render_region(plate, area, 1.0), render_region(&back, area, 1.0))
|
||||
}
|
||||
|
||||
/// Ink `ink`'s PostScript plate of `art` over a page of 100% `ink` (`under`), checked against the
|
||||
/// plate of `art` alone (drawn from the print plan, or with `postscript` from its PostScript
|
||||
/// plate): where `art` puts none of the ink down, the ink under it prints, and where it puts ink
|
||||
/// down, its own amount prints. The pixels of the page where `art` alone puts no ink, those of
|
||||
/// them where the ink under it does not print, and the pixels where `art` puts ink down that do
|
||||
/// not print its amount.
|
||||
fn keeps_the_ink_below(art: &[Node], under: &Paint, ink: &str, level: Level, postscript: bool) -> (usize, usize, usize) {
|
||||
let (plan, own) = plate_of(&over(None, art), ink, level);
|
||||
let alone = if postscript { own } else { plan };
|
||||
let (_, printed) = plate_of(&over(Some(under.clone()), art), ink, level);
|
||||
// Pixels whose neighbors all have paper (or all have ink) on the plate of `art` alone: an
|
||||
// edge falls on either side of a pixel's center, and the edge of the inked part is lightest.
|
||||
let around = |x: u32, y: u32, paper: bool| {
|
||||
(x.saturating_sub(1)..=(x + 1).min(alone.width - 1))
|
||||
.all(|i| (y.saturating_sub(1)..=(y + 1).min(alone.height - 1)).all(|j| (alone.over_white(i, j)[0] >= 254) == paper))
|
||||
};
|
||||
let (mut paper, mut knocked_out, mut wrong) = (0, 0, 0);
|
||||
for y in 0..alone.height {
|
||||
for x in 0..alone.width {
|
||||
let (a, p) = (alone.over_white(x, y)[0], printed.over_white(x, y)[0]);
|
||||
if around(x, y, true) {
|
||||
paper += 1;
|
||||
knocked_out += usize::from(p > 60);
|
||||
} else if around(x, y, false) {
|
||||
wrong += usize::from(a.abs_diff(p) > 48);
|
||||
}
|
||||
}
|
||||
}
|
||||
(paper, knocked_out, wrong)
|
||||
}
|
||||
|
||||
/// A rectangle from (20, 10) to (180, 90) with `fill` and `stroke` (16 pt), each set to
|
||||
/// overprint.
|
||||
fn overprinting(fill: Paint, stroke: Paint) -> Node {
|
||||
let mut n = Node::path(NodeId(0), shapes::rectangle(Rect::new(20.0, 10.0, 180.0, 90.0)), Appearance::basic(fill, stroke, 16.0));
|
||||
for it in &mut n.appearance.items {
|
||||
*it.overprint_mut() = true;
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// `stops` (offset, color) as a `kind` gradient placed at `geom`, spreading as `spread`.
|
||||
fn gradient(kind: GradientKind, stops: &[(f32, Color)], geom: GradientGeom, spread: GradientSpread) -> Paint {
|
||||
let stops = stops.iter().map(|(o, c)| GradientStop::new(*o, *c)).collect();
|
||||
let mut g = GradientPaint::new(Gradient { spread, repeats: 2, ..Gradient::new(kind, stops) });
|
||||
g.geom = Some(geom);
|
||||
Paint::Gradient(Box::new(g))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_overprinting_gradient_keeps_the_ink_below_where_it_puts_none_on_a_postscript_plate() {
|
||||
// Cyan in the outer stops, none from 0.3 to 0.6 (magenta only there).
|
||||
let (inked, none) = (Color::cmyk(0.6, 0.3, 0.0, 0.0), Color::cmyk(0.0, 0.3, 0.0, 0.0));
|
||||
let stops = [(0.0, inked), (0.3, none), (0.6, none), (1.0, inked)];
|
||||
let c = Point::new(100.0, 50.0);
|
||||
let around = GradientGeom { start: c, end: c + Vec2::new(70.0, -20.0), aspect: 0.7, focal: None };
|
||||
let across = GradientGeom { start: Point::new(30.0, 40.0), end: Point::new(170.0, 60.0), aspect: 1.0, focal: None };
|
||||
let pad = GradientSpread::Pad;
|
||||
let fills = [
|
||||
("linear", gradient(GradientKind::Linear, &stops, across, pad)),
|
||||
("radial", gradient(GradientKind::Radial, &stops, around, pad)),
|
||||
("off-center radial", gradient(GradientKind::Radial, &stops, GradientGeom { focal: Some(c + Vec2::new(-20.0, 10.0)), ..around }, pad)),
|
||||
("conic", gradient(GradientKind::Conic, &stops, around, pad)),
|
||||
("diamond", gradient(GradientKind::Diamond, &stops, around, pad)),
|
||||
("repeating linear", gradient(GradientKind::Linear, &stops, across, GradientSpread::Repeat)),
|
||||
("reflecting radial", gradient(GradientKind::Radial, &stops, around, GradientSpread::Reflect)),
|
||||
// A hard edge: two stops at 0.5, the inked half first.
|
||||
("hard edge", gradient(GradientKind::Linear, &[(0.0, inked), (0.5, inked), (0.5, none), (1.0, none)], across, pad)),
|
||||
// Starting and ending with no cyan, padding past both ends.
|
||||
("none at the ends", gradient(GradientKind::Linear, &[(0.2, none), (0.4, none), (0.5, inked), (0.8, none)], across, pad)),
|
||||
];
|
||||
// Many stretches with no cyan.
|
||||
let many: Vec<(f32, Color)> = (0..16).map(|i| (i as f32 / 15.0, if i % 4 < 2 { inked } else { none })).collect();
|
||||
let fills = fills.into_iter().chain([("many stops", gradient(GradientKind::Linear, &many, across, pad))]);
|
||||
let cyan = Paint::solid(Color::cmyk(1.0, 0.0, 0.0, 0.0));
|
||||
let cases: Vec<_> = fills.map(|(name, fill)| (name, overprinting(fill, Paint::None), cyan.clone(), "Cyan")).collect();
|
||||
assert_keeps_the_ink_below(&cases);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_overprinting_gradient_with_a_hard_stop_at_an_end_keeps_the_ink_below_on_a_postscript_plate() {
|
||||
// Two stops at an end, one with cyan and one without: Level 2's bands pad with the end stop,
|
||||
// Level 3's shading with the stretch next to it, so each level is checked against its own
|
||||
// plate of the gradient alone.
|
||||
let (inked, none) = (Color::cmyk(0.6, 0.3, 0.0, 0.0), Color::cmyk(0.0, 0.3, 0.0, 0.0));
|
||||
let ends = [
|
||||
("none then cyan at 0", [(0.0, none), (0.0, inked), (1.0, inked)]),
|
||||
("cyan then none at 1", [(0.0, inked), (1.0, inked), (1.0, none)]),
|
||||
("cyan then none at 0", [(0.0, inked), (0.0, none), (1.0, none)]),
|
||||
("none then cyan at 1", [(0.0, none), (1.0, none), (1.0, inked)]),
|
||||
];
|
||||
let c = Point::new(100.0, 50.0);
|
||||
let around = GradientGeom { start: c, end: c + Vec2::new(50.0, -10.0), aspect: 0.7, focal: None };
|
||||
let across = GradientGeom { start: Point::new(40.0, 40.0), end: Point::new(160.0, 60.0), aspect: 1.0, focal: None };
|
||||
let pad = GradientSpread::Pad;
|
||||
let cyan = Paint::solid(Color::cmyk(1.0, 0.0, 0.0, 0.0));
|
||||
let shapes = [(GradientKind::Linear, across, "linear"), (GradientKind::Radial, around, "radial"), (GradientKind::Diamond, around, "diamond")];
|
||||
let mut cases = vec![];
|
||||
for (name, stops) in &ends {
|
||||
for (kind, geom, shape) in shapes {
|
||||
let fill = gradient(kind, stops, geom, pad);
|
||||
cases.push((format!("{shape}, {name}"), overprinting(fill, Paint::None), cyan.clone(), "Cyan"));
|
||||
}
|
||||
}
|
||||
let cases: Vec<_> = cases.iter().map(|(name, art, under, ink)| (name.as_str(), art.clone(), under.clone(), *ink)).collect();
|
||||
assert_keeps_the_ink_below_of(&cases, true);
|
||||
}
|
||||
|
||||
/// [`keeps_the_ink_below`] for each of `cases` (a name, the art, the paint under it and the ink
|
||||
/// of the plate) at Level 3 and Level 2, with every case that fails named.
|
||||
fn assert_keeps_the_ink_below(cases: &[(&str, Node, Paint, &str)]) {
|
||||
assert_keeps_the_ink_below_of(cases, false);
|
||||
}
|
||||
|
||||
/// [`assert_keeps_the_ink_below`], checked against the PostScript plate of each case's art alone
|
||||
/// with `postscript`.
|
||||
fn assert_keeps_the_ink_below_of(cases: &[(&str, Node, Paint, &str)], postscript: bool) {
|
||||
let mut failed = vec![];
|
||||
for (name, art, under, ink) in cases {
|
||||
for level in [Level::Three, Level::Two] {
|
||||
let (paper, knocked_out, wrong) = keeps_the_ink_below(std::slice::from_ref(art), under, ink, level, postscript);
|
||||
if knocked_out + wrong >= 100 {
|
||||
failed.push(format!("{name} at level {level:?}: {knocked_out} of {paper} knocked out, {wrong} of the others differ"));
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(failed.is_empty(), "{failed:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overprinting_gradient_strokes_type_freeforms_and_spot_inks_keep_the_ink_below_on_postscript_plates() {
|
||||
let (inked, none) = (Color::cmyk(0.6, 0.3, 0.0, 0.0), Color::cmyk(0.0, 0.3, 0.0, 0.0));
|
||||
let stops = [(0.0, inked), (0.3, none), (0.6, none), (1.0, inked)];
|
||||
let across = GradientGeom { start: Point::new(30.0, 40.0), end: Point::new(170.0, 60.0), aspect: 1.0, focal: None };
|
||||
let linear = gradient(GradientKind::Linear, &stops, across, GradientSpread::Pad);
|
||||
let stroked = |mode: StrokeGradientMode| {
|
||||
let mut n = overprinting(Paint::None, linear.clone());
|
||||
if let Some(st) = n.appearance.stroke_mut() {
|
||||
st.gradient_mode = mode;
|
||||
}
|
||||
n
|
||||
};
|
||||
// Type: a gradient placed on the characters' bounds.
|
||||
let on_type = GradientPaint::new(Gradient::new(GradientKind::Linear, stops.iter().map(|(o, c)| GradientStop::new(*o, *c)).collect()));
|
||||
let style = CharStyle { fill: Paint::Gradient(Box::new(on_type)), overprint_fill: true, size: 80.0, ..Default::default() };
|
||||
let text = Node::new(NodeId(0), NodeKind::Text(Box::new(TextObject::point(Point::new(20.0, 85.0), "HIM", style))));
|
||||
// A freeform gradient with wide spreads of pure color around its points: none of the cyan
|
||||
// around the left one.
|
||||
let mut freeform = GradientPaint::new(Gradient::new(GradientKind::Freeform, vec![GradientStop::new(0.0, none), GradientStop::new(1.0, inked)]));
|
||||
let pure = |at: Point, c: Color| FreeformPoint { spread: 0.9, ..FreeformPoint::new(at, c) };
|
||||
let points = vec![pure(Point::new(50.0, 50.0), none), pure(Point::new(150.0, 50.0), inked)];
|
||||
freeform.freeform = Some(Freeform { points, ..Default::default() });
|
||||
// A spot ink's own plate: its tints in the outer stops, none of it from 0.3 to 0.6.
|
||||
let tint = |t: f32| GradientStop { swatch: Some("Ink".into()), tint: t, ..GradientStop::new(0.0, Color::cmyk(0.0, 0.0, 0.0, t)) };
|
||||
let spot = [
|
||||
GradientStop { offset: 0.0, ..tint(0.8) },
|
||||
GradientStop::new(0.3, none),
|
||||
GradientStop::new(0.6, none),
|
||||
GradientStop { offset: 1.0, ..tint(0.5) },
|
||||
];
|
||||
let mut on_spot = GradientPaint::new(Gradient::new(GradientKind::Linear, spot.to_vec()));
|
||||
on_spot.geom = Some(across);
|
||||
let cyan = Paint::solid(Color::cmyk(1.0, 0.0, 0.0, 0.0));
|
||||
let full = Paint::Solid { color: Color::cmyk(0.0, 0.0, 0.0, 1.0), swatch: Some("Ink".into()), tint: 1.0 };
|
||||
let cases = [
|
||||
("stroke within", stroked(StrokeGradientMode::Within), cyan.clone(), "Cyan"),
|
||||
("stroke along", stroked(StrokeGradientMode::Along), cyan.clone(), "Cyan"),
|
||||
("stroke across", stroked(StrokeGradientMode::Across), cyan.clone(), "Cyan"),
|
||||
("type", text, cyan.clone(), "Cyan"),
|
||||
("freeform", overprinting(Paint::Gradient(Box::new(freeform)), Paint::None), cyan, "Cyan"),
|
||||
("spot", overprinting(Paint::Gradient(Box::new(on_spot)), Paint::None), full, "Ink"),
|
||||
];
|
||||
assert_keeps_the_ink_below(&cases);
|
||||
}
|
||||
+264
-16
@@ -8,6 +8,7 @@ use std::sync::Arc;
|
||||
|
||||
use kurbo::Shape;
|
||||
use vectorcraft_color::{BlendMode, Color, GradientKind, GradientPaint, Paint};
|
||||
use vectorcraft_doc::overprint::is_white;
|
||||
use vectorcraft_doc::{
|
||||
AppearanceItem, ColorMode, Document, Effect, ImageBlob, LineCap, LineJoin, Node, NodeKind, StrokeAlign, StrokeLayer, SymbolBoxes, TextObject,
|
||||
};
|
||||
@@ -213,6 +214,14 @@ impl GradientSpace {
|
||||
GradientSpace::Inks(_, n) => *n,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether components `c` in this space are paper white: no ink, or full light.
|
||||
fn paper(&self, c: &[f32]) -> bool {
|
||||
match self {
|
||||
GradientSpace::Process(Space::Gray | Space::Rgb) => c.iter().all(|v| *v >= 1.0),
|
||||
GradientSpace::Process(Space::Cmyk) | GradientSpace::Inks(..) => c.iter().all(|v| *v <= 0.0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A gradient's stops as written: offsets from 0 to 1 and the components in its space.
|
||||
@@ -287,6 +296,12 @@ pub(crate) struct Scene<'a> {
|
||||
max_body: usize,
|
||||
/// Symbols and brush art being written inside one another.
|
||||
nest: u32,
|
||||
/// The document is a separation's plate: every color is the gray of one ink's coverage
|
||||
/// ([`Self::on_plate`]).
|
||||
plate: bool,
|
||||
/// The gradient being painted overprints on a plate: where it is paper white it puts none of
|
||||
/// the plate's ink down, and the plate below it is left as it is ([`Self::inked_spans`]).
|
||||
keep_below: bool,
|
||||
}
|
||||
|
||||
impl<'a> Scene<'a> {
|
||||
@@ -315,9 +330,19 @@ impl<'a> Scene<'a> {
|
||||
pending: 0,
|
||||
max_body: MAX_BODY,
|
||||
nest: 0,
|
||||
plate: false,
|
||||
keep_below: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// This scene drawing a separation's plate when `plate` is true: an overprinting gradient
|
||||
/// paints only where it puts the plate's ink down, as an overprinting solid color that puts
|
||||
/// none down is drawn as nothing on it.
|
||||
pub fn on_plate(mut self, plate: bool) -> Self {
|
||||
self.plate = plate;
|
||||
self
|
||||
}
|
||||
|
||||
/// This scene with a page body of at most `max` bytes.
|
||||
#[cfg(test)]
|
||||
pub fn with_max_body(mut self, max: usize) -> Self {
|
||||
@@ -689,13 +714,20 @@ impl<'a> Scene<'a> {
|
||||
self.line("q");
|
||||
push_path(&mut self.body, bp);
|
||||
self.body.push_str(clip_op(rule));
|
||||
self.paint_area(p, bounds, bp.bounding_box());
|
||||
self.paint_overprinting(overprint, p, bounds, bp.bounding_box());
|
||||
self.line("Q");
|
||||
}
|
||||
}
|
||||
self.overprint_off(on);
|
||||
}
|
||||
|
||||
/// [`Self::paint_area`] for a fill or stroke that overprints when `overprint` is true.
|
||||
fn paint_overprinting(&mut self, overprint: bool, p: &Paint, bounds: Rect, area: Rect) {
|
||||
let keep = std::mem::replace(&mut self.keep_below, self.plate && overprint);
|
||||
self.paint_area(p, bounds, area);
|
||||
self.keep_below = keep;
|
||||
}
|
||||
|
||||
/// Paint all of `area` (inside the current clip) with gradient or pattern `p`, placed on
|
||||
/// `bounds`.
|
||||
fn paint_area(&mut self, p: &Paint, bounds: Rect, area: Rect) {
|
||||
@@ -786,7 +818,7 @@ impl<'a> Scene<'a> {
|
||||
self.line("q");
|
||||
push_path(&mut self.body, bp);
|
||||
self.line("strokepath W");
|
||||
self.paint_area(p, paint_bounds, w.reach(st, bounds));
|
||||
self.paint_overprinting(st.overprint, p, paint_bounds, w.reach(st, bounds));
|
||||
self.line("Q");
|
||||
}
|
||||
}
|
||||
@@ -1152,7 +1184,8 @@ impl<'a> Scene<'a> {
|
||||
|
||||
/// Paint all of `area` (inside the current clip) with linear, radial, conic or diamond gradient
|
||||
/// `g`, placed on `bounds`: a smooth shading at Level 3, else stepped fills (a conic: wedges at
|
||||
/// both levels; a diamond: four linear gradients, [`Self::diamond_quadrants`]).
|
||||
/// both levels; a diamond: four linear gradients, [`Self::diamond_quadrants`]). Overprinting
|
||||
/// on a plate, it is clipped to the levels where it puts ink down ([`Self::inked_spans`]).
|
||||
fn gradient(&mut self, g: &GradientPaint, bounds: Rect, area: Rect) {
|
||||
let geom = g.resolve(bounds);
|
||||
// One mixed around the hue wheel that reflects is repeated from its curve's stops, which
|
||||
@@ -1185,7 +1218,7 @@ impl<'a> Scene<'a> {
|
||||
}
|
||||
let (space, stops) = self.gradient_stops(&g.gradient);
|
||||
if !stops.windows(2).any(|w| w[1].0 > w[0].0) {
|
||||
if let Some((_, c)) = stops.first() {
|
||||
if let Some((_, c)) = stops.first().filter(|(_, c)| !(self.keep_below && space.paper(c))) {
|
||||
self.set_comps(&space, c);
|
||||
self.rect_fill(area);
|
||||
}
|
||||
@@ -1193,20 +1226,47 @@ impl<'a> Scene<'a> {
|
||||
}
|
||||
let space = &space;
|
||||
let smooth = self.o.level == Level::Three && !self.o.compatible_gradients;
|
||||
let spans = if g.gradient.kind == GradientKind::Conic { None } else { self.inked_spans(space, &stops, smooth) };
|
||||
match g.gradient.kind {
|
||||
GradientKind::Conic => self.conic_steps(&geom, area, space, &stops, &g.gradient),
|
||||
GradientKind::Diamond => self.diamond_quadrants(&geom, area, space, &stops, smooth),
|
||||
GradientKind::Diamond => {
|
||||
// Its levels are diamonds about the center, the square's edge at 1.
|
||||
let frame = geom.diamond_frame();
|
||||
if let Some(spans) = &spans {
|
||||
let Some(frame) = frame else {
|
||||
// Without a frame it is its last stop everywhere.
|
||||
if stops.last().is_some_and(|(_, c)| !space.paper(c)) {
|
||||
self.diamond_quadrants(&geom, area, space, &stops, smooth);
|
||||
}
|
||||
return;
|
||||
};
|
||||
let level = |t: f64| (t > 0.0).then(|| frame * BezPath::from_vec(diamond(t)));
|
||||
self.line("q");
|
||||
let clipped = self.clip_rings(spans, area.inflate(1.0, 1.0), level);
|
||||
if clipped {
|
||||
self.diamond_quadrants(&geom, area, space, &stops, smooth);
|
||||
}
|
||||
self.line("Q");
|
||||
return;
|
||||
}
|
||||
self.diamond_quadrants(&geom, area, space, &stops, smooth);
|
||||
}
|
||||
GradientKind::Radial => {
|
||||
let r = geom.length().max(1e-6);
|
||||
let squash = geom.radial_squash();
|
||||
let inv = squash.inverse();
|
||||
let (f, c) = (inv * geom.focal_point(), geom.start);
|
||||
let local = inv.transform_rect_bbox(area);
|
||||
self.line("q");
|
||||
let _ = writeln!(self.body, "{} cm", ps::matrix(squash));
|
||||
if smooth {
|
||||
self.shading(3, space, &[f.x, f.y, 0.0, c.x, c.y, r], &stops);
|
||||
} else {
|
||||
self.radial_steps(f, c, r, inv.transform_rect_bbox(area), space, &stops);
|
||||
// Its levels are circles from the focal point, at 1 the circle of radius `r`.
|
||||
let level = |t: f64| (t > 0.0).then(|| kurbo::Circle::new(f + (c - f) * t, r * t).to_path(0.01));
|
||||
if spans.as_ref().is_none_or(|spans| self.clip_rings(spans, local.inflate(1.0, 1.0), level)) {
|
||||
if smooth {
|
||||
self.shading(3, space, &[f.x, f.y, 0.0, c.x, c.y, r], &stops);
|
||||
} else {
|
||||
self.radial_steps(f, c, r, local, space, &stops);
|
||||
}
|
||||
}
|
||||
self.line("Q");
|
||||
}
|
||||
@@ -1215,15 +1275,122 @@ impl<'a> Scene<'a> {
|
||||
if s.distance(e) < 1e-9 {
|
||||
e = s + Vec2::new(1.0, 0.0);
|
||||
}
|
||||
if smooth {
|
||||
self.shading(2, space, &[s.x, s.y, e.x, e.y], &stops);
|
||||
if let Some(spans) = &spans {
|
||||
self.line("q");
|
||||
if self.clip_strips(spans, s, e, area) {
|
||||
self.linear(s, e, area, space, &stops, smooth);
|
||||
}
|
||||
self.line("Q");
|
||||
} else {
|
||||
self.linear_steps(s, e, area, space, &stops);
|
||||
self.linear(s, e, area, space, &stops, smooth);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A linear gradient from `s` to `e` over `area`: a smooth shading, else stepped fills.
|
||||
fn linear(&mut self, s: Point, e: Point, area: Rect, space: &GradientSpace, stops: &[(f64, Vec<f32>)], smooth: bool) {
|
||||
if smooth {
|
||||
self.shading(2, space, &[s.x, s.y, e.x, e.y], stops);
|
||||
} else {
|
||||
self.linear_steps(s, e, area, space, stops);
|
||||
}
|
||||
}
|
||||
|
||||
/// Where an overprinting gradient with `stops` in `space` puts ink on a plate
|
||||
/// ([`Self::keep_below`]): the spans of its levels outside every stretch between two stops of
|
||||
/// paper white and outside the padding past an end painted paper white, in order, an end
|
||||
/// padding with ink unbounded. The padding takes the end stop's color when stepped and the
|
||||
/// end stretch's color when `smooth` ([`Self::shading`]); the two differ when two stops share
|
||||
/// the end's offset. `None` when the gradient puts ink everywhere or does not overprint on a
|
||||
/// plate; empty when it puts none down.
|
||||
fn inked_spans(&self, space: &GradientSpace, stops: &[(f64, Vec<f32>)], smooth: bool) -> Option<Vec<(f64, f64)>> {
|
||||
if !self.keep_below {
|
||||
return None;
|
||||
}
|
||||
let stretches: Vec<_> = stops.windows(2).filter(|w| w[1].0 > w[0].0).collect();
|
||||
let (first, last) = (stretches.first()?, stretches.last()?);
|
||||
let (start, end) = if smooth { (&first[0].1, &last[1].1) } else { (&stops.first()?.1, &stops.last()?.1) };
|
||||
let (before, after) = (space.paper(start), space.paper(end));
|
||||
let mut blank: Vec<(f64, f64)> = vec![];
|
||||
let mut add = |a: f64, b: f64| match blank.last_mut() {
|
||||
Some(l) if l.1 >= a => l.1 = l.1.max(b),
|
||||
_ => blank.push((a, b)),
|
||||
};
|
||||
if before {
|
||||
add(f64::NEG_INFINITY, first[0].0);
|
||||
}
|
||||
for w in &stretches {
|
||||
if space.paper(&w[0].1) && space.paper(&w[1].1) {
|
||||
add(w[0].0, w[1].0);
|
||||
}
|
||||
}
|
||||
if after {
|
||||
add(last[1].0, f64::INFINITY);
|
||||
}
|
||||
if blank.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut inked = vec![];
|
||||
let mut from = f64::NEG_INFINITY;
|
||||
for (a, b) in blank {
|
||||
if a > from {
|
||||
inked.push((from, a));
|
||||
}
|
||||
from = b;
|
||||
}
|
||||
if from < f64::INFINITY {
|
||||
inked.push((from, f64::INFINITY));
|
||||
}
|
||||
Some(inked)
|
||||
}
|
||||
|
||||
/// Clip to the parts of `area` where a linear gradient from `s` to `e` has a level in `spans`:
|
||||
/// a strip across the gradient for each. False, with nothing written, when no span reaches
|
||||
/// into `area`.
|
||||
fn clip_strips(&mut self, spans: &[(f64, f64)], s: Point, e: Point, area: Rect) -> bool {
|
||||
let d = e - s;
|
||||
let len = d.hypot();
|
||||
// Gradient space: x along the gradient (0 to 1), y across it in points.
|
||||
let frame = Affine::new([d.x, d.y, -d.y / len, d.x / len, s.x, s.y]);
|
||||
let local = frame.inverse().transform_rect_bbox(area.inflate(1.0, 1.0));
|
||||
let mut bp = BezPath::new();
|
||||
for &(a, b) in spans {
|
||||
let (a, b) = (a.max(local.x0), b.min(local.x1));
|
||||
if a < b {
|
||||
bp.extend((frame * Rect::new(a, local.y0, b, local.y1).to_path(0.1)).iter());
|
||||
}
|
||||
}
|
||||
self.clip_path(&bp, FillRule::NonZero)
|
||||
}
|
||||
|
||||
/// Clip to the levels in `spans` of a gradient whose level `t` is bounded by `level(t)` (a
|
||||
/// closed path holding every lower level; `None` for a level without area): for each span
|
||||
/// the ring between its levels, an unbounded end at `outer`, even-odd. False, with nothing
|
||||
/// written, when no span has area.
|
||||
fn clip_rings(&mut self, spans: &[(f64, f64)], outer: Rect, level: impl Fn(f64) -> Option<BezPath>) -> bool {
|
||||
let mut bp = BezPath::new();
|
||||
for &(a, b) in spans {
|
||||
let edge = if b.is_finite() { level(b) } else { Some(outer.to_path(0.1)) };
|
||||
let Some(edge) = edge else { continue };
|
||||
bp.extend(edge.iter());
|
||||
if let Some(inner) = level(a).filter(|_| a.is_finite()) {
|
||||
bp.extend(inner.iter());
|
||||
}
|
||||
}
|
||||
self.clip_path(&bp, FillRule::EvenOdd)
|
||||
}
|
||||
|
||||
/// Clip to `bp` by `rule`. False, with nothing written, when `bp` is empty.
|
||||
fn clip_path(&mut self, bp: &BezPath, rule: FillRule) -> bool {
|
||||
if bp.elements().is_empty() {
|
||||
return false;
|
||||
}
|
||||
push_path(&mut self.body, bp);
|
||||
self.body.push_str(clip_op(rule));
|
||||
true
|
||||
}
|
||||
|
||||
/// A conic gradient as [`CONIC_WEDGE_COUNT`] solid wedges about its center covering `area`
|
||||
/// (PostScript has no conic shading), each running on to the seam under the next, so no
|
||||
/// hairline shows between neighbors ([`vectorcraft_color::GradientGeom::conic_wedges`]).
|
||||
@@ -1243,7 +1410,24 @@ impl<'a> Scene<'a> {
|
||||
Some(w) => w[1].1.clone(),
|
||||
None => stops.last().map_or_else(Vec::new, |s| s.1.clone()),
|
||||
};
|
||||
for (pts, t) in geom.conic_wedges(area, g.conic_wedge_count(CONIC_WEDGE_COUNT), true) {
|
||||
let count = g.conic_wedge_count(CONIC_WEDGE_COUNT);
|
||||
// Overprinting on a plate: clipped to the wedges that put ink down, each up to the next.
|
||||
let clipped = self.keep_below && {
|
||||
let wedges = geom.conic_wedges(area, count, false);
|
||||
let inked: Vec<_> = wedges.iter().filter(|(_, t)| !space.paper(&at(spread(*t)))).collect();
|
||||
if inked.is_empty() {
|
||||
return;
|
||||
}
|
||||
inked.len() < wedges.len() && {
|
||||
let mut bp = BezPath::new();
|
||||
for (pts, _) in inked {
|
||||
bp.extend(BezPath::from_vec(polygon(pts)).iter());
|
||||
}
|
||||
self.line("q");
|
||||
self.clip_path(&bp, FillRule::NonZero)
|
||||
}
|
||||
};
|
||||
for (pts, t) in geom.conic_wedges(area, count, true) {
|
||||
self.set_comps(space, &at(spread(t)));
|
||||
for (i, p) in pts.iter().enumerate() {
|
||||
push_nums(&mut self.body, &[p.x, p.y]);
|
||||
@@ -1251,6 +1435,9 @@ impl<'a> Scene<'a> {
|
||||
}
|
||||
self.line("closepath fill");
|
||||
}
|
||||
if clipped {
|
||||
self.line("Q");
|
||||
}
|
||||
}
|
||||
|
||||
/// A diamond gradient over `area` as four linear gradients, each clipped to a quadrant of its
|
||||
@@ -1442,20 +1629,68 @@ impl<'a> Scene<'a> {
|
||||
let field = g.freeform_on(b).model_field(spread_scale(b));
|
||||
let q = |v: f32| (unit(v) * 255.0).round() as u8;
|
||||
let (w, h) = (u32::from(cols), u32::from(rows));
|
||||
// Overprinting on a plate: the cells of paper white put none of the ink down, so they are
|
||||
// left out, as clear pixels at Level 3 and outside a clip of the other cells at Level 2.
|
||||
let blank: Option<Vec<bool>> = self.keep_below.then(|| field.grid(area, cols, rows).map(|(c, _)| is_white(&Paint::solid(c))).collect());
|
||||
let blank = blank.filter(|b| b.contains(&true));
|
||||
if blank.as_ref().is_some_and(|b| !b.contains(&false)) {
|
||||
return;
|
||||
}
|
||||
let keyed = self.o.level == Level::Three;
|
||||
let clear = |i: usize, a: u8| if keyed && blank.as_ref().is_some_and(|b| b[i]) { 0 } else { a };
|
||||
let image = if field.model() == Some(Model::Cmyk) || (self.cmyk && field.model() == Some(Model::Gray)) {
|
||||
let inks: Vec<u8> = field
|
||||
.grid(area, cols, rows)
|
||||
.flat_map(|(color, a)| {
|
||||
.enumerate()
|
||||
.flat_map(|(i, (color, a))| {
|
||||
let [c, m, y, k] = color.to_cmyk();
|
||||
[q(c), q(m), q(y), q(k), q(a)]
|
||||
[q(c), q(m), q(y), q(k), clear(i, q(a))]
|
||||
})
|
||||
.collect();
|
||||
self.encode_inks(&inks, w, h)
|
||||
} else {
|
||||
let rgba: Vec<u8> = field.display_grid(area, cols, rows).flat_map(|(c, a)| [q(c[0]), q(c[1]), q(c[2]), q(a)]).collect();
|
||||
let rgba: Vec<u8> =
|
||||
field.display_grid(area, cols, rows).enumerate().flat_map(|(i, (c, a))| [q(c[0]), q(c[1]), q(c[2]), clear(i, q(a))]).collect();
|
||||
self.encode_image(&rgba, w, h)
|
||||
};
|
||||
let Some(image) = image else { return };
|
||||
let cells = blank.filter(|_| !keyed).map(|b| {
|
||||
let (cw, ch) = (area.width() / f64::from(cols), area.height() / f64::from(rows));
|
||||
let mut bp = BezPath::new();
|
||||
for (row, line) in b.chunks(usize::from(cols)).enumerate() {
|
||||
let mut col = 0;
|
||||
while col < line.len() {
|
||||
let start = col;
|
||||
while col < line.len() && !line[col] {
|
||||
col += 1;
|
||||
}
|
||||
if col > start {
|
||||
let (y0, y1) = (area.y0 + row as f64 * ch, area.y0 + (row + 1) as f64 * ch);
|
||||
bp.extend(Rect::new(area.x0 + start as f64 * cw, y0, area.x0 + col as f64 * cw, y1).to_path(0.1).iter());
|
||||
}
|
||||
col += 1;
|
||||
}
|
||||
}
|
||||
bp
|
||||
});
|
||||
if let Some(bp) = &cells {
|
||||
// Each row's run of cells is a rectangle of five path elements, about 60 bytes.
|
||||
if self.size().saturating_add(bp.elements().len().saturating_mul(12)).saturating_add(image.inline_len) > self.max_body {
|
||||
self.warn(TOO_LARGE);
|
||||
return;
|
||||
}
|
||||
self.line("q");
|
||||
self.clip_path(bp, FillRule::NonZero);
|
||||
}
|
||||
self.place_field(image, place);
|
||||
if cells.is_some() {
|
||||
self.line("Q");
|
||||
}
|
||||
}
|
||||
|
||||
/// Place freeform gradient image `image` on the unit square mapped by `place`, drawn from an
|
||||
/// image already kept when one is encoded the same.
|
||||
fn place_field(&mut self, image: ImageCode, place: Affine) {
|
||||
let key = image.content_key();
|
||||
let found =
|
||||
self.fields.get(&key).and_then(|bucket| bucket.iter().copied().find(|&i| self.codes.get(i).is_some_and(|c| c.same_image(&image))));
|
||||
@@ -1849,6 +2084,19 @@ fn image_code(prelude: String, dict: String, filter: &'static str, op: &'static
|
||||
code
|
||||
}
|
||||
|
||||
/// The closed polygon through `pts`.
|
||||
fn polygon(pts: &[Point]) -> Vec<kurbo::PathEl> {
|
||||
let mut els: Vec<kurbo::PathEl> =
|
||||
pts.iter().enumerate().map(|(i, p)| if i == 0 { kurbo::PathEl::MoveTo(*p) } else { kurbo::PathEl::LineTo(*p) }).collect();
|
||||
els.push(kurbo::PathEl::ClosePath);
|
||||
els
|
||||
}
|
||||
|
||||
/// The square with corners (±`t`, 0) and (0, ±`t`).
|
||||
fn diamond(t: f64) -> Vec<kurbo::PathEl> {
|
||||
polygon(&[Point::new(t, 0.0), Point::new(0.0, t), Point::new(-t, 0.0), Point::new(0.0, -t)])
|
||||
}
|
||||
|
||||
/// `a` to `b` at `t`.
|
||||
fn mix(a: &[f32], b: &[f32], t: f32) -> Vec<f32> {
|
||||
a.iter().zip(b).map(|(x, y)| x + (y - x) * t).collect()
|
||||
|
||||
@@ -327,7 +327,7 @@ fn install_errors(interp: &mut Interp, object_proto: ObjId) -> JsResult<()> {
|
||||
for (i, (name, f)) in kinds.into_iter().enumerate() {
|
||||
// Error.prototype and each NativeError prototype are Error objects (sections 15.11.4 and
|
||||
// 15.11.7.7).
|
||||
let proto = alloc(interp, Class::Error, Some(if i == 0 { object_proto } else { error_proto }));
|
||||
let proto = alloc(interp, Class::Error(None), Some(if i == 0 { object_proto } else { error_proto }));
|
||||
if i == 0 {
|
||||
error_proto = proto;
|
||||
method(interp, proto, "toString", error_to_string, 0)?;
|
||||
|
||||
@@ -215,7 +215,9 @@ pub(crate) enum Class {
|
||||
length_writable: bool,
|
||||
},
|
||||
Function(Func),
|
||||
Error,
|
||||
/// An error object. One the interpreter threw itself holds a hash of the description it had
|
||||
/// then ([`crate::interp::Interp::describe`]); one a script made holds `None`.
|
||||
Error(Option<u64>),
|
||||
Arguments(Box<ArgMap>),
|
||||
/// A `Boolean` object made by ToObject, with its primitive value.
|
||||
Boolean(bool),
|
||||
@@ -313,7 +315,7 @@ impl Class {
|
||||
Class::Ordinary | Class::ForIn(_) => "Object",
|
||||
Class::Array { .. } => "Array",
|
||||
Class::Function(_) => "Function",
|
||||
Class::Error => "Error",
|
||||
Class::Error(_) => "Error",
|
||||
Class::Arguments(_) => "Arguments",
|
||||
Class::Boolean(_) => "Boolean",
|
||||
Class::Number(_) => "Number",
|
||||
|
||||
+45
-3
@@ -48,6 +48,14 @@ fn internal<T>(message: &str) -> JsResult<T> {
|
||||
Err(Abrupt::Internal(message.into()))
|
||||
}
|
||||
|
||||
/// The hash an error the interpreter throws keeps of its description ([`Interp::throw`]).
|
||||
fn description_hash(text: &str) -> u64 {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut h = std::hash::DefaultHasher::new();
|
||||
text.hash(&mut h);
|
||||
h.finish()
|
||||
}
|
||||
|
||||
/// The kinds of error object the engine throws.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum ErrorType {
|
||||
@@ -60,6 +68,21 @@ pub(crate) enum ErrorType {
|
||||
Uri,
|
||||
}
|
||||
|
||||
impl ErrorType {
|
||||
/// The `name` the prototype of this kind of error has before a script changes it.
|
||||
pub(crate) fn name(self) -> &'static str {
|
||||
match self {
|
||||
ErrorType::Error => "Error",
|
||||
ErrorType::Eval => "EvalError",
|
||||
ErrorType::Range => "RangeError",
|
||||
ErrorType::Reference => "ReferenceError",
|
||||
ErrorType::Syntax => "SyntaxError",
|
||||
ErrorType::Type => "TypeError",
|
||||
ErrorType::Uri => "URIError",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The objects the interpreter itself refers to.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct Intrinsics {
|
||||
@@ -538,15 +561,34 @@ impl Interp {
|
||||
|
||||
pub(crate) fn error_object(&mut self, t: ErrorType, message: &str) -> ObjId {
|
||||
let proto = self.intrinsics.error_proto(t);
|
||||
let mut o = Object::new(Class::Error, Some(proto));
|
||||
let mut o = Object::new(Class::Error(None), Some(proto));
|
||||
if !message.is_empty() {
|
||||
o.props.insert(key("message"), Prop::Data { value: Value::str(message), flags: HIDDEN });
|
||||
}
|
||||
self.heap.alloc_object(o)
|
||||
}
|
||||
|
||||
/// An error of the interpreter's or a host function's own, marked as such with a hash of the
|
||||
/// description it has with its kind's own name ([`Self::thrown_by_script`]), so a name a script
|
||||
/// gave the kind's prototype before the error was made counts as the script's text.
|
||||
pub(crate) fn throw(&mut self, t: ErrorType, message: &str) -> Abrupt {
|
||||
Abrupt::Throw(Value::Object(self.error_object(t, message)))
|
||||
let o = self.error_object(t, message);
|
||||
let own = if message.is_empty() { t.name().to_string() } else { format!("{}: {message}", t.name()) };
|
||||
if let Some(object) = self.heap.object_mut(o) {
|
||||
object.class = Class::Error(Some(description_hash(&own)));
|
||||
}
|
||||
Abrupt::Throw(Value::Object(o))
|
||||
}
|
||||
|
||||
/// Is the text [`Self::describe`] gives for the thrown value `v` the script's own? It is unless
|
||||
/// `v` is an error the interpreter or a host function threw, with its name and message as they
|
||||
/// were then: a value the script threw, an error it made, and an error whose name or message it
|
||||
/// changed all hold its own text.
|
||||
pub(crate) fn thrown_by_script(&mut self, v: &Value) -> bool {
|
||||
let Value::Object(o) = v else { return true };
|
||||
let Some(Class::Error(Some(hash))) = self.heap.object(*o).map(|o| &o.class) else { return true };
|
||||
let hash = *hash;
|
||||
description_hash(&self.describe(v)) != hash
|
||||
}
|
||||
|
||||
pub(crate) fn type_error(&mut self, message: &str) -> Abrupt {
|
||||
@@ -819,7 +861,7 @@ impl Interp {
|
||||
let passed = matches!((&v, std::mem::replace(&mut self.passing, Value::Undefined)), (Value::Object(a), Value::Object(b)) if *a == b);
|
||||
if !passed
|
||||
&& let Value::Object(o) = v
|
||||
&& self.heap.object(o).is_some_and(|o| matches!(o.class, Class::Error))
|
||||
&& self.heap.object(o).is_some_and(|o| matches!(o.class, Class::Error(_)))
|
||||
{
|
||||
self.last_error = v.clone();
|
||||
}
|
||||
|
||||
@@ -239,6 +239,44 @@ fn errors_carry_line_and_column() {
|
||||
assert_eq!(e.message, "42");
|
||||
}
|
||||
|
||||
/// A run error says whether its message is the script's own text, whatever that text reads: an
|
||||
/// error the interpreter or a host function threw is not, even when a script caught it and threw
|
||||
/// it again, and a value or error the script made, or an error whose name or message it changed,
|
||||
/// is.
|
||||
#[test]
|
||||
fn script_error_origin_distinguishes_native_and_authored_values() {
|
||||
let native = "RangeError: invalid array length";
|
||||
for (src, message, authored) in [
|
||||
("new Array(-1)", native, false),
|
||||
("try { new Array(-1); } catch (e) { throw e; }", native, false),
|
||||
("try { new Array(-1); } catch (e) { e.message = 'invalid array length'; throw e; }", native, false),
|
||||
("nope()", "ReferenceError: nope is not defined", false),
|
||||
("throw new RangeError('invalid array length')", native, true),
|
||||
("throw new Error('invalid array length')", "Error: invalid array length", true),
|
||||
("throw 'invalid array length'", "invalid array length", true),
|
||||
("throw 17", "17", true),
|
||||
("throw {}", "[object Object]", true),
|
||||
("throw new Error()", "Error", true),
|
||||
("try { new Array(-1); } catch (e) { throw e.message; }", "invalid array length", true),
|
||||
("try { new Array(-1); } catch (e) { throw new RangeError(e.message); }", native, true),
|
||||
("try { new Array(-1); } catch (e) { e.message = 'mine'; throw e; }", "RangeError: mine", true),
|
||||
("try { nope(); } catch (e) { e.name = 'TypeError'; throw e; }", "TypeError: nope is not defined", true),
|
||||
("try { new Array(-1); } catch (e) { RangeError.prototype.name = 'Mine'; throw e; }", "Mine: invalid array length", true),
|
||||
("RangeError.prototype.name = 'Mine'; new Array(-1)", "Mine: invalid array length", true),
|
||||
("RangeError.prototype.name = 'RangeError'; new Array(-1)", native, false),
|
||||
] {
|
||||
let e = fail(src);
|
||||
assert_eq!((e.kind, e.message.as_str(), e.authored), (RunErrorKind::Thrown, message, authored), "{src}");
|
||||
}
|
||||
assert!(!fail("var x = ;").authored, "a syntax error");
|
||||
let mut realm = Realm::new();
|
||||
realm.define_function("add", |_| Err("add takes two numbers".into()));
|
||||
let e = realm.run("add()").unwrap_err();
|
||||
assert_eq!((e.message.as_str(), e.authored), ("Error: add takes two numbers", false), "a host function's error");
|
||||
let e = realm.run("throw new Error('add takes two numbers')").unwrap_err();
|
||||
assert_eq!((e.message.as_str(), e.authored), ("Error: add takes two numbers", true));
|
||||
}
|
||||
|
||||
/// An error about a property of `null` or `undefined` names a computed property whose name is a
|
||||
/// primitive, and says whether the script read or set it, never naming an empty property; a
|
||||
/// member assignment, an object key and a long name leave the name out.
|
||||
|
||||
+29
-10
@@ -139,6 +139,10 @@ pub struct RunError {
|
||||
pub message: String,
|
||||
pub line: u32,
|
||||
pub column: u32,
|
||||
/// `message` is text the script supplied: a value it threw, or an error object it made or whose
|
||||
/// name or message it changed. False for the interpreter's and host functions' own errors,
|
||||
/// syntax errors and limits, even when a script caught one and threw it again.
|
||||
pub authored: bool,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for RunError {
|
||||
@@ -151,7 +155,7 @@ impl std::error::Error for RunError {}
|
||||
|
||||
impl From<SyntaxError> for RunError {
|
||||
fn from(e: SyntaxError) -> Self {
|
||||
RunError { kind: RunErrorKind::Syntax, message: e.to_string(), line: e.line, column: e.column }
|
||||
RunError { kind: RunErrorKind::Syntax, message: e.to_string(), line: e.line, column: e.column, authored: false }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -241,7 +245,7 @@ impl Realm {
|
||||
self.script_tag = UNKNOWN_SOURCE;
|
||||
let interp = &mut self.interp;
|
||||
if let Some(message) = &interp.install_error {
|
||||
return Err(RunError { kind: RunErrorKind::Internal, message: message.clone(), line: 0, column: 0 });
|
||||
return Err(RunError { kind: RunErrorKind::Internal, message: message.clone(), line: 0, column: 0, authored: false });
|
||||
}
|
||||
interp.fuel = interp.limits.fuel;
|
||||
interp.flattened_fuel.set(0);
|
||||
@@ -269,7 +273,7 @@ impl Realm {
|
||||
interp.error_tag = self.script_tag;
|
||||
Err(e.into())
|
||||
}
|
||||
Err(CompileError::Internal(m)) => Err(RunError { kind: RunErrorKind::Internal, message: m, line: 0, column: 0 }),
|
||||
Err(CompileError::Internal(m)) => Err(RunError { kind: RunErrorKind::Internal, message: m, line: 0, column: 0, authored: false }),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -293,15 +297,18 @@ impl Realm {
|
||||
Ok(v) => Ok(interp.to_js_value(&v)),
|
||||
Err(Abrupt::Throw(v)) => {
|
||||
let message = interp.describe(&v);
|
||||
let authored = interp.thrown_by_script(&v);
|
||||
interp.last_thrown = v;
|
||||
Err(RunError { kind: RunErrorKind::Thrown, message, line, column })
|
||||
Err(RunError { kind: RunErrorKind::Thrown, message, line, column, authored })
|
||||
}
|
||||
Err(Abrupt::Limit(LimitKind::Host)) => {
|
||||
let message = interp.host_abort.take().unwrap_or_else(|| format!("limit reached: {:?}", LimitKind::Host));
|
||||
Err(RunError { kind: RunErrorKind::Limit(LimitKind::Host), message, line, column })
|
||||
Err(RunError { kind: RunErrorKind::Limit(LimitKind::Host), message, line, column, authored: false })
|
||||
}
|
||||
Err(Abrupt::Limit(kind)) => Err(RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line, column }),
|
||||
Err(Abrupt::Internal(message)) => Err(RunError { kind: RunErrorKind::Internal, message, line, column }),
|
||||
Err(Abrupt::Limit(kind)) => {
|
||||
Err(RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line, column, authored: false })
|
||||
}
|
||||
Err(Abrupt::Internal(message)) => Err(RunError { kind: RunErrorKind::Internal, message, line, column, authored: false }),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -323,10 +330,16 @@ impl Realm {
|
||||
pub fn advance(&mut self, slice: u64) -> Result<Progress, RunError> {
|
||||
let interp = &mut self.interp;
|
||||
if interp.frames.is_empty() {
|
||||
return Err(RunError { kind: RunErrorKind::Internal, message: "no run to advance".into(), line: 0, column: 0 });
|
||||
return Err(RunError { kind: RunErrorKind::Internal, message: "no run to advance".into(), line: 0, column: 0, authored: false });
|
||||
}
|
||||
if interp.waiting {
|
||||
return Err(RunError { kind: RunErrorKind::Internal, message: "the run waits for a host function's result".into(), line: 0, column: 0 });
|
||||
return Err(RunError {
|
||||
kind: RunErrorKind::Internal,
|
||||
message: "the run waits for a host function's result".into(),
|
||||
line: 0,
|
||||
column: 0,
|
||||
authored: false,
|
||||
});
|
||||
}
|
||||
let total = interp.fuel;
|
||||
let cap = slice.saturating_add(self.unbroken_fuel).min(total);
|
||||
@@ -384,7 +397,13 @@ impl Realm {
|
||||
pub fn answer(&mut self, d: crate::Data) -> Result<(), RunError> {
|
||||
let interp = &mut self.interp;
|
||||
if !interp.waiting {
|
||||
return Err(RunError { kind: RunErrorKind::Internal, message: "no host function waits for a result".into(), line: 0, column: 0 });
|
||||
return Err(RunError {
|
||||
kind: RunErrorKind::Internal,
|
||||
message: "no host function waits for a result".into(),
|
||||
line: 0,
|
||||
column: 0,
|
||||
authored: false,
|
||||
});
|
||||
}
|
||||
interp.waiting = false;
|
||||
// The value on top of the stack stood in for the result.
|
||||
|
||||
@@ -1663,6 +1663,45 @@ fn transform_refused_by_a_later_operation_changes_nothing() {
|
||||
assert_eq!(count(&mut s), base, "one undo removes the rectangle");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transform_rejects_a_mistyped_reflect_copy_or_origin_before_editing() {
|
||||
let inspect = |s: &mut Server, id| serde_json::from_str::<Value>(&text_of(&call(s, id, "doc_inspect", json!({})))).unwrap();
|
||||
let mut s = server();
|
||||
let first = id_of(&call(&mut s, 1, "draw_path", json!({"d": "M10 10 L30 10 L30 25 Z"})));
|
||||
let second = id_of(&call(&mut s, 2, "draw_path", json!({"d": "M40 40 L60 40 L60 55 Z"})));
|
||||
let before = inspect(&mut s, 3);
|
||||
let cases = [
|
||||
("object.reflect", json!({"dx": 10, "reflect": 42, "copy": true})),
|
||||
("object.reflect", json!({"dx": 10, "reflect": true})),
|
||||
("copy", json!({"dx": 10, "copy": "yes"})),
|
||||
("origin", json!({"dx": 10, "rotate": 30, "origin": "center", "copy": true})),
|
||||
("origin", json!({"dx": 10, "rotate": 30, "origin": [5]})),
|
||||
("origin", json!({"dx": 10, "rotate": 30, "origin": [5, "a"]})),
|
||||
];
|
||||
for (index, (says, mut args)) in cases.into_iter().enumerate() {
|
||||
args["ids"] = json!([first]);
|
||||
let request_id = 4 + index as u64 * 2;
|
||||
let rejected = call(&mut s, request_id, "transform", args.clone());
|
||||
assert_eq!(rejected["isError"], true, "{args}: {rejected}");
|
||||
assert!(text_of(&rejected).contains(says), "{args}: {rejected}");
|
||||
// The document, the selection and the undo history are as they were.
|
||||
assert_eq!(inspect(&mut s, request_id + 1), before, "{args}");
|
||||
}
|
||||
// A null `reflect`, `copy` or `origin` is left out.
|
||||
let applied = call(&mut s, 20, "transform", json!({"ids": [second], "dx": 10, "reflect": null, "copy": null, "origin": null}));
|
||||
assert_eq!(applied["isError"], false, "{applied}");
|
||||
let applied: Value = serde_json::from_str(&text_of(&applied)).unwrap();
|
||||
assert_eq!(applied["applied"], json!(["move"]));
|
||||
let applied = call(&mut s, 21, "transform", json!({"ids": [second], "rotate": 90, "origin": null}));
|
||||
assert_eq!(applied["isError"], false, "{applied}");
|
||||
// The schema allows null for every argument but `ids`.
|
||||
let tools = tool_definitions();
|
||||
let props = &tools.iter().find(|t| t["name"] == "transform").unwrap()["inputSchema"]["properties"];
|
||||
for key in ["dx", "dy", "rotate", "scale", "scaleX", "scaleY", "shear", "reflect", "copy", "origin"] {
|
||||
assert!(props[key]["anyOf"].as_array().is_some_and(|a| a.contains(&json!({"type": "null"}))), "{key}: {}", props[key]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_text_rejects_invalid_path_effects_before_editing() {
|
||||
let mut s = server();
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! A shape tool's double-click on a selected live shape's corner widget through MCP: the
|
||||
//! gesture's `requests` carry the Transform panel.
|
||||
//! Live shape widgets through MCP: a shape tool's double-click on a selected live shape's corner
|
||||
//! widget, whose gesture's `requests` carry the Transform panel, and a drag on a live polygon's
|
||||
//! side widget.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_tools::corners::CornerWidgets;
|
||||
@@ -28,3 +29,74 @@ fn a_corner_widget_double_click_with_a_shape_tool_requests_the_transform_panel()
|
||||
let off = ok(&mut h, "pointer_gesture", json!({"events": [{"kind": "doubleclick", "x": 280, "y": 280}]}));
|
||||
assert_eq!(off["requests"], json!([]), "{off}");
|
||||
}
|
||||
|
||||
/// The selected live polygon's sides, radius and transform.
|
||||
fn polygon(h: &mut Headless) -> (u32, f64, vectorcraft_geom::Affine) {
|
||||
let st = h.session.doc().unwrap();
|
||||
let id = st.selection.objects[0];
|
||||
let vectorcraft_doc::NodeKind::Path { live, .. } = &st.doc.node(id).unwrap().kind else { panic!("not a path") };
|
||||
let Some(vectorcraft_doc::LiveShape::Polygon { sides, radius, xf, .. }) = live.as_deref() else { panic!("not a live polygon: {live:?}") };
|
||||
(*sides, *radius, *xf)
|
||||
}
|
||||
|
||||
/// A drag down on a live polygon's side widget with the Selection tool gives it more sides in one
|
||||
/// undo step, keeping its radius and transform; undo puts the count back.
|
||||
#[test]
|
||||
fn a_side_widget_drag_changes_a_polygons_sides_in_one_undo_step() {
|
||||
let mut h = Headless::new();
|
||||
h.call("engine.execute", json!({"command": "file.new", "params": {"width": 300, "height": 300}})).unwrap();
|
||||
h.call("engine.execute", json!({"command": "shape.polygon", "params": {"cx": 150, "cy": 150, "radius": 60, "sides": 5}})).unwrap();
|
||||
let st = h.session.doc().unwrap();
|
||||
let id = st.selection.objects[0];
|
||||
let b = st.doc.node(id).unwrap().geometric_bounds_with(&st.doc.symbol_boxes()).expect("bounds");
|
||||
let bx = vectorcraft_doc::OrientedBox::aligned(b);
|
||||
let w = vectorcraft_tools::sidewidget::SideWidget::of(&st.doc, &st.selection, &bx, h.view.zoom).expect("a side widget");
|
||||
let steps = st.history.undo.len();
|
||||
let before = polygon(&mut h);
|
||||
assert_eq!(before.0, 5);
|
||||
let zoom = h.view.zoom;
|
||||
let ev = |kind: &str, dy: f64| json!({"kind": kind, "x": w.at.x, "y": w.at.y + dy / zoom});
|
||||
ok(&mut h, "pointer_gesture", json!({"tool": "selection", "events": [ev("down", 0.0), ev("drag", 13.0), ev("drag", 25.0), ev("up", 25.0)]}));
|
||||
let after = polygon(&mut h);
|
||||
assert_eq!((after.0, after.1, after.2), (7, before.1, before.2));
|
||||
assert_eq!(h.session.doc().unwrap().history.undo.len(), steps + 1, "one undo step");
|
||||
h.call("engine.execute", json!({"command": "edit.undo", "params": {}})).unwrap();
|
||||
assert_eq!(polygon(&mut h), before);
|
||||
// A drag that comes back to the start leaves no undo step.
|
||||
ok(&mut h, "pointer_gesture", json!({"tool": "selection", "events": [ev("down", 0.0), ev("drag", 25.0), ev("drag", 0.0), ev("up", 0.0)]}));
|
||||
assert_eq!(polygon(&mut h), before);
|
||||
assert_eq!(h.session.doc().unwrap().history.undo.len(), steps);
|
||||
}
|
||||
|
||||
/// A batch run during a side widget drag settles the drag first. A batch step that switches
|
||||
/// documents then ends the drag without undoing the batch's own steps in the document it leaves.
|
||||
#[test]
|
||||
fn a_batch_that_switches_documents_during_a_side_widget_drag_keeps_its_steps() {
|
||||
let mut h = Headless::new();
|
||||
for _ in 0..2 {
|
||||
h.call("engine.execute", json!({"command": "file.new", "params": {"width": 300, "height": 300}})).unwrap();
|
||||
}
|
||||
h.call("engine.execute", json!({"command": "shape.polygon", "params": {"cx": 150, "cy": 150, "radius": 60, "sides": 5}})).unwrap();
|
||||
let st = h.session.doc().unwrap();
|
||||
let (uid, id) = (st.uid, st.selection.objects[0]);
|
||||
let b = st.doc.node(id).unwrap().geometric_bounds_with(&st.doc.symbol_boxes()).expect("bounds");
|
||||
let bx = vectorcraft_doc::OrientedBox::aligned(b);
|
||||
let w = vectorcraft_tools::sidewidget::SideWidget::of(&st.doc, &st.selection, &bx, h.view.zoom).expect("a side widget");
|
||||
let steps = st.history.undo.len();
|
||||
let zoom = h.view.zoom;
|
||||
let ev = |kind: &str, dy: f64| json!({"kind": kind, "x": w.at.x, "y": w.at.y + dy / zoom});
|
||||
// The drag stays held: no `up`.
|
||||
ok(&mut h, "pointer_gesture", json!({"tool": "selection", "events": [ev("down", 0.0), ev("drag", 13.0), ev("drag", 25.0)]}));
|
||||
let batch = json!({"commands": [
|
||||
{"command": "shape.rectangle", "params": {"x": 10, "y": 10, "width": 20, "height": 20}},
|
||||
{"command": "document.activate", "params": {"index": 0}}
|
||||
]});
|
||||
h.call("engine.execute", json!({"command": "command.batch", "params": batch})).unwrap();
|
||||
let st = h.session.documents().iter().find(|d| d.uid == uid).expect("the polygon's document");
|
||||
let vectorcraft_doc::NodeKind::Path { live, .. } = &st.doc.node(id).unwrap().kind else { panic!("not a path") };
|
||||
assert!(matches!(live.as_deref(), Some(vectorcraft_doc::LiveShape::Polygon { sides: 7, .. })), "the settled drag: {live:?}");
|
||||
assert_eq!(st.history.undo.len(), steps + 2, "the drag and the batch, each one undo step");
|
||||
let rect = st.selection.objects[0];
|
||||
assert_ne!(rect, id, "the batch's rectangle is selected");
|
||||
assert!(st.doc.node(rect).is_some(), "the batch's rectangle stays");
|
||||
}
|
||||
@@ -8,6 +8,11 @@ fn num(desc: &str) -> Value {
|
||||
json!({"type": "number", "description": desc})
|
||||
}
|
||||
|
||||
/// A number or null.
|
||||
fn num_or_null(desc: &str) -> Value {
|
||||
json!({"description": desc, "anyOf": [{"type": "number"}, {"type": "null"}]})
|
||||
}
|
||||
|
||||
fn string(desc: &str) -> Value {
|
||||
json!({"type": "string", "description": desc})
|
||||
}
|
||||
@@ -466,20 +471,20 @@ pub fn tool_definitions() -> Vec<Value> {
|
||||
tool(
|
||||
"transform",
|
||||
"Transform",
|
||||
"Move, rotate, scale, reflect or shear the selection (or `ids`); several may be combined and run in that order. Angles in degrees (counter-clockwise), scale in %. Scale and reflect act along the selection's bounding box, turned with rotated objects until Reset Bounding Box. `origin` [x,y] defaults to the selection centre; `copy` transforms a copy. A scale, reflect or shear its command refuses returns that error before any step runs, and nothing changes.",
|
||||
"Move, rotate, scale, reflect or shear the selection (or `ids`); several may be combined and run in that order. Angles in degrees (counter-clockwise), scale in %. Scale and reflect act along the selection's bounding box, turned with rotated objects until Reset Bounding Box. `origin` [x,y] defaults to the selection center; `copy` transforms a copy. A scale, reflect or shear its command refuses, or an argument of the wrong type, returns that error before any step runs, and nothing changes.",
|
||||
obj(
|
||||
json!({
|
||||
"ids": {"type": "array", "items": {"type": "integer"}},
|
||||
"dx": num("Move right"),
|
||||
"dy": num("Move down"),
|
||||
"rotate": num("Rotation in degrees counter-clockwise"),
|
||||
"scale": num("Uniform scale in %"),
|
||||
"scaleX": num("Horizontal scale in %"),
|
||||
"scaleY": num("Vertical scale in %"),
|
||||
"reflect": {"type": "string", "enum": ["vertical", "horizontal"]},
|
||||
"shear": num("Shear angle in degrees (horizontal axis: positive moves the top to the right, turning the vertical edges clockwise)"),
|
||||
"origin": {"type": "array", "items": {"type": "number"}, "minItems": 2, "maxItems": 2},
|
||||
"copy": {"type": "boolean"},
|
||||
"dx": num_or_null("Move right (null: 0)"),
|
||||
"dy": num_or_null("Move down (null: 0)"),
|
||||
"rotate": num_or_null("Rotation in degrees counter-clockwise"),
|
||||
"scale": num_or_null("Uniform scale in %"),
|
||||
"scaleX": num_or_null("Horizontal scale in %"),
|
||||
"scaleY": num_or_null("Vertical scale in %"),
|
||||
"reflect": {"anyOf": [{"type": "string", "enum": ["vertical", "horizontal"]}, {"type": "null"}]},
|
||||
"shear": num_or_null("Shear angle in degrees (horizontal axis: positive moves the top to the right, turning the vertical edges clockwise)"),
|
||||
"origin": {"anyOf": [{"type": "array", "items": {"type": "number"}, "minItems": 2, "maxItems": 2}, {"type": "null"}]},
|
||||
"copy": {"anyOf": [{"type": "boolean"}, {"type": "null"}]},
|
||||
}),
|
||||
&[],
|
||||
),
|
||||
|
||||
@@ -303,7 +303,8 @@ pub(super) fn add_text(b: &mut dyn Backend, a: &Args) -> Result<Value, String> {
|
||||
|
||||
pub(super) fn transform(b: &mut dyn Backend, a: &Args) -> Result<Value, String> {
|
||||
// Each operation is its own command: check the params the later ones refuse before the first
|
||||
// runs, so a refused request changes nothing.
|
||||
// runs, so a refused request changes nothing. The `transform` arm of `dispatch` has already
|
||||
// refused a `dx`, `dy`, `rotate`, `scale`, `scaleX`, `scaleY` or `shear` that is not a number.
|
||||
fn bad(cmd: &'static str) -> impl Fn(String) -> String {
|
||||
move |e| format!("invalid parameters for `{cmd}`: {e}")
|
||||
}
|
||||
@@ -312,7 +313,12 @@ pub(super) fn transform(b: &mut dyn Backend, a: &Args) -> Result<Value, String>
|
||||
if sx.is_some() || sy.is_some() {
|
||||
vectorcraft_engine::cmd::scale_factors(sx.unwrap_or(100.0), sy.unwrap_or(100.0)).map_err(bad("object.scale"))?;
|
||||
}
|
||||
let reflect = a.get("reflect").and_then(Value::as_str);
|
||||
// A null `reflect`, `copy` or `origin` is left out.
|
||||
let reflect = match a.get("reflect") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(Value::String(axis)) => Some(axis.as_str()),
|
||||
Some(v) => return Err(format!("invalid parameters for `object.reflect`: axis must be \"vertical\" or \"horizontal\", not `{v}`")),
|
||||
};
|
||||
if let Some(axis) = reflect {
|
||||
vectorcraft_engine::cmd::reflect_axis(Some(&json!(axis))).map_err(bad("object.reflect"))?;
|
||||
}
|
||||
@@ -320,9 +326,18 @@ pub(super) fn transform(b: &mut dyn Backend, a: &Args) -> Result<Value, String>
|
||||
if let Some(sh) = shear {
|
||||
vectorcraft_engine::cmd::shear_tangent(sh).map_err(bad("object.shear"))?;
|
||||
}
|
||||
let copy = match a.get("copy") {
|
||||
None | Some(Value::Null) => false,
|
||||
Some(v) => v.as_bool().ok_or_else(|| format!("`copy` must be true or false, not {v}"))?,
|
||||
};
|
||||
if let Some(o) = a.get("origin").filter(|o| !o.is_null())
|
||||
&& !o.as_array().is_some_and(|xy| xy.len() == 2 && xy.iter().all(Value::is_number))
|
||||
{
|
||||
return Err(format!("`origin` must be [x, y], not {o}"));
|
||||
}
|
||||
select_ids(b, a)?;
|
||||
// With `copy`, the first operation duplicates and the rest transform the copy (the new selection).
|
||||
let copy = std::cell::Cell::new(a.get("copy").and_then(Value::as_bool).unwrap_or(false));
|
||||
let copy = std::cell::Cell::new(copy);
|
||||
let with = |mut p: Value| {
|
||||
if let Some(o) = a.get("origin") {
|
||||
p["origin"] = o.clone();
|
||||
|
||||
@@ -143,6 +143,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"",
|
||||
"{} opens SVG Options; with params = document.export {path?, svg?: {…SVG options}, range?…} (a .svgz path writes it gzipped)",
|
||||
),
|
||||
(
|
||||
"file.export.svg.browser",
|
||||
"Show in Browser",
|
||||
"",
|
||||
"{svg?: {…SVG options}, exportSelection?} SVG Options' Show in Browser: write the SVG of one page (with exportSelection the selection's crop, else the first artboard the options choose) and its linked images to a new temporary folder and open it in the default browser (desktop; refused for control and MCP requests) → {path, warnings}",
|
||||
),
|
||||
(
|
||||
"file.export.png",
|
||||
"Export As PNG…",
|
||||
@@ -688,7 +694,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"window.panel.float",
|
||||
"Float Panel",
|
||||
"",
|
||||
"{panel: id or \"tools\", x?, y?, width?, height?, group?: bool, column?: bool or n, onto?: id, above?: id, below?: id, collapsed?: bool} float a panel (with `group`, its whole group; with `column`, its whole dock column or floating window) as a floating window with its top-left corner at x, y in window points (default: inside the dock area, cascaded), as dragging its tab out does; a whole floating window keeps its rect unless given one. `onto` makes it a tab of the floating group holding that panel instead; `above` / `below` a group of its own above or below the group holding that panel, in its floating window or dock column. `collapsed` then minimizes (true) or restores (false) its window or group. A hidden panel shows first. \"tools\" floats the Tools panel at x, y. Returns {layout, closed, floating}",
|
||||
"{panel: id or \"tools\", x?, y?, width?, height?, group?: bool, column?: bool or n, onto?: id, above?: id, below?: id, collapsed?: bool} float a panel (with `group`, its whole group; with `column`, its whole dock column or floating window) as a floating window with its top-left corner at x, y in window points (default: inside the dock area, cascaded), as dragging its tab out does; a whole floating window keeps its rect unless given one. Supplied geometry also moves or resizes an existing native window; omitted components keep their current values. `onto` makes it a tab of the floating group holding that panel instead; `above` / `below` a group of its own above or below the group holding that panel, in its floating window or dock column. `collapsed` then minimizes (true) or restores (false) its window or group. A hidden panel shows first. \"tools\" floats the Tools panel at x, y. Returns {layout, closed, floating}",
|
||||
),
|
||||
(
|
||||
"window.panel.dock",
|
||||
@@ -871,7 +877,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"",
|
||||
"{effect: id, index?: int (edit that applied effect in place, prefilled; OK runs effect.setParams), item?: appearance item index|null (the fill/stroke whose effects, null the object's; default: the Appearance panel's active item), aligned?: bool (index and item are rows of the first selected object's stack, which OK edits in each object where it has them, as effect.setParams does)} open the effect's dialog with live preview; without `index`, an effect already in that list first opens `effectExists` (confirm edits it, discard adds another) → {pending: \"effectExists\"}",
|
||||
),
|
||||
("ui.paramDialog", "Command Dialog", "", "{command, label?, params} open a parameter dialog for any command"),
|
||||
(
|
||||
"ui.paramDialog",
|
||||
"Command Dialog",
|
||||
"",
|
||||
"{command, label?, params} open a parameter dialog for any command. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed",
|
||||
),
|
||||
(
|
||||
"ui.recolorDialog",
|
||||
"Recolor Artwork…",
|
||||
@@ -1443,7 +1454,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.colorWheel",
|
||||
"Color Wheel Options",
|
||||
"",
|
||||
"{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, and pick the box's channel, as Box Channel does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); keys left out keep their values, params that are not an object, another key or a value off the list are an error and change nothing, both are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel}",
|
||||
"{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, vision?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, and pick the box's channel, as Box Channel does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, vision}",
|
||||
),
|
||||
(
|
||||
"ui.savePdfDialog",
|
||||
|
||||
@@ -85,14 +85,23 @@ pub fn export(doc: &Document, region: Rect, kind: Kind) -> Result<Output, String
|
||||
Ok(export_regions(doc, &[region], kind)?.pop().unwrap_or_default())
|
||||
}
|
||||
|
||||
/// The error [`export_regions`] returns for `regions`, without writing anything: a region whose
|
||||
/// corners are not all finite, or that has no width or no height, is empty. Corners in either
|
||||
/// order are allowed.
|
||||
pub fn check_regions(regions: &[Rect]) -> Result<(), String> {
|
||||
let empty = |r: Rect| ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) || r.width() <= 0.0 || r.height() <= 0.0;
|
||||
if regions.iter().any(|r| empty(r.abs())) {
|
||||
return Err("the export region is empty".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write the visible art of `doc` over each of `regions` as `kind`, one metafile per region in the
|
||||
/// same order, each as [`export`] writes it over that region. The live effects are applied once
|
||||
/// for all of them. When any region is empty, nothing is written and the result is an error.
|
||||
pub fn export_regions(doc: &Document, regions: &[Rect], kind: Kind) -> Result<Vec<Output>, String> {
|
||||
check_regions(regions)?;
|
||||
let regions: Vec<Rect> = regions.iter().map(|r| r.abs()).collect();
|
||||
if regions.iter().any(|r| ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) || r.width() <= 0.0 || r.height() <= 0.0) {
|
||||
return Err("the export region is empty".into());
|
||||
}
|
||||
if regions.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
@@ -8,6 +8,9 @@
|
||||
//! Both are found as roots over the normal's angle: sampled, then refined by bisection, with
|
||||
//! sampled minima refined too so that a double root (outlines that touch) or two roots between
|
||||
//! neighboring samples are kept.
|
||||
//!
|
||||
//! One of the two may be a point instead ([`Outline::point`]): its support value is `p · n`, and
|
||||
//! the tangents are the lines through it that touch the other outline.
|
||||
|
||||
use std::f64::consts::TAU;
|
||||
|
||||
@@ -60,7 +63,7 @@ pub enum OutlineError {
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Coincide;
|
||||
|
||||
/// A convex closed outline that [`common_tangents`] takes.
|
||||
/// A convex closed outline, or a point, that [`common_tangents`] takes.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Outline {
|
||||
/// The unit circle under an affine map: the center is the map's translation, `m` its linear
|
||||
@@ -70,9 +73,19 @@ pub enum Outline {
|
||||
/// when the segments run counter-clockwise (y up); the segment where `p · n` is largest then
|
||||
/// comes later in the list as the angle of `n` grows.
|
||||
Convex { segments: Vec<CubicBez>, center: Point, size: f64, ccw: bool },
|
||||
/// A single point.
|
||||
Point { at: Point },
|
||||
}
|
||||
|
||||
impl Outline {
|
||||
/// The point `at`, whose tangents are the lines through it.
|
||||
pub fn point(at: Point) -> Result<Self, OutlineError> {
|
||||
if !at.x.is_finite() || !at.y.is_finite() {
|
||||
return Err(OutlineError::Empty);
|
||||
}
|
||||
Ok(Outline::Point { at })
|
||||
}
|
||||
|
||||
/// The ellipse that `unit` maps the unit circle onto.
|
||||
pub fn ellipse(unit: Affine) -> Result<Self, OutlineError> {
|
||||
let [a, b, c, d, e, f] = unit.as_coeffs();
|
||||
@@ -183,6 +196,7 @@ impl Outline {
|
||||
size: *size,
|
||||
ccw: *ccw,
|
||||
},
|
||||
Outline::Point { at } => Outline::Point { at: *at + d },
|
||||
}
|
||||
}
|
||||
|
||||
@@ -203,7 +217,7 @@ impl Outline {
|
||||
/// The support value at `n` and the segment it is reached on, from every segment.
|
||||
fn support_scan(&self, n: Vec2) -> (f64, usize) {
|
||||
match self {
|
||||
Outline::Ellipse { .. } => (self.support(n), 0),
|
||||
Outline::Ellipse { .. } | Outline::Point { .. } => (self.support(n), 0),
|
||||
Outline::Convex { segments, .. } => {
|
||||
let mut best = (f64::MIN, 0);
|
||||
for (i, s) in segments.iter().enumerate() {
|
||||
@@ -222,7 +236,7 @@ impl Outline {
|
||||
/// where the support value was reached at a normal angle a little less than `n`'s.
|
||||
fn support_from(&self, n: Vec2, from: usize) -> (f64, usize) {
|
||||
match self {
|
||||
Outline::Ellipse { .. } => (self.support(n), 0),
|
||||
Outline::Ellipse { .. } | Outline::Point { .. } => (self.support(n), 0),
|
||||
Outline::Convex { segments, ccw, .. } => {
|
||||
let len = segments.len();
|
||||
if len == 0 {
|
||||
@@ -251,14 +265,20 @@ impl Outline {
|
||||
}
|
||||
}
|
||||
|
||||
/// The center: an ellipse's, or a path's center of area.
|
||||
/// The center: an ellipse's, a path's center of area, or the point itself.
|
||||
pub fn center(&self) -> Point {
|
||||
match self {
|
||||
Outline::Ellipse { center, .. } | Outline::Convex { center, .. } => *center,
|
||||
Outline::Point { at } => *at,
|
||||
}
|
||||
}
|
||||
|
||||
/// The diagonal of the bounds (an ellipse's: of the box its axes span).
|
||||
/// Whether this is a point.
|
||||
pub fn is_point(&self) -> bool {
|
||||
matches!(self, Outline::Point { .. })
|
||||
}
|
||||
|
||||
/// The diagonal of the bounds (an ellipse's: of the box its axes span; a point's: 0).
|
||||
pub fn size(&self) -> f64 {
|
||||
match self {
|
||||
Outline::Ellipse { m, .. } => {
|
||||
@@ -266,6 +286,7 @@ impl Outline {
|
||||
2.0 * (a.hypot(c).powi(2) + b.hypot(d).powi(2)).sqrt()
|
||||
}
|
||||
Outline::Convex { size, .. } => *size,
|
||||
Outline::Point { .. } => 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -280,6 +301,7 @@ impl Outline {
|
||||
}
|
||||
best
|
||||
}
|
||||
Outline::Point { at } => at.to_vec2().dot(n),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -320,6 +342,7 @@ impl Outline {
|
||||
let Some(&(peak, _)) = all.iter().max_by(|x, y| x.1.total_cmp(&y.1)) else { return vec![] };
|
||||
all.into_iter().filter(|(p, v)| h - v <= tol + slope * (*p - peak).hypot()).map(|(p, _)| p).collect()
|
||||
}
|
||||
Outline::Point { at } => vec![*at],
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -406,7 +429,14 @@ fn dir(angle: f64) -> Vec2 {
|
||||
/// the angle of its normal. Separate outlines have two of each; overlapping ones only external
|
||||
/// ones (two for ellipses, possibly more for paths whose outlines cross more often); one inside the
|
||||
/// other none; outlines that touch share one tangent where they touch.
|
||||
///
|
||||
/// When one of them is a point, its external and internal tangents are the same lines, and they
|
||||
/// come back as external ones: two when the point lies outside the other outline, one when it lies
|
||||
/// on it, none inside. Two points have none.
|
||||
pub fn common_tangents(a: &Outline, b: &Outline) -> Result<Vec<Tangent>, Coincide> {
|
||||
if a.is_point() && b.is_point() {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
// Worked out about the point between the two centers.
|
||||
let origin = (a.center().to_vec2() + b.center().to_vec2()) / 2.0;
|
||||
let (a, b) = (&a.shifted(-origin), &b.shifted(-origin));
|
||||
@@ -434,7 +464,11 @@ pub fn common_tangents(a: &Outline, b: &Outline) -> Result<Vec<Tangent>, Coincid
|
||||
let (ha, hb, hb_back) = (hints(a, 1.0), hints(b, 1.0), hints(b, -1.0));
|
||||
let hint = |h: &[usize], k: usize| h.get(k).copied().unwrap_or(0);
|
||||
let external = roots(&at, &|t, k| a.support_from(dir(t), hint(&ha, k)).0 - b.support_from(dir(t), hint(&hb, k)).0, tol)?;
|
||||
let internal = roots(&at, &|t, k| a.support_from(dir(t), hint(&ha, k)).0 + b.support_from(-dir(t), hint(&hb_back, k)).0, tol)?;
|
||||
let internal = if a.is_point() || b.is_point() {
|
||||
vec![]
|
||||
} else {
|
||||
roots(&at, &|t, k| a.support_from(dir(t), hint(&ha, k)).0 + b.support_from(-dir(t), hint(&hb_back, k)).0, tol)?
|
||||
};
|
||||
let (a, b) = (Hinted { o: a, at: &at, hints: &ha }, Hinted { o: b, at: &at, hints: &hb });
|
||||
let mut out = Vec::with_capacity(external.len() + internal.len());
|
||||
for (kind, list) in [(TangentKind::External, external), (TangentKind::Internal, internal)] {
|
||||
@@ -506,8 +540,13 @@ fn tangent_at(a: &Hinted, b: &Hinted, kind: TangentKind, angle: f64, double: boo
|
||||
// A double root's angle is found less exactly than a simple one's, so touching points may
|
||||
// stand a little apart.
|
||||
let (from, to) = if double && hi - lo <= 1e-6 * size {
|
||||
// Touching at one point: the narrower outline's width along the line, centered there.
|
||||
let width = [a, b].map(|o| o.support(angle + TAU / 4.0).0 + o.support(angle - TAU / 4.0).0).into_iter().fold(f64::MAX, f64::min);
|
||||
// Touching at one point: the narrower outline's width along the line, centered there. A
|
||||
// point on the other outline takes that outline's width.
|
||||
let width = [a, b]
|
||||
.into_iter()
|
||||
.filter(|o| !o.o.is_point())
|
||||
.map(|o| o.support(angle + TAU / 4.0).0 + o.support(angle - TAU / 4.0).0)
|
||||
.fold(f64::MAX, f64::min);
|
||||
let mid = (lo + hi) / 2.0;
|
||||
(mid - width / 2.0, mid + width / 2.0)
|
||||
} else if mean(&on_a) <= mean(&on_b) {
|
||||
@@ -975,6 +1014,127 @@ mod tests {
|
||||
assert!((best - 0.25).abs() < 1e-12, "{best}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_point_outside_a_turned_ellipse_has_two_tangents_through_it() {
|
||||
let m = ellipse_map(100.0, 50.0, 40.0, 15.0, 30.0);
|
||||
let (oval, p) = (Outline::ellipse(m).unwrap(), Point::new(-60.0, 120.0));
|
||||
let samples = sample_ellipse(m, 5_000);
|
||||
for point_first in [true, false] {
|
||||
let point = Outline::point(p).unwrap();
|
||||
let all = if point_first { common_tangents(&point, &oval) } else { common_tangents(&oval, &point) }.unwrap();
|
||||
assert_eq!(all.len(), 2, "{all:?}");
|
||||
for t in &all {
|
||||
assert_eq!(t.kind, TangentKind::External);
|
||||
// Each runs from the first outline given to the second: from the point when it
|
||||
// comes first.
|
||||
let (at_point, on_oval) = if point_first { (t.from, t.to) } else { (t.to, t.from) };
|
||||
assert!((at_point - p).hypot() < 1e-9, "{t:?}");
|
||||
// Taken back to the unit circle, the far end lies on it and the line runs square to
|
||||
// its radius there.
|
||||
let inv = m.inverse();
|
||||
let (q, d) = ((inv * on_oval).to_vec2(), (inv * on_oval) - (inv * at_point));
|
||||
assert!((q.hypot() - 1.0).abs() < 1e-9, "{q:?}");
|
||||
assert!((q.dot(d) / d.hypot()).abs() < 1e-7, "{q:?} {d:?}");
|
||||
// The whole ellipse lies on one side of the line.
|
||||
let dir = on_oval - at_point;
|
||||
let n = Vec2::new(-dir.y, dir.x) / dir.hypot();
|
||||
let side: Vec<f64> = samples.iter().map(|s| (*s - at_point).dot(n)).collect();
|
||||
let (lo, hi) = side.iter().fold((f64::MAX, f64::MIN), |(lo, hi), v| (lo.min(*v), hi.max(*v)));
|
||||
assert!(lo > -1e-6 || hi < 1e-6, "crosses: {lo} .. {hi}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_point_on_inside_and_beside_a_path() {
|
||||
// On a circle: the one tangent there, centered on the point and as long as the circle is
|
||||
// wide.
|
||||
let on = common_tangents(&Outline::point(Point::new(10.0, 0.0)).unwrap(), &circle(0.0, 0.0, 10.0)).unwrap();
|
||||
assert_eq!(on.len(), 1, "{on:?}");
|
||||
assert!(ends_within(&on[0], Point::new(10.0, -10.0), Point::new(10.0, 10.0), 1e-5), "{on:?}");
|
||||
// Inside, and two points: none.
|
||||
assert!(common_tangents(&Outline::point(Point::new(3.0, 4.0)).unwrap(), &circle(0.0, 0.0, 10.0)).unwrap().is_empty());
|
||||
let two = (Outline::point(Point::new(0.0, 0.0)).unwrap(), Outline::point(Point::new(5.0, 0.0)).unwrap());
|
||||
assert!(common_tangents(&two.0, &two.1).unwrap().is_empty());
|
||||
// Beside a square, in line with its bottom side: that tangent covers the whole side, and
|
||||
// the other one touches the corner at (10, 10).
|
||||
let square = SubPath::polyline(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)].map(Point::from), true);
|
||||
let sq = Outline::convex(&square).unwrap();
|
||||
let p = Point::new(20.0, 0.0);
|
||||
let all = common_tangents(&Outline::point(p).unwrap(), &sq).unwrap();
|
||||
assert_eq!(all.len(), 2, "{all:?}");
|
||||
assert!(all.iter().any(|t| ends_at(t, p, Point::new(0.0, 0.0))), "{all:?}");
|
||||
assert!(all.iter().any(|t| ends_at(t, p, Point::new(10.0, 10.0))), "{all:?}");
|
||||
assert!(all.iter().all(|t| (t.from - p).hypot() < 1e-9), "from the point: {all:?}");
|
||||
// On a straight side, off its middle: the one tangent is that side, covered whole.
|
||||
let side = common_tangents(&Outline::point(Point::new(2.0, 0.0)).unwrap(), &sq).unwrap();
|
||||
assert_eq!(side.len(), 1, "{side:?}");
|
||||
assert!(ends_at(&side[0], Point::new(0.0, 0.0), Point::new(10.0, 0.0)), "{side:?}");
|
||||
// At a corner of the square: one line through the corner, at the middle of the directions
|
||||
// that touch there, as long as the square is wide along it.
|
||||
let corner = common_tangents(&Outline::point(Point::new(10.0, 10.0)).unwrap(), &sq).unwrap();
|
||||
assert_eq!(corner.len(), 1, "{corner:?}");
|
||||
// The diagonal is 10√2 long, so each end lies 5√2 from the corner, along (1, -1).
|
||||
assert!(ends_within(&corner[0], Point::new(15.0, 5.0), Point::new(5.0, 15.0), 1e-5), "{corner:?}");
|
||||
// A point that is not finite is refused.
|
||||
assert_eq!(Outline::point(Point::new(f64::NAN, 0.0)).err(), Some(OutlineError::Empty));
|
||||
assert_eq!(Outline::point(Point::new(0.0, f64::INFINITY)).err(), Some(OutlineError::Empty));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_point_placed_on_a_turned_outline_has_one_tangent() {
|
||||
// A point worked out on the outline lies a rounding error inside or outside it, and still
|
||||
// gets the one line there, as long as the outline is wide along it.
|
||||
let one = |p: Point, o: &Outline, samples: &[Point]| {
|
||||
let all = common_tangents(&Outline::point(p).unwrap(), o).unwrap();
|
||||
assert_eq!(all.len(), 1, "{p:?}: {all:?}");
|
||||
// The line runs through the point.
|
||||
let (a, d) = (all[0].from, all[0].to - all[0].from);
|
||||
assert!(d.hypot() > 1.0 && ((p - a).cross(d) / d.hypot()).abs() < 1e-6, "{p:?}: {all:?}");
|
||||
// Its length is the outline's width along it, measured on dense samples.
|
||||
let u = d / d.hypot();
|
||||
let (lo, hi) = samples.iter().map(|s| s.to_vec2().dot(u)).fold((f64::MAX, f64::MIN), |(lo, hi), v| (lo.min(v), hi.max(v)));
|
||||
assert!((d.hypot() - (hi - lo)).abs() < 1e-3, "{p:?}: {} against {}", d.hypot(), hi - lo);
|
||||
};
|
||||
let m = ellipse_map(100.0, 50.0, 40.0, 15.0, 30.0);
|
||||
let (oval, oval_samples) = (Outline::ellipse(m).unwrap(), sample_ellipse(m, 20_000));
|
||||
for k in 0..37 {
|
||||
let a = 0.17 + k as f64 * TAU / 37.0;
|
||||
one(m * Point::new(a.cos(), a.sin()), &oval, &oval_samples);
|
||||
}
|
||||
// A closed Bézier circle, turned and moved: on each anchor and partway along each segment.
|
||||
let turned = shapes::ellipse(Rect::new(-60.0, -60.0, 60.0, 60.0)).transformed(Affine::translate((37.3, -12.9)) * Affine::rotate(0.7));
|
||||
let sp = turned.subpaths[0].clone();
|
||||
let (path, path_samples) = (Outline::convex(&sp).unwrap(), sample_path(&sp, 5_000));
|
||||
for an in sp.anchors.iter() {
|
||||
one(an.p, &path, &path_samples);
|
||||
}
|
||||
for k in 0..sp.segment_count() {
|
||||
for t in [0.21, 0.5, 0.83] {
|
||||
one(sp.segment(k).eval(t), &path, &path_samples);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_point_within_the_touching_tolerance_counts_as_on_the_outline() {
|
||||
// The tolerance is a billionth of the larger of the circle's size and the point's distance
|
||||
// from its center: closer than that, inside or outside, the point gets the one line there.
|
||||
let round = circle(0.0, 0.0, 10.0);
|
||||
let tol = 1e-9 * round.size().max(10.0);
|
||||
let at = |dx: f64| common_tangents(&Outline::point(Point::new(10.0 + dx, 0.0)).unwrap(), &round).unwrap();
|
||||
for dx in [-0.5 * tol, 0.5 * tol] {
|
||||
let on = at(dx);
|
||||
assert_eq!(on.len(), 1, "{dx}: {on:?}");
|
||||
assert!(ends_within(&on[0], Point::new(10.0, -10.0), Point::new(10.0, 10.0), 1e-5), "{dx}: {on:?}");
|
||||
}
|
||||
// Farther than that, a point inside gets none and a point outside gets two.
|
||||
assert!(at(-100.0 * tol).is_empty());
|
||||
assert_eq!(at(100.0 * tol).len(), 2);
|
||||
assert!(at(-1e-6).is_empty());
|
||||
assert_eq!(at(1e-6).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_concave_empty_and_identical_outlines_are_refused() {
|
||||
let open = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0)], false);
|
||||
|
||||
@@ -7,7 +7,7 @@ use std::sync::Arc;
|
||||
|
||||
use vectorcraft_color::cms::{self, Cms, Model, ProfileKind};
|
||||
use vectorcraft_color::swatch::REGISTRATION;
|
||||
use vectorcraft_color::{BlendMode, Color, GradientKind, Paint};
|
||||
use vectorcraft_color::{BlendMode, Color, GradientKind, GradientStop, Paint};
|
||||
use vectorcraft_doc::inks::{Link, StopPlates, inks, plates, spot_color, stop_inks, visit_node_colors};
|
||||
use vectorcraft_doc::overprint::{darken_overprints, is_black_ink, is_white};
|
||||
use vectorcraft_doc::{AppearanceItem, ColorMode, Document, ImageBlob, Node, NodeKind};
|
||||
@@ -175,33 +175,74 @@ impl<'a> Separator<'a> {
|
||||
/// carry counts as none. A link to a swatch the document lacks separates as the color's own
|
||||
/// values, so such a black counts as unlinked.
|
||||
fn no_ink(&self, plate: &str, p: &Paint) -> bool {
|
||||
let process = |swatch: Option<&str>| swatch.is_none_or(|n| n != REGISTRATION && self.doc.swatch(n).is_none_or(|w| !w.spot));
|
||||
let none = |c: &Color, process: bool, ink: f32| ink <= 0.0 || (self.postscript && process && ink <= 0.005 && is_black_ink(c, 1.0, false));
|
||||
match p {
|
||||
Paint::Solid { color, swatch, tint } => {
|
||||
none(color, process(swatch.as_deref()), self.ink(plate, color, swatch.as_deref().map(|s| (s, *tint))))
|
||||
self.none(color, self.process(swatch.as_deref()), self.ink(plate, color, swatch.as_deref().map(|s| (s, *tint))))
|
||||
}
|
||||
Paint::Gradient(g) => match g.freeform.as_ref().filter(|f| g.gradient.kind == GradientKind::Freeform && !f.points.is_empty()) {
|
||||
Some(f) => f.points.iter().all(|pt| none(&pt.color, true, self.ink(plate, &pt.color, None))),
|
||||
None => {
|
||||
!g.gradient.stops.is_empty()
|
||||
&& g.gradient.stops.iter().all(|s| {
|
||||
let ink = self.stop_ink(plate, &s.color, s.swatch.as_deref().map(|n| (n, s.tint)), s.plates);
|
||||
none(&s.color, s.plates.is_none() && process(s.swatch.as_deref()), ink)
|
||||
})
|
||||
}
|
||||
Some(f) => f.points.iter().all(|pt| self.point_none(plate, &pt.color)),
|
||||
None => !g.gradient.stops.is_empty() && g.gradient.stops.iter().all(|s| self.stop_none(plate, s)),
|
||||
},
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a color linked to swatch `swatch` separates as process inks: no link, or a link
|
||||
/// to a process swatch or to one the document lacks, other than Registration.
|
||||
fn process(&self, swatch: Option<&str>) -> bool {
|
||||
swatch.is_none_or(|n| n != REGISTRATION && self.doc.swatch(n).is_none_or(|w| !w.spot))
|
||||
}
|
||||
|
||||
/// Whether `ink` of color `c` (separating as process inks when `process` is true) counts as
|
||||
/// none, as [`Self::no_ink`] says.
|
||||
fn none(&self, c: &Color, process: bool, ink: f32) -> bool {
|
||||
ink <= 0.0 || (self.postscript && process && ink <= 0.005 && is_black_ink(c, 1.0, false))
|
||||
}
|
||||
|
||||
/// Whether gradient stop `s` puts none of ink `plate` down, as [`Self::no_ink`] says.
|
||||
fn stop_none(&self, plate: &str, s: &GradientStop) -> bool {
|
||||
let ink = self.stop_ink(plate, &s.color, s.swatch.as_deref().map(|n| (n, s.tint)), s.plates);
|
||||
self.none(&s.color, s.plates.is_none() && self.process(s.swatch.as_deref()), ink)
|
||||
}
|
||||
|
||||
/// Whether a freeform gradient's point of color `c` puts none of ink `plate` down, as
|
||||
/// [`Self::no_ink`] says.
|
||||
fn point_none(&self, plate: &str, c: &Color) -> bool {
|
||||
self.none(c, true, self.ink(plate, c, None))
|
||||
}
|
||||
|
||||
/// On a PostScript plate, make paper white the stops and points of overprinting gradient `p`
|
||||
/// that put none of ink `plate` down while others do ([`Self::no_ink`]'s rule for each): the
|
||||
/// writer leaves the plate below as it is where the gradient is paper white.
|
||||
fn clear_inkless_stops(&self, plate: &str, p: &mut Paint) {
|
||||
let Paint::Gradient(g) = p else { return };
|
||||
if !self.postscript {
|
||||
return;
|
||||
}
|
||||
let paper = Color::Gray { k: 0.0 };
|
||||
match g.freeform.as_mut().filter(|f| g.gradient.kind == GradientKind::Freeform && !f.points.is_empty()) {
|
||||
Some(f) => {
|
||||
for pt in f.points.iter_mut().filter(|pt| self.point_none(plate, &pt.color)) {
|
||||
pt.color = paper;
|
||||
}
|
||||
}
|
||||
None => {
|
||||
for s in g.gradient.stops.iter_mut().filter(|s| self.stop_none(plate, s)) {
|
||||
*s = GradientStop { color: paper, swatch: None, tint: 1.0, plates: None, ..s.clone() };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Overprinting fills and strokes of `a`'s subtree with a Normal blending mode, and
|
||||
/// overprinting character fills and strokes, that put none of ink `plate` down leave its plate
|
||||
/// as it is: they are drawn as nothing on it (white ones with `discard_white` aside, which
|
||||
/// knock out). A writer without blending modes (PostScript) then keeps the ink below them,
|
||||
/// where it would draw their Darken as a knockout. One that puts any ink down is drawn, and on
|
||||
/// a PostScript plate its ink replaces the ink below, as a nonzero component of an overprinting
|
||||
/// color replaces the backdrop's with overprint mode 1 (ISO 32000-1, 11.7.4.2).
|
||||
/// color replaces the backdrop's with overprint mode 1 (ISO 32000-1, 11.7.4.2). On a
|
||||
/// PostScript plate, the stops and points of such a gradient that put none of the ink down
|
||||
/// become paper white ([`Self::clear_inkless_stops`]), which the writer leaves out there.
|
||||
fn clear_inkless_overprints(&self, plate: &str, a: &mut Arc<Node>, discard_white: bool) {
|
||||
let inkless = |overprint: bool, p: &Paint| overprint && !p.is_none() && !(discard_white && is_white(p)) && self.no_ink(plate, p);
|
||||
let n = Arc::make_mut(a);
|
||||
@@ -212,15 +253,21 @@ impl<'a> Separator<'a> {
|
||||
};
|
||||
if normal && inkless(it.overprint(), it.paint()) {
|
||||
*it.paint_mut() = Paint::None;
|
||||
} else if normal && it.overprint() {
|
||||
self.clear_inkless_stops(plate, it.paint_mut());
|
||||
}
|
||||
}
|
||||
if let NodeKind::Text(t) = &mut n.kind {
|
||||
for r in &mut t.runs {
|
||||
if inkless(r.style.overprint_fill, &r.style.fill) {
|
||||
r.style.fill = Paint::None;
|
||||
} else if r.style.overprint_fill {
|
||||
self.clear_inkless_stops(plate, &mut r.style.fill);
|
||||
}
|
||||
if inkless(r.style.overprint_stroke, &r.style.stroke) {
|
||||
r.style.stroke = Paint::None;
|
||||
} else if r.style.overprint_stroke {
|
||||
self.clear_inkless_stops(plate, &mut r.style.stroke);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -999,6 +999,42 @@ fn overprinting_paints_keep_their_faint_ink_on_postscript_plates() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_near_black_stop_of_an_overprinting_gradient_puts_no_cyan_on_postscript_plates() {
|
||||
// 0.4% cyan beside 100% K counts as black on a PostScript plate stop by stop, as a solid fill
|
||||
// of it does: the cyan plate draws that stop of an overprinting gradient as paper white. A
|
||||
// PDF plate and a gradient that does not overprint keep the 0.4%.
|
||||
let stops = vec![GradientStop::new(0.0, Color::cmyk(0.004, 0.0, 0.0, 1.0)), GradientStop::new(1.0, Color::cmyk(0.5, 0.0, 0.0, 0.0))];
|
||||
let fade = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))));
|
||||
let square = |x: f64, overprint: bool| {
|
||||
let r = shapes::rectangle(Rect::new(x, 15.0, x + 20.0, 35.0));
|
||||
let mut n = Node::path(vectorcraft_doc::NodeId(0), r, Appearance::basic(fade.clone(), Paint::None, 0.0));
|
||||
if let Some(f) = n.appearance.fill_mut() {
|
||||
f.overprint = overprint;
|
||||
}
|
||||
n
|
||||
};
|
||||
let d = over_cyan(vec![square(10.0, true), square(40.0, false)]);
|
||||
// The cyan plate's stops of each gradient, in thousandths of the ink.
|
||||
let stops = |postscript: bool| {
|
||||
let opts = PrintOptions { settings: settings(json!({"output": {"mode": "separations"}})), postscript, ..Default::default() };
|
||||
let p = plan(&d, &opts).unwrap();
|
||||
let mut all = vec![];
|
||||
p.plates[0].walk(|n| {
|
||||
if let Some(Paint::Gradient(g)) = n.appearance.fill().map(|f| &f.paint) {
|
||||
let gray = |s: &GradientStop| match s.color {
|
||||
Color::Gray { k } if s.swatch.is_none() => (k * 1000.0).round(),
|
||||
c => panic!("{c:?}"),
|
||||
};
|
||||
all.push(g.gradient.stops.iter().map(gray).collect::<Vec<_>>());
|
||||
}
|
||||
});
|
||||
all
|
||||
};
|
||||
assert_eq!(stops(true), [[0.0, 500.0], [4.0, 500.0]], "PostScript: the overprinting gradient, the other");
|
||||
assert_eq!(stops(false), [[4.0, 500.0], [4.0, 500.0]], "PDF");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overprinting_type_leaves_the_inks_below_on_separations() {
|
||||
let style = vectorcraft_doc::CharStyle { fill: Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)), ..Default::default() };
|
||||
|
||||
@@ -203,6 +203,21 @@ pub fn quantize_to(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions, pal
|
||||
finish(px, &colors, width, height, &palette, o, o.dither)
|
||||
}
|
||||
|
||||
/// For each pixel of `rgba`, the entry of `palette` nearest its color, as [`quantize_to`] measures
|
||||
/// it (the matte, transparency and `o.reduction`'s distance weights) without dither; `None` for a
|
||||
/// pixel that becomes transparent, and for every pixel when `palette` is empty.
|
||||
pub fn nearest_entries(rgba: &[u8], o: &PaletteOptions, palette: &[[u8; 3]]) -> Vec<Option<usize>> {
|
||||
let px = rgba.as_chunks::<4>().0;
|
||||
let colors = opaque_colors(px, o, false);
|
||||
let pal: Vec<[f32; 3]> = palette.iter().map(|c| c.map(f32::from)).collect();
|
||||
let index = PaletteIndex::new(&pal, o.reduction.weights());
|
||||
colors
|
||||
.iter()
|
||||
.zip(px)
|
||||
.map(|(c, p)| if pal.is_empty() || (o.transparency && p[3] < 128) { None } else { Some(index.nearest(c.map(f32::from))) })
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The color of each pixel when opaque: blended over the matte, and gray when `gray`.
|
||||
fn opaque_colors(px: &[[u8; 4]], o: &PaletteOptions, gray: bool) -> Vec<[u8; 3]> {
|
||||
let matte = o.matte.unwrap_or([255; 3]);
|
||||
|
||||
@@ -80,14 +80,19 @@ fn lossy_makes_runs_and_smaller_gifs() {
|
||||
let px = image(96, 64, |x, y| [(x * 2 + y) as u8, (y * 3) as u8, ((x * y) % 255) as u8]);
|
||||
let ix = quantize(&px, 96, 64, &PaletteOptions { colors: 64, dither: Dither::Diffusion, ..Default::default() });
|
||||
let mut lossy_ix = ix.clone();
|
||||
lossy(&mut lossy_ix, &px, 80);
|
||||
lossy(&mut lossy_ix, &px, 80, &[]);
|
||||
let runs = |ix: &Indexed| ix.indices.windows(2).filter(|w| w[0] != w[1]).count();
|
||||
assert!(runs(&lossy_ix) < runs(&ix));
|
||||
let size = |ix: &Indexed| gif::encode(ix, false).unwrap().len();
|
||||
assert!(size(&lossy_ix) < size(&ix), "{} vs {}", size(&lossy_ix), size(&ix));
|
||||
let mut none = ix.clone();
|
||||
lossy(&mut none, &px, 0);
|
||||
lossy(&mut none, &px, 0, &[]);
|
||||
assert_eq!(none, ix);
|
||||
// A fixed entry keeps its pixels and takes no others.
|
||||
let fixed: Vec<u8> = (0..ix.palette.len()).filter_map(|i| u8::try_from(i).ok()).collect();
|
||||
let mut kept = ix.clone();
|
||||
lossy(&mut kept, &px, 100, &fixed);
|
||||
assert_eq!(kept, ix);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -83,19 +83,24 @@ pub fn to_transparent(ix: &mut Indexed, mapped: impl Fn(usize) -> bool) -> Vec<O
|
||||
|
||||
/// Lossy GIF compression: a pixel takes the entry of the pixel left of it when that entry is
|
||||
/// within `amount` (0–100) of its own colour in `rgba` (the straight pixels it was reduced from).
|
||||
/// Longer runs of one index compress better in a GIF, at the cost of some noise.
|
||||
pub fn lossy(ix: &mut Indexed, rgba: &[u8], amount: u8) {
|
||||
/// Longer runs of one index compress better in a GIF, at the cost of some noise. No pixel moves
|
||||
/// into or out of the transparent entry or an entry in `fixed`.
|
||||
pub fn lossy(ix: &mut Indexed, rgba: &[u8], amount: u8, fixed: &[u8]) {
|
||||
let w = ix.width as usize;
|
||||
if amount == 0 || w == 0 || rgba.len() != ix.indices.len() * 4 {
|
||||
return;
|
||||
}
|
||||
// Up to 64 levels apart in each channel at 100.
|
||||
let limit = (f32::from(amount.min(100)) / 100.0 * 64.0).powi(2) * 3.0;
|
||||
let mut held = [false; 256];
|
||||
for i in fixed.iter().chain(&ix.transparent) {
|
||||
held[usize::from(*i)] = true;
|
||||
}
|
||||
let px = rgba.as_chunks::<4>().0;
|
||||
for (row, src) in ix.indices.chunks_mut(w).zip(px.chunks(w)) {
|
||||
for x in 1..row.len() {
|
||||
let (prev, cur) = (row[x - 1], row[x]);
|
||||
if prev == cur || ix.transparent.is_some_and(|t| t == prev || t == cur) {
|
||||
if prev == cur || held[usize::from(prev)] || held[usize::from(cur)] {
|
||||
continue;
|
||||
}
|
||||
let (Some(c), Some(p)) = (src.get(x), ix.palette.get(prev as usize)) else { continue };
|
||||
|
||||
@@ -64,10 +64,13 @@ use crate::{Frame, Renderer, blend_mode, fill_rule, paint};
|
||||
mod bounds;
|
||||
mod entries;
|
||||
mod pixels;
|
||||
mod placement;
|
||||
mod predicates;
|
||||
mod raster;
|
||||
mod renderer;
|
||||
|
||||
pub use placement::pinned_appearance_for_geometry_edit;
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) use bounds::visual_bounds;
|
||||
pub(crate) use bounds::{
|
||||
|
||||
@@ -726,6 +726,12 @@ fn cull_bounds_in(symbols: &SymbolBoxes, n: &Node, after_reshape: bool, brush: b
|
||||
let a = art_effects_reach(symbols, n);
|
||||
Some(b.inflate(a, a))
|
||||
}
|
||||
// A spine can rotate a blend's keys and steps past their unrotated visual bounds.
|
||||
NodeKind::Blend { .. } => {
|
||||
let b = n.reach_bounds_with(symbols)?;
|
||||
let a = live_content_reach(symbols, n);
|
||||
vectorcraft_geom::union_opt(Some(b.inflate(a, a)), placed_blend_effect_bounds(symbols, n))
|
||||
}
|
||||
_ => {
|
||||
let b = n.visual_bounds_with(symbols)?;
|
||||
let b = match &n.kind {
|
||||
@@ -804,16 +810,43 @@ pub(crate) fn with_own_raster_reach(symbols: &SymbolBoxes, n: &Node, b: Rect) ->
|
||||
b.inflate(o, o)
|
||||
}
|
||||
|
||||
/// `n`'s own visual box, type's grown to hold its glyphs ([`glyphs_box`]): what it draws when its
|
||||
/// object effects leave it as it is (Revolve builds no art from type).
|
||||
/// `n`'s own box, type's grown to hold its glyphs ([`glyphs_box`]) and a blend's to hold its
|
||||
/// spine-placed keys and steps: what it draws when its object effects leave it as it is
|
||||
/// (Revolve builds no art from type).
|
||||
fn own_box(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
|
||||
let b = n.visual_bounds_with(symbols)?;
|
||||
let b = match &n.kind {
|
||||
NodeKind::Blend { .. } => vectorcraft_geom::union_opt(n.reach_bounds_with(symbols), placed_blend_effect_bounds(symbols, n)),
|
||||
_ => n.visual_bounds_with(symbols),
|
||||
}?;
|
||||
Some(match &n.kind {
|
||||
NodeKind::Text(t) => vectorcraft_geom::union_opt(Some(b), glyphs_box(t, n.appearance.outset())).unwrap_or(b),
|
||||
_ => b,
|
||||
})
|
||||
}
|
||||
|
||||
/// A rotated blend's effect-bearing content, measured after spine placement. Geometry effects
|
||||
/// run on the placed shapes, so their reach on the original keys need not cover what they paint.
|
||||
/// Effect-free blends keep the quick rail envelope without evaluating their steps.
|
||||
fn placed_blend_effect_bounds(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
|
||||
let NodeKind::Blend { spec, .. } = &n.kind else { return None };
|
||||
if spec.orientation != vectorcraft_doc::BlendOrientation::AlignToPath {
|
||||
return None;
|
||||
}
|
||||
let mut has_effects = false;
|
||||
n.walk(&mut |c| {
|
||||
has_effects |= has_fx(c)
|
||||
|| has_object_fx(c)
|
||||
|| match &c.kind {
|
||||
NodeKind::SymbolInstance { symbol, .. } => symbols.has_effects(symbol),
|
||||
_ => false,
|
||||
};
|
||||
});
|
||||
if !has_effects {
|
||||
return None;
|
||||
}
|
||||
effects::expand_live(Some(symbols.document()), n).iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, cull_bounds(symbols, c)))
|
||||
}
|
||||
|
||||
/// The box of type `t`'s glyphs as laid out (its layout bounds, else laid out now), grown by its
|
||||
/// characters' strokes, miter spikes included, and by `outset`: on a path they stand above it and
|
||||
/// run past its ends, in an area they can hang past its frame, where its own box
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
//! Stored gradient fits for geometry edits on the renderer's ordinary shape/container paths.
|
||||
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeKind};
|
||||
use vectorcraft_effects::{self as effects, GeomContext};
|
||||
use vectorcraft_geom::{BezPath, Rect, Shape};
|
||||
|
||||
use super::bounds::{apply_carrying, effected_path_carrying, item_effects, node_bezpath};
|
||||
use super::predicates::has_non_container_art_fx;
|
||||
use super::renderer::carried;
|
||||
|
||||
/// Store the current renderer fit of gradients that can be represented by the existing appearance.
|
||||
///
|
||||
/// Alternate materialized art, visible plug-ins, Rasterize and path-coordinate stroke gradients
|
||||
/// keep their existing fit behavior. An unsupported or non-roundtripping carry also leaves its row
|
||||
/// unchanged; this neither flattens art nor changes persisted effects. `None` makes no change.
|
||||
pub fn pinned_appearance_for_geometry_edit(doc: &Document, n: &Node) -> Option<Appearance> {
|
||||
if !n.appearance.has_unplaced_gradient() || unsupported(n) || has_non_container_art_fx(n) {
|
||||
return None;
|
||||
}
|
||||
// Enclosing geometry effects change the fit outside this node-local pass.
|
||||
// Without that context, leave the paint fitted rather than storing a false frame.
|
||||
if doc.ancestry(n.id)?.into_iter().filter(|&id| id != n.id).any(|id| {
|
||||
doc.node(id).is_some_and(|ancestor| {
|
||||
matches!(ancestor.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && effects::has_geometry(&ancestor.appearance.effects)
|
||||
})
|
||||
}) {
|
||||
return None;
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Group { .. } | NodeKind::Layer { .. } => effects::pinned_container_appearance(doc, n),
|
||||
NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => pinned_shape(doc, n),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn rasterizes(fx: &[Effect]) -> bool {
|
||||
fx.iter().any(|effect| effect.visible && effect.id == effects::RASTERIZE)
|
||||
}
|
||||
|
||||
fn unsupported(n: &Node) -> bool {
|
||||
effects::has_plugin_effect(n)
|
||||
|| rasterizes(&n.appearance.effects)
|
||||
|| n.appearance.items.iter().any(|item| {
|
||||
item.visible() && (rasterizes(item.effects()) || matches!(item, AppearanceItem::Stroke(stroke) if stroke.path_gradient().is_some()))
|
||||
})
|
||||
}
|
||||
|
||||
fn unplaced(item: &AppearanceItem) -> bool {
|
||||
item.visible() && matches!(item.paint(), Paint::Gradient(gradient) if !gradient.is_placed())
|
||||
}
|
||||
|
||||
fn pinned_shape(doc: &Document, n: &Node) -> Option<Appearance> {
|
||||
let bp = node_bezpath(n)?;
|
||||
let (geometry, object_carry) = effected_path_carrying(doc, n, &bp);
|
||||
if geometry.elements().is_empty() {
|
||||
return None;
|
||||
}
|
||||
// Share the renderer's actual temporary object carry and skipped-effect flags.
|
||||
let temporary = carried(n, &object_carry);
|
||||
let paints = temporary.as_deref().unwrap_or(n);
|
||||
let context = GeomContext { doc: Some(doc), ..GeomContext::of(paints) };
|
||||
let mut appearance = (*n.appearance).clone();
|
||||
let mut changed = false;
|
||||
for (index, original) in n.appearance.items.iter().enumerate().filter(|(_, item)| unplaced(item)) {
|
||||
// `item` must belong to the same temporary appearance borrowed by `context.item`:
|
||||
// that lookup uses pointer identity to recover the actual row index/seed.
|
||||
let item = paints.appearance.items.get(index)?;
|
||||
let (item_geometry, item_carry) = apply_carrying(item_effects(item), &geometry, &context.item(item));
|
||||
let bounds = item_bounds(item, &geometry, &item_geometry, &item_carry)?;
|
||||
if let Some(pinned) = effects::pinned_gradient_item(original, bounds, &[&object_carry, &item_carry]) {
|
||||
*appearance.items.get_mut(index)? = pinned;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
changed.then_some(appearance)
|
||||
}
|
||||
|
||||
/// The same temporary item carry/skipped flags and `ib` choice as `Renderer::paint_items`.
|
||||
fn item_bounds(item: &AppearanceItem, geometry: &BezPath, item_geometry: &BezPath, carry: &effects::Carry) -> Option<Rect> {
|
||||
let mut appearance = Appearance { items: vec![item.clone()], ..Default::default() };
|
||||
if !carry.is_empty() && matches!(item.paint(), Paint::Gradient(_)) {
|
||||
carry.apply(&mut appearance);
|
||||
}
|
||||
let mut item = appearance.items.pop()?;
|
||||
if carry.skipped() {
|
||||
carry.hide_skipped(item.effects_mut());
|
||||
}
|
||||
Some(if effects::has_geometry(item_effects(&item)) && !item_geometry.elements().is_empty() {
|
||||
item_geometry.bounding_box()
|
||||
} else {
|
||||
geometry.bounding_box()
|
||||
})
|
||||
}
|
||||
@@ -25,11 +25,20 @@ pub(crate) fn has_fx(n: &Node) -> bool {
|
||||
/// effect copies it with a gradient or changes its fills and strokes ([`effects::has_transform_art`]),
|
||||
/// or is it a group or layer with an appearance of its own (see [`Renderer::draw_object_fx`])?
|
||||
pub(crate) fn has_object_fx(n: &Node) -> bool {
|
||||
object_fx(n, true)
|
||||
}
|
||||
|
||||
/// The alternate-art dispatches other than a group or layer's own container appearance.
|
||||
pub(super) fn has_non_container_art_fx(n: &Node) -> bool {
|
||||
object_fx(n, false)
|
||||
}
|
||||
|
||||
fn object_fx(n: &Node, containers: bool) -> bool {
|
||||
(effects::needs_outline(n) && (visible(&n.appearance.effects) || n.projection().is_some()))
|
||||
|| effects::has_item_geometry(n)
|
||||
|| effects::has_instance_row_raster(n)
|
||||
|| effects::has_transform_art(n)
|
||||
|| effects::has_container_appearance(n)
|
||||
|| (containers && effects::has_container_appearance(n))
|
||||
|| effects::has_crop_marks(n)
|
||||
|| effects::addons::halftone::has_halftone(n)
|
||||
|| effects::has_adjustment(n)
|
||||
|
||||
@@ -1029,7 +1029,7 @@ impl Renderer {
|
||||
/// the Transform effects the geometry pass left out hidden ([`effects::Carry::hide_skipped`]), so
|
||||
/// its raster effects and those of its fills and strokes stay with its art; `None` when it stays
|
||||
/// as it is.
|
||||
fn carried(n: &Node, carry: &effects::Carry) -> Option<Arc<Node>> {
|
||||
pub(super) fn carried(n: &Node, carry: &effects::Carry) -> Option<Arc<Node>> {
|
||||
let moves = carry.moves(&n.appearance);
|
||||
(moves || carry.skipped()).then(|| {
|
||||
let mut m = n.clone();
|
||||
|
||||
@@ -43,6 +43,7 @@ use lru::FrameCache;
|
||||
pub use brush_fx::instance_art;
|
||||
pub use changed::{Changed, changed, placed_area, view_pixels};
|
||||
pub use effects::stroke::width_outline;
|
||||
pub use fx::pinned_appearance_for_geometry_edit;
|
||||
pub use images::{IMAGE_CACHE_MAX, image_cache_bytes, installed_memory, newly_undecodable, set_image_cache_budget};
|
||||
pub use live::expand_live;
|
||||
pub use pattern::render_pattern_swatch;
|
||||
|
||||
@@ -9,6 +9,8 @@ description = "VectorCraft text: font database, shaping, layout, glyph outlines"
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
# The shared font catalog from craft-libs main (it has the outline, bidi and caret helpers used here).
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3", default-features = false }
|
||||
vectorcraft-geom = { workspace = true }
|
||||
vectorcraft-doc = { workspace = true }
|
||||
kurbo = { workspace = true }
|
||||
|
||||
@@ -8,7 +8,7 @@ use std::sync::{Arc, Mutex, RwLock};
|
||||
|
||||
use kurbo::BezPath;
|
||||
use skrifa::instance::{Location, LocationRef, Size};
|
||||
use skrifa::outline::{DrawSettings, OutlinePen};
|
||||
use skrifa::outline::OutlinePen;
|
||||
use skrifa::raw::FileRef;
|
||||
use skrifa::string::StringId;
|
||||
use skrifa::{GlyphId, MetadataProvider, Tag};
|
||||
@@ -74,7 +74,7 @@ pub use stylistic_sets::StylisticSet;
|
||||
use traits::Alias;
|
||||
#[cfg(test)]
|
||||
use traits::{FaceKeys, face_names};
|
||||
pub use traits::{FontClass, FontLikeness, FontMatch, FontTraits};
|
||||
pub use traits::{FontClass, FontLikeness, FontMatch, FontTraits, GENERIC_FAMILIES, is_generic_family};
|
||||
#[cfg(test)]
|
||||
pub(crate) use traits::{alias_lists, face_styles, on_faces_published};
|
||||
pub use wanted::{WantedFont, WantedFonts};
|
||||
|
||||
@@ -53,6 +53,25 @@ impl OutlinePen for FlipPen {
|
||||
}
|
||||
}
|
||||
|
||||
// Share font decoding while preserving the app's existing y-down geometry and resource budget.
|
||||
impl craft_font_catalog::GlyphPen for FlipPen {
|
||||
fn move_to(&mut self, x: f32, y: f32) {
|
||||
OutlinePen::move_to(self, x, y);
|
||||
}
|
||||
fn line_to(&mut self, x: f32, y: f32) {
|
||||
OutlinePen::line_to(self, x, y);
|
||||
}
|
||||
fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
|
||||
OutlinePen::quad_to(self, x1, y1, x, y);
|
||||
}
|
||||
fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
|
||||
OutlinePen::curve_to(self, x1, y1, x2, y2, x, y);
|
||||
}
|
||||
fn close(&mut self) {
|
||||
OutlinePen::close(self);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -10,10 +10,7 @@ use super::names::{norm, norm_chars, script_families};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::scan::{enumerate_faces, font_files};
|
||||
use super::traits::{Alias, FontMatch, FontTraits, regular_rank};
|
||||
use super::{
|
||||
Arc, BezPath, CANONICAL_CACHE_MAX, Color, ColourContent, DrawSettings, FontDb, GlyphId, GlyphImage, MetadataProvider, NEXT_ID, OUTLINE_CACHE_MAX,
|
||||
Ordering, Size,
|
||||
};
|
||||
use super::{Arc, BezPath, CANONICAL_CACHE_MAX, Color, ColourContent, FontDb, GlyphImage, MetadataProvider, NEXT_ID, OUTLINE_CACHE_MAX, Ordering};
|
||||
|
||||
/// The most faces [`FontDb::postscript_faces`] gives, and the most families it loads.
|
||||
const MAX_POSTSCRIPT_FACES: usize = 16;
|
||||
@@ -368,6 +365,12 @@ impl FontDb {
|
||||
loaded.or_else(|| self.instance_by_id(id))
|
||||
}
|
||||
|
||||
/// The faces loaded so far (the bundled fonts and the installed ones type has used), in load
|
||||
/// order. Installed fonts that nothing has asked for yet are not among them.
|
||||
pub fn loaded_faces(&self) -> Vec<Arc<FontFace>> {
|
||||
self.read_faces().clone()
|
||||
}
|
||||
|
||||
/// The face of character style `st`: [`Self::face_version`] of its font, instanced at its
|
||||
/// Variable Font settings ([`Self::instance`]).
|
||||
pub fn style_face(&self, st: &vectorcraft_doc::CharStyle) -> Option<Arc<FontFace>> {
|
||||
@@ -654,13 +657,7 @@ impl FontDb {
|
||||
if let Some(p) = self.outlines.lock().unwrap_or_else(|e| e.into_inner()).get(&key) {
|
||||
return p.clone();
|
||||
}
|
||||
let mut pen = FlipPen(BezPath::new());
|
||||
if let Some(f) = face.skrifa()
|
||||
&& let Some(g) = f.outline_glyphs().get(GlyphId::new(gid))
|
||||
{
|
||||
let _ = g.draw(DrawSettings::unhinted(Size::unscaled(), face.location()), &mut pen);
|
||||
}
|
||||
let p = Arc::new(pen.0);
|
||||
let p = Arc::new(self.outline_uncached(face, gid));
|
||||
let mut cache = self.outlines.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if cache.len() >= OUTLINE_CACHE_MAX {
|
||||
cache.clear();
|
||||
@@ -669,6 +666,17 @@ impl FontDb {
|
||||
p
|
||||
}
|
||||
|
||||
/// [`Self::outline`] without the cache: for reading many glyphs once (Retype's index), which
|
||||
/// would otherwise push out the outlines the canvas keeps there.
|
||||
pub fn outline_uncached(&self, face: &FontFace, gid: u32) -> BezPath {
|
||||
let mut pen = FlipPen(BezPath::new());
|
||||
if let Ok(font) = craft_font_catalog::FontOutline::from_bytes(face.data(), face.index(), face.variations()) {
|
||||
// As before, keep the prefix emitted before a malformed glyph reports an error.
|
||||
let _ = font.draw_to(gid, &mut pen);
|
||||
}
|
||||
pen.0
|
||||
}
|
||||
|
||||
/// Glyph `gid`'s colour bitmap (`sbix`, `CBDT`) in `face`, cached per (face, glyph).
|
||||
pub fn glyph_image(&self, face: &FontFace, gid: u32) -> Option<Arc<GlyphImage>> {
|
||||
if !face.colour_bitmaps {
|
||||
@@ -722,3 +730,89 @@ impl FontDb {
|
||||
content
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod shared_outline_tests {
|
||||
use super::super::glyph_pen::FlipPen;
|
||||
use super::*;
|
||||
use skrifa::instance::Size;
|
||||
use skrifa::outline::DrawSettings;
|
||||
use skrifa::{GlyphId, MetadataProvider};
|
||||
|
||||
#[test]
|
||||
fn shared_outlines_match_original_pen_for_variable_instances() {
|
||||
let db = FontDb::with_font_dirs(vec![]);
|
||||
let Some(bytes) = crate::test_fonts::variable_font() else { return };
|
||||
assert!(db.add_font(bytes) > 0);
|
||||
let face = db.face(crate::test_fonts::VARIABLE_FAMILY, "Bold").expect("named instance is registered");
|
||||
let f = face.skrifa().expect("font parses");
|
||||
for ch in ['A', 'V', ' ', 'a'] {
|
||||
let Some(glyph) = f.charmap().map(ch) else { continue };
|
||||
let mut old = FlipPen(BezPath::new());
|
||||
if let Some(outline) = f.outline_glyphs().get(GlyphId::new(glyph.to_u32())) {
|
||||
// Match the prior production behavior, including a partial path on error.
|
||||
let _ = outline.draw(DrawSettings::unhinted(Size::unscaled(), face.location()), &mut old);
|
||||
}
|
||||
assert_eq!(*db.outline(&face, glyph.to_u32()), old.0, "glyph {ch}");
|
||||
}
|
||||
}
|
||||
|
||||
// Generated CFF keeps the differential tests independent of installed fonts.
|
||||
fn cff_font(program: &[u8]) -> Vec<u8> {
|
||||
let mut cff = vec![1, 0, 4, 4, 0, 1, 1, 1, 2, b'X', 0, 1, 1, 1, 7, 29, 0, 0, 0, 25, 17, 0, 0, 0, 0];
|
||||
cff.extend_from_slice(&[0, 1, 4]);
|
||||
cff.extend_from_slice(&1u32.to_be_bytes());
|
||||
cff.extend_from_slice(&((program.len() as u32) + 1).to_be_bytes());
|
||||
cff.extend_from_slice(program);
|
||||
let mut builder = write_fonts::FontBuilder::new();
|
||||
let mut head = vec![0; 54];
|
||||
head[18..20].copy_from_slice(&1000u16.to_be_bytes());
|
||||
let mut hhea = vec![0; 36];
|
||||
hhea[34..36].copy_from_slice(&1u16.to_be_bytes());
|
||||
for (tag, data) in [(b"head", head), (b"hhea", hhea), (b"hmtx", vec![0, 100, 0, 0]), (b"maxp", vec![0, 0, 0x50, 0, 0, 1]), (b"CFF ", cff)] {
|
||||
builder.add_raw(write_fonts::types::Tag::new(tag), data);
|
||||
}
|
||||
builder.build()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_cff_prefix_matches_original_pen() {
|
||||
let bytes = cff_font(&[139, 139, 21, 239, 139, 5, 10, 14]);
|
||||
let gid = 0;
|
||||
let f = skrifa::FontRef::new(&bytes).unwrap();
|
||||
let mut old = FlipPen(BezPath::new());
|
||||
let result = f
|
||||
.outline_glyphs()
|
||||
.get(GlyphId::new(gid))
|
||||
.unwrap()
|
||||
.draw(DrawSettings::unhinted(Size::unscaled(), skrifa::instance::LocationRef::default()), &mut old);
|
||||
assert!(result.is_err());
|
||||
assert!(!old.0.elements().is_empty());
|
||||
let shared = craft_font_catalog::FontOutline::from_bytes(&bytes, 0, &[]).unwrap();
|
||||
let mut streamed = FlipPen(BezPath::new());
|
||||
assert!(shared.draw_to(gid, &mut streamed).is_err());
|
||||
assert_eq!(streamed.0, old.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_valid_outline_matches_original_pen() {
|
||||
let mut program = vec![139, 139, 21];
|
||||
for _ in 0..100_001 {
|
||||
program.extend_from_slice(&[140, 6]);
|
||||
}
|
||||
program.push(14);
|
||||
let bytes = cff_font(&program);
|
||||
let f = skrifa::FontRef::new(&bytes).unwrap();
|
||||
let mut old = FlipPen(BezPath::new());
|
||||
f.outline_glyphs()
|
||||
.get(GlyphId::new(0))
|
||||
.unwrap()
|
||||
.draw(DrawSettings::unhinted(Size::unscaled(), skrifa::instance::LocationRef::default()), &mut old)
|
||||
.unwrap();
|
||||
assert!(old.0.elements().len() > 100_000);
|
||||
let shared = craft_font_catalog::FontOutline::from_bytes(&bytes, 0, &[]).unwrap();
|
||||
let mut streamed = FlipPen(BezPath::new());
|
||||
shared.draw_to(0, &mut streamed).unwrap();
|
||||
assert_eq!(streamed.0, old.0);
|
||||
}
|
||||
}
|
||||
@@ -433,6 +433,29 @@ impl FontMatch {
|
||||
}
|
||||
}
|
||||
|
||||
/// The CSS generic font families (CSS Fonts Module Level 4), which SVG and HTML files name in place
|
||||
/// of a font and no font file provides; compared in any ASCII case ([`is_generic_family`]). The
|
||||
/// list leaves out `fangsong`, which is also the family name of a Chinese font (FangSong).
|
||||
pub const GENERIC_FAMILIES: &[&str] = &[
|
||||
"serif",
|
||||
"sans-serif",
|
||||
"monospace",
|
||||
"cursive",
|
||||
"fantasy",
|
||||
"system-ui",
|
||||
"ui-serif",
|
||||
"ui-sans-serif",
|
||||
"ui-monospace",
|
||||
"ui-rounded",
|
||||
"math",
|
||||
"emoji",
|
||||
];
|
||||
|
||||
/// Whether `family` (surrounding spaces ignored) is one of the [`GENERIC_FAMILIES`], in any ASCII case.
|
||||
pub fn is_generic_family(family: &str) -> bool {
|
||||
GENERIC_FAMILIES.iter().any(|g| g.eq_ignore_ascii_case(family.trim()))
|
||||
}
|
||||
|
||||
/// A face's (family, style) names.
|
||||
pub(super) fn face_names(f: &skrifa::FontRef<'_>) -> Option<(String, String)> {
|
||||
let family = name(f, &[StringId::TYPOGRAPHIC_FAMILY_NAME, StringId::FAMILY_NAME])?;
|
||||
|
||||
+16
-24
@@ -62,30 +62,22 @@ fn continues_cluster(prev: Option<&SGlyph>, g: Option<&SGlyph>) -> bool {
|
||||
/// ([`upright_extent`]) as a share of `upright`, the length in font units its own width runs down.
|
||||
/// Empty for a glyph of one character.
|
||||
fn ligature_carets(text: &str, g: &SGlyph, rtl: bool, upright: Option<f64>) -> Vec<(usize, f64)> {
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
let Some(s) = text.get(g.byte..g.byte + g.len).filter(|_| g.len > 1) else { return Vec::new() };
|
||||
let starts: Vec<usize> = s.grapheme_indices(true).skip(1).map(|(i, _)| g.byte + i).collect();
|
||||
if starts.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let parts = starts.len() + 1;
|
||||
let from_font = if let Some(length) = upright {
|
||||
let (cell, top) = upright_extent(g);
|
||||
g.face
|
||||
.vertical_ligature_carets(g.gid, starts.len(), top, cell)
|
||||
.filter(|c| c.len() == starts.len() && length > 0.0)
|
||||
.map(|c| c.into_iter().map(|d| d / length).collect::<Vec<f64>>())
|
||||
.filter(|c| c.iter().all(|f| *f > 0.0 && *f < 1.0))
|
||||
} else {
|
||||
let advance = g.face.advance(g.gid);
|
||||
g.face
|
||||
.ligature_carets(g.gid, starts.len())
|
||||
.filter(|c| c.len() == starts.len() && advance > 0.0)
|
||||
.map(|c| c.into_iter().map(|x| if rtl { 1.0 - x / advance } else { x / advance }).collect::<Vec<f64>>())
|
||||
};
|
||||
let mut at = from_font.unwrap_or_else(|| (1..parts).map(|j| j as f64 / parts as f64).collect());
|
||||
at.sort_by(f64::total_cmp);
|
||||
starts.into_iter().zip(at).collect()
|
||||
craft_font_catalog::ligature_caret_stops(text, g.byte, g.len, |count| {
|
||||
if let Some(length) = upright {
|
||||
let (cell, top) = upright_extent(g);
|
||||
g.face
|
||||
.vertical_ligature_carets(g.gid, count, top, cell)
|
||||
.filter(|c| c.len() == count && length > 0.0)
|
||||
.map(|c| c.into_iter().map(|d| d / length).collect::<Vec<f64>>())
|
||||
.filter(|c| c.iter().all(|f| *f > 0.0 && *f < 1.0))
|
||||
} else {
|
||||
let advance = g.face.advance(g.gid);
|
||||
g.face
|
||||
.ligature_carets(g.gid, count)
|
||||
.filter(|c| c.len() == count && advance > 0.0)
|
||||
.map(|c| c.into_iter().map(|x| if rtl { 1.0 - x / advance } else { x / advance }).collect::<Vec<f64>>())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Does glyph `g`, standing upright in vertical type, take a cell of its own down the column? Every
|
||||
|
||||
@@ -81,34 +81,9 @@ pub(super) fn visual_order(bidi: Option<&BidiInfo<'_>>, paragraph_start: usize,
|
||||
return vec![];
|
||||
}
|
||||
let levels = bidi.reordered_levels(para, line.start.saturating_sub(paragraph_start)..line.end.saturating_sub(paragraph_start));
|
||||
// A list marker (length 0) is a cluster of its own.
|
||||
let mut clusters: Vec<Range<usize>> = Vec::new();
|
||||
for (i, g) in glyphs.iter().enumerate() {
|
||||
if i > 0 && glyphs.get(i - 1).is_some_and(|p| p.byte == g.byte && (p.len == 0) == (g.len == 0)) {
|
||||
if let Some(c) = clusters.last_mut() {
|
||||
c.end = i + 1;
|
||||
}
|
||||
} else {
|
||||
clusters.push(i..i + 1);
|
||||
}
|
||||
}
|
||||
// A list marker is at the paragraph's level, and at a right-to-left one its tab is drawn
|
||||
// before (left of) its characters.
|
||||
let cluster_levels: Vec<_> = clusters
|
||||
.iter()
|
||||
.filter_map(|c| glyphs.get(c.start))
|
||||
.map(|g| if g.len == 0 { g.level } else { levels.get(g.byte.saturating_sub(paragraph_start)).copied().unwrap_or(g.level) })
|
||||
.collect();
|
||||
let reversed = |i: usize| glyphs.get(clusters.get(i).map_or(0, |c| c.start)).is_some_and(|g| g.len == 0 && g.level.is_rtl());
|
||||
unicode_bidi::BidiInfo::reorder_visual(&cluster_levels)
|
||||
.into_iter()
|
||||
.filter_map(|i| clusters.get(i).map(|c| (c.clone(), reversed(i))))
|
||||
.flat_map(|(c, rev)| {
|
||||
let mut v: Vec<usize> = c.collect();
|
||||
if rev {
|
||||
v.reverse();
|
||||
}
|
||||
v
|
||||
})
|
||||
.collect()
|
||||
craft_font_catalog::visual_order(
|
||||
glyphs.iter().map(|g| craft_font_catalog::VisualGlyph { byte: g.byte, len: g.len, level: g.level }),
|
||||
paragraph_start,
|
||||
&levels,
|
||||
)
|
||||
}
|
||||
@@ -458,24 +458,8 @@ pub(super) fn break_line(
|
||||
line_end: &[f64],
|
||||
fits: Option<&dyn Fn(usize, bool) -> bool>,
|
||||
) -> (usize, bool) {
|
||||
// The line ending at `chosen`, once it holds a tab, when it fits as drawn; otherwise the latest
|
||||
// of the legal `breaks` before it that fits as drawn, measuring at most `checks` of them from
|
||||
// the latest back and bisecting the earlier ones without a hyphen; the first of them when none
|
||||
// of those measured fits.
|
||||
let settle = |tabbed: bool, checks: usize, chosen: (usize, bool), breaks: &[(usize, bool)]| -> (usize, bool) {
|
||||
let Some(fits) = fits.filter(|_| tabbed) else { return chosen };
|
||||
if fits(chosen.0, chosen.1) {
|
||||
return chosen;
|
||||
}
|
||||
let earlier = breaks.get(breaks.partition_point(|b| b.0 <= i)..breaks.partition_point(|b| b.0 < chosen.0)).unwrap_or_default();
|
||||
if let Some(&b) = earlier.iter().rev().take(checks).find(|b| fits(b.0, b.1)) {
|
||||
return b;
|
||||
}
|
||||
// Without a hyphen, a line that ends later is drawn no narrower, so those breaks bisect.
|
||||
let rest = earlier.get(..earlier.len().saturating_sub(checks)).unwrap_or_default();
|
||||
let plain: Vec<&(usize, bool)> = rest.iter().filter(|b| !b.1).collect();
|
||||
let fitting = plain.partition_point(|b| fits(b.0, b.1));
|
||||
fitting.checked_sub(1).and_then(|k| plain.get(k).copied()).or(earlier.first()).copied().unwrap_or(chosen)
|
||||
let settle = |tabbed: bool, checks: usize, chosen: (usize, bool), breaks: &[(usize, bool)]| {
|
||||
craft_font_catalog::settle_line_break(tabbed, checks, i, chosen, breaks, fits)
|
||||
};
|
||||
// How many breaks a line measures as drawn one by one.
|
||||
let checks = |back: f64| if back > 0.0 { MAX_DRAWN_CHECKS_STEPPING_BACK } else { MAX_DRAWN_CHECKS };
|
||||
|
||||
@@ -26,6 +26,7 @@ mod justify;
|
||||
mod kashida;
|
||||
mod kept;
|
||||
mod layout;
|
||||
pub mod retype;
|
||||
mod shape;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod suitcase;
|
||||
@@ -41,10 +42,10 @@ pub use features::{
|
||||
EXTRA_FEATURES, LIGATURE_TRACKING_LIMITS, MAX_FEATURE_VALUE, MAX_STYLE_FEATURES, OtFeatures, explicit_ligatures, ligatures_suppressed_by,
|
||||
};
|
||||
pub use fontdb::{
|
||||
CompositeCoverage, FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontLikeness, FontMatch, FontTraits, GlyphAlternate, GlyphCategory,
|
||||
GlyphCategoryKind, GlyphOrigin, IcfMargins, JoiningPosition, LentCompositeFonts, PlatformFontFiles, RECENTLY_ADDED_WITHIN, RecentlyAdded,
|
||||
StylisticSet, Substitution, SubstitutionKind, WantedFont, WantedFonts, app_font_dir, is_font_file, is_suitcase, set_app_font_dir,
|
||||
set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined, style_weight, system_font_dirs, user_font_dirs,
|
||||
CompositeCoverage, FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontLikeness, FontMatch, FontTraits, GENERIC_FAMILIES, GlyphAlternate,
|
||||
GlyphCategory, GlyphCategoryKind, GlyphOrigin, IcfMargins, JoiningPosition, LentCompositeFonts, PlatformFontFiles, RECENTLY_ADDED_WITHIN,
|
||||
RecentlyAdded, StylisticSet, Substitution, SubstitutionKind, WantedFont, WantedFonts, app_font_dir, is_font_file, is_generic_family, is_suitcase,
|
||||
set_app_font_dir, set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined, style_weight, system_font_dirs, user_font_dirs,
|
||||
};
|
||||
pub use hyphen::{hyphenation_exceptions, set_hyphenation_exceptions};
|
||||
pub use layout::{envelope_ink, layout_inputs, register_envelope_ink};
|
||||
|
||||
@@ -0,0 +1,911 @@
|
||||
//! Retype's glyph matching (Type › Retype, #4934): which glyph of which loaded font an outlined
|
||||
//! glyph's shape is, the same up to uniform scale, rotation and translation.
|
||||
//!
|
||||
//! Phase 1 is exact matching only. Each contour is read from a starting corner that does not
|
||||
//! depend on where the path happens to start (the corner farthest from the shape's corners'
|
||||
//! centre; every such corner is tried when several tie), with straight edges split in two read as
|
||||
//! one. Points sampled at equal steps of arc length along the contours shortlist the glyphs whose
|
||||
//! best similarity transform (a Procrustes fit) leaves a tiny leftover distance, and the whole
|
||||
//! outline, turned onto the shape, must then lie on it. That holds for outlines made from a font
|
||||
//! the app has (Create Outlines' output, and other apps' that keep each glyph's contours whole and
|
||||
//! in the font's order). Near matches (other versions of a font, hinted or simplified outlines,
|
||||
//! faux styles, glyphs merged into one path) are left unmatched; fuzzy identification is phase 2.
|
||||
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
use std::sync::Arc;
|
||||
|
||||
use kurbo::{Affine, BezPath, CubicBez, Line, ParamCurve, ParamCurveArclen, ParamCurveNearest, PathEl, PathSeg, Point, QuadBez, Shape};
|
||||
|
||||
use crate::{FontDb, FontFace};
|
||||
|
||||
/// At most this many faces are indexed.
|
||||
pub const MAX_FACES: usize = 96;
|
||||
/// At most this many encoded characters of one face are indexed (in code point order).
|
||||
pub const MAX_GLYPHS_PER_FACE: usize = 65_536;
|
||||
/// At most this many glyphs are indexed in all: faces past it are left out.
|
||||
pub const MAX_GLYPHS: usize = 262_144;
|
||||
/// Shapes with more path elements than this are not matched.
|
||||
pub const MAX_ELEMENTS: usize = 4096;
|
||||
/// Shapes (and glyphs) with more contours than this are not matched.
|
||||
const MAX_CONTOURS: usize = 48;
|
||||
/// Points sampled along each contour.
|
||||
const SAMPLES: usize = 32;
|
||||
/// The most readings of a shape (one per choice of tied starting corners) that are tried.
|
||||
const MAX_VARIANTS: usize = 64;
|
||||
/// The largest leftover distance (root mean square over the samples) for a match, as a fraction of
|
||||
/// the shape's spread about its centre.
|
||||
const TOLERANCE: f64 = 2e-3;
|
||||
/// How far the whole outline, turned onto the shape, may lie from it (both ways), as a fraction of
|
||||
/// the shape's spread.
|
||||
const OUTLINE_TOLERANCE: f64 = 5e-3;
|
||||
/// Points of a flattened outline past which the whole-outline check gives up (and so rejects).
|
||||
const MAX_OUTLINE_POINTS: usize = 8192;
|
||||
/// Points along an outline past which the whole-outline check gives up (and so rejects).
|
||||
const MAX_CHECKED_POINTS: usize = 65_536;
|
||||
/// The most glyphs one shape is reported to be ([`RetypeIndex::matches`]).
|
||||
pub const MAX_CANDIDATES: usize = 16;
|
||||
/// How far apart two shapes' spread-to-length ratios may be and still be compared.
|
||||
const INVARIANT_SLACK: f64 = 0.02;
|
||||
|
||||
/// One glyph an outlined shape matched.
|
||||
#[derive(Clone)]
|
||||
pub struct GlyphMatch {
|
||||
pub face: Arc<FontFace>,
|
||||
pub gid: u32,
|
||||
/// The character the face's cmap maps to the glyph (the lowest, when several do).
|
||||
pub ch: char,
|
||||
/// Document units per font unit: the font size is `scale` × units per em.
|
||||
pub scale: f64,
|
||||
/// The glyph's turn, radians (as [`kurbo::Affine::rotate`] turns).
|
||||
pub angle: f64,
|
||||
/// Where the glyph's origin (its baseline start) lies.
|
||||
pub origin: Point,
|
||||
/// The leftover distance, relative to the shape's spread.
|
||||
pub residual: f64,
|
||||
/// How many contours the glyph has.
|
||||
pub contours: usize,
|
||||
/// Other poses the glyph fits the shape in equally (a glyph that looks the same turned).
|
||||
pub alts: Vec<Pose>,
|
||||
}
|
||||
|
||||
/// Where and how a glyph lies: its size, turn and origin.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Pose {
|
||||
/// Document units per font unit.
|
||||
pub scale: f64,
|
||||
/// Radians, as [`kurbo::Affine::rotate`] turns.
|
||||
pub angle: f64,
|
||||
/// Where the glyph's origin lies.
|
||||
pub origin: Point,
|
||||
}
|
||||
|
||||
impl GlyphMatch {
|
||||
/// This match in each pose it fits: its own first, then [`Self::alts`].
|
||||
pub fn poses(&self) -> impl Iterator<Item = GlyphMatch> + '_ {
|
||||
let own = Pose { scale: self.scale, angle: self.angle, origin: self.origin };
|
||||
std::iter::once(own).chain(self.alts.iter().copied()).map(move |p| GlyphMatch {
|
||||
scale: p.scale,
|
||||
angle: p.angle,
|
||||
origin: p.origin,
|
||||
..self.clone()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A shape reduced for matching: points along each contour, centred.
|
||||
struct Signature {
|
||||
contours: usize,
|
||||
/// Centred points, [`SAMPLES`] per contour.
|
||||
pts: Vec<Point>,
|
||||
centre: Point,
|
||||
/// Root mean square distance of the points from the centre.
|
||||
spread: f64,
|
||||
/// `spread` / the total contour length: unchanged by scale, turn and move.
|
||||
invariant: f64,
|
||||
}
|
||||
|
||||
struct Entry {
|
||||
face: usize,
|
||||
gid: u32,
|
||||
ch: char,
|
||||
sig: Signature,
|
||||
/// The glyph's outline in font units, for the whole-outline check.
|
||||
outline: BezPath,
|
||||
}
|
||||
|
||||
/// The glyphs of a set of faces, ready to match shapes against.
|
||||
#[derive(Default)]
|
||||
pub struct RetypeIndex {
|
||||
faces: Vec<Arc<FontFace>>,
|
||||
entries: Vec<Entry>,
|
||||
/// Entry indices by contour count, sorted by invariant.
|
||||
buckets: HashMap<usize, Vec<usize>>,
|
||||
}
|
||||
|
||||
impl RetypeIndex {
|
||||
/// Index the outline glyphs of `faces` (the first [`MAX_FACES`], each face once) whose
|
||||
/// [`shape_key`] is in `keys` (the selected shapes' keys): the others could match no shape, so
|
||||
/// they are not sampled. Outlines are read past the shared outline cache, which keeps the
|
||||
/// canvas's glyphs.
|
||||
pub fn build(db: &FontDb, faces: impl IntoIterator<Item = Arc<FontFace>>, keys: &BTreeSet<u64>) -> Self {
|
||||
let mut kept: Vec<Arc<FontFace>> = vec![];
|
||||
for f in faces {
|
||||
if kept.len() >= MAX_FACES {
|
||||
break;
|
||||
}
|
||||
if !kept.iter().any(|k| k.id() == f.id()) {
|
||||
kept.push(f);
|
||||
}
|
||||
}
|
||||
let mut entries = vec![];
|
||||
'faces: for (fi, face) in kept.iter().enumerate() {
|
||||
for &(gid, ch, key) in face_keys(db, face).iter() {
|
||||
// The budget holds inside a face too: no glyph is sampled past it.
|
||||
if entries.len() >= MAX_GLYPHS {
|
||||
break 'faces;
|
||||
}
|
||||
if !keys.contains(&key) {
|
||||
continue;
|
||||
}
|
||||
let outline = db.outline_uncached(face, gid);
|
||||
if let Some(sig) = signatures(&outline, false).into_iter().next() {
|
||||
entries.push(Entry { face: fi, gid, ch, sig, outline });
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut buckets: HashMap<usize, Vec<usize>> = HashMap::new();
|
||||
for (i, e) in entries.iter().enumerate() {
|
||||
buckets.entry(e.sig.contours).or_default().push(i);
|
||||
}
|
||||
for list in buckets.values_mut() {
|
||||
list.sort_by(|a, b| {
|
||||
let (x, y) = (entries.get(*a).map_or(0.0, |e| e.sig.invariant), entries.get(*b).map_or(0.0, |e| e.sig.invariant));
|
||||
x.total_cmp(&y)
|
||||
});
|
||||
}
|
||||
RetypeIndex { faces: kept, entries, buckets }
|
||||
}
|
||||
|
||||
/// The faces indexed.
|
||||
pub fn faces(&self) -> &[Arc<FontFace>] {
|
||||
&self.faces
|
||||
}
|
||||
|
||||
/// How many glyphs are indexed.
|
||||
pub fn len(&self) -> usize {
|
||||
self.entries.len()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.entries.is_empty()
|
||||
}
|
||||
|
||||
/// The glyphs `shape` (in document space) is: every glyph that fits it exactly, upright ones
|
||||
/// first, then the closest; empty when it is no glyph of the indexed faces. One shape can be
|
||||
/// several glyphs: an L, and a turned L (U+A780) turned half round; a u, and an n upside down.
|
||||
/// A glyph that looks the same turned (an I, an O, a hyphen) also fits in more than one pose:
|
||||
/// the upright-most comes first and the others are kept in [`GlyphMatch::alts`]. The line
|
||||
/// around the shape chooses among them. At most [`MAX_CANDIDATES`].
|
||||
pub fn matches(&self, shape: &BezPath) -> Vec<GlyphMatch> {
|
||||
let variants = signatures(shape, true);
|
||||
let Some(first) = variants.first() else { return vec![] };
|
||||
let Some(list) = self.buckets.get(&first.contours) else { return vec![] };
|
||||
let lo = first.invariant * (1.0 - INVARIANT_SLACK);
|
||||
let hi = first.invariant * (1.0 + INVARIANT_SLACK);
|
||||
let start = list.partition_point(|i| self.entries.get(*i).is_some_and(|e| e.sig.invariant < lo));
|
||||
let tol = first.spread * OUTLINE_TOLERANCE;
|
||||
// The shape flattened for the whole-outline check, once, when a glyph first gets that far.
|
||||
let mut shape_flat: Option<Option<Flat>> = None;
|
||||
let mut out: Vec<(usize, GlyphMatch)> = vec![];
|
||||
for i in list.iter().skip(start) {
|
||||
let Some(e) = self.entries.get(*i) else { continue };
|
||||
if e.sig.invariant > hi {
|
||||
break;
|
||||
}
|
||||
let Some(face) = self.faces.get(e.face) else { continue };
|
||||
// Each reading of the shape (its tied starting corners) that fits the glyph is a pose.
|
||||
let mut poses: Vec<(Pose, f64)> = vec![];
|
||||
for sig in &variants {
|
||||
let Some((z, residual)) = fit(&e.sig, sig) else { continue };
|
||||
if residual > TOLERANCE {
|
||||
continue;
|
||||
}
|
||||
// The glyph's origin is (0, 0) in font units: it lands at centre − z·glyph centre.
|
||||
let gc = mul(z, e.sig.centre);
|
||||
let pose = Pose { scale: z.0.hypot(z.1), angle: z.1.atan2(z.0), origin: Point::new(sig.centre.x - gc.x, sig.centre.y - gc.y) };
|
||||
if poses.iter().any(|(p, _)| wrapped(p.angle - pose.angle).abs() < 1e-6) {
|
||||
continue;
|
||||
}
|
||||
// The samples can step over a detail (a notch between two of them): the whole
|
||||
// outline, turned onto the shape, must lie on it.
|
||||
let flat = shape_flat.get_or_insert_with(|| Flat::new(shape, tol));
|
||||
let Some(flat) = flat.as_ref() else { break };
|
||||
let onto = Affine::new([z.0, z.1, -z.1, z.0, pose.origin.x, pose.origin.y]);
|
||||
if !Flat::new(&(onto * e.outline.clone()), tol).is_some_and(|g| g.agrees(flat)) {
|
||||
continue;
|
||||
}
|
||||
poses.push((pose, residual));
|
||||
}
|
||||
// The upright-most pose first.
|
||||
poses.sort_by(|a, b| wrapped(a.0.angle).abs().total_cmp(&wrapped(b.0.angle).abs()));
|
||||
let Some(((pose, _), rest)) = poses.split_first() else { continue };
|
||||
let residual = poses.iter().map(|(_, r)| *r).fold(f64::INFINITY, f64::min);
|
||||
let m = GlyphMatch {
|
||||
face: face.clone(),
|
||||
gid: e.gid,
|
||||
ch: e.ch,
|
||||
scale: pose.scale,
|
||||
angle: pose.angle,
|
||||
origin: pose.origin,
|
||||
residual,
|
||||
contours: e.sig.contours,
|
||||
alts: rest.iter().map(|(p, _)| *p).collect(),
|
||||
};
|
||||
out.push((e.face, m));
|
||||
}
|
||||
let upright = |m: &GlyphMatch| wrapped(m.angle).abs() >= 1e-3;
|
||||
out.sort_by(|a, b| {
|
||||
upright(&a.1).cmp(&upright(&b.1)).then(a.1.residual.total_cmp(&b.1.residual)).then(a.0.cmp(&b.0)).then(a.1.ch.cmp(&b.1.ch))
|
||||
});
|
||||
out.truncate(MAX_CANDIDATES);
|
||||
out.into_iter().map(|(_, m)| m).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// `a` wrapped into −π..π.
|
||||
fn wrapped(a: f64) -> f64 {
|
||||
(a + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI
|
||||
}
|
||||
|
||||
/// A face's glyphs as the index looks them up: (glyph, character, [`shape_key`]), one per glyph
|
||||
/// under the lowest character that maps to it.
|
||||
type FaceKeys = Arc<Vec<(u32, char, u64)>>;
|
||||
|
||||
/// How many glyph keys [`face_keys`] keeps in all (16 bytes each).
|
||||
const KEPT_KEYS: usize = 1 << 20;
|
||||
|
||||
/// The faces' keys [`face_keys`] keeps, for the database generation they were read in.
|
||||
#[derive(Default)]
|
||||
struct KeptKeys {
|
||||
generation: u64,
|
||||
glyphs: usize,
|
||||
faces: HashMap<(u64, u32), FaceKeys>,
|
||||
}
|
||||
|
||||
/// [`FaceKeys`] of `face`, worked out once per face (each glyph drawn once, past the outline
|
||||
/// cache) and kept: a later Retype samples only the glyphs whose key a selected shape has. Keys
|
||||
/// already kept stay while new faces' keys would not fit, so a run over more faces than fit still
|
||||
/// finds the same ones kept the next time; they are let go when fonts are added or rescanned.
|
||||
fn face_keys(db: &FontDb, face: &FontFace) -> FaceKeys {
|
||||
static KEPT: std::sync::OnceLock<std::sync::Mutex<KeptKeys>> = std::sync::OnceLock::new();
|
||||
let kept = KEPT.get_or_init(Default::default);
|
||||
let at = (db.id(), face.id());
|
||||
let generation = db.generation();
|
||||
{
|
||||
let mut k = kept.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if k.generation != generation {
|
||||
*k = KeptKeys { generation, ..Default::default() };
|
||||
}
|
||||
if let Some(keys) = k.faces.get(&at) {
|
||||
return keys.clone();
|
||||
}
|
||||
}
|
||||
let mut by_gid: HashMap<u32, char> = HashMap::new();
|
||||
for &(c, gid) in face.mapped_chars().iter().take(MAX_GLYPHS_PER_FACE) {
|
||||
if c.is_whitespace() || c.is_control() || is_shape_symbol(c) {
|
||||
continue;
|
||||
}
|
||||
by_gid.entry(gid).and_modify(|e| *e = (*e).min(c)).or_insert(c);
|
||||
}
|
||||
let mut gids: Vec<(u32, char)> = by_gid.into_iter().collect();
|
||||
gids.sort_unstable();
|
||||
let keys: FaceKeys = Arc::new(gids.into_iter().filter_map(|(gid, ch)| Some((gid, ch, shape_key(&db.outline_uncached(face, gid))?))).collect());
|
||||
let mut k = kept.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if k.generation != generation {
|
||||
return keys;
|
||||
}
|
||||
// Another Retype may have worked them out meanwhile: keep and charge one list.
|
||||
if let Some(already) = k.faces.get(&at) {
|
||||
return already.clone();
|
||||
}
|
||||
if k.glyphs + keys.len() <= KEPT_KEYS {
|
||||
k.glyphs += keys.len();
|
||||
k.faces.insert(at, keys.clone());
|
||||
}
|
||||
keys
|
||||
}
|
||||
|
||||
/// Characters whose glyphs are plain shapes (box drawing, blocks, geometric shapes, legacy
|
||||
/// computing symbols) or a font's own icons (private use): a drawn rectangle or circle is the same
|
||||
/// shape as one of them, so matching them would turn art into text. They are not matched.
|
||||
fn is_shape_symbol(c: char) -> bool {
|
||||
matches!(
|
||||
u32::from(c),
|
||||
0x2500..=0x25FF | 0x2B00..=0x2BFF | 0x1F780..=0x1F7FF | 0x1FB00..=0x1FBFF | 0xE000..=0xF8FF | 0xF0000..=0x10FFFF
|
||||
)
|
||||
}
|
||||
|
||||
/// Complex multiply: `z` (a scaled turn) applied to `p`.
|
||||
fn mul(z: (f64, f64), p: Point) -> Point {
|
||||
Point::new(z.0 * p.x - z.1 * p.y, z.1 * p.x + z.0 * p.y)
|
||||
}
|
||||
|
||||
/// The scaled turn `z` that best takes glyph `g`'s points onto shape `s`'s (both centred), and the
|
||||
/// leftover distance relative to the shape's spread; `None` for degenerate shapes.
|
||||
fn fit(g: &Signature, s: &Signature) -> Option<((f64, f64), f64)> {
|
||||
if g.pts.len() != s.pts.len() || g.pts.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let (mut re, mut im, mut gg) = (0.0, 0.0, 0.0);
|
||||
for (a, b) in g.pts.iter().zip(&s.pts) {
|
||||
// Σ s · conj(g)
|
||||
re += b.x * a.x + b.y * a.y;
|
||||
im += b.y * a.x - b.x * a.y;
|
||||
gg += a.x * a.x + a.y * a.y;
|
||||
}
|
||||
if gg <= 0.0 || !gg.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let z = (re / gg, im / gg);
|
||||
let mut res = 0.0;
|
||||
for (a, b) in g.pts.iter().zip(&s.pts) {
|
||||
let p = mul(z, *a);
|
||||
res += (p.x - b.x).powi(2) + (p.y - b.y).powi(2);
|
||||
}
|
||||
let n = s.pts.len() as f64;
|
||||
let rel = (res / n).sqrt() / s.spread;
|
||||
rel.is_finite().then_some((z, rel))
|
||||
}
|
||||
|
||||
/// An outline flattened for the whole-outline check: its segments, points along them (every
|
||||
/// corner, and points twice `tol` apart between corners: a detail narrower than that has corners
|
||||
/// of its own), and a uniform grid listing each segment under every cell its box, grown by `tol`,
|
||||
/// touches, so whether a point lies within `tol` of the outline is asked of the few segments
|
||||
/// around it.
|
||||
struct Flat {
|
||||
segs: Vec<(Point, Point)>,
|
||||
pts: Vec<Point>,
|
||||
origin: Point,
|
||||
cell: f64,
|
||||
cols: usize,
|
||||
rows: usize,
|
||||
/// Segment indices per cell, row by row.
|
||||
cells: Vec<Vec<u32>>,
|
||||
tol: f64,
|
||||
}
|
||||
|
||||
impl Flat {
|
||||
/// Cells along the longer side, at most.
|
||||
const MAX_SIDE: f64 = 48.0;
|
||||
/// Segment listings in all, at most: past it (or past [`MAX_OUTLINE_POINTS`] segments or
|
||||
/// [`MAX_CHECKED_POINTS`] points), `None`, and so no match.
|
||||
const MAX_LISTINGS: usize = 1 << 18;
|
||||
|
||||
fn new(path: &BezPath, tol: f64) -> Option<Flat> {
|
||||
if !tol.is_finite() || tol <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let mut segs = vec![];
|
||||
let (mut start, mut last) = (Point::ZERO, Point::ZERO);
|
||||
let mut too_many = false;
|
||||
kurbo::flatten(path.iter(), tol / 2.0, |el| {
|
||||
if segs.len() > MAX_OUTLINE_POINTS {
|
||||
too_many = true;
|
||||
return;
|
||||
}
|
||||
match el {
|
||||
PathEl::MoveTo(q) => (start, last) = (q, q),
|
||||
PathEl::LineTo(q) => {
|
||||
segs.push((last, q));
|
||||
last = q;
|
||||
}
|
||||
PathEl::ClosePath => {
|
||||
segs.push((last, start));
|
||||
last = start;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
});
|
||||
if too_many {
|
||||
return None;
|
||||
}
|
||||
let mut pts = vec![];
|
||||
for (s, e) in &segs {
|
||||
let steps = (s.distance(*e) / (2.0 * tol)).ceil();
|
||||
if !steps.is_finite() || pts.len() as f64 + steps > MAX_CHECKED_POINTS as f64 {
|
||||
return None;
|
||||
}
|
||||
let steps = (steps as usize).max(1);
|
||||
pts.extend((0..steps).map(|i| s.lerp(*e, i as f64 / steps as f64)));
|
||||
}
|
||||
let (first, _) = segs.first()?;
|
||||
let mut bb = kurbo::Rect::from_points(*first, *first);
|
||||
for (s, e) in &segs {
|
||||
bb = bb.union_pt(*s).union_pt(*e);
|
||||
}
|
||||
let bb = bb.inflate(tol, tol);
|
||||
let cell = (bb.width().max(bb.height()) / Self::MAX_SIDE).max(2.0 * tol);
|
||||
if !cell.is_finite() || cell <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let at = |v: f64, o: f64| (((v - o) / cell).floor().max(0.0) as usize).min(Self::MAX_SIDE as usize);
|
||||
let (cols, rows) = (at(bb.x1, bb.x0) + 1, at(bb.y1, bb.y0) + 1);
|
||||
let mut cells: Vec<Vec<u32>> = vec![vec![]; cols * rows];
|
||||
let mut listings = 0usize;
|
||||
for (i, (s, e)) in segs.iter().enumerate() {
|
||||
let r = kurbo::Rect::from_points(*s, *e).inflate(tol, tol);
|
||||
for cy in at(r.y0, bb.y0)..=at(r.y1, bb.y0).min(rows - 1) {
|
||||
for cx in at(r.x0, bb.x0)..=at(r.x1, bb.x0).min(cols - 1) {
|
||||
listings += 1;
|
||||
if listings > Self::MAX_LISTINGS {
|
||||
return None;
|
||||
}
|
||||
if let Some(c) = cells.get_mut(cy * cols + cx) {
|
||||
c.push(u32::try_from(i).ok()?);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(Flat { segs, pts, origin: Point::new(bb.x0, bb.y0), cell, cols, rows, cells, tol })
|
||||
}
|
||||
|
||||
/// Does `p` lie within `tol` of a segment?
|
||||
fn near(&self, p: Point) -> bool {
|
||||
let (fx, fy) = ((p.x - self.origin.x) / self.cell, (p.y - self.origin.y) / self.cell);
|
||||
if !(fx >= 0.0 && fy >= 0.0) || fx >= self.cols as f64 || fy >= self.rows as f64 {
|
||||
return false;
|
||||
}
|
||||
let (cx, cy) = (fx as usize, fy as usize);
|
||||
let tol2 = self.tol * self.tol;
|
||||
self.cells.get(cy * self.cols + cx).is_some_and(|list| {
|
||||
list.iter().filter_map(|i| self.segs.get(*i as usize)).any(|(s, e)| Line::new(*s, *e).nearest(p, 1e-9).distance_sq <= tol2)
|
||||
})
|
||||
}
|
||||
|
||||
/// Do the two outlines lie on each other: every point of each within `tol` of the other?
|
||||
fn agrees(&self, other: &Flat) -> bool {
|
||||
self.pts.iter().all(|p| other.near(*p)) && other.pts.iter().all(|p| self.near(*p))
|
||||
}
|
||||
}
|
||||
|
||||
/// Do outlines `a` and `b` (in one space) lie on each other: every point of each, flattened, within
|
||||
/// `tol` of the other? `false` when either is too large to check.
|
||||
#[cfg(test)]
|
||||
fn outlines_agree(a: &BezPath, b: &BezPath, tol: f64) -> bool {
|
||||
matches!((Flat::new(a, tol), Flat::new(b, tol)), (Some(fa), Some(fb)) if fa.agrees(&fb))
|
||||
}
|
||||
|
||||
/// `seg` as a line when it is one (a curve with its handles on its ends or on its line), else as it is.
|
||||
fn as_line(seg: PathSeg) -> PathSeg {
|
||||
let on_line = |a: Point, b: Point, p: Point| {
|
||||
let ab = b - a;
|
||||
let len = ab.hypot();
|
||||
len > 0.0 && (ab.cross(p - a)).abs() <= len * len * 1e-12 && (p - a).dot(ab) >= 0.0 && (p - b).dot(ab) <= 0.0
|
||||
};
|
||||
match seg {
|
||||
PathSeg::Quad(q) if q.p1 == q.p0 || q.p1 == q.p2 || on_line(q.p0, q.p2, q.p1) => PathSeg::Line(Line::new(q.p0, q.p2)),
|
||||
PathSeg::Cubic(c) if (c.p1 == c.p0 || on_line(c.p0, c.p3, c.p1)) && (c.p2 == c.p3 || on_line(c.p0, c.p3, c.p2)) => {
|
||||
PathSeg::Line(Line::new(c.p0, c.p3))
|
||||
}
|
||||
s => s,
|
||||
}
|
||||
}
|
||||
|
||||
/// Lines `a` then `b` run on in one direction: one edge split in two.
|
||||
fn runs_on(a: &PathSeg, b: &PathSeg) -> bool {
|
||||
let (PathSeg::Line(a), PathSeg::Line(b)) = (a, b) else { return false };
|
||||
let (u, v) = (a.p1 - a.p0, b.p1 - b.p0);
|
||||
let (lu, lv) = (u.hypot(), v.hypot());
|
||||
lu > 0.0 && lv > 0.0 && u.cross(v).abs() <= lu * lv * 1e-9 && u.dot(v) > 0.0
|
||||
}
|
||||
|
||||
/// `path`'s contours as segments, the closing line included, read the same however the path was
|
||||
/// written: segments that go nowhere are dropped, curves that are straight read as lines, and a
|
||||
/// straight edge split in two (around the start too) reads as one. `None` past the size caps.
|
||||
fn contours(path: &BezPath) -> Option<Vec<Vec<PathSeg>>> {
|
||||
if path.elements().len() > MAX_ELEMENTS {
|
||||
return None;
|
||||
}
|
||||
let mut out: Vec<Vec<PathSeg>> = vec![];
|
||||
let mut cur: Vec<PathSeg> = vec![];
|
||||
let (mut start, mut last) = (Point::ZERO, Point::ZERO);
|
||||
let push = |cur: &mut Vec<PathSeg>, seg: PathSeg| {
|
||||
let seg = as_line(seg);
|
||||
if seg.start() == seg.end() && matches!(seg, PathSeg::Line(_)) {
|
||||
return;
|
||||
}
|
||||
match cur.last_mut() {
|
||||
Some(prev) if runs_on(prev, &seg) => *prev = PathSeg::Line(Line::new(prev.start(), seg.end())),
|
||||
_ => cur.push(seg),
|
||||
}
|
||||
};
|
||||
let flush = |cur: &mut Vec<PathSeg>, start: Point, last: Point, out: &mut Vec<Vec<PathSeg>>| {
|
||||
if last.distance(start) > 0.0 {
|
||||
push(cur, PathSeg::Line(Line::new(last, start)));
|
||||
}
|
||||
// An edge split at the contour's start: its two halves are the last and first segments.
|
||||
if cur.len() > 1
|
||||
&& let (Some(l), Some(f)) = (cur.last().copied(), cur.first().copied())
|
||||
&& runs_on(&l, &f)
|
||||
{
|
||||
cur.pop();
|
||||
if let Some(first) = cur.first_mut() {
|
||||
*first = PathSeg::Line(Line::new(l.start(), f.end()));
|
||||
}
|
||||
}
|
||||
if !cur.is_empty() {
|
||||
out.push(std::mem::take(cur));
|
||||
}
|
||||
};
|
||||
for el in path.elements() {
|
||||
match *el {
|
||||
PathEl::MoveTo(p) => {
|
||||
flush(&mut cur, start, last, &mut out);
|
||||
start = p;
|
||||
last = p;
|
||||
}
|
||||
PathEl::LineTo(p) => {
|
||||
push(&mut cur, PathSeg::Line(Line::new(last, p)));
|
||||
last = p;
|
||||
}
|
||||
PathEl::QuadTo(a, p) => {
|
||||
push(&mut cur, PathSeg::Quad(QuadBez::new(last, a, p)));
|
||||
last = p;
|
||||
}
|
||||
PathEl::CurveTo(a, b, p) => {
|
||||
push(&mut cur, PathSeg::Cubic(CubicBez::new(last, a, b, p)));
|
||||
last = p;
|
||||
}
|
||||
PathEl::ClosePath => {
|
||||
flush(&mut cur, start, last, &mut out);
|
||||
last = start;
|
||||
}
|
||||
}
|
||||
if out.len() > MAX_CONTOURS {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
flush(&mut cur, start, last, &mut out);
|
||||
(out.len() <= MAX_CONTOURS).then_some(out)
|
||||
}
|
||||
|
||||
/// A cheap key two shapes share when one is the other scaled, turned and moved: how many segments
|
||||
/// each of its contours has, in order, as [`contours`] reads them, hashed. Glyphs whose key no
|
||||
/// selected shape has are not sampled. `None` past the size caps or for an empty shape.
|
||||
pub fn shape_key(path: &BezPath) -> Option<u64> {
|
||||
let cs = contours(path)?;
|
||||
if cs.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// FNV-1a over the counts: equal keys for equal counts; a rare clash only samples a glyph more.
|
||||
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
for n in std::iter::once(cs.len()).chain(cs.iter().map(Vec::len)) {
|
||||
for b in (n as u64).to_le_bytes() {
|
||||
h ^= u64::from(b);
|
||||
h = h.wrapping_mul(0x0000_0100_0000_01b3);
|
||||
}
|
||||
}
|
||||
Some(h)
|
||||
}
|
||||
|
||||
/// `path` read for matching: one reading per choice of starting corners (the corner of each contour
|
||||
/// farthest from the centre of all the shape's corners; every tied corner when `all_ties`, else the
|
||||
/// first), at most [`MAX_VARIANTS`] tried. Empty for a shape with nothing to match.
|
||||
fn signatures(path: &BezPath, all_ties: bool) -> Vec<Signature> {
|
||||
let bounds = path.bounding_box();
|
||||
let size = bounds.width().hypot(bounds.height());
|
||||
if !size.is_finite() || size <= 0.0 {
|
||||
return vec![];
|
||||
}
|
||||
let accuracy = size * 1e-6;
|
||||
let Some(cs) = contours(path) else { return vec![] };
|
||||
// Each contour with length, with its segments' lengths.
|
||||
let cs: Vec<(Vec<PathSeg>, Vec<f64>)> = cs
|
||||
.into_iter()
|
||||
.map(|c| {
|
||||
let lens: Vec<f64> = c.iter().map(|s| s.arclen(accuracy)).collect();
|
||||
(c, lens)
|
||||
})
|
||||
.filter(|(_, lens)| {
|
||||
let len: f64 = lens.iter().sum();
|
||||
len.is_finite() && len > size * 1e-9
|
||||
})
|
||||
.collect();
|
||||
let corners: Vec<Point> = cs.iter().flat_map(|(c, _)| c.iter().map(|s| s.start())).collect();
|
||||
if corners.is_empty() {
|
||||
return vec![];
|
||||
}
|
||||
let n = corners.len() as f64;
|
||||
let mid = Point::new(corners.iter().map(|p| p.x).sum::<f64>() / n, corners.iter().map(|p| p.y).sum::<f64>() / n);
|
||||
// Each contour's starting corners: those farthest from `mid`, ties within a hair.
|
||||
let starts: Vec<Vec<usize>> = cs
|
||||
.iter()
|
||||
.map(|(c, _)| {
|
||||
let d: Vec<f64> = c.iter().map(|s| s.start().distance(mid)).collect();
|
||||
let far = d.iter().copied().fold(0.0, f64::max);
|
||||
let tied: Vec<usize> = d.iter().enumerate().filter(|(_, v)| **v >= far - size * 1e-7).map(|(i, _)| i).collect();
|
||||
if all_ties { tied } else { tied.into_iter().take(1).collect() }
|
||||
})
|
||||
.collect();
|
||||
let mut out = vec![];
|
||||
let mut pick = vec![0usize; cs.len()];
|
||||
// Readings tried, kept or not: a shape whose readings all fail (its sums run past what f64
|
||||
// holds) tries no more than this either.
|
||||
let mut tried = 0usize;
|
||||
loop {
|
||||
if tried >= MAX_VARIANTS {
|
||||
break;
|
||||
}
|
||||
tried += 1;
|
||||
if let Some(sig) = sample(&cs, &starts, &pick, accuracy) {
|
||||
out.push(sig);
|
||||
}
|
||||
// The next choice of tied corners (a counter in mixed radix).
|
||||
let mut i = 0;
|
||||
loop {
|
||||
let Some((p, s)) = pick.get_mut(i).zip(starts.get(i)) else { return out };
|
||||
*p += 1;
|
||||
if *p < s.len() {
|
||||
break;
|
||||
}
|
||||
*p = 0;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// One reading of the contours `cs`, contour `i` starting at segment `starts[i][pick[i]]`.
|
||||
fn sample(cs: &[(Vec<PathSeg>, Vec<f64>)], starts: &[Vec<usize>], pick: &[usize], accuracy: f64) -> Option<Signature> {
|
||||
let mut pts = Vec::with_capacity(cs.len() * SAMPLES);
|
||||
let mut total = 0.0;
|
||||
for (((c, lens), s), p) in cs.iter().zip(starts).zip(pick) {
|
||||
let from = *s.get(*p)?;
|
||||
let m = c.len();
|
||||
let len: f64 = lens.iter().sum();
|
||||
total += len;
|
||||
let (mut k, mut before) = (0usize, 0.0);
|
||||
let at_k = |k: usize| (from + k) % m;
|
||||
for j in 0..SAMPLES {
|
||||
let at = len * j as f64 / SAMPLES as f64;
|
||||
while k + 1 < m && before + lens.get(at_k(k)).copied().unwrap_or(0.0) < at {
|
||||
before += lens.get(at_k(k)).copied().unwrap_or(0.0);
|
||||
k += 1;
|
||||
}
|
||||
let (Some(seg), Some(l)) = (c.get(at_k(k)), lens.get(at_k(k))) else { return None };
|
||||
let t = if *l > 0.0 { seg.inv_arclen((at - before).clamp(0.0, *l), accuracy) } else { 0.0 };
|
||||
pts.push(seg.eval(t));
|
||||
}
|
||||
}
|
||||
if pts.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let n = pts.len() as f64;
|
||||
let centre = Point::new(pts.iter().map(|p| p.x).sum::<f64>() / n, pts.iter().map(|p| p.y).sum::<f64>() / n);
|
||||
for p in &mut pts {
|
||||
*p = Point::new(p.x - centre.x, p.y - centre.y);
|
||||
}
|
||||
let spread = (pts.iter().map(|p| p.x * p.x + p.y * p.y).sum::<f64>() / n).sqrt();
|
||||
if !spread.is_finite() || spread <= 0.0 || !total.is_finite() || total <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
Some(Signature { contours: cs.len(), pts, centre, spread, invariant: spread / total })
|
||||
}
|
||||
|
||||
/// The first reading of `path` (for tests).
|
||||
#[cfg(test)]
|
||||
fn signature(path: &BezPath) -> Option<Signature> {
|
||||
signatures(path, false).into_iter().next()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn letter() -> BezPath {
|
||||
// A hand-made "P"-like shape: an outer contour and a counter.
|
||||
let mut p = BezPath::new();
|
||||
p.move_to((0.0, 0.0));
|
||||
p.line_to((0.0, -700.0));
|
||||
p.curve_to((300.0, -700.0), (450.0, -600.0), (450.0, -480.0));
|
||||
p.quad_to((450.0, -300.0), (120.0, -300.0));
|
||||
p.line_to((120.0, 0.0));
|
||||
p.close_path();
|
||||
p.move_to((120.0, -600.0));
|
||||
p.line_to((120.0, -400.0));
|
||||
p.quad_to((330.0, -400.0), (330.0, -500.0));
|
||||
p.quad_to((330.0, -600.0), (120.0, -600.0));
|
||||
p.close_path();
|
||||
p
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shape_matches_itself_scaled_turned_and_moved() {
|
||||
let g = signature(&letter()).unwrap();
|
||||
let xf = Affine::translate((300.0, 200.0)) * Affine::rotate(0.4) * Affine::scale(0.024);
|
||||
let s = signature(&(xf * letter())).unwrap();
|
||||
let (z, res) = fit(&g, &s).unwrap();
|
||||
assert!(res < 1e-6, "{res}");
|
||||
assert!((z.0.hypot(z.1) - 0.024).abs() < 1e-9);
|
||||
assert!((z.1.atan2(z.0) - 0.4).abs() < 1e-9);
|
||||
let origin = s.centre - mul(z, g.centre).to_vec2();
|
||||
assert!(origin.distance(Point::new(300.0, 200.0)) < 1e-6, "{origin:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_written_as_curves_still_match() {
|
||||
// Paths store lines as cubics with handles on their anchors, or the closing line explicitly.
|
||||
let mut alt = BezPath::new();
|
||||
alt.move_to((0.0, 0.0));
|
||||
alt.curve_to((0.0, 0.0), (0.0, -700.0), (0.0, -700.0));
|
||||
alt.curve_to((300.0, -700.0), (450.0, -600.0), (450.0, -480.0));
|
||||
alt.extend([PathEl::QuadTo((450.0, -300.0).into(), (120.0, -300.0).into())]);
|
||||
alt.line_to((120.0, 0.0));
|
||||
alt.line_to((0.0, 0.0));
|
||||
alt.close_path();
|
||||
alt.move_to((120.0, -600.0));
|
||||
alt.line_to((120.0, -400.0));
|
||||
alt.quad_to((330.0, -400.0), (330.0, -500.0));
|
||||
alt.quad_to((330.0, -600.0), (120.0, -600.0));
|
||||
alt.close_path();
|
||||
let (_, res) = fit(&signature(&letter()).unwrap(), &signature(&alt).unwrap()).unwrap();
|
||||
assert!(res < 1e-6, "{res}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_shape_does_not_match() {
|
||||
let mut o = BezPath::new();
|
||||
o.extend(kurbo::Circle::new((200.0, -350.0), 300.0).path_elements(0.1));
|
||||
let mut box_ = BezPath::new();
|
||||
box_.extend(kurbo::Rect::new(0.0, -700.0, 450.0, 0.0).path_elements(0.1));
|
||||
let (a, b) = (signature(&o).unwrap(), signature(&box_).unwrap());
|
||||
assert!(fit(&a, &b).is_none_or(|(_, r)| r > TOLERANCE));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_shape_symbols_are_not_matched() {
|
||||
// A block element (U+1FB89) drew as a rectangle and took a drawn rectangle for it.
|
||||
for c in ['\u{1FB89}', '\u{25A0}', '\u{2588}', '\u{E000}'] {
|
||||
assert!(is_shape_symbol(c), "{c:?}");
|
||||
}
|
||||
for c in ['A', 'l', '-', '\u{6F22}', '\u{0915}'] {
|
||||
assert!(!is_shape_symbol(c), "{c:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn degenerate_and_hostile_shapes_give_none() {
|
||||
assert!(signature(&BezPath::new()).is_none());
|
||||
let mut dot = BezPath::new();
|
||||
dot.move_to((5.0, 5.0));
|
||||
dot.close_path();
|
||||
assert!(signature(&dot).is_none());
|
||||
let mut nan = BezPath::new();
|
||||
nan.move_to((f64::NAN, 0.0));
|
||||
nan.line_to((1.0, 1.0));
|
||||
assert!(signature(&nan).is_none());
|
||||
let mut huge = BezPath::new();
|
||||
huge.move_to((0.0, 0.0));
|
||||
for i in 0..(MAX_ELEMENTS + 1) {
|
||||
huge.line_to((i as f64, (i % 7) as f64));
|
||||
}
|
||||
assert!(signature(&huge).is_none());
|
||||
}
|
||||
|
||||
/// The best fit of `shape`'s readings onto `glyph`'s first one.
|
||||
fn best_fit(glyph: &BezPath, shape: &BezPath) -> f64 {
|
||||
let g = signature(glyph).unwrap();
|
||||
signatures(shape, true).iter().filter_map(|s| fit(&g, s)).map(|(_, r)| r).fold(f64::INFINITY, f64::min)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_contour_started_at_another_corner_still_matches() {
|
||||
// The counter of letter(), started at its second corner instead of its first.
|
||||
let mut p = BezPath::new();
|
||||
p.move_to((0.0, 0.0));
|
||||
p.line_to((0.0, -700.0));
|
||||
p.curve_to((300.0, -700.0), (450.0, -600.0), (450.0, -480.0));
|
||||
p.quad_to((450.0, -300.0), (120.0, -300.0));
|
||||
p.line_to((120.0, 0.0));
|
||||
p.close_path();
|
||||
p.move_to((120.0, -400.0));
|
||||
p.quad_to((330.0, -400.0), (330.0, -500.0));
|
||||
p.quad_to((330.0, -600.0), (120.0, -600.0));
|
||||
p.line_to((120.0, -400.0));
|
||||
p.close_path();
|
||||
let shape = Affine::translate((40.0, 90.0)) * Affine::rotate(-1.1) * Affine::scale(0.03) * p;
|
||||
assert_eq!(shape_key(&shape), shape_key(&letter()));
|
||||
assert!(best_fit(&letter(), &shape) < 1e-6);
|
||||
// A triangle started at each of its corners.
|
||||
let tri = |a: (f64, f64), b: (f64, f64), c: (f64, f64)| {
|
||||
let mut t = BezPath::new();
|
||||
t.move_to(a);
|
||||
t.line_to(b);
|
||||
t.line_to(c);
|
||||
t.close_path();
|
||||
t
|
||||
};
|
||||
let g = tri((0.0, 0.0), (300.0, 0.0), (0.0, -400.0));
|
||||
for s in [tri((300.0, 0.0), (0.0, -400.0), (0.0, 0.0)), tri((0.0, -400.0), (0.0, 0.0), (300.0, 0.0))] {
|
||||
assert!(best_fit(&g, &s) < 1e-6);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edge_split_in_two_reads_as_one() {
|
||||
let mut p = BezPath::new();
|
||||
p.move_to((0.0, 0.0));
|
||||
p.line_to((0.0, -350.0));
|
||||
p.line_to((0.0, -700.0));
|
||||
p.curve_to((300.0, -700.0), (450.0, -600.0), (450.0, -480.0));
|
||||
p.quad_to((450.0, -300.0), (120.0, -300.0));
|
||||
p.line_to((120.0, 0.0));
|
||||
p.line_to((60.0, 0.0));
|
||||
p.close_path();
|
||||
p.move_to((120.0, -600.0));
|
||||
p.line_to((120.0, -400.0));
|
||||
p.quad_to((330.0, -400.0), (330.0, -500.0));
|
||||
p.quad_to((330.0, -600.0), (120.0, -600.0));
|
||||
p.close_path();
|
||||
assert_eq!(shape_key(&p), shape_key(&letter()), "split edges, the closing one too, read as one");
|
||||
assert!(best_fit(&letter(), &p) < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_detail_between_samples_fails_the_whole_outline_check() {
|
||||
let bar = |notch: f64| {
|
||||
let mut p = BezPath::new();
|
||||
p.move_to((0.0, 0.0));
|
||||
p.line_to((1000.0, 0.0));
|
||||
p.line_to((1000.0, -100.0));
|
||||
// A notch 2 units wide, in or out, between two samples along the top edge.
|
||||
p.line_to((501.0, -100.0));
|
||||
p.line_to((501.0, -100.0 + notch));
|
||||
p.line_to((499.0, -100.0 + notch));
|
||||
p.line_to((499.0, -100.0));
|
||||
p.line_to((0.0, -100.0));
|
||||
p.close_path();
|
||||
p
|
||||
};
|
||||
let (out, inn) = (bar(-10.0), bar(10.0));
|
||||
assert_eq!(shape_key(&out), shape_key(&inn), "same key");
|
||||
let tol = signature(&inn).unwrap().spread * OUTLINE_TOLERANCE;
|
||||
assert!(!outlines_agree(&out, &inn, tol), "the whole outline does");
|
||||
assert!(outlines_agree(&out, &out, tol));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn readings_that_all_fail_stop_at_the_cap() {
|
||||
// 48 concentric squares (four tied corners each: 4^48 choices) so large that every reading
|
||||
// overflows: the tries stop at the cap instead of running through the choices.
|
||||
let mut p = BezPath::new();
|
||||
for i in 1..=48 {
|
||||
let r = 1e153 * f64::from(i);
|
||||
p.move_to((-r, -r));
|
||||
p.line_to((r, -r));
|
||||
p.line_to((r, r));
|
||||
p.line_to((-r, r));
|
||||
p.close_path();
|
||||
}
|
||||
let t0 = std::time::Instant::now();
|
||||
assert!(signatures(&p, true).is_empty());
|
||||
assert!(t0.elapsed() < std::time::Duration::from_secs(5), "{:?}", t0.elapsed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_corners_joined_another_way_are_another_outline() {
|
||||
let poly = |pts: &[(f64, f64)]| {
|
||||
let mut p = BezPath::new();
|
||||
p.move_to(pts[0]);
|
||||
for q in &pts[1..] {
|
||||
p.line_to(*q);
|
||||
}
|
||||
p.close_path();
|
||||
p
|
||||
};
|
||||
let square = poly(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]);
|
||||
let bow = poly(&[(0.0, 0.0), (100.0, 100.0), (100.0, 0.0), (0.0, 100.0)]);
|
||||
assert!(!outlines_agree(&square, &bow, 1.0), "every corner lies on the other, the edges do not");
|
||||
assert!(outlines_agree(&square, &square, 1.0));
|
||||
}
|
||||
}
|
||||
+35
-57
@@ -8,7 +8,7 @@ use unicode_bidi::Level;
|
||||
use unicode_script::{Script, UnicodeScript};
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
|
||||
use harfrust::{BufferClusterLevel, Direction, Feature, ShapeOptions, Tag, UnicodeBuffer};
|
||||
use harfrust::{Direction, Feature, Tag};
|
||||
use kurbo::Shape;
|
||||
use skrifa::MetadataProvider;
|
||||
use skrifa::charmap::Charmap;
|
||||
@@ -673,7 +673,7 @@ pub(crate) fn shape_runs(
|
||||
// Split into segments by font coverage (and case, for Small Caps).
|
||||
let mut seg = Segment { db, range: a..a, runs, source_runs, st, face: primary.clone(), small: false, level: level_at(a) };
|
||||
let mut cache: std::collections::HashMap<&str, Arc<FontFace>> = std::collections::HashMap::new();
|
||||
let mut script = Script::Common;
|
||||
let mut boundary = craft_font_catalog::SegmentBoundary::new(primary.id(), level_at(a));
|
||||
// A grapheme cluster (a letter and its marks, an emoji sequence) is set in one face.
|
||||
for (i, cluster) in text[a..b].grapheme_indices(true) {
|
||||
let i = a + i;
|
||||
@@ -693,20 +693,16 @@ pub(crate) fn shape_runs(
|
||||
};
|
||||
let small = small_caps && c.is_lowercase();
|
||||
let next_script = shaping_script(c);
|
||||
let strong_script = !matches!(next_script, Script::Common | Script::Inherited);
|
||||
let script_change = strong_script && script != Script::Common && script != next_script;
|
||||
let strong_script = (!matches!(next_script, Script::Common | Script::Inherited)).then_some(next_script);
|
||||
// Combining marks, zero width joiners and non-joiners, and variation selectors stay
|
||||
// with the character before them.
|
||||
if (face.id() != seg.face.id() || small != seg.small || level != seg.level || script_change) && !is_mark(c) {
|
||||
if boundary.advance(face.id(), level, small, strong_script, is_mark(c)) {
|
||||
if i > seg.range.start {
|
||||
seg.range.end = i;
|
||||
shape_segment(text, &range, &seg, feats, out);
|
||||
}
|
||||
seg = Segment { range: i..i, face, small, level, ..seg };
|
||||
}
|
||||
if strong_script {
|
||||
script = next_script;
|
||||
}
|
||||
}
|
||||
if b > seg.range.start {
|
||||
seg.range.end = b;
|
||||
@@ -1301,10 +1297,7 @@ fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool {
|
||||
/// `digits`: not what the layout handles itself (tab, line and paragraph breaks), joiners or
|
||||
/// variation selectors.
|
||||
fn drawn_chars(cluster: &str, digits: Digits) -> impl Iterator<Item = char> + '_ {
|
||||
cluster
|
||||
.chars()
|
||||
.map(move |c| digits.map(c))
|
||||
.filter(|&c| !(c.is_control() || matches!(c, '\u{200C}' | '\u{200D}' | '\u{2028}' | '\u{FE00}'..='\u{FE0F}' | '\u{E0100}'..='\u{E01EF}')))
|
||||
craft_font_catalog::drawable_characters(cluster, move |c| digits.map(c))
|
||||
}
|
||||
|
||||
/// Does the face with charmap `map` have a glyph for `c` (any face does when it has no charmap)?
|
||||
@@ -1316,11 +1309,14 @@ fn in_face(map: Option<&Charmap<'_>>, c: char) -> bool {
|
||||
/// first fallback face with all of them, so that a letter's marks are shaped with it and attach to
|
||||
/// it (#4491); when there is none, the face its first character takes on its own.
|
||||
fn fallback_face(db: &FontDb, primary: &Arc<FontFace>, pmap: Option<&Charmap<'_>>, cluster: &str, digits: Digits) -> Arc<FontFace> {
|
||||
let fallback = |c| db.fallback_for_style(c, primary.id(), primary.weight, primary.italic);
|
||||
drawn_chars(cluster, digits)
|
||||
.find_map(|c| fallback(c).filter(|f| drawn_chars(cluster, digits).all(|c| f.covers(c))))
|
||||
.or_else(|| drawn_chars(cluster, digits).next().filter(|&c| !in_face(pmap, c)).and_then(fallback))
|
||||
.unwrap_or_else(|| primary.clone())
|
||||
craft_font_catalog::cluster_face(
|
||||
cluster,
|
||||
primary,
|
||||
|c| digits.map(c),
|
||||
|c| in_face(pmap, c),
|
||||
|c| db.fallback_for_style(c, primary.id(), primary.weight, primary.italic),
|
||||
|face, c| face.covers(c),
|
||||
)
|
||||
}
|
||||
|
||||
/// The script `c` is shaped in: Japanese and Chinese text mixes Han, Hiragana, Katakana and
|
||||
@@ -1606,46 +1602,28 @@ fn shape_segment(text: &str, context: &Range<usize>, seg: &Segment, feats: &OtFe
|
||||
let along_features = with_more(&|s| feats.resolve(s));
|
||||
// gid, cluster, x and y advance, x and y offset.
|
||||
let shape = |feats: &[Feature], direction: Direction| {
|
||||
let mut buf = UnicodeBuffer::new();
|
||||
for (i, c) in text_seg.char_indices() {
|
||||
let cl = (range.start + i) as u32;
|
||||
let c = st.digits.map(c);
|
||||
if upper {
|
||||
for u in c.to_uppercase() {
|
||||
buf.add(u, cl);
|
||||
}
|
||||
} else {
|
||||
buf.add(c, cl);
|
||||
}
|
||||
}
|
||||
buf.set_direction(direction);
|
||||
buf.guess_segment_properties();
|
||||
if char_level.get() {
|
||||
buf.set_cluster_level(BufferClusterLevel::Characters);
|
||||
}
|
||||
// The characters' language picks the font's forms for it (`locl`: Turkish keeps fi
|
||||
// apart and the dot on its i).
|
||||
if let Some(l) = &language {
|
||||
buf.set_language(l.clone());
|
||||
}
|
||||
// Harfrust keeps this Unicode context for joining/positional shaping, but does not emit
|
||||
// glyphs for it. This retains context at real style/font segmentation boundaries without
|
||||
// shaping across those boundaries or claiming cross-style ligatures/mark attachment.
|
||||
if let Some(pre) = text.get(context.start..range.start) {
|
||||
buf.set_pre_context(pre);
|
||||
}
|
||||
if let Some(post) = text.get(range.end..context.end) {
|
||||
buf.set_post_context(post);
|
||||
}
|
||||
// A buffer whose characters name no script reads as `UNKNOWN`: its plan has none.
|
||||
let script = Some(buf.script()).filter(|s| *s != harfrust::script::UNKNOWN);
|
||||
let plan = face.shape_plan(&shaper, buf.direction(), script, language.as_ref(), feats);
|
||||
let gb = shaper.shape(buf, ShapeOptions::new().features(feats).plan(Some(&plan)));
|
||||
gb.glyph_infos()
|
||||
.iter()
|
||||
.zip(gb.glyph_positions())
|
||||
.map(|(info, pos)| (info.glyph_id, info.cluster, pos.x_advance, pos.y_advance, pos.x_offset, pos.y_offset))
|
||||
.collect::<Vec<_>>()
|
||||
let input = craft_font_catalog::RunInput {
|
||||
text: text_seg,
|
||||
source_start: range.start,
|
||||
pre_context: text.get(context.start..range.start).unwrap_or_default(),
|
||||
post_context: text.get(range.end..context.end).unwrap_or_default(),
|
||||
direction,
|
||||
language: language.as_ref(),
|
||||
features: feats,
|
||||
character_clusters: char_level.get(),
|
||||
uppercase: upper,
|
||||
};
|
||||
craft_font_catalog::shape_run(
|
||||
&shaper,
|
||||
&input,
|
||||
|c| st.digits.map(c),
|
||||
|shaper, direction, script, language, features| face.shape_plan(shaper, direction, script, language, features),
|
||||
)
|
||||
// HarfRust clusters are u32; a run beyond that source offset cannot be represented.
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|g| (g.glyph_id, g.cluster, g.x_advance, g.y_advance, g.x_offset, g.y_offset))
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let along = if level.is_rtl() { Direction::RightToLeft } else { Direction::LeftToRight };
|
||||
*raw = shape(&along_features, along).into_iter().map(|(g, c, xa, _, xo, yo)| (g, c, xa, xo, yo)).collect();
|
||||
|
||||
@@ -134,7 +134,7 @@ impl Tool for EnclosingLassoTool {
|
||||
let symbols = cx.doc.symbol_boxes();
|
||||
let region = (points.len() >= 3).then(|| Region::new(polygon(&points, true))).flatten();
|
||||
let mut ids = if let Some(region) = region {
|
||||
enclosure_candidates(cx.doc, region.path.bounding_box(), cx.isolation, cx.outline)
|
||||
enclosure_candidates(cx.doc, region.path.bounding_box(), cx.isolation, cx.outline, !cx.guides)
|
||||
.into_iter()
|
||||
.filter(|id| cx.doc.node(*id).is_some_and(|n| node_inside(n, &symbols, ®ion)))
|
||||
.collect()
|
||||
|
||||
+676
-21
@@ -4,11 +4,12 @@
|
||||
//! a click on a circle or arc gives its radius. Escape cancels without leaving any artwork.
|
||||
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::HashMap;
|
||||
use vectorcraft_doc::{
|
||||
Node, NodeId,
|
||||
Node, NodeId, NodeKind,
|
||||
dimension::{self, Dimension, DimensionMode, DimensionOptions, DimensionSource, FreePoint, Orientation, PointRef, SegmentRef},
|
||||
};
|
||||
use vectorcraft_geom::{BezPath, Point, Vec2};
|
||||
use vectorcraft_geom::{BezPath, Point, Rect, Vec2};
|
||||
|
||||
/// The three kinds of dimension the tool draws.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
@@ -68,14 +69,28 @@ pub struct DimensionTool {
|
||||
/// Where the next Linear pick lands, as last worked out for the pointer (for the overlays).
|
||||
snapped: Option<(Point, Option<PointRef>)>,
|
||||
/// Whether the last Linear pick worked out landed on the end of a line of a dimension already
|
||||
/// drawn (shown as an anchor).
|
||||
/// drawn, or on a corner of a path's preview bounds (shown as an anchor).
|
||||
on_end: bool,
|
||||
/// The path that holds the last Linear pick worked out, when it landed on a corner of that
|
||||
/// path's preview bounds.
|
||||
corner: Option<NodeId>,
|
||||
/// The path that holds the first Linear point, when it was picked on a corner of that path's
|
||||
/// preview bounds.
|
||||
first_corner: Option<NodeId>,
|
||||
/// Whether the press under way began on an anchor a Linear click picks.
|
||||
press_on_anchor: bool,
|
||||
/// The second point clicked for the Linear dimension being placed, and where the pointer was
|
||||
/// for that click (a snap or Shift can move the point away from it): placed with the pointer
|
||||
/// still at either, it is aligned.
|
||||
second: Option<(Point, Point)>,
|
||||
/// The preview bounds the Linear picks measured, for the document's revision.
|
||||
preview_boxes: PreviewBoxes,
|
||||
/// While a Linear dimension is placed with its line on the level of another dimension's line:
|
||||
/// the ends of that other line. A Smart Guide runs along the level across both lines.
|
||||
level_guide: Option<(Point, Point)>,
|
||||
/// While a dimension is placed: the lines of the visible, unlocked linear dimensions in the
|
||||
/// document before its first preview ([`dimension_lines`]), which its line can line up with.
|
||||
levels: Vec<DimensionLine>,
|
||||
}
|
||||
|
||||
/// What a linear dimension between `a` and `b` measures with the pointer at `p` while it is
|
||||
@@ -170,9 +185,14 @@ fn anchor_near(cx: &ToolContext, edge: &SegmentRef, p: Point) -> Option<(usize,
|
||||
/// The anchor nearest `p` within reach, on any editable path (the topmost on a tie), as a link to
|
||||
/// its path. Bounded work, and dimension artwork is skipped, as in [`pick`].
|
||||
fn anchor_under(cx: &ToolContext, p: Point) -> Option<(Point, PointRef)> {
|
||||
anchor_under_where(cx, p, |_| true)
|
||||
}
|
||||
|
||||
/// [`anchor_under`] outside the objects `keep` turns down, and outside everything in them.
|
||||
fn anchor_under_where(cx: &ToolContext, p: Point, keep: impl Fn(NodeId) -> bool) -> Option<(Point, PointRef)> {
|
||||
type Best = Option<(f64, Point, PointRef)>;
|
||||
fn visit(n: &Node, p: Point, reach: f64, budget: &mut usize, best: &mut Best) {
|
||||
if *budget == 0 || !n.visible || n.locked || n.extras().dimension.is_some() {
|
||||
fn visit(n: &Node, p: Point, reach: f64, keep: &dyn Fn(NodeId) -> bool, budget: &mut usize, best: &mut Best) {
|
||||
if *budget == 0 || !n.visible || n.locked || n.extras().dimension.is_some() || !keep(n.id) {
|
||||
return;
|
||||
}
|
||||
if let Some(path) = n.path_data() {
|
||||
@@ -191,17 +211,178 @@ fn anchor_under(cx: &ToolContext, p: Point) -> Option<(Point, PointRef)> {
|
||||
}
|
||||
if let Some(ch) = n.children() {
|
||||
for c in ch.iter().rev() {
|
||||
visit(c, p, reach, budget, best);
|
||||
visit(c, p, reach, keep, budget, best);
|
||||
}
|
||||
}
|
||||
}
|
||||
let (reach, mut budget, mut best) = (cx.tol(ANCHOR_REACH), 20_000usize, None);
|
||||
for n in cx.doc.layers.iter().rev() {
|
||||
visit(n, p, reach, &mut budget, &mut best);
|
||||
visit(n, p, reach, &keep, &mut budget, &mut best);
|
||||
}
|
||||
best.map(|(_, at, r)| (at, r))
|
||||
}
|
||||
|
||||
/// The geometric bounds of the paths [`preview_corner`] looked at, and the preview bounds of
|
||||
/// those it measured, kept while the document is unchanged, so that the pointer moving over the
|
||||
/// art measures each path once.
|
||||
#[derive(Default)]
|
||||
struct PreviewBoxes {
|
||||
revision: Option<(u64, u64)>,
|
||||
geometric: HashMap<NodeId, Option<Rect>>,
|
||||
preview: HashMap<NodeId, Option<Rect>>,
|
||||
/// Whether a point at each corner (by object and corner number) can be held against its path.
|
||||
holdable: HashMap<(NodeId, usize), bool>,
|
||||
}
|
||||
|
||||
/// A corner of an object's preview bounds that a Linear pick can land on.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct PreviewCorner {
|
||||
at: Point,
|
||||
/// The path the point is held against.
|
||||
holder: NodeId,
|
||||
/// The same corner of the object's geometric bounds: an anchor of `holder` there is the
|
||||
/// anchor the corner stands in for.
|
||||
stands_for: Point,
|
||||
}
|
||||
|
||||
/// With Use Preview Bounds on, the corner of a path's or compound path's preview bounds (its
|
||||
/// strokes and effects included) nearest `p` within reach, on any editable one whose preview
|
||||
/// bounds differ from its geometric bounds. In a compound path, the member whose own box reaches
|
||||
/// nearest to the corner holds it. The work is bounded, and dimension artwork is skipped, as in
|
||||
/// [`pick`]. `cache` keeps the bounds measured for the document's revision.
|
||||
fn preview_corner(cx: &ToolContext, p: Point, cache: &mut PreviewBoxes) -> Option<PreviewCorner> {
|
||||
struct Walk<'a, 'c> {
|
||||
symbols: Option<vectorcraft_doc::SymbolBoxes<'a>>,
|
||||
doc: &'a vectorcraft_doc::Document,
|
||||
cache: &'c mut PreviewBoxes,
|
||||
p: Point,
|
||||
reach: f64,
|
||||
budget: usize,
|
||||
best: Option<(f64, PreviewCorner)>,
|
||||
}
|
||||
fn visit(n: &Node, w: &mut Walk) {
|
||||
if w.budget == 0 || !n.visible || n.locked || n.extras().dimension.is_some() {
|
||||
return;
|
||||
}
|
||||
w.budget -= 1;
|
||||
// Only effects, on the object or on one of its fills or strokes, paint further out than
|
||||
// its strokes reach.
|
||||
let effects = !n.appearance.effects.is_empty() || n.appearance.items.iter().any(|i| !i.effects().is_empty());
|
||||
let reach = n.appearance.outset() + w.reach;
|
||||
let corners = |r: Rect| [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)];
|
||||
// A path is its own member; a compound path's members are its paths.
|
||||
let compound = match &n.kind {
|
||||
NodeKind::Compound { children, .. } => Some(children.as_slice()),
|
||||
_ => None,
|
||||
};
|
||||
let members =
|
||||
|| compound.into_iter().flatten().map(|c| c.as_ref()).chain(compound.is_none().then_some(n)).filter(|m| m.path_data().is_some());
|
||||
// A path made into a guide draws as a guide, without its strokes or effects. The pointer
|
||||
// test includes the right and bottom edges, as the distance test below does.
|
||||
let within = |r: Rect| (r.x0..=r.x1).contains(&w.p.x) && (r.y0..=r.y1).contains(&w.p.y);
|
||||
if !n.is_guide()
|
||||
&& members().next().is_some()
|
||||
&& let Some(geometric) = *w.cache.geometric.entry(n.id).or_insert_with(|| n.geometric_bounds())
|
||||
&& (effects || within(geometric.inflate(reach, reach)))
|
||||
{
|
||||
let doc = w.doc;
|
||||
let measured = match w.cache.preview.get(&n.id) {
|
||||
Some(r) => *r,
|
||||
None => {
|
||||
let symbols = w.symbols.get_or_insert_with(|| doc.symbol_boxes());
|
||||
let r = vectorcraft_effects::preview::visual_bounds(symbols, n);
|
||||
w.cache.preview.insert(n.id, r);
|
||||
r
|
||||
}
|
||||
};
|
||||
if let Some(r) = measured
|
||||
&& r != geometric
|
||||
{
|
||||
for (k, q) in corners(r).into_iter().enumerate() {
|
||||
let d = q.distance(w.p);
|
||||
if d > w.reach || w.best.is_some_and(|(nearest, ..)| d >= nearest) {
|
||||
continue;
|
||||
}
|
||||
// The path whose own box reaches furthest towards the corner holds it: in a
|
||||
// compound path, the member that puts that corner where it is. A hidden or
|
||||
// locked member gives no corner.
|
||||
let mut holder: Option<(f64, NodeId, bool)> = None;
|
||||
for m in members() {
|
||||
let Some(b) = *w.cache.geometric.entry(m.id).or_insert_with(|| m.geometric_bounds()) else { continue };
|
||||
let gap = corners(b).get(k).map_or(f64::INFINITY, |c| c.distance(q));
|
||||
let editable = m.visible && !m.locked;
|
||||
if holder.is_none_or(|(near, _, was)| gap < near || (gap == near && editable && !was)) {
|
||||
holder = Some((gap, m.id, editable));
|
||||
}
|
||||
}
|
||||
let holder = holder.filter(|(.., editable)| *editable).map(|(gap, id, _)| (gap, id));
|
||||
// A path that cannot hold a point at the corner (a stroked dot, whose anchors
|
||||
// all coincide) gives no corner.
|
||||
let holdable = |id: NodeId, cache: &mut PreviewBoxes| {
|
||||
*cache.holdable.entry((n.id, k)).or_insert_with(|| FreePoint::on(doc, id, q).is_some())
|
||||
};
|
||||
let holder = holder.filter(|(_, id)| holdable(*id, w.cache));
|
||||
if let Some(((_, holder), stands_for)) = holder.zip(corners(geometric).get(k).copied()) {
|
||||
w.best = Some((d, PreviewCorner { at: q, holder, stands_for }));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// A compound path draws its members with its own appearance: they give no corners of
|
||||
// their own.
|
||||
if compound.is_none()
|
||||
&& let Some(ch) = n.children()
|
||||
{
|
||||
for c in ch.iter().rev() {
|
||||
visit(c, w);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Anchors take a pick whatever the snapping options, and so do the corners standing in for them.
|
||||
if !cx.preview_bounds {
|
||||
return None;
|
||||
}
|
||||
if cache.revision != Some(cx.revision) {
|
||||
*cache = PreviewBoxes { revision: Some(cx.revision), ..Default::default() };
|
||||
}
|
||||
let mut w = Walk { symbols: None, doc: cx.doc, cache, p, reach: cx.tol(ANCHOR_REACH), budget: 20_000, best: None };
|
||||
for n in cx.doc.layers.iter().rev() {
|
||||
visit(n, &mut w);
|
||||
}
|
||||
w.best.map(|(_, corner)| corner)
|
||||
}
|
||||
|
||||
/// The anchor a pick at `p` lands on instead of `corner`, given `anchor`, the nearest anchor
|
||||
/// within reach; `None` when the corner takes it (VectorCraft's own rule). The corner takes the
|
||||
/// pick from the anchors of the path holding it at the same corner of the object's geometric
|
||||
/// bounds, which sit on the stroke's centerline. An anchor right on the corner takes it, and so
|
||||
/// does the nearest other anchor, of this object or of other art, when it is nearer the pointer
|
||||
/// than the corner. The holder's anchors and the other art are searched with a budget each, and
|
||||
/// `anchor` wins a tie, as the topmost.
|
||||
fn anchor_over_corner(cx: &ToolContext, p: Point, corner: &PreviewCorner, anchor: Option<(Point, PointRef)>) -> Option<(Point, PointRef)> {
|
||||
if anchor.as_ref().is_some_and(|(at, _)| at.distance(corner.at) <= 1e-9) {
|
||||
return anchor;
|
||||
}
|
||||
let stands_in = |(at, nearest): &(Point, PointRef)| nearest.node == corner.holder && at.distance(corner.stands_for) <= 1e-9;
|
||||
let first = anchor.filter(|a| !stands_in(a));
|
||||
let reach = cx.tol(ANCHOR_REACH);
|
||||
let own = cx.doc.node(corner.holder).and_then(|n| n.path_data()).and_then(|path| {
|
||||
let anchors = path.subpaths.iter().enumerate().flat_map(|(subpath, sp)| sp.anchors.iter().enumerate().map(move |(i, a)| (subpath, i, a.p)));
|
||||
anchors
|
||||
.take(20_000)
|
||||
.filter(|(.., q)| q.distance(p) <= reach && q.distance(corner.stands_for) > 1e-9)
|
||||
.min_by(|(.., a), (.., b)| a.distance(p).total_cmp(&b.distance(p)))
|
||||
.map(|(subpath, anchor, q)| (q, PointRef { node: corner.holder, subpath, anchor }))
|
||||
});
|
||||
let other = anchor_under_where(cx, p, |id| id != corner.holder);
|
||||
first
|
||||
.into_iter()
|
||||
.chain(other)
|
||||
.chain(own)
|
||||
.filter(|(q, _)| q.distance(p) < corner.at.distance(p) || q.distance(corner.at) <= 1e-9)
|
||||
.min_by(|(a, _), (b, _)| a.distance(p).total_cmp(&b.distance(p)))
|
||||
}
|
||||
|
||||
/// Where a pick at `p` lands on the artwork of the visible, unlocked dimensions already drawn,
|
||||
/// with no link to it: the nearest end of one of their lines (dimension and extension lines)
|
||||
/// within the anchor reach, as an anchor (`true`); else the nearest point of one of those lines
|
||||
@@ -285,6 +466,58 @@ fn on_dimensions(cx: &ToolContext, p: Point) -> Option<(Point, bool)> {
|
||||
best.end.map(|(_, q)| (q, true)).or_else(|| best.line.map(|(_, q)| (q, false)))
|
||||
}
|
||||
|
||||
/// The line of a linear dimension already drawn: its ends and its direction.
|
||||
type DimensionLine = ((Point, Point), Vec2);
|
||||
|
||||
/// The lines of the visible, unlocked linear dimensions in the document. Bounded work, as in
|
||||
/// [`on_dimensions`].
|
||||
fn dimension_lines(cx: &ToolContext) -> Vec<DimensionLine> {
|
||||
fn visit(n: &Node, budget: &mut usize, out: &mut Vec<DimensionLine>) {
|
||||
if *budget == 0 || !n.visible || n.locked {
|
||||
return;
|
||||
}
|
||||
*budget -= 1;
|
||||
if let Some(d) = &n.extras().dimension {
|
||||
if d.mode == DimensionMode::Linear {
|
||||
out.push((d.line_ends(), d.direction()));
|
||||
}
|
||||
return;
|
||||
}
|
||||
for c in n.children().into_iter().flatten().rev() {
|
||||
visit(c, budget, out);
|
||||
}
|
||||
}
|
||||
let (mut budget, mut out) = (20_000usize, vec![]);
|
||||
for n in cx.doc.layers.iter().rev() {
|
||||
visit(n, &mut budget, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Where the line of the linear dimension `d`, placed through `p`, lands on the level of one of
|
||||
/// the `levels` that runs parallel to it, within `reach` of `p` across the line: the point to
|
||||
/// place `d` through, and the ends of that other line. The nearest level wins, then the line
|
||||
/// nearest `p` along it (none nearer than a line that `p` lies across).
|
||||
fn line_level(levels: &[DimensionLine], d: &Dimension, p: Point, reach: f64) -> Option<(Point, (Point, Point))> {
|
||||
if d.mode != DimensionMode::Linear {
|
||||
return None;
|
||||
}
|
||||
let (u, normal) = (d.direction(), d.normal());
|
||||
let mut best: Option<(f64, f64, f64, (Point, Point))> = None;
|
||||
for &(ends, direction) in levels {
|
||||
if u.cross(direction).abs() > 1e-6 {
|
||||
continue;
|
||||
}
|
||||
let shift = (ends.0 - p).dot(normal);
|
||||
let (s0, s1) = ((ends.0 - p).dot(u), (ends.1 - p).dot(u));
|
||||
let along = if s0 * s1 <= 0.0 { 0.0 } else { s0.abs().min(s1.abs()) };
|
||||
if shift.is_finite() && along.is_finite() && shift.abs() <= reach && best.is_none_or(|(s, a, _, _)| (shift.abs(), along) < (s, a)) {
|
||||
best = Some((shift.abs(), along, shift, ends));
|
||||
}
|
||||
}
|
||||
best.map(|(_, _, shift, ends)| (p + normal * shift, ends))
|
||||
}
|
||||
|
||||
/// The point of `edge` closest to `p`.
|
||||
fn nearest_on(cx: &ToolContext, edge: &SegmentRef, p: Point) -> Option<Point> {
|
||||
use vectorcraft_geom::kurbo::ParamCurveNearest;
|
||||
@@ -303,10 +536,23 @@ fn nearest_on(cx: &ToolContext, edge: &SegmentRef, p: Point) -> Option<Point> {
|
||||
/// A point on a segment keeps its place along the segment. Any other point is held
|
||||
/// against the anchors of the path under it, or, with no path under it, the path of the other
|
||||
/// point, so that it moves with that path. None when neither point has a path to link to.
|
||||
fn points_source(cx: &ToolContext, (a, ra): (Point, &Option<PointRef>), (b, rb): (Point, &Option<PointRef>)) -> Option<DimensionSource> {
|
||||
let (edge_a, edge_b) = (pick(cx, a), pick(cx, b));
|
||||
let node = |r: &Option<PointRef>, e: &Option<SegmentRef>| r.as_ref().map(|r| r.node).or_else(|| e.as_ref().map(|e| e.node));
|
||||
let (path_a, path_b) = (node(ra, &edge_a), node(rb, &edge_b));
|
||||
/// `held_a` and `held_b` name the path holding a point picked on a corner of that path's
|
||||
/// preview bounds: such a point is held against that path, however far its strokes or effects
|
||||
/// put the corner from the path and whatever other segment lies there.
|
||||
fn points_source(
|
||||
cx: &ToolContext,
|
||||
(a, ra, held_a): (Point, &Option<PointRef>, Option<NodeId>),
|
||||
(b, rb, held_b): (Point, &Option<PointRef>, Option<NodeId>),
|
||||
) -> Option<DimensionSource> {
|
||||
// A path deleted since the pick holds nothing.
|
||||
let holder = |held: Option<NodeId>| held.filter(|node| cx.doc.node(*node).is_some());
|
||||
let (corner_a, corner_b) = (holder(held_a), holder(held_b));
|
||||
let edge = |p: Point, corner: Option<NodeId>| if corner.is_some() { None } else { pick(cx, p) };
|
||||
let (edge_a, edge_b) = (edge(a, corner_a), edge(b, corner_b));
|
||||
let node = |r: &Option<PointRef>, corner: Option<NodeId>, e: &Option<SegmentRef>| {
|
||||
r.as_ref().map(|r| r.node).or(corner).or_else(|| e.as_ref().map(|e| e.node))
|
||||
};
|
||||
let (path_a, path_b) = (node(ra, corner_a, &edge_a), node(rb, corner_b, &edge_b));
|
||||
let free = |p: Point, r: &Option<PointRef>, edge: &Option<SegmentRef>, own: Option<NodeId>, other: Option<NodeId>| {
|
||||
if r.is_some() {
|
||||
return None;
|
||||
@@ -324,7 +570,10 @@ fn points_source(cx: &ToolContext, (a, ra): (Point, &Option<PointRef>), (b, rb):
|
||||
}
|
||||
|
||||
impl DimensionTool {
|
||||
/// Where a Linear pick at `p` lands: on the nearest anchor of any path, within reach (kept as
|
||||
/// Where a Linear pick at `p` lands: with Use Preview Bounds on, on the nearest corner of a
|
||||
/// path's preview bounds within reach, where they differ from its anchors, unless another
|
||||
/// anchor is nearer (held against the path, labeled "anchor"; [`anchor_over_corner`]); else on the
|
||||
/// nearest anchor of any path, within reach (kept as
|
||||
/// a link to its path), labeled "anchor"; else on the nearest end of a line of a dimension
|
||||
/// already drawn, within the same reach (no link), also labeled "anchor"; else where Smart Guides put it (another object's anchor or centre, in
|
||||
/// line with one, or for the second point square to a segment or grazing a curve from the
|
||||
@@ -341,7 +590,18 @@ impl DimensionTool {
|
||||
});
|
||||
let guided = self.snap.hover(cx, p, &[], leave.as_ref());
|
||||
self.on_end = false;
|
||||
if let Some((point, reference)) = anchor_under(cx, p) {
|
||||
self.corner = None;
|
||||
let mut anchor = anchor_under(cx, p);
|
||||
if let Some(corner) = preview_corner(cx, p, &mut self.preview_boxes) {
|
||||
anchor = anchor_over_corner(cx, p, &corner, anchor);
|
||||
if anchor.is_none() {
|
||||
self.on_end = true;
|
||||
self.corner = Some(corner.holder);
|
||||
self.snap.label(corner.at, "anchor");
|
||||
return (corner.at, None);
|
||||
}
|
||||
}
|
||||
if let Some((point, reference)) = anchor {
|
||||
self.snap.label(point, "anchor");
|
||||
return (point, Some(reference));
|
||||
}
|
||||
@@ -435,6 +695,7 @@ impl DimensionTool {
|
||||
p
|
||||
}
|
||||
fn preview(&mut self, cx: &ToolContext, p: Point) -> Vec<Action> {
|
||||
self.level_guide = None;
|
||||
let Some(d) = &mut self.pending else { return vec![] };
|
||||
if matches!(d.mode, DimensionMode::Radius | DimensionMode::Diameter)
|
||||
&& let Some(Target::Radial { center, radius, .. }) = self.press.as_ref().and_then(|(_, t)| t.as_ref())
|
||||
@@ -462,10 +723,18 @@ impl DimensionTool {
|
||||
if d.resolve(cx.doc).is_err() {
|
||||
return vec![];
|
||||
}
|
||||
d.place(p);
|
||||
// With Smart Guides on, a linear dimension's line lands on the level of a parallel
|
||||
// dimension line already drawn within the Smart Guides snapping tolerance. The lines are
|
||||
// read before the first preview, so the preview of this dimension is not one of them.
|
||||
if !self.began {
|
||||
self.levels = dimension_lines(cx);
|
||||
}
|
||||
let level = if cx.smart_guides { line_level(&self.levels, d, p, cx.snap_tol()) } else { None };
|
||||
d.place(level.map_or(p, |(on_level, _)| on_level));
|
||||
if d.validate().is_err() {
|
||||
return vec![];
|
||||
}
|
||||
self.level_guide = level.map(|(_, ends)| ends);
|
||||
let mut actions = vec![];
|
||||
if !self.began {
|
||||
actions.push(Action::Begin("Create Dimension".into()));
|
||||
@@ -488,6 +757,8 @@ impl DimensionTool {
|
||||
self.press = None;
|
||||
self.press_on_anchor = false;
|
||||
self.on_end = false;
|
||||
self.corner = None;
|
||||
self.first_corner = None;
|
||||
self.points.clear();
|
||||
self.lines.clear();
|
||||
self.dragging = false;
|
||||
@@ -495,21 +766,30 @@ impl DimensionTool {
|
||||
self.snap.clear();
|
||||
self.snapped = None;
|
||||
self.second = None;
|
||||
self.level_guide = None;
|
||||
self.levels.clear();
|
||||
}
|
||||
/// A plain click: picks a point or a line, or measures a circle's radius.
|
||||
fn click(&mut self, cx: &ToolContext, p: Point, target: Option<Target>, mods: Mods) -> Vec<Action> {
|
||||
match self.kind {
|
||||
Kind::Linear => {
|
||||
let (mut at, mut reference) = self.snap_linear(cx, p);
|
||||
let mut corner = self.corner;
|
||||
if mods.shift
|
||||
&& let Some((last, _)) = self.points.last()
|
||||
{
|
||||
let snapped = at;
|
||||
at = constrained(cx, *last, at);
|
||||
reference = reference.filter(|r| r.position(cx.doc) == Some(at));
|
||||
corner = corner.filter(|_| at.distance(snapped) <= 1e-9);
|
||||
}
|
||||
self.points.push((at, reference));
|
||||
if self.points.len() == 1 {
|
||||
self.first_corner = corner;
|
||||
}
|
||||
if let [(a, ra), (b, rb)] = self.points.as_slice() {
|
||||
let source = points_source(cx, (*a, ra), (*b, rb));
|
||||
let source = points_source(cx, (*a, ra, self.first_corner), (*b, rb, corner));
|
||||
self.first_corner = None;
|
||||
let mut d = self.recipe(DimensionMode::Linear, *a, *b, Point::ZERO, source);
|
||||
if d.resolve(cx.doc).is_ok() {
|
||||
self.second = Some((*b, p));
|
||||
@@ -609,11 +889,14 @@ impl Tool for DimensionTool {
|
||||
self.press = Some((ev.pos, None));
|
||||
return self.preview(cx, ev.pos);
|
||||
}
|
||||
// A Linear press on an anchor, or on the end of a dimension's line, picks it unless
|
||||
// it drags past the anchor's reach: moving a few pixels before the release does not
|
||||
// drag out the dimension of a segment under the pointer.
|
||||
self.press_on_anchor =
|
||||
self.kind == Kind::Linear && (anchor_under(cx, ev.pos).is_some() || on_dimensions(cx, ev.pos).is_some_and(|(_, end)| end));
|
||||
// A Linear press on an anchor, on a corner of preview bounds or on the end of a
|
||||
// dimension's line, picks it unless it drags past the anchor's reach: moving a few
|
||||
// pixels before the release does not drag out the dimension of a segment under the
|
||||
// pointer.
|
||||
self.press_on_anchor = self.kind == Kind::Linear
|
||||
&& (anchor_under(cx, ev.pos).is_some()
|
||||
|| preview_corner(cx, ev.pos, &mut self.preview_boxes).is_some()
|
||||
|| on_dimensions(cx, ev.pos).is_some_and(|(_, end)| end));
|
||||
self.press = Some((ev.pos, self.target(cx, ev.pos)));
|
||||
vec![]
|
||||
}
|
||||
@@ -664,6 +947,7 @@ impl Tool for DimensionTool {
|
||||
self.press = None;
|
||||
if self.pending.is_some() && self.began {
|
||||
self.began = false;
|
||||
self.level_guide = None;
|
||||
vec![Action::Cancel]
|
||||
} else {
|
||||
vec![]
|
||||
@@ -727,7 +1011,7 @@ impl Tool for DimensionTool {
|
||||
let linear_pick = self.kind == Kind::Linear && self.pending.is_none() && self.lines.is_empty();
|
||||
let snapped = self.snapped.clone().filter(|_| linear_pick);
|
||||
if let Some((q, reference)) = &snapped
|
||||
&& (reference.is_some() || q.distance(self.at) > 1e-9)
|
||||
&& (reference.is_some() || self.on_end || q.distance(self.at) > 1e-9)
|
||||
{
|
||||
let on_anchor = reference.is_some() || self.on_end;
|
||||
out.push(Overlay::Anchor { p: *q, color, filled: !on_anchor, size: if on_anchor { 10.0 } else { 6.0 } });
|
||||
@@ -741,6 +1025,21 @@ impl Tool for DimensionTool {
|
||||
if linear_pick {
|
||||
out.extend(self.snap.guides().iter().cloned());
|
||||
}
|
||||
// A dimension line placed on the level of another: one alignment guide across both lines,
|
||||
// unless Alignment Guides are off.
|
||||
if cx.alignment_guides
|
||||
&& let (Some(d), Some((c, e))) = (&self.pending, self.level_guide)
|
||||
{
|
||||
let (a, b) = d.line_ends();
|
||||
let u = d.direction();
|
||||
let along = |q: &Point| q.to_vec2().dot(u);
|
||||
let ends = [a, b, c, e];
|
||||
if let (Some(lo), Some(hi)) =
|
||||
(ends.iter().min_by(|p, q| along(p).total_cmp(&along(q))), ends.iter().max_by(|p, q| along(p).total_cmp(&along(q))))
|
||||
{
|
||||
out.push(Overlay::Line { a: *lo, b: *hi, color: cx.smart_guide_color, dashed: false });
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
@@ -778,6 +1077,21 @@ mod tests {
|
||||
assert!(t.pointer(&c, &ev(PointerKind::Up, 150.0, 60.0)).is_empty(), "the release places nothing");
|
||||
}
|
||||
|
||||
/// Of two dimension lines on one level, a line the pointer lies across wins over a line whose
|
||||
/// end is nearer the pointer.
|
||||
#[test]
|
||||
fn a_line_the_pointer_lies_across_wins_on_one_level() {
|
||||
let pt = Point::new;
|
||||
let d = DimensionTool::default().recipe(DimensionMode::Linear, pt(200.0, 200.0), pt(300.0, 200.0), pt(250.0, 200.0), None);
|
||||
let across = ((pt(0.0, 170.0), pt(400.0, 170.0)), Vec2::new(1.0, 0.0));
|
||||
let beside = ((pt(100.0, 170.0), pt(200.0, 170.0)), Vec2::new(1.0, 0.0));
|
||||
for levels in [[beside, across], [across, beside]] {
|
||||
let (at, ends) = line_level(&levels, &d, pt(250.0, 172.0), 4.0).expect("on the level");
|
||||
assert!(at.distance(pt(250.0, 170.0)) < 1e-9, "{at:?}");
|
||||
assert_eq!(ends, across.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_placement_press_does_not_commit_the_dimension() {
|
||||
let (d, _) = doc_with_rect();
|
||||
@@ -937,6 +1251,347 @@ mod tests {
|
||||
assert!(at.distance(pending.b) < 1e-9, "{at:?} {:?}", pending.b);
|
||||
}
|
||||
|
||||
/// With Use Preview Bounds on, clicks by the corners of a stroked path land on the corners of
|
||||
/// its preview bounds, held against the path, so the dimension measures the outside of the
|
||||
/// stroke as W and H do. Without a stroke, or with the preference off, the anchors are picked.
|
||||
#[test]
|
||||
fn with_preview_bounds_points_land_on_the_corners_of_the_stroke() {
|
||||
use vectorcraft_doc::dimension::FreePoint;
|
||||
let (d, id) = doc_with_rect();
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let pick = |c: &ToolContext| {
|
||||
let mut t = DimensionTool::default();
|
||||
for (x, y) in [(101.0, 101.0), (199.0, 199.0)] {
|
||||
t.pointer(c, &PointerEvent::new(PointerKind::Move, x, y));
|
||||
t.pointer(c, &PointerEvent::new(PointerKind::Down, x, y));
|
||||
t.pointer(c, &PointerEvent::new(PointerKind::Up, x, y));
|
||||
}
|
||||
t.pending.expect("both points were picked")
|
||||
};
|
||||
let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) };
|
||||
let pending = pick(&c);
|
||||
let near = |a: Point, b: Point| a.distance(b) < 1e-9;
|
||||
assert!(near(pending.a, Point::new(99.5, 99.5)) && near(pending.b, Point::new(200.5, 200.5)), "{:?} {:?}", pending.a, pending.b);
|
||||
let Some(DimensionSource::Points { a: None, b: None, free_a: Some(free_a), free_b: Some(free_b), .. }) = &pending.source else {
|
||||
panic!("{:?}", pending.source)
|
||||
};
|
||||
for (free, at) in [(free_a, pending.a), (free_b, pending.b)] {
|
||||
assert!(matches!(free, FreePoint::Anchors { node, .. } if *node == id), "{free:?}");
|
||||
assert!(free.position(&d).expect("the anchors that hold it exist").distance(at) < 1e-9);
|
||||
}
|
||||
// A line of another path through the corner leaves the point held against the rectangle.
|
||||
let mut crossed = d.clone();
|
||||
let (l, line) = (crossed.layers[0].id, crossed.alloc_id());
|
||||
let path = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(0.0, 99.5), Point::new(300.0, 99.5)], false));
|
||||
crossed.insert(Some(l), 1, Node::path(line, path, vectorcraft_doc::Appearance::default_art())).expect("the line");
|
||||
let pending = pick(&ToolContext { preview_bounds: true, ..cx(&crossed, &s, &p) });
|
||||
assert!(near(pending.a, Point::new(99.5, 99.5)), "{:?}", pending.a);
|
||||
let Some(DimensionSource::Points { free_a: Some(free_a), .. }) = &pending.source else { panic!("{:?}", pending.source) };
|
||||
assert!(matches!(free_a, FreePoint::Anchors { node, .. } if *node == id), "{free_a:?}");
|
||||
let anchors = |pending: &Dimension| (pending.a, pending.b, pending.source.clone());
|
||||
let anchor = |anchor| Some(PointRef { node: id, subpath: 0, anchor });
|
||||
let linked = DimensionSource::Points { a: anchor(0), b: anchor(2), vertex: None, free_a: None, free_b: None };
|
||||
let off = pick(&cx(&d, &s, &p));
|
||||
assert_eq!(anchors(&off), (Point::new(100.0, 100.0), Point::new(200.0, 200.0), Some(linked.clone())), "preference off");
|
||||
let mut bare = d.clone();
|
||||
bare.node_mut(id).expect("the rectangle").appearance = vectorcraft_doc::Appearance::default().into();
|
||||
let c = ToolContext { preview_bounds: true, ..cx(&bare, &s, &p) };
|
||||
assert_eq!(anchors(&pick(&c)), (Point::new(100.0, 100.0), Point::new(200.0, 200.0), Some(linked)), "no stroke");
|
||||
// A compound path's stroke: the points are held against the member that reaches the
|
||||
// corner, not the small hole drawn first.
|
||||
let mut compound = vectorcraft_doc::Document::new(500.0, 500.0);
|
||||
let (l, hole, part, whole) = (compound.layers[0].id, compound.alloc_id(), compound.alloc_id(), compound.alloc_id());
|
||||
let square = |id, a: f64, b: f64| {
|
||||
std::sync::Arc::new(Node::path(id, vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(a, a, b, b)), Default::default()))
|
||||
};
|
||||
let children = vec![square(hole, 140.0, 160.0), square(part, 100.0, 200.0)];
|
||||
let mut n = Node::new(whole, NodeKind::Compound { children, rule: Default::default() });
|
||||
n.appearance = vectorcraft_doc::Appearance::default_art().into();
|
||||
compound.insert(Some(l), 0, n).expect("the compound path");
|
||||
let pending = pick(&ToolContext { preview_bounds: true, ..cx(&compound, &s, &p) });
|
||||
assert!(near(pending.a, Point::new(99.5, 99.5)) && near(pending.b, Point::new(200.5, 200.5)), "{:?} {:?}", pending.a, pending.b);
|
||||
let Some(DimensionSource::Points { free_a: Some(free_a), free_b: Some(free_b), .. }) = &pending.source else {
|
||||
panic!("{:?}", pending.source)
|
||||
};
|
||||
for free in [free_a, free_b] {
|
||||
assert!(matches!(free, FreePoint::Anchors { node, .. } if *node == part), "{free:?}");
|
||||
}
|
||||
// A 40 point stroke, and an Offset Path effect on the fill, put the corners further from
|
||||
// the path than a click on the path reaches: the points still land there and stay linked.
|
||||
let mut wide = vectorcraft_doc::Appearance::default_art();
|
||||
wide.stroke_mut().expect("a stroke").width = 40.0;
|
||||
let mut offset = vectorcraft_doc::Appearance::default_art();
|
||||
let effect =
|
||||
vectorcraft_doc::Effect { id: "path.offsetPath".into(), params: serde_json::json!({"offset": 30, "joins": "miter"}), visible: true };
|
||||
offset.effects_mut(Some(0)).expect("the fill").push(effect);
|
||||
for (appearance, out) in [(wide, 20.0), (offset, 30.0)] {
|
||||
let mut d = d.clone();
|
||||
d.node_mut(id).expect("the rectangle").appearance = appearance.into();
|
||||
let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) };
|
||||
let mut t = DimensionTool::default();
|
||||
for (x, y) in [(101.0 - out, 101.0 - out), (199.0 + out, 199.0 + out)] {
|
||||
t.pointer(&c, &PointerEvent::new(PointerKind::Move, x, y));
|
||||
t.pointer(&c, &PointerEvent::new(PointerKind::Down, x, y));
|
||||
t.pointer(&c, &PointerEvent::new(PointerKind::Up, x, y));
|
||||
}
|
||||
let pending = t.pending.expect("both points were picked");
|
||||
let (a, b) = (Point::new(100.0 - out, 100.0 - out), Point::new(200.0 + out, 200.0 + out));
|
||||
assert!(near(pending.a, a) && near(pending.b, b), "{out}: {:?} {:?}", pending.a, pending.b);
|
||||
let Some(DimensionSource::Points { free_a: Some(free_a), free_b: Some(free_b), .. }) = &pending.source else {
|
||||
panic!("{out}: {:?}", pending.source)
|
||||
};
|
||||
for free in [free_a, free_b] {
|
||||
assert!(matches!(free, FreePoint::Anchors { node, .. } if *node == id), "{out}: {free:?}");
|
||||
}
|
||||
}
|
||||
// A press on a corner over another path's segment picks the corner when the pointer moves
|
||||
// a few pixels before the release, as on an anchor.
|
||||
let mut d = d.clone();
|
||||
let mut wide = vectorcraft_doc::Appearance::default_art();
|
||||
wide.stroke_mut().expect("a stroke").width = 40.0;
|
||||
d.node_mut(id).expect("the rectangle").appearance = wide.into();
|
||||
let (l, line) = (d.layers[0].id, d.alloc_id());
|
||||
let path = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(0.0, 82.0), Point::new(95.0, 82.0)], false));
|
||||
d.insert(Some(l), 1, Node::path(line, path, Default::default())).expect("the line");
|
||||
let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) };
|
||||
let mut t = DimensionTool::default();
|
||||
assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 81.0, 81.0)).is_empty());
|
||||
assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 85.0, 81.0)).is_empty(), "no segment dimension is dragged out");
|
||||
assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 85.0, 81.0)).is_empty());
|
||||
assert!(t.points.first().is_some_and(|(q, _)| near(*q, Point::new(80.0, 80.0))), "{:?}", t.points);
|
||||
}
|
||||
|
||||
/// With Use Preview Bounds on, hovering by a corner of a stroked path's preview bounds, or
|
||||
/// right on it, shows the anchor ring there.
|
||||
#[test]
|
||||
fn hovering_a_corner_of_the_preview_bounds_shows_the_anchor_ring() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) };
|
||||
for (x, y) in [(101.0, 101.0), (99.5, 99.5)] {
|
||||
let mut t = DimensionTool::default();
|
||||
t.pointer(&c, &PointerEvent::new(PointerKind::Move, x, y));
|
||||
let ring = t
|
||||
.overlays(&c)
|
||||
.into_iter()
|
||||
.any(|o| matches!(o, Overlay::Anchor { p, filled: false, size, .. } if p.distance(Point::new(99.5, 99.5)) < 1e-9 && size == 10.0));
|
||||
assert!(ring, "({x}, {y})");
|
||||
let label = t
|
||||
.snap
|
||||
.guides()
|
||||
.iter()
|
||||
.any(|o| matches!(o, Overlay::Label { p, text, .. } if text == "anchor" && p.distance(Point::new(99.5, 99.5)) < 1e-9));
|
||||
assert!(label, "({x}, {y}): {:?}", t.snap.guides());
|
||||
}
|
||||
}
|
||||
|
||||
/// With Use Preview Bounds on, a corner of the preview bounds takes a pick with Smart Guides and
|
||||
/// Snap to Point off, as an anchor does, and an anchor of other art nearer the pointer than the
|
||||
/// corner takes it from the corner. The point moves with the path, and a later change to the
|
||||
/// stroke weight leaves it where it was.
|
||||
#[test]
|
||||
fn preview_bounds_corners_take_picks_as_anchors_do() {
|
||||
let (d, id) = doc_with_rect();
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let near = |a: Point, b: Point| a.distance(b) < 1e-9;
|
||||
let pick = |c: &ToolContext, at: [(f64, f64); 2]| {
|
||||
let mut t = DimensionTool::default();
|
||||
for (x, y) in at {
|
||||
t.pointer(c, &PointerEvent::new(PointerKind::Move, x, y));
|
||||
t.pointer(c, &PointerEvent::new(PointerKind::Down, x, y));
|
||||
t.pointer(c, &PointerEvent::new(PointerKind::Up, x, y));
|
||||
}
|
||||
t.pending.expect("both points were picked")
|
||||
};
|
||||
let unsnapped = ToolContext { preview_bounds: true, smart_guides: false, snap_to_point: false, ..cx(&d, &s, &p) };
|
||||
let pending = pick(&unsnapped, [(101.0, 101.0), (199.0, 199.0)]);
|
||||
assert!(near(pending.a, Point::new(99.5, 99.5)) && near(pending.b, Point::new(200.5, 200.5)), "{:?} {:?}", pending.a, pending.b);
|
||||
// An unstroked line whose end lies 2.5 points outside the corner.
|
||||
let mut other = d.clone();
|
||||
let (l, line) = (other.layers[0].id, other.alloc_id());
|
||||
let path = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(97.0, 97.0), Point::new(50.0, 50.0)], false));
|
||||
other.insert(Some(l), 1, Node::path(line, path, Default::default())).expect("the line");
|
||||
let c = ToolContext { preview_bounds: true, ..cx(&other, &s, &p) };
|
||||
let pending = pick(&c, [(97.5, 97.5), (199.0, 199.0)]);
|
||||
assert!(near(pending.a, Point::new(97.0, 97.0)), "the line's end is nearer: {:?}", pending.a);
|
||||
let Some(DimensionSource::Points { a: Some(a), .. }) = &pending.source else { panic!("{:?}", pending.source) };
|
||||
assert_eq!(a.node, line);
|
||||
let pending = pick(&c, [(99.0, 99.0), (199.0, 199.0)]);
|
||||
assert!(near(pending.a, Point::new(99.5, 99.5)), "the corner is nearer: {:?}", pending.a);
|
||||
// Right on the rectangle's anchor, with another path's anchor nearer than the corner: that
|
||||
// anchor takes the point, not the rectangle's own anchor on the stroke's centerline.
|
||||
let mut beside = d.clone();
|
||||
let (l, line) = (beside.layers[0].id, beside.alloc_id());
|
||||
let path =
|
||||
vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(100.5, 100.0), Point::new(150.0, 50.0)], false));
|
||||
beside.insert(Some(l), 1, Node::path(line, path, Default::default())).expect("the line");
|
||||
let pending = pick(&ToolContext { preview_bounds: true, ..cx(&beside, &s, &p) }, [(100.0, 100.0), (199.0, 199.0)]);
|
||||
let Some(DimensionSource::Points { a: Some(a), .. }) = &pending.source else { panic!("{:?}", pending.source) };
|
||||
assert!(near(pending.a, Point::new(100.5, 100.0)) && a.node == line, "{:?} {a:?}", pending.a);
|
||||
// The point held against the rectangle moves with it and stays put when the stroke changes.
|
||||
let pending = pick(&ToolContext { preview_bounds: true, ..cx(&d, &s, &p) }, [(101.0, 101.0), (199.0, 199.0)]);
|
||||
let Some(DimensionSource::Points { free_a: Some(free), .. }) = &pending.source else { panic!("{:?}", pending.source) };
|
||||
let mut moved = d.clone();
|
||||
moved.node_mut(id).expect("the rectangle").transform(vectorcraft_geom::Affine::translate((10.0, 0.0)), false);
|
||||
assert!(free.position(&moved).is_some_and(|q| near(q, Point::new(109.5, 99.5))), "{:?}", free.position(&moved));
|
||||
let mut wider = d.clone();
|
||||
let mut wide = vectorcraft_doc::Appearance::default_art();
|
||||
wide.stroke_mut().expect("a stroke").width = 40.0;
|
||||
wider.node_mut(id).expect("the rectangle").appearance = wide.into();
|
||||
assert!(free.position(&wider).is_some_and(|q| near(q, Point::new(99.5, 99.5))), "{:?}", free.position(&wider));
|
||||
// Scaled 200% with Scale Strokes off, the point moves with the anchors and no longer sits
|
||||
// on the corner of the preview bounds, which the 1 point stroke puts at (199.5, 199.5).
|
||||
let mut scaled = d.clone();
|
||||
scaled.node_mut(id).expect("the rectangle").transform(vectorcraft_geom::Affine::scale(2.0), false);
|
||||
assert!(free.position(&scaled).is_some_and(|q| near(q, Point::new(199.0, 199.0))), "{:?}", free.position(&scaled));
|
||||
}
|
||||
|
||||
/// With Use Preview Bounds on, a corner takes the pick only from the anchors at the same corner
|
||||
/// of its object's geometric bounds. The other anchors of a small stroked circle stay
|
||||
/// pickable, so does the end of another line lying on the anchor the corner stands in for, and
|
||||
/// of two stroked rectangles sharing an edge, each corner of the shared anchors is held against
|
||||
/// its own rectangle.
|
||||
#[test]
|
||||
fn a_corner_takes_only_the_anchor_it_stands_for() {
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let near = |a: Point, b: Point| a.distance(b) < 1e-9;
|
||||
let mut d = vectorcraft_doc::Document::new(500.0, 500.0);
|
||||
let (l, circle) = (d.layers[0].id, d.alloc_id());
|
||||
let path = vectorcraft_geom::shapes::ellipse(Rect::new(296.0, 296.0, 304.0, 304.0));
|
||||
d.insert(Some(l), 0, Node::path(circle, path, vectorcraft_doc::Appearance::default_art())).expect("the circle");
|
||||
let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) };
|
||||
let mut t = DimensionTool::default();
|
||||
let (q, reference) = t.snap_linear(&c, Point::new(300.0, 296.0));
|
||||
assert!(near(q, Point::new(300.0, 296.0)) && reference.is_some_and(|r| r.node == circle), "{q:?}");
|
||||
let (q, reference) = t.snap_linear(&c, Point::new(296.5, 296.5));
|
||||
assert!(near(q, Point::new(295.5, 295.5)) && reference.is_none() && t.corner == Some(circle), "{q:?}");
|
||||
// An unstroked line ending right on the rectangle's anchor: a click there picks the line's
|
||||
// end, and a click nearer the corner picks the corner.
|
||||
let (mut d, id) = doc_with_rect();
|
||||
let (l, line) = (d.layers[0].id, d.alloc_id());
|
||||
let path =
|
||||
vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(100.0, 100.0), Point::new(50.0, 20.0)], false));
|
||||
d.insert(Some(l), 1, Node::path(line, path, Default::default())).expect("the line");
|
||||
let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) };
|
||||
let mut t = DimensionTool::default();
|
||||
let (q, reference) = t.snap_linear(&c, Point::new(100.0, 100.0));
|
||||
assert!(near(q, Point::new(100.0, 100.0)) && reference.is_some_and(|r| r.node == line), "{q:?}");
|
||||
let (q, reference) = t.snap_linear(&c, Point::new(99.6, 99.6));
|
||||
assert!(near(q, Point::new(99.5, 99.5)) && reference.is_none() && t.corner == Some(id), "{q:?}");
|
||||
// Another path's end right on the corner: a click on the rectangle's anchor picks that end.
|
||||
let (mut d, _) = doc_with_rect();
|
||||
let (l, line) = (d.layers[0].id, d.alloc_id());
|
||||
let path = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(99.5, 99.5), Point::new(50.0, 20.0)], false));
|
||||
d.insert(Some(l), 0, Node::path(line, path, Default::default())).expect("the line");
|
||||
let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) };
|
||||
let mut t = DimensionTool::default();
|
||||
let (q, reference) = t.snap_linear(&c, Point::new(100.0, 100.0));
|
||||
assert!(near(q, Point::new(99.5, 99.5)) && reference.as_ref().is_some_and(|r| r.node == line), "{q:?} {reference:?}");
|
||||
// A stroked dot, a path whose two anchors coincide, cannot hold a point at a corner: a
|
||||
// click by it picks its anchor.
|
||||
let mut d = vectorcraft_doc::Document::new(500.0, 500.0);
|
||||
let (l, dot) = (d.layers[0].id, d.alloc_id());
|
||||
let path =
|
||||
vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(300.0, 300.0), Point::new(300.0, 300.0)], false));
|
||||
let mut round = vectorcraft_doc::Appearance::default_art();
|
||||
let stroke = round.stroke_mut().expect("a stroke");
|
||||
(stroke.width, stroke.cap) = (10.0, vectorcraft_doc::LineCap::Round);
|
||||
d.insert(Some(l), 0, Node::path(dot, path, round)).expect("the dot");
|
||||
let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) };
|
||||
let mut t = DimensionTool::default();
|
||||
let (q, reference) = t.snap_linear(&c, Point::new(296.0, 296.0));
|
||||
assert!(near(q, Point::new(300.0, 300.0)) && reference.is_some_and(|r| r.node == dot) && t.corner.is_none(), "{q:?}");
|
||||
// A stroked rectangle made into a guide, and a stroked member of a compound path without
|
||||
// a stroke of its own, give no corners.
|
||||
for kind in ["guide", "member"] {
|
||||
let (mut d, id) = doc_with_rect();
|
||||
let mut wide = vectorcraft_doc::Appearance::default_art();
|
||||
wide.stroke_mut().expect("a stroke").width = 40.0;
|
||||
if kind == "guide" {
|
||||
let n = d.node_mut(id).expect("the rectangle");
|
||||
n.appearance = wide.into();
|
||||
if let NodeKind::Path { guide, .. } = &mut n.kind {
|
||||
*guide = true;
|
||||
}
|
||||
} else {
|
||||
let mut fresh = vectorcraft_doc::Document::new(500.0, 500.0);
|
||||
let (l, part, whole) = (fresh.layers[0].id, fresh.alloc_id(), fresh.alloc_id());
|
||||
let mut member = Node::path(part, vectorcraft_geom::shapes::rectangle(Rect::new(100.0, 100.0, 200.0, 200.0)), Default::default());
|
||||
member.appearance = wide.into();
|
||||
let n = Node::new(whole, NodeKind::Compound { children: vec![std::sync::Arc::new(member)], rule: Default::default() });
|
||||
fresh.insert(Some(l), 0, n).expect("the compound path");
|
||||
d = fresh;
|
||||
}
|
||||
let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) };
|
||||
let mut t = DimensionTool::default();
|
||||
let (q, _) = t.snap_linear(&c, Point::new(81.0, 81.0));
|
||||
assert!(!near(q, Point::new(80.0, 80.0)) && t.corner.is_none(), "{kind}: {q:?}");
|
||||
}
|
||||
// Two stroked rectangles sharing the edge x = 200; the right one is on top.
|
||||
let (mut d, left) = doc_with_rect();
|
||||
let (l, right) = (d.layers[0].id, d.alloc_id());
|
||||
let path = vectorcraft_geom::shapes::rectangle(Rect::new(200.0, 100.0, 300.0, 200.0));
|
||||
d.insert(Some(l), 1, Node::path(right, path, vectorcraft_doc::Appearance::default_art())).expect("the right rectangle");
|
||||
let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) };
|
||||
for (pointer, corner, holder) in [((200.4, 99.6), (200.5, 99.5), left), ((199.6, 99.6), (199.5, 99.5), right)] {
|
||||
let mut t = DimensionTool::default();
|
||||
for kind in [PointerKind::Move, PointerKind::Down, PointerKind::Up] {
|
||||
t.pointer(&c, &PointerEvent::new(kind, pointer.0, pointer.1));
|
||||
}
|
||||
for kind in [PointerKind::Move, PointerKind::Down, PointerKind::Up] {
|
||||
t.pointer(&c, &PointerEvent::new(kind, 250.0, 300.0));
|
||||
}
|
||||
let pending = t.pending.expect("both points were picked");
|
||||
assert!(near(pending.a, Point::new(corner.0, corner.1)), "{pointer:?}: {:?}", pending.a);
|
||||
let Some(DimensionSource::Points { a: None, free_a: Some(free), .. }) = &pending.source else { panic!("{:?}", pending.source) };
|
||||
assert!(matches!(free, FreePoint::Anchors { node, .. } if *node == holder), "{pointer:?}: {free:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A point is held against a path for a corner of its preview bounds only when it was picked
|
||||
/// there: the same position picked another way links to the segment under it.
|
||||
#[test]
|
||||
fn a_point_is_held_for_a_corner_only_when_picked_on_it() {
|
||||
let (mut d, id) = doc_with_rect();
|
||||
let (l, line) = (d.layers[0].id, d.alloc_id());
|
||||
let path = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(0.0, 99.5), Point::new(300.0, 99.5)], false));
|
||||
d.insert(Some(l), 1, Node::path(line, path, Default::default())).expect("the line");
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) };
|
||||
let (corner, b) = (Point::new(99.5, 99.5), Point::new(250.0, 99.5));
|
||||
for (held, node) in [(Some(id), id), (None, line)] {
|
||||
let source = points_source(&c, (corner, &None, held), (b, &None, None));
|
||||
let Some(DimensionSource::Points { free_a: Some(free), .. }) = &source else { panic!("{source:?}") };
|
||||
let linked = match free {
|
||||
FreePoint::Anchors { node, .. } => *node,
|
||||
FreePoint::OnSegment { edge, .. } => edge.node,
|
||||
};
|
||||
assert_eq!(linked, node, "{held:?}: {free:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Hovering right on the end of a dimension's line shows the anchor ring there.
|
||||
#[test]
|
||||
fn hovering_right_on_a_dimension_lines_end_shows_the_anchor_ring() {
|
||||
let mut d = vectorcraft_doc::Document::new(500.0, 500.0);
|
||||
let (l, id) = (d.layers[0].id, d.alloc_id());
|
||||
let path =
|
||||
vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(300.0, 300.0), Point::new(400.0, 300.0)], false));
|
||||
let mut n = Node::path(id, path, Default::default());
|
||||
let recipe = DimensionTool::default().recipe(DimensionMode::Linear, Point::new(0.0, 0.0), Point::new(50.0, 0.0), Point::ZERO, None);
|
||||
n.extras_mut().dimension = Some(Box::new(recipe));
|
||||
d.insert(Some(l), 0, n).expect("the dimension's line");
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let c = ToolContext { smart_guides: true, snap_to_point: true, ..cx(&d, &s, &p) };
|
||||
let mut t = DimensionTool::default();
|
||||
t.pointer(&c, &PointerEvent::new(PointerKind::Move, 300.0, 300.0));
|
||||
let ring = t
|
||||
.overlays(&c)
|
||||
.into_iter()
|
||||
.any(|o| matches!(o, Overlay::Anchor { p, filled: false, size, .. } if p.distance(Point::new(300.0, 300.0)) < 1e-9 && size == 10.0));
|
||||
assert!(ring, "{:?}", t.overlays(&c));
|
||||
}
|
||||
|
||||
/// The anchors of a live rectangle are picked the same way.
|
||||
#[test]
|
||||
fn a_press_on_a_live_shapes_anchor_picks_it() {
|
||||
|
||||
@@ -1674,7 +1674,7 @@ impl DirectSelectionTool {
|
||||
// marquee or an Alt-marquee, every object it touches, each whole (#8047).
|
||||
if enclosed || whole || self.group {
|
||||
(self.spine, self.spine_more) = (None, vec![]);
|
||||
let mut touched = vectorcraft_doc::hit::marquee_in_view(cx.doc, r, cx.isolation, true, cx.outline);
|
||||
let mut touched = vectorcraft_doc::hit::marquee_in_view(cx.doc, r, cx.isolation, true, cx.outline, !cx.guides);
|
||||
let editable = cx.doc.editable();
|
||||
touched.retain(|id| editable(*id));
|
||||
let picked = if enclosed { crate::select::inside(cx, r, touched) } else { touched };
|
||||
@@ -1684,8 +1684,11 @@ impl DirectSelectionTool {
|
||||
}
|
||||
// Anchors inside the rect, on editable paths inside isolation mode.
|
||||
let mut sel: Vec<(NodeId, Vec<AnchorRef>)> = vec![];
|
||||
// Guide paths only while guides can be picked: not while they are locked or hidden (#8538).
|
||||
walk_pickable(cx.doc, cx.isolation, |n| {
|
||||
if let NodeKind::Path { path, .. } = &n.kind {
|
||||
if let NodeKind::Path { path, guide, .. } = &n.kind
|
||||
&& (cx.guides || !*guide)
|
||||
{
|
||||
let v: Vec<AnchorRef> = path.anchors().filter(|(_, _, a)| r.contains(a.p)).map(|(s, i, _)| (s, i)).collect();
|
||||
if !v.is_empty() {
|
||||
sel.push((n.id, v));
|
||||
@@ -1773,7 +1776,7 @@ impl DirectSelectionTool {
|
||||
}
|
||||
// Objects without anchors to pick (type, images, symbols…) are selected whole when
|
||||
// the marquee touches them, as with the Selection tool (#927).
|
||||
for id in vectorcraft_doc::hit::marquee_in_view(cx.doc, r, cx.isolation, true, cx.outline) {
|
||||
for id in vectorcraft_doc::hit::marquee_in_view(cx.doc, r, cx.isolation, true, cx.outline, !cx.guides) {
|
||||
let whole = cx.doc.node(id).is_some_and(|n| !matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }));
|
||||
if whole && !sel.iter().any(|(s, _)| *s == id) && !framed.iter().any(|(f, _)| *f == id) && !meshed.contains(&id) && spined != Some(id) {
|
||||
sel.push((id, vec![]));
|
||||
@@ -1785,7 +1788,8 @@ impl DirectSelectionTool {
|
||||
let mut crossed: Vec<(NodeId, Vec<AnchorRef>)> = vec![];
|
||||
if !self.group {
|
||||
walk_pickable(cx.doc, cx.isolation, |n| {
|
||||
if let NodeKind::Path { path, .. } = &n.kind
|
||||
if let NodeKind::Path { path, guide, .. } = &n.kind
|
||||
&& (cx.guides || !*guide)
|
||||
&& editable(n.id)
|
||||
{
|
||||
let segs = crossed_segments(path, r);
|
||||
|
||||
Loaded 100 of 224 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user