Merge main into fix/the-liquify-warning-s-tool-name-and-object-kinds

This commit is contained in:
dotCooCoo
2026-11-14 20:48:34 -08:00
118 changed files with 4731 additions and 311 deletions
+1 -1
View File
@@ -64,7 +64,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Assign Profile…",
["Edit"],
None,
"{rgb?: profile|null, cmyk?: profile|null} tag the document with profiles (color numbers are kept; null: the working space). Colors then show and convert through the profiles assigned; the working spaces stay as edit.colorSettings set them → {rgb, cmyk}",
"{rgb?: profile|null, cmyk?: profile|null} tag the document with profiles (color numbers are kept; null: no profile, Don't Color Manage This Document, so colors show through the working space; the working space's name: that profile stays assigned when the working space changes). Colors then show and convert through the profiles assigned; the working spaces stay as edit.colorSettings set them → {rgb, cmyk}",
has_doc,
assign_profile
),
+1 -1
View File
@@ -92,7 +92,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Eraser",
[],
None,
"{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1), size?: pt (10), sizeMode?: \"fixed\" (default) | \"pressure\" (Eraser Tool Options' Size set to Pressure: the tip is size − sizeVariation across where the pen presses lightest and size + sizeVariation where it presses hardest, as path.blob), sizeVariation?: pt (0), angle?: ° (0: the tip's long axis counter-clockwise from level), roundness?: % (100, kept within 1–100)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one",
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation ° clockwise, as path.freehand), size?: pt (10), angle?: ° (0: the tip's long axis counter-clockwise from level), roundness?: % (100, kept within 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0 or more, default 0)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An unknown mode, or a variation below 0 or past its range, is an error and erases nothing",
has_doc,
erase_region
),
+107 -5
View File
@@ -1,11 +1,14 @@
use super::common::{
dist_to_polyline, fill_targets, ids_json, path_mut, path_of, points_param, poly_bounds, pressure_region, replace_with_pieces, samples_param,
sibling_with, size_pressure, target_paths, usize_opt,
PenRecord, Sample, dist_to_polyline, fill_targets, ids_json, path_mut, path_of, points_param, poly_bounds, pressure_region, replace_with_pieces,
samples_param, sibling_with, size_pressure, target_paths, usize_opt,
};
use super::{
Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, ParamCurve, PathData, Point, Result, Session, SubPath,
Value, bad, eraser_area, eraser_tip, f64_or, fill_contains, json, number_or, object_param, po,
Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, Paint, ParamCurve, PathData, Point, Result, Session,
SubPath, Value, Vec2, bad, eraser_area, eraser_tip, f64_or, fill_contains, json, number_or, object_param, po,
};
use vectorcraft_brush::{Brush, BrushKind, Calligraphic, Variation};
use vectorcraft_doc::StrokeLayer;
use vectorcraft_tools::draw2::MIN_BRUSH_SIZE;
/// Split a filled path into connected pieces (each outer contour with its holes).
pub(in super::super) fn components(pd: &PathData) -> Vec<PathData> {
@@ -278,7 +281,11 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result<Value> {
}
let angle = number_or(p, "angle", 0.0, C)?;
let roundness = number_or(p, "roundness", 100.0, C)?;
let pressure = size_pressure(p, &samples, C)?;
let vary = eraser_variations(p, C)?;
if varies_beyond_size_pressure(&vary) {
return erase_varied(s, &samples, [angle, roundness, size], vary);
}
let pressure = if vary[2].0 == Variation::Pressure { size_pressure(p, &samples, C)? } else { None };
let pts: Vec<Point> = samples.into_iter().map(|s| s.pt).collect();
let r = size / 2.0;
// The tip's short axis (its narrowest with Pressure): an open path is sampled at least every half of it.
@@ -318,6 +325,101 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result<Value> {
apply_plan(s, "Eraser", plan)
}
/// The variation modes `path.eraseRegion` takes for each of `angleMode`, `roundnessMode` and
/// `sizeMode`.
const ERASER_MODES: &str = "\"fixed\", \"random\", \"pressure\", \"tilt\", \"bearing\" or \"rotation\"";
/// Eraser Tool Options' Angle, Roundness and Size variations: for each of angle (`angleMode` with
/// `angleVariation` in degrees, at most 180), roundness (`roundnessMode` with `roundnessVariation`
/// in percent, at most 100) and size (`sizeMode` with `sizeVariation` in points), its mode and how
/// far it varies either way. A mode left out or null is Fixed, and a variation left out or null
/// is 0; any other mode, or a variation that is negative or past its most, is refused.
fn eraser_variations(p: &Value, cmd: &str) -> Result<[(Variation, f64); 3]> {
const KEYS: [(&str, &str, f64); 3] =
[("angleMode", "angleVariation", 180.0), ("roundnessMode", "roundnessVariation", 100.0), ("sizeMode", "sizeVariation", f64::INFINITY)];
let mut out = [(Variation::Fixed, 0.0); 3];
for (slot, (mode_key, var_key, most)) in out.iter_mut().zip(KEYS) {
let mode = match p.get(mode_key).filter(|v| !v.is_null()) {
None => Variation::Fixed,
Some(Value::String(id)) => Variation::parse(id).ok_or_else(|| bad(cmd, format!("{mode_key} is one of {ERASER_MODES}, not `{id}`")))?,
Some(other) => return Err(bad(cmd, format!("{mode_key} is one of {ERASER_MODES}, not {other}"))),
};
let variation = number_or(p, var_key, 0.0, cmd)?;
if !(variation.is_finite() && variation >= 0.0) {
return Err(bad(cmd, format!("{var_key} must be 0 or more")));
}
if variation > most {
return Err(bad(cmd, format!("{var_key} must be at most {most}")));
}
*slot = (mode, variation);
}
Ok(out)
}
/// Does any of the Eraser's Angle, Roundness and Size vary with something other than Size on
/// Pressure? A mode whose variation is 0 does not vary.
fn varies_beyond_size_pressure(vary: &[(Variation, f64); 3]) -> bool {
vary.iter().enumerate().any(|(i, (mode, v))| *v > 0.0 && *mode != Variation::Fixed && !(i == 2 && *mode == Variation::Pressure))
}
/// `path.eraseRegion` with its tip varying along the drag ([`eraser_variations`]): the area the
/// tip covers is swept as a Calligraphic brush nib of the same angle, roundness, size, modes and
/// variations, with what the pen recorded along the drag. Random draws one value for the drag
/// and the pen modes follow the pen at each point; a drag without that recording (a mouse) takes
/// the value itself. `tip`: the angle, roundness and size.
fn erase_varied(s: &mut Session, samples: &[Sample], tip: [f64; 3], vary: [(Variation, f64); 3]) -> Result<Value> {
let [angle, roundness, size] = tip;
let mut pts: Vec<Point> = samples.iter().map(|s| s.pt).collect();
// A press without a drag is a dab: a sweep needs some length.
if let [only] = pts[..] {
pts.push(only + Vec2::new(0.01, 0.0));
}
// A nib's size is kept within 1296 pt and the stroke's width scales it: a larger tip is swept
// at a fraction of its size on a stroke as many times wider.
let [(am, av), (rm, rv), (sm, sv)] = vary;
let sv = if sm == Variation::Fixed { 0.0 } else { sv };
let scale = ((size + sv) / Calligraphic::RANGES[2].1).max(1.0);
let nib = Calligraphic {
angle,
roundness: roundness.clamp(1.0, 100.0),
size: size / scale,
variation: [av, rv, sv / scale],
modes: Some([am, rm, sm]),
};
let brush = Brush { name: "Eraser".into(), kind: BrushKind::Calligraphic(nib) };
let mut stroke = StrokeLayer::new(Paint::None, scale);
PenRecord::of_samples(samples).write(&mut stroke);
let spine = SubPath::polyline(&pts, false);
let st = s.doc()?;
let pieces = vectorcraft_brush::stroke_pieces(&st.doc, &brush, &PathData::single(spine).to_bezpath(), &stroke);
let areas: Vec<PathData> = pieces.iter().filter_map(|n| n.path_data().cloned()).collect();
if areas.is_empty() {
return Ok(json!({ "ids": [] }));
}
let region =
po::try_unite_all(&areas.iter().map(|a| (a, FillRule::NonZero)).collect::<Vec<_>>()).map_err(|e| EngineError::Other(e.to_string()))?;
let bp = region.to_bezpath();
// The narrowest the tip gets across: an open path is sampled at least every half of it.
let low = |i: usize| match vary[i] {
(Variation::Fixed, _) => tip[i],
(_, v) => tip[i] - v,
};
let short = low(2).max(MIN_BRUSH_SIZE) * low(1).clamp(1.0, 100.0) / 100.0;
let reach = (size + sv) / 2.0;
let mut plan: Vec<(NodeId, Vec<PathData>)> = vec![];
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, reach))? {
if pd.is_closed() {
if po::area(&po::boolean(&pd, rule, &region, FillRule::NonZero, BoolOp::Intersect), FillRule::NonZero) <= 1e-6 {
continue;
}
plan.push((id, components(&po::boolean(&pd, rule, &region, FillRule::NonZero, BoolOp::Difference))));
} else if let Some(pieces) = erase_outline(&pd, short / 2.0, &|q| fill_contains(&bp, FillRule::NonZero, q)) {
plan.push((id, pieces));
}
}
apply_plan(s, "Eraser", plan)
}
fn apply_plan(s: &mut Session, label: &str, plan: Vec<(NodeId, Vec<PathData>)>) -> Result<Value> {
if plan.is_empty() {
return Ok(json!({ "ids": [] }));
+1
View File
@@ -91,6 +91,7 @@ pub(crate) use mesh3d::{mesh_file_names, mesh_files};
pub use naming::{NameParts as FileNameParts, parse_date as parse_file_date, render as render_file_name};
pub(crate) use native::preview_png;
pub use native::with_compression_pref;
pub(crate) use pdfimport::opened_page_document;
pub use pdfimport::{LoadOptions, page_document};
pub(crate) use save::job_for;
pub(crate) use save::save as save_document;
File diff suppressed because one or more lines are too long
+160 -8
View File
@@ -8,7 +8,7 @@ use std::sync::Arc;
use serde::Deserialize;
use serde::de::DeserializeOwned;
use serde_json::Value;
use vectorcraft_doc::{Artboard, Document, Node, NodeKind, SymbolOverride};
use vectorcraft_doc::{Artboard, Document, Node, NodeKind, SYMBOL_SIZES, SymbolOverride};
use vectorcraft_geom::Rect;
use vectorcraft_render::AntiAlias;
use vectorcraft_render::encode::jpeg::{self, JpegOptions};
@@ -454,7 +454,12 @@ pub fn export_art_bounds(doc: &Document, format: &str) -> Option<Rect> {
/// make the same appearance changes to its art are measured on a copy of the symbol of their own,
/// in which each object is judged with those changes ([`as_drawn`]); the objects taken out of
/// a dynamic symbol's art leave empty groups in their places, by which instances find the objects
/// they change.
/// they change. Each copy keeps its symbol's 9-slice guides and natural size. An instance whose art
/// goes through 9-slice guides at any depth is measured as its art placed through them
/// ([`placed_instances`]), with the objects `left_out` picks hidden after placing: the guides cut
/// the box of the whole art. Where an instance stays one, the art of a symbol with 9-slice guides,
/// and of the symbols whose instances are in that art at any depth ([`sliced_art`]), is measured
/// whole.
fn bounds_without(doc: &Document, left_out: &dyn Fn(&Node) -> bool) -> Option<Rect> {
// The symbols instances show (the first of each name).
let mut names = HashSet::new();
@@ -492,12 +497,15 @@ fn bounds_without(doc: &Document, left_out: &dyn Fn(&Node) -> bool) -> Option<Re
let Some(s) = d.symbols.get(*i).cloned() else { continue };
for (k, c) in sets.get(s.name.as_str()).into_iter().flatten().flatten().enumerate() {
copies.push((d.symbols.len(), c.as_slice()));
d.symbols.push(vectorcraft_doc::Symbol { name: format!("{}\u{0}{k}", s.name), ..s.clone() });
let name = format!("{}\u{0}{k}", s.name);
copy_placement(&mut d, &s.name, &name);
d.symbols.push(vectorcraft_doc::Symbol { name, ..s.clone() });
}
}
d
});
let src = remapped_doc.as_ref().unwrap_or(doc);
let whole = sliced_art(src);
// The symbols to measure with the changes their instances make (`None` for a static symbol),
// without the dynamic symbols measured whole.
let entries: Vec<(usize, Option<&[&SymbolOverride]>)> = shown
@@ -517,11 +525,25 @@ fn bounds_without(doc: &Document, left_out: &dyn Fn(&Node) -> bool) -> Option<Re
}
let left_out =
&|n: &Node| left_out(n) || matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if empty.contains(symbol.as_str()) && !has_effects(n));
// The instances whose art goes through 9-slice guides, at any depth, are measured as their art
// placed by those guides without the objects `left_out` picks, and without a clip group that
// holds only such objects.
let layers = hidden_nodes(&src.layers, left_out);
let placing = holding(src, &whole);
let layers = if placing.is_empty() {
layers
} else {
let picked = &|n: &Node| {
left_out(n) || matches!(n.kind, NodeKind::Group { clip: true, .. }) && all_left_out(n, left_out, &empty, None, &mut Vec::new())
};
let mut budget = 0;
let from = layers.as_deref().unwrap_or(&src.layers);
Some(from.iter().map(|l| placed_instances(src, l, &placing, picked, &mut budget, 0).unwrap_or_else(|| l.clone())).collect())
};
let symbols: Vec<(usize, Arc<Node>)> = entries
.iter()
.filter_map(|(i, c)| {
let s = src.symbols.get(*i).filter(|s| !empty.contains(s.name.as_str()))?;
let s = src.symbols.get(*i).filter(|s| !empty.contains(s.name.as_str()) && !whole.contains(s.name.as_str()))?;
without_nodes(&s.art, left_out, *c, &mut Vec::new()).map(|art| (*i, art))
})
.collect();
@@ -540,6 +562,135 @@ fn bounds_without(doc: &Document, left_out: &dyn Fn(&Node) -> bool) -> Option<Re
vectorcraft_render::encode::art_bounds(&d)
}
/// Give symbol `to` of `d` the 9-slice guides and the natural size that symbol `from` has.
fn copy_placement(d: &mut Document, from: &str, to: &str) {
if let Some(guides) = d.symbol_nine_slice(from) {
d.set_symbol_nine_slice(to, Some(guides));
}
if let Some(size) = d.unknown.get(SYMBOL_SIZES).and_then(|m| m.get(from)).cloned()
&& let Some(sizes) = d.unknown.get_mut(SYMBOL_SIZES).and_then(Value::as_object_mut)
{
sizes.insert(to.to_string(), size);
}
}
/// The names of the symbols of `doc` with 9-slice guides, and of the symbols whose instances are in
/// the art of those at any depth.
fn sliced_art(doc: &Document) -> HashSet<&str> {
let mut arts: HashMap<&str, &Arc<Node>> = HashMap::new();
for s in &doc.symbols {
arts.entry(s.name.as_str()).or_insert(&s.art);
}
let mut todo: Vec<&str> = arts.keys().copied().filter(|name| doc.symbol_nine_slice(name).is_some()).collect();
let mut found = HashSet::new();
while let Some(name) = todo.pop() {
if !found.insert(name) {
continue;
}
if let Some(&art) = arts.get(name) {
art.walk(&mut |n| {
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind {
todo.push(symbol.as_str());
}
});
}
}
found
}
/// The names of the symbols of `doc` in `sliced`, and of the symbols whose art holds an instance of
/// one of those at any depth.
fn holding<'a>(doc: &'a Document, sliced: &HashSet<&'a str>) -> HashSet<&'a str> {
let mut held_by: HashMap<&str, Vec<&str>> = HashMap::new();
let mut seen = HashSet::new();
for s in doc.symbols.iter().filter(|s| seen.insert(s.name.as_str())) {
s.art.walk(&mut |n| {
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind {
held_by.entry(symbol.as_str()).or_default().push(s.name.as_str());
}
});
}
let mut found = HashSet::new();
let mut todo: Vec<&str> = sliced.iter().copied().collect();
while let Some(name) = todo.pop() {
if found.insert(name) {
todo.extend(held_by.get(name).into_iter().flatten().copied());
}
}
found
}
/// The most instances deep [`placed_instances`] places symbol art.
const MAX_PLACED_DEPTH: usize = 32;
/// `n` with each instance of the `placing` symbols in it, and in its layers and groups at any depth,
/// made a group with the instance's appearance that holds the instance's art (with its changes and
/// stain) as `doc` places it, through the symbol's 9-slice guides when it has them, without the
/// objects `picked` picks ([`without_nodes`]; hidden when it picks the whole art); `None` when `n`
/// holds no such instance, or is hidden. An instance on a perspective grid, one
/// [`MAX_PLACED_DEPTH`] instances deep, one in another kind of object (a blend, for example), and
/// one whose art would take the objects placed in all (`budget`) past
/// [`vectorcraft_doc::MAX_SYMBOL_NODES`] stay instances.
/// Their symbols' art is measured whole, as taking objects out of it would change the box the
/// guides cut, and the page can come out larger than the plot.
fn placed_instances(
doc: &Document,
n: &Arc<Node>,
placing: &HashSet<&str>,
picked: &dyn Fn(&Node) -> bool,
budget: &mut u64,
depth: usize,
) -> Option<Arc<Node>> {
// Hidden art is not plotted, and placing it would take from the budget of the art that is.
if !n.visible {
return None;
}
match &n.kind {
NodeKind::SymbolInstance { symbol, xf } => {
if !placing.contains(symbol.as_str()) || depth >= MAX_PLACED_DEPTH || n.projection().is_some() {
return None;
}
let sym = doc.symbols.iter().find(|s| s.name == *symbol)?;
let art = vectorcraft_doc::symbol_overrides::instance_art(&sym.art, n);
let most = doc.symbol_slice_map(symbol, *xf).map_or(art.count_with_masks() as u64, |m| m.most_placed(&art, doc));
if budget.saturating_add(most) > vectorcraft_doc::MAX_SYMBOL_NODES {
return None;
}
let art = Arc::new(doc.place_symbol_art(symbol, &art, *xf)?);
*budget = budget.saturating_add(art.count_with_masks() as u64);
let art = placed_instances(doc, &art, placing, picked, budget, depth + 1).unwrap_or(art);
let art = if picked(&art) {
let mut hidden = (*art).clone();
hidden.visible = false;
Arc::new(hidden)
} else {
without_nodes(&art, picked, None, &mut Vec::new()).unwrap_or(art)
};
let mut g = (**n).clone();
g.kind = NodeKind::Group { children: vec![art], clip: false };
Some(Arc::new(g))
}
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => {
let mut out: Option<Vec<Arc<Node>>> = None;
for (i, c) in children.iter().enumerate() {
if let Some(new) = placed_instances(doc, c, placing, picked, budget, depth)
&& let Some(slot) = out.get_or_insert_with(|| children.clone()).get_mut(i)
{
*slot = new;
}
}
out.map(|c| {
let mut m = (**n).clone();
if let Some(children) = m.children_mut() {
*children = c;
}
Arc::new(m)
})
}
_ => None,
}
}
/// The appearance changes instance `n` makes to its symbol's art, without those that change nothing.
fn own_changes(n: &Node) -> Vec<&SymbolOverride> {
n.extras().symbol_overrides.iter().filter(|o| !o.is_empty()).collect()
@@ -600,9 +751,10 @@ fn all_left_out(n: &Node, left_out: &dyn Fn(&Node) -> bool, empty: &HashSet<&str
/// Add the sets of appearance changes that the instances in `n` and its subtree make to the art of
/// the symbols `sets` names, each set once, and those of the instances in the art of the symbols the
/// instances show (`walked`, the symbols already looked in). The instances that `left_out` picks or
/// that are in an object it picks are left out, and with `hidden` (in a layer) the hidden ones and
/// those in a hidden object. A symbol with more than [`MAX_ART_COPIES`] sets gets `None`.
/// instances show (`walked`, the symbols already looked in). With `hidden` (in a layer), the
/// instances that are hidden or that `left_out` picks, and those in such an object, are left out.
/// In symbol art every instance counts, since an instance of the symbol can change the objects
/// that hold it. A symbol with more than [`MAX_ART_COPIES`] sets gets `None`.
fn drawn_changes<'a>(
doc: &'a Document,
n: &'a Node,
@@ -611,7 +763,7 @@ fn drawn_changes<'a>(
walked: &mut HashSet<&'a str>,
sets: &mut HashMap<&'a str, Option<Vec<Vec<&'a SymbolOverride>>>>,
) {
if hidden && !n.visible || left_out(n) {
if hidden && (!n.visible || left_out(n)) {
return;
}
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind {
File diff suppressed because one or more lines are too long
+58 -15
View File
@@ -205,7 +205,7 @@ pub fn page_document(bytes: &[u8], page: usize, o: &LoadOptions) -> Result<(Docu
}
/// [`page_document`] of `opened`, the PDF `bytes` already read.
fn opened_page_document(bytes: &[u8], opened: &vectorcraft_pdf::Opened, page: usize, o: &LoadOptions) -> Result<(Document, Vec<String>)> {
pub(crate) fn opened_page_document(bytes: &[u8], opened: &vectorcraft_pdf::Opened, page: usize, o: &LoadOptions) -> Result<(Document, Vec<String>)> {
vectorcraft_pdf::import_opened(bytes, opened, &page_options(page, o)).map(|r| (r.document, r.warnings)).map_err(err)
}
@@ -217,8 +217,11 @@ fn page_options(page: usize, o: &LoadOptions) -> ImportOptions {
/// `document.open` with `linkPages`: the pages `o` picks of the PDF (or PDF-compatible `.ai` or
/// `.ait`) `name`, read from `path`, as a document holding one placed document per page, linked to
/// that page of the file as File › Place with Link places one ([`document::source`]). Each page
/// gets an artboard of its `o.crop` box (its art's bounds for `bounding`), in a row from the left
/// with the gap a PDF's artboards open with, and a layer named after the page. The document opens
/// gets an artboard of its `o.crop` box (its art's bounds for `bounding`, a blank page's crop box;
/// a PDF-compatible `.ai` asked for its crop box gets its trim box, as it opens), in a row from the
/// left with the gap a PDF's artboards open with, and a layer named after the page. On its trim box,
/// a page shows its bleed box round the artboard, and the document's bleed is the pages' bleed (the
/// widest on each side); the artboards are then the gap apart plus the bleed on both sides. The document opens
/// in CMYK when most of the pages read in CMYK, unless `o.color_mode` names a mode. Refused without a
/// path, for any other file, with a password (a linked page is read again without one), with
/// `textAs: outlines` (a linked page shows the file's own type) and for a file over
@@ -239,12 +242,16 @@ pub(super) fn linked_pages(name: &str, bytes: &[u8], path: Option<&str>, o: &Loa
if bytes.len() > document::MAX_FILE {
return Err(bad(C, format!("linkPages: `{file}` is over {} MB", document::MAX_FILE >> 20)));
}
let count = vectorcraft_pdf::open_pdf(bytes, None).map_err(err)?.page_count();
// The file is read once: every page is read from it.
let opened = vectorcraft_pdf::open_pdf(bytes, None).map_err(err)?;
let count = opened.page_count();
let picked = match &o.pages {
None => (0..count).collect(),
Some(range) => parse_range(range, count).map_err(|e| err(format!("pages: {e}")))?,
};
let bounding = o.crop == CropTo::Bounding;
// A PDF-compatible `.ai` asked for its crop box opens on its trim boxes ([`LoadOptions::import_options`]).
let crop = if o.crop == CropTo::Crop && opened.has_illustrator_data() { CropTo::Trim } else { o.crop };
let mut doc = Document::new(1.0, 1.0);
let board = doc.artboards.first().cloned().ok_or_else(|| err("a new document has no artboard"))?;
doc.artboards.clear();
@@ -253,14 +260,55 @@ pub(super) fn linked_pages(name: &str, bytes: &[u8], path: Option<&str>, o: &Loa
let gap = ImportOptions::default().artboard_gap;
// Every page's object keeps the same one copy of the file.
let shared = Arc::new(bytes.to_vec());
let (mut x, mut warnings, mut cmyk_pages) = (0.0, Vec::<String>::new(), 0);
for (i, &index) in picked.iter().enumerate() {
// The file is hashed once for all its pages.
let hash = link.hash.clone().unwrap_or_else(|| vectorcraft_doc::links::hash_bytes(bytes));
let (mut warnings, mut cmyk_pages) = (Vec::<String>::new(), 0);
// Each page as read, with its bleed (top, bottom, left, right). The pages are laid out once
// the document's bleed is known.
let mut read_pages = Vec::with_capacity(picked.len());
for &index in &picked {
let page = index as u32 + 1;
let s = document::shared_source(name, &shared, Some(path), page, bounding, document::page_box(o.crop), C)?;
let file_once = document::SharedFile { bytes: &shared, hash: &hash, opened: &opened };
// On its trim box, a page shows its bleed box, the artboard on the trim box inside it, so
// the art in the bleed shows and prints as bleed.
let bleed = if crop == CropTo::Trim { opened.page_bleed(index) } else { None };
let page_box = if bleed.is_some() { vectorcraft_doc::PageBox::Bleed } else { document::page_box(crop) };
let read = |bounding| document::shared_source(name, file_once, Some(path), page, bounding, page_box, C);
// A blank page has no art's bounds: it keeps its crop box, as opening it as art does.
let (mut s, bounding) = match read(bounding) {
Err(e) if bounding && e.to_string().contains("has no art to place") => (read(false)?, false),
s => (s?, bounding),
};
// A page that is only a placeholder (a `.ai` saved without PDF compatibility) shows the
// file's editing data, not a page of the file.
if s.editing_data {
return Err(bad(C, format!("linkPages: `{file}` isn't a PDF or a PDF-compatible .ai file")));
}
cmyk_pages += usize::from(s.color_mode == ColorMode::Cmyk);
// The document's bleed is the widest of the pages' on each side.
let sides = bleed.unwrap_or_default();
for (side, b) in doc.setup.bleed.iter_mut().zip(sides) {
*side = side.max(b.min(vectorcraft_doc::setup::MAX_BLEED));
}
for w in std::mem::take(&mut s.warnings) {
if !warnings.contains(&w) {
warnings.push(w);
}
}
read_pages.push((page, s, bounding, sides));
}
// Each artboard is the gap from the one before plus the bleed on both sides of it: the
// document's bleed, which export adds round every artboard, or a page's own bleed box where it
// reaches farther. Neither page then shows or exports the other's art.
let [_, _, doc_left, doc_right] = doc.setup.bleed;
let mut x = 0.0;
for (i, (page, s, bounding, [top, bottom, left, right])) in read_pages.into_iter().enumerate() {
if i > 0 {
x += doc_left.max(left);
}
let mut node = document::node(&mut doc, &s, LinkInfo { page: Some(page), ..link.clone() }, bounding);
if let NodeKind::PlacedDocument(p) = &mut node.kind {
p.xf = Affine::translate((x, 0.0));
p.xf = Affine::translate((x - left, -top));
}
node.name = Some(file.clone());
let mut layer = Node::layer(doc.alloc_id(), &format!("Page {page}"), LayerColor::Preset((i % 27) as u8));
@@ -268,14 +316,9 @@ pub(super) fn linked_pages(name: &str, bytes: &[u8], path: Option<&str>, o: &Loa
children.push(Arc::new(node));
}
doc.layers.push(Arc::new(layer));
let rect = Rect::new(x, 0.0, x + s.frame.width(), s.frame.height());
let rect = Rect::new(x, 0.0, x + s.frame.width() - left - right, s.frame.height() - top - bottom);
doc.artboards.push(Artboard { id: i as u32 + 1, name: format!("Artboard {}", i + 1), rect, ..board.clone() });
x = rect.x1 + gap;
for w in s.warnings {
if !warnings.contains(&w) {
warnings.push(w);
}
}
x = rect.x1 + doc_right.max(right) + gap;
}
// Pages painted mostly in CMYK read as CMYK documents, as opening them as art does: the
// document opens in CMYK (with the CMYK default swatches) when most of its pages do.
@@ -1160,6 +1160,91 @@ fn an_ai_file_saved_without_its_pdf_part_places_from_its_editing_data() {
assert!(e.contains("placeholder"), "{e}");
}
/// `document.open` with `linkPages` refuses a `.ai` saved without PDF compatibility, whose page is
/// only a placeholder, and opens a PDF-compatible one.
#[test]
fn link_pages_refuses_an_ai_file_saved_without_its_pdf_part() {
let d = std::env::temp_dir().join(format!("vc-ailinkpages-{}", std::process::id()));
std::fs::create_dir_all(&d).unwrap();
let file = |name: &str, page: &str| {
let path = d.join(name);
std::fs::write(&path, ai::ai(&compressed(&ai::sample_data()), page)).unwrap();
path.to_string_lossy().to_string()
};
let (plain, compatible) = (file("plain.ai", PLACEHOLDER), file("compatible.ai", "0 g 10 10 40 40 re f"));
let mut s = Session::new();
let e = s.execute("document.open", &json!({"path": plain, "linkPages": true})).unwrap_err().to_string();
assert!(e.contains("isn't a PDF or a PDF-compatible .ai file"), "{e}");
assert!(s.documents().is_empty(), "nothing opened");
s.execute("document.open", &json!({"path": compatible, "linkPages": true})).unwrap();
assert!(s.doc().unwrap().doc.has_placed());
let _ = std::fs::remove_dir_all(&d);
}
/// `document.open` with `linkPages` opens a PDF-compatible `.ai` asked for its crop box on its trim
/// box, as it opens as art, showing its bleed box round the artboard, which is the document's bleed.
#[test]
fn link_pages_open_an_ai_file_on_its_trim_box_with_its_bleed() {
let d = std::env::temp_dir().join(format!("vc-ailinkpagestrim-{}", std::process::id()));
std::fs::create_dir_all(&d).unwrap();
let path = d.join("trimmed.ai");
let boxes = "/TrimBox [10 10 190 90] /BleedBox [4 2 196 98]";
std::fs::write(&path, ai::ai_with(&compressed(&ai::sample_data()), "0 g 10 10 40 40 re f", boxes)).unwrap();
let path = path.to_string_lossy().to_string();
let mut s = Session::new();
s.execute("document.open", &json!({"path": path, "linkPages": true})).unwrap();
let doc = &s.doc().unwrap().doc;
let board = doc.artboards[0].rect;
assert_eq!((board.width(), board.height()), (180.0, 80.0), "the trim box");
assert_eq!(doc.setup.bleed, [8.0, 8.0, 6.0, 6.0], "top, bottom, left, right");
// The page shows its bleed box, so the art in the bleed is kept.
let placed = doc.layers[0].children().unwrap()[0].clone();
let NodeKind::PlacedDocument(p) = &placed.kind else { panic!("{:?}", placed.kind) };
assert_eq!((p.width, p.height, p.page_box), (192.0, 96.0, vectorcraft_doc::PageBox::Bleed));
assert_eq!(p.xf.translation(), vectorcraft_geom::Vec2::new(-6.0, -8.0), "the trim box on the artboard");
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn link_pages_on_their_trim_boxes_keep_the_bleed_between_the_artboards() {
// Two 100 pt trim boxes: the first with 60 pt of bleed on each side, the second with 80 pt on
// its left, more than the largest document bleed (72 pt).
let entries = format!("/PieceInfo << /Illustrator << /Private << /AIPrivateData1 {} 0 R /NumBlock 1 >> >> >>", first_extra(2));
let first = PdfPage {
bleed: Some([0.0, 0.0, 220.0, 220.0]),
trim: Some([60.0, 60.0, 160.0, 160.0]),
entries,
..PdfPage::new(220.0, 220.0, "0 g 0 0 220 220 re f")
};
let second = PdfPage {
bleed: Some([0.0, 0.0, 240.0, 220.0]),
trim: Some([80.0, 60.0, 180.0, 160.0]),
..PdfPage::new(240.0, 220.0, "0 g 0 0 240 220 re f")
};
let d = std::env::temp_dir().join(format!("vc-ailinkpagesgap-{}", std::process::id()));
std::fs::create_dir_all(&d).unwrap();
let path = d.join("pages.ai");
std::fs::write(&path, pdf_with(&[first, second], &["<< /Length 4 >>\nstream\ndata\nendstream"], None)).unwrap();
let path = path.to_string_lossy().to_string();
let mut s = Session::new();
s.execute("document.open", &json!({"path": path, "linkPages": true})).unwrap();
let doc = &s.doc().unwrap().doc;
assert_eq!(doc.setup.bleed, [60.0, 60.0, 72.0, 60.0], "top, bottom, left, right");
// The first page's bleed ends at 160; the second's starts 36 pt later, 80 pt left of its trim box.
let boards: Vec<(f64, f64)> = doc.artboards.iter().map(|a| (a.rect.x0, a.rect.x1)).collect();
assert_eq!(boards, [(0.0, 100.0), (276.0, 376.0)]);
let shown: Vec<f64> = doc
.layers
.iter()
.map(|l| match &l.children().unwrap()[0].kind {
NodeKind::PlacedDocument(p) => p.xf.translation().x,
k => panic!("{k:?}"),
})
.collect();
assert_eq!(shown, [-60.0, 196.0], "each page's bleed box round its artboard");
let _ = std::fs::remove_dir_all(&d);
}
/// A page of text alone, as text-only art has in its PDF part: no path is painted.
const TEXT_ART: &str = "BT /F1 36 Tf 10 40 Td (Text only) Tj ET";
+146
View File
@@ -338,6 +338,152 @@ fn a_plot_of_the_arts_bounds_leaves_out_images_in_dynamic_symbol_art() {
assert!(e.contains("no visible art"), "{e}");
}
/// A rectangle filled black, or one that paints nothing.
fn plot_rect(d: &mut vectorcraft_doc::Document, r: vectorcraft_geom::Rect, painted: bool) -> std::sync::Arc<vectorcraft_doc::Node> {
use vectorcraft_color::{Color, Paint};
let fill = if painted { Paint::solid(Color::BLACK) } else { Paint::None };
let appearance = vectorcraft_doc::Appearance::basic(fill, Paint::None, 0.0);
std::sync::Arc::new(vectorcraft_doc::Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(r), appearance))
}
/// An instance of symbol `symbol` placed by `xf`.
fn plot_instance(d: &mut vectorcraft_doc::Document, symbol: &str, xf: vectorcraft_geom::Affine) -> vectorcraft_doc::Node {
vectorcraft_doc::Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: symbol.into(), xf })
}
/// Symbol `name` holding `art` in a group.
fn plot_symbol(d: &mut vectorcraft_doc::Document, name: &str, art: Vec<std::sync::Arc<vectorcraft_doc::Node>>, dynamic: bool) {
let group = vectorcraft_doc::Node::group(d.alloc_id(), art);
d.symbols.push(vectorcraft_doc::Symbol { dynamic, name: name.into(), art: std::sync::Arc::new(group) });
}
/// Puts `n` on the first layer of `d`.
fn plot_on_layer(d: &mut vectorcraft_doc::Document, n: vectorcraft_doc::Node) {
std::sync::Arc::make_mut(&mut d.layers[0]).children_mut().unwrap().push(std::sync::Arc::new(n));
}
/// The art of a symbol with 9-slice guides, static or dynamic, is placed whole and measured
/// without what the plot leaves out: a frame that paints nothing sets where the guides place the
/// painted art inside it, and is not measured itself.
#[test]
fn a_plot_of_the_arts_bounds_places_9_slice_symbol_art_by_all_of_it() {
use vectorcraft_geom::{Affine, Rect};
// Static and dynamic, and with the instance's fill staining the art.
for (dynamic, stained) in [(false, false), (true, false), (false, true)] {
let mut d = vectorcraft_doc::Document::new(400.0, 400.0);
let frame = plot_rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), false);
let square = plot_rect(&mut d, Rect::new(40.0, 40.0, 60.0, 60.0), true);
plot_symbol(&mut d, "Panel", vec![frame, square], dynamic);
d.set_symbol_nine_slice("Panel", Some(vectorcraft_doc::SymbolNineSlice::default()));
let mut wide = plot_instance(&mut d, "Panel", Affine::scale_non_uniform(2.0, 1.0));
if stained {
let red = vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0));
wide.appearance = vectorcraft_doc::Appearance::basic(red, vectorcraft_color::Paint::None, 0.0).into();
}
plot_on_layer(&mut d, wide);
// Scaled 2 times across, the middle column maps x to 3x - 50: the square draws from x 70
// to 130.
let b = super::export_art_bounds(&d, "hpgl").unwrap();
let exact = [(b.x0, 70.0), (b.y0, 40.0), (b.x1, 130.0), (b.y1, 60.0)].iter().all(|(a, e)| (a - e).abs() < 1e-6);
assert!(exact, "dynamic: {dynamic}, stained: {stained}, {b:?}");
}
}
/// In art placed through 9-slice guides, a group with a fill of its own keeps the path it paints,
/// which paints nothing by itself.
#[test]
fn a_plot_of_the_arts_bounds_keeps_what_a_group_paints_in_9_slice_symbol_art() {
use vectorcraft_geom::{Affine, Rect};
let mut d = vectorcraft_doc::Document::new(400.0, 400.0);
let frame = plot_rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), false);
let bare = plot_rect(&mut d, Rect::new(40.0, 40.0, 60.0, 60.0), false);
let mut group = vectorcraft_doc::Node::group(d.alloc_id(), vec![bare]);
let black = vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK);
group.appearance = vectorcraft_doc::Appearance::basic(black, vectorcraft_color::Paint::None, 0.0).into();
plot_symbol(&mut d, "Panel", vec![frame, std::sync::Arc::new(group)], false);
d.set_symbol_nine_slice("Panel", Some(vectorcraft_doc::SymbolNineSlice::default()));
let wide = plot_instance(&mut d, "Panel", Affine::scale_non_uniform(2.0, 1.0));
plot_on_layer(&mut d, wide);
let b = super::export_art_bounds(&d, "hpgl").expect("the group's path is plotted");
let exact = [(b.x0, 70.0), (b.y0, 40.0), (b.x1, 130.0), (b.y1, 60.0)].iter().all(|(a, e)| (a - e).abs() < 1e-6);
assert!(exact, "{b:?}");
}
/// A symbol without guides in the art of a symbol with 9-slice guides is measured without what the
/// plot leaves out, in the placed art and in an instance of its own.
#[test]
fn a_plot_of_the_arts_bounds_leaves_out_unplotted_art_of_symbols_in_9_slice_art() {
use vectorcraft_geom::{Affine, Rect};
let mut d = vectorcraft_doc::Document::new(400.0, 400.0);
let far = plot_rect(&mut d, Rect::new(45.0, -500.0, 55.0, -480.0), false);
let dot = plot_rect(&mut d, Rect::new(45.0, 45.0, 55.0, 55.0), true);
plot_symbol(&mut d, "Dot", vec![far, dot], false);
let frame = plot_rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), false);
let inner = std::sync::Arc::new(plot_instance(&mut d, "Dot", Affine::IDENTITY));
plot_symbol(&mut d, "Panel", vec![frame, inner], false);
d.set_symbol_nine_slice("Panel", Some(vectorcraft_doc::SymbolNineSlice::default()));
let wide = plot_instance(&mut d, "Panel", Affine::scale_non_uniform(2.0, 1.0));
plot_on_layer(&mut d, wide);
let near = |b: Rect, e: [f64; 4]| [b.x0, b.y0, b.x1, b.y1].iter().zip(e).all(|(a, e)| (a - e).abs() < 1e-6);
// The dot's box is in the middle column, which maps x to 3x - 50.
let b = super::export_art_bounds(&d, "hpgl").unwrap();
assert!(near(b, [85.0, 45.0, 115.0, 55.0]), "{b:?}");
let own = plot_instance(&mut d, "Dot", Affine::translate((200.0, 0.0)));
plot_on_layer(&mut d, own);
let b = super::export_art_bounds(&d, "hpgl").unwrap();
assert!(near(b, [85.0, 45.0, 255.0, 55.0]), "{b:?}");
}
/// The copy of a dynamic symbol that an instance's changes are measured on keeps the symbol's
/// 9-slice guides.
#[test]
fn a_plot_of_the_arts_bounds_measures_changed_9_slice_instances_by_their_guides() {
use vectorcraft_geom::{Affine, Rect};
let mut d = vectorcraft_doc::Document::new(400.0, 400.0);
let bar = plot_rect(&mut d, Rect::new(10.0, 40.0, 70.0, 60.0), true);
plot_symbol(&mut d, "Bar", vec![bar], false);
let frame = plot_rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), false);
let inner = std::sync::Arc::new(plot_instance(&mut d, "Bar", Affine::IDENTITY));
plot_symbol(&mut d, "Panel", vec![frame, inner], true);
d.set_symbol_nine_slice("Panel", Some(vectorcraft_doc::SymbolNineSlice::default()));
let mut wide = plot_instance(&mut d, "Panel", Affine::scale_non_uniform(2.0, 1.0));
wide.extras_mut().symbol_overrides =
vec![vectorcraft_doc::SymbolOverride { path: vec![0], fill: Some(vectorcraft_color::Paint::None), ..Default::default() }];
plot_on_layer(&mut d, wide);
// The bar crosses the left guide and is placed by the middle column's map, x to 3x - 50: it
// draws from x -20 to 160.
let b = super::export_art_bounds(&d, "hpgl").unwrap();
let exact = |b: Rect| [(b.x0, -20.0), (b.y0, 40.0), (b.x1, 160.0), (b.y1, 60.0)].iter().all(|(a, e)| (a - e).abs() < 1e-6);
assert!(exact(b), "{b:?}");
// The same instance in the art of a symbol without guides.
let wide = std::sync::Arc::make_mut(&mut d.layers[0]).children_mut().unwrap().pop().unwrap();
plot_symbol(&mut d, "Holder", vec![wide], false);
let holder = plot_instance(&mut d, "Holder", Affine::IDENTITY);
plot_on_layer(&mut d, holder);
let b = super::export_art_bounds(&d, "hpgl").unwrap();
assert!(exact(b), "{b:?}");
}
/// An instance in a dynamic symbol's art, in a group at 0% opacity that an instance of the symbol
/// brings back to full opacity, is measured with the paint it gives its own symbol's art.
#[test]
fn a_plot_of_the_arts_bounds_measures_instances_that_an_instance_brings_back() {
use vectorcraft_geom::{Affine, Rect};
let mut d = vectorcraft_doc::Document::new(400.0, 400.0);
let bare = plot_rect(&mut d, Rect::new(300.0, 300.0, 320.0, 320.0), false);
plot_symbol(&mut d, "Inner", vec![bare], true);
let mut inner = plot_instance(&mut d, "Inner", Affine::IDENTITY);
let black = vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK);
inner.extras_mut().symbol_overrides = vec![vectorcraft_doc::SymbolOverride { path: vec![0], fill: Some(black), ..Default::default() }];
plot_symbol(&mut d, "Outer", vec![std::sync::Arc::new(inner)], true);
std::sync::Arc::make_mut(&mut d.symbols[1].art).opacity = 0.0;
let mut outer = plot_instance(&mut d, "Outer", Affine::IDENTITY);
outer.extras_mut().symbol_overrides = vec![vectorcraft_doc::SymbolOverride { path: vec![], opacity: Some(1.0), ..Default::default() }];
plot_on_layer(&mut d, outer);
let b = super::export_art_bounds(&d, "hpgl").expect("the painted rectangle is plotted");
assert!((b.x0 - 300.0).abs() < 1e-6 && (b.x1 - 320.0).abs() < 1e-6, "{b:?}");
}
/// A placed image with a Vector Halftone effect is measured when the effect makes dots, and left
/// out when it would take more cells than the effect makes.
#[test]
@@ -158,6 +158,9 @@ fn apply_transform_moving_guides(
}
None => ids.clone(),
};
// Pattern editing with Move Tile with Art: the tile art's bounds before a move.
let moves_only = c[0] == 1.0 && c[1] == 0.0 && c[2] == 0.0 && c[3] == 1.0;
let tile_art = if objects && !copy && moves_only { crate::cmd::patterncmds::tile_art_bounds(d) } else { None };
// Transforms don't move nodes in the tree, so reuse the paths found for the no-copy
// case; copies and a settled typing session need paths from the edited document.
let paths = if reindex { d.index_paths(targets.iter().copied()) } else { paths };
@@ -172,6 +175,10 @@ fn apply_transform_moving_guides(
for id in &targets {
super::pixelgrid::keep_compound_aligned(d, *id, sc);
}
// Moving all of the tile art moves the tile as far.
if let Some(before) = tile_art {
crate::cmd::patterncmds::move_tile_with_art(d, &targets, before);
}
}
if with_guides && (delta.x != 0.0 || delta.y != 0.0) {
for i in sel.guides.clone() {
File diff suppressed because one or more lines are too long
+64 -8
View File
@@ -78,7 +78,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Pattern Options",
["Window", "Pattern Options"],
None,
"{name? (default: the pattern being edited), newName? (trimmed; blank: the name is kept), tileType?, brickOffset?, width?, height?, hSpacing?, vSpacing?, sizeTileToArt?: bool, overlap?: {h: left|right, v: top|bottom}, copies?: 3|5|7|9, dimCopies?: %, showTileEdge?: bool, showSwatchBounds?: bool (outline the part of the tiling the swatch repeats, dashed)}",
"{name? (default: the pattern being edited), newName? (trimmed; blank: the name is kept), tileType?, brickOffset?, width?, height?, hSpacing?, vSpacing?, sizeTileToArt?: bool, moveTileWithArt?: bool (in pattern editing mode, a move of all of the tile art moves the tile with it; off for a new pattern), overlap?: {h: left|right, v: top|bottom}, copies?: 3|5|7|9, dimCopies?: %, showTileEdge?: bool, showSwatchBounds?: bool (outline the part of the tiling the swatch repeats, dashed)}",
has_doc,
pattern_options
),
@@ -530,7 +530,7 @@ fn pattern_options(s: &mut Session, p: &Value) -> Result<Value> {
let cur = s.doc()?.doc.pattern(&name).cloned().ok_or_else(|| bad(C, format!("no pattern `{name}`")))?;
let tt = tile_type_param(p, C, cur.tile_type)?;
check_numbers(p, &["width", "height", "hSpacing", "vSpacing", "copies", "dimCopies"], C)?;
check_switches(p, &["sizeTileToArt", "showTileEdge", "showSwatchBounds"], C)?;
check_switches(p, &["sizeTileToArt", "moveTileWithArt", "showTileEdge", "showSwatchBounds"], C)?;
let num = |k: &str| p.get(k).and_then(Value::as_f64);
for k in ["width", "height"] {
if num(k).is_some_and(|v| !(v.is_finite() && v > 0.0)) {
@@ -560,11 +560,11 @@ fn pattern_options(s: &mut Session, p: &Value) -> Result<Value> {
};
let edit_layer = editing(s).filter(|e| e.pattern == name).map(|e| e.layer);
let out_name = new_name.clone().unwrap_or(name.clone());
s.edit("Pattern Options", |d, _| {
// While editing, the tile art is the edit layer's.
let live_art: Option<Vec<Arc<Node>>> =
edit_layer.and_then(|l| d.node(l)).and_then(|l| l.children()).map(|ch| ch.iter().filter(|c| !c.is_ruler_guide()).cloned().collect());
let def = d.pattern_mut(&name).ok_or_else(|| EngineError::Other("pattern missing".into()))?;
// While editing, the tile art is the edit layer's.
let live_art = |d: &Document| -> Option<Vec<Arc<Node>>> {
edit_layer.and_then(|l| d.node(l)).and_then(|l| l.children()).map(|ch| ch.iter().filter(|c| !c.is_ruler_guide()).cloned().collect())
};
let apply = |def: &mut PatternDef, live_art: Option<Vec<Arc<Node>>>| {
def.tile_type = tt;
def.overlap = overlap;
if let Some(v) = num("hSpacing") {
@@ -576,6 +576,9 @@ fn pattern_options(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(v) = p.get("sizeTileToArt").and_then(Value::as_bool) {
def.size_tile_to_art = v;
}
if let Some(v) = p.get("moveTileWithArt").and_then(Value::as_bool) {
def.move_tile_with_art = v;
}
if let Some(v) = num("copies") {
def.copies = (v as u32).clamp(1, 15) | 1;
}
@@ -590,13 +593,24 @@ fn pattern_options(s: &mut Session, p: &Value) -> Result<Value> {
}
if def.size_tile_to_art {
let saved = std::mem::take(&mut def.art);
def.art = live_art.clone().unwrap_or_else(|| saved.clone());
def.art = live_art.unwrap_or_else(|| saved.clone());
def.fit_tile_to_art();
def.art = saved;
} else if num("width").is_some() || num("height").is_some() {
let c = def.tile.center();
def.tile = Rect::from_center_size(c, (num("width").unwrap_or(def.tile.width()), num("height").unwrap_or(def.tile.height())));
}
};
// Options that change nothing leave the document and its undo history as they are.
let mut next = cur.clone();
apply(&mut next, live_art(&s.doc()?.doc));
if next == cur && new_name.is_none() {
return Ok(json!({ "name": out_name }));
}
s.edit("Pattern Options", |d, _| {
let live = live_art(d);
let def = d.pattern_mut(&name).ok_or_else(|| EngineError::Other("pattern missing".into()))?;
apply(def, live);
if let Some(nn) = &new_name {
def.name = nn.clone();
rename_pattern_uses(d, &name, nn);
@@ -609,6 +623,47 @@ fn pattern_options(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "name": out_name }))
}
/// The tile art's objects (the editing layer's, ruler guides aside) while `d` edits a pattern that
/// has Move Tile with Art on, with the pattern's name.
fn moving_tile_art(d: &Document) -> Option<(String, Vec<Arc<Node>>)> {
let pe = d.pattern_edit.as_ref()?;
if !d.pattern(&pe.pattern).is_some_and(|p| p.move_tile_with_art) {
return None;
}
let art = d.node(pe.layer)?.children()?.iter().filter(|c| !c.is_ruler_guide()).cloned().collect();
Some((pe.pattern.clone(), art))
}
/// Before a move: the bounds of the tile art for [`move_tile_with_art`], `None` unless `d` edits a
/// pattern with Move Tile with Art on.
pub(crate) fn tile_art_bounds(d: &Document) -> Option<Rect> {
moving_tile_art(d).and_then(|(_, art)| vectorcraft_doc::live::nodes_bounds(&art))
}
/// Move Tile with Art: after a move of `moved` that takes every object of the tile art (a group
/// counting when all of its objects moved), the tile moves by as much as the art did, measured from
/// its bounds `before` the move (objects aligned to the pixel grid snap back to it). A move of only
/// some of the art leaves the tile where it is.
pub(crate) fn move_tile_with_art(d: &mut Document, moved: &[NodeId], before: Rect) {
let Some((name, art)) = moving_tile_art(d) else { return };
let moved: std::collections::HashSet<NodeId> = moved.iter().copied().collect();
// An object moves whole when it moved, or when every object in it did (a group whose members
// were selected and moved one by one).
fn whole(n: &Node, moved: &std::collections::HashSet<NodeId>) -> bool {
moved.contains(&n.id) || n.children().is_some_and(|ch| !ch.is_empty() && ch.iter().all(|c| whole(c, moved)))
}
if art.is_empty() || !art.iter().all(|c| whole(c, &moved)) {
return;
}
let Some(after) = vectorcraft_doc::live::nodes_bounds(&art) else { return };
let by = after.origin() - before.origin();
if (by.x != 0.0 || by.y != 0.0)
&& let Some(def) = d.pattern_mut(&name)
{
def.tile = def.tile + by;
}
}
/// Side `side` of the `overlap` object `o` gives `cmd`: true for the second of `names`, false for the
/// first, `current` when `o` leaves it out or gives null. Any other value is an error.
fn overlap_side(o: &Value, side: &str, names: [&str; 2], current: bool, cmd: &str) -> Result<bool> {
@@ -680,6 +735,7 @@ fn pattern_list(s: &mut Session, _: &Value) -> Result<Value> {
"hSpacing": p.h_spacing,
"vSpacing": p.v_spacing,
"sizeTileToArt": p.size_tile_to_art,
"moveTileWithArt": p.move_tile_with_art,
"overlap": {"h": if p.overlap.right_in_front { "right" } else { "left" }, "v": if p.overlap.bottom_in_front { "bottom" } else { "top" }},
"copies": p.copies,
"dimCopies": p.dim_copies,
+12 -6
View File
@@ -257,7 +257,7 @@ fn load(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool) -> Result<Loa
let (natural, warnings) = (s.frame, s.warnings.clone());
return Ok(Loaded { name, format, art: Art::Document(s, link.clone(), !crop), natural, warnings, link: Some(link), board: None });
}
let a = pdf_art(src.name, &src.bytes, src.path, page, opts, !crop, cmd)?;
let a = pdf_art(src.name, (&src.bytes, None), src.path, page, opts, !crop, cmd)?;
let art = Art::Vector { src: Box::new(a.doc), nodes: a.nodes, clip: a.clip };
return Ok(Loaded { name, format, art, natural: a.frame, warnings: a.warnings, link: None, board: None });
}
@@ -308,10 +308,12 @@ fn load(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool) -> Result<Loa
/// art; read with `opts.password`. Only the page placed is read. A .ai saved without PDF
/// compatibility is read from its editing data, as it opens, and placed as an EPS is: the art on
/// artboard `page`, its linked images found from its folder. So is page 1 of a .ai or PDF whose
/// PDF part can't be read.
/// PDF part can't be read. `opened`, when given, is the PDF `bytes` already read
/// ([`vectorcraft_pdf::open_pdf`] with `opts`' password): its pages are read without reading the
/// file again.
pub(crate) fn pdf_art(
src: &str,
bytes: &[u8],
(bytes, opened): (&[u8], Option<&vectorcraft_pdf::Opened>),
path: Option<&str>,
page: usize,
opts: fileio::LoadOptions,
@@ -321,11 +323,15 @@ pub(crate) fn pdf_art(
let name = fileio::file_name(src);
let index = page.checked_sub(1).ok_or_else(|| bad(cmd, "page must be a whole number from 1"))?;
let o = fileio::LoadOptions { crop: if bounding { CropTo::Crop } else { opts.crop }, ..opts };
let mut read = fileio::page_document(bytes, index, &o);
let page_document = |i: usize| match opened {
Some(opened) => fileio::opened_page_document(bytes, opened, i, &o),
None => fileio::page_document(bytes, i, &o),
};
let mut read = page_document(index);
// Such a file can have more artboards than placeholder pages.
if page > 1
&& read.is_err()
&& let Err(e) = fileio::page_document(bytes, 0, &o)
&& let Err(e) = page_document(0)
&& fileio::is_placeholder(&e)
{
read = Err(e);
@@ -351,7 +357,7 @@ pub(crate) fn pdf_art(
let clip = (!bounding).then_some(board);
let frame = clip.or_else(|| shown_bounds(&symbols, &nodes));
let frame = frame.filter(|r| r.width() > 0.0 || r.height() > 0.0).ok_or_else(|| bad(cmd, format!("`{name}` has no art to place")))?;
Ok(document::DocumentArt { doc, nodes, clip, frame, warnings })
Ok(document::DocumentArt { doc, nodes, clip, frame, warnings, editing_data: alone })
}
/// The bounds of what `nodes` draw, as an export measures art
+48 -13
View File
@@ -100,6 +100,9 @@ pub(crate) struct DocumentArt {
/// What is shown: the artboard, or the art's bounds.
pub frame: Rect,
pub warnings: Vec<String>,
/// Whether a PDF or `.ai` page was read from the file's editing data (its page only a
/// placeholder, or its PDF part unreadable) instead of from the page.
pub editing_data: bool,
}
/// Artboard `page` (1-based) of the VectorCraft document `name` (`bytes`, read from `path` when
@@ -114,6 +117,21 @@ pub(crate) fn document_art(
bounding: bool,
page_box: PageBox,
cmd: &str,
) -> Result<DocumentArt> {
opened_document_art(name, (bytes, None), path, page, bounding, page_box, cmd)
}
/// [`document_art`] of `bytes` and, for a PDF already read, `opened`: the PDF `bytes` as
/// [`vectorcraft_pdf::open_pdf`] read it without a password, so its page is read without reading
/// the file again.
fn opened_document_art(
name: &str,
(bytes, opened): (&[u8], Option<&vectorcraft_pdf::Opened>),
path: Option<&str>,
page: u32,
bounding: bool,
page_box: PageBox,
cmd: &str,
) -> Result<DocumentArt> {
let file = fileio::file_name(name);
let pdf = is_pdf(name, bytes);
@@ -125,7 +143,7 @@ pub(crate) fn document_art(
}
if pdf {
let o = fileio::LoadOptions { crop: crop_to(page_box), ..Default::default() };
return super::pdf_art(name, bytes, path, page as usize, o, bounding, cmd);
return super::pdf_art(name, (bytes, opened), path, page as usize, o, bounding, cmd);
}
let mut l = fileio::load(name, bytes)?;
// Its linked images show their files; its placed documents stay as they are, unless their
@@ -145,7 +163,7 @@ pub(crate) fn document_art(
let nodes = super::on_artboard(&symbols, &layers, board);
let frame = if bounding { super::shown_bounds(&symbols, &nodes) } else { Some(board) };
let frame = frame.filter(|r| r.width() > 0.0 || r.height() > 0.0).ok_or_else(|| bad(cmd, format!("`{file}` has no art to place")))?;
Ok(DocumentArt { doc: l.doc, nodes, clip: (!bounding).then_some(board), frame, warnings: l.warnings })
Ok(DocumentArt { doc: l.doc, nodes, clip: (!bounding).then_some(board), frame, warnings: l.warnings, editing_data: false })
}
/// The most placed documents read inside one another while their links are resolved.
@@ -223,6 +241,8 @@ pub(crate) struct Source {
pub warnings: Vec<String>,
/// The colour mode the file's art was read in (a PDF page painted mostly in CMYK reads in CMYK).
pub color_mode: ColorMode,
/// [`DocumentArt::editing_data`].
pub editing_data: bool,
}
/// The VectorCraft document `name` (`bytes`, from `path` when there is one) read for showing
@@ -232,33 +252,48 @@ pub(crate) fn source(name: &str, bytes: &[u8], path: Option<&str>, page: u32, bo
read_source(name, bytes, None, path, (page, bounding, page_box), cmd)
}
/// [`source`] of the file whose bytes `bytes` holds, kept by the blob without a copy of its own:
/// several pages of one file read this way share one copy of it.
/// A PDF (or PDF-compatible `.ai`) whose pages are read for placing linked, read once for them all.
#[derive(Clone, Copy)]
pub(crate) struct SharedFile<'a> {
/// The file's bytes, which every page's blob keeps without a copy of its own.
pub bytes: &'a Arc<Vec<u8>>,
/// The bytes' hash ([`hash_bytes`]).
pub hash: &'a str,
/// The bytes as [`vectorcraft_pdf::open_pdf`] read them, without a password.
pub opened: &'a vectorcraft_pdf::Opened,
}
/// [`source`] of page `page` of `file`: several pages of one file read this way share one copy of
/// it, and the file is hashed and read once for them all.
pub(crate) fn shared_source(
name: &str,
bytes: &Arc<Vec<u8>>,
file: SharedFile<'_>,
path: Option<&str>,
page: u32,
bounding: bool,
page_box: PageBox,
cmd: &str,
) -> Result<Source> {
read_source(name, bytes, Some(bytes), path, (page, bounding, page_box), cmd)
read_source(name, file.bytes, Some(file), path, (page, bounding, page_box), cmd)
}
/// [`source`], the blob keeping `shared` when given (else a copy of `bytes`); `shown` is the page
/// (or artboard), whether the art's bounds are shown, and the page's box.
/// [`source`], the blob keeping `shared`'s bytes when given (else a copy of `bytes`), its hash
/// used for the key (else `bytes` hashed) and its pages read from what was read of it; `shown` is
/// the page (or artboard), whether the art's bounds are shown, and the page's box.
fn read_source(
name: &str,
bytes: &[u8],
shared: Option<&Arc<Vec<u8>>>,
shared: Option<SharedFile<'_>>,
path: Option<&str>,
shown: (u32, bool, PageBox),
cmd: &str,
) -> Result<Source> {
let (page, bounding, page_box) = shown;
let hash = shared.map_or_else(|| hash_bytes(bytes), |f| f.hash.to_string());
let opened = shared.map(|f| f.opened);
let shared = shared.map(|f| f.bytes);
// The same document placed the same way is read once (placing it again is free).
let key = key_for(&hash_bytes(bytes), page, bounding, page_box);
let key = key_for(&hash, page, bounding, page_box);
// Resolving its links depends on where the file is and on what the caller may read, so a hit
// needs the same path, and nothing is shared with or from a confined (automation) caller.
let confined = crate::file_access::current().is_some();
@@ -269,7 +304,7 @@ fn read_source(
}
return Ok(s);
}
let a = document_art(name, bytes, path, page, bounding, page_box, cmd)?;
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 shown = PlacedDocument {
@@ -284,10 +319,10 @@ fn read_source(
};
let art = group(a.nodes, a.clip);
blob.proxy = preview(&a.doc, &art, a.frame).map(Arc::new);
let color_mode = a.doc.color_mode;
let (color_mode, editing_data) = (a.doc.color_mode, a.editing_data);
// Drawing it needn't read it again.
vectorcraft_doc::placed_document::prime(&shown, blob.bytes.clone(), (a.doc, art, a.frame));
let s = Source { blob, key, page_box, frame: a.frame, warnings: a.warnings, color_mode };
let s = Source { blob, key, page_box, frame: a.frame, warnings: a.warnings, color_mode, editing_data };
if !confined {
let mut m = lock_memo();
if m.len() >= MEMO_SIZE {
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -2008,6 +2008,38 @@ fn glyph_form_is_one_character_attribute_saved_only_when_set() {
assert!(runs(&s).iter().all(|r| r.style.glyph_form == GlyphForm::Default));
}
/// A glyph choice (`text.setGlyphAlternate`) would keep drawing its own glyph over a glyph form,
/// so setting a form other than "default" takes it away, in `text.setRangeStyle` and in
/// `text.setFormat`; "default" (Revert To Default Forms) and calls without `glyphForm` keep it.
#[test]
fn a_glyph_form_takes_away_the_characters_glyph_choice() {
use vectorcraft_doc::{GlyphChoice, GlyphForm};
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "亜唖"})).unwrap()["id"].as_u64().unwrap();
let choice = GlyphChoice { ch: '唖', gid: 42, font: "Test-Regular".into(), version: "1".into() };
if let Some(NodeKind::Text(t)) = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(NodeId(id)).map(|n| &mut n.kind) {
vectorcraft_text::edit::style_range(&mut t.runs, 3, 6, |st| st.glyph_alternate = Some(choice.clone()));
}
let state = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.glyph_form, r.style.glyph_alternate.is_some())).collect::<Vec<_>>(),
_ => panic!("text"),
};
s.execute("text.setRangeStyle", &json!({"id": id, "size": 30})).unwrap();
assert_eq!(state(&s), [("亜".into(), GlyphForm::Default, false), ("唖".into(), GlyphForm::Default, true)], "no glyphForm: kept");
s.execute("text.setRangeStyle", &json!({"id": id, "glyphForm": "default"})).unwrap();
assert_eq!(state(&s)[1], ("唖".into(), GlyphForm::Default, true), "default: kept");
s.execute("text.setRangeStyle", &json!({"id": id, "start": 3, "end": 6, "glyphForm": "jis78"})).unwrap();
assert_eq!(state(&s), [("亜".into(), GlyphForm::Default, false), ("唖".into(), GlyphForm::Jis78, false)]);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(state(&s)[1], ("唖".into(), GlyphForm::Default, true), "one undo step brings both back");
s.execute("select.set", &json!({"ids": [id]})).unwrap();
s.execute("text.setFormat", &json!({"glyphForm": "default"})).unwrap();
assert!(state(&s).iter().any(|r| r.2), "default: kept");
s.execute("text.setFormat", &json!({"glyphForm": "traditional"})).unwrap();
assert!(state(&s).iter().all(|r| r.1 == GlyphForm::Traditional && !r.2), "{:?}", state(&s));
}
/// No Break is a character attribute, saved only when on.
#[test]
fn no_break_is_a_character_attribute_saved_only_when_on() {