Merge remote-tracking branch 'upstream/main' into pencil-redraw-extend

# Conflicts:
#	docs/target-app-parity.md
#	docs/ui-parity.md
This commit is contained in:
ncic committed 2026-11-21 18:13:24 +01:00
commit 6cd0de02b1
183 files changed
+12737 -11709

No files matched your search

+30 -2
View File
@@ -67,7 +67,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Clear Appearance",
["Window", "Appearance"],
None,
"{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own) and reset its opacity and blend mode. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind",
"{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own; in the contents of a Live Paint group, a face one empty fill and an edge one empty stroke) and reset its opacity and blend mode. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind",
has_doc,
clear_appearance
),
@@ -76,7 +76,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Reduce to Basic Appearance",
["Window", "Appearance"],
None,
"{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes)",
"{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked; in the contents of a Live Paint group, a face keeps only the fill and an edge only the stroke), and drop the object's effects. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes)",
has_doc,
reduce_basic
),
@@ -529,6 +529,24 @@ pub(crate) fn contents_skipped(s: &Session, p: &Value, fill: bool) -> Result<Has
Ok(super::paint::live_paint_parts_skipped(&s.doc()?.doc, &appearance_roots(s, p)?, fill))
}
/// The faces and the edges of the Live Paint groups whose contents `p` targets (`target: "contents"`). A command that
/// gives them a whole appearance gives a face only its fill rows and an edge only its stroke rows
/// ([`keep_rows_of_kind`]). Both are empty without `target: "contents"`.
pub(crate) fn contents_parts(s: &Session, p: &Value) -> Result<(HashSet<NodeId>, HashSet<NodeId>)> {
if !targets_contents(p)? {
return Ok((HashSet::new(), HashSet::new()));
}
let (faces, edges, _) = super::paint::live_paint_split(&s.doc()?.doc, &appearance_roots(s, p)?);
Ok((faces, edges))
}
/// Remove from `n` its stroke rows (`fill`) or its fill rows: a Live Paint face draws fills and an edge strokes.
pub(crate) fn keep_rows_of_kind(n: &mut Node, fill: bool) {
if n.appearance.items.iter().any(|it| it.is_fill() != fill) {
n.appearance.items.retain(|it| it.is_fill() == fill);
}
}
/// The refusal of an appearance edit whose targets are all the art of graph designs drawn in graph series.
const DESIGN_ART: &str = "the art of a graph design in a graph series is drawn again from the design: edit the design to change it";
@@ -1044,12 +1062,17 @@ fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
fn clear_appearance(s: &mut Session, p: &Value) -> Result<Value> {
let ids = require_whole_targets(s, p, "appearance.clear")?;
let (faces, edges) = contents_parts(s, p)?;
// When every object is cleared already, the document and its undo history stay as they are.
let before = s.doc()?.doc.clone();
super::overprint::edit_counted(s, "Clear Appearance", |d| {
for id in &ids {
if let Some(n) = d.node_mut(*id) {
clear(n);
// A Live Paint group's face keeps an empty fill and its edge an empty stroke.
if faces.contains(id) || edges.contains(id) {
keep_rows_of_kind(n, faces.contains(id));
}
super::object::snap_if_aligned(n);
}
}
@@ -1284,6 +1307,7 @@ fn is_group(n: &Node) -> bool {
fn reduce_basic(s: &mut Session, p: &Value) -> Result<Value> {
let ids = require_whole_targets(s, p, "appearance.reduceToBasic")?;
let (faces, edges) = contents_parts(s, p)?;
// When every object comes out as it was, the document and its undo history stay as they are.
let before = s.doc()?.doc.clone();
// The Appearance panel's active row (a row of the first selected object's stack, and in each
@@ -1322,6 +1346,10 @@ fn reduce_basic(s: &mut Session, p: &Value) -> Result<Value> {
st.blend = BlendMode::Normal;
n.appearance.items.push(AppearanceItem::Stroke(st));
}
// A Live Paint group's face keeps only its fill and its edge only its stroke.
if faces.contains(id) || edges.contains(id) {
keep_rows_of_kind(n, faces.contains(id));
}
super::object::snap_if_aligned(n);
}
}
+2 -2
View File
@@ -48,7 +48,7 @@ use dynamic::{symbol_instance_reset, symbol_instance_select_part, symbol_instanc
use symbolism::symbol_set_density;
use symbols::selected_instances;
pub(crate) use symbols::{
expand_instances_under, expandable_instances, instance_in_place, natural_size, normalize, place_xf, set_natural_size, store_symbol,
Placement, expand_instances_under, expandable_instances, instance_in_place, natural_size, normalize, place_xf, set_natural_size, store_symbol,
stored_natural_size,
};
use symbols::{
@@ -234,7 +234,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Place Symbol Instance",
[],
None,
"{name?, x?, y?} place an instance so its registration point is at (x, y) (default: artboard centre; name default: current) → {id}",
"{name?, x?, y?} place an instance so its registration point is at (x, y) (default: artboard centre; name default: current), on top of the current layer, or in Draw Behind directly below the bottommost selected object (at the bottom of the current layer with nothing selected) → {id}",
has_doc,
symbol_place
),
+36 -2
View File
@@ -33,6 +33,40 @@ pub(crate) fn place_xf(at: Point, (w, h): (f64, f64), reg: SymbolRegistration) -
Affine::translate(c.to_vec2()) * Affine::scale_non_uniform(w / (2.0 * HALF), h / (2.0 * HALF))
}
/// Where a placed symbol instance goes in the active document, worked out before the edit from
/// the drawing mode, the selection and the layer new art goes into.
pub(crate) struct Placement {
parent: Option<NodeId>,
behind: bool,
anchor: Option<NodeId>,
}
impl Placement {
/// On top of the layer new art goes into; in Draw Behind, directly below the bottommost
/// selected object (beside the compound path that holds it), or at the bottom of that layer
/// when nothing is selected. An error when that layer is locked or hidden.
pub(crate) fn of(s: &Session) -> Result<Self> {
let st = s.doc()?;
let parent = st.target_parent()?;
let behind = s.draw_mode == crate::DrawMode::Behind;
let compound_of = |id: NodeId| st.doc.parent_of(id).filter(|p| st.doc.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })));
let anchor = behind.then(|| st.selection.in_paint_order(&st.doc).first().copied()).flatten().map(|id| compound_of(id).unwrap_or(id));
Ok(Self { parent, behind, anchor })
}
/// Inserts instance `n` where this placement puts it. In a clip group or a clipping layer the
/// clipping path stays at the bottom.
pub(crate) fn insert(&self, d: &mut Document, n: Node) -> Result<NodeId> {
let (parent, index) = match (self.behind, self.anchor.and_then(|a| d.position(a))) {
(false, _) => return Ok(d.insert(self.parent, usize::MAX, n)?),
(true, Some((par, i, _))) => (par, i),
(true, None) => (self.parent, 0),
};
let floor = usize::from(parent.and_then(|p| d.node(p)).is_some_and(Node::clips));
Ok(d.insert(parent, index.max(floor), n)?)
}
}
fn registration_param(p: &Value, cmd: &str) -> Result<Option<SymbolRegistration>> {
match p.get("registration") {
None => Ok(None),
@@ -437,10 +471,10 @@ pub(super) fn symbol_place(s: &mut Session, p: &Value) -> Result<Value> {
let at = Point::new(number_or(p, "x", centre.x, "symbol.place")?, number_or(p, "y", centre.y, "symbol.place")?);
let size = natural_size(d, &name);
let reg = d.symbol_registration(&name);
let parent = s.doc()?.target_parent()?;
let spot = Placement::of(s)?;
let id = s.edit("Place Symbol Instance", |d, sel| {
let id = d.alloc_id();
d.insert(parent, usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: name.clone(), xf: place_xf(at, size, reg) }))?;
spot.insert(d, Node::new(id, NodeKind::SymbolInstance { symbol: name.clone(), xf: place_xf(at, size, reg) }))?;
sel.set([id]);
Ok(id)
})?;
+7 -1
View File
@@ -114,7 +114,13 @@ fn tree(d: &Document) -> Vec<(usize, NodeId)> {
fn assert_same(a: &Session, b: &Session, when: &str) {
let (x, y) = (a.doc().unwrap(), b.doc().unwrap());
assert_eq!(tree(&x.doc), tree(&y.doc), "{when}: the tree");
assert!(*x.doc == *y.doc, "{when}: the document");
// `file.new` stamps each document with the second it was made, and the two can be a second apart.
let unstamped = |d: &Document| {
let mut d = d.clone();
d.metadata.created = None;
d
};
assert!(unstamped(&x.doc) == unstamped(&y.doc), "{when}: the document");
assert_eq!(x.selection, y.selection, "{when}: the selection");
// Each session's document has its own uid; the clipboard names the one it came from.
assert_eq!(a.clipboard.source_doc.is_some(), b.clipboard.source_doc.is_some(), "{when}: the clipboard's source");
+8 -2
View File
@@ -97,7 +97,7 @@ fn effect_specs() -> Vec<CommandSpec> {
"Expand Appearance",
["Object"],
None,
"{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry or raster effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them, its raster effects an image as for other objects; a symbol instance in that art whose topmost fill or stroke has such an effect (its own or one the outer instance passes on) becomes its art and image in turn. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. One expansion makes at most 1,024 images of raster effects, 256 megapixels in all (VectorCraft's own limits): an object or symbol instance whose image would go past them stays as it is, with its effects, and when nothing else expands that is an error. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says; or raster effects were left past the limits), rasterLeft? (how many objects were left so)}",
"{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry or raster effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them, its raster effects an image as for other objects; a symbol instance in that art whose topmost fill or stroke has such an effect (its own or one the outer instance passes on) becomes its art and image in turn. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. One expansion makes at most 1,024 images of raster effects, 256 megapixels in all (VectorCraft's own limits): an object or symbol instance whose image would go past them stays as it is, with its effects, and when nothing else expands that is an error. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places, a plain instance in a group or layer whose raster effect makes an image of it included) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says; or raster effects were left past the limits), rasterLeft? (how many objects were left so)}",
can_expand,
expand_appearance
),
@@ -1611,13 +1611,18 @@ fn expanded_node(
/// Does `n`, an object in it, or the art of a symbol placed in it hold a plug-in effect that
/// expanding it draws: a visible one, the object's own or a visible fill's or stroke's, on an
/// object that expands ([`expandable`]; in a symbol's art, `in_art`, every object does). A symbol's
/// object that expands ([`expandable`]; in a symbol's art, `in_art`, every object does, and so does
/// every object in a group or layer with a raster effect, whose image draws all of it). A symbol's
/// art counts where an instance of it expands. `seen` holds the symbols already looked into.
fn holds_plugin_effect(d: &Document, n: &Node, in_art: bool, seen: &mut std::collections::HashSet<String>) -> bool {
let plugin = |e: &Effect| e.visible && vectorcraft_plugins::effect::plugin_id(&e.id).is_some();
let mut symbols = vec![];
let mut drawn = vec![];
let mut holds = false;
n.walk(&mut |c| {
if !in_art && is_container(c) && !rasterfx::raster_fx(c).is_empty() {
drawn.push(c);
}
if !in_art && !expandable(c) {
return;
}
@@ -1627,6 +1632,7 @@ fn holds_plugin_effect(d: &Document, n: &Node, in_art: bool, seen: &mut std::col
}
});
holds
|| drawn.into_iter().any(|g| holds_plugin_effect(d, g, true, seen))
|| symbols.into_iter().any(|name| {
seen.insert(name.clone()) && d.symbols.iter().find(|s| s.name == name).is_some_and(|s| holds_plugin_effect(d, &s.art, true, seen))
})
+1 -1
View File
@@ -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;
+8 -8
View File
@@ -1,7 +1,7 @@
//! `.cdr` drawings of versions 1 to 27 (`.cdr`, and `.cdt` templates): the pages, layers,
//! guidelines, groups, curves, rectangles, ellipses, arcs and polygons with uniform fills and
//! outlines, their hidden and locked states, fill rules and uniform transparency that
//! `vectorcraft-cdr` reads, mapped to editable VectorCraft art. Pages become
//! `craft-cdr` reads, mapped to editable VectorCraft art. Pages become
//! artboards side by side; layers of the same name on different pages become one layer where the
//! pages stack them in the same order. What the
//! reader leaves out is listed in the warnings, one line for each kind ([`note`]). `.cmx` exchange
@@ -10,9 +10,9 @@
use std::collections::HashMap;
use std::sync::Arc;
use craft_cdr::model::{self as cd, LayerKind};
use craft_cdr::{Limits, Warning};
use kurbo::{Affine, Rect};
use vectorcraft_cdr::model::{self as cd, LayerKind};
use vectorcraft_cdr::{Limits, Warning};
use vectorcraft_doc::{Artboard, ColorMode, Document, Guide, LayerColor, Node, NodeKind};
use super::load::err;
@@ -92,12 +92,12 @@ const MAX_LAYERS: usize = 10_000;
/// Is `bytes` a `.cdr` drawing this importer reads?
pub(super) fn is_cdr(bytes: &[u8]) -> bool {
vectorcraft_cdr::is_cdr(bytes)
craft_cdr::is_cdr(bytes)
}
pub(super) fn import(bytes: &[u8]) -> Result<(Document, Vec<String>)> {
let d = vectorcraft_cdr::read(bytes, Limits::default()).map_err(|e| match e {
vectorcraft_cdr::Error::Version(v) => {
let d = craft_cdr::read(bytes, Limits::default()).map_err(|e| match e {
craft_cdr::Error::Version(v) => {
let version = v / 100;
err(format!("CDR {version} drawings can't be opened: VectorCraft reads versions 1 to 27"))
}
@@ -108,13 +108,13 @@ pub(super) fn import(bytes: &[u8]) -> Result<(Document, Vec<String>)> {
/// Is `bytes` a `.cmx` file, of any byte order or coordinate size?
pub(super) fn is_cmx(bytes: &[u8]) -> bool {
vectorcraft_cdr::is_cmx(bytes)
craft_cdr::is_cmx(bytes)
}
/// A `.cmx` file with 32-bit coordinates: its pages, layers, groups and curves with uniform fills
/// and outlines, mapped as a `.cdr` drawing's are.
pub(super) fn import_cmx(bytes: &[u8]) -> Result<(Document, Vec<String>)> {
let d = vectorcraft_cdr::read_cmx(bytes, Limits::default()).map_err(|why| err(format!("this CMX file can't be read ({why})")))?;
let d = craft_cdr::read_cmx(bytes, Limits::default()).map_err(|why| err(format!("this CMX file can't be read ({why})")))?;
Ok(build(&d, cmx_note, CMX_PAGES_CUT))
}
+2 -2
View File
@@ -4,9 +4,9 @@
use std::collections::HashMap;
use std::sync::Arc;
use craft_cdr::Warning;
use craft_cdr::model::{self as cd, Geometry};
use kurbo::{Affine, BezPath, Point, Rect};
use vectorcraft_cdr::Warning;
use vectorcraft_cdr::model::{self as cd, Geometry};
use vectorcraft_color::swatch::REGISTRATION;
use vectorcraft_color::{BlendMode, Color, Paint, Swatch};
use vectorcraft_doc::appearance::{Appearance, AppearanceItem, Dash, FillLayer, LineCap, LineJoin, StrokeLayer};
+2 -2
View File
@@ -533,11 +533,11 @@ pub const FORMATS: &[Format] = &[
// jxl-oxide reads a JPEG XL file's first frame, which is stored as PNG. Exports don't write it.
reader("jxl", "JPEG XL", &["jxl"], "image/jxl", true),
// `.cdr` drawings of versions 1 to 27 (`WL` files, RIFF files from version 3, and the ZIP packages of 14 on), read by
// `vectorcraft-cdr`; a `.cdt` template opens as a new untitled document. Exports don't write
// `craft-cdr`; a `.cdt` template opens as a new untitled document. Exports don't write
// them.
reader("cdr", "CDR Drawing", &["cdr"], "application/vnd.corel-draw", false), // brand-ok: shared MIME type
reader("cdt", "CDR Template", &["cdt"], "application/vnd.corel-draw", false), // brand-ok: shared MIME type
// `.cmx` exchange files with 32-bit coordinates, read by `vectorcraft-cdr`; exports don't write
// `.cmx` exchange files with 32-bit coordinates, read by `craft-cdr`; exports don't write
// them.
reader("cmx", "CMX", &["cmx"], "image/x-cmx", false),
// QuickDraw pictures, read by `vectorcraft_metafile::import_pict` into paths, type and images.
+14
View File
@@ -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> {
+1 -1
View File
@@ -2,8 +2,8 @@
//! artboards, layers, guides, live shapes, solid paint and strokes.
use super::*;
use craft_cdr::synth::{self, V, chunk, list};
use serde_json::json;
use vectorcraft_cdr::synth::{self, V, chunk, list};
use vectorcraft_doc::{LiveShape, Node, NodeKind};
fn walk(nodes: &[std::sync::Arc<Node>], out: &mut Vec<Node>) {
+1 -1
View File
@@ -2,8 +2,8 @@
//! paths, solid paint and strokes, with their warnings and refusals.
use super::*;
use craft_cdr::synth_cmx::*;
use serde_json::json;
use vectorcraft_cdr::synth_cmx::*;
use vectorcraft_doc::{Node, NodeKind};
fn paths(nodes: &[std::sync::Arc<Node>], out: &mut Vec<Node>) {
@@ -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]
+139
View File
@@ -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
+29 -1
View File
@@ -192,7 +192,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Target",
[],
None,
"{id, add?: bool (Shift-click: the item joins the selection, or leaves it when all selected; nothing is targeted)} target a layer, group or object as clicking its target circle in the Layers panel does: a layer gets its visible, unlocked art (its sublayers' too) selected and becomes the current layer, and appearance.*, effect.*, transparency.* and the opacity-mask commands without `ids` then act on the layer itself; anything else is selected. Any other selection change ends the targeting (`document.inspect` → target) → {id, selected: [..]}",
"{id, add?: bool} or {range: [id…], add?: bool} target a layer, group or object as clicking its target circle in the Layers panel does: a layer gets its visible, unlocked art (its sublayers' too) selected and becomes the current layer, and appearance.*, effect.*, transparency.* and the opacity-mask commands without `ids` then act on the layer itself; anything else is selected. `add` (Ctrl/Cmd-click): the item joins the selection, or leaves it when all selected; nothing is targeted. `range` (Shift-click, the rows from the last circle clicked to this one): the art of every listed row that is visible, unlocked and inside the isolated group is selected, or added to the selection with `add` (Shift+Ctrl/Cmd-click); nothing is targeted. Any other selection change ends the targeting (`document.inspect` → target) → {id, selected: [..]} (with `range`: {range, selected})",
has_doc,
target
),
@@ -433,6 +433,9 @@ fn paste_remembers_layers(s: &mut Session, p: &Value) -> Result<Value> {
/// The Layers panel's target circle.
fn target(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "layer.target";
if let Some(ids) = ids_param(p, "range", C)? {
return target_range(s, p, ids);
}
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?;
let st = s.doc()?;
let n = st.doc.node(id).ok_or(EngineError::NoNode(id))?;
@@ -458,6 +461,31 @@ fn target(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "id": id.0, "selected": st.selection.objects.iter().map(|i| i.0).collect::<Vec<_>>() }))
}
/// `layer.target` with `range`, a Shift-click range of target circles: the art of every listed row
/// that is visible, unlocked and inside the isolated group is selected, or added to the selection
/// with `add`. Nothing is targeted, and the highlighted rows stay. The current layer follows the
/// selection, as with any selection change ([`Session::select`]).
fn target_range(s: &mut Session, p: &Value, mut ids: Vec<NodeId>) -> Result<Value> {
const C: &str = "layer.target";
ids.truncate(MAX_ROWS);
let add = switch_or(p, "add", false, C)?;
let rows = {
let st = s.doc()?;
// Measures the locked artboards once for every row, not once per row.
let editable = st.doc.editable();
ids.retain(|id| st.doc.node(*id).is_some() && editable(*id) && in_isolation(&st.doc, st.isolation, *id));
st.layer_rows.clone()
};
if ids.is_empty() {
return Err(bad(C, "no row in the range is visible, unlocked and inside the isolated group"));
}
s.select(|d, sel| sel.target_range(d, &ids, add))?;
let st = s.doc_mut()?;
// Targeting doesn't change which rows are highlighted.
st.layer_rows = rows;
Ok(json!({ "range": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "selected": st.selection.objects.iter().map(|i| i.0).collect::<Vec<_>>() }))
}
/// The Layers panel's clipping mask button: the top object of a layer (or group) clips the rest,
/// or the clipping mask is released.
fn clip_toggle(s: &mut Session, p: &Value) -> Result<Value> {
+114 -54
View File
@@ -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);
}
}
+3 -3
View File
@@ -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(),
}))
+3 -3
View File
@@ -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
),
+3 -1
View File
@@ -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
View File
@@ -13,8 +13,14 @@
//! per line of glyphs, with the first glyph's fill and stroke. A line whose glyphs are evenly spaced
//! apart takes that spacing as its tracking ([`Line::tracked`]), and lines stacked at one leading
//! and lined up at their starts, ends or centers become one area type object ([`blocks`]). Shapes
//! that match no font stay as they are and are reported. Near matches (another version of the
//! font, simplified outlines, merged glyphs) and images are phase 2.
//! that match no font stay as they are and are reported.
//!
//! With a `tolerance`, a shape that matches no glyph exactly may still nearly match one: another
//! version of the font, or the outline simplified or built another way
//! ([`RetypeIndex::near_matches`]); each line reports how closely its glyphs fit. A compound path
//! holding several glyphs (a word outlined as one path) is split into its glyphs
//! ([`vectorcraft_text::retype::clusters`]), and becomes type only when every one of them does.
//! The tolerance, the score and the splitting rules are VectorCraft's own. Images are phase 2.
use std::f64::consts::{PI, TAU};
use std::sync::Arc;
@@ -22,6 +28,7 @@ use std::sync::Arc;
use kurbo::{BezPath, Point, Vec2};
use serde_json::{Value, json};
use vectorcraft_doc::{Appearance, CharStyle, Document, Node, NodeId, NodeKind, TextObject};
use vectorcraft_geom::FillRule;
use vectorcraft_text::FontDb;
use vectorcraft_text::retype::{GlyphMatch, RetypeIndex};
@@ -41,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Retype",
["Type"],
None,
"{fonts?: [family…]} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation (exact matches only); matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool)}], unmatched: [id…], truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error when no shape matches",
"{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only)} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups, 512 contours and 65,536 path elements, and 16,384 contours per command) is split into them, and becomes type only when every one of them matches; matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it), and before a near-matched glyph the line's size and turn would draw further from its shape than the tolerance; a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a counter narrower than three times the outline tolerance across in some direction, an outline too large to check, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, or that overlap at all when the compound has an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke, also keep the shape an outline); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are when another shape became type), truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error, with no unmatched list, when no shape becomes type, or when tolerance is not a number from 0 to 0.05",
has_selected_path,
retype
)]
@@ -60,6 +67,10 @@ struct Piece {
/// art must stay painted after it: the line ends here.
after_barrier: bool,
path: BezPath,
/// The shape is filled by the nonzero rule, not the even-odd rule.
nonzero: bool,
/// The shape has a visible fill: a shape that only has a stroke paints no area to compare.
filled: bool,
appearance: Appearance,
/// The shape's own transparency, which the new type takes.
opacity: f32,
@@ -83,11 +94,13 @@ fn collect(n: &Node, parent: Option<NodeId>, depth: usize, barrier: &mut bool, t
*barrier = true;
return;
}
let piece = |path: BezPath, after_barrier: bool| Piece {
let piece = |path: BezPath, after_barrier: bool, rule: FillRule| Piece {
id: n.id,
parent,
after_barrier,
path,
nonzero: rule == FillRule::NonZero,
filled: n.appearance.fill().is_some_and(|f| f.visible && !f.paint.is_none()),
appearance: (*n.appearance).clone(),
opacity: n.opacity,
blend: n.blend,
@@ -100,8 +113,10 @@ fn collect(n: &Node, parent: Option<NodeId>, depth: usize, barrier: &mut bool, t
}
}
// Only closed shapes can be glyphs: an open path stroked along a glyph's outline is not one.
NodeKind::Path { path, clipping: false, guide: false, .. } if path.is_closed() => out.push(piece(path.to_bezpath(), std::mem::take(barrier))),
NodeKind::Compound { children, .. } => {
NodeKind::Path { path, rule, clipping: false, guide: false, .. } if path.is_closed() => {
out.push(piece(path.to_bezpath(), std::mem::take(barrier), *rule))
}
NodeKind::Compound { children, rule } => {
let mut path = BezPath::new();
for c in children {
match &c.kind {
@@ -113,7 +128,7 @@ fn collect(n: &Node, parent: Option<NodeId>, depth: usize, barrier: &mut bool, t
}
}
}
out.push(piece(path, std::mem::take(barrier)));
out.push(piece(path, std::mem::take(barrier), *rule));
}
// Live type, images, clip groups and the rest stay, and the type after them stays after them.
_ => *barrier = true,
@@ -185,6 +200,9 @@ struct Line {
parent: Option<NodeId>,
opacity: f32,
blend: vectorcraft_color::BlendMode,
/// The tolerance near matches were taken with (0: exact only): a near-matched glyph may differ
/// that much in size, turn and place from the rest of its line ([`Self::slack_for`]).
slack: f64,
}
impl Line {
@@ -192,6 +210,12 @@ impl Line {
Vec2::new(self.angle.cos(), self.angle.sin())
}
/// The slack glyph `m` of this line is allowed: [`Self::slack`] when `m` or the line's first
/// glyph, whose size and turn the line takes, is a near match, else 0.
fn slack_for(&self, m: &GlyphMatch) -> f64 {
if m.exact && self.matches.first().is_none_or(|f| f.exact) { 0.0 } else { self.slack }
}
/// Does glyph `m` of shape `pc` continue this line (same group, paint and transparency, same
/// font, size and turn, on its baseline, after its end)?
fn continues(&self, pc: &Piece, m: &GlyphMatch) -> bool {
@@ -199,15 +223,16 @@ impl Line {
let d = m.origin - self.origin;
let dir = self.dir();
let across = d.cross(dir).abs();
let slack = self.slack_for(m);
pc.parent == self.parent
&& pc.appearance == self.appearance
&& pc.opacity == self.opacity
&& pc.blend == self.blend
&& m.face.id() == self.face.id()
// One size and turn for the whole line: the type sets every glyph at the first one's.
&& (m.scale - self.scale).abs() <= self.scale * 1e-4
&& (m.scale - self.scale).abs() <= self.scale * slack.max(1e-4)
// Wrapped: type turned 180° has angles near +π and −π.
&& ((m.angle - self.angle + PI).rem_euclid(TAU) - PI).abs() < 1e-5
&& ((m.angle - self.angle + PI).rem_euclid(TAU) - PI).abs() < slack.max(1e-5)
&& across < size * 0.05
// After the line's end, or, for type tracked tighter than that, still ahead of the
// last glyph's start (by more than rounding); the layout check decides whether it fits.
@@ -319,6 +344,7 @@ impl Line {
parent: self.parent,
opacity: self.opacity,
blend: self.blend,
slack: self.slack,
};
for (id, m) in ids.iter().zip(ms).skip(1) {
l.push(*id, m);
@@ -370,7 +396,7 @@ impl Line {
/// (a substitution the font makes) or the same glyph elsewhere (tracking, manual spacing,
/// more space than whole spaces make); `None` when the type draws every glyph in its place.
fn first_mismatch(&self, t: &TextObject) -> Option<usize> {
first_mismatch(t, &self.matches, self.size())
first_mismatch(t, &self.matches, self.size(), self.slack)
}
/// Along the line, where its first glyph starts and its last glyph's advance ends, from
@@ -395,14 +421,16 @@ impl Line {
/// untracked type does. When untracked type with the spaces also draws the whole line, the line stays
/// untracked if the tracking is under one unit or the tracked reading drops a gap untracked
/// type reads as one space. The line also stays as it is when its tracking is 0 or outside
/// -1000..10000, and when its tracking is negative and the line does not paint the same as one
/// -1000..10000, when one of its glyphs is a near match, and when its tracking is negative and the line does not paint the same as one
/// object ([`paints_as_one`]: its glyphs may overlap). Each of the nine layouts at most takes
/// its characters, spaces included, from `budget` before it runs; without enough left, the
/// line stays as it is, or becomes the best tracked reading laid out before the budget ran out.
fn tracked(self, system_layout: bool, budget: &mut usize) -> Line {
let size = self.size();
let n = self.pieces.len();
if n < 3 || size <= 0.0 {
// A near-matched glyph sits within the tolerance of where the font draws it, so the gaps
// of a line with one say nothing about spacing.
if n < 3 || size <= 0.0 || self.matches.iter().any(|m| !m.exact) {
return self;
}
// Each layout takes its characters, spaces included, from `budget` before it runs.
@@ -568,10 +596,16 @@ impl Line {
/// Normal blend, a solid fill or none, and no stroke? One object composites its transparency and
/// blend once, spans a gradient over all of it, and strokes after filling every glyph.
fn paints_as_one(l: &Line) -> bool {
l.opacity == 1.0
&& l.blend == vectorcraft_color::BlendMode::Normal
&& matches!(l.appearance.fill_paint(), vectorcraft_color::Paint::None | vectorcraft_color::Paint::Solid { .. })
&& matches!(l.appearance.stroke_paint(), vectorcraft_color::Paint::None)
paints_once(l.opacity, l.blend, &l.appearance)
}
/// Does art with `opacity`, `blend` and `appearance` paint its overlaps the same as one object
/// and as several ([`paints_as_one`])?
fn paints_once(opacity: f32, blend: vectorcraft_color::BlendMode, appearance: &Appearance) -> bool {
opacity == 1.0
&& blend == vectorcraft_color::BlendMode::Normal
&& matches!(appearance.fill_paint(), vectorcraft_color::Paint::None | vectorcraft_color::Paint::Solid { .. })
&& matches!(appearance.stroke_paint(), vectorcraft_color::Paint::None)
}
/// The tracking Retype sets, in 1/1000 em.
@@ -596,21 +630,64 @@ fn round_tracking(t: f64) -> f64 {
/// The first of `matches` that type `t` (at `size`) does not draw as the outlines did: another
/// glyph (a substitution the font makes) or the same glyph elsewhere (tracking, manual spacing,
/// more space than whole spaces make); `None` when the type draws every glyph in its place.
fn first_mismatch(t: &TextObject, matches: &[GlyphMatch], size: f64) -> Option<usize> {
fn first_mismatch(t: &TextObject, matches: &[GlyphMatch], size: f64, slack: f64) -> Option<usize> {
let lay = vectorcraft_text::layout(FontDb::global(), t);
let mut drawn = lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty());
let tol = (size * 0.01).max(0.01);
// With a tolerance, a near-matched glyph, or any glyph of a line whose first glyph is one,
// may sit that much further (as a fraction of the size) from where the type draws it.
let first_exact = matches.first().is_none_or(|f| f.exact);
for (k, m) in matches.iter().enumerate() {
let Some(g) = drawn.next() else { return Some(k) };
let tol = (size * (0.01 + if m.exact && first_exact { 0.0 } else { slack })).max(0.01);
let at = t.xf * (g.xf * Point::ORIGIN);
if g.font_id != m.face.id() || g.gid != m.gid || at.distance(m.origin) > tol {
return Some(k);
}
// The type sets the glyph at its line's size and turn, which may differ from the glyph's
// own: the glyph drawn so must still lie within the tolerance of the shape (its center
// within the same distance as its origin).
if !(m.exact && first_exact) {
let (shape, moved) = set_apart(t, g, m);
// An exact match's own leftover is within the exact matcher's reach, not the tolerance.
let own = if m.exact { 0.0 } else { m.pose_residual };
if own.hypot(shape) > slack + 1e-9 || moved > tol {
return Some(k);
}
}
}
// Ink the outlines did not have: the last glyph is where it went wrong.
drawn.next().map(|_| matches.len().saturating_sub(1))
}
/// How glyph `g`, as type `t` draws it, differs from glyph `m` in the size, turn and place `m`
/// was matched in. The first value bounds, whatever points the outline is sampled at, the root
/// mean square distance between the two outlines' points about their center, relative to the
/// root mean square distance of `m`'s points from that center (the measure of near matches'
/// leftover distance): the largest stretch of the change from `m`'s size and turn to the drawn
/// one, which for a change of size and turn alone is that distance exactly. The second is how far
/// apart the two draw the center of the glyph's bounding box. Both are infinite when they cannot
/// be measured.
fn set_apart(t: &TextObject, g: &vectorcraft_text::PositionedGlyph, m: &GlyphMatch) -> (f64, f64) {
let (sin, cos) = m.angle.sin_cos();
let matched = kurbo::Affine::new([m.scale * cos, m.scale * sin, -m.scale * sin, m.scale * cos, m.origin.x, m.origin.y]);
let (gd, md) = (g.xf.determinant(), matched.determinant());
if !gd.is_finite() || gd.abs() < 1e-12 || !md.is_finite() || md.abs() < 1e-12 {
return (f64::INFINITY, f64::INFINITY);
}
let drawn = t.xf * g.xf;
// The change from the matched glyph to the drawn one, less the identity, without the move.
let [a, b, c, d, _, _] = (drawn * matched.inverse()).as_coeffs();
let (a, d) = (a - 1.0, d - 1.0);
// The largest singular value of [[a, c], [b, d]].
let (p, q) = ((a * a + b * b + c * c + d * d) / 2.0, a * d - b * c);
let shape = (p + (p * p - q * q).max(0.0).sqrt()).sqrt();
// The center of the glyph's box, in font units.
let center = g.xf.inverse() * kurbo::Shape::bounding_box(&g.outline).center();
let moved = (drawn * center).distance(matched * center);
let finite = |v: f64| if v.is_finite() { v } else { f64::INFINITY };
(finite(shape), finite(moved))
}
/// `lines` checked against their own layout: a line splits where its type stops drawing the
/// outlines, and a glyph its type cannot draw even on its own stays an outline (`unmatched`).
/// The glyphs laid out are bounded by a multiple of the number of glyphs.
@@ -739,6 +816,8 @@ struct Made {
text: String,
face: Arc<vectorcraft_text::FontFace>,
size: f64,
/// The tolerance near matches were taken with ([`Line::slack`]).
slack: f64,
tracking: f64,
/// The leading set on the type: None for Auto or a single line.
leading: Option<f64>,
@@ -756,6 +835,7 @@ impl Made {
text: l.text.clone(),
face: l.face.clone(),
size: l.size(),
slack: l.slack,
tracking: l.tracking,
leading: None,
opacity: l.opacity,
@@ -888,7 +968,7 @@ impl Block {
t.xf = kurbo::Affine::translate(m.origin - at) * t.xf;
}
super::typecmd::refresh_bounds(&mut t);
if let Some(k) = first_mismatch(&t, &matches, size) {
if let Some(k) = first_mismatch(&t, &matches, size, first.slack) {
// The line that holds glyph `k`.
let mut seen = 0usize;
let at = self.lines.iter().position(|l| {
@@ -917,7 +997,7 @@ impl Block {
let mut area = t.clone();
super::typemenu::point_to_area(&mut area);
let mut point = None;
if in_range(&area) && first_mismatch(&area, &matches, size).is_none() {
if in_range(&area) && first_mismatch(&area, &matches, size, first.slack).is_none() {
point = Some(std::mem::replace(&mut t, area));
}
vec![Made {
@@ -928,6 +1008,7 @@ impl Block {
text: all.text,
face: first.face.clone(),
size,
slack: first.slack,
tracking: all.tracking,
leading: set_leading,
opacity: first.opacity,
@@ -964,7 +1045,7 @@ fn share_tracking(lines: &mut [Line], system_layout: bool) {
/// `lines`, in paint order, as the objects Retype makes: runs of lines that stack as the lines of
/// one paragraph do become one object ([`Block`]). `follows(a, b)`: shape `b` comes right after
/// shape `a`, with nothing between them in paint order. `budget`: see [`Block::made`].
/// shape `a`, or is `a`, with nothing between them in paint order. `budget`: see [`Block::made`].
fn blocks(lines: Vec<Line>, follows: impl Fn(NodeId, NodeId) -> bool, system_layout: bool, budget: &mut usize) -> Vec<Made> {
let mut out = vec![];
let mut block: Option<Block> = None;
@@ -1054,11 +1135,13 @@ fn reposed(l: &Line, id: NodeId, m: &GlyphMatch) -> Line {
parent: l.parent,
opacity: l.opacity,
blend: l.blend,
slack: l.slack,
}
}
/// A new line of shape `pc` alone, as the first of its candidate glyphs `cands` (none: `None`).
fn new_line(pc: &Piece, cands: &[GlyphMatch]) -> Option<Line> {
/// A new line of shape `pc` alone, as the first of its candidate glyphs `cands` (none: `None`),
/// with near matches taken at tolerance `slack`.
fn new_line(pc: &Piece, cands: &[GlyphMatch], slack: f64) -> Option<Line> {
let m = cands.first()?;
let dir = Vec2::new(m.angle.cos(), m.angle.sin());
Some(Line {
@@ -1076,18 +1159,344 @@ fn new_line(pc: &Piece, cands: &[GlyphMatch]) -> Option<Line> {
parent: pc.parent,
opacity: pc.opacity,
blend: pc.blend,
slack,
})
}
/// The lines, by index, to drop so that no shape of several glyphs becomes type in part: each line
/// is given by the shapes it sets, one per glyph, and `glyphs_of` says how many glyphs a shape
/// is. A line setting a glyph of a shape not all of whose glyphs are set goes, and then so do the
/// lines setting the other glyphs of the shapes it held.
fn partial_lines(lines: &[Vec<NodeId>], glyphs_of: &std::collections::HashMap<NodeId, usize>) -> std::collections::HashSet<usize> {
let mut dropped = std::collections::HashSet::new();
loop {
let mut set: std::collections::HashMap<NodeId, usize> = std::collections::HashMap::new();
for (_, l) in lines.iter().enumerate().filter(|(i, _)| !dropped.contains(i)) {
for id in l {
*set.entry(*id).or_default() += 1;
}
}
let partial: std::collections::HashSet<NodeId> =
set.iter().filter(|(id, n)| glyphs_of.get(*id).is_some_and(|want| *n < want)).map(|(id, _)| *id).collect();
let before = dropped.len();
for (i, l) in lines.iter().enumerate() {
if l.iter().any(|id| partial.contains(id)) {
dropped.insert(i);
}
}
if dropped.len() == before {
return dropped;
}
}
}
/// Glyph runs longer than this (in contour groups) are not tried when a shape is split.
const MAX_RUN: usize = 3;
/// Complete splits of one shape that one [`split_parts`] search (exact or near) checks the paint
/// of, at most. When none of them is accepted, that search leaves the shape whole.
const MAX_SPLIT_TRIES: usize = 32;
/// A shape of more contour groups than this is not split: it is matched whole only.
const MAX_SPLIT_GROUPS: usize = 256;
/// A shape of more contours than this is not split either, and its contours are not grouped.
const MAX_SPLIT_CONTOURS: usize = 512;
/// Contours of all the selected shapes one command groups, at most: the shapes past them are
/// matched whole only.
const MAX_SPLIT_TOTAL_CONTOURS: usize = 16_384;
/// A shape of more path elements than this is not split, and its contours are not grouped: 16
/// times the most a glyph may have ([`vectorcraft_text::retype::MAX_ELEMENTS`]).
const MAX_SPLIT_ELEMENTS: usize = 16 * vectorcraft_text::retype::MAX_ELEMENTS;
/// `path`'s contour groups when it is split into glyphs: none for fewer than two or more than
/// [`MAX_SPLIT_GROUPS`], for more than [`MAX_SPLIT_CONTOURS`] contours or [`MAX_SPLIT_ELEMENTS`]
/// path elements, and for more contours than `budget` holds. A path of two or more contours takes
/// them from `budget` when it is grouped.
fn split_groups(path: &BezPath, budget: &mut usize) -> Vec<BezPath> {
// Grouping copies the contours and compares every contour with every other: count first.
let n = path.elements().iter().filter(|e| matches!(e, kurbo::PathEl::MoveTo(_))).count();
if !(2..=MAX_SPLIT_CONTOURS).contains(&n) || n > *budget || path.elements().len() > MAX_SPLIT_ELEMENTS {
return vec![];
}
*budget -= n;
let groups = vectorcraft_text::retype::clusters(path);
if (2..=MAX_SPLIT_GROUPS).contains(&groups.len()) { groups } else { vec![] }
}
/// The parts of shape `path` to match: the whole shape, or, when it is no glyph and holds several
/// contour `groups` ([`split_groups`]), runs of up to [`MAX_RUN`] groups in order, the longest that matches first (an i before a dotless i and a dot) among the runs after
/// which the rest of the groups can still be matched. Each part with its candidates; empty when
/// the shape matches nothing and its groups cannot all be matched. `find(path, part, near)` gives
/// a path's candidates: its `part` flag is set for a part of a split shape, whose contours Make
/// Compound Path may have turned the other way round, and its `near` flag allows near matches.
/// Exact matches come first: the whole shape, then its groups, then the whole shape nearly, then
/// its groups nearly. A split of several parts is kept only when `together(runs, near)` accepts the
/// paths of its runs (the parts, set one beside another, paint what the shape paints); `near` is
/// set when the parts were found by near matching.
fn parts<M>(
path: &BezPath,
groups: &[BezPath],
find: &dyn Fn(&BezPath, bool, bool) -> Vec<M>,
together: &dyn Fn(&[BezPath], bool) -> bool,
) -> Vec<Vec<M>> {
let whole = find(path, false, false);
if !whole.is_empty() {
return vec![whole];
}
let exact = split_parts(groups, &|run| find(run, true, false), &|runs| together(runs, false));
if !exact.is_empty() {
return exact;
}
let whole = find(path, false, true);
if !whole.is_empty() {
return vec![whole];
}
split_parts(groups, &|run| find(run, true, true), &|runs| together(runs, true))
}
/// [`parts`] of a shape split into contour `groups`, each run's candidates from `find`; empty for
/// no groups, when the groups cannot all be matched and when `together` rejects every split of
/// several parts it is asked about. The complete splits are tried with the longest runs first,
/// then with the shortest runs, then the others in order, a longer run at an earlier group first.
/// `together` is asked about at most [`MAX_SPLIT_TRIES`] splits. `find` is asked about a run only
/// when the search reaches it, and about each run at most once, so at most [`MAX_RUN`] times per
/// group.
fn split_parts<M>(groups: &[BezPath], find: &dyn Fn(&BezPath) -> Vec<M>, together: &dyn Fn(&[BezPath]) -> bool) -> Vec<Vec<M>> {
let g = groups.len();
let mut s = Splits { groups, find, found: (0..g).map(|_| (0..MAX_RUN).map(|_| None).collect()).collect(), whole: vec![None; g] };
// A split is the runs it takes, each as (start, number of groups).
let mut first = vec![];
if g == 0 || !s.extend(&mut first, false) {
return vec![];
}
let runs_of =
|split: &[(usize, usize)]| -> Vec<BezPath> { split.iter().map(|&(at, n)| groups.get(at..at + n).map(joined).unwrap_or_default()).collect() };
let accepted = 'search: {
if first.len() == 1 {
break 'search Some(first);
}
// The shortest runs are looked up only once the longest are rejected.
let mut shortest = vec![];
let mut shortest_next = true;
let mut rest = first.clone();
let mut candidate = Some(first.clone());
let mut tried = 0;
while let Some(split) = candidate.take() {
if tried == MAX_SPLIT_TRIES {
break;
}
tried += 1;
if together(&runs_of(&split)) {
break 'search Some(split);
}
if std::mem::take(&mut shortest_next) && s.extend(&mut shortest, true) && shortest != first {
candidate = Some(shortest.clone());
continue;
}
candidate = loop {
if !s.advance(&mut rest) {
break None;
}
if rest != shortest {
break Some(rest.clone());
}
};
}
None
};
let Some(split) = accepted else { return vec![] };
let mut out = vec![];
for (at, n) in split {
let Some(Some(cands)) = s.found.get_mut(at).and_then(|f| f.get_mut(n.wrapping_sub(1))).map(Option::take) else { return vec![] };
out.push(cands);
}
out
}
/// The state of one [`split_parts`] search: each run's candidates and whether the groups from each
/// start can all be matched, each found when the search first needs it.
struct Splits<'a, M> {
groups: &'a [BezPath],
find: &'a dyn Fn(&BezPath) -> Vec<M>,
/// By start and length less one: the run's candidates, once looked up.
found: Vec<Vec<Option<Vec<M>>>>,
/// By start: whether the groups from there on can all be matched, once known.
whole: Vec<Option<bool>>,
}
impl<M> Splits<'_, M> {
/// Whether the run of `n` groups at `at` matches, looking it up the first time.
fn matches(&mut self, at: usize, n: usize) -> bool {
let Some(slot) = self.found.get_mut(at).and_then(|f| f.get_mut(n.wrapping_sub(1))) else { return false };
if slot.is_none() {
let cands = self.groups.get(at..at + n).map(|run| (self.find)(&joined(run))).unwrap_or_default();
*slot = Some(cands);
}
slot.as_ref().is_some_and(|c| !c.is_empty())
}
/// Whether the groups from `at` on can all be matched. The search goes from `at` forward, the
/// longest run first, and no start is searched twice, so it ends after at most [`MAX_RUN`]
/// lookups and checks per group.
fn completes(&mut self, at: usize) -> bool {
let g = self.groups.len();
if at >= g {
return at == g;
}
if let Some(known) = self.whole.get(at).copied().flatten() {
return known;
}
// From `at`: the starts still to settle, each with the run length to try next.
let mut stack: Vec<(usize, usize)> = vec![(at, MAX_RUN.min(g - at))];
while let Some(&(i, n)) = stack.last() {
if self.whole.get(i).copied().flatten().is_some() {
stack.pop();
continue;
}
if n == 0 {
if let Some(w) = self.whole.get_mut(i) {
*w = Some(false);
}
stack.pop();
continue;
}
if let Some(top) = stack.last_mut() {
top.1 = n - 1;
}
if !self.matches(i, n) {
continue;
}
let next = i + n;
match if next == g { Some(true) } else { self.whole.get(next).copied().flatten() } {
Some(true) => {
if let Some(w) = self.whole.get_mut(i) {
*w = Some(true);
}
stack.pop();
}
Some(false) => {}
None => {
// Settle `next` first, then try this run again.
if let Some(top) = stack.last_mut() {
top.1 = n;
}
stack.push((next, MAX_RUN.min(g - next)));
}
}
}
self.whole.get(at).copied().flatten() == Some(true)
}
/// Whether `n` groups at `at` are a run a complete split can take.
fn fits(&mut self, at: usize, n: usize) -> bool {
self.matches(at, n) && self.completes(at + n)
}
/// Takes `split` on to the last group, with the longest run that fits at each start (or, with
/// `shortest`, the shortest); false when no run fits.
fn extend(&mut self, split: &mut Vec<(usize, usize)>, shortest: bool) -> bool {
let g = self.groups.len();
let mut i = split.last().map_or(0, |&(at, n)| at + n);
while i < g {
let most = MAX_RUN.min(g - i);
let lens: Vec<usize> = if shortest { (1..=most).collect() } else { (1..=most).rev().collect() };
let Some(n) = lens.into_iter().find(|&n| self.fits(i, n)) else { return false };
split.push((i, n));
i += n;
}
true
}
/// Moves `split` on to the next complete split, in order: the runs before the last start where
/// a shorter run fits kept, that shorter run, and the longest runs after it. False past the last.
fn advance(&mut self, split: &mut Vec<(usize, usize)>) -> bool {
while let Some((at, n)) = split.pop() {
if let Some(m) = (1..n).rev().find(|&m| self.fits(at, m)) {
split.push((at, m));
return self.extend(split, false);
}
}
false
}
}
/// Contour groups joined into one path.
fn joined(run: &[BezPath]) -> BezPath {
let mut p = BezPath::new();
for g in run {
p.extend(g.iter());
}
p
}
/// Every run of contour `groups` ([`split_groups`]) [`parts`] may try.
fn runs(groups: &[BezPath]) -> Vec<BezPath> {
let mut out = vec![];
for i in 0..groups.len() {
for n in 1..=MAX_RUN.min(groups.len() - i) {
if let Some(run) = groups.get(i..i + n) {
out.push(joined(run));
}
}
}
out
}
/// The keys the index looks glyphs up by for the `shapes` (each with its contour groups) and
/// every run of their groups: their exact [`shape_key`](vectorcraft_text::retype::shape_key)s and,
/// with a `tolerance` above 0, at most [`MAX_NEAR_KEYS`](vectorcraft_text::retype::MAX_NEAR_KEYS)
/// distinct [`near_key`](vectorcraft_text::retype::near_key)s: every whole shape's first, in the
/// order the shapes come, then the runs of their groups. Paths past that many near keys are not
/// looked up for near matches.
fn lookup_keys<'a>(
shapes: impl IntoIterator<Item = (&'a BezPath, &'a [BezPath])>,
tolerance: f64,
) -> (std::collections::BTreeSet<u64>, Vec<vectorcraft_text::retype::NearKey>) {
use vectorcraft_text::retype::{MAX_NEAR_KEYS, near_key, shape_key};
let mut wanted = std::collections::BTreeSet::new();
let mut near_wanted = vec![];
let mut add = |run: &BezPath| {
wanted.extend(shape_key(run));
if tolerance > 0.0
&& near_wanted.len() < MAX_NEAR_KEYS
&& let Some(k) = near_key(run)
&& !near_wanted.contains(&k)
{
near_wanted.push(k);
}
};
let shapes: Vec<(&BezPath, &[BezPath])> = shapes.into_iter().collect();
// The whole shapes first, then the runs of their groups.
for (path, _) in &shapes {
add(path);
}
for (_, groups) in &shapes {
for run in runs(groups) {
add(&run);
}
}
(wanted, near_wanted)
}
fn retype(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "type.retype";
let fonts: Vec<String> = match p.get("fonts") {
None | Some(Value::Null) => vec![],
None => vec![],
Some(Value::Array(a)) => {
a.iter().map(|v| v.as_str().map(str::to_owned).ok_or_else(|| bad(C, "fonts must be a list of family names"))).collect::<Result<_>>()?
}
Some(_) => return Err(bad(C, "fonts must be a list of family names")),
};
let tolerance = match p.get("tolerance") {
None => 0.0,
Some(v) => match v.as_f64() {
Some(t) if (0.0..=vectorcraft_text::retype::MAX_TOLERANCE).contains(&t) => t,
_ => return Err(bad(C, "tolerance must be a number from 0 to 0.05")),
},
};
let roots = selected_roots(s)?;
let db = FontDb::global();
let system_layout = s.doc()?.doc.setup.system_layout;
@@ -1114,59 +1523,130 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
if pieces.is_empty() {
return Err(EngineError::Other("Retype: select outlined text (paths or compound paths)".into()));
}
// Only glyphs with a selected shape's key (segments per contour) can match one: the others are
// not sampled.
let wanted: std::collections::BTreeSet<u64> =
pieces.iter().filter(|pc| !pc.keeps_outline).filter_map(|pc| vectorcraft_text::retype::shape_key(&pc.path)).collect();
// Only glyphs with a selected shape's key (segments per contour) can match one exactly, and
// only glyphs with as many contours and a close area-to-length ratio nearly: the others are
// not sampled. A shape of several glyphs is looked up by the runs of its groups too.
let mut budget = MAX_SPLIT_TOTAL_CONTOURS;
let groups: Vec<Vec<BezPath>> = pieces.iter().map(|pc| if pc.keeps_outline { vec![] } else { split_groups(&pc.path, &mut budget) }).collect();
let (wanted, near_wanted) =
lookup_keys(pieces.iter().zip(&groups).filter(|(pc, _)| !pc.keeps_outline).map(|(pc, g)| (&pc.path, g.as_slice())), tolerance);
// Nothing to match (every shape stays an outline): no font is read.
let index = if wanted.is_empty() { RetypeIndex::default() } else { RetypeIndex::build(db, candidate_faces(db, d, &fonts), &wanted) };
let found: Vec<Vec<GlyphMatch>> = pieces.iter().map(|pc| if pc.keeps_outline { vec![] } else { index.matches(&pc.path) }).collect();
let index = if wanted.is_empty() && near_wanted.is_empty() {
RetypeIndex::default()
} else {
RetypeIndex::build_near(db, candidate_faces(db, d, &fonts), &wanted, &near_wanted)
};
// Exact matches first; near ones, when allowed, only for a path with none.
// With a visible fill, a glyph is kept only when it paints the area the shape paints under
// the shape's fill rule (`fill` is `Some(nonzero)`).
let find = |path: &BezPath, part: bool, near: bool, fill: Option<bool>| {
let painted = |ms: Vec<GlyphMatch>, tol: f64| -> Vec<GlyphMatch> {
match fill {
Some(nonzero) => ms.iter().filter_map(|m| index.painted_agrees(m, path, nonzero, tol)).collect(),
None => ms,
}
};
let exact = painted(if part { index.matches_either_way(path) } else { index.all_matches(path) }, 0.0);
if exact.is_empty() && near { painted(index.near_matches(path, tolerance), tolerance) } else { exact }
};
// Each shape's parts (one, unless it holds several glyphs), each with its candidates.
let found: Vec<Vec<Vec<GlyphMatch>>> = pieces
.iter()
.zip(&groups)
.map(|(pc, g)| {
if pc.keeps_outline {
return vec![];
}
let fill = pc.filled.then_some(pc.nonzero);
// Parts that all match exactly are checked at tolerance 0, in the near phase as in
// the exact one; only a part that matches nearly brings the tolerance in.
// The glyphs of a split may become separate objects: when the shape does not paint
// its overlaps as several objects would (translucent, another blend, a gradient or
// pattern fill, a stroke), its parts must not overlap, which the parts read by the
// even-odd rule against them all joined show.
let once = paints_once(pc.opacity, pc.blend, &pc.appearance);
let together = |runs: &[BezPath], near: bool| {
if fill.is_none() && once {
return true;
}
let nearly = near && runs.iter().any(|r| find(r, true, false, fill).is_empty());
let tol = if nearly { tolerance } else { 0.0 };
fill.is_none_or(|nz| vectorcraft_text::retype::parts_paint_alike(&pc.path, runs, nz, tol))
&& (once || vectorcraft_text::retype::parts_paint_alike(&joined(runs), runs, false, tol))
};
parts(&pc.path, g, &|p, part, near| find(p, part, near, fill), &together)
})
.collect();
// The face most shapes match, so a glyph several fonts share is set in the same font as
// the glyphs around it.
let mut votes: Vec<(u32, usize)> = vec![];
for ms in &found {
// Each shape votes once for each face it fits.
let mut faces: Vec<u32> = ms.iter().map(|m| m.face.id()).collect();
faces.sort_unstable();
faces.dedup();
for f in faces {
match votes.iter_mut().find(|(v, _)| *v == f) {
Some(v) => v.1 += 1,
None => votes.push((f, 1)),
// the glyphs around it. Among faces that as many shapes match, the one whose glyphs fit
// them closest in all (the least leftover distance summed over those shapes), so every
// part that fits it takes the same face, exact matches as near ones. Simplified outlines
// of one font can nearly fit another font's look-alike glyphs, some of them more closely.
// A part's matches are all exact or all near, so the distances a face sums compare alike.
let mut votes: Vec<(u32, usize, f64)> = vec![];
for ms in found.iter().flatten() {
// Each shape votes once for each face it fits, with the leftover distance of its
// closest glyph in that face.
let mut faces: Vec<(u32, f64)> = vec![];
for m in ms {
let residual = if m.residual.is_finite() { m.residual } else { f64::INFINITY };
match faces.iter_mut().find(|(f, _)| *f == m.face.id()) {
Some(f) => f.1 = f.1.min(residual),
None => faces.push((m.face.id(), residual)),
}
}
for (f, residual) in faces {
match votes.iter_mut().find(|(v, ..)| *v == f) {
Some(v) => {
v.1 += 1;
v.2 += residual;
}
None => votes.push((f, 1, residual)),
}
}
}
let rank = |face: u32| votes.iter().find(|(f, _)| *f == face).map_or(0, |v| v.1);
let rank = |face: u32| votes.iter().find(|(f, ..)| *f == face).map_or((0, f64::INFINITY), |v| (v.1, v.2));
// Most votes, then the least summed distance, then the first (the matches come upright and
// closest first).
let ranked = |(i, a): &(usize, &GlyphMatch), (j, b): &(usize, &GlyphMatch)| {
let ((va, da), (vb, db)) = (rank(a.face.id()), rank(b.face.id()));
va.cmp(&vb).then(db.total_cmp(&da)).then(j.cmp(i))
};
let mut lines: Vec<Line> = vec![];
let mut unmatched = vec![];
// An unmatched shape between glyphs ends the line: the type after it is painted after it.
let mut open = false;
for (pc, ms) in pieces.iter().zip(&found) {
// How many glyphs each shape is: a shape of several becomes type only when all of them do.
let mut glyphs_of: std::collections::HashMap<NodeId, usize> = std::collections::HashMap::new();
for (pc, parts) in pieces.iter().zip(&found) {
if pc.after_barrier {
open = false;
}
// The shape's candidates in the face most shapes fit (the first such face, as the
// matches come upright and closest first).
let face = ms.iter().enumerate().max_by_key(|(i, m)| (rank(m.face.id()), std::cmp::Reverse(*i))).map(|(_, m)| m.face.id());
let cands: Vec<GlyphMatch> = ms.iter().filter(|m| Some(m.face.id()) == face).cloned().collect();
if cands.is_empty() {
if parts.is_empty() {
unmatched.push(pc.id);
open = false;
continue;
}
let joined = match lines.last_mut() {
Some(l) if open => join(l, pc, &cands),
_ => false,
};
if !joined {
lines.extend(new_line(pc, &cands));
glyphs_of.insert(pc.id, parts.len());
for ms in parts {
// The part's candidates in the face most shapes fit (see `ranked`).
let face = ms.iter().enumerate().max_by(ranked).map(|(_, m)| m.face.id());
let cands: Vec<GlyphMatch> = ms.iter().filter(|m| Some(m.face.id()) == face).cloned().collect();
let joined = match lines.last_mut() {
Some(l) if open => join(l, pc, &cands),
_ => false,
};
if !joined {
lines.extend(new_line(pc, &cands, tolerance));
}
open = true;
}
open = true;
}
// A lone one-contour glyph (a period, a hyphen, a bullet) is too plain to tell from drawn
// art (a dot, a bar): beside other shapes it stays an outline. Selected on its own, it is
// what was asked for. Lone means alone on its baseline as the outlines lie, before the
// layout check splits lines (tracking and manual kerning split them glyph by glyph).
// art (a dot, a bar): beside other shapes, the other glyphs of a split compound path
// included, it stays an outline. Selected on its own, it is what was asked for. Lone means
// alone on its baseline as the outlines lie, before the layout check splits lines (tracking
// and manual kerning split them glyph by glyph).
let lone_pieces: std::collections::HashSet<NodeId> = lines.iter().flat_map(Line::lone_one_contour).collect();
// Each line's tracking is measured with nine layouts at most: the line as read (its
// characters), its glyphs without and with one space between them (three times its
@@ -1177,7 +1657,7 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
let mut lines: Vec<Line> = lines.into_iter().map(|l| l.tracked(system_layout, &mut budget)).collect();
share_tracking(&mut lines, system_layout);
let mut lines = verified(lines, system_layout, &mut unmatched);
if pieces.len() > 1 {
if pieces.len() > 1 || glyphs_of.values().any(|n| *n > 1) {
lines.retain(|l| {
let lone = matches!(l.pieces.as_slice(), [id] if lone_pieces.contains(id));
if lone {
@@ -1186,9 +1666,24 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
!lone
});
}
let dropped = partial_lines(&lines.iter().map(|l| l.pieces.clone()).collect::<Vec<_>>(), &glyphs_of);
let mut k = 0;
lines.retain(|l| {
let keep = !dropped.contains(&k);
k += 1;
if !keep {
unmatched.extend(l.pieces.iter().copied());
}
keep
});
// A shape of several glyphs is reported once, and not when it became type.
let kept: std::collections::HashSet<NodeId> = lines.iter().flat_map(|l| l.pieces.iter().copied()).collect();
let mut seen = std::collections::HashSet::new();
unmatched.retain(|id| !kept.contains(id) && seen.insert(*id));
let at: std::collections::HashMap<NodeId, usize> = pieces.iter().enumerate().map(|(i, pc)| (pc.id, i)).collect();
// Lines split from one compound path share its shape, with nothing between them.
let follows = |a: NodeId, b: NodeId| match (at.get(&a), at.get(&b)) {
(Some(i), Some(j)) => *j == i + 1 && pieces.get(*j).is_some_and(|pc| !pc.after_barrier),
(Some(i), Some(j)) => *j == *i || (*j == i + 1 && pieces.get(*j).is_some_and(|pc| !pc.after_barrier)),
_ => false,
};
// Joining lines takes at most four tries' work per glyph (see [`Block::made`]), with room
@@ -1204,6 +1699,9 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
let before = lines.iter().any(|l| l.point.is_some()).then(|| d.clone());
let mut ids = vec![];
let mut emptied = vec![];
// Every line's type goes in before the shapes go: a shape of several glyphs is the first
// shape of more than one line. Each goes just before its first shape, so lines from one
// shape keep their order.
for l in &lines {
let Some(first) = l.pieces.first() else { continue };
let (par, idx, _) = d.position(*first).ok_or(EngineError::NoNode(*first))?;
@@ -1213,14 +1711,18 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
node.opacity = l.opacity;
node.blend = l.blend;
d.insert(par, idx, node)?;
for pc in &l.pieces {
if let Some((Some(parent), _, _)) = d.position(*pc) {
emptied.push(parent);
}
d.remove(*pc)?;
}
ids.push(id);
}
let mut removed = std::collections::HashSet::new();
for pc in lines.iter().flat_map(|l| l.pieces.iter()) {
if !removed.insert(*pc) {
continue;
}
if let Some((Some(parent), _, _)) = d.position(*pc) {
emptied.push(parent);
}
d.remove(*pc)?;
}
// A group left holding only the new type (Create Outlines' group) gives way to it, unless
// the group has transparency, effects, a mask or a name of its own, which then keep
// applying to the type inside it. A group left empty goes.
@@ -1284,7 +1786,7 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
for (l, id) in lines.iter().zip(&ids).filter(|_| units > 0) {
let Some(point) = &l.point else { continue };
let Some(NodeKind::Text(t)) = probe.node(*id).map(|n| &n.kind) else { continue };
if flowed && (t.wrap.is_empty() || first_mismatch(t, &l.matches, l.size).is_none()) {
if flowed && (t.wrap.is_empty() || first_mismatch(t, &l.matches, l.size, l.slack).is_none()) {
continue;
}
if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) {
@@ -1306,14 +1808,18 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
"fonts": lines
.iter()
.zip(&made)
.map(|(l, id)| json!({
"family": l.face.family,
"style": l.face.style,
"size": l.size,
"tracking": l.tracking,
"leading": l.leading,
"area": area(id),
}))
.map(|(l, id)| {
let score = l.matches.iter().map(GlyphMatch::score).fold(1.0, f64::min);
json!({
"family": l.face.family,
"style": l.face.style,
"size": l.size,
"tracking": l.tracking,
"leading": l.leading,
"area": area(id),
"score": (score * 1000.0).round() / 1000.0,
})
})
.collect::<Vec<_>>(),
"unmatched": unmatched.iter().map(|i| i.0).collect::<Vec<_>>(),
"truncated": truncated,
+824 -3
View File
@@ -10,7 +10,13 @@ fn session() -> Session {
}
/// Point text, outlined: the id of the outlines' group.
fn outlined(s: &mut Session, p: serde_json::Value) -> u64 {
fn outlined(s: &mut Session, mut p: serde_json::Value) -> u64 {
// A text without a font is set in the system's default face, which differs from machine to
// machine and decides which glyphs a near match can tell apart.
if p.get("font").is_none() {
p["font"] = json!("Source Sans 3");
p["style"] = json!("Regular");
}
let id = s.execute("text.create", &p).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap()
@@ -84,7 +90,7 @@ fn a_drawn_shape_is_reported_and_left_alone() {
let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "AB", "size": 40}));
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let before = s.doc().unwrap().doc.clone();
for bad in [json!("Source Sans 3"), json!([1]), json!({"family": "x"})] {
for bad in [json!("Source Sans 3"), json!([1]), json!({"family": "x"}), json!(null)] {
let e = s.execute("type.retype", &json!({"fonts": bad})).unwrap_err().to_string();
assert!(e.contains("fonts must be a list of family names"), "{e}");
}
@@ -539,6 +545,118 @@ fn a_long_tracked_line_is_checked_in_time() {
eprintln!("450 tracked glyphs: {:?}, {} objects", t0.elapsed(), texts.len());
}
/// Every path in the document flattened into lines `tol` from its curves, each contour started at
/// its second point and run backwards: outlines simplified and built nothing like the font's.
fn simplify_every_path(s: &mut Session, tol: f64) {
let mut ids = vec![];
s.doc().unwrap().doc.walk(|n| {
if matches!(n.kind, NodeKind::Path { .. }) {
ids.push(n.id);
}
});
simplify_paths(s, &ids, tol);
}
/// [`simplify_every_path`] for the paths `ids` only.
fn simplify_paths(s: &mut Session, ids: &[NodeId], tol: f64) {
s.edit("test", |d, _| {
for id in ids {
let data = d.node_mut(*id).unwrap().path_data_mut().unwrap();
let mut contours: Vec<Vec<kurbo::Point>> = vec![];
kurbo::flatten(data.to_bezpath().iter(), tol, |el| match el {
kurbo::PathEl::MoveTo(q) => contours.push(vec![q]),
kurbo::PathEl::LineTo(q) => contours.last_mut().unwrap().push(q),
_ => {}
});
let mut out = kurbo::BezPath::new();
for mut c in contours {
if c.len() > 1 && c.first() == c.last() {
c.pop();
}
c.rotate_left(1);
c.reverse();
out.move_to(c[0]);
for q in &c[1..] {
out.line_to(*q);
}
out.close_path();
}
*data = vectorcraft_geom::PathData::from_bezpath(&out);
}
Ok(())
})
.unwrap();
}
#[test]
fn simplified_outlines_retype_only_with_a_tolerance_and_report_their_score() {
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Rag", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
simplify_every_path(&mut s, 0.05);
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let before = s.doc().unwrap().doc.clone();
let e = s.execute("type.retype", &json!({})).unwrap_err().to_string();
assert!(e.contains("no selected shape matches"), "no exact match: {e}");
for bad in [json!(-0.01), json!(0.06), json!("0.02"), json!(true), json!(null)] {
let e = s.execute("type.retype", &json!({"tolerance": bad})).unwrap_err().to_string();
assert!(e.contains("tolerance must be a number from 0 to 0.05"), "{e}");
}
assert!(s.doc().unwrap().doc == before, "nothing changes");
let r = s.execute("type.retype", &json!({"tolerance": 0.02})).unwrap();
assert_eq!(r["texts"], json!(["Rag"]), "{r}");
assert_eq!(r["unmatched"], json!([]));
assert_eq!((r["fonts"][0]["family"].as_str(), r["fonts"][0]["style"].as_str()), (Some("Source Sans 3"), Some("Regular")));
let score = r["fonts"][0]["score"].as_f64().unwrap();
assert!(score > 0.5 && score < 1.0, "a near match scores below an exact one: {score}");
let t = text_of(&s, r["ids"][0].as_u64().unwrap());
assert!(near(t.first_style().size, 40.0, 0.4), "size {}", t.first_style().size);
let o = t.xf.translation();
assert!(near(o.x, 40.0, 0.4) && near(o.y, 100.0, 0.4), "baseline start {o:?}");
}
#[test]
fn exact_matches_score_one() {
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Rag", "size": 40}));
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({"tolerance": 0.02})).unwrap();
assert_eq!(r["texts"], json!(["Rag"]), "{r}");
assert_eq!(r["fonts"][0]["score"], json!(1.0));
}
#[test]
fn exact_matches_with_a_small_leftover_still_score_one() {
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Rag", "size": 40}));
// Each glyph stretched 0.1% across its own centre: still within the exact matcher's reach, with
// a leftover distance above 0.
let mut ids = vec![];
s.doc().unwrap().doc.walk(|n| {
if matches!(n.kind, NodeKind::Path { .. }) {
ids.push(n.id);
}
});
s.edit("test", |d, _| {
for id in &ids {
let data = d.node_mut(*id).unwrap().path_data_mut().unwrap();
let p = data.to_bezpath();
let c = kurbo::Shape::bounding_box(&p).center();
let xf = kurbo::Affine::translate(c.to_vec2()) * kurbo::Affine::scale_non_uniform(1.001, 1.0) * kurbo::Affine::translate(-c.to_vec2());
*data = vectorcraft_geom::PathData::from_bezpath(&(xf * p));
}
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
// Each glyph's size now differs a little, so each is its own line.
let texts: Vec<&str> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap()).collect();
assert_eq!(texts.concat(), "Rag", "{r}");
for f in r["fonts"].as_array().unwrap() {
assert_eq!(f["score"], json!(1.0), "{r}");
}
}
#[test]
fn two_overlapping_lone_glyphs_beside_art_stay_outlines() {
// Two M outlines start 0.3 em apart, closer than the first one's advance: a tight-tracking
@@ -583,6 +701,55 @@ fn assert_same_places(a: &TextObject, b: &TextObject) {
}
}
#[test]
fn exact_glyphs_of_another_size_are_another_line_even_with_a_tolerance() {
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Tia", "size": 40}));
// The a (two contours, so not a lone one-contour glyph) made 4% larger about where it starts
// on the baseline: still exactly the glyph.
let a = *children_of(&s, g).last().unwrap();
// The a's paths (a compound path's, or its own).
let paths: Vec<u64> = match s.doc().unwrap().doc.node(NodeId(a)).unwrap().children() {
Some(c) => c.iter().map(|c| c.id.0).collect(),
None => vec![a],
};
s.edit("test", |d, _| {
let x0 = paths
.iter()
.map(|id| kurbo::Shape::bounding_box(&d.node_mut(NodeId(*id)).unwrap().path_data_mut().unwrap().to_bezpath()).x0)
.fold(f64::INFINITY, f64::min);
let at = kurbo::Vec2::new(x0, 100.0);
let xf = kurbo::Affine::translate(at) * kurbo::Affine::scale(1.04) * kurbo::Affine::translate(-at);
for id in &paths {
let data = d.node_mut(NodeId(*id)).unwrap().path_data_mut().unwrap();
*data = vectorcraft_geom::PathData::from_bezpath(&(xf * data.to_bezpath()));
}
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({"tolerance": 0.05})).unwrap();
assert_eq!(r["texts"], json!(["Ti", "a"]), "{r}");
let sizes: Vec<f64> = r["fonts"].as_array().unwrap().iter().map(|f| f["size"].as_f64().unwrap()).collect();
assert!(near(sizes[0], 40.0, 0.01) && near(sizes[1], 41.6, 0.01), "{sizes:?}");
assert!(r["fonts"].as_array().unwrap().iter().all(|f| f["score"] == json!(1.0)), "{r}");
}
#[test]
fn turned_near_matched_round_glyphs_keep_the_line_turn() {
// Round glyphs (o, O, the period) and glyphs that look alike half round (N, x, z) fit
// simplified outlines at more than one turn: each takes the turn of its line.
for (text, rotation) in [("no.", 90), ("no.", 180), ("zoo", 135), ("NOON", 180), ("xoxo", 200), ("on", 120)] {
let mut s = session();
let g = outlined(&mut s, json!({"x": 300, "y": 200, "text": text, "size": 40, "rotation": rotation}));
simplify_every_path(&mut s, 0.05);
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({"tolerance": 0.02})).unwrap();
assert_eq!(r["texts"], json!([text]), "turned {rotation}: {r}");
assert_eq!(r["unmatched"], json!([]), "{r}");
}
}
#[test]
fn several_lines_become_one_area_type_object() {
let mut s = session();
@@ -870,6 +1037,660 @@ fn spaced_letters_keep_their_spaces_when_type_draws_them() {
}
}
#[test]
fn a_near_glyph_moved_by_more_than_the_tolerance_ends_the_line() {
// The m (one path) of simplified outlines moved along the baseline by `shift` of the font
// size (40), retyped with a tolerance of 0.03: it may sit 1% + 3% of the size from where the
// type draws it.
let run = |shift: f64| {
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Tim", "size": 40}));
simplify_every_path(&mut s, 0.05);
let m = *children_of(&s, g).last().unwrap();
s.edit("test", |d, _| {
let data = d.node_mut(NodeId(m)).unwrap().path_data_mut().unwrap();
*data = vectorcraft_geom::PathData::from_bezpath(&(kurbo::Affine::translate((40.0 * shift, 0.0)) * data.to_bezpath()));
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({"tolerance": 0.03})).unwrap();
let texts: Vec<String> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect();
assert_eq!(texts.concat(), "Tim", "{r}");
texts.len()
};
assert_eq!(run(0.02), 1, "within the tolerance: one line");
assert!(run(0.06) > 1, "past it: the line splits where the m was moved");
}
/// The bounding box of shape `id` (a path, or a compound path's paths), in document space.
fn shape_box(s: &Session, id: u64) -> kurbo::Rect {
let d = &s.doc().unwrap().doc;
let n = d.node(NodeId(id)).unwrap();
let paths: Vec<&vectorcraft_doc::Node> = match n.children() {
Some(c) => c.iter().map(|c| &**c).collect(),
None => vec![n],
};
paths
.iter()
.filter_map(|p| match &p.kind {
NodeKind::Path { path, .. } => Some(kurbo::Shape::bounding_box(&path.to_bezpath())),
_ => None,
})
.reduce(|a, b| a.union(b))
.unwrap()
}
/// The bounding box of each glyph with ink that type `t` draws, in document space.
fn drawn_boxes(t: &TextObject) -> Vec<kurbo::Rect> {
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty()).map(|g| kurbo::Shape::bounding_box(&(t.xf * g.outline.clone()))).collect()
}
#[test]
fn a_near_glyph_whose_size_and_turn_differ_past_the_tolerance_ends_the_line() {
// The m of simplified outlines made 4% larger, and turned 0.04 radians as well, about where it
// starts on the baseline, retyped with a tolerance of 0.05. Each change alone is within the
// size and turn a near-matched line allows, but drawn at the line's size and turn the m would
// lie further than 0.05 of its spread from its outline: it becomes type of its own. Larger
// alone, it is still within the tolerance and stays on the line.
for (scale, turn, lines) in [(1.04, 0.0, 1), (1.04, 0.04, 2)] {
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Tim", "size": 40}));
simplify_every_path(&mut s, 0.05);
let kids = children_of(&s, g);
let m = *kids.last().unwrap();
let x0 = shape_box(&s, m).x0;
s.edit("test", |d, _| {
let at = kurbo::Vec2::new(x0, 100.0);
let xf = kurbo::Affine::translate(at) * kurbo::Affine::rotate(turn) * kurbo::Affine::scale(scale) * kurbo::Affine::translate(-at);
let data = d.node_mut(NodeId(m)).unwrap().path_data_mut().unwrap();
*data = vectorcraft_geom::PathData::from_bezpath(&(xf * data.to_bezpath()));
Ok(())
})
.unwrap();
let before: Vec<kurbo::Rect> = kids.iter().map(|k| shape_box(&s, *k)).collect();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({"tolerance": 0.05})).unwrap();
let texts: Vec<&str> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap()).collect();
assert_eq!(texts.concat(), "Tim", "{r}");
assert_eq!(texts.len(), lines, "scale {scale}, turn {turn}: {r}");
if lines == 1 {
continue;
}
let drawn: Vec<kurbo::Rect> = r["ids"].as_array().unwrap().iter().flat_map(|id| drawn_boxes(&text_of(&s, id.as_u64().unwrap()))).collect();
assert_eq!(drawn.len(), before.len(), "{r}");
for b in &before {
// The glyph drawn nearest where the outline was.
let d = drawn.iter().min_by(|p, q| p.center().distance(b.center()).total_cmp(&q.center().distance(b.center()))).unwrap();
let size = b.width().hypot(b.height());
assert!(
(d.width() - b.width()).abs() < size * 0.01 && (d.height() - b.height()).abs() < size * 0.01,
"scale {scale}, turn {turn}: the outline's box {b:?}, the type's {d:?}: {r}"
);
}
}
}
#[test]
fn an_exact_glyph_moved_splits_the_line_whatever_the_tolerance() {
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Tim", "size": 40}));
let m = *children_of(&s, g).last().unwrap();
s.edit("test", |d, _| {
let data = d.node_mut(NodeId(m)).unwrap().path_data_mut().unwrap();
*data = vectorcraft_geom::PathData::from_bezpath(&(kurbo::Affine::translate((40.0 * 0.03, 0.0)) * data.to_bezpath()));
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({"tolerance": 0.05})).unwrap();
assert_eq!(r["texts"], json!(["Ti", "m"]), "exact glyphs keep the exact limits: {r}");
}
#[test]
fn an_exact_glyph_after_a_near_one_keeps_the_exact_limits() {
// T exact, o simplified (a near match), m exact moved by 3% of the size along the baseline.
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Tom", "size": 40}));
let kids = children_of(&s, g);
let o: Vec<NodeId> = match s.doc().unwrap().doc.node(NodeId(kids[1])).unwrap().children() {
Some(c) => c.iter().map(|c| c.id).collect(),
None => vec![NodeId(kids[1])],
};
simplify_paths(&mut s, &o, 0.05);
let m = kids[2];
s.edit("test", |d, _| {
let data = d.node_mut(NodeId(m)).unwrap().path_data_mut().unwrap();
*data = vectorcraft_geom::PathData::from_bezpath(&(kurbo::Affine::translate((40.0 * 0.03, 0.0)) * data.to_bezpath()));
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({"tolerance": 0.05})).unwrap();
assert_eq!(r["texts"], json!(["To", "m"]), "the near o does not loosen the m's limits: {r}");
}
/// The outlines of `text` made into one compound path: the compound's id.
fn one_compound(s: &mut Session, text: &str) -> u64 {
let g = outlined(s, json!({"x": 40, "y": 100, "text": text, "size": 40}));
let glyphs = children_of(s, g);
s.execute("select.set", &json!({"ids": glyphs})).unwrap();
s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()
}
#[test]
fn a_word_outlined_as_one_compound_path_splits_into_its_glyphs() {
let mut s = session();
let c = one_compound(&mut s, "Tim");
s.execute("select.set", &json!({"ids": [c]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!(["Tim"]), "the i's stem and dot are one glyph: {r}");
assert_eq!(r["unmatched"], json!([]));
assert!(s.doc().unwrap().doc.node(NodeId(c)).is_none(), "the compound becomes the type");
}
#[test]
fn a_lone_period_in_a_compound_selected_alone_stays_an_outline() {
let mut s = session();
// An A and, far below it, a period, made into one compound path and selected alone: the
// period, alone on its baseline beside the A, is a dot as much as a period, so it stays an
// outline, and so does the A in the same compound.
let t = outlined(&mut s, json!({"x": 40, "y": 100, "text": "A", "size": 40}));
let dot = outlined(&mut s, json!({"x": 40, "y": 300, "text": ".", "size": 40}));
let mut ids = children_of(&s, t);
ids.extend(children_of(&s, dot));
s.execute("select.set", &json!({"ids": ids})).unwrap();
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [c]})).unwrap();
let before = s.doc().unwrap().doc.clone();
let e = match s.execute("type.retype", &json!({})) {
Ok(r) => panic!("the period became type: {r}"),
Err(e) => e.to_string(),
};
assert!(e.contains("(1 checked)"), "{e}");
assert!(s.doc().unwrap().doc == before, "nothing changes");
}
#[test]
fn lines_from_one_compound_path_keep_their_order() {
let mut s = session();
// Two lines of outlines made into one compound path, farther apart than the lines of one
// paragraph, so each stays an object of its own.
let top = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Tim", "size": 40}));
let low = outlined(&mut s, json!({"x": 40, "y": 300, "text": "Ham", "size": 40}));
let mut glyphs = children_of(&s, top);
glyphs.extend(children_of(&s, low));
s.execute("select.set", &json!({"ids": glyphs})).unwrap();
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [c]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
let ids: Vec<u64> = r["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
assert_eq!(ids.len(), 2, "{r}");
let texts: Vec<String> = ids.iter().map(|id| text_of(&s, *id).plain_text()).collect();
let d = &s.doc().unwrap().doc;
let at: Vec<usize> = ids.iter().map(|id| d.position(NodeId(*id)).unwrap().1).collect();
// The lines stack in the order of the compound's contours: the first line behind the second.
let first = texts.iter().position(|t| t == "Tim").unwrap();
let second = texts.iter().position(|t| t == "Ham").unwrap();
assert!(at[first] < at[second], "{texts:?} at {at:?}");
}
#[test]
fn stacked_lines_from_one_compound_path_become_one_object() {
let mut s = session();
// Two lines of one paragraph, outlined and made into one compound path: they join as the
// lines of separate outlines do.
let text = "Tim\nHam";
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 40}));
let glyphs = children_of(&s, g);
s.execute("select.set", &json!({"ids": glyphs})).unwrap();
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [c]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!([text]), "{r}");
assert_eq!(r["unmatched"], json!([]), "{r}");
assert!(s.doc().unwrap().doc.node(NodeId(c)).is_none(), "the compound becomes the type");
}
#[test]
fn a_compound_whose_parts_are_not_all_glyphs_stays_whole() {
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Ti", "size": 40}));
let mut ids = children_of(&s, g);
// A shape no glyph is, beside the letters, in the same compound.
ids.push(s.execute("shape.star", &json!({"cx": 140, "cy": 85, "radius1": 12, "radius2": 5, "points": 7})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": ids})).unwrap();
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [c]})).unwrap();
let before = s.doc().unwrap().doc.clone();
let e = s.execute("type.retype", &json!({})).unwrap_err().to_string();
assert!(e.contains("(1 checked)"), "reported once: {e}");
assert!(s.doc().unwrap().doc == before, "nothing changes");
}
#[test]
fn glyphs_that_overlap_in_an_even_odd_compound_stay_an_outline() {
let mut s = session();
// Two o's moved onto each other and made into one compound path: the even-odd rule leaves
// the overlap unpainted, and two glyphs set side by side would paint it.
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "oo", "size": 40}));
let kids = children_of(&s, g);
s.execute("object.move", &json!({"ids": [kids[1]], "dx": -9, "dy": 0})).unwrap();
s.execute("select.set", &json!({"ids": kids})).unwrap();
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [c]})).unwrap();
let before = s.doc().unwrap().doc.clone();
let e = match s.execute("type.retype", &json!({})) {
Ok(r) => panic!("the overlapping o's became type: {r}"),
Err(e) => e.to_string(),
};
assert!(e.contains("(1 checked)"), "{e}");
assert!(s.doc().unwrap().doc == before, "nothing changes");
}
#[test]
fn a_translucent_compound_whose_glyphs_overlap_stays_an_outline() {
// Two i's, the second moved half onto the first and down off its baseline, made into one
// compound path filled by the nonzero rule with every contour running one way: the parts paint
// the shape's area, but on two lines they become two objects, and at 50% opacity their
// overlap would be painted twice.
for opacity in [1.0f32, 0.5] {
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "ii", "size": 40}));
let kids = children_of(&s, g);
let dx = shape_box(&s, kids[0]).x0 - shape_box(&s, kids[1]).x0 + 2.0;
s.execute("object.move", &json!({"ids": [kids[1]], "dx": dx, "dy": 6})).unwrap();
s.execute("select.set", &json!({"ids": kids})).unwrap();
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
let paths = children_of(&s, c);
s.edit("test", |d, _| {
// Make Compound Path turns the second glyph's contours the other way round.
for p in &paths {
let data = d.node_mut(NodeId(*p)).unwrap().path_data_mut().unwrap();
let b = data.to_bezpath();
if kurbo::Shape::area(&b) < 0.0 {
*data = vectorcraft_geom::PathData::from_bezpath(&b.reverse_subpaths());
}
}
let n = d.node_mut(NodeId(c)).unwrap();
n.opacity = opacity;
if let NodeKind::Compound { rule, .. } = &mut n.kind {
*rule = vectorcraft_geom::FillRule::NonZero;
}
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [c]})).unwrap();
let r = s.execute("type.retype", &json!({}));
if opacity == 1.0 {
let r = r.unwrap();
assert_eq!(r["texts"], json!(["i", "i"]), "opaque, the two lines become type: {r}");
} else {
assert!(r.is_err(), "translucent, the compound stays an outline: {r:?}");
}
}
}
#[test]
fn overlapping_exact_glyphs_stay_an_outline_when_near_matches_are_allowed() {
// Exact parts the even-odd rule rejects stay rejected when the near phase finds them again.
for dx in [-9.0, -11.0, -12.0, -13.0, -14.0] {
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "oo", "size": 40}));
let kids = children_of(&s, g);
s.execute("object.move", &json!({"ids": [kids[1]], "dx": dx, "dy": 0})).unwrap();
s.execute("select.set", &json!({"ids": kids})).unwrap();
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [c]})).unwrap();
for tolerance in [0.0, 0.05] {
if let Ok(r) = s.execute("type.retype", &json!({"tolerance": tolerance})) {
panic!("the overlapping o's became type at dx {dx}, tolerance {tolerance}: {r}");
}
}
}
}
#[test]
fn exact_parts_of_a_compound_are_checked_at_tolerance_zero() {
let mut s = session();
// A T and an o whose boxes overlap by 4 units, one painted area apart (the o sits under the
// bar's arm): a strip that the probes of tolerance 0.05 cannot see into but those of an exact
// match can. Both parts match exactly, so asking for near matches does not change the result.
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "To", "size": 40}));
let kids = children_of(&s, g);
let (t, o) = (kids[0], kids[1]);
let bounds = |s: &Session, id: u64| s.doc().unwrap().doc.node(NodeId(id)).unwrap().geometric_bounds().unwrap();
let dx = bounds(&s, t).x1 - 4.0 - bounds(&s, o).x0;
s.execute("object.move", &json!({"ids": [o], "dx": dx, "dy": 0})).unwrap();
s.execute("select.set", &json!({"ids": kids})).unwrap();
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
for params in [json!({}), json!({"tolerance": 0.05})] {
s.execute("select.set", &json!({"ids": [c]})).unwrap();
let before = s.doc().unwrap().doc.clone();
let r = s.execute("type.retype", &params).unwrap();
assert_eq!(r["unmatched"], json!([]), "{params}: {r}");
assert!(s.doc().unwrap().doc.node(NodeId(c)).is_none(), "{params}: the compound becomes type");
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc == before, "{params}: undo restores it");
}
}
#[test]
fn glyphs_side_by_side_in_an_even_odd_compound_still_become_type() {
let mut s = session();
let c = one_compound(&mut s, "oo");
s.execute("select.set", &json!({"ids": [c]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!(["oo"]), "{r}");
}
#[test]
fn a_compound_whose_glyph_stays_an_outline_keeps_its_other_glyphs_too() {
let mut s = session();
// An A (two contours), and far below it a period: a lone one-contour glyph beside other
// shapes stays an outline, so the A, in the same compound, must stay too.
let t = outlined(&mut s, json!({"x": 40, "y": 100, "text": "A", "size": 40}));
let dot = outlined(&mut s, json!({"x": 40, "y": 300, "text": ".", "size": 40}));
let paths = |s: &Session, id: u64| match s.doc().unwrap().doc.node(NodeId(id)).unwrap().children() {
Some(c) => c.iter().map(|c| c.id.0).collect(),
None => vec![id],
};
let mut ids: Vec<u64> = paths(&s, t);
ids.extend(paths(&s, dot));
assert_eq!(ids.len(), 2, "one path each");
s.execute("select.set", &json!({"ids": ids})).unwrap();
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
let r = s.execute("shape.rectangle", &json!({"x": 300, "y": 300, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [c, r]})).unwrap();
let before = s.doc().unwrap().doc.clone();
let e = match s.execute("type.retype", &json!({})) {
Ok(r) => panic!("the A became type without its period: {r}"),
Err(e) => e.to_string(),
};
assert!(e.contains("(2 checked)"), "{e}");
assert!(s.doc().unwrap().doc == before, "nothing changes");
}
#[test]
fn a_split_takes_a_shorter_run_when_the_longest_leaves_a_group_unmatched() {
use kurbo::Shape;
// Three groups A, B and C side by side. A and B together are a glyph, but then C alone is
// none; A alone and B and C together are glyphs, so the split is A, BC.
let mut p = kurbo::BezPath::new();
for x in [0.0, 100.0, 200.0] {
p.extend(kurbo::Rect::new(x, 0.0, x + 40.0, 40.0).path_elements(0.1));
}
let find = |path: &kurbo::BezPath, part: bool, _near: bool| -> Vec<&'static str> {
let b = path.bounding_box();
match (part, b.x0.round() as i64, b.x1.round() as i64) {
(true, 0, 140) => vec!["AB"],
(true, 0, 40) => vec!["A"],
(true, 100, 240) => vec!["BC"],
_ => vec![],
}
};
let groups = all_groups(&p);
assert_eq!(super::parts(&p, &groups, &find, &|_, _| true), vec![vec!["A"], vec!["BC"]]);
// A split the parts' paint does not allow is dropped.
assert!(super::parts(&p, &groups, &find, &|_, _| false).is_empty());
// With no way to match every group, nothing.
let none = |path: &kurbo::BezPath, part: bool, _near: bool| -> Vec<&'static str> {
let b = path.bounding_box();
if part && b.x0.round() as i64 == 0 && b.x1.round() as i64 == 140 { vec!["AB"] } else { vec![] }
};
assert!(super::parts(&p, &groups, &none, &|_, _| true).is_empty());
}
#[test]
fn a_split_the_paint_check_rejects_gives_way_to_another_complete_split() {
use kurbo::Shape;
let mut p = kurbo::BezPath::new();
for x in [0.0, 100.0, 200.0] {
p.extend(kurbo::Rect::new(x, 0.0, x + 40.0, 40.0).path_elements(0.1));
}
let find = |path: &kurbo::BezPath, part: bool, _near: bool| -> Vec<&'static str> {
let b = path.bounding_box();
match (part, b.x0.round() as i64, b.x1.round() as i64) {
(true, 0, 140) => vec!["AB"],
(true, 0, 40) => vec!["A"],
(true, 100, 140) => vec!["B"],
(true, 200, 240) => vec!["C"],
_ => vec![],
}
};
let groups = all_groups(&p);
// The longest runs first (AB, C) are rejected; the three single glyphs are kept.
let singles = |runs: &[kurbo::BezPath], _near: bool| runs.len() == 3;
assert_eq!(super::parts(&p, &groups, &find, &singles), vec![vec!["A"], vec!["B"], vec!["C"]]);
// When no complete split is accepted, nothing.
assert!(super::parts(&p, &groups, &find, &|_, _| false).is_empty());
}
#[test]
fn a_split_between_the_longest_and_the_shortest_runs_is_tried() {
use kurbo::Shape;
// Four groups A, B, C and D. ABC and D (the longest runs first) and the four single glyphs
// (the shortest) are complete splits the paint check rejects; AB and CD is the one it accepts.
let mut p = kurbo::BezPath::new();
for x in [0.0, 100.0, 200.0, 300.0] {
p.extend(kurbo::Rect::new(x, 0.0, x + 40.0, 40.0).path_elements(0.1));
}
let find = |path: &kurbo::BezPath, part: bool, _near: bool| -> Vec<&'static str> {
let b = path.bounding_box();
match (part, b.x0.round() as i64, b.x1.round() as i64) {
(true, 0, 240) => vec!["ABC"],
(true, 0, 140) => vec!["AB"],
(true, 200, 340) => vec!["CD"],
(true, 0, 40) => vec!["A"],
(true, 100, 140) => vec!["B"],
(true, 200, 240) => vec!["C"],
(true, 300, 340) => vec!["D"],
_ => vec![],
}
};
let groups = all_groups(&p);
let pairs = |runs: &[kurbo::BezPath], _near: bool| runs.len() == 2 && runs.first().is_some_and(|r| r.bounding_box().x1.round() as i64 == 140);
assert_eq!(super::parts(&p, &groups, &find, &pairs), vec![vec!["AB"], vec!["CD"]]);
}
#[test]
fn at_most_max_split_tries_complete_splits_are_checked() {
use kurbo::Shape;
// Twelve groups, every run of up to three of them a glyph: far more complete splits than the
// cap. The paint check is asked about the cap's number of them and no more, and each run is
// looked up at most once.
let mut p = kurbo::BezPath::new();
for i in 0..12 {
let x = f64::from(i) * 100.0;
p.extend(kurbo::Rect::new(x, 0.0, x + 40.0, 40.0).path_elements(0.1));
}
let groups = all_groups(&p);
assert_eq!(groups.len(), 12);
let looked_up = std::cell::Cell::new(0usize);
let find = |_: &kurbo::BezPath| -> Vec<&'static str> {
looked_up.set(looked_up.get() + 1);
vec!["glyph"]
};
let asked = &std::cell::Cell::new(0usize);
let accept_at = |n: usize| {
move |_: &[kurbo::BezPath]| {
asked.set(asked.get() + 1);
asked.get() == n
}
};
// Rejected every time: the search stops at the cap.
assert!(super::split_parts(&groups, &find, &accept_at(usize::MAX)).is_empty());
assert_eq!(asked.get(), super::MAX_SPLIT_TRIES);
assert!(looked_up.get() <= super::MAX_RUN * groups.len(), "{} lookups", looked_up.get());
// A first split that is accepted looks up its own runs only: four runs of three groups.
asked.set(0);
looked_up.set(0);
assert_eq!(super::split_parts(&groups, &find, &accept_at(1)).len(), 4);
assert_eq!(looked_up.get(), 4);
// The last split tried is still taken; the one past the cap is not tried.
asked.set(0);
assert!(super::split_parts(&groups, &find, &accept_at(super::MAX_SPLIT_TRIES)).len() > 1);
asked.set(0);
assert!(super::split_parts(&groups, &find, &accept_at(super::MAX_SPLIT_TRIES + 1)).is_empty());
assert_eq!(asked.get(), super::MAX_SPLIT_TRIES);
}
/// `path`'s contour groups, with no limit on the contours grouped.
fn all_groups(path: &kurbo::BezPath) -> Vec<kurbo::BezPath> {
let mut budget = usize::MAX;
super::split_groups(path, &mut budget)
}
#[test]
fn exact_matches_of_the_parts_come_before_a_near_match_of_the_whole() {
use kurbo::Shape;
// Two groups side by side, each exactly a glyph (two periods), and the whole only nearly one
// (a dieresis): the parts win.
let mut p = kurbo::BezPath::new();
for x in [0.0, 100.0] {
p.extend(kurbo::Rect::new(x, 0.0, x + 40.0, 40.0).path_elements(0.1));
}
let find = |path: &kurbo::BezPath, part: bool, near: bool| -> Vec<&'static str> {
let b = path.bounding_box();
match (part, near, b.x0.round() as i64, b.x1.round() as i64) {
(false, true, 0, 140) => vec!["dieresis"],
(true, _, 0, 40) | (true, _, 100, 140) => vec!["period"],
_ => vec![],
}
};
let groups = all_groups(&p);
assert_eq!(super::parts(&p, &groups, &find, &|_, _| true), vec![vec!["period"], vec!["period"]]);
// When the parts match only nearly too, the whole near match comes first.
let near_only = |path: &kurbo::BezPath, part: bool, near: bool| -> Vec<&'static str> {
let b = path.bounding_box();
match (part, near, b.x0.round() as i64, b.x1.round() as i64) {
(false, true, 0, 140) => vec!["dieresis"],
(true, true, 0, 40) | (true, true, 100, 140) => vec!["period"],
_ => vec![],
}
};
assert_eq!(super::parts(&p, &groups, &near_only, &|_, _| true), vec![vec!["dieresis"]]);
// The split's paint check is told whether the parts were found nearly: exact parts are
// checked at tolerance 0 whatever tolerance the command was given.
let seen = std::cell::RefCell::new(vec![]);
let record = |_: &[kurbo::BezPath], near: bool| {
seen.borrow_mut().push(near);
true
};
assert_eq!(super::parts(&p, &groups, &find, &record), vec![vec!["period"], vec!["period"]]);
assert_eq!(*seen.borrow(), vec![false]);
seen.borrow_mut().clear();
let split_near_only = |path: &kurbo::BezPath, part: bool, near: bool| -> Vec<&'static str> {
let b = path.bounding_box();
match (part, near, b.x0.round() as i64, b.x1.round() as i64) {
(true, true, 0, 40) | (true, true, 100, 140) => vec!["period"],
_ => vec![],
}
};
assert_eq!(super::parts(&p, &groups, &split_near_only, &record), vec![vec!["period"], vec!["period"]]);
assert_eq!(*seen.borrow(), vec![true]);
}
#[test]
fn a_shape_that_lost_a_glyph_drops_the_lines_of_its_other_glyphs() {
use std::collections::HashMap;
// Shapes 1 and 2 are two glyphs each, shape 3 one. Line 0 sets one glyph of 1 and one of 2;
// line 1 sets the other glyph of 2 and shape 3. Shape 1's other glyph is set nowhere.
let (a, b, c) = (NodeId(1), NodeId(2), NodeId(3));
let glyphs_of: HashMap<NodeId, usize> = [(a, 2), (b, 2), (c, 1)].into();
let lines = vec![vec![a, b], vec![b, c]];
let dropped = super::partial_lines(&lines, &glyphs_of);
assert!(dropped.contains(&0), "shape 1 is set only in part: {dropped:?}");
assert!(dropped.contains(&1), "then shape 2 is too: {dropped:?}");
// Every glyph set: nothing goes.
let whole = vec![vec![a, b], vec![a, b, c]];
assert!(super::partial_lines(&whole, &glyphs_of).is_empty());
}
#[test]
fn a_compound_of_too_many_path_elements_is_not_grouped() {
// Two contours side by side, each a polygon of `k` corners.
let two = |k: usize| {
let mut p = kurbo::BezPath::new();
for x in [0.0, 300.0] {
for i in 0..k {
let a = i as f64 / k as f64 * std::f64::consts::TAU;
let q = kurbo::Point::new(x + 100.0 + 100.0 * a.cos(), 100.0 + 100.0 * a.sin());
if i == 0 { p.move_to(q) } else { p.line_to(q) }
}
p.close_path();
}
p
};
let mut budget = usize::MAX;
assert_eq!(super::split_groups(&two(100), &mut budget).len(), 2, "a small compound is grouped");
let big = two(super::MAX_SPLIT_ELEMENTS / 2);
assert!(big.elements().len() > super::MAX_SPLIT_ELEMENTS);
let mut budget = usize::MAX;
assert!(super::split_groups(&big, &mut budget).is_empty(), "past the element limit it is matched whole only");
assert_eq!(budget, usize::MAX, "and takes no contours from the budget");
}
#[test]
fn the_runs_and_near_keys_a_selection_is_looked_up_by_are_bounded() {
use kurbo::Shape;
use vectorcraft_text::retype::MAX_NEAR_KEYS;
// A compound path of `n` rectangles side by side, each of another width: every run of up to
// three of them has its own near key.
let row = |n: usize| {
let mut p = kurbo::BezPath::new();
for i in 0..n {
let x = i as f64 * 100.0;
p.extend(kurbo::Rect::new(x, 0.0, x + 10.0 + i as f64 * 0.37, 40.0).path_elements(0.1));
}
p
};
// Each shape with its contour groups, as the command looks them up.
let with_groups = |shapes: &[kurbo::BezPath]| -> Vec<(kurbo::BezPath, Vec<kurbo::BezPath>)> {
let mut budget = super::MAX_SPLIT_TOTAL_CONTOURS;
shapes.iter().map(|p| (p.clone(), super::split_groups(p, &mut budget))).collect()
};
let keys_of = |shapes: &[(kurbo::BezPath, Vec<kurbo::BezPath>)], tolerance: f64| {
super::lookup_keys(shapes.iter().map(|(p, g)| (p, g.as_slice())), tolerance)
};
let few = with_groups(&[row(20)]);
assert_eq!(super::runs(&few[0].1).len(), 20 + 19 + 18, "every run of 1 to 3 groups");
let (_, keys) = keys_of(&few, 0.01);
assert!(keys.len() > 20, "{}", keys.len());
assert!(keys_of(&few, 0.0).1.is_empty(), "no near keys without a tolerance");
// Past 256 groups the shape is matched whole only, and past 512 contours its contours are not
// grouped at all.
assert!(all_groups(&row(300)).is_empty());
assert_eq!(all_groups(&row(256)).len(), 256);
let mut nested = kurbo::BezPath::new();
for i in 0..200 {
// Each square with two squares inside it: 200 groups of 3 contours.
let x = i as f64 * 100.0;
nested.extend(kurbo::Rect::new(x, 0.0, x + 90.0, 90.0).path_elements(0.1));
nested.extend(kurbo::Rect::new(x + 10.0, 10.0, x + 40.0, 40.0).path_elements(0.1));
nested.extend(kurbo::Rect::new(x + 50.0, 50.0, x + 80.0, 80.0).path_elements(0.1));
}
assert!(all_groups(&nested).is_empty(), "600 contours");
assert_eq!(vectorcraft_text::retype::clusters(&nested).len(), 200, "which would make 200 groups");
// Many shapes with many runs each: the near keys stop at the cap.
let mut shapes: Vec<kurbo::BezPath> = (0..8).map(|k| kurbo::Affine::scale_non_uniform(1.0, 1.0 + k as f64 * 0.5) * row(200)).collect();
let (_, keys) = keys_of(&with_groups(&shapes), 0.01);
assert_eq!(keys.len(), MAX_NEAR_KEYS);
// A plain shape selected after them still gets its own near key: whole shapes come first.
let plain = kurbo::Circle::new((0.0, 0.0), 30.0).to_path(0.1);
let key = vectorcraft_text::retype::near_key(&plain).unwrap();
shapes.push(plain);
let (_, keys) = keys_of(&with_groups(&shapes), 0.01);
assert!(keys.contains(&key));
// One command groups at most MAX_SPLIT_TOTAL_CONTOURS contours: the shapes after them are
// matched whole only.
let full = vec![row(256); super::MAX_SPLIT_TOTAL_CONTOURS / 256 + 1];
let split: Vec<usize> = with_groups(&full).iter().map(|(_, g)| g.len()).collect();
assert!(split[..split.len() - 1].iter().all(|n| *n == 256), "{split:?}");
assert_eq!(split.last(), Some(&0));
}
#[test]
fn slight_tracking_without_spaces_is_kept() {
// Tracking 3 moves the last glyph less than the layout check notices: both readings draw it.
@@ -897,7 +1718,7 @@ fn lines_in(s: &Session, g: u64) -> Vec<super::Line> {
for pc in &pieces {
let cands: Vec<_> = index.matches(&pc.path).into_iter().filter(|m| m.face.id() == face).collect();
if !lines.last_mut().is_some_and(|l| super::join(l, pc, &cands)) {
lines.extend(super::new_line(pc, &cands));
lines.extend(super::new_line(pc, &cands, 0.0));
}
}
lines
+25 -7
View File
@@ -31,7 +31,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Apply Graphic Style",
["Window", "Graphic Styles"],
None,
"{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (with `add`: of the kinds of row the style shows) and, without `add`, the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows (with `add`: of the kinds of row the style shows) and, without `add`, its object opacity and blend mode for every label or line of its kind. With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}",
"{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. In the contents of a Live Paint group, each face takes only the style's fills and each edge only its strokes, and neither is linked. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (with `add`: of the kinds of row the style shows) and, without `add`, the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows (with `add`: of the kinds of row the style shows) and, without `add`, its object opacity and blend mode for every label or line of its kind. With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}",
has_doc,
style_apply
),
@@ -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;
+8 -8
View File
@@ -15,7 +15,7 @@ use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, Symbol, SymbolNineSlice};
use vectorcraft_geom::{Affine, Anchor, AnchorKind, PathData, Point, Rect, SubPath, shapes};
use super::brushsym::{CURRENT_SYMBOL, natural_size, normalize, place_xf, set_natural_size};
use super::brushsym::{CURRENT_SYMBOL, Placement, natural_size, normalize, place_xf, set_natural_size};
use super::clipboard::Clipboard;
use super::clipboard::resources::SwatchChoices;
use super::swatch::str_list;
@@ -50,7 +50,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add to Symbols",
["Window", "Symbol Libraries"],
None,
"{library: id or name, name? | names?: [symbol names in the library] (default: all of it), place?: false (also place an instance of the first one, its registration point at x, y: default the first artboard's centre), x?, y?, swatchConflict? (as edit.paste)} copy library symbols into the document's Symbols as one undo step (with the place), with their Symbol Options and the resources they use (the symbols they nest, patterns, swatches, brushes, graphic styles, images). A symbol the document already has (same name and art) isn't added again; a name another symbol has gets a number (\"Star 2\"). The first one becomes the current symbol → {library, names: [each symbol's name in the document], added: [names added], existing: [names already there], placed?: id}",
"{library: id or name, name? | names?: [symbol names in the library] (default: all of it), place?: false (also place an instance of the first one, its registration point at x, y: default the first artboard's centre, in the stacking order symbol.place gives it, Draw Behind included), x?, y?, swatchConflict? (as edit.paste)} copy library symbols into the document's Symbols as one undo step (with the place), with their Symbol Options and the resources they use (the symbols they nest, patterns, swatches, brushes, graphic styles, images). A symbol the document already has (same name and art) isn't added again; a name another symbol has gets a number (\"Star 2\"). The first one becomes the current symbol → {library, names: [each symbol's name in the document], added: [names added], existing: [names already there], placed?: id}",
has_doc,
add
),
@@ -59,7 +59,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Place Symbol Instance",
[],
None,
"{sourceDocument: uid, name: a symbol of that document, x?, y?} place an instance of a symbol of another open document so its registration point is at (x, y) (default: the first artboard's center), as a symbol dragged from that document's Symbols panel onto the canvas is placed. The symbol, the symbols it nests and the resources they use are added as a drop of art from that document adds them, in the same undo step as the instance: a symbol the active document already has with the same name, art and Symbol Options is used, and one with the same name but other art or Symbol Options gets a number (\"Leaf 2\"); each symbol added takes its Symbol Options along. When sourceDocument is the active document, its own symbol is placed, as symbol.place places it. An error, with no edit, when that document is no longer open or has no symbol `name` → {id, name: the symbol's name in the active document}",
"{sourceDocument: uid, name: a symbol of that document, x?, y?} place an instance of a symbol of another open document so its registration point is at (x, y) (default: the first artboard's center), in the stacking order symbol.place gives it (Draw Behind included), as a symbol dragged from that document's Symbols panel onto the canvas is placed. The symbol, the symbols it nests and the resources they use are added as a drop of art from that document adds them, in the same undo step as the instance: a symbol the active document already has with the same name, art and Symbol Options is used, and one with the same name but other art or Symbol Options gets a number (\"Leaf 2\"); each symbol added takes its Symbol Options along. When sourceDocument is the active document, its own symbol is placed, as symbol.place places it. An error, with no edit, when that document is no longer open or has no symbol `name` → {id, name: the symbol's name in the active document}",
has_doc,
place_from_document
),
@@ -816,7 +816,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
let doc_names: Vec<String> = picked.iter().map(|n| target(&imported.renamed, n)).collect();
let centre = st.doc.artboards.first().map(|a| a.rect.center()).unwrap_or(Point::ZERO);
let at = if place { Some(Point::new(number_or(p, "x", centre.x, C)?, number_or(p, "y", centre.y, C)?)) } else { None };
let parent = if place { st.target_parent()? } else { None };
let spot = if place { Some(Placement::of(s)?) } else { None };
let mut out = json!({ "library": shown_library_id(s, &info.id) });
if imported.added > 0 || place {
let placed = s.edit("Add to Symbols", |d, sel| {
@@ -830,10 +830,10 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
}
let Some(first) = doc_names.first() else { return Ok(None) };
d.unknown.insert(CURRENT_SYMBOL.into(), json!(first));
let Some(at) = at else { return Ok(None) };
let (Some(at), Some(spot)) = (at, &spot) else { return Ok(None) };
let xf = place_xf(at, natural_size(d, first), d.symbol_registration(first));
let id = d.alloc_id();
d.insert(parent, usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: first.clone(), xf }))?;
spot.insert(d, Node::new(id, NodeKind::SymbolInstance { symbol: first.clone(), xf }))?;
sel.set([id]);
Ok(Some(id))
})?;
@@ -860,7 +860,7 @@ fn place_from_document(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.doc()?;
let centre = st.doc.artboards.first().map(|a| a.rect.center()).unwrap_or(Point::ZERO);
let at = Point::new(number_or(p, "x", centre.x, C)?, number_or(p, "y", centre.y, C)?);
let parent = st.target_parent()?;
let spot = Placement::of(s)?;
let same = uid == st.uid;
let src = s.documents().iter().find(|d| d.uid == uid).map(|d| Arc::clone(&d.doc));
let src = src.ok_or_else(|| bad(C, "the document the symbol came from is no longer open"))?;
@@ -883,7 +883,7 @@ fn place_from_document(s: &mut Session, p: &Value) -> Result<Value> {
};
let xf = place_xf(at, natural_size(d, &placed), d.symbol_registration(&placed));
let id = d.alloc_id();
d.insert(parent, usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: placed.clone(), xf }))?;
spot.insert(d, Node::new(id, NodeKind::SymbolInstance { symbol: placed.clone(), xf }))?;
sel.set([id]);
Ok((id, placed))
})?;
+1
View File
@@ -112,6 +112,7 @@ mod live;
mod livecorners;
mod maskview;
pub(super) mod menucmds;
mod mesh_picks;
mod nativefile;
mod newart;
mod newdoc;
+67
View File
@@ -2231,6 +2231,73 @@ fn place_and_break_link_round_trip_geometry() {
assert_eq!(n.appearance.stroke_width(), 1.0, "strokes are not scaled by normalisation");
}
/// In Draw Behind, Place Symbol Instance puts the instance directly below the bottommost selected
/// object (beside the compound path that holds a selected path, above a clipping path), or at the
/// bottom of the current layer with nothing selected, selected and in one undo step. Draw Normal
/// and Draw Inside keep it on top, and a locked layer refuses it with no edit.
#[test]
fn placed_instances_go_below_the_selection_in_draw_behind() {
let mut s = session();
let (inst, name, _) = make_symbol(&mut s);
let (a, b) = (rect(&mut s, 0.0, 0.0, 10.0, 10.0), rect(&mut s, 20.0, 0.0, 10.0, 10.0));
let layer = s.doc().unwrap().doc.layers[0].id;
let kids = |s: &Session, id: NodeId| node(s, id).children().unwrap().iter().map(|c| c.id).collect::<Vec<_>>();
let place = |s: &mut Session| NodeId(s.execute("symbol.place", &json!({"name": name, "x": 300, "y": 200})).unwrap()["id"].as_u64().unwrap());
s.execute("view.drawMode", &json!({"mode": "behind"})).unwrap();
select(&mut s, &[b]);
let before = undo_len(&s);
let p = place(&mut s);
assert_eq!(kids(&s, layer), vec![inst, a, p, b], "directly below the selected object");
assert_eq!(undo_len(&s), before + 1);
assert_eq!(s.doc().unwrap().selection.objects, [p]);
assert!(close(bounds(&s, p), Rect::new(260.0, 180.0, 340.0, 220.0), 1e-9), "{:?}", bounds(&s, p));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(kids(&s, layer), vec![inst, a, b]);
// Below the bottommost of several selected objects.
select(&mut s, &[b, a]);
let p = place(&mut s);
assert_eq!(kids(&s, layer), vec![inst, p, a, b]);
s.execute("edit.undo", &json!({})).unwrap();
// With nothing selected, at the bottom of the current layer.
select(&mut s, &[]);
let p = place(&mut s);
assert_eq!(kids(&s, layer), vec![p, inst, a, b]);
s.execute("edit.undo", &json!({})).unwrap();
// A path selected in a compound path: beside the compound path, not inside it.
select(&mut s, &[a, b]);
s.execute("object.compoundPath.make", &json!({})).unwrap();
let compound = kids(&s, layer)[1];
let member = kids(&s, compound)[1];
select(&mut s, &[member]);
let p = place(&mut s);
assert_eq!(kids(&s, layer), vec![inst, p, compound]);
assert_eq!(kids(&s, compound).len(), 2);
s.execute("edit.undo", &json!({})).unwrap();
// Draw Normal and Draw Inside put it on top of the layer.
for mode in ["normal", "inside"] {
select(&mut s, &[compound]);
s.execute("view.drawMode", &json!({"mode": mode})).unwrap();
let p = place(&mut s);
assert_eq!(kids(&s, layer), vec![inst, compound, p], "{mode}");
s.execute("edit.undo", &json!({})).unwrap();
}
// In a clipping layer the clipping path stays at the bottom, the selected clipping path too.
s.execute("view.drawMode", &json!({"mode": "behind"})).unwrap();
s.execute("layer.clippingMask.toggle", &json!({"id": layer.0})).unwrap();
assert_eq!(kids(&s, layer), vec![compound, inst]);
for picked in [&[][..], &[compound]] {
select(&mut s, picked);
let p = place(&mut s);
assert_eq!(kids(&s, layer), vec![compound, p, inst], "{picked:?}");
s.execute("edit.undo", &json!({})).unwrap();
}
// A locked layer takes nothing.
s.execute("layer.setProps", &json!({"id": layer.0, "locked": true})).unwrap();
let before = (undo_len(&s), s.doc().unwrap().doc.clone());
assert!(s.execute("symbol.place", &json!({"name": name})).is_err());
assert_eq!((undo_len(&s), &s.doc().unwrap().doc), (before.0, &before.1));
}
#[test]
fn hidden_instance_fill_does_not_tint_expanded_symbol_art() {
for command in ["symbol.breakLink", "object.expand"] {
+87
View File
@@ -4630,6 +4630,93 @@ fn live_paint_group_with_only_source_paths_ignores_add_fill_and_add_stroke_of_it
assert!(s.execute("appearance.addFill", &json!({"target": "contents"})).is_err(), "no selection is still refused");
}
/// Whether every face of Live Paint group `g` holds only fill rows and every edge only stroke rows.
fn parts_hold_their_kind(s: &Session, g: NodeId) -> bool {
let (faces, edges) = part_looks(s, g);
faces.iter().all(|a| a.items.iter().all(|it| it.is_fill())) && edges.iter().all(|a| a.items.iter().all(|it| !it.is_fill()))
}
/// A graphic style applied to the contents of a Live Paint group, replacing their appearance or added to it, gives
/// the faces its fills and the edges its strokes, and the faces and edges are not linked to it.
#[test]
fn live_paint_group_contents_take_a_graphic_style_by_kind() {
let red = Paint::solid(Color::from_hex("#ff0000").unwrap());
let blue = Paint::solid(Color::from_hex("#0000ff").unwrap());
for add in [false, true] {
let mut s = session();
let g = live(&mut s);
let r = rect(&mut s, 400.0, 0.0, 50.0, 50.0);
s.execute("select.set", &json!({"ids": [r.0]})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap();
s.execute("graphicStyle.new", &json!({"name": "Both", "id": r.0})).unwrap();
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
s.execute("graphicStyle.apply", &json!({"name": "Both", "target": "contents", "add": add})).unwrap();
assert!(parts_hold_their_kind(&s, g), "add {add}: faces hold fills and edges strokes");
let (faces, edges) = part_looks(&s, g);
assert!(faces.iter().all(|a| a.items.iter().any(|it| *it.paint() == red)), "add {add}: each face takes the style's fill");
assert!(edges.iter().all(|a| a.items.iter().any(|it| *it.paint() == blue)), "add {add}: each edge takes the style's stroke");
let n = node(&s, g);
let mut parts = vectorcraft_tools::builder::faces(&n).into_iter().chain(vectorcraft_tools::builder::edges(&n));
assert!(parts.all(|p| p.extras().graphic_style.is_none()), "add {add}: no face or edge is linked");
}
}
/// A fill-only graphic style added to the contents of a Live Paint group without faces changes nothing and records no
/// undo step.
#[test]
fn live_paint_group_contents_without_faces_take_no_fill_only_style() {
let mut s = session();
let g = live(&mut s);
let faces: Vec<NodeId> = vectorcraft_tools::builder::faces(&node(&s, g)).iter().map(|p| p.id).collect();
s.edit("t", |d, _| {
d.children_mut(Some(g)).unwrap().retain(|c| !faces.contains(&c.id));
Ok(())
})
.unwrap();
let r = rect(&mut s, 400.0, 0.0, 50.0, 50.0);
s.edit("t", |d, _| {
let fill = AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::from_hex("#ff0000").unwrap())));
d.node_mut(r).unwrap().appearance = vectorcraft_doc::Appearance { items: vec![fill], ..Default::default() }.into();
Ok(())
})
.unwrap();
s.execute("graphicStyle.new", &json!({"name": "Fill", "id": r.0})).unwrap();
// The edges are linked to a style of their own, which they keep.
let edge = vectorcraft_tools::builder::edges(&node(&s, g))[0].id;
s.execute("graphicStyle.new", &json!({"name": "Edge", "id": edge.0})).unwrap();
assert!(node(&s, g).children().unwrap().iter().any(|c| c.extras().graphic_style.is_some()), "an edge is linked");
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
let (before, undo) = (node(&s, g), s.doc().unwrap().history.undo.len());
s.execute("graphicStyle.apply", &json!({"name": "Fill", "target": "contents", "add": true})).unwrap();
assert_eq!(node(&s, g), before, "the edges keep their rows and their link");
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step");
}
/// Clear Appearance and Reduce to Basic Appearance on the contents of a Live Paint group leave each face with fill
/// rows only and each edge with stroke rows only.
#[test]
fn live_paint_group_contents_clear_and_reduce_keep_each_part_to_its_kind() {
for cmd in ["appearance.clear", "appearance.reduceToBasic"] {
let mut s = session();
let g = live(&mut s);
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff00ff"})).unwrap();
s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap();
// A face and an edge given rows of the other kind through their own ids.
let n = node(&s, g);
let (face, edge) = (vectorcraft_tools::builder::faces(&n)[0].id, vectorcraft_tools::builder::edges(&n)[0].id);
s.execute("appearance.addStroke", &json!({"ids": [face.0]})).unwrap();
s.execute("appearance.addFill", &json!({"ids": [edge.0]})).unwrap();
assert!(!parts_hold_their_kind(&s, g), "{cmd}: the face and the edge hold rows of the other kind");
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
s.execute(cmd, &json!({"target": "contents"})).unwrap();
assert!(parts_hold_their_kind(&s, g), "{cmd}: faces hold fills and edges strokes");
let (faces, edges) = part_looks(&s, g);
assert!(faces.iter().chain(&edges).all(|a| !a.items.is_empty()), "{cmd}: each face and edge keeps a row");
}
}
/// A selected Live Paint group with no part of the edited kind is still a selection: a stroke edit
/// of a group without edges, or a fill gradient edit of a group without faces, changes nothing and
/// leaves the settings for new art as they are.
+47
View File
@@ -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");
+238
View File
@@ -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
+127
View File
@@ -0,0 +1,127 @@
//! Gradient mesh points picked with one of the tools that pick them (the Mesh tool, Direct
//! Selection, the Lasso, the Polygonal Lasso) stay picked when another of them is chosen, or lent
//! for a Cmd-click, so a fill color then recolors just them.
use serde_json::json;
use vectorcraft_color::Color;
use vectorcraft_doc::NodeKind;
use vectorcraft_tools::{Mods, PointerEvent, PointerKind};
use crate::*;
/// A session with a selected 1 x 1 gradient mesh (four white points) at (10, 10), 50 pt square.
fn mesh_session() -> (Session, NodeId) {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
let m = NodeId(s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap());
s.execute("object.mesh.create", &json!({"ids": [m.0], "rows": 1, "cols": 1})).unwrap();
s.execute("select.set", &json!({"ids": [m.0]})).unwrap();
(s, m)
}
fn colors(s: &Session, m: NodeId) -> Vec<Color> {
match &s.doc().unwrap().doc.node(m).unwrap().kind {
NodeKind::Mesh(g) => g.points.iter().map(|p| p.color).collect(),
k => panic!("not a mesh: {k:?}"),
}
}
/// Click mesh point `i` of `m` with the active tool.
fn press(s: &mut Session, m: NodeId, i: usize, mods: Mods) {
let q = match &s.doc().unwrap().doc.node(m).unwrap().kind {
NodeKind::Mesh(g) => g.points[i].p,
k => panic!("not a mesh: {k:?}"),
};
for kind in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(kind, q.x, q.y).with_mods(mods), ViewInfo::default()).unwrap();
}
}
/// A point picked with the Mesh tool stays picked through Direct Selection, the Lasso and the
/// Polygonal Lasso and back to the Mesh tool: each fill color recolors just that point.
#[test]
fn mesh_point_picks_carry_between_the_mesh_point_tools() {
let (mut s, m) = mesh_session();
let v = ViewInfo::default();
let white = colors(&s, m)[0];
s.select_tool("mesh", v).unwrap();
press(&mut s, m, 0, Mods::default());
for (tool, hex, c) in [
("directSelection", "#0000ff", Color::rgb8(0, 0, 255)),
("lasso", "#00ff00", Color::rgb8(0, 255, 0)),
("polygonalLasso", "#ff0000", Color::rgb8(255, 0, 0)),
("directSelection", "#ffff00", Color::rgb8(255, 255, 0)),
("mesh", "#00ffff", Color::rgb8(0, 255, 255)),
] {
s.select_tool(tool, v).unwrap();
s.execute("paint.setFill", &json!({"color": hex})).unwrap();
assert_eq!(colors(&s, m), [c, white, white, white], "{tool} recolors only the picked point");
}
}
/// A point picked with Direct Selection stays picked for the Mesh tool.
#[test]
fn direct_selection_picks_carry_to_the_mesh_tool() {
let (mut s, m) = mesh_session();
let v = ViewInfo::default();
let white = colors(&s, m)[0];
s.select_tool("directSelection", v).unwrap();
press(&mut s, m, 2, Mods::default());
s.select_tool("mesh", v).unwrap();
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
assert_eq!(colors(&s, m), [white, white, Color::rgb8(0, 0, 255), white]);
}
/// The Selection tool picks no mesh points: after it, the Mesh tool starts with none picked, and a
/// fill color leaves every point as it was.
#[test]
fn a_tool_that_picks_no_mesh_points_drops_the_picks() {
let (mut s, m) = mesh_session();
let v = ViewInfo::default();
let before = colors(&s, m);
s.select_tool("mesh", v).unwrap();
press(&mut s, m, 0, Mods::default());
s.select_tool("selection", v).unwrap();
s.execute("select.set", &json!({"ids": [m.0]})).unwrap();
s.select_tool("mesh", v).unwrap();
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
assert_eq!(colors(&s, m), before, "no point is picked");
}
/// A plain Lasso click away from the art deselects it and unpicks the points the Mesh tool picked,
/// so the Mesh tool chosen next has none picked.
#[test]
fn a_lasso_click_that_deselects_unpicks_the_mesh_points() {
let (mut s, m) = mesh_session();
let v = ViewInfo::default();
let before = colors(&s, m);
s.select_tool("mesh", v).unwrap();
press(&mut s, m, 0, Mods::default());
s.select_tool("lasso", v).unwrap();
for kind in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(kind, 500.0, 500.0), v).unwrap();
}
assert!(s.doc().unwrap().selection.objects.is_empty(), "the click deselects the mesh");
s.execute("select.set", &json!({"ids": [m.0]})).unwrap();
s.select_tool("mesh", v).unwrap();
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
assert_eq!(colors(&s, m), before, "no point is picked");
}
/// Direct Selection lent to the Mesh tool for a Cmd-click starts from the Mesh tool's picks, so a
/// Shift-click adds to them, and gives back what it left picked.
#[test]
fn the_lent_direct_selection_carries_the_mesh_tools_picks() {
let (mut s, m) = mesh_session();
let v = ViewInfo::default();
let white = colors(&s, m)[0];
// Cmd lends the selection tool chosen last.
s.select_tool("directSelection", v).unwrap();
s.select_tool("mesh", v).unwrap();
press(&mut s, m, 0, Mods::default());
press(&mut s, m, 3, Mods { cmd: true, shift: true, ..Default::default() });
assert_eq!(s.tool_id(), "mesh");
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
let b = Color::rgb8(0, 0, 255);
assert_eq!(colors(&s, m), [b, white, white, b], "both points stay picked");
}
+42
View File
@@ -514,3 +514,45 @@ fn another_documents_symbol_is_added_and_placed_in_one_step() {
let e = s.execute("symbol.placeFromDocument", &json!({"sourceDocument": source, "name": "Star"})).unwrap_err();
assert!(e.to_string().contains("no longer open"), "{e}");
}
/// A symbol dragged onto the canvas, from another document's Symbols panel or from a symbol
/// library, is stacked as Place Symbol Instance stacks it: in Draw Behind directly below the
/// selected object, or at the bottom of the current layer with nothing selected, in one undo step
/// with the symbol it adds. A locked layer refuses it with no edit.
#[test]
fn dropped_symbols_go_below_the_selection_in_draw_behind() {
let mut s = kit();
let source = s.doc().unwrap().uid;
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
let rect =
|s: &mut Session, x: f64| NodeId(run(s, "shape.rectangle", json!({"x": x, "y": 0, "width": 10, "height": 10}))["id"].as_u64().unwrap());
let (a, b) = (rect(&mut s, 0.0), rect(&mut s, 20.0));
let layer = doc(&s).layers[0].id;
let kids = |s: &Session| doc(s).node(layer).unwrap().children().unwrap().iter().map(|c| c.id).collect::<Vec<_>>();
run(&mut s, "view.drawMode", json!({"mode": "behind"}));
let drops = [
("symbol.placeFromDocument", json!({"sourceDocument": source, "name": "Badge", "x": 30, "y": 40}), "id"),
("symbol.addFromLibrary", json!({"library": "basic shapes", "name": "Square", "place": true, "x": 30, "y": 40}), "placed"),
];
for (cmd, p, key) in &drops {
for (picked, at) in [(vec![b], 1), (vec![], 0)] {
run(&mut s, "select.set", json!({"ids": picked.iter().map(|i| i.0).collect::<Vec<_>>()}));
let before = undo_len(&s);
let placed = NodeId(run(&mut s, cmd, p.clone())[*key].as_u64().unwrap());
let mut want = vec![a, b];
want.insert(at, placed);
assert_eq!(kids(&s), want, "{cmd} {picked:?}");
assert_eq!(undo_len(&s), before + 1, "{cmd}");
assert_eq!(s.doc().unwrap().selection.objects, [placed]);
run(&mut s, "edit.undo", json!({}));
assert!(symbols(&s).is_empty(), "{cmd}: the undo takes the added symbol too");
}
}
// A locked layer takes nothing.
run(&mut s, "layer.setProps", json!({"id": layer.0, "locked": true}));
let before = (undo_len(&s), doc(&s).clone());
for (cmd, p, _) in &drops {
assert!(s.execute(cmd, p).is_err(), "{cmd}");
assert_eq!((undo_len(&s), doc(&s)), (before.0, &before.1), "{cmd}");
}
}
-7
View File
@@ -879,13 +879,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!({})),
(
+24 -12
View File
@@ -186,12 +186,13 @@ impl Session {
let text_selection = ((id == "eyedropper" && is_type(self.tool.id())) || (self.tool.id() == "eyedropper" && is_type(id)))
.then(|| self.tool.options())
.filter(|o| o.get("editing").is_some_and(|v| !v.is_null()) && o.get("start") != o.get("end"));
// The gradient mesh points the Mesh tool, Direct Selection or the Lasso picked stay picked
// for the Eyedropper, which samples into them (#8090), and for the tool after it.
let mesh_points = (id == "eyedropper" || self.tool.id() == "eyedropper")
// The gradient mesh points the Mesh tool, Direct Selection, the Lasso or the Polygonal Lasso
// picked stay picked when another of these tools or the Eyedropper, which samples into
// them (#8090), is chosen: a fill color then recolors just them. None stay picked when
// none were.
let mesh_points = (Self::picks_mesh_points(id) && Self::picks_mesh_points(self.tool.id()))
.then(|| self.tool.options().get("meshPoints").cloned())
.flatten()
.filter(|v| v.as_array().is_some_and(|a| !a.is_empty()));
.flatten();
self.deactivate_tool(view)?;
self.keep_tool_settings();
self.tool = self.make_tool(id);
@@ -208,6 +209,13 @@ impl Session {
Ok(())
}
/// Does tool `id` pick gradient mesh points (its `meshPoints` option): the Mesh tool, Direct
/// Selection, the Lasso, the Polygonal Lasso and the Eyedropper? Group Selection, which
/// selects whole objects, does not.
fn picks_mesh_points(id: &str) -> bool {
matches!(id, "mesh" | "directSelection" | "lasso" | "polygonalLasso" | "eyedropper")
}
/// Deactivate the tool and apply the actions it returns. In a batch, a Cancel is left out: the
/// batch settled the tool's drag when it began, and the open interaction holds the batch's
/// steps, which the batch keeps or rolls back as a whole.
@@ -292,9 +300,9 @@ impl Session {
// double-click or triple-click compares.
self.tool.press_elsewhere();
let mut lent = self.make_tool(id);
// The gradient mesh points the Eyedropper holds are the lent tool's picks, which a Shift
// click adds to (#8090).
if self.tool.id() == "eyedropper" {
// The gradient mesh points the lending tool picked (the Mesh tool's, the Lasso's, the
// Eyedropper's) are the lent tool's picks, which a Shift click adds to (#8090).
if Self::picks_mesh_points(self.tool.id()) && Self::picks_mesh_points(id) {
let points = self.tool.options().get("meshPoints").cloned().unwrap_or_else(|| Value::Array(vec![]));
lent.set_option("meshPoints", &points);
}
@@ -312,10 +320,14 @@ impl Session {
/// Cmd+click that takes the type being edited out of the selection ends its edit (#3779).
pub(crate) fn give_back_tool(&mut self, view: ViewInfo) -> Result<()> {
let Some(lender) = self.lender.take() else { return Ok(()) };
// The points the lent tool left picked go back to the Eyedropper, none when it unpicked
// them all (#8090). Group Selection picks no mesh points, so the Eyedropper keeps its own.
let mesh_points =
(lender.id() == "eyedropper" && self.tool.id() != "groupSelection").then(|| self.tool.options().get("meshPoints").cloned()).flatten();
// The points the lent tool left picked go back to the tool it was lent to when that tool
// picks mesh points, none when it unpicked them all (#8090). Group Selection and the
// Selection tool pick no mesh points, so the tool keeps its own. Unchanged picks are not
// set again, so the Mesh tool keeps the point whose handles it shows.
let mesh_points = (Self::picks_mesh_points(lender.id()) && Self::picks_mesh_points(self.tool.id()))
.then(|| self.tool.options().get("meshPoints").cloned())
.flatten()
.filter(|p| lender.options().get("meshPoints") != Some(p));
let r = self.deactivate_tool(view);
self.keep_tool_settings();
self.tool = lender;