Merge main into feat/scripts-text-paint

This commit is contained in:
dotCooCoo committed 2026-12-01 14:57:03 -08:00
commit 7abdcad40e
65 files changed
+4905 -197

No files matched your search

+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;
}
+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
@@ -94,12 +94,13 @@ 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};
mod colors;
mod defaults;
mod paths;
mod print;
mod save_open;
mod tags;
mod text;
@@ -205,6 +206,8 @@ pub(super) struct State {
saving: Cell<bool>,
/// `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>,
@@ -224,6 +227,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> {
@@ -2967,7 +2981,7 @@ const ENUMS: &[(&str, &[&str])] = &[
pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> {
text::install_enums(realm)?;
paths::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)?;
}
@@ -3006,6 +3020,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();
@@ -3085,8 +3100,9 @@ fn classes(link: &Link) -> Vec<HostClass> {
document.extend(defaults::document_members(l));
document.extend(text::styles::doc_members(l));
document.extend(["layers", "artboards", "groupItems", "swatches", "symbols", "activeLayer"].into_iter().map(|m| later(l, "Document", m)));
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(
@@ -3197,6 +3213,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
classes.extend(text::classes(l));
classes.extend(variables::classes(l));
classes.extend(save_open::classes(l));
classes.extend(print::classes(l));
classes.push(class(
"Layer",
None,
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,
@@ -2641,6 +2679,12 @@ impl Session {
"hostCalls": host.calls.get(),
});
host.more_written(&mut report);
// 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));
@@ -2894,6 +2938,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();
@@ -2960,6 +3006,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 -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);
+4
View File
@@ -1495,6 +1495,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"),
@@ -96,8 +97,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"),
(
@@ -241,6 +243,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 \
+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:?}"),
+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]
+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"
+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) {
+4
View File
@@ -981,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()
}
+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");
+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;
}
@@ -47,6 +49,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::<()>();
+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
+81 -5
View File
@@ -2756,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,
@@ -3214,6 +3215,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]`, `[name]` (read as
`pageItems["name"]` is read), `index(key)`,
@@ -3781,7 +3854,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
@@ -13068,7 +13142,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
@@ -1119,6 +1119,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Scripts: `document.characterStyles` and `document.paragraphStyles` add, find, rename, redefine, apply and remove character and paragraph styles, with the Normal styles listed first and kept, and a text range lists the styles its text is in, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ describe them (`docs/mcp.md`). Style names of 1 to 256 characters without control characters, and at most 4,096 styles named in one run, are VectorCraft's own rules. Load Character Styles, Load Paragraph Styles and Load All Styles refuse a file larger than 64 MB. A paragraph style's character attributes are not there yet. `crates/engine/src/tests/script_styles.rs`.
- 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: `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`. `Document.layers`, `Document.activeLayer` and the other classes this list does not name 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