mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-22 10:23:16 +01:00
Merge main into feat/draw-behind-alt-drag-copy
This commit is contained in:
commit
9eb8cd6146
100 files changed
+6502
-515
No files matched your search
Generated
+1
@@ -7056,6 +7056,7 @@ dependencies = [
|
||||
"craft-image-codecs",
|
||||
"craft-vectorcraft-format",
|
||||
"log",
|
||||
"rustix 1.1.6",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
|
||||
@@ -13,6 +13,8 @@ workspace = true
|
||||
spine-count = []
|
||||
# `vectorcraft_doc::symbols_read` for other crates' tests (dev-dependencies only).
|
||||
symbol-read-count = []
|
||||
# `vectorcraft_doc::locked_artboard_measures` for other crates' tests (dev-dependencies only).
|
||||
locked-artboard-count = []
|
||||
|
||||
[dependencies]
|
||||
vectorcraft-geom = { workspace = true }
|
||||
|
||||
@@ -174,6 +174,21 @@ impl ArtboardSide {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature = "locked-artboard-count"))]
|
||||
thread_local! {
|
||||
/// How many objects [`LockedArtboards::overlaps`] has measured on this thread.
|
||||
static LOCKED_ARTBOARD_MEASURES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// How many objects [`LockedArtboards::overlaps`] has measured on this thread, for other crates'
|
||||
/// tests that count how often art is measured to find what a locked artboard holds (the
|
||||
/// `locked-artboard-count` feature, dev-dependencies only).
|
||||
#[cfg(any(test, feature = "locked-artboard-count"))]
|
||||
#[doc(hidden)]
|
||||
pub fn locked_artboard_measures() -> usize {
|
||||
LOCKED_ARTBOARD_MEASURES.with(std::cell::Cell::get)
|
||||
}
|
||||
|
||||
/// A document's locked artboards ([`Document::locked_artboards`]).
|
||||
pub struct LockedArtboards<'a> {
|
||||
pub(crate) rects: Vec<Rect>,
|
||||
@@ -210,6 +225,8 @@ impl LockedArtboards<'_> {
|
||||
if let Some(held) = self.held.borrow().get(&n.id) {
|
||||
return *held;
|
||||
}
|
||||
#[cfg(any(test, feature = "locked-artboard-count"))]
|
||||
LOCKED_ARTBOARD_MEASURES.with(|c| c.set(c.get() + 1));
|
||||
let held =
|
||||
n.visual_bounds_with(&self.symbols).is_some_and(|b| self.rects.iter().any(|r| b.x0 < r.x1 && b.x1 > r.x0 && b.y0 < r.y1 && b.y1 > r.y0));
|
||||
self.held.borrow_mut().insert(n.id, held);
|
||||
|
||||
+20
-3
@@ -1162,9 +1162,15 @@ impl Lerp {
|
||||
&& let (Some(qa), Some(qb)) = (a.image_corners(), b.image_corners())
|
||||
{
|
||||
let near = if t < 0.5 { qa } else { qb };
|
||||
if n.set_image_corners([0, 1, 2, 3].map(|i| qa[i].lerp(qb[i], t))).is_err() {
|
||||
// The nearer key's corners passed the same check when it was distorted.
|
||||
let _ = n.set_image_corners(near);
|
||||
if n.set_image_corners([0, 1, 2, 3].map(|i| qa[i].lerp(qb[i], t))).is_err() && n.set_image_corners(near).is_err() {
|
||||
// Corners from a transform that collapses the image fail the check too: the
|
||||
// step is then placed as the nearer key is.
|
||||
if let (NodeKind::Image(o), NodeKind::Image(k)) = (&mut n.kind, &base.kind) {
|
||||
o.xf = k.xf;
|
||||
}
|
||||
if n.extras().image_quad != base.extras().image_quad {
|
||||
n.extras_mut().image_quad = base.extras().image_quad.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
n.extras_mut().mask = None;
|
||||
@@ -2343,6 +2349,17 @@ mod tests {
|
||||
let near = (if t < 0.5 { &a } else { b }).image_corners().unwrap();
|
||||
assert!(got.iter().zip(near).all(|(g, w)| g.distance(w) < 1e-9), "{t}: {got:?} against {near:?}");
|
||||
}
|
||||
// Toward an image whose transform has no height, neither the step's corners nor the
|
||||
// nearer key's pass the check: the step is placed as that key is.
|
||||
let mut flat = image([(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]);
|
||||
let collapsed = Affine::new([-3.0, 0.0, 0.0, 0.0, 100.0, 0.0]);
|
||||
if let NodeKind::Image(im) = &mut flat.kind {
|
||||
im.xf = collapsed;
|
||||
}
|
||||
let step = Lerp::new(&a, &flat, (None, None)).at(0.5);
|
||||
let NodeKind::Image(im) = &step.kind else { panic!("an image") };
|
||||
assert_eq!(im.xf, collapsed);
|
||||
assert!(!step.is_distorted_image() && step.extras().image_quad.is_none());
|
||||
}
|
||||
|
||||
fn key(x: f64) -> Arc<Node> {
|
||||
|
||||
@@ -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()
|
||||
{
|
||||
|
||||
@@ -1463,6 +1463,7 @@ const SELECTING: HitOptions = HitOptions {
|
||||
skip_guides: false,
|
||||
clip_outlines: true,
|
||||
area_type_interior: false,
|
||||
ignore_layer_preview: false,
|
||||
scope: None,
|
||||
};
|
||||
|
||||
|
||||
@@ -392,6 +392,11 @@ mod tests {
|
||||
assert_eq!(n.image_quad(), None);
|
||||
assert!(distorted_art(&n).is_none());
|
||||
assert_eq!(n.image_corners(), Some(rect_corners(Rect::new(0.0, 0.0, 100.0, 100.0))));
|
||||
// Reading the file drops it, so a later transform can't make it a distortion.
|
||||
let mut back: Node = serde_json::from_value(serde_json::to_value(&n).unwrap()).unwrap();
|
||||
assert!(back.extras().image_quad.is_none());
|
||||
back.transform(Affine::scale_non_uniform(1e6, 1.0), false);
|
||||
assert!(!back.is_distorted_image());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -161,6 +161,9 @@ mod records;
|
||||
mod stored_art;
|
||||
mod units;
|
||||
|
||||
#[cfg(any(test, feature = "locked-artboard-count"))]
|
||||
#[doc(hidden)]
|
||||
pub use artboard::locked_artboard_measures;
|
||||
pub use artboard::{ARTBOARD_GAP, Artboard, ArtboardSide, LockedArtboards, RetiredArtboardId, VIDEO_PIXEL_ASPECT_RANGE, VIDEO_SAFE_INSETS};
|
||||
pub use canvas_range::BeyondCanvas;
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -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> {
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
),
|
||||
|
||||
@@ -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)
|
||||
})?;
|
||||
|
||||
@@ -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))
|
||||
})
|
||||
|
||||
@@ -42,7 +42,7 @@ pub mod jxlread;
|
||||
mod legacy_ai;
|
||||
mod load;
|
||||
mod mesh3d;
|
||||
pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, image_clip, size_note};
|
||||
pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, image_clip, preview_with_clip, size_note};
|
||||
mod heifread;
|
||||
pub mod hpgl;
|
||||
mod jp2read;
|
||||
|
||||
@@ -1370,6 +1370,20 @@ pub(crate) fn image_clip(blob: &ImageBlob) -> Option<vectorcraft_geom::PathData>
|
||||
vectorcraft_geom::path::with_anchor_budget(vectorcraft_geom::path::MAX_READ_ANCHORS, || serde_json::from_slice(json).ok())
|
||||
}
|
||||
|
||||
/// `blob` with its preview keeping the clipping path its PNG or TIFF keeps ([`image_clip`]), in a
|
||||
/// text chunk of the preview PNG as [`png_with_clip`] writes it: a document saved without its
|
||||
/// linked files holds the preview alone, and the Links commands then still know a clip group of
|
||||
/// that path as the file's. Unchanged without a preview or a clipping path.
|
||||
pub(crate) fn preview_with_clip(mut blob: ImageBlob) -> ImageBlob {
|
||||
let Some(proxy) = blob.proxy.clone().filter(|p| !std::sync::Arc::ptr_eq(p, &blob.bytes) && png_clip(p).is_none()) else { return blob };
|
||||
let Some(json) = image_clip(&blob).and_then(|clip| serde_json::to_string(&clip).ok()).filter(|j| j.len() <= MAX_PNG_CLIP) else {
|
||||
return blob;
|
||||
};
|
||||
let png = vectorcraft_render::encode::png::with_text(proxy.to_vec(), &[(CLIP_KEYWORD, json.into())]);
|
||||
blob.proxy = Some(std::sync::Arc::new(png));
|
||||
blob
|
||||
}
|
||||
|
||||
/// An image as a document of its physical size at the resolution it declares (as Place sizes it;
|
||||
/// 72 ppi, 1 px = 1 pt, when it declares none), the image named after the file.
|
||||
pub(super) fn raster_doc(name: &str, bytes: &[u8]) -> Result<Document> {
|
||||
|
||||
@@ -602,6 +602,217 @@ fn relink_and_update_follow_the_clipping_path_of_a_linked_psd() {
|
||||
assert_eq!(clip_group(&s.doc().unwrap().doc, group), (squared, true, NodeId(image)), "links.update reads the clipping path again");
|
||||
}
|
||||
|
||||
/// links.relink follows the clipping path of a linked PSD file for an image changed by Perspective
|
||||
/// Distort or Free Distort too: the new file's clipping path is mapped through the image's corners,
|
||||
/// a clip group of the old file's clipping path loses it when the new file names none, and a later
|
||||
/// file's clipping path clips it again.
|
||||
#[test]
|
||||
fn relink_follows_the_clipping_path_of_a_distorted_psd() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("psd-relink-distorted");
|
||||
let cut = write_file(&dir, "cut.psd", &red_psd(&triangle_resources()));
|
||||
let square = write_file(&dir, "square.psd", &red_psd(&square_resources()));
|
||||
let plain = write_file(&dir, "plain.psd", &red_psd(&[]));
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
|
||||
let r = s.execute("file.place", &json!({"path": cut, "at": [50, 25]})).unwrap();
|
||||
let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), NodeId(r["image"].as_u64().unwrap()));
|
||||
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
|
||||
s.execute("object.distort", &json!({"corners": [[0, 0], [100, 8], [90, 50], [6, 44]]})).unwrap();
|
||||
let node = |s: &Session| s.doc().unwrap().doc.node(image).unwrap().clone();
|
||||
assert!(node(&s).is_distorted_image());
|
||||
let corners = node(&s).image_corners().unwrap();
|
||||
// A path's anchors (in the image's pixels) where the image's corners put them.
|
||||
let mapped = |s: &Session, pixels: &[[f64; 2]]| -> Vec<[f64; 2]> {
|
||||
let map = node(s).image_map().unwrap();
|
||||
pixels.iter().map(|[x, y]| map.apply(vectorcraft_geom::Point::new(*x, *y)).unwrap()).map(|p| [p.x, p.y]).collect()
|
||||
};
|
||||
let near =
|
||||
|a: &[[f64; 2]], b: &[[f64; 2]]| a.len() == b.len() && a.iter().zip(b).all(|(p, q)| (p[0] - q[0]).abs() < 1e-6 && (p[1] - q[1]).abs() < 1e-6);
|
||||
let (anchors, even_odd, held) = clip_group(&s.doc().unwrap().doc, group);
|
||||
let triangle = mapped(&s, &[[50.0, 0.0], [100.0, 50.0], [0.0, 50.0]]);
|
||||
assert!(near(&anchors, &triangle) && even_odd && held == image, "{anchors:?} vs {triangle:?}");
|
||||
s.execute("links.relink", &json!({"ids": [image.0], "path": square})).unwrap();
|
||||
let (anchors, even_odd, held) = clip_group(&s.doc().unwrap().doc, group);
|
||||
let squared = mapped(&s, &[[25.0, 12.5], [75.0, 12.5], [75.0, 37.5], [25.0, 37.5]]);
|
||||
assert!(near(&anchors, &squared) && even_odd && held == image, "the new file's clipping path: {anchors:?} vs {squared:?}");
|
||||
assert_eq!(node(&s).image_corners().unwrap(), corners);
|
||||
s.execute("links.relink", &json!({"ids": [image.0], "path": plain})).unwrap();
|
||||
match s.doc().unwrap().doc.node(group).map(|n| &n.kind) {
|
||||
Some(NodeKind::Group { children, clip: false }) => assert_eq!(children.iter().map(|c| c.id).collect::<Vec<_>>(), [image]),
|
||||
other => panic!("a plain group of the image: {other:?}"),
|
||||
}
|
||||
s.execute("links.relink", &json!({"ids": [image.0], "path": cut})).unwrap();
|
||||
let (anchors, _, held) = clip_group(&s.doc().unwrap().doc, group);
|
||||
assert!(near(&anchors, &triangle) && held == image, "clipped again: {anchors:?} vs {triangle:?}");
|
||||
assert!(node(&s).is_distorted_image());
|
||||
assert_eq!(node(&s).image_corners().unwrap(), corners);
|
||||
}
|
||||
|
||||
/// Update Links follows the clipping path of a linked PSD file for an image changed by Perspective
|
||||
/// Distort or Free Distort: the file's new clipping path is drawn through the image's corners, and
|
||||
/// a file without one leaves a plain group.
|
||||
#[test]
|
||||
fn update_links_follows_the_clipping_path_of_a_distorted_psd() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("psd-update-distorted");
|
||||
let cut = write_file(&dir, "cut.psd", &red_psd(&triangle_resources()));
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
|
||||
let r = s.execute("file.place", &json!({"path": cut, "at": [50, 25]})).unwrap();
|
||||
let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), NodeId(r["image"].as_u64().unwrap()));
|
||||
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
|
||||
s.execute("object.distort", &json!({"corners": [[0, 0], [100, 8], [90, 50], [6, 44]]})).unwrap();
|
||||
let node = |s: &Session| s.doc().unwrap().doc.node(image).unwrap().clone();
|
||||
let corners = node(&s).image_corners().unwrap();
|
||||
let map = node(&s).image_map().unwrap();
|
||||
let squared: Vec<[f64; 2]> = [[25.0, 12.5], [75.0, 12.5], [75.0, 37.5], [25.0, 37.5]]
|
||||
.iter()
|
||||
.map(|[x, y]| map.apply(vectorcraft_geom::Point::new(*x, *y)).unwrap())
|
||||
.map(|p| [p.x, p.y])
|
||||
.collect();
|
||||
std::fs::write(&cut, red_psd(&square_resources())).unwrap();
|
||||
s.execute("links.update", &json!({"ids": [image.0]})).unwrap();
|
||||
let (anchors, even_odd, held) = clip_group(&s.doc().unwrap().doc, group);
|
||||
let near = anchors.len() == squared.len() && anchors.iter().zip(&squared).all(|(p, q)| (p[0] - q[0]).abs() < 1e-6 && (p[1] - q[1]).abs() < 1e-6);
|
||||
assert!(near && even_odd && held == image, "the file's new clipping path: {anchors:?} vs {squared:?}");
|
||||
assert_eq!(node(&s).image_corners().unwrap(), corners);
|
||||
std::fs::write(&cut, red_psd(&[])).unwrap();
|
||||
s.execute("links.update", &json!({"ids": [image.0]})).unwrap();
|
||||
match s.doc().unwrap().doc.node(group).map(|n| &n.kind) {
|
||||
Some(NodeKind::Group { children, clip: false }) => assert_eq!(children.iter().map(|c| c.id).collect::<Vec<_>>(), [image]),
|
||||
other => panic!("a plain group of the image: {other:?}"),
|
||||
}
|
||||
assert_eq!(node(&s).image_corners().unwrap(), corners);
|
||||
}
|
||||
|
||||
/// A document saved without its linked files keeps a linked PSD file's image as a preview, smaller
|
||||
/// than the file. Reopened after the file's clipping path changed, Update Links still knows the
|
||||
/// clip group of the old clipping path as the file's and gives it the new one, for an image changed
|
||||
/// by Perspective Distort or Free Distort and for one that is not.
|
||||
#[test]
|
||||
fn update_links_after_reopening_from_the_preview_replaces_the_files_clipping_path() {
|
||||
let big = |resources: &[u8]| psd(1, 3, (400, 200), 8, 3, &[], resources, &[], &raw(&[&[255; 80000], &[0; 80000], &[0; 80000]]));
|
||||
for distorted in [false, true] {
|
||||
let dir = vectorcraft_testkit::TempDir::new(if distorted { "psd-preview-distorted" } else { "psd-preview" });
|
||||
let cut = write_file(&dir, "cut.psd", &big(&triangle_resources()));
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap();
|
||||
let r = s.execute("file.place", &json!({"path": cut, "at": [200, 100]})).unwrap();
|
||||
let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), NodeId(r["image"].as_u64().unwrap()));
|
||||
if distorted {
|
||||
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
|
||||
s.execute("object.distort", &json!({"corners": [[0, 0], [400, 30], [360, 200], [20, 180]]})).unwrap();
|
||||
}
|
||||
let node = |s: &Session| s.doc().unwrap().doc.node(image).unwrap().clone();
|
||||
let corners = node(&s).image_corners().unwrap();
|
||||
let doc_path = dir.join("poster.vectorcraft").to_string_lossy().into_owned();
|
||||
s.execute("document.save", &json!({"path": doc_path})).unwrap();
|
||||
std::fs::write(&cut, big(&square_resources())).unwrap();
|
||||
s.execute("document.open", &json!({"path": doc_path})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let NodeKind::Image(im) = &d.node(image).unwrap().kind else { panic!("an image") };
|
||||
assert!(d.images[&im.key].is_proxy(), "the saved preview shows");
|
||||
let r = s.execute("links.update", &json!({"ids": [image.0]})).unwrap();
|
||||
assert_eq!(r["updated"], json!([image.0]), "{r}");
|
||||
let map = node(&s).image_map().unwrap();
|
||||
let squared: Vec<[f64; 2]> = [[100.0, 50.0], [300.0, 50.0], [300.0, 150.0], [100.0, 150.0]]
|
||||
.iter()
|
||||
.map(|[x, y]| map.apply(vectorcraft_geom::Point::new(*x, *y)).unwrap())
|
||||
.map(|p| [p.x, p.y])
|
||||
.collect();
|
||||
let (anchors, even_odd, held) = clip_group(&s.doc().unwrap().doc, group);
|
||||
let near =
|
||||
anchors.len() == squared.len() && anchors.iter().zip(&squared).all(|(p, q)| (p[0] - q[0]).abs() < 1e-6 && (p[1] - q[1]).abs() < 1e-6);
|
||||
assert!(near && even_odd && held == image, "distorted: {distorted}: {anchors:?} vs {squared:?}");
|
||||
assert_eq!(node(&s).image_corners().unwrap(), corners);
|
||||
}
|
||||
}
|
||||
|
||||
/// Unembed of a distorted image from a PSD file, with a path and with a folder, keeps the clip
|
||||
/// group of the clipping path that file names, drawn through its corners, and so does relinking it
|
||||
/// to the file written. Update Links reads the clipping path the file on disk keeps then, and all
|
||||
/// four corners stay where they were.
|
||||
#[test]
|
||||
fn unembed_keeps_the_clipping_path_of_a_distorted_psd() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("psd-unembed-distorted-clip");
|
||||
// An RGB file is kept as a PNG, a CMYK one as a TIFF.
|
||||
let cmyk = |resources: &[u8]| psd(1, 4, (100, 50), 8, 4, &[], resources, &[], &raw(&[&[0; 5000], &[255; 5000], &[255; 5000], &[0; 5000]]));
|
||||
let files = [("rgb", red_psd(&triangle_resources())), ("cmyk", cmyk(&triangle_resources()))];
|
||||
// The file Unembed writes, as stored, for the same kind of file clipped to the square.
|
||||
let squared_file = |kind: &str| {
|
||||
let file = if kind == "rgb" { red_psd(&square_resources()) } else { cmyk(&square_resources()) };
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
|
||||
let r = s.execute("file.place", &json!({"name": "square.psd", "dataBase64": vectorcraft_format::base64_encode(&file)})).unwrap();
|
||||
let r = s.execute("links.unembed", &json!({"id": r["image"]})).unwrap();
|
||||
vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap()
|
||||
};
|
||||
for ((kind, file), folder) in files.iter().flat_map(|f| [(f, false), (f, true)]) {
|
||||
let data = vectorcraft_format::base64_encode(file);
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
|
||||
let r = s.execute("file.place", &json!({"name": "cut.psd", "dataBase64": data, "at": [50, 25]})).unwrap();
|
||||
let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), NodeId(r["image"].as_u64().unwrap()));
|
||||
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
|
||||
s.execute("object.distort", &json!({"corners": [[0, 0], [100, 8], [90, 50], [6, 44]]})).unwrap();
|
||||
let before = clip_group(&s.doc().unwrap().doc, group);
|
||||
let corners = s.doc().unwrap().doc.node(image).unwrap().image_corners().unwrap();
|
||||
// Without an extension the image is written in the format it is stored in.
|
||||
let path = if folder {
|
||||
let out = dir.join(format!("folder-{kind}"));
|
||||
std::fs::create_dir_all(&out).unwrap();
|
||||
let r = s.execute("links.unembed", &json!({"ids": [image.0], "folder": out})).unwrap();
|
||||
r["unembedded"][0]["path"].as_str().unwrap().to_string()
|
||||
} else {
|
||||
let r = s.execute("links.unembed", &json!({"id": image.0, "path": dir.join(format!("written-{kind}"))})).unwrap();
|
||||
r["path"].as_str().unwrap().to_string()
|
||||
};
|
||||
let ext = if *kind == "rgb" { ["png"].as_slice() } else { ["tif", "tiff"].as_slice() };
|
||||
assert!(ext.contains(&super::extension(&path).as_str()), "{kind}: {path}");
|
||||
for step in ["unembed", "relink", "update"] {
|
||||
let mut want = before.0.clone();
|
||||
if step == "relink" {
|
||||
s.execute("links.relink", &json!({"ids": [image.0], "path": path})).unwrap();
|
||||
}
|
||||
if step == "update" {
|
||||
// The file on disk now keeps the square: Update Links reads it from there.
|
||||
std::fs::write(&path, squared_file(kind)).unwrap();
|
||||
let r = s.execute("links.update", &json!({"ids": [image.0]})).unwrap();
|
||||
assert_eq!(r["updated"], json!([image.0]), "{kind}: {r}");
|
||||
let map = s.doc().unwrap().doc.node(image).unwrap().image_map().unwrap();
|
||||
want = [[25.0, 12.5], [75.0, 12.5], [75.0, 37.5], [25.0, 37.5]]
|
||||
.iter()
|
||||
.map(|[x, y]| map.apply(vectorcraft_geom::Point::new(*x, *y)).unwrap())
|
||||
.map(|p| [p.x, p.y])
|
||||
.collect();
|
||||
}
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let NodeKind::Image(im) = &d.node(image).unwrap().kind else { panic!("an image") };
|
||||
assert!(im.link.is_some(), "linked to the file written");
|
||||
assert_eq!(d.node(image).unwrap().image_corners().unwrap(), corners, "{kind}, {step}, folder: {folder}");
|
||||
// The clipping path is drawn through the corners, within rounding.
|
||||
let (anchors, even_odd, held) = clip_group(d, group);
|
||||
let near =
|
||||
anchors.len() == want.len() && anchors.iter().zip(&want).all(|(p, q)| (p[0] - q[0]).abs() < 1e-6 && (p[1] - q[1]).abs() < 1e-6);
|
||||
assert!(near && (even_odd, held) == (before.1, before.2), "{kind}, {step}, folder: {folder}: {anchors:?} vs {want:?}");
|
||||
}
|
||||
}
|
||||
// A path that converts the image writes a file without the clipping path: the clip group
|
||||
// becomes a plain group of the image, as Relink to any file without one leaves it.
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
|
||||
let data = vectorcraft_format::base64_encode(&red_psd(&triangle_resources()));
|
||||
let r = s.execute("file.place", &json!({"name": "cut.psd", "dataBase64": data, "at": [50, 25]})).unwrap();
|
||||
let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), NodeId(r["image"].as_u64().unwrap()));
|
||||
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
|
||||
s.execute("object.distort", &json!({"corners": [[0, 0], [100, 8], [90, 50], [6, 44]]})).unwrap();
|
||||
s.execute("links.unembed", &json!({"id": image.0, "path": dir.join("converted.jpg")})).unwrap();
|
||||
match s.doc().unwrap().doc.node(group).map(|n| &n.kind) {
|
||||
Some(NodeKind::Group { children, clip: false }) => assert_eq!(children.iter().map(|c| c.id).collect::<Vec<_>>(), [image]),
|
||||
other => panic!("a plain group of the image: {other:?}"),
|
||||
}
|
||||
assert!(s.doc().unwrap().doc.node(image).unwrap().is_distorted_image());
|
||||
}
|
||||
|
||||
/// Unembed keeps the clip group of the clipping path an embedded PSD file's image came with, with a
|
||||
/// path and with a folder, and so do relinking to the written file, placing it and opening it.
|
||||
#[test]
|
||||
|
||||
@@ -3455,6 +3455,145 @@ fn redefining_a_graphic_style_keeps_an_edited_mark_of_a_linked_series_group() {
|
||||
assert!(marks[1..].iter().all(|m| d.node(*m).unwrap().extras().graphic_style == Some(style.id)));
|
||||
}
|
||||
|
||||
/// A column graph whose series 0 group is linked to style "Blue" (as a file can hold it) and whose first path directly
|
||||
/// inside that group is linked to style "Green" and has its look: the session, the graph, the group, series 0's paths,
|
||||
/// and the ids of "Blue" and "Green".
|
||||
fn linked_group_with_a_green_mark() -> (Session, NodeId, NodeId, Vec<NodeId>, u32, u32) {
|
||||
let (mut s, id, _, marks) = column_marks();
|
||||
let (group, _) = series_0_group(&s, id);
|
||||
let (blue, green) = blue_and_green_styles(&mut s);
|
||||
link_group_and_member(&mut s, group, &blue, marks[0], &green);
|
||||
(s, id, group, marks, blue.id, green.id)
|
||||
}
|
||||
|
||||
/// Graphic styles "Blue" (a blue fill at 50% opacity) and "Green" (a green fill at full opacity), made from one new
|
||||
/// rectangle that is linked to neither.
|
||||
fn blue_and_green_styles(s: &mut Session) -> (vectorcraft_doc::GraphicStyle, vectorcraft_doc::GraphicStyle) {
|
||||
let (rect, _) = blue_style(s, "Blue", false);
|
||||
s.execute("appearance.setItem", &json!({"ids": [rect.0], "index": top_row(s, rect, true), "color": "#00ff00", "opacity": 100})).unwrap();
|
||||
s.execute("graphicStyle.new", &json!({"id": rect.0, "name": "Green"})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
(d.graphic_style("Blue").unwrap().clone(), d.graphic_style("Green").unwrap().clone())
|
||||
}
|
||||
|
||||
/// Links `group` to `outer` with its look and `member` to `inner` with its look, as a file can hold them.
|
||||
fn link_group_and_member(
|
||||
s: &mut Session,
|
||||
group: NodeId,
|
||||
outer: &vectorcraft_doc::GraphicStyle,
|
||||
member: NodeId,
|
||||
inner: &vectorcraft_doc::GraphicStyle,
|
||||
) {
|
||||
s.edit("Link", |d, _| {
|
||||
let g = d.node_mut(group).unwrap();
|
||||
g.appearance = outer.appearance.clone().into();
|
||||
g.extras_mut().graphic_style = Some(outer.id);
|
||||
let m = d.node_mut(member).unwrap();
|
||||
m.appearance = inner.appearance.clone().into();
|
||||
m.extras_mut().graphic_style = Some(inner.id);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// Asserts that `d` holds what `was` holds for a redefinition of style "Blue": its definition, the link of `group`, the
|
||||
/// look and link of each of `members`, and everything graph `id` stores (series paints and label rows included).
|
||||
fn assert_same_redefine_state(
|
||||
d: &vectorcraft_doc::Document,
|
||||
was: &vectorcraft_doc::Document,
|
||||
id: NodeId,
|
||||
group: NodeId,
|
||||
members: &[NodeId],
|
||||
when: &str,
|
||||
) {
|
||||
assert_eq!(d.graphic_style("Blue"), was.graphic_style("Blue"), "{when}: the definition of Blue");
|
||||
assert_eq!(d.node(group).unwrap().extras().graphic_style, was.node(group).unwrap().extras().graphic_style, "{when}: the group's link");
|
||||
for m in members {
|
||||
let (a, b) = (d.node(*m).unwrap(), was.node(*m).unwrap());
|
||||
assert_eq!((&a.appearance, a.extras().graphic_style), (&b.appearance, b.extras().graphic_style), "{when}: member {m:?}");
|
||||
}
|
||||
assert_eq!(d.node(id).unwrap().extras().graph, was.node(id).unwrap().extras().graph, "{when}: what the graph stores");
|
||||
}
|
||||
|
||||
/// Redefine Graphic Style with another style's look (`from`) on a linked series group leaves a path of the group that is
|
||||
/// linked to that other style linked to it, and restyles and links the group's other paths; one undo takes the
|
||||
/// redefinition back and redo makes it again.
|
||||
#[test]
|
||||
fn redefining_a_graphic_style_from_another_style_keeps_a_mark_linked_to_it() {
|
||||
let (mut s, id, group, marks, blue, green) = linked_group_with_a_green_mark();
|
||||
let own = s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.clone();
|
||||
let look = s.doc().unwrap().doc.graphic_style("Green").unwrap().appearance.fill_paint();
|
||||
let was = s.doc().unwrap().doc.clone();
|
||||
s.execute("graphicStyle.redefine", &json!({"name": "Blue", "from": "Green"})).unwrap();
|
||||
let after = s.doc().unwrap().doc.clone();
|
||||
let first = after.node(marks[0]).unwrap();
|
||||
assert_eq!((&first.appearance, first.extras().graphic_style), (&own, Some(green)), "the mark keeps its own style");
|
||||
assert!(marks[1..].iter().all(|m| after.node(*m).unwrap().appearance.fill_paint() == look));
|
||||
assert!(marks[1..].iter().all(|m| after.node(*m).unwrap().extras().graphic_style == Some(blue)));
|
||||
assert_eq!(after.node(group).unwrap().extras().graphic_style, None);
|
||||
assert_eq!(spec(&s, id).series_paints[0].fill, Some(look), "the graph stores the new look");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_same_redefine_state(&s.doc().unwrap().doc, &was, id, group, &marks, "after one undo");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_same_redefine_state(&s.doc().unwrap().doc, &after, id, group, &marks, "after redo");
|
||||
}
|
||||
|
||||
/// Redefine Graphic Style from an object on a linked series group leaves a path of the group that is linked to another
|
||||
/// style as it is, restyles and links the group's other paths; one undo takes the redefinition back and redo makes it
|
||||
/// again.
|
||||
#[test]
|
||||
fn redefining_a_graphic_style_from_an_object_keeps_a_mark_linked_to_another_style() {
|
||||
let (mut s, id, group, marks, blue, green) = linked_group_with_a_green_mark();
|
||||
let own = s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.clone();
|
||||
let red = NodeId(s.execute("shape.rectangle", &json!({"x": 700, "y": 700, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("appearance.setItem", &json!({"ids": [red.0], "index": top_row(&s, red, true), "color": "#ff0000", "opacity": 100})).unwrap();
|
||||
let look = s.doc().unwrap().doc.node(red).unwrap().appearance.fill_paint();
|
||||
let was = s.doc().unwrap().doc.clone();
|
||||
s.execute("graphicStyle.redefine", &json!({"name": "Blue", "id": red.0})).unwrap();
|
||||
let after = s.doc().unwrap().doc.clone();
|
||||
let first = after.node(marks[0]).unwrap();
|
||||
assert_eq!((&first.appearance, first.extras().graphic_style), (&own, Some(green)), "the mark keeps its own style");
|
||||
assert!(marks[1..].iter().all(|m| after.node(*m).unwrap().appearance.fill_paint() == look));
|
||||
assert!(marks[1..].iter().all(|m| after.node(*m).unwrap().extras().graphic_style == Some(blue)));
|
||||
assert_eq!(after.node(group).unwrap().extras().graphic_style, None);
|
||||
assert_eq!(spec(&s, id).series_paints[0].fill, Some(look), "the graph stores the new look");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_same_redefine_state(&s.doc().unwrap().doc, &was, id, group, &marks, "after one undo");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_same_redefine_state(&s.doc().unwrap().doc, &after, id, group, &marks, "after redo");
|
||||
}
|
||||
|
||||
/// Redefine Graphic Style on a graph's Legend group linked to the style leaves a label of the group that is linked to
|
||||
/// another style with its look and its link, restyles and links the group's other label, and clears and unlinks the
|
||||
/// group; one undo takes the redefinition back and redo makes it again.
|
||||
#[test]
|
||||
fn redefining_a_graphic_style_keeps_a_legend_label_linked_to_another_style() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let legend = group(s.doc().unwrap().doc.node(id).unwrap(), "Legend").id;
|
||||
let labels = [text_id(&s, id, "Legend", "2024"), text_id(&s, id, "Legend", "2025")];
|
||||
let (blue, green) = blue_and_green_styles(&mut s);
|
||||
link_group_and_member(&mut s, legend, &blue, labels[0], &green);
|
||||
let own = s.doc().unwrap().doc.node(labels[0]).unwrap().appearance.clone();
|
||||
let red = NodeId(s.execute("shape.rectangle", &json!({"x": 700, "y": 700, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("appearance.setItem", &json!({"ids": [red.0], "index": top_row(&s, red, true), "color": "#ff0000", "opacity": 100})).unwrap();
|
||||
let look = s.doc().unwrap().doc.node(red).unwrap().appearance.fill_paint();
|
||||
let was = s.doc().unwrap().doc.clone();
|
||||
s.execute("graphicStyle.redefine", &json!({"name": "Blue", "id": red.0})).unwrap();
|
||||
let after = s.doc().unwrap().doc.clone();
|
||||
let kept = after.node(labels[0]).unwrap();
|
||||
assert_eq!((&kept.appearance, kept.extras().graphic_style), (&own, Some(green.id)), "the label keeps its own style");
|
||||
let other = after.node(labels[1]).unwrap();
|
||||
assert_eq!((other.appearance.fill_paint(), other.extras().graphic_style), (look, Some(blue.id)), "the other label follows");
|
||||
let g = after.node(legend).unwrap();
|
||||
assert_eq!((g.appearance.items.is_empty(), g.extras().graphic_style), (true, None), "the group is cleared and unlinked");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_same_redefine_state(&s.doc().unwrap().doc, &was, id, legend, &labels, "after one undo");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_same_redefine_state(&s.doc().unwrap().doc, &after, id, legend, &labels, "after redo");
|
||||
}
|
||||
|
||||
/// Series `index`'s group: its object opacity and blend mode, and those of each path directly inside it.
|
||||
fn group_transparency(s: &Session, id: NodeId, index: u32) -> ((f32, BlendMode), Vec<(f32, BlendMode)>) {
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
|
||||
@@ -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
|
||||
|
||||
+114
-54
@@ -33,7 +33,7 @@ use vectorcraft_doc::{
|
||||
Appearance, DataValue, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeId, NodeKind, PageBox, PlacedDocument, PlacementOptions,
|
||||
StoredPlace, StoredRoot,
|
||||
};
|
||||
use vectorcraft_geom::{Affine, FillRule, PathData, Rect, shapes};
|
||||
use vectorcraft_geom::{Affine, FillRule, Homography, PathData, Rect, shapes};
|
||||
|
||||
use super::fileio::{self, RasterImage, absolute_path, file_created, file_stamp, read_file, write_file};
|
||||
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, ids_param, object_param, str_param, switch_or, text_param};
|
||||
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Update Links",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. Images and placed documents inside symbols, graph designs, patterns, opacity masks and the art of stored brushes have ids of their own, as links.list gives them; those that show the same content as one read again are read again too. One undo step → {updated: [ids], missing: [ids], warnings?: [a DCS file's spot plate whose ink a swatch of the document already names, as file.place warns]}",
|
||||
"{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. Images and placed documents inside symbols, graph designs, patterns, opacity masks and the art of stored brushes have ids of their own, as links.list gives them; those that show the same content as one read again are read again too. An image changed by Perspective Distort or Free Distort keeps its corners, with the file's pixels between them, and its Placement Options do not apply; the clipping path its file names is drawn through the corners, and a clip group of the old file's clipping path gets the new one, or becomes a plain group when the file names none. One undo step → {updated: [ids], missing: [ids], warnings?: [a DCS file's spot plate whose ink a swatch of the document already names, as file.place warns]}",
|
||||
has_doc,
|
||||
update
|
||||
),
|
||||
@@ -72,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Relink",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, scope?: selected (default: ids) | all (ids and every other object linked to the same file as one of them, in the layers, opacity-mask art, symbols, graph designs, patterns and the art of stored brushes) | missingInFolder (with path: ids, then every other missing link whose file name is in path's folder, each to the file of its name there; names not there are in notFound; with copy, only images are looked for) | each (with paths), paths?: [{ids, path}] (with scope each, in place of ids, path and folder: each link to its own file; an id in two entries is an error), copy?: false (with path or paths, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used; an error for a DCS file that reads plate files of its own), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy; to is the file name alone when the document's folder is outside the automation read roots), warnings?: (as links.update's)}",
|
||||
"{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, scope?: selected (default: ids) | all (ids and every other object linked to the same file as one of them, in the layers, opacity-mask art, symbols, graph designs, patterns and the art of stored brushes) | missingInFolder (with path: ids, then every other missing link whose file name is in path's folder, each to the file of its name there; names not there are in notFound; with copy, only images are looked for) | each (with paths), paths?: [{ids, path}] (with scope each, in place of ids, path and folder: each link to its own file; an id in two entries is an error), copy?: false (with path or paths, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used; an error for a DCS file that reads plate files of its own), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. An image changed by Perspective Distort or Free Distort keeps its corners, with the new file's pixels between them, whatever preserve or its Placement Options say, and its clipping is handled as links.update handles it. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy; to is the file name alone when the document's folder is outside the automation read roots), warnings?: (as links.update's, and, when preserve is given, one naming the distorted images it was not applied to)}",
|
||||
has_doc,
|
||||
relink
|
||||
),
|
||||
@@ -99,7 +99,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Embed Image",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [image or placed document ids] (default: the selected linked ones)} break the links (the Links panel's Break Link): images keep the linked files' pixels in the document; a placed document becomes an editable copy of its art, as placing its file without link gives (its symbols, patterns, swatches and images joining the document). An image whose file can't be found and that shows the saved preview, or a placed document whose file can't be read or changed, stays linked: relink or update it first. An image placed from a DCS file can't be embedded (an error, and nothing changes). One undo step → {embedded: [ids], missing: [ids]}",
|
||||
"{ids?: [image or placed document ids] (default: the selected linked ones)} break the links (the Links panel's Break Link): images keep the linked files' pixels in the document; a placed document becomes an editable copy of its art, as placing its file without link gives (its symbols, patterns, swatches and images joining the document). An image whose file can't be found and that shows the saved preview, or a placed document whose file can't be read or changed, stays linked: relink or update it first. An image placed from a DCS file can't be embedded (an error, and nothing changes). An image changed by Perspective Distort or Free Distort keeps its corners. One undo step → {embedded: [ids], missing: [ids]}",
|
||||
has_doc,
|
||||
embed
|
||||
),
|
||||
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Unembed",
|
||||
[],
|
||||
None,
|
||||
"{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (instead of id; one id is the same as id), folder?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds; written as stored (here and with folder), an image from a PSD or PSB file keeps the clip group of the clipping path that file names, and the file written keeps the path, so Open, Place, Relink and Update Links read the file with that clip group. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to). With folder: write each embedded image of ids or id (default: the selected embedded images) to a new file in folder, as stored (as PNG when that format is not one of VectorCraft's raster file formats), named after the image (characters a file name can't hold become _; Image when nothing is left), with Name 2 … Name 99 when the name is taken; a file already there is never replaced. Linked images among ids are left as they are. Each image links to its file and keeps its bounds. One undo step (undo does not remove the files); when a file can't be written, the files this call wrote are removed and nothing changes → {unembedded: [{id, path}], skipped: [ids of linked images]}; id with ids, path with folder, and ids of more or fewer than one image without folder are errors",
|
||||
"{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (instead of id; one id is the same as id), folder?} write the image's pixels to the file at path and link the image to it, keeping its bounds (an image changed by Perspective Distort or Free Distort keeps its corners). The image is written as stored (PNG, JPEG, GIF, WebP or TIFF; as PNG when that format is not one of VectorCraft's raster file formats) when path has no extension or names the stored format, and converted when path ends in another of .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp. Written as stored (here and with folder), an image from a PSD or PSB file keeps the clip group of the clipping path that file names, and the file written keeps the path, so Open, Place, Relink and Update Links read the file with that clip group (drawn through a distorted image's corners); a converted file holds no clipping path, and the clip group becomes a plain group. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to). With folder: write each embedded image of ids or id (default: the selected embedded images) to a new file in folder, as stored (as PNG when that format is not one of VectorCraft's raster file formats), named after the image (characters a file name can't hold become _; Image when nothing is left), with Name 2 … Name 99 when the name is taken; a file already there is never replaced. Linked images among ids are left as they are. Each image links to its file and keeps its bounds (a distorted image its corners). One undo step (undo does not remove the files); when a file can't be written, the files this call wrote are removed and nothing changes → {unembedded: [{id, path}], skipped: [ids of linked images]}; id with ids, path with folder, and ids of more or fewer than one image without folder are errors",
|
||||
has_doc,
|
||||
unembed
|
||||
),
|
||||
@@ -609,13 +609,14 @@ pub(crate) fn kept_unread(bytes: &[u8]) -> bool {
|
||||
/// `blob`, an image [`fileio::raster_image`] read from a file, ready to keep. When `unread` (the
|
||||
/// file is one [`kept_unread`] names), its pixels are decoded once to check that they can be read,
|
||||
/// and a `linked` image's preview is made from that decode ([`ImageBlob::checked_with_proxy`]);
|
||||
/// otherwise a `linked` image gets its preview ([`ImageBlob::with_proxy`]). An error when the
|
||||
/// pixels can't be read.
|
||||
/// otherwise a `linked` image gets its preview ([`ImageBlob::with_proxy`]). The preview keeps the
|
||||
/// clipping path the image keeps ([`fileio::preview_with_clip`]). An error when the pixels can't
|
||||
/// be read.
|
||||
pub(crate) fn readable(blob: ImageBlob, unread: bool, linked: bool) -> Result<ImageBlob> {
|
||||
if !unread {
|
||||
return Ok(if linked { blob.with_proxy() } else { blob });
|
||||
return Ok(if linked { fileio::preview_with_clip(blob.with_proxy()) } else { blob });
|
||||
}
|
||||
blob.checked_with_proxy(linked).ok_or_else(|| EngineError::Other("the image's pixels can't be read".into()))
|
||||
blob.checked_with_proxy(linked).map(fileio::preview_with_clip).ok_or_else(|| EngineError::Other("the image's pixels can't be read".into()))
|
||||
}
|
||||
|
||||
/// [`readable`], and the pixels it decoded are kept in the image store the renderers share
|
||||
@@ -626,6 +627,7 @@ pub(crate) fn readable_and_kept(blob: ImageBlob, unread: bool, linked: bool) ->
|
||||
return readable(blob, unread, linked);
|
||||
}
|
||||
let (blob, pixels) = blob.checked_with_pixels(linked).ok_or_else(|| EngineError::Other("the image's pixels can't be read".into()))?;
|
||||
let blob = fileio::preview_with_clip(blob);
|
||||
if let Some(pixels) = pixels {
|
||||
vectorcraft_render::keep_decoded_image(&blob, pixels);
|
||||
}
|
||||
@@ -792,13 +794,20 @@ fn clip_to(
|
||||
new_xf: Affine,
|
||||
held: Option<(&PathData, FillRule)>,
|
||||
) -> ClipTo {
|
||||
let old = old_clip.filter(|_| held.is_some()).map(|(path, rule)| (path.transformed(old_xf), *rule));
|
||||
let file = img.clip.as_ref().map(|(path, rule)| (path.transformed(new_xf), *rule));
|
||||
placed_clip_to(old.as_ref(), clip, file, held)
|
||||
}
|
||||
|
||||
/// [`clip_to`] with the clipping paths of the old file (`old`) and of the new file (`file`) already
|
||||
/// on the page.
|
||||
fn placed_clip_to(old: Option<&FileClip>, clip: Option<Clip>, file: Option<FileClip>, held: Option<(&PathData, FillRule)>) -> ClipTo {
|
||||
// Whether the clip group holding just the image is the old file's: a clipping path whose fill
|
||||
// rule was changed in the document is not.
|
||||
let file_held = match (old_clip, held) {
|
||||
(Some((old, old_rule)), Some((held, rule))) => rule == *old_rule && same_path(&old.transformed(old_xf), held),
|
||||
let file_held = match (old, held) {
|
||||
(Some((old, old_rule)), Some((held, rule))) => rule == *old_rule && same_path(old, held),
|
||||
_ => false,
|
||||
};
|
||||
let file = img.clip.as_ref().map(|(path, rule)| (path.transformed(new_xf), *rule));
|
||||
if let Some(clip) = clip {
|
||||
let placement = clip_shape(clip);
|
||||
return match file {
|
||||
@@ -1211,14 +1220,44 @@ pub(crate) fn set_image_from_path(d: &mut Document, id: NodeId, path: &str, doc_
|
||||
install(d, &[id], read, Some(Preserve::Bounds), None)
|
||||
}
|
||||
|
||||
/// Distorted image `im` shows the file read for `link` (`img`) and keeps its corners and its
|
||||
/// clipping: the new pixels fill them. Its transform is scaled to the new pixel size, so a reader
|
||||
/// that places it by the transform still gives it its old size.
|
||||
fn refill_distorted(im: &mut ImageObject, link: &LinkInfo, img: &RasterImage) {
|
||||
if (img.width, img.height) != (im.width, im.height) && img.width > 0 && img.height > 0 {
|
||||
im.xf *= Affine::scale_non_uniform(f64::from(im.width) / f64::from(img.width), f64::from(im.height) / f64::from(img.height));
|
||||
/// Distorted image `n` shows the file read for `link` (`img`) and keeps its corners: the new pixels
|
||||
/// fill them. Its transform is scaled to the new pixel size, so a reader that places it by the
|
||||
/// transform still gives it its old size. Its Placement Options do not apply. The result is what
|
||||
/// happens to its clip, as [`clip_to`] decides from the clipping path of the clip group holding
|
||||
/// just it (`held`): the clipping paths of its old file (`old_clip`, in its old pixels) and of the
|
||||
/// new file (`img.clip`, else the path kept in its stored PNG or TIFF, as Unembed writes it:
|
||||
/// [`file_clip`]) are mapped to the page through its corners, anchors and handles alike, as a
|
||||
/// distort maps a path's.
|
||||
fn refill_distorted(n: &mut Node, old_clip: Option<&FileClip>, link: &LinkInfo, img: &RasterImage, held: Option<(&PathData, FillRule)>) -> ClipTo {
|
||||
let old = old_clip.filter(|_| held.is_some()).and_then(|(path, rule)| Some((warped(path, &n.image_map()?)?, *rule)));
|
||||
if let NodeKind::Image(im) = &mut n.kind {
|
||||
if (img.width, img.height) != (im.width, im.height) && img.width > 0 && img.height > 0 {
|
||||
im.xf *= Affine::scale_non_uniform(f64::from(im.width) / f64::from(img.width), f64::from(im.height) / f64::from(img.height));
|
||||
}
|
||||
(im.key, im.width, im.height, im.link) = (img.key.clone(), img.width, img.height, Some(link.clone()));
|
||||
}
|
||||
(im.key, im.width, im.height, im.link) = (img.key.clone(), img.width, img.height, Some(link.clone()));
|
||||
let file = img.clip.clone().or_else(|| file_clip(&img.blob)).and_then(|(path, rule)| Some((warped(&path, &n.image_map()?)?, rule)));
|
||||
placed_clip_to(old.as_ref(), None, file, held)
|
||||
}
|
||||
|
||||
/// `path` with its anchors and handles mapped through `map` as a distort maps a path's points
|
||||
/// (`xform::Projective::apply`): a point on the map's horizon is mapped as if a billionth in front
|
||||
/// of it, and one past it to the far side. `None` when a point maps to no finite page point.
|
||||
fn warped(path: &PathData, map: &Homography) -> Option<PathData> {
|
||||
let [[a, b, c], [d, e, f], [g, h, i]] = map.0;
|
||||
let apply = |p: vectorcraft_geom::Point| {
|
||||
let w = g * p.x + h * p.y + i;
|
||||
let w = if w.abs() < 1e-9 { 1e-9_f64.copysign(w) } else { w };
|
||||
let q = vectorcraft_geom::Point::new((a * p.x + b * p.y + c) / w, (d * p.x + e * p.y + f) / w);
|
||||
q.is_finite().then_some(q)
|
||||
};
|
||||
let mut out = path.clone();
|
||||
for sp in &mut out.subpaths {
|
||||
for anchor in &mut sp.anchors {
|
||||
(anchor.p, anchor.h_in, anchor.h_out) = (apply(anchor.p)?, apply(anchor.h_in)?, apply(anchor.h_out)?);
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Image objects `ids` (in the layers or outside them) show the file read for `link` (`img`), each
|
||||
@@ -1245,12 +1284,15 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio
|
||||
let mut make = |n: &Node, held: Option<(&PathData, FillRule)>| {
|
||||
let mut n = n.clone();
|
||||
let mut clip = ClipTo::Keep;
|
||||
let distorted = n.is_distorted_image();
|
||||
if n.is_distorted_image() {
|
||||
let old_clip = match &n.kind {
|
||||
NodeKind::Image(im) => old.get(&im.key).and_then(|(_, clip)| clip.clone()),
|
||||
_ => None,
|
||||
};
|
||||
let clip = refill_distorted(&mut n, old_clip.as_ref(), &link, &img, held);
|
||||
return (n, clip);
|
||||
}
|
||||
if let NodeKind::Image(im) = &mut n.kind {
|
||||
if distorted {
|
||||
refill_distorted(im, &link, &img);
|
||||
return (n, clip);
|
||||
}
|
||||
let o = PlacementOptions { preserve: force.unwrap_or(im.placement.preserve), ..im.placement };
|
||||
let size = |w: u32, h: u32| (w as f64, h as f64);
|
||||
let (old_pt, old_clip) = match old.get(&im.key) {
|
||||
@@ -1267,10 +1309,13 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio
|
||||
}
|
||||
for id in ids {
|
||||
if d.node(*id).is_some_and(Node::is_distorted_image) {
|
||||
if let Some(n) = d.node_mut(*id)
|
||||
&& let NodeKind::Image(im) = &mut n.kind
|
||||
{
|
||||
refill_distorted(im, &link, &img);
|
||||
let old_clip = match d.node(*id).map(|n| &n.kind) {
|
||||
Some(NodeKind::Image(im)) => d.images.get(&im.key).and_then(file_clip),
|
||||
_ => None,
|
||||
};
|
||||
let held = clip_path_of(d, *id).map(|(path, rule)| (path.clone(), rule));
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
clips.push((*id, refill_distorted(n, old_clip.as_ref(), &link, &img, held.as_ref().map(|(path, rule)| (path, *rule)))));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
@@ -1625,7 +1670,7 @@ fn resolve_links(d: &mut Document, base: LinkBase, update: bool, low_res_proxy_e
|
||||
store_image(d, &g.key, blob, true);
|
||||
} else if let Some(b) = d.images.get(&g.key).filter(|b| b.proxy.is_none()) {
|
||||
// Linked before links kept a preview.
|
||||
let b = b.clone().with_proxy();
|
||||
let b = fileio::preview_with_clip(b.clone().with_proxy());
|
||||
d.images.insert(g.key.clone(), b);
|
||||
}
|
||||
// Found away from its path, or read again: the link follows.
|
||||
@@ -2091,9 +2136,6 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
// Whether the images were found as the missing links (nothing selected, a folder given) rather
|
||||
// than named or selected.
|
||||
let mut found_missing = false;
|
||||
let mut ids: Vec<NodeId> = match (&each, ids_param(p, "ids", C)?) {
|
||||
(Some(each), _) => each.iter().flat_map(|(ids, _)| ids.iter().copied()).collect(),
|
||||
(None, Some(ids)) => ids,
|
||||
@@ -2101,7 +2143,6 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let selected: Vec<NodeId> = st.selection.objects.iter().copied().filter(|id| image(id).is_some()).collect();
|
||||
match folder_param {
|
||||
Some(_) if selected.is_empty() => {
|
||||
found_missing = true;
|
||||
groups(&st.doc, None).into_iter().filter(|g| probe(g, LinkBase::of(st)).0 == Status::Missing).flat_map(|g| g.ids).collect()
|
||||
}
|
||||
_ => selected,
|
||||
@@ -2114,11 +2155,6 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if ids.is_empty() {
|
||||
return Err(bad(C, "select the images to relink, or pass ids"));
|
||||
}
|
||||
// A named or selected distorted image is refused before a folder is searched, whether or not
|
||||
// its file is found there.
|
||||
if !found_missing && let Some(id) = ids.iter().find(|id| stored(&doc, **id).is_some_and(Node::is_distorted_image)) {
|
||||
return Err(super::xform::distorted_image_error(C, *id));
|
||||
}
|
||||
// All Instances: the other stored objects linked to the same files, each once.
|
||||
if scope == Scope::All {
|
||||
let paths: BTreeSet<&str> = ids.iter().filter_map(|id| image(id).flatten()).map(|l| l.path.as_str()).collect();
|
||||
@@ -2163,11 +2199,6 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
(None, None, None) => return Err(bad(C, "give path (a file) or folder")),
|
||||
}
|
||||
// A new file's placement options place a plain image: a distorted one is left as it is.
|
||||
let distorted = files.iter().flat_map(|(ids, _)| ids).find(|id| stored(&doc, **id).is_some_and(Node::is_distorted_image));
|
||||
if let Some(id) = distorted {
|
||||
return Err(super::xform::distorted_image_error(C, *id));
|
||||
}
|
||||
// Every file is read and checked before any is copied.
|
||||
let mut checked = vec![];
|
||||
for (ids, path) in files {
|
||||
@@ -2227,8 +2258,10 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
let relinked: Vec<u64> = reads.iter().flat_map(|(ids, _)| ids_json(ids)).collect();
|
||||
let unpreserved = preserve.and_then(|_| unpreserved_note(&doc, &reads));
|
||||
drop(doc);
|
||||
let warnings = spot_swatch_notes(&s.doc()?.doc, reads.iter().map(|(_, read)| read));
|
||||
let mut warnings = spot_swatch_notes(&s.doc()?.doc, reads.iter().map(|(_, read)| read));
|
||||
warnings.extend(unpreserved);
|
||||
if !reads.is_empty() {
|
||||
s.edit("Relink", |d, _| editing_brush_art(d, |d| reads.into_iter().try_for_each(|(ids, read)| install_read(d, &ids, read, preserve, None))))?;
|
||||
}
|
||||
@@ -2251,6 +2284,23 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The warning that Relink's `preserve` was not applied to the images of `reads` changed by
|
||||
/// Perspective Distort or Free Distort, which keep their corners, naming them; `None` when there
|
||||
/// are none.
|
||||
fn unpreserved_note(doc: &Document, reads: &[(Vec<NodeId>, Read)]) -> Option<String> {
|
||||
let ids: Vec<String> = reads
|
||||
.iter()
|
||||
.filter(|(_, read)| matches!(read, Read::Image(_)))
|
||||
.flat_map(|(ids, _)| ids)
|
||||
.filter(|id| stored(doc, **id).is_some_and(Node::is_distorted_image))
|
||||
.map(|id| id.0.to_string())
|
||||
.collect();
|
||||
let images = if ids.len() == 1 { "image" } else { "images" };
|
||||
(!ids.is_empty()).then(|| {
|
||||
format!("preserve was not applied to {images} {}: an image changed by Perspective Distort or Free Distort keeps its corners", ids.join(", "))
|
||||
})
|
||||
}
|
||||
|
||||
/// `links.relink {scope: "missingInFolder"}`: the other missing links of `st` (not `given`; only
|
||||
/// images when `images_only`, as copy takes), each added to `files` with the file of its name in
|
||||
/// the folder of the first file there; names not there go to `not_found`.
|
||||
@@ -2630,9 +2680,6 @@ fn embed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if ids.is_empty() {
|
||||
return Err(bad(C, "select the linked images or placed documents, or pass ids"));
|
||||
}
|
||||
if let Some(id) = ids.iter().find(|id| stored(&doc, **id).is_some_and(Node::is_distorted_image)) {
|
||||
return Err(super::xform::distorted_image_error(C, *id));
|
||||
}
|
||||
// A DCS file's plates print from its file.
|
||||
let separated = |id: &NodeId| match kind(id) {
|
||||
Some(NodeKind::Image(im)) => st.doc.images.get(&im.key).is_some_and(ImageBlob::is_separated),
|
||||
@@ -2761,11 +2808,8 @@ fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if im.link.is_some() {
|
||||
return Err(bad(C, format!("image {} is linked already", id.0)));
|
||||
}
|
||||
if n.is_distorted_image() {
|
||||
return Err(super::xform::distorted_image_error(C, id));
|
||||
}
|
||||
let blob = st.doc.images.get(&im.key).filter(|b| !b.is_proxy()).ok_or_else(|| bad(C, "the image's pixels aren't in the document"))?;
|
||||
// As stored (PNG, JPEG, GIF, WebP), unless the path names another format.
|
||||
// As stored (PNG, JPEG, GIF, WebP, or TIFF for an image that keeps CMYK inks), unless the path names another format.
|
||||
let stored = stored_extension(blob);
|
||||
let path = str_param(p, "path");
|
||||
let ext = match path.map(fileio::extension) {
|
||||
@@ -2815,9 +2859,6 @@ fn unembed_to_folder(s: &mut Session, p: &Value, ids: Option<Vec<NodeId>>) -> Re
|
||||
skipped.push(id);
|
||||
continue;
|
||||
}
|
||||
if n.is_distorted_image() {
|
||||
return Err(super::xform::distorted_image_error(C, id));
|
||||
}
|
||||
let blob = st.doc.images.get(&im.key).filter(|b| !b.is_proxy()).ok_or_else(|| bad(C, "the image's pixels aren't in the document"))?;
|
||||
embedded.push((id, n.display_name(), blob));
|
||||
}
|
||||
@@ -3137,4 +3178,23 @@ mod tests {
|
||||
let long = unembed_stem(&"é".repeat(200));
|
||||
assert!(long.len() <= 150 && long.chars().all(|c| c == 'é'), "{}", long.len());
|
||||
}
|
||||
|
||||
/// A clipping path mapped through a distorted image's corners keeps the points that lie on or
|
||||
/// past the map's horizon, each mapped as a distort maps a path's point.
|
||||
#[test]
|
||||
fn points_past_the_horizon_are_mapped_as_a_distort_maps_them() {
|
||||
use vectorcraft_geom::{Anchor, Point, SubPath};
|
||||
// w = 1 + x / 100: the horizon is the line x = -100.
|
||||
let map = Homography([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.01, 0.0, 1.0]]);
|
||||
let (at, handle, on) = (Point::new(0.0, 0.0), Point::new(-200.0, 0.0), Point::new(-100.0, 5.0));
|
||||
assert!(map.apply(handle).is_none() && map.apply(on).is_none());
|
||||
let path = PathData::new(vec![SubPath::new(vec![Anchor::smooth(at, handle), Anchor::corner(on)], false)]);
|
||||
let out = warped(&path, &map).expect("a path");
|
||||
let (first, second) = (out.subpaths[0].anchors[0], out.subpaths[0].anchors[1]);
|
||||
assert_eq!((first.p, first.h_in), (at, Point::new(200.0 / 3.0, 0.0)));
|
||||
// w = -1: the handle maps to the far side.
|
||||
assert_eq!(first.h_out, Point::new(200.0, 0.0));
|
||||
// w = 0 is taken as a billionth.
|
||||
assert!(second.p.is_finite() && (second.p.x.abs() - 1e11).abs() < 1.0 && (second.p.y.abs() - 5e9).abs() < 1.0, "{:?}", second.p);
|
||||
}
|
||||
}
|
||||
@@ -1188,8 +1188,8 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let doc = super::links::with_brush_art(&st.doc);
|
||||
let n = doc.stored_node(id).map(|(n, _)| &**n).ok_or(EngineError::NoNode(id))?;
|
||||
let NodeKind::Image(im) = &n.kind else { return Err(bad(C, format!("object {} is not an image", id.0))) };
|
||||
// Effective resolution, taken at the middle of a distorted image.
|
||||
let ppi = effective_ppi(vectorcraft_doc::image_quad::nearest_affine(n).unwrap_or(im.xf));
|
||||
// Effective resolution at the middle of a distorted image.
|
||||
let xf = vectorcraft_doc::image_quad::nearest_affine(n).unwrap_or(im.xf);
|
||||
let size = n.geometric_bounds().unwrap_or_default();
|
||||
// A linked file outside the read roots of the caller asking now is left unnamed, as in Link Info.
|
||||
let doc_path = super::links::LinkBase::of(st).doc;
|
||||
@@ -1201,7 +1201,7 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"colorMode": st.doc.images.get(&im.key).map_or("RGB", |b| color_mode(&b.bytes)),
|
||||
"pixelWidth": im.width,
|
||||
"pixelHeight": im.height,
|
||||
"ppi": ppi,
|
||||
"ppi": effective_ppi(xf),
|
||||
"width": size.width(),
|
||||
"height": size.height(),
|
||||
}))
|
||||
|
||||
@@ -1044,7 +1044,7 @@ fn load_folder(s: &Session, folder: &str) -> Value {
|
||||
if r.disabled_changed {
|
||||
s.store_disabled_plugins_in(&turn);
|
||||
}
|
||||
json!({"folder": folder, "loaded": r.loaded, "failed": r.failed.iter().map(|(f, e)| json!({"file": f, "error": e})).collect::<Vec<_>>()})
|
||||
json!({"folder": folder, "loaded": r.loaded, "failed": r.failed.iter().map(|(f, e)| json!({"file": f, "error": e})).collect::<Vec<_>>(), "leftOut": r.left_out})
|
||||
}
|
||||
Err(e) => json!({"folder": folder, "error": e.to_string()}),
|
||||
}
|
||||
@@ -1270,7 +1270,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"List Plug-ins",
|
||||
[],
|
||||
None,
|
||||
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}]} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
|
||||
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
|
||||
always,
|
||||
list
|
||||
),
|
||||
@@ -1333,7 +1333,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reload Plug-ins",
|
||||
["Object", "Plug-ins"],
|
||||
None,
|
||||
"{path?: a folder (default: the Additional Plug-ins Folder preference)} install every *.wasm in it (desktop; a bad module, and one disabled with plugin.setEnabled, is reported and skipped, and so are a heavy filter and a plug-in that lists permissions the user hasn't granted this very module, its bytes included; an error in Safe Mode) → {folder, loaded: [id], failed: [{file, error}]}",
|
||||
"{path?: a folder (default: the Additional Plug-ins Folder preference)} install every *.wasm in it, the first 1,000 by file name (desktop; a bad module, one that isn't a regular file, and one disabled with plugin.setEnabled, is reported and skipped, and so are a heavy filter and a plug-in that lists permissions the user hasn't granted this very module, its bytes included; an error in Safe Mode) → {folder, loaded: [id], failed: [{file, error}], leftOut: the count of *.wasm files past the first 1,000, not tried}",
|
||||
always,
|
||||
reload
|
||||
),
|
||||
|
||||
@@ -89,11 +89,13 @@ fn check(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
continue;
|
||||
};
|
||||
let bounds = doc.node(source).and_then(|n| vectorcraft_render::painted_bounds(&doc, n));
|
||||
// A distorted image is measured at its middle, as Link Info measures it.
|
||||
let xf = doc.node(source).and_then(vectorcraft_doc::image_quad::nearest_affine).unwrap_or(im.xf);
|
||||
let ppi = context
|
||||
.pages
|
||||
.iter()
|
||||
.filter(|(area, _)| bounds.is_some_and(|b| area.intersect(b).area() > 0.0))
|
||||
.map(|(_, to_page)| super::place::effective_ppi(*to_page * im.xf))
|
||||
.map(|(_, to_page)| super::place::effective_ppi(*to_page * xf))
|
||||
.reduce(|[a, b], [c, d]| [a.min(c), b.min(d)]);
|
||||
let Some(ppi) = ppi else {
|
||||
resolution_unchecked += 1;
|
||||
|
||||
+581
-75
@@ -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,
|
||||
|
||||
@@ -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", ¶ms).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
|
||||
|
||||
@@ -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
|
||||
),
|
||||
@@ -76,7 +76,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Redefine Graphic Style",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{name?, id?} | {name, from} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object (a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own: the topmost path directly in it; a graph's Axes or Legend group: its topmost line or label); the objects still linked to it update, and that object becomes linked. With `from`, the style takes the look of the style named `from` (its fills, strokes, effects, opacity, blend mode, isolate and knockout) and keeps its own name and place; `from` and the objects linked to it stay as they are, `from` naming the style itself or a style with the same look changes nothing, and `from` with `id` is an error. The art of a graph design in a series keeps its look and is unlinked, as the source or as a linked object. A linked graph series group passes the style to the paths directly in it, a linked Axes group to its lines and labels and a linked Legend group to its labels, other than the source and paths linked to the style whose look was edited, and is left cleared (as appearance.clear) and unlinked. On a linked path directly in a graph series, 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: 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 → {name}",
|
||||
"{name?, id?} | {name, from} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object (a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own: the topmost path directly in it; a graph's Axes or Legend group: its topmost line or label); the objects still linked to it update, and that object becomes linked. With `from`, the style takes the look of the style named `from` (its fills, strokes, effects, opacity, blend mode, isolate and knockout) and keeps its own name and place; `from` and the objects linked to it stay as they are, `from` naming the style itself or a style with the same look changes nothing, and `from` with `id` is an error. The art of a graph design in a series keeps its look and is unlinked, as the source or as a linked object. A linked graph series group passes the style to the paths directly in it, a linked Axes group to its lines and labels and a linked Legend group to its labels, other than the source, paths linked to the style whose look was edited and members linked to another style, and is left cleared (as appearance.clear) and unlinked. On a linked path directly in a graph series, 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: 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 → {name}",
|
||||
has_doc,
|
||||
style_redefine
|
||||
),
|
||||
@@ -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()
|
||||
}
|
||||
@@ -539,10 +554,13 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
linked.into_iter().partition(|nid| !super::graph::is_design_art(d, *nid) && d.node(*nid).is_some_and(|n| in_sync(n, &old)));
|
||||
set_link(d, &edited, None);
|
||||
// A linked graph series group passes the style to the paths directly inside it, so the graph stores it, and
|
||||
// goes back to the empty appearance the graph draws it with. The source and the edited paths keep their look.
|
||||
// goes back to the empty appearance the graph draws it with; a linked Axes or Legend group does the same with its
|
||||
// lines and labels. The source and the edited paths keep their look, and a member linked to another style keeps
|
||||
// its look and its link.
|
||||
let mut follow_marks = super::graph::series_group_marks(d, &follow);
|
||||
let edited: HashSet<NodeId> = edited.into_iter().collect();
|
||||
follow_marks.retain(|nid| Some(*nid) != src && !edited.contains(nid));
|
||||
let takes_style = |nid: NodeId| d.node(nid).is_some_and(|n| n.extras().graphic_style.is_none_or(|g| g == id));
|
||||
follow_marks.retain(|nid| Some(*nid) != src && !edited.contains(nid) && takes_style(*nid));
|
||||
super::appearance::clear_stood_for(d, &super::appearance::stood_for(&follow, &follow_marks));
|
||||
let g = d.graphic_styles[i].clone();
|
||||
let mut shared = None;
|
||||
|
||||
@@ -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))
|
||||
})?;
|
||||
|
||||
@@ -112,6 +112,7 @@ mod live;
|
||||
mod livecorners;
|
||||
mod maskview;
|
||||
pub(super) mod menucmds;
|
||||
mod mesh_picks;
|
||||
mod nativefile;
|
||||
mod newart;
|
||||
mod newdoc;
|
||||
|
||||
@@ -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"] {
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -220,6 +220,53 @@ fn update_link_takes_the_files_new_clipping_path() {
|
||||
assert!((after - before / 2.0).abs() < 1e-6, "the clipping path follows the file: {before} → {after}");
|
||||
}
|
||||
|
||||
/// For an image changed by Perspective Distort or Free Distort, Update Links and Relink draw the
|
||||
/// DCS file's new clipping path through the image's corners, and a file without one leaves a plain
|
||||
/// group.
|
||||
#[test]
|
||||
fn update_and_relink_draw_the_files_clipping_path_through_a_distorted_images_corners() {
|
||||
let dir = temp_dir("distorted-clip");
|
||||
let path = write(&dir, "pic.eps", &two_plates());
|
||||
let mut s = session();
|
||||
let r = s.execute("file.place", &json!({ "path": path, "at": [100, 100] })).unwrap();
|
||||
let group = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
let id = image_of(&s, &r["ids"][0]).id;
|
||||
s.execute("select.set", &json!({ "ids": [group.0] })).unwrap();
|
||||
s.execute("object.distort", &json!({ "corners": [[100, 100], [160, 104], [150, 140], [96, 136]] })).unwrap();
|
||||
let node = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
assert!(node(&s).is_distorted_image());
|
||||
let corners = node(&s).image_corners().unwrap();
|
||||
// The clip group's path anchors, and points of the 2 × 2 pixels where the corners put them.
|
||||
let anchors = |s: &Session| {
|
||||
let NodeKind::Group { children, clip: true } = &s.doc().unwrap().doc.node(group).unwrap().kind else { panic!("a clipping group") };
|
||||
let NodeKind::Path { path, clipping: true, .. } = &children[0].kind else { panic!("a clipping path") };
|
||||
path.anchors().map(|(_, _, a)| a.p).collect::<Vec<_>>()
|
||||
};
|
||||
let on_page = |s: &Session, x: f64| {
|
||||
let map = node(s).image_map().unwrap();
|
||||
[(0.0, 0.0), (x, 0.0), (x, 2.0), (0.0, 2.0)].map(|(px, py)| map.apply(vectorcraft_geom::Point::new(px, py)).unwrap())
|
||||
};
|
||||
let matches = |found: &[vectorcraft_geom::Point], want: &[vectorcraft_geom::Point]| {
|
||||
found.len() == want.len() && want.iter().all(|w| found.iter().any(|f| f.distance(*w) < 1e-6))
|
||||
};
|
||||
assert!(matches(&anchors(&s), &on_page(&s, 1.0)), "the left half: {:?} vs {:?}", anchors(&s), on_page(&s, 1.0));
|
||||
// The same file, its composite drawn through the left quarter of the page (same length).
|
||||
let quarter = String::from_utf8(two_plates()).unwrap().replacen("10 0 lineto 10 10 lineto", " 5 0 lineto 5 10 lineto", 1);
|
||||
std::fs::write(&path, quarter.as_bytes()).unwrap();
|
||||
s.execute("links.update", &json!({ "ids": [id.0] })).unwrap();
|
||||
assert!(matches(&anchors(&s), &on_page(&s, 0.5)), "the left quarter: {:?} vs {:?}", anchors(&s), on_page(&s, 0.5));
|
||||
assert_eq!(node(&s).image_corners().unwrap(), corners);
|
||||
// Relink to a file whose composite has no clipping path.
|
||||
let unclipped = String::from_utf8(two_plates()).unwrap().replacen("closepath clip newpath", "closepath newpath ", 1);
|
||||
let other = write(&dir, "other.eps", unclipped.as_bytes());
|
||||
s.execute("links.relink", &json!({ "ids": [id.0], "path": other })).unwrap();
|
||||
match &s.doc().unwrap().doc.node(group).unwrap().kind {
|
||||
NodeKind::Group { children, clip: false } => assert_eq!(children.iter().map(|c| c.id).collect::<Vec<_>>(), [id]),
|
||||
other => panic!("a plain group of the image: {other:?}"),
|
||||
}
|
||||
assert_eq!(node(&s).image_corners().unwrap(), corners);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_link_clips_an_image_whose_file_gained_a_clipping_path() {
|
||||
let dir = temp_dir("update-gained-clip");
|
||||
|
||||
@@ -663,6 +663,213 @@ fn update_links_keeps_a_distorted_images_corners() {
|
||||
scale_matches_ppi(&mut s);
|
||||
}
|
||||
|
||||
/// Relink with scope `all` puts the new file's pixels between the corners of the distorted images
|
||||
/// in symbols too, and scales each one's transform to the new pixel size, so a placement by the
|
||||
/// transform keeps the old size.
|
||||
#[test]
|
||||
fn relink_of_all_instances_keeps_the_corners_of_distorted_images_in_symbols() {
|
||||
let dir = Folder::new("distorted-relink-all");
|
||||
let (photo, other) = (dir.file("photo.png"), dir.file("other.png"));
|
||||
write(&photo, &png(20, 10, RED));
|
||||
write(&other, &png(60, 20, BLUE));
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &photo);
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("object.distort", &json!({"corners": [[150, 100], [250, 110], [260, 200], [140, 190]]})).unwrap();
|
||||
let before = s.doc().unwrap().doc.node(id).unwrap().image_corners().unwrap();
|
||||
// The far corner of the pixels as the transform alone places them.
|
||||
let far = |s: &Session| {
|
||||
let NodeKind::Image(im) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("an image") };
|
||||
im.xf * vectorcraft_geom::Point::new(f64::from(im.width), f64::from(im.height))
|
||||
};
|
||||
let far_before = far(&s);
|
||||
// A distorted copy in a symbol shows the same file.
|
||||
let copy = place(&mut s, &photo);
|
||||
s.execute("select.set", &json!({"ids": [copy.0]})).unwrap();
|
||||
s.execute("object.distort", &json!({"corners": [[10, 10], [60, 15], [58, 50], [5, 45]]})).unwrap();
|
||||
s.execute("symbol.new", &json!({"name": "Mark", "ids": [copy.0]})).unwrap();
|
||||
let in_symbol = |s: &Session| {
|
||||
let mut out = vec![];
|
||||
s.doc().unwrap().doc.symbols[0].art.walk(&mut |n| {
|
||||
if let NodeKind::Image(im) = &n.kind {
|
||||
out.push((n.image_quad(), (im.width, im.height)));
|
||||
}
|
||||
});
|
||||
out
|
||||
};
|
||||
let [(Some(symbol_quad), (20, 10))] = in_symbol(&s)[..] else { panic!("one distorted image in the symbol: {:?}", in_symbol(&s)) };
|
||||
let r = s.execute("links.relink", &json!({"ids": [id.0], "path": other, "scope": "all"})).unwrap();
|
||||
let relinked = r["relinked"].as_array().unwrap();
|
||||
assert!(relinked.len() == 2 && relinked.contains(&json!(id.0)), "the image and the symbol's: {r}");
|
||||
assert!(r.get("warnings").is_none(), "no preserve was given: {r}");
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
assert_eq!((n.is_distorted_image(), n.image_corners().unwrap()), (true, before));
|
||||
assert_eq!((image(&s, id).width, image(&s, id).height), (60, 20));
|
||||
assert!(far(&s).distance(far_before) < 1e-9, "{:?} vs {far_before:?}", far(&s));
|
||||
assert_eq!(in_symbol(&s), [(Some(symbol_quad), (60, 20))], "the symbol's image keeps its corners");
|
||||
}
|
||||
|
||||
/// Relink with scope `all` puts the new file's pixels between the corners of a distorted image in
|
||||
/// an opacity mask's art.
|
||||
#[test]
|
||||
fn relink_of_all_instances_keeps_the_corners_of_a_distorted_image_in_an_opacity_mask() {
|
||||
let dir = Folder::new("distorted-relink-mask");
|
||||
let (photo, other) = (dir.file("photo.png"), dir.file("other.png"));
|
||||
write(&photo, &png(20, 10, RED));
|
||||
write(&other, &png(60, 20, BLUE));
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &photo);
|
||||
let masked = super::rect(&mut s, 10.0, 10.0, 60.0, 60.0);
|
||||
let mask = place(&mut s, &photo);
|
||||
s.execute("select.set", &json!({"ids": [mask.0]})).unwrap();
|
||||
s.execute("object.distort", &json!({"corners": [[10, 10], [60, 15], [58, 50], [5, 45]]})).unwrap();
|
||||
s.execute("transparency.makeOpacityMask", &json!({"ids": [masked.0, mask.0]})).unwrap();
|
||||
// The image in the art of `masked`'s opacity mask: (id, corners, pixel size).
|
||||
let in_mask = |s: &Session| {
|
||||
let mut out = vec![];
|
||||
s.doc().unwrap().doc.visit_stored(|n, place| {
|
||||
if let NodeKind::Image(im) = &n.kind
|
||||
&& place.mask_of == Some(masked)
|
||||
{
|
||||
out.push((n.id, n.image_quad(), (im.width, im.height)));
|
||||
}
|
||||
});
|
||||
out
|
||||
};
|
||||
let [(mask_id, Some(quad), (20, 10))] = in_mask(&s)[..] else { panic!("one distorted image in the mask: {:?}", in_mask(&s)) };
|
||||
let r = s.execute("links.relink", &json!({"ids": [id.0], "path": other, "scope": "all"})).unwrap();
|
||||
let relinked = r["relinked"].as_array().unwrap();
|
||||
assert!(relinked.len() == 2 && relinked.contains(&json!(mask_id.0)), "the image and the mask's: {r}");
|
||||
assert_eq!(in_mask(&s), [(mask_id, Some(quad), (60, 20))], "the mask's image keeps its corners");
|
||||
}
|
||||
|
||||
/// Relink, Embed and Unembed keep a distorted image's corners, each in one undo step: Relink puts
|
||||
/// the new file's pixels between them whatever `preserve` and the Placement Options say, Embed
|
||||
/// keeps the pixels in the document, and Unembed links the image to the file it writes.
|
||||
#[test]
|
||||
fn relink_embed_and_unembed_keep_a_distorted_images_corners() {
|
||||
let dir = Folder::new("distorted-relink");
|
||||
let (photo, other, written) = (dir.file("photo.png"), dir.file("other.png"), dir.file("written.png"));
|
||||
write(&photo, &png(20, 10, RED));
|
||||
write(&other, &png(60, 20, BLUE));
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &photo);
|
||||
s.execute("links.placementOptions", &json!({"ids": [id.0], "preserve": "fill", "clip": true})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
// Around the artboard's center, where `centre_colour` looks.
|
||||
s.execute("object.distort", &json!({"corners": [[150, 100], [250, 110], [260, 200], [140, 190]]})).unwrap();
|
||||
let corners = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().image_corners().unwrap();
|
||||
let before = corners(&s);
|
||||
let distorted = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().is_distorted_image();
|
||||
let clipped = |s: &Session| {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
matches!(d.parent_of(id).and_then(|p| d.node(p)).map(|p| &p.kind), Some(NodeKind::Group { clip: true, .. }))
|
||||
};
|
||||
let undo_len = |s: &Session| s.doc().unwrap().history.undo.len();
|
||||
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
|
||||
|
||||
let undo = undo_len(&s);
|
||||
let r = s.execute("links.relink", &json!({"ids": [id.0], "path": other, "preserve": "fileDimensions"})).unwrap();
|
||||
// The given preserve is reported as not applied.
|
||||
let warning = format!("preserve was not applied to image {}: an image changed by Perspective Distort or Free Distort keeps its corners", id.0);
|
||||
assert_eq!(r, json!({"relinked": [id.0], "notFound": [], "warnings": [warning]}));
|
||||
assert_eq!(undo_len(&s), undo + 1);
|
||||
assert!(distorted(&s));
|
||||
assert_eq!(corners(&s), before);
|
||||
assert!(!clipped(&s), "not clipped by its Placement Options");
|
||||
let im = image(&s, id);
|
||||
assert_eq!((im.width, im.height), (60, 20));
|
||||
assert_eq!(im.link.as_ref().map(|l| l.path.as_str()), Some(other.as_str()));
|
||||
assert!(near(centre_colour(&s.doc().unwrap().doc), BLUE));
|
||||
|
||||
let r = s.execute("links.embed", &json!({"ids": [id.0]})).unwrap();
|
||||
assert_eq!(r["embedded"], json!([id.0]), "{r}");
|
||||
assert_eq!(undo_len(&s), undo + 2);
|
||||
assert!(distorted(&s));
|
||||
assert_eq!(corners(&s), before);
|
||||
assert!(image(&s, id).link.is_none());
|
||||
assert!(near(centre_colour(&s.doc().unwrap().doc), BLUE));
|
||||
|
||||
let r = s.execute("links.unembed", &json!({"id": id.0, "path": written})).unwrap();
|
||||
assert_eq!(r["id"], json!(id.0), "{r}");
|
||||
assert_eq!(undo_len(&s), undo + 3);
|
||||
assert!(distorted(&s));
|
||||
assert_eq!(corners(&s), before);
|
||||
assert!(!clipped(&s));
|
||||
let im = image(&s, id);
|
||||
assert_eq!((im.width, im.height), (60, 20));
|
||||
assert!(im.link.is_some());
|
||||
assert!(Path::new(&written).exists());
|
||||
assert!(near(centre_colour(&s.doc().unwrap().doc), BLUE));
|
||||
|
||||
// Undo takes each back to the same corners, and the first file's pixels in the end.
|
||||
for _ in 0..3 {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(distorted(&s));
|
||||
assert_eq!(corners(&s), before);
|
||||
}
|
||||
assert_eq!((image(&s, id).width, image(&s, id).height), (20, 10));
|
||||
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
|
||||
}
|
||||
|
||||
/// Unembed into a folder keeps a distorted image's corners, in one undo step.
|
||||
#[test]
|
||||
fn unembed_to_a_folder_keeps_a_distorted_images_corners() {
|
||||
let dir = Folder::new("distorted-unembed-folder");
|
||||
let (photo, out) = (dir.file("photo.png"), dir.file("out"));
|
||||
std::fs::create_dir_all(&out).unwrap();
|
||||
write(&photo, &png(20, 10, RED));
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &photo);
|
||||
s.execute("links.embed", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("object.distort", &json!({"corners": [[150, 100], [250, 110], [260, 200], [140, 190]]})).unwrap();
|
||||
let corners = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().image_corners().unwrap();
|
||||
let before = corners(&s);
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let r = s.execute("links.unembed", &json!({"ids": [id.0], "folder": out})).unwrap();
|
||||
assert_eq!(r["unembedded"][0]["id"], json!(id.0), "{r}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
assert!(s.doc().unwrap().doc.node(id).unwrap().is_distorted_image());
|
||||
assert_eq!(corners(&s), before);
|
||||
assert!(image(&s, id).link.is_some());
|
||||
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
|
||||
}
|
||||
|
||||
/// Embed reads the file of a distorted image that shows its saved preview and keeps the file's
|
||||
/// pixels in the document between the image's corners, in one undo step.
|
||||
#[test]
|
||||
fn embed_reads_a_distorted_images_file_between_its_corners() {
|
||||
let dir = Folder::new("distorted-embed-preview");
|
||||
let photo = dir.file("photo.png");
|
||||
// Large enough that the document saves a smaller preview of it.
|
||||
write(&photo, &png(600, 300, RED));
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &photo);
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("object.distort", &json!({"corners": [[150, 100], [250, 110], [260, 200], [140, 190]]})).unwrap();
|
||||
let corners = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().image_corners().unwrap();
|
||||
let before = corners(&s);
|
||||
let doc_path = dir.file("poster.vectorcraft");
|
||||
save(&mut s, &doc_path);
|
||||
std::fs::remove_file(&photo).unwrap();
|
||||
open(&mut s, &doc_path);
|
||||
assert!(s.doc().unwrap().doc.images[&image(&s, id).key].is_proxy(), "the preview stands in");
|
||||
assert!(s.doc().unwrap().doc.node(id).unwrap().is_distorted_image());
|
||||
write(&photo, &png(400, 200, BLUE));
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let r = s.execute("links.embed", &json!({"ids": [id.0]})).unwrap();
|
||||
assert_eq!(r, json!({"embedded": [id.0], "missing": []}));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
assert!(n.is_distorted_image());
|
||||
assert_eq!(n.image_corners().unwrap(), before);
|
||||
let im = image(&s, id);
|
||||
assert_eq!((im.width, im.height, im.link.is_none()), (400, 200, true));
|
||||
assert!(!s.doc().unwrap().doc.images[&im.key].is_proxy(), "the file's pixels are in the document");
|
||||
assert!(near(centre_colour(&s.doc().unwrap().doc), BLUE));
|
||||
}
|
||||
|
||||
/// Update Links reads a changed file again for the images inside symbols, patterns and opacity
|
||||
/// masks too: those showing the same content as an image in the layers, and those no object in the
|
||||
/// layers shows. Each takes the file's place as its own Placement Options say, in one undo step,
|
||||
@@ -2617,6 +2824,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
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
@@ -1043,13 +1043,6 @@ fn distort_refuses_a_folded_image_and_crop_and_trace_refuse_a_distorted_one() {
|
||||
for (cmd, params) in [
|
||||
("object.cropImage", json!({})),
|
||||
("imageTrace.make", json!({})),
|
||||
("links.relink", json!({"path": "/nowhere/pic.png"})),
|
||||
// Refused before the folder is searched, so a file missing there does not hide it.
|
||||
("links.relink", json!({"folder": "/nowhere"})),
|
||||
("links.embed", json!({"ids": [img.0]})),
|
||||
("links.unembed", json!({})),
|
||||
// Refused before any file is written.
|
||||
("links.unembed", json!({"folder": "/nowhere"})),
|
||||
("object.createObjectMosaic", json!({})),
|
||||
("object.mesh.create", json!({})),
|
||||
(
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
@@ -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]
|
||||
|
||||
@@ -112,6 +112,26 @@ fn preflight_resolution_follows_placed_size_and_both_axes() {
|
||||
assert!(codes(&screen).is_empty(), "{screen}");
|
||||
}
|
||||
|
||||
/// A distorted image's resolution is measured at its middle, as Image Info measures it.
|
||||
#[test]
|
||||
fn preflight_resolution_of_a_distorted_image_is_image_infos() {
|
||||
let dir = Folder::new("preflight-resolution-distorted");
|
||||
let path = dir.file("picture.png");
|
||||
std::fs::write(&path, png(100, 100, [200, 50, 10])).unwrap();
|
||||
let mut s = new();
|
||||
let id = s.execute("file.place", &json!({ "path": path, "link": false, "at": [200, 200] })).unwrap()["ids"][0].clone();
|
||||
s.execute("select.set", &json!({ "ids": [id] })).unwrap();
|
||||
s.execute("object.setBounds", &json!({ "width": 24, "height": 24 })).unwrap();
|
||||
assert!(codes(&s.execute("document.preflight", &json!({ "minPpi": 200 })).unwrap()).is_empty());
|
||||
// The top stays 24 pt wide; the bottom is 120 pt wide.
|
||||
s.execute("object.distort", &json!({ "corners": [[188, 188], [212, 188], [260, 212], [140, 212]] })).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().is_distorted_image());
|
||||
let info = s.execute("image.info", &json!({ "id": id })).unwrap();
|
||||
let r = s.execute("document.preflight", &json!({ "minPpi": 200 })).unwrap();
|
||||
let f = r["findings"].as_array().unwrap().iter().find(|f| f["code"] == "lowResolution").expect("a low resolution finding");
|
||||
assert_eq!(f["effectivePpi"], info["ppi"], "{info}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preflight_resolution_accepts_the_exact_threshold_but_rejects_a_real_shortfall() {
|
||||
let dir = Folder::new("preflight-resolution-boundary");
|
||||
|
||||
@@ -9309,6 +9309,57 @@ fn a_masked_copy_nested_too_deep_for_its_mask_keeps_all_of_its_pixels() {
|
||||
assert!(whole >= 2, "the first copy and a copy whose mask is left out: {sizes:?}");
|
||||
}
|
||||
|
||||
/// A distorted image in the art of an opacity mask written at the deepest level a mask takes is
|
||||
/// written as its pieces, as an undistorted image there is written whole: the mask keeps its art.
|
||||
#[test]
|
||||
fn a_distorted_image_in_a_mask_at_the_nesting_limit_keeps_its_pixels() {
|
||||
// GUARDS: the distorted image was written there as an empty group, so the mask hid the object.
|
||||
let masks = |distorted: bool| {
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let mut masked = speckled_photo(&mut doc);
|
||||
let mut art = speckled_photo(&mut doc);
|
||||
if distorted {
|
||||
let q = [(40.0, 10.0), (100.0, 10.0), (148.0, 138.0), (20.0, 138.0)].map(|(x, y)| vectorcraft_geom::Point::new(x, y));
|
||||
art.set_image_corners(q).unwrap();
|
||||
}
|
||||
masked.extras_mut().mask = Some(Box::new(OpacityMask { art: Arc::new(art), clip: false, invert: false, disabled: false, linked: true }));
|
||||
doc.symbols.push(Symbol { dynamic: false, name: "S0".into(), art: Arc::new(masked) });
|
||||
// Each isolated instance is written as its art, a level deeper: the masked object's mask
|
||||
// art is at the limit.
|
||||
for i in 1..writer::MAX_NEST - 1 {
|
||||
let mut inner = instance(&mut doc, &format!("S{}", i - 1), Affine::IDENTITY);
|
||||
inner.isolate = true;
|
||||
doc.symbols.push(Symbol { dynamic: false, name: format!("S{i}"), art: Arc::new(inner) });
|
||||
}
|
||||
let mut outer = instance(&mut doc, &format!("S{}", writer::MAX_NEST - 2), Affine::IDENTITY);
|
||||
outer.isolate = true;
|
||||
doc.insert(Some(layer), usize::MAX, outer).unwrap();
|
||||
let out = export_ai_editing(&doc, &opts()).unwrap();
|
||||
assert!(!out.warnings.iter().any(|w| w == writer::DEEP_MASKS), "{:?}", out.warnings);
|
||||
// Each mask read back, by whether its art holds an image.
|
||||
let back = read_back(&doc);
|
||||
let mut found = vec![];
|
||||
let mut look = |n: &Node| {
|
||||
if let Some(m) = n.extras().mask.as_ref() {
|
||||
let mut image = false;
|
||||
m.art.walk(&mut |c| image |= matches!(c.kind, NodeKind::Image(_)));
|
||||
found.push(image);
|
||||
}
|
||||
};
|
||||
for l in &back.layers {
|
||||
l.walk(&mut look);
|
||||
}
|
||||
for s in &back.symbols {
|
||||
s.art.walk(&mut look);
|
||||
}
|
||||
found
|
||||
};
|
||||
let (plain, distorted) = (masks(false), masks(true));
|
||||
assert!(!plain.is_empty() && plain.iter().all(|i| *i), "{plain:?}");
|
||||
assert_eq!(distorted, plain);
|
||||
}
|
||||
|
||||
/// [`warped_photo`] linked to `/Users/someone/Job/art/photo.png`, in folder `art` next to the
|
||||
/// document's.
|
||||
fn linked_warped_photo(doc: &mut Document, effects: Vec<vectorcraft_doc::Effect>) -> Node {
|
||||
|
||||
@@ -974,8 +974,9 @@ impl<'a> Writer<'a> {
|
||||
self.warn(w);
|
||||
}
|
||||
let moved = bounds && self.wrap_on_bounds(n, state);
|
||||
// A gradient mesh's drawn look is paths, which hold nothing: it is written at any depth.
|
||||
if self.nest < MAX_NEST || matches!(n.kind, NodeKind::Mesh(_)) {
|
||||
// A gradient mesh's drawn look is paths, and a distorted image's is clipped copies of its
|
||||
// image, which hold nothing: they are written at any depth.
|
||||
if self.nest < MAX_NEST || matches!(n.kind, NodeKind::Mesh(_)) || n.is_distorted_image() {
|
||||
let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n);
|
||||
self.nest += 1;
|
||||
self.drawn += 1;
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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()) {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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
@@ -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 {
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
//!
|
||||
//! The roots are found by sampling a distance function along one parameter: samples where it is 0,
|
||||
//! bisection where it changes sign, and a golden-section search where it comes down to 0 between
|
||||
//! samples without changing sign.
|
||||
//! samples without changing sign. For a radius, each second segment has its own distance function.
|
||||
|
||||
use kurbo::{CubicBez, ParamCurve, ParamCurveDeriv, ParamCurveNearest, Point, Vec2};
|
||||
|
||||
@@ -256,7 +256,19 @@ pub fn circles_of_radius(first: CubicBez, second: &[CubicBez], radius: f64) -> V
|
||||
let mut found = vec![];
|
||||
for side in [1.0, -1.0] {
|
||||
let center = |t: f64| normal(&first, t, own).map(|n| first.eval(t) + n * (side * radius));
|
||||
for t in roots(&samples, |t| center(t).and_then(|c| nearest(c, second)).map(|(d, _)| d - radius), CONTACT * radius) {
|
||||
// Each second segment is searched on its own, so that two segments touching circles close
|
||||
// together along `first` give both; `touching` then checks each circle against all of them.
|
||||
let mut ts: Vec<f64> = second
|
||||
.iter()
|
||||
.flat_map(|seg| {
|
||||
let dist = |t: f64| center(t).and_then(|c| nearest(c, std::slice::from_ref(seg))).map(|(d, _)| d - radius);
|
||||
roots(&samples, dist, CONTACT * radius)
|
||||
})
|
||||
.collect();
|
||||
// A segment repeated in `second` gives the same places again; each is checked once.
|
||||
ts.sort_by(f64::total_cmp);
|
||||
ts.dedup();
|
||||
for t in ts {
|
||||
if let Some(c) = center(t)
|
||||
&& let Some(touch) = touching(c, radius, second, own)
|
||||
{
|
||||
|
||||
@@ -654,6 +654,20 @@ fn two_circles_between_the_same_two_places_tried_are_both_found() {
|
||||
assert!(near(found[0].circle.center, x - dx, 20.0, 1e-6) && near(found[1].circle.center, x + dx, 20.0, 1e-6), "{found:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_segments_that_touch_circles_close_together_give_both() {
|
||||
// A peak whose two feet touch circles of radius 20 on y = 0 at both feet, between the same
|
||||
// places tried along the line; then the same on a line 10,000 pt long, with the feet 10 pt apart.
|
||||
for (len, a, b) in [(100.0, 50.03, 50.15), (1e4, 5003.0, 5013.0)] {
|
||||
let top = 0.5 * (a + b);
|
||||
let second = [line((a, 40.0), (top, 60.0)), line((top, 60.0), (b, 40.0))];
|
||||
let found = circles_of_radius(line((0.0, 0.0), (len, 0.0)), &second, 20.0);
|
||||
assert_eq!(found.len(), 2, "{len}: {found:?}");
|
||||
assert!(near(found[0].circle.center, a, 20.0, 1e-6) && near(found[0].second, a, 40.0, 1e-6), "{len}: {found:?}");
|
||||
assert!(near(found[1].circle.center, b, 20.0, 1e-6) && near(found[1].second, b, 40.0, 1e-6), "{len}: {found:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tiny_circle_between_long_lines_close_together_is_found() {
|
||||
let found = circles_through(line((0.0, 0.0), (100.0, 0.0)), 0.5, &[line((0.0, 1e-4), (100.0, 1e-4))]);
|
||||
|
||||
@@ -196,6 +196,32 @@ fn a_distorted_image_is_written_with_its_corners_on_its_quad() {
|
||||
assert!(quad_clips >= 1, "no clipping path on the quad");
|
||||
}
|
||||
|
||||
/// A distorted image's own fill that Convert to Shape gives a shape is written with it.
|
||||
#[test]
|
||||
fn a_distorted_image_keeps_its_own_shaped_fill() {
|
||||
use vectorcraft_doc::{AppearanceItem, Effect, FillLayer, color::Color, color::Paint};
|
||||
let mut d = doc(encoded(colour(), ImageFormat::Png), "image/png");
|
||||
let id = d.layers[0].children().unwrap()[0].id;
|
||||
let q = [(40.0, 10.0), (60.0, 10.0), (90.0, 90.0), (10.0, 90.0)].map(|(x, y)| Point::new(x, y));
|
||||
let n = d.node_mut(id).unwrap();
|
||||
n.set_image_corners(q).unwrap();
|
||||
let mut fill = FillLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0)));
|
||||
fill.effects = vec![Effect { id: "convertToShape.rectangle".into(), params: json!({"relative": true, "extraW": 0, "extraH": 0}), visible: true }];
|
||||
n.appearance.items.push(AppearanceItem::Fill(fill));
|
||||
let bytes = export_with_report(&d, &PdfOptions::default()).unwrap().bytes;
|
||||
let back = crate::import(&bytes).unwrap();
|
||||
let (mut green, mut pieces) = (false, 0);
|
||||
back.walk(|n| match &n.kind {
|
||||
NodeKind::Image(_) => pieces += 1,
|
||||
NodeKind::Path { .. } => {
|
||||
green |= n.appearance.fill().and_then(|f| f.paint.color()).is_some_and(|c| c.to_rgb()[1] > 0.9 && c.to_rgb()[0] < 0.1)
|
||||
}
|
||||
_ => {}
|
||||
});
|
||||
assert!(pieces > 2, "{pieces}");
|
||||
assert!(green, "the fill is written");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jpeg_zip_and_automatic_compression() {
|
||||
let png = doc(encoded(colour(), ImageFormat::Png), "image/png");
|
||||
|
||||
@@ -28,5 +28,10 @@ wasmparser = { workspace = true }
|
||||
# the build through eframe.
|
||||
web-time = "1"
|
||||
|
||||
# Opens a `.wasm` in the plug-ins folder without waiting when it is a named pipe (`registry.rs`).
|
||||
# Already in Cargo.lock, so this adds no new crate.
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
rustix = { workspace = true, features = ["std", "fs"] }
|
||||
|
||||
[dev-dependencies]
|
||||
wat = { workspace = true }
|
||||
+187
-22
@@ -182,20 +182,75 @@ pub fn intern(s: &str) -> &'static str {
|
||||
/// and loads it.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn load_file(path: &std::path::Path, limits: Limits) -> Result<Plugin> {
|
||||
use std::io::Read;
|
||||
let meta = std::fs::metadata(path).map_err(|e| Error::Io(format!("{}: {e}", path.display())))?;
|
||||
if !meta.is_file() {
|
||||
return Err(Error::Io(format!("{} is not a file", path.display())));
|
||||
}
|
||||
if meta.len() > limits.max_module_bytes as u64 {
|
||||
return Err(Error::Module(format!("{} is {} bytes (limit {})", path.display(), meta.len(), limits.max_module_bytes)));
|
||||
}
|
||||
let f = std::fs::File::open(path).map_err(|e| Error::Io(format!("{}: {e}", path.display())))?;
|
||||
let mut bytes = Vec::new();
|
||||
f.take(limits.max_module_bytes as u64 + 1).read_to_end(&mut bytes).map_err(|e| Error::Io(format!("{}: {e}", path.display())))?;
|
||||
let bytes = read_module(path, &limits, || {})?;
|
||||
Ok(Plugin::load(&bytes, limits)?.with_source(path.display().to_string()))
|
||||
}
|
||||
|
||||
/// The bytes of the module file at `path`. A path that doesn't name a regular file is refused
|
||||
/// before it is opened, and so is one over the module limit. On Unix the file is opened without
|
||||
/// waiting, so a named pipe put in its place after that check doesn't hold the load until something
|
||||
/// writes to it; what was opened is checked again and refused the same way. `opening` runs between
|
||||
/// the first check and the open.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn read_module(path: &std::path::Path, limits: &Limits, opening: impl FnOnce()) -> Result<Vec<u8>> {
|
||||
use std::io::Read;
|
||||
let io = |e: std::io::Error| Error::Io(format!("{}: {e}", path.display()));
|
||||
let regular = |meta: std::fs::Metadata| {
|
||||
if !meta.is_file() {
|
||||
return Err(Error::Io(format!("{} is not a file", path.display())));
|
||||
}
|
||||
if meta.len() > limits.max_module_bytes as u64 {
|
||||
return Err(Error::Module(format!("{} is {} bytes (limit {})", path.display(), meta.len(), limits.max_module_bytes)));
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
regular(std::fs::metadata(path).map_err(io)?)?;
|
||||
opening();
|
||||
let f = open_module(path).map_err(io)?;
|
||||
regular(f.metadata().map_err(io)?)?;
|
||||
let mut bytes = Vec::new();
|
||||
f.take(limits.max_module_bytes as u64 + 1).read_to_end(&mut bytes).map_err(io)?;
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// Opens the module file at `path` for reading. On Unix the open doesn't wait for a writer when
|
||||
/// the path names a named pipe, and doesn't make a terminal device the controlling terminal.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn open_module(path: &std::path::Path) -> std::io::Result<std::fs::File> {
|
||||
let mut open = std::fs::OpenOptions::new();
|
||||
open.read(true);
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::OpenOptionsExt::custom_flags(&mut open, (rustix::fs::OFlags::NONBLOCK | rustix::fs::OFlags::NOCTTY).bits() as i32);
|
||||
open.open(path)
|
||||
}
|
||||
|
||||
/// The most `.wasm` files one [`load_folder`] reads.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const MAX_FOLDER_FILES: usize = 1000;
|
||||
|
||||
/// The first [`MAX_FOLDER_FILES`] `*.wasm` paths directly in `dir` by file name, sorted, and how
|
||||
/// many more there are. Only that many paths are held while the folder is listed. An error while
|
||||
/// the folder is listed is returned, as one opening it is.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn folder_files(dir: &std::path::Path) -> Result<(Vec<std::path::PathBuf>, usize)> {
|
||||
let io = |e: std::io::Error| Error::Io(format!("{}: {e}", dir.display()));
|
||||
let rd = std::fs::read_dir(dir).map_err(io)?;
|
||||
let mut kept = std::collections::BinaryHeap::new();
|
||||
let mut more = 0;
|
||||
for entry in rd {
|
||||
let p = entry.map_err(io)?.path();
|
||||
if !p.extension().is_some_and(|x| x.eq_ignore_ascii_case("wasm")) {
|
||||
continue;
|
||||
}
|
||||
kept.push(p);
|
||||
if kept.len() > MAX_FOLDER_FILES {
|
||||
kept.pop();
|
||||
more += 1;
|
||||
}
|
||||
}
|
||||
Ok((kept.into_sorted_vec(), more))
|
||||
}
|
||||
|
||||
/// What [`load_folder`] reports for a plug-in the user disabled.
|
||||
pub const DISABLED: &str = "disabled: turn it on again in Help › Safe Mode, for the next launch";
|
||||
|
||||
@@ -204,18 +259,22 @@ pub const DISABLED: &str = "disabled: turn it on again in Help › Safe Mode, fo
|
||||
pub struct FolderReport {
|
||||
/// Ids of the plug-ins installed.
|
||||
pub loaded: Vec<String>,
|
||||
/// `(file, error)` for each `.wasm` that failed to load.
|
||||
/// `(file, error)` for each `.wasm` that failed to load, including one that isn't a regular file.
|
||||
pub failed: Vec<(String, String)>,
|
||||
/// How many `.wasm` files were not tried because the folder holds more than a load reads.
|
||||
pub left_out: usize,
|
||||
/// The disabled items saved for the next launch changed: a plug-in disabled by its id alone was
|
||||
/// found in a file, which is now disabled too ([`crate::safe_mode::disable_file_of`]). The app
|
||||
/// saves the list again.
|
||||
pub disabled_changed: bool,
|
||||
}
|
||||
|
||||
/// Installs every `*.wasm` directly in `dir` (not recursive), in file-name order. A bad module is
|
||||
/// reported and skipped, the others still load; so is a heavy one ([`crate::Budget::Heavy`]),
|
||||
/// which installs only once the user agrees, and one that lists permissions the user has not
|
||||
/// granted this very module ([`approved`]).
|
||||
/// Installs every `*.wasm` directly in `dir` (not recursive), in file-name order, up to the first
|
||||
/// 1,000 by file name; the report counts the files left out ([`FolderReport::left_out`]). Anything
|
||||
/// that isn't a regular file, such as a named pipe, is reported and skipped without waiting on it
|
||||
/// ([`load_file`]). A bad module is reported and skipped, the others still load; so is a heavy one
|
||||
/// ([`crate::Budget::Heavy`]), which installs only once the user agrees, and one that lists
|
||||
/// permissions the user has not granted this very module ([`approved`]).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn load_folder(dir: &std::path::Path) -> Result<FolderReport> {
|
||||
load_folder_where(dir, |_| Ok(()), approved)
|
||||
@@ -237,12 +296,8 @@ pub fn load_folder_where(
|
||||
) -> Result<FolderReport> {
|
||||
use crate::safe_mode::{self, Item};
|
||||
safe_mode::check()?;
|
||||
let rd = std::fs::read_dir(dir).map_err(|e| Error::Io(format!("{}: {e}", dir.display())))?;
|
||||
let mut files: Vec<std::path::PathBuf> =
|
||||
rd.filter_map(|e| e.ok().map(|e| e.path())).filter(|p| p.extension().is_some_and(|x| x.eq_ignore_ascii_case("wasm"))).collect();
|
||||
files.sort();
|
||||
files.truncate(1000);
|
||||
let mut report = FolderReport::default();
|
||||
let (files, left_out) = folder_files(dir)?;
|
||||
let mut report = FolderReport { left_out, ..FolderReport::default() };
|
||||
for f in files {
|
||||
if let Err(why) = allow(&f) {
|
||||
report.failed.push((f.display().to_string(), why));
|
||||
@@ -453,4 +508,114 @@ mod tests {
|
||||
assert!(granted(id).is_none(), "a module without permissions forgets the grant");
|
||||
assert!(remove(id));
|
||||
}
|
||||
|
||||
/// An empty folder for one test, with anything an earlier run left there removed.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn test_dir(name: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("vc-registry-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
/// Makes a named pipe at `path`.
|
||||
#[cfg(unix)]
|
||||
fn make_pipe(path: &std::path::Path) {
|
||||
assert!(std::process::Command::new("mkfifo").arg(path).status().unwrap().success(), "mkfifo {}", path.display());
|
||||
}
|
||||
|
||||
/// Limits that let a test go past the module size with a few bytes.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn small_limits() -> Limits {
|
||||
Limits { max_module_bytes: 16, ..Limits::default() }
|
||||
}
|
||||
|
||||
/// A module file is opened so that a named pipe in its place doesn't make the open wait for a
|
||||
/// writer. The test holds the pipe open for reading and writing itself, so the open returns
|
||||
/// either way.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_module_file_is_opened_without_waiting_for_a_writer() {
|
||||
let dir = test_dir("open");
|
||||
let pipe = dir.join("x.wasm");
|
||||
make_pipe(&pipe);
|
||||
let held = std::fs::OpenOptions::new().read(true).write(true).open(&pipe).unwrap();
|
||||
let opened = open_module(&pipe).unwrap();
|
||||
let flags = rustix::fs::fcntl_getfl(&opened).unwrap();
|
||||
drop((opened, held));
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
assert!(flags.contains(rustix::fs::OFlags::NONBLOCK), "the open would wait for a writer: {flags:?}");
|
||||
}
|
||||
|
||||
/// A `.wasm` that a named pipe replaces after it was checked is refused as not a file, even
|
||||
/// when the pipe holds more bytes than the module limit allows.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_file_replaced_by_a_pipe_is_refused() {
|
||||
use std::io::Write;
|
||||
let dir = test_dir("pipe");
|
||||
let path = dir.join("x.wasm");
|
||||
let pipe = dir.join("pipe");
|
||||
std::fs::write(&path, b"\0asm").unwrap();
|
||||
make_pipe(&pipe);
|
||||
let mut held = std::fs::OpenOptions::new().read(true).write(true).open(&pipe).unwrap();
|
||||
held.write_all(&[0; 32]).unwrap();
|
||||
let read = read_module(&path, &small_limits(), || std::fs::rename(&pipe, &path).unwrap());
|
||||
drop(held);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
assert!(matches!(&read, Err(Error::Io(e)) if e.ends_with("is not a file")), "{read:?}");
|
||||
}
|
||||
|
||||
/// A `.wasm` that grows past the module limit after it was checked is refused by its size.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_file_that_grows_after_the_check_is_refused() {
|
||||
let dir = test_dir("grow");
|
||||
let path = dir.join("x.wasm");
|
||||
std::fs::write(&path, b"\0asm").unwrap();
|
||||
let read = read_module(&path, &small_limits(), || std::fs::write(&path, [0; 32]).unwrap());
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
assert!(matches!(&read, Err(Error::Module(e)) if e.contains("limit 16")), "{read:?}");
|
||||
}
|
||||
|
||||
/// A folder load reports a subfolder, a named pipe and a link to a named pipe with `.wasm`
|
||||
/// names as not files, and goes on.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_folder_reports_entries_that_are_not_files() {
|
||||
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
crate::safe_mode::set_active(None);
|
||||
let dir = test_dir("special");
|
||||
std::fs::create_dir(dir.join("a.wasm")).unwrap();
|
||||
make_pipe(&dir.join("b.wasm"));
|
||||
std::os::unix::fs::symlink(dir.join("b.wasm"), dir.join("c.wasm")).unwrap();
|
||||
let r = load_folder_where(&dir, |_| Ok(()), |_| false);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
let r = r.unwrap();
|
||||
let failed: Vec<(String, bool)> = r.failed.iter().map(|(f, e)| (f.clone(), e.ends_with("is not a file"))).collect();
|
||||
let expected: Vec<(String, bool)> = ["a", "b", "c"].iter().map(|n| (dir.join(format!("{n}.wasm")).display().to_string(), true)).collect();
|
||||
assert_eq!(failed, expected, "{r:?}");
|
||||
assert!(r.loaded.is_empty() && r.left_out == 0, "{r:?}");
|
||||
}
|
||||
|
||||
/// A folder with more `.wasm` files than a load reads tries the first ones by file name and
|
||||
/// counts the files it left out.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_folder_over_the_file_limit_reports_the_files_left_out() {
|
||||
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
crate::safe_mode::set_active(None);
|
||||
let dir = test_dir("limit");
|
||||
// Written last first, so the listing's order is not the file-name order.
|
||||
for i in (0..MAX_FOLDER_FILES + 2).rev() {
|
||||
std::fs::write(dir.join(format!("{i:05}.wasm")), b"").unwrap();
|
||||
}
|
||||
let r = load_folder_where(&dir, |_| Ok(()), |_| false).unwrap();
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
assert!(r.loaded.is_empty(), "{r:?}");
|
||||
assert_eq!(r.left_out, 2, "{r:?}");
|
||||
let tried: Vec<String> = r.failed.iter().map(|(f, _)| f.clone()).collect();
|
||||
let first: Vec<String> = (0..MAX_FOLDER_FILES).map(|i| dir.join(format!("{i:05}.wasm")).display().to_string()).collect();
|
||||
assert_eq!(tried, first, "the first files by name, in that order");
|
||||
}
|
||||
}
|
||||
@@ -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>),
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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"];
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -3,6 +3,8 @@ use super::build::{style_italic, style_weight};
|
||||
use super::dirs::sfnt_of;
|
||||
use super::face::{MAX_AXES, MAX_INSTANCES};
|
||||
use super::names::{all_names, name, norm};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::traits::may_set_thai;
|
||||
use super::traits::{FaceKeys, FaceStyle, FontTraits, face_styles};
|
||||
use super::{FileRef, MetadataProvider, Path, StringId, Tag};
|
||||
|
||||
@@ -126,40 +128,51 @@ pub(super) fn font_files(path: &Path) -> Vec<Vec<u8>> {
|
||||
const OUTLINE_TABLES: [&[u8; 4]; 6] = [b"glyf", b"CFF ", b"CFF2", b"VARC", b"sbix", b"CBDT"];
|
||||
|
||||
/// The styles of every face in the font file at `path` ([`face_styles`]), reading only its table
|
||||
/// directories and `name`, `fvar` and `OS/2` tables: a scan opens hundreds of font files, many of
|
||||
/// directories and `name`, `fvar` and `OS/2` tables (and the `cmap` table of a face that may set
|
||||
/// Thai, [`may_set_thai`]): a scan opens hundreds of font files, many of
|
||||
/// them megabytes long. Faces without outlines the font engine draws (no [`OUTLINE_TABLES`] table)
|
||||
/// are left out.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(super) fn file_face_names(path: &Path) -> Vec<FaceStyle> {
|
||||
file_face_names_within(path, MAX_FACES, u64::MAX)
|
||||
file_face_names_reading(path, MAX_FACES, u64::MAX, true)
|
||||
}
|
||||
|
||||
/// [`file_face_names`], reading at most `max_faces` faces and `max_read` bytes of the file in all.
|
||||
/// A suitcase font's resource fork is read whole when it is at most `max_read` bytes long, and the
|
||||
/// limits then apply to each of its fonts; a longer fork gives none.
|
||||
/// [`file_face_names`], reading at most `max_faces` faces and `max_read` bytes of the file in all,
|
||||
/// and no `cmap` table: a face's [`FontTraits::thai`] is false. A suitcase font's resource fork is
|
||||
/// read whole when it is at most `max_read` bytes long, and the limits then apply to each of its
|
||||
/// fonts; a longer fork gives none.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn file_face_names_within(path: &Path, max_faces: u32, max_read: u64) -> Vec<FaceStyle> {
|
||||
file_face_names_reading(path, max_faces, max_read, false)
|
||||
}
|
||||
|
||||
/// [`file_face_names_within`], reading the `cmap` table of a face that may set Thai when
|
||||
/// `read_cmap` is true.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn file_face_names_reading(path: &Path, max_faces: u32, max_read: u64, read_cmap: bool) -> Vec<FaceStyle> {
|
||||
if crate::suitcase::is_suitcase(path) {
|
||||
if crate::suitcase::fork_len(path) > max_read {
|
||||
return vec![];
|
||||
}
|
||||
return crate::suitcase::read_fonts(path)
|
||||
.into_iter()
|
||||
.flat_map(|font| reader_face_names_within(std::io::Cursor::new(font), max_faces, max_read))
|
||||
.flat_map(|font| reader_face_names_within(std::io::Cursor::new(font), max_faces, max_read, read_cmap))
|
||||
.collect();
|
||||
}
|
||||
match std::fs::File::open(path) {
|
||||
Ok(file) => reader_face_names_within(file, max_faces, max_read),
|
||||
Ok(file) => reader_face_names_within(file, max_faces, max_read, read_cmap),
|
||||
Err(_) => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
/// [`file_face_names_within`] for the font file `file` reads.
|
||||
/// [`file_face_names_reading`] for the font file `file` reads.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn reader_face_names_within(mut file: impl std::io::Read + std::io::Seek, max_faces: u32, max_read: u64) -> Vec<FaceStyle> {
|
||||
fn reader_face_names_within(mut file: impl std::io::Read + std::io::Seek, max_faces: u32, max_read: u64, read_cmap: bool) -> Vec<FaceStyle> {
|
||||
use std::io::SeekFrom;
|
||||
/// The largest table read from a (possibly damaged) file.
|
||||
/// The largest table read from a (possibly damaged) file, other than `cmap`.
|
||||
const MAX_NAME_TABLE: u32 = 1 << 20;
|
||||
/// The largest `cmap` table read.
|
||||
const MAX_CMAP_TABLE: u32 = 16 << 20;
|
||||
/// The `post` table's header: version, italic angle, underline and fixed-pitch fields.
|
||||
const POST_HEADER: u32 = 32;
|
||||
let mut read = 0u64;
|
||||
@@ -188,11 +201,12 @@ fn reader_face_names_within(mut file: impl std::io::Read + std::io::Seek, max_fa
|
||||
if !records.as_chunks::<16>().0.iter().any(|r| OUTLINE_TABLES.iter().any(|t| r.starts_with(*t))) {
|
||||
return None;
|
||||
}
|
||||
// A table's first `most` bytes at most; a table read whole longer than `MAX_NAME_TABLE` gives nothing.
|
||||
// A table's first `most` bytes at most; a table read whole longer than `MAX_NAME_TABLE`
|
||||
// (`MAX_CMAP_TABLE` for `cmap`) gives nothing.
|
||||
let mut table_within = |tag: &[u8; 4], most: u32| -> Option<Vec<u8>> {
|
||||
let rec: &[u8] = records.as_chunks::<16>().0.iter().find(|r| r.starts_with(tag))?;
|
||||
let (offset, len) = (be32(rec, 8)?, be32(rec, 12)?.min(most));
|
||||
if len > MAX_NAME_TABLE {
|
||||
if len > if tag == b"cmap" { MAX_CMAP_TABLE } else { MAX_NAME_TABLE } {
|
||||
return None;
|
||||
}
|
||||
read_at(offset.into(), len as usize)
|
||||
@@ -217,7 +231,13 @@ fn reader_face_names_within(mut file: impl std::io::Read + std::io::Seek, max_fa
|
||||
tables.push((tag, data.as_slice()));
|
||||
}
|
||||
}
|
||||
let font = sfnt_of(&tables)?;
|
||||
let mut font = sfnt_of(&tables)?;
|
||||
// Its character map too when it may set Thai, to tell whether it does.
|
||||
let cmap = if read_cmap && may_set_thai(&skrifa::FontRef::new(&font).ok()?) { table_within(b"cmap", u32::MAX) } else { None };
|
||||
if let Some(cmap) = &cmap {
|
||||
tables.push((b"cmap", cmap.as_slice()));
|
||||
font = sfnt_of(&tables)?;
|
||||
}
|
||||
Some(face_styles(&skrifa::FontRef::new(&font).ok()?))
|
||||
})
|
||||
.flatten()
|
||||
|
||||
@@ -95,7 +95,7 @@ impl FontClass {
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct FontTraits {
|
||||
pub japanese: bool,
|
||||
/// Its character map has Thai (ก and า).
|
||||
/// Its OS/2 table allows Thai ([`may_set_thai`]) and its character map has Thai (ก and า).
|
||||
pub thai: bool,
|
||||
pub class: FontClass,
|
||||
/// The face has variation axes (an `fvar` table of at most 64 axes); for a family, one of
|
||||
@@ -216,8 +216,21 @@ impl FontLikeness {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a face may set Thai by its OS/2 table: it has none, or the table's Unicode ranges have
|
||||
/// Thai (bit 24) or its code pages have Thai (bit 16, code page 874). Only such a face has its
|
||||
/// character map checked for Thai ([`FontTraits::thai`]); the system font scan reads a face's
|
||||
/// `cmap` table only then ([`super::scan::file_face_names`]).
|
||||
pub(super) fn may_set_thai(font: &skrifa::FontRef<'_>) -> bool {
|
||||
use skrifa::raw::TableProvider;
|
||||
match font.os2() {
|
||||
Ok(o) => o.ul_unicode_range_1() & (1 << 24) != 0 || o.ul_code_page_range_1().unwrap_or(0) & (1 << 16) != 0,
|
||||
Err(_) => true,
|
||||
}
|
||||
}
|
||||
|
||||
impl FontTraits {
|
||||
/// From a face's OS/2 and `fvar` tables (when it has them) and names.
|
||||
/// From a face's OS/2 and `fvar` tables (when it has them), names and, when it may set Thai
|
||||
/// ([`may_set_thai`]), character map.
|
||||
fn of(font: &skrifa::FontRef<'_>, keys: &FaceKeys) -> Self {
|
||||
use skrifa::raw::TableProvider;
|
||||
let os2 = font.os2().ok();
|
||||
@@ -230,7 +243,7 @@ impl FontTraits {
|
||||
};
|
||||
// Hiragana (bit 49) or Katakana (bit 50) in the Unicode ranges, or the JIS code page.
|
||||
let japanese = ranges2 & (0b11 << 17) != 0 || codepages & (1 << 17) != 0 || has_japanese_name;
|
||||
let thai = ['\u{0E01}', '\u{0E32}'].iter().all(|c| font.charmap().map(*c).is_some());
|
||||
let thai = may_set_thai(font) && ['\u{0E01}', '\u{0E32}'].iter().all(|c| font.charmap().map(*c).is_some());
|
||||
let family_type = panose.first().copied().unwrap_or(0);
|
||||
let serif_style = panose.get(1).copied().unwrap_or(0);
|
||||
let proportion = panose.get(3).copied().unwrap_or(0);
|
||||
|
||||
@@ -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(®ions),
|
||||
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
File diff suppressed because it is too large.
Load diff
@@ -705,6 +705,51 @@ fn repeat_font(family: &str, chars: &[(char, char)]) -> Option<Vec<u8>> {
|
||||
Some(builder.build())
|
||||
}
|
||||
|
||||
/// The families [`thai_font`] can be named, two fonts that set Thai.
|
||||
pub const THAI_FAMILY: &str = "Thaitest Sans";
|
||||
pub const THAI_OTHER_FAMILY: &str = "Thaiothertest Sans";
|
||||
|
||||
/// Bundled Source Sans 3 Regular as `family`, with a cmap that maps ก and า to the glyphs of A and
|
||||
/// B beside the Latin letters and the space. With `claimed`, its OS/2 table has the Thai Unicode
|
||||
/// range (bit 24) set; without, neither that range nor the Thai code page (bit 16). `None` when it
|
||||
/// can't be built.
|
||||
pub fn thai_font(family: &str, claimed: bool) -> Option<Vec<u8>> {
|
||||
use write_fonts::tables::cmap::Cmap;
|
||||
|
||||
const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf");
|
||||
let font = skrifa::FontRef::new(BASE).ok()?;
|
||||
let charmap = font.charmap();
|
||||
let glyph = |c| Some(write_fonts::types::GlyphId::new(charmap.map(c)?.to_u32()));
|
||||
let mut mappings: Vec<(char, write_fonts::types::GlyphId)> = vec![('\u{0E01}', glyph('A')?), ('\u{0E32}', glyph('B')?)];
|
||||
for c in ('A'..='Z').chain('a'..='z').chain([' ']) {
|
||||
mappings.push((c, glyph(c)?));
|
||||
}
|
||||
let cmap = Cmap::from_mappings(mappings).ok()?;
|
||||
let full = format!("{family} Regular");
|
||||
let postscript = format!("{}-Regular", family.replace(' ', ""));
|
||||
let name = name_table(&[(1, family), (2, "Regular"), (4, &full), (6, &postscript)])?;
|
||||
let mut builder = FontBuilder::new();
|
||||
builder.add_table(&cmap).ok()?;
|
||||
builder.add_raw(Tag::new(b"name"), name);
|
||||
for r in font.table_directory.table_records() {
|
||||
let tag = Tag::new(&r.tag().to_be_bytes());
|
||||
if tag == Tag::new(b"GSUB") || builder.contains(tag) {
|
||||
continue;
|
||||
}
|
||||
let mut data = font.table_data(r.tag())?.as_bytes().to_vec();
|
||||
if tag == Tag::new(b"OS/2") {
|
||||
// ulUnicodeRange1 at bytes 42 to 46, ulCodePageRange1 at bytes 78 to 82.
|
||||
let ranges = u32::from_be_bytes(data.get(42..46)?.try_into().ok()?);
|
||||
let ranges = if claimed { ranges | 1 << 24 } else { ranges & !(1 << 24) };
|
||||
data.get_mut(42..46)?.copy_from_slice(&ranges.to_be_bytes());
|
||||
let pages = u32::from_be_bytes(data.get(78..82)?.try_into().ok()?) & !(1 << 16);
|
||||
data.get_mut(78..82)?.copy_from_slice(&pages.to_be_bytes());
|
||||
}
|
||||
builder.add_raw(tag, data);
|
||||
}
|
||||
Some(builder.build())
|
||||
}
|
||||
|
||||
/// The family of [`half_form_font`].
|
||||
pub const HALF_FORM_FAMILY: &str = "Halftest Sans";
|
||||
|
||||
|
||||
@@ -421,26 +421,27 @@ fn composer_x_mixed_sizes_around_text_wrap() {
|
||||
let l = layout(db(), &t);
|
||||
(line_texts(&t, &l), l, t)
|
||||
};
|
||||
let (every, l, t) = set(Composer::EveryLine);
|
||||
assert_eq!(
|
||||
every,
|
||||
["Destroy all creatures with", "toughness\u{a0}X", "or less. Then", "draw a card for", "each creature", "destroyed this", "way."]
|
||||
);
|
||||
assert!(past_their_room(&t, &l).is_empty() && !l.overflow, "{:?}", l.lines);
|
||||
// Two spans share each baseline beside the object.
|
||||
assert_eq!(l.lines[1].baseline, l.lines[2].baseline);
|
||||
assert!(l.lines[1].ascent > 30.0 && l.lines[2].avail.0 > object.x1, "{:?}", l.lines);
|
||||
let text = t.plain_text();
|
||||
let hits = l.glyphs.iter().filter(|g| {
|
||||
let li = &l.lines[g.line];
|
||||
let across = li.baseline - li.ascent < object.y1 && li.baseline + li.descent > object.y0;
|
||||
across && !text[g.byte..].starts_with(char::is_whitespace) && g.origin.x < object.x1 && g.origin.x + g.advance > object.x0
|
||||
});
|
||||
assert_eq!(hits.count(), 0, "{:?}", l.lines);
|
||||
// The single-line composer measures each line across its height too, and breaks this
|
||||
// paragraph the same way.
|
||||
let (greedy, _, _) = set(Composer::SingleLine);
|
||||
assert_eq!(every, greedy);
|
||||
// paragraph the same way, with its lines set clear of the object as well.
|
||||
for composer in [Composer::EveryLine, Composer::SingleLine] {
|
||||
let (texts, l, t) = set(composer);
|
||||
assert_eq!(
|
||||
texts,
|
||||
["Destroy all creatures with", "toughness\u{a0}X", "or less. Then", "draw a card for", "each creature", "destroyed this", "way."],
|
||||
"{composer:?}"
|
||||
);
|
||||
assert!(past_their_room(&t, &l).is_empty() && !l.overflow, "{composer:?}: {:?}", l.lines);
|
||||
// Two spans share each baseline beside the object.
|
||||
assert_eq!(l.lines[1].baseline, l.lines[2].baseline, "{composer:?}");
|
||||
assert!(l.lines[1].ascent > 30.0 && l.lines[2].avail.0 > object.x1, "{composer:?}: {:?}", l.lines);
|
||||
let text = t.plain_text();
|
||||
let hits = l.glyphs.iter().filter(|g| {
|
||||
let li = &l.lines[g.line];
|
||||
let across = li.baseline - li.ascent < object.y1 && li.baseline + li.descent > object.y0;
|
||||
across && !text[g.byte..].starts_with(char::is_whitespace) && g.origin.x < object.x1 && g.origin.x + g.advance > object.x0
|
||||
});
|
||||
assert_eq!(hits.count(), 0, "{composer:?}: {:?}", l.lines);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -581,23 +582,23 @@ fn composer_x_mixed_sizes_overflow_around_text_wrap() {
|
||||
let l = layout(db(), &t);
|
||||
(line_texts(&t, &l), l, t)
|
||||
};
|
||||
let (every, l, t) = set(Composer::EveryLine);
|
||||
assert!(l.overflow && l.lines.len() >= 3, "{:?}", l.lines);
|
||||
assert!(l.lines.windows(2).all(|p| p[0].end == p[1].start && p[0].start < p[0].end), "{:?}", l.lines);
|
||||
assert!(past_their_room(&t, &l).is_empty(), "{:?}", l.lines);
|
||||
let text = t.plain_text();
|
||||
let hits = l.glyphs.iter().filter(|g| {
|
||||
let li = &l.lines[g.line];
|
||||
let across = li.baseline - li.ascent < object.y1 && li.baseline + li.descent > object.y0;
|
||||
across && !text[g.byte..].starts_with(char::is_whitespace) && g.origin.x < object.x1 && g.origin.x + g.advance > object.x0
|
||||
});
|
||||
assert_eq!(hits.count(), 0, "{:?}", l.lines);
|
||||
// The lines that fit break as in `composer_x_mixed_sizes_around_text_wrap`'s taller frame.
|
||||
assert_eq!(every, ["Destroy all creatures with", "toughness\u{a0}X", "or less. Then", "draw a card for", "each creature"]);
|
||||
// The single-line composer measures each line across its height too, and breaks the lines
|
||||
// that fit the same way.
|
||||
let (greedy, ..) = set(Composer::SingleLine);
|
||||
assert_eq!(every, greedy);
|
||||
// The single-line composer measures each line across its height too, and breaks and sets the
|
||||
// lines that fit the same way.
|
||||
for composer in [Composer::EveryLine, Composer::SingleLine] {
|
||||
let (texts, l, t) = set(composer);
|
||||
assert!(l.overflow && l.lines.len() >= 3, "{composer:?}: {:?}", l.lines);
|
||||
assert!(l.lines.windows(2).all(|p| p[0].end == p[1].start && p[0].start < p[0].end), "{composer:?}: {:?}", l.lines);
|
||||
assert!(past_their_room(&t, &l).is_empty(), "{composer:?}: {:?}", l.lines);
|
||||
let text = t.plain_text();
|
||||
let hits = l.glyphs.iter().filter(|g| {
|
||||
let li = &l.lines[g.line];
|
||||
let across = li.baseline - li.ascent < object.y1 && li.baseline + li.descent > object.y0;
|
||||
across && !text[g.byte..].starts_with(char::is_whitespace) && g.origin.x < object.x1 && g.origin.x + g.advance > object.x0
|
||||
});
|
||||
assert_eq!(hits.count(), 0, "{composer:?}: {:?}", l.lines);
|
||||
// The lines that fit break as in `composer_x_mixed_sizes_around_text_wrap`'s taller frame.
|
||||
assert_eq!(texts, ["Destroy all creatures with", "toughness\u{a0}X", "or less. Then", "draw a card for", "each creature"], "{composer:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -590,6 +590,39 @@ fn the_scan_reads_a_familys_likeness_without_loading_it() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Font menus' Thai filter and Show Similar Fonts: the scan tells whether a family sets Thai as
|
||||
/// loading it does. A face whose OS/2 table names neither the Thai range nor the Thai code page does
|
||||
/// not set Thai, loaded or scanned, whatever its character map holds.
|
||||
#[test]
|
||||
fn the_scan_tells_whether_a_family_sets_thai_without_loading_it() {
|
||||
use crate::test_fonts::{THAI_FAMILY, THAI_OTHER_FAMILY, thai_font};
|
||||
let dir = std::env::temp_dir().join(format!("vc-sysfonts-{}-thai", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
for claimed in [true, false] {
|
||||
std::fs::write(dir.join("Thaitest-Regular.ttf"), thai_font(THAI_FAMILY, claimed).unwrap()).unwrap();
|
||||
let scanned = FontDb::with_font_dirs(vec![dir.clone()]);
|
||||
let thai = scanned.family_traits(THAI_FAMILY).thai;
|
||||
assert!(!scanned.is_loaded(THAI_FAMILY), "the scan's traits, nothing loaded");
|
||||
let loaded = FontDb::with_font_dirs(vec![]);
|
||||
assert_eq!(loaded.add_font(thai_font(THAI_FAMILY, claimed).unwrap()), 1);
|
||||
assert_eq!(thai, loaded.family_traits(THAI_FAMILY).thai, "claimed: {claimed}");
|
||||
assert_eq!(thai, claimed);
|
||||
}
|
||||
// A loaded Thai family lists a scanned Thai family before a Latin family that looks the same,
|
||||
// and the order stays when the scanned family is loaded.
|
||||
std::fs::write(dir.join("Thaitest-Regular.ttf"), thai_font(THAI_FAMILY, true).unwrap()).unwrap();
|
||||
let db = FontDb::with_font_dirs(vec![dir.clone()]);
|
||||
assert_eq!(db.add_font(thai_font(THAI_OTHER_FAMILY, true).unwrap()), 1);
|
||||
let families: Vec<String> = ["Source Sans 3", THAI_FAMILY, THAI_OTHER_FAMILY].map(String::from).to_vec();
|
||||
let expected: Vec<String> = [THAI_OTHER_FAMILY, THAI_FAMILY, "Source Sans 3"].map(String::from).to_vec();
|
||||
assert_eq!(db.similar_families(THAI_OTHER_FAMILY, &families), expected);
|
||||
assert!(!db.is_loaded(THAI_FAMILY));
|
||||
assert_eq!(db.add_font(thai_font(THAI_FAMILY, true).unwrap()), 1);
|
||||
assert_eq!(db.similar_families(THAI_OTHER_FAMILY, &families), expected);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registered_fonts_outside_the_font_folders_are_their_full_paths() {
|
||||
let dir = std::env::temp_dir().join("Fonts");
|
||||
|
||||
@@ -24,5 +24,5 @@ serde_json = { workspace = true }
|
||||
craft-image-codecs = { workspace = true }
|
||||
# The tests lay type out in the bundled fonts (the workspace leaves turning them on to the engine).
|
||||
vectorcraft-text = { workspace = true, features = ["test-fonts", "bundled-fonts"] }
|
||||
# How many times a path is flattened.
|
||||
vectorcraft-doc = { workspace = true, features = ["spine-count"] }
|
||||
# How many times a path is flattened, and how often art is measured for the locked artboards.
|
||||
vectorcraft-doc = { workspace = true, features = ["spine-count", "locked-artboard-count"] }
|
||||
@@ -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);
|
||||
|
||||
@@ -170,7 +170,8 @@ fn round_step(least: f64) -> f64 {
|
||||
/// Draw circle `c`: through three points spread around it, with `shape.circleThroughPoints`, which
|
||||
/// leaves it where it is with Align New Objects to Pixel Grid on, so that it stays tangent. None
|
||||
/// when the three points do not give the circle back to within `tol` (a circle too small for its
|
||||
/// distance from the origin, or too large, in floating point).
|
||||
/// distance from the origin, or too large, in floating point), or when the circle would reach past
|
||||
/// the canvas ([`crate::circle::circle_of`]), which the command refuses.
|
||||
fn draw(c: &SegmentCircle, tol: f64) -> Option<Action> {
|
||||
let (at, r) = (c.circle.center, c.circle.radius);
|
||||
let points: Vec<Point> = [90.0f64, 210.0, 330.0]
|
||||
@@ -180,7 +181,7 @@ fn draw(c: &SegmentCircle, tol: f64) -> Option<Action> {
|
||||
Point::new(at.x + r * k, at.y + r * s)
|
||||
})
|
||||
.collect();
|
||||
let (back, rb) = vectorcraft_geom::shapes::circle_through(points[0], points[1], points[2])?;
|
||||
let (back, rb) = crate::circle::circle_of(&points)?;
|
||||
if !(back.distance(at) <= tol && (rb - r).abs() <= tol) {
|
||||
return None;
|
||||
}
|
||||
@@ -462,7 +463,7 @@ impl Tool for TangentCircleTool {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::testutil::*;
|
||||
use vectorcraft_doc::{Appearance, Document, Node, Selection};
|
||||
use vectorcraft_doc::{Appearance, Document, MAX_COORD, Node, Selection};
|
||||
use vectorcraft_geom::{PathData, SubPath};
|
||||
|
||||
/// Two open lines, (100, 100)–(300, 100) and (100, 140)–(300, 140), and an L from (100, 300)
|
||||
@@ -810,4 +811,40 @@ mod tests {
|
||||
.collect();
|
||||
assert!(matches!(segments[..], [n] if n < 100), "{segments:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_circle_that_would_reach_past_the_canvas_is_not_offered() {
|
||||
// Two lines 40 pt apart ending at the canvas edge, x = 4,000,000: a click at x the first gives
|
||||
// the circle of radius 20 around (x, 120), whose right side is at x + 20.
|
||||
let mut d = Document::new(500.0, 500.0);
|
||||
let l = d.layers[0].id;
|
||||
for y in [100.0, 140.0] {
|
||||
let id = d.alloc_id();
|
||||
let pts = [Point::new(MAX_COORD - 100.0, y), Point::new(MAX_COORD, y)];
|
||||
d.insert(Some(l), 0, Node::path(id, PathData::single(SubPath::polyline(&pts, false)), Appearance::default_art())).unwrap();
|
||||
}
|
||||
let (sel, p) = (Selection::default(), paint());
|
||||
let cx = cx(&d, &sel, &p);
|
||||
let mut t = TangentCircleTool::default();
|
||||
// Past the edge by 5 pt: the note shows, and a click draws nothing.
|
||||
let x = MAX_COORD - 15.0;
|
||||
t.pointer(&cx, &ev(PointerKind::Down, x, 100.0));
|
||||
t.pointer(&cx, &ev(PointerKind::Up, x, 100.0));
|
||||
t.pointer(&cx, &ev(PointerKind::Move, x, 140.0));
|
||||
assert!(t.found.is_none() && t.looked, "{:?}", t.found);
|
||||
assert!(t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == NO_CIRCLE)));
|
||||
t.pointer(&cx, &ev(PointerKind::Down, x, 140.0));
|
||||
assert!(t.pointer(&cx, &ev(PointerKind::Up, x, 140.0)).is_empty(), "nothing drawn");
|
||||
assert!(t.first.is_some(), "the first segment stays for another try");
|
||||
// Its right side 1 pt inside the edge: drawn.
|
||||
let x = MAX_COORD - 21.0;
|
||||
t.key(&cx, ToolKey::Escape, Mods::default());
|
||||
t.pointer(&cx, &ev(PointerKind::Down, x, 100.0));
|
||||
t.pointer(&cx, &ev(PointerKind::Up, x, 100.0));
|
||||
t.pointer(&cx, &ev(PointerKind::Down, x, 140.0));
|
||||
let released = up(&mut t, &cx, &ev(PointerKind::Up, x, 140.0));
|
||||
let (bx, by, w, h) = drawn(&released);
|
||||
assert!((bx - (x - 20.0)).abs() < 1e-3 && (by - 100.0).abs() < 1e-3 && (w - 40.0).abs() < 1e-3 && (h - 40.0).abs() < 1e-3, "{released:?}");
|
||||
assert!(bx + w <= MAX_COORD, "{released:?}");
|
||||
}
|
||||
}
|
||||
@@ -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]
|
||||
|
||||
@@ -451,6 +451,7 @@ impl ToolContext<'_> {
|
||||
skip_guides: !self.guides,
|
||||
clip_outlines: false,
|
||||
area_type_interior: false,
|
||||
ignore_layer_preview: false,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -55,9 +55,9 @@ struct PathWidgets {
|
||||
|
||||
impl PathWidgets {
|
||||
/// The widgets of path `id` at `zoom` (screen px per document point), if it has any: any path
|
||||
/// with Direct Selection (`any_path`), live rectangles and polygons with Selection. `id` is
|
||||
/// editable ([`Document::is_editable`]).
|
||||
fn of(doc: &Document, selection: &Selection, id: NodeId, zoom: f64, any_path: bool) -> Option<Self> {
|
||||
/// with Direct Selection (`any_path`), live rectangles and polygons with Selection, when
|
||||
/// `editable` ([`Document::editable`]) answers true for `id`.
|
||||
fn of(doc: &Document, selection: &Selection, id: NodeId, zoom: f64, any_path: bool, editable: &impl Fn(NodeId) -> bool) -> Option<Self> {
|
||||
if selection.segments.contains_key(&id) {
|
||||
return None;
|
||||
}
|
||||
@@ -65,6 +65,10 @@ impl PathWidgets {
|
||||
if !any_path && !matches!(live.as_deref(), Some(LiveShape::Rectangle { .. } | LiveShape::Polygon { .. })) {
|
||||
return None;
|
||||
}
|
||||
// After the kind: on a locked artboard it measures the art of the layer object holding `id`.
|
||||
if !editable(id) {
|
||||
return None;
|
||||
}
|
||||
let lc = LiveCorners::new(path, live.as_deref())?;
|
||||
let det = lc.xf.determinant().abs();
|
||||
if det < 1e-12 {
|
||||
@@ -105,9 +109,10 @@ impl CornerWidgets {
|
||||
/// The widgets at `zoom` (screen px per document point), if the selection has them: on any
|
||||
/// path with Direct Selection (`any_path`), on live rectangles and polygons with Selection.
|
||||
pub fn of(doc: &Document, selection: &Selection, zoom: f64, any_path: bool) -> Option<Self> {
|
||||
let editable = doc.editable();
|
||||
let paths: Vec<_> =
|
||||
selection.objects.iter().filter(|id| editable(**id)).filter_map(|id| PathWidgets::of(doc, selection, *id, zoom, any_path)).collect();
|
||||
// Made for the first path, then shared: the art on the locked artboards is measured once.
|
||||
let locks = std::cell::OnceCell::new();
|
||||
let editable = |id| locks.get_or_init(|| doc.editable())(id);
|
||||
let paths: Vec<_> = selection.objects.iter().filter_map(|id| PathWidgets::of(doc, selection, *id, zoom, any_path, &editable)).collect();
|
||||
(!paths.is_empty()).then_some(Self { paths })
|
||||
}
|
||||
|
||||
|
||||
+142
-25
@@ -245,10 +245,18 @@ struct PreviewBoxes {
|
||||
revision: Option<(u64, u64)>,
|
||||
geometric: HashMap<NodeId, Option<Rect>>,
|
||||
preview: HashMap<NodeId, Option<Rect>>,
|
||||
/// The editable path holding each corner of a measured object's preview bounds, found when
|
||||
/// the object is measured, so that a pointer move reads no member.
|
||||
holders: HashMap<NodeId, [Option<NodeId>; 4]>,
|
||||
/// Whether a point at each corner (by object and corner number) can be held against its path.
|
||||
holdable: HashMap<(NodeId, usize), bool>,
|
||||
}
|
||||
|
||||
/// How many member paths one pointer move may read to measure objects not yet measured, apart
|
||||
/// from the objects it visits: an object with more members than are left gives no corner on
|
||||
/// that move.
|
||||
const PREVIEW_MEMBER_WORK: usize = 20_000;
|
||||
|
||||
/// A corner of an object's preview bounds that a Linear pick can land on.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct PreviewCorner {
|
||||
@@ -264,7 +272,9 @@ struct PreviewCorner {
|
||||
/// strokes and effects included) nearest `p` within reach, on any editable one whose preview
|
||||
/// bounds differ from its geometric bounds. In a compound path, the member whose own box reaches
|
||||
/// nearest to the corner holds it. The work is bounded, and dimension artwork is skipped, as in
|
||||
/// [`pick`]. `cache` keeps the bounds measured for the document's revision.
|
||||
/// [`pick`]: the objects visited count against one budget, and the member paths read to measure
|
||||
/// them against [`PREVIEW_MEMBER_WORK`]. `cache` keeps the bounds and holders measured for the
|
||||
/// document's revision.
|
||||
fn preview_corner(cx: &ToolContext, p: Point, cache: &mut PreviewBoxes) -> Option<PreviewCorner> {
|
||||
struct Walk<'a, 'c> {
|
||||
symbols: Option<vectorcraft_doc::SymbolBoxes<'a>>,
|
||||
@@ -273,8 +283,38 @@ fn preview_corner(cx: &ToolContext, p: Point, cache: &mut PreviewBoxes) -> Optio
|
||||
p: Point,
|
||||
reach: f64,
|
||||
budget: usize,
|
||||
/// Member paths left to read for objects not yet measured.
|
||||
work: usize,
|
||||
best: Option<(f64, PreviewCorner)>,
|
||||
}
|
||||
/// Takes `count` from the member work left, or nothing when less is left.
|
||||
fn charge(work: &mut usize, count: usize) -> bool {
|
||||
let fits = count <= *work;
|
||||
if fits {
|
||||
*work -= count;
|
||||
}
|
||||
fits
|
||||
}
|
||||
fn corners(r: Rect) -> [Point; 4] {
|
||||
[Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)]
|
||||
}
|
||||
/// For each corner of `preview`, the path whose own box reaches nearest to it: in a compound
|
||||
/// path, the member that puts that corner where it is. A hidden or locked member, or one made
|
||||
/// into a guide, gives no corner. One pass reads each member once for all four corners.
|
||||
fn holders<'n>(members: impl Iterator<Item = &'n Node>, preview: Rect) -> [Option<NodeId>; 4] {
|
||||
let mut best: [Option<(f64, NodeId, bool)>; 4] = [None; 4];
|
||||
for m in members {
|
||||
let Some(b) = m.geometric_bounds() else { continue };
|
||||
let editable = m.visible && !m.locked && !m.is_guide();
|
||||
for ((holder, c), q) in best.iter_mut().zip(corners(b)).zip(corners(preview)) {
|
||||
let gap = c.distance(q);
|
||||
if holder.is_none_or(|(near, _, was)| gap < near || (gap == near && editable && !was)) {
|
||||
*holder = Some((gap, m.id, editable));
|
||||
}
|
||||
}
|
||||
}
|
||||
best.map(|h| h.filter(|(.., editable)| *editable).map(|(_, id, _)| id))
|
||||
}
|
||||
fn visit(n: &Node, w: &mut Walk) {
|
||||
if w.budget == 0 || !n.visible || n.locked || n.extras().dimension.is_some() {
|
||||
return;
|
||||
@@ -284,7 +324,6 @@ fn preview_corner(cx: &ToolContext, p: Point, cache: &mut PreviewBoxes) -> Optio
|
||||
// its strokes reach.
|
||||
let effects = !n.appearance.effects.is_empty() || n.appearance.items.iter().any(|i| !i.effects().is_empty());
|
||||
let reach = n.appearance.outset() + w.reach;
|
||||
let corners = |r: Rect| [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)];
|
||||
// A path is its own member; a compound path's members are its paths.
|
||||
let compound = match &n.kind {
|
||||
NodeKind::Compound { children, .. } => Some(children.as_slice()),
|
||||
@@ -292,25 +331,45 @@ fn preview_corner(cx: &ToolContext, p: Point, cache: &mut PreviewBoxes) -> Optio
|
||||
};
|
||||
let members =
|
||||
|| compound.into_iter().flatten().map(|c| c.as_ref()).chain(compound.is_none().then_some(n)).filter(|m| m.path_data().is_some());
|
||||
// Measuring the object, its bounds or its holders, reads every member once.
|
||||
let count = compound.map_or(1, <[_]>::len);
|
||||
// A path made into a guide draws as a guide, without its strokes or effects. The pointer
|
||||
// test includes the right and bottom edges, as the distance test below does.
|
||||
let within = |r: Rect| (r.x0..=r.x1).contains(&w.p.x) && (r.y0..=r.y1).contains(&w.p.y);
|
||||
if !n.is_guide()
|
||||
&& members().next().is_some()
|
||||
&& let Some(geometric) = *w.cache.geometric.entry(n.id).or_insert_with(|| n.geometric_bounds())
|
||||
// Set once this move has paid for reading the members: measuring the preview bounds and
|
||||
// holders on the same move reads them again without a second charge.
|
||||
let mut paid = false;
|
||||
let geometric = match w.cache.geometric.get(&n.id) {
|
||||
_ if n.is_guide() || members().next().is_none() => None,
|
||||
Some(g) => *g,
|
||||
None if charge(&mut w.work, count) => {
|
||||
paid = true;
|
||||
let g = n.geometric_bounds();
|
||||
w.cache.geometric.insert(n.id, g);
|
||||
g
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
if let Some(geometric) = geometric
|
||||
&& (effects || within(geometric.inflate(reach, reach)))
|
||||
{
|
||||
let doc = w.doc;
|
||||
let measured = match w.cache.preview.get(&n.id) {
|
||||
Some(r) => *r,
|
||||
None => {
|
||||
Some(r) => Some(*r),
|
||||
None if paid || charge(&mut w.work, count) => {
|
||||
let symbols = w.symbols.get_or_insert_with(|| doc.symbol_boxes());
|
||||
let r = vectorcraft_effects::preview::visual_bounds(symbols, n);
|
||||
w.cache.preview.insert(n.id, r);
|
||||
r
|
||||
if let Some(r) = r
|
||||
&& r != geometric
|
||||
{
|
||||
w.cache.holders.insert(n.id, holders(members(), r));
|
||||
}
|
||||
Some(r)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
if let Some(r) = measured
|
||||
if let Some(Some(r)) = measured
|
||||
&& r != geometric
|
||||
{
|
||||
for (k, q) in corners(r).into_iter().enumerate() {
|
||||
@@ -318,26 +377,13 @@ fn preview_corner(cx: &ToolContext, p: Point, cache: &mut PreviewBoxes) -> Optio
|
||||
if d > w.reach || w.best.is_some_and(|(nearest, ..)| d >= nearest) {
|
||||
continue;
|
||||
}
|
||||
// The path whose own box reaches furthest towards the corner holds it: in a
|
||||
// compound path, the member that puts that corner where it is. A hidden or
|
||||
// locked member gives no corner.
|
||||
let mut holder: Option<(f64, NodeId, bool)> = None;
|
||||
for m in members() {
|
||||
let Some(b) = *w.cache.geometric.entry(m.id).or_insert_with(|| m.geometric_bounds()) else { continue };
|
||||
let gap = corners(b).get(k).map_or(f64::INFINITY, |c| c.distance(q));
|
||||
let editable = m.visible && !m.locked;
|
||||
if holder.is_none_or(|(near, _, was)| gap < near || (gap == near && editable && !was)) {
|
||||
holder = Some((gap, m.id, editable));
|
||||
}
|
||||
}
|
||||
let holder = holder.filter(|(.., editable)| *editable).map(|(gap, id, _)| (gap, id));
|
||||
let holder = w.cache.holders.get(&n.id).and_then(|h| h.get(k).copied().flatten());
|
||||
// A path that cannot hold a point at the corner (a stroked dot, whose anchors
|
||||
// all coincide) gives no corner.
|
||||
let holdable = |id: NodeId, cache: &mut PreviewBoxes| {
|
||||
*cache.holdable.entry((n.id, k)).or_insert_with(|| FreePoint::on(doc, id, q).is_some())
|
||||
};
|
||||
let holder = holder.filter(|(_, id)| holdable(*id, w.cache));
|
||||
if let Some(((_, holder), stands_for)) = holder.zip(corners(geometric).get(k).copied()) {
|
||||
if let Some((holder, stands_for)) = holder.filter(|id| holdable(*id, w.cache)).zip(corners(geometric).get(k).copied()) {
|
||||
w.best = Some((d, PreviewCorner { at: q, holder, stands_for }));
|
||||
}
|
||||
}
|
||||
@@ -360,7 +406,7 @@ fn preview_corner(cx: &ToolContext, p: Point, cache: &mut PreviewBoxes) -> Optio
|
||||
if cache.revision != Some(cx.revision) {
|
||||
*cache = PreviewBoxes { revision: Some(cx.revision), ..Default::default() };
|
||||
}
|
||||
let mut w = Walk { symbols: None, doc: cx.doc, cache, p, reach: cx.tol(ANCHOR_REACH), budget: 20_000, best: None };
|
||||
let mut w = Walk { symbols: None, doc: cx.doc, cache, p, reach: cx.tol(ANCHOR_REACH), budget: 20_000, work: PREVIEW_MEMBER_WORK, best: None };
|
||||
for n in cx.doc.layers.iter().rev() {
|
||||
visit(n, &mut w);
|
||||
}
|
||||
@@ -1671,6 +1717,60 @@ mod tests {
|
||||
assert!(t.points.first().is_some_and(|(q, _)| near(*q, Point::new(80.0, 80.0))), "{:?}", t.points);
|
||||
}
|
||||
|
||||
/// A stroked compound path of a small hole and `extra` more tiny squares inside a square from
|
||||
/// 100 to 200, with the ids of the compound, the hole and the square.
|
||||
fn stroked_compound(extra: usize) -> (vectorcraft_doc::Document, [NodeId; 3]) {
|
||||
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 square =
|
||||
|id, a: f64, b: f64| std::sync::Arc::new(Node::path(id, vectorcraft_geom::shapes::rectangle(Rect::new(a, a, b, b)), Default::default()));
|
||||
let mut children = vec![square(hole, 140.0, 160.0), square(part, 100.0, 200.0)];
|
||||
for _ in 0..extra {
|
||||
children.push(square(d.alloc_id(), 150.0, 151.0));
|
||||
}
|
||||
let mut n = Node::new(whole, NodeKind::Compound { children, rule: Default::default() });
|
||||
n.appearance = vectorcraft_doc::Appearance::default_art().into();
|
||||
d.insert(Some(l), 0, n).expect("the compound path");
|
||||
(d, [whole, hole, part])
|
||||
}
|
||||
|
||||
/// The member holding each corner of a compound path is found when the compound is measured,
|
||||
/// and later pointer moves over the same revision take it from the cache without reading the
|
||||
/// members.
|
||||
#[test]
|
||||
fn a_compound_paths_corner_holders_are_found_once_per_revision() {
|
||||
let (d, [whole, hole, part]) = stroked_compound(0);
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) };
|
||||
let mut cache = PreviewBoxes::default();
|
||||
let corner = preview_corner(&c, Point::new(99.5, 99.5), &mut cache).expect("the corner of the stroke");
|
||||
assert_eq!(corner.holder, part, "the member that reaches the corner holds it");
|
||||
assert_eq!(cache.holders.get(&whole), Some(&[Some(part); 4]));
|
||||
// A move over the same revision reads the holder from the cache: one changed there is the
|
||||
// one it gives.
|
||||
cache.holders.insert(whole, [Some(hole); 4]);
|
||||
let corner = preview_corner(&c, Point::new(200.5, 200.5), &mut cache).expect("the corner of the stroke");
|
||||
assert_eq!(corner.holder, hole, "the cached holder is used");
|
||||
}
|
||||
|
||||
/// A compound path with more members than one pointer move may read gives no corner, and is
|
||||
/// neither measured nor cached, so its member work stays bounded. A compound within the limit
|
||||
/// still gives its corner.
|
||||
#[test]
|
||||
fn a_compound_path_past_the_member_work_gives_no_corner() {
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
// Two members plus `extra`: exactly the limit, then one more.
|
||||
for (extra, within) in [(PREVIEW_MEMBER_WORK - 2, true), (PREVIEW_MEMBER_WORK - 1, false)] {
|
||||
let (d, [whole, ..]) = stroked_compound(extra);
|
||||
let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) };
|
||||
let mut cache = PreviewBoxes::default();
|
||||
let corner = preview_corner(&c, Point::new(99.5, 99.5), &mut cache);
|
||||
assert_eq!(corner.is_some(), within, "{} members", extra + 2);
|
||||
assert_eq!(cache.preview.contains_key(&whole), within, "{} members", extra + 2);
|
||||
assert_eq!(cache.geometric.contains_key(&whole), within, "{} members", extra + 2);
|
||||
}
|
||||
}
|
||||
|
||||
/// With Use Preview Bounds on, hovering by a corner of a stroked path's preview bounds, or
|
||||
/// right on it, shows the anchor ring there.
|
||||
#[test]
|
||||
@@ -1837,6 +1937,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());
|
||||
|
||||
@@ -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`]).
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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> {
|
||||
@@ -718,6 +738,9 @@ pub(crate) mod testutil {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod widget_order_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod cursor_tests {
|
||||
use super::testutil::{cx, doc_with_rect, paint};
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -20,13 +20,14 @@ impl MirrorAxis {
|
||||
/// A single editable mirror repeat selected whole. Multi-selection keeps ordinary transforms.
|
||||
pub fn of(doc: &Document, selection: &Selection, zoom: f64) -> Option<Self> {
|
||||
let [id] = selection.objects.as_slice() else { return None };
|
||||
if !selection.anchors.is_empty() || !selection.segments.is_empty() || !doc.is_editable(*id) || !zoom.is_finite() || zoom <= 0.0 {
|
||||
if !selection.anchors.is_empty() || !selection.segments.is_empty() || !zoom.is_finite() || zoom <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let n = doc.node(*id)?;
|
||||
let NodeKind::Repeat(spec) = &n.kind else { return None };
|
||||
let RepeatKind::Mirror { angle, center } = spec.kind else { return None };
|
||||
if !angle.is_finite() || !finite(center) {
|
||||
// After the kind: on a locked artboard it measures the art of the layer object holding `id`.
|
||||
if !angle.is_finite() || !finite(center) || !doc.is_editable(*id) {
|
||||
return None;
|
||||
}
|
||||
let bounds = n.geometric_bounds_with(&doc.symbol_boxes())?;
|
||||
@@ -185,6 +186,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};
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -104,12 +104,14 @@ fn one_group<'a>(doc: &'a Document, selection: &Selection, zoom: f64) -> Option<
|
||||
return None;
|
||||
}
|
||||
let [group] = selection.objects.as_slice() else { return None };
|
||||
if !doc.editable()(*group) {
|
||||
return None;
|
||||
}
|
||||
let n = doc.node(*group)?;
|
||||
let rec = n.extras().objects_on_path.as_deref()?;
|
||||
let children = n.children()?;
|
||||
// After the group is known: on a locked artboard it measures the art of the layer object that
|
||||
// holds `group`.
|
||||
if !doc.editable()(*group) {
|
||||
return None;
|
||||
}
|
||||
let (path, measured) = attachable(children.iter().find(|c| c.id == rec.path)?)?;
|
||||
Some(Group { id: *group, rec, children: children.as_slice(), path, measured: Arc::new(measured) })
|
||||
}
|
||||
@@ -948,6 +950,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 +961,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 +983,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 +1120,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 +1549,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 +1771,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 +2048,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]
|
||||
|
||||
+17
-3
@@ -98,11 +98,15 @@ impl PieWidget {
|
||||
if !selection.anchors.is_empty() || !zoom.is_finite() || zoom <= 0.0 {
|
||||
return vec![];
|
||||
}
|
||||
let editable = doc.editable();
|
||||
let shown = |id: &&NodeId| editable(**id) && !selection.segments.contains_key(*id);
|
||||
// Made for the first ellipse, then shared: on a locked artboard it measures the art of the
|
||||
// layer object that holds each ellipse.
|
||||
let editable = std::cell::OnceCell::new();
|
||||
let mut out = vec![];
|
||||
for id in selection.objects.iter().filter(shown) {
|
||||
for id in selection.objects.iter().filter(|id| !selection.segments.contains_key(*id)) {
|
||||
let Some((e, (start, end))) = Ellipse::of(doc, *id) else { continue };
|
||||
if !editable.get_or_init(|| doc.editable())(*id) {
|
||||
continue;
|
||||
}
|
||||
let c = e.center();
|
||||
for (which, deg) in [(PieEnd::End, end), (PieEnd::Start, start)] {
|
||||
let on = e.point_at(deg);
|
||||
@@ -310,6 +314,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]
|
||||
|
||||
@@ -90,13 +90,14 @@ impl GridHandles {
|
||||
/// bounding box the Selection tool shows; its geometric bounds without one) at `zoom`.
|
||||
pub fn of(doc: &Document, selection: &Selection, frame: Option<OrientedBox>, zoom: f64) -> Option<Self> {
|
||||
let [id] = selection.objects.as_slice() else { return None };
|
||||
if !selection.anchors.is_empty() || !selection.segments.is_empty() || !doc.is_editable(*id) || !zoom.is_finite() || zoom <= 0.0 {
|
||||
if !selection.anchors.is_empty() || !selection.segments.is_empty() || !zoom.is_finite() || zoom <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let n = doc.node(*id)?;
|
||||
let NodeKind::Repeat(spec) = &n.kind else { return None };
|
||||
let RepeatKind::Grid { h_spacing, v_spacing, rows, cols, grid_type, .. } = spec.kind else { return None };
|
||||
if !h_spacing.is_finite() || !v_spacing.is_finite() {
|
||||
// After the kind: on a locked artboard it measures the art of the layer object holding `id`.
|
||||
if !h_spacing.is_finite() || !v_spacing.is_finite() || !doc.is_editable(*id) {
|
||||
return None;
|
||||
}
|
||||
let source = spec.source_bounds()?;
|
||||
@@ -369,6 +370,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();
|
||||
|
||||
@@ -124,13 +124,14 @@ impl RadialHandles {
|
||||
/// at `zoom`.
|
||||
pub fn of(doc: &Document, selection: &Selection, frame: Option<OrientedBox>, zoom: f64) -> Option<Self> {
|
||||
let [id] = selection.objects.as_slice() else { return None };
|
||||
if !selection.anchors.is_empty() || !selection.segments.is_empty() || !doc.is_editable(*id) || !zoom.is_finite() || zoom <= 0.0 {
|
||||
if !selection.anchors.is_empty() || !selection.segments.is_empty() || !zoom.is_finite() || zoom <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let n = doc.node(*id)?;
|
||||
let NodeKind::Repeat(spec) = &n.kind else { return None };
|
||||
let RepeatKind::Radial { instances, radius, center, start_angle, end_angle, .. } = spec.kind else { return None };
|
||||
if ![radius, center.x, center.y, start_angle, end_angle].iter().all(|v| v.is_finite()) {
|
||||
// After the kind: on a locked artboard it measures the art of the layer object holding `id`.
|
||||
if ![radius, center.x, center.y, start_angle, end_angle].iter().all(|v| v.is_finite()) || !doc.is_editable(*id) {
|
||||
return None;
|
||||
}
|
||||
let source = spec.source_bounds()?;
|
||||
@@ -533,6 +534,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();
|
||||
|
||||
+58
-18
@@ -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.
|
||||
@@ -597,8 +608,13 @@ pub(crate) fn shown_box(cx: &ToolContext) -> Option<OrientedBox> {
|
||||
/// Direct Selection's does (#4891).
|
||||
pub(crate) fn hit_center(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, Point)> {
|
||||
let (symbols, editable) = (cx.doc.symbol_boxes(), cx.doc.editable());
|
||||
cx.selection.objects.iter().copied().filter(|id| editable(*id) && crate::direct::in_scope(cx.doc, cx.isolation, *id)).find_map(|id| {
|
||||
let c = cx.doc.node(id).filter(|n| n.shows_center())?.geometric_bounds_with(&symbols)?.center();
|
||||
cx.selection.objects.iter().copied().find_map(|id| {
|
||||
let n = cx.doc.node(id).filter(|n| n.shows_center())?;
|
||||
// After the center: on a locked artboard it measures the art of the layer object holding `id`.
|
||||
if !crate::direct::in_scope(cx.doc, cx.isolation, id) || !editable(id) {
|
||||
return None;
|
||||
}
|
||||
let c = n.geometric_bounds_with(&symbols)?.center();
|
||||
(c.distance(p) <= tol).then_some((id, c))
|
||||
})
|
||||
}
|
||||
@@ -784,6 +800,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 +971,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 +1065,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 +1076,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 +1221,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 +1230,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 +1250,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 +1259,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 +1268,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 +1277,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 +1286,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 +1295,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 +1688,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 +1699,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![],
|
||||
});
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -44,11 +44,15 @@ impl SideWidget {
|
||||
/// segments of it selected.
|
||||
pub fn of(doc: &Document, selection: &Selection, bx: &OrientedBox, zoom: f64) -> Option<Self> {
|
||||
let [id] = selection.objects[..] else { return None };
|
||||
if !selection.anchors.is_empty() || selection.segments.contains_key(&id) || !doc.is_editable(id) || !zoom.is_finite() || zoom <= 0.0 {
|
||||
if !selection.anchors.is_empty() || selection.segments.contains_key(&id) || !zoom.is_finite() || zoom <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let NodeKind::Path { live, .. } = &doc.node(id)?.kind else { return None };
|
||||
let Some(LiveShape::Polygon { sides, .. }) = live.as_deref() else { return None };
|
||||
// After the kind: on a locked artboard it measures the art of the layer object holding `id`.
|
||||
if !doc.is_editable(id) {
|
||||
return None;
|
||||
}
|
||||
let r = bx.rect;
|
||||
let at = bx.to_doc() * Point::new(r.x1 + OFFSET_PX / zoom, r.center().y);
|
||||
(at.x.is_finite() && at.y.is_finite()).then_some(Self { id, at, sides: *sides })
|
||||
|
||||
@@ -32,7 +32,7 @@ impl TraceDivider {
|
||||
/// The divider of the one Image Trace object selected whole, when it shows the Split view.
|
||||
pub fn of(doc: &Document, selection: &Selection, zoom: f64) -> Option<Self> {
|
||||
let [id] = selection.objects.as_slice() else { return None };
|
||||
if !selection.anchors.is_empty() || !selection.segments.is_empty() || !doc.is_editable(*id) || !zoom.is_finite() || zoom <= 0.0 {
|
||||
if !selection.anchors.is_empty() || !selection.segments.is_empty() || !zoom.is_finite() || zoom <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let n = doc.node(*id)?;
|
||||
@@ -41,6 +41,10 @@ impl TraceDivider {
|
||||
}
|
||||
let NodeKind::Group { children, clip: false } = &n.kind else { return None };
|
||||
let NodeKind::Image(im) = &children.first()?.kind else { return None };
|
||||
// After the kind: on a locked artboard it measures the art of the layer object holding `id`.
|
||||
if !doc.is_editable(*id) {
|
||||
return None;
|
||||
}
|
||||
let (width, height) = (f64::from(im.width), f64::from(im.height));
|
||||
let det = im.xf.determinant();
|
||||
if width <= 0.0 || height <= 0.0 || !det.is_finite() || det.abs() < 1e-12 || !im.xf.as_coeffs().iter().all(|c| c.is_finite()) {
|
||||
|
||||
@@ -34,7 +34,7 @@ impl TypeWidget {
|
||||
/// path, nor type in perspective, which transforms whole).
|
||||
pub fn of(doc: &Document, selection: &Selection, bx: &OrientedBox, zoom: f64) -> Option<Self> {
|
||||
let [id] = selection.objects[..] else { return None };
|
||||
if !doc.is_editable(id) || !zoom.is_finite() || zoom <= 0.0 {
|
||||
if !zoom.is_finite() || zoom <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let n = doc.node(id).filter(|n| n.extras().perspective.is_none())?;
|
||||
@@ -44,6 +44,10 @@ impl TypeWidget {
|
||||
TextKind::Area { .. } => true,
|
||||
_ => return None,
|
||||
};
|
||||
// Last: on a locked artboard it measures the art of the layer object that holds `id`.
|
||||
if !doc.is_editable(id) {
|
||||
return None;
|
||||
}
|
||||
let r = bx.rect;
|
||||
Some(Self { id, at: bx.to_doc() * Point::new(r.x1 + OFFSET_PX / zoom, r.center().y), area })
|
||||
}
|
||||
|
||||
@@ -0,0 +1,359 @@
|
||||
//! The Selection tool's on-canvas widgets ask whether an object is editable only once its kind
|
||||
//! can have the widget: on a locked artboard the question measures the art of the layer object
|
||||
//! that holds the object.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::objects_on_path::{CENTER, ObjectsOnPath, place};
|
||||
use vectorcraft_doc::pattern::RepeatSpec;
|
||||
use vectorcraft_doc::{
|
||||
Appearance, Document, ImageObject, LiveShape, Node, NodeId, NodeKind, OrientedBox, Selection, TextKind, TextObject, locked_artboard_measures,
|
||||
};
|
||||
use vectorcraft_geom::{Affine, Point, Rect, shapes};
|
||||
|
||||
use crate::corners::CornerWidgets;
|
||||
use crate::mirror::MirrorAxis;
|
||||
use crate::objects_on_path::Widgets;
|
||||
use crate::pie::PieWidget;
|
||||
use crate::repeat_grid::GridHandles;
|
||||
use crate::repeat_radial::RadialHandles;
|
||||
use crate::select::hit_center;
|
||||
use crate::sidewidget::SideWidget;
|
||||
use crate::testutil::{cx, paint};
|
||||
use crate::trace_split::TraceDivider;
|
||||
use crate::typewidget::TypeWidget;
|
||||
|
||||
/// The page's left edge of the locked artboard: art placed this far right is on it.
|
||||
const LOCKED_X: f64 = 2000.0;
|
||||
|
||||
/// A widget constructor: its name, whether it needs exactly one selected object, the name of an
|
||||
/// object (in [`mixed`]) that has the widget, and what it gives for a selection and a pointer (as
|
||||
/// text).
|
||||
type Site = (&'static str, bool, &'static str, fn(&Document, &Selection, Point) -> String);
|
||||
|
||||
/// The center of the first object of `ids`: where the center widget is looked for.
|
||||
fn pointer(doc: &Document, ids: &[NodeId]) -> Point {
|
||||
ids.first().and_then(|id| doc.node(*id)?.geometric_bounds_with(&doc.symbol_boxes())).map_or(Point::ZERO, |b| b.center())
|
||||
}
|
||||
|
||||
fn center_at(doc: &Document, sel: &Selection, p: Point) -> String {
|
||||
let paint = paint();
|
||||
format!("{:?}", hit_center(&cx(doc, sel, &paint), p, 1.0))
|
||||
}
|
||||
|
||||
const SITES: [Site; 11] = [
|
||||
("type", true, "point type", |d, s, _| format!("{:?}", TypeWidget::of(d, s, &OrientedBox::aligned(Rect::new(0.0, 0.0, 10.0, 10.0)), 1.0))),
|
||||
("pie", false, "ellipse", |d, s, _| format!("{:?}", PieWidget::of(d, s, 1.0))),
|
||||
("objects on path", true, "objects on path", |d, s, _| format!("{:?}", Widgets::of(d, s, 1.0))),
|
||||
("mirror", true, "mirror", |d, s, _| format!("{:?}", MirrorAxis::of(d, s, 1.0))),
|
||||
("grid", true, "grid", |d, s, _| format!("{:?}", GridHandles::of(d, s, None, 1.0))),
|
||||
("radial", true, "radial", |d, s, _| format!("{:?}", RadialHandles::of(d, s, None, 1.0))),
|
||||
("sides", true, "polygon", |d, s, _| format!("{:?}", SideWidget::of(d, s, &OrientedBox::aligned(Rect::new(0.0, 0.0, 10.0, 10.0)), 1.0))),
|
||||
("trace split", true, "trace", |d, s, _| format!("{:?}", TraceDivider::of(d, s, 1.0))),
|
||||
("corners", false, "live rectangle", |d, s, _| format!("{:?}", CornerWidgets::of(d, s, 1.0, false))),
|
||||
("corners of any path", false, "rectangle", |d, s, _| format!("{:?}", CornerWidgets::of(d, s, 1.0, true))),
|
||||
("center", false, "ellipse", center_at),
|
||||
];
|
||||
|
||||
fn with_live(id: NodeId, shape: LiveShape) -> Node {
|
||||
let mut n = Node::path(id, shape.to_path(), Appearance::default_art());
|
||||
if let NodeKind::Path { live: slot, .. } = &mut n.kind {
|
||||
*slot = Some(Box::new(shape));
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
fn rect(d: &mut Document, r: Rect) -> Node {
|
||||
Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::default_art())
|
||||
}
|
||||
|
||||
fn repeat(d: &mut Document, dx: f64, spec: fn(Vec<Arc<Node>>) -> RepeatSpec) -> Node {
|
||||
let source = rect(d, Rect::new(dx + 500.0, 500.0, dx + 540.0, 540.0));
|
||||
let mut n = rect(d, Rect::new(dx + 500.0, 500.0, dx + 540.0, 540.0));
|
||||
n.kind = NodeKind::Repeat(spec(vec![Arc::new(source)]));
|
||||
n
|
||||
}
|
||||
|
||||
/// The objects every widget is asked about, by name, placed `dx` right of the page's origin. `big`
|
||||
/// is a group of that many rectangles.
|
||||
fn objects(d: &mut Document, dx: f64, big: usize) -> Vec<(&'static str, Node)> {
|
||||
let mut out = vec![("rectangle", rect(d, Rect::new(dx + 50.0, 50.0, dx + 150.0, 150.0)))];
|
||||
let mut centered = rect(d, Rect::new(dx + 50.0, 200.0, dx + 150.0, 260.0));
|
||||
centered.edit_attrs(|a| a.show_center = Some(true));
|
||||
out.push(("rectangle with its center shown", centered));
|
||||
let ellipse = |d: &mut Document, y: f64| {
|
||||
with_live(d.alloc_id(), LiveShape::Ellipse { w: 120.0, h: 60.0, pie: (0.0, 90.0), xf: Affine::translate((dx + 200.0, y)) })
|
||||
};
|
||||
out.push(("ellipse", ellipse(d, 50.0)));
|
||||
let mut hidden_center = ellipse(d, 150.0);
|
||||
hidden_center.edit_attrs(|a| a.show_center = Some(false));
|
||||
out.push(("ellipse with its center hidden", hidden_center));
|
||||
let polygon = LiveShape::Polygon {
|
||||
radius: 50.0,
|
||||
sides: 6,
|
||||
xf: Affine::translate((dx + 400.0, 100.0)),
|
||||
radii: vec![],
|
||||
kinds: vec![],
|
||||
radii_relative: false,
|
||||
};
|
||||
out.push(("polygon", with_live(d.alloc_id(), polygon)));
|
||||
let live_rect = LiveShape::Rectangle {
|
||||
w: 100.0,
|
||||
h: 80.0,
|
||||
radii: [0.0; 4],
|
||||
kinds: Default::default(),
|
||||
radii_relative: false,
|
||||
xf: Affine::translate((dx + 50.0, 300.0)),
|
||||
};
|
||||
out.push(("live rectangle", with_live(d.alloc_id(), live_rect)));
|
||||
let point = TextObject::point(Point::new(dx + 300.0, 300.0), "Point", Default::default());
|
||||
out.push(("point type", Node::new(d.alloc_id(), NodeKind::Text(Box::new(point)))));
|
||||
let mut area = TextObject::point(Point::new(dx + 300.0, 400.0), "Area", Default::default());
|
||||
area.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, 120.0, 40.0)) };
|
||||
out.push(("area type", Node::new(d.alloc_id(), NodeKind::Text(Box::new(area)))));
|
||||
let line = Node::path(d.alloc_id(), shapes::line(Point::new(dx, 700.0), Point::new(dx + 400.0, 700.0)), Appearance::default_art());
|
||||
let (a, b) = (rect(d, Rect::new(dx + 50.0, 600.0, dx + 70.0, 620.0)), rect(d, Rect::new(dx + 100.0, 600.0, dx + 120.0, 620.0)));
|
||||
let rec = ObjectsOnPath::new(line.id, &[&a, &b], CENTER, 0.0);
|
||||
let mut on_path = Node::new(d.alloc_id(), NodeKind::Group { children: vec![Arc::new(line), Arc::new(a), Arc::new(b)], clip: false });
|
||||
on_path.extras_mut().objects_on_path = Some(Box::new(rec));
|
||||
place(&mut on_path, &Document::new(1.0, 1.0).symbol_boxes());
|
||||
out.push(("objects on path", on_path));
|
||||
out.push(("mirror", repeat(d, dx, |s| RepeatSpec::mirror(s, 90.0, 10.0))));
|
||||
out.push(("grid", repeat(d, dx, |s| RepeatSpec::grid(s, 20.0, 20.0))));
|
||||
out.push(("radial", repeat(d, dx, |s| RepeatSpec::radial(s, 8, Some(100.0)))));
|
||||
let im = ImageObject {
|
||||
key: "k".into(),
|
||||
width: 100,
|
||||
height: 50,
|
||||
xf: Affine::translate((dx + 600.0, 600.0)),
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
let source = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im)));
|
||||
let mut traced = Node::group(d.alloc_id(), vec![Arc::new(source)]);
|
||||
traced.extras_mut().trace = Some(Box::new(json!({"view": "split", "split": 0.5})));
|
||||
out.push(("trace", traced));
|
||||
out.push(("big group", grid_of_rects(d, Point::new(dx + 700.0, 50.0), big, 50)));
|
||||
out
|
||||
}
|
||||
|
||||
/// A group of `count` 3 × 3 rectangles, `per_row` to a row, 5 apart, from `at`.
|
||||
fn grid_of_rects(d: &mut Document, at: Point, count: usize, per_row: usize) -> Node {
|
||||
let members = (0..count)
|
||||
.map(|i| {
|
||||
let (x, y) = (at.x + (i % per_row) as f64 * 5.0, at.y + (i / per_row) as f64 * 5.0);
|
||||
Arc::new(rect(d, Rect::new(x, y, x + 3.0, y + 3.0)))
|
||||
})
|
||||
.collect();
|
||||
Node::group(d.alloc_id(), members)
|
||||
}
|
||||
|
||||
fn is_empty(widget: &str) -> bool {
|
||||
matches!(widget, "None" | "[]") || widget == format!("{:?}", Widgets::default())
|
||||
}
|
||||
|
||||
/// A document with one artboard that is not locked and, at [`LOCKED_X`], one that is, holding
|
||||
/// [`objects`] on each, plus an ellipse on a locked layer and a polygon on a hidden one. Each
|
||||
/// object's name, whether it is on the locked artboard, and its id.
|
||||
fn mixed(big: usize) -> (Document, Vec<(&'static str, bool, NodeId)>) {
|
||||
let mut d = Document::new(1000.0, 1000.0);
|
||||
let mut board = d.artboards[0].clone();
|
||||
board.rect = Rect::new(LOCKED_X, 0.0, LOCKED_X + 1000.0, 1000.0);
|
||||
board.locked = true;
|
||||
d.artboards.push(board);
|
||||
let l = d.layers[0].id;
|
||||
let mut ids = vec![];
|
||||
for (dx, on) in [(0.0, false), (LOCKED_X, true)] {
|
||||
for (name, n) in objects(&mut d, dx, big) {
|
||||
ids.push((name, on, n.id));
|
||||
d.insert(Some(l), 0, n).unwrap();
|
||||
}
|
||||
}
|
||||
for (name, hide) in [("ellipse", false), ("polygon", true)] {
|
||||
let layer = d.add_layer(None);
|
||||
let n = objects(&mut d, 0.0, 0).into_iter().find(|(o, _)| *o == name).map(|(_, n)| n).unwrap();
|
||||
ids.push((name, false, n.id));
|
||||
d.insert(Some(layer), 0, n).unwrap();
|
||||
let layer = d.node_mut(layer).unwrap();
|
||||
if hide {
|
||||
layer.visible = false;
|
||||
} else {
|
||||
layer.locked = true;
|
||||
}
|
||||
}
|
||||
(d, ids)
|
||||
}
|
||||
|
||||
fn selection(ids: &[NodeId]) -> Selection {
|
||||
let mut s = Selection::default();
|
||||
s.set(ids.iter().copied());
|
||||
s
|
||||
}
|
||||
|
||||
/// `doc` with every artboard and layer unlocked and every layer shown: everything in it is
|
||||
/// editable.
|
||||
fn all_editable(doc: &Document) -> Document {
|
||||
let mut free = doc.clone();
|
||||
for a in &mut free.artboards {
|
||||
a.locked = false;
|
||||
}
|
||||
for l in doc.layers.iter().map(|l| l.id) {
|
||||
let n = free.node_mut(l).unwrap();
|
||||
(n.visible, n.locked) = (true, false);
|
||||
}
|
||||
free
|
||||
}
|
||||
|
||||
/// Every widget gives what it gave when it asked about editability first: for an editable object,
|
||||
/// what it gives with everything editable, and for one that is not, what it gives without it.
|
||||
#[test]
|
||||
fn the_widgets_are_the_same_as_when_editability_came_first() {
|
||||
let (doc, ids) = mixed(20);
|
||||
let free = all_editable(&doc);
|
||||
let all: Vec<NodeId> = ids.iter().map(|o| o.2).collect();
|
||||
let mut selections: Vec<Vec<NodeId>> = all.iter().map(|id| vec![*id]).collect();
|
||||
selections.extend(all.windows(2).map(<[NodeId]>::to_vec));
|
||||
selections.extend([all.clone(), all.iter().rev().copied().collect(), vec![], vec![NodeId(u64::MAX)]]);
|
||||
let editable = doc.editable();
|
||||
for ids in &selections {
|
||||
let sel = selection(ids);
|
||||
let kept = selection(&ids.iter().copied().filter(|id| editable(*id)).collect::<Vec<_>>());
|
||||
let p = pointer(&doc, ids);
|
||||
for (name, single, _, f) in SITES {
|
||||
// A widget of one object only shows for a selection of one, editable or not.
|
||||
let old = f(&free, if single && ids.len() != 1 { &sel } else { &kept }, p);
|
||||
assert_eq!(f(&doc, &sel, p), old, "{name} of {ids:?}");
|
||||
}
|
||||
}
|
||||
// Each widget shows for an object of its kind off the locked artboard and not on it, so the
|
||||
// comparison is not of empty results alone.
|
||||
for (name, _, has, f) in SITES {
|
||||
for on in [false, true] {
|
||||
let (_, _, id) = ids.iter().find(|o| o.0 == has && o.1 == on).unwrap();
|
||||
let w = f(&doc, &selection(&[*id]), pointer(&doc, &[*id]));
|
||||
assert_eq!(is_empty(&w), on, "{name} of the {has} (on the locked artboard: {on}): {w}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An object of another kind is not measured for the locked artboard, alone or with others; an
|
||||
/// object of the widget's kind still is, and its widget is left out.
|
||||
#[test]
|
||||
fn widgets_measure_no_art_for_objects_of_other_kinds() {
|
||||
let (doc, ids) = mixed(500);
|
||||
let id = |name: &str, on: bool| ids.iter().find(|o| o.0 == name && o.1 == on).map(|o| o.2).unwrap();
|
||||
let big = id("big group", true);
|
||||
let others = [big, id("rectangle", true), id("area type", true), id("trace", true)];
|
||||
let mut measured = vec![];
|
||||
for (name, single, has, f) in SITES {
|
||||
let several: Vec<NodeId> = others.iter().copied().filter(|o| *o != id(has, true)).collect();
|
||||
for ids in [vec![big], several] {
|
||||
if single && ids.len() != 1 {
|
||||
continue;
|
||||
}
|
||||
let before = locked_artboard_measures();
|
||||
std::hint::black_box(f(&doc, &selection(&ids), pointer(&doc, &ids)));
|
||||
if locked_artboard_measures() != before {
|
||||
measured.push(format!("{name} of {ids:?}"));
|
||||
}
|
||||
}
|
||||
let before = locked_artboard_measures();
|
||||
std::hint::black_box(f(&doc, &selection(&[id(has, true)]), pointer(&doc, &[id(has, true)])));
|
||||
assert!(locked_artboard_measures() > before, "{name} of a {has} on the locked artboard");
|
||||
}
|
||||
assert_eq!(measured, Vec::<String>::new());
|
||||
}
|
||||
|
||||
fn thread_cpu() -> Option<std::time::Duration> {
|
||||
let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?;
|
||||
stat.split_whitespace().next()?.parse().ok().map(std::time::Duration::from_nanos)
|
||||
}
|
||||
|
||||
/// The time `f` takes: this thread's CPU time where Linux reports it, otherwise the wall clock.
|
||||
fn cpu_time(f: impl FnOnce()) -> std::time::Duration {
|
||||
match thread_cpu() {
|
||||
Some(before) => {
|
||||
f();
|
||||
thread_cpu().map_or(std::time::Duration::ZERO, |after| after.saturating_sub(before))
|
||||
}
|
||||
None => {
|
||||
let start = std::time::Instant::now();
|
||||
f();
|
||||
start.elapsed()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Timings of each widget for a group of 5,000 rectangles and for 128 rectangles, selected on a
|
||||
/// locked artboard and with no artboard locked, 100 calls a run: with the editability check first
|
||||
/// (the selection's editable objects are kept, then the widget is asked about them in the document
|
||||
/// with everything editable, as in [`the_widgets_are_the_same_as_when_editability_came_first`]),
|
||||
/// and as the widgets are now. 7 runs each, in turn. Ignored by default; it prints the median per
|
||||
/// call and sets no bound on it:
|
||||
/// `cargo test --release -p vectorcraft-tools --lib widget_order_perf -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore = "a benchmark: run with --ignored --nocapture"]
|
||||
fn widget_order_perf() {
|
||||
const RUNS: usize = 7;
|
||||
const CALLS: usize = 100;
|
||||
eprintln!("widget_order_perf: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" });
|
||||
let (mut locked, _) = mixed(0);
|
||||
let l = locked.layers[0].id;
|
||||
let group = grid_of_rects(&mut locked, Point::new(LOCKED_X, 0.0), 5000, 100);
|
||||
let group_id = group.id;
|
||||
locked.insert(Some(l), 0, group).unwrap();
|
||||
let mut rects = vec![];
|
||||
for i in 0..128 {
|
||||
let (x, y) = (LOCKED_X + (i % 16) as f64 * 60.0, 600.0 + (i / 16) as f64 * 40.0);
|
||||
let n = rect(&mut locked, Rect::new(x, y, x + 30.0, y + 30.0));
|
||||
rects.push(n.id);
|
||||
locked.insert(Some(l), 0, n).unwrap();
|
||||
}
|
||||
let unlocked = all_editable(&locked);
|
||||
for (doc, board) in [(&locked, "locked artboard"), (&unlocked, "no artboard locked")] {
|
||||
for (what, ids) in [("a group of 5,000", vec![group_id]), ("128 rectangles", rects.clone())] {
|
||||
timings(doc, &selection(&ids), &format!("{what}, {board}"));
|
||||
}
|
||||
}
|
||||
|
||||
fn timings(doc: &Document, sel: &Selection, case: &str) {
|
||||
// The widgets' own editability checks find nothing locked here, so each object's
|
||||
// editability is measured once, as when it came first.
|
||||
let free = all_editable(doc);
|
||||
for (name, single, _, f) in SITES {
|
||||
if single && sel.objects.len() != 1 {
|
||||
continue;
|
||||
}
|
||||
let p = pointer(doc, &sel.objects);
|
||||
let before = || {
|
||||
for _ in 0..CALLS {
|
||||
let editable = doc.editable();
|
||||
let kept = selection(&sel.objects.iter().copied().filter(|id| editable(*id)).collect::<Vec<_>>());
|
||||
std::hint::black_box(f(std::hint::black_box(&free), &kept, p));
|
||||
}
|
||||
};
|
||||
let after = || {
|
||||
for _ in 0..CALLS {
|
||||
std::hint::black_box(f(std::hint::black_box(doc), sel, p));
|
||||
}
|
||||
};
|
||||
let (mut old, mut new) = (vec![], vec![]);
|
||||
for run in 0..RUNS {
|
||||
// The two take turns going first.
|
||||
if run % 2 == 0 {
|
||||
old.push(cpu_time(before));
|
||||
new.push(cpu_time(after));
|
||||
} else {
|
||||
new.push(cpu_time(after));
|
||||
old.push(cpu_time(before));
|
||||
}
|
||||
}
|
||||
old.sort();
|
||||
new.sort();
|
||||
let us = |d: std::time::Duration| d.as_secs_f64() * 1e6 / CALLS as f64;
|
||||
eprintln!("{name}, {case}: {:.2} µs a call with the check first, {:.2} µs without", us(old[RUNS / 2]), us(new[RUNS / 2]));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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]
|
||||
|
||||
@@ -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
@@ -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).
|
||||
|
||||
+91
-29
@@ -957,7 +957,8 @@ link, and `graphicStyle.apply` with `add` unlinks the group. With `appearance.tr
|
||||
target group's paths keeps its look on a move, and a `source` that is the group's only path is an error.
|
||||
`graphicStyle.redefine` gives the style to the paths directly in a series group linked to it, whether or not the group
|
||||
has rows of its own, links them, and clears and unlinks the group; the source and the paths linked to the style whose
|
||||
look was edited keep their look. Read as a source, by `graphicStyle.new`, `graphicStyle.redefine` or
|
||||
look was edited keep their look, and a path in the group linked to another style keeps its look and its link. Read as a
|
||||
source, by `graphicStyle.new`, `graphicStyle.redefine` or
|
||||
`appearance.transfer`, a series group that has no fill, stroke, effect, opacity, blend mode, isolation, knockout or
|
||||
style link of its own gives the look and the style link of the topmost path directly in it, and a move with
|
||||
`appearance.transfer` clears each of those paths; a series group that has one of them is read itself.
|
||||
@@ -2556,10 +2557,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
|
||||
@@ -3885,7 +3886,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
|
||||
@@ -5147,7 +5151,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}}}}
|
||||
@@ -5702,11 +5706,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.
|
||||
@@ -6218,7 +6226,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
|
||||
@@ -7574,16 +7583,22 @@ or breaks these rules, opens with the image placed by its transform. A drag is o
|
||||
the corners where they are records none. Image info (`image.info`) gives a distorted image's resolution at its middle, and Link
|
||||
Info (`links.info`) gives its scale and rotation there.
|
||||
|
||||
Crop Image (`object.cropImage`), Image Trace (`imageTrace.make`, `imageTrace.makeAndExpand`), Relink (`links.relink`),
|
||||
Embed (`links.embed`), Unembed (`links.unembed`), Create Object Mosaic (`object.createObjectMosaic`) and Place with
|
||||
Replace (`file.place` with `replace`) of anything but a text file refuse a distorted image with an error that names the
|
||||
distortion; Place with Replace does not refuse a clipping group that holds a distorted image of a DCS file's plates. Relink and Unembed refuse a named or selected distorted image before they search a folder or write a file.
|
||||
Create Gradient Mesh (`object.mesh.create`) converts the other objects it is given and lists each distorted image it
|
||||
leaves as it is in `skipped`, with its `id` and the error as `reason`; with nothing else to convert, it returns that
|
||||
error. Update Links (`links.update`) puts a changed file's pixels between a distorted
|
||||
image's corners, without applying its Placement Options. Mask (`object.maskImage`) draws its clipping path through the
|
||||
image's corners. Rasterize (`object.rasterize`) draws the image between its corners and makes a plain image of the
|
||||
result. These rules are VectorCraft's own.
|
||||
Crop Image (`object.cropImage`), Image Trace (`imageTrace.make`, `imageTrace.makeAndExpand`), Create Object Mosaic
|
||||
(`object.createObjectMosaic`) and Place with Replace (`file.place` with `replace`) of anything but a text file refuse a
|
||||
distorted image with an error that names the distortion; Place with Replace does not refuse a clipping group that holds
|
||||
a distorted image of a DCS file's plates. Create Gradient Mesh (`object.mesh.create`) converts the other objects it is
|
||||
given and lists each distorted image it leaves as it is in `skipped`, with its `id` and the error as `reason`; with
|
||||
nothing else to convert, it returns that error. Update Links (`links.update`) and Relink
|
||||
(`links.relink`) put the file's pixels between a distorted image's corners, without applying its Placement Options or
|
||||
Relink's `preserve`. When `preserve` is given, Relink adds a `warnings` entry naming those images; without it, Relink
|
||||
adds none for them. The clipping path a PSD, PSB or DCS
|
||||
file names is drawn through the corners: the clip group of the old file's clipping path gets the new file's clipping
|
||||
path, or becomes a plain group when the new file names none. Embed (`links.embed`) and Unembed (`links.unembed`) keep
|
||||
the corners, each in one undo step. Unembed of a distorted image from a PSD or PSB file, written as stored (PNG, or
|
||||
TIFF for a CMYK file), keeps the clip group of that file's clipping path, and so do Relink and Update Links to the
|
||||
file it wrote; a path that converts the image writes no clipping path, and the clip group becomes a plain group. Mask
|
||||
(`object.maskImage`) draws its clipping path through the image's corners. Rasterize (`object.rasterize`) draws the
|
||||
image between its corners and makes a plain image of the result. These rules are VectorCraft's own.
|
||||
|
||||
```json
|
||||
{"name":"run_command","arguments":{"command":"object.distort","params":{"corners":[[40,0],[60,0],[100,100],[0,100]]}}}
|
||||
@@ -9136,7 +9151,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. In Draw Behind, an Alt-drag (Option-drag on macOS) of whole objects with
|
||||
the Selection or Direct Selection tool puts each copy directly below its own original, in the original's group or layer,
|
||||
and selects the copies: the tools send `object.transform` with `copy` and `drawBehind: true`. The copy of the clipping
|
||||
@@ -11431,6 +11447,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
|
||||
@@ -12587,7 +12644,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
|
||||
@@ -12607,7 +12664,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
|
||||
@@ -12629,7 +12686,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
|
||||
@@ -13221,7 +13279,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
|
||||
@@ -14200,8 +14259,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
|
||||
@@ -14502,8 +14564,8 @@ Tools:
|
||||
outside it with a point on it (within a millionth of its radius); it never crosses the first segment, and it
|
||||
touches the two segments at different points. The circle is a new ellipse with the current paint, drawn through
|
||||
three of its points with `shape.circleThroughPoints` so that Align New Objects to Pixel Grid leaves it in place, one
|
||||
undo step. A circle too small or too large for its three points to give it back in floating point counts as no
|
||||
circle. Shift pressed or let go during a click counts at the release. With no circle the note shows, a click draws
|
||||
undo step. A circle too small or too large for its three points to give it back in floating point, or one that
|
||||
would reach past the canvas (4,000,000 pt from the origin), counts as no circle. Shift pressed or let go during a click counts at the release. With no circle the note shows, a click draws
|
||||
nothing and the first segment stays picked; it also stays when drawing the circle fails or the press on the second
|
||||
segment is canceled (a canceled touch). Escape, an edit, Undo or Redo outside the tool, another document, or a
|
||||
change to the first segment that makes no undo step (a live preview, or one that was canceled) forgets the first
|
||||
|
||||
+7
-3
@@ -34,7 +34,7 @@ in `crates/engine/src/cmd/plugin.rs`).
|
||||
| `plugin.inspect` | as `plugin.install`: `{"path"}` or `{"dataBase64", "name"?}` | Validates a module without installing it; returns the `plugin.list` entry it would have, plus `needsApproval` (true when installing it needs a person's approval), `needsReplace` (true when `plugin.install` needs `replace: true`), and the `commandAllowlist` ids no command has (`unknownCommands`) and those no plug-in may call (`refusedCommands`). |
|
||||
| `plugin.remove` | `{"id"}` | Uninstalls, and deletes it from the `Plug-ins` folder with its [settings and cache](#settings-and-cache). |
|
||||
| `plugin.clearCache` | `{"id"?}` | Deletes every entry in the [cache](#settings-and-cache) of plug-in `id`, or of every installed plug-in; settings stay. Returns `{"cleared": [id], "bytesFreed"}`. |
|
||||
| `plugin.reload` | `{"path"?: "folder"}` (default: the preference folder) | Installs every `*.wasm` in a folder; a bad module is reported and skipped, and so are a heavy filter and a plug-in whose permissions the user hasn't granted (nobody was asked). |
|
||||
| `plugin.reload` | `{"path"?: "folder"}` (default: the preference folder) | Installs every `*.wasm` in a folder, the first 1,000 by file name; a bad module is reported and skipped, and so are an entry that is not a regular file, a heavy filter and a plug-in whose permissions the user hasn't granted (nobody was asked). Returns `{"folder", "loaded", "failed": [{file, error}], "leftOut"}`; `leftOut` counts the `*.wasm` files past the first 1,000, which were not tried. |
|
||||
|
||||
Live effects are applied like any effect: `effect.apply {"effect": "plugin.<id>", "params": {…}}`, edited with
|
||||
`effect.setParams`, listed by `effect.list` (menu `Effect › Plug-ins`) and baked by Object › Expand Appearance.
|
||||
@@ -108,7 +108,10 @@ replaced by a module without it.
|
||||
**Preference folder.** Edit › Preferences › Plug-ins & Scratch Disks › *Additional Plug-ins Folder*: when set, every
|
||||
`*.wasm` in that folder (not recursive) is installed at startup and whenever the preference changes (desktop builds;
|
||||
the web build installs from bytes). On the desktop, Choose… beside the field picks the folder; the dialog refuses a
|
||||
picked or typed folder whose contents can't be listed, and `prefs.set` refuses such a folder too.
|
||||
picked or typed folder whose contents can't be listed, and `prefs.set` refuses such a folder too. A folder load reads at
|
||||
most 1,000 `.wasm` files, the first ones by file name (VectorCraft's own limit); its report counts the files left out
|
||||
(`leftOut`). An entry that is not a regular file, such as a subfolder or a named pipe with a `.wasm` name, is listed in
|
||||
the report and skipped, and the load does not wait on a named pipe.
|
||||
|
||||
Plug-ins are installed **per process**, not per document. Documents store a live effect as an ordinary effect record
|
||||
(`{"id": "plugin.<id>", "params": {…}}`): while the plug-in is installed it is drawn, exported and expanded; without it
|
||||
@@ -684,7 +687,8 @@ every attribute:
|
||||
`"unknown"`, read from the image itself. An image whose corners Perspective Distort or Free Distort moved to a shape
|
||||
that is not a parallelogram also has `corners`, its pixel rectangle's corners on the page (top left, top right,
|
||||
bottom right, bottom left), and its `transform` is then the affine placement nearest them, the one that matches the
|
||||
perspective at the middle of its pixels. An embedded image whose pixels take at most 1 MiB in base64 (443 × 443
|
||||
perspective at the middle of its pixels. Corners that make a parallelogram are described by `transform` alone. An
|
||||
embedded image whose pixels take at most 1 MiB in base64 (443 × 443
|
||||
pixels fit) has them in `pixelsBase64`: straight RGBA, 8 bits a channel, row by row from the top, and
|
||||
`pixelsOmitted: false`. A CMYK image's pixels are its inks through the working CMYK profile, as sRGB. The pixels of
|
||||
all the images in one input take at most 16 MiB in base64, and an image the host starts to decode takes its size
|
||||
|
||||
@@ -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`.
|
||||
@@ -1194,7 +1195,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- After a rotation the Scale and Reflect tools, the Scale and Reflect dialogs, `object.scale`, `object.reflect` with a named axis and the Transform and Properties panels' flips act along the selection's turned bounding box until Reset Bounding Box: the horizontal and vertical scale stretch along its own width and height, and the vertical and horizontal reflection axes are its own. The Reflect tool's default axis and its Shift steps start from the box's axes, and an axis drawn with the tool is the line drawn on the page. `basis: "page"` keeps the page's axes (VectorCraft's own rules; `bboxrotate::scale_and_reflect_follow_the_turned_box`, tools `xform::transform::tests::scale_and_reflect_drags_follow_a_turned_bounding_box`).
|
||||
- The Reflect tool sets an axis with two clicks: a click sets the first point (and the reference point), and a second click reflects the selection across the line through both points as one undo step; Alt/Option on the second click reflects a copy, and a drag after the first click draws the axis from it ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/reflect-or-flip-objects.html)). A dashed line runs from the first point to the pointer until the second click. VectorCraft's own rules: an Alt-click opens the dialog and sets no axis; a second click whose snapped point is within 3 screen pixels of the first point's snapped point does nothing and the axis keeps waiting; Shift does not constrain a plain second click; Escape, Enter, a changed selection, an edit made outside the tool or another tool drops the waiting axis. A double-click arrives as two clicks: its first click is the second point, so a double-click away from the first point reflects the selection, and the double-click then opens the dialog with no axis waiting (tools `xform::transform::tests::a_second_reflect_click_reflects_across_the_line_through_both_points` and the four tests after it; engine `xform::two_reflect_clicks_reflect_across_their_line_as_one_undo_step`).
|
||||
- Perspective Distort and Free Distort (`object.distort`) turn each warped object's bounding box as the warp turns the object at its own center, the objects inside groups, compound paths and clip groups and the art of linked opacity masks included, so the next Selection or Free Transform drag uses the tilted box; Object › Transform › Reset Bounding Box squares it again, and corners left where they are add no undo step (VectorCraft's own rule; `bboxrotate::distort_turns_an_upright_box_with_the_warp_at_its_center`, `distort_turns_each_member_and_linked_mask_by_its_own_warp`, `mirrored_and_collapsing_distorts_keep_valid_angles`, `distort_angles_undo_redo_and_reopen_together`, `xform::unchanged_distort_records_no_history`).
|
||||
- Perspective Distort and Free Distort (`object.distort`) move an image's four corners exactly onto the handles when the image is distorted alone; with other objects the handles stand for the whole selection, and the image's corners follow the same warp without necessarily landing on them. The image's pixels are drawn in perspective between its corners on the canvas, in print and in every export that holds images, as a mesh of affine image pieces (DXF and WMF write the nearest parallelogram and warn, as the `.ai` writers do for an image nested 8 deep in opacity masks, symbols, live objects and pattern tiles, or in a legacy `.ai` in symbols and live objects, not counting ordinary groups and layers, and leave out an image nested deeper; HP-GL plots leave images out); the native file saves the corners; bounds, clicks, blends, the Eyedropper, Outline view, the Color Theme Picker and Weed Box and Lines follow them; Image info and Link Info measure the image at its middle; and corners that would fold the image over, fall on one line, cross the warp's horizon or lie too close together for a perspective map are refused. Crop Image, Image Trace, Relink, Embed, Unembed, Create Object Mosaic, Create Gradient Mesh and Place with Replace refuse a distorted image (Place with Replace refuses only when the object it measures is the distorted image, so it does not refuse when the placed file is text or the replaced object is a DCS file's plates); Update Links puts a changed file's pixels between its corners; Rasterize makes a plain image of it. All of this is VectorCraft's own rule (doc `image_quad::tests`, `blend::tests::steps_between_distorted_images_have_corners_between_theirs`; engine `xform::distort_puts_an_images_corners_on_the_handles`, `distort_moves_an_image_and_a_path_as_one`, `distort_refuses_a_folded_image_and_crop_and_trace_refuse_a_distorted_one`, `distort_names_the_horizon_and_an_unchanged_distort_of_a_distorted_image_records_nothing`, `distort_of_a_blend_holding_an_image_is_not_refused`, `free_transform_distort_drag_on_an_image_is_one_undo_step`, `mask_on_a_distorted_image_follows_its_corners`, `a_transform_effect_moves_a_distorted_images_corners`, `a_transform_after_a_warp_moves_a_distorted_image_once`, `baked_raster_effect_pixels_replace_a_distortion`, `rasterize_draws_a_distorted_image_between_its_corners`, `image_info_measures_a_distorted_image_at_its_middle`, `a_distorted_image_saves_and_reads_back`, `links::update_links_keeps_a_distorted_images_corners`, `recolor::theme_picker_reads_a_distorted_image_where_it_is_drawn`, `addons::cutting::weed::tests::a_distorted_image_is_measured_by_the_frame_through_its_corners`; render `outline_mode_draws_a_distorted_images_frame_through_its_corners`, `meshwarp::outline_mode_paints_a_distorted_images_pixels_once_where_its_pieces_overlap`, `meshwarp::the_canvas_cuts_a_distorted_images_mesh_for_the_zoom`, `objectfx::a_distorted_image_is_opaque_between_its_corners_and_its_shadow_follows_them`, `objectfx::a_distorted_image_is_opaque_inside_its_corners_at_every_zoom`; svg `warp_pieces::a_distorted_image_is_written_between_its_corners`; pdf `compression::a_distorted_image_is_written_with_its_corners_on_its_quad`; eps `a_distorted_image_is_written_with_its_corners_on_its_quad`, `ai_editing::tests::a_distorted_image_nested_as_deep_as_the_limit_is_written_as_its_nearest_placement`, `legacy_ai::tests::a_distorted_image_nested_as_deep_as_the_limit_is_written_as_its_nearest_placement`; cad `a_distorted_image_is_written_as_its_nearest_parallelogram_with_a_warning`; metafile `a_distorted_image_is_its_mesh_with_clips_and_its_nearest_parallelogram_without`; tools `xform::eyedropper::tests::clicking_an_image_samples_its_pixels`; plugins `objects::tests::a_distorted_image_comes_with_its_corners`; ui-egui `i18n::tests::distorted_image_messages_are_in_complete_catalogs`).
|
||||
- Perspective Distort and Free Distort (`object.distort`) move an image's four corners exactly onto the handles when the image is distorted alone; with other objects the handles stand for the whole selection, and the image's corners follow the same warp without necessarily landing on them. The image's pixels are drawn in perspective between its corners on the canvas, in print and in every export that holds images, as a mesh of affine image pieces (DXF and WMF write the nearest parallelogram and warn, as the `.ai` writers do for an image nested 8 deep in opacity masks, symbols, live objects and pattern tiles, or in a legacy `.ai` in symbols and live objects, not counting ordinary groups and layers, and leave out an image nested deeper; HP-GL plots leave images out); the native file saves the corners; bounds, clicks, blends, the Eyedropper, Outline view, the Color Theme Picker and Weed Box and Lines follow them; Image info and Link Info measure the image at its middle; and corners that would fold the image over, fall on one line, cross the warp's horizon or lie too close together for a perspective map are refused. Crop Image, Image Trace, Create Object Mosaic, Create Gradient Mesh and Place with Replace refuse a distorted image (Place with Replace refuses only when the object it measures is the distorted image, so it does not refuse when the placed file is text or the replaced object is a DCS file's plates); Update Links and Relink put the file's pixels between its corners, with the file's clipping path drawn through them, and Embed and Unembed keep them; Rasterize makes a plain image of it. All of this is VectorCraft's own rule (doc `image_quad::tests`, `blend::tests::steps_between_distorted_images_have_corners_between_theirs`; engine `xform::distort_puts_an_images_corners_on_the_handles`, `distort_moves_an_image_and_a_path_as_one`, `distort_refuses_a_folded_image_and_crop_and_trace_refuse_a_distorted_one`, `distort_names_the_horizon_and_an_unchanged_distort_of_a_distorted_image_records_nothing`, `distort_of_a_blend_holding_an_image_is_not_refused`, `free_transform_distort_drag_on_an_image_is_one_undo_step`, `mask_on_a_distorted_image_follows_its_corners`, `a_transform_effect_moves_a_distorted_images_corners`, `a_transform_after_a_warp_moves_a_distorted_image_once`, `baked_raster_effect_pixels_replace_a_distortion`, `rasterize_draws_a_distorted_image_between_its_corners`, `image_info_measures_a_distorted_image_at_its_middle`, `a_distorted_image_saves_and_reads_back`, `links::update_links_keeps_a_distorted_images_corners`, `links::relink_embed_and_unembed_keep_a_distorted_images_corners`, `links::unembed_to_a_folder_keeps_a_distorted_images_corners`, `links::embed_reads_a_distorted_images_file_between_its_corners`, `links::relink_of_all_instances_keeps_the_corners_of_distorted_images_in_symbols`, `cmd::fileio::tests_psdread::relink_follows_the_clipping_path_of_a_distorted_psd`, `cmd::fileio::tests_psdread::unembed_keeps_the_clipping_path_of_a_distorted_psd`, `cmd::links::tests::points_past_the_horizon_are_mapped_as_a_distort_maps_them`, `recolor::theme_picker_reads_a_distorted_image_where_it_is_drawn`, `addons::cutting::weed::tests::a_distorted_image_is_measured_by_the_frame_through_its_corners`; render `outline_mode_draws_a_distorted_images_frame_through_its_corners`, `meshwarp::outline_mode_paints_a_distorted_images_pixels_once_where_its_pieces_overlap`, `meshwarp::the_canvas_cuts_a_distorted_images_mesh_for_the_zoom`, `objectfx::a_distorted_image_is_opaque_between_its_corners_and_its_shadow_follows_them`, `objectfx::a_distorted_image_is_opaque_inside_its_corners_at_every_zoom`; svg `warp_pieces::a_distorted_image_is_written_between_its_corners`; pdf `compression::a_distorted_image_is_written_with_its_corners_on_its_quad`; eps `a_distorted_image_is_written_with_its_corners_on_its_quad`, `ai_editing::tests::a_distorted_image_nested_as_deep_as_the_limit_is_written_as_its_nearest_placement`, `legacy_ai::tests::a_distorted_image_nested_as_deep_as_the_limit_is_written_as_its_nearest_placement`; cad `a_distorted_image_is_written_as_its_nearest_parallelogram_with_a_warning`; metafile `a_distorted_image_is_its_mesh_with_clips_and_its_nearest_parallelogram_without`; tools `xform::eyedropper::tests::clicking_an_image_samples_its_pixels`; plugins `objects::tests::a_distorted_image_comes_with_its_corners`; ui-egui `i18n::tests::distorted_image_messages_are_in_complete_catalogs`).
|
||||
- The Free Transform widget's Constrain works in Free Distort as well as in Free Transform ([the help page](https://helpx.adobe.com/illustrator/using/tool-techniques/free-transform-tool.html)). With Constrain on, or Shift held, a corner dragged in Free Distort moves only along the line through the opposite corner, in the box's own proportions, and the other three corners stay in place; on a turned box the line runs through the box's own corners. The line is VectorCraft's own rule. Cmd/Ctrl+Alt+Shift on a corner still drags in Perspective Distort, where Constrain stays unavailable (tools `xform::free::tests::free_distort_corner_keeps_to_its_diagonal_with_shift_or_constrain`, `shift_pressed_during_a_free_distort_drag_constrains_it`, `a_turned_box_is_constrained_along_its_own_diagonal`, `along_diagonal_of_a_degenerate_box`; engine `xform::free_transform_constrained_distort_keeps_the_corner_on_its_diagonal`; ui-egui `free_transform::tests::the_widget_sets_the_mode_and_a_corner_drag_then_distorts`).
|
||||
- With Smart Guides › Transform Tools on, a Free Transform shear (Cmd/Ctrl on a side handle) shows its angle next to the pointer, as the Shear tool does, and a handle drag that turns from a scale into a shear and back shows only the current operation's value ([the help page](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/smart-guides-options.html)). The angle's sign and its one decimal place are VectorCraft's own rule, the same as the Shear tool's label (tools `xform::free::tests::shear_drag_shows_its_angle_with_transform_tools_guides`, `a_handle_drag_that_changes_operation_relabels_it`).
|
||||
- Native macOS menu bar, vector tool cursors, a command palette (Help › Search Commands…), middle-button panning with any tool. Native menus explicitly end tracking on command selection, outside window presses and Escape; menu updates wait until tracking ends, and a dismissing press never starts a canvas gesture (M14.8).
|
||||
@@ -1422,7 +1423,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). In Draw Behind, an Alt-drag copy made with the Selection or Direct Selection tool goes directly below its original and is selected, as [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) lists duplicating by Alt-drag among the actions the mode applies to; with several objects, each copy goes below its own original in that original's group or layer, and in Draw Normal and Draw Inside, and for the transform dialogs' Copy, Duplicate and Transform Again, copies still go above (VectorCraft's own rules).
|
||||
- **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, an Alt-drag copy made with the Selection or Direct Selection tool goes directly below its original and is selected, as [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) lists duplicating by Alt-drag among the actions the mode applies to; with several objects, each copy goes below its own original in that original's group or layer, and in Draw Normal and Draw Inside, and for the transform dialogs' Copy, Duplicate and Transform Again, copies still go above (VectorCraft's own rules). 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`).
|
||||
@@ -1589,7 +1590,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`).
|
||||
@@ -1906,6 +1907,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`.
|
||||
@@ -1947,7 +1949,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.
|
||||
@@ -2052,6 +2054,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.
|
||||
@@ -2125,7 +2128,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
A graphic style dragged onto the Graphic Styles panel's New Graphic Style button is duplicated, as the panel menu's Duplicate Graphic Style does, and both put the copy at the end of the list, as the help page describes ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=391)). VectorCraft's own rules: the button takes the drop with no art selected; a dragged style that is highlighted brings the other highlighted styles, copied in panel order in one undo step, and the copies are highlighted; the copy is named `<name> copy`, with a number when that is taken, and no art is linked to it (`a_style_dropped_on_new_graphic_style_is_duplicated_at_the_end` in `crates/ui-egui/src/panels/graphic_styles.rs`, `tests::styles::duplicate_puts_the_copy_at_the_end_of_the_list_in_one_undo_step`).
|
||||
A graphic style dragged onto the Graphic Styles panel's Delete Graphic Style button is deleted, which the help page gives as another way to delete a style besides the panel menu's Delete Graphic Style; art that used the style keeps its look and is no longer linked to it ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=392)). VectorCraft's own rules: the drop asks first as the button does, and with Alt held it deletes without asking; the button takes the drop with no style highlighted; a dragged style that is highlighted brings the other highlighted styles, deleted in one undo step (`a_style_dropped_on_delete_graphic_style_is_deleted_as_the_button_deletes` in `crates/ui-egui/src/panels/graphic_styles.rs`).
|
||||
The Appearance panel's thumbnail dropped on a graphic style with Alt held replaces that style with the look of the object the panel shows; the style keeps its name and the art that uses it takes the new look, as the help page describes ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=568)). VectorCraft's own rules: art dragged off the canvas does the same with its first object; the style keeps its place in the list, is outlined while one is held over it with Alt, and the replacement is one undo step; an object already linked to the style with its look changes nothing; without Alt the drop makes a new style (`art_or_an_appearance_dropped_on_a_style_with_alt_replaces_that_style` in `crates/ui-egui/src/panels/graphic_styles.rs`).
|
||||
A graphic style dragged onto another style in the Graphic Styles panel with Alt held gives that style the dragged style's look; the replaced style keeps its name and the art that uses it takes the new look, as the help page describes ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=568)). VectorCraft's own rules: the dragged style and the art linked to it stay as they are; the replaced style keeps its place in the list and is outlined while a style is held over it with Alt; the replacement is one undo step; a style dropped on itself, or on a style with the same look, changes nothing and records no undo step; without Alt the style moves (`graphicStyle.redefine {name, from}`, `a_style_dropped_on_another_with_alt_replaces_that_style` in `crates/ui-egui/src/panels/graphic_styles.rs`, `tests::styles::redefine_from_a_style_gives_the_style_that_look`).
|
||||
A graphic style dragged onto another style in the Graphic Styles panel with Alt held gives that style the dragged style's look; the replaced style keeps its name and the art that uses it takes the new look, as the help page describes ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=568)). VectorCraft's own rules: the dragged style and the art linked to it stay as they are, including a path linked to the dragged style inside a graph series group that uses the replaced style; the replaced style keeps its place in the list and is outlined while a style is held over it with Alt; the replacement is one undo step; a style dropped on itself, or on a style with the same look, changes nothing and records no undo step; without Alt the style moves (`graphicStyle.redefine {name, from}`, `a_style_dropped_on_another_with_alt_replaces_that_style` in `crates/ui-egui/src/panels/graphic_styles.rs`, `tests::styles::redefine_from_a_style_gives_the_style_that_look`, `cmd::graph::tests::redefining_a_graphic_style_from_another_style_keeps_a_mark_linked_to_it`). As VectorCraft's own rule, Redefine Graphic Style from an object also leaves a path inside such a series group, or a line or label inside a graph's Axes or Legend group that uses the style, with its look and its link when it is linked to another style (`redefining_a_graphic_style_from_an_object_keeps_a_mark_linked_to_another_style`, `redefining_a_graphic_style_keeps_a_legend_label_linked_to_another_style`).
|
||||
In the Graphic Styles panel's thumbnail and list views, a style with no fill and no stroke, one with only effects or transparency included, shows its preview shape with a black outline, a white fill and a red slash, as the help page describes for the panel's thumbnails ([Graphic styles](https://helpx.adobe.com/illustrator/using/graphic-styles.html)); its effects still draw on that shape. The Control bar's Style picker and chip, graphic style library panels and the large preview on the selected object show the same marker. A fill or stroke row that paints None does not count as a fill or stroke, and a hidden row or one with zero opacity does; these rules, the marker outside the panel's thumbnails and the slash's direction and size are VectorCraft's own (`a_style_with_no_fill_and_no_stroke_shows_an_outlined_shape_and_a_red_slash` in `crates/ui-egui/src/panels/graphic_styles.rs`).
|
||||
In the Graphic Styles panel's thumbnail and list views, right-clicking a style item opens its context menu offering Graphic Style Options…, Duplicate Graphic Style (or Duplicate Graphic Styles when multiple styles are selected), Delete Graphic Style (or Delete Graphic Styles), Redefine Graphic Style (enabled when canvas art is selected), and Break Link to Graphic Style (enabled when the selection is linked to this style). Right-clicking an unselected style selects it first, while right-clicking an item in an existing multi-selection preserves the multi-selection. Default Graphic Style disables Options and Delete. Secondary button hold still triggers large preview on tiles/rows. Tests: `right_click_context_menu_in_graphic_styles_panel`, `right_click_context_menu_default_style_disables_options_and_delete`, and `right_click_context_menu_preserves_multiselection_and_works_in_list_view` in `crates/ui-egui/src/panels/graphic_styles.rs`.
|
||||
Applying a style to several objects, and Redefine Graphic Style, give the objects one shared copy of the style's appearance instead of a copy each; an object that is edited later gets its own copy, and an object whose placed gradients are fitted to its own bounds gets its own. The undo history's memory estimate counts a shared appearance once. Saved files are unchanged (`crates/engine/src/tests/styles.rs`).
|
||||
@@ -2322,7 +2325,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`).
|
||||
@@ -2496,6 +2499,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
The contour passes of the two-path boolean operations, Offset Path, compound shapes and Intertwine test the list of shapes that cover each face instead of a flag for every shape, so each test's time follows how many shapes cover the face rather than how many shapes there are. The contours, their order and the output are the same. The many-shape boolean that compound shapes use takes 0.75 to 0.83 billion CPU cycles on its thread instead of 1.28 to 1.33 billion to unite 10,000 squares that do not touch, and 2.27 to 2.30 billion instead of 2.43 to 2.47 billion for 1,500 members of two squares each over 3,000 overlapping squares (dev build, six runs of each, alternating, while other builds were running).
|
||||
Pathfinder › Unite and the other commands that unite filled paths sweep a single input once instead of twice when its own sweep neither splits nor drops any of its segments and no two of its segments lie within twice the sweep tolerance. The output is the same. Unite on one compound path of 4,000 rings takes 485 to 542 ms instead of 872 to 1,008 ms, and on one zigzag polygon of 20,000 teeth 70 to 76 ms instead of 118 to 130 ms (release build, medians of three alternating rounds of five runs, while other builds were running).
|
||||
With more than 10,000 type on a path objects selected, the Selection and Direct Selection tools neither draw nor hit-test the objects' brackets.
|
||||
The on-canvas widgets of the selection (the type, pie, side count and corner widgets, the Objects on Path, Mirror, Grid and Radial Repeat controls, the Image Trace Split divider and the center point) first check that an object is of a kind that has the widget, and only then whether it is editable, which on a locked artboard measures the art of the layer object holding it. The widgets shown are the same. With a group of 5,000 rectangles selected on a locked artboard, each widget took 2.1 to 2.3 ms of thread CPU time a call with the editability check first and under 0.01 ms without it (Linux x86_64, optimized test build, median of 7 runs of 100 calls; `widget_order_perf` in `crates/tools`). With no artboard locked, both orders take under 0.01 ms a call for that group.
|
||||
The renderer outlines the stroke of a path object with more than 1,024 path elements, without dashes or a width profile, only in and around the view, with a margin of the view's size on each side, and outlines it again when the view moves past that margin. The pixels are the same. At 1600 × 1200, the frame after one anchor of an open path of 200,000 anchors moves takes 28 to 30 ms instead of 103 ms, and with a closed path of 50,000 anchors 10 ms instead of 30 ms (`cargo run --release -p vectorcraft-engine --example anchor_bench`).
|
||||
The renderer outlines a dashed stroke of such a path the same way, without a width profile, and draws its dashes and dots in the same places as when the whole path is dashed, so the pixels are the same. A pattern too fine to draw is drawn solid, as before, and its stroke is outlined near the view too. At 1600 × 1200, the frame after one anchor moves takes 14 ms instead of 102 ms with a filled closed path of 50,000 anchors and a stroke of 6 pt dashes and 4 pt gaps (`cargo run --release -p vectorcraft-engine --example anchor_bench`, which now includes that document).
|
||||
When anchors of a path or compound path of 1,024 anchors or more are added or deleted, or a subpath is closed or opened, the next frame writes again only the path elements from the first anchor that changed to the last, and the closing segment when an end anchor changed or the subpath was closed or opened. It measures again only the runs of segments that held them; a run grows or shrinks with the segments added or deleted, and one that grows past 256 segments is split. When a member gains or loses subpaths, the renderer makes the path of that member again. When a compound path gains or loses members, it makes the path of those members and of every member between the first and the last of them again. An edit that adds or deletes anchors in, closes or opens more than 16 subpaths makes the whole path again. The pixels and the cull bounds are the same.
|
||||
@@ -2991,7 +2995,7 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov
|
||||
|
||||
## Path Precision Tools add-on: Tangent Circle Tool (2026-11-17)
|
||||
|
||||
A VectorCraft addition, so no area score moves. The Tangent Circle Tool (`tangentCircle`; Object › Plug-ins › Path Precision Tools and the All Tools drawer) draws a circle on two clicked path segments: tangent to the first at the point clicked (its center on the normal there) and touching the second segment or one beside it on its subpath, the touch nearest the pointer winning. Shift gives the circle the tool's radius, and a drag from the second segment sets the radius to the drag's length (Shift: steps of 1, 2 or 5 times a power of 10 pt, at least 4 screen pixels; Cmd/Ctrl: a tenth of the movement); with a radius the circle may touch the first segment anywhere along it. Before the click the circle shows with its center, radii and radius, or a note says there is none. The circles are found by sampling the distance to the second segments along the first segment's normal (or along the first segment, for a radius) and taking the places where it equals the radius (samples, bisection where it crosses, and a search where it only touches). Left out are circles whose nearest point of the second segments is not on the circle (within a millionth of the radius: where the first segment turns back on itself the distance jumps past the radius without a touch), circles that cross the first segment, circles that touch both segments at one point, circles without a finite radius above 0, and circles too small or too large for three of their points to give them back in floating point; a circle found twice (the same center, touching the first segment at the same point) is kept once. The circle is a new ellipse with the current paint, one undo step; the first segment stays picked until it is drawn, also when drawing fails or the press is canceled, and the circles are looked for again when a live preview, or one that was canceled, changes either segment without an undo step (a changed first segment is forgotten). Tests: `tangent_circle::tests` in `vectorcraft-pathops` (parallel and crossing lines, a curved second segment, a corner's fillet, lines twice the radius apart, a touch between the places tried, the ends of a line with its handles on its anchors, a circle that crosses the first segment, a first segment that turns back, no circle), `addons::tangent_circle::tests` in `vectorcraft-tools` (two clicks, Shift and the radius option, a drag with Shift and Cmd/Ctrl, no circle and Escape, a canceled press, a canceled preview, a circle its three points cannot draw), the session test for a failed draw in `vectorcraft-engine` and the Path Precision Tools menu, options, drawer and catalog tests in `vectorcraft-ui-egui`. Commands: `docs/mcp.md` › Path Precision Tools add-on.
|
||||
A VectorCraft addition, so no area score moves. The Tangent Circle Tool (`tangentCircle`; Object › Plug-ins › Path Precision Tools and the All Tools drawer) draws a circle on two clicked path segments: tangent to the first at the point clicked (its center on the normal there) and touching the second segment or one beside it on its subpath, the touch nearest the pointer winning. Shift gives the circle the tool's radius, and a drag from the second segment sets the radius to the drag's length (Shift: steps of 1, 2 or 5 times a power of 10 pt, at least 4 screen pixels; Cmd/Ctrl: a tenth of the movement); with a radius the circle may touch the first segment anywhere along it. Before the click the circle shows with its center, radii and radius, or a note says there is none. The circles are found by sampling the distance to the second segments along the first segment's normal (or along the first segment, for a radius) and taking the places where it equals the radius (samples, bisection where it crosses, and a search where it only touches). Left out are circles whose nearest point of the second segments is not on the circle (within a millionth of the radius: where the first segment turns back on itself the distance jumps past the radius without a touch), circles that cross the first segment, circles that touch both segments at one point, circles without a finite radius above 0, circles too small or too large for three of their points to give them back in floating point, and circles that would reach past the canvas; a circle found twice (the same center, touching the first segment at the same point) is kept once. The circle is a new ellipse with the current paint, one undo step; the first segment stays picked until it is drawn, also when drawing fails or the press is canceled, and the circles are looked for again when a live preview, or one that was canceled, changes either segment without an undo step (a changed first segment is forgotten). Tests: `tangent_circle::tests` in `vectorcraft-pathops` (parallel and crossing lines, a curved second segment, a corner's fillet, lines twice the radius apart, a touch between the places tried, the ends of a line with its handles on its anchors, a circle that crosses the first segment, a first segment that turns back, no circle), `addons::tangent_circle::tests` in `vectorcraft-tools` (two clicks, Shift and the radius option, a drag with Shift and Cmd/Ctrl, no circle and Escape, a canceled press, a canceled preview, a circle its three points cannot draw, a circle past the canvas), the session test for a failed draw in `vectorcraft-engine` and the Path Precision Tools menu, options, drawer and catalog tests in `vectorcraft-ui-egui`. Commands: `docs/mcp.md` › Path Precision Tools add-on.
|
||||
|
||||
## Path Precision Tools add-on: Trim at Crossings (2026-11-13)
|
||||
|
||||
@@ -3078,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
@@ -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. |
|
||||
|
||||
Reference in new issue
Block a user