Merge main into fix/library-numbered-tint-names

This commit is contained in:
dotCooCoo committed 2026-11-24 11:36:43 -08:00
commit ec42aea37f
1193 files changed
+171986 -267075

No files matched your search

+6 -1
View File
@@ -94,6 +94,7 @@ pub(crate) mod slices;
pub mod spelling;
mod stroke;
mod style;
pub use style::styled_node;
pub mod stylelib;
mod svgfilter;
mod swatch;
@@ -853,11 +854,15 @@ pub(crate) use object::bounds_rewrite;
pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned};
/// The rules `object.scale`, `object.reflect` and `object.shear` check their params with.
pub use object::{reflect_axis, scale_factors, shear_tangent};
pub(crate) use paint::LIVE_PAINT_BUCKET;
pub(crate) use paint::{LIVE_PAINT_BUCKET, asks_defaults_only};
pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location_keys};
pub use select::SIMILAR;
pub(crate) use vectorcraft_doc::range::parse_range;
/// What the fill and stroke proxies read from the selected objects, kept with the selection
/// ([`crate::doc_state::SelectionRecord`]).
pub(crate) use paint::SelectionPaints;
/// A date param in Unix seconds that defaults to the clock: `None` when absent (now, see
/// [`clock_date`]), `Some(None)` for null (no date), else `Some(Some(seconds))`.
pub(crate) fn date_param(p: &Value, key: &str, cmd: &str) -> Result<Option<Option<i64>>> {
+1 -1
View File
@@ -52,7 +52,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Print Ink Fixes",
["Object", "Plug-ins", "Color Effects"],
None,
"{scope?: \"selection\" (the selection, or `ids`; by default, the document while nothing is selected) | \"document\" (every layer), inkLimit?: total ink % 1..400 (0 or left out: off), excludePureBlack?: true (black-only and grey colours keep their ink), removeWhiteOverprint?: false (white fills and strokes stop overprinting), overprintBlack?: black % 1..100 (black-only and grey fills and strokes this dark or darker overprint, as edit.colors.overprintBlack; 0 or left out: off), textOnly?: false (Overprint Black on type only), fill?: true, stroke?: true, ids?: [id…]} prepare a CMYK document's inks for print as one undo step: CMYK colours (solid, gradient stops, gradient meshes) with more total ink than inkLimit are scaled down to it (colours of spot swatches and Registration stay), white overprint is removed and black overprint set. Refused in RGB documents (File › Document Color Mode › CMYK Color first). On a path directly in a graph series, the graph also stores a paint the ink limit changes on the topmost visible fill or stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, inkLimited: paints and meshes scaled, whiteOverprintRemoved: objects, blackOverprinted: objects}",
"{scope?: \"selection\" (the selection, or `ids`; by default, the document while nothing is selected) | \"document\" (every layer), inkLimit?: total ink % 1..400 (0 or left out: off), excludePureBlack?: true (black-only and grey colours keep their ink), removeWhiteOverprint?: false (white fills and strokes, and colorized images with a white color, stop overprinting), overprintBlack?: black % 1..100 (black-only and grey fills and strokes this dark or darker overprint, as edit.colors.overprintBlack; 0 or left out: off), textOnly?: false (Overprint Black on type only), fill?: true, stroke?: true, ids?: [id…]} prepare a CMYK document's inks for print as one undo step: CMYK colours (solid, gradient stops, gradient meshes) with more total ink than inkLimit are scaled down to it (colours of spot swatches and Registration stay), white overprint is removed and black overprint set. Refused in RGB documents (File › Document Color Mode › CMYK Color first). On a path directly in a graph series, the graph also stores a paint the ink limit changes on the topmost visible fill or stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, inkLimited: paints and meshes scaled, whiteOverprintRemoved: objects, blackOverprinted: objects}",
has_doc,
print_fixes::run
),
@@ -98,6 +98,11 @@ impl Fixes {
off(self.stroke, is_white(&r.style.stroke), &mut r.style.overprint_stroke);
}
}
// A colorized image's color is its fill.
if n.colorize_overprints() {
let white = n.extras().colorize.as_deref().is_some_and(is_white);
off(self.fill, white, &mut n.extras_mut().colorize_overprint);
}
changed
}
@@ -409,7 +409,8 @@ fn a_mask_that_hides_nothing_keeps_the_link() {
#[test]
fn color_mask_refuses_previews_and_images_too_large() {
let preview = std::sync::Arc::new(framed());
let (mut s, id) = linked("missing", ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview) });
let (mut s, id) =
linked("missing", ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview), file_font: Default::default() });
let e = s.execute(COLOR_MASK, &hide_white()).unwrap_err().to_string();
assert!(e.contains(COLOR_MASK) && e.contains("the linked image shows its preview: embed or relink it first"), "{e}");
assert_eq!(mask_of(doc(&s), id), None);
+6 -1
View File
@@ -525,7 +525,12 @@ fn a_linked_image_is_embedded_and_one_that_shows_its_preview_is_refused() {
assert_eq!(im.placement, clip, "its Placement Options kept, as Embed keeps them");
// Pixels the file wasn't read for: the preview, as an image whose file is missing shows it.
let preview = Arc::new(bytes);
let missing = place_linked(&mut s, "missing", ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview) }, (12, 10));
let missing = place_linked(
&mut s,
"missing",
ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview), file_font: Default::default() },
(12, 10),
);
let before = (image_of(&s, missing), undo_len(&s));
let e = s.execute(C, &json!({})).unwrap_err();
assert!(e.to_string().contains("the linked image shows its preview: embed or relink it first"), "{e}");
+1 -1
View File
@@ -135,7 +135,7 @@ impl Session {
/// Whether `name` is a built-in preset's, "Custom" (changed settings, as the panel and a traced
/// object show them), or a saved preset's other than the one at `except`.
fn trace_preset_taken(&self, name: &str, except: Option<usize>) -> bool {
pub fn trace_preset_taken(&self, name: &str, except: Option<usize>) -> bool {
tr::preset(name).is_some() || name.trim().eq_ignore_ascii_case("Custom") || self.trace_preset_index(name).is_some_and(|i| Some(i) != except)
}
+17 -2
View File
@@ -160,6 +160,10 @@ fn node_refs(n: &Node, f: Visit) {
for s in t.para_styles().filter_map(|pa| pa.style_name.as_ref()) {
f(Ref::Name(Res::ParaStyle, s));
}
// The fonts its file carried travel with it, as images do.
for ff in t.file_fonts.iter().flat_map(|ff| &ff.fonts) {
f(Ref::Name(Res::Image, &ff.key));
}
}
NodeKind::Image(im) => f(Ref::Name(Res::Image, &im.key)),
NodeKind::PlacedDocument(pl) => f(Ref::Name(Res::Image, &pl.key)),
@@ -817,6 +821,9 @@ impl Relink {
if relaid {
refresh_bounds(t);
}
if let Some(fonts) = &mut t.file_fonts {
fonts.map_keys(|key| self.name(Res::Image, key));
}
}
NodeKind::Image(im) => self.name(Res::Image, &mut im.key),
NodeKind::PlacedDocument(pl) => self.name(Res::Image, &mut pl.key),
@@ -1144,6 +1151,8 @@ pub(crate) struct Imported {
/// `{kind, from, to}` for every resource the pasted objects now know under another name: added
/// renamed, or a copy added renamed by an earlier paste.
pub renamed: Vec<Value>,
/// File-font resources refused while binding pasted type.
pub warnings: Vec<String>,
/// The graph designs the pasted graphs draw with that the document has under the same name
/// and that would draw them otherwise than the art they were pasted with: the document keeps
/// its own, and the pasted graphs are drawn again with it.
@@ -1171,13 +1180,18 @@ impl Imported {
}
}
/// Point a pasted copy at the document's resources. A pie's legend labels in wedges that now show a color of the
/// other darkness take the contrast a redraw sets there.
pub(crate) fn apply(&self, n: &mut Node) {
/// other darkness take the contrast a redraw sets there. Fonts the copy carries are bound to the faces `d` holds.
pub(crate) fn apply(&mut self, n: &mut Node, d: &Document) {
if self.relinks {
let shades = super::super::graph::wedge_shades(n);
self.relink.node(n);
super::super::graph::follow_wedge_shades(n, &shades);
}
for note in vectorcraft_text::FontDb::global().bind_node_file_fonts(n, &|key| d.images.get(key)) {
if !self.warnings.contains(&note) {
self.warnings.push(note);
}
}
}
}
@@ -1505,6 +1519,7 @@ impl Clipboard {
&& out.relink.colors.is_empty()
&& out.relink.kinsoku.is_empty()
&& used.styles.is_empty());
out.warnings.extend(vectorcraft_text::FontDb::global().bind_document_file_fonts(d));
Ok(out)
}
+4 -4
View File
@@ -13,7 +13,7 @@ use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::cms::Model;
use vectorcraft_color::harmony::{Guide, GuideOptions, Harmony, Variation};
use vectorcraft_color::harmony::{self, Guide, GuideOptions, Harmony};
use vectorcraft_color::{Color, Paint, keep_model};
use vectorcraft_doc::live::lerp_color;
use vectorcraft_doc::pattern::PatternDef;
@@ -962,8 +962,8 @@ fn harmony(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "color.harmony";
let base = p.get("color").and_then(color_value).ok_or_else(|| bad(C, "missing or invalid `color`"))?;
let rule = text_param(p, "rule", C)?.ok_or_else(|| bad(C, "missing `rule`"))?;
let rule = Harmony::parse(rule).ok_or_else(|| {
let ids: Vec<String> = Harmony::ALL.iter().map(|h| h.id()).collect();
let rule = harmony::parse(rule).ok_or_else(|| {
let ids: Vec<&str> = Harmony::ALL.iter().map(|h| h.id()).collect();
bad(C, format!("unknown rule `{rule}` ({})", ids.join("|")))
})?;
check_numbers(p, &["steps", "amount"], C)?;
@@ -972,7 +972,7 @@ fn harmony(s: &mut Session, p: &Value) -> Result<Value> {
opts.steps = n.min(u32::MAX as u64) as u32;
}
if let Some(v) = text_param(p, "variation", C)? {
opts.variation = Variation::parse(v).ok_or_else(|| bad(C, format!("unknown variation `{v}` (tintsShades|warmCool|vividMuted)")))?;
opts.variation = harmony::parse_variation(v).ok_or_else(|| bad(C, format!("unknown variation `{v}` (tintsShades|warmCool|vividMuted)")))?;
}
if let Some(a) = p.get("amount").and_then(Value::as_f64) {
opts.amount = a as f32;
+1 -1
View File
@@ -169,7 +169,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Overprint Black…",
["Edit", "Edit Colors"],
None,
"{remove?: false, percentage?: 100, fill?: true, stroke?: true, includeCmyBlacks?: false, includeSpotBlacks?: false, ids?} make the black fills and/or strokes of the selection (or ids; groups: their contents; type: its characters) overprint, or stop (remove). Black: K ≥ percentage with no C, M or Y (any with includeCmyBlacks), not linked to a spot swatch (unless includeSpotBlacks); a gradient is black when every stop is → {changed: objects}",
"{remove?: false, percentage?: 100, fill?: true, stroke?: true, includeCmyBlacks?: false, includeSpotBlacks?: false, ids?} make the black fills and/or strokes of the selection (or ids; groups: their contents; type: its characters; a grayscale or 1-bit image colorized by paint.setFill: its color, as a fill) overprint, or stop (remove). Black: K ≥ percentage with no C, M or Y (any with includeCmyBlacks), not linked to a spot swatch (unless includeSpotBlacks); a gradient is black when every stop is → {changed: objects}",
has_doc,
super::overprint::overprint_black
),
@@ -26,6 +26,7 @@ pub const MAX_FILE: usize = 64 << 10;
/// The most setups `view.proofSetup.list` lists.
pub const MAX_LISTED: usize = 100;
/// The most folder entries `view.proofSetup.list` looks at, setup files or not.
#[cfg(not(target_arch = "wasm32"))]
const MAX_SCANNED: usize = 100_000;
/// The longest `name`, in characters.
const MAX_NAME: usize = 100;
+4 -4
View File
@@ -5,7 +5,7 @@
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use vectorcraft_color::Color;
use vectorcraft_color::harmony::{Harmony, THEME_SIZE};
use vectorcraft_color::harmony::{self, THEME_SIZE};
use vectorcraft_color::recolor::ColorKey;
use vectorcraft_tools::params::color_json;
@@ -98,7 +98,7 @@ fn next_name(s: &Session) -> String {
fn save(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "colorTheme.save";
let rule = match str_param(p, "rule") {
Some(r) => Some(Harmony::parse(r).ok_or_else(|| bad(C, format!("unknown rule `{r}` (see color.harmony)")))?),
Some(r) => Some(harmony::parse(r).ok_or_else(|| bad(C, format!("unknown rule `{r}` (see color.harmony)")))?),
None => None,
};
let colors: Vec<Color> = match (p.get("colors"), p.get("color")) {
@@ -107,7 +107,7 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
}
(None, Some(c)) => {
let base = color_value(c).ok_or_else(|| bad(C, "invalid `color`"))?;
rule.ok_or_else(|| bad(C, "`color` needs a `rule` to make the theme from"))?.theme(base)
harmony::theme(rule.ok_or_else(|| bad(C, "`color` needs a `rule` to make the theme from"))?, base)
}
_ => return Err(bad(C, "give `colors`, or `color` and `rule`")),
};
@@ -123,7 +123,7 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
if s.prefs.color_themes.iter().enumerate().any(|(i, t)| Some(i) != replace && t.name.eq_ignore_ascii_case(&name)) {
return Err(bad(C, format!("a theme is already called {name} (replace: \"{name}\" overwrites it)")));
}
let theme = ColorTheme { name: name.clone(), colors, rule: rule.map(Harmony::id) };
let theme = ColorTheme { name: name.clone(), colors, rule: rule.map(|h| h.id().to_owned()) };
match replace {
Some(i) => s.prefs.color_themes[i] = theme,
None => s.prefs.color_themes.push(theme),
+20 -9
View File
@@ -23,6 +23,9 @@ use super::{CommandSpec, Result, Session, bad, cmd, has_doc, switch_or, text_par
/// The extension of the files Export writes and Import reads.
pub const EXTS: &[&str] = &["vccomposite"];
/// The id of the export command.
const EXPORT: &str = "type.compositeFonts.export";
/// The largest file Import reads, in bytes.
const MAX_FILE_BYTES: usize = 4 << 20;
@@ -271,7 +274,7 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
}
fn export(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "type.compositeFonts.export";
const C: &str = EXPORT;
let path = text_param(p, "path", C)?;
if path.is_some_and(|p| p.trim().is_empty()) {
return Err(bad(C, "path is empty"));
@@ -306,21 +309,29 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
if fonts.is_empty() {
return Err(bad(C, "no composite fonts to export"));
}
let mut file = Map::new();
file.insert("compositeFonts".into(), json!(fonts));
let text = serde_json::to_string_pretty(&file).map_err(|e| bad(C, e.to_string()))?;
if text.len() > MAX_FILE_BYTES {
return Err(bad(C, "the composite fonts make a file larger than 4 MB, which Import can't read; export fewer of them"));
}
let bytes = file_bytes(&fonts)?;
match path {
Some(path) => {
write_file(path, text.as_bytes())?;
write_file(path, &bytes)?;
Ok(json!({ "path": path, "count": fonts.len() }))
}
None => Ok(json!({ "data": text, "count": fonts.len() })),
// The bytes are UTF-8 JSON text, so the lossy conversion changes nothing.
None => Ok(json!({ "data": String::from_utf8_lossy(&bytes), "count": fonts.len() })),
}
}
/// The bytes of an export file holding `fonts`: what [`import`] reads. Refused when they would make a
/// file larger than Import reads.
pub fn file_bytes(fonts: &[CompositeFont]) -> Result<Vec<u8>> {
let mut file = Map::new();
file.insert("compositeFonts".into(), json!(fonts));
let text = serde_json::to_string_pretty(&file).map_err(|e| bad(EXPORT, e.to_string()))?;
if text.len() > MAX_FILE_BYTES {
return Err(bad(EXPORT, "the composite fonts make a file larger than 4 MB, which Import can't read; export fewer of them"));
}
Ok(text.into_bytes())
}
/// The composite fonts in the bytes of an exported file.
fn read_fonts(bytes: &[u8], c: &str) -> Result<Vec<CompositeFont>> {
let v: Value = serde_json::from_slice(bytes).map_err(|e| bad(c, format!("not a composite fonts file: {e}")))?;
+27 -6
View File
@@ -14,7 +14,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Create Dimension",
[],
None,
"{mode?: linear|angular|radius|diameter, a?: [x,y], b?: [x,y], vertex?: [x,y], source?: {kind: segment, edge: {node,subpath,segment}}|{kind: angle, first: edge, second: edge}|{kind: circle, node}|{kind: arc, edge}|{kind: points, a?, b?, vertex?: {node,subpath,anchor}, freeA?, freeB?: a point that is not an anchor, {kind: onSegment, edge: {node,subpath,segment}, t: 0..1 (curve parameter)}|{kind: anchors, node, anchors: [{subpath,anchor,part?: point|in|out (the anchor, default, or its in or out handle),weight}] (2 or 3 points of one path whose weights add up to 1), across?: (2 anchors only: times the first-to-second anchor vector (x,y) turned to (-y,x), which points down when the vector points right)} (an end is an anchor or a free point, not both)}, orientation?: aligned|horizontal|vertical (linear only: the distance between the points, or only its horizontal or vertical part; default aligned), offset?: pt (the line's distance from the first point: along the left normal of a → b when aligned, downward when horizontal, leftward when vertical; negative goes the other way), options?: {units: in|mm|pt|pc|px|cm|m|ft|yd, precision: 0-6, scale: drawing:real, hideUnits, lineWeight, lineType: solid|dashed|dotted, lineColor: [r,g,b], arrowStyle: filled|open|tick|none, arrowHead: null|a built-in stroke.set arrowhead name (Barbed, LineArrow…; drawn at both ends in place of arrowStyle's head; versions that have the stroke arrowhead but do not read arrowHead draw arrowStyle when they draw the dimension again; custom arrowheads are refused), arrowScale: %, extensionWeight, extensionType, extensionColor, extensionOffset, extensionLength, hideExtensions, fontFamily, fontStyle, fontSize, textColor, textPosition: away|between, textAlignment: left|center|right, textOffset}} → {id,label}; linked measurements follow source edits",
"{mode?: linear|angular|radius|diameter, a?: [x,y], b?: [x,y], vertex?: [x,y], source?: {kind: segment, edge: {node,subpath,segment}}|{kind: angle, first: edge, second: edge}|{kind: circle, node}|{kind: arc, edge}|{kind: extent, node} (linear only: a whole path between its outermost points, leftmost and rightmost when horizontal or aligned, topmost and bottommost when vertical)|{kind: points, a?, b?, vertex?: {node,subpath,anchor}, freeA?, freeB?: a point that is not an anchor, {kind: onSegment, edge: {node,subpath,segment}, t: 0..1 (curve parameter)}|{kind: anchors, node, anchors: [{subpath,anchor,part?: point|in|out (the anchor, default, or its in or out handle),weight}] (2 or 3 points of one path whose weights add up to 1), across?: (2 anchors only: times the first-to-second anchor vector (x,y) turned to (-y,x), which points down when the vector points right)} (an end is an anchor or a free point, not both)}, orientation?: aligned|horizontal|vertical (linear only: the distance between the points, or only its horizontal or vertical part; default aligned), offset?: pt (the line's distance from the first point: along the left normal of a → b when aligned, downward when horizontal, leftward when vertical; negative goes the other way), options?: {units: in|mm|pt|pc|px|cm|m|ft|yd, precision: 0-6, scale: drawing:real, hideUnits, lineWeight, lineType: solid|dashed|dotted, lineColor: [r,g,b], arrowStyle: filled|open|tick|none, arrowHead: null|a built-in stroke.set arrowhead name (Barbed, LineArrow…; drawn at both ends in place of arrowStyle's head; versions that have the stroke arrowhead but do not read arrowHead draw arrowStyle when they draw the dimension again; custom arrowheads are refused), arrowScale: %, extensionWeight, extensionType, extensionColor, extensionOffset, extensionLength, hideExtensions, fontFamily, fontStyle, fontSize, textColor, textPosition: away|between, textAlignment: left|center|right, textOffset}} → {id,label}; linked measurements follow source edits",
has_doc,
create
),
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Update Dimensions",
[],
None,
"{ids?: [dimension ids] (default selection), options?: dimension options, orientation?: aligned|horizontal|vertical (linear dimensions only; the line stays on the side of the points it was on), offset?: pt (as in dimension.create)} restyle, turn or move existing dimensions → {ids}",
"{ids?: [dimension ids] (default selection), options?: dimension options, orientation?: aligned|horizontal|vertical (linear dimensions only; the line stays on the side of the points it was on; for an extent source, an error when that would put the line more than 1,000,000 pt from its first point and no offset is given), offset?: pt (as in dimension.create), at?: [x,y] (after offset: puts a linear dimension's line through this point, gives an angular dimension's arc a radius of the point's distance from the vertex, at least 12 pt, or turns a radius or diameter line toward it; what the dimension measures does not change)} restyle, turn or move existing dimensions → {ids}",
has_doc,
update
),
@@ -80,6 +80,7 @@ fn recipe(s: &Session, p: &Value) -> Result<Dimension> {
| (DimensionMode::Angular, DimensionSource::Angle { .. })
| (DimensionMode::Radius | DimensionMode::Diameter, DimensionSource::Circle { .. } | DimensionSource::Arc { .. })
| (DimensionMode::Linear | DimensionMode::Angular, DimensionSource::Points { .. })
| (DimensionMode::Linear, DimensionSource::Extent { .. })
);
if !compatible {
return Err(error("Dimension mode does not match its source"));
@@ -159,6 +160,7 @@ fn update(s: &mut Session, p: &Value) -> Result<Value> {
return Err(error("Select dimensions to update"));
}
let o = if p.get("options").is_some() { Some(options(s, p)?) } else { None };
let at = if p.get("at").is_some() { Some(point(p, "at")?) } else { None };
// Every dimension is checked before anything changes, and an update that changes none of
// them records no undo step.
let mut next = Vec::with_capacity(ids.len());
@@ -174,10 +176,21 @@ fn update(s: &mut Session, p: &Value) -> Result<Value> {
dim.options = o.clone();
}
if let Some(orientation) = orientation(p, dim.mode)? {
dim.set_orientation(orientation);
// An offset given with the orientation replaces the one the orientation would
// give: the dimension takes the orientation, and `resolve` reads its points.
if let Err(e) = dim.set_orientation(orientation, doc) {
if p.get("offset").is_none() {
return Err(error(e));
}
dim.orientation = orientation;
}
}
dim.offset = distance(p, dim.offset)?;
dim.resolve(doc).map_err(error)?;
if let Some(at) = at {
dim.place(at);
dim.resolve(doc).map_err(error)?;
}
if dim != old {
next.push((*id, dim));
}
@@ -452,7 +465,14 @@ pub(crate) fn refresh(before: &Document, doc: &mut Document) -> Result<bool> {
for (id, old) in dimensions {
let mut next = old.clone();
let moved = next.moved.take();
if next.source.as_ref().is_some_and(|s| s.topology_changed(before, doc)) || next.resolve(doc).is_err() {
// Whether the path a dimension of a whole path measures changed: when it did not, the
// dimension keeps its points without reading the path again, and is only checked.
let whole_changed = match &next.source {
Some(s @ DimensionSource::Extent { .. }) => Some(s.art_changed(before, doc)),
_ => None,
};
let unreadable = if whole_changed == Some(false) { next.validate().is_err() } else { next.resolve(doc).is_err() };
if next.source.as_ref().is_some_and(|s| s.topology_changed(before, doc)) || unreadable {
// The art it measured was deleted, or rebuilt with other anchors, or no longer fits
// (an ellipse that was a circle): it stays where it was, no longer linked, in this
// same undo step, rather than attaching to a different edge.
@@ -465,13 +485,14 @@ pub(crate) fn refresh(before: &Document, doc: &mut Document) -> Result<bool> {
changed = true;
continue;
}
next.keep_gap(&old);
next.keep_gap(&old, (whole_changed == Some(true)).then_some((before, doc)));
if let Some(xf) = next.source.as_ref().and_then(|s| s.reflection(before, doc)) {
next.mirror_line(&old, xf * old.handle());
next.mirror_line(&old, xf * old.handle(), Some((before, doc)));
}
// Moved on its own (the art it measures stayed put): it keeps its new place.
if let Some(v) = moved
&& (next.a, next.b, next.vertex) == (old.a, old.b, old.vertex)
&& whole_changed != Some(true)
{
next.place(old.handle() + v);
if next.resolve(doc).is_err() {
+1 -1
View File
@@ -17,7 +17,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Document Setup",
[],
None,
"{units?: \"Points\"|\"Inches\"|\"Millimeters\"|…, bleed?: pt (all sides)|[top, bottom, left, right]|{top?, bottom?, left?, right?} (0–72 pt), outlineImages?: bool (show images in Outline mode), highlightSubstitutedGlyphs?: bool (Highlight Substituted Fonts is a preference: prefs.set highlightSubstitutedFonts; a highlightSubstitutedFonts key is ignored and the reply carries a warning),gridSize?: \"small\"|\"medium\"|\"large\", gridColors?: \"Light\"|\"Medium\"|\"Dark\"|\"Red\"|\"Orange\"|\"Green\"|\"Blue\"|\"Purple\"|[colour, colour] (transparency grid; the first is also the paper colour; #rrggbbaa and #rgba are refused), simulatePaper?: bool, flattenerPreset?: \"High Resolution\"|\"Medium Resolution\"|\"Low Resolution\"|a saved preset (flattener.presets.list), discardWhiteOverprint?: bool, language?: \"English: USA\"|\"German\"|\"French\"|… (also picks its quotes), quotes?: {double?: \"“”\", single?: \"‘’\"} (beside a language: only if they differ from the current ones), typographersQuotes?: bool (typed straight quotes become the document's quotes), superscript?: {size?: %, position?: %}, subscript?: {size?: %, position?: %}, smallCapsSize?: %, exportText?: \"editable\"|\"appearance\" (SVG text as text or as outlines), backgroundContents?: \"transparent\"|\"white\" (white: raster exports are white behind the art), alignNewObjectsToPixelGrid?: bool (Align New Objects to Pixel Grid: paths and compound paths drawn from then on are pixel-aligned, as object.setPixelAligned; art already in the document, pasted, duplicated or placed keeps its own setting), …the keys of its own reply (it can be passed back; the values it only reports are ignored)} change the document setup in one undo step; no params → the current setup",
"{units?: \"Points\"|\"Inches\"|\"Millimeters\"|…, bleed?: pt (all sides)|[top, bottom, left, right]|{top?, bottom?, left?, right?} (0–72 pt), outlineImages?: bool (show images in Outline mode; off: a linked image or placed document shows its box crossed from corner to corner), highlightSubstitutedGlyphs?: bool (Highlight Substituted Fonts is a preference: prefs.set highlightSubstitutedFonts; a highlightSubstitutedFonts key is ignored and the reply carries a warning),gridSize?: \"small\"|\"medium\"|\"large\", gridColors?: \"Light\"|\"Medium\"|\"Dark\"|\"Red\"|\"Orange\"|\"Green\"|\"Blue\"|\"Purple\"|[colour, colour] (transparency grid; the first is also the paper colour; #rrggbbaa and #rgba are refused), simulatePaper?: bool, flattenerPreset?: \"High Resolution\"|\"Medium Resolution\"|\"Low Resolution\"|a saved preset (flattener.presets.list), discardWhiteOverprint?: bool, language?: \"English: USA\"|\"German\"|\"French\"|… (also picks its quotes), quotes?: {double?: \"“”\", single?: \"‘’\"} (beside a language: only if they differ from the current ones), typographersQuotes?: bool (typed straight quotes become the document's quotes), superscript?: {size?: %, position?: %}, subscript?: {size?: %, position?: %}, smallCapsSize?: %, exportText?: \"editable\"|\"appearance\" (SVG text as text or as outlines), backgroundContents?: \"transparent\"|\"white\" (white: raster exports are white behind the art), alignNewObjectsToPixelGrid?: bool (Align New Objects to Pixel Grid: paths and compound paths drawn from then on are pixel-aligned, as object.setPixelAligned; art already in the document, pasted, duplicated or placed keeps its own setting), …the keys of its own reply (it can be passed back; the values it only reports are ignored)} change the document setup in one undo step; no params → the current setup",
has_doc,
setup
)]
+2 -2
View File
@@ -120,7 +120,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Smooth",
[],
None,
"{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the smoothing), radius?: pt (12), fidelity?: pt (2.5; kept within 0.000078125 and about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom)} smooth selected paths near the drag, keeping a corner where the path turns by more than 57.5° at the anchor and over radius and twice radius on either side → {ids, before, after}",
"{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the smoothing), radius?: pt (12; from 0.001 to 1000), fidelity?: pt (2.5; from 0.000078125 to about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom, kept within the range)} smooth selected paths near the drag, keeping a corner where the path turns by more than 57.5° at the anchor and over radius and twice radius on either side, and leaving a subpath as it is when the result would not be smoother (docs/mcp.md) → {ids, before, after}. A radius or fidelity outside its range is refused with an error, and nothing changes",
has_selection,
smooth_region
),
@@ -129,7 +129,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Join",
[],
None,
"{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the join), tolerance?: pt (12)} join the open-path endpoints scrubbed over, or trim two crossing open paths whose overhanging ends are scrubbed and join them at the crossing → {id}",
"{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the join), tolerance?: pt (12; from 0.001 to 1000)} join the open-path endpoints scrubbed over, or trim two crossing open paths whose overhanging ends are scrubbed and join them at the crossing → {id}. A tolerance outside 0.001 to 1000 is refused with an error, and nothing changes",
has_doc,
join_scrub
),
+455 -108
View File
@@ -1,9 +1,12 @@
use vectorcraft_pathops::addons::pathtools as pt;
use std::collections::HashMap;
use super::common::{dist_to_polyline, ids_json, path_mut, path_of, points_param, poly_bounds, subpath_len, target_paths};
use vectorcraft_pathops::addons::pathtools as pt;
use vectorcraft_pathops::start_nearest;
use super::common::{dist_to_polyline, ids_json, path_mut, path_of, points_param, poly_bounds, ranged, subpath_len, target_paths};
use super::{
Anchor, BezPath, CubicBez, NodeId, ParamCurve, ParamCurveNearest, PathData, Point, Rect, Result, Session, SimplifyOptions, SubPath, Value, json,
number_or, po,
Anchor, BezPath, CubicBez, NodeId, ParamCurve, ParamCurveNearest, PathData, Point, Rect, Result, Session, SimplifyOptions, SubPath, Value, bad,
json, number_or, po,
};
// ---------- Smooth ----------
@@ -323,84 +326,6 @@ fn refit_run(anchors: &[Anchor], tol: f64, sigma: f64, free: [bool; 2]) -> Vec<A
out.into_vec()
}
/// Distance (points) from an anchor within which a smoothed closed path starts at that anchor
/// instead of at a new one split in beside it.
const START_SNAP: f64 = 1e-3;
/// Distance (points) within which two points of a smoothed closed path count as equally near its
/// old start.
const START_TIE: f64 = 1e-6;
/// Where `p` lies along the closed `orig` from its first anchor: the segment index and parameter of
/// the point of `orig` nearest `p`, the first such point in its order. Sorts after every finite place
/// when there is none.
fn place_along(orig: &SubPath, p: Point) -> (usize, f64) {
let mut best: Option<(f64, usize, f64)> = None;
for j in 0..orig.anchors.len() {
let hit = orig.segment(j).nearest(p, 1e-9);
if hit.distance_sq.is_finite() && hit.t.is_finite() && best.is_none_or(|(d, ..)| hit.distance_sq < d) {
best = Some((hit.distance_sq, j, hit.t));
}
}
best.map_or((usize::MAX, f64::INFINITY), |(_, j, t)| (j, t))
}
/// The closed `sp` started at the point on it nearest `start`: at the anchor there, or at a new
/// anchor split into the segment there, which leaves the outline as it is. Of points equally near
/// `start`, the one earliest along `orig` (the path before smoothing) from its first anchor is used,
/// then the first in `sp`'s order. An open `sp`, or one with no segment or no finite nearest point,
/// is returned as it is.
fn start_nearest(mut sp: SubPath, start: Point, orig: &SubPath) -> SubPath {
let n = sp.anchors.len();
if !sp.closed || n < 2 {
return sp;
}
// (distance, place along `orig` once a tie needs it, segment of `sp`, parameter)
type Best = (f64, Option<(usize, f64)>, usize, f64);
let mut best: Option<Best> = None;
for i in 0..n {
let c = sp.segment(i);
let hit = c.nearest(start, 1e-9);
if !hit.distance_sq.is_finite() || !hit.t.is_finite() {
continue;
}
let d = hit.distance_sq.sqrt();
match &mut best {
None => best = Some((d, None, i, hit.t)),
Some((bd, bplace, bi, bt)) if (d - *bd).abs() <= START_TIE => {
let held = *bplace.get_or_insert_with(|| place_along(orig, sp.segment(*bi).eval(*bt)));
let place = place_along(orig, c.eval(hit.t));
if place.0 < held.0 || (place.0 == held.0 && place.1 < held.1) {
best = Some((d, Some(place), i, hit.t));
}
}
Some((bd, ..)) if d < *bd => best = Some((d, None, i, hit.t)),
Some(_) => {}
}
}
let Some((_, _, i, t)) = best else { return sp };
let c = sp.segment(i);
let at = c.eval(t);
let first = if at.distance(c.p0) <= START_SNAP {
i
} else if at.distance(c.p3) <= START_SNAP {
(i + 1) % n
} else {
let mid = if sp.segment_is_line(i) {
Anchor::corner(at)
} else {
let (l, r) = (c.subsegment(0.0..t), c.subsegment(t..1.0));
sp.anchors[i].h_out = l.p1;
sp.anchors[(i + 1) % n].h_in = r.p2;
Anchor::with_handles(at, l.p2, r.p1)
};
sp.anchors.insert(i + 1, mid);
i + 1
};
sp.anchors.rotate_left(first);
sp
}
/// Pieces of curve that one Smooth drag measures against the drag while it searches the segments
/// under it ([`reach_samples`]), shared equally by the curved segments that come within its reach,
/// each of which gets at least one: enough to search 300,000 pt of curve within the default reach
@@ -421,6 +346,8 @@ fn drag_stretches(pts: &[Point]) -> Vec<usize> {
/// The stretches of the drag `pts` among `of` whose bounds come within `radius` of `r` on both
/// axes: every stretch within `radius` of a point in `r`, and perhaps a few more.
fn stretches_near(pts: &[Point], of: &[usize], r: Rect, radius: f64) -> Vec<usize> {
#[cfg(test)]
STRETCH_TESTS.with(|c| c.set(c.get() + of.len()));
let r = r.inflate(radius, radius);
of.iter()
.copied()
@@ -432,8 +359,115 @@ fn stretches_near(pts: &[Point], of: &[usize], r: Rect, radius: f64) -> Vec<usiz
.collect()
}
#[cfg(test)]
thread_local! {
/// Tests: how many times this thread measured a point or a box against one stretch of a drag.
static STRETCH_TESTS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Most grid cells [`DragReach`] lists one stretch of the drag in. A stretch whose reach covers more
/// is measured against every point and box instead.
const MAX_STRETCH_CELLS: usize = 64;
/// Most grid cells across the drag's bounds on each axis in [`DragReach`].
const MAX_DRAG_CELLS: f64 = 1024.0;
/// The stretches of a Smooth drag listed by the cells of a grid that their reach covers, so that a
/// point or a piece of path is measured only against the stretches whose reach it is in. Each query
/// gives at least every stretch that measuring against the whole drag finds in reach, so the results
/// are the same as measuring against the whole drag.
struct DragReach<'a> {
pts: &'a [Point],
radius: f64,
/// Every stretch of the drag, in order.
all: Vec<usize>,
/// The drag's bounds grown by more than `radius`, with the cell size; `None` when the drag or
/// the reach is not a finite number, and then every query gives every stretch.
grid: Option<(Rect, f64)>,
cells: HashMap<(i64, i64), Vec<usize>>,
/// The stretches whose reach covers more than [`MAX_STRETCH_CELLS`] cells.
wide: Vec<usize>,
}
impl<'a> DragReach<'a> {
fn new(pts: &'a [Point], radius: f64) -> Self {
let all = drag_stretches(pts);
let mut reach = DragReach { pts, radius, all, grid: None, cells: HashMap::new(), wide: vec![] };
if pts.is_empty() || !radius.is_finite() || pts.iter().any(|p| !p.x.is_finite() || !p.y.is_finite()) {
return reach;
}
// Enough more than the reach to cover the rounding of each distance and box measured.
let size = pts.iter().fold(0.0_f64, |m, p| m.max(p.x.abs()).max(p.y.abs()));
let pad = radius + 1e-6 * radius.max(1.0) + 1e-9 * size;
let area = poly_bounds(pts, pad);
let cell = pad.max(area.width().max(area.height()) / MAX_DRAG_CELLS);
if !(cell.is_finite() && cell > 0.0 && area.width().is_finite() && area.height().is_finite()) {
return reach;
}
reach.grid = Some((area, cell));
for &k in &reach.all {
let Some(&a) = pts.get(k) else { continue };
let b = pts.get(k + 1).copied().unwrap_or(a);
let r = Rect::from_points(a, b).inflate(pad, pad);
let ((x0, y0), (x1, y1)) = (reach.cell_of(Point::new(r.x0, r.y0)), reach.cell_of(Point::new(r.x1, r.y1)));
if (x1 - x0 + 1).saturating_mul(y1 - y0 + 1) > MAX_STRETCH_CELLS as i64 {
reach.wide.push(k);
continue;
}
for x in x0..=x1 {
for y in y0..=y1 {
reach.cells.entry((x, y)).or_default().push(k);
}
}
}
reach
}
/// The cell `q` is in, counted from the corner of the grid.
fn cell_of(&self, q: Point) -> (i64, i64) {
let Some((area, cell)) = self.grid else { return (0, 0) };
(((q.x - area.x0) / cell).floor() as i64, ((q.y - area.y0) / cell).floor() as i64)
}
/// Whether `q` is within the reach of the drag, and `slack` more.
fn in_reach(&self, q: Point, slack: f64) -> bool {
let limit = self.radius + slack;
let Some((area, _)) = self.grid else { return dist_to_stretches(self.pts, &self.all, q) <= limit };
if !(q.x >= area.x0 && q.x <= area.x1 && q.y >= area.y0 && q.y <= area.y1) {
return false;
}
let listed = self.cells.get(&self.cell_of(q)).map_or(&[][..], Vec::as_slice);
dist_to_stretches(self.pts, listed, q).min(dist_to_stretches(self.pts, &self.wide, q)) <= limit
}
/// The stretches, in order, that may come within the reach of `r`: at least every one that
/// [`stretches_near`] gives for `r` from the whole drag.
fn near_rect(&self, r: Rect) -> Vec<usize> {
let Some((area, _)) = self.grid else { return self.all.clone() };
let (x0, x1, y0, y1) = (r.x0.max(area.x0), r.x1.min(area.x1), r.y0.max(area.y0), r.y1.min(area.y1));
if !(x0 <= x1 && y0 <= y1) {
return vec![];
}
let ((cx0, cy0), (cx1, cy1)) = (self.cell_of(Point::new(x0, y0)), self.cell_of(Point::new(x1, y1)));
if (cx1 - cx0 + 1).saturating_mul(cy1 - cy0 + 1) > self.all.len() as i64 {
return self.all.clone();
}
let mut out = self.wide.clone();
for x in cx0..=cx1 {
for y in cy0..=cy1 {
out.extend(self.cells.get(&(x, y)).into_iter().flatten());
}
}
out.sort_unstable();
out.dedup();
out
}
}
/// The distance from `q` to the nearest of the stretches `of` of the drag `pts`.
fn dist_to_stretches(pts: &[Point], of: &[usize], q: Point) -> f64 {
#[cfg(test)]
STRETCH_TESTS.with(|c| c.set(c.get() + of.len()));
of.iter()
.filter_map(|&k| {
let a = *pts.get(k)?;
@@ -468,15 +502,18 @@ fn nearest_to_stretches(s: CubicBez, pts: &[Point], of: &[usize]) -> (f64, f64)
best
}
/// How many curved segments of `pd` may come within `radius` of the drag `pts`.
fn segments_in_reach(pd: &PathData, pts: &[Point], radius: f64) -> usize {
let all = drag_stretches(pts);
/// How many curved segments of `pd` may come within the reach of the drag.
fn segments_in_reach(pd: &PathData, reach: &DragReach) -> usize {
pd.subpaths
.iter()
.map(|sp| {
(0..sp.segment_count())
.filter(|&i| {
!vectorcraft_tools::draw2::segment_is_straight(sp, i) && !stretches_near(pts, &all, control_box(sp.segment(i)), radius).is_empty()
if vectorcraft_tools::draw2::segment_is_straight(sp, i) {
return false;
}
let b = control_box(sp.segment(i));
!stretches_near(reach.pts, &reach.near_rect(b), b, reach.radius).is_empty()
})
.count()
})
@@ -516,26 +553,26 @@ fn reach_samples(c: CubicBez, (t0, t1): (f64, f64), (pts, of): (&[Point], &[usiz
reach_samples(c, (mid, t1), (pts, &near), radius, budget, out);
}
/// `sp` cut where the reach `radius` of the drag `pts` crosses its curved segments, and whether each
/// `sp` cut where the reach of the drag crosses its curved segments, and whether each
/// anchor of the result is in reach. An anchor in reach is added in the middle of each stretch of a
/// segment in reach that does not run on from one of the segment's anchors in reach, and an anchor
/// out of reach in the middle of each stretch out of reach between two stretches in reach, so that a
/// stretch in reach is smoothed even when the segment's anchors are not, and the stretches between
/// stay as they are. A segment is searched no more than half the reach apart where it comes within
/// the reach of the drag ([`reach_samples`]), measuring up to `share` pieces of each segment.
fn mark_reached(sp: &SubPath, pts: &[Point], radius: f64, share: usize) -> (SubPath, Vec<bool>) {
let near = |q: Point| dist_to_polyline(pts, q) <= radius;
fn mark_reached(sp: &SubPath, reach: &DragReach, share: usize) -> (SubPath, Vec<bool>) {
let (pts, radius) = (reach.pts, reach.radius);
let n = sp.anchors.len();
let marked: Vec<bool> = sp.anchors.iter().map(|a| near(a.p)).collect();
let marked: Vec<bool> = sp.anchors.iter().map(|a| reach.in_reach(a.p, 0.0)).collect();
let mut places = vec![];
let all = drag_stretches(pts);
for i in 0..sp.segment_count() {
if vectorcraft_tools::draw2::segment_is_straight(sp, i) {
continue;
}
let c = sp.segment(i);
let (mut samples, mut budget) = (vec![], share);
reach_samples(c, (0.0, 1.0), (pts, &all), radius, &mut budget, &mut samples);
let near = reach.near_rect(control_box(c.subsegment(0.0..1.0)));
reach_samples(c, (0.0, 1.0), (pts, &near), radius, &mut budget, &mut samples);
// Stretches of samples alike, in order: (in reach, first, last).
let mut runs: Vec<(bool, usize, usize)> = vec![];
for (k, s) in samples.iter().enumerate() {
@@ -573,7 +610,7 @@ fn mark_reached(sp: &SubPath, pts: &[Point], radius: f64, share: usize) -> (SubP
.anchors
.iter()
.enumerate()
.map(|(j, a)| if added.contains(&j) { dist_to_polyline(pts, a.p) <= radius + 1e-9 * radius.max(1.0) } else { kept.next().unwrap_or(false) })
.map(|(j, a)| if added.contains(&j) { reach.in_reach(a.p, 1e-9 * radius.max(1.0)) } else { kept.next().unwrap_or(false) })
.collect();
(out, marked)
}
@@ -581,13 +618,14 @@ fn mark_reached(sp: &SubPath, pts: &[Point], radius: f64, share: usize) -> (SubP
/// `sp` with the anchors in the drag's reach smoothed and refitted, `None` when none are in reach.
/// A closed path whose first anchor is in reach starts at the point of the refitted path nearest
/// that anchor's place (VectorCraft's own rule).
fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f64, sigma: f64) -> Option<SubPath> {
fn smooth_subpath(sp: &SubPath, reach: &DragReach, share: usize, tol: f64, sigma: f64) -> Option<SubPath> {
if sp.anchors.len() < 2 {
return None;
}
let near = &|q: Point| dist_to_polyline(pts, q) <= radius;
let radius = reach.radius;
let near = &|q: Point| reach.in_reach(q, 0.0);
// A drag along a segment smooths it even when its anchors are out of reach.
let (sp, marked) = mark_reached(sp, pts, radius, share);
let (sp, marked) = mark_reached(sp, reach, share);
let sp = &sp;
if !marked.iter().any(|m| *m) {
return None;
@@ -711,14 +749,16 @@ fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool
}
i += 1;
}
let mut out = anchors.to_vec();
let mut out = EditsFromEnd::new(anchors.to_vec());
for (a, b) in runs.into_iter().rev() {
let (mut lo, mut hi) = (a.saturating_sub(1), (b + 1).min(n - 1));
// How much of the segments leading out of the run is in reach. A segment that is in reach
// only at the run's anchor stays out of the piece, so the piece ends at that anchor rather
// than in a sliver of a segment, which would leave the refit no direction to end along.
let after = if hi > b { split_at_reach(CubicBez::new(out[hi].p, out[hi].h_in, out[b].h_out, out[b].p), near, radius) } else { Reach::Whole };
let before = if lo < a { split_at_reach(CubicBez::new(out[lo].p, out[lo].h_out, out[a].h_in, out[a].p), near, radius) } else { Reach::Whole };
let Some(span) = out.get(lo, hi) else { continue };
let (first, start, end, last) = (span[0], span[a - lo], span[b - lo], span[hi - lo]);
let after = if hi > b { split_at_reach(CubicBez::new(last.p, last.h_in, end.h_out, end.p), near, radius) } else { Reach::Whole };
let before = if lo < a { split_at_reach(CubicBez::new(first.p, first.h_out, start.h_in, start.p), near, radius) } else { Reach::Whole };
if matches!(after, Reach::End) {
hi = b;
}
@@ -728,7 +768,8 @@ fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool
if hi == lo {
continue;
}
let mut piece = out[lo..=hi].to_vec();
let Some(piece) = out.get(lo, hi) else { continue };
let mut piece = piece.to_vec();
// The anchors outside the reach, kept with the part of their segment that is outside.
let (mut head, mut tail) = (None, None);
if let Reach::Split(far, reach) = after
@@ -751,16 +792,143 @@ fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool
if same_anchors(&new, &piece) {
continue;
}
out.splice(lo..=hi, head.into_iter().chain(new).chain(tail));
out.replace(lo, hi, head.into_iter().chain(new).chain(tail));
}
out
out.finish()
}
/// A list edited by replacing stretches of it, each one ending no later than where the one before
/// started, in time proportional to the items replaced and moved rather than to the list's length
/// for each edit.
struct EditsFromEnd<T> {
/// The start of the list.
head: Vec<T>,
/// The rest of the list, last item first.
rest: Vec<T>,
}
impl<T> EditsFromEnd<T> {
fn new(items: Vec<T>) -> Self {
EditsFromEnd { head: items, rest: vec![] }
}
/// The items `lo` to `hi` of the list, `None` when it is shorter.
fn get(&mut self, lo: usize, hi: usize) -> Option<&[T]> {
while self.head.len() <= hi {
self.head.push(self.rest.pop()?);
}
self.head.get(lo..=hi)
}
/// The list with the items `lo` to `hi` replaced by `with`, as [`Vec::splice`] gives it. Leaves
/// the list as it is when it is shorter.
fn replace(&mut self, lo: usize, hi: usize, with: impl IntoIterator<Item = T>) {
if lo > hi || self.get(lo, hi).is_none() {
return;
}
self.rest.extend(self.head.drain(hi + 1..).rev());
self.head.truncate(lo);
self.head.extend(with);
}
fn finish(mut self) -> Vec<T> {
self.head.extend(self.rest.into_iter().rev());
self.head
}
}
/// Most pieces [`roughness`] cuts one curved segment into.
const ROUGHNESS_SEGMENT_PIECES: usize = 1024;
/// Most pieces [`roughness`] cuts the curved segments of one subpath into, shared equally by them.
const ROUGHNESS_PIECES: usize = 1 << 18;
/// How rough the subpath `sp` is, measured along the lines between points on each curved segment
/// about `step` apart along its control polygon (at least 4 and at most
/// [`ROUGHNESS_SEGMENT_PIECES`] pieces a segment, fewer on a subpath of very many segments): how
/// much it turns along its length in radians, from the direction each segment leaves its first anchor
/// along to the one it arrives at its last anchor along, with each turn at an anchor counted twice;
/// and how much it bends, the sum of each turn between two pieces squared over their mean length.
/// `None` when a point or a turn is not a number.
fn roughness(sp: &SubPath, step: f64) -> Option<(f64, f64)> {
let segments = sp.segment_count();
let most = (ROUGHNESS_PIECES / segments.max(1)).clamp(4, ROUGHNESS_SEGMENT_PIECES);
// The directions along the path, each with whether it leaves an anchor, and the pieces' vectors.
let (mut dirs, mut pieces): (Vec<(kurbo::Vec2, bool)>, Vec<kurbo::Vec2>) = (vec![], vec![]);
for i in 0..segments {
let c = sp.segment(i);
if sp.segment_is_line(i) {
dirs.push((c.p3 - c.p0, true));
pieces.push(c.p3 - c.p0);
continue;
}
let leave = [c.p1 - c.p0, c.p2 - c.p0, c.p3 - c.p0].into_iter().find(|d| d.hypot() > 1e-12).unwrap_or_default();
let arrive = [c.p3 - c.p2, c.p3 - c.p1, c.p3 - c.p0].into_iter().find(|d| d.hypot() > 1e-12).unwrap_or_default();
let len = polygon_len(c);
let k = if step > 0.0 && step.is_finite() && len.is_finite() { (len / step).ceil().clamp(4.0, most as f64) as usize } else { most };
dirs.push((leave, true));
let mut at = c.p0;
for j in 1..=k {
let q = if j == k { c.p3 } else { c.eval(j as f64 / k as f64) };
dirs.push((q - at, false));
pieces.push(q - at);
at = q;
}
dirs.push((arrive, false));
}
// A direction of no length is left out; the turn at an anchor is then taken at the next one.
let mut kept: Vec<(kurbo::Vec2, bool)> = Vec::with_capacity(dirs.len());
let mut at_anchor = false;
for (d, anchor) in dirs {
at_anchor |= anchor;
if d.hypot() > 1e-12 {
kept.push((d, at_anchor));
at_anchor = false;
}
}
pieces.retain(|d| d.hypot() > 1e-12);
let turn = |u: kurbo::Vec2, v: kurbo::Vec2| u.cross(v).atan2(u.dot(v)).abs();
let pairs = |n: usize| if sp.closed { n } else { n.saturating_sub(1) };
let mut turning = 0.0;
for j in 0..pairs(kept.len()) {
let (u, (v, anchor)) = (kept[j].0, kept[(j + 1) % kept.len()]);
turning += if anchor { 2.0 } else { 1.0 } * turn(u, v);
}
let mut bending = 0.0;
for j in 0..pairs(pieces.len()) {
let (u, v) = (pieces[j], pieces[(j + 1) % pieces.len()]);
bending += turn(u, v).powi(2) / (0.5 * (u.hypot() + v.hypot()));
}
(turning.is_finite() && bending.is_finite()).then_some((turning, bending))
}
/// Whether the Smooth tool keeps `new`, the subpath `old` smoothed with the reach `radius`
/// (VectorCraft's own rule). Both are measured with [`roughness`] at one spacing, an eighth of the
/// reach or 1/512 of the diagonal of `old`'s control points, whichever is smaller. `new` must turn
/// no more than a thousandth more than `old` (counting a turn of less than 1 radian as 1), and it
/// must have fewer anchors, turn less, or bend more than a ten-thousandth less. A result that would
/// leave the path rougher, or that adds anchors or changes the path without smoothing it, is not
/// kept.
fn smoother(old: &SubPath, new: &SubPath, radius: f64) -> bool {
let size = old.anchors.iter().fold(None, |r: Option<Rect>, a| {
let b = Rect::from_points(a.p, a.h_in).union_pt(a.h_out);
Some(r.map_or(b, |r| r.union(b)))
});
let step = (radius / 8.0).min(size.map_or(0.0, |r| r.width().hypot(r.height()) / 512.0));
let (Some((t0, b0)), Some((t1, b1))) = (roughness(old, step), roughness(new, step)) else { return false };
let scale = t0.max(1.0);
t1 <= t0 + 1e-3 * scale && (new.anchors.len() < old.anchors.len() || t0 - t1 >= 1e-6 * scale || b0 - b1 > 1e-4 * b0)
}
pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "path.smoothRegion";
let pts = points_param(p, "points", C)?;
let radius = number_or(p, "radius", 12.0, C)?.max(0.0);
let tol = number_or(p, "fidelity", 2.5, C)?.clamp(vectorcraft_tools::draw2::SMOOTH_MIN_TOLERANCE, vectorcraft_tools::draw2::SMOOTH_MAX_TOLERANCE);
let radius = ranged(p, "radius", 12.0, vectorcraft_tools::draw2::REACH_RANGE, C)?;
let tol = number_or(p, "fidelity", 2.5, C)?;
let (lo, hi) = (vectorcraft_tools::draw2::SMOOTH_MIN_TOLERANCE, vectorcraft_tools::draw2::SMOOTH_MAX_TOLERANCE);
if !(lo..=hi).contains(&tol) {
return Err(bad(C, format!("`fidelity` must be from {lo} to {hi} pt")));
}
let sigma = radius * SMOOTH_SPREAD;
let st = s.doc()?;
let mut plan = vec![];
@@ -769,15 +937,16 @@ pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result<Value> {
for id in target_paths(&st.doc, &st.selection, poly_bounds(&pts, radius)) {
paths.push((id, path_of(&st.doc, id)?.0));
}
let reach = DragReach::new(&pts, radius);
// Each curved segment in reach gets the same share of the search, whatever order they come in.
let in_reach: usize = paths.iter().map(|(_, pd)| segments_in_reach(pd, &pts, radius)).sum();
let in_reach: usize = paths.iter().map(|(_, pd)| segments_in_reach(pd, &reach)).sum();
let share = (MAX_REACH_PIECES / in_reach.max(1)).max(1);
for (id, pd) in paths {
let mut changed = false;
let subs: Vec<SubPath> = pd
.subpaths
.iter()
.map(|sp| match smooth_subpath(sp, &pts, radius, share, tol, sigma) {
.map(|sp| match smooth_subpath(sp, &reach, share, tol, sigma) {
Some(n) if n != *sp && n.anchors.len() >= 2 => {
changed = true;
n
@@ -785,7 +954,10 @@ pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result<Value> {
_ => sp.clone(),
})
.collect();
if changed {
// A subpath whose result would not be smoother stays as it was.
let subs: Vec<SubPath> =
subs.into_iter().zip(&pd.subpaths).map(|(n, sp)| if n == *sp || smoother(sp, &n, radius) { n } else { sp.clone() }).collect();
if changed && subs != pd.subpaths {
let np = PathData::new(subs);
before += pd.anchor_count();
after += np.anchor_count();
@@ -908,7 +1080,7 @@ fn trim_join(d: &vectorcraft_doc::Document, ids: &[NodeId], pts: &[Point], tol:
pub(super) fn join_scrub(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "path.joinScrub";
let pts = points_param(p, "points", C)?;
let tol = number_or(p, "tolerance", 12.0, C)?.max(0.0);
let tol = ranged(p, "tolerance", 12.0, vectorcraft_tools::draw2::REACH_RANGE, C)?;
let st = s.doc()?;
let targets = target_paths(&st.doc, &st.selection, poly_bounds(&pts, tol));
// Paths that cross with their ends scrubbed are trimmed there and joined (#5844).
@@ -1035,6 +1207,8 @@ pub(super) fn join_scrub(s: &mut Session, p: &Value) -> Result<Value> {
#[cfg(test)]
mod tests {
use vectorcraft_pathops::START_SNAP;
use super::*;
/// A closed ring of four smooth anchors round (100, 100) with radius 50.
@@ -1153,6 +1327,153 @@ mod tests {
pts.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect()
}
/// A path of `n` smooth anchors 1 pt apart, along x and up and down by 3 pt, every segment
/// curved; closed, the anchors go round a circle `n` pt long instead.
fn wave(n: usize, closed: bool) -> SubPath {
let anchors = (0..n)
.map(|i| {
let f = i as f64;
if closed {
let r = n as f64 / std::f64::consts::TAU + f64::from(u8::from(i % 2 == 1)) * 3.0;
let a = f / n as f64 * std::f64::consts::TAU;
let (p, t) = (Point::new(r * a.cos(), r * a.sin()), kurbo::Vec2::new(-a.sin(), a.cos()) * 0.4);
Anchor::with_handles(p, p - t, p + t)
} else {
let p = Point::new(f, f64::from(u8::from(i % 2 == 1)) * 3.0);
Anchor::with_handles(p, p - kurbo::Vec2::new(0.4, 0.0), p + kurbo::Vec2::new(0.4, 0.0))
}
})
.collect();
SubPath::new(anchors, closed)
}
/// The same drag measured against all of its stretches for every point and box.
fn linear<'a>(pts: &'a [Point], radius: f64) -> DragReach<'a> {
DragReach { grid: None, ..DragReach::new(pts, radius) }
}
/// How many stretch measures `f` made on this thread.
fn stretch_tests(f: impl FnOnce()) -> usize {
STRETCH_TESTS.with(|c| c.set(0));
f();
STRETCH_TESTS.with(std::cell::Cell::get)
}
/// A drag of 200 points over 200 pt of a curved path of 100,000 anchors measures the anchors
/// and segments near the drag against the stretches near them, not every anchor and segment
/// against every stretch (about 40 million measures), and smooths the path as measuring
/// everything does.
#[test]
fn a_drag_over_a_long_path_measures_only_what_is_near_it() {
let sp = wave(100_000, false);
let pts: Vec<Point> = (0..200).map(|i| Point::new(50_000.0 + f64::from(i), 1.5)).collect();
let reach = DragReach::new(&pts, 12.0);
let pd = PathData::single(sp.clone());
let mut in_reach = 0;
let boxes = stretch_tests(|| in_reach = segments_in_reach(&pd, &reach));
assert!(in_reach > 0 && boxes < 100_000, "{in_reach} segments in reach, {boxes} measures");
let share = (MAX_REACH_PIECES / in_reach).max(1);
let mut got = None;
let marks = stretch_tests(|| got = Some(mark_reached(&sp, &reach, share)));
assert!(marks < 100_000, "{marks} measures");
let smoothed = smooth_subpath(&sp, &reach, share, 2.5, 4.0);
assert!(smoothed.is_some());
let all = linear(&pts, 12.0);
assert_eq!(segments_in_reach(&pd, &all), in_reach);
assert_eq!(Some(mark_reached(&sp, &all, share)), got);
assert_eq!(smooth_subpath(&sp, &all, share, 2.5, 4.0), smoothed);
}
/// Paths and drags of many shapes, a drag of one point, one far away, one with a stretch longer
/// than the grid lists by cell, one with a point that is not a number, and reaches of 0 to 50 pt:
/// the grid gives the same segments in reach, the same marks and the same smoothed path as
/// measuring against the whole drag.
#[test]
fn the_drag_grid_gives_the_results_of_measuring_the_whole_drag() {
let far = Point::new(1e7, -1e7);
let paths = [
ring(),
wave(1500, false),
wave(1500, true),
SubPath::polyline(&(0..500).map(|i| Point::new(f64::from(i) * 2.0, f64::from(i % 3) * 4.0)).collect::<Vec<_>>(), false),
SubPath::new(
vec![Anchor::with_handles(Point::new(0.0, 0.0), Point::new(0.0, 0.0), Point::new(3e5, 4e5)), Anchor::corner(Point::new(1e6, 0.0))],
false,
),
SubPath::new(
wave(200, true)
.anchors
.iter()
.map(|a| Anchor::with_handles(a.p + far.to_vec2(), a.h_in + far.to_vec2(), a.h_out + far.to_vec2()))
.collect(),
true,
),
];
let line = |from: (f64, f64), to: (f64, f64), n: u32| -> Vec<Point> {
(0..=n).map(|i| Point::new(from.0, from.1).lerp(Point::new(to.0, to.1), f64::from(i) / f64::from(n))).collect()
};
let mut loop_drag: Vec<Point> =
(0..400).map(|i| Point::new(100.0 + 120.0 * (f64::from(i) * 0.05).cos(), 120.0 * (f64::from(i) * 0.05).sin())).collect();
loop_drag.extend(line((0.0, 0.0), (1500.0, 2.0), 50));
let drags = [
vec![Point::new(150.0, 100.0)],
line((40.0, 90.0), (160.0, 110.0), 30),
line((-100.0, 1.0), (1600.0, 2.0), 1500),
loop_drag,
line((5e6, 5e6), (5e6 + 10.0, 5e6), 5),
vec![Point::new(0.0, 0.0), Point::new(1500.0, 3.0), Point::new(1500.0, 3.2), Point::new(10.0, 0.5)],
vec![Point::new(10.0, 1.0), Point::new(f64::NAN, 0.0), Point::new(12.0, 1.0)],
(0..1000).map(|i| Point::new(f64::from(i) * 0.01, 1.0)).collect(),
line((far.x, far.y), (far.x + 300.0, far.y + 40.0), 80),
];
for pts in &drags {
for radius in [0.0, 0.5, 12.0, 50.0] {
let (grid, all) = (DragReach::new(pts, radius), linear(pts, radius));
for (k, sp) in paths.iter().enumerate() {
let pd = PathData::single(sp.clone());
let in_reach = segments_in_reach(&pd, &all);
assert_eq!(segments_in_reach(&pd, &grid), in_reach, "path {k}, reach {radius}, drag {:?}", pts.first());
let share = (MAX_REACH_PIECES / in_reach.max(1)).max(1);
assert_eq!(mark_reached(sp, &grid, share), mark_reached(sp, &all, share), "path {k}, reach {radius}, drag {:?}", pts.first());
let sigma = radius * SMOOTH_SPREAD;
let want = smooth_subpath(sp, &all, share, 2.5, sigma);
assert_eq!(smooth_subpath(sp, &grid, share, 2.5, sigma), want, "path {k}, reach {radius}, drag {:?}", pts.first());
}
}
}
}
/// Replacing stretches of a list from its end, each one ending no later than where the one
/// before started (sometimes on that item, sometimes with nothing or with more items), gives the
/// list that [`Vec::splice`] gives.
#[test]
fn edits_from_the_end_match_splicing() {
let mut seed = 0x2545_f491_u64;
let mut next = |m: usize| {
seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407);
(seed >> 33) as usize % m.max(1)
};
for round in 0..200 {
let items: Vec<usize> = (0..next(60) + 1).collect();
let (mut want, mut got) = (items.clone(), EditsFromEnd::new(items.clone()));
let mut end = items.len() - 1;
loop {
let hi = end.saturating_sub(next(3));
let lo = hi.saturating_sub(next(6));
let with: Vec<usize> = (0..next(5)).map(|j| 1000 * (round + 1) + j).collect();
let Some(stretch) = want.get(lo..=hi).map(<[usize]>::to_vec) else { break };
assert_eq!(got.get(lo, hi).map(<[usize]>::to_vec), Some(stretch), "round {round}");
want.splice(lo..=hi, with.clone());
got.replace(lo, hi, with);
if lo == 0 {
break;
}
end = lo;
}
assert_eq!(got.finish(), want, "round {round}");
}
}
/// Anchors on one point, anchors that are not numbers or are too far out to measure, and a
/// zigzag of 100,001 anchors 1 pt high give no corner and do not fail; a square's four anchors
/// are its corners, and an open path's ends never are.
@@ -1272,4 +1593,30 @@ mod tests {
assert_eq!(smooth_corners(&jags, true, 12.0), vec![false; 16]);
assert_eq!(smooth_corners(&polyline(&[(0.0, 0.0), (6.0, 0.0), (3.0, 5.196)]), true, 12.0), vec![true; 3]);
}
/// `sp` scaled by `k` about the origin.
fn scaled(sp: &SubPath, k: f64) -> SubPath {
let at = |p: Point| Point::new(p.x * k, p.y * k);
SubPath::new(sp.anchors.iter().map(|a| Anchor { p: at(a.p), h_in: at(a.h_in), h_out: at(a.h_out), ..*a }).collect::<Vec<Anchor>>(), sp.closed)
}
/// The Smooth tool keeps a result that turns less, and not one that turns more with as many
/// anchors, one that adds an anchor and keeps the outline, or one that is the path itself, at
/// any size.
#[test]
fn the_smooth_tool_keeps_only_a_smoother_result() {
let round = ring();
let mut bumped = ring();
bumped.anchors[1].translate(kurbo::Vec2::new(0.0, -25.0));
let split = start_nearest(ring(), round.segment(0).eval(0.3), &round);
assert_eq!(split.anchors.len(), 5, "{split:?}");
for k in [1e-3, 1.0, 1e3] {
let (round, bumped, split) = (scaled(&round, k), scaled(&bumped, k), scaled(&split, k));
let reach = 12.0 * k;
assert!(smoother(&bumped, &round, reach), "at {k}x a bump smoothed away is kept");
assert!(!smoother(&round, &bumped, reach), "at {k}x a bump added is not kept");
assert!(!smoother(&round, &split, reach), "at {k}x an anchor added on the outline is not kept");
assert!(!smoother(&round, &round.clone(), reach), "at {k}x the same path is not kept");
}
}
}
+3 -2
View File
@@ -1552,7 +1552,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
let (ids, imported, artboards, into) = s.edit(mode.label(), |d, sel| {
// Converted colors are compared with the document's resources, as another document's are
// (`Clipboard::import_into`); its images are still the document's own.
let imported = clip.import_into(d, choices, same_doc)?;
let mut imported = clip.import_into(d, choices, same_doc)?;
// Draw Inside: the clip group of the object drawn into, made on the first paste.
let into = inside.map(|t| super::create::draw_inside_group(d, t)).transpose()?;
let artboards: Vec<usize> = boards
@@ -1570,7 +1570,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
let mut c = d.reid(n);
// A pasted symbol set packs from the density recorded for it at Copy.
d.carry_set_densities(n, &c, &clip.set_densities);
imported.apply(&mut c);
imported.apply(&mut c, d);
let sc = vectorcraft_doc::Scaling { patterns: mode == PasteMode::Drag, ..Default::default() };
if xf != Affine::IDENTITY {
// A cross-document drag carries the graphic's appearance with it,
@@ -1698,6 +1698,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
"added": imported.added,
"merged": imported.merged,
"renamed": imported.renamed,
"warnings": imported.warnings,
}))
}
+49 -10
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, 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)}",
"{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 visible plain instance outside template layers 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
),
@@ -1616,33 +1616,72 @@ 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, and so does
/// every object in a group or layer with a raster effect, whose image draws all of it). A symbol's
/// object that expands ([`expandable`]; in a symbol's art, `in_art`, every object does), or that the
/// image of a group or layer with a raster effect draws ([`rasterizes_plugin_effect`]). 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;
}
holds |= c.appearance.effects.iter().any(plugin) || c.appearance.items.iter().any(|i| i.visible() && i.effects().iter().any(plugin));
holds |= has_own_plugin_effect(c);
if let NodeKind::SymbolInstance { symbol, .. } = &c.kind {
symbols.push(symbol.clone());
}
});
holds
|| drawn.into_iter().any(|g| holds_plugin_effect(d, g, true, seen))
|| (!in_art && rasterizes_plugin_effect(d, n, &mut std::collections::HashSet::new()))
|| 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))
})
}
/// Does `n` have a visible plug-in effect of its own, or on a visible fill or stroke?
fn has_own_plugin_effect(n: &Node) -> bool {
let plugin = |e: &Effect| e.visible && vectorcraft_plugins::effect::plugin_id(&e.id).is_some();
n.appearance.effects.iter().any(plugin) || n.appearance.items.iter().any(|i| i.visible() && i.effects().iter().any(plugin))
}
/// Does a group or layer in `n` with a raster effect make an image of a visible plug-in effect
/// ([`draws_plugin_effect`])? Expansion makes the image of such a group or layer even when it, or
/// a group around it, is hidden. A group or layer that paints something and whose raster effects
/// are not all shadows and outer glows becomes one image of what it draws, so the groups and layers
/// in it make no images of their own; one that paints nothing makes no image, and its members
/// expand on their own.
fn rasterizes_plugin_effect(d: &Document, n: &Node, seen: &mut std::collections::HashSet<String>) -> bool {
let fx = if is_container(n) { rasterfx::raster_fx(n) } else { vec![] };
if !fx.is_empty() {
if draws_plugin_effect(d, n, seen) {
return true;
}
if !fx.iter().all(effects::RasterFx::is_below) && vectorcraft_render::painted_bounds(d, n).is_some() {
return false;
}
}
n.children().into_iter().flatten().any(|c| rasterizes_plugin_effect(d, c, seen))
}
/// Does `n`, an object the image of `n` draws in it, or the art of a symbol such an instance places,
/// have a visible plug-in effect ([`has_own_plugin_effect`])? The image leaves out a hidden object
/// in `n`, a template layer, a guide or a ruler guide, and everything in it, as the renderer does
/// with templates skipped. `seen` holds the symbols already looked into.
fn draws_plugin_effect(d: &Document, n: &Node, seen: &mut std::collections::HashSet<String>) -> bool {
if has_own_plugin_effect(n) {
return true;
}
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind
&& seen.insert(symbol.clone())
&& d.symbols.iter().find(|s| s.name == *symbol).is_some_and(|s| draws_plugin_effect(d, &s.art, seen))
{
return true;
}
let drawn =
|c: &Node| c.visible && !c.is_ruler_guide() && !matches!(c.kind, NodeKind::Layer { template: true, .. } | NodeKind::Path { guide: true, .. });
n.children().into_iter().flatten().any(|c| drawn(c) && draws_plugin_effect(d, c, seen))
}
fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
let roots = edit_targets(s, p, "effect.expandAppearance")?;
// In Safe Mode a plug-in effect draws nothing: expanding it would drop the effect and keep the
+1 -1
View File
@@ -79,10 +79,10 @@ pub(crate) use encode::{anti_alias, background, with_single_artboard};
pub(crate) use export::with_artboard_fills;
pub(crate) use export::{EXPORT_PARAMS, export_crop, isolated};
pub use export::{export_doc, export_source, selection_doc, unused_option_notes};
pub(crate) use load::decode_native_file;
use load::err;
pub(crate) use load::import_svg;
pub(crate) use load::is_placeholder;
pub(crate) use load::native_file;
pub(crate) use load::page_or_editing_data;
pub(crate) use load::source;
pub use load::{
+19 -11
View File
@@ -140,9 +140,8 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> {
if let Some(f) = craft_image_codecs::detect(bytes).and_then(image_format) {
return Some(f);
}
// A version 2 PICT is known by its version opcodes after the picture's frame, at byte 522 of a
// file or byte 10 of a bare picture (version 1 by its file's name), so a format whose
// signature starts the file is checked first.
// A PICT is known by its version opcodes after the picture's frame, at byte 522 of a file or
// byte 10 of a bare picture, so a format whose signature starts the file is checked first.
if vectorcraft_metafile::is_pict(bytes) {
return format("pict");
}
@@ -193,8 +192,11 @@ fn restore_or_import(
let mut fallback = None;
if let Some((intact, bytes)) = editing {
let native = if intact { bytes() } else { None };
match native.and_then(|b| native_file(&b).ok()) {
Some((doc, _, warnings)) => return Ok((doc, warnings, true)),
match native.and_then(|b| decode_native_file(&b).ok()) {
Some((mut doc, _, mut warnings)) => {
warnings.extend(vectorcraft_text::FontDb::global().bind_document_file_fonts(&mut doc));
return Ok((doc, warnings, true));
}
None => fallback = Some(if intact { EDITING_DAMAGED } else { EDITING_STALE }),
}
}
@@ -205,9 +207,9 @@ fn restore_or_import(
Ok((doc, warnings, false))
}
/// A native file's document and details, the colour profiles it carries installed where missing
/// (with a warning for each that can't be used).
pub(crate) fn native_file(bytes: &[u8]) -> Result<(Document, vectorcraft_format::FileInfo, Vec<String>)> {
/// Decode a native file and install its colour profiles, preserving profile and depth warnings.
/// The caller must assemble any external resources and bind file fonts before layout.
pub(crate) fn decode_native_file(bytes: &[u8]) -> Result<(Document, vectorcraft_format::FileInfo, Vec<String>)> {
let f = vectorcraft_format::load_file(bytes).map_err(err)?;
let mut warnings = super::native::install_profiles(f.profiles);
warnings.extend(f.depth_notes);
@@ -424,7 +426,8 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
})?
}
"vectorcraft" | "template" => {
let (d, info, warnings) = native_file(bytes)?;
let (mut d, info, mut warnings) = decode_native_file(bytes)?;
warnings.extend(vectorcraft_text::FontDb::global().bind_document_file_fonts(&mut d));
native_pdf_compatible = Some(info.pdf_compatible);
converted = info.is_old() || super::extension(name) == vectorcraft_format::LEGACY_EXTENSION;
(d, warnings, false)
@@ -688,7 +691,8 @@ pub fn open_bytes(s: &mut Session, name: &str, bytes: &[u8], path: Option<String
/// [`open_bytes`] with the `document.open` options in `p` ([`LoadOptions::from_params`]).
pub fn open_bytes_with(s: &mut Session, name: &str, bytes: &[u8], path: Option<String>, p: &Value) -> Result<Value> {
let update_links = s.prefs.update_links == "automatically";
open_read(s, read_for_open(name, bytes, path, p, update_links, s.prefs.low_res_proxy_eps)?)
let p = s.prefs.with_pdf_font_choice(p);
open_read(s, read_for_open(name, bytes, path, &p, update_links, s.prefs.low_res_proxy_eps)?)
}
/// A file read for `document.open` but not opened yet ([`read_for_open`], [`open_read`]).
@@ -860,7 +864,11 @@ impl ReadFile {
let Some((update_links, low_res_proxy_eps)) = self.links_left.take() else { return };
let base = crate::cmd::links::LinkBase::file(self.path.as_deref());
self.links = crate::cmd::links::resolve(&mut self.loaded.doc, base, update_links, low_res_proxy_eps);
Session::refresh_text_bounds(&mut self.loaded.doc);
for note in Session::refresh_text_bounds(&mut self.loaded.doc) {
if !self.loaded.warnings.contains(&note) {
self.loaded.warnings.push(note);
}
}
}
/// The policies with the profile answer and the color mode `colorMode` asks for, once; the
+25 -7
View File
@@ -7,7 +7,9 @@
//! about the point the object turns about: in points in OBJ and USD (whose layer says how many
//! meters a unit is), in meters in glTF, as its specification asks. glTF and USD colors are linear,
//! as their specifications ask; MTL colors are the display colors. Materials are two-sided, since
//! an open solid or a turned plane is seen from both sides.
//! an open solid or a turned plane is seen from both sides. Every corner carries its normal and
//! texture coordinates (`vt`, `TEXCOORD_0`, `primvars:st`); a mesh whose lists do not match, or
//! that holds a value that is not a number, is refused before anything is written.
//!
//! The graphics mapped onto a face of a solid ([`textures`]) are a PNG picture of that face: its
//! color with the graphics drawn over it, flat and unshaded, which the face's own mesh shows through
@@ -140,6 +142,7 @@ pub(crate) fn image_maps(textures: &[Option<Texture>]) -> Vec<bool> {
/// OBJ with its MTL after it and the PNG files of `textures` last (an OBJ's opacity maps each after
/// its texture). `textures` holds the picture of each part that has one, in the order of `parts`.
pub(crate) fn mesh_files(stem: &str, format: &str, parts: &[SolidMesh], textures: &[Option<Texture>]) -> Result<Vec<(String, Vec<u8>)>, String> {
check_parts(parts)?;
let (images, image) = images(parts.len(), textures);
let maps: Vec<bool> = images.iter().map(|(_, map)| map.is_some()).collect();
let names = mesh_file_names(stem, format, &maps)?;
@@ -180,6 +183,21 @@ impl Scene<'_> {
let t = self.textures.get(k)?.as_ref()?;
Some((t.uv.as_slice(), (*self.image.get(k)?)?))
}
/// Part `k`'s texture coordinates, one for each corner, 0 to 1 across from the left and down
/// from the top: its picture's when it has one, else its mesh's own.
fn coords(&self, k: usize) -> Option<&[[f64; 2]]> {
let count = self.parts.get(k)?.mesh.positions.len();
let own = self.parts.get(k).map(|p| p.mesh.uvs.as_slice());
self.texture(k).map(|(uv, _)| uv).into_iter().chain(own).find(|uv| uv.len() == count && count > 0)
}
}
/// An error when a part's mesh cannot be written as it is: its lists do not match, or a
/// position, normal or texture coordinate is not a number
/// ([`vectorcraft_render::effects::Mesh::check`]).
fn check_parts(parts: &[SolidMesh]) -> Result<(), String> {
parts.iter().try_for_each(|p| p.mesh.check())
}
/// A material: a color, with a picture that replaces its red, green and blue.
@@ -230,7 +248,7 @@ fn obj(stem: &str, scene: &Scene) -> (String, String) {
}
// OBJ's texture coordinates run up from the picture's bottom.
for k in 0..parts.len() {
for uv in scene.texture(k).map(|(uv, _)| uv).unwrap_or_default() {
for uv in scene.coords(k).unwrap_or_default() {
let _ = writeln!(o, "vt {} {}", num(uv[0]), num(1.0 - uv[1]));
}
}
@@ -243,9 +261,9 @@ fn obj(stem: &str, scene: &Scene) -> (String, String) {
for (k, p) in parts.iter().enumerate() {
let _ = writeln!(o, "g Solid_{}", k + 1);
let _ = writeln!(o, "usemtl Material_{}", material.get(k).copied().unwrap_or(0) + 1);
let textured = scene.texture(k).filter(|(uv, _)| uv.len() == p.mesh.positions.len()).is_some();
let coords = scene.coords(k).is_some();
for t in &p.mesh.triangles {
if textured {
if coords {
let [a, b, c] = t.map(|i| i as usize);
let corner = |i: usize| format!("{}/{}/{}", i + base, i + uv_base, i + base);
let _ = writeln!(o, "f {} {} {}", corner(a), corner(b), corner(c));
@@ -255,7 +273,7 @@ fn obj(stem: &str, scene: &Scene) -> (String, String) {
}
}
base += p.mesh.positions.len();
uv_base += scene.texture(k).map_or(0, |(uv, _)| uv.len());
uv_base += scene.coords(k).map_or(0, <[_]>::len);
}
let mut m = String::new();
for (k, mat) in materials.iter().enumerate() {
@@ -313,7 +331,7 @@ fn gltf(stem: &str, scene: &Scene) -> String {
"material": material.get(k).copied().unwrap_or(0),
});
// glTF's texture coordinates run down from the picture's top, as the picture's own do.
if let Some((uv, _)) = scene.texture(k).filter(|(uv, _)| uv.len() == count) {
if let Some(uv) = scene.coords(k) {
let bytes = uv.iter().flatten().flat_map(|x| (*x as f32).to_le_bytes()).collect();
let coords = view(&mut buffer, bytes, 34962);
primitive["attributes"]["TEXCOORD_0"] = json!(accessors.len());
@@ -415,7 +433,7 @@ fn usda(stem: &str, scene: &Scene) -> String {
);
let _ = writeln!(u, " float[] primvars:displayOpacity = [{}] (\n interpolation = \"constant\"\n )", c[3]);
// USD's texture coordinates run up from the picture's bottom.
if let Some((uv, _)) = scene.texture(k).filter(|(uv, _)| uv.len() == p.mesh.positions.len()) {
if let Some(uv) = scene.coords(k) {
let st = list(uv.iter().map(|t| format!("({}, {})", num(t[0]), num(1.0 - t[1]))).collect());
let _ = writeln!(u, " texCoord2f[] primvars:st = [{st}] (\n interpolation = \"vertex\"\n )");
}
+49 -13
View File
@@ -1,12 +1,18 @@
use serde_json::Value;
use vectorcraft_render::effects::{Mesh, SolidMesh};
use vectorcraft_render::effects::{Mesh, MeshPart, SolidMesh};
use super::*;
/// A 10 × 10 square facing the viewer: two triangles, each with corners of its own.
fn square(color: [f32; 4]) -> SolidMesh {
let [a, b, c, d] = [[-5.0, -5.0, 0.0], [5.0, -5.0, 0.0], [5.0, 5.0, 0.0], [-5.0, 5.0, 0.0]];
let mesh = Mesh { positions: vec![a, b, c, a, c, d], normals: vec![[0.0, 0.0, 1.0]; 6], triangles: vec![[0, 1, 2], [3, 4, 5]] };
let mesh = Mesh {
positions: vec![a, b, c, a, c, d],
normals: vec![[0.0, 0.0, 1.0]; 6],
uvs: vec![[0.0, 1.0], [1.0, 1.0], [1.0, 0.0], [0.0, 1.0], [1.0, 0.0], [0.0, 0.0]],
triangles: vec![[0, 1, 2], [3, 4, 5]],
parts: vec![MeshPart::Front; 2],
};
SolidMesh::plain(mesh, color)
}
@@ -31,8 +37,9 @@ fn obj_numbers_corners_across_solids_and_names_its_materials() {
assert!(obj.starts_with("mtllib Box.mtl\no Box\n"));
assert_eq!(obj.lines().filter(|l| l.starts_with("v ")).count(), 18);
assert_eq!(obj.lines().filter(|l| l.starts_with("vn ")).count(), 18);
assert_eq!(obj.lines().filter(|l| l.starts_with("vt ")).count(), 18);
// The third solid's last triangle uses corners 13 to 18; red solids share Material_1.
assert_eq!(obj.lines().rfind(|l| l.starts_with("f ")), Some("f 16//16 17//17 18//18"));
assert_eq!(obj.lines().rfind(|l| l.starts_with("f ")), Some("f 16/16/16 17/17/17 18/18/18"));
assert_eq!(obj.lines().filter(|l| l.starts_with("usemtl ")).collect::<Vec<_>>(), ["usemtl Material_1", "usemtl Material_2", "usemtl Material_1"]);
let mtl = text(&files, "Box.mtl");
assert_eq!(mtl.matches("newmtl").count(), 2);
@@ -64,8 +71,12 @@ fn gltf_holds_its_buffer_and_every_accessor_fits_it() {
assert_eq!(g["materials"][1]["alphaMode"], "BLEND");
assert!(g["materials"][0].get("alphaMode").is_none());
assert_eq!(g["materials"][0]["doubleSided"], true);
// Without graphics there are no textures.
assert!(g.get("images").is_none() && g.get("textures").is_none() && prims[0]["attributes"].get("TEXCOORD_0").is_none());
// Without graphics there are no textures, but every corner has its mesh's texture coordinates.
assert!(g.get("images").is_none() && g.get("textures").is_none());
for p in prims {
let uv = &g["accessors"][p["attributes"]["TEXCOORD_0"].as_u64().unwrap() as usize];
assert_eq!((uv["type"].as_str(), uv["count"].as_u64()), (Some("VEC2"), Some(6)));
}
}
#[test]
@@ -82,7 +93,28 @@ fn usda_is_y_up_in_points_with_a_material_for_each_color() {
// sRGB 0.5 is about 0.214 linear.
assert!(u.contains("color3f inputs:diffuseColor = (0.21404"), "{u}");
assert_eq!(u.matches('{').count(), u.matches('}').count());
assert!(!u.contains("primvars:st") && !u.contains("UsdUVTexture"));
// Each mesh carries its own texture coordinates, up from the bottom, with no picture to show.
assert_eq!(u.matches("texCoord2f[] primvars:st = [(0, 0), (1, 0), (1, 1), (0, 0), (1, 1), (0, 1)]").count(), 2, "{u}");
assert!(!u.contains("UsdUVTexture"));
}
#[test]
fn a_mesh_whose_lists_do_not_match_or_hold_no_number_is_refused() {
let good = square(RED);
let mut nan = square(RED);
nan.mesh.uvs[2] = [f64::NAN, 0.0];
let mut infinite = square(RED);
infinite.mesh.normals[0] = [f64::INFINITY, 0.0, 0.0];
let mut short = square(RED);
short.mesh.uvs.pop();
let mut unnamed = square(RED);
unnamed.mesh.parts.pop();
for bad in [nan, infinite, short, unnamed] {
for format in FORMATS_3D {
assert!(plain_files("Box", format, &[good.clone(), bad.clone()]).is_err(), "{format} {bad:?}");
}
}
assert!(plain_files("Box", "obj", &[good]).is_ok());
}
#[test]
@@ -141,7 +173,10 @@ fn prim_names_are_usd_identifiers() {
fn textured(png: &[u8]) -> (Vec<SolidMesh>, Vec<Option<Texture>>) {
let uv = vec![[0.0, 1.0], [1.0, 1.0], [1.0, 0.0], [0.0, 1.0], [1.0, 0.0], [0.0, 0.0]];
let texture = Texture { png: Arc::new(png.to_vec()), opacity: None, uv };
(vec![square(RED), square(BLUE)], vec![None, Some(texture)])
// The picture's coordinates replace the mesh's own.
let mut blue = square(BLUE);
blue.mesh.uvs = vec![[0.25, 0.25]; 6];
(vec![square(RED), blue], vec![None, Some(texture)])
}
#[test]
@@ -154,16 +189,18 @@ fn each_format_carries_a_textured_part_with_its_coordinates_and_picture() {
assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["My_Box.obj", "My_Box.mtl", "My_Box-texture-1.png"]);
assert_eq!(files[2].1, png);
let obj = text(&files, "My_Box.obj");
assert_eq!(obj.lines().filter(|l| l.starts_with("vt ")).collect::<Vec<_>>(), ["vt 0 0", "vt 1 0", "vt 1 1", "vt 0 0", "vt 1 1", "vt 0 1"]);
assert_eq!(obj.lines().rfind(|l| l.starts_with("f ")), Some("f 10/4/10 11/5/11 12/6/12"));
assert!(obj.contains("f 1//1 2//2 3//3"), "the plain part keeps no texture coordinates");
// The plain part's own coordinates come first, then the textured part's picture's.
let square_vt = ["vt 0 0", "vt 1 0", "vt 1 1", "vt 0 0", "vt 1 1", "vt 0 1"];
assert_eq!(obj.lines().filter(|l| l.starts_with("vt ")).collect::<Vec<_>>(), [square_vt, square_vt].concat());
assert_eq!(obj.lines().rfind(|l| l.starts_with("f ")), Some("f 10/10/10 11/11/11 12/12/12"));
assert!(obj.contains("f 1/1/1 2/2/2 3/3/3"), "the plain part keeps its mesh's texture coordinates");
let mtl = text(&files, "My_Box.mtl");
assert!(mtl.contains("newmtl Material_2\nKd 1 1 1\nd 1\nillum 1\nmap_Kd -clamp on My_Box-texture-1.png\n"), "{mtl}");
assert_eq!(mtl.matches("map_Kd").count(), 1);
// glTF: TEXCOORD_0 down from the top, and the picture embedded as a data URI.
let g: Value = serde_json::from_str(&text(&mesh_files("Box", "gltf", &parts, &pictures).unwrap(), "Box.gltf")).unwrap();
let prims = g["meshes"][0]["primitives"].as_array().unwrap();
assert!(prims[0]["attributes"].get("TEXCOORD_0").is_none());
assert!(prims[0]["attributes"].get("TEXCOORD_0").is_some(), "the plain part keeps its mesh's texture coordinates");
let uv = &g["accessors"][prims[1]["attributes"]["TEXCOORD_0"].as_u64().unwrap() as usize];
assert_eq!((uv["type"].as_str(), uv["count"].as_u64(), uv["componentType"].as_u64()), (Some("VEC2"), Some(6), Some(5126)));
let view = &g["bufferViews"][uv["bufferView"].as_u64().unwrap() as usize];
@@ -182,8 +219,7 @@ fn each_format_carries_a_textured_part_with_its_coordinates_and_picture() {
let files = mesh_files("Box", "usda", &parts, &pictures).unwrap();
assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box.usda", "Box-texture-1.png"]);
let u = text(&files, "Box.usda");
assert_eq!(u.matches("primvars:st").count(), 1);
assert!(u.contains("texCoord2f[] primvars:st = [(0, 0), (1, 0), (1, 1), (0, 0), (1, 1), (0, 1)]"), "{u}");
assert_eq!(u.matches("texCoord2f[] primvars:st = [(0, 0), (1, 0), (1, 1), (0, 0), (1, 1), (0, 1)]").count(), 2, "{u}");
assert!(u.contains("color3f inputs:diffuseColor.connect = </Box/Materials/Material_2/Texture.outputs:rgb>"), "{u}");
assert!(u.contains("asset inputs:file = @Box-texture-1.png@") && u.contains("uniform token info:id = \"UsdUVTexture\""));
assert!(u.contains("float2 inputs:st.connect = </Box/Materials/Material_2/Coordinates.outputs:result>"));
+17 -16
View File
@@ -8,7 +8,10 @@ use std::sync::Arc;
use serde::Deserialize;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeKind};
use vectorcraft_pdf::{Overprint, PdfError, PdfOptions, PdfPreset, PdfSettings, Standard, THUMBNAIL_SIZE, Thumbnail};
use vectorcraft_pdf::{
APP, ActiveProfiles, Overprint, PdfError, PdfOptions, PdfPreset, PdfSettings, Standard, THUMBNAIL_SIZE, Thumbnail, default_preset_name,
leaves_out_bleed, page_bleed,
};
use super::super::flatten::{FlattenOptions, flatten_document, see_through_images};
use super::super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, str_param};
@@ -17,9 +20,6 @@ use crate::EngineError;
const C: &str = "document.exportPdf";
/// The built-in preset every PDF export starts from.
pub use vectorcraft_pdf::DEFAULT_PRESET;
/// The PDF options `document.formats` lists; `document.exportPdf` documents every field.
pub(crate) const OPTIONS: &[FormatOption] = &[
super::ARTBOARD,
@@ -151,13 +151,13 @@ pub fn presets(s: &Session) -> Vec<String> {
/// The built-in preset names, then those of `saved`.
fn names(saved: &[PdfPreset]) -> Vec<String> {
vectorcraft_pdf::builtin_presets().into_iter().map(|p| p.name).chain(saved.iter().map(|p| p.name.clone())).collect()
vectorcraft_pdf::builtin_presets(APP).into_iter().map(|p| p.name).chain(saved.iter().map(|p| p.name.clone())).collect()
}
/// The preset `name` names: a built-in one (any case; `default` is the app default) or one of
/// `saved`.
pub fn find_preset(name: &str, saved: &[PdfPreset]) -> Option<PdfPreset> {
vectorcraft_pdf::builtin_preset(name).or_else(|| saved.iter().find(|p| p.name.eq_ignore_ascii_case(name.trim())).cloned())
vectorcraft_pdf::builtin_preset(name, APP).or_else(|| saved.iter().find(|p| p.name.eq_ignore_ascii_case(name.trim())).cloned())
}
fn preset(cmd: &str, name: &str, saved: &[PdfPreset]) -> Result<PdfSettings> {
@@ -166,9 +166,10 @@ fn preset(cmd: &str, name: &str, saved: &[PdfPreset]) -> Result<PdfSettings> {
.ok_or_else(|| bad(cmd, format!("unknown PDF preset `{name}` (presets: {})", names(saved).join(", "))))
}
/// The settings of the preset `p` names (default: [`DEFAULT_PRESET`]), before `p`'s options.
/// The settings of the preset `p` names (default: [`default_preset_name`]), before `p`'s options.
pub fn preset_settings(cmd: &str, p: &Value, saved: &[PdfPreset]) -> Result<PdfSettings> {
preset(cmd, str_param(p, "preset").unwrap_or(DEFAULT_PRESET), saved)
let default = default_preset_name(APP);
preset(cmd, str_param(p, "preset").unwrap_or(&default), saved)
}
/// Merge `over` into `base`: objects key by key (recursively), `null` keeps the base (the
@@ -194,7 +195,7 @@ pub(crate) fn pdf_error(cmd: &str, e: PdfError) -> EngineError {
}
/// The settings `p` asks for: its preset (built-in or one of `saved`; default
/// [`DEFAULT_PRESET`]) with `p`'s options applied over it. Choosing another standard turns
/// [`default_preset_name`]) with `p`'s options applied over it. Choosing another standard turns
/// Preserve Editing off, the layers off where it has none, and sets the latest compatibility it
/// allows, unless `p` asks for those. Checked as a preset is
/// ([`PdfSettings::check_values`]): profiles that aren't there pass. Keys that aren't PDF options
@@ -219,14 +220,14 @@ pub fn resolve(cmd: &str, p: &Value, saved: &[PdfPreset]) -> Result<PdfSettings>
s.compatibility = s.standard.version();
}
}
s.check_values().map_err(|e| pdf_error(cmd, e))?;
s.check_values().map_err(|e| pdf_error(cmd, e.into()))?;
Ok(s)
}
/// [`resolve`], refusing what the writer can't honour ([`PdfSettings::check`]).
pub fn settings_with(cmd: &str, p: &Value, saved: &[PdfPreset]) -> Result<PdfSettings> {
let s = resolve(cmd, p, saved)?;
s.check().map_err(|e| pdf_error(cmd, e))?;
s.check(&ActiveProfiles::default()).map_err(|e| pdf_error(cmd, e.into()))?;
Ok(s)
}
@@ -240,7 +241,7 @@ pub fn settings(cmd: &str, p: &Value) -> Result<PdfSettings> {
/// built-in presets. Params naming none come back as they are.
pub fn expand_preset<'a>(s: &Session, cmd: &str, p: &'a Value) -> Result<Cow<'a, Value>> {
let expanded = match str_param(p, "preset") {
Some(name) if vectorcraft_pdf::builtin_preset(name).is_none() => {
Some(name) if vectorcraft_pdf::builtin_preset(name, APP).is_none() => {
let set = settings_with(cmd, p, &s.prefs.pdf_presets)?;
let mut q = p.clone();
merge(&mut q, &serde_json::to_value(set).map_err(|e| EngineError::Other(e.to_string()))?);
@@ -316,7 +317,7 @@ pub(super) fn art_page(cmd: &str, doc: &Document, p: &Value) -> Result<Option<(D
}
/// The warning for a PDF/X file that leaves out the document's bleed
/// ([`vectorcraft_pdf::PdfSettings::leaves_out_bleed`]).
/// ([`vectorcraft_pdf::leaves_out_bleed`]).
pub const BLEED_LEFT_OUT: &str = "the document sets a bleed that this PDF/X file leaves out: turn on Use document bleed settings";
/// How far, in points, an object's edge may sit inside the trim edge, or short of the bleed edge,
@@ -579,7 +580,7 @@ fn encode_carrying_at(
// createLayers writes non-printing layers with /PrintState /OFF, so they count only with
// includeNonPrinting, which writes them as printing art.
let set = &opts.settings;
let short = if bleed_check { short_of_bleed(doc, set.bleed_of(doc), opts.artboards.as_deref(), set.include_non_printing) } else { 0 };
let short = if bleed_check { short_of_bleed(doc, page_bleed(&set.bleed, doc), opts.artboards.as_deref(), set.include_non_printing) } else { 0 };
// The pages' background colors, behind the art (the editing data keeps them as colors).
let pages = opts.artboards.clone().unwrap_or_else(|| (0..doc.artboards.len()).collect());
let filled = super::export::with_artboard_fills(doc, p, pages).map_err(|e| bad(cmd, e))?;
@@ -592,7 +593,7 @@ fn encode_carrying_at(
let mut notes = vec![];
// A loss, ahead of the flattening note: the PDF/X pages leave out the bleed that Document
// Setup gives.
if opts.settings.leaves_out_bleed(doc) {
if leaves_out_bleed(&opts.settings, doc) {
notes.push(Note::loss(BLEED_LEFT_OUT));
}
// Art that reaches the trim edge but leaves part of the page's bleed empty.
@@ -760,7 +761,7 @@ fn pdf_settings(s: &mut Session, p: &Value) -> Result<Value> {
};
note_texts(&notes)
}
_ => set.warnings(),
_ => set.warnings(&ActiveProfiles::default()).into_iter().map(|w| w.message).collect(),
};
let v = serde_json::to_value(&set).map_err(|e| EngineError::Other(e.to_string()))?;
Ok(json!({ "settings": v, "presets": presets(s), "changed": diff, "warnings": warnings }))
+21 -2
View File
@@ -47,6 +47,10 @@ pub struct LoadOptions {
/// A `.ai` opens from its editing copy even where that draws differently from its PDF part
/// (which can be older than it), with a warning, instead of from the PDF part.
pub trust_editing_data: bool,
/// A PDF's type in a font it embeds and this machine lacks is drawn in the file's own glyphs
/// (default; the `embeddedFonts` param, and Preferences › File Handling › Use fonts embedded in
/// imported PDFs for opens and places that give none).
pub embedded_fonts: bool,
/// The encoding names in a `.ai` or EPS's editing data are read in when they aren't UTF-8
/// (`legacyNameEncoding`).
pub legacy_names: vectorcraft_eps::NameEncoding,
@@ -74,6 +78,7 @@ impl Default for LoadOptions {
editing_data: true,
trust_editing_data: false,
legacy_names: vectorcraft_eps::NameEncoding::default(),
embedded_fonts: true,
native: true,
link_pages: false,
}
@@ -84,7 +89,7 @@ impl LoadOptions {
/// From command params: `pages` (`"2-3, 5"`, a page number or `"all"`), `page` (one page, when
/// `pages` isn't given), `cropTo` (or `crop`), `password`, `colorMode` (`rgb` | `cmyk`) with `grays`,
/// `textAs` (`text` | `outlines`), `layers` (true | false), `hiddenLayers` (true | false),
/// `importSlices` (true | false), `editingData` (true | false | `always`),
/// `importSlices` (true | false), `editingData` (true | false | `always`), `embeddedFonts` (true | false),
/// `legacyNameEncoding` (one of [`vectorcraft_eps::NameEncoding::LABELS`]), `linkPages` (true |
/// false) and `dxf` (the DXF import options).
pub fn from_params(cmd: &str, p: &Value) -> Result<Self> {
@@ -135,6 +140,10 @@ impl LoadOptions {
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "linkPages must be true or false"))?,
};
let dxf = super::dxfimport::options(cmd, p.get("dxf"))?;
let embedded_fonts = match p.get("embeddedFonts").filter(|v| !v.is_null()) {
None => true,
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "embeddedFonts must be true or false"))?,
};
Ok(Self {
pages,
crop,
@@ -148,6 +157,7 @@ impl LoadOptions {
dxf,
editing_data,
trust_editing_data,
embedded_fonts,
legacy_names,
native: true,
link_pages,
@@ -177,6 +187,7 @@ impl LoadOptions {
text_as: self.text_as,
layers: self.layers,
uncalibrated_rgb: editor_document,
embedded_fonts: self.embedded_fonts,
..Default::default()
})
}
@@ -219,7 +230,15 @@ pub(crate) fn opened_page_document(bytes: &[u8], opened: &vectorcraft_pdf::Opene
/// The import options of [`page_document`].
fn page_options(page: usize, o: &LoadOptions) -> ImportOptions {
ImportOptions { pages: Some(vec![page]), crop: o.crop, password: o.password.clone(), text_as: o.text_as, layers: false, ..Default::default() }
ImportOptions {
pages: Some(vec![page]),
crop: o.crop,
password: o.password.clone(),
text_as: o.text_as,
layers: false,
embedded_fonts: o.embedded_fonts,
..Default::default()
}
}
/// Whether `document.open`'s `linkPages` takes the file `name` holding `bytes`: a PDF or a
+5 -1
View File
@@ -1148,10 +1148,14 @@ impl SaveJob {
/// Once written: Save and Save As (except to a template) make the file `st`'s own: path,
/// title, format, options, and the snapshot as the saved state (edits made since the job was
/// made keep the document modified; changes that are not edits to save don't,
/// [`DocState::same_content`]).
/// [`DocState::same_content`]). Saved outside a command a script runs, from the document's
/// content as it is now, the document is as the person left it ([`DocState::by_script`]).
pub fn finish(self, st: &mut DocState) {
let retargets = self.plan.retargets();
if let (true, Some(path)) = (retargets, self.plan.path) {
if !crate::file_access::in_script_command() && st.same_content(&self.source) {
st.by_script = None;
}
st.path = Some(path);
st.format = self.plan.format.id;
st.save_options = self.plan.options;
+5 -4
View File
@@ -2,7 +2,8 @@
use serde_json::{Value, json};
use super::pdf::DEFAULT_PRESET;
use vectorcraft_pdf::{APP, default_preset_name};
use super::*;
fn session(artboards: usize) -> Session {
@@ -310,7 +311,7 @@ fn bad_options_are_refused() {
#[test]
fn options_apply_over_the_preset() {
let mut s = session(1);
let a = b64(&export(&mut s, json!({"preset": DEFAULT_PRESET, "compression": {"compressText": false}})));
let a = b64(&export(&mut s, json!({"preset": default_preset_name(APP), "compression": {"compressText": false}})));
let b = b64(&export(&mut s, json!({"preset": "default"})));
assert!(a.len() > b.len(), "content streams left uncompressed");
assert!(String::from_utf8_lossy(&a).contains(" re") || String::from_utf8_lossy(&a).contains(" l"));
@@ -499,7 +500,7 @@ fn pdf_settings_summarise_changes_and_warnings() {
let mut s = Session::new();
let v = s.execute("document.pdfSettings", &json!({})).unwrap();
assert_eq!(v["settings"]["compatibility"], "1.7");
assert_eq!(v["presets"][0], DEFAULT_PRESET);
assert_eq!(v["presets"][0], default_preset_name(APP));
assert_eq!(v["changed"], json!([]));
assert_eq!(v["warnings"], json!([]));
let p = json!({"compatibility": "1.5", "compression": {"compressText": false}, "createLayers": true, "security": {"copy": false, "openPassword": ""}});
@@ -544,5 +545,5 @@ fn formats_list_the_pdf_options() {
assert!(pdf["options"].get(k).is_some(), "{k}");
}
assert_eq!(pdf["options"]["compatibility"]["default"], "1.7");
assert_eq!(pdf["options"]["preset"]["default"], DEFAULT_PRESET);
assert_eq!(pdf["options"]["preset"]["default"], default_preset_name(APP));
}
@@ -3,7 +3,7 @@
use serde_json::{Value, json};
use vectorcraft_doc::NodeKind;
use vectorcraft_pdf::TextAs;
use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf, pdf_with_catalog};
use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf, pdf_with, pdf_with_catalog};
use super::*;
@@ -135,11 +135,12 @@ fn ai_layer_names_are_read_as_pdf_doc_encoding() {
#[test]
fn load_options_read_text_and_layers() {
let o = LoadOptions::from_params("x", &json!({"textAs": "Outlines", "layers": false})).unwrap();
assert_eq!((o.text_as, o.layers), (TextAs::Outlines, false));
let o = LoadOptions::from_params("x", &json!({"textAs": "Outlines", "layers": false, "hiddenLayers": true, "embeddedFonts": false})).unwrap();
assert_eq!((o.text_as, o.layers, o.hidden_layers, o.embedded_fonts), (TextAs::Outlines, false, true, false));
assert!(o.is_partial(), "without its hidden layers, Save doesn't write the file back");
let d = LoadOptions::default();
assert_eq!((d.text_as, d.layers, d.is_partial()), (TextAs::Text, true, false));
assert_eq!((d.hidden_layers, d.embedded_fonts), (false, true));
let n = LoadOptions { native: false, ..Default::default() };
assert!(n.is_partial(), "without the document it carries, Save doesn't write the file back");
}
@@ -180,3 +181,415 @@ fn exports_that_draw_type_in_a_missing_font_say_it_is_the_fallback_font() {
s.execute("text.replaceFont", &json!({"from": {"family": family}, "to": {"family": "Source Serif 4"}})).unwrap();
assert!(!warned(&mut s, json!({"format": "pdf"})), "replaced: nothing is substituted");
}
/// A page in a font the file carries that no machine has (`Zyxwvu-Serif`: a
/// simple TrueType font in WinAnsiEncoding, its program the bundled Source Serif 4's).
fn carried_font_pdf(content: &str, height: f64) -> Vec<u8> {
let data = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/SourceSerif4-Regular.ttf")).unwrap();
let face = vectorcraft_text::FontDb::global().face("Source Serif 4", "Regular").unwrap();
let widths: Vec<String> =
(32u8..=126).map(|c| format!("{:.0}", face.advance(face.glyph_for(char::from(c))) * 1000.0 / face.units_per_em())).collect();
let hex: String = data.iter().map(|b| format!("{b:02x}")).collect();
let n = first_extra(1);
let page = PdfPage { resources: format!("/Font << /F1 {n} 0 R >>"), ..PdfPage::new(300.0, height, content) };
let font = format!(
"<< /Type /Font /Subtype /TrueType /BaseFont /ABCDEF+Zyxwvu-Serif /FirstChar 32 /LastChar 126 /Widths [{}] /Encoding /WinAnsiEncoding /FontDescriptor {} 0 R >>",
widths.join(" "),
n + 1
);
let descriptor = format!(
"<< /Type /FontDescriptor /FontName /ABCDEF+Zyxwvu-Serif /Flags 34 /FontBBox [-500 -300 1500 1000] /ItalicAngle 0 /Ascent 900 /Descent -300 /CapHeight 660 /StemV 80 /FontFile2 {} 0 R >>",
n + 2
);
let file = format!("<< /Length {} /Filter /ASCIIHexDecode >>\nstream\n{hex}>\nendstream", hex.len() + 1);
pdf_with(&[page], &[&font, &descriptor, &file], None)
}
/// The glyphs of the active document's type (document space origins) and how many come from fonts
/// files carried.
fn glyphs(s: &Session) -> (Vec<kurbo::Point>, usize) {
let db = vectorcraft_text::FontDb::global();
let (mut at, mut carried) = (vec![], 0);
s.doc().unwrap().doc.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
for g in vectorcraft_text::layout(db, t).glyphs {
at.push(t.xf * g.origin);
carried += usize::from(db.is_file_font(g.font_id));
}
}
});
(at, carried)
}
/// Type in a font the PDF carries that isn't installed keeps the file's look until it is edited:
/// no export says it is substituted, it saves and reopens so, and it stays listed as missing. Edited,
/// it takes the substitute, which exports then name.
#[test]
fn type_in_a_font_the_pdf_carries_keeps_its_look_until_edited() {
let mut s = Session::new();
let r = open(&mut s, &carried_font_pdf("BT /F1 24 Tf 20 50 Td (Hamburg Zoo) Tj ET", 100.0), json!({})).unwrap();
let fonts = s.execute("text.fonts", &json!({})).unwrap();
let family = fonts[0]["family"].as_str().unwrap().to_string();
assert_eq!(fonts[0]["status"], "missing", "{fonts}");
assert!(r["warnings"].to_string().contains("until their text is edited"), "{r}");
let missing = s.execute("text.missingFonts", &json!({})).unwrap();
assert!(missing["fonts"].to_string().contains(&family), "still missing: {missing}");
let (at, carried) = glyphs(&s);
assert_eq!((at.len(), carried), (11, 11), "every glyph the file's");
let warned = |s: &mut Session| s.execute("document.serialize", &json!({"format": "png"})).unwrap()["warnings"].to_string().contains(&family);
assert!(!warned(&mut s), "drawn as the file draws it: not substituted");
// Saved and opened again: the same.
let native = s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap()["dataBase64"].as_str().unwrap().to_string();
s.execute("document.open", &json!({"name": "kept.vectorcraft", "dataBase64": native})).unwrap();
assert_eq!(glyphs(&s), (at.clone(), carried));
// Edited: the substitute, which exports name, and the font still missing.
let mut id = None;
s.doc().unwrap().doc.walk(|n| {
if matches!(n.kind, NodeKind::Text(_)) {
id = Some(n.id);
}
});
let id = id.unwrap();
let preflight = |s: &mut Session| s.execute("document.preflight", &json!({})).unwrap()["findings"].clone();
assert!(!preflight(&mut s).to_string().contains(&family), "carried font is not substituted");
s.execute("text.setText", &json!({"id": id, "text": "Hamburg Zoo!"})).unwrap();
assert_eq!(glyphs(&s).1, 0, "edited: no glyph from the file's font");
assert!(warned(&mut s), "edited: substituted");
let findings = preflight(&mut s);
assert!(
findings.as_array().unwrap().iter().any(|f| f["code"] == "missingFont"
&& f["name"].as_str().is_some_and(|n| n.contains(&family))
&& f["ids"].as_array().is_some_and(|ids| ids.contains(&json!(id.0)))),
"preflight identifies the substituted text owner: {findings}"
);
assert!(s.execute("text.missingFonts", &json!({})).unwrap()["fonts"].to_string().contains(&family));
// Undone: the file's look again.
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(glyphs(&s), (at, carried));
assert!(!preflight(&mut s).to_string().contains(&family), "undo restores the carried font");
}
#[test]
fn wrapped_carried_font_keeps_pdf_positions_after_native_reopen() {
let db = vectorcraft_text::FontDb::global();
let serif = db.face("Source Serif 4", "Regular").unwrap();
let fallback = db.face(vectorcraft_text::FALLBACK_FAMILY, "Regular").unwrap();
let advance = |face: &vectorcraft_text::FontFace| face.advance(face.glyph_for('H')) / face.units_per_em();
assert!((advance(&serif) - advance(&fallback)).abs() > 0.01, "fixture must differ from the substitute");
let content = "BT /F1 24 Tf 20 160 Td (Hamburg Zoo ) Tj ET BT /F1 24 Tf 20 100 Td (Hamburg Zoo ) Tj ET BT /F1 24 Tf 20 40 Td (Hamburg Zoo) Tj ET";
let bytes = carried_font_pdf(content, 200.0);
let mut reference = Session::new();
open(&mut reference, &bytes, json!({"textAs": "outlines"})).unwrap();
let want = glyph_ink(&reference, false);
assert_eq!(want.len(), 3);
let mut s = Session::new();
open(&mut s, &bytes, json!({})).unwrap();
let compare = |s: &Session| {
let mut areas = 0;
s.doc().unwrap().doc.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
assert!(matches!(t.kind, vectorcraft_doc::TextKind::Area { .. }), "wrapped text must stay one area");
assert_eq!(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).lines.len(), 3);
areas += 1;
}
});
assert_eq!(areas, 1);
let got = glyph_ink(s, false);
assert_eq!(got.len(), want.len());
for (got, want) in got.iter().zip(&want) {
let off = (got.x0 - want.x0).abs().max((got.x1 - want.x1).abs()).max((got.y0 - want.y0).abs()).max((got.y1 - want.y1).abs());
assert!(off < 0.25, "{got:?} is {off} pt from {want:?}");
}
};
compare(&s);
let native = s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap()["dataBase64"].as_str().unwrap().to_string();
s.execute("document.open", &json!({"name": "wrapped.vectorcraft", "dataBase64": native})).unwrap();
compare(&s);
}
fn owned_font_document(family: &str, width: f64) -> (vectorcraft_doc::Document, vectorcraft_doc::ImageBlob, vectorcraft_doc::NodeId) {
use kurbo::{Point, Rect, Shape};
use vectorcraft_doc::{CharStyle, Document, FILE_FONT_MIME, FileFont, FileFonts, ImageBlob, Node, TextObject};
use vectorcraft_text::{FileFontInfo, FileGlyph, build_file_font};
let info = FileFontInfo { family: family.into(), style: "Regular".into(), ..Default::default() };
let g = FileGlyph { ch: 'x', outline: Rect::new(0.0, 0.0, width, 700.0).to_path(0.1), advance: width + 100.0 };
let blob = ImageBlob::new(FILE_FONT_MIME, build_file_font(&info, &[g]).unwrap());
let mut doc = Document::new(100.0, 100.0);
doc.images.insert("chosen".into(), blob.clone());
let mut t = TextObject::point(Point::new(10.0, 40.0), "x", CharStyle { font_family: family.into(), size: 20.0, ..Default::default() });
t.file_fonts = Some(Box::new(FileFonts::new(vec![FileFont { family: family.into(), style: "Regular".into(), key: "chosen".into() }], "x")));
let id = doc.alloc_id();
doc.insert(Some(doc.layers[0].id), usize::MAX, Node::new(id, NodeKind::Text(Box::new(t)))).unwrap();
(doc, blob, id)
}
/// No machine fonts are needed: the two native documents own different synthetic glyphs under
/// the same key. Paste must relink its own bytes, including after closing the source tab.
#[test]
fn owned_file_fonts_survive_native_open_close_clipboard_undo_and_export() {
use vectorcraft_doc::Document;
use vectorcraft_text::FontDb;
const FAMILY: &str = "Native Owned File Font Regression";
let open_native = |s: &mut Session, doc: &Document| {
let bytes = vectorcraft_format::save_file(doc);
s.execute("document.open", &json!({"name": "font.vectorcraft", "dataBase64": vectorcraft_format::base64_encode(&bytes)})).unwrap()
};
let face_of = |s: &Session, id| {
let NodeKind::Text(t) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("text") };
let g = &vectorcraft_text::layout(FontDb::global(), t).glyphs[0];
FontDb::global().face_by_id(g.font_id).unwrap()
};
let (a, a_blob, a_id) = owned_font_document(FAMILY, 200.0);
let (b, b_blob, b_id) = owned_font_document(FAMILY, 800.0);
let mut s = Session::new();
open_native(&mut s, &a);
let a_index = s.active_index().unwrap();
assert_eq!(face_of(&s, a_id).file_data(), a_blob.bytes.as_slice());
open_native(&mut s, &b);
let b_index = s.active_index().unwrap();
let carried = face_of(&s, b_id).id();
assert_eq!(face_of(&s, b_id).file_data(), b_blob.bytes.as_slice());
s.execute("select.set", &json!({"ids": [b_id.0]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
assert!(s.close_document(b_index));
assert!(s.set_active(a_index));
let pasted = s.execute("edit.pasteInPlace", &json!({})).unwrap();
assert!(pasted["warnings"].as_array().unwrap().is_empty(), "{pasted}");
assert!(pasted["renamed"].as_array().unwrap().iter().any(|v| v["kind"] == "image" && v["from"] == "chosen"));
let id = vectorcraft_doc::NodeId(pasted["ids"][0].as_u64().unwrap());
assert_eq!(face_of(&s, id).id(), carried);
assert_eq!(face_of(&s, id).file_data(), b_blob.bytes.as_slice());
assert_eq!(face_of(&s, a_id).file_data(), a_blob.bytes.as_slice());
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(face_of(&s, id).file_data(), b_blob.bytes.as_slice());
for options in [json!({"format": "pdf", "advanced": {"outlineText": false}}), json!({"format": "svg", "embedFonts": true})] {
let svg = options["format"] == "svg";
let exported = s.execute("document.serialize", &options).unwrap();
if svg {
let text = exported["text"].as_str().unwrap();
assert_eq!(text.matches("@font-face").count(), 2, "both distinct owned faces are embedded");
} else {
let bytes = vectorcraft_format::base64_decode(exported["dataBase64"].as_str().unwrap()).unwrap();
assert!(bytes.starts_with(b"%PDF-"));
}
// SVG may warn that the same CSS description cannot distinguish these two x glyphs.
assert!(!exported["warnings"].to_string().contains(vectorcraft_text::FALLBACK_FAMILY), "{exported}");
}
let saved = s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap();
s.execute("document.open", &json!({"name": "pasted.vectorcraft", "dataBase64": saved["dataBase64"]})).unwrap();
assert_eq!(face_of(&s, id).file_data(), b_blob.bytes.as_slice());
assert_eq!(face_of(&s, a_id).file_data(), a_blob.bytes.as_slice());
let mut unowned = b.clone();
unowned.images.clear();
let report = open_native(&mut s, &unowned);
assert!(report["warnings"].to_string().contains(FAMILY));
assert_eq!(glyphs(&s).1, 0, "a metadata-only reference cannot borrow any open document's font");
}
/// Place owns its carried font even after the decoded source is dropped, whether the destination
/// reuses an equal unbound blob or renames a key occupied by another font.
#[test]
fn placed_fonts_keep_owned_bytes_after_resource_reuse_or_name_collision() {
use vectorcraft_doc::Document;
use vectorcraft_text::FontDb;
const FAMILY: &str = "Placed Owned Font Regression";
let (source, expected, _) = owned_font_document(FAMILY, 200.0);
let bytes = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&source));
for same_bytes in [true, false] {
let mut host = Document::new(100.0, 100.0);
let blob = if same_bytes { expected.clone() } else { owned_font_document(FAMILY, 800.0).1 };
host.images.insert("chosen".into(), blob);
let mut s = Session::new();
s.add_document(host, None);
let placed = s.execute("file.place", &json!({"name": "font.vectorcraft", "dataBase64": bytes, "link": false})).unwrap();
assert!(placed["warnings"].as_array().unwrap().is_empty(), "{placed}");
let check = |s: &Session| {
let db = FontDb::global();
let mut drawn = 0;
s.doc().unwrap().doc.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
for g in vectorcraft_text::layout(db, t).glyphs {
assert!(db.is_file_font(g.font_id), "the destination, not a source cache, owns the font");
assert_eq!(db.face_by_id(g.font_id).unwrap().file_data(), expected.bytes.as_slice());
drawn += 1;
}
}
});
assert_eq!(drawn, 1);
};
check(&s);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(glyphs(&s).1, 0);
s.execute("edit.redo", &json!({})).unwrap();
check(&s);
let saved = s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap();
let reopened = s.execute("document.open", &json!({"name": "placed.vectorcraft", "dataBase64": saved["dataBase64"]})).unwrap();
assert!(reopened["warnings"].as_array().unwrap().is_empty(), "{reopened}");
check(&s);
}
}
fn linked_owned_font_document(family: &str) -> (vectorcraft_doc::Document, vectorcraft_doc::ImageBlob, vectorcraft_doc::NodeId) {
use kurbo::Affine;
use vectorcraft_doc::{Document, ImageBlob, LinkInfo, Node, PlacedDocument};
let (source, expected, _) = owned_font_document(family, 200.0);
let bytes = vectorcraft_format::save_file(&source);
let blob = ImageBlob::new("application/json", bytes);
let key = format!("placed-font-{}", blob.content_key());
let mut host = Document::new(100.0, 100.0);
host.images.insert("chosen".into(), owned_font_document(family, 800.0).1);
host.images.insert(key.clone(), blob);
let placed = PlacedDocument {
key,
link: LinkInfo::new("/font-placement-regression.vectorcraft"),
bounding: false,
page_box: Default::default(),
width: 100.0,
height: 100.0,
xf: Affine::IDENTITY,
placement: Default::default(),
};
let id = host.alloc_id();
host.insert(Some(host.layers[0].id), usize::MAX, Node::new(id, NodeKind::PlacedDocument(Box::new(placed)))).unwrap();
(host, expected, id)
}
/// Break Link and older-version saves must preserve the placed file's own bytes rather than bind
/// text to the host's unrelated font under the same key when reopened.
#[test]
fn placed_carried_fonts_survive_break_link_and_older_version_save() {
use vectorcraft_text::FontDb;
for break_link in [true, false] {
let family = if break_link { "Break Link Owned Font Regression" } else { "Older Save Owned Font Regression" };
let (host, expected, id) = linked_owned_font_document(family);
let mut s = Session::new();
s.add_document(host, None);
if break_link {
let embedded = s.execute("links.embed", &json!({"ids": [id.0]})).unwrap();
assert_eq!(embedded["embedded"], json!([id.0]), "{embedded}");
assert_eq!(glyphs(&s).1, 1);
}
let version = if break_link { vectorcraft_format::VERSION } else { vectorcraft_format::VERSION - 1 };
let saved = s.execute("document.serialize", &json!({"format": "vectorcraft", "version": version, "preview": false})).unwrap();
let reopened = s.execute("document.open", &json!({"name": "placed-font.vectorcraft", "dataBase64": saved["dataBase64"]})).unwrap();
assert!(reopened["warnings"].as_array().unwrap().is_empty(), "{reopened}");
let db = FontDb::global();
let mut drawn = 0;
s.doc().unwrap().doc.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
for g in vectorcraft_text::layout(db, t).glyphs {
assert!(db.is_file_font(g.font_id));
assert_eq!(db.face_by_id(g.font_id).unwrap().file_data(), expected.bytes.as_slice(), "{family}");
drawn += 1;
}
}
});
assert_eq!(drawn, 1, "{family}");
assert!(!s.doc().unwrap().doc.has_placed(), "the reopened art is editable, not a linked source");
}
}
/// Glyphs `a`, `b`, `a` in an unavailable carried font, all named `a` by ToUnicode.
fn two_glyphs_for_one_character_pdf(content: &str) -> Vec<u8> {
let data = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/SourceSerif4-Regular.ttf")).unwrap();
let face = vectorcraft_text::FontDb::global().face("Source Serif 4", "Regular").unwrap();
let widths: Vec<String> =
(32u8..=126).map(|c| format!("{:.0}", face.advance(face.glyph_for(char::from(c))) * 1000.0 / face.units_per_em())).collect();
let hex: String = data.iter().map(|b| format!("{b:02x}")).collect();
let n = first_extra(1);
let page = PdfPage { resources: format!("/Font << /F1 {n} 0 R >>"), ..PdfPage::new(400.0, 200.0, content) };
let font = format!(
"<< /Type /Font /Subtype /TrueType /BaseFont /ABCDEF+Zyxwvu-Serif /FirstChar 32 /LastChar 126 /Widths [{}] /Encoding /WinAnsiEncoding /FontDescriptor {} 0 R /ToUnicode {} 0 R >>",
widths.join(" "),
n + 1,
n + 3
);
let descriptor = format!(
"<< /Type /FontDescriptor /FontName /ABCDEF+Zyxwvu-Serif /Flags 34 /FontBBox [-500 -300 1500 1000] /ItalicAngle 0 /Ascent 900 /Descent -300 /CapHeight 660 /StemV 80 /FontFile2 {} 0 R >>",
n + 2
);
let file = format!("<< /Length {} /Filter /ASCIIHexDecode >>\nstream\n{hex}>\nendstream", hex.len() + 1);
let cmap = "/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CMapName /Adobe-Identity-UCS def /CMapType 2 def 1 begincodespacerange <00> <FF> endcodespacerange 2 beginbfchar <61> <0061> <62> <0061> endbfchar endcmap CMapName currentdict /CMap defineresource pop end end";
let tounicode = format!("<< /Length {} >>\nstream\n{cmap}\nendstream", cmap.len() + 1);
pdf_with(&[page], &[&font, &descriptor, &file, &tounicode], None)
}
/// The three glyph ink boxes, grouped by x for the TJ fixture or by y for separate lines.
fn glyph_ink(s: &Session, across: bool) -> Vec<kurbo::Rect> {
use kurbo::Shape;
let db = vectorcraft_text::FontDb::global();
let mut lines: [Option<kurbo::Rect>; 3] = [None; 3];
let mut add = |path: &kurbo::BezPath| {
let els = path.elements();
let mut start = 0;
for end in (1..=els.len()).filter(|&e| e == els.len() || matches!(els[e], kurbo::PathEl::MoveTo(_))) {
let ink = kurbo::BezPath::from_vec(els[start..end].to_vec()).bounding_box();
let line = if across {
usize::from(ink.center().x > 90.0) + usize::from(ink.center().x > 230.0)
} else {
usize::from(ink.center().y > 70.0) + usize::from(ink.center().y > 130.0)
};
lines[line] = Some(lines[line].map_or(ink, |l| l.union(ink)));
start = end;
}
};
s.doc().unwrap().doc.walk(|n| match &n.kind {
NodeKind::Text(t) => vectorcraft_text::layout(db, t).glyphs.iter().for_each(|g| add(&(t.xf * g.outline.clone()))),
NodeKind::Path { path, .. } => add(&path.to_bezpath()),
_ => {}
});
lines.into_iter().flatten().collect()
}
/// Two different glyphs of a carried font for one character can't both go into the font kept with
/// the document, which has one glyph per character, so the line with the other glyph is outlines.
/// Opened, saved in the native format and opened again, each glyph is still the one the file draws,
/// where it draws it: the same page opened as outlines is the reference.
#[test]
fn two_glyphs_for_one_character_survive_a_native_save_and_reopen() {
let content = "BT /F1 30 Tf 20 160 Td (a) Tj ET BT /F1 30 Tf 20 100 Td (b) Tj ET BT /F1 30 Tf 20 40 Td (a) Tj ET";
assert_carried_glyph_roundtrip(content, false);
}
#[test]
fn conflicting_carried_glyphs_in_a_filled_and_stroked_tj_survive_native_reopen() {
let content = "BT 2 Tr /F1 30 Tf 20 100 Td [(a) -3500 (b) -3500 (a)] TJ 0 Tr ET";
assert_carried_glyph_roundtrip(content, true);
}
fn assert_carried_glyph_roundtrip(content: &str, across: bool) {
let bytes = two_glyphs_for_one_character_pdf(content);
let mut reference_session = Session::new();
open(&mut reference_session, &bytes, json!({"textAs": "outlines"})).unwrap();
let reference = glyph_ink(&reference_session, across);
assert_eq!(reference.len(), 3, "the file draws three glyphs: {reference:?}");
assert!((reference[0].height() - reference[1].height()).abs() > 2.0, "the file's two glyphs differ in shape: {reference:?}");
assert!((reference[0].height() - reference[2].height()).abs() < 0.01, "the first and third are the same glyph: {reference:?}");
let mut s = Session::new();
open(&mut s, &bytes, json!({})).unwrap();
assert!(
live_texts(&s).iter().any(|t| t == "a") && live_texts(&s).len() < 3,
"some glyphs stay type, the other is outlines: {:?}",
live_texts(&s)
);
let close = |s: &Session, what: &str| {
let got = glyph_ink(s, across);
assert_eq!(got.len(), reference.len(), "{what}: {got:?}");
for (got, want) in got.iter().zip(&reference) {
let off = (got.x0 - want.x0).abs().max((got.x1 - want.x1).abs()).max((got.y0 - want.y0).abs()).max((got.y1 - want.y1).abs());
assert!(off < 0.25, "{what}: {got:?} is {off} pt from the file's {want:?}");
}
};
close(&s, "opened");
let native = s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap()["dataBase64"].as_str().unwrap().to_string();
s.execute("document.open", &json!({"name": "kept.vectorcraft", "dataBase64": native})).unwrap();
close(&s, "saved and reopened");
}
@@ -405,9 +405,9 @@ fn zipped_and_32_bit_layers_read() {
/// A layer without a Unicode name takes the name its Pascal string holds, read as Mac Roman.
#[test]
fn names_without_a_unicode_name_read_as_mac_roman() {
let l = L { legacy: Some(b"Caf\x8E \xD2Old\xD3"), ..layer("", [0, 0, 1, 1], [0, 0, 0, 255]) };
let l = L { legacy: Some(b"Caf\x8E\xCA\xD2Old\xD3\xDB"), ..layer("", [0, 0, 1, 1], [0, 0, 0, 255]) };
let (s, r) = open(&file(1, 1, &[l], 8, false, false), json!({}));
assert_eq!(name(&s.doc().unwrap().doc.layers[0]), "Café “Old”", "{r}");
assert_eq!(name(&s.doc().unwrap().doc.layers[0]), "Café\u{a0}“Old”€", "{r}");
}
#[test]
+5
View File
@@ -1154,11 +1154,16 @@ fn drop_own_overprints(n: &mut Node) {
(r.style.overprint_fill, r.style.overprint_stroke) = (false, false);
}
}
// An image keeps the flag after its color is removed, and a later color would overprint.
if n.extras().colorize_overprint {
n.extras_mut().colorize_overprint = false;
}
}
}
fn overprints(n: &Node) -> bool {
n.appearance.items.iter().any(AppearanceItem::overprint)
|| n.extras().colorize_overprint
|| matches!(&n.kind, NodeKind::Text(t) if t.runs.iter().any(|r| r.style.overprint_fill || r.style.overprint_stroke))
}
+29 -9
View File
@@ -484,10 +484,17 @@ pub(super) fn used_fonts(d: &Document) -> BTreeSet<UsedFont> {
/// in `art` (art read from a file, its resources in `d`), the type in opacity masks included. The
/// pattern being edited is read from the editing layer only.
pub(super) fn art_fonts(d: &Document, art: &[Node]) -> BTreeSet<UsedFont> {
fonts_of(d, art, false)
}
/// [`art_fonts`]; `drawn`: only those the type is drawn in, not the fonts of runs drawn in a font
/// their file carried ([`in_file_fonts`]).
fn fonts_of(d: &Document, art: &[Node], drawn: bool) -> BTreeSet<UsedFont> {
let mut fonts = BTreeSet::new();
let mut add = |n: &Node| {
if let NodeKind::Text(t) = &n.kind {
fonts.extend(t.runs.iter().flat_map(run_fonts));
let file = if drawn { in_file_fonts(t) } else { vec![] };
fonts.extend(t.runs.iter().filter(|r| !file.contains(&(r.style.font_family.as_str(), r.style.font_style.as_str()))).flat_map(run_fonts));
}
};
let patterns = d.patterns.iter().filter(|p| !pattern_being_edited(d, &p.name)).flat_map(|p| p.art.iter().map(|a| &**a));
@@ -659,21 +666,25 @@ impl<'a> Printed<'a> {
}
}
match &n.kind {
NodeKind::Text(_) => {
NodeKind::Text(t) => {
if overflows && self.own {
self.overflow.insert(n.id);
}
if overflows && let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) {
p.overflow.insert(owner);
}
let file = in_file_fonts(t);
for r in runs {
let fonts = run_fonts(r);
if let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) {
for font in &fonts {
p.fonts.entry(font.clone()).or_default().insert(owner);
// Drawn in a font its file carried: printed as the file drew it.
if !file.contains(&(r.style.font_family.as_str(), r.style.font_style.as_str())) {
let fonts = run_fonts(r);
if let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) {
for font in &fonts {
p.fonts.entry(font.clone()).or_default().insert(owner);
}
}
self.fonts.extend(fonts);
}
self.fonts.extend(fonts);
// Inline graphics draw their symbols' art.
if let Some(art) = r.inline.as_ref().filter(|_| draws_inline(r)) {
self.symbol(&art.symbol);
@@ -757,9 +768,18 @@ fn drawn_runs(t: &vectorcraft_doc::TextObject) -> (Vec<&TextRun>, bool) {
/// What an export that draws type (as outlines, embedded fonts or pixels) says when `d` uses font
/// families that aren't available (their type is drawn in the fallback font, not the font it
/// names) or styles that its family doesn't have (the closest style is drawn).
/// names) or styles that its family doesn't have (the closest style is drawn). Type drawn in a
/// font its file carried isn't substituted.
pub(super) fn substitution_warning(d: &Document) -> Option<String> {
substitution_warning_of(used_fonts(d))
substitution_warning_of(fonts_of(d, &[], true))
}
/// The families and styles of the runs of `t` drawn in a font its file carried
/// ([`vectorcraft_text::FontDb::file_faces`]): drawn as the file drew them, not in a substitute,
/// though the font they name isn't available.
fn in_file_fonts(t: &vectorcraft_doc::TextObject) -> Vec<(&str, &str)> {
let faces = vectorcraft_text::FontDb::global().file_faces(t);
t.runs.iter().zip(faces).filter(|(_, f)| f.is_some()).map(|(r, _)| (r.style.font_family.as_str(), r.style.font_style.as_str())).collect()
}
/// [`substitution_warning`] for type set in `fonts`.
+1 -1
View File
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Gradient",
["Window", "Gradient"],
None,
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds; an error when no object is edited, as with nothing selected, the Live Paint Bucket's gradient, or a fill edit of a Live Paint group without faces: the default gradient fits each new object and keeps no aspect), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. Without `item`, a Live Paint group's faces take a fill edit and its edges take a stroke edit. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without its placement, fitted to each label. While the Live Paint Bucket is the active tool and no ids, id or i Line truncated
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds; an error when no object is edited, as with nothing selected, the Live Paint Bucket's gradient, or a fill edit of a Live Paint group without faces: the default gradient fits each new object and keeps no aspect), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, defaultsOnly?: bool (as paint.setFill), strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. Without `item`, a Live Paint group's faces take a fill edit and its edges take a stroke edit. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without its placement, fitted to each label. While the Live Paint Bucke Line truncated
has_doc,
edit_gradient
),
+1 -1
View File
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Apply Gradient Preset",
[],
None,
"{name: a preset's name (gradient.presets.list), stroke?, item?, ids?|id?, target? (as paint.editGradient)} give the gradient behind the active proxy (or the targeted fill or stroke) the preset's type, stops, method, spread and repeats (a freeform preset's: the first three), and a fill its dither, keeping its placement; a solid or no paint becomes the gradient. One undo step, as paint.editGradient (while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the default changes, by the active proxy) → {name, ids: the objects painted (none: only the default changed)}",
"{name: a preset's name (gradient.presets.list), stroke?, item?, ids?|id?, defaultsOnly?, target? (as paint.editGradient)} give the gradient behind the active proxy (or the targeted fill or stroke) the preset's type, stops, method, spread and repeats (a freeform preset's: the first three), and a fill its dither, keeping its placement; a solid or no paint becomes the gradient. One undo step, as paint.editGradient (while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, only the default changes, by the active proxy) → {name, ids: the objects painted (none: only the default changed)}",
has_doc,
apply
),
+1 -1
View File
@@ -447,7 +447,7 @@ fn locate(s: &mut Session, p: &Value) -> Result<Value> {
}
let row = ancestry.last().copied().ok_or(EngineError::NoNode(id))?;
st.layer_rows = vec![row];
st.locate_reveal = Some(row);
st.layers_reveal = Some(crate::LayersReveal::Row(row));
st.revision += 1;
let ancestry: Vec<u64> = ancestry.iter().map(|i| i.0).collect();
Ok(if layers_only { json!({ "id": row.0, "objectId": id.0, "ancestry": ancestry }) } else { json!({ "id": id.0, "ancestry": ancestry }) })
+15 -11
View File
@@ -712,7 +712,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Use Library Item",
[],
None,
"{library?, kind, item: name (graphic: id or name), center?: [x, y] (graphic; default: the first artboard's centre), to?: fill|stroke (colors, gradients, patterns; default: the kind's), recorded?: the item as it was when used (recorded in the journal so a replay matches)} graphic: place a copy centred on `center`, its resources pasted along, selected, one undo step; colors and gradients: paint the selection (and the defaults) as paint.setFill/paint.setStroke, a gradient fitting each object; a spot color links to the document's spot swatch of its ink's name, added when the document has none of that colour (a name taken by another colour gets a number), one undo step; patterns: add the pattern and its swatch to the document (a name the document gives another pattern gets a number; the same pattern is reused, also when its art links to the document's own color of a name; a global or spot color its art links to whose name the document gives another color comes in numbered, or as the document's numbered copy of the same color, and the pattern links to it) and paint the selection (and the defaults) with it, one undo step; charStyle/paraStyle: add the style to the document (a name taken by different attributes gets a number; a character style's color linked to a swatch that isn't a global or spot swatch of the document keeps the color it shows, unlinked) and apply it to the selected text, one undo step → {kind, ids?, style?}",
"{library?, kind, item: name (graphic: id or name), center?: [x, y] (graphic; default: the first artboard's centre), to?: fill|stroke (colors, gradients, patterns; default: the kind's), defaultsOnly?: bool (colors, gradients, patterns: paint only the defaults, as with paint.setFill's; the journal records it for an item used while the Live Paint Bucket is the active tool), recorded?: the item as it was when used (recorded in the journal so a replay matches)} graphic: place a copy centred on `center`, its resources pasted along, selected, one undo step; colors and gradients: paint the selection (and the defaults) as paint.setFill/paint.setStroke, a gradient fitting each object; a spot color links to the document's spot swatch of its ink's name, added when the document has none of that colour (a name taken by another colour gets a number), one undo step; patterns: add the pattern and its swatch to the document (a name the document gives another pattern gets a number; the same pattern is reused, also when its art links to the document's own color of a name; a global or spot color its art links to whose name the document gives another color comes in numbered, or as the document's numbered copy of the same color, and the pattern links to it) and paint the selection (and the defaults) with it, one undo step; charStyle/paraStyle: add the style to the document (a name taken by different attributes gets a number; a character style's color linked to a swatch that isn't a global or spot swatch of the document keeps the color it shows, unlinked) and apply it to the selected text, one undo step → {kind, ids?, style?}",
has_doc,
use_item
),
@@ -1185,6 +1185,7 @@ fn item_param<'a>(s: &Session, p: &'a Value, cmd: &str) -> Result<(String, Kind,
fn use_item(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "library.use";
super::switch_or(p, "defaultsOnly", false, C)?;
// A replay (the journal) carries what the item was, so it doesn't depend on the library.
let recorded = p.get("recorded").cloned();
let (kind, data) = match recorded {
@@ -1246,18 +1247,20 @@ fn use_item(s: &mut Session, p: &Value) -> Result<Value> {
}
Kind::FillColor | Kind::StrokeColor => {
let stroke = to_stroke(p, kind)?;
let only = super::paint::defaults_only(s, p, C)?;
let color = data.get("color").cloned().ok_or_else(|| bad(C, "no colour"))?;
let set = if stroke { "paint.setStroke" } else { "paint.setFill" };
match str_param(&data, "spot").map(str::trim).filter(|n| !n.is_empty()) {
Some(ink) => use_spot(s, set, ink, &color, &data)?,
Some(ink) => use_spot(s, set, ink, &color, &data, only)?,
None => {
s.execute(set, &json!({ "color": color }))?;
s.execute(set, &super::paint::with_defaults_only(json!({ "color": color }), only))?;
}
}
Ok(json!({ "kind": if stroke { "strokeColor" } else { "fillColor" } }))
}
Kind::FillGradient | Kind::StrokeGradient => {
let stroke = to_stroke(p, kind)?;
let only = super::paint::defaults_only(s, p, C)?;
let damaged = || bad(C, "the library item is damaged");
let mut g: GradientPaint = data.get("gradient").cloned().and_then(|v| serde_json::from_value(v).ok()).ok_or_else(damaged)?;
if !clean_gradient(&mut g) {
@@ -1267,12 +1270,13 @@ fn use_item(s: &mut Session, p: &Value) -> Result<Value> {
for st in &mut g.gradient.stops {
st.color = super::paint::new_color(s, &json!({}), st.color);
}
super::paint::apply_paint(s, &json!({}), Paint::Gradient(Box::new(g)), !stroke)?;
super::paint::apply_paint(s, &super::paint::with_defaults_only(json!({}), only), Paint::Gradient(Box::new(g)), !stroke)?;
Ok(json!({ "kind": if stroke { "strokeGradient" } else { "fillGradient" } }))
}
Kind::FillPattern | Kind::StrokePattern => {
let stroke = to_stroke(p, kind)?;
let pattern = use_pattern(s, &data, stroke)?;
let only = super::paint::defaults_only(s, p, C)?;
let pattern = use_pattern(s, &data, stroke, only)?;
Ok(json!({ "kind": if stroke { "strokePattern" } else { "fillPattern" }, "pattern": pattern }))
}
Kind::CharStyle | Kind::ParaStyle => {
@@ -1303,8 +1307,8 @@ fn use_item(s: &mut Session, p: &Value) -> Result<Value> {
/// Paint with library spot colour `ink` (`color` its full-strength colour, `data`'s `tint` its
/// tint) through `set` (paint.setFill or paint.setStroke), linked to the document's spot swatch of
/// that name: the one it has when it is the same colour, else a new one (a name taken by another
/// colour gets a number), one undo step (#5812).
fn use_spot(s: &mut Session, set: &str, ink: &str, color: &Value, data: &Value) -> Result<()> {
/// colour gets a number), one undo step (#5812). With `only`, only the default takes it.
fn use_spot(s: &mut Session, set: &str, ink: &str, color: &Value, data: &Value, only: bool) -> Result<()> {
const C: &str = "library.use";
let c = color_value(color).ok_or_else(|| bad(C, "the library item is damaged"))?;
let tint = data.get("tint").and_then(Value::as_f64).filter(|t| t.is_finite()).map_or(1.0, |t| t.clamp(0.0, 1.0));
@@ -1321,7 +1325,7 @@ fn use_spot(s: &mut Session, set: &str, ink: &str, color: &Value, data: &Value)
if tint < 1.0 {
p["tint"] = json!(tint * 100.0);
}
s.execute(set, &p)?;
s.execute(set, &super::paint::with_defaults_only(p, only))?;
Ok(())
})
}
@@ -1339,8 +1343,8 @@ fn to_stroke(p: &Value, kind: Kind) -> Result<bool> {
/// Add library pattern `data` (`{pattern, data}`) to the document, with its swatch and the
/// resources its art uses (the same pattern there already is reused; a name the document gives
/// another one gets a number), and paint the selection's fill (`stroke`: stroke) and the default
/// with it, one undo step → the pattern's name in the document.
fn use_pattern(s: &mut Session, data: &Value, stroke: bool) -> Result<String> {
/// with it (with `only`, only the default), one undo step → the pattern's name in the document.
fn use_pattern(s: &mut Session, data: &Value, stroke: bool, only: bool) -> Result<String> {
const C: &str = "library.use";
let damaged = || bad(C, "the library item is damaged");
let bytes = data.get("data").and_then(Value::as_str).and_then(vectorcraft_format::base64_decode).ok_or_else(damaged)?;
@@ -1378,7 +1382,7 @@ fn use_pattern(s: &mut Session, data: &Value, stroke: bool) -> Result<String> {
}
// The pattern itself, not a swatch of its name (a color swatch can share it); `swatch` keeps
// the placement of a pattern the targets already have, as picking its swatch does.
super::paint::apply_paint(s, &json!({ "swatch": target }), paint.clone(), !stroke)
super::paint::apply_paint(s, &super::paint::with_defaults_only(json!({ "swatch": target }), only), paint.clone(), !stroke)
})?;
Ok(target)
}
+30 -2
View File
@@ -328,7 +328,12 @@ impl<'a> LinkBase<'a> {
/// The open document `st`'s. One with no file of its own looks beside the file it was read from.
pub(crate) fn of(st: &'a crate::DocState) -> Self {
let (path, from) = (st.path.as_deref(), st.links_from.as_deref());
Self::of_files(st.path.as_deref(), st.links_from.as_deref())
}
/// An open document's, by its own file `path` and the file it was read from, `from`
/// ([`crate::DocState::links_from`]), as [`Self::of`] gives them.
pub(crate) fn of_files(path: Option<&'a str>, from: Option<&'a str>) -> Self {
Self { doc: path.or(from), relative: from.or(path) }
}
}
@@ -401,6 +406,29 @@ fn locate(link: &LinkInfo, base: LinkBase) -> Option<Found> {
Some(f)
}
/// The files the links of `d` (a document looking from `base`) lead to now: where [`locate`]
/// finds each linked image's and placed document's file from `base` and from no document (as
/// output reads them, [`full_linked_images`]), the plate files of their own of images placed from
/// DCS files, and the image files its data sets name. The commands a script runs may read these
/// for the documents open when the run began, as the person left them
/// ([`crate::file_access::ScriptGate::linked`]).
pub(crate) fn files_linked(d: &Document, base: LinkBase) -> Vec<String> {
let mut out = vec![];
for g in groups(d, None) {
for from in [base, LinkBase::default()] {
let Some(f) = locate(&g.link, from) else { continue };
out.extend(g.plate_files.iter().filter_map(|p| super::place::dcs::plate_file_path(&f.path, &p.name)));
out.push(f.path);
}
}
let values = d.variables.datasets.iter().flat_map(|set| set.values.values());
out.extend(values.filter_map(|v| match v {
DataValue::Image(path) => fileio::document_path(path, base.doc).ok(),
_ => None,
}));
out
}
/// The place `stored` names from the file `from`, as `resolve` ([`fileio::document_path`]) follows
/// it, when it also follows that place from the document's own file `doc`: a network share the
/// document is no longer on is refused.
@@ -563,7 +591,7 @@ pub(crate) fn full_linked_images<'a>(d: &'a Document, base: LinkBase) -> (Cow<'a
Some(f) if img.blob.bytes.as_slice() == bytes.as_slice() => f.mime.to_string(),
_ => img.blob.mime.clone(),
};
out.images.insert(key, ImageBlob { mime, bytes: img.blob.bytes, proxy: preview });
out.images.insert(key, ImageBlob { mime, bytes: img.blob.bytes, proxy: preview, file_font: Default::default() });
}
let mut warnings = vec![];
match previews.len() {
+67 -8
View File
@@ -13,14 +13,29 @@
//! resets new art when it opens such a document.
use std::borrow::Cow;
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::{BlendMode, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, ColorMode, DEFAULT_GRAPHIC_STYLE, Document, FillLayer, GraphicStyle, Node, NodeKind, StrokeLayer};
use vectorcraft_tools::PaintDefaults;
/// The object new art takes its appearance from, with that appearance
/// ([`Session::new_art_source`]).
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct NewArtSource {
doc: u64,
id: vectorcraft_doc::NodeId,
appearance: Appearance,
opacity: f32,
blend: BlendMode,
style: Option<String>,
}
use super::gradient::unplaced;
use super::paint::SelectionPaints;
use super::{CommandSpec, Result, Session, always, cmd, switch_or};
use crate::doc_state::{SelectionRecord, objects_only};
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -207,16 +222,35 @@ impl Session {
/// After each command: with New Art Has Basic Appearance off, new art takes the appearance of
/// the first selected object (so the last selection's once nothing is selected). Not while the
/// Live Paint Bucket is the active tool: the fill and stroke are the colors it paints with.
/// Live Paint Bucket is the active tool: the fill and stroke are the colors it paints with. Nor
/// after a command that changed only them (`defaultsOnly`), unless a later step of a batch
/// changed what new art would take ([`Session::new_art_source`]).
pub(crate) fn inherit_new_art(&mut self) {
if self.prefs.new_art_basic || self.bucket_paints() {
return;
}
let Some(st) = self.active() else { return };
let Some(n) = st.selection.subjects().first().and_then(|id| st.doc.node(*id)) else { return };
let style = super::style::linked_style(&st.doc, n).map(|g| g.name.clone());
let (ap, opacity, blend) = (super::style::captured(n), n.opacity, n.blend);
self.take_new_art(ap, opacity, blend, style, true);
let Some(source) = self.new_art_source() else { return };
if matches!(&self.defaults_only_ran, Some(Some(ran)) if *ran == source) {
return;
}
let NewArtSource { appearance, opacity, blend, style, .. } = source;
self.take_new_art(appearance, opacity, blend, style, true);
}
/// What [`Session::inherit_new_art`] gives new art: the appearance of the active document's
/// first selected object, if any.
pub(crate) fn new_art_source(&self) -> Option<NewArtSource> {
let st = self.active()?;
let id = *st.selection.subjects().first()?;
let n = st.doc.node(id)?;
Some(NewArtSource {
doc: st.uid,
id,
appearance: super::style::captured(n),
opacity: n.opacity,
blend: n.blend,
style: super::style::linked_style(&st.doc, n).map(|g| g.name.clone()),
})
}
/// After a command changed the selection, with New Art Has Basic Appearance on: the fill and
@@ -236,9 +270,10 @@ impl Session {
if !has_paint {
return;
}
let (fill_mixed, stroke_mixed) = self.proxy_mixed();
let read = self.read_selection_paints();
let (fill_mixed, stroke_mixed) = read.as_ref().map_or_else(|| self.proxy_mixed(), |p| (p.fill_mixed, p.stroke_mixed));
let (fill, stroke) = self.proxy_paints();
let weight_mixed = self.active().is_some_and(|st| st.stroke_mixed().weight);
let weight_mixed = read.as_ref().map_or_else(|| self.active().is_some_and(|st| st.stroke_mixed().weight), |p| p.weight_mixed);
let weight = self.shown_stroke().filter(|st| st.paint != Paint::None && !weight_mixed).map(|st| st.width);
if !fill_mixed {
self.paint.fill = unplaced(&fill);
@@ -250,6 +285,30 @@ impl Session {
self.paint.stroke_width = width;
}
}
/// The [`SelectionPaints`] of the active document's selection, read now and kept in its
/// [`SelectionRecord`] when the record holds none. `None` when anything besides whole objects
/// is selected ([`objects_only`]), with an active Appearance item, when a selected object is in
/// a Live Paint group, and with gradient mesh points picked: the proxies then read the
/// selection with [`Session::proxy_mixed`] and [`crate::DocState::stroke_mixed`]. While the
/// Live Paint Bucket paints, [`Session::load_selection_paints`] returns before reading them.
fn read_selection_paints(&mut self) -> Option<SelectionPaints> {
if self.appearance_item().is_some() {
return None;
}
let st = self.active_mut()?;
if !objects_only(&st.selection) {
return None;
}
if st.selection_paints().is_none() {
let paints = SelectionPaints::of(&st.doc, &st.selection.objects);
let settled = st.selection_record().and_then(|r| r.settled);
st.selection_record =
Some(SelectionRecord { doc: Arc::downgrade(&st.doc), objects: st.selection.objects.clone(), settled, paints: Some(paints) });
}
let paints = st.selection_paints()?.clone();
(!paints.in_live_paint && self.fill_mesh_points().is_empty()).then_some(paints)
}
}
fn set_basic(s: &mut Session, p: &Value) -> Result<Value> {
+2 -1
View File
@@ -960,10 +960,11 @@ impl Session {
let bytes = crate::store::read_capped(&path, MAX_PROFILE_BYTES)?;
// The color profiles the file carries are installed where missing, as opening it installs
// them, so the new document's assigned profiles draw and are saved with it.
let (mut doc, _, warnings) = super::fileio::native_file(&bytes).map_err(|e| e.to_string())?;
let (mut doc, _, mut warnings) = super::fileio::decode_native_file(&bytes).map_err(|e| e.to_string())?;
// Linked images in its symbols, patterns and brushes are read from their files, as placing
// a document reads them.
super::links::resolve(&mut doc, super::links::LinkBase::file(Some(&file)), false, false);
warnings.extend(vectorcraft_text::FontDb::global().bind_document_file_fonts(&mut doc));
Ok(Some(ReadProfile { doc, file, warnings }))
}
}
+14 -1
View File
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Overprint",
[],
None,
"{fill?: bool, stroke?: bool, item?: appearance item index|null, ids?|id?, target?: \"object\"|\"contents\"} make fills and/or strokes overprint (Overprint Preview, Separations Preview) or knock out: item's, else every fill or stroke of the painted objects (groups: their contents; type: its characters too). Without item and ids, the Appearance panel's active item stands in when it is of that kind. A whole Live Paint group (also its contents with `item`) takes the fill flags on its faces and the stroke flags on its edges, and its hidden source paths keep theirs → {changed: objects}",
"{fill?: bool, stroke?: bool, item?: appearance item index|null, ids?|id?, target?: \"object\"|\"contents\"} make fills and/or strokes overprint (Overprint Preview, Separations Preview) or knock out: item's, else every fill or stroke of the painted objects (groups: their contents; type: its characters too; a grayscale or 1-bit image colorized by paint.setFill: without item, the fill flags set whether its color overprints). Without item and ids, the Appearance panel's active item stands in when it is of that kind. A whole Live Paint group (also its contents with `item`) takes the fill flags on its faces and the stroke flags on its edges, and its hidden source paths keep theirs → {changed: objects}",
has_doc,
set_overprint
),
@@ -97,9 +97,18 @@ fn flags(n: &Node, fill: bool, index: Option<usize>) -> Vec<bool> {
if let (None, NodeKind::Text(t)) = (index, &n.kind) {
v.extend(t.runs.iter().map(|r| if fill { r.style.overprint_fill } else { r.style.overprint_stroke }));
}
if fill && index.is_none() && colorized(n) {
v.push(n.extras().colorize_overprint);
}
v
}
/// Is `n` an image colorized with a color, whose fill overprint is its color's
/// ([`vectorcraft_doc::NodeExtras::colorize_overprint`])?
fn colorized(n: &Node) -> bool {
matches!(n.kind, NodeKind::Image(_)) && n.extras().colorize.as_deref().is_some_and(|p| !p.is_none())
}
/// [`flags`], to change.
fn flags_mut(n: &mut Node, fill: bool, index: Option<usize>) -> Vec<&mut bool> {
let mut v: Vec<&mut bool> = n
@@ -178,6 +187,10 @@ pub(super) fn apply_overprint(d: &mut Document, jobs: &[OverprintJob], cmd: &str
changed.insert(*id);
}
}
if *fill && index.is_none() && colorized(n) && n.extras().colorize_overprint != *on {
n.extras_mut().colorize_overprint = *on;
changed.insert(*id);
}
}
}
Ok(())
+183 -27
View File
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Fill",
[],
None,
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the default changes (the color the bucket paints with) and the selection keeps its paint → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}",
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), ids?|id?, defaultsOnly?: bool, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, only the default changes (the color the bucket paints with) and the selection keeps its paint; `defaultsOnly` with ids, id or item is refused, and the journal records a change the bucket made this way with `defaultsOnly: true`, so a replay with another tool active changes the default too → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}",
has_doc,
|s, p| set_paint(s, p, true)
),
@@ -45,7 +45,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Swap Fill and Stroke",
[],
Some("Shift+X"),
"{ids?|id?} swap the fill and stroke of the selection (type too) and of the defaults. A Live Paint group's faces take the stroke its edges share and its edges take the fill its faces share, a gradient fitted to each face or edge; a group whose faces' fills or edges' strokes differ (a freeform gradient counts as differing), or that has no face or no edge, keeps its paint. On a path directly in a graph series, the graph also stores the swapped paints and the stroke weight, and on a graph label the swapped paints of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring what the swap changes on its rows for every line of its kind (exceptions: docs/mcp.md). While the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), only the defaults change",
"{ids?|id?, defaultsOnly?: bool} swap the fill and stroke of the selection (type too) and of the defaults. A Live Paint group's faces take the stroke its edges share and its edges take the fill its faces share, a gradient fitted to each face or edge; a group whose faces' fills or edges' strokes differ (a freeform gradient counts as differing), or that has no face or no edge, keeps its paint. On a path directly in a graph series, the graph also stores the swapped paints and the stroke weight, and on a graph label the swapped paints of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring what the swap changes on its rows for every line of its kind (exceptions: docs/mcp.md). While the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), or `defaultsOnly: true` is given, only the defaults change",
has_doc,
swap
),
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Default Fill and Stroke",
[],
Some("D"),
"{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults (in a document whose Default Graphic Style differs from the shipped one, as a New Document profile can redefine it: that style's fills, strokes and effects, without its opacity or a link to it); type gets black fill and no stroke. A Live Paint group's faces get no fill and its edges get a 0.5 pt black stroke, in place of their whole appearance and also when the Default Graphic Style is redefined, and with only Live Paint groups selected (or in ids) the defaults become no fill and a 0.5 pt black stroke (with New Art Has Basic Appearance off, new art then takes the selection's appearance, as after any command). On a 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 on a graph label the black fill and no stroke of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (exceptions: docs/mcp.md). While the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), only the defaults change",
"{ids?|id?, defaultsOnly?: bool} white fill and 1 pt black stroke for the selection and the defaults (in a document whose Default Graphic Style differs from the shipped one, as a New Document profile can redefine it: that style's fills, strokes and effects, without its opacity or a link to it); type gets black fill and no stroke. A Live Paint group's faces get no fill and its edges get a 0.5 pt black stroke, in place of their whole appearance and also when the Default Graphic Style is redefined, and with only Live Paint groups selected (or in ids) the defaults become no fill and a 0.5 pt black stroke (with New Art Has Basic Appearance off, new art then takes the selection's appearance, as after any command). On a 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 on a graph label the black fill and no stroke of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (exceptions: docs/mcp.md). While the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), or `defaultsOnly: true` is given, only the defaults change",
has_doc,
default_paint
),
@@ -75,11 +75,12 @@ pub fn specs() -> Vec<CommandSpec> {
"None",
[],
Some("/"),
"{} set the active proxy (fill or stroke) to None, as paint.setFill or paint.setStroke with none does (while the Live Paint Bucket is the active tool, only the default changes) → {objects}",
"{defaultsOnly?: bool} set the active proxy (fill or stroke) to None, as paint.setFill or paint.setStroke with none does (while the Live Paint Bucket is the active tool, or with `defaultsOnly: true`, only the default changes) → {objects}",
has_doc,
|s, _| {
|s, p| {
let f = s.fill_active;
set_paint(s, &json!({"none": true}), f)
let only = switch_or(p, "defaultsOnly", false, "paint.none")?;
set_paint(s, &with_defaults_only(json!({"none": true}), only), f)
}
),
cmd!(
@@ -102,7 +103,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
"Invert",
[],
None,
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents and, except with target \"contents\", their own fills and strokes; a compound path's member stands for its compound path; a Live Paint group recolors its faces' fills or its edges' strokes) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, or while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md); no undo step when no color changes → {changed}",
"{stroke?: bool (default: the active proxy), ids?|id?, defaultsOnly?: bool, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents and, except with target \"contents\", their own fills and strokes; a compound path's member stands for its compound path; a Live Paint group recolors its faces' fills or its edges' strokes) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, or while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md); no undo step when no color changes → {changed}",
has_doc,
|s, p| proxy_recolor(s, p, "paint.invert", "Invert", &super::colorcmds::invert)
),
@@ -111,7 +112,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
"Complement",
[],
None,
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} replace the active proxy's colours by their complements ((highest + lowest) − each component, over RGB or CMY; grey unchanged) keeping each colour's model; a Live Paint group recolors its faces' fills or its edges' strokes as with paint.invert; honours the Appearance panel's active item and a selected object of a dynamic symbol instance as paint.invert does; with nothing selected, or while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), the default; no undo step when no color changes → {changed}",
"{stroke?: bool (default: the active proxy), ids?|id?, defaultsOnly?: bool, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} replace the active proxy's colours by their complements ((highest + lowest) − each component, over RGB or CMY; grey unchanged) keeping each colour's model; a Live Paint group recolors its faces' fills or its edges' strokes as with paint.invert; honours the Appearance panel's active item and a selected object of a dynamic symbol instance as paint.invert does; with nothing selected, or while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, the default; no undo step when no color changes → {changed}",
has_doc,
|s, p| proxy_recolor(s, p, "paint.complement", "Complement", &|c: Color| c.complement_keep_model())
),
@@ -120,7 +121,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
"Apply Last Color",
[],
Some(","),
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last solid colour used (paint.recent lastColor) to the active proxy of the selection and the default (while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), to the default only) → {objects} (as paint.setFill)",
"{stroke?: bool (default: the active proxy), ids?|id?, defaultsOnly?: bool, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last solid colour used (paint.recent lastColor) to the active proxy of the selection and the default (while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, to the default only) → {objects} (as paint.setFill)",
has_doc,
|s, p| {
let paint = Paint::solid(s.last_solid);
@@ -132,7 +133,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
"Apply Last Gradient",
[],
Some("."),
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last gradient used (paint.recent lastGradient), fitted to each object, to the active proxy of the selection and the default (while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), to the default only) → {objects} (as paint.setFill)",
"{stroke?: bool (default: the active proxy), ids?|id?, defaultsOnly?: bool, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last gradient used (paint.recent lastGradient), fitted to each object, to the active proxy of the selection and the default (while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, to the default only) → {objects} (as paint.setFill)",
has_doc,
|s, p| {
let paint = super::gradient::unplaced(&Paint::Gradient(Box::new(s.last_gradient.clone())));
@@ -223,7 +224,7 @@ impl Session {
// A Live Paint group without faces (or edges) shows the next selected object's paint; any other
// object without a painted object shows the defaults for new art. A face or edge selected with
// its Live Paint group counts with the group, wherever it is in the selection.
let covered = live_paint_covered(&st.doc, st.selection.subjects());
let covered = st.selection_live_paint_covered(st.selection.subjects());
for id in st.selection.subjects().iter().filter(|id| !covered.contains(*id)) {
let Some(n) = st.doc.node(*id) else { continue };
let mut nodes = vec![];
@@ -302,6 +303,74 @@ pub(crate) fn painted<'a>(n: &'a Node, top: bool, stroke: bool, out: &mut Vec<&'
}
}
/// What the proxies read from selected objects: the first fill, stroke and stroke weight met, and
/// whether another one differs ([`DocState::proxy_mixed`] without an active Appearance item or
/// picked mesh points, and [`super::stroke::StrokeMixed::weight`]), and whether an object lies in a
/// Live Paint group or may hold a gradient mesh. The objects added to a selection are read with
/// [`SelectionPaints::add`].
#[derive(Clone, Debug, Default)]
pub(crate) struct SelectionPaints {
fill: Option<Paint>,
pub(crate) fill_mixed: bool,
stroke: Option<Paint>,
pub(crate) stroke_mixed: bool,
weight: Option<f64>,
pub(crate) weight_mixed: bool,
/// An object is a face or edge of a Live Paint group, or lies inside one
/// ([`live_paint_covered`]).
pub(crate) in_live_paint: bool,
/// An object is a gradient mesh or a container ([`Session::fill_mesh_points`]).
pub(crate) may_hold_mesh: bool,
}
impl SelectionPaints {
/// Read objects `ids` of `doc`.
pub(crate) fn of(doc: &Document, ids: &[NodeId]) -> Self {
let mut p = Self::default();
p.add(doc, ids);
p
}
/// Read objects `ids` of `doc` too.
pub(crate) fn add(&mut self, doc: &Document, ids: &[NodeId]) {
fn meet<T>(first: &mut Option<T>, mixed: &mut bool, value: T, same: impl Fn(&T, &T) -> bool) {
match first {
Some(f) => *mixed |= !same(f, &value),
None => *first = Some(value),
}
}
// As in `proxy_mixed_with`: every node with an added id, in tree order.
let (mut fills, mut strokes) = (vec![], vec![]);
for n in doc.nodes_in_order(ids.iter().copied()) {
painted(n, true, false, &mut fills);
painted(n, true, true, &mut strokes);
}
for n in fills {
meet(&mut self.fill, &mut self.fill_mixed, proxy_paint(n, false, None), same_in_proxy);
}
for n in strokes {
meet(&mut self.stroke, &mut self.stroke_mixed, proxy_paint(n, true, None), same_in_proxy);
}
// As in `stroke_mixed`: the node each added id names.
for id in ids {
let Some(n) = doc.node(*id) else { continue };
self.in_live_paint |= in_live_paint(doc, *id);
self.may_hold_mesh |= matches!(n.kind, NodeKind::Mesh(_)) || n.is_container();
let mut nodes = vec![];
painted(n, true, true, &mut nodes);
for n in nodes {
let widths: Vec<f64> = match &n.kind {
NodeKind::Text(t) => t.runs.iter().map(|r| r.style.stroke_layer().width).collect(),
_ => n.appearance.stroke().map(|s| s.width).into_iter().collect(),
};
for w in widths {
meet(&mut self.weight, &mut self.weight_mixed, w, |a, b| a == b);
}
}
}
}
}
impl DocState {
/// Whether the selected objects' fills and strokes differ as the proxies show them (a "?"
/// proxy; a group whose contents differ counts). `item` (the Appearance panel's active item)
@@ -328,7 +397,7 @@ impl DocState {
let (mut selected, mut fills, mut strokes) = (vec![], vec![], vec![]);
// The faces and edges of the selected Live Paint groups (or of those inside selected groups): selected as well,
// they count with their group's.
let covered = live_paint_covered(&self.doc, &self.selection.objects);
let covered = self.selection_live_paint_covered(&self.selection.objects);
// Every node with a selected id, in tree order: a repeated id (a damaged file) counts at each
// place it appears.
for n in self.doc.nodes_in_order(self.selection.objects.iter().copied()) {
@@ -373,16 +442,25 @@ impl DocState {
}
}
/// Is `t` the Live Paint Bucket, or a tool armed to switch back to it after its pick?
fn works_for_bucket(t: &dyn vectorcraft_tools::Tool) -> bool {
t.id() == LIVE_PAINT_BUCKET || t.returns_to() == Some(LIVE_PAINT_BUCKET)
}
impl Session {
/// Did the Live Paint Bucket, or the Eyedropper armed for it, lend the active tool (a Cmd+click)?
pub(crate) fn lent_by_bucket(&self) -> bool {
self.lender.as_deref().is_some_and(works_for_bucket)
}
/// Do the fill and stroke proxies, and the paint commands that name no objects, stand for the
/// colors the Live Paint Bucket paints with? They do while the bucket is the active tool, while
/// a Cmd+click with the bucket uses the Selection tool, and while the Eyedropper samples into a
/// stop of the bucket's gradient for the Gradient panel's eyedropper, up to and including the
/// sample its click takes before it switches back to the bucket.
pub fn bucket_paints(&self) -> bool {
let for_bucket = |t: &dyn vectorcraft_tools::Tool| t.id() == LIVE_PAINT_BUCKET || t.returns_to() == Some(LIVE_PAINT_BUCKET);
// A Cmd+click lends the Selection tool to the bucket, or to the Eyedropper armed for it.
self.back_to_bucket || for_bucket(self.tool.as_ref()) || self.lender.as_deref().is_some_and(for_bucket)
self.back_to_bucket || works_for_bucket(self.tool.as_ref()) || self.lent_by_bucket()
}
/// The tool the active tool's armed one-shot pick switches back to after its click
@@ -668,7 +746,13 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
characters.borrow_mut().push(n.id);
}
if index.is_none() && colorized.contains(&n.id) {
n.extras_mut().colorize = paint.color().map(|_| Box::new(paint.clone()));
let colorize = paint.color().map(|_| Box::new(paint.clone()));
// Without a color the image has nothing to overprint, and a later color starts
// knocking out.
if colorize.is_none() {
n.extras_mut().colorize_overprint = false;
}
n.extras_mut().colorize = colorize;
return Ok(());
}
if index.is_none()
@@ -750,28 +834,84 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
Ok(json!({"objects": ids.iter().collect::<std::collections::BTreeSet<_>>().len()}))
}
/// Is the Live Paint Bucket the active tool ([`Session::bucket_paints`]) while `p` names no `ids`,
/// `id` or `item`? A fill,
/// stroke or stroke weight chosen then is what the bucket paints with, so it goes to the defaults
/// and the selection keeps its paint.
pub(crate) fn for_bucket(s: &Session, p: &Value) -> bool {
/// Does `p` name no `ids`, `id` or `item`?
fn names_no_target(p: &Value) -> bool {
// A null `ids` or `id` is no target, as `given_nodes` reads it; `item: null` names the top row.
s.bucket_paints() && ["ids", "id"].iter().all(|k| p.get(k).is_none_or(Value::is_null)) && p.get("item").is_none()
["ids", "id"].iter().all(|k| p.get(k).is_none_or(Value::is_null)) && p.get("item").is_none()
}
/// `p` with `ids: []` when [`for_bucket`]: the paint goes to the defaults only. None otherwise.
/// A bad `target` or `aligned` is refused first, as it is without the bucket.
pub(crate) fn bucket_color_params(s: &Session, p: &Value, cmd: &str) -> Result<Option<Value>> {
/// Is the Live Paint Bucket the active tool ([`Session::bucket_paints`]), or does `p` give
/// `defaultsOnly: true`, while `p` names no `ids`, `id` or `item`? A fill, stroke or stroke weight
/// chosen then is what the bucket paints with, so it goes to the defaults and the selection keeps
/// its paint.
pub(crate) fn for_bucket(s: &Session, p: &Value) -> bool {
names_no_target(p) && (s.bucket_paints() || asks_defaults_only(p))
}
/// Does `p` give `defaultsOnly: true`?
pub(crate) fn asks_defaults_only(p: &Value) -> bool {
p.get("defaultsOnly") == Some(&Value::Bool(true))
}
/// `p` with `ids: []` (and without `defaultsOnly`) when [`for_bucket`]: the paint goes to the
/// defaults only. None otherwise. A bad `target` or `aligned` is refused first, as it is without
/// the bucket, and so is a `defaultsOnly` that is not a bool or comes with `ids`, `id` or `item`.
/// When the bucket routed the command, the journal entry notes `defaultsOnly: true`, so replaying
/// it with another tool active changes the defaults only as well.
pub(crate) fn bucket_color_params(s: &mut Session, p: &Value, cmd: &str) -> Result<Option<Value>> {
let only = switch_or(p, "defaultsOnly", false, cmd)?;
if only && !names_no_target(p) {
return Err(bad(cmd, "`defaultsOnly` cannot be combined with `ids`, `id` or `item`"));
}
if !for_bucket(s, p) {
return Ok(None);
}
super::appearance::aligned(p, cmd)?;
super::appearance::targets_contents(p)?;
if !only {
s.note_journal("defaultsOnly", json!(true));
}
s.note_defaults_only();
let mut v = p.as_object().cloned().unwrap_or_default();
v.remove("defaultsOnly");
v.insert("ids".into(), json!([]));
Ok(Some(Value::Object(v)))
}
/// Whether the paint commands that `cmd` runs with params of its own change only the defaults:
/// `p` gives `defaultsOnly: true`, or the Live Paint Bucket paints ([`Session::bucket_paints`]),
/// which the journal entry of `cmd` notes for a replay.
pub(crate) fn defaults_only(s: &mut Session, p: &Value, cmd: &str) -> Result<bool> {
if switch_or(p, "defaultsOnly", false, cmd)? {
s.note_defaults_only();
return Ok(true);
}
let bucket = s.bucket_paints();
if bucket {
s.note_journal("defaultsOnly", json!(true));
s.note_defaults_only();
}
Ok(bucket)
}
impl Session {
/// Note that the running command changed only the paint defaults, with the appearance new art
/// takes from the selection now ([`Session::inherit_new_art`]). No appearance is captured
/// while inheritance does not run (New Art Has Basic Appearance on, or the bucket painting).
fn note_defaults_only(&mut self) {
let inherits = !self.prefs.new_art_basic && !self.bucket_paints();
self.defaults_only_ran = Some(if inherits { self.new_art_source() } else { None });
}
}
/// `q` with `defaultsOnly: true` when `only` ([`defaults_only`]).
pub(crate) fn with_defaults_only(mut q: Value, only: bool) -> Value {
if only && let Some(o) = q.as_object_mut() {
o.insert("defaultsOnly".into(), json!(true));
}
q
}
/// The Live Paint groups in `roots` (or inside them), given or selected whole, with the ids of
/// their faces and of their edges, found where [`leaf_targets`] finds the objects a paint command
/// changes: a given or selected object other than a group or layer (a blend, say) and a compound
@@ -855,8 +995,7 @@ pub(crate) fn live_paint_split(d: &Document, roots: &[NodeId]) -> LivePaintParts
/// object: they count with their group, wherever they are in `selected`. The groups are looked for only when an
/// object in `selected` is inside a Live Paint group.
pub(crate) fn live_paint_covered(d: &Document, selected: &[NodeId]) -> std::collections::HashSet<NodeId> {
let inside = |id: &NodeId| d.ancestry(*id).is_some_and(|up| up.iter().rev().skip(1).filter_map(|a| d.node(*a)).any(is_live_paint));
if !selected.iter().any(inside) {
if !selected.iter().any(|id| in_live_paint(d, *id)) {
return std::collections::HashSet::new();
}
let (mut parts, edges, _) = live_paint_split(d, selected);
@@ -864,6 +1003,22 @@ pub(crate) fn live_paint_covered(d: &Document, selected: &[NodeId]) -> std::coll
parts
}
/// Is `id` inside a Live Paint group (one of the groups around it is one)?
fn in_live_paint(d: &Document, id: NodeId) -> bool {
d.ancestry(id).is_some_and(|up| up.iter().rev().skip(1).filter_map(|a| d.node(*a)).any(is_live_paint))
}
impl DocState {
/// [`live_paint_covered`] for `ids`, the selected objects or the selection's subjects: none
/// when the [`SelectionPaints`] of the selection say no selected object is in a Live Paint group.
pub(crate) fn selection_live_paint_covered(&self, ids: &[NodeId]) -> std::collections::HashSet<NodeId> {
if self.selection_paints().is_some_and(|p| !p.in_live_paint) {
return std::collections::HashSet::new();
}
live_paint_covered(&self.doc, ids)
}
}
/// The instance whose object is selected with Direct Selection, and that object's path
/// ([`super::brushsym::selected_part`]), when `p` names no `ids`, `id` or `item`: the paint commands
/// then change that object. A bad `target` or `aligned` is refused as it is for any other selection.
@@ -1109,7 +1264,8 @@ impl Session {
// Only gradient meshes have points to pick: a selection with no mesh and no container that
// could hold one skips reading the tool's options.
let may_hold_mesh = |id: &NodeId| st.doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Mesh(_)) || n.is_container());
if st.selection.symbol_part.is_some() || !st.selection.subjects().iter().any(may_hold_mesh) {
let none_may = || st.selection_paints().map_or_else(|| !st.selection.subjects().iter().any(may_hold_mesh), |p| !p.may_hold_mesh);
if st.selection.symbol_part.is_some() || none_may() {
return vec![];
}
let Ok(item) = item_target(self, &Value::Null, "paint.setFill").map(|t| t.of_kind(self, true)) else { return vec![] };
+2 -5
View File
@@ -199,14 +199,11 @@ pub fn specs() -> Vec<CommandSpec> {
// ---------- helpers ----------
/// Number param that also accepts strings like `"10 pt"`.
/// Number param that also accepts a string when all of it is a number (`"10"`, not `"10abc"`).
pub(crate) fn num_param(p: &Value, key: &str) -> Option<f64> {
match p.get(key)? {
Value::Number(n) => n.as_f64(),
Value::String(s) => {
let t: String = s.trim().chars().take_while(|c| c.is_ascii_digit() || matches!(c, '.' | '-' | '+' | 'e' | 'E')).collect();
t.parse().ok()
}
Value::String(s) => whole_number(s),
_ => None,
}
.filter(|v: &f64| v.is_finite())
+7 -7
View File
@@ -5,7 +5,7 @@
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use vectorcraft_pdf::{PdfPreset, builtin_preset, builtin_presets};
use vectorcraft_pdf::{APP, ActiveProfiles, PdfPreset, builtin_preset, builtin_presets};
use super::fileio::pdf::{find_preset, resolve};
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, str_param};
@@ -75,7 +75,7 @@ pub fn specs() -> Vec<CommandSpec> {
impl Session {
/// Every PDF preset: the built-in ones, then the saved ones.
pub fn pdf_presets(&self) -> Vec<PdfPreset> {
let mut v = builtin_presets();
let mut v = builtin_presets(APP);
v.extend(self.prefs.pdf_presets.iter().cloned());
v
}
@@ -93,16 +93,16 @@ impl Session {
/// Whether `name` is taken by a built-in PDF preset or a saved one other than the one at
/// `except`.
fn pdf_preset_taken(&self, name: &str, except: Option<usize>) -> bool {
builtin_preset(name).is_some() || self.pdf_saved_index(name).is_some_and(|i| Some(i) != except)
builtin_preset(name, APP).is_some() || self.pdf_saved_index(name).is_some_and(|i| Some(i) != except)
}
}
fn row(p: PdfPreset, built_in: bool) -> Value {
json!({ "name": p.name, "builtIn": built_in, "supported": p.settings.check().is_ok(), "description": p.description, "settings": p.settings })
json!({ "name": p.name, "builtIn": built_in, "supported": p.settings.check(&ActiveProfiles::default()).is_ok(), "description": p.description, "settings": p.settings })
}
fn list(s: &mut Session, _: &Value) -> Result<Value> {
let rows = builtin_presets().into_iter().map(|p| row(p, true)).chain(s.prefs.pdf_presets.iter().cloned().map(|p| row(p, false)));
let rows = builtin_presets(APP).into_iter().map(|p| row(p, true)).chain(s.prefs.pdf_presets.iter().cloned().map(|p| row(p, false)));
Ok(json!({ "presets": rows.collect::<Vec<_>>() }))
}
@@ -113,7 +113,7 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
Some(n) => n.to_string(),
None => s.new_pdf_preset_name(),
};
if builtin_preset(&name).is_some() {
if builtin_preset(&name, APP).is_some() {
return Err(bad(C, format!("`{name}` is a built-in preset and is read-only: save it under another name")));
}
let at = s.pdf_saved_index(&name);
@@ -145,7 +145,7 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
fn delete(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "pdf.preset.delete";
let name = str_param(p, "name").ok_or_else(|| bad(C, "missing `name`"))?;
if builtin_preset(name).is_some() {
if builtin_preset(name, APP).is_some() {
return Err(bad(C, format!("`{name}` is a built-in preset and stays")));
}
let i = s.pdf_saved_index(name).ok_or_else(|| bad(C, format!("no saved PDF preset named `{name}`")))?;
+1 -1
View File
@@ -786,7 +786,7 @@ fn prepare(s: &Session, p: &Value) -> Result<PlaceJob> {
(true, _) => return Err(bad(PLACE, "replace: select the one object to replace")),
};
let replaced = old.and_then(|id| st.doc.node(id)).cloned();
Ok(PlaceJob { doc: st.uid, params: p.clone(), old, replaced, target: board_at(&st.doc, at) })
Ok(PlaceJob { doc: st.uid, params: s.prefs.with_pdf_font_choice(p), old, replaced, target: board_at(&st.doc, at) })
}
/// Place the file `read` holds in the active document.
+16
View File
@@ -72,6 +72,9 @@ fn refs(n: &mut Node, f: &mut impl FnMut(Ref)) {
paint_refs(&mut r.style.fill, f);
paint_refs(&mut r.style.stroke, f);
}
if let Some(fonts) = &mut t.file_fonts {
fonts.map_keys(|key| f(Ref::Image(key)));
}
}
NodeKind::Image(im) => f(Ref::Image(&mut im.key)),
NodeKind::PlacedDocument(pl) => f(Ref::Image(&mut pl.key)),
@@ -352,6 +355,19 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
dst.images.insert(new.to_string(), blob.clone());
}
}
// Equal font bytes can reuse an existing image entry whose runtime lease is still empty.
// Transfer the validated source lease too: cached text nodes hold only weak references.
for (old, (new, copy)) in &images {
if *copy {
continue;
}
let Some(blob) = src.images.get(old).filter(|b| b.mime == vectorcraft_doc::FILE_FONT_MIME) else { continue };
let Some(target) = new.as_ref().and_then(|key| dst.images.get_mut(key)) else { continue };
let owner = blob.file_font.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(face) = owner.as_ref().filter(|face| std::ptr::eq(face.bytes(), blob.bytes.as_slice()) || face.bytes() == blob.bytes.as_slice()) {
*target.file_font.get_mut().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(face.clone());
}
}
for (old, new) in copies(&symbols) {
if let Some(mut def) = src.symbols.iter().find(|s| s.name == old).cloned() {
def.name = new.to_string();
+5 -2
View File
@@ -333,7 +333,7 @@ fn read_source(
}
let a = opened_document_art(name, (bytes, opened), path, page, bounding, page_box, cmd)?;
let bytes = shared.cloned().unwrap_or_else(|| Arc::new(bytes.to_vec()));
let mut blob = ImageBlob { mime: mime(name, &bytes).into(), bytes, proxy: None };
let mut blob = ImageBlob { mime: mime(name, &bytes).into(), bytes, proxy: None, file_font: Default::default() };
let shown = PlacedDocument {
link: LinkInfo { page: Some(page), ..LinkInfo::new(path.unwrap_or(name)) },
key: key.clone(),
@@ -468,7 +468,10 @@ pub(crate) fn full_documents(d: &Document) -> (Cow<'_, Document>, Vec<String>) {
let Some(blob) = out.images.get(&p.key) else { continue };
match vectorcraft_doc::placed_document::full_bytes(&p, blob) {
Some(bytes) => {
out.images.insert(p.key.clone(), ImageBlob { mime: mime(p.link.name(), &bytes).into(), bytes, proxy: blob.proxy.clone() });
out.images.insert(
p.key.clone(),
ImageBlob { mime: mime(p.link.name(), &bytes).into(), bytes, proxy: blob.proxy.clone(), file_font: Default::default() },
);
}
None => {
previews.insert(p.key);
+2 -2
View File
@@ -651,8 +651,8 @@ mod tests {
let s = read(concat!(r"{\rtf1\ansi\uc1 caf\u233?\uc2 \u", "8364", r"\'80\'80 \uc1\u-10179?\u-8704? end\'93q\'94}"));
assert_eq!(text_of(&s), "café€ 😀 end“q”");
assert_eq!(text_of(&read(r"{\rtf1\uc1\u233\bin1 ?X}")), "éX", "binary data is one fallback character");
let mac = read(r"{\rtf1\mac \'8e\'a5}");
assert_eq!(text_of(&mac), "é•", "Mac Roman");
let mac = read(r"{\rtf1\mac \'8e\'ca\'a5\'db\'de}");
assert_eq!(text_of(&mac), "é\u{a0}•€fi", "Mac Roman");
}
#[test]
+2 -15
View File
@@ -185,20 +185,7 @@ pub(in crate::cmd) fn windows_1252(b: u8) -> char {
/// Byte `b` of Mac Roman.
pub(in crate::cmd) fn mac_roman(b: u8) -> char {
const HIGH: [char; 128] = [
'Ä', 'Å', 'Ç', 'É', 'Ñ', 'Ö', 'Ü', 'á', 'à', 'â', 'ä', 'ã', 'å', 'ç', 'é', 'è', //
'ê', 'ë', 'í', 'ì', 'î', 'ï', 'ñ', 'ó', 'ò', 'ô', 'ö', 'õ', 'ú', 'ù', 'û', 'ü', //
'†', '°', '¢', '£', '§', '•', '¶', 'ß', '®', '©', '™', '´', '¨', '≠', 'Æ', 'Ø', //
'∞', '±', '≤', '≥', '¥', 'µ', '∂', '∑', '∏', 'π', '∫', 'ª', 'º', 'Ω', 'æ', 'ø', //
'¿', '¡', '¬', '√', 'ƒ', '≈', '∆', '«', '»', '…', '\u{A0}', 'À', 'Ã', 'Õ', 'Œ', 'œ', //
'–', '—', '“', '”', '‘', '’', '÷', '◊', 'ÿ', 'Ÿ', '⁄', '€', '‹', '›', 'fi', 'fl', //
'‡', '·', '‚', '„', '‰', 'Â', 'Ê', 'Á', 'Ë', 'È', 'Í', 'Î', 'Ï', 'Ì', 'Ó', 'Ô', //
'\u{F8FF}', 'Ò', 'Ú', 'Û', 'Ù', 'ı', 'ˆ', '˜', '¯', '˘', '˙', '˚', '¸', '˝', '˛', 'ˇ',
];
match b {
0x80.. => HIGH.get(usize::from(b - 0x80)).copied().unwrap_or(char::REPLACEMENT_CHARACTER),
_ => char::from(b),
}
craft_codepage::windows_byte(craft_codepage::MAC_ROMAN_CODE_PAGE, b)
}
/// `text` with its line breaks (CR LF, CR or LF) as paragraph breaks, cleaned up as `o` says:
@@ -344,7 +331,7 @@ mod tests {
let ansi = TextOptions { character_set: CharacterSet::Ansi, ..TextOptions::default() };
assert_eq!(decode(&[0x93, b'q', 0x94, 0xE9], ansi), "“q”é");
let mac = TextOptions { character_set: CharacterSet::Ansi, mac: true, ..TextOptions::default() };
assert_eq!(decode(&[0xD2, b'q', 0xD3, 0x8E, 0xA5, 0xDB], mac), "“q”é•€");
assert_eq!(decode(&[0xD2, b'q', 0xD3, 0x8E, 0xCA, 0xA5, 0xDB, 0xDE, 0xF0], mac), "“q”é\u{a0}•€fi\u{f8ff}");
}
/// The other character sets decode by their Encoding Standard decoders: the platform matters
+46 -15
View File
@@ -47,7 +47,7 @@
use std::sync::{Arc, Mutex, RwLock};
use serde_json::{Map, Value, json};
use vectorcraft_doc::{Effect, Node};
use vectorcraft_doc::{Document, Effect, Node};
use vectorcraft_plugins::{Budget, Command, Kind, Plugin, effect, export, objects, registry, safe_mode};
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, cmd, has_doc, ids_param, str_param, switch_or};
@@ -330,7 +330,8 @@ impl FilterRun {
/// Applies the plug-in's `output` to the active document as one undo step: its objects, and what
/// it keeps with the document from now on. An output its permissions don't allow, and one that
/// changes or leaves out a read-only object it was given, is refused, and the document stays as
/// it was.
/// it was. An output that changes neither the objects nor the kept data records no undo step and
/// leaves the document unmodified; its objects are still selected.
fn finish(self, s: &mut Session, output: &[u8]) -> Result<Value> {
let m = self.plugin.manifest();
let may = m.permissions();
@@ -342,18 +343,43 @@ impl FilterRun {
// A command's undo step is named after the command.
let label = self.label();
let (inputs, parent) = (self.inputs, self.parent);
let ids = s.edit(&label, |d, sel| {
let before = (!may_write).then(|| d.layers.clone());
let ids = objects::apply_output(d, &inputs, out.objects, parent, &admit_effects).map_err(err)?;
if before.is_some_and(|b| b != d.layers) {
return Err(not_granted(&m.name, Permission::DocWrite));
// The output is applied to a copy of the document, as `colorcmds::edit_if_changed` applies
// its pass: only a copy whose objects or kept data differ becomes the document, as one undo
// step. Otherwise the document, its undo and redo steps and its saved state stay as they
// were, and only the selection is set.
if s.script_running() {
return Err(EngineError::Busy);
}
if !s.previewing && super::typing_in_progress(s) {
super::settle_interaction(s)?;
}
let now = s.doc()?.doc.clone();
let mut d = (*now).clone();
let before = (!may_write).then(|| d.layers.clone());
let ids = objects::apply_output(&mut d, &inputs, out.objects, parent, &admit_effects).map_err(err)?;
if before.is_some_and(|b| b != d.layers) {
return Err(not_granted(&m.name, Permission::DocWrite));
}
if let Some(data) = out.document_data {
d.set_plugin_data(&m.id, data);
}
let selectable = |d: &Document| ids.iter().copied().filter(|&id| d.node(id).is_some_and(objects::selectable)).collect::<Vec<_>>();
if same_art(&d.layers, &now.layers) && d.plugin_data(&m.id) == now.plugin_data(&m.id) {
let st = s.doc()?;
let mut sel = st.selection.clone();
sel.set(selectable(&st.doc));
if sel != st.selection {
s.select(|_, selection| *selection = sel)?;
}
if let Some(data) = out.document_data {
d.set_plugin_data(&m.id, data);
}
sel.set(ids.iter().copied().filter(|&id| d.node(id).is_some_and(objects::selectable)));
Ok(ids)
})?;
} else {
// The document is shared with `now` no longer, so `s.edit` does not copy it again.
drop(now);
s.edit(&label, |doc, sel| {
*doc = d;
sel.set(selectable(doc));
Ok(())
})?;
}
let mut out = json!({"plugin": m.id, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()});
if let Some(cmd) = &self.command {
out["command"] = json!(cmd.id);
@@ -362,6 +388,11 @@ impl FilterRun {
}
}
/// Whether layer lists `a` and `b` hold the same art: a layer that is shared is not compared again.
fn same_art(a: &[Arc<Node>], b: &[Arc<Node>]) -> bool {
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| Arc::ptr_eq(x, y) || x == y)
}
/// The error of a filter `name` whose output needs `permission`, which it wasn't granted.
fn not_granted(name: &str, permission: Permission) -> EngineError {
let (name, p) = (permissions::display_text(name, permissions::MAX_SHOWN_NAME), permission.name());
@@ -483,7 +514,7 @@ fn spec_of(p: &Plugin, c: &Command) -> &'static CommandSpec {
fields.push_str(own);
}
let params = format!(
"{{{fields}}} run “{label}”, a command of plug-in {}, on the selected paths and compound paths as plugin.run runs a filter, with _context.command {:?}: one undo step → {{plugin, command, ids}}",
"{{{fields}}} run “{label}”, a command of plug-in {}, on the selected paths and compound paths as plugin.run runs a filter, with _context.command {:?}: one undo step, none when the run changes nothing → {{plugin, command, ids}}",
m.id, c.id
);
let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner());
@@ -1288,7 +1319,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Run Plug-in",
[],
None,
"{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step; the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs per run (an object that doesn't fit what the objects before it left comes with pixelsOmitted or truncated; an image that reaches the decoder counts toward the pixels even when decoding fails); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given, or the run is refused and nothing changes. With nothing selected it gets no objects (generators add theirs to the current layer). A filter with a commandAllowlist runs the commands it names while it runs (vc_call, see docs/plugins.md): its calls and its output are one undo step, and a run that fails or makes a call that fails changes nothing → {plugin, ids}",
"{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step (an output that changes no object and no kept data records none and leaves the document unmodified); the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs per run (an object that doesn't fit what the objects before it left comes with pixelsOmitted or truncated; an image that reaches the decoder counts toward the pixels even when decoding fails); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given, or the run is refused and nothing changes. With nothing selected it gets no objects (generators add theirs to the current layer). A filter with a commandAllowlist runs the commands it names while it runs (vc_call, see docs/plugins.md): its calls and its output are one undo step, and a run that fails or makes a call that fails changes nothing → {plugin, ids}",
has_doc,
run
),
+1
View File
@@ -396,6 +396,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[
p!("recoveryOffForComplex", "File Handling", "Data Recovery", "Turn off Data Recovery for complex documents", bool),
p!("recentFilesCount", "File Handling", "Files", "Number of Recent Files to Display", int(0, 30)),
p!("lowResProxyEps", "File Handling", "Files", "Use Low Resolution Proxy for Linked EPS", bool),
p!("pdfImportEmbeddedFonts", "File Handling", "Files", "Use fonts embedded in imported PDFs", bool),
p!("antiAliasedBitmaps", "File Handling", "Files", "Display Bitmaps as Anti-aliased Images in Pixel Preview", bool),
p!(
"updateLinks",
+8 -3
View File
@@ -5,7 +5,7 @@
use serde::Deserialize;
use serde_json::{Value, json};
use vectorcraft_doc::Document;
use vectorcraft_eps::{Level, PrintJob, PrintPage};
use vectorcraft_eps::{Level, PrintFonts, PrintJob, PrintPage};
use vectorcraft_geom::{Affine, Rect};
use vectorcraft_pdf::{PrintLayers, PrintOptions, PrintPreview, PrintSettings};
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Print Setup",
[],
None,
"{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100 (1–1000 % with custom and tiling), linked: true (width and height stay equal: give one and the other follows, and turning it on sets the height to the width; a different width and height without linked turn it off, and with linked: true, or linked: null over a linked scale, are an error; a saved scale without linked reads it as false)}, overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one gray page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, overprintBlack: false (separations: solid 100% K or 100% gray fills, strokes and characters, to within half a percent, overprint in the printed copy, gradients when every stop is (every point of a freeform one); rich, RGB, spot-linked and lighter blacks are not marked, and paints already set to overprint keep it; composite ignores it), inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (screen angle, degrees counter-clockwise as PostScript setscreen takes it; default C 15, M 75, Y 0, K 45, spots 45), convertToProcess: false (a spot ink only: it prints on the process plates, with no plate of its own, and its print, frequency and angle are kept for when it prints as a spot ink again; spotsToProcess converts every spot ink whatever it says)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colors keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colors are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution, or lower for a page larger than 64 Mpx or 32,768 px a side), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)",
"{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100 (1–1000 % with custom and tiling), linked: true (width and height stay equal: give one and the other follows, and turning it on sets the height to the width; a different width and height without linked turn it off, and with linked: true, or linked: null over a linked scale, are an error; a saved scale without linked reads it as false)}, overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one gray page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, overprintBlack: false (separations: solid 100% K or 100% gray fills, strokes and characters, to within half a percent, overprint in the printed copy, gradients when every stop is (every point of a freeform one); rich, RGB, spot-linked and lighter blacks are not marked, and paints already set to overprint keep it; composite ignores it), inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (screen angle, degrees counter-clockwise as PostScript setscreen takes it; default C 15, M 75, Y 0, K 45, spots 45), convertToProcess: false (a spot ink only: it prints on the process plates, with no plate of its own, and its print, frequency and angle are kept for when it prints as a spot ink again; spotsToProcess converts every spot ink whatever it says)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete (PostScript output: subset (default) sends each page the glyphs it shows, complete sends every glyph of each font once before the first page, none sends no font and names the printer's own; PDF output embeds subsets of the fonts whose licenses allow it, and draws the others as outlines, with any of them, and none or complete adds a note)}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colors keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colors are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution, or lower for a page larger than 64 Mpx or 32,768 px a side), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or pre Line truncated
has_doc,
setup
),
@@ -276,6 +276,11 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> {
setting_notes.push("the printer profile converts the colours of PDF output: PostScript prints the document's colours".to_string());
}
let flatness = (!set.graphics.auto_flatness).then_some(set.graphics.flatness);
let fonts = match set.graphics.fonts {
vectorcraft_pdf::FontDownload::None => PrintFonts::Resident,
vectorcraft_pdf::FontDownload::Subset => PrintFonts::Subset,
vectorcraft_pdf::FontDownload::Complete => PrintFonts::Complete,
};
let plan = vectorcraft_pdf::plan(prepared.as_ref().unwrap_or(doc), &PrintOptions { settings: set, postscript: true, ..Default::default() })
.map_err(|e| pdf_error(PRINT, e))?;
let pages: Vec<PrintPage> = plan
@@ -294,7 +299,7 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> {
ink: sh.ink.as_ref().map(|i| (i.name.as_str(), i.frequency, i.angle)),
})
.collect();
let job = PrintJob { level, title: plan.title.clone(), created: plan.created, flatness };
let job = PrintJob { level, title: plan.title.clone(), created: plan.created, flatness, fonts };
let out = vectorcraft_eps::print(&pages, &plan.order, &job).map_err(|e| bad(PRINT, e))?;
for w in plan.warnings.iter().chain(&out.warnings) {
if !warnings.contains(w) {
+1 -1
View File
@@ -67,7 +67,7 @@ fn drop_guides(nodes: &mut Vec<Arc<Node>>) {
/// nothing is drawn get none.
fn bitmap_document(cmd: &str, doc: &Document, set: &PrintSettings, rich_black: bool) -> Result<Document> {
let regions = vectorcraft_pdf::print_regions(doc, set).map_err(|e| pdf_error(cmd, e))?;
let bleed = set.bleed.of(doc);
let bleed = vectorcraft_pdf::page_bleed(&set.bleed, doc);
let mut art = doc.clone();
drop_guides(&mut art.layers);
let anti_alias = if doc.raster_effects.anti_alias { AntiAlias::Art } else { AntiAlias::None };
+34 -8
View File
@@ -874,6 +874,11 @@ struct Meta {
/// images were kept apart: the document entry holds them).
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
images: BTreeMap<String, ImageRef>,
/// A command a script ran opened or changed the document since the person last saved it
/// ([`crate::DocState::by_script`]): the commands scripts run treat the restored document as
/// one a script opened.
#[serde(skip_serializing_if = "std::ops::Not::not")]
by_script: bool,
}
/// One of a copy's images: its entry in the copy's area.
@@ -1033,10 +1038,13 @@ impl RecoveryJob {
let meta_name = format!("{}{META_EXT}", self.file);
// The details name the images, so a crash between writing the document and its details
// would pair the new document with the old copy's images: when the new document has
// images the old details don't name, they name both until the new document is in.
let old = read_meta(store, &self.file).images;
if meta.images.iter().any(|(k, r)| old.get(k).is_none_or(|o| o.blob != r.blob)) {
// images the old details don't name, they name both until the new document is in. Likewise
// when a script's command changed the document since the old details: they say so first.
let old_meta = read_meta(store, &self.file);
let old = old_meta.images;
if (meta.by_script && !old_meta.by_script) || meta.images.iter().any(|(k, r)| old.get(k).is_none_or(|o| o.blob != r.blob)) {
let mut both = meta.clone();
both.by_script |= old_meta.by_script;
for (k, r) in old {
both.images.entry(k).or_insert(r);
}
@@ -1195,6 +1203,7 @@ pub fn jobs(s: &mut Session, store: &Arc<dyn RecoveryStore>) -> Result<(Vec<Reco
links_from: st.links_from.clone().filter(|_| st.path.is_none()),
// Filled in as the copy is written.
images: BTreeMap::new(),
by_script: st.by_script.is_some(),
};
out.push(RecoveryJob { uid: st.uid, file, title, meta, save, store: store.clone() });
}
@@ -1456,9 +1465,19 @@ fn targets(s: &mut Session, store: &dyn RecoveryStore, cmd: &str, p: &Value) ->
/// (for Save As) and format. The copy moves into this session's area (another crash keeps it).
fn restore_one(s: &mut Session, store: &Arc<dyn RecoveryStore>, file: &str) -> Result<Value> {
let bytes = store.read(&format!("{file}{DOC_EXT}")).map_err(EngineError::Other)?;
let meta_bytes = store.read(&format!("{file}{META_EXT}")).unwrap_or_default();
let meta: Meta = serde_json::from_slice(&meta_bytes).unwrap_or_default();
let (mut doc, _, mut warnings) = fileio::native_file(&bytes).map_err(|e| EngineError::Other(format!("recovery copy `{file}`: {e}")))?;
// A details entry that is missing or can't be parsed does not say whether a script's command
// changed the document: the copy restores as one a script opened, and the details written for
// it say so.
let read = store.read(&format!("{file}{META_EXT}")).ok().and_then(|b| serde_json::from_slice::<Meta>(&b).ok().map(|m| (m, b)));
let (meta, meta_bytes) = match read {
Some(both) => both,
None => {
let meta = Meta { by_script: true, ..Meta::default() };
let bytes = serde_json::to_vec_pretty(&meta).map_err(|e| EngineError::Other(e.to_string()))?;
(meta, bytes)
}
};
let (mut doc, _, mut warnings) = fileio::decode_native_file(&bytes).map_err(|e| EngineError::Other(format!("recovery copy `{file}`: {e}")))?;
// A frame whose first paragraph continues from the frame before draws it without the
// paragraph's first-line indent and list marker.
super::threads::mark_continued(&mut doc);
@@ -1473,7 +1492,7 @@ fn restore_one(s: &mut Session, store: &Arc<dyn RecoveryStore>, file: &str) -> R
};
match read {
Ok(data) => {
let mut blob = ImageBlob { mime: r.mime.clone(), bytes: data, proxy: None };
let mut blob = ImageBlob { mime: r.mime.clone(), bytes: data, proxy: None, file_font: Default::default() };
// Until the linked file is read, the preview stands in for it.
if r.proxy {
blob.proxy = Some(blob.bytes.clone());
@@ -1497,8 +1516,10 @@ fn restore_one(s: &mut Session, store: &Arc<dyn RecoveryStore>, file: &str) -> R
for (blob, data) in &blobs {
store.write(&format!("{area}/{blob}"), data).map_err(EngineError::Other)?;
}
store.write(&format!("{mine}{DOC_EXT}"), &bytes).map_err(EngineError::Other)?;
// The details go first: a crash in between leaves no copy without them (a copy is its
// document entry), and the copy in the old area stays whole.
store.write(&format!("{mine}{META_EXT}"), &meta_bytes).map_err(EngineError::Other)?;
store.write(&format!("{mine}{DOC_EXT}"), &bytes).map_err(EngineError::Other)?;
}
// The copy's images in its old area go with the area, once no copy is left there.
store.remove(&format!("{file}{DOC_EXT}")).map_err(EngineError::Other)?;
@@ -1510,6 +1531,8 @@ fn restore_one(s: &mut Session, store: &Arc<dyn RecoveryStore>, file: &str) -> R
let links_from = meta.path.clone().or_else(|| meta.links_from.clone());
let base = super::links::LinkBase::file(links_from.as_deref());
let links = super::links::resolve(&mut doc, base, s.prefs.update_links == "automatically", s.prefs.low_res_proxy_eps);
// Bind only after the copy's external resources and linked files have been restored.
warnings.extend(Session::refresh_text_bounds(&mut doc));
let index = s.add_document(doc, meta.path.clone());
let st = s.doc_mut()?;
st.recovered = true;
@@ -1517,6 +1540,9 @@ fn restore_one(s: &mut Session, store: &Arc<dyn RecoveryStore>, file: &str) -> R
st.imported_from = meta.imported_from.clone();
st.import_losses = meta.import_losses.clone();
st.format = SAVE_FORMATS.iter().copied().find(|f| *f == meta.format).unwrap_or("vectorcraft");
if meta.by_script {
st.by_script = Some(crate::doc_state::ByScript::Opened);
}
if let Some(pdf) = meta.native_pdf_compatible {
st.save_options.insert("pdfCompatible".into(), json!(pdf));
}
+96 -8
View File
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Retype",
["Type"],
None,
"{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",
"{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 (a part matching exactly also with its contours the other way round, or with only some of them so, as an o's counter alone in an even-odd compound), 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, a combining mark that would start a line (a shape whose first 16 matched glyphs include another character's starts it as that character), 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
)]
@@ -777,10 +777,24 @@ fn set_apart(t: &TextObject, g: &vectorcraft_text::PositionedGlyph, m: &GlyphMat
/// The most glyphs [`verified`] measures the tracking of after a split.
const MEASURE_SPAN: usize = 32;
/// One part of shape `id`, by the glyph it matched (face, glyph, origin, turn and scale): the parts
/// of a compound path share its id.
type PartKey = (NodeId, u32, u32, [u64; 4]);
fn part_key(id: NodeId, m: &GlyphMatch) -> PartKey {
(id, m.face.id(), m.gid, [m.origin.x.to_bits(), m.origin.y.to_bits(), m.angle.to_bits(), m.scale.to_bits()])
}
/// `lines` checked against their own layout: a line splits where its type stops drawing the
/// outlines, and a glyph its type cannot draw even on its own stays an outline (`unmatched`).
/// The glyphs laid out are bounded by a multiple of the number of glyphs.
fn verified(lines: Vec<Line>, system_layout: bool, unmatched: &mut Vec<NodeId>) -> Vec<Line> {
/// `spacing` holds, for a part of a shape read as a combining mark, the other character that part
/// is. The glyphs laid out are bounded by a multiple of the number of glyphs.
fn verified(
lines: Vec<Line>,
system_layout: bool,
spacing: &std::collections::HashMap<PartKey, GlyphMatch>,
unmatched: &mut Vec<NodeId>,
) -> Vec<Line> {
// Glyphs laid out in all, at most: past it, the glyphs left unchecked stay outlines.
let mut budget = lines.iter().map(|l| l.pieces.len()).sum::<usize>().saturating_mul(16).saturating_add(256);
// Measuring the tracking of the glyphs after a split has a budget of its own, so it cannot
@@ -796,6 +810,44 @@ fn verified(lines: Vec<Line>, system_layout: bool, unmatched: &mut Vec<NodeId>)
let mut out = vec![];
while let Some(l) = todo.pop_front() {
let n = l.pieces.len();
// A combining mark goes with the character before it: a mark that a split left first on
// a line becomes the other character its shape is (`spacing`), alone on a line, or else
// stays an outline, and the line goes on from the glyph after it ([`new_line`] starts no
// line with one).
if l.matches.first().is_some_and(|m| vectorcraft_text::retype::is_combining_mark(m.ch)) {
let first = l.pieces.first().copied();
let alone = first.zip(l.matches.first()).and_then(|(id, mark)| spacing.get(&part_key(id, mark)).map(|m| reposed(&l, id, m)));
if alone.is_none() {
unmatched.extend(first);
}
if n > 1 {
// The tracking was measured with the mark's gap in it: the rest is measured again
// without it, from the same budgets as the rest after a split. A rest that starts
// with a mark too is not measured here: its own pass leaves that mark out and
// measures the glyphs after it.
let measurable = n > 3 && remeasured >= (n - 1).saturating_mul(6) && track_budget >= (n - 1).saturating_mul(6);
let rest = if l.matches.get(1).is_some_and(|m| vectorcraft_text::retype::is_combining_mark(m.ch)) {
l.part(1, n)
} else if measurable {
remeasured = remeasured.saturating_sub((n - 1).saturating_mul(6));
track_budget = track_budget.saturating_sub(n - 1);
l.respaced(1, n, 0.0).map(|r| r.tracked(system_layout, &mut track_budget))
} else if l.tracking == 0.0 {
l.part(1, n)
} else {
l.respaced(1, n, 0.0)
};
match rest {
Some(rest) => todo.push_front(rest),
None => unmatched.extend(l.pieces.get(1..).unwrap_or_default().iter().copied()),
}
}
// Checked before the rest, so the lines keep the outlines' order.
if let Some(alone) = alone {
todo.push_front(alone);
}
continue;
}
// The line's type is laid out over a window from its start that doubles while the type
// draws the window's glyphs as the outlines do, so finding where it stops costs about
// twice the glyphs before that point, not the whole rest of the line each time.
@@ -1244,6 +1296,8 @@ fn join(l: &mut Line, pc: &Piece, cands: &[GlyphMatch]) -> bool {
.iter()
.flat_map(|c| c.poses())
.filter(|fp| !(fp.gid == current.gid && fp.face.id() == current.face.id() && fp.angle == current.angle))
// No line starts with a combining mark (see [`new_line`]).
.filter(|fp| !vectorcraft_text::retype::is_combining_mark(fp.ch))
.collect();
for fp in others {
let mut turned = reposed(l, id, &fp);
@@ -1278,10 +1332,11 @@ fn reposed(l: &Line, id: NodeId, m: &GlyphMatch) -> 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`.
/// A new line of shape `pc` alone, as the first of its candidate glyphs `cands` that is not a
/// combining mark (none: `None`), with near matches taken at tolerance `slack`. No line starts
/// with a mark: a mark combines with the character before it.
fn new_line(pc: &Piece, cands: &[GlyphMatch], slack: f64) -> Option<Line> {
let m = cands.first()?;
let m = cands.iter().find(|m| !vectorcraft_text::retype::is_combining_mark(m.ch))?;
let dir = Vec2::new(m.angle.cos(), m.angle.sin());
Some(Line {
pieces: vec![pc.id],
@@ -1755,6 +1810,7 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
let mut unmatched = vec![];
// An unmatched shape between glyphs ends the line: the type after it is painted after it.
let mut open = false;
let mut spacing: std::collections::HashMap<PartKey, GlyphMatch> = std::collections::HashMap::new();
// 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) {
@@ -1775,8 +1831,40 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
Some(l) if open => join(l, pc, &cands),
_ => false,
};
// A part that joined a line, perhaps as a mark, that is also another character, in
// that face or else in the face most shapes fit of those it is a character in: the
// character, should a split leave the part first on a line ([`verified`]). Kept by
// the glyph the part joined as, since the parts of a compound path share its id.
let is_mark = |m: &GlyphMatch| vectorcraft_text::retype::is_combining_mark(m.ch);
if joined
&& cands.iter().any(is_mark)
&& let Some(m) = cands
.iter()
.find(|m| !is_mark(m))
.or_else(|| ms.iter().enumerate().filter(|(_, m)| !is_mark(m)).max_by(ranked).map(|(_, m)| m))
&& let Some(at) = lines.last().and_then(|l| l.matches.last())
{
spacing.insert(part_key(pc.id, at), m.clone());
}
if !joined {
lines.extend(new_line(pc, &cands, tolerance));
// A part that is only marks in that face may be another character in a face
// fewer shapes fit: it starts its line in the one of those most shapes fit.
let started = new_line(pc, &cands, tolerance).or_else(|| {
let face = ms.iter().enumerate().filter(|(_, m)| !is_mark(m)).max_by(ranked).map(|(_, m)| m.face.id());
let cands: Vec<GlyphMatch> = ms.iter().filter(|m| Some(m.face.id()) == face).cloned().collect();
new_line(pc, &cands, tolerance)
});
match started {
Some(l) => lines.push(l),
// Only combining marks: no line starts with one, so the shape stays an
// outline (a shape of several glyphs then is not whole type, see
// `partial_lines`) and the glyph after it starts the next line.
None => {
unmatched.push(pc.id);
open = false;
continue;
}
}
}
open = true;
}
@@ -1795,7 +1883,7 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
lines.iter().map(|l| l.text.chars().count().saturating_add(l.pieces.len().saturating_mul(393))).fold(256usize, usize::saturating_add);
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);
let mut lines = verified(lines, system_layout, &spacing, &mut unmatched);
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));
+17 -7
View File
@@ -26,7 +26,7 @@ pub(in crate::cmd) fn specs() -> Vec<CommandSpec> {
"Find Matching Fonts",
[],
None,
"{count?: 1..96 (default 10)} the fonts whose glyphs match the selected outlined text, as the Retype panel lists them: each selected shape (paths and compound paths, inside groups too) is compared with the glyphs of up to 96 loaded fonts, those of the document's live type first, by type.retype's matching (exact matches only); of two versions of a font loaded at once, only the version its family and style name gives is compared, the one choosing the font sets; the fonts rank by how many shapes each matches, then by the mean distance left after fitting, then by family and style name; the document does not change → {fonts: [{family, style, matched (shapes it matches)}] (the first count), shapes (shapes compared), more (more fonts match than count), truncated (shapes past the limits were left out)}; a count that is not a whole number from 1 to 96 is an error",
"{count?: 1..96 (default 10)} the fonts whose glyphs match the selected outlined text, as the Retype panel lists them: each selected shape (paths and compound paths, inside groups too) is compared with the glyphs of up to 96 loaded fonts, those of the document's live type first, by type.retype's matching (exact matches only), a font whose glyphs match the shapes only as combining marks not listed; of two versions of a font loaded at once, only the version its family and style name gives is compared, the one choosing the font sets; the fonts rank by how many shapes each matches, then by the mean distance left after fitting, then by family and style name; the document does not change → {fonts: [{family, style, matched (shapes it matches)}] (the first count), shapes (shapes compared), more (more fonts match than count), truncated (shapes past the limits were left out)}; a count that is not a whole number from 1 to 96 is an error",
has_selected_path,
retype_fonts
)]
@@ -44,6 +44,8 @@ struct Ranked {
matched: usize,
/// The sum of those matches' leftover distances.
residual: f64,
/// Whether some shape matched a glyph of it that is not a combining mark.
character: bool,
}
impl Ranked {
@@ -101,23 +103,31 @@ fn retype_fonts_in(s: &mut Session, p: &Value, db: &FontDb) -> Result<Value> {
for pc in &pieces {
// A shape can fit several glyphs or poses of one font: it counts once for the font, at its
// closest fit.
let mut best: Vec<(Arc<vectorcraft_text::FontFace>, f64)> = vec![];
let mut best: Vec<(Arc<vectorcraft_text::FontFace>, f64, bool)> = vec![];
for m in index.all_matches(&pc.path) {
match best.iter_mut().find(|(f, _)| f.id() == m.face.id()) {
Some(b) => b.1 = b.1.min(m.residual),
None => best.push((m.face, m.residual)),
let character = !vectorcraft_text::retype::is_combining_mark(m.ch);
match best.iter_mut().find(|(f, _, _)| f.id() == m.face.id()) {
Some(b) => {
b.1 = b.1.min(m.residual);
b.2 |= character;
}
None => best.push((m.face, m.residual, character)),
}
}
for (face, residual) in best {
for (face, residual, character) in best {
match ranked.iter_mut().find(|r| r.face.id() == face.id()) {
Some(r) => {
r.matched += 1;
r.residual += residual;
r.character |= character;
}
None => ranked.push(Ranked { face, matched: 1, residual }),
None => ranked.push(Ranked { face, matched: 1, residual, character }),
}
}
}
// A font whose glyphs match the shapes only as combining marks would retype none of them, as
// type.retype starts no line with a mark: it is not listed.
ranked.retain(|r| r.character);
ranked.sort_by(|a, b| {
b.matched
.cmp(&a.matched)
@@ -106,6 +106,21 @@ fn shapes_that_are_no_glyph_list_no_font() {
assert!(s.execute("type.retypeFonts", &json!({})).is_err());
}
#[test]
fn a_font_that_matches_only_combining_marks_is_not_listed() {
let mut s = session();
// A lone combining mark (a drawn dot, bar or ring is the same shape): type.retype keeps it.
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "\u{312}", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = query(&mut s, json!({}), bundled());
assert_eq!(r, json!({"fonts": [], "shapes": 1, "more": false, "truncated": false}));
// After a base, the mark counts with it.
let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "x\u{312}", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = query(&mut s, json!({}), bundled());
assert!(names(&r).contains(&("Source Sans 3".into(), "Regular".into(), 2)), "{r}");
}
#[test]
fn shapes_past_the_limits_are_reported_as_left_out() {
let mut s = session();
+195 -8
View File
@@ -97,6 +97,165 @@ fn a_drawn_shape_is_reported_and_left_alone() {
assert!(s.doc().unwrap().doc == before);
}
#[test]
fn a_mark_in_one_font_starts_its_line_as_another_fonts_character() {
use vectorcraft_text::test_fonts::{SPACING_COMMA_FAMILY, spacing_comma_font};
// The comma below of Source Sans 3 is only marks there, and a modifier letter in this face.
vectorcraft_text::FontDb::global().add_font(spacing_comma_font().unwrap());
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "\u{326}", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!(["\u{2bb}"]), "{r}");
assert_eq!(r["fonts"][0]["family"], json!(SPACING_COMMA_FAMILY), "{r}");
// After a base, it joins the line as the mark; moved off its base, the split leaves it first,
// and it becomes the other face's character there.
let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "x\u{326}yz", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
let mark = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap()[1].id.0;
s.execute("select.set", &json!({"ids": [mark]})).unwrap();
s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "\u{2bb}", "yz"]), &json!([])), "{r}");
assert_eq!(r["fonts"][1]["family"], json!(SPACING_COMMA_FAMILY), "{r}");
}
#[test]
fn a_combining_mark_starts_no_line() {
// A combining mark on its own (a drawn dot, bar or ring is the same shape) stays an outline.
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "\u{312}", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
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"), "{e}");
assert!(s.doc().unwrap().doc == before, "nothing changes");
// A shape that is both a mark (tilde below) and a character (small tilde) starts its line as
// the character.
let g = outlined(&mut s, json!({"x": 140, "y": 100, "text": "\u{303}", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!(["\u{2dc}"]), "{r}");
// A glyph after it does not turn it back into the mark (diaeresis below, diaeresis).
let g = outlined(&mut s, json!({"x": 240, "y": 100, "text": "\u{324}a", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["\u{a8}", "a"]), &json!([])), "{r}");
// First on a line, the mark stays an outline and the glyphs after it are retyped.
let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "\u{312}ab", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
let mark = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap()[0].id.0;
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!(["ab"]), "{r}");
assert_eq!(r["unmatched"], json!([mark]));
// After a base, the mark is retyped with it.
let g = outlined(&mut s, json!({"x": 40, "y": 300, "text": "x\u{323}", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!(["x\u{323}"]), "{r}");
// Moved off its base, the mark is where the line splits, and the part after the split does
// not start with it either.
let g = outlined(&mut s, json!({"x": 300, "y": 200, "text": "x\u{312}yz", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
let mark = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap()[1].id.0;
s.execute("select.set", &json!({"ids": [mark]})).unwrap();
s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "yz"]), &json!([mark])), "{r}");
// A mark that is also another character (dot below, dot above) becomes that character there.
let g = outlined(&mut s, json!({"x": 300, "y": 120, "text": "x\u{323}yz", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
let mark = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap()[1].id.0;
s.execute("select.set", &json!({"ids": [mark]})).unwrap();
s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "\u{2d9}", "yz"]), &json!([])), "{r}");
// Tracked, the part after the mark keeps the tracking its own glyphs are spaced by.
let id = s
.execute("text.create", &json!({"x": 40, "y": 60, "text": "x\u{312}yzw", "size": 40, "font": "Source Sans 3", "style": "Regular"}))
.unwrap()["id"]
.as_u64()
.unwrap();
s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": 5, "tracking": 50})).unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
let mark = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap()[1].id.0;
s.execute("select.set", &json!({"ids": [mark]})).unwrap();
s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "yzw"]), &json!([mark])), "{r}");
assert_eq!(r["fonts"][1]["tracking"], json!(50.0), "{r}");
// A one-contour glyph after a mark that stays an outline (a bar, then a dot) is alone, and
// beside other shapes it stays an outline too.
let dot = outlined(&mut s, json!({"x": 300, "y": 300, "text": "\u{312}.", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
let mut pair: Vec<u64> = s.doc().unwrap().doc.children(Some(NodeId(dot))).unwrap().iter().map(|n| n.id.0).collect();
pair.sort_unstable();
let word = outlined(&mut s, json!({"x": 40, "y": 380, "text": "ab", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
s.execute("select.set", &json!({"ids": [dot, word]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!(["ab"]), "{r}");
let mut left: Vec<u64> = r["unmatched"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
left.sort_unstable();
assert_eq!(left, pair, "{r}");
}
#[test]
fn marks_of_one_compound_path_each_become_their_own_character() {
// Two marks that are also other characters (dot below, dot above; tilde, small tilde), moved
// off their base and made one compound path: each becomes the character its own shape is.
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "x\u{323}\u{303}yz", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
let kids: Vec<u64> = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap().iter().map(|n| n.id.0).collect();
assert_eq!(kids.len(), 5);
s.execute("select.set", &json!({"ids": [kids[1], kids[2]]})).unwrap();
s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap();
s.execute("object.compoundPath.make", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["unmatched"], json!([]), "{r}");
let texts: Vec<&str> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap()).collect();
let mut marks = texts.get(1..3).unwrap_or_default().to_vec();
marks.sort_unstable();
assert_eq!((texts.first(), texts.get(3), texts.len()), (Some(&"x"), Some(&"yz"), 4), "{r}");
assert_eq!(marks, ["\u{2d9}", "\u{2dc}"], "{r}");
}
#[test]
fn marks_first_after_a_split_leave_other_lines_their_tracking() {
// Twenty marks moved off their base, each one first on its line in turn, do not use up the
// measures of the other lines: the tracked line retyped with them keeps its tracking.
let mut s = session();
let marks = outlined(
&mut s,
json!({"x": 40, "y": 100, "text": format!("x{}a", "\u{312}".repeat(20)), "size": 40, "font": "Source Sans 3", "style": "Regular"}),
);
let mut moved: Vec<u64> = s.doc().unwrap().doc.children(Some(NodeId(marks))).unwrap().iter().map(|n| n.id.0).collect();
assert_eq!(moved.len(), 22);
moved = moved[1..21].to_vec();
let id = s
.execute("text.create", &json!({"x": 40, "y": 300, "text": "x\u{312}yzw", "size": 40, "font": "Source Sans 3", "style": "Regular"}))
.unwrap()["id"]
.as_u64()
.unwrap();
s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": 5, "tracking": 50})).unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let tracked = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
let mark = s.doc().unwrap().doc.children(Some(NodeId(tracked))).unwrap()[1].id.0;
moved.push(mark);
s.execute("select.set", &json!({"ids": moved})).unwrap();
s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap();
s.execute("select.set", &json!({"ids": [marks, tracked]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
let texts = r["texts"].as_array().unwrap();
let at = texts.iter().position(|t| t == "yzw").unwrap_or_else(|| panic!("yzw in {r}"));
assert_eq!(r["fonts"][at]["tracking"], json!(50.0), "{r}");
let mut left: Vec<u64> = r["unmatched"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
left.sort_unstable();
moved.sort_unstable();
assert_eq!(left, moved, "{r}");
}
#[test]
fn mixed_selection_retypes_the_glyphs_and_keeps_the_rest() {
let mut s = session();
@@ -121,7 +280,7 @@ fn two_words_keep_their_space() {
#[test]
fn craft_fonts_glyphs_retype_too() {
let Some(f) = vectorcraft_text::CRAFT_FONTS.iter().find(|f| f.is_japanese()) else {
let Some(f) = vectorcraft_text::CRAFT_FONTS.iter().find(|f| f.has_script("Jpan")) else {
eprintln!("skipped: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout to run it)");
return;
};
@@ -1385,6 +1544,34 @@ fn glyphs_side_by_side_in_an_even_odd_compound_still_become_type() {
assert_eq!(r["texts"], json!(["oo"]), "{r}");
}
#[test]
fn a_glyph_with_only_some_contours_turned_in_an_even_odd_compound_still_becomes_type() {
// An even-odd compound paints the same whichever way its contours run, so an o's counter may
// run the same way as its outer contour: neither the part as it is nor all its contours turned
// is the glyph. Filled by the nonzero rule, the same contours paint the o's counter, and the
// compound stays an outline.
for turned in [1usize, 2] {
let mut s = session();
let c = one_compound(&mut s, "do");
// One path per contour: the d's two, then the o's two.
let paths = children_of(&s, c);
assert_eq!(paths.len(), 4, "a d and an o are two contours each");
let p = paths[paths.len() - turned];
s.edit("test", |d, _| {
let data = d.node_mut(NodeId(p)).unwrap().path_data_mut().unwrap();
*data = vectorcraft_geom::PathData::from_bezpath(&data.to_bezpath().reverse_subpaths());
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [c]})).unwrap();
assert!(s.execute("type.retype", &json!({})).is_err(), "nonzero, contour {turned} turned paints the counter");
s.execute("path.setFillRule", &json!({"rule": "evenOdd", "ids": [c]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!(["do"]), "contour {turned} turned: {r}");
assert_eq!(r["unmatched"], json!([]), "{r}");
}
}
#[test]
fn a_compound_whose_glyph_stays_an_outline_keeps_its_other_glyphs_too() {
let mut s = session();
@@ -1749,7 +1936,7 @@ fn the_glyphs_after_one_type_cannot_draw_keep_their_tracking() {
l.matches[bad].gid = other;
let bad_id = l.pieces[bad];
let mut unmatched = vec![];
let out = super::verified(vec![l], false, &mut unmatched);
let out = super::verified(vec![l], false, &Default::default(), &mut unmatched);
assert_eq!(unmatched, vec![bad_id], "{bad}");
let last = out.last().unwrap();
assert_eq!(last.pieces.len(), 5 - bad, "{bad}: {:?}", out.iter().map(|l| (l.pieces.len(), l.tracking)).collect::<Vec<_>>());
@@ -1801,7 +1988,7 @@ fn the_rest_of_a_widely_tracked_line_keeps_its_tracking_after_a_split() {
assert_eq!(l.tracking, 8000.0);
l.matches[0].gid += 1;
let mut unmatched = vec![];
let out = super::verified(vec![l], false, &mut unmatched);
let out = super::verified(vec![l], false, &Default::default(), &mut unmatched);
assert_eq!(unmatched.len(), 1);
let last = out.last().unwrap();
assert_eq!((last.pieces.len(), last.tracking), (99, 8000.0), "{:?}", out.iter().map(|l| (l.pieces.len(), l.tracking)).collect::<Vec<_>>());
@@ -1823,7 +2010,7 @@ fn glyphs_type_cannot_draw_do_not_use_up_the_tracking_measure() {
m.gid += 1;
}
let mut unmatched = vec![];
let out = super::verified(vec![l], false, &mut unmatched);
let out = super::verified(vec![l], false, &Default::default(), &mut unmatched);
assert_eq!(unmatched.len(), 5);
let last = out.last().unwrap();
assert_eq!((last.pieces.len(), last.tracking), (95, 300.0), "{:?}", out.iter().map(|l| (l.pieces.len(), l.tracking)).collect::<Vec<_>>());
@@ -1916,7 +2103,7 @@ fn a_long_run_after_a_split_keeps_a_tracking_under_one_unit_that_adds_up() {
assert!(near(l.tracking, 0.2, 0.01), "{}", l.tracking);
l.matches[0].gid += 1;
let mut unmatched = vec![];
let out = super::verified(vec![l], false, &mut unmatched);
let out = super::verified(vec![l], false, &Default::default(), &mut unmatched);
assert_eq!(unmatched.len(), 1);
let last = out.last().unwrap();
assert!(last.pieces.len() == 399 && near(last.tracking, 0.2, 0.01), "{:?}", out.iter().map(|l| (l.pieces.len(), l.tracking)).collect::<Vec<_>>());
@@ -1946,7 +2133,7 @@ fn a_long_rest_tracked_past_a_negative_space_advance_keeps_its_word_spaces_after
assert_eq!((l.text.as_str(), l.tracking), (text.as_str(), tracking), "{times}");
l.matches[0].gid += 1;
let mut unmatched = vec![];
let out = super::verified(vec![l], false, &mut unmatched);
let out = super::verified(vec![l], false, &Default::default(), &mut unmatched);
assert_eq!(unmatched.len(), 1, "{times}");
let texts: Vec<(&str, f64)> = out.iter().map(|l| (l.text.as_str(), l.tracking)).collect();
assert_eq!(texts, vec![(&text[1..], tracking)], "{times}");
@@ -1983,7 +2170,7 @@ fn a_long_rest_with_a_positive_pair_kerning_that_matches_a_space_gains_no_space_
assert_eq!((l.text.as_str(), l.tracking), (text.as_str(), tracking));
l.matches[0].gid += 1;
let mut unmatched = vec![];
let out = super::verified(vec![l], false, &mut unmatched);
let out = super::verified(vec![l], false, &Default::default(), &mut unmatched);
assert_eq!(unmatched.len(), 1);
let texts: Vec<(&str, f64)> = out.iter().map(|l| (l.text.as_str(), l.tracking)).collect();
assert_eq!(texts, vec![(&text[1..], tracking)]);
@@ -2103,7 +2290,7 @@ fn a_long_tightly_tracked_rest_keeps_its_word_spaces_after_a_split() {
assert_eq!((l.text.as_str(), l.tracking), (text.as_str(), tracking));
l.matches[0].gid += 1;
let mut unmatched = vec![];
let out = super::verified(vec![l], false, &mut unmatched);
let out = super::verified(vec![l], false, &Default::default(), &mut unmatched);
assert_eq!(unmatched.len(), 1);
let texts: Vec<(&str, f64)> = out.iter().map(|l| (l.text.as_str(), l.tracking)).collect();
assert_eq!(texts, vec![(&text[1..], tracking)]);
+11 -8
View File
@@ -11,7 +11,7 @@ use vectorcraft_geom::PathData;
use vectorcraft_tools::builder::is_live_paint;
use super::appearance::{ItemTarget, edit_items, item_target};
use super::paint::{live_paint_covered, live_paint_parts_skipped, painted};
use super::paint::{live_paint_parts_skipped, painted};
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, ok, str_param};
use crate::DocState;
use crate::inspect::{ALIGNS, CAPS, JOINS, StrokeMixed, node_stroke, scale_layer};
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Stroke Options",
["Window", "Stroke"],
None,
"{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path, stop?}} (a custom head with its art, as document.inspect reports one; stop: where the stroke ends under the head, in head units back from the tip, 0..64 (otherwise, or without one, halfway along the head); refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone; a Live Paint group takes them on its edges only. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the stroke for new art changes (the bucket paints edges with its color and weight) → {objects: how many objects took the stroke options}",
"{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path, stop?}} (a custom head with its art, as document.inspect reports one; stop: where the stroke ends under the head, in head units back from the tip, 0..64 (otherwise, or without one, halfway along the head); refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, defaultsOnly?: bool, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone; a Live Paint group takes them on its edges only. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given (refused with ids, id or item), only the stroke for new art changes (the bucket paints edges with its color and weight) → {objects: how many objects took the stroke options}",
has_doc,
stroke_set
),
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Stroke Weight Up",
[],
Some("Cmd+Alt+."),
"{ids?|id?} raise each selected stroke's weight by one step of Units › Stroke (a quarter unit below one unit, then whole units; up to 1000 pt), each from its own weight: the selected objects' active or top stroke, type's stroked characters; objects without a stroke, and a Live Paint group's faces, are left alone. With nothing selected (and no ids), the weight of the next object drawn, and so while the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none). On a path directly in a graph series, the graph also stores the new weight of the topmost visible stroke, and on a graph label the new weight of its characters' stroke or its stroke row for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {objects}",
"{ids?|id?, defaultsOnly?: bool (as stroke.set)} raise each selected stroke's weight by one step of Units › Stroke (a quarter unit below one unit, then whole units; up to 1000 pt), each from its own weight: the selected objects' active or top stroke, type's stroked characters; objects without a stroke, and a Live Paint group's faces, are left alone. With nothing selected (and no ids), the weight of the next object drawn, and so while the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), or `defaultsOnly: true` is given. On a path directly in a graph series, the graph also stores the new weight of the topmost visible stroke, and on a graph label the new weight of its characters' stroke or its stroke row for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {objects}",
has_doc,
|s, p| stroke_step(s, p, true)
),
@@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Stroke Weight Down",
[],
Some("Cmd+Alt+,"),
"{ids?|id?} lower each selected stroke's weight by one step, as stroke.weightUp raises it, down to a quarter unit (a thinner weight is kept) → {objects}",
"{ids?|id?, defaultsOnly?: bool (as stroke.set)} lower each selected stroke's weight by one step, as stroke.weightUp raises it, down to a quarter unit (a thinner weight is kept) → {objects}",
has_doc,
|s, p| stroke_step(s, p, false)
),
@@ -50,7 +50,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Stroke Options",
[],
None,
"{arrowScale?: [start %, end %], swapArrows?: bool, flipProfile?: \"along\"|\"across\", brush?: name|null, item?: stroke item index|null, aligned?: bool (as stroke.set), ids?|id?, target?: \"object\"|\"contents\"} Stroke panel extras (with nothing selected, all but brush set up the next object drawn, and so while the Live Paint Bucket is the active tool and no ids, id, item or brush are given, a null ids or id counting as none; without item, a Live Paint group's edges take them and its faces are left alone)",
"{arrowScale?: [start %, end %], swapArrows?: bool, flipProfile?: \"along\"|\"across\", brush?: name|null, item?: stroke item index|null, aligned?: bool (as stroke.set), ids?|id?, defaultsOnly?: bool (as stroke.set; refused with brush), target?: \"object\"|\"contents\"} Stroke panel extras (with nothing selected, all but brush set up the next object drawn, and so while the Live Paint Bucket is the active tool, or with `defaultsOnly: true`, and no ids, id, item or brush are given, a null ids or id counting as none; without item, a Live Paint group's edges take them and its faces are left alone)",
has_doc,
stroke_advanced
),
@@ -465,7 +465,7 @@ impl Session {
// A Live Paint group without edges shows the next selected object's stroke; any other object
// without a painted object shows none. A face or edge selected with its Live Paint group counts
// with the group, wherever it is in the selection.
let covered = live_paint_covered(&st.doc, &st.selection.objects);
let covered = st.selection_live_paint_covered(&st.selection.objects);
for id in st.selection.objects.iter().filter(|id| !covered.contains(*id)) {
let Some(n) = st.doc.node(*id) else { continue };
let mut nodes = vec![];
@@ -540,7 +540,7 @@ impl DocState {
} else {
let selected: Vec<&Node> = self.selection.objects.iter().filter_map(|id| self.doc.node(*id)).collect();
// The faces and edges of the selected Live Paint groups: selected as well, they count with their group's.
let covered = live_paint_covered(&self.doc, &self.selection.objects);
let covered = self.selection_live_paint_covered(&self.selection.objects);
for n in selected.into_iter().filter(|n| !covered.contains(&n.id)) {
painted(n, true, true, &mut nodes);
}
@@ -618,7 +618,10 @@ fn stroke_advanced(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, "nothing to change"));
}
// As stroke.set: the stroke the Live Paint Bucket paints with changes; the selection keeps its own.
// A brush still goes to the selection.
// A brush still goes to the selection, and new art has no brush for `defaultsOnly` to set.
if brush.is_some() && super::switch_or(p, "defaultsOnly", false, C)? {
return Err(bad(C, "`defaultsOnly` cannot be combined with `brush`"));
}
let bucket_p = if brush.is_none() { super::paint::bucket_color_params(s, p, C)? } else { None };
let bucket = bucket_p.is_some();
let p = bucket_p.as_ref().unwrap_or(p);
+8 -7
View File
@@ -329,14 +329,15 @@ impl Session {
let g = st.doc.graphic_style_by_id(n.extras().graphic_style?)?;
Some((g, in_sync(n, g)))
}
}
/// A copy of `n` with style `g` applied as `graphicStyle.apply` applies it (Override Character
/// Color as set): the Graphic Styles panel's previews.
pub fn styled(&self, n: &Node, g: &GraphicStyle) -> Node {
let mut n = n.clone();
style_node(&mut n, g, &mut None, self.prefs.override_char_color);
n
}
/// A copy of `n` with style `g` applied as `graphicStyle.apply` applies it, type's characters too
/// with `override_char_color` (the preference Override Character Color): the Graphic Styles
/// panel's previews.
pub fn styled_node(n: &Node, g: &GraphicStyle, override_char_color: bool) -> Node {
let mut n = n.clone();
style_node(&mut n, g, &mut None, override_char_color);
n
}
// ---------- commands ----------
+11 -3
View File
@@ -50,7 +50,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add to Swatches",
["Window", "Swatch Libraries"],
None,
"{library: id or name, names?: [swatch or colour group names in the library] (default: all of it; a group comes as a colour group, a single swatch ungrouped), apply?: \"fill\"|\"stroke\" (also apply the first one to the selection and the defaults, as paint.setFill / paint.setStroke), focus?: true (with apply: false keeps the active proxy)} copy library swatches into the document as one undo step. A swatch the document already has (same name and paint, and for a color the same process, global or spot kind, or a numbered copy of that name with the same color when the name has another color there) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"); a tint or gradient whose global or spot color comes in under a numbered name, or is in the document as such a numbered copy, links to that copy; a global or spot color it links to that the document lacks comes in with it. A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, also when its art links to the document's own color of a name, and a name another pattern or swatch has gets a number; a global or spot color its art links to whose name the document gives another color comes in numbered, skipping the names of the library's other swatches, and the pattern links to it, not to a numbered copy that is the library's other swatch of that name; a swatch of a numbered library name that the art brings, such as a tint \"Ink 2\" or a pattern's swatch when its pattern comes in under another name, keeps that name when the document does not use it, and a pattern swatch or a pattern the art is painted with that comes in numbered skips the library's other names too → {library, added: [names in the document, the colors patterns, tints and gradients brought included], existing: [names already there], applied?: name}",
"{library: id or name, names?: [swatch or colour group names in the library] (default: all of it; a group comes as a colour group, a single swatch ungrouped), apply?: \"fill\"|\"stroke\" (also apply the first one to the selection and the defaults, as paint.setFill / paint.setStroke), focus?: true (with apply: false keeps the active proxy), defaultsOnly?: bool (with apply: apply it to the defaults only, as paint.setFill does; the journal records it for swatches applied while the Live Paint Bucket is the active tool)} copy library swatches into the document as one undo step. A swatch the document already has (same name and paint, and for a color the same process, global or spot kind, or a numbered copy of that name with the same color when the name has another color there) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"); a tint or gradient whose global or spot color comes in under a numbered name, or is in the document as such a numbered copy, links to that copy; a global or spot color it links to that the document lacks comes in with it. A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, also when its art links to the document's own color of a name, and a name another pattern or swatch has gets a number; a global or spot color its art links to whose name the document gives another color comes in numbered, skipping the names of the library's other swatches, and the pattern links to it, not to a numbered copy that is the library's other swatch of that name; a swatch of a numbered library name that the art brings, such as a tint \"Ink 2\" or a pattern's swatch when its pattern comes in under another name, keeps that name when the document does not use it, and a pattern swatch or a pattern the art is painted with that comes in numbered skips the library's other names too → {library, added: [names in the document, the colors patterns, tints and gradients brought included], existing: [names already there], applied?: name}",
has_doc,
add
),
@@ -98,6 +98,8 @@ pub fn specs() -> Vec<CommandSpec> {
#[derive(Clone, Debug, Default)]
pub struct DesignLibraries {
libs: Vec<DesignLibrary>,
/// How many times a library was set; the next library's [`DesignLibrary::generation`].
loads: u64,
}
/// A document loaded as a swatch library that holds graph designs ([`DesignLibraries`]).
@@ -109,6 +111,9 @@ pub struct DesignLibrary {
pub name: String,
/// The designs and the resources their art uses.
pub doc: Arc<vectorcraft_doc::Document>,
/// Which load of the library this is: it differs from every other load's, so a picture of a design of
/// this library is stale once the library is loaded again.
pub generation: u64,
}
impl DesignLibraries {
@@ -126,8 +131,9 @@ impl DesignLibraries {
/// before; with no designs, `id` no longer has any.
fn set(&mut self, id: &str, name: &str, doc: Option<vectorcraft_doc::Document>) {
self.libs.retain(|l| l.id != id);
self.loads += 1;
if let Some(doc) = doc {
self.libs.push(DesignLibrary { id: id.to_string(), name: name.to_string(), doc: Arc::new(doc) });
self.libs.push(DesignLibrary { id: id.to_string(), name: name.to_string(), doc: Arc::new(doc), generation: self.loads });
}
}
}
@@ -1142,6 +1148,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
Some(other) => return Err(bad(C, format!("apply is \"fill\" or \"stroke\", not `{other}`"))),
};
let focus = switch_or(p, "focus", true, C)?;
switch_or(p, "defaultsOnly", false, C)?;
let picked = picked(&lib, &names_param(p, C)?, C)?;
// Swatches the document already has (same name and paint; for a pattern swatch, a swatch of the
// same pattern) are reused, not added again. The patterns are in a built-in pattern library's
@@ -1578,7 +1585,8 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
let mut out = json!({"library": shown_library_id(s, &info.id), "added": added_names, "existing": names(&existing)});
if let (Some(cmd), Some((_, first))) = (apply, picked.first()) {
let name = added.iter().chain(&existing).find(|(l, _)| *l == first.name).map_or(first.name.clone(), |(_, n)| n.clone());
s.execute(cmd, &json!({"swatch": name, "focus": focus}))?;
let only = super::paint::defaults_only(s, p, C)?;
s.execute(cmd, &super::paint::with_defaults_only(json!({"swatch": name, "focus": focus}), only))?;
// Adding and applying undo together.
squash(s, undo_before, "Add to Swatches");
out["applied"] = json!(name);
+23 -13
View File
@@ -11,8 +11,8 @@ use super::menucmds::whole_or;
use super::stroke::StrokeChange;
use super::typecmd::refresh_bounds;
use super::{
CommandSpec, EngineError, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, color_value, has_doc, has_selection, index,
number_or, object_param, point_param, str_param, switch_or, targets, text_param,
CommandSpec, EngineError, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, color_value, finite_numbers, has_doc, has_selection,
index, number_or, object_param, str_param, switch_or, targets, text_param,
};
pub fn specs() -> Vec<CommandSpec> {
@@ -85,7 +85,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Area / Path Type",
[],
None,
"{path: id, mode: \"area\"|\"onPath\", text?: \"\", vertical?: bool = false, at?: [x, y] (on-path start: nearest point), size?: pt 0.1..1296 (outside it: an error), font?, style?, color?, keepModel? (as text.create), fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (area: as text.areaOptions; default autoHeight when the autoSizeAreaType preference is on), placeholder?: bool (placeholder text instead, as text.create), justify?, leadingModel?, charAlign? (as text.create)} turn a path into an area-type frame or a type-on-a-path baseline (the path's paint is dropped) → {id, bounds: {x, y, width, height} (as text.create), overflow?: [id] (the text doesn't fit; left out when it fits)}",
"{path: id, mode: \"area\"|\"onPath\", text?: \"\", vertical?: bool = false, at?: [x, y] (on-path start: nearest point; anything but two numbers: an error), size?: pt 0.1..1296 (outside it: an error), font?, style?, color?, keepModel? (as text.create), fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (area: as text.areaOptions; default autoHeight when the autoSizeAreaType preference is on), placeholder?: bool (placeholder text instead, as text.create), justify?, leadingModel?, charAlign? (as text.create)} turn a path into an area-type frame or a type-on-a-path baseline (the path's paint is dropped) → {id, bounds: {x, y, width, height} (as text.create), overflow?: [id] (the text doesn't fit; left out when it fits)}",
has_doc,
create_in_path
),
@@ -255,9 +255,15 @@ fn byte_param(p: &Value, k: &str) -> Option<usize> {
/// The byte offset that `p` gives for `k`, or `default` when `p` leaves it out or gives null. Any
/// other value that is not a whole number of at least 0, such as `"2"`, `-1` or `1.5`, is an error.
fn offset_or(p: &Value, k: &str, default: usize, cmd: &str) -> Result<usize> {
Ok(offset_given(p, k, cmd)?.unwrap_or(default))
}
/// The byte offset that `p` gives for `k`, or `None` when `p` leaves it out or gives null. Any
/// other value that is not a whole number of at least 0, such as `"2"`, `-1` or `1.5`, is an error.
fn offset_given(p: &Value, k: &str, cmd: &str) -> Result<Option<usize>> {
match p.get(k) {
None | Some(Value::Null) => Ok(default),
Some(_) => Ok(index(whole_or(p, k, 0, cmd)?)),
None | Some(Value::Null) => Ok(None),
Some(_) => Ok(Some(index(whole_or(p, k, 0, cmd)?))),
}
}
@@ -280,7 +286,7 @@ pub(crate) fn edit_range(s: &mut Session, p: &Value) -> Result<Value> {
None | Some(Value::Null) => None,
Some(v) => Some(serde_json::from_value(v.clone()).map_err(|e| bad(C, format!("bad `runs`: {e}")))?),
};
let insert = str_param(p, "insert").unwrap_or("").to_string();
let insert = text_param(p, "insert", C)?.unwrap_or("").to_string();
let clear = clear_param(s, p, id, C)?;
let caret = s.edit("Typing", |d, _| {
for other in &clear {
@@ -1313,8 +1319,7 @@ pub fn effective_kerning(db: &vectorcraft_text::FontDb, t: &TextObject, lay: &ve
/// The character at byte `start` of `p` in text object `t`, its bytes and its font's face. An error
/// when there is no character there, it is an inline graphic, or its font is not available.
fn glyph_target(t: &TextObject, p: &Value, c: &str) -> Result<(char, std::ops::Range<usize>, std::sync::Arc<vectorcraft_text::FontFace>)> {
check_numbers(p, &["start"], c)?;
let start = byte_param(p, "start").ok_or_else(|| bad(c, "missing `start` (the byte offset of a character)"))?;
let start = offset_given(p, "start", c)?.ok_or_else(|| bad(c, "missing `start` (the byte offset of a character)"))?;
let mut at = 0;
for run in &t.runs {
let end = at + run.text.len();
@@ -1558,8 +1563,7 @@ fn glyph_alternates(s: &mut Session, p: &Value) -> Result<Value> {
fn touch_type(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "text.touchType";
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?;
check_numbers(p, &["start"], C)?;
let start = byte_param(p, "start").ok_or_else(|| bad(C, "missing `start` (the byte offset of a character)"))?;
let start = offset_given(p, "start", C)?.ok_or_else(|| bad(C, "missing `start` (the byte offset of a character)"))?;
if !["dx", "dy", "hScale", "vScale", "rotation"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) {
return Err(bad(C, "nothing to change: give dx, dy, hScale, vScale or rotation"));
}
@@ -1797,7 +1801,7 @@ fn touch_type(s: &mut Session, p: &Value) -> Result<Value> {
fn create_in_path(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "text.createInPath";
let pid = object_param(p, "path", C)?.ok_or_else(|| bad(C, "missing `path` (a path object id)"))?;
let on_path = match str_param(p, "mode").unwrap_or("area") {
let on_path = match text_param(p, "mode", C)?.unwrap_or("area") {
"area" => false,
"onPath" | "path" => true,
o => return Err(bad(C, format!("mode must be area|onPath, got {o}"))),
@@ -1815,8 +1819,12 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result<Value> {
check_switches(p, &["vertical", "placeholder"], C)?;
super::color_param(p, "color", C)?;
let style = super::create::new_type_style(s, p, C)?;
let text = str_param(p, "text").unwrap_or("").to_string();
let start = match point_param(p, "at") {
let text = text_param(p, "text", C)?.unwrap_or("").to_string();
let at = match p.get("at").filter(|v| !v.is_null()) {
None => None,
Some(v) => Some(finite_numbers::<2>(v).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad(C, "`at` must be a point: [x, y]"))?),
};
let start = match at {
Some(at) if on_path => vectorcraft_geom::ArcPath::new(path).fraction_at(at).unwrap_or(0.0),
_ => 0.0,
};
@@ -1842,6 +1850,7 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result<Value> {
system_layout: false,
fractional_widths: true,
list_count: 0,
file_fonts: None,
list_level_counts: Vec::new(),
cached_bounds: None,
cached_baselines: Vec::new(),
@@ -2150,6 +2159,7 @@ fn headline_tracking(t: &TextObject, target: f64) -> Option<f64> {
system_layout: t.system_layout,
fractional_widths: t.fractional_widths,
list_count: 0,
file_fonts: None,
list_level_counts: Vec::new(),
cached_bounds: None,
cached_baselines: Vec::new(),
+2 -2
View File
@@ -13,7 +13,7 @@ use super::edit::selected_roots;
use super::pathops::{length_given, number_given, shape_node};
use super::{
CommandSpec, EngineError, Result, Session, bad, check_numbers, cmd, color_value, f64_req, has_doc, has_selection, index, index_opt, number_or,
object_param, ok, str_param, switch_or, targets, text_param,
object_param, ok, switch_or, targets, text_param,
};
pub fn specs() -> Vec<CommandSpec> {
@@ -873,7 +873,7 @@ pub(crate) fn style_chars(t: &mut TextObject, range: Option<TextRange>, mut f: i
}
fn set_text(s: &mut Session, p: &Value) -> Result<Value> {
let text = str_param(p, "text").ok_or_else(|| bad("text.setText", "missing `text`"))?.to_string();
let text = text_param(p, "text", "text.setText")?.ok_or_else(|| bad("text.setText", "missing `text`"))?.to_string();
let ids = text_targets(s, p, "text.setText")?;
// The text the type already has is no undo step.
edit_if_nodes_changed(s, "Typing", &ids, |d| {
+9 -2
View File
@@ -30,7 +30,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Sample Color",
[],
None,
"{color (#rrggbbaa and #rgba are refused), stroke?: bool (default: whichever proxy is active), ids?, stop?: index, clearStroke?: bool} sample a color into the active fill/stroke (and the selection; `ids: []` changes only the paint default, and so does a sample without ids while the Live Paint Bucket is the active tool, `stop` included); `clearStroke: true` requires `stroke: false`, `ids: []` and no `stop`, and clears the default stroke after sampling an image into the fill; with `stop`, recolor that stop of the gradient behind the proxy instead (paint.editGradient); with `stop` and objects in `ids`, whatever tool is active, the stops come from the topmost fill (or stroke) of the first object that paint.editGradient edits for those ids (a compound path for its member); in a CMYK document an RGB color is stored as CMYK through the color settings, as paint.setFill stores it",
"{color (#rrggbbaa and #rgba are refused), stroke?: bool (default: whichever proxy is active), ids?, defaultsOnly?: bool, stop?: index, clearStroke?: bool} sample a color into the active fill/stroke (and the selection; `ids: []` changes only the paint default, and so does a sample without ids while the Live Paint Bucket is the active tool or with `defaultsOnly: true` (refused with ids), `stop` included); `clearStroke: true` requires `stroke: false`, `ids: []` and no `stop`, and clears the default stroke after sampling an image into the fill; with `stop`, recolor that stop of the gradient behind the proxy instead (paint.editGradient); with `stop` and objects in `ids`, whatever tool is active, the stops come from the topmost fill (or stroke) of the first object that paint.editGradient edits for those ids (a compound path for its member); in a CMYK document an RGB color is stored as CMYK through the color settings, as paint.setFill stores it",
has_doc,
sample_color
),
@@ -523,6 +523,10 @@ fn sample_color(s: &mut Session, p: &Value) -> Result<Value> {
if clear_stroke && (stroke || p.get("stroke") != Some(&Value::Bool(false)) || p.get("ids") != Some(&json!([])) || p.get("stop").is_some()) {
return Err(bad(C, "`clearStroke` requires `stroke: false`, `ids: []` and no `stop`"));
}
let only = super::switch_or(p, "defaultsOnly", false, C)?;
if only && p.get("ids").is_some_and(|v| !v.is_null()) {
return Err(bad(C, "`defaultsOnly` cannot be combined with `ids`, `id` or `item`"));
}
let c = p.get("color").ok_or_else(|| bad(C, "missing color"))?;
let (id, mut q) = match p.get("stop") {
None | Some(Value::Null) => (if stroke { "paint.setStroke" } else { "paint.setFill" }, json!({ "color": c })),
@@ -532,7 +536,9 @@ fn sample_color(s: &mut Session, p: &Value) -> Result<Value> {
let (paint, source) = match given_stop_paint(s, p, stroke)? {
Some(paint) => (paint, "the paint of the first object in `ids`"),
None => {
let (fill, stroke_paint) = s.proxy_paints();
// The default's gradient with `defaultsOnly`, as the proxies show it while the Live
// Paint Bucket paints.
let (fill, stroke_paint) = if only { (s.paint.fill.clone(), s.paint.stroke.clone()) } else { s.proxy_paints() };
(if stroke { stroke_paint } else { fill }, "the paint behind the proxy")
}
};
@@ -548,6 +554,7 @@ fn sample_color(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(ids) = p.get("ids") {
q["ids"] = ids.clone();
}
let q = super::paint::with_defaults_only(q, only);
let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.into()))?;
let result = super::run_checked(s, spec, &q)?;
if clear_stroke {
+213 -5
View File
@@ -25,10 +25,11 @@ pub struct DocState {
/// Panel state, not art selection: not saved, not undoable (`layer.setCurrent`,
/// `layer.highlight`).
pub layer_rows: Vec<NodeId>,
/// The row the last Locate Object or Locate Layer (`layer.locate`) highlighted, until the
/// Layers panel takes it: the panel opens the layers around that row and scrolls to it, also
/// when the row was already highlighted. Panel state: not saved, not undoable.
pub locate_reveal: Option<NodeId>,
/// What the Layers panel reveals at its next pass, until the panel takes it: the panel opens
/// the layers around the row and scrolls to it, also when the row was already highlighted.
/// Set by `layer.locate` and, for what a top-level command, an interaction's commit or a
/// selection changed, by [`DocState::request_reveal`]. Panel state: not saved, not undoable.
pub layers_reveal: Option<LayersReveal>,
/// The variable highlighted in the Variables panel: what its Delete, Options… and Select
/// Bound Object act on. Panel state, not art selection: not saved, not undoable
/// (`variable.highlight`). A name, so renaming a variable moves the highlight with it.
@@ -128,6 +129,11 @@ pub struct DocState {
/// paths the document links to are looked at within them later too, when the Links panel
/// asks about a link outside any caller's scope.
pub opened_by: Option<Arc<file_access::AutomationRoots>>,
/// What the commands scripts ran did to the document since the person last opened or saved it:
/// `None` when they did nothing. The commands a script runs read and write the document's file,
/// and read the files it links to, only as the person left them ([`DocState::as_person_left`]).
/// Not saved.
pub(crate) by_script: Option<ByScript>,
/// The live-effect plug-in stages deferred while the document is drawn on screen, and the time
/// budget of its first view ([`vectorcraft_plugins::deferred`]). Not saved.
pub plugin_effects: vectorcraft_plugins::deferred::Deferrals,
@@ -144,6 +150,50 @@ pub struct DocState {
/// measured: the next refresh checks only the layer trees that differ from it
/// ([`cmd::inline::refresh`]). Not saved.
pub(crate) inline_resolved: Option<cmd::inline::Resolved>,
/// The selected objects as [`crate::Session::select`] last checked them or the proxies last
/// read them, with the document they were checked in ([`SelectionRecord`]). Not saved.
pub(crate) selection_record: Option<SelectionRecord>,
}
/// A selection of objects alone ([`objects_only`]) with the document it was checked or read in:
/// while the document and the selected objects stay the same, a command that adds objects checks
/// and reads only the added ones.
#[derive(Clone, Debug)]
pub(crate) struct SelectionRecord {
/// The document, held as [`EmptyArtboards::doc`] holds it.
pub(crate) doc: std::sync::Weak<Document>,
pub(crate) objects: Vec<NodeId>,
/// Lock Guides as it was when [`crate::Session::select`] left these objects selected; `None`
/// when it did not.
pub(crate) settled: Option<bool>,
/// What the proxies read from these objects; `None` when they were not read.
pub(crate) paints: Option<cmd::SelectionPaints>,
}
/// Whether `sel` holds selected objects and nothing else: no anchors, segments, key, target,
/// slices, ruler guides, object of a symbol instance's art or object on a path.
pub(crate) fn objects_only(sel: &Selection) -> bool {
sel.anchors.is_empty()
&& sel.segments.is_empty()
&& sel.key.is_none()
&& sel.target.is_none()
&& sel.slices.is_empty()
&& sel.guides.is_empty()
&& sel.key_guide.is_none()
&& sel.key_anchor.is_none()
&& sel.symbol_part.is_none()
&& sel.on_path_member.is_none()
}
/// What the commands scripts ran did to an open document since the person last opened or saved it
/// ([`DocState::by_script`]).
#[derive(Clone, Debug)]
pub(crate) enum ByScript {
/// A command a script ran opened it (or made it).
Opened,
/// A command a script ran changed it or gave it another file: the document, its file and the
/// file it was read from as they were before the first such command.
Changed { doc: Arc<Document>, path: Option<String>, links_from: Option<String> },
}
/// Whether a document has an artboard for Delete Empty Artboards to delete, with the document that
@@ -179,6 +229,30 @@ thread_local! {
static NEXT_DOC_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
/// What the Layers panel is asked to reveal ([`DocState::layers_reveal`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LayersReveal {
/// Open the layers around this row and scroll to it: it was highlighted, located or isolated.
Row(NodeId),
/// The current layer changed with no row highlighted: reveal that layer.
Current(NodeId),
/// The last selected object changed: reveal its row when Panel Options › Locate Selected
/// Objects is on.
Selected(NodeId),
}
/// What decides a [`LayersReveal`], as of one moment: the isolation, the highlighted rows, the
/// current layer and the last selected object of one document, with the request pending then.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct LayersView {
uid: u64,
isolation: Option<NodeId>,
rows: Vec<NodeId>,
active_layer: Option<NodeId>,
last_selected: Option<NodeId>,
reveal: Option<LayersReveal>,
}
/// The rows open in the Layers panel: the layers, sublayers and groups that show what they hold.
/// A document opens with the ones it was saved with ([`Document::layers_open`]), else with only
/// its top-level layers open (a `.ai` another app wrote opens with none open).
@@ -326,7 +400,7 @@ impl DocState {
revision: 1,
active_layer,
layer_rows: vec![],
locate_reveal: None,
layers_reveal: None,
variables_highlight: None,
variables_sort: Default::default(),
isolation: None,
@@ -360,11 +434,77 @@ impl DocState {
links_from: None,
last_perspective: None,
opened_by: file_access::current(),
by_script: None,
empty_artboards: Default::default(),
plugin_effects: Default::default(),
art_to_fit: Default::default(),
measured_in_own: None,
inline_resolved: None,
selection_record: None,
}
}
/// The [`SelectionRecord`] of the selection now: `None` when the document or the selected
/// objects changed since it was made, or when anything besides whole objects is selected
/// ([`objects_only`]). Only a new [`Document`] makes the record stale: the document's new art
/// is the one state that changes in place and matters to it, and [`crate::Session::select`]
/// checks the whole selection while there is new art.
pub(crate) fn selection_record(&self) -> Option<&SelectionRecord> {
self.selection_record
.as_ref()
.filter(|r| std::ptr::eq(r.doc.as_ptr(), Arc::as_ptr(&self.doc)) && objects_only(&self.selection) && r.objects == self.selection.objects)
}
/// What the proxies read from the selected objects, when the [`SelectionRecord`] of the
/// selection now holds it.
pub(crate) fn selection_paints(&self) -> Option<&cmd::SelectionPaints> {
self.selection_record().and_then(|r| r.paints.as_ref())
}
/// Keep the [`SelectionRecord`] of the selection that [`crate::Session::select`] left, with
/// Lock Guides `guides_locked`. `record` is the record of the selection before: when the
/// selected objects start with its objects, the added objects are read into its paints.
pub(crate) fn record_selection(&mut self, record: Option<SelectionRecord>, guides_locked: bool) {
if !objects_only(&self.selection) {
self.selection_record = None;
return;
}
let objects = &self.selection.objects;
self.selection_record = Some(match record {
Some(mut r) if objects.starts_with(&r.objects) => {
let added = &objects[r.objects.len()..];
if let Some(p) = &mut r.paints {
p.add(&self.doc, added);
}
r.objects.extend_from_slice(added);
r.settled = Some(guides_locked);
r
}
_ => SelectionRecord { doc: Arc::downgrade(&self.doc), objects: objects.clone(), settled: Some(guides_locked), paints: None },
});
}
/// The document, its file and the file it was read from as the person last left them, for the
/// commands scripts run ([`DocState::by_script`]): `None` for a document a script's command
/// opened.
pub(crate) fn as_person_left(&self) -> Option<(&Arc<Document>, Option<&str>, Option<&str>)> {
match &self.by_script {
None => Some((&self.doc, self.path.as_deref(), self.links_from.as_deref())),
Some(ByScript::Opened) => None,
Some(ByScript::Changed { doc, path, links_from }) => Some((doc, path.as_deref(), links_from.as_deref())),
}
}
/// Notes what a command a script ran did to the document, which was `was` (the document, its
/// file and the file it was read from) before the command ran, or not open when `was` is
/// `None`. The first change is kept until the person saves the document.
pub(crate) fn note_script_command(&mut self, was: Option<(&Arc<Document>, &Option<String>, &Option<String>)>) {
if self.by_script.is_some() {
return;
}
let Some((doc, path, links_from)) = was else {
self.by_script = Some(ByScript::Opened);
return;
};
if !Arc::ptr_eq(doc, &self.doc) || *path != self.path || *links_from != self.links_from {
self.by_script = Some(ByScript::Changed { doc: doc.clone(), path: path.clone(), links_from: links_from.clone() });
}
}
/// `measure`'s answer for the document now. `measure` runs once for each version of the document,
@@ -657,6 +797,74 @@ impl DocState {
pub fn highlighted_rows(&self) -> Vec<NodeId> {
self.layer_rows.iter().copied().filter(|id| self.doc.node(*id).is_some()).collect()
}
/// What decides the Layers panel's reveal request now.
pub(crate) fn layers_view(&self) -> LayersView {
LayersView {
uid: self.uid,
isolation: self.isolation,
rows: self.layer_rows.clone(),
active_layer: self.active_layer,
last_selected: self.selection.objects.last().copied(),
reveal: self.layers_reveal,
}
}
/// [`DocState::layers_view`] as it was when interaction `it` began: what a commit of the
/// interaction changed is compared with that, since the previews changed the state meanwhile.
pub(crate) fn layers_view_before(&self, it: &Interaction) -> LayersView {
LayersView {
uid: self.uid,
isolation: it.isolation,
rows: it.layer_rows.clone(),
active_layer: it.active_layer,
last_selected: it.selection.objects.last().copied(),
reveal: self.layers_reveal,
}
}
/// Ask the Layers panel to reveal what changed since `before`, in this order: isolation entered
/// or left, the highlighted rows, the last selected object, the current layer. A request made
/// meanwhile (`layer.locate`) stands, and nothing is asked while an interaction is open, so a
/// drag's previews reveal nothing and its commit does.
pub(crate) fn request_reveal(&mut self, before: &LayersView) {
if self.uid != before.uid || self.layers_reveal != before.reveal || self.interaction.is_some() {
return;
}
let now = self.layers_view();
let mut request = None;
if now.isolation != before.isolation {
request = self.reveal_isolation(now.isolation, before.isolation);
}
if request.is_none() && now.rows != before.rows {
request = self.highlighted_rows().first().copied().map(LayersReveal::Row);
}
// A new selection asks for its object even when it changed the current layer too: the panel
// falls back to the current layer when it does not locate the object.
if request.is_none() && now.last_selected != before.last_selected {
request = now.last_selected.map(LayersReveal::Selected);
// An emptied selection leaves no object to locate.
if request.is_none() && matches!(self.layers_reveal, Some(LayersReveal::Selected(_))) {
self.layers_reveal = None;
}
}
if request.is_none() && now.active_layer != before.active_layer {
request = self.current_layer().map(LayersReveal::Current);
}
if request.is_some() {
self.layers_reveal = request;
}
}
/// The request for isolation moving from `before` to `now`: entering opens the isolated row,
/// leaving opens the layers around the row that was isolated.
fn reveal_isolation(&mut self, now: Option<NodeId>, before: Option<NodeId>) -> Option<LayersReveal> {
if let Some(root) = now.filter(|r| self.doc.node(*r).is_some()) {
self.layers_open.set(root, true);
return Some(LayersReveal::Row(root));
}
let former = before?;
for around in self.doc.ancestry(former)?.into_iter().filter(|a| *a != former) {
self.layers_open.set(around, true);
}
Some(LayersReveal::Row(former))
}
/// The object whose opacity mask View Opacity Mask shows ([`DocState::mask_view`]): only while
/// its mask is being edited, so leaving editing by any route (undo, deleting the object) ends it.
pub fn shown_mask(&self) -> Option<NodeId> {
+178 -9
View File
@@ -27,7 +27,8 @@
//! [`ScriptScope`] holds the folders a running script's own files (its includes and `$.evalFile`)
//! are read from, and the places its `File` and `Folder` objects read and write, inside the roots.
//! [`ScriptGate`] holds the same places for the commands the script runs with `vc.run`, with the
//! files of the open documents.
//! files of the open documents, and for reading, the files the documents open when the run began
//! link to, each as the person last left the document.
use std::cell::RefCell;
use std::ffi::OsString;
@@ -276,19 +277,56 @@ impl ScopeHandle {
/// What a command a running script runs (`vc.run`) may read and write: the places the script's
/// `File` and `Folder` objects may ([`ScriptScope`]), and the files the documents open in the app
/// were opened from or saved to. The automation roots apply as well. A path refused by its name
/// alone ([`ScriptScope::refused_by_name`]) is refused here too.
/// were opened from or saved to by the person ([`crate::DocState::as_person_left`]). Reading, and
/// only reading, the files the documents link to as the person left them when the run began is
/// allowed as well ([`ScriptGate::linked`]). The automation roots apply as well. A path refused by
/// its name alone ([`ScriptScope::refused_by_name`]) is refused here too.
#[derive(Clone, Debug)]
pub(crate) struct ScriptGate {
pub(crate) read: ScriptScope,
pub(crate) write: ScriptScope,
/// The paths of the open documents' files, as the documents hold them.
/// The paths of the open documents' files, as the documents held them when the person last
/// opened or saved them. A document a script's command opened has none here.
pub(crate) documents: Vec<String>,
/// The files the documents link to as the person left them when the run began: readable, not
/// writable.
pub(crate) linked: LinkedFiles,
/// Another gate a path must pass as well ([`ScopeHandle::within_current`]).
pub(crate) also: Option<Arc<ScriptGate>>,
}
/// The files the commands a script runs may only read because the documents open when the run
/// began link to them as the person left them ([`ScriptGate::linked`]).
#[derive(Clone, Debug, Default)]
pub(crate) struct LinkedFiles {
/// The real paths of the files, as they were when the run's first command was run, sorted. A
/// path that leads to another file now is not one of them.
files: Arc<[PathBuf]>,
}
impl LinkedFiles {
/// Is `real`, a real path, one of the files?
fn has(&self, real: &Path) -> bool {
self.files.binary_search_by(|f| f.as_path().cmp(real)).is_ok()
}
}
impl ScriptGate {
/// The real paths of the files at `paths` that are files now, each once, for
/// [`ScriptGate::linked`]. A path refused by its name alone, and one that cannot be resolved,
/// is left out.
pub(crate) fn real_files(paths: impl IntoIterator<Item = String>) -> LinkedFiles {
let mut real: Vec<PathBuf> = paths
.into_iter()
.filter(|p| !ScriptScope::refused_by_name(Path::new(p)))
.filter_map(|p| resolve(&p).ok())
.filter(|p| p.is_file())
.collect();
real.sort();
real.dedup();
LinkedFiles { files: real.into() }
}
/// This gate with `next` at the end of its chain of `also` gates, so a path must pass every
/// gate already in the chain as well as `next`.
fn followed_by(&self, next: Arc<ScriptGate>) -> ScriptGate {
@@ -310,7 +348,8 @@ impl ScriptGate {
Access::Read => self.read.allows(&real) || self.write.allows(&real),
Access::Write => self.write.allows(&real),
};
scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real))
let linked = matches!(access, Access::Read) && self.linked.has(&real) && !self.read.keeps_out(&real);
scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) || linked
});
if allowed { Ok(()) } else { Err(format!("Script file access denied: {path}")) }
}
@@ -354,6 +393,11 @@ fn check_gate(path: &str, access: Access) -> Result<(), String> {
GATE.with(|g| g.borrow().clone()).map_or(Ok(()), |g| g.check(path, access))
}
/// Whether this thread runs a command a script runs ([`with_script_gate`]).
pub(crate) fn in_script_command() -> bool {
GATE.with(|g| g.borrow().is_some())
}
/// The roots in force on this thread, if any.
pub fn current() -> Option<Arc<AutomationRoots>> {
match SCOPE.with(|s| s.borrow().clone()) {
@@ -620,7 +664,13 @@ impl ScriptScope {
pub(crate) fn allows(&self, real: &Path) -> bool {
(self.files.iter().any(|f| inside(real, f) && real.components().count() == f.components().count())
|| self.roots.iter().any(|r| inside(real, r)))
&& !self.fenced.iter().any(|f| inside(real, f) && !self.open.iter().any(|o| inside(o, f) && inside(real, o)))
&& !self.keeps_out(real)
}
/// Is the real path `real` in a folder kept out ([`ScriptScope::fence`]), and not in a place
/// left open there?
fn keeps_out(&self, real: &Path) -> bool {
self.fenced.iter().any(|f| inside(real, f) && !self.open.iter().any(|o| inside(o, f) && inside(real, o)))
}
/// The scope of a script run from a file in the folder whose real path, with its links already
@@ -920,8 +970,13 @@ mod tests {
#[test]
fn a_narrowed_scope_keeps_the_script_gates_of_both() {
let (base, _) = folders("narrowed-gate");
let gate =
|dir: &str| ScriptGate { read: ScriptScope::of_folder(&base.join(dir)), write: ScriptScope::default(), documents: vec![], also: None };
let gate = |dir: &str| ScriptGate {
read: ScriptScope::of_folder(&base.join(dir)),
write: ScriptScope::default(),
documents: vec![],
linked: LinkedFiles::default(),
also: None,
};
let (inside, other) = (s(base.join("in/a.svg")), s(base.join("outside/secret.svg")));
let reads = |saved: ScopeHandle, gate_here: Option<ScriptGate>| {
let narrowed = match gate_here {
@@ -944,7 +999,13 @@ mod tests {
#[test]
fn a_scope_narrowed_several_times_keeps_every_gate() {
let (base, _) = folders("narrowed-thrice");
let gate = |dir: &Path| ScriptGate { read: ScriptScope::of_folder(dir), write: ScriptScope::default(), documents: vec![], also: None };
let gate = |dir: &Path| ScriptGate {
read: ScriptScope::of_folder(dir),
write: ScriptScope::default(),
documents: vec![],
linked: LinkedFiles::default(),
also: None,
};
let (inside, other) = (s(base.join("in/a.svg")), s(base.join("outside/secret.svg")));
let narrow = |saved: ScopeHandle, g: ScriptGate| with_script_gate(g, || saved.within_current());
let reads = |h: &ScopeHandle| h.clone().run(|| (check_read(&inside).is_ok(), check_read(&other).is_ok()));
@@ -959,6 +1020,114 @@ mod tests {
let _ = std::fs::remove_dir_all(base);
}
/// A file an open document linked to when the run began is readable through the gate; its path
/// written with `..`, writing it, a file next to it and a file that was not there when the gate
/// was made are not allowed, and the automation roots still apply.
#[test]
fn a_gate_reads_only_the_linked_files_it_was_given() {
let (base, roots) = folders("linked");
let (secret, other) = (base.join("outside/secret.svg"), base.join("outside/other.svg"));
std::fs::write(&other, "<svg/>").unwrap();
let later = base.join("outside/later.svg");
let linked = ScriptGate::real_files([s(secret.clone()), s(later.clone()), s(base.join("outside"))]);
assert_eq!(linked.files.len(), 1, "a missing file and a folder are left out: {linked:?}");
let gate =
ScriptGate { read: ScriptScope::of_folder(&base.join("in")), write: ScriptScope::default(), documents: vec![], linked, also: None };
std::fs::write(&later, "<svg/>").unwrap();
let (read, write) =
(|p: &Path| gate.check(&s(p.to_path_buf()), Access::Read).is_ok(), |p: &Path| gate.check(&s(p.to_path_buf()), Access::Write).is_ok());
assert!(read(&secret));
assert!(!read(&base.join("outside/../outside/secret.svg")), "a path with `..` is refused by its name");
assert!(!write(&secret), "linked files are not written");
assert!(!read(&other), "a file next to a linked one");
assert!(!read(&later), "a file made after the gate");
assert!(!read(&base.join("outside")), "the linked file's folder");
let g = gate.clone();
assert!(confine(Some(&roots), || with_script_gate(g, || check_read(&s(secret.clone())).is_err())), "the roots apply first");
let _ = std::fs::remove_dir_all(base);
}
/// A linked file in a folder the script's scope keeps out, such as the settings folder, is not
/// read through the gate; one in a place left open there is.
#[test]
fn a_gate_reads_no_linked_file_in_a_folder_kept_out() {
let (base, _) = folders("linked-fenced");
let (kept, open) = (base.join("outside/kept.svg"), base.join("outside/open/a.svg"));
std::fs::create_dir_all(base.join("outside/open")).unwrap();
std::fs::write(&kept, "<svg/>").unwrap();
std::fs::write(&open, "<svg/>").unwrap();
let real = |p: &Path| resolve(&s(p.to_path_buf())).unwrap();
let mut read = ScriptScope::of_folder(&base.join("in"));
read.fence(real(&base.join("outside")), &[real(&base.join("outside/open"))]);
let gate = ScriptGate {
read,
write: ScriptScope::default(),
documents: vec![],
linked: ScriptGate::real_files([s(kept.clone()), s(open.clone())]),
also: None,
};
assert!(gate.check(&s(kept), Access::Read).is_err(), "in the folder kept out");
assert!(gate.check(&s(open), Access::Read).is_ok(), "in a place left open");
let _ = std::fs::remove_dir_all(base);
}
/// A path read through the linked files gives no access to the file it leads to after it is
/// pointed elsewhere by a link in one of its folders.
#[test]
fn a_path_read_through_a_linked_file_gives_nothing_once_it_leads_elsewhere() {
let (base, _) = folders("linked-redirected");
#[cfg(unix)]
let made = |target: &Path, link: &Path| std::os::unix::fs::symlink(target, link).is_ok();
#[cfg(windows)]
let made = |target: &Path, link: &Path| std::os::windows::fs::symlink_dir(target, link).is_ok();
#[cfg(not(any(unix, windows)))]
let made = |_: &Path, _: &Path| false;
let (first, second, via) = (base.join("outside/first"), base.join("outside/second"), base.join("outside/via"));
for dir in [&first, &second] {
std::fs::create_dir_all(dir).unwrap();
std::fs::write(dir.join("a.svg"), "<svg/>").unwrap();
}
// Windows needs Developer Mode or elevation to make links: nothing to test without them.
if !made(&first, &via) {
eprintln!("skipped: symbolic links can't be made here");
let _ = std::fs::remove_dir_all(base);
return;
}
let (doc, elsewhere) = (s(via.join("a.svg")), s(second.join("a.svg")));
let gate = ScriptGate {
read: ScriptScope::default(),
write: ScriptScope::default(),
documents: vec![],
linked: ScriptGate::real_files([doc.clone()]),
also: None,
};
assert!(gate.check(&doc, Access::Read).is_ok(), "read through the linked file");
std::fs::remove_dir(&via).or_else(|_| std::fs::remove_file(&via)).unwrap();
assert!(made(&second, &via));
for (path, access) in [(&doc, Access::Read), (&doc, Access::Write), (&elsewhere, Access::Read), (&elsewhere, Access::Write)] {
assert!(gate.check(path, access).is_err(), "{path} {access:?}");
}
let _ = std::fs::remove_dir_all(base);
}
/// A link to a linked file read through the gate counts only while it leads to that file.
#[cfg(unix)]
#[test]
fn a_gate_refuses_a_link_that_now_leads_elsewhere() {
let (base, _) = folders("linked-moved");
let (secret, other, link) = (base.join("outside/secret.svg"), base.join("outside/other.svg"), base.join("outside/link.svg"));
std::fs::write(&other, "<svg/>").unwrap();
std::os::unix::fs::symlink(&secret, &link).unwrap();
let linked = ScriptGate::real_files([s(link.clone())]);
let gate = ScriptGate { read: ScriptScope::default(), write: ScriptScope::default(), documents: vec![], linked, also: None };
assert!(gate.check(&s(link.clone()), Access::Read).is_ok() && gate.check(&s(secret.clone()), Access::Read).is_ok());
std::fs::remove_file(&link).unwrap();
std::os::unix::fs::symlink(&other, &link).unwrap();
assert!(gate.check(&s(link.clone()), Access::Read).is_err(), "the link leads to another file now");
assert!(gate.check(&s(other), Access::Read).is_err());
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn network_paths_are_told_by_name() {
for p in [r"\\server\share\x.svg", "//server/share/x.svg", r"\\?\UNC\server\share\x.svg", r"\\?\unc\server\share"] {
+6
View File
@@ -10,6 +10,9 @@ pub struct Interaction {
pub preview: Option<(String, Value)>,
/// A replaced or canceled preview restores these new-art paints from before the interaction.
pub(crate) paint: vectorcraft_tools::PaintDefaults,
/// A preview of the interaction gave `defaultsOnly: true`: every later preview and a cancel put
/// `paint` back, whichever preview is the latest.
pub(crate) used_defaults_only: bool,
/// An accepted batch preview uses these final paints after changing the document color mode.
pub(crate) preview_paint: Option<vectorcraft_tools::PaintDefaults>,
/// Conversion of new-art paints waits until a color-mode preview is accepted.
@@ -33,6 +36,9 @@ pub struct Interaction {
/// The bounding box of `selection` in `doc`, measured once for a move drag
/// ([`crate::Session::move_drag_box`]): each step offsets it by the drag's move.
pub(crate) move_box: std::sync::OnceLock<Option<vectorcraft_doc::OrientedBox>>,
/// A switch to another document keeps the previews as one undo step in this one, as a panel field's scrub keeps
/// its edits; otherwise the switch cancels the interaction, as it does a drag.
pub keep_on_switch: bool,
}
/// What Object → Transform → Transform Again (⌘D) repeats ([`SessionState::last_transform`]).
+9 -3
View File
@@ -75,8 +75,9 @@ pub struct Session {
/// back as it was at the release ([`Session::pointer`]).
pub(crate) lender: Option<Box<dyn Tool>>,
/// Set while tool actions that end by switching back to the Live Paint Bucket are applied (the
/// Eyedropper's sample into a stop of the bucket's gradient): their paint commands change the
/// colors the bucket paints with ([`Session::bucket_paints`]).
/// Eyedropper's sample into a stop of the bucket's gradient), and while a tool the bucket lent
/// is deactivated as it goes back: their paint commands change the colors the bucket paints
/// with ([`Session::bucket_paints`]).
pub(crate) back_to_bucket: bool,
/// Pointer and key input that came while the tool computed an edit on another thread, each with
/// its number and view, made in order once the edit is applied.
@@ -234,6 +235,11 @@ pub struct Session {
/// The running top-level query command changed the selection and is journaled like any other
/// command ([`Session::journal_query`]).
journal_query: bool,
/// The running top-level command changed only the paint defaults, as the Live Paint Bucket
/// or `defaultsOnly: true` has a paint command do, when new art would have taken this
/// appearance (none: nothing selected): unless a later batch step changes it, the selection's
/// appearance does not replace the defaults afterwards ([`Session::inherit_new_art`]).
pub(crate) defaults_only_ran: Option<Option<cmd::newart::NewArtSource>>,
/// From `edit.undoGroup.begin` to `edit.undoGroup.end`: the name of the undo step (`None`: after
/// its first edit). Each document opened or created meanwhile opens an undo group of its own
/// ([`Session::add_document`]). `None` otherwise.
@@ -432,7 +438,7 @@ pub(crate) use command_sets::SELECTS_GIVEN_IDS;
#[cfg(test)]
use command_sets::given_ids;
pub use command_sets::{DRAWS_SHAPE, FIT_ACTIVE_ARTBOARD, ON_ACTIVE_ARTBOARD, waits_for_tool_edit};
pub use doc_state::{DocState, OpenRows, RecalledSelection};
pub use doc_state::{DocState, LayersReveal, OpenRows, RecalledSelection};
pub use error::{EngineError, READ_ONLY_LOCATION, Result, SCRIPT_BUSY};
#[cfg(test)]
use history::history_budget_for;
+16
View File
@@ -281,6 +281,10 @@ pub struct Prefs {
pub recovery_off_for_complex: bool,
pub recent_files_count: u32,
pub low_res_proxy_eps: bool,
/// File Handling › Use fonts embedded in imported PDFs: type in a font a PDF embeds and this
/// machine lacks is drawn in the file's own glyphs (on by default); off, it is set in the
/// fallback font with the missing-font warning (#4568).
pub pdf_import_embedded_fonts: bool,
pub anti_aliased_bitmaps: bool,
pub update_links: String,
/// PDF Text: what the text of a PDF, `.ai` or `.ait` file opened or placed from the app
@@ -446,6 +450,17 @@ pub const KEY_HOLD_DELAY: f64 = 0.35;
pub const KEY_HOLD_DELAY_RANGE: (f64, f64) = (0.2, 1.0);
impl Prefs {
/// The `document.open` / place params `p` with `embeddedFonts: false` added when Preferences
/// › File Handling › Use fonts embedded in imported PDFs is off and `p` gives no choice of its own.
pub fn with_pdf_font_choice(&self, p: &serde_json::Value) -> serde_json::Value {
if self.pdf_import_embedded_fonts || p.get("embeddedFonts").is_some_and(|v| !v.is_null()) {
return p.clone();
}
let mut out = if p.is_object() { p.clone() } else { serde_json::json!({}) };
out["embeddedFonts"] = serde_json::json!(false);
out
}
/// The Hold Shortcut Delay in seconds, inside its range. A restored settings file is not
/// checked against the range, so a value outside it is brought inside, and one that is not a
/// number gives the default.
@@ -592,6 +607,7 @@ impl Default for Prefs {
recovery_off_for_complex: false,
recent_files_count: 20,
low_res_proxy_eps: false,
pdf_import_embedded_fonts: true,
anti_aliased_bitmaps: false,
update_links: s("askWhenModified"),
pdf_text_as: s("text"),
+8 -5
View File
@@ -54,7 +54,9 @@
//! for, loses the grant before that code runs. A run with nobody to ask gets `null` and
//! [`NO_PICKER`].
//! - The commands a script runs with `vc.run` read and write only in the places above and in the
//! files of the open documents ([`crate::file_access::ScriptGate`]).
//! files the person gave the open documents ([`crate::file_access::ScriptGate`]). They also read
//! the files that the documents open when the run began link to, as the person last left those
//! documents and as those links led then.
//! - `open('w')` empties the file at once; what a script writes is kept in memory, at most
//! [`MAX_FILE_BYTES`] a file, and written when it closes the file or the run ends; a run writes at
//! most [`MAX_RUN_BYTES`] in all and ends past that. `write` encodes in the file's encoding (an
@@ -462,10 +464,11 @@ impl Disk {
}
}
/// The gate for a command the script runs: the places it reads and writes now, and the files of
/// the open documents, `documents`.
pub(crate) fn gate(&self, documents: Vec<String>) -> crate::file_access::ScriptGate {
crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, also: None }
/// The gate for a command the script runs: the places it reads and writes now, the files the
/// person gave the open documents, `documents`, and the files it may only read because the documents open when
/// the run began link to them, `linked`.
pub(crate) fn gate(&self, documents: Vec<String>, linked: crate::file_access::LinkedFiles) -> crate::file_access::ScriptGate {
crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, linked, also: None }
}
/// The files written since this was last asked, to name in the report.
+16 -1
View File
@@ -217,6 +217,15 @@ pub(crate) struct Files {
levels: usize,
/// The files `$.evalFile` is running, the script first.
frames: Vec<Frame>,
/// The run reads ECMAScript 2015 ([`es2015_script`]): its files are parsed that way.
es2015: bool,
}
/// A script at `path` runs with [`vectorcraft_js::Options::es2015`] when its file name ends in
/// `.js` (in any letter case); a `.jsx` script, any other file and a script given as text run as
/// ECMAScript 5.1 with the ExtendScript extensions.
pub(crate) fn es2015_script(path: Option<&str>) -> bool {
path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("js"))
}
/// The output being built: its UTF-16 text, the line it is on, the units since that line began,
@@ -311,9 +320,15 @@ impl Files {
chain: real.into_iter().collect(),
levels: 0,
frames: vec![Frame { shown: Arc::from(path.unwrap_or_default()), dir }],
es2015: es2015_script(path),
}
}
/// The options a file of this run is parsed with, preprocessor lines aside.
pub(crate) fn options(&self) -> Options {
Options { max_source_units: MAX_TOTAL_BYTES, es2015: self.es2015, ..Options::default() }
}
/// The `JSINCLUDE` folders of this process: absolute folders separated by `;`.
pub(crate) fn jsinclude_env() -> Vec<PathBuf> {
#[cfg(test)]
@@ -456,7 +471,7 @@ impl Files {
return Ok(());
}
let fail = |kind, message: String, line, column| Failure { kind, message, index, file: shown.clone(), line, column };
let options = Options { preprocessor_lines: true, max_source_units: MAX_TOTAL_BYTES, ..Options::default() };
let options = Options { preprocessor_lines: true, ..self.options() };
let program = vectorcraft_js::parse_utf16(&units, &options).map_err(|e| fail(FailKind::Syntax, e.message, e.line, e.column))?;
let mut cursor = 0usize;
for d in &program.directives {
+58 -4
View File
@@ -799,6 +799,35 @@ struct Host {
dollar: dollar::RunState,
/// The run's `args`, which `vc.args` gives, and their size as `vc.args` charges it.
args: RefCell<(Data, u64)>,
/// The documents open when the run began as the person last left them, each with its own file
/// and the file it was read from ([`crate::DocState::as_person_left`],
/// [`crate::cmd::links::LinkBase::of_files`]), until the run's first command takes the files
/// they link to from them ([`Host::linked`]).
run_docs: RefCell<Vec<RunDoc>>,
/// The files the documents open when the run began link to as the person left them
/// ([`crate::file_access::ScriptGate::linked`]).
linked: std::cell::OnceCell<crate::file_access::LinkedFiles>,
}
/// A document open when a run began, with its own file and the file it was read from.
type RunDoc = (Arc<crate::Document>, Option<String>, Option<String>);
impl Host {
/// The files the commands the run runs may read because the documents open when the run began
/// link to them, found once, from those documents as the person left them: a link a script's
/// command added or changed, in this run or an earlier one, and a document it opened, give it
/// no file to read.
fn linked(&self) -> crate::file_access::LinkedFiles {
self.linked
.get_or_init(|| {
let docs = std::mem::take(&mut *self.run_docs.borrow_mut());
let files = docs.iter().flat_map(|(d, path, from)| {
crate::cmd::links::files_linked(d, crate::cmd::links::LinkBase::of_files(path.as_deref(), from.as_deref()))
});
crate::file_access::ScriptGate::real_files(files.collect::<Vec<_>>())
})
.clone()
}
}
/// A run's host calls by kind, as its report gives them in `hostCallCounts`.
@@ -1238,9 +1267,19 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value
let before: Vec<(u64, Arc<crate::Document>, u64)> =
if mutating { s.docs.iter().map(|d| (d.uid, d.doc.clone(), d.doc.peek_next_id())).collect() } else { Vec::new() };
crate::file_access::start_recording_writes();
// The command reads and writes only where the script's own files may, and the open documents' files.
let gate = host.disk.borrow().gate(s.docs.iter().filter_map(|d| d.path.clone()).collect());
// The command reads and writes only where the script's own files may, and the files the person gave
// the open documents; it also reads the files the documents open when the run began link to, as the
// person left them. A document a script's command opened gives it no file.
let documents = s.docs.iter().filter_map(|d| d.as_person_left().and_then(|(_, path, _)| path.map(str::to_string))).collect();
let gate = host.disk.borrow().gate(documents, host.linked());
let was: Vec<(u64, RunDoc)> = s.docs.iter().map(|d| (d.uid, (d.doc.clone(), d.path.clone(), d.links_from.clone()))).collect();
let r = crate::file_access::with_script_gate(gate, || s.execute(id, params));
// What the command opened, changed or gave another file is not as the person left it.
for st in &mut s.docs {
let prior = was.iter().find(|(uid, _)| *uid == st.uid);
st.note_script_command(prior.map(|(_, (doc, path, from))| (doc, path, from)));
}
drop(was);
// A file a command wrote before it failed is on disk all the same.
let mut written = host.written.borrow_mut();
for path in crate::file_access::finish_recording_writes(r.is_ok()) {
@@ -1475,7 +1514,7 @@ fn eval_file(host: &Host, args: Vec<Data>) -> std::result::Result<Data, HostErro
if f.line > 0 { host.placed(error, f.file, f.line, f.column) } else { error }
})?;
// A file without preprocessor lines is parsed here first, so its syntax error names its place.
let options = vectorcraft_js::Options { max_source_units: include::MAX_TOTAL_BYTES, ..vectorcraft_js::Options::default() };
let options = host.files.borrow().options();
if let Err(e) = vectorcraft_js::parse(&expanded.source, &options) {
host.files.borrow_mut().end_eval();
let (_, file, line, column) = expanded.map.locate(e.line, e.column);
@@ -1967,11 +2006,16 @@ impl Session {
// A realm made here gets the script extensions, `$` and the dialogs; a kept one has them
// from its first run, and they act for the run that calls them.
let fresh = realm.is_none();
let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), ..Options::default() };
// A `.js` script reads ECMAScript 2015; `eval`, `Function`, includes and `$.evalFile` read
// code the way the script does.
let es2015 = include::es2015_script(request.file.as_deref());
let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, ..Options::default() };
let strict = options.strict;
// A kept engine reads each run's code the way that run's script does.
let mut realm = match realm {
Some(mut realm) => {
realm.set_limits(limits);
realm.set_es2015(es2015);
realm
}
None => {
@@ -2040,6 +2084,14 @@ impl Session {
eval_strict: Cell::new(None),
dollar: dollar::RunState::new(&request.locale),
args: RefCell::new((Data::Undefined, 0)),
run_docs: RefCell::new(
self.docs
.iter()
.filter_map(DocState::as_person_left)
.map(|(doc, path, from)| (doc.clone(), path.map(str::to_string), from.map(str::to_string)))
.collect(),
),
linked: std::cell::OnceCell::new(),
});
*link.borrow_mut() = Some(host.clone());
let args = match to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) {
@@ -2065,6 +2117,7 @@ impl Session {
Ok(expanded) => {
*host.script_map.borrow_mut() = expanded.map;
realm.set_strict_writes(expanded.strict == Some(true));
realm.set_script_name(Some(host.name.to_string()));
if fresh {
let l = link.clone();
realm.set_source_locator(Rc::new(move |tag, line| match current(&l) {
@@ -2073,6 +2126,7 @@ impl Session {
}));
}
(if fresh { realm.add_script_extensions() } else { Ok(()) })
.and_then(|()| if fresh { realm.add_unit_values() } else { Ok(()) })
.and_then(|()| if fresh { realm.define_host_object("vc", vc_object(&link)) } else { Ok(()) })
.and_then(|()| if fresh { realm.define_host_object("$", dollar_object(&link, info, &localization)) } else { Ok(()) })
.and_then(|()| if fresh { dialogs::install(&mut realm, &link) } else { Ok(()) })
+20 -3
View File
@@ -24,6 +24,10 @@ impl Session {
});
// Clicks find an image's own fills and strokes where their effects draw them.
vectorcraft_doc::hit::set_image_paint(vectorcraft_render::effects::image_paint);
// Direct Selection picks and outlines the parts of a dynamic symbol's instance where the
// effects of the instance's fill and stroke draw them.
vectorcraft_doc::hit::set_instance_row_art(vectorcraft_render::effects::add_instance_row_effects_to_parts);
vectorcraft_doc::hit::set_instance_reshapes(vectorcraft_render::effects::has_item_geometry);
// Clicks inside a clip group fall in the region its clipping path's effects give it.
vectorcraft_doc::hit::set_clip_region(vectorcraft_render::effects::reshaped_clip_outline);
// Clicks and marquees find paths, compound paths, groups and layers where their geometry
@@ -114,6 +118,7 @@ impl Session {
journal_note: Default::default(),
note_depth: 1,
journal_query: false,
defaults_only_ran: None,
explicit_undo_group: None,
batch_stash: None,
batch_steps: None,
@@ -214,9 +219,14 @@ impl Session {
let _ = self.give_back_tool(view);
let _ = self.deactivate_tool(view);
// A batch leaves its interaction open in the document it leaves, to keep or roll back with
// the rest of the batch; anything else in progress (a drag) is cancelled.
// the rest of the batch; one that keeps on a switch is kept; anything else in progress (a
// drag) is cancelled.
if self.batch_stash.is_none() {
let _ = self.cancel_interaction();
let _ = if self.active().and_then(|st| st.interaction.as_ref()).is_some_and(|it| it.keep_on_switch) {
self.commit_interaction()
} else {
self.cancel_interaction()
};
}
self.keep_tool_settings();
self.tool = self.make_tool(self.tool.id());
@@ -289,7 +299,9 @@ impl Session {
/// what is fitted to type's bounds (an envelope warping it) would come out differently. That
/// holds for the type in symbol definitions, pattern tiles, graph designs and opacity masks too,
/// not only in the layers (#1738).
pub(crate) fn refresh_text_bounds(doc: &mut Document) {
pub(crate) fn refresh_text_bounds(doc: &mut Document) -> Vec<String> {
// The fonts files carried for their type draw it ([`vectorcraft_doc::FileFonts`]).
let warnings = vectorcraft_text::FontDb::global().bind_document_file_fonts(doc);
// Inline graphics in text take their size from their symbols' art (not saved either).
doc.resolve_inline_art();
let mut uncached = |t: &TextObject| t.cached_bounds.is_none();
@@ -299,6 +311,7 @@ impl Session {
// The symbols' type is measured now: the inline graphics showing those symbols take their
// art's measured size, a symbol's type before the type that shows that symbol inline.
doc.resolve_inline_art_with(&mut cmd::typecmd::refresh_bounds_for_first_frame);
warnings
}
/// Measure the type in open document `index` that `stale` picks (in its trees as
@@ -340,6 +353,8 @@ impl Session {
// (importers and the native reader have seen to theirs already, with a warning).
doc.limit_depth();
cmd::compositefonts::filter_loaded(&mut doc);
// Importers report binding failures; programmatic additions still need owned resources.
let _ = vectorcraft_text::FontDb::global().bind_document_file_fonts(&mut doc);
// Inline graphics in text take their size from their symbols' art (not saved).
doc.resolve_inline_art();
// Ruler guides a reader left in the saved list become nodes on their layers.
@@ -402,6 +417,8 @@ impl Session {
st.opened_as_tab = old.opened_as_tab;
st.revision = old.revision + 1;
st.format = old.format;
// What scripts' commands did to the document stays until the person saves it.
st.by_script = old.by_script.clone();
st.save_options = old.save_options.clone();
// The remembered artboard pick follows the artboards it named when the file read back has
// the artboards the document had at the save, in the same order and with the same ids (a
+70 -15
View File
@@ -1,12 +1,17 @@
use super::{
Arc, Document, EngineError, Interaction, LastTransform, NamedStep, Result, Selection, Session, TOO_DEEP, Value, cmd, deselect_hidden, doc_sane,
objects_in_range,
Arc, Document, EngineError, Interaction, LastTransform, NamedStep, NodeKind, Result, Selection, Session, TOO_DEEP, Value, cmd, deselect_hidden,
doc_sane, objects_in_range,
};
use crate::doc_state::objects_only;
impl Session {
/// Run `f` on a mutable copy of the active document. Outside an interaction this records one
/// undo step labelled `label`; inside one it just mutates (the interaction commits later).
pub fn edit<T>(&mut self, label: &str, f: impl FnOnce(&mut Document, &mut Selection) -> Result<T>) -> Result<T> {
self.revealing(|s| s.edit_unwatched(label, f))
}
fn edit_unwatched<T>(&mut self, label: &str, f: impl FnOnce(&mut Document, &mut Selection) -> Result<T>) -> Result<T> {
if self.script_running() {
return Err(EngineError::Busy);
}
@@ -197,19 +202,41 @@ impl Session {
/// Change only the selection (not an undo step).
pub fn select(&mut self, f: impl FnOnce(&Document, &mut Selection)) -> Result<()> {
self.revealing(|s| s.select_unwatched(f))
}
fn select_unwatched(&mut self, f: impl FnOnce(&Document, &mut Selection)) -> Result<()> {
self.active_appearance_item = None;
let menu = self.menu.clone();
let st = self.doc_mut()?;
let before = st.selection.objects.clone();
let new_art = st.selection.new_art.clone();
let record = if st.selection_record().is_some() { st.selection_record.take() } else { None };
f(&st.doc, &mut st.selection);
st.selection.prune(&st.doc);
// Lock Guides locks the paths made into guides too (#1534), and Lock Slices and Hide
// Slices keep the slices out, whatever selects them.
deselect_hidden(&menu, &st.doc, &mut st.selection);
// The art on a locked artboard can't be selected, whatever selects it, except new art
// that was selected and still is.
st.protect_locked_artboards(&before, &new_art, None);
let added = objects_only(&st.selection) && st.selection.objects.starts_with(&before);
// Objects added to objects this checked in the same document, with Lock Guides as it was
// then and no art on a locked artboard to protect, are checked alone, by the rules `prune`
// and `deselect_hidden` apply to an object.
let settled = record.as_ref().is_some_and(|r| r.settled == Some(menu.guides_locked))
&& st.selection.new_art.is_empty()
&& st.doc.new_art.get().is_empty()
&& !st.doc.artboards.iter().any(|a| a.locked);
if added && settled {
let doc = &st.doc;
let tail = st.selection.objects.split_off(before.len());
st.selection.objects.extend(tail.into_iter().filter(|id| {
doc.node(*id).is_some_and(|n| !n.is_ruler_guide() && !(menu.guides_locked && matches!(n.kind, NodeKind::Path { guide: true, .. })))
}));
} else {
st.selection.prune(&st.doc);
// Lock Guides locks the paths made into guides too (#1534), and Lock Slices and Hide
// Slices keep the slices out, whatever selects them.
deselect_hidden(&menu, &st.doc, &mut st.selection);
// The art on a locked artboard can't be selected, whatever selects it, except new art
// that was selected and still is.
st.protect_locked_artboards(&before, &new_art, None);
}
st.record_selection(record, menu.guides_locked);
// Selecting art makes its layer (or sublayer) the current one, as in the Layers panel of
// the reference app: new art then goes beside it.
if st.selection.objects != before
@@ -301,6 +328,7 @@ impl Session {
selection: Arc::new(st.selection.clone()),
preview: None,
paint,
used_defaults_only: false,
preview_paint: None,
color_mode_paints: None,
deferred_color_mode: None,
@@ -312,6 +340,7 @@ impl Session {
plane_placed: false,
copies: None,
move_box: std::sync::OnceLock::new(),
keep_on_switch: false,
});
Ok(())
}
@@ -322,7 +351,8 @@ impl Session {
return Err(EngineError::Busy);
}
// While the Live Paint Bucket is active, paint previews change only the bucket's colors, so
// each preview starts from the colors the interaction began with.
// each preview starts from the colors the interaction began with; so does a preview with
// `defaultsOnly: true`, and one after it.
let bucket = self.bucket_paints();
let (paint, restore_paint) = {
let menu = self.menu.clone();
@@ -337,9 +367,11 @@ impl Session {
st.doc = it.doc.clone();
// A batch, or a preview that changed the new-art paints (a pattern rename), started from
// the paints the interaction began with.
it.used_defaults_only |= cmd::asks_defaults_only(params);
let restore_paint = bucket
|| cmd == "command.batch"
|| it.preview.as_ref().is_some_and(|(id, _)| id == "command.batch")
|| it.used_defaults_only
|| it.preview.as_ref().is_some_and(|(id, p)| id == "command.batch" || cmd::asks_defaults_only(p))
|| it.color_mode_paints.is_some();
let paint = it.paint.clone();
it.preview_paint = None;
@@ -369,6 +401,8 @@ impl Session {
let outer = std::mem::replace(&mut self.previewing, true);
let r = self.execute(cmd, params);
self.previewing = outer;
// A step inside a batch that changed only the defaults counts as well.
let ran_defaults_only = self.defaults_only_ran.is_some();
if let Some(paint) = color_mode_paint {
self.paint = paint;
}
@@ -376,6 +410,7 @@ impl Session {
let batch_paint = (r.is_ok() && cmd == "command.batch").then(|| self.paint.clone());
let st = self.doc_mut()?;
if let Some(it) = &mut st.interaction {
it.used_defaults_only |= ran_defaults_only;
// A failed preview leaves the document at the snapshot, so nothing is left to commit
// (not even an earlier successful preview, which the reset above already undid).
it.preview = r.is_ok().then(|| (cmd.to_string(), params));
@@ -390,6 +425,17 @@ impl Session {
}
pub fn commit_interaction(&mut self) -> Result<()> {
// The interaction is taken below, so its starting state is read first: the commit is what
// the previews that came before it changed.
let before = (self.depth == 0).then(|| self.active().and_then(|st| st.interaction.as_ref().map(|it| st.layers_view_before(it)))).flatten();
let r = self.commit_interaction_unwatched();
if let Some(before) = before {
self.reveal_since(&before);
}
r
}
fn commit_interaction_unwatched(&mut self) -> Result<()> {
self.clear_deferred_overlay_cache();
self.decoded_images.empty();
if let Some(paint) = self.active().and_then(|st| st.interaction.as_ref()).and_then(|it| it.preview_paint.clone()) {
@@ -485,12 +531,18 @@ impl Session {
self.decoded_images.empty();
self.pending_paint = None;
// While the Live Paint Bucket is active, a previewed color is the bucket's color, which the
// cancel puts back as well.
// cancel puts back as well, as it does a color previewed with `defaultsOnly: true`.
let bucket = self.bucket_paints();
let used_defaults_only = self.active().and_then(|st| st.interaction.as_ref()).is_some_and(|it| it.used_defaults_only);
if let Some(paint) = self
.active()
.and_then(|st| st.interaction.as_ref())
.filter(|it| bucket || it.preview.as_ref().is_some_and(|(id, _)| id == "command.batch") || it.color_mode_paints.is_some())
.filter(|it| {
bucket
|| it.used_defaults_only
|| it.preview.as_ref().is_some_and(|(id, p)| id == "command.batch" || cmd::asks_defaults_only(p))
|| it.color_mode_paints.is_some()
})
.map(|it| it.paint.clone())
{
self.paint = paint;
@@ -503,8 +555,11 @@ impl Session {
// A canceled preview's Assign Profile is undone with it.
self.sync_front_profiles();
// With New Art Has Basic Appearance off, new art takes the appearance of the selection as
// the document has it again, not as a preview left it.
self.inherit_new_art();
// the document has it again, not as a preview left it. An interaction that changed only the
// defaults (`defaultsOnly: true`) leaves the defaults it began with.
if !used_defaults_only {
self.inherit_new_art();
}
Ok(())
}
+31 -4
View File
@@ -59,6 +59,30 @@ impl Session {
/// Execute a command by id. This is THE entry point for every frontend.
pub fn execute(&mut self, id: &str, params: &Value) -> Result<Value> {
self.revealing(|s| s.execute_unwatched(id, params))
}
/// Run `f`, a top-level entry that changes the active document's rows, current layer or
/// selection, then ask the Layers panel to reveal what it changed ([`DocState::request_reveal`]).
/// Nothing is asked inside a command, while an interaction is open or while a tool is busy: the
/// entry that ends them asks.
pub(super) fn revealing<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
let before = (self.depth == 0 && !self.tool_busy()).then(|| self.active().map(crate::DocState::layers_view)).flatten();
let r = f(self);
if let Some(before) = before {
self.reveal_since(&before);
}
r
}
/// Ask the Layers panel of the active document to reveal what changed since `before`.
pub(super) fn reveal_since(&mut self, before: &crate::doc_state::LayersView) {
if let Some(st) = self.active_mut() {
st.request_reveal(before);
}
}
fn execute_unwatched(&mut self, id: &str, params: &Value) -> Result<Value> {
let spec = find_command(id).ok_or_else(|| cmd::params::unknown_command(id))?;
// A clipboard import is a query that replaces the clipboard, which the end of a run sets too.
if self.depth == 0 && self.script_key.is_some() && (waits_for_tool_edit(id) || id.starts_with("clipboard.import")) {
@@ -161,6 +185,7 @@ impl Session {
self.journal_note.clear();
self.note_depth = 1;
self.journal_query = false;
self.defaults_only_ran = None;
self.batch_stash = None;
self.batch_steps = None;
}
@@ -263,8 +288,9 @@ impl Session {
}
/// Record `key: value` in the running top-level command's journal entry (or its interaction's
/// preview, or its step in a batch) unless its params give `key` (a null gives nothing): a value
/// it resolved from the preferences or the clock.
/// preview, or its step in a batch) unless its params give `key` (a null gives nothing, and a
/// noted `defaultsOnly` replaces the params' own): a value it resolved from the preferences or
/// the clock.
pub fn note_journal(&mut self, key: &str, value: Value) {
if self.depth == self.note_depth {
self.journal_note.insert(key.to_string(), value);
@@ -359,10 +385,11 @@ impl Session {
let mut note = std::mem::take(&mut self.journal_note);
match params {
// The params' own values win, except a null: it reads as a key left out, so the
// noted value is the one the command resolved.
// noted value is the one the command resolved. A noted `defaultsOnly` wins too: the
// Live Paint Bucket kept the command to the defaults although the params gave `false`.
Value::Object(m) if !note.is_empty() => {
for (k, v) in m {
if !v.is_null() || !note.contains_key(k) {
if (!v.is_null() && k != "defaultsOnly") || !note.contains_key(k) {
note.insert(k.clone(), v.clone());
}
}
+2 -2
View File
@@ -42,7 +42,7 @@ use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::SystemTime;
use vectorcraft_pdf::{PdfPreset, builtin_preset};
use vectorcraft_pdf::{APP, PdfPreset, builtin_preset};
use vectorcraft_plugins::permissions::GrantToken;
use vectorcraft_plugins::safe_mode;
use vectorcraft_plugins::storage::{self, Meter, Storage, StorageError};
@@ -1555,7 +1555,7 @@ fn load_presets(dir: &Path) -> Vec<PdfPreset> {
for mut preset in file.presets {
let name = preset.name.trim().to_string();
let usable = !name.is_empty()
&& builtin_preset(&name).is_none()
&& builtin_preset(&name, APP).is_none()
&& !presets.iter().any(|q| q.name.eq_ignore_ascii_case(&name))
&& preset.settings.check_values().is_ok()
&& presets.len() < MAX_STORE_FILES;
+10 -4
View File
@@ -301,8 +301,9 @@ fn export_3d_paints_mapped_graphics_on_their_caps_in_every_format() {
assert!(is_red(pixel(back, at(20.0), 64)) && is_blue(pixel(back, 64, 64)), "{:?}", pixel(back, 64, 64));
// The USDA's front cap shows the front picture through st, up from the picture's bottom.
let usda = String::from_utf8(out[0].1.clone()).unwrap();
assert_eq!(usda.matches("primvars:st").count(), 2);
assert_eq!(usda.matches("UsdUVTexture").count(), 2);
assert_eq!(usda.matches("def Mesh").count(), 3, "the walls, the front cap and the back cap");
assert_eq!(usda.matches("texCoord2f[] primvars:st").count(), 3, "every mesh carries texture coordinates");
// glTF holds both pictures, and a cap's coordinates stay inside its picture.
let (mut s, _) = mapped("gltf");
let out = files(&run(&mut s, "assets.export3D", json!({})));
@@ -354,7 +355,7 @@ fn export_3d_paints_graphics_mapped_onto_a_revolves_side_in_every_format() {
let middle = (150.0 * scale) as u32;
assert!(is_red(pixel(picture, 256, middle)) && is_blue(pixel(picture, 10, 10)), "{:?}", pixel(picture, 256, middle));
let usda = String::from_utf8(out[0].1.clone()).unwrap();
assert_eq!((usda.matches("def Mesh").count(), usda.matches("primvars:st").count()), (1, 1), "the side is the only face");
assert_eq!((usda.matches("def Mesh").count(), usda.matches("UsdUVTexture").count()), (1, 1), "the side is the only face");
// Moved 50 pt around the axis, the graphic moves as far across the picture.
let (mut s, _) = revolved("usda", json!({}), 50.0);
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 512})));
@@ -381,7 +382,8 @@ fn a_partial_revolve_keeps_its_cut_sides_plain_beside_its_textured_side() {
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Ball.usda", "Ball-texture-1.png"]);
let usda = String::from_utf8(out[0].1.clone()).unwrap();
assert_eq!((usda.matches("def Mesh").count(), usda.matches("primvars:st").count()), (2, 1), "the cut sides and the side");
assert_eq!((usda.matches("def Mesh").count(), usda.matches("UsdUVTexture").count()), (2, 1), "the cut sides and the side");
assert_eq!(usda.matches("texCoord2f[] primvars:st").count(), 2, "the plain cut sides keep their own texture coordinates");
let d = &s.doc().unwrap().doc;
let id = d.asset(asset).unwrap().nodes[0].0;
// Without its graphics the surface is one plain mesh, as before.
@@ -476,7 +478,11 @@ fn export_3d_keeps_flat_colors_without_graphics_and_refuses_bad_texture_sizes()
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box.obj", "Box.mtl"]);
let obj = String::from_utf8(out[0].1.clone()).unwrap();
assert!(!obj.contains("vt ") && obj.lines().filter(|l| l.starts_with("g ")).count() == 1);
assert!(!out[1].1.windows(6).any(|w| w == b"map_Kd") && obj.lines().filter(|l| l.starts_with("g ")).count() == 1);
// The plain mesh still carries a texture coordinate, 0 to 1, for every corner.
let count = |p: &str| obj.lines().filter(|l| l.starts_with(p)).count();
assert!(count("vt ") > 0 && count("vt ") == count("v "));
assert!(obj.lines().filter_map(|l| l.strip_prefix("vt ")).flat_map(|l| l.split(' ')).all(|v| (0.0..=1.0).contains(&v.parse::<f64>().unwrap())));
}
#[test]
+204
View File
@@ -3331,6 +3331,182 @@ fn live_paint_bucket_paint_and_stroke_commands_leave_the_selection_unpainted() {
assert!(failed.is_empty(), "{failed:#?}");
}
/// A paint or stroke command that the Live Paint Bucket kept to its own colors is journaled with
/// `defaultsOnly: true`, also when its params gave `false`. Replaying the entry with the Selection
/// tool active changes the same defaults and leaves the selection's paint as it was, also with New
/// Art Has Basic Appearance off. Every command that fails is listed.
#[test]
fn live_paint_bucket_commands_replay_from_the_journal_with_another_tool() {
let blue = Color::from_hex("#0000ff").unwrap();
// A Live Paint group and a rectangle, both selected, a library with a fill color, a radial
// gradient as the default fill and a 2 pt default weight.
let setup = |s: &mut Session, basic: bool| {
s.execute("appearance.setNewArtBasic", &json!({"on": basic})).unwrap();
let g = live(s);
let art = rect(s, 300.0, 300.0, 40.0, 40.0);
s.execute("paint.setFill", &json!({"color": "#00ff00", "ids": [art.0]})).unwrap();
let lib = s.execute("library.create", &json!({})).unwrap()["id"].as_str().unwrap().to_string();
s.execute("select.set", &json!({"ids": [art.0]})).unwrap();
let item = s.execute("library.add", &json!({"library": lib, "kind": "fillColor"})).unwrap()["name"].as_str().unwrap().to_string();
s.execute("select.set", &json!({"ids": [g.0, art.0]})).unwrap();
s.execute("paint.setFill", &json!({"gradient": {"kind": "radial"}, "defaultsOnly": true})).unwrap();
s.paint.stroke_width = 2.0;
s.last_solid = blue;
(g, art, lib, item)
};
let cases: Vec<(&str, Value)> = vec![
("paint.setFill", json!({"color": "#00ffff"})),
("paint.setFill", json!({"color": "#00ffff", "defaultsOnly": false})),
("paint.setStroke", json!({"color": "#00ffff"})),
("paint.none", json!({})),
("paint.swap", json!({})),
("paint.default", json!({})),
("paint.lastColor", json!({"stroke": false})),
("paint.lastGradient", json!({"stroke": true})),
("paint.invert", json!({"stroke": false})),
("paint.complement", json!({"stroke": false})),
("paint.sampleColor", json!({"color": "#00ffff", "stroke": true})),
("paint.sampleColor", json!({"color": "#00ffff", "stroke": false, "stop": 0})),
("paint.editGradient", json!({"stroke": false, "angle": 45})),
("gradient.presets.apply", json!({"name": "vignette"})),
("stroke.set", json!({"weight": 5})),
("stroke.weightUp", json!({})),
("stroke.weightDown", json!({})),
("stroke.setAdvanced", json!({"arrowScale": [150, 200]})),
("swatch.library.add", json!({"library": "web-safe-216", "names": ["#FF6600"], "apply": "fill"})),
("library.use", json!({"kind": "fillColor"})),
];
let mut failed = vec![];
for basic in [true, false] {
for (cmd, params) in &cases {
let mut params = params.clone();
let mut a = session();
let (_, _, lib, item) = setup(&mut a, basic);
if *cmd == "library.use" {
params["library"] = json!(lib);
params["item"] = json!(item);
}
a.select_tool("livePaintBucket", ViewInfo::default()).unwrap();
let start = a.journal.len();
if let Err(e) = a.execute(cmd, &params) {
failed.push(format!("{cmd} {params} (basic {basic}): {e}"));
continue;
}
let Some((id, recorded)) = a.journal.since(start).last().cloned() else {
failed.push(format!("{cmd} {params} (basic {basic}): not journaled"));
continue;
};
if recorded.get("defaultsOnly") != Some(&json!(true)) {
failed.push(format!("{cmd} {params} (basic {basic}): the journal entry {recorded} does not keep the change to the defaults"));
}
let mut b = session();
let (g, art, _, _) = setup(&mut b, basic);
let (group, painted) = (node(&b, g), node(&b, art));
if let Err(e) = b.replay(&id, &recorded) {
failed.push(format!("{cmd} {params} (basic {basic}): the replay failed: {e}"));
continue;
}
if node(&b, g) != group || node(&b, art) != painted {
failed.push(format!("{cmd} {params} (basic {basic}): the replay painted the selection"));
}
if (&b.paint.fill, &b.paint.stroke, b.paint.stroke_width, b.new_art_stroke())
!= (&a.paint.fill, &a.paint.stroke, a.paint.stroke_width, a.new_art_stroke())
{
failed.push(format!("{cmd} {params} (basic {basic}): the replay left other defaults"));
}
}
}
assert!(failed.is_empty(), "{failed:#?}");
// In a batch with New Art Has Basic Appearance off, a selection change after a `defaultsOnly`
// step still gives new art the new selection's appearance; without one, the defaults stay.
let cyan = Paint::solid(Color::from_hex("#00ffff").unwrap());
let set_cyan = json!({"command": "paint.setFill", "params": {"color": "#00ffff", "defaultsOnly": true}});
let mut s = session();
let (_, art, ..) = setup(&mut s, false);
s.execute("command.batch", &json!({"commands": [set_cyan.clone()]})).unwrap();
assert_eq!(s.paint.fill, cyan, "the defaults keep the batch's fill");
s.execute("paint.setFill", &json!({"color": "#ff0000", "defaultsOnly": true})).unwrap();
s.execute("command.batch", &json!({"commands": [set_cyan.clone(), {"command": "select.key", "params": {"id": art.0}}]})).unwrap();
assert_eq!(s.paint.fill, cyan, "a new key object leaves the objects new art takes its appearance from");
s.execute("command.batch", &json!({"commands": [set_cyan.clone(), {"command": "select.set", "params": {"ids": [art.0]}}]})).unwrap();
assert_eq!(s.paint.fill, Paint::solid(Color::from_hex("#00ff00").unwrap()), "new art takes the newly selected fill");
// A later step that changes the selected object's appearance gives new art that appearance.
s.execute("command.batch", &json!({"commands": [set_cyan, {"command": "transparency.set", "params": {"opacity": 40, "ids": [art.0]}}]})).unwrap();
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
assert_eq!((&s.paint.fill, s.paint.opacity), (&green, 0.4), "new art takes the selection's new opacity, and its fill");
// `defaultsOnly: true` with the Selection tool: a canceled preview puts the defaults back, and
// each preview starts from the defaults the interaction began with.
let mut s = session();
let (g, art, ..) = setup(&mut s, true);
let (group, painted, fill) = (node(&s, g), node(&s, art), s.paint.fill.clone());
s.begin_interaction("Fill Color").unwrap();
s.preview("paint.setFill", &json!({"color": "#123456", "defaultsOnly": true})).unwrap();
assert_eq!(s.paint.fill, Paint::solid(Color::from_hex("#123456").unwrap()));
s.cancel_interaction().unwrap();
assert_eq!(s.paint.fill, fill, "the canceled color is not kept");
s.begin_interaction("Stroke Weight").unwrap();
for _ in 0..3 {
s.preview("stroke.weightUp", &json!({"defaultsOnly": true})).unwrap();
}
assert_eq!(s.paint.stroke_width, 3.0, "each preview starts from 2 pt");
s.cancel_interaction().unwrap();
assert_eq!(s.paint.stroke_width, 2.0);
// A preview with `defaultsOnly: true` after one that set the defaults with the selection
// starts from the defaults the interaction began with too.
s.begin_interaction("Stroke Weight").unwrap();
s.preview("stroke.set", &json!({"weight": 7})).unwrap();
assert_eq!(s.paint.stroke_width, 7.0);
s.preview("paint.setFill", &json!({"color": "#123456", "defaultsOnly": true})).unwrap();
assert_eq!(s.paint.stroke_width, 2.0, "the discarded preview's weight is not kept");
s.cancel_interaction().unwrap();
assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (fill.clone(), 2.0));
assert_eq!((node(&s, g), node(&s, art)), (group, painted), "the selection keeps its paint");
// A later preview without `defaultsOnly` leaves the interaction one that changed the defaults:
// canceling puts them back.
s.begin_interaction("Stroke Weight").unwrap();
s.preview("stroke.weightUp", &json!({"defaultsOnly": true})).unwrap();
s.preview("stroke.set", &json!({"weight": 7})).unwrap();
s.cancel_interaction().unwrap();
assert_eq!(s.paint.stroke_width, 2.0, "the canceled interaction's weight is not kept");
// With New Art Has Basic Appearance off and an object selected, canceling such an interaction
// keeps the defaults it began with, not the selection's appearance.
let mut s = session();
let (_, art, ..) = setup(&mut s, false);
s.execute("paint.setFill", &json!({"color": "#ff0000", "defaultsOnly": true})).unwrap();
let (red, selected) = (s.paint.fill.clone(), node(&s, art));
s.begin_interaction("Fill Color").unwrap();
s.preview("paint.setFill", &json!({"color": "#00ffff", "defaultsOnly": true})).unwrap();
s.preview("stroke.set", &json!({"weight": 7})).unwrap();
s.cancel_interaction().unwrap();
assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (red, 2.0), "the defaults the interaction began with stay");
assert_eq!(node(&s, art), selected, "the selection keeps its paint");
// The same when the defaults-only step was inside a batch that a later preview replaced.
s.begin_interaction("Fill Color").unwrap();
let step = json!({"command": "paint.setFill", "params": {"color": "#00ffff", "defaultsOnly": true}});
s.preview("command.batch", &json!({"commands": [step]})).unwrap();
s.preview("stroke.set", &json!({"weight": 7})).unwrap();
s.cancel_interaction().unwrap();
assert_eq!(s.paint.fill, Paint::solid(Color::from_hex("#ff0000").unwrap()), "a batch's defaults-only step is put back");
// `defaultsOnly` is a bool, and names no objects or brush.
let (g, ..) = setup(&mut s, true);
for (cmd, params) in [
("paint.none", json!({"defaultsOnly": true, "ids": [g.0]})),
("paint.none", json!({"defaultsOnly": true, "id": g.0})),
("paint.none", json!({"defaultsOnly": true, "item": null})),
("paint.sampleColor", json!({"color": "#00ffff", "defaultsOnly": true, "id": g.0})),
("paint.sampleColor", json!({"color": "#00ffff", "defaultsOnly": true, "item": null})),
("paint.setFill", json!({"color": "#00ffff", "defaultsOnly": "yes"})),
("paint.setFill", json!({"color": "#00ffff", "defaultsOnly": true, "ids": [g.0]})),
("stroke.set", json!({"weight": 3, "defaultsOnly": true, "item": 0})),
("paint.sampleColor", json!({"color": "#00ffff", "defaultsOnly": true, "ids": [g.0]})),
("paint.none", json!({"defaultsOnly": 1})),
("stroke.setAdvanced", json!({"brush": null, "defaultsOnly": true})),
("stroke.setAdvanced", json!({"brush": "3 pt. Round", "defaultsOnly": true})),
] {
assert!(s.execute(cmd, &params).is_err(), "{cmd} {params}");
}
}
/// `paint.editGradient` with an `aspect` and no object to edit (the Live Paint Bucket's gradient,
/// nothing selected, or a fill edit of a Live Paint group without faces) is an error that leaves the default gradient as it was, since a gradient
/// fitted to each object has no aspect of its own. Named objects still take the aspect.
@@ -3493,6 +3669,34 @@ fn live_paint_bucket_keeps_its_colors_through_the_stop_eyedropper_and_a_cmd_clic
assert_eq!((s.paint.fill.clone(), s.tool_returns_to()), (fill, None), "the pick ended without a sample");
}
/// A Cmd-drag of a corner widget with the Live Paint Bucket that is cut short by choosing the
/// bucket again (the Selection tool it lent cancels the drag as it goes back) leaves the bucket's
/// colors as they were, with New Art Has Basic Appearance off: the selected object's appearance
/// does not replace them.
#[test]
fn live_paint_bucket_keeps_its_colors_when_a_lent_drag_is_cut_short() {
let v = ViewInfo::default();
let mut s = session();
let rect = rect(&mut s, 300.0, 300.0, 100.0, 100.0);
s.execute("paint.setFill", &json!({"color": "#00ff00", "ids": [rect.0]})).unwrap();
s.execute("appearance.setNewArtBasic", &json!({"on": false})).unwrap();
s.execute("select.set", &json!({"ids": [rect.0]})).unwrap();
s.select_tool("livePaintBucket", v).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
let fill = s.paint.fill.clone();
let st = s.doc().unwrap();
let w = vectorcraft_tools::corners::CornerWidgets::showing(&st.doc, &st.selection, v.zoom, false, true, 180.0).expect("corner widgets show");
let at = w.visible().next().expect("a widget");
let cmd = Mods { cmd: true, ..Mods::default() };
s.pointer(&PointerEvent::new(PointerKind::Down, at.x, at.y).with_mods(cmd), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, at.x + 8.0, at.y + 8.0).with_mods(cmd), v).unwrap();
assert_eq!(s.tool_id(), "selection", "the bucket lent the Selection tool for the drag");
assert!(s.in_interaction(), "the corner widget drag is in progress");
s.select_tool("livePaintBucket", v).unwrap();
assert_eq!(s.tool_id(), "livePaintBucket");
assert_eq!(s.paint.fill, fill, "the bucket's fill stays");
}
/// A gradient stop selected on the selection's gradient is not selected once the Live Paint
/// Bucket is active (its proxies show the default paint), and one selected on the bucket's
/// gradient is not selected once another tool is chosen.
+3 -3
View File
@@ -1,7 +1,7 @@
//! The Color Guide: `color.harmony` and saving several colours as swatches at once.
use serde_json::{Value, json};
use vectorcraft_color::Color;
use vectorcraft_color::{Color, harmony};
use crate::*;
@@ -38,9 +38,9 @@ fn harmony_query_returns_the_group_and_its_grid() {
assert_eq!(r2["rule"], "splitComplementary");
assert_eq!(r2["grid"][0].as_array().unwrap().len(), 9, "4 steps by default");
// Every rule answers, base first.
for h in vectorcraft_color::harmony::Harmony::ALL {
for h in harmony::Harmony::ALL {
let r = s.execute("color.harmony", &json!({"color": "#3366cc", "rule": h.id()})).unwrap();
assert_eq!(r["colors"][0], "#3366cc", "{}", h.label());
assert_eq!(r["colors"][0], "#3366cc", "{}", harmony::label(h));
}
assert!(s.execute("color.harmony", &json!({"color": "#ff0000", "rule": "square"})).is_err());
assert!(s.execute("color.harmony", &json!({"rule": "triad"})).is_err());
+128 -3
View File
@@ -481,7 +481,7 @@ fn eps_export_still_flattens_a_colorize_paint_on_a_color_image() {
fn a_colorized_missing_link_placeholder_is_not_flattened() {
let mut s = session();
let bytes = std::sync::Arc::new(vectorcraft_doc::links::missing_placeholder().unwrap());
let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) });
let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes), file_font: Default::default() });
s.edit("Colorize", |d, _| {
d.node_mut(id).unwrap().extras_mut().colorize = Some(Box::new(Paint::solid(Color::rgb8(255, 0, 0))));
Ok(())
@@ -502,7 +502,7 @@ fn a_colorized_missing_link_placeholder_is_not_flattened() {
fn a_fill_color_recolors_a_colorized_missing_link_placeholder() {
let mut s = session();
let bytes = std::sync::Arc::new(vectorcraft_doc::links::missing_placeholder().unwrap());
let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) });
let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes), file_font: Default::default() });
s.edit("Colorize", |d, _| {
d.node_mut(id).unwrap().extras_mut().colorize = Some(Box::new(Paint::solid(Color::rgb8(255, 0, 0))));
Ok(())
@@ -523,7 +523,7 @@ fn a_fill_color_recolors_a_colorized_missing_link_placeholder() {
fn a_colorized_missing_link_placeholder_in_a_spot_color_refuses_a_process_color() {
let mut s = session();
let bytes = std::sync::Arc::new(vectorcraft_doc::links::missing_placeholder().unwrap());
let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) });
let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes), file_font: Default::default() });
s.execute("swatch.new", &json!({"name": "Ink 2", "color": {"c": 100, "m": 0, "y": 0, "k": 0}, "spot": true})).unwrap();
s.edit("Colorize", |d, _| {
let ink = Paint::Solid { color: Color::rgb8(255, 0, 0), swatch: Some("Ink".into()), tint: 1.0 };
@@ -707,6 +707,131 @@ fn a_color_image_takes_a_fill_item_as_before() {
assert!(s.doc().unwrap().doc.node(id).unwrap().appearance.fill().is_some(), "a fill item, as before");
}
#[test]
fn overprint_fill_makes_a_colorized_images_color_overprint() {
let mut s = session();
let id = image(&mut s, "gray", gray(false));
let overprints = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().colorize_overprints();
// Before the image is colorized it has no fill to overprint.
let r = s.execute("object.setOverprint", &json!({"fill": true})).unwrap();
assert_eq!(r["changed"], 0);
s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap();
let r = s.execute("object.setOverprint", &json!({"fill": true})).unwrap();
assert_eq!(r["changed"], 1);
assert!(overprints(&s));
assert_eq!(s.execute("attributes.info", &json!({})).unwrap()["overprintFill"], true);
// A second time nothing changes, and no undo step is recorded.
let r = s.execute("object.setOverprint", &json!({"fill": true})).unwrap();
assert_eq!(r["changed"], 0);
// Native files keep it.
let d = &s.doc().unwrap().doc;
let back = vectorcraft_format::load(&vectorcraft_format::save(d, false)).unwrap();
assert!(back.node(id).unwrap().colorize_overprints());
// EPS turns overprinting on for the image's ink.
let out = s.execute("document.exportEps", &json!({"previewFormat": "none", "useArtboards": false})).unwrap();
let bytes = vectorcraft_format::base64_decode(out["dataBase64"].as_str().unwrap()).unwrap();
let ps = String::from_utf8_lossy(&bytes);
let (Some(on), Some(mask)) = (ps.find("true op"), ps.find("imagemask")) else { panic!("{ps}") };
assert!(on < mask, "overprint is on before the image is drawn");
// A legacy .ai file writes the image mask with its fill overprint, which opens again.
let r = s.execute("file.saveCopy", &json!({"format": "ai", "aiVersion": "7"})).unwrap();
let mut t = Session::new();
t.execute("document.open", &json!({"name": "t.ai", "dataBase64": r["dataBase64"]})).unwrap();
let mut opened = vec![];
t.doc().unwrap().doc.walk(|n| {
if matches!(n.kind, NodeKind::Image(_)) {
opened.push(n.colorize_overprints());
}
});
assert_eq!(opened, [true]);
s.execute("edit.undo", &json!({})).unwrap();
assert!(!overprints(&s), "undo makes it knock out again");
assert_eq!(s.execute("attributes.info", &json!({})).unwrap()["overprintFill"], false);
// Taking the color off drops its overprint, so a new color knocks out.
s.execute("object.setOverprint", &json!({"fill": true})).unwrap();
s.execute("paint.setFill", &json!({"none": true})).unwrap();
assert!(!s.doc().unwrap().doc.node(id).unwrap().extras().colorize_overprint);
s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap();
assert!(!overprints(&s), "a new color starts knocking out");
}
/// Overprint Black and Print Ink Fixes' Remove White Overprint treat a colorized image's color as
/// its fill.
#[test]
fn overprint_black_and_print_fixes_reach_a_colorized_images_color() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200, "colorMode": "cmyk"})).unwrap();
let id = image(&mut s, "gray", gray(false));
let overprints = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().colorize_overprints();
s.execute("paint.setFill", &json!({"color": {"c": 0, "m": 0, "y": 0, "k": 100}})).unwrap();
let v = s.execute("edit.colors.overprintBlack", &json!({})).unwrap();
assert!(overprints(&s), "a black image overprints: {v}");
s.execute("paint.setFill", &json!({"color": {"c": 0, "m": 0, "y": 0, "k": 0}})).unwrap();
assert!(overprints(&s), "a new color keeps the flag");
let v = s.execute("addon.color.printFixes", &json!({"removeWhiteOverprint": true})).unwrap();
assert_eq!(v["whiteOverprintRemoved"], 1, "{v}");
assert!(!overprints(&s), "white knocks out again");
}
/// A flattening for a file that writes colorized images in their ink (EPS) keeps the image, and
/// without Preserve Overprints its color knocks out again, as fills do; with it, the color keeps
/// overprinting.
#[test]
fn flattening_without_preserve_overprints_drops_a_colorized_images_overprint() {
let mut s = session();
image(&mut s, "gray", gray(false));
s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap();
s.execute("object.setOverprint", &json!({"fill": true})).unwrap();
// A translucent square elsewhere gives the flattener something to flatten.
let square = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("transparency.set", &json!({"ids": [square], "opacity": 50})).unwrap();
let overprints = |preserve: bool| {
let mut options = crate::cmd::flatten::FlattenOptions::preset("low").unwrap();
(options.keeps_colorize, options.preserve_overprints) = (true, preserve);
let flat = crate::cmd::flatten::flatten_document(&s.doc().unwrap().doc, &options).unwrap().unwrap();
let mut found = vec![];
flat.walk(|n| {
if matches!(n.kind, NodeKind::Image(_)) {
found.push(n.colorize_overprints());
}
});
found
};
assert_eq!(overprints(true), [true]);
assert_eq!(overprints(false), [false]);
}
/// Flattening without Preserve Overprints also clears the overprint an image keeps after its
/// color was removed, so a color given to it later knocks out.
#[test]
fn flattening_without_preserve_overprints_clears_an_uncolored_images_overprint() {
let mut s = session();
let id = image(&mut s, "gray", gray(false));
s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap();
s.execute("object.setOverprint", &json!({"fill": true})).unwrap();
let square = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("transparency.set", &json!({"ids": [square], "opacity": 50})).unwrap();
let mut d = (*s.doc().unwrap().doc).clone();
let Some(n) = d.node_mut(id) else { panic!("the image") };
n.extras_mut().colorize = None;
assert!(n.extras().colorize_overprint && !n.colorize_overprints(), "the flag outlives the color");
let mut options = crate::cmd::flatten::FlattenOptions::preset("low").unwrap();
(options.keeps_colorize, options.preserve_overprints) = (true, false);
let flat = crate::cmd::flatten::flatten_document(&d, &options).unwrap().unwrap();
let mut found = vec![];
flat.walk(|n| {
if matches!(n.kind, NodeKind::Image(_)) {
found.push(n.extras().colorize_overprint);
}
});
assert_eq!(found, [false]);
}
#[test]
fn colorized_images_save_and_open_with_their_color() {
let mut s = session();
+2 -2
View File
@@ -3,7 +3,7 @@
use serde_json::{Value, json};
use vectorcraft_color::Color;
use vectorcraft_color::harmony::Harmony;
use vectorcraft_color::harmony::{self, Harmony};
use crate::*;
@@ -31,7 +31,7 @@ fn themes_save_list_edit_and_delete() {
let r = run(&mut s, "colorTheme.save", json!({"color": "#3366cc", "rule": "Triad", "name": " Sea "}));
assert_eq!(r["name"], "Sea");
let t = &run(&mut s, "colorTheme.list", json!({}))["themes"][1];
let want: Vec<String> = Harmony::Triad.theme(Color::from_hex("#3366cc").unwrap()).iter().map(Color::to_hex).collect();
let want: Vec<String> = harmony::theme(Harmony::Triad, Color::from_hex("#3366cc").unwrap()).iter().map(Color::to_hex).collect();
assert_eq!(t["colors"], json!(want));
assert_eq!(t["rule"], "triad");
// Names stay unique (ignoring case); replace edits a theme in place, renaming it if asked.
-10
View File
@@ -238,16 +238,6 @@ fn a_typed_closing_double_quote_opens_where_a_quote_opens() {
// More than one character is pasted text, not a typed quote.
let id = type_at(&mut s, 50.0, 300.0, &["”a”"]);
assert_eq!(text(&s, id).plain_text(), "”a”");
// An IME commit of a lone `”` that will open is not verbatim (it is rewritten); from the Glyphs
// panel it would be inserted as it is.
let v = ViewInfo::default();
s.select_tool("type", v).unwrap();
for k in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(k, 50.0, 312.0), v).unwrap();
}
assert!(!s.tool_typed_text_is_verbatim("”", v));
assert!(s.tool_text_is_verbatim("”", v));
s.tool_key(ToolKey::Escape, Default::default(), v).unwrap();
// A `”` inserted from the Glyphs panel or pasted alone stays as inserted.
let id = enter_at(&mut s, 50.0, 325.0, &["”", "a"], false);
assert_eq!(text(&s, id).plain_text(), "”a");
+153 -15
View File
@@ -2306,15 +2306,25 @@ fn a_smooth_drag_that_comes_back_to_a_segment_smooths_where_it_comes_back() {
assert!(gap < 0.5, "{between:?} is {gap} pt off the smoothed path");
}
/// A click on a curve 100,000 pt long, between the places a fixed number of samples along it would
/// look at, still finds the curve under it.
/// A click on the sharp crest of a curve 100,000 pt wide finds the curve under it, although the crest
/// lies halfway between two of 65 evenly spaced places along the curve and more than the click's 12 pt
/// reach from each of them, so a search that looked only at those places would miss it.
#[test]
fn a_smooth_drag_finds_a_very_long_curve_under_it() {
use kurbo::ParamCurve;
let mut s = session();
let anchors = [json!({"x": 0.0, "y": 0.0, "out": [30000.0, -9000.0]}), json!({"x": 100000.0, "y": 0.0, "in": [70000.0, -9000.0]})];
// The crest is a cusp at t0: the control points are chosen so that the curve's velocity is 0 there.
let (t0, wide): (f64, f64) = (32.5 / 64.0, 1.0e5);
let (d0, d2) = ((wide, -wide), (wide, wide));
let d1 = ((1.0 - t0).powi(2) * d0.0 + t0 * t0 * d2.0, (1.0 - t0).powi(2) * d0.1 + t0 * t0 * d2.1);
let d1 = (-d1.0 / (2.0 * t0 * (1.0 - t0)), -d1.1 / (2.0 * t0 * (1.0 - t0)));
let (p1, p2) = (d0, (d0.0 + d1.0, d0.1 + d1.1));
let anchors = [json!({"x": 0.0, "y": 0.0, "out": [p1.0, p1.1]}), json!({"x": p2.0 + d2.0, "y": p2.1 + d2.1, "in": [p2.0, p2.1]})];
let id = smooth_test_path(&mut s, &anchors, false);
let at = path(&s, id).subpaths[0].segment(0).eval(0.5 + 0.5 / 1024.0);
let curve = path(&s, id).subpaths[0].segment(0);
let at = curve.eval(t0);
let nearest_place = (0..=64).map(|k| curve.eval(f64::from(k) / 64.0).distance(at)).fold(f64::INFINITY, f64::min);
assert!(nearest_place > 12.0, "the nearest of 65 places is {nearest_place} pt from the click");
assert_eq!(smooth_pass_ids(&mut s, &[at]), json!([id.0]));
}
@@ -2329,9 +2339,9 @@ fn a_smooth_click_that_only_just_reaches_a_segment_smooths_it() {
assert_ne!(path(&s, id), before);
}
/// A drag that runs along a very long curve first and then crosses a second curve away from its
/// middle, with both of its anchors out of reach, smooths the second curve too: each curve in reach
/// gets the same share of the search, so the long one does not use it all.
/// A drag that runs along a very long curve first and then crosses a second curve at the peak in
/// its middle, with both of its anchors out of reach, smooths the second curve too: each curve in
/// reach gets the same share of the search, so the long one does not use it all.
#[test]
fn a_long_curve_searched_first_leaves_the_next_curve_its_share() {
let mut s = session();
@@ -2342,7 +2352,7 @@ fn a_long_curve_searched_first_leaves_the_next_curve_its_share() {
);
let next = smooth_test_path(
&mut s,
&[json!({"x": 100100.0, "y": -100.0, "out": [100130.0, 200.0]}), json!({"x": 100100.0, "y": 900.0, "in": [100130.0, 600.0]})],
&[json!({"x": 100050.0, "y": 75.0, "out": [100150.0, -25.0]}), json!({"x": 100250.0, "y": 75.0, "in": [100150.0, -25.0]})],
false,
);
s.execute("select.set", &json!({"ids": [long.0, next.0]})).unwrap();
@@ -2372,14 +2382,14 @@ fn smoothing_smooths_an_open_two_anchor_path() {
assert_eq!((a[0].p, a[a.len() - 1].p), (Point::new(100.0, 200.0), Point::new(200.0, 200.0)), "the ends stay");
}
/// A closed path of two anchors is smoothed along the middle of one side and stays closed.
/// A closed path of two anchors is smoothed at the peak in the middle of one side and stays closed.
#[test]
fn smoothing_smooths_a_closed_two_anchor_path() {
use kurbo::ParamCurve;
let mut s = session();
let anchors = [
json!({"x": 100.0, "y": 300.0, "in": [100.0, 400.0], "out": [100.0, 200.0]}),
json!({"x": 300.0, "y": 300.0, "in": [300.0, 160.0], "out": [300.0, 440.0]}),
json!({"x": 100.0, "y": 300.0, "in": [100.0, 400.0], "out": [200.0, 150.0]}),
json!({"x": 300.0, "y": 300.0, "in": [200.0, 150.0], "out": [300.0, 440.0]}),
];
let id = smooth_test_path(&mut s, &anchors, true);
let before = path(&s, id);
@@ -2405,6 +2415,76 @@ fn smoothing_leaves_paths_out_of_reach_and_straight_segments_alone() {
assert_eq!(path(&s, line), before);
}
/// Whether `id` is still a Live Shape.
fn smooth_test_live(s: &Session, id: NodeId) -> bool {
matches!(s.doc().unwrap().doc.node(id).unwrap().kind, NodeKind::Path { live: Some(_), .. })
}
/// Smooth drags over a clean ellipse, again and again and at any Fidelity, change nothing: the
/// ellipse has nothing to smooth, so no pass adds anchors to it, leaves it rougher, adds an undo step
/// or takes its Live Shape away. Each returns no ids and counts of 0, as a drag that reaches no path
/// does.
#[test]
fn smooth_drags_over_a_clean_ellipse_change_nothing() {
for fidelity in [0.05, 0.5, 2.5, 10.0] {
let mut s = session();
let id = NodeId(s.execute("shape.ellipse", &json!({"x": 100, "y": 100, "width": 200, "height": 120})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
let before = path(&s, id);
let undo = s.doc().unwrap().history.undo.len();
let pts: Vec<_> = smooth_drag_along(100.0, 160.0, 240.0).iter().map(|p| json!([p.x, p.y])).collect();
for pass in 1..=4 {
let r = s.execute("path.smoothRegion", &json!({"points": pts, "radius": 12, "fidelity": fidelity})).unwrap();
assert_eq!(r, json!({"ids": [], "before": 0, "after": 0}), "Fidelity {fidelity}, pass {pass}");
assert_eq!(path(&s, id), before, "Fidelity {fidelity}, pass {pass}: {} anchors", path(&s, id).anchor_count());
assert!(smooth_test_live(&s, id), "Fidelity {fidelity}, pass {pass}: still a Live Shape");
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "Fidelity {fidelity}, pass {pass}: no undo step");
}
}
}
/// A Smooth drag over a clean ellipse and a jagged line selected together smooths the line only: the
/// result names the line and counts its anchors alone, the ellipse stays as it was and a Live Shape,
/// and one undo brings the line back.
#[test]
fn a_smooth_drag_over_an_ellipse_and_a_jagged_line_changes_only_the_line() {
let mut s = session();
let ellipse = NodeId(s.execute("shape.ellipse", &json!({"x": 100, "y": 100, "width": 200, "height": 120})).unwrap()["id"].as_u64().unwrap());
let mut seed = 11u64;
let anchors: Vec<_> = (0..=50).map(|i| json!({"x": 320.0 + 5.0 * f64::from(i), "y": 100.0 + smooth_noise(&mut seed)})).collect();
let line = smooth_test_path(&mut s, &anchors, false);
s.execute("select.set", &json!({"ids": [ellipse.0, line.0]})).unwrap();
let (oval, jagged) = (path(&s, ellipse), path(&s, line));
let pts: Vec<_> = smooth_drag_along(100.0, 160.0, 580.0).iter().map(|p| json!([p.x, p.y])).collect();
let r = s.execute("path.smoothRegion", &json!({"points": pts, "radius": 12, "fidelity": 2.5})).unwrap();
let smoothed = path(&s, line);
assert!(smoothed.anchor_count() < jagged.anchor_count(), "the line is smoothed: {} anchors", smoothed.anchor_count());
assert_eq!(r, json!({"ids": [line.0], "before": jagged.anchor_count(), "after": smoothed.anchor_count()}));
assert_eq!(path(&s, ellipse), oval);
assert!(smooth_test_live(&s, ellipse), "the ellipse is still a Live Shape");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!((path(&s, line), path(&s, ellipse)), (jagged, oval));
}
/// A Smooth drag at the lowest Fidelity still smooths a jagged line: it turns less and has fewer
/// anchors after each of three drags.
#[test]
fn a_smooth_drag_at_the_lowest_fidelity_still_smooths_a_jagged_line() {
let mut s = session();
let mut seed = 11u64;
let anchors: Vec<_> = (0..=60).map(|i| json!({"x": 100.0 + 5.0 * f64::from(i), "y": 200.0 + smooth_noise(&mut seed)})).collect();
let id = smooth_test_path(&mut s, &anchors, false);
let pts: Vec<_> = smooth_drag_along(200.0, 90.0, 410.0).iter().map(|p| json!([p.x, p.y])).collect();
let mut before = path(&s, id);
for pass in 1..=3 {
s.execute("path.smoothRegion", &json!({"points": pts, "radius": 12, "fidelity": 0.05})).unwrap();
let after = path(&s, id);
assert!(after.anchor_count() < before.anchor_count(), "pass {pass}: {} -> {} anchors", before.anchor_count(), after.anchor_count());
assert!(total_turning(&after) < total_turning(&before), "pass {pass}: turning {} -> {}", total_turning(&before), total_turning(&after));
before = after;
}
}
/// The turn, in degrees, of `sp` at each of its anchors: round a closed path, and 0 at an open
/// path's first and last anchors.
fn smooth_anchor_turns(sp: &vectorcraft_geom::SubPath) -> Vec<f64> {
@@ -3335,6 +3415,66 @@ fn path_eraser_width_outside_its_range_is_refused() {
}
}
/// `path.smoothRegion` refuses a `radius` outside 0.001 to 1000 pt and a `fidelity` outside the
/// Smooth tool's tolerance range, and `path.joinScrub` a `tolerance` outside 0.001 to 1000 pt: the
/// document, the selection and the undo history do not change. The ends of each range are taken,
/// and null is read as the key left out, which smooths or joins in one undo step.
#[test]
fn smooth_and_join_refuse_a_reach_or_fidelity_outside_its_range() {
let mut s = session();
let anchors: Vec<_> = (0..=40).map(|i| json!({"x": 100.0 + i as f64 * 5.0, "y": if i % 2 == 0 { 200.0 } else { 203.0 }})).collect();
let r = s.execute("path.create", &json!({"anchors": anchors})).unwrap();
let id = NodeId(r["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
let drag = json!({"points": [[90, 200], [200, 200], [310, 200]]});
let (lo, hi) = (vectorcraft_tools::draw2::SMOOTH_MIN_TOLERANCE, vectorcraft_tools::draw2::SMOOTH_MAX_TOLERANCE);
let reaches = [json!(0), json!(-1), json!(0.0009), json!(1e-300), json!(1000.01), json!(1e300)];
let fidelities = [json!(0), json!(-1), json!(lo / 2.0), json!(hi * 1.01), json!(1e300)];
let refused = reaches
.iter()
.map(|x| ("radius", x, "`radius` must be from 0.001 to 1000".to_string()))
.chain(fidelities.iter().map(|x| ("fidelity", x, format!("`fidelity` must be from {lo} to {hi} pt"))));
for (key, x, want) in refused {
let sel = s.doc().unwrap().selection.clone();
refuses_with(&mut s, "path.smoothRegion", &with(&drag, json!({ key: x })), &want);
assert_eq!(s.doc().unwrap().selection, sel, "{key} {x} changed the selection");
}
for extra in [json!({"radius": 0.001}), json!({"radius": 1000}), json!({"fidelity": lo}), json!({"fidelity": hi})] {
let undo = undo_steps(&s);
s.execute("path.smoothRegion", &with(&drag, extra.clone())).unwrap_or_else(|e| panic!("{extra}: {e}"));
while undo_steps(&s) > undo {
s.execute("edit.undo", &json!({})).unwrap();
}
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
}
let before = path(&s, id);
let undo = undo_steps(&s);
s.execute("path.smoothRegion", &with(&drag, json!({"radius": null, "fidelity": null}))).unwrap();
assert!(path(&s, id) != before, "the default radius and fidelity smoothed nothing");
assert_eq!(undo_steps(&s), undo + 1);
let mut s = session();
line(&mut s, 100.0, 100.0, 200.0, 100.0);
line(&mut s, 205.0, 100.0, 300.0, 150.0);
s.execute("select.none", &json!({})).unwrap();
let scrub = json!({"points": [[202, 90], [202, 110]]});
for x in &reaches {
refuses_with(&mut s, "path.joinScrub", &with(&scrub, json!({"tolerance": x})), "`tolerance` must be from 0.001 to 1000");
assert_eq!(paths(&s).len(), 2, "tolerance {x}");
}
s.execute("path.joinScrub", &with(&scrub, json!({"tolerance": 0.001}))).unwrap();
assert_eq!(paths(&s).len(), 2, "0.001 pt reaches neither end");
let undo = undo_steps(&s);
s.execute("path.joinScrub", &with(&scrub, json!({"tolerance": 1000}))).unwrap();
while undo_steps(&s) > undo {
s.execute("edit.undo", &json!({})).unwrap();
}
s.execute("select.none", &json!({})).unwrap();
s.execute("path.joinScrub", &with(&scrub, json!({"tolerance": null}))).unwrap();
assert_eq!(paths(&s).len(), 1, "the default tolerance joined nothing");
assert_eq!(undo_steps(&s), undo + 1);
}
/// The Eraser, Path Eraser, Smooth, Join and Blob Brush commands refuse a size, angle, roundness,
/// width, radius, fidelity or tolerance given as text or as another value that is not a number, and change
/// nothing; null is read as the key left out.
@@ -5047,10 +5187,8 @@ fn the_pen_continues_any_open_path_and_joins_another() {
assert_eq!(s.doc().unwrap().selection.objects, vec![a]);
assert_eq!(s.cursor(Point::new(300.0, 200.0), none, v), Cursor::PenJoin);
assert_eq!(s.cursor(Point::new(350.0, 200.0), none, v), Cursor::PenDrawing, "the middle of the other path");
// #1009: Use Precise Cursors makes the join pointer a crosshair too.
s.execute("prefs.set", &json!({"key": "usePreciseCursors", "value": true})).unwrap();
assert_eq!(s.cursor(Point::new(300.0, 200.0), none, v), Cursor::Crosshair);
s.execute("prefs.set", &json!({"key": "usePreciseCursors", "value": false})).unwrap();
// #1009: Use Precise Cursors makes the join pointer a crosshair too (the canvas applies `Cursor::precise`).
assert_eq!(s.cursor(Point::new(300.0, 200.0), none, v).precise(), Cursor::Crosshair);
assert_eq!(gesture(&mut s, &[(300.0, 200.0)], none), 1);
let pts = |s: &Session, id| path(s, id).subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|x| (x.p.x, x.p.y))).collect::<Vec<_>>();
assert_eq!(pts(&s, a), [(100.0, 100.0), (200.0, 100.0), (300.0, 200.0), (400.0, 200.0)]);
+180
View File
@@ -587,6 +587,186 @@ fn direct_selection_paints_one_object_of_one_dynamic_instance() {
assert_eq!(pixel(&s, 80, 30), BLUE);
}
/// Instance `inst` with a new fill (`fill`) or stroke row without paint whose effect is `effect`
/// with `params`.
fn row_effect(s: &mut Session, inst: NodeId, fill: bool, effect: &str, params: Value) {
s.execute(if fill { "appearance.addFill" } else { "appearance.addStroke" }, &json!({"ids": [inst.0]})).unwrap();
let row = node(s, inst).appearance.items.len() - 1;
s.execute("appearance.setItem", &json!({"ids": [inst.0], "index": row, "none": true})).unwrap();
s.execute("effect.apply", &json!({"ids": [inst.0], "item": row, "effect": effect, "params": params})).unwrap();
}
/// The object of `inst`'s art that Direct Selection picks at (`x`, `y`) with `opt`.
fn part_at(s: &Session, inst: NodeId, (x, y): (f64, f64), opt: vectorcraft_doc::hit::HitOptions) -> Option<Vec<u32>> {
let doc = &s.doc().unwrap().doc;
vectorcraft_doc::hit::symbol_part_at(doc, doc.node(inst).unwrap(), vectorcraft_geom::Point::new(x, y), opt)
}
/// The box of the outline of the object at `path` in `inst`'s art, as Direct Selection draws it.
fn part_outline_box(s: &Session, inst: NodeId, path: &[u32]) -> Rect {
use vectorcraft_geom::kurbo::Shape;
let doc = &s.doc().unwrap().doc;
let outline = vectorcraft_doc::hit::symbol_part_outline_in_view(doc, doc.node(inst).unwrap(), path, Default::default()).unwrap();
outline.bounding_box()
}
/// A geometry effect on a dynamic instance's fill or stroke moves where the objects of its art
/// are drawn: Direct Selection picks an object where it is drawn, not where its own shape no longer
/// paints, and outlines it there; Outline view still takes the plain shapes.
#[test]
fn direct_selection_picks_a_part_where_the_instance_fill_and_stroke_effects_draw_it() {
use vectorcraft_doc::hit::HitOptions;
let opt = HitOptions { tol: 1.0, ..Default::default() };
let mut s = session();
let inst = pair(&mut s, "dynamic");
row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100}));
// The squares are drawn at x 110..150 and 160..200.
assert_eq!(part_at(&s, inst, (130.0, 30.0), opt), Some(vec![0]), "the first square where it is drawn");
assert_eq!(part_at(&s, inst, (180.0, 30.0), opt), Some(vec![1]), "the second square where it is drawn");
assert_eq!(part_at(&s, inst, (80.0, 30.0), opt), None, "where the second square's own shape no longer paints");
assert_eq!(part_at(&s, inst, (60.5, 30.0), opt), None, "the plain edge of the second square");
assert_eq!(part_at(&s, inst, (60.5, 30.0), HitOptions { outline: true, ..opt }), Some(vec![1]), "Outline view draws the plain shapes");
let b = part_outline_box(&s, inst, &[0]);
assert!((b.x0 - 110.0).abs() < 0.5 && (b.x1 - 150.0).abs() < 0.5, "the outline follows the moved square: {b:?}");
direct(&mut s, (130.0, 30.0), (130.0, 30.0), Mods::default());
let sel = s.doc().unwrap().selection.clone();
assert_eq!(sel.objects, [inst]);
assert_eq!(sel.symbol_part, Some(vectorcraft_doc::SymbolPart { instance: inst, path: vec![0] }), "a press on the drawn square picks it");
// A stroke effect: Offset Path moves the first square's stroke out to x = 0.
let mut s = session();
let (a, b) = (square(&mut s, 10.0), square(&mut s, 60.0));
s.execute("paint.setStroke", &json!({"ids": [a.0, b.0], "color": "#00ff00"})).unwrap();
let inst = id(&s.execute("symbol.new", &json!({"name": "Pair", "ids": [a.0, b.0], "type": "dynamic"})).unwrap());
row_effect(&mut s, inst, false, "path.offsetPath", json!({"offset": 10}));
assert_eq!(part_at(&s, inst, (0.5, 30.0), opt), Some(vec![0]), "the moved stroke");
assert_eq!(part_at(&s, inst, (30.0, 30.0), opt), Some(vec![0]), "the fill keeps its shape");
let b = part_outline_box(&s, inst, &[0]);
assert!(b.x0 < 1.0 && b.x1 > 59.0, "the outline takes in the moved stroke: {b:?}");
// A symbol instance in the art takes the effect too: it is picked and outlined where its art is
// drawn, not in its box. The fill effect moves its square; its image has no fill and stays.
let mut s = session();
let a = square(&mut s, 10.0);
place_image(&mut s);
let img = top(&s);
let inner = id(&s.execute("symbol.new", &json!({"name": "Inner", "ids": [a.0, img.0]})).unwrap());
let b = square(&mut s, 60.0);
let inst = id(&s.execute("symbol.new", &json!({"name": "Outer", "ids": [inner.0, b.0], "type": "dynamic"})).unwrap());
row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100}));
assert_eq!(part_at(&s, inst, (130.0, 30.0), opt), Some(vec![0]), "the nested instance's square where it is drawn");
assert_eq!(part_at(&s, inst, (65.0, 35.0), opt), Some(vec![0]), "the nested instance's image");
assert_eq!(part_at(&s, inst, (30.0, 30.0), opt), None, "the nested instance's own box");
let b = part_outline_box(&s, inst, &[0]);
assert!((b.x0 - 50.0).abs() < 0.5 && (b.x1 - 150.0).abs() < 0.5, "the outline takes in the moved square and the image: {b:?}");
// A nested instance with a geometry effect of its own is picked where both effects draw it.
let mut s = session();
let a = square(&mut s, 10.0);
let inner = id(&s.execute("symbol.new", &json!({"name": "Inner", "ids": [a.0]})).unwrap());
s.execute("effect.apply", &json!({"ids": [inner.0], "effect": "distort.transform", "params": {"moveV": 30}})).unwrap();
let b = square(&mut s, 60.0);
let inst = id(&s.execute("symbol.new", &json!({"name": "Outer", "ids": [inner.0, b.0], "type": "dynamic"})).unwrap());
row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100}));
assert_eq!(part_at(&s, inst, (130.0, 60.0), opt), Some(vec![0]), "the nested square moved by both effects");
assert_eq!(part_at(&s, inst, (30.0, 30.0), opt), None, "the nested instance's own box");
let b = part_outline_box(&s, inst, &[0]);
assert!((b.x0 - 110.0).abs() < 0.5 && (b.y0 - 40.0).abs() < 0.5 && (b.y1 - 80.0).abs() < 0.5, "the outline follows both effects: {b:?}");
// Type with a fill of its own in the art is picked and outlined where the fill effect draws its
// glyphs, not in its own bounds.
let mut s = session();
let t = id(&s.execute("text.create", &json!({"x": 10, "y": 45, "size": 40, "text": "I"})).unwrap());
s.execute("appearance.addFill", &json!({"ids": [t.0]})).unwrap();
let plain = {
let doc = &s.doc().unwrap().doc;
doc.node(t).unwrap().geometric_bounds().unwrap()
};
let b = square(&mut s, 60.0);
let inst = id(&s.execute("symbol.new", &json!({"name": "Outer", "ids": [t.0, b.0], "type": "dynamic"})).unwrap());
row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100}));
// The type's own color still paints the glyph in place; the new fill paints it 100 pt right.
let drawn = part_outline_box(&s, inst, &[0]);
assert!(drawn.x1 > plain.x1 + 90.0 && drawn.x1 < plain.x1 + 101.0, "the outline takes in the moved glyph: {drawn:?}, plain {plain:?}");
let glyph = drawn.x1 - 100.0 - drawn.x0;
let (x, y) = (drawn.x1 - glyph / 2.0, (drawn.y0 + drawn.y1) / 2.0);
assert_eq!(part_at(&s, inst, (x, y), opt), Some(vec![0]), "the type where the fill effect draws its glyph");
assert_eq!(part_at(&s, inst, (plain.x0 + 1.0, plain.y0 + 1.0), opt), None, "the type's own bounds, off its glyph");
let by_path = HitOptions { type_path_only: true, ..opt };
assert_eq!(part_at(&s, inst, (plain.x1 - 1.5, 45.0), by_path), Some(vec![0]), "Type Object Selection by Path Only takes the baseline");
// A nested instance whose own effect adds only pixels (a drop shadow) is still picked where the
// outer fill effect draws its art.
let mut s = session();
let a = square(&mut s, 10.0);
let inner = id(&s.execute("symbol.new", &json!({"name": "Inner", "ids": [a.0]})).unwrap());
s.execute("effect.apply", &json!({"ids": [inner.0], "effect": "stylize.dropShadow"})).unwrap();
let b = square(&mut s, 60.0);
let inst = id(&s.execute("symbol.new", &json!({"name": "Outer", "ids": [inner.0, b.0], "type": "dynamic"})).unwrap());
row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100}));
assert_eq!(part_at(&s, inst, (130.0, 30.0), opt), Some(vec![0]), "the shadowed nested square where it is drawn");
assert_eq!(part_at(&s, inst, (30.0, 30.0), opt), None, "the shadowed nested instance's own box");
// An image whose fill has Convert to Shape is picked and outlined where the instance's fill
// effect moves that shape.
let mut s = session();
place_image(&mut s);
let img = top(&s);
let frame = node(&s, img).geometric_bounds().unwrap();
s.execute("appearance.addFill", &json!({"ids": [img.0]})).unwrap();
s.execute("paint.setFill", &json!({"ids": [img.0], "color": "#00ff00", "item": 0})).unwrap();
s.execute("effect.apply", &json!({"ids": [img.0], "effect": "convertToShape.rectangle", "item": 0})).unwrap();
let b = square(&mut s, 200.0);
let inst = id(&s.execute("symbol.new", &json!({"name": "Outer", "ids": [img.0, b.0], "type": "dynamic"})).unwrap());
row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100}));
let c = frame.center();
assert_eq!(part_at(&s, inst, (c.x + 100.0, c.y), opt), Some(vec![0]), "the image where its fill is drawn");
let o = part_outline_box(&s, inst, &[0]);
assert!(o.x1 > frame.x1 + 99.0, "the outline takes in the moved fill: {o:?}, frame {frame:?}");
}
/// A clipping path in a dynamic symbol's art with a geometry effect of its own is picked by its
/// own geometry, and Direct Selection outlines that geometry, not the shape the effect draws.
#[test]
fn a_picked_clipping_path_is_outlined_by_its_own_geometry() {
let mut s = session();
let content = square(&mut s, 20.0);
let clip = square(&mut s, 10.0);
s.execute("object.clippingMask.make", &json!({"ids": [content.0, clip.0]})).unwrap();
s.execute("effect.apply", &json!({"ids": [clip.0], "effect": "path.offsetPath", "params": {"offset": 10}})).unwrap();
let group = top(&s);
assert!(node(&s, group).clips());
let inst = id(&s.execute("symbol.new", &json!({"name": "Clip", "ids": [group.0], "type": "dynamic"})).unwrap());
let b = part_outline_box(&s, inst, &[0]);
assert!((b.x0 - 10.0).abs() < 0.5 && (b.x1 - 50.0).abs() < 0.5, "the clipping path's own edge: {b:?}");
}
/// A symbol instance in a dynamic symbol's art whose own art is a clip group takes the instance's
/// fill effect on the clip group's members, which the canvas draws moved: Direct Selection picks it
/// where its member is drawn, not where the member's own shape is, and outlines it there.
#[test]
fn a_nested_instance_of_a_clip_group_is_picked_where_the_fill_effect_draws_its_art() {
use vectorcraft_doc::hit::HitOptions;
let opt = HitOptions { tol: 1.0, ..Default::default() };
let mut s = session();
let content = square(&mut s, 10.0);
let clip = id(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 200, "height": 60})).unwrap());
s.execute("object.clippingMask.make", &json!({"ids": [content.0, clip.0]})).unwrap();
let group = top(&s);
assert!(node(&s, group).clips());
let inner = id(&s.execute("symbol.new", &json!({"name": "Inner", "ids": [group.0]})).unwrap());
let b = square(&mut s, 160.0);
let inst = id(&s.execute("symbol.new", &json!({"name": "Outer", "ids": [inner.0, b.0], "type": "dynamic"})).unwrap());
row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100}));
// The member is drawn at x 110..150, inside the clipping path.
assert_eq!(pixel(&s, 130, 30), BLUE, "the canvas draws the member moved");
assert_ne!(pixel(&s, 30, 30), BLUE, "and not in its own place");
assert_eq!(part_at(&s, inst, (130.0, 30.0), opt), Some(vec![0]), "the nested instance where its member is drawn");
assert_eq!(part_at(&s, inst, (30.0, 30.0), opt), None, "the member's own place");
let o = part_outline_box(&s, inst, &[0]);
assert!((o.x0 - 110.0).abs() < 0.5 && (o.x1 - 150.0).abs() < 0.5, "the outline follows the moved member: {o:?}");
}
#[test]
fn a_drag_of_a_picked_object_moves_nothing_and_says_why() {
let mut s = session();
-16
View File
@@ -302,19 +302,3 @@ fn ime_target_survives_edits_and_changes_with_the_document() {
let second = s.tool_ime_target(v).expect("the new document's type has a target");
assert_ne!(first.0, second.0, "a document replacement is a new IME owner");
}
/// The outgoing surrounding-text source excludes the pre-edit and reports UTF-8 byte offsets.
#[test]
fn ime_surrounding_excludes_the_preedit_and_remaps_offsets() {
let mut s = session();
let v = ViewInfo::default();
s.select_tool("type", v).unwrap();
click(&mut s, 100.0, 100.0);
s.tool_text("Hé", v).unwrap();
s.tool_preedit("xy", None, v).unwrap();
let vectorcraft_tools::ImeSurrounding::Available { text, cursor, anchor } = s.tool_ime_surrounding(4000, v) else {
panic!("type editing has a context");
};
assert_eq!(text, "Hé");
assert_eq!((cursor, anchor), (3, 3), "the caret sits after the committed text, before the pre-edit");
}
+64 -1
View File
@@ -1,6 +1,7 @@
//! Commands that remove, insert or copy many objects, and an Alt-drag that copies them, each walk
//! the document's tree a few times on one layer of 25,000 to 100,000 objects, and objects in two
//! layers and inside a group keep their order and ids.
//! layers and inside a group keep their order and ids. Selecting objects one at a time looks up
//! only the added ones.
use std::sync::Arc;
use std::time::Duration;
@@ -120,6 +121,44 @@ fn delete_of_100000_objects_takes_few_tree_walks() {
undo_gives_back(&mut s, &before);
}
#[test]
fn deleting_2000_objects_by_id_one_at_a_time_takes_few_tree_walks() {
// From the top down, from the bottom up, and from the middle out.
let orders: [fn(Vec<NodeId>) -> Vec<NodeId>; 3] = [
|ids| ids.into_iter().rev().collect(),
|ids| ids,
|ids| {
let middle = ids.len() / 2;
let mut placed: Vec<(usize, NodeId)> = ids.into_iter().enumerate().collect();
placed.sort_by_key(|(k, _)| k.abs_diff(middle));
placed.into_iter().map(|(_, id)| id).collect()
},
];
for order in orders {
let mut s = session(2_000, square);
s.execute("guide.add", &json!({"pos": 5.0})).unwrap();
let doc = &s.doc().unwrap().doc;
let all: Vec<NodeId> = layer(&s, 0).into_iter().filter(|id| !doc.node(*id).unwrap().is_ruler_guide()).collect();
assert_eq!(all.len(), 2_000);
let (kept, art) = (all[0], all[1..].to_vec());
s.execute("select.set", &json!({"ids": [kept]})).unwrap();
let ids = order(art);
let (mut s, steps) = soon(s, "edit.clear", move |s| {
let mut steps = vec![s.doc().unwrap().doc.clone()];
for id in &ids {
s.execute("edit.clear", &json!({"ids": [id.0]})).unwrap();
steps.push(s.doc().unwrap().doc.clone());
}
steps
});
assert_eq!(layer(&s, 0).len(), 2, "the kept object and the guide");
assert!(selected(&s, &[kept]));
for before in steps.iter().rev().skip(1).take(3) {
undo_gives_back(&mut s, before);
}
}
}
#[test]
fn delete_selection_of_100000_rows_takes_few_tree_walks() {
let s = session(100_000, square);
@@ -658,3 +697,27 @@ fn copies_of_ids_listed_twice_or_inside_another_listed_id_keep_their_order_and_i
assert_eq!(layers(&s), [json!([a, n + 1, n, b, c, [group, d, e, f]]), json!([g, h])]);
undo_gives_back(&mut s, &before);
}
/// `select.add` run once for each of `n` objects, from nothing selected → the walks of the tree and
/// the lookups by id it took.
fn add_one_at_a_time(n: usize) -> (u64, u64) {
let mut s = session(n, square);
s.execute("select.none", &json!({})).unwrap();
let ids = layer(&s, 0);
let (walks, lookups) = (vectorcraft_doc::tree_walks(), vectorcraft_doc::path_lookups());
for id in &ids {
s.execute("select.add", &json!({"ids": [id.0]})).unwrap();
}
assert!(selected(&s, &ids));
(vectorcraft_doc::tree_walks() - walks, vectorcraft_doc::path_lookups() - lookups)
}
/// Selecting objects one at a time checks and reads only the object each `select.add` adds: twice
/// as many objects take about twice as many lookups, and the tree is not walked for each one.
#[test]
fn selecting_objects_one_at_a_time_looks_up_only_the_added_objects() {
let (walks, lookups) = add_one_at_a_time(1_000);
let (more_walks, more_lookups) = add_one_at_a_time(2_000);
assert!(walks.max(more_walks) <= MOST_TREE_WALKS, "walked the tree {walks} and {more_walks} times");
assert!(more_lookups <= lookups * 5 / 2, "{lookups} lookups for 1,000 objects, {more_lookups} for 2,000");
}
+52 -4
View File
@@ -1326,11 +1326,11 @@ fn locate_layer_highlights_the_layer_holding_the_object() {
let r = run(&mut s, "layer.locate", json!({"layersOnly": true}));
assert_eq!(r, json!({"id": sub.0, "objectId": b.0, "ancestry": [layer.0, sub.0]}), "the group's sublayer");
assert_eq!(s.doc().unwrap().highlighted_rows(), vec![sub]);
assert_eq!(s.doc().unwrap().locate_reveal, Some(sub), "the Layers panel reveals the located row");
s.doc_mut().unwrap().locate_reveal = None;
assert_eq!(s.doc().unwrap().layers_reveal, Some(crate::LayersReveal::Row(sub)), "the Layers panel reveals the located row");
s.doc_mut().unwrap().layers_reveal = None;
let undo = s.doc().unwrap().history.undo.len();
run(&mut s, "layer.locate", json!({"layersOnly": true}));
assert_eq!(s.doc().unwrap().locate_reveal, Some(sub), "again for a row already highlighted");
assert_eq!(s.doc().unwrap().layers_reveal, Some(crate::LayersReveal::Row(sub)), "again for a row already highlighted");
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step");
assert_eq!(run(&mut s, "layer.locate", json!({"id": c.0, "layersOnly": true}))["id"], layer.0, "art directly in a layer");
assert_eq!(s.doc().unwrap().highlighted_rows(), vec![layer]);
@@ -1342,12 +1342,60 @@ fn locate_layer_highlights_the_layer_holding_the_object() {
for p in [json!({"id": b.0, "layersOnly": "yes"}), json!({"id": 999_999, "layersOnly": true})] {
assert!(s.execute("layer.locate", &p).is_err(), "{p}");
assert_eq!(s.doc().unwrap().highlighted_rows(), vec![g], "{p}");
assert_eq!(s.doc().unwrap().locate_reveal, Some(g), "{p}");
assert_eq!(s.doc().unwrap().layers_reveal, Some(crate::LayersReveal::Row(g)), "{p}");
}
run(&mut s, "select.none", json!({}));
assert!(s.execute("layer.locate", &json!({"layersOnly": true})).is_err(), "nothing selected");
}
/// The session asks the Layers panel to reveal what a top-level command changed: isolation, then
/// the highlighted rows, the last selected object and the current layer. An open interaction asks
/// for nothing, and a failed command changes nothing.
#[test]
fn the_layers_panel_is_asked_to_reveal_what_a_command_changed() {
use crate::LayersReveal::{Current, Row, Selected};
let mut s = session();
let (layer, sub, _, g, b, c) = tree(&mut s);
let take = |s: &mut Session| s.doc_mut().unwrap().layers_reveal.take();
take(&mut s);
run(&mut s, "layer.highlight", highlight_params([c], "set"));
take(&mut s);
run(&mut s, "layer.highlight", highlight_params([g], "set"));
assert_eq!(take(&mut s), Some(Row(g)), "a highlighted row");
// The current layer changes with the selection of art in another layer: the new selection asks
// for its object, and the panel falls back to the current layer when it does not locate it.
s.doc_mut().unwrap().active_layer = Some(sub);
run(&mut s, "select.set", json!({"ids": [c.0]}));
assert_eq!(take(&mut s), Some(Selected(c)), "a new selection wins over a new current layer");
// A new current layer alone asks for it: the highlighted row made current again.
run(&mut s, "layer.highlight", highlight_params([c], "set"));
take(&mut s);
s.doc_mut().unwrap().active_layer = Some(sub);
run(&mut s, "layer.setCurrent", json!({"id": c.0}));
assert_eq!(take(&mut s), Some(Current(layer)), "a new current layer alone");
// Within the current layer only the last selected object changes.
s.doc_mut().unwrap().active_layer = Some(sub);
run(&mut s, "select.set", json!({"ids": [b.0]}));
take(&mut s);
run(&mut s, "select.set", json!({"ids": [g.0]}));
assert_eq!(take(&mut s), Some(Selected(g)), "the last selected object");
// Isolation entered and left reveals the isolated row.
run(&mut s, "object.isolate", json!({"id": g.0}));
assert_eq!(take(&mut s), Some(Row(g)), "isolation entered");
run(&mut s, "object.exitIsolation", json!({}));
assert_eq!(take(&mut s), Some(Row(g)), "isolation left");
// A failed command asks for nothing.
assert!(s.execute("layer.locate", &json!({"id": 999_999})).is_err());
assert_eq!(take(&mut s), None);
// A command inside an open interaction asks for nothing either.
run(&mut s, "select.set", json!({"ids": [g.0]}));
take(&mut s);
s.begin_interaction("Drag").unwrap();
run(&mut s, "select.set", json!({"ids": [b.0]}));
assert_eq!(take(&mut s), None, "a preview");
s.cancel_interaction().unwrap();
}
#[test]
fn the_clipping_mask_button_acts_on_the_highlighted_group() {
let mut s = session();
+33
View File
@@ -1002,3 +1002,36 @@ fn a_double_click_on_a_corner_widget_with_a_shape_tool_asks_for_the_transform_pa
assert!(st.interaction.is_none());
assert_eq!(s.tool_id(), "rectangle");
}
/// A double-click on a corner widget of a selected live rectangle with the Selection tool asks
/// the frontend for the Transform panel, and leaves the document, its undo history, the
/// selection and the tool as they were; with Direct Selection it still opens Corners.
#[test]
fn a_double_click_on_a_corner_widget_with_the_selection_tool_asks_for_the_transform_panel() {
use vectorcraft_tools::{Mods, PointerEvent, PointerKind};
let (mut s, id) = session();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
let v = ViewInfo::default();
let st = s.doc().unwrap();
let w = vectorcraft_tools::corners::CornerWidgets::showing(&st.doc, &st.selection, v.zoom, false, true, 180.0).expect("corner widgets show");
let at = w.visible().next().expect("a widget");
let (doc, selection, steps) = (st.doc.clone(), st.selection.clone(), st.history.undo.len());
let double_click = |s: &mut Session, tool: &str| {
s.select_tool(tool, v).unwrap();
let mut asked = vec![];
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] {
asked.extend(s.pointer(&PointerEvent::new(kind, at.x, at.y).with_mods(Mods::default()), v).unwrap());
}
asked
};
assert_eq!(double_click(&mut s, "selection"), vec![UiRequest::Panel("transform".into())]);
let st = s.doc().unwrap();
assert!(*st.doc == *doc, "the document is unchanged");
assert_eq!(st.selection, selection);
assert_eq!(st.history.undo.len(), steps, "no undo step");
assert!(st.interaction.is_none());
assert_eq!(s.tool_id(), "selection");
// Direct Selection opens Corners for the corner it picked with the first click.
let asked = double_click(&mut s, "directSelection");
assert!(matches!(asked.as_slice(), [UiRequest::Dialog(k, _)] if k == vectorcraft_tools::corners::DIALOG), "{asked:?}");
}
+32
View File
@@ -4621,6 +4621,38 @@ fn locked_guides_lock_guide_paths() {
assert_eq!(selected(&s), vec![b]);
}
/// A guide path added to the selection after another object stays unselected while Lock Guides is
/// on, and is selected once it is off.
#[test]
fn a_guide_path_added_after_another_object_stays_unselected_while_guides_are_locked() {
let mut s = session();
let b = rect(&mut s, 20.0, 20.0, 10.0, 10.0);
let g = guide_path(&mut s, 0.0);
s.execute("view.guides.lock", &json!({"locked": true})).unwrap();
for id in [b, g] {
s.execute("select.add", &json!({"ids": [id.0]})).unwrap();
}
assert_eq!(selected(&s), vec![b]);
s.execute("view.guides.lock", &json!({"locked": false})).unwrap();
s.execute("select.add", &json!({"ids": [g.0]})).unwrap();
assert_eq!(selected(&s), vec![b, g]);
}
/// An id that names no object and a ruler guide's id, added to a selection after another object,
/// leave the selection as a whole new selection of the same ids would.
#[test]
fn a_missing_object_and_a_ruler_guide_added_after_another_object_stay_unselected() {
let mut s = session();
let (b, c) = (rect(&mut s, 20.0, 20.0, 10.0, 10.0), rect(&mut s, 40.0, 20.0, 10.0, 10.0));
s.execute("guide.add", &json!({"vertical": true, "pos": 100})).unwrap();
let guide = s.doc().unwrap().doc.ruler_guides()[0].id.unwrap();
s.execute("select.none", &json!({})).unwrap();
s.execute("select.add", &json!({"ids": [b.0]})).unwrap();
let missing = NodeId(u64::MAX);
s.select(|_, sel| sel.objects.extend([missing, guide, c])).unwrap();
assert_eq!(selected(&s), vec![b, c]);
}
/// A rectangle at (`x`, 0), 10 pt wide, made into a guide; nothing is selected after.
fn guide_path(s: &mut Session, x: f64) -> NodeId {
let g = rect(s, x, 0.0, 10.0, 10.0);
+41
View File
@@ -192,6 +192,47 @@ fn a_paint_the_selected_objects_do_not_share_stays_as_it_was() {
assert_eq!((s.paint.stroke.clone(), s.paint.stroke_width), (node(&s, a).appearance.stroke_paint(), 5.0), "the strokes are shared");
}
fn add(s: &mut Session, id: NodeId) {
run(s, "select.add", json!({"ids": [id.0]}));
}
/// Objects added one at a time are compared with the objects already selected: a fill and weight
/// they all share loads, one they don't stays as it was.
#[test]
fn objects_added_one_at_a_time_load_only_the_paints_all_selected_objects_share() {
let mut s = session();
let a = painted(&mut s, 20.0, "#ff0000", "#00ff00", 5.0);
let b = painted(&mut s, 120.0, "#ff0000", "#00ff00", 5.0);
let c = painted(&mut s, 220.0, "#0000ff", "#00ff00", 1.0);
let red = node(&s, a).appearance.fill_paint();
run(&mut s, "select.none", json!({}));
add(&mut s, a);
(s.paint.fill, s.paint.stroke_width) = (Paint::None, 0.5);
add(&mut s, b);
assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (red, 5.0), "a and b share them");
(s.paint.fill, s.paint.stroke_width) = (Paint::None, 0.5);
add(&mut s, c);
assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (Paint::None, 0.5), "c's differ");
}
/// An edit of the selected objects between two additions is read: the objects selected before it
/// are compared as the edit left them.
#[test]
fn an_object_added_after_an_edit_is_compared_with_the_edited_objects() {
let mut s = session();
let a = painted(&mut s, 20.0, "#ff0000", "#00ff00", 5.0);
let b = painted(&mut s, 120.0, "#ff0000", "#00ff00", 5.0);
let c = painted(&mut s, 220.0, "#0000ff", "#00ff00", 5.0);
let blue = node(&s, c).appearance.fill_paint();
run(&mut s, "select.none", json!({}));
add(&mut s, a);
add(&mut s, b);
run(&mut s, "paint.setFill", json!({"color": "#0000ff", "ids": [a.0, b.0]}));
s.paint.fill = Paint::None;
add(&mut s, c);
assert_eq!(s.paint.fill, blue, "a, b and c are all blue now");
}
#[test]
fn art_without_paint_leaves_the_proxies_as_they_were() {
let mut s = session();
+9 -2
View File
@@ -1019,8 +1019,15 @@ fn package_copies_held_postscript_only_for_a_placed_document_with_a_postscript_n
im.link.as_mut().unwrap().path = logo_ai.clone();
im.link.as_mut().unwrap().relative = None;
let key = im.key.clone();
d.images
.insert(key, vectorcraft_doc::ImageBlob { mime: "application/postscript".into(), bytes: std::sync::Arc::new(eps.to_vec()), proxy: None });
d.images.insert(
key,
vectorcraft_doc::ImageBlob {
mime: "application/postscript".into(),
bytes: std::sync::Arc::new(eps.to_vec()),
proxy: None,
file_font: Default::default(),
},
);
Ok(())
})
.unwrap();
+15
View File
@@ -967,6 +967,21 @@ fn a_locked_artboard_protects_the_art_on_it() {
assert!(!tile.is_empty() && !tile.contains(&a), "{tile:?}");
}
/// Art on a locked artboard stays unselected when `select.add` adds it after another object.
#[test]
fn art_on_a_locked_artboard_added_after_another_object_stays_unselected() {
let mut s = session();
let a = rect(&mut s);
s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 200, "height": 200})).unwrap();
let b = NodeId(s.execute("shape.rectangle", &json!({"x": 1010, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap());
s.execute("artboard.setProps", &json!({"index": 1, "locked": true})).unwrap();
s.execute("select.none", &json!({})).unwrap();
for id in [a, b] {
s.execute("select.add", &json!({"ids": [id.0]})).unwrap();
}
assert_eq!(s.doc().unwrap().selection.objects, [a]);
}
/// New art on a locked artboard stays selected and editable until the selection leaves it: a
/// second Pen click goes on the path the first one started, and pasted art moves. Once another
/// object is clicked, a click, a marquee, `select.set` and Select All pass over that art. Undo, in
+6
View File
@@ -1736,11 +1736,17 @@ fn pathfinder_options_round_trip_and_refuse_bad_values() {
assert_eq!(s.execute("prefs.get", &json!({"key": "pathfinder"})).unwrap(), set);
let mm = s.execute("object.pathfinder.options", &json!({"precision": "1 mm"})).unwrap()["precision"].as_f64().unwrap();
assert!((mm - 72.0 / 25.4).abs() < 1e-9, "a length with a unit: {mm}");
for (given, want) in [("10 pt", 10.0), ("0.25", 0.25)] {
let r = s.execute("object.pathfinder.options", &json!({"precision": given})).unwrap();
assert_eq!(r["precision"], json!(want), "{given}");
}
s.execute("object.pathfinder.options", &json!({"precision": 0.5})).unwrap();
for bad in [
json!({"precision": 0}),
json!({"precision": 11}),
json!({"precision": "x"}),
json!({"precision": "1abc"}),
json!({"precision": "0.5 extra"}),
json!({"precision": -1}),
json!({"removeRedundantPoints": "yes"}),
json!({"removeUnpainted": 1}),
+23 -17
View File
@@ -1667,21 +1667,31 @@ fn mirror_axis(s: &Session) -> vectorcraft_tools::mirror::MirrorAxis {
vectorcraft_tools::mirror::MirrorAxis::of(&st.doc, &st.selection, 1.0).unwrap()
}
/// A press on the mirror axis at `at`, as the canvas's selection widgets take it.
fn mirror_press(s: &mut Session, at: Point) -> vectorcraft_tools::mirror::MirrorDrag {
s.with_tool_context(ViewInfo::default(), |cx| vectorcraft_tools::mirror::MirrorDrag::hit(cx, at, Mods::default())).expect("a press on the axis")
}
/// The mirror axis drag `d` moved to `to`, its actions applied as the canvas's selection widgets apply them.
fn mirror_drag(s: &mut Session, d: &mut vectorcraft_tools::mirror::MirrorDrag, to: Point, mods: Mods) {
let acts = s.with_tool_context(ViewInfo::default(), |cx| d.drag(cx, to, mods));
s.apply_actions(acts).unwrap();
}
#[test]
fn mirror_axis_drag_previews_once_and_undo_redo_preserve_source() {
use vectorcraft_tools::{PointerEvent, PointerKind};
let mut s = session();
rect(&mut s, 100.0, 100.0, 60.0, 80.0);
let id = id_of(&s.execute("object.repeat.mirror", &json!({})).unwrap());
let before = node(&s, id);
let axis = mirror_axis(&s);
let v = ViewInfo::default();
s.select_tool("selection", v).unwrap();
let h = crate::tests::history(&s);
for (kind, dx) in [(PointerKind::Down, 0.0), (PointerKind::Drag, 20.0), (PointerKind::Drag, 30.0), (PointerKind::Up, 40.0)] {
s.pointer(&PointerEvent::new(kind, axis.center.x + dx, axis.center.y), v).unwrap();
let mut d = mirror_press(&mut s, axis.center);
for dx in [20.0, 30.0, 40.0] {
mirror_drag(&mut s, &mut d, axis.center + vectorcraft_geom::Vec2::new(dx, 0.0), Mods::default());
assert!(close(mirror_axis(&s).center, axis.center + vectorcraft_geom::Vec2::new(dx, 0.0)));
}
s.apply_actions(d.finish()).unwrap();
assert_eq!(crate::tests::history(&s).0, h.0 + 1);
let after = node(&s, id);
let (NodeKind::Repeat(a), NodeKind::Repeat(b)) = (&before.kind, &after.kind) else { panic!() };
@@ -1695,33 +1705,29 @@ fn mirror_axis_drag_previews_once_and_undo_redo_preserve_source() {
#[test]
fn mirror_axis_rotation_snaps_and_escape_restores_document_and_history() {
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
let mut s = session();
rect(&mut s, 100.0, 100.0, 60.0, 80.0);
let id = id_of(&s.execute("object.repeat.mirror", &json!({})).unwrap());
let v = ViewInfo::default();
s.select_tool("selection", v).unwrap();
let before = node(&s, id);
let h = crate::tests::history(&s);
let axis = mirror_axis(&s);
let end = axis.ends[1];
let destination = axis.center + vectorcraft_geom::Vec2::new(70.0, 60.0);
s.pointer(&PointerEvent::new(PointerKind::Down, end.x, end.y), v).unwrap();
let shift = Mods { shift: true, ..Default::default() };
s.pointer(&PointerEvent::new(PointerKind::Drag, destination.x, destination.y).with_mods(shift), v).unwrap();
let mut d = mirror_press(&mut s, end);
mirror_drag(&mut s, &mut d, destination, shift);
assert!((mirror_axis(&s).angle - 45.0).abs() < 1e-6);
assert_eq!(mirror_axis(&s).center, axis.center);
s.tool_key(ToolKey::Escape, Mods::default(), v).unwrap();
assert!(!s.tool_busy());
s.pointer(&PointerEvent::new(PointerKind::Up, destination.x, destination.y), v).unwrap();
s.apply_actions(d.cancel()).unwrap();
assert_eq!(node(&s, id), before);
assert_eq!(crate::tests::history(&s), h);
// A click is not an edit, and a subsequent real drag still works after cancellation.
s.pointer(&PointerEvent::new(PointerKind::Down, end.x, end.y), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, end.x, end.y), v).unwrap();
let click = mirror_press(&mut s, end).finish();
s.apply_actions(click).unwrap();
assert_eq!(crate::tests::history(&s), h);
s.pointer(&PointerEvent::new(PointerKind::Down, end.x, end.y), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, destination.x, destination.y).with_mods(shift), v).unwrap();
let mut d = mirror_press(&mut s, end);
mirror_drag(&mut s, &mut d, destination, shift);
s.apply_actions(d.finish()).unwrap();
assert!((mirror_axis(&s).angle - 45.0).abs() < 1e-6);
assert_eq!(crate::tests::history(&s).0, h.0 + 1);
}
+5 -4
View File
@@ -4,7 +4,7 @@
use serde_json::{Value, json};
use crate::Session;
use crate::cmd::fileio::pdf::DEFAULT_PRESET;
use vectorcraft_pdf::{APP, default_preset_name};
fn session() -> Session {
let mut s = Session::new();
@@ -31,14 +31,15 @@ fn built_in_presets_are_listed_and_read_only() {
let mut s = session();
let v = s.execute("pdf.preset.list", &json!({})).unwrap();
let rows = v["presets"].as_array().unwrap();
assert_eq!(rows[0]["name"], DEFAULT_PRESET);
let default = default_preset_name(APP);
assert_eq!(rows[0]["name"], default);
assert!(rows.iter().all(|r| r["builtIn"] == true && !r["description"].as_str().unwrap().is_empty()));
let row = |n: &str| rows.iter().find(|r| r["name"] == n).unwrap_or_else(|| panic!("{n}"));
for n in ["High Quality Print", "Press Quality", "Smallest File Size", "PDF/X-1a:2001", "PDF/X-3:2002", "PDF/X-4:2010"] {
assert_eq!(row(n)["builtIn"], true);
}
assert!(rows.iter().all(|r| r["supported"] == true), "every built-in standard is written");
assert_eq!(row(DEFAULT_PRESET)["settings"]["preserveEditing"], true);
assert_eq!(row(&default)["settings"]["preserveEditing"], true);
// Read-only: neither changed nor deleted, in any case.
assert!(is_bad_params(s.execute("pdf.preset.save", &json!({"name": "press quality", "compatibility": "1.4"}))));
assert!(is_bad_params(s.execute("pdf.preset.save", &json!({"name": "default"}))));
@@ -96,7 +97,7 @@ fn presets_export_and_import_round_trip() {
let r = s.execute("pdf.preset.import", &json!({"data": text})).unwrap();
assert_eq!(r["imported"], json!(["Proof", "Press Quality 2"]), "a built-in name gets a number");
assert_eq!(s.prefs.pdf_presets[0], saved[0], "the same preset comes back");
let press = vectorcraft_pdf::builtin_preset("Press Quality").unwrap();
let press = vectorcraft_pdf::builtin_preset("Press Quality", APP).unwrap();
assert_eq!(s.prefs.pdf_presets[1].settings, press.settings);
// replace: saved presets of the same names are overwritten.
let r = s.execute("pdf.preset.import", &json!({"data": text, "replace": true})).unwrap();
+4 -1
View File
@@ -999,7 +999,10 @@ fn a_placed_brush_whose_art_uses_a_renamed_image_is_copied() {
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
s.edit("Brush", |d, _| {
d.images.insert("k".into(), vectorcraft_doc::ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None });
d.images.insert(
"k".into(),
vectorcraft_doc::ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None, file_font: Default::default() },
);
let im = vectorcraft_doc::ImageObject {
key: "k".into(),
width: 2,
+233 -7
View File
@@ -182,6 +182,136 @@ fn filters_make_guides_and_locked_objects_left_unselected() {
assert_eq!(st.history.undo.len(), undo + 1);
}
/// A compound path handed back with its path as it was keeps its members, hidden and locked ones
/// included. A changed path replaces its members, and is refused while a member is hidden, locked,
/// a guide or not a path, as is turning it into a plain path.
#[test]
fn a_filter_keeps_or_replaces_a_compound_path_s_members_whole() {
use std::sync::Arc;
use vectorcraft_doc::{Appearance, Node, NodeKind};
use vectorcraft_geom::FillRule;
let mut s = session();
let compound_of = |s: &mut Session, members: Vec<Node>| {
let mut id = NodeId(0);
s.edit("Set up", |d, _| {
let n = Node::new(d.alloc_id(), NodeKind::Compound { children: members.into_iter().map(Arc::new).collect(), rule: FillRule::NonZero });
let layer = d.layers[0].id;
id = d.insert(Some(layer), usize::MAX, n).unwrap();
Ok(())
})
.unwrap();
id
};
let members = |s: &Session, id: NodeId| match &node(s, id).kind {
NodeKind::Compound { children, .. } => children.iter().map(|c| (c.id, c.visible, c.locked, c.path_data().cloned())).collect::<Vec<_>>(),
_ => Vec::new(),
};
let new_ids = |s: &mut Session| s.edit("Set up", |d, _| Ok([d.alloc_id(), d.alloc_id(), d.alloc_id(), d.alloc_id()])).unwrap();
let [a, b, c, d] = new_ids(&mut s);
let [g, h, i, j] = new_ids(&mut s);
let hidden = |id: NodeId, x: f64| {
let mut n = Node::path(id, square_at(x), Appearance::default());
n.visible = false;
n
};
let locked = |id: NodeId, x: f64| {
let mut n = Node::path(id, square_at(x), Appearance::default());
n.locked = true;
n
};
// A member with an empty subpath, which plug-in output can't hold, still counts as handed back.
let empty = Node::path(g, PathData::single(SubPath::polyline(&[], false)), Appearance::default());
let kept = compound_of(&mut s, vec![hidden(a, 40.0), locked(b, 80.0), empty]);
let plain =
compound_of(&mut s, vec![Node::path(c, square_at(120.0), Appearance::default()), Node::path(d, square_at(160.0), Appearance::default())]);
let was = members(&s, kept);
install_wat(&mut s, &tpl::module(&tpl::manifest("test.engine.compound.echo", "filter", "{}"), tpl::ECHO, "", 1));
run(&mut s, "plugin.run", json!({"id": "test.engine.compound.echo", "ids": [kept.0]}));
assert_eq!(members(&s, kept), was, "handed back as it was, the members stay as they were");
// New geometry for a compound with a hidden or a locked member, or the same geometry as a plain
// path, is refused, and the document is left alone.
let mut moved = square_at(200.0);
moved.subpaths.extend(square_at(240.0).subpaths);
let reshape = |id: &str, target: NodeId, extra: Value| {
let mut o = json!({"id": target.0, "path": moved.clone()});
o.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
tpl::returning(&tpl::manifest(id, "filter", "{}"), &json!({ "objects": [o] }).to_string())
};
let hidden_only = compound_of(&mut s, vec![hidden(h, 360.0)]);
let locked_only = compound_of(&mut s, vec![Node::path(i, square_at(360.0), Appearance::default()), locked(j, 380.0)]);
// A member that is itself a compound path, shown and unlocked but holding a hidden member: its
// geometry isn't in the input, so a new path or a plain path would drop it.
let [k, l, m, _] = new_ids(&mut s);
let inner = Node::new(k, NodeKind::Compound { children: vec![Arc::new(hidden(l, 400.0))], rule: FillRule::NonZero });
let nested = compound_of(&mut s, vec![Node::path(m, square_at(440.0), Appearance::default()), inner]);
let was_nested = node(&s, nested).clone();
run(&mut s, "plugin.run", json!({"id": "test.engine.compound.echo", "ids": [nested.0]}));
assert_eq!(node(&s, nested).kind, was_nested.kind, "handed back as it was, a nested compound member stays");
let flagged = "a hidden, locked or guide member";
for (target, why) in [(hidden_only, flagged), (locked_only, flagged), (nested, "a member that isn't a path")] {
install_wat(&mut s, &reshape("test.engine.compound.reshape", target, json!({})));
let flatten = tpl::returning(
&tpl::manifest("test.engine.compound.flatten", "filter", "{}"),
&json!({"objects": [{"id": target.0, "type": "path"}]}).to_string(),
);
install_wat(&mut s, &flatten);
let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
for id in ["test.engine.compound.reshape", "test.engine.compound.flatten"] {
let e = s.execute("plugin.run", &json!({"id": id, "ids": [target.0]})).unwrap_err().to_string();
assert!(e.contains(&format!("compound path {} has {why}", target.0)), "{id}: {e}");
assert_eq!((s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()), before, "{id}");
}
}
// Without such members, new geometry replaces the members: one per subpath, in the old members' places.
install_wat(&mut s, &reshape("test.engine.compound.reshape", plain, json!({})));
run(&mut s, "plugin.run", json!({"id": "test.engine.compound.reshape", "ids": [plain.0]}));
let now = members(&s, plain);
assert_eq!(now.iter().map(|m| m.3.clone()).collect::<Vec<_>>(), [Some(square_at(200.0)), Some(square_at(240.0))]);
assert!(now.iter().all(|m| m.1 && !m.2), "shown and unlocked members: {now:?}");
assert_eq!(now.iter().map(|m| m.0).collect::<Vec<_>>(), [c, d], "the members keep their places' ids");
// A guide member is refused the same way, unless the output sets `guide` for the whole object.
let guide_of = |s: &mut Session| {
let [e, f, ..] = new_ids(s);
let mut guide_member = Node::path(e, square_at(280.0), Appearance::default());
if let NodeKind::Path { guide, .. } = &mut guide_member.kind {
*guide = true;
}
compound_of(s, vec![guide_member, Node::path(f, square_at(320.0), Appearance::default())])
};
let guides = |s: &Session, id: NodeId| match &node(s, id).kind {
NodeKind::Compound { children, .. } => children.iter().map(|c| matches!(c.kind, NodeKind::Path { guide: true, .. })).collect::<Vec<_>>(),
_ => Vec::new(),
};
let guide = guide_of(&mut s);
install_wat(&mut s, &reshape("test.engine.compound.reshape", guide, json!({})));
let err = s.execute("plugin.run", &json!({"id": "test.engine.compound.reshape", "ids": [guide.0]})).unwrap_err().to_string();
assert!(err.contains("guide member"), "{err}");
let flatten = tpl::returning(
&tpl::manifest("test.engine.compound.flatten.unflagged", "filter", "{}"),
&json!({"objects": [{"id": guide.0, "type": "path"}]}).to_string(),
);
install_wat(&mut s, &flatten);
let err = s.execute("plugin.run", &json!({"id": "test.engine.compound.flatten.unflagged", "ids": [guide.0]})).unwrap_err().to_string();
assert!(err.contains(&format!("compound path {} has {flagged}", guide.0)), "{err}");
assert_eq!(guides(&s, guide), [true, false], "a refused flatten leaves the guide member as it was");
for (id, on) in [("test.engine.compound.unguide", false), ("test.engine.compound.reguide", true)] {
let target = guide_of(&mut s);
install_wat(&mut s, &reshape(id, target, json!({ "guide": on })));
run(&mut s, "plugin.run", json!({"id": id, "ids": [target.0]}));
assert_eq!(members(&s, target).iter().map(|m| m.3.clone()).collect::<Vec<_>>(), [Some(square_at(200.0)), Some(square_at(240.0))], "{id}");
assert_eq!(guides(&s, target), [on, on], "{id}: every new member takes the output's `guide`");
}
// Turning it into a plain path is allowed the same way when the output sets `guide`.
let target = guide_of(&mut s);
let flatten = tpl::returning(
&tpl::manifest("test.engine.compound.flatten.guide", "filter", "{}"),
&json!({"objects": [{"id": target.0, "type": "path", "guide": true}]}).to_string(),
);
install_wat(&mut s, &flatten);
run(&mut s, "plugin.run", json!({"id": "test.engine.compound.flatten.guide", "ids": [target.0]}));
assert!(matches!(node(&s, target).kind, NodeKind::Path { guide: true, .. }), "{:?}", node(&s, target).kind);
}
#[test]
fn failing_plugins_leave_the_document_and_history_alone() {
let mut s = session();
@@ -1808,6 +1938,86 @@ fn filters_keep_their_data_with_the_document() {
assert_eq!(data(&s), None);
}
/// A filter run whose output changes nothing (an echo) records no undo step, leaves a saved
/// document unmodified and the document as it was, and still selects its objects. One that changes
/// one of the objects records exactly one step, and running it again records none.
#[test]
fn a_filter_run_that_changes_nothing_records_no_undo_step() {
let mut s = session();
let a = rect(&mut s, 10.0, "#ff0000");
let b = rect(&mut s, 40.0, "#0000ff");
let echo = "test.engine.noop.echo";
install_wat(&mut s, &tpl::module(&tpl::manifest(echo, "filter", "{}"), tpl::ECHO, "", 1));
run(&mut s, "select.none", json!({}));
s.doc_mut().unwrap().mark_saved();
let (doc, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
let r = run(&mut s, "plugin.run", json!({"id": echo, "ids": [a.0, b.0]}));
assert_eq!(r["ids"], json!([a.0, b.0]));
let st = s.doc().unwrap();
assert!(std::sync::Arc::ptr_eq(&st.doc, &doc), "the document stays as it was");
assert_eq!((st.history.undo.len(), st.is_dirty()), (undo, false), "no undo step; still saved");
assert_eq!(st.selection.objects, [a, b], "its objects are selected");
// Renaming one object of the two is one undo step.
let renamer = "test.engine.noop.renamer";
let renamed = json!({"objects": [{"id": a.0, "name": "Renamed"}, {"id": b.0}]});
install_wat(&mut s, &tpl::returning(&tpl::manifest(renamer, "filter", "{}"), &renamed.to_string()));
run(&mut s, "plugin.run", json!({"id": renamer, "ids": [a.0, b.0]}));
let st = s.doc().unwrap();
assert_eq!((st.history.undo.len(), st.is_dirty()), (undo + 1, true));
assert_eq!(node(&s, a).name.as_deref(), Some("Renamed"));
// Run again, it renames nothing: no second step.
run(&mut s, "plugin.run", json!({"id": renamer, "ids": [a.0, b.0]}));
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
for id in [echo, renamer] {
run(&mut s, "plugin.remove", json!({"id": id}));
}
}
/// A filter that writes the data it already keeps with the document records no undo step; writing
/// other data, or removing it, records one, and removing data it does not keep records none.
#[test]
fn a_filter_that_keeps_the_same_data_records_no_undo_step() {
let mut s = session();
let id = rect(&mut s, 10.0, "#ff0000");
let pid = "test.engine.noop.data";
let keep = |s: &mut Session, data: Value| {
let out = json!({"objects": [{"id": id.0}], "documentData": data});
install_wat(s, &tpl::returning(&tpl::manifest(pid, "filter", "{}"), &out.to_string()));
run(s, "plugin.run", json!({"id": pid, "ids": [id.0]}));
s.doc().unwrap().history.undo.len()
};
let undo = s.doc().unwrap().history.undo.len();
assert_eq!(keep(&mut s, json!({"pen": 2})), undo + 1);
assert_eq!(keep(&mut s, json!({"pen": 2})), undo + 1, "the same data: no step");
assert_eq!(keep(&mut s, json!({"pen": 3})), undo + 2);
assert_eq!(keep(&mut s, Value::Null), undo + 3, "removed");
assert_eq!(keep(&mut s, Value::Null), undo + 3, "nothing kept to remove: no step");
assert_eq!(s.doc().unwrap().doc.plugin_data(pid), None);
run(&mut s, "plugin.remove", json!({"id": pid}));
}
/// A plug-in command whose run changes nothing records no undo step, and so does a filter or a
/// command that may call commands and hands back what it is given.
#[test]
fn a_plugin_command_that_changes_nothing_records_no_undo_step() {
let mut s = session();
rect(&mut s, 10.0, "#ff0000");
run(&mut s, "select.all", json!({}));
let undo = s.doc().unwrap().history.undo.len();
let id = "test.engine.noop.cmds";
install_wat(&mut s, &grower(id));
run(&mut s, &format!("plugin.{id}.tidy"), json!({}));
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "tidy hands back its input");
run(&mut s, "plugin.remove", json!({"id": id}));
let calling = "test.engine.noop.calling";
install_echo_calling(&mut s, calling, r#"[{"id":"same","label":"Same"}]"#);
run(&mut s, &format!("plugin.{calling}.same"), json!({}));
run(&mut s, "plugin.run", json!({"id": calling}));
assert!(!s.in_interaction());
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "an echo that may call commands");
run(&mut s, "plugin.remove", json!({"id": calling}));
}
#[test]
fn plugin_management_commands() {
let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner());
@@ -2017,6 +2227,23 @@ fn a_heavy_filter_installs_once_the_user_agrees() {
assert!(install(&mut s, DESATURATE).get("budget").is_none());
}
/// A module that carries its manifest in a `vc_manifest` custom section is inspected and installed
/// without any of its code running: its start function traps and its `vc_manifest` export loops.
#[test]
fn a_plugin_with_a_manifest_section_installs_without_running() {
let mut s = session();
let id = "test.engine.section";
let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"filter","abi":1}}"#);
let extra = r#"(func (export "vc_manifest") (result i64) (loop $l (br $l)) (i64.const 0)) (func $trap unreachable) (start $trap)"#;
let data = vectorcraft_format::base64_encode(&wat::parse_str(tpl::sectioned(&manifest, tpl::ECHO, extra, 1)).unwrap());
let inspected = run(&mut s, "plugin.inspect", json!({"dataBase64": data}));
assert_eq!(inspected["id"], id);
assert!(vectorcraft_plugins::registry::get(id).is_none(), "inspecting installs nothing");
assert_eq!(run(&mut s, "plugin.install", json!({"dataBase64": data}))["id"], id);
assert!(vectorcraft_plugins::registry::get(id).is_some());
run(&mut s, "plugin.remove", json!({"id": id}));
}
#[test]
fn invalid_install_flags_are_refused() {
let mut s = session();
@@ -5299,13 +5526,12 @@ fn deferred_move(s: &mut Session) -> NodeId {
r
}
/// The rectangle a run named `label` during [`deferred_move`] left: moved, with the interaction
/// ended and the move an undo step of its own before the run's.
fn assert_moved_once(s: &Session, r: NodeId, label: &str) {
/// The rectangle a run that hands back what it is given left during [`deferred_move`]: moved, with
/// the interaction ended and the move the last undo step, since the run changed nothing.
fn assert_moved_once(s: &Session, r: NodeId) {
assert!(!s.in_interaction());
assert_eq!(node(s, r).geometric_bounds().unwrap().x0, 17.0, "the filter was given the moved rectangle");
let labels: Vec<&str> = s.doc().unwrap().history.undo.iter().rev().take(2).map(|e| e.label.as_str()).collect();
assert_eq!(labels, [label, "Move"]);
assert_eq!(s.doc().unwrap().history.undo.last().map(|e| e.label.as_str()), Some("Move"));
}
/// With Real-time Drawing off, `plugin.run` of a filter that calls commands during a drag applies
@@ -5317,7 +5543,7 @@ fn a_filter_that_calls_commands_is_given_a_deferred_move() {
install_echo_calling(&mut s, id, "[]");
let r = deferred_move(&mut s);
run(&mut s, "plugin.run", json!({"id": id}));
assert_moved_once(&s, r, &format!("Test {id}"));
assert_moved_once(&s, r);
run(&mut s, "plugin.remove", json!({"id": id}));
}
@@ -5330,6 +5556,6 @@ fn a_plugin_command_that_calls_commands_is_given_a_deferred_move() {
install_echo_calling(&mut s, id, r#"[{"id":"same","label":"Same"}]"#);
let r = deferred_move(&mut s);
run(&mut s, &format!("plugin.{id}.same"), json!({}));
assert_moved_once(&s, r, "Same");
assert_moved_once(&s, r);
run(&mut s, "plugin.remove", json!({"id": id}));
}
+50 -31
View File
@@ -699,7 +699,8 @@ fn double_clicking_a_single_object_isolates_it() {
}
/// General › Use Precise Cursors (#394): the Pen's pointer becomes a crosshair; the Selection
/// tool's arrow stays.
/// tool's arrow stays. The canvas applies the preference to the tool's own pointer
/// (`Cursor::precise`).
#[test]
fn use_precise_cursors_makes_drawing_cursors_crosshairs() {
use vectorcraft_tools::{Cursor, Mods};
@@ -712,41 +713,31 @@ fn use_precise_cursors_makes_drawing_cursors_crosshairs() {
assert_eq!(cursor(&mut s, "pen"), Cursor::Pen);
assert_eq!(cursor(&mut s, "eyedropper"), Cursor::Eyedropper);
s.execute("prefs.set", &json!({"key": "usePreciseCursors", "value": true})).unwrap();
assert_eq!(cursor(&mut s, "pen"), Cursor::Crosshair);
assert_eq!(cursor(&mut s, "eyedropper"), Cursor::Crosshair);
assert_eq!(cursor(&mut s, "selection"), Cursor::Arrow);
assert_eq!(cursor(&mut s, "pen").precise(), Cursor::Crosshair);
assert_eq!(cursor(&mut s, "eyedropper").precise(), Cursor::Crosshair);
assert_eq!(cursor(&mut s, "selection").precise(), Cursor::Arrow);
s.execute("prefs.set", &json!({"key": "usePreciseCursors", "value": false})).unwrap();
assert_eq!(cursor(&mut s, "eyedropper"), Cursor::Eyedropper);
}
/// Caps Lock gives the drawing tools the precise crosshair while it is on, and leaves the saved
/// Use Precise Cursors preference as it was.
/// Caps Lock is reported and set through `view.capsLock`, and leaves the saved Use Precise
/// Cursors preference as it was; the canvas gives the drawing tools the crosshair while it is on.
#[test]
fn caps_lock_gives_drawing_tools_the_crosshair() {
use vectorcraft_tools::{Cursor, Mods};
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
let cursor = |s: &mut Session, tool: &str| {
s.select_tool(tool, ViewInfo::default()).unwrap();
s.cursor(vectorcraft_geom::Point::new(300.0, 300.0), Mods::default(), ViewInfo::default())
};
assert_eq!(s.execute("view.capsLock", &json!({})).unwrap(), json!({"on": false}));
assert_eq!(s.execute("view.capsLock", &json!({"on": true})).unwrap(), json!({"on": true}));
assert!(!s.prefs.use_precise_cursors, "Caps Lock leaves the preference off");
assert_eq!(cursor(&mut s, "pen"), Cursor::Crosshair);
assert_eq!(cursor(&mut s, "lasso"), Cursor::Crosshair);
assert_eq!(cursor(&mut s, "eyedropper"), Cursor::Crosshair);
assert_eq!(cursor(&mut s, "selection"), Cursor::Arrow);
assert_eq!(s.execute("view.capsLock", &json!({})).unwrap(), json!({"on": true}));
assert_eq!(s.execute("view.capsLock", &json!({"on": false})).unwrap(), json!({"on": false}));
assert_eq!(cursor(&mut s, "pen"), Cursor::Pen);
assert_eq!(cursor(&mut s, "eyedropper"), Cursor::Eyedropper);
assert!(s.execute("view.capsLock", &json!({"on": 1})).is_err());
assert_eq!(s.execute("view.capsLock", &json!({})).unwrap(), json!({"on": false}));
}
/// Use Precise Cursors changes the pointer of the tools that have one of their own: off, each shows its own
/// pointer; on, a crosshair. Every other drawing tool shows a crosshair either way, and the Type tool and the
/// Scissors over no path keep theirs.
/// pointer; on, a crosshair (the canvas applies `Cursor::precise` to it). Every other drawing tool shows a
/// crosshair either way, and the Type tool and the Scissors over no path keep theirs.
#[test]
fn use_precise_cursors_swaps_the_tools_own_pointers_for_a_crosshair() {
use vectorcraft_tools::{Cursor, Mods};
@@ -804,13 +795,13 @@ fn use_precise_cursors_swaps_the_tools_own_pointers_for_a_crosshair() {
}
s.execute("prefs.set", &json!({"key": "usePreciseCursors", "value": true})).unwrap();
for (tool, _) in own {
assert_eq!(cursor(&mut s, tool), Cursor::Crosshair, "{tool} on");
assert_eq!(cursor(&mut s, tool).precise(), Cursor::Crosshair, "{tool} on");
}
for tool in always {
assert_eq!(cursor(&mut s, tool), Cursor::Crosshair, "{tool} on");
assert_eq!(cursor(&mut s, tool).precise(), Cursor::Crosshair, "{tool} on");
}
assert_eq!(cursor(&mut s, "type"), Cursor::Text);
assert_eq!(cursor(&mut s, "scissors"), Cursor::ScissorsNotAllowed);
assert_eq!(cursor(&mut s, "type").precise(), Cursor::Text);
assert_eq!(cursor(&mut s, "scissors").precise(), Cursor::ScissorsNotAllowed);
s.execute("prefs.set", &json!({"key": "usePreciseCursors", "value": false})).unwrap();
for (tool, c) in own {
assert_eq!(cursor(&mut s, tool), c, "{tool} off again");
@@ -818,7 +809,8 @@ fn use_precise_cursors_swaps_the_tools_own_pointers_for_a_crosshair() {
}
/// With no selected path, the Smooth tool shows Not Allowed, and Use Precise Cursors leaves it so; with a
/// selected path, it shows its own pointer, or a crosshair with the preference on.
/// selected path, it shows its own pointer, or a crosshair with the preference on (the canvas applies
/// `Cursor::precise`).
#[test]
fn use_precise_cursors_keeps_the_smooth_tools_not_allowed_pointer() {
use vectorcraft_tools::{Cursor, Mods};
@@ -826,20 +818,21 @@ fn use_precise_cursors_keeps_the_smooth_tools_not_allowed_pointer() {
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
let at = vectorcraft_geom::Point::new(300.0, 300.0);
s.select_tool("smooth", ViewInfo::default()).unwrap();
let shown = |c: Cursor, precise: bool| if precise { c.precise() } else { c };
for precise in [false, true] {
s.execute("prefs.set", &json!({"key": "usePreciseCursors", "value": precise})).unwrap();
assert_eq!(s.cursor(at, Mods::default(), ViewInfo::default()), Cursor::NotAllowed, "precise {precise}");
assert_eq!(shown(s.cursor(at, Mods::default(), ViewInfo::default()), precise), Cursor::NotAllowed, "precise {precise}");
}
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
for (precise, c) in [(false, Cursor::Smooth), (true, Cursor::Crosshair)] {
s.execute("prefs.set", &json!({"key": "usePreciseCursors", "value": precise})).unwrap();
assert_eq!(s.cursor(at, Mods::default(), ViewInfo::default()), c, "precise {precise}");
assert_eq!(shown(s.cursor(at, Mods::default(), ViewInfo::default()), precise), c, "precise {precise}");
}
}
/// With Alt held while drawing, the Pencil and the Paintbrush show their closing cursors, and Use Precise Cursors
/// turns those into a crosshair too.
/// turns those into a crosshair too (the canvas applies `Cursor::precise`).
#[test]
fn alt_shows_the_pencil_and_paintbrush_closing_cursors() {
use vectorcraft_tools::{Cursor, Mods, PointerEvent, PointerKind};
@@ -853,7 +846,9 @@ fn alt_shows_the_pencil_and_paintbrush_closing_cursors() {
s.select_tool(tool, ViewInfo::default()).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Down, 250.0, 250.0), ViewInfo::default()).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 300.0, 300.0), ViewInfo::default()).unwrap();
assert_eq!(s.cursor(at, alt, ViewInfo::default()), if precise { Cursor::Crosshair } else { c }, "{tool}, precise {precise}");
let shown = s.cursor(at, alt, ViewInfo::default());
assert_eq!(shown, c, "{tool}, precise {precise}");
assert_eq!(shown.precise(), Cursor::Crosshair, "{tool}");
s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 300.0), ViewInfo::default()).unwrap();
}
}
@@ -2167,10 +2162,14 @@ fn real_time_drawing_off_still_shows_a_dragged_nine_slice_guide() {
let left = |s: &Session| s.doc().unwrap().doc.symbol_nine_slice("Box").unwrap().left;
assert_eq!(left(&s), 0.25);
let steps = s.doc().unwrap().history.undo.len();
s.pointer(&PointerEvent::new(PointerKind::Down, 125.0, 150.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 110.0, 150.0), v).unwrap();
let drag = crate::tests::symbol_nine_slice::guide_drag(
&mut s,
v,
vectorcraft_geom::Point::new(125.0, 150.0),
vectorcraft_geom::Point::new(110.0, 150.0),
);
assert!((left(&s) - 0.1).abs() < 1e-9, "the guide moves while dragged: {}", left(&s));
s.pointer(&PointerEvent::new(PointerKind::Up, 110.0, 150.0), v).unwrap();
s.apply_actions(drag.finish()).unwrap();
let d = s.doc().unwrap();
assert!((left(&s) - 0.1).abs() < 1e-9);
assert_eq!((d.history.undo.len(), d.history.undo.last().map(|e| e.label.as_str())), (steps + 1, Some("Symbol Options")));
@@ -2979,6 +2978,26 @@ fn snap_to_glyph_options_read_set_and_reset() {
assert_eq!(s.execute("view.snapToGlyph.options", &json!({})).unwrap(), all);
}
/// File Handling › Use fonts embedded in imported PDFs (`pdfImportEmbeddedFonts`, on by default)
/// reaches Open and Place as the `embeddedFonts` choice, unless a call gives its own (#4568).
#[test]
fn the_embedded_fonts_preference_reaches_the_import_options() {
use crate::cmd::fileio::LoadOptions;
let mut s = Session::new();
assert!(s.prefs.pdf_import_embedded_fonts, "on by default");
let on = s.prefs.with_pdf_font_choice(&json!({}));
assert!(LoadOptions::from_params("x", &on).unwrap().embedded_fonts);
s.execute("prefs.set", &json!({"key": "pdfImportEmbeddedFonts", "value": false})).unwrap();
let off = s.prefs.with_pdf_font_choice(&json!({"page": 2}));
assert_eq!(off["page"], 2, "the call's own params stay");
assert!(!LoadOptions::from_params("x", &off).unwrap().embedded_fonts);
assert!(!LoadOptions::from_params("x", &s.prefs.with_pdf_font_choice(&Value::Null)).unwrap().embedded_fonts);
// A call that says so wins over the preference.
let own = s.prefs.with_pdf_font_choice(&json!({"embeddedFonts": true}));
assert!(LoadOptions::from_params("x", &own).unwrap().embedded_fonts);
assert!(LoadOptions::from_params("x", &json!({"embeddedFonts": "yes"})).is_err());
}
/// Pixel Snapping Options: `view.snapToPixel.options` reads and sets While Drawing, While Moving
/// and While Scaling, all on by default, kept as the `pixelSnap` preference group; bad keys and
/// values change nothing, preferences saved without the group read it as all on, and resetting the
+30
View File
@@ -125,3 +125,33 @@ fn type_that_does_not_fit_its_frame_is_named_when_its_artboard_prints() {
let (_, v) = print_ps(&mut s, json!({"settings": {"artboards": "range", "range": "1"}}));
assert_eq!(over(&v), 0, "{v}");
}
/// Graphics › Fonts reaches the PostScript output: Subset (the default) sends each page the
/// glyphs it shows, None names the printer's font and sends none, Complete sends every glyph once
/// before the first page. PDF output notes that it embeds subsets.
#[test]
fn the_fonts_setting_chooses_how_type_is_sent() {
let mut s = session(1);
s.execute("text.create", &json!({"x": 20, "y": 100, "text": "Ab", "size": 24})).unwrap();
assert_eq!(s.execute("print.setup", &json!({})).unwrap()["settings"]["graphics"]["fonts"], "subset");
let fonts = |s: &mut Session, f: &str| print_ps(s, json!({"settings": {"graphics": {"fonts": f}}}));
let (ps, _) = print_ps(&mut s, json!({}));
let page = ps.split("%%Page: ").nth(1).unwrap();
assert_eq!(page.matches("/FontType 3 def").count(), 1, "{ps}");
assert_eq!(page.matches("> show").count(), 2, "{page}");
assert_eq!(dsc(&ps, "DocumentSuppliedResources"), ["font VCft0.0"]);
let (ps, v) = fonts(&mut s, "none");
assert!(!ps.contains("FontType") && !ps.contains("%%BeginResource"), "{ps}");
assert_eq!(dsc(&ps, "DocumentNeededResources").len(), 1, "{ps}");
assert!(v["warnings"].to_string().contains("the printer needs the font"), "{v}");
let (ps, _) = fonts(&mut s, "complete");
let (head, pages) = ps.split_once("%%EndSetup").unwrap();
assert!(head.contains("/FontType 3 def") && !pages.contains("FontType") && pages.contains("> show"), "{ps}");
let (ps, _) = fonts(&mut s, "subset");
assert_eq!(ps.split("%%Page: ").nth(1).unwrap().matches("/FontType 3 def").count(), 1);
// PDF output embeds subsets whatever the setting, and says so.
for (f, noted) in [("none", true), ("subset", false), ("complete", true)] {
let v = s.execute("file.print", &json!({"settings": {"graphics": {"fonts": f}}})).unwrap();
assert_eq!(v["warnings"].to_string().contains("PDF print embeds subsets"), noted, "{f}: {v}");
}
}
+27
View File
@@ -794,6 +794,33 @@ fn a_hovered_arc_shows_the_protractor_with_the_rubber_band() {
}
}
/// The two arms of a cross centered on `c` among the overlays.
fn crosses_at(o: &[Overlay], c: Point) -> usize {
o.iter().filter(|o| matches!(o, Overlay::Line { a, b, .. } if a.midpoint(*b).distance(c) < 1e-9)).count()
}
/// While a half circle from (200, 100) to (300, 100) is dragged, or is the piece the next click
/// adds, the tool shows a cross at its center, (250, 100); while a line is dragged, it shows none.
#[test]
fn an_arc_shows_a_cross_at_its_center() {
let mut s = session();
quick_pen(&mut s);
let center = pt(250.0, 100.0);
for (action, arms) in [("line", 0), ("sharpArc", 2)] {
key(&mut s, ToolKey::Escape);
s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "line"})).unwrap();
click(&mut s, 100.0, 100.0);
click(&mut s, 200.0, 100.0);
s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": action})).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Move, 300.0, 100.0), view()).unwrap();
assert_eq!(crosses_at(&s.overlays(view()), center), arms, "hovering, {action}");
s.pointer(&PointerEvent::new(PointerKind::Down, 280.0, 150.0), view()).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 300.0, 100.0), view()).unwrap();
assert_eq!(crosses_at(&s.overlays(view()), center), arms, "dragging, {action}");
s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 100.0), view()).unwrap();
}
}
/// With Measurement Labels on, hovering after the path's last point shows the distance label
/// beside the pointer; with them off, no label shows.
#[test]
+138
View File
@@ -69,6 +69,77 @@ fn native_recovery_copies_leave_out_the_pdf() {
assert_eq!(vectorcraft_format::load(&bytes).unwrap().node_count(), s.doc().unwrap().doc.node_count());
}
const RECOVERY_FONT_FAMILY: &str = "Recovery Carried Font Regression";
const RECOVERY_FONT_BYTES: &[u8] = include_bytes!("../../../../assets/fonts/Inter-Regular.ttf");
fn carried_font_copy() -> (Arc<MemoryStore>, vectorcraft_doc::NodeId) {
use vectorcraft_doc::{CharStyle, FILE_FONT_MIME, FileFont, FileFonts, ImageBlob, Node, NodeKind, TextObject};
let (mut s, store) = session();
let doc = Arc::make_mut(&mut s.doc_mut().unwrap().doc);
doc.images.insert("recovered-font".into(), ImageBlob::new(FILE_FONT_MIME, RECOVERY_FONT_BYTES.to_vec()));
// An uninstalled family ensures the fixture must be read from the recovered resource.
let style = CharStyle { font_family: RECOVERY_FONT_FAMILY.into(), size: 20.0, ..Default::default() };
let mut text = TextObject::point(kurbo::Point::new(10.0, 40.0), "x", style);
text.file_fonts = Some(Box::new(FileFonts::new(
vec![FileFont { family: RECOVERY_FONT_FAMILY.into(), style: "Regular".into(), key: "recovered-font".into() }],
"x",
)));
let id = doc.alloc_id();
doc.insert(Some(doc.layers[0].id), usize::MAX, Node::new(id, NodeKind::Text(Box::new(text)))).unwrap();
let saved = s.execute("file.recovery.save", &json!({})).unwrap();
let file = saved["saved"][0]["file"].as_str().unwrap();
let lean = vectorcraft_format::load(&store.read(&format!("{file}.vectorcraft")).unwrap()).unwrap();
assert!(lean.images.is_empty(), "the font travels in the recovery store, not the document entry");
drop(s);
(store, id)
}
#[test]
fn recovered_carried_fonts_bind_after_their_resources_are_restored() {
use vectorcraft_doc::NodeKind;
use vectorcraft_text::FontDb;
let (store, id) = carried_font_copy();
let mut s = relaunch(&store);
let reply = s.execute("file.recovery.restore", &json!({})).unwrap();
assert_eq!(reply["restored"].as_array().unwrap().len(), 1, "{reply}");
assert!(reply["failed"].as_array().unwrap().is_empty(), "{reply}");
assert!(reply["restored"][0]["warnings"].as_array().unwrap().is_empty(), "{reply}");
let doc = &s.doc().unwrap().doc;
assert_eq!(doc.images["recovered-font"].bytes.as_slice(), RECOVERY_FONT_BYTES);
let NodeKind::Text(text) = &doc.node(id).unwrap().kind else { panic!("text") };
let db = FontDb::global();
let laid = vectorcraft_text::layout(db, text);
assert_eq!(laid.glyphs.len(), 1);
let face = db.face_by_id(laid.glyphs[0].font_id).unwrap();
assert_eq!(face.file_data(), RECOVERY_FONT_BYTES, "layout uses the recovered font's exact bytes");
}
#[test]
fn recovered_missing_or_corrupt_carried_fonts_report_the_actual_refusal() {
for missing in [true, false] {
let (store, id) = carried_font_copy();
let blob = store.list().unwrap().into_iter().find(|name| name.ends_with(".blob")).unwrap();
if missing {
store.remove(&blob).unwrap();
} else {
store.write(&blob, b"not a font").unwrap();
}
let mut s = relaunch(&store);
let reply = s.execute("file.recovery.restore", &json!({})).unwrap();
assert_eq!(reply["restored"].as_array().unwrap().len(), 1, "{reply}");
assert!(reply["failed"].as_array().unwrap().is_empty(), "{reply}");
let warnings = reply["restored"][0]["warnings"].as_array().unwrap();
assert!(
warnings.iter().any(|note| note.as_str().is_some_and(|note| note.contains(RECOVERY_FONT_FAMILY) && note.contains("substitute"))),
"missing={missing}: {reply}"
);
let vectorcraft_doc::NodeKind::Text(text) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("text") };
assert!(vectorcraft_text::FontDb::global().file_faces(text).is_empty(), "missing={missing}");
}
}
#[test]
fn restored_recovery_copies_keep_the_original_pdf_preference() {
let dir = crate::tests_links::Folder::new("recovered-pdf-preference");
@@ -1714,3 +1785,70 @@ fn a_crash_between_a_copys_document_and_its_details_keeps_every_image() {
assert_eq!(images_of(&s), images, "first copy: {first}");
}
}
/// A crash between writing a copy's document and its details, after a script's command changed
/// the document since the last copy, restores the document as one a script opened.
#[test]
fn a_crash_between_a_copys_document_and_its_details_keeps_a_scripts_change() {
let store = Arc::new(MemoryStore::default());
let mut s = session_in(&store);
s.execute("file.recovery.save", &json!({})).unwrap();
let source = "vc.run('shape.ellipse', {x: 80, y: 20, width: 20, height: 20});";
s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap();
assert!(s.doc().unwrap().by_script.is_some(), "the script's command changed the document");
let doc = vectorcraft_doc::Document::clone(&s.doc().unwrap().doc);
s.recovery.set_store(Arc::new(DiesAfterDocument { inner: store.clone(), dead: Default::default() }));
assert!(s.execute("file.recovery.save", &json!({})).is_err(), "the details weren't written");
drop(s);
let mut s = relaunch(&store);
assert_eq!(restored(s.execute("file.recovery.restore", &json!({})).unwrap()), 1);
let count = |d: &vectorcraft_doc::Document| d.layers.iter().map(|l| l.count()).sum::<usize>();
assert_eq!(count(&s.doc().unwrap().doc), count(&doc), "the new document is in");
assert!(s.doc().unwrap().by_script.is_some(), "restored as a document a script opened");
}
/// A crash while a restore moves a copy into the app's own area leaves no copy that a later
/// restore opens without its details: a script's change is kept.
#[test]
fn a_crash_while_a_copy_is_restored_keeps_a_scripts_change() {
let store = Arc::new(MemoryStore::default());
let mut s = session_in(&store);
let source = "vc.run('shape.ellipse', {x: 80, y: 20, width: 20, height: 20});";
s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap();
s.execute("file.recovery.save", &json!({})).unwrap();
drop(s);
let mut s = Session::new();
s.recovery.set_store(Arc::new(DiesAfterDocument { inner: store.clone(), dead: Default::default() }));
let _ = s.execute("file.recovery.restore", &json!({}));
drop(s);
let mut s = relaunch(&store);
assert!(restored(s.execute("file.recovery.restore", &json!({})).unwrap()) >= 1);
for st in s.documents().iter().filter(|st| st.recovered) {
assert!(st.by_script.is_some(), "every restored copy keeps the script's change: {}", st.title());
}
}
/// A copy whose details entry is missing or can't be parsed restores as a document a script
/// opened, and so does the copy that restore writes, after a later crash; a valid details entry
/// without the script's mark restores as the person left it.
#[test]
fn a_copy_without_readable_details_restores_as_a_scripts_document() {
let cases: [Option<&[u8]>; 3] = [Some(b"{ not json"), None, Some(b"{}")];
for details in cases {
let store = Arc::new(MemoryStore::default());
let mut s = session_in(&store);
let r = s.execute("file.recovery.save", &json!({})).unwrap();
let entry = format!("{}.json", r["saved"][0]["file"].as_str().unwrap());
drop(s);
match details {
Some(bytes) => store.write(&entry, bytes).unwrap(),
None => store.remove(&entry).unwrap(),
}
let by_script = details != Some(b"{}".as_slice());
for round in 1..=2 {
let mut s = relaunch(&store);
assert_eq!(restored(s.execute("file.recovery.restore", &json!({})).unwrap()), 1, "{details:?}, restore {round}");
assert_eq!(s.doc().unwrap().by_script.is_some(), by_script, "{details:?}, restore {round}");
}
}
}
+34 -4
View File
@@ -1,5 +1,5 @@
//! The `$` object's members besides `$.write` and `$.writeln`, the global `localize` and
//! `toSource`, and what of them one run keeps to itself.
//! The `$` object's members besides `$.write` and `$.writeln`, the global `localize`, `toSource`
//! and `UnitValue`, and what of them one run keeps to itself.
use std::time::Duration;
@@ -63,7 +63,7 @@ fn each_member_has_its_value() {
("$.memCache", json!(0)),
("$.os", json!(os)),
("$.screens.length", json!(0)),
("$.stack", json!("[global]@t.js:1\n")),
("$.stack", json!("[t.js]\n[global]@t.js:1\n")),
("$.strict", json!(false)),
("$.version", json!(version)),
("typeof $.getenv + typeof $.setenv + typeof $.sleep", json!("functionfunctionfunction")),
@@ -140,6 +140,15 @@ fn to_source_writes_plain_data() {
assert!(thrown(&mut s, "toSource(vc)").starts_with("TypeError"), "a host object is not plain data");
}
#[test]
fn unit_values_convert_and_calculate_in_a_run() {
let mut s = Session::new();
assert_eq!(value(&mut s, "UnitValue('1 in').as('pt')"), json!(72));
assert_eq!(value(&mut s, "String(new UnitValue(1, 'm') + new UnitValue(10, 'cm'))"), json!("1.1 m"));
assert_eq!(value(&mut s, "[UnitValue(98, 'cm') < UnitValue(1, 'm'), UnitValue(98, 'cm') == 98]"), json!([true, true]));
assert!(thrown(&mut s, "UnitValue(1, 'in').as('furlong')").starts_with("Error"));
}
#[test]
fn getenv_reads_only_its_names_and_setenv_changes_only_the_run() {
let mut s = Session::new();
@@ -165,10 +174,31 @@ fn getenv_reads_only_its_names_and_setenv_changes_only_the_run() {
fn error_line_and_stack_follow_the_running_code() {
let mut s = Session::new();
let source = "try { null.x; } catch (e) {}\nfunction where() {\n return [$.line, $.stack, $.error instanceof TypeError];\n}\nvc.log(where());";
assert_eq!(logged(&mut s, source)[0], json!([3, "[global]@t.js:5\nwhere@t.js:3\n", true]));
assert_eq!(logged(&mut s, source)[0], json!([3, "[t.js]\n[global]@t.js:5\nwhere@t.js:3\n", true]));
assert_eq!(value(&mut s, "$.error"), json!(null), "each run starts without one");
}
/// `$.stack`'s first line is the run's name in square brackets, the name `script.run` reports,
/// in a function as at the top level.
#[test]
fn the_stack_starts_with_the_runs_name() {
let mut s = Session::new();
let first = |s: &mut Session, params: Value| {
let r = s.execute("script.run", &params).unwrap_or_else(|e| panic!("{params}: {e}"));
let line = r["log"][0].as_str().unwrap_or_default().to_string();
(line, r["name"].clone())
};
let top = "vc.log($.stack.split('\\n')[0]);";
let (line, name) = first(&mut s, json!({"source": top, "name": "Marks.jsx"}));
assert_eq!((line.as_str(), name), ("[Marks.jsx]", json!("Marks.jsx")));
let inner = "function f() { return $.stack.split('\\n')[0]; }\nvc.log(f());";
assert_eq!(first(&mut s, json!({"source": inner, "name": "Marks.jsx"})).0, "[Marks.jsx]");
let (line, name) = first(&mut s, json!({"source": format!("#script \"Named\"\n{top}")}));
assert_eq!((line.as_str(), name), ("[Named]", json!("Named")), "a #script line names the run");
let (line, name) = first(&mut s, json!({"source": top}));
assert_eq!(format!("[{}]", name.as_str().unwrap_or_default()), line, "a run given no name");
}
#[test]
fn sleep_waits_between_slices_until_its_time_has_passed() {
let mut s = Session::new();
+9 -5
View File
@@ -298,19 +298,23 @@ fn the_line_and_the_stack_of_code_an_earlier_run_kept_are_at_that_runs_files() {
};
let r = call(&mut s, "vc.log(fromMain());");
assert_eq!(r[0], 4, "{r}");
assert_eq!(short_stack(&r[1]), "[global]@caller.js:3\nfromMain@def.jsx:5\nfromInclude@inc.jsxinc:4\n");
assert_eq!(short_stack(&call(&mut s, "vc.log(fromText());")), "[global]@caller.js:3\nfromText@t.js:4\n");
assert_eq!(
short_stack(&r[1]),
"[caller.js]\n[global]@caller.js:3\nfromMain@def.jsx:5\nfromInclude@inc.jsxinc:4\n",
"the first line names the run that is calling, not the one that defined the function"
);
assert_eq!(short_stack(&call(&mut s, "vc.log(fromText());")), "[caller.js]\n[global]@caller.js:3\nfromText@t.js:4\n");
assert_eq!(call(&mut s, "vc.log(eval('\\n\\n$.line'));"), 3);
assert_eq!(call(&mut s, "vc.log(eval('\\n$.stack'));"), "[global]@caller.js:3\n[global]@[eval]:2\n");
assert_eq!(call(&mut s, "vc.log(eval('\\n$.stack'));"), "[caller.js]\n[global]@caller.js:3\n[global]@[eval]:2\n");
let r = call(&mut s, "vc.log(new Function('\\nreturn $.stack;')());");
assert_eq!(r, "[global]@caller.js:3\n[anonymous]@[eval]:4\n", "the line of the function source `Function` compiles");
assert_eq!(r, "[caller.js]\n[global]@caller.js:3\n[anonymous]@[eval]:4\n", "the line of the function source `Function` compiles");
// A map larger than the budget is not kept.
TEST_KEPT_MAP_BYTES.with(|b| b.set(Some(1)));
let lost = run(&mut s, "#targetengine e\n\n\nfunction lost() {\n return [$.line, $.stack];\n}");
let r = lost.map(|_| call(&mut s, "vc.log(lost());"));
TEST_KEPT_MAP_BYTES.with(|b| b.set(None));
let r = r.unwrap();
assert_eq!(r, json!([0, "[global]@caller.js:3\nlost@[unknown]:0\n"]));
assert_eq!(r, json!([0, "[caller.js]\n[global]@caller.js:3\nlost@[unknown]:0\n"]));
let _ = std::fs::remove_dir_all(base);
}
Loaded 100 of 1193 files, more files were not shown because too many files have changed in this diff. Show more