Merge main into feat/scripts-api-d3-layers-artboards

This commit is contained in:
dotCooCoo
2026-12-01 15:07:13 -08:00
91 changed files with 5866 additions and 272 deletions
+1 -2
View File
@@ -654,8 +654,7 @@ mod tests {
let held = rss_mb();
drop(buffer);
let (Some((held, _)), Some((now, peak))) = (held, rss_mb()) else {
eprintln!("no memory reading (Linux without `ps`): nothing to check");
return;
panic!("rss_mb gave no memory reading");
};
assert!(peak.is_some_and(|peak| peak > held - 16.0), "holding 64 MB: {held:.1} MB, after freeing it: {now:.1} MB, peak {peak:?}");
}
+3
View File
@@ -28,6 +28,9 @@ impl PrintService for SystemPrint {
fn setup(&mut self, printer: Option<&str>) -> Result<(), String> {
system::setup(printer)
}
fn scripts_may_print(&self) -> bool {
true
}
}
/// The status after the job `title` went to `printer` (the default one without a name), with the
+146 -22
View File
@@ -90,16 +90,10 @@ impl DotShape {
fn path(self, t: f64, s: f64) -> PathData {
let square = |side: f64| shapes::rectangle(Rect::from_center_size(Point::ZERO, (side, side)));
match self {
DotShape::Circle => {
let r = s * (t / std::f64::consts::PI).sqrt();
shapes::ellipse(Rect::from_center_size(Point::ZERO, (2.0 * r, 2.0 * r)))
}
DotShape::Ellipse => {
let r = s * (t / std::f64::consts::PI).sqrt();
shapes::ellipse(Rect::from_center_size(Point::ZERO, (2.6 * r, 2.0 * r / 1.3)))
}
DotShape::Circle => cell_dot(t, s / 2.0, CellKind::Circle),
DotShape::Ellipse => cell_dot(t, s / 2.0, CellKind::Ellipse),
DotShape::Square => square(s * t.sqrt()),
DotShape::Diamond => square(s * t.sqrt()).transformed(Affine::rotate(std::f64::consts::FRAC_PI_4)),
DotShape::Diamond => cell_dot(t, s / 2.0, CellKind::Diamond),
// Cells along a row join into a line as thick as the tone.
DotShape::Line => shapes::rectangle(Rect::from_center_size(Point::ZERO, (s * 1.001, s * t))),
DotShape::Euclidean => PathData::from_bezpath(&spot(t, s / 2.0, SpotKind::Euclidean)),
@@ -296,6 +290,9 @@ fn spot_quadrant(u: f64, h: f64, kind: SpotKind) -> Vec<CubicBez> {
/// the cell with the dot of the opposite tone cut out at each corner, so the dark joins up and the
/// light becomes holes.
fn spot(t: f64, h: f64, kind: SpotKind) -> BezPath {
if t <= 0.5 {
return four_quadrants(&spot_quadrant(t, h, kind));
}
let mut bp = BezPath::new();
let mut add = |curves: Vec<CubicBez>, first: bool| {
for (k, c) in curves.iter().enumerate() {
@@ -305,20 +302,129 @@ fn spot(t: f64, h: f64, kind: SpotKind) -> BezPath {
bp.curve_to(c.p1, c.p2, c.p3);
}
};
if t <= 0.5 {
let q1 = spot_quadrant(t, h, kind);
add(q1.clone(), true);
add(reversed(&mapped(&q1, |p| Point::new(-p.x, p.y))), false);
add(mapped(&q1, |p| Point::new(-p.x, -p.y)), false);
add(reversed(&mapped(&q1, |p| Point::new(p.x, -p.y))), false);
} else {
// Round the corners counterclockwise, each one's hole the dot of the opposite tone.
let q1 = spot_quadrant(1.0 - t.min(1.0), h, kind);
add(reversed(&mapped(&q1, |p| Point::new(h - p.x, h - p.y))), true);
add(mapped(&q1, |p| Point::new(p.x - h, h - p.y)), false);
add(reversed(&mapped(&q1, |p| Point::new(p.x - h, p.y - h))), false);
add(mapped(&q1, |p| Point::new(h - p.x, p.y - h)), false);
// Round the corners counterclockwise, each one's hole the dot of the opposite tone.
let q1 = spot_quadrant(1.0 - t.min(1.0), h, kind);
add(reversed(&mapped(&q1, |p| Point::new(h - p.x, h - p.y))), true);
add(mapped(&q1, |p| Point::new(p.x - h, h - p.y)), false);
add(reversed(&mapped(&q1, |p| Point::new(p.x - h, p.y - h))), false);
add(mapped(&q1, |p| Point::new(h - p.x, p.y - h)), false);
bp.close_path();
bp
}
/// The dots that grow past their cell's sides: drawn clipped to the cell, so neighbors meet along
/// the shared side instead of overlapping, sized so the clipped dot covers the tone, and the whole
/// cell at full tone.
#[derive(Clone, Copy)]
enum CellKind {
Circle,
/// 1.69 times as wide as tall.
Ellipse,
Diamond,
}
static CELL_CIRCLE: OnceLock<Vec<f64>> = OnceLock::new();
static CELL_ELLIPSE: OnceLock<Vec<f64>> = OnceLock::new();
static CELL_DIAMOND: OnceLock<Vec<f64>> = OnceLock::new();
impl CellKind {
/// The first quadrant of the dot of size `r` clipped to the quadrant [0, 1]², from the x axis to
/// the y axis. Circle: radius `r`; Ellipse: semi-axes 1.3 `r` and `r` / 1.3; Diamond: half
/// diagonal `r`.
fn quadrant(self, r: f64) -> Vec<CubicBez> {
let corner = Point::new(1.0, 1.0);
match self {
CellKind::Diamond if r <= 1.0 => vec![segment(Point::new(r, 0.0), Point::new(0.0, r))],
CellKind::Diamond if r < 2.0 => vec![
segment(Point::new(1.0, 0.0), Point::new(1.0, r - 1.0)),
segment(Point::new(1.0, r - 1.0), Point::new(r - 1.0, 1.0)),
segment(Point::new(r - 1.0, 1.0), Point::new(0.0, 1.0)),
],
CellKind::Diamond => vec![segment(Point::new(1.0, 0.0), corner), segment(corner, Point::new(0.0, 1.0))],
CellKind::Circle | CellKind::Ellipse => {
let (a, b) = if matches!(self, CellKind::Circle) { (r, r) } else { (1.3 * r, r / 1.3) };
// The ellipse stays inside x ≤ 1 from angle tx and inside y ≤ 1 up to angle ty.
let tx = (1.0 / a).min(1.0).acos();
let ty = (1.0 / b).min(1.0).asin();
if tx >= ty {
return vec![segment(Point::new(1.0, 0.0), corner), segment(corner, Point::new(0.0, 1.0))];
}
let at = |th: f64| Point::new(a * th.cos(), b * th.sin());
let mut out = vec![];
if a > 1.0 {
out.push(segment(Point::new(1.0, 0.0), at(tx)));
}
ellipse_arc(&mut out, a, b, tx, ty);
if b > 1.0 {
out.push(segment(at(ty), Point::new(0.0, 1.0)));
}
out
}
}
}
/// The size at which the dot covers the whole quadrant.
fn max_size(self) -> f64 {
match self {
CellKind::Circle => std::f64::consts::SQRT_2,
// 1 / (1.3 r)² + (1.3 / r)² = 1 at the corner.
CellKind::Ellipse => (1.0 / 1.69 + 1.69_f64).sqrt(),
CellKind::Diamond => 2.0,
}
}
fn table(self) -> &'static OnceLock<Vec<f64>> {
match self {
CellKind::Circle => &CELL_CIRCLE,
CellKind::Ellipse => &CELL_ELLIPSE,
CellKind::Diamond => &CELL_DIAMOND,
}
}
/// For tones `k / SIZE_STEPS`, the size of the dot whose clipped quadrant covers that tone.
fn sizes(self) -> Vec<f64> {
(0..=SIZE_STEPS)
.map(|k| {
let target = k as f64 / SIZE_STEPS as f64;
let (mut lo, mut hi) = (0.0, self.max_size());
for _ in 0..50 {
let mid = (lo + hi) / 2.0;
if curves_area(&self.quadrant(mid)) < target { lo = mid } else { hi = mid }
}
(lo + hi) / 2.0
})
.collect()
}
}
/// The `kind` dot for tone `t` (0..1) in a cell of half side `h` centered on the origin, clipped to
/// the cell ([`CellKind`]).
fn cell_dot(t: f64, h: f64, kind: CellKind) -> PathData {
let sizes = kind.table().get_or_init(|| kind.sizes());
let x = t.clamp(0.0, 1.0) * SIZE_STEPS as f64;
let i = (x.floor() as usize).min(SIZE_STEPS - 1);
let (lo, hi) = (sizes.get(i).copied().unwrap_or(0.0), sizes.get(i + 1).copied().unwrap_or(0.0));
let r = lo + (hi - lo) * (x - i as f64);
let q1 = mapped(&kind.quadrant(r), |p| Point::new(p.x * h, p.y * h));
PathData::from_bezpath(&four_quadrants(&q1))
}
/// The closed path through `q1` (from the x axis to the y axis) and its mirror images in the other
/// three quadrants, counterclockwise.
fn four_quadrants(q1: &[CubicBez]) -> BezPath {
let mut bp = BezPath::new();
let mut add = |curves: Vec<CubicBez>, first: bool| {
for (k, c) in curves.iter().enumerate() {
if k == 0 {
if first { bp.move_to(c.p0) } else { bp.line_to(c.p0) }
}
bp.curve_to(c.p1, c.p2, c.p3);
}
};
add(q1.to_vec(), true);
add(reversed(&mapped(q1, |p| Point::new(-p.x, p.y))), false);
add(mapped(q1, |p| Point::new(-p.x, -p.y)), false);
add(reversed(&mapped(q1, |p| Point::new(p.x, -p.y))), false);
bp.close_path();
bp
}
@@ -709,6 +815,24 @@ mod tests {
assert_eq!((DotShape::parse("Euclidean"), DotShape::parse("elliptical")), (Some(DotShape::Euclidean), Some(DotShape::Elliptical)));
}
#[test]
fn round_and_diamond_dots_stay_in_their_cell_and_fill_it_at_full_tone() {
for shape in [DotShape::Circle, DotShape::Ellipse, DotShape::Diamond] {
for t in [0.2, 0.6, 0.85, 0.97] {
// The dot never reaches into a neighbor's cell, so dots of different tones meet
// along the shared side instead of overlapping into notches.
let b = shape.path(t, 2.0).control_bounds().unwrap();
assert!(b.x0 >= -1.0 - 1e-9 && b.x1 <= 1.0 + 1e-9 && b.y0 >= -1.0 - 1e-9 && b.y1 <= 1.0 + 1e-9, "{shape:?} at {t}: {b:?}");
// What it covers of the cell is the tone.
let area = shape.path(t, 2.0).to_bezpath().area().abs() / 4.0;
assert!((area - t).abs() < 2e-3, "{shape:?} at {t}: {area}");
}
// Full tone is the whole cell, its corners included.
assert!(covers(shape, 1.0, (0.49, 0.49)) && covers(shape, 1.0, (-0.49, 0.49)), "{shape:?}");
assert!(!covers(shape, 0.9, (0.499, 0.499)), "{shape:?}");
}
}
#[test]
fn euclidean_dots_meet_corner_to_corner_at_half() {
let s = DotShape::Euclidean;
+16 -4
View File
@@ -1035,10 +1035,11 @@ fn a_baked_group_with_type_keeps_a_shadow_on_each_copy() {
use vectorcraft_doc::text::{CharStyle, TextObject};
let style = CharStyle { size: 40.0, fill: Paint::solid(Color::BLACK), ..Default::default() };
let words = Node::new(NodeId(161), vectorcraft_doc::NodeKind::Text(Box::new(TextObject::point(Point::new(5.0, 60.0), "IIII", style))));
if !crate::outline_text(&words).is_some_and(|o| paths_in(&o) > 0) {
if !fonts() {
eprintln!("skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)");
return;
}
assert!(crate::outline_text(&words).is_some_and(|o| paths_in(&o) > 0), "the type outlines to paths");
let g = group(160, vec![words, square(162, vec![])], vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 150, "copies": 1}))]);
let b = baked(g);
assert!(near(&shadows_in(&b), &[(10.0, 0.0), (10.0, 0.0)]), "{:?}", shadows_in(&b));
@@ -1640,6 +1641,17 @@ fn type_node(id: u64, effects: Vec<Effect>) -> Node {
n
}
/// Whether the face of the default character style is installed, so that type lays out glyphs.
/// When it is, `type_node`'s type must outline to paths.
fn fonts() -> bool {
let style = vectorcraft_doc::text::CharStyle::default();
if vectorcraft_text::FontDb::global().face(&style.font_family, &style.font_style).is_none() {
return false;
}
assert!(crate::outline_text(&type_node(95, vec![])).is_some_and(|o| paths_in(&o) > 0), "{}: the type outlines to paths", style.font_family);
true
}
/// An instance at (50, 50) with `effects` of a symbol, and the symbol's art: a black 20 pt square
/// centered on its origin.
fn instance(id: u64, effects: Vec<Effect>) -> (Node, Node) {
@@ -1660,7 +1672,7 @@ fn instance(id: u64, effects: Vec<Effect>) -> (Node, Node) {
/// image and the instance are checked.
#[test]
fn each_copy_of_type_an_image_or_a_symbol_instance_carries_the_shadow_listed_before_it() {
let fonts = crate::outline_text(&type_node(95, vec![])).is_some_and(|o| paths_in(&o) > 0);
let fonts = fonts();
if !fonts {
eprintln!("type skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)");
}
@@ -1702,7 +1714,7 @@ fn each_copy_of_type_an_image_or_a_symbol_instance_carries_the_shadow_listed_bef
/// listed before that effect, as the canvas draws it, rather than staying type under one shadow.
#[test]
fn baked_type_whose_transform_moves_its_copies_keeps_a_shadow_on_each() {
if !crate::outline_text(&type_node(99, vec![])).is_some_and(|o| paths_in(&o) > 0) {
if !fonts() {
eprintln!("skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)");
return;
}
@@ -1738,7 +1750,7 @@ fn type_carries_its_fills_shadow_on_each_copy() {
n
};
let copying = vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 1}))];
if !crate::outline_text(&type_node(95, vec![])).is_some_and(|o| paths_in(&o) > 0) {
if !fonts() {
eprintln!("type skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)");
return;
}
+1 -1
View File
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New…",
["File"],
None,
"{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), rows?: n (gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file is a link or a folder, could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent",
"{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (a whole number, 1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (a whole number, 1–1000; default: all in one row), rows?: n (a whole number, 1–1000; gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file is a link or a folder, could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent",
always,
super::newdoc::file_new
),
+2 -2
View File
@@ -135,7 +135,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Placement Options",
[],
None,
"{ids?: [image or placed document ids] (default: the selected ones), preserve?: transforms|bounds (default)|fileDimensions|fit|fill, align?: topLeft|top|topRight|left|center (default)|right|bottomLeft|bottom|bottomRight (where the new art sits; not for bounds), clip?: false (clip it to the old bounds where it is larger)} how a file read again (links.relink, links.update) takes each image's place: transforms keeps its scale (relative to each file's 100% size), rotation and position; bounds stretches it into the old bounds; fileDimensions puts it at 100%, unrotated; fit and fill scale it proportionally to fit inside or cover the old bounds. Without options → {placement} of the first image; else one undo step → {ids, placement}",
"{ids?: [image or placed document ids] (default: the selected ones), preserve?: transforms|bounds (default)|fileDimensions|fit|fill, align?: topLeft|top|topRight|left|center (default)|right|bottomLeft|bottom|bottomRight (where the new art sits; not for bounds), clip?: false (clip it to the old bounds where it is larger)} how a file read again (links.relink, links.update) takes each image's place: transforms keeps its scale (relative to each file's 100% size), rotation and position; bounds stretches it into the old bounds; fileDimensions puts it at 100%, unrotated; fit and fill scale it proportionally to fit inside or cover the old bounds. Without options → {ids, placement} (the images read, and the placement of the first); else one undo step → {ids, placement}",
has_doc,
placement_options
),
@@ -3230,7 +3230,7 @@ fn placement_options(s: &mut Session, p: &Value) -> Result<Value> {
let first = ids.first().and_then(|id| placement_of(&doc, *id)).unwrap_or_default();
drop(doc);
if preserve.is_none() && align.is_none() && clip.is_none() {
return Ok(json!({ "placement": placement_json(first) }));
return Ok(json!({ "ids": ids_json(&ids), "placement": placement_json(first) }));
}
let set = |o: &mut PlacementOptions| {
o.preserve = preserve.unwrap_or(o.preserve);
+28 -21
View File
@@ -299,7 +299,11 @@ impl DocSettings {
}
/// These settings with `p`'s changes (the params of `file.new`) → validated.
pub fn with_params(mut self, p: &Value, cmd: &str) -> Result<Self> {
pub fn with_params(self, p: &Value, cmd: &str) -> Result<Self> {
self.with_params_inner(p, cmd, false)
}
fn with_params_inner(mut self, p: &Value, cmd: &str, replaying: bool) -> Result<Self> {
if let Some(u) = p.get("units").filter(|v| !v.is_null()) {
let u = u.as_str().unwrap_or("");
self.units = Unit::named(u).ok_or_else(|| bad(cmd, format!("unknown units `{u}`")))?;
@@ -329,11 +333,11 @@ impl DocSettings {
Some(o) => return Err(bad(cmd, format!("orientation must be portrait or landscape, not `{o}`"))),
}
if let Some(n) = p.get("artboards").filter(|v| !v.is_null()) {
let n = n.as_f64().filter(|n| n.is_finite()).ok_or_else(|| bad(cmd, "artboards must be a number"))?;
self.artboards = n.round().clamp(1.0, MAX_ARTBOARDS as f64) as u32;
self.artboards = if replaying { n.as_f64().map(|n| n.round().clamp(1.0, f64::from(MAX_ARTBOARDS)) as u32) } else { count(n) }
.ok_or_else(|| bad(cmd, format!("artboards must be a whole number from 1 to {MAX_ARTBOARDS}")))?;
}
if let Some(l) = p.get("artboardLayout").filter(|v| !v.is_null()) {
self.layout_params(l, cmd)?;
self.layout_params(l, cmd, replaying)?;
}
if let Some(b) = p.get("bleed").filter(|v| !v.is_null()) {
self.bleed = super::docsetup::bleed_param(b, self.bleed, cmd)?;
@@ -371,7 +375,7 @@ impl DocSettings {
}
/// `artboardLayout: {layout?, columns?, rows?, spacing?, rightToLeft?}` or just a layout id.
fn layout_params(&mut self, l: &Value, cmd: &str) -> Result<()> {
fn layout_params(&mut self, l: &Value, cmd: &str, replaying: bool) -> Result<()> {
let bad_layout = || bad(cmd, "artboardLayout.layout must be gridByRow, gridByColumn, row or column");
if let Some(id) = l.as_str() {
self.layout = ArtboardLayout::parse(id).ok_or_else(bad_layout)?;
@@ -380,25 +384,22 @@ impl DocSettings {
}
return Ok(());
}
let o = l.as_object().ok_or_else(|| bad(cmd, "artboardLayout must be {layout?, columns?, spacing?, rightToLeft?}"))?;
let o = l.as_object().ok_or_else(|| bad(cmd, "artboardLayout must be {layout?, columns?, rows?, spacing?, rightToLeft?}"))?;
for (k, v) in o {
match k.as_str() {
"layout" => self.layout = v.as_str().and_then(ArtboardLayout::parse).ok_or_else(bad_layout)?,
"columns" => {
self.columns = v
.as_f64()
.filter(|c| c.is_finite() && *c >= 1.0)
.ok_or_else(|| bad(cmd, "artboardLayout.columns must be 1 or more"))?
.round()
.min(MAX_ARTBOARDS as f64) as u32
self.columns =
if replaying { v.as_f64().filter(|n| *n >= 1.0).map(|n| n.round().min(f64::from(MAX_ARTBOARDS)) as u32) } else { count(v) }
.ok_or_else(|| bad(cmd, format!("artboardLayout.columns must be a whole number from 1 to {MAX_ARTBOARDS}")))?
}
"rows" => {
self.rows = v
.as_f64()
.map(f64::round)
.filter(|r| (1.0..=MAX_ARTBOARDS as f64).contains(r))
.map(|r| r as u32)
.ok_or_else(|| bad(cmd, format!("artboardLayout.rows must be from 1 to {MAX_ARTBOARDS}")))?
self.rows = if replaying {
v.as_f64().map(f64::round).filter(|n| (1.0..=f64::from(MAX_ARTBOARDS)).contains(n)).map(|n| n as u32)
} else {
count(v)
}
.ok_or_else(|| bad(cmd, format!("artboardLayout.rows must be a whole number from 1 to {MAX_ARTBOARDS}")))?
}
"spacing" => {
self.spacing = v
@@ -407,7 +408,7 @@ impl DocSettings {
.ok_or_else(|| bad(cmd, format!("artboardLayout.spacing must be 0–{MAX_SPACING} pt")))?
}
"rightToLeft" => self.right_to_left = v.as_bool().ok_or_else(|| bad(cmd, "artboardLayout.rightToLeft must be true or false"))?,
_ => return Err(bad(cmd, format!("unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft)"))),
_ => return Err(bad(cmd, format!("unknown artboardLayout key `{k}` (layout, columns, rows, spacing, rightToLeft)"))),
}
}
if o.contains_key("rows") && self.layout != ArtboardLayout::GridByColumn {
@@ -610,6 +611,12 @@ fn de_rows<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<u32, D
Ok(u32::deserialize(d)?.min(MAX_ARTBOARDS))
}
/// A count `file.new` takes (artboards, columns, rows): a whole number, written `4` or `4.0`, from 1
/// to [`MAX_ARTBOARDS`]; anything else is `None`.
fn count(v: &Value) -> Option<u32> {
v.as_f64().filter(|n| n.fract() == 0.0 && (1.0..=f64::from(MAX_ARTBOARDS)).contains(n)).map(|n| n as u32)
}
/// A saved or Recent preset's artboard spacing, kept to 0 to [`MAX_SPACING`] points.
fn de_spacing<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<f64, D::Error> {
Ok(f64::deserialize(d)?.clamp(0.0, MAX_SPACING))
@@ -871,7 +878,7 @@ pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result<Value> {
// A preset keeps its name in Recent unless its size changed (turning it doesn't count).
let sorted = |d: &DocSettings| (d.width.min(d.height), d.width.max(d.height), d.units);
let size = str_param(p, "preset").map(|_| sorted(&base));
let mut settings = base.with_params(p, C)?;
let mut settings = base.with_params_inner(p, C, s.replaying())?;
if size != Some(sorted(&settings)) {
settings.name = "Custom".into();
}
@@ -956,7 +963,7 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
Some(from) => find(s, from).ok_or_else(|| bad(C, format!("no preset called `{from}` (see file.newPresets)")))?,
None => s.default_settings(),
};
let mut preset = base.with_params(p, C)?;
let mut preset = base.with_params_inner(p, C, s.replaying())?;
preset.name = name.to_string();
let saved = &mut s.prefs.new_doc_presets;
match saved.iter_mut().find(|q| q.name.eq_ignore_ascii_case(name)) {
+37 -10
View File
@@ -12,7 +12,7 @@ use vectorcraft_pdf::{PrintLayers, PrintOptions, PrintPreview, PrintSettings};
use super::fileio::pdf::{merge, pdf_error};
use super::fileio::{extension, write_or_return};
use super::flatten::has_transparent_tile_images;
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, str_param};
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, str_param, u64_req};
const SETUP: &str = "print.setup";
@@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Print",
[],
Some("Cmd+P"),
"{preset?: name (as print.setup's: its settings instead of the document's; the saved settings stay), settings?: {…settings of print.setup} (over the document's or the preset's), includeArtboardFill?: true (each artboard's background color prints behind its art; false leaves it out), path?, format?: pdf (default: a print-ready PDF) | postscript (the default for a .ps path: a PostScript file with DSC comments, %%Pages, a page per sheet with its paper size, marks, separations with their ink and halftone screen, the fixed flatness, negatives), level?: 3|2 (the PostScript language level), flattenerPreset?: \"medium\" (PostScript: the preset transparency is flattened with — high, low or a saved one, see flattener.presets.list), acknowledgeLoss?: bool (with path: write over the file the document was read from although reading it left things out), forPrinter?: bool (the PDF goes to a print queue: a page whose paper is turned to landscape is written upright, the art turned a quarter anticlockwise, as a printer driver turns a landscape job; macOS prints a landscape page as it is, cut off on upright paper; paper wide in Portrait and transverse pages stay as they are)} print the document, one page per sheet of paper (per tile, per ink, per copy; with copiesPerSheet, a sheet holds as many copies of an artboard as fit) → {pages, format, path, bytes, warnings}; no path → {dataBase64, bytes, pages, format, warnings}. Raster effects print at the document's raster effects resolution; a PDF leaves halftone screens and flatness to the output device",
"{preset?: name (as print.setup's: its settings instead of the document's; the saved settings stay), settings?: {…settings of print.setup} (over the document's or the preset's), includeArtboardFill?: true (each artboard's background color prints behind its art; false leaves it out), path?, format?: pdf (default: a print-ready PDF) | postscript (the default for a .ps path: a PostScript file with DSC comments, %%Pages, a page per sheet with its paper size, marks, separations with their ink and halftone screen, the fixed flatness, negatives), level?: 3|2 (the PostScript language level), flattenerPreset?: \"medium\" (PostScript: the preset transparency is flattened with — high, low or a saved one, see flattener.presets.list), acknowledgeLoss?: bool (with path: write over the file the document was read from although reading it left things out), maxPages?: n (a whole number: the job is composed only when it prints at most n pages, copies counted; with more, nothing is composed or written and the reply is {pages, format}), forPrinter?: bool (the PDF goes to a print queue: a page whose paper is turned to landscape is written upright, the art turned a quarter anticlockwise, as a printer driver turns a landscape job; macOS prints a landscape page as it is, cut off on upright paper; paper wide in Portrait and transverse pages stay as they are)} print the document, one page per sheet of paper (per tile, per ink, per copy; with copiesPerSheet, a sheet holds as many copies of an artboard as fit) → {pages, format, path, bytes, warnings}; no path → {dataBase64, bytes, pages, format, warnings}. Raster effects print at the document's raster effects resolution; a PDF leaves halftone screens and flatness to the output device",
has_doc,
print
),
@@ -222,6 +222,11 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> {
super::fileio::check_not_lossy_overwrite(s.doc()?, path, p, PRINT)?;
}
let postscript = to_postscript(p)?;
let max_pages = match p.get("maxPages") {
None => None,
Some(_) => Some(u64_req(p, "maxPages", PRINT)?),
};
let too_many = |pages: usize| max_pages.is_some_and(|m| pages as u64 > m);
let doc = &s.doc()?.doc;
let mut set = preset_or_saved(PRINT, s, doc, p)?;
if postscript {
@@ -244,6 +249,27 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> {
&& !bitmap
&& super::printadvanced::flattener(PRINT, &set, &s.prefs.flattener_presets)?
.is_some_and(|o| has_transparent_tile_images(&vectorcraft_pdf::printed_document(doc, &set), &o));
let level = match p.get("level").filter(|v| postscript && !v.is_null()) {
Some(v) => {
let t = super::fileio::dxf::text(v);
Level::from_id(&t).ok_or_else(|| bad(PRINT, format!("level `{t}`: 2 or 3")))?
}
None => Level::default(),
};
// A job past `maxPages` is turned away before Print as Bitmap or a flattener preset prepares it,
// once the options are checked, when its pages follow from the artboards alone (composite, no
// `skipBlank`, artboards not ignored); the pages are counted again on the prepared art.
super::printadvanced::flattener(PRINT, &set, &s.prefs.flattener_presets)?;
let by_artboards = !set.skip_blank
&& !matches!(set.artboards, vectorcraft_pdf::PrintArtboards::Ignore)
&& set.output.mode == vectorcraft_pdf::OutputMode::Composite;
if max_pages.is_some()
&& by_artboards
&& let Ok(pv) = vectorcraft_pdf::preview(doc, &set)
&& too_many(pv.pages)
{
return Ok(json!({ "pages": pv.pages, "format": if postscript { "postscript" } else { "pdf" } }));
}
// Print as Bitmap and the flattener preset (Advanced) render and flatten it first.
let prepared = super::printadvanced::prepare(PRINT, doc, &set, &s.prefs.flattener_presets, s.prefs.black_output == "rich")?;
let path = str_param(p, "path");
@@ -251,7 +277,12 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> {
let which = set.print_layers;
if !postscript {
let printed = prepared.as_ref().unwrap_or(doc);
let typed = type_warnings(&full, which, &areas(&vectorcraft_pdf::preview(printed, &set).map_err(|e| pdf_error(PRINT, e))?));
let laid_out = vectorcraft_pdf::preview(printed, &set).map_err(|e| pdf_error(PRINT, e))?;
// `maxPages` is checked on the art as it prints, before the job is composed.
if too_many(laid_out.pages) {
return Ok(json!({ "pages": laid_out.pages, "format": "pdf" }));
}
let typed = type_warnings(&full, which, &areas(&laid_out));
let mut r =
vectorcraft_pdf::print(printed, &PrintOptions { settings: set, for_printer: bool_or(p, "forPrinter", false), ..Default::default() })
.map_err(|e| pdf_error(PRINT, e))?;
@@ -260,13 +291,6 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> {
r.warnings.extend(r.setting_notes);
return write_or_return(path, &r.bytes, json!({ "pages": r.pages, "format": "pdf", "warnings": r.warnings }));
}
let level = match p.get("level").filter(|v| !v.is_null()) {
Some(v) => {
let t = super::fileio::dxf::text(v);
Level::from_id(&t).ok_or_else(|| bad(PRINT, format!("level `{t}`: 2 or 3")))?
}
None => Level::default(),
};
// What the job loses, then the notes on the options: a reply lists them in that order.
let (mut warnings, mut setting_notes) = (vec![], vec![]);
if !bitmap && (tile_images || doc.layers.iter().any(|l| l.shows_transparency())) {
@@ -283,6 +307,9 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> {
};
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))?;
if too_many(plan.order.len()) {
return Ok(json!({ "pages": plan.order.len(), "format": "postscript" }));
}
let pages: Vec<PrintPage> = plan
.sheets
.iter()
+10
View File
@@ -384,6 +384,16 @@ pub struct Session {
pub(crate) script_style_trail: script::StyleTrail,
/// While a slice of a script runs in this session.
pub(crate) script_in_run: bool,
/// The one command a member of the script object model runs past
/// [`script::refused_to_scripts`] while it is set: `file.print` for `Document.print`, after the
/// member checked its options and its file.
pub(crate) script_unfenced: Option<&'static str>,
/// The printers the frontend lists for the next run, which takes them: `app.printerList` and
/// `Document.print` to a printer read them. `None`: scripts cannot print to a printer here.
pub script_printers: Option<script::printing::Printers>,
/// The jobs the last run that printed to a printer prepared, until the frontend takes them
/// ([`Session::take_script_prints`]).
pub(crate) script_prints: Vec<script::printing::PreparedPrint>,
/// The desktop app supplies each window by (document uid, runtime window identity) while a
/// script runs. Scripts read them as `Document.views`, and the app applies their zoom, center,
/// and screen mode. This list is empty without windows (headless).
+20 -3
View File
@@ -95,10 +95,11 @@ use vectorcraft_js::{
ArgInfo, Data, HostClass, HostError, HostFunction, HostItem, HostMember, MemberInfo, Realm, RunError, host_ref, host_ref_parts,
};
use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size};
use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_kept, command_value, current, data_size};
use crate::{DocState, Document, NodeId, NodeKind, Session, WindowView};
pub(super) mod layers;
mod print;
mod save_open;
mod tags;
mod text;
@@ -234,6 +235,8 @@ pub(super) struct State {
pub(super) boards_chosen_in_new: RefCell<Vec<(u64, usize)>>,
/// `app.userInteractionLevel` ([`save_open`]).
save_options: save_open::State,
/// The print option objects ([`print`]).
printing: print::State,
text: text::TextState,
presets: RefCell<Vec<Vec<(String, Data)>>>,
preset_bytes: Cell<u64>,
@@ -253,6 +256,17 @@ impl State {
self.saving.get()
}
/// Gives the run the printers the frontend listed (`None`: none can be printed to here), and
/// whether jobs an earlier run prepared still wait.
pub(super) fn start_printing(&self, printers: Option<super::printing::Printers>, waiting: bool) {
self.printing.start(printers, waiting);
}
/// The jobs the run prepared for a printer, which the run no longer holds.
pub(super) fn take_prints(&self) -> Vec<super::printing::PreparedPrint> {
self.printing.take_jobs()
}
/// The id of the tool `app.selectTool` chose last in the run, which becomes the current tool
/// when the run ends without an error.
pub(super) fn chosen_tool(&self) -> Option<&'static str> {
@@ -3033,7 +3047,7 @@ const ENUMS: &[(&str, &[&str])] = &[
/// holds.
pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> {
text::install_enums(realm)?;
for (name, members) in ENUMS.iter().chain(save_open::ENUMS) {
for (name, members) in ENUMS.iter().chain(save_open::ENUMS).chain(print::ENUMS) {
let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect();
realm.define_host_object(name, items)?;
}
@@ -3072,6 +3086,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
application.push(("textFonts".into(), text::app_text_fonts(l), MemberInfo { collection: true, ..typed("TextFonts") }));
application.push(later(l, "Application", "beep"));
application.extend(save_open::application_members(l));
application.extend(print::application_members(l));
application.extend(super::actions::app_members(l));
let preset = {
let l = link.clone();
@@ -3152,8 +3167,9 @@ fn classes(link: &Link) -> Vec<HostClass> {
document.extend(text::styles::doc_members(l));
document.extend(["swatches", "symbols"].into_iter().map(|m| later(l, "Document", m)));
document.extend(layers::document_members(l));
document.extend(save_open::document_members(l));
document.extend(variables::document_members(l));
document.extend(save_open::document_members(l));
document.extend(print::document_members(l));
document.push(("tags".into(), get(l, tags::doc_tags), MemberInfo { collection: true, ..typed("Tags") }));
classes.push(class("Document", None, document, None));
classes.push(class(
@@ -3266,6 +3282,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
classes.extend(variables::classes(l));
classes.extend(layers::classes(l));
classes.extend(save_open::classes(l));
classes.extend(print::classes(l));
classes.extend(tags::classes(l));
classes
}
File diff suppressed because it is too large Load Diff
+4 -4
View File
@@ -717,18 +717,18 @@ fn typename(d: &Data) -> Option<&str> {
// ---- Files ----
/// The path of the `File` argument `d`, or a `TypeError` naming the method.
fn file_path<'a>(d: &'a Data, method: &str) -> std::result::Result<&'a str, HostError> {
pub(super) fn file_path<'a>(d: &'a Data, method: &str) -> std::result::Result<&'a str, HostError> {
vectorcraft_js::file_ref_path(d).ok_or_else(|| HostError::Type(format!("{method} needs a File")))
}
/// The error a refused path throws: the `File` error and the path.
fn refused(message: &str, path: &str) -> HostError {
pub(super) fn refused(message: &str, path: &str) -> HostError {
HostError::Error(format!("{message}: {path}"))
}
/// Runs `f` with the commands' reads and writes held to the script's own grants
/// ([`super::super::files::Disk::exact`]).
fn exactly(h: &Host, f: impl FnOnce() -> Answer) -> Answer {
pub(super) fn exactly(h: &Host, f: impl FnOnce() -> Answer) -> Answer {
h.disk.borrow_mut().exact = true;
let r = f();
h.disk.borrow_mut().exact = false;
@@ -747,7 +747,7 @@ fn warned(h: &Host, method: &str, id: &str, p: &Value) -> Answer {
}
/// The path to give a command for the real path `real`, or an error when it is not valid UTF-8.
fn plain(real: std::path::PathBuf) -> std::result::Result<String, HostError> {
pub(super) fn plain(real: std::path::PathBuf) -> std::result::Result<String, HostError> {
crate::cmd::findfiles::plain(real).into_os_string().into_string().map_err(|_| HostError::Error("Script file path is not valid UTF-8".into()))
}
+49 -1
View File
@@ -47,6 +47,10 @@
//! run. An engine keeps no document and no run: its host functions reach the run through a link
//! that holds the run's host only while the run goes on. An error, a limit or a stop puts the
//! documents back and keeps the engine's globals; an internal error drops the engine.
//!
//! `Document.print` to a printer prepares its job in memory; the session holds the jobs of a run
//! only after the run's changes are kept, for the frontend to send once the person approves them
//! ([`printing`]).
pub mod actions;
pub mod console;
@@ -54,6 +58,7 @@ pub mod dialogs;
pub mod dollar;
pub mod dom;
pub mod include;
pub mod printing;
pub mod scriptui;
pub use dialogs::{DialogAnswer, DialogKind, ScriptDialog};
@@ -1405,6 +1410,17 @@ fn command(host: &Host, id: &str, params: &Value) -> std::result::Result<Data, H
/// [`command`], with the command's result as it gave it as well as the script's copy of it.
fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(Data, Value), HostError> {
command_crossing(host, id, params, true).map(|(data, value)| (data.unwrap_or(Data::Undefined), value))
}
/// [`command`] for a member that keeps the command's result itself: the result does not cross to
/// the script, so it is not held to the limits of a crossing. → the result as the command gave it.
fn command_kept(host: &Host, id: &str, params: &Value) -> std::result::Result<Value, HostError> {
command_crossing(host, id, params, false).map(|(_, value)| value)
}
/// [`command_value`], with the script's copy of the result made only when `cross` is true.
fn command_crossing(host: &Host, id: &str, params: &Value, cross: bool) -> std::result::Result<(Option<Data>, Value), HostError> {
// Point changes that wait in the object model are written before any command runs.
dom::flush(host)?;
let session = host.session.clone();
@@ -1430,10 +1446,13 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(
};
let mark = host.growth_mark();
let crossed = host.charge_growth(objects, added).and_then(|()| {
if !cross {
return Ok(None);
}
let data = to_data(&value, &result_limits(), 0, &mut (0, 0))
.map_err(|place| HostError::Range(format!("vc.run: the result{place} is too large for a script")))?;
host.charge_call(data_size(&data))?;
Ok(data)
Ok(Some(data))
});
// A command whose result does not reach the script is put back, like one that failed, and so is
// the growth it was charged.
@@ -1985,6 +2004,22 @@ impl Session {
self.script_report.as_ref()
}
/// Whether jobs a run prepared for a printer wait to be sent or dropped ([`printing`]).
pub fn script_prints_waiting(&self) -> bool {
!self.script_prints.is_empty()
}
/// The jobs that wait, as [`Self::take_script_prints`] would give them.
pub fn script_prints(&self) -> &[printing::PreparedPrint] {
&self.script_prints
}
/// The jobs the last run that printed to a printer prepared, which the session no longer holds:
/// the frontend sends them or drops them ([`printing`]).
pub fn take_script_prints(&mut self) -> Vec<printing::PreparedPrint> {
std::mem::take(&mut self.script_prints)
}
/// The Script Console: the lines of this session's runs, oldest first.
pub fn script_console(&self) -> &console::Console {
&self.script_console
@@ -2344,6 +2379,9 @@ impl Session {
),
linked: std::cell::OnceCell::new(),
});
// The printers the frontend listed are this run's alone, and a run may not print while
// jobs an earlier run prepared still wait for the person.
host.dom.start_printing(self.script_printers.take(), !self.script_prints.is_empty());
*link.borrow_mut() = Some(host.clone());
let args = match to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) {
Ok(args) => args,
@@ -2645,6 +2683,12 @@ impl Session {
if let Some(boards) = dom::layers::active_artboards(&host.dom.active_artboards.borrow(), &start, self.documents()) {
report["activeArtboards"] = boards;
}
// The jobs it prepared for a printer wait for the frontend now that its changes are kept.
let prints = host.dom.take_prints();
if !prints.is_empty() {
report["prints"] = json!(prints.len());
self.script_prints = prints;
}
let rejections = rejections_report(host, &job.realm);
if let (false, Some(o)) = (rejections.is_empty(), report.as_object_mut()) {
o.insert("unhandledRejections".into(), Value::Array(rejections));
@@ -2898,6 +2942,8 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result<std::result:
}
std::mem::swap(s, &mut *cell.borrow_mut());
s.script_in_run = false;
// A panic in a member that opened the fence for one command skips its own reset.
s.script_unfenced = None;
job.world.swap(s);
s.depth = depth;
s.sync_front_profiles();
@@ -2964,6 +3010,8 @@ thread_local! {
pub(crate) static TEST_RESULT_BYTES: Cell<Option<usize>> = const { Cell::new(None) };
/// Tests: makes the next slice panic.
pub(crate) static PANIC_IN_SLICE: Cell<bool> = const { Cell::new(false) };
/// Tests: makes the next command a member runs past the script fence panic before it runs.
pub(crate) static PANIC_WHILE_UNFENCED: Cell<bool> = const { Cell::new(false) };
/// Tests: the objects a run may add in place of [`GROWTH_OBJECTS`].
pub(crate) static TEST_GROWTH: Cell<Option<u64>> = const { Cell::new(None) };
/// Tests: the bytes a run may keep in place of [`GROWTH_BYTES`].
+101
View File
@@ -0,0 +1,101 @@
//! Printing to a printer from a script: the printers a frontend lists for a run ([`Printers`]),
//! which `app.printerList` and `PrintOptions.printerName` read, and the jobs `Document.print`
//! prepares ([`PreparedPrint`]).
//!
//! A run that prints to a printer sends nothing while it runs: each job is composed in memory and
//! kept with the run. When the run fails or is stopped, its jobs are dropped with its changes. When
//! it ends and its changes are kept, the session holds its jobs ([`crate::Session::take_script_prints`])
//! for the frontend, which sends them only when the person at the computer approves them.
//!
//! A printer name is only a key into the list the frontend gave: it never becomes a path, a URL or
//! a command line.
//!
//! The limits are VectorCraft's own: [`MAX_PRINTERS`], [`MAX_PRINTER_NAME_BYTES`], [`MAX_JOBS`],
//! [`MAX_SHEETS`] and [`MAX_JOB_BYTES`].
/// The most printers a run lists.
pub const MAX_PRINTERS: usize = 256;
/// The longest printer name a run lists, in bytes.
pub const MAX_PRINTER_NAME_BYTES: usize = 512;
/// The most printer jobs one run prepares.
pub const MAX_JOBS: usize = 4;
/// The most sheets of paper the jobs of one run hold together, every copy counted.
pub const MAX_SHEETS: u64 = 100;
/// The most bytes the jobs of one run hold together.
pub const MAX_JOB_BYTES: usize = 32 << 20;
/// The printers a frontend lists for a run, by name, with the system's default printer.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Printers {
names: Vec<String>,
default: Option<usize>,
/// The printer turns no landscape page to fit its paper: jobs are written upright
/// (`file.print`'s `forPrinter`).
pub for_printer: bool,
}
impl Printers {
/// The printers of `list` (name, whether it is the default), in its order. A name that is
/// empty, longer than [`MAX_PRINTER_NAME_BYTES`] or holds a control character is left out, and
/// so is a name that repeats an earlier one, though its default mark is kept. Every printer
/// after the first [`MAX_PRINTERS`] is left out, except the default printer, which takes the
/// last place when it comes later.
pub fn new(list: impl IntoIterator<Item = (String, bool)>, for_printer: bool) -> Self {
let mut names: Vec<String> = Vec::new();
let mut default = None;
for (name, is_default) in list {
let full = names.len() >= MAX_PRINTERS;
if full && default.is_some() {
break;
}
if name.is_empty() || name.len() > MAX_PRINTER_NAME_BYTES || name.chars().any(char::is_control) {
continue;
}
if let Some(i) = names.iter().position(|n| *n == name) {
if is_default && default.is_none() {
default = Some(i);
}
continue;
}
if full {
if is_default && let Some(last) = names.last_mut() {
*last = name;
default = Some(MAX_PRINTERS - 1);
}
continue;
}
if is_default && default.is_none() {
default = Some(names.len());
}
names.push(name);
}
Self { names, default, for_printer }
}
/// The printers' names.
pub fn names(&self) -> &[String] {
&self.names
}
/// The system's default printer, when the list holds it.
pub fn default_name(&self) -> Option<&str> {
self.default.map(|i| self.names[i].as_str())
}
/// Whether the list holds a printer named exactly `name`.
pub fn has(&self, name: &str) -> bool {
self.names.iter().any(|n| n == name)
}
}
/// A job a run prepared for a printer: a print-ready PDF, every copy in it.
#[derive(Clone, Debug, PartialEq)]
pub struct PreparedPrint {
/// The printer, by the name the run's list gave it.
pub printer: String,
/// The title of the document it prints, the job's name in the print queue.
pub title: String,
pub pdf: Vec<u8>,
/// The sheets of paper it prints, every copy counted.
pub sheets: u64,
}
+3
View File
@@ -192,6 +192,9 @@ impl Session {
script_high_water: Default::default(),
script_style_trail: Default::default(),
script_in_run: false,
script_unfenced: None,
script_printers: None,
script_prints: Vec::new(),
window_views: vec![],
script_copy_first: cfg!(target_arch = "wasm32"),
}
+1 -1
View File
@@ -104,7 +104,7 @@ impl Session {
return Err(EngineError::PluginBusy);
}
// A step of a batch a script runs is held to the same rule as the script's own commands.
if self.script_in_run && crate::script::refused_to_scripts(id) {
if self.script_in_run && crate::script::refused_to_scripts(id) && self.script_unfenced != Some(id) {
return Err(EngineError::Other(crate::script::refused_text(id)));
}
// An edit the active tool is computing on another thread (a Shape Builder merge) is
+1
View File
@@ -190,6 +190,7 @@ mod script_folder;
mod script_include;
mod script_io;
mod script_modules;
mod script_print;
mod script_run;
mod script_save_open;
mod script_scriptui;
+4 -1
View File
@@ -578,7 +578,10 @@ fn placement_options_read_set_and_round_trip() {
let mut s = session();
let id = place(&mut s, &pic);
run(&mut s, "select.set", json!({"ids": [id.0]}));
assert_eq!(run(&mut s, "links.placementOptions", json!({})), json!({"placement": {"preserve": "bounds", "align": "center", "clip": false}}));
assert_eq!(
run(&mut s, "links.placementOptions", json!({})),
json!({"ids": [id.0], "placement": {"preserve": "bounds", "align": "center", "clip": false}})
);
let r = run(&mut s, "links.placementOptions", json!({"preserve": "fill", "align": "topRight", "clip": true}));
assert_eq!(r, json!({"ids": [id.0], "placement": {"preserve": "fill", "align": "topRight", "clip": true}}));
assert!(s.execute("links.placementOptions", &json!({"preserve": "stretch"})).is_err());
+73
View File
@@ -173,6 +173,79 @@ fn ppi_overprint_preview_and_bad_params() {
}
}
/// Artboard counts, columns and rows are whole numbers in range: a fraction or a count outside
/// 1 to 1000 is an error, not rounded or clamped to one.
#[test]
fn counts_that_are_not_whole_or_out_of_range_are_errors() {
for p in [
json!({"artboards": 2.4}),
json!({"artboards": 0}),
json!({"artboards": -0.5}),
json!({"artboards": 1001}),
json!({"artboardLayout": {"columns": 2.4}}),
json!({"artboardLayout": {"columns": 1001}}),
json!({"artboardLayout": {"layout": "gridByColumn", "rows": 2.4}}),
json!({"artboardLayout": {"layout": "gridByColumn", "rows": 0.6}}),
json!({"artboardLayout": {"layout": "gridByColumn", "rows": 1000.4}}),
] {
let mut s = Session::new();
assert!(s.execute("file.new", &p).is_err(), "{p}");
assert!(s.active().is_none(), "{p}: no document on an error");
}
let s = new_doc(json!({"artboards": 6.0, "artboardLayout": {"layout": "gridByColumn", "rows": 2.0}}));
assert_eq!(s.doc().unwrap().doc.artboards.len(), 6, "a whole number written 6.0 is a count");
}
#[test]
fn replaying_a_journal_rounds_an_older_artboard_count() {
let mut recorded = new_doc(json!({"artboards": 2}));
recorded.journal.last_mut().unwrap().1["artboards"] = json!(2.4);
let mut s = Session::new();
for (id, p) in &recorded.journal {
s.replay(id, p).unwrap();
}
assert_eq!(boards(&s), boards(&recorded));
assert_eq!(boards(&s).len(), 2);
assert!(s.execute("file.new", &json!({"artboards": 2.4})).is_err());
}
#[test]
fn replayed_counts_keep_their_rounding_and_range_rules() {
for (key, value, expected) in [
("artboards", 0.0, 1),
("artboards", 1001.0, 1000),
("columns", 2.4, 2),
("columns", 1001.0, 1000),
("rows", 2.4, 2),
("rows", 0.6, 1),
("rows", 1000.4, 1000),
] {
let mut p = json!({"width": 10, "height": 10, "artboards": 4,
"artboardLayout": {"layout": "gridByColumn", "spacing": 0}});
if key == "artboards" {
p[key] = json!(value);
} else {
p["artboardLayout"][key] = json!(value);
}
let mut s = Session::new();
s.replay("file.new", &p).unwrap();
assert!(s.execute("file.new", &p).is_err(), "{p}");
if key == "artboards" {
p[key] = json!(expected);
} else {
p["artboardLayout"][key] = json!(expected);
}
assert_eq!(boards(&s), boards(&new_doc(p)));
}
for layout in [json!({"columns": 0.6}), json!({"rows": 0.4}), json!({"rows": 1000.6})] {
let mut p = json!({"artboardLayout": layout});
p["artboardLayout"]["layout"] = json!("gridByColumn");
let mut s = Session::new();
assert!(s.replay("file.new", &p).is_err(), "{p}");
assert!(s.active().is_none(), "{p}");
}
}
#[test]
fn categories_list_generated_presets_with_neutral_names() {
let mut s = Session::new();
+4 -2
View File
@@ -445,11 +445,13 @@ fn each_copys_shadow_on_type_expands_as_the_canvas_draws_it() {
let shadow = json!({"x": 20, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"});
run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "params": shadow}));
run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": {"scaleH": 200, "scaleV": 200, "moveV": 80, "copies": 1}}));
let before = render(&s);
if !(0..100u32).any(|y| (0..200u32).any(|x| before.pixel(x, y) == [255, 0, 0, 255])) {
let style = vectorcraft_doc::text::CharStyle::default();
if vectorcraft_text::FontDb::global().face(&style.font_family, &style.font_style).is_none() {
eprintln!("skipped: built without a font that draws the type");
return;
}
let before = render(&s);
assert!((0..100u32).any(|y| (0..200u32).any(|x| before.pixel(x, y) == [255, 0, 0, 255])), "the type draws in red");
// The rightmost red pixel of the copy, below the type, and 38 pt right of it the copy's shadow.
let red =
(100..200u32).flat_map(|y| (0..200u32).map(move |x| (x, y))).filter(|&(x, y)| before.pixel(x, y) == [255, 0, 0, 255]).max_by_key(|p| p.0);
+5 -1
View File
@@ -1161,7 +1161,7 @@ fn file_new_takes_the_rows_of_a_grid_by_column() {
let (plain, spaced) = (plain.with_params(&to_row, "file.new").unwrap(), spaced.with_params(&to_row, "file.new").unwrap());
assert_eq!(plain.grid_columns(), spaced.grid_columns());
let e = s.execute("file.new", &json!({"artboardLayout": {"layout": "gridByColumn", "rows": 0}})).unwrap_err().to_string();
assert!(e.contains("rows must be from 1 to 1000"), "{e}");
assert!(e.contains("rows must be a whole number from 1 to 1000"), "{e}");
for layout in ["gridByRow", "row", "column"] {
let e = s.execute("file.new", &json!({"artboardLayout": {"layout": layout, "rows": 2}})).unwrap_err().to_string();
assert!(e.contains("rows needs the gridByColumn layout"), "{layout}: {e}");
@@ -1494,6 +1494,10 @@ fn a_document_preset_is_an_instance_of_its_class() {
let mut s = Session::new();
let out = log(&mut s, "var p = new DocumentPreset(); vc.log(p instanceof DocumentPreset); vc.log(p.typename); vc.log(p.width);");
assert_eq!(out, vec![json!(true), json!("DocumentPreset"), json!(612)]);
// A named engine keeps the preset, but in a later run its type name throws, as its settings do.
run(&mut s, "#targetengine keep\nvar held = new DocumentPreset();").unwrap();
let e = failure(&mut s, "#targetengine keep\nheld.typename;");
assert!(e.contains("this is not a DocumentPreset"), "{e}");
}
/// A preset kept from an earlier run throws from `typename` and `toString()` as it does from its
+748
View File
@@ -0,0 +1,748 @@
//! Printing from a script: `Document.print` with `PrintOptions` and its option classes,
//! `app.printPresetsList`, `app.PPDFileList`, and the checks every option and the file go through.
use std::path::{Path, PathBuf};
use serde_json::{Value, json};
use crate::script::printing::{MAX_PRINTER_NAME_BYTES, MAX_PRINTERS, PreparedPrint, Printers};
use crate::*;
const DENIED: &str = "Script file access denied";
/// A test's folder, removed when the test ends, a failed assertion included.
struct Workspace(PathBuf);
impl std::ops::Deref for Workspace {
type Target = Path;
fn deref(&self) -> &Path {
&self.0
}
}
impl AsRef<Path> for Workspace {
fn as_ref(&self) -> &Path {
&self.0
}
}
impl Drop for Workspace {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// A fresh folder for test `name`, by its real path, with `main` for the script.
fn folder(name: &str) -> Workspace {
let base = std::env::temp_dir().join(format!("vc-script-print-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
std::fs::create_dir_all(base.join("main")).unwrap();
std::fs::create_dir_all(base.join("outside")).unwrap();
Workspace(std::fs::canonicalize(&base).unwrap())
}
/// A session whose scripts keep their data folders in `base/settings/Script Data`, with a
/// 300 × 200 document of two artboards holding a rectangle.
fn session(base: &Path) -> Session {
let mut s = Session::new();
s.attach_script_data(base.join("settings/Script Data"));
s.execute("file.new", &json!({"width": 300, "height": 200, "artboards": 2})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap();
s
}
/// Runs `main/main.jsx` in `base` with the text `text` in `s`.
fn run(s: &mut Session, base: &Path, text: &str) -> Result<Value> {
let main = base.join("main/main.jsx");
std::fs::write(&main, text.as_bytes()).unwrap();
s.execute("script.run", &json!({"path": main.to_string_lossy()}))
}
fn logged(s: &mut Session, base: &Path, text: &str) -> Value {
run(s, base, text).unwrap_or_else(|e| panic!("{text}: {e}"))["log"].clone()
}
fn failure(s: &mut Session, base: &Path, text: &str) -> String {
run(s, base, text).map(|r| panic!("{text} ran: {r}")).unwrap_err().to_string()
}
/// The script's data folder, where it may write.
fn data_folder(s: &mut Session, base: &Path) -> PathBuf {
PathBuf::from(logged(s, base, "vc.log(Folder.userData.fsName);")[0].as_str().unwrap())
}
fn quoted(p: &Path) -> String {
serde_json::to_string(&p.to_string_lossy()).unwrap()
}
fn pages(path: &Path) -> Vec<(f64, f64)> {
let info = vectorcraft_pdf::info(&std::fs::read(path).unwrap(), None).unwrap();
info.pages.iter().map(|p| (p.width.round(), p.height.round())).collect()
}
#[test]
fn print_writes_the_file_with_the_assigned_options_over_the_saved_settings() {
let base = folder("happy");
let mut s = session(&base);
s.execute("print.setup", &json!({"settings": {"collate": true, "marks": {"trim": true}}})).unwrap();
let saved = s.execute("print.setup", &json!({})).unwrap()["settings"].clone();
let undo = s.active().unwrap().history.undo.len();
let dir = data_folder(&mut s, &base);
let d = quoted(&dir);
let out = logged(
&mut s,
&base,
&format!(
"Folder.userData; var dir = {d}, doc = app.activeDocument;\n\
var o = new PrintOptions(), j = new PrintJobOptions();\n\
vc.log([o.typename, j.typename, j.copies, j.collate, j.printAllArtboards, j.designation, o.coordinateOptions.typename]);\n\
o.jobOptions = j; j.copies = 2; j.file = new File(dir + '/a.pdf');\n\
j.copies = 3; vc.log([o.jobOptions.copies, j.collate]);\n\
doc.print(o);\n\
var back = o.jobOptions.file; j.file = back; vc.log([back instanceof File, back.name]);\n\
j.printAllArtboards = false; j.artboardRange = '2'; j.copies = 1; j.file = new File(dir + '/b.pdf');\n\
o.paperOptions.name = 'a4'; o.coordinateOptions.fitToPage = true; o.coordinateOptions.orientation = PrintOrientation.PORTRAIT;\n\
o.printerName = ''; o.fontOptions.downloadFonts = PrintFontDownloadMode.DOWNLOADSUBSET;\n\
doc.print(o);\n\
j.file = new File(dir + '/c.ps'); doc.print(o);\n\
o.postScriptOptions.postScriptLevel = PrinterPostScriptLevelEnum.PSLEVEL2; j.file = new File(dir + '/level2.prn');\n\
doc.print(o);\n\
vc.log([app.printPresetsList[0], app.PPDFileList.length]);"
),
);
let expected =
json!(["PrintOptions", "PrintJobOptions", 1, false, true, "PrintArtworkDesignation.VISIBLEPRINTABLELAYERS", "PrintCoordinateOptions"]);
assert_eq!(out[0], expected, "a new option object reads as its help page's defaults");
assert_eq!(out[1], json!([3, false]), "a change after the assignment is read through the PrintOptions");
assert_eq!(out[2], json!([true, "a.pdf"]), "jobOptions.file reads back as a File");
assert_eq!(out[3], json!(["[Default]", 0]));
assert_eq!(pages(&dir.join("a.pdf")).len(), 6, "two artboards, three copies");
assert_eq!(pages(&dir.join("b.pdf")), vec![(595.0, 842.0)], "artboard 2 only, on upright A4");
let ps = std::fs::read_to_string(dir.join("c.ps")).unwrap();
assert!(ps.starts_with("%!PS") && !ps.contains("%%LanguageLevel: 2"), "a .ps name alone: {}", &ps[..ps.len().min(200)]);
let ps = std::fs::read_to_string(dir.join("level2.prn")).unwrap();
assert!(ps.starts_with("%!PS") && ps.contains("%%LanguageLevel: 2"), "a level alone: {}", &ps[..ps.len().min(200)]);
assert_eq!(s.execute("print.setup", &json!({})).unwrap()["settings"], saved, "printing leaves the saved settings as they are");
assert_eq!(s.active().unwrap().history.undo.len(), undo, "and adds no undo step");
// The commands stay closed to vc.run, before and after a print.
for case in [
"vc.run('file.print', {});",
"var o = new PrintOptions(); o.jobOptions.file = new File(Folder.userData.fsName + '/d.pdf'); app.activeDocument.print(o); vc.run('file.print', {});",
"vc.run('print.setup', {settings: {copies: 5}});",
] {
let e = failure(&mut s, &base, case);
assert!(e.contains("a script cannot run"), "{case}: {e}");
}
assert_eq!(s.execute("print.setup", &json!({})).unwrap()["settings"], saved);
let _ = std::fs::remove_dir_all(base);
}
/// Without the printers a frontend lists for scripts (a run outside the app, the web), printing to
/// a printer and `app.printerList` throw, and nothing is prepared.
#[test]
fn print_without_a_file_does_not_print() {
let base = folder("no-file");
let mut s = session(&base);
for case in [
"app.activeDocument.print();",
"app.activeDocument.print(new PrintOptions());",
"var o = new PrintOptions(); o.jobOptions.copies = 2; app.activeDocument.print(o);",
"var o = new PrintOptions(); o.printerName = 'Office'; app.activeDocument.print(o);",
] {
let e = failure(&mut s, &base, case);
assert!(e.contains("Printing to a printer is not available here"), "{case}: {e}");
}
let e = failure(&mut s, &base, "app.printerList;");
assert!(e.contains("Application.printerList is not available here"), "{e}");
assert!(!s.script_prints_waiting());
let _ = std::fs::remove_dir_all(base);
}
/// The printers a frontend lists, `Office` the default, with a name a shell or a file system would
/// read as more than a name.
const ODD_NAME: &str = "Lab; rm -rf / & \\\\srv\\q $(x) ../p";
fn printers() -> Printers {
Printers::new([("Office".to_string(), true), (ODD_NAME.to_string(), false)], false)
}
/// The PDF pages a prepared job holds.
fn job_pages(job: &PreparedPrint) -> usize {
vectorcraft_pdf::info(&job.pdf, None).unwrap().pages.len()
}
/// `app.printerList` gives a `Printer` for each printer the frontend listed, at most 256 of them,
/// without names that are empty, too long, hold a control character or repeat; the list is the
/// run's own, needs an open document, and its objects go stale after the run.
#[test]
fn printer_list_is_the_bounded_list_the_frontend_gave() {
let base = folder("printer-list");
let mut s = session(&base);
let mut list: Vec<(String, bool)> = (0..300).map(|i| (format!("Printer {i}"), i == 1)).collect();
list.insert(0, ("x".repeat(MAX_PRINTER_NAME_BYTES + 1), true));
list.insert(1, ("Bad\nName".into(), false));
list.insert(2, (String::new(), false));
list.insert(3, ("Printer 5".into(), false));
let snapshot = Printers::new(list, false);
assert_eq!(snapshot.names().len(), MAX_PRINTERS);
assert_eq!(snapshot.default_name(), Some("Printer 1"));
// A default listed after the first 256 takes the last place, and a repeated name keeps a later
// default mark without a second entry.
let late = Printers::new((0..300).map(|i| (format!("Q{i}"), i == 280)), false);
let names = late.names();
assert_eq!((names.len(), late.default_name(), names[254].as_str(), names[255].as_str()), (MAX_PRINTERS, Some("Q280"), "Q254", "Q280"));
let repeat = Printers::new([("A".to_string(), false), ("B".to_string(), false), ("A".to_string(), true)], false);
assert_eq!((repeat.names(), repeat.default_name()), (&["A".to_string(), "B".to_string()][..], Some("A")));
s.script_printers = Some(snapshot);
let out = logged(
&mut s,
&base,
"#targetengine keep\nvar l = app.printerList; held = l[0];\n\
vc.log([l.length, l[0].name, l[0].typename, l[1].name, l[255].name]);\n\
try { l[0].name = 'Other'; } catch (e) {} vc.log(l[0].name);\n\
try { l[0].printerInfo; } catch (e) { vc.log(e.message); }",
);
assert_eq!(out[0], json!([256, "Printer 5", "Printer", "Printer 0", "Printer 255"]));
assert_eq!(out[1], json!("Printer 5"), "name is read-only");
assert_eq!(out[2], json!("Printer.printerInfo is not available yet"));
// The next run has no list unless the frontend gives one again.
let e = failure(&mut s, &base, "app.printerList;");
assert!(e.contains("Application.printerList is not available here"), "{e}");
s.script_printers = Some(printers());
let e = failure(&mut s, &base, "#targetengine keep\nheld.name;");
assert!(e.contains("Stale printer"), "{e}");
s.script_printers = Some(printers());
assert_eq!(logged(&mut s, &base, "vc.log(app.printerList[1].name);")[0], json!(ODD_NAME));
// With no document open there is no list.
let mut empty = Session::new();
empty.attach_script_data(base.join("settings/Script Data"));
empty.script_printers = Some(printers());
let e = failure(&mut empty, &base, "app.printerList;");
assert!(e.contains("Application.printerList needs an open document"), "{e}");
let _ = std::fs::remove_dir_all(base);
}
/// `print` without a file prepares a print-ready PDF for the printer it names, or the default one,
/// and sends nothing: the session holds the jobs once the run's changes are kept, for the frontend
/// to take. A name is matched exactly, whatever characters it holds.
#[test]
fn print_to_a_printer_holds_the_job_until_the_run_ends() {
let base = folder("prepared");
let mut s = session(&base);
s.script_printers = Some(printers());
let name = serde_json::to_string(ODD_NAME).unwrap();
let report = run(
&mut s,
&base,
&format!(
"var o = new PrintOptions(); o.printerName = {name}; o.jobOptions.copies = 2; o.jobOptions.collate = true;\n\
app.activeDocument.print(o);\n\
vc.run('shape.rectangle', {{x: 150, y: 10, width: 20, height: 20}});\n\
app.activeDocument.print();"
),
)
.unwrap();
assert_eq!(report["prints"], 2, "{report}");
assert!(s.script_prints_waiting());
let title = s.active().unwrap().title();
let jobs = s.take_script_prints();
assert!(!s.script_prints_waiting());
assert_eq!(jobs.len(), 2);
assert_eq!((jobs[0].printer.as_str(), jobs[0].sheets, job_pages(&jobs[0])), (ODD_NAME, 4, 4), "two artboards, two copies");
assert_eq!((jobs[1].printer.as_str(), jobs[1].sheets, job_pages(&jobs[1])), ("Office", 2, 2), "the default printer");
assert!(jobs.iter().all(|j| j.title == title && j.pdf.starts_with(b"%PDF")));
// Each job holds the document as it was when print was called: one copy of the second job has
// the rectangle the script added after the first job, and the first job's two copies do not.
let paths = |job: &PreparedPrint| {
let mut n = 0;
vectorcraft_pdf::import(&job.pdf).unwrap().walk(|c| n += usize::from(matches!(c.kind, vectorcraft_doc::NodeKind::Path { .. })));
n
};
assert_eq!(paths(&jobs[0]) % 2, 0, "two equal copies");
assert_eq!(paths(&jobs[0]) / 2 + 1, paths(&jobs[1]), "the second job has the added rectangle");
assert!(s.take_script_prints().is_empty(), "a job is taken once");
let _ = std::fs::remove_dir_all(base);
}
/// A run that throws, runs out of fuel or ends at a failed command keeps no job.
#[test]
fn a_run_that_fails_keeps_no_print_job() {
let base = folder("rollback");
let mut s = session(&base);
let objects = s.active().unwrap().doc.layers[0].children().map_or(0, Vec::len);
for case in [
"app.activeDocument.print(); throw new Error('late');",
"app.activeDocument.print(); vc.run('no.such.command', {});",
"app.activeDocument.print(); app.activeDocument.print(); app.activeDocument.print(); app.activeDocument.print(); app.activeDocument.print();",
] {
s.script_printers = Some(printers());
failure(&mut s, &base, case);
assert!(!s.script_prints_waiting(), "{case}");
}
s.script_printers = Some(printers());
let stopped = s.execute("script.run", &json!({"source": "app.activeDocument.print(); while (true) {}", "name": "t.js", "maxFuel": 2_000_000}));
assert!(stopped.is_err());
assert!(s.take_script_prints().is_empty());
assert_eq!(s.active().unwrap().doc.layers[0].children().map_or(0, Vec::len), objects);
let _ = std::fs::remove_dir_all(base);
}
/// A name that is not exactly a listed printer's, a list with no default, PostScript, more jobs or
/// sheets than a run may prepare and jobs an earlier run left waiting all throw, and nothing is
/// prepared; a file wins over a printer name.
#[test]
fn print_to_a_printer_refuses_what_it_cannot_send() {
let base = folder("refuse");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
let cases = [
("o.printerName = 'office';", "PrintOptions.printerName names no installed printer: office"),
("o.printerName = 'Offic';", "names no installed printer: Offic"),
("o.printerName = ' Office';", "names no installed printer: Office"),
("o.printerName = 'Office\\n';", "names no installed printer"),
("o.postScriptOptions.postScriptLevel = PrinterPostScriptLevelEnum.PSLEVEL2;", "PostScript prints only to a file"),
("o.jobOptions.copies = 51;", "at most 100 sheets in a run; this job has 102"),
("for (var i = 0; i < 4; i++) app.activeDocument.print(o);", "at most 4 jobs to a printer in a run"),
("o.printPreset = 'Nope';", "printPreset names no print preset"),
];
for (case, part) in cases {
s.script_printers = Some(printers());
let e = failure(&mut s, &base, &format!("var o = new PrintOptions(); {case} app.activeDocument.print(o);"));
assert!(e.contains(part), "{case}: {e}");
assert!(!s.script_prints_waiting(), "{case}");
}
// A job past the sheet limit is refused before it is composed.
s.script_printers = Some(printers());
failure(&mut s, &base, "var o = new PrintOptions(); o.jobOptions.copies = 999; app.activeDocument.print(o);");
let report = s.script_report().unwrap();
let ran: Vec<&str> = report["slowestCommands"].as_array().unwrap().iter().filter_map(|c| c["id"].as_str()).collect();
assert_eq!(ran, ["file.print"], "{report}");
s.script_printers = Some(Printers::new([("Office".to_string(), false)], false));
let e = failure(&mut s, &base, "app.activeDocument.print();");
assert!(e.contains("There is no default printer: set PrintOptions.printerName"), "{e}");
// Jobs an earlier run left waiting: the next run cannot print to a printer until they are taken.
s.script_printers = Some(printers());
logged(&mut s, &base, "app.activeDocument.print();");
s.script_printers = Some(printers());
let e = failure(&mut s, &base, "app.activeDocument.print();");
assert!(e.contains("A print job from an earlier script still waits for approval"), "{e}");
assert_eq!(s.take_script_prints().len(), 1, "the earlier job is kept");
s.script_printers = Some(printers());
logged(&mut s, &base, "app.activeDocument.print();");
assert_eq!(s.take_script_prints().len(), 1);
// A file wins over the printer name.
s.script_printers = Some(printers());
let file = quoted(&dir.join("f.pdf"));
logged(
&mut s,
&base,
&format!(
"Folder.userData; var o = new PrintOptions(); o.printerName = 'Nowhere'; o.jobOptions.file = new File({file}); app.activeDocument.print(o);"
),
);
assert!(dir.join("f.pdf").exists());
assert!(!s.script_prints_waiting());
let _ = std::fs::remove_dir_all(base);
}
/// The pages of a job for a printer are counted from the art as it prints, artboard backgrounds
/// included, as `file.print` lays it out: an artboard that holds only its background prints with
/// `skipBlank`, and counts toward the sheet limit.
#[test]
fn print_to_a_printer_counts_the_pages_of_the_art_as_it_prints() {
let base = folder("backgrounds");
let mut s = session(&base);
s.execute("artboard.setProps", &json!({"index": 1, "color": "#ff0000"})).unwrap();
s.execute("print.setup", &json!({"settings": {"skipBlank": true, "artboards": "range", "range": "2"}})).unwrap();
s.script_printers = Some(printers());
logged(&mut s, &base, "app.activeDocument.print();");
let jobs = s.take_script_prints();
assert_eq!(jobs.iter().map(|j| (j.sheets, job_pages(j))).collect::<Vec<_>>(), [(1, 1)], "the background prints");
s.execute("print.setup", &json!({"settings": {"artboards": "all"}})).unwrap();
s.script_printers = Some(printers());
let e = failure(&mut s, &base, "var o = new PrintOptions(); o.jobOptions.copies = 51; app.activeDocument.print(o);");
assert!(e.contains("this job has 102"), "both artboards print: {e}");
assert!(!s.script_prints_waiting());
let _ = std::fs::remove_dir_all(base);
}
/// `file.print`'s `maxPages` composes nothing for a longer job, and only after the other params are
/// checked.
#[test]
fn file_print_max_pages_composes_only_what_fits() {
let base = folder("max-pages");
let mut s = session(&base);
let r = s.execute("file.print", &json!({"maxPages": 5, "settings": {"copies": 3}})).unwrap();
assert_eq!((&r["pages"], r.get("dataBase64").is_none()), (&json!(6), true), "{r}");
let r = s.execute("file.print", &json!({"maxPages": 6, "settings": {"copies": 3}})).unwrap();
assert_eq!((&r["pages"], r["dataBase64"].is_string()), (&json!(6), true));
for bad in [
json!({"maxPages": 0, "format": "postscript", "level": 1}),
json!({"maxPages": 0, "settings": {"advanced": {"flattenerPreset": "nope"}}}),
json!({"maxPages": -1}),
json!({"maxPages": "2"}),
json!({"maxPages": null}),
] {
assert!(s.execute("file.print", &bad).is_err(), "{bad}");
}
let _ = std::fs::remove_dir_all(base);
}
/// Bad values throw when they are assigned, and nothing prints.
#[test]
fn print_options_refuse_bad_values() {
let base = folder("bad");
let mut s = session(&base);
let cases = [
("j.copies = 0;", "RangeError", "copies must be a whole number from 1 to 999"),
("j.copies = NaN;", "TypeError", "copies"),
("j.copies = 1e12;", "RangeError", "copies must be a whole number"),
("j.copies = 1.5;", "RangeError", "copies must be a whole number"),
("j.copies = '2';", "TypeError", "copies must be a number"),
("j.collate = 1;", "TypeError", "collate must be true or false"),
("c.horizontalScale = NaN;", "TypeError", "horizontalScale"),
("c.horizontalScale = Infinity;", "TypeError", "horizontalScale"),
("c.verticalScale = 20000;", "RangeError", "verticalScale must be from 1 to 10000"),
("c.verticalScale = 0;", "RangeError", "verticalScale must be from 1 to 10000"),
("m.trimMarksWeight = -1;", "RangeError", "trimMarksWeight must be from 0"),
("c.orientation = 'PrintOrientation.SIDEWAYS';", "TypeError", "orientation must be a PrintOrientation value"),
("c.orientation = 'PrintTiling.TILEFULLPAGES';", "TypeError", "orientation must be a PrintOrientation value"),
("j.file = 'C:/out.pdf';", "TypeError", "file must be a File"),
("j.file = {};", "TypeError", "file must be a File"),
("o.jobOptions = new PrintCoordinateOptions();", "TypeError", "jobOptions must be a PrintJobOptions"),
("o.jobOptions = {copies: 2};", "TypeError", "jobOptions must be a PrintJobOptions"),
("o.printPreset = new Array(5000).join('x');", "RangeError", "printPreset is too long"),
("app.activeDocument.print({jobOptions: j});", "TypeError", "print's options must be a PrintOptions object"),
("app.activeDocument.print(j);", "TypeError", "print's options must be a PrintOptions object"),
];
let prefix = "var o = new PrintOptions(), j = o.jobOptions, c = o.coordinateOptions, m = o.pageMarksOptions;";
for (case, kind, part) in cases {
let e = failure(&mut s, &base, &format!("{prefix} {case}"));
assert!(e.contains(kind) && e.contains(part), "{case}: {e}");
}
let _ = std::fs::remove_dir_all(base);
}
/// Options that `file.print` cannot honor throw instead of being dropped.
#[test]
fn options_that_are_not_available_throw() {
let base = folder("later");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
let file = format!("j.file = new File({});", quoted(&dir.join("x.pdf")));
let cases = [
("o.PPDName = 'Generic';", "PrintOptions.PPDName is not available yet"),
("o.PPDName = '/etc/cups/ppd/office.ppd';", "PrintOptions.PPDName is not available yet"),
("j.name = 'Job';", "PrintJobOptions.name is not available yet"),
("j.printArea = PrintingBounds.ARTWORKBOUNDS;", "PrintingBounds.ARTWORKBOUNDS is not available yet"),
("o.colorSeparationOptions.colorSeparationMode = PrintColorSeparationMode.INRIPSEPARATION;", "INRIPSEPARATION is not available yet"),
("o.colorManagementOptions.colorProfileMode = PrintColorProfile.PRINTERPROFILE;", "PRINTERPROFILE is not available yet"),
("o.colorSeparationOptions.inkList = [];", "PrintColorSeparationOptions.inkList is not available yet"),
("o.fontOptions.downloadFonts = PrintFontDownloadMode.DOWNLOADCOMPLETE;", "PrintFontOptions.downloadFonts is not available yet"),
("o.flattenerOptions.rasterizationResolution = 600;", "PrintFlattenerOptions.rasterizationResolution is not available yet"),
("o.flattenerOptions.rasterizationResolution = NaN;", "PrintFlattenerOptions.rasterizationResolution"),
("o.pageMarksOptions.bleedOffsetRect = [0, 0, 0, 0];", "PrintPageMarksOptions.bleedOffsetRect is not available yet"),
("o.paperOptions.offset = 10;", "PrintPaperOptions.offset is not available yet"),
("o.postScriptOptions.postScriptLevel = PrinterPostScriptLevelEnum.PSLEVEL1;", "PSLEVEL1 is not available yet"),
("o.postScriptOptions.binaryPrinting = true;", "PrintPostScriptOptions.binaryPrinting is not available yet"),
(
&format!("{file} o.coordinateOptions.horizontalScale = 2000; app.activeDocument.print(o);"),
"horizontalScale above 1000 is not available yet",
),
];
let prefix = "Folder.userData; var o = new PrintOptions(), j = o.jobOptions;";
for (case, part) in cases {
let e = failure(&mut s, &base, &format!("{prefix} {case}"));
assert!(e.contains(part), "{case}: {e}");
}
assert!(!dir.join("x.pdf").exists(), "nothing printed");
// With Fit to Page on, the scale factors are not used, so a factor above 1000 does not stop the job.
let out = logged(
&mut s,
&base,
&format!(
"{prefix} {file} var c = o.coordinateOptions; c.horizontalScale = 2000; c.verticalScale = 2000; c.fitToPage = true;\
app.activeDocument.print(o); vc.log(true);"
),
);
assert_eq!(out, json!([true]));
assert!(dir.join("x.pdf").exists(), "the fitted job printed");
let _ = std::fs::remove_dir_all(base);
}
/// A panic while `print` has the fence open for `file.print` closes it again for the next run.
#[test]
fn a_panic_while_printing_leaves_the_fence_closed() {
let base = folder("panic-unfenced");
let mut s = session(&base);
let print = "var o = new PrintOptions(); o.jobOptions.file = new File(Folder.userData.fsName + '/p.pdf'); app.activeDocument.print(o);";
crate::script::PANIC_WHILE_UNFENCED.with(|p| p.set(true));
let r = run(&mut s, &base, print);
crate::script::PANIC_WHILE_UNFENCED.with(|p| p.set(false));
let e = r.map(|r| panic!("the print ran: {r}")).unwrap_err().to_string();
assert!(e.contains("a command past the fence failed"), "the run ends at the panic: {e}");
let e = failure(&mut s, &base, "vc.run('file.print', {});");
assert!(e.contains("a script cannot run"), "{e}");
}
#[test]
fn print_writes_only_where_the_script_may() {
let base = folder("refused");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
let grants = base.join("settings/Script Grants.json");
std::fs::write(&grants, "{}").unwrap();
for target in [base.join("outside/x.pdf"), grants.clone(), dir.clone()] {
let case =
format!("Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({}); app.activeDocument.print(o);", quoted(&target));
let e = failure(&mut s, &base, &case);
assert!(e.contains("Script file"), "{case}: {e}");
if target != dir {
assert!(e.contains(DENIED), "{case}: {e}");
}
}
assert!(!base.join("outside/x.pdf").exists());
assert_eq!(std::fs::read_to_string(&grants).unwrap(), "{}");
let _ = std::fs::remove_dir_all(base);
}
/// A print to a file a `File` object holds open for writing throws, so the object's bytes written at
/// the end of the run do not replace the printed file.
#[test]
fn print_does_not_write_a_file_open_for_writing() {
let base = folder("openhandle");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
let p = quoted(&dir.join("x.pdf"));
let log = logged(
&mut s,
&base,
&format!(
"Folder.userData; var w = new File({p}); w.open('w'); w.write('pending');\nvar o = new PrintOptions(); o.jobOptions.file = new File({p});\ntry {{ app.activeDocument.print(o); vc.log('ran'); }} catch (e) {{ vc.log(e.message); }}"
),
);
assert!(log[0].as_str().unwrap().contains(crate::script::files::OPEN_FOR_WRITING), "{log}");
assert_eq!(std::fs::read_to_string(dir.join("x.pdf")).unwrap(), "pending", "the File's own bytes");
let _ = std::fs::remove_dir_all(base);
}
/// One assigned scale factor leaves the other at the document's saved value.
#[test]
fn one_assigned_scale_factor_keeps_the_saved_other() {
let base = folder("scale");
let mut s = session(&base);
let common = json!({"media": "letter", "autoRotate": false, "orientation": "portrait", "artboards": "range", "range": "1"});
let mut saved = common.clone();
saved["scale"] = json!({"width": 100, "height": 500, "linked": false});
s.execute("print.setup", &json!({"settings": saved})).unwrap();
let dir = data_folder(&mut s, &base);
let mut expected = common;
expected["scaling"] = json!("tileFull");
expected["scale"] = json!({"width": 400, "height": 500, "linked": false});
let want = s.execute("file.print", &json!({"settings": expected, "path": dir.join("want.pdf").to_string_lossy()})).unwrap();
logged(
&mut s,
&base,
&format!(
"Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({});\n\
o.coordinateOptions.horizontalScale = 400; o.coordinateOptions.tiling = PrintTiling.TILEFULLPAGES;\n\
app.activeDocument.print(o);",
quoted(&dir.join("got.pdf"))
),
);
let got = pages(&dir.join("got.pdf"));
assert_eq!(got.len() as u64, want["pages"].as_u64().unwrap(), "the saved vertical scale of 500% is kept");
assert!(got.len() >= 4, "1200 by 1000 pt of art tiles over at least four letter pages: {got:?}");
let _ = std::fs::remove_dir_all(base);
}
/// An assigned `artboardRange` replaces a saved range, an assigned `printArea` prints by artboard over
/// saved settings that ignore the artboards, and two scale factors that differ by any amount print
/// unlinked.
#[test]
fn assigned_job_and_scale_options_apply_over_the_saved_settings() {
let base = folder("over-saved");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
let print = |s: &mut Session, name: &str, body: &str| {
let file = quoted(&dir.join(name));
logged(
s,
&base,
&format!("Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({file}); {body} app.activeDocument.print(o);"),
);
pages(&dir.join(name)).len()
};
s.execute("print.setup", &json!({"settings": {"artboards": "range", "range": "1"}})).unwrap();
assert_eq!(print(&mut s, "saved.pdf", ""), 1, "the saved range");
assert_eq!(print(&mut s, "range.pdf", "o.jobOptions.artboardRange = '1-2';"), 2, "the assigned range replaces the saved one");
s.execute("print.setup", &json!({"settings": {"artboards": "ignore"}})).unwrap();
assert_eq!(print(&mut s, "ignore.pdf", ""), 1, "all the art as one page");
assert_eq!(print(&mut s, "area.pdf", "o.jobOptions.printArea = PrintingBounds.ARTBOARDBOUNDS;"), 2, "each artboard prints");
assert_eq!(print(&mut s, "range-ignored.pdf", "o.jobOptions.artboardRange = '2';"), 1, "a range alone keeps ignoring the artboards");
let area_range = "o.jobOptions.printArea = PrintingBounds.ARTBOARDBOUNDS; o.jobOptions.artboardRange = '2';";
assert_eq!(print(&mut s, "area-range.pdf", area_range), 1, "printArea with a range prints the range");
let scaled = "o.coordinateOptions.horizontalScale = 100; o.coordinateOptions.verticalScale = 100.0000000005;";
assert!(print(&mut s, "scale.pdf", scaled) >= 1, "factors that differ by a tiny amount print unlinked");
assert_eq!(s.execute("print.setup", &json!({})).unwrap()["settings"]["artboards"], json!("ignore"), "the saved settings stay");
let _ = std::fs::remove_dir_all(base);
}
/// The format follows the name `jobOptions.file` gives, not the extension of the file a link in the
/// granted folder leads to.
#[cfg(unix)]
#[test]
fn the_format_follows_the_name_the_script_gives() {
let base = folder("format-name");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
std::fs::write(dir.join("proof.pdf"), "old").unwrap();
std::os::unix::fs::symlink(dir.join("proof.pdf"), dir.join("proof.ps")).unwrap();
logged(
&mut s,
&base,
&format!(
"Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({}); app.activeDocument.print(o);",
quoted(&dir.join("proof.ps"))
),
);
let written = std::fs::read(dir.join("proof.pdf")).unwrap();
assert!(written.starts_with(b"%!PS"), "PostScript for a .ps name: {:?}", String::from_utf8_lossy(&written[..written.len().min(40)]));
let _ = std::fs::remove_dir_all(base);
}
/// Artboard ranges the document does not hold and preset names that are not presets, such as
/// paths, throw before anything is written.
#[test]
fn print_refuses_ranges_and_preset_names_it_cannot_honor() {
let base = folder("names");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
let file = format!("j.file = new File({});", quoted(&dir.join("x.pdf")));
let cases = [
("j.printAllArtboards = false; j.artboardRange = '3';", "RangeError", "artboardRange: range `3`"),
("j.printAllArtboards = false; j.artboardRange = '0-1';", "RangeError", "artboardRange"),
("j.printAllArtboards = false; j.artboardRange = '../../outside';", "RangeError", "artboardRange"),
("j.printAllArtboards = false; j.artboardRange = '2-1';", "RangeError", "artboardRange"),
("j.artboardRange = '3';", "RangeError", "artboardRange: range `3`"),
("o.printPreset = 'Office';", "Error", "printPreset names no print preset: Office"),
(&format!("o.printPreset = {};", quoted(&base.join("settings/Script Grants.json"))), "Error", "printPreset names no print preset"),
("o.printPreset = '../../preset';", "Error", "printPreset names no print preset"),
("o.flattenerPreset = '/etc/passwd';", "Error", "flattenerPreset names no flattener preset"),
(&format!("o.flattenerPreset = {};", quoted(&base.join("outside/f.xml"))), "Error", "flattenerPreset names no flattener preset"),
];
let prefix = format!("Folder.userData; var o = new PrintOptions(), j = o.jobOptions; {file}");
for (case, kind, part) in cases {
let e = failure(&mut s, &base, &format!("{prefix} {case} app.activeDocument.print(o);"));
assert!(e.contains(kind) && e.contains(part), "{case}: {e}");
}
assert!(!dir.join("x.pdf").exists(), "nothing printed");
// The names the lists give print, in any case.
logged(&mut s, &base, &format!("{prefix} o.printPreset = '[default]'; o.flattenerPreset = 'high resolution'; app.activeDocument.print(o);"));
assert!(dir.join("x.pdf").exists());
let _ = std::fs::remove_dir_all(base);
}
/// A color profile, a paper or a preset name that is empty, path-shaped, holds a control character
/// or is not on its list throws before anything is written; a listed name in any case prints.
#[test]
fn print_refuses_profile_paper_and_blank_preset_names() {
let base = folder("profile-paper");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
let file = format!("j.file = new File({});", quoted(&dir.join("x.pdf")));
let profile = "PrintColorManagementOptions.name names no color profile";
let paper = "PrintPaperOptions.name names no paper";
let cases = [
("c.name = '../sRGB IEC61966-2.1';", profile),
("c.name = 'C:/Windows/System32/spool/drivers/color/sRGB IEC61966-2.1';", profile),
("c.name = '\\\\\\\\server\\\\share\\\\cmyk.icc';", profile),
("c.name = 'No Such Profile';", profile),
("c.colorProfileMode = PrintColorProfile.SOURCEPROFILE; c.name = '../cmyk.icc';", profile),
("c.name = ' ';", "PrintColorManagementOptions.name must name a color profile"),
("p.name = '../letter';", paper),
("p.name = 'let\\u0007ter';", paper),
("p.name = '\\tA4\\n';", paper),
("o.printPreset = '[Default]\\n';", "PrintOptions.printPreset names no print preset"),
("p.name = 'Office Tray 2';", paper),
("p.name = '';", "PrintPaperOptions.name must name a paper"),
("p.name = 'a4'; p.width = 300;", "PrintPaperOptions.width and height apply only to custom paper, not a4"),
("o.flattenerPreset = ' ';", "PrintOptions.flattenerPreset must name a flattener preset"),
("o.flattenerPreset = '';", "PrintOptions.flattenerPreset must name a flattener preset"),
("o.printPreset = ' ';", "PrintOptions.printPreset must name a print preset"),
];
let prefix = format!("Folder.userData; var o = new PrintOptions(), j = o.jobOptions, c = o.colorManagementOptions, p = o.paperOptions; {file}");
for (case, part) in cases {
let e = failure(&mut s, &base, &format!("{prefix} {case} app.activeDocument.print(o);"));
assert!(e.contains(part), "{case}: {e}");
}
assert!(!dir.join("x.pdf").exists(), "nothing printed");
// Listed names print in any case and with spaces around them.
logged(
&mut s,
&base,
&format!(
"{prefix} c.colorProfileMode = PrintColorProfile.CUSTOMPROFILE; c.name = 'srgb iec61966-2.1'; p.name = ' A4 ';\n\
o.printPreset = ' [Default] '; o.flattenerPreset = ' High Resolution '; app.activeDocument.print(o);"
),
);
let sizes = pages(&dir.join("x.pdf"));
assert!(!sizes.is_empty() && sizes.iter().all(|&(w, h)| [(595.0, 842.0), (842.0, 595.0)].contains(&(w, h))), "A4: {sizes:?}");
// A custom paper takes the assigned size.
let custom = format!(
"Folder.userData; var o = new PrintOptions(), p = o.paperOptions; o.jobOptions.file = new File({});\n\
p.name = 'Custom'; p.width = 360; p.height = 504; o.coordinateOptions.orientation = PrintOrientation.PORTRAIT;\n\
app.activeDocument.print(o);",
quoted(&dir.join("custom.pdf"))
);
logged(&mut s, &base, &custom);
let sizes = pages(&dir.join("custom.pdf"));
assert!(!sizes.is_empty() && sizes.iter().all(|&size| size == (360.0, 504.0)), "custom: {sizes:?}");
let _ = std::fs::remove_dir_all(base);
}
/// Each warning `file.print` gives goes to the Script Console.
#[test]
fn print_writes_its_warnings_to_the_script_console() {
let base = folder("warnings");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
let settings = json!({"color": {"profile": "sRGB IEC61966-2.1"}});
let want =
s.execute("file.print", &json!({"format": "postscript", "settings": settings, "path": dir.join("want.ps").to_string_lossy()})).unwrap();
let warnings: Vec<String> = want["warnings"].as_array().unwrap().iter().map(|w| format!("Document.print: {}", w.as_str().unwrap())).collect();
assert!(warnings.iter().any(|w| w.contains("printer profile")), "{want}");
let report = run(
&mut s,
&base,
&format!(
"Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({});\n\
o.colorManagementOptions.name = 'sRGB IEC61966-2.1'; o.postScriptOptions.postScriptLevel = PrinterPostScriptLevelEnum.PSLEVEL3;\n\
app.activeDocument.print(o);",
quoted(&dir.join("got.ps"))
),
)
.unwrap();
assert_eq!(report["console"]["lines"], json!(warnings));
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn option_objects_are_bounded_and_go_stale_after_their_run() {
let base = folder("bounds");
let mut s = session(&base);
let e = failure(&mut s, &base, "for (var i = 0; i < 1000; i++) new PrintJobOptions();");
assert!(e.contains("RangeError") && e.contains("at most 256 print option objects"), "{e}");
let e = failure(&mut s, &base, "var o = new PrintOptions(); for (var i = 0; i < 1000; i++) o.jobOptions = new PrintJobOptions();");
assert!(e.contains("at most 256"), "{e}");
// A named engine keeps its globals, but an option object from an earlier run is stale.
run(&mut s, &base, "#targetengine keep\nvar held = new PrintOptions();").unwrap();
let e = failure(&mut s, &base, "#targetengine keep\nnew PrintOptions(); held.printPreset;");
assert!(e.contains("Stale print options"), "{e}");
let e = failure(&mut s, &base, "#targetengine keep\napp.activeDocument.print(held);");
assert!(e.contains("Stale print options"), "{e}");
let e = failure(&mut s, &base, "#targetengine keep\nvar o = new PrintOptions(); o.jobOptions = held.jobOptions;");
assert!(e.contains("Stale print options"), "{e}");
let _ = std::fs::remove_dir_all(base);
}
@@ -644,6 +644,24 @@ fn a_link_out_of_the_granted_folder_is_refused() {
let _ = std::fs::remove_dir_all(base);
}
/// Without options, `saveAs` takes the format from the path the script names, not from the file a
/// link at that path leads to.
#[cfg(unix)]
#[test]
fn save_as_takes_the_format_of_the_named_path_through_a_link() {
let base = folder("link-format");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
std::fs::write(dir.join("target.pdf"), "old").unwrap();
std::os::unix::fs::symlink(dir.join("target.pdf"), dir.join("drawing.svg")).unwrap();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
logged(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&dir.join("drawing.svg"))));
let written = std::fs::read(dir.join("target.pdf")).unwrap();
assert!(!written.starts_with(b"%PDF"), "the named .svg path writes SVG, not PDF");
assert!(String::from_utf8_lossy(&written).contains("<svg"), "an SVG file");
let _ = std::fs::remove_dir_all(base);
}
/// Bad arguments throw before anything is written or opened.
#[test]
fn bad_arguments_are_refused_with_an_error() {
+29 -8
View File
@@ -729,7 +729,9 @@ fn a_temporary_file_starts_private() {
}
/// A replaced sidecar that had no access ACL takes none from its folder's default ACL, whose named
/// users the sidecar's group bits would let in. (Skipped where `setfacl` or ACLs are missing.)
/// users the sidecar's group bits would let in. The default ACL is set through its extended
/// attribute, so the test runs where the `acl` tools are not installed. (Skipped on a file system
/// without ACLs.)
#[cfg(target_os = "linux")]
#[test]
fn a_replaced_sidecar_takes_no_inherited_acl() {
@@ -741,11 +743,28 @@ fn a_replaced_sidecar_takes_no_inherited_acl() {
&format!("var p = Folder.userData.fsName + '/a.xmp'; var f = new File(p); f.open('w'); f.write({PACKET:?}); f.close(); vc.log(p);"),
);
let path = PathBuf::from(log[0].as_str().unwrap());
let set = std::process::Command::new("setfacl").args(["-d", "-m", "u:nobody:rw"]).arg(path.parent().unwrap()).status();
if !set.is_ok_and(|s| s.success()) {
let _ = std::fs::remove_dir_all(base);
return;
let parent = path.parent().unwrap();
// `u::rw-,u:nobody:rw-,g::r--,m::rw-,o::r--` as the kernel's attribute: version 2, then tag,
// permissions and id per entry.
let mut acl = 2u32.to_le_bytes().to_vec();
for (tag, perm, id) in [(0x01u16, 6u16, u32::MAX), (0x02, 6, 65534), (0x04, 4, u32::MAX), (0x10, 6, u32::MAX), (0x20, 4, u32::MAX)] {
acl.extend(tag.to_le_bytes());
acl.extend(perm.to_le_bytes());
acl.extend(id.to_le_bytes());
}
match rustix::fs::setxattr(parent, "system.posix_acl_default", &acl, rustix::fs::XattrFlags::empty()) {
Ok(()) => {}
Err(e) if e == rustix::io::Errno::NOTSUP => {
let _ = std::fs::remove_dir_all(base);
return;
}
Err(e) => panic!("setting the default ACL: {e}"),
}
let mut buf = vec![0u8; 4096];
let probe = parent.join("probe");
std::fs::write(&probe, b"").unwrap();
assert!(rustix::fs::getxattr(&probe, "system.posix_acl_access", &mut buf[..]).is_ok(), "a new file takes the default ACL");
std::fs::remove_file(&probe).unwrap();
logged(
&mut s,
&base,
@@ -753,9 +772,11 @@ fn a_replaced_sidecar_takes_no_inherited_acl() {
var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m); x.closeFile();",
);
assert!(std::fs::read_to_string(&path).unwrap().contains("<dc:format>changed</dc:format>"));
let acl = std::process::Command::new("getfacl").args(["--omit-header", "--absolute-names"]).arg(&path).output().unwrap();
let acl = String::from_utf8_lossy(&acl.stdout);
assert!(!acl.contains("nobody"), "the replacement takes no ACL entry the sidecar lacked: {acl}");
assert_eq!(
rustix::fs::getxattr(&path, "system.posix_acl_access", &mut buf[..]),
Err(rustix::io::Errno::NODATA),
"the replacement takes no ACL entry the sidecar lacked"
);
let _ = std::fs::remove_dir_all(base);
}
@@ -37,6 +37,7 @@ const OUTSIDE: &[(&str, &str, &str)] = &[
("Folder.prototype.remove", "var d = new Folder(p); d.remove();", "filesWritten"),
("Folder.prototype.rename", "var d = new Folder(p); d.rename(q);", "filesWritten"),
("Folder.prototype.execute", "var d = new Folder(p); d.execute();", "filesOpened"),
("Document.prototype.print", "var o = new PrintOptions(); o.jobOptions.file = new File(p); app.activeDocument.print(o);", "filesWritten"),
("Document.prototype.exportVariables", "app.activeDocument.exportVariables(f);", "filesWritten"),
("ExternalObject", "var lib = new ExternalObject(n);", "nativeCode"),
("Document.prototype.saveAs", "app.activeDocument.saveAs(f);", "filesWritten"),
@@ -98,8 +99,9 @@ const INSIDE: &[(&str, &str)] = &[
(
"Application.prototype.",
"activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents doScript \
executeMenuCommand getIsFileOpen loadAction loadAction= open redo redraw selection selection= selectTool textFonts \
toString typename undo unloadAction unloadAction= userInteractionLevel userInteractionLevel=",
executeMenuCommand getIsFileOpen loadAction loadAction= open PPDFileList printPresetsList printerList redo redraw \
selection selection= selectTool textFonts toString typename undo unloadAction unloadAction= userInteractionLevel \
userInteractionLevel=",
),
("DocumentPreset.", "prototype"),
(
@@ -279,6 +281,88 @@ const INSIDE: &[(&str, &str)] = &[
("PDFOverprint.", "DISCARDPDFOVERPRINT PRESERVEPDFOVERPRINT"),
("SaveOptions.", "DONOTSAVECHANGES PROMPTTOSAVECHANGES"),
("UserInteractionLevel.", "DISPLAYALERTS DONTDISPLAYALERTS"),
// The print option classes and the enumerations of printing.
(
"",
"FontSubstitutionPolicy PageMarksTypes PostScriptImageCompressionType PrintArtworkDesignation PrintColorIntent \
PrintColorManagementOptions PrintColorProfile PrintColorSeparationMode PrintColorSeparationOptions \
PrintCoordinateOptions PrintFlattenerOptions PrintFontDownloadMode PrintFontOptions PrintJobOptions PrintOptions \
PrintOrientation PrintPageMarksOptions PrintPaperOptions PrintPosition PrintPostScriptOptions PrintTiling \
Printer PrinterPostScriptLevelEnum PrintingBounds",
),
("Printer.", "prototype"),
("Printer.prototype.", "constructor name printerInfo printerInfo= typename"),
("PrintOptions.", "prototype"),
(
"PrintOptions.prototype.",
"PPDName PPDName= colorManagementOptions colorManagementOptions= colorSeparationOptions colorSeparationOptions= \
constructor coordinateOptions coordinateOptions= flattenerOptions flattenerOptions= flattenerPreset \
flattenerPreset= fontOptions fontOptions= jobOptions jobOptions= pageMarksOptions pageMarksOptions= paperOptions \
paperOptions= postScriptOptions postScriptOptions= printPreset printPreset= printerName printerName= typename",
),
("PrintJobOptions.", "prototype"),
(
"PrintJobOptions.prototype.",
"artboardRange artboardRange= bitmapResolution bitmapResolution= collate collate= constructor copies copies= \
designation designation= file file= name name= printAllArtboards printAllArtboards= printArea printArea= \
printAsBitmap printAsBitmap= reversePages reversePages= typename",
),
("PrintColorManagementOptions.", "prototype"),
("PrintColorManagementOptions.prototype.", "colorProfileMode colorProfileMode= constructor intent intent= name name= typename"),
("PrintColorSeparationOptions.", "prototype"),
(
"PrintColorSeparationOptions.prototype.",
"colorSeparationMode colorSeparationMode= constructor convertSpotColors convertSpotColors= inkList inkList= \
overPrintBlack overPrintBlack= typename",
),
("PrintCoordinateOptions.", "prototype"),
(
"PrintCoordinateOptions.prototype.",
"constructor emulsion emulsion= fitToPage fitToPage= horizontalScale horizontalScale= orientation orientation= \
position position= tiling tiling= typename verticalScale verticalScale=",
),
("PrintFlattenerOptions.", "prototype"),
(
"PrintFlattenerOptions.prototype.",
"clipComplexRegions clipComplexRegions= constructor convertStrokesToOutlines convertStrokesToOutlines= \
convertTextToOutlines convertTextToOutlines= flatteningBalance flatteningBalance= gradientResolution \
gradientResolution= overprint overprint= rasterizationResolution rasterizationResolution= typename",
),
("PrintFontOptions.", "prototype"),
("PrintFontOptions.prototype.", "constructor downloadFonts downloadFonts= fontSubstitution fontSubstitution= typename"),
("PrintPageMarksOptions.", "prototype"),
(
"PrintPageMarksOptions.prototype.",
"bleedOffsetRect bleedOffsetRect= colorBars colorBars= constructor marksOffsetRect marksOffsetRect= pageInfoMarks \
pageInfoMarks= pageMarksType pageMarksType= registrationMarks registrationMarks= trimMarks trimMarks= \
trimMarksWeight trimMarksWeight= typename",
),
("PrintPaperOptions.", "prototype"),
("PrintPaperOptions.prototype.", "constructor height height= name name= offset offset= transverse transverse= typename width width="),
("PrintPostScriptOptions.", "prototype"),
(
"PrintPostScriptOptions.prototype.",
"binaryPrinting binaryPrinting= compatibleShading compatibleShading= constructor forceContinuousTone \
forceContinuousTone= imageCompression imageCompression= negativePrinting negativePrinting= postScriptLevel \
postScriptLevel= shadingResolution shadingResolution= typename",
),
("FontSubstitutionPolicy.", "SUBSTITUTEDEVICE SUBSTITUTEOBLIQUE SUBSTITUTETINT"),
("PageMarksTypes.", "Japanese Roman"),
("PostScriptImageCompressionType.", "IMAGECOMPRESSIONNONE JPEG RLE"),
("PrintArtworkDesignation.", "ALLLAYERS VISIBLELAYERS VISIBLEPRINTABLELAYERS"),
("PrintColorIntent.", "ABSOLUTECOLORIMETRIC PERCEPTUALINTENT RELATIVECOLORIMETRIC SATURATIONINTENT"),
("PrintColorProfile.", "CUSTOMPROFILE OLDSTYLEPROFILE PRINTERPROFILE SOURCEPROFILE"),
("PrintColorSeparationMode.", "COMPOSITE HOSTBASEDSEPARATION INRIPSEPARATION"),
("PrintFontDownloadMode.", "DOWNLOADCOMPLETE DOWNLOADNONE DOWNLOADSUBSET"),
("PrintOrientation.", "AUTOROTATE LANDSCAPE PORTRAIT REVERSELANDSCAPE REVERSEPORTRAIT"),
(
"PrintPosition.",
"TRANSLATEBOTTOM TRANSLATEBOTTOMLEFT TRANSLATEBOTTOMRIGHT TRANSLATECENTER TRANSLATELEFT TRANSLATERIGHT TRANSLATETOP \
TRANSLATETOPLEFT TRANSLATETOPRIGHT",
),
("PrintTiling.", "TILEFULLPAGES TILEIMAGEABLEAREAS TILESINGLEFULLPAGE"),
("PrinterPostScriptLevelEnum.", "PSLEVEL1 PSLEVEL2 PSLEVEL3"),
("PrintingBounds.", "ARTBOARDBOUNDS ARTWORKBOUNDS"),
(
"",
"CharacterAttributes CharacterStyle CharacterStyleAttributes CharacterStyles Characters Justification \
+6 -1
View File
@@ -378,7 +378,7 @@ impl<'a> Reader<'a> {
}
}
"Xw" => self.gs.hidden = Self::nums(&vals).last() == Some(&1.0),
"A" => self.gs.locked = Self::nums(&vals).last() == Some(&1.0),
"A" => self.gs.locked = Self::nums(&vals).last().is_some_and(|&v| v != 0.0),
"XW" => self.state_marker(&vals, hidden),
// Gradients.
"Bd" => self.gradient_def = GradientDef::begin(&vals, &mut self.names),
@@ -978,9 +978,14 @@ impl<'a> Reader<'a> {
let Some(mut look) = f.children.pop() else { return };
let state = (look.opacity, look.blend, look.isolate, look.knockout, look.knockout_shape);
(look.opacity, look.blend, look.isolate, look.knockout, look.knockout_shape) = (1.0, BlendMode::Normal, false, Knockout::Neutral, false);
let (visible, locked) = (object.visible, object.locked);
(object.opacity, object.blend, object.isolate, object.knockout_shape) = (1.0, BlendMode::Normal, false, false);
object.visible = true;
object.locked = false;
let mut group = Node::group(self.doc.alloc_id(), vec![Arc::new(look), Arc::new(object)]);
(group.opacity, group.blend, group.isolate, group.knockout, group.knockout_shape) = state;
group.visible = visible;
group.locked = locked;
self.text_looks.insert(group.id);
if let Some(f) = self.frames.last_mut() {
f.children.push(group);
+29
View File
@@ -12411,6 +12411,35 @@ fn type_with_an_art_brush_keeps_its_drawn_look() {
assert_eq!(brushed, 0, "{:?}", r.warnings);
}
/// A hidden styled text wrapper group inherits hidden state while its inner text and look retain
/// intrinsic visibility, so showing the group makes the inner artwork visible.
#[test]
fn hidden_styled_text_look_wrapper_group_showing_reveals_inner_text() {
let own: String = "/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n7 /StoryIndex ,\n;\n".lines().map(|l| format!("%_{l}\n")).collect();
let object = format!(
"0 Ae\nu\n/AI11Text :\n1 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\n{RED}{}f\nU\n0 0.5 0 0 0 Xy\n0 0 Xd\n6 () XW\n1 Xw\n1 A\n{own}1 (Inked) XW\n0 Xw\n0 A\n",
rect_path(20.0, 18.0, 100.0, 62.0)
);
let def = format!("{}{}", lopsided_art("Ribbon art"), plugin_object(ART_BRUSH, "Ribbon", RIBBON));
let r = read_ok(&format!("{def}{}{}", art_style("Ribbon", 1.0, &STRETCHED, ""), layer(&object)));
let a = art(&r.doc);
assert_eq!(a.len(), 1, "wrapper group created: {a:#?}");
let group = &a[0];
assert!(!group.visible, "wrapper group must inherit hidden state");
assert!(group.locked, "wrapper group must inherit locked state");
let children = group.children().expect("must be a group of look and text");
assert_eq!(children.len(), 2);
for child in children {
assert!(child.visible, "inner child must retain intrinsic visibility");
assert!(!child.locked, "inner child must not be locked");
}
let mut shown = (**group).clone();
shown.visible = true;
for child in shown.children().unwrap() {
assert!(child.visible, "inner child remains visible when parent group is shown");
}
}
/// Each copy a Scatter brush places is its section's art turned over before the copy's rotation:
/// the side of the section with y up goes down the page with the rotation at 0° to the page, and
/// to the right of the path's direction when the rotation follows the path. A rotation turns the
+1 -1
View File
@@ -43,7 +43,7 @@ use super::ate::{Story, Texts};
mod build;
pub(super) mod compare;
mod layers;
pub(super) mod layers;
mod plan;
mod slots;
+6 -4
View File
@@ -4,8 +4,8 @@ use super::compare::{
};
use super::plan::{made_only, make_slots, plan, readable_all};
use super::slots::{
ART_LEFT_OUT, Content, DREW_DIFFERENTLY, Filled, MAX_PAIRS, MAX_SLOTS, MAX_TEXT, OUTLINE_REACH, SlotInfo, TEXT_LEFT_OUT, TYPE_LEFT_OUT,
collect_slots, extent, few, fill_slots, letters, text_objects, words,
ART_LEFT_OUT, Content, DREW_DIFFERENTLY, Filled, MAX_PAIRS, MAX_PLACE_PAIRS, MAX_SLOTS, MAX_TEXT, OUTLINE_REACH, SlotInfo, TEXT_LEFT_OUT,
TYPE_LEFT_OUT, collect_slots, extent, few, fill_slots, letters, text_objects, words,
};
use super::{
Affine, Arc, BTreeSet, Document, Node, NodeId, NodeKind, PathData, Rect, Scaling, Story, Structure, Texts, Unit, VariableKind, Vec2, ai,
@@ -1514,9 +1514,11 @@ fn slot_content(
}
// The page's type is matched with every text object whose type isn't made, and weighed against
// where every made one draws: that has its limits (the slots of type that looks draw are within
// them, see `build_from`).
// them, see `build_from`). A file whose text document makes all but a few text objects is
// matched only with those few (#9176).
let open = infos.iter().zip(&made).filter(|(i, m)| i.look.is_none() && m.is_none()).count();
if open > MAX_SLOTS || infos.len().saturating_mul(pages[0].len()) > MAX_PAIRS {
let shown = pages[0].len();
if open > MAX_SLOTS || open.saturating_mul(shown) > MAX_PAIRS || infos.len().saturating_mul(shown) > MAX_PLACE_PAIRS {
return Err("it has too many text objects".into());
}
let mut content = plan(infos, stories, made, template, to_doc, pages, notes);
+83 -3
View File
@@ -172,13 +172,19 @@ pub fn layered_ai_from(
}
// The PDF part, its pages placed and named as the editing data's artboards are, when the
// layers can't be used (`why`).
let from_pdf_part = |mut visible: Document, mut warnings: Vec<String>, why: &str| {
let from_pdf_part = |mut visible: Document, mut warnings: Vec<String>, why: &str, layers_read: bool| {
let mut read = ai::Names::new(names);
let mut board_names = ai::Names::new(names);
let (boards, active) = ai::artboards(&data, &mut board_names);
if place_pages(&boards, active, &mut visible, unit) {
read.absorb(board_names);
}
// The editing data's locks, read again only here (and only when its layers could be read):
// the layers read below are spent on the editable document, which most files open as.
if let Some(layers) = layers_read.then(|| ai::read_over_page(&data, false, names).ok()).flatten() {
let private_layers: Vec<LockTree> = layers.doc.layers.iter().map(|l| LockTree::from_node(l)).collect();
apply_private_layer_locks(&mut visible.layers, &private_layers);
}
let have = visible.patterns.len();
let own_palette = use_palette(&data, &mut visible, &mut read);
use_brushes(&data, &mut visible, have, &mut warnings, &mut read);
@@ -199,7 +205,9 @@ pub fn layered_ai_from(
// The envelopes of type the page doesn't hold against layers that don't draw as it, and how many
// envelopes of type the layers had.
let (mut free, mut count) = (None, 0);
let built = structure.unwrap_or_else(|| read().map(Box::new)).and_then(|structure| {
let structure = structure.unwrap_or_else(|| read().map(Box::new));
let layers_read = structure.is_ok();
let built = structure.and_then(|structure| {
count = structure.warped_type.envelope_count();
build_weighing(*structure, &data, Some(&visible), Page::Artboard, outlined, trust, unit, &mut free, &mut text)
});
@@ -230,7 +238,7 @@ pub fn layered_ai_from(
all.extend(notes.into_iter().filter(|n| !all.contains(n)).collect::<Vec<_>>());
(done, all, true)
}
Err(why) => from_pdf_part(visible, warnings, &why),
Err(why) => from_pdf_part(visible, warnings, &why, layers_read),
}
}
@@ -245,6 +253,78 @@ fn holds_type_envelope(nodes: &[Arc<Node>]) -> bool {
})
}
/// Lightweight lock metadata snapshot of a node hierarchy, preserving names and lock states
/// without holding `Arc<Node>` references to the artwork tree.
#[derive(Clone, Debug, Default)]
pub(crate) struct LockTree {
pub name: Option<String>,
pub locked: bool,
pub children: Vec<LockTree>,
}
impl LockTree {
pub fn from_node(node: &Node) -> Self {
Self {
name: node.name.clone(),
locked: node.locked,
children: node.children().map(|kids| kids.iter().map(|k| Self::from_node(k)).collect()).unwrap_or_default(),
}
}
}
/// Match unique names between visible nodes and private lock trees.
fn unique_name_pairs<T: std::ops::Deref<Target = Node>>(vis_nodes: &[T], priv_nodes: &[LockTree]) -> Vec<(usize, usize)> {
let mut priv_names: std::collections::HashMap<&str, (usize, usize)> = std::collections::HashMap::new();
for (i, p) in priv_nodes.iter().enumerate() {
if let Some(name) = p.name.as_deref() {
let entry = priv_names.entry(name).or_insert((0, i));
entry.0 += 1;
}
}
let mut vis_names: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
for v in vis_nodes.iter() {
if let Some(name) = v.name.as_deref() {
*vis_names.entry(name).or_insert(0) += 1;
}
}
let mut pairs = Vec::new();
for (v_idx, vis) in vis_nodes.iter().enumerate() {
if let Some(name) = vis.name.as_deref()
&& vis_names.get(name).copied() == Some(1)
&& let Some(&(1, p_idx)) = priv_names.get(name)
{
pairs.push((v_idx, p_idx));
}
}
pairs
}
/// Apply lock states from private data layers to visible PDF layers.
pub(crate) fn apply_private_layer_locks(visible_layers: &mut [Arc<Node>], private_layers: &[LockTree]) {
// Only layers that are evidently the same one (a name unique on both sides) take its locks: one
// layer each is no evidence, since a PDF part without layers comes in on a layer named for its
// page, and the editing data it was set aside for may not be the art on it.
for (v_idx, p_idx) in unique_name_pairs(visible_layers, private_layers) {
apply_node_locks(Arc::make_mut(&mut visible_layers[v_idx]), &private_layers[p_idx]);
}
}
fn apply_node_locks(vis: &mut Node, priv_: &LockTree) {
if priv_.locked {
vis.locked = true;
}
let Some(vis_kids) = vis.children_mut() else { return };
if vis_kids.is_empty() || priv_.children.is_empty() {
return;
}
for (v_idx, p_idx) in unique_name_pairs(vis_kids.as_slice(), &priv_.children) {
apply_node_locks(Arc::make_mut(&mut vis_kids[v_idx]), &priv_.children[p_idx]);
}
}
/// The `.ai` whose editing copy is `private` (as [`layered_ai`] takes it) from its layers alone,
/// without its PDF part, whose pages (each its trim box in points, width and height) are `pages`
/// and are in units of `unit` points (its first page's `UserUnit`): the document and the notes of
+111 -6
View File
@@ -50,6 +50,11 @@ pub(crate) const MAX_TEXT: usize = 16 << 20;
/// kept as outlines and a node of the page's type.
pub(super) const MAX_PAIRS: usize = 4_000_000;
/// Most pairs of a text object whose type is made and a piece of the page's type weighed only by
/// where each lies (a box against a box, far cheaper than matching the page's type with a text
/// object's words, which [`MAX_PAIRS`] limits).
pub(super) const MAX_PLACE_PAIRS: usize = 4 * MAX_PAIRS;
/// `names` for a note: the first few, and how many more.
pub(super) fn few(names: BTreeSet<String>) -> String {
const SHOWN: usize = 5;
@@ -307,12 +312,6 @@ pub(super) fn fill_slots(
.iter()
.map(|p| {
let mut p = reid(doc, p);
if !visible {
Arc::make_mut(&mut p).visible = false;
}
if locked {
Arc::make_mut(&mut p).locked = true;
}
if let Some(name) = name.filter(|_| matches!(p.kind, NodeKind::Text(_))) {
Arc::make_mut(&mut p).name = Some(name.clone());
}
@@ -321,6 +320,7 @@ pub(super) fn fill_slots(
.collect();
let mut text = vec![];
text_ids(&parts, &mut text);
let mut wrapped = false;
// When the page draws each of them with no transparency, the slot's, or the slot's
// combined with that of the objects around it, the slot's takes its place: on the one
// part, or on a group of several when the slot has transparency. Otherwise every part
@@ -342,9 +342,12 @@ pub(super) fn fill_slots(
(p.opacity, p.blend, p.isolate, p.knockout, p.knockout_shape) = (state.0, state.1, state.2, state.3, shape);
} else if transparent {
let mut group = Node::group(doc.alloc_id(), std::mem::take(&mut parts));
group.visible = visible;
group.locked = locked;
(group.opacity, group.blend, group.isolate, group.knockout, group.knockout_shape) =
(state.0, state.1, state.2, state.3, shape);
parts.push(Arc::new(group));
wrapped = true;
}
}
// A wrap object stays one: the page's parts of it in a group, when there are several.
@@ -352,12 +355,25 @@ pub(super) fn fill_slots(
if parts.len() > 1 {
let mut group = Node::group(doc.alloc_id(), std::mem::take(&mut parts));
group.visible = visible;
group.locked = locked;
parts.push(Arc::new(group));
wrapped = true;
}
for p in &mut parts {
Arc::make_mut(p).extras_mut().wrap = wrap;
}
}
if !wrapped {
for p in &mut parts {
let p = Arc::make_mut(p);
if !visible {
p.visible = false;
}
if locked {
p.locked = true;
}
}
}
// One text object with the slot's appearance and transparency keeps its graphic style.
if let ([p], Some(a)) = (parts.as_mut_slice(), styled.as_ref())
&& linked.is_some()
@@ -751,4 +767,93 @@ mod tests {
let inner = nodes[0].children().unwrap()[0].id;
assert_eq!(filled.get(&slot), Some(&Filled { text: vec![inner], objects: vec![nodes[0].id, nodes[1].id] }));
}
/// A transparent slot wrapper group inherits hidden state while its inner children retain
/// their original visibility (both visible and intrinsically hidden), so showing the group
/// reveals only the intrinsically visible artwork.
#[test]
fn transparent_slot_wrapper_group_showing_reveals_inner_art() {
let mut doc = Document::new(100.0, 100.0);
let mut slot = Node::group(doc.alloc_id(), vec![]);
slot.name = Some("\u{0}text0:0".into());
slot.visible = false;
slot.locked = true;
slot.opacity = 0.5; // see_through(n) == true -> transparent == true
let part = |doc: &mut Document, x: f64, visible: bool| {
let t = vectorcraft_doc::TextObject::point(Point::new(x, 50.0), "Part", Default::default());
let mut node = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t)));
node.visible = visible;
Arc::new(node)
};
// Page run contains both a visible child and an intrinsically hidden child:
let parts = vec![part(&mut doc, 10.0, true), part(&mut doc, 60.0, false)];
let mut nodes = vec![Arc::new(slot)];
let mut content = vec![Content::Page(parts)].into_iter();
let (mut empty, mut made, mut filled) = (0, vec![], std::collections::HashMap::new());
fill_slots(&mut doc, &mut nodes, &mut content, &Default::default(), &mut empty, &mut made, &mut vec![], &mut filled);
assert_eq!(nodes.len(), 1);
let group = &nodes[0];
assert!(!group.visible, "wrapper group must inherit hidden state (visible = false)");
assert!(group.locked, "wrapper group must inherit locked state");
let children = group.children().expect("must be a group of parts");
assert_eq!(children.len(), 2);
assert!(children[0].visible, "intrinsically visible child retains visible = true");
assert!(!children[0].locked, "inner child must not be locked");
assert!(!children[1].visible, "intrinsically hidden child retains visible = false");
assert!(!children[1].locked, "inner child must not be locked");
// Showing the group updates only the group node's visible field:
let mut shown = (**group).clone();
shown.visible = true;
assert!(shown.visible);
let shown_children = shown.children().unwrap();
assert!(shown_children[0].visible, "intrinsically visible child is visible when parent group is shown");
assert!(!shown_children[1].visible, "intrinsically hidden child remains hidden when parent group is shown");
}
/// A wrap slot wrapper group inherits hidden and locked states without overwriting children's
/// original visibility flags when a page run contains both visible and intrinsically hidden children.
#[test]
fn wrap_slot_wrapper_group_preserves_child_visibility_and_showing_reveals_art() {
let mut doc = Document::new(100.0, 100.0);
let mut slot = Node::group(doc.alloc_id(), vec![]);
slot.name = Some("\u{0}text0:0".into());
slot.visible = false;
slot.locked = true;
let wrap = vectorcraft_doc::TextWrap { offset: 3.0, invert: true };
slot.extras_mut().wrap = Some(wrap);
let part = |doc: &mut Document, x: f64, visible: bool| {
let t = vectorcraft_doc::TextObject::point(Point::new(x, 50.0), "Part", Default::default());
let mut node = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t)));
node.visible = visible;
Arc::new(node)
};
let parts = vec![part(&mut doc, 10.0, true), part(&mut doc, 60.0, false)];
let mut nodes = vec![Arc::new(slot)];
let mut content = vec![Content::Page(parts)].into_iter();
let (mut empty, mut made, mut filled) = (0, vec![], std::collections::HashMap::new());
fill_slots(&mut doc, &mut nodes, &mut content, &Default::default(), &mut empty, &mut made, &mut vec![], &mut filled);
assert_eq!(nodes.len(), 1);
let group = &nodes[0];
assert!(!group.visible, "wrap wrapper group must inherit hidden state");
assert!(group.locked, "wrap wrapper group must inherit locked state");
let children = group.children().expect("must be a group of parts");
assert_eq!(children.len(), 2);
assert!(children[0].visible, "intrinsically visible child retains visible = true");
assert!(!children[0].locked, "inner child must not be locked");
assert!(!children[1].visible, "intrinsically hidden child retains visible = false");
assert!(!children[1].locked, "inner child must not be locked");
let mut shown = (**group).clone();
shown.visible = true;
let shown_children = shown.children().unwrap();
assert!(shown_children[0].visible, "intrinsically visible child is visible when parent group is shown");
assert!(!shown_children[1].visible, "intrinsically hidden child remains hidden when parent group is shown");
}
}
+355
View File
@@ -8664,6 +8664,361 @@ fn trusted_editing_data_keeps_an_artboard_taller_than_its_pdf_page() {
assert!(!read, "the uncapped dimension must still match: {w:?}");
}
/// A locked layer as the format writes it.
fn locked_layer(name: &str, body: &str) -> String {
format!("%AI5_BeginLayer\n1 1 0 1 0 0 1 0 79 128 255 0 50 0 Lb\n({name}) Ln\n{body}\nLB\n%AI5_EndLayer--\n")
}
#[test]
fn ai_locked_layers_and_groups_preserve_locks() {
let art_locked_group = format!("1 A\nu\n{}\nU\n0 A", square(10, 10));
let plain_layer = layer("Unlocked Layer", true, &square(0, 0));
let locked_l = locked_layer("Locked Layer", &art_locked_group);
let n = native(&format!("{plain_layer}{locked_l}"));
let file = private(&n);
let (doc, notes, read) = crate::layered_ai(&file, pdf_part(10.0, 86.0), vec![], false, true, 1.0);
assert!(read, "{notes:?}");
let unlocked = doc.layers.iter().find(|l| l.name.as_deref() == Some("Unlocked Layer")).unwrap();
let locked = doc.layers.iter().find(|l| l.name.as_deref() == Some("Locked Layer")).unwrap();
assert!(!unlocked.locked, "Unlocked Layer is not locked");
assert!(locked.locked, "Locked Layer retains locked == true");
let group = locked.children().and_then(|c| c.iter().find(|n| matches!(n.kind, NodeKind::Group { .. })));
assert!(group.is_some_and(|g| g.locked), "group with 1 A retains locked == true");
}
#[test]
fn ai_fallback_to_pdf_part_preserves_private_stream_layer_and_group_locks() {
use std::sync::Arc;
let art_locked_group = format!("1 A\nu\n{}\nU\n%_/ArtDictionary :\n%_(Locked Subgroup) /String (AIArtName) ,\n%_;\n0 A", square(10, 10));
let locked_l = locked_layer("Map Layer", &art_locked_group);
let n = native(&locked_l);
let file = private(&n);
let mut pdf = Document::new(100.0, 100.0);
pdf.layers.clear();
let mut vis_layer = Node::layer(pdf.alloc_id(), "Map Layer", LayerColor::Preset(0));
vis_layer.locked = false;
let mut vis_group = Node::group(pdf.alloc_id(), vec![]);
vis_group.name = Some("Locked Subgroup".to_string());
vis_group.locked = false;
if let NodeKind::Layer { children, .. } = &mut vis_layer.kind {
children.push(Arc::new(vis_group));
}
pdf.layers.push(Arc::new(vis_layer));
let layers = crate::AiLayers::decode(&file);
let (doc, _notes, read) = crate::layered_ai_from(layers, pdf, vec![], false, false, 1.0, crate::NameEncoding::default());
assert!(!read, "falls back to PDF part");
let map_layer = doc.layers.iter().find(|l| l.name.as_deref() == Some("Map Layer")).unwrap();
assert!(map_layer.locked, "Map Layer preserved locked == true from private stream metadata");
let subgroup = map_layer.children().and_then(|c| c.iter().find(|n| n.name.as_deref() == Some("Locked Subgroup"))).unwrap();
assert!(subgroup.locked, "Locked Subgroup preserved locked == true from private stream metadata");
}
#[test]
fn ai_duplicate_group_names_under_different_layers_preserve_individual_lock_states() {
use std::sync::Arc;
let art_locked_group = format!("1 A\nu\n{}\nU\n%_/ArtDictionary :\n%_(SharedGroup) /String (AIArtName) ,\n%_;\n0 A", square(10, 10));
let art_unlocked_group = format!("0 A\nu\n{}\nU\n%_/ArtDictionary :\n%_(SharedGroup) /String (AIArtName) ,\n%_;\n0 A", square(10, 10));
let layer_a = layer("Layer A", true, &art_locked_group);
let layer_b = layer("Layer B", true, &art_unlocked_group);
let n = native(&format!("{layer_a}{layer_b}"));
let file = private(&n);
let mut pdf = Document::new(100.0, 100.0);
pdf.layers.clear();
let mut vis_a = Node::layer(pdf.alloc_id(), "Layer A", LayerColor::Preset(0));
let mut vis_grp_a = Node::group(pdf.alloc_id(), vec![]);
vis_grp_a.name = Some("SharedGroup".to_string());
vis_grp_a.locked = false;
if let NodeKind::Layer { children, .. } = &mut vis_a.kind {
children.push(Arc::new(vis_grp_a));
}
let mut vis_b = Node::layer(pdf.alloc_id(), "Layer B", LayerColor::Preset(1));
let mut vis_grp_b = Node::group(pdf.alloc_id(), vec![]);
vis_grp_b.name = Some("SharedGroup".to_string());
vis_grp_b.locked = false;
if let NodeKind::Layer { children, .. } = &mut vis_b.kind {
children.push(Arc::new(vis_grp_b));
}
pdf.layers.push(Arc::new(vis_a));
pdf.layers.push(Arc::new(vis_b));
let layers = crate::AiLayers::decode(&file);
let (doc, _notes, read) = crate::layered_ai_from(layers, pdf, vec![], false, false, 1.0, crate::NameEncoding::default());
assert!(!read, "falls back to PDF part");
let l_a = doc.layers.iter().find(|l| l.name.as_deref() == Some("Layer A")).unwrap();
let l_b = doc.layers.iter().find(|l| l.name.as_deref() == Some("Layer B")).unwrap();
let grp_a = l_a.children().and_then(|c| c.iter().find(|n| n.name.as_deref() == Some("SharedGroup"))).unwrap();
let grp_b = l_b.children().and_then(|c| c.iter().find(|n| n.name.as_deref() == Some("SharedGroup"))).unwrap();
assert!(grp_a.locked, "Layer A's SharedGroup is locked");
assert!(!grp_b.locked, "Layer B's SharedGroup remains unlocked");
}
#[test]
fn ai_reordered_mixed_named_and_unnamed_children_preserve_locks() {
use std::sync::Arc;
let mut doc = Document::new(100.0, 100.0);
let mut priv_layer = Node::layer(doc.alloc_id(), "Map", LayerColor::Preset(0));
let mut priv_unnamed = Node::group(doc.alloc_id(), vec![]);
priv_unnamed.locked = false;
let mut priv_roads = Node::group(doc.alloc_id(), vec![]);
priv_roads.name = Some("Roads".to_string());
priv_roads.locked = true;
if let NodeKind::Layer { children, .. } = &mut priv_layer.kind {
children.push(Arc::new(priv_unnamed));
children.push(Arc::new(priv_roads));
}
let mut vis_layer = Node::layer(doc.alloc_id(), "Map", LayerColor::Preset(0));
let mut vis_roads = Node::group(doc.alloc_id(), vec![]);
vis_roads.name = Some("Roads".to_string());
vis_roads.locked = false;
let mut vis_unnamed = Node::group(doc.alloc_id(), vec![]);
vis_unnamed.locked = false;
if let NodeKind::Layer { children, .. } = &mut vis_layer.kind {
children.push(Arc::new(vis_roads));
children.push(Arc::new(vis_unnamed));
}
let mut visible_layers = vec![Arc::new(vis_layer)];
let private_layers = vec![super::native::layers::LockTree::from_node(&priv_layer)];
super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers);
let roads = visible_layers[0].children().unwrap()[0].clone();
let unnamed = visible_layers[0].children().unwrap()[1].clone();
assert_eq!(roads.name.as_deref(), Some("Roads"));
assert!(roads.locked, "Roads matched by unique name and preserved locked == true");
assert!(!unnamed.locked, "unnamed child matched to unlocked private child");
}
#[test]
fn ai_reordered_three_children_roads_triangle_circle_preserve_locks() {
use std::sync::Arc;
let mut doc = Document::new(100.0, 100.0);
// Private children: [Roads (unlocked), locked triangle (unnamed), unlocked circle (unnamed)]
let mut priv_layer = Node::layer(doc.alloc_id(), "Layer", LayerColor::Preset(0));
let mut priv_roads = Node::group(doc.alloc_id(), vec![]);
priv_roads.name = Some("Roads".to_string());
priv_roads.locked = false;
let mut priv_triangle = Node::group(doc.alloc_id(), vec![]);
priv_triangle.locked = true;
let mut priv_circle = Node::group(doc.alloc_id(), vec![]);
priv_circle.locked = false;
if let NodeKind::Layer { children, .. } = &mut priv_layer.kind {
children.push(Arc::new(priv_roads));
children.push(Arc::new(priv_triangle));
children.push(Arc::new(priv_circle));
}
// Visible children: [triangle (unnamed), circle (unnamed), Roads]
let mut vis_layer = Node::layer(doc.alloc_id(), "Layer", LayerColor::Preset(0));
let mut vis_triangle = Node::group(doc.alloc_id(), vec![]);
vis_triangle.locked = false;
let mut vis_circle = Node::group(doc.alloc_id(), vec![]);
vis_circle.locked = false;
let mut vis_roads = Node::group(doc.alloc_id(), vec![]);
vis_roads.name = Some("Roads".to_string());
vis_roads.locked = false;
if let NodeKind::Layer { children, .. } = &mut vis_layer.kind {
children.push(Arc::new(vis_triangle));
children.push(Arc::new(vis_circle));
children.push(Arc::new(vis_roads));
}
let mut visible_layers = vec![Arc::new(vis_layer)];
let private_layers = vec![super::native::layers::LockTree::from_node(&priv_layer)];
super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers);
let vis_tri = visible_layers[0].children().unwrap()[0].clone();
let vis_circ = visible_layers[0].children().unwrap()[1].clone();
let vis_rd = visible_layers[0].children().unwrap()[2].clone();
assert!(!vis_tri.locked, "unnamed triangle does not pair blindly with private triangle");
assert!(!vis_circ.locked, "unnamed circle remains unlocked");
assert!(!vis_rd.locked, "Roads matched to unlocked private Roads by unique name");
}
/// The PDF part's one layer, named for its page because the PDF part has no layers, isn't the
/// editing data's one layer: nothing says the art on it is that layer's, so the layer's lock and
/// those of what it holds stay out of it.
#[test]
fn ai_fallback_with_generated_page_name_does_not_take_private_layer_lock() {
use std::sync::Arc;
let mut doc = Document::new(100.0, 100.0);
let mut priv_layer = Node::layer(doc.alloc_id(), "Map", LayerColor::Preset(0));
priv_layer.locked = true;
let mut priv_roads = Node::group(doc.alloc_id(), vec![]);
priv_roads.name = Some("Roads".to_string());
priv_roads.locked = true;
if let NodeKind::Layer { children, .. } = &mut priv_layer.kind {
children.push(Arc::new(priv_roads));
}
let mut vis_layer = Node::layer(doc.alloc_id(), "Page 1", LayerColor::Preset(0));
let mut vis_roads = Node::group(doc.alloc_id(), vec![]);
vis_roads.name = Some("Roads".to_string());
if let NodeKind::Layer { children, .. } = &mut vis_layer.kind {
children.push(Arc::new(vis_roads));
}
let mut visible_layers = vec![Arc::new(vis_layer)];
let private_layers = vec![super::native::layers::LockTree::from_node(&priv_layer)];
super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers);
assert!(!visible_layers[0].locked, "the page's layer doesn't take the editing data's layer lock");
assert!(!visible_layers[0].children().unwrap()[0].locked, "nor does what it holds");
}
/// An editing copy that doesn't fit the PDF part (a stale copy of another page size) is set aside,
/// and the PDF part without layers comes in on one layer named for its page: the editing copy's
/// locked layer doesn't lock that art, which nothing ties to it.
#[test]
fn a_stale_editing_copy_does_not_lock_the_pdf_parts_page_layer() {
let art = native(&locked_layer("Map", &square(10, 10)));
let mut page = Document::new(300.0, 300.0);
std::sync::Arc::make_mut(&mut page.layers[0]).name = Some("Page 1".into());
let (d, w, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0);
assert!(!read, "the editing copy of another page size is set aside: {w:?}");
assert_eq!(names(&d), ["Page 1"], "{w:?}");
assert!(!d.layers[0].locked, "the page's layer isn't locked: {w:?}");
}
#[test]
fn ai_unnamed_visible_child_does_not_pair_with_private_node() {
use std::sync::Arc;
let mut doc = Document::new(100.0, 100.0);
let mut priv_layer = Node::layer(doc.alloc_id(), "Layer", LayerColor::Preset(0));
let mut priv_unnamed = Node::group(doc.alloc_id(), vec![]);
priv_unnamed.locked = false;
let mut priv_roads = Node::group(doc.alloc_id(), vec![]);
priv_roads.name = Some("Roads".to_string());
priv_roads.locked = true;
if let NodeKind::Layer { children, .. } = &mut priv_layer.kind {
children.push(Arc::new(priv_unnamed));
children.push(Arc::new(priv_roads));
}
let mut vis_layer = Node::layer(doc.alloc_id(), "Layer", LayerColor::Preset(0));
let mut vis_first = Node::group(doc.alloc_id(), vec![]);
vis_first.locked = false;
let mut vis_second = Node::group(doc.alloc_id(), vec![]);
vis_second.locked = false;
if let NodeKind::Layer { children, .. } = &mut vis_layer.kind {
children.push(Arc::new(vis_first));
children.push(Arc::new(vis_second));
}
let mut visible_layers = vec![Arc::new(vis_layer)];
let private_layers = vec![super::native::layers::LockTree::from_node(&priv_layer)];
super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers);
let first = visible_layers[0].children().unwrap()[0].clone();
let second = visible_layers[0].children().unwrap()[1].clone();
assert!(!first.locked, "first unnamed visible group is unlocked");
assert!(!second.locked, "second unnamed visible group does not pair positionally with locked Roads group");
}
#[test]
fn ai_multi_page_unlayered_pdf_does_not_blindly_pair_with_private_layers() {
use std::sync::Arc;
let mut doc = Document::new(100.0, 100.0);
let mut priv_1 = Node::layer(doc.alloc_id(), "Layer 1", LayerColor::Preset(0));
priv_1.locked = true;
let mut priv_2 = Node::layer(doc.alloc_id(), "Layer 2", LayerColor::Preset(0));
priv_2.locked = false;
let vis_1 = Node::layer(doc.alloc_id(), "Page 1", LayerColor::Preset(0));
let vis_2 = Node::layer(doc.alloc_id(), "Page 2", LayerColor::Preset(0));
let mut visible_layers = vec![Arc::new(vis_1), Arc::new(vis_2)];
let private_layers = vec![super::native::layers::LockTree::from_node(&priv_1), super::native::layers::LockTree::from_node(&priv_2)];
super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers);
assert!(!visible_layers[0].locked, "Page 1 does not pair with private Layer 1");
assert!(!visible_layers[1].locked, "Page 2 does not pair with private Layer 2");
}
#[test]
fn ai_duplicate_visible_name_does_not_lock_multiple_from_single_private_node() {
use std::sync::Arc;
let mut doc = Document::new(100.0, 100.0);
let mut priv_layer = Node::layer(doc.alloc_id(), "Layer", LayerColor::Preset(0));
let mut priv_roads = Node::group(doc.alloc_id(), vec![]);
priv_roads.name = Some("Roads".to_string());
priv_roads.locked = true;
let mut priv_buildings = Node::group(doc.alloc_id(), vec![]);
priv_buildings.name = Some("Buildings".to_string());
priv_buildings.locked = false;
if let NodeKind::Layer { children, .. } = &mut priv_layer.kind {
children.push(Arc::new(priv_roads));
children.push(Arc::new(priv_buildings));
}
let mut vis_layer = Node::layer(doc.alloc_id(), "Layer", LayerColor::Preset(0));
let mut vis_roads1 = Node::group(doc.alloc_id(), vec![]);
vis_roads1.name = Some("Roads".to_string());
vis_roads1.locked = false;
let mut vis_roads2 = Node::group(doc.alloc_id(), vec![]);
vis_roads2.name = Some("Roads".to_string());
vis_roads2.locked = false;
if let NodeKind::Layer { children, .. } = &mut vis_layer.kind {
children.push(Arc::new(vis_roads1));
children.push(Arc::new(vis_roads2));
}
let mut visible_layers = vec![Arc::new(vis_layer)];
let private_layers = vec![super::native::layers::LockTree::from_node(&priv_layer)];
super::native::layers::apply_private_layer_locks(&mut visible_layers, &private_layers);
let r1 = visible_layers[0].children().unwrap()[0].clone();
let r2 = visible_layers[0].children().unwrap()[1].clone();
assert!(!r1.locked, "ambiguous duplicate visible name does not receive private lock");
assert!(!r2.locked, "second duplicate visible name remains unlocked");
}
/// #9176: a file with more text objects than the page's type can be matched with each, all but one
/// of them made from its text document, opens with its layers, and what is locked in it stays
/// locked. Only the one text object whose type isn't made is matched with the page's type; the made
/// ones are weighed by where they lie. (Our own minimized copy of the reported file's structure:
/// about two thousand text objects whose type the text document makes, a few it can't, and as many
/// pieces of type on the page, with locked groups.)
#[test]
fn a_file_with_many_made_text_objects_and_one_unread_keeps_its_layers_and_locks() {
// Every text object against every piece of the page's type is past `MAX_PAIRS` (four million).
let many = 2050;
let doc =
last_frame_unread(&text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), ("Odd\r", 0, (8200.0, 8160.0), (0.0, 0.0), 0.0)]));
let locked_group = format!("1 A\nu\n{}\nU\n0 A\n", square(10, 10));
let art = native_with_text(&layer("Map", true, &(locked_group + &text_object(0).repeat(many) + &text_object(1))), &doc);
// The PDF part: the square, the made type where the text document puts it, once per text object,
// and as many small pieces of type apart from one another, which the one text object whose type
// isn't made takes.
let mut page = pdf_part(10.0, 86.0);
let layer_id = page.layers[0].id;
let put = |page: &mut Document, at: (f64, f64), text: &str, size: f64| {
let style = vectorcraft_doc::CharStyle { size, ..Default::default() };
let text = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(at.0, at.1), text, style);
let id = page.alloc_id();
let end = page.layers[0].children().map_or(0, |c| c.len());
page.insert(Some(layer_id), end, Node::new(id, NodeKind::Text(Box::new(text)))).unwrap();
};
for _ in 0..many {
put(&mut page, (58.5, 38.5), "Hi there", 14.0);
}
for k in 0..many {
// Down each column, so that no two pieces painted one after the other are on one line.
put(&mut page, (1.0 + (k / 46) as f64 * 2.1, 1.0 + (k % 46) as f64 * 2.1), "o", 1.0);
}
let (d, w, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0);
assert!(read, "{w:?}");
assert_eq!(names(&d), ["Map"], "{w:?}");
let group = d.layers[0].children().and_then(|c| c.iter().find(|n| matches!(n.kind, NodeKind::Group { .. })));
assert!(group.is_some_and(|g| g.locked), "the group locked in the file stays locked: {w:?}");
assert!(all_texts(&d).iter().filter(|t| *t == "Hi there").count() >= many, "{w:?}");
}
/// The page's "2014" drawn as one piece 20 points across the art, and two text objects "20" and
/// "14" anchored at `twenty` and `fourteen`, set in the bundled Source Sans 3 at 14 points (a digit
/// 6.958 points wide) so that where they draw doesn't hang on the fonts installed.
+30 -3
View File
@@ -422,15 +422,17 @@ mod tests {
}
/// A replaced file that had no access ACL gets none from the folder's default ACL, whose named
/// users the old file's group bits would let in. (Skipped where `setfacl` or ACLs are missing.)
/// users the old file's group bits would let in. The default ACL is set through its extended
/// attribute, so the test runs where the `acl` tools are not installed. (Skipped on a file system
/// without ACLs.)
#[cfg(target_os = "linux")]
#[test]
fn a_replacement_takes_no_inherited_acl_the_old_file_lacked() {
let d = dir("acl");
let f = d.join("doc.vectorcraft");
std::fs::write(&f, b"old").unwrap();
let set = std::process::Command::new("setfacl").args(["-d", "-m", "u:nobody:rw"]).arg(&d).status();
if !set.is_ok_and(|s| s.success()) {
if !set_default_acl_for_nobody(&d) {
let _ = std::fs::remove_dir_all(&d);
return;
}
write_atomic(&f, b"new").unwrap();
@@ -439,6 +441,31 @@ mod tests {
let _ = std::fs::remove_dir_all(&d);
}
/// Give folder `d` the default ACL `u::rw-,u:nobody:rw-,g::r--,m::rw-,o::r--`, written as the
/// kernel's `system.posix_acl_default` attribute (version 2, then tag, permissions and id per entry).
#[cfg(target_os = "linux")]
/// `false` when the folder's file system keeps no ACLs.
fn set_default_acl_for_nobody(d: &Path) -> bool {
const NO_ID: u32 = u32::MAX;
let mut acl = 2u32.to_le_bytes().to_vec();
for (tag, perm, id) in [(0x01u16, 6u16, NO_ID), (0x02, 6, 65534), (0x04, 4, NO_ID), (0x10, 6, NO_ID), (0x20, 4, NO_ID)] {
acl.extend(tag.to_le_bytes());
acl.extend(perm.to_le_bytes());
acl.extend(id.to_le_bytes());
}
match rustix::fs::setxattr(d, "system.posix_acl_default", &acl, rustix::fs::XattrFlags::empty()) {
Ok(()) => {}
Err(e) if e == rustix::io::Errno::NOTSUP => return false,
Err(e) => panic!("setting the default ACL: {e}"),
}
let mut buf = vec![0u8; 4096];
let probe = d.join("probe");
std::fs::write(&probe, b"").unwrap();
assert!(rustix::fs::getxattr(&probe, "system.posix_acl_access", &mut buf[..]).is_ok(), "a new file takes the default ACL");
std::fs::remove_file(&probe).unwrap();
true
}
/// The other files in `d` besides `keep`.
fn leftovers(d: &Path, keep: &str) -> Vec<String> {
std::fs::read_dir(d).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().to_string()).filter(|n| n != keep).collect()
+5 -9
View File
@@ -68,20 +68,16 @@ problem;
#[test]
fn json2_polyfill_round_trips_with_the_built_in_json() {
let mut realm = Realm::new();
match realm.run(NEEDS) {
Ok(JsValue::Bool(true)) => {}
other => panic!("json2: the interpreter lacks Date, String.prototype.replace or RegExp, which json2.js uses: {other:?}"),
}
let Some(path) = json2_file() else {
println!("json2: SKIPPED (no json2.js; run cargo xtask test262)");
return;
};
let source = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
let mut realm = Realm::new();
match realm.run(NEEDS) {
Ok(JsValue::Bool(true)) => {}
Ok(JsValue::Bool(false)) => {
println!("json2: SKIPPED (the interpreter lacks Date, String.prototype.replace or RegExp, which json2.js uses)");
return;
}
other => panic!("json2: the built-in check failed: {other:?}"),
}
match realm.run(&format!("{BEFORE}\n{source}\n{ROUND_TRIP}")) {
Ok(JsValue::String(s)) if s == "ok" => println!("json2: the polyfill and the built-in JSON agree on every sample"),
other => panic!("json2: {other:?}"),
+8 -8
View File
@@ -1274,7 +1274,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.layerOptions",
"Options for Selection…",
"",
"{ids?|id?} open Layer Options for Layers panel rows (default: the highlighted rows, else the current layer), filled in from the first: dialog `layerOptions`, fields name, color (a preset name such as \"Light Blue\" or #rrggbb), template, locked, visible, printable, preview, dimImages (bool), dimPercent (0–100); an object's row has name, visible and locked. Unchanged OK adds no undo step; edits run layer.setProps in one undo step. Existing names are preserved unless Name is edited or explicitly set; for several rows it sends only the fields set in the dialog",
"{ids?|id?} open Layer Options for Layers panel rows (default: the highlighted rows, else the current layer), filled in from the first: dialog `ui.layerOptions`, fields name, color (a preset name such as \"Light Blue\" or #rrggbb), template, locked, visible, printable, preview, dimImages (bool), dimPercent (0–100); an object's row has name, visible and locked. Unchanged OK adds no undo step; edits run layer.setProps in one undo step. Existing names are preserved unless Name is edited or explicitly set; for several rows it sends only the fields set in the dialog",
),
(
"ui.layerDelete",
@@ -1292,7 +1292,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.newLayer",
"New Layer Options…",
"Cmd+Alt+L",
"{sublayer?: bool} open Layer Options for a new layer (or a sublayer of the current layer), named and coloured as it would be: dialog `layerOptions` with mode new|newSublayer; OK runs layer.new or layer.newSublayer with the fields. In isolation mode, a layer that would be outside the isolated art is an error and nothing opens; OK checks again, and with isolation mode started since, it returns the same error and makes no layer",
"{sublayer?: bool} open Layer Options for a new layer (or a sublayer of the current layer), named and coloured as it would be: dialog `ui.layerOptions` with mode new|newSublayer; OK runs layer.new or layer.newSublayer with the fields. In isolation mode, a layer that would be outside the isolated art is an error and nothing opens; OK checks again, and with isolation mode started since, it returns the same error and makes no layer",
),
(
"ui.newArtboard",
@@ -1310,13 +1310,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.layersPanelOptions",
"Panel Options…",
"",
"{} open the Layers panel's Panel Options: dialog `layersPanelOptions`, fields layersOnly, locateSelected (Locate Selected Objects, off by default: when the last selected object changes outside the panel, on the canvas or by a command, the panel opens the layers and groups around it and scrolls to its row, as after layer.locate, without highlighting the row; when Show Layers Only, a search or the filter leaves the object without a row, the panel opens no rows for it and scrolls as with the option off; a change made during a drag is located when the drag ends), rowSize (small|medium|large|other), otherSize (12–100 pt), thumbLayers, thumbGroups, thumbObjects; OK applies them (kept with the UI state)",
"{} open the Layers panel's Panel Options: dialog `ui.layersPanelOptions`, fields layersOnly, locateSelected (Locate Selected Objects, off by default: when the last selected object changes outside the panel, on the canvas or by a command, the panel opens the layers and groups around it and scrolls to its row, as after layer.locate, without highlighting the row; when Show Layers Only, a search or the filter leaves the object without a row, the panel opens no rows for it and scrolls as with the option off; a change made during a drag is located when the drag ends), rowSize (small|medium|large|other), otherSize (12–100 pt), thumbLayers, thumbGroups, thumbObjects; OK applies them (kept with the UI state)",
),
(
"ui.navigatorPanelOptions",
"Panel Options…",
"",
"{color?: #rrggbb or a preset name (Light Red, the default, then the layer colors such as \"Light Blue\"), solidDashes?: bool (Draw Dashed Lines as Solid Lines, off by default: the Navigator's thumbnail draws dashed strokes without their dashes; the canvas, printing and exports keep them), viewArtboardContentsOnly?: bool (View Artboard Contents Only in the panel menu, on by default and for UI state saved without it: the thumbnail fits the artboards and draws only the art inside them, cut at each artboard's edges; off, it also shows the art on the pasteboard)} set the Navigator panel's options, the color its view box is drawn in, solid dashes and artboard contents only (kept with the UI state) → {color, solidDashes, viewArtboardContentsOnly}; with none, open its Panel Options (dialog `navigatorPanelOptions`, fields color, solidDashes; OK sets them); an error for a value that is not a color or not true or false, which changes nothing",
"{color?: #rrggbb or a preset name (Light Red, the default, then the layer colors such as \"Light Blue\"), solidDashes?: bool (Draw Dashed Lines as Solid Lines, off by default: the Navigator's thumbnail draws dashed strokes without their dashes; the canvas, printing and exports keep them), viewArtboardContentsOnly?: bool (View Artboard Contents Only in the panel menu, on by default and for UI state saved without it: the thumbnail fits the artboards and draws only the art inside them, cut at each artboard's edges; off, it also shows the art on the pasteboard)} set the Navigator panel's options, the color its view box is drawn in, solid dashes and artboard contents only (kept with the UI state) → {color, solidDashes, viewArtboardContentsOnly}; with none, open its Panel Options (dialog `ui.navigatorPanelOptions`, fields color, solidDashes; OK sets them); an error for a value that is not a color or not true or false, which changes nothing",
),
(
"ui.attributesPanelOptions",
@@ -1645,7 +1645,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.rasterEffectsSettingsDialog",
"Document Raster Effects Settings Dialog",
"",
"{} open Document Raster Effects Settings (dialog `rasterEffectsSettings`: the document.rasterEffectsSettings fields); OK runs it. The menu item opens it too",
"{} open Document Raster Effects Settings (dialog `document.rasterEffectsSettings`: the document.rasterEffectsSettings fields); OK runs it. The menu item opens it too",
),
(
"ui.effectGalleryDialog",
@@ -1663,7 +1663,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.pdfPresetDialog",
"PDF Preset",
"",
"{name?: a saved preset to edit | preset?: the preset a new one starts from (default VectorCraft Default)} open the preset editor (dialog `pdfPreset`: the Save PDF dialog's option fields plus `name` and `description`); OK runs pdf.preset.save and returns to PDF Presets",
"{name?: a saved preset to edit | preset?: the preset a new one starts from (default VectorCraft Default)} open the preset editor (dialog `pdf-export`: the Save PDF dialog's option fields plus `name` and `description`); OK runs pdf.preset.save and returns to PDF Presets",
),
("file.openRecent11", "Open Recent File 11", "", "{}"),
("file.openRecent12", "Open Recent File 12", "", "{}"),
@@ -1918,7 +1918,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.actionSet.reset",
"Reset Actions",
"",
"{mode?: \"replace\" | \"append\"} Reset Actions. replace (the default) replaces every set in the Actions panel with a new copy of the built-in Default Actions set, makes it current and selected, clears the panel's selected action and step and its expanded actions, and closes an open Set Options, New Action, Batch or step dialog that names a set; when the panel already shows only the built-in set as it comes in that state, nothing changes, the sets keep their ids and changed is false. append adds a new copy of the built-in set after the sets there are, with the next free number when its name is in use (Default Actions 2), and keeps the current set and the selection. Omitted params count as {}. Params of another type, another key, another mode, or a reset while an action records or plays (also while it waits at a stop) is an error and changes nothing. No undo step is recorded. The panel menu's Reset Actions asks first (dialog `resetActions`): OK runs this with replace, Append with append → {changed, mode, set: the first built-in set's index}",
"{mode?: \"replace\" | \"append\"} Reset Actions. replace (the default) replaces every set in the Actions panel with a new copy of the built-in Default Actions set, makes it current and selected, clears the panel's selected action and step and its expanded actions, and closes an open Set Options, New Action, Batch or step dialog that names a set; when the panel already shows only the built-in set as it comes in that state, nothing changes, the sets keep their ids and changed is false. append adds a new copy of the built-in set after the sets there are, with the next free number when its name is in use (Default Actions 2), and keeps the current set and the selection. Omitted params count as {}. Params of another type, another key, another mode, or a reset while an action records or plays (also while it waits at a stop) is an error and changes nothing. No undo step is recorded. The panel menu's Reset Actions asks first (dialog `actionsQuestion`): OK runs this with replace, Append with append → {changed, mode, set: the first built-in set's index}",
),
(
"ui.actionSet.clear",
@@ -1949,7 +1949,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"file.saveForWeb",
"Save for Web (Legacy)…",
"Cmd+Alt+Shift+S",
"{} open Save for Web (dialog `saveForWeb`: fields = the webExport.settings settings, `preset` loads a preset, __view: original|optimized|2up|4up, __zoom, __kbps; Save… remembers the settings and writes the files, Done only remembers them); with settings = document.exportForWeb, written to path, else a picked file (the web downloads the files) → {path, files, bytes}",
"{} open Save for Web (dialog `save-for-web`: fields = the webExport.settings settings, `preset` loads a preset, __view: original|optimized|2up|4up, __zoom, __kbps; Save… remembers the settings and writes the files, Done only remembers them); with settings = document.exportForWeb, written to path, else a picked file (the web downloads the files) → {path, files, bytes}",
),
(
"file.saveForWeb.browser",
+3 -3
View File
@@ -503,13 +503,13 @@ fn arabic_ligatures_keep_their_letters_in_order() {
let t = TextObject::point(kurbo::Point::ORIGIN, "لا", style);
vectorcraft_text::layout(db, &t).glyphs.len() == 1
};
// An installed Arabic font with a lam-alef ligature whose glyphs come back as live type.
// An installed Arabic font with a lam-alef ligature. The test checks that its type comes
// back, so the choice of font does not depend on the import.
let Some(face) = preferred
.iter()
.chain(&db.families())
.filter_map(|f| db.face(f, "Regular"))
.filter(|f| f.covers('\u{0644}') && f.covers('\u{0627}') && ligates(f))
.find(|f| !imported_texts(f, "بب").is_empty())
.find(|f| f.covers('\u{0644}') && f.covers('\u{0627}') && ligates(f))
else {
return; // No such font on this host.
};
+7 -11
View File
@@ -202,8 +202,7 @@ fn line_break_hyphens_of_right_to_left_lines_are_written_as_text_where_the_canva
/// The kashidas of justified Arabic type (Insert Kashidas), which stand for no character either,
/// are drawn as paths: reopened, the type holds its letters and no hyphen or tatweel. Skipped
/// without an OpenType font that covers Arabic and the tatweel, when the layout adds no kashida,
/// or when PDF text import returns no strings on this platform.
/// without an OpenType font that covers Arabic and the tatweel.
#[test]
fn kashidas_are_not_written_as_hyphens() {
let db = FontDb::global();
@@ -221,20 +220,17 @@ fn kashidas_are_not_written_as_hyphens() {
t.para.justify = vectorcraft_doc::Justify::JustifyAll;
t.para.kashida = vectorcraft_doc::text::Kashida::Medium;
let tatweel = face.glyph_for('\u{0640}');
if !vectorcraft_text::layout(db, &t).glyphs.iter().any(|g| g.len == 0 && g.gid == tatweel) {
return;
}
assert!(
vectorcraft_text::layout(db, &t).glyphs.iter().any(|g| g.len == 0 && g.gid == tatweel),
"{}: justified layout inserts a kashida",
face.family
);
let back = texts(&import_as(&pdf(&doc(vec![t]), false).bytes, TextAs::Text));
if back.is_empty() {
return;
}
assert!(!back.is_empty(), "{}: the PDF's type comes back", face.family);
assert!(!back.concat().contains(['-', '\u{2010}', '\u{0640}']), "{back:?}");
// Every letter comes back, at least as often as the text holds it (the justified words may
// come back as type objects of their own).
let all = back.concat();
if all.is_empty() {
return;
}
let count = |s: &str, c: char| s.chars().filter(|&x| x == c).count();
for c in text.chars().filter(|c| c.is_alphabetic()) {
assert!(count(&all, c) >= count(text, c), "{c}: {back:?}");
+57 -1
View File
@@ -475,6 +475,10 @@ struct Chain {
group: Option<usize>,
}
/// Characters a member chain holds at least, more than the longest chain the checks compare
/// (`app.documents.addDocumentNoUI().print()` has 39).
const CHAIN_CHARS: usize = 64;
impl Chain {
fn new(root: String, bare: bool, line: usize) -> Self {
let (chars, cut) = (root.chars().count(), root.ends_with('…'));
@@ -523,6 +527,42 @@ impl Chain {
self.last_change = false;
self.append(if call { "()" } else { "[]" }, cap);
}
/// The index that ends the chain is of the member `name`, which a string literal in brackets
/// named: `[]` becomes `.name` when one of [`catalog::DOM_DOCUMENTS`] reads that member as a
/// property (`app['activeDocument']`, `app['documents'][0]`). Any other name keeps the index.
fn name_index(&mut self, name: &str, cap: usize) {
let Some(base) = self.path.strip_suffix("[]").filter(|_| !self.cut) else { return };
let property = |d: &&str| {
d.strip_prefix(base)
.and_then(|m| m.strip_prefix('.'))
.and_then(|m| m.strip_prefix(name))
.is_some_and(|rest| rest.is_empty() || rest.starts_with('.') || rest.starts_with('['))
};
let ident = !name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '$');
if !ident || !catalog::DOM_DOCUMENTS.iter().any(property) {
return;
}
self.path.truncate(self.path.len() - 2);
self.chars = self.chars.saturating_sub(2);
self.last_change = false;
for s in [".", name] {
self.append(s, cap);
}
}
/// The call that ends the chain is of the member `name`, which a string literal in brackets
/// named: `[]()` becomes `.name()`.
fn name_call(&mut self, name: &str, cap: usize) {
if self.cut || !self.path.ends_with("[]()") {
return;
}
self.path.truncate(self.path.len() - 4);
self.chars = self.chars.saturating_sub(4);
for s in [".", name, "()"] {
self.append(s, cap);
}
}
}
/// A function body being read: the bracket depth inside it, and what each name declared in it
@@ -862,10 +902,16 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
// ---------- member chains ----------
/// The most characters a member chain holds while it is read: [`crate::Limits::echo`], and at least
/// [`CHAIN_CHARS`], so a short echo limit cuts only the chains the report lists.
fn chain_cap(&self) -> usize {
self.acc.limits.echo.max(CHAIN_CHARS)
}
/// Whether the active chain takes `t` (a `.`, a member's name, `[` or `(`); any other token ends
/// it.
fn continue_chain(&mut self, t: &Sig<'s>) -> bool {
let cap = self.acc.limits.echo;
let cap = self.chain_cap();
let Some(c) = self.active.as_mut() else { return false };
if c.after_dot {
c.after_dot = false;
@@ -1262,6 +1308,16 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
}
if self.suspended.last().is_some_and(|c| c.wait == self.depth()) {
self.active = self.suspended.pop();
// `app['activeDocument']`: a string literal in the brackets names a member.
if t.text == "]"
&& is(self.h[1], "[")
&& let Some(name) = self.h[0].filter(|s| s.kind == T::Str).map(|s| unquote(s.text, 32))
{
let cap = self.chain_cap();
if let Some(c) = self.active.as_mut() {
c.name_index(&name, cap);
}
}
}
self.close_scopes();
let grouped = self.close_parens(t);
+60 -7
View File
@@ -307,18 +307,61 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
}
}
/// Whether this `(` calls a document's `print`: the document-model member chain the `(` has just
/// set aside until its `)` is one of [`catalog::DOM_DOCUMENTS`] followed by `called`, the method
/// as the chain writes it (`.print()`, or `[]()` when brackets name it).
fn document_print(&self, called: &str) -> bool {
self.called_on(called).is_some_and(|receiver| catalog::DOM_DOCUMENTS.contains(&receiver))
}
/// Whether this `(` calls a method of the application object: `receiver`, which `before` comes
/// before, is the application object ([`Self::app_receiver`]), or the document-model member chain
/// the `(` has just set aside until its `)` is `app` followed by `called`. The chain starts at `app`
/// or at a variable that holds it, never at a property named `app` or at an `app` the script declared.
fn app_call(&self, called: &str, receiver: Option<Sig<'s>>, before: Option<Sig<'s>>) -> bool {
self.app_receiver(receiver, before) || self.called_on(called) == Some(catalog::DOM_ROOTS[0])
}
/// Whether the method `name`, which a string literal in brackets named, gives a document: the
/// member chain this `(` has just set aside, with `name` called on its receiver, is one of
/// [`catalog::DOM_DOCUMENTS`].
fn gives_document(&self, name: &str) -> bool {
let named =
|receiver: &str, d: &str| d.strip_prefix(receiver).and_then(|m| m.strip_prefix('.')).and_then(|m| m.strip_suffix("()")) == Some(name);
self.called_on("[]()").is_some_and(|receiver| catalog::DOM_DOCUMENTS.iter().any(|d| named(receiver, d)))
}
/// What the document-model member chain that this `(` has just set aside until its `)` holds before
/// `called`, when the chain ends with `called`.
fn called_on(&self, called: &str) -> Option<&str> {
let chain = self.suspended.last().filter(|c| c.wait.saturating_add(1) == self.depth());
chain.and_then(|c| c.path.strip_suffix(called))
}
/// `(` after a name: a call.
fn call(&mut self, t: &Sig<'s>, line: Option<usize>) {
let [h0, h1, h2, h3] = self.h;
// `doc['saveAs'](f)`: a document method named by a string literal in brackets.
// `doc['saveAs'](f)`, `doc['exportVariables'](f)` and `app['open'](f)`: a method named by a string literal in brackets.
if is(h0, "]")
&& is(h2, "[")
&& let Some(method) = h1.filter(|s| s.kind == T::Str).map(|s| unquote(s.text, 32))
&& catalog::DOM_FILE_WRITES.contains(&method.as_str())
&& !Self::defines(self.index_receiver, &method)
&& let Some(name) = h1.filter(|s| s.kind == T::Str).map(|s| unquote(s.text, 32))
{
self.acc.feature(FeatureId::FileWrite, line);
self.acc.outside(OutsideId::FilesWritten, line, None);
if (catalog::DOM_FILE_WRITES.contains(&name.as_str()) && !Self::defines(self.index_receiver, &name))
|| (name == catalog::DOM_PRINT && self.document_print("[]()"))
{
self.acc.feature(FeatureId::FileWrite, line);
self.acc.outside(OutsideId::FilesWritten, line, None);
} else if catalog::DOM_FILE_READS.contains(&name.as_str()) && self.app_call("[]()", h3, self.h4) {
self.acc.feature(FeatureId::FileRead, line);
}
// `app['open'](f)` and `app.documents['index'](0)` give a document, as `app.open(f)` and
// `app.documents.index(0)` do.
if self.gives_document(&name) {
let (depth, cap) = (self.depth(), self.chain_cap());
if let Some(c) = self.suspended.last_mut().filter(|c| c.wait.saturating_add(1) == depth) {
c.name_call(&name, cap);
}
}
return;
}
let Some(callee) = h0.filter(|s| s.kind == T::Ident) else { return };
@@ -339,10 +382,14 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
self.acc.feature(FeatureId::ScriptuiDrawing, line);
} else if catalog::INSTANCE_DIALOGS.contains(&n) {
self.acc.feature(FeatureId::FileDialog, line);
} else if catalog::FOLDER_READS.contains(&n) || (file && catalog::FILE_READS.contains(&n)) {
} else if catalog::FOLDER_READS.contains(&n)
|| (file && catalog::FILE_READS.contains(&n))
|| (catalog::DOM_FILE_READS.contains(&n) && self.app_call(&format!(".{n}()"), h2, h3))
{
self.acc.feature(FeatureId::FileRead, line);
} else if (file && catalog::FILE_WRITES.contains(&n))
|| (catalog::DOM_FILE_WRITES.contains(&n) && !Self::defines(self.writer_bits(h2, h3, Some(t.start)), n))
|| (n == catalog::DOM_PRINT && self.document_print(".print()"))
{
self.acc.feature(FeatureId::FileWrite, line);
self.acc.outside(OutsideId::FilesWritten, line, None);
@@ -366,6 +413,12 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
}
}
/// Whether `receiver`, which `before` comes before, is the application object: the name `app`
/// that no `.` comes before and that the script has not declared as its own.
fn app_receiver(&self, receiver: Option<Sig<'s>>, before: Option<Sig<'s>>) -> bool {
word(receiver, catalog::DOM_ROOTS[0]) && !member_mark(before) && !self.shadowed.first().copied().unwrap_or(true)
}
/// The methods that `receiver`, which `before` comes before, defines when it is a variable holding
/// an object literal of the script's own ([`Analyzer::writers`]), not a property of the same name;
/// 0 for anything else. A receiver the check does not follow may be a document.
+29
View File
@@ -78,6 +78,35 @@ pub(crate) const DOM_ROOTS: [&str; 4] = ["app", "activeDocument", "documents", "
// Document methods that write the file they are given: https://ai-scripting.docsforadobe.dev/jsobjref/Document/
pub(crate) const DOM_FILE_WRITES: &[&str] = &["exportFile", "exportVariables", "saveAs"];
// Application methods that read the file they are given: https://ai-scripting.docsforadobe.dev/jsobjref/Application/
pub(crate) const DOM_FILE_READS: &[&str] = &["open"];
// The document method that writes the file its options' `jobOptions.file` names, on the same page.
// It counts only when a member chain that ends with one of `DOM_DOCUMENTS` calls it.
pub(crate) const DOM_PRINT: &str = "print";
// The member chains that give a document, whole and as the chains are written (`[]` for an index,
// `()` for a call): https://ai-scripting.docsforadobe.dev/jsobjref/Application/ (`activeDocument`,
// `documents`, `open`) and https://ai-scripting.docsforadobe.dev/jsobjref/Documents/ (`add`, `addDocument`,
// `addDocumentNoUI`, `getByName`). `index` is not on that page; it comes from VectorCraft's own binding of
// the collection (`crates/engine/src/script/dom.rs`), which returns the document at a position or with a name.
pub(crate) const DOM_DOCUMENTS: &[&str] = &[
"activeDocument",
"app.activeDocument",
"documents[]",
"app.documents[]",
"documents.add()",
"app.documents.add()",
"documents.addDocument()",
"app.documents.addDocument()",
"documents.addDocumentNoUI()",
"app.documents.addDocumentNoUI()",
"documents.getByName()",
"app.documents.getByName()",
"documents.index()",
"app.documents.index()",
"app.open()",
];
// The save option of `Document.close` that saves the document to its own file:
// https://ai-scripting.docsforadobe.dev/jsobjref/Document/ and
+3 -2
View File
@@ -342,10 +342,11 @@ impl<'l> Acc<'l> {
}
pub fn member(&mut self, path: &str) {
if let Some(n) = self.members.get_mut(path) {
let key = self.echoed(path);
if let Some(n) = self.members.get_mut(&*key) {
*n = n.saturating_add(1);
} else if self.room(self.members.len()) {
self.members.insert(path.to_string(), 1);
self.members.insert(key.into_owned(), 1);
}
}
+85
View File
@@ -638,6 +638,91 @@ fn save_as_and_export_file_in_brackets_write_a_file() {
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[3, 4][..])]);
}
/// `app.open` reads the file it is given, called by name or with its name as a string literal in
/// brackets, also through a variable that holds the application; a document has no `open` method, and
/// a property or a variable named `app` is not the application.
#[test]
fn app_open_reads_a_file() {
let r = report(concat!(
"var f = new File(p);\n",
"var d = app.open(f);\n",
"app['open'](f);\n",
"app.activeDocument['open'](f);\n",
"x.app.open(f);\n",
"x.app['open'](f);\n",
"var a = app; a.open(f);\n",
"a['open'](f);\n",
"var b = x.app; b.open(f); b['open'](f);\n",
));
assert_eq!(feature(&r, "file.read").map(|f| f.lines.as_slice()), Some(&[2, 3, 7, 8][..]));
assert!(r.outside.is_empty());
let r = report("var app = {};\napp.open(f);\napp['open'](f);\n");
assert!(feature(&r, "file.read").is_none());
// A short echo limit cuts the member chains the report lists, not what the check finds.
let short = Limits { echo: 4, ..Limits::default() };
let src =
"app.open(f);\napp['open'](f);\nvar a = app; a.open(f);\nvar d = app['open'](f); d.print(o);\napp.documents.addDocumentNoUI('P').print(o);\n";
let r = check("t.jsx", src.as_bytes(), None, &short);
assert_eq!(feature(&r, "file.read").map(|f| f.lines.as_slice()), Some(&[1, 2, 3, 4][..]));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 5][..]));
assert!(!r.members.is_empty());
assert!(r.members.iter().all(|m| m.name.chars().count() <= short.echo));
}
/// A document's `print` writes the file its options' `jobOptions.file` names, called with a dot or
/// with its name in brackets, on a document (also one `add`, `addDocument`, `addDocumentNoUI`, `getByName`,
/// `index` or `app.open`, with or without brackets, returns) or a variable that holds one; reading the method without
/// calling it, and a `print` method of another object, do not.
#[test]
fn print_writes_a_file() {
let r = report(concat!(
"var o = new PrintOptions(); o.jobOptions.file = new File(p);\n",
"app.activeDocument.print(o);\n",
"app.activeDocument['print'](o);\n",
"var n = app.activeDocument['print'];\n",
"var d = app.documents[0]; d.print(o);\n",
"logger.print('hello'); logger['print']('hello');\n",
"app.activeDocument.name.concat(logger.print('x'));\n",
"app.print(o); app.activeDocument.layers[0]['print'](o); app.documents['print'](o); app.preferences.activeDocument.print(o);\n",
"var e = app.open(new File(p)); e.print(o);\n",
"activeDocument.print(o);\n",
"documents.addDocument('Print').print(o);\n",
"app.documents.addDocument('Print', s, false).print(o);\n",
"documents.addDocumentNoUI('Print').print(o);\n",
"app.documents.addDocumentNoUI('Print').print(o);\n",
"var g = app['open'](new File(p)); g.print(o);\n",
"var h = app['activeDocument'](new File(p)); h.print(o);\n",
"app.documents.index(0).print(o);\n",
"documents.index('Print')['print'](o);\n",
"var i = app.documents.index(1); i.print(o);\n",
"app.documents['index'](0).print(o);\n",
"var j = documents['getByName']('Print'); j['print'](o);\n",
"app.documents['length'](0).print(o);\n",
));
let lines = &[2, 3, 5, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21][..];
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(lines));
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", lines)]);
}
/// A string literal in brackets that names `activeDocument` or `documents` reads that property, so the
/// `print` of the document it gives writes a file; any other name in the brackets, a name that is not
/// a property's, and a computed name do not give a document.
#[test]
fn print_on_a_document_named_in_brackets_writes_a_file() {
let r = report(concat!(
"var o = new PrintOptions(); o.jobOptions.file = new File(p);\n",
"app['activeDocument'].print(o);\n",
"app[\"documents\"][0].print(o);\n",
"var d = app['documents'][1]; d.print(o);\n",
"app['documents']['add']().print(o);\n",
"app['preferences'].print(o); app['activeDocuments'].print(o); app['documents[]'].print(o);\n",
"app['documents'].print(o); app[k].print(o); x.app['activeDocument'].print(o);\n",
));
let lines = &[2, 3, 4, 5][..];
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(lines));
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", lines)]);
}
/// `saveAs` and `exportFile` called on an object literal of the script's own that defines them write
/// nothing, with `.` or in brackets. On a document, on a variable the check does not follow, on one
/// assigned something else since, and for a method the literal does not define, they write the file.
+4 -4
View File
@@ -228,11 +228,10 @@ fn narrow_arabic_area_wrap_keeps_base_and_mark_together_when_supported() {
let levels = bidi.as_ref().map_or(&[][..], |info| &info.levels);
let mut shaped = Vec::new();
shape_range(db, text, 0..text.len(), &[(0..text.len(), &style)], &[], &OtFeatures::default(), levels, &mut shaped);
let Some(first) = shaped.first() else { return };
let first = shaped.first().expect("the text shapes to glyphs");
let first_end = shaped.iter().take_while(|g| g.byte == first.byte).count();
if first.byte != 0 || first_end < 2 || first_end >= shaped.len() {
return;
}
assert_eq!(first.byte, 0, "{}: the first cluster starts the text: {shaped:?}", face.family);
assert!(first_end >= 2 && first_end < shaped.len(), "{}: the base and its mark are one cluster of two glyphs: {shaped:?}", face.family);
// Pick a narrow width that fits glyphs before one positive-advance glyph but not that next
// glyph. This ensures the old per-glyph loop would have returned inside the first cluster.
let mut prefix = shaped.first().map_or(0.0, |g| g.adv);
@@ -245,6 +244,7 @@ fn narrow_arabic_area_wrap_keeps_base_and_mark_together_when_supported() {
None
}
});
// A face whose mark has no advance gives no width that splits the cluster.
let Some(width) = width else { return };
let mut object = TextObject::point(Point::ZERO, text, style);
+1 -12
View File
@@ -183,12 +183,7 @@ fn type_arrows_keep_devanagari_clusters_across_wrapped_lines() {
let split_width: f64 = hindi_glyphs.iter().filter(|g| g.byte == split).map(|g| g.advance).sum();
assert!(prefix_width.is_finite() && prefix_width > 0.0, "setup: prefix has positive finite advance");
assert!(split_width.is_finite(), "setup: the internal raw-group advance is finite");
if split_width <= 0.0 {
eprintln!(
"SKIPPED: type_arrows_keep_devanagari_clusters_across_wrapped_lines; layout capability: the selected face has no positive-advance raw group at internal byte {split}"
);
return;
}
assert!(split_width > 0.0, "setup: {} lays out a positive-advance raw group at internal byte {split}", face.family);
let width = prefix_width + split_width * 0.5;
assert!(width.is_finite() && width > prefix_width && width < prefix_width + split_width, "setup: one measured width separates the raw groups");
@@ -205,12 +200,6 @@ fn type_arrows_keep_devanagari_clusters_across_wrapped_lines() {
assert_eq!(edit::prev_cluster(text, hindi.len()), second, "setup: logical cluster start is 6");
assert_eq!(edit::prev_cluster(text, split), second, "setup: raw line endpoint 12 is inside the grapheme");
assert_eq!(edit::next_cluster(text, split), hindi.len(), "setup: raw line endpoint 12 is not its end");
if lay.lines.len() < 2 || (lay.lines[0].start, lay.lines[0].end, lay.lines[1].start) != (0, split, split) {
eprintln!(
"SKIPPED: type_arrows_keep_devanagari_clusters_across_wrapped_lines; layout capability: the measured frame does not expose adjacent wrapped endpoints at internal byte {split}"
);
return;
}
assert!(lay.lines.len() >= 2, "setup: actual wrapping occurred");
assert_eq!(
(lay.lines[0].start, lay.lines[0].end, lay.lines[1].start),
+1 -2
View File
@@ -248,6 +248,5 @@ fn properties_and_the_control_bar_remove_the_background_at_once() {
assert!(closed(&app), "it runs at once");
assert_eq!(steps(&app), n + 1, "one undo step");
// The defaults (tolerance and softness 10): the white goes, the near-white ring fades.
let [corner, ring, block] = alphas(&app);
assert!(corner == 0 && ring > 0 && ring < 255 && block == 255, "{:?}", alphas(&app));
assert_eq!(alphas(&app), [0, 95, 255]);
}
+1 -1
View File
@@ -253,7 +253,7 @@ impl VectorcraftApp {
}
let spot_base = panels::color_guide::before_command(self);
let plugins_before = dialogs::plugin::before_command();
let r = self.session.execute(id, &params).map_err(|e| e.to_string());
let r = crate::print::execute_listing_printers(self, id, &params);
let r = panels::actions::after_recorded_command(self, r);
if r.is_ok()
&& let Some(op) = completed_pathfinder_operation(id, &params)
+7 -5
View File
@@ -158,11 +158,13 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) {
}
/// The tab at the top of window `w`'s floating OS window ([`crate::doc_windows`]): a strip with the
/// window's tab, without its ×. Dragged onto the main strip it docks there ([`doc_tabs`]); the
/// window moves by its title bar, so a tear-off is ignored. → the strip's response.
pub(crate) fn window_tab(app: &VectorcraftApp, ui: &mut Ui, w: Win) -> egui::Response {
let tabs = [DocumentTab::new(w, document_window_title(app, w).unwrap_or_default()).closable(false)];
DocumentTabs::new(tl!("Window"), &tabs).selected(w).reorderable(true).tear_off(true).large(app.session.prefs.large_tabs).show(ui).response
/// window's tab and its ×, as the tab has under the main strip. Dragged onto the main strip it
/// docks there ([`doc_tabs`]); the window moves by its title bar, so a tear-off is ignored. →
/// whether the tab's × or a middle click asked to close the window.
pub(crate) fn window_tab(app: &VectorcraftApp, ui: &mut Ui, w: Win) -> bool {
let tabs = [DocumentTab::new(w, document_window_title(app, w).unwrap_or_default())];
let strip = DocumentTabs::new(tl!("Window"), &tabs).selected(w).reorderable(true).tear_off(true).large(app.session.prefs.large_tabs);
strip.show(ui).events.into_iter().any(|event| matches!(event, DocumentTabsEvent::CloseRequested(x) if x == w))
}
/// Makes document `i` the current one, as a click on its tab does: the Home screen closes, and
@@ -84,13 +84,14 @@ fn remove_strokes_runs_the_delete_and_cancel_changes_nothing() {
let name = "10 pt. Oval";
app.run("brush.apply", json!({"name": name})).unwrap();
let before = app.session.active().unwrap().history.undo.len();
let width = app.session.active().unwrap().doc.node(path).and_then(|n| n.appearance.stroke()).unwrap().width;
ask(&mut app, json!({"name": name}), true);
answer::<BrushDeleteQuestion>(&mut app, choice, pump);
assert_eq!(open_question(&app), None);
assert_eq!(app.session.active().unwrap().history.undo.len(), before + usize::from(choice.is_some()));
let stroke = app.session.active().unwrap().doc.node(path).and_then(|n| n.appearance.stroke()).unwrap();
assert_eq!(stroke.brush.as_deref(), choice.is_none().then_some(name));
assert!(stroke.width > 0.0);
assert_eq!(stroke.width, width, "the stroke keeps its width");
}
}
+2 -2
View File
@@ -437,8 +437,8 @@ mod tests {
confirm(&mut app, &ctx);
assert!(!app.session.in_interaction());
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1);
let lighter = vectorcraft_color::Color::from_hex(&fill_hex(&app, id)).unwrap().to_rgb()[0];
assert!(lighter > 0.6, "{lighter}");
// #808080 holds less than 50% black, so taking 50% away leaves none.
assert_eq!(fill_hex(&app, id), "#ffffff");
}
#[test]
@@ -1185,4 +1185,20 @@ mod tests {
ok(&mut app);
assert_eq!(app.session.active().unwrap().doc.node(layer).unwrap().display_name(), "Fresh Draft");
}
/// `ui.layerOptions` and `ui.newLayer` open the dialog whose `key` their params text names, as `ui.inspect`
/// lists it.
#[test]
fn layer_options_params_text_names_the_dialog_key_ui_inspect_lists() {
for (command, arguments) in [("ui.layerOptions", json!({})), ("ui.newLayer", json!({})), ("ui.newLayer", json!({"sublayer": true}))] {
let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == command).expect("registered").3;
let mut app = app();
app.run(command, arguments).unwrap();
let ctx = app.ui_ctx.clone().unwrap();
let ui = crate::control::inspect(&app, &ctx);
let key = ui["dialogs"].as_array().and_then(|d| d.last()).and_then(|d| d["key"].as_str()).expect("a dialog with a key");
assert_eq!(key, KEY);
assert!(doc.contains(&format!("dialog `{key}`")), "{command} opens `{key}`, which its params text does not name");
}
}
}
@@ -127,4 +127,17 @@ mod tests {
let old: crate::UiState = serde_json::from_value(json!({"layers_panel": {"layersOnly": true}})).unwrap();
assert!(old.layers_panel.layers_only && !old.layers_panel.locate_selected, "options saved without it");
}
/// `ui.layersPanelOptions` opens the dialog whose `key` its params text names, as `ui.inspect` lists it.
#[test]
fn panel_options_params_text_names_the_dialog_key_ui_inspect_lists() {
let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == CMD).expect("registered").3;
let mut app = app();
app.run(CMD, json!({})).unwrap();
let ctx = app.ui_ctx.clone().unwrap();
let ui = crate::control::inspect(&app, &ctx);
let key = ui["dialogs"].as_array().and_then(|d| d.last()).and_then(|d| d["key"].as_str()).expect("a dialog with a key");
assert_eq!(key, CMD);
assert!(doc.contains(&format!("dialog `{key}`")), "{CMD} opens `{key}`, which its params text does not name");
}
}
@@ -208,4 +208,18 @@ mod tests {
let old: crate::UiState = serde_json::from_value(json!({})).unwrap();
assert_eq!(old.navigator_panel, crate::panels::navigator::PanelOptions::default(), "UI state saved without them");
}
/// `ui.navigatorPanelOptions` without options opens the dialog whose `key` its params text names, as `ui.inspect`
/// lists it.
#[test]
fn panel_options_params_text_names_the_dialog_key_ui_inspect_lists() {
let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == KEY).expect("registered").3;
let mut app = app();
app.run(KEY, json!({})).unwrap();
let ctx = app.ui_ctx.clone().unwrap();
let ui = crate::control::inspect(&app, &ctx);
let key = ui["dialogs"].as_array().and_then(|d| d.last()).and_then(|d| d["key"].as_str()).expect("a dialog with a key");
assert_eq!(key, KEY);
assert!(doc.contains(&format!("dialog `{key}`")), "{KEY} opens `{key}`, which its params text does not name");
}
}
+2 -1
View File
@@ -1317,7 +1317,8 @@ mod tests {
let mut app = app();
open(&mut app);
set(&app, "artboards", json!(5)).unwrap();
set(&app, "artboardLayout", json!({"layout": "gridByColumn", "rows": 3.6, "spacing": 10})).unwrap();
assert!(set(&app, "artboardLayout", json!({"layout": "gridByColumn", "rows": 3.6, "spacing": 10})).is_err(), "a fraction is refused");
set(&app, "artboardLayout", json!({"layout": "gridByColumn", "rows": 4, "spacing": 10})).unwrap();
assert_eq!(fields(&app)["artboardLayout"]["rows"], json!(4));
create(&mut app);
let st = app.session.active().unwrap();
@@ -3,8 +3,8 @@
//! clipped to them.
//!
//! Fields: `preserve` (transforms|bounds|fileDimensions|fit|fill), `align` (0-8, row by row from
//! the top left) and `clip`. OK runs `links.placementOptions` with them and `ids` (null: the
//! selected images): one undo step.
//! the top left) and `clip`. OK runs `links.placementOptions` with them and the `ids` the dialog
//! opened on (by default the images selected then): one undo step.
// PLAN: assumed craft_ui paths for ParamDialog, ParamKind, Param, DialogFields, FieldValue, HostedParamDialog and Label.
use craft::ui::contract::Bind;
@@ -48,6 +48,8 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
let source = (active.uid, active.reverts);
let ids = p.get("ids").cloned().unwrap_or(Value::Null);
let r = app.session.execute(CMD, &json!({ "ids": ids })).map_err(|e| e.to_string())?;
// The images read: OK applies to these, whatever is selected by then.
let ids = r["ids"].clone();
let placement = &r["placement"];
let align = ALIGN.iter().position(|a| Some(*a) == placement["align"].as_str()).unwrap_or(CENTRE);
let mut fields = DialogFields::from_pairs([
@@ -217,4 +217,18 @@ mod tests {
assert!(matches!(n.kind, vectorcraft_doc::NodeKind::Path { .. }), "the rectangle stays a path");
assert_eq!(st.history.undo.len(), steps + 1);
}
/// `ui.rasterEffectsSettingsDialog` opens the dialog whose `key` its params text names, as `ui.inspect` lists it.
#[test]
fn settings_dialog_params_text_names_the_dialog_key_ui_inspect_lists() {
const COMMAND: &str = "ui.rasterEffectsSettingsDialog";
let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == COMMAND).expect("registered").3;
let mut app = app();
app.run(COMMAND, json!({})).unwrap();
let ctx = app.ui_ctx.clone().unwrap();
let ui = crate::control::inspect(&app, &ctx);
let key = ui["dialogs"].as_array().and_then(|d| d.last()).and_then(|d| d["key"].as_str()).expect("a dialog with a key");
assert_eq!(key, super::CMD);
assert!(doc.contains(&format!("dialog `{key}`")), "{COMMAND} opens `{key}`, which its params text does not name");
}
}
@@ -898,3 +898,18 @@ fn optimize_to_file_size_starts_at_the_size_of_the_art_as_it_is_now() {
let bytes = fields(&app)["optimizeK"].as_f64().unwrap() * 1024.0;
assert!(bytes >= after as f64 && bytes < after as f64 + 2.0, "{bytes} for {after}");
}
/// `file.saveForWeb` without settings opens the dialog whose `key` its params text names, as `ui.inspect` lists it.
#[test]
fn params_text_names_the_dialog_key_ui_inspect_lists() {
const COMMAND: &str = "file.saveForWeb";
let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == COMMAND).expect("registered").3;
let dir = vectorcraft_testkit::temp_dir("sfw-dialog-key");
let (mut app, _) = app(&dir, false);
app.run(COMMAND, json!({})).unwrap();
let ctx = app.ui_ctx.clone().unwrap();
let ui = crate::control::inspect(&app, &ctx);
let key = ui["dialogs"].as_array().and_then(|d| d.last()).and_then(|d| d["key"].as_str()).expect("a dialog with a key");
assert_eq!(key, "save-for-web");
assert!(doc.contains(&format!("dialog `{key}`")), "{COMMAND} opens `{key}`, which its params text does not name");
}
@@ -1175,3 +1175,17 @@ fn the_range_bleed_and_subset_fields_are_named() {
}
}
}
/// `ui.pdfPresetDialog` opens the preset editor whose `key` its params text names, as `ui.inspect` lists it.
#[test]
fn preset_editor_params_text_names_the_dialog_key_ui_inspect_lists() {
const COMMAND: &str = "ui.pdfPresetDialog";
let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == COMMAND).expect("registered").3;
let (mut app, _) = app();
app.run(COMMAND, json!({})).unwrap();
let ctx = app.ui_ctx.clone().unwrap();
let ui = crate::control::inspect(&app, &ctx);
let key = ui["dialogs"].as_array().and_then(|d| d.last()).and_then(|d| d["key"].as_str()).expect("a dialog with a key");
assert_eq!(key, PDF_KEY);
assert!(doc.contains(&format!("dialog `{key}`")), "{COMMAND} opens `{key}`, which its params text does not name");
}
+176 -1
View File
@@ -39,11 +39,24 @@
//! allows are the ones Choose… picked, at most 2,048; no field sets them. Escape, `ui.dialog.cancel`
//! and `ui.dialog.confirm` without an `answer` give Deny. Enter allows nothing: both Allow buttons
//! are not the dialog's default. `selectDlg` opens the host's folder picker in its own folder.
//!
//! The jobs a script prepared for a printer (`Document.print` without a file) wait for the dialog of
//! kind `scriptPrint`, which opens once the run has ended and its changes are kept, when no other
//! dialog is open and no text field or text being typed on the canvas has the keyboard. Its fields
//! are `jobs` (each job's `document`, `printer` and `pages`, read from the jobs when it opens; no
//! field sets them) and `answer`. Only the person at the keyboard prints them, with a click on its
//! Print button or Space once Tab gave it the focus: the button takes no click for
//! [`PRINT_ENABLE_DELAY_SECS`] after the dialog is first drawn, and Enter does not print.
//! `ui.dialog.set` refuses `answer: "print"`, `ui.dialog.confirm` without `answer: "cancel"` is
//! refused, and a click made by automation is refused and the dialog opens again. Cancel, Escape,
//! `ui.dialog.cancel` and `answer: "cancel"` drop the jobs, from anyone; the script's changes stay
//! either way.
use std::path::Path;
use std::sync::Arc;
use craft::host::{PickRequest, Picked};
use craft::keymap::Key;
use craft::theme::variant::Tone;
use craft::ui::buttons::Button;
use craft::ui::contract::{Bind, Outcome as _, Props as _, Scroll, Show as _, ShowContainer as _};
@@ -52,6 +65,7 @@ use craft::ui::dialog::{
};
use craft::ui::display::Text;
use craft::ui::layout_components::Stack;
use craft::ui::runtime::keys;
use craft::ui::sections::{DialogRole, FooterButton};
use craft::ui::text::TextField;
use egui::Ui;
@@ -60,6 +74,7 @@ use vectorcraft_engine::cmd::scripts::{RUN_EXTS, TOO_LARGE, runs};
use vectorcraft_engine::file_access::ScopeHandle;
use vectorcraft_engine::script::dialogs::{MAX_PROMPT_BYTES, cut_to, shown_text};
use vectorcraft_engine::script::files::{MAX_ENTRIES, PickAnswer, PickerKind, ScriptPicker};
use vectorcraft_engine::script::printing::PreparedPrint;
use vectorcraft_engine::script::{DialogAnswer, MAX_SOURCE_BYTES, ScriptDialog};
use super::script_window::{self, ScriptWindow};
@@ -76,6 +91,8 @@ pub const CLOSE_KIND: &str = "scriptClose";
pub const NOTICE_KIND: &str = "scriptDialog";
/// The dialog kind of a script's file dialogs.
pub const PICKER_KIND: &str = "scriptFiles";
/// The dialog kind of the question before the jobs a script prepared for a printer are sent.
pub const PRINT_KIND: &str = "scriptPrint";
/// Why Allow Once and Always Allow are refused to automation.
pub(crate) const BY_PERSON: &str = "Only the person at the keyboard can allow a script's file access";
@@ -744,17 +761,21 @@ pub(crate) fn settle_close(app: &mut VectorcraftApp) {
/// Takes the answers of the script's dialogs, once per frame, and gives them to the run.
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
let Some((notice, files, run, growth, close)) = with_host(app, |host, _| {
let Some((notice, files, run, growth, close, print)) = with_host(app, |host, _| {
(
host.take::<ScriptNotice>(),
host.take::<ScriptFiles>(),
host.take::<RunQuestion>(),
host.take::<GrowthQuestion>(),
host.take::<CloseQuestion>(),
host.take::<ScriptPrint>(),
)
}) else {
return;
};
if let Some(result) = print {
settle_print(app, result);
}
if let Some(result) = notice {
settle_notice(app, result);
}
@@ -963,3 +984,157 @@ fn choose(app: &mut VectorcraftApp) {
Ok(Value::Null)
});
}
/// How long the print question's Print button takes no click after the dialog is first drawn, in
/// seconds: VectorCraft's own value, so a click or key meant for what was there before does not
/// send a job.
pub(crate) const PRINT_ENABLE_DELAY_SECS: f64 = 1.0;
/// Opens the question before the jobs a script prepared for a printer are sent, once the run has
/// ended, no other dialog is open and nothing is being typed: while a text field or text on the
/// canvas has the keyboard it waits, and a later poll opens it.
pub(crate) fn ask_print(app: &mut VectorcraftApp) {
if app.session.script_running() || !app.session.script_prints_waiting() || busy(app) {
return;
}
let typing = app.ui_ctx.as_ref().is_some_and(egui::Context::text_edit_focused) || app.session.tool_wants_text();
if typing {
return;
}
let dialog = ScriptPrint::new(app.session.script_prints());
with_host(app, |host, _| host.open(dialog));
}
/// One job as the print question lists it.
#[derive(Clone)]
struct PrintRow {
document: String,
printer: String,
pages: u64,
}
/// What the print question answers with: whether Print was clicked.
pub(crate) struct PrintAnswer {
pub(crate) print: bool,
}
/// The question before the jobs a script prepared for a printer are sent. It lists the jobs as they
/// were when it opened, so no field of the dialog changes what the person reads.
pub(crate) struct ScriptPrint {
jobs: Vec<PrintRow>,
/// When the dialog was first drawn, on egui's clock.
shown_at: Option<f64>,
answer: Option<&'static str>,
}
impl ScriptPrint {
fn new(jobs: &[PreparedPrint]) -> Self {
let jobs = jobs.iter().map(|j| PrintRow { document: j.title.clone(), printer: j.printer.clone(), pages: j.sheets }).collect();
Self { jobs, shown_at: None, answer: None }
}
}
impl StackDialog for ScriptPrint {
type Result = PrintAnswer;
fn id(&self) -> DialogId {
dialog_id(PRINT_KIND)
}
fn key(&self) -> Option<&str> {
Some(PRINT_KIND)
}
/// Print takes no click until [`PRINT_ENABLE_DELAY_SECS`] after the dialog was first drawn, and
/// is not the dialog's default: Enter never prints, also on the focused button.
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<PrintAnswer>> {
let now = ui.input(|i| i.time);
// A focused button takes Enter as a click: an Enter held, or pressed in this pass and let go in it too, refuses Print.
let pressed = |e: &egui::Event| matches!(e, egui::Event::Key { key: egui::Key::Enter, pressed: true, .. });
let enter = keys::held(ui.ctx()).contains(&Key::Enter) || ui.input(|i| i.raw.events.iter().any(pressed));
let wait = (*self.shown_at.get_or_insert(now) + PRINT_ENABLE_DELAY_SECS - now).max(0.0);
if wait > 0.0 {
ui.ctx().request_repaint_after_secs(wait as f32);
}
// Print pressed with Enter is refused and leaves the question open.
let buttons = [
FooterButton::new(tl!("Print"), DialogRole::Other).enabled(wait <= 0.0).stays_open(enter),
FooterButton::new(tl!("Cancel"), DialogRole::Cancel),
];
let jobs = &self.jobs;
let prompt =
Prompt::new(tl!("Print"), tl!("The script asks to print these jobs. Its changes to the documents are kept whether or not you print."))
.answers(buttons)
.extras(move |ui| {
egui::ScrollArea::vertical().id_salt("script-print-jobs").max_height(200.0).show(ui, |ui| {
egui::Grid::new("script-print-jobs").num_columns(3).spacing([16.0, 4.0]).show(ui, |ui| {
for head in [tl!("Document"), tl!("Printer"), tl!("Pages")] {
Text::new(head).show(ui);
}
ui.end_row();
for job in jobs {
Text::new(shown_text(&job.document, false)).show(ui);
Text::new(shown_text(&job.printer, false)).show(ui);
Text::new(job.pages.to_string()).show(ui);
ui.end_row();
}
});
});
});
match prompt.show(ui).picked? {
0 if wait <= 0.0 && !enter => Some(DialogResult::Ok(PrintAnswer { print: true })),
0 => None,
_ => Some(DialogResult::Cancel),
}
}
/// `ui.dialog.confirm` takes only Cancel.
fn confirm(&mut self, _: &egui::Context) -> Option<PrintAnswer> {
(self.answer == Some("cancel")).then_some(PrintAnswer { print: false })
}
fn json_fields(&self) -> Option<Value> {
let jobs: Vec<Value> = self.jobs.iter().map(|j| json!({"document": j.document, "printer": j.printer, "pages": j.pages})).collect();
Some(json!({ "jobs": jobs, "answer": self.answer }))
}
fn set_json_field(&mut self, _: &egui::Context, field: &str, value: Value) -> Result<(), String> {
if field != "answer" {
return Err(FieldRefusal::Unknown.message(field));
}
self.answer = Some(match value.as_str() {
Some("cancel") => "cancel",
Some("print") => return Err(PRINT_BY_PERSON.into()),
_ => return Err("`answer` for the print question must be one of: print, cancel".into()),
});
Ok(())
}
}
/// Sends the jobs when the person at the keyboard clicked Print; drops them on Cancel, from anyone.
/// Print from a pass automation drove is refused and the question opens again.
pub(crate) fn settle_print(app: &mut VectorcraftApp, result: DialogResult<PrintAnswer>) {
let print = result.ok().is_some_and(|a| a.print);
if print && app.automation_asked() {
app.status(PRINT_BY_PERSON);
ask_print(app);
return;
}
let jobs = app.session.take_script_prints();
if jobs.is_empty() {
return;
}
if !print {
app.status(PRINTS_DROPPED);
return;
}
// The dialog is closed and the jobs are taken: a failure is reported in the status bar.
if let Err(e) = crate::print::send_script_prints(app, jobs) {
app.status(e);
}
}
/// Print's refusal when automation asked for it.
pub(crate) const PRINT_BY_PERSON: &str = "Only the person at the keyboard can print a script's print jobs";
/// The status after Cancel.
pub(crate) const PRINTS_DROPPED: &str = "The script's print jobs were not sent";
+14 -3
View File
@@ -18,7 +18,8 @@
use craft::ui::contract::{Props as _, ShowContainer as _};
use craft::ui::runtime::windows::WindowHost;
use craft::ui::shell::DocumentWindow;
use craft::ui::shell::{DocumentWindow, Frame, TitleBar};
use craft::ui::style::SurfaceKind;
use serde_json::{Value, json};
use crate::VectorcraftApp;
@@ -446,6 +447,7 @@ fn show_windows(app: &mut VectorcraftApp, ui: &mut egui::Ui) {
let is_current = views::current(app) == Some(win);
let live = is_current && !crate::menus::home_showing(app);
let mut pressed = false;
let mut tab_close = false;
let mut found = (None, None, false);
let window = DocumentWindow::new(title).id_salt((w.uid, w.number, w.generation)).first_placed(w.place.translate(origin));
let window = if raise == Some((w.uid, w.view)) { window.raise() } else { window };
@@ -456,7 +458,16 @@ fn show_windows(app: &mut VectorcraftApp, ui: &mut egui::Ui) {
}
// A press anywhere on the window, its title bar and tab included, makes its document current.
pressed = pressed_on_layer(ui);
crate::chrome::window_tab(app, ui, win);
// Where the app draws the OS window's frame, the tab sits in a title bar: its free area moves the
// window and its captions act on it. The fallback layer has a title row of its own.
let app_frame = !matches!(WindowHost::of(ui.ctx()).frame(), Frame::Native);
if ui.ctx().viewport_id() != egui::ViewportId::ROOT && app_frame {
let tab = |ui: &mut egui::Ui, _: &mut craft::ui::contract::BodyCx<'_>| tab_close |= crate::chrome::window_tab(app, ui, win);
let bar = TitleBar::new().surface(SurfaceKind::Background).show_fitted(ui, tab, |_, _| {});
tab_close |= bar.close_requested;
} else {
tab_close = crate::chrome::window_tab(app, ui, win);
}
let areas = [(win, ui.available_rect_before_wrap())];
let unfitted = crate::canvas::panes::refit_resized(app, &areas);
// The display that shows the window, the size of its body and whether its view fits it in this frame.
@@ -479,7 +490,7 @@ fn show_windows(app: &mut VectorcraftApp, ui: &mut egui::Ui) {
x.place = placed.translate(-origin);
}
}
if out.close_requested.is_some() {
if out.close_requested.is_some() || tab_close {
close = Some(win);
} else if (out.focus_gained || pressed) && !is_current && !app.any_dialog_open() {
activate = Some(win);
+85 -1
View File
@@ -602,12 +602,15 @@ fn a_document_made_current_in_presentation_mode_comes_to_the_front_after_it() {
/// A stand-in for the window system of the documents' OS windows: it runs each one's frame and asks
/// each to close while `close` is set. Each
/// window is 500 × 400 points with its top-left corner at `origin` on the screen, and its next
/// frame takes `events`.
/// frame takes `events`. `commands` gathers the commands the windows' frames sent, and `strip` is where the last
/// window drew its tab strip, in its own points.
#[derive(Default)]
struct Host {
close: bool,
origin: Pos2,
events: Vec<egui::Event>,
commands: Vec<egui::ViewportCommand>,
strip: Option<egui::Rect>,
}
fn native_host() -> std::rc::Rc<std::cell::RefCell<Host>> {
@@ -638,6 +641,14 @@ fn native_host() -> std::rc::Rc<std::cell::RefCell<Host>> {
let input = egui::RawInput { viewport_id: id, viewports, screen_rect: Some(rect), events, ..Default::default() };
let mut full = ctx.run_ui(input, |ui| (viewport.viewport_ui_cb)(ui));
full.textures_delta.clear();
let mut shared = shared.borrow_mut();
shared.commands.extend(full.viewport_output.values().flat_map(|out| out.commands.iter().cloned()));
let nodes = full.platform_output.accesskit_update.as_ref().map_or(&[][..], |u| &u.nodes[..]);
let strip =
nodes.iter().find(|(_, n)| n.role() == egui::accesskit::Role::TabList && n.label() == Some("Window")).and_then(|(_, n)| n.bounds());
if let Some(b) = strip {
shared.strip = Some(egui::Rect::from_min_max(pos2(b.x0 as f32, b.y0 as f32), pos2(b.x1 as f32, b.y1 as f32)));
}
});
host
}
@@ -666,6 +677,79 @@ fn closing_an_os_window_keeps_it_while_its_unsaved_document_stays_open() {
assert_eq!(app.ui.floating.len(), 1, "its window is still shown");
}
/// [`crate::testing::ui_context`] with the frame the desktop host gives a window on Windows: no OS title bar, so the
/// app draws the title bar and its caption buttons.
fn integrated_frame_context() -> egui::Context {
use craft::window::policy::{Backend, Desktop, Os, Runtime, TitleBarPref, WindowKind, decide};
let desktop = Desktop::detect(Backend::X11);
let decision = decide(Os::Windows, Runtime::Native, Backend::X11, &desktop, WindowKind::Main, TitleBarPref::Integrated, None);
assert!(matches!(decision.frame, Frame::Integrated(_)), "{:?}", decision.frame);
let ctx = egui::Context::default();
craft::ui::shell::embed::install(&ctx, craft::ui::testing::install_spec().frame(decision), &crate::ui_fonts()).expect("the runtime installs");
craft::ui::testing::windows::set_os(&ctx, Os::Windows);
let prefs = vectorcraft_engine::Prefs::default();
let print = crate::state::print_ppi(prefs.display_print_size, None);
craft::ui::runtime::frame::set_input(&ctx, craft::ui::runtime::frame::FrameInput::new(crate::app::root_env(&prefs, 1.0, print)));
ctx
}
/// A floating document's OS window without an OS title bar moves when the free part of the bar holding its tab is
/// dragged.
#[test]
fn a_floating_os_window_without_an_os_title_bar_moves_by_the_bar_of_its_tab() {
let host = native_host();
let ctx = integrated_frame_context();
ctx.set_embed_viewports(false);
let mut app = app_with(2);
if !WindowHost::of(&ctx).viewports_available() {
// Wayland: the windows are inside the main window, where the layer's title row moves them.
return;
}
frame(&mut app, &ctx, vec![]);
app.run("window.arrange.floatInWindow", json!({"index": 1})).unwrap();
frame(&mut app, &ctx, vec![]);
frame(&mut app, &ctx, vec![]);
host.borrow_mut().commands.clear();
// Just right of the tab strip, on the bar's free band, in the window's own points.
let strip = host.borrow().strip.expect("the window drew its tab strip");
let at = pos2(strip.right() + 8.0, strip.center().y);
let mut commands = Vec::new();
for events in [
vec![egui::Event::PointerMoved(at)],
vec![button(at, true)],
vec![egui::Event::PointerMoved(at + vec2(10.0, 4.0))],
vec![egui::Event::PointerMoved(at + vec2(30.0, 12.0))],
vec![button(at + vec2(30.0, 12.0), false)],
] {
host.borrow_mut().events = events;
let out = run_frame(&mut app, &ctx, vec![]);
commands.extend(out.viewport_output.values().flat_map(|v| v.commands.iter().cloned()));
}
commands.append(&mut host.borrow_mut().commands);
assert!(commands.contains(&egui::ViewportCommand::StartDrag), "the drag moves the window: {commands:?}");
assert!(is_floating(&app, 1), "the document still floats");
}
/// A floating document's tab keeps its close button: a middle click on it, as on a tab under the main strip, closes
/// the window and its document.
#[test]
fn a_floating_documents_tab_closes_its_window() {
let mut app = app_with(2);
let ctx = crate::testing::ui_context();
frame(&mut app, &ctx, vec![]);
app.run("window.arrange.floatInWindow", json!({"index": 0})).unwrap();
frame(&mut app, &ctx, vec![]);
let shapes = frame(&mut app, &ctx, vec![]);
let title = app.session.documents()[0].title();
let tab = window_tab_at(&shapes, &title, window_of(&app, &ctx, 0));
let middle = |pressed| egui::Event::PointerButton { pos: tab, button: egui::PointerButton::Middle, pressed, modifiers: egui::Modifiers::NONE };
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(tab), middle(true)]);
frame(&mut app, &ctx, vec![middle(false)]);
frame(&mut app, &ctx, vec![]);
assert_eq!(app.session.documents().len(), 1, "its document closed");
assert!(app.ui.floating.is_empty(), "its window closed");
}
/// The update prompt, opening on its own, takes the keyboard once from a document's OS window that
/// has it, and leaves the keyboard alone when none of those windows has it.
#[test]
+1
View File
@@ -22,6 +22,7 @@ pub(crate) fn panel_body(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) {
| "blend"
| "character"
| "color"
| "docInfo"
| "magicWand"
| "openType"
| "paragraph"
+8 -8
View File
@@ -1275,7 +1275,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.layerOptions",
"Options for Selection…",
"",
"{ids?|id?} open Layer Options for Layers panel rows (default: the highlighted rows, else the current layer), filled in from the first: dialog `layerOptions`, fields name, color (a preset name such as \"Light Blue\" or #rrggbb), template, locked, visible, printable, preview, dimImages (bool), dimPercent (0–100); an object's row has name, visible and locked. Unchanged OK adds no undo step; edits run layer.setProps in one undo step. Existing names are preserved unless Name is edited or explicitly set; for several rows it sends only the fields set in the dialog",
"{ids?|id?} open Layer Options for Layers panel rows (default: the highlighted rows, else the current layer), filled in from the first: dialog `ui.layerOptions`, fields name, color (a preset name such as \"Light Blue\" or #rrggbb), template, locked, visible, printable, preview, dimImages (bool), dimPercent (0–100); an object's row has name, visible and locked. Unchanged OK adds no undo step; edits run layer.setProps in one undo step. Existing names are preserved unless Name is edited or explicitly set; for several rows it sends only the fields set in the dialog",
),
(
"ui.layerDelete",
@@ -1293,7 +1293,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.newLayer",
"New Layer Options…",
"Cmd+Alt+L",
"{sublayer?: bool} open Layer Options for a new layer (or a sublayer of the current layer), named and coloured as it would be: dialog `layerOptions` with mode new|newSublayer; OK runs layer.new or layer.newSublayer with the fields. In isolation mode, a layer that would be outside the isolated art is an error and nothing opens; OK checks again, and with isolation mode started since, it returns the same error and makes no layer",
"{sublayer?: bool} open Layer Options for a new layer (or a sublayer of the current layer), named and coloured as it would be: dialog `ui.layerOptions` with mode new|newSublayer; OK runs layer.new or layer.newSublayer with the fields. In isolation mode, a layer that would be outside the isolated art is an error and nothing opens; OK checks again, and with isolation mode started since, it returns the same error and makes no layer",
),
(
"ui.newArtboard",
@@ -1311,13 +1311,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.layersPanelOptions",
"Panel Options…",
"",
"{} open the Layers panel's Panel Options: dialog `layersPanelOptions`, fields layersOnly, locateSelected (Locate Selected Objects, off by default: when the last selected object changes outside the panel, on the canvas or by a command, the panel opens the layers and groups around it and scrolls to its row, as after layer.locate, without highlighting the row; when Show Layers Only, a search or the filter leaves the object without a row, the panel opens no rows for it and scrolls as with the option off; a change made during a drag is located when the drag ends), rowSize (small|medium|large|other), otherSize (12–100 pt), thumbLayers, thumbGroups, thumbObjects; OK applies them (kept with the UI state)",
"{} open the Layers panel's Panel Options: dialog `ui.layersPanelOptions`, fields layersOnly, locateSelected (Locate Selected Objects, off by default: when the last selected object changes outside the panel, on the canvas or by a command, the panel opens the layers and groups around it and scrolls to its row, as after layer.locate, without highlighting the row; when Show Layers Only, a search or the filter leaves the object without a row, the panel opens no rows for it and scrolls as with the option off; a change made during a drag is located when the drag ends), rowSize (small|medium|large|other), otherSize (12–100 pt), thumbLayers, thumbGroups, thumbObjects; OK applies them (kept with the UI state)",
),
(
"ui.navigatorPanelOptions",
"Panel Options…",
"",
"{color?: #rrggbb or a preset name (Light Red, the default, then the layer colors such as \"Light Blue\"), solidDashes?: bool (Draw Dashed Lines as Solid Lines, off by default: the Navigator's thumbnail draws dashed strokes without their dashes; the canvas, printing and exports keep them), viewArtboardContentsOnly?: bool (View Artboard Contents Only in the panel menu, on by default and for UI state saved without it: the thumbnail fits the artboards and draws only the art inside them, cut at each artboard's edges; off, it also shows the art on the pasteboard)} set the Navigator panel's options, the color its view box is drawn in, solid dashes and artboard contents only (kept with the UI state) → {color, solidDashes, viewArtboardContentsOnly}; with none, open its Panel Options (dialog `navigatorPanelOptions`, fields color, solidDashes; OK sets them); an error for a value that is not a color or not true or false, which changes nothing",
"{color?: #rrggbb or a preset name (Light Red, the default, then the layer colors such as \"Light Blue\"), solidDashes?: bool (Draw Dashed Lines as Solid Lines, off by default: the Navigator's thumbnail draws dashed strokes without their dashes; the canvas, printing and exports keep them), viewArtboardContentsOnly?: bool (View Artboard Contents Only in the panel menu, on by default and for UI state saved without it: the thumbnail fits the artboards and draws only the art inside them, cut at each artboard's edges; off, it also shows the art on the pasteboard)} set the Navigator panel's options, the color its view box is drawn in, solid dashes and artboard contents only (kept with the UI state) → {color, solidDashes, viewArtboardContentsOnly}; with none, open its Panel Options (dialog `ui.navigatorPanelOptions`, fields color, solidDashes; OK sets them); an error for a value that is not a color or not true or false, which changes nothing",
),
(
"ui.attributesPanelOptions",
@@ -1646,7 +1646,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.rasterEffectsSettingsDialog",
"Document Raster Effects Settings Dialog",
"",
"{} open Document Raster Effects Settings (dialog `rasterEffectsSettings`: the document.rasterEffectsSettings fields); OK runs it. The menu item opens it too",
"{} open Document Raster Effects Settings (dialog `document.rasterEffectsSettings`: the document.rasterEffectsSettings fields); OK runs it. The menu item opens it too",
),
(
"ui.effectGalleryDialog",
@@ -1664,7 +1664,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.pdfPresetDialog",
"PDF Preset",
"",
"{name?: a saved preset to edit | preset?: the preset a new one starts from (default VectorCraft Default)} open the preset editor (dialog `pdfPreset`: the Save PDF dialog's option fields plus `name` and `description`); OK runs pdf.preset.save and returns to PDF Presets",
"{name?: a saved preset to edit | preset?: the preset a new one starts from (default VectorCraft Default)} open the preset editor (dialog `pdf-export`: the Save PDF dialog's option fields plus `name` and `description`); OK runs pdf.preset.save and returns to PDF Presets",
),
("file.openRecent11", "Open Recent File 11", "", "{}"),
("file.openRecent12", "Open Recent File 12", "", "{}"),
@@ -1919,7 +1919,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
crate::panels::actions::RESET,
"Reset Actions",
"",
"{mode?: \"replace\" | \"append\"} Reset Actions. replace (the default) replaces every set in the Actions panel with a new copy of the built-in Default Actions set, makes it current and selected, clears the panel's selected action and step and its expanded actions, and closes an open Set Options, New Action, Batch or step dialog that names a set; when the panel already shows only the built-in set as it comes in that state, nothing changes, the sets keep their ids and changed is false. append adds a new copy of the built-in set after the sets there are, with the next free number when its name is in use (Default Actions 2), and keeps the current set and the selection. Omitted params count as {}. Params of another type, another key, another mode, or a reset while an action records or plays (also while it waits at a stop) is an error and changes nothing. No undo step is recorded. The panel menu's Reset Actions asks first (dialog `resetActions`): OK runs this with replace, Append with append → {changed, mode, set: the first built-in set's index}",
"{mode?: \"replace\" | \"append\"} Reset Actions. replace (the default) replaces every set in the Actions panel with a new copy of the built-in Default Actions set, makes it current and selected, clears the panel's selected action and step and its expanded actions, and closes an open Set Options, New Action, Batch or step dialog that names a set; when the panel already shows only the built-in set as it comes in that state, nothing changes, the sets keep their ids and changed is false. append adds a new copy of the built-in set after the sets there are, with the next free number when its name is in use (Default Actions 2), and keeps the current set and the selection. Omitted params count as {}. Params of another type, another key, another mode, or a reset while an action records or plays (also while it waits at a stop) is an error and changes nothing. No undo step is recorded. The panel menu's Reset Actions asks first (dialog `actionsQuestion`): OK runs this with replace, Append with append → {changed, mode, set: the first built-in set's index}",
),
(
crate::panels::actions::CLEAR,
@@ -1950,7 +1950,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"file.saveForWeb",
"Save for Web (Legacy)…",
"Cmd+Alt+Shift+S",
"{} open Save for Web (dialog `saveForWeb`: fields = the webExport.settings settings, `preset` loads a preset, __view: original|optimized|2up|4up, __zoom, __kbps; Save… remembers the settings and writes the files, Done only remembers them); with settings = document.exportForWeb, written to path, else a picked file (the web downloads the files) → {path, files, bytes}",
"{} open Save for Web (dialog `save-for-web`: fields = the webExport.settings settings, `preset` loads a preset, __view: original|optimized|2up|4up, __zoom, __kbps; Save… remembers the settings and writes the files, Done only remembers them); with settings = document.exportForWeb, written to path, else a picked file (the web downloads the files) → {path, files, bytes}",
),
(
"file.saveForWeb.browser",
@@ -1344,3 +1344,17 @@ fn insert_select_object_refuses_bad_params_and_changes_nothing() {
}
assert!(app.run(INSERT_SELECT_OBJECT, place(json!({"note": "x".repeat(1024)}))).is_ok(), "1,024 bytes goes in");
}
/// The panel menu's Reset Actions asks in the dialog whose `key` the params text of [`RESET`] names, as `ui.inspect`
/// lists it.
#[test]
fn reset_params_text_names_the_question_key_ui_inspect_lists() {
let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == RESET).expect("registered").3;
let mut app = new_app();
edits::ask_reset(&mut app);
let ctx = app.ui_ctx.clone().unwrap();
let ui = crate::control::inspect(&app, &ctx);
let key = ui["dialogs"].as_array().and_then(|d| d.last()).and_then(|d| d["key"].as_str()).expect("a dialog with a key");
assert_eq!(key, "actionsQuestion");
assert!(doc.contains(&format!("dialog `{key}`")), "Reset Actions opens `{key}`, which the params text of {RESET} does not name");
}
+3
View File
@@ -884,6 +884,9 @@ impl LibraryKind for BrushLibraries {
fn path(app: &VectorcraftApp, id: &str) -> Option<String> {
app.session.brush_libraries.path(id).map(str::to_string)
}
fn same(a: &Self::Lib, b: &Self::Lib) -> bool {
Rc::ptr_eq(a, b)
}
fn rows<'a>(lib: &'a Self::Lib, _id: &str) -> Vec<Row<'a, LibBrush>> {
lib.iter().map(|b| Row { name: b.name(), item: Some(b) }).collect()
}
+1 -1
View File
@@ -950,7 +950,7 @@ mod tests {
app.canvas.doc_info.clone().unwrap().1
};
let all = shown(&mut app, "");
assert!(all["pathArea"].as_f64().is_some_and(|a| a > 0.0), "{}", all["pathArea"]);
assert!(all["pathArea"].as_f64().is_some_and(|a| (a - 200.0).abs() < 1e-6), "{}", all["pathArea"]);
assert!(Arc::ptr_eq(&all, &shown(&mut app, "objects")), "Objects reuses All Categories' result");
for category in ["document", "fonts"] {
let other = shown(&mut app, category);
@@ -1004,6 +1004,9 @@ impl LibraryKind for GraphicStyleLibraries {
fn path(app: &VectorcraftApp, id: &str) -> Option<String> {
app.session.style_libraries.path(id).map(str::to_string)
}
fn same(a: &Self::Lib, b: &Self::Lib) -> bool {
Arc::ptr_eq(a, b)
}
fn rows<'a>(lib: &'a Self::Lib, _id: &str) -> Vec<Row<'a, LibStyle>> {
lib.iter().map(|s| Row { name: &s.style().name, item: Some(s) }).collect()
}
+71 -17
View File
@@ -15,9 +15,11 @@
//! Library… (`ui.libraryPanel.locate`). The find text is the browser's; the selection is panel state
//! (`UiState::library_selection`).
use std::any::Any;
use std::borrow::Cow;
use std::cell::RefCell;
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::rc::Rc;
use craft::behavior::{IconId, Selection, SelectionModel};
use craft::host::PickRequest;
@@ -25,9 +27,7 @@ use craft::theme::variant::Tone;
use craft::ui::contract::{Bind, MemoKey, MemoProps, SelectMode, Show as _, ShowContainer as _, Trigger};
use craft::ui::menu::{Menu, MenuItem, PanelRow};
use craft::ui::notices::{Notice, NoticeAction, NoticeLayout};
use craft::ui::patterns::presets::{
PresetBrowser, PresetEvent, PresetFns, PresetKind, PresetRow, PresetRowMenu, PresetSource, PresetState, PresetView,
};
use craft::ui::patterns::presets::{PresetBrowser, PresetEvent, PresetFns, PresetRow, PresetRowMenu, PresetSource, PresetState, PresetView};
use craft::ui::primitives::{ContentPainterCx, IconSpec};
use craft::ui::runtime::access::PopupKind;
use craft::ui::runtime::commands::{CommandRef, CommandState, CommandStates};
@@ -122,7 +122,7 @@ pub(crate) trait LibraryKind {
/// The view a panel shows until another is picked.
const VIEW: View = View::MediumThumb;
/// A library's contents, cheap to clone.
type Lib;
type Lib: Clone + 'static;
type Item: Sync;
/// What the thumbnails paint with besides each item (a panel setting, the documents a library's patterns come
/// from); `()` for nothing.
@@ -135,6 +135,9 @@ pub(crate) trait LibraryKind {
fn find(app: &VectorcraftApp, key: &str) -> Found;
/// The file library `id` was read from, if any.
fn path(app: &VectorcraftApp, id: &str) -> Option<String>;
/// Whether `a` and `b` are the same contents, not only equal ones: the panel reuses the browser rows it built for
/// `a` while [`get`](Self::get) returns `b`.
fn same(a: &Self::Lib, b: &Self::Lib) -> bool;
/// The rows of library `id`; the browser's search filters what it shows (by the shown name and
/// [`PresetRow::search_name`]).
fn rows<'a>(lib: &'a Self::Lib, id: &str) -> Vec<Row<'a, Self::Item>>;
@@ -608,6 +611,7 @@ fn saved_view(view: PresetView, zoom: f64) -> View {
/// The browser rows of library `id`'s `rows`, flat: a folder is a row of its own before its items, which a click
/// selects as it selects an item (production's folder tiles neither opened nor closed).
fn browser_rows<K: LibraryKind>(panel: &str, id: &str, rows: &[Row<K::Item>]) -> Vec<PresetRow<LibraryKey>> {
BUILDS.with(|n| n.set(n.get() + 1));
rows.iter()
.map(|r| {
let label = K::label(id, r.name);
@@ -624,22 +628,73 @@ fn browser_rows<K: LibraryKind>(panel: &str, id: &str, rows: &[Row<K::Item>]) ->
.collect()
}
/// A library panel's browser rows, built for one library's contents in one UI language.
struct BuiltRows<L> {
/// The contents the rows were built from, held so that [`LibraryKind::same`] does not match other contents
/// later stored at the same address.
lib: L,
lang: crate::i18n::Lang,
/// Different for every build, so the browser's memo key changes with the rows.
build: u64,
rows: Rc<Vec<PresetRow<LibraryKey>>>,
/// Each item row's position in [`LibraryKind::rows`], by stored name.
items: Rc<HashMap<String, usize>>,
}
thread_local! {
/// Each library panel's [`BuiltRows`], by panel id.
static BUILT_ROWS: RefCell<HashMap<String, Box<dyn Any>>> = RefCell::new(HashMap::new());
/// How many times [`browser_rows`] has run, for tests.
static BUILDS: Cell<u64> = const { Cell::new(0) };
}
/// How many times the panels have built browser rows on this thread.
#[cfg(test)]
pub(crate) fn row_builds() -> u64 {
BUILDS.with(Cell::get)
}
/// [`BuiltRows::build`], [`BuiltRows::rows`] and [`BuiltRows::items`].
type Built = (u64, Rc<Vec<PresetRow<LibraryKey>>>, Rc<HashMap<String, usize>>);
/// Panel `panel`'s browser rows of `lib`: the ones built before while the panel shows the same contents in the same
/// language, otherwise built now. Building drops the rows of the panels that are no longer open in `ui`.
fn built_rows<K: LibraryKind>(ui: &UiState, panel: &str, id: &str, lib: &K::Lib) -> Built {
let lang = crate::i18n::current();
BUILT_ROWS.with(|cache| {
let mut cache = cache.borrow_mut();
if let Some(b) = cache.get(panel).and_then(|b| b.downcast_ref::<BuiltRows<K::Lib>>())
&& b.lang == lang
&& K::same(&b.lib, lib)
{
return (b.build, b.rows.clone(), b.items.clone());
}
let flat = K::rows(lib, id);
let rows = Rc::new(browser_rows::<K>(panel, id, &flat));
let items = Rc::new(flat.iter().enumerate().filter(|(_, r)| r.item.is_some()).map(|(i, r)| (r.name.to_string(), i)).collect());
let build = BUILDS.with(Cell::get);
let built = BuiltRows { lib: lib.clone(), lang, build, rows: rows.clone(), items: Rc::clone(&items) };
cache.retain(|p, _| is_open(ui, p));
cache.insert(panel.to_string(), Box::new(built));
(build, rows, items)
})
}
/// What a library's browser shows: its rows, the items their thumbnails paint and what those paint with.
struct Shown<'a, K: LibraryKind> {
/// [`BuiltRows::build`] of `rows`.
build: u64,
rows: &'a [PresetRow<LibraryKey>],
items: HashMap<&'a str, &'a K::Item>,
flat: &'a [Row<'a, K::Item>],
items: &'a HashMap<String, usize>,
thumbs: K::Thumbs,
}
/// By the rows (each names its library and item, whose look a library keeps) and what the thumbnails paint with.
/// By the build of the rows (each names its library and item, whose look a library keeps) and what the thumbnails
/// paint with.
impl<K: LibraryKind> MemoProps for Shown<'_, K> {
fn key(&self, key: &mut MemoKey) {
for row in self.rows {
row.key.key(key);
row.label.key(key);
row.depth.key(key);
(row.kind == PresetKind::Item).key(key);
}
self.build.key(key);
self.rows.len().key(key);
self.thumbs.key(key);
}
@@ -658,15 +713,14 @@ fn body<K: LibraryKind>(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) {
};
let panel = panel_id(K::KIND, id);
let (view, hide_find) = settings(&app.ui, K::KIND, id).map_or((K::VIEW, false), |s| (s.view.unwrap_or(K::VIEW), s.hide_find));
let (build, rows, items) = built_rows::<K>(&app.ui, &panel, id, &lib);
let flat = K::rows(&lib, id);
let rows = browser_rows::<K>(&panel, id, &flat);
let items = flat.iter().filter_map(|r| r.item.map(|i| (r.name, i))).collect();
let fns = PresetFns::new(|shown: &Shown<'_, K>, _| shown.rows.to_vec()).thumb(|shown, cx, rect, info| {
if let Some(item) = shown.items.get(info.key.name.as_str()) {
if let Some(item) = shown.items.get(info.key.name.as_str()).and_then(|&i| shown.flat.get(i)).and_then(|r| r.item) {
K::thumb(&shown.thumbs, cx, rect, item);
}
});
let source = PresetSource::new(Shown::<K> { rows: &rows, items, thumbs: K::thumbs(app, &lib) }, fns);
let source = PresetSource::new(Shown::<K> { build, rows: &rows, flat: &flat, items: &items, thumbs: K::thumbs(app, &lib) }, fns);
let selection = selected(app, &panel);
// The search text and the open groups are the browser's; the view is the panel's setting.
let state_id = egui::Id::unique(("library-panel-state", &panel));
@@ -786,3 +786,27 @@ fn built_in_library_swatches_are_listed_in_the_ui_language() {
assert!(app.session.doc().unwrap().doc.swatch("Clay 1").is_some(), "added under its own name");
crate::i18n::set_current(crate::i18n::Lang::EN);
}
/// A library panel builds its browser rows once for the library it shows, not on every frame, and builds them again
/// when the UI language changes the names it lists.
#[test]
fn library_panel_builds_its_rows_once_per_library_and_language() {
let mut app = app();
let ctx = context();
app.run("window.swatchLibrary", json!({"library": "earth-tones"})).unwrap();
let panel = shown(&app);
app.run("ui.libraryPanel", json!({"panel": panel, "view": "smallList"})).unwrap();
let draw = |app: &mut VectorcraftApp, ui: &mut Ui| show(app, ui, &panel);
let before = row_builds();
for _ in 0..4 {
draw_frame(&mut app, &ctx, &draw, vec![]);
}
assert_eq!(row_builds() - before, 1, "four frames of an unchanged library build its rows once");
crate::i18n::set_current(crate::i18n::Lang::from_code("fr").expect("fr registered"));
draw_frame(&mut app, &ctx, &draw, vec![]);
let out = draw_frame(&mut app, &ctx, &draw, vec![]);
crate::i18n::set_current(crate::i18n::Lang::EN);
assert_eq!(row_builds() - before, 2, "a new UI language builds the rows again, once");
let painted = crate::tests_labels::shapes_text(&out);
assert!(painted.lines().any(|l| l == "Argile 1"), "the rebuilt rows are in the new language: {painted}");
}
+32 -1
View File
@@ -855,7 +855,38 @@ mod tests {
let mut app = selected_text();
let Some((st, _)) = text_style(&app) else { panic!("no text style") };
let sets = set_entries(&app, &st);
// Builds without the bundled fonts have no face that offers sets.
// With the bundled fonts, the text's face offers sets. Without them, an installed face may.
assert!(!cfg!(feature = "bundled-fonts") || !sets.is_empty(), "the bundled face of the text offers stylistic sets");
// The submenu lists the `ss01` to `ss20` sets that the text's face offers, read here from
// the face itself, so the test returns early only when the face offers none.
let db = FontDb::global();
let available = db.has_family(&db.canonical(&st.font_family, &st.font_style).0);
let face_sets = if available { db.style_face(&st).map(|face| face.stylistic_sets()).unwrap_or_default() } else { Vec::new() };
let expected: Vec<String> = face_sets.iter().filter(|set| (1..=20).contains(&set.number)).map(|set| format!("ss{:02}", set.number)).collect();
let listed: Vec<String> = sets.iter().map(|(_, flag, _)| flag.tag().unwrap_or_default().to_string()).collect();
assert_eq!(listed, expected, "the submenu lists the stylistic sets of the text's face");
let rows = menu_rows(&app);
if expected.is_empty() {
assert!(!rows.iter().any(|row| matches!(row, PanelRow::Submenu(..))), "the submenu is left out when the face offers no sets");
} else {
let submenu = rows.iter().find_map(|row| match row {
PanelRow::Submenu(_, sub) if (1..=20).any(|number| has_row(sub, &toggle_ref(&format!("ss{number:02}")))) => Some(sub),
_ => None,
});
let actual: Vec<&str> = submenu
.expect("the menu has a Stylistic Sets submenu")
.iter()
.filter_map(|row| match row {
PanelRow::Command(c) if c.id == TOGGLE => Some(c.params["tag"].as_str().expect("a toggle has a tag")),
_ => None,
})
.collect();
assert_eq!(actual, expected, "the submenu toggle tags match the face's sets in order");
}
for tag in &expected {
let r = toggle_ref(tag);
assert!(rows.iter().any(|row| matches!(row, PanelRow::Submenu(_, sub) if has_row(sub, &r))), "the submenu has a row for {tag}");
}
let Some((first, flag, _)) = sets.first() else { return };
let (label, tag) = (set_label(first), flag.tag().unwrap());
set(&mut app, OtFeatures { small_caps: true, ..Default::default() });
@@ -106,6 +106,9 @@ impl LibraryKind for SwatchLibraries {
fn path(app: &VectorcraftApp, id: &str) -> Option<String> {
app.session.swatch_libraries.path(id).map(str::to_string)
}
fn same(a: &Self::Lib, b: &Self::Lib) -> bool {
Arc::ptr_eq(a, b)
}
/// Ungrouped swatches, then each colour group's folder and swatches, as in the Swatches panel; the browser's Find
/// narrows them.
fn rows<'a>(lib: &'a Self::Lib, _id: &str) -> Vec<Row<'a, Swatch>> {
@@ -135,7 +138,7 @@ impl LibraryKind for SwatchLibraries {
row
}
fn thumbs(app: &VectorcraftApp, lib: &Self::Lib) -> PatternSources {
PatternSources(lib.iter().filter_map(|w| Some((w.name.clone(), swatchlib::pattern_source(&app.session, w)?))).collect())
PatternSources(lib.iter().filter_map(|w| swatchlib::pattern_source(&app.session, w).map(|d| (w.name.clone(), d))).collect())
}
/// A pattern library's pattern, or a loaded library's, drawn from the library.
fn thumb(sources: &PatternSources, cx: &ContentPainterCx<'_>, rect: Rect, w: &Swatch) {
+12 -3
View File
@@ -535,7 +535,7 @@ const AT_START: usize = 4;
/// A click makes a symbol current and a double click edits it; a symbol drags out to the canvas,
/// onto New Symbol (duplicated) or onto Delete Symbol. Art dragged off the canvas and dropped on the
/// list becomes a symbol (Shift at the release keeps the art as ordinary art); dropped on a symbol
/// with Alt it redefines that symbol in one undo step.
/// with Alt it redefines that symbol in one undo step, and Alt+Shift also keeps the art.
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let Some((doc, revision, uid, reverts, has_sel)) =
app.session.active().map(|st| (st.doc.clone(), st.revision, st.uid, st.reverts, !st.selection.is_empty()))
@@ -651,8 +651,13 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
&& redefines(&doc, ids)
{
// Redefine Symbol with the dropped art, which becomes an instance of it, in one
// undo step. Alt art that cannot redefine changes nothing.
run_reported(app, "symbol.update", json!({ "name": target.name, "ids": node_ids(ids) }));
// undo step; Shift keeps the art as ordinary art, as the menu's Redefine Symbol
// does. Alt art that cannot redefine changes nothing.
let mut params = json!({ "name": target.name, "ids": node_ids(ids) });
if mods.shift {
params["keepArt"] = json!(true);
}
run_reported(app, "symbol.update", params);
}
}
PresetEvent::Menu { target, command, .. } => item_command(app, &target.name, &command),
@@ -976,6 +981,10 @@ impl LibraryKind for SymbolLibraries {
fn path(app: &VectorcraftApp, id: &str) -> Option<String> {
app.session.symbol_libraries.path(id).map(str::to_string)
}
/// [`get`](LibraryKind::get) wraps the library anew each time: by the library the symbols are in.
fn same(a: &Self::Lib, b: &Self::Lib) -> bool {
a.len() == b.len() && a.first().zip(b.first()).is_none_or(|(a, b)| Arc::ptr_eq(&a.lib, &b.lib))
}
fn rows<'a>(lib: &'a Self::Lib, _id: &str) -> Vec<Row<'a, LibSymbol>> {
lib.iter().map(|s| Row { name: s.name(), item: Some(s) }).collect()
}
@@ -1638,6 +1638,31 @@ fn alt_art_drop_on_a_symbol_redefines_that_symbol_in_one_step() {
}
}
/// Art released with Alt and Shift held on a symbol's tile or row, in each view, redefines that
/// symbol and stays ordinary art in its place, as Redefine Symbol with Shift leaves it, in one
/// undo step.
#[test]
fn alt_shift_art_drop_on_a_symbol_redefines_it_and_keeps_the_art() {
for view in ["thumbnail", "smallList", "largeList"] {
let (app, shape, placed) = alt_drop_doc(view);
let leaf = symbol_art(&app, "Leaf");
let undo = undo_len(&app);
let mut p = harness(app, art_and_symbols);
p.drag("Art", "Leaf", Modifiers::ALT | Modifiers::SHIFT);
let mut app = p.app();
assert_eq!(symbols(&mut app), ["Leaf", "Dot"], "{view}: no symbol added");
assert_eq!(undo_len(&app), undo + 1, "{view}: one undo step");
let doc = app.session.active().unwrap().doc.clone();
let ratio = doc.node(placed).and_then(|n| n.geometric_bounds()).map(|b| b.width() / b.height());
assert!(ratio.is_some_and(|r| (r - 2.0).abs() < 1e-6), "{view}: Leaf is the dropped art: {ratio:?}");
assert!(doc.node(shape).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. })), "{view}: the art keeps its id as a path");
assert_eq!(art(&app, "Leaf"), (1, 1), "{view}: the art stays ordinary art, not a Leaf instance");
app.run("edit.undo", json!({})).unwrap();
assert!(Arc::ptr_eq(&leaf, &symbol_art(&app, "Leaf")), "{view}: undo restores Leaf");
assert_eq!(art(&app, "Leaf"), (1, 1), "{view}: undo leaves the art");
}
}
/// An Alt drop that cannot redefine the symbol under the pointer changes nothing, makes no new
/// symbol and adds no undo step: art holding an instance of the symbol, which the redefine
/// refuses, a layer, and art released outside the list.
+3 -3
View File
@@ -217,10 +217,10 @@ fn ramp_and_shift_edit_every_selected_blend_and_keep_their_other_options() {
assert_eq!(undo_depth(&p.app()), depth + 1, "one undo step for both blends");
// The value typed goes to both; each keeps its own spacing, type and the other value.
if name == "Ramp:" {
assert!(after_a.ease.ramp > 0.0 && after_a.ease.ramp == after_b.ease.ramp, "{after_a:?} {after_b:?}");
assert!((after_a.ease.ramp - 0.75).abs() < 1e-9 && (after_b.ease.ramp - 0.75).abs() < 1e-9, "{after_a:?} {after_b:?}");
assert_eq!((after_a.color_shift, after_b.color_shift), (before_a.color_shift, before_b.color_shift));
} else {
assert!(after_a.color_shift > 0.0 && after_a.color_shift == after_b.color_shift, "{after_a:?} {after_b:?}");
assert_eq!((after_a.color_shift, after_b.color_shift), (75.0, 75.0), "{after_a:?} {after_b:?}");
assert_eq!((after_a.ease.ramp, after_b.ease.ramp), (before_a.ease.ramp, before_b.ease.ramp));
}
assert_eq!((after_a.spacing, after_b.spacing), (BlendSpacing::Steps(3), BlendSpacing::Distance(12.0)));
@@ -238,7 +238,7 @@ fn ramp_is_dimmed_while_a_selected_blend_has_no_spine() {
assert!(!p.enabled("Ramp:") && p.enabled("Shift:"));
p.type_into("Shift:", "75");
let app = p.app();
assert!(spec(&app, a).color_shift > 0.0 && spec(&app, b).color_shift == spec(&app, a).color_shift);
assert_eq!((spec(&app, a).color_shift, spec(&app, b).color_shift), (75.0, 75.0));
}
#[test]
@@ -452,7 +452,7 @@ fn an_opacity_click_in_one_frame_keeps_its_opacity_over_a_typed_alpha() {
quick_click(&mut p, rail.rect.center());
let (hex, opacity) = first_stop(&p);
assert_eq!(hex, "#336699", "the text applies");
assert!(opacity > 0.2 && opacity < 0.8, "the press sets the opacity: {opacity}");
assert!((opacity - 0.5).abs() < 0.005, "the press sets the opacity: {opacity}");
}
/// A press on the opacity slider that takes the focus from an edited field applies the text and
@@ -94,7 +94,7 @@ fn the_row_shows_under_the_box_view() {
let at = along(&slider(&p), 0.5);
p.fx.click_at(at).idle(2);
let o = fill_opacity(&p.app());
assert!((o - 0.5).abs() < 0.05, "{o}");
assert!((o - 0.5).abs() < 0.005, "{o}");
}
/// A value this build does not read keeps the rest of the preferences and reads as the default.
@@ -122,7 +122,7 @@ fn the_slider_sets_the_fill_opacity_and_takes_the_arrow_keys() {
let at = along(&slider(&p), 0.5);
p.fx.click_at(at).idle(2);
let o = fill_opacity(&p.app());
assert!((o - 0.5).abs() < 0.05, "{o}");
assert!((o - 0.5).abs() < 0.005, "{o}");
let labels = undo_labels(&p.app());
assert_eq!((labels.len(), labels.last().map(String::as_str)), (undo + 1, Some("Opacity")));
assert_eq!(crate::panels::current_paints(&p.app()).0.color().unwrap().to_hex(), "#ff0000");
+88
View File
@@ -681,6 +681,94 @@ fn placement_options_dialog_sets_the_options() {
assert_eq!(r["placement"], json!({"preserve": "fit", "align": "bottomRight", "clip": false}));
}
#[test]
fn placement_options_dialog_keeps_the_links_it_opened_on_when_the_selection_changes() {
use crate::tests::picks::{answer_dialog, open_dialogs};
let dir = Folder::new("dialog-selection");
let (app, first, _) = app(&dir);
let mut app = crate::testing::windowed(app);
let c = dir.file("second.png", &png(60, 40));
let second = app.run("file.place", json!({"path": c, "at": [200, 150]})).unwrap()["ids"][0].as_u64().unwrap();
app.run("links.placementOptions", json!({"ids": [first], "preserve": "fill"})).unwrap();
app.run("links.placementOptions", json!({"ids": [second], "preserve": "bounds"})).unwrap();
let placement = |app: &mut VectorcraftApp, id: u64| app.run("links.placementOptions", json!({"ids": [id]})).unwrap()["placement"].clone();
let second_before = placement(&mut app, second);
app.run("select.set", json!({"ids": [first]})).unwrap();
app.run("ui.placementOptionsDialog", json!({})).unwrap();
let open = open_dialogs(&app);
assert_eq!(open.len(), 1, "the dialog is open");
app.run("select.set", json!({"ids": [second]})).unwrap();
answer_dialog(&mut app, open[0].id, &[("preserve", json!("fit"))], true);
assert_eq!(placement(&mut app, second), second_before, "the image selected after the dialog opened keeps its options");
assert_eq!(placement(&mut app, first)["preserve"], json!("fit"), "OK applies to the image the dialog opened on");
}
/// Two linked images, the first with preserve `fill` and the second with `bounds`, in a window.
fn two_links(dir: &Folder) -> (VectorcraftApp, u64, u64) {
let (app, first, _) = app(dir);
let mut app = crate::testing::windowed(app);
let c = dir.file("second.png", &png(60, 40));
let second = app.run("file.place", json!({"path": c, "at": [200, 150]})).unwrap()["ids"][0].as_u64().unwrap();
app.run("links.placementOptions", json!({"ids": [first], "preserve": "fill"})).unwrap();
app.run("links.placementOptions", json!({"ids": [second], "preserve": "bounds"})).unwrap();
(app, first, second)
}
fn preserve_of(app: &mut VectorcraftApp, id: u64) -> serde_json::Value {
app.run("links.placementOptions", json!({"ids": [id]})).unwrap()["placement"]["preserve"].clone()
}
#[test]
fn placement_options_dialog_keeps_the_links_it_opened_on_when_the_selection_is_emptied() {
use crate::tests::picks::{answer_dialog, open_dialogs};
let dir = Folder::new("dialog-deselect");
let (mut app, first, second) = two_links(&dir);
app.run("select.set", json!({"ids": [first]})).unwrap();
app.run("ui.placementOptionsDialog", json!({})).unwrap();
let open = open_dialogs(&app);
app.run("select.set", json!({"ids": []})).unwrap();
answer_dialog(&mut app, open[0].id, &[("preserve", json!("fit"))], true);
assert!(open_dialogs(&app).is_empty(), "OK closes the dialog");
assert_eq!(preserve_of(&mut app, first), json!("fit"));
assert_eq!(preserve_of(&mut app, second), json!("bounds"));
}
#[test]
fn placement_options_dialog_changes_nothing_when_a_link_it_opened_on_is_deleted() {
use craft::ui::dialog::HeldOk;
use crate::tests::picks::{answer_dialog, open_dialogs};
let dir = Folder::new("dialog-deleted");
let (mut app, first, second) = two_links(&dir);
app.run("select.set", json!({"ids": [first]})).unwrap();
app.run("ui.placementOptionsDialog", json!({})).unwrap();
let open = open_dialogs(&app);
app.run("edit.clear", json!({})).unwrap();
app.run("select.set", json!({"ids": [second]})).unwrap();
let undo = app.session.active().unwrap().history.undo.len();
answer_dialog(&mut app, open[0].id, &[("preserve", json!("fit"))], true);
let refused = app.dialogs().unwrap().with(|h| matches!(h.held_state(open[0].id), Some(HeldOk::Refused(_))));
assert!(refused, "OK is refused and the dialog stays open");
assert_eq!(preserve_of(&mut app, second), json!("bounds"), "the selected image keeps its options");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "no undo step");
}
#[test]
fn placement_options_dialog_applies_to_the_ids_it_was_given() {
use crate::tests::picks::{answer_dialog, open_dialogs};
let dir = Folder::new("dialog-ids");
let (mut app, first, second) = two_links(&dir);
app.run("select.set", json!({"ids": [first]})).unwrap();
app.run("ui.placementOptionsDialog", json!({"ids": [second]})).unwrap();
let open = open_dialogs(&app);
assert_eq!(open.len(), 1, "the dialog is open");
answer_dialog(&mut app, open[0].id, &[("preserve", json!("fit"))], true);
assert_eq!(preserve_of(&mut app, second), json!("fit"));
assert_eq!(preserve_of(&mut app, first), json!("fill"), "the selected image keeps its options");
}
#[test]
fn properties_shows_the_selected_image_and_its_link_actions() {
let dir = Folder::new("props");
+76
View File
@@ -4,9 +4,15 @@
//! it, or saves the PDF when asked to (`toFile`, `path`) or when there is no print service; a
//! PostScript file (`format: "postscript"`, or a `.ps` path) is always saved. `print.printers`
//! lists the printers.
//!
//! A script run started in the app gets the printers of a service that lets scripts print
//! ([`PrintService::scripts_may_print`], the desktop's), as names only. The jobs a script prepares
//! for them are sent after the run's changes are kept and the person approves them
//! ([`crate::dialogs::script_run::PRINT_KIND`], [`send_script_prints`]).
use serde_json::{Value, json};
use vectorcraft_engine::cmd::fileio;
use vectorcraft_engine::script::printing::{PreparedPrint, Printers};
use crate::{VectorcraftApp, io};
@@ -48,6 +54,11 @@ pub trait PrintService {
fn has_setup(&self) -> bool {
false
}
/// Whether scripts may list this service's printers and send jobs to them once the person
/// approves them. The browser's print dialog picks its own printer, so the web's does not.
fn scripts_may_print(&self) -> bool {
false
}
/// Setup…: open the system's settings of `printer` (`None`: the printers).
fn setup(&mut self, _printer: Option<&str>) -> Result<(), String> {
Err("there are no printer settings to open here".into())
@@ -61,6 +72,71 @@ pub fn printers(app: &mut VectorcraftApp) -> Value {
json!({ "printers": printers, "service": app.services.print.is_some(), "setup": setup })
}
/// The printers a script run may print to: the print service's, by name, when it lets scripts
/// print; `None` otherwise.
pub fn script_printers(app: &mut VectorcraftApp) -> Option<Printers> {
let service = app.services.print.as_mut().filter(|s| s.scripts_may_print())?;
let for_printer = !service.turns_landscape();
Some(Printers::new(service.printers().into_iter().map(|p| (p.name, p.default)), for_printer))
}
/// Runs the engine command `id`. A `script.run` started here lists the printers it may print to
/// ([`script_printers`]), and only that run lists them.
pub(crate) fn execute_listing_printers(app: &mut VectorcraftApp, id: &str, params: &Value) -> Result<Value, String> {
if id == "script.run" {
app.session.script_printers = script_printers(app);
}
let r = app.session.execute(id, params).map_err(|e| e.to_string());
app.session.script_printers = None;
r
}
/// The error for a script's jobs when the print service does not let scripts print.
const NO_SCRIPT_PRINTING: &str = "Printing from scripts is not available here: the script's print jobs were not sent";
/// Sends the jobs a script prepared, which the person approved, each to its printer. Every printer
/// must still be one the service lists, by its exact name, or no job is sent. → `{sent}`, or
/// `{background: true}` while the desktop's worker sends them.
pub(crate) fn send_script_prints(app: &mut VectorcraftApp, jobs: Vec<PreparedPrint>) -> Result<Value, String> {
let service = app.services.print.as_mut().filter(|s| s.scripts_may_print()).ok_or(NO_SCRIPT_PRINTING)?;
let listed: Vec<String> = service.printers().into_iter().map(|p| p.name).collect();
if let Some(gone) = jobs.iter().find(|j| !listed.contains(&j.printer)) {
return Err(format!("The printer {} is no longer installed: the script's print jobs were not sent", gone.printer));
}
let count = jobs.len();
if let Some(submit) = service.shared_print() {
return crate::background::run(
app,
true,
"Printing from a script".into(),
None,
move |_| send_each(&mut |job| submit(job), &jobs).map(|notes| json!({ "notes": notes })),
move |app, result| {
let notes = result?;
app.status(notes["notes"].as_array().and_then(|n| n.last()).and_then(Value::as_str).unwrap_or_default());
Ok(json!({ "sent": count }))
},
);
}
let notes = send_each(&mut |job| service.print(job), &jobs)?;
app.status(notes.last().cloned().unwrap_or_default());
Ok(json!({ "sent": count }))
}
/// Gives each of `jobs` to `submit`, in order, stopping at the first that fails. → what each one
/// gave, or the error, which says how many were sent before it.
fn send_each(submit: &mut dyn FnMut(&PrintJob<'_>) -> Result<String, String>, jobs: &[PreparedPrint]) -> Result<Vec<String>, String> {
let mut notes = Vec::new();
for (sent, job) in jobs.iter().enumerate() {
match submit(&PrintJob { printer: Some(&job.printer), title: &job.title, pdf: &job.pdf, direct_pdf: false }) {
Ok(note) => notes.push(note),
Err(e) if sent == 0 => return Err(e),
Err(e) => return Err(format!("{e} ({sent} of {} print jobs were sent)", jobs.len())),
}
}
Ok(notes)
}
/// `file.print` with settings: print the active document with `settings` (over the document's, or
/// over those of the print preset `preset` names) on `printer` (default: the system's default), or
/// save the job as a PDF at `path` (else a picked file, the web downloads it) with `toFile`, a
+5 -1
View File
@@ -2,7 +2,8 @@
//! its end, while the app goes on drawing the documents as they were before the run. The status bar
//! shows it with a Stop button; a run that has added a great deal, or that opened a dialog with
//! `alert`, `confirm`, `prompt`, a ScriptUI dialog's `show()` or a `File` or `Folder` file dialog,
//! waits for the person's answer.
//! waits for the person's answer. A run that prepared jobs for a printer ends with the question
//! before they are sent.
use serde_json::{Value, json};
use vectorcraft_engine::WindowView;
@@ -14,6 +15,7 @@ use crate::dialogs::script_window;
/// Advances the running script by one slice, or asks what its growth needs asked.
pub fn poll(app: &mut VectorcraftApp) {
startup_failures(app);
script_run::ask_print(app);
if !app.session.script_running() {
return;
}
@@ -48,6 +50,8 @@ pub fn poll(app: &mut VectorcraftApp) {
if !crate::panels::actions::after_journaled_edit(app) {
app.status(format!("Ran {name}"));
}
// The jobs it prepared for a printer wait for the person's answer.
script_run::ask_print(app);
}
Err(e) => ended_with_error(app, startup, e.to_string()),
}
+3
View File
@@ -1838,6 +1838,9 @@ fn a_heavy_filter_plugin_runs_from_its_shortcut_as_from_its_menu_item() {
// the key is still running when Cancel stops it, however long the frames take.
let jobs = std::sync::Arc::new(craft::host::ManualJobs::new());
app.host = std::sync::Arc::new(craft::host::Host::builder(app.host.app().clone()).i18n(crate::i18n::shared()).jobs(jobs).build());
// The clock stands still: the run's progress window, which opens once the run is old enough
// and takes the keys, stays closed however slowly the frames run.
app.now_override = Some(0.0);
app.session.allow_plugin_grants_from_requests();
app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
let (at_once, asks) = ("test.UI.heavy_filter-at-once", "test.UI.heavy_filter-asks");
+2
View File
@@ -23,6 +23,7 @@ mod numfields;
mod overprint;
mod paintchips;
pub(crate) mod panel_harness;
mod panel_scroll;
mod pastechords;
mod pathtype;
mod pdfoutput;
@@ -44,6 +45,7 @@ mod saveext;
mod screenmode;
mod script_check;
mod script_dialogs;
mod script_print;
mod script_run;
mod script_window;
mod scripts_menu;
+14
View File
@@ -383,6 +383,20 @@ impl Panel {
seen.is_some_and(|r| r.width() >= 0.0 && r.height() >= 0.0)
}
/// The named control the latest frame lays out lowest, where its name finds that control: the control a reader
/// reaches last.
pub(crate) fn lowest(&self) -> Option<String> {
let mut names = self.names();
names.sort();
names.dedup();
names
.into_iter()
.filter_map(|name| self.fixture.by_label(&name).map(|t| (name, t.rect.bottom())))
.filter(|(_, bottom)| bottom.is_finite())
.max_by(|a, b| a.1.total_cmp(&b.1))
.map(|(name, _)| name)
}
/// Whether the control named `name` takes input.
pub(crate) fn enabled(&self, name: &str) -> bool {
!self.fixture.tree().is_disabled_key(self.look(name).node)
+61
View File
@@ -0,0 +1,61 @@
//! Every panel in a dock group shorter than its contents scrolls to its last control (#10262).
use std::cell::RefCell;
use egui::{Ui, pos2, vec2};
use serde_json::json;
use vectorcraft_engine::Session;
use crate::VectorcraftApp;
use crate::tests::panel_harness::Panel;
thread_local! {
/// The panel the harness draws.
static SHOWN: RefCell<String> = const { RefCell::new(String::new()) };
}
fn draw(app: &mut VectorcraftApp, ui: &mut Ui) {
let id = SHOWN.with(|s| s.borrow().clone());
crate::dock::panel_body(app, ui, &id);
}
/// The panels whose last control a short dock group hides and the wheel does not bring into view.
fn unreachable_panels(room_height: f32) -> Vec<String> {
let mut stuck = Vec::new();
for (id, _) in crate::state::all_panels() {
SHOWN.with(|s| *s.borrow_mut() = id.to_owned());
let mut app = VectorcraftApp::new(Session::new(), Default::default());
if let Err(e) = app.run("file.new", json!({"width": 200, "height": 200})) {
panic!("file.new: {e}");
}
// A selected path, so the panels that edit a selection show their controls.
if let Err(e) = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})) {
panic!("shape.rectangle: {e}");
}
let mut panel = Panel::new(app, draw);
let Some(last) = panel.lowest() else { continue };
panel.room(vec2(300.0, room_height));
panel.frame();
panel.frame();
if !panel.shows(&last) || panel.in_view(&last) {
continue;
}
for _ in 0..60 {
panel.scroll_at(pos2(150.0, room_height / 2.0), -120.0);
if panel.in_view(&last) {
break;
}
}
if !panel.in_view(&last) {
stuck.push(format!("{id}: {last:?}"));
}
}
stuck
}
#[test]
fn every_panel_in_a_short_dock_group_scrolls_to_its_last_control() {
let mut stuck = unreachable_panels(120.0);
stuck.extend(unreachable_panels(60.0));
assert!(stuck.is_empty(), "panels whose last control the wheel cannot reach: {stuck:?}");
}
+4 -2
View File
@@ -215,8 +215,10 @@ fn filter_dialog_previews_and_commits_one_undo_step() {
set_field(&mut h, "amount", json!(50)).unwrap();
step(&mut h);
assert!(h.state().session.in_interaction(), "previewing");
let [r, g, _] = fill_rgb(h.state(), id);
assert!(r < 1.0 && g > 0.0, "half desaturated on the canvas: {r} {g}");
let [r, g, b] = fill_rgb(h.state(), id);
for (got, want) in [(r, 0.6063), (g, 0.1063), (b, 0.1063)] {
assert!((got - want).abs() < 1e-4, "half desaturated on the canvas: {r} {g} {b}");
}
step(&mut h);
let (shown, _) = h.state().canvas.shown.as_ref().expect("a rendered canvas frame");
let shown_fill = shown.node(id).unwrap().appearance.fill_paint().color().unwrap().to_rgb_uncalibrated();
+343
View File
@@ -0,0 +1,343 @@
//! A script's jobs for a printer (`Document.print` without a file): the run lists the print
//! service's printers, and its jobs are sent after it ends, only when the person at the keyboard
//! approves them with a click on Print.
use std::cell::RefCell;
use std::rc::Rc;
use craft::ui::dialog::DialogResult;
use egui::{Pos2, Rect, vec2};
use serde_json::json;
use vectorcraft_engine::Session;
use super::script_dialogs::{cancel, confirm, fields, is_open, pump, set};
use crate::dialogs::script_run::{self, PRINT_BY_PERSON, PRINT_ENABLE_DELAY_SECS, PRINT_KIND, PRINTS_DROPPED, PrintAnswer, ScriptPrint};
use crate::print::{PrintJob, PrintService, Printer};
use crate::{Services, VectorcraftApp, menus, script_runs};
/// What the service was sent: (printer, title, bytes).
type Sent = Rc<RefCell<Vec<(Option<String>, String, Vec<u8>)>>>;
/// A print service that records the jobs it is sent, with the printers `names` (the first one the
/// default), which lets scripts print when `scripts` is true.
struct Spool {
sent: Sent,
names: Rc<RefCell<Vec<String>>>,
scripts: bool,
}
impl PrintService for Spool {
fn printers(&mut self) -> Vec<Printer> {
self.names.borrow().iter().enumerate().map(|(i, name)| Printer::new(name.clone()).is_default(i == 0)).collect()
}
fn print(&mut self, job: &PrintJob) -> Result<String, String> {
self.sent.borrow_mut().push((job.printer.map(str::to_string), job.title.to_string(), job.pdf.to_vec()));
Ok(format!("Sent to {}", job.printer.unwrap_or("the default printer")))
}
fn scripts_may_print(&self) -> bool {
self.scripts
}
}
/// An app in a window, with a document, a print service listing Office (the default) and Lab, and
/// no warning before a script runs.
fn print_app(scripts: bool) -> (VectorcraftApp, Sent, Rc<RefCell<Vec<String>>>) {
let sent = Sent::default();
let names = Rc::new(RefCell::new(vec!["Office".to_string(), "Lab".to_string()]));
let spool = Spool { sent: sent.clone(), names: names.clone(), scripts };
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Services { print: Some(Box::new(spool)), ..Default::default() }));
app.run("file.new", json!({})).unwrap();
app.session.prefs.show_external_script_warning = false;
(app, sent, names)
}
fn objects(app: &VectorcraftApp) -> usize {
app.session.doc().unwrap().doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum()
}
/// Runs `source` as File › Scripts › Other Script… runs it, to its end.
fn run(app: &mut VectorcraftApp, source: &str) {
menus::run_ui_command(app, "ui.runScript", &json!({ "source": source, "name": "p.js" })).unwrap().unwrap();
for _ in 0..10_000 {
script_runs::poll(app);
if !app.session.script_running() {
return;
}
}
panic!("the script did not end");
}
const PRINT_TO_LAB: &str =
"var o = new PrintOptions(); o.printerName = 'Lab'; app.activeDocument.print(o); vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10});";
fn asking(app: &VectorcraftApp) -> bool {
is_open::<ScriptPrint>(app)
}
/// One pass of the dialog host at `time` with `events`, then the frame's pump → the texts drawn,
/// with where.
fn frame(app: &mut VectorcraftApp, time: f64, events: Vec<egui::Event>) -> Vec<(String, Rect)> {
fn texts(s: &egui::Shape, out: &mut Vec<(String, Rect)>) {
match s {
egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect())),
egui::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)),
_ => {}
}
}
let ctx = app.ui_ctx.clone().unwrap();
let dialogs = app.dialogs().unwrap();
let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 800.0)));
let raw = egui::RawInput { screen_rect, time: Some(time), events, ..Default::default() };
let mut out = ctx.run_ui(raw, |ui| dialogs.with(|host| host.run(ui)));
out.textures_delta.clear();
pump(app);
let mut v = vec![];
out.shapes.iter().for_each(|c| texts(&c.shape, &mut v));
v
}
/// Where the button `label` was drawn: the last text that reads it (the heading reads Print too).
fn button(texts: &[(String, Rect)], label: &str) -> Pos2 {
texts.iter().rev().find(|(t, _)| t.trim() == label).unwrap_or_else(|| panic!("no `{label}` in {texts:?}")).1.center()
}
/// A click of the primary button at `pos` from `time`: hover, press and release in frames of their
/// own, as a person's click comes.
fn click(app: &mut VectorcraftApp, time: f64, pos: Pos2) {
let press = |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
for (i, event) in [egui::Event::PointerMoved(pos), press(true), press(false)].into_iter().enumerate() {
frame(app, time + 0.01 * i as f64, vec![event]);
}
}
/// A press of `key` with no modifiers at `time`, let go in a frame of its own, as a person lets go
/// of it.
fn key(app: &mut VectorcraftApp, time: f64, key: egui::Key) {
let event = |pressed| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: Default::default() };
frame(app, time, vec![event(true)]);
frame(app, time + 0.01, vec![event(false)]);
}
/// Draws the open question from `time` until it settles, then clicks its `label` button once
/// [`PRINT_ENABLE_DELAY_SECS`] have passed since it was first drawn.
fn click_after_delay(app: &mut VectorcraftApp, time: f64, label: &str) {
frame(app, time, vec![]);
frame(app, time + 0.1, vec![]);
let later = time + PRINT_ENABLE_DELAY_SECS + 0.1;
let pos = button(&frame(app, later, vec![]), label);
click(app, later + 0.1, pos);
}
/// The job is sent after the run's changes are kept, once, and only when the person at the
/// keyboard clicks Print: Print from automation is refused and the question opens again, and
/// `ui.dialog.set` and `ui.dialog.confirm` cannot print.
#[test]
fn a_scripts_print_job_is_sent_only_when_the_person_clicks_print() {
let (mut app, sent, _) = print_app(true);
run(&mut app, PRINT_TO_LAB);
assert_eq!(objects(&app), 1, "the run's changes are kept");
assert!(asking(&app));
assert!(sent.borrow().is_empty(), "nothing is sent before the person answers");
let jobs = fields(&app, PRINT_KIND)["jobs"].clone();
assert_eq!(jobs[0]["printer"], "Lab");
assert_eq!(jobs.as_array().map(Vec::len), Some(1));
for (field, value) in [("jobs", json!([])), ("printer", json!("Office"))] {
let e = set(&app, PRINT_KIND, field, value).unwrap_err();
assert!(e.contains(&format!("unknown field `{field}`")), "{field}: {e}");
}
assert_eq!(set(&app, PRINT_KIND, "answer", json!("print")).unwrap_err(), PRINT_BY_PERSON);
assert!(!confirm(&mut app, PRINT_KIND), "confirm takes only Cancel");
assert!(asking(&app), "the question stays open");
// A Print that a pass automation drove gave.
script_run::with_host(&app, |host, ctx| host.cancel::<ScriptPrint>(ctx)).unwrap();
let _ = script_run::with_host(&app, |host, _| host.take::<ScriptPrint>());
app.ui.answering_control = true;
script_run::settle_print(&mut app, DialogResult::Ok(PrintAnswer { print: true }));
app.ui.answering_control = false;
assert_eq!(app.ui.status, PRINT_BY_PERSON);
assert!(asking(&app), "the question opens again");
assert!(sent.borrow().is_empty());
click_after_delay(&mut app, 10.0, "Print");
assert!(!asking(&app));
{
let sent = sent.borrow();
assert_eq!(sent.len(), 1);
assert_eq!(sent[0].0.as_deref(), Some("Lab"));
assert!(sent[0].2.starts_with(b"%PDF"));
}
assert_eq!(app.ui.status, "Sent to Lab");
for _ in 0..5 {
script_runs::poll(&mut app);
}
assert_eq!(sent.borrow().len(), 1, "a job is sent once");
assert!(!asking(&app));
}
/// Enter does not print, and Print takes no click until [`PRINT_ENABLE_DELAY_SECS`] after the
/// question was first drawn; a click after that prints.
#[test]
fn enter_or_an_early_click_does_not_print() {
let (mut app, sent, _) = print_app(true);
run(&mut app, PRINT_TO_LAB);
assert!(asking(&app));
frame(&mut app, 10.0, vec![]);
frame(&mut app, 10.05, vec![]);
let pos = button(&frame(&mut app, 10.1, vec![]), "Print");
click(&mut app, 10.2, pos);
assert!(asking(&app), "an early click");
for time in [10.3, 10.4] {
key(&mut app, time, egui::Key::Enter);
assert!(asking(&app), "at {time}");
}
let later = 10.0 + PRINT_ENABLE_DELAY_SECS + 0.1;
for time in [later, later + 0.1] {
key(&mut app, time, egui::Key::Enter);
assert!(asking(&app), "Enter at {time}");
}
// Tab gives a button the keyboard focus: Enter on it does not print either.
key(&mut app, later + 0.15, egui::Key::Tab);
key(&mut app, later + 0.17, egui::Key::Enter);
assert!(asking(&app), "Enter on the focused button");
// Nor does an Enter pressed and let go within one frame.
let enter = |pressed| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: Default::default() };
frame(&mut app, later + 0.185, vec![enter(true), enter(false)]);
assert!(asking(&app), "Enter pressed and let go in one frame");
assert!(sent.borrow().is_empty(), "nothing is sent");
// The question has settled where it stays; Print is clicked there.
let pos = button(&frame(&mut app, later + 0.19, vec![]), "Print");
click(&mut app, later + 0.2, pos);
assert!(!asking(&app));
assert_eq!(sent.borrow().len(), 1);
}
/// While a text field has the keyboard when the run ends, the question waits, and nothing is sent;
/// it opens at the first poll after the field lets the keyboard go.
#[test]
fn the_print_question_waits_while_a_text_field_has_the_keyboard() {
let (mut app, sent, _) = print_app(true);
let ctx = app.ui_ctx.clone().unwrap();
let id = egui::Id::unique("script-print-typing");
let mut text = String::new();
let mut draw = |time: f64, focus: bool| {
let raw = egui::RawInput { time: Some(time), ..Default::default() };
let mut out = ctx.run_ui(raw, |ui| {
let r = ui.add(egui::TextEdit::singleline(&mut text).id(id));
if focus {
r.request_focus();
}
});
out.textures_delta.clear();
};
draw(1.0, true);
draw(1.1, false);
assert!(ctx.text_edit_focused());
run(&mut app, PRINT_TO_LAB);
for _ in 0..3 {
script_runs::poll(&mut app);
}
assert!(!asking(&app), "the question waits");
assert!(app.session.script_prints_waiting(), "the job waits");
ctx.memory_mut(|m| m.surrender_focus(id));
script_runs::poll(&mut app);
assert!(asking(&app));
assert!(sent.borrow().is_empty());
}
/// Cancel, from anyone, drops the jobs and keeps the run's changes.
#[test]
fn cancel_drops_a_scripts_print_jobs_and_keeps_its_changes() {
let (mut app, sent, _) = print_app(true);
run(&mut app, &format!("app.activeDocument.print(); {PRINT_TO_LAB}"));
assert_eq!(app.session.script_prints().len(), 2);
cancel(&mut app, PRINT_KIND);
assert!(!asking(&app));
assert!(!app.session.script_prints_waiting());
assert_eq!(app.ui.status, PRINTS_DROPPED);
script_runs::poll(&mut app);
assert!(!asking(&app), "the question does not come back");
assert!(sent.borrow().is_empty());
assert_eq!(objects(&app), 1);
// `answer: "cancel"` with `ui.dialog.confirm` does the same.
run(&mut app, PRINT_TO_LAB);
set(&app, PRINT_KIND, "answer", json!("cancel")).unwrap();
assert!(confirm(&mut app, PRINT_KIND));
assert!(!asking(&app));
assert!(!app.session.script_prints_waiting());
// The Cancel button, at once or later, does the same.
run(&mut app, PRINT_TO_LAB);
assert!(asking(&app));
frame(&mut app, 10.0, vec![]);
let pos = button(&frame(&mut app, 10.1, vec![]), "Cancel");
click(&mut app, 10.2, pos);
assert!(!asking(&app));
assert!(!app.session.script_prints_waiting());
assert_eq!(app.ui.status, PRINTS_DROPPED);
// The app draws on: the closed question's layer is gone by the next frame.
frame(&mut app, 10.3, vec![]);
run(&mut app, PRINT_TO_LAB);
assert!(asking(&app));
click_after_delay(&mut app, 20.0, "Cancel");
assert!(!asking(&app));
assert!(!app.session.script_prints_waiting());
assert!(sent.borrow().is_empty());
assert_eq!(objects(&app), 4);
}
/// A run that fails asks nothing and sends nothing; a printer that went away before Print is
/// refused and no job is sent.
#[test]
fn a_failed_run_or_a_printer_that_went_away_sends_nothing() {
let (mut app, sent, names) = print_app(true);
run(&mut app, &format!("{PRINT_TO_LAB} throw new Error('late');"));
assert!(!asking(&app));
assert!(!app.session.script_prints_waiting());
assert_eq!(objects(&app), 0);
run(&mut app, &format!("app.activeDocument.print(); {PRINT_TO_LAB}"));
assert!(asking(&app));
names.borrow_mut().retain(|n| n != "Lab");
click_after_delay(&mut app, 10.0, "Print");
assert_eq!(app.ui.status, "The printer Lab is no longer installed: the script's print jobs were not sent");
assert!(sent.borrow().is_empty(), "neither job is sent");
assert!(!asking(&app));
}
/// Without a service that lets scripts print (the web's), or without any, printing to a printer
/// from a script throws and nothing is asked or sent.
#[test]
fn a_script_cannot_print_to_a_printer_without_a_service_that_allows_it() {
let (mut app, sent, _) = print_app(false);
run(&mut app, PRINT_TO_LAB);
assert!(app.ui.status.contains("Printing to a printer is not available here"), "{}", app.ui.status);
assert!(!asking(&app));
assert!(sent.borrow().is_empty());
let mut bare = crate::testing::windowed(VectorcraftApp::new(Session::new(), Services::default()));
bare.run("file.new", json!({})).unwrap();
bare.session.prefs.show_external_script_warning = false;
run(&mut bare, "vc.log(app.printerList.length);");
assert!(bare.ui.status.contains("Application.printerList is not available here"), "{}", bare.ui.status);
// A run the app started lists the service's printers; a later run without one does not.
let (mut app, _, _) = print_app(true);
run(&mut app, "var l = app.printerList; vc.log([l.length, l[0].name, l[1].name]);");
assert_eq!(app.session.script_report().unwrap()["log"], json!([[2, "Office", "Lab"]]));
assert!(app.session.script_printers.is_none());
// A run that does not start leaves no list behind for a later one.
assert!(app.run("script.run", json!({"source": "1", "path": "x.js"})).is_err());
assert!(app.session.script_printers.is_none());
}
/// Space on Print, once Tab gave it the keyboard focus after [`PRINT_ENABLE_DELAY_SECS`], prints:
/// a keyboard user can approve the jobs without a mouse.
#[test]
fn space_on_the_focused_print_button_prints() {
let (mut app, sent, _) = print_app(true);
run(&mut app, PRINT_TO_LAB);
frame(&mut app, 10.0, vec![]);
let later = 10.0 + PRINT_ENABLE_DELAY_SECS + 0.1;
frame(&mut app, later, vec![]);
key(&mut app, later + 0.1, egui::Key::Tab);
key(&mut app, later + 0.2, egui::Key::Space);
assert!(!asking(&app));
assert_eq!(sent.borrow().len(), 1);
}
+2 -2
View File
@@ -214,7 +214,7 @@ mod tests {
#[test]
fn jobs_come_back_newest_last_per_slot() {
let Some(w) = ThumbWorker::<u8, u32>::start(&crate::testing::ui_context(), "test") else { return };
let w = ThumbWorker::<u8, u32>::start(&crate::testing::ui_context(), "test").expect("the worker thread starts");
let job = |n: u32| -> JobFn { Box::new(move |_| Some(Rendered { width: n, height: 1, pixels: vec![0; 4] })) };
for k in 1..=3 {
assert!(w.submit(0, k, job(k)));
@@ -238,7 +238,7 @@ mod tests {
#[test]
fn discarded_jobs_do_not_run_and_the_running_one_finishes() {
let Some(w) = ThumbWorker::<u8, u32>::start(&crate::testing::ui_context(), "test") else { return };
let w = ThumbWorker::<u8, u32>::start(&crate::testing::ui_context(), "test").expect("the worker thread starts");
let job = |n: u32| -> JobFn { Box::new(move |_| Some(Rendered { width: n, height: 1, pixels: vec![0; 4] })) };
// A job that holds the thread until it is let go, so the others queue behind it.
let (started, running) = channel::<()>();
+5 -5
View File
@@ -600,7 +600,7 @@ keeps the dialog's options as a saved preset.
PDF presets: `ui.pdfPresetsDialog {selected?}` opens Edit → PDF Presets (dialog `pdfPresets`, field `selected`: a
preset name). Built-in presets are read-only. New… and Edit… open the preset editor, which `ui.pdfPresetDialog {name?
(a saved preset to edit) | preset? (the preset a new one starts from)}` opens too: dialog `pdfPreset`, the Save PDF
(a saved preset to edit) | preset? (the preset a new one starts from)}` opens too: dialog `pdf-export`, the Save PDF
dialog's option fields plus `name` and `description`; `ui.dialog.confirm` runs `pdf.preset.save` and returns to PDF
Presets (a new preset can't take a name in use). Delete, Import… and Export… are `pdf.preset.delete`,
`pdf.preset.import` and `pdf.preset.export`; `ui.dialog.confirm` closes. Opening a `.vcpdfpresets` file with `app.open`
@@ -757,7 +757,7 @@ the dock's tab strip while Layers shows) lists the layer commands (New Layer…,
Options for Selection…, clipping mask, isolation, Locate Object, Merge Selected, Flatten Artwork, Collect in New
Layer, Release to Layers, Reverse Order, Template, Hide/Outline/Lock Others or Show/Preview/Unlock All Layers), Paste
Remembers Layers (`layer.pasteRemembersLayers`, checked when on) and Panel Options…. Layer Options is the
`layerOptions` dialog (`ui.layerOptions {ids?}`, `ui.newLayer {sublayer?}`), Panel Options the `layersPanelOptions`
`ui.layerOptions` dialog (`ui.layerOptions {ids?}`, `ui.newLayer {sublayer?}`), Panel Options the `ui.layersPanelOptions`
dialog (`ui.layersPanelOptions`), and `ui.layersExpand {ids?, open?}` opens or closes rows; see the Layers panel
section of `docs/mcp.md` for the row commands (`layer.setCurrent`, `layer.highlight`, `layer.move`…).
@@ -769,7 +769,7 @@ File Info: File → File Info… (`file.info` from the menu or Cmd+Alt+Shift+I;
stays open.
Document Raster Effects Settings: Effect → Document Raster Effects Settings… (`ui.rasterEffectsSettingsDialog` for
agents) opens the `rasterEffectsSettings` dialog. Its fields are what `document.rasterEffectsSettings` reports
agents) opens the `document.rasterEffectsSettings` dialog. Its fields are what `document.rasterEffectsSettings` reports
(`resolution`, `colorModel`, `background`, `antiAlias`, `clippingMask`, `addAround` in pt, `preserveSpotColors`);
`ui.dialog.confirm` runs it with them as one undo step; a bad value keeps the dialog open. Object → Rasterize… opens the
`object.rasterize` dialog, whose fields (`ppi`, `colorModel`, `background`, `antiAlias`, `clippingMask`,
@@ -884,7 +884,7 @@ art too large at that scale) keeps the dialog open.
Placement Options: the Links panel's flyout (or `ui.placementOptionsDialog {ids?}` for agents) opens the
`placementOptions` dialog for the selected images (fields `ids`, `preserve`: `transforms`/`bounds`/`fileDimensions`/
`fit`/`fill`, `align`: `topLeft` … `bottomRight`, `clip`). `ui.dialog.confirm` runs `links.placementOptions` with them as
one undo step.
one undo step, on the images the dialog opened on even when the selection has changed since.
Relink: the Links panel's Relink… button and flyout item (or `ui.relinkDialog {ids?}` for agents) open the `relink`
dialog for the selected images and placed documents (fields `ids`, `links`: `[{name, ids}]`, one row per linked file,
@@ -997,7 +997,7 @@ the save dialog) opens `tiffOptions`, `bmpOptions` or `tgaOptions`: the raster r
rows off; RLE turns flipped rows off). `ui.dialog.set` the fields and `ui.dialog.confirm` writes the file(s) with
`document.export`.
Save for Web: File → Export → Save for Web (Legacy)… (`file.saveForWeb`, Ctrl/Cmd+Alt+Shift+S) opens the `saveForWeb`
Save for Web: File → Export → Save for Web (Legacy)… (`file.saveForWeb`, Ctrl/Cmd+Alt+Shift+S) opens the `save-for-web`
dialog on the remembered settings (`webExport.settings`). Its fields are the `document.exportForWeb` settings
(`format`, `colors`, `reduction`, `dither`, `quality`, `colorTable`, `width`, `percent`, `output`…; set `preset` to load
a preset) plus `__view` (`original`, `optimized`, `2up`, `4up`), `__zoom` (`fit` or a percentage), `__kbps` and
+1 -1
View File
@@ -353,7 +353,7 @@ The app decides which cursors exist; whoever draws them works from the list. For
## Test lint
`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on an `assert_eq!` or `assert_ne!` of an expression with itself, such as `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`) and `thread::sleep` in test code (`sleep`). It lists the hits of the other rules without failing: a test whose only checks are that a value exists or a collection is not empty (`is_ok`, `is_some`, `!is_empty`, `len() > 0`: `only-weak`), `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, an environment variable that no CI leg sets, and test code that reads Rust source outside the audits listed in `SOURCE_AUDITS`. The base is `--base <rev>` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it. A `// test-lint: allow <rule> <reason>` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail.
`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on an `assert_eq!` or `assert_ne!` of an expression with itself, such as `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`), `thread::sleep` in test code (`sleep`), test code that reads Rust source outside the audits listed in `SOURCE_AUDITS` (`reads-source`), and a test that a `cfg` on it or on a `mod` above it excludes from every CI target that builds the crate (`never-run`). `never-run` reports a test only when it can evaluate the `cfg` on every such target; a predicate it does not evaluate, such as a `feature`, counts as unknown, so `#[cfg(all(feature = "gpu", not(feature = "gpu")))]` is not reported. It lists the hits of the other rules without failing: a test whose only checks are that a value exists or a collection is not empty (`is_ok`, `is_some`, `!is_empty`, `len() > 0`: `only-weak`), `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, an environment variable that no CI leg sets, and the hits of `census`, `mirror`, `constant-echo`, `fixture-only` and `exact-pixel`. The base is `--base <rev>` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it. A `// test-lint: allow <rule> <reason>` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail.
## Tests
+94 -12
View File
@@ -632,6 +632,11 @@ of `appearance.setItem`, `anchor` of `path.removeAnchor` and `addon.pen.removePo
value such as `"3"`, `2.5`, `-1` or `true` with `` `index` must be a whole number ``, naming the key, and reports a key
left out or null as missing (such as `` missing integer `index` ``). An optional one, such as `subpath`, keeps its default when
left out or null; `appearance.setActiveItem` reads a null `index` as clearing the active item.
`file.new` refuses a number given for `artboards`, `artboardLayout.columns` or `artboardLayout.rows` that is not a
whole number from 1 to 1000, such as `2.4`, `0` or `1001`, and opens no document. A null `artboards` keeps the
default or the preset's count; a null `columns` or `rows` is an error. A `file.new` step replayed from a journal or
played from the Actions panel keeps the earlier rules: `artboards` is rounded and kept within 1 to 1000, a `columns` of
1 or more is rounded and kept to at most 1000, and a `rows` is rounded and must then be from 1 to 1000.
A command that leaves out an object selected inside a
selected group also leaves it out when `ids` list it together with a group that holds it. Every command that takes
`ids` (or `slices`, for the slice commands) refuses a list with an entry that is not a non-negative integer, or a value
@@ -2751,9 +2756,10 @@ control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script,
assign or declare `Folder`; a variable whose name a member assignment writes counts as one that may hold a File
object; the same objects left out are not counted for the File-only functions `open`, `read`, `readch`,
`readln`, `write`, `writeln`, `copy`, `createAlias`, `openDlg` and `saveDlg`, which a Folder object does not
have; a document's `saveAs`, `exportFile` or `exportVariables` counts too, and so does `SaveOptions.SAVECHANGES`
wherever the script reads it, since `close` given it saves the document to its file), `filesOpened` (files opened
in other apps), `network`,
have; a document's `saveAs`, `exportFile` or `exportVariables` counts too, and so do `print` called on
`app.activeDocument`, `app.documents[i]`, `documents.add()`, `documents.getByName()` or `app.open()`, or on a
variable that holds one of them, and `SaveOptions.SAVECHANGES` wherever the script reads it, since `close` given
it saves the document to its file), `filesOpened` (files opened in other apps), `network`,
`nativeCode`, `otherApps` (messages to other apps), `environment` (environment variables), `unseenCode` (`eval`,
`new Function` and `$.evalFile`) and `preferences` (the reference app's preferences changed).
- `problems` lists what would stop the script loading as written (strings, comments, regular expressions,
@@ -3296,6 +3302,78 @@ through `$`:
show the prompt. A bad value throws an error before anything is written. The warnings of the save or export that
`saveAs`, `exportFile`, `app.open` and `close` run go to the console, each after the method's name
(`saveAs: …`).
- `Document.print(options?)` runs `file.print` on the document, with the options a script assigned over the
document's print settings, or over the preset's when `printPreset` is assigned. The document's print settings
stay as they are, and `print` adds no undo step
(https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/).
`options` is a `new PrintOptions()`, whose `jobOptions`, `colorManagementOptions`, `colorSeparationOptions`,
`coordinateOptions`, `flattenerOptions`, `fontOptions`, `pageMarksOptions`, `paperOptions` and `postScriptOptions`
are `new PrintJobOptions()`, `new PrintColorManagementOptions()`, `new PrintColorSeparationOptions()`,
`new PrintCoordinateOptions()`, `new PrintFlattenerOptions()`, `new PrintFontOptions()`,
`new PrintPageMarksOptions()`, `new PrintPaperOptions()` and `new PrintPostScriptOptions()`
(https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ and the pages beside it). Each property reads as
its help page's default until it is assigned, and a `PrintOptions` holds its option objects by reference, so a change
made after the assignment is printed. `print` maps `printPreset` (a print preset's name) and `flattenerPreset`;
`copies` (1 to 999), `collate`, `reversePages`, `designation`, `printAllArtboards`, `artboardRange`,
`printAsBitmap` and `file` of the job; `colorProfileMode` (`SOURCEPROFILE` and `CUSTOMPROFILE`), `intent` and
`name` (an RGB or CMYK profile) of color management; `colorSeparationMode` (`COMPOSITE` and
`HOSTBASEDSEPARATION`), `convertSpotColors` and `overPrintBlack`; `emulsion`, `fitToPage`, `horizontalScale` and
`verticalScale` (1 to 1000), `orientation`, `position` and `tiling`; `overprint` of the flattener; `colorBars`,
`pageInfoMarks`, `registrationMarks`, `trimMarks`, `pageMarksType` and `trimMarksWeight`; `name`, `width`,
`height` and `transverse` of the paper; and `negativePrinting` and `postScriptLevel` (`PSLEVEL2` and `PSLEVEL3`).
`app.printPresetsList` gives the print presets' names, `[Default]` first, and `app.PPDFileList` is empty.
The enumerations `PrintColorProfile`, `PrintColorIntent`, `PrintColorSeparationMode`, `PrintOrientation`,
`PrintPosition`, `PrintTiling`, `PrintArtworkDesignation`, `PrintingBounds`, `PrintFontDownloadMode`,
`FontSubstitutionPolicy`, `PageMarksTypes`, `PostScriptImageCompressionType` and `PrinterPostScriptLevelEnum` hold
strings such as `"PrintTiling.TILEFULLPAGES"`. VectorCraft's own rules: `print` writes the file `jobOptions.file`
names, checked as `saveAs` checks its file: PostScript when the name ends with `.ps` or `postScriptLevel` is
assigned, a print-ready PDF otherwise, also when that name is a link to a file with another extension, and
`printerName` does not apply. Without a file, `print` prints to the
printer `printerName` names, or to the system's default printer when it is `""` or not assigned
(https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/). The name must be exactly the name of a printer the
app listed for the run, or `print` throws `PrintOptions.printerName names no installed printer`; with no default
printer it throws `There is no default printer`. `print` composes the job as a print-ready PDF when it is called
and sends nothing while the run goes on. When the run ends and its changes are kept, the app asks before it sends
the jobs (dialog kind `scriptPrint`, listing each job's document, printer and pages). The dialog does not open
while a text field or text being typed on the canvas has the keyboard; it opens once neither does. The jobs are
sent only after the person at the keyboard clicks its Print button, or presses Space once Tab has moved the focus to
it: the button takes no click for the first second after the dialog appears (VectorCraft's own value), and Enter
does not print. `ui.dialog.set` refuses `answer: "print"`, `ui.dialog.confirm` is refused unless `answer` is
`"cancel"`, and a Print that synthetic input gives is refused and the dialog opens again. Cancel, Escape,
`ui.dialog.cancel` and `answer: "cancel"` drop the jobs and keep the run's changes. A run that fails or is stopped sends
nothing. Before it sends them, the app checks that each printer is still installed under that name, and sends none
when one is not. A run prepares at most 4 jobs, together at most 100 pages, every copy counted, and 32 MiB, and
none while an earlier run's jobs wait for an answer. The pages are counted from the art as it prints, artboard
backgrounds and placed files included, before the job is composed. A job for a printer is a PDF, so `postScriptLevel` with no
file throws. Where the app lists no printers for scripts (the web build, and MCP or the command line without the app),
`print` with no file throws `Printing to a printer is not available here`. `app.printerList` gives a `Printer` for
each printer the app listed for the run, at most 256, leaving out names longer than 512 bytes or with a control
character; when the system's default printer comes after the first 256, it takes the last place
(https://ai-scripting.docsforadobe.dev/jsobjref/Application/,
https://ai-scripting.docsforadobe.dev/jsobjref/Printer/). Its `name` is read-only and its `printerInfo` throws an
error that says it is not available yet. With no document open, `app.printerList` throws `Application.printerList
needs an open document`, as the Printer help page describes, and where the app lists no printers for scripts it
throws `Application.printerList is not available here`. A printer name is only compared with the listed names: it
is never read as a path, a URL or a command. `fitToPage` set to true wins over the scale factors and the tiling
mode. With `printAllArtboards` false, `artboardRange` picks the artboards, and without a range every artboard
prints. With `printAllArtboards` not assigned, an assigned `artboardRange` replaces the range of the settings
`print` starts from, which prints when those settings print a range. `print` starts from the preset's settings
when `printPreset` is assigned, otherwise from the document's saved settings. When those settings ignore the
artboards, an assigned `printArea` prints the artboards an assigned `artboardRange` names, or each artboard without
a range. With one of `horizontalScale` and `verticalScale` assigned, the other keeps its value in the settings
`print` starts from. `print` throws before anything is written when an assigned `artboardRange` names an
artboard the document does not have, also with `printAllArtboards` true, when `printPreset` or `flattenerPreset`
is not a preset's name (any case), when `colorManagementOptions.name` is not an RGB or CMYK profile's name (any
case), when `paperOptions.name` is not a paper `file.print` knows, or when it names a paper other than `custom`
and `width` or `height` is assigned above 0. An assigned name that is empty or only spaces, or holds `/`, `\` or
a control character (also at either end), throws too, and each checked name is sent without the spaces around it.
`PPDName` takes only `""`. A listed option that is not mapped, or a value that is not mapped such as
`PrintingBounds.ARTWORKBOUNDS`, `INRIPSEPARATION`, `PSLEVEL1` or a scale above 1000 with `fitToPage` not true,
throws an error that says it is not available yet. Each value is checked when it is assigned: a wrong type, a number that is not finite or is
out of range, a string longer than 4,096 bytes, an option object of the wrong class or from an earlier run, and a
path given as a string all throw. A run makes at most 256 option objects. Each warning `file.print` gives goes to
the Script Console as a line that starts with `Document.print: `. `vc.run` still cannot run `file.print` or
`print.*`.
- `Document.pathItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/) lists the document's paths in the
order of `pageItems`, paths inside groups and compound paths included, with `length`, `[i]`, `index(key)`,
`getByName(name)`, `removeAll()`, `add()` (a path with no points, from `path.create`, painted as new art; when new
@@ -3848,7 +3926,8 @@ In the app, a script past the growth limit stops at a question to continue or to
with an error at that limit. The headless reply is `{ok: true, name, changed, written, log, fuelUsed, hostCalls,
runTimeMs, timingAvailable, hostCallCounts, slowestCommands, console, dialogs, dialogCount, dialogsTruncated}`, with
`unhandledRejections` and `unhandledRejectionCount` as well when a `.js` script left rejected promises unhandled. In
the app the reply is `{running: true, name}`, and the report appears later as `scriptReport` in `ui.inspect`. The
the app the reply is `{running: true, name}`, and the report appears later as `scriptReport` in `ui.inspect`, with
`prints`, the number of jobs the run prepared for a printer, when it prepared any. The
report of a failed run has the same fields after `kind`, `message`, `messageOrigin`, `line`, `column`, `file` (when
the error is in another file than the script) and `fuelLeft`. `messageOrigin` is `script` when `message` is text the
script supplied (a value it threw, or an error it made or whose name or message it changed) and `built-in` for the
@@ -4897,7 +4976,7 @@ shows no notice.
## Navigator panel options
The Navigator panel menu's Panel Options… opens the `navigatorPanelOptions` dialog (fields `color`, `solidDashes`),
The Navigator panel menu's Panel Options… opens the `ui.navigatorPanelOptions` dialog (fields `color`, `solidDashes`),
and `ui.navigatorPanelOptions {color?, solidDashes?, viewArtboardContentsOnly?}` sets the options without it →
`{color, solidDashes, viewArtboardContentsOnly}`; with none of the keys it opens the dialog. `color` is the color the
panel's view box is drawn in: `#rrggbb` or a preset name.
@@ -5290,8 +5369,9 @@ already walks Image Trace. Short agent entry points:
of it in one undo step; with `keepArt: true` the art stays ordinary art in its place, with its ids, and stays selected
unless it is hidden or locked, and the result's `id` is null; a `keepArt` other than true or false is an error; art that holds an instance of the symbol (opacity masks included), directly or through the art
of the symbols it holds instances of, is refused and nothing changes; the Symbols panel menu's Redefine Symbol sends `keepArt: true` when it
is chosen with Shift held, and the panel sends it with the dragged art's `ids` when art dragged
off the canvas is released on a symbol's tile or row with Alt (Option on macOS) held),
is chosen with Shift held, and the panel sends `symbol.update` with the dragged art's `ids` when art dragged
off the canvas is released on a symbol's tile or row with Alt (Option on macOS) held, with `keepArt: true` when Shift
is held too),
`symbol.edit {id?, ids?, name?, x?, y?, artboard?, viewCenter?}` (symbol editing mode: the symbol's art on a temporary
isolated layer, where the instance `id` shows it or centered on (x, y), by default on the center of artboard
`artboard`, the active one the app passes, or in a document without artboards on `viewCenter`, the view's center the
@@ -6072,7 +6152,7 @@ already walks Image Trace. Short agent entry points:
next free number when its name is in use (`Default Actions 2`), and keeps the current set and the selection.
Omitted params count as `{}`. Params of another type, another key, another `mode`, or a reset while an action
records or plays (also while it waits at a stop) is an error and changes nothing. Reset records no undo step. The panel menu's Reset
Actions is disabled while an action records or plays; it opens a `resetActions` question (fields `message`,
Actions is disabled while an action records or plays; it opens an `actionsQuestion` question (fields `message`,
`detail`, `append`): OK runs this with `replace`, Append with `append`, and `ui.dialog.cancel` changes nothing.
`ui.actionSet.clear {ids?: [id]}` is Clear Actions, and returns `{cleared}`, the number of sets deleted. It deletes
every set in the panel with its actions, the built-in Default Actions set included, so no set is current or
@@ -7954,14 +8034,14 @@ and `layerRows`, the rows highlighted in the panel.
`object.setProps` return an error when they would give either name to another path directly in the group, and a
path pasted directly into the group under either name loses its name.
- **Dialogs and panel state** (control channel and the app's MCP): `ui.layerOptions {ids?}` and `ui.newLayer
{sublayer?}` open Layer Options (dialog `layerOptions`: name, color, template, locked, visible, printable, preview,
{sublayer?}` open Layer Options (dialog `ui.layerOptions`: name, color, template, locked, visible, printable, preview,
dimImages, dimPercent; for existing rows, unchanged approval adds no undo step; an edit is one undo step.
Existing rows keep their stored names unless Name is edited or explicitly set through `ui.dialog.set`, so generated labels remain automatic.
`ui.dialog.set` of `template` also sets `locked` and `dimImages`, as the
checkbox does, except a Dim Images set before it; for several `ids` the dialog shows the first row's settings, and OK sends only the fields set with a
control or `ui.dialog.set`; Cmd/Ctrl+Alt+L runs `ui.newLayer` for a new layer; in isolation mode `ui.newLayer` for a
layer that would be outside the isolated art is an error, OK in the dialog checks again and returns the same error,
and the Layers panel's New Layer and New Sublayer are off then), `ui.layersPanelOptions` opens Panel Options (`layersPanelOptions`:
and the Layers panel's New Layer and New Sublayer are off then), `ui.layersPanelOptions` opens Panel Options (`ui.layersPanelOptions`:
layersOnly, locateSelected, rowSize small|medium|large|other, otherSize, thumbLayers, thumbGroups, thumbObjects), and
`ui.layersExpand {ids?, open?}` opens or closes rows as their triangles do (Alt-click: everything inside).
With `locateSelected` on (Locate Selected Objects, off by default), when the last selected object changes on the canvas
@@ -10720,7 +10800,7 @@ and goes back to Document Setup, whose OK runs `document.setup`; its Cancel goes
`file.new` takes everything New Document sets: `preset` (a name from `file.newPresets`), `name`, `width`/`height`
(points, or lengths such as `"210 mm"`), `units`, `orientation`, `artboards` with `artboardLayout {layout, columns,
rows, spacing, rightToLeft}` (`rows`, 1 to 1000 and rounded to a whole number, gives a `gridByColumn` layout that many rows, at most one for each artboard, in place of `columns`, and is
rows, spacing, rightToLeft}` (`artboards`, `columns` and `rows` are whole numbers from 1 to 1000, and any other number is an error; `rows` gives a `gridByColumn` layout that many rows, at most one for each artboard, in place of `columns`, and is
an error with another layout; a preset keeps the rows, and `file.newPresets` lists them as set even when there are
fewer artboards, until `columns` without `rows`, or another layout, is given; New Document's Columns shows the columns
the rows give the current number of artboards, and New Document drops the rows when Columns or the layout changes),
@@ -13134,7 +13214,9 @@ bleed, composite or separations output, graphics and colour management options o
`transform` from the document onto the page (pt, y down), the document `area` it prints, its `trim` box on the page
and, with copies per sheet, each copy's artboard on the page (`copies`), plus `tiles`, the
`inks` of a separation and `warnings`. `file.print {settings?, path?}` writes the job as a print-ready PDF (one page per
sheet, tile, ink and copy); headless it answers `dataBase64`. In the app, `file.print` with no params opens the Print
sheet, tile, ink and copy); headless it answers `dataBase64`. With `maxPages`, the job is composed only when it
prints at most that many pages, copies counted; with more, `file.print` composes and writes nothing and answers
`{pages, format}`. In the app, `file.print` with no params opens the Print
dialog, and with params it prints through the system (`printer`: a name from `print.printers`, default the system's
default printer) or, with `toFile`, a `path` or no printing available, saves the PDF.
+2
View File
@@ -1120,6 +1120,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Scripts: a text frame's `nextFrame` and `previousFrame` read and set its links to the frames before and after it, `areaText` and `pathText` thread a new frame to a base frame, and `document.stories` lists the stories, each with its frames in thread order and its text across them as one text range with its characters, words and paragraphs, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Story/ and https://ai-scripting.docsforadobe.dev/jsobjref/Stories/ describe them; `text.thread.setNeighbor` links or unlinks two frames by id (`docs/mcp.md`). Which links are refused, and how a story is listed and found, are VectorCraft's own rules. `crates/engine/src/tests/script_threads.rs`.
- Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`.
- Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks, new empty groups and compound paths and paths moved into compound paths, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`); `artboards.add` returns the new artboard and `artboards.insert` returns nothing. Scoped collections support string conversion, which fails for `Layers`, `GroupItems`, `CompoundPathItems` and `Artboards` once their container is gone; compound paths expose `PathItems` objects and reject unsupported path creation. Empty clipping containers release their masks in the deletion's undo step, and `clipped` changes check locks. Layer selection changes keep unrelated selected objects, layer colors are assignable `RGBColor` values, stacking scans count toward the script budget, and paths moved into pixel-aligned compound paths are snapped. `crates/engine/src/tests/script_dom.rs`, `crates/ui-egui/src/tests/script_run.rs`.
- Scripts: `Document.print` prints the document to a file with `PrintOptions` and the job, color management, color separation, coordinate, flattener, font, page marks, paper and PostScript option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ describe, over the document's print settings, and `app.printPresetsList` lists the print presets (`docs/mcp.md`). `crates/engine/src/tests/script_print.rs`.
- Scripts: `Document.print` without a file prints to the printer `PrintOptions.printerName` names, or the default printer, and `app.printerList` lists the installed printers as `Printer` objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/ and https://ai-scripting.docsforadobe.dev/jsobjref/Printer/ describe. VectorCraft's own rules: the jobs are sent after the run's changes are kept and the person at the keyboard clicks Print or presses Space on it, which takes no click or focus for the first second, nothing is sent from a failed run, and the web build, and MCP or the command line without the app, cannot print to a printer from a script (`docs/mcp.md`). `crates/engine/src/tests/script_print.rs`, `crates/ui-egui/src/tests/script_print.rs`.
- Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents, `Document.fullName` and `saved` give a document's file and saved state, setting `saved` records that state (`document.setSaved`), `Document.path` gives its folder as a `Folder` (VectorCraft's own type), and `Document.close` closes it, saving to its file first with `SaveOptions.SAVECHANGES`, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/Document/ describe (the enumerations of the options that keep their defaults included), and read and write only where the script's `File` objects may, refusing a path whose real file name is not valid UTF-8; the warnings of each save, export and open go to the console (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`.
- Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/).
`Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. Type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`.
+3 -2
View File
@@ -35,8 +35,9 @@ commands:
cursors warn about Cursor values with no entry in crates/tools/src/cursors.toml (never fails)
test-lint [--base <rev>] [--all]
weak tests in the lines changed since the base: fail on self-compares, reasonless
#[ignore] and sleeps; list only is_ok/is_some checks, unguarded .all(), no assertion,
early returns, unset env gates... (xtask/src/test_lint.rs); --all lists every hit
#[ignore], sleeps, reads of Rust source and tests no CI target runs; list only
is_ok/is_some checks, unguarded .all(), no assertion, early returns, unset env
gates, constant echoes, exact pixels... (xtask/src/test_lint.rs); --all lists every hit
by crate and never fails
i18n-report list the strings each language's catalog lacks, shown in English (fails only on a
broken scan; ci runs it too)
+1122 -31
View File
File diff suppressed because it is too large Load Diff