Merge main into fix/flare-lone-x2-y2-error

This commit is contained in:
dotCooCoo committed 2026-11-20 19:55:07 -08:00
commit b763053289
63 files changed
+4610 -292

No files matched your search

+9 -3
View File
@@ -78,6 +78,9 @@ pub struct HitOptions {
/// Off, the empty part of the frame (away from its edge and its lines of type) takes no
/// clicks, so they reach the art behind (#7274).
pub area_type_interior: bool,
/// The point hit tests ([`hit_test`], [`hit_test_visible`] and [`hit_test_visible_skipping`])
/// hit the art on a layer whose Preview is off as painted, not in outline.
pub ignore_layer_preview: bool,
}
impl Default for HitOptions {
@@ -90,6 +93,7 @@ impl Default for HitOptions {
skip_guides: false,
clip_outlines: false,
area_type_interior: false,
ignore_layer_preview: false,
scope: None,
}
}
@@ -847,7 +851,7 @@ fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(No
continue;
}
chain.push(layer.id);
let opt = if matches!(layer.kind, NodeKind::Layer { preview: false, .. }) { HitOptions { outline: true, ..opt } } else { opt };
let opt = if !opt.ignore_layer_preview && previews_off(layer) { HitOptions { outline: true, ..opt } } else { opt };
if let Some(h) = hit_children(layer, p, opt, &symbols, skip, &mut chain, editable_only) {
return Some(finish(h));
}
@@ -1211,7 +1215,9 @@ fn hit_children(
chain.push(c.id);
let hit = plain(i == 0 && clip.is_some(), || match &c.kind {
// A sublayer whose Preview is off is clicked in outline, like an outline view.
NodeKind::Layer { preview: false, .. } => hit_children(c, p, HitOptions { outline: true, ..opt }, symbols, skip, chain, editable_only),
NodeKind::Layer { preview: false, .. } if !opt.ignore_layer_preview => {
hit_children(c, p, HitOptions { outline: true, ..opt }, symbols, skip, chain, editable_only)
}
NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Intertwine { .. } => {
hit_children(c, p, opt, symbols, skip, chain, editable_only)
}
@@ -1325,7 +1331,7 @@ fn art_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, accept: &
match &n.kind {
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } | NodeKind::Intertwine { children } => {
// A layer with Preview off is clicked in outline, as [`hit_children`] clicks it.
let opt = HitOptions { outline: opt.outline || previews_off(n), ..opt };
let opt = HitOptions { outline: opt.outline || !opt.ignore_layer_preview && previews_off(n), ..opt };
if n.clips()
&& let Some(clip) = children.first()
{
+1
View File
@@ -1463,6 +1463,7 @@ const SELECTING: HitOptions = HitOptions {
skip_guides: false,
clip_outlines: true,
area_type_interior: false,
ignore_layer_preview: false,
scope: None,
};
+3 -2
View File
@@ -583,9 +583,10 @@ pub fn pathfinder_children(doc: Option<&Document>, group: &Node, hook: Option<Ou
let own_fill = has_visible_fill(group);
// A compound shape's area has no paint of its own: the shape's own appearance paints it. The
// shape's top painting fill is the area's fill for Remove Unpainted Artwork and for Outline's
// strokes, while Divide pieces stay unpainted so that the fill is not drawn twice.
// strokes, while Divide pieces stay unpainted so that the fill is not drawn twice. The shape's
// strokes stay out: the shape's own appearance already strokes the result.
let area_style = group.is_compound_shape().then(|| {
let items = group.appearance.items.iter().filter(|i| paints(i)).cloned().collect();
let items = top_painting_fill(&group.appearance).cloned().into_iter().collect();
Node::path(group.id, PathData::default(), Appearance { items, ..Default::default() })
});
let style_of = |s: &Node| -> Option<Node> {
+19
View File
@@ -306,6 +306,25 @@ fn outline_strokes_a_compound_shapes_area_in_its_fill() {
}
}
/// Outline of a compound shape with no fill gives the edges no paint of their own when Remove
/// Unpainted Artwork is off. The shape's own appearance strokes the result, so the shape's stroke
/// is not copied onto the edges.
#[test]
fn outline_of_an_unfilled_compound_shape_adds_no_stroke() {
let mut g = compound_shape(ShapeMode::Add);
let mut a = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 4.0);
if let Some(AppearanceItem::Stroke(s)) = a.items.last_mut() {
s.opacity = 0.5;
}
g.appearance = a.into();
g.appearance.effects.push(Effect { id: "pathfinder.outline".into(), params: serde_json::json!({"removeUnpainted": false}), visible: true });
let out = pathfinder_children(None, &g, None).unwrap();
assert!(!out.is_empty(), "{out:#?}");
for n in &out {
assert!(!n.appearance.items.iter().any(paints), "{n:#?}");
}
}
/// With Remove Unpainted Artwork, Divide keeps the pieces of an unfilled member when its group's
/// own visible fill paints them and leaves them out when the group has no fill. Outline leaves out
/// the member's segments either way.
+30 -2
View File
@@ -67,7 +67,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Clear Appearance",
["Window", "Appearance"],
None,
"{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own) and reset its opacity and blend mode. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind",
"{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own; in the contents of a Live Paint group, a face one empty fill and an edge one empty stroke) and reset its opacity and blend mode. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind",
has_doc,
clear_appearance
),
@@ -76,7 +76,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Reduce to Basic Appearance",
["Window", "Appearance"],
None,
"{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes)",
"{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked; in the contents of a Live Paint group, a face keeps only the fill and an edge only the stroke), and drop the object's effects. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes)",
has_doc,
reduce_basic
),
@@ -529,6 +529,24 @@ pub(crate) fn contents_skipped(s: &Session, p: &Value, fill: bool) -> Result<Has
Ok(super::paint::live_paint_parts_skipped(&s.doc()?.doc, &appearance_roots(s, p)?, fill))
}
/// The faces and the edges of the Live Paint groups whose contents `p` targets (`target: "contents"`). A command that
/// gives them a whole appearance gives a face only its fill rows and an edge only its stroke rows
/// ([`keep_rows_of_kind`]). Both are empty without `target: "contents"`.
pub(crate) fn contents_parts(s: &Session, p: &Value) -> Result<(HashSet<NodeId>, HashSet<NodeId>)> {
if !targets_contents(p)? {
return Ok((HashSet::new(), HashSet::new()));
}
let (faces, edges, _) = super::paint::live_paint_split(&s.doc()?.doc, &appearance_roots(s, p)?);
Ok((faces, edges))
}
/// Remove from `n` its stroke rows (`fill`) or its fill rows: a Live Paint face draws fills and an edge strokes.
pub(crate) fn keep_rows_of_kind(n: &mut Node, fill: bool) {
if n.appearance.items.iter().any(|it| it.is_fill() != fill) {
n.appearance.items.retain(|it| it.is_fill() == fill);
}
}
/// The refusal of an appearance edit whose targets are all the art of graph designs drawn in graph series.
const DESIGN_ART: &str = "the art of a graph design in a graph series is drawn again from the design: edit the design to change it";
@@ -1044,12 +1062,17 @@ fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
fn clear_appearance(s: &mut Session, p: &Value) -> Result<Value> {
let ids = require_whole_targets(s, p, "appearance.clear")?;
let (faces, edges) = contents_parts(s, p)?;
// When every object is cleared already, the document and its undo history stay as they are.
let before = s.doc()?.doc.clone();
super::overprint::edit_counted(s, "Clear Appearance", |d| {
for id in &ids {
if let Some(n) = d.node_mut(*id) {
clear(n);
// A Live Paint group's face keeps an empty fill and its edge an empty stroke.
if faces.contains(id) || edges.contains(id) {
keep_rows_of_kind(n, faces.contains(id));
}
super::object::snap_if_aligned(n);
}
}
@@ -1284,6 +1307,7 @@ fn is_group(n: &Node) -> bool {
fn reduce_basic(s: &mut Session, p: &Value) -> Result<Value> {
let ids = require_whole_targets(s, p, "appearance.reduceToBasic")?;
let (faces, edges) = contents_parts(s, p)?;
// When every object comes out as it was, the document and its undo history stay as they are.
let before = s.doc()?.doc.clone();
// The Appearance panel's active row (a row of the first selected object's stack, and in each
@@ -1322,6 +1346,10 @@ fn reduce_basic(s: &mut Session, p: &Value) -> Result<Value> {
st.blend = BlendMode::Normal;
n.appearance.items.push(AppearanceItem::Stroke(st));
}
// A Live Paint group's face keeps only its fill and its edge only its stroke.
if faces.contains(id) || edges.contains(id) {
keep_rows_of_kind(n, faces.contains(id));
}
super::object::snap_if_aligned(n);
}
}
+2 -2
View File
@@ -48,7 +48,7 @@ use dynamic::{symbol_instance_reset, symbol_instance_select_part, symbol_instanc
use symbolism::symbol_set_density;
use symbols::selected_instances;
pub(crate) use symbols::{
expand_instances_under, expandable_instances, instance_in_place, natural_size, normalize, place_xf, set_natural_size, store_symbol,
Placement, expand_instances_under, expandable_instances, instance_in_place, natural_size, normalize, place_xf, set_natural_size, store_symbol,
stored_natural_size,
};
use symbols::{
@@ -234,7 +234,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Place Symbol Instance",
[],
None,
"{name?, x?, y?} place an instance so its registration point is at (x, y) (default: artboard centre; name default: current) → {id}",
"{name?, x?, y?} place an instance so its registration point is at (x, y) (default: artboard centre; name default: current), on top of the current layer, or in Draw Behind directly below the bottommost selected object (at the bottom of the current layer with nothing selected) → {id}",
has_doc,
symbol_place
),
+36 -2
View File
@@ -33,6 +33,40 @@ pub(crate) fn place_xf(at: Point, (w, h): (f64, f64), reg: SymbolRegistration) -
Affine::translate(c.to_vec2()) * Affine::scale_non_uniform(w / (2.0 * HALF), h / (2.0 * HALF))
}
/// Where a placed symbol instance goes in the active document, worked out before the edit from
/// the drawing mode, the selection and the layer new art goes into.
pub(crate) struct Placement {
parent: Option<NodeId>,
behind: bool,
anchor: Option<NodeId>,
}
impl Placement {
/// On top of the layer new art goes into; in Draw Behind, directly below the bottommost
/// selected object (beside the compound path that holds it), or at the bottom of that layer
/// when nothing is selected. An error when that layer is locked or hidden.
pub(crate) fn of(s: &Session) -> Result<Self> {
let st = s.doc()?;
let parent = st.target_parent()?;
let behind = s.draw_mode == crate::DrawMode::Behind;
let compound_of = |id: NodeId| st.doc.parent_of(id).filter(|p| st.doc.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })));
let anchor = behind.then(|| st.selection.in_paint_order(&st.doc).first().copied()).flatten().map(|id| compound_of(id).unwrap_or(id));
Ok(Self { parent, behind, anchor })
}
/// Inserts instance `n` where this placement puts it. In a clip group or a clipping layer the
/// clipping path stays at the bottom.
pub(crate) fn insert(&self, d: &mut Document, n: Node) -> Result<NodeId> {
let (parent, index) = match (self.behind, self.anchor.and_then(|a| d.position(a))) {
(false, _) => return Ok(d.insert(self.parent, usize::MAX, n)?),
(true, Some((par, i, _))) => (par, i),
(true, None) => (self.parent, 0),
};
let floor = usize::from(parent.and_then(|p| d.node(p)).is_some_and(Node::clips));
Ok(d.insert(parent, index.max(floor), n)?)
}
}
fn registration_param(p: &Value, cmd: &str) -> Result<Option<SymbolRegistration>> {
match p.get("registration") {
None => Ok(None),
@@ -437,10 +471,10 @@ pub(super) fn symbol_place(s: &mut Session, p: &Value) -> Result<Value> {
let at = Point::new(number_or(p, "x", centre.x, "symbol.place")?, number_or(p, "y", centre.y, "symbol.place")?);
let size = natural_size(d, &name);
let reg = d.symbol_registration(&name);
let parent = s.doc()?.target_parent()?;
let spot = Placement::of(s)?;
let id = s.edit("Place Symbol Instance", |d, sel| {
let id = d.alloc_id();
d.insert(parent, usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: name.clone(), xf: place_xf(at, size, reg) }))?;
spot.insert(d, Node::new(id, NodeKind::SymbolInstance { symbol: name.clone(), xf: place_xf(at, size, reg) }))?;
sel.set([id]);
Ok(id)
})?;
+8 -2
View File
@@ -97,7 +97,7 @@ fn effect_specs() -> Vec<CommandSpec> {
"Expand Appearance",
["Object"],
None,
"{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry or raster effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them, its raster effects an image as for other objects; a symbol instance in that art whose topmost fill or stroke has such an effect (its own or one the outer instance passes on) becomes its art and image in turn. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. One expansion makes at most 1,024 images of raster effects, 256 megapixels in all (VectorCraft's own limits): an object or symbol instance whose image would go past them stays as it is, with its effects, and when nothing else expands that is an error. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says; or raster effects were left past the limits), rasterLeft? (how many objects were left so)}",
"{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry or raster effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them, its raster effects an image as for other objects; a symbol instance in that art whose topmost fill or stroke has such an effect (its own or one the outer instance passes on) becomes its art and image in turn. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. One expansion makes at most 1,024 images of raster effects, 256 megapixels in all (VectorCraft's own limits): an object or symbol instance whose image would go past them stays as it is, with its effects, and when nothing else expands that is an error. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places, a plain instance in a group or layer whose raster effect makes an image of it included) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says; or raster effects were left past the limits), rasterLeft? (how many objects were left so)}",
can_expand,
expand_appearance
),
@@ -1611,13 +1611,18 @@ fn expanded_node(
/// Does `n`, an object in it, or the art of a symbol placed in it hold a plug-in effect that
/// expanding it draws: a visible one, the object's own or a visible fill's or stroke's, on an
/// object that expands ([`expandable`]; in a symbol's art, `in_art`, every object does). A symbol's
/// object that expands ([`expandable`]; in a symbol's art, `in_art`, every object does, and so does
/// every object in a group or layer with a raster effect, whose image draws all of it). A symbol's
/// art counts where an instance of it expands. `seen` holds the symbols already looked into.
fn holds_plugin_effect(d: &Document, n: &Node, in_art: bool, seen: &mut std::collections::HashSet<String>) -> bool {
let plugin = |e: &Effect| e.visible && vectorcraft_plugins::effect::plugin_id(&e.id).is_some();
let mut symbols = vec![];
let mut drawn = vec![];
let mut holds = false;
n.walk(&mut |c| {
if !in_art && is_container(c) && !rasterfx::raster_fx(c).is_empty() {
drawn.push(c);
}
if !in_art && !expandable(c) {
return;
}
@@ -1627,6 +1632,7 @@ fn holds_plugin_effect(d: &Document, n: &Node, in_art: bool, seen: &mut std::col
}
});
holds
|| drawn.into_iter().any(|g| holds_plugin_effect(d, g, true, seen))
|| symbols.into_iter().any(|name| {
seen.insert(name.clone()) && d.symbols.iter().find(|s| s.name == name).is_some_and(|s| holds_plugin_effect(d, &s.art, true, seen))
})
@@ -332,6 +332,36 @@ fn pasted_type_brings_its_kinsoku_sets() {
assert_eq!(style_set(&s), Value::Null);
}
/// Type pasted back after its set was edited breaks its lines by the set as it is now: with B in
/// Cannot End Line the first line of `A B C` ends at A, and once the set holds nothing, it ends at B.
#[test]
fn pasted_type_relayouts_after_its_kinsoku_set_was_edited() {
let mut s = session();
s.execute("type.kinsokuSets.set", &json!({"sets": [{"name": "Tight", "cannotEnd": "B"}]})).unwrap();
let create = json!({"x": 10, "y": 10, "text": "A B C", "size": 20, "font": "JetBrains Mono", "area": {"width": 40, "height": 120}});
let id = s.execute("text.create", &create).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
s.execute("text.setFormat", &json!({"kinsoku": "Tight"})).unwrap();
let lines = |t: &vectorcraft_doc::TextObject| t.baselines().collect::<Vec<_>>();
let first_width = |t: &vectorcraft_doc::TextObject| t.baselines().next().map(|(a, b)| b.x - a.x).unwrap_or_default();
let copied = text(&s, id);
s.execute("edit.copy", &json!({})).unwrap();
s.execute("type.kinsokuSets.set", &json!({"sets": [{"name": "Tight"}]})).unwrap();
// The set's edit lays the type in the document out anew, and its first line takes B.
let edited = text(&s, id);
assert_eq!(lines(&edited).len(), 2);
assert!(first_width(&edited) > first_width(&copied), "{:?} against {:?}", lines(&edited), lines(&copied));
let v = s.execute("edit.paste", &json!({})).unwrap();
let t = text(&s, v["ids"][0].as_u64().unwrap());
let now = s.doc().unwrap().doc.kinsoku_sets[0].clone();
assert_eq!(t.para_at(0).kinsoku_set.as_deref(), Some(&now));
let mut fresh = t.clone();
crate::cmd::typecmd::refresh_bounds(&mut fresh);
assert_eq!(lines(&t), lines(&fresh), "the pasted type is laid out with the edited set");
assert_eq!(first_width(&t), first_width(&edited));
}
/// A pasted set whose name, at the longest a name can be, the document's set with other
/// characters already has comes in under a free name that fits: the number takes the place of the
/// name's last characters, and a space left at the end of them is dropped. A second paste uses
+581 -75
View File
@@ -13,8 +13,14 @@
//! per line of glyphs, with the first glyph's fill and stroke. A line whose glyphs are evenly spaced
//! apart takes that spacing as its tracking ([`Line::tracked`]), and lines stacked at one leading
//! and lined up at their starts, ends or centers become one area type object ([`blocks`]). 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.
//! that match no font stay as they are and are reported.
//!
//! With a `tolerance`, a shape that matches no glyph exactly may still nearly match one: another
//! version of the font, or the outline simplified or built another way
//! ([`RetypeIndex::near_matches`]); each line reports how closely its glyphs fit. A compound path
//! holding several glyphs (a word outlined as one path) is split into its glyphs
//! ([`vectorcraft_text::retype::clusters`]), and becomes type only when every one of them does.
//! The tolerance, the score and the splitting rules are VectorCraft's own. Images are phase 2.
use std::f64::consts::{PI, TAU};
use std::sync::Arc;
@@ -22,6 +28,7 @@ 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_geom::FillRule;
use vectorcraft_text::FontDb;
use vectorcraft_text::retype::{GlyphMatch, RetypeIndex};
@@ -41,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Retype",
["Type"],
None,
"{fonts?: [family…]} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: 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 unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, 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 (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool)}], unmatched: [id…], truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error when no shape matches",
"{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only)} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: 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; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups, 512 contours and 65,536 path elements, and 16,384 contours per command) is split into them, and becomes type only when every one of them matches; matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it), and before a near-matched glyph the line's size and turn would draw further from its shape than the tolerance; a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a counter narrower than three times the outline tolerance across in some direction, an outline too large to check, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, or that overlap at all when the compound has an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke, also keep the shape an outline); 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 (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are when another shape became type), truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error, with no unmatched list, when no shape becomes type, or when tolerance is not a number from 0 to 0.05",
has_selected_path,
retype
)]
@@ -60,6 +67,10 @@ struct Piece {
/// art must stay painted after it: the line ends here.
after_barrier: bool,
path: BezPath,
/// The shape is filled by the nonzero rule, not the even-odd rule.
nonzero: bool,
/// The shape has a visible fill: a shape that only has a stroke paints no area to compare.
filled: bool,
appearance: Appearance,
/// The shape's own transparency, which the new type takes.
opacity: f32,
@@ -83,11 +94,13 @@ fn collect(n: &Node, parent: Option<NodeId>, depth: usize, barrier: &mut bool, t
*barrier = true;
return;
}
let piece = |path: BezPath, after_barrier: bool| Piece {
let piece = |path: BezPath, after_barrier: bool, rule: FillRule| Piece {
id: n.id,
parent,
after_barrier,
path,
nonzero: rule == FillRule::NonZero,
filled: n.appearance.fill().is_some_and(|f| f.visible && !f.paint.is_none()),
appearance: (*n.appearance).clone(),
opacity: n.opacity,
blend: n.blend,
@@ -100,8 +113,10 @@ fn collect(n: &Node, parent: Option<NodeId>, depth: usize, barrier: &mut bool, t
}
}
// 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, .. } => {
NodeKind::Path { path, rule, clipping: false, guide: false, .. } if path.is_closed() => {
out.push(piece(path.to_bezpath(), std::mem::take(barrier), *rule))
}
NodeKind::Compound { children, rule } => {
let mut path = BezPath::new();
for c in children {
match &c.kind {
@@ -113,7 +128,7 @@ fn collect(n: &Node, parent: Option<NodeId>, depth: usize, barrier: &mut bool, t
}
}
}
out.push(piece(path, std::mem::take(barrier)));
out.push(piece(path, std::mem::take(barrier), *rule));
}
// Live type, images, clip groups and the rest stay, and the type after them stays after them.
_ => *barrier = true,
@@ -185,6 +200,9 @@ struct Line {
parent: Option<NodeId>,
opacity: f32,
blend: vectorcraft_color::BlendMode,
/// The tolerance near matches were taken with (0: exact only): a near-matched glyph may differ
/// that much in size, turn and place from the rest of its line ([`Self::slack_for`]).
slack: f64,
}
impl Line {
@@ -192,6 +210,12 @@ impl Line {
Vec2::new(self.angle.cos(), self.angle.sin())
}
/// The slack glyph `m` of this line is allowed: [`Self::slack`] when `m` or the line's first
/// glyph, whose size and turn the line takes, is a near match, else 0.
fn slack_for(&self, m: &GlyphMatch) -> f64 {
if m.exact && self.matches.first().is_none_or(|f| f.exact) { 0.0 } else { self.slack }
}
/// 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 {
@@ -199,15 +223,16 @@ impl Line {
let d = m.origin - self.origin;
let dir = self.dir();
let across = d.cross(dir).abs();
let slack = self.slack_for(m);
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
&& (m.scale - self.scale).abs() <= self.scale * slack.max(1e-4)
// Wrapped: type turned 180° has angles near +π and −π.
&& ((m.angle - self.angle + PI).rem_euclid(TAU) - PI).abs() < 1e-5
&& ((m.angle - self.angle + PI).rem_euclid(TAU) - PI).abs() < slack.max(1e-5)
&& across < size * 0.05
// After the line's end, or, for type tracked tighter than that, still ahead of the
// last glyph's start (by more than rounding); the layout check decides whether it fits.
@@ -319,6 +344,7 @@ impl Line {
parent: self.parent,
opacity: self.opacity,
blend: self.blend,
slack: self.slack,
};
for (id, m) in ids.iter().zip(ms).skip(1) {
l.push(*id, m);
@@ -370,7 +396,7 @@ impl Line {
/// (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> {
first_mismatch(t, &self.matches, self.size())
first_mismatch(t, &self.matches, self.size(), self.slack)
}
/// Along the line, where its first glyph starts and its last glyph's advance ends, from
@@ -395,14 +421,16 @@ impl Line {
/// untracked type does. When untracked type with the spaces also draws the whole line, the line stays
/// untracked if the tracking is under one unit or the tracked reading drops a gap untracked
/// type reads as one space. The line also stays as it is when its tracking is 0 or outside
/// -1000..10000, and when its tracking is negative and the line does not paint the same as one
/// -1000..10000, when one of its glyphs is a near match, and when its tracking is negative and the line does not paint the same as one
/// object ([`paints_as_one`]: its glyphs may overlap). Each of the nine layouts at most takes
/// its characters, spaces included, from `budget` before it runs; without enough left, the
/// line stays as it is, or becomes the best tracked reading laid out before the budget ran out.
fn tracked(self, system_layout: bool, budget: &mut usize) -> Line {
let size = self.size();
let n = self.pieces.len();
if n < 3 || size <= 0.0 {
// A near-matched glyph sits within the tolerance of where the font draws it, so the gaps
// of a line with one say nothing about spacing.
if n < 3 || size <= 0.0 || self.matches.iter().any(|m| !m.exact) {
return self;
}
// Each layout takes its characters, spaces included, from `budget` before it runs.
@@ -568,10 +596,16 @@ impl Line {
/// Normal blend, a solid fill or none, and no stroke? One object composites its transparency and
/// blend once, spans a gradient over all of it, and strokes after filling every glyph.
fn paints_as_one(l: &Line) -> bool {
l.opacity == 1.0
&& l.blend == vectorcraft_color::BlendMode::Normal
&& matches!(l.appearance.fill_paint(), vectorcraft_color::Paint::None | vectorcraft_color::Paint::Solid { .. })
&& matches!(l.appearance.stroke_paint(), vectorcraft_color::Paint::None)
paints_once(l.opacity, l.blend, &l.appearance)
}
/// Does art with `opacity`, `blend` and `appearance` paint its overlaps the same as one object
/// and as several ([`paints_as_one`])?
fn paints_once(opacity: f32, blend: vectorcraft_color::BlendMode, appearance: &Appearance) -> bool {
opacity == 1.0
&& blend == vectorcraft_color::BlendMode::Normal
&& matches!(appearance.fill_paint(), vectorcraft_color::Paint::None | vectorcraft_color::Paint::Solid { .. })
&& matches!(appearance.stroke_paint(), vectorcraft_color::Paint::None)
}
/// The tracking Retype sets, in 1/1000 em.
@@ -596,21 +630,64 @@ fn round_tracking(t: f64) -> f64 {
/// The first of `matches` that type `t` (at `size`) 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(t: &TextObject, matches: &[GlyphMatch], size: f64) -> Option<usize> {
fn first_mismatch(t: &TextObject, matches: &[GlyphMatch], size: f64, slack: f64) -> 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 = (size * 0.01).max(0.01);
// With a tolerance, a near-matched glyph, or any glyph of a line whose first glyph is one,
// may sit that much further (as a fraction of the size) from where the type draws it.
let first_exact = matches.first().is_none_or(|f| f.exact);
for (k, m) in matches.iter().enumerate() {
let Some(g) = drawn.next() else { return Some(k) };
let tol = (size * (0.01 + if m.exact && first_exact { 0.0 } else { slack })).max(0.01);
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);
}
// The type sets the glyph at its line's size and turn, which may differ from the glyph's
// own: the glyph drawn so must still lie within the tolerance of the shape (its center
// within the same distance as its origin).
if !(m.exact && first_exact) {
let (shape, moved) = set_apart(t, g, m);
// An exact match's own leftover is within the exact matcher's reach, not the tolerance.
let own = if m.exact { 0.0 } else { m.pose_residual };
if own.hypot(shape) > slack + 1e-9 || moved > tol {
return Some(k);
}
}
}
// Ink the outlines did not have: the last glyph is where it went wrong.
drawn.next().map(|_| matches.len().saturating_sub(1))
}
/// How glyph `g`, as type `t` draws it, differs from glyph `m` in the size, turn and place `m`
/// was matched in. The first value bounds, whatever points the outline is sampled at, the root
/// mean square distance between the two outlines' points about their center, relative to the
/// root mean square distance of `m`'s points from that center (the measure of near matches'
/// leftover distance): the largest stretch of the change from `m`'s size and turn to the drawn
/// one, which for a change of size and turn alone is that distance exactly. The second is how far
/// apart the two draw the center of the glyph's bounding box. Both are infinite when they cannot
/// be measured.
fn set_apart(t: &TextObject, g: &vectorcraft_text::PositionedGlyph, m: &GlyphMatch) -> (f64, f64) {
let (sin, cos) = m.angle.sin_cos();
let matched = kurbo::Affine::new([m.scale * cos, m.scale * sin, -m.scale * sin, m.scale * cos, m.origin.x, m.origin.y]);
let (gd, md) = (g.xf.determinant(), matched.determinant());
if !gd.is_finite() || gd.abs() < 1e-12 || !md.is_finite() || md.abs() < 1e-12 {
return (f64::INFINITY, f64::INFINITY);
}
let drawn = t.xf * g.xf;
// The change from the matched glyph to the drawn one, less the identity, without the move.
let [a, b, c, d, _, _] = (drawn * matched.inverse()).as_coeffs();
let (a, d) = (a - 1.0, d - 1.0);
// The largest singular value of [[a, c], [b, d]].
let (p, q) = ((a * a + b * b + c * c + d * d) / 2.0, a * d - b * c);
let shape = (p + (p * p - q * q).max(0.0).sqrt()).sqrt();
// The center of the glyph's box, in font units.
let center = g.xf.inverse() * kurbo::Shape::bounding_box(&g.outline).center();
let moved = (drawn * center).distance(matched * center);
let finite = |v: f64| if v.is_finite() { v } else { f64::INFINITY };
(finite(shape), finite(moved))
}
/// `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.
@@ -739,6 +816,8 @@ struct Made {
text: String,
face: Arc<vectorcraft_text::FontFace>,
size: f64,
/// The tolerance near matches were taken with ([`Line::slack`]).
slack: f64,
tracking: f64,
/// The leading set on the type: None for Auto or a single line.
leading: Option<f64>,
@@ -756,6 +835,7 @@ impl Made {
text: l.text.clone(),
face: l.face.clone(),
size: l.size(),
slack: l.slack,
tracking: l.tracking,
leading: None,
opacity: l.opacity,
@@ -888,7 +968,7 @@ impl Block {
t.xf = kurbo::Affine::translate(m.origin - at) * t.xf;
}
super::typecmd::refresh_bounds(&mut t);
if let Some(k) = first_mismatch(&t, &matches, size) {
if let Some(k) = first_mismatch(&t, &matches, size, first.slack) {
// The line that holds glyph `k`.
let mut seen = 0usize;
let at = self.lines.iter().position(|l| {
@@ -917,7 +997,7 @@ impl Block {
let mut area = t.clone();
super::typemenu::point_to_area(&mut area);
let mut point = None;
if in_range(&area) && first_mismatch(&area, &matches, size).is_none() {
if in_range(&area) && first_mismatch(&area, &matches, size, first.slack).is_none() {
point = Some(std::mem::replace(&mut t, area));
}
vec![Made {
@@ -928,6 +1008,7 @@ impl Block {
text: all.text,
face: first.face.clone(),
size,
slack: first.slack,
tracking: all.tracking,
leading: set_leading,
opacity: first.opacity,
@@ -964,7 +1045,7 @@ fn share_tracking(lines: &mut [Line], system_layout: bool) {
/// `lines`, in paint order, as the objects Retype makes: runs of lines that stack as the lines of
/// one paragraph do become one object ([`Block`]). `follows(a, b)`: shape `b` comes right after
/// shape `a`, with nothing between them in paint order. `budget`: see [`Block::made`].
/// shape `a`, or is `a`, with nothing between them in paint order. `budget`: see [`Block::made`].
fn blocks(lines: Vec<Line>, follows: impl Fn(NodeId, NodeId) -> bool, system_layout: bool, budget: &mut usize) -> Vec<Made> {
let mut out = vec![];
let mut block: Option<Block> = None;
@@ -1054,11 +1135,13 @@ fn reposed(l: &Line, id: NodeId, m: &GlyphMatch) -> Line {
parent: l.parent,
opacity: l.opacity,
blend: l.blend,
slack: l.slack,
}
}
/// 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> {
/// A new line of shape `pc` alone, as the first of its candidate glyphs `cands` (none: `None`),
/// with near matches taken at tolerance `slack`.
fn new_line(pc: &Piece, cands: &[GlyphMatch], slack: f64) -> Option<Line> {
let m = cands.first()?;
let dir = Vec2::new(m.angle.cos(), m.angle.sin());
Some(Line {
@@ -1076,18 +1159,344 @@ fn new_line(pc: &Piece, cands: &[GlyphMatch]) -> Option<Line> {
parent: pc.parent,
opacity: pc.opacity,
blend: pc.blend,
slack,
})
}
/// The lines, by index, to drop so that no shape of several glyphs becomes type in part: each line
/// is given by the shapes it sets, one per glyph, and `glyphs_of` says how many glyphs a shape
/// is. A line setting a glyph of a shape not all of whose glyphs are set goes, and then so do the
/// lines setting the other glyphs of the shapes it held.
fn partial_lines(lines: &[Vec<NodeId>], glyphs_of: &std::collections::HashMap<NodeId, usize>) -> std::collections::HashSet<usize> {
let mut dropped = std::collections::HashSet::new();
loop {
let mut set: std::collections::HashMap<NodeId, usize> = std::collections::HashMap::new();
for (_, l) in lines.iter().enumerate().filter(|(i, _)| !dropped.contains(i)) {
for id in l {
*set.entry(*id).or_default() += 1;
}
}
let partial: std::collections::HashSet<NodeId> =
set.iter().filter(|(id, n)| glyphs_of.get(*id).is_some_and(|want| *n < want)).map(|(id, _)| *id).collect();
let before = dropped.len();
for (i, l) in lines.iter().enumerate() {
if l.iter().any(|id| partial.contains(id)) {
dropped.insert(i);
}
}
if dropped.len() == before {
return dropped;
}
}
}
/// Glyph runs longer than this (in contour groups) are not tried when a shape is split.
const MAX_RUN: usize = 3;
/// Complete splits of one shape that one [`split_parts`] search (exact or near) checks the paint
/// of, at most. When none of them is accepted, that search leaves the shape whole.
const MAX_SPLIT_TRIES: usize = 32;
/// A shape of more contour groups than this is not split: it is matched whole only.
const MAX_SPLIT_GROUPS: usize = 256;
/// A shape of more contours than this is not split either, and its contours are not grouped.
const MAX_SPLIT_CONTOURS: usize = 512;
/// Contours of all the selected shapes one command groups, at most: the shapes past them are
/// matched whole only.
const MAX_SPLIT_TOTAL_CONTOURS: usize = 16_384;
/// A shape of more path elements than this is not split, and its contours are not grouped: 16
/// times the most a glyph may have ([`vectorcraft_text::retype::MAX_ELEMENTS`]).
const MAX_SPLIT_ELEMENTS: usize = 16 * vectorcraft_text::retype::MAX_ELEMENTS;
/// `path`'s contour groups when it is split into glyphs: none for fewer than two or more than
/// [`MAX_SPLIT_GROUPS`], for more than [`MAX_SPLIT_CONTOURS`] contours or [`MAX_SPLIT_ELEMENTS`]
/// path elements, and for more contours than `budget` holds. A path of two or more contours takes
/// them from `budget` when it is grouped.
fn split_groups(path: &BezPath, budget: &mut usize) -> Vec<BezPath> {
// Grouping copies the contours and compares every contour with every other: count first.
let n = path.elements().iter().filter(|e| matches!(e, kurbo::PathEl::MoveTo(_))).count();
if !(2..=MAX_SPLIT_CONTOURS).contains(&n) || n > *budget || path.elements().len() > MAX_SPLIT_ELEMENTS {
return vec![];
}
*budget -= n;
let groups = vectorcraft_text::retype::clusters(path);
if (2..=MAX_SPLIT_GROUPS).contains(&groups.len()) { groups } else { vec![] }
}
/// The parts of shape `path` to match: the whole shape, or, when it is no glyph and holds several
/// contour `groups` ([`split_groups`]), runs of up to [`MAX_RUN`] groups in order, the longest that matches first (an i before a dotless i and a dot) among the runs after
/// which the rest of the groups can still be matched. Each part with its candidates; empty when
/// the shape matches nothing and its groups cannot all be matched. `find(path, part, near)` gives
/// a path's candidates: its `part` flag is set for a part of a split shape, whose contours Make
/// Compound Path may have turned the other way round, and its `near` flag allows near matches.
/// Exact matches come first: the whole shape, then its groups, then the whole shape nearly, then
/// its groups nearly. A split of several parts is kept only when `together(runs, near)` accepts the
/// paths of its runs (the parts, set one beside another, paint what the shape paints); `near` is
/// set when the parts were found by near matching.
fn parts<M>(
path: &BezPath,
groups: &[BezPath],
find: &dyn Fn(&BezPath, bool, bool) -> Vec<M>,
together: &dyn Fn(&[BezPath], bool) -> bool,
) -> Vec<Vec<M>> {
let whole = find(path, false, false);
if !whole.is_empty() {
return vec![whole];
}
let exact = split_parts(groups, &|run| find(run, true, false), &|runs| together(runs, false));
if !exact.is_empty() {
return exact;
}
let whole = find(path, false, true);
if !whole.is_empty() {
return vec![whole];
}
split_parts(groups, &|run| find(run, true, true), &|runs| together(runs, true))
}
/// [`parts`] of a shape split into contour `groups`, each run's candidates from `find`; empty for
/// no groups, when the groups cannot all be matched and when `together` rejects every split of
/// several parts it is asked about. The complete splits are tried with the longest runs first,
/// then with the shortest runs, then the others in order, a longer run at an earlier group first.
/// `together` is asked about at most [`MAX_SPLIT_TRIES`] splits. `find` is asked about a run only
/// when the search reaches it, and about each run at most once, so at most [`MAX_RUN`] times per
/// group.
fn split_parts<M>(groups: &[BezPath], find: &dyn Fn(&BezPath) -> Vec<M>, together: &dyn Fn(&[BezPath]) -> bool) -> Vec<Vec<M>> {
let g = groups.len();
let mut s = Splits { groups, find, found: (0..g).map(|_| (0..MAX_RUN).map(|_| None).collect()).collect(), whole: vec![None; g] };
// A split is the runs it takes, each as (start, number of groups).
let mut first = vec![];
if g == 0 || !s.extend(&mut first, false) {
return vec![];
}
let runs_of =
|split: &[(usize, usize)]| -> Vec<BezPath> { split.iter().map(|&(at, n)| groups.get(at..at + n).map(joined).unwrap_or_default()).collect() };
let accepted = 'search: {
if first.len() == 1 {
break 'search Some(first);
}
// The shortest runs are looked up only once the longest are rejected.
let mut shortest = vec![];
let mut shortest_next = true;
let mut rest = first.clone();
let mut candidate = Some(first.clone());
let mut tried = 0;
while let Some(split) = candidate.take() {
if tried == MAX_SPLIT_TRIES {
break;
}
tried += 1;
if together(&runs_of(&split)) {
break 'search Some(split);
}
if std::mem::take(&mut shortest_next) && s.extend(&mut shortest, true) && shortest != first {
candidate = Some(shortest.clone());
continue;
}
candidate = loop {
if !s.advance(&mut rest) {
break None;
}
if rest != shortest {
break Some(rest.clone());
}
};
}
None
};
let Some(split) = accepted else { return vec![] };
let mut out = vec![];
for (at, n) in split {
let Some(Some(cands)) = s.found.get_mut(at).and_then(|f| f.get_mut(n.wrapping_sub(1))).map(Option::take) else { return vec![] };
out.push(cands);
}
out
}
/// The state of one [`split_parts`] search: each run's candidates and whether the groups from each
/// start can all be matched, each found when the search first needs it.
struct Splits<'a, M> {
groups: &'a [BezPath],
find: &'a dyn Fn(&BezPath) -> Vec<M>,
/// By start and length less one: the run's candidates, once looked up.
found: Vec<Vec<Option<Vec<M>>>>,
/// By start: whether the groups from there on can all be matched, once known.
whole: Vec<Option<bool>>,
}
impl<M> Splits<'_, M> {
/// Whether the run of `n` groups at `at` matches, looking it up the first time.
fn matches(&mut self, at: usize, n: usize) -> bool {
let Some(slot) = self.found.get_mut(at).and_then(|f| f.get_mut(n.wrapping_sub(1))) else { return false };
if slot.is_none() {
let cands = self.groups.get(at..at + n).map(|run| (self.find)(&joined(run))).unwrap_or_default();
*slot = Some(cands);
}
slot.as_ref().is_some_and(|c| !c.is_empty())
}
/// Whether the groups from `at` on can all be matched. The search goes from `at` forward, the
/// longest run first, and no start is searched twice, so it ends after at most [`MAX_RUN`]
/// lookups and checks per group.
fn completes(&mut self, at: usize) -> bool {
let g = self.groups.len();
if at >= g {
return at == g;
}
if let Some(known) = self.whole.get(at).copied().flatten() {
return known;
}
// From `at`: the starts still to settle, each with the run length to try next.
let mut stack: Vec<(usize, usize)> = vec![(at, MAX_RUN.min(g - at))];
while let Some(&(i, n)) = stack.last() {
if self.whole.get(i).copied().flatten().is_some() {
stack.pop();
continue;
}
if n == 0 {
if let Some(w) = self.whole.get_mut(i) {
*w = Some(false);
}
stack.pop();
continue;
}
if let Some(top) = stack.last_mut() {
top.1 = n - 1;
}
if !self.matches(i, n) {
continue;
}
let next = i + n;
match if next == g { Some(true) } else { self.whole.get(next).copied().flatten() } {
Some(true) => {
if let Some(w) = self.whole.get_mut(i) {
*w = Some(true);
}
stack.pop();
}
Some(false) => {}
None => {
// Settle `next` first, then try this run again.
if let Some(top) = stack.last_mut() {
top.1 = n;
}
stack.push((next, MAX_RUN.min(g - next)));
}
}
}
self.whole.get(at).copied().flatten() == Some(true)
}
/// Whether `n` groups at `at` are a run a complete split can take.
fn fits(&mut self, at: usize, n: usize) -> bool {
self.matches(at, n) && self.completes(at + n)
}
/// Takes `split` on to the last group, with the longest run that fits at each start (or, with
/// `shortest`, the shortest); false when no run fits.
fn extend(&mut self, split: &mut Vec<(usize, usize)>, shortest: bool) -> bool {
let g = self.groups.len();
let mut i = split.last().map_or(0, |&(at, n)| at + n);
while i < g {
let most = MAX_RUN.min(g - i);
let lens: Vec<usize> = if shortest { (1..=most).collect() } else { (1..=most).rev().collect() };
let Some(n) = lens.into_iter().find(|&n| self.fits(i, n)) else { return false };
split.push((i, n));
i += n;
}
true
}
/// Moves `split` on to the next complete split, in order: the runs before the last start where
/// a shorter run fits kept, that shorter run, and the longest runs after it. False past the last.
fn advance(&mut self, split: &mut Vec<(usize, usize)>) -> bool {
while let Some((at, n)) = split.pop() {
if let Some(m) = (1..n).rev().find(|&m| self.fits(at, m)) {
split.push((at, m));
return self.extend(split, false);
}
}
false
}
}
/// Contour groups joined into one path.
fn joined(run: &[BezPath]) -> BezPath {
let mut p = BezPath::new();
for g in run {
p.extend(g.iter());
}
p
}
/// Every run of contour `groups` ([`split_groups`]) [`parts`] may try.
fn runs(groups: &[BezPath]) -> Vec<BezPath> {
let mut out = vec![];
for i in 0..groups.len() {
for n in 1..=MAX_RUN.min(groups.len() - i) {
if let Some(run) = groups.get(i..i + n) {
out.push(joined(run));
}
}
}
out
}
/// The keys the index looks glyphs up by for the `shapes` (each with its contour groups) and
/// every run of their groups: their exact [`shape_key`](vectorcraft_text::retype::shape_key)s and,
/// with a `tolerance` above 0, at most [`MAX_NEAR_KEYS`](vectorcraft_text::retype::MAX_NEAR_KEYS)
/// distinct [`near_key`](vectorcraft_text::retype::near_key)s: every whole shape's first, in the
/// order the shapes come, then the runs of their groups. Paths past that many near keys are not
/// looked up for near matches.
fn lookup_keys<'a>(
shapes: impl IntoIterator<Item = (&'a BezPath, &'a [BezPath])>,
tolerance: f64,
) -> (std::collections::BTreeSet<u64>, Vec<vectorcraft_text::retype::NearKey>) {
use vectorcraft_text::retype::{MAX_NEAR_KEYS, near_key, shape_key};
let mut wanted = std::collections::BTreeSet::new();
let mut near_wanted = vec![];
let mut add = |run: &BezPath| {
wanted.extend(shape_key(run));
if tolerance > 0.0
&& near_wanted.len() < MAX_NEAR_KEYS
&& let Some(k) = near_key(run)
&& !near_wanted.contains(&k)
{
near_wanted.push(k);
}
};
let shapes: Vec<(&BezPath, &[BezPath])> = shapes.into_iter().collect();
// The whole shapes first, then the runs of their groups.
for (path, _) in &shapes {
add(path);
}
for (_, groups) in &shapes {
for run in runs(groups) {
add(&run);
}
}
(wanted, near_wanted)
}
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![],
None => 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 tolerance = match p.get("tolerance") {
None => 0.0,
Some(v) => match v.as_f64() {
Some(t) if (0.0..=vectorcraft_text::retype::MAX_TOLERANCE).contains(&t) => t,
_ => return Err(bad(C, "tolerance must be a number from 0 to 0.05")),
},
};
let roots = selected_roots(s)?;
let db = FontDb::global();
let system_layout = s.doc()?.doc.setup.system_layout;
@@ -1114,59 +1523,130 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
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();
// Only glyphs with a selected shape's key (segments per contour) can match one exactly, and
// only glyphs with as many contours and a close area-to-length ratio nearly: the others are
// not sampled. A shape of several glyphs is looked up by the runs of its groups too.
let mut budget = MAX_SPLIT_TOTAL_CONTOURS;
let groups: Vec<Vec<BezPath>> = pieces.iter().map(|pc| if pc.keeps_outline { vec![] } else { split_groups(&pc.path, &mut budget) }).collect();
let (wanted, near_wanted) =
lookup_keys(pieces.iter().zip(&groups).filter(|(pc, _)| !pc.keeps_outline).map(|(pc, g)| (&pc.path, g.as_slice())), tolerance);
// 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();
let index = if wanted.is_empty() && near_wanted.is_empty() {
RetypeIndex::default()
} else {
RetypeIndex::build_near(db, candidate_faces(db, d, &fonts), &wanted, &near_wanted)
};
// Exact matches first; near ones, when allowed, only for a path with none.
// With a visible fill, a glyph is kept only when it paints the area the shape paints under
// the shape's fill rule (`fill` is `Some(nonzero)`).
let find = |path: &BezPath, part: bool, near: bool, fill: Option<bool>| {
let painted = |ms: Vec<GlyphMatch>, tol: f64| -> Vec<GlyphMatch> {
match fill {
Some(nonzero) => ms.iter().filter_map(|m| index.painted_agrees(m, path, nonzero, tol)).collect(),
None => ms,
}
};
let exact = painted(if part { index.matches_either_way(path) } else { index.all_matches(path) }, 0.0);
if exact.is_empty() && near { painted(index.near_matches(path, tolerance), tolerance) } else { exact }
};
// Each shape's parts (one, unless it holds several glyphs), each with its candidates.
let found: Vec<Vec<Vec<GlyphMatch>>> = pieces
.iter()
.zip(&groups)
.map(|(pc, g)| {
if pc.keeps_outline {
return vec![];
}
let fill = pc.filled.then_some(pc.nonzero);
// Parts that all match exactly are checked at tolerance 0, in the near phase as in
// the exact one; only a part that matches nearly brings the tolerance in.
// The glyphs of a split may become separate objects: when the shape does not paint
// its overlaps as several objects would (translucent, another blend, a gradient or
// pattern fill, a stroke), its parts must not overlap, which the parts read by the
// even-odd rule against them all joined show.
let once = paints_once(pc.opacity, pc.blend, &pc.appearance);
let together = |runs: &[BezPath], near: bool| {
if fill.is_none() && once {
return true;
}
let nearly = near && runs.iter().any(|r| find(r, true, false, fill).is_empty());
let tol = if nearly { tolerance } else { 0.0 };
fill.is_none_or(|nz| vectorcraft_text::retype::parts_paint_alike(&pc.path, runs, nz, tol))
&& (once || vectorcraft_text::retype::parts_paint_alike(&joined(runs), runs, false, tol))
};
parts(&pc.path, g, &|p, part, near| find(p, part, near, fill), &together)
})
.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)),
// the glyphs around it. Among faces that as many shapes match, the one whose glyphs fit
// them closest in all (the least leftover distance summed over those shapes), so every
// part that fits it takes the same face, exact matches as near ones. Simplified outlines
// of one font can nearly fit another font's look-alike glyphs, some of them more closely.
// A part's matches are all exact or all near, so the distances a face sums compare alike.
let mut votes: Vec<(u32, usize, f64)> = vec![];
for ms in found.iter().flatten() {
// Each shape votes once for each face it fits, with the leftover distance of its
// closest glyph in that face.
let mut faces: Vec<(u32, f64)> = vec![];
for m in ms {
let residual = if m.residual.is_finite() { m.residual } else { f64::INFINITY };
match faces.iter_mut().find(|(f, _)| *f == m.face.id()) {
Some(f) => f.1 = f.1.min(residual),
None => faces.push((m.face.id(), residual)),
}
}
for (f, residual) in faces {
match votes.iter_mut().find(|(v, ..)| *v == f) {
Some(v) => {
v.1 += 1;
v.2 += residual;
}
None => votes.push((f, 1, residual)),
}
}
}
let rank = |face: u32| votes.iter().find(|(f, _)| *f == face).map_or(0, |v| v.1);
let rank = |face: u32| votes.iter().find(|(f, ..)| *f == face).map_or((0, f64::INFINITY), |v| (v.1, v.2));
// Most votes, then the least summed distance, then the first (the matches come upright and
// closest first).
let ranked = |(i, a): &(usize, &GlyphMatch), (j, b): &(usize, &GlyphMatch)| {
let ((va, da), (vb, db)) = (rank(a.face.id()), rank(b.face.id()));
va.cmp(&vb).then(db.total_cmp(&da)).then(j.cmp(i))
};
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) {
// How many glyphs each shape is: a shape of several becomes type only when all of them do.
let mut glyphs_of: std::collections::HashMap<NodeId, usize> = std::collections::HashMap::new();
for (pc, parts) 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() {
if parts.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));
glyphs_of.insert(pc.id, parts.len());
for ms in parts {
// The part's candidates in the face most shapes fit (see `ranked`).
let face = ms.iter().enumerate().max_by(ranked).map(|(_, m)| m.face.id());
let cands: Vec<GlyphMatch> = ms.iter().filter(|m| Some(m.face.id()) == face).cloned().collect();
let joined = match lines.last_mut() {
Some(l) if open => join(l, pc, &cands),
_ => false,
};
if !joined {
lines.extend(new_line(pc, &cands, tolerance));
}
open = true;
}
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).
// art (a dot, a bar): beside other shapes, the other glyphs of a split compound path
// included, 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().flat_map(Line::lone_one_contour).collect();
// Each line's tracking is measured with nine layouts at most: the line as read (its
// characters), its glyphs without and with one space between them (three times its
@@ -1177,7 +1657,7 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
let mut lines: Vec<Line> = lines.into_iter().map(|l| l.tracked(system_layout, &mut budget)).collect();
share_tracking(&mut lines, system_layout);
let mut lines = verified(lines, system_layout, &mut unmatched);
if pieces.len() > 1 {
if pieces.len() > 1 || glyphs_of.values().any(|n| *n > 1) {
lines.retain(|l| {
let lone = matches!(l.pieces.as_slice(), [id] if lone_pieces.contains(id));
if lone {
@@ -1186,9 +1666,24 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
!lone
});
}
let dropped = partial_lines(&lines.iter().map(|l| l.pieces.clone()).collect::<Vec<_>>(), &glyphs_of);
let mut k = 0;
lines.retain(|l| {
let keep = !dropped.contains(&k);
k += 1;
if !keep {
unmatched.extend(l.pieces.iter().copied());
}
keep
});
// A shape of several glyphs is reported once, and not when it became type.
let kept: std::collections::HashSet<NodeId> = lines.iter().flat_map(|l| l.pieces.iter().copied()).collect();
let mut seen = std::collections::HashSet::new();
unmatched.retain(|id| !kept.contains(id) && seen.insert(*id));
let at: std::collections::HashMap<NodeId, usize> = pieces.iter().enumerate().map(|(i, pc)| (pc.id, i)).collect();
// Lines split from one compound path share its shape, with nothing between them.
let follows = |a: NodeId, b: NodeId| match (at.get(&a), at.get(&b)) {
(Some(i), Some(j)) => *j == i + 1 && pieces.get(*j).is_some_and(|pc| !pc.after_barrier),
(Some(i), Some(j)) => *j == *i || (*j == i + 1 && pieces.get(*j).is_some_and(|pc| !pc.after_barrier)),
_ => false,
};
// Joining lines takes at most four tries' work per glyph (see [`Block::made`]), with room
@@ -1204,6 +1699,9 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
let before = lines.iter().any(|l| l.point.is_some()).then(|| d.clone());
let mut ids = vec![];
let mut emptied = vec![];
// Every line's type goes in before the shapes go: a shape of several glyphs is the first
// shape of more than one line. Each goes just before its first shape, so lines from one
// shape keep their order.
for l in &lines {
let Some(first) = l.pieces.first() else { continue };
let (par, idx, _) = d.position(*first).ok_or(EngineError::NoNode(*first))?;
@@ -1213,14 +1711,18 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
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);
}
let mut removed = std::collections::HashSet::new();
for pc in lines.iter().flat_map(|l| l.pieces.iter()) {
if !removed.insert(*pc) {
continue;
}
if let Some((Some(parent), _, _)) = d.position(*pc) {
emptied.push(parent);
}
d.remove(*pc)?;
}
// 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.
@@ -1284,7 +1786,7 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
for (l, id) in lines.iter().zip(&ids).filter(|_| units > 0) {
let Some(point) = &l.point else { continue };
let Some(NodeKind::Text(t)) = probe.node(*id).map(|n| &n.kind) else { continue };
if flowed && (t.wrap.is_empty() || first_mismatch(t, &l.matches, l.size).is_none()) {
if flowed && (t.wrap.is_empty() || first_mismatch(t, &l.matches, l.size, l.slack).is_none()) {
continue;
}
if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) {
@@ -1306,14 +1808,18 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
"fonts": lines
.iter()
.zip(&made)
.map(|(l, id)| json!({
"family": l.face.family,
"style": l.face.style,
"size": l.size,
"tracking": l.tracking,
"leading": l.leading,
"area": area(id),
}))
.map(|(l, id)| {
let score = l.matches.iter().map(GlyphMatch::score).fold(1.0, f64::min);
json!({
"family": l.face.family,
"style": l.face.style,
"size": l.size,
"tracking": l.tracking,
"leading": l.leading,
"area": area(id),
"score": (score * 1000.0).round() / 1000.0,
})
})
.collect::<Vec<_>>(),
"unmatched": unmatched.iter().map(|i| i.0).collect::<Vec<_>>(),
"truncated": truncated,
+824 -3
View File
@@ -10,7 +10,13 @@ fn session() -> Session {
}
/// Point text, outlined: the id of the outlines' group.
fn outlined(s: &mut Session, p: serde_json::Value) -> u64 {
fn outlined(s: &mut Session, mut p: serde_json::Value) -> u64 {
// A text without a font is set in the system's default face, which differs from machine to
// machine and decides which glyphs a near match can tell apart.
if p.get("font").is_none() {
p["font"] = json!("Source Sans 3");
p["style"] = json!("Regular");
}
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()
@@ -84,7 +90,7 @@ fn a_drawn_shape_is_reported_and_left_alone() {
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"})] {
for bad in [json!("Source Sans 3"), json!([1]), json!({"family": "x"}), json!(null)] {
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}");
}
@@ -539,6 +545,118 @@ fn a_long_tracked_line_is_checked_in_time() {
eprintln!("450 tracked glyphs: {:?}, {} objects", t0.elapsed(), texts.len());
}
/// Every path in the document flattened into lines `tol` from its curves, each contour started at
/// its second point and run backwards: outlines simplified and built nothing like the font's.
fn simplify_every_path(s: &mut Session, tol: f64) {
let mut ids = vec![];
s.doc().unwrap().doc.walk(|n| {
if matches!(n.kind, NodeKind::Path { .. }) {
ids.push(n.id);
}
});
simplify_paths(s, &ids, tol);
}
/// [`simplify_every_path`] for the paths `ids` only.
fn simplify_paths(s: &mut Session, ids: &[NodeId], tol: f64) {
s.edit("test", |d, _| {
for id in ids {
let data = d.node_mut(*id).unwrap().path_data_mut().unwrap();
let mut contours: Vec<Vec<kurbo::Point>> = vec![];
kurbo::flatten(data.to_bezpath().iter(), tol, |el| match el {
kurbo::PathEl::MoveTo(q) => contours.push(vec![q]),
kurbo::PathEl::LineTo(q) => contours.last_mut().unwrap().push(q),
_ => {}
});
let mut out = kurbo::BezPath::new();
for mut c in contours {
if c.len() > 1 && c.first() == c.last() {
c.pop();
}
c.rotate_left(1);
c.reverse();
out.move_to(c[0]);
for q in &c[1..] {
out.line_to(*q);
}
out.close_path();
}
*data = vectorcraft_geom::PathData::from_bezpath(&out);
}
Ok(())
})
.unwrap();
}
#[test]
fn simplified_outlines_retype_only_with_a_tolerance_and_report_their_score() {
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Rag", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
simplify_every_path(&mut s, 0.05);
s.execute("select.set", &json!({"ids": [g]})).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"), "no exact match: {e}");
for bad in [json!(-0.01), json!(0.06), json!("0.02"), json!(true), json!(null)] {
let e = s.execute("type.retype", &json!({"tolerance": bad})).unwrap_err().to_string();
assert!(e.contains("tolerance must be a number from 0 to 0.05"), "{e}");
}
assert!(s.doc().unwrap().doc == before, "nothing changes");
let r = s.execute("type.retype", &json!({"tolerance": 0.02})).unwrap();
assert_eq!(r["texts"], json!(["Rag"]), "{r}");
assert_eq!(r["unmatched"], json!([]));
assert_eq!((r["fonts"][0]["family"].as_str(), r["fonts"][0]["style"].as_str()), (Some("Source Sans 3"), Some("Regular")));
let score = r["fonts"][0]["score"].as_f64().unwrap();
assert!(score > 0.5 && score < 1.0, "a near match scores below an exact one: {score}");
let t = text_of(&s, r["ids"][0].as_u64().unwrap());
assert!(near(t.first_style().size, 40.0, 0.4), "size {}", t.first_style().size);
let o = t.xf.translation();
assert!(near(o.x, 40.0, 0.4) && near(o.y, 100.0, 0.4), "baseline start {o:?}");
}
#[test]
fn exact_matches_score_one() {
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Rag", "size": 40}));
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({"tolerance": 0.02})).unwrap();
assert_eq!(r["texts"], json!(["Rag"]), "{r}");
assert_eq!(r["fonts"][0]["score"], json!(1.0));
}
#[test]
fn exact_matches_with_a_small_leftover_still_score_one() {
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Rag", "size": 40}));
// Each glyph stretched 0.1% across its own centre: still within the exact matcher's reach, with
// a leftover distance above 0.
let mut ids = vec![];
s.doc().unwrap().doc.walk(|n| {
if matches!(n.kind, NodeKind::Path { .. }) {
ids.push(n.id);
}
});
s.edit("test", |d, _| {
for id in &ids {
let data = d.node_mut(*id).unwrap().path_data_mut().unwrap();
let p = data.to_bezpath();
let c = kurbo::Shape::bounding_box(&p).center();
let xf = kurbo::Affine::translate(c.to_vec2()) * kurbo::Affine::scale_non_uniform(1.001, 1.0) * kurbo::Affine::translate(-c.to_vec2());
*data = vectorcraft_geom::PathData::from_bezpath(&(xf * p));
}
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
// Each glyph's size now differs a little, so each is its own line.
let texts: Vec<&str> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap()).collect();
assert_eq!(texts.concat(), "Rag", "{r}");
for f in r["fonts"].as_array().unwrap() {
assert_eq!(f["score"], json!(1.0), "{r}");
}
}
#[test]
fn two_overlapping_lone_glyphs_beside_art_stay_outlines() {
// Two M outlines start 0.3 em apart, closer than the first one's advance: a tight-tracking
@@ -583,6 +701,55 @@ fn assert_same_places(a: &TextObject, b: &TextObject) {
}
}
#[test]
fn exact_glyphs_of_another_size_are_another_line_even_with_a_tolerance() {
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Tia", "size": 40}));
// The a (two contours, so not a lone one-contour glyph) made 4% larger about where it starts
// on the baseline: still exactly the glyph.
let a = *children_of(&s, g).last().unwrap();
// The a's paths (a compound path's, or its own).
let paths: Vec<u64> = match s.doc().unwrap().doc.node(NodeId(a)).unwrap().children() {
Some(c) => c.iter().map(|c| c.id.0).collect(),
None => vec![a],
};
s.edit("test", |d, _| {
let x0 = paths
.iter()
.map(|id| kurbo::Shape::bounding_box(&d.node_mut(NodeId(*id)).unwrap().path_data_mut().unwrap().to_bezpath()).x0)
.fold(f64::INFINITY, f64::min);
let at = kurbo::Vec2::new(x0, 100.0);
let xf = kurbo::Affine::translate(at) * kurbo::Affine::scale(1.04) * kurbo::Affine::translate(-at);
for id in &paths {
let data = d.node_mut(NodeId(*id)).unwrap().path_data_mut().unwrap();
*data = vectorcraft_geom::PathData::from_bezpath(&(xf * data.to_bezpath()));
}
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({"tolerance": 0.05})).unwrap();
assert_eq!(r["texts"], json!(["Ti", "a"]), "{r}");
let sizes: Vec<f64> = r["fonts"].as_array().unwrap().iter().map(|f| f["size"].as_f64().unwrap()).collect();
assert!(near(sizes[0], 40.0, 0.01) && near(sizes[1], 41.6, 0.01), "{sizes:?}");
assert!(r["fonts"].as_array().unwrap().iter().all(|f| f["score"] == json!(1.0)), "{r}");
}
#[test]
fn turned_near_matched_round_glyphs_keep_the_line_turn() {
// Round glyphs (o, O, the period) and glyphs that look alike half round (N, x, z) fit
// simplified outlines at more than one turn: each takes the turn of its line.
for (text, rotation) in [("no.", 90), ("no.", 180), ("zoo", 135), ("NOON", 180), ("xoxo", 200), ("on", 120)] {
let mut s = session();
let g = outlined(&mut s, json!({"x": 300, "y": 200, "text": text, "size": 40, "rotation": rotation}));
simplify_every_path(&mut s, 0.05);
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({"tolerance": 0.02})).unwrap();
assert_eq!(r["texts"], json!([text]), "turned {rotation}: {r}");
assert_eq!(r["unmatched"], json!([]), "{r}");
}
}
#[test]
fn several_lines_become_one_area_type_object() {
let mut s = session();
@@ -870,6 +1037,660 @@ fn spaced_letters_keep_their_spaces_when_type_draws_them() {
}
}
#[test]
fn a_near_glyph_moved_by_more_than_the_tolerance_ends_the_line() {
// The m (one path) of simplified outlines moved along the baseline by `shift` of the font
// size (40), retyped with a tolerance of 0.03: it may sit 1% + 3% of the size from where the
// type draws it.
let run = |shift: f64| {
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Tim", "size": 40}));
simplify_every_path(&mut s, 0.05);
let m = *children_of(&s, g).last().unwrap();
s.edit("test", |d, _| {
let data = d.node_mut(NodeId(m)).unwrap().path_data_mut().unwrap();
*data = vectorcraft_geom::PathData::from_bezpath(&(kurbo::Affine::translate((40.0 * shift, 0.0)) * data.to_bezpath()));
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({"tolerance": 0.03})).unwrap();
let texts: Vec<String> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect();
assert_eq!(texts.concat(), "Tim", "{r}");
texts.len()
};
assert_eq!(run(0.02), 1, "within the tolerance: one line");
assert!(run(0.06) > 1, "past it: the line splits where the m was moved");
}
/// The bounding box of shape `id` (a path, or a compound path's paths), in document space.
fn shape_box(s: &Session, id: u64) -> kurbo::Rect {
let d = &s.doc().unwrap().doc;
let n = d.node(NodeId(id)).unwrap();
let paths: Vec<&vectorcraft_doc::Node> = match n.children() {
Some(c) => c.iter().map(|c| &**c).collect(),
None => vec![n],
};
paths
.iter()
.filter_map(|p| match &p.kind {
NodeKind::Path { path, .. } => Some(kurbo::Shape::bounding_box(&path.to_bezpath())),
_ => None,
})
.reduce(|a, b| a.union(b))
.unwrap()
}
/// The bounding box of each glyph with ink that type `t` draws, in document space.
fn drawn_boxes(t: &TextObject) -> Vec<kurbo::Rect> {
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty()).map(|g| kurbo::Shape::bounding_box(&(t.xf * g.outline.clone()))).collect()
}
#[test]
fn a_near_glyph_whose_size_and_turn_differ_past_the_tolerance_ends_the_line() {
// The m of simplified outlines made 4% larger, and turned 0.04 radians as well, about where it
// starts on the baseline, retyped with a tolerance of 0.05. Each change alone is within the
// size and turn a near-matched line allows, but drawn at the line's size and turn the m would
// lie further than 0.05 of its spread from its outline: it becomes type of its own. Larger
// alone, it is still within the tolerance and stays on the line.
for (scale, turn, lines) in [(1.04, 0.0, 1), (1.04, 0.04, 2)] {
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Tim", "size": 40}));
simplify_every_path(&mut s, 0.05);
let kids = children_of(&s, g);
let m = *kids.last().unwrap();
let x0 = shape_box(&s, m).x0;
s.edit("test", |d, _| {
let at = kurbo::Vec2::new(x0, 100.0);
let xf = kurbo::Affine::translate(at) * kurbo::Affine::rotate(turn) * kurbo::Affine::scale(scale) * kurbo::Affine::translate(-at);
let data = d.node_mut(NodeId(m)).unwrap().path_data_mut().unwrap();
*data = vectorcraft_geom::PathData::from_bezpath(&(xf * data.to_bezpath()));
Ok(())
})
.unwrap();
let before: Vec<kurbo::Rect> = kids.iter().map(|k| shape_box(&s, *k)).collect();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({"tolerance": 0.05})).unwrap();
let texts: Vec<&str> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap()).collect();
assert_eq!(texts.concat(), "Tim", "{r}");
assert_eq!(texts.len(), lines, "scale {scale}, turn {turn}: {r}");
if lines == 1 {
continue;
}
let drawn: Vec<kurbo::Rect> = r["ids"].as_array().unwrap().iter().flat_map(|id| drawn_boxes(&text_of(&s, id.as_u64().unwrap()))).collect();
assert_eq!(drawn.len(), before.len(), "{r}");
for b in &before {
// The glyph drawn nearest where the outline was.
let d = drawn.iter().min_by(|p, q| p.center().distance(b.center()).total_cmp(&q.center().distance(b.center()))).unwrap();
let size = b.width().hypot(b.height());
assert!(
(d.width() - b.width()).abs() < size * 0.01 && (d.height() - b.height()).abs() < size * 0.01,
"scale {scale}, turn {turn}: the outline's box {b:?}, the type's {d:?}: {r}"
);
}
}
}
#[test]
fn an_exact_glyph_moved_splits_the_line_whatever_the_tolerance() {
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Tim", "size": 40}));
let m = *children_of(&s, g).last().unwrap();
s.edit("test", |d, _| {
let data = d.node_mut(NodeId(m)).unwrap().path_data_mut().unwrap();
*data = vectorcraft_geom::PathData::from_bezpath(&(kurbo::Affine::translate((40.0 * 0.03, 0.0)) * data.to_bezpath()));
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({"tolerance": 0.05})).unwrap();
assert_eq!(r["texts"], json!(["Ti", "m"]), "exact glyphs keep the exact limits: {r}");
}
#[test]
fn an_exact_glyph_after_a_near_one_keeps_the_exact_limits() {
// T exact, o simplified (a near match), m exact moved by 3% of the size along the baseline.
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Tom", "size": 40}));
let kids = children_of(&s, g);
let o: Vec<NodeId> = match s.doc().unwrap().doc.node(NodeId(kids[1])).unwrap().children() {
Some(c) => c.iter().map(|c| c.id).collect(),
None => vec![NodeId(kids[1])],
};
simplify_paths(&mut s, &o, 0.05);
let m = kids[2];
s.edit("test", |d, _| {
let data = d.node_mut(NodeId(m)).unwrap().path_data_mut().unwrap();
*data = vectorcraft_geom::PathData::from_bezpath(&(kurbo::Affine::translate((40.0 * 0.03, 0.0)) * data.to_bezpath()));
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({"tolerance": 0.05})).unwrap();
assert_eq!(r["texts"], json!(["To", "m"]), "the near o does not loosen the m's limits: {r}");
}
/// The outlines of `text` made into one compound path: the compound's id.
fn one_compound(s: &mut Session, text: &str) -> u64 {
let g = outlined(s, json!({"x": 40, "y": 100, "text": text, "size": 40}));
let glyphs = children_of(s, g);
s.execute("select.set", &json!({"ids": glyphs})).unwrap();
s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()
}
#[test]
fn a_word_outlined_as_one_compound_path_splits_into_its_glyphs() {
let mut s = session();
let c = one_compound(&mut s, "Tim");
s.execute("select.set", &json!({"ids": [c]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!(["Tim"]), "the i's stem and dot are one glyph: {r}");
assert_eq!(r["unmatched"], json!([]));
assert!(s.doc().unwrap().doc.node(NodeId(c)).is_none(), "the compound becomes the type");
}
#[test]
fn a_lone_period_in_a_compound_selected_alone_stays_an_outline() {
let mut s = session();
// An A and, far below it, a period, made into one compound path and selected alone: the
// period, alone on its baseline beside the A, is a dot as much as a period, so it stays an
// outline, and so does the A in the same compound.
let t = outlined(&mut s, json!({"x": 40, "y": 100, "text": "A", "size": 40}));
let dot = outlined(&mut s, json!({"x": 40, "y": 300, "text": ".", "size": 40}));
let mut ids = children_of(&s, t);
ids.extend(children_of(&s, dot));
s.execute("select.set", &json!({"ids": ids})).unwrap();
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [c]})).unwrap();
let before = s.doc().unwrap().doc.clone();
let e = match s.execute("type.retype", &json!({})) {
Ok(r) => panic!("the period became type: {r}"),
Err(e) => e.to_string(),
};
assert!(e.contains("(1 checked)"), "{e}");
assert!(s.doc().unwrap().doc == before, "nothing changes");
}
#[test]
fn lines_from_one_compound_path_keep_their_order() {
let mut s = session();
// Two lines of outlines made into one compound path, farther apart than the lines of one
// paragraph, so each stays an object of its own.
let top = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Tim", "size": 40}));
let low = outlined(&mut s, json!({"x": 40, "y": 300, "text": "Ham", "size": 40}));
let mut glyphs = children_of(&s, top);
glyphs.extend(children_of(&s, low));
s.execute("select.set", &json!({"ids": glyphs})).unwrap();
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [c]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
let ids: Vec<u64> = r["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
assert_eq!(ids.len(), 2, "{r}");
let texts: Vec<String> = ids.iter().map(|id| text_of(&s, *id).plain_text()).collect();
let d = &s.doc().unwrap().doc;
let at: Vec<usize> = ids.iter().map(|id| d.position(NodeId(*id)).unwrap().1).collect();
// The lines stack in the order of the compound's contours: the first line behind the second.
let first = texts.iter().position(|t| t == "Tim").unwrap();
let second = texts.iter().position(|t| t == "Ham").unwrap();
assert!(at[first] < at[second], "{texts:?} at {at:?}");
}
#[test]
fn stacked_lines_from_one_compound_path_become_one_object() {
let mut s = session();
// Two lines of one paragraph, outlined and made into one compound path: they join as the
// lines of separate outlines do.
let text = "Tim\nHam";
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 40}));
let glyphs = children_of(&s, g);
s.execute("select.set", &json!({"ids": glyphs})).unwrap();
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [c]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!([text]), "{r}");
assert_eq!(r["unmatched"], json!([]), "{r}");
assert!(s.doc().unwrap().doc.node(NodeId(c)).is_none(), "the compound becomes the type");
}
#[test]
fn a_compound_whose_parts_are_not_all_glyphs_stays_whole() {
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Ti", "size": 40}));
let mut ids = children_of(&s, g);
// A shape no glyph is, beside the letters, in the same compound.
ids.push(s.execute("shape.star", &json!({"cx": 140, "cy": 85, "radius1": 12, "radius2": 5, "points": 7})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": ids})).unwrap();
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [c]})).unwrap();
let before = s.doc().unwrap().doc.clone();
let e = s.execute("type.retype", &json!({})).unwrap_err().to_string();
assert!(e.contains("(1 checked)"), "reported once: {e}");
assert!(s.doc().unwrap().doc == before, "nothing changes");
}
#[test]
fn glyphs_that_overlap_in_an_even_odd_compound_stay_an_outline() {
let mut s = session();
// Two o's moved onto each other and made into one compound path: the even-odd rule leaves
// the overlap unpainted, and two glyphs set side by side would paint it.
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "oo", "size": 40}));
let kids = children_of(&s, g);
s.execute("object.move", &json!({"ids": [kids[1]], "dx": -9, "dy": 0})).unwrap();
s.execute("select.set", &json!({"ids": kids})).unwrap();
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [c]})).unwrap();
let before = s.doc().unwrap().doc.clone();
let e = match s.execute("type.retype", &json!({})) {
Ok(r) => panic!("the overlapping o's became type: {r}"),
Err(e) => e.to_string(),
};
assert!(e.contains("(1 checked)"), "{e}");
assert!(s.doc().unwrap().doc == before, "nothing changes");
}
#[test]
fn a_translucent_compound_whose_glyphs_overlap_stays_an_outline() {
// Two i's, the second moved half onto the first and down off its baseline, made into one
// compound path filled by the nonzero rule with every contour running one way: the parts paint
// the shape's area, but on two lines they become two objects, and at 50% opacity their
// overlap would be painted twice.
for opacity in [1.0f32, 0.5] {
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "ii", "size": 40}));
let kids = children_of(&s, g);
let dx = shape_box(&s, kids[0]).x0 - shape_box(&s, kids[1]).x0 + 2.0;
s.execute("object.move", &json!({"ids": [kids[1]], "dx": dx, "dy": 6})).unwrap();
s.execute("select.set", &json!({"ids": kids})).unwrap();
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
let paths = children_of(&s, c);
s.edit("test", |d, _| {
// Make Compound Path turns the second glyph's contours the other way round.
for p in &paths {
let data = d.node_mut(NodeId(*p)).unwrap().path_data_mut().unwrap();
let b = data.to_bezpath();
if kurbo::Shape::area(&b) < 0.0 {
*data = vectorcraft_geom::PathData::from_bezpath(&b.reverse_subpaths());
}
}
let n = d.node_mut(NodeId(c)).unwrap();
n.opacity = opacity;
if let NodeKind::Compound { rule, .. } = &mut n.kind {
*rule = vectorcraft_geom::FillRule::NonZero;
}
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [c]})).unwrap();
let r = s.execute("type.retype", &json!({}));
if opacity == 1.0 {
let r = r.unwrap();
assert_eq!(r["texts"], json!(["i", "i"]), "opaque, the two lines become type: {r}");
} else {
assert!(r.is_err(), "translucent, the compound stays an outline: {r:?}");
}
}
}
#[test]
fn overlapping_exact_glyphs_stay_an_outline_when_near_matches_are_allowed() {
// Exact parts the even-odd rule rejects stay rejected when the near phase finds them again.
for dx in [-9.0, -11.0, -12.0, -13.0, -14.0] {
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "oo", "size": 40}));
let kids = children_of(&s, g);
s.execute("object.move", &json!({"ids": [kids[1]], "dx": dx, "dy": 0})).unwrap();
s.execute("select.set", &json!({"ids": kids})).unwrap();
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [c]})).unwrap();
for tolerance in [0.0, 0.05] {
if let Ok(r) = s.execute("type.retype", &json!({"tolerance": tolerance})) {
panic!("the overlapping o's became type at dx {dx}, tolerance {tolerance}: {r}");
}
}
}
}
#[test]
fn exact_parts_of_a_compound_are_checked_at_tolerance_zero() {
let mut s = session();
// A T and an o whose boxes overlap by 4 units, one painted area apart (the o sits under the
// bar's arm): a strip that the probes of tolerance 0.05 cannot see into but those of an exact
// match can. Both parts match exactly, so asking for near matches does not change the result.
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "To", "size": 40}));
let kids = children_of(&s, g);
let (t, o) = (kids[0], kids[1]);
let bounds = |s: &Session, id: u64| s.doc().unwrap().doc.node(NodeId(id)).unwrap().geometric_bounds().unwrap();
let dx = bounds(&s, t).x1 - 4.0 - bounds(&s, o).x0;
s.execute("object.move", &json!({"ids": [o], "dx": dx, "dy": 0})).unwrap();
s.execute("select.set", &json!({"ids": kids})).unwrap();
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
for params in [json!({}), json!({"tolerance": 0.05})] {
s.execute("select.set", &json!({"ids": [c]})).unwrap();
let before = s.doc().unwrap().doc.clone();
let r = s.execute("type.retype", &params).unwrap();
assert_eq!(r["unmatched"], json!([]), "{params}: {r}");
assert!(s.doc().unwrap().doc.node(NodeId(c)).is_none(), "{params}: the compound becomes type");
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc == before, "{params}: undo restores it");
}
}
#[test]
fn glyphs_side_by_side_in_an_even_odd_compound_still_become_type() {
let mut s = session();
let c = one_compound(&mut s, "oo");
s.execute("select.set", &json!({"ids": [c]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!(["oo"]), "{r}");
}
#[test]
fn a_compound_whose_glyph_stays_an_outline_keeps_its_other_glyphs_too() {
let mut s = session();
// An A (two contours), and far below it a period: a lone one-contour glyph beside other
// shapes stays an outline, so the A, in the same compound, must stay too.
let t = outlined(&mut s, json!({"x": 40, "y": 100, "text": "A", "size": 40}));
let dot = outlined(&mut s, json!({"x": 40, "y": 300, "text": ".", "size": 40}));
let paths = |s: &Session, id: u64| match s.doc().unwrap().doc.node(NodeId(id)).unwrap().children() {
Some(c) => c.iter().map(|c| c.id.0).collect(),
None => vec![id],
};
let mut ids: Vec<u64> = paths(&s, t);
ids.extend(paths(&s, dot));
assert_eq!(ids.len(), 2, "one path each");
s.execute("select.set", &json!({"ids": ids})).unwrap();
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
let r = s.execute("shape.rectangle", &json!({"x": 300, "y": 300, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [c, r]})).unwrap();
let before = s.doc().unwrap().doc.clone();
let e = match s.execute("type.retype", &json!({})) {
Ok(r) => panic!("the A became type without its period: {r}"),
Err(e) => e.to_string(),
};
assert!(e.contains("(2 checked)"), "{e}");
assert!(s.doc().unwrap().doc == before, "nothing changes");
}
#[test]
fn a_split_takes_a_shorter_run_when_the_longest_leaves_a_group_unmatched() {
use kurbo::Shape;
// Three groups A, B and C side by side. A and B together are a glyph, but then C alone is
// none; A alone and B and C together are glyphs, so the split is A, BC.
let mut p = kurbo::BezPath::new();
for x in [0.0, 100.0, 200.0] {
p.extend(kurbo::Rect::new(x, 0.0, x + 40.0, 40.0).path_elements(0.1));
}
let find = |path: &kurbo::BezPath, part: bool, _near: bool| -> Vec<&'static str> {
let b = path.bounding_box();
match (part, b.x0.round() as i64, b.x1.round() as i64) {
(true, 0, 140) => vec!["AB"],
(true, 0, 40) => vec!["A"],
(true, 100, 240) => vec!["BC"],
_ => vec![],
}
};
let groups = all_groups(&p);
assert_eq!(super::parts(&p, &groups, &find, &|_, _| true), vec![vec!["A"], vec!["BC"]]);
// A split the parts' paint does not allow is dropped.
assert!(super::parts(&p, &groups, &find, &|_, _| false).is_empty());
// With no way to match every group, nothing.
let none = |path: &kurbo::BezPath, part: bool, _near: bool| -> Vec<&'static str> {
let b = path.bounding_box();
if part && b.x0.round() as i64 == 0 && b.x1.round() as i64 == 140 { vec!["AB"] } else { vec![] }
};
assert!(super::parts(&p, &groups, &none, &|_, _| true).is_empty());
}
#[test]
fn a_split_the_paint_check_rejects_gives_way_to_another_complete_split() {
use kurbo::Shape;
let mut p = kurbo::BezPath::new();
for x in [0.0, 100.0, 200.0] {
p.extend(kurbo::Rect::new(x, 0.0, x + 40.0, 40.0).path_elements(0.1));
}
let find = |path: &kurbo::BezPath, part: bool, _near: bool| -> Vec<&'static str> {
let b = path.bounding_box();
match (part, b.x0.round() as i64, b.x1.round() as i64) {
(true, 0, 140) => vec!["AB"],
(true, 0, 40) => vec!["A"],
(true, 100, 140) => vec!["B"],
(true, 200, 240) => vec!["C"],
_ => vec![],
}
};
let groups = all_groups(&p);
// The longest runs first (AB, C) are rejected; the three single glyphs are kept.
let singles = |runs: &[kurbo::BezPath], _near: bool| runs.len() == 3;
assert_eq!(super::parts(&p, &groups, &find, &singles), vec![vec!["A"], vec!["B"], vec!["C"]]);
// When no complete split is accepted, nothing.
assert!(super::parts(&p, &groups, &find, &|_, _| false).is_empty());
}
#[test]
fn a_split_between_the_longest_and_the_shortest_runs_is_tried() {
use kurbo::Shape;
// Four groups A, B, C and D. ABC and D (the longest runs first) and the four single glyphs
// (the shortest) are complete splits the paint check rejects; AB and CD is the one it accepts.
let mut p = kurbo::BezPath::new();
for x in [0.0, 100.0, 200.0, 300.0] {
p.extend(kurbo::Rect::new(x, 0.0, x + 40.0, 40.0).path_elements(0.1));
}
let find = |path: &kurbo::BezPath, part: bool, _near: bool| -> Vec<&'static str> {
let b = path.bounding_box();
match (part, b.x0.round() as i64, b.x1.round() as i64) {
(true, 0, 240) => vec!["ABC"],
(true, 0, 140) => vec!["AB"],
(true, 200, 340) => vec!["CD"],
(true, 0, 40) => vec!["A"],
(true, 100, 140) => vec!["B"],
(true, 200, 240) => vec!["C"],
(true, 300, 340) => vec!["D"],
_ => vec![],
}
};
let groups = all_groups(&p);
let pairs = |runs: &[kurbo::BezPath], _near: bool| runs.len() == 2 && runs.first().is_some_and(|r| r.bounding_box().x1.round() as i64 == 140);
assert_eq!(super::parts(&p, &groups, &find, &pairs), vec![vec!["AB"], vec!["CD"]]);
}
#[test]
fn at_most_max_split_tries_complete_splits_are_checked() {
use kurbo::Shape;
// Twelve groups, every run of up to three of them a glyph: far more complete splits than the
// cap. The paint check is asked about the cap's number of them and no more, and each run is
// looked up at most once.
let mut p = kurbo::BezPath::new();
for i in 0..12 {
let x = f64::from(i) * 100.0;
p.extend(kurbo::Rect::new(x, 0.0, x + 40.0, 40.0).path_elements(0.1));
}
let groups = all_groups(&p);
assert_eq!(groups.len(), 12);
let looked_up = std::cell::Cell::new(0usize);
let find = |_: &kurbo::BezPath| -> Vec<&'static str> {
looked_up.set(looked_up.get() + 1);
vec!["glyph"]
};
let asked = &std::cell::Cell::new(0usize);
let accept_at = |n: usize| {
move |_: &[kurbo::BezPath]| {
asked.set(asked.get() + 1);
asked.get() == n
}
};
// Rejected every time: the search stops at the cap.
assert!(super::split_parts(&groups, &find, &accept_at(usize::MAX)).is_empty());
assert_eq!(asked.get(), super::MAX_SPLIT_TRIES);
assert!(looked_up.get() <= super::MAX_RUN * groups.len(), "{} lookups", looked_up.get());
// A first split that is accepted looks up its own runs only: four runs of three groups.
asked.set(0);
looked_up.set(0);
assert_eq!(super::split_parts(&groups, &find, &accept_at(1)).len(), 4);
assert_eq!(looked_up.get(), 4);
// The last split tried is still taken; the one past the cap is not tried.
asked.set(0);
assert!(super::split_parts(&groups, &find, &accept_at(super::MAX_SPLIT_TRIES)).len() > 1);
asked.set(0);
assert!(super::split_parts(&groups, &find, &accept_at(super::MAX_SPLIT_TRIES + 1)).is_empty());
assert_eq!(asked.get(), super::MAX_SPLIT_TRIES);
}
/// `path`'s contour groups, with no limit on the contours grouped.
fn all_groups(path: &kurbo::BezPath) -> Vec<kurbo::BezPath> {
let mut budget = usize::MAX;
super::split_groups(path, &mut budget)
}
#[test]
fn exact_matches_of_the_parts_come_before_a_near_match_of_the_whole() {
use kurbo::Shape;
// Two groups side by side, each exactly a glyph (two periods), and the whole only nearly one
// (a dieresis): the parts win.
let mut p = kurbo::BezPath::new();
for x in [0.0, 100.0] {
p.extend(kurbo::Rect::new(x, 0.0, x + 40.0, 40.0).path_elements(0.1));
}
let find = |path: &kurbo::BezPath, part: bool, near: bool| -> Vec<&'static str> {
let b = path.bounding_box();
match (part, near, b.x0.round() as i64, b.x1.round() as i64) {
(false, true, 0, 140) => vec!["dieresis"],
(true, _, 0, 40) | (true, _, 100, 140) => vec!["period"],
_ => vec![],
}
};
let groups = all_groups(&p);
assert_eq!(super::parts(&p, &groups, &find, &|_, _| true), vec![vec!["period"], vec!["period"]]);
// When the parts match only nearly too, the whole near match comes first.
let near_only = |path: &kurbo::BezPath, part: bool, near: bool| -> Vec<&'static str> {
let b = path.bounding_box();
match (part, near, b.x0.round() as i64, b.x1.round() as i64) {
(false, true, 0, 140) => vec!["dieresis"],
(true, true, 0, 40) | (true, true, 100, 140) => vec!["period"],
_ => vec![],
}
};
assert_eq!(super::parts(&p, &groups, &near_only, &|_, _| true), vec![vec!["dieresis"]]);
// The split's paint check is told whether the parts were found nearly: exact parts are
// checked at tolerance 0 whatever tolerance the command was given.
let seen = std::cell::RefCell::new(vec![]);
let record = |_: &[kurbo::BezPath], near: bool| {
seen.borrow_mut().push(near);
true
};
assert_eq!(super::parts(&p, &groups, &find, &record), vec![vec!["period"], vec!["period"]]);
assert_eq!(*seen.borrow(), vec![false]);
seen.borrow_mut().clear();
let split_near_only = |path: &kurbo::BezPath, part: bool, near: bool| -> Vec<&'static str> {
let b = path.bounding_box();
match (part, near, b.x0.round() as i64, b.x1.round() as i64) {
(true, true, 0, 40) | (true, true, 100, 140) => vec!["period"],
_ => vec![],
}
};
assert_eq!(super::parts(&p, &groups, &split_near_only, &record), vec![vec!["period"], vec!["period"]]);
assert_eq!(*seen.borrow(), vec![true]);
}
#[test]
fn a_shape_that_lost_a_glyph_drops_the_lines_of_its_other_glyphs() {
use std::collections::HashMap;
// Shapes 1 and 2 are two glyphs each, shape 3 one. Line 0 sets one glyph of 1 and one of 2;
// line 1 sets the other glyph of 2 and shape 3. Shape 1's other glyph is set nowhere.
let (a, b, c) = (NodeId(1), NodeId(2), NodeId(3));
let glyphs_of: HashMap<NodeId, usize> = [(a, 2), (b, 2), (c, 1)].into();
let lines = vec![vec![a, b], vec![b, c]];
let dropped = super::partial_lines(&lines, &glyphs_of);
assert!(dropped.contains(&0), "shape 1 is set only in part: {dropped:?}");
assert!(dropped.contains(&1), "then shape 2 is too: {dropped:?}");
// Every glyph set: nothing goes.
let whole = vec![vec![a, b], vec![a, b, c]];
assert!(super::partial_lines(&whole, &glyphs_of).is_empty());
}
#[test]
fn a_compound_of_too_many_path_elements_is_not_grouped() {
// Two contours side by side, each a polygon of `k` corners.
let two = |k: usize| {
let mut p = kurbo::BezPath::new();
for x in [0.0, 300.0] {
for i in 0..k {
let a = i as f64 / k as f64 * std::f64::consts::TAU;
let q = kurbo::Point::new(x + 100.0 + 100.0 * a.cos(), 100.0 + 100.0 * a.sin());
if i == 0 { p.move_to(q) } else { p.line_to(q) }
}
p.close_path();
}
p
};
let mut budget = usize::MAX;
assert_eq!(super::split_groups(&two(100), &mut budget).len(), 2, "a small compound is grouped");
let big = two(super::MAX_SPLIT_ELEMENTS / 2);
assert!(big.elements().len() > super::MAX_SPLIT_ELEMENTS);
let mut budget = usize::MAX;
assert!(super::split_groups(&big, &mut budget).is_empty(), "past the element limit it is matched whole only");
assert_eq!(budget, usize::MAX, "and takes no contours from the budget");
}
#[test]
fn the_runs_and_near_keys_a_selection_is_looked_up_by_are_bounded() {
use kurbo::Shape;
use vectorcraft_text::retype::MAX_NEAR_KEYS;
// A compound path of `n` rectangles side by side, each of another width: every run of up to
// three of them has its own near key.
let row = |n: usize| {
let mut p = kurbo::BezPath::new();
for i in 0..n {
let x = i as f64 * 100.0;
p.extend(kurbo::Rect::new(x, 0.0, x + 10.0 + i as f64 * 0.37, 40.0).path_elements(0.1));
}
p
};
// Each shape with its contour groups, as the command looks them up.
let with_groups = |shapes: &[kurbo::BezPath]| -> Vec<(kurbo::BezPath, Vec<kurbo::BezPath>)> {
let mut budget = super::MAX_SPLIT_TOTAL_CONTOURS;
shapes.iter().map(|p| (p.clone(), super::split_groups(p, &mut budget))).collect()
};
let keys_of = |shapes: &[(kurbo::BezPath, Vec<kurbo::BezPath>)], tolerance: f64| {
super::lookup_keys(shapes.iter().map(|(p, g)| (p, g.as_slice())), tolerance)
};
let few = with_groups(&[row(20)]);
assert_eq!(super::runs(&few[0].1).len(), 20 + 19 + 18, "every run of 1 to 3 groups");
let (_, keys) = keys_of(&few, 0.01);
assert!(keys.len() > 20, "{}", keys.len());
assert!(keys_of(&few, 0.0).1.is_empty(), "no near keys without a tolerance");
// Past 256 groups the shape is matched whole only, and past 512 contours its contours are not
// grouped at all.
assert!(all_groups(&row(300)).is_empty());
assert_eq!(all_groups(&row(256)).len(), 256);
let mut nested = kurbo::BezPath::new();
for i in 0..200 {
// Each square with two squares inside it: 200 groups of 3 contours.
let x = i as f64 * 100.0;
nested.extend(kurbo::Rect::new(x, 0.0, x + 90.0, 90.0).path_elements(0.1));
nested.extend(kurbo::Rect::new(x + 10.0, 10.0, x + 40.0, 40.0).path_elements(0.1));
nested.extend(kurbo::Rect::new(x + 50.0, 50.0, x + 80.0, 80.0).path_elements(0.1));
}
assert!(all_groups(&nested).is_empty(), "600 contours");
assert_eq!(vectorcraft_text::retype::clusters(&nested).len(), 200, "which would make 200 groups");
// Many shapes with many runs each: the near keys stop at the cap.
let mut shapes: Vec<kurbo::BezPath> = (0..8).map(|k| kurbo::Affine::scale_non_uniform(1.0, 1.0 + k as f64 * 0.5) * row(200)).collect();
let (_, keys) = keys_of(&with_groups(&shapes), 0.01);
assert_eq!(keys.len(), MAX_NEAR_KEYS);
// A plain shape selected after them still gets its own near key: whole shapes come first.
let plain = kurbo::Circle::new((0.0, 0.0), 30.0).to_path(0.1);
let key = vectorcraft_text::retype::near_key(&plain).unwrap();
shapes.push(plain);
let (_, keys) = keys_of(&with_groups(&shapes), 0.01);
assert!(keys.contains(&key));
// One command groups at most MAX_SPLIT_TOTAL_CONTOURS contours: the shapes after them are
// matched whole only.
let full = vec![row(256); super::MAX_SPLIT_TOTAL_CONTOURS / 256 + 1];
let split: Vec<usize> = with_groups(&full).iter().map(|(_, g)| g.len()).collect();
assert!(split[..split.len() - 1].iter().all(|n| *n == 256), "{split:?}");
assert_eq!(split.last(), Some(&0));
}
#[test]
fn slight_tracking_without_spaces_is_kept() {
// Tracking 3 moves the last glyph less than the layout check notices: both readings draw it.
@@ -897,7 +1718,7 @@ fn lines_in(s: &Session, g: u64) -> Vec<super::Line> {
for pc in &pieces {
let cands: Vec<_> = index.matches(&pc.path).into_iter().filter(|m| m.face.id() == face).collect();
if !lines.last_mut().is_some_and(|l| super::join(l, pc, &cands)) {
lines.extend(super::new_line(pc, &cands));
lines.extend(super::new_line(pc, &cands, 0.0));
}
}
lines
+19 -4
View File
@@ -31,7 +31,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Apply Graphic Style",
["Window", "Graphic Styles"],
None,
"{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (with `add`: of the kinds of row the style shows) and, without `add`, the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows (with `add`: of the kinds of row the style shows) and, without `add`, its object opacity and blend mode for every label or line of its kind. With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}",
"{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. In the contents of a Live Paint group, each face takes only the style's fills and each edge only its strokes, and neither is linked. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (with `add`: of the kinds of row the style shows) and, without `add`, the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows (with `add`: of the kinds of row the style shows) and, without `add`, its object opacity and blend mode for every label or line of its kind. With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}",
has_doc,
style_apply
),
@@ -351,6 +351,9 @@ fn style_apply(s: &mut Session, p: &Value) -> Result<Value> {
// The series groups their paths stand for: a style that replaces the appearance clears what they hold themselves,
// and a style added on top unlinks them.
let groups = super::appearance::stood_for(&own, &ids);
// In the contents of a Live Paint group, a face takes the style's fills and an edge its strokes.
let (faces, edges) = super::appearance::contents_parts(s, p)?;
let part = |id: &NodeId| (faces.contains(id) || edges.contains(id)).then(|| faces.contains(id));
if ids.is_empty() {
if p.get("ids").is_some() || p.get("id").is_some() {
return Err(bad("graphicStyle.apply", "no such objects"));
@@ -361,13 +364,20 @@ fn style_apply(s: &mut Session, p: &Value) -> Result<Value> {
return Ok(json!({ "newArt": true }));
}
let before = s.doc()?.doc.clone();
s.edit("Apply Graphic Style", |d, _| {
// An apply that changes nothing (a fill-only style added to edges only) records no undo step.
super::overprint::edit_counted(s, "Apply Graphic Style", |d| {
if add {
let g = d.graphic_styles[i].clone();
for id in &ids {
if let Some(n) = d.node_mut(*id) {
let ap = g.appearance_on(n).into_owned();
n.appearance.items.extend(ap.items);
let kind = part(id);
let rows: Vec<_> = ap.items.into_iter().filter(|it| kind.is_none_or(|fill| it.is_fill() == fill)).collect();
// A face or edge the style adds nothing to keeps its appearance and its link.
if kind.is_some() && rows.is_empty() && ap.effects.is_empty() {
continue;
}
n.appearance.items.extend(rows);
n.appearance.effects.extend(ap.effects);
n.extras_mut().graphic_style = None;
}
@@ -387,13 +397,18 @@ fn style_apply(s: &mut Session, p: &Value) -> Result<Value> {
let mut shared = None;
for id in &ids {
apply_style(d, *id, &g, &mut shared, chars);
// A face or edge that keeps only the rows of its kind no longer has the style's look, so it is not linked.
if let (Some(fill), Some(n)) = (part(id), d.node_mut(*id)) {
super::appearance::keep_rows_of_kind(n, fill);
n.extras_mut().graphic_style = None;
}
}
super::appearance::clear_stood_for(d, &groups);
super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false, true);
// A label or graph line keeps its new rows for its kind.
super::graph::capture_label_rows(d, &ids);
}
Ok(())
Ok(usize::from(*d != *before))
})?;
ok()
}
+8 -8
View File
@@ -15,7 +15,7 @@ use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, Symbol, SymbolNineSlice};
use vectorcraft_geom::{Affine, Anchor, AnchorKind, PathData, Point, Rect, SubPath, shapes};
use super::brushsym::{CURRENT_SYMBOL, natural_size, normalize, place_xf, set_natural_size};
use super::brushsym::{CURRENT_SYMBOL, Placement, natural_size, normalize, place_xf, set_natural_size};
use super::clipboard::Clipboard;
use super::clipboard::resources::SwatchChoices;
use super::swatch::str_list;
@@ -50,7 +50,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add to Symbols",
["Window", "Symbol Libraries"],
None,
"{library: id or name, name? | names?: [symbol names in the library] (default: all of it), place?: false (also place an instance of the first one, its registration point at x, y: default the first artboard's centre), x?, y?, swatchConflict? (as edit.paste)} copy library symbols into the document's Symbols as one undo step (with the place), with their Symbol Options and the resources they use (the symbols they nest, patterns, swatches, brushes, graphic styles, images). A symbol the document already has (same name and art) isn't added again; a name another symbol has gets a number (\"Star 2\"). The first one becomes the current symbol → {library, names: [each symbol's name in the document], added: [names added], existing: [names already there], placed?: id}",
"{library: id or name, name? | names?: [symbol names in the library] (default: all of it), place?: false (also place an instance of the first one, its registration point at x, y: default the first artboard's centre, in the stacking order symbol.place gives it, Draw Behind included), x?, y?, swatchConflict? (as edit.paste)} copy library symbols into the document's Symbols as one undo step (with the place), with their Symbol Options and the resources they use (the symbols they nest, patterns, swatches, brushes, graphic styles, images). A symbol the document already has (same name and art) isn't added again; a name another symbol has gets a number (\"Star 2\"). The first one becomes the current symbol → {library, names: [each symbol's name in the document], added: [names added], existing: [names already there], placed?: id}",
has_doc,
add
),
@@ -59,7 +59,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Place Symbol Instance",
[],
None,
"{sourceDocument: uid, name: a symbol of that document, x?, y?} place an instance of a symbol of another open document so its registration point is at (x, y) (default: the first artboard's center), as a symbol dragged from that document's Symbols panel onto the canvas is placed. The symbol, the symbols it nests and the resources they use are added as a drop of art from that document adds them, in the same undo step as the instance: a symbol the active document already has with the same name, art and Symbol Options is used, and one with the same name but other art or Symbol Options gets a number (\"Leaf 2\"); each symbol added takes its Symbol Options along. When sourceDocument is the active document, its own symbol is placed, as symbol.place places it. An error, with no edit, when that document is no longer open or has no symbol `name` → {id, name: the symbol's name in the active document}",
"{sourceDocument: uid, name: a symbol of that document, x?, y?} place an instance of a symbol of another open document so its registration point is at (x, y) (default: the first artboard's center), in the stacking order symbol.place gives it (Draw Behind included), as a symbol dragged from that document's Symbols panel onto the canvas is placed. The symbol, the symbols it nests and the resources they use are added as a drop of art from that document adds them, in the same undo step as the instance: a symbol the active document already has with the same name, art and Symbol Options is used, and one with the same name but other art or Symbol Options gets a number (\"Leaf 2\"); each symbol added takes its Symbol Options along. When sourceDocument is the active document, its own symbol is placed, as symbol.place places it. An error, with no edit, when that document is no longer open or has no symbol `name` → {id, name: the symbol's name in the active document}",
has_doc,
place_from_document
),
@@ -816,7 +816,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
let doc_names: Vec<String> = picked.iter().map(|n| target(&imported.renamed, n)).collect();
let centre = st.doc.artboards.first().map(|a| a.rect.center()).unwrap_or(Point::ZERO);
let at = if place { Some(Point::new(number_or(p, "x", centre.x, C)?, number_or(p, "y", centre.y, C)?)) } else { None };
let parent = if place { st.target_parent()? } else { None };
let spot = if place { Some(Placement::of(s)?) } else { None };
let mut out = json!({ "library": shown_library_id(s, &info.id) });
if imported.added > 0 || place {
let placed = s.edit("Add to Symbols", |d, sel| {
@@ -830,10 +830,10 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
}
let Some(first) = doc_names.first() else { return Ok(None) };
d.unknown.insert(CURRENT_SYMBOL.into(), json!(first));
let Some(at) = at else { return Ok(None) };
let (Some(at), Some(spot)) = (at, &spot) else { return Ok(None) };
let xf = place_xf(at, natural_size(d, first), d.symbol_registration(first));
let id = d.alloc_id();
d.insert(parent, usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: first.clone(), xf }))?;
spot.insert(d, Node::new(id, NodeKind::SymbolInstance { symbol: first.clone(), xf }))?;
sel.set([id]);
Ok(Some(id))
})?;
@@ -860,7 +860,7 @@ fn place_from_document(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.doc()?;
let centre = st.doc.artboards.first().map(|a| a.rect.center()).unwrap_or(Point::ZERO);
let at = Point::new(number_or(p, "x", centre.x, C)?, number_or(p, "y", centre.y, C)?);
let parent = st.target_parent()?;
let spot = Placement::of(s)?;
let same = uid == st.uid;
let src = s.documents().iter().find(|d| d.uid == uid).map(|d| Arc::clone(&d.doc));
let src = src.ok_or_else(|| bad(C, "the document the symbol came from is no longer open"))?;
@@ -883,7 +883,7 @@ fn place_from_document(s: &mut Session, p: &Value) -> Result<Value> {
};
let xf = place_xf(at, natural_size(d, &placed), d.symbol_registration(&placed));
let id = d.alloc_id();
d.insert(parent, usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: placed.clone(), xf }))?;
spot.insert(d, Node::new(id, NodeKind::SymbolInstance { symbol: placed.clone(), xf }))?;
sel.set([id]);
Ok((id, placed))
})?;
+1
View File
@@ -112,6 +112,7 @@ mod live;
mod livecorners;
mod maskview;
pub(super) mod menucmds;
mod mesh_picks;
mod nativefile;
mod newart;
mod newdoc;
+67
View File
@@ -2228,6 +2228,73 @@ fn place_and_break_link_round_trip_geometry() {
assert_eq!(n.appearance.stroke_width(), 1.0, "strokes are not scaled by normalisation");
}
/// In Draw Behind, Place Symbol Instance puts the instance directly below the bottommost selected
/// object (beside the compound path that holds a selected path, above a clipping path), or at the
/// bottom of the current layer with nothing selected, selected and in one undo step. Draw Normal
/// and Draw Inside keep it on top, and a locked layer refuses it with no edit.
#[test]
fn placed_instances_go_below_the_selection_in_draw_behind() {
let mut s = session();
let (inst, name, _) = make_symbol(&mut s);
let (a, b) = (rect(&mut s, 0.0, 0.0, 10.0, 10.0), rect(&mut s, 20.0, 0.0, 10.0, 10.0));
let layer = s.doc().unwrap().doc.layers[0].id;
let kids = |s: &Session, id: NodeId| node(s, id).children().unwrap().iter().map(|c| c.id).collect::<Vec<_>>();
let place = |s: &mut Session| NodeId(s.execute("symbol.place", &json!({"name": name, "x": 300, "y": 200})).unwrap()["id"].as_u64().unwrap());
s.execute("view.drawMode", &json!({"mode": "behind"})).unwrap();
select(&mut s, &[b]);
let before = undo_len(&s);
let p = place(&mut s);
assert_eq!(kids(&s, layer), vec![inst, a, p, b], "directly below the selected object");
assert_eq!(undo_len(&s), before + 1);
assert_eq!(s.doc().unwrap().selection.objects, [p]);
assert!(close(bounds(&s, p), Rect::new(260.0, 180.0, 340.0, 220.0), 1e-9), "{:?}", bounds(&s, p));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(kids(&s, layer), vec![inst, a, b]);
// Below the bottommost of several selected objects.
select(&mut s, &[b, a]);
let p = place(&mut s);
assert_eq!(kids(&s, layer), vec![inst, p, a, b]);
s.execute("edit.undo", &json!({})).unwrap();
// With nothing selected, at the bottom of the current layer.
select(&mut s, &[]);
let p = place(&mut s);
assert_eq!(kids(&s, layer), vec![p, inst, a, b]);
s.execute("edit.undo", &json!({})).unwrap();
// A path selected in a compound path: beside the compound path, not inside it.
select(&mut s, &[a, b]);
s.execute("object.compoundPath.make", &json!({})).unwrap();
let compound = kids(&s, layer)[1];
let member = kids(&s, compound)[1];
select(&mut s, &[member]);
let p = place(&mut s);
assert_eq!(kids(&s, layer), vec![inst, p, compound]);
assert_eq!(kids(&s, compound).len(), 2);
s.execute("edit.undo", &json!({})).unwrap();
// Draw Normal and Draw Inside put it on top of the layer.
for mode in ["normal", "inside"] {
select(&mut s, &[compound]);
s.execute("view.drawMode", &json!({"mode": mode})).unwrap();
let p = place(&mut s);
assert_eq!(kids(&s, layer), vec![inst, compound, p], "{mode}");
s.execute("edit.undo", &json!({})).unwrap();
}
// In a clipping layer the clipping path stays at the bottom, the selected clipping path too.
s.execute("view.drawMode", &json!({"mode": "behind"})).unwrap();
s.execute("layer.clippingMask.toggle", &json!({"id": layer.0})).unwrap();
assert_eq!(kids(&s, layer), vec![compound, inst]);
for picked in [&[][..], &[compound]] {
select(&mut s, picked);
let p = place(&mut s);
assert_eq!(kids(&s, layer), vec![compound, p, inst], "{picked:?}");
s.execute("edit.undo", &json!({})).unwrap();
}
// A locked layer takes nothing.
s.execute("layer.setProps", &json!({"id": layer.0, "locked": true})).unwrap();
let before = (undo_len(&s), s.doc().unwrap().doc.clone());
assert!(s.execute("symbol.place", &json!({"name": name})).is_err());
assert_eq!((undo_len(&s), &s.doc().unwrap().doc), (before.0, &before.1));
}
#[test]
fn hidden_instance_fill_does_not_tint_expanded_symbol_art() {
for command in ["symbol.breakLink", "object.expand"] {
+87
View File
@@ -4630,6 +4630,93 @@ fn live_paint_group_with_only_source_paths_ignores_add_fill_and_add_stroke_of_it
assert!(s.execute("appearance.addFill", &json!({"target": "contents"})).is_err(), "no selection is still refused");
}
/// Whether every face of Live Paint group `g` holds only fill rows and every edge only stroke rows.
fn parts_hold_their_kind(s: &Session, g: NodeId) -> bool {
let (faces, edges) = part_looks(s, g);
faces.iter().all(|a| a.items.iter().all(|it| it.is_fill())) && edges.iter().all(|a| a.items.iter().all(|it| !it.is_fill()))
}
/// A graphic style applied to the contents of a Live Paint group, replacing their appearance or added to it, gives
/// the faces its fills and the edges its strokes, and the faces and edges are not linked to it.
#[test]
fn live_paint_group_contents_take_a_graphic_style_by_kind() {
let red = Paint::solid(Color::from_hex("#ff0000").unwrap());
let blue = Paint::solid(Color::from_hex("#0000ff").unwrap());
for add in [false, true] {
let mut s = session();
let g = live(&mut s);
let r = rect(&mut s, 400.0, 0.0, 50.0, 50.0);
s.execute("select.set", &json!({"ids": [r.0]})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap();
s.execute("graphicStyle.new", &json!({"name": "Both", "id": r.0})).unwrap();
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
s.execute("graphicStyle.apply", &json!({"name": "Both", "target": "contents", "add": add})).unwrap();
assert!(parts_hold_their_kind(&s, g), "add {add}: faces hold fills and edges strokes");
let (faces, edges) = part_looks(&s, g);
assert!(faces.iter().all(|a| a.items.iter().any(|it| *it.paint() == red)), "add {add}: each face takes the style's fill");
assert!(edges.iter().all(|a| a.items.iter().any(|it| *it.paint() == blue)), "add {add}: each edge takes the style's stroke");
let n = node(&s, g);
let mut parts = vectorcraft_tools::builder::faces(&n).into_iter().chain(vectorcraft_tools::builder::edges(&n));
assert!(parts.all(|p| p.extras().graphic_style.is_none()), "add {add}: no face or edge is linked");
}
}
/// A fill-only graphic style added to the contents of a Live Paint group without faces changes nothing and records no
/// undo step.
#[test]
fn live_paint_group_contents_without_faces_take_no_fill_only_style() {
let mut s = session();
let g = live(&mut s);
let faces: Vec<NodeId> = vectorcraft_tools::builder::faces(&node(&s, g)).iter().map(|p| p.id).collect();
s.edit("t", |d, _| {
d.children_mut(Some(g)).unwrap().retain(|c| !faces.contains(&c.id));
Ok(())
})
.unwrap();
let r = rect(&mut s, 400.0, 0.0, 50.0, 50.0);
s.edit("t", |d, _| {
let fill = AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::from_hex("#ff0000").unwrap())));
d.node_mut(r).unwrap().appearance = vectorcraft_doc::Appearance { items: vec![fill], ..Default::default() }.into();
Ok(())
})
.unwrap();
s.execute("graphicStyle.new", &json!({"name": "Fill", "id": r.0})).unwrap();
// The edges are linked to a style of their own, which they keep.
let edge = vectorcraft_tools::builder::edges(&node(&s, g))[0].id;
s.execute("graphicStyle.new", &json!({"name": "Edge", "id": edge.0})).unwrap();
assert!(node(&s, g).children().unwrap().iter().any(|c| c.extras().graphic_style.is_some()), "an edge is linked");
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
let (before, undo) = (node(&s, g), s.doc().unwrap().history.undo.len());
s.execute("graphicStyle.apply", &json!({"name": "Fill", "target": "contents", "add": true})).unwrap();
assert_eq!(node(&s, g), before, "the edges keep their rows and their link");
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step");
}
/// Clear Appearance and Reduce to Basic Appearance on the contents of a Live Paint group leave each face with fill
/// rows only and each edge with stroke rows only.
#[test]
fn live_paint_group_contents_clear_and_reduce_keep_each_part_to_its_kind() {
for cmd in ["appearance.clear", "appearance.reduceToBasic"] {
let mut s = session();
let g = live(&mut s);
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff00ff"})).unwrap();
s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap();
// A face and an edge given rows of the other kind through their own ids.
let n = node(&s, g);
let (face, edge) = (vectorcraft_tools::builder::faces(&n)[0].id, vectorcraft_tools::builder::edges(&n)[0].id);
s.execute("appearance.addStroke", &json!({"ids": [face.0]})).unwrap();
s.execute("appearance.addFill", &json!({"ids": [edge.0]})).unwrap();
assert!(!parts_hold_their_kind(&s, g), "{cmd}: the face and the edge hold rows of the other kind");
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
s.execute(cmd, &json!({"target": "contents"})).unwrap();
assert!(parts_hold_their_kind(&s, g), "{cmd}: faces hold fills and edges strokes");
let (faces, edges) = part_looks(&s, g);
assert!(faces.iter().chain(&edges).all(|a| !a.items.is_empty()), "{cmd}: each face and edge keeps a row");
}
}
/// A selected Live Paint group with no part of the edited kind is still a selection: a stroke edit
/// of a group without edges, or a fill gradient edit of a group without faces, changes nothing and
/// leaves the settings for new art as they are.
+31
View File
@@ -2617,6 +2617,37 @@ fn confined_screens_rows_check_the_artboard_each_file_holds() {
}
}
/// A confined caller's single-file PDF with Preserve Editing of several artboards carries the art
/// of every artboard on its pages: an image linked outside the read roots on the second artboard
/// alone refuses it. A single-file PDF of assets is refused before any link is checked.
#[test]
fn confined_single_file_pdf_checks_every_artboard_it_carries() {
use crate::file_access::{AutomationRoots, confine};
let away = Folder::new("single-pdf-away");
let home = Folder::new("single-pdf-home");
let photo = away.file("photo.png");
write(&photo, &png(60, 30, RED));
let mut s = session();
let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
let rect: vectorcraft_doc::NodeId = serde_json::from_value(r["id"].clone()).unwrap();
s.execute("artboard.new", &json!({"x": 2000, "y": 0, "width": 200, "height": 200})).unwrap();
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
let p = |folder: &str| json!({"range": "1-2", "folder": home.file(folder), "pdfs": "single", "formats": [{"format": "pdf", "preserveEditing": true}]});
let r = confine(roots.as_ref(), || s.execute("document.exportForScreens", &p("plain"))).unwrap_or_else(|e| panic!("{e}"));
assert_eq!(r["files"].as_array().map(Vec::len), Some(1), "{r}");
let r = s.execute("file.place", &json!({"path": photo, "at": [2100, 100]})).unwrap();
assert_eq!(r["linked"], true, "{r}");
let e = confine(roots.as_ref(), || s.execute("document.exportForScreens", &p("linked"))).expect_err("second artboard links outside").to_string();
assert!(e.contains("a linked image file is outside the read roots"), "{e}");
assert!(!Path::new(&home.file("linked")).exists(), "the refused export writes no folder");
let asset = s.execute("assets.add", &json!({"ids": [rect.0]})).unwrap()["assets"][0].as_u64().unwrap();
let assets = json!({"assets": [asset], "folder": home.file("assets"), "pdfs": "single", "formats": [{"format": "pdf", "preserveEditing": true}]});
let e = confine(roots.as_ref(), || s.execute("assets.export", &assets)).expect_err("single-file PDF of assets").to_string();
assert!(e.contains("pdfs `single` writes artboards as the pages of one PDF"), "{e}");
assert!(!Path::new(&home.file("assets")).exists(), "the refused export writes no folder");
}
/// A confined caller's native outputs (a native file or template, an EPS or `.ai` file, a PDF with
/// Preserve Editing, a package's document) carry the document without the Export for Screens
/// folder when it is outside the read roots, with the other export settings and the art; the open
+127
View File
@@ -0,0 +1,127 @@
//! Gradient mesh points picked with one of the tools that pick them (the Mesh tool, Direct
//! Selection, the Lasso, the Polygonal Lasso) stay picked when another of them is chosen, or lent
//! for a Cmd-click, so a fill color then recolors just them.
use serde_json::json;
use vectorcraft_color::Color;
use vectorcraft_doc::NodeKind;
use vectorcraft_tools::{Mods, PointerEvent, PointerKind};
use crate::*;
/// A session with a selected 1 x 1 gradient mesh (four white points) at (10, 10), 50 pt square.
fn mesh_session() -> (Session, NodeId) {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
let m = NodeId(s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap());
s.execute("object.mesh.create", &json!({"ids": [m.0], "rows": 1, "cols": 1})).unwrap();
s.execute("select.set", &json!({"ids": [m.0]})).unwrap();
(s, m)
}
fn colors(s: &Session, m: NodeId) -> Vec<Color> {
match &s.doc().unwrap().doc.node(m).unwrap().kind {
NodeKind::Mesh(g) => g.points.iter().map(|p| p.color).collect(),
k => panic!("not a mesh: {k:?}"),
}
}
/// Click mesh point `i` of `m` with the active tool.
fn press(s: &mut Session, m: NodeId, i: usize, mods: Mods) {
let q = match &s.doc().unwrap().doc.node(m).unwrap().kind {
NodeKind::Mesh(g) => g.points[i].p,
k => panic!("not a mesh: {k:?}"),
};
for kind in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(kind, q.x, q.y).with_mods(mods), ViewInfo::default()).unwrap();
}
}
/// A point picked with the Mesh tool stays picked through Direct Selection, the Lasso and the
/// Polygonal Lasso and back to the Mesh tool: each fill color recolors just that point.
#[test]
fn mesh_point_picks_carry_between_the_mesh_point_tools() {
let (mut s, m) = mesh_session();
let v = ViewInfo::default();
let white = colors(&s, m)[0];
s.select_tool("mesh", v).unwrap();
press(&mut s, m, 0, Mods::default());
for (tool, hex, c) in [
("directSelection", "#0000ff", Color::rgb8(0, 0, 255)),
("lasso", "#00ff00", Color::rgb8(0, 255, 0)),
("polygonalLasso", "#ff0000", Color::rgb8(255, 0, 0)),
("directSelection", "#ffff00", Color::rgb8(255, 255, 0)),
("mesh", "#00ffff", Color::rgb8(0, 255, 255)),
] {
s.select_tool(tool, v).unwrap();
s.execute("paint.setFill", &json!({"color": hex})).unwrap();
assert_eq!(colors(&s, m), [c, white, white, white], "{tool} recolors only the picked point");
}
}
/// A point picked with Direct Selection stays picked for the Mesh tool.
#[test]
fn direct_selection_picks_carry_to_the_mesh_tool() {
let (mut s, m) = mesh_session();
let v = ViewInfo::default();
let white = colors(&s, m)[0];
s.select_tool("directSelection", v).unwrap();
press(&mut s, m, 2, Mods::default());
s.select_tool("mesh", v).unwrap();
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
assert_eq!(colors(&s, m), [white, white, Color::rgb8(0, 0, 255), white]);
}
/// The Selection tool picks no mesh points: after it, the Mesh tool starts with none picked, and a
/// fill color leaves every point as it was.
#[test]
fn a_tool_that_picks_no_mesh_points_drops_the_picks() {
let (mut s, m) = mesh_session();
let v = ViewInfo::default();
let before = colors(&s, m);
s.select_tool("mesh", v).unwrap();
press(&mut s, m, 0, Mods::default());
s.select_tool("selection", v).unwrap();
s.execute("select.set", &json!({"ids": [m.0]})).unwrap();
s.select_tool("mesh", v).unwrap();
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
assert_eq!(colors(&s, m), before, "no point is picked");
}
/// A plain Lasso click away from the art deselects it and unpicks the points the Mesh tool picked,
/// so the Mesh tool chosen next has none picked.
#[test]
fn a_lasso_click_that_deselects_unpicks_the_mesh_points() {
let (mut s, m) = mesh_session();
let v = ViewInfo::default();
let before = colors(&s, m);
s.select_tool("mesh", v).unwrap();
press(&mut s, m, 0, Mods::default());
s.select_tool("lasso", v).unwrap();
for kind in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(kind, 500.0, 500.0), v).unwrap();
}
assert!(s.doc().unwrap().selection.objects.is_empty(), "the click deselects the mesh");
s.execute("select.set", &json!({"ids": [m.0]})).unwrap();
s.select_tool("mesh", v).unwrap();
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
assert_eq!(colors(&s, m), before, "no point is picked");
}
/// Direct Selection lent to the Mesh tool for a Cmd-click starts from the Mesh tool's picks, so a
/// Shift-click adds to them, and gives back what it left picked.
#[test]
fn the_lent_direct_selection_carries_the_mesh_tools_picks() {
let (mut s, m) = mesh_session();
let v = ViewInfo::default();
let white = colors(&s, m)[0];
// Cmd lends the selection tool chosen last.
s.select_tool("directSelection", v).unwrap();
s.select_tool("mesh", v).unwrap();
press(&mut s, m, 0, Mods::default());
press(&mut s, m, 3, Mods { cmd: true, shift: true, ..Default::default() });
assert_eq!(s.tool_id(), "mesh");
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
let b = Color::rgb8(0, 0, 255);
assert_eq!(colors(&s, m), [b, white, white, b], "both points stay picked");
}
+42
View File
@@ -514,3 +514,45 @@ fn another_documents_symbol_is_added_and_placed_in_one_step() {
let e = s.execute("symbol.placeFromDocument", &json!({"sourceDocument": source, "name": "Star"})).unwrap_err();
assert!(e.to_string().contains("no longer open"), "{e}");
}
/// A symbol dragged onto the canvas, from another document's Symbols panel or from a symbol
/// library, is stacked as Place Symbol Instance stacks it: in Draw Behind directly below the
/// selected object, or at the bottom of the current layer with nothing selected, in one undo step
/// with the symbol it adds. A locked layer refuses it with no edit.
#[test]
fn dropped_symbols_go_below_the_selection_in_draw_behind() {
let mut s = kit();
let source = s.doc().unwrap().uid;
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
let rect =
|s: &mut Session, x: f64| NodeId(run(s, "shape.rectangle", json!({"x": x, "y": 0, "width": 10, "height": 10}))["id"].as_u64().unwrap());
let (a, b) = (rect(&mut s, 0.0), rect(&mut s, 20.0));
let layer = doc(&s).layers[0].id;
let kids = |s: &Session| doc(s).node(layer).unwrap().children().unwrap().iter().map(|c| c.id).collect::<Vec<_>>();
run(&mut s, "view.drawMode", json!({"mode": "behind"}));
let drops = [
("symbol.placeFromDocument", json!({"sourceDocument": source, "name": "Badge", "x": 30, "y": 40}), "id"),
("symbol.addFromLibrary", json!({"library": "basic shapes", "name": "Square", "place": true, "x": 30, "y": 40}), "placed"),
];
for (cmd, p, key) in &drops {
for (picked, at) in [(vec![b], 1), (vec![], 0)] {
run(&mut s, "select.set", json!({"ids": picked.iter().map(|i| i.0).collect::<Vec<_>>()}));
let before = undo_len(&s);
let placed = NodeId(run(&mut s, cmd, p.clone())[*key].as_u64().unwrap());
let mut want = vec![a, b];
want.insert(at, placed);
assert_eq!(kids(&s), want, "{cmd} {picked:?}");
assert_eq!(undo_len(&s), before + 1, "{cmd}");
assert_eq!(s.doc().unwrap().selection.objects, [placed]);
run(&mut s, "edit.undo", json!({}));
assert!(symbols(&s).is_empty(), "{cmd}: the undo takes the added symbol too");
}
}
// A locked layer takes nothing.
run(&mut s, "layer.setProps", json!({"id": layer.0, "locked": true}));
let before = (undo_len(&s), doc(&s).clone());
for (cmd, p, _) in &drops {
assert!(s.execute(cmd, p).is_err(), "{cmd}");
assert_eq!((undo_len(&s), doc(&s)), (before.0, &before.1), "{cmd}");
}
}
+24 -12
View File
@@ -186,12 +186,13 @@ impl Session {
let text_selection = ((id == "eyedropper" && is_type(self.tool.id())) || (self.tool.id() == "eyedropper" && is_type(id)))
.then(|| self.tool.options())
.filter(|o| o.get("editing").is_some_and(|v| !v.is_null()) && o.get("start") != o.get("end"));
// The gradient mesh points the Mesh tool, Direct Selection or the Lasso picked stay picked
// for the Eyedropper, which samples into them (#8090), and for the tool after it.
let mesh_points = (id == "eyedropper" || self.tool.id() == "eyedropper")
// The gradient mesh points the Mesh tool, Direct Selection, the Lasso or the Polygonal Lasso
// picked stay picked when another of these tools or the Eyedropper, which samples into
// them (#8090), is chosen: a fill color then recolors just them. None stay picked when
// none were.
let mesh_points = (Self::picks_mesh_points(id) && Self::picks_mesh_points(self.tool.id()))
.then(|| self.tool.options().get("meshPoints").cloned())
.flatten()
.filter(|v| v.as_array().is_some_and(|a| !a.is_empty()));
.flatten();
self.deactivate_tool(view)?;
self.keep_tool_settings();
self.tool = self.make_tool(id);
@@ -208,6 +209,13 @@ impl Session {
Ok(())
}
/// Does tool `id` pick gradient mesh points (its `meshPoints` option): the Mesh tool, Direct
/// Selection, the Lasso, the Polygonal Lasso and the Eyedropper? Group Selection, which
/// selects whole objects, does not.
fn picks_mesh_points(id: &str) -> bool {
matches!(id, "mesh" | "directSelection" | "lasso" | "polygonalLasso" | "eyedropper")
}
/// 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.
@@ -292,9 +300,9 @@ impl Session {
// double-click or triple-click compares.
self.tool.press_elsewhere();
let mut lent = self.make_tool(id);
// The gradient mesh points the Eyedropper holds are the lent tool's picks, which a Shift
// click adds to (#8090).
if self.tool.id() == "eyedropper" {
// The gradient mesh points the lending tool picked (the Mesh tool's, the Lasso's, the
// Eyedropper's) are the lent tool's picks, which a Shift click adds to (#8090).
if Self::picks_mesh_points(self.tool.id()) && Self::picks_mesh_points(id) {
let points = self.tool.options().get("meshPoints").cloned().unwrap_or_else(|| Value::Array(vec![]));
lent.set_option("meshPoints", &points);
}
@@ -312,10 +320,14 @@ impl Session {
/// Cmd+click that takes the type being edited out of the selection ends its edit (#3779).
pub(crate) fn give_back_tool(&mut self, view: ViewInfo) -> Result<()> {
let Some(lender) = self.lender.take() else { return Ok(()) };
// The points the lent tool left picked go back to the Eyedropper, none when it unpicked
// 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();
// The points the lent tool left picked go back to the tool it was lent to when that tool
// picks mesh points, none when it unpicked them all (#8090). Group Selection and the
// Selection tool pick no mesh points, so the tool keeps its own. Unchanged picks are not
// set again, so the Mesh tool keeps the point whose handles it shows.
let mesh_points = (Self::picks_mesh_points(lender.id()) && Self::picks_mesh_points(self.tool.id()))
.then(|| self.tool.options().get("meshPoints").cloned())
.flatten()
.filter(|p| lender.options().get("meshPoints") != Some(p));
let r = self.deactivate_tool(view);
self.keep_tool_settings();
self.tool = lender;
+1
View File
@@ -32,6 +32,7 @@ mod pen_rubber_band;
mod ruler_guide_nodes;
mod ruler_guide_perf;
mod ruler_origin;
mod script_host_vs_scriptcheck;
mod selection_commands;
mod stroke_visibility;
mod text_stroke_scale;
@@ -0,0 +1,166 @@
//! Every global and member the script host (`script.run`) adds to the JavaScript engine is in one of
//! the tables below, and each name that reaches outside the document has the `outside` id
//! `script.check` (`vectorcraft-scriptcheck`) gives it. The names are read from a run: the own
//! properties of the global object, of each object or function it holds and of each function's
//! `prototype`, with a setter listed again as `name=`. The names a plain `vectorcraft_js::Realm` also
//! has are the language's, which reach files and other apps only through the host; `eval` and
//! `Function` still have rows, since they run code the checker can't read. A name the host adds
//! without a row fails the test.
use std::collections::BTreeSet;
use serde_json::json;
use vectorcraft_engine::Session;
use vectorcraft_js::{DirectiveName, JsValue, Realm};
use vectorcraft_scriptcheck::{Limits, check};
/// The names that reach outside the document: each with a script that uses it and the `outside` id
/// the checker gives that script.
const OUTSIDE: &[(&str, &str, &str)] = &[
("eval", "eval(s);", "unseenCode"),
("Function", "var g = new Function(s);", "unseenCode"),
("$.evalFile", "$.evalFile(p);", "unseenCode"),
("$.getenv", "var h = $.getenv(n);", "environment"),
("$.setenv", "$.setenv(n, v);", "environment"),
("File.prototype.open", "var f = new File(p); f.open('w');", "filesWritten"),
("File.prototype.write", "var f = new File(p); f.write(s);", "filesWritten"),
("File.prototype.writeln", "var f = new File(p); f.writeln(s);", "filesWritten"),
("File.prototype.copy", "var f = new File(p); f.copy(q);", "filesWritten"),
("File.prototype.createAlias", "var f = new File(p); f.createAlias(q);", "filesWritten"),
("File.prototype.remove", "var f = new File(p); f.remove();", "filesWritten"),
("File.prototype.rename", "var f = new File(p); f.rename(q);", "filesWritten"),
("File.prototype.length=", "var f = new File(p); f.length = 0;", "filesWritten"),
("File.prototype.hidden=", "var f = new File(p); f.hidden = true;", "filesWritten"),
("File.prototype.readonly=", "var f = new File(p); f.readonly = true;", "filesWritten"),
("File.prototype.execute", "var f = new File(p); f.execute();", "filesOpened"),
("Folder.prototype.create", "var d = new Folder(p); d.create();", "filesWritten"),
("Folder.prototype.remove", "var d = new Folder(p); d.remove();", "filesWritten"),
("Folder.prototype.rename", "var d = new Folder(p); d.rename(q);", "filesWritten"),
("Folder.prototype.execute", "var d = new Folder(p); d.execute();", "filesOpened"),
];
/// The names the host adds that stay inside the document and the run, by the object that has them.
/// Reading a file or a folder, a file dialog and a message to the person do not change anything
/// outside it.
const INSIDE: &[(&str, &str)] = &[
("", "$ File Folder alert confirm localize prompt toSource"),
("Object.prototype.", "toSource"),
("localize.", "length"),
("toSource.", "length"),
(
"$.",
"about appEncoding appEncoding= bp build buildDate colorPicker decimalPoint engineName error fileName flags \
flags= gc global hiresTimer includePath level line locale locale= localize localize= memCache memCache= os screens \
sleep stack strict version write writeln",
),
("File.", "decode encode fs isEncodingAvailable openDialog saveDialog length prototype"),
(
"File.prototype.",
"absoluteURI alias changePath close constructor created creator displayName encoding encoding= eof error error= \
exists fsName fullName getRelativeURI hidden length lineFeed lineFeed= modified name openDlg parent path read \
readch readln readonly relativeURI resolve saveDlg seek tell toString type",
),
(
"Folder.",
"appData appPackage commonFiles current current= decode desktop encode fs isEncodingAvailable length myDocuments \
prototype selectDialog startup system temp trash userData",
),
(
"Folder.prototype.",
"absoluteURI alias changePath constructor created displayName error error= exists fsName fullName getFiles \
getRelativeURI modified name parent path relativeURI resolve selectDlg toString",
),
];
/// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's
/// own API, and what `vc.run` does depends on the command it runs.
const NOT_CHECKED: &str = "vc";
/// An expression whose value is the list of names, one to a line.
const LIST: &str = r#"(function () {
var out = [];
function add(o, prefix) {
var own = Object.getOwnPropertyNames(o);
for (var i = 0; i < own.length; i++) {
out.push(prefix + own[i]);
var d = Object.getOwnPropertyDescriptor(o, own[i]);
if (d && d.set) out.push(prefix + own[i] + "=");
}
}
var g = (function () { return this; })();
var globals = Object.getOwnPropertyNames(g);
add(g, "");
for (var i = 0; i < globals.length; i++) {
var v = g[globals[i]];
if (v !== null && (typeof v == "object" || typeof v == "function")) {
add(v, globals[i] + ".");
if (typeof v == "function" && v.prototype !== null && typeof v.prototype == "object") add(v.prototype, globals[i] + ".prototype.");
}
}
return out.join("\n");
})()"#;
/// The names a script run by the host has.
fn host_names() -> BTreeSet<String> {
let mut s = Session::new();
let r = s.execute("script.run", &json!({"source": format!("vc.log({LIST});"), "name": "list.js"})).unwrap();
let text = r["log"][0].as_str().unwrap_or_else(|| panic!("no list in {r}"));
text.lines().map(str::to_string).collect()
}
/// The names a plain JavaScript engine has.
fn language_names() -> BTreeSet<String> {
match Realm::new().run(LIST) {
Ok(JsValue::String(text)) => text.lines().map(str::to_string).collect(),
other => panic!("no list: {other:?}"),
}
}
fn table_names() -> BTreeSet<String> {
let inside = INSIDE.iter().flat_map(|(prefix, names)| names.split_whitespace().map(move |n| format!("{prefix}{n}")));
OUTSIDE.iter().map(|(n, ..)| n.to_string()).chain(inside).chain([NOT_CHECKED.to_string()]).collect()
}
#[test]
fn every_name_the_host_adds_has_a_row() {
let host = host_names();
let language = language_names();
let table = table_names();
let not_checked = |n: &&String| n.starts_with(&format!("{NOT_CHECKED}."));
let missing: Vec<_> = host.difference(&language).filter(|n| !table.contains(*n) && !not_checked(n)).collect();
assert!(missing.is_empty(), "the host adds these names, which no table here lists: {missing:?}");
let gone: Vec<_> = table.difference(&host).collect();
assert!(gone.is_empty(), "the tables list these names, which a script run by the host does not have: {gone:?}");
}
#[test]
fn every_name_that_reaches_outside_has_its_checker_id() {
for (name, script, id) in OUTSIDE {
let r = check("probe.jsx", script.as_bytes(), None, &Limits::default());
let ids: Vec<_> = r.outside.iter().map(|o| o.id).collect();
assert!(ids.contains(id), "{name}: the checker gives {ids:?} for {script:?}, not {id}");
}
}
/// A line with the directive `d`. The match has no catch-all, so a new directive needs a row, and
/// [`DirectiveName::from_name`] reads only the directives in [`DirectiveName::ALL`].
fn directive_line(d: DirectiveName) -> &'static str {
match d {
DirectiveName::Include => "#include \"lib.jsxinc\"",
DirectiveName::IncludePath => "#includepath \"lib\"",
DirectiveName::Script => "#script Tidy",
DirectiveName::Strict => "#strict on",
DirectiveName::Target => "#target vectorcraft",
DirectiveName::TargetEngine => "#targetengine session",
}
}
#[test]
fn the_checker_lists_every_directive_the_host_reads() {
for d in DirectiveName::ALL {
let line = directive_line(d);
let r = check("probe.jsx", format!("{line}\nvar a = 1;\n").as_bytes(), None, &Limits::default());
let listed: Vec<_> = r.directives.iter().map(|d| d.name.to_string()).collect();
assert_eq!(listed, [d.as_str()], "{line}");
}
}
+43
View File
@@ -463,6 +463,49 @@ fn expand_appearance_keeps_a_plug_in_effect_safe_mode_skips() {
s.execute("effect.expandAppearance", &json!({})).unwrap();
}
/// In Safe Mode, Expand Appearance refuses a group whose raster effect makes an image of a plain
/// instance in it when the instance's symbol art holds a plug-in effect.
#[test]
fn expand_appearance_in_safe_mode_checks_symbol_art_a_group_image_draws() {
let _f = fresh();
let mut s = Session::new();
let fx = wat::parse_str(tpl::returning(&tpl::manifest("test.sm.sym", "effect", "{}"), r#"{"objects":[]}"#)).unwrap();
s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&fx)})).unwrap();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
s.execute("effect.apply", &json!({"effect": "plugin.test.sm.sym"})).unwrap();
s.execute("symbol.new", &json!({"name": "fx"})).unwrap();
let plain = s.execute("symbol.place", &json!({"name": "fx", "x": 100, "y": 100})).unwrap()["id"].clone();
let refused = |s: &mut Session, group: &Value| {
let before = s.execute("document.inspect", &json!({})).unwrap();
safe_mode::set_active(Some(safe_mode::Source::Flag));
let err = s.execute("effect.expandAppearance", &json!({"ids": [group]})).unwrap_err().to_string();
safe_mode::set_active(None);
assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{err}");
assert_eq!(s.execute("document.inspect", &json!({})).unwrap(), before, "nothing changes");
};
// A Gaussian Blur of the group's own.
let group = s.execute("object.group", &json!({"ids": [plain]})).unwrap()["id"].clone();
s.execute("effect.apply", &json!({"effect": "blur.gaussian", "ids": [group], "params": {"radius": 2}})).unwrap();
refused(&mut s, &group);
// A Gaussian Blur on a fill of a group around a group that holds another plain instance.
let blurred_fill = {
let t = s.execute("shape.rectangle", &json!({"x": 150, "y": 10, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("effect.apply", &json!({"effect": "blur.gaussian", "ids": [t], "item": 0, "params": {"radius": 2}})).unwrap();
s.doc().unwrap().doc.node(vectorcraft_engine::doc::NodeId(t)).unwrap().appearance.items[0].clone()
};
let plain = s.execute("symbol.place", &json!({"name": "fx", "x": 100, "y": 20})).unwrap()["id"].clone();
let inner = s.execute("object.group", &json!({"ids": [plain]})).unwrap()["id"].clone();
let outer = s.execute("object.group", &json!({"ids": [inner]})).unwrap()["id"].as_u64().unwrap();
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc)
.node_mut(vectorcraft_engine::doc::NodeId(outer))
.unwrap()
.appearance
.items
.push(blurred_fill);
refused(&mut s, &json!(outer));
}
/// In Safe Mode, a plug-in effect in the art of a graph design in a series stops Expand Appearance of the graph only
/// when an effect of the series group draws that art with the group.
#[test]
+1 -22
View File
@@ -3,7 +3,6 @@
use std::collections::HashMap;
use std::fmt::Write;
use std::hash::{Hash, Hasher};
use vectorcraft_color::gradient::GradientGeom;
use vectorcraft_color::swatch::REGISTRATION;
@@ -14,6 +13,7 @@ use vectorcraft_geom::{Affine, BezPath, Rect, Shape, Vec2};
use super::{MAX_NEST, Writer, Xy};
use crate::ai_ops::{self, average, unit};
use crate::gradient_key::gradient_key;
use crate::ps;
pub(in crate::ai_editing) const GRADIENTS: &str =
@@ -64,27 +64,6 @@ fn same_gradient(a: &Gradient, b: &Gradient) -> bool {
a == b
}
/// A key of `g` for [`GradientDefs`]: the same gradients have the same key (each number by its
/// bits, with -0 as 0); different gradients may share one.
fn gradient_key(g: &Gradient) -> u64 {
let bits = |x: f32| if x == 0.0 { 0 } else { x.to_bits() };
let mut h = std::hash::DefaultHasher::new();
std::mem::discriminant(&g.kind).hash(&mut h);
std::mem::discriminant(&g.method).hash(&mut h);
(g.dither, g.spread, g.repeats, g.stops.len()).hash(&mut h);
for s in &g.stops {
let (model, c) = match s.color {
Color::Rgb { r, g, b } => (0u8, [r, g, b, 0.0]),
Color::Cmyk { c, m, y, k } => (1, [c, m, y, k]),
Color::Gray { k } => (2, [k, 0.0, 0.0, 0.0]),
Color::Lab { l, a, b } => (3, [l, a, b, 0.0]),
};
(model, c.map(bits), [s.offset, s.opacity, s.midpoint, s.tint].map(bits)).hash(&mut h);
(&s.swatch, s.plates.map(|p| p.map(bits))).hash(&mut h);
}
h.finish()
}
/// The gradient definitions, in the order they are first used, found by name and by gradient
/// without comparing each one.
#[derive(Default)]
+29
View File
@@ -0,0 +1,29 @@
//! A key of a gradient for the gradient definitions the legacy `.ai` writer
//! ([`crate::legacy_ai`]) and the editing data writer ([`crate::ai_editing`]) look up: the writers
//! keep each definition's place under its gradient's key and compare only the gradients that
//! share it.
use std::hash::{Hash, Hasher};
use vectorcraft_color::{Color, Gradient};
/// A key of `g`: the same gradients have the same key (each number by its bits, with -0 as 0);
/// different gradients may share one.
pub(crate) fn gradient_key(g: &Gradient) -> u64 {
let bits = |x: f32| if x == 0.0 { 0 } else { x.to_bits() };
let mut h = std::hash::DefaultHasher::new();
std::mem::discriminant(&g.kind).hash(&mut h);
std::mem::discriminant(&g.method).hash(&mut h);
(g.dither, g.spread, g.repeats, g.stops.len()).hash(&mut h);
for s in &g.stops {
let (model, c) = match s.color {
Color::Rgb { r, g, b } => (0u8, [r, g, b, 0.0]),
Color::Cmyk { c, m, y, k } => (1, [c, m, y, k]),
Color::Gray { k } => (2, [k, 0.0, 0.0, 0.0]),
Color::Lab { l, a, b } => (3, [l, a, b, 0.0]),
};
(model, c.map(bits), [s.offset, s.opacity, s.midpoint, s.tint].map(bits)).hash(&mut h);
(&s.swatch, s.plates.map(|p| p.map(bits))).hash(&mut h);
}
h.finish()
}
+113
View File
@@ -1696,6 +1696,119 @@ fn colliding_gradient_and_spot_names_are_numbered_as_before() {
assert!(text.contains("%%DocumentCustomColors: (?)\n%%+ (? 2)\n%%+ (? 3)\n%%+ (? 2 2)\n"), "{text}");
}
/// `doc` written with its gradient definitions found by comparing each in turn (`scanned`) or
/// through their index.
fn export_scanned(doc: &Document, scanned: bool) -> LegacyAiOutput {
let o = LegacyAiOptions { created: Some(0), ..LegacyAiOptions::default() };
super::writer::SCANNED_DEFINITIONS.with(|s| s.set(scanned));
let out = export_legacy_ai(doc, &o);
super::writer::SCANNED_DEFINITIONS.with(|s| s.set(false));
out.unwrap()
}
/// A document of rectangles filled with gradients: one with a gradient swatch `Sky` of its own;
/// `distinct` with gradients of their own; `reused` with one of `ramps` others in turn; one with a
/// gradient swatch `Dawn` whose gradient is the first of those `ramps`; two whose gradients differ
/// only in the sign of a zero offset; and two with the same gradient, whose midpoint is not a
/// number.
fn many_gradients(distinct: u16, reused: u16, ramps: u16) -> Document {
let mut doc = Document::new(1000.0, 1000.0);
let layer = doc.layers[0].id;
let shade = |i: u16, n: u16| f32::from(i) / f32::from(n.max(1));
let mut paints = vec![gradient_from(Color::rgb(0.1, 0.2, 0.3), Some("Sky"))];
for i in 0..distinct {
paints.push(gradient_from(Color::rgb(shade(i, distinct), 0.5, 0.0), None));
}
for i in 0..reused {
paints.push(gradient_from(Color::cmyk(0.0, shade(i % ramps.max(1), ramps), 0.5, 0.0), None));
}
paints.push(gradient_from(Color::cmyk(0.0, 0.0, 0.5, 0.0), Some("Dawn")));
let stops = |offset: f32, midpoint: f32| {
let mut first = GradientStop::new(offset, Color::rgb(0.2, 0.3, 0.4));
first.midpoint = midpoint;
let g = Gradient::new(GradientKind::Linear, vec![first, GradientStop::new(1.0, Color::BLACK)]);
Paint::Gradient(Box::new(GradientPaint::new(g)))
};
paints.extend([stops(0.0, 0.5), stops(-0.0, 0.5), stops(0.0, f32::NAN), stops(0.0, f32::NAN)]);
for (i, paint) in (0u16..).zip(paints) {
let (x, y) = (f64::from(i % 40) * 25.0, f64::from(i / 40 % 40) * 25.0);
let n = shape(&mut doc, shapes::rectangle(Rect::new(x, y, x + 20.0, y + 20.0)), paint, Paint::None);
doc.insert(Some(layer), usize::MAX, n).unwrap();
}
doc
}
/// Gradient definitions found through their index are those found by comparing each in turn: the
/// file is the same, byte for byte, with the same warnings. An earlier definition of the same
/// gradient serves a gradient swatch of another name; gradients that differ only in the sign of a
/// zero share a definition; a gradient that is not equal to itself is defined each time.
#[test]
fn indexed_gradient_definitions_write_the_same_file() {
let doc = many_gradients(300, 300, 7);
let (indexed, scanned) = (export_scanned(&doc, false), export_scanned(&doc, true));
let differ = indexed.bytes.iter().zip(&scanned.bytes).position(|(a, b)| a != b);
assert!(indexed.bytes == scanned.bytes, "the files differ from byte {differ:?} ({} and {} bytes)", indexed.bytes.len(), scanned.bytes.len());
assert_eq!(indexed.warnings, scanned.warnings);
assert_eq!(indexed.setting_notes, scanned.setting_notes);
let text = String::from_utf8(indexed.bytes).unwrap();
let defined: Vec<&str> = text.lines().filter_map(|l| l.strip_suffix(" 0 2 Bd")).collect();
// `Sky`, 300 of their own, 7 reused, 1 for both signs of zero and 2 for the gradient that
// is not a number.
assert_eq!(defined.len(), 1 + 300 + 7 + 1 + 2, "{defined:?}");
assert_eq!(defined.first(), Some(&"(Sky)"));
assert!(!defined.contains(&"(Dawn)"), "{defined:?}");
}
/// A gradient is matched with the definitions of the same gradient, not with each definition:
/// 1,000 gradients of their own and 1,000 of 10 others take a comparison or so each, where
/// comparing each definition in turn takes hundreds of thousands.
#[test]
fn legacy_gradient_definitions_are_found_without_comparing_each() {
let doc = many_gradients(1000, 1000, 10);
let comparisons = |scanned: bool| {
super::writer::GRADIENT_COMPARISONS.with(|c| c.set(0));
export_scanned(&doc, scanned);
super::writer::GRADIENT_COMPARISONS.with(std::cell::Cell::get)
};
let (indexed, scanned) = (comparisons(false), comparisons(true));
assert!(indexed <= 2 * 2006, "{indexed} comparisons through the index");
assert!(scanned > 100 * indexed, "{scanned} comparisons scanning, {indexed} through the index");
}
/// The time to write 5,000 rectangles with gradients of their own and 5,000 with 50 others, with
/// the definitions found by comparing each in turn and through their index: the median of 7 runs
/// of each, alternating, with the files compared. Run with
/// `cargo test --release -p vectorcraft-eps --lib -- --ignored --nocapture legacy_gradient_definitions_timing`.
#[test]
#[ignore = "timing"]
fn legacy_gradient_definitions_timing() {
let doc = many_gradients(5000, 5000, 50);
let mut times = [vec![], vec![]];
let mut files: [Option<Vec<u8>>; 2] = [None, None];
let mut how = "";
for _ in 0..7 {
for (k, scanned) in [true, false].into_iter().enumerate() {
let (start, h) = thread_time();
let out = export_scanned(&doc, scanned);
times[k].push(thread_time().0.saturating_sub(start));
how = h;
files[k].get_or_insert(out.bytes);
}
}
assert_eq!(files[0], files[1]);
for t in &mut times {
t.sort();
}
let ms = |d: std::time::Duration| d.as_secs_f64() * 1000.0;
println!("10,006 gradient fills, median of 7 runs ({how}):");
println!("| definitions found | median (ms) | runs (ms) |");
println!("|---|---:|---|");
for (k, label) in ["comparing each in turn", "through the index"].into_iter().enumerate() {
let runs: Vec<String> = times[k].iter().map(|d| format!("{:.1}", ms(*d))).collect();
println!("| {label} | {:.1} | {} |", ms(times[k][3]), runs.join(", "));
}
}
/// The time this thread has run, and how it was measured.
fn thread_time() -> (std::time::Duration, &'static str) {
if let Some(ns) = std::fs::read_to_string("/proc/thread-self/schedstat").ok().and_then(|s| s.split_whitespace().next()?.parse::<u64>().ok()) {
+45 -9
View File
@@ -10,6 +10,7 @@ use super::{
TextObject, UNDECODED, Vec2, Write, ai_ops, latin, ps, stroke,
};
use super::{CONIC, CONIC_WEDGES, DEEP_DISTORTED, DIAMOND, GRAPHS, HUE_STOPS, PERCEPTUAL_STOPS, SPREAD, SPREAD_CAPPED};
use crate::gradient_key::gradient_key;
#[cfg(test)]
thread_local! {
@@ -18,6 +19,18 @@ thread_local! {
/// Whether [`Numbered::take`] numbers names on this thread by searching the names given so
/// far, one number at a time, for each number it tries.
pub(super) static SCANNED_NAMES: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
/// Whether [`Writer::defined`] finds a gradient's definition on this thread by comparing the
/// gradient with each definition in turn.
pub(super) static SCANNED_DEFINITIONS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
/// How many times [`Writer::defined`] has compared two gradients on this thread.
pub(super) static GRADIENT_COMPARISONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Are gradients `a` and `b` the same?
fn same_gradient(a: &Gradient, b: &Gradient) -> bool {
#[cfg(test)]
GRADIENT_COMPARISONS.with(|c| c.set(c.get() + 1));
a == b
}
/// An image's coverage ([`ImageBlob::coverage`]): its width, its height and one byte a pixel.
@@ -34,7 +47,7 @@ pub(super) struct Writer<'a> {
/// Spot colors used: the name written and full CMYK equivalent.
pub(super) spots: Vec<(String, [f32; 4])>,
/// The name each spot color (by its swatch's name) is written with ([`Self::spot`]).
spot_names: Vec<(String, String)>,
spot_names: std::collections::HashMap<String, String>,
pub(super) warnings: Vec<String>,
/// Notes on what the options asked for ([`crate::LegacyAiOutput::setting_notes`]).
pub(super) setting_notes: Vec<String>,
@@ -73,6 +86,13 @@ pub(super) struct Writer<'a> {
gradient_names: Numbered,
/// The names spot colors are written with ([`Self::spot`]).
spot_written: Numbered,
/// The names of [`Self::spots`].
spot_set: std::collections::HashSet<String>,
/// The PostScript names of [`Self::fonts`].
font_set: std::collections::HashSet<String>,
/// The places in [`Self::gradients`] of the definitions, in order, by their gradient's key
/// ([`gradient_key`]).
gradient_index: std::collections::HashMap<u64, Vec<usize>>,
}
impl<'a> Writer<'a> {
@@ -84,7 +104,7 @@ impl<'a> Writer<'a> {
body: String::new(),
gradients: vec![],
spots: vec![],
spot_names: vec![],
spot_names: std::collections::HashMap::new(),
warnings: vec![],
setting_notes: vec![],
locked: false,
@@ -103,6 +123,9 @@ impl<'a> Writer<'a> {
in_graph: false,
gradient_names: Numbered::default(),
spot_written: Numbered::default(),
spot_set: std::collections::HashSet::new(),
font_set: std::collections::HashSet::new(),
gradient_index: std::collections::HashMap::new(),
}
}
@@ -160,16 +183,17 @@ impl<'a> Writer<'a> {
/// Windows-1252 are written as `?` (with a warning), and it is numbered when another spot color
/// is already written with that name; the name is the same each time.
fn spot(&mut self, name: &str, cmyk: [f32; 4]) -> String {
let written = match self.spot_names.iter().find(|(n, _)| n == name) {
Some((_, w)) => w.clone(),
let written = match self.spot_names.get(name) {
Some(w) => w.clone(),
None => {
let base = self.latin_name(name, TITLE_AND_COLOR_NAMES);
let written = self.spot_written.take(base);
self.spot_names.push((name.to_string(), written.clone()));
self.spot_names.insert(name.to_string(), written.clone());
written
}
};
if !self.spots.iter().any(|(n, _)| *n == written) {
if !self.spot_set.contains(&written) {
self.spot_set.insert(written.clone());
self.spots.push((written.clone(), cmyk));
}
written
@@ -178,7 +202,7 @@ impl<'a> Writer<'a> {
/// The name spot color `name` (its swatch's name) is written with, once [`Self::spot`] has
/// noted it.
pub(super) fn spot_name<'n>(&'n self, name: &'n str) -> &'n str {
self.spot_names.iter().find(|(n, _)| n == name).map_or(name, |(_, w)| w.as_str())
self.spot_names.get(name).map_or(name, String::as_str)
}
/// A top-level layer. False when it isn't a layer.
@@ -831,15 +855,26 @@ impl<'a> Writer<'a> {
/// The name of the definition of `g` (its swatch's name when it has one, with each character
/// outside Windows-1252 written as `?` and a warning), defined the first time.
fn define(&mut self, g: &Gradient, swatch: Option<&str>) -> String {
if let Some((name, _)) = self.gradients.iter().find(|(_, d)| d == g) {
let key = gradient_key(g);
if let Some((name, _)) = self.defined(g, key).and_then(|i| self.gradients.get(i)) {
return name.clone();
}
let base = self.latin_name(swatch.filter(|s| !s.is_empty()).unwrap_or("Gradient"), TITLE_AND_COLOR_NAMES);
let name = self.gradient_names.take(base);
self.gradient_index.entry(key).or_default().push(self.gradients.len());
self.gradients.push((name.clone(), g.clone()));
name
}
/// The place in [`Self::gradients`] of the first definition of `g`, whose key is `key`.
fn defined(&self, g: &Gradient, key: u64) -> Option<usize> {
#[cfg(test)]
if SCANNED_DEFINITIONS.with(std::cell::Cell::get) {
return self.gradients.iter().position(|(_, d)| same_gradient(d, g));
}
self.gradient_index.get(&key)?.iter().copied().find(|i| self.gradients.get(*i).is_some_and(|(_, d)| same_gradient(d, g)))
}
// ---------- type ----------
/// Type: a text object when the format can hold it as text, else its outlines (type with
@@ -1016,7 +1051,8 @@ impl<'a> Writer<'a> {
self.line_style(&st.stroke_layer());
}
let (name, truetype, ascent, descent) = font_of(st);
if !self.fonts.iter().any(|(n, _)| *n == name) {
if !self.font_set.contains(&name) {
self.font_set.insert(name.clone());
self.fonts.push((name.clone(), truetype));
}
let size = finite(st.size, 12.0);
+2
View File
@@ -32,12 +32,14 @@
//! ([`export_ai_editing`], [`ai_private_data`]).
//! - `ai_ops`: the path and line style operators those two write.
//! - `ai_graph`: the records of a live graph those two write around its group.
//! - `gradient_key`: the key those two find gradient definitions by.
//! - [`dcs`]: DCS files, an EPS file with one program per printing plate, read for placing.
mod ai_editing;
mod ai_graph;
mod ai_ops;
pub mod dcs;
mod gradient_key;
mod import;
mod latin;
mod legacy_ai;
+11 -9
View File
@@ -288,17 +288,19 @@ pub enum DirectiveName {
}
impl DirectiveName {
/// Every directive a preprocessor line can name.
pub const ALL: [DirectiveName; 6] = [
DirectiveName::Include,
DirectiveName::IncludePath,
DirectiveName::Script,
DirectiveName::Strict,
DirectiveName::Target,
DirectiveName::TargetEngine,
];
/// The directive named `name`, compared without case.
pub fn from_name(name: &str) -> Option<DirectiveName> {
const NAMES: [(&str, DirectiveName); 6] = [
("include", DirectiveName::Include),
("includepath", DirectiveName::IncludePath),
("script", DirectiveName::Script),
("strict", DirectiveName::Strict),
("target", DirectiveName::Target),
("targetengine", DirectiveName::TargetEngine),
];
NAMES.iter().find(|(n, _)| n.eq_ignore_ascii_case(name)).map(|(_, d)| *d)
DirectiveName::ALL.into_iter().find(|d| d.as_str().eq_ignore_ascii_case(name))
}
pub fn as_str(self) -> &'static str {
+4
View File
@@ -239,6 +239,10 @@ enum Pending<'s> {
MenuString(Option<usize>, &'s str),
/// `.open(`: a string literal with the open mode may follow.
Open(Option<usize>),
/// A File object's `length`, `hidden` or `readonly` (`f.length`, `f['length']`): an assignment
/// or an update (`++`, `--`) that sets it may follow. With `true`, a prefix update came before
/// the receiver, and it sets the property unless a member or a call follows it.
Setter(Option<usize>, bool),
/// A platform name where a property key or a label may stand (first, or after `{`, `,`, `;` or
/// `}`): it is a key or a label when `:` follows.
Name(&'s str, Option<usize>),
+49 -6
View File
@@ -1,6 +1,6 @@
//! The platform features, menu commands and later syntax the analysis recognises.
use super::{Analyzer, FeatureId, NEWER, OutsideId, Pending, Sig, T, catalog, is, member_mark, newer_number, report, unquote, word};
use super::{Analyzer, COMPOUND, FeatureId, NEWER, OutsideId, Pending, Sig, T, catalog, is, member_mark, newer_number, report, unquote, word};
/// A global name of the platform the report looks for (`$`, `File`, `Socket`, `alert`, `eval`…).
pub(super) fn platform_name(n: &str) -> bool {
@@ -72,6 +72,17 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
self.open_mode(&unquote(t.text, 2), l);
}
}
Pending::Setter(l, prefix) => {
let sets = if prefix {
!t.is(".") && !t.is("[") && !t.is("(")
} else {
// An update operator after a line break belongs to the next line's operand.
t.kind == T::Punct && (t.text == "=" || COMPOUND.contains(&t.text) || (matches!(t.text, "++" | "--") && !t.nl))
};
if sets {
self.file_setter(l);
}
}
}
match t.kind {
T::Ident => self.name(t, line),
@@ -113,7 +124,29 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
match pending {
Pending::Window(l) | Pending::WindowType(l) => self.acc.feature(FeatureId::ScriptuiWindow, l),
Pending::Menu(l) | Pending::MenuString(l, _) => self.menu(None, l),
Pending::Open(_) | Pending::Name(..) | Pending::None => {}
Pending::Setter(l, true) => self.file_setter(l),
Pending::Open(_) | Pending::Setter(_, false) | Pending::Name(..) | Pending::None => {}
}
}
/// A File object's `length`, `hidden` or `readonly` set at `line`: the file changes.
fn file_setter(&mut self, line: Option<usize>) {
self.acc.feature(FeatureId::FileWrite, line);
self.acc.outside(OutsideId::FilesWritten, line, None);
}
/// `name`, a property of `receiver` read with `.` or as a string literal in brackets, `before`
/// coming before the receiver: when it is a File object's setter, the next token says whether it
/// is set ([`Pending::Setter`]). An update operator in `before` is a prefix (`++f.length`) when
/// the receiver is on its line, or when it starts a line or comes where an expression may start;
/// otherwise it ends the operand before it (`i++` and a line break, then `f.length`).
fn setter(&mut self, name: &str, receiver: Option<Sig<'s>>, before: Option<Sig<'s>>, line: Option<usize>) {
if catalog::FILE_SETTERS.contains(&name) && self.file_receiver(receiver, before) {
// Before a receiver that ends in `)` (`new File(i++).length`), the operator is inside the
// parentheses.
let update = before.filter(|b| (b.is("++") || b.is("--")) && receiver.is_some_and(|r| r.kind == T::Ident));
let prefix = update.is_some_and(|b| b.nl || b.expr || receiver.is_some_and(|r| !r.nl));
self.pending = Pending::Setter(line, prefix);
}
}
@@ -170,6 +203,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
if n == catalog::REFLECT {
self.acc.feature(FeatureId::Reflection, line);
}
self.setter(n, h1, h2, line);
return;
}
if member_mark(h0) {
@@ -231,6 +265,11 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
fn punct(&mut self, t: &Sig<'s>, line: Option<usize>) {
let [h0, h1, h2, h3] = self.h;
match t.text {
// `f['length']`: a File object's setter may follow.
"]" if is(h1, "[") && h0.is_some_and(|s| s.kind == T::Str) => {
let name = h0.map(|s| unquote(s.text, 16)).unwrap_or_default();
self.setter(&name, h2, h3, line);
}
"(" => self.call(line),
// `Name.prototype["+"] = …` defines an operator.
"=" => {
@@ -251,10 +290,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
let Some(callee) = h0.filter(|s| s.kind == T::Ident) else { return };
let n = callee.text;
if is(h1, ".") {
// The receiver is a variable holding a File or Folder object (not a property of the same
// name), or a File or Folder object made in place or held in grouping parentheses
// ([`Sig::file`]).
let file = h2.is_some_and(|r| r.file || (r.kind == T::Ident && !member_mark(h3) && self.files.contains(r.text)));
let file = self.file_receiver(h2, h3);
if n == catalog::MENU_COMMAND {
self.pending = Pending::Menu(line);
} else if n == catalog::OPEN && file {
@@ -288,6 +324,13 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
}
}
/// Whether `receiver`, which `before` comes before, is a variable holding a File or Folder object
/// (not a property of the same name), or a File or Folder object made in place or held in
/// grouping parentheses ([`Sig::file`]).
fn file_receiver(&self, receiver: Option<Sig<'s>>, before: Option<Sig<'s>>) -> bool {
receiver.is_some_and(|r| r.file || (r.kind == T::Ident && !member_mark(before) && self.files.contains(r.text)))
}
fn string(&mut self, t: &Sig<'s>, line: Option<usize>) {
let [h0, h1, h2, _] = self.h;
if t.text.contains(catalog::ACTION_TEXT) {
+3
View File
@@ -32,6 +32,9 @@ pub(crate) const FOLDER: &str = "Folder";
pub(crate) const FILE_READS: &[&str] = &["read", "readch", "readln"];
pub(crate) const FOLDER_READS: &[&str] = &["getFiles"];
pub(crate) const FILE_WRITES: &[&str] = &["write", "writeln", "remove", "rename", "copy", "createAlias", "create"];
/// The properties of a File object whose setting changes the file: its length, and its hidden and
/// read-only flags.
pub(crate) const FILE_SETTERS: &[&str] = &["length", "hidden", "readonly"];
pub(crate) const FILE_DIALOGS: &[&str] = &["openDialog", "saveDialog"];
pub(crate) const FOLDER_DIALOGS: &[&str] = &["selectDialog"];
pub(crate) const INSTANCE_DIALOGS: &[&str] = &["openDlg", "saveDlg", "selectDlg"];
+34
View File
@@ -530,6 +530,40 @@ fn the_scripts_own_platform_names_are_not_the_platforms() {
assert_eq!(r.outside.iter().map(|o| o.id).collect::<Vec<_>>(), ["filesWritten"]);
}
/// Setting a File object's length, hidden or read-only flag changes the file; reading them, comparing
/// them and setting them on another object does not.
#[test]
fn setting_a_files_length_or_flags_writes_it() {
let r = report(concat!(
"var f = new File(p);\n",
"f.length = 0;\n",
"f.readonly = true;\n",
"f.hidden |= 1;\n",
"f.length++;\n",
"new File(q).length = 4;\n",
"if (x) --f.length;\n",
"f['readonly'] = false;\n",
"++\n",
"f.length;\n",
"var k = ++\n",
"f['length'];\n",
"++f.length.x; var z = new File(i++).length;\n",
"var n = f.length;\n",
"if (f.readonly == true) {}\n",
"o.length = 0;\n",
"o.f.length = 0;\n",
"var s = [1]; s.length = 0;\n",
"var m = f['length'];\n",
"i++\n",
"f.length;\n",
"f.length\n",
"++i;\n",
));
let outside: Vec<(&str, &[usize])> = r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect();
assert_eq!(outside, [("filesWritten", &[2, 3, 4, 5, 6, 7, 8, 10, 12][..])]);
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[2, 3, 4, 5, 6, 7, 8, 10, 12][..]));
}
#[test]
fn a_function_after_a_line_that_ends_a_statement_is_a_declaration() {
let r = report("var n = 1\nfunction File() {}\nFile('x');\nvar m = 2 /* a\n */ function Socket() {}\nnew Socket();\n");
+52
View File
@@ -1312,6 +1312,58 @@ fn shaped_composition_searches_share_the_frame_budget() {
assert_eq!(three.steps_left.get(), breaking::MAX_TOTAL_STEPS, "the layout's own steps");
}
/// The every-line composer places a line where its first word fits, and measures that word by the
/// paragraph's custom Kinsoku set: with A in the set's Cannot End Line, the first word of `A BC`
/// runs past the space to the end, so the line `A` skips the frame's 20 pt top and takes the
/// 50 pt band below it. Without the set the word is `A` alone and the top holds it.
#[test]
fn shaped_first_word_uses_the_custom_kinsoku_set() {
use super::shaped::{Budget, Shaped};
use crate::composer::Measure;
use std::cell::Cell;
use std::rc::Rc;
let text = "A BC";
let glyphs = full_width(text);
let set = custom_set("", "A", "", &[]);
assert_eq!(breaking::word_width(&glyphs, 0, &[], breaking::KinsokuRules::Custom(&set), Burasagari::None), 40.0);
assert_eq!(breaking::word_width(&glyphs, 0, &[], Kinsoku::Hard, Burasagari::None), 10.0);
// 20 pt wide down to 40 pt, and 50 pt wide below.
let frame = BezPath::from_vec(vec![
PathEl::MoveTo((0.0, 0.0).into()),
PathEl::LineTo((20.0, 0.0).into()),
PathEl::LineTo((20.0, 40.0).into()),
PathEl::LineTo((50.0, 40.0).into()),
PathEl::LineTo((50.0, 120.0).into()),
PathEl::LineTo((0.0, 120.0).into()),
PathEl::ClosePath,
]);
let regions = region::Region::cells(&frame, &LayoutOptions::default(), &[]);
let pen = breaking::Pen {
regions: Some(&regions),
ri: 0,
prev: None,
pending: 0.0,
fb: FirstBaseline::Ascent,
fb_min: 0.0,
queued: vec![],
above: Default::default(),
model: LeadingModel::default(),
next_top: None,
no_room_for: f64::INFINITY,
steps_left: Rc::new(Cell::new(breaking::MAX_TOTAL_STEPS)),
search: Rc::new(Budget::default()),
};
let first_line = |para: &ParaStyle| {
let mut measure = Shaped::new(&glyphs, &[], para, &|_| 0.0, false, false, &pen);
let state = measure.first();
measure.line(&state, 0, 1).ok().flatten().map(|(width, _)| width)
};
let hard = ParaStyle { kinsoku: Kinsoku::Hard, ..ParaStyle::default() };
let custom = ParaStyle { kinsoku_set: Some(Arc::new(set)), ..hard.clone() };
assert_eq!(first_line(&hard), Some(20.0), "the frame's top holds the word A");
assert_eq!(first_line(&custom), Some(50.0), "the word A BC needs the band below");
}
/// The glyphs of `text`, each 10 pt wide, with Korean words kept whole unless `anywhere` (Korean
/// Line Break Anywhere on).
fn korean(text: &str, anywhere: bool) -> Vec<SGlyph> {
+1416 -44
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -167,7 +167,7 @@ impl Tool for PolygonalLassoTool {
self.mesh.options()
}
/// Pick the gradient mesh points the Eyedropper held (`meshPoints`).
/// Pick the gradient mesh points the tool chosen before held (`meshPoints`).
fn set_option(&mut self, key: &str, value: &serde_json::Value) {
if key == "meshPoints" {
self.mesh.set_options(value);
+11 -1
View File
@@ -512,7 +512,7 @@ mod tests {
assert_eq!(a, vec![Action::Preview("object.blend.setEasing".into(), json!({"id": id.0, "ramp": 0.0}))], "clamped at 0");
let a = t.pointer(&c, &ev(PointerKind::Drag, at + Vec2::new(500.0, 0.0)));
assert_eq!(a, vec![Action::Preview("object.blend.setEasing".into(), json!({"id": id.0, "ramp": 100.0}))], "clamped at 100");
assert_eq!(t.pointer(&c, &ev(PointerKind::Up, at)), vec![Action::Commit]);
assert_eq!(t.pointer(&c, &ev(PointerKind::Up, at + Vec2::new(500.0, 0.0))), vec![Action::Commit]);
// A click that doesn't move sends nothing.
assert!(t.pointer(&c, &ev(PointerKind::Down, at)).is_empty());
assert!(t.pointer(&c, &ev(PointerKind::Up, at)).is_empty());
@@ -546,6 +546,16 @@ mod tests {
assert_eq!(a[1], Action::Preview("object.blend.setEasing".into(), json!({"id": id.0, "ramp": 50.0})));
}
/// A drag with the Selection tool reads where it is released, and a tool switch cancels it.
#[test]
fn a_drag_reads_its_release() {
let (d, _, s) = blend_doc(&[(100.0, 200.0), (300.0, 200.0)], eased());
let p = paint();
let c = cx(&d, &s, &p);
let at = Point::new(200.0, 216.0);
check_widget_release_and_tool_switch(&c, at, at + Vec2::new(20.0, 0.0), at + Vec2::new(40.0, 0.0));
}
/// Switching away from the Selection or Blend tool during a drag cancels it, and after a press
/// that has not moved there is nothing to put back.
#[test]
+1
View File
@@ -451,6 +451,7 @@ impl ToolContext<'_> {
skip_guides: !self.guides,
clip_outlines: false,
area_type_interior: false,
ignore_layer_preview: false,
}
}
+19 -2
View File
@@ -320,12 +320,12 @@ fn preview_corner(cx: &ToolContext, p: Point, cache: &mut PreviewBoxes) -> Optio
}
// 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.
// locked member, or one made into a guide, 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;
let editable = m.visible && !m.locked && !m.is_guide();
if holder.is_none_or(|(near, _, was)| gap < near || (gap == near && editable && !was)) {
holder = Some((gap, m.id, editable));
}
@@ -1837,6 +1837,23 @@ mod tests {
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:?}");
}
// A visible, unlocked member of a stroked compound path made into a guide does not hold
// the corner its box puts there.
let mut d = vectorcraft_doc::Document::new(500.0, 500.0);
let (l, hole, part, whole) = (d.layers[0].id, d.alloc_id(), d.alloc_id(), d.alloc_id());
let mut guide = Node::path(part, vectorcraft_geom::shapes::rectangle(Rect::new(100.0, 100.0, 200.0, 200.0)), Default::default());
if let NodeKind::Path { guide, .. } = &mut guide.kind {
*guide = true;
}
let small = Node::path(hole, vectorcraft_geom::shapes::rectangle(Rect::new(140.0, 140.0, 160.0, 160.0)), Default::default());
let mut n =
Node::new(whole, NodeKind::Compound { children: vec![std::sync::Arc::new(small), std::sync::Arc::new(guide)], rule: Default::default() });
n.appearance = vectorcraft_doc::Appearance::default_art().into();
d.insert(Some(l), 0, n).expect("the compound path");
let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) };
let mut t = DimensionTool::default();
let (q, _) = t.snap_linear(&c, Point::new(99.6, 99.6));
assert!(t.corner.is_none() && !near(q, Point::new(99.5, 99.5)), "{q:?} {:?}", t.corner);
// 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());
+1 -1
View File
@@ -823,7 +823,7 @@ impl Tool for DirectSelectionTool {
fn options(&self) -> Value {
self.mesh.options()
}
/// Direct Selection picks the gradient mesh points the Eyedropper held (`meshPoints`); Group
/// Direct Selection picks the gradient mesh points the tool chosen before held (`meshPoints`); Group
/// Selection, which selects whole objects, does not.
/// The session sets `lentByCmd` on the tool Cmd/Ctrl lends for one gesture
/// ([`DirectSelectionTool::mirrors`]).
+21
View File
@@ -448,6 +448,10 @@ impl Tool for FamilyTool {
_ => self.grid_skew_key(key).is_some(),
}
}
/// The pointer left the canvas: the Smart Guide of the hover goes.
fn hover_ended(&mut self, _cx: &ToolContext) {
self.snap.clear();
}
fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {
let mut o = self.snap.guides().to_vec();
if let Some(s) = self.start.filter(|_| self.began && cx.measurement_labels) {
@@ -1254,6 +1258,23 @@ mod tests {
assert!(t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == "align")));
}
/// The "anchor" label a hover shows goes when the pointer leaves the canvas.
#[test]
fn leaving_the_canvas_drops_the_hover_label() {
let (d, _) = doc_with_rect();
let s = Selection::default();
let p = paint();
let cx = cx(&d, &s, &p);
let label = |o: &[Overlay]| o.iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == "anchor"));
for id in ["arc", "spiral", "rectangularGrid", "polarGrid"] {
let mut t = FamilyTool::new(id);
t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 98.0, 102.0));
assert!(label(&t.overlays(&cx)), "{id}");
t.hover_ended(&cx);
assert!(!label(&t.overlays(&cx)), "{id}: {:?}", t.overlays(&cx));
}
}
/// A grid's Default Size and Reference Point are options for a click's dialog; the drag
/// draws the box it is dragged to and leaves them out of its command.
#[test]
+4 -10
View File
@@ -1300,12 +1300,6 @@ impl GestureTool {
self.poses.len() == self.points.len()
}
/// The tip at point `i` of the stroke, as `path.eraseRegion` reads the pen there
/// ([`Self::controls_of_point`]).
fn tip_of_point(&self, i: usize) -> [f64; 3] {
self.tip_of_controls(self.controls_of_point(i))
}
/// The tip halfway along the step from point `j` to point `j + 1`, as `path.eraseRegion` reads
/// the pen there: the pressure and tilt halfway between those at the two points, and the
/// bearing and rotation halfway between them the shorter way round. A tip whose angle follows
@@ -1945,7 +1939,7 @@ impl Tool for GestureTool {
};
let mut area = self.area.take().filter(|a| a.fits(key, &self.points)).unwrap_or_else(|| AreaPreview::new(key, self.points[0]));
let sized = |[angle, roundness, size]: [f64; 3]| [angle, roundness, if size_varies { size } else { self.size }];
area.step(&self.points, &|i| sized(self.tip_of_point(i)), &|j| sized(self.tip_between(j)));
area.step(&self.points, &|j| sized(self.tip_between(j)));
let paths = area.paths(&self.points);
o.extend(paths.settled.into_iter().map(|path| Overlay::SharedPath { path, color, width: 1.0, dash: None }));
o.extend(paths.live.into_iter().map(|path| Overlay::Path { path, color, width: 1.0, dashed: false }));
@@ -1953,9 +1947,9 @@ impl Tool for GestureTool {
self.area.set(Some(area));
} else if size_varies {
// With Size on a mode that follows the pen, each step of the drag shows as wide as the
// tip the pen gives at its ends. A long drag's steps are kept from call to call
// ([`LinePreview::segments`]).
let width_of = |j: usize| ((self.tip_of_point(j)[2] + self.tip_of_point(j + 1)[2]) / 2.0 * cx.zoom) as f32;
// tip the pen gives halfway along it, as `path.eraseRegion` reads it. A long drag's
// steps are kept from call to call ([`LinePreview::segments`]).
let width_of = |j: usize| (self.tip_between(j)[2] * cx.zoom) as f32;
if self.points.len() > line::PIECE_SEGMENTS + 1 {
let mut kept = self.line.take().unwrap_or_default();
for (j, path) in kept.segments(&self.points).into_iter().enumerate() {
+15 -14
View File
@@ -157,8 +157,8 @@ pub(super) struct AreaPreview {
sq: Vec<Point>,
/// The last point taken, on the page.
last: Point,
/// The tip at the last point taken, when the tip varies along the drag.
last_tip: Option<Tip>,
/// The tip halfway along the last segment taken, when the tip varies along the drag.
last_middle: Option<Tip>,
/// The tip's radius along each segment, where its tip is round. It is also as far as the
/// segment's area reaches from the segment in the grid's space.
radius: Vec<f64>,
@@ -196,7 +196,7 @@ impl AreaPreview {
side: widest.max(MIN_BRUSH_SIZE),
sq: vec![],
last: first,
last_tip: None,
last_middle: None,
radius: vec![],
to_round: vec![],
pieces: vec![],
@@ -240,20 +240,22 @@ impl AreaPreview {
}
/// Take the points of the drag `pts` added since the last call and check outlines, within this
/// call's limits. When the tip varies along the drag, `tip(i)` gives the tip at point `i`, and
/// segment `j` takes `middle(j)`, the tip halfway along it. A last point whose tip changed since
/// it was taken (a pen turned or tilted in place) gives its segment the new tip.
pub(super) fn step(&mut self, pts: &[Point], tip: &dyn Fn(usize) -> Tip, middle: &dyn Fn(usize) -> Tip) {
/// call's limits. When the tip varies along the drag, segment `j` takes `middle(j)`, the tip
/// halfway along it. A last segment whose tip halfway along it changed since it was taken (a pen
/// turned or tilted in place at its end) takes the new tip, also where the tip at its end stays
/// the same (a size held at its least).
pub(super) fn step(&mut self, pts: &[Point], middle: &dyn Fn(usize) -> Tip) {
self.work = AreaWork::default();
let mut changed = BTreeSet::new();
if self.key.varies
&& let Some(j) = self.sq.len().checked_sub(2)
&& self.last_tip.is_some_and(|t| t != tip(j + 1))
&& self.last_middle.is_some_and(|t| t != middle(j))
{
let k = self.piece_of(j);
let old = self.radius[j];
self.set_tip(j, middle(j));
self.last_tip = Some(tip(j + 1));
let tip = middle(j);
self.set_tip(j, tip);
self.last_middle = Some(tip);
changed.insert(k);
// The pieces near the old tip or the new one are checked again.
let new = self.radius[j];
@@ -266,13 +268,12 @@ impl AreaPreview {
self.sq.push(self.squash * pts[i]);
self.last = pts[i];
self.work.points += 1;
if self.key.varies {
self.last_tip = Some(tip(i));
}
let Some(j) = i.checked_sub(1) else { continue };
if self.key.varies {
self.radius.push(0.0);
self.set_tip(j, middle(j));
let tip = middle(j);
self.set_tip(j, tip);
self.last_middle = Some(tip);
} else {
self.radius.push(self.key.size / 2.0);
}
+67
View File
@@ -3622,6 +3622,73 @@ fn the_eraser_drag_area_takes_the_tip_halfway_along_each_step() {
t.pointer(&cx, &PointerEvent { pressure: 1.0, ..PointerEvent::new(PointerKind::Up, 150.0, 150.0) });
}
/// A step of a round Eraser drag whose Size follows the pen shows as wide as the tip halfway along
/// it, as the release erases: with Size 10 pt on Pressure by up to 20 pt, a step from no pressure
/// (the tip at its 0.1 pt least) to full pressure (30 pt) shows 10 pt wide, not the 15.05 pt
/// halfway between the tips at its ends.
#[test]
fn a_round_eraser_drag_step_is_as_wide_as_the_tip_halfway_along_it() {
let (d, _) = doc_with_rect();
let s = Selection::default();
let p = paint();
let cx = ToolContext { precise_cursors: true, ..cx(&d, &s, &p) };
let mut t = GestureTool::new("eraser");
for (k, v) in [("size", json!(10)), ("sizeMode", json!("pressure")), ("sizeVariation", json!(20))] {
t.set_option(k, &v);
}
t.pointer(&cx, &PointerEvent { pressure: 0.0, ..PointerEvent::new(PointerKind::Down, 50.0, 150.0) });
t.pointer(&cx, &PointerEvent { pressure: 1.0, ..PointerEvent::new(PointerKind::Drag, 150.0, 150.0) });
let o = t.overlays(&cx);
assert!(matches!(&o[..], [Overlay::Path { width, .. }] if (*width - 10.0).abs() < 1e-4), "{o:?}");
t.pointer(&cx, &PointerEvent { pressure: 1.0, ..PointerEvent::new(PointerKind::Up, 150.0, 150.0) });
}
/// A pen tilted in place at the last point of an Eraser drag gives the last step the new tip halfway
/// along it, even where the tip at that point stays the same: with Size 10 pt on Tilt by up to 20 pt,
/// the tip at a pen leaning 80° and at one leaning 85° is the 0.1 pt least, while halfway along a
/// step from an upright pen it goes from 12.22 pt to 11.11 pt.
#[test]
fn the_eraser_drag_area_takes_the_new_tip_halfway_along_a_step_whose_end_tip_stays() {
let (d, _) = doc_with_rect();
let s = Selection::default();
let p = paint();
let cx = ToolContext { precise_cursors: true, ..cx(&d, &s, &p) };
let bounds = |t: &GestureTool| {
drain_area(t, &cx);
let o = t.overlays(&cx);
o.iter()
.filter_map(|o| match o {
Overlay::Path { path, .. } => Some(vectorcraft_geom::Shape::bounding_box(path)),
Overlay::SharedPath { path, .. } => Some(vectorcraft_geom::Shape::bounding_box(&**path)),
_ => None,
})
.reduce(|a, b| a.union(b))
.unwrap_or_else(|| panic!("{o:?}"))
};
// The tip lying level, 4 times as long as it is wide: a step from x 50 to x 150 with a tip
// `size` long reaches `size` / 2 before and after it and `size` / 8 above and below.
let near = |b: vectorcraft_geom::Rect, size: f64| {
let want = (50.0 - size / 2.0, 150.0 - size / 8.0, 150.0 + size / 2.0, 150.0 + size / 8.0);
assert!([b.x0 - want.0, b.y0 - want.1, b.x1 - want.2, b.y1 - want.3].iter().all(|e| e.abs() < 0.01), "{b:?} vs {want:?}");
};
let mut t = GestureTool::new("eraser");
for (k, v) in [("size", json!(10)), ("roundness", json!(25)), ("sizeMode", json!("tilt")), ("sizeVariation", json!(20))] {
t.set_option(k, &v);
}
let press = |t: &mut GestureTool, lean: f32, kind: PointerKind, x: f64| {
let pen = Some(PenPose { tilt: Some([lean, 0.0]), rotation: None, wheel: None });
t.pointer(&cx, &PointerEvent { pen, pressure: 1.0, ..PointerEvent::new(kind, x, 150.0) });
};
press(&mut t, 0.0, PointerKind::Down, 50.0);
press(&mut t, 80.0, PointerKind::Drag, 150.0);
// Tilt reads 1 upright and 1/9 at 80°, 5/9 halfway: 10 + 20 × (2 × 5/9 − 1) pt.
near(bounds(&t), 10.0 + 20.0 / 9.0);
// At 85° Tilt reads 1/18, 19/36 halfway.
press(&mut t, 85.0, PointerKind::Drag, 150.0);
near(bounds(&t), 10.0 + 20.0 / 18.0);
press(&mut t, 85.0, PointerKind::Up, 150.0);
}
/// The outline of a long Eraser drag whose tip turns and changes shape with the pen is built a
/// bounded amount per frame, and once finished it shows nothing inside the area: no point of it
/// lies well inside the area of any step, each step with the tip halfway along it.
+20
View File
@@ -618,6 +618,26 @@ pub(crate) mod testutil {
PaintDefaults::default()
}
/// With the Selection tool, a widget pressed at `at` and dragged to `q`, then released at `r`, is
/// dragged to `r` before the drag ends: the release keeps what a drag to `r` shows. Switching
/// tools during the drag cancels it, and the release after it commits nothing.
pub fn check_widget_release_and_tool_switch(cx: &ToolContext, at: Point, q: Point, r: Point) {
let pressed = || {
let mut t = crate::select::SelectionTool::default();
t.pointer(cx, &PointerEvent::new(PointerKind::Down, at.x, at.y));
assert!(!t.pointer(cx, &PointerEvent::new(PointerKind::Drag, q.x, q.y)).is_empty(), "the drag to {q:?} changes the widget");
t
};
let mut want = pressed().pointer(cx, &PointerEvent::new(PointerKind::Drag, r.x, r.y));
assert!(!want.is_empty(), "the drag to {r:?} changes the widget");
want.push(Action::Commit);
assert_eq!(pressed().pointer(cx, &PointerEvent::new(PointerKind::Up, r.x, r.y)), want, "released at {r:?}");
let mut t = pressed();
assert_eq!(t.deactivate(cx), vec![Action::Cancel], "a tool switch cancels the drag");
assert!(!t.busy() && !t.transforming());
assert!(t.pointer(cx, &PointerEvent::new(PointerKind::Up, q.x, q.y)).is_empty(), "the release commits nothing");
}
/// An 800 × 600 window on a view at 100% turned `deg` degrees clockwise (Rotate View): at 90°
/// one pixel right on screen is one point up the page.
pub fn turned_view(deg: f64) -> Option<ScreenFrame> {
+1 -1
View File
@@ -360,7 +360,7 @@ impl Tool for MeshTool {
fn options(&self) -> serde_json::Value {
self.edit.options()
}
/// Pick the gradient mesh points the Eyedropper held (`meshPoints`).
/// Pick the gradient mesh points the tool chosen before held (`meshPoints`).
fn set_option(&mut self, key: &str, value: &serde_json::Value) {
if key == "meshPoints" {
self.edit.set_options(value);
+1 -1
View File
@@ -325,7 +325,7 @@ impl MeshEdit {
}
/// Pick the points a `meshPoints` option lists (see [`points_of`]), with none focused: the
/// points the Eyedropper held when the tool switched back.
/// points the tool chosen before (another mesh-point tool or the Eyedropper) held.
pub fn set_options(&mut self, value: &Value) {
if self.drag.is_some() {
return;
+16
View File
@@ -185,6 +185,22 @@ mod tests {
assert!(MirrorAxis::of(&doc, &selection, 1.0).is_none());
}
/// With the Selection tool, a drag of the axis reads where it is released, and a tool switch
/// cancels it.
#[test]
fn an_axis_drag_reads_its_release_and_a_tool_switch_cancels_it() {
let (mut doc, id) = doc_with_rect();
let mut source = doc.node(id).unwrap().clone();
source.id = doc.alloc_id();
doc.node_mut(id).unwrap().kind = NodeKind::Repeat(RepeatSpec::mirror(vec![Arc::new(source)], 90.0, 10.0));
let mut selection = Selection::default();
selection.set([id]);
let paint = paint();
let cx = cx(&doc, &selection, &paint);
let at = MirrorAxis::of(&doc, &selection, 1.0).unwrap().center;
crate::testutil::check_widget_release_and_tool_switch(&cx, at, at + Vec2::new(20.0, 0.0), at + Vec2::new(40.0, 0.0));
}
#[test]
fn a_tool_switch_cancels_a_mirror_axis_drag() {
use crate::{PointerEvent, PointerKind, Tool};
+9
View File
@@ -238,6 +238,15 @@ mod tests {
assert_eq!(t.pointer(&c, &ev(PointerKind::Up, 150.0, 250.0)), vec![Action::Commit]);
}
/// A guide drag reads where it is released, and a tool switch cancels it.
#[test]
fn a_guide_drag_reads_its_release_and_a_tool_switch_cancels_it() {
let d = editing(Some(SymbolNineSlice::default()));
let (s, p) = (Selection::default(), paint());
let c = cx(&d, &s, &p);
check_widget_release_and_tool_switch(&c, Point::new(126.0, 150.0), Point::new(115.0, 150.0), Point::new(105.0, 150.0));
}
/// Escape during a guide drag cancels it and is the tool's; the release after it commits
/// nothing. A double-click on a guide neither edits the art nor leaves the mode.
#[test]
+125 -7
View File
@@ -948,6 +948,9 @@ pub struct ObjectsOnPathTool {
member: Option<MemberDrag>,
/// Where the pointer is while no button is down, for the Select/Move widget it is over.
pointer: Option<Point>,
/// Where the pointer was at the last press or drag: a widget drag released anywhere else is
/// dragged there before it ends.
held_at: Option<Point>,
/// The reference point of each object attached next (0-8, row by row from the top left).
pivot: u8,
/// The angle of each object attached next, in degrees counter-clockwise from upright on the path.
@@ -956,7 +959,18 @@ pub struct ObjectsOnPathTool {
impl Default for ObjectsOnPathTool {
fn default() -> Self {
Self { hover: None, press: None, rotating: None, spacing: None, moving: None, member: None, pointer: None, pivot: CENTER, rotate: 0.0 }
Self {
hover: None,
press: None,
rotating: None,
spacing: None,
moving: None,
member: None,
pointer: None,
held_at: None,
pivot: CENTER,
rotate: 0.0,
}
}
}
@@ -967,31 +981,51 @@ impl Tool for ObjectsOnPathTool {
fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
let p = ev.pos;
let released_away = ev.kind == PointerKind::Up && self.held_at != Some(p);
if matches!(ev.kind, PointerKind::Down | PointerKind::Drag) {
self.held_at = Some(p);
}
if let Some(d) = &mut self.rotating {
return match ev.kind {
PointerKind::Drag => d.drag(cx, p, ev.mods.shift),
PointerKind::Up => self.rotating.take().map(RotateAllDrag::finish).unwrap_or_default(),
PointerKind::Up => {
let mut out = if released_away { d.drag(cx, p, ev.mods.shift) } else { vec![] };
out.extend(self.rotating.take().map(RotateAllDrag::finish).unwrap_or_default());
out
}
_ => vec![],
};
}
if let Some(d) = &mut self.spacing {
return match ev.kind {
PointerKind::Drag => d.drag(cx, p, ev.mods.alt),
PointerKind::Up => self.spacing.take().map(SpaceDrag::finish).unwrap_or_default(),
PointerKind::Up => {
let mut out = if released_away { d.drag(cx, p, ev.mods.alt) } else { vec![] };
out.extend(self.spacing.take().map(SpaceDrag::finish).unwrap_or_default());
out
}
_ => vec![],
};
}
if let Some(d) = &mut self.moving {
return match ev.kind {
PointerKind::Drag => d.drag(cx, p),
PointerKind::Up => self.moving.take().map(MoveAllDrag::finish).unwrap_or_default(),
PointerKind::Up => {
let mut out = if released_away { d.drag(cx, p) } else { vec![] };
out.extend(self.moving.take().map(MoveAllDrag::finish).unwrap_or_default());
out
}
_ => vec![],
};
}
if let Some(d) = &mut self.member {
return match ev.kind {
PointerKind::Drag => d.drag(cx, p),
PointerKind::Up => self.member.take().map(MemberDrag::finish).unwrap_or_default(),
PointerKind::Up => {
let mut out = if released_away { d.drag(cx, p) } else { vec![] };
out.extend(self.member.take().map(MemberDrag::finish).unwrap_or_default());
out
}
_ => vec![],
};
}
@@ -1084,6 +1118,11 @@ impl Tool for ObjectsOnPathTool {
vec![]
}
/// Switching tools while the button is down cancels the click or the drag, as Escape does.
fn deactivate(&mut self, cx: &ToolContext) -> Vec<Action> {
self.key(cx, ToolKey::Escape, Mods::default())
}
fn options(&self) -> Value {
json!({ "pivot": self.pivot, "rotate": self.rotate })
}
@@ -1508,7 +1547,7 @@ mod tests {
assert!(matches!(a.last(), Some(Action::Preview(_, p)) if p["spacing"] == "auto" && p["start"] == 0.0), "{id}: {a:?}");
assert_eq!(spaced(&t.pointer(&c, &ev(PointerKind::Drag, at.x - 900.0, at.y))), Some((0.0, 0.0)), "{id}");
assert_eq!(spaced(&t.pointer(&c, &alt(PointerKind::Drag, at.x - 900.0, at.y))), Some((0.0, 200.0)), "{id}");
assert_eq!(t.pointer(&c, &ev(PointerKind::Up, at.x, at.y)), vec![Action::Commit], "{id}");
assert_eq!(t.pointer(&c, &alt(PointerKind::Up, at.x - 900.0, at.y)), vec![Action::Commit], "{id}");
assert!(!t.busy(), "{id}");
// A click on the widget that does not move changes nothing.
assert!(t.pointer(&c, &ev(PointerKind::Down, at.x, at.y)).is_empty());
@@ -1730,7 +1769,7 @@ mod tests {
assert_eq!(moved(&t.pointer(&c, &ev(PointerKind::Drag, at.x + 900.0, at.y))), Some((300.0, None)), "{id}");
assert_eq!(moved(&t.pointer(&c, &ev(PointerKind::Drag, at.x + 880.0, at.y))), Some((280.0, None)), "{id}");
assert_eq!(moved(&t.pointer(&c, &ev(PointerKind::Drag, at.x - 900.0, at.y))), Some((0.0, None)), "{id}");
assert_eq!(t.pointer(&c, &ev(PointerKind::Up, at.x, at.y)), vec![Action::Commit], "{id}");
assert_eq!(t.pointer(&c, &ev(PointerKind::Up, at.x - 900.0, at.y)), vec![Action::Commit], "{id}");
assert!(!t.busy(), "{id}");
// A click on the widget that does not move changes nothing.
assert!(t.pointer(&c, &ev(PointerKind::Down, at.x, at.y)).is_empty());
@@ -2007,6 +2046,85 @@ mod tests {
}
}
/// The release is read where it happens: a release away from the last drag event drags the
/// widget there before the drag ends, with the Selection tool and the Objects on Path tool.
#[test]
fn the_release_position_sets_each_widget() {
let new_tools = || -> [Box<dyn Tool>; 2] { [Box::new(crate::select::SelectionTool::default()), Box::new(ObjectsOnPathTool::default())] };
let paint = paint();
let (d, _, sel) = group_doc(0.0);
let c = cx(&d, &sel, &paint);
for mut t in new_tools() {
let (at, q, r) = (around(0.0), around(60.0), around(90.0));
t.pointer(&c, &ev(PointerKind::Down, at.x, at.y));
t.pointer(&c, &ev(PointerKind::Drag, q.x, q.y));
let a = t.pointer(&c, &ev(PointerKind::Up, r.x, r.y));
let (last, shown) = a.split_last().unwrap();
assert_eq!(last, &Action::Commit, "{}", t.id());
assert!(previewed(shown).is_some_and(|deg| (deg - 90.0).abs() < 1e-9), "{}: Rotate All {a:?}", t.id());
}
let at = SpaceWidget::of(&d, &sel, 1.0).unwrap().at;
for mut t in new_tools() {
t.pointer(&c, &ev(PointerKind::Down, at.x, at.y));
t.pointer(&c, &ev(PointerKind::Drag, at.x - 100.0, at.y));
let a = t.pointer(&c, &ev(PointerKind::Up, at.x - 50.0, at.y));
let (last, shown) = a.split_last().unwrap();
assert_eq!(last, &Action::Commit, "{}", t.id());
assert_eq!(spaced(shown), Some((350.0, 0.0)), "{}: Space {a:?}", t.id());
}
let (d, _, sel) = spaced_doc(Some(100.0), 50.0);
let c = cx(&d, &sel, &paint);
let at = MoveAllWidget::of(&d, &sel, 1.0).unwrap().at;
for mut t in new_tools() {
t.pointer(&c, &ev(PointerKind::Down, at.x, at.y));
t.pointer(&c, &ev(PointerKind::Drag, at.x + 80.0, at.y));
let a = t.pointer(&c, &ev(PointerKind::Up, at.x + 90.0, at.y));
let (last, shown) = a.split_last().unwrap();
assert_eq!(last, &Action::Commit, "{}", t.id());
assert_eq!(moved(shown), Some((140.0, None)), "{}: Move All {a:?}", t.id());
}
let (d, _, sel, ids) = three_doc();
let c = cx(&d, &sel, &paint);
for mut t in new_tools() {
t.pointer(&c, &ev(PointerKind::Down, 200.0, 300.0));
t.pointer(&c, &ev(PointerKind::Drag, 280.0, 310.0));
let a = t.pointer(&c, &ev(PointerKind::Up, 330.0, 300.0));
assert_eq!(previewed_target(&a), Some(ids[2].0), "{}: Select/Move {a:?}", t.id());
assert_eq!(a[1..], [Action::Commit, choose(ids[1])], "{}", t.id());
}
}
/// Switching tools during a widget drag cancels it, as Escape does, with the Selection tool and
/// the Objects on Path tool; after a press that has not moved there is nothing to put back.
#[test]
fn a_tool_switch_cancels_a_widget_drag() {
let new_tools = || -> [Box<dyn Tool>; 2] { [Box::new(crate::select::SelectionTool::default()), Box::new(ObjectsOnPathTool::default())] };
let paint = paint();
let (d, _, sel) = group_doc(0.0);
let (md, _, msel) = spaced_doc(Some(100.0), 50.0);
let (od, _, osel, _) = three_doc();
let space = SpaceWidget::of(&d, &sel, 1.0).unwrap().at;
let move_all = MoveAllWidget::of(&md, &msel, 1.0).unwrap().at;
let presses = [
(cx(&d, &sel, &paint), around(0.0), around(60.0)),
(cx(&d, &sel, &paint), space, space - Vec2::new(100.0, 0.0)),
(cx(&md, &msel, &paint), move_all, move_all + Vec2::new(80.0, 0.0)),
(cx(&od, &osel, &paint), Point::new(200.0, 300.0), Point::new(330.0, 300.0)),
];
for (c, at, q) in &presses {
for mut t in new_tools() {
t.pointer(c, &ev(PointerKind::Down, at.x, at.y));
assert!(!t.pointer(c, &ev(PointerKind::Drag, q.x, q.y)).is_empty(), "{}", t.id());
assert_eq!(t.deactivate(c), vec![Action::Cancel], "{} at {at:?}", t.id());
assert!(!t.busy() && !t.transforming(), "{}", t.id());
assert!(t.pointer(c, &ev(PointerKind::Up, q.x, q.y)).is_empty(), "{}: the release keeps nothing", t.id());
t.pointer(c, &ev(PointerKind::Down, at.x, at.y));
assert!(t.deactivate(c).is_empty(), "{}", t.id());
assert!(!t.busy(), "{}", t.id());
}
}
}
/// Round a closed path the drag goes on across the first anchor: the first object, dragged back
/// past it, takes the last place.
#[test]
+10
View File
@@ -310,6 +310,16 @@ mod tests {
assert!(t.pointer(&c, &ev(PointerKind::Up, Point::new(100.0, 200.0))).is_empty(), "the release commits nothing");
}
/// A pie widget drag with the Selection tool reads where it is released, and a tool switch
/// cancels it.
#[test]
fn a_pie_widget_drag_reads_its_release_and_a_tool_switch_cancels_it() {
let (d, _, s) = doc_with_ellipse((0.0, 360.0));
let p = paint();
let c = cx(&d, &s, &p);
check_widget_release_and_tool_switch(&c, Point::new(312.0, 150.0), Point::new(200.0, 20.0), Point::new(100.0, 150.0));
}
/// On a whole ellipse the two widgets sit at the very same point, whatever its size, place or
/// angle, so a press there always takes the End widget.
#[test]
+11
View File
@@ -369,6 +369,17 @@ mod tests {
assert!(GridDrag::hit(&c, g.rows_at, Mods { alt: true, ..Mods::default() }).is_none());
}
/// With the Selection tool, a handle drag reads where it is released, and a tool switch cancels
/// it.
#[test]
fn a_handle_drag_reads_its_release_and_a_tool_switch_cancels_it() {
let (doc, selection) = grid();
let paint = paint();
let c = cx(&doc, &selection, &paint);
let g = GridHandles::of(&doc, &selection, crate::select::selection_box(&c), 1.0).unwrap();
crate::testutil::check_widget_release_and_tool_switch(&c, g.rows_at, g.rows_at + Vec2::new(0.0, 240.0), g.rows_at + Vec2::new(0.0, 360.0));
}
#[test]
fn a_bounding_box_handle_wins_where_they_overlap() {
let (doc, selection) = grid();
+11
View File
@@ -533,6 +533,17 @@ mod tests {
assert!(RadialDrag::hit(&c, h.instances_at, Mods { alt: true, ..Mods::default() }).is_none());
}
/// With the Selection tool, a handle drag reads where it is released, and a tool switch cancels
/// it.
#[test]
fn a_handle_drag_reads_its_release_and_a_tool_switch_cancels_it() {
let (doc, selection) = radial();
let paint = paint();
let c = cx(&doc, &selection, &paint);
let at = RadialHandles::of(&doc, &selection, crate::select::selection_box(&c), 1.0).unwrap().instances_at;
crate::testutil::check_widget_release_and_tool_switch(&c, at, at + Vec2::new(0.0, 32.0), at + Vec2::new(0.0, 64.0));
}
#[test]
fn dragging_the_radius_handle_moves_the_circle_in_and_out() {
let (doc, selection) = radial();
+51 -16
View File
@@ -58,6 +58,14 @@ use crate::sidewidget::{self, SideDrag};
use crate::typewidget;
use crate::{Action, Cursor, Mods, Overlay, PixelOp, PointerEvent, PointerKind, Tool, ToolContext, ToolKey, json_ids};
/// The release of the widget drag `d`: released away from the last press or drag (`away`), it is
/// dragged there first (`drag`); then it ends (`finish`).
fn released<D>(mut d: D, away: bool, drag: impl FnOnce(&mut D) -> Vec<Action>, finish: impl FnOnce(D) -> Vec<Action>) -> Vec<Action> {
let mut out = if away { drag(&mut d) } else { vec![] };
out.extend(finish(d));
out
}
/// Direction is read on screen, even in a turned view. Within three pixels of the press's
/// horizontal position, retain the previous rule so hand jitter does not flip it.
fn marquee_direction(cx: &ToolContext, start: Point, cur: Point, previous: bool) -> bool {
@@ -213,6 +221,9 @@ pub struct SelectionTool {
loaded_at_press: Option<(NodeId, bool)>,
/// Where the pointer last hovered: the type on a path bracket under it draws thicker.
bracket_hover: Option<Point>,
/// Where the pointer was at the last press or drag: a widget drag released anywhere else is
/// dragged there before it ends.
held_at: Option<Point>,
}
/// What Distance Guides measure the selection to.
@@ -784,6 +795,16 @@ impl SelectionTool {
}
}
/// Notes where a press or a drag last held the pointer, and says whether a release lands
/// somewhere else.
fn note_held_at(&mut self, ev: &PointerEvent) -> bool {
let released_away = ev.kind == PointerKind::Up && self.held_at != Some(ev.pos);
if matches!(ev.kind, PointerKind::Down | PointerKind::Drag) {
self.held_at = Some(ev.pos);
}
released_away
}
/// The pointer loaded with the text of area type or type on a path `from` ([`State::Loaded`]):
/// a press starts placing it, and its release threads it (`text.thread.add`), into a frame put
/// `before` `from` or after it. None when `from` can no longer thread: the press is an
@@ -945,20 +966,33 @@ impl Tool for SelectionTool {
out
}
/// Switching tools during a drag of a blend widget, a corner widget, a pie widget, a
/// polygon's side widget, a mirror axis, a grid or radial repeat's handles or an Image Trace
/// divider cancels it, as Escape does: its value goes back.
/// Switching tools during a drag of a widget (a blend, corner, pie or side widget, an Objects on
/// Path widget, a bracket of type on a path, a repeat's control, a 9-slice guide or an Image
/// Trace divider) cancels it, as Escape does: its value goes back.
fn deactivate(&mut self, _cx: &ToolContext) -> Vec<Action> {
match std::mem::take(&mut self.state) {
State::BlendWidget(d) if d.adjusting() => vec![Action::Cancel],
State::Corner(c) if c.adjusting() => vec![Action::Cancel],
State::Pie(d) if d.adjusting() => vec![Action::Cancel],
State::RotateAll(d) if d.adjusting() => vec![Action::Cancel],
State::Space(d) if d.adjusting() => vec![Action::Cancel],
State::MoveAll(d) if d.adjusting() => vec![Action::Cancel],
State::Member(d) if d.adjusting() => vec![Action::Cancel],
State::Bracket(b) if b.adjusting() => vec![Action::Cancel],
State::Sides(d) => d.cancel(),
State::Mirror(d) => d.cancel(),
State::GridRepeat(d) => d.cancel(),
State::RadialRepeat(d) => d.cancel(),
State::NineSlice(d) => d.cancel(),
State::TraceSplit(d) => d.cancel(),
State::BlendWidget(_) | State::Corner(_) | State::Pie(_) => vec![],
State::BlendWidget(_)
| State::Corner(_)
| State::Pie(_)
| State::RotateAll(_)
| State::Space(_)
| State::MoveAll(_)
| State::Member(_)
| State::Bracket(_) => vec![],
other => {
self.state = other;
vec![]
@@ -1026,6 +1060,7 @@ impl Tool for SelectionTool {
/// the art; the drags then move, scale, rotate, marquee or drag what it took.
fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
self.note_loaded_at_press(ev.kind);
let released_away = self.note_held_at(ev);
let hovering = ev.kind == PointerKind::Move && matches!(self.state, State::Idle);
self.bracket_hover = hovering.then_some(ev.pos);
self.alt_hover = hovering && ev.mods.alt;
@@ -1036,7 +1071,7 @@ impl Tool for SelectionTool {
return out;
}
// The edited symbol's 9-slice guides take precedence over every other control and the art.
if let Some(out) = self.nine_slice_guides(cx, ev) {
if let Some(out) = self.nine_slice_guides(cx, ev, released_away) {
return out;
}
// Mirror and grid repeat controls take precedence over art and ruler guides; the mirror
@@ -1181,7 +1216,7 @@ impl Tool for SelectionTool {
}
(PointerKind::Up, State::Corner(c)) => {
self.state = State::Idle;
c.finish()
released(c, released_away, |c| c.drag(cx, p), CornerDrag::finish)
}
(PointerKind::Drag, State::Pie(mut d)) => {
let out = d.drag(cx, p);
@@ -1190,7 +1225,7 @@ impl Tool for SelectionTool {
}
(PointerKind::Up, State::Pie(d)) => {
self.state = State::Idle;
d.finish()
released(d, released_away, |d| d.drag(cx, p), PieDrag::finish)
}
(PointerKind::Drag, State::Sides(mut d)) => {
let out = d.drag(cx, p);
@@ -1210,7 +1245,7 @@ impl Tool for SelectionTool {
}
(PointerKind::Up, State::BlendWidget(d)) => {
self.state = State::Idle;
d.finish()
released(d, released_away, |d| d.drag(cx, p), BlendWidgetDrag::finish)
}
(PointerKind::Drag, State::RotateAll(mut d)) => {
let out = d.drag(cx, p, m.shift);
@@ -1219,7 +1254,7 @@ impl Tool for SelectionTool {
}
(PointerKind::Up, State::RotateAll(d)) => {
self.state = State::Idle;
d.finish()
released(d, released_away, |d| d.drag(cx, p, m.shift), RotateAllDrag::finish)
}
(PointerKind::Drag, State::Space(mut d)) => {
let out = d.drag(cx, p, m.alt);
@@ -1228,7 +1263,7 @@ impl Tool for SelectionTool {
}
(PointerKind::Up, State::Space(d)) => {
self.state = State::Idle;
d.finish()
released(d, released_away, |d| d.drag(cx, p, m.alt), SpaceDrag::finish)
}
(PointerKind::Drag, State::MoveAll(mut d)) => {
let out = d.drag(cx, p);
@@ -1237,7 +1272,7 @@ impl Tool for SelectionTool {
}
(PointerKind::Up, State::MoveAll(d)) => {
self.state = State::Idle;
d.finish()
released(d, released_away, |d| d.drag(cx, p), MoveAllDrag::finish)
}
(PointerKind::Drag, State::Member(mut d)) => {
let out = d.drag(cx, p);
@@ -1246,7 +1281,7 @@ impl Tool for SelectionTool {
}
(PointerKind::Up, State::Member(d)) => {
self.state = State::Idle;
d.finish()
released(d, released_away, |d| d.drag(cx, p), MemberDrag::finish)
}
(PointerKind::Drag, State::Bracket(mut b)) => {
let out = b.drag(cx, p, m.cmd);
@@ -1255,7 +1290,7 @@ impl Tool for SelectionTool {
}
(PointerKind::Up, State::Bracket(b)) => {
self.state = State::Idle;
b.finish()
released(b, released_away, |b| b.drag(cx, p, m.cmd), BracketDrag::finish)
}
(PointerKind::Up, State::Moving { began, deselect, key, exclude, .. }) => {
self.release_move(cx, ev.backquote, began, deselect, key, exclude)
@@ -1648,8 +1683,8 @@ impl SelectionTool {
}
/// A press on a 9-slice guide of the edited symbol starts dragging it; the drag and the
/// release go to it.
fn nine_slice_guides(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Option<Vec<Action>> {
/// release go to it, and a release away from the last drag (`released_away`) moves it there.
fn nine_slice_guides(&mut self, cx: &ToolContext, ev: &PointerEvent, released_away: bool) -> Option<Vec<Action>> {
if let State::NineSlice(mut d) = self.state.clone() {
return Some(match ev.kind {
PointerKind::Drag => {
@@ -1659,7 +1694,7 @@ impl SelectionTool {
}
PointerKind::Up => {
self.state = State::Idle;
d.finish()
released(d, released_away, |d| d.drag(cx, ev.pos), crate::nineslice::GuideDrag::finish)
}
_ => vec![],
});
+22
View File
@@ -654,6 +654,28 @@ fn escape_cancels_a_bracket_drag() {
assert!(t.pointer(&cx, &ev(PointerKind::Up, 330.0, 290.0)).is_empty(), "the release commits nothing");
}
/// A bracket drag of type on a path reads where it is released, and a tool switch cancels it.
#[test]
fn a_bracket_drag_reads_its_release_and_a_tool_switch_cancels_it() {
let (d, id) = crate::testutil::doc_with_path_type();
let mut s = Selection::default();
s.add(id);
let p = paint();
let cx = cx(&d, &s, &p);
check_widget_release_and_tool_switch(&cx, Point::new(280.0, 290.0), Point::new(320.0, 290.0), Point::new(340.0, 290.0));
}
/// A corner widget drag reads where it is released, and a tool switch cancels it.
#[test]
fn a_corner_widget_drag_reads_its_release_and_a_tool_switch_cancels_it() {
let (d, id) = doc_with_live_rect();
let mut s = Selection::default();
s.add(id);
let p = paint();
let cx = cx(&d, &s, &p);
check_widget_release_and_tool_switch(&cx, Point::new(190.0, 191.0), Point::new(175.0, 176.0), Point::new(165.0, 166.0));
}
/// #812: with Smart Guides on, hovering near an object's centre or an anchor labels it, and a
/// press there grabs the object by that point.
#[test]
+3 -1
View File
@@ -973,9 +973,11 @@ impl Tool for ShapeTool {
fn ends_on_escape(&self, _cx: &ToolContext) -> bool {
!self.through.is_empty()
}
/// The pointer left the canvas: the circle's preview through it goes.
/// The pointer left the canvas: the circle's preview through it and the Smart Guide of the
/// hover go.
fn hover_ended(&mut self, _cx: &ToolContext) {
self.hover = None;
self.snap.clear();
}
/// An edit, Undo or Redo made outside the tool, or another document, drops the points placed
/// for a circle.
+17
View File
@@ -968,6 +968,23 @@ fn corners_snap_to_smart_guides() {
assert!(t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text == &cx.segment_measure_label(from, to))));
}
/// The "anchor" label a hover shows goes when the pointer leaves the canvas, for every shape tool.
#[test]
fn leaving_the_canvas_drops_the_hover_label() {
let (d, _) = doc_with_rect();
let s = Selection::default();
let p = paint();
let cx = cx(&d, &s, &p);
let label = |o: &[Overlay]| o.iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == "anchor"));
for id in ["rectangle", "roundedRectangle", "ellipse", "polygon", "star", "lineSegment"] {
let mut t = ShapeTool::new(id);
t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 98.0, 102.0));
assert!(label(&t.overlays(&cx)), "{id}");
t.hover_ended(&cx);
assert!(!label(&t.overlays(&cx)), "{id}: {:?}", t.overlays(&cx));
}
}
/// Line Segment Tool Options: Length and Angle are options (for a click's dialog), and Fill
/// Line makes the drag's line take the current fill.
#[test]
+163 -7
View File
@@ -8,14 +8,15 @@
//!
//! Points mode (the Gradient panel's Draw toggle): a click inside the selected art adds a point
//! there, coloured as the gradient is there. Lines mode: successive clicks draw a smooth line
//! through the points they add, until Escape (or a click off the art) ends it; clicking an
//! existing point first starts the line from it. Delete or Backspace removes the selected point.
//! through the points they add, until Escape, a click off the art or moving the pointer out of
//! the object ends it; clicking an existing point first starts the line from it. Delete or
//! Backspace removes the selected point.
use serde_json::{Value, json};
use vectorcraft_color::freeform::LineHit;
use vectorcraft_color::{Color, Freeform, FreeformMode, FreeformPoint};
use vectorcraft_doc::NodeId;
use vectorcraft_doc::hit::hit_test;
use vectorcraft_doc::hit::{HitOptions, hit_test, hit_test_visible_skipping};
use vectorcraft_geom::{Point, Shape, Vec2};
use super::paint_owner;
@@ -183,6 +184,44 @@ fn on_art(cx: &ToolContext, p: Point) -> bool {
hit_test(cx.doc, p, cx.hit_options()).is_some_and(|h| cx.selection.objects.contains(&paint_owner(cx.doc, h.leaf)))
}
/// Is `p` on object `id`: inside its path's area (where a dragged point stays) and every clipping
/// mask above it, or on its own art where a click hits it with the art lying over it left out (a
/// stroke, type's glyphs)?
fn on_object(cx: &ToolContext, id: NodeId, p: Point) -> bool {
let Some(n) = cx.doc.node(id) else { return false };
let ancestry = cx.doc.ancestry(id).unwrap_or_default();
let contains = |shapes: &[(vectorcraft_geom::BezPath, vectorcraft_geom::FillRule)]| {
shapes.iter().any(|(bp, rule)| vectorcraft_geom::hit::fill_contains(bp, *rule, p))
};
// A mask with a live effect clips by the effect's result, which the hit test below measures.
let plain = |clip: &vectorcraft_doc::Node| {
let mut effects = false;
clip.walk(&mut |c| {
effects |= c.appearance.effects.iter().any(|e| e.visible) || c.appearance.items.iter().any(|i| i.effects().iter().any(|e| e.visible));
});
!effects
};
let unmasked = || {
ancestry.iter().filter_map(|a| cx.doc.node(*a)).filter(|a| a.clips()).all(|a| {
a.children()
.and_then(|c| c.first())
.is_none_or(|clip| clip.id == id || plain(clip) && contains(&vectorcraft_doc::hit::clip_regions(clip)))
})
};
if contains(&n.clip_shapes(None)) && unmasked() {
return true;
}
let mut keep = std::collections::HashSet::new();
n.walk(&mut |c| {
keep.insert(c.id);
});
keep.extend(ancestry);
// The art as painted, whatever the view, the layers' Preview and the path-only selection
// preferences.
let opt = HitOptions { outline: false, path_only: false, type_path_only: false, ignore_layer_preview: true, ..cx.hit_options() };
hit_test_visible_skipping(cx.doc, p, opt, &|n| !keep.contains(&n)).is_some_and(|h| h.leaf == id || h.ancestry.contains(&id))
}
pub(super) fn press(cx: &ToolContext, a: &Annotator, p: Point) -> (Vec<Action>, Gesture) {
let mut out = vec![];
let grab = if let Some(i) = a.point_at(cx, p) {
@@ -293,8 +332,13 @@ pub(super) fn double_click(cx: &ToolContext, a: &Annotator, p: Point) -> Vec<Act
}
/// Pointer moves: Lines mode's rubber band follows the pointer over the art (where a click
/// extends the line).
/// extends the line). Moving out of the object ends the line, so the next click on the object
/// starts another; the object's own art counts (its fill, stroke or glyphs), also where other art
/// lies over it.
pub(super) fn hover(cx: &ToolContext, lines: &mut Lines, p: Point) {
if lines.open && Annotator::of(cx).is_some_and(|a| !on_object(cx, a.id, p)) {
lines.open = false;
}
lines.hover = (lines.open && on_art(cx, p)).then_some(p);
}
@@ -433,9 +477,7 @@ mod tests {
t.pointer(&cx, &ev(PointerKind::Move, 170.0, 160.0));
let dashed = |t: &GradientTool, cx: &ToolContext| t.overlays(cx).iter().filter(|o| matches!(o, Overlay::Path { dashed: true, .. })).count();
assert_eq!(dashed(&t, &cx), 2, "the rubber band and the selected point's spread ring");
// Off the art (where a click ends the line) it goes.
t.pointer(&cx, &ev(PointerKind::Move, 400.0, 400.0));
assert_eq!(dashed(&t, &cx), 1);
// A click inside the object extends the line.
assert_eq!(click(&mut t, &cx, 170.0, 160.0), vec![add(170.0, 160.0, true)]);
// Escape ends the line: the next click starts another.
assert!(t.key(&cx, ToolKey::Escape, Default::default()).is_empty());
@@ -452,6 +494,120 @@ mod tests {
assert!(!t.claims_key(&cx, ToolKey::Escape));
}
/// Moving the pointer out of the object and back ends Lines mode's line: the next click on
/// the object starts another. Moves inside the object, also over other art on top of it, keep
/// the line open.
#[test]
fn leaving_the_object_ends_the_line() {
let (mut d, s) = doc(FreeformMode::Lines);
// Unselected art over the object's lower right corner and past it.
let (l, top) = (d.layers[0].id, d.alloc_id());
let rect = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(160.0, 160.0, 230.0, 230.0));
d.insert(Some(l), 1, vectorcraft_doc::Node::path(top, rect, vectorcraft_doc::Appearance::default_art())).unwrap();
let p = paint();
let mut cx = cx(&d, &s, &p);
let mut t = GradientTool::default();
let add = |x: f64, y: f64, line: bool| Action::Exec("paint.freeform.addPoint".into(), json!({"at": [x, y], "line": line, "stroke": false}));
let dashed = |t: &GradientTool, cx: &ToolContext| t.overlays(cx).iter().filter(|o| matches!(o, Overlay::Path { dashed: true, .. })).count();
assert_eq!(click(&mut t, &cx, 140.0, 150.0), vec![add(140.0, 150.0, false)]);
cx.freeform_point = Some(2);
// Inside the object, over the other art as well, the line stays open.
t.pointer(&cx, &ev(PointerKind::Move, 130.0, 130.0));
t.pointer(&cx, &ev(PointerKind::Move, 180.0, 190.0));
assert!(t.claims_key(&cx, ToolKey::Escape));
assert_eq!(click(&mut t, &cx, 150.0, 140.0), vec![add(150.0, 140.0, true)]);
// Out of the object (here still over the other art) and back: the line has ended.
t.pointer(&cx, &ev(PointerKind::Move, 210.0, 210.0));
assert!(!t.claims_key(&cx, ToolKey::Escape), "no line is left for Escape to end");
t.pointer(&cx, &ev(PointerKind::Move, 170.0, 130.0));
assert_eq!(dashed(&t, &cx), 1, "only the spread ring: no rubber band");
assert_eq!(click(&mut t, &cx, 170.0, 130.0), vec![add(170.0, 130.0, false)]);
// The next click joins the new line.
assert_eq!(click(&mut t, &cx, 130.0, 170.0), vec![add(130.0, 170.0, true)]);
// Out past an edge with no other art there ends it too.
t.pointer(&cx, &ev(PointerKind::Move, 60.0, 150.0));
t.pointer(&cx, &ev(PointerKind::Move, 140.0, 160.0));
assert_eq!(click(&mut t, &cx, 140.0, 160.0), vec![add(140.0, 160.0, false)]);
}
/// The object's stroke is part of the object: moving onto it past the filled area keeps the
/// line open, and moving past the stroke ends it. The same holds on a layer with Preview off.
#[test]
fn the_stroke_counts_as_the_object() {
for preview in [true, false] {
let (mut d, s) = doc(FreeformMode::Lines);
let id = s.objects[0];
d.node_mut(id).unwrap().appearance.stroke_mut().unwrap().width = 20.0;
let l = d.layers[0].id;
if let vectorcraft_doc::NodeKind::Layer { preview: p, .. } = &mut d.node_mut(l).unwrap().kind {
*p = preview;
}
let p = paint();
let mut cx = cx(&d, &s, &p);
let mut t = GradientTool::default();
cx.freeform_point = Some(2);
// The line starts from the existing point.
assert!(click(&mut t, &cx, 150.0, 180.0).is_empty());
t.pointer(&cx, &ev(PointerKind::Move, 206.0, 150.0));
assert!(t.claims_key(&cx, ToolKey::Escape), "on the stroke the line stays open (Preview {preview})");
if preview {
let add = Action::Exec("paint.freeform.addPoint".into(), json!({"at": [160.0, 150.0], "line": true, "stroke": false}));
assert_eq!(click(&mut t, &cx, 160.0, 150.0), vec![add]);
}
t.pointer(&cx, &ev(PointerKind::Move, 230.0, 150.0));
assert!(!t.claims_key(&cx, ToolKey::Escape), "past the stroke the line has ended (Preview {preview})");
}
}
/// In a clipping mask, the part of the object the mask hides is outside it: moving there ends
/// the line.
#[test]
fn the_part_a_mask_hides_is_off_the_object() {
use std::sync::Arc;
use vectorcraft_doc::{Appearance, Node, NodeKind};
let (d0, s0) = doc(FreeformMode::Lines);
let mut obj = d0.node(s0.objects[0]).unwrap().clone();
let mut d = Document::new(500.0, 500.0);
let l = d.layers[0].id;
let (group, clip, id) = (d.alloc_id(), d.alloc_id(), d.alloc_id());
obj.id = id;
let mask =
Node::path(clip, vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(100.0, 100.0, 160.0, 200.0)), Appearance::default_art());
d.insert(Some(l), 0, Node::new(group, NodeKind::Group { children: vec![Arc::new(mask), Arc::new(obj)], clip: true })).unwrap();
let mut s = Selection::default();
s.add(id);
let p = paint();
let mut cx = cx(&d, &s, &p);
cx.freeform_point = Some(2);
let mut t = GradientTool::default();
assert!(click(&mut t, &cx, 150.0, 180.0).is_empty());
t.pointer(&cx, &ev(PointerKind::Move, 130.0, 150.0));
assert!(t.claims_key(&cx, ToolKey::Escape), "inside the mask the line stays open");
t.pointer(&cx, &ev(PointerKind::Move, 185.0, 150.0));
assert!(!t.claims_key(&cx, ToolKey::Escape), "where the mask hides the object the line has ended");
}
/// Outline view, a layer with Preview off and Object Selection by Path Only don't shrink the
/// object to its path: a line started from a point stays open over the object's fill.
#[test]
fn the_fill_counts_in_outline_view_and_with_path_only_selection() {
let (mut d, s) = doc(FreeformMode::Lines);
let l = d.layers[0].id;
if let vectorcraft_doc::NodeKind::Layer { preview, .. } = &mut d.node_mut(l).unwrap().kind {
*preview = false;
}
let p = paint();
let mut cx = cx(&d, &s, &p);
(cx.outline, cx.path_only, cx.type_path_only) = (true, true, true);
cx.freeform_point = Some(2);
let mut t = GradientTool::default();
assert!(click(&mut t, &cx, 150.0, 180.0).is_empty());
t.pointer(&cx, &ev(PointerKind::Move, 140.0, 150.0));
assert!(t.claims_key(&cx, ToolKey::Escape), "over the fill the line stays open");
t.pointer(&cx, &ev(PointerKind::Move, 240.0, 150.0));
assert!(!t.claims_key(&cx, ToolKey::Escape), "off the object the line has ended");
}
/// A dropped click adds no point and leaves the line being drawn open: the next click still
/// joins it. A dropped drag of a point is canceled as by Escape.
#[test]
+7 -2
View File
@@ -145,7 +145,12 @@ impl Tool for LassoTool {
let poly = std::mem::take(&mut self.points);
let (add, sub) = (ev.mods.shift, ev.mods.alt);
if poly.len() < 3 {
return if add || sub { vec![] } else { vec![Action::Exec("select.none".into(), json!({}))] };
if add || sub {
return vec![];
}
// The click deselects everything, so no mesh point stays picked.
self.mesh.unfocus();
return vec![Action::Exec("select.none".into(), json!({}))];
}
vec![lasso_select(cx, &mut self.mesh, &poly, add, sub)]
}
@@ -165,7 +170,7 @@ impl Tool for LassoTool {
self.mesh.options()
}
/// Pick the gradient mesh points the Eyedropper held (`meshPoints`).
/// Pick the gradient mesh points the tool chosen before held (`meshPoints`).
fn set_option(&mut self, key: &str, value: &Value) {
if key == "meshPoints" {
self.mesh.set_options(value);
+1 -1
View File
@@ -515,7 +515,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi
- **Missing:** CJK vertical
composition (custom mojikumi sets and the Mojikumi Settings dialog, kinsoku settings #633, manual tate-chu-yoko), Middle Eastern
features beyond bidi, digit types, Character Direction and Kashidas (a split caret; the Middle Eastern & South Asian composers are done, #4935),
Touch Type, Retype beyond exact matches of available fonts (phase 1 is in, #4934, and the Retype panel lists the exactly matching fonts; near matches, installed fonts not yet loaded and text in images remain), Snap to Glyph; optional preservation of font sizes during group scaling (#1034 enhancement).
Touch Type, Retype beyond exact matches of available fonts (phase 1 is in, #4934, the Retype panel lists the exactly matching fonts, and `type.retype` takes near matches within a tolerance and words outlined as one compound path; glyphs fused into one contour, near matches in the panel's list, installed fonts not yet loaded and text in images remain), Snap to Glyph; optional preservation of font sizes during group scaling (#1034 enhancement).
Itemized in [type-parity.md](type-parity.md).
- **Impact:** professional typography and Japanese/Chinese publishing.
- **Estimate:** 34–47 h (type core 14–19 h blocks beta).
+71 -16
View File
@@ -2559,10 +2559,10 @@ control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script,
- `menuCommands.strings` lists the string literals the script passes to `executeMenuCommand`
(`app.executeMenuCommand('…')`), each with a count and its lines, and `menuCommands.dynamic` counts the calls
whose argument isn't a string literal.
- `outside` lists what the script does outside the document: `filesWritten` (with the open modes used),
`filesOpened` (files opened in other apps), `network`, `nativeCode`, `otherApps` (messages to other apps),
`environment` (environment variables), `unseenCode` (`eval`, `new Function` and `$.evalFile`) and
`preferences` (the reference app's preferences changed).
- `outside` lists what the script does outside the document: `filesWritten` (with the open modes used; setting a
File object's `length`, `hidden` or `readonly` counts too), `filesOpened` (files opened in other apps), `network`,
`nativeCode`, `otherApps` (messages to other apps), `environment` (environment variables), `unseenCode` (`eval`,
`new Function` and `$.evalFile`) and `preferences` (the reference app's preferences changed).
- `problems` lists what would stop the script loading as written (strings, comments, regular expressions,
template literals and XML literals that aren't closed, brackets that don't match, syntax newer than ES3 and
unknown directives) and notes on its text (bytes that aren't valid UTF-8, mixed line endings, and nesting deeper
@@ -3888,7 +3888,10 @@ already walks Image Trace. Short agent entry points:
art, where it is, snaps the art again after it is edited, and does not count
instances in `select.object.notAlignedToPixelGrid`; `alignToPixelGrid` alone with the value the symbol already has
adds no undo step),
`symbol.place {name?, x?, y?}`, `symbol.placeFromDocument {sourceDocument, name, x?, y?}` (an instance of a symbol
`symbol.place {name?, x?, y?}` (on top of the current layer; in Draw Behind directly below the bottommost selected
object, beside the compound path that holds it, or at the bottom of the current layer with nothing selected, above
a clipping path; `symbol.placeFromDocument` and `symbol.addFromLibrary` with `place` stack the instance the same
way), `symbol.placeFromDocument {sourceDocument, name, x?, y?}` (an instance of a symbol
of another open document, as a symbol dragged from that document's Symbols panel onto the canvas places it: the
symbol, the symbols it nests and the resources they use are added as `edit.dropSelection` adds them, in the same
undo step, and a symbol with the same name but other art or Symbol Options is added under a free name; an error
@@ -5150,7 +5153,7 @@ art", and a loaded file draws the source path, as it does for a solid past its l
documentation names the controls and their ranges
([3D and Materials panel options](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/3d-materials-panel-options.html)).
The settings are saved in the native file; SVG and PDF exports draw the shadow, and `effect.expandAppearance` keeps
it as a path. Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic) have no shadow. See [three-d.md](three-d.md#shadows).
a hard shadow as a path and turns a blurred one into an image. Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic) have no shadow. See [three-d.md](three-d.md#shadows).
```json
{"name":"run_command","arguments":{"command":"effect.setParams","params":{"index":0,"item":null,"params":{"shadow":true,"shadowPosition":"below","shadowDistance":10,"shadowBounds":150}}}}
@@ -5705,11 +5708,15 @@ fills and strokes above it paint over the members (characters), those below unde
`appearance.contents_index`. The `appearance.*`, `effect.*` and `graphicStyle.apply` commands edit the selected
objects themselves (a group's own stack; layers through `ids`) or, with `target: "contents"`, the objects inside the
groups and layers. In a Live Paint group those are its faces and edges, not its hidden source paths.
`appearance.addFill` adds a fill to the faces only, and `appearance.addStroke` adds a stroke to the edges only; a selected group left with only its hidden source paths is returned without a change. A
`appearance.addFill` adds a fill to the faces only, and `appearance.addStroke` adds a stroke to the edges only. On a
selected group left with only its hidden source paths, either command changes nothing. A
fill or stroke command with an `item` and `target: "contents"` (such as `paint.setFill`, `stroke.set`,
`paint.invert`, `paint.setGradientGeom` and `object.setOverprint`) changes the faces for a fill row and the edges for
a stroke row. The row commands (`appearance.setItem`, `appearance.removeItem` and the others) find their rows on each
face and edge as on any other object in the contents.
face and edge as on any other object in the contents. `graphicStyle.apply` gives each face only the style's fills and
each edge only its strokes, with or without `add`, and links neither to the style. `appearance.clear` leaves a face
one empty fill and an edge one empty stroke, and `appearance.reduceToBasic` keeps only a face's fill and only an
edge's stroke.
`appearance.targetContents` selects a group's members (double-clicking the Contents row).
SVG and PDF export bake a group's own fills, strokes and geometry effects into paths; its raster effects stay a
filter on the whole group in SVG and become an image of the whole group in PDF.
@@ -6221,7 +6228,8 @@ Each Effect › Pathfinder effect (`pathfinder.add` … `pathfinder.softMix`, no
in its params: `precision` (a number, 0.001–10 pt), `removeRedundantPoints` and `removeUnpainted` (true or false), which
mean what they mean for the panel's operations; the other operations ignore `removeUnpainted`. With `removeUnpainted`
on, a compound shape's area counts as filled when the shape has a visible fill of its own, and Divide keeps every piece
when the group or compound shape has one. Outline strokes a compound shape's area in the shape's own fill. `effect.apply`
when the group or compound shape has one. Outline strokes a compound shape's area in the shape's own fill, and gives
the edges no paint when the shape has no fill (the shape's own strokes still draw over the result). `effect.apply`
fills the ones `params` leave out from the current Pathfinder Options, and the values join its journal entry. An effect
saved without them evaluates with precision 0.01 and both switches off, as before effects kept them. `effect.setParams
{index, params: {precision?, removeRedundantPoints?, removeUnpainted?}}` edits them as one undo step; values the
@@ -9139,7 +9147,8 @@ undo step. When a matched layer, or a layer around it, is hidden or locked, the
Drawing modes (`view.drawMode`) apply
too: in Draw Inside, `edit.paste`, `edit.pasteInPlace` and `edit.pasteOnAllArtboards` put the objects inside the
object drawn into (its clip group, made on the first paste), whatever Paste Remembers Layers says; in Draw Behind,
`edit.pasteInPlace` and `edit.pasteOnAllArtboards` put them just below the selection. `edit.pasteInFront` and
`edit.pasteInPlace` and `edit.pasteOnAllArtboards` put them just below the selection, and a placed symbol instance
(`symbol.place`) goes just below the selection too. `edit.pasteInFront` and
`edit.pasteInBack` ignore the drawing mode. When the object drawn into is the one isolation mode isolates (`object.isolate`,
or a double-click on it with the Selection tool), art drawn or pasted inside it takes isolation mode into its clip group,
so the new art can be picked and isn't dimmed; `edit.undo` or `edit.redo` that removes the isolated object ends
@@ -11429,6 +11438,47 @@ hidden state and stay live on the group; none of them is copied onto the glyph p
glyph.
`object.expand` outlines type with this command, so Fill and Stroke expand those paths' gradients, patterns and strokes.
`type.retype` (Type › Retype) turns outlined glyphs back into point text. By default a shape must be exactly a glyph of
an available font. With `tolerance` (0 to 0.05), a shape of at most 8 contours that is no glyph exactly becomes the
glyph it is closest to when its leftover distance from that glyph, relative to the shape's outline spread (the root
mean square distance of its sampled outline points from their center), is at most the
tolerance: an outline simplified, a curve split in two, or contours in another order, start or direction. The tolerance
and this measure are VectorCraft's own. A near-matched glyph may differ from its line by the tolerance in size, turn
and place; an exact glyph keeps the exact limits unless the line's first glyph, whose size and turn the line takes, is
a near match. The line also splits before a near-matched glyph, or a glyph of a line whose first glyph is one, that
the type would draw further from its shape than the tolerance by the same measure (its own leftover distance together
with the change of size and turn) or with its center further away than its origin may be. Each entry of `fonts` in the result has a `score`, from 1 when every glyph of the line is exact down to 0
at a leftover distance of 0.05. A compound path that holds several
glyphs, such as a word made into one compound path, is split into groups of contours (a contour with the contours
inside it) in path order, and runs of up to three groups are matched, the longest first among those after which the
remaining groups can still all be matched, so an i's stem and dot become one i. A group whose contours run the other
way round, as Make Compound Path leaves some of them, still matches exactly. Exact matches of the whole shape come
first, then exact matches of its groups, then near matches of the whole shape, then near matches of its groups. The
compound becomes type only when every one of its glyphs does; otherwise it stays as it is and is reported once in
`unmatched` when another shape of the selection becomes type, and the command returns an error when no shape does. A
glyph also has to paint the area the shape paints under the shape's fill rule: a compound filled by the nonzero rule
whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it. A shape with a counter narrower than three times the
outline tolerance across in some direction, turned or not, cannot be checked this way and stays an outline: at `tolerance` 0.05, a
counter 10 units wide in a 100 by 100 shape, or a 60 by 10 one turned 45 degrees. So does a shape whose outline is too large to check. The glyphs of a compound path that splits into several are set one beside
another, so a split whose parts overlap where the shape's fill rule leaves the overlap unpainted (two o's on each
other under the even-odd rule) stays an outline. A split whose parts overlap at all also stays an outline when the
compound has an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke, since the
glyphs may become separate objects that paint the overlap twice. When the split with the longest runs fails that check, the split with the
shortest runs is checked, then the other complete splits in order, up to 32 splits per shape for exact matches and 32
for near matches; when none passes, the shape stays an outline. Glyphs fused into one contour are not split, and a compound path of more than 256 groups, 512 contours
or 65,536 path elements is matched whole only. One command groups at most 16,384 contours, in selection order; the shapes after them are
matched whole only. Near matching compares a shape with at most the 256 glyphs closest to it in proportion, in at
most 50 million point comparisons per shape and 2 billion per command, ranking a glyph by proportion counting as one
comparison per contour and one more; past them, the glyphs not yet ranked or compared are left out. It looks glyphs up for at most 1,024 distinct shapes and runs per command: every selected shape first, in
selection order, then the runs of groups of the compound paths. Glyphs close only to the shapes and runs past that
limit are not looked up. At most 262,144 glyphs are drawn to check whether they could near match, and at most 32,768
are indexed for it, each face taking an equal share of both; of a face's glyphs, those closest to the selected shapes
in proportion are indexed.
```json
{"name":"run_command","arguments":{"command":"type.retype","params":{"tolerance":0.02}}}
```
`type.createOutlines` (Type › Create Outlines) and `effect.expandAppearance` (when it outlines type, as Expand
Appearance describes) take an outlined frame of threaded text out of its thread with the text it shows, and the other
frames keep the text they hold. When the thread's last frame is outlined, the text it has no room for, which its
@@ -12585,7 +12635,7 @@ on an open path that are not drawn because they fall before the path's start can
## Retype tracking
`type.retype {fonts?}` turns selected outlined text back into point text when its shapes are glyphs of a font the app
has. A line of three or more glyphs gets the spacing that most of its gaps share as its tracking, in 1/1000 em. Retype
has. A line of three or more exactly matched glyphs (none a near match, see `tolerance`) gets the spacing that most of its gaps share as its tracking, in 1/1000 em. Retype
tries the value rounded to a whole number first when it is within 0.05 of one, then the value as measured. The font's
advances and pair kerning are left out of the measure, and word spaces are counted after the tracking. The tracking is
kept when the tracked type draws the whole line in place, or more of it from its start than untracked type does. When
@@ -12605,7 +12655,7 @@ tracking their own gaps give. These rules are VectorCraft's own. Each entry of t
## Retype several lines
`type.retype` joins lines that follow each other in paint order, with the same group, paint, font, size, turn and
`type.retype` joins lines that follow each other in paint order (lines split from one compound path do), with the same group, paint, font, size, turn and
tracking (an untracked line of one or two glyphs takes the tracking of the others), into one type object when each
line's baseline is the same distance below the one before (between 0.25 and 3 times the size) and the lines line up at their starts, ends or centers. The object is area type with Convert To Area
Type's frame, its lines separated by line breaks, with left, right or center alignment, checked in that order. Its
@@ -12627,7 +12677,8 @@ the result's `texts` list holds an object's lines joined by `\n`, and each entry
`type.retypeFonts {count?}` lists the fonts whose glyphs match the selected outlined text. It compares each selected path
and compound path, inside groups too, with the glyphs of up to 96 loaded fonts, those of the document's live type
first, by the matching `type.retype` uses, and it counts only exact matches. When two versions of a font are loaded,
first, by the matching `type.retype` uses, and it counts only exact matches of whole shapes: it does not split a
compound path into glyphs or take near matches. When two versions of a font are loaded,
only the version its family and style name gives is compared, which is the version that choosing the font sets. The
fonts rank by how many shapes each matches, then by the mean distance left after fitting, then by family and style
name. `count` is a whole number from 1 to 96 (default 10); any other value is an error. The reply is
@@ -13219,7 +13270,8 @@ session and refuses `--connect`. In Safe Mode no plug-in loads or
runs: `plugin.install`, `plugin.run`, `plugin.reload` and exporters return an error, and a live-effect plug-in draws its
object's geometry unchanged while the object keeps the effect: `effect.list` gives that effect `skipped: true`, and the
Appearance panel shows "(Safe Mode)" after its name and the plug-in's id in its tooltip. `effect.expandAppearance` returns an
error and changes nothing when an object it would expand holds such an effect, in it or in a symbol it places. `vectorcraft` rejects an option it does not know (such as
error and changes nothing when an object it would expand holds such an effect, in it or in a symbol it places. That includes a
plain symbol instance in a group or layer with a raster effect, since the group's image draws the symbol's art. `vectorcraft` rejects an option it does not know (such as
`--safe-mod`) instead of opening it as a file; `--` before a file name that starts with `-` opens it. The web build keeps
no installed plug-ins from one page load to the next and has no launch marker, so it never offers the choice. `plugin.safeMode` returns `{active, source, disabled,
pendingItem}`; a command does not turn Safe Mode on or off. `plugin.setEnabled {id | file, enabled}` turns a plug-in on or
@@ -14198,8 +14250,11 @@ away); its click on a gradient mesh's line picks the line's two
ends, and a click inside a patch picks the four points around it. The picked points show filled. Dragging one of them
moves them all as one undo step (`object.mesh.movePoints`), a click on one of several picked points picks it alone,
and the arrow keys nudge them by the keyboard increment. The active tool lists them in its options
(`tool.setOption {}` returns them as `meshPoints: [{id, index}…]`). Switching to the Eyedropper keeps them picked, its
options list them too, and the Mesh tool, Direct Selection or a Lasso chosen next picks them again. While a selected, editable mesh has
(`tool.setOption {}` returns them as `meshPoints: [{id, index}…]`). Switching between the Mesh tool, Direct Selection,
the Lasso, the Polygonal Lasso and the Eyedropper keeps them picked, and so does a Cmd/Ctrl-click with the selection
tool one of them lends; any other tool, Group Selection included, drops them. A plain Lasso click away from the art
(`select.none`) unpicks them. The Eyedropper's options list them too.
While a selected, editable mesh has
points picked, an Eyedropper click or Shift-click on an image or other art samples the color under the pointer into
those points alone as `paint.sampleColor {color, stroke: false, ids}` with the meshes that have points picked: one undo
step, none when the color is unchanged. Other selected objects keep their paint. A click on one of those meshes, and
+12 -5
View File
@@ -1071,6 +1071,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Headless CLI (`vectorcraft-cli run`, `convert`, `info`, `bench`, `perf`, `mcp`). A `run` step, like a `command_batch` step over MCP, can use an earlier step's result (`"$1.id"`, #785); `run --commands FILE` (or `-` for standard input) reads the steps from a JSON array or JSON Lines, past the Windows command-line limit (#3147, `apps/vectorcraft-cli/tests/it/cli.rs` `run_reads_*`, `run_refuses_malformed_commands_naming_the_step`).
- File › Scripts › Check Script… reads a script written for Illustrator (`.jsx`, `.jsxinc` or a compiled `.jsxbin`) without running any of it and reports what it needs (the document model, files, dialogs, menu commands, features only Illustrator has), what it would do outside the document, the menu commands and document-model members it uses, its directives and included files, and the problems that would stop it loading (`script.check`, which also reads `.js` files); File › Open and drag-and-drop show the report for `.jsx`, `.jsxinc` and `.jsxbin` files.
- Check Script reads names by the same identifier rule as `vectorcraft-js`: Unicode 17.0 `ID_Start` characters, `$` and `_` start a name, and `ID_Continue` characters and `$` continue it (https://www.unicode.org/reports/tr31/, https://tc39.es/ecma262/#sec-names-and-keywords). U+2118, U+203F, U+00B7 and the zero width non-joiner and joiner are name characters, and U+00B2 and U+2E2F are not. Of the characters Unicode 17.0 assigned, U+088F starts a name and U+1ACF may follow its first character. A `\uXXXX` escape is read as its character only where a name may hold it, so `\u0030abc` does not become a name that starts with a digit; a `\u{…}` escape takes any number of hexadecimal digits up to U+10FFFF, and one that is empty, unclosed, out of range or a surrogate is not part of a name. Each `\u{…}` escape read in a name is reported as syntax newer than ES3, which has only the four-digit form (https://ecma-international.org/wp-content/uploads/ECMA-262_3rd_edition_december_1999.pdf, section 7.6). A private name may start with an escape (`this.#\u{61}pp` is the private name `#app`), and a private name at the start of a line inside braces is not read as a directive unless its name is a directive's. Tests: `crates/scriptcheck/src/tests.rs` (`names_are_made_of_the_unicode_identifier_characters`, `an_escape_stands_for_a_character_only_where_a_name_may_hold_it`, `braced_escapes_in_names_are_read_by_their_value`, `braced_name_escape_reports_later_syntax_and_member`, `private_names_with_escaped_starts_are_single_tokens`, `private_name_at_line_start_is_not_a_directive`), `crates/engine/tests/it/js_lexer_vs_scriptcheck.rs` (`both_lexers_take_the_same_characters_into_names`).
- Check Script reports `file.write` and `filesWritten` when a script sets a File object's `length`, `hidden` or `readonly` (https://extendscript.docsforadobe.dev/file-system-access/file-object/), by plain or compound assignment, `++` or `--`, or the name as a string literal in brackets. A test lists every global and member the script host adds to the JavaScript engine, except VectorCraft's own `vc` and its members, and fails when one has no row; for each one that reaches outside the document it checks that `script.check` reports the expected `outside` id, and it checks that the checker lists every directive the host reads. Tests: `crates/scriptcheck/src/tests.rs` (`setting_a_files_length_or_flags_writes_it`), `crates/engine/tests/it/script_host_vs_scriptcheck.rs` (`every_name_the_host_adds_has_a_row`, `every_name_that_reaches_outside_has_its_checker_id`, `the_checker_lists_every_directive_the_host_reads`).
- `vectorcraft-js` parses JavaScript as ECMAScript 5.1 defines it, with the legacy octal forms, block functions and lenient regular expressions of Annex B, into a syntax tree with source spans; it reads the `#target`, `#include` and other preprocessor lines as directives without running them, and a script that breaks the grammar or an early-error rule gives a `SyntaxError` with its line and column. Nesting past the parser's depth limit (`Options::max_depth`, 200 by default) gives a `SyntaxError` instead of exhausting the stack. `cargo xtask test262` fetches the conformance suite at a pinned commit and parses its ES5 tests: 5,411 of 5,418 runs pass (the 7 others use `let` and `const`). This entry covers parsing; the next entry covers running scripts. Tests: `crates/js/src/tests.rs`, `crates/engine/tests/it/js_lexer_vs_scriptcheck.rs`.
- `vectorcraft-js` identifiers, written out or as `\uXXXX` and `\u{...}` escapes, take the characters Unicode's `ID_Start` and `ID_Continue` properties allow (https://www.unicode.org/reports/tr31/), plus `$` and, at the start, `_`, as later ECMAScript editions define them (https://tc39.es/ecma262/#sec-names-and-keywords). `Other_ID_Start` characters such as U+2118 and `Other_ID_Continue` characters such as U+00B7 and the zero width non-joiner and joiner are accepted, and no `Pattern_Syntax` or `Pattern_White_Space` character is. Letter categories come from Unicode 17.0, so U+088F starts an identifier and U+1ACF may follow its first character; characters assigned after Unicode 17.0 are not yet identifier characters. Tests: `crates/js/src/tests.rs` (`identifier_characters_are_unicode_17_id_start_and_id_continue`, which checks every code point, `identifiers_take_the_characters_unicode_17_assigned`, `identifiers_take_the_other_id_start_and_continue_characters`, `identifiers_refuse_pattern_syntax_surrogates_and_bad_escapes`, `no_pattern_syntax_or_white_space_character_is_an_identifier_character`).
- `vectorcraft-js`'s `Realm` runs ECMAScript 5.1 scripts: the parsed script compiles to verified bytecode that a non-recursive interpreter runs, with closures, `this`, `arguments`, `with`, direct and indirect `eval`, `new Function`, `try`/`catch`/`finally`, labeled `break` and `continue`, and `for`-`in` in insertion order, over a mark-and-sweep heap, with the built-ins the next two entries list. Every run is bounded by fuel, heap bytes, frames, nested host calls and an interrupt flag (smaller defaults in the wasm build), and a run that reaches a limit stops with a limit error that `try` cannot catch. `cargo xtask test262` also runs the suite's ES5 language tests that need only the built-ins present: 4,280 of 4,286 runs pass (4 of the others expect the completion values of later editions, and 2 expect a configurable function `length`). The app does not call it yet. Tests: `crates/js/src/interp_tests.rs`, `crates/js/tests/test262.rs`.
@@ -1423,7 +1424,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- **Compound paths:** Make keeps the backmost object's appearance and each contour; selecting a member in Direct Selection reads and changes the compound's fill rule in Attributes. Direction remains a per-member edit. Rendered holes, unchanged contour geometry, no-op history and Undo/Redo are covered by `engine/tests/it/compound_attributes.rs` (#1197). Behaviour reference: [public compound-path documentation](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/create-compound-paths.html). Make Compound Path on a group (such as outlined type) keeps the paint of its backmost path instead of drawing nothing, and compound paths joined into one keep their holes (#1537).
- **Saved selections:** Select ▸ Save Selection… asks for a name and keeps the selection in the document (saved with the file, undoable, up to 25); each one is listed at the bottom of the Select menu and a click selects its objects again; Edit Selection… lists them to rename or delete, applied together on OK. A file's saved selections are capped and checked against its objects when it opens.
Select ▸ Update Selection replaces the objects of the saved selection last recalled with the selected objects, in one undo step that marks the document changed (`select.update`). After Edit Selection… renames that saved selection, Update Selection replaces it under the new name; after Edit Selection… deletes it, Update Selection is disabled until another saved selection is recalled or the delete is undone. Undo and Redo do not change which saved selection is recalled.
- **Drawing modes:** in Draw Inside, a double-click with a selection tool outside the object being drawn into sets the drawing mode to Draw Normal, as Shift+D does. Pastes follow the drawing mode ([drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) (#3705): in Draw Inside, Paste, Paste in Place and Paste on All Artboards put the copies inside the object drawn into, in one undo step, Paste Remembers Layers aside; in Draw Behind, Paste in Place and Paste on All Artboards put them just below the selection; Paste in Front and Paste in Back ignore the mode. Shift+D cycles Draw Normal → Draw Behind → Draw Inside → Draw Normal, skipping Draw Inside unless one path, compound path or type is selected. With the object drawn into isolated (a double-click on it with the Selection tool), art drawn or pasted inside it takes isolation mode into its clip group, so it can be clicked and isn't dimmed, as art added in isolation mode belongs with what is isolated ([isolation mode](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html)) (#3705); undo or redo that removes the isolated object ends isolation mode. While Draw Inside lasts, a dotted open rectangle marks the corners of the object drawn into (#4319). In Draw Behind, New Layer (the Layers panel's button, its menu, Ctrl/Cmd+L and the Layer Options dialog) puts the new layer directly below the current layer, at its level, as [the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=234) describes and [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) lists; Ctrl/Cmd-click still puts it on top and Ctrl/Cmd+Alt-click below, and New Sublayer is not affected (VectorCraft's own rule).
- **Drawing modes:** in Draw Inside, a double-click with a selection tool outside the object being drawn into sets the drawing mode to Draw Normal, as Shift+D does. Pastes follow the drawing mode ([drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) (#3705): in Draw Inside, Paste, Paste in Place and Paste on All Artboards put the copies inside the object drawn into, in one undo step, Paste Remembers Layers aside; in Draw Behind, Paste in Place and Paste on All Artboards put them just below the selection; Paste in Front and Paste in Back ignore the mode. Shift+D cycles Draw Normal → Draw Behind → Draw Inside → Draw Normal, skipping Draw Inside unless one path, compound path or type is selected. With the object drawn into isolated (a double-click on it with the Selection tool), art drawn or pasted inside it takes isolation mode into its clip group, so it can be clicked and isn't dimmed, as art added in isolation mode belongs with what is isolated ([isolation mode](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html)) (#3705); undo or redo that removes the isolated object ends isolation mode. While Draw Inside lasts, a dotted open rectangle marks the corners of the object drawn into (#4319). In Draw Behind, New Layer (the Layers panel's button, its menu, Ctrl/Cmd+L and the Layer Options dialog) puts the new layer directly below the current layer, at its level, as [the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=234) describes and [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) lists; Ctrl/Cmd-click still puts it on top and Ctrl/Cmd+Alt-click below, and New Sublayer is not affected (VectorCraft's own rule). In Draw Behind, a placed symbol instance (Place Symbol Instance in the Symbols panel, and a symbol dragged onto the canvas from the Symbols panel or a symbol library) goes directly below the selected object, or at the bottom of the current layer with nothing selected, as [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) describes for placing symbols; below the bottommost of several selected objects, beside the compound path that holds a selected path, and above a clipping path are VectorCraft's own rules. Draw Normal and Draw Inside keep it on top of the current layer.
- **Drawing:** Pen, Curvature, anchor tools, Pencil, Paintbrush, Blob Brush, Smooth, Path Eraser, Join. Direction handles dragged with Direct Selection or the Anchor Point tool snap to smart guides, and Shift keeps them at 45° steps from their anchor. The Pen continues any open path from the end clicked, and while drawing, a click on an end of another open path joins the two into one (#776). The Curvature tool edits any selected path, whatever drew it, keeping its shape except where edited (#798): a click on a point makes it current and a drag moves it, re-curving only its two segments; double-click, or Alt-click on any point but an end of an open path, toggles it smooth or corner and Delete removes it; a click on a segment adds a point without changing the shape; with an end of an open path current, clicks go on from it and its other end closes it (`path.curvatureEdit`). An Alt-click on an end of a selected open path makes that end current without changing it, so the next click goes on from it, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-shapes-with-the-curvature-tool.html) describes for continuing a path; an Alt-click that starts a new path places a corner point, as later Alt-clicks do. Every point a drawing tool places snaps to Smart Guides through one snapper (#506): the Pen's and Curvature tool's anchors, the Pencil's ends, the shape tools' start and dragged corner or radius (Rectangle, Rounded Rectangle, Ellipse, Polygon, Star, Line Segment, Arc, Spiral, the grids), the Type tool's click and frame, a new artboard's corners. A filled Pencil path keeps a stroke of None (#1804, part of #1679). While a Pencil or Paintbrush stroke is drawn back to within Close Paths When Ends Are Within of its start, the cursor shows the closing ring and a release there closes the path, as [Draw straight lines with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-straight-lines-with-the-pencil-tool.html) describes for the Pencil. The [ and ] keys reach the Blob Brush, the Eraser and the Symbolism tools in the app (#1734, part of #1661).
Blob Brush and Eraser Tool Options' Size is Fixed or Pressure with a Variation (#4590, #3961): with Pressure a pen stroke is Size − Variation wide where it presses lightest and Size + Variation where it presses hardest, and a mouse stroke keeps the Size.
`path.blob` and `path.eraseRegion` refuse a Size outside 0.1 to 1000 pt and a Variation outside 0 to 1000 pt, also with Size set to Fixed, and the drawing commands that read pen values refuse a pressure outside 0 to 1, a tilt outside −90° to 90°, a rotation outside 0° to 360° and a point array of more than six numbers, with an error naming the key; the document, the selection and the undo history stay as they were. The pressure and tilt ranges are those of [Pointer Events](https://www.w3.org/TR/pointerevents3/); the Size, Variation and rotation ranges are VectorCraft's own values (`tests::draw2::pen_values_outside_their_ranges_are_refused`).
@@ -1590,7 +1591,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
A modal window that opens without a press in the window (a dialog opened from the macOS menu bar or by an automation command, the About window, a file dialog, the update prompt, or the progress window of a plug-in, trace or open run) closes the Command Palette, a tool group's flyout, the All Tools drawer and any open menu or popup in the pass it opens. While such a window is open, the palette stays closed, so opening it from the macOS menu bar or by an automation command does not take the keyboard from the window; it opens again once the window closes (`palette` tests `a_dialog_opened_from_the_system_menu_closes_the_palette`, `the_about_window_closes_the_palette`, `a_progress_window_closes_the_palette`, `the_palette_opened_over_a_dialog_closes`, `a_click_on_the_menu_bar_closes_the_palette_before_a_dialog_opens`, `a_dialog_opened_without_a_press_closes_a_flyout`, `a_dialog_opened_without_a_press_closes_the_tools_drawer`, `a_dialog_opened_without_a_press_closes_a_menu`, `the_palette_opened_as_a_dialog_closes_stays_open_until_the_next_dialog`).
The Command Palette ranks its results by how well they match. A query that is a result's id lists that result first (`view.goto1` lists Saved View 1 above Saved View 10); then come results whose name is the query, results whose name without its menu path starts with it, and results whose initials it is ("ea" finds Export As…). Within each of those, a result where every word of the query is a whole word of its name ranks above one where a word only starts a word of the name, then one where it is a word of the menu that holds it, then of its id, then text inside a word, so a query that is a menu's title ("object") lists results named with that word above the items of that menu. A tool ranks above a menu command, panel, effect or filter plug-in that matches as well, so "rect" lists the Rectangle Tool above Effect › Convert to Shape › Rectangle…, and of two results of the same kind the shorter name comes first. Words of the menu bar item that runs a result also find it, the item's own label included ("exit" finds Quit VectorCraft, which File › Exit runs); with the native macOS menu bar, the items that bar moves into its application menu are found under it (Preferences… under Settings). Every result the earlier search found is still found, and the highlight stays on its result when a plug-in is installed, a shortcut changes or the language changes while the palette is open (`palette::search` tests `a_better_word_grade_ranks_first`, `a_better_whole_query_tier_ranks_first`, `kind_and_length_never_lift_a_worse_grade`, `a_menu_title_does_not_lift_its_items`, `common_queries_list_the_command_near_the_top`, `every_result_is_found_first_by_its_name_and_its_id`, `every_result_found_before_is_still_found_and_shown`, `results_know_their_place_in_the_menu_bar`, `native_homes_follow_the_native_application_menu`; `palette` test `the_highlight_stays_on_its_result_when_the_results_change`).
A Command Palette query word in an English plural or verb form finds a result whose English name or menu path holds the base word: "rounded corners" lists Effect › Stylize › Round Corners… first, and "scaling" finds Object › Transform › Scale…. The search drops `'s`; `es` after `s`, `x`, `z`, `ch` or `sh` (also trying the word with only its `s` dropped, so "rasterizes" finds Rasterize…); a final `s` in words of more than 3 letters, except after `ss`, `us` or `is`; `ing` in words of more than 5 letters and `ed` in words of more than 4. After `ing` or `ed`, a doubled `b`, `d`, `g`, `m`, `n`, `p`, `r` or `t` is tried both single and doubled, the single letter only when at least 3 letters are left ("cutting" meets Cut, "added" meets Add); otherwise the word is also tried with an `e` ("scaling" meets Scale…). It turns `ies` into `y` or `ie` in words of more than 5 letters and `sses` into `ss`, and leaves `series` and `species` as they are. Among results that the whole query matches the same way (as an id, as a label, at the start of a label, as initials, or none of these), a result whose name holds the base word of a query word ranks below one that holds the query word whole and above one where the query word only starts a word of the name, so "scale zz" lists a name with "Zz Scaling" above one with "Zz Scalers". "scale" alone still lists "Scalers" above "Scaling", because "Scalers" starts with the query. A partly typed word that is not itself a word of any result ("scal") does not meet a base word. Names shown in other languages and ids are not changed this way, and every result found before is still found (`palette::search` tests `plurals_and_verb_forms_meet_their_base_word`, `a_plural_or_verb_form_finds_the_result`, `a_better_word_grade_ranks_first`, `a_partly_typed_word_does_not_lift_a_verb_form`, `a_whole_query_tier_comes_before_a_stem_form`, `results_matched_without_a_stem_keep_their_order`).
A Command Palette query word with a typo still finds the result: "gruop" lists Object › Group first, and "eyedroper", "rectange" and "elipse" list the same first results as the words spelled right, the Eyedropper, Rectangle and Ellipse tools among them. When a query word of 4 or more letters is not a word, a base word or the start of a word of any result's name, menu path or id, the search compares it (also when another result matches it through a word with the same meaning, so "spin" finds Span as well as Rotate) with the words of result names and menu paths, and a word 1 edit away (2 for a query word of 8 or more letters) matches; a letter added, left out or changed, or two letters next to each other swapped, is one edit. A query word meets at most the 32 nearest such words. Results matched through a typo come after every result the query matches in its name, menu path or id without one, and before every result the query matches only through its description; among them the query is read with the misspelled word replaced by the word it meets, so they come in the order the word spelled right gives; then a result whose label holds the word comes before one whose menu path holds it. Ids, and query words and result words with Chinese, Japanese or Korean letters, are not compared this way, and matching through a typo does not change the order of the results matched without one (`palette::search` tests `edits_are_counted_up_to_a_bound`, `a_word_with_a_typo_finds_the_result`, `a_typo_meets_at_most_32_words`, `a_word_with_the_same_meaning_elsewhere_still_finds_a_typo`, `a_description_match_ranks_below_a_typo`, `misspelled_words_find_the_command`).
A Command Palette query word with a typo still finds the result: "gruop" lists Object › Group first, and "eyedroper", "rectange" and "elipse" list the same first results as the words spelled right, the Eyedropper, Rectangle and Ellipse tools among them. When a query word of 4 or more letters is not a word, a base word or the start of a word of any result's name, menu path or id, the search compares it (also when another result matches it through a word with the same meaning, so "spin" finds Span as well as Rotate) with the words of result names and menu paths, and a word 1 edit away (2 for a query word of 8 or more letters) matches; a letter added, left out or changed, or two letters next to each other swapped, is one edit. A query word meets at most the 32 nearest such words. Results matched through a typo come after every result the query matches in its name, menu path or id without one, and before every result the query matches only through its description; among them, how the whole query matches is judged with the misspelled word replaced by the word it meets. Results that match it equally then come in this order: a result whose label holds every word matched through a typo before one whose menu path holds such a word, then by the grades of the other words and how many such words the menu path holds, and after that as every other result is ordered, so two such results can come in a different order than the words spelled right give them. With two words matched through typos, a result whose label holds one and whose menu path holds the other ties on these grades with a result that holds them the other way round. Ids, and query words and result words with Chinese, Japanese or Korean letters, are not compared this way, and matching through a typo does not change the order of the results matched without one (`palette::search` tests `edits_are_counted_up_to_a_bound`, `a_word_with_a_typo_finds_the_result`, `a_typo_meets_at_most_32_words`, `a_word_with_the_same_meaning_elsewhere_still_finds_a_typo`, `a_description_match_ranks_below_a_typo`, `misspelled_words_find_the_command`).
A Command Palette query word also finds a result whose name or menu path holds a word with the same meaning: "remove bg" lists Remove Background… first, "outline text" lists Type › Create Outlines first, and "flip", "combine", "vectorize" and "colour" list Reflect…, Unite, an Image Trace command and the Color panel among the first 3 results. The words come from VectorCraft's own table of 21 groups of English words (`palette/words.rs`, at most 60 groups of at most 6 words); a word that is the whole label of another command, such as Merge or Mirror, is in no group, and neither is Insert. A word or its English base word that is in a group meets the other words of its group in labels and menu paths, and their base words, but not ids or word starts. A result whose label holds the word itself ranks above one whose label holds a word with the same meaning, which ranks above one whose menu path holds the word, so "type" now lists Scale Text Attributes above Type › Orientation › Vertical. A catalog may add a group's words in its language with a row in the `search` context (the group's English words joined by ", ", then that language's words), used while that language is the UI language; no catalog has to have these rows (`palette::search` tests `a_word_with_the_same_meaning_finds_the_result`, `a_catalog_row_adds_words_to_a_group`, `words_with_the_same_meaning_find_the_command`; `palette::words` tests; `i18n` test `search_rows_name_a_group_and_add_single_words`).
The Command Palette ranks the commands listed in Recent Commands first among the results that match a query as well as they do and have the same use grade (described below), the most recent first, and below every result that matches it better: after a pick of Effect › Convert to Shape › Rectangle…, "rect" lists it above the Rectangle Tool unless the Rectangle Tool has the higher use grade, so Enter runs it again. A recent pick ranks after the whole-query match, the word grades, the matches through a typo, a description or a word with the same meaning, and the use grade, and before the kind of result and the name's length. The ranking uses the list Recent Commands shows. This is VectorCraft's own behavior (`palette::search` test `a_recent_pick_ranks_first_within_its_grades`; `palette` tests `a_recent_pick_ranks_first_among_results_that_match_as_well`, `the_kept_ranking_follows_the_recent_picks`).
The Command Palette also counts how many times each command is picked and ranks the commands picked most often first among the results that match a query as well as they do, also after they leave Recent Commands, and below every result that matches it better. A pick is counted only when Recent Commands records it, so a refused pick and a pick of Search Commands… are not counted. Counts are compared in grades that double: grade 1 starts at 1 pick, grade 2 at 3, grade 3 at 7, and so on up to grade 9, and a command picked once ranks above the commands never picked. The grade ranks after the word grades and the typo, description and same-meaning matches, and before the place among the recent picks. The count is kept for at most 200 commands: a new command then removes, of the half of the commands picked longest ago, the one with the fewest picks, of those the one picked longest ago. When a count reaches 1,000, every count is halved and commands left at 0 are dropped. The counts are saved with the other interface settings (`command_uses` in `ui.json`); a count above 999 loads as 999 and an unreadable entry is dropped. The web build keeps them for the session. This is VectorCraft's own behavior (`palette::search` test `a_command_picked_often_ranks_first_within_its_grades`; `palette` tests `a_command_picked_often_ranks_first_among_results_that_match_as_well`, `the_kept_ranking_follows_the_pick_counts`, `a_count_does_not_pass_a_better_match`, `pick_counts_rank_in_grades_that_double`, `the_201st_command_removes_the_least_used_and_keeps_itself`, `new_commands_build_up_counts_when_every_counted_one_has_more_picks`, `counts_are_halved_at_one_thousand`, `saved_pick_counts_load_what_is_readable`, `only_a_pick_recorded_in_recent_commands_is_counted`).
@@ -1907,6 +1908,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- **Several mesh points at once (#4207, #4208, #4170):** the Mesh tool and Direct Selection pick several points of a gradient mesh or mesh envelope: Shift-click adds a point or takes a picked one away, Direct Selection's marquee picks the points inside it (Shift toggles them) and selects their meshes, and its click on a mesh line picks the line's two ends and one inside a patch the four points around it. The picked points show filled; dragging one moves them all as one undo step and the arrow keys nudge them (`object.mesh.movePoints {id, points, dx, dy}` or `{items, dx, dy}`), and a click on one of several picked points picks it alone. A solid fill colour (`paint.setFill`: Color panel, Swatches, Eyedropper) recolours every picked point, and the Transparency panel's Opacity fades them instead of the object, the panel showing their opacity (blank when it differs); `object.mesh.setPointColor` takes `points` or `items`. Public reference: [Edit mesh objects](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-meshes/edit-mesh-objects.html) (Shift selects multiple mesh points; a fill colour colours the selected point), [Macworld, gradient mesh](https://www.macworld.com/article/202693/gmesh2.html) (Direct Selection: a mesh line selects the points at both ends, a patch the points around it, Shift-click adds or removes points), [Peachpit](https://www.peachpit.com/articles/article.aspx?p=1638270) (each mesh point can have its own colour or transparency). Tests: `shift_clicks_pick_mesh_points_that_drag_and_nudge_together` and `direct_selection_picks_mesh_points_by_marquee_line_and_patch` in `crates/tools/src/meshedit.rs`, `picked_mesh_points_take_the_fill_opacity_and_drag_together` in `crates/engine/src/tests/editcolors.rs`, `mesh_points_move_and_colour_together` in `crates/engine/src/tests/live.rs`. Scores and hours unchanged.
- **Picked mesh points in the panels** (VectorCraft's own rule): with points of a gradient mesh picked by the Mesh tool, Direct Selection or the Lasso, the Fill proxy, the Color panel and the Color Wheel show the first picked point's color, so their sliders keep the color a drag sets, and "?" shows when the picked points' colors differ. The Control bar shows the first picked point's opacity. Tests: `the_fill_proxy_shows_the_picked_mesh_points_color`, `the_fill_proxy_follows_where_the_fill_goes_with_an_appearance_row_active` and `the_fill_proxy_counts_picked_mesh_points_beside_other_objects` in `crates/engine/src/tests/xform.rs`, `picked_mesh_points_are_the_color_the_panel_shows_and_edits` in `crates/ui-egui/src/panels/color/tests.rs`, `picking_mesh_points_shows_their_opacity` in `crates/ui-egui/src/panels/transparency.rs`. Scores and hours unchanged.
- **The Eyedropper samples into picked mesh points (#8090):** mesh points picked with the Mesh tool, Direct Selection or the Lasso stay picked after switching to the Eyedropper and go back to one of those tools chosen next, and a click or Shift-click on an image or other art then samples the color under the pointer into every picked point as one undo step, leaving the mesh's other points and its appearance as they were. VectorCraft's own rules: a plain click on vector art samples its color into the points instead of copying its appearance, other selected objects keep their paint, and a click on a mesh with points picked works as before. Public references: [Edit mesh objects](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-meshes/edit-mesh-objects.html) (a mesh point is recolored by selecting it and choosing a fill color), [Appearance attributes](https://helpx.adobe.com/illustrator/using/appearance-attributes.html) (Shift-click samples the color from a part of a mesh object or a placed image and applies it to the selected fill). Tests: `picked_mesh_points_take_the_eyedropper_sample` in `crates/engine/src/tests/eyedropper.rs`, `picked_mesh_points_take_the_color_a_click_samples` in `crates/tools/src/xform/eyedropper.rs`, `mesh_point_tools_take_back_the_eyedroppers_picks` in `crates/tools/src/meshedit.rs`. Scores and hours unchanged.
- **Picked mesh points survive a tool switch:** mesh points picked with the Mesh tool, Direct Selection, the Lasso or the Polygonal Lasso stay picked when another of these tools or the Eyedropper is chosen, and when one of them lends Direct Selection for a Cmd/Ctrl-click, so a fill color chosen afterward recolors just those points. A plain Lasso click away from the art deselects it and unpicks them. Any other tool, Group Selection included, drops them. Public references: [Edit mesh objects](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-meshes/edit-mesh-objects.html) (a mesh point picked with the Mesh tool is recolored by choosing a fill color in the Swatches or Color panel), [Archived help guide, page 202](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=202) (the Mesh tool and Direct Selection both move mesh points). Carrying the picks between the tools is VectorCraft's own rule. Tests: `crates/engine/src/tests/mesh_picks.rs`. Scores and hours unchanged.
- **Image Trace Flat Logo mode:** a fourth mode beside Black and White, Grayscale and Color, for flat-colour logos. Each pixel is read as a blend of the logo's colours (found automatically or named), the blend is interpolated smoothly and every outline is placed where two colours are equally present, so edges are accurate to a fraction of a pixel. Outlines are then cleaned: corners the blur rounded are put back, near-straight runs and near-circular arcs become exact lines and arcs, the rest is fitted with as few Béziers as the tolerance allows, touching colours overlap by a hair so no gap opens, and an outline that strays from the raw contour is fitted plainly instead. Gradients and photos are refused with advice to use Color. Line art whose only solid area is white paper (strokes a pixel or two wide) takes its colours from the strokes' cores, with the lighter shades along a stroke's anti-aliased edge folded into its ink; a page whose ink (a channel at least 48 below white) covers under 1% of it traces to nothing, as blank paper does. *Measured* (a local experiment, not run in CI): a flat-colour logo's vector original was rendered down to a soft 199 × 100 px transparent PNG, traced, and the result compared with the original at 1600 px wide. The built-in colour presets (6 Colors, 16 Colors, High Fidelity Photo, Low Fidelity Photo) had a mean edge error of 2.5 to 3.4 px and region overlap of 0.88 to 0.91; Flat Logo had 0.78 px and 0.966 (0.48 px and 0.975 from a crisp source), in about 0.1 s. Limits: flat-colour art only; needle-thin sharp tips are shortened by about 1.7 source pixels because the blur erases them; it works at no more than 1024 px on the long side (larger images are averaged down first); only one logo family has been scored against a vector original.
- **Image Trace, Flat Logo named colors only:** with `logoColors` named, `"logoWhite": false` traces those colors only, so white areas take the nearest of them and no white is added; a named white is kept, and enclosed transparent areas stay holes; code-drawn tests in `crates/trace` and `crates/engine`.
- **Image Trace, Flat Logo flat-art check with named colors:** with `logoColors` named, whether the image is flat art is judged by its own colors, as many as are named, with white, or as the Colors setting gives, whichever is more. Named colors 20 levels off a flat badge's colors still trace it, a hatch on a light ground gives the same result with close and far named colors, a gradient's refusal score does not depend on how far the named colors are from it, and areas of colors that were not named are traced in the named colors instead of being refused; code-drawn tests in `crates/trace`.
@@ -1948,7 +1950,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
As VectorCraft's own rule, OK in Live Paint Selection Tool Options, Live Paint Bucket Options, Gap Options and Tile Edge Color gives an error for a color with an alpha part (`#rrggbbaa` or `#rgba`) and changes nothing.
As VectorCraft's own rule, a Live Paint edit that changes nothing records no undo step, keeps the redo steps and leaves a saved document saved: a Live Paint Bucket click or drag over faces that already have the fill, a stroke on an edge that already has the paint and weight, Gap Options OK with the options the groups have and no gap to close, and Make or Merge with one Live Paint group alone. Such a fill or stroke also leaves the recent colors as they are. Regression tests: `live_paint_fill_same_paint_is_no_op`, `live_paint_bucket_click_with_the_face_paint_is_no_op`, `live_paint_stroke_edge_same_paint_and_width_is_no_op`, `live_paint_gap_options_same_values_are_no_op`, `live_paint_gap_options_close_without_gaps_is_no_op`, `live_paint_make_existing_group_is_no_op` and `live_paint_merge_single_group_is_no_op` in `crates/engine/src/tests/build.rs`, and `ok_on_unchanged_options_records_no_undo_step` in `crates/ui-egui/src/dialogs/live_paint_gaps.rs`.
As VectorCraft's own rule, the Live Paint Bucket replaces all of a face's fills, or all of an edge's strokes, with one fill or stroke of the paint, shown, fully opaque and blending normally, so a lower fill or stroke no longer draws under the new paint and a fill or stroke of none leaves nothing of that kind drawing; the face's strokes, the edge's fills, the part's own opacity and the topmost shown stroke's dashes, caps and arrowheads stay as they are, and a part that already has only that one fill or stroke records no undo step. [The help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html) says the tool paints faces with the current fill and edges with the current stroke. Regression tests: `live_paint_bucket_replaces_every_fill_row`, `live_paint_stroke_edge_replaces_every_stroke_row` and `live_paint_stroke_edge_paints_the_shown_stroke` in `crates/engine/src/tests/build.rs`.
As VectorCraft's own rule, with a tool other than the Live Paint Bucket, a fill given to a whole selected Live Paint group paints its faces only and a stroke paints its edges only, and the hidden source paths keep their paint. Swap Fill and Stroke trades the fill the faces share with the stroke the edges share, and Default Fill and Stroke leaves the faces with no fill and gives the edges a 0.5 pt black stroke (`docs/mcp.md`). The Eyedropper gives the picked fill attributes to the faces and the picked stroke attributes to the edges, and picks up a whole group as its first face's fills with its first edge's strokes. Overprint Fill goes to the faces and Overprint Stroke goes to the edges. The proxies show the same paint whatever the order of a selection that holds the group and one of its parts. Appearance panel edits of the group's contents leave the hidden source paths as they are, a new fill goes on the faces, and a new stroke goes on the edges. Evidence: `tests::build::{live_paint_group_fill_goes_to_faces_and_stroke_to_edges, live_paint_group_swap_trades_the_faces_fill_and_the_edges_stroke, live_paint_group_default_clears_the_faces_and_gives_the_edges_a_thin_black_stroke, live_paint_group_invert_recolors_the_faces_fill, live_paint_group_gradient_vector_and_freeform_edits_change_its_faces, live_paint_group_stroke_panel_edits_change_its_edges, live_paint_group_rules_stop_where_paint_commands_stop, live_paint_group_without_parts_of_the_edited_kind_leaves_new_art_alone, live_paint_group_proxies_do_not_depend_on_the_selection_order, live_paint_group_eyedropper_gives_the_fill_to_faces_and_the_stroke_to_edges, live_paint_group_eyedropper_gives_every_fill_and_stroke_row, live_paint_group_contents_edits_follow_the_group_rule, live_paint_group_item_edits_and_overprint_follow_the_group_rule, live_paint_group_inside_a_selected_group_keeps_the_proxies_independent_of_order, live_paint_group_eyedropper_picks_up_the_group_and_appends_without_effects}`.
As VectorCraft's own rule, with a tool other than the Live Paint Bucket, a fill given to a whole selected Live Paint group paints its faces only and a stroke paints its edges only, and the hidden source paths keep their paint. Swap Fill and Stroke trades the fill the faces share with the stroke the edges share, and Default Fill and Stroke leaves the faces with no fill and gives the edges a 0.5 pt black stroke (`docs/mcp.md`). The Eyedropper gives the picked fill attributes to the faces and the picked stroke attributes to the edges, and picks up a whole group as its first face's fills with its first edge's strokes. Overprint Fill goes to the faces and Overprint Stroke goes to the edges. The proxies show the same paint whatever the order of a selection that holds the group and one of its parts. Appearance panel edits of the group's contents leave the hidden source paths as they are, a new fill goes on the faces, and a new stroke goes on the edges; a graphic style gives the faces only its fills and the edges only its strokes, and Clear Appearance and Reduce to Basic Appearance leave the faces only fill rows and the edges only stroke rows. Evidence: `tests::build::{live_paint_group_fill_goes_to_faces_and_stroke_to_edges, live_paint_group_swap_trades_the_faces_fill_and_the_edges_stroke, live_paint_group_default_clears_the_faces_and_gives_the_edges_a_thin_black_stroke, live_paint_group_invert_recolors_the_faces_fill, live_paint_group_gradient_vector_and_freeform_edits_change_its_faces, live_paint_group_stroke_panel_edits_change_its_edges, live_paint_group_rules_stop_where_paint_commands_stop, live_paint_group_without_parts_of_the_edited_kind_leaves_new_art_alone, live_paint_group_proxies_do_not_depend_on_the_selection_order, live_paint_group_eyedropper_gives_the_fill_to_faces_and_the_stroke_to_edges, live_paint_group_eyedropper_gives_every_fill_and_stroke_row, live_paint_group_contents_edits_follow_the_group_rule, live_paint_group_item_edits_and_overprint_follow_the_group_rule, live_paint_group_inside_a_selected_group_keeps_the_proxies_independent_of_order, live_paint_group_eyedropper_picks_up_the_group_and_appends_without_effects, live_paint_group_eyedropper_reversed_skips_an_empty_group_for_the_next_whole_group, live_paint_group_eyedropper_does_not_target_its_own_source_group, live_paint_group_with_only_source_paths_leaves_new_art_alone_for_a_contents_edit, live_paint_group_with_only_source_paths_ignores_add_fill_and_add_stroke_of_its_contents, live_paint_group_contents_take_a_graphic_style_by_kind, live_paint_group_contents_without_faces_take_no_fill_only_style, live_paint_group_contents_clear_and_reduce_keep_each_part_to_its_kind}`.
As VectorCraft's own rule, `tool.setOption` for the Live Paint Bucket and the Live Paint Selection tool, chosen or not, checks every value before it sets any: a switch that is not `true` or `false`, a `color` that is not an RGB color or a layer color's name, or that has an alpha part, a `width` that is not a number and an option the tool does not have give an error naming the option, and nothing is set or saved. A `width` outside 1 to 20 px is still set to the nearest end of that range. Saved settings that hold an invalid value still load, and the tool keeps its default for that option. Evidence: `tests::build::{live_paint_tool_options_refuse_invalid_values_and_change_nothing, live_paint_tool_options_take_rgb_colors_and_clamp_the_width, live_paint_tools_load_saved_settings_with_invalid_values}`.
As VectorCraft's own rule, `tool.setOption` for the Shape Builder, chosen or not, checks every value the same way: a switch that is not `true` or `false`, a `pickColorFrom` or `selection` that is not one of its names, a `gapLength` that is not a number, a `highlightColor` that is not an RGB color or a layer color's name, or that has an alpha part, and an option the tool does not have give an error naming the option, and nothing is set or saved. A `gapLength` outside 0 to 72 pt is still set to the nearest end of that range. Evidence: `tests::build::{shape_builder_tool_options_refuse_invalid_values_and_change_nothing, shape_builder_tool_options_take_valid_values_and_clamp_the_gap}`.
A drag of 3 screen pixels or more with the Live Paint Selection tool draws a marquee and selects the faces and edges it touches, partly enclosed ones included, and a Shift-drag adds them to the selection or removes them from it ([Modify Live Paint groups](https://web.archive.org/web/20261006115247/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/modify-live-paint-groups.html)). A click and a marquee change the selection on release, and Escape before the release leaves the selection as it was. Locked Live Paint groups, those on a locked layer or artboard, and in isolation mode those outside the isolated art are not highlighted or selected.
@@ -2053,6 +2055,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
Escape ends that eyedropper's pick, and Brush Options' Key Color pick, without sampling and returns to the tool that started it; the stop keeps its color, and Brush Options stays open with its Key Color until a new Escape cancels it (#8024, [Modify gradients, archived user guide](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=264)).
Cmd/Ctrl-click on the Gradient panel's Gradient Fill box or on the Tools panel's Gradient button resets the gradient of the active Fill or Stroke to the linear White, Black gradient, as one undo step ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)).
With a gradient stop or a freeform gradient point selected, Alt-clicking a color swatch in the Swatches panel recolors it instead of the inactive Fill or Stroke.
In the Gradient tool's freeform Lines mode, moving the pointer out of the object and back ends the line being drawn, and the next click on the object starts a new line from the point it adds. The help page describes this way of starting another line segment in the same object ([Create freeform gradient in lines mode](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=262)). As VectorCraft's own rules, the line ends as soon as the pointer, with no button held, moves off the object's own art, its fill, stroke or glyphs (other art lying over the object still counts as inside), and Escape and a click off the art still end it as before (`xform::freeform::tests::leaving_the_object_ends_the_line`).
- **Freeform gradient colors in their own model:** Object ▸ Expand and Object ▸ Create Gradient Mesh (`object.mesh.create`) mix a freeform gradient's points in the color model they share: points of C50 M20 Y0 K10 give mesh points of C50 M20 Y0 K10, and RGB points keep their values in a working RGB space other than sRGB. The canvas, the gradient chips and the SVG, PDF, EPS and EMF writers mix the points in that model too. PDF and EPS write a gradient whose points are all CMYK, or all Gray in a CMYK file, as a CMYK image, which PDF's Output settings convert as they convert any CMYK image. Points in different models mix in display RGB (on the canvas in a CMYK document that shows transparency, as the inks of each point), and a CMYK document stores the result of Expand as CMYK through the color settings. Points colored along CMYK stops (`paint.editGradient {stops}`, or a CMYK gradient switched to freeform) are CMYK, and so are a point `paint.freeform.splitLine` adds between CMYK points and a point `paint.freeform.addPoint` adds without `color` to CMYK points. Public reference: [Gradients](https://web.archive.org/web/20250714042311/https://helpx.adobe.com/illustrator/using/gradients.html) and [Meshes](https://web.archive.org/web/20250812201019/https://helpx.adobe.com/illustrator/using/meshes.html), which do not state how colors in different models mix; the rule is VectorCraft's own.
- **Strokes:** one stroke-geometry module shared by the canvas, SVG, PDF and Outline Stroke; dotted lines (zero-length dashes draw dots or squares); arrowheads with hollow outlines, tip-on-end or extend-past-end alignment and one opacity for line and head. SVG and PDF export arrowheads, width profiles, brushes and aligned strokes exactly as the canvas draws them; Outline Stroke and the live Outline Stroke effect outline every stroke item as drawn (dashes, heads, profiles, alignment); dashes can be fitted to corners and path ends; width profiles carry through dashes, and their corners take the join. The Stroke panel edits type's character strokes, follows the stroke units (its weight presets are round values in that unit: `0.25 mm`, `0.0625 in`, `1 px`, #426; fields show four decimals in mm, cm and inches, three in points), shows mixed values blank and opens from the Control bar. A width profile library, thirty-one more arrowheads (among them Line Arrow: two arms of the head's weight (stroke weight × arrowhead scale, at least 0.25 pt: the line's weight at 100 % for lines of 0.25 pt or more) at right angles, cut square, #5421), and Width Point Edit with multi-select and discontinuous points. Visual bounds and clicks cover the whole painted stroke. Scale Strokes & Effects, Scale Corners and Use Preview Bounds work everywhere, and new art inherits stroke options, a graphic style or the whole last appearance. A width profile's sides run as a smooth C1 curve between the width points (a monotone cubic Hermite, Fritsch–Carlson, with the one-sided three-point PCHIP slope at the profile's ends and flat either side of a step), sampled adaptively along the path (two samples per profile segment, refined where the width bends, and leaning on dense path flattening) so straight runs draw it too; added samples offset along the source curve's exact tangent, not the flattened chord, so high zoom follows the true width; the sampled edges are fitted with G1 cubics within a tenth of the flattening tolerance (0.001 pt at the default 0.01 pt) rather than one cubic per flatten step, so exports stay close to a uniform stroke's path data; a point reshapes the curve as far as its neighbours' neighbours (their slopes depend on it), and coincident points still step.
- **Brushes (part of #852):** double-clicking a brush in the Brushes panel (or the panel menu's Brush Options…) opens Calligraphic Brush Options (Name; Angle, Roundness and Size, each Fixed, Random, Pressure, Tilt, Bearing or Rotation with its Variation; live previews of the nib and of a light–heavy–light stroke) or Bristle Brush Options (Shape and the bristle sliders); OK edits the brush and every stroke painted with it. The Paintbrush records the pen pressure along each stroke (kept with the path, saved, and joined when a stroke continues a path); a Calligraphic value on Pressure goes from value − variation at the lightest pressure to value + variation at the heaviest, on the canvas and in SVG, PDF and the other exports. Brushes saved before keep their look. Scatter Brush Options (Size, Spacing, Scatter and Rotation, each Fixed, Random between two values, Pressure from the first at the lightest pressure to the second at the heaviest, Tilt, Bearing or Rotation; Rotation relative to Page or Path), Art Brush Options (Width, Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with the guides' start and end, the four Directions, Flip Along and Across, Overlap) and Pattern Brush Options (Scale, Spacing, the five tiles shown, Flip Along and Across, Stretch to fit, Add space to fit or Approximate path) each have Colorization (None, Tints, Tints and Shades, Hue Shift with its Key Color picked from the art's colours) and a live stroke preview; values from files and commands are clamped to their ranges. Art Brush Options › Overlap places art on each run between sharp corners so folds do not overlap (`ArtBrush.overlap`; `art_brush_overlap_splits_at_corners`). Still to come: Stylus Wheel for Pattern brushes and on Windows and the web, pen pressure on macOS where the windowing layer reports none, and tilt, bearing and rotation for Pattern and Bristle brushes and on native Wayland and the web.
@@ -2323,7 +2326,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- BMP files named `.dib` or `.rle` (run-length encoded bitmaps included), Photoshop files named `.pdd` and PNG files named `.pns` open and place, linked or embedded, as BMP, PSD and PNG files, in any letter case: the Open and Place dialogs list them with their format, the Links panel names their format, and Edit Original opens them. Exports write only `.bmp`, `.psd` and `.png` (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/links.rs`).
- File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer, merging a layer that uses a Knockout option with the layers below it, and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), a Knockout value of 1 is read as a shallow knockout and applied to a layer or group inside a group, which is merged with the visible layers below it in that group (its pixels clear them to transparency, it is drawn there at its fill opacity, and its opacity fades the result; in a pass-through group only when it and the visible layers below it are in the Normal mode; a knockout at 0 opacity, or at 0 fill where it covers none of their painted pixels, isn't merged for the knockout), and adjustment layers, layer effects, vector masks and the other knockouts (top-level layers, clipped layers, layers that others are clipped to, pass-through groups with layers in other modes, other Knockout values, and merges that need more memory than allowed) aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`).
- File › Open of a PSD or PSB file with two or more layers, and File › Place of one without Link, show PSD Import Options: Convert Layers to Objects with Import Hidden Layers, or Flatten Layers to a Single Image, the options [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded. A file placed with Link shows its flat image and isn't asked about. `file.place` takes `layers` and `hiddenLayers`, and `document.psdInfo` counts a file's layers without opening it. VectorCraft's own rules: placed layers come in as one group named after the file, a layer as an image and a layer group as a group, at the place the merged image would take and clipped to the canvas when layers reach past it; the dialog asks from two layers up and starts from the choices made last. Layer comps aren't read (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`).
- A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` give the clip group the clipping path the new file names, or leave a plain group when it names none, and files that name no clipping path come in as before. `links.unembed` keeps the clip group, and the PNG or TIFF it writes is read with the path on File › Open, File › Place, `links.relink` and `links.update` (`crates/engine/src/cmd/fileio/tests_psdread.rs`).
- A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` give the clip group the clipping path the new file names, or leave a plain group when it names none; `links.update` leaves a distorted image's clipping as it is. When Placement Options do not clip the image, a clip group whose clipping path was changed in the document (an anchor or handle moved by a thousandth of a point or more, anchors added or removed, a subpath opened or closed, or its fill rule changed) and a clipping mask made in the document are kept: a new file that names no clipping path leaves the mask clipping the image, and the clip group of a new file that names one goes inside the mask. Files that name no clipping path come in as before. `links.unembed` keeps the clip group, and the PNG or TIFF it writes is read with the path on File › Open, File › Place, `links.relink` and `links.update` (`crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/dcs.rs`).
- Import Slices: File › Open of a PSD or PSB file with slices, and File › Place of one without Link, bring its slices in as user slices, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded; PSD Import Options offers Import Slices for such a file. `document.open` and `file.place` take `importSlices`, and `document.psdInfo` counts the slices. The slices are read from image resource 1050 in version 6 and in the descriptor of versions 7 and 8, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it. VectorCraft's own rules: Import Slices applies to Convert Layers to Objects and to Flatten Layers to a Single Image alike, and makes the dialog ask for a file with fewer than two layers; placed slices move and scale with the art in the same undo step; each slice keeps its name, type, link, target, message, alternative text, cell text and background color; slices the file generated automatically, and slices wholly outside the canvas, are left out; slices that can't be read are left out with a warning while the art comes in; with Show Import Options off, a PSD file is placed with the PSD Import Options chosen last, and on, each PSD file of the place cursor asks for them (`crates/engine/src/cmd/fileio/tests_psdslices.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`).
The import fuzz tests open, count and place PSD files whose resource 1050 is in version 6 (with a version 16 descriptor after a record) and in the descriptors of versions 7 and 8, with their data mutated, cut short with the resource's length saying so, and cut short in the file; a slice count past 10,000 or past the slices stored, and data one byte short, bring the art in without its slices and with a warning. `tests_psdslices::damaged_slices_never_panic` now fails when a command reports an internal error (`import_fuzz::the_sliced_psd_samples_bring_in_their_user_slices`, `import_fuzz::sliced_psd_samples_with_huge_counts_or_cut_short_come_in_without_their_slices`, `import_fuzz::mutated_psd_slices_never_panic`). Scores and estimates unchanged.
- PSD export writes slices: the user and object slices that reach into the exported artboard go into image resource 1050 in version 6, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it and as Import Slices reads it, so an opened PSD file's slices survive its export. VectorCraft's own rules: slices are written with Write Layers and as a flat image alike, clipped to the artboard in its pixels; an object slice is written as a user slice over its object's bounds, and an HTML Text slice as No Image with its type's text; auto slices are left out and laid out again on open; text alignment is written as the default (`crates/render/src/encode/tests_psd.rs`, `crates/engine/src/cmd/fileio/tests_psdslices.rs`).
@@ -3079,7 +3082,11 @@ Check Spelling followed (2026-11-15): Edit › Spelling › Check Spelling… (`
## Retype, phase 1 (2026-11-18)
The public pages describe Retype finding the fonts that match selected outlined text (or text in an image), from the fonts on the device among others, and applying them to live text ([identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html)). Phase 1 (#4934) is local and exact: Type › Retype (`type.retype`) compares each selected glyph shape with the glyphs of the loaded fonts, the document's fonts and any families named in `fonts`, the same up to uniform scale, rotation and translation, and sets the matched characters as point text in that font and size at the same baseline, one object per line, in one undo step. Shapes that match no font stay and are reported. The search is bounded, not exhaustive: at most 96 faces (named families first, then the document's fonts, then the other loaded faces), the first 65,536 encoded characters of each, and glyphs of plain-shape characters (box drawing, blocks, geometric shapes, private use) are left out; a glyph outside those limits is reported as matching no font. Exact matching also reads a curve an exporter split in two as a different shape (phase 2, with the other near matches). Tested by round trips through Create Outlines (plain, bold and turned, serif, word spaces), a drawn shape and a mixed selection (`crates/engine/src/cmd/retype_tests.rs`). Near matches, the ranked font list, installed fonts not yet loaded and images remain (phase 2).
The public pages describe Retype finding the fonts that match selected outlined text (or text in an image), from the fonts on the device among others, and applying them to live text ([identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html)). Phase 1 (#4934) is local and exact: Type › Retype (`type.retype`) compares each selected glyph shape with the glyphs of the loaded fonts, the document's fonts and any families named in `fonts`, the same up to uniform scale, rotation and translation, and sets the matched characters as point text in that font and size at the same baseline, one object per line, in one undo step. Shapes that match no font stay and are reported. The search is bounded, not exhaustive: at most 96 faces (named families first, then the document's fonts, then the other loaded faces), the first 65,536 encoded characters of each, and glyphs of plain-shape characters (box drawing, blocks, geometric shapes, private use) are left out; a glyph outside those limits is reported as matching no font. Exact matching also reads a curve an exporter split in two as a different shape; near matching with a tolerance (below) reads it as the glyph. Tested by round trips through Create Outlines (plain, bold and turned, serif, word spaces), a drawn shape and a mixed selection (`crates/engine/src/cmd/retype_tests.rs`). Installed fonts not yet loaded and images remain (phase 2).
## Retype near matches (2026-11-18)
The public page orders Retype's matching fonts by how close each is to the text's appearance ([identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html)), so outlines need not be exactly a font's glyphs. `type.retype` takes a `tolerance` (0 to 0.05, default 0 for exact matches only). Above 0, a shape of up to 8 contours that is no glyph exactly is read at equal steps of length from any start and in either direction, its contours paired with the glyph's by length, and it becomes the glyph it is closest to when the leftover distance, relative to the shape's size, is at most the tolerance and the glyph's outline and the shape's each lie within three times the tolerance (relative to the shape's size, and at least 0.5%) of the other. A near-matched glyph may differ from its line by the tolerance in size, turn and place; an exact glyph keeps the exact limits unless the line's first glyph, whose size and turn the line takes, is a near match. Each line in the result has a `score` from 1 (exact) to 0. A compound path holding several glyphs (a word made into one compound path) is split into groups of contours and matched in runs of up to three groups, and becomes type only when every glyph does; exact matching of those groups also reads contours that run the other way round, as Make Compound Path leaves them. Exact matches of the whole shape come first, then exact matches of its groups, then near matches. The tolerance, the score and the splitting are VectorCraft's own. Tested with outlines flattened into lines, restarted, reversed and simplified, a curve split in two, contours in another order, turned lines of round glyphs, a word made into one compound path, and a compound with a part that is no glyph (`crates/engine/src/cmd/retype_tests.rs`, `crates/text/src/retype.rs`). The Retype panel's list (below) still takes exact matches of whole shapes only. Glyphs fused into one contour, installed fonts not yet loaded and images remain.
## Retype panel (2026-11-18)
+1 -1
View File
@@ -56,7 +56,7 @@ against Illustrator's public documentation; **estimated** unless noted.
| Alt + numeric-keypad codes while typing (Windows: `Alt+0176` → °) | partial | #5108: on Windows the character Windows posts when Alt comes up after keypad digits is typed at the caret like any other, in the typing's undo step, and the keypad digits typed with Alt run no shortcut. With NumLock off the keypad keys (Insert, End, arrows, Clear, Home, Page Up/Down without the extended-key flag) count as digits too and don't move the caret (`windows_alt_codes` unit tests; neither NumLock on nor off has been tried on a Windows machine yet). `type.insert {code}` (Windows Alt+0 code, Windows-1252 for 128–159) and `{unicode}` (hex code point) insert a character by its code (`menucmds::insert_a_character_by_its_code`). macOS and Linux have no such system convention and egui reports a keypad digit as the top-row digit, so there it does nothing; a floating panel window doesn't receive the character |
| Caret: the arrows and Delete step over whole clusters (Thai consonant with its marks, combining accents, emoji); Backspace removes one character | done | in text with right-to-left characters the arrows move in visual order and stop on both sides of a character drawn with no width, such as a zero width non-joiner |
| Touch Type tool | done | moves, scales and rotates one character through its kerning, baseline shift, scales and rotation (`text.touchType`); a character with a preceding logical character on the same line can move along the line in either reading direction; the first logical character moves only up and down. Positive `dx` follows reading order. These direction rules are VectorCraft's choices. |
| Retype (identify fonts in outlines/images) | partial | Phase 1 (#4934): Type › Retype (`type.retype`) turns outlined glyphs back into type when each shape is exactly a glyph of a loaded font, a font the document uses or a family named in `fonts` (the same up to uniform scale, rotation and translation): one object per line unless lines stack into one object as described below, in that font and size, at the same baseline and turn, with the first glyph's fill and stroke, in one undo step; shapes that match no font stay as they are and are reported. Evenly spaced glyphs keep their spacing as tracking (gaps one space wide stay word spaces when type draws them), and lines stacked at one leading and lined up at their starts, ends or centers become one area type object with that leading and alignment (VectorCraft's own rules, checked against the layout). Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Missing (phase 2): near or fuzzy matches (another version of the font, simplified outlines, glyphs merged into one path), opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, installed fonts not yet loaded, text in images. Public behaviour: [identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html) |
| Retype (identify fonts in outlines/images) | partial | Phase 1 (#4934): Type › Retype (`type.retype`) turns outlined glyphs back into type when each shape is exactly a glyph of a loaded font, a font the document uses or a family named in `fonts` (the same up to uniform scale, rotation and translation): one object per line unless lines stack into one object as described below, in that font and size, at the same baseline and turn, with the first glyph's fill and stroke, in one undo step; shapes that match no font stay as they are and are reported. Near matches: with `tolerance` (0 to 0.05), shapes of up to 8 contours whose leftover distance from a glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (simplified outlines, curves split in two, contours in another order or direction) match too, and each line reports a `score`; a compound path holding several glyphs is split into them and becomes type only when all of them match. A line of three or more exactly matched glyphs keeps the spacing most of its gaps share as tracking (gaps one space wide stay word spaces when type draws them). A line of two glyphs that untracked type does not draw in place takes the tracking of the nearest tracked line in the same font, size and turn, and keeps it only when type at that tracking draws both glyphs in place; a line of one or two glyphs that joins tracked lines in one object takes their tracking. Other lines are set untracked, each glyph at its own position, and lines stacked at one leading and lined up at their starts, ends or centers become one area type object with that leading and alignment (VectorCraft's own rules, checked against the layout). Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Missing (phase 2): glyphs fused into one contour, near matches and compound paths of several glyphs in the panel's list, opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, installed fonts not yet loaded, text in images. Public behaviour: [identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html) |
| Snap to Glyph | done | View › Snap to Glyph (`view.snapToGlyph`): with Smart Guides on, new point type and drawing tools snap to live-text baselines and glyph bounds, the corners of each glyph's box included, turning with rotated type (#5112; `guides::tests::a_drawn_point_lands_on_a_corner_of_a_glyphs_bounds`, `Targets::for_drawing`, `tools::text_tests::snap_to_glyph_lines_up_new_point_type_with_a_baseline`). With Alignment Guides on as well, and Snap to Grid and Snap to Pixel off, both ends of a Measure or Measure & Inspect drag snap to those guides and show them during the drag (`Targets::for_measure`, `xform::measure::tests::its_ends_land_on_glyph_guides_with_snap_to_glyph`). That the Measure tools take the guides is VectorCraft's choice; they leave out Anchor Point, which [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/snap-to-glyph.html) limits to the Pen tool and objects moved with the Selection tool. Character panel menu › Show Snap to Glyph Options: Baseline, x-height, Glyph Bounds, Proximity Guides, Angular Guides and Anchor Point each turn their guides on or off (`view.snapToGlyph.options`, all on by default; #4232), after a Snap to Glyph checkbox for View › Snap to Glyph; showing them scrolls the panel to them (#5273) |
| Thai, Lao, Khmer, Myanmar: shaping (marks, reordering), lines broken between words, word-by-word caret and double-click | done | words found by ICU4X's line segmenter: dictionaries on the desktop, LSTM models on the web |
| Middle Eastern: bidirectional layout, Paragraph Direction | done | PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import still needs ActualText support (#6165); separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. |